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 simple_xattrs_init(&cgrp->xattrs);
1358 static void init_cgroup_root(struct cgroupfs_root *root)
1360 struct cgroup *cgrp = &root->top_cgroup;
1362 INIT_LIST_HEAD(&root->subsys_list);
1363 INIT_LIST_HEAD(&root->root_list);
1364 root->number_of_cgroups = 1;
1366 RCU_INIT_POINTER(cgrp->name, &root_cgroup_name);
1367 init_cgroup_housekeeping(cgrp);
1368 idr_init(&root->cgroup_idr);
1371 static int cgroup_init_root_id(struct cgroupfs_root *root, int start, int end)
1375 lockdep_assert_held(&cgroup_mutex);
1376 lockdep_assert_held(&cgroup_root_mutex);
1378 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, start, end,
1383 root->hierarchy_id = id;
1387 static void cgroup_exit_root_id(struct cgroupfs_root *root)
1389 lockdep_assert_held(&cgroup_mutex);
1390 lockdep_assert_held(&cgroup_root_mutex);
1392 if (root->hierarchy_id) {
1393 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1394 root->hierarchy_id = 0;
1398 static int cgroup_test_super(struct super_block *sb, void *data)
1400 struct cgroup_sb_opts *opts = data;
1401 struct cgroupfs_root *root = sb->s_fs_info;
1403 /* If we asked for a name then it must match */
1404 if (opts->name && strcmp(opts->name, root->name))
1408 * If we asked for subsystems (or explicitly for no
1409 * subsystems) then they must match
1411 if ((opts->subsys_mask || opts->none)
1412 && (opts->subsys_mask != root->subsys_mask))
1418 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1420 struct cgroupfs_root *root;
1422 if (!opts->subsys_mask && !opts->none)
1425 root = kzalloc(sizeof(*root), GFP_KERNEL);
1427 return ERR_PTR(-ENOMEM);
1429 init_cgroup_root(root);
1432 * We need to set @root->subsys_mask now so that @root can be
1433 * matched by cgroup_test_super() before it finishes
1434 * initialization; otherwise, competing mounts with the same
1435 * options may try to bind the same subsystems instead of waiting
1436 * for the first one leading to unexpected mount errors.
1437 * SUBSYS_BOUND will be set once actual binding is complete.
1439 root->subsys_mask = opts->subsys_mask;
1440 root->flags = opts->flags;
1441 if (opts->release_agent)
1442 strcpy(root->release_agent_path, opts->release_agent);
1444 strcpy(root->name, opts->name);
1445 if (opts->cpuset_clone_children)
1446 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1450 static void cgroup_free_root(struct cgroupfs_root *root)
1453 /* hierarhcy ID shoulid already have been released */
1454 WARN_ON_ONCE(root->hierarchy_id);
1456 idr_destroy(&root->cgroup_idr);
1461 static int cgroup_set_super(struct super_block *sb, void *data)
1464 struct cgroup_sb_opts *opts = data;
1466 /* If we don't have a new root, we can't set up a new sb */
1467 if (!opts->new_root)
1470 BUG_ON(!opts->subsys_mask && !opts->none);
1472 ret = set_anon_super(sb, NULL);
1476 sb->s_fs_info = opts->new_root;
1477 opts->new_root->sb = sb;
1479 sb->s_blocksize = PAGE_CACHE_SIZE;
1480 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1481 sb->s_magic = CGROUP_SUPER_MAGIC;
1482 sb->s_op = &cgroup_ops;
1487 static int cgroup_get_rootdir(struct super_block *sb)
1489 static const struct dentry_operations cgroup_dops = {
1490 .d_iput = cgroup_diput,
1491 .d_delete = cgroup_delete,
1494 struct inode *inode =
1495 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1500 inode->i_fop = &simple_dir_operations;
1501 inode->i_op = &cgroup_dir_inode_operations;
1502 /* directories start off with i_nlink == 2 (for "." entry) */
1504 sb->s_root = d_make_root(inode);
1507 /* for everything else we want ->d_op set */
1508 sb->s_d_op = &cgroup_dops;
1512 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1513 int flags, const char *unused_dev_name,
1516 struct cgroup_sb_opts opts;
1517 struct cgroupfs_root *root;
1519 struct super_block *sb;
1520 struct cgroupfs_root *new_root;
1521 struct list_head tmp_links;
1522 struct inode *inode;
1523 const struct cred *cred;
1525 /* First find the desired set of subsystems */
1526 mutex_lock(&cgroup_mutex);
1527 ret = parse_cgroupfs_options(data, &opts);
1528 mutex_unlock(&cgroup_mutex);
1533 * Allocate a new cgroup root. We may not need it if we're
1534 * reusing an existing hierarchy.
1536 new_root = cgroup_root_from_opts(&opts);
1537 if (IS_ERR(new_root)) {
1538 ret = PTR_ERR(new_root);
1541 opts.new_root = new_root;
1543 /* Locate an existing or new sb for this hierarchy */
1544 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1547 cgroup_free_root(opts.new_root);
1551 root = sb->s_fs_info;
1553 if (root == opts.new_root) {
1554 /* We used the new root structure, so this is a new hierarchy */
1555 struct cgroup *root_cgrp = &root->top_cgroup;
1556 struct cgroupfs_root *existing_root;
1558 struct css_set *cset;
1560 BUG_ON(sb->s_root != NULL);
1562 ret = cgroup_get_rootdir(sb);
1564 goto drop_new_super;
1565 inode = sb->s_root->d_inode;
1567 mutex_lock(&inode->i_mutex);
1568 mutex_lock(&cgroup_mutex);
1569 mutex_lock(&cgroup_root_mutex);
1571 root_cgrp->id = idr_alloc(&root->cgroup_idr, root_cgrp,
1573 if (root_cgrp->id < 0)
1576 /* Check for name clashes with existing mounts */
1578 if (strlen(root->name))
1579 for_each_active_root(existing_root)
1580 if (!strcmp(existing_root->name, root->name))
1584 * We're accessing css_set_count without locking
1585 * css_set_lock here, but that's OK - it can only be
1586 * increased by someone holding cgroup_lock, and
1587 * that's us. The worst that can happen is that we
1588 * have some link structures left over
1590 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1594 /* ID 0 is reserved for dummy root, 1 for unified hierarchy */
1595 ret = cgroup_init_root_id(root, 2, 0);
1599 sb->s_root->d_fsdata = root_cgrp;
1600 root_cgrp->dentry = sb->s_root;
1603 * We're inside get_sb() and will call lookup_one_len() to
1604 * create the root files, which doesn't work if SELinux is
1605 * in use. The following cred dancing somehow works around
1606 * it. See 2ce9738ba ("cgroupfs: use init_cred when
1607 * populating new cgroupfs mount") for more details.
1609 cred = override_creds(&init_cred);
1611 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1615 ret = rebind_subsystems(root, root->subsys_mask, 0);
1622 * There must be no failure case after here, since rebinding
1623 * takes care of subsystems' refcounts, which are explicitly
1624 * dropped in the failure exit path.
1627 list_add(&root->root_list, &cgroup_roots);
1628 cgroup_root_count++;
1630 /* Link the top cgroup in this hierarchy into all
1631 * the css_set objects */
1632 write_lock(&css_set_lock);
1633 hash_for_each(css_set_table, i, cset, hlist)
1634 link_css_set(&tmp_links, cset, root_cgrp);
1635 write_unlock(&css_set_lock);
1637 free_cgrp_cset_links(&tmp_links);
1639 BUG_ON(!list_empty(&root_cgrp->children));
1640 BUG_ON(root->number_of_cgroups != 1);
1642 mutex_unlock(&cgroup_root_mutex);
1643 mutex_unlock(&cgroup_mutex);
1644 mutex_unlock(&inode->i_mutex);
1647 * We re-used an existing hierarchy - the new root (if
1648 * any) is not needed
1650 cgroup_free_root(opts.new_root);
1652 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1653 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1654 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1656 goto drop_new_super;
1658 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1663 kfree(opts.release_agent);
1665 return dget(sb->s_root);
1668 free_cgrp_cset_links(&tmp_links);
1669 cgroup_addrm_files(&root->top_cgroup, cgroup_base_files, false);
1672 cgroup_exit_root_id(root);
1673 mutex_unlock(&cgroup_root_mutex);
1674 mutex_unlock(&cgroup_mutex);
1675 mutex_unlock(&inode->i_mutex);
1677 deactivate_locked_super(sb);
1679 kfree(opts.release_agent);
1681 return ERR_PTR(ret);
1684 static void cgroup_kill_sb(struct super_block *sb) {
1685 struct cgroupfs_root *root = sb->s_fs_info;
1686 struct cgroup *cgrp = &root->top_cgroup;
1687 struct cgrp_cset_link *link, *tmp_link;
1692 BUG_ON(root->number_of_cgroups != 1);
1693 BUG_ON(!list_empty(&cgrp->children));
1695 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1696 mutex_lock(&cgroup_mutex);
1697 mutex_lock(&cgroup_root_mutex);
1699 /* Rebind all subsystems back to the default hierarchy */
1700 if (root->flags & CGRP_ROOT_SUBSYS_BOUND) {
1701 ret = rebind_subsystems(root, 0, root->subsys_mask);
1702 /* Shouldn't be able to fail ... */
1707 * Release all the links from cset_links to this hierarchy's
1710 write_lock(&css_set_lock);
1712 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1713 list_del(&link->cset_link);
1714 list_del(&link->cgrp_link);
1717 write_unlock(&css_set_lock);
1719 if (!list_empty(&root->root_list)) {
1720 list_del(&root->root_list);
1721 cgroup_root_count--;
1724 cgroup_exit_root_id(root);
1726 mutex_unlock(&cgroup_root_mutex);
1727 mutex_unlock(&cgroup_mutex);
1728 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1730 simple_xattrs_free(&cgrp->xattrs);
1732 kill_litter_super(sb);
1733 cgroup_free_root(root);
1736 static struct file_system_type cgroup_fs_type = {
1738 .mount = cgroup_mount,
1739 .kill_sb = cgroup_kill_sb,
1742 static struct kobject *cgroup_kobj;
1745 * cgroup_path - generate the path of a cgroup
1746 * @cgrp: the cgroup in question
1747 * @buf: the buffer to write the path into
1748 * @buflen: the length of the buffer
1750 * Writes path of cgroup into buf. Returns 0 on success, -errno on error.
1752 * We can't generate cgroup path using dentry->d_name, as accessing
1753 * dentry->name must be protected by irq-unsafe dentry->d_lock or parent
1754 * inode's i_mutex, while on the other hand cgroup_path() can be called
1755 * with some irq-safe spinlocks held.
1757 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1759 int ret = -ENAMETOOLONG;
1762 if (!cgrp->parent) {
1763 if (strlcpy(buf, "/", buflen) >= buflen)
1764 return -ENAMETOOLONG;
1768 start = buf + buflen - 1;
1773 const char *name = cgroup_name(cgrp);
1777 if ((start -= len) < buf)
1779 memcpy(start, name, len);
1785 cgrp = cgrp->parent;
1786 } while (cgrp->parent);
1788 memmove(buf, start, buf + buflen - start);
1793 EXPORT_SYMBOL_GPL(cgroup_path);
1796 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1797 * @task: target task
1798 * @buf: the buffer to write the path into
1799 * @buflen: the length of the buffer
1801 * Determine @task's cgroup on the first (the one with the lowest non-zero
1802 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1803 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1804 * cgroup controller callbacks.
1806 * Returns 0 on success, fails with -%ENAMETOOLONG if @buflen is too short.
1808 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1810 struct cgroupfs_root *root;
1811 struct cgroup *cgrp;
1812 int hierarchy_id = 1, ret = 0;
1815 return -ENAMETOOLONG;
1817 mutex_lock(&cgroup_mutex);
1819 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1822 cgrp = task_cgroup_from_root(task, root);
1823 ret = cgroup_path(cgrp, buf, buflen);
1825 /* if no hierarchy exists, everyone is in "/" */
1826 memcpy(buf, "/", 2);
1829 mutex_unlock(&cgroup_mutex);
1832 EXPORT_SYMBOL_GPL(task_cgroup_path);
1835 * Control Group taskset
1837 struct task_and_cgroup {
1838 struct task_struct *task;
1839 struct cgroup *cgrp;
1840 struct css_set *cset;
1843 struct cgroup_taskset {
1844 struct task_and_cgroup single;
1845 struct flex_array *tc_array;
1848 struct cgroup *cur_cgrp;
1852 * cgroup_taskset_first - reset taskset and return the first task
1853 * @tset: taskset of interest
1855 * @tset iteration is initialized and the first task is returned.
1857 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1859 if (tset->tc_array) {
1861 return cgroup_taskset_next(tset);
1863 tset->cur_cgrp = tset->single.cgrp;
1864 return tset->single.task;
1867 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1870 * cgroup_taskset_next - iterate to the next task in taskset
1871 * @tset: taskset of interest
1873 * Return the next task in @tset. Iteration must have been initialized
1874 * with cgroup_taskset_first().
1876 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1878 struct task_and_cgroup *tc;
1880 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1883 tc = flex_array_get(tset->tc_array, tset->idx++);
1884 tset->cur_cgrp = tc->cgrp;
1887 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1890 * cgroup_taskset_cur_css - return the matching css for the current task
1891 * @tset: taskset of interest
1892 * @subsys_id: the ID of the target subsystem
1894 * Return the css for the current (last returned) task of @tset for
1895 * subsystem specified by @subsys_id. This function must be preceded by
1896 * either cgroup_taskset_first() or cgroup_taskset_next().
1898 struct cgroup_subsys_state *cgroup_taskset_cur_css(struct cgroup_taskset *tset,
1901 return cgroup_css(tset->cur_cgrp, cgroup_subsys[subsys_id]);
1903 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_css);
1906 * cgroup_taskset_size - return the number of tasks in taskset
1907 * @tset: taskset of interest
1909 int cgroup_taskset_size(struct cgroup_taskset *tset)
1911 return tset->tc_array ? tset->tc_array_len : 1;
1913 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1917 * cgroup_task_migrate - move a task from one cgroup to another.
1919 * Must be called with cgroup_mutex and threadgroup locked.
1921 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1922 struct task_struct *tsk,
1923 struct css_set *new_cset)
1925 struct css_set *old_cset;
1928 * We are synchronized through threadgroup_lock() against PF_EXITING
1929 * setting such that we can't race against cgroup_exit() changing the
1930 * css_set to init_css_set and dropping the old one.
1932 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1933 old_cset = task_css_set(tsk);
1936 rcu_assign_pointer(tsk->cgroups, new_cset);
1939 /* Update the css_set linked lists if we're using them */
1940 write_lock(&css_set_lock);
1941 if (!list_empty(&tsk->cg_list))
1942 list_move(&tsk->cg_list, &new_cset->tasks);
1943 write_unlock(&css_set_lock);
1946 * We just gained a reference on old_cset by taking it from the
1947 * task. As trading it for new_cset is protected by cgroup_mutex,
1948 * we're safe to drop it here; it will be freed under RCU.
1950 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1951 put_css_set(old_cset);
1955 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1956 * @cgrp: the cgroup to attach to
1957 * @tsk: the task or the leader of the threadgroup to be attached
1958 * @threadgroup: attach the whole threadgroup?
1960 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
1961 * task_lock of @tsk or each thread in the threadgroup individually in turn.
1963 static int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk,
1966 int retval, i, group_size;
1967 struct cgroup_subsys *ss, *failed_ss = NULL;
1968 struct cgroupfs_root *root = cgrp->root;
1969 /* threadgroup list cursor and array */
1970 struct task_struct *leader = tsk;
1971 struct task_and_cgroup *tc;
1972 struct flex_array *group;
1973 struct cgroup_taskset tset = { };
1976 * step 0: in order to do expensive, possibly blocking operations for
1977 * every thread, we cannot iterate the thread group list, since it needs
1978 * rcu or tasklist locked. instead, build an array of all threads in the
1979 * group - group_rwsem prevents new threads from appearing, and if
1980 * threads exit, this will just be an over-estimate.
1983 group_size = get_nr_threads(tsk);
1986 /* flex_array supports very large thread-groups better than kmalloc. */
1987 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
1990 /* pre-allocate to guarantee space while iterating in rcu read-side. */
1991 retval = flex_array_prealloc(group, 0, group_size, GFP_KERNEL);
1993 goto out_free_group_list;
1997 * Prevent freeing of tasks while we take a snapshot. Tasks that are
1998 * already PF_EXITING could be freed from underneath us unless we
1999 * take an rcu_read_lock.
2003 struct task_and_cgroup ent;
2005 /* @tsk either already exited or can't exit until the end */
2006 if (tsk->flags & PF_EXITING)
2009 /* as per above, nr_threads may decrease, but not increase. */
2010 BUG_ON(i >= group_size);
2012 ent.cgrp = task_cgroup_from_root(tsk, root);
2013 /* nothing to do if this task is already in the cgroup */
2014 if (ent.cgrp == cgrp)
2017 * saying GFP_ATOMIC has no effect here because we did prealloc
2018 * earlier, but it's good form to communicate our expectations.
2020 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
2021 BUG_ON(retval != 0);
2026 } while_each_thread(leader, tsk);
2028 /* remember the number of threads in the array for later. */
2030 tset.tc_array = group;
2031 tset.tc_array_len = group_size;
2033 /* methods shouldn't be called if no task is actually migrating */
2036 goto out_free_group_list;
2039 * step 1: check that we can legitimately attach to the cgroup.
2041 for_each_root_subsys(root, ss) {
2042 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss);
2044 if (ss->can_attach) {
2045 retval = ss->can_attach(css, &tset);
2048 goto out_cancel_attach;
2054 * step 2: make sure css_sets exist for all threads to be migrated.
2055 * we use find_css_set, which allocates a new one if necessary.
2057 for (i = 0; i < group_size; i++) {
2058 struct css_set *old_cset;
2060 tc = flex_array_get(group, i);
2061 old_cset = task_css_set(tc->task);
2062 tc->cset = find_css_set(old_cset, cgrp);
2065 goto out_put_css_set_refs;
2070 * step 3: now that we're guaranteed success wrt the css_sets,
2071 * proceed to move all tasks to the new cgroup. There are no
2072 * failure cases after here, so this is the commit point.
2074 for (i = 0; i < group_size; i++) {
2075 tc = flex_array_get(group, i);
2076 cgroup_task_migrate(tc->cgrp, tc->task, tc->cset);
2078 /* nothing is sensitive to fork() after this point. */
2081 * step 4: do subsystem attach callbacks.
2083 for_each_root_subsys(root, ss) {
2084 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss);
2087 ss->attach(css, &tset);
2091 * step 5: success! and cleanup
2094 out_put_css_set_refs:
2096 for (i = 0; i < group_size; i++) {
2097 tc = flex_array_get(group, i);
2100 put_css_set(tc->cset);
2105 for_each_root_subsys(root, ss) {
2106 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss);
2108 if (ss == failed_ss)
2110 if (ss->cancel_attach)
2111 ss->cancel_attach(css, &tset);
2114 out_free_group_list:
2115 flex_array_free(group);
2120 * Find the task_struct of the task to attach by vpid and pass it along to the
2121 * function to attach either it or all tasks in its threadgroup. Will lock
2122 * cgroup_mutex and threadgroup; may take task_lock of task.
2124 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2126 struct task_struct *tsk;
2127 const struct cred *cred = current_cred(), *tcred;
2130 if (!cgroup_lock_live_group(cgrp))
2136 tsk = find_task_by_vpid(pid);
2140 goto out_unlock_cgroup;
2143 * even if we're attaching all tasks in the thread group, we
2144 * only need to check permissions on one of them.
2146 tcred = __task_cred(tsk);
2147 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2148 !uid_eq(cred->euid, tcred->uid) &&
2149 !uid_eq(cred->euid, tcred->suid)) {
2152 goto out_unlock_cgroup;
2158 tsk = tsk->group_leader;
2161 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2162 * trapped in a cpuset, or RT worker may be born in a cgroup
2163 * with no rt_runtime allocated. Just say no.
2165 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2168 goto out_unlock_cgroup;
2171 get_task_struct(tsk);
2174 threadgroup_lock(tsk);
2176 if (!thread_group_leader(tsk)) {
2178 * a race with de_thread from another thread's exec()
2179 * may strip us of our leadership, if this happens,
2180 * there is no choice but to throw this task away and
2181 * try again; this is
2182 * "double-double-toil-and-trouble-check locking".
2184 threadgroup_unlock(tsk);
2185 put_task_struct(tsk);
2186 goto retry_find_task;
2190 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2192 threadgroup_unlock(tsk);
2194 put_task_struct(tsk);
2196 mutex_unlock(&cgroup_mutex);
2201 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2202 * @from: attach to all cgroups of a given task
2203 * @tsk: the task to be attached
2205 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2207 struct cgroupfs_root *root;
2210 mutex_lock(&cgroup_mutex);
2211 for_each_active_root(root) {
2212 struct cgroup *from_cgrp = task_cgroup_from_root(from, root);
2214 retval = cgroup_attach_task(from_cgrp, tsk, false);
2218 mutex_unlock(&cgroup_mutex);
2222 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2224 static int cgroup_tasks_write(struct cgroup_subsys_state *css,
2225 struct cftype *cft, u64 pid)
2227 return attach_task_by_pid(css->cgroup, pid, false);
2230 static int cgroup_procs_write(struct cgroup_subsys_state *css,
2231 struct cftype *cft, u64 tgid)
2233 return attach_task_by_pid(css->cgroup, tgid, true);
2236 static int cgroup_release_agent_write(struct cgroup_subsys_state *css,
2237 struct cftype *cft, const char *buffer)
2239 BUILD_BUG_ON(sizeof(css->cgroup->root->release_agent_path) < PATH_MAX);
2240 if (strlen(buffer) >= PATH_MAX)
2242 if (!cgroup_lock_live_group(css->cgroup))
2244 mutex_lock(&cgroup_root_mutex);
2245 strcpy(css->cgroup->root->release_agent_path, buffer);
2246 mutex_unlock(&cgroup_root_mutex);
2247 mutex_unlock(&cgroup_mutex);
2251 static int cgroup_release_agent_show(struct cgroup_subsys_state *css,
2252 struct cftype *cft, struct seq_file *seq)
2254 struct cgroup *cgrp = css->cgroup;
2256 if (!cgroup_lock_live_group(cgrp))
2258 seq_puts(seq, cgrp->root->release_agent_path);
2259 seq_putc(seq, '\n');
2260 mutex_unlock(&cgroup_mutex);
2264 static int cgroup_sane_behavior_show(struct cgroup_subsys_state *css,
2265 struct cftype *cft, struct seq_file *seq)
2267 seq_printf(seq, "%d\n", cgroup_sane_behavior(css->cgroup));
2271 /* A buffer size big enough for numbers or short strings */
2272 #define CGROUP_LOCAL_BUFFER_SIZE 64
2274 static ssize_t cgroup_write_X64(struct cgroup_subsys_state *css,
2275 struct cftype *cft, struct file *file,
2276 const char __user *userbuf, size_t nbytes,
2277 loff_t *unused_ppos)
2279 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
2285 if (nbytes >= sizeof(buffer))
2287 if (copy_from_user(buffer, userbuf, nbytes))
2290 buffer[nbytes] = 0; /* nul-terminate */
2291 if (cft->write_u64) {
2292 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
2295 retval = cft->write_u64(css, cft, val);
2297 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
2300 retval = cft->write_s64(css, cft, val);
2307 static ssize_t cgroup_write_string(struct cgroup_subsys_state *css,
2308 struct cftype *cft, struct file *file,
2309 const char __user *userbuf, size_t nbytes,
2310 loff_t *unused_ppos)
2312 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
2314 size_t max_bytes = cft->max_write_len;
2315 char *buffer = local_buffer;
2318 max_bytes = sizeof(local_buffer) - 1;
2319 if (nbytes >= max_bytes)
2321 /* Allocate a dynamic buffer if we need one */
2322 if (nbytes >= sizeof(local_buffer)) {
2323 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2327 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2332 buffer[nbytes] = 0; /* nul-terminate */
2333 retval = cft->write_string(css, cft, strstrip(buffer));
2337 if (buffer != local_buffer)
2342 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2343 size_t nbytes, loff_t *ppos)
2345 struct cfent *cfe = __d_cfe(file->f_dentry);
2346 struct cftype *cft = __d_cft(file->f_dentry);
2347 struct cgroup_subsys_state *css = cfe->css;
2350 return cft->write(css, cft, file, buf, nbytes, ppos);
2351 if (cft->write_u64 || cft->write_s64)
2352 return cgroup_write_X64(css, cft, file, buf, nbytes, ppos);
2353 if (cft->write_string)
2354 return cgroup_write_string(css, cft, file, buf, nbytes, ppos);
2356 int ret = cft->trigger(css, (unsigned int)cft->private);
2357 return ret ? ret : nbytes;
2362 static ssize_t cgroup_read_u64(struct cgroup_subsys_state *css,
2363 struct cftype *cft, struct file *file,
2364 char __user *buf, size_t nbytes, loff_t *ppos)
2366 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2367 u64 val = cft->read_u64(css, cft);
2368 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2370 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2373 static ssize_t cgroup_read_s64(struct cgroup_subsys_state *css,
2374 struct cftype *cft, struct file *file,
2375 char __user *buf, size_t nbytes, loff_t *ppos)
2377 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2378 s64 val = cft->read_s64(css, cft);
2379 int len = sprintf(tmp, "%lld\n", (long long) val);
2381 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2384 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2385 size_t nbytes, loff_t *ppos)
2387 struct cfent *cfe = __d_cfe(file->f_dentry);
2388 struct cftype *cft = __d_cft(file->f_dentry);
2389 struct cgroup_subsys_state *css = cfe->css;
2392 return cft->read(css, cft, file, buf, nbytes, ppos);
2394 return cgroup_read_u64(css, cft, file, buf, nbytes, ppos);
2396 return cgroup_read_s64(css, cft, file, buf, nbytes, ppos);
2401 * seqfile ops/methods for returning structured data. Currently just
2402 * supports string->u64 maps, but can be extended in future.
2405 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2407 struct seq_file *sf = cb->state;
2408 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2411 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2413 struct cfent *cfe = m->private;
2414 struct cftype *cft = cfe->type;
2415 struct cgroup_subsys_state *css = cfe->css;
2417 if (cft->read_map) {
2418 struct cgroup_map_cb cb = {
2419 .fill = cgroup_map_add,
2422 return cft->read_map(css, cft, &cb);
2424 return cft->read_seq_string(css, cft, m);
2427 static const struct file_operations cgroup_seqfile_operations = {
2429 .write = cgroup_file_write,
2430 .llseek = seq_lseek,
2431 .release = single_release,
2434 static int cgroup_file_open(struct inode *inode, struct file *file)
2436 struct cfent *cfe = __d_cfe(file->f_dentry);
2437 struct cftype *cft = __d_cft(file->f_dentry);
2438 struct cgroup *cgrp = __d_cgrp(cfe->dentry->d_parent);
2439 struct cgroup_subsys_state *css;
2442 err = generic_file_open(inode, file);
2447 * If the file belongs to a subsystem, pin the css. Will be
2448 * unpinned either on open failure or release. This ensures that
2449 * @css stays alive for all file operations.
2452 css = cgroup_css(cgrp, cft->ss);
2453 if (cft->ss && !css_tryget(css))
2461 * @cfe->css is used by read/write/close to determine the
2462 * associated css. @file->private_data would be a better place but
2463 * that's already used by seqfile. Multiple accessors may use it
2464 * simultaneously which is okay as the association never changes.
2466 WARN_ON_ONCE(cfe->css && cfe->css != css);
2469 if (cft->read_map || cft->read_seq_string) {
2470 file->f_op = &cgroup_seqfile_operations;
2471 err = single_open(file, cgroup_seqfile_show, cfe);
2472 } else if (cft->open) {
2473 err = cft->open(inode, file);
2481 static int cgroup_file_release(struct inode *inode, struct file *file)
2483 struct cfent *cfe = __d_cfe(file->f_dentry);
2484 struct cftype *cft = __d_cft(file->f_dentry);
2485 struct cgroup_subsys_state *css = cfe->css;
2489 ret = cft->release(inode, file);
2496 * cgroup_rename - Only allow simple rename of directories in place.
2498 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2499 struct inode *new_dir, struct dentry *new_dentry)
2502 struct cgroup_name *name, *old_name;
2503 struct cgroup *cgrp;
2506 * It's convinient to use parent dir's i_mutex to protected
2509 lockdep_assert_held(&old_dir->i_mutex);
2511 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2513 if (new_dentry->d_inode)
2515 if (old_dir != new_dir)
2518 cgrp = __d_cgrp(old_dentry);
2521 * This isn't a proper migration and its usefulness is very
2522 * limited. Disallow if sane_behavior.
2524 if (cgroup_sane_behavior(cgrp))
2527 name = cgroup_alloc_name(new_dentry);
2531 ret = simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2537 old_name = rcu_dereference_protected(cgrp->name, true);
2538 rcu_assign_pointer(cgrp->name, name);
2540 kfree_rcu(old_name, rcu_head);
2544 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2546 if (S_ISDIR(dentry->d_inode->i_mode))
2547 return &__d_cgrp(dentry)->xattrs;
2549 return &__d_cfe(dentry)->xattrs;
2552 static inline int xattr_enabled(struct dentry *dentry)
2554 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2555 return root->flags & CGRP_ROOT_XATTR;
2558 static bool is_valid_xattr(const char *name)
2560 if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2561 !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2566 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2567 const void *val, size_t size, int flags)
2569 if (!xattr_enabled(dentry))
2571 if (!is_valid_xattr(name))
2573 return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2576 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2578 if (!xattr_enabled(dentry))
2580 if (!is_valid_xattr(name))
2582 return simple_xattr_remove(__d_xattrs(dentry), name);
2585 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2586 void *buf, size_t size)
2588 if (!xattr_enabled(dentry))
2590 if (!is_valid_xattr(name))
2592 return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2595 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2597 if (!xattr_enabled(dentry))
2599 return simple_xattr_list(__d_xattrs(dentry), buf, size);
2602 static const struct file_operations cgroup_file_operations = {
2603 .read = cgroup_file_read,
2604 .write = cgroup_file_write,
2605 .llseek = generic_file_llseek,
2606 .open = cgroup_file_open,
2607 .release = cgroup_file_release,
2610 static const struct inode_operations cgroup_file_inode_operations = {
2611 .setxattr = cgroup_setxattr,
2612 .getxattr = cgroup_getxattr,
2613 .listxattr = cgroup_listxattr,
2614 .removexattr = cgroup_removexattr,
2617 static const struct inode_operations cgroup_dir_inode_operations = {
2618 .lookup = simple_lookup,
2619 .mkdir = cgroup_mkdir,
2620 .rmdir = cgroup_rmdir,
2621 .rename = cgroup_rename,
2622 .setxattr = cgroup_setxattr,
2623 .getxattr = cgroup_getxattr,
2624 .listxattr = cgroup_listxattr,
2625 .removexattr = cgroup_removexattr,
2629 * Check if a file is a control file
2631 struct cftype *__file_cft(struct file *file)
2633 if (file_inode(file)->i_fop != &cgroup_file_operations)
2634 return ERR_PTR(-EINVAL);
2635 return __d_cft(file->f_dentry);
2638 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2639 struct super_block *sb)
2641 struct inode *inode;
2645 if (dentry->d_inode)
2648 inode = cgroup_new_inode(mode, sb);
2652 if (S_ISDIR(mode)) {
2653 inode->i_op = &cgroup_dir_inode_operations;
2654 inode->i_fop = &simple_dir_operations;
2656 /* start off with i_nlink == 2 (for "." entry) */
2658 inc_nlink(dentry->d_parent->d_inode);
2661 * Control reaches here with cgroup_mutex held.
2662 * @inode->i_mutex should nest outside cgroup_mutex but we
2663 * want to populate it immediately without releasing
2664 * cgroup_mutex. As @inode isn't visible to anyone else
2665 * yet, trylock will always succeed without affecting
2668 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2669 } else if (S_ISREG(mode)) {
2671 inode->i_fop = &cgroup_file_operations;
2672 inode->i_op = &cgroup_file_inode_operations;
2674 d_instantiate(dentry, inode);
2675 dget(dentry); /* Extra count - pin the dentry in core */
2680 * cgroup_file_mode - deduce file mode of a control file
2681 * @cft: the control file in question
2683 * returns cft->mode if ->mode is not 0
2684 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2685 * returns S_IRUGO if it has only a read handler
2686 * returns S_IWUSR if it has only a write hander
2688 static umode_t cgroup_file_mode(const struct cftype *cft)
2695 if (cft->read || cft->read_u64 || cft->read_s64 ||
2696 cft->read_map || cft->read_seq_string)
2699 if (cft->write || cft->write_u64 || cft->write_s64 ||
2700 cft->write_string || cft->trigger)
2706 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2708 struct dentry *dir = cgrp->dentry;
2709 struct cgroup *parent = __d_cgrp(dir);
2710 struct dentry *dentry;
2714 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2716 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
2717 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
2718 strcpy(name, cft->ss->name);
2721 strcat(name, cft->name);
2723 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2725 cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2729 dentry = lookup_one_len(name, dir, strlen(name));
2730 if (IS_ERR(dentry)) {
2731 error = PTR_ERR(dentry);
2735 cfe->type = (void *)cft;
2736 cfe->dentry = dentry;
2737 dentry->d_fsdata = cfe;
2738 simple_xattrs_init(&cfe->xattrs);
2740 mode = cgroup_file_mode(cft);
2741 error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2743 list_add_tail(&cfe->node, &parent->files);
2753 * cgroup_addrm_files - add or remove files to a cgroup directory
2754 * @cgrp: the target cgroup
2755 * @cfts: array of cftypes to be added
2756 * @is_add: whether to add or remove
2758 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2759 * For removals, this function never fails. If addition fails, this
2760 * function doesn't remove files already added. The caller is responsible
2763 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2769 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
2770 lockdep_assert_held(&cgroup_mutex);
2772 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2773 /* does cft->flags tell us to skip this file on @cgrp? */
2774 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2776 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2778 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2782 ret = cgroup_add_file(cgrp, cft);
2784 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2789 cgroup_rm_file(cgrp, cft);
2795 static void cgroup_cfts_prepare(void)
2796 __acquires(&cgroup_mutex)
2799 * Thanks to the entanglement with vfs inode locking, we can't walk
2800 * the existing cgroups under cgroup_mutex and create files.
2801 * Instead, we use css_for_each_descendant_pre() and drop RCU read
2802 * lock before calling cgroup_addrm_files().
2804 mutex_lock(&cgroup_mutex);
2807 static int cgroup_cfts_commit(struct cftype *cfts, bool is_add)
2808 __releases(&cgroup_mutex)
2811 struct cgroup_subsys *ss = cfts[0].ss;
2812 struct cgroup *root = &ss->root->top_cgroup;
2813 struct super_block *sb = ss->root->sb;
2814 struct dentry *prev = NULL;
2815 struct inode *inode;
2816 struct cgroup_subsys_state *css;
2820 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2821 if (!cfts || ss->root == &cgroup_dummy_root ||
2822 !atomic_inc_not_zero(&sb->s_active)) {
2823 mutex_unlock(&cgroup_mutex);
2828 * All cgroups which are created after we drop cgroup_mutex will
2829 * have the updated set of files, so we only need to update the
2830 * cgroups created before the current @cgroup_serial_nr_next.
2832 update_before = cgroup_serial_nr_next;
2834 mutex_unlock(&cgroup_mutex);
2836 /* add/rm files for all cgroups created before */
2838 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2839 struct cgroup *cgrp = css->cgroup;
2841 if (cgroup_is_dead(cgrp))
2844 inode = cgrp->dentry->d_inode;
2849 prev = cgrp->dentry;
2851 mutex_lock(&inode->i_mutex);
2852 mutex_lock(&cgroup_mutex);
2853 if (cgrp->serial_nr < update_before && !cgroup_is_dead(cgrp))
2854 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2855 mutex_unlock(&cgroup_mutex);
2856 mutex_unlock(&inode->i_mutex);
2864 deactivate_super(sb);
2869 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2870 * @ss: target cgroup subsystem
2871 * @cfts: zero-length name terminated array of cftypes
2873 * Register @cfts to @ss. Files described by @cfts are created for all
2874 * existing cgroups to which @ss is attached and all future cgroups will
2875 * have them too. This function can be called anytime whether @ss is
2878 * Returns 0 on successful registration, -errno on failure. Note that this
2879 * function currently returns 0 as long as @cfts registration is successful
2880 * even if some file creation attempts on existing cgroups fail.
2882 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2884 struct cftype_set *set;
2888 set = kzalloc(sizeof(*set), GFP_KERNEL);
2892 for (cft = cfts; cft->name[0] != '\0'; cft++)
2895 cgroup_cfts_prepare();
2897 list_add_tail(&set->node, &ss->cftsets);
2898 ret = cgroup_cfts_commit(cfts, true);
2900 cgroup_rm_cftypes(cfts);
2903 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2906 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2907 * @cfts: zero-length name terminated array of cftypes
2909 * Unregister @cfts. Files described by @cfts are removed from all
2910 * existing cgroups and all future cgroups won't have them either. This
2911 * function can be called anytime whether @cfts' subsys is attached or not.
2913 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2916 int cgroup_rm_cftypes(struct cftype *cfts)
2918 struct cftype_set *set;
2920 if (!cfts || !cfts[0].ss)
2923 cgroup_cfts_prepare();
2925 list_for_each_entry(set, &cfts[0].ss->cftsets, node) {
2926 if (set->cfts == cfts) {
2927 list_del(&set->node);
2929 cgroup_cfts_commit(cfts, false);
2934 cgroup_cfts_commit(NULL, false);
2939 * cgroup_task_count - count the number of tasks in a cgroup.
2940 * @cgrp: the cgroup in question
2942 * Return the number of tasks in the cgroup.
2944 int cgroup_task_count(const struct cgroup *cgrp)
2947 struct cgrp_cset_link *link;
2949 read_lock(&css_set_lock);
2950 list_for_each_entry(link, &cgrp->cset_links, cset_link)
2951 count += atomic_read(&link->cset->refcount);
2952 read_unlock(&css_set_lock);
2957 * To reduce the fork() overhead for systems that are not actually using
2958 * their cgroups capability, we don't maintain the lists running through
2959 * each css_set to its tasks until we see the list actually used - in other
2960 * words after the first call to css_task_iter_start().
2962 static void cgroup_enable_task_cg_lists(void)
2964 struct task_struct *p, *g;
2965 write_lock(&css_set_lock);
2966 use_task_css_set_links = 1;
2968 * We need tasklist_lock because RCU is not safe against
2969 * while_each_thread(). Besides, a forking task that has passed
2970 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2971 * is not guaranteed to have its child immediately visible in the
2972 * tasklist if we walk through it with RCU.
2974 read_lock(&tasklist_lock);
2975 do_each_thread(g, p) {
2978 * We should check if the process is exiting, otherwise
2979 * it will race with cgroup_exit() in that the list
2980 * entry won't be deleted though the process has exited.
2982 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2983 list_add(&p->cg_list, &task_css_set(p)->tasks);
2985 } while_each_thread(g, p);
2986 read_unlock(&tasklist_lock);
2987 write_unlock(&css_set_lock);
2991 * css_next_child - find the next child of a given css
2992 * @pos_css: the current position (%NULL to initiate traversal)
2993 * @parent_css: css whose children to walk
2995 * This function returns the next child of @parent_css and should be called
2996 * under RCU read lock. The only requirement is that @parent_css and
2997 * @pos_css are accessible. The next sibling is guaranteed to be returned
2998 * regardless of their states.
3000 struct cgroup_subsys_state *
3001 css_next_child(struct cgroup_subsys_state *pos_css,
3002 struct cgroup_subsys_state *parent_css)
3004 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
3005 struct cgroup *cgrp = parent_css->cgroup;
3006 struct cgroup *next;
3008 WARN_ON_ONCE(!rcu_read_lock_held());
3011 * @pos could already have been removed. Once a cgroup is removed,
3012 * its ->sibling.next is no longer updated when its next sibling
3013 * changes. As CGRP_DEAD assertion is serialized and happens
3014 * before the cgroup is taken off the ->sibling list, if we see it
3015 * unasserted, it's guaranteed that the next sibling hasn't
3016 * finished its grace period even if it's already removed, and thus
3017 * safe to dereference from this RCU critical section. If
3018 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
3019 * to be visible as %true here.
3021 * If @pos is dead, its next pointer can't be dereferenced;
3022 * however, as each cgroup is given a monotonically increasing
3023 * unique serial number and always appended to the sibling list,
3024 * the next one can be found by walking the parent's children until
3025 * we see a cgroup with higher serial number than @pos's. While
3026 * this path can be slower, it's taken only when either the current
3027 * cgroup is removed or iteration and removal race.
3030 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
3031 } else if (likely(!cgroup_is_dead(pos))) {
3032 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3034 list_for_each_entry_rcu(next, &cgrp->children, sibling)
3035 if (next->serial_nr > pos->serial_nr)
3039 if (&next->sibling == &cgrp->children)
3042 return cgroup_css(next, parent_css->ss);
3044 EXPORT_SYMBOL_GPL(css_next_child);
3047 * css_next_descendant_pre - find the next descendant for pre-order walk
3048 * @pos: the current position (%NULL to initiate traversal)
3049 * @root: css whose descendants to walk
3051 * To be used by css_for_each_descendant_pre(). Find the next descendant
3052 * to visit for pre-order traversal of @root's descendants. @root is
3053 * included in the iteration and the first node to be visited.
3055 * While this function requires RCU read locking, it doesn't require the
3056 * whole traversal to be contained in a single RCU critical section. This
3057 * function will return the correct next descendant as long as both @pos
3058 * and @root are accessible and @pos is a descendant of @root.
3060 struct cgroup_subsys_state *
3061 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3062 struct cgroup_subsys_state *root)
3064 struct cgroup_subsys_state *next;
3066 WARN_ON_ONCE(!rcu_read_lock_held());
3068 /* if first iteration, visit @root */
3072 /* visit the first child if exists */
3073 next = css_next_child(NULL, pos);
3077 /* no child, visit my or the closest ancestor's next sibling */
3078 while (pos != root) {
3079 next = css_next_child(pos, css_parent(pos));
3082 pos = css_parent(pos);
3087 EXPORT_SYMBOL_GPL(css_next_descendant_pre);
3090 * css_rightmost_descendant - return the rightmost descendant of a css
3091 * @pos: css of interest
3093 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3094 * is returned. This can be used during pre-order traversal to skip
3097 * While this function requires RCU read locking, it doesn't require the
3098 * whole traversal to be contained in a single RCU critical section. This
3099 * function will return the correct rightmost descendant as long as @pos is
3102 struct cgroup_subsys_state *
3103 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3105 struct cgroup_subsys_state *last, *tmp;
3107 WARN_ON_ONCE(!rcu_read_lock_held());
3111 /* ->prev isn't RCU safe, walk ->next till the end */
3113 css_for_each_child(tmp, last)
3119 EXPORT_SYMBOL_GPL(css_rightmost_descendant);
3121 static struct cgroup_subsys_state *
3122 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3124 struct cgroup_subsys_state *last;
3128 pos = css_next_child(NULL, pos);
3135 * css_next_descendant_post - find the next descendant for post-order walk
3136 * @pos: the current position (%NULL to initiate traversal)
3137 * @root: css whose descendants to walk
3139 * To be used by css_for_each_descendant_post(). Find the next descendant
3140 * to visit for post-order traversal of @root's descendants. @root is
3141 * included in the iteration and the last node to be visited.
3143 * While this function requires RCU read locking, it doesn't require the
3144 * whole traversal to be contained in a single RCU critical section. This
3145 * function will return the correct next descendant as long as both @pos
3146 * and @cgroup are accessible and @pos is a descendant of @cgroup.
3148 struct cgroup_subsys_state *
3149 css_next_descendant_post(struct cgroup_subsys_state *pos,
3150 struct cgroup_subsys_state *root)
3152 struct cgroup_subsys_state *next;
3154 WARN_ON_ONCE(!rcu_read_lock_held());
3156 /* if first iteration, visit leftmost descendant which may be @root */
3158 return css_leftmost_descendant(root);
3160 /* if we visited @root, we're done */
3164 /* if there's an unvisited sibling, visit its leftmost descendant */
3165 next = css_next_child(pos, css_parent(pos));
3167 return css_leftmost_descendant(next);
3169 /* no sibling left, visit parent */
3170 return css_parent(pos);
3172 EXPORT_SYMBOL_GPL(css_next_descendant_post);
3175 * css_advance_task_iter - advance a task itererator to the next css_set
3176 * @it: the iterator to advance
3178 * Advance @it to the next css_set to walk.
3180 static void css_advance_task_iter(struct css_task_iter *it)
3182 struct list_head *l = it->cset_link;
3183 struct cgrp_cset_link *link;
3184 struct css_set *cset;
3186 /* Advance to the next non-empty css_set */
3189 if (l == &it->origin_css->cgroup->cset_links) {
3190 it->cset_link = NULL;
3193 link = list_entry(l, struct cgrp_cset_link, cset_link);
3195 } while (list_empty(&cset->tasks));
3197 it->task = cset->tasks.next;
3201 * css_task_iter_start - initiate task iteration
3202 * @css: the css to walk tasks of
3203 * @it: the task iterator to use
3205 * Initiate iteration through the tasks of @css. The caller can call
3206 * css_task_iter_next() to walk through the tasks until the function
3207 * returns NULL. On completion of iteration, css_task_iter_end() must be
3210 * Note that this function acquires a lock which is released when the
3211 * iteration finishes. The caller can't sleep while iteration is in
3214 void css_task_iter_start(struct cgroup_subsys_state *css,
3215 struct css_task_iter *it)
3216 __acquires(css_set_lock)
3219 * The first time anyone tries to iterate across a css, we need to
3220 * enable the list linking each css_set to its tasks, and fix up
3221 * all existing tasks.
3223 if (!use_task_css_set_links)
3224 cgroup_enable_task_cg_lists();
3226 read_lock(&css_set_lock);
3228 it->origin_css = css;
3229 it->cset_link = &css->cgroup->cset_links;
3231 css_advance_task_iter(it);
3235 * css_task_iter_next - return the next task for the iterator
3236 * @it: the task iterator being iterated
3238 * The "next" function for task iteration. @it should have been
3239 * initialized via css_task_iter_start(). Returns NULL when the iteration
3242 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3244 struct task_struct *res;
3245 struct list_head *l = it->task;
3246 struct cgrp_cset_link *link;
3248 /* If the iterator cg is NULL, we have no tasks */
3251 res = list_entry(l, struct task_struct, cg_list);
3252 /* Advance iterator to find next entry */
3254 link = list_entry(it->cset_link, struct cgrp_cset_link, cset_link);
3255 if (l == &link->cset->tasks) {
3257 * We reached the end of this task list - move on to the
3258 * next cgrp_cset_link.
3260 css_advance_task_iter(it);
3268 * css_task_iter_end - finish task iteration
3269 * @it: the task iterator to finish
3271 * Finish task iteration started by css_task_iter_start().
3273 void css_task_iter_end(struct css_task_iter *it)
3274 __releases(css_set_lock)
3276 read_unlock(&css_set_lock);
3279 static inline int started_after_time(struct task_struct *t1,
3280 struct timespec *time,
3281 struct task_struct *t2)
3283 int start_diff = timespec_compare(&t1->start_time, time);
3284 if (start_diff > 0) {
3286 } else if (start_diff < 0) {
3290 * Arbitrarily, if two processes started at the same
3291 * time, we'll say that the lower pointer value
3292 * started first. Note that t2 may have exited by now
3293 * so this may not be a valid pointer any longer, but
3294 * that's fine - it still serves to distinguish
3295 * between two tasks started (effectively) simultaneously.
3302 * This function is a callback from heap_insert() and is used to order
3304 * In this case we order the heap in descending task start time.
3306 static inline int started_after(void *p1, void *p2)
3308 struct task_struct *t1 = p1;
3309 struct task_struct *t2 = p2;
3310 return started_after_time(t1, &t2->start_time, t2);
3314 * css_scan_tasks - iterate though all the tasks in a css
3315 * @css: the css to iterate tasks of
3316 * @test: optional test callback
3317 * @process: process callback
3318 * @data: data passed to @test and @process
3319 * @heap: optional pre-allocated heap used for task iteration
3321 * Iterate through all the tasks in @css, calling @test for each, and if it
3322 * returns %true, call @process for it also.
3324 * @test may be NULL, meaning always true (select all tasks), which
3325 * effectively duplicates css_task_iter_{start,next,end}() but does not
3326 * lock css_set_lock for the call to @process.
3328 * It is guaranteed that @process will act on every task that is a member
3329 * of @css for the duration of this call. This function may or may not
3330 * call @process for tasks that exit or move to a different css during the
3331 * call, or are forked or move into the css during the call.
3333 * Note that @test may be called with locks held, and may in some
3334 * situations be called multiple times for the same task, so it should be
3337 * If @heap is non-NULL, a heap has been pre-allocated and will be used for
3338 * heap operations (and its "gt" member will be overwritten), else a
3339 * temporary heap will be used (allocation of which may cause this function
3342 int css_scan_tasks(struct cgroup_subsys_state *css,
3343 bool (*test)(struct task_struct *, void *),
3344 void (*process)(struct task_struct *, void *),
3345 void *data, struct ptr_heap *heap)
3348 struct css_task_iter it;
3349 struct task_struct *p, *dropped;
3350 /* Never dereference latest_task, since it's not refcounted */
3351 struct task_struct *latest_task = NULL;
3352 struct ptr_heap tmp_heap;
3353 struct timespec latest_time = { 0, 0 };
3356 /* The caller supplied our heap and pre-allocated its memory */
3357 heap->gt = &started_after;
3359 /* We need to allocate our own heap memory */
3361 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3363 /* cannot allocate the heap */
3369 * Scan tasks in the css, using the @test callback to determine
3370 * which are of interest, and invoking @process callback on the
3371 * ones which need an update. Since we don't want to hold any
3372 * locks during the task updates, gather tasks to be processed in a
3373 * heap structure. The heap is sorted by descending task start
3374 * time. If the statically-sized heap fills up, we overflow tasks
3375 * that started later, and in future iterations only consider tasks
3376 * that started after the latest task in the previous pass. This
3377 * guarantees forward progress and that we don't miss any tasks.
3380 css_task_iter_start(css, &it);
3381 while ((p = css_task_iter_next(&it))) {
3383 * Only affect tasks that qualify per the caller's callback,
3384 * if he provided one
3386 if (test && !test(p, data))
3389 * Only process tasks that started after the last task
3392 if (!started_after_time(p, &latest_time, latest_task))
3394 dropped = heap_insert(heap, p);
3395 if (dropped == NULL) {
3397 * The new task was inserted; the heap wasn't
3401 } else if (dropped != p) {
3403 * The new task was inserted, and pushed out a
3407 put_task_struct(dropped);
3410 * Else the new task was newer than anything already in
3411 * the heap and wasn't inserted
3414 css_task_iter_end(&it);
3417 for (i = 0; i < heap->size; i++) {
3418 struct task_struct *q = heap->ptrs[i];
3420 latest_time = q->start_time;
3423 /* Process the task per the caller's callback */
3428 * If we had to process any tasks at all, scan again
3429 * in case some of them were in the middle of forking
3430 * children that didn't get processed.
3431 * Not the most efficient way to do it, but it avoids
3432 * having to take callback_mutex in the fork path
3436 if (heap == &tmp_heap)
3437 heap_free(&tmp_heap);
3441 static void cgroup_transfer_one_task(struct task_struct *task, void *data)
3443 struct cgroup *new_cgroup = data;
3445 mutex_lock(&cgroup_mutex);
3446 cgroup_attach_task(new_cgroup, task, false);
3447 mutex_unlock(&cgroup_mutex);
3451 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3452 * @to: cgroup to which the tasks will be moved
3453 * @from: cgroup in which the tasks currently reside
3455 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3457 return css_scan_tasks(&from->dummy_css, NULL, cgroup_transfer_one_task,
3462 * Stuff for reading the 'tasks'/'procs' files.
3464 * Reading this file can return large amounts of data if a cgroup has
3465 * *lots* of attached tasks. So it may need several calls to read(),
3466 * but we cannot guarantee that the information we produce is correct
3467 * unless we produce it entirely atomically.
3471 /* which pidlist file are we talking about? */
3472 enum cgroup_filetype {
3478 * A pidlist is a list of pids that virtually represents the contents of one
3479 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3480 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3483 struct cgroup_pidlist {
3485 * used to find which pidlist is wanted. doesn't change as long as
3486 * this particular list stays in the list.
3488 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3491 /* how many elements the above list has */
3493 /* how many files are using the current array */
3495 /* each of these stored in a list by its cgroup */
3496 struct list_head links;
3497 /* pointer to the cgroup we belong to, for list removal purposes */
3498 struct cgroup *owner;
3499 /* protects the other fields */
3500 struct rw_semaphore rwsem;
3504 * The following two functions "fix" the issue where there are more pids
3505 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3506 * TODO: replace with a kernel-wide solution to this problem
3508 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3509 static void *pidlist_allocate(int count)
3511 if (PIDLIST_TOO_LARGE(count))
3512 return vmalloc(count * sizeof(pid_t));
3514 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3516 static void pidlist_free(void *p)
3518 if (is_vmalloc_addr(p))
3525 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3526 * Returns the number of unique elements.
3528 static int pidlist_uniq(pid_t *list, int length)
3533 * we presume the 0th element is unique, so i starts at 1. trivial
3534 * edge cases first; no work needs to be done for either
3536 if (length == 0 || length == 1)
3538 /* src and dest walk down the list; dest counts unique elements */
3539 for (src = 1; src < length; src++) {
3540 /* find next unique element */
3541 while (list[src] == list[src-1]) {
3546 /* dest always points to where the next unique element goes */
3547 list[dest] = list[src];
3554 static int cmppid(const void *a, const void *b)
3556 return *(pid_t *)a - *(pid_t *)b;
3560 * find the appropriate pidlist for our purpose (given procs vs tasks)
3561 * returns with the lock on that pidlist already held, and takes care
3562 * of the use count, or returns NULL with no locks held if we're out of
3565 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3566 enum cgroup_filetype type)
3568 struct cgroup_pidlist *l;
3569 /* don't need task_nsproxy() if we're looking at ourself */
3570 struct pid_namespace *ns = task_active_pid_ns(current);
3573 * We can't drop the pidlist_mutex before taking the l->rwsem in case
3574 * the last ref-holder is trying to remove l from the list at the same
3575 * time. Holding the pidlist_mutex precludes somebody taking whichever
3576 * list we find out from under us - compare release_pid_array().
3578 mutex_lock(&cgrp->pidlist_mutex);
3579 list_for_each_entry(l, &cgrp->pidlists, links) {
3580 if (l->key.type == type && l->key.ns == ns) {
3581 /* make sure l doesn't vanish out from under us */
3582 down_write(&l->rwsem);
3583 mutex_unlock(&cgrp->pidlist_mutex);
3587 /* entry not found; create a new one */
3588 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3590 mutex_unlock(&cgrp->pidlist_mutex);
3593 init_rwsem(&l->rwsem);
3594 down_write(&l->rwsem);
3596 l->key.ns = get_pid_ns(ns);
3598 list_add(&l->links, &cgrp->pidlists);
3599 mutex_unlock(&cgrp->pidlist_mutex);
3604 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3606 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3607 struct cgroup_pidlist **lp)
3611 int pid, n = 0; /* used for populating the array */
3612 struct css_task_iter it;
3613 struct task_struct *tsk;
3614 struct cgroup_pidlist *l;
3617 * If cgroup gets more users after we read count, we won't have
3618 * enough space - tough. This race is indistinguishable to the
3619 * caller from the case that the additional cgroup users didn't
3620 * show up until sometime later on.
3622 length = cgroup_task_count(cgrp);
3623 array = pidlist_allocate(length);
3626 /* now, populate the array */
3627 css_task_iter_start(&cgrp->dummy_css, &it);
3628 while ((tsk = css_task_iter_next(&it))) {
3629 if (unlikely(n == length))
3631 /* get tgid or pid for procs or tasks file respectively */
3632 if (type == CGROUP_FILE_PROCS)
3633 pid = task_tgid_vnr(tsk);
3635 pid = task_pid_vnr(tsk);
3636 if (pid > 0) /* make sure to only use valid results */
3639 css_task_iter_end(&it);
3641 /* now sort & (if procs) strip out duplicates */
3642 sort(array, length, sizeof(pid_t), cmppid, NULL);
3643 if (type == CGROUP_FILE_PROCS)
3644 length = pidlist_uniq(array, length);
3645 l = cgroup_pidlist_find(cgrp, type);
3647 pidlist_free(array);
3650 /* store array, freeing old if necessary - lock already held */
3651 pidlist_free(l->list);
3655 up_write(&l->rwsem);
3661 * cgroupstats_build - build and fill cgroupstats
3662 * @stats: cgroupstats to fill information into
3663 * @dentry: A dentry entry belonging to the cgroup for which stats have
3666 * Build and fill cgroupstats so that taskstats can export it to user
3669 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3672 struct cgroup *cgrp;
3673 struct css_task_iter it;
3674 struct task_struct *tsk;
3677 * Validate dentry by checking the superblock operations,
3678 * and make sure it's a directory.
3680 if (dentry->d_sb->s_op != &cgroup_ops ||
3681 !S_ISDIR(dentry->d_inode->i_mode))
3685 cgrp = dentry->d_fsdata;
3687 css_task_iter_start(&cgrp->dummy_css, &it);
3688 while ((tsk = css_task_iter_next(&it))) {
3689 switch (tsk->state) {
3691 stats->nr_running++;
3693 case TASK_INTERRUPTIBLE:
3694 stats->nr_sleeping++;
3696 case TASK_UNINTERRUPTIBLE:
3697 stats->nr_uninterruptible++;
3700 stats->nr_stopped++;
3703 if (delayacct_is_task_waiting_on_io(tsk))
3704 stats->nr_io_wait++;
3708 css_task_iter_end(&it);
3716 * seq_file methods for the tasks/procs files. The seq_file position is the
3717 * next pid to display; the seq_file iterator is a pointer to the pid
3718 * in the cgroup->l->list array.
3721 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3724 * Initially we receive a position value that corresponds to
3725 * one more than the last pid shown (or 0 on the first call or
3726 * after a seek to the start). Use a binary-search to find the
3727 * next pid to display, if any
3729 struct cgroup_pidlist *l = s->private;
3730 int index = 0, pid = *pos;
3733 down_read(&l->rwsem);
3735 int end = l->length;
3737 while (index < end) {
3738 int mid = (index + end) / 2;
3739 if (l->list[mid] == pid) {
3742 } else if (l->list[mid] <= pid)
3748 /* If we're off the end of the array, we're done */
3749 if (index >= l->length)
3751 /* Update the abstract position to be the actual pid that we found */
3752 iter = l->list + index;
3757 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3759 struct cgroup_pidlist *l = s->private;
3763 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3765 struct cgroup_pidlist *l = s->private;
3767 pid_t *end = l->list + l->length;
3769 * Advance to the next pid in the array. If this goes off the
3781 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3783 return seq_printf(s, "%d\n", *(int *)v);
3787 * seq_operations functions for iterating on pidlists through seq_file -
3788 * independent of whether it's tasks or procs
3790 static const struct seq_operations cgroup_pidlist_seq_operations = {
3791 .start = cgroup_pidlist_start,
3792 .stop = cgroup_pidlist_stop,
3793 .next = cgroup_pidlist_next,
3794 .show = cgroup_pidlist_show,
3797 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
3800 * the case where we're the last user of this particular pidlist will
3801 * have us remove it from the cgroup's list, which entails taking the
3802 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3803 * pidlist_mutex, we have to take pidlist_mutex first.
3805 mutex_lock(&l->owner->pidlist_mutex);
3806 down_write(&l->rwsem);
3807 BUG_ON(!l->use_count);
3808 if (!--l->use_count) {
3809 /* we're the last user if refcount is 0; remove and free */
3810 list_del(&l->links);
3811 mutex_unlock(&l->owner->pidlist_mutex);
3812 pidlist_free(l->list);
3813 put_pid_ns(l->key.ns);
3814 up_write(&l->rwsem);
3818 mutex_unlock(&l->owner->pidlist_mutex);
3819 up_write(&l->rwsem);
3822 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
3824 struct cgroup_pidlist *l;
3825 if (!(file->f_mode & FMODE_READ))
3828 * the seq_file will only be initialized if the file was opened for
3829 * reading; hence we check if it's not null only in that case.
3831 l = ((struct seq_file *)file->private_data)->private;
3832 cgroup_release_pid_array(l);
3833 return seq_release(inode, file);
3836 static const struct file_operations cgroup_pidlist_operations = {
3838 .llseek = seq_lseek,
3839 .write = cgroup_file_write,
3840 .release = cgroup_pidlist_release,
3844 * The following functions handle opens on a file that displays a pidlist
3845 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3848 /* helper function for the two below it */
3849 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
3851 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
3852 struct cgroup_pidlist *l;
3855 /* Nothing to do for write-only files */
3856 if (!(file->f_mode & FMODE_READ))
3859 /* have the array populated */
3860 retval = pidlist_array_load(cgrp, type, &l);
3863 /* configure file information */
3864 file->f_op = &cgroup_pidlist_operations;
3866 retval = seq_open(file, &cgroup_pidlist_seq_operations);
3868 cgroup_release_pid_array(l);
3871 ((struct seq_file *)file->private_data)->private = l;
3874 static int cgroup_tasks_open(struct inode *unused, struct file *file)
3876 return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
3878 static int cgroup_procs_open(struct inode *unused, struct file *file)
3880 return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
3883 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3886 return notify_on_release(css->cgroup);
3889 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3890 struct cftype *cft, u64 val)
3892 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3894 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3896 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3901 * When dput() is called asynchronously, if umount has been done and
3902 * then deactivate_super() in cgroup_free_fn() kills the superblock,
3903 * there's a small window that vfs will see the root dentry with non-zero
3904 * refcnt and trigger BUG().
3906 * That's why we hold a reference before dput() and drop it right after.
3908 static void cgroup_dput(struct cgroup *cgrp)
3910 struct super_block *sb = cgrp->root->sb;
3912 atomic_inc(&sb->s_active);
3914 deactivate_super(sb);
3917 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3920 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3923 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3924 struct cftype *cft, u64 val)
3927 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3929 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3933 static struct cftype cgroup_base_files[] = {
3935 .name = "cgroup.procs",
3936 .open = cgroup_procs_open,
3937 .write_u64 = cgroup_procs_write,
3938 .release = cgroup_pidlist_release,
3939 .mode = S_IRUGO | S_IWUSR,
3942 .name = "cgroup.clone_children",
3943 .flags = CFTYPE_INSANE,
3944 .read_u64 = cgroup_clone_children_read,
3945 .write_u64 = cgroup_clone_children_write,
3948 .name = "cgroup.sane_behavior",
3949 .flags = CFTYPE_ONLY_ON_ROOT,
3950 .read_seq_string = cgroup_sane_behavior_show,
3954 * Historical crazy stuff. These don't have "cgroup." prefix and
3955 * don't exist if sane_behavior. If you're depending on these, be
3956 * prepared to be burned.
3960 .flags = CFTYPE_INSANE, /* use "procs" instead */
3961 .open = cgroup_tasks_open,
3962 .write_u64 = cgroup_tasks_write,
3963 .release = cgroup_pidlist_release,
3964 .mode = S_IRUGO | S_IWUSR,
3967 .name = "notify_on_release",
3968 .flags = CFTYPE_INSANE,
3969 .read_u64 = cgroup_read_notify_on_release,
3970 .write_u64 = cgroup_write_notify_on_release,
3973 .name = "release_agent",
3974 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
3975 .read_seq_string = cgroup_release_agent_show,
3976 .write_string = cgroup_release_agent_write,
3977 .max_write_len = PATH_MAX,
3983 * cgroup_populate_dir - create subsys files in a cgroup directory
3984 * @cgrp: target cgroup
3985 * @subsys_mask: mask of the subsystem ids whose files should be added
3987 * On failure, no file is added.
3989 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
3991 struct cgroup_subsys *ss;
3994 /* process cftsets of each subsystem */
3995 for_each_subsys(ss, i) {
3996 struct cftype_set *set;
3998 if (!test_bit(i, &subsys_mask))
4001 list_for_each_entry(set, &ss->cftsets, node) {
4002 ret = cgroup_addrm_files(cgrp, set->cfts, true);
4008 /* This cgroup is ready now */
4009 for_each_root_subsys(cgrp->root, ss) {
4010 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss);
4011 struct css_id *id = rcu_dereference_protected(css->id, true);
4014 * Update id->css pointer and make this css visible from
4015 * CSS ID functions. This pointer will be dereferened
4016 * from RCU-read-side without locks.
4019 rcu_assign_pointer(id->css, css);
4024 cgroup_clear_dir(cgrp, subsys_mask);
4029 * css destruction is four-stage process.
4031 * 1. Destruction starts. Killing of the percpu_ref is initiated.
4032 * Implemented in kill_css().
4034 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4035 * and thus css_tryget() is guaranteed to fail, the css can be offlined
4036 * by invoking offline_css(). After offlining, the base ref is put.
4037 * Implemented in css_killed_work_fn().
4039 * 3. When the percpu_ref reaches zero, the only possible remaining
4040 * accessors are inside RCU read sections. css_release() schedules the
4043 * 4. After the grace period, the css can be freed. Implemented in
4044 * css_free_work_fn().
4046 * It is actually hairier because both step 2 and 4 require process context
4047 * and thus involve punting to css->destroy_work adding two additional
4048 * steps to the already complex sequence.
4050 static void css_free_work_fn(struct work_struct *work)
4052 struct cgroup_subsys_state *css =
4053 container_of(work, struct cgroup_subsys_state, destroy_work);
4054 struct cgroup *cgrp = css->cgroup;
4057 css_put(css->parent);
4059 css->ss->css_free(css);
4063 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4065 struct cgroup_subsys_state *css =
4066 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4069 * css holds an extra ref to @cgrp->dentry which is put on the last
4070 * css_put(). dput() requires process context which we don't have.
4072 INIT_WORK(&css->destroy_work, css_free_work_fn);
4073 schedule_work(&css->destroy_work);
4076 static void css_release(struct percpu_ref *ref)
4078 struct cgroup_subsys_state *css =
4079 container_of(ref, struct cgroup_subsys_state, refcnt);
4081 call_rcu(&css->rcu_head, css_free_rcu_fn);
4084 static void init_css(struct cgroup_subsys_state *css, struct cgroup_subsys *ss,
4085 struct cgroup *cgrp)
4093 css->parent = cgroup_css(cgrp->parent, ss);
4095 css->flags |= CSS_ROOT;
4097 BUG_ON(cgroup_css(cgrp, ss));
4100 /* invoke ->css_online() on a new CSS and mark it online if successful */
4101 static int online_css(struct cgroup_subsys_state *css)
4103 struct cgroup_subsys *ss = css->ss;
4106 lockdep_assert_held(&cgroup_mutex);
4109 ret = ss->css_online(css);
4111 css->flags |= CSS_ONLINE;
4112 css->cgroup->nr_css++;
4113 rcu_assign_pointer(css->cgroup->subsys[ss->subsys_id], css);
4118 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4119 static void offline_css(struct cgroup_subsys_state *css)
4121 struct cgroup_subsys *ss = css->ss;
4123 lockdep_assert_held(&cgroup_mutex);
4125 if (!(css->flags & CSS_ONLINE))
4128 if (ss->css_offline)
4129 ss->css_offline(css);
4131 css->flags &= ~CSS_ONLINE;
4132 css->cgroup->nr_css--;
4133 RCU_INIT_POINTER(css->cgroup->subsys[ss->subsys_id], css);
4137 * cgroup_create - create a cgroup
4138 * @parent: cgroup that will be parent of the new cgroup
4139 * @dentry: dentry of the new cgroup
4140 * @mode: mode to set on new inode
4142 * Must be called with the mutex on the parent inode held
4144 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4147 struct cgroup_subsys_state *css_ar[CGROUP_SUBSYS_COUNT] = { };
4148 struct cgroup *cgrp;
4149 struct cgroup_name *name;
4150 struct cgroupfs_root *root = parent->root;
4152 struct cgroup_subsys *ss;
4153 struct super_block *sb = root->sb;
4155 /* allocate the cgroup and its ID, 0 is reserved for the root */
4156 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4160 name = cgroup_alloc_name(dentry);
4163 rcu_assign_pointer(cgrp->name, name);
4166 * Temporarily set the pointer to NULL, so idr_find() won't return
4167 * a half-baked cgroup.
4169 cgrp->id = idr_alloc(&root->cgroup_idr, NULL, 1, 0, GFP_KERNEL);
4174 * Only live parents can have children. Note that the liveliness
4175 * check isn't strictly necessary because cgroup_mkdir() and
4176 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4177 * anyway so that locking is contained inside cgroup proper and we
4178 * don't get nasty surprises if we ever grow another caller.
4180 if (!cgroup_lock_live_group(parent)) {
4185 /* Grab a reference on the superblock so the hierarchy doesn't
4186 * get deleted on unmount if there are child cgroups. This
4187 * can be done outside cgroup_mutex, since the sb can't
4188 * disappear while someone has an open control file on the
4190 atomic_inc(&sb->s_active);
4192 init_cgroup_housekeeping(cgrp);
4194 dentry->d_fsdata = cgrp;
4195 cgrp->dentry = dentry;
4197 cgrp->parent = parent;
4198 cgrp->dummy_css.parent = &parent->dummy_css;
4199 cgrp->root = parent->root;
4201 if (notify_on_release(parent))
4202 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4204 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4205 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4207 for_each_root_subsys(root, ss) {
4208 struct cgroup_subsys_state *css;
4210 css = ss->css_alloc(cgroup_css(parent, ss));
4215 css_ar[ss->subsys_id] = css;
4217 err = percpu_ref_init(&css->refcnt, css_release);
4221 init_css(css, ss, cgrp);
4224 err = alloc_css_id(css);
4231 * Create directory. cgroup_create_file() returns with the new
4232 * directory locked on success so that it can be populated without
4233 * dropping cgroup_mutex.
4235 err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4238 lockdep_assert_held(&dentry->d_inode->i_mutex);
4240 cgrp->serial_nr = cgroup_serial_nr_next++;
4242 /* allocation complete, commit to creation */
4243 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4244 root->number_of_cgroups++;
4246 /* each css holds a ref to the cgroup's dentry and the parent css */
4247 for_each_root_subsys(root, ss) {
4248 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4251 css_get(css->parent);
4254 /* hold a ref to the parent's dentry */
4255 dget(parent->dentry);
4257 /* creation succeeded, notify subsystems */
4258 for_each_root_subsys(root, ss) {
4259 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4261 err = online_css(css);
4265 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4267 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",
4268 current->comm, current->pid, ss->name);
4269 if (!strcmp(ss->name, "memory"))
4270 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4271 ss->warned_broken_hierarchy = true;
4275 idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4277 err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
4281 err = cgroup_populate_dir(cgrp, root->subsys_mask);
4285 mutex_unlock(&cgroup_mutex);
4286 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4291 for_each_root_subsys(root, ss) {
4292 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4295 percpu_ref_cancel_init(&css->refcnt);
4299 mutex_unlock(&cgroup_mutex);
4300 /* Release the reference count that we took on the superblock */
4301 deactivate_super(sb);
4303 idr_remove(&root->cgroup_idr, cgrp->id);
4305 kfree(rcu_dereference_raw(cgrp->name));
4311 cgroup_destroy_locked(cgrp);
4312 mutex_unlock(&cgroup_mutex);
4313 mutex_unlock(&dentry->d_inode->i_mutex);
4317 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4319 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4321 /* the vfs holds inode->i_mutex already */
4322 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4326 * This is called when the refcnt of a css is confirmed to be killed.
4327 * css_tryget() is now guaranteed to fail.
4329 static void css_killed_work_fn(struct work_struct *work)
4331 struct cgroup_subsys_state *css =
4332 container_of(work, struct cgroup_subsys_state, destroy_work);
4333 struct cgroup *cgrp = css->cgroup;
4335 mutex_lock(&cgroup_mutex);
4338 * css_tryget() is guaranteed to fail now. Tell subsystems to
4339 * initate destruction.
4344 * If @cgrp is marked dead, it's waiting for refs of all css's to
4345 * be disabled before proceeding to the second phase of cgroup
4346 * destruction. If we are the last one, kick it off.
4348 if (!cgrp->nr_css && cgroup_is_dead(cgrp))
4349 cgroup_destroy_css_killed(cgrp);
4351 mutex_unlock(&cgroup_mutex);
4354 * Put the css refs from kill_css(). Each css holds an extra
4355 * reference to the cgroup's dentry and cgroup removal proceeds
4356 * regardless of css refs. On the last put of each css, whenever
4357 * that may be, the extra dentry ref is put so that dentry
4358 * destruction happens only after all css's are released.
4363 /* css kill confirmation processing requires process context, bounce */
4364 static void css_killed_ref_fn(struct percpu_ref *ref)
4366 struct cgroup_subsys_state *css =
4367 container_of(ref, struct cgroup_subsys_state, refcnt);
4369 INIT_WORK(&css->destroy_work, css_killed_work_fn);
4370 schedule_work(&css->destroy_work);
4374 * kill_css - destroy a css
4375 * @css: css to destroy
4377 * This function initiates destruction of @css by removing cgroup interface
4378 * files and putting its base reference. ->css_offline() will be invoked
4379 * asynchronously once css_tryget() is guaranteed to fail and when the
4380 * reference count reaches zero, @css will be released.
4382 static void kill_css(struct cgroup_subsys_state *css)
4384 cgroup_clear_dir(css->cgroup, 1 << css->ss->subsys_id);
4387 * Killing would put the base ref, but we need to keep it alive
4388 * until after ->css_offline().
4393 * cgroup core guarantees that, by the time ->css_offline() is
4394 * invoked, no new css reference will be given out via
4395 * css_tryget(). We can't simply call percpu_ref_kill() and
4396 * proceed to offlining css's because percpu_ref_kill() doesn't
4397 * guarantee that the ref is seen as killed on all CPUs on return.
4399 * Use percpu_ref_kill_and_confirm() to get notifications as each
4400 * css is confirmed to be seen as killed on all CPUs.
4402 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4406 * cgroup_destroy_locked - the first stage of cgroup destruction
4407 * @cgrp: cgroup to be destroyed
4409 * css's make use of percpu refcnts whose killing latency shouldn't be
4410 * exposed to userland and are RCU protected. Also, cgroup core needs to
4411 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
4412 * invoked. To satisfy all the requirements, destruction is implemented in
4413 * the following two steps.
4415 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4416 * userland visible parts and start killing the percpu refcnts of
4417 * css's. Set up so that the next stage will be kicked off once all
4418 * the percpu refcnts are confirmed to be killed.
4420 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4421 * rest of destruction. Once all cgroup references are gone, the
4422 * cgroup is RCU-freed.
4424 * This function implements s1. After this step, @cgrp is gone as far as
4425 * the userland is concerned and a new cgroup with the same name may be
4426 * created. As cgroup doesn't care about the names internally, this
4427 * doesn't cause any problem.
4429 static int cgroup_destroy_locked(struct cgroup *cgrp)
4430 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4432 struct dentry *d = cgrp->dentry;
4433 struct cgroup_subsys *ss;
4434 struct cgroup *child;
4437 lockdep_assert_held(&d->d_inode->i_mutex);
4438 lockdep_assert_held(&cgroup_mutex);
4441 * css_set_lock synchronizes access to ->cset_links and prevents
4442 * @cgrp from being removed while __put_css_set() is in progress.
4444 read_lock(&css_set_lock);
4445 empty = list_empty(&cgrp->cset_links);
4446 read_unlock(&css_set_lock);
4451 * Make sure there's no live children. We can't test ->children
4452 * emptiness as dead children linger on it while being destroyed;
4453 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
4457 list_for_each_entry_rcu(child, &cgrp->children, sibling) {
4458 empty = cgroup_is_dead(child);
4467 * Initiate massacre of all css's. cgroup_destroy_css_killed()
4468 * will be invoked to perform the rest of destruction once the
4469 * percpu refs of all css's are confirmed to be killed.
4471 for_each_root_subsys(cgrp->root, ss)
4472 kill_css(cgroup_css(cgrp, ss));
4475 * Mark @cgrp dead. This prevents further task migration and child
4476 * creation by disabling cgroup_lock_live_group(). Note that
4477 * CGRP_DEAD assertion is depended upon by css_next_child() to
4478 * resume iteration after dropping RCU read lock. See
4479 * css_next_child() for details.
4481 set_bit(CGRP_DEAD, &cgrp->flags);
4483 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4484 raw_spin_lock(&release_list_lock);
4485 if (!list_empty(&cgrp->release_list))
4486 list_del_init(&cgrp->release_list);
4487 raw_spin_unlock(&release_list_lock);
4490 * If @cgrp has css's attached, the second stage of cgroup
4491 * destruction is kicked off from css_killed_work_fn() after the
4492 * refs of all attached css's are killed. If @cgrp doesn't have
4493 * any css, we kick it off here.
4496 cgroup_destroy_css_killed(cgrp);
4499 * Clear the base files and remove @cgrp directory. The removal
4500 * puts the base ref but we aren't quite done with @cgrp yet, so
4503 cgroup_addrm_files(cgrp, cgroup_base_files, false);
4505 cgroup_d_remove_dir(d);
4511 * cgroup_destroy_css_killed - the second step of cgroup destruction
4512 * @work: cgroup->destroy_free_work
4514 * This function is invoked from a work item for a cgroup which is being
4515 * destroyed after all css's are offlined and performs the rest of
4516 * destruction. This is the second step of destruction described in the
4517 * comment above cgroup_destroy_locked().
4519 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
4521 struct cgroup *parent = cgrp->parent;
4522 struct dentry *d = cgrp->dentry;
4524 lockdep_assert_held(&cgroup_mutex);
4526 /* delete this cgroup from parent->children */
4527 list_del_rcu(&cgrp->sibling);
4530 * We should remove the cgroup object from idr before its grace
4531 * period starts, so we won't be looking up a cgroup while the
4532 * cgroup is being freed.
4534 idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4539 set_bit(CGRP_RELEASABLE, &parent->flags);
4540 check_for_release(parent);
4543 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4547 mutex_lock(&cgroup_mutex);
4548 ret = cgroup_destroy_locked(dentry->d_fsdata);
4549 mutex_unlock(&cgroup_mutex);
4554 static void __init_or_module cgroup_init_cftsets(struct cgroup_subsys *ss)
4556 INIT_LIST_HEAD(&ss->cftsets);
4559 * base_cftset is embedded in subsys itself, no need to worry about
4562 if (ss->base_cftypes) {
4565 for (cft = ss->base_cftypes; cft->name[0] != '\0'; cft++)
4568 ss->base_cftset.cfts = ss->base_cftypes;
4569 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4573 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4575 struct cgroup_subsys_state *css;
4577 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4579 mutex_lock(&cgroup_mutex);
4581 /* init base cftset */
4582 cgroup_init_cftsets(ss);
4584 /* Create the top cgroup state for this subsystem */
4585 list_add(&ss->sibling, &cgroup_dummy_root.subsys_list);
4586 ss->root = &cgroup_dummy_root;
4587 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
4588 /* We don't handle early failures gracefully */
4589 BUG_ON(IS_ERR(css));
4590 init_css(css, ss, cgroup_dummy_top);
4592 /* Update the init_css_set to contain a subsys
4593 * pointer to this state - since the subsystem is
4594 * newly registered, all tasks and hence the
4595 * init_css_set is in the subsystem's top cgroup. */
4596 init_css_set.subsys[ss->subsys_id] = css;
4598 need_forkexit_callback |= ss->fork || ss->exit;
4600 /* At system boot, before all subsystems have been
4601 * registered, no tasks have been forked, so we don't
4602 * need to invoke fork callbacks here. */
4603 BUG_ON(!list_empty(&init_task.tasks));
4605 BUG_ON(online_css(css));
4607 mutex_unlock(&cgroup_mutex);
4609 /* this function shouldn't be used with modular subsystems, since they
4610 * need to register a subsys_id, among other things */
4615 * cgroup_load_subsys: load and register a modular subsystem at runtime
4616 * @ss: the subsystem to load
4618 * This function should be called in a modular subsystem's initcall. If the
4619 * subsystem is built as a module, it will be assigned a new subsys_id and set
4620 * up for use. If the subsystem is built-in anyway, work is delegated to the
4621 * simpler cgroup_init_subsys.
4623 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
4625 struct cgroup_subsys_state *css;
4627 struct hlist_node *tmp;
4628 struct css_set *cset;
4631 /* check name and function validity */
4632 if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
4633 ss->css_alloc == NULL || ss->css_free == NULL)
4637 * we don't support callbacks in modular subsystems. this check is
4638 * before the ss->module check for consistency; a subsystem that could
4639 * be a module should still have no callbacks even if the user isn't
4640 * compiling it as one.
4642 if (ss->fork || ss->exit)
4646 * an optionally modular subsystem is built-in: we want to do nothing,
4647 * since cgroup_init_subsys will have already taken care of it.
4649 if (ss->module == NULL) {
4650 /* a sanity check */
4651 BUG_ON(cgroup_subsys[ss->subsys_id] != ss);
4655 /* init base cftset */
4656 cgroup_init_cftsets(ss);
4658 mutex_lock(&cgroup_mutex);
4659 cgroup_subsys[ss->subsys_id] = ss;
4662 * no ss->css_alloc seems to need anything important in the ss
4663 * struct, so this can happen first (i.e. before the dummy root
4666 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
4668 /* failure case - need to deassign the cgroup_subsys[] slot. */
4669 cgroup_subsys[ss->subsys_id] = NULL;
4670 mutex_unlock(&cgroup_mutex);
4671 return PTR_ERR(css);
4674 list_add(&ss->sibling, &cgroup_dummy_root.subsys_list);
4675 ss->root = &cgroup_dummy_root;
4677 /* our new subsystem will be attached to the dummy hierarchy. */
4678 init_css(css, ss, cgroup_dummy_top);
4679 /* init_idr must be after init_css() because it sets css->id. */
4681 ret = cgroup_init_idr(ss, css);
4687 * Now we need to entangle the css into the existing css_sets. unlike
4688 * in cgroup_init_subsys, there are now multiple css_sets, so each one
4689 * will need a new pointer to it; done by iterating the css_set_table.
4690 * furthermore, modifying the existing css_sets will corrupt the hash
4691 * table state, so each changed css_set will need its hash recomputed.
4692 * this is all done under the css_set_lock.
4694 write_lock(&css_set_lock);
4695 hash_for_each_safe(css_set_table, i, tmp, cset, hlist) {
4696 /* skip entries that we already rehashed */
4697 if (cset->subsys[ss->subsys_id])
4699 /* remove existing entry */
4700 hash_del(&cset->hlist);
4702 cset->subsys[ss->subsys_id] = css;
4703 /* recompute hash and restore entry */
4704 key = css_set_hash(cset->subsys);
4705 hash_add(css_set_table, &cset->hlist, key);
4707 write_unlock(&css_set_lock);
4709 ret = online_css(css);
4714 mutex_unlock(&cgroup_mutex);
4718 mutex_unlock(&cgroup_mutex);
4719 /* @ss can't be mounted here as try_module_get() would fail */
4720 cgroup_unload_subsys(ss);
4723 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
4726 * cgroup_unload_subsys: unload a modular subsystem
4727 * @ss: the subsystem to unload
4729 * This function should be called in a modular subsystem's exitcall. When this
4730 * function is invoked, the refcount on the subsystem's module will be 0, so
4731 * the subsystem will not be attached to any hierarchy.
4733 void cgroup_unload_subsys(struct cgroup_subsys *ss)
4735 struct cgrp_cset_link *link;
4737 BUG_ON(ss->module == NULL);
4740 * we shouldn't be called if the subsystem is in use, and the use of
4741 * try_module_get() in rebind_subsystems() should ensure that it
4742 * doesn't start being used while we're killing it off.
4744 BUG_ON(ss->root != &cgroup_dummy_root);
4746 mutex_lock(&cgroup_mutex);
4748 offline_css(cgroup_css(cgroup_dummy_top, ss));
4751 idr_destroy(&ss->idr);
4753 /* deassign the subsys_id */
4754 cgroup_subsys[ss->subsys_id] = NULL;
4756 /* remove subsystem from the dummy root's list of subsystems */
4757 list_del_init(&ss->sibling);
4760 * disentangle the css from all css_sets attached to the dummy
4761 * top. as in loading, we need to pay our respects to the hashtable
4764 write_lock(&css_set_lock);
4765 list_for_each_entry(link, &cgroup_dummy_top->cset_links, cset_link) {
4766 struct css_set *cset = link->cset;
4769 hash_del(&cset->hlist);
4770 cset->subsys[ss->subsys_id] = NULL;
4771 key = css_set_hash(cset->subsys);
4772 hash_add(css_set_table, &cset->hlist, key);
4774 write_unlock(&css_set_lock);
4777 * remove subsystem's css from the cgroup_dummy_top and free it -
4778 * need to free before marking as null because ss->css_free needs
4779 * the cgrp->subsys pointer to find their state. note that this
4780 * also takes care of freeing the css_id.
4782 ss->css_free(cgroup_css(cgroup_dummy_top, ss));
4783 RCU_INIT_POINTER(cgroup_dummy_top->subsys[ss->subsys_id], NULL);
4785 mutex_unlock(&cgroup_mutex);
4787 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
4790 * cgroup_init_early - cgroup initialization at system boot
4792 * Initialize cgroups at system boot, and initialize any
4793 * subsystems that request early init.
4795 int __init cgroup_init_early(void)
4797 struct cgroup_subsys *ss;
4800 atomic_set(&init_css_set.refcount, 1);
4801 INIT_LIST_HEAD(&init_css_set.cgrp_links);
4802 INIT_LIST_HEAD(&init_css_set.tasks);
4803 INIT_HLIST_NODE(&init_css_set.hlist);
4805 init_cgroup_root(&cgroup_dummy_root);
4806 cgroup_root_count = 1;
4807 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4809 init_cgrp_cset_link.cset = &init_css_set;
4810 init_cgrp_cset_link.cgrp = cgroup_dummy_top;
4811 list_add(&init_cgrp_cset_link.cset_link, &cgroup_dummy_top->cset_links);
4812 list_add(&init_cgrp_cset_link.cgrp_link, &init_css_set.cgrp_links);
4814 /* at bootup time, we don't worry about modular subsystems */
4815 for_each_builtin_subsys(ss, i) {
4817 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
4818 BUG_ON(!ss->css_alloc);
4819 BUG_ON(!ss->css_free);
4820 if (ss->subsys_id != i) {
4821 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
4822 ss->name, ss->subsys_id);
4827 cgroup_init_subsys(ss);
4833 * cgroup_init - cgroup initialization
4835 * Register cgroup filesystem and /proc file, and initialize
4836 * any subsystems that didn't request early init.
4838 int __init cgroup_init(void)
4840 struct cgroup_subsys *ss;
4844 err = bdi_init(&cgroup_backing_dev_info);
4848 for_each_builtin_subsys(ss, i) {
4849 if (!ss->early_init)
4850 cgroup_init_subsys(ss);
4852 cgroup_init_idr(ss, init_css_set.subsys[ss->subsys_id]);
4855 /* allocate id for the dummy hierarchy */
4856 mutex_lock(&cgroup_mutex);
4857 mutex_lock(&cgroup_root_mutex);
4859 /* Add init_css_set to the hash table */
4860 key = css_set_hash(init_css_set.subsys);
4861 hash_add(css_set_table, &init_css_set.hlist, key);
4863 BUG_ON(cgroup_init_root_id(&cgroup_dummy_root, 0, 1));
4865 err = idr_alloc(&cgroup_dummy_root.cgroup_idr, cgroup_dummy_top,
4869 mutex_unlock(&cgroup_root_mutex);
4870 mutex_unlock(&cgroup_mutex);
4872 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4878 err = register_filesystem(&cgroup_fs_type);
4880 kobject_put(cgroup_kobj);
4884 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4888 bdi_destroy(&cgroup_backing_dev_info);
4894 * proc_cgroup_show()
4895 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4896 * - Used for /proc/<pid>/cgroup.
4897 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4898 * doesn't really matter if tsk->cgroup changes after we read it,
4899 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4900 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4901 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4902 * cgroup to top_cgroup.
4905 /* TODO: Use a proper seq_file iterator */
4906 int proc_cgroup_show(struct seq_file *m, void *v)
4909 struct task_struct *tsk;
4912 struct cgroupfs_root *root;
4915 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4921 tsk = get_pid_task(pid, PIDTYPE_PID);
4927 mutex_lock(&cgroup_mutex);
4929 for_each_active_root(root) {
4930 struct cgroup_subsys *ss;
4931 struct cgroup *cgrp;
4934 seq_printf(m, "%d:", root->hierarchy_id);
4935 for_each_root_subsys(root, ss)
4936 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4937 if (strlen(root->name))
4938 seq_printf(m, "%sname=%s", count ? "," : "",
4941 cgrp = task_cgroup_from_root(tsk, root);
4942 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
4950 mutex_unlock(&cgroup_mutex);
4951 put_task_struct(tsk);
4958 /* Display information about each subsystem and each hierarchy */
4959 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4961 struct cgroup_subsys *ss;
4964 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4966 * ideally we don't want subsystems moving around while we do this.
4967 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4968 * subsys/hierarchy state.
4970 mutex_lock(&cgroup_mutex);
4972 for_each_subsys(ss, i)
4973 seq_printf(m, "%s\t%d\t%d\t%d\n",
4974 ss->name, ss->root->hierarchy_id,
4975 ss->root->number_of_cgroups, !ss->disabled);
4977 mutex_unlock(&cgroup_mutex);
4981 static int cgroupstats_open(struct inode *inode, struct file *file)
4983 return single_open(file, proc_cgroupstats_show, NULL);
4986 static const struct file_operations proc_cgroupstats_operations = {
4987 .open = cgroupstats_open,
4989 .llseek = seq_lseek,
4990 .release = single_release,
4994 * cgroup_fork - attach newly forked task to its parents cgroup.
4995 * @child: pointer to task_struct of forking parent process.
4997 * Description: A task inherits its parent's cgroup at fork().
4999 * A pointer to the shared css_set was automatically copied in
5000 * fork.c by dup_task_struct(). However, we ignore that copy, since
5001 * it was not made under the protection of RCU or cgroup_mutex, so
5002 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
5003 * have already changed current->cgroups, allowing the previously
5004 * referenced cgroup group to be removed and freed.
5006 * At the point that cgroup_fork() is called, 'current' is the parent
5007 * task, and the passed argument 'child' points to the child task.
5009 void cgroup_fork(struct task_struct *child)
5012 get_css_set(task_css_set(current));
5013 child->cgroups = current->cgroups;
5014 task_unlock(current);
5015 INIT_LIST_HEAD(&child->cg_list);
5019 * cgroup_post_fork - called on a new task after adding it to the task list
5020 * @child: the task in question
5022 * Adds the task to the list running through its css_set if necessary and
5023 * call the subsystem fork() callbacks. Has to be after the task is
5024 * visible on the task list in case we race with the first call to
5025 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
5028 void cgroup_post_fork(struct task_struct *child)
5030 struct cgroup_subsys *ss;
5034 * use_task_css_set_links is set to 1 before we walk the tasklist
5035 * under the tasklist_lock and we read it here after we added the child
5036 * to the tasklist under the tasklist_lock as well. If the child wasn't
5037 * yet in the tasklist when we walked through it from
5038 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
5039 * should be visible now due to the paired locking and barriers implied
5040 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
5041 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
5044 if (use_task_css_set_links) {
5045 write_lock(&css_set_lock);
5047 if (list_empty(&child->cg_list))
5048 list_add(&child->cg_list, &task_css_set(child)->tasks);
5050 write_unlock(&css_set_lock);
5054 * Call ss->fork(). This must happen after @child is linked on
5055 * css_set; otherwise, @child might change state between ->fork()
5056 * and addition to css_set.
5058 if (need_forkexit_callback) {
5060 * fork/exit callbacks are supported only for builtin
5061 * subsystems, and the builtin section of the subsys
5062 * array is immutable, so we don't need to lock the
5063 * subsys array here. On the other hand, modular section
5064 * of the array can be freed at module unload, so we
5067 for_each_builtin_subsys(ss, i)
5074 * cgroup_exit - detach cgroup from exiting task
5075 * @tsk: pointer to task_struct of exiting process
5076 * @run_callback: run exit callbacks?
5078 * Description: Detach cgroup from @tsk and release it.
5080 * Note that cgroups marked notify_on_release force every task in
5081 * them to take the global cgroup_mutex mutex when exiting.
5082 * This could impact scaling on very large systems. Be reluctant to
5083 * use notify_on_release cgroups where very high task exit scaling
5084 * is required on large systems.
5086 * the_top_cgroup_hack:
5088 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
5090 * We call cgroup_exit() while the task is still competent to
5091 * handle notify_on_release(), then leave the task attached to the
5092 * root cgroup in each hierarchy for the remainder of its exit.
5094 * To do this properly, we would increment the reference count on
5095 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
5096 * code we would add a second cgroup function call, to drop that
5097 * reference. This would just create an unnecessary hot spot on
5098 * the top_cgroup reference count, to no avail.
5100 * Normally, holding a reference to a cgroup without bumping its
5101 * count is unsafe. The cgroup could go away, or someone could
5102 * attach us to a different cgroup, decrementing the count on
5103 * the first cgroup that we never incremented. But in this case,
5104 * top_cgroup isn't going away, and either task has PF_EXITING set,
5105 * which wards off any cgroup_attach_task() attempts, or task is a failed
5106 * fork, never visible to cgroup_attach_task.
5108 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
5110 struct cgroup_subsys *ss;
5111 struct css_set *cset;
5115 * Unlink from the css_set task list if necessary.
5116 * Optimistically check cg_list before taking
5119 if (!list_empty(&tsk->cg_list)) {
5120 write_lock(&css_set_lock);
5121 if (!list_empty(&tsk->cg_list))
5122 list_del_init(&tsk->cg_list);
5123 write_unlock(&css_set_lock);
5126 /* Reassign the task to the init_css_set. */
5128 cset = task_css_set(tsk);
5129 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
5131 if (run_callbacks && need_forkexit_callback) {
5133 * fork/exit callbacks are supported only for builtin
5134 * subsystems, see cgroup_post_fork() for details.
5136 for_each_builtin_subsys(ss, i) {
5138 struct cgroup_subsys_state *old_css = cset->subsys[i];
5139 struct cgroup_subsys_state *css = task_css(tsk, i);
5141 ss->exit(css, old_css, tsk);
5147 put_css_set_taskexit(cset);
5150 static void check_for_release(struct cgroup *cgrp)
5152 if (cgroup_is_releasable(cgrp) &&
5153 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
5155 * Control Group is currently removeable. If it's not
5156 * already queued for a userspace notification, queue
5159 int need_schedule_work = 0;
5161 raw_spin_lock(&release_list_lock);
5162 if (!cgroup_is_dead(cgrp) &&
5163 list_empty(&cgrp->release_list)) {
5164 list_add(&cgrp->release_list, &release_list);
5165 need_schedule_work = 1;
5167 raw_spin_unlock(&release_list_lock);
5168 if (need_schedule_work)
5169 schedule_work(&release_agent_work);
5174 * Notify userspace when a cgroup is released, by running the
5175 * configured release agent with the name of the cgroup (path
5176 * relative to the root of cgroup file system) as the argument.
5178 * Most likely, this user command will try to rmdir this cgroup.
5180 * This races with the possibility that some other task will be
5181 * attached to this cgroup before it is removed, or that some other
5182 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5183 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5184 * unused, and this cgroup will be reprieved from its death sentence,
5185 * to continue to serve a useful existence. Next time it's released,
5186 * we will get notified again, if it still has 'notify_on_release' set.
5188 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5189 * means only wait until the task is successfully execve()'d. The
5190 * separate release agent task is forked by call_usermodehelper(),
5191 * then control in this thread returns here, without waiting for the
5192 * release agent task. We don't bother to wait because the caller of
5193 * this routine has no use for the exit status of the release agent
5194 * task, so no sense holding our caller up for that.
5196 static void cgroup_release_agent(struct work_struct *work)
5198 BUG_ON(work != &release_agent_work);
5199 mutex_lock(&cgroup_mutex);
5200 raw_spin_lock(&release_list_lock);
5201 while (!list_empty(&release_list)) {
5202 char *argv[3], *envp[3];
5204 char *pathbuf = NULL, *agentbuf = NULL;
5205 struct cgroup *cgrp = list_entry(release_list.next,
5208 list_del_init(&cgrp->release_list);
5209 raw_spin_unlock(&release_list_lock);
5210 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5213 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
5215 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5220 argv[i++] = agentbuf;
5221 argv[i++] = pathbuf;
5225 /* minimal command environment */
5226 envp[i++] = "HOME=/";
5227 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5230 /* Drop the lock while we invoke the usermode helper,
5231 * since the exec could involve hitting disk and hence
5232 * be a slow process */
5233 mutex_unlock(&cgroup_mutex);
5234 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5235 mutex_lock(&cgroup_mutex);
5239 raw_spin_lock(&release_list_lock);
5241 raw_spin_unlock(&release_list_lock);
5242 mutex_unlock(&cgroup_mutex);
5245 static int __init cgroup_disable(char *str)
5247 struct cgroup_subsys *ss;
5251 while ((token = strsep(&str, ",")) != NULL) {
5256 * cgroup_disable, being at boot time, can't know about
5257 * module subsystems, so we don't worry about them.
5259 for_each_builtin_subsys(ss, i) {
5260 if (!strcmp(token, ss->name)) {
5262 printk(KERN_INFO "Disabling %s control group"
5263 " subsystem\n", ss->name);
5270 __setup("cgroup_disable=", cgroup_disable);
5273 * Functons for CSS ID.
5276 /* to get ID other than 0, this should be called when !cgroup_is_dead() */
5277 unsigned short css_id(struct cgroup_subsys_state *css)
5279 struct css_id *cssid;
5282 * This css_id() can return correct value when somone has refcnt
5283 * on this or this is under rcu_read_lock(). Once css->id is allocated,
5284 * it's unchanged until freed.
5286 cssid = rcu_dereference_raw(css->id);
5292 EXPORT_SYMBOL_GPL(css_id);
5295 * css_is_ancestor - test "root" css is an ancestor of "child"
5296 * @child: the css to be tested.
5297 * @root: the css supporsed to be an ancestor of the child.
5299 * Returns true if "root" is an ancestor of "child" in its hierarchy. Because
5300 * this function reads css->id, the caller must hold rcu_read_lock().
5301 * But, considering usual usage, the csses should be valid objects after test.
5302 * Assuming that the caller will do some action to the child if this returns
5303 * returns true, the caller must take "child";s reference count.
5304 * If "child" is valid object and this returns true, "root" is valid, too.
5307 bool css_is_ancestor(struct cgroup_subsys_state *child,
5308 const struct cgroup_subsys_state *root)
5310 struct css_id *child_id;
5311 struct css_id *root_id;
5313 child_id = rcu_dereference(child->id);
5316 root_id = rcu_dereference(root->id);
5319 if (child_id->depth < root_id->depth)
5321 if (child_id->stack[root_id->depth] != root_id->id)
5326 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
5328 struct css_id *id = rcu_dereference_protected(css->id, true);
5330 /* When this is called before css_id initialization, id can be NULL */
5334 BUG_ON(!ss->use_id);
5336 rcu_assign_pointer(id->css, NULL);
5337 rcu_assign_pointer(css->id, NULL);
5338 spin_lock(&ss->id_lock);
5339 idr_remove(&ss->idr, id->id);
5340 spin_unlock(&ss->id_lock);
5341 kfree_rcu(id, rcu_head);
5343 EXPORT_SYMBOL_GPL(free_css_id);
5346 * This is called by init or create(). Then, calls to this function are
5347 * always serialized (By cgroup_mutex() at create()).
5350 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
5352 struct css_id *newid;
5355 BUG_ON(!ss->use_id);
5357 size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
5358 newid = kzalloc(size, GFP_KERNEL);
5360 return ERR_PTR(-ENOMEM);
5362 idr_preload(GFP_KERNEL);
5363 spin_lock(&ss->id_lock);
5364 /* Don't use 0. allocates an ID of 1-65535 */
5365 ret = idr_alloc(&ss->idr, newid, 1, CSS_ID_MAX + 1, GFP_NOWAIT);
5366 spin_unlock(&ss->id_lock);
5369 /* Returns error when there are no free spaces for new ID.*/
5374 newid->depth = depth;
5378 return ERR_PTR(ret);
5382 static int __init_or_module cgroup_init_idr(struct cgroup_subsys *ss,
5383 struct cgroup_subsys_state *rootcss)
5385 struct css_id *newid;
5387 spin_lock_init(&ss->id_lock);
5390 newid = get_new_cssid(ss, 0);
5392 return PTR_ERR(newid);
5394 newid->stack[0] = newid->id;
5395 RCU_INIT_POINTER(newid->css, rootcss);
5396 RCU_INIT_POINTER(rootcss->id, newid);
5400 static int alloc_css_id(struct cgroup_subsys_state *child_css)
5402 struct cgroup_subsys_state *parent_css = css_parent(child_css);
5403 struct css_id *child_id, *parent_id;
5406 parent_id = rcu_dereference_protected(parent_css->id, true);
5407 depth = parent_id->depth + 1;
5409 child_id = get_new_cssid(child_css->ss, depth);
5410 if (IS_ERR(child_id))
5411 return PTR_ERR(child_id);
5413 for (i = 0; i < depth; i++)
5414 child_id->stack[i] = parent_id->stack[i];
5415 child_id->stack[depth] = child_id->id;
5417 * child_id->css pointer will be set after this cgroup is available
5418 * see cgroup_populate_dir()
5420 rcu_assign_pointer(child_css->id, child_id);
5426 * css_lookup - lookup css by id
5427 * @ss: cgroup subsys to be looked into.
5430 * Returns pointer to cgroup_subsys_state if there is valid one with id.
5431 * NULL if not. Should be called under rcu_read_lock()
5433 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
5435 struct css_id *cssid = NULL;
5437 BUG_ON(!ss->use_id);
5438 cssid = idr_find(&ss->idr, id);
5440 if (unlikely(!cssid))
5443 return rcu_dereference(cssid->css);
5445 EXPORT_SYMBOL_GPL(css_lookup);
5448 * css_from_dir - get corresponding css from the dentry of a cgroup dir
5449 * @dentry: directory dentry of interest
5450 * @ss: subsystem of interest
5452 * Must be called under RCU read lock. The caller is responsible for
5453 * pinning the returned css if it needs to be accessed outside the RCU
5456 struct cgroup_subsys_state *css_from_dir(struct dentry *dentry,
5457 struct cgroup_subsys *ss)
5459 struct cgroup *cgrp;
5461 WARN_ON_ONCE(!rcu_read_lock_held());
5463 /* is @dentry a cgroup dir? */
5464 if (!dentry->d_inode ||
5465 dentry->d_inode->i_op != &cgroup_dir_inode_operations)
5466 return ERR_PTR(-EBADF);
5468 cgrp = __d_cgrp(dentry);
5469 return cgroup_css(cgrp, ss) ?: ERR_PTR(-ENOENT);
5473 * css_from_id - lookup css by id
5474 * @id: the cgroup id
5475 * @ss: cgroup subsys to be looked into
5477 * Returns the css if there's valid one with @id, otherwise returns NULL.
5478 * Should be called under rcu_read_lock().
5480 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5482 struct cgroup *cgrp;
5484 rcu_lockdep_assert(rcu_read_lock_held() ||
5485 lockdep_is_held(&cgroup_mutex),
5486 "css_from_id() needs proper protection");
5488 cgrp = idr_find(&ss->root->cgroup_idr, id);
5490 return cgroup_css(cgrp, ss);
5494 #ifdef CONFIG_CGROUP_DEBUG
5495 static struct cgroup_subsys_state *
5496 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5498 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5501 return ERR_PTR(-ENOMEM);
5506 static void debug_css_free(struct cgroup_subsys_state *css)
5511 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5514 return cgroup_task_count(css->cgroup);
5517 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5520 return (u64)(unsigned long)current->cgroups;
5523 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5529 count = atomic_read(&task_css_set(current)->refcount);
5534 static int current_css_set_cg_links_read(struct cgroup_subsys_state *css,
5536 struct seq_file *seq)
5538 struct cgrp_cset_link *link;
5539 struct css_set *cset;
5541 read_lock(&css_set_lock);
5543 cset = rcu_dereference(current->cgroups);
5544 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5545 struct cgroup *c = link->cgrp;
5549 name = c->dentry->d_name.name;
5552 seq_printf(seq, "Root %d group %s\n",
5553 c->root->hierarchy_id, name);
5556 read_unlock(&css_set_lock);
5560 #define MAX_TASKS_SHOWN_PER_CSS 25
5561 static int cgroup_css_links_read(struct cgroup_subsys_state *css,
5562 struct cftype *cft, struct seq_file *seq)
5564 struct cgrp_cset_link *link;
5566 read_lock(&css_set_lock);
5567 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5568 struct css_set *cset = link->cset;
5569 struct task_struct *task;
5571 seq_printf(seq, "css_set %p\n", cset);
5572 list_for_each_entry(task, &cset->tasks, cg_list) {
5573 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5574 seq_puts(seq, " ...\n");
5577 seq_printf(seq, " task %d\n",
5578 task_pid_vnr(task));
5582 read_unlock(&css_set_lock);
5586 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5588 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
5591 static struct cftype debug_files[] = {
5593 .name = "taskcount",
5594 .read_u64 = debug_taskcount_read,
5598 .name = "current_css_set",
5599 .read_u64 = current_css_set_read,
5603 .name = "current_css_set_refcount",
5604 .read_u64 = current_css_set_refcount_read,
5608 .name = "current_css_set_cg_links",
5609 .read_seq_string = current_css_set_cg_links_read,
5613 .name = "cgroup_css_links",
5614 .read_seq_string = cgroup_css_links_read,
5618 .name = "releasable",
5619 .read_u64 = releasable_read,
5625 struct cgroup_subsys debug_subsys = {
5627 .css_alloc = debug_css_alloc,
5628 .css_free = debug_css_free,
5629 .subsys_id = debug_subsys_id,
5630 .base_cftypes = debug_files,
5632 #endif /* CONFIG_CGROUP_DEBUG */