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>
34 #include <linux/init_task.h>
35 #include <linux/kernel.h>
36 #include <linux/list.h>
38 #include <linux/mutex.h>
39 #include <linux/mount.h>
40 #include <linux/pagemap.h>
41 #include <linux/proc_fs.h>
42 #include <linux/rcupdate.h>
43 #include <linux/sched.h>
44 #include <linux/backing-dev.h>
45 #include <linux/seq_file.h>
46 #include <linux/slab.h>
47 #include <linux/magic.h>
48 #include <linux/spinlock.h>
49 #include <linux/string.h>
50 #include <linux/sort.h>
51 #include <linux/kmod.h>
52 #include <linux/module.h>
53 #include <linux/delayacct.h>
54 #include <linux/cgroupstats.h>
55 #include <linux/hash.h>
56 #include <linux/namei.h>
57 #include <linux/pid_namespace.h>
58 #include <linux/idr.h>
59 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
60 #include <linux/eventfd.h>
61 #include <linux/poll.h>
62 #include <linux/flex_array.h> /* used in cgroup_attach_proc */
63 #include <linux/kthread.h>
65 #include <linux/atomic.h>
67 /* css deactivation bias, makes css->refcnt negative to deny new trygets */
68 #define CSS_DEACT_BIAS INT_MIN
71 * cgroup_mutex is the master lock. Any modification to cgroup or its
72 * hierarchy must be performed while holding it.
74 * cgroup_root_mutex nests inside cgroup_mutex and should be held to modify
75 * cgroupfs_root of any cgroup hierarchy - subsys list, flags,
76 * release_agent_path and so on. Modifying requires both cgroup_mutex and
77 * cgroup_root_mutex. Readers can acquire either of the two. This is to
78 * break the following locking order cycle.
80 * A. cgroup_mutex -> cred_guard_mutex -> s_type->i_mutex_key -> namespace_sem
81 * B. namespace_sem -> cgroup_mutex
83 * B happens only through cgroup_show_options() and using cgroup_root_mutex
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
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
108 struct cgroupfs_root {
109 struct super_block *sb;
112 * The bitmask of subsystems intended to be attached to this
115 unsigned long subsys_mask;
117 /* Unique id for this hierarchy. */
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 */
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.
162 struct list_head node;
163 struct dentry *dentry;
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)
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;
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.
208 * Control file which the event associated.
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.
224 wait_queue_head_t *wqh;
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
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 */
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)
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;
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;
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 #define CSS_SET_TABLE_SIZE (1 << CSS_SET_HASH_BITS)
380 static struct hlist_head css_set_table[CSS_SET_TABLE_SIZE];
382 static struct hlist_head *css_set_hash(struct cgroup_subsys_state *css[])
386 unsigned long tmp = 0UL;
388 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++)
389 tmp += (unsigned long)css[i];
390 tmp = (tmp >> 16) ^ tmp;
392 index = hash_long(tmp, CSS_SET_HASH_BITS);
394 return &css_set_table[index];
397 /* We don't maintain the lists running through each css_set to its
398 * task until after the first call to cgroup_iter_start(). This
399 * reduces the fork()/exit() overhead for people who have cgroups
400 * compiled into their kernel but not actually in use */
401 static int use_task_css_set_links __read_mostly;
403 static void __put_css_set(struct css_set *cg, int taskexit)
405 struct cg_cgroup_link *link;
406 struct cg_cgroup_link *saved_link;
408 * Ensure that the refcount doesn't hit zero while any readers
409 * can see it. Similar to atomic_dec_and_lock(), but for an
412 if (atomic_add_unless(&cg->refcount, -1, 1))
414 write_lock(&css_set_lock);
415 if (!atomic_dec_and_test(&cg->refcount)) {
416 write_unlock(&css_set_lock);
420 /* This css_set is dead. unlink it and release cgroup refcounts */
421 hlist_del(&cg->hlist);
424 list_for_each_entry_safe(link, saved_link, &cg->cg_links,
426 struct cgroup *cgrp = link->cgrp;
427 list_del(&link->cg_link_list);
428 list_del(&link->cgrp_link_list);
429 if (atomic_dec_and_test(&cgrp->count) &&
430 notify_on_release(cgrp)) {
432 set_bit(CGRP_RELEASABLE, &cgrp->flags);
433 check_for_release(cgrp);
439 write_unlock(&css_set_lock);
440 kfree_rcu(cg, rcu_head);
444 * refcounted get/put for css_set objects
446 static inline void get_css_set(struct css_set *cg)
448 atomic_inc(&cg->refcount);
451 static inline void put_css_set(struct css_set *cg)
453 __put_css_set(cg, 0);
456 static inline void put_css_set_taskexit(struct css_set *cg)
458 __put_css_set(cg, 1);
462 * compare_css_sets - helper function for find_existing_css_set().
463 * @cg: candidate css_set being tested
464 * @old_cg: existing css_set for a task
465 * @new_cgrp: cgroup that's being entered by the task
466 * @template: desired set of css pointers in css_set (pre-calculated)
468 * Returns true if "cg" matches "old_cg" except for the hierarchy
469 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
471 static bool compare_css_sets(struct css_set *cg,
472 struct css_set *old_cg,
473 struct cgroup *new_cgrp,
474 struct cgroup_subsys_state *template[])
476 struct list_head *l1, *l2;
478 if (memcmp(template, cg->subsys, sizeof(cg->subsys))) {
479 /* Not all subsystems matched */
484 * Compare cgroup pointers in order to distinguish between
485 * different cgroups in heirarchies with no subsystems. We
486 * could get by with just this check alone (and skip the
487 * memcmp above) but on most setups the memcmp check will
488 * avoid the need for this more expensive check on almost all
493 l2 = &old_cg->cg_links;
495 struct cg_cgroup_link *cgl1, *cgl2;
496 struct cgroup *cg1, *cg2;
500 /* See if we reached the end - both lists are equal length. */
501 if (l1 == &cg->cg_links) {
502 BUG_ON(l2 != &old_cg->cg_links);
505 BUG_ON(l2 == &old_cg->cg_links);
507 /* Locate the cgroups associated with these links. */
508 cgl1 = list_entry(l1, struct cg_cgroup_link, cg_link_list);
509 cgl2 = list_entry(l2, struct cg_cgroup_link, cg_link_list);
512 /* Hierarchies should be linked in the same order. */
513 BUG_ON(cg1->root != cg2->root);
516 * If this hierarchy is the hierarchy of the cgroup
517 * that's changing, then we need to check that this
518 * css_set points to the new cgroup; if it's any other
519 * hierarchy, then this css_set should point to the
520 * same cgroup as the old css_set.
522 if (cg1->root == new_cgrp->root) {
534 * find_existing_css_set() is a helper for
535 * find_css_set(), and checks to see whether an existing
536 * css_set is suitable.
538 * oldcg: the cgroup group that we're using before the cgroup
541 * cgrp: the cgroup that we're moving into
543 * template: location in which to build the desired set of subsystem
544 * state objects for the new cgroup group
546 static struct css_set *find_existing_css_set(
547 struct css_set *oldcg,
549 struct cgroup_subsys_state *template[])
552 struct cgroupfs_root *root = cgrp->root;
553 struct hlist_head *hhead;
554 struct hlist_node *node;
558 * Build the set of subsystem state objects that we want to see in the
559 * new css_set. while subsystems can change globally, the entries here
560 * won't change, so no need for locking.
562 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
563 if (root->subsys_mask & (1UL << i)) {
564 /* Subsystem is in this hierarchy. So we want
565 * the subsystem state from the new
567 template[i] = cgrp->subsys[i];
569 /* Subsystem is not in this hierarchy, so we
570 * don't want to change the subsystem state */
571 template[i] = oldcg->subsys[i];
575 hhead = css_set_hash(template);
576 hlist_for_each_entry(cg, node, hhead, hlist) {
577 if (!compare_css_sets(cg, oldcg, cgrp, template))
580 /* This css_set matches what we need */
584 /* No existing cgroup group matched */
588 static void free_cg_links(struct list_head *tmp)
590 struct cg_cgroup_link *link;
591 struct cg_cgroup_link *saved_link;
593 list_for_each_entry_safe(link, saved_link, tmp, cgrp_link_list) {
594 list_del(&link->cgrp_link_list);
600 * allocate_cg_links() allocates "count" cg_cgroup_link structures
601 * and chains them on tmp through their cgrp_link_list fields. Returns 0 on
602 * success or a negative error
604 static int allocate_cg_links(int count, struct list_head *tmp)
606 struct cg_cgroup_link *link;
609 for (i = 0; i < count; i++) {
610 link = kmalloc(sizeof(*link), GFP_KERNEL);
615 list_add(&link->cgrp_link_list, tmp);
621 * link_css_set - a helper function to link a css_set to a cgroup
622 * @tmp_cg_links: cg_cgroup_link objects allocated by allocate_cg_links()
623 * @cg: the css_set to be linked
624 * @cgrp: the destination cgroup
626 static void link_css_set(struct list_head *tmp_cg_links,
627 struct css_set *cg, struct cgroup *cgrp)
629 struct cg_cgroup_link *link;
631 BUG_ON(list_empty(tmp_cg_links));
632 link = list_first_entry(tmp_cg_links, struct cg_cgroup_link,
636 atomic_inc(&cgrp->count);
637 list_move(&link->cgrp_link_list, &cgrp->css_sets);
639 * Always add links to the tail of the list so that the list
640 * is sorted by order of hierarchy creation
642 list_add_tail(&link->cg_link_list, &cg->cg_links);
646 * find_css_set() takes an existing cgroup group and a
647 * cgroup object, and returns a css_set object that's
648 * equivalent to the old group, but with the given cgroup
649 * substituted into the appropriate hierarchy. Must be called with
652 static struct css_set *find_css_set(
653 struct css_set *oldcg, struct cgroup *cgrp)
656 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT];
658 struct list_head tmp_cg_links;
660 struct hlist_head *hhead;
661 struct cg_cgroup_link *link;
663 /* First see if we already have a cgroup group that matches
665 read_lock(&css_set_lock);
666 res = find_existing_css_set(oldcg, cgrp, template);
669 read_unlock(&css_set_lock);
674 res = kmalloc(sizeof(*res), GFP_KERNEL);
678 /* Allocate all the cg_cgroup_link objects that we'll need */
679 if (allocate_cg_links(root_count, &tmp_cg_links) < 0) {
684 atomic_set(&res->refcount, 1);
685 INIT_LIST_HEAD(&res->cg_links);
686 INIT_LIST_HEAD(&res->tasks);
687 INIT_HLIST_NODE(&res->hlist);
689 /* Copy the set of subsystem state objects generated in
690 * find_existing_css_set() */
691 memcpy(res->subsys, template, sizeof(res->subsys));
693 write_lock(&css_set_lock);
694 /* Add reference counts and links from the new css_set. */
695 list_for_each_entry(link, &oldcg->cg_links, cg_link_list) {
696 struct cgroup *c = link->cgrp;
697 if (c->root == cgrp->root)
699 link_css_set(&tmp_cg_links, res, c);
702 BUG_ON(!list_empty(&tmp_cg_links));
706 /* Add this cgroup group to the hash table */
707 hhead = css_set_hash(res->subsys);
708 hlist_add_head(&res->hlist, hhead);
710 write_unlock(&css_set_lock);
716 * Return the cgroup for "task" from the given hierarchy. Must be
717 * called with cgroup_mutex held.
719 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
720 struct cgroupfs_root *root)
723 struct cgroup *res = NULL;
725 BUG_ON(!mutex_is_locked(&cgroup_mutex));
726 read_lock(&css_set_lock);
728 * No need to lock the task - since we hold cgroup_mutex the
729 * task can't change groups, so the only thing that can happen
730 * is that it exits and its css is set back to init_css_set.
733 if (css == &init_css_set) {
734 res = &root->top_cgroup;
736 struct cg_cgroup_link *link;
737 list_for_each_entry(link, &css->cg_links, cg_link_list) {
738 struct cgroup *c = link->cgrp;
739 if (c->root == root) {
745 read_unlock(&css_set_lock);
751 * There is one global cgroup mutex. We also require taking
752 * task_lock() when dereferencing a task's cgroup subsys pointers.
753 * See "The task_lock() exception", at the end of this comment.
755 * A task must hold cgroup_mutex to modify cgroups.
757 * Any task can increment and decrement the count field without lock.
758 * So in general, code holding cgroup_mutex can't rely on the count
759 * field not changing. However, if the count goes to zero, then only
760 * cgroup_attach_task() can increment it again. Because a count of zero
761 * means that no tasks are currently attached, therefore there is no
762 * way a task attached to that cgroup can fork (the other way to
763 * increment the count). So code holding cgroup_mutex can safely
764 * assume that if the count is zero, it will stay zero. Similarly, if
765 * a task holds cgroup_mutex on a cgroup with zero count, it
766 * knows that the cgroup won't be removed, as cgroup_rmdir()
769 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
770 * (usually) take cgroup_mutex. These are the two most performance
771 * critical pieces of code here. The exception occurs on cgroup_exit(),
772 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
773 * is taken, and if the cgroup count is zero, a usermode call made
774 * to the release agent with the name of the cgroup (path relative to
775 * the root of cgroup file system) as the argument.
777 * A cgroup can only be deleted if both its 'count' of using tasks
778 * is zero, and its list of 'children' cgroups is empty. Since all
779 * tasks in the system use _some_ cgroup, and since there is always at
780 * least one task in the system (init, pid == 1), therefore, top_cgroup
781 * always has either children cgroups and/or using tasks. So we don't
782 * need a special hack to ensure that top_cgroup cannot be deleted.
784 * The task_lock() exception
786 * The need for this exception arises from the action of
787 * cgroup_attach_task(), which overwrites one task's cgroup pointer with
788 * another. It does so using cgroup_mutex, however there are
789 * several performance critical places that need to reference
790 * task->cgroup without the expense of grabbing a system global
791 * mutex. Therefore except as noted below, when dereferencing or, as
792 * in cgroup_attach_task(), modifying a task's cgroup pointer we use
793 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
794 * the task_struct routinely used for such matters.
796 * P.S. One more locking exception. RCU is used to guard the
797 * update of a tasks cgroup pointer by cgroup_attach_task()
801 * cgroup_lock - lock out any changes to cgroup structures
804 void cgroup_lock(void)
806 mutex_lock(&cgroup_mutex);
808 EXPORT_SYMBOL_GPL(cgroup_lock);
811 * cgroup_unlock - release lock on cgroup changes
813 * Undo the lock taken in a previous cgroup_lock() call.
815 void cgroup_unlock(void)
817 mutex_unlock(&cgroup_mutex);
819 EXPORT_SYMBOL_GPL(cgroup_unlock);
822 * A couple of forward declarations required, due to cyclic reference loop:
823 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
824 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
828 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode);
829 static struct dentry *cgroup_lookup(struct inode *, struct dentry *, unsigned int);
830 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
831 static int cgroup_populate_dir(struct cgroup *cgrp, bool base_files,
832 unsigned long subsys_mask);
833 static const struct inode_operations cgroup_dir_inode_operations;
834 static const struct file_operations proc_cgroupstats_operations;
836 static struct backing_dev_info cgroup_backing_dev_info = {
838 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
841 static int alloc_css_id(struct cgroup_subsys *ss,
842 struct cgroup *parent, struct cgroup *child);
844 static struct inode *cgroup_new_inode(umode_t mode, struct super_block *sb)
846 struct inode *inode = new_inode(sb);
849 inode->i_ino = get_next_ino();
850 inode->i_mode = mode;
851 inode->i_uid = current_fsuid();
852 inode->i_gid = current_fsgid();
853 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
854 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
859 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
861 /* is dentry a directory ? if so, kfree() associated cgroup */
862 if (S_ISDIR(inode->i_mode)) {
863 struct cgroup *cgrp = dentry->d_fsdata;
864 struct cgroup_subsys *ss;
865 BUG_ON(!(cgroup_is_removed(cgrp)));
866 /* It's possible for external users to be holding css
867 * reference counts on a cgroup; css_put() needs to
868 * be able to access the cgroup after decrementing
869 * the reference count in order to know if it needs to
870 * queue the cgroup to be handled by the release
874 mutex_lock(&cgroup_mutex);
876 * Release the subsystem state objects.
878 for_each_subsys(cgrp->root, ss)
881 cgrp->root->number_of_cgroups--;
882 mutex_unlock(&cgroup_mutex);
885 * Drop the active superblock reference that we took when we
888 deactivate_super(cgrp->root->sb);
891 * if we're getting rid of the cgroup, refcount should ensure
892 * that there are no pidlists left.
894 BUG_ON(!list_empty(&cgrp->pidlists));
896 simple_xattrs_free(&cgrp->xattrs);
898 ida_simple_remove(&cgrp->root->cgroup_ida, cgrp->id);
899 kfree_rcu(cgrp, rcu_head);
901 struct cfent *cfe = __d_cfe(dentry);
902 struct cgroup *cgrp = dentry->d_parent->d_fsdata;
903 struct cftype *cft = cfe->type;
905 WARN_ONCE(!list_empty(&cfe->node) &&
906 cgrp != &cgrp->root->top_cgroup,
907 "cfe still linked for %s\n", cfe->type->name);
909 simple_xattrs_free(&cft->xattrs);
914 static int cgroup_delete(const struct dentry *d)
919 static void remove_dir(struct dentry *d)
921 struct dentry *parent = dget(d->d_parent);
924 simple_rmdir(parent->d_inode, d);
928 static int cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
932 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
933 lockdep_assert_held(&cgroup_mutex);
935 list_for_each_entry(cfe, &cgrp->files, node) {
936 struct dentry *d = cfe->dentry;
938 if (cft && cfe->type != cft)
943 simple_unlink(cgrp->dentry->d_inode, d);
944 list_del_init(&cfe->node);
953 * cgroup_clear_directory - selective removal of base and subsystem files
954 * @dir: directory containing the files
955 * @base_files: true if the base files should be removed
956 * @subsys_mask: mask of the subsystem ids whose files should be removed
958 static void cgroup_clear_directory(struct dentry *dir, bool base_files,
959 unsigned long subsys_mask)
961 struct cgroup *cgrp = __d_cgrp(dir);
962 struct cgroup_subsys *ss;
964 for_each_subsys(cgrp->root, ss) {
965 struct cftype_set *set;
966 if (!test_bit(ss->subsys_id, &subsys_mask))
968 list_for_each_entry(set, &ss->cftsets, node)
969 cgroup_addrm_files(cgrp, NULL, set->cfts, false);
972 while (!list_empty(&cgrp->files))
973 cgroup_rm_file(cgrp, NULL);
978 * NOTE : the dentry must have been dget()'ed
980 static void cgroup_d_remove_dir(struct dentry *dentry)
982 struct dentry *parent;
983 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
985 cgroup_clear_directory(dentry, true, root->subsys_mask);
987 parent = dentry->d_parent;
988 spin_lock(&parent->d_lock);
989 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
990 list_del_init(&dentry->d_u.d_child);
991 spin_unlock(&dentry->d_lock);
992 spin_unlock(&parent->d_lock);
997 * Call with cgroup_mutex held. Drops reference counts on modules, including
998 * any duplicate ones that parse_cgroupfs_options took. If this function
999 * returns an error, no reference counts are touched.
1001 static int rebind_subsystems(struct cgroupfs_root *root,
1002 unsigned long final_subsys_mask)
1004 unsigned long added_mask, removed_mask;
1005 struct cgroup *cgrp = &root->top_cgroup;
1008 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1009 BUG_ON(!mutex_is_locked(&cgroup_root_mutex));
1011 removed_mask = root->actual_subsys_mask & ~final_subsys_mask;
1012 added_mask = final_subsys_mask & ~root->actual_subsys_mask;
1013 /* Check that any added subsystems are currently free */
1014 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1015 unsigned long bit = 1UL << i;
1016 struct cgroup_subsys *ss = subsys[i];
1017 if (!(bit & added_mask))
1020 * Nobody should tell us to do a subsys that doesn't exist:
1021 * parse_cgroupfs_options should catch that case and refcounts
1022 * ensure that subsystems won't disappear once selected.
1025 if (ss->root != &rootnode) {
1026 /* Subsystem isn't free */
1031 /* Currently we don't handle adding/removing subsystems when
1032 * any child cgroups exist. This is theoretically supportable
1033 * but involves complex error handling, so it's being left until
1035 if (root->number_of_cgroups > 1)
1038 /* Process each subsystem */
1039 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1040 struct cgroup_subsys *ss = subsys[i];
1041 unsigned long bit = 1UL << i;
1042 if (bit & added_mask) {
1043 /* We're binding this subsystem to this hierarchy */
1045 BUG_ON(cgrp->subsys[i]);
1046 BUG_ON(!dummytop->subsys[i]);
1047 BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
1048 cgrp->subsys[i] = dummytop->subsys[i];
1049 cgrp->subsys[i]->cgroup = cgrp;
1050 list_move(&ss->sibling, &root->subsys_list);
1054 /* refcount was already taken, and we're keeping it */
1055 } else if (bit & removed_mask) {
1056 /* We're removing this subsystem */
1058 BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
1059 BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
1062 dummytop->subsys[i]->cgroup = dummytop;
1063 cgrp->subsys[i] = NULL;
1064 subsys[i]->root = &rootnode;
1065 list_move(&ss->sibling, &rootnode.subsys_list);
1066 /* subsystem is now free - drop reference on module */
1067 module_put(ss->module);
1068 } else if (bit & final_subsys_mask) {
1069 /* Subsystem state should already exist */
1071 BUG_ON(!cgrp->subsys[i]);
1073 * a refcount was taken, but we already had one, so
1074 * drop the extra reference.
1076 module_put(ss->module);
1077 #ifdef CONFIG_MODULE_UNLOAD
1078 BUG_ON(ss->module && !module_refcount(ss->module));
1081 /* Subsystem state shouldn't exist */
1082 BUG_ON(cgrp->subsys[i]);
1085 root->subsys_mask = root->actual_subsys_mask = final_subsys_mask;
1091 static int cgroup_show_options(struct seq_file *seq, struct dentry *dentry)
1093 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
1094 struct cgroup_subsys *ss;
1096 mutex_lock(&cgroup_root_mutex);
1097 for_each_subsys(root, ss)
1098 seq_printf(seq, ",%s", ss->name);
1099 if (test_bit(ROOT_NOPREFIX, &root->flags))
1100 seq_puts(seq, ",noprefix");
1101 if (test_bit(ROOT_XATTR, &root->flags))
1102 seq_puts(seq, ",xattr");
1103 if (strlen(root->release_agent_path))
1104 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1105 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1106 seq_puts(seq, ",clone_children");
1107 if (strlen(root->name))
1108 seq_printf(seq, ",name=%s", root->name);
1109 mutex_unlock(&cgroup_root_mutex);
1113 struct cgroup_sb_opts {
1114 unsigned long subsys_mask;
1115 unsigned long flags;
1116 char *release_agent;
1117 bool cpuset_clone_children;
1119 /* User explicitly requested empty subsystem */
1122 struct cgroupfs_root *new_root;
1127 * Convert a hierarchy specifier into a bitmask of subsystems and flags. Call
1128 * with cgroup_mutex held to protect the subsys[] array. This function takes
1129 * refcounts on subsystems to be used, unless it returns error, in which case
1130 * no refcounts are taken.
1132 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1134 char *token, *o = data;
1135 bool all_ss = false, one_ss = false;
1136 unsigned long mask = (unsigned long)-1;
1138 bool module_pin_failed = false;
1140 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1142 #ifdef CONFIG_CPUSETS
1143 mask = ~(1UL << cpuset_subsys_id);
1146 memset(opts, 0, sizeof(*opts));
1148 while ((token = strsep(&o, ",")) != NULL) {
1151 if (!strcmp(token, "none")) {
1152 /* Explicitly have no subsystems */
1156 if (!strcmp(token, "all")) {
1157 /* Mutually exclusive option 'all' + subsystem name */
1163 if (!strcmp(token, "noprefix")) {
1164 set_bit(ROOT_NOPREFIX, &opts->flags);
1167 if (!strcmp(token, "clone_children")) {
1168 opts->cpuset_clone_children = true;
1171 if (!strcmp(token, "xattr")) {
1172 set_bit(ROOT_XATTR, &opts->flags);
1175 if (!strncmp(token, "release_agent=", 14)) {
1176 /* Specifying two release agents is forbidden */
1177 if (opts->release_agent)
1179 opts->release_agent =
1180 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1181 if (!opts->release_agent)
1185 if (!strncmp(token, "name=", 5)) {
1186 const char *name = token + 5;
1187 /* Can't specify an empty name */
1190 /* Must match [\w.-]+ */
1191 for (i = 0; i < strlen(name); i++) {
1195 if ((c == '.') || (c == '-') || (c == '_'))
1199 /* Specifying two names is forbidden */
1202 opts->name = kstrndup(name,
1203 MAX_CGROUP_ROOT_NAMELEN - 1,
1211 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1212 struct cgroup_subsys *ss = subsys[i];
1215 if (strcmp(token, ss->name))
1220 /* Mutually exclusive option 'all' + subsystem name */
1223 set_bit(i, &opts->subsys_mask);
1228 if (i == CGROUP_SUBSYS_COUNT)
1233 * If the 'all' option was specified select all the subsystems,
1234 * otherwise if 'none', 'name=' and a subsystem name options
1235 * were not specified, let's default to 'all'
1237 if (all_ss || (!one_ss && !opts->none && !opts->name)) {
1238 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1239 struct cgroup_subsys *ss = subsys[i];
1244 set_bit(i, &opts->subsys_mask);
1248 /* Consistency checks */
1251 * Option noprefix was introduced just for backward compatibility
1252 * with the old cpuset, so we allow noprefix only if mounting just
1253 * the cpuset subsystem.
1255 if (test_bit(ROOT_NOPREFIX, &opts->flags) &&
1256 (opts->subsys_mask & mask))
1260 /* Can't specify "none" and some subsystems */
1261 if (opts->subsys_mask && opts->none)
1265 * We either have to specify by name or by subsystems. (So all
1266 * empty hierarchies must have a name).
1268 if (!opts->subsys_mask && !opts->name)
1272 * Grab references on all the modules we'll need, so the subsystems
1273 * don't dance around before rebind_subsystems attaches them. This may
1274 * take duplicate reference counts on a subsystem that's already used,
1275 * but rebind_subsystems handles this case.
1277 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1278 unsigned long bit = 1UL << i;
1280 if (!(bit & opts->subsys_mask))
1282 if (!try_module_get(subsys[i]->module)) {
1283 module_pin_failed = true;
1287 if (module_pin_failed) {
1289 * oops, one of the modules was going away. this means that we
1290 * raced with a module_delete call, and to the user this is
1291 * essentially a "subsystem doesn't exist" case.
1293 for (i--; i >= 0; i--) {
1294 /* drop refcounts only on the ones we took */
1295 unsigned long bit = 1UL << i;
1297 if (!(bit & opts->subsys_mask))
1299 module_put(subsys[i]->module);
1307 static void drop_parsed_module_refcounts(unsigned long subsys_mask)
1310 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1311 unsigned long bit = 1UL << i;
1313 if (!(bit & subsys_mask))
1315 module_put(subsys[i]->module);
1319 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1322 struct cgroupfs_root *root = sb->s_fs_info;
1323 struct cgroup *cgrp = &root->top_cgroup;
1324 struct cgroup_sb_opts opts;
1325 unsigned long added_mask, removed_mask;
1327 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1328 mutex_lock(&cgroup_mutex);
1329 mutex_lock(&cgroup_root_mutex);
1331 /* See what subsystems are wanted */
1332 ret = parse_cgroupfs_options(data, &opts);
1336 /* See feature-removal-schedule.txt */
1337 if (opts.subsys_mask != root->actual_subsys_mask || opts.release_agent)
1338 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1339 task_tgid_nr(current), current->comm);
1341 added_mask = opts.subsys_mask & ~root->subsys_mask;
1342 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1344 /* Don't allow flags or name to change at remount */
1345 if (opts.flags != root->flags ||
1346 (opts.name && strcmp(opts.name, root->name))) {
1348 drop_parsed_module_refcounts(opts.subsys_mask);
1353 * Clear out the files of subsystems that should be removed, do
1354 * this before rebind_subsystems, since rebind_subsystems may
1355 * change this hierarchy's subsys_list.
1357 cgroup_clear_directory(cgrp->dentry, false, removed_mask);
1359 ret = rebind_subsystems(root, opts.subsys_mask);
1361 /* rebind_subsystems failed, re-populate the removed files */
1362 cgroup_populate_dir(cgrp, false, removed_mask);
1363 drop_parsed_module_refcounts(opts.subsys_mask);
1367 /* re-populate subsystem files */
1368 cgroup_populate_dir(cgrp, false, added_mask);
1370 if (opts.release_agent)
1371 strcpy(root->release_agent_path, opts.release_agent);
1373 kfree(opts.release_agent);
1375 mutex_unlock(&cgroup_root_mutex);
1376 mutex_unlock(&cgroup_mutex);
1377 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1381 static const struct super_operations cgroup_ops = {
1382 .statfs = simple_statfs,
1383 .drop_inode = generic_delete_inode,
1384 .show_options = cgroup_show_options,
1385 .remount_fs = cgroup_remount,
1388 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1390 INIT_LIST_HEAD(&cgrp->sibling);
1391 INIT_LIST_HEAD(&cgrp->children);
1392 INIT_LIST_HEAD(&cgrp->files);
1393 INIT_LIST_HEAD(&cgrp->css_sets);
1394 INIT_LIST_HEAD(&cgrp->allcg_node);
1395 INIT_LIST_HEAD(&cgrp->release_list);
1396 INIT_LIST_HEAD(&cgrp->pidlists);
1397 mutex_init(&cgrp->pidlist_mutex);
1398 INIT_LIST_HEAD(&cgrp->event_list);
1399 spin_lock_init(&cgrp->event_list_lock);
1400 simple_xattrs_init(&cgrp->xattrs);
1403 static void init_cgroup_root(struct cgroupfs_root *root)
1405 struct cgroup *cgrp = &root->top_cgroup;
1407 INIT_LIST_HEAD(&root->subsys_list);
1408 INIT_LIST_HEAD(&root->root_list);
1409 INIT_LIST_HEAD(&root->allcg_list);
1410 root->number_of_cgroups = 1;
1412 cgrp->top_cgroup = cgrp;
1413 init_cgroup_housekeeping(cgrp);
1414 list_add_tail(&cgrp->allcg_node, &root->allcg_list);
1417 static bool init_root_id(struct cgroupfs_root *root)
1422 if (!ida_pre_get(&hierarchy_ida, GFP_KERNEL))
1424 spin_lock(&hierarchy_id_lock);
1425 /* Try to allocate the next unused ID */
1426 ret = ida_get_new_above(&hierarchy_ida, next_hierarchy_id,
1427 &root->hierarchy_id);
1429 /* Try again starting from 0 */
1430 ret = ida_get_new(&hierarchy_ida, &root->hierarchy_id);
1432 next_hierarchy_id = root->hierarchy_id + 1;
1433 } else if (ret != -EAGAIN) {
1434 /* Can only get here if the 31-bit IDR is full ... */
1437 spin_unlock(&hierarchy_id_lock);
1442 static int cgroup_test_super(struct super_block *sb, void *data)
1444 struct cgroup_sb_opts *opts = data;
1445 struct cgroupfs_root *root = sb->s_fs_info;
1447 /* If we asked for a name then it must match */
1448 if (opts->name && strcmp(opts->name, root->name))
1452 * If we asked for subsystems (or explicitly for no
1453 * subsystems) then they must match
1455 if ((opts->subsys_mask || opts->none)
1456 && (opts->subsys_mask != root->subsys_mask))
1462 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1464 struct cgroupfs_root *root;
1466 if (!opts->subsys_mask && !opts->none)
1469 root = kzalloc(sizeof(*root), GFP_KERNEL);
1471 return ERR_PTR(-ENOMEM);
1473 if (!init_root_id(root)) {
1475 return ERR_PTR(-ENOMEM);
1477 init_cgroup_root(root);
1479 root->subsys_mask = opts->subsys_mask;
1480 root->flags = opts->flags;
1481 ida_init(&root->cgroup_ida);
1482 if (opts->release_agent)
1483 strcpy(root->release_agent_path, opts->release_agent);
1485 strcpy(root->name, opts->name);
1486 if (opts->cpuset_clone_children)
1487 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1491 static void cgroup_drop_root(struct cgroupfs_root *root)
1496 BUG_ON(!root->hierarchy_id);
1497 spin_lock(&hierarchy_id_lock);
1498 ida_remove(&hierarchy_ida, root->hierarchy_id);
1499 spin_unlock(&hierarchy_id_lock);
1500 ida_destroy(&root->cgroup_ida);
1504 static int cgroup_set_super(struct super_block *sb, void *data)
1507 struct cgroup_sb_opts *opts = data;
1509 /* If we don't have a new root, we can't set up a new sb */
1510 if (!opts->new_root)
1513 BUG_ON(!opts->subsys_mask && !opts->none);
1515 ret = set_anon_super(sb, NULL);
1519 sb->s_fs_info = opts->new_root;
1520 opts->new_root->sb = sb;
1522 sb->s_blocksize = PAGE_CACHE_SIZE;
1523 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1524 sb->s_magic = CGROUP_SUPER_MAGIC;
1525 sb->s_op = &cgroup_ops;
1530 static int cgroup_get_rootdir(struct super_block *sb)
1532 static const struct dentry_operations cgroup_dops = {
1533 .d_iput = cgroup_diput,
1534 .d_delete = cgroup_delete,
1537 struct inode *inode =
1538 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1543 inode->i_fop = &simple_dir_operations;
1544 inode->i_op = &cgroup_dir_inode_operations;
1545 /* directories start off with i_nlink == 2 (for "." entry) */
1547 sb->s_root = d_make_root(inode);
1550 /* for everything else we want ->d_op set */
1551 sb->s_d_op = &cgroup_dops;
1555 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1556 int flags, const char *unused_dev_name,
1559 struct cgroup_sb_opts opts;
1560 struct cgroupfs_root *root;
1562 struct super_block *sb;
1563 struct cgroupfs_root *new_root;
1564 struct inode *inode;
1566 /* First find the desired set of subsystems */
1567 mutex_lock(&cgroup_mutex);
1568 ret = parse_cgroupfs_options(data, &opts);
1569 mutex_unlock(&cgroup_mutex);
1574 * Allocate a new cgroup root. We may not need it if we're
1575 * reusing an existing hierarchy.
1577 new_root = cgroup_root_from_opts(&opts);
1578 if (IS_ERR(new_root)) {
1579 ret = PTR_ERR(new_root);
1582 opts.new_root = new_root;
1584 /* Locate an existing or new sb for this hierarchy */
1585 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1588 cgroup_drop_root(opts.new_root);
1592 root = sb->s_fs_info;
1594 if (root == opts.new_root) {
1595 /* We used the new root structure, so this is a new hierarchy */
1596 struct list_head tmp_cg_links;
1597 struct cgroup *root_cgrp = &root->top_cgroup;
1598 struct cgroupfs_root *existing_root;
1599 const struct cred *cred;
1602 BUG_ON(sb->s_root != NULL);
1604 ret = cgroup_get_rootdir(sb);
1606 goto drop_new_super;
1607 inode = sb->s_root->d_inode;
1609 mutex_lock(&inode->i_mutex);
1610 mutex_lock(&cgroup_mutex);
1611 mutex_lock(&cgroup_root_mutex);
1613 /* Check for name clashes with existing mounts */
1615 if (strlen(root->name))
1616 for_each_active_root(existing_root)
1617 if (!strcmp(existing_root->name, root->name))
1621 * We're accessing css_set_count without locking
1622 * css_set_lock here, but that's OK - it can only be
1623 * increased by someone holding cgroup_lock, and
1624 * that's us. The worst that can happen is that we
1625 * have some link structures left over
1627 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
1631 ret = rebind_subsystems(root, root->subsys_mask);
1632 if (ret == -EBUSY) {
1633 free_cg_links(&tmp_cg_links);
1637 * There must be no failure case after here, since rebinding
1638 * takes care of subsystems' refcounts, which are explicitly
1639 * dropped in the failure exit path.
1642 /* EBUSY should be the only error here */
1645 list_add(&root->root_list, &roots);
1648 sb->s_root->d_fsdata = root_cgrp;
1649 root->top_cgroup.dentry = sb->s_root;
1651 /* Link the top cgroup in this hierarchy into all
1652 * the css_set objects */
1653 write_lock(&css_set_lock);
1654 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
1655 struct hlist_head *hhead = &css_set_table[i];
1656 struct hlist_node *node;
1659 hlist_for_each_entry(cg, node, hhead, hlist)
1660 link_css_set(&tmp_cg_links, cg, root_cgrp);
1662 write_unlock(&css_set_lock);
1664 free_cg_links(&tmp_cg_links);
1666 BUG_ON(!list_empty(&root_cgrp->children));
1667 BUG_ON(root->number_of_cgroups != 1);
1669 cred = override_creds(&init_cred);
1670 cgroup_populate_dir(root_cgrp, true, root->subsys_mask);
1672 mutex_unlock(&cgroup_root_mutex);
1673 mutex_unlock(&cgroup_mutex);
1674 mutex_unlock(&inode->i_mutex);
1677 * We re-used an existing hierarchy - the new root (if
1678 * any) is not needed
1680 cgroup_drop_root(opts.new_root);
1681 /* no subsys rebinding, so refcounts don't change */
1682 drop_parsed_module_refcounts(opts.subsys_mask);
1685 kfree(opts.release_agent);
1687 return dget(sb->s_root);
1690 mutex_unlock(&cgroup_root_mutex);
1691 mutex_unlock(&cgroup_mutex);
1692 mutex_unlock(&inode->i_mutex);
1694 deactivate_locked_super(sb);
1696 drop_parsed_module_refcounts(opts.subsys_mask);
1698 kfree(opts.release_agent);
1700 return ERR_PTR(ret);
1703 static void cgroup_kill_sb(struct super_block *sb) {
1704 struct cgroupfs_root *root = sb->s_fs_info;
1705 struct cgroup *cgrp = &root->top_cgroup;
1707 struct cg_cgroup_link *link;
1708 struct cg_cgroup_link *saved_link;
1712 BUG_ON(root->number_of_cgroups != 1);
1713 BUG_ON(!list_empty(&cgrp->children));
1715 mutex_lock(&cgroup_mutex);
1716 mutex_lock(&cgroup_root_mutex);
1718 /* Rebind all subsystems back to the default hierarchy */
1719 ret = rebind_subsystems(root, 0);
1720 /* Shouldn't be able to fail ... */
1724 * Release all the links from css_sets to this hierarchy's
1727 write_lock(&css_set_lock);
1729 list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1731 list_del(&link->cg_link_list);
1732 list_del(&link->cgrp_link_list);
1735 write_unlock(&css_set_lock);
1737 if (!list_empty(&root->root_list)) {
1738 list_del(&root->root_list);
1742 mutex_unlock(&cgroup_root_mutex);
1743 mutex_unlock(&cgroup_mutex);
1745 simple_xattrs_free(&cgrp->xattrs);
1747 kill_litter_super(sb);
1748 cgroup_drop_root(root);
1751 static struct file_system_type cgroup_fs_type = {
1753 .mount = cgroup_mount,
1754 .kill_sb = cgroup_kill_sb,
1757 static struct kobject *cgroup_kobj;
1760 * cgroup_path - generate the path of a cgroup
1761 * @cgrp: the cgroup in question
1762 * @buf: the buffer to write the path into
1763 * @buflen: the length of the buffer
1765 * Called with cgroup_mutex held or else with an RCU-protected cgroup
1766 * reference. Writes path of cgroup into buf. Returns 0 on success,
1769 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1771 struct dentry *dentry = cgrp->dentry;
1774 rcu_lockdep_assert(rcu_read_lock_held() || cgroup_lock_is_held(),
1775 "cgroup_path() called without proper locking");
1777 if (!dentry || cgrp == dummytop) {
1779 * Inactive subsystems have no dentry for their root
1786 start = buf + buflen - 1;
1790 int len = dentry->d_name.len;
1792 if ((start -= len) < buf)
1793 return -ENAMETOOLONG;
1794 memcpy(start, dentry->d_name.name, len);
1795 cgrp = cgrp->parent;
1799 dentry = cgrp->dentry;
1803 return -ENAMETOOLONG;
1806 memmove(buf, start, buf + buflen - start);
1809 EXPORT_SYMBOL_GPL(cgroup_path);
1812 * Control Group taskset
1814 struct task_and_cgroup {
1815 struct task_struct *task;
1816 struct cgroup *cgrp;
1820 struct cgroup_taskset {
1821 struct task_and_cgroup single;
1822 struct flex_array *tc_array;
1825 struct cgroup *cur_cgrp;
1829 * cgroup_taskset_first - reset taskset and return the first task
1830 * @tset: taskset of interest
1832 * @tset iteration is initialized and the first task is returned.
1834 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1836 if (tset->tc_array) {
1838 return cgroup_taskset_next(tset);
1840 tset->cur_cgrp = tset->single.cgrp;
1841 return tset->single.task;
1844 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1847 * cgroup_taskset_next - iterate to the next task in taskset
1848 * @tset: taskset of interest
1850 * Return the next task in @tset. Iteration must have been initialized
1851 * with cgroup_taskset_first().
1853 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1855 struct task_and_cgroup *tc;
1857 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1860 tc = flex_array_get(tset->tc_array, tset->idx++);
1861 tset->cur_cgrp = tc->cgrp;
1864 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1867 * cgroup_taskset_cur_cgroup - return the matching cgroup for the current task
1868 * @tset: taskset of interest
1870 * Return the cgroup for the current (last returned) task of @tset. This
1871 * function must be preceded by either cgroup_taskset_first() or
1872 * cgroup_taskset_next().
1874 struct cgroup *cgroup_taskset_cur_cgroup(struct cgroup_taskset *tset)
1876 return tset->cur_cgrp;
1878 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_cgroup);
1881 * cgroup_taskset_size - return the number of tasks in taskset
1882 * @tset: taskset of interest
1884 int cgroup_taskset_size(struct cgroup_taskset *tset)
1886 return tset->tc_array ? tset->tc_array_len : 1;
1888 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1892 * cgroup_task_migrate - move a task from one cgroup to another.
1894 * Must be called with cgroup_mutex and threadgroup locked.
1896 static void cgroup_task_migrate(struct cgroup *cgrp, struct cgroup *oldcgrp,
1897 struct task_struct *tsk, struct css_set *newcg)
1899 struct css_set *oldcg;
1902 * We are synchronized through threadgroup_lock() against PF_EXITING
1903 * setting such that we can't race against cgroup_exit() changing the
1904 * css_set to init_css_set and dropping the old one.
1906 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1907 oldcg = tsk->cgroups;
1910 rcu_assign_pointer(tsk->cgroups, newcg);
1913 /* Update the css_set linked lists if we're using them */
1914 write_lock(&css_set_lock);
1915 if (!list_empty(&tsk->cg_list))
1916 list_move(&tsk->cg_list, &newcg->tasks);
1917 write_unlock(&css_set_lock);
1920 * We just gained a reference on oldcg by taking it from the task. As
1921 * trading it for newcg is protected by cgroup_mutex, we're safe to drop
1922 * it here; it will be freed under RCU.
1924 set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1929 * cgroup_attach_task - attach task 'tsk' to cgroup 'cgrp'
1930 * @cgrp: the cgroup the task is attaching to
1931 * @tsk: the task to be attached
1933 * Call with cgroup_mutex and threadgroup locked. May take task_lock of
1936 int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
1939 struct cgroup_subsys *ss, *failed_ss = NULL;
1940 struct cgroup *oldcgrp;
1941 struct cgroupfs_root *root = cgrp->root;
1942 struct cgroup_taskset tset = { };
1943 struct css_set *newcg;
1945 /* @tsk either already exited or can't exit until the end */
1946 if (tsk->flags & PF_EXITING)
1949 /* Nothing to do if the task is already in that cgroup */
1950 oldcgrp = task_cgroup_from_root(tsk, root);
1951 if (cgrp == oldcgrp)
1954 tset.single.task = tsk;
1955 tset.single.cgrp = oldcgrp;
1957 for_each_subsys(root, ss) {
1958 if (ss->can_attach) {
1959 retval = ss->can_attach(cgrp, &tset);
1962 * Remember on which subsystem the can_attach()
1963 * failed, so that we only call cancel_attach()
1964 * against the subsystems whose can_attach()
1965 * succeeded. (See below)
1973 newcg = find_css_set(tsk->cgroups, cgrp);
1979 cgroup_task_migrate(cgrp, oldcgrp, tsk, newcg);
1981 for_each_subsys(root, ss) {
1983 ss->attach(cgrp, &tset);
1989 for_each_subsys(root, ss) {
1990 if (ss == failed_ss)
1992 * This subsystem was the one that failed the
1993 * can_attach() check earlier, so we don't need
1994 * to call cancel_attach() against it or any
1995 * remaining subsystems.
1998 if (ss->cancel_attach)
1999 ss->cancel_attach(cgrp, &tset);
2006 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2007 * @from: attach to all cgroups of a given task
2008 * @tsk: the task to be attached
2010 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2012 struct cgroupfs_root *root;
2016 for_each_active_root(root) {
2017 struct cgroup *from_cg = task_cgroup_from_root(from, root);
2019 retval = cgroup_attach_task(from_cg, tsk);
2027 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2030 * cgroup_attach_proc - attach all threads in a threadgroup to a cgroup
2031 * @cgrp: the cgroup to attach to
2032 * @leader: the threadgroup leader task_struct of the group to be attached
2034 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
2035 * task_lock of each thread in leader's threadgroup individually in turn.
2037 static int cgroup_attach_proc(struct cgroup *cgrp, struct task_struct *leader)
2039 int retval, i, group_size;
2040 struct cgroup_subsys *ss, *failed_ss = NULL;
2041 /* guaranteed to be initialized later, but the compiler needs this */
2042 struct cgroupfs_root *root = cgrp->root;
2043 /* threadgroup list cursor and array */
2044 struct task_struct *tsk;
2045 struct task_and_cgroup *tc;
2046 struct flex_array *group;
2047 struct cgroup_taskset tset = { };
2050 * step 0: in order to do expensive, possibly blocking operations for
2051 * every thread, we cannot iterate the thread group list, since it needs
2052 * rcu or tasklist locked. instead, build an array of all threads in the
2053 * group - group_rwsem prevents new threads from appearing, and if
2054 * threads exit, this will just be an over-estimate.
2056 group_size = get_nr_threads(leader);
2057 /* flex_array supports very large thread-groups better than kmalloc. */
2058 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
2061 /* pre-allocate to guarantee space while iterating in rcu read-side. */
2062 retval = flex_array_prealloc(group, 0, group_size - 1, GFP_KERNEL);
2064 goto out_free_group_list;
2069 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2070 * already PF_EXITING could be freed from underneath us unless we
2071 * take an rcu_read_lock.
2075 struct task_and_cgroup ent;
2077 /* @tsk either already exited or can't exit until the end */
2078 if (tsk->flags & PF_EXITING)
2081 /* as per above, nr_threads may decrease, but not increase. */
2082 BUG_ON(i >= group_size);
2084 ent.cgrp = task_cgroup_from_root(tsk, root);
2085 /* nothing to do if this task is already in the cgroup */
2086 if (ent.cgrp == cgrp)
2089 * saying GFP_ATOMIC has no effect here because we did prealloc
2090 * earlier, but it's good form to communicate our expectations.
2092 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
2093 BUG_ON(retval != 0);
2095 } while_each_thread(leader, tsk);
2097 /* remember the number of threads in the array for later. */
2099 tset.tc_array = group;
2100 tset.tc_array_len = group_size;
2102 /* methods shouldn't be called if no task is actually migrating */
2105 goto out_free_group_list;
2108 * step 1: check that we can legitimately attach to the cgroup.
2110 for_each_subsys(root, ss) {
2111 if (ss->can_attach) {
2112 retval = ss->can_attach(cgrp, &tset);
2115 goto out_cancel_attach;
2121 * step 2: make sure css_sets exist for all threads to be migrated.
2122 * we use find_css_set, which allocates a new one if necessary.
2124 for (i = 0; i < group_size; i++) {
2125 tc = flex_array_get(group, i);
2126 tc->cg = find_css_set(tc->task->cgroups, cgrp);
2129 goto out_put_css_set_refs;
2134 * step 3: now that we're guaranteed success wrt the css_sets,
2135 * proceed to move all tasks to the new cgroup. There are no
2136 * failure cases after here, so this is the commit point.
2138 for (i = 0; i < group_size; i++) {
2139 tc = flex_array_get(group, i);
2140 cgroup_task_migrate(cgrp, tc->cgrp, tc->task, tc->cg);
2142 /* nothing is sensitive to fork() after this point. */
2145 * step 4: do subsystem attach callbacks.
2147 for_each_subsys(root, ss) {
2149 ss->attach(cgrp, &tset);
2153 * step 5: success! and cleanup
2157 out_put_css_set_refs:
2159 for (i = 0; i < group_size; i++) {
2160 tc = flex_array_get(group, i);
2163 put_css_set(tc->cg);
2168 for_each_subsys(root, ss) {
2169 if (ss == failed_ss)
2171 if (ss->cancel_attach)
2172 ss->cancel_attach(cgrp, &tset);
2175 out_free_group_list:
2176 flex_array_free(group);
2181 * Find the task_struct of the task to attach by vpid and pass it along to the
2182 * function to attach either it or all tasks in its threadgroup. Will lock
2183 * cgroup_mutex and threadgroup; may take task_lock of task.
2185 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2187 struct task_struct *tsk;
2188 const struct cred *cred = current_cred(), *tcred;
2191 if (!cgroup_lock_live_group(cgrp))
2197 tsk = find_task_by_vpid(pid);
2201 goto out_unlock_cgroup;
2204 * even if we're attaching all tasks in the thread group, we
2205 * only need to check permissions on one of them.
2207 tcred = __task_cred(tsk);
2208 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2209 !uid_eq(cred->euid, tcred->uid) &&
2210 !uid_eq(cred->euid, tcred->suid)) {
2213 goto out_unlock_cgroup;
2219 tsk = tsk->group_leader;
2222 * Workqueue threads may acquire PF_THREAD_BOUND and become
2223 * trapped in a cpuset, or RT worker may be born in a cgroup
2224 * with no rt_runtime allocated. Just say no.
2226 if (tsk == kthreadd_task || (tsk->flags & PF_THREAD_BOUND)) {
2229 goto out_unlock_cgroup;
2232 get_task_struct(tsk);
2235 threadgroup_lock(tsk);
2237 if (!thread_group_leader(tsk)) {
2239 * a race with de_thread from another thread's exec()
2240 * may strip us of our leadership, if this happens,
2241 * there is no choice but to throw this task away and
2242 * try again; this is
2243 * "double-double-toil-and-trouble-check locking".
2245 threadgroup_unlock(tsk);
2246 put_task_struct(tsk);
2247 goto retry_find_task;
2249 ret = cgroup_attach_proc(cgrp, tsk);
2251 ret = cgroup_attach_task(cgrp, tsk);
2252 threadgroup_unlock(tsk);
2254 put_task_struct(tsk);
2260 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
2262 return attach_task_by_pid(cgrp, pid, false);
2265 static int cgroup_procs_write(struct cgroup *cgrp, struct cftype *cft, u64 tgid)
2267 return attach_task_by_pid(cgrp, tgid, true);
2271 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
2272 * @cgrp: the cgroup to be checked for liveness
2274 * On success, returns true; the lock should be later released with
2275 * cgroup_unlock(). On failure returns false with no lock held.
2277 bool cgroup_lock_live_group(struct cgroup *cgrp)
2279 mutex_lock(&cgroup_mutex);
2280 if (cgroup_is_removed(cgrp)) {
2281 mutex_unlock(&cgroup_mutex);
2286 EXPORT_SYMBOL_GPL(cgroup_lock_live_group);
2288 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
2291 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
2292 if (strlen(buffer) >= PATH_MAX)
2294 if (!cgroup_lock_live_group(cgrp))
2296 mutex_lock(&cgroup_root_mutex);
2297 strcpy(cgrp->root->release_agent_path, buffer);
2298 mutex_unlock(&cgroup_root_mutex);
2303 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
2304 struct seq_file *seq)
2306 if (!cgroup_lock_live_group(cgrp))
2308 seq_puts(seq, cgrp->root->release_agent_path);
2309 seq_putc(seq, '\n');
2314 /* A buffer size big enough for numbers or short strings */
2315 #define CGROUP_LOCAL_BUFFER_SIZE 64
2317 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
2319 const char __user *userbuf,
2320 size_t nbytes, loff_t *unused_ppos)
2322 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
2328 if (nbytes >= sizeof(buffer))
2330 if (copy_from_user(buffer, userbuf, nbytes))
2333 buffer[nbytes] = 0; /* nul-terminate */
2334 if (cft->write_u64) {
2335 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
2338 retval = cft->write_u64(cgrp, cft, val);
2340 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
2343 retval = cft->write_s64(cgrp, cft, val);
2350 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
2352 const char __user *userbuf,
2353 size_t nbytes, loff_t *unused_ppos)
2355 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
2357 size_t max_bytes = cft->max_write_len;
2358 char *buffer = local_buffer;
2361 max_bytes = sizeof(local_buffer) - 1;
2362 if (nbytes >= max_bytes)
2364 /* Allocate a dynamic buffer if we need one */
2365 if (nbytes >= sizeof(local_buffer)) {
2366 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2370 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2375 buffer[nbytes] = 0; /* nul-terminate */
2376 retval = cft->write_string(cgrp, cft, strstrip(buffer));
2380 if (buffer != local_buffer)
2385 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2386 size_t nbytes, loff_t *ppos)
2388 struct cftype *cft = __d_cft(file->f_dentry);
2389 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2391 if (cgroup_is_removed(cgrp))
2394 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
2395 if (cft->write_u64 || cft->write_s64)
2396 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
2397 if (cft->write_string)
2398 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
2400 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
2401 return ret ? ret : nbytes;
2406 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
2408 char __user *buf, size_t nbytes,
2411 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2412 u64 val = cft->read_u64(cgrp, cft);
2413 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2415 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2418 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
2420 char __user *buf, size_t nbytes,
2423 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2424 s64 val = cft->read_s64(cgrp, cft);
2425 int len = sprintf(tmp, "%lld\n", (long long) val);
2427 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2430 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2431 size_t nbytes, loff_t *ppos)
2433 struct cftype *cft = __d_cft(file->f_dentry);
2434 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2436 if (cgroup_is_removed(cgrp))
2440 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
2442 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
2444 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
2449 * seqfile ops/methods for returning structured data. Currently just
2450 * supports string->u64 maps, but can be extended in future.
2453 struct cgroup_seqfile_state {
2455 struct cgroup *cgroup;
2458 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2460 struct seq_file *sf = cb->state;
2461 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2464 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2466 struct cgroup_seqfile_state *state = m->private;
2467 struct cftype *cft = state->cft;
2468 if (cft->read_map) {
2469 struct cgroup_map_cb cb = {
2470 .fill = cgroup_map_add,
2473 return cft->read_map(state->cgroup, cft, &cb);
2475 return cft->read_seq_string(state->cgroup, cft, m);
2478 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
2480 struct seq_file *seq = file->private_data;
2481 kfree(seq->private);
2482 return single_release(inode, file);
2485 static const struct file_operations cgroup_seqfile_operations = {
2487 .write = cgroup_file_write,
2488 .llseek = seq_lseek,
2489 .release = cgroup_seqfile_release,
2492 static int cgroup_file_open(struct inode *inode, struct file *file)
2497 err = generic_file_open(inode, file);
2500 cft = __d_cft(file->f_dentry);
2502 if (cft->read_map || cft->read_seq_string) {
2503 struct cgroup_seqfile_state *state =
2504 kzalloc(sizeof(*state), GFP_USER);
2508 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
2509 file->f_op = &cgroup_seqfile_operations;
2510 err = single_open(file, cgroup_seqfile_show, state);
2513 } else if (cft->open)
2514 err = cft->open(inode, file);
2521 static int cgroup_file_release(struct inode *inode, struct file *file)
2523 struct cftype *cft = __d_cft(file->f_dentry);
2525 return cft->release(inode, file);
2530 * cgroup_rename - Only allow simple rename of directories in place.
2532 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2533 struct inode *new_dir, struct dentry *new_dentry)
2535 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2537 if (new_dentry->d_inode)
2539 if (old_dir != new_dir)
2541 return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2544 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2546 if (S_ISDIR(dentry->d_inode->i_mode))
2547 return &__d_cgrp(dentry)->xattrs;
2549 return &__d_cft(dentry)->xattrs;
2552 static inline int xattr_enabled(struct dentry *dentry)
2554 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2555 return test_bit(ROOT_XATTR, &root->flags);
2558 static bool is_valid_xattr(const char *name)
2560 if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2561 !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2566 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2567 const void *val, size_t size, int flags)
2569 if (!xattr_enabled(dentry))
2571 if (!is_valid_xattr(name))
2573 return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2576 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2578 if (!xattr_enabled(dentry))
2580 if (!is_valid_xattr(name))
2582 return simple_xattr_remove(__d_xattrs(dentry), name);
2585 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2586 void *buf, size_t size)
2588 if (!xattr_enabled(dentry))
2590 if (!is_valid_xattr(name))
2592 return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2595 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2597 if (!xattr_enabled(dentry))
2599 return simple_xattr_list(__d_xattrs(dentry), buf, size);
2602 static const struct file_operations cgroup_file_operations = {
2603 .read = cgroup_file_read,
2604 .write = cgroup_file_write,
2605 .llseek = generic_file_llseek,
2606 .open = cgroup_file_open,
2607 .release = cgroup_file_release,
2610 static const struct inode_operations cgroup_file_inode_operations = {
2611 .setxattr = cgroup_setxattr,
2612 .getxattr = cgroup_getxattr,
2613 .listxattr = cgroup_listxattr,
2614 .removexattr = cgroup_removexattr,
2617 static const struct inode_operations cgroup_dir_inode_operations = {
2618 .lookup = cgroup_lookup,
2619 .mkdir = cgroup_mkdir,
2620 .rmdir = cgroup_rmdir,
2621 .rename = cgroup_rename,
2622 .setxattr = cgroup_setxattr,
2623 .getxattr = cgroup_getxattr,
2624 .listxattr = cgroup_listxattr,
2625 .removexattr = cgroup_removexattr,
2628 static struct dentry *cgroup_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
2630 if (dentry->d_name.len > NAME_MAX)
2631 return ERR_PTR(-ENAMETOOLONG);
2632 d_add(dentry, NULL);
2637 * Check if a file is a control file
2639 static inline struct cftype *__file_cft(struct file *file)
2641 if (file->f_dentry->d_inode->i_fop != &cgroup_file_operations)
2642 return ERR_PTR(-EINVAL);
2643 return __d_cft(file->f_dentry);
2646 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2647 struct super_block *sb)
2649 struct inode *inode;
2653 if (dentry->d_inode)
2656 inode = cgroup_new_inode(mode, sb);
2660 if (S_ISDIR(mode)) {
2661 inode->i_op = &cgroup_dir_inode_operations;
2662 inode->i_fop = &simple_dir_operations;
2664 /* start off with i_nlink == 2 (for "." entry) */
2666 inc_nlink(dentry->d_parent->d_inode);
2669 * Control reaches here with cgroup_mutex held.
2670 * @inode->i_mutex should nest outside cgroup_mutex but we
2671 * want to populate it immediately without releasing
2672 * cgroup_mutex. As @inode isn't visible to anyone else
2673 * yet, trylock will always succeed without affecting
2676 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2677 } else if (S_ISREG(mode)) {
2679 inode->i_fop = &cgroup_file_operations;
2680 inode->i_op = &cgroup_file_inode_operations;
2682 d_instantiate(dentry, inode);
2683 dget(dentry); /* Extra count - pin the dentry in core */
2688 * cgroup_file_mode - deduce file mode of a control file
2689 * @cft: the control file in question
2691 * returns cft->mode if ->mode is not 0
2692 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2693 * returns S_IRUGO if it has only a read handler
2694 * returns S_IWUSR if it has only a write hander
2696 static umode_t cgroup_file_mode(const struct cftype *cft)
2703 if (cft->read || cft->read_u64 || cft->read_s64 ||
2704 cft->read_map || cft->read_seq_string)
2707 if (cft->write || cft->write_u64 || cft->write_s64 ||
2708 cft->write_string || cft->trigger)
2714 static int cgroup_add_file(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2717 struct dentry *dir = cgrp->dentry;
2718 struct cgroup *parent = __d_cgrp(dir);
2719 struct dentry *dentry;
2723 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2725 simple_xattrs_init(&cft->xattrs);
2727 if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) {
2728 strcpy(name, subsys->name);
2731 strcat(name, cft->name);
2733 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2735 cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2739 dentry = lookup_one_len(name, dir, strlen(name));
2740 if (IS_ERR(dentry)) {
2741 error = PTR_ERR(dentry);
2745 mode = cgroup_file_mode(cft);
2746 error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2748 cfe->type = (void *)cft;
2749 cfe->dentry = dentry;
2750 dentry->d_fsdata = cfe;
2751 list_add_tail(&cfe->node, &parent->files);
2760 static int cgroup_addrm_files(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2761 struct cftype cfts[], bool is_add)
2766 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2767 /* does cft->flags tell us to skip this file on @cgrp? */
2768 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2770 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2774 err = cgroup_add_file(cgrp, subsys, cft);
2776 err = cgroup_rm_file(cgrp, cft);
2778 pr_warning("cgroup_addrm_files: failed to %s %s, err=%d\n",
2779 is_add ? "add" : "remove", cft->name, err);
2786 static DEFINE_MUTEX(cgroup_cft_mutex);
2788 static void cgroup_cfts_prepare(void)
2789 __acquires(&cgroup_cft_mutex) __acquires(&cgroup_mutex)
2792 * Thanks to the entanglement with vfs inode locking, we can't walk
2793 * the existing cgroups under cgroup_mutex and create files.
2794 * Instead, we increment reference on all cgroups and build list of
2795 * them using @cgrp->cft_q_node. Grab cgroup_cft_mutex to ensure
2796 * exclusive access to the field.
2798 mutex_lock(&cgroup_cft_mutex);
2799 mutex_lock(&cgroup_mutex);
2802 static void cgroup_cfts_commit(struct cgroup_subsys *ss,
2803 struct cftype *cfts, bool is_add)
2804 __releases(&cgroup_mutex) __releases(&cgroup_cft_mutex)
2807 struct cgroup *cgrp, *n;
2809 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2810 if (cfts && ss->root != &rootnode) {
2811 list_for_each_entry(cgrp, &ss->root->allcg_list, allcg_node) {
2813 list_add_tail(&cgrp->cft_q_node, &pending);
2817 mutex_unlock(&cgroup_mutex);
2820 * All new cgroups will see @cfts update on @ss->cftsets. Add/rm
2821 * files for all cgroups which were created before.
2823 list_for_each_entry_safe(cgrp, n, &pending, cft_q_node) {
2824 struct inode *inode = cgrp->dentry->d_inode;
2826 mutex_lock(&inode->i_mutex);
2827 mutex_lock(&cgroup_mutex);
2828 if (!cgroup_is_removed(cgrp))
2829 cgroup_addrm_files(cgrp, ss, cfts, is_add);
2830 mutex_unlock(&cgroup_mutex);
2831 mutex_unlock(&inode->i_mutex);
2833 list_del_init(&cgrp->cft_q_node);
2837 mutex_unlock(&cgroup_cft_mutex);
2841 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2842 * @ss: target cgroup subsystem
2843 * @cfts: zero-length name terminated array of cftypes
2845 * Register @cfts to @ss. Files described by @cfts are created for all
2846 * existing cgroups to which @ss is attached and all future cgroups will
2847 * have them too. This function can be called anytime whether @ss is
2850 * Returns 0 on successful registration, -errno on failure. Note that this
2851 * function currently returns 0 as long as @cfts registration is successful
2852 * even if some file creation attempts on existing cgroups fail.
2854 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2856 struct cftype_set *set;
2858 set = kzalloc(sizeof(*set), GFP_KERNEL);
2862 cgroup_cfts_prepare();
2864 list_add_tail(&set->node, &ss->cftsets);
2865 cgroup_cfts_commit(ss, cfts, true);
2869 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2872 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2873 * @ss: target cgroup subsystem
2874 * @cfts: zero-length name terminated array of cftypes
2876 * Unregister @cfts from @ss. Files described by @cfts are removed from
2877 * all existing cgroups to which @ss is attached and all future cgroups
2878 * won't have them either. This function can be called anytime whether @ss
2879 * is attached or not.
2881 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2882 * registered with @ss.
2884 int cgroup_rm_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2886 struct cftype_set *set;
2888 cgroup_cfts_prepare();
2890 list_for_each_entry(set, &ss->cftsets, node) {
2891 if (set->cfts == cfts) {
2892 list_del_init(&set->node);
2893 cgroup_cfts_commit(ss, cfts, false);
2898 cgroup_cfts_commit(ss, NULL, false);
2903 * cgroup_task_count - count the number of tasks in a cgroup.
2904 * @cgrp: the cgroup in question
2906 * Return the number of tasks in the cgroup.
2908 int cgroup_task_count(const struct cgroup *cgrp)
2911 struct cg_cgroup_link *link;
2913 read_lock(&css_set_lock);
2914 list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
2915 count += atomic_read(&link->cg->refcount);
2917 read_unlock(&css_set_lock);
2922 * Advance a list_head iterator. The iterator should be positioned at
2923 * the start of a css_set
2925 static void cgroup_advance_iter(struct cgroup *cgrp,
2926 struct cgroup_iter *it)
2928 struct list_head *l = it->cg_link;
2929 struct cg_cgroup_link *link;
2932 /* Advance to the next non-empty css_set */
2935 if (l == &cgrp->css_sets) {
2939 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
2941 } while (list_empty(&cg->tasks));
2943 it->task = cg->tasks.next;
2947 * To reduce the fork() overhead for systems that are not actually
2948 * using their cgroups capability, we don't maintain the lists running
2949 * through each css_set to its tasks until we see the list actually
2950 * used - in other words after the first call to cgroup_iter_start().
2952 static void cgroup_enable_task_cg_lists(void)
2954 struct task_struct *p, *g;
2955 write_lock(&css_set_lock);
2956 use_task_css_set_links = 1;
2958 * We need tasklist_lock because RCU is not safe against
2959 * while_each_thread(). Besides, a forking task that has passed
2960 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2961 * is not guaranteed to have its child immediately visible in the
2962 * tasklist if we walk through it with RCU.
2964 read_lock(&tasklist_lock);
2965 do_each_thread(g, p) {
2968 * We should check if the process is exiting, otherwise
2969 * it will race with cgroup_exit() in that the list
2970 * entry won't be deleted though the process has exited.
2972 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2973 list_add(&p->cg_list, &p->cgroups->tasks);
2975 } while_each_thread(g, p);
2976 read_unlock(&tasklist_lock);
2977 write_unlock(&css_set_lock);
2981 * cgroup_next_descendant_pre - find the next descendant for pre-order walk
2982 * @pos: the current position (%NULL to initiate traversal)
2983 * @cgroup: cgroup whose descendants to walk
2985 * To be used by cgroup_for_each_descendant_pre(). Find the next
2986 * descendant to visit for pre-order traversal of @cgroup's descendants.
2988 struct cgroup *cgroup_next_descendant_pre(struct cgroup *pos,
2989 struct cgroup *cgroup)
2991 struct cgroup *next;
2993 WARN_ON_ONCE(!rcu_read_lock_held());
2995 /* if first iteration, pretend we just visited @cgroup */
2997 if (list_empty(&cgroup->children))
3002 /* visit the first child if exists */
3003 next = list_first_or_null_rcu(&pos->children, struct cgroup, sibling);
3007 /* no child, visit my or the closest ancestor's next sibling */
3009 next = list_entry_rcu(pos->sibling.next, struct cgroup,
3011 if (&next->sibling != &pos->parent->children)
3015 } while (pos != cgroup);
3019 EXPORT_SYMBOL_GPL(cgroup_next_descendant_pre);
3021 static struct cgroup *cgroup_leftmost_descendant(struct cgroup *pos)
3023 struct cgroup *last;
3027 pos = list_first_or_null_rcu(&pos->children, struct cgroup,
3035 * cgroup_next_descendant_post - find the next descendant for post-order walk
3036 * @pos: the current position (%NULL to initiate traversal)
3037 * @cgroup: cgroup whose descendants to walk
3039 * To be used by cgroup_for_each_descendant_post(). Find the next
3040 * descendant to visit for post-order traversal of @cgroup's descendants.
3042 struct cgroup *cgroup_next_descendant_post(struct cgroup *pos,
3043 struct cgroup *cgroup)
3045 struct cgroup *next;
3047 WARN_ON_ONCE(!rcu_read_lock_held());
3049 /* if first iteration, visit the leftmost descendant */
3051 next = cgroup_leftmost_descendant(cgroup);
3052 return next != cgroup ? next : NULL;
3055 /* if there's an unvisited sibling, visit its leftmost descendant */
3056 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3057 if (&next->sibling != &pos->parent->children)
3058 return cgroup_leftmost_descendant(next);
3060 /* no sibling left, visit parent */
3062 return next != cgroup ? next : NULL;
3064 EXPORT_SYMBOL_GPL(cgroup_next_descendant_post);
3066 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
3067 __acquires(css_set_lock)
3070 * The first time anyone tries to iterate across a cgroup,
3071 * we need to enable the list linking each css_set to its
3072 * tasks, and fix up all existing tasks.
3074 if (!use_task_css_set_links)
3075 cgroup_enable_task_cg_lists();
3077 read_lock(&css_set_lock);
3078 it->cg_link = &cgrp->css_sets;
3079 cgroup_advance_iter(cgrp, it);
3082 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
3083 struct cgroup_iter *it)
3085 struct task_struct *res;
3086 struct list_head *l = it->task;
3087 struct cg_cgroup_link *link;
3089 /* If the iterator cg is NULL, we have no tasks */
3092 res = list_entry(l, struct task_struct, cg_list);
3093 /* Advance iterator to find next entry */
3095 link = list_entry(it->cg_link, struct cg_cgroup_link, cgrp_link_list);
3096 if (l == &link->cg->tasks) {
3097 /* We reached the end of this task list - move on to
3098 * the next cg_cgroup_link */
3099 cgroup_advance_iter(cgrp, it);
3106 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
3107 __releases(css_set_lock)
3109 read_unlock(&css_set_lock);
3112 static inline int started_after_time(struct task_struct *t1,
3113 struct timespec *time,
3114 struct task_struct *t2)
3116 int start_diff = timespec_compare(&t1->start_time, time);
3117 if (start_diff > 0) {
3119 } else if (start_diff < 0) {
3123 * Arbitrarily, if two processes started at the same
3124 * time, we'll say that the lower pointer value
3125 * started first. Note that t2 may have exited by now
3126 * so this may not be a valid pointer any longer, but
3127 * that's fine - it still serves to distinguish
3128 * between two tasks started (effectively) simultaneously.
3135 * This function is a callback from heap_insert() and is used to order
3137 * In this case we order the heap in descending task start time.
3139 static inline int started_after(void *p1, void *p2)
3141 struct task_struct *t1 = p1;
3142 struct task_struct *t2 = p2;
3143 return started_after_time(t1, &t2->start_time, t2);
3147 * cgroup_scan_tasks - iterate though all the tasks in a cgroup
3148 * @scan: struct cgroup_scanner containing arguments for the scan
3150 * Arguments include pointers to callback functions test_task() and
3152 * Iterate through all the tasks in a cgroup, calling test_task() for each,
3153 * and if it returns true, call process_task() for it also.
3154 * The test_task pointer may be NULL, meaning always true (select all tasks).
3155 * Effectively duplicates cgroup_iter_{start,next,end}()
3156 * but does not lock css_set_lock for the call to process_task().
3157 * The struct cgroup_scanner may be embedded in any structure of the caller's
3159 * It is guaranteed that process_task() will act on every task that
3160 * is a member of the cgroup for the duration of this call. This
3161 * function may or may not call process_task() for tasks that exit
3162 * or move to a different cgroup during the call, or are forked or
3163 * move into the cgroup during the call.
3165 * Note that test_task() may be called with locks held, and may in some
3166 * situations be called multiple times for the same task, so it should
3168 * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
3169 * pre-allocated and will be used for heap operations (and its "gt" member will
3170 * be overwritten), else a temporary heap will be used (allocation of which
3171 * may cause this function to fail).
3173 int cgroup_scan_tasks(struct cgroup_scanner *scan)
3176 struct cgroup_iter it;
3177 struct task_struct *p, *dropped;
3178 /* Never dereference latest_task, since it's not refcounted */
3179 struct task_struct *latest_task = NULL;
3180 struct ptr_heap tmp_heap;
3181 struct ptr_heap *heap;
3182 struct timespec latest_time = { 0, 0 };
3185 /* The caller supplied our heap and pre-allocated its memory */
3187 heap->gt = &started_after;
3189 /* We need to allocate our own heap memory */
3191 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3193 /* cannot allocate the heap */
3199 * Scan tasks in the cgroup, using the scanner's "test_task" callback
3200 * to determine which are of interest, and using the scanner's
3201 * "process_task" callback to process any of them that need an update.
3202 * Since we don't want to hold any locks during the task updates,
3203 * gather tasks to be processed in a heap structure.
3204 * The heap is sorted by descending task start time.
3205 * If the statically-sized heap fills up, we overflow tasks that
3206 * started later, and in future iterations only consider tasks that
3207 * started after the latest task in the previous pass. This
3208 * guarantees forward progress and that we don't miss any tasks.
3211 cgroup_iter_start(scan->cg, &it);
3212 while ((p = cgroup_iter_next(scan->cg, &it))) {
3214 * Only affect tasks that qualify per the caller's callback,
3215 * if he provided one
3217 if (scan->test_task && !scan->test_task(p, scan))
3220 * Only process tasks that started after the last task
3223 if (!started_after_time(p, &latest_time, latest_task))
3225 dropped = heap_insert(heap, p);
3226 if (dropped == NULL) {
3228 * The new task was inserted; the heap wasn't
3232 } else if (dropped != p) {
3234 * The new task was inserted, and pushed out a
3238 put_task_struct(dropped);
3241 * Else the new task was newer than anything already in
3242 * the heap and wasn't inserted
3245 cgroup_iter_end(scan->cg, &it);
3248 for (i = 0; i < heap->size; i++) {
3249 struct task_struct *q = heap->ptrs[i];
3251 latest_time = q->start_time;
3254 /* Process the task per the caller's callback */
3255 scan->process_task(q, scan);
3259 * If we had to process any tasks at all, scan again
3260 * in case some of them were in the middle of forking
3261 * children that didn't get processed.
3262 * Not the most efficient way to do it, but it avoids
3263 * having to take callback_mutex in the fork path
3267 if (heap == &tmp_heap)
3268 heap_free(&tmp_heap);
3273 * Stuff for reading the 'tasks'/'procs' files.
3275 * Reading this file can return large amounts of data if a cgroup has
3276 * *lots* of attached tasks. So it may need several calls to read(),
3277 * but we cannot guarantee that the information we produce is correct
3278 * unless we produce it entirely atomically.
3282 /* which pidlist file are we talking about? */
3283 enum cgroup_filetype {
3289 * A pidlist is a list of pids that virtually represents the contents of one
3290 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3291 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3294 struct cgroup_pidlist {
3296 * used to find which pidlist is wanted. doesn't change as long as
3297 * this particular list stays in the list.
3299 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3302 /* how many elements the above list has */
3304 /* how many files are using the current array */
3306 /* each of these stored in a list by its cgroup */
3307 struct list_head links;
3308 /* pointer to the cgroup we belong to, for list removal purposes */
3309 struct cgroup *owner;
3310 /* protects the other fields */
3311 struct rw_semaphore mutex;
3315 * The following two functions "fix" the issue where there are more pids
3316 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3317 * TODO: replace with a kernel-wide solution to this problem
3319 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3320 static void *pidlist_allocate(int count)
3322 if (PIDLIST_TOO_LARGE(count))
3323 return vmalloc(count * sizeof(pid_t));
3325 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3327 static void pidlist_free(void *p)
3329 if (is_vmalloc_addr(p))
3334 static void *pidlist_resize(void *p, int newcount)
3337 /* note: if new alloc fails, old p will still be valid either way */
3338 if (is_vmalloc_addr(p)) {
3339 newlist = vmalloc(newcount * sizeof(pid_t));
3342 memcpy(newlist, p, newcount * sizeof(pid_t));
3345 newlist = krealloc(p, newcount * sizeof(pid_t), GFP_KERNEL);
3351 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3352 * If the new stripped list is sufficiently smaller and there's enough memory
3353 * to allocate a new buffer, will let go of the unneeded memory. Returns the
3354 * number of unique elements.
3356 /* is the size difference enough that we should re-allocate the array? */
3357 #define PIDLIST_REALLOC_DIFFERENCE(old, new) ((old) - PAGE_SIZE >= (new))
3358 static int pidlist_uniq(pid_t **p, int length)
3365 * we presume the 0th element is unique, so i starts at 1. trivial
3366 * edge cases first; no work needs to be done for either
3368 if (length == 0 || length == 1)
3370 /* src and dest walk down the list; dest counts unique elements */
3371 for (src = 1; src < length; src++) {
3372 /* find next unique element */
3373 while (list[src] == list[src-1]) {
3378 /* dest always points to where the next unique element goes */
3379 list[dest] = list[src];
3384 * if the length difference is large enough, we want to allocate a
3385 * smaller buffer to save memory. if this fails due to out of memory,
3386 * we'll just stay with what we've got.
3388 if (PIDLIST_REALLOC_DIFFERENCE(length, dest)) {
3389 newlist = pidlist_resize(list, dest);
3396 static int cmppid(const void *a, const void *b)
3398 return *(pid_t *)a - *(pid_t *)b;
3402 * find the appropriate pidlist for our purpose (given procs vs tasks)
3403 * returns with the lock on that pidlist already held, and takes care
3404 * of the use count, or returns NULL with no locks held if we're out of
3407 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3408 enum cgroup_filetype type)
3410 struct cgroup_pidlist *l;
3411 /* don't need task_nsproxy() if we're looking at ourself */
3412 struct pid_namespace *ns = current->nsproxy->pid_ns;
3415 * We can't drop the pidlist_mutex before taking the l->mutex in case
3416 * the last ref-holder is trying to remove l from the list at the same
3417 * time. Holding the pidlist_mutex precludes somebody taking whichever
3418 * list we find out from under us - compare release_pid_array().
3420 mutex_lock(&cgrp->pidlist_mutex);
3421 list_for_each_entry(l, &cgrp->pidlists, links) {
3422 if (l->key.type == type && l->key.ns == ns) {
3423 /* make sure l doesn't vanish out from under us */
3424 down_write(&l->mutex);
3425 mutex_unlock(&cgrp->pidlist_mutex);
3429 /* entry not found; create a new one */
3430 l = kmalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3432 mutex_unlock(&cgrp->pidlist_mutex);
3435 init_rwsem(&l->mutex);
3436 down_write(&l->mutex);
3438 l->key.ns = get_pid_ns(ns);
3439 l->use_count = 0; /* don't increment here */
3442 list_add(&l->links, &cgrp->pidlists);
3443 mutex_unlock(&cgrp->pidlist_mutex);
3448 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3450 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3451 struct cgroup_pidlist **lp)
3455 int pid, n = 0; /* used for populating the array */
3456 struct cgroup_iter it;
3457 struct task_struct *tsk;
3458 struct cgroup_pidlist *l;
3461 * If cgroup gets more users after we read count, we won't have
3462 * enough space - tough. This race is indistinguishable to the
3463 * caller from the case that the additional cgroup users didn't
3464 * show up until sometime later on.
3466 length = cgroup_task_count(cgrp);
3467 array = pidlist_allocate(length);
3470 /* now, populate the array */
3471 cgroup_iter_start(cgrp, &it);
3472 while ((tsk = cgroup_iter_next(cgrp, &it))) {
3473 if (unlikely(n == length))
3475 /* get tgid or pid for procs or tasks file respectively */
3476 if (type == CGROUP_FILE_PROCS)
3477 pid = task_tgid_vnr(tsk);
3479 pid = task_pid_vnr(tsk);
3480 if (pid > 0) /* make sure to only use valid results */
3483 cgroup_iter_end(cgrp, &it);
3485 /* now sort & (if procs) strip out duplicates */
3486 sort(array, length, sizeof(pid_t), cmppid, NULL);
3487 if (type == CGROUP_FILE_PROCS)
3488 length = pidlist_uniq(&array, length);
3489 l = cgroup_pidlist_find(cgrp, type);
3491 pidlist_free(array);
3494 /* store array, freeing old if necessary - lock already held */
3495 pidlist_free(l->list);
3499 up_write(&l->mutex);
3505 * cgroupstats_build - build and fill cgroupstats
3506 * @stats: cgroupstats to fill information into
3507 * @dentry: A dentry entry belonging to the cgroup for which stats have
3510 * Build and fill cgroupstats so that taskstats can export it to user
3513 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3516 struct cgroup *cgrp;
3517 struct cgroup_iter it;
3518 struct task_struct *tsk;
3521 * Validate dentry by checking the superblock operations,
3522 * and make sure it's a directory.
3524 if (dentry->d_sb->s_op != &cgroup_ops ||
3525 !S_ISDIR(dentry->d_inode->i_mode))
3529 cgrp = dentry->d_fsdata;
3531 cgroup_iter_start(cgrp, &it);
3532 while ((tsk = cgroup_iter_next(cgrp, &it))) {
3533 switch (tsk->state) {
3535 stats->nr_running++;
3537 case TASK_INTERRUPTIBLE:
3538 stats->nr_sleeping++;
3540 case TASK_UNINTERRUPTIBLE:
3541 stats->nr_uninterruptible++;
3544 stats->nr_stopped++;
3547 if (delayacct_is_task_waiting_on_io(tsk))
3548 stats->nr_io_wait++;
3552 cgroup_iter_end(cgrp, &it);
3560 * seq_file methods for the tasks/procs files. The seq_file position is the
3561 * next pid to display; the seq_file iterator is a pointer to the pid
3562 * in the cgroup->l->list array.
3565 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3568 * Initially we receive a position value that corresponds to
3569 * one more than the last pid shown (or 0 on the first call or
3570 * after a seek to the start). Use a binary-search to find the
3571 * next pid to display, if any
3573 struct cgroup_pidlist *l = s->private;
3574 int index = 0, pid = *pos;
3577 down_read(&l->mutex);
3579 int end = l->length;
3581 while (index < end) {
3582 int mid = (index + end) / 2;
3583 if (l->list[mid] == pid) {
3586 } else if (l->list[mid] <= pid)
3592 /* If we're off the end of the array, we're done */
3593 if (index >= l->length)
3595 /* Update the abstract position to be the actual pid that we found */
3596 iter = l->list + index;
3601 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3603 struct cgroup_pidlist *l = s->private;
3607 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3609 struct cgroup_pidlist *l = s->private;
3611 pid_t *end = l->list + l->length;
3613 * Advance to the next pid in the array. If this goes off the
3625 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3627 return seq_printf(s, "%d\n", *(int *)v);
3631 * seq_operations functions for iterating on pidlists through seq_file -
3632 * independent of whether it's tasks or procs
3634 static const struct seq_operations cgroup_pidlist_seq_operations = {
3635 .start = cgroup_pidlist_start,
3636 .stop = cgroup_pidlist_stop,
3637 .next = cgroup_pidlist_next,
3638 .show = cgroup_pidlist_show,
3641 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
3644 * the case where we're the last user of this particular pidlist will
3645 * have us remove it from the cgroup's list, which entails taking the
3646 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3647 * pidlist_mutex, we have to take pidlist_mutex first.
3649 mutex_lock(&l->owner->pidlist_mutex);
3650 down_write(&l->mutex);
3651 BUG_ON(!l->use_count);
3652 if (!--l->use_count) {
3653 /* we're the last user if refcount is 0; remove and free */
3654 list_del(&l->links);
3655 mutex_unlock(&l->owner->pidlist_mutex);
3656 pidlist_free(l->list);
3657 put_pid_ns(l->key.ns);
3658 up_write(&l->mutex);
3662 mutex_unlock(&l->owner->pidlist_mutex);
3663 up_write(&l->mutex);
3666 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
3668 struct cgroup_pidlist *l;
3669 if (!(file->f_mode & FMODE_READ))
3672 * the seq_file will only be initialized if the file was opened for
3673 * reading; hence we check if it's not null only in that case.
3675 l = ((struct seq_file *)file->private_data)->private;
3676 cgroup_release_pid_array(l);
3677 return seq_release(inode, file);
3680 static const struct file_operations cgroup_pidlist_operations = {
3682 .llseek = seq_lseek,
3683 .write = cgroup_file_write,
3684 .release = cgroup_pidlist_release,
3688 * The following functions handle opens on a file that displays a pidlist
3689 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3692 /* helper function for the two below it */
3693 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
3695 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
3696 struct cgroup_pidlist *l;
3699 /* Nothing to do for write-only files */
3700 if (!(file->f_mode & FMODE_READ))
3703 /* have the array populated */
3704 retval = pidlist_array_load(cgrp, type, &l);
3707 /* configure file information */
3708 file->f_op = &cgroup_pidlist_operations;
3710 retval = seq_open(file, &cgroup_pidlist_seq_operations);
3712 cgroup_release_pid_array(l);
3715 ((struct seq_file *)file->private_data)->private = l;
3718 static int cgroup_tasks_open(struct inode *unused, struct file *file)
3720 return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
3722 static int cgroup_procs_open(struct inode *unused, struct file *file)
3724 return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
3727 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
3730 return notify_on_release(cgrp);
3733 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
3737 clear_bit(CGRP_RELEASABLE, &cgrp->flags);
3739 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3741 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3746 * Unregister event and free resources.
3748 * Gets called from workqueue.
3750 static void cgroup_event_remove(struct work_struct *work)
3752 struct cgroup_event *event = container_of(work, struct cgroup_event,
3754 struct cgroup *cgrp = event->cgrp;
3756 event->cft->unregister_event(cgrp, event->cft, event->eventfd);
3758 eventfd_ctx_put(event->eventfd);
3764 * Gets called on POLLHUP on eventfd when user closes it.
3766 * Called with wqh->lock held and interrupts disabled.
3768 static int cgroup_event_wake(wait_queue_t *wait, unsigned mode,
3769 int sync, void *key)
3771 struct cgroup_event *event = container_of(wait,
3772 struct cgroup_event, wait);
3773 struct cgroup *cgrp = event->cgrp;
3774 unsigned long flags = (unsigned long)key;
3776 if (flags & POLLHUP) {
3777 __remove_wait_queue(event->wqh, &event->wait);
3778 spin_lock(&cgrp->event_list_lock);
3779 list_del_init(&event->list);
3780 spin_unlock(&cgrp->event_list_lock);
3782 * We are in atomic context, but cgroup_event_remove() may
3783 * sleep, so we have to call it in workqueue.
3785 schedule_work(&event->remove);
3791 static void cgroup_event_ptable_queue_proc(struct file *file,
3792 wait_queue_head_t *wqh, poll_table *pt)
3794 struct cgroup_event *event = container_of(pt,
3795 struct cgroup_event, pt);
3798 add_wait_queue(wqh, &event->wait);
3802 * Parse input and register new cgroup event handler.
3804 * Input must be in format '<event_fd> <control_fd> <args>'.
3805 * Interpretation of args is defined by control file implementation.
3807 static int cgroup_write_event_control(struct cgroup *cgrp, struct cftype *cft,
3810 struct cgroup_event *event = NULL;
3811 unsigned int efd, cfd;
3812 struct file *efile = NULL;
3813 struct file *cfile = NULL;
3817 efd = simple_strtoul(buffer, &endp, 10);
3822 cfd = simple_strtoul(buffer, &endp, 10);
3823 if ((*endp != ' ') && (*endp != '\0'))
3827 event = kzalloc(sizeof(*event), GFP_KERNEL);
3831 INIT_LIST_HEAD(&event->list);
3832 init_poll_funcptr(&event->pt, cgroup_event_ptable_queue_proc);
3833 init_waitqueue_func_entry(&event->wait, cgroup_event_wake);
3834 INIT_WORK(&event->remove, cgroup_event_remove);
3836 efile = eventfd_fget(efd);
3837 if (IS_ERR(efile)) {
3838 ret = PTR_ERR(efile);
3842 event->eventfd = eventfd_ctx_fileget(efile);
3843 if (IS_ERR(event->eventfd)) {
3844 ret = PTR_ERR(event->eventfd);
3854 /* the process need read permission on control file */
3855 /* AV: shouldn't we check that it's been opened for read instead? */
3856 ret = inode_permission(cfile->f_path.dentry->d_inode, MAY_READ);
3860 event->cft = __file_cft(cfile);
3861 if (IS_ERR(event->cft)) {
3862 ret = PTR_ERR(event->cft);
3866 if (!event->cft->register_event || !event->cft->unregister_event) {
3871 ret = event->cft->register_event(cgrp, event->cft,
3872 event->eventfd, buffer);
3876 if (efile->f_op->poll(efile, &event->pt) & POLLHUP) {
3877 event->cft->unregister_event(cgrp, event->cft, event->eventfd);
3883 * Events should be removed after rmdir of cgroup directory, but before
3884 * destroying subsystem state objects. Let's take reference to cgroup
3885 * directory dentry to do that.
3889 spin_lock(&cgrp->event_list_lock);
3890 list_add(&event->list, &cgrp->event_list);
3891 spin_unlock(&cgrp->event_list_lock);
3902 if (event && event->eventfd && !IS_ERR(event->eventfd))
3903 eventfd_ctx_put(event->eventfd);
3905 if (!IS_ERR_OR_NULL(efile))
3913 static u64 cgroup_clone_children_read(struct cgroup *cgrp,
3916 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3919 static int cgroup_clone_children_write(struct cgroup *cgrp,
3924 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3926 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3931 * for the common functions, 'private' gives the type of file
3933 /* for hysterical raisins, we can't put this on the older files */
3934 #define CGROUP_FILE_GENERIC_PREFIX "cgroup."
3935 static struct cftype files[] = {
3938 .open = cgroup_tasks_open,
3939 .write_u64 = cgroup_tasks_write,
3940 .release = cgroup_pidlist_release,
3941 .mode = S_IRUGO | S_IWUSR,
3944 .name = CGROUP_FILE_GENERIC_PREFIX "procs",
3945 .open = cgroup_procs_open,
3946 .write_u64 = cgroup_procs_write,
3947 .release = cgroup_pidlist_release,
3948 .mode = S_IRUGO | S_IWUSR,
3951 .name = "notify_on_release",
3952 .read_u64 = cgroup_read_notify_on_release,
3953 .write_u64 = cgroup_write_notify_on_release,
3956 .name = CGROUP_FILE_GENERIC_PREFIX "event_control",
3957 .write_string = cgroup_write_event_control,
3961 .name = "cgroup.clone_children",
3962 .read_u64 = cgroup_clone_children_read,
3963 .write_u64 = cgroup_clone_children_write,
3966 .name = "release_agent",
3967 .flags = CFTYPE_ONLY_ON_ROOT,
3968 .read_seq_string = cgroup_release_agent_show,
3969 .write_string = cgroup_release_agent_write,
3970 .max_write_len = PATH_MAX,
3976 * cgroup_populate_dir - selectively creation of files in a directory
3977 * @cgrp: target cgroup
3978 * @base_files: true if the base files should be added
3979 * @subsys_mask: mask of the subsystem ids whose files should be added
3981 static int cgroup_populate_dir(struct cgroup *cgrp, bool base_files,
3982 unsigned long subsys_mask)
3985 struct cgroup_subsys *ss;
3988 err = cgroup_addrm_files(cgrp, NULL, files, true);
3993 /* process cftsets of each subsystem */
3994 for_each_subsys(cgrp->root, ss) {
3995 struct cftype_set *set;
3996 if (!test_bit(ss->subsys_id, &subsys_mask))
3999 list_for_each_entry(set, &ss->cftsets, node)
4000 cgroup_addrm_files(cgrp, ss, set->cfts, true);
4003 /* This cgroup is ready now */
4004 for_each_subsys(cgrp->root, ss) {
4005 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4007 * Update id->css pointer and make this css visible from
4008 * CSS ID functions. This pointer will be dereferened
4009 * from RCU-read-side without locks.
4012 rcu_assign_pointer(css->id->css, css);
4018 static void css_dput_fn(struct work_struct *work)
4020 struct cgroup_subsys_state *css =
4021 container_of(work, struct cgroup_subsys_state, dput_work);
4022 struct dentry *dentry = css->cgroup->dentry;
4023 struct super_block *sb = dentry->d_sb;
4025 atomic_inc(&sb->s_active);
4027 deactivate_super(sb);
4030 static void init_cgroup_css(struct cgroup_subsys_state *css,
4031 struct cgroup_subsys *ss,
4032 struct cgroup *cgrp)
4035 atomic_set(&css->refcnt, 1);
4038 if (cgrp == dummytop)
4039 css->flags |= CSS_ROOT;
4040 BUG_ON(cgrp->subsys[ss->subsys_id]);
4041 cgrp->subsys[ss->subsys_id] = css;
4044 * css holds an extra ref to @cgrp->dentry which is put on the last
4045 * css_put(). dput() requires process context, which css_put() may
4046 * be called without. @css->dput_work will be used to invoke
4047 * dput() asynchronously from css_put().
4049 INIT_WORK(&css->dput_work, css_dput_fn);
4052 /* invoke ->post_create() on a new CSS and mark it online if successful */
4053 static int online_css(struct cgroup_subsys *ss, struct cgroup *cgrp)
4057 lockdep_assert_held(&cgroup_mutex);
4060 ret = ss->css_online(cgrp);
4062 cgrp->subsys[ss->subsys_id]->flags |= CSS_ONLINE;
4066 /* if the CSS is online, invoke ->pre_destory() on it and mark it offline */
4067 static void offline_css(struct cgroup_subsys *ss, struct cgroup *cgrp)
4068 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4070 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4072 lockdep_assert_held(&cgroup_mutex);
4074 if (!(css->flags & CSS_ONLINE))
4078 * css_offline() should be called with cgroup_mutex unlocked. See
4079 * 3fa59dfbc3 ("cgroup: fix potential deadlock in pre_destroy") for
4080 * details. This temporary unlocking should go away once
4081 * cgroup_mutex is unexported from controllers.
4083 if (ss->css_offline) {
4084 mutex_unlock(&cgroup_mutex);
4085 ss->css_offline(cgrp);
4086 mutex_lock(&cgroup_mutex);
4089 cgrp->subsys[ss->subsys_id]->flags &= ~CSS_ONLINE;
4093 * cgroup_create - create a cgroup
4094 * @parent: cgroup that will be parent of the new cgroup
4095 * @dentry: dentry of the new cgroup
4096 * @mode: mode to set on new inode
4098 * Must be called with the mutex on the parent inode held
4100 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4103 struct cgroup *cgrp;
4104 struct cgroupfs_root *root = parent->root;
4106 struct cgroup_subsys *ss;
4107 struct super_block *sb = root->sb;
4109 /* allocate the cgroup and its ID, 0 is reserved for the root */
4110 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4114 cgrp->id = ida_simple_get(&root->cgroup_ida, 1, 0, GFP_KERNEL);
4119 * Only live parents can have children. Note that the liveliness
4120 * check isn't strictly necessary because cgroup_mkdir() and
4121 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4122 * anyway so that locking is contained inside cgroup proper and we
4123 * don't get nasty surprises if we ever grow another caller.
4125 if (!cgroup_lock_live_group(parent)) {
4130 /* Grab a reference on the superblock so the hierarchy doesn't
4131 * get deleted on unmount if there are child cgroups. This
4132 * can be done outside cgroup_mutex, since the sb can't
4133 * disappear while someone has an open control file on the
4135 atomic_inc(&sb->s_active);
4137 init_cgroup_housekeeping(cgrp);
4139 cgrp->parent = parent;
4140 cgrp->root = parent->root;
4141 cgrp->top_cgroup = parent->top_cgroup;
4143 if (notify_on_release(parent))
4144 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4146 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4147 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4149 for_each_subsys(root, ss) {
4150 struct cgroup_subsys_state *css;
4152 css = ss->css_alloc(cgrp);
4157 init_cgroup_css(css, ss, cgrp);
4159 err = alloc_css_id(ss, parent, cgrp);
4166 * Create directory. cgroup_create_file() returns with the new
4167 * directory locked on success so that it can be populated without
4168 * dropping cgroup_mutex.
4170 err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4173 lockdep_assert_held(&dentry->d_inode->i_mutex);
4175 /* allocation complete, commit to creation */
4176 dentry->d_fsdata = cgrp;
4177 cgrp->dentry = dentry;
4178 list_add_tail(&cgrp->allcg_node, &root->allcg_list);
4179 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4180 root->number_of_cgroups++;
4182 /* each css holds a ref to the cgroup's dentry */
4183 for_each_subsys(root, ss)
4186 /* creation succeeded, notify subsystems */
4187 for_each_subsys(root, ss) {
4188 err = online_css(ss, cgrp);
4192 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4194 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",
4195 current->comm, current->pid, ss->name);
4196 if (!strcmp(ss->name, "memory"))
4197 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4198 ss->warned_broken_hierarchy = true;
4202 err = cgroup_populate_dir(cgrp, true, root->subsys_mask);
4206 mutex_unlock(&cgroup_mutex);
4207 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4212 for_each_subsys(root, ss) {
4213 if (cgrp->subsys[ss->subsys_id])
4216 mutex_unlock(&cgroup_mutex);
4217 /* Release the reference count that we took on the superblock */
4218 deactivate_super(sb);
4220 ida_simple_remove(&root->cgroup_ida, cgrp->id);
4226 cgroup_destroy_locked(cgrp);
4227 mutex_unlock(&cgroup_mutex);
4228 mutex_unlock(&dentry->d_inode->i_mutex);
4232 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4234 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4236 /* the vfs holds inode->i_mutex already */
4237 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4241 * Check the reference count on each subsystem. Since we already
4242 * established that there are no tasks in the cgroup, if the css refcount
4243 * is also 1, then there should be no outstanding references, so the
4244 * subsystem is safe to destroy. We scan across all subsystems rather than
4245 * using the per-hierarchy linked list of mounted subsystems since we can
4246 * be called via check_for_release() with no synchronization other than
4247 * RCU, and the subsystem linked list isn't RCU-safe.
4249 static int cgroup_has_css_refs(struct cgroup *cgrp)
4254 * We won't need to lock the subsys array, because the subsystems
4255 * we're concerned about aren't going anywhere since our cgroup root
4256 * has a reference on them.
4258 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4259 struct cgroup_subsys *ss = subsys[i];
4260 struct cgroup_subsys_state *css;
4262 /* Skip subsystems not present or not in this hierarchy */
4263 if (ss == NULL || ss->root != cgrp->root)
4266 css = cgrp->subsys[ss->subsys_id];
4268 * When called from check_for_release() it's possible
4269 * that by this point the cgroup has been removed
4270 * and the css deleted. But a false-positive doesn't
4271 * matter, since it can only happen if the cgroup
4272 * has been deleted and hence no longer needs the
4273 * release agent to be called anyway.
4275 if (css && css_refcnt(css) > 1)
4281 static int cgroup_destroy_locked(struct cgroup *cgrp)
4282 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4284 struct dentry *d = cgrp->dentry;
4285 struct cgroup *parent = cgrp->parent;
4287 struct cgroup_event *event, *tmp;
4288 struct cgroup_subsys *ss;
4289 LIST_HEAD(tmp_list);
4291 lockdep_assert_held(&d->d_inode->i_mutex);
4292 lockdep_assert_held(&cgroup_mutex);
4294 if (atomic_read(&cgrp->count) || !list_empty(&cgrp->children))
4298 * Block new css_tryget() by deactivating refcnt and mark @cgrp
4299 * removed. This makes future css_tryget() and child creation
4300 * attempts fail thus maintaining the removal conditions verified
4303 for_each_subsys(cgrp->root, ss) {
4304 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4306 WARN_ON(atomic_read(&css->refcnt) < 0);
4307 atomic_add(CSS_DEACT_BIAS, &css->refcnt);
4309 set_bit(CGRP_REMOVED, &cgrp->flags);
4311 /* tell subsystems to initate destruction */
4312 for_each_subsys(cgrp->root, ss)
4313 offline_css(ss, cgrp);
4316 * Put all the base refs. Each css holds an extra reference to the
4317 * cgroup's dentry and cgroup removal proceeds regardless of css
4318 * refs. On the last put of each css, whenever that may be, the
4319 * extra dentry ref is put so that dentry destruction happens only
4320 * after all css's are released.
4322 for_each_subsys(cgrp->root, ss)
4323 css_put(cgrp->subsys[ss->subsys_id]);
4325 raw_spin_lock(&release_list_lock);
4326 if (!list_empty(&cgrp->release_list))
4327 list_del_init(&cgrp->release_list);
4328 raw_spin_unlock(&release_list_lock);
4330 /* delete this cgroup from parent->children */
4331 list_del_rcu(&cgrp->sibling);
4332 list_del_init(&cgrp->allcg_node);
4335 cgroup_d_remove_dir(d);
4338 set_bit(CGRP_RELEASABLE, &parent->flags);
4339 check_for_release(parent);
4342 * Unregister events and notify userspace.
4343 * Notify userspace about cgroup removing only after rmdir of cgroup
4344 * directory to avoid race between userspace and kernelspace. Use
4345 * a temporary list to avoid a deadlock with cgroup_event_wake(). Since
4346 * cgroup_event_wake() is called with the wait queue head locked,
4347 * remove_wait_queue() cannot be called while holding event_list_lock.
4349 spin_lock(&cgrp->event_list_lock);
4350 list_splice_init(&cgrp->event_list, &tmp_list);
4351 spin_unlock(&cgrp->event_list_lock);
4352 list_for_each_entry_safe(event, tmp, &tmp_list, list) {
4353 list_del_init(&event->list);
4354 remove_wait_queue(event->wqh, &event->wait);
4355 eventfd_signal(event->eventfd, 1);
4356 schedule_work(&event->remove);
4362 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4366 mutex_lock(&cgroup_mutex);
4367 ret = cgroup_destroy_locked(dentry->d_fsdata);
4368 mutex_unlock(&cgroup_mutex);
4373 static void __init_or_module cgroup_init_cftsets(struct cgroup_subsys *ss)
4375 INIT_LIST_HEAD(&ss->cftsets);
4378 * base_cftset is embedded in subsys itself, no need to worry about
4381 if (ss->base_cftypes) {
4382 ss->base_cftset.cfts = ss->base_cftypes;
4383 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4387 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4389 struct cgroup_subsys_state *css;
4391 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4393 mutex_lock(&cgroup_mutex);
4395 /* init base cftset */
4396 cgroup_init_cftsets(ss);
4398 /* Create the top cgroup state for this subsystem */
4399 list_add(&ss->sibling, &rootnode.subsys_list);
4400 ss->root = &rootnode;
4401 css = ss->css_alloc(dummytop);
4402 /* We don't handle early failures gracefully */
4403 BUG_ON(IS_ERR(css));
4404 init_cgroup_css(css, ss, dummytop);
4406 /* Update the init_css_set to contain a subsys
4407 * pointer to this state - since the subsystem is
4408 * newly registered, all tasks and hence the
4409 * init_css_set is in the subsystem's top cgroup. */
4410 init_css_set.subsys[ss->subsys_id] = css;
4412 need_forkexit_callback |= ss->fork || ss->exit;
4414 /* At system boot, before all subsystems have been
4415 * registered, no tasks have been forked, so we don't
4416 * need to invoke fork callbacks here. */
4417 BUG_ON(!list_empty(&init_task.tasks));
4420 BUG_ON(online_css(ss, dummytop));
4422 mutex_unlock(&cgroup_mutex);
4424 /* this function shouldn't be used with modular subsystems, since they
4425 * need to register a subsys_id, among other things */
4430 * cgroup_load_subsys: load and register a modular subsystem at runtime
4431 * @ss: the subsystem to load
4433 * This function should be called in a modular subsystem's initcall. If the
4434 * subsystem is built as a module, it will be assigned a new subsys_id and set
4435 * up for use. If the subsystem is built-in anyway, work is delegated to the
4436 * simpler cgroup_init_subsys.
4438 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
4440 struct cgroup_subsys_state *css;
4443 /* check name and function validity */
4444 if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
4445 ss->css_alloc == NULL || ss->css_free == NULL)
4449 * we don't support callbacks in modular subsystems. this check is
4450 * before the ss->module check for consistency; a subsystem that could
4451 * be a module should still have no callbacks even if the user isn't
4452 * compiling it as one.
4454 if (ss->fork || ss->exit)
4458 * an optionally modular subsystem is built-in: we want to do nothing,
4459 * since cgroup_init_subsys will have already taken care of it.
4461 if (ss->module == NULL) {
4462 /* a sanity check */
4463 BUG_ON(subsys[ss->subsys_id] != ss);
4467 /* init base cftset */
4468 cgroup_init_cftsets(ss);
4470 mutex_lock(&cgroup_mutex);
4471 subsys[ss->subsys_id] = ss;
4474 * no ss->css_alloc seems to need anything important in the ss
4475 * struct, so this can happen first (i.e. before the rootnode
4478 css = ss->css_alloc(dummytop);
4480 /* failure case - need to deassign the subsys[] slot. */
4481 subsys[ss->subsys_id] = NULL;
4482 mutex_unlock(&cgroup_mutex);
4483 return PTR_ERR(css);
4486 list_add(&ss->sibling, &rootnode.subsys_list);
4487 ss->root = &rootnode;
4489 /* our new subsystem will be attached to the dummy hierarchy. */
4490 init_cgroup_css(css, ss, dummytop);
4491 /* init_idr must be after init_cgroup_css because it sets css->id. */
4493 ret = cgroup_init_idr(ss, css);
4499 * Now we need to entangle the css into the existing css_sets. unlike
4500 * in cgroup_init_subsys, there are now multiple css_sets, so each one
4501 * will need a new pointer to it; done by iterating the css_set_table.
4502 * furthermore, modifying the existing css_sets will corrupt the hash
4503 * table state, so each changed css_set will need its hash recomputed.
4504 * this is all done under the css_set_lock.
4506 write_lock(&css_set_lock);
4507 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
4509 struct hlist_node *node, *tmp;
4510 struct hlist_head *bucket = &css_set_table[i], *new_bucket;
4512 hlist_for_each_entry_safe(cg, node, tmp, bucket, hlist) {
4513 /* skip entries that we already rehashed */
4514 if (cg->subsys[ss->subsys_id])
4516 /* remove existing entry */
4517 hlist_del(&cg->hlist);
4519 cg->subsys[ss->subsys_id] = css;
4520 /* recompute hash and restore entry */
4521 new_bucket = css_set_hash(cg->subsys);
4522 hlist_add_head(&cg->hlist, new_bucket);
4525 write_unlock(&css_set_lock);
4528 ret = online_css(ss, dummytop);
4533 mutex_unlock(&cgroup_mutex);
4537 mutex_unlock(&cgroup_mutex);
4538 /* @ss can't be mounted here as try_module_get() would fail */
4539 cgroup_unload_subsys(ss);
4542 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
4545 * cgroup_unload_subsys: unload a modular subsystem
4546 * @ss: the subsystem to unload
4548 * This function should be called in a modular subsystem's exitcall. When this
4549 * function is invoked, the refcount on the subsystem's module will be 0, so
4550 * the subsystem will not be attached to any hierarchy.
4552 void cgroup_unload_subsys(struct cgroup_subsys *ss)
4554 struct cg_cgroup_link *link;
4555 struct hlist_head *hhead;
4557 BUG_ON(ss->module == NULL);
4560 * we shouldn't be called if the subsystem is in use, and the use of
4561 * try_module_get in parse_cgroupfs_options should ensure that it
4562 * doesn't start being used while we're killing it off.
4564 BUG_ON(ss->root != &rootnode);
4566 mutex_lock(&cgroup_mutex);
4568 offline_css(ss, dummytop);
4572 idr_remove_all(&ss->idr);
4573 idr_destroy(&ss->idr);
4576 /* deassign the subsys_id */
4577 subsys[ss->subsys_id] = NULL;
4579 /* remove subsystem from rootnode's list of subsystems */
4580 list_del_init(&ss->sibling);
4583 * disentangle the css from all css_sets attached to the dummytop. as
4584 * in loading, we need to pay our respects to the hashtable gods.
4586 write_lock(&css_set_lock);
4587 list_for_each_entry(link, &dummytop->css_sets, cgrp_link_list) {
4588 struct css_set *cg = link->cg;
4590 hlist_del(&cg->hlist);
4591 cg->subsys[ss->subsys_id] = NULL;
4592 hhead = css_set_hash(cg->subsys);
4593 hlist_add_head(&cg->hlist, hhead);
4595 write_unlock(&css_set_lock);
4598 * remove subsystem's css from the dummytop and free it - need to
4599 * free before marking as null because ss->css_free needs the
4600 * cgrp->subsys pointer to find their state. note that this also
4601 * takes care of freeing the css_id.
4603 ss->css_free(dummytop);
4604 dummytop->subsys[ss->subsys_id] = NULL;
4606 mutex_unlock(&cgroup_mutex);
4608 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
4611 * cgroup_init_early - cgroup initialization at system boot
4613 * Initialize cgroups at system boot, and initialize any
4614 * subsystems that request early init.
4616 int __init cgroup_init_early(void)
4619 atomic_set(&init_css_set.refcount, 1);
4620 INIT_LIST_HEAD(&init_css_set.cg_links);
4621 INIT_LIST_HEAD(&init_css_set.tasks);
4622 INIT_HLIST_NODE(&init_css_set.hlist);
4624 init_cgroup_root(&rootnode);
4626 init_task.cgroups = &init_css_set;
4628 init_css_set_link.cg = &init_css_set;
4629 init_css_set_link.cgrp = dummytop;
4630 list_add(&init_css_set_link.cgrp_link_list,
4631 &rootnode.top_cgroup.css_sets);
4632 list_add(&init_css_set_link.cg_link_list,
4633 &init_css_set.cg_links);
4635 for (i = 0; i < CSS_SET_TABLE_SIZE; i++)
4636 INIT_HLIST_HEAD(&css_set_table[i]);
4638 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4639 struct cgroup_subsys *ss = subsys[i];
4641 /* at bootup time, we don't worry about modular subsystems */
4642 if (!ss || ss->module)
4646 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
4647 BUG_ON(!ss->css_alloc);
4648 BUG_ON(!ss->css_free);
4649 if (ss->subsys_id != i) {
4650 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
4651 ss->name, ss->subsys_id);
4656 cgroup_init_subsys(ss);
4662 * cgroup_init - cgroup initialization
4664 * Register cgroup filesystem and /proc file, and initialize
4665 * any subsystems that didn't request early init.
4667 int __init cgroup_init(void)
4671 struct hlist_head *hhead;
4673 err = bdi_init(&cgroup_backing_dev_info);
4677 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4678 struct cgroup_subsys *ss = subsys[i];
4680 /* at bootup time, we don't worry about modular subsystems */
4681 if (!ss || ss->module)
4683 if (!ss->early_init)
4684 cgroup_init_subsys(ss);
4686 cgroup_init_idr(ss, init_css_set.subsys[ss->subsys_id]);
4689 /* Add init_css_set to the hash table */
4690 hhead = css_set_hash(init_css_set.subsys);
4691 hlist_add_head(&init_css_set.hlist, hhead);
4692 BUG_ON(!init_root_id(&rootnode));
4694 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4700 err = register_filesystem(&cgroup_fs_type);
4702 kobject_put(cgroup_kobj);
4706 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4710 bdi_destroy(&cgroup_backing_dev_info);
4716 * proc_cgroup_show()
4717 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4718 * - Used for /proc/<pid>/cgroup.
4719 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4720 * doesn't really matter if tsk->cgroup changes after we read it,
4721 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4722 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4723 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4724 * cgroup to top_cgroup.
4727 /* TODO: Use a proper seq_file iterator */
4728 static int proc_cgroup_show(struct seq_file *m, void *v)
4731 struct task_struct *tsk;
4734 struct cgroupfs_root *root;
4737 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4743 tsk = get_pid_task(pid, PIDTYPE_PID);
4749 mutex_lock(&cgroup_mutex);
4751 for_each_active_root(root) {
4752 struct cgroup_subsys *ss;
4753 struct cgroup *cgrp;
4756 seq_printf(m, "%d:", root->hierarchy_id);
4757 for_each_subsys(root, ss)
4758 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4759 if (strlen(root->name))
4760 seq_printf(m, "%sname=%s", count ? "," : "",
4763 cgrp = task_cgroup_from_root(tsk, root);
4764 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
4772 mutex_unlock(&cgroup_mutex);
4773 put_task_struct(tsk);
4780 static int cgroup_open(struct inode *inode, struct file *file)
4782 struct pid *pid = PROC_I(inode)->pid;
4783 return single_open(file, proc_cgroup_show, pid);
4786 const struct file_operations proc_cgroup_operations = {
4787 .open = cgroup_open,
4789 .llseek = seq_lseek,
4790 .release = single_release,
4793 /* Display information about each subsystem and each hierarchy */
4794 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4798 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4800 * ideally we don't want subsystems moving around while we do this.
4801 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4802 * subsys/hierarchy state.
4804 mutex_lock(&cgroup_mutex);
4805 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4806 struct cgroup_subsys *ss = subsys[i];
4809 seq_printf(m, "%s\t%d\t%d\t%d\n",
4810 ss->name, ss->root->hierarchy_id,
4811 ss->root->number_of_cgroups, !ss->disabled);
4813 mutex_unlock(&cgroup_mutex);
4817 static int cgroupstats_open(struct inode *inode, struct file *file)
4819 return single_open(file, proc_cgroupstats_show, NULL);
4822 static const struct file_operations proc_cgroupstats_operations = {
4823 .open = cgroupstats_open,
4825 .llseek = seq_lseek,
4826 .release = single_release,
4830 * cgroup_fork - attach newly forked task to its parents cgroup.
4831 * @child: pointer to task_struct of forking parent process.
4833 * Description: A task inherits its parent's cgroup at fork().
4835 * A pointer to the shared css_set was automatically copied in
4836 * fork.c by dup_task_struct(). However, we ignore that copy, since
4837 * it was not made under the protection of RCU or cgroup_mutex, so
4838 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
4839 * have already changed current->cgroups, allowing the previously
4840 * referenced cgroup group to be removed and freed.
4842 * At the point that cgroup_fork() is called, 'current' is the parent
4843 * task, and the passed argument 'child' points to the child task.
4845 void cgroup_fork(struct task_struct *child)
4848 child->cgroups = current->cgroups;
4849 get_css_set(child->cgroups);
4850 task_unlock(current);
4851 INIT_LIST_HEAD(&child->cg_list);
4855 * cgroup_post_fork - called on a new task after adding it to the task list
4856 * @child: the task in question
4858 * Adds the task to the list running through its css_set if necessary and
4859 * call the subsystem fork() callbacks. Has to be after the task is
4860 * visible on the task list in case we race with the first call to
4861 * cgroup_iter_start() - to guarantee that the new task ends up on its
4864 void cgroup_post_fork(struct task_struct *child)
4869 * use_task_css_set_links is set to 1 before we walk the tasklist
4870 * under the tasklist_lock and we read it here after we added the child
4871 * to the tasklist under the tasklist_lock as well. If the child wasn't
4872 * yet in the tasklist when we walked through it from
4873 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4874 * should be visible now due to the paired locking and barriers implied
4875 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4876 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4879 if (use_task_css_set_links) {
4880 write_lock(&css_set_lock);
4882 if (list_empty(&child->cg_list))
4883 list_add(&child->cg_list, &child->cgroups->tasks);
4885 write_unlock(&css_set_lock);
4889 * Call ss->fork(). This must happen after @child is linked on
4890 * css_set; otherwise, @child might change state between ->fork()
4891 * and addition to css_set.
4893 if (need_forkexit_callback) {
4894 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4895 struct cgroup_subsys *ss = subsys[i];
4898 * fork/exit callbacks are supported only for
4899 * builtin subsystems and we don't need further
4900 * synchronization as they never go away.
4902 if (!ss || ss->module)
4912 * cgroup_exit - detach cgroup from exiting task
4913 * @tsk: pointer to task_struct of exiting process
4914 * @run_callback: run exit callbacks?
4916 * Description: Detach cgroup from @tsk and release it.
4918 * Note that cgroups marked notify_on_release force every task in
4919 * them to take the global cgroup_mutex mutex when exiting.
4920 * This could impact scaling on very large systems. Be reluctant to
4921 * use notify_on_release cgroups where very high task exit scaling
4922 * is required on large systems.
4924 * the_top_cgroup_hack:
4926 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
4928 * We call cgroup_exit() while the task is still competent to
4929 * handle notify_on_release(), then leave the task attached to the
4930 * root cgroup in each hierarchy for the remainder of its exit.
4932 * To do this properly, we would increment the reference count on
4933 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
4934 * code we would add a second cgroup function call, to drop that
4935 * reference. This would just create an unnecessary hot spot on
4936 * the top_cgroup reference count, to no avail.
4938 * Normally, holding a reference to a cgroup without bumping its
4939 * count is unsafe. The cgroup could go away, or someone could
4940 * attach us to a different cgroup, decrementing the count on
4941 * the first cgroup that we never incremented. But in this case,
4942 * top_cgroup isn't going away, and either task has PF_EXITING set,
4943 * which wards off any cgroup_attach_task() attempts, or task is a failed
4944 * fork, never visible to cgroup_attach_task.
4946 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
4952 * Unlink from the css_set task list if necessary.
4953 * Optimistically check cg_list before taking
4956 if (!list_empty(&tsk->cg_list)) {
4957 write_lock(&css_set_lock);
4958 if (!list_empty(&tsk->cg_list))
4959 list_del_init(&tsk->cg_list);
4960 write_unlock(&css_set_lock);
4963 /* Reassign the task to the init_css_set. */
4966 tsk->cgroups = &init_css_set;
4968 if (run_callbacks && need_forkexit_callback) {
4969 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4970 struct cgroup_subsys *ss = subsys[i];
4972 /* modular subsystems can't use callbacks */
4973 if (!ss || ss->module)
4977 struct cgroup *old_cgrp =
4978 rcu_dereference_raw(cg->subsys[i])->cgroup;
4979 struct cgroup *cgrp = task_cgroup(tsk, i);
4980 ss->exit(cgrp, old_cgrp, tsk);
4987 put_css_set_taskexit(cg);
4991 * cgroup_is_descendant - see if @cgrp is a descendant of @task's cgrp
4992 * @cgrp: the cgroup in question
4993 * @task: the task in question
4995 * See if @cgrp is a descendant of @task's cgroup in the appropriate
4998 * If we are sending in dummytop, then presumably we are creating
4999 * the top cgroup in the subsystem.
5001 * Called only by the ns (nsproxy) cgroup.
5003 int cgroup_is_descendant(const struct cgroup *cgrp, struct task_struct *task)
5006 struct cgroup *target;
5008 if (cgrp == dummytop)
5011 target = task_cgroup_from_root(task, cgrp->root);
5012 while (cgrp != target && cgrp!= cgrp->top_cgroup)
5013 cgrp = cgrp->parent;
5014 ret = (cgrp == target);
5018 static void check_for_release(struct cgroup *cgrp)
5020 /* All of these checks rely on RCU to keep the cgroup
5021 * structure alive */
5022 if (cgroup_is_releasable(cgrp) && !atomic_read(&cgrp->count)
5023 && list_empty(&cgrp->children) && !cgroup_has_css_refs(cgrp)) {
5024 /* Control Group is currently removeable. If it's not
5025 * already queued for a userspace notification, queue
5027 int need_schedule_work = 0;
5028 raw_spin_lock(&release_list_lock);
5029 if (!cgroup_is_removed(cgrp) &&
5030 list_empty(&cgrp->release_list)) {
5031 list_add(&cgrp->release_list, &release_list);
5032 need_schedule_work = 1;
5034 raw_spin_unlock(&release_list_lock);
5035 if (need_schedule_work)
5036 schedule_work(&release_agent_work);
5040 /* Caller must verify that the css is not for root cgroup */
5041 bool __css_tryget(struct cgroup_subsys_state *css)
5046 v = css_refcnt(css);
5047 t = atomic_cmpxchg(&css->refcnt, v, v + 1);
5055 EXPORT_SYMBOL_GPL(__css_tryget);
5057 /* Caller must verify that the css is not for root cgroup */
5058 void __css_put(struct cgroup_subsys_state *css)
5060 struct cgroup *cgrp = css->cgroup;
5064 v = css_unbias_refcnt(atomic_dec_return(&css->refcnt));
5068 if (notify_on_release(cgrp)) {
5069 set_bit(CGRP_RELEASABLE, &cgrp->flags);
5070 check_for_release(cgrp);
5074 schedule_work(&css->dput_work);
5079 EXPORT_SYMBOL_GPL(__css_put);
5082 * Notify userspace when a cgroup is released, by running the
5083 * configured release agent with the name of the cgroup (path
5084 * relative to the root of cgroup file system) as the argument.
5086 * Most likely, this user command will try to rmdir this cgroup.
5088 * This races with the possibility that some other task will be
5089 * attached to this cgroup before it is removed, or that some other
5090 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5091 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5092 * unused, and this cgroup will be reprieved from its death sentence,
5093 * to continue to serve a useful existence. Next time it's released,
5094 * we will get notified again, if it still has 'notify_on_release' set.
5096 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5097 * means only wait until the task is successfully execve()'d. The
5098 * separate release agent task is forked by call_usermodehelper(),
5099 * then control in this thread returns here, without waiting for the
5100 * release agent task. We don't bother to wait because the caller of
5101 * this routine has no use for the exit status of the release agent
5102 * task, so no sense holding our caller up for that.
5104 static void cgroup_release_agent(struct work_struct *work)
5106 BUG_ON(work != &release_agent_work);
5107 mutex_lock(&cgroup_mutex);
5108 raw_spin_lock(&release_list_lock);
5109 while (!list_empty(&release_list)) {
5110 char *argv[3], *envp[3];
5112 char *pathbuf = NULL, *agentbuf = NULL;
5113 struct cgroup *cgrp = list_entry(release_list.next,
5116 list_del_init(&cgrp->release_list);
5117 raw_spin_unlock(&release_list_lock);
5118 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5121 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
5123 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5128 argv[i++] = agentbuf;
5129 argv[i++] = pathbuf;
5133 /* minimal command environment */
5134 envp[i++] = "HOME=/";
5135 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5138 /* Drop the lock while we invoke the usermode helper,
5139 * since the exec could involve hitting disk and hence
5140 * be a slow process */
5141 mutex_unlock(&cgroup_mutex);
5142 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5143 mutex_lock(&cgroup_mutex);
5147 raw_spin_lock(&release_list_lock);
5149 raw_spin_unlock(&release_list_lock);
5150 mutex_unlock(&cgroup_mutex);
5153 static int __init cgroup_disable(char *str)
5158 while ((token = strsep(&str, ",")) != NULL) {
5161 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
5162 struct cgroup_subsys *ss = subsys[i];
5165 * cgroup_disable, being at boot time, can't
5166 * know about module subsystems, so we don't
5169 if (!ss || ss->module)
5172 if (!strcmp(token, ss->name)) {
5174 printk(KERN_INFO "Disabling %s control group"
5175 " subsystem\n", ss->name);
5182 __setup("cgroup_disable=", cgroup_disable);
5185 * Functons for CSS ID.
5189 *To get ID other than 0, this should be called when !cgroup_is_removed().
5191 unsigned short css_id(struct cgroup_subsys_state *css)
5193 struct css_id *cssid;
5196 * This css_id() can return correct value when somone has refcnt
5197 * on this or this is under rcu_read_lock(). Once css->id is allocated,
5198 * it's unchanged until freed.
5200 cssid = rcu_dereference_check(css->id, css_refcnt(css));
5206 EXPORT_SYMBOL_GPL(css_id);
5208 unsigned short css_depth(struct cgroup_subsys_state *css)
5210 struct css_id *cssid;
5212 cssid = rcu_dereference_check(css->id, css_refcnt(css));
5215 return cssid->depth;
5218 EXPORT_SYMBOL_GPL(css_depth);
5221 * css_is_ancestor - test "root" css is an ancestor of "child"
5222 * @child: the css to be tested.
5223 * @root: the css supporsed to be an ancestor of the child.
5225 * Returns true if "root" is an ancestor of "child" in its hierarchy. Because
5226 * this function reads css->id, the caller must hold rcu_read_lock().
5227 * But, considering usual usage, the csses should be valid objects after test.
5228 * Assuming that the caller will do some action to the child if this returns
5229 * returns true, the caller must take "child";s reference count.
5230 * If "child" is valid object and this returns true, "root" is valid, too.
5233 bool css_is_ancestor(struct cgroup_subsys_state *child,
5234 const struct cgroup_subsys_state *root)
5236 struct css_id *child_id;
5237 struct css_id *root_id;
5239 child_id = rcu_dereference(child->id);
5242 root_id = rcu_dereference(root->id);
5245 if (child_id->depth < root_id->depth)
5247 if (child_id->stack[root_id->depth] != root_id->id)
5252 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
5254 struct css_id *id = css->id;
5255 /* When this is called before css_id initialization, id can be NULL */
5259 BUG_ON(!ss->use_id);
5261 rcu_assign_pointer(id->css, NULL);
5262 rcu_assign_pointer(css->id, NULL);
5263 spin_lock(&ss->id_lock);
5264 idr_remove(&ss->idr, id->id);
5265 spin_unlock(&ss->id_lock);
5266 kfree_rcu(id, rcu_head);
5268 EXPORT_SYMBOL_GPL(free_css_id);
5271 * This is called by init or create(). Then, calls to this function are
5272 * always serialized (By cgroup_mutex() at create()).
5275 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
5277 struct css_id *newid;
5278 int myid, error, size;
5280 BUG_ON(!ss->use_id);
5282 size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
5283 newid = kzalloc(size, GFP_KERNEL);
5285 return ERR_PTR(-ENOMEM);
5287 if (unlikely(!idr_pre_get(&ss->idr, GFP_KERNEL))) {
5291 spin_lock(&ss->id_lock);
5292 /* Don't use 0. allocates an ID of 1-65535 */
5293 error = idr_get_new_above(&ss->idr, newid, 1, &myid);
5294 spin_unlock(&ss->id_lock);
5296 /* Returns error when there are no free spaces for new ID.*/
5301 if (myid > CSS_ID_MAX)
5305 newid->depth = depth;
5309 spin_lock(&ss->id_lock);
5310 idr_remove(&ss->idr, myid);
5311 spin_unlock(&ss->id_lock);
5314 return ERR_PTR(error);
5318 static int __init_or_module cgroup_init_idr(struct cgroup_subsys *ss,
5319 struct cgroup_subsys_state *rootcss)
5321 struct css_id *newid;
5323 spin_lock_init(&ss->id_lock);
5326 newid = get_new_cssid(ss, 0);
5328 return PTR_ERR(newid);
5330 newid->stack[0] = newid->id;
5331 newid->css = rootcss;
5332 rootcss->id = newid;
5336 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
5337 struct cgroup *child)
5339 int subsys_id, i, depth = 0;
5340 struct cgroup_subsys_state *parent_css, *child_css;
5341 struct css_id *child_id, *parent_id;
5343 subsys_id = ss->subsys_id;
5344 parent_css = parent->subsys[subsys_id];
5345 child_css = child->subsys[subsys_id];
5346 parent_id = parent_css->id;
5347 depth = parent_id->depth + 1;
5349 child_id = get_new_cssid(ss, depth);
5350 if (IS_ERR(child_id))
5351 return PTR_ERR(child_id);
5353 for (i = 0; i < depth; i++)
5354 child_id->stack[i] = parent_id->stack[i];
5355 child_id->stack[depth] = child_id->id;
5357 * child_id->css pointer will be set after this cgroup is available
5358 * see cgroup_populate_dir()
5360 rcu_assign_pointer(child_css->id, child_id);
5366 * css_lookup - lookup css by id
5367 * @ss: cgroup subsys to be looked into.
5370 * Returns pointer to cgroup_subsys_state if there is valid one with id.
5371 * NULL if not. Should be called under rcu_read_lock()
5373 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
5375 struct css_id *cssid = NULL;
5377 BUG_ON(!ss->use_id);
5378 cssid = idr_find(&ss->idr, id);
5380 if (unlikely(!cssid))
5383 return rcu_dereference(cssid->css);
5385 EXPORT_SYMBOL_GPL(css_lookup);
5388 * css_get_next - lookup next cgroup under specified hierarchy.
5389 * @ss: pointer to subsystem
5390 * @id: current position of iteration.
5391 * @root: pointer to css. search tree under this.
5392 * @foundid: position of found object.
5394 * Search next css under the specified hierarchy of rootid. Calling under
5395 * rcu_read_lock() is necessary. Returns NULL if it reaches the end.
5397 struct cgroup_subsys_state *
5398 css_get_next(struct cgroup_subsys *ss, int id,
5399 struct cgroup_subsys_state *root, int *foundid)
5401 struct cgroup_subsys_state *ret = NULL;
5404 int rootid = css_id(root);
5405 int depth = css_depth(root);
5410 BUG_ON(!ss->use_id);
5411 WARN_ON_ONCE(!rcu_read_lock_held());
5413 /* fill start point for scan */
5417 * scan next entry from bitmap(tree), tmpid is updated after
5420 tmp = idr_get_next(&ss->idr, &tmpid);
5423 if (tmp->depth >= depth && tmp->stack[depth] == rootid) {
5424 ret = rcu_dereference(tmp->css);
5430 /* continue to scan from next id */
5437 * get corresponding css from file open on cgroupfs directory
5439 struct cgroup_subsys_state *cgroup_css_from_dir(struct file *f, int id)
5441 struct cgroup *cgrp;
5442 struct inode *inode;
5443 struct cgroup_subsys_state *css;
5445 inode = f->f_dentry->d_inode;
5446 /* check in cgroup filesystem dir */
5447 if (inode->i_op != &cgroup_dir_inode_operations)
5448 return ERR_PTR(-EBADF);
5450 if (id < 0 || id >= CGROUP_SUBSYS_COUNT)
5451 return ERR_PTR(-EINVAL);
5454 cgrp = __d_cgrp(f->f_dentry);
5455 css = cgrp->subsys[id];
5456 return css ? css : ERR_PTR(-ENOENT);
5459 #ifdef CONFIG_CGROUP_DEBUG
5460 static struct cgroup_subsys_state *debug_css_alloc(struct cgroup *cont)
5462 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5465 return ERR_PTR(-ENOMEM);
5470 static void debug_css_free(struct cgroup *cont)
5472 kfree(cont->subsys[debug_subsys_id]);
5475 static u64 cgroup_refcount_read(struct cgroup *cont, struct cftype *cft)
5477 return atomic_read(&cont->count);
5480 static u64 debug_taskcount_read(struct cgroup *cont, struct cftype *cft)
5482 return cgroup_task_count(cont);
5485 static u64 current_css_set_read(struct cgroup *cont, struct cftype *cft)
5487 return (u64)(unsigned long)current->cgroups;
5490 static u64 current_css_set_refcount_read(struct cgroup *cont,
5496 count = atomic_read(¤t->cgroups->refcount);
5501 static int current_css_set_cg_links_read(struct cgroup *cont,
5503 struct seq_file *seq)
5505 struct cg_cgroup_link *link;
5508 read_lock(&css_set_lock);
5510 cg = rcu_dereference(current->cgroups);
5511 list_for_each_entry(link, &cg->cg_links, cg_link_list) {
5512 struct cgroup *c = link->cgrp;
5516 name = c->dentry->d_name.name;
5519 seq_printf(seq, "Root %d group %s\n",
5520 c->root->hierarchy_id, name);
5523 read_unlock(&css_set_lock);
5527 #define MAX_TASKS_SHOWN_PER_CSS 25
5528 static int cgroup_css_links_read(struct cgroup *cont,
5530 struct seq_file *seq)
5532 struct cg_cgroup_link *link;
5534 read_lock(&css_set_lock);
5535 list_for_each_entry(link, &cont->css_sets, cgrp_link_list) {
5536 struct css_set *cg = link->cg;
5537 struct task_struct *task;
5539 seq_printf(seq, "css_set %p\n", cg);
5540 list_for_each_entry(task, &cg->tasks, cg_list) {
5541 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5542 seq_puts(seq, " ...\n");
5545 seq_printf(seq, " task %d\n",
5546 task_pid_vnr(task));
5550 read_unlock(&css_set_lock);
5554 static u64 releasable_read(struct cgroup *cgrp, struct cftype *cft)
5556 return test_bit(CGRP_RELEASABLE, &cgrp->flags);
5559 static struct cftype debug_files[] = {
5561 .name = "cgroup_refcount",
5562 .read_u64 = cgroup_refcount_read,
5565 .name = "taskcount",
5566 .read_u64 = debug_taskcount_read,
5570 .name = "current_css_set",
5571 .read_u64 = current_css_set_read,
5575 .name = "current_css_set_refcount",
5576 .read_u64 = current_css_set_refcount_read,
5580 .name = "current_css_set_cg_links",
5581 .read_seq_string = current_css_set_cg_links_read,
5585 .name = "cgroup_css_links",
5586 .read_seq_string = cgroup_css_links_read,
5590 .name = "releasable",
5591 .read_u64 = releasable_read,
5597 struct cgroup_subsys debug_subsys = {
5599 .css_alloc = debug_css_alloc,
5600 .css_free = debug_css_free,
5601 .subsys_id = debug_subsys_id,
5602 .base_cftypes = debug_files,
5604 #endif /* CONFIG_CGROUP_DEBUG */