rpmsg: convert to idr_alloc()
[linux/fpc-iii.git] / kernel / cgroup.c
blob888fba457bb3bda8a3cf7a7cfea5b3ce80056497
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/hashtable.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 /* IDs for cgroups in this hierarchy */
142 struct ida cgroup_ida;
144 /* The path to use for release notifications. */
145 char release_agent_path[PATH_MAX];
147 /* The name for this hierarchy - may be empty */
148 char name[MAX_CGROUP_ROOT_NAMELEN];
152 * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the
153 * subsystems that are otherwise unattached - it never has more than a
154 * single cgroup, and all tasks are part of that cgroup.
156 static struct cgroupfs_root rootnode;
159 * cgroupfs file entry, pointed to from leaf dentry->d_fsdata.
161 struct cfent {
162 struct list_head node;
163 struct dentry *dentry;
164 struct cftype *type;
168 * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when
169 * cgroup_subsys->use_id != 0.
171 #define CSS_ID_MAX (65535)
172 struct css_id {
174 * The css to which this ID points. This pointer is set to valid value
175 * after cgroup is populated. If cgroup is removed, this will be NULL.
176 * This pointer is expected to be RCU-safe because destroy()
177 * is called after synchronize_rcu(). But for safe use, css_tryget()
178 * should be used for avoiding race.
180 struct cgroup_subsys_state __rcu *css;
182 * ID of this css.
184 unsigned short id;
186 * Depth in hierarchy which this ID belongs to.
188 unsigned short depth;
190 * ID is freed by RCU. (and lookup routine is RCU safe.)
192 struct rcu_head rcu_head;
194 * Hierarchy of CSS ID belongs to.
196 unsigned short stack[0]; /* Array of Length (depth+1) */
200 * cgroup_event represents events which userspace want to receive.
202 struct cgroup_event {
204 * Cgroup which the event belongs to.
206 struct cgroup *cgrp;
208 * Control file which the event associated.
210 struct cftype *cft;
212 * eventfd to signal userspace about the event.
214 struct eventfd_ctx *eventfd;
216 * Each of these stored in a list by the cgroup.
218 struct list_head list;
220 * All fields below needed to unregister event when
221 * userspace closes eventfd.
223 poll_table pt;
224 wait_queue_head_t *wqh;
225 wait_queue_t wait;
226 struct work_struct remove;
229 /* The list of hierarchy roots */
231 static LIST_HEAD(roots);
232 static int root_count;
234 static DEFINE_IDA(hierarchy_ida);
235 static int next_hierarchy_id;
236 static DEFINE_SPINLOCK(hierarchy_id_lock);
238 /* dummytop is a shorthand for the dummy hierarchy's top cgroup */
239 #define dummytop (&rootnode.top_cgroup)
241 /* This flag indicates whether tasks in the fork and exit paths should
242 * check for fork/exit handlers to call. This avoids us having to do
243 * extra work in the fork/exit path if none of the subsystems need to
244 * be called.
246 static int need_forkexit_callback __read_mostly;
248 static int cgroup_destroy_locked(struct cgroup *cgrp);
249 static int cgroup_addrm_files(struct cgroup *cgrp, struct cgroup_subsys *subsys,
250 struct cftype cfts[], bool is_add);
252 #ifdef CONFIG_PROVE_LOCKING
253 int cgroup_lock_is_held(void)
255 return lockdep_is_held(&cgroup_mutex);
257 #else /* #ifdef CONFIG_PROVE_LOCKING */
258 int cgroup_lock_is_held(void)
260 return mutex_is_locked(&cgroup_mutex);
262 #endif /* #else #ifdef CONFIG_PROVE_LOCKING */
264 EXPORT_SYMBOL_GPL(cgroup_lock_is_held);
266 static int css_unbias_refcnt(int refcnt)
268 return refcnt >= 0 ? refcnt : refcnt - CSS_DEACT_BIAS;
271 /* the current nr of refs, always >= 0 whether @css is deactivated or not */
272 static int css_refcnt(struct cgroup_subsys_state *css)
274 int v = atomic_read(&css->refcnt);
276 return css_unbias_refcnt(v);
279 /* convenient tests for these bits */
280 inline int cgroup_is_removed(const struct cgroup *cgrp)
282 return test_bit(CGRP_REMOVED, &cgrp->flags);
285 /* bits in struct cgroupfs_root flags field */
286 enum {
287 ROOT_NOPREFIX, /* mounted subsystems have no named prefix */
288 ROOT_XATTR, /* supports extended attributes */
291 static int cgroup_is_releasable(const struct cgroup *cgrp)
293 const int bits =
294 (1 << CGRP_RELEASABLE) |
295 (1 << CGRP_NOTIFY_ON_RELEASE);
296 return (cgrp->flags & bits) == bits;
299 static int notify_on_release(const struct cgroup *cgrp)
301 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
305 * for_each_subsys() allows you to iterate on each subsystem attached to
306 * an active hierarchy
308 #define for_each_subsys(_root, _ss) \
309 list_for_each_entry(_ss, &_root->subsys_list, sibling)
311 /* for_each_active_root() allows you to iterate across the active hierarchies */
312 #define for_each_active_root(_root) \
313 list_for_each_entry(_root, &roots, root_list)
315 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
317 return dentry->d_fsdata;
320 static inline struct cfent *__d_cfe(struct dentry *dentry)
322 return dentry->d_fsdata;
325 static inline struct cftype *__d_cft(struct dentry *dentry)
327 return __d_cfe(dentry)->type;
330 /* the list of cgroups eligible for automatic release. Protected by
331 * release_list_lock */
332 static LIST_HEAD(release_list);
333 static DEFINE_RAW_SPINLOCK(release_list_lock);
334 static void cgroup_release_agent(struct work_struct *work);
335 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
336 static void check_for_release(struct cgroup *cgrp);
338 /* Link structure for associating css_set objects with cgroups */
339 struct cg_cgroup_link {
341 * List running through cg_cgroup_links associated with a
342 * cgroup, anchored on cgroup->css_sets
344 struct list_head cgrp_link_list;
345 struct cgroup *cgrp;
347 * List running through cg_cgroup_links pointing at a
348 * single css_set object, anchored on css_set->cg_links
350 struct list_head cg_link_list;
351 struct css_set *cg;
354 /* The default css_set - used by init and its children prior to any
355 * hierarchies being mounted. It contains a pointer to the root state
356 * for each subsystem. Also used to anchor the list of css_sets. Not
357 * reference-counted, to improve performance when child cgroups
358 * haven't been created.
361 static struct css_set init_css_set;
362 static struct cg_cgroup_link init_css_set_link;
364 static int cgroup_init_idr(struct cgroup_subsys *ss,
365 struct cgroup_subsys_state *css);
367 /* css_set_lock protects the list of css_set objects, and the
368 * chain of tasks off each css_set. Nests outside task->alloc_lock
369 * due to cgroup_iter_start() */
370 static DEFINE_RWLOCK(css_set_lock);
371 static int css_set_count;
374 * hash table for cgroup groups. This improves the performance to find
375 * an existing css_set. This hash doesn't (currently) take into
376 * account cgroups in empty hierarchies.
378 #define CSS_SET_HASH_BITS 7
379 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
381 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
383 int i;
384 unsigned long key = 0UL;
386 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++)
387 key += (unsigned long)css[i];
388 key = (key >> 16) ^ key;
390 return key;
393 /* We don't maintain the lists running through each css_set to its
394 * task until after the first call to cgroup_iter_start(). This
395 * reduces the fork()/exit() overhead for people who have cgroups
396 * compiled into their kernel but not actually in use */
397 static int use_task_css_set_links __read_mostly;
399 static void __put_css_set(struct css_set *cg, int taskexit)
401 struct cg_cgroup_link *link;
402 struct cg_cgroup_link *saved_link;
404 * Ensure that the refcount doesn't hit zero while any readers
405 * can see it. Similar to atomic_dec_and_lock(), but for an
406 * rwlock
408 if (atomic_add_unless(&cg->refcount, -1, 1))
409 return;
410 write_lock(&css_set_lock);
411 if (!atomic_dec_and_test(&cg->refcount)) {
412 write_unlock(&css_set_lock);
413 return;
416 /* This css_set is dead. unlink it and release cgroup refcounts */
417 hash_del(&cg->hlist);
418 css_set_count--;
420 list_for_each_entry_safe(link, saved_link, &cg->cg_links,
421 cg_link_list) {
422 struct cgroup *cgrp = link->cgrp;
423 list_del(&link->cg_link_list);
424 list_del(&link->cgrp_link_list);
427 * We may not be holding cgroup_mutex, and if cgrp->count is
428 * dropped to 0 the cgroup can be destroyed at any time, hence
429 * rcu_read_lock is used to keep it alive.
431 rcu_read_lock();
432 if (atomic_dec_and_test(&cgrp->count) &&
433 notify_on_release(cgrp)) {
434 if (taskexit)
435 set_bit(CGRP_RELEASABLE, &cgrp->flags);
436 check_for_release(cgrp);
438 rcu_read_unlock();
440 kfree(link);
443 write_unlock(&css_set_lock);
444 kfree_rcu(cg, rcu_head);
448 * refcounted get/put for css_set objects
450 static inline void get_css_set(struct css_set *cg)
452 atomic_inc(&cg->refcount);
455 static inline void put_css_set(struct css_set *cg)
457 __put_css_set(cg, 0);
460 static inline void put_css_set_taskexit(struct css_set *cg)
462 __put_css_set(cg, 1);
466 * compare_css_sets - helper function for find_existing_css_set().
467 * @cg: candidate css_set being tested
468 * @old_cg: existing css_set for a task
469 * @new_cgrp: cgroup that's being entered by the task
470 * @template: desired set of css pointers in css_set (pre-calculated)
472 * Returns true if "cg" matches "old_cg" except for the hierarchy
473 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
475 static bool compare_css_sets(struct css_set *cg,
476 struct css_set *old_cg,
477 struct cgroup *new_cgrp,
478 struct cgroup_subsys_state *template[])
480 struct list_head *l1, *l2;
482 if (memcmp(template, cg->subsys, sizeof(cg->subsys))) {
483 /* Not all subsystems matched */
484 return false;
488 * Compare cgroup pointers in order to distinguish between
489 * different cgroups in heirarchies with no subsystems. We
490 * could get by with just this check alone (and skip the
491 * memcmp above) but on most setups the memcmp check will
492 * avoid the need for this more expensive check on almost all
493 * candidates.
496 l1 = &cg->cg_links;
497 l2 = &old_cg->cg_links;
498 while (1) {
499 struct cg_cgroup_link *cgl1, *cgl2;
500 struct cgroup *cg1, *cg2;
502 l1 = l1->next;
503 l2 = l2->next;
504 /* See if we reached the end - both lists are equal length. */
505 if (l1 == &cg->cg_links) {
506 BUG_ON(l2 != &old_cg->cg_links);
507 break;
508 } else {
509 BUG_ON(l2 == &old_cg->cg_links);
511 /* Locate the cgroups associated with these links. */
512 cgl1 = list_entry(l1, struct cg_cgroup_link, cg_link_list);
513 cgl2 = list_entry(l2, struct cg_cgroup_link, cg_link_list);
514 cg1 = cgl1->cgrp;
515 cg2 = cgl2->cgrp;
516 /* Hierarchies should be linked in the same order. */
517 BUG_ON(cg1->root != cg2->root);
520 * If this hierarchy is the hierarchy of the cgroup
521 * that's changing, then we need to check that this
522 * css_set points to the new cgroup; if it's any other
523 * hierarchy, then this css_set should point to the
524 * same cgroup as the old css_set.
526 if (cg1->root == new_cgrp->root) {
527 if (cg1 != new_cgrp)
528 return false;
529 } else {
530 if (cg1 != cg2)
531 return false;
534 return true;
538 * find_existing_css_set() is a helper for
539 * find_css_set(), and checks to see whether an existing
540 * css_set is suitable.
542 * oldcg: the cgroup group that we're using before the cgroup
543 * transition
545 * cgrp: the cgroup that we're moving into
547 * template: location in which to build the desired set of subsystem
548 * state objects for the new cgroup group
550 static struct css_set *find_existing_css_set(
551 struct css_set *oldcg,
552 struct cgroup *cgrp,
553 struct cgroup_subsys_state *template[])
555 int i;
556 struct cgroupfs_root *root = cgrp->root;
557 struct hlist_node *node;
558 struct css_set *cg;
559 unsigned long key;
562 * Build the set of subsystem state objects that we want to see in the
563 * new css_set. while subsystems can change globally, the entries here
564 * won't change, so no need for locking.
566 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
567 if (root->subsys_mask & (1UL << i)) {
568 /* Subsystem is in this hierarchy. So we want
569 * the subsystem state from the new
570 * cgroup */
571 template[i] = cgrp->subsys[i];
572 } else {
573 /* Subsystem is not in this hierarchy, so we
574 * don't want to change the subsystem state */
575 template[i] = oldcg->subsys[i];
579 key = css_set_hash(template);
580 hash_for_each_possible(css_set_table, cg, node, hlist, key) {
581 if (!compare_css_sets(cg, oldcg, cgrp, template))
582 continue;
584 /* This css_set matches what we need */
585 return cg;
588 /* No existing cgroup group matched */
589 return NULL;
592 static void free_cg_links(struct list_head *tmp)
594 struct cg_cgroup_link *link;
595 struct cg_cgroup_link *saved_link;
597 list_for_each_entry_safe(link, saved_link, tmp, cgrp_link_list) {
598 list_del(&link->cgrp_link_list);
599 kfree(link);
604 * allocate_cg_links() allocates "count" cg_cgroup_link structures
605 * and chains them on tmp through their cgrp_link_list fields. Returns 0 on
606 * success or a negative error
608 static int allocate_cg_links(int count, struct list_head *tmp)
610 struct cg_cgroup_link *link;
611 int i;
612 INIT_LIST_HEAD(tmp);
613 for (i = 0; i < count; i++) {
614 link = kmalloc(sizeof(*link), GFP_KERNEL);
615 if (!link) {
616 free_cg_links(tmp);
617 return -ENOMEM;
619 list_add(&link->cgrp_link_list, tmp);
621 return 0;
625 * link_css_set - a helper function to link a css_set to a cgroup
626 * @tmp_cg_links: cg_cgroup_link objects allocated by allocate_cg_links()
627 * @cg: the css_set to be linked
628 * @cgrp: the destination cgroup
630 static void link_css_set(struct list_head *tmp_cg_links,
631 struct css_set *cg, struct cgroup *cgrp)
633 struct cg_cgroup_link *link;
635 BUG_ON(list_empty(tmp_cg_links));
636 link = list_first_entry(tmp_cg_links, struct cg_cgroup_link,
637 cgrp_link_list);
638 link->cg = cg;
639 link->cgrp = cgrp;
640 atomic_inc(&cgrp->count);
641 list_move(&link->cgrp_link_list, &cgrp->css_sets);
643 * Always add links to the tail of the list so that the list
644 * is sorted by order of hierarchy creation
646 list_add_tail(&link->cg_link_list, &cg->cg_links);
650 * find_css_set() takes an existing cgroup group and a
651 * cgroup object, and returns a css_set object that's
652 * equivalent to the old group, but with the given cgroup
653 * substituted into the appropriate hierarchy. Must be called with
654 * cgroup_mutex held
656 static struct css_set *find_css_set(
657 struct css_set *oldcg, struct cgroup *cgrp)
659 struct css_set *res;
660 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT];
662 struct list_head tmp_cg_links;
664 struct cg_cgroup_link *link;
665 unsigned long key;
667 /* First see if we already have a cgroup group that matches
668 * the desired set */
669 read_lock(&css_set_lock);
670 res = find_existing_css_set(oldcg, cgrp, template);
671 if (res)
672 get_css_set(res);
673 read_unlock(&css_set_lock);
675 if (res)
676 return res;
678 res = kmalloc(sizeof(*res), GFP_KERNEL);
679 if (!res)
680 return NULL;
682 /* Allocate all the cg_cgroup_link objects that we'll need */
683 if (allocate_cg_links(root_count, &tmp_cg_links) < 0) {
684 kfree(res);
685 return NULL;
688 atomic_set(&res->refcount, 1);
689 INIT_LIST_HEAD(&res->cg_links);
690 INIT_LIST_HEAD(&res->tasks);
691 INIT_HLIST_NODE(&res->hlist);
693 /* Copy the set of subsystem state objects generated in
694 * find_existing_css_set() */
695 memcpy(res->subsys, template, sizeof(res->subsys));
697 write_lock(&css_set_lock);
698 /* Add reference counts and links from the new css_set. */
699 list_for_each_entry(link, &oldcg->cg_links, cg_link_list) {
700 struct cgroup *c = link->cgrp;
701 if (c->root == cgrp->root)
702 c = cgrp;
703 link_css_set(&tmp_cg_links, res, c);
706 BUG_ON(!list_empty(&tmp_cg_links));
708 css_set_count++;
710 /* Add this cgroup group to the hash table */
711 key = css_set_hash(res->subsys);
712 hash_add(css_set_table, &res->hlist, key);
714 write_unlock(&css_set_lock);
716 return res;
720 * Return the cgroup for "task" from the given hierarchy. Must be
721 * called with cgroup_mutex held.
723 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
724 struct cgroupfs_root *root)
726 struct css_set *css;
727 struct cgroup *res = NULL;
729 BUG_ON(!mutex_is_locked(&cgroup_mutex));
730 read_lock(&css_set_lock);
732 * No need to lock the task - since we hold cgroup_mutex the
733 * task can't change groups, so the only thing that can happen
734 * is that it exits and its css is set back to init_css_set.
736 css = task->cgroups;
737 if (css == &init_css_set) {
738 res = &root->top_cgroup;
739 } else {
740 struct cg_cgroup_link *link;
741 list_for_each_entry(link, &css->cg_links, cg_link_list) {
742 struct cgroup *c = link->cgrp;
743 if (c->root == root) {
744 res = c;
745 break;
749 read_unlock(&css_set_lock);
750 BUG_ON(!res);
751 return res;
755 * There is one global cgroup mutex. We also require taking
756 * task_lock() when dereferencing a task's cgroup subsys pointers.
757 * See "The task_lock() exception", at the end of this comment.
759 * A task must hold cgroup_mutex to modify cgroups.
761 * Any task can increment and decrement the count field without lock.
762 * So in general, code holding cgroup_mutex can't rely on the count
763 * field not changing. However, if the count goes to zero, then only
764 * cgroup_attach_task() can increment it again. Because a count of zero
765 * means that no tasks are currently attached, therefore there is no
766 * way a task attached to that cgroup can fork (the other way to
767 * increment the count). So code holding cgroup_mutex can safely
768 * assume that if the count is zero, it will stay zero. Similarly, if
769 * a task holds cgroup_mutex on a cgroup with zero count, it
770 * knows that the cgroup won't be removed, as cgroup_rmdir()
771 * needs that mutex.
773 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
774 * (usually) take cgroup_mutex. These are the two most performance
775 * critical pieces of code here. The exception occurs on cgroup_exit(),
776 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
777 * is taken, and if the cgroup count is zero, a usermode call made
778 * to the release agent with the name of the cgroup (path relative to
779 * the root of cgroup file system) as the argument.
781 * A cgroup can only be deleted if both its 'count' of using tasks
782 * is zero, and its list of 'children' cgroups is empty. Since all
783 * tasks in the system use _some_ cgroup, and since there is always at
784 * least one task in the system (init, pid == 1), therefore, top_cgroup
785 * always has either children cgroups and/or using tasks. So we don't
786 * need a special hack to ensure that top_cgroup cannot be deleted.
788 * The task_lock() exception
790 * The need for this exception arises from the action of
791 * cgroup_attach_task(), which overwrites one task's cgroup pointer with
792 * another. It does so using cgroup_mutex, however there are
793 * several performance critical places that need to reference
794 * task->cgroup without the expense of grabbing a system global
795 * mutex. Therefore except as noted below, when dereferencing or, as
796 * in cgroup_attach_task(), modifying a task's cgroup pointer we use
797 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
798 * the task_struct routinely used for such matters.
800 * P.S. One more locking exception. RCU is used to guard the
801 * update of a tasks cgroup pointer by cgroup_attach_task()
805 * cgroup_lock - lock out any changes to cgroup structures
808 void cgroup_lock(void)
810 mutex_lock(&cgroup_mutex);
812 EXPORT_SYMBOL_GPL(cgroup_lock);
815 * cgroup_unlock - release lock on cgroup changes
817 * Undo the lock taken in a previous cgroup_lock() call.
819 void cgroup_unlock(void)
821 mutex_unlock(&cgroup_mutex);
823 EXPORT_SYMBOL_GPL(cgroup_unlock);
826 * A couple of forward declarations required, due to cyclic reference loop:
827 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
828 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
829 * -> cgroup_mkdir.
832 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode);
833 static struct dentry *cgroup_lookup(struct inode *, struct dentry *, unsigned int);
834 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
835 static int cgroup_populate_dir(struct cgroup *cgrp, bool base_files,
836 unsigned long subsys_mask);
837 static const struct inode_operations cgroup_dir_inode_operations;
838 static const struct file_operations proc_cgroupstats_operations;
840 static struct backing_dev_info cgroup_backing_dev_info = {
841 .name = "cgroup",
842 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
845 static int alloc_css_id(struct cgroup_subsys *ss,
846 struct cgroup *parent, struct cgroup *child);
848 static struct inode *cgroup_new_inode(umode_t mode, struct super_block *sb)
850 struct inode *inode = new_inode(sb);
852 if (inode) {
853 inode->i_ino = get_next_ino();
854 inode->i_mode = mode;
855 inode->i_uid = current_fsuid();
856 inode->i_gid = current_fsgid();
857 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
858 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
860 return inode;
863 static void cgroup_free_fn(struct work_struct *work)
865 struct cgroup *cgrp = container_of(work, struct cgroup, free_work);
866 struct cgroup_subsys *ss;
868 mutex_lock(&cgroup_mutex);
870 * Release the subsystem state objects.
872 for_each_subsys(cgrp->root, ss)
873 ss->css_free(cgrp);
875 cgrp->root->number_of_cgroups--;
876 mutex_unlock(&cgroup_mutex);
879 * Drop the active superblock reference that we took when we
880 * created the cgroup
882 deactivate_super(cgrp->root->sb);
885 * if we're getting rid of the cgroup, refcount should ensure
886 * that there are no pidlists left.
888 BUG_ON(!list_empty(&cgrp->pidlists));
890 simple_xattrs_free(&cgrp->xattrs);
892 ida_simple_remove(&cgrp->root->cgroup_ida, cgrp->id);
893 kfree(cgrp);
896 static void cgroup_free_rcu(struct rcu_head *head)
898 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
900 schedule_work(&cgrp->free_work);
903 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
905 /* is dentry a directory ? if so, kfree() associated cgroup */
906 if (S_ISDIR(inode->i_mode)) {
907 struct cgroup *cgrp = dentry->d_fsdata;
909 BUG_ON(!(cgroup_is_removed(cgrp)));
910 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
911 } else {
912 struct cfent *cfe = __d_cfe(dentry);
913 struct cgroup *cgrp = dentry->d_parent->d_fsdata;
914 struct cftype *cft = cfe->type;
916 WARN_ONCE(!list_empty(&cfe->node) &&
917 cgrp != &cgrp->root->top_cgroup,
918 "cfe still linked for %s\n", cfe->type->name);
919 kfree(cfe);
920 simple_xattrs_free(&cft->xattrs);
922 iput(inode);
925 static int cgroup_delete(const struct dentry *d)
927 return 1;
930 static void remove_dir(struct dentry *d)
932 struct dentry *parent = dget(d->d_parent);
934 d_delete(d);
935 simple_rmdir(parent->d_inode, d);
936 dput(parent);
939 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
941 struct cfent *cfe;
943 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
944 lockdep_assert_held(&cgroup_mutex);
947 * If we're doing cleanup due to failure of cgroup_create(),
948 * the corresponding @cfe may not exist.
950 list_for_each_entry(cfe, &cgrp->files, node) {
951 struct dentry *d = cfe->dentry;
953 if (cft && cfe->type != cft)
954 continue;
956 dget(d);
957 d_delete(d);
958 simple_unlink(cgrp->dentry->d_inode, d);
959 list_del_init(&cfe->node);
960 dput(d);
962 break;
967 * cgroup_clear_directory - selective removal of base and subsystem files
968 * @dir: directory containing the files
969 * @base_files: true if the base files should be removed
970 * @subsys_mask: mask of the subsystem ids whose files should be removed
972 static void cgroup_clear_directory(struct dentry *dir, bool base_files,
973 unsigned long subsys_mask)
975 struct cgroup *cgrp = __d_cgrp(dir);
976 struct cgroup_subsys *ss;
978 for_each_subsys(cgrp->root, ss) {
979 struct cftype_set *set;
980 if (!test_bit(ss->subsys_id, &subsys_mask))
981 continue;
982 list_for_each_entry(set, &ss->cftsets, node)
983 cgroup_addrm_files(cgrp, NULL, set->cfts, false);
985 if (base_files) {
986 while (!list_empty(&cgrp->files))
987 cgroup_rm_file(cgrp, NULL);
992 * NOTE : the dentry must have been dget()'ed
994 static void cgroup_d_remove_dir(struct dentry *dentry)
996 struct dentry *parent;
997 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
999 cgroup_clear_directory(dentry, true, root->subsys_mask);
1001 parent = dentry->d_parent;
1002 spin_lock(&parent->d_lock);
1003 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
1004 list_del_init(&dentry->d_u.d_child);
1005 spin_unlock(&dentry->d_lock);
1006 spin_unlock(&parent->d_lock);
1007 remove_dir(dentry);
1011 * Call with cgroup_mutex held. Drops reference counts on modules, including
1012 * any duplicate ones that parse_cgroupfs_options took. If this function
1013 * returns an error, no reference counts are touched.
1015 static int rebind_subsystems(struct cgroupfs_root *root,
1016 unsigned long final_subsys_mask)
1018 unsigned long added_mask, removed_mask;
1019 struct cgroup *cgrp = &root->top_cgroup;
1020 int i;
1022 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1023 BUG_ON(!mutex_is_locked(&cgroup_root_mutex));
1025 removed_mask = root->actual_subsys_mask & ~final_subsys_mask;
1026 added_mask = final_subsys_mask & ~root->actual_subsys_mask;
1027 /* Check that any added subsystems are currently free */
1028 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1029 unsigned long bit = 1UL << i;
1030 struct cgroup_subsys *ss = subsys[i];
1031 if (!(bit & added_mask))
1032 continue;
1034 * Nobody should tell us to do a subsys that doesn't exist:
1035 * parse_cgroupfs_options should catch that case and refcounts
1036 * ensure that subsystems won't disappear once selected.
1038 BUG_ON(ss == NULL);
1039 if (ss->root != &rootnode) {
1040 /* Subsystem isn't free */
1041 return -EBUSY;
1045 /* Currently we don't handle adding/removing subsystems when
1046 * any child cgroups exist. This is theoretically supportable
1047 * but involves complex error handling, so it's being left until
1048 * later */
1049 if (root->number_of_cgroups > 1)
1050 return -EBUSY;
1052 /* Process each subsystem */
1053 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1054 struct cgroup_subsys *ss = subsys[i];
1055 unsigned long bit = 1UL << i;
1056 if (bit & added_mask) {
1057 /* We're binding this subsystem to this hierarchy */
1058 BUG_ON(ss == NULL);
1059 BUG_ON(cgrp->subsys[i]);
1060 BUG_ON(!dummytop->subsys[i]);
1061 BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
1062 cgrp->subsys[i] = dummytop->subsys[i];
1063 cgrp->subsys[i]->cgroup = cgrp;
1064 list_move(&ss->sibling, &root->subsys_list);
1065 ss->root = root;
1066 if (ss->bind)
1067 ss->bind(cgrp);
1068 /* refcount was already taken, and we're keeping it */
1069 } else if (bit & removed_mask) {
1070 /* We're removing this subsystem */
1071 BUG_ON(ss == NULL);
1072 BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
1073 BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
1074 if (ss->bind)
1075 ss->bind(dummytop);
1076 dummytop->subsys[i]->cgroup = dummytop;
1077 cgrp->subsys[i] = NULL;
1078 subsys[i]->root = &rootnode;
1079 list_move(&ss->sibling, &rootnode.subsys_list);
1080 /* subsystem is now free - drop reference on module */
1081 module_put(ss->module);
1082 } else if (bit & final_subsys_mask) {
1083 /* Subsystem state should already exist */
1084 BUG_ON(ss == NULL);
1085 BUG_ON(!cgrp->subsys[i]);
1087 * a refcount was taken, but we already had one, so
1088 * drop the extra reference.
1090 module_put(ss->module);
1091 #ifdef CONFIG_MODULE_UNLOAD
1092 BUG_ON(ss->module && !module_refcount(ss->module));
1093 #endif
1094 } else {
1095 /* Subsystem state shouldn't exist */
1096 BUG_ON(cgrp->subsys[i]);
1099 root->subsys_mask = root->actual_subsys_mask = final_subsys_mask;
1101 return 0;
1104 static int cgroup_show_options(struct seq_file *seq, struct dentry *dentry)
1106 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
1107 struct cgroup_subsys *ss;
1109 mutex_lock(&cgroup_root_mutex);
1110 for_each_subsys(root, ss)
1111 seq_printf(seq, ",%s", ss->name);
1112 if (test_bit(ROOT_NOPREFIX, &root->flags))
1113 seq_puts(seq, ",noprefix");
1114 if (test_bit(ROOT_XATTR, &root->flags))
1115 seq_puts(seq, ",xattr");
1116 if (strlen(root->release_agent_path))
1117 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1118 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1119 seq_puts(seq, ",clone_children");
1120 if (strlen(root->name))
1121 seq_printf(seq, ",name=%s", root->name);
1122 mutex_unlock(&cgroup_root_mutex);
1123 return 0;
1126 struct cgroup_sb_opts {
1127 unsigned long subsys_mask;
1128 unsigned long flags;
1129 char *release_agent;
1130 bool cpuset_clone_children;
1131 char *name;
1132 /* User explicitly requested empty subsystem */
1133 bool none;
1135 struct cgroupfs_root *new_root;
1140 * Convert a hierarchy specifier into a bitmask of subsystems and flags. Call
1141 * with cgroup_mutex held to protect the subsys[] array. This function takes
1142 * refcounts on subsystems to be used, unless it returns error, in which case
1143 * no refcounts are taken.
1145 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1147 char *token, *o = data;
1148 bool all_ss = false, one_ss = false;
1149 unsigned long mask = (unsigned long)-1;
1150 int i;
1151 bool module_pin_failed = false;
1153 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1155 #ifdef CONFIG_CPUSETS
1156 mask = ~(1UL << cpuset_subsys_id);
1157 #endif
1159 memset(opts, 0, sizeof(*opts));
1161 while ((token = strsep(&o, ",")) != NULL) {
1162 if (!*token)
1163 return -EINVAL;
1164 if (!strcmp(token, "none")) {
1165 /* Explicitly have no subsystems */
1166 opts->none = true;
1167 continue;
1169 if (!strcmp(token, "all")) {
1170 /* Mutually exclusive option 'all' + subsystem name */
1171 if (one_ss)
1172 return -EINVAL;
1173 all_ss = true;
1174 continue;
1176 if (!strcmp(token, "noprefix")) {
1177 set_bit(ROOT_NOPREFIX, &opts->flags);
1178 continue;
1180 if (!strcmp(token, "clone_children")) {
1181 opts->cpuset_clone_children = true;
1182 continue;
1184 if (!strcmp(token, "xattr")) {
1185 set_bit(ROOT_XATTR, &opts->flags);
1186 continue;
1188 if (!strncmp(token, "release_agent=", 14)) {
1189 /* Specifying two release agents is forbidden */
1190 if (opts->release_agent)
1191 return -EINVAL;
1192 opts->release_agent =
1193 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1194 if (!opts->release_agent)
1195 return -ENOMEM;
1196 continue;
1198 if (!strncmp(token, "name=", 5)) {
1199 const char *name = token + 5;
1200 /* Can't specify an empty name */
1201 if (!strlen(name))
1202 return -EINVAL;
1203 /* Must match [\w.-]+ */
1204 for (i = 0; i < strlen(name); i++) {
1205 char c = name[i];
1206 if (isalnum(c))
1207 continue;
1208 if ((c == '.') || (c == '-') || (c == '_'))
1209 continue;
1210 return -EINVAL;
1212 /* Specifying two names is forbidden */
1213 if (opts->name)
1214 return -EINVAL;
1215 opts->name = kstrndup(name,
1216 MAX_CGROUP_ROOT_NAMELEN - 1,
1217 GFP_KERNEL);
1218 if (!opts->name)
1219 return -ENOMEM;
1221 continue;
1224 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1225 struct cgroup_subsys *ss = subsys[i];
1226 if (ss == NULL)
1227 continue;
1228 if (strcmp(token, ss->name))
1229 continue;
1230 if (ss->disabled)
1231 continue;
1233 /* Mutually exclusive option 'all' + subsystem name */
1234 if (all_ss)
1235 return -EINVAL;
1236 set_bit(i, &opts->subsys_mask);
1237 one_ss = true;
1239 break;
1241 if (i == CGROUP_SUBSYS_COUNT)
1242 return -ENOENT;
1246 * If the 'all' option was specified select all the subsystems,
1247 * otherwise if 'none', 'name=' and a subsystem name options
1248 * were not specified, let's default to 'all'
1250 if (all_ss || (!one_ss && !opts->none && !opts->name)) {
1251 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1252 struct cgroup_subsys *ss = subsys[i];
1253 if (ss == NULL)
1254 continue;
1255 if (ss->disabled)
1256 continue;
1257 set_bit(i, &opts->subsys_mask);
1261 /* Consistency checks */
1264 * Option noprefix was introduced just for backward compatibility
1265 * with the old cpuset, so we allow noprefix only if mounting just
1266 * the cpuset subsystem.
1268 if (test_bit(ROOT_NOPREFIX, &opts->flags) &&
1269 (opts->subsys_mask & mask))
1270 return -EINVAL;
1273 /* Can't specify "none" and some subsystems */
1274 if (opts->subsys_mask && opts->none)
1275 return -EINVAL;
1278 * We either have to specify by name or by subsystems. (So all
1279 * empty hierarchies must have a name).
1281 if (!opts->subsys_mask && !opts->name)
1282 return -EINVAL;
1285 * Grab references on all the modules we'll need, so the subsystems
1286 * don't dance around before rebind_subsystems attaches them. This may
1287 * take duplicate reference counts on a subsystem that's already used,
1288 * but rebind_subsystems handles this case.
1290 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1291 unsigned long bit = 1UL << i;
1293 if (!(bit & opts->subsys_mask))
1294 continue;
1295 if (!try_module_get(subsys[i]->module)) {
1296 module_pin_failed = true;
1297 break;
1300 if (module_pin_failed) {
1302 * oops, one of the modules was going away. this means that we
1303 * raced with a module_delete call, and to the user this is
1304 * essentially a "subsystem doesn't exist" case.
1306 for (i--; i >= 0; i--) {
1307 /* drop refcounts only on the ones we took */
1308 unsigned long bit = 1UL << i;
1310 if (!(bit & opts->subsys_mask))
1311 continue;
1312 module_put(subsys[i]->module);
1314 return -ENOENT;
1317 return 0;
1320 static void drop_parsed_module_refcounts(unsigned long subsys_mask)
1322 int i;
1323 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1324 unsigned long bit = 1UL << i;
1326 if (!(bit & subsys_mask))
1327 continue;
1328 module_put(subsys[i]->module);
1332 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1334 int ret = 0;
1335 struct cgroupfs_root *root = sb->s_fs_info;
1336 struct cgroup *cgrp = &root->top_cgroup;
1337 struct cgroup_sb_opts opts;
1338 unsigned long added_mask, removed_mask;
1340 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1341 mutex_lock(&cgroup_mutex);
1342 mutex_lock(&cgroup_root_mutex);
1344 /* See what subsystems are wanted */
1345 ret = parse_cgroupfs_options(data, &opts);
1346 if (ret)
1347 goto out_unlock;
1349 if (opts.subsys_mask != root->actual_subsys_mask || opts.release_agent)
1350 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1351 task_tgid_nr(current), current->comm);
1353 added_mask = opts.subsys_mask & ~root->subsys_mask;
1354 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1356 /* Don't allow flags or name to change at remount */
1357 if (opts.flags != root->flags ||
1358 (opts.name && strcmp(opts.name, root->name))) {
1359 ret = -EINVAL;
1360 drop_parsed_module_refcounts(opts.subsys_mask);
1361 goto out_unlock;
1365 * Clear out the files of subsystems that should be removed, do
1366 * this before rebind_subsystems, since rebind_subsystems may
1367 * change this hierarchy's subsys_list.
1369 cgroup_clear_directory(cgrp->dentry, false, removed_mask);
1371 ret = rebind_subsystems(root, opts.subsys_mask);
1372 if (ret) {
1373 /* rebind_subsystems failed, re-populate the removed files */
1374 cgroup_populate_dir(cgrp, false, removed_mask);
1375 drop_parsed_module_refcounts(opts.subsys_mask);
1376 goto out_unlock;
1379 /* re-populate subsystem files */
1380 cgroup_populate_dir(cgrp, false, added_mask);
1382 if (opts.release_agent)
1383 strcpy(root->release_agent_path, opts.release_agent);
1384 out_unlock:
1385 kfree(opts.release_agent);
1386 kfree(opts.name);
1387 mutex_unlock(&cgroup_root_mutex);
1388 mutex_unlock(&cgroup_mutex);
1389 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1390 return ret;
1393 static const struct super_operations cgroup_ops = {
1394 .statfs = simple_statfs,
1395 .drop_inode = generic_delete_inode,
1396 .show_options = cgroup_show_options,
1397 .remount_fs = cgroup_remount,
1400 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1402 INIT_LIST_HEAD(&cgrp->sibling);
1403 INIT_LIST_HEAD(&cgrp->children);
1404 INIT_LIST_HEAD(&cgrp->files);
1405 INIT_LIST_HEAD(&cgrp->css_sets);
1406 INIT_LIST_HEAD(&cgrp->allcg_node);
1407 INIT_LIST_HEAD(&cgrp->release_list);
1408 INIT_LIST_HEAD(&cgrp->pidlists);
1409 INIT_WORK(&cgrp->free_work, cgroup_free_fn);
1410 mutex_init(&cgrp->pidlist_mutex);
1411 INIT_LIST_HEAD(&cgrp->event_list);
1412 spin_lock_init(&cgrp->event_list_lock);
1413 simple_xattrs_init(&cgrp->xattrs);
1416 static void init_cgroup_root(struct cgroupfs_root *root)
1418 struct cgroup *cgrp = &root->top_cgroup;
1420 INIT_LIST_HEAD(&root->subsys_list);
1421 INIT_LIST_HEAD(&root->root_list);
1422 INIT_LIST_HEAD(&root->allcg_list);
1423 root->number_of_cgroups = 1;
1424 cgrp->root = root;
1425 cgrp->top_cgroup = cgrp;
1426 init_cgroup_housekeeping(cgrp);
1427 list_add_tail(&cgrp->allcg_node, &root->allcg_list);
1430 static bool init_root_id(struct cgroupfs_root *root)
1432 int ret = 0;
1434 do {
1435 if (!ida_pre_get(&hierarchy_ida, GFP_KERNEL))
1436 return false;
1437 spin_lock(&hierarchy_id_lock);
1438 /* Try to allocate the next unused ID */
1439 ret = ida_get_new_above(&hierarchy_ida, next_hierarchy_id,
1440 &root->hierarchy_id);
1441 if (ret == -ENOSPC)
1442 /* Try again starting from 0 */
1443 ret = ida_get_new(&hierarchy_ida, &root->hierarchy_id);
1444 if (!ret) {
1445 next_hierarchy_id = root->hierarchy_id + 1;
1446 } else if (ret != -EAGAIN) {
1447 /* Can only get here if the 31-bit IDR is full ... */
1448 BUG_ON(ret);
1450 spin_unlock(&hierarchy_id_lock);
1451 } while (ret);
1452 return true;
1455 static int cgroup_test_super(struct super_block *sb, void *data)
1457 struct cgroup_sb_opts *opts = data;
1458 struct cgroupfs_root *root = sb->s_fs_info;
1460 /* If we asked for a name then it must match */
1461 if (opts->name && strcmp(opts->name, root->name))
1462 return 0;
1465 * If we asked for subsystems (or explicitly for no
1466 * subsystems) then they must match
1468 if ((opts->subsys_mask || opts->none)
1469 && (opts->subsys_mask != root->subsys_mask))
1470 return 0;
1472 return 1;
1475 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1477 struct cgroupfs_root *root;
1479 if (!opts->subsys_mask && !opts->none)
1480 return NULL;
1482 root = kzalloc(sizeof(*root), GFP_KERNEL);
1483 if (!root)
1484 return ERR_PTR(-ENOMEM);
1486 if (!init_root_id(root)) {
1487 kfree(root);
1488 return ERR_PTR(-ENOMEM);
1490 init_cgroup_root(root);
1492 root->subsys_mask = opts->subsys_mask;
1493 root->flags = opts->flags;
1494 ida_init(&root->cgroup_ida);
1495 if (opts->release_agent)
1496 strcpy(root->release_agent_path, opts->release_agent);
1497 if (opts->name)
1498 strcpy(root->name, opts->name);
1499 if (opts->cpuset_clone_children)
1500 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1501 return root;
1504 static void cgroup_drop_root(struct cgroupfs_root *root)
1506 if (!root)
1507 return;
1509 BUG_ON(!root->hierarchy_id);
1510 spin_lock(&hierarchy_id_lock);
1511 ida_remove(&hierarchy_ida, root->hierarchy_id);
1512 spin_unlock(&hierarchy_id_lock);
1513 ida_destroy(&root->cgroup_ida);
1514 kfree(root);
1517 static int cgroup_set_super(struct super_block *sb, void *data)
1519 int ret;
1520 struct cgroup_sb_opts *opts = data;
1522 /* If we don't have a new root, we can't set up a new sb */
1523 if (!opts->new_root)
1524 return -EINVAL;
1526 BUG_ON(!opts->subsys_mask && !opts->none);
1528 ret = set_anon_super(sb, NULL);
1529 if (ret)
1530 return ret;
1532 sb->s_fs_info = opts->new_root;
1533 opts->new_root->sb = sb;
1535 sb->s_blocksize = PAGE_CACHE_SIZE;
1536 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1537 sb->s_magic = CGROUP_SUPER_MAGIC;
1538 sb->s_op = &cgroup_ops;
1540 return 0;
1543 static int cgroup_get_rootdir(struct super_block *sb)
1545 static const struct dentry_operations cgroup_dops = {
1546 .d_iput = cgroup_diput,
1547 .d_delete = cgroup_delete,
1550 struct inode *inode =
1551 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1553 if (!inode)
1554 return -ENOMEM;
1556 inode->i_fop = &simple_dir_operations;
1557 inode->i_op = &cgroup_dir_inode_operations;
1558 /* directories start off with i_nlink == 2 (for "." entry) */
1559 inc_nlink(inode);
1560 sb->s_root = d_make_root(inode);
1561 if (!sb->s_root)
1562 return -ENOMEM;
1563 /* for everything else we want ->d_op set */
1564 sb->s_d_op = &cgroup_dops;
1565 return 0;
1568 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1569 int flags, const char *unused_dev_name,
1570 void *data)
1572 struct cgroup_sb_opts opts;
1573 struct cgroupfs_root *root;
1574 int ret = 0;
1575 struct super_block *sb;
1576 struct cgroupfs_root *new_root;
1577 struct inode *inode;
1579 /* First find the desired set of subsystems */
1580 mutex_lock(&cgroup_mutex);
1581 ret = parse_cgroupfs_options(data, &opts);
1582 mutex_unlock(&cgroup_mutex);
1583 if (ret)
1584 goto out_err;
1587 * Allocate a new cgroup root. We may not need it if we're
1588 * reusing an existing hierarchy.
1590 new_root = cgroup_root_from_opts(&opts);
1591 if (IS_ERR(new_root)) {
1592 ret = PTR_ERR(new_root);
1593 goto drop_modules;
1595 opts.new_root = new_root;
1597 /* Locate an existing or new sb for this hierarchy */
1598 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1599 if (IS_ERR(sb)) {
1600 ret = PTR_ERR(sb);
1601 cgroup_drop_root(opts.new_root);
1602 goto drop_modules;
1605 root = sb->s_fs_info;
1606 BUG_ON(!root);
1607 if (root == opts.new_root) {
1608 /* We used the new root structure, so this is a new hierarchy */
1609 struct list_head tmp_cg_links;
1610 struct cgroup *root_cgrp = &root->top_cgroup;
1611 struct cgroupfs_root *existing_root;
1612 const struct cred *cred;
1613 int i;
1614 struct hlist_node *node;
1615 struct css_set *cg;
1617 BUG_ON(sb->s_root != NULL);
1619 ret = cgroup_get_rootdir(sb);
1620 if (ret)
1621 goto drop_new_super;
1622 inode = sb->s_root->d_inode;
1624 mutex_lock(&inode->i_mutex);
1625 mutex_lock(&cgroup_mutex);
1626 mutex_lock(&cgroup_root_mutex);
1628 /* Check for name clashes with existing mounts */
1629 ret = -EBUSY;
1630 if (strlen(root->name))
1631 for_each_active_root(existing_root)
1632 if (!strcmp(existing_root->name, root->name))
1633 goto unlock_drop;
1636 * We're accessing css_set_count without locking
1637 * css_set_lock here, but that's OK - it can only be
1638 * increased by someone holding cgroup_lock, and
1639 * that's us. The worst that can happen is that we
1640 * have some link structures left over
1642 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
1643 if (ret)
1644 goto unlock_drop;
1646 ret = rebind_subsystems(root, root->subsys_mask);
1647 if (ret == -EBUSY) {
1648 free_cg_links(&tmp_cg_links);
1649 goto unlock_drop;
1652 * There must be no failure case after here, since rebinding
1653 * takes care of subsystems' refcounts, which are explicitly
1654 * dropped in the failure exit path.
1657 /* EBUSY should be the only error here */
1658 BUG_ON(ret);
1660 list_add(&root->root_list, &roots);
1661 root_count++;
1663 sb->s_root->d_fsdata = root_cgrp;
1664 root->top_cgroup.dentry = sb->s_root;
1666 /* Link the top cgroup in this hierarchy into all
1667 * the css_set objects */
1668 write_lock(&css_set_lock);
1669 hash_for_each(css_set_table, i, node, cg, hlist)
1670 link_css_set(&tmp_cg_links, cg, root_cgrp);
1671 write_unlock(&css_set_lock);
1673 free_cg_links(&tmp_cg_links);
1675 BUG_ON(!list_empty(&root_cgrp->children));
1676 BUG_ON(root->number_of_cgroups != 1);
1678 cred = override_creds(&init_cred);
1679 cgroup_populate_dir(root_cgrp, true, root->subsys_mask);
1680 revert_creds(cred);
1681 mutex_unlock(&cgroup_root_mutex);
1682 mutex_unlock(&cgroup_mutex);
1683 mutex_unlock(&inode->i_mutex);
1684 } else {
1686 * We re-used an existing hierarchy - the new root (if
1687 * any) is not needed
1689 cgroup_drop_root(opts.new_root);
1690 /* no subsys rebinding, so refcounts don't change */
1691 drop_parsed_module_refcounts(opts.subsys_mask);
1694 kfree(opts.release_agent);
1695 kfree(opts.name);
1696 return dget(sb->s_root);
1698 unlock_drop:
1699 mutex_unlock(&cgroup_root_mutex);
1700 mutex_unlock(&cgroup_mutex);
1701 mutex_unlock(&inode->i_mutex);
1702 drop_new_super:
1703 deactivate_locked_super(sb);
1704 drop_modules:
1705 drop_parsed_module_refcounts(opts.subsys_mask);
1706 out_err:
1707 kfree(opts.release_agent);
1708 kfree(opts.name);
1709 return ERR_PTR(ret);
1712 static void cgroup_kill_sb(struct super_block *sb) {
1713 struct cgroupfs_root *root = sb->s_fs_info;
1714 struct cgroup *cgrp = &root->top_cgroup;
1715 int ret;
1716 struct cg_cgroup_link *link;
1717 struct cg_cgroup_link *saved_link;
1719 BUG_ON(!root);
1721 BUG_ON(root->number_of_cgroups != 1);
1722 BUG_ON(!list_empty(&cgrp->children));
1724 mutex_lock(&cgroup_mutex);
1725 mutex_lock(&cgroup_root_mutex);
1727 /* Rebind all subsystems back to the default hierarchy */
1728 ret = rebind_subsystems(root, 0);
1729 /* Shouldn't be able to fail ... */
1730 BUG_ON(ret);
1733 * Release all the links from css_sets to this hierarchy's
1734 * root cgroup
1736 write_lock(&css_set_lock);
1738 list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1739 cgrp_link_list) {
1740 list_del(&link->cg_link_list);
1741 list_del(&link->cgrp_link_list);
1742 kfree(link);
1744 write_unlock(&css_set_lock);
1746 if (!list_empty(&root->root_list)) {
1747 list_del(&root->root_list);
1748 root_count--;
1751 mutex_unlock(&cgroup_root_mutex);
1752 mutex_unlock(&cgroup_mutex);
1754 simple_xattrs_free(&cgrp->xattrs);
1756 kill_litter_super(sb);
1757 cgroup_drop_root(root);
1760 static struct file_system_type cgroup_fs_type = {
1761 .name = "cgroup",
1762 .mount = cgroup_mount,
1763 .kill_sb = cgroup_kill_sb,
1766 static struct kobject *cgroup_kobj;
1769 * cgroup_path - generate the path of a cgroup
1770 * @cgrp: the cgroup in question
1771 * @buf: the buffer to write the path into
1772 * @buflen: the length of the buffer
1774 * Called with cgroup_mutex held or else with an RCU-protected cgroup
1775 * reference. Writes path of cgroup into buf. Returns 0 on success,
1776 * -errno on error.
1778 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1780 struct dentry *dentry = cgrp->dentry;
1781 char *start;
1783 rcu_lockdep_assert(rcu_read_lock_held() || cgroup_lock_is_held(),
1784 "cgroup_path() called without proper locking");
1786 if (cgrp == dummytop) {
1788 * Inactive subsystems have no dentry for their root
1789 * cgroup
1791 strcpy(buf, "/");
1792 return 0;
1795 start = buf + buflen - 1;
1797 *start = '\0';
1798 for (;;) {
1799 int len = dentry->d_name.len;
1801 if ((start -= len) < buf)
1802 return -ENAMETOOLONG;
1803 memcpy(start, dentry->d_name.name, len);
1804 cgrp = cgrp->parent;
1805 if (!cgrp)
1806 break;
1808 dentry = cgrp->dentry;
1809 if (!cgrp->parent)
1810 continue;
1811 if (--start < buf)
1812 return -ENAMETOOLONG;
1813 *start = '/';
1815 memmove(buf, start, buf + buflen - start);
1816 return 0;
1818 EXPORT_SYMBOL_GPL(cgroup_path);
1821 * Control Group taskset
1823 struct task_and_cgroup {
1824 struct task_struct *task;
1825 struct cgroup *cgrp;
1826 struct css_set *cg;
1829 struct cgroup_taskset {
1830 struct task_and_cgroup single;
1831 struct flex_array *tc_array;
1832 int tc_array_len;
1833 int idx;
1834 struct cgroup *cur_cgrp;
1838 * cgroup_taskset_first - reset taskset and return the first task
1839 * @tset: taskset of interest
1841 * @tset iteration is initialized and the first task is returned.
1843 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1845 if (tset->tc_array) {
1846 tset->idx = 0;
1847 return cgroup_taskset_next(tset);
1848 } else {
1849 tset->cur_cgrp = tset->single.cgrp;
1850 return tset->single.task;
1853 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1856 * cgroup_taskset_next - iterate to the next task in taskset
1857 * @tset: taskset of interest
1859 * Return the next task in @tset. Iteration must have been initialized
1860 * with cgroup_taskset_first().
1862 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1864 struct task_and_cgroup *tc;
1866 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1867 return NULL;
1869 tc = flex_array_get(tset->tc_array, tset->idx++);
1870 tset->cur_cgrp = tc->cgrp;
1871 return tc->task;
1873 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1876 * cgroup_taskset_cur_cgroup - return the matching cgroup for the current task
1877 * @tset: taskset of interest
1879 * Return the cgroup for the current (last returned) task of @tset. This
1880 * function must be preceded by either cgroup_taskset_first() or
1881 * cgroup_taskset_next().
1883 struct cgroup *cgroup_taskset_cur_cgroup(struct cgroup_taskset *tset)
1885 return tset->cur_cgrp;
1887 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_cgroup);
1890 * cgroup_taskset_size - return the number of tasks in taskset
1891 * @tset: taskset of interest
1893 int cgroup_taskset_size(struct cgroup_taskset *tset)
1895 return tset->tc_array ? tset->tc_array_len : 1;
1897 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1901 * cgroup_task_migrate - move a task from one cgroup to another.
1903 * Must be called with cgroup_mutex and threadgroup locked.
1905 static void cgroup_task_migrate(struct cgroup *cgrp, struct cgroup *oldcgrp,
1906 struct task_struct *tsk, struct css_set *newcg)
1908 struct css_set *oldcg;
1911 * We are synchronized through threadgroup_lock() against PF_EXITING
1912 * setting such that we can't race against cgroup_exit() changing the
1913 * css_set to init_css_set and dropping the old one.
1915 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1916 oldcg = tsk->cgroups;
1918 task_lock(tsk);
1919 rcu_assign_pointer(tsk->cgroups, newcg);
1920 task_unlock(tsk);
1922 /* Update the css_set linked lists if we're using them */
1923 write_lock(&css_set_lock);
1924 if (!list_empty(&tsk->cg_list))
1925 list_move(&tsk->cg_list, &newcg->tasks);
1926 write_unlock(&css_set_lock);
1929 * We just gained a reference on oldcg by taking it from the task. As
1930 * trading it for newcg is protected by cgroup_mutex, we're safe to drop
1931 * it here; it will be freed under RCU.
1933 set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1934 put_css_set(oldcg);
1938 * cgroup_attach_task - attach task 'tsk' to cgroup 'cgrp'
1939 * @cgrp: the cgroup the task is attaching to
1940 * @tsk: the task to be attached
1942 * Call with cgroup_mutex and threadgroup locked. May take task_lock of
1943 * @tsk during call.
1945 int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
1947 int retval = 0;
1948 struct cgroup_subsys *ss, *failed_ss = NULL;
1949 struct cgroup *oldcgrp;
1950 struct cgroupfs_root *root = cgrp->root;
1951 struct cgroup_taskset tset = { };
1952 struct css_set *newcg;
1954 /* @tsk either already exited or can't exit until the end */
1955 if (tsk->flags & PF_EXITING)
1956 return -ESRCH;
1958 /* Nothing to do if the task is already in that cgroup */
1959 oldcgrp = task_cgroup_from_root(tsk, root);
1960 if (cgrp == oldcgrp)
1961 return 0;
1963 tset.single.task = tsk;
1964 tset.single.cgrp = oldcgrp;
1966 for_each_subsys(root, ss) {
1967 if (ss->can_attach) {
1968 retval = ss->can_attach(cgrp, &tset);
1969 if (retval) {
1971 * Remember on which subsystem the can_attach()
1972 * failed, so that we only call cancel_attach()
1973 * against the subsystems whose can_attach()
1974 * succeeded. (See below)
1976 failed_ss = ss;
1977 goto out;
1982 newcg = find_css_set(tsk->cgroups, cgrp);
1983 if (!newcg) {
1984 retval = -ENOMEM;
1985 goto out;
1988 cgroup_task_migrate(cgrp, oldcgrp, tsk, newcg);
1990 for_each_subsys(root, ss) {
1991 if (ss->attach)
1992 ss->attach(cgrp, &tset);
1995 out:
1996 if (retval) {
1997 for_each_subsys(root, ss) {
1998 if (ss == failed_ss)
2000 * This subsystem was the one that failed the
2001 * can_attach() check earlier, so we don't need
2002 * to call cancel_attach() against it or any
2003 * remaining subsystems.
2005 break;
2006 if (ss->cancel_attach)
2007 ss->cancel_attach(cgrp, &tset);
2010 return retval;
2014 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2015 * @from: attach to all cgroups of a given task
2016 * @tsk: the task to be attached
2018 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2020 struct cgroupfs_root *root;
2021 int retval = 0;
2023 cgroup_lock();
2024 for_each_active_root(root) {
2025 struct cgroup *from_cg = task_cgroup_from_root(from, root);
2027 retval = cgroup_attach_task(from_cg, tsk);
2028 if (retval)
2029 break;
2031 cgroup_unlock();
2033 return retval;
2035 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2038 * cgroup_attach_proc - attach all threads in a threadgroup to a cgroup
2039 * @cgrp: the cgroup to attach to
2040 * @leader: the threadgroup leader task_struct of the group to be attached
2042 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
2043 * task_lock of each thread in leader's threadgroup individually in turn.
2045 static int cgroup_attach_proc(struct cgroup *cgrp, struct task_struct *leader)
2047 int retval, i, group_size;
2048 struct cgroup_subsys *ss, *failed_ss = NULL;
2049 /* guaranteed to be initialized later, but the compiler needs this */
2050 struct cgroupfs_root *root = cgrp->root;
2051 /* threadgroup list cursor and array */
2052 struct task_struct *tsk;
2053 struct task_and_cgroup *tc;
2054 struct flex_array *group;
2055 struct cgroup_taskset tset = { };
2058 * step 0: in order to do expensive, possibly blocking operations for
2059 * every thread, we cannot iterate the thread group list, since it needs
2060 * rcu or tasklist locked. instead, build an array of all threads in the
2061 * group - group_rwsem prevents new threads from appearing, and if
2062 * threads exit, this will just be an over-estimate.
2064 group_size = get_nr_threads(leader);
2065 /* flex_array supports very large thread-groups better than kmalloc. */
2066 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
2067 if (!group)
2068 return -ENOMEM;
2069 /* pre-allocate to guarantee space while iterating in rcu read-side. */
2070 retval = flex_array_prealloc(group, 0, group_size - 1, GFP_KERNEL);
2071 if (retval)
2072 goto out_free_group_list;
2074 tsk = leader;
2075 i = 0;
2077 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2078 * already PF_EXITING could be freed from underneath us unless we
2079 * take an rcu_read_lock.
2081 rcu_read_lock();
2082 do {
2083 struct task_and_cgroup ent;
2085 /* @tsk either already exited or can't exit until the end */
2086 if (tsk->flags & PF_EXITING)
2087 continue;
2089 /* as per above, nr_threads may decrease, but not increase. */
2090 BUG_ON(i >= group_size);
2091 ent.task = tsk;
2092 ent.cgrp = task_cgroup_from_root(tsk, root);
2093 /* nothing to do if this task is already in the cgroup */
2094 if (ent.cgrp == cgrp)
2095 continue;
2097 * saying GFP_ATOMIC has no effect here because we did prealloc
2098 * earlier, but it's good form to communicate our expectations.
2100 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
2101 BUG_ON(retval != 0);
2102 i++;
2103 } while_each_thread(leader, tsk);
2104 rcu_read_unlock();
2105 /* remember the number of threads in the array for later. */
2106 group_size = i;
2107 tset.tc_array = group;
2108 tset.tc_array_len = group_size;
2110 /* methods shouldn't be called if no task is actually migrating */
2111 retval = 0;
2112 if (!group_size)
2113 goto out_free_group_list;
2116 * step 1: check that we can legitimately attach to the cgroup.
2118 for_each_subsys(root, ss) {
2119 if (ss->can_attach) {
2120 retval = ss->can_attach(cgrp, &tset);
2121 if (retval) {
2122 failed_ss = ss;
2123 goto out_cancel_attach;
2129 * step 2: make sure css_sets exist for all threads to be migrated.
2130 * we use find_css_set, which allocates a new one if necessary.
2132 for (i = 0; i < group_size; i++) {
2133 tc = flex_array_get(group, i);
2134 tc->cg = find_css_set(tc->task->cgroups, cgrp);
2135 if (!tc->cg) {
2136 retval = -ENOMEM;
2137 goto out_put_css_set_refs;
2142 * step 3: now that we're guaranteed success wrt the css_sets,
2143 * proceed to move all tasks to the new cgroup. There are no
2144 * failure cases after here, so this is the commit point.
2146 for (i = 0; i < group_size; i++) {
2147 tc = flex_array_get(group, i);
2148 cgroup_task_migrate(cgrp, tc->cgrp, tc->task, tc->cg);
2150 /* nothing is sensitive to fork() after this point. */
2153 * step 4: do subsystem attach callbacks.
2155 for_each_subsys(root, ss) {
2156 if (ss->attach)
2157 ss->attach(cgrp, &tset);
2161 * step 5: success! and cleanup
2163 retval = 0;
2164 out_put_css_set_refs:
2165 if (retval) {
2166 for (i = 0; i < group_size; i++) {
2167 tc = flex_array_get(group, i);
2168 if (!tc->cg)
2169 break;
2170 put_css_set(tc->cg);
2173 out_cancel_attach:
2174 if (retval) {
2175 for_each_subsys(root, ss) {
2176 if (ss == failed_ss)
2177 break;
2178 if (ss->cancel_attach)
2179 ss->cancel_attach(cgrp, &tset);
2182 out_free_group_list:
2183 flex_array_free(group);
2184 return retval;
2188 * Find the task_struct of the task to attach by vpid and pass it along to the
2189 * function to attach either it or all tasks in its threadgroup. Will lock
2190 * cgroup_mutex and threadgroup; may take task_lock of task.
2192 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2194 struct task_struct *tsk;
2195 const struct cred *cred = current_cred(), *tcred;
2196 int ret;
2198 if (!cgroup_lock_live_group(cgrp))
2199 return -ENODEV;
2201 retry_find_task:
2202 rcu_read_lock();
2203 if (pid) {
2204 tsk = find_task_by_vpid(pid);
2205 if (!tsk) {
2206 rcu_read_unlock();
2207 ret= -ESRCH;
2208 goto out_unlock_cgroup;
2211 * even if we're attaching all tasks in the thread group, we
2212 * only need to check permissions on one of them.
2214 tcred = __task_cred(tsk);
2215 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2216 !uid_eq(cred->euid, tcred->uid) &&
2217 !uid_eq(cred->euid, tcred->suid)) {
2218 rcu_read_unlock();
2219 ret = -EACCES;
2220 goto out_unlock_cgroup;
2222 } else
2223 tsk = current;
2225 if (threadgroup)
2226 tsk = tsk->group_leader;
2229 * Workqueue threads may acquire PF_THREAD_BOUND and become
2230 * trapped in a cpuset, or RT worker may be born in a cgroup
2231 * with no rt_runtime allocated. Just say no.
2233 if (tsk == kthreadd_task || (tsk->flags & PF_THREAD_BOUND)) {
2234 ret = -EINVAL;
2235 rcu_read_unlock();
2236 goto out_unlock_cgroup;
2239 get_task_struct(tsk);
2240 rcu_read_unlock();
2242 threadgroup_lock(tsk);
2243 if (threadgroup) {
2244 if (!thread_group_leader(tsk)) {
2246 * a race with de_thread from another thread's exec()
2247 * may strip us of our leadership, if this happens,
2248 * there is no choice but to throw this task away and
2249 * try again; this is
2250 * "double-double-toil-and-trouble-check locking".
2252 threadgroup_unlock(tsk);
2253 put_task_struct(tsk);
2254 goto retry_find_task;
2256 ret = cgroup_attach_proc(cgrp, tsk);
2257 } else
2258 ret = cgroup_attach_task(cgrp, tsk);
2259 threadgroup_unlock(tsk);
2261 put_task_struct(tsk);
2262 out_unlock_cgroup:
2263 cgroup_unlock();
2264 return ret;
2267 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
2269 return attach_task_by_pid(cgrp, pid, false);
2272 static int cgroup_procs_write(struct cgroup *cgrp, struct cftype *cft, u64 tgid)
2274 return attach_task_by_pid(cgrp, tgid, true);
2278 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
2279 * @cgrp: the cgroup to be checked for liveness
2281 * On success, returns true; the lock should be later released with
2282 * cgroup_unlock(). On failure returns false with no lock held.
2284 bool cgroup_lock_live_group(struct cgroup *cgrp)
2286 mutex_lock(&cgroup_mutex);
2287 if (cgroup_is_removed(cgrp)) {
2288 mutex_unlock(&cgroup_mutex);
2289 return false;
2291 return true;
2293 EXPORT_SYMBOL_GPL(cgroup_lock_live_group);
2295 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
2296 const char *buffer)
2298 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
2299 if (strlen(buffer) >= PATH_MAX)
2300 return -EINVAL;
2301 if (!cgroup_lock_live_group(cgrp))
2302 return -ENODEV;
2303 mutex_lock(&cgroup_root_mutex);
2304 strcpy(cgrp->root->release_agent_path, buffer);
2305 mutex_unlock(&cgroup_root_mutex);
2306 cgroup_unlock();
2307 return 0;
2310 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
2311 struct seq_file *seq)
2313 if (!cgroup_lock_live_group(cgrp))
2314 return -ENODEV;
2315 seq_puts(seq, cgrp->root->release_agent_path);
2316 seq_putc(seq, '\n');
2317 cgroup_unlock();
2318 return 0;
2321 /* A buffer size big enough for numbers or short strings */
2322 #define CGROUP_LOCAL_BUFFER_SIZE 64
2324 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
2325 struct file *file,
2326 const char __user *userbuf,
2327 size_t nbytes, loff_t *unused_ppos)
2329 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
2330 int retval = 0;
2331 char *end;
2333 if (!nbytes)
2334 return -EINVAL;
2335 if (nbytes >= sizeof(buffer))
2336 return -E2BIG;
2337 if (copy_from_user(buffer, userbuf, nbytes))
2338 return -EFAULT;
2340 buffer[nbytes] = 0; /* nul-terminate */
2341 if (cft->write_u64) {
2342 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
2343 if (*end)
2344 return -EINVAL;
2345 retval = cft->write_u64(cgrp, cft, val);
2346 } else {
2347 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
2348 if (*end)
2349 return -EINVAL;
2350 retval = cft->write_s64(cgrp, cft, val);
2352 if (!retval)
2353 retval = nbytes;
2354 return retval;
2357 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
2358 struct file *file,
2359 const char __user *userbuf,
2360 size_t nbytes, loff_t *unused_ppos)
2362 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
2363 int retval = 0;
2364 size_t max_bytes = cft->max_write_len;
2365 char *buffer = local_buffer;
2367 if (!max_bytes)
2368 max_bytes = sizeof(local_buffer) - 1;
2369 if (nbytes >= max_bytes)
2370 return -E2BIG;
2371 /* Allocate a dynamic buffer if we need one */
2372 if (nbytes >= sizeof(local_buffer)) {
2373 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2374 if (buffer == NULL)
2375 return -ENOMEM;
2377 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2378 retval = -EFAULT;
2379 goto out;
2382 buffer[nbytes] = 0; /* nul-terminate */
2383 retval = cft->write_string(cgrp, cft, strstrip(buffer));
2384 if (!retval)
2385 retval = nbytes;
2386 out:
2387 if (buffer != local_buffer)
2388 kfree(buffer);
2389 return retval;
2392 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2393 size_t nbytes, loff_t *ppos)
2395 struct cftype *cft = __d_cft(file->f_dentry);
2396 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2398 if (cgroup_is_removed(cgrp))
2399 return -ENODEV;
2400 if (cft->write)
2401 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
2402 if (cft->write_u64 || cft->write_s64)
2403 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
2404 if (cft->write_string)
2405 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
2406 if (cft->trigger) {
2407 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
2408 return ret ? ret : nbytes;
2410 return -EINVAL;
2413 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
2414 struct file *file,
2415 char __user *buf, size_t nbytes,
2416 loff_t *ppos)
2418 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2419 u64 val = cft->read_u64(cgrp, cft);
2420 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2422 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2425 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
2426 struct file *file,
2427 char __user *buf, size_t nbytes,
2428 loff_t *ppos)
2430 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2431 s64 val = cft->read_s64(cgrp, cft);
2432 int len = sprintf(tmp, "%lld\n", (long long) val);
2434 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2437 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2438 size_t nbytes, loff_t *ppos)
2440 struct cftype *cft = __d_cft(file->f_dentry);
2441 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2443 if (cgroup_is_removed(cgrp))
2444 return -ENODEV;
2446 if (cft->read)
2447 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
2448 if (cft->read_u64)
2449 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
2450 if (cft->read_s64)
2451 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
2452 return -EINVAL;
2456 * seqfile ops/methods for returning structured data. Currently just
2457 * supports string->u64 maps, but can be extended in future.
2460 struct cgroup_seqfile_state {
2461 struct cftype *cft;
2462 struct cgroup *cgroup;
2465 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2467 struct seq_file *sf = cb->state;
2468 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2471 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2473 struct cgroup_seqfile_state *state = m->private;
2474 struct cftype *cft = state->cft;
2475 if (cft->read_map) {
2476 struct cgroup_map_cb cb = {
2477 .fill = cgroup_map_add,
2478 .state = m,
2480 return cft->read_map(state->cgroup, cft, &cb);
2482 return cft->read_seq_string(state->cgroup, cft, m);
2485 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
2487 struct seq_file *seq = file->private_data;
2488 kfree(seq->private);
2489 return single_release(inode, file);
2492 static const struct file_operations cgroup_seqfile_operations = {
2493 .read = seq_read,
2494 .write = cgroup_file_write,
2495 .llseek = seq_lseek,
2496 .release = cgroup_seqfile_release,
2499 static int cgroup_file_open(struct inode *inode, struct file *file)
2501 int err;
2502 struct cftype *cft;
2504 err = generic_file_open(inode, file);
2505 if (err)
2506 return err;
2507 cft = __d_cft(file->f_dentry);
2509 if (cft->read_map || cft->read_seq_string) {
2510 struct cgroup_seqfile_state *state =
2511 kzalloc(sizeof(*state), GFP_USER);
2512 if (!state)
2513 return -ENOMEM;
2514 state->cft = cft;
2515 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
2516 file->f_op = &cgroup_seqfile_operations;
2517 err = single_open(file, cgroup_seqfile_show, state);
2518 if (err < 0)
2519 kfree(state);
2520 } else if (cft->open)
2521 err = cft->open(inode, file);
2522 else
2523 err = 0;
2525 return err;
2528 static int cgroup_file_release(struct inode *inode, struct file *file)
2530 struct cftype *cft = __d_cft(file->f_dentry);
2531 if (cft->release)
2532 return cft->release(inode, file);
2533 return 0;
2537 * cgroup_rename - Only allow simple rename of directories in place.
2539 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2540 struct inode *new_dir, struct dentry *new_dentry)
2542 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2543 return -ENOTDIR;
2544 if (new_dentry->d_inode)
2545 return -EEXIST;
2546 if (old_dir != new_dir)
2547 return -EIO;
2548 return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2551 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2553 if (S_ISDIR(dentry->d_inode->i_mode))
2554 return &__d_cgrp(dentry)->xattrs;
2555 else
2556 return &__d_cft(dentry)->xattrs;
2559 static inline int xattr_enabled(struct dentry *dentry)
2561 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2562 return test_bit(ROOT_XATTR, &root->flags);
2565 static bool is_valid_xattr(const char *name)
2567 if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2568 !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2569 return true;
2570 return false;
2573 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2574 const void *val, size_t size, int flags)
2576 if (!xattr_enabled(dentry))
2577 return -EOPNOTSUPP;
2578 if (!is_valid_xattr(name))
2579 return -EINVAL;
2580 return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2583 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2585 if (!xattr_enabled(dentry))
2586 return -EOPNOTSUPP;
2587 if (!is_valid_xattr(name))
2588 return -EINVAL;
2589 return simple_xattr_remove(__d_xattrs(dentry), name);
2592 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2593 void *buf, size_t size)
2595 if (!xattr_enabled(dentry))
2596 return -EOPNOTSUPP;
2597 if (!is_valid_xattr(name))
2598 return -EINVAL;
2599 return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2602 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2604 if (!xattr_enabled(dentry))
2605 return -EOPNOTSUPP;
2606 return simple_xattr_list(__d_xattrs(dentry), buf, size);
2609 static const struct file_operations cgroup_file_operations = {
2610 .read = cgroup_file_read,
2611 .write = cgroup_file_write,
2612 .llseek = generic_file_llseek,
2613 .open = cgroup_file_open,
2614 .release = cgroup_file_release,
2617 static const struct inode_operations cgroup_file_inode_operations = {
2618 .setxattr = cgroup_setxattr,
2619 .getxattr = cgroup_getxattr,
2620 .listxattr = cgroup_listxattr,
2621 .removexattr = cgroup_removexattr,
2624 static const struct inode_operations cgroup_dir_inode_operations = {
2625 .lookup = cgroup_lookup,
2626 .mkdir = cgroup_mkdir,
2627 .rmdir = cgroup_rmdir,
2628 .rename = cgroup_rename,
2629 .setxattr = cgroup_setxattr,
2630 .getxattr = cgroup_getxattr,
2631 .listxattr = cgroup_listxattr,
2632 .removexattr = cgroup_removexattr,
2635 static struct dentry *cgroup_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
2637 if (dentry->d_name.len > NAME_MAX)
2638 return ERR_PTR(-ENAMETOOLONG);
2639 d_add(dentry, NULL);
2640 return NULL;
2644 * Check if a file is a control file
2646 static inline struct cftype *__file_cft(struct file *file)
2648 if (file_inode(file)->i_fop != &cgroup_file_operations)
2649 return ERR_PTR(-EINVAL);
2650 return __d_cft(file->f_dentry);
2653 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2654 struct super_block *sb)
2656 struct inode *inode;
2658 if (!dentry)
2659 return -ENOENT;
2660 if (dentry->d_inode)
2661 return -EEXIST;
2663 inode = cgroup_new_inode(mode, sb);
2664 if (!inode)
2665 return -ENOMEM;
2667 if (S_ISDIR(mode)) {
2668 inode->i_op = &cgroup_dir_inode_operations;
2669 inode->i_fop = &simple_dir_operations;
2671 /* start off with i_nlink == 2 (for "." entry) */
2672 inc_nlink(inode);
2673 inc_nlink(dentry->d_parent->d_inode);
2676 * Control reaches here with cgroup_mutex held.
2677 * @inode->i_mutex should nest outside cgroup_mutex but we
2678 * want to populate it immediately without releasing
2679 * cgroup_mutex. As @inode isn't visible to anyone else
2680 * yet, trylock will always succeed without affecting
2681 * lockdep checks.
2683 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2684 } else if (S_ISREG(mode)) {
2685 inode->i_size = 0;
2686 inode->i_fop = &cgroup_file_operations;
2687 inode->i_op = &cgroup_file_inode_operations;
2689 d_instantiate(dentry, inode);
2690 dget(dentry); /* Extra count - pin the dentry in core */
2691 return 0;
2695 * cgroup_file_mode - deduce file mode of a control file
2696 * @cft: the control file in question
2698 * returns cft->mode if ->mode is not 0
2699 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2700 * returns S_IRUGO if it has only a read handler
2701 * returns S_IWUSR if it has only a write hander
2703 static umode_t cgroup_file_mode(const struct cftype *cft)
2705 umode_t mode = 0;
2707 if (cft->mode)
2708 return cft->mode;
2710 if (cft->read || cft->read_u64 || cft->read_s64 ||
2711 cft->read_map || cft->read_seq_string)
2712 mode |= S_IRUGO;
2714 if (cft->write || cft->write_u64 || cft->write_s64 ||
2715 cft->write_string || cft->trigger)
2716 mode |= S_IWUSR;
2718 return mode;
2721 static int cgroup_add_file(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2722 struct cftype *cft)
2724 struct dentry *dir = cgrp->dentry;
2725 struct cgroup *parent = __d_cgrp(dir);
2726 struct dentry *dentry;
2727 struct cfent *cfe;
2728 int error;
2729 umode_t mode;
2730 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2732 simple_xattrs_init(&cft->xattrs);
2734 if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) {
2735 strcpy(name, subsys->name);
2736 strcat(name, ".");
2738 strcat(name, cft->name);
2740 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2742 cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2743 if (!cfe)
2744 return -ENOMEM;
2746 dentry = lookup_one_len(name, dir, strlen(name));
2747 if (IS_ERR(dentry)) {
2748 error = PTR_ERR(dentry);
2749 goto out;
2752 mode = cgroup_file_mode(cft);
2753 error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2754 if (!error) {
2755 cfe->type = (void *)cft;
2756 cfe->dentry = dentry;
2757 dentry->d_fsdata = cfe;
2758 list_add_tail(&cfe->node, &parent->files);
2759 cfe = NULL;
2761 dput(dentry);
2762 out:
2763 kfree(cfe);
2764 return error;
2767 static int cgroup_addrm_files(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2768 struct cftype cfts[], bool is_add)
2770 struct cftype *cft;
2771 int err, ret = 0;
2773 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2774 /* does cft->flags tell us to skip this file on @cgrp? */
2775 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2776 continue;
2777 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2778 continue;
2780 if (is_add) {
2781 err = cgroup_add_file(cgrp, subsys, cft);
2782 if (err)
2783 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2784 cft->name, err);
2785 ret = err;
2786 } else {
2787 cgroup_rm_file(cgrp, cft);
2790 return ret;
2793 static DEFINE_MUTEX(cgroup_cft_mutex);
2795 static void cgroup_cfts_prepare(void)
2796 __acquires(&cgroup_cft_mutex) __acquires(&cgroup_mutex)
2799 * Thanks to the entanglement with vfs inode locking, we can't walk
2800 * the existing cgroups under cgroup_mutex and create files.
2801 * Instead, we increment reference on all cgroups and build list of
2802 * them using @cgrp->cft_q_node. Grab cgroup_cft_mutex to ensure
2803 * exclusive access to the field.
2805 mutex_lock(&cgroup_cft_mutex);
2806 mutex_lock(&cgroup_mutex);
2809 static void cgroup_cfts_commit(struct cgroup_subsys *ss,
2810 struct cftype *cfts, bool is_add)
2811 __releases(&cgroup_mutex) __releases(&cgroup_cft_mutex)
2813 LIST_HEAD(pending);
2814 struct cgroup *cgrp, *n;
2816 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2817 if (cfts && ss->root != &rootnode) {
2818 list_for_each_entry(cgrp, &ss->root->allcg_list, allcg_node) {
2819 dget(cgrp->dentry);
2820 list_add_tail(&cgrp->cft_q_node, &pending);
2824 mutex_unlock(&cgroup_mutex);
2827 * All new cgroups will see @cfts update on @ss->cftsets. Add/rm
2828 * files for all cgroups which were created before.
2830 list_for_each_entry_safe(cgrp, n, &pending, cft_q_node) {
2831 struct inode *inode = cgrp->dentry->d_inode;
2833 mutex_lock(&inode->i_mutex);
2834 mutex_lock(&cgroup_mutex);
2835 if (!cgroup_is_removed(cgrp))
2836 cgroup_addrm_files(cgrp, ss, cfts, is_add);
2837 mutex_unlock(&cgroup_mutex);
2838 mutex_unlock(&inode->i_mutex);
2840 list_del_init(&cgrp->cft_q_node);
2841 dput(cgrp->dentry);
2844 mutex_unlock(&cgroup_cft_mutex);
2848 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2849 * @ss: target cgroup subsystem
2850 * @cfts: zero-length name terminated array of cftypes
2852 * Register @cfts to @ss. Files described by @cfts are created for all
2853 * existing cgroups to which @ss is attached and all future cgroups will
2854 * have them too. This function can be called anytime whether @ss is
2855 * attached or not.
2857 * Returns 0 on successful registration, -errno on failure. Note that this
2858 * function currently returns 0 as long as @cfts registration is successful
2859 * even if some file creation attempts on existing cgroups fail.
2861 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2863 struct cftype_set *set;
2865 set = kzalloc(sizeof(*set), GFP_KERNEL);
2866 if (!set)
2867 return -ENOMEM;
2869 cgroup_cfts_prepare();
2870 set->cfts = cfts;
2871 list_add_tail(&set->node, &ss->cftsets);
2872 cgroup_cfts_commit(ss, cfts, true);
2874 return 0;
2876 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2879 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2880 * @ss: target cgroup subsystem
2881 * @cfts: zero-length name terminated array of cftypes
2883 * Unregister @cfts from @ss. Files described by @cfts are removed from
2884 * all existing cgroups to which @ss is attached and all future cgroups
2885 * won't have them either. This function can be called anytime whether @ss
2886 * is attached or not.
2888 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2889 * registered with @ss.
2891 int cgroup_rm_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2893 struct cftype_set *set;
2895 cgroup_cfts_prepare();
2897 list_for_each_entry(set, &ss->cftsets, node) {
2898 if (set->cfts == cfts) {
2899 list_del_init(&set->node);
2900 cgroup_cfts_commit(ss, cfts, false);
2901 return 0;
2905 cgroup_cfts_commit(ss, NULL, false);
2906 return -ENOENT;
2910 * cgroup_task_count - count the number of tasks in a cgroup.
2911 * @cgrp: the cgroup in question
2913 * Return the number of tasks in the cgroup.
2915 int cgroup_task_count(const struct cgroup *cgrp)
2917 int count = 0;
2918 struct cg_cgroup_link *link;
2920 read_lock(&css_set_lock);
2921 list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
2922 count += atomic_read(&link->cg->refcount);
2924 read_unlock(&css_set_lock);
2925 return count;
2929 * Advance a list_head iterator. The iterator should be positioned at
2930 * the start of a css_set
2932 static void cgroup_advance_iter(struct cgroup *cgrp,
2933 struct cgroup_iter *it)
2935 struct list_head *l = it->cg_link;
2936 struct cg_cgroup_link *link;
2937 struct css_set *cg;
2939 /* Advance to the next non-empty css_set */
2940 do {
2941 l = l->next;
2942 if (l == &cgrp->css_sets) {
2943 it->cg_link = NULL;
2944 return;
2946 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
2947 cg = link->cg;
2948 } while (list_empty(&cg->tasks));
2949 it->cg_link = l;
2950 it->task = cg->tasks.next;
2954 * To reduce the fork() overhead for systems that are not actually
2955 * using their cgroups capability, we don't maintain the lists running
2956 * through each css_set to its tasks until we see the list actually
2957 * used - in other words after the first call to cgroup_iter_start().
2959 static void cgroup_enable_task_cg_lists(void)
2961 struct task_struct *p, *g;
2962 write_lock(&css_set_lock);
2963 use_task_css_set_links = 1;
2965 * We need tasklist_lock because RCU is not safe against
2966 * while_each_thread(). Besides, a forking task that has passed
2967 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2968 * is not guaranteed to have its child immediately visible in the
2969 * tasklist if we walk through it with RCU.
2971 read_lock(&tasklist_lock);
2972 do_each_thread(g, p) {
2973 task_lock(p);
2975 * We should check if the process is exiting, otherwise
2976 * it will race with cgroup_exit() in that the list
2977 * entry won't be deleted though the process has exited.
2979 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2980 list_add(&p->cg_list, &p->cgroups->tasks);
2981 task_unlock(p);
2982 } while_each_thread(g, p);
2983 read_unlock(&tasklist_lock);
2984 write_unlock(&css_set_lock);
2988 * cgroup_next_descendant_pre - find the next descendant for pre-order walk
2989 * @pos: the current position (%NULL to initiate traversal)
2990 * @cgroup: cgroup whose descendants to walk
2992 * To be used by cgroup_for_each_descendant_pre(). Find the next
2993 * descendant to visit for pre-order traversal of @cgroup's descendants.
2995 struct cgroup *cgroup_next_descendant_pre(struct cgroup *pos,
2996 struct cgroup *cgroup)
2998 struct cgroup *next;
3000 WARN_ON_ONCE(!rcu_read_lock_held());
3002 /* if first iteration, pretend we just visited @cgroup */
3003 if (!pos) {
3004 if (list_empty(&cgroup->children))
3005 return NULL;
3006 pos = cgroup;
3009 /* visit the first child if exists */
3010 next = list_first_or_null_rcu(&pos->children, struct cgroup, sibling);
3011 if (next)
3012 return next;
3014 /* no child, visit my or the closest ancestor's next sibling */
3015 do {
3016 next = list_entry_rcu(pos->sibling.next, struct cgroup,
3017 sibling);
3018 if (&next->sibling != &pos->parent->children)
3019 return next;
3021 pos = pos->parent;
3022 } while (pos != cgroup);
3024 return NULL;
3026 EXPORT_SYMBOL_GPL(cgroup_next_descendant_pre);
3029 * cgroup_rightmost_descendant - return the rightmost descendant of a cgroup
3030 * @pos: cgroup of interest
3032 * Return the rightmost descendant of @pos. If there's no descendant,
3033 * @pos is returned. This can be used during pre-order traversal to skip
3034 * subtree of @pos.
3036 struct cgroup *cgroup_rightmost_descendant(struct cgroup *pos)
3038 struct cgroup *last, *tmp;
3040 WARN_ON_ONCE(!rcu_read_lock_held());
3042 do {
3043 last = pos;
3044 /* ->prev isn't RCU safe, walk ->next till the end */
3045 pos = NULL;
3046 list_for_each_entry_rcu(tmp, &last->children, sibling)
3047 pos = tmp;
3048 } while (pos);
3050 return last;
3052 EXPORT_SYMBOL_GPL(cgroup_rightmost_descendant);
3054 static struct cgroup *cgroup_leftmost_descendant(struct cgroup *pos)
3056 struct cgroup *last;
3058 do {
3059 last = pos;
3060 pos = list_first_or_null_rcu(&pos->children, struct cgroup,
3061 sibling);
3062 } while (pos);
3064 return last;
3068 * cgroup_next_descendant_post - find the next descendant for post-order walk
3069 * @pos: the current position (%NULL to initiate traversal)
3070 * @cgroup: cgroup whose descendants to walk
3072 * To be used by cgroup_for_each_descendant_post(). Find the next
3073 * descendant to visit for post-order traversal of @cgroup's descendants.
3075 struct cgroup *cgroup_next_descendant_post(struct cgroup *pos,
3076 struct cgroup *cgroup)
3078 struct cgroup *next;
3080 WARN_ON_ONCE(!rcu_read_lock_held());
3082 /* if first iteration, visit the leftmost descendant */
3083 if (!pos) {
3084 next = cgroup_leftmost_descendant(cgroup);
3085 return next != cgroup ? next : NULL;
3088 /* if there's an unvisited sibling, visit its leftmost descendant */
3089 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3090 if (&next->sibling != &pos->parent->children)
3091 return cgroup_leftmost_descendant(next);
3093 /* no sibling left, visit parent */
3094 next = pos->parent;
3095 return next != cgroup ? next : NULL;
3097 EXPORT_SYMBOL_GPL(cgroup_next_descendant_post);
3099 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
3100 __acquires(css_set_lock)
3103 * The first time anyone tries to iterate across a cgroup,
3104 * we need to enable the list linking each css_set to its
3105 * tasks, and fix up all existing tasks.
3107 if (!use_task_css_set_links)
3108 cgroup_enable_task_cg_lists();
3110 read_lock(&css_set_lock);
3111 it->cg_link = &cgrp->css_sets;
3112 cgroup_advance_iter(cgrp, it);
3115 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
3116 struct cgroup_iter *it)
3118 struct task_struct *res;
3119 struct list_head *l = it->task;
3120 struct cg_cgroup_link *link;
3122 /* If the iterator cg is NULL, we have no tasks */
3123 if (!it->cg_link)
3124 return NULL;
3125 res = list_entry(l, struct task_struct, cg_list);
3126 /* Advance iterator to find next entry */
3127 l = l->next;
3128 link = list_entry(it->cg_link, struct cg_cgroup_link, cgrp_link_list);
3129 if (l == &link->cg->tasks) {
3130 /* We reached the end of this task list - move on to
3131 * the next cg_cgroup_link */
3132 cgroup_advance_iter(cgrp, it);
3133 } else {
3134 it->task = l;
3136 return res;
3139 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
3140 __releases(css_set_lock)
3142 read_unlock(&css_set_lock);
3145 static inline int started_after_time(struct task_struct *t1,
3146 struct timespec *time,
3147 struct task_struct *t2)
3149 int start_diff = timespec_compare(&t1->start_time, time);
3150 if (start_diff > 0) {
3151 return 1;
3152 } else if (start_diff < 0) {
3153 return 0;
3154 } else {
3156 * Arbitrarily, if two processes started at the same
3157 * time, we'll say that the lower pointer value
3158 * started first. Note that t2 may have exited by now
3159 * so this may not be a valid pointer any longer, but
3160 * that's fine - it still serves to distinguish
3161 * between two tasks started (effectively) simultaneously.
3163 return t1 > t2;
3168 * This function is a callback from heap_insert() and is used to order
3169 * the heap.
3170 * In this case we order the heap in descending task start time.
3172 static inline int started_after(void *p1, void *p2)
3174 struct task_struct *t1 = p1;
3175 struct task_struct *t2 = p2;
3176 return started_after_time(t1, &t2->start_time, t2);
3180 * cgroup_scan_tasks - iterate though all the tasks in a cgroup
3181 * @scan: struct cgroup_scanner containing arguments for the scan
3183 * Arguments include pointers to callback functions test_task() and
3184 * process_task().
3185 * Iterate through all the tasks in a cgroup, calling test_task() for each,
3186 * and if it returns true, call process_task() for it also.
3187 * The test_task pointer may be NULL, meaning always true (select all tasks).
3188 * Effectively duplicates cgroup_iter_{start,next,end}()
3189 * but does not lock css_set_lock for the call to process_task().
3190 * The struct cgroup_scanner may be embedded in any structure of the caller's
3191 * creation.
3192 * It is guaranteed that process_task() will act on every task that
3193 * is a member of the cgroup for the duration of this call. This
3194 * function may or may not call process_task() for tasks that exit
3195 * or move to a different cgroup during the call, or are forked or
3196 * move into the cgroup during the call.
3198 * Note that test_task() may be called with locks held, and may in some
3199 * situations be called multiple times for the same task, so it should
3200 * be cheap.
3201 * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
3202 * pre-allocated and will be used for heap operations (and its "gt" member will
3203 * be overwritten), else a temporary heap will be used (allocation of which
3204 * may cause this function to fail).
3206 int cgroup_scan_tasks(struct cgroup_scanner *scan)
3208 int retval, i;
3209 struct cgroup_iter it;
3210 struct task_struct *p, *dropped;
3211 /* Never dereference latest_task, since it's not refcounted */
3212 struct task_struct *latest_task = NULL;
3213 struct ptr_heap tmp_heap;
3214 struct ptr_heap *heap;
3215 struct timespec latest_time = { 0, 0 };
3217 if (scan->heap) {
3218 /* The caller supplied our heap and pre-allocated its memory */
3219 heap = scan->heap;
3220 heap->gt = &started_after;
3221 } else {
3222 /* We need to allocate our own heap memory */
3223 heap = &tmp_heap;
3224 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3225 if (retval)
3226 /* cannot allocate the heap */
3227 return retval;
3230 again:
3232 * Scan tasks in the cgroup, using the scanner's "test_task" callback
3233 * to determine which are of interest, and using the scanner's
3234 * "process_task" callback to process any of them that need an update.
3235 * Since we don't want to hold any locks during the task updates,
3236 * gather tasks to be processed in a heap structure.
3237 * The heap is sorted by descending task start time.
3238 * If the statically-sized heap fills up, we overflow tasks that
3239 * started later, and in future iterations only consider tasks that
3240 * started after the latest task in the previous pass. This
3241 * guarantees forward progress and that we don't miss any tasks.
3243 heap->size = 0;
3244 cgroup_iter_start(scan->cg, &it);
3245 while ((p = cgroup_iter_next(scan->cg, &it))) {
3247 * Only affect tasks that qualify per the caller's callback,
3248 * if he provided one
3250 if (scan->test_task && !scan->test_task(p, scan))
3251 continue;
3253 * Only process tasks that started after the last task
3254 * we processed
3256 if (!started_after_time(p, &latest_time, latest_task))
3257 continue;
3258 dropped = heap_insert(heap, p);
3259 if (dropped == NULL) {
3261 * The new task was inserted; the heap wasn't
3262 * previously full
3264 get_task_struct(p);
3265 } else if (dropped != p) {
3267 * The new task was inserted, and pushed out a
3268 * different task
3270 get_task_struct(p);
3271 put_task_struct(dropped);
3274 * Else the new task was newer than anything already in
3275 * the heap and wasn't inserted
3278 cgroup_iter_end(scan->cg, &it);
3280 if (heap->size) {
3281 for (i = 0; i < heap->size; i++) {
3282 struct task_struct *q = heap->ptrs[i];
3283 if (i == 0) {
3284 latest_time = q->start_time;
3285 latest_task = q;
3287 /* Process the task per the caller's callback */
3288 scan->process_task(q, scan);
3289 put_task_struct(q);
3292 * If we had to process any tasks at all, scan again
3293 * in case some of them were in the middle of forking
3294 * children that didn't get processed.
3295 * Not the most efficient way to do it, but it avoids
3296 * having to take callback_mutex in the fork path
3298 goto again;
3300 if (heap == &tmp_heap)
3301 heap_free(&tmp_heap);
3302 return 0;
3306 * Stuff for reading the 'tasks'/'procs' files.
3308 * Reading this file can return large amounts of data if a cgroup has
3309 * *lots* of attached tasks. So it may need several calls to read(),
3310 * but we cannot guarantee that the information we produce is correct
3311 * unless we produce it entirely atomically.
3315 /* which pidlist file are we talking about? */
3316 enum cgroup_filetype {
3317 CGROUP_FILE_PROCS,
3318 CGROUP_FILE_TASKS,
3322 * A pidlist is a list of pids that virtually represents the contents of one
3323 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3324 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3325 * to the cgroup.
3327 struct cgroup_pidlist {
3329 * used to find which pidlist is wanted. doesn't change as long as
3330 * this particular list stays in the list.
3332 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3333 /* array of xids */
3334 pid_t *list;
3335 /* how many elements the above list has */
3336 int length;
3337 /* how many files are using the current array */
3338 int use_count;
3339 /* each of these stored in a list by its cgroup */
3340 struct list_head links;
3341 /* pointer to the cgroup we belong to, for list removal purposes */
3342 struct cgroup *owner;
3343 /* protects the other fields */
3344 struct rw_semaphore mutex;
3348 * The following two functions "fix" the issue where there are more pids
3349 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3350 * TODO: replace with a kernel-wide solution to this problem
3352 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3353 static void *pidlist_allocate(int count)
3355 if (PIDLIST_TOO_LARGE(count))
3356 return vmalloc(count * sizeof(pid_t));
3357 else
3358 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3360 static void pidlist_free(void *p)
3362 if (is_vmalloc_addr(p))
3363 vfree(p);
3364 else
3365 kfree(p);
3367 static void *pidlist_resize(void *p, int newcount)
3369 void *newlist;
3370 /* note: if new alloc fails, old p will still be valid either way */
3371 if (is_vmalloc_addr(p)) {
3372 newlist = vmalloc(newcount * sizeof(pid_t));
3373 if (!newlist)
3374 return NULL;
3375 memcpy(newlist, p, newcount * sizeof(pid_t));
3376 vfree(p);
3377 } else {
3378 newlist = krealloc(p, newcount * sizeof(pid_t), GFP_KERNEL);
3380 return newlist;
3384 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3385 * If the new stripped list is sufficiently smaller and there's enough memory
3386 * to allocate a new buffer, will let go of the unneeded memory. Returns the
3387 * number of unique elements.
3389 /* is the size difference enough that we should re-allocate the array? */
3390 #define PIDLIST_REALLOC_DIFFERENCE(old, new) ((old) - PAGE_SIZE >= (new))
3391 static int pidlist_uniq(pid_t **p, int length)
3393 int src, dest = 1;
3394 pid_t *list = *p;
3395 pid_t *newlist;
3398 * we presume the 0th element is unique, so i starts at 1. trivial
3399 * edge cases first; no work needs to be done for either
3401 if (length == 0 || length == 1)
3402 return length;
3403 /* src and dest walk down the list; dest counts unique elements */
3404 for (src = 1; src < length; src++) {
3405 /* find next unique element */
3406 while (list[src] == list[src-1]) {
3407 src++;
3408 if (src == length)
3409 goto after;
3411 /* dest always points to where the next unique element goes */
3412 list[dest] = list[src];
3413 dest++;
3415 after:
3417 * if the length difference is large enough, we want to allocate a
3418 * smaller buffer to save memory. if this fails due to out of memory,
3419 * we'll just stay with what we've got.
3421 if (PIDLIST_REALLOC_DIFFERENCE(length, dest)) {
3422 newlist = pidlist_resize(list, dest);
3423 if (newlist)
3424 *p = newlist;
3426 return dest;
3429 static int cmppid(const void *a, const void *b)
3431 return *(pid_t *)a - *(pid_t *)b;
3435 * find the appropriate pidlist for our purpose (given procs vs tasks)
3436 * returns with the lock on that pidlist already held, and takes care
3437 * of the use count, or returns NULL with no locks held if we're out of
3438 * memory.
3440 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3441 enum cgroup_filetype type)
3443 struct cgroup_pidlist *l;
3444 /* don't need task_nsproxy() if we're looking at ourself */
3445 struct pid_namespace *ns = task_active_pid_ns(current);
3448 * We can't drop the pidlist_mutex before taking the l->mutex in case
3449 * the last ref-holder is trying to remove l from the list at the same
3450 * time. Holding the pidlist_mutex precludes somebody taking whichever
3451 * list we find out from under us - compare release_pid_array().
3453 mutex_lock(&cgrp->pidlist_mutex);
3454 list_for_each_entry(l, &cgrp->pidlists, links) {
3455 if (l->key.type == type && l->key.ns == ns) {
3456 /* make sure l doesn't vanish out from under us */
3457 down_write(&l->mutex);
3458 mutex_unlock(&cgrp->pidlist_mutex);
3459 return l;
3462 /* entry not found; create a new one */
3463 l = kmalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3464 if (!l) {
3465 mutex_unlock(&cgrp->pidlist_mutex);
3466 return l;
3468 init_rwsem(&l->mutex);
3469 down_write(&l->mutex);
3470 l->key.type = type;
3471 l->key.ns = get_pid_ns(ns);
3472 l->use_count = 0; /* don't increment here */
3473 l->list = NULL;
3474 l->owner = cgrp;
3475 list_add(&l->links, &cgrp->pidlists);
3476 mutex_unlock(&cgrp->pidlist_mutex);
3477 return l;
3481 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3483 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3484 struct cgroup_pidlist **lp)
3486 pid_t *array;
3487 int length;
3488 int pid, n = 0; /* used for populating the array */
3489 struct cgroup_iter it;
3490 struct task_struct *tsk;
3491 struct cgroup_pidlist *l;
3494 * If cgroup gets more users after we read count, we won't have
3495 * enough space - tough. This race is indistinguishable to the
3496 * caller from the case that the additional cgroup users didn't
3497 * show up until sometime later on.
3499 length = cgroup_task_count(cgrp);
3500 array = pidlist_allocate(length);
3501 if (!array)
3502 return -ENOMEM;
3503 /* now, populate the array */
3504 cgroup_iter_start(cgrp, &it);
3505 while ((tsk = cgroup_iter_next(cgrp, &it))) {
3506 if (unlikely(n == length))
3507 break;
3508 /* get tgid or pid for procs or tasks file respectively */
3509 if (type == CGROUP_FILE_PROCS)
3510 pid = task_tgid_vnr(tsk);
3511 else
3512 pid = task_pid_vnr(tsk);
3513 if (pid > 0) /* make sure to only use valid results */
3514 array[n++] = pid;
3516 cgroup_iter_end(cgrp, &it);
3517 length = n;
3518 /* now sort & (if procs) strip out duplicates */
3519 sort(array, length, sizeof(pid_t), cmppid, NULL);
3520 if (type == CGROUP_FILE_PROCS)
3521 length = pidlist_uniq(&array, length);
3522 l = cgroup_pidlist_find(cgrp, type);
3523 if (!l) {
3524 pidlist_free(array);
3525 return -ENOMEM;
3527 /* store array, freeing old if necessary - lock already held */
3528 pidlist_free(l->list);
3529 l->list = array;
3530 l->length = length;
3531 l->use_count++;
3532 up_write(&l->mutex);
3533 *lp = l;
3534 return 0;
3538 * cgroupstats_build - build and fill cgroupstats
3539 * @stats: cgroupstats to fill information into
3540 * @dentry: A dentry entry belonging to the cgroup for which stats have
3541 * been requested.
3543 * Build and fill cgroupstats so that taskstats can export it to user
3544 * space.
3546 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3548 int ret = -EINVAL;
3549 struct cgroup *cgrp;
3550 struct cgroup_iter it;
3551 struct task_struct *tsk;
3554 * Validate dentry by checking the superblock operations,
3555 * and make sure it's a directory.
3557 if (dentry->d_sb->s_op != &cgroup_ops ||
3558 !S_ISDIR(dentry->d_inode->i_mode))
3559 goto err;
3561 ret = 0;
3562 cgrp = dentry->d_fsdata;
3564 cgroup_iter_start(cgrp, &it);
3565 while ((tsk = cgroup_iter_next(cgrp, &it))) {
3566 switch (tsk->state) {
3567 case TASK_RUNNING:
3568 stats->nr_running++;
3569 break;
3570 case TASK_INTERRUPTIBLE:
3571 stats->nr_sleeping++;
3572 break;
3573 case TASK_UNINTERRUPTIBLE:
3574 stats->nr_uninterruptible++;
3575 break;
3576 case TASK_STOPPED:
3577 stats->nr_stopped++;
3578 break;
3579 default:
3580 if (delayacct_is_task_waiting_on_io(tsk))
3581 stats->nr_io_wait++;
3582 break;
3585 cgroup_iter_end(cgrp, &it);
3587 err:
3588 return ret;
3593 * seq_file methods for the tasks/procs files. The seq_file position is the
3594 * next pid to display; the seq_file iterator is a pointer to the pid
3595 * in the cgroup->l->list array.
3598 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3601 * Initially we receive a position value that corresponds to
3602 * one more than the last pid shown (or 0 on the first call or
3603 * after a seek to the start). Use a binary-search to find the
3604 * next pid to display, if any
3606 struct cgroup_pidlist *l = s->private;
3607 int index = 0, pid = *pos;
3608 int *iter;
3610 down_read(&l->mutex);
3611 if (pid) {
3612 int end = l->length;
3614 while (index < end) {
3615 int mid = (index + end) / 2;
3616 if (l->list[mid] == pid) {
3617 index = mid;
3618 break;
3619 } else if (l->list[mid] <= pid)
3620 index = mid + 1;
3621 else
3622 end = mid;
3625 /* If we're off the end of the array, we're done */
3626 if (index >= l->length)
3627 return NULL;
3628 /* Update the abstract position to be the actual pid that we found */
3629 iter = l->list + index;
3630 *pos = *iter;
3631 return iter;
3634 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3636 struct cgroup_pidlist *l = s->private;
3637 up_read(&l->mutex);
3640 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3642 struct cgroup_pidlist *l = s->private;
3643 pid_t *p = v;
3644 pid_t *end = l->list + l->length;
3646 * Advance to the next pid in the array. If this goes off the
3647 * end, we're done
3649 p++;
3650 if (p >= end) {
3651 return NULL;
3652 } else {
3653 *pos = *p;
3654 return p;
3658 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3660 return seq_printf(s, "%d\n", *(int *)v);
3664 * seq_operations functions for iterating on pidlists through seq_file -
3665 * independent of whether it's tasks or procs
3667 static const struct seq_operations cgroup_pidlist_seq_operations = {
3668 .start = cgroup_pidlist_start,
3669 .stop = cgroup_pidlist_stop,
3670 .next = cgroup_pidlist_next,
3671 .show = cgroup_pidlist_show,
3674 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
3677 * the case where we're the last user of this particular pidlist will
3678 * have us remove it from the cgroup's list, which entails taking the
3679 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3680 * pidlist_mutex, we have to take pidlist_mutex first.
3682 mutex_lock(&l->owner->pidlist_mutex);
3683 down_write(&l->mutex);
3684 BUG_ON(!l->use_count);
3685 if (!--l->use_count) {
3686 /* we're the last user if refcount is 0; remove and free */
3687 list_del(&l->links);
3688 mutex_unlock(&l->owner->pidlist_mutex);
3689 pidlist_free(l->list);
3690 put_pid_ns(l->key.ns);
3691 up_write(&l->mutex);
3692 kfree(l);
3693 return;
3695 mutex_unlock(&l->owner->pidlist_mutex);
3696 up_write(&l->mutex);
3699 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
3701 struct cgroup_pidlist *l;
3702 if (!(file->f_mode & FMODE_READ))
3703 return 0;
3705 * the seq_file will only be initialized if the file was opened for
3706 * reading; hence we check if it's not null only in that case.
3708 l = ((struct seq_file *)file->private_data)->private;
3709 cgroup_release_pid_array(l);
3710 return seq_release(inode, file);
3713 static const struct file_operations cgroup_pidlist_operations = {
3714 .read = seq_read,
3715 .llseek = seq_lseek,
3716 .write = cgroup_file_write,
3717 .release = cgroup_pidlist_release,
3721 * The following functions handle opens on a file that displays a pidlist
3722 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3723 * in the cgroup.
3725 /* helper function for the two below it */
3726 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
3728 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
3729 struct cgroup_pidlist *l;
3730 int retval;
3732 /* Nothing to do for write-only files */
3733 if (!(file->f_mode & FMODE_READ))
3734 return 0;
3736 /* have the array populated */
3737 retval = pidlist_array_load(cgrp, type, &l);
3738 if (retval)
3739 return retval;
3740 /* configure file information */
3741 file->f_op = &cgroup_pidlist_operations;
3743 retval = seq_open(file, &cgroup_pidlist_seq_operations);
3744 if (retval) {
3745 cgroup_release_pid_array(l);
3746 return retval;
3748 ((struct seq_file *)file->private_data)->private = l;
3749 return 0;
3751 static int cgroup_tasks_open(struct inode *unused, struct file *file)
3753 return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
3755 static int cgroup_procs_open(struct inode *unused, struct file *file)
3757 return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
3760 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
3761 struct cftype *cft)
3763 return notify_on_release(cgrp);
3766 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
3767 struct cftype *cft,
3768 u64 val)
3770 clear_bit(CGRP_RELEASABLE, &cgrp->flags);
3771 if (val)
3772 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3773 else
3774 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3775 return 0;
3779 * Unregister event and free resources.
3781 * Gets called from workqueue.
3783 static void cgroup_event_remove(struct work_struct *work)
3785 struct cgroup_event *event = container_of(work, struct cgroup_event,
3786 remove);
3787 struct cgroup *cgrp = event->cgrp;
3789 remove_wait_queue(event->wqh, &event->wait);
3791 event->cft->unregister_event(cgrp, event->cft, event->eventfd);
3793 /* Notify userspace the event is going away. */
3794 eventfd_signal(event->eventfd, 1);
3796 eventfd_ctx_put(event->eventfd);
3797 kfree(event);
3798 dput(cgrp->dentry);
3802 * Gets called on POLLHUP on eventfd when user closes it.
3804 * Called with wqh->lock held and interrupts disabled.
3806 static int cgroup_event_wake(wait_queue_t *wait, unsigned mode,
3807 int sync, void *key)
3809 struct cgroup_event *event = container_of(wait,
3810 struct cgroup_event, wait);
3811 struct cgroup *cgrp = event->cgrp;
3812 unsigned long flags = (unsigned long)key;
3814 if (flags & POLLHUP) {
3816 * If the event has been detached at cgroup removal, we
3817 * can simply return knowing the other side will cleanup
3818 * for us.
3820 * We can't race against event freeing since the other
3821 * side will require wqh->lock via remove_wait_queue(),
3822 * which we hold.
3824 spin_lock(&cgrp->event_list_lock);
3825 if (!list_empty(&event->list)) {
3826 list_del_init(&event->list);
3828 * We are in atomic context, but cgroup_event_remove()
3829 * may sleep, so we have to call it in workqueue.
3831 schedule_work(&event->remove);
3833 spin_unlock(&cgrp->event_list_lock);
3836 return 0;
3839 static void cgroup_event_ptable_queue_proc(struct file *file,
3840 wait_queue_head_t *wqh, poll_table *pt)
3842 struct cgroup_event *event = container_of(pt,
3843 struct cgroup_event, pt);
3845 event->wqh = wqh;
3846 add_wait_queue(wqh, &event->wait);
3850 * Parse input and register new cgroup event handler.
3852 * Input must be in format '<event_fd> <control_fd> <args>'.
3853 * Interpretation of args is defined by control file implementation.
3855 static int cgroup_write_event_control(struct cgroup *cgrp, struct cftype *cft,
3856 const char *buffer)
3858 struct cgroup_event *event = NULL;
3859 struct cgroup *cgrp_cfile;
3860 unsigned int efd, cfd;
3861 struct file *efile = NULL;
3862 struct file *cfile = NULL;
3863 char *endp;
3864 int ret;
3866 efd = simple_strtoul(buffer, &endp, 10);
3867 if (*endp != ' ')
3868 return -EINVAL;
3869 buffer = endp + 1;
3871 cfd = simple_strtoul(buffer, &endp, 10);
3872 if ((*endp != ' ') && (*endp != '\0'))
3873 return -EINVAL;
3874 buffer = endp + 1;
3876 event = kzalloc(sizeof(*event), GFP_KERNEL);
3877 if (!event)
3878 return -ENOMEM;
3879 event->cgrp = cgrp;
3880 INIT_LIST_HEAD(&event->list);
3881 init_poll_funcptr(&event->pt, cgroup_event_ptable_queue_proc);
3882 init_waitqueue_func_entry(&event->wait, cgroup_event_wake);
3883 INIT_WORK(&event->remove, cgroup_event_remove);
3885 efile = eventfd_fget(efd);
3886 if (IS_ERR(efile)) {
3887 ret = PTR_ERR(efile);
3888 goto fail;
3891 event->eventfd = eventfd_ctx_fileget(efile);
3892 if (IS_ERR(event->eventfd)) {
3893 ret = PTR_ERR(event->eventfd);
3894 goto fail;
3897 cfile = fget(cfd);
3898 if (!cfile) {
3899 ret = -EBADF;
3900 goto fail;
3903 /* the process need read permission on control file */
3904 /* AV: shouldn't we check that it's been opened for read instead? */
3905 ret = inode_permission(file_inode(cfile), MAY_READ);
3906 if (ret < 0)
3907 goto fail;
3909 event->cft = __file_cft(cfile);
3910 if (IS_ERR(event->cft)) {
3911 ret = PTR_ERR(event->cft);
3912 goto fail;
3916 * The file to be monitored must be in the same cgroup as
3917 * cgroup.event_control is.
3919 cgrp_cfile = __d_cgrp(cfile->f_dentry->d_parent);
3920 if (cgrp_cfile != cgrp) {
3921 ret = -EINVAL;
3922 goto fail;
3925 if (!event->cft->register_event || !event->cft->unregister_event) {
3926 ret = -EINVAL;
3927 goto fail;
3930 ret = event->cft->register_event(cgrp, event->cft,
3931 event->eventfd, buffer);
3932 if (ret)
3933 goto fail;
3935 if (efile->f_op->poll(efile, &event->pt) & POLLHUP) {
3936 event->cft->unregister_event(cgrp, event->cft, event->eventfd);
3937 ret = 0;
3938 goto fail;
3942 * Events should be removed after rmdir of cgroup directory, but before
3943 * destroying subsystem state objects. Let's take reference to cgroup
3944 * directory dentry to do that.
3946 dget(cgrp->dentry);
3948 spin_lock(&cgrp->event_list_lock);
3949 list_add(&event->list, &cgrp->event_list);
3950 spin_unlock(&cgrp->event_list_lock);
3952 fput(cfile);
3953 fput(efile);
3955 return 0;
3957 fail:
3958 if (cfile)
3959 fput(cfile);
3961 if (event && event->eventfd && !IS_ERR(event->eventfd))
3962 eventfd_ctx_put(event->eventfd);
3964 if (!IS_ERR_OR_NULL(efile))
3965 fput(efile);
3967 kfree(event);
3969 return ret;
3972 static u64 cgroup_clone_children_read(struct cgroup *cgrp,
3973 struct cftype *cft)
3975 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3978 static int cgroup_clone_children_write(struct cgroup *cgrp,
3979 struct cftype *cft,
3980 u64 val)
3982 if (val)
3983 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3984 else
3985 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3986 return 0;
3990 * for the common functions, 'private' gives the type of file
3992 /* for hysterical raisins, we can't put this on the older files */
3993 #define CGROUP_FILE_GENERIC_PREFIX "cgroup."
3994 static struct cftype files[] = {
3996 .name = "tasks",
3997 .open = cgroup_tasks_open,
3998 .write_u64 = cgroup_tasks_write,
3999 .release = cgroup_pidlist_release,
4000 .mode = S_IRUGO | S_IWUSR,
4003 .name = CGROUP_FILE_GENERIC_PREFIX "procs",
4004 .open = cgroup_procs_open,
4005 .write_u64 = cgroup_procs_write,
4006 .release = cgroup_pidlist_release,
4007 .mode = S_IRUGO | S_IWUSR,
4010 .name = "notify_on_release",
4011 .read_u64 = cgroup_read_notify_on_release,
4012 .write_u64 = cgroup_write_notify_on_release,
4015 .name = CGROUP_FILE_GENERIC_PREFIX "event_control",
4016 .write_string = cgroup_write_event_control,
4017 .mode = S_IWUGO,
4020 .name = "cgroup.clone_children",
4021 .read_u64 = cgroup_clone_children_read,
4022 .write_u64 = cgroup_clone_children_write,
4025 .name = "release_agent",
4026 .flags = CFTYPE_ONLY_ON_ROOT,
4027 .read_seq_string = cgroup_release_agent_show,
4028 .write_string = cgroup_release_agent_write,
4029 .max_write_len = PATH_MAX,
4031 { } /* terminate */
4035 * cgroup_populate_dir - selectively creation of files in a directory
4036 * @cgrp: target cgroup
4037 * @base_files: true if the base files should be added
4038 * @subsys_mask: mask of the subsystem ids whose files should be added
4040 static int cgroup_populate_dir(struct cgroup *cgrp, bool base_files,
4041 unsigned long subsys_mask)
4043 int err;
4044 struct cgroup_subsys *ss;
4046 if (base_files) {
4047 err = cgroup_addrm_files(cgrp, NULL, files, true);
4048 if (err < 0)
4049 return err;
4052 /* process cftsets of each subsystem */
4053 for_each_subsys(cgrp->root, ss) {
4054 struct cftype_set *set;
4055 if (!test_bit(ss->subsys_id, &subsys_mask))
4056 continue;
4058 list_for_each_entry(set, &ss->cftsets, node)
4059 cgroup_addrm_files(cgrp, ss, set->cfts, true);
4062 /* This cgroup is ready now */
4063 for_each_subsys(cgrp->root, ss) {
4064 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4066 * Update id->css pointer and make this css visible from
4067 * CSS ID functions. This pointer will be dereferened
4068 * from RCU-read-side without locks.
4070 if (css->id)
4071 rcu_assign_pointer(css->id->css, css);
4074 return 0;
4077 static void css_dput_fn(struct work_struct *work)
4079 struct cgroup_subsys_state *css =
4080 container_of(work, struct cgroup_subsys_state, dput_work);
4081 struct dentry *dentry = css->cgroup->dentry;
4082 struct super_block *sb = dentry->d_sb;
4084 atomic_inc(&sb->s_active);
4085 dput(dentry);
4086 deactivate_super(sb);
4089 static void init_cgroup_css(struct cgroup_subsys_state *css,
4090 struct cgroup_subsys *ss,
4091 struct cgroup *cgrp)
4093 css->cgroup = cgrp;
4094 atomic_set(&css->refcnt, 1);
4095 css->flags = 0;
4096 css->id = NULL;
4097 if (cgrp == dummytop)
4098 css->flags |= CSS_ROOT;
4099 BUG_ON(cgrp->subsys[ss->subsys_id]);
4100 cgrp->subsys[ss->subsys_id] = css;
4103 * css holds an extra ref to @cgrp->dentry which is put on the last
4104 * css_put(). dput() requires process context, which css_put() may
4105 * be called without. @css->dput_work will be used to invoke
4106 * dput() asynchronously from css_put().
4108 INIT_WORK(&css->dput_work, css_dput_fn);
4111 /* invoke ->post_create() on a new CSS and mark it online if successful */
4112 static int online_css(struct cgroup_subsys *ss, struct cgroup *cgrp)
4114 int ret = 0;
4116 lockdep_assert_held(&cgroup_mutex);
4118 if (ss->css_online)
4119 ret = ss->css_online(cgrp);
4120 if (!ret)
4121 cgrp->subsys[ss->subsys_id]->flags |= CSS_ONLINE;
4122 return ret;
4125 /* if the CSS is online, invoke ->pre_destory() on it and mark it offline */
4126 static void offline_css(struct cgroup_subsys *ss, struct cgroup *cgrp)
4127 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4129 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4131 lockdep_assert_held(&cgroup_mutex);
4133 if (!(css->flags & CSS_ONLINE))
4134 return;
4137 * css_offline() should be called with cgroup_mutex unlocked. See
4138 * 3fa59dfbc3 ("cgroup: fix potential deadlock in pre_destroy") for
4139 * details. This temporary unlocking should go away once
4140 * cgroup_mutex is unexported from controllers.
4142 if (ss->css_offline) {
4143 mutex_unlock(&cgroup_mutex);
4144 ss->css_offline(cgrp);
4145 mutex_lock(&cgroup_mutex);
4148 cgrp->subsys[ss->subsys_id]->flags &= ~CSS_ONLINE;
4152 * cgroup_create - create a cgroup
4153 * @parent: cgroup that will be parent of the new cgroup
4154 * @dentry: dentry of the new cgroup
4155 * @mode: mode to set on new inode
4157 * Must be called with the mutex on the parent inode held
4159 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4160 umode_t mode)
4162 struct cgroup *cgrp;
4163 struct cgroupfs_root *root = parent->root;
4164 int err = 0;
4165 struct cgroup_subsys *ss;
4166 struct super_block *sb = root->sb;
4168 /* allocate the cgroup and its ID, 0 is reserved for the root */
4169 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4170 if (!cgrp)
4171 return -ENOMEM;
4173 cgrp->id = ida_simple_get(&root->cgroup_ida, 1, 0, GFP_KERNEL);
4174 if (cgrp->id < 0)
4175 goto err_free_cgrp;
4178 * Only live parents can have children. Note that the liveliness
4179 * check isn't strictly necessary because cgroup_mkdir() and
4180 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4181 * anyway so that locking is contained inside cgroup proper and we
4182 * don't get nasty surprises if we ever grow another caller.
4184 if (!cgroup_lock_live_group(parent)) {
4185 err = -ENODEV;
4186 goto err_free_id;
4189 /* Grab a reference on the superblock so the hierarchy doesn't
4190 * get deleted on unmount if there are child cgroups. This
4191 * can be done outside cgroup_mutex, since the sb can't
4192 * disappear while someone has an open control file on the
4193 * fs */
4194 atomic_inc(&sb->s_active);
4196 init_cgroup_housekeeping(cgrp);
4198 dentry->d_fsdata = cgrp;
4199 cgrp->dentry = dentry;
4201 cgrp->parent = parent;
4202 cgrp->root = parent->root;
4203 cgrp->top_cgroup = parent->top_cgroup;
4205 if (notify_on_release(parent))
4206 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4208 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4209 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4211 for_each_subsys(root, ss) {
4212 struct cgroup_subsys_state *css;
4214 css = ss->css_alloc(cgrp);
4215 if (IS_ERR(css)) {
4216 err = PTR_ERR(css);
4217 goto err_free_all;
4219 init_cgroup_css(css, ss, cgrp);
4220 if (ss->use_id) {
4221 err = alloc_css_id(ss, parent, cgrp);
4222 if (err)
4223 goto err_free_all;
4228 * Create directory. cgroup_create_file() returns with the new
4229 * directory locked on success so that it can be populated without
4230 * dropping cgroup_mutex.
4232 err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4233 if (err < 0)
4234 goto err_free_all;
4235 lockdep_assert_held(&dentry->d_inode->i_mutex);
4237 /* allocation complete, commit to creation */
4238 list_add_tail(&cgrp->allcg_node, &root->allcg_list);
4239 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4240 root->number_of_cgroups++;
4242 /* each css holds a ref to the cgroup's dentry */
4243 for_each_subsys(root, ss)
4244 dget(dentry);
4246 /* creation succeeded, notify subsystems */
4247 for_each_subsys(root, ss) {
4248 err = online_css(ss, cgrp);
4249 if (err)
4250 goto err_destroy;
4252 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4253 parent->parent) {
4254 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",
4255 current->comm, current->pid, ss->name);
4256 if (!strcmp(ss->name, "memory"))
4257 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4258 ss->warned_broken_hierarchy = true;
4262 err = cgroup_populate_dir(cgrp, true, root->subsys_mask);
4263 if (err)
4264 goto err_destroy;
4266 mutex_unlock(&cgroup_mutex);
4267 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4269 return 0;
4271 err_free_all:
4272 for_each_subsys(root, ss) {
4273 if (cgrp->subsys[ss->subsys_id])
4274 ss->css_free(cgrp);
4276 mutex_unlock(&cgroup_mutex);
4277 /* Release the reference count that we took on the superblock */
4278 deactivate_super(sb);
4279 err_free_id:
4280 ida_simple_remove(&root->cgroup_ida, cgrp->id);
4281 err_free_cgrp:
4282 kfree(cgrp);
4283 return err;
4285 err_destroy:
4286 cgroup_destroy_locked(cgrp);
4287 mutex_unlock(&cgroup_mutex);
4288 mutex_unlock(&dentry->d_inode->i_mutex);
4289 return err;
4292 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4294 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4296 /* the vfs holds inode->i_mutex already */
4297 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4301 * Check the reference count on each subsystem. Since we already
4302 * established that there are no tasks in the cgroup, if the css refcount
4303 * is also 1, then there should be no outstanding references, so the
4304 * subsystem is safe to destroy. We scan across all subsystems rather than
4305 * using the per-hierarchy linked list of mounted subsystems since we can
4306 * be called via check_for_release() with no synchronization other than
4307 * RCU, and the subsystem linked list isn't RCU-safe.
4309 static int cgroup_has_css_refs(struct cgroup *cgrp)
4311 int i;
4314 * We won't need to lock the subsys array, because the subsystems
4315 * we're concerned about aren't going anywhere since our cgroup root
4316 * has a reference on them.
4318 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4319 struct cgroup_subsys *ss = subsys[i];
4320 struct cgroup_subsys_state *css;
4322 /* Skip subsystems not present or not in this hierarchy */
4323 if (ss == NULL || ss->root != cgrp->root)
4324 continue;
4326 css = cgrp->subsys[ss->subsys_id];
4328 * When called from check_for_release() it's possible
4329 * that by this point the cgroup has been removed
4330 * and the css deleted. But a false-positive doesn't
4331 * matter, since it can only happen if the cgroup
4332 * has been deleted and hence no longer needs the
4333 * release agent to be called anyway.
4335 if (css && css_refcnt(css) > 1)
4336 return 1;
4338 return 0;
4341 static int cgroup_destroy_locked(struct cgroup *cgrp)
4342 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4344 struct dentry *d = cgrp->dentry;
4345 struct cgroup *parent = cgrp->parent;
4346 DEFINE_WAIT(wait);
4347 struct cgroup_event *event, *tmp;
4348 struct cgroup_subsys *ss;
4349 LIST_HEAD(tmp_list);
4351 lockdep_assert_held(&d->d_inode->i_mutex);
4352 lockdep_assert_held(&cgroup_mutex);
4354 if (atomic_read(&cgrp->count) || !list_empty(&cgrp->children))
4355 return -EBUSY;
4358 * Block new css_tryget() by deactivating refcnt and mark @cgrp
4359 * removed. This makes future css_tryget() and child creation
4360 * attempts fail thus maintaining the removal conditions verified
4361 * above.
4363 for_each_subsys(cgrp->root, ss) {
4364 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4366 WARN_ON(atomic_read(&css->refcnt) < 0);
4367 atomic_add(CSS_DEACT_BIAS, &css->refcnt);
4369 set_bit(CGRP_REMOVED, &cgrp->flags);
4371 /* tell subsystems to initate destruction */
4372 for_each_subsys(cgrp->root, ss)
4373 offline_css(ss, cgrp);
4376 * Put all the base refs. Each css holds an extra reference to the
4377 * cgroup's dentry and cgroup removal proceeds regardless of css
4378 * refs. On the last put of each css, whenever that may be, the
4379 * extra dentry ref is put so that dentry destruction happens only
4380 * after all css's are released.
4382 for_each_subsys(cgrp->root, ss)
4383 css_put(cgrp->subsys[ss->subsys_id]);
4385 raw_spin_lock(&release_list_lock);
4386 if (!list_empty(&cgrp->release_list))
4387 list_del_init(&cgrp->release_list);
4388 raw_spin_unlock(&release_list_lock);
4390 /* delete this cgroup from parent->children */
4391 list_del_rcu(&cgrp->sibling);
4392 list_del_init(&cgrp->allcg_node);
4394 dget(d);
4395 cgroup_d_remove_dir(d);
4396 dput(d);
4398 set_bit(CGRP_RELEASABLE, &parent->flags);
4399 check_for_release(parent);
4402 * Unregister events and notify userspace.
4403 * Notify userspace about cgroup removing only after rmdir of cgroup
4404 * directory to avoid race between userspace and kernelspace.
4406 spin_lock(&cgrp->event_list_lock);
4407 list_for_each_entry_safe(event, tmp, &cgrp->event_list, list) {
4408 list_del_init(&event->list);
4409 schedule_work(&event->remove);
4411 spin_unlock(&cgrp->event_list_lock);
4413 return 0;
4416 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4418 int ret;
4420 mutex_lock(&cgroup_mutex);
4421 ret = cgroup_destroy_locked(dentry->d_fsdata);
4422 mutex_unlock(&cgroup_mutex);
4424 return ret;
4427 static void __init_or_module cgroup_init_cftsets(struct cgroup_subsys *ss)
4429 INIT_LIST_HEAD(&ss->cftsets);
4432 * base_cftset is embedded in subsys itself, no need to worry about
4433 * deregistration.
4435 if (ss->base_cftypes) {
4436 ss->base_cftset.cfts = ss->base_cftypes;
4437 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4441 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4443 struct cgroup_subsys_state *css;
4445 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4447 mutex_lock(&cgroup_mutex);
4449 /* init base cftset */
4450 cgroup_init_cftsets(ss);
4452 /* Create the top cgroup state for this subsystem */
4453 list_add(&ss->sibling, &rootnode.subsys_list);
4454 ss->root = &rootnode;
4455 css = ss->css_alloc(dummytop);
4456 /* We don't handle early failures gracefully */
4457 BUG_ON(IS_ERR(css));
4458 init_cgroup_css(css, ss, dummytop);
4460 /* Update the init_css_set to contain a subsys
4461 * pointer to this state - since the subsystem is
4462 * newly registered, all tasks and hence the
4463 * init_css_set is in the subsystem's top cgroup. */
4464 init_css_set.subsys[ss->subsys_id] = css;
4466 need_forkexit_callback |= ss->fork || ss->exit;
4468 /* At system boot, before all subsystems have been
4469 * registered, no tasks have been forked, so we don't
4470 * need to invoke fork callbacks here. */
4471 BUG_ON(!list_empty(&init_task.tasks));
4473 ss->active = 1;
4474 BUG_ON(online_css(ss, dummytop));
4476 mutex_unlock(&cgroup_mutex);
4478 /* this function shouldn't be used with modular subsystems, since they
4479 * need to register a subsys_id, among other things */
4480 BUG_ON(ss->module);
4484 * cgroup_load_subsys: load and register a modular subsystem at runtime
4485 * @ss: the subsystem to load
4487 * This function should be called in a modular subsystem's initcall. If the
4488 * subsystem is built as a module, it will be assigned a new subsys_id and set
4489 * up for use. If the subsystem is built-in anyway, work is delegated to the
4490 * simpler cgroup_init_subsys.
4492 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
4494 struct cgroup_subsys_state *css;
4495 int i, ret;
4496 struct hlist_node *node, *tmp;
4497 struct css_set *cg;
4498 unsigned long key;
4500 /* check name and function validity */
4501 if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
4502 ss->css_alloc == NULL || ss->css_free == NULL)
4503 return -EINVAL;
4506 * we don't support callbacks in modular subsystems. this check is
4507 * before the ss->module check for consistency; a subsystem that could
4508 * be a module should still have no callbacks even if the user isn't
4509 * compiling it as one.
4511 if (ss->fork || ss->exit)
4512 return -EINVAL;
4515 * an optionally modular subsystem is built-in: we want to do nothing,
4516 * since cgroup_init_subsys will have already taken care of it.
4518 if (ss->module == NULL) {
4519 /* a sanity check */
4520 BUG_ON(subsys[ss->subsys_id] != ss);
4521 return 0;
4524 /* init base cftset */
4525 cgroup_init_cftsets(ss);
4527 mutex_lock(&cgroup_mutex);
4528 subsys[ss->subsys_id] = ss;
4531 * no ss->css_alloc seems to need anything important in the ss
4532 * struct, so this can happen first (i.e. before the rootnode
4533 * attachment).
4535 css = ss->css_alloc(dummytop);
4536 if (IS_ERR(css)) {
4537 /* failure case - need to deassign the subsys[] slot. */
4538 subsys[ss->subsys_id] = NULL;
4539 mutex_unlock(&cgroup_mutex);
4540 return PTR_ERR(css);
4543 list_add(&ss->sibling, &rootnode.subsys_list);
4544 ss->root = &rootnode;
4546 /* our new subsystem will be attached to the dummy hierarchy. */
4547 init_cgroup_css(css, ss, dummytop);
4548 /* init_idr must be after init_cgroup_css because it sets css->id. */
4549 if (ss->use_id) {
4550 ret = cgroup_init_idr(ss, css);
4551 if (ret)
4552 goto err_unload;
4556 * Now we need to entangle the css into the existing css_sets. unlike
4557 * in cgroup_init_subsys, there are now multiple css_sets, so each one
4558 * will need a new pointer to it; done by iterating the css_set_table.
4559 * furthermore, modifying the existing css_sets will corrupt the hash
4560 * table state, so each changed css_set will need its hash recomputed.
4561 * this is all done under the css_set_lock.
4563 write_lock(&css_set_lock);
4564 hash_for_each_safe(css_set_table, i, node, tmp, cg, hlist) {
4565 /* skip entries that we already rehashed */
4566 if (cg->subsys[ss->subsys_id])
4567 continue;
4568 /* remove existing entry */
4569 hash_del(&cg->hlist);
4570 /* set new value */
4571 cg->subsys[ss->subsys_id] = css;
4572 /* recompute hash and restore entry */
4573 key = css_set_hash(cg->subsys);
4574 hash_add(css_set_table, node, key);
4576 write_unlock(&css_set_lock);
4578 ss->active = 1;
4579 ret = online_css(ss, dummytop);
4580 if (ret)
4581 goto err_unload;
4583 /* success! */
4584 mutex_unlock(&cgroup_mutex);
4585 return 0;
4587 err_unload:
4588 mutex_unlock(&cgroup_mutex);
4589 /* @ss can't be mounted here as try_module_get() would fail */
4590 cgroup_unload_subsys(ss);
4591 return ret;
4593 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
4596 * cgroup_unload_subsys: unload a modular subsystem
4597 * @ss: the subsystem to unload
4599 * This function should be called in a modular subsystem's exitcall. When this
4600 * function is invoked, the refcount on the subsystem's module will be 0, so
4601 * the subsystem will not be attached to any hierarchy.
4603 void cgroup_unload_subsys(struct cgroup_subsys *ss)
4605 struct cg_cgroup_link *link;
4607 BUG_ON(ss->module == NULL);
4610 * we shouldn't be called if the subsystem is in use, and the use of
4611 * try_module_get in parse_cgroupfs_options should ensure that it
4612 * doesn't start being used while we're killing it off.
4614 BUG_ON(ss->root != &rootnode);
4616 mutex_lock(&cgroup_mutex);
4618 offline_css(ss, dummytop);
4619 ss->active = 0;
4621 if (ss->use_id)
4622 idr_destroy(&ss->idr);
4624 /* deassign the subsys_id */
4625 subsys[ss->subsys_id] = NULL;
4627 /* remove subsystem from rootnode's list of subsystems */
4628 list_del_init(&ss->sibling);
4631 * disentangle the css from all css_sets attached to the dummytop. as
4632 * in loading, we need to pay our respects to the hashtable gods.
4634 write_lock(&css_set_lock);
4635 list_for_each_entry(link, &dummytop->css_sets, cgrp_link_list) {
4636 struct css_set *cg = link->cg;
4637 unsigned long key;
4639 hash_del(&cg->hlist);
4640 cg->subsys[ss->subsys_id] = NULL;
4641 key = css_set_hash(cg->subsys);
4642 hash_add(css_set_table, &cg->hlist, key);
4644 write_unlock(&css_set_lock);
4647 * remove subsystem's css from the dummytop and free it - need to
4648 * free before marking as null because ss->css_free needs the
4649 * cgrp->subsys pointer to find their state. note that this also
4650 * takes care of freeing the css_id.
4652 ss->css_free(dummytop);
4653 dummytop->subsys[ss->subsys_id] = NULL;
4655 mutex_unlock(&cgroup_mutex);
4657 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
4660 * cgroup_init_early - cgroup initialization at system boot
4662 * Initialize cgroups at system boot, and initialize any
4663 * subsystems that request early init.
4665 int __init cgroup_init_early(void)
4667 int i;
4668 atomic_set(&init_css_set.refcount, 1);
4669 INIT_LIST_HEAD(&init_css_set.cg_links);
4670 INIT_LIST_HEAD(&init_css_set.tasks);
4671 INIT_HLIST_NODE(&init_css_set.hlist);
4672 css_set_count = 1;
4673 init_cgroup_root(&rootnode);
4674 root_count = 1;
4675 init_task.cgroups = &init_css_set;
4677 init_css_set_link.cg = &init_css_set;
4678 init_css_set_link.cgrp = dummytop;
4679 list_add(&init_css_set_link.cgrp_link_list,
4680 &rootnode.top_cgroup.css_sets);
4681 list_add(&init_css_set_link.cg_link_list,
4682 &init_css_set.cg_links);
4684 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4685 struct cgroup_subsys *ss = subsys[i];
4687 /* at bootup time, we don't worry about modular subsystems */
4688 if (!ss || ss->module)
4689 continue;
4691 BUG_ON(!ss->name);
4692 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
4693 BUG_ON(!ss->css_alloc);
4694 BUG_ON(!ss->css_free);
4695 if (ss->subsys_id != i) {
4696 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
4697 ss->name, ss->subsys_id);
4698 BUG();
4701 if (ss->early_init)
4702 cgroup_init_subsys(ss);
4704 return 0;
4708 * cgroup_init - cgroup initialization
4710 * Register cgroup filesystem and /proc file, and initialize
4711 * any subsystems that didn't request early init.
4713 int __init cgroup_init(void)
4715 int err;
4716 int i;
4717 unsigned long key;
4719 err = bdi_init(&cgroup_backing_dev_info);
4720 if (err)
4721 return err;
4723 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4724 struct cgroup_subsys *ss = subsys[i];
4726 /* at bootup time, we don't worry about modular subsystems */
4727 if (!ss || ss->module)
4728 continue;
4729 if (!ss->early_init)
4730 cgroup_init_subsys(ss);
4731 if (ss->use_id)
4732 cgroup_init_idr(ss, init_css_set.subsys[ss->subsys_id]);
4735 /* Add init_css_set to the hash table */
4736 key = css_set_hash(init_css_set.subsys);
4737 hash_add(css_set_table, &init_css_set.hlist, key);
4738 BUG_ON(!init_root_id(&rootnode));
4740 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4741 if (!cgroup_kobj) {
4742 err = -ENOMEM;
4743 goto out;
4746 err = register_filesystem(&cgroup_fs_type);
4747 if (err < 0) {
4748 kobject_put(cgroup_kobj);
4749 goto out;
4752 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4754 out:
4755 if (err)
4756 bdi_destroy(&cgroup_backing_dev_info);
4758 return err;
4762 * proc_cgroup_show()
4763 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4764 * - Used for /proc/<pid>/cgroup.
4765 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4766 * doesn't really matter if tsk->cgroup changes after we read it,
4767 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4768 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4769 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4770 * cgroup to top_cgroup.
4773 /* TODO: Use a proper seq_file iterator */
4774 static int proc_cgroup_show(struct seq_file *m, void *v)
4776 struct pid *pid;
4777 struct task_struct *tsk;
4778 char *buf;
4779 int retval;
4780 struct cgroupfs_root *root;
4782 retval = -ENOMEM;
4783 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4784 if (!buf)
4785 goto out;
4787 retval = -ESRCH;
4788 pid = m->private;
4789 tsk = get_pid_task(pid, PIDTYPE_PID);
4790 if (!tsk)
4791 goto out_free;
4793 retval = 0;
4795 mutex_lock(&cgroup_mutex);
4797 for_each_active_root(root) {
4798 struct cgroup_subsys *ss;
4799 struct cgroup *cgrp;
4800 int count = 0;
4802 seq_printf(m, "%d:", root->hierarchy_id);
4803 for_each_subsys(root, ss)
4804 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4805 if (strlen(root->name))
4806 seq_printf(m, "%sname=%s", count ? "," : "",
4807 root->name);
4808 seq_putc(m, ':');
4809 cgrp = task_cgroup_from_root(tsk, root);
4810 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
4811 if (retval < 0)
4812 goto out_unlock;
4813 seq_puts(m, buf);
4814 seq_putc(m, '\n');
4817 out_unlock:
4818 mutex_unlock(&cgroup_mutex);
4819 put_task_struct(tsk);
4820 out_free:
4821 kfree(buf);
4822 out:
4823 return retval;
4826 static int cgroup_open(struct inode *inode, struct file *file)
4828 struct pid *pid = PROC_I(inode)->pid;
4829 return single_open(file, proc_cgroup_show, pid);
4832 const struct file_operations proc_cgroup_operations = {
4833 .open = cgroup_open,
4834 .read = seq_read,
4835 .llseek = seq_lseek,
4836 .release = single_release,
4839 /* Display information about each subsystem and each hierarchy */
4840 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4842 int i;
4844 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4846 * ideally we don't want subsystems moving around while we do this.
4847 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4848 * subsys/hierarchy state.
4850 mutex_lock(&cgroup_mutex);
4851 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4852 struct cgroup_subsys *ss = subsys[i];
4853 if (ss == NULL)
4854 continue;
4855 seq_printf(m, "%s\t%d\t%d\t%d\n",
4856 ss->name, ss->root->hierarchy_id,
4857 ss->root->number_of_cgroups, !ss->disabled);
4859 mutex_unlock(&cgroup_mutex);
4860 return 0;
4863 static int cgroupstats_open(struct inode *inode, struct file *file)
4865 return single_open(file, proc_cgroupstats_show, NULL);
4868 static const struct file_operations proc_cgroupstats_operations = {
4869 .open = cgroupstats_open,
4870 .read = seq_read,
4871 .llseek = seq_lseek,
4872 .release = single_release,
4876 * cgroup_fork - attach newly forked task to its parents cgroup.
4877 * @child: pointer to task_struct of forking parent process.
4879 * Description: A task inherits its parent's cgroup at fork().
4881 * A pointer to the shared css_set was automatically copied in
4882 * fork.c by dup_task_struct(). However, we ignore that copy, since
4883 * it was not made under the protection of RCU or cgroup_mutex, so
4884 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
4885 * have already changed current->cgroups, allowing the previously
4886 * referenced cgroup group to be removed and freed.
4888 * At the point that cgroup_fork() is called, 'current' is the parent
4889 * task, and the passed argument 'child' points to the child task.
4891 void cgroup_fork(struct task_struct *child)
4893 task_lock(current);
4894 child->cgroups = current->cgroups;
4895 get_css_set(child->cgroups);
4896 task_unlock(current);
4897 INIT_LIST_HEAD(&child->cg_list);
4901 * cgroup_post_fork - called on a new task after adding it to the task list
4902 * @child: the task in question
4904 * Adds the task to the list running through its css_set if necessary and
4905 * call the subsystem fork() callbacks. Has to be after the task is
4906 * visible on the task list in case we race with the first call to
4907 * cgroup_iter_start() - to guarantee that the new task ends up on its
4908 * list.
4910 void cgroup_post_fork(struct task_struct *child)
4912 int i;
4915 * use_task_css_set_links is set to 1 before we walk the tasklist
4916 * under the tasklist_lock and we read it here after we added the child
4917 * to the tasklist under the tasklist_lock as well. If the child wasn't
4918 * yet in the tasklist when we walked through it from
4919 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4920 * should be visible now due to the paired locking and barriers implied
4921 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4922 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4923 * lock on fork.
4925 if (use_task_css_set_links) {
4926 write_lock(&css_set_lock);
4927 task_lock(child);
4928 if (list_empty(&child->cg_list))
4929 list_add(&child->cg_list, &child->cgroups->tasks);
4930 task_unlock(child);
4931 write_unlock(&css_set_lock);
4935 * Call ss->fork(). This must happen after @child is linked on
4936 * css_set; otherwise, @child might change state between ->fork()
4937 * and addition to css_set.
4939 if (need_forkexit_callback) {
4940 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4941 struct cgroup_subsys *ss = subsys[i];
4944 * fork/exit callbacks are supported only for
4945 * builtin subsystems and we don't need further
4946 * synchronization as they never go away.
4948 if (!ss || ss->module)
4949 continue;
4951 if (ss->fork)
4952 ss->fork(child);
4958 * cgroup_exit - detach cgroup from exiting task
4959 * @tsk: pointer to task_struct of exiting process
4960 * @run_callback: run exit callbacks?
4962 * Description: Detach cgroup from @tsk and release it.
4964 * Note that cgroups marked notify_on_release force every task in
4965 * them to take the global cgroup_mutex mutex when exiting.
4966 * This could impact scaling on very large systems. Be reluctant to
4967 * use notify_on_release cgroups where very high task exit scaling
4968 * is required on large systems.
4970 * the_top_cgroup_hack:
4972 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
4974 * We call cgroup_exit() while the task is still competent to
4975 * handle notify_on_release(), then leave the task attached to the
4976 * root cgroup in each hierarchy for the remainder of its exit.
4978 * To do this properly, we would increment the reference count on
4979 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
4980 * code we would add a second cgroup function call, to drop that
4981 * reference. This would just create an unnecessary hot spot on
4982 * the top_cgroup reference count, to no avail.
4984 * Normally, holding a reference to a cgroup without bumping its
4985 * count is unsafe. The cgroup could go away, or someone could
4986 * attach us to a different cgroup, decrementing the count on
4987 * the first cgroup that we never incremented. But in this case,
4988 * top_cgroup isn't going away, and either task has PF_EXITING set,
4989 * which wards off any cgroup_attach_task() attempts, or task is a failed
4990 * fork, never visible to cgroup_attach_task.
4992 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
4994 struct css_set *cg;
4995 int i;
4998 * Unlink from the css_set task list if necessary.
4999 * Optimistically check cg_list before taking
5000 * css_set_lock
5002 if (!list_empty(&tsk->cg_list)) {
5003 write_lock(&css_set_lock);
5004 if (!list_empty(&tsk->cg_list))
5005 list_del_init(&tsk->cg_list);
5006 write_unlock(&css_set_lock);
5009 /* Reassign the task to the init_css_set. */
5010 task_lock(tsk);
5011 cg = tsk->cgroups;
5012 tsk->cgroups = &init_css_set;
5014 if (run_callbacks && need_forkexit_callback) {
5015 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
5016 struct cgroup_subsys *ss = subsys[i];
5018 /* modular subsystems can't use callbacks */
5019 if (!ss || ss->module)
5020 continue;
5022 if (ss->exit) {
5023 struct cgroup *old_cgrp =
5024 rcu_dereference_raw(cg->subsys[i])->cgroup;
5025 struct cgroup *cgrp = task_cgroup(tsk, i);
5026 ss->exit(cgrp, old_cgrp, tsk);
5030 task_unlock(tsk);
5032 put_css_set_taskexit(cg);
5036 * cgroup_is_descendant - see if @cgrp is a descendant of @task's cgrp
5037 * @cgrp: the cgroup in question
5038 * @task: the task in question
5040 * See if @cgrp is a descendant of @task's cgroup in the appropriate
5041 * hierarchy.
5043 * If we are sending in dummytop, then presumably we are creating
5044 * the top cgroup in the subsystem.
5046 * Called only by the ns (nsproxy) cgroup.
5048 int cgroup_is_descendant(const struct cgroup *cgrp, struct task_struct *task)
5050 int ret;
5051 struct cgroup *target;
5053 if (cgrp == dummytop)
5054 return 1;
5056 target = task_cgroup_from_root(task, cgrp->root);
5057 while (cgrp != target && cgrp!= cgrp->top_cgroup)
5058 cgrp = cgrp->parent;
5059 ret = (cgrp == target);
5060 return ret;
5063 static void check_for_release(struct cgroup *cgrp)
5065 /* All of these checks rely on RCU to keep the cgroup
5066 * structure alive */
5067 if (cgroup_is_releasable(cgrp) && !atomic_read(&cgrp->count)
5068 && list_empty(&cgrp->children) && !cgroup_has_css_refs(cgrp)) {
5069 /* Control Group is currently removeable. If it's not
5070 * already queued for a userspace notification, queue
5071 * it now */
5072 int need_schedule_work = 0;
5073 raw_spin_lock(&release_list_lock);
5074 if (!cgroup_is_removed(cgrp) &&
5075 list_empty(&cgrp->release_list)) {
5076 list_add(&cgrp->release_list, &release_list);
5077 need_schedule_work = 1;
5079 raw_spin_unlock(&release_list_lock);
5080 if (need_schedule_work)
5081 schedule_work(&release_agent_work);
5085 /* Caller must verify that the css is not for root cgroup */
5086 bool __css_tryget(struct cgroup_subsys_state *css)
5088 while (true) {
5089 int t, v;
5091 v = css_refcnt(css);
5092 t = atomic_cmpxchg(&css->refcnt, v, v + 1);
5093 if (likely(t == v))
5094 return true;
5095 else if (t < 0)
5096 return false;
5097 cpu_relax();
5100 EXPORT_SYMBOL_GPL(__css_tryget);
5102 /* Caller must verify that the css is not for root cgroup */
5103 void __css_put(struct cgroup_subsys_state *css)
5105 struct cgroup *cgrp = css->cgroup;
5106 int v;
5108 rcu_read_lock();
5109 v = css_unbias_refcnt(atomic_dec_return(&css->refcnt));
5111 switch (v) {
5112 case 1:
5113 if (notify_on_release(cgrp)) {
5114 set_bit(CGRP_RELEASABLE, &cgrp->flags);
5115 check_for_release(cgrp);
5117 break;
5118 case 0:
5119 schedule_work(&css->dput_work);
5120 break;
5122 rcu_read_unlock();
5124 EXPORT_SYMBOL_GPL(__css_put);
5127 * Notify userspace when a cgroup is released, by running the
5128 * configured release agent with the name of the cgroup (path
5129 * relative to the root of cgroup file system) as the argument.
5131 * Most likely, this user command will try to rmdir this cgroup.
5133 * This races with the possibility that some other task will be
5134 * attached to this cgroup before it is removed, or that some other
5135 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5136 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5137 * unused, and this cgroup will be reprieved from its death sentence,
5138 * to continue to serve a useful existence. Next time it's released,
5139 * we will get notified again, if it still has 'notify_on_release' set.
5141 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5142 * means only wait until the task is successfully execve()'d. The
5143 * separate release agent task is forked by call_usermodehelper(),
5144 * then control in this thread returns here, without waiting for the
5145 * release agent task. We don't bother to wait because the caller of
5146 * this routine has no use for the exit status of the release agent
5147 * task, so no sense holding our caller up for that.
5149 static void cgroup_release_agent(struct work_struct *work)
5151 BUG_ON(work != &release_agent_work);
5152 mutex_lock(&cgroup_mutex);
5153 raw_spin_lock(&release_list_lock);
5154 while (!list_empty(&release_list)) {
5155 char *argv[3], *envp[3];
5156 int i;
5157 char *pathbuf = NULL, *agentbuf = NULL;
5158 struct cgroup *cgrp = list_entry(release_list.next,
5159 struct cgroup,
5160 release_list);
5161 list_del_init(&cgrp->release_list);
5162 raw_spin_unlock(&release_list_lock);
5163 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5164 if (!pathbuf)
5165 goto continue_free;
5166 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
5167 goto continue_free;
5168 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5169 if (!agentbuf)
5170 goto continue_free;
5172 i = 0;
5173 argv[i++] = agentbuf;
5174 argv[i++] = pathbuf;
5175 argv[i] = NULL;
5177 i = 0;
5178 /* minimal command environment */
5179 envp[i++] = "HOME=/";
5180 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5181 envp[i] = NULL;
5183 /* Drop the lock while we invoke the usermode helper,
5184 * since the exec could involve hitting disk and hence
5185 * be a slow process */
5186 mutex_unlock(&cgroup_mutex);
5187 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5188 mutex_lock(&cgroup_mutex);
5189 continue_free:
5190 kfree(pathbuf);
5191 kfree(agentbuf);
5192 raw_spin_lock(&release_list_lock);
5194 raw_spin_unlock(&release_list_lock);
5195 mutex_unlock(&cgroup_mutex);
5198 static int __init cgroup_disable(char *str)
5200 int i;
5201 char *token;
5203 while ((token = strsep(&str, ",")) != NULL) {
5204 if (!*token)
5205 continue;
5206 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
5207 struct cgroup_subsys *ss = subsys[i];
5210 * cgroup_disable, being at boot time, can't
5211 * know about module subsystems, so we don't
5212 * worry about them.
5214 if (!ss || ss->module)
5215 continue;
5217 if (!strcmp(token, ss->name)) {
5218 ss->disabled = 1;
5219 printk(KERN_INFO "Disabling %s control group"
5220 " subsystem\n", ss->name);
5221 break;
5225 return 1;
5227 __setup("cgroup_disable=", cgroup_disable);
5230 * Functons for CSS ID.
5234 *To get ID other than 0, this should be called when !cgroup_is_removed().
5236 unsigned short css_id(struct cgroup_subsys_state *css)
5238 struct css_id *cssid;
5241 * This css_id() can return correct value when somone has refcnt
5242 * on this or this is under rcu_read_lock(). Once css->id is allocated,
5243 * it's unchanged until freed.
5245 cssid = rcu_dereference_check(css->id, css_refcnt(css));
5247 if (cssid)
5248 return cssid->id;
5249 return 0;
5251 EXPORT_SYMBOL_GPL(css_id);
5253 unsigned short css_depth(struct cgroup_subsys_state *css)
5255 struct css_id *cssid;
5257 cssid = rcu_dereference_check(css->id, css_refcnt(css));
5259 if (cssid)
5260 return cssid->depth;
5261 return 0;
5263 EXPORT_SYMBOL_GPL(css_depth);
5266 * css_is_ancestor - test "root" css is an ancestor of "child"
5267 * @child: the css to be tested.
5268 * @root: the css supporsed to be an ancestor of the child.
5270 * Returns true if "root" is an ancestor of "child" in its hierarchy. Because
5271 * this function reads css->id, the caller must hold rcu_read_lock().
5272 * But, considering usual usage, the csses should be valid objects after test.
5273 * Assuming that the caller will do some action to the child if this returns
5274 * returns true, the caller must take "child";s reference count.
5275 * If "child" is valid object and this returns true, "root" is valid, too.
5278 bool css_is_ancestor(struct cgroup_subsys_state *child,
5279 const struct cgroup_subsys_state *root)
5281 struct css_id *child_id;
5282 struct css_id *root_id;
5284 child_id = rcu_dereference(child->id);
5285 if (!child_id)
5286 return false;
5287 root_id = rcu_dereference(root->id);
5288 if (!root_id)
5289 return false;
5290 if (child_id->depth < root_id->depth)
5291 return false;
5292 if (child_id->stack[root_id->depth] != root_id->id)
5293 return false;
5294 return true;
5297 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
5299 struct css_id *id = css->id;
5300 /* When this is called before css_id initialization, id can be NULL */
5301 if (!id)
5302 return;
5304 BUG_ON(!ss->use_id);
5306 rcu_assign_pointer(id->css, NULL);
5307 rcu_assign_pointer(css->id, NULL);
5308 spin_lock(&ss->id_lock);
5309 idr_remove(&ss->idr, id->id);
5310 spin_unlock(&ss->id_lock);
5311 kfree_rcu(id, rcu_head);
5313 EXPORT_SYMBOL_GPL(free_css_id);
5316 * This is called by init or create(). Then, calls to this function are
5317 * always serialized (By cgroup_mutex() at create()).
5320 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
5322 struct css_id *newid;
5323 int myid, error, size;
5325 BUG_ON(!ss->use_id);
5327 size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
5328 newid = kzalloc(size, GFP_KERNEL);
5329 if (!newid)
5330 return ERR_PTR(-ENOMEM);
5331 /* get id */
5332 if (unlikely(!idr_pre_get(&ss->idr, GFP_KERNEL))) {
5333 error = -ENOMEM;
5334 goto err_out;
5336 spin_lock(&ss->id_lock);
5337 /* Don't use 0. allocates an ID of 1-65535 */
5338 error = idr_get_new_above(&ss->idr, newid, 1, &myid);
5339 spin_unlock(&ss->id_lock);
5341 /* Returns error when there are no free spaces for new ID.*/
5342 if (error) {
5343 error = -ENOSPC;
5344 goto err_out;
5346 if (myid > CSS_ID_MAX)
5347 goto remove_idr;
5349 newid->id = myid;
5350 newid->depth = depth;
5351 return newid;
5352 remove_idr:
5353 error = -ENOSPC;
5354 spin_lock(&ss->id_lock);
5355 idr_remove(&ss->idr, myid);
5356 spin_unlock(&ss->id_lock);
5357 err_out:
5358 kfree(newid);
5359 return ERR_PTR(error);
5363 static int __init_or_module cgroup_init_idr(struct cgroup_subsys *ss,
5364 struct cgroup_subsys_state *rootcss)
5366 struct css_id *newid;
5368 spin_lock_init(&ss->id_lock);
5369 idr_init(&ss->idr);
5371 newid = get_new_cssid(ss, 0);
5372 if (IS_ERR(newid))
5373 return PTR_ERR(newid);
5375 newid->stack[0] = newid->id;
5376 newid->css = rootcss;
5377 rootcss->id = newid;
5378 return 0;
5381 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
5382 struct cgroup *child)
5384 int subsys_id, i, depth = 0;
5385 struct cgroup_subsys_state *parent_css, *child_css;
5386 struct css_id *child_id, *parent_id;
5388 subsys_id = ss->subsys_id;
5389 parent_css = parent->subsys[subsys_id];
5390 child_css = child->subsys[subsys_id];
5391 parent_id = parent_css->id;
5392 depth = parent_id->depth + 1;
5394 child_id = get_new_cssid(ss, depth);
5395 if (IS_ERR(child_id))
5396 return PTR_ERR(child_id);
5398 for (i = 0; i < depth; i++)
5399 child_id->stack[i] = parent_id->stack[i];
5400 child_id->stack[depth] = child_id->id;
5402 * child_id->css pointer will be set after this cgroup is available
5403 * see cgroup_populate_dir()
5405 rcu_assign_pointer(child_css->id, child_id);
5407 return 0;
5411 * css_lookup - lookup css by id
5412 * @ss: cgroup subsys to be looked into.
5413 * @id: the id
5415 * Returns pointer to cgroup_subsys_state if there is valid one with id.
5416 * NULL if not. Should be called under rcu_read_lock()
5418 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
5420 struct css_id *cssid = NULL;
5422 BUG_ON(!ss->use_id);
5423 cssid = idr_find(&ss->idr, id);
5425 if (unlikely(!cssid))
5426 return NULL;
5428 return rcu_dereference(cssid->css);
5430 EXPORT_SYMBOL_GPL(css_lookup);
5433 * css_get_next - lookup next cgroup under specified hierarchy.
5434 * @ss: pointer to subsystem
5435 * @id: current position of iteration.
5436 * @root: pointer to css. search tree under this.
5437 * @foundid: position of found object.
5439 * Search next css under the specified hierarchy of rootid. Calling under
5440 * rcu_read_lock() is necessary. Returns NULL if it reaches the end.
5442 struct cgroup_subsys_state *
5443 css_get_next(struct cgroup_subsys *ss, int id,
5444 struct cgroup_subsys_state *root, int *foundid)
5446 struct cgroup_subsys_state *ret = NULL;
5447 struct css_id *tmp;
5448 int tmpid;
5449 int rootid = css_id(root);
5450 int depth = css_depth(root);
5452 if (!rootid)
5453 return NULL;
5455 BUG_ON(!ss->use_id);
5456 WARN_ON_ONCE(!rcu_read_lock_held());
5458 /* fill start point for scan */
5459 tmpid = id;
5460 while (1) {
5462 * scan next entry from bitmap(tree), tmpid is updated after
5463 * idr_get_next().
5465 tmp = idr_get_next(&ss->idr, &tmpid);
5466 if (!tmp)
5467 break;
5468 if (tmp->depth >= depth && tmp->stack[depth] == rootid) {
5469 ret = rcu_dereference(tmp->css);
5470 if (ret) {
5471 *foundid = tmpid;
5472 break;
5475 /* continue to scan from next id */
5476 tmpid = tmpid + 1;
5478 return ret;
5482 * get corresponding css from file open on cgroupfs directory
5484 struct cgroup_subsys_state *cgroup_css_from_dir(struct file *f, int id)
5486 struct cgroup *cgrp;
5487 struct inode *inode;
5488 struct cgroup_subsys_state *css;
5490 inode = file_inode(f);
5491 /* check in cgroup filesystem dir */
5492 if (inode->i_op != &cgroup_dir_inode_operations)
5493 return ERR_PTR(-EBADF);
5495 if (id < 0 || id >= CGROUP_SUBSYS_COUNT)
5496 return ERR_PTR(-EINVAL);
5498 /* get cgroup */
5499 cgrp = __d_cgrp(f->f_dentry);
5500 css = cgrp->subsys[id];
5501 return css ? css : ERR_PTR(-ENOENT);
5504 #ifdef CONFIG_CGROUP_DEBUG
5505 static struct cgroup_subsys_state *debug_css_alloc(struct cgroup *cont)
5507 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5509 if (!css)
5510 return ERR_PTR(-ENOMEM);
5512 return css;
5515 static void debug_css_free(struct cgroup *cont)
5517 kfree(cont->subsys[debug_subsys_id]);
5520 static u64 cgroup_refcount_read(struct cgroup *cont, struct cftype *cft)
5522 return atomic_read(&cont->count);
5525 static u64 debug_taskcount_read(struct cgroup *cont, struct cftype *cft)
5527 return cgroup_task_count(cont);
5530 static u64 current_css_set_read(struct cgroup *cont, struct cftype *cft)
5532 return (u64)(unsigned long)current->cgroups;
5535 static u64 current_css_set_refcount_read(struct cgroup *cont,
5536 struct cftype *cft)
5538 u64 count;
5540 rcu_read_lock();
5541 count = atomic_read(&current->cgroups->refcount);
5542 rcu_read_unlock();
5543 return count;
5546 static int current_css_set_cg_links_read(struct cgroup *cont,
5547 struct cftype *cft,
5548 struct seq_file *seq)
5550 struct cg_cgroup_link *link;
5551 struct css_set *cg;
5553 read_lock(&css_set_lock);
5554 rcu_read_lock();
5555 cg = rcu_dereference(current->cgroups);
5556 list_for_each_entry(link, &cg->cg_links, cg_link_list) {
5557 struct cgroup *c = link->cgrp;
5558 const char *name;
5560 if (c->dentry)
5561 name = c->dentry->d_name.name;
5562 else
5563 name = "?";
5564 seq_printf(seq, "Root %d group %s\n",
5565 c->root->hierarchy_id, name);
5567 rcu_read_unlock();
5568 read_unlock(&css_set_lock);
5569 return 0;
5572 #define MAX_TASKS_SHOWN_PER_CSS 25
5573 static int cgroup_css_links_read(struct cgroup *cont,
5574 struct cftype *cft,
5575 struct seq_file *seq)
5577 struct cg_cgroup_link *link;
5579 read_lock(&css_set_lock);
5580 list_for_each_entry(link, &cont->css_sets, cgrp_link_list) {
5581 struct css_set *cg = link->cg;
5582 struct task_struct *task;
5583 int count = 0;
5584 seq_printf(seq, "css_set %p\n", cg);
5585 list_for_each_entry(task, &cg->tasks, cg_list) {
5586 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5587 seq_puts(seq, " ...\n");
5588 break;
5589 } else {
5590 seq_printf(seq, " task %d\n",
5591 task_pid_vnr(task));
5595 read_unlock(&css_set_lock);
5596 return 0;
5599 static u64 releasable_read(struct cgroup *cgrp, struct cftype *cft)
5601 return test_bit(CGRP_RELEASABLE, &cgrp->flags);
5604 static struct cftype debug_files[] = {
5606 .name = "cgroup_refcount",
5607 .read_u64 = cgroup_refcount_read,
5610 .name = "taskcount",
5611 .read_u64 = debug_taskcount_read,
5615 .name = "current_css_set",
5616 .read_u64 = current_css_set_read,
5620 .name = "current_css_set_refcount",
5621 .read_u64 = current_css_set_refcount_read,
5625 .name = "current_css_set_cg_links",
5626 .read_seq_string = current_css_set_cg_links_read,
5630 .name = "cgroup_css_links",
5631 .read_seq_string = cgroup_css_links_read,
5635 .name = "releasable",
5636 .read_u64 = releasable_read,
5639 { } /* terminate */
5642 struct cgroup_subsys debug_subsys = {
5643 .name = "debug",
5644 .css_alloc = debug_css_alloc,
5645 .css_free = debug_css_free,
5646 .subsys_id = debug_subsys_id,
5647 .base_cftypes = debug_files,
5649 #endif /* CONFIG_CGROUP_DEBUG */