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/flex_array.h> /* used in cgroup_attach_task */
60 #include <linux/kthread.h>
62 #include <linux/atomic.h>
65 * cgroup_mutex is the master lock. Any modification to cgroup or its
66 * hierarchy must be performed while holding it.
68 * cgroup_root_mutex nests inside cgroup_mutex and should be held to modify
69 * cgroupfs_root of any cgroup hierarchy - subsys list, flags,
70 * release_agent_path and so on. Modifying requires both cgroup_mutex and
71 * cgroup_root_mutex. Readers can acquire either of the two. This is to
72 * break the following locking order cycle.
74 * A. cgroup_mutex -> cred_guard_mutex -> s_type->i_mutex_key -> namespace_sem
75 * B. namespace_sem -> cgroup_mutex
77 * B happens only through cgroup_show_options() and using cgroup_root_mutex
80 #ifdef CONFIG_PROVE_RCU
81 DEFINE_MUTEX(cgroup_mutex);
82 EXPORT_SYMBOL_GPL(cgroup_mutex); /* only for lockdep */
84 static DEFINE_MUTEX(cgroup_mutex);
87 static DEFINE_MUTEX(cgroup_root_mutex);
90 * Generate an array of cgroup subsystem pointers. At boot time, this is
91 * populated with the built in subsystems, and modular subsystems are
92 * registered after that. The mutable section of this array is protected by
95 #define SUBSYS(_x) [_x ## _subsys_id] = &_x ## _subsys,
96 #define IS_SUBSYS_ENABLED(option) IS_BUILTIN(option)
97 static struct cgroup_subsys *cgroup_subsys[CGROUP_SUBSYS_COUNT] = {
98 #include <linux/cgroup_subsys.h>
102 * The dummy hierarchy, reserved for the subsystems that are otherwise
103 * unattached - it never has more than a single cgroup, and all tasks are
104 * part of that cgroup.
106 static struct cgroupfs_root cgroup_dummy_root;
108 /* dummy_top is a shorthand for the dummy hierarchy's top cgroup */
109 static struct cgroup * const cgroup_dummy_top = &cgroup_dummy_root.top_cgroup;
112 * cgroupfs file entry, pointed to from leaf dentry->d_fsdata.
115 struct list_head node;
116 struct dentry *dentry;
118 struct cgroup_subsys_state *css;
121 struct simple_xattrs xattrs;
125 * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when
126 * cgroup_subsys->use_id != 0.
128 #define CSS_ID_MAX (65535)
131 * The css to which this ID points. This pointer is set to valid value
132 * after cgroup is populated. If cgroup is removed, this will be NULL.
133 * This pointer is expected to be RCU-safe because destroy()
134 * is called after synchronize_rcu(). But for safe use, css_tryget()
135 * should be used for avoiding race.
137 struct cgroup_subsys_state __rcu *css;
143 * Depth in hierarchy which this ID belongs to.
145 unsigned short depth;
147 * ID is freed by RCU. (and lookup routine is RCU safe.)
149 struct rcu_head rcu_head;
151 * Hierarchy of CSS ID belongs to.
153 unsigned short stack[0]; /* Array of Length (depth+1) */
156 /* The list of hierarchy roots */
158 static LIST_HEAD(cgroup_roots);
159 static int cgroup_root_count;
162 * Hierarchy ID allocation and mapping. It follows the same exclusion
163 * rules as other root ops - both cgroup_mutex and cgroup_root_mutex for
164 * writes, either for reads.
166 static DEFINE_IDR(cgroup_hierarchy_idr);
168 static struct cgroup_name root_cgroup_name = { .name = "/" };
171 * Assign a monotonically increasing serial number to cgroups. It
172 * guarantees cgroups with bigger numbers are newer than those with smaller
173 * numbers. Also, as cgroups are always appended to the parent's
174 * ->children list, it guarantees that sibling cgroups are always sorted in
175 * the ascending serial number order on the list. Protected by
178 static u64 cgroup_serial_nr_next = 1;
180 /* This flag indicates whether tasks in the fork and exit paths should
181 * check for fork/exit handlers to call. This avoids us having to do
182 * extra work in the fork/exit path if none of the subsystems need to
185 static int need_forkexit_callback __read_mostly;
187 static struct cftype cgroup_base_files[];
189 static void cgroup_destroy_css_killed(struct cgroup *cgrp);
190 static int cgroup_destroy_locked(struct cgroup *cgrp);
191 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
195 * cgroup_css - obtain a cgroup's css for the specified subsystem
196 * @cgrp: the cgroup of interest
197 * @ss: the subsystem of interest (%NULL returns the dummy_css)
199 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
200 * function must be called either under cgroup_mutex or rcu_read_lock() and
201 * the caller is responsible for pinning the returned css if it wants to
202 * keep accessing it outside the said locks. This function may return
203 * %NULL if @cgrp doesn't have @subsys_id enabled.
205 struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
206 struct cgroup_subsys *ss)
209 return rcu_dereference_check(cgrp->subsys[ss->subsys_id],
210 lockdep_is_held(&cgroup_mutex));
212 return &cgrp->dummy_css;
215 /* convenient tests for these bits */
216 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
218 return test_bit(CGRP_DEAD, &cgrp->flags);
222 * cgroup_is_descendant - test ancestry
223 * @cgrp: the cgroup to be tested
224 * @ancestor: possible ancestor of @cgrp
226 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
227 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
228 * and @ancestor are accessible.
230 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
233 if (cgrp == ancestor)
239 EXPORT_SYMBOL_GPL(cgroup_is_descendant);
241 static int cgroup_is_releasable(const struct cgroup *cgrp)
244 (1 << CGRP_RELEASABLE) |
245 (1 << CGRP_NOTIFY_ON_RELEASE);
246 return (cgrp->flags & bits) == bits;
249 static int notify_on_release(const struct cgroup *cgrp)
251 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
255 * for_each_subsys - iterate all loaded cgroup subsystems
256 * @ss: the iteration cursor
257 * @i: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
259 * Should be called under cgroup_mutex.
261 #define for_each_subsys(ss, i) \
262 for ((i) = 0; (i) < CGROUP_SUBSYS_COUNT; (i)++) \
263 if (({ lockdep_assert_held(&cgroup_mutex); \
264 !((ss) = cgroup_subsys[i]); })) { } \
268 * for_each_builtin_subsys - iterate all built-in cgroup subsystems
269 * @ss: the iteration cursor
270 * @i: the index of @ss, CGROUP_BUILTIN_SUBSYS_COUNT after reaching the end
272 * Bulit-in subsystems are always present and iteration itself doesn't
273 * require any synchronization.
275 #define for_each_builtin_subsys(ss, i) \
276 for ((i) = 0; (i) < CGROUP_BUILTIN_SUBSYS_COUNT && \
277 (((ss) = cgroup_subsys[i]) || true); (i)++)
279 /* iterate each subsystem attached to a hierarchy */
280 #define for_each_root_subsys(root, ss) \
281 list_for_each_entry((ss), &(root)->subsys_list, sibling)
283 /* iterate across the active hierarchies */
284 #define for_each_active_root(root) \
285 list_for_each_entry((root), &cgroup_roots, root_list)
287 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
289 return dentry->d_fsdata;
292 static inline struct cfent *__d_cfe(struct dentry *dentry)
294 return dentry->d_fsdata;
297 static inline struct cftype *__d_cft(struct dentry *dentry)
299 return __d_cfe(dentry)->type;
303 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
304 * @cgrp: the cgroup to be checked for liveness
306 * On success, returns true; the mutex should be later unlocked. On
307 * failure returns false with no lock held.
309 static bool cgroup_lock_live_group(struct cgroup *cgrp)
311 mutex_lock(&cgroup_mutex);
312 if (cgroup_is_dead(cgrp)) {
313 mutex_unlock(&cgroup_mutex);
319 /* the list of cgroups eligible for automatic release. Protected by
320 * release_list_lock */
321 static LIST_HEAD(release_list);
322 static DEFINE_RAW_SPINLOCK(release_list_lock);
323 static void cgroup_release_agent(struct work_struct *work);
324 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
325 static void check_for_release(struct cgroup *cgrp);
328 * A cgroup can be associated with multiple css_sets as different tasks may
329 * belong to different cgroups on different hierarchies. In the other
330 * direction, a css_set is naturally associated with multiple cgroups.
331 * This M:N relationship is represented by the following link structure
332 * which exists for each association and allows traversing the associations
335 struct cgrp_cset_link {
336 /* the cgroup and css_set this link associates */
338 struct css_set *cset;
340 /* list of cgrp_cset_links anchored at cgrp->cset_links */
341 struct list_head cset_link;
343 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
344 struct list_head cgrp_link;
347 /* The default css_set - used by init and its children prior to any
348 * hierarchies being mounted. It contains a pointer to the root state
349 * for each subsystem. Also used to anchor the list of css_sets. Not
350 * reference-counted, to improve performance when child cgroups
351 * haven't been created.
354 static struct css_set init_css_set;
355 static struct cgrp_cset_link init_cgrp_cset_link;
357 static int cgroup_init_idr(struct cgroup_subsys *ss,
358 struct cgroup_subsys_state *css);
361 * css_set_lock protects the list of css_set objects, and the chain of
362 * tasks off each css_set. Nests outside task->alloc_lock due to
363 * css_task_iter_start().
365 static DEFINE_RWLOCK(css_set_lock);
366 static int css_set_count;
369 * hash table for cgroup groups. This improves the performance to find
370 * an existing css_set. This hash doesn't (currently) take into
371 * account cgroups in empty hierarchies.
373 #define CSS_SET_HASH_BITS 7
374 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
376 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
378 unsigned long key = 0UL;
379 struct cgroup_subsys *ss;
382 for_each_subsys(ss, i)
383 key += (unsigned long)css[i];
384 key = (key >> 16) ^ key;
390 * We don't maintain the lists running through each css_set to its task
391 * until after the first call to css_task_iter_start(). This reduces the
392 * fork()/exit() overhead for people who have cgroups compiled into their
393 * kernel but not actually in use.
395 static int use_task_css_set_links __read_mostly;
397 static void __put_css_set(struct css_set *cset, int taskexit)
399 struct cgrp_cset_link *link, *tmp_link;
402 * Ensure that the refcount doesn't hit zero while any readers
403 * can see it. Similar to atomic_dec_and_lock(), but for an
406 if (atomic_add_unless(&cset->refcount, -1, 1))
408 write_lock(&css_set_lock);
409 if (!atomic_dec_and_test(&cset->refcount)) {
410 write_unlock(&css_set_lock);
414 /* This css_set is dead. unlink it and release cgroup refcounts */
415 hash_del(&cset->hlist);
418 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
419 struct cgroup *cgrp = link->cgrp;
421 list_del(&link->cset_link);
422 list_del(&link->cgrp_link);
424 /* @cgrp can't go away while we're holding css_set_lock */
425 if (list_empty(&cgrp->cset_links) && notify_on_release(cgrp)) {
427 set_bit(CGRP_RELEASABLE, &cgrp->flags);
428 check_for_release(cgrp);
434 write_unlock(&css_set_lock);
435 kfree_rcu(cset, rcu_head);
439 * refcounted get/put for css_set objects
441 static inline void get_css_set(struct css_set *cset)
443 atomic_inc(&cset->refcount);
446 static inline void put_css_set(struct css_set *cset)
448 __put_css_set(cset, 0);
451 static inline void put_css_set_taskexit(struct css_set *cset)
453 __put_css_set(cset, 1);
457 * compare_css_sets - helper function for find_existing_css_set().
458 * @cset: candidate css_set being tested
459 * @old_cset: existing css_set for a task
460 * @new_cgrp: cgroup that's being entered by the task
461 * @template: desired set of css pointers in css_set (pre-calculated)
463 * Returns true if "cset" matches "old_cset" except for the hierarchy
464 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
466 static bool compare_css_sets(struct css_set *cset,
467 struct css_set *old_cset,
468 struct cgroup *new_cgrp,
469 struct cgroup_subsys_state *template[])
471 struct list_head *l1, *l2;
473 if (memcmp(template, cset->subsys, sizeof(cset->subsys))) {
474 /* Not all subsystems matched */
479 * Compare cgroup pointers in order to distinguish between
480 * different cgroups in heirarchies with no subsystems. We
481 * could get by with just this check alone (and skip the
482 * memcmp above) but on most setups the memcmp check will
483 * avoid the need for this more expensive check on almost all
487 l1 = &cset->cgrp_links;
488 l2 = &old_cset->cgrp_links;
490 struct cgrp_cset_link *link1, *link2;
491 struct cgroup *cgrp1, *cgrp2;
495 /* See if we reached the end - both lists are equal length. */
496 if (l1 == &cset->cgrp_links) {
497 BUG_ON(l2 != &old_cset->cgrp_links);
500 BUG_ON(l2 == &old_cset->cgrp_links);
502 /* Locate the cgroups associated with these links. */
503 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
504 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
507 /* Hierarchies should be linked in the same order. */
508 BUG_ON(cgrp1->root != cgrp2->root);
511 * If this hierarchy is the hierarchy of the cgroup
512 * that's changing, then we need to check that this
513 * css_set points to the new cgroup; if it's any other
514 * hierarchy, then this css_set should point to the
515 * same cgroup as the old css_set.
517 if (cgrp1->root == new_cgrp->root) {
518 if (cgrp1 != new_cgrp)
529 * find_existing_css_set - init css array and find the matching css_set
530 * @old_cset: the css_set that we're using before the cgroup transition
531 * @cgrp: the cgroup that we're moving into
532 * @template: out param for the new set of csses, should be clear on entry
534 static struct css_set *find_existing_css_set(struct css_set *old_cset,
536 struct cgroup_subsys_state *template[])
538 struct cgroupfs_root *root = cgrp->root;
539 struct cgroup_subsys *ss;
540 struct css_set *cset;
545 * Build the set of subsystem state objects that we want to see in the
546 * new css_set. while subsystems can change globally, the entries here
547 * won't change, so no need for locking.
549 for_each_subsys(ss, i) {
550 if (root->subsys_mask & (1UL << i)) {
551 /* Subsystem is in this hierarchy. So we want
552 * the subsystem state from the new
554 template[i] = cgroup_css(cgrp, ss);
556 /* Subsystem is not in this hierarchy, so we
557 * don't want to change the subsystem state */
558 template[i] = old_cset->subsys[i];
562 key = css_set_hash(template);
563 hash_for_each_possible(css_set_table, cset, hlist, key) {
564 if (!compare_css_sets(cset, old_cset, cgrp, template))
567 /* This css_set matches what we need */
571 /* No existing cgroup group matched */
575 static void free_cgrp_cset_links(struct list_head *links_to_free)
577 struct cgrp_cset_link *link, *tmp_link;
579 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
580 list_del(&link->cset_link);
586 * allocate_cgrp_cset_links - allocate cgrp_cset_links
587 * @count: the number of links to allocate
588 * @tmp_links: list_head the allocated links are put on
590 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
591 * through ->cset_link. Returns 0 on success or -errno.
593 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
595 struct cgrp_cset_link *link;
598 INIT_LIST_HEAD(tmp_links);
600 for (i = 0; i < count; i++) {
601 link = kzalloc(sizeof(*link), GFP_KERNEL);
603 free_cgrp_cset_links(tmp_links);
606 list_add(&link->cset_link, tmp_links);
612 * link_css_set - a helper function to link a css_set to a cgroup
613 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
614 * @cset: the css_set to be linked
615 * @cgrp: the destination cgroup
617 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
620 struct cgrp_cset_link *link;
622 BUG_ON(list_empty(tmp_links));
623 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
626 list_move(&link->cset_link, &cgrp->cset_links);
628 * Always add links to the tail of the list so that the list
629 * is sorted by order of hierarchy creation
631 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
635 * find_css_set - return a new css_set with one cgroup updated
636 * @old_cset: the baseline css_set
637 * @cgrp: the cgroup to be updated
639 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
640 * substituted into the appropriate hierarchy.
642 static struct css_set *find_css_set(struct css_set *old_cset,
645 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
646 struct css_set *cset;
647 struct list_head tmp_links;
648 struct cgrp_cset_link *link;
651 lockdep_assert_held(&cgroup_mutex);
653 /* First see if we already have a cgroup group that matches
655 read_lock(&css_set_lock);
656 cset = find_existing_css_set(old_cset, cgrp, template);
659 read_unlock(&css_set_lock);
664 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
668 /* Allocate all the cgrp_cset_link objects that we'll need */
669 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
674 atomic_set(&cset->refcount, 1);
675 INIT_LIST_HEAD(&cset->cgrp_links);
676 INIT_LIST_HEAD(&cset->tasks);
677 INIT_HLIST_NODE(&cset->hlist);
679 /* Copy the set of subsystem state objects generated in
680 * find_existing_css_set() */
681 memcpy(cset->subsys, template, sizeof(cset->subsys));
683 write_lock(&css_set_lock);
684 /* Add reference counts and links from the new css_set. */
685 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
686 struct cgroup *c = link->cgrp;
688 if (c->root == cgrp->root)
690 link_css_set(&tmp_links, cset, c);
693 BUG_ON(!list_empty(&tmp_links));
697 /* Add this cgroup group to the hash table */
698 key = css_set_hash(cset->subsys);
699 hash_add(css_set_table, &cset->hlist, key);
701 write_unlock(&css_set_lock);
707 * Return the cgroup for "task" from the given hierarchy. Must be
708 * called with cgroup_mutex held.
710 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
711 struct cgroupfs_root *root)
713 struct css_set *cset;
714 struct cgroup *res = NULL;
716 BUG_ON(!mutex_is_locked(&cgroup_mutex));
717 read_lock(&css_set_lock);
719 * No need to lock the task - since we hold cgroup_mutex the
720 * task can't change groups, so the only thing that can happen
721 * is that it exits and its css is set back to init_css_set.
723 cset = task_css_set(task);
724 if (cset == &init_css_set) {
725 res = &root->top_cgroup;
727 struct cgrp_cset_link *link;
729 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
730 struct cgroup *c = link->cgrp;
732 if (c->root == root) {
738 read_unlock(&css_set_lock);
744 * There is one global cgroup mutex. We also require taking
745 * task_lock() when dereferencing a task's cgroup subsys pointers.
746 * See "The task_lock() exception", at the end of this comment.
748 * A task must hold cgroup_mutex to modify cgroups.
750 * Any task can increment and decrement the count field without lock.
751 * So in general, code holding cgroup_mutex can't rely on the count
752 * field not changing. However, if the count goes to zero, then only
753 * cgroup_attach_task() can increment it again. Because a count of zero
754 * means that no tasks are currently attached, therefore there is no
755 * way a task attached to that cgroup can fork (the other way to
756 * increment the count). So code holding cgroup_mutex can safely
757 * assume that if the count is zero, it will stay zero. Similarly, if
758 * a task holds cgroup_mutex on a cgroup with zero count, it
759 * knows that the cgroup won't be removed, as cgroup_rmdir()
762 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
763 * (usually) take cgroup_mutex. These are the two most performance
764 * critical pieces of code here. The exception occurs on cgroup_exit(),
765 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
766 * is taken, and if the cgroup count is zero, a usermode call made
767 * to the release agent with the name of the cgroup (path relative to
768 * the root of cgroup file system) as the argument.
770 * A cgroup can only be deleted if both its 'count' of using tasks
771 * is zero, and its list of 'children' cgroups is empty. Since all
772 * tasks in the system use _some_ cgroup, and since there is always at
773 * least one task in the system (init, pid == 1), therefore, top_cgroup
774 * always has either children cgroups and/or using tasks. So we don't
775 * need a special hack to ensure that top_cgroup cannot be deleted.
777 * The task_lock() exception
779 * The need for this exception arises from the action of
780 * cgroup_attach_task(), which overwrites one task's cgroup pointer with
781 * another. It does so using cgroup_mutex, however there are
782 * several performance critical places that need to reference
783 * task->cgroup without the expense of grabbing a system global
784 * mutex. Therefore except as noted below, when dereferencing or, as
785 * in cgroup_attach_task(), modifying a task's cgroup pointer we use
786 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
787 * the task_struct routinely used for such matters.
789 * P.S. One more locking exception. RCU is used to guard the
790 * update of a tasks cgroup pointer by cgroup_attach_task()
794 * A couple of forward declarations required, due to cyclic reference loop:
795 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
796 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
800 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode);
801 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
802 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask);
803 static const struct inode_operations cgroup_dir_inode_operations;
804 static const struct file_operations proc_cgroupstats_operations;
806 static struct backing_dev_info cgroup_backing_dev_info = {
808 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
811 static int alloc_css_id(struct cgroup_subsys_state *child_css);
813 static struct inode *cgroup_new_inode(umode_t mode, struct super_block *sb)
815 struct inode *inode = new_inode(sb);
818 inode->i_ino = get_next_ino();
819 inode->i_mode = mode;
820 inode->i_uid = current_fsuid();
821 inode->i_gid = current_fsgid();
822 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
823 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
828 static struct cgroup_name *cgroup_alloc_name(struct dentry *dentry)
830 struct cgroup_name *name;
832 name = kmalloc(sizeof(*name) + dentry->d_name.len + 1, GFP_KERNEL);
835 strcpy(name->name, dentry->d_name.name);
839 static void cgroup_free_fn(struct work_struct *work)
841 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
843 mutex_lock(&cgroup_mutex);
844 cgrp->root->number_of_cgroups--;
845 mutex_unlock(&cgroup_mutex);
848 * We get a ref to the parent's dentry, and put the ref when
849 * this cgroup is being freed, so it's guaranteed that the
850 * parent won't be destroyed before its children.
852 dput(cgrp->parent->dentry);
855 * Drop the active superblock reference that we took when we
856 * created the cgroup. This will free cgrp->root, if we are
857 * holding the last reference to @sb.
859 deactivate_super(cgrp->root->sb);
862 * if we're getting rid of the cgroup, refcount should ensure
863 * that there are no pidlists left.
865 BUG_ON(!list_empty(&cgrp->pidlists));
867 simple_xattrs_free(&cgrp->xattrs);
869 kfree(rcu_dereference_raw(cgrp->name));
873 static void cgroup_free_rcu(struct rcu_head *head)
875 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
877 INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
878 schedule_work(&cgrp->destroy_work);
881 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
883 /* is dentry a directory ? if so, kfree() associated cgroup */
884 if (S_ISDIR(inode->i_mode)) {
885 struct cgroup *cgrp = dentry->d_fsdata;
887 BUG_ON(!(cgroup_is_dead(cgrp)));
888 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
890 struct cfent *cfe = __d_cfe(dentry);
891 struct cgroup *cgrp = dentry->d_parent->d_fsdata;
893 WARN_ONCE(!list_empty(&cfe->node) &&
894 cgrp != &cgrp->root->top_cgroup,
895 "cfe still linked for %s\n", cfe->type->name);
896 simple_xattrs_free(&cfe->xattrs);
902 static int cgroup_delete(const struct dentry *d)
907 static void remove_dir(struct dentry *d)
909 struct dentry *parent = dget(d->d_parent);
912 simple_rmdir(parent->d_inode, d);
916 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
920 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
921 lockdep_assert_held(&cgroup_mutex);
924 * If we're doing cleanup due to failure of cgroup_create(),
925 * the corresponding @cfe may not exist.
927 list_for_each_entry(cfe, &cgrp->files, node) {
928 struct dentry *d = cfe->dentry;
930 if (cft && cfe->type != cft)
935 simple_unlink(cgrp->dentry->d_inode, d);
936 list_del_init(&cfe->node);
944 * cgroup_clear_dir - remove subsys files in a cgroup directory
945 * @cgrp: target cgroup
946 * @subsys_mask: mask of the subsystem ids whose files should be removed
948 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned long subsys_mask)
950 struct cgroup_subsys *ss;
953 for_each_subsys(ss, i) {
954 struct cftype_set *set;
956 if (!test_bit(i, &subsys_mask))
958 list_for_each_entry(set, &ss->cftsets, node)
959 cgroup_addrm_files(cgrp, set->cfts, false);
964 * NOTE : the dentry must have been dget()'ed
966 static void cgroup_d_remove_dir(struct dentry *dentry)
968 struct dentry *parent;
970 parent = dentry->d_parent;
971 spin_lock(&parent->d_lock);
972 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
973 list_del_init(&dentry->d_u.d_child);
974 spin_unlock(&dentry->d_lock);
975 spin_unlock(&parent->d_lock);
980 * Call with cgroup_mutex held. Drops reference counts on modules, including
981 * any duplicate ones that parse_cgroupfs_options took. If this function
982 * returns an error, no reference counts are touched.
984 static int rebind_subsystems(struct cgroupfs_root *root,
985 unsigned long added_mask, unsigned removed_mask)
987 struct cgroup *cgrp = &root->top_cgroup;
988 struct cgroup_subsys *ss;
989 unsigned long pinned = 0;
992 BUG_ON(!mutex_is_locked(&cgroup_mutex));
993 BUG_ON(!mutex_is_locked(&cgroup_root_mutex));
995 /* Check that any added subsystems are currently free */
996 for_each_subsys(ss, i) {
997 if (!(added_mask & (1 << i)))
1000 /* is the subsystem mounted elsewhere? */
1001 if (ss->root != &cgroup_dummy_root) {
1006 /* pin the module */
1007 if (!try_module_get(ss->module)) {
1014 /* subsys could be missing if unloaded between parsing and here */
1015 if (added_mask != pinned) {
1020 ret = cgroup_populate_dir(cgrp, added_mask);
1025 * Nothing can fail from this point on. Remove files for the
1026 * removed subsystems and rebind each subsystem.
1028 cgroup_clear_dir(cgrp, removed_mask);
1030 for_each_subsys(ss, i) {
1031 unsigned long bit = 1UL << i;
1033 if (bit & added_mask) {
1034 /* We're binding this subsystem to this hierarchy */
1035 BUG_ON(cgroup_css(cgrp, ss));
1036 BUG_ON(!cgroup_css(cgroup_dummy_top, ss));
1037 BUG_ON(cgroup_css(cgroup_dummy_top, ss)->cgroup != cgroup_dummy_top);
1039 rcu_assign_pointer(cgrp->subsys[i],
1040 cgroup_css(cgroup_dummy_top, ss));
1041 cgroup_css(cgrp, ss)->cgroup = cgrp;
1043 list_move(&ss->sibling, &root->subsys_list);
1046 ss->bind(cgroup_css(cgrp, ss));
1048 /* refcount was already taken, and we're keeping it */
1049 root->subsys_mask |= bit;
1050 } else if (bit & removed_mask) {
1051 /* We're removing this subsystem */
1052 BUG_ON(cgroup_css(cgrp, ss) != cgroup_css(cgroup_dummy_top, ss));
1053 BUG_ON(cgroup_css(cgrp, ss)->cgroup != cgrp);
1056 ss->bind(cgroup_css(cgroup_dummy_top, ss));
1058 cgroup_css(cgroup_dummy_top, ss)->cgroup = cgroup_dummy_top;
1059 RCU_INIT_POINTER(cgrp->subsys[i], NULL);
1061 cgroup_subsys[i]->root = &cgroup_dummy_root;
1062 list_move(&ss->sibling, &cgroup_dummy_root.subsys_list);
1064 /* subsystem is now free - drop reference on module */
1065 module_put(ss->module);
1066 root->subsys_mask &= ~bit;
1071 * Mark @root has finished binding subsystems. @root->subsys_mask
1072 * now matches the bound subsystems.
1074 root->flags |= CGRP_ROOT_SUBSYS_BOUND;
1079 for_each_subsys(ss, i)
1080 if (pinned & (1 << i))
1081 module_put(ss->module);
1085 static int cgroup_show_options(struct seq_file *seq, struct dentry *dentry)
1087 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
1088 struct cgroup_subsys *ss;
1090 mutex_lock(&cgroup_root_mutex);
1091 for_each_root_subsys(root, ss)
1092 seq_printf(seq, ",%s", ss->name);
1093 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1094 seq_puts(seq, ",sane_behavior");
1095 if (root->flags & CGRP_ROOT_NOPREFIX)
1096 seq_puts(seq, ",noprefix");
1097 if (root->flags & CGRP_ROOT_XATTR)
1098 seq_puts(seq, ",xattr");
1099 if (strlen(root->release_agent_path))
1100 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1101 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1102 seq_puts(seq, ",clone_children");
1103 if (strlen(root->name))
1104 seq_printf(seq, ",name=%s", root->name);
1105 mutex_unlock(&cgroup_root_mutex);
1109 struct cgroup_sb_opts {
1110 unsigned long subsys_mask;
1111 unsigned long flags;
1112 char *release_agent;
1113 bool cpuset_clone_children;
1115 /* User explicitly requested empty subsystem */
1118 struct cgroupfs_root *new_root;
1123 * Convert a hierarchy specifier into a bitmask of subsystems and
1124 * flags. Call with cgroup_mutex held to protect the cgroup_subsys[]
1125 * array. This function takes refcounts on subsystems to be used, unless it
1126 * returns error, in which case no refcounts are taken.
1128 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1130 char *token, *o = data;
1131 bool all_ss = false, one_ss = false;
1132 unsigned long mask = (unsigned long)-1;
1133 struct cgroup_subsys *ss;
1136 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1138 #ifdef CONFIG_CPUSETS
1139 mask = ~(1UL << cpuset_subsys_id);
1142 memset(opts, 0, sizeof(*opts));
1144 while ((token = strsep(&o, ",")) != NULL) {
1147 if (!strcmp(token, "none")) {
1148 /* Explicitly have no subsystems */
1152 if (!strcmp(token, "all")) {
1153 /* Mutually exclusive option 'all' + subsystem name */
1159 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1160 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1163 if (!strcmp(token, "noprefix")) {
1164 opts->flags |= CGRP_ROOT_NOPREFIX;
1167 if (!strcmp(token, "clone_children")) {
1168 opts->cpuset_clone_children = true;
1171 if (!strcmp(token, "xattr")) {
1172 opts->flags |= CGRP_ROOT_XATTR;
1175 if (!strncmp(token, "release_agent=", 14)) {
1176 /* Specifying two release agents is forbidden */
1177 if (opts->release_agent)
1179 opts->release_agent =
1180 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1181 if (!opts->release_agent)
1185 if (!strncmp(token, "name=", 5)) {
1186 const char *name = token + 5;
1187 /* Can't specify an empty name */
1190 /* Must match [\w.-]+ */
1191 for (i = 0; i < strlen(name); i++) {
1195 if ((c == '.') || (c == '-') || (c == '_'))
1199 /* Specifying two names is forbidden */
1202 opts->name = kstrndup(name,
1203 MAX_CGROUP_ROOT_NAMELEN - 1,
1211 for_each_subsys(ss, i) {
1212 if (strcmp(token, ss->name))
1217 /* Mutually exclusive option 'all' + subsystem name */
1220 set_bit(i, &opts->subsys_mask);
1225 if (i == CGROUP_SUBSYS_COUNT)
1230 * If the 'all' option was specified select all the subsystems,
1231 * otherwise if 'none', 'name=' and a subsystem name options
1232 * were not specified, let's default to 'all'
1234 if (all_ss || (!one_ss && !opts->none && !opts->name))
1235 for_each_subsys(ss, i)
1237 set_bit(i, &opts->subsys_mask);
1239 /* Consistency checks */
1241 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1242 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1244 if (opts->flags & CGRP_ROOT_NOPREFIX) {
1245 pr_err("cgroup: sane_behavior: noprefix is not allowed\n");
1249 if (opts->cpuset_clone_children) {
1250 pr_err("cgroup: sane_behavior: clone_children is not allowed\n");
1256 * Option noprefix was introduced just for backward compatibility
1257 * with the old cpuset, so we allow noprefix only if mounting just
1258 * the cpuset subsystem.
1260 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1264 /* Can't specify "none" and some subsystems */
1265 if (opts->subsys_mask && opts->none)
1269 * We either have to specify by name or by subsystems. (So all
1270 * empty hierarchies must have a name).
1272 if (!opts->subsys_mask && !opts->name)
1278 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1281 struct cgroupfs_root *root = sb->s_fs_info;
1282 struct cgroup *cgrp = &root->top_cgroup;
1283 struct cgroup_sb_opts opts;
1284 unsigned long added_mask, removed_mask;
1286 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1287 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1291 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1292 mutex_lock(&cgroup_mutex);
1293 mutex_lock(&cgroup_root_mutex);
1295 /* See what subsystems are wanted */
1296 ret = parse_cgroupfs_options(data, &opts);
1300 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1301 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1302 task_tgid_nr(current), current->comm);
1304 added_mask = opts.subsys_mask & ~root->subsys_mask;
1305 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1307 /* Don't allow flags or name to change at remount */
1308 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1309 (opts.name && strcmp(opts.name, root->name))) {
1310 pr_err("cgroup: option or name mismatch, new: 0x%lx \"%s\", old: 0x%lx \"%s\"\n",
1311 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1312 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1317 /* remounting is not allowed for populated hierarchies */
1318 if (root->number_of_cgroups > 1) {
1323 ret = rebind_subsystems(root, added_mask, removed_mask);
1327 if (opts.release_agent)
1328 strcpy(root->release_agent_path, opts.release_agent);
1330 kfree(opts.release_agent);
1332 mutex_unlock(&cgroup_root_mutex);
1333 mutex_unlock(&cgroup_mutex);
1334 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1338 static const struct super_operations cgroup_ops = {
1339 .statfs = simple_statfs,
1340 .drop_inode = generic_delete_inode,
1341 .show_options = cgroup_show_options,
1342 .remount_fs = cgroup_remount,
1345 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1347 INIT_LIST_HEAD(&cgrp->sibling);
1348 INIT_LIST_HEAD(&cgrp->children);
1349 INIT_LIST_HEAD(&cgrp->files);
1350 INIT_LIST_HEAD(&cgrp->cset_links);
1351 INIT_LIST_HEAD(&cgrp->release_list);
1352 INIT_LIST_HEAD(&cgrp->pidlists);
1353 mutex_init(&cgrp->pidlist_mutex);
1354 cgrp->dummy_css.cgroup = cgrp;
1355 INIT_LIST_HEAD(&cgrp->event_list);
1356 spin_lock_init(&cgrp->event_list_lock);
1357 simple_xattrs_init(&cgrp->xattrs);
1360 static void init_cgroup_root(struct cgroupfs_root *root)
1362 struct cgroup *cgrp = &root->top_cgroup;
1364 INIT_LIST_HEAD(&root->subsys_list);
1365 INIT_LIST_HEAD(&root->root_list);
1366 root->number_of_cgroups = 1;
1368 RCU_INIT_POINTER(cgrp->name, &root_cgroup_name);
1369 init_cgroup_housekeeping(cgrp);
1370 idr_init(&root->cgroup_idr);
1373 static int cgroup_init_root_id(struct cgroupfs_root *root, int start, int end)
1377 lockdep_assert_held(&cgroup_mutex);
1378 lockdep_assert_held(&cgroup_root_mutex);
1380 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, start, end,
1385 root->hierarchy_id = id;
1389 static void cgroup_exit_root_id(struct cgroupfs_root *root)
1391 lockdep_assert_held(&cgroup_mutex);
1392 lockdep_assert_held(&cgroup_root_mutex);
1394 if (root->hierarchy_id) {
1395 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1396 root->hierarchy_id = 0;
1400 static int cgroup_test_super(struct super_block *sb, void *data)
1402 struct cgroup_sb_opts *opts = data;
1403 struct cgroupfs_root *root = sb->s_fs_info;
1405 /* If we asked for a name then it must match */
1406 if (opts->name && strcmp(opts->name, root->name))
1410 * If we asked for subsystems (or explicitly for no
1411 * subsystems) then they must match
1413 if ((opts->subsys_mask || opts->none)
1414 && (opts->subsys_mask != root->subsys_mask))
1420 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1422 struct cgroupfs_root *root;
1424 if (!opts->subsys_mask && !opts->none)
1427 root = kzalloc(sizeof(*root), GFP_KERNEL);
1429 return ERR_PTR(-ENOMEM);
1431 init_cgroup_root(root);
1434 * We need to set @root->subsys_mask now so that @root can be
1435 * matched by cgroup_test_super() before it finishes
1436 * initialization; otherwise, competing mounts with the same
1437 * options may try to bind the same subsystems instead of waiting
1438 * for the first one leading to unexpected mount errors.
1439 * SUBSYS_BOUND will be set once actual binding is complete.
1441 root->subsys_mask = opts->subsys_mask;
1442 root->flags = opts->flags;
1443 if (opts->release_agent)
1444 strcpy(root->release_agent_path, opts->release_agent);
1446 strcpy(root->name, opts->name);
1447 if (opts->cpuset_clone_children)
1448 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1452 static void cgroup_free_root(struct cgroupfs_root *root)
1455 /* hierarhcy ID shoulid already have been released */
1456 WARN_ON_ONCE(root->hierarchy_id);
1458 idr_destroy(&root->cgroup_idr);
1463 static int cgroup_set_super(struct super_block *sb, void *data)
1466 struct cgroup_sb_opts *opts = data;
1468 /* If we don't have a new root, we can't set up a new sb */
1469 if (!opts->new_root)
1472 BUG_ON(!opts->subsys_mask && !opts->none);
1474 ret = set_anon_super(sb, NULL);
1478 sb->s_fs_info = opts->new_root;
1479 opts->new_root->sb = sb;
1481 sb->s_blocksize = PAGE_CACHE_SIZE;
1482 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1483 sb->s_magic = CGROUP_SUPER_MAGIC;
1484 sb->s_op = &cgroup_ops;
1489 static int cgroup_get_rootdir(struct super_block *sb)
1491 static const struct dentry_operations cgroup_dops = {
1492 .d_iput = cgroup_diput,
1493 .d_delete = cgroup_delete,
1496 struct inode *inode =
1497 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1502 inode->i_fop = &simple_dir_operations;
1503 inode->i_op = &cgroup_dir_inode_operations;
1504 /* directories start off with i_nlink == 2 (for "." entry) */
1506 sb->s_root = d_make_root(inode);
1509 /* for everything else we want ->d_op set */
1510 sb->s_d_op = &cgroup_dops;
1514 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1515 int flags, const char *unused_dev_name,
1518 struct cgroup_sb_opts opts;
1519 struct cgroupfs_root *root;
1521 struct super_block *sb;
1522 struct cgroupfs_root *new_root;
1523 struct list_head tmp_links;
1524 struct inode *inode;
1525 const struct cred *cred;
1527 /* First find the desired set of subsystems */
1528 mutex_lock(&cgroup_mutex);
1529 ret = parse_cgroupfs_options(data, &opts);
1530 mutex_unlock(&cgroup_mutex);
1535 * Allocate a new cgroup root. We may not need it if we're
1536 * reusing an existing hierarchy.
1538 new_root = cgroup_root_from_opts(&opts);
1539 if (IS_ERR(new_root)) {
1540 ret = PTR_ERR(new_root);
1543 opts.new_root = new_root;
1545 /* Locate an existing or new sb for this hierarchy */
1546 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1549 cgroup_free_root(opts.new_root);
1553 root = sb->s_fs_info;
1555 if (root == opts.new_root) {
1556 /* We used the new root structure, so this is a new hierarchy */
1557 struct cgroup *root_cgrp = &root->top_cgroup;
1558 struct cgroupfs_root *existing_root;
1560 struct css_set *cset;
1562 BUG_ON(sb->s_root != NULL);
1564 ret = cgroup_get_rootdir(sb);
1566 goto drop_new_super;
1567 inode = sb->s_root->d_inode;
1569 mutex_lock(&inode->i_mutex);
1570 mutex_lock(&cgroup_mutex);
1571 mutex_lock(&cgroup_root_mutex);
1573 root_cgrp->id = idr_alloc(&root->cgroup_idr, root_cgrp,
1575 if (root_cgrp->id < 0)
1578 /* Check for name clashes with existing mounts */
1580 if (strlen(root->name))
1581 for_each_active_root(existing_root)
1582 if (!strcmp(existing_root->name, root->name))
1586 * We're accessing css_set_count without locking
1587 * css_set_lock here, but that's OK - it can only be
1588 * increased by someone holding cgroup_lock, and
1589 * that's us. The worst that can happen is that we
1590 * have some link structures left over
1592 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1596 /* ID 0 is reserved for dummy root, 1 for unified hierarchy */
1597 ret = cgroup_init_root_id(root, 2, 0);
1601 sb->s_root->d_fsdata = root_cgrp;
1602 root_cgrp->dentry = sb->s_root;
1605 * We're inside get_sb() and will call lookup_one_len() to
1606 * create the root files, which doesn't work if SELinux is
1607 * in use. The following cred dancing somehow works around
1608 * it. See 2ce9738ba ("cgroupfs: use init_cred when
1609 * populating new cgroupfs mount") for more details.
1611 cred = override_creds(&init_cred);
1613 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1617 ret = rebind_subsystems(root, root->subsys_mask, 0);
1624 * There must be no failure case after here, since rebinding
1625 * takes care of subsystems' refcounts, which are explicitly
1626 * dropped in the failure exit path.
1629 list_add(&root->root_list, &cgroup_roots);
1630 cgroup_root_count++;
1632 /* Link the top cgroup in this hierarchy into all
1633 * the css_set objects */
1634 write_lock(&css_set_lock);
1635 hash_for_each(css_set_table, i, cset, hlist)
1636 link_css_set(&tmp_links, cset, root_cgrp);
1637 write_unlock(&css_set_lock);
1639 free_cgrp_cset_links(&tmp_links);
1641 BUG_ON(!list_empty(&root_cgrp->children));
1642 BUG_ON(root->number_of_cgroups != 1);
1644 mutex_unlock(&cgroup_root_mutex);
1645 mutex_unlock(&cgroup_mutex);
1646 mutex_unlock(&inode->i_mutex);
1649 * We re-used an existing hierarchy - the new root (if
1650 * any) is not needed
1652 cgroup_free_root(opts.new_root);
1654 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1655 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1656 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1658 goto drop_new_super;
1660 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1665 kfree(opts.release_agent);
1667 return dget(sb->s_root);
1670 free_cgrp_cset_links(&tmp_links);
1671 cgroup_addrm_files(&root->top_cgroup, cgroup_base_files, false);
1674 cgroup_exit_root_id(root);
1675 mutex_unlock(&cgroup_root_mutex);
1676 mutex_unlock(&cgroup_mutex);
1677 mutex_unlock(&inode->i_mutex);
1679 deactivate_locked_super(sb);
1681 kfree(opts.release_agent);
1683 return ERR_PTR(ret);
1686 static void cgroup_kill_sb(struct super_block *sb) {
1687 struct cgroupfs_root *root = sb->s_fs_info;
1688 struct cgroup *cgrp = &root->top_cgroup;
1689 struct cgrp_cset_link *link, *tmp_link;
1694 BUG_ON(root->number_of_cgroups != 1);
1695 BUG_ON(!list_empty(&cgrp->children));
1697 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1698 mutex_lock(&cgroup_mutex);
1699 mutex_lock(&cgroup_root_mutex);
1701 /* Rebind all subsystems back to the default hierarchy */
1702 if (root->flags & CGRP_ROOT_SUBSYS_BOUND) {
1703 ret = rebind_subsystems(root, 0, root->subsys_mask);
1704 /* Shouldn't be able to fail ... */
1709 * Release all the links from cset_links to this hierarchy's
1712 write_lock(&css_set_lock);
1714 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1715 list_del(&link->cset_link);
1716 list_del(&link->cgrp_link);
1719 write_unlock(&css_set_lock);
1721 if (!list_empty(&root->root_list)) {
1722 list_del(&root->root_list);
1723 cgroup_root_count--;
1726 cgroup_exit_root_id(root);
1728 mutex_unlock(&cgroup_root_mutex);
1729 mutex_unlock(&cgroup_mutex);
1730 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1732 simple_xattrs_free(&cgrp->xattrs);
1734 kill_litter_super(sb);
1735 cgroup_free_root(root);
1738 static struct file_system_type cgroup_fs_type = {
1740 .mount = cgroup_mount,
1741 .kill_sb = cgroup_kill_sb,
1744 static struct kobject *cgroup_kobj;
1747 * cgroup_path - generate the path of a cgroup
1748 * @cgrp: the cgroup in question
1749 * @buf: the buffer to write the path into
1750 * @buflen: the length of the buffer
1752 * Writes path of cgroup into buf. Returns 0 on success, -errno on error.
1754 * We can't generate cgroup path using dentry->d_name, as accessing
1755 * dentry->name must be protected by irq-unsafe dentry->d_lock or parent
1756 * inode's i_mutex, while on the other hand cgroup_path() can be called
1757 * with some irq-safe spinlocks held.
1759 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1761 int ret = -ENAMETOOLONG;
1764 if (!cgrp->parent) {
1765 if (strlcpy(buf, "/", buflen) >= buflen)
1766 return -ENAMETOOLONG;
1770 start = buf + buflen - 1;
1775 const char *name = cgroup_name(cgrp);
1779 if ((start -= len) < buf)
1781 memcpy(start, name, len);
1787 cgrp = cgrp->parent;
1788 } while (cgrp->parent);
1790 memmove(buf, start, buf + buflen - start);
1795 EXPORT_SYMBOL_GPL(cgroup_path);
1798 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1799 * @task: target task
1800 * @buf: the buffer to write the path into
1801 * @buflen: the length of the buffer
1803 * Determine @task's cgroup on the first (the one with the lowest non-zero
1804 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1805 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1806 * cgroup controller callbacks.
1808 * Returns 0 on success, fails with -%ENAMETOOLONG if @buflen is too short.
1810 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1812 struct cgroupfs_root *root;
1813 struct cgroup *cgrp;
1814 int hierarchy_id = 1, ret = 0;
1817 return -ENAMETOOLONG;
1819 mutex_lock(&cgroup_mutex);
1821 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1824 cgrp = task_cgroup_from_root(task, root);
1825 ret = cgroup_path(cgrp, buf, buflen);
1827 /* if no hierarchy exists, everyone is in "/" */
1828 memcpy(buf, "/", 2);
1831 mutex_unlock(&cgroup_mutex);
1834 EXPORT_SYMBOL_GPL(task_cgroup_path);
1837 * Control Group taskset
1839 struct task_and_cgroup {
1840 struct task_struct *task;
1841 struct cgroup *cgrp;
1842 struct css_set *cset;
1845 struct cgroup_taskset {
1846 struct task_and_cgroup single;
1847 struct flex_array *tc_array;
1850 struct cgroup *cur_cgrp;
1854 * cgroup_taskset_first - reset taskset and return the first task
1855 * @tset: taskset of interest
1857 * @tset iteration is initialized and the first task is returned.
1859 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1861 if (tset->tc_array) {
1863 return cgroup_taskset_next(tset);
1865 tset->cur_cgrp = tset->single.cgrp;
1866 return tset->single.task;
1869 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1872 * cgroup_taskset_next - iterate to the next task in taskset
1873 * @tset: taskset of interest
1875 * Return the next task in @tset. Iteration must have been initialized
1876 * with cgroup_taskset_first().
1878 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1880 struct task_and_cgroup *tc;
1882 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1885 tc = flex_array_get(tset->tc_array, tset->idx++);
1886 tset->cur_cgrp = tc->cgrp;
1889 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1892 * cgroup_taskset_cur_css - return the matching css for the current task
1893 * @tset: taskset of interest
1894 * @subsys_id: the ID of the target subsystem
1896 * Return the css for the current (last returned) task of @tset for
1897 * subsystem specified by @subsys_id. This function must be preceded by
1898 * either cgroup_taskset_first() or cgroup_taskset_next().
1900 struct cgroup_subsys_state *cgroup_taskset_cur_css(struct cgroup_taskset *tset,
1903 return cgroup_css(tset->cur_cgrp, cgroup_subsys[subsys_id]);
1905 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_css);
1908 * cgroup_taskset_size - return the number of tasks in taskset
1909 * @tset: taskset of interest
1911 int cgroup_taskset_size(struct cgroup_taskset *tset)
1913 return tset->tc_array ? tset->tc_array_len : 1;
1915 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1919 * cgroup_task_migrate - move a task from one cgroup to another.
1921 * Must be called with cgroup_mutex and threadgroup locked.
1923 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1924 struct task_struct *tsk,
1925 struct css_set *new_cset)
1927 struct css_set *old_cset;
1930 * We are synchronized through threadgroup_lock() against PF_EXITING
1931 * setting such that we can't race against cgroup_exit() changing the
1932 * css_set to init_css_set and dropping the old one.
1934 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1935 old_cset = task_css_set(tsk);
1938 rcu_assign_pointer(tsk->cgroups, new_cset);
1941 /* Update the css_set linked lists if we're using them */
1942 write_lock(&css_set_lock);
1943 if (!list_empty(&tsk->cg_list))
1944 list_move(&tsk->cg_list, &new_cset->tasks);
1945 write_unlock(&css_set_lock);
1948 * We just gained a reference on old_cset by taking it from the
1949 * task. As trading it for new_cset is protected by cgroup_mutex,
1950 * we're safe to drop it here; it will be freed under RCU.
1952 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1953 put_css_set(old_cset);
1957 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1958 * @cgrp: the cgroup to attach to
1959 * @tsk: the task or the leader of the threadgroup to be attached
1960 * @threadgroup: attach the whole threadgroup?
1962 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
1963 * task_lock of @tsk or each thread in the threadgroup individually in turn.
1965 static int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk,
1968 int retval, i, group_size;
1969 struct cgroup_subsys *ss, *failed_ss = NULL;
1970 struct cgroupfs_root *root = cgrp->root;
1971 /* threadgroup list cursor and array */
1972 struct task_struct *leader = tsk;
1973 struct task_and_cgroup *tc;
1974 struct flex_array *group;
1975 struct cgroup_taskset tset = { };
1978 * step 0: in order to do expensive, possibly blocking operations for
1979 * every thread, we cannot iterate the thread group list, since it needs
1980 * rcu or tasklist locked. instead, build an array of all threads in the
1981 * group - group_rwsem prevents new threads from appearing, and if
1982 * threads exit, this will just be an over-estimate.
1985 group_size = get_nr_threads(tsk);
1988 /* flex_array supports very large thread-groups better than kmalloc. */
1989 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
1992 /* pre-allocate to guarantee space while iterating in rcu read-side. */
1993 retval = flex_array_prealloc(group, 0, group_size, GFP_KERNEL);
1995 goto out_free_group_list;
1999 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2000 * already PF_EXITING could be freed from underneath us unless we
2001 * take an rcu_read_lock.
2005 struct task_and_cgroup ent;
2007 /* @tsk either already exited or can't exit until the end */
2008 if (tsk->flags & PF_EXITING)
2011 /* as per above, nr_threads may decrease, but not increase. */
2012 BUG_ON(i >= group_size);
2014 ent.cgrp = task_cgroup_from_root(tsk, root);
2015 /* nothing to do if this task is already in the cgroup */
2016 if (ent.cgrp == cgrp)
2019 * saying GFP_ATOMIC has no effect here because we did prealloc
2020 * earlier, but it's good form to communicate our expectations.
2022 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
2023 BUG_ON(retval != 0);
2028 } while_each_thread(leader, tsk);
2030 /* remember the number of threads in the array for later. */
2032 tset.tc_array = group;
2033 tset.tc_array_len = group_size;
2035 /* methods shouldn't be called if no task is actually migrating */
2038 goto out_free_group_list;
2041 * step 1: check that we can legitimately attach to the cgroup.
2043 for_each_root_subsys(root, ss) {
2044 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss);
2046 if (ss->can_attach) {
2047 retval = ss->can_attach(css, &tset);
2050 goto out_cancel_attach;
2056 * step 2: make sure css_sets exist for all threads to be migrated.
2057 * we use find_css_set, which allocates a new one if necessary.
2059 for (i = 0; i < group_size; i++) {
2060 struct css_set *old_cset;
2062 tc = flex_array_get(group, i);
2063 old_cset = task_css_set(tc->task);
2064 tc->cset = find_css_set(old_cset, cgrp);
2067 goto out_put_css_set_refs;
2072 * step 3: now that we're guaranteed success wrt the css_sets,
2073 * proceed to move all tasks to the new cgroup. There are no
2074 * failure cases after here, so this is the commit point.
2076 for (i = 0; i < group_size; i++) {
2077 tc = flex_array_get(group, i);
2078 cgroup_task_migrate(tc->cgrp, tc->task, tc->cset);
2080 /* nothing is sensitive to fork() after this point. */
2083 * step 4: do subsystem attach callbacks.
2085 for_each_root_subsys(root, ss) {
2086 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss);
2089 ss->attach(css, &tset);
2093 * step 5: success! and cleanup
2096 out_put_css_set_refs:
2098 for (i = 0; i < group_size; i++) {
2099 tc = flex_array_get(group, i);
2102 put_css_set(tc->cset);
2107 for_each_root_subsys(root, ss) {
2108 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss);
2110 if (ss == failed_ss)
2112 if (ss->cancel_attach)
2113 ss->cancel_attach(css, &tset);
2116 out_free_group_list:
2117 flex_array_free(group);
2122 * Find the task_struct of the task to attach by vpid and pass it along to the
2123 * function to attach either it or all tasks in its threadgroup. Will lock
2124 * cgroup_mutex and threadgroup; may take task_lock of task.
2126 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2128 struct task_struct *tsk;
2129 const struct cred *cred = current_cred(), *tcred;
2132 if (!cgroup_lock_live_group(cgrp))
2138 tsk = find_task_by_vpid(pid);
2142 goto out_unlock_cgroup;
2145 * even if we're attaching all tasks in the thread group, we
2146 * only need to check permissions on one of them.
2148 tcred = __task_cred(tsk);
2149 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2150 !uid_eq(cred->euid, tcred->uid) &&
2151 !uid_eq(cred->euid, tcred->suid)) {
2154 goto out_unlock_cgroup;
2160 tsk = tsk->group_leader;
2163 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2164 * trapped in a cpuset, or RT worker may be born in a cgroup
2165 * with no rt_runtime allocated. Just say no.
2167 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2170 goto out_unlock_cgroup;
2173 get_task_struct(tsk);
2176 threadgroup_lock(tsk);
2178 if (!thread_group_leader(tsk)) {
2180 * a race with de_thread from another thread's exec()
2181 * may strip us of our leadership, if this happens,
2182 * there is no choice but to throw this task away and
2183 * try again; this is
2184 * "double-double-toil-and-trouble-check locking".
2186 threadgroup_unlock(tsk);
2187 put_task_struct(tsk);
2188 goto retry_find_task;
2192 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2194 threadgroup_unlock(tsk);
2196 put_task_struct(tsk);
2198 mutex_unlock(&cgroup_mutex);
2203 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2204 * @from: attach to all cgroups of a given task
2205 * @tsk: the task to be attached
2207 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2209 struct cgroupfs_root *root;
2212 mutex_lock(&cgroup_mutex);
2213 for_each_active_root(root) {
2214 struct cgroup *from_cgrp = task_cgroup_from_root(from, root);
2216 retval = cgroup_attach_task(from_cgrp, tsk, false);
2220 mutex_unlock(&cgroup_mutex);
2224 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2226 static int cgroup_tasks_write(struct cgroup_subsys_state *css,
2227 struct cftype *cft, u64 pid)
2229 return attach_task_by_pid(css->cgroup, pid, false);
2232 static int cgroup_procs_write(struct cgroup_subsys_state *css,
2233 struct cftype *cft, u64 tgid)
2235 return attach_task_by_pid(css->cgroup, tgid, true);
2238 static int cgroup_release_agent_write(struct cgroup_subsys_state *css,
2239 struct cftype *cft, const char *buffer)
2241 BUILD_BUG_ON(sizeof(css->cgroup->root->release_agent_path) < PATH_MAX);
2242 if (strlen(buffer) >= PATH_MAX)
2244 if (!cgroup_lock_live_group(css->cgroup))
2246 mutex_lock(&cgroup_root_mutex);
2247 strcpy(css->cgroup->root->release_agent_path, buffer);
2248 mutex_unlock(&cgroup_root_mutex);
2249 mutex_unlock(&cgroup_mutex);
2253 static int cgroup_release_agent_show(struct cgroup_subsys_state *css,
2254 struct cftype *cft, struct seq_file *seq)
2256 struct cgroup *cgrp = css->cgroup;
2258 if (!cgroup_lock_live_group(cgrp))
2260 seq_puts(seq, cgrp->root->release_agent_path);
2261 seq_putc(seq, '\n');
2262 mutex_unlock(&cgroup_mutex);
2266 static int cgroup_sane_behavior_show(struct cgroup_subsys_state *css,
2267 struct cftype *cft, struct seq_file *seq)
2269 seq_printf(seq, "%d\n", cgroup_sane_behavior(css->cgroup));
2273 /* A buffer size big enough for numbers or short strings */
2274 #define CGROUP_LOCAL_BUFFER_SIZE 64
2276 static ssize_t cgroup_write_X64(struct cgroup_subsys_state *css,
2277 struct cftype *cft, struct file *file,
2278 const char __user *userbuf, size_t nbytes,
2279 loff_t *unused_ppos)
2281 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
2287 if (nbytes >= sizeof(buffer))
2289 if (copy_from_user(buffer, userbuf, nbytes))
2292 buffer[nbytes] = 0; /* nul-terminate */
2293 if (cft->write_u64) {
2294 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
2297 retval = cft->write_u64(css, cft, val);
2299 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
2302 retval = cft->write_s64(css, cft, val);
2309 static ssize_t cgroup_write_string(struct cgroup_subsys_state *css,
2310 struct cftype *cft, struct file *file,
2311 const char __user *userbuf, size_t nbytes,
2312 loff_t *unused_ppos)
2314 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
2316 size_t max_bytes = cft->max_write_len;
2317 char *buffer = local_buffer;
2320 max_bytes = sizeof(local_buffer) - 1;
2321 if (nbytes >= max_bytes)
2323 /* Allocate a dynamic buffer if we need one */
2324 if (nbytes >= sizeof(local_buffer)) {
2325 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2329 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2334 buffer[nbytes] = 0; /* nul-terminate */
2335 retval = cft->write_string(css, cft, strstrip(buffer));
2339 if (buffer != local_buffer)
2344 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2345 size_t nbytes, loff_t *ppos)
2347 struct cfent *cfe = __d_cfe(file->f_dentry);
2348 struct cftype *cft = __d_cft(file->f_dentry);
2349 struct cgroup_subsys_state *css = cfe->css;
2352 return cft->write(css, cft, file, buf, nbytes, ppos);
2353 if (cft->write_u64 || cft->write_s64)
2354 return cgroup_write_X64(css, cft, file, buf, nbytes, ppos);
2355 if (cft->write_string)
2356 return cgroup_write_string(css, cft, file, buf, nbytes, ppos);
2358 int ret = cft->trigger(css, (unsigned int)cft->private);
2359 return ret ? ret : nbytes;
2364 static ssize_t cgroup_read_u64(struct cgroup_subsys_state *css,
2365 struct cftype *cft, struct file *file,
2366 char __user *buf, size_t nbytes, loff_t *ppos)
2368 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2369 u64 val = cft->read_u64(css, cft);
2370 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2372 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2375 static ssize_t cgroup_read_s64(struct cgroup_subsys_state *css,
2376 struct cftype *cft, struct file *file,
2377 char __user *buf, size_t nbytes, loff_t *ppos)
2379 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2380 s64 val = cft->read_s64(css, cft);
2381 int len = sprintf(tmp, "%lld\n", (long long) val);
2383 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2386 static ssize_t cgroup_file_read(struct file *file, 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 = cfe->css;
2394 return cft->read(css, cft, file, buf, nbytes, ppos);
2396 return cgroup_read_u64(css, cft, file, buf, nbytes, ppos);
2398 return cgroup_read_s64(css, cft, file, buf, nbytes, ppos);
2403 * seqfile ops/methods for returning structured data. Currently just
2404 * supports string->u64 maps, but can be extended in future.
2407 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2409 struct seq_file *sf = cb->state;
2410 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2413 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2415 struct cfent *cfe = m->private;
2416 struct cftype *cft = cfe->type;
2417 struct cgroup_subsys_state *css = cfe->css;
2419 if (cft->read_map) {
2420 struct cgroup_map_cb cb = {
2421 .fill = cgroup_map_add,
2424 return cft->read_map(css, cft, &cb);
2426 return cft->read_seq_string(css, cft, m);
2429 static const struct file_operations cgroup_seqfile_operations = {
2431 .write = cgroup_file_write,
2432 .llseek = seq_lseek,
2433 .release = single_release,
2436 static int cgroup_file_open(struct inode *inode, struct file *file)
2438 struct cfent *cfe = __d_cfe(file->f_dentry);
2439 struct cftype *cft = __d_cft(file->f_dentry);
2440 struct cgroup *cgrp = __d_cgrp(cfe->dentry->d_parent);
2441 struct cgroup_subsys_state *css;
2444 err = generic_file_open(inode, file);
2449 * If the file belongs to a subsystem, pin the css. Will be
2450 * unpinned either on open failure or release. This ensures that
2451 * @css stays alive for all file operations.
2454 css = cgroup_css(cgrp, cft->ss);
2455 if (cft->ss && !css_tryget(css))
2463 * @cfe->css is used by read/write/close to determine the
2464 * associated css. @file->private_data would be a better place but
2465 * that's already used by seqfile. Multiple accessors may use it
2466 * simultaneously which is okay as the association never changes.
2468 WARN_ON_ONCE(cfe->css && cfe->css != css);
2471 if (cft->read_map || cft->read_seq_string) {
2472 file->f_op = &cgroup_seqfile_operations;
2473 err = single_open(file, cgroup_seqfile_show, cfe);
2474 } else if (cft->open) {
2475 err = cft->open(inode, file);
2483 static int cgroup_file_release(struct inode *inode, struct file *file)
2485 struct cfent *cfe = __d_cfe(file->f_dentry);
2486 struct cftype *cft = __d_cft(file->f_dentry);
2487 struct cgroup_subsys_state *css = cfe->css;
2491 ret = cft->release(inode, file);
2498 * cgroup_rename - Only allow simple rename of directories in place.
2500 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2501 struct inode *new_dir, struct dentry *new_dentry)
2504 struct cgroup_name *name, *old_name;
2505 struct cgroup *cgrp;
2508 * It's convinient to use parent dir's i_mutex to protected
2511 lockdep_assert_held(&old_dir->i_mutex);
2513 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2515 if (new_dentry->d_inode)
2517 if (old_dir != new_dir)
2520 cgrp = __d_cgrp(old_dentry);
2523 * This isn't a proper migration and its usefulness is very
2524 * limited. Disallow if sane_behavior.
2526 if (cgroup_sane_behavior(cgrp))
2529 name = cgroup_alloc_name(new_dentry);
2533 ret = simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2539 old_name = rcu_dereference_protected(cgrp->name, true);
2540 rcu_assign_pointer(cgrp->name, name);
2542 kfree_rcu(old_name, rcu_head);
2546 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2548 if (S_ISDIR(dentry->d_inode->i_mode))
2549 return &__d_cgrp(dentry)->xattrs;
2551 return &__d_cfe(dentry)->xattrs;
2554 static inline int xattr_enabled(struct dentry *dentry)
2556 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2557 return root->flags & CGRP_ROOT_XATTR;
2560 static bool is_valid_xattr(const char *name)
2562 if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2563 !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2568 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2569 const void *val, size_t size, int flags)
2571 if (!xattr_enabled(dentry))
2573 if (!is_valid_xattr(name))
2575 return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2578 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2580 if (!xattr_enabled(dentry))
2582 if (!is_valid_xattr(name))
2584 return simple_xattr_remove(__d_xattrs(dentry), name);
2587 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2588 void *buf, size_t size)
2590 if (!xattr_enabled(dentry))
2592 if (!is_valid_xattr(name))
2594 return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2597 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2599 if (!xattr_enabled(dentry))
2601 return simple_xattr_list(__d_xattrs(dentry), buf, size);
2604 static const struct file_operations cgroup_file_operations = {
2605 .read = cgroup_file_read,
2606 .write = cgroup_file_write,
2607 .llseek = generic_file_llseek,
2608 .open = cgroup_file_open,
2609 .release = cgroup_file_release,
2612 static const struct inode_operations cgroup_file_inode_operations = {
2613 .setxattr = cgroup_setxattr,
2614 .getxattr = cgroup_getxattr,
2615 .listxattr = cgroup_listxattr,
2616 .removexattr = cgroup_removexattr,
2619 static const struct inode_operations cgroup_dir_inode_operations = {
2620 .lookup = simple_lookup,
2621 .mkdir = cgroup_mkdir,
2622 .rmdir = cgroup_rmdir,
2623 .rename = cgroup_rename,
2624 .setxattr = cgroup_setxattr,
2625 .getxattr = cgroup_getxattr,
2626 .listxattr = cgroup_listxattr,
2627 .removexattr = cgroup_removexattr,
2631 * Check if a file is a control file
2633 struct cftype *__file_cft(struct file *file)
2635 if (file_inode(file)->i_fop != &cgroup_file_operations)
2636 return ERR_PTR(-EINVAL);
2637 return __d_cft(file->f_dentry);
2640 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2641 struct super_block *sb)
2643 struct inode *inode;
2647 if (dentry->d_inode)
2650 inode = cgroup_new_inode(mode, sb);
2654 if (S_ISDIR(mode)) {
2655 inode->i_op = &cgroup_dir_inode_operations;
2656 inode->i_fop = &simple_dir_operations;
2658 /* start off with i_nlink == 2 (for "." entry) */
2660 inc_nlink(dentry->d_parent->d_inode);
2663 * Control reaches here with cgroup_mutex held.
2664 * @inode->i_mutex should nest outside cgroup_mutex but we
2665 * want to populate it immediately without releasing
2666 * cgroup_mutex. As @inode isn't visible to anyone else
2667 * yet, trylock will always succeed without affecting
2670 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2671 } else if (S_ISREG(mode)) {
2673 inode->i_fop = &cgroup_file_operations;
2674 inode->i_op = &cgroup_file_inode_operations;
2676 d_instantiate(dentry, inode);
2677 dget(dentry); /* Extra count - pin the dentry in core */
2682 * cgroup_file_mode - deduce file mode of a control file
2683 * @cft: the control file in question
2685 * returns cft->mode if ->mode is not 0
2686 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2687 * returns S_IRUGO if it has only a read handler
2688 * returns S_IWUSR if it has only a write hander
2690 static umode_t cgroup_file_mode(const struct cftype *cft)
2697 if (cft->read || cft->read_u64 || cft->read_s64 ||
2698 cft->read_map || cft->read_seq_string)
2701 if (cft->write || cft->write_u64 || cft->write_s64 ||
2702 cft->write_string || cft->trigger)
2708 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2710 struct dentry *dir = cgrp->dentry;
2711 struct cgroup *parent = __d_cgrp(dir);
2712 struct dentry *dentry;
2716 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2718 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
2719 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
2720 strcpy(name, cft->ss->name);
2723 strcat(name, cft->name);
2725 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2727 cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2731 dentry = lookup_one_len(name, dir, strlen(name));
2732 if (IS_ERR(dentry)) {
2733 error = PTR_ERR(dentry);
2737 cfe->type = (void *)cft;
2738 cfe->dentry = dentry;
2739 dentry->d_fsdata = cfe;
2740 simple_xattrs_init(&cfe->xattrs);
2742 mode = cgroup_file_mode(cft);
2743 error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2745 list_add_tail(&cfe->node, &parent->files);
2755 * cgroup_addrm_files - add or remove files to a cgroup directory
2756 * @cgrp: the target cgroup
2757 * @cfts: array of cftypes to be added
2758 * @is_add: whether to add or remove
2760 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2761 * For removals, this function never fails. If addition fails, this
2762 * function doesn't remove files already added. The caller is responsible
2765 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2771 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
2772 lockdep_assert_held(&cgroup_mutex);
2774 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2775 /* does cft->flags tell us to skip this file on @cgrp? */
2776 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2778 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2780 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2784 ret = cgroup_add_file(cgrp, cft);
2786 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2791 cgroup_rm_file(cgrp, cft);
2797 static void cgroup_cfts_prepare(void)
2798 __acquires(&cgroup_mutex)
2801 * Thanks to the entanglement with vfs inode locking, we can't walk
2802 * the existing cgroups under cgroup_mutex and create files.
2803 * Instead, we use css_for_each_descendant_pre() and drop RCU read
2804 * lock before calling cgroup_addrm_files().
2806 mutex_lock(&cgroup_mutex);
2809 static int cgroup_cfts_commit(struct cftype *cfts, bool is_add)
2810 __releases(&cgroup_mutex)
2813 struct cgroup_subsys *ss = cfts[0].ss;
2814 struct cgroup *root = &ss->root->top_cgroup;
2815 struct super_block *sb = ss->root->sb;
2816 struct dentry *prev = NULL;
2817 struct inode *inode;
2818 struct cgroup_subsys_state *css;
2822 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2823 if (!cfts || ss->root == &cgroup_dummy_root ||
2824 !atomic_inc_not_zero(&sb->s_active)) {
2825 mutex_unlock(&cgroup_mutex);
2830 * All cgroups which are created after we drop cgroup_mutex will
2831 * have the updated set of files, so we only need to update the
2832 * cgroups created before the current @cgroup_serial_nr_next.
2834 update_before = cgroup_serial_nr_next;
2836 mutex_unlock(&cgroup_mutex);
2838 /* add/rm files for all cgroups created before */
2840 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2841 struct cgroup *cgrp = css->cgroup;
2843 if (cgroup_is_dead(cgrp))
2846 inode = cgrp->dentry->d_inode;
2851 prev = cgrp->dentry;
2853 mutex_lock(&inode->i_mutex);
2854 mutex_lock(&cgroup_mutex);
2855 if (cgrp->serial_nr < update_before && !cgroup_is_dead(cgrp))
2856 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2857 mutex_unlock(&cgroup_mutex);
2858 mutex_unlock(&inode->i_mutex);
2866 deactivate_super(sb);
2871 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2872 * @ss: target cgroup subsystem
2873 * @cfts: zero-length name terminated array of cftypes
2875 * Register @cfts to @ss. Files described by @cfts are created for all
2876 * existing cgroups to which @ss is attached and all future cgroups will
2877 * have them too. This function can be called anytime whether @ss is
2880 * Returns 0 on successful registration, -errno on failure. Note that this
2881 * function currently returns 0 as long as @cfts registration is successful
2882 * even if some file creation attempts on existing cgroups fail.
2884 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2886 struct cftype_set *set;
2890 set = kzalloc(sizeof(*set), GFP_KERNEL);
2894 for (cft = cfts; cft->name[0] != '\0'; cft++)
2897 cgroup_cfts_prepare();
2899 list_add_tail(&set->node, &ss->cftsets);
2900 ret = cgroup_cfts_commit(cfts, true);
2902 cgroup_rm_cftypes(cfts);
2905 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2908 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2909 * @cfts: zero-length name terminated array of cftypes
2911 * Unregister @cfts. Files described by @cfts are removed from all
2912 * existing cgroups and all future cgroups won't have them either. This
2913 * function can be called anytime whether @cfts' subsys is attached or not.
2915 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2918 int cgroup_rm_cftypes(struct cftype *cfts)
2920 struct cftype_set *set;
2922 if (!cfts || !cfts[0].ss)
2925 cgroup_cfts_prepare();
2927 list_for_each_entry(set, &cfts[0].ss->cftsets, node) {
2928 if (set->cfts == cfts) {
2929 list_del(&set->node);
2931 cgroup_cfts_commit(cfts, false);
2936 cgroup_cfts_commit(NULL, false);
2941 * cgroup_task_count - count the number of tasks in a cgroup.
2942 * @cgrp: the cgroup in question
2944 * Return the number of tasks in the cgroup.
2946 int cgroup_task_count(const struct cgroup *cgrp)
2949 struct cgrp_cset_link *link;
2951 read_lock(&css_set_lock);
2952 list_for_each_entry(link, &cgrp->cset_links, cset_link)
2953 count += atomic_read(&link->cset->refcount);
2954 read_unlock(&css_set_lock);
2959 * To reduce the fork() overhead for systems that are not actually using
2960 * their cgroups capability, we don't maintain the lists running through
2961 * each css_set to its tasks until we see the list actually used - in other
2962 * words after the first call to css_task_iter_start().
2964 static void cgroup_enable_task_cg_lists(void)
2966 struct task_struct *p, *g;
2967 write_lock(&css_set_lock);
2968 use_task_css_set_links = 1;
2970 * We need tasklist_lock because RCU is not safe against
2971 * while_each_thread(). Besides, a forking task that has passed
2972 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2973 * is not guaranteed to have its child immediately visible in the
2974 * tasklist if we walk through it with RCU.
2976 read_lock(&tasklist_lock);
2977 do_each_thread(g, p) {
2980 * We should check if the process is exiting, otherwise
2981 * it will race with cgroup_exit() in that the list
2982 * entry won't be deleted though the process has exited.
2984 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2985 list_add(&p->cg_list, &task_css_set(p)->tasks);
2987 } while_each_thread(g, p);
2988 read_unlock(&tasklist_lock);
2989 write_unlock(&css_set_lock);
2993 * css_next_child - find the next child of a given css
2994 * @pos_css: the current position (%NULL to initiate traversal)
2995 * @parent_css: css whose children to walk
2997 * This function returns the next child of @parent_css and should be called
2998 * under RCU read lock. The only requirement is that @parent_css and
2999 * @pos_css are accessible. The next sibling is guaranteed to be returned
3000 * regardless of their states.
3002 struct cgroup_subsys_state *
3003 css_next_child(struct cgroup_subsys_state *pos_css,
3004 struct cgroup_subsys_state *parent_css)
3006 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
3007 struct cgroup *cgrp = parent_css->cgroup;
3008 struct cgroup *next;
3010 WARN_ON_ONCE(!rcu_read_lock_held());
3013 * @pos could already have been removed. Once a cgroup is removed,
3014 * its ->sibling.next is no longer updated when its next sibling
3015 * changes. As CGRP_DEAD assertion is serialized and happens
3016 * before the cgroup is taken off the ->sibling list, if we see it
3017 * unasserted, it's guaranteed that the next sibling hasn't
3018 * finished its grace period even if it's already removed, and thus
3019 * safe to dereference from this RCU critical section. If
3020 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
3021 * to be visible as %true here.
3023 * If @pos is dead, its next pointer can't be dereferenced;
3024 * however, as each cgroup is given a monotonically increasing
3025 * unique serial number and always appended to the sibling list,
3026 * the next one can be found by walking the parent's children until
3027 * we see a cgroup with higher serial number than @pos's. While
3028 * this path can be slower, it's taken only when either the current
3029 * cgroup is removed or iteration and removal race.
3032 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
3033 } else if (likely(!cgroup_is_dead(pos))) {
3034 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3036 list_for_each_entry_rcu(next, &cgrp->children, sibling)
3037 if (next->serial_nr > pos->serial_nr)
3041 if (&next->sibling == &cgrp->children)
3044 return cgroup_css(next, parent_css->ss);
3046 EXPORT_SYMBOL_GPL(css_next_child);
3049 * css_next_descendant_pre - find the next descendant for pre-order walk
3050 * @pos: the current position (%NULL to initiate traversal)
3051 * @root: css whose descendants to walk
3053 * To be used by css_for_each_descendant_pre(). Find the next descendant
3054 * to visit for pre-order traversal of @root's descendants. @root is
3055 * included in the iteration and the first node to be visited.
3057 * While this function requires RCU read locking, it doesn't require the
3058 * whole traversal to be contained in a single RCU critical section. This
3059 * function will return the correct next descendant as long as both @pos
3060 * and @root are accessible and @pos is a descendant of @root.
3062 struct cgroup_subsys_state *
3063 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3064 struct cgroup_subsys_state *root)
3066 struct cgroup_subsys_state *next;
3068 WARN_ON_ONCE(!rcu_read_lock_held());
3070 /* if first iteration, visit @root */
3074 /* visit the first child if exists */
3075 next = css_next_child(NULL, pos);
3079 /* no child, visit my or the closest ancestor's next sibling */
3080 while (pos != root) {
3081 next = css_next_child(pos, css_parent(pos));
3084 pos = css_parent(pos);
3089 EXPORT_SYMBOL_GPL(css_next_descendant_pre);
3092 * css_rightmost_descendant - return the rightmost descendant of a css
3093 * @pos: css of interest
3095 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3096 * is returned. This can be used during pre-order traversal to skip
3099 * While this function requires RCU read locking, it doesn't require the
3100 * whole traversal to be contained in a single RCU critical section. This
3101 * function will return the correct rightmost descendant as long as @pos is
3104 struct cgroup_subsys_state *
3105 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3107 struct cgroup_subsys_state *last, *tmp;
3109 WARN_ON_ONCE(!rcu_read_lock_held());
3113 /* ->prev isn't RCU safe, walk ->next till the end */
3115 css_for_each_child(tmp, last)
3121 EXPORT_SYMBOL_GPL(css_rightmost_descendant);
3123 static struct cgroup_subsys_state *
3124 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3126 struct cgroup_subsys_state *last;
3130 pos = css_next_child(NULL, pos);
3137 * css_next_descendant_post - find the next descendant for post-order walk
3138 * @pos: the current position (%NULL to initiate traversal)
3139 * @root: css whose descendants to walk
3141 * To be used by css_for_each_descendant_post(). Find the next descendant
3142 * to visit for post-order traversal of @root's descendants. @root is
3143 * included in the iteration and the last node to be visited.
3145 * While this function requires RCU read locking, it doesn't require the
3146 * whole traversal to be contained in a single RCU critical section. This
3147 * function will return the correct next descendant as long as both @pos
3148 * and @cgroup are accessible and @pos is a descendant of @cgroup.
3150 struct cgroup_subsys_state *
3151 css_next_descendant_post(struct cgroup_subsys_state *pos,
3152 struct cgroup_subsys_state *root)
3154 struct cgroup_subsys_state *next;
3156 WARN_ON_ONCE(!rcu_read_lock_held());
3158 /* if first iteration, visit leftmost descendant which may be @root */
3160 return css_leftmost_descendant(root);
3162 /* if we visited @root, we're done */
3166 /* if there's an unvisited sibling, visit its leftmost descendant */
3167 next = css_next_child(pos, css_parent(pos));
3169 return css_leftmost_descendant(next);
3171 /* no sibling left, visit parent */
3172 return css_parent(pos);
3174 EXPORT_SYMBOL_GPL(css_next_descendant_post);
3177 * css_advance_task_iter - advance a task itererator to the next css_set
3178 * @it: the iterator to advance
3180 * Advance @it to the next css_set to walk.
3182 static void css_advance_task_iter(struct css_task_iter *it)
3184 struct list_head *l = it->cset_link;
3185 struct cgrp_cset_link *link;
3186 struct css_set *cset;
3188 /* Advance to the next non-empty css_set */
3191 if (l == &it->origin_css->cgroup->cset_links) {
3192 it->cset_link = NULL;
3195 link = list_entry(l, struct cgrp_cset_link, cset_link);
3197 } while (list_empty(&cset->tasks));
3199 it->task = cset->tasks.next;
3203 * css_task_iter_start - initiate task iteration
3204 * @css: the css to walk tasks of
3205 * @it: the task iterator to use
3207 * Initiate iteration through the tasks of @css. The caller can call
3208 * css_task_iter_next() to walk through the tasks until the function
3209 * returns NULL. On completion of iteration, css_task_iter_end() must be
3212 * Note that this function acquires a lock which is released when the
3213 * iteration finishes. The caller can't sleep while iteration is in
3216 void css_task_iter_start(struct cgroup_subsys_state *css,
3217 struct css_task_iter *it)
3218 __acquires(css_set_lock)
3221 * The first time anyone tries to iterate across a css, we need to
3222 * enable the list linking each css_set to its tasks, and fix up
3223 * all existing tasks.
3225 if (!use_task_css_set_links)
3226 cgroup_enable_task_cg_lists();
3228 read_lock(&css_set_lock);
3230 it->origin_css = css;
3231 it->cset_link = &css->cgroup->cset_links;
3233 css_advance_task_iter(it);
3237 * css_task_iter_next - return the next task for the iterator
3238 * @it: the task iterator being iterated
3240 * The "next" function for task iteration. @it should have been
3241 * initialized via css_task_iter_start(). Returns NULL when the iteration
3244 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3246 struct task_struct *res;
3247 struct list_head *l = it->task;
3248 struct cgrp_cset_link *link;
3250 /* If the iterator cg is NULL, we have no tasks */
3253 res = list_entry(l, struct task_struct, cg_list);
3254 /* Advance iterator to find next entry */
3256 link = list_entry(it->cset_link, struct cgrp_cset_link, cset_link);
3257 if (l == &link->cset->tasks) {
3259 * We reached the end of this task list - move on to the
3260 * next cgrp_cset_link.
3262 css_advance_task_iter(it);
3270 * css_task_iter_end - finish task iteration
3271 * @it: the task iterator to finish
3273 * Finish task iteration started by css_task_iter_start().
3275 void css_task_iter_end(struct css_task_iter *it)
3276 __releases(css_set_lock)
3278 read_unlock(&css_set_lock);
3281 static inline int started_after_time(struct task_struct *t1,
3282 struct timespec *time,
3283 struct task_struct *t2)
3285 int start_diff = timespec_compare(&t1->start_time, time);
3286 if (start_diff > 0) {
3288 } else if (start_diff < 0) {
3292 * Arbitrarily, if two processes started at the same
3293 * time, we'll say that the lower pointer value
3294 * started first. Note that t2 may have exited by now
3295 * so this may not be a valid pointer any longer, but
3296 * that's fine - it still serves to distinguish
3297 * between two tasks started (effectively) simultaneously.
3304 * This function is a callback from heap_insert() and is used to order
3306 * In this case we order the heap in descending task start time.
3308 static inline int started_after(void *p1, void *p2)
3310 struct task_struct *t1 = p1;
3311 struct task_struct *t2 = p2;
3312 return started_after_time(t1, &t2->start_time, t2);
3316 * css_scan_tasks - iterate though all the tasks in a css
3317 * @css: the css to iterate tasks of
3318 * @test: optional test callback
3319 * @process: process callback
3320 * @data: data passed to @test and @process
3321 * @heap: optional pre-allocated heap used for task iteration
3323 * Iterate through all the tasks in @css, calling @test for each, and if it
3324 * returns %true, call @process for it also.
3326 * @test may be NULL, meaning always true (select all tasks), which
3327 * effectively duplicates css_task_iter_{start,next,end}() but does not
3328 * lock css_set_lock for the call to @process.
3330 * It is guaranteed that @process will act on every task that is a member
3331 * of @css for the duration of this call. This function may or may not
3332 * call @process for tasks that exit or move to a different css during the
3333 * call, or are forked or move into the css during the call.
3335 * Note that @test may be called with locks held, and may in some
3336 * situations be called multiple times for the same task, so it should be
3339 * If @heap is non-NULL, a heap has been pre-allocated and will be used for
3340 * heap operations (and its "gt" member will be overwritten), else a
3341 * temporary heap will be used (allocation of which may cause this function
3344 int css_scan_tasks(struct cgroup_subsys_state *css,
3345 bool (*test)(struct task_struct *, void *),
3346 void (*process)(struct task_struct *, void *),
3347 void *data, struct ptr_heap *heap)
3350 struct css_task_iter it;
3351 struct task_struct *p, *dropped;
3352 /* Never dereference latest_task, since it's not refcounted */
3353 struct task_struct *latest_task = NULL;
3354 struct ptr_heap tmp_heap;
3355 struct timespec latest_time = { 0, 0 };
3358 /* The caller supplied our heap and pre-allocated its memory */
3359 heap->gt = &started_after;
3361 /* We need to allocate our own heap memory */
3363 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3365 /* cannot allocate the heap */
3371 * Scan tasks in the css, using the @test callback to determine
3372 * which are of interest, and invoking @process callback on the
3373 * ones which need an update. Since we don't want to hold any
3374 * locks during the task updates, gather tasks to be processed in a
3375 * heap structure. The heap is sorted by descending task start
3376 * time. If the statically-sized heap fills up, we overflow tasks
3377 * that started later, and in future iterations only consider tasks
3378 * that started after the latest task in the previous pass. This
3379 * guarantees forward progress and that we don't miss any tasks.
3382 css_task_iter_start(css, &it);
3383 while ((p = css_task_iter_next(&it))) {
3385 * Only affect tasks that qualify per the caller's callback,
3386 * if he provided one
3388 if (test && !test(p, data))
3391 * Only process tasks that started after the last task
3394 if (!started_after_time(p, &latest_time, latest_task))
3396 dropped = heap_insert(heap, p);
3397 if (dropped == NULL) {
3399 * The new task was inserted; the heap wasn't
3403 } else if (dropped != p) {
3405 * The new task was inserted, and pushed out a
3409 put_task_struct(dropped);
3412 * Else the new task was newer than anything already in
3413 * the heap and wasn't inserted
3416 css_task_iter_end(&it);
3419 for (i = 0; i < heap->size; i++) {
3420 struct task_struct *q = heap->ptrs[i];
3422 latest_time = q->start_time;
3425 /* Process the task per the caller's callback */
3430 * If we had to process any tasks at all, scan again
3431 * in case some of them were in the middle of forking
3432 * children that didn't get processed.
3433 * Not the most efficient way to do it, but it avoids
3434 * having to take callback_mutex in the fork path
3438 if (heap == &tmp_heap)
3439 heap_free(&tmp_heap);
3443 static void cgroup_transfer_one_task(struct task_struct *task, void *data)
3445 struct cgroup *new_cgroup = data;
3447 mutex_lock(&cgroup_mutex);
3448 cgroup_attach_task(new_cgroup, task, false);
3449 mutex_unlock(&cgroup_mutex);
3453 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3454 * @to: cgroup to which the tasks will be moved
3455 * @from: cgroup in which the tasks currently reside
3457 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3459 return css_scan_tasks(&from->dummy_css, NULL, cgroup_transfer_one_task,
3464 * Stuff for reading the 'tasks'/'procs' files.
3466 * Reading this file can return large amounts of data if a cgroup has
3467 * *lots* of attached tasks. So it may need several calls to read(),
3468 * but we cannot guarantee that the information we produce is correct
3469 * unless we produce it entirely atomically.
3473 /* which pidlist file are we talking about? */
3474 enum cgroup_filetype {
3480 * A pidlist is a list of pids that virtually represents the contents of one
3481 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3482 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3485 struct cgroup_pidlist {
3487 * used to find which pidlist is wanted. doesn't change as long as
3488 * this particular list stays in the list.
3490 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3493 /* how many elements the above list has */
3495 /* how many files are using the current array */
3497 /* each of these stored in a list by its cgroup */
3498 struct list_head links;
3499 /* pointer to the cgroup we belong to, for list removal purposes */
3500 struct cgroup *owner;
3501 /* protects the other fields */
3502 struct rw_semaphore rwsem;
3506 * The following two functions "fix" the issue where there are more pids
3507 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3508 * TODO: replace with a kernel-wide solution to this problem
3510 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3511 static void *pidlist_allocate(int count)
3513 if (PIDLIST_TOO_LARGE(count))
3514 return vmalloc(count * sizeof(pid_t));
3516 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3518 static void pidlist_free(void *p)
3520 if (is_vmalloc_addr(p))
3527 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3528 * Returns the number of unique elements.
3530 static int pidlist_uniq(pid_t *list, int length)
3535 * we presume the 0th element is unique, so i starts at 1. trivial
3536 * edge cases first; no work needs to be done for either
3538 if (length == 0 || length == 1)
3540 /* src and dest walk down the list; dest counts unique elements */
3541 for (src = 1; src < length; src++) {
3542 /* find next unique element */
3543 while (list[src] == list[src-1]) {
3548 /* dest always points to where the next unique element goes */
3549 list[dest] = list[src];
3556 static int cmppid(const void *a, const void *b)
3558 return *(pid_t *)a - *(pid_t *)b;
3562 * find the appropriate pidlist for our purpose (given procs vs tasks)
3563 * returns with the lock on that pidlist already held, and takes care
3564 * of the use count, or returns NULL with no locks held if we're out of
3567 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3568 enum cgroup_filetype type)
3570 struct cgroup_pidlist *l;
3571 /* don't need task_nsproxy() if we're looking at ourself */
3572 struct pid_namespace *ns = task_active_pid_ns(current);
3575 * We can't drop the pidlist_mutex before taking the l->rwsem in case
3576 * the last ref-holder is trying to remove l from the list at the same
3577 * time. Holding the pidlist_mutex precludes somebody taking whichever
3578 * list we find out from under us - compare release_pid_array().
3580 mutex_lock(&cgrp->pidlist_mutex);
3581 list_for_each_entry(l, &cgrp->pidlists, links) {
3582 if (l->key.type == type && l->key.ns == ns) {
3583 /* make sure l doesn't vanish out from under us */
3584 down_write(&l->rwsem);
3585 mutex_unlock(&cgrp->pidlist_mutex);
3589 /* entry not found; create a new one */
3590 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3592 mutex_unlock(&cgrp->pidlist_mutex);
3595 init_rwsem(&l->rwsem);
3596 down_write(&l->rwsem);
3598 l->key.ns = get_pid_ns(ns);
3600 list_add(&l->links, &cgrp->pidlists);
3601 mutex_unlock(&cgrp->pidlist_mutex);
3606 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3608 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3609 struct cgroup_pidlist **lp)
3613 int pid, n = 0; /* used for populating the array */
3614 struct css_task_iter it;
3615 struct task_struct *tsk;
3616 struct cgroup_pidlist *l;
3619 * If cgroup gets more users after we read count, we won't have
3620 * enough space - tough. This race is indistinguishable to the
3621 * caller from the case that the additional cgroup users didn't
3622 * show up until sometime later on.
3624 length = cgroup_task_count(cgrp);
3625 array = pidlist_allocate(length);
3628 /* now, populate the array */
3629 css_task_iter_start(&cgrp->dummy_css, &it);
3630 while ((tsk = css_task_iter_next(&it))) {
3631 if (unlikely(n == length))
3633 /* get tgid or pid for procs or tasks file respectively */
3634 if (type == CGROUP_FILE_PROCS)
3635 pid = task_tgid_vnr(tsk);
3637 pid = task_pid_vnr(tsk);
3638 if (pid > 0) /* make sure to only use valid results */
3641 css_task_iter_end(&it);
3643 /* now sort & (if procs) strip out duplicates */
3644 sort(array, length, sizeof(pid_t), cmppid, NULL);
3645 if (type == CGROUP_FILE_PROCS)
3646 length = pidlist_uniq(array, length);
3647 l = cgroup_pidlist_find(cgrp, type);
3649 pidlist_free(array);
3652 /* store array, freeing old if necessary - lock already held */
3653 pidlist_free(l->list);
3657 up_write(&l->rwsem);
3663 * cgroupstats_build - build and fill cgroupstats
3664 * @stats: cgroupstats to fill information into
3665 * @dentry: A dentry entry belonging to the cgroup for which stats have
3668 * Build and fill cgroupstats so that taskstats can export it to user
3671 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3674 struct cgroup *cgrp;
3675 struct css_task_iter it;
3676 struct task_struct *tsk;
3679 * Validate dentry by checking the superblock operations,
3680 * and make sure it's a directory.
3682 if (dentry->d_sb->s_op != &cgroup_ops ||
3683 !S_ISDIR(dentry->d_inode->i_mode))
3687 cgrp = dentry->d_fsdata;
3689 css_task_iter_start(&cgrp->dummy_css, &it);
3690 while ((tsk = css_task_iter_next(&it))) {
3691 switch (tsk->state) {
3693 stats->nr_running++;
3695 case TASK_INTERRUPTIBLE:
3696 stats->nr_sleeping++;
3698 case TASK_UNINTERRUPTIBLE:
3699 stats->nr_uninterruptible++;
3702 stats->nr_stopped++;
3705 if (delayacct_is_task_waiting_on_io(tsk))
3706 stats->nr_io_wait++;
3710 css_task_iter_end(&it);
3718 * seq_file methods for the tasks/procs files. The seq_file position is the
3719 * next pid to display; the seq_file iterator is a pointer to the pid
3720 * in the cgroup->l->list array.
3723 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3726 * Initially we receive a position value that corresponds to
3727 * one more than the last pid shown (or 0 on the first call or
3728 * after a seek to the start). Use a binary-search to find the
3729 * next pid to display, if any
3731 struct cgroup_pidlist *l = s->private;
3732 int index = 0, pid = *pos;
3735 down_read(&l->rwsem);
3737 int end = l->length;
3739 while (index < end) {
3740 int mid = (index + end) / 2;
3741 if (l->list[mid] == pid) {
3744 } else if (l->list[mid] <= pid)
3750 /* If we're off the end of the array, we're done */
3751 if (index >= l->length)
3753 /* Update the abstract position to be the actual pid that we found */
3754 iter = l->list + index;
3759 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3761 struct cgroup_pidlist *l = s->private;
3765 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3767 struct cgroup_pidlist *l = s->private;
3769 pid_t *end = l->list + l->length;
3771 * Advance to the next pid in the array. If this goes off the
3783 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3785 return seq_printf(s, "%d\n", *(int *)v);
3789 * seq_operations functions for iterating on pidlists through seq_file -
3790 * independent of whether it's tasks or procs
3792 static const struct seq_operations cgroup_pidlist_seq_operations = {
3793 .start = cgroup_pidlist_start,
3794 .stop = cgroup_pidlist_stop,
3795 .next = cgroup_pidlist_next,
3796 .show = cgroup_pidlist_show,
3799 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
3802 * the case where we're the last user of this particular pidlist will
3803 * have us remove it from the cgroup's list, which entails taking the
3804 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3805 * pidlist_mutex, we have to take pidlist_mutex first.
3807 mutex_lock(&l->owner->pidlist_mutex);
3808 down_write(&l->rwsem);
3809 BUG_ON(!l->use_count);
3810 if (!--l->use_count) {
3811 /* we're the last user if refcount is 0; remove and free */
3812 list_del(&l->links);
3813 mutex_unlock(&l->owner->pidlist_mutex);
3814 pidlist_free(l->list);
3815 put_pid_ns(l->key.ns);
3816 up_write(&l->rwsem);
3820 mutex_unlock(&l->owner->pidlist_mutex);
3821 up_write(&l->rwsem);
3824 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
3826 struct cgroup_pidlist *l;
3827 if (!(file->f_mode & FMODE_READ))
3830 * the seq_file will only be initialized if the file was opened for
3831 * reading; hence we check if it's not null only in that case.
3833 l = ((struct seq_file *)file->private_data)->private;
3834 cgroup_release_pid_array(l);
3835 return seq_release(inode, file);
3838 static const struct file_operations cgroup_pidlist_operations = {
3840 .llseek = seq_lseek,
3841 .write = cgroup_file_write,
3842 .release = cgroup_pidlist_release,
3846 * The following functions handle opens on a file that displays a pidlist
3847 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3850 /* helper function for the two below it */
3851 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
3853 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
3854 struct cgroup_pidlist *l;
3857 /* Nothing to do for write-only files */
3858 if (!(file->f_mode & FMODE_READ))
3861 /* have the array populated */
3862 retval = pidlist_array_load(cgrp, type, &l);
3865 /* configure file information */
3866 file->f_op = &cgroup_pidlist_operations;
3868 retval = seq_open(file, &cgroup_pidlist_seq_operations);
3870 cgroup_release_pid_array(l);
3873 ((struct seq_file *)file->private_data)->private = l;
3876 static int cgroup_tasks_open(struct inode *unused, struct file *file)
3878 return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
3880 static int cgroup_procs_open(struct inode *unused, struct file *file)
3882 return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
3885 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3888 return notify_on_release(css->cgroup);
3891 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3892 struct cftype *cft, u64 val)
3894 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3896 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3898 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3903 * When dput() is called asynchronously, if umount has been done and
3904 * then deactivate_super() in cgroup_free_fn() kills the superblock,
3905 * there's a small window that vfs will see the root dentry with non-zero
3906 * refcnt and trigger BUG().
3908 * That's why we hold a reference before dput() and drop it right after.
3910 static void cgroup_dput(struct cgroup *cgrp)
3912 struct super_block *sb = cgrp->root->sb;
3914 atomic_inc(&sb->s_active);
3916 deactivate_super(sb);
3919 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3922 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3925 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3926 struct cftype *cft, u64 val)
3929 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3931 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3935 static struct cftype cgroup_base_files[] = {
3937 .name = "cgroup.procs",
3938 .open = cgroup_procs_open,
3939 .write_u64 = cgroup_procs_write,
3940 .release = cgroup_pidlist_release,
3941 .mode = S_IRUGO | S_IWUSR,
3944 .name = "cgroup.clone_children",
3945 .flags = CFTYPE_INSANE,
3946 .read_u64 = cgroup_clone_children_read,
3947 .write_u64 = cgroup_clone_children_write,
3950 .name = "cgroup.sane_behavior",
3951 .flags = CFTYPE_ONLY_ON_ROOT,
3952 .read_seq_string = cgroup_sane_behavior_show,
3956 * Historical crazy stuff. These don't have "cgroup." prefix and
3957 * don't exist if sane_behavior. If you're depending on these, be
3958 * prepared to be burned.
3962 .flags = CFTYPE_INSANE, /* use "procs" instead */
3963 .open = cgroup_tasks_open,
3964 .write_u64 = cgroup_tasks_write,
3965 .release = cgroup_pidlist_release,
3966 .mode = S_IRUGO | S_IWUSR,
3969 .name = "notify_on_release",
3970 .flags = CFTYPE_INSANE,
3971 .read_u64 = cgroup_read_notify_on_release,
3972 .write_u64 = cgroup_write_notify_on_release,
3975 .name = "release_agent",
3976 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
3977 .read_seq_string = cgroup_release_agent_show,
3978 .write_string = cgroup_release_agent_write,
3979 .max_write_len = PATH_MAX,
3985 * cgroup_populate_dir - create subsys files in a cgroup directory
3986 * @cgrp: target cgroup
3987 * @subsys_mask: mask of the subsystem ids whose files should be added
3989 * On failure, no file is added.
3991 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
3993 struct cgroup_subsys *ss;
3996 /* process cftsets of each subsystem */
3997 for_each_subsys(ss, i) {
3998 struct cftype_set *set;
4000 if (!test_bit(i, &subsys_mask))
4003 list_for_each_entry(set, &ss->cftsets, node) {
4004 ret = cgroup_addrm_files(cgrp, set->cfts, true);
4010 /* This cgroup is ready now */
4011 for_each_root_subsys(cgrp->root, ss) {
4012 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss);
4013 struct css_id *id = rcu_dereference_protected(css->id, true);
4016 * Update id->css pointer and make this css visible from
4017 * CSS ID functions. This pointer will be dereferened
4018 * from RCU-read-side without locks.
4021 rcu_assign_pointer(id->css, css);
4026 cgroup_clear_dir(cgrp, subsys_mask);
4031 * css destruction is four-stage process.
4033 * 1. Destruction starts. Killing of the percpu_ref is initiated.
4034 * Implemented in kill_css().
4036 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4037 * and thus css_tryget() is guaranteed to fail, the css can be offlined
4038 * by invoking offline_css(). After offlining, the base ref is put.
4039 * Implemented in css_killed_work_fn().
4041 * 3. When the percpu_ref reaches zero, the only possible remaining
4042 * accessors are inside RCU read sections. css_release() schedules the
4045 * 4. After the grace period, the css can be freed. Implemented in
4046 * css_free_work_fn().
4048 * It is actually hairier because both step 2 and 4 require process context
4049 * and thus involve punting to css->destroy_work adding two additional
4050 * steps to the already complex sequence.
4052 static void css_free_work_fn(struct work_struct *work)
4054 struct cgroup_subsys_state *css =
4055 container_of(work, struct cgroup_subsys_state, destroy_work);
4056 struct cgroup *cgrp = css->cgroup;
4059 css_put(css->parent);
4061 css->ss->css_free(css);
4065 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4067 struct cgroup_subsys_state *css =
4068 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4071 * css holds an extra ref to @cgrp->dentry which is put on the last
4072 * css_put(). dput() requires process context which we don't have.
4074 INIT_WORK(&css->destroy_work, css_free_work_fn);
4075 schedule_work(&css->destroy_work);
4078 static void css_release(struct percpu_ref *ref)
4080 struct cgroup_subsys_state *css =
4081 container_of(ref, struct cgroup_subsys_state, refcnt);
4083 call_rcu(&css->rcu_head, css_free_rcu_fn);
4086 static void init_css(struct cgroup_subsys_state *css, struct cgroup_subsys *ss,
4087 struct cgroup *cgrp)
4095 css->parent = cgroup_css(cgrp->parent, ss);
4097 css->flags |= CSS_ROOT;
4099 BUG_ON(cgroup_css(cgrp, ss));
4102 /* invoke ->css_online() on a new CSS and mark it online if successful */
4103 static int online_css(struct cgroup_subsys_state *css)
4105 struct cgroup_subsys *ss = css->ss;
4108 lockdep_assert_held(&cgroup_mutex);
4111 ret = ss->css_online(css);
4113 css->flags |= CSS_ONLINE;
4114 css->cgroup->nr_css++;
4115 rcu_assign_pointer(css->cgroup->subsys[ss->subsys_id], css);
4120 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4121 static void offline_css(struct cgroup_subsys_state *css)
4123 struct cgroup_subsys *ss = css->ss;
4125 lockdep_assert_held(&cgroup_mutex);
4127 if (!(css->flags & CSS_ONLINE))
4130 if (ss->css_offline)
4131 ss->css_offline(css);
4133 css->flags &= ~CSS_ONLINE;
4134 css->cgroup->nr_css--;
4135 RCU_INIT_POINTER(css->cgroup->subsys[ss->subsys_id], css);
4139 * cgroup_create - create a cgroup
4140 * @parent: cgroup that will be parent of the new cgroup
4141 * @dentry: dentry of the new cgroup
4142 * @mode: mode to set on new inode
4144 * Must be called with the mutex on the parent inode held
4146 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4149 struct cgroup_subsys_state *css_ar[CGROUP_SUBSYS_COUNT] = { };
4150 struct cgroup *cgrp;
4151 struct cgroup_name *name;
4152 struct cgroupfs_root *root = parent->root;
4154 struct cgroup_subsys *ss;
4155 struct super_block *sb = root->sb;
4157 /* allocate the cgroup and its ID, 0 is reserved for the root */
4158 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4162 name = cgroup_alloc_name(dentry);
4165 rcu_assign_pointer(cgrp->name, name);
4168 * Temporarily set the pointer to NULL, so idr_find() won't return
4169 * a half-baked cgroup.
4171 cgrp->id = idr_alloc(&root->cgroup_idr, NULL, 1, 0, GFP_KERNEL);
4176 * Only live parents can have children. Note that the liveliness
4177 * check isn't strictly necessary because cgroup_mkdir() and
4178 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4179 * anyway so that locking is contained inside cgroup proper and we
4180 * don't get nasty surprises if we ever grow another caller.
4182 if (!cgroup_lock_live_group(parent)) {
4187 /* Grab a reference on the superblock so the hierarchy doesn't
4188 * get deleted on unmount if there are child cgroups. This
4189 * can be done outside cgroup_mutex, since the sb can't
4190 * disappear while someone has an open control file on the
4192 atomic_inc(&sb->s_active);
4194 init_cgroup_housekeeping(cgrp);
4196 dentry->d_fsdata = cgrp;
4197 cgrp->dentry = dentry;
4199 cgrp->parent = parent;
4200 cgrp->dummy_css.parent = &parent->dummy_css;
4201 cgrp->root = parent->root;
4203 if (notify_on_release(parent))
4204 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4206 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4207 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4209 for_each_root_subsys(root, ss) {
4210 struct cgroup_subsys_state *css;
4212 css = ss->css_alloc(cgroup_css(parent, ss));
4217 css_ar[ss->subsys_id] = css;
4219 err = percpu_ref_init(&css->refcnt, css_release);
4223 init_css(css, ss, cgrp);
4226 err = alloc_css_id(css);
4233 * Create directory. cgroup_create_file() returns with the new
4234 * directory locked on success so that it can be populated without
4235 * dropping cgroup_mutex.
4237 err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4240 lockdep_assert_held(&dentry->d_inode->i_mutex);
4242 cgrp->serial_nr = cgroup_serial_nr_next++;
4244 /* allocation complete, commit to creation */
4245 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4246 root->number_of_cgroups++;
4248 /* each css holds a ref to the cgroup's dentry and the parent css */
4249 for_each_root_subsys(root, ss) {
4250 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4253 css_get(css->parent);
4256 /* hold a ref to the parent's dentry */
4257 dget(parent->dentry);
4259 /* creation succeeded, notify subsystems */
4260 for_each_root_subsys(root, ss) {
4261 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4263 err = online_css(css);
4267 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4269 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",
4270 current->comm, current->pid, ss->name);
4271 if (!strcmp(ss->name, "memory"))
4272 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4273 ss->warned_broken_hierarchy = true;
4277 idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4279 err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
4283 err = cgroup_populate_dir(cgrp, root->subsys_mask);
4287 mutex_unlock(&cgroup_mutex);
4288 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4293 for_each_root_subsys(root, ss) {
4294 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4297 percpu_ref_cancel_init(&css->refcnt);
4301 mutex_unlock(&cgroup_mutex);
4302 /* Release the reference count that we took on the superblock */
4303 deactivate_super(sb);
4305 idr_remove(&root->cgroup_idr, cgrp->id);
4307 kfree(rcu_dereference_raw(cgrp->name));
4313 cgroup_destroy_locked(cgrp);
4314 mutex_unlock(&cgroup_mutex);
4315 mutex_unlock(&dentry->d_inode->i_mutex);
4319 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4321 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4323 /* the vfs holds inode->i_mutex already */
4324 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4328 * This is called when the refcnt of a css is confirmed to be killed.
4329 * css_tryget() is now guaranteed to fail.
4331 static void css_killed_work_fn(struct work_struct *work)
4333 struct cgroup_subsys_state *css =
4334 container_of(work, struct cgroup_subsys_state, destroy_work);
4335 struct cgroup *cgrp = css->cgroup;
4337 mutex_lock(&cgroup_mutex);
4340 * css_tryget() is guaranteed to fail now. Tell subsystems to
4341 * initate destruction.
4346 * If @cgrp is marked dead, it's waiting for refs of all css's to
4347 * be disabled before proceeding to the second phase of cgroup
4348 * destruction. If we are the last one, kick it off.
4350 if (!cgrp->nr_css && cgroup_is_dead(cgrp))
4351 cgroup_destroy_css_killed(cgrp);
4353 mutex_unlock(&cgroup_mutex);
4356 * Put the css refs from kill_css(). Each css holds an extra
4357 * reference to the cgroup's dentry and cgroup removal proceeds
4358 * regardless of css refs. On the last put of each css, whenever
4359 * that may be, the extra dentry ref is put so that dentry
4360 * destruction happens only after all css's are released.
4365 /* css kill confirmation processing requires process context, bounce */
4366 static void css_killed_ref_fn(struct percpu_ref *ref)
4368 struct cgroup_subsys_state *css =
4369 container_of(ref, struct cgroup_subsys_state, refcnt);
4371 INIT_WORK(&css->destroy_work, css_killed_work_fn);
4372 schedule_work(&css->destroy_work);
4376 * kill_css - destroy a css
4377 * @css: css to destroy
4379 * This function initiates destruction of @css by removing cgroup interface
4380 * files and putting its base reference. ->css_offline() will be invoked
4381 * asynchronously once css_tryget() is guaranteed to fail and when the
4382 * reference count reaches zero, @css will be released.
4384 static void kill_css(struct cgroup_subsys_state *css)
4386 cgroup_clear_dir(css->cgroup, 1 << css->ss->subsys_id);
4389 * Killing would put the base ref, but we need to keep it alive
4390 * until after ->css_offline().
4395 * cgroup core guarantees that, by the time ->css_offline() is
4396 * invoked, no new css reference will be given out via
4397 * css_tryget(). We can't simply call percpu_ref_kill() and
4398 * proceed to offlining css's because percpu_ref_kill() doesn't
4399 * guarantee that the ref is seen as killed on all CPUs on return.
4401 * Use percpu_ref_kill_and_confirm() to get notifications as each
4402 * css is confirmed to be seen as killed on all CPUs.
4404 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4408 * cgroup_destroy_locked - the first stage of cgroup destruction
4409 * @cgrp: cgroup to be destroyed
4411 * css's make use of percpu refcnts whose killing latency shouldn't be
4412 * exposed to userland and are RCU protected. Also, cgroup core needs to
4413 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
4414 * invoked. To satisfy all the requirements, destruction is implemented in
4415 * the following two steps.
4417 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4418 * userland visible parts and start killing the percpu refcnts of
4419 * css's. Set up so that the next stage will be kicked off once all
4420 * the percpu refcnts are confirmed to be killed.
4422 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4423 * rest of destruction. Once all cgroup references are gone, the
4424 * cgroup is RCU-freed.
4426 * This function implements s1. After this step, @cgrp is gone as far as
4427 * the userland is concerned and a new cgroup with the same name may be
4428 * created. As cgroup doesn't care about the names internally, this
4429 * doesn't cause any problem.
4431 static int cgroup_destroy_locked(struct cgroup *cgrp)
4432 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4434 struct dentry *d = cgrp->dentry;
4435 struct cgroup_subsys *ss;
4436 struct cgroup *child;
4439 lockdep_assert_held(&d->d_inode->i_mutex);
4440 lockdep_assert_held(&cgroup_mutex);
4443 * css_set_lock synchronizes access to ->cset_links and prevents
4444 * @cgrp from being removed while __put_css_set() is in progress.
4446 read_lock(&css_set_lock);
4447 empty = list_empty(&cgrp->cset_links);
4448 read_unlock(&css_set_lock);
4453 * Make sure there's no live children. We can't test ->children
4454 * emptiness as dead children linger on it while being destroyed;
4455 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
4459 list_for_each_entry_rcu(child, &cgrp->children, sibling) {
4460 empty = cgroup_is_dead(child);
4469 * Initiate massacre of all css's. cgroup_destroy_css_killed()
4470 * will be invoked to perform the rest of destruction once the
4471 * percpu refs of all css's are confirmed to be killed.
4473 for_each_root_subsys(cgrp->root, ss)
4474 kill_css(cgroup_css(cgrp, ss));
4477 * Mark @cgrp dead. This prevents further task migration and child
4478 * creation by disabling cgroup_lock_live_group(). Note that
4479 * CGRP_DEAD assertion is depended upon by css_next_child() to
4480 * resume iteration after dropping RCU read lock. See
4481 * css_next_child() for details.
4483 set_bit(CGRP_DEAD, &cgrp->flags);
4485 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4486 raw_spin_lock(&release_list_lock);
4487 if (!list_empty(&cgrp->release_list))
4488 list_del_init(&cgrp->release_list);
4489 raw_spin_unlock(&release_list_lock);
4492 * If @cgrp has css's attached, the second stage of cgroup
4493 * destruction is kicked off from css_killed_work_fn() after the
4494 * refs of all attached css's are killed. If @cgrp doesn't have
4495 * any css, we kick it off here.
4498 cgroup_destroy_css_killed(cgrp);
4501 * Clear the base files and remove @cgrp directory. The removal
4502 * puts the base ref but we aren't quite done with @cgrp yet, so
4505 cgroup_addrm_files(cgrp, cgroup_base_files, false);
4507 cgroup_d_remove_dir(d);
4513 * cgroup_destroy_css_killed - the second step of cgroup destruction
4514 * @work: cgroup->destroy_free_work
4516 * This function is invoked from a work item for a cgroup which is being
4517 * destroyed after all css's are offlined and performs the rest of
4518 * destruction. This is the second step of destruction described in the
4519 * comment above cgroup_destroy_locked().
4521 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
4523 struct cgroup *parent = cgrp->parent;
4524 struct dentry *d = cgrp->dentry;
4526 lockdep_assert_held(&cgroup_mutex);
4528 /* delete this cgroup from parent->children */
4529 list_del_rcu(&cgrp->sibling);
4532 * We should remove the cgroup object from idr before its grace
4533 * period starts, so we won't be looking up a cgroup while the
4534 * cgroup is being freed.
4536 idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4541 set_bit(CGRP_RELEASABLE, &parent->flags);
4542 check_for_release(parent);
4545 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4549 mutex_lock(&cgroup_mutex);
4550 ret = cgroup_destroy_locked(dentry->d_fsdata);
4551 mutex_unlock(&cgroup_mutex);
4556 static void __init_or_module cgroup_init_cftsets(struct cgroup_subsys *ss)
4558 INIT_LIST_HEAD(&ss->cftsets);
4561 * base_cftset is embedded in subsys itself, no need to worry about
4564 if (ss->base_cftypes) {
4567 for (cft = ss->base_cftypes; cft->name[0] != '\0'; cft++)
4570 ss->base_cftset.cfts = ss->base_cftypes;
4571 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4575 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4577 struct cgroup_subsys_state *css;
4579 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4581 mutex_lock(&cgroup_mutex);
4583 /* init base cftset */
4584 cgroup_init_cftsets(ss);
4586 /* Create the top cgroup state for this subsystem */
4587 list_add(&ss->sibling, &cgroup_dummy_root.subsys_list);
4588 ss->root = &cgroup_dummy_root;
4589 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
4590 /* We don't handle early failures gracefully */
4591 BUG_ON(IS_ERR(css));
4592 init_css(css, ss, cgroup_dummy_top);
4594 /* Update the init_css_set to contain a subsys
4595 * pointer to this state - since the subsystem is
4596 * newly registered, all tasks and hence the
4597 * init_css_set is in the subsystem's top cgroup. */
4598 init_css_set.subsys[ss->subsys_id] = css;
4600 need_forkexit_callback |= ss->fork || ss->exit;
4602 /* At system boot, before all subsystems have been
4603 * registered, no tasks have been forked, so we don't
4604 * need to invoke fork callbacks here. */
4605 BUG_ON(!list_empty(&init_task.tasks));
4607 BUG_ON(online_css(css));
4609 mutex_unlock(&cgroup_mutex);
4611 /* this function shouldn't be used with modular subsystems, since they
4612 * need to register a subsys_id, among other things */
4617 * cgroup_load_subsys: load and register a modular subsystem at runtime
4618 * @ss: the subsystem to load
4620 * This function should be called in a modular subsystem's initcall. If the
4621 * subsystem is built as a module, it will be assigned a new subsys_id and set
4622 * up for use. If the subsystem is built-in anyway, work is delegated to the
4623 * simpler cgroup_init_subsys.
4625 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
4627 struct cgroup_subsys_state *css;
4629 struct hlist_node *tmp;
4630 struct css_set *cset;
4633 /* check name and function validity */
4634 if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
4635 ss->css_alloc == NULL || ss->css_free == NULL)
4639 * we don't support callbacks in modular subsystems. this check is
4640 * before the ss->module check for consistency; a subsystem that could
4641 * be a module should still have no callbacks even if the user isn't
4642 * compiling it as one.
4644 if (ss->fork || ss->exit)
4648 * an optionally modular subsystem is built-in: we want to do nothing,
4649 * since cgroup_init_subsys will have already taken care of it.
4651 if (ss->module == NULL) {
4652 /* a sanity check */
4653 BUG_ON(cgroup_subsys[ss->subsys_id] != ss);
4657 /* init base cftset */
4658 cgroup_init_cftsets(ss);
4660 mutex_lock(&cgroup_mutex);
4661 cgroup_subsys[ss->subsys_id] = ss;
4664 * no ss->css_alloc seems to need anything important in the ss
4665 * struct, so this can happen first (i.e. before the dummy root
4668 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
4670 /* failure case - need to deassign the cgroup_subsys[] slot. */
4671 cgroup_subsys[ss->subsys_id] = NULL;
4672 mutex_unlock(&cgroup_mutex);
4673 return PTR_ERR(css);
4676 list_add(&ss->sibling, &cgroup_dummy_root.subsys_list);
4677 ss->root = &cgroup_dummy_root;
4679 /* our new subsystem will be attached to the dummy hierarchy. */
4680 init_css(css, ss, cgroup_dummy_top);
4681 /* init_idr must be after init_css() because it sets css->id. */
4683 ret = cgroup_init_idr(ss, css);
4689 * Now we need to entangle the css into the existing css_sets. unlike
4690 * in cgroup_init_subsys, there are now multiple css_sets, so each one
4691 * will need a new pointer to it; done by iterating the css_set_table.
4692 * furthermore, modifying the existing css_sets will corrupt the hash
4693 * table state, so each changed css_set will need its hash recomputed.
4694 * this is all done under the css_set_lock.
4696 write_lock(&css_set_lock);
4697 hash_for_each_safe(css_set_table, i, tmp, cset, hlist) {
4698 /* skip entries that we already rehashed */
4699 if (cset->subsys[ss->subsys_id])
4701 /* remove existing entry */
4702 hash_del(&cset->hlist);
4704 cset->subsys[ss->subsys_id] = css;
4705 /* recompute hash and restore entry */
4706 key = css_set_hash(cset->subsys);
4707 hash_add(css_set_table, &cset->hlist, key);
4709 write_unlock(&css_set_lock);
4711 ret = online_css(css);
4716 mutex_unlock(&cgroup_mutex);
4720 mutex_unlock(&cgroup_mutex);
4721 /* @ss can't be mounted here as try_module_get() would fail */
4722 cgroup_unload_subsys(ss);
4725 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
4728 * cgroup_unload_subsys: unload a modular subsystem
4729 * @ss: the subsystem to unload
4731 * This function should be called in a modular subsystem's exitcall. When this
4732 * function is invoked, the refcount on the subsystem's module will be 0, so
4733 * the subsystem will not be attached to any hierarchy.
4735 void cgroup_unload_subsys(struct cgroup_subsys *ss)
4737 struct cgrp_cset_link *link;
4739 BUG_ON(ss->module == NULL);
4742 * we shouldn't be called if the subsystem is in use, and the use of
4743 * try_module_get() in rebind_subsystems() should ensure that it
4744 * doesn't start being used while we're killing it off.
4746 BUG_ON(ss->root != &cgroup_dummy_root);
4748 mutex_lock(&cgroup_mutex);
4750 offline_css(cgroup_css(cgroup_dummy_top, ss));
4753 idr_destroy(&ss->idr);
4755 /* deassign the subsys_id */
4756 cgroup_subsys[ss->subsys_id] = NULL;
4758 /* remove subsystem from the dummy root's list of subsystems */
4759 list_del_init(&ss->sibling);
4762 * disentangle the css from all css_sets attached to the dummy
4763 * top. as in loading, we need to pay our respects to the hashtable
4766 write_lock(&css_set_lock);
4767 list_for_each_entry(link, &cgroup_dummy_top->cset_links, cset_link) {
4768 struct css_set *cset = link->cset;
4771 hash_del(&cset->hlist);
4772 cset->subsys[ss->subsys_id] = NULL;
4773 key = css_set_hash(cset->subsys);
4774 hash_add(css_set_table, &cset->hlist, key);
4776 write_unlock(&css_set_lock);
4779 * remove subsystem's css from the cgroup_dummy_top and free it -
4780 * need to free before marking as null because ss->css_free needs
4781 * the cgrp->subsys pointer to find their state. note that this
4782 * also takes care of freeing the css_id.
4784 ss->css_free(cgroup_css(cgroup_dummy_top, ss));
4785 RCU_INIT_POINTER(cgroup_dummy_top->subsys[ss->subsys_id], NULL);
4787 mutex_unlock(&cgroup_mutex);
4789 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
4792 * cgroup_init_early - cgroup initialization at system boot
4794 * Initialize cgroups at system boot, and initialize any
4795 * subsystems that request early init.
4797 int __init cgroup_init_early(void)
4799 struct cgroup_subsys *ss;
4802 atomic_set(&init_css_set.refcount, 1);
4803 INIT_LIST_HEAD(&init_css_set.cgrp_links);
4804 INIT_LIST_HEAD(&init_css_set.tasks);
4805 INIT_HLIST_NODE(&init_css_set.hlist);
4807 init_cgroup_root(&cgroup_dummy_root);
4808 cgroup_root_count = 1;
4809 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4811 init_cgrp_cset_link.cset = &init_css_set;
4812 init_cgrp_cset_link.cgrp = cgroup_dummy_top;
4813 list_add(&init_cgrp_cset_link.cset_link, &cgroup_dummy_top->cset_links);
4814 list_add(&init_cgrp_cset_link.cgrp_link, &init_css_set.cgrp_links);
4816 /* at bootup time, we don't worry about modular subsystems */
4817 for_each_builtin_subsys(ss, i) {
4819 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
4820 BUG_ON(!ss->css_alloc);
4821 BUG_ON(!ss->css_free);
4822 if (ss->subsys_id != i) {
4823 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
4824 ss->name, ss->subsys_id);
4829 cgroup_init_subsys(ss);
4835 * cgroup_init - cgroup initialization
4837 * Register cgroup filesystem and /proc file, and initialize
4838 * any subsystems that didn't request early init.
4840 int __init cgroup_init(void)
4842 struct cgroup_subsys *ss;
4846 err = bdi_init(&cgroup_backing_dev_info);
4850 for_each_builtin_subsys(ss, i) {
4851 if (!ss->early_init)
4852 cgroup_init_subsys(ss);
4854 cgroup_init_idr(ss, init_css_set.subsys[ss->subsys_id]);
4857 /* allocate id for the dummy hierarchy */
4858 mutex_lock(&cgroup_mutex);
4859 mutex_lock(&cgroup_root_mutex);
4861 /* Add init_css_set to the hash table */
4862 key = css_set_hash(init_css_set.subsys);
4863 hash_add(css_set_table, &init_css_set.hlist, key);
4865 BUG_ON(cgroup_init_root_id(&cgroup_dummy_root, 0, 1));
4867 err = idr_alloc(&cgroup_dummy_root.cgroup_idr, cgroup_dummy_top,
4871 mutex_unlock(&cgroup_root_mutex);
4872 mutex_unlock(&cgroup_mutex);
4874 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4880 err = register_filesystem(&cgroup_fs_type);
4882 kobject_put(cgroup_kobj);
4886 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4890 bdi_destroy(&cgroup_backing_dev_info);
4896 * proc_cgroup_show()
4897 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4898 * - Used for /proc/<pid>/cgroup.
4899 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4900 * doesn't really matter if tsk->cgroup changes after we read it,
4901 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4902 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4903 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4904 * cgroup to top_cgroup.
4907 /* TODO: Use a proper seq_file iterator */
4908 int proc_cgroup_show(struct seq_file *m, void *v)
4911 struct task_struct *tsk;
4914 struct cgroupfs_root *root;
4917 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4923 tsk = get_pid_task(pid, PIDTYPE_PID);
4929 mutex_lock(&cgroup_mutex);
4931 for_each_active_root(root) {
4932 struct cgroup_subsys *ss;
4933 struct cgroup *cgrp;
4936 seq_printf(m, "%d:", root->hierarchy_id);
4937 for_each_root_subsys(root, ss)
4938 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4939 if (strlen(root->name))
4940 seq_printf(m, "%sname=%s", count ? "," : "",
4943 cgrp = task_cgroup_from_root(tsk, root);
4944 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
4952 mutex_unlock(&cgroup_mutex);
4953 put_task_struct(tsk);
4960 /* Display information about each subsystem and each hierarchy */
4961 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4963 struct cgroup_subsys *ss;
4966 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4968 * ideally we don't want subsystems moving around while we do this.
4969 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4970 * subsys/hierarchy state.
4972 mutex_lock(&cgroup_mutex);
4974 for_each_subsys(ss, i)
4975 seq_printf(m, "%s\t%d\t%d\t%d\n",
4976 ss->name, ss->root->hierarchy_id,
4977 ss->root->number_of_cgroups, !ss->disabled);
4979 mutex_unlock(&cgroup_mutex);
4983 static int cgroupstats_open(struct inode *inode, struct file *file)
4985 return single_open(file, proc_cgroupstats_show, NULL);
4988 static const struct file_operations proc_cgroupstats_operations = {
4989 .open = cgroupstats_open,
4991 .llseek = seq_lseek,
4992 .release = single_release,
4996 * cgroup_fork - attach newly forked task to its parents cgroup.
4997 * @child: pointer to task_struct of forking parent process.
4999 * Description: A task inherits its parent's cgroup at fork().
5001 * A pointer to the shared css_set was automatically copied in
5002 * fork.c by dup_task_struct(). However, we ignore that copy, since
5003 * it was not made under the protection of RCU or cgroup_mutex, so
5004 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
5005 * have already changed current->cgroups, allowing the previously
5006 * referenced cgroup group to be removed and freed.
5008 * At the point that cgroup_fork() is called, 'current' is the parent
5009 * task, and the passed argument 'child' points to the child task.
5011 void cgroup_fork(struct task_struct *child)
5014 get_css_set(task_css_set(current));
5015 child->cgroups = current->cgroups;
5016 task_unlock(current);
5017 INIT_LIST_HEAD(&child->cg_list);
5021 * cgroup_post_fork - called on a new task after adding it to the task list
5022 * @child: the task in question
5024 * Adds the task to the list running through its css_set if necessary and
5025 * call the subsystem fork() callbacks. Has to be after the task is
5026 * visible on the task list in case we race with the first call to
5027 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
5030 void cgroup_post_fork(struct task_struct *child)
5032 struct cgroup_subsys *ss;
5036 * use_task_css_set_links is set to 1 before we walk the tasklist
5037 * under the tasklist_lock and we read it here after we added the child
5038 * to the tasklist under the tasklist_lock as well. If the child wasn't
5039 * yet in the tasklist when we walked through it from
5040 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
5041 * should be visible now due to the paired locking and barriers implied
5042 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
5043 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
5046 if (use_task_css_set_links) {
5047 write_lock(&css_set_lock);
5049 if (list_empty(&child->cg_list))
5050 list_add(&child->cg_list, &task_css_set(child)->tasks);
5052 write_unlock(&css_set_lock);
5056 * Call ss->fork(). This must happen after @child is linked on
5057 * css_set; otherwise, @child might change state between ->fork()
5058 * and addition to css_set.
5060 if (need_forkexit_callback) {
5062 * fork/exit callbacks are supported only for builtin
5063 * subsystems, and the builtin section of the subsys
5064 * array is immutable, so we don't need to lock the
5065 * subsys array here. On the other hand, modular section
5066 * of the array can be freed at module unload, so we
5069 for_each_builtin_subsys(ss, i)
5076 * cgroup_exit - detach cgroup from exiting task
5077 * @tsk: pointer to task_struct of exiting process
5078 * @run_callback: run exit callbacks?
5080 * Description: Detach cgroup from @tsk and release it.
5082 * Note that cgroups marked notify_on_release force every task in
5083 * them to take the global cgroup_mutex mutex when exiting.
5084 * This could impact scaling on very large systems. Be reluctant to
5085 * use notify_on_release cgroups where very high task exit scaling
5086 * is required on large systems.
5088 * the_top_cgroup_hack:
5090 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
5092 * We call cgroup_exit() while the task is still competent to
5093 * handle notify_on_release(), then leave the task attached to the
5094 * root cgroup in each hierarchy for the remainder of its exit.
5096 * To do this properly, we would increment the reference count on
5097 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
5098 * code we would add a second cgroup function call, to drop that
5099 * reference. This would just create an unnecessary hot spot on
5100 * the top_cgroup reference count, to no avail.
5102 * Normally, holding a reference to a cgroup without bumping its
5103 * count is unsafe. The cgroup could go away, or someone could
5104 * attach us to a different cgroup, decrementing the count on
5105 * the first cgroup that we never incremented. But in this case,
5106 * top_cgroup isn't going away, and either task has PF_EXITING set,
5107 * which wards off any cgroup_attach_task() attempts, or task is a failed
5108 * fork, never visible to cgroup_attach_task.
5110 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
5112 struct cgroup_subsys *ss;
5113 struct css_set *cset;
5117 * Unlink from the css_set task list if necessary.
5118 * Optimistically check cg_list before taking
5121 if (!list_empty(&tsk->cg_list)) {
5122 write_lock(&css_set_lock);
5123 if (!list_empty(&tsk->cg_list))
5124 list_del_init(&tsk->cg_list);
5125 write_unlock(&css_set_lock);
5128 /* Reassign the task to the init_css_set. */
5130 cset = task_css_set(tsk);
5131 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
5133 if (run_callbacks && need_forkexit_callback) {
5135 * fork/exit callbacks are supported only for builtin
5136 * subsystems, see cgroup_post_fork() for details.
5138 for_each_builtin_subsys(ss, i) {
5140 struct cgroup_subsys_state *old_css = cset->subsys[i];
5141 struct cgroup_subsys_state *css = task_css(tsk, i);
5143 ss->exit(css, old_css, tsk);
5149 put_css_set_taskexit(cset);
5152 static void check_for_release(struct cgroup *cgrp)
5154 if (cgroup_is_releasable(cgrp) &&
5155 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
5157 * Control Group is currently removeable. If it's not
5158 * already queued for a userspace notification, queue
5161 int need_schedule_work = 0;
5163 raw_spin_lock(&release_list_lock);
5164 if (!cgroup_is_dead(cgrp) &&
5165 list_empty(&cgrp->release_list)) {
5166 list_add(&cgrp->release_list, &release_list);
5167 need_schedule_work = 1;
5169 raw_spin_unlock(&release_list_lock);
5170 if (need_schedule_work)
5171 schedule_work(&release_agent_work);
5176 * Notify userspace when a cgroup is released, by running the
5177 * configured release agent with the name of the cgroup (path
5178 * relative to the root of cgroup file system) as the argument.
5180 * Most likely, this user command will try to rmdir this cgroup.
5182 * This races with the possibility that some other task will be
5183 * attached to this cgroup before it is removed, or that some other
5184 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5185 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5186 * unused, and this cgroup will be reprieved from its death sentence,
5187 * to continue to serve a useful existence. Next time it's released,
5188 * we will get notified again, if it still has 'notify_on_release' set.
5190 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5191 * means only wait until the task is successfully execve()'d. The
5192 * separate release agent task is forked by call_usermodehelper(),
5193 * then control in this thread returns here, without waiting for the
5194 * release agent task. We don't bother to wait because the caller of
5195 * this routine has no use for the exit status of the release agent
5196 * task, so no sense holding our caller up for that.
5198 static void cgroup_release_agent(struct work_struct *work)
5200 BUG_ON(work != &release_agent_work);
5201 mutex_lock(&cgroup_mutex);
5202 raw_spin_lock(&release_list_lock);
5203 while (!list_empty(&release_list)) {
5204 char *argv[3], *envp[3];
5206 char *pathbuf = NULL, *agentbuf = NULL;
5207 struct cgroup *cgrp = list_entry(release_list.next,
5210 list_del_init(&cgrp->release_list);
5211 raw_spin_unlock(&release_list_lock);
5212 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5215 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
5217 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5222 argv[i++] = agentbuf;
5223 argv[i++] = pathbuf;
5227 /* minimal command environment */
5228 envp[i++] = "HOME=/";
5229 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5232 /* Drop the lock while we invoke the usermode helper,
5233 * since the exec could involve hitting disk and hence
5234 * be a slow process */
5235 mutex_unlock(&cgroup_mutex);
5236 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5237 mutex_lock(&cgroup_mutex);
5241 raw_spin_lock(&release_list_lock);
5243 raw_spin_unlock(&release_list_lock);
5244 mutex_unlock(&cgroup_mutex);
5247 static int __init cgroup_disable(char *str)
5249 struct cgroup_subsys *ss;
5253 while ((token = strsep(&str, ",")) != NULL) {
5258 * cgroup_disable, being at boot time, can't know about
5259 * module subsystems, so we don't worry about them.
5261 for_each_builtin_subsys(ss, i) {
5262 if (!strcmp(token, ss->name)) {
5264 printk(KERN_INFO "Disabling %s control group"
5265 " subsystem\n", ss->name);
5272 __setup("cgroup_disable=", cgroup_disable);
5275 * Functons for CSS ID.
5278 /* to get ID other than 0, this should be called when !cgroup_is_dead() */
5279 unsigned short css_id(struct cgroup_subsys_state *css)
5281 struct css_id *cssid;
5284 * This css_id() can return correct value when somone has refcnt
5285 * on this or this is under rcu_read_lock(). Once css->id is allocated,
5286 * it's unchanged until freed.
5288 cssid = rcu_dereference_raw(css->id);
5294 EXPORT_SYMBOL_GPL(css_id);
5297 * css_is_ancestor - test "root" css is an ancestor of "child"
5298 * @child: the css to be tested.
5299 * @root: the css supporsed to be an ancestor of the child.
5301 * Returns true if "root" is an ancestor of "child" in its hierarchy. Because
5302 * this function reads css->id, the caller must hold rcu_read_lock().
5303 * But, considering usual usage, the csses should be valid objects after test.
5304 * Assuming that the caller will do some action to the child if this returns
5305 * returns true, the caller must take "child";s reference count.
5306 * If "child" is valid object and this returns true, "root" is valid, too.
5309 bool css_is_ancestor(struct cgroup_subsys_state *child,
5310 const struct cgroup_subsys_state *root)
5312 struct css_id *child_id;
5313 struct css_id *root_id;
5315 child_id = rcu_dereference(child->id);
5318 root_id = rcu_dereference(root->id);
5321 if (child_id->depth < root_id->depth)
5323 if (child_id->stack[root_id->depth] != root_id->id)
5328 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
5330 struct css_id *id = rcu_dereference_protected(css->id, true);
5332 /* When this is called before css_id initialization, id can be NULL */
5336 BUG_ON(!ss->use_id);
5338 rcu_assign_pointer(id->css, NULL);
5339 rcu_assign_pointer(css->id, NULL);
5340 spin_lock(&ss->id_lock);
5341 idr_remove(&ss->idr, id->id);
5342 spin_unlock(&ss->id_lock);
5343 kfree_rcu(id, rcu_head);
5345 EXPORT_SYMBOL_GPL(free_css_id);
5348 * This is called by init or create(). Then, calls to this function are
5349 * always serialized (By cgroup_mutex() at create()).
5352 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
5354 struct css_id *newid;
5357 BUG_ON(!ss->use_id);
5359 size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
5360 newid = kzalloc(size, GFP_KERNEL);
5362 return ERR_PTR(-ENOMEM);
5364 idr_preload(GFP_KERNEL);
5365 spin_lock(&ss->id_lock);
5366 /* Don't use 0. allocates an ID of 1-65535 */
5367 ret = idr_alloc(&ss->idr, newid, 1, CSS_ID_MAX + 1, GFP_NOWAIT);
5368 spin_unlock(&ss->id_lock);
5371 /* Returns error when there are no free spaces for new ID.*/
5376 newid->depth = depth;
5380 return ERR_PTR(ret);
5384 static int __init_or_module cgroup_init_idr(struct cgroup_subsys *ss,
5385 struct cgroup_subsys_state *rootcss)
5387 struct css_id *newid;
5389 spin_lock_init(&ss->id_lock);
5392 newid = get_new_cssid(ss, 0);
5394 return PTR_ERR(newid);
5396 newid->stack[0] = newid->id;
5397 RCU_INIT_POINTER(newid->css, rootcss);
5398 RCU_INIT_POINTER(rootcss->id, newid);
5402 static int alloc_css_id(struct cgroup_subsys_state *child_css)
5404 struct cgroup_subsys_state *parent_css = css_parent(child_css);
5405 struct css_id *child_id, *parent_id;
5408 parent_id = rcu_dereference_protected(parent_css->id, true);
5409 depth = parent_id->depth + 1;
5411 child_id = get_new_cssid(child_css->ss, depth);
5412 if (IS_ERR(child_id))
5413 return PTR_ERR(child_id);
5415 for (i = 0; i < depth; i++)
5416 child_id->stack[i] = parent_id->stack[i];
5417 child_id->stack[depth] = child_id->id;
5419 * child_id->css pointer will be set after this cgroup is available
5420 * see cgroup_populate_dir()
5422 rcu_assign_pointer(child_css->id, child_id);
5428 * css_lookup - lookup css by id
5429 * @ss: cgroup subsys to be looked into.
5432 * Returns pointer to cgroup_subsys_state if there is valid one with id.
5433 * NULL if not. Should be called under rcu_read_lock()
5435 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
5437 struct css_id *cssid = NULL;
5439 BUG_ON(!ss->use_id);
5440 cssid = idr_find(&ss->idr, id);
5442 if (unlikely(!cssid))
5445 return rcu_dereference(cssid->css);
5447 EXPORT_SYMBOL_GPL(css_lookup);
5450 * css_from_dir - get corresponding css from the dentry of a cgroup dir
5451 * @dentry: directory dentry of interest
5452 * @ss: subsystem of interest
5454 * Must be called under RCU read lock. The caller is responsible for
5455 * pinning the returned css if it needs to be accessed outside the RCU
5458 struct cgroup_subsys_state *css_from_dir(struct dentry *dentry,
5459 struct cgroup_subsys *ss)
5461 struct cgroup *cgrp;
5463 WARN_ON_ONCE(!rcu_read_lock_held());
5465 /* is @dentry a cgroup dir? */
5466 if (!dentry->d_inode ||
5467 dentry->d_inode->i_op != &cgroup_dir_inode_operations)
5468 return ERR_PTR(-EBADF);
5470 cgrp = __d_cgrp(dentry);
5471 return cgroup_css(cgrp, ss) ?: ERR_PTR(-ENOENT);
5475 * css_from_id - lookup css by id
5476 * @id: the cgroup id
5477 * @ss: cgroup subsys to be looked into
5479 * Returns the css if there's valid one with @id, otherwise returns NULL.
5480 * Should be called under rcu_read_lock().
5482 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5484 struct cgroup *cgrp;
5486 rcu_lockdep_assert(rcu_read_lock_held() ||
5487 lockdep_is_held(&cgroup_mutex),
5488 "css_from_id() needs proper protection");
5490 cgrp = idr_find(&ss->root->cgroup_idr, id);
5492 return cgroup_css(cgrp, ss);
5496 #ifdef CONFIG_CGROUP_DEBUG
5497 static struct cgroup_subsys_state *
5498 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5500 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5503 return ERR_PTR(-ENOMEM);
5508 static void debug_css_free(struct cgroup_subsys_state *css)
5513 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5516 return cgroup_task_count(css->cgroup);
5519 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5522 return (u64)(unsigned long)current->cgroups;
5525 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5531 count = atomic_read(&task_css_set(current)->refcount);
5536 static int current_css_set_cg_links_read(struct cgroup_subsys_state *css,
5538 struct seq_file *seq)
5540 struct cgrp_cset_link *link;
5541 struct css_set *cset;
5543 read_lock(&css_set_lock);
5545 cset = rcu_dereference(current->cgroups);
5546 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5547 struct cgroup *c = link->cgrp;
5551 name = c->dentry->d_name.name;
5554 seq_printf(seq, "Root %d group %s\n",
5555 c->root->hierarchy_id, name);
5558 read_unlock(&css_set_lock);
5562 #define MAX_TASKS_SHOWN_PER_CSS 25
5563 static int cgroup_css_links_read(struct cgroup_subsys_state *css,
5564 struct cftype *cft, struct seq_file *seq)
5566 struct cgrp_cset_link *link;
5568 read_lock(&css_set_lock);
5569 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5570 struct css_set *cset = link->cset;
5571 struct task_struct *task;
5573 seq_printf(seq, "css_set %p\n", cset);
5574 list_for_each_entry(task, &cset->tasks, cg_list) {
5575 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5576 seq_puts(seq, " ...\n");
5579 seq_printf(seq, " task %d\n",
5580 task_pid_vnr(task));
5584 read_unlock(&css_set_lock);
5588 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5590 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
5593 static struct cftype debug_files[] = {
5595 .name = "taskcount",
5596 .read_u64 = debug_taskcount_read,
5600 .name = "current_css_set",
5601 .read_u64 = current_css_set_read,
5605 .name = "current_css_set_refcount",
5606 .read_u64 = current_css_set_refcount_read,
5610 .name = "current_css_set_cg_links",
5611 .read_seq_string = current_css_set_cg_links_read,
5615 .name = "cgroup_css_links",
5616 .read_seq_string = cgroup_css_links_read,
5620 .name = "releasable",
5621 .read_u64 = releasable_read,
5627 struct cgroup_subsys debug_subsys = {
5629 .css_alloc = debug_css_alloc,
5630 .css_free = debug_css_free,
5631 .subsys_id = debug_subsys_id,
5632 .base_cftypes = debug_files,
5634 #endif /* CONFIG_CGROUP_DEBUG */