2 * Generic process-grouping system.
4 * Based originally on the cpuset system, extracted by Paul Menage
5 * Copyright (C) 2006 Google, Inc
7 * Notifications support
8 * Copyright (C) 2009 Nokia Corporation
9 * Author: Kirill A. Shutemov
11 * Copyright notices from the original cpuset code:
12 * --------------------------------------------------
13 * Copyright (C) 2003 BULL SA.
14 * Copyright (C) 2004-2006 Silicon Graphics, Inc.
16 * Portions derived from Patrick Mochel's sysfs code.
17 * sysfs is Copyright (c) 2001-3 Patrick Mochel
19 * 2003-10-10 Written by Simon Derr.
20 * 2003-10-22 Updates by Stephen Hemminger.
21 * 2004 May-July Rework by Paul Jackson.
22 * ---------------------------------------------------
24 * This file is subject to the terms and conditions of the GNU General Public
25 * License. See the file COPYING in the main directory of the Linux
26 * distribution for more details.
29 #include <linux/cgroup.h>
30 #include <linux/cred.h>
31 #include <linux/ctype.h>
32 #include <linux/errno.h>
33 #include <linux/init_task.h>
34 #include <linux/kernel.h>
35 #include <linux/list.h>
37 #include <linux/mutex.h>
38 #include <linux/mount.h>
39 #include <linux/pagemap.h>
40 #include <linux/proc_fs.h>
41 #include <linux/rcupdate.h>
42 #include <linux/sched.h>
43 #include <linux/backing-dev.h>
44 #include <linux/seq_file.h>
45 #include <linux/slab.h>
46 #include <linux/magic.h>
47 #include <linux/spinlock.h>
48 #include <linux/string.h>
49 #include <linux/sort.h>
50 #include <linux/kmod.h>
51 #include <linux/module.h>
52 #include <linux/delayacct.h>
53 #include <linux/cgroupstats.h>
54 #include <linux/hashtable.h>
55 #include <linux/namei.h>
56 #include <linux/pid_namespace.h>
57 #include <linux/idr.h>
58 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
59 #include <linux/eventfd.h>
60 #include <linux/poll.h>
61 #include <linux/flex_array.h> /* used in cgroup_attach_task */
62 #include <linux/kthread.h>
64 #include <linux/atomic.h>
66 /* css deactivation bias, makes css->refcnt negative to deny new trygets */
67 #define CSS_DEACT_BIAS INT_MIN
70 * cgroup_mutex is the master lock. Any modification to cgroup or its
71 * hierarchy must be performed while holding it.
73 * cgroup_root_mutex nests inside cgroup_mutex and should be held to modify
74 * cgroupfs_root of any cgroup hierarchy - subsys list, flags,
75 * release_agent_path and so on. Modifying requires both cgroup_mutex and
76 * cgroup_root_mutex. Readers can acquire either of the two. This is to
77 * break the following locking order cycle.
79 * A. cgroup_mutex -> cred_guard_mutex -> s_type->i_mutex_key -> namespace_sem
80 * B. namespace_sem -> cgroup_mutex
82 * B happens only through cgroup_show_options() and using cgroup_root_mutex
85 #ifdef CONFIG_PROVE_RCU
86 DEFINE_MUTEX(cgroup_mutex);
87 EXPORT_SYMBOL_GPL(cgroup_mutex); /* only for task_subsys_state_check() */
89 static DEFINE_MUTEX(cgroup_mutex);
92 static DEFINE_MUTEX(cgroup_root_mutex);
95 * Generate an array of cgroup subsystem pointers. At boot time, this is
96 * populated with the built in subsystems, and modular subsystems are
97 * registered after that. The mutable section of this array is protected by
100 #define SUBSYS(_x) [_x ## _subsys_id] = &_x ## _subsys,
101 #define IS_SUBSYS_ENABLED(option) IS_BUILTIN(option)
102 static struct cgroup_subsys *subsys[CGROUP_SUBSYS_COUNT] = {
103 #include <linux/cgroup_subsys.h>
107 * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the
108 * subsystems that are otherwise unattached - it never has more than a
109 * single cgroup, and all tasks are part of that cgroup.
111 static struct cgroupfs_root rootnode;
114 * cgroupfs file entry, pointed to from leaf dentry->d_fsdata.
117 struct list_head node;
118 struct dentry *dentry;
122 struct simple_xattrs xattrs;
126 * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when
127 * cgroup_subsys->use_id != 0.
129 #define CSS_ID_MAX (65535)
132 * The css to which this ID points. This pointer is set to valid value
133 * after cgroup is populated. If cgroup is removed, this will be NULL.
134 * This pointer is expected to be RCU-safe because destroy()
135 * is called after synchronize_rcu(). But for safe use, css_tryget()
136 * should be used for avoiding race.
138 struct cgroup_subsys_state __rcu *css;
144 * Depth in hierarchy which this ID belongs to.
146 unsigned short depth;
148 * ID is freed by RCU. (and lookup routine is RCU safe.)
150 struct rcu_head rcu_head;
152 * Hierarchy of CSS ID belongs to.
154 unsigned short stack[0]; /* Array of Length (depth+1) */
158 * cgroup_event represents events which userspace want to receive.
160 struct cgroup_event {
162 * Cgroup which the event belongs to.
166 * Control file which the event associated.
170 * eventfd to signal userspace about the event.
172 struct eventfd_ctx *eventfd;
174 * Each of these stored in a list by the cgroup.
176 struct list_head list;
178 * All fields below needed to unregister event when
179 * userspace closes eventfd.
182 wait_queue_head_t *wqh;
184 struct work_struct remove;
187 /* The list of hierarchy roots */
189 static LIST_HEAD(roots);
190 static int root_count;
193 * Hierarchy ID allocation and mapping. It follows the same exclusion
194 * rules as other root ops - both cgroup_mutex and cgroup_root_mutex for
195 * writes, either for reads.
197 static DEFINE_IDR(cgroup_hierarchy_idr);
199 /* dummytop is a shorthand for the dummy hierarchy's top cgroup */
200 #define dummytop (&rootnode.top_cgroup)
202 static struct cgroup_name root_cgroup_name = { .name = "/" };
204 /* This flag indicates whether tasks in the fork and exit paths should
205 * check for fork/exit handlers to call. This avoids us having to do
206 * extra work in the fork/exit path if none of the subsystems need to
209 static int need_forkexit_callback __read_mostly;
211 static int cgroup_destroy_locked(struct cgroup *cgrp);
212 static int cgroup_addrm_files(struct cgroup *cgrp, struct cgroup_subsys *subsys,
213 struct cftype cfts[], bool is_add);
215 static int css_unbias_refcnt(int refcnt)
217 return refcnt >= 0 ? refcnt : refcnt - CSS_DEACT_BIAS;
220 /* the current nr of refs, always >= 0 whether @css is deactivated or not */
221 static int css_refcnt(struct cgroup_subsys_state *css)
223 int v = atomic_read(&css->refcnt);
225 return css_unbias_refcnt(v);
228 /* convenient tests for these bits */
229 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
231 return test_bit(CGRP_DEAD, &cgrp->flags);
235 * cgroup_is_descendant - test ancestry
236 * @cgrp: the cgroup to be tested
237 * @ancestor: possible ancestor of @cgrp
239 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
240 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
241 * and @ancestor are accessible.
243 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
246 if (cgrp == ancestor)
252 EXPORT_SYMBOL_GPL(cgroup_is_descendant);
254 static int cgroup_is_releasable(const struct cgroup *cgrp)
257 (1 << CGRP_RELEASABLE) |
258 (1 << CGRP_NOTIFY_ON_RELEASE);
259 return (cgrp->flags & bits) == bits;
262 static int notify_on_release(const struct cgroup *cgrp)
264 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
268 * for_each_subsys() allows you to iterate on each subsystem attached to
269 * an active hierarchy
271 #define for_each_subsys(_root, _ss) \
272 list_for_each_entry(_ss, &_root->subsys_list, sibling)
274 /* for_each_active_root() allows you to iterate across the active hierarchies */
275 #define for_each_active_root(_root) \
276 list_for_each_entry(_root, &roots, root_list)
278 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
280 return dentry->d_fsdata;
283 static inline struct cfent *__d_cfe(struct dentry *dentry)
285 return dentry->d_fsdata;
288 static inline struct cftype *__d_cft(struct dentry *dentry)
290 return __d_cfe(dentry)->type;
294 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
295 * @cgrp: the cgroup to be checked for liveness
297 * On success, returns true; the mutex should be later unlocked. On
298 * failure returns false with no lock held.
300 static bool cgroup_lock_live_group(struct cgroup *cgrp)
302 mutex_lock(&cgroup_mutex);
303 if (cgroup_is_dead(cgrp)) {
304 mutex_unlock(&cgroup_mutex);
310 /* the list of cgroups eligible for automatic release. Protected by
311 * release_list_lock */
312 static LIST_HEAD(release_list);
313 static DEFINE_RAW_SPINLOCK(release_list_lock);
314 static void cgroup_release_agent(struct work_struct *work);
315 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
316 static void check_for_release(struct cgroup *cgrp);
319 * A cgroup can be associated with multiple css_sets as different tasks may
320 * belong to different cgroups on different hierarchies. In the other
321 * direction, a css_set is naturally associated with multiple cgroups.
322 * This M:N relationship is represented by the following link structure
323 * which exists for each association and allows traversing the associations
326 struct cgrp_cset_link {
327 /* the cgroup and css_set this link associates */
329 struct css_set *cset;
331 /* list of cgrp_cset_links anchored at cgrp->cset_links */
332 struct list_head cset_link;
334 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
335 struct list_head cgrp_link;
338 /* The default css_set - used by init and its children prior to any
339 * hierarchies being mounted. It contains a pointer to the root state
340 * for each subsystem. Also used to anchor the list of css_sets. Not
341 * reference-counted, to improve performance when child cgroups
342 * haven't been created.
345 static struct css_set init_css_set;
346 static struct cgrp_cset_link init_cgrp_cset_link;
348 static int cgroup_init_idr(struct cgroup_subsys *ss,
349 struct cgroup_subsys_state *css);
351 /* css_set_lock protects the list of css_set objects, and the
352 * chain of tasks off each css_set. Nests outside task->alloc_lock
353 * due to cgroup_iter_start() */
354 static DEFINE_RWLOCK(css_set_lock);
355 static int css_set_count;
358 * hash table for cgroup groups. This improves the performance to find
359 * an existing css_set. This hash doesn't (currently) take into
360 * account cgroups in empty hierarchies.
362 #define CSS_SET_HASH_BITS 7
363 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
365 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
368 unsigned long key = 0UL;
370 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++)
371 key += (unsigned long)css[i];
372 key = (key >> 16) ^ key;
377 /* We don't maintain the lists running through each css_set to its
378 * task until after the first call to cgroup_iter_start(). This
379 * reduces the fork()/exit() overhead for people who have cgroups
380 * compiled into their kernel but not actually in use */
381 static int use_task_css_set_links __read_mostly;
383 static void __put_css_set(struct css_set *cset, int taskexit)
385 struct cgrp_cset_link *link, *tmp_link;
388 * Ensure that the refcount doesn't hit zero while any readers
389 * can see it. Similar to atomic_dec_and_lock(), but for an
392 if (atomic_add_unless(&cset->refcount, -1, 1))
394 write_lock(&css_set_lock);
395 if (!atomic_dec_and_test(&cset->refcount)) {
396 write_unlock(&css_set_lock);
400 /* This css_set is dead. unlink it and release cgroup refcounts */
401 hash_del(&cset->hlist);
404 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
405 struct cgroup *cgrp = link->cgrp;
407 list_del(&link->cset_link);
408 list_del(&link->cgrp_link);
410 /* @cgrp can't go away while we're holding css_set_lock */
411 if (list_empty(&cgrp->cset_links) && notify_on_release(cgrp)) {
413 set_bit(CGRP_RELEASABLE, &cgrp->flags);
414 check_for_release(cgrp);
420 write_unlock(&css_set_lock);
421 kfree_rcu(cset, rcu_head);
425 * refcounted get/put for css_set objects
427 static inline void get_css_set(struct css_set *cset)
429 atomic_inc(&cset->refcount);
432 static inline void put_css_set(struct css_set *cset)
434 __put_css_set(cset, 0);
437 static inline void put_css_set_taskexit(struct css_set *cset)
439 __put_css_set(cset, 1);
443 * compare_css_sets - helper function for find_existing_css_set().
444 * @cset: candidate css_set being tested
445 * @old_cset: existing css_set for a task
446 * @new_cgrp: cgroup that's being entered by the task
447 * @template: desired set of css pointers in css_set (pre-calculated)
449 * Returns true if "cg" matches "old_cg" except for the hierarchy
450 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
452 static bool compare_css_sets(struct css_set *cset,
453 struct css_set *old_cset,
454 struct cgroup *new_cgrp,
455 struct cgroup_subsys_state *template[])
457 struct list_head *l1, *l2;
459 if (memcmp(template, cset->subsys, sizeof(cset->subsys))) {
460 /* Not all subsystems matched */
465 * Compare cgroup pointers in order to distinguish between
466 * different cgroups in heirarchies with no subsystems. We
467 * could get by with just this check alone (and skip the
468 * memcmp above) but on most setups the memcmp check will
469 * avoid the need for this more expensive check on almost all
473 l1 = &cset->cgrp_links;
474 l2 = &old_cset->cgrp_links;
476 struct cgrp_cset_link *link1, *link2;
477 struct cgroup *cgrp1, *cgrp2;
481 /* See if we reached the end - both lists are equal length. */
482 if (l1 == &cset->cgrp_links) {
483 BUG_ON(l2 != &old_cset->cgrp_links);
486 BUG_ON(l2 == &old_cset->cgrp_links);
488 /* Locate the cgroups associated with these links. */
489 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
490 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
493 /* Hierarchies should be linked in the same order. */
494 BUG_ON(cgrp1->root != cgrp2->root);
497 * If this hierarchy is the hierarchy of the cgroup
498 * that's changing, then we need to check that this
499 * css_set points to the new cgroup; if it's any other
500 * hierarchy, then this css_set should point to the
501 * same cgroup as the old css_set.
503 if (cgrp1->root == new_cgrp->root) {
504 if (cgrp1 != new_cgrp)
515 * find_existing_css_set() is a helper for
516 * find_css_set(), and checks to see whether an existing
517 * css_set is suitable.
519 * oldcg: the cgroup group that we're using before the cgroup
522 * cgrp: the cgroup that we're moving into
524 * template: location in which to build the desired set of subsystem
525 * state objects for the new cgroup group
527 static struct css_set *find_existing_css_set(struct css_set *old_cset,
529 struct cgroup_subsys_state *template[])
532 struct cgroupfs_root *root = cgrp->root;
533 struct css_set *cset;
537 * Build the set of subsystem state objects that we want to see in the
538 * new css_set. while subsystems can change globally, the entries here
539 * won't change, so no need for locking.
541 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
542 if (root->subsys_mask & (1UL << i)) {
543 /* Subsystem is in this hierarchy. So we want
544 * the subsystem state from the new
546 template[i] = cgrp->subsys[i];
548 /* Subsystem is not in this hierarchy, so we
549 * don't want to change the subsystem state */
550 template[i] = old_cset->subsys[i];
554 key = css_set_hash(template);
555 hash_for_each_possible(css_set_table, cset, hlist, key) {
556 if (!compare_css_sets(cset, old_cset, cgrp, template))
559 /* This css_set matches what we need */
563 /* No existing cgroup group matched */
567 static void free_cgrp_cset_links(struct list_head *links_to_free)
569 struct cgrp_cset_link *link, *tmp_link;
571 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
572 list_del(&link->cset_link);
578 * allocate_cgrp_cset_links - allocate cgrp_cset_links
579 * @count: the number of links to allocate
580 * @tmp_links: list_head the allocated links are put on
582 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
583 * through ->cset_link. Returns 0 on success or -errno.
585 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
587 struct cgrp_cset_link *link;
590 INIT_LIST_HEAD(tmp_links);
592 for (i = 0; i < count; i++) {
593 link = kzalloc(sizeof(*link), GFP_KERNEL);
595 free_cgrp_cset_links(tmp_links);
598 list_add(&link->cset_link, tmp_links);
604 * link_css_set - a helper function to link a css_set to a cgroup
605 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
606 * @cset: the css_set to be linked
607 * @cgrp: the destination cgroup
609 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
612 struct cgrp_cset_link *link;
614 BUG_ON(list_empty(tmp_links));
615 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
618 list_move(&link->cset_link, &cgrp->cset_links);
620 * Always add links to the tail of the list so that the list
621 * is sorted by order of hierarchy creation
623 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
627 * find_css_set() takes an existing cgroup group and a
628 * cgroup object, and returns a css_set object that's
629 * equivalent to the old group, but with the given cgroup
630 * substituted into the appropriate hierarchy. Must be called with
633 static struct css_set *find_css_set(struct css_set *old_cset,
636 struct css_set *cset;
637 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT];
638 struct list_head tmp_links;
639 struct cgrp_cset_link *link;
642 /* First see if we already have a cgroup group that matches
644 read_lock(&css_set_lock);
645 cset = find_existing_css_set(old_cset, cgrp, template);
648 read_unlock(&css_set_lock);
653 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
657 /* Allocate all the cgrp_cset_link objects that we'll need */
658 if (allocate_cgrp_cset_links(root_count, &tmp_links) < 0) {
663 atomic_set(&cset->refcount, 1);
664 INIT_LIST_HEAD(&cset->cgrp_links);
665 INIT_LIST_HEAD(&cset->tasks);
666 INIT_HLIST_NODE(&cset->hlist);
668 /* Copy the set of subsystem state objects generated in
669 * find_existing_css_set() */
670 memcpy(cset->subsys, template, sizeof(cset->subsys));
672 write_lock(&css_set_lock);
673 /* Add reference counts and links from the new css_set. */
674 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
675 struct cgroup *c = link->cgrp;
677 if (c->root == cgrp->root)
679 link_css_set(&tmp_links, cset, c);
682 BUG_ON(!list_empty(&tmp_links));
686 /* Add this cgroup group to the hash table */
687 key = css_set_hash(cset->subsys);
688 hash_add(css_set_table, &cset->hlist, key);
690 write_unlock(&css_set_lock);
696 * Return the cgroup for "task" from the given hierarchy. Must be
697 * called with cgroup_mutex held.
699 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
700 struct cgroupfs_root *root)
702 struct css_set *cset;
703 struct cgroup *res = NULL;
705 BUG_ON(!mutex_is_locked(&cgroup_mutex));
706 read_lock(&css_set_lock);
708 * No need to lock the task - since we hold cgroup_mutex the
709 * task can't change groups, so the only thing that can happen
710 * is that it exits and its css is set back to init_css_set.
712 cset = task->cgroups;
713 if (cset == &init_css_set) {
714 res = &root->top_cgroup;
716 struct cgrp_cset_link *link;
718 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
719 struct cgroup *c = link->cgrp;
721 if (c->root == root) {
727 read_unlock(&css_set_lock);
733 * There is one global cgroup mutex. We also require taking
734 * task_lock() when dereferencing a task's cgroup subsys pointers.
735 * See "The task_lock() exception", at the end of this comment.
737 * A task must hold cgroup_mutex to modify cgroups.
739 * Any task can increment and decrement the count field without lock.
740 * So in general, code holding cgroup_mutex can't rely on the count
741 * field not changing. However, if the count goes to zero, then only
742 * cgroup_attach_task() can increment it again. Because a count of zero
743 * means that no tasks are currently attached, therefore there is no
744 * way a task attached to that cgroup can fork (the other way to
745 * increment the count). So code holding cgroup_mutex can safely
746 * assume that if the count is zero, it will stay zero. Similarly, if
747 * a task holds cgroup_mutex on a cgroup with zero count, it
748 * knows that the cgroup won't be removed, as cgroup_rmdir()
751 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
752 * (usually) take cgroup_mutex. These are the two most performance
753 * critical pieces of code here. The exception occurs on cgroup_exit(),
754 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
755 * is taken, and if the cgroup count is zero, a usermode call made
756 * to the release agent with the name of the cgroup (path relative to
757 * the root of cgroup file system) as the argument.
759 * A cgroup can only be deleted if both its 'count' of using tasks
760 * is zero, and its list of 'children' cgroups is empty. Since all
761 * tasks in the system use _some_ cgroup, and since there is always at
762 * least one task in the system (init, pid == 1), therefore, top_cgroup
763 * always has either children cgroups and/or using tasks. So we don't
764 * need a special hack to ensure that top_cgroup cannot be deleted.
766 * The task_lock() exception
768 * The need for this exception arises from the action of
769 * cgroup_attach_task(), which overwrites one task's cgroup pointer with
770 * another. It does so using cgroup_mutex, however there are
771 * several performance critical places that need to reference
772 * task->cgroup without the expense of grabbing a system global
773 * mutex. Therefore except as noted below, when dereferencing or, as
774 * in cgroup_attach_task(), modifying a task's cgroup pointer we use
775 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
776 * the task_struct routinely used for such matters.
778 * P.S. One more locking exception. RCU is used to guard the
779 * update of a tasks cgroup pointer by cgroup_attach_task()
783 * A couple of forward declarations required, due to cyclic reference loop:
784 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
785 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
789 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode);
790 static struct dentry *cgroup_lookup(struct inode *, struct dentry *, unsigned int);
791 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
792 static int cgroup_populate_dir(struct cgroup *cgrp, bool base_files,
793 unsigned long subsys_mask);
794 static const struct inode_operations cgroup_dir_inode_operations;
795 static const struct file_operations proc_cgroupstats_operations;
797 static struct backing_dev_info cgroup_backing_dev_info = {
799 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
802 static int alloc_css_id(struct cgroup_subsys *ss,
803 struct cgroup *parent, struct cgroup *child);
805 static struct inode *cgroup_new_inode(umode_t mode, struct super_block *sb)
807 struct inode *inode = new_inode(sb);
810 inode->i_ino = get_next_ino();
811 inode->i_mode = mode;
812 inode->i_uid = current_fsuid();
813 inode->i_gid = current_fsgid();
814 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
815 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
820 static struct cgroup_name *cgroup_alloc_name(struct dentry *dentry)
822 struct cgroup_name *name;
824 name = kmalloc(sizeof(*name) + dentry->d_name.len + 1, GFP_KERNEL);
827 strcpy(name->name, dentry->d_name.name);
831 static void cgroup_free_fn(struct work_struct *work)
833 struct cgroup *cgrp = container_of(work, struct cgroup, free_work);
834 struct cgroup_subsys *ss;
836 mutex_lock(&cgroup_mutex);
838 * Release the subsystem state objects.
840 for_each_subsys(cgrp->root, ss)
843 cgrp->root->number_of_cgroups--;
844 mutex_unlock(&cgroup_mutex);
847 * We get a ref to the parent's dentry, and put the ref when
848 * this cgroup is being freed, so it's guaranteed that the
849 * parent won't be destroyed before its children.
851 dput(cgrp->parent->dentry);
853 ida_simple_remove(&cgrp->root->cgroup_ida, cgrp->id);
856 * Drop the active superblock reference that we took when we
857 * created the cgroup. This will free cgrp->root, if we are
858 * holding the last reference to @sb.
860 deactivate_super(cgrp->root->sb);
863 * if we're getting rid of the cgroup, refcount should ensure
864 * that there are no pidlists left.
866 BUG_ON(!list_empty(&cgrp->pidlists));
868 simple_xattrs_free(&cgrp->xattrs);
870 kfree(rcu_dereference_raw(cgrp->name));
874 static void cgroup_free_rcu(struct rcu_head *head)
876 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
878 schedule_work(&cgrp->free_work);
881 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
883 /* is dentry a directory ? if so, kfree() associated cgroup */
884 if (S_ISDIR(inode->i_mode)) {
885 struct cgroup *cgrp = dentry->d_fsdata;
887 BUG_ON(!(cgroup_is_dead(cgrp)));
888 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
890 struct cfent *cfe = __d_cfe(dentry);
891 struct cgroup *cgrp = dentry->d_parent->d_fsdata;
893 WARN_ONCE(!list_empty(&cfe->node) &&
894 cgrp != &cgrp->root->top_cgroup,
895 "cfe still linked for %s\n", cfe->type->name);
896 simple_xattrs_free(&cfe->xattrs);
902 static int cgroup_delete(const struct dentry *d)
907 static void remove_dir(struct dentry *d)
909 struct dentry *parent = dget(d->d_parent);
912 simple_rmdir(parent->d_inode, d);
916 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
920 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
921 lockdep_assert_held(&cgroup_mutex);
924 * If we're doing cleanup due to failure of cgroup_create(),
925 * the corresponding @cfe may not exist.
927 list_for_each_entry(cfe, &cgrp->files, node) {
928 struct dentry *d = cfe->dentry;
930 if (cft && cfe->type != cft)
935 simple_unlink(cgrp->dentry->d_inode, d);
936 list_del_init(&cfe->node);
944 * cgroup_clear_directory - selective removal of base and subsystem files
945 * @dir: directory containing the files
946 * @base_files: true if the base files should be removed
947 * @subsys_mask: mask of the subsystem ids whose files should be removed
949 static void cgroup_clear_directory(struct dentry *dir, bool base_files,
950 unsigned long subsys_mask)
952 struct cgroup *cgrp = __d_cgrp(dir);
953 struct cgroup_subsys *ss;
955 for_each_subsys(cgrp->root, ss) {
956 struct cftype_set *set;
957 if (!test_bit(ss->subsys_id, &subsys_mask))
959 list_for_each_entry(set, &ss->cftsets, node)
960 cgroup_addrm_files(cgrp, NULL, set->cfts, false);
963 while (!list_empty(&cgrp->files))
964 cgroup_rm_file(cgrp, NULL);
969 * NOTE : the dentry must have been dget()'ed
971 static void cgroup_d_remove_dir(struct dentry *dentry)
973 struct dentry *parent;
974 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
976 cgroup_clear_directory(dentry, true, root->subsys_mask);
978 parent = dentry->d_parent;
979 spin_lock(&parent->d_lock);
980 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
981 list_del_init(&dentry->d_u.d_child);
982 spin_unlock(&dentry->d_lock);
983 spin_unlock(&parent->d_lock);
988 * Call with cgroup_mutex held. Drops reference counts on modules, including
989 * any duplicate ones that parse_cgroupfs_options took. If this function
990 * returns an error, no reference counts are touched.
992 static int rebind_subsystems(struct cgroupfs_root *root,
993 unsigned long final_subsys_mask)
995 unsigned long added_mask, removed_mask;
996 struct cgroup *cgrp = &root->top_cgroup;
999 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1000 BUG_ON(!mutex_is_locked(&cgroup_root_mutex));
1002 removed_mask = root->actual_subsys_mask & ~final_subsys_mask;
1003 added_mask = final_subsys_mask & ~root->actual_subsys_mask;
1004 /* Check that any added subsystems are currently free */
1005 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1006 unsigned long bit = 1UL << i;
1007 struct cgroup_subsys *ss = subsys[i];
1008 if (!(bit & added_mask))
1011 * Nobody should tell us to do a subsys that doesn't exist:
1012 * parse_cgroupfs_options should catch that case and refcounts
1013 * ensure that subsystems won't disappear once selected.
1016 if (ss->root != &rootnode) {
1017 /* Subsystem isn't free */
1022 /* Currently we don't handle adding/removing subsystems when
1023 * any child cgroups exist. This is theoretically supportable
1024 * but involves complex error handling, so it's being left until
1026 if (root->number_of_cgroups > 1)
1029 /* Process each subsystem */
1030 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1031 struct cgroup_subsys *ss = subsys[i];
1032 unsigned long bit = 1UL << i;
1033 if (bit & added_mask) {
1034 /* We're binding this subsystem to this hierarchy */
1036 BUG_ON(cgrp->subsys[i]);
1037 BUG_ON(!dummytop->subsys[i]);
1038 BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
1039 cgrp->subsys[i] = dummytop->subsys[i];
1040 cgrp->subsys[i]->cgroup = cgrp;
1041 list_move(&ss->sibling, &root->subsys_list);
1045 /* refcount was already taken, and we're keeping it */
1046 } else if (bit & removed_mask) {
1047 /* We're removing this subsystem */
1049 BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
1050 BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
1053 dummytop->subsys[i]->cgroup = dummytop;
1054 cgrp->subsys[i] = NULL;
1055 subsys[i]->root = &rootnode;
1056 list_move(&ss->sibling, &rootnode.subsys_list);
1057 /* subsystem is now free - drop reference on module */
1058 module_put(ss->module);
1059 } else if (bit & final_subsys_mask) {
1060 /* Subsystem state should already exist */
1062 BUG_ON(!cgrp->subsys[i]);
1064 * a refcount was taken, but we already had one, so
1065 * drop the extra reference.
1067 module_put(ss->module);
1068 #ifdef CONFIG_MODULE_UNLOAD
1069 BUG_ON(ss->module && !module_refcount(ss->module));
1072 /* Subsystem state shouldn't exist */
1073 BUG_ON(cgrp->subsys[i]);
1076 root->subsys_mask = root->actual_subsys_mask = final_subsys_mask;
1081 static int cgroup_show_options(struct seq_file *seq, struct dentry *dentry)
1083 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
1084 struct cgroup_subsys *ss;
1086 mutex_lock(&cgroup_root_mutex);
1087 for_each_subsys(root, ss)
1088 seq_printf(seq, ",%s", ss->name);
1089 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1090 seq_puts(seq, ",sane_behavior");
1091 if (root->flags & CGRP_ROOT_NOPREFIX)
1092 seq_puts(seq, ",noprefix");
1093 if (root->flags & CGRP_ROOT_XATTR)
1094 seq_puts(seq, ",xattr");
1095 if (strlen(root->release_agent_path))
1096 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1097 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1098 seq_puts(seq, ",clone_children");
1099 if (strlen(root->name))
1100 seq_printf(seq, ",name=%s", root->name);
1101 mutex_unlock(&cgroup_root_mutex);
1105 struct cgroup_sb_opts {
1106 unsigned long subsys_mask;
1107 unsigned long flags;
1108 char *release_agent;
1109 bool cpuset_clone_children;
1111 /* User explicitly requested empty subsystem */
1114 struct cgroupfs_root *new_root;
1119 * Convert a hierarchy specifier into a bitmask of subsystems and flags. Call
1120 * with cgroup_mutex held to protect the subsys[] array. This function takes
1121 * refcounts on subsystems to be used, unless it returns error, in which case
1122 * no refcounts are taken.
1124 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1126 char *token, *o = data;
1127 bool all_ss = false, one_ss = false;
1128 unsigned long mask = (unsigned long)-1;
1130 bool module_pin_failed = false;
1132 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1134 #ifdef CONFIG_CPUSETS
1135 mask = ~(1UL << cpuset_subsys_id);
1138 memset(opts, 0, sizeof(*opts));
1140 while ((token = strsep(&o, ",")) != NULL) {
1143 if (!strcmp(token, "none")) {
1144 /* Explicitly have no subsystems */
1148 if (!strcmp(token, "all")) {
1149 /* Mutually exclusive option 'all' + subsystem name */
1155 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1156 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1159 if (!strcmp(token, "noprefix")) {
1160 opts->flags |= CGRP_ROOT_NOPREFIX;
1163 if (!strcmp(token, "clone_children")) {
1164 opts->cpuset_clone_children = true;
1167 if (!strcmp(token, "xattr")) {
1168 opts->flags |= CGRP_ROOT_XATTR;
1171 if (!strncmp(token, "release_agent=", 14)) {
1172 /* Specifying two release agents is forbidden */
1173 if (opts->release_agent)
1175 opts->release_agent =
1176 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1177 if (!opts->release_agent)
1181 if (!strncmp(token, "name=", 5)) {
1182 const char *name = token + 5;
1183 /* Can't specify an empty name */
1186 /* Must match [\w.-]+ */
1187 for (i = 0; i < strlen(name); i++) {
1191 if ((c == '.') || (c == '-') || (c == '_'))
1195 /* Specifying two names is forbidden */
1198 opts->name = kstrndup(name,
1199 MAX_CGROUP_ROOT_NAMELEN - 1,
1207 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1208 struct cgroup_subsys *ss = subsys[i];
1211 if (strcmp(token, ss->name))
1216 /* Mutually exclusive option 'all' + subsystem name */
1219 set_bit(i, &opts->subsys_mask);
1224 if (i == CGROUP_SUBSYS_COUNT)
1229 * If the 'all' option was specified select all the subsystems,
1230 * otherwise if 'none', 'name=' and a subsystem name options
1231 * were not specified, let's default to 'all'
1233 if (all_ss || (!one_ss && !opts->none && !opts->name)) {
1234 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1235 struct cgroup_subsys *ss = subsys[i];
1240 set_bit(i, &opts->subsys_mask);
1244 /* Consistency checks */
1246 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1247 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1249 if (opts->flags & CGRP_ROOT_NOPREFIX) {
1250 pr_err("cgroup: sane_behavior: noprefix is not allowed\n");
1254 if (opts->cpuset_clone_children) {
1255 pr_err("cgroup: sane_behavior: clone_children is not allowed\n");
1261 * Option noprefix was introduced just for backward compatibility
1262 * with the old cpuset, so we allow noprefix only if mounting just
1263 * the cpuset subsystem.
1265 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1269 /* Can't specify "none" and some subsystems */
1270 if (opts->subsys_mask && opts->none)
1274 * We either have to specify by name or by subsystems. (So all
1275 * empty hierarchies must have a name).
1277 if (!opts->subsys_mask && !opts->name)
1281 * Grab references on all the modules we'll need, so the subsystems
1282 * don't dance around before rebind_subsystems attaches them. This may
1283 * take duplicate reference counts on a subsystem that's already used,
1284 * but rebind_subsystems handles this case.
1286 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1287 unsigned long bit = 1UL << i;
1289 if (!(bit & opts->subsys_mask))
1291 if (!try_module_get(subsys[i]->module)) {
1292 module_pin_failed = true;
1296 if (module_pin_failed) {
1298 * oops, one of the modules was going away. this means that we
1299 * raced with a module_delete call, and to the user this is
1300 * essentially a "subsystem doesn't exist" case.
1302 for (i--; i >= 0; i--) {
1303 /* drop refcounts only on the ones we took */
1304 unsigned long bit = 1UL << i;
1306 if (!(bit & opts->subsys_mask))
1308 module_put(subsys[i]->module);
1316 static void drop_parsed_module_refcounts(unsigned long subsys_mask)
1319 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1320 unsigned long bit = 1UL << i;
1322 if (!(bit & subsys_mask))
1324 module_put(subsys[i]->module);
1328 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1331 struct cgroupfs_root *root = sb->s_fs_info;
1332 struct cgroup *cgrp = &root->top_cgroup;
1333 struct cgroup_sb_opts opts;
1334 unsigned long added_mask, removed_mask;
1336 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1337 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1341 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1342 mutex_lock(&cgroup_mutex);
1343 mutex_lock(&cgroup_root_mutex);
1345 /* See what subsystems are wanted */
1346 ret = parse_cgroupfs_options(data, &opts);
1350 if (opts.subsys_mask != root->actual_subsys_mask || opts.release_agent)
1351 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1352 task_tgid_nr(current), current->comm);
1354 added_mask = opts.subsys_mask & ~root->subsys_mask;
1355 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1357 /* Don't allow flags or name to change at remount */
1358 if (opts.flags != root->flags ||
1359 (opts.name && strcmp(opts.name, root->name))) {
1361 drop_parsed_module_refcounts(opts.subsys_mask);
1366 * Clear out the files of subsystems that should be removed, do
1367 * this before rebind_subsystems, since rebind_subsystems may
1368 * change this hierarchy's subsys_list.
1370 cgroup_clear_directory(cgrp->dentry, false, removed_mask);
1372 ret = rebind_subsystems(root, opts.subsys_mask);
1374 /* rebind_subsystems failed, re-populate the removed files */
1375 cgroup_populate_dir(cgrp, false, removed_mask);
1376 drop_parsed_module_refcounts(opts.subsys_mask);
1380 /* re-populate subsystem files */
1381 cgroup_populate_dir(cgrp, false, added_mask);
1383 if (opts.release_agent)
1384 strcpy(root->release_agent_path, opts.release_agent);
1386 kfree(opts.release_agent);
1388 mutex_unlock(&cgroup_root_mutex);
1389 mutex_unlock(&cgroup_mutex);
1390 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1394 static const struct super_operations cgroup_ops = {
1395 .statfs = simple_statfs,
1396 .drop_inode = generic_delete_inode,
1397 .show_options = cgroup_show_options,
1398 .remount_fs = cgroup_remount,
1401 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1403 INIT_LIST_HEAD(&cgrp->sibling);
1404 INIT_LIST_HEAD(&cgrp->children);
1405 INIT_LIST_HEAD(&cgrp->files);
1406 INIT_LIST_HEAD(&cgrp->cset_links);
1407 INIT_LIST_HEAD(&cgrp->allcg_node);
1408 INIT_LIST_HEAD(&cgrp->release_list);
1409 INIT_LIST_HEAD(&cgrp->pidlists);
1410 INIT_WORK(&cgrp->free_work, cgroup_free_fn);
1411 mutex_init(&cgrp->pidlist_mutex);
1412 INIT_LIST_HEAD(&cgrp->event_list);
1413 spin_lock_init(&cgrp->event_list_lock);
1414 simple_xattrs_init(&cgrp->xattrs);
1417 static void init_cgroup_root(struct cgroupfs_root *root)
1419 struct cgroup *cgrp = &root->top_cgroup;
1421 INIT_LIST_HEAD(&root->subsys_list);
1422 INIT_LIST_HEAD(&root->root_list);
1423 INIT_LIST_HEAD(&root->allcg_list);
1424 root->number_of_cgroups = 1;
1426 cgrp->name = &root_cgroup_name;
1427 init_cgroup_housekeeping(cgrp);
1428 list_add_tail(&cgrp->allcg_node, &root->allcg_list);
1431 static int cgroup_init_root_id(struct cgroupfs_root *root)
1435 lockdep_assert_held(&cgroup_mutex);
1436 lockdep_assert_held(&cgroup_root_mutex);
1438 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 2, 0, GFP_KERNEL);
1442 root->hierarchy_id = id;
1446 static void cgroup_exit_root_id(struct cgroupfs_root *root)
1448 lockdep_assert_held(&cgroup_mutex);
1449 lockdep_assert_held(&cgroup_root_mutex);
1451 if (root->hierarchy_id) {
1452 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1453 root->hierarchy_id = 0;
1457 static int cgroup_test_super(struct super_block *sb, void *data)
1459 struct cgroup_sb_opts *opts = data;
1460 struct cgroupfs_root *root = sb->s_fs_info;
1462 /* If we asked for a name then it must match */
1463 if (opts->name && strcmp(opts->name, root->name))
1467 * If we asked for subsystems (or explicitly for no
1468 * subsystems) then they must match
1470 if ((opts->subsys_mask || opts->none)
1471 && (opts->subsys_mask != root->subsys_mask))
1477 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1479 struct cgroupfs_root *root;
1481 if (!opts->subsys_mask && !opts->none)
1484 root = kzalloc(sizeof(*root), GFP_KERNEL);
1486 return ERR_PTR(-ENOMEM);
1488 init_cgroup_root(root);
1490 root->subsys_mask = opts->subsys_mask;
1491 root->flags = opts->flags;
1492 ida_init(&root->cgroup_ida);
1493 if (opts->release_agent)
1494 strcpy(root->release_agent_path, opts->release_agent);
1496 strcpy(root->name, opts->name);
1497 if (opts->cpuset_clone_children)
1498 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1502 static void cgroup_free_root(struct cgroupfs_root *root)
1505 /* hierarhcy ID shoulid already have been released */
1506 WARN_ON_ONCE(root->hierarchy_id);
1508 ida_destroy(&root->cgroup_ida);
1513 static int cgroup_set_super(struct super_block *sb, void *data)
1516 struct cgroup_sb_opts *opts = data;
1518 /* If we don't have a new root, we can't set up a new sb */
1519 if (!opts->new_root)
1522 BUG_ON(!opts->subsys_mask && !opts->none);
1524 ret = set_anon_super(sb, NULL);
1528 sb->s_fs_info = opts->new_root;
1529 opts->new_root->sb = sb;
1531 sb->s_blocksize = PAGE_CACHE_SIZE;
1532 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1533 sb->s_magic = CGROUP_SUPER_MAGIC;
1534 sb->s_op = &cgroup_ops;
1539 static int cgroup_get_rootdir(struct super_block *sb)
1541 static const struct dentry_operations cgroup_dops = {
1542 .d_iput = cgroup_diput,
1543 .d_delete = cgroup_delete,
1546 struct inode *inode =
1547 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1552 inode->i_fop = &simple_dir_operations;
1553 inode->i_op = &cgroup_dir_inode_operations;
1554 /* directories start off with i_nlink == 2 (for "." entry) */
1556 sb->s_root = d_make_root(inode);
1559 /* for everything else we want ->d_op set */
1560 sb->s_d_op = &cgroup_dops;
1564 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1565 int flags, const char *unused_dev_name,
1568 struct cgroup_sb_opts opts;
1569 struct cgroupfs_root *root;
1571 struct super_block *sb;
1572 struct cgroupfs_root *new_root;
1573 struct inode *inode;
1575 /* First find the desired set of subsystems */
1576 mutex_lock(&cgroup_mutex);
1577 ret = parse_cgroupfs_options(data, &opts);
1578 mutex_unlock(&cgroup_mutex);
1583 * Allocate a new cgroup root. We may not need it if we're
1584 * reusing an existing hierarchy.
1586 new_root = cgroup_root_from_opts(&opts);
1587 if (IS_ERR(new_root)) {
1588 ret = PTR_ERR(new_root);
1591 opts.new_root = new_root;
1593 /* Locate an existing or new sb for this hierarchy */
1594 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1597 cgroup_free_root(opts.new_root);
1601 root = sb->s_fs_info;
1603 if (root == opts.new_root) {
1604 /* We used the new root structure, so this is a new hierarchy */
1605 struct list_head tmp_links;
1606 struct cgroup *root_cgrp = &root->top_cgroup;
1607 struct cgroupfs_root *existing_root;
1608 const struct cred *cred;
1610 struct css_set *cset;
1612 BUG_ON(sb->s_root != NULL);
1614 ret = cgroup_get_rootdir(sb);
1616 goto drop_new_super;
1617 inode = sb->s_root->d_inode;
1619 mutex_lock(&inode->i_mutex);
1620 mutex_lock(&cgroup_mutex);
1621 mutex_lock(&cgroup_root_mutex);
1623 /* Check for name clashes with existing mounts */
1625 if (strlen(root->name))
1626 for_each_active_root(existing_root)
1627 if (!strcmp(existing_root->name, root->name))
1631 * We're accessing css_set_count without locking
1632 * css_set_lock here, but that's OK - it can only be
1633 * increased by someone holding cgroup_lock, and
1634 * that's us. The worst that can happen is that we
1635 * have some link structures left over
1637 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1641 ret = cgroup_init_root_id(root);
1645 ret = rebind_subsystems(root, root->subsys_mask);
1646 if (ret == -EBUSY) {
1647 free_cgrp_cset_links(&tmp_links);
1651 * There must be no failure case after here, since rebinding
1652 * takes care of subsystems' refcounts, which are explicitly
1653 * dropped in the failure exit path.
1656 /* EBUSY should be the only error here */
1659 list_add(&root->root_list, &roots);
1662 sb->s_root->d_fsdata = root_cgrp;
1663 root->top_cgroup.dentry = sb->s_root;
1665 /* Link the top cgroup in this hierarchy into all
1666 * the css_set objects */
1667 write_lock(&css_set_lock);
1668 hash_for_each(css_set_table, i, cset, hlist)
1669 link_css_set(&tmp_links, cset, root_cgrp);
1670 write_unlock(&css_set_lock);
1672 free_cgrp_cset_links(&tmp_links);
1674 BUG_ON(!list_empty(&root_cgrp->children));
1675 BUG_ON(root->number_of_cgroups != 1);
1677 cred = override_creds(&init_cred);
1678 cgroup_populate_dir(root_cgrp, true, root->subsys_mask);
1680 mutex_unlock(&cgroup_root_mutex);
1681 mutex_unlock(&cgroup_mutex);
1682 mutex_unlock(&inode->i_mutex);
1685 * We re-used an existing hierarchy - the new root (if
1686 * any) is not needed
1688 cgroup_free_root(opts.new_root);
1690 if (((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) &&
1691 root->flags != opts.flags) {
1692 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1694 goto drop_new_super;
1697 /* no subsys rebinding, so refcounts don't change */
1698 drop_parsed_module_refcounts(opts.subsys_mask);
1701 kfree(opts.release_agent);
1703 return dget(sb->s_root);
1706 cgroup_exit_root_id(root);
1707 mutex_unlock(&cgroup_root_mutex);
1708 mutex_unlock(&cgroup_mutex);
1709 mutex_unlock(&inode->i_mutex);
1711 deactivate_locked_super(sb);
1713 drop_parsed_module_refcounts(opts.subsys_mask);
1715 kfree(opts.release_agent);
1717 return ERR_PTR(ret);
1720 static void cgroup_kill_sb(struct super_block *sb) {
1721 struct cgroupfs_root *root = sb->s_fs_info;
1722 struct cgroup *cgrp = &root->top_cgroup;
1723 struct cgrp_cset_link *link, *tmp_link;
1728 BUG_ON(root->number_of_cgroups != 1);
1729 BUG_ON(!list_empty(&cgrp->children));
1731 mutex_lock(&cgroup_mutex);
1732 mutex_lock(&cgroup_root_mutex);
1734 /* Rebind all subsystems back to the default hierarchy */
1735 ret = rebind_subsystems(root, 0);
1736 /* Shouldn't be able to fail ... */
1740 * Release all the links from cset_links to this hierarchy's
1743 write_lock(&css_set_lock);
1745 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1746 list_del(&link->cset_link);
1747 list_del(&link->cgrp_link);
1750 write_unlock(&css_set_lock);
1752 if (!list_empty(&root->root_list)) {
1753 list_del(&root->root_list);
1757 cgroup_exit_root_id(root);
1759 mutex_unlock(&cgroup_root_mutex);
1760 mutex_unlock(&cgroup_mutex);
1762 simple_xattrs_free(&cgrp->xattrs);
1764 kill_litter_super(sb);
1765 cgroup_free_root(root);
1768 static struct file_system_type cgroup_fs_type = {
1770 .mount = cgroup_mount,
1771 .kill_sb = cgroup_kill_sb,
1774 static struct kobject *cgroup_kobj;
1777 * cgroup_path - generate the path of a cgroup
1778 * @cgrp: the cgroup in question
1779 * @buf: the buffer to write the path into
1780 * @buflen: the length of the buffer
1782 * Writes path of cgroup into buf. Returns 0 on success, -errno on error.
1784 * We can't generate cgroup path using dentry->d_name, as accessing
1785 * dentry->name must be protected by irq-unsafe dentry->d_lock or parent
1786 * inode's i_mutex, while on the other hand cgroup_path() can be called
1787 * with some irq-safe spinlocks held.
1789 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1791 int ret = -ENAMETOOLONG;
1794 if (!cgrp->parent) {
1795 if (strlcpy(buf, "/", buflen) >= buflen)
1796 return -ENAMETOOLONG;
1800 start = buf + buflen - 1;
1805 const char *name = cgroup_name(cgrp);
1809 if ((start -= len) < buf)
1811 memcpy(start, name, len);
1817 cgrp = cgrp->parent;
1818 } while (cgrp->parent);
1820 memmove(buf, start, buf + buflen - start);
1825 EXPORT_SYMBOL_GPL(cgroup_path);
1828 * task_cgroup_path_from_hierarchy - cgroup path of a task on a hierarchy
1829 * @task: target task
1830 * @hierarchy_id: the hierarchy to look up @task's cgroup from
1831 * @buf: the buffer to write the path into
1832 * @buflen: the length of the buffer
1834 * Determine @task's cgroup on the hierarchy specified by @hierarchy_id and
1835 * copy its path into @buf. This function grabs cgroup_mutex and shouldn't
1836 * be used inside locks used by cgroup controller callbacks.
1838 int task_cgroup_path_from_hierarchy(struct task_struct *task, int hierarchy_id,
1839 char *buf, size_t buflen)
1841 struct cgroupfs_root *root;
1842 struct cgroup *cgrp = NULL;
1845 mutex_lock(&cgroup_mutex);
1847 root = idr_find(&cgroup_hierarchy_idr, hierarchy_id);
1849 cgrp = task_cgroup_from_root(task, root);
1850 ret = cgroup_path(cgrp, buf, buflen);
1853 mutex_unlock(&cgroup_mutex);
1857 EXPORT_SYMBOL_GPL(task_cgroup_path_from_hierarchy);
1860 * Control Group taskset
1862 struct task_and_cgroup {
1863 struct task_struct *task;
1864 struct cgroup *cgrp;
1868 struct cgroup_taskset {
1869 struct task_and_cgroup single;
1870 struct flex_array *tc_array;
1873 struct cgroup *cur_cgrp;
1877 * cgroup_taskset_first - reset taskset and return the first task
1878 * @tset: taskset of interest
1880 * @tset iteration is initialized and the first task is returned.
1882 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1884 if (tset->tc_array) {
1886 return cgroup_taskset_next(tset);
1888 tset->cur_cgrp = tset->single.cgrp;
1889 return tset->single.task;
1892 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1895 * cgroup_taskset_next - iterate to the next task in taskset
1896 * @tset: taskset of interest
1898 * Return the next task in @tset. Iteration must have been initialized
1899 * with cgroup_taskset_first().
1901 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1903 struct task_and_cgroup *tc;
1905 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1908 tc = flex_array_get(tset->tc_array, tset->idx++);
1909 tset->cur_cgrp = tc->cgrp;
1912 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1915 * cgroup_taskset_cur_cgroup - return the matching cgroup for the current task
1916 * @tset: taskset of interest
1918 * Return the cgroup for the current (last returned) task of @tset. This
1919 * function must be preceded by either cgroup_taskset_first() or
1920 * cgroup_taskset_next().
1922 struct cgroup *cgroup_taskset_cur_cgroup(struct cgroup_taskset *tset)
1924 return tset->cur_cgrp;
1926 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_cgroup);
1929 * cgroup_taskset_size - return the number of tasks in taskset
1930 * @tset: taskset of interest
1932 int cgroup_taskset_size(struct cgroup_taskset *tset)
1934 return tset->tc_array ? tset->tc_array_len : 1;
1936 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1940 * cgroup_task_migrate - move a task from one cgroup to another.
1942 * Must be called with cgroup_mutex and threadgroup locked.
1944 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1945 struct task_struct *tsk,
1946 struct css_set *new_cset)
1948 struct css_set *old_cset;
1951 * We are synchronized through threadgroup_lock() against PF_EXITING
1952 * setting such that we can't race against cgroup_exit() changing the
1953 * css_set to init_css_set and dropping the old one.
1955 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1956 old_cset = tsk->cgroups;
1959 rcu_assign_pointer(tsk->cgroups, new_cset);
1962 /* Update the css_set linked lists if we're using them */
1963 write_lock(&css_set_lock);
1964 if (!list_empty(&tsk->cg_list))
1965 list_move(&tsk->cg_list, &new_cset->tasks);
1966 write_unlock(&css_set_lock);
1969 * We just gained a reference on old_cset by taking it from the
1970 * task. As trading it for new_cset is protected by cgroup_mutex,
1971 * we're safe to drop it here; it will be freed under RCU.
1973 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1974 put_css_set(old_cset);
1978 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1979 * @cgrp: the cgroup to attach to
1980 * @tsk: the task or the leader of the threadgroup to be attached
1981 * @threadgroup: attach the whole threadgroup?
1983 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
1984 * task_lock of @tsk or each thread in the threadgroup individually in turn.
1986 static int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk,
1989 int retval, i, group_size;
1990 struct cgroup_subsys *ss, *failed_ss = NULL;
1991 struct cgroupfs_root *root = cgrp->root;
1992 /* threadgroup list cursor and array */
1993 struct task_struct *leader = tsk;
1994 struct task_and_cgroup *tc;
1995 struct flex_array *group;
1996 struct cgroup_taskset tset = { };
1999 * step 0: in order to do expensive, possibly blocking operations for
2000 * every thread, we cannot iterate the thread group list, since it needs
2001 * rcu or tasklist locked. instead, build an array of all threads in the
2002 * group - group_rwsem prevents new threads from appearing, and if
2003 * threads exit, this will just be an over-estimate.
2006 group_size = get_nr_threads(tsk);
2009 /* flex_array supports very large thread-groups better than kmalloc. */
2010 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
2013 /* pre-allocate to guarantee space while iterating in rcu read-side. */
2014 retval = flex_array_prealloc(group, 0, group_size, GFP_KERNEL);
2016 goto out_free_group_list;
2020 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2021 * already PF_EXITING could be freed from underneath us unless we
2022 * take an rcu_read_lock.
2026 struct task_and_cgroup ent;
2028 /* @tsk either already exited or can't exit until the end */
2029 if (tsk->flags & PF_EXITING)
2032 /* as per above, nr_threads may decrease, but not increase. */
2033 BUG_ON(i >= group_size);
2035 ent.cgrp = task_cgroup_from_root(tsk, root);
2036 /* nothing to do if this task is already in the cgroup */
2037 if (ent.cgrp == cgrp)
2040 * saying GFP_ATOMIC has no effect here because we did prealloc
2041 * earlier, but it's good form to communicate our expectations.
2043 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
2044 BUG_ON(retval != 0);
2049 } while_each_thread(leader, tsk);
2051 /* remember the number of threads in the array for later. */
2053 tset.tc_array = group;
2054 tset.tc_array_len = group_size;
2056 /* methods shouldn't be called if no task is actually migrating */
2059 goto out_free_group_list;
2062 * step 1: check that we can legitimately attach to the cgroup.
2064 for_each_subsys(root, ss) {
2065 if (ss->can_attach) {
2066 retval = ss->can_attach(cgrp, &tset);
2069 goto out_cancel_attach;
2075 * step 2: make sure css_sets exist for all threads to be migrated.
2076 * we use find_css_set, which allocates a new one if necessary.
2078 for (i = 0; i < group_size; i++) {
2079 tc = flex_array_get(group, i);
2080 tc->cg = find_css_set(tc->task->cgroups, cgrp);
2083 goto out_put_css_set_refs;
2088 * step 3: now that we're guaranteed success wrt the css_sets,
2089 * proceed to move all tasks to the new cgroup. There are no
2090 * failure cases after here, so this is the commit point.
2092 for (i = 0; i < group_size; i++) {
2093 tc = flex_array_get(group, i);
2094 cgroup_task_migrate(tc->cgrp, tc->task, tc->cg);
2096 /* nothing is sensitive to fork() after this point. */
2099 * step 4: do subsystem attach callbacks.
2101 for_each_subsys(root, ss) {
2103 ss->attach(cgrp, &tset);
2107 * step 5: success! and cleanup
2110 out_put_css_set_refs:
2112 for (i = 0; i < group_size; i++) {
2113 tc = flex_array_get(group, i);
2116 put_css_set(tc->cg);
2121 for_each_subsys(root, ss) {
2122 if (ss == failed_ss)
2124 if (ss->cancel_attach)
2125 ss->cancel_attach(cgrp, &tset);
2128 out_free_group_list:
2129 flex_array_free(group);
2134 * Find the task_struct of the task to attach by vpid and pass it along to the
2135 * function to attach either it or all tasks in its threadgroup. Will lock
2136 * cgroup_mutex and threadgroup; may take task_lock of task.
2138 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2140 struct task_struct *tsk;
2141 const struct cred *cred = current_cred(), *tcred;
2144 if (!cgroup_lock_live_group(cgrp))
2150 tsk = find_task_by_vpid(pid);
2154 goto out_unlock_cgroup;
2157 * even if we're attaching all tasks in the thread group, we
2158 * only need to check permissions on one of them.
2160 tcred = __task_cred(tsk);
2161 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2162 !uid_eq(cred->euid, tcred->uid) &&
2163 !uid_eq(cred->euid, tcred->suid)) {
2166 goto out_unlock_cgroup;
2172 tsk = tsk->group_leader;
2175 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2176 * trapped in a cpuset, or RT worker may be born in a cgroup
2177 * with no rt_runtime allocated. Just say no.
2179 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2182 goto out_unlock_cgroup;
2185 get_task_struct(tsk);
2188 threadgroup_lock(tsk);
2190 if (!thread_group_leader(tsk)) {
2192 * a race with de_thread from another thread's exec()
2193 * may strip us of our leadership, if this happens,
2194 * there is no choice but to throw this task away and
2195 * try again; this is
2196 * "double-double-toil-and-trouble-check locking".
2198 threadgroup_unlock(tsk);
2199 put_task_struct(tsk);
2200 goto retry_find_task;
2204 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2206 threadgroup_unlock(tsk);
2208 put_task_struct(tsk);
2210 mutex_unlock(&cgroup_mutex);
2215 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2216 * @from: attach to all cgroups of a given task
2217 * @tsk: the task to be attached
2219 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2221 struct cgroupfs_root *root;
2224 mutex_lock(&cgroup_mutex);
2225 for_each_active_root(root) {
2226 struct cgroup *from_cg = task_cgroup_from_root(from, root);
2228 retval = cgroup_attach_task(from_cg, tsk, false);
2232 mutex_unlock(&cgroup_mutex);
2236 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2238 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
2240 return attach_task_by_pid(cgrp, pid, false);
2243 static int cgroup_procs_write(struct cgroup *cgrp, struct cftype *cft, u64 tgid)
2245 return attach_task_by_pid(cgrp, tgid, true);
2248 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
2251 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
2252 if (strlen(buffer) >= PATH_MAX)
2254 if (!cgroup_lock_live_group(cgrp))
2256 mutex_lock(&cgroup_root_mutex);
2257 strcpy(cgrp->root->release_agent_path, buffer);
2258 mutex_unlock(&cgroup_root_mutex);
2259 mutex_unlock(&cgroup_mutex);
2263 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
2264 struct seq_file *seq)
2266 if (!cgroup_lock_live_group(cgrp))
2268 seq_puts(seq, cgrp->root->release_agent_path);
2269 seq_putc(seq, '\n');
2270 mutex_unlock(&cgroup_mutex);
2274 static int cgroup_sane_behavior_show(struct cgroup *cgrp, struct cftype *cft,
2275 struct seq_file *seq)
2277 seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
2281 /* A buffer size big enough for numbers or short strings */
2282 #define CGROUP_LOCAL_BUFFER_SIZE 64
2284 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
2286 const char __user *userbuf,
2287 size_t nbytes, loff_t *unused_ppos)
2289 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
2295 if (nbytes >= sizeof(buffer))
2297 if (copy_from_user(buffer, userbuf, nbytes))
2300 buffer[nbytes] = 0; /* nul-terminate */
2301 if (cft->write_u64) {
2302 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
2305 retval = cft->write_u64(cgrp, cft, val);
2307 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
2310 retval = cft->write_s64(cgrp, cft, val);
2317 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
2319 const char __user *userbuf,
2320 size_t nbytes, loff_t *unused_ppos)
2322 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
2324 size_t max_bytes = cft->max_write_len;
2325 char *buffer = local_buffer;
2328 max_bytes = sizeof(local_buffer) - 1;
2329 if (nbytes >= max_bytes)
2331 /* Allocate a dynamic buffer if we need one */
2332 if (nbytes >= sizeof(local_buffer)) {
2333 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2337 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2342 buffer[nbytes] = 0; /* nul-terminate */
2343 retval = cft->write_string(cgrp, cft, strstrip(buffer));
2347 if (buffer != local_buffer)
2352 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2353 size_t nbytes, loff_t *ppos)
2355 struct cftype *cft = __d_cft(file->f_dentry);
2356 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2358 if (cgroup_is_dead(cgrp))
2361 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
2362 if (cft->write_u64 || cft->write_s64)
2363 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
2364 if (cft->write_string)
2365 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
2367 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
2368 return ret ? ret : nbytes;
2373 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
2375 char __user *buf, size_t nbytes,
2378 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2379 u64 val = cft->read_u64(cgrp, cft);
2380 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2382 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2385 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
2387 char __user *buf, size_t nbytes,
2390 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2391 s64 val = cft->read_s64(cgrp, cft);
2392 int len = sprintf(tmp, "%lld\n", (long long) val);
2394 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2397 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2398 size_t nbytes, loff_t *ppos)
2400 struct cftype *cft = __d_cft(file->f_dentry);
2401 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2403 if (cgroup_is_dead(cgrp))
2407 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
2409 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
2411 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
2416 * seqfile ops/methods for returning structured data. Currently just
2417 * supports string->u64 maps, but can be extended in future.
2420 struct cgroup_seqfile_state {
2422 struct cgroup *cgroup;
2425 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2427 struct seq_file *sf = cb->state;
2428 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2431 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2433 struct cgroup_seqfile_state *state = m->private;
2434 struct cftype *cft = state->cft;
2435 if (cft->read_map) {
2436 struct cgroup_map_cb cb = {
2437 .fill = cgroup_map_add,
2440 return cft->read_map(state->cgroup, cft, &cb);
2442 return cft->read_seq_string(state->cgroup, cft, m);
2445 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
2447 struct seq_file *seq = file->private_data;
2448 kfree(seq->private);
2449 return single_release(inode, file);
2452 static const struct file_operations cgroup_seqfile_operations = {
2454 .write = cgroup_file_write,
2455 .llseek = seq_lseek,
2456 .release = cgroup_seqfile_release,
2459 static int cgroup_file_open(struct inode *inode, struct file *file)
2464 err = generic_file_open(inode, file);
2467 cft = __d_cft(file->f_dentry);
2469 if (cft->read_map || cft->read_seq_string) {
2470 struct cgroup_seqfile_state *state;
2472 state = kzalloc(sizeof(*state), GFP_USER);
2477 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
2478 file->f_op = &cgroup_seqfile_operations;
2479 err = single_open(file, cgroup_seqfile_show, state);
2482 } else if (cft->open)
2483 err = cft->open(inode, file);
2490 static int cgroup_file_release(struct inode *inode, struct file *file)
2492 struct cftype *cft = __d_cft(file->f_dentry);
2494 return cft->release(inode, file);
2499 * cgroup_rename - Only allow simple rename of directories in place.
2501 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2502 struct inode *new_dir, struct dentry *new_dentry)
2505 struct cgroup_name *name, *old_name;
2506 struct cgroup *cgrp;
2509 * It's convinient to use parent dir's i_mutex to protected
2512 lockdep_assert_held(&old_dir->i_mutex);
2514 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2516 if (new_dentry->d_inode)
2518 if (old_dir != new_dir)
2521 cgrp = __d_cgrp(old_dentry);
2523 name = cgroup_alloc_name(new_dentry);
2527 ret = simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2533 old_name = cgrp->name;
2534 rcu_assign_pointer(cgrp->name, name);
2536 kfree_rcu(old_name, rcu_head);
2540 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2542 if (S_ISDIR(dentry->d_inode->i_mode))
2543 return &__d_cgrp(dentry)->xattrs;
2545 return &__d_cfe(dentry)->xattrs;
2548 static inline int xattr_enabled(struct dentry *dentry)
2550 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2551 return root->flags & CGRP_ROOT_XATTR;
2554 static bool is_valid_xattr(const char *name)
2556 if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2557 !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2562 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2563 const void *val, size_t size, int flags)
2565 if (!xattr_enabled(dentry))
2567 if (!is_valid_xattr(name))
2569 return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2572 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2574 if (!xattr_enabled(dentry))
2576 if (!is_valid_xattr(name))
2578 return simple_xattr_remove(__d_xattrs(dentry), name);
2581 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2582 void *buf, size_t size)
2584 if (!xattr_enabled(dentry))
2586 if (!is_valid_xattr(name))
2588 return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2591 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2593 if (!xattr_enabled(dentry))
2595 return simple_xattr_list(__d_xattrs(dentry), buf, size);
2598 static const struct file_operations cgroup_file_operations = {
2599 .read = cgroup_file_read,
2600 .write = cgroup_file_write,
2601 .llseek = generic_file_llseek,
2602 .open = cgroup_file_open,
2603 .release = cgroup_file_release,
2606 static const struct inode_operations cgroup_file_inode_operations = {
2607 .setxattr = cgroup_setxattr,
2608 .getxattr = cgroup_getxattr,
2609 .listxattr = cgroup_listxattr,
2610 .removexattr = cgroup_removexattr,
2613 static const struct inode_operations cgroup_dir_inode_operations = {
2614 .lookup = cgroup_lookup,
2615 .mkdir = cgroup_mkdir,
2616 .rmdir = cgroup_rmdir,
2617 .rename = cgroup_rename,
2618 .setxattr = cgroup_setxattr,
2619 .getxattr = cgroup_getxattr,
2620 .listxattr = cgroup_listxattr,
2621 .removexattr = cgroup_removexattr,
2624 static struct dentry *cgroup_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
2626 if (dentry->d_name.len > NAME_MAX)
2627 return ERR_PTR(-ENAMETOOLONG);
2628 d_add(dentry, NULL);
2633 * Check if a file is a control file
2635 static inline struct cftype *__file_cft(struct file *file)
2637 if (file_inode(file)->i_fop != &cgroup_file_operations)
2638 return ERR_PTR(-EINVAL);
2639 return __d_cft(file->f_dentry);
2642 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2643 struct super_block *sb)
2645 struct inode *inode;
2649 if (dentry->d_inode)
2652 inode = cgroup_new_inode(mode, sb);
2656 if (S_ISDIR(mode)) {
2657 inode->i_op = &cgroup_dir_inode_operations;
2658 inode->i_fop = &simple_dir_operations;
2660 /* start off with i_nlink == 2 (for "." entry) */
2662 inc_nlink(dentry->d_parent->d_inode);
2665 * Control reaches here with cgroup_mutex held.
2666 * @inode->i_mutex should nest outside cgroup_mutex but we
2667 * want to populate it immediately without releasing
2668 * cgroup_mutex. As @inode isn't visible to anyone else
2669 * yet, trylock will always succeed without affecting
2672 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2673 } else if (S_ISREG(mode)) {
2675 inode->i_fop = &cgroup_file_operations;
2676 inode->i_op = &cgroup_file_inode_operations;
2678 d_instantiate(dentry, inode);
2679 dget(dentry); /* Extra count - pin the dentry in core */
2684 * cgroup_file_mode - deduce file mode of a control file
2685 * @cft: the control file in question
2687 * returns cft->mode if ->mode is not 0
2688 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2689 * returns S_IRUGO if it has only a read handler
2690 * returns S_IWUSR if it has only a write hander
2692 static umode_t cgroup_file_mode(const struct cftype *cft)
2699 if (cft->read || cft->read_u64 || cft->read_s64 ||
2700 cft->read_map || cft->read_seq_string)
2703 if (cft->write || cft->write_u64 || cft->write_s64 ||
2704 cft->write_string || cft->trigger)
2710 static int cgroup_add_file(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2713 struct dentry *dir = cgrp->dentry;
2714 struct cgroup *parent = __d_cgrp(dir);
2715 struct dentry *dentry;
2719 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2721 if (subsys && !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
2722 strcpy(name, subsys->name);
2725 strcat(name, cft->name);
2727 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2729 cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2733 dentry = lookup_one_len(name, dir, strlen(name));
2734 if (IS_ERR(dentry)) {
2735 error = PTR_ERR(dentry);
2739 cfe->type = (void *)cft;
2740 cfe->dentry = dentry;
2741 dentry->d_fsdata = cfe;
2742 simple_xattrs_init(&cfe->xattrs);
2744 mode = cgroup_file_mode(cft);
2745 error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2747 list_add_tail(&cfe->node, &parent->files);
2756 static int cgroup_addrm_files(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2757 struct cftype cfts[], bool is_add)
2762 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2763 /* does cft->flags tell us to skip this file on @cgrp? */
2764 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2766 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2768 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2772 err = cgroup_add_file(cgrp, subsys, cft);
2774 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2778 cgroup_rm_file(cgrp, cft);
2784 static DEFINE_MUTEX(cgroup_cft_mutex);
2786 static void cgroup_cfts_prepare(void)
2787 __acquires(&cgroup_cft_mutex) __acquires(&cgroup_mutex)
2790 * Thanks to the entanglement with vfs inode locking, we can't walk
2791 * the existing cgroups under cgroup_mutex and create files.
2792 * Instead, we increment reference on all cgroups and build list of
2793 * them using @cgrp->cft_q_node. Grab cgroup_cft_mutex to ensure
2794 * exclusive access to the field.
2796 mutex_lock(&cgroup_cft_mutex);
2797 mutex_lock(&cgroup_mutex);
2800 static void cgroup_cfts_commit(struct cgroup_subsys *ss,
2801 struct cftype *cfts, bool is_add)
2802 __releases(&cgroup_mutex) __releases(&cgroup_cft_mutex)
2805 struct cgroup *cgrp, *n;
2807 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2808 if (cfts && ss->root != &rootnode) {
2809 list_for_each_entry(cgrp, &ss->root->allcg_list, allcg_node) {
2811 list_add_tail(&cgrp->cft_q_node, &pending);
2815 mutex_unlock(&cgroup_mutex);
2818 * All new cgroups will see @cfts update on @ss->cftsets. Add/rm
2819 * files for all cgroups which were created before.
2821 list_for_each_entry_safe(cgrp, n, &pending, cft_q_node) {
2822 struct inode *inode = cgrp->dentry->d_inode;
2824 mutex_lock(&inode->i_mutex);
2825 mutex_lock(&cgroup_mutex);
2826 if (!cgroup_is_dead(cgrp))
2827 cgroup_addrm_files(cgrp, ss, cfts, is_add);
2828 mutex_unlock(&cgroup_mutex);
2829 mutex_unlock(&inode->i_mutex);
2831 list_del_init(&cgrp->cft_q_node);
2835 mutex_unlock(&cgroup_cft_mutex);
2839 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2840 * @ss: target cgroup subsystem
2841 * @cfts: zero-length name terminated array of cftypes
2843 * Register @cfts to @ss. Files described by @cfts are created for all
2844 * existing cgroups to which @ss is attached and all future cgroups will
2845 * have them too. This function can be called anytime whether @ss is
2848 * Returns 0 on successful registration, -errno on failure. Note that this
2849 * function currently returns 0 as long as @cfts registration is successful
2850 * even if some file creation attempts on existing cgroups fail.
2852 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2854 struct cftype_set *set;
2856 set = kzalloc(sizeof(*set), GFP_KERNEL);
2860 cgroup_cfts_prepare();
2862 list_add_tail(&set->node, &ss->cftsets);
2863 cgroup_cfts_commit(ss, cfts, true);
2867 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2870 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2871 * @ss: target cgroup subsystem
2872 * @cfts: zero-length name terminated array of cftypes
2874 * Unregister @cfts from @ss. Files described by @cfts are removed from
2875 * all existing cgroups to which @ss is attached and all future cgroups
2876 * won't have them either. This function can be called anytime whether @ss
2877 * is attached or not.
2879 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2880 * registered with @ss.
2882 int cgroup_rm_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2884 struct cftype_set *set;
2886 cgroup_cfts_prepare();
2888 list_for_each_entry(set, &ss->cftsets, node) {
2889 if (set->cfts == cfts) {
2890 list_del_init(&set->node);
2891 cgroup_cfts_commit(ss, cfts, false);
2896 cgroup_cfts_commit(ss, NULL, false);
2901 * cgroup_task_count - count the number of tasks in a cgroup.
2902 * @cgrp: the cgroup in question
2904 * Return the number of tasks in the cgroup.
2906 int cgroup_task_count(const struct cgroup *cgrp)
2909 struct cgrp_cset_link *link;
2911 read_lock(&css_set_lock);
2912 list_for_each_entry(link, &cgrp->cset_links, cset_link)
2913 count += atomic_read(&link->cset->refcount);
2914 read_unlock(&css_set_lock);
2919 * Advance a list_head iterator. The iterator should be positioned at
2920 * the start of a css_set
2922 static void cgroup_advance_iter(struct cgroup *cgrp, struct cgroup_iter *it)
2924 struct list_head *l = it->cset_link;
2925 struct cgrp_cset_link *link;
2926 struct css_set *cset;
2928 /* Advance to the next non-empty css_set */
2931 if (l == &cgrp->cset_links) {
2932 it->cset_link = NULL;
2935 link = list_entry(l, struct cgrp_cset_link, cset_link);
2937 } while (list_empty(&cset->tasks));
2939 it->task = cset->tasks.next;
2943 * To reduce the fork() overhead for systems that are not actually
2944 * using their cgroups capability, we don't maintain the lists running
2945 * through each css_set to its tasks until we see the list actually
2946 * used - in other words after the first call to cgroup_iter_start().
2948 static void cgroup_enable_task_cg_lists(void)
2950 struct task_struct *p, *g;
2951 write_lock(&css_set_lock);
2952 use_task_css_set_links = 1;
2954 * We need tasklist_lock because RCU is not safe against
2955 * while_each_thread(). Besides, a forking task that has passed
2956 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2957 * is not guaranteed to have its child immediately visible in the
2958 * tasklist if we walk through it with RCU.
2960 read_lock(&tasklist_lock);
2961 do_each_thread(g, p) {
2964 * We should check if the process is exiting, otherwise
2965 * it will race with cgroup_exit() in that the list
2966 * entry won't be deleted though the process has exited.
2968 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2969 list_add(&p->cg_list, &p->cgroups->tasks);
2971 } while_each_thread(g, p);
2972 read_unlock(&tasklist_lock);
2973 write_unlock(&css_set_lock);
2977 * cgroup_next_sibling - find the next sibling of a given cgroup
2978 * @pos: the current cgroup
2980 * This function returns the next sibling of @pos and should be called
2981 * under RCU read lock. The only requirement is that @pos is accessible.
2982 * The next sibling is guaranteed to be returned regardless of @pos's
2985 struct cgroup *cgroup_next_sibling(struct cgroup *pos)
2987 struct cgroup *next;
2989 WARN_ON_ONCE(!rcu_read_lock_held());
2992 * @pos could already have been removed. Once a cgroup is removed,
2993 * its ->sibling.next is no longer updated when its next sibling
2994 * changes. As CGRP_DEAD is set on removal which is fully
2995 * serialized, if we see it unasserted, it's guaranteed that the
2996 * next sibling hasn't finished its grace period even if it's
2997 * already removed, and thus safe to dereference from this RCU
2998 * critical section. If ->sibling.next is inaccessible,
2999 * cgroup_is_dead() is guaranteed to be visible as %true here.
3001 if (likely(!cgroup_is_dead(pos))) {
3002 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3003 if (&next->sibling != &pos->parent->children)
3009 * Can't dereference the next pointer. Each cgroup is given a
3010 * monotonically increasing unique serial number and always
3011 * appended to the sibling list, so the next one can be found by
3012 * walking the parent's children until we see a cgroup with higher
3013 * serial number than @pos's.
3015 * While this path can be slow, it's taken only when either the
3016 * current cgroup is removed or iteration and removal race.
3018 list_for_each_entry_rcu(next, &pos->parent->children, sibling)
3019 if (next->serial_nr > pos->serial_nr)
3023 EXPORT_SYMBOL_GPL(cgroup_next_sibling);
3026 * cgroup_next_descendant_pre - find the next descendant for pre-order walk
3027 * @pos: the current position (%NULL to initiate traversal)
3028 * @cgroup: cgroup whose descendants to walk
3030 * To be used by cgroup_for_each_descendant_pre(). Find the next
3031 * descendant to visit for pre-order traversal of @cgroup's descendants.
3033 * While this function requires RCU read locking, it doesn't require the
3034 * whole traversal to be contained in a single RCU critical section. This
3035 * function will return the correct next descendant as long as both @pos
3036 * and @cgroup are accessible and @pos is a descendant of @cgroup.
3038 struct cgroup *cgroup_next_descendant_pre(struct cgroup *pos,
3039 struct cgroup *cgroup)
3041 struct cgroup *next;
3043 WARN_ON_ONCE(!rcu_read_lock_held());
3045 /* if first iteration, pretend we just visited @cgroup */
3049 /* visit the first child if exists */
3050 next = list_first_or_null_rcu(&pos->children, struct cgroup, sibling);
3054 /* no child, visit my or the closest ancestor's next sibling */
3055 while (pos != cgroup) {
3056 next = cgroup_next_sibling(pos);
3064 EXPORT_SYMBOL_GPL(cgroup_next_descendant_pre);
3067 * cgroup_rightmost_descendant - return the rightmost descendant of a cgroup
3068 * @pos: cgroup of interest
3070 * Return the rightmost descendant of @pos. If there's no descendant,
3071 * @pos is returned. This can be used during pre-order traversal to skip
3074 * While this function requires RCU read locking, it doesn't require the
3075 * whole traversal to be contained in a single RCU critical section. This
3076 * function will return the correct rightmost descendant as long as @pos is
3079 struct cgroup *cgroup_rightmost_descendant(struct cgroup *pos)
3081 struct cgroup *last, *tmp;
3083 WARN_ON_ONCE(!rcu_read_lock_held());
3087 /* ->prev isn't RCU safe, walk ->next till the end */
3089 list_for_each_entry_rcu(tmp, &last->children, sibling)
3095 EXPORT_SYMBOL_GPL(cgroup_rightmost_descendant);
3097 static struct cgroup *cgroup_leftmost_descendant(struct cgroup *pos)
3099 struct cgroup *last;
3103 pos = list_first_or_null_rcu(&pos->children, struct cgroup,
3111 * cgroup_next_descendant_post - find the next descendant for post-order walk
3112 * @pos: the current position (%NULL to initiate traversal)
3113 * @cgroup: cgroup whose descendants to walk
3115 * To be used by cgroup_for_each_descendant_post(). Find the next
3116 * descendant to visit for post-order traversal of @cgroup's descendants.
3118 * While this function requires RCU read locking, it doesn't require the
3119 * whole traversal to be contained in a single RCU critical section. This
3120 * function will return the correct next descendant as long as both @pos
3121 * and @cgroup are accessible and @pos is a descendant of @cgroup.
3123 struct cgroup *cgroup_next_descendant_post(struct cgroup *pos,
3124 struct cgroup *cgroup)
3126 struct cgroup *next;
3128 WARN_ON_ONCE(!rcu_read_lock_held());
3130 /* if first iteration, visit the leftmost descendant */
3132 next = cgroup_leftmost_descendant(cgroup);
3133 return next != cgroup ? next : NULL;
3136 /* if there's an unvisited sibling, visit its leftmost descendant */
3137 next = cgroup_next_sibling(pos);
3139 return cgroup_leftmost_descendant(next);
3141 /* no sibling left, visit parent */
3143 return next != cgroup ? next : NULL;
3145 EXPORT_SYMBOL_GPL(cgroup_next_descendant_post);
3147 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
3148 __acquires(css_set_lock)
3151 * The first time anyone tries to iterate across a cgroup,
3152 * we need to enable the list linking each css_set to its
3153 * tasks, and fix up all existing tasks.
3155 if (!use_task_css_set_links)
3156 cgroup_enable_task_cg_lists();
3158 read_lock(&css_set_lock);
3159 it->cset_link = &cgrp->cset_links;
3160 cgroup_advance_iter(cgrp, it);
3163 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
3164 struct cgroup_iter *it)
3166 struct task_struct *res;
3167 struct list_head *l = it->task;
3168 struct cgrp_cset_link *link;
3170 /* If the iterator cg is NULL, we have no tasks */
3173 res = list_entry(l, struct task_struct, cg_list);
3174 /* Advance iterator to find next entry */
3176 link = list_entry(it->cset_link, struct cgrp_cset_link, cset_link);
3177 if (l == &link->cset->tasks) {
3178 /* We reached the end of this task list - move on to
3179 * the next cg_cgroup_link */
3180 cgroup_advance_iter(cgrp, it);
3187 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
3188 __releases(css_set_lock)
3190 read_unlock(&css_set_lock);
3193 static inline int started_after_time(struct task_struct *t1,
3194 struct timespec *time,
3195 struct task_struct *t2)
3197 int start_diff = timespec_compare(&t1->start_time, time);
3198 if (start_diff > 0) {
3200 } else if (start_diff < 0) {
3204 * Arbitrarily, if two processes started at the same
3205 * time, we'll say that the lower pointer value
3206 * started first. Note that t2 may have exited by now
3207 * so this may not be a valid pointer any longer, but
3208 * that's fine - it still serves to distinguish
3209 * between two tasks started (effectively) simultaneously.
3216 * This function is a callback from heap_insert() and is used to order
3218 * In this case we order the heap in descending task start time.
3220 static inline int started_after(void *p1, void *p2)
3222 struct task_struct *t1 = p1;
3223 struct task_struct *t2 = p2;
3224 return started_after_time(t1, &t2->start_time, t2);
3228 * cgroup_scan_tasks - iterate though all the tasks in a cgroup
3229 * @scan: struct cgroup_scanner containing arguments for the scan
3231 * Arguments include pointers to callback functions test_task() and
3233 * Iterate through all the tasks in a cgroup, calling test_task() for each,
3234 * and if it returns true, call process_task() for it also.
3235 * The test_task pointer may be NULL, meaning always true (select all tasks).
3236 * Effectively duplicates cgroup_iter_{start,next,end}()
3237 * but does not lock css_set_lock for the call to process_task().
3238 * The struct cgroup_scanner may be embedded in any structure of the caller's
3240 * It is guaranteed that process_task() will act on every task that
3241 * is a member of the cgroup for the duration of this call. This
3242 * function may or may not call process_task() for tasks that exit
3243 * or move to a different cgroup during the call, or are forked or
3244 * move into the cgroup during the call.
3246 * Note that test_task() may be called with locks held, and may in some
3247 * situations be called multiple times for the same task, so it should
3249 * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
3250 * pre-allocated and will be used for heap operations (and its "gt" member will
3251 * be overwritten), else a temporary heap will be used (allocation of which
3252 * may cause this function to fail).
3254 int cgroup_scan_tasks(struct cgroup_scanner *scan)
3257 struct cgroup_iter it;
3258 struct task_struct *p, *dropped;
3259 /* Never dereference latest_task, since it's not refcounted */
3260 struct task_struct *latest_task = NULL;
3261 struct ptr_heap tmp_heap;
3262 struct ptr_heap *heap;
3263 struct timespec latest_time = { 0, 0 };
3266 /* The caller supplied our heap and pre-allocated its memory */
3268 heap->gt = &started_after;
3270 /* We need to allocate our own heap memory */
3272 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3274 /* cannot allocate the heap */
3280 * Scan tasks in the cgroup, using the scanner's "test_task" callback
3281 * to determine which are of interest, and using the scanner's
3282 * "process_task" callback to process any of them that need an update.
3283 * Since we don't want to hold any locks during the task updates,
3284 * gather tasks to be processed in a heap structure.
3285 * The heap is sorted by descending task start time.
3286 * If the statically-sized heap fills up, we overflow tasks that
3287 * started later, and in future iterations only consider tasks that
3288 * started after the latest task in the previous pass. This
3289 * guarantees forward progress and that we don't miss any tasks.
3292 cgroup_iter_start(scan->cg, &it);
3293 while ((p = cgroup_iter_next(scan->cg, &it))) {
3295 * Only affect tasks that qualify per the caller's callback,
3296 * if he provided one
3298 if (scan->test_task && !scan->test_task(p, scan))
3301 * Only process tasks that started after the last task
3304 if (!started_after_time(p, &latest_time, latest_task))
3306 dropped = heap_insert(heap, p);
3307 if (dropped == NULL) {
3309 * The new task was inserted; the heap wasn't
3313 } else if (dropped != p) {
3315 * The new task was inserted, and pushed out a
3319 put_task_struct(dropped);
3322 * Else the new task was newer than anything already in
3323 * the heap and wasn't inserted
3326 cgroup_iter_end(scan->cg, &it);
3329 for (i = 0; i < heap->size; i++) {
3330 struct task_struct *q = heap->ptrs[i];
3332 latest_time = q->start_time;
3335 /* Process the task per the caller's callback */
3336 scan->process_task(q, scan);
3340 * If we had to process any tasks at all, scan again
3341 * in case some of them were in the middle of forking
3342 * children that didn't get processed.
3343 * Not the most efficient way to do it, but it avoids
3344 * having to take callback_mutex in the fork path
3348 if (heap == &tmp_heap)
3349 heap_free(&tmp_heap);
3353 static void cgroup_transfer_one_task(struct task_struct *task,
3354 struct cgroup_scanner *scan)
3356 struct cgroup *new_cgroup = scan->data;
3358 mutex_lock(&cgroup_mutex);
3359 cgroup_attach_task(new_cgroup, task, false);
3360 mutex_unlock(&cgroup_mutex);
3364 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3365 * @to: cgroup to which the tasks will be moved
3366 * @from: cgroup in which the tasks currently reside
3368 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3370 struct cgroup_scanner scan;
3373 scan.test_task = NULL; /* select all tasks in cgroup */
3374 scan.process_task = cgroup_transfer_one_task;
3378 return cgroup_scan_tasks(&scan);
3382 * Stuff for reading the 'tasks'/'procs' files.
3384 * Reading this file can return large amounts of data if a cgroup has
3385 * *lots* of attached tasks. So it may need several calls to read(),
3386 * but we cannot guarantee that the information we produce is correct
3387 * unless we produce it entirely atomically.
3391 /* which pidlist file are we talking about? */
3392 enum cgroup_filetype {
3398 * A pidlist is a list of pids that virtually represents the contents of one
3399 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3400 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3403 struct cgroup_pidlist {
3405 * used to find which pidlist is wanted. doesn't change as long as
3406 * this particular list stays in the list.
3408 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3411 /* how many elements the above list has */
3413 /* how many files are using the current array */
3415 /* each of these stored in a list by its cgroup */
3416 struct list_head links;
3417 /* pointer to the cgroup we belong to, for list removal purposes */
3418 struct cgroup *owner;
3419 /* protects the other fields */
3420 struct rw_semaphore mutex;
3424 * The following two functions "fix" the issue where there are more pids
3425 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3426 * TODO: replace with a kernel-wide solution to this problem
3428 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3429 static void *pidlist_allocate(int count)
3431 if (PIDLIST_TOO_LARGE(count))
3432 return vmalloc(count * sizeof(pid_t));
3434 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3436 static void pidlist_free(void *p)
3438 if (is_vmalloc_addr(p))
3445 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3446 * Returns the number of unique elements.
3448 static int pidlist_uniq(pid_t *list, int length)
3453 * we presume the 0th element is unique, so i starts at 1. trivial
3454 * edge cases first; no work needs to be done for either
3456 if (length == 0 || length == 1)
3458 /* src and dest walk down the list; dest counts unique elements */
3459 for (src = 1; src < length; src++) {
3460 /* find next unique element */
3461 while (list[src] == list[src-1]) {
3466 /* dest always points to where the next unique element goes */
3467 list[dest] = list[src];
3474 static int cmppid(const void *a, const void *b)
3476 return *(pid_t *)a - *(pid_t *)b;
3480 * find the appropriate pidlist for our purpose (given procs vs tasks)
3481 * returns with the lock on that pidlist already held, and takes care
3482 * of the use count, or returns NULL with no locks held if we're out of
3485 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3486 enum cgroup_filetype type)
3488 struct cgroup_pidlist *l;
3489 /* don't need task_nsproxy() if we're looking at ourself */
3490 struct pid_namespace *ns = task_active_pid_ns(current);
3493 * We can't drop the pidlist_mutex before taking the l->mutex in case
3494 * the last ref-holder is trying to remove l from the list at the same
3495 * time. Holding the pidlist_mutex precludes somebody taking whichever
3496 * list we find out from under us - compare release_pid_array().
3498 mutex_lock(&cgrp->pidlist_mutex);
3499 list_for_each_entry(l, &cgrp->pidlists, links) {
3500 if (l->key.type == type && l->key.ns == ns) {
3501 /* make sure l doesn't vanish out from under us */
3502 down_write(&l->mutex);
3503 mutex_unlock(&cgrp->pidlist_mutex);
3507 /* entry not found; create a new one */
3508 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3510 mutex_unlock(&cgrp->pidlist_mutex);
3513 init_rwsem(&l->mutex);
3514 down_write(&l->mutex);
3516 l->key.ns = get_pid_ns(ns);
3518 list_add(&l->links, &cgrp->pidlists);
3519 mutex_unlock(&cgrp->pidlist_mutex);
3524 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3526 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3527 struct cgroup_pidlist **lp)
3531 int pid, n = 0; /* used for populating the array */
3532 struct cgroup_iter it;
3533 struct task_struct *tsk;
3534 struct cgroup_pidlist *l;
3537 * If cgroup gets more users after we read count, we won't have
3538 * enough space - tough. This race is indistinguishable to the
3539 * caller from the case that the additional cgroup users didn't
3540 * show up until sometime later on.
3542 length = cgroup_task_count(cgrp);
3543 array = pidlist_allocate(length);
3546 /* now, populate the array */
3547 cgroup_iter_start(cgrp, &it);
3548 while ((tsk = cgroup_iter_next(cgrp, &it))) {
3549 if (unlikely(n == length))
3551 /* get tgid or pid for procs or tasks file respectively */
3552 if (type == CGROUP_FILE_PROCS)
3553 pid = task_tgid_vnr(tsk);
3555 pid = task_pid_vnr(tsk);
3556 if (pid > 0) /* make sure to only use valid results */
3559 cgroup_iter_end(cgrp, &it);
3561 /* now sort & (if procs) strip out duplicates */
3562 sort(array, length, sizeof(pid_t), cmppid, NULL);
3563 if (type == CGROUP_FILE_PROCS)
3564 length = pidlist_uniq(array, length);
3565 l = cgroup_pidlist_find(cgrp, type);
3567 pidlist_free(array);
3570 /* store array, freeing old if necessary - lock already held */
3571 pidlist_free(l->list);
3575 up_write(&l->mutex);
3581 * cgroupstats_build - build and fill cgroupstats
3582 * @stats: cgroupstats to fill information into
3583 * @dentry: A dentry entry belonging to the cgroup for which stats have
3586 * Build and fill cgroupstats so that taskstats can export it to user
3589 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3592 struct cgroup *cgrp;
3593 struct cgroup_iter it;
3594 struct task_struct *tsk;
3597 * Validate dentry by checking the superblock operations,
3598 * and make sure it's a directory.
3600 if (dentry->d_sb->s_op != &cgroup_ops ||
3601 !S_ISDIR(dentry->d_inode->i_mode))
3605 cgrp = dentry->d_fsdata;
3607 cgroup_iter_start(cgrp, &it);
3608 while ((tsk = cgroup_iter_next(cgrp, &it))) {
3609 switch (tsk->state) {
3611 stats->nr_running++;
3613 case TASK_INTERRUPTIBLE:
3614 stats->nr_sleeping++;
3616 case TASK_UNINTERRUPTIBLE:
3617 stats->nr_uninterruptible++;
3620 stats->nr_stopped++;
3623 if (delayacct_is_task_waiting_on_io(tsk))
3624 stats->nr_io_wait++;
3628 cgroup_iter_end(cgrp, &it);
3636 * seq_file methods for the tasks/procs files. The seq_file position is the
3637 * next pid to display; the seq_file iterator is a pointer to the pid
3638 * in the cgroup->l->list array.
3641 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3644 * Initially we receive a position value that corresponds to
3645 * one more than the last pid shown (or 0 on the first call or
3646 * after a seek to the start). Use a binary-search to find the
3647 * next pid to display, if any
3649 struct cgroup_pidlist *l = s->private;
3650 int index = 0, pid = *pos;
3653 down_read(&l->mutex);
3655 int end = l->length;
3657 while (index < end) {
3658 int mid = (index + end) / 2;
3659 if (l->list[mid] == pid) {
3662 } else if (l->list[mid] <= pid)
3668 /* If we're off the end of the array, we're done */
3669 if (index >= l->length)
3671 /* Update the abstract position to be the actual pid that we found */
3672 iter = l->list + index;
3677 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3679 struct cgroup_pidlist *l = s->private;
3683 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3685 struct cgroup_pidlist *l = s->private;
3687 pid_t *end = l->list + l->length;
3689 * Advance to the next pid in the array. If this goes off the
3701 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3703 return seq_printf(s, "%d\n", *(int *)v);
3707 * seq_operations functions for iterating on pidlists through seq_file -
3708 * independent of whether it's tasks or procs
3710 static const struct seq_operations cgroup_pidlist_seq_operations = {
3711 .start = cgroup_pidlist_start,
3712 .stop = cgroup_pidlist_stop,
3713 .next = cgroup_pidlist_next,
3714 .show = cgroup_pidlist_show,
3717 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
3720 * the case where we're the last user of this particular pidlist will
3721 * have us remove it from the cgroup's list, which entails taking the
3722 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3723 * pidlist_mutex, we have to take pidlist_mutex first.
3725 mutex_lock(&l->owner->pidlist_mutex);
3726 down_write(&l->mutex);
3727 BUG_ON(!l->use_count);
3728 if (!--l->use_count) {
3729 /* we're the last user if refcount is 0; remove and free */
3730 list_del(&l->links);
3731 mutex_unlock(&l->owner->pidlist_mutex);
3732 pidlist_free(l->list);
3733 put_pid_ns(l->key.ns);
3734 up_write(&l->mutex);
3738 mutex_unlock(&l->owner->pidlist_mutex);
3739 up_write(&l->mutex);
3742 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
3744 struct cgroup_pidlist *l;
3745 if (!(file->f_mode & FMODE_READ))
3748 * the seq_file will only be initialized if the file was opened for
3749 * reading; hence we check if it's not null only in that case.
3751 l = ((struct seq_file *)file->private_data)->private;
3752 cgroup_release_pid_array(l);
3753 return seq_release(inode, file);
3756 static const struct file_operations cgroup_pidlist_operations = {
3758 .llseek = seq_lseek,
3759 .write = cgroup_file_write,
3760 .release = cgroup_pidlist_release,
3764 * The following functions handle opens on a file that displays a pidlist
3765 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3768 /* helper function for the two below it */
3769 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
3771 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
3772 struct cgroup_pidlist *l;
3775 /* Nothing to do for write-only files */
3776 if (!(file->f_mode & FMODE_READ))
3779 /* have the array populated */
3780 retval = pidlist_array_load(cgrp, type, &l);
3783 /* configure file information */
3784 file->f_op = &cgroup_pidlist_operations;
3786 retval = seq_open(file, &cgroup_pidlist_seq_operations);
3788 cgroup_release_pid_array(l);
3791 ((struct seq_file *)file->private_data)->private = l;
3794 static int cgroup_tasks_open(struct inode *unused, struct file *file)
3796 return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
3798 static int cgroup_procs_open(struct inode *unused, struct file *file)
3800 return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
3803 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
3806 return notify_on_release(cgrp);
3809 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
3813 clear_bit(CGRP_RELEASABLE, &cgrp->flags);
3815 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3817 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3822 * Unregister event and free resources.
3824 * Gets called from workqueue.
3826 static void cgroup_event_remove(struct work_struct *work)
3828 struct cgroup_event *event = container_of(work, struct cgroup_event,
3830 struct cgroup *cgrp = event->cgrp;
3832 remove_wait_queue(event->wqh, &event->wait);
3834 event->cft->unregister_event(cgrp, event->cft, event->eventfd);
3836 /* Notify userspace the event is going away. */
3837 eventfd_signal(event->eventfd, 1);
3839 eventfd_ctx_put(event->eventfd);
3845 * Gets called on POLLHUP on eventfd when user closes it.
3847 * Called with wqh->lock held and interrupts disabled.
3849 static int cgroup_event_wake(wait_queue_t *wait, unsigned mode,
3850 int sync, void *key)
3852 struct cgroup_event *event = container_of(wait,
3853 struct cgroup_event, wait);
3854 struct cgroup *cgrp = event->cgrp;
3855 unsigned long flags = (unsigned long)key;
3857 if (flags & POLLHUP) {
3859 * If the event has been detached at cgroup removal, we
3860 * can simply return knowing the other side will cleanup
3863 * We can't race against event freeing since the other
3864 * side will require wqh->lock via remove_wait_queue(),
3867 spin_lock(&cgrp->event_list_lock);
3868 if (!list_empty(&event->list)) {
3869 list_del_init(&event->list);
3871 * We are in atomic context, but cgroup_event_remove()
3872 * may sleep, so we have to call it in workqueue.
3874 schedule_work(&event->remove);
3876 spin_unlock(&cgrp->event_list_lock);
3882 static void cgroup_event_ptable_queue_proc(struct file *file,
3883 wait_queue_head_t *wqh, poll_table *pt)
3885 struct cgroup_event *event = container_of(pt,
3886 struct cgroup_event, pt);
3889 add_wait_queue(wqh, &event->wait);
3893 * Parse input and register new cgroup event handler.
3895 * Input must be in format '<event_fd> <control_fd> <args>'.
3896 * Interpretation of args is defined by control file implementation.
3898 static int cgroup_write_event_control(struct cgroup *cgrp, struct cftype *cft,
3901 struct cgroup_event *event = NULL;
3902 struct cgroup *cgrp_cfile;
3903 unsigned int efd, cfd;
3904 struct file *efile = NULL;
3905 struct file *cfile = NULL;
3909 efd = simple_strtoul(buffer, &endp, 10);
3914 cfd = simple_strtoul(buffer, &endp, 10);
3915 if ((*endp != ' ') && (*endp != '\0'))
3919 event = kzalloc(sizeof(*event), GFP_KERNEL);
3923 INIT_LIST_HEAD(&event->list);
3924 init_poll_funcptr(&event->pt, cgroup_event_ptable_queue_proc);
3925 init_waitqueue_func_entry(&event->wait, cgroup_event_wake);
3926 INIT_WORK(&event->remove, cgroup_event_remove);
3928 efile = eventfd_fget(efd);
3929 if (IS_ERR(efile)) {
3930 ret = PTR_ERR(efile);
3934 event->eventfd = eventfd_ctx_fileget(efile);
3935 if (IS_ERR(event->eventfd)) {
3936 ret = PTR_ERR(event->eventfd);
3946 /* the process need read permission on control file */
3947 /* AV: shouldn't we check that it's been opened for read instead? */
3948 ret = inode_permission(file_inode(cfile), MAY_READ);
3952 event->cft = __file_cft(cfile);
3953 if (IS_ERR(event->cft)) {
3954 ret = PTR_ERR(event->cft);
3959 * The file to be monitored must be in the same cgroup as
3960 * cgroup.event_control is.
3962 cgrp_cfile = __d_cgrp(cfile->f_dentry->d_parent);
3963 if (cgrp_cfile != cgrp) {
3968 if (!event->cft->register_event || !event->cft->unregister_event) {
3973 ret = event->cft->register_event(cgrp, event->cft,
3974 event->eventfd, buffer);
3978 efile->f_op->poll(efile, &event->pt);
3981 * Events should be removed after rmdir of cgroup directory, but before
3982 * destroying subsystem state objects. Let's take reference to cgroup
3983 * directory dentry to do that.
3987 spin_lock(&cgrp->event_list_lock);
3988 list_add(&event->list, &cgrp->event_list);
3989 spin_unlock(&cgrp->event_list_lock);
4000 if (event && event->eventfd && !IS_ERR(event->eventfd))
4001 eventfd_ctx_put(event->eventfd);
4003 if (!IS_ERR_OR_NULL(efile))
4011 static u64 cgroup_clone_children_read(struct cgroup *cgrp,
4014 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4017 static int cgroup_clone_children_write(struct cgroup *cgrp,
4022 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4024 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4028 static struct cftype cgroup_base_files[] = {
4030 .name = "cgroup.procs",
4031 .open = cgroup_procs_open,
4032 .write_u64 = cgroup_procs_write,
4033 .release = cgroup_pidlist_release,
4034 .mode = S_IRUGO | S_IWUSR,
4037 .name = "cgroup.event_control",
4038 .write_string = cgroup_write_event_control,
4042 .name = "cgroup.clone_children",
4043 .flags = CFTYPE_INSANE,
4044 .read_u64 = cgroup_clone_children_read,
4045 .write_u64 = cgroup_clone_children_write,
4048 .name = "cgroup.sane_behavior",
4049 .flags = CFTYPE_ONLY_ON_ROOT,
4050 .read_seq_string = cgroup_sane_behavior_show,
4054 * Historical crazy stuff. These don't have "cgroup." prefix and
4055 * don't exist if sane_behavior. If you're depending on these, be
4056 * prepared to be burned.
4060 .flags = CFTYPE_INSANE, /* use "procs" instead */
4061 .open = cgroup_tasks_open,
4062 .write_u64 = cgroup_tasks_write,
4063 .release = cgroup_pidlist_release,
4064 .mode = S_IRUGO | S_IWUSR,
4067 .name = "notify_on_release",
4068 .flags = CFTYPE_INSANE,
4069 .read_u64 = cgroup_read_notify_on_release,
4070 .write_u64 = cgroup_write_notify_on_release,
4073 .name = "release_agent",
4074 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
4075 .read_seq_string = cgroup_release_agent_show,
4076 .write_string = cgroup_release_agent_write,
4077 .max_write_len = PATH_MAX,
4083 * cgroup_populate_dir - selectively creation of files in a directory
4084 * @cgrp: target cgroup
4085 * @base_files: true if the base files should be added
4086 * @subsys_mask: mask of the subsystem ids whose files should be added
4088 static int cgroup_populate_dir(struct cgroup *cgrp, bool base_files,
4089 unsigned long subsys_mask)
4092 struct cgroup_subsys *ss;
4095 err = cgroup_addrm_files(cgrp, NULL, cgroup_base_files, true);
4100 /* process cftsets of each subsystem */
4101 for_each_subsys(cgrp->root, ss) {
4102 struct cftype_set *set;
4103 if (!test_bit(ss->subsys_id, &subsys_mask))
4106 list_for_each_entry(set, &ss->cftsets, node)
4107 cgroup_addrm_files(cgrp, ss, set->cfts, true);
4110 /* This cgroup is ready now */
4111 for_each_subsys(cgrp->root, ss) {
4112 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4114 * Update id->css pointer and make this css visible from
4115 * CSS ID functions. This pointer will be dereferened
4116 * from RCU-read-side without locks.
4119 rcu_assign_pointer(css->id->css, css);
4125 static void css_dput_fn(struct work_struct *work)
4127 struct cgroup_subsys_state *css =
4128 container_of(work, struct cgroup_subsys_state, dput_work);
4129 struct dentry *dentry = css->cgroup->dentry;
4130 struct super_block *sb = dentry->d_sb;
4132 atomic_inc(&sb->s_active);
4134 deactivate_super(sb);
4137 static void init_cgroup_css(struct cgroup_subsys_state *css,
4138 struct cgroup_subsys *ss,
4139 struct cgroup *cgrp)
4142 atomic_set(&css->refcnt, 1);
4145 if (cgrp == dummytop)
4146 css->flags |= CSS_ROOT;
4147 BUG_ON(cgrp->subsys[ss->subsys_id]);
4148 cgrp->subsys[ss->subsys_id] = css;
4151 * css holds an extra ref to @cgrp->dentry which is put on the last
4152 * css_put(). dput() requires process context, which css_put() may
4153 * be called without. @css->dput_work will be used to invoke
4154 * dput() asynchronously from css_put().
4156 INIT_WORK(&css->dput_work, css_dput_fn);
4159 /* invoke ->post_create() on a new CSS and mark it online if successful */
4160 static int online_css(struct cgroup_subsys *ss, struct cgroup *cgrp)
4164 lockdep_assert_held(&cgroup_mutex);
4167 ret = ss->css_online(cgrp);
4169 cgrp->subsys[ss->subsys_id]->flags |= CSS_ONLINE;
4173 /* if the CSS is online, invoke ->pre_destory() on it and mark it offline */
4174 static void offline_css(struct cgroup_subsys *ss, struct cgroup *cgrp)
4175 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4177 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4179 lockdep_assert_held(&cgroup_mutex);
4181 if (!(css->flags & CSS_ONLINE))
4184 if (ss->css_offline)
4185 ss->css_offline(cgrp);
4187 cgrp->subsys[ss->subsys_id]->flags &= ~CSS_ONLINE;
4191 * cgroup_create - create a cgroup
4192 * @parent: cgroup that will be parent of the new cgroup
4193 * @dentry: dentry of the new cgroup
4194 * @mode: mode to set on new inode
4196 * Must be called with the mutex on the parent inode held
4198 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4201 static atomic64_t serial_nr_cursor = ATOMIC64_INIT(0);
4202 struct cgroup *cgrp;
4203 struct cgroup_name *name;
4204 struct cgroupfs_root *root = parent->root;
4206 struct cgroup_subsys *ss;
4207 struct super_block *sb = root->sb;
4209 /* allocate the cgroup and its ID, 0 is reserved for the root */
4210 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4214 name = cgroup_alloc_name(dentry);
4217 rcu_assign_pointer(cgrp->name, name);
4219 cgrp->id = ida_simple_get(&root->cgroup_ida, 1, 0, GFP_KERNEL);
4224 * Only live parents can have children. Note that the liveliness
4225 * check isn't strictly necessary because cgroup_mkdir() and
4226 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4227 * anyway so that locking is contained inside cgroup proper and we
4228 * don't get nasty surprises if we ever grow another caller.
4230 if (!cgroup_lock_live_group(parent)) {
4235 /* Grab a reference on the superblock so the hierarchy doesn't
4236 * get deleted on unmount if there are child cgroups. This
4237 * can be done outside cgroup_mutex, since the sb can't
4238 * disappear while someone has an open control file on the
4240 atomic_inc(&sb->s_active);
4242 init_cgroup_housekeeping(cgrp);
4244 dentry->d_fsdata = cgrp;
4245 cgrp->dentry = dentry;
4247 cgrp->parent = parent;
4248 cgrp->root = parent->root;
4250 if (notify_on_release(parent))
4251 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4253 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4254 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4256 for_each_subsys(root, ss) {
4257 struct cgroup_subsys_state *css;
4259 css = ss->css_alloc(cgrp);
4264 init_cgroup_css(css, ss, cgrp);
4266 err = alloc_css_id(ss, parent, cgrp);
4273 * Create directory. cgroup_create_file() returns with the new
4274 * directory locked on success so that it can be populated without
4275 * dropping cgroup_mutex.
4277 err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4280 lockdep_assert_held(&dentry->d_inode->i_mutex);
4283 * Assign a monotonically increasing serial number. With the list
4284 * appending below, it guarantees that sibling cgroups are always
4285 * sorted in the ascending serial number order on the parent's
4288 cgrp->serial_nr = atomic64_inc_return(&serial_nr_cursor);
4290 /* allocation complete, commit to creation */
4291 list_add_tail(&cgrp->allcg_node, &root->allcg_list);
4292 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4293 root->number_of_cgroups++;
4295 /* each css holds a ref to the cgroup's dentry */
4296 for_each_subsys(root, ss)
4299 /* hold a ref to the parent's dentry */
4300 dget(parent->dentry);
4302 /* creation succeeded, notify subsystems */
4303 for_each_subsys(root, ss) {
4304 err = online_css(ss, cgrp);
4308 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4310 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",
4311 current->comm, current->pid, ss->name);
4312 if (!strcmp(ss->name, "memory"))
4313 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4314 ss->warned_broken_hierarchy = true;
4318 err = cgroup_populate_dir(cgrp, true, root->subsys_mask);
4322 mutex_unlock(&cgroup_mutex);
4323 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4328 for_each_subsys(root, ss) {
4329 if (cgrp->subsys[ss->subsys_id])
4332 mutex_unlock(&cgroup_mutex);
4333 /* Release the reference count that we took on the superblock */
4334 deactivate_super(sb);
4336 ida_simple_remove(&root->cgroup_ida, cgrp->id);
4338 kfree(rcu_dereference_raw(cgrp->name));
4344 cgroup_destroy_locked(cgrp);
4345 mutex_unlock(&cgroup_mutex);
4346 mutex_unlock(&dentry->d_inode->i_mutex);
4350 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4352 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4354 /* the vfs holds inode->i_mutex already */
4355 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4358 static int cgroup_destroy_locked(struct cgroup *cgrp)
4359 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4361 struct dentry *d = cgrp->dentry;
4362 struct cgroup *parent = cgrp->parent;
4363 struct cgroup_event *event, *tmp;
4364 struct cgroup_subsys *ss;
4367 lockdep_assert_held(&d->d_inode->i_mutex);
4368 lockdep_assert_held(&cgroup_mutex);
4371 * css_set_lock synchronizes access to ->cset_links and prevents
4372 * @cgrp from being removed while __put_css_set() is in progress.
4374 read_lock(&css_set_lock);
4375 empty = list_empty(&cgrp->cset_links) && list_empty(&cgrp->children);
4376 read_unlock(&css_set_lock);
4381 * Block new css_tryget() by deactivating refcnt and mark @cgrp
4382 * removed. This makes future css_tryget() attempts fail which we
4383 * guarantee to ->css_offline() callbacks.
4385 for_each_subsys(cgrp->root, ss) {
4386 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4388 WARN_ON(atomic_read(&css->refcnt) < 0);
4389 atomic_add(CSS_DEACT_BIAS, &css->refcnt);
4393 * Mark @cgrp dead. This prevents further task migration and child
4394 * creation by disabling cgroup_lock_live_group(). Note that
4395 * CGRP_DEAD assertion is depended upon by cgroup_next_sibling() to
4396 * resume iteration after dropping RCU read lock. See
4397 * cgroup_next_sibling() for details.
4399 set_bit(CGRP_DEAD, &cgrp->flags);
4401 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4402 raw_spin_lock(&release_list_lock);
4403 if (!list_empty(&cgrp->release_list))
4404 list_del_init(&cgrp->release_list);
4405 raw_spin_unlock(&release_list_lock);
4408 * Remove @cgrp directory. The removal puts the base ref but we
4409 * aren't quite done with @cgrp yet, so hold onto it.
4412 cgroup_d_remove_dir(d);
4415 * Unregister events and notify userspace.
4416 * Notify userspace about cgroup removing only after rmdir of cgroup
4417 * directory to avoid race between userspace and kernelspace.
4419 spin_lock(&cgrp->event_list_lock);
4420 list_for_each_entry_safe(event, tmp, &cgrp->event_list, list) {
4421 list_del_init(&event->list);
4422 schedule_work(&event->remove);
4424 spin_unlock(&cgrp->event_list_lock);
4426 /* tell subsystems to initate destruction */
4427 for_each_subsys(cgrp->root, ss)
4428 offline_css(ss, cgrp);
4431 * Put all the base refs. Each css holds an extra reference to the
4432 * cgroup's dentry and cgroup removal proceeds regardless of css
4433 * refs. On the last put of each css, whenever that may be, the
4434 * extra dentry ref is put so that dentry destruction happens only
4435 * after all css's are released.
4437 for_each_subsys(cgrp->root, ss)
4438 css_put(cgrp->subsys[ss->subsys_id]);
4440 /* delete this cgroup from parent->children */
4441 list_del_rcu(&cgrp->sibling);
4442 list_del_init(&cgrp->allcg_node);
4446 set_bit(CGRP_RELEASABLE, &parent->flags);
4447 check_for_release(parent);
4452 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4456 mutex_lock(&cgroup_mutex);
4457 ret = cgroup_destroy_locked(dentry->d_fsdata);
4458 mutex_unlock(&cgroup_mutex);
4463 static void __init_or_module cgroup_init_cftsets(struct cgroup_subsys *ss)
4465 INIT_LIST_HEAD(&ss->cftsets);
4468 * base_cftset is embedded in subsys itself, no need to worry about
4471 if (ss->base_cftypes) {
4472 ss->base_cftset.cfts = ss->base_cftypes;
4473 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4477 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4479 struct cgroup_subsys_state *css;
4481 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4483 mutex_lock(&cgroup_mutex);
4485 /* init base cftset */
4486 cgroup_init_cftsets(ss);
4488 /* Create the top cgroup state for this subsystem */
4489 list_add(&ss->sibling, &rootnode.subsys_list);
4490 ss->root = &rootnode;
4491 css = ss->css_alloc(dummytop);
4492 /* We don't handle early failures gracefully */
4493 BUG_ON(IS_ERR(css));
4494 init_cgroup_css(css, ss, dummytop);
4496 /* Update the init_css_set to contain a subsys
4497 * pointer to this state - since the subsystem is
4498 * newly registered, all tasks and hence the
4499 * init_css_set is in the subsystem's top cgroup. */
4500 init_css_set.subsys[ss->subsys_id] = css;
4502 need_forkexit_callback |= ss->fork || ss->exit;
4504 /* At system boot, before all subsystems have been
4505 * registered, no tasks have been forked, so we don't
4506 * need to invoke fork callbacks here. */
4507 BUG_ON(!list_empty(&init_task.tasks));
4509 BUG_ON(online_css(ss, dummytop));
4511 mutex_unlock(&cgroup_mutex);
4513 /* this function shouldn't be used with modular subsystems, since they
4514 * need to register a subsys_id, among other things */
4519 * cgroup_load_subsys: load and register a modular subsystem at runtime
4520 * @ss: the subsystem to load
4522 * This function should be called in a modular subsystem's initcall. If the
4523 * subsystem is built as a module, it will be assigned a new subsys_id and set
4524 * up for use. If the subsystem is built-in anyway, work is delegated to the
4525 * simpler cgroup_init_subsys.
4527 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
4529 struct cgroup_subsys_state *css;
4531 struct hlist_node *tmp;
4532 struct css_set *cset;
4535 /* check name and function validity */
4536 if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
4537 ss->css_alloc == NULL || ss->css_free == NULL)
4541 * we don't support callbacks in modular subsystems. this check is
4542 * before the ss->module check for consistency; a subsystem that could
4543 * be a module should still have no callbacks even if the user isn't
4544 * compiling it as one.
4546 if (ss->fork || ss->exit)
4550 * an optionally modular subsystem is built-in: we want to do nothing,
4551 * since cgroup_init_subsys will have already taken care of it.
4553 if (ss->module == NULL) {
4554 /* a sanity check */
4555 BUG_ON(subsys[ss->subsys_id] != ss);
4559 /* init base cftset */
4560 cgroup_init_cftsets(ss);
4562 mutex_lock(&cgroup_mutex);
4563 subsys[ss->subsys_id] = ss;
4566 * no ss->css_alloc seems to need anything important in the ss
4567 * struct, so this can happen first (i.e. before the rootnode
4570 css = ss->css_alloc(dummytop);
4572 /* failure case - need to deassign the subsys[] slot. */
4573 subsys[ss->subsys_id] = NULL;
4574 mutex_unlock(&cgroup_mutex);
4575 return PTR_ERR(css);
4578 list_add(&ss->sibling, &rootnode.subsys_list);
4579 ss->root = &rootnode;
4581 /* our new subsystem will be attached to the dummy hierarchy. */
4582 init_cgroup_css(css, ss, dummytop);
4583 /* init_idr must be after init_cgroup_css because it sets css->id. */
4585 ret = cgroup_init_idr(ss, css);
4591 * Now we need to entangle the css into the existing css_sets. unlike
4592 * in cgroup_init_subsys, there are now multiple css_sets, so each one
4593 * will need a new pointer to it; done by iterating the css_set_table.
4594 * furthermore, modifying the existing css_sets will corrupt the hash
4595 * table state, so each changed css_set will need its hash recomputed.
4596 * this is all done under the css_set_lock.
4598 write_lock(&css_set_lock);
4599 hash_for_each_safe(css_set_table, i, tmp, cset, hlist) {
4600 /* skip entries that we already rehashed */
4601 if (cset->subsys[ss->subsys_id])
4603 /* remove existing entry */
4604 hash_del(&cset->hlist);
4606 cset->subsys[ss->subsys_id] = css;
4607 /* recompute hash and restore entry */
4608 key = css_set_hash(cset->subsys);
4609 hash_add(css_set_table, &cset->hlist, key);
4611 write_unlock(&css_set_lock);
4613 ret = online_css(ss, dummytop);
4618 mutex_unlock(&cgroup_mutex);
4622 mutex_unlock(&cgroup_mutex);
4623 /* @ss can't be mounted here as try_module_get() would fail */
4624 cgroup_unload_subsys(ss);
4627 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
4630 * cgroup_unload_subsys: unload a modular subsystem
4631 * @ss: the subsystem to unload
4633 * This function should be called in a modular subsystem's exitcall. When this
4634 * function is invoked, the refcount on the subsystem's module will be 0, so
4635 * the subsystem will not be attached to any hierarchy.
4637 void cgroup_unload_subsys(struct cgroup_subsys *ss)
4639 struct cgrp_cset_link *link;
4641 BUG_ON(ss->module == NULL);
4644 * we shouldn't be called if the subsystem is in use, and the use of
4645 * try_module_get in parse_cgroupfs_options should ensure that it
4646 * doesn't start being used while we're killing it off.
4648 BUG_ON(ss->root != &rootnode);
4650 mutex_lock(&cgroup_mutex);
4652 offline_css(ss, dummytop);
4655 idr_destroy(&ss->idr);
4657 /* deassign the subsys_id */
4658 subsys[ss->subsys_id] = NULL;
4660 /* remove subsystem from rootnode's list of subsystems */
4661 list_del_init(&ss->sibling);
4664 * disentangle the css from all css_sets attached to the dummytop. as
4665 * in loading, we need to pay our respects to the hashtable gods.
4667 write_lock(&css_set_lock);
4668 list_for_each_entry(link, &dummytop->cset_links, cset_link) {
4669 struct css_set *cset = link->cset;
4672 hash_del(&cset->hlist);
4673 cset->subsys[ss->subsys_id] = NULL;
4674 key = css_set_hash(cset->subsys);
4675 hash_add(css_set_table, &cset->hlist, key);
4677 write_unlock(&css_set_lock);
4680 * remove subsystem's css from the dummytop and free it - need to
4681 * free before marking as null because ss->css_free needs the
4682 * cgrp->subsys pointer to find their state. note that this also
4683 * takes care of freeing the css_id.
4685 ss->css_free(dummytop);
4686 dummytop->subsys[ss->subsys_id] = NULL;
4688 mutex_unlock(&cgroup_mutex);
4690 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
4693 * cgroup_init_early - cgroup initialization at system boot
4695 * Initialize cgroups at system boot, and initialize any
4696 * subsystems that request early init.
4698 int __init cgroup_init_early(void)
4701 atomic_set(&init_css_set.refcount, 1);
4702 INIT_LIST_HEAD(&init_css_set.cgrp_links);
4703 INIT_LIST_HEAD(&init_css_set.tasks);
4704 INIT_HLIST_NODE(&init_css_set.hlist);
4706 init_cgroup_root(&rootnode);
4708 init_task.cgroups = &init_css_set;
4710 init_cgrp_cset_link.cset = &init_css_set;
4711 init_cgrp_cset_link.cgrp = dummytop;
4712 list_add(&init_cgrp_cset_link.cset_link, &rootnode.top_cgroup.cset_links);
4713 list_add(&init_cgrp_cset_link.cgrp_link, &init_css_set.cgrp_links);
4715 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4716 struct cgroup_subsys *ss = subsys[i];
4718 /* at bootup time, we don't worry about modular subsystems */
4719 if (!ss || ss->module)
4723 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
4724 BUG_ON(!ss->css_alloc);
4725 BUG_ON(!ss->css_free);
4726 if (ss->subsys_id != i) {
4727 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
4728 ss->name, ss->subsys_id);
4733 cgroup_init_subsys(ss);
4739 * cgroup_init - cgroup initialization
4741 * Register cgroup filesystem and /proc file, and initialize
4742 * any subsystems that didn't request early init.
4744 int __init cgroup_init(void)
4750 err = bdi_init(&cgroup_backing_dev_info);
4754 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4755 struct cgroup_subsys *ss = subsys[i];
4757 /* at bootup time, we don't worry about modular subsystems */
4758 if (!ss || ss->module)
4760 if (!ss->early_init)
4761 cgroup_init_subsys(ss);
4763 cgroup_init_idr(ss, init_css_set.subsys[ss->subsys_id]);
4766 /* Add init_css_set to the hash table */
4767 key = css_set_hash(init_css_set.subsys);
4768 hash_add(css_set_table, &init_css_set.hlist, key);
4770 /* allocate id for the dummy hierarchy */
4771 mutex_lock(&cgroup_mutex);
4772 mutex_lock(&cgroup_root_mutex);
4774 BUG_ON(cgroup_init_root_id(&rootnode));
4776 mutex_unlock(&cgroup_root_mutex);
4777 mutex_unlock(&cgroup_mutex);
4779 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4785 err = register_filesystem(&cgroup_fs_type);
4787 kobject_put(cgroup_kobj);
4791 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4795 bdi_destroy(&cgroup_backing_dev_info);
4801 * proc_cgroup_show()
4802 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4803 * - Used for /proc/<pid>/cgroup.
4804 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4805 * doesn't really matter if tsk->cgroup changes after we read it,
4806 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4807 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4808 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4809 * cgroup to top_cgroup.
4812 /* TODO: Use a proper seq_file iterator */
4813 int proc_cgroup_show(struct seq_file *m, void *v)
4816 struct task_struct *tsk;
4819 struct cgroupfs_root *root;
4822 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4828 tsk = get_pid_task(pid, PIDTYPE_PID);
4834 mutex_lock(&cgroup_mutex);
4836 for_each_active_root(root) {
4837 struct cgroup_subsys *ss;
4838 struct cgroup *cgrp;
4841 seq_printf(m, "%d:", root->hierarchy_id);
4842 for_each_subsys(root, ss)
4843 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4844 if (strlen(root->name))
4845 seq_printf(m, "%sname=%s", count ? "," : "",
4848 cgrp = task_cgroup_from_root(tsk, root);
4849 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
4857 mutex_unlock(&cgroup_mutex);
4858 put_task_struct(tsk);
4865 /* Display information about each subsystem and each hierarchy */
4866 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4870 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4872 * ideally we don't want subsystems moving around while we do this.
4873 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4874 * subsys/hierarchy state.
4876 mutex_lock(&cgroup_mutex);
4877 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4878 struct cgroup_subsys *ss = subsys[i];
4881 seq_printf(m, "%s\t%d\t%d\t%d\n",
4882 ss->name, ss->root->hierarchy_id,
4883 ss->root->number_of_cgroups, !ss->disabled);
4885 mutex_unlock(&cgroup_mutex);
4889 static int cgroupstats_open(struct inode *inode, struct file *file)
4891 return single_open(file, proc_cgroupstats_show, NULL);
4894 static const struct file_operations proc_cgroupstats_operations = {
4895 .open = cgroupstats_open,
4897 .llseek = seq_lseek,
4898 .release = single_release,
4902 * cgroup_fork - attach newly forked task to its parents cgroup.
4903 * @child: pointer to task_struct of forking parent process.
4905 * Description: A task inherits its parent's cgroup at fork().
4907 * A pointer to the shared css_set was automatically copied in
4908 * fork.c by dup_task_struct(). However, we ignore that copy, since
4909 * it was not made under the protection of RCU or cgroup_mutex, so
4910 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
4911 * have already changed current->cgroups, allowing the previously
4912 * referenced cgroup group to be removed and freed.
4914 * At the point that cgroup_fork() is called, 'current' is the parent
4915 * task, and the passed argument 'child' points to the child task.
4917 void cgroup_fork(struct task_struct *child)
4920 child->cgroups = current->cgroups;
4921 get_css_set(child->cgroups);
4922 task_unlock(current);
4923 INIT_LIST_HEAD(&child->cg_list);
4927 * cgroup_post_fork - called on a new task after adding it to the task list
4928 * @child: the task in question
4930 * Adds the task to the list running through its css_set if necessary and
4931 * call the subsystem fork() callbacks. Has to be after the task is
4932 * visible on the task list in case we race with the first call to
4933 * cgroup_iter_start() - to guarantee that the new task ends up on its
4936 void cgroup_post_fork(struct task_struct *child)
4941 * use_task_css_set_links is set to 1 before we walk the tasklist
4942 * under the tasklist_lock and we read it here after we added the child
4943 * to the tasklist under the tasklist_lock as well. If the child wasn't
4944 * yet in the tasklist when we walked through it from
4945 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4946 * should be visible now due to the paired locking and barriers implied
4947 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4948 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4951 if (use_task_css_set_links) {
4952 write_lock(&css_set_lock);
4954 if (list_empty(&child->cg_list))
4955 list_add(&child->cg_list, &child->cgroups->tasks);
4957 write_unlock(&css_set_lock);
4961 * Call ss->fork(). This must happen after @child is linked on
4962 * css_set; otherwise, @child might change state between ->fork()
4963 * and addition to css_set.
4965 if (need_forkexit_callback) {
4967 * fork/exit callbacks are supported only for builtin
4968 * subsystems, and the builtin section of the subsys
4969 * array is immutable, so we don't need to lock the
4970 * subsys array here. On the other hand, modular section
4971 * of the array can be freed at module unload, so we
4974 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
4975 struct cgroup_subsys *ss = subsys[i];
4984 * cgroup_exit - detach cgroup from exiting task
4985 * @tsk: pointer to task_struct of exiting process
4986 * @run_callback: run exit callbacks?
4988 * Description: Detach cgroup from @tsk and release it.
4990 * Note that cgroups marked notify_on_release force every task in
4991 * them to take the global cgroup_mutex mutex when exiting.
4992 * This could impact scaling on very large systems. Be reluctant to
4993 * use notify_on_release cgroups where very high task exit scaling
4994 * is required on large systems.
4996 * the_top_cgroup_hack:
4998 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
5000 * We call cgroup_exit() while the task is still competent to
5001 * handle notify_on_release(), then leave the task attached to the
5002 * root cgroup in each hierarchy for the remainder of its exit.
5004 * To do this properly, we would increment the reference count on
5005 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
5006 * code we would add a second cgroup function call, to drop that
5007 * reference. This would just create an unnecessary hot spot on
5008 * the top_cgroup reference count, to no avail.
5010 * Normally, holding a reference to a cgroup without bumping its
5011 * count is unsafe. The cgroup could go away, or someone could
5012 * attach us to a different cgroup, decrementing the count on
5013 * the first cgroup that we never incremented. But in this case,
5014 * top_cgroup isn't going away, and either task has PF_EXITING set,
5015 * which wards off any cgroup_attach_task() attempts, or task is a failed
5016 * fork, never visible to cgroup_attach_task.
5018 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
5020 struct css_set *cset;
5024 * Unlink from the css_set task list if necessary.
5025 * Optimistically check cg_list before taking
5028 if (!list_empty(&tsk->cg_list)) {
5029 write_lock(&css_set_lock);
5030 if (!list_empty(&tsk->cg_list))
5031 list_del_init(&tsk->cg_list);
5032 write_unlock(&css_set_lock);
5035 /* Reassign the task to the init_css_set. */
5037 cset = tsk->cgroups;
5038 tsk->cgroups = &init_css_set;
5040 if (run_callbacks && need_forkexit_callback) {
5042 * fork/exit callbacks are supported only for builtin
5043 * subsystems, see cgroup_post_fork() for details.
5045 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
5046 struct cgroup_subsys *ss = subsys[i];
5049 struct cgroup *old_cgrp =
5050 rcu_dereference_raw(cset->subsys[i])->cgroup;
5051 struct cgroup *cgrp = task_cgroup(tsk, i);
5052 ss->exit(cgrp, old_cgrp, tsk);
5058 put_css_set_taskexit(cset);
5061 static void check_for_release(struct cgroup *cgrp)
5063 if (cgroup_is_releasable(cgrp) &&
5064 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
5066 * Control Group is currently removeable. If it's not
5067 * already queued for a userspace notification, queue
5070 int need_schedule_work = 0;
5072 raw_spin_lock(&release_list_lock);
5073 if (!cgroup_is_dead(cgrp) &&
5074 list_empty(&cgrp->release_list)) {
5075 list_add(&cgrp->release_list, &release_list);
5076 need_schedule_work = 1;
5078 raw_spin_unlock(&release_list_lock);
5079 if (need_schedule_work)
5080 schedule_work(&release_agent_work);
5084 /* Caller must verify that the css is not for root cgroup */
5085 bool __css_tryget(struct cgroup_subsys_state *css)
5090 v = css_refcnt(css);
5091 t = atomic_cmpxchg(&css->refcnt, v, v + 1);
5099 EXPORT_SYMBOL_GPL(__css_tryget);
5101 /* Caller must verify that the css is not for root cgroup */
5102 void __css_put(struct cgroup_subsys_state *css)
5106 v = css_unbias_refcnt(atomic_dec_return(&css->refcnt));
5108 schedule_work(&css->dput_work);
5110 EXPORT_SYMBOL_GPL(__css_put);
5113 * Notify userspace when a cgroup is released, by running the
5114 * configured release agent with the name of the cgroup (path
5115 * relative to the root of cgroup file system) as the argument.
5117 * Most likely, this user command will try to rmdir this cgroup.
5119 * This races with the possibility that some other task will be
5120 * attached to this cgroup before it is removed, or that some other
5121 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5122 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5123 * unused, and this cgroup will be reprieved from its death sentence,
5124 * to continue to serve a useful existence. Next time it's released,
5125 * we will get notified again, if it still has 'notify_on_release' set.
5127 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5128 * means only wait until the task is successfully execve()'d. The
5129 * separate release agent task is forked by call_usermodehelper(),
5130 * then control in this thread returns here, without waiting for the
5131 * release agent task. We don't bother to wait because the caller of
5132 * this routine has no use for the exit status of the release agent
5133 * task, so no sense holding our caller up for that.
5135 static void cgroup_release_agent(struct work_struct *work)
5137 BUG_ON(work != &release_agent_work);
5138 mutex_lock(&cgroup_mutex);
5139 raw_spin_lock(&release_list_lock);
5140 while (!list_empty(&release_list)) {
5141 char *argv[3], *envp[3];
5143 char *pathbuf = NULL, *agentbuf = NULL;
5144 struct cgroup *cgrp = list_entry(release_list.next,
5147 list_del_init(&cgrp->release_list);
5148 raw_spin_unlock(&release_list_lock);
5149 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5152 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
5154 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5159 argv[i++] = agentbuf;
5160 argv[i++] = pathbuf;
5164 /* minimal command environment */
5165 envp[i++] = "HOME=/";
5166 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5169 /* Drop the lock while we invoke the usermode helper,
5170 * since the exec could involve hitting disk and hence
5171 * be a slow process */
5172 mutex_unlock(&cgroup_mutex);
5173 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5174 mutex_lock(&cgroup_mutex);
5178 raw_spin_lock(&release_list_lock);
5180 raw_spin_unlock(&release_list_lock);
5181 mutex_unlock(&cgroup_mutex);
5184 static int __init cgroup_disable(char *str)
5189 while ((token = strsep(&str, ",")) != NULL) {
5192 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
5193 struct cgroup_subsys *ss = subsys[i];
5196 * cgroup_disable, being at boot time, can't
5197 * know about module subsystems, so we don't
5200 if (!ss || ss->module)
5203 if (!strcmp(token, ss->name)) {
5205 printk(KERN_INFO "Disabling %s control group"
5206 " subsystem\n", ss->name);
5213 __setup("cgroup_disable=", cgroup_disable);
5216 * Functons for CSS ID.
5219 /* to get ID other than 0, this should be called when !cgroup_is_dead() */
5220 unsigned short css_id(struct cgroup_subsys_state *css)
5222 struct css_id *cssid;
5225 * This css_id() can return correct value when somone has refcnt
5226 * on this or this is under rcu_read_lock(). Once css->id is allocated,
5227 * it's unchanged until freed.
5229 cssid = rcu_dereference_check(css->id, css_refcnt(css));
5235 EXPORT_SYMBOL_GPL(css_id);
5238 * css_is_ancestor - test "root" css is an ancestor of "child"
5239 * @child: the css to be tested.
5240 * @root: the css supporsed to be an ancestor of the child.
5242 * Returns true if "root" is an ancestor of "child" in its hierarchy. Because
5243 * this function reads css->id, the caller must hold rcu_read_lock().
5244 * But, considering usual usage, the csses should be valid objects after test.
5245 * Assuming that the caller will do some action to the child if this returns
5246 * returns true, the caller must take "child";s reference count.
5247 * If "child" is valid object and this returns true, "root" is valid, too.
5250 bool css_is_ancestor(struct cgroup_subsys_state *child,
5251 const struct cgroup_subsys_state *root)
5253 struct css_id *child_id;
5254 struct css_id *root_id;
5256 child_id = rcu_dereference(child->id);
5259 root_id = rcu_dereference(root->id);
5262 if (child_id->depth < root_id->depth)
5264 if (child_id->stack[root_id->depth] != root_id->id)
5269 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
5271 struct css_id *id = css->id;
5272 /* When this is called before css_id initialization, id can be NULL */
5276 BUG_ON(!ss->use_id);
5278 rcu_assign_pointer(id->css, NULL);
5279 rcu_assign_pointer(css->id, NULL);
5280 spin_lock(&ss->id_lock);
5281 idr_remove(&ss->idr, id->id);
5282 spin_unlock(&ss->id_lock);
5283 kfree_rcu(id, rcu_head);
5285 EXPORT_SYMBOL_GPL(free_css_id);
5288 * This is called by init or create(). Then, calls to this function are
5289 * always serialized (By cgroup_mutex() at create()).
5292 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
5294 struct css_id *newid;
5297 BUG_ON(!ss->use_id);
5299 size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
5300 newid = kzalloc(size, GFP_KERNEL);
5302 return ERR_PTR(-ENOMEM);
5304 idr_preload(GFP_KERNEL);
5305 spin_lock(&ss->id_lock);
5306 /* Don't use 0. allocates an ID of 1-65535 */
5307 ret = idr_alloc(&ss->idr, newid, 1, CSS_ID_MAX + 1, GFP_NOWAIT);
5308 spin_unlock(&ss->id_lock);
5311 /* Returns error when there are no free spaces for new ID.*/
5316 newid->depth = depth;
5320 return ERR_PTR(ret);
5324 static int __init_or_module cgroup_init_idr(struct cgroup_subsys *ss,
5325 struct cgroup_subsys_state *rootcss)
5327 struct css_id *newid;
5329 spin_lock_init(&ss->id_lock);
5332 newid = get_new_cssid(ss, 0);
5334 return PTR_ERR(newid);
5336 newid->stack[0] = newid->id;
5337 newid->css = rootcss;
5338 rootcss->id = newid;
5342 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
5343 struct cgroup *child)
5345 int subsys_id, i, depth = 0;
5346 struct cgroup_subsys_state *parent_css, *child_css;
5347 struct css_id *child_id, *parent_id;
5349 subsys_id = ss->subsys_id;
5350 parent_css = parent->subsys[subsys_id];
5351 child_css = child->subsys[subsys_id];
5352 parent_id = parent_css->id;
5353 depth = parent_id->depth + 1;
5355 child_id = get_new_cssid(ss, depth);
5356 if (IS_ERR(child_id))
5357 return PTR_ERR(child_id);
5359 for (i = 0; i < depth; i++)
5360 child_id->stack[i] = parent_id->stack[i];
5361 child_id->stack[depth] = child_id->id;
5363 * child_id->css pointer will be set after this cgroup is available
5364 * see cgroup_populate_dir()
5366 rcu_assign_pointer(child_css->id, child_id);
5372 * css_lookup - lookup css by id
5373 * @ss: cgroup subsys to be looked into.
5376 * Returns pointer to cgroup_subsys_state if there is valid one with id.
5377 * NULL if not. Should be called under rcu_read_lock()
5379 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
5381 struct css_id *cssid = NULL;
5383 BUG_ON(!ss->use_id);
5384 cssid = idr_find(&ss->idr, id);
5386 if (unlikely(!cssid))
5389 return rcu_dereference(cssid->css);
5391 EXPORT_SYMBOL_GPL(css_lookup);
5394 * get corresponding css from file open on cgroupfs directory
5396 struct cgroup_subsys_state *cgroup_css_from_dir(struct file *f, int id)
5398 struct cgroup *cgrp;
5399 struct inode *inode;
5400 struct cgroup_subsys_state *css;
5402 inode = file_inode(f);
5403 /* check in cgroup filesystem dir */
5404 if (inode->i_op != &cgroup_dir_inode_operations)
5405 return ERR_PTR(-EBADF);
5407 if (id < 0 || id >= CGROUP_SUBSYS_COUNT)
5408 return ERR_PTR(-EINVAL);
5411 cgrp = __d_cgrp(f->f_dentry);
5412 css = cgrp->subsys[id];
5413 return css ? css : ERR_PTR(-ENOENT);
5416 #ifdef CONFIG_CGROUP_DEBUG
5417 static struct cgroup_subsys_state *debug_css_alloc(struct cgroup *cont)
5419 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5422 return ERR_PTR(-ENOMEM);
5427 static void debug_css_free(struct cgroup *cont)
5429 kfree(cont->subsys[debug_subsys_id]);
5432 static u64 debug_taskcount_read(struct cgroup *cont, struct cftype *cft)
5434 return cgroup_task_count(cont);
5437 static u64 current_css_set_read(struct cgroup *cont, struct cftype *cft)
5439 return (u64)(unsigned long)current->cgroups;
5442 static u64 current_css_set_refcount_read(struct cgroup *cont,
5448 count = atomic_read(¤t->cgroups->refcount);
5453 static int current_css_set_cg_links_read(struct cgroup *cont,
5455 struct seq_file *seq)
5457 struct cgrp_cset_link *link;
5458 struct css_set *cset;
5460 read_lock(&css_set_lock);
5462 cset = rcu_dereference(current->cgroups);
5463 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5464 struct cgroup *c = link->cgrp;
5468 name = c->dentry->d_name.name;
5471 seq_printf(seq, "Root %d group %s\n",
5472 c->root->hierarchy_id, name);
5475 read_unlock(&css_set_lock);
5479 #define MAX_TASKS_SHOWN_PER_CSS 25
5480 static int cgroup_css_links_read(struct cgroup *cont,
5482 struct seq_file *seq)
5484 struct cgrp_cset_link *link;
5486 read_lock(&css_set_lock);
5487 list_for_each_entry(link, &cont->cset_links, cset_link) {
5488 struct css_set *cset = link->cset;
5489 struct task_struct *task;
5491 seq_printf(seq, "css_set %p\n", cset);
5492 list_for_each_entry(task, &cset->tasks, cg_list) {
5493 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5494 seq_puts(seq, " ...\n");
5497 seq_printf(seq, " task %d\n",
5498 task_pid_vnr(task));
5502 read_unlock(&css_set_lock);
5506 static u64 releasable_read(struct cgroup *cgrp, struct cftype *cft)
5508 return test_bit(CGRP_RELEASABLE, &cgrp->flags);
5511 static struct cftype debug_files[] = {
5513 .name = "taskcount",
5514 .read_u64 = debug_taskcount_read,
5518 .name = "current_css_set",
5519 .read_u64 = current_css_set_read,
5523 .name = "current_css_set_refcount",
5524 .read_u64 = current_css_set_refcount_read,
5528 .name = "current_css_set_cg_links",
5529 .read_seq_string = current_css_set_cg_links_read,
5533 .name = "cgroup_css_links",
5534 .read_seq_string = cgroup_css_links_read,
5538 .name = "releasable",
5539 .read_u64 = releasable_read,
5545 struct cgroup_subsys debug_subsys = {
5547 .css_alloc = debug_css_alloc,
5548 .css_free = debug_css_free,
5549 .subsys_id = debug_subsys_id,
5550 .base_cftypes = debug_files,
5552 #endif /* CONFIG_CGROUP_DEBUG */