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>
67 * cgroup_mutex is the master lock. Any modification to cgroup or its
68 * hierarchy must be performed while holding it.
70 * cgroup_root_mutex nests inside cgroup_mutex and should be held to modify
71 * cgroupfs_root of any cgroup hierarchy - subsys list, flags,
72 * release_agent_path and so on. Modifying requires both cgroup_mutex and
73 * cgroup_root_mutex. Readers can acquire either of the two. This is to
74 * break the following locking order cycle.
76 * A. cgroup_mutex -> cred_guard_mutex -> s_type->i_mutex_key -> namespace_sem
77 * B. namespace_sem -> cgroup_mutex
79 * B happens only through cgroup_show_options() and using cgroup_root_mutex
82 #ifdef CONFIG_PROVE_RCU
83 DEFINE_MUTEX(cgroup_mutex);
84 EXPORT_SYMBOL_GPL(cgroup_mutex); /* only for lockdep */
86 static DEFINE_MUTEX(cgroup_mutex);
89 static DEFINE_MUTEX(cgroup_root_mutex);
92 * Generate an array of cgroup subsystem pointers. At boot time, this is
93 * populated with the built in subsystems, and modular subsystems are
94 * registered after that. The mutable section of this array is protected by
97 #define SUBSYS(_x) [_x ## _subsys_id] = &_x ## _subsys,
98 #define IS_SUBSYS_ENABLED(option) IS_BUILTIN(option)
99 static struct cgroup_subsys *cgroup_subsys[CGROUP_SUBSYS_COUNT] = {
100 #include <linux/cgroup_subsys.h>
104 * The dummy hierarchy, reserved for the subsystems that are otherwise
105 * unattached - it never has more than a single cgroup, and all tasks are
106 * part of that cgroup.
108 static struct cgroupfs_root cgroup_dummy_root;
110 /* dummy_top is a shorthand for the dummy hierarchy's top cgroup */
111 static struct cgroup * const cgroup_dummy_top = &cgroup_dummy_root.top_cgroup;
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 * css which the event belongs to.
164 struct cgroup_subsys_state *css;
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(cgroup_roots);
190 static int cgroup_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 static struct cgroup_name root_cgroup_name = { .name = "/" };
202 * Assign a monotonically increasing serial number to cgroups. It
203 * guarantees cgroups with bigger numbers are newer than those with smaller
204 * numbers. Also, as cgroups are always appended to the parent's
205 * ->children list, it guarantees that sibling cgroups are always sorted in
206 * the ascending serial number order on the list. Protected by
209 static u64 cgroup_serial_nr_next = 1;
211 /* This flag indicates whether tasks in the fork and exit paths should
212 * check for fork/exit handlers to call. This avoids us having to do
213 * extra work in the fork/exit path if none of the subsystems need to
216 static int need_forkexit_callback __read_mostly;
218 static struct cftype cgroup_base_files[];
220 static void cgroup_offline_fn(struct work_struct *work);
221 static int cgroup_destroy_locked(struct cgroup *cgrp);
222 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
226 * cgroup_css - obtain a cgroup's css for the specified subsystem
227 * @cgrp: the cgroup of interest
228 * @subsys_id: the subsystem of interest
230 * Return @cgrp's css (cgroup_subsys_state) associated with @subsys_id.
232 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
235 return cgrp->subsys[subsys_id];
238 /* convenient tests for these bits */
239 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
241 return test_bit(CGRP_DEAD, &cgrp->flags);
245 * cgroup_is_descendant - test ancestry
246 * @cgrp: the cgroup to be tested
247 * @ancestor: possible ancestor of @cgrp
249 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
250 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
251 * and @ancestor are accessible.
253 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
256 if (cgrp == ancestor)
262 EXPORT_SYMBOL_GPL(cgroup_is_descendant);
264 static int cgroup_is_releasable(const struct cgroup *cgrp)
267 (1 << CGRP_RELEASABLE) |
268 (1 << CGRP_NOTIFY_ON_RELEASE);
269 return (cgrp->flags & bits) == bits;
272 static int notify_on_release(const struct cgroup *cgrp)
274 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
278 * for_each_subsys - iterate all loaded cgroup subsystems
279 * @ss: the iteration cursor
280 * @i: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
282 * Should be called under cgroup_mutex.
284 #define for_each_subsys(ss, i) \
285 for ((i) = 0; (i) < CGROUP_SUBSYS_COUNT; (i)++) \
286 if (({ lockdep_assert_held(&cgroup_mutex); \
287 !((ss) = cgroup_subsys[i]); })) { } \
291 * for_each_builtin_subsys - iterate all built-in cgroup subsystems
292 * @ss: the iteration cursor
293 * @i: the index of @ss, CGROUP_BUILTIN_SUBSYS_COUNT after reaching the end
295 * Bulit-in subsystems are always present and iteration itself doesn't
296 * require any synchronization.
298 #define for_each_builtin_subsys(ss, i) \
299 for ((i) = 0; (i) < CGROUP_BUILTIN_SUBSYS_COUNT && \
300 (((ss) = cgroup_subsys[i]) || true); (i)++)
302 /* iterate each subsystem attached to a hierarchy */
303 #define for_each_root_subsys(root, ss) \
304 list_for_each_entry((ss), &(root)->subsys_list, sibling)
306 /* iterate across the active hierarchies */
307 #define for_each_active_root(root) \
308 list_for_each_entry((root), &cgroup_roots, root_list)
310 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
312 return dentry->d_fsdata;
315 static inline struct cfent *__d_cfe(struct dentry *dentry)
317 return dentry->d_fsdata;
320 static inline struct cftype *__d_cft(struct dentry *dentry)
322 return __d_cfe(dentry)->type;
326 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
327 * @cgrp: the cgroup to be checked for liveness
329 * On success, returns true; the mutex should be later unlocked. On
330 * failure returns false with no lock held.
332 static bool cgroup_lock_live_group(struct cgroup *cgrp)
334 mutex_lock(&cgroup_mutex);
335 if (cgroup_is_dead(cgrp)) {
336 mutex_unlock(&cgroup_mutex);
342 /* the list of cgroups eligible for automatic release. Protected by
343 * release_list_lock */
344 static LIST_HEAD(release_list);
345 static DEFINE_RAW_SPINLOCK(release_list_lock);
346 static void cgroup_release_agent(struct work_struct *work);
347 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
348 static void check_for_release(struct cgroup *cgrp);
351 * A cgroup can be associated with multiple css_sets as different tasks may
352 * belong to different cgroups on different hierarchies. In the other
353 * direction, a css_set is naturally associated with multiple cgroups.
354 * This M:N relationship is represented by the following link structure
355 * which exists for each association and allows traversing the associations
358 struct cgrp_cset_link {
359 /* the cgroup and css_set this link associates */
361 struct css_set *cset;
363 /* list of cgrp_cset_links anchored at cgrp->cset_links */
364 struct list_head cset_link;
366 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
367 struct list_head cgrp_link;
370 /* The default css_set - used by init and its children prior to any
371 * hierarchies being mounted. It contains a pointer to the root state
372 * for each subsystem. Also used to anchor the list of css_sets. Not
373 * reference-counted, to improve performance when child cgroups
374 * haven't been created.
377 static struct css_set init_css_set;
378 static struct cgrp_cset_link init_cgrp_cset_link;
380 static int cgroup_init_idr(struct cgroup_subsys *ss,
381 struct cgroup_subsys_state *css);
384 * css_set_lock protects the list of css_set objects, and the chain of
385 * tasks off each css_set. Nests outside task->alloc_lock due to
386 * css_task_iter_start().
388 static DEFINE_RWLOCK(css_set_lock);
389 static int css_set_count;
392 * hash table for cgroup groups. This improves the performance to find
393 * an existing css_set. This hash doesn't (currently) take into
394 * account cgroups in empty hierarchies.
396 #define CSS_SET_HASH_BITS 7
397 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
399 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
401 unsigned long key = 0UL;
402 struct cgroup_subsys *ss;
405 for_each_subsys(ss, i)
406 key += (unsigned long)css[i];
407 key = (key >> 16) ^ key;
413 * We don't maintain the lists running through each css_set to its task
414 * until after the first call to css_task_iter_start(). This reduces the
415 * fork()/exit() overhead for people who have cgroups compiled into their
416 * kernel but not actually in use.
418 static int use_task_css_set_links __read_mostly;
420 static void __put_css_set(struct css_set *cset, int taskexit)
422 struct cgrp_cset_link *link, *tmp_link;
425 * Ensure that the refcount doesn't hit zero while any readers
426 * can see it. Similar to atomic_dec_and_lock(), but for an
429 if (atomic_add_unless(&cset->refcount, -1, 1))
431 write_lock(&css_set_lock);
432 if (!atomic_dec_and_test(&cset->refcount)) {
433 write_unlock(&css_set_lock);
437 /* This css_set is dead. unlink it and release cgroup refcounts */
438 hash_del(&cset->hlist);
441 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
442 struct cgroup *cgrp = link->cgrp;
444 list_del(&link->cset_link);
445 list_del(&link->cgrp_link);
447 /* @cgrp can't go away while we're holding css_set_lock */
448 if (list_empty(&cgrp->cset_links) && notify_on_release(cgrp)) {
450 set_bit(CGRP_RELEASABLE, &cgrp->flags);
451 check_for_release(cgrp);
457 write_unlock(&css_set_lock);
458 kfree_rcu(cset, rcu_head);
462 * refcounted get/put for css_set objects
464 static inline void get_css_set(struct css_set *cset)
466 atomic_inc(&cset->refcount);
469 static inline void put_css_set(struct css_set *cset)
471 __put_css_set(cset, 0);
474 static inline void put_css_set_taskexit(struct css_set *cset)
476 __put_css_set(cset, 1);
480 * compare_css_sets - helper function for find_existing_css_set().
481 * @cset: candidate css_set being tested
482 * @old_cset: existing css_set for a task
483 * @new_cgrp: cgroup that's being entered by the task
484 * @template: desired set of css pointers in css_set (pre-calculated)
486 * Returns true if "cset" matches "old_cset" except for the hierarchy
487 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
489 static bool compare_css_sets(struct css_set *cset,
490 struct css_set *old_cset,
491 struct cgroup *new_cgrp,
492 struct cgroup_subsys_state *template[])
494 struct list_head *l1, *l2;
496 if (memcmp(template, cset->subsys, sizeof(cset->subsys))) {
497 /* Not all subsystems matched */
502 * Compare cgroup pointers in order to distinguish between
503 * different cgroups in heirarchies with no subsystems. We
504 * could get by with just this check alone (and skip the
505 * memcmp above) but on most setups the memcmp check will
506 * avoid the need for this more expensive check on almost all
510 l1 = &cset->cgrp_links;
511 l2 = &old_cset->cgrp_links;
513 struct cgrp_cset_link *link1, *link2;
514 struct cgroup *cgrp1, *cgrp2;
518 /* See if we reached the end - both lists are equal length. */
519 if (l1 == &cset->cgrp_links) {
520 BUG_ON(l2 != &old_cset->cgrp_links);
523 BUG_ON(l2 == &old_cset->cgrp_links);
525 /* Locate the cgroups associated with these links. */
526 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
527 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
530 /* Hierarchies should be linked in the same order. */
531 BUG_ON(cgrp1->root != cgrp2->root);
534 * If this hierarchy is the hierarchy of the cgroup
535 * that's changing, then we need to check that this
536 * css_set points to the new cgroup; if it's any other
537 * hierarchy, then this css_set should point to the
538 * same cgroup as the old css_set.
540 if (cgrp1->root == new_cgrp->root) {
541 if (cgrp1 != new_cgrp)
552 * find_existing_css_set - init css array and find the matching css_set
553 * @old_cset: the css_set that we're using before the cgroup transition
554 * @cgrp: the cgroup that we're moving into
555 * @template: out param for the new set of csses, should be clear on entry
557 static struct css_set *find_existing_css_set(struct css_set *old_cset,
559 struct cgroup_subsys_state *template[])
561 struct cgroupfs_root *root = cgrp->root;
562 struct cgroup_subsys *ss;
563 struct css_set *cset;
568 * Build the set of subsystem state objects that we want to see in the
569 * new css_set. while subsystems can change globally, the entries here
570 * won't change, so no need for locking.
572 for_each_subsys(ss, i) {
573 if (root->subsys_mask & (1UL << i)) {
574 /* Subsystem is in this hierarchy. So we want
575 * the subsystem state from the new
577 template[i] = cgrp->subsys[i];
579 /* Subsystem is not in this hierarchy, so we
580 * don't want to change the subsystem state */
581 template[i] = old_cset->subsys[i];
585 key = css_set_hash(template);
586 hash_for_each_possible(css_set_table, cset, hlist, key) {
587 if (!compare_css_sets(cset, old_cset, cgrp, template))
590 /* This css_set matches what we need */
594 /* No existing cgroup group matched */
598 static void free_cgrp_cset_links(struct list_head *links_to_free)
600 struct cgrp_cset_link *link, *tmp_link;
602 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
603 list_del(&link->cset_link);
609 * allocate_cgrp_cset_links - allocate cgrp_cset_links
610 * @count: the number of links to allocate
611 * @tmp_links: list_head the allocated links are put on
613 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
614 * through ->cset_link. Returns 0 on success or -errno.
616 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
618 struct cgrp_cset_link *link;
621 INIT_LIST_HEAD(tmp_links);
623 for (i = 0; i < count; i++) {
624 link = kzalloc(sizeof(*link), GFP_KERNEL);
626 free_cgrp_cset_links(tmp_links);
629 list_add(&link->cset_link, tmp_links);
635 * link_css_set - a helper function to link a css_set to a cgroup
636 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
637 * @cset: the css_set to be linked
638 * @cgrp: the destination cgroup
640 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
643 struct cgrp_cset_link *link;
645 BUG_ON(list_empty(tmp_links));
646 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
649 list_move(&link->cset_link, &cgrp->cset_links);
651 * Always add links to the tail of the list so that the list
652 * is sorted by order of hierarchy creation
654 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
658 * find_css_set - return a new css_set with one cgroup updated
659 * @old_cset: the baseline css_set
660 * @cgrp: the cgroup to be updated
662 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
663 * substituted into the appropriate hierarchy.
665 static struct css_set *find_css_set(struct css_set *old_cset,
668 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
669 struct css_set *cset;
670 struct list_head tmp_links;
671 struct cgrp_cset_link *link;
674 lockdep_assert_held(&cgroup_mutex);
676 /* First see if we already have a cgroup group that matches
678 read_lock(&css_set_lock);
679 cset = find_existing_css_set(old_cset, cgrp, template);
682 read_unlock(&css_set_lock);
687 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
691 /* Allocate all the cgrp_cset_link objects that we'll need */
692 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
697 atomic_set(&cset->refcount, 1);
698 INIT_LIST_HEAD(&cset->cgrp_links);
699 INIT_LIST_HEAD(&cset->tasks);
700 INIT_HLIST_NODE(&cset->hlist);
702 /* Copy the set of subsystem state objects generated in
703 * find_existing_css_set() */
704 memcpy(cset->subsys, template, sizeof(cset->subsys));
706 write_lock(&css_set_lock);
707 /* Add reference counts and links from the new css_set. */
708 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
709 struct cgroup *c = link->cgrp;
711 if (c->root == cgrp->root)
713 link_css_set(&tmp_links, cset, c);
716 BUG_ON(!list_empty(&tmp_links));
720 /* Add this cgroup group to the hash table */
721 key = css_set_hash(cset->subsys);
722 hash_add(css_set_table, &cset->hlist, key);
724 write_unlock(&css_set_lock);
730 * Return the cgroup for "task" from the given hierarchy. Must be
731 * called with cgroup_mutex held.
733 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
734 struct cgroupfs_root *root)
736 struct css_set *cset;
737 struct cgroup *res = NULL;
739 BUG_ON(!mutex_is_locked(&cgroup_mutex));
740 read_lock(&css_set_lock);
742 * No need to lock the task - since we hold cgroup_mutex the
743 * task can't change groups, so the only thing that can happen
744 * is that it exits and its css is set back to init_css_set.
746 cset = task_css_set(task);
747 if (cset == &init_css_set) {
748 res = &root->top_cgroup;
750 struct cgrp_cset_link *link;
752 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
753 struct cgroup *c = link->cgrp;
755 if (c->root == root) {
761 read_unlock(&css_set_lock);
767 * There is one global cgroup mutex. We also require taking
768 * task_lock() when dereferencing a task's cgroup subsys pointers.
769 * See "The task_lock() exception", at the end of this comment.
771 * A task must hold cgroup_mutex to modify cgroups.
773 * Any task can increment and decrement the count field without lock.
774 * So in general, code holding cgroup_mutex can't rely on the count
775 * field not changing. However, if the count goes to zero, then only
776 * cgroup_attach_task() can increment it again. Because a count of zero
777 * means that no tasks are currently attached, therefore there is no
778 * way a task attached to that cgroup can fork (the other way to
779 * increment the count). So code holding cgroup_mutex can safely
780 * assume that if the count is zero, it will stay zero. Similarly, if
781 * a task holds cgroup_mutex on a cgroup with zero count, it
782 * knows that the cgroup won't be removed, as cgroup_rmdir()
785 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
786 * (usually) take cgroup_mutex. These are the two most performance
787 * critical pieces of code here. The exception occurs on cgroup_exit(),
788 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
789 * is taken, and if the cgroup count is zero, a usermode call made
790 * to the release agent with the name of the cgroup (path relative to
791 * the root of cgroup file system) as the argument.
793 * A cgroup can only be deleted if both its 'count' of using tasks
794 * is zero, and its list of 'children' cgroups is empty. Since all
795 * tasks in the system use _some_ cgroup, and since there is always at
796 * least one task in the system (init, pid == 1), therefore, top_cgroup
797 * always has either children cgroups and/or using tasks. So we don't
798 * need a special hack to ensure that top_cgroup cannot be deleted.
800 * The task_lock() exception
802 * The need for this exception arises from the action of
803 * cgroup_attach_task(), which overwrites one task's cgroup pointer with
804 * another. It does so using cgroup_mutex, however there are
805 * several performance critical places that need to reference
806 * task->cgroup without the expense of grabbing a system global
807 * mutex. Therefore except as noted below, when dereferencing or, as
808 * in cgroup_attach_task(), modifying a task's cgroup pointer we use
809 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
810 * the task_struct routinely used for such matters.
812 * P.S. One more locking exception. RCU is used to guard the
813 * update of a tasks cgroup pointer by cgroup_attach_task()
817 * A couple of forward declarations required, due to cyclic reference loop:
818 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
819 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
823 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode);
824 static struct dentry *cgroup_lookup(struct inode *, struct dentry *, unsigned int);
825 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
826 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask);
827 static const struct inode_operations cgroup_dir_inode_operations;
828 static const struct file_operations proc_cgroupstats_operations;
830 static struct backing_dev_info cgroup_backing_dev_info = {
832 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
835 static int alloc_css_id(struct cgroup_subsys *ss,
836 struct cgroup *parent, struct cgroup *child);
838 static struct inode *cgroup_new_inode(umode_t mode, struct super_block *sb)
840 struct inode *inode = new_inode(sb);
843 inode->i_ino = get_next_ino();
844 inode->i_mode = mode;
845 inode->i_uid = current_fsuid();
846 inode->i_gid = current_fsgid();
847 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
848 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
853 static struct cgroup_name *cgroup_alloc_name(struct dentry *dentry)
855 struct cgroup_name *name;
857 name = kmalloc(sizeof(*name) + dentry->d_name.len + 1, GFP_KERNEL);
860 strcpy(name->name, dentry->d_name.name);
864 static void cgroup_free_fn(struct work_struct *work)
866 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
867 struct cgroup_subsys *ss;
869 mutex_lock(&cgroup_mutex);
871 * Release the subsystem state objects.
873 for_each_root_subsys(cgrp->root, ss) {
874 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
879 cgrp->root->number_of_cgroups--;
880 mutex_unlock(&cgroup_mutex);
883 * We get a ref to the parent's dentry, and put the ref when
884 * this cgroup is being freed, so it's guaranteed that the
885 * parent won't be destroyed before its children.
887 dput(cgrp->parent->dentry);
890 * Drop the active superblock reference that we took when we
891 * created the cgroup. This will free cgrp->root, if we are
892 * holding the last reference to @sb.
894 deactivate_super(cgrp->root->sb);
897 * if we're getting rid of the cgroup, refcount should ensure
898 * that there are no pidlists left.
900 BUG_ON(!list_empty(&cgrp->pidlists));
902 simple_xattrs_free(&cgrp->xattrs);
904 kfree(rcu_dereference_raw(cgrp->name));
908 static void cgroup_free_rcu(struct rcu_head *head)
910 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
912 INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
913 schedule_work(&cgrp->destroy_work);
916 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
918 /* is dentry a directory ? if so, kfree() associated cgroup */
919 if (S_ISDIR(inode->i_mode)) {
920 struct cgroup *cgrp = dentry->d_fsdata;
922 BUG_ON(!(cgroup_is_dead(cgrp)));
923 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
925 struct cfent *cfe = __d_cfe(dentry);
926 struct cgroup *cgrp = dentry->d_parent->d_fsdata;
928 WARN_ONCE(!list_empty(&cfe->node) &&
929 cgrp != &cgrp->root->top_cgroup,
930 "cfe still linked for %s\n", cfe->type->name);
931 simple_xattrs_free(&cfe->xattrs);
937 static int cgroup_delete(const struct dentry *d)
942 static void remove_dir(struct dentry *d)
944 struct dentry *parent = dget(d->d_parent);
947 simple_rmdir(parent->d_inode, d);
951 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
955 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
956 lockdep_assert_held(&cgroup_mutex);
959 * If we're doing cleanup due to failure of cgroup_create(),
960 * the corresponding @cfe may not exist.
962 list_for_each_entry(cfe, &cgrp->files, node) {
963 struct dentry *d = cfe->dentry;
965 if (cft && cfe->type != cft)
970 simple_unlink(cgrp->dentry->d_inode, d);
971 list_del_init(&cfe->node);
979 * cgroup_clear_dir - remove subsys files in a cgroup directory
980 * @cgrp: target cgroup
981 * @subsys_mask: mask of the subsystem ids whose files should be removed
983 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned long subsys_mask)
985 struct cgroup_subsys *ss;
988 for_each_subsys(ss, i) {
989 struct cftype_set *set;
991 if (!test_bit(i, &subsys_mask))
993 list_for_each_entry(set, &ss->cftsets, node)
994 cgroup_addrm_files(cgrp, set->cfts, false);
999 * NOTE : the dentry must have been dget()'ed
1001 static void cgroup_d_remove_dir(struct dentry *dentry)
1003 struct dentry *parent;
1005 parent = dentry->d_parent;
1006 spin_lock(&parent->d_lock);
1007 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
1008 list_del_init(&dentry->d_u.d_child);
1009 spin_unlock(&dentry->d_lock);
1010 spin_unlock(&parent->d_lock);
1015 * Call with cgroup_mutex held. Drops reference counts on modules, including
1016 * any duplicate ones that parse_cgroupfs_options took. If this function
1017 * returns an error, no reference counts are touched.
1019 static int rebind_subsystems(struct cgroupfs_root *root,
1020 unsigned long added_mask, unsigned removed_mask)
1022 struct cgroup *cgrp = &root->top_cgroup;
1023 struct cgroup_subsys *ss;
1024 unsigned long pinned = 0;
1027 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1028 BUG_ON(!mutex_is_locked(&cgroup_root_mutex));
1030 /* Check that any added subsystems are currently free */
1031 for_each_subsys(ss, i) {
1032 if (!(added_mask & (1 << i)))
1035 /* is the subsystem mounted elsewhere? */
1036 if (ss->root != &cgroup_dummy_root) {
1041 /* pin the module */
1042 if (!try_module_get(ss->module)) {
1049 /* subsys could be missing if unloaded between parsing and here */
1050 if (added_mask != pinned) {
1055 ret = cgroup_populate_dir(cgrp, added_mask);
1060 * Nothing can fail from this point on. Remove files for the
1061 * removed subsystems and rebind each subsystem.
1063 cgroup_clear_dir(cgrp, removed_mask);
1065 for_each_subsys(ss, i) {
1066 unsigned long bit = 1UL << i;
1068 if (bit & added_mask) {
1069 /* We're binding this subsystem to this hierarchy */
1070 BUG_ON(cgrp->subsys[i]);
1071 BUG_ON(!cgroup_dummy_top->subsys[i]);
1072 BUG_ON(cgroup_dummy_top->subsys[i]->cgroup != cgroup_dummy_top);
1074 cgrp->subsys[i] = cgroup_dummy_top->subsys[i];
1075 cgrp->subsys[i]->cgroup = cgrp;
1076 list_move(&ss->sibling, &root->subsys_list);
1079 ss->bind(cgrp->subsys[i]);
1081 /* refcount was already taken, and we're keeping it */
1082 root->subsys_mask |= bit;
1083 } else if (bit & removed_mask) {
1084 /* We're removing this subsystem */
1085 BUG_ON(cgrp->subsys[i] != cgroup_dummy_top->subsys[i]);
1086 BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
1089 ss->bind(cgroup_dummy_top->subsys[i]);
1090 cgroup_dummy_top->subsys[i]->cgroup = cgroup_dummy_top;
1091 cgrp->subsys[i] = NULL;
1092 cgroup_subsys[i]->root = &cgroup_dummy_root;
1093 list_move(&ss->sibling, &cgroup_dummy_root.subsys_list);
1095 /* subsystem is now free - drop reference on module */
1096 module_put(ss->module);
1097 root->subsys_mask &= ~bit;
1102 * Mark @root has finished binding subsystems. @root->subsys_mask
1103 * now matches the bound subsystems.
1105 root->flags |= CGRP_ROOT_SUBSYS_BOUND;
1110 for_each_subsys(ss, i)
1111 if (pinned & (1 << i))
1112 module_put(ss->module);
1116 static int cgroup_show_options(struct seq_file *seq, struct dentry *dentry)
1118 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
1119 struct cgroup_subsys *ss;
1121 mutex_lock(&cgroup_root_mutex);
1122 for_each_root_subsys(root, ss)
1123 seq_printf(seq, ",%s", ss->name);
1124 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1125 seq_puts(seq, ",sane_behavior");
1126 if (root->flags & CGRP_ROOT_NOPREFIX)
1127 seq_puts(seq, ",noprefix");
1128 if (root->flags & CGRP_ROOT_XATTR)
1129 seq_puts(seq, ",xattr");
1130 if (strlen(root->release_agent_path))
1131 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1132 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1133 seq_puts(seq, ",clone_children");
1134 if (strlen(root->name))
1135 seq_printf(seq, ",name=%s", root->name);
1136 mutex_unlock(&cgroup_root_mutex);
1140 struct cgroup_sb_opts {
1141 unsigned long subsys_mask;
1142 unsigned long flags;
1143 char *release_agent;
1144 bool cpuset_clone_children;
1146 /* User explicitly requested empty subsystem */
1149 struct cgroupfs_root *new_root;
1154 * Convert a hierarchy specifier into a bitmask of subsystems and
1155 * flags. Call with cgroup_mutex held to protect the cgroup_subsys[]
1156 * array. This function takes refcounts on subsystems to be used, unless it
1157 * returns error, in which case no refcounts are taken.
1159 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1161 char *token, *o = data;
1162 bool all_ss = false, one_ss = false;
1163 unsigned long mask = (unsigned long)-1;
1164 struct cgroup_subsys *ss;
1167 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1169 #ifdef CONFIG_CPUSETS
1170 mask = ~(1UL << cpuset_subsys_id);
1173 memset(opts, 0, sizeof(*opts));
1175 while ((token = strsep(&o, ",")) != NULL) {
1178 if (!strcmp(token, "none")) {
1179 /* Explicitly have no subsystems */
1183 if (!strcmp(token, "all")) {
1184 /* Mutually exclusive option 'all' + subsystem name */
1190 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1191 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1194 if (!strcmp(token, "noprefix")) {
1195 opts->flags |= CGRP_ROOT_NOPREFIX;
1198 if (!strcmp(token, "clone_children")) {
1199 opts->cpuset_clone_children = true;
1202 if (!strcmp(token, "xattr")) {
1203 opts->flags |= CGRP_ROOT_XATTR;
1206 if (!strncmp(token, "release_agent=", 14)) {
1207 /* Specifying two release agents is forbidden */
1208 if (opts->release_agent)
1210 opts->release_agent =
1211 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1212 if (!opts->release_agent)
1216 if (!strncmp(token, "name=", 5)) {
1217 const char *name = token + 5;
1218 /* Can't specify an empty name */
1221 /* Must match [\w.-]+ */
1222 for (i = 0; i < strlen(name); i++) {
1226 if ((c == '.') || (c == '-') || (c == '_'))
1230 /* Specifying two names is forbidden */
1233 opts->name = kstrndup(name,
1234 MAX_CGROUP_ROOT_NAMELEN - 1,
1242 for_each_subsys(ss, i) {
1243 if (strcmp(token, ss->name))
1248 /* Mutually exclusive option 'all' + subsystem name */
1251 set_bit(i, &opts->subsys_mask);
1256 if (i == CGROUP_SUBSYS_COUNT)
1261 * If the 'all' option was specified select all the subsystems,
1262 * otherwise if 'none', 'name=' and a subsystem name options
1263 * were not specified, let's default to 'all'
1265 if (all_ss || (!one_ss && !opts->none && !opts->name))
1266 for_each_subsys(ss, i)
1268 set_bit(i, &opts->subsys_mask);
1270 /* Consistency checks */
1272 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1273 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1275 if (opts->flags & CGRP_ROOT_NOPREFIX) {
1276 pr_err("cgroup: sane_behavior: noprefix is not allowed\n");
1280 if (opts->cpuset_clone_children) {
1281 pr_err("cgroup: sane_behavior: clone_children is not allowed\n");
1287 * Option noprefix was introduced just for backward compatibility
1288 * with the old cpuset, so we allow noprefix only if mounting just
1289 * the cpuset subsystem.
1291 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1295 /* Can't specify "none" and some subsystems */
1296 if (opts->subsys_mask && opts->none)
1300 * We either have to specify by name or by subsystems. (So all
1301 * empty hierarchies must have a name).
1303 if (!opts->subsys_mask && !opts->name)
1309 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1312 struct cgroupfs_root *root = sb->s_fs_info;
1313 struct cgroup *cgrp = &root->top_cgroup;
1314 struct cgroup_sb_opts opts;
1315 unsigned long added_mask, removed_mask;
1317 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1318 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1322 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1323 mutex_lock(&cgroup_mutex);
1324 mutex_lock(&cgroup_root_mutex);
1326 /* See what subsystems are wanted */
1327 ret = parse_cgroupfs_options(data, &opts);
1331 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1332 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1333 task_tgid_nr(current), current->comm);
1335 added_mask = opts.subsys_mask & ~root->subsys_mask;
1336 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1338 /* Don't allow flags or name to change at remount */
1339 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1340 (opts.name && strcmp(opts.name, root->name))) {
1341 pr_err("cgroup: option or name mismatch, new: 0x%lx \"%s\", old: 0x%lx \"%s\"\n",
1342 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1343 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1348 /* remounting is not allowed for populated hierarchies */
1349 if (root->number_of_cgroups > 1) {
1354 ret = rebind_subsystems(root, added_mask, removed_mask);
1358 if (opts.release_agent)
1359 strcpy(root->release_agent_path, opts.release_agent);
1361 kfree(opts.release_agent);
1363 mutex_unlock(&cgroup_root_mutex);
1364 mutex_unlock(&cgroup_mutex);
1365 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1369 static const struct super_operations cgroup_ops = {
1370 .statfs = simple_statfs,
1371 .drop_inode = generic_delete_inode,
1372 .show_options = cgroup_show_options,
1373 .remount_fs = cgroup_remount,
1376 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1378 INIT_LIST_HEAD(&cgrp->sibling);
1379 INIT_LIST_HEAD(&cgrp->children);
1380 INIT_LIST_HEAD(&cgrp->files);
1381 INIT_LIST_HEAD(&cgrp->cset_links);
1382 INIT_LIST_HEAD(&cgrp->release_list);
1383 INIT_LIST_HEAD(&cgrp->pidlists);
1384 mutex_init(&cgrp->pidlist_mutex);
1385 cgrp->dummy_css.cgroup = cgrp;
1386 INIT_LIST_HEAD(&cgrp->event_list);
1387 spin_lock_init(&cgrp->event_list_lock);
1388 simple_xattrs_init(&cgrp->xattrs);
1391 static void init_cgroup_root(struct cgroupfs_root *root)
1393 struct cgroup *cgrp = &root->top_cgroup;
1395 INIT_LIST_HEAD(&root->subsys_list);
1396 INIT_LIST_HEAD(&root->root_list);
1397 root->number_of_cgroups = 1;
1399 RCU_INIT_POINTER(cgrp->name, &root_cgroup_name);
1400 init_cgroup_housekeeping(cgrp);
1401 idr_init(&root->cgroup_idr);
1404 static int cgroup_init_root_id(struct cgroupfs_root *root, int start, int end)
1408 lockdep_assert_held(&cgroup_mutex);
1409 lockdep_assert_held(&cgroup_root_mutex);
1411 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, start, end,
1416 root->hierarchy_id = id;
1420 static void cgroup_exit_root_id(struct cgroupfs_root *root)
1422 lockdep_assert_held(&cgroup_mutex);
1423 lockdep_assert_held(&cgroup_root_mutex);
1425 if (root->hierarchy_id) {
1426 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1427 root->hierarchy_id = 0;
1431 static int cgroup_test_super(struct super_block *sb, void *data)
1433 struct cgroup_sb_opts *opts = data;
1434 struct cgroupfs_root *root = sb->s_fs_info;
1436 /* If we asked for a name then it must match */
1437 if (opts->name && strcmp(opts->name, root->name))
1441 * If we asked for subsystems (or explicitly for no
1442 * subsystems) then they must match
1444 if ((opts->subsys_mask || opts->none)
1445 && (opts->subsys_mask != root->subsys_mask))
1451 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1453 struct cgroupfs_root *root;
1455 if (!opts->subsys_mask && !opts->none)
1458 root = kzalloc(sizeof(*root), GFP_KERNEL);
1460 return ERR_PTR(-ENOMEM);
1462 init_cgroup_root(root);
1465 * We need to set @root->subsys_mask now so that @root can be
1466 * matched by cgroup_test_super() before it finishes
1467 * initialization; otherwise, competing mounts with the same
1468 * options may try to bind the same subsystems instead of waiting
1469 * for the first one leading to unexpected mount errors.
1470 * SUBSYS_BOUND will be set once actual binding is complete.
1472 root->subsys_mask = opts->subsys_mask;
1473 root->flags = opts->flags;
1474 if (opts->release_agent)
1475 strcpy(root->release_agent_path, opts->release_agent);
1477 strcpy(root->name, opts->name);
1478 if (opts->cpuset_clone_children)
1479 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1483 static void cgroup_free_root(struct cgroupfs_root *root)
1486 /* hierarhcy ID shoulid already have been released */
1487 WARN_ON_ONCE(root->hierarchy_id);
1489 idr_destroy(&root->cgroup_idr);
1494 static int cgroup_set_super(struct super_block *sb, void *data)
1497 struct cgroup_sb_opts *opts = data;
1499 /* If we don't have a new root, we can't set up a new sb */
1500 if (!opts->new_root)
1503 BUG_ON(!opts->subsys_mask && !opts->none);
1505 ret = set_anon_super(sb, NULL);
1509 sb->s_fs_info = opts->new_root;
1510 opts->new_root->sb = sb;
1512 sb->s_blocksize = PAGE_CACHE_SIZE;
1513 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1514 sb->s_magic = CGROUP_SUPER_MAGIC;
1515 sb->s_op = &cgroup_ops;
1520 static int cgroup_get_rootdir(struct super_block *sb)
1522 static const struct dentry_operations cgroup_dops = {
1523 .d_iput = cgroup_diput,
1524 .d_delete = cgroup_delete,
1527 struct inode *inode =
1528 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1533 inode->i_fop = &simple_dir_operations;
1534 inode->i_op = &cgroup_dir_inode_operations;
1535 /* directories start off with i_nlink == 2 (for "." entry) */
1537 sb->s_root = d_make_root(inode);
1540 /* for everything else we want ->d_op set */
1541 sb->s_d_op = &cgroup_dops;
1545 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1546 int flags, const char *unused_dev_name,
1549 struct cgroup_sb_opts opts;
1550 struct cgroupfs_root *root;
1552 struct super_block *sb;
1553 struct cgroupfs_root *new_root;
1554 struct list_head tmp_links;
1555 struct inode *inode;
1556 const struct cred *cred;
1558 /* First find the desired set of subsystems */
1559 mutex_lock(&cgroup_mutex);
1560 ret = parse_cgroupfs_options(data, &opts);
1561 mutex_unlock(&cgroup_mutex);
1566 * Allocate a new cgroup root. We may not need it if we're
1567 * reusing an existing hierarchy.
1569 new_root = cgroup_root_from_opts(&opts);
1570 if (IS_ERR(new_root)) {
1571 ret = PTR_ERR(new_root);
1574 opts.new_root = new_root;
1576 /* Locate an existing or new sb for this hierarchy */
1577 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1580 cgroup_free_root(opts.new_root);
1584 root = sb->s_fs_info;
1586 if (root == opts.new_root) {
1587 /* We used the new root structure, so this is a new hierarchy */
1588 struct cgroup *root_cgrp = &root->top_cgroup;
1589 struct cgroupfs_root *existing_root;
1591 struct css_set *cset;
1593 BUG_ON(sb->s_root != NULL);
1595 ret = cgroup_get_rootdir(sb);
1597 goto drop_new_super;
1598 inode = sb->s_root->d_inode;
1600 mutex_lock(&inode->i_mutex);
1601 mutex_lock(&cgroup_mutex);
1602 mutex_lock(&cgroup_root_mutex);
1604 root_cgrp->id = idr_alloc(&root->cgroup_idr, root_cgrp,
1606 if (root_cgrp->id < 0)
1609 /* Check for name clashes with existing mounts */
1611 if (strlen(root->name))
1612 for_each_active_root(existing_root)
1613 if (!strcmp(existing_root->name, root->name))
1617 * We're accessing css_set_count without locking
1618 * css_set_lock here, but that's OK - it can only be
1619 * increased by someone holding cgroup_lock, and
1620 * that's us. The worst that can happen is that we
1621 * have some link structures left over
1623 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1627 /* ID 0 is reserved for dummy root, 1 for unified hierarchy */
1628 ret = cgroup_init_root_id(root, 2, 0);
1632 sb->s_root->d_fsdata = root_cgrp;
1633 root_cgrp->dentry = sb->s_root;
1636 * We're inside get_sb() and will call lookup_one_len() to
1637 * create the root files, which doesn't work if SELinux is
1638 * in use. The following cred dancing somehow works around
1639 * it. See 2ce9738ba ("cgroupfs: use init_cred when
1640 * populating new cgroupfs mount") for more details.
1642 cred = override_creds(&init_cred);
1644 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1648 ret = rebind_subsystems(root, root->subsys_mask, 0);
1655 * There must be no failure case after here, since rebinding
1656 * takes care of subsystems' refcounts, which are explicitly
1657 * dropped in the failure exit path.
1660 list_add(&root->root_list, &cgroup_roots);
1661 cgroup_root_count++;
1663 /* Link the top cgroup in this hierarchy into all
1664 * the css_set objects */
1665 write_lock(&css_set_lock);
1666 hash_for_each(css_set_table, i, cset, hlist)
1667 link_css_set(&tmp_links, cset, root_cgrp);
1668 write_unlock(&css_set_lock);
1670 free_cgrp_cset_links(&tmp_links);
1672 BUG_ON(!list_empty(&root_cgrp->children));
1673 BUG_ON(root->number_of_cgroups != 1);
1675 mutex_unlock(&cgroup_root_mutex);
1676 mutex_unlock(&cgroup_mutex);
1677 mutex_unlock(&inode->i_mutex);
1680 * We re-used an existing hierarchy - the new root (if
1681 * any) is not needed
1683 cgroup_free_root(opts.new_root);
1685 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1686 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1687 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1689 goto drop_new_super;
1691 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1696 kfree(opts.release_agent);
1698 return dget(sb->s_root);
1701 free_cgrp_cset_links(&tmp_links);
1702 cgroup_addrm_files(&root->top_cgroup, cgroup_base_files, false);
1705 cgroup_exit_root_id(root);
1706 mutex_unlock(&cgroup_root_mutex);
1707 mutex_unlock(&cgroup_mutex);
1708 mutex_unlock(&inode->i_mutex);
1710 deactivate_locked_super(sb);
1712 kfree(opts.release_agent);
1714 return ERR_PTR(ret);
1717 static void cgroup_kill_sb(struct super_block *sb) {
1718 struct cgroupfs_root *root = sb->s_fs_info;
1719 struct cgroup *cgrp = &root->top_cgroup;
1720 struct cgrp_cset_link *link, *tmp_link;
1725 BUG_ON(root->number_of_cgroups != 1);
1726 BUG_ON(!list_empty(&cgrp->children));
1728 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1729 mutex_lock(&cgroup_mutex);
1730 mutex_lock(&cgroup_root_mutex);
1732 /* Rebind all subsystems back to the default hierarchy */
1733 if (root->flags & CGRP_ROOT_SUBSYS_BOUND) {
1734 ret = rebind_subsystems(root, 0, root->subsys_mask);
1735 /* 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);
1754 cgroup_root_count--;
1757 cgroup_exit_root_id(root);
1759 mutex_unlock(&cgroup_root_mutex);
1760 mutex_unlock(&cgroup_mutex);
1761 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1763 simple_xattrs_free(&cgrp->xattrs);
1765 kill_litter_super(sb);
1766 cgroup_free_root(root);
1769 static struct file_system_type cgroup_fs_type = {
1771 .mount = cgroup_mount,
1772 .kill_sb = cgroup_kill_sb,
1775 static struct kobject *cgroup_kobj;
1778 * cgroup_path - generate the path of a cgroup
1779 * @cgrp: the cgroup in question
1780 * @buf: the buffer to write the path into
1781 * @buflen: the length of the buffer
1783 * Writes path of cgroup into buf. Returns 0 on success, -errno on error.
1785 * We can't generate cgroup path using dentry->d_name, as accessing
1786 * dentry->name must be protected by irq-unsafe dentry->d_lock or parent
1787 * inode's i_mutex, while on the other hand cgroup_path() can be called
1788 * with some irq-safe spinlocks held.
1790 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1792 int ret = -ENAMETOOLONG;
1795 if (!cgrp->parent) {
1796 if (strlcpy(buf, "/", buflen) >= buflen)
1797 return -ENAMETOOLONG;
1801 start = buf + buflen - 1;
1806 const char *name = cgroup_name(cgrp);
1810 if ((start -= len) < buf)
1812 memcpy(start, name, len);
1818 cgrp = cgrp->parent;
1819 } while (cgrp->parent);
1821 memmove(buf, start, buf + buflen - start);
1826 EXPORT_SYMBOL_GPL(cgroup_path);
1829 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1830 * @task: target task
1831 * @buf: the buffer to write the path into
1832 * @buflen: the length of the buffer
1834 * Determine @task's cgroup on the first (the one with the lowest non-zero
1835 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1836 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1837 * cgroup controller callbacks.
1839 * Returns 0 on success, fails with -%ENAMETOOLONG if @buflen is too short.
1841 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1843 struct cgroupfs_root *root;
1844 struct cgroup *cgrp;
1845 int hierarchy_id = 1, ret = 0;
1848 return -ENAMETOOLONG;
1850 mutex_lock(&cgroup_mutex);
1852 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1855 cgrp = task_cgroup_from_root(task, root);
1856 ret = cgroup_path(cgrp, buf, buflen);
1858 /* if no hierarchy exists, everyone is in "/" */
1859 memcpy(buf, "/", 2);
1862 mutex_unlock(&cgroup_mutex);
1865 EXPORT_SYMBOL_GPL(task_cgroup_path);
1868 * Control Group taskset
1870 struct task_and_cgroup {
1871 struct task_struct *task;
1872 struct cgroup *cgrp;
1873 struct css_set *cset;
1876 struct cgroup_taskset {
1877 struct task_and_cgroup single;
1878 struct flex_array *tc_array;
1881 struct cgroup *cur_cgrp;
1885 * cgroup_taskset_first - reset taskset and return the first task
1886 * @tset: taskset of interest
1888 * @tset iteration is initialized and the first task is returned.
1890 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1892 if (tset->tc_array) {
1894 return cgroup_taskset_next(tset);
1896 tset->cur_cgrp = tset->single.cgrp;
1897 return tset->single.task;
1900 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1903 * cgroup_taskset_next - iterate to the next task in taskset
1904 * @tset: taskset of interest
1906 * Return the next task in @tset. Iteration must have been initialized
1907 * with cgroup_taskset_first().
1909 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1911 struct task_and_cgroup *tc;
1913 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1916 tc = flex_array_get(tset->tc_array, tset->idx++);
1917 tset->cur_cgrp = tc->cgrp;
1920 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1923 * cgroup_taskset_cur_css - return the matching css for the current task
1924 * @tset: taskset of interest
1925 * @subsys_id: the ID of the target subsystem
1927 * Return the css for the current (last returned) task of @tset for
1928 * subsystem specified by @subsys_id. This function must be preceded by
1929 * either cgroup_taskset_first() or cgroup_taskset_next().
1931 struct cgroup_subsys_state *cgroup_taskset_cur_css(struct cgroup_taskset *tset,
1934 return cgroup_css(tset->cur_cgrp, subsys_id);
1936 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_css);
1939 * cgroup_taskset_size - return the number of tasks in taskset
1940 * @tset: taskset of interest
1942 int cgroup_taskset_size(struct cgroup_taskset *tset)
1944 return tset->tc_array ? tset->tc_array_len : 1;
1946 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1950 * cgroup_task_migrate - move a task from one cgroup to another.
1952 * Must be called with cgroup_mutex and threadgroup locked.
1954 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1955 struct task_struct *tsk,
1956 struct css_set *new_cset)
1958 struct css_set *old_cset;
1961 * We are synchronized through threadgroup_lock() against PF_EXITING
1962 * setting such that we can't race against cgroup_exit() changing the
1963 * css_set to init_css_set and dropping the old one.
1965 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1966 old_cset = task_css_set(tsk);
1969 rcu_assign_pointer(tsk->cgroups, new_cset);
1972 /* Update the css_set linked lists if we're using them */
1973 write_lock(&css_set_lock);
1974 if (!list_empty(&tsk->cg_list))
1975 list_move(&tsk->cg_list, &new_cset->tasks);
1976 write_unlock(&css_set_lock);
1979 * We just gained a reference on old_cset by taking it from the
1980 * task. As trading it for new_cset is protected by cgroup_mutex,
1981 * we're safe to drop it here; it will be freed under RCU.
1983 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1984 put_css_set(old_cset);
1988 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1989 * @cgrp: the cgroup to attach to
1990 * @tsk: the task or the leader of the threadgroup to be attached
1991 * @threadgroup: attach the whole threadgroup?
1993 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
1994 * task_lock of @tsk or each thread in the threadgroup individually in turn.
1996 static int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk,
1999 int retval, i, group_size;
2000 struct cgroup_subsys *ss, *failed_ss = NULL;
2001 struct cgroupfs_root *root = cgrp->root;
2002 /* threadgroup list cursor and array */
2003 struct task_struct *leader = tsk;
2004 struct task_and_cgroup *tc;
2005 struct flex_array *group;
2006 struct cgroup_taskset tset = { };
2009 * step 0: in order to do expensive, possibly blocking operations for
2010 * every thread, we cannot iterate the thread group list, since it needs
2011 * rcu or tasklist locked. instead, build an array of all threads in the
2012 * group - group_rwsem prevents new threads from appearing, and if
2013 * threads exit, this will just be an over-estimate.
2016 group_size = get_nr_threads(tsk);
2019 /* flex_array supports very large thread-groups better than kmalloc. */
2020 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
2023 /* pre-allocate to guarantee space while iterating in rcu read-side. */
2024 retval = flex_array_prealloc(group, 0, group_size, GFP_KERNEL);
2026 goto out_free_group_list;
2030 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2031 * already PF_EXITING could be freed from underneath us unless we
2032 * take an rcu_read_lock.
2036 struct task_and_cgroup ent;
2038 /* @tsk either already exited or can't exit until the end */
2039 if (tsk->flags & PF_EXITING)
2042 /* as per above, nr_threads may decrease, but not increase. */
2043 BUG_ON(i >= group_size);
2045 ent.cgrp = task_cgroup_from_root(tsk, root);
2046 /* nothing to do if this task is already in the cgroup */
2047 if (ent.cgrp == cgrp)
2050 * saying GFP_ATOMIC has no effect here because we did prealloc
2051 * earlier, but it's good form to communicate our expectations.
2053 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
2054 BUG_ON(retval != 0);
2059 } while_each_thread(leader, tsk);
2061 /* remember the number of threads in the array for later. */
2063 tset.tc_array = group;
2064 tset.tc_array_len = group_size;
2066 /* methods shouldn't be called if no task is actually migrating */
2069 goto out_free_group_list;
2072 * step 1: check that we can legitimately attach to the cgroup.
2074 for_each_root_subsys(root, ss) {
2075 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
2077 if (ss->can_attach) {
2078 retval = ss->can_attach(css, &tset);
2081 goto out_cancel_attach;
2087 * step 2: make sure css_sets exist for all threads to be migrated.
2088 * we use find_css_set, which allocates a new one if necessary.
2090 for (i = 0; i < group_size; i++) {
2091 struct css_set *old_cset;
2093 tc = flex_array_get(group, i);
2094 old_cset = task_css_set(tc->task);
2095 tc->cset = find_css_set(old_cset, cgrp);
2098 goto out_put_css_set_refs;
2103 * step 3: now that we're guaranteed success wrt the css_sets,
2104 * proceed to move all tasks to the new cgroup. There are no
2105 * failure cases after here, so this is the commit point.
2107 for (i = 0; i < group_size; i++) {
2108 tc = flex_array_get(group, i);
2109 cgroup_task_migrate(tc->cgrp, tc->task, tc->cset);
2111 /* nothing is sensitive to fork() after this point. */
2114 * step 4: do subsystem attach callbacks.
2116 for_each_root_subsys(root, ss) {
2117 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
2120 ss->attach(css, &tset);
2124 * step 5: success! and cleanup
2127 out_put_css_set_refs:
2129 for (i = 0; i < group_size; i++) {
2130 tc = flex_array_get(group, i);
2133 put_css_set(tc->cset);
2138 for_each_root_subsys(root, ss) {
2139 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
2141 if (ss == failed_ss)
2143 if (ss->cancel_attach)
2144 ss->cancel_attach(css, &tset);
2147 out_free_group_list:
2148 flex_array_free(group);
2153 * Find the task_struct of the task to attach by vpid and pass it along to the
2154 * function to attach either it or all tasks in its threadgroup. Will lock
2155 * cgroup_mutex and threadgroup; may take task_lock of task.
2157 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2159 struct task_struct *tsk;
2160 const struct cred *cred = current_cred(), *tcred;
2163 if (!cgroup_lock_live_group(cgrp))
2169 tsk = find_task_by_vpid(pid);
2173 goto out_unlock_cgroup;
2176 * even if we're attaching all tasks in the thread group, we
2177 * only need to check permissions on one of them.
2179 tcred = __task_cred(tsk);
2180 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2181 !uid_eq(cred->euid, tcred->uid) &&
2182 !uid_eq(cred->euid, tcred->suid)) {
2185 goto out_unlock_cgroup;
2191 tsk = tsk->group_leader;
2194 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2195 * trapped in a cpuset, or RT worker may be born in a cgroup
2196 * with no rt_runtime allocated. Just say no.
2198 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2201 goto out_unlock_cgroup;
2204 get_task_struct(tsk);
2207 threadgroup_lock(tsk);
2209 if (!thread_group_leader(tsk)) {
2211 * a race with de_thread from another thread's exec()
2212 * may strip us of our leadership, if this happens,
2213 * there is no choice but to throw this task away and
2214 * try again; this is
2215 * "double-double-toil-and-trouble-check locking".
2217 threadgroup_unlock(tsk);
2218 put_task_struct(tsk);
2219 goto retry_find_task;
2223 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2225 threadgroup_unlock(tsk);
2227 put_task_struct(tsk);
2229 mutex_unlock(&cgroup_mutex);
2234 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2235 * @from: attach to all cgroups of a given task
2236 * @tsk: the task to be attached
2238 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2240 struct cgroupfs_root *root;
2243 mutex_lock(&cgroup_mutex);
2244 for_each_active_root(root) {
2245 struct cgroup *from_cgrp = task_cgroup_from_root(from, root);
2247 retval = cgroup_attach_task(from_cgrp, tsk, false);
2251 mutex_unlock(&cgroup_mutex);
2255 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2257 static int cgroup_tasks_write(struct cgroup_subsys_state *css,
2258 struct cftype *cft, u64 pid)
2260 return attach_task_by_pid(css->cgroup, pid, false);
2263 static int cgroup_procs_write(struct cgroup_subsys_state *css,
2264 struct cftype *cft, u64 tgid)
2266 return attach_task_by_pid(css->cgroup, tgid, true);
2269 static int cgroup_release_agent_write(struct cgroup_subsys_state *css,
2270 struct cftype *cft, const char *buffer)
2272 BUILD_BUG_ON(sizeof(css->cgroup->root->release_agent_path) < PATH_MAX);
2273 if (strlen(buffer) >= PATH_MAX)
2275 if (!cgroup_lock_live_group(css->cgroup))
2277 mutex_lock(&cgroup_root_mutex);
2278 strcpy(css->cgroup->root->release_agent_path, buffer);
2279 mutex_unlock(&cgroup_root_mutex);
2280 mutex_unlock(&cgroup_mutex);
2284 static int cgroup_release_agent_show(struct cgroup_subsys_state *css,
2285 struct cftype *cft, struct seq_file *seq)
2287 struct cgroup *cgrp = css->cgroup;
2289 if (!cgroup_lock_live_group(cgrp))
2291 seq_puts(seq, cgrp->root->release_agent_path);
2292 seq_putc(seq, '\n');
2293 mutex_unlock(&cgroup_mutex);
2297 static int cgroup_sane_behavior_show(struct cgroup_subsys_state *css,
2298 struct cftype *cft, struct seq_file *seq)
2300 seq_printf(seq, "%d\n", cgroup_sane_behavior(css->cgroup));
2304 /* return the css for the given cgroup file */
2305 static struct cgroup_subsys_state *cgroup_file_css(struct cfent *cfe)
2307 struct cftype *cft = cfe->type;
2308 struct cgroup *cgrp = __d_cgrp(cfe->dentry->d_parent);
2311 return cgrp->subsys[cft->ss->subsys_id];
2312 return &cgrp->dummy_css;
2315 /* A buffer size big enough for numbers or short strings */
2316 #define CGROUP_LOCAL_BUFFER_SIZE 64
2318 static ssize_t cgroup_write_X64(struct cgroup_subsys_state *css,
2319 struct cftype *cft, struct file *file,
2320 const char __user *userbuf, size_t nbytes,
2321 loff_t *unused_ppos)
2323 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
2329 if (nbytes >= sizeof(buffer))
2331 if (copy_from_user(buffer, userbuf, nbytes))
2334 buffer[nbytes] = 0; /* nul-terminate */
2335 if (cft->write_u64) {
2336 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
2339 retval = cft->write_u64(css, cft, val);
2341 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
2344 retval = cft->write_s64(css, cft, val);
2351 static ssize_t cgroup_write_string(struct cgroup_subsys_state *css,
2352 struct cftype *cft, struct file *file,
2353 const char __user *userbuf, size_t nbytes,
2354 loff_t *unused_ppos)
2356 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
2358 size_t max_bytes = cft->max_write_len;
2359 char *buffer = local_buffer;
2362 max_bytes = sizeof(local_buffer) - 1;
2363 if (nbytes >= max_bytes)
2365 /* Allocate a dynamic buffer if we need one */
2366 if (nbytes >= sizeof(local_buffer)) {
2367 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2371 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2376 buffer[nbytes] = 0; /* nul-terminate */
2377 retval = cft->write_string(css, cft, strstrip(buffer));
2381 if (buffer != local_buffer)
2386 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2387 size_t nbytes, loff_t *ppos)
2389 struct cfent *cfe = __d_cfe(file->f_dentry);
2390 struct cftype *cft = __d_cft(file->f_dentry);
2391 struct cgroup_subsys_state *css = cgroup_file_css(cfe);
2394 return cft->write(css, cft, file, buf, nbytes, ppos);
2395 if (cft->write_u64 || cft->write_s64)
2396 return cgroup_write_X64(css, cft, file, buf, nbytes, ppos);
2397 if (cft->write_string)
2398 return cgroup_write_string(css, cft, file, buf, nbytes, ppos);
2400 int ret = cft->trigger(css, (unsigned int)cft->private);
2401 return ret ? ret : nbytes;
2406 static ssize_t cgroup_read_u64(struct cgroup_subsys_state *css,
2407 struct cftype *cft, struct file *file,
2408 char __user *buf, size_t nbytes, loff_t *ppos)
2410 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2411 u64 val = cft->read_u64(css, cft);
2412 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2414 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2417 static ssize_t cgroup_read_s64(struct cgroup_subsys_state *css,
2418 struct cftype *cft, struct file *file,
2419 char __user *buf, size_t nbytes, loff_t *ppos)
2421 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2422 s64 val = cft->read_s64(css, cft);
2423 int len = sprintf(tmp, "%lld\n", (long long) val);
2425 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2428 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2429 size_t nbytes, loff_t *ppos)
2431 struct cfent *cfe = __d_cfe(file->f_dentry);
2432 struct cftype *cft = __d_cft(file->f_dentry);
2433 struct cgroup_subsys_state *css = cgroup_file_css(cfe);
2436 return cft->read(css, cft, file, buf, nbytes, ppos);
2438 return cgroup_read_u64(css, cft, file, buf, nbytes, ppos);
2440 return cgroup_read_s64(css, cft, file, buf, nbytes, ppos);
2445 * seqfile ops/methods for returning structured data. Currently just
2446 * supports string->u64 maps, but can be extended in future.
2449 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2451 struct seq_file *sf = cb->state;
2452 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2455 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2457 struct cfent *cfe = m->private;
2458 struct cftype *cft = cfe->type;
2459 struct cgroup_subsys_state *css = cgroup_file_css(cfe);
2461 if (cft->read_map) {
2462 struct cgroup_map_cb cb = {
2463 .fill = cgroup_map_add,
2466 return cft->read_map(css, cft, &cb);
2468 return cft->read_seq_string(css, cft, m);
2471 static const struct file_operations cgroup_seqfile_operations = {
2473 .write = cgroup_file_write,
2474 .llseek = seq_lseek,
2475 .release = single_release,
2478 static int cgroup_file_open(struct inode *inode, struct file *file)
2480 struct cfent *cfe = __d_cfe(file->f_dentry);
2481 struct cftype *cft = __d_cft(file->f_dentry);
2482 struct cgroup_subsys_state *css = cgroup_file_css(cfe);
2485 err = generic_file_open(inode, file);
2490 * If the file belongs to a subsystem, pin the css. Will be
2491 * unpinned either on open failure or release. This ensures that
2492 * @css stays alive for all file operations.
2494 if (css->ss && !css_tryget(css))
2497 if (cft->read_map || cft->read_seq_string) {
2498 file->f_op = &cgroup_seqfile_operations;
2499 err = single_open(file, cgroup_seqfile_show, cfe);
2500 } else if (cft->open) {
2501 err = cft->open(inode, file);
2509 static int cgroup_file_release(struct inode *inode, struct file *file)
2511 struct cfent *cfe = __d_cfe(file->f_dentry);
2512 struct cftype *cft = __d_cft(file->f_dentry);
2513 struct cgroup_subsys_state *css = cgroup_file_css(cfe);
2517 ret = cft->release(inode, file);
2524 * cgroup_rename - Only allow simple rename of directories in place.
2526 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2527 struct inode *new_dir, struct dentry *new_dentry)
2530 struct cgroup_name *name, *old_name;
2531 struct cgroup *cgrp;
2534 * It's convinient to use parent dir's i_mutex to protected
2537 lockdep_assert_held(&old_dir->i_mutex);
2539 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2541 if (new_dentry->d_inode)
2543 if (old_dir != new_dir)
2546 cgrp = __d_cgrp(old_dentry);
2549 * This isn't a proper migration and its usefulness is very
2550 * limited. Disallow if sane_behavior.
2552 if (cgroup_sane_behavior(cgrp))
2555 name = cgroup_alloc_name(new_dentry);
2559 ret = simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2565 old_name = rcu_dereference_protected(cgrp->name, true);
2566 rcu_assign_pointer(cgrp->name, name);
2568 kfree_rcu(old_name, rcu_head);
2572 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2574 if (S_ISDIR(dentry->d_inode->i_mode))
2575 return &__d_cgrp(dentry)->xattrs;
2577 return &__d_cfe(dentry)->xattrs;
2580 static inline int xattr_enabled(struct dentry *dentry)
2582 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2583 return root->flags & CGRP_ROOT_XATTR;
2586 static bool is_valid_xattr(const char *name)
2588 if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2589 !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2594 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2595 const void *val, size_t size, int flags)
2597 if (!xattr_enabled(dentry))
2599 if (!is_valid_xattr(name))
2601 return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2604 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2606 if (!xattr_enabled(dentry))
2608 if (!is_valid_xattr(name))
2610 return simple_xattr_remove(__d_xattrs(dentry), name);
2613 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2614 void *buf, size_t size)
2616 if (!xattr_enabled(dentry))
2618 if (!is_valid_xattr(name))
2620 return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2623 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2625 if (!xattr_enabled(dentry))
2627 return simple_xattr_list(__d_xattrs(dentry), buf, size);
2630 static const struct file_operations cgroup_file_operations = {
2631 .read = cgroup_file_read,
2632 .write = cgroup_file_write,
2633 .llseek = generic_file_llseek,
2634 .open = cgroup_file_open,
2635 .release = cgroup_file_release,
2638 static const struct inode_operations cgroup_file_inode_operations = {
2639 .setxattr = cgroup_setxattr,
2640 .getxattr = cgroup_getxattr,
2641 .listxattr = cgroup_listxattr,
2642 .removexattr = cgroup_removexattr,
2645 static const struct inode_operations cgroup_dir_inode_operations = {
2646 .lookup = cgroup_lookup,
2647 .mkdir = cgroup_mkdir,
2648 .rmdir = cgroup_rmdir,
2649 .rename = cgroup_rename,
2650 .setxattr = cgroup_setxattr,
2651 .getxattr = cgroup_getxattr,
2652 .listxattr = cgroup_listxattr,
2653 .removexattr = cgroup_removexattr,
2656 static struct dentry *cgroup_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
2658 if (dentry->d_name.len > NAME_MAX)
2659 return ERR_PTR(-ENAMETOOLONG);
2660 d_add(dentry, NULL);
2665 * Check if a file is a control file
2667 static inline struct cftype *__file_cft(struct file *file)
2669 if (file_inode(file)->i_fop != &cgroup_file_operations)
2670 return ERR_PTR(-EINVAL);
2671 return __d_cft(file->f_dentry);
2674 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2675 struct super_block *sb)
2677 struct inode *inode;
2681 if (dentry->d_inode)
2684 inode = cgroup_new_inode(mode, sb);
2688 if (S_ISDIR(mode)) {
2689 inode->i_op = &cgroup_dir_inode_operations;
2690 inode->i_fop = &simple_dir_operations;
2692 /* start off with i_nlink == 2 (for "." entry) */
2694 inc_nlink(dentry->d_parent->d_inode);
2697 * Control reaches here with cgroup_mutex held.
2698 * @inode->i_mutex should nest outside cgroup_mutex but we
2699 * want to populate it immediately without releasing
2700 * cgroup_mutex. As @inode isn't visible to anyone else
2701 * yet, trylock will always succeed without affecting
2704 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2705 } else if (S_ISREG(mode)) {
2707 inode->i_fop = &cgroup_file_operations;
2708 inode->i_op = &cgroup_file_inode_operations;
2710 d_instantiate(dentry, inode);
2711 dget(dentry); /* Extra count - pin the dentry in core */
2716 * cgroup_file_mode - deduce file mode of a control file
2717 * @cft: the control file in question
2719 * returns cft->mode if ->mode is not 0
2720 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2721 * returns S_IRUGO if it has only a read handler
2722 * returns S_IWUSR if it has only a write hander
2724 static umode_t cgroup_file_mode(const struct cftype *cft)
2731 if (cft->read || cft->read_u64 || cft->read_s64 ||
2732 cft->read_map || cft->read_seq_string)
2735 if (cft->write || cft->write_u64 || cft->write_s64 ||
2736 cft->write_string || cft->trigger)
2742 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2744 struct dentry *dir = cgrp->dentry;
2745 struct cgroup *parent = __d_cgrp(dir);
2746 struct dentry *dentry;
2750 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2752 if (cft->ss && !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
2753 strcpy(name, cft->ss->name);
2756 strcat(name, cft->name);
2758 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2760 cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2764 dentry = lookup_one_len(name, dir, strlen(name));
2765 if (IS_ERR(dentry)) {
2766 error = PTR_ERR(dentry);
2770 cfe->type = (void *)cft;
2771 cfe->dentry = dentry;
2772 dentry->d_fsdata = cfe;
2773 simple_xattrs_init(&cfe->xattrs);
2775 mode = cgroup_file_mode(cft);
2776 error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2778 list_add_tail(&cfe->node, &parent->files);
2788 * cgroup_addrm_files - add or remove files to a cgroup directory
2789 * @cgrp: the target cgroup
2790 * @cfts: array of cftypes to be added
2791 * @is_add: whether to add or remove
2793 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2794 * For removals, this function never fails. If addition fails, this
2795 * function doesn't remove files already added. The caller is responsible
2798 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2804 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
2805 lockdep_assert_held(&cgroup_mutex);
2807 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2808 /* does cft->flags tell us to skip this file on @cgrp? */
2809 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2811 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2813 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2817 ret = cgroup_add_file(cgrp, cft);
2819 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2824 cgroup_rm_file(cgrp, cft);
2830 static void cgroup_cfts_prepare(void)
2831 __acquires(&cgroup_mutex)
2834 * Thanks to the entanglement with vfs inode locking, we can't walk
2835 * the existing cgroups under cgroup_mutex and create files.
2836 * Instead, we use css_for_each_descendant_pre() and drop RCU read
2837 * lock before calling cgroup_addrm_files().
2839 mutex_lock(&cgroup_mutex);
2842 static int cgroup_cfts_commit(struct cftype *cfts, bool is_add)
2843 __releases(&cgroup_mutex)
2846 struct cgroup_subsys *ss = cfts[0].ss;
2847 struct cgroup *root = &ss->root->top_cgroup;
2848 struct super_block *sb = ss->root->sb;
2849 struct dentry *prev = NULL;
2850 struct inode *inode;
2851 struct cgroup_subsys_state *css;
2855 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2856 if (!cfts || ss->root == &cgroup_dummy_root ||
2857 !atomic_inc_not_zero(&sb->s_active)) {
2858 mutex_unlock(&cgroup_mutex);
2863 * All cgroups which are created after we drop cgroup_mutex will
2864 * have the updated set of files, so we only need to update the
2865 * cgroups created before the current @cgroup_serial_nr_next.
2867 update_before = cgroup_serial_nr_next;
2869 mutex_unlock(&cgroup_mutex);
2871 /* add/rm files for all cgroups created before */
2873 css_for_each_descendant_pre(css, cgroup_css(root, ss->subsys_id)) {
2874 struct cgroup *cgrp = css->cgroup;
2876 if (cgroup_is_dead(cgrp))
2879 inode = cgrp->dentry->d_inode;
2884 prev = cgrp->dentry;
2886 mutex_lock(&inode->i_mutex);
2887 mutex_lock(&cgroup_mutex);
2888 if (cgrp->serial_nr < update_before && !cgroup_is_dead(cgrp))
2889 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2890 mutex_unlock(&cgroup_mutex);
2891 mutex_unlock(&inode->i_mutex);
2899 deactivate_super(sb);
2904 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2905 * @ss: target cgroup subsystem
2906 * @cfts: zero-length name terminated array of cftypes
2908 * Register @cfts to @ss. Files described by @cfts are created for all
2909 * existing cgroups to which @ss is attached and all future cgroups will
2910 * have them too. This function can be called anytime whether @ss is
2913 * Returns 0 on successful registration, -errno on failure. Note that this
2914 * function currently returns 0 as long as @cfts registration is successful
2915 * even if some file creation attempts on existing cgroups fail.
2917 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2919 struct cftype_set *set;
2923 set = kzalloc(sizeof(*set), GFP_KERNEL);
2927 for (cft = cfts; cft->name[0] != '\0'; cft++)
2930 cgroup_cfts_prepare();
2932 list_add_tail(&set->node, &ss->cftsets);
2933 ret = cgroup_cfts_commit(cfts, true);
2935 cgroup_rm_cftypes(cfts);
2938 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2941 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2942 * @cfts: zero-length name terminated array of cftypes
2944 * Unregister @cfts. Files described by @cfts are removed from all
2945 * existing cgroups and all future cgroups won't have them either. This
2946 * function can be called anytime whether @cfts' subsys is attached or not.
2948 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2951 int cgroup_rm_cftypes(struct cftype *cfts)
2953 struct cftype_set *set;
2955 if (!cfts || !cfts[0].ss)
2958 cgroup_cfts_prepare();
2960 list_for_each_entry(set, &cfts[0].ss->cftsets, node) {
2961 if (set->cfts == cfts) {
2962 list_del(&set->node);
2964 cgroup_cfts_commit(cfts, false);
2969 cgroup_cfts_commit(NULL, false);
2974 * cgroup_task_count - count the number of tasks in a cgroup.
2975 * @cgrp: the cgroup in question
2977 * Return the number of tasks in the cgroup.
2979 int cgroup_task_count(const struct cgroup *cgrp)
2982 struct cgrp_cset_link *link;
2984 read_lock(&css_set_lock);
2985 list_for_each_entry(link, &cgrp->cset_links, cset_link)
2986 count += atomic_read(&link->cset->refcount);
2987 read_unlock(&css_set_lock);
2992 * To reduce the fork() overhead for systems that are not actually using
2993 * their cgroups capability, we don't maintain the lists running through
2994 * each css_set to its tasks until we see the list actually used - in other
2995 * words after the first call to css_task_iter_start().
2997 static void cgroup_enable_task_cg_lists(void)
2999 struct task_struct *p, *g;
3000 write_lock(&css_set_lock);
3001 use_task_css_set_links = 1;
3003 * We need tasklist_lock because RCU is not safe against
3004 * while_each_thread(). Besides, a forking task that has passed
3005 * cgroup_post_fork() without seeing use_task_css_set_links = 1
3006 * is not guaranteed to have its child immediately visible in the
3007 * tasklist if we walk through it with RCU.
3009 read_lock(&tasklist_lock);
3010 do_each_thread(g, p) {
3013 * We should check if the process is exiting, otherwise
3014 * it will race with cgroup_exit() in that the list
3015 * entry won't be deleted though the process has exited.
3017 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
3018 list_add(&p->cg_list, &task_css_set(p)->tasks);
3020 } while_each_thread(g, p);
3021 read_unlock(&tasklist_lock);
3022 write_unlock(&css_set_lock);
3026 * css_next_child - find the next child of a given css
3027 * @pos_css: the current position (%NULL to initiate traversal)
3028 * @parent_css: css whose children to walk
3030 * This function returns the next child of @parent_css and should be called
3031 * under RCU read lock. The only requirement is that @parent_css and
3032 * @pos_css are accessible. The next sibling is guaranteed to be returned
3033 * regardless of their states.
3035 struct cgroup_subsys_state *
3036 css_next_child(struct cgroup_subsys_state *pos_css,
3037 struct cgroup_subsys_state *parent_css)
3039 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
3040 struct cgroup *cgrp = parent_css->cgroup;
3041 struct cgroup *next;
3043 WARN_ON_ONCE(!rcu_read_lock_held());
3046 * @pos could already have been removed. Once a cgroup is removed,
3047 * its ->sibling.next is no longer updated when its next sibling
3048 * changes. As CGRP_DEAD assertion is serialized and happens
3049 * before the cgroup is taken off the ->sibling list, if we see it
3050 * unasserted, it's guaranteed that the next sibling hasn't
3051 * finished its grace period even if it's already removed, and thus
3052 * safe to dereference from this RCU critical section. If
3053 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
3054 * to be visible as %true here.
3056 * If @pos is dead, its next pointer can't be dereferenced;
3057 * however, as each cgroup is given a monotonically increasing
3058 * unique serial number and always appended to the sibling list,
3059 * the next one can be found by walking the parent's children until
3060 * we see a cgroup with higher serial number than @pos's. While
3061 * this path can be slower, it's taken only when either the current
3062 * cgroup is removed or iteration and removal race.
3065 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
3066 } else if (likely(!cgroup_is_dead(pos))) {
3067 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3069 list_for_each_entry_rcu(next, &cgrp->children, sibling)
3070 if (next->serial_nr > pos->serial_nr)
3074 if (&next->sibling == &cgrp->children)
3078 return cgroup_css(next, parent_css->ss->subsys_id);
3080 return &next->dummy_css;
3082 EXPORT_SYMBOL_GPL(css_next_child);
3085 * css_next_descendant_pre - find the next descendant for pre-order walk
3086 * @pos: the current position (%NULL to initiate traversal)
3087 * @root: css whose descendants to walk
3089 * To be used by css_for_each_descendant_pre(). Find the next descendant
3090 * to visit for pre-order traversal of @root's descendants. @root is
3091 * included in the iteration and the first node to be visited.
3093 * While this function requires RCU read locking, it doesn't require the
3094 * whole traversal to be contained in a single RCU critical section. This
3095 * function will return the correct next descendant as long as both @pos
3096 * and @root are accessible and @pos is a descendant of @root.
3098 struct cgroup_subsys_state *
3099 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3100 struct cgroup_subsys_state *root)
3102 struct cgroup_subsys_state *next;
3104 WARN_ON_ONCE(!rcu_read_lock_held());
3106 /* if first iteration, visit @root */
3110 /* visit the first child if exists */
3111 next = css_next_child(NULL, pos);
3115 /* no child, visit my or the closest ancestor's next sibling */
3116 while (pos != root) {
3117 next = css_next_child(pos, css_parent(pos));
3120 pos = css_parent(pos);
3125 EXPORT_SYMBOL_GPL(css_next_descendant_pre);
3128 * css_rightmost_descendant - return the rightmost descendant of a css
3129 * @pos: css of interest
3131 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3132 * is returned. This can be used during pre-order traversal to skip
3135 * While this function requires RCU read locking, it doesn't require the
3136 * whole traversal to be contained in a single RCU critical section. This
3137 * function will return the correct rightmost descendant as long as @pos is
3140 struct cgroup_subsys_state *
3141 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3143 struct cgroup_subsys_state *last, *tmp;
3145 WARN_ON_ONCE(!rcu_read_lock_held());
3149 /* ->prev isn't RCU safe, walk ->next till the end */
3151 css_for_each_child(tmp, last)
3157 EXPORT_SYMBOL_GPL(css_rightmost_descendant);
3159 static struct cgroup_subsys_state *
3160 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3162 struct cgroup_subsys_state *last;
3166 pos = css_next_child(NULL, pos);
3173 * css_next_descendant_post - find the next descendant for post-order walk
3174 * @pos: the current position (%NULL to initiate traversal)
3175 * @root: css whose descendants to walk
3177 * To be used by css_for_each_descendant_post(). Find the next descendant
3178 * to visit for post-order traversal of @root's descendants. @root is
3179 * included in the iteration and the last node to be visited.
3181 * While this function requires RCU read locking, it doesn't require the
3182 * whole traversal to be contained in a single RCU critical section. This
3183 * function will return the correct next descendant as long as both @pos
3184 * and @cgroup are accessible and @pos is a descendant of @cgroup.
3186 struct cgroup_subsys_state *
3187 css_next_descendant_post(struct cgroup_subsys_state *pos,
3188 struct cgroup_subsys_state *root)
3190 struct cgroup_subsys_state *next;
3192 WARN_ON_ONCE(!rcu_read_lock_held());
3194 /* if first iteration, visit the leftmost descendant */
3196 next = css_leftmost_descendant(root);
3197 return next != root ? next : NULL;
3200 /* if we visited @root, we're done */
3204 /* if there's an unvisited sibling, visit its leftmost descendant */
3205 next = css_next_child(pos, css_parent(pos));
3207 return css_leftmost_descendant(next);
3209 /* no sibling left, visit parent */
3210 return css_parent(pos);
3212 EXPORT_SYMBOL_GPL(css_next_descendant_post);
3215 * css_advance_task_iter - advance a task itererator to the next css_set
3216 * @it: the iterator to advance
3218 * Advance @it to the next css_set to walk.
3220 static void css_advance_task_iter(struct css_task_iter *it)
3222 struct list_head *l = it->cset_link;
3223 struct cgrp_cset_link *link;
3224 struct css_set *cset;
3226 /* Advance to the next non-empty css_set */
3229 if (l == &it->origin_css->cgroup->cset_links) {
3230 it->cset_link = NULL;
3233 link = list_entry(l, struct cgrp_cset_link, cset_link);
3235 } while (list_empty(&cset->tasks));
3237 it->task = cset->tasks.next;
3241 * css_task_iter_start - initiate task iteration
3242 * @css: the css to walk tasks of
3243 * @it: the task iterator to use
3245 * Initiate iteration through the tasks of @css. The caller can call
3246 * css_task_iter_next() to walk through the tasks until the function
3247 * returns NULL. On completion of iteration, css_task_iter_end() must be
3250 * Note that this function acquires a lock which is released when the
3251 * iteration finishes. The caller can't sleep while iteration is in
3254 void css_task_iter_start(struct cgroup_subsys_state *css,
3255 struct css_task_iter *it)
3256 __acquires(css_set_lock)
3259 * The first time anyone tries to iterate across a css, we need to
3260 * enable the list linking each css_set to its tasks, and fix up
3261 * all existing tasks.
3263 if (!use_task_css_set_links)
3264 cgroup_enable_task_cg_lists();
3266 read_lock(&css_set_lock);
3268 it->origin_css = css;
3269 it->cset_link = &css->cgroup->cset_links;
3271 css_advance_task_iter(it);
3275 * css_task_iter_next - return the next task for the iterator
3276 * @it: the task iterator being iterated
3278 * The "next" function for task iteration. @it should have been
3279 * initialized via css_task_iter_start(). Returns NULL when the iteration
3282 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3284 struct task_struct *res;
3285 struct list_head *l = it->task;
3286 struct cgrp_cset_link *link;
3288 /* If the iterator cg is NULL, we have no tasks */
3291 res = list_entry(l, struct task_struct, cg_list);
3292 /* Advance iterator to find next entry */
3294 link = list_entry(it->cset_link, struct cgrp_cset_link, cset_link);
3295 if (l == &link->cset->tasks) {
3297 * We reached the end of this task list - move on to the
3298 * next cgrp_cset_link.
3300 css_advance_task_iter(it);
3308 * css_task_iter_end - finish task iteration
3309 * @it: the task iterator to finish
3311 * Finish task iteration started by css_task_iter_start().
3313 void css_task_iter_end(struct css_task_iter *it)
3314 __releases(css_set_lock)
3316 read_unlock(&css_set_lock);
3319 static inline int started_after_time(struct task_struct *t1,
3320 struct timespec *time,
3321 struct task_struct *t2)
3323 int start_diff = timespec_compare(&t1->start_time, time);
3324 if (start_diff > 0) {
3326 } else if (start_diff < 0) {
3330 * Arbitrarily, if two processes started at the same
3331 * time, we'll say that the lower pointer value
3332 * started first. Note that t2 may have exited by now
3333 * so this may not be a valid pointer any longer, but
3334 * that's fine - it still serves to distinguish
3335 * between two tasks started (effectively) simultaneously.
3342 * This function is a callback from heap_insert() and is used to order
3344 * In this case we order the heap in descending task start time.
3346 static inline int started_after(void *p1, void *p2)
3348 struct task_struct *t1 = p1;
3349 struct task_struct *t2 = p2;
3350 return started_after_time(t1, &t2->start_time, t2);
3354 * css_scan_tasks - iterate though all the tasks in a css
3355 * @css: the css to iterate tasks of
3356 * @test: optional test callback
3357 * @process: process callback
3358 * @data: data passed to @test and @process
3359 * @heap: optional pre-allocated heap used for task iteration
3361 * Iterate through all the tasks in @css, calling @test for each, and if it
3362 * returns %true, call @process for it also.
3364 * @test may be NULL, meaning always true (select all tasks), which
3365 * effectively duplicates css_task_iter_{start,next,end}() but does not
3366 * lock css_set_lock for the call to @process.
3368 * It is guaranteed that @process will act on every task that is a member
3369 * of @css for the duration of this call. This function may or may not
3370 * call @process for tasks that exit or move to a different css during the
3371 * call, or are forked or move into the css during the call.
3373 * Note that @test may be called with locks held, and may in some
3374 * situations be called multiple times for the same task, so it should be
3377 * If @heap is non-NULL, a heap has been pre-allocated and will be used for
3378 * heap operations (and its "gt" member will be overwritten), else a
3379 * temporary heap will be used (allocation of which may cause this function
3382 int css_scan_tasks(struct cgroup_subsys_state *css,
3383 bool (*test)(struct task_struct *, void *),
3384 void (*process)(struct task_struct *, void *),
3385 void *data, struct ptr_heap *heap)
3388 struct css_task_iter it;
3389 struct task_struct *p, *dropped;
3390 /* Never dereference latest_task, since it's not refcounted */
3391 struct task_struct *latest_task = NULL;
3392 struct ptr_heap tmp_heap;
3393 struct timespec latest_time = { 0, 0 };
3396 /* The caller supplied our heap and pre-allocated its memory */
3397 heap->gt = &started_after;
3399 /* We need to allocate our own heap memory */
3401 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3403 /* cannot allocate the heap */
3409 * Scan tasks in the css, using the @test callback to determine
3410 * which are of interest, and invoking @process callback on the
3411 * ones which need an update. Since we don't want to hold any
3412 * locks during the task updates, gather tasks to be processed in a
3413 * heap structure. The heap is sorted by descending task start
3414 * time. If the statically-sized heap fills up, we overflow tasks
3415 * that started later, and in future iterations only consider tasks
3416 * that started after the latest task in the previous pass. This
3417 * guarantees forward progress and that we don't miss any tasks.
3420 css_task_iter_start(css, &it);
3421 while ((p = css_task_iter_next(&it))) {
3423 * Only affect tasks that qualify per the caller's callback,
3424 * if he provided one
3426 if (test && !test(p, data))
3429 * Only process tasks that started after the last task
3432 if (!started_after_time(p, &latest_time, latest_task))
3434 dropped = heap_insert(heap, p);
3435 if (dropped == NULL) {
3437 * The new task was inserted; the heap wasn't
3441 } else if (dropped != p) {
3443 * The new task was inserted, and pushed out a
3447 put_task_struct(dropped);
3450 * Else the new task was newer than anything already in
3451 * the heap and wasn't inserted
3454 css_task_iter_end(&it);
3457 for (i = 0; i < heap->size; i++) {
3458 struct task_struct *q = heap->ptrs[i];
3460 latest_time = q->start_time;
3463 /* Process the task per the caller's callback */
3468 * If we had to process any tasks at all, scan again
3469 * in case some of them were in the middle of forking
3470 * children that didn't get processed.
3471 * Not the most efficient way to do it, but it avoids
3472 * having to take callback_mutex in the fork path
3476 if (heap == &tmp_heap)
3477 heap_free(&tmp_heap);
3481 static void cgroup_transfer_one_task(struct task_struct *task, void *data)
3483 struct cgroup *new_cgroup = data;
3485 mutex_lock(&cgroup_mutex);
3486 cgroup_attach_task(new_cgroup, task, false);
3487 mutex_unlock(&cgroup_mutex);
3491 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3492 * @to: cgroup to which the tasks will be moved
3493 * @from: cgroup in which the tasks currently reside
3495 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3497 return css_scan_tasks(&from->dummy_css, NULL, cgroup_transfer_one_task,
3502 * Stuff for reading the 'tasks'/'procs' files.
3504 * Reading this file can return large amounts of data if a cgroup has
3505 * *lots* of attached tasks. So it may need several calls to read(),
3506 * but we cannot guarantee that the information we produce is correct
3507 * unless we produce it entirely atomically.
3511 /* which pidlist file are we talking about? */
3512 enum cgroup_filetype {
3518 * A pidlist is a list of pids that virtually represents the contents of one
3519 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3520 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3523 struct cgroup_pidlist {
3525 * used to find which pidlist is wanted. doesn't change as long as
3526 * this particular list stays in the list.
3528 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3531 /* how many elements the above list has */
3533 /* how many files are using the current array */
3535 /* each of these stored in a list by its cgroup */
3536 struct list_head links;
3537 /* pointer to the cgroup we belong to, for list removal purposes */
3538 struct cgroup *owner;
3539 /* protects the other fields */
3540 struct rw_semaphore rwsem;
3544 * The following two functions "fix" the issue where there are more pids
3545 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3546 * TODO: replace with a kernel-wide solution to this problem
3548 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3549 static void *pidlist_allocate(int count)
3551 if (PIDLIST_TOO_LARGE(count))
3552 return vmalloc(count * sizeof(pid_t));
3554 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3556 static void pidlist_free(void *p)
3558 if (is_vmalloc_addr(p))
3565 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3566 * Returns the number of unique elements.
3568 static int pidlist_uniq(pid_t *list, int length)
3573 * we presume the 0th element is unique, so i starts at 1. trivial
3574 * edge cases first; no work needs to be done for either
3576 if (length == 0 || length == 1)
3578 /* src and dest walk down the list; dest counts unique elements */
3579 for (src = 1; src < length; src++) {
3580 /* find next unique element */
3581 while (list[src] == list[src-1]) {
3586 /* dest always points to where the next unique element goes */
3587 list[dest] = list[src];
3594 static int cmppid(const void *a, const void *b)
3596 return *(pid_t *)a - *(pid_t *)b;
3600 * find the appropriate pidlist for our purpose (given procs vs tasks)
3601 * returns with the lock on that pidlist already held, and takes care
3602 * of the use count, or returns NULL with no locks held if we're out of
3605 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3606 enum cgroup_filetype type)
3608 struct cgroup_pidlist *l;
3609 /* don't need task_nsproxy() if we're looking at ourself */
3610 struct pid_namespace *ns = task_active_pid_ns(current);
3613 * We can't drop the pidlist_mutex before taking the l->rwsem in case
3614 * the last ref-holder is trying to remove l from the list at the same
3615 * time. Holding the pidlist_mutex precludes somebody taking whichever
3616 * list we find out from under us - compare release_pid_array().
3618 mutex_lock(&cgrp->pidlist_mutex);
3619 list_for_each_entry(l, &cgrp->pidlists, links) {
3620 if (l->key.type == type && l->key.ns == ns) {
3621 /* make sure l doesn't vanish out from under us */
3622 down_write(&l->rwsem);
3623 mutex_unlock(&cgrp->pidlist_mutex);
3627 /* entry not found; create a new one */
3628 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3630 mutex_unlock(&cgrp->pidlist_mutex);
3633 init_rwsem(&l->rwsem);
3634 down_write(&l->rwsem);
3636 l->key.ns = get_pid_ns(ns);
3638 list_add(&l->links, &cgrp->pidlists);
3639 mutex_unlock(&cgrp->pidlist_mutex);
3644 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3646 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3647 struct cgroup_pidlist **lp)
3651 int pid, n = 0; /* used for populating the array */
3652 struct css_task_iter it;
3653 struct task_struct *tsk;
3654 struct cgroup_pidlist *l;
3657 * If cgroup gets more users after we read count, we won't have
3658 * enough space - tough. This race is indistinguishable to the
3659 * caller from the case that the additional cgroup users didn't
3660 * show up until sometime later on.
3662 length = cgroup_task_count(cgrp);
3663 array = pidlist_allocate(length);
3666 /* now, populate the array */
3667 css_task_iter_start(&cgrp->dummy_css, &it);
3668 while ((tsk = css_task_iter_next(&it))) {
3669 if (unlikely(n == length))
3671 /* get tgid or pid for procs or tasks file respectively */
3672 if (type == CGROUP_FILE_PROCS)
3673 pid = task_tgid_vnr(tsk);
3675 pid = task_pid_vnr(tsk);
3676 if (pid > 0) /* make sure to only use valid results */
3679 css_task_iter_end(&it);
3681 /* now sort & (if procs) strip out duplicates */
3682 sort(array, length, sizeof(pid_t), cmppid, NULL);
3683 if (type == CGROUP_FILE_PROCS)
3684 length = pidlist_uniq(array, length);
3685 l = cgroup_pidlist_find(cgrp, type);
3687 pidlist_free(array);
3690 /* store array, freeing old if necessary - lock already held */
3691 pidlist_free(l->list);
3695 up_write(&l->rwsem);
3701 * cgroupstats_build - build and fill cgroupstats
3702 * @stats: cgroupstats to fill information into
3703 * @dentry: A dentry entry belonging to the cgroup for which stats have
3706 * Build and fill cgroupstats so that taskstats can export it to user
3709 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3712 struct cgroup *cgrp;
3713 struct css_task_iter it;
3714 struct task_struct *tsk;
3717 * Validate dentry by checking the superblock operations,
3718 * and make sure it's a directory.
3720 if (dentry->d_sb->s_op != &cgroup_ops ||
3721 !S_ISDIR(dentry->d_inode->i_mode))
3725 cgrp = dentry->d_fsdata;
3727 css_task_iter_start(&cgrp->dummy_css, &it);
3728 while ((tsk = css_task_iter_next(&it))) {
3729 switch (tsk->state) {
3731 stats->nr_running++;
3733 case TASK_INTERRUPTIBLE:
3734 stats->nr_sleeping++;
3736 case TASK_UNINTERRUPTIBLE:
3737 stats->nr_uninterruptible++;
3740 stats->nr_stopped++;
3743 if (delayacct_is_task_waiting_on_io(tsk))
3744 stats->nr_io_wait++;
3748 css_task_iter_end(&it);
3756 * seq_file methods for the tasks/procs files. The seq_file position is the
3757 * next pid to display; the seq_file iterator is a pointer to the pid
3758 * in the cgroup->l->list array.
3761 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3764 * Initially we receive a position value that corresponds to
3765 * one more than the last pid shown (or 0 on the first call or
3766 * after a seek to the start). Use a binary-search to find the
3767 * next pid to display, if any
3769 struct cgroup_pidlist *l = s->private;
3770 int index = 0, pid = *pos;
3773 down_read(&l->rwsem);
3775 int end = l->length;
3777 while (index < end) {
3778 int mid = (index + end) / 2;
3779 if (l->list[mid] == pid) {
3782 } else if (l->list[mid] <= pid)
3788 /* If we're off the end of the array, we're done */
3789 if (index >= l->length)
3791 /* Update the abstract position to be the actual pid that we found */
3792 iter = l->list + index;
3797 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3799 struct cgroup_pidlist *l = s->private;
3803 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3805 struct cgroup_pidlist *l = s->private;
3807 pid_t *end = l->list + l->length;
3809 * Advance to the next pid in the array. If this goes off the
3821 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3823 return seq_printf(s, "%d\n", *(int *)v);
3827 * seq_operations functions for iterating on pidlists through seq_file -
3828 * independent of whether it's tasks or procs
3830 static const struct seq_operations cgroup_pidlist_seq_operations = {
3831 .start = cgroup_pidlist_start,
3832 .stop = cgroup_pidlist_stop,
3833 .next = cgroup_pidlist_next,
3834 .show = cgroup_pidlist_show,
3837 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
3840 * the case where we're the last user of this particular pidlist will
3841 * have us remove it from the cgroup's list, which entails taking the
3842 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3843 * pidlist_mutex, we have to take pidlist_mutex first.
3845 mutex_lock(&l->owner->pidlist_mutex);
3846 down_write(&l->rwsem);
3847 BUG_ON(!l->use_count);
3848 if (!--l->use_count) {
3849 /* we're the last user if refcount is 0; remove and free */
3850 list_del(&l->links);
3851 mutex_unlock(&l->owner->pidlist_mutex);
3852 pidlist_free(l->list);
3853 put_pid_ns(l->key.ns);
3854 up_write(&l->rwsem);
3858 mutex_unlock(&l->owner->pidlist_mutex);
3859 up_write(&l->rwsem);
3862 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
3864 struct cgroup_pidlist *l;
3865 if (!(file->f_mode & FMODE_READ))
3868 * the seq_file will only be initialized if the file was opened for
3869 * reading; hence we check if it's not null only in that case.
3871 l = ((struct seq_file *)file->private_data)->private;
3872 cgroup_release_pid_array(l);
3873 return seq_release(inode, file);
3876 static const struct file_operations cgroup_pidlist_operations = {
3878 .llseek = seq_lseek,
3879 .write = cgroup_file_write,
3880 .release = cgroup_pidlist_release,
3884 * The following functions handle opens on a file that displays a pidlist
3885 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3888 /* helper function for the two below it */
3889 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
3891 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
3892 struct cgroup_pidlist *l;
3895 /* Nothing to do for write-only files */
3896 if (!(file->f_mode & FMODE_READ))
3899 /* have the array populated */
3900 retval = pidlist_array_load(cgrp, type, &l);
3903 /* configure file information */
3904 file->f_op = &cgroup_pidlist_operations;
3906 retval = seq_open(file, &cgroup_pidlist_seq_operations);
3908 cgroup_release_pid_array(l);
3911 ((struct seq_file *)file->private_data)->private = l;
3914 static int cgroup_tasks_open(struct inode *unused, struct file *file)
3916 return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
3918 static int cgroup_procs_open(struct inode *unused, struct file *file)
3920 return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
3923 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3926 return notify_on_release(css->cgroup);
3929 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3930 struct cftype *cft, u64 val)
3932 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3934 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3936 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3941 * When dput() is called asynchronously, if umount has been done and
3942 * then deactivate_super() in cgroup_free_fn() kills the superblock,
3943 * there's a small window that vfs will see the root dentry with non-zero
3944 * refcnt and trigger BUG().
3946 * That's why we hold a reference before dput() and drop it right after.
3948 static void cgroup_dput(struct cgroup *cgrp)
3950 struct super_block *sb = cgrp->root->sb;
3952 atomic_inc(&sb->s_active);
3954 deactivate_super(sb);
3958 * Unregister event and free resources.
3960 * Gets called from workqueue.
3962 static void cgroup_event_remove(struct work_struct *work)
3964 struct cgroup_event *event = container_of(work, struct cgroup_event,
3966 struct cgroup_subsys_state *css = event->css;
3967 struct cgroup *cgrp = css->cgroup;
3969 remove_wait_queue(event->wqh, &event->wait);
3971 event->cft->unregister_event(css, event->cft, event->eventfd);
3973 /* Notify userspace the event is going away. */
3974 eventfd_signal(event->eventfd, 1);
3976 eventfd_ctx_put(event->eventfd);
3982 * Gets called on POLLHUP on eventfd when user closes it.
3984 * Called with wqh->lock held and interrupts disabled.
3986 static int cgroup_event_wake(wait_queue_t *wait, unsigned mode,
3987 int sync, void *key)
3989 struct cgroup_event *event = container_of(wait,
3990 struct cgroup_event, wait);
3991 struct cgroup *cgrp = event->css->cgroup;
3992 unsigned long flags = (unsigned long)key;
3994 if (flags & POLLHUP) {
3996 * If the event has been detached at cgroup removal, we
3997 * can simply return knowing the other side will cleanup
4000 * We can't race against event freeing since the other
4001 * side will require wqh->lock via remove_wait_queue(),
4004 spin_lock(&cgrp->event_list_lock);
4005 if (!list_empty(&event->list)) {
4006 list_del_init(&event->list);
4008 * We are in atomic context, but cgroup_event_remove()
4009 * may sleep, so we have to call it in workqueue.
4011 schedule_work(&event->remove);
4013 spin_unlock(&cgrp->event_list_lock);
4019 static void cgroup_event_ptable_queue_proc(struct file *file,
4020 wait_queue_head_t *wqh, poll_table *pt)
4022 struct cgroup_event *event = container_of(pt,
4023 struct cgroup_event, pt);
4026 add_wait_queue(wqh, &event->wait);
4030 * Parse input and register new cgroup event handler.
4032 * Input must be in format '<event_fd> <control_fd> <args>'.
4033 * Interpretation of args is defined by control file implementation.
4035 static int cgroup_write_event_control(struct cgroup_subsys_state *css,
4036 struct cftype *cft, const char *buffer)
4038 struct cgroup *cgrp = css->cgroup;
4039 struct cgroup_event *event;
4040 struct cgroup *cgrp_cfile;
4041 unsigned int efd, cfd;
4047 efd = simple_strtoul(buffer, &endp, 10);
4052 cfd = simple_strtoul(buffer, &endp, 10);
4053 if ((*endp != ' ') && (*endp != '\0'))
4057 event = kzalloc(sizeof(*event), GFP_KERNEL);
4061 INIT_LIST_HEAD(&event->list);
4062 init_poll_funcptr(&event->pt, cgroup_event_ptable_queue_proc);
4063 init_waitqueue_func_entry(&event->wait, cgroup_event_wake);
4064 INIT_WORK(&event->remove, cgroup_event_remove);
4066 efile = eventfd_fget(efd);
4067 if (IS_ERR(efile)) {
4068 ret = PTR_ERR(efile);
4072 event->eventfd = eventfd_ctx_fileget(efile);
4073 if (IS_ERR(event->eventfd)) {
4074 ret = PTR_ERR(event->eventfd);
4081 goto out_put_eventfd;
4084 /* the process need read permission on control file */
4085 /* AV: shouldn't we check that it's been opened for read instead? */
4086 ret = inode_permission(file_inode(cfile), MAY_READ);
4090 event->cft = __file_cft(cfile);
4091 if (IS_ERR(event->cft)) {
4092 ret = PTR_ERR(event->cft);
4097 * The file to be monitored must be in the same cgroup as
4098 * cgroup.event_control is.
4100 cgrp_cfile = __d_cgrp(cfile->f_dentry->d_parent);
4101 if (cgrp_cfile != cgrp) {
4106 if (!event->cft->register_event || !event->cft->unregister_event) {
4111 ret = event->cft->register_event(css, event->cft,
4112 event->eventfd, buffer);
4116 efile->f_op->poll(efile, &event->pt);
4119 * Events should be removed after rmdir of cgroup directory, but before
4120 * destroying subsystem state objects. Let's take reference to cgroup
4121 * directory dentry to do that.
4125 spin_lock(&cgrp->event_list_lock);
4126 list_add(&event->list, &cgrp->event_list);
4127 spin_unlock(&cgrp->event_list_lock);
4137 eventfd_ctx_put(event->eventfd);
4146 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
4149 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4152 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
4153 struct cftype *cft, u64 val)
4156 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4158 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4162 static struct cftype cgroup_base_files[] = {
4164 .name = "cgroup.procs",
4165 .open = cgroup_procs_open,
4166 .write_u64 = cgroup_procs_write,
4167 .release = cgroup_pidlist_release,
4168 .mode = S_IRUGO | S_IWUSR,
4171 .name = "cgroup.event_control",
4172 .write_string = cgroup_write_event_control,
4176 .name = "cgroup.clone_children",
4177 .flags = CFTYPE_INSANE,
4178 .read_u64 = cgroup_clone_children_read,
4179 .write_u64 = cgroup_clone_children_write,
4182 .name = "cgroup.sane_behavior",
4183 .flags = CFTYPE_ONLY_ON_ROOT,
4184 .read_seq_string = cgroup_sane_behavior_show,
4188 * Historical crazy stuff. These don't have "cgroup." prefix and
4189 * don't exist if sane_behavior. If you're depending on these, be
4190 * prepared to be burned.
4194 .flags = CFTYPE_INSANE, /* use "procs" instead */
4195 .open = cgroup_tasks_open,
4196 .write_u64 = cgroup_tasks_write,
4197 .release = cgroup_pidlist_release,
4198 .mode = S_IRUGO | S_IWUSR,
4201 .name = "notify_on_release",
4202 .flags = CFTYPE_INSANE,
4203 .read_u64 = cgroup_read_notify_on_release,
4204 .write_u64 = cgroup_write_notify_on_release,
4207 .name = "release_agent",
4208 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
4209 .read_seq_string = cgroup_release_agent_show,
4210 .write_string = cgroup_release_agent_write,
4211 .max_write_len = PATH_MAX,
4217 * cgroup_populate_dir - create subsys files in a cgroup directory
4218 * @cgrp: target cgroup
4219 * @subsys_mask: mask of the subsystem ids whose files should be added
4221 * On failure, no file is added.
4223 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
4225 struct cgroup_subsys *ss;
4228 /* process cftsets of each subsystem */
4229 for_each_subsys(ss, i) {
4230 struct cftype_set *set;
4232 if (!test_bit(i, &subsys_mask))
4235 list_for_each_entry(set, &ss->cftsets, node) {
4236 ret = cgroup_addrm_files(cgrp, set->cfts, true);
4242 /* This cgroup is ready now */
4243 for_each_root_subsys(cgrp->root, ss) {
4244 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4245 struct css_id *id = rcu_dereference_protected(css->id, true);
4248 * Update id->css pointer and make this css visible from
4249 * CSS ID functions. This pointer will be dereferened
4250 * from RCU-read-side without locks.
4253 rcu_assign_pointer(id->css, css);
4258 cgroup_clear_dir(cgrp, subsys_mask);
4262 static void css_dput_fn(struct work_struct *work)
4264 struct cgroup_subsys_state *css =
4265 container_of(work, struct cgroup_subsys_state, dput_work);
4267 cgroup_dput(css->cgroup);
4270 static void css_release(struct percpu_ref *ref)
4272 struct cgroup_subsys_state *css =
4273 container_of(ref, struct cgroup_subsys_state, refcnt);
4275 schedule_work(&css->dput_work);
4278 static void init_cgroup_css(struct cgroup_subsys_state *css,
4279 struct cgroup_subsys *ss,
4280 struct cgroup *cgrp)
4286 if (cgrp == cgroup_dummy_top)
4287 css->flags |= CSS_ROOT;
4288 BUG_ON(cgrp->subsys[ss->subsys_id]);
4289 cgrp->subsys[ss->subsys_id] = css;
4292 * css holds an extra ref to @cgrp->dentry which is put on the last
4293 * css_put(). dput() requires process context, which css_put() may
4294 * be called without. @css->dput_work will be used to invoke
4295 * dput() asynchronously from css_put().
4297 INIT_WORK(&css->dput_work, css_dput_fn);
4300 /* invoke ->css_online() on a new CSS and mark it online if successful */
4301 static int online_css(struct cgroup_subsys *ss, struct cgroup *cgrp)
4303 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4306 lockdep_assert_held(&cgroup_mutex);
4309 ret = ss->css_online(css);
4311 css->flags |= CSS_ONLINE;
4315 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4316 static void offline_css(struct cgroup_subsys *ss, struct cgroup *cgrp)
4318 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4320 lockdep_assert_held(&cgroup_mutex);
4322 if (!(css->flags & CSS_ONLINE))
4325 if (ss->css_offline)
4326 ss->css_offline(css);
4328 css->flags &= ~CSS_ONLINE;
4332 * cgroup_create - create a cgroup
4333 * @parent: cgroup that will be parent of the new cgroup
4334 * @dentry: dentry of the new cgroup
4335 * @mode: mode to set on new inode
4337 * Must be called with the mutex on the parent inode held
4339 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4342 struct cgroup *cgrp;
4343 struct cgroup_name *name;
4344 struct cgroupfs_root *root = parent->root;
4346 struct cgroup_subsys *ss;
4347 struct super_block *sb = root->sb;
4349 /* allocate the cgroup and its ID, 0 is reserved for the root */
4350 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4354 name = cgroup_alloc_name(dentry);
4357 rcu_assign_pointer(cgrp->name, name);
4360 * Temporarily set the pointer to NULL, so idr_find() won't return
4361 * a half-baked cgroup.
4363 cgrp->id = idr_alloc(&root->cgroup_idr, NULL, 1, 0, GFP_KERNEL);
4368 * Only live parents can have children. Note that the liveliness
4369 * check isn't strictly necessary because cgroup_mkdir() and
4370 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4371 * anyway so that locking is contained inside cgroup proper and we
4372 * don't get nasty surprises if we ever grow another caller.
4374 if (!cgroup_lock_live_group(parent)) {
4379 /* Grab a reference on the superblock so the hierarchy doesn't
4380 * get deleted on unmount if there are child cgroups. This
4381 * can be done outside cgroup_mutex, since the sb can't
4382 * disappear while someone has an open control file on the
4384 atomic_inc(&sb->s_active);
4386 init_cgroup_housekeeping(cgrp);
4388 dentry->d_fsdata = cgrp;
4389 cgrp->dentry = dentry;
4391 cgrp->parent = parent;
4392 cgrp->root = parent->root;
4394 if (notify_on_release(parent))
4395 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4397 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4398 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4400 for_each_root_subsys(root, ss) {
4401 struct cgroup_subsys_state *css;
4403 css = ss->css_alloc(parent->subsys[ss->subsys_id]);
4409 err = percpu_ref_init(&css->refcnt, css_release);
4415 init_cgroup_css(css, ss, cgrp);
4418 err = alloc_css_id(ss, parent, cgrp);
4425 * Create directory. cgroup_create_file() returns with the new
4426 * directory locked on success so that it can be populated without
4427 * dropping cgroup_mutex.
4429 err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4432 lockdep_assert_held(&dentry->d_inode->i_mutex);
4434 cgrp->serial_nr = cgroup_serial_nr_next++;
4436 /* allocation complete, commit to creation */
4437 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4438 root->number_of_cgroups++;
4440 /* each css holds a ref to the cgroup's dentry */
4441 for_each_root_subsys(root, ss)
4444 /* hold a ref to the parent's dentry */
4445 dget(parent->dentry);
4447 /* creation succeeded, notify subsystems */
4448 for_each_root_subsys(root, ss) {
4449 err = online_css(ss, cgrp);
4453 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4455 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",
4456 current->comm, current->pid, ss->name);
4457 if (!strcmp(ss->name, "memory"))
4458 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4459 ss->warned_broken_hierarchy = true;
4463 idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4465 err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
4469 err = cgroup_populate_dir(cgrp, root->subsys_mask);
4473 mutex_unlock(&cgroup_mutex);
4474 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4479 for_each_root_subsys(root, ss) {
4480 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4483 percpu_ref_cancel_init(&css->refcnt);
4487 mutex_unlock(&cgroup_mutex);
4488 /* Release the reference count that we took on the superblock */
4489 deactivate_super(sb);
4491 idr_remove(&root->cgroup_idr, cgrp->id);
4493 kfree(rcu_dereference_raw(cgrp->name));
4499 cgroup_destroy_locked(cgrp);
4500 mutex_unlock(&cgroup_mutex);
4501 mutex_unlock(&dentry->d_inode->i_mutex);
4505 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4507 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4509 /* the vfs holds inode->i_mutex already */
4510 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4513 static void cgroup_css_killed(struct cgroup *cgrp)
4515 if (!atomic_dec_and_test(&cgrp->css_kill_cnt))
4518 /* percpu ref's of all css's are killed, kick off the next step */
4519 INIT_WORK(&cgrp->destroy_work, cgroup_offline_fn);
4520 schedule_work(&cgrp->destroy_work);
4523 static void css_ref_killed_fn(struct percpu_ref *ref)
4525 struct cgroup_subsys_state *css =
4526 container_of(ref, struct cgroup_subsys_state, refcnt);
4528 cgroup_css_killed(css->cgroup);
4532 * cgroup_destroy_locked - the first stage of cgroup destruction
4533 * @cgrp: cgroup to be destroyed
4535 * css's make use of percpu refcnts whose killing latency shouldn't be
4536 * exposed to userland and are RCU protected. Also, cgroup core needs to
4537 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
4538 * invoked. To satisfy all the requirements, destruction is implemented in
4539 * the following two steps.
4541 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4542 * userland visible parts and start killing the percpu refcnts of
4543 * css's. Set up so that the next stage will be kicked off once all
4544 * the percpu refcnts are confirmed to be killed.
4546 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4547 * rest of destruction. Once all cgroup references are gone, the
4548 * cgroup is RCU-freed.
4550 * This function implements s1. After this step, @cgrp is gone as far as
4551 * the userland is concerned and a new cgroup with the same name may be
4552 * created. As cgroup doesn't care about the names internally, this
4553 * doesn't cause any problem.
4555 static int cgroup_destroy_locked(struct cgroup *cgrp)
4556 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4558 struct dentry *d = cgrp->dentry;
4559 struct cgroup_event *event, *tmp;
4560 struct cgroup_subsys *ss;
4563 lockdep_assert_held(&d->d_inode->i_mutex);
4564 lockdep_assert_held(&cgroup_mutex);
4567 * css_set_lock synchronizes access to ->cset_links and prevents
4568 * @cgrp from being removed while __put_css_set() is in progress.
4570 read_lock(&css_set_lock);
4571 empty = list_empty(&cgrp->cset_links) && list_empty(&cgrp->children);
4572 read_unlock(&css_set_lock);
4577 * Block new css_tryget() by killing css refcnts. cgroup core
4578 * guarantees that, by the time ->css_offline() is invoked, no new
4579 * css reference will be given out via css_tryget(). We can't
4580 * simply call percpu_ref_kill() and proceed to offlining css's
4581 * because percpu_ref_kill() doesn't guarantee that the ref is seen
4582 * as killed on all CPUs on return.
4584 * Use percpu_ref_kill_and_confirm() to get notifications as each
4585 * css is confirmed to be seen as killed on all CPUs. The
4586 * notification callback keeps track of the number of css's to be
4587 * killed and schedules cgroup_offline_fn() to perform the rest of
4588 * destruction once the percpu refs of all css's are confirmed to
4591 atomic_set(&cgrp->css_kill_cnt, 1);
4592 for_each_root_subsys(cgrp->root, ss) {
4593 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4596 * Killing would put the base ref, but we need to keep it
4597 * alive until after ->css_offline.
4599 percpu_ref_get(&css->refcnt);
4601 atomic_inc(&cgrp->css_kill_cnt);
4602 percpu_ref_kill_and_confirm(&css->refcnt, css_ref_killed_fn);
4604 cgroup_css_killed(cgrp);
4607 * Mark @cgrp dead. This prevents further task migration and child
4608 * creation by disabling cgroup_lock_live_group(). Note that
4609 * CGRP_DEAD assertion is depended upon by css_next_child() to
4610 * resume iteration after dropping RCU read lock. See
4611 * css_next_child() for details.
4613 set_bit(CGRP_DEAD, &cgrp->flags);
4615 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4616 raw_spin_lock(&release_list_lock);
4617 if (!list_empty(&cgrp->release_list))
4618 list_del_init(&cgrp->release_list);
4619 raw_spin_unlock(&release_list_lock);
4622 * Clear and remove @cgrp directory. The removal puts the base ref
4623 * but we aren't quite done with @cgrp yet, so hold onto it.
4625 cgroup_clear_dir(cgrp, cgrp->root->subsys_mask);
4626 cgroup_addrm_files(cgrp, cgroup_base_files, false);
4628 cgroup_d_remove_dir(d);
4631 * Unregister events and notify userspace.
4632 * Notify userspace about cgroup removing only after rmdir of cgroup
4633 * directory to avoid race between userspace and kernelspace.
4635 spin_lock(&cgrp->event_list_lock);
4636 list_for_each_entry_safe(event, tmp, &cgrp->event_list, list) {
4637 list_del_init(&event->list);
4638 schedule_work(&event->remove);
4640 spin_unlock(&cgrp->event_list_lock);
4646 * cgroup_offline_fn - the second step of cgroup destruction
4647 * @work: cgroup->destroy_free_work
4649 * This function is invoked from a work item for a cgroup which is being
4650 * destroyed after the percpu refcnts of all css's are guaranteed to be
4651 * seen as killed on all CPUs, and performs the rest of destruction. This
4652 * is the second step of destruction described in the comment above
4653 * cgroup_destroy_locked().
4655 static void cgroup_offline_fn(struct work_struct *work)
4657 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
4658 struct cgroup *parent = cgrp->parent;
4659 struct dentry *d = cgrp->dentry;
4660 struct cgroup_subsys *ss;
4662 mutex_lock(&cgroup_mutex);
4665 * css_tryget() is guaranteed to fail now. Tell subsystems to
4666 * initate destruction.
4668 for_each_root_subsys(cgrp->root, ss)
4669 offline_css(ss, cgrp);
4672 * Put the css refs from cgroup_destroy_locked(). Each css holds
4673 * an extra reference to the cgroup's dentry and cgroup removal
4674 * proceeds regardless of css refs. On the last put of each css,
4675 * whenever that may be, the extra dentry ref is put so that dentry
4676 * destruction happens only after all css's are released.
4678 for_each_root_subsys(cgrp->root, ss)
4679 css_put(cgrp->subsys[ss->subsys_id]);
4681 /* delete this cgroup from parent->children */
4682 list_del_rcu(&cgrp->sibling);
4685 * We should remove the cgroup object from idr before its grace
4686 * period starts, so we won't be looking up a cgroup while the
4687 * cgroup is being freed.
4689 idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4694 set_bit(CGRP_RELEASABLE, &parent->flags);
4695 check_for_release(parent);
4697 mutex_unlock(&cgroup_mutex);
4700 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4704 mutex_lock(&cgroup_mutex);
4705 ret = cgroup_destroy_locked(dentry->d_fsdata);
4706 mutex_unlock(&cgroup_mutex);
4711 static void __init_or_module cgroup_init_cftsets(struct cgroup_subsys *ss)
4713 INIT_LIST_HEAD(&ss->cftsets);
4716 * base_cftset is embedded in subsys itself, no need to worry about
4719 if (ss->base_cftypes) {
4722 for (cft = ss->base_cftypes; cft->name[0] != '\0'; cft++)
4725 ss->base_cftset.cfts = ss->base_cftypes;
4726 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4730 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4732 struct cgroup_subsys_state *css;
4734 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4736 mutex_lock(&cgroup_mutex);
4738 /* init base cftset */
4739 cgroup_init_cftsets(ss);
4741 /* Create the top cgroup state for this subsystem */
4742 list_add(&ss->sibling, &cgroup_dummy_root.subsys_list);
4743 ss->root = &cgroup_dummy_root;
4744 css = ss->css_alloc(cgroup_dummy_top->subsys[ss->subsys_id]);
4745 /* We don't handle early failures gracefully */
4746 BUG_ON(IS_ERR(css));
4747 init_cgroup_css(css, ss, cgroup_dummy_top);
4749 /* Update the init_css_set to contain a subsys
4750 * pointer to this state - since the subsystem is
4751 * newly registered, all tasks and hence the
4752 * init_css_set is in the subsystem's top cgroup. */
4753 init_css_set.subsys[ss->subsys_id] = css;
4755 need_forkexit_callback |= ss->fork || ss->exit;
4757 /* At system boot, before all subsystems have been
4758 * registered, no tasks have been forked, so we don't
4759 * need to invoke fork callbacks here. */
4760 BUG_ON(!list_empty(&init_task.tasks));
4762 BUG_ON(online_css(ss, cgroup_dummy_top));
4764 mutex_unlock(&cgroup_mutex);
4766 /* this function shouldn't be used with modular subsystems, since they
4767 * need to register a subsys_id, among other things */
4772 * cgroup_load_subsys: load and register a modular subsystem at runtime
4773 * @ss: the subsystem to load
4775 * This function should be called in a modular subsystem's initcall. If the
4776 * subsystem is built as a module, it will be assigned a new subsys_id and set
4777 * up for use. If the subsystem is built-in anyway, work is delegated to the
4778 * simpler cgroup_init_subsys.
4780 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
4782 struct cgroup_subsys_state *css;
4784 struct hlist_node *tmp;
4785 struct css_set *cset;
4788 /* check name and function validity */
4789 if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
4790 ss->css_alloc == NULL || ss->css_free == NULL)
4794 * we don't support callbacks in modular subsystems. this check is
4795 * before the ss->module check for consistency; a subsystem that could
4796 * be a module should still have no callbacks even if the user isn't
4797 * compiling it as one.
4799 if (ss->fork || ss->exit)
4803 * an optionally modular subsystem is built-in: we want to do nothing,
4804 * since cgroup_init_subsys will have already taken care of it.
4806 if (ss->module == NULL) {
4807 /* a sanity check */
4808 BUG_ON(cgroup_subsys[ss->subsys_id] != ss);
4812 /* init base cftset */
4813 cgroup_init_cftsets(ss);
4815 mutex_lock(&cgroup_mutex);
4816 cgroup_subsys[ss->subsys_id] = ss;
4819 * no ss->css_alloc seems to need anything important in the ss
4820 * struct, so this can happen first (i.e. before the dummy root
4823 css = ss->css_alloc(cgroup_dummy_top->subsys[ss->subsys_id]);
4825 /* failure case - need to deassign the cgroup_subsys[] slot. */
4826 cgroup_subsys[ss->subsys_id] = NULL;
4827 mutex_unlock(&cgroup_mutex);
4828 return PTR_ERR(css);
4831 list_add(&ss->sibling, &cgroup_dummy_root.subsys_list);
4832 ss->root = &cgroup_dummy_root;
4834 /* our new subsystem will be attached to the dummy hierarchy. */
4835 init_cgroup_css(css, ss, cgroup_dummy_top);
4836 /* init_idr must be after init_cgroup_css because it sets css->id. */
4838 ret = cgroup_init_idr(ss, css);
4844 * Now we need to entangle the css into the existing css_sets. unlike
4845 * in cgroup_init_subsys, there are now multiple css_sets, so each one
4846 * will need a new pointer to it; done by iterating the css_set_table.
4847 * furthermore, modifying the existing css_sets will corrupt the hash
4848 * table state, so each changed css_set will need its hash recomputed.
4849 * this is all done under the css_set_lock.
4851 write_lock(&css_set_lock);
4852 hash_for_each_safe(css_set_table, i, tmp, cset, hlist) {
4853 /* skip entries that we already rehashed */
4854 if (cset->subsys[ss->subsys_id])
4856 /* remove existing entry */
4857 hash_del(&cset->hlist);
4859 cset->subsys[ss->subsys_id] = css;
4860 /* recompute hash and restore entry */
4861 key = css_set_hash(cset->subsys);
4862 hash_add(css_set_table, &cset->hlist, key);
4864 write_unlock(&css_set_lock);
4866 ret = online_css(ss, cgroup_dummy_top);
4871 mutex_unlock(&cgroup_mutex);
4875 mutex_unlock(&cgroup_mutex);
4876 /* @ss can't be mounted here as try_module_get() would fail */
4877 cgroup_unload_subsys(ss);
4880 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
4883 * cgroup_unload_subsys: unload a modular subsystem
4884 * @ss: the subsystem to unload
4886 * This function should be called in a modular subsystem's exitcall. When this
4887 * function is invoked, the refcount on the subsystem's module will be 0, so
4888 * the subsystem will not be attached to any hierarchy.
4890 void cgroup_unload_subsys(struct cgroup_subsys *ss)
4892 struct cgrp_cset_link *link;
4894 BUG_ON(ss->module == NULL);
4897 * we shouldn't be called if the subsystem is in use, and the use of
4898 * try_module_get() in rebind_subsystems() should ensure that it
4899 * doesn't start being used while we're killing it off.
4901 BUG_ON(ss->root != &cgroup_dummy_root);
4903 mutex_lock(&cgroup_mutex);
4905 offline_css(ss, cgroup_dummy_top);
4908 idr_destroy(&ss->idr);
4910 /* deassign the subsys_id */
4911 cgroup_subsys[ss->subsys_id] = NULL;
4913 /* remove subsystem from the dummy root's list of subsystems */
4914 list_del_init(&ss->sibling);
4917 * disentangle the css from all css_sets attached to the dummy
4918 * top. as in loading, we need to pay our respects to the hashtable
4921 write_lock(&css_set_lock);
4922 list_for_each_entry(link, &cgroup_dummy_top->cset_links, cset_link) {
4923 struct css_set *cset = link->cset;
4926 hash_del(&cset->hlist);
4927 cset->subsys[ss->subsys_id] = NULL;
4928 key = css_set_hash(cset->subsys);
4929 hash_add(css_set_table, &cset->hlist, key);
4931 write_unlock(&css_set_lock);
4934 * remove subsystem's css from the cgroup_dummy_top and free it -
4935 * need to free before marking as null because ss->css_free needs
4936 * the cgrp->subsys pointer to find their state. note that this
4937 * also takes care of freeing the css_id.
4939 ss->css_free(cgroup_dummy_top->subsys[ss->subsys_id]);
4940 cgroup_dummy_top->subsys[ss->subsys_id] = NULL;
4942 mutex_unlock(&cgroup_mutex);
4944 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
4947 * cgroup_init_early - cgroup initialization at system boot
4949 * Initialize cgroups at system boot, and initialize any
4950 * subsystems that request early init.
4952 int __init cgroup_init_early(void)
4954 struct cgroup_subsys *ss;
4957 atomic_set(&init_css_set.refcount, 1);
4958 INIT_LIST_HEAD(&init_css_set.cgrp_links);
4959 INIT_LIST_HEAD(&init_css_set.tasks);
4960 INIT_HLIST_NODE(&init_css_set.hlist);
4962 init_cgroup_root(&cgroup_dummy_root);
4963 cgroup_root_count = 1;
4964 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4966 init_cgrp_cset_link.cset = &init_css_set;
4967 init_cgrp_cset_link.cgrp = cgroup_dummy_top;
4968 list_add(&init_cgrp_cset_link.cset_link, &cgroup_dummy_top->cset_links);
4969 list_add(&init_cgrp_cset_link.cgrp_link, &init_css_set.cgrp_links);
4971 /* at bootup time, we don't worry about modular subsystems */
4972 for_each_builtin_subsys(ss, i) {
4974 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
4975 BUG_ON(!ss->css_alloc);
4976 BUG_ON(!ss->css_free);
4977 if (ss->subsys_id != i) {
4978 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
4979 ss->name, ss->subsys_id);
4984 cgroup_init_subsys(ss);
4990 * cgroup_init - cgroup initialization
4992 * Register cgroup filesystem and /proc file, and initialize
4993 * any subsystems that didn't request early init.
4995 int __init cgroup_init(void)
4997 struct cgroup_subsys *ss;
5001 err = bdi_init(&cgroup_backing_dev_info);
5005 for_each_builtin_subsys(ss, i) {
5006 if (!ss->early_init)
5007 cgroup_init_subsys(ss);
5009 cgroup_init_idr(ss, init_css_set.subsys[ss->subsys_id]);
5012 /* allocate id for the dummy hierarchy */
5013 mutex_lock(&cgroup_mutex);
5014 mutex_lock(&cgroup_root_mutex);
5016 /* Add init_css_set to the hash table */
5017 key = css_set_hash(init_css_set.subsys);
5018 hash_add(css_set_table, &init_css_set.hlist, key);
5020 BUG_ON(cgroup_init_root_id(&cgroup_dummy_root, 0, 1));
5022 err = idr_alloc(&cgroup_dummy_root.cgroup_idr, cgroup_dummy_top,
5026 mutex_unlock(&cgroup_root_mutex);
5027 mutex_unlock(&cgroup_mutex);
5029 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
5035 err = register_filesystem(&cgroup_fs_type);
5037 kobject_put(cgroup_kobj);
5041 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
5045 bdi_destroy(&cgroup_backing_dev_info);
5051 * proc_cgroup_show()
5052 * - Print task's cgroup paths into seq_file, one line for each hierarchy
5053 * - Used for /proc/<pid>/cgroup.
5054 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
5055 * doesn't really matter if tsk->cgroup changes after we read it,
5056 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
5057 * anyway. No need to check that tsk->cgroup != NULL, thanks to
5058 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
5059 * cgroup to top_cgroup.
5062 /* TODO: Use a proper seq_file iterator */
5063 int proc_cgroup_show(struct seq_file *m, void *v)
5066 struct task_struct *tsk;
5069 struct cgroupfs_root *root;
5072 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5078 tsk = get_pid_task(pid, PIDTYPE_PID);
5084 mutex_lock(&cgroup_mutex);
5086 for_each_active_root(root) {
5087 struct cgroup_subsys *ss;
5088 struct cgroup *cgrp;
5091 seq_printf(m, "%d:", root->hierarchy_id);
5092 for_each_root_subsys(root, ss)
5093 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
5094 if (strlen(root->name))
5095 seq_printf(m, "%sname=%s", count ? "," : "",
5098 cgrp = task_cgroup_from_root(tsk, root);
5099 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
5107 mutex_unlock(&cgroup_mutex);
5108 put_task_struct(tsk);
5115 /* Display information about each subsystem and each hierarchy */
5116 static int proc_cgroupstats_show(struct seq_file *m, void *v)
5118 struct cgroup_subsys *ss;
5121 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
5123 * ideally we don't want subsystems moving around while we do this.
5124 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
5125 * subsys/hierarchy state.
5127 mutex_lock(&cgroup_mutex);
5129 for_each_subsys(ss, i)
5130 seq_printf(m, "%s\t%d\t%d\t%d\n",
5131 ss->name, ss->root->hierarchy_id,
5132 ss->root->number_of_cgroups, !ss->disabled);
5134 mutex_unlock(&cgroup_mutex);
5138 static int cgroupstats_open(struct inode *inode, struct file *file)
5140 return single_open(file, proc_cgroupstats_show, NULL);
5143 static const struct file_operations proc_cgroupstats_operations = {
5144 .open = cgroupstats_open,
5146 .llseek = seq_lseek,
5147 .release = single_release,
5151 * cgroup_fork - attach newly forked task to its parents cgroup.
5152 * @child: pointer to task_struct of forking parent process.
5154 * Description: A task inherits its parent's cgroup at fork().
5156 * A pointer to the shared css_set was automatically copied in
5157 * fork.c by dup_task_struct(). However, we ignore that copy, since
5158 * it was not made under the protection of RCU or cgroup_mutex, so
5159 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
5160 * have already changed current->cgroups, allowing the previously
5161 * referenced cgroup group to be removed and freed.
5163 * At the point that cgroup_fork() is called, 'current' is the parent
5164 * task, and the passed argument 'child' points to the child task.
5166 void cgroup_fork(struct task_struct *child)
5169 get_css_set(task_css_set(current));
5170 child->cgroups = current->cgroups;
5171 task_unlock(current);
5172 INIT_LIST_HEAD(&child->cg_list);
5176 * cgroup_post_fork - called on a new task after adding it to the task list
5177 * @child: the task in question
5179 * Adds the task to the list running through its css_set if necessary and
5180 * call the subsystem fork() callbacks. Has to be after the task is
5181 * visible on the task list in case we race with the first call to
5182 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
5185 void cgroup_post_fork(struct task_struct *child)
5187 struct cgroup_subsys *ss;
5191 * use_task_css_set_links is set to 1 before we walk the tasklist
5192 * under the tasklist_lock and we read it here after we added the child
5193 * to the tasklist under the tasklist_lock as well. If the child wasn't
5194 * yet in the tasklist when we walked through it from
5195 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
5196 * should be visible now due to the paired locking and barriers implied
5197 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
5198 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
5201 if (use_task_css_set_links) {
5202 write_lock(&css_set_lock);
5204 if (list_empty(&child->cg_list))
5205 list_add(&child->cg_list, &task_css_set(child)->tasks);
5207 write_unlock(&css_set_lock);
5211 * Call ss->fork(). This must happen after @child is linked on
5212 * css_set; otherwise, @child might change state between ->fork()
5213 * and addition to css_set.
5215 if (need_forkexit_callback) {
5217 * fork/exit callbacks are supported only for builtin
5218 * subsystems, and the builtin section of the subsys
5219 * array is immutable, so we don't need to lock the
5220 * subsys array here. On the other hand, modular section
5221 * of the array can be freed at module unload, so we
5224 for_each_builtin_subsys(ss, i)
5231 * cgroup_exit - detach cgroup from exiting task
5232 * @tsk: pointer to task_struct of exiting process
5233 * @run_callback: run exit callbacks?
5235 * Description: Detach cgroup from @tsk and release it.
5237 * Note that cgroups marked notify_on_release force every task in
5238 * them to take the global cgroup_mutex mutex when exiting.
5239 * This could impact scaling on very large systems. Be reluctant to
5240 * use notify_on_release cgroups where very high task exit scaling
5241 * is required on large systems.
5243 * the_top_cgroup_hack:
5245 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
5247 * We call cgroup_exit() while the task is still competent to
5248 * handle notify_on_release(), then leave the task attached to the
5249 * root cgroup in each hierarchy for the remainder of its exit.
5251 * To do this properly, we would increment the reference count on
5252 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
5253 * code we would add a second cgroup function call, to drop that
5254 * reference. This would just create an unnecessary hot spot on
5255 * the top_cgroup reference count, to no avail.
5257 * Normally, holding a reference to a cgroup without bumping its
5258 * count is unsafe. The cgroup could go away, or someone could
5259 * attach us to a different cgroup, decrementing the count on
5260 * the first cgroup that we never incremented. But in this case,
5261 * top_cgroup isn't going away, and either task has PF_EXITING set,
5262 * which wards off any cgroup_attach_task() attempts, or task is a failed
5263 * fork, never visible to cgroup_attach_task.
5265 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
5267 struct cgroup_subsys *ss;
5268 struct css_set *cset;
5272 * Unlink from the css_set task list if necessary.
5273 * Optimistically check cg_list before taking
5276 if (!list_empty(&tsk->cg_list)) {
5277 write_lock(&css_set_lock);
5278 if (!list_empty(&tsk->cg_list))
5279 list_del_init(&tsk->cg_list);
5280 write_unlock(&css_set_lock);
5283 /* Reassign the task to the init_css_set. */
5285 cset = task_css_set(tsk);
5286 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
5288 if (run_callbacks && need_forkexit_callback) {
5290 * fork/exit callbacks are supported only for builtin
5291 * subsystems, see cgroup_post_fork() for details.
5293 for_each_builtin_subsys(ss, i) {
5295 struct cgroup_subsys_state *old_css = cset->subsys[i];
5296 struct cgroup_subsys_state *css = task_css(tsk, i);
5298 ss->exit(css, old_css, tsk);
5304 put_css_set_taskexit(cset);
5307 static void check_for_release(struct cgroup *cgrp)
5309 if (cgroup_is_releasable(cgrp) &&
5310 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
5312 * Control Group is currently removeable. If it's not
5313 * already queued for a userspace notification, queue
5316 int need_schedule_work = 0;
5318 raw_spin_lock(&release_list_lock);
5319 if (!cgroup_is_dead(cgrp) &&
5320 list_empty(&cgrp->release_list)) {
5321 list_add(&cgrp->release_list, &release_list);
5322 need_schedule_work = 1;
5324 raw_spin_unlock(&release_list_lock);
5325 if (need_schedule_work)
5326 schedule_work(&release_agent_work);
5331 * Notify userspace when a cgroup is released, by running the
5332 * configured release agent with the name of the cgroup (path
5333 * relative to the root of cgroup file system) as the argument.
5335 * Most likely, this user command will try to rmdir this cgroup.
5337 * This races with the possibility that some other task will be
5338 * attached to this cgroup before it is removed, or that some other
5339 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5340 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5341 * unused, and this cgroup will be reprieved from its death sentence,
5342 * to continue to serve a useful existence. Next time it's released,
5343 * we will get notified again, if it still has 'notify_on_release' set.
5345 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5346 * means only wait until the task is successfully execve()'d. The
5347 * separate release agent task is forked by call_usermodehelper(),
5348 * then control in this thread returns here, without waiting for the
5349 * release agent task. We don't bother to wait because the caller of
5350 * this routine has no use for the exit status of the release agent
5351 * task, so no sense holding our caller up for that.
5353 static void cgroup_release_agent(struct work_struct *work)
5355 BUG_ON(work != &release_agent_work);
5356 mutex_lock(&cgroup_mutex);
5357 raw_spin_lock(&release_list_lock);
5358 while (!list_empty(&release_list)) {
5359 char *argv[3], *envp[3];
5361 char *pathbuf = NULL, *agentbuf = NULL;
5362 struct cgroup *cgrp = list_entry(release_list.next,
5365 list_del_init(&cgrp->release_list);
5366 raw_spin_unlock(&release_list_lock);
5367 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5370 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
5372 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5377 argv[i++] = agentbuf;
5378 argv[i++] = pathbuf;
5382 /* minimal command environment */
5383 envp[i++] = "HOME=/";
5384 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5387 /* Drop the lock while we invoke the usermode helper,
5388 * since the exec could involve hitting disk and hence
5389 * be a slow process */
5390 mutex_unlock(&cgroup_mutex);
5391 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5392 mutex_lock(&cgroup_mutex);
5396 raw_spin_lock(&release_list_lock);
5398 raw_spin_unlock(&release_list_lock);
5399 mutex_unlock(&cgroup_mutex);
5402 static int __init cgroup_disable(char *str)
5404 struct cgroup_subsys *ss;
5408 while ((token = strsep(&str, ",")) != NULL) {
5413 * cgroup_disable, being at boot time, can't know about
5414 * module subsystems, so we don't worry about them.
5416 for_each_builtin_subsys(ss, i) {
5417 if (!strcmp(token, ss->name)) {
5419 printk(KERN_INFO "Disabling %s control group"
5420 " subsystem\n", ss->name);
5427 __setup("cgroup_disable=", cgroup_disable);
5430 * Functons for CSS ID.
5433 /* to get ID other than 0, this should be called when !cgroup_is_dead() */
5434 unsigned short css_id(struct cgroup_subsys_state *css)
5436 struct css_id *cssid;
5439 * This css_id() can return correct value when somone has refcnt
5440 * on this or this is under rcu_read_lock(). Once css->id is allocated,
5441 * it's unchanged until freed.
5443 cssid = rcu_dereference_raw(css->id);
5449 EXPORT_SYMBOL_GPL(css_id);
5452 * css_is_ancestor - test "root" css is an ancestor of "child"
5453 * @child: the css to be tested.
5454 * @root: the css supporsed to be an ancestor of the child.
5456 * Returns true if "root" is an ancestor of "child" in its hierarchy. Because
5457 * this function reads css->id, the caller must hold rcu_read_lock().
5458 * But, considering usual usage, the csses should be valid objects after test.
5459 * Assuming that the caller will do some action to the child if this returns
5460 * returns true, the caller must take "child";s reference count.
5461 * If "child" is valid object and this returns true, "root" is valid, too.
5464 bool css_is_ancestor(struct cgroup_subsys_state *child,
5465 const struct cgroup_subsys_state *root)
5467 struct css_id *child_id;
5468 struct css_id *root_id;
5470 child_id = rcu_dereference(child->id);
5473 root_id = rcu_dereference(root->id);
5476 if (child_id->depth < root_id->depth)
5478 if (child_id->stack[root_id->depth] != root_id->id)
5483 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
5485 struct css_id *id = rcu_dereference_protected(css->id, true);
5487 /* When this is called before css_id initialization, id can be NULL */
5491 BUG_ON(!ss->use_id);
5493 rcu_assign_pointer(id->css, NULL);
5494 rcu_assign_pointer(css->id, NULL);
5495 spin_lock(&ss->id_lock);
5496 idr_remove(&ss->idr, id->id);
5497 spin_unlock(&ss->id_lock);
5498 kfree_rcu(id, rcu_head);
5500 EXPORT_SYMBOL_GPL(free_css_id);
5503 * This is called by init or create(). Then, calls to this function are
5504 * always serialized (By cgroup_mutex() at create()).
5507 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
5509 struct css_id *newid;
5512 BUG_ON(!ss->use_id);
5514 size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
5515 newid = kzalloc(size, GFP_KERNEL);
5517 return ERR_PTR(-ENOMEM);
5519 idr_preload(GFP_KERNEL);
5520 spin_lock(&ss->id_lock);
5521 /* Don't use 0. allocates an ID of 1-65535 */
5522 ret = idr_alloc(&ss->idr, newid, 1, CSS_ID_MAX + 1, GFP_NOWAIT);
5523 spin_unlock(&ss->id_lock);
5526 /* Returns error when there are no free spaces for new ID.*/
5531 newid->depth = depth;
5535 return ERR_PTR(ret);
5539 static int __init_or_module cgroup_init_idr(struct cgroup_subsys *ss,
5540 struct cgroup_subsys_state *rootcss)
5542 struct css_id *newid;
5544 spin_lock_init(&ss->id_lock);
5547 newid = get_new_cssid(ss, 0);
5549 return PTR_ERR(newid);
5551 newid->stack[0] = newid->id;
5552 RCU_INIT_POINTER(newid->css, rootcss);
5553 RCU_INIT_POINTER(rootcss->id, newid);
5557 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
5558 struct cgroup *child)
5560 int subsys_id, i, depth = 0;
5561 struct cgroup_subsys_state *parent_css, *child_css;
5562 struct css_id *child_id, *parent_id;
5564 subsys_id = ss->subsys_id;
5565 parent_css = parent->subsys[subsys_id];
5566 child_css = child->subsys[subsys_id];
5567 parent_id = rcu_dereference_protected(parent_css->id, true);
5568 depth = parent_id->depth + 1;
5570 child_id = get_new_cssid(ss, depth);
5571 if (IS_ERR(child_id))
5572 return PTR_ERR(child_id);
5574 for (i = 0; i < depth; i++)
5575 child_id->stack[i] = parent_id->stack[i];
5576 child_id->stack[depth] = child_id->id;
5578 * child_id->css pointer will be set after this cgroup is available
5579 * see cgroup_populate_dir()
5581 rcu_assign_pointer(child_css->id, child_id);
5587 * css_lookup - lookup css by id
5588 * @ss: cgroup subsys to be looked into.
5591 * Returns pointer to cgroup_subsys_state if there is valid one with id.
5592 * NULL if not. Should be called under rcu_read_lock()
5594 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
5596 struct css_id *cssid = NULL;
5598 BUG_ON(!ss->use_id);
5599 cssid = idr_find(&ss->idr, id);
5601 if (unlikely(!cssid))
5604 return rcu_dereference(cssid->css);
5606 EXPORT_SYMBOL_GPL(css_lookup);
5609 * get corresponding css from file open on cgroupfs directory
5611 struct cgroup_subsys_state *cgroup_css_from_dir(struct file *f, int id)
5613 struct cgroup *cgrp;
5614 struct inode *inode;
5615 struct cgroup_subsys_state *css;
5617 inode = file_inode(f);
5618 /* check in cgroup filesystem dir */
5619 if (inode->i_op != &cgroup_dir_inode_operations)
5620 return ERR_PTR(-EBADF);
5622 if (id < 0 || id >= CGROUP_SUBSYS_COUNT)
5623 return ERR_PTR(-EINVAL);
5626 cgrp = __d_cgrp(f->f_dentry);
5627 css = cgrp->subsys[id];
5628 return css ? css : ERR_PTR(-ENOENT);
5631 #ifdef CONFIG_CGROUP_DEBUG
5632 static struct cgroup_subsys_state *
5633 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5635 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5638 return ERR_PTR(-ENOMEM);
5643 static void debug_css_free(struct cgroup_subsys_state *css)
5648 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5651 return cgroup_task_count(css->cgroup);
5654 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5657 return (u64)(unsigned long)current->cgroups;
5660 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5666 count = atomic_read(&task_css_set(current)->refcount);
5671 static int current_css_set_cg_links_read(struct cgroup_subsys_state *css,
5673 struct seq_file *seq)
5675 struct cgrp_cset_link *link;
5676 struct css_set *cset;
5678 read_lock(&css_set_lock);
5680 cset = rcu_dereference(current->cgroups);
5681 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5682 struct cgroup *c = link->cgrp;
5686 name = c->dentry->d_name.name;
5689 seq_printf(seq, "Root %d group %s\n",
5690 c->root->hierarchy_id, name);
5693 read_unlock(&css_set_lock);
5697 #define MAX_TASKS_SHOWN_PER_CSS 25
5698 static int cgroup_css_links_read(struct cgroup_subsys_state *css,
5699 struct cftype *cft, struct seq_file *seq)
5701 struct cgrp_cset_link *link;
5703 read_lock(&css_set_lock);
5704 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5705 struct css_set *cset = link->cset;
5706 struct task_struct *task;
5708 seq_printf(seq, "css_set %p\n", cset);
5709 list_for_each_entry(task, &cset->tasks, cg_list) {
5710 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5711 seq_puts(seq, " ...\n");
5714 seq_printf(seq, " task %d\n",
5715 task_pid_vnr(task));
5719 read_unlock(&css_set_lock);
5723 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5725 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
5728 static struct cftype debug_files[] = {
5730 .name = "taskcount",
5731 .read_u64 = debug_taskcount_read,
5735 .name = "current_css_set",
5736 .read_u64 = current_css_set_read,
5740 .name = "current_css_set_refcount",
5741 .read_u64 = current_css_set_refcount_read,
5745 .name = "current_css_set_cg_links",
5746 .read_seq_string = current_css_set_cg_links_read,
5750 .name = "cgroup_css_links",
5751 .read_seq_string = cgroup_css_links_read,
5755 .name = "releasable",
5756 .read_u64 = releasable_read,
5762 struct cgroup_subsys debug_subsys = {
5764 .css_alloc = debug_css_alloc,
5765 .css_free = debug_css_free,
5766 .subsys_id = debug_subsys_id,
5767 .base_cftypes = debug_files,
5769 #endif /* CONFIG_CGROUP_DEBUG */