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 * cgroup destruction makes heavy use of work items and there can be a lot
91 * of concurrent destructions. Use a separate workqueue so that cgroup
92 * destruction work items don't end up filling up max_active of system_wq
93 * which may lead to deadlock.
95 static struct workqueue_struct *cgroup_destroy_wq;
98 * Generate an array of cgroup subsystem pointers. At boot time, this is
99 * populated with the built in subsystems, and modular subsystems are
100 * registered after that. The mutable section of this array is protected by
103 #define SUBSYS(_x) [_x ## _subsys_id] = &_x ## _subsys,
104 #define IS_SUBSYS_ENABLED(option) IS_BUILTIN(option)
105 static struct cgroup_subsys *cgroup_subsys[CGROUP_SUBSYS_COUNT] = {
106 #include <linux/cgroup_subsys.h>
110 * The dummy hierarchy, reserved for the subsystems that are otherwise
111 * unattached - it never has more than a single cgroup, and all tasks are
112 * part of that cgroup.
114 static struct cgroupfs_root cgroup_dummy_root;
116 /* dummy_top is a shorthand for the dummy hierarchy's top cgroup */
117 static struct cgroup * const cgroup_dummy_top = &cgroup_dummy_root.top_cgroup;
120 * cgroupfs file entry, pointed to from leaf dentry->d_fsdata.
123 struct list_head node;
124 struct dentry *dentry;
126 struct cgroup_subsys_state *css;
129 struct simple_xattrs xattrs;
132 /* The list of hierarchy roots */
134 static LIST_HEAD(cgroup_roots);
135 static int cgroup_root_count;
138 * Hierarchy ID allocation and mapping. It follows the same exclusion
139 * rules as other root ops - both cgroup_mutex and cgroup_root_mutex for
140 * writes, either for reads.
142 static DEFINE_IDR(cgroup_hierarchy_idr);
144 static struct cgroup_name root_cgroup_name = { .name = "/" };
147 * Assign a monotonically increasing serial number to cgroups. It
148 * guarantees cgroups with bigger numbers are newer than those with smaller
149 * numbers. Also, as cgroups are always appended to the parent's
150 * ->children list, it guarantees that sibling cgroups are always sorted in
151 * the ascending serial number order on the list. Protected by
154 static u64 cgroup_serial_nr_next = 1;
156 /* This flag indicates whether tasks in the fork and exit paths should
157 * check for fork/exit handlers to call. This avoids us having to do
158 * extra work in the fork/exit path if none of the subsystems need to
161 static int need_forkexit_callback __read_mostly;
163 static struct cftype cgroup_base_files[];
165 static void cgroup_destroy_css_killed(struct cgroup *cgrp);
166 static int cgroup_destroy_locked(struct cgroup *cgrp);
167 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
171 * cgroup_css - obtain a cgroup's css for the specified subsystem
172 * @cgrp: the cgroup of interest
173 * @ss: the subsystem of interest (%NULL returns the dummy_css)
175 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
176 * function must be called either under cgroup_mutex or rcu_read_lock() and
177 * the caller is responsible for pinning the returned css if it wants to
178 * keep accessing it outside the said locks. This function may return
179 * %NULL if @cgrp doesn't have @subsys_id enabled.
181 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
182 struct cgroup_subsys *ss)
185 return rcu_dereference_check(cgrp->subsys[ss->subsys_id],
186 lockdep_is_held(&cgroup_mutex));
188 return &cgrp->dummy_css;
191 /* convenient tests for these bits */
192 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
194 return test_bit(CGRP_DEAD, &cgrp->flags);
198 * cgroup_is_descendant - test ancestry
199 * @cgrp: the cgroup to be tested
200 * @ancestor: possible ancestor of @cgrp
202 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
203 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
204 * and @ancestor are accessible.
206 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
209 if (cgrp == ancestor)
215 EXPORT_SYMBOL_GPL(cgroup_is_descendant);
217 static int cgroup_is_releasable(const struct cgroup *cgrp)
220 (1 << CGRP_RELEASABLE) |
221 (1 << CGRP_NOTIFY_ON_RELEASE);
222 return (cgrp->flags & bits) == bits;
225 static int notify_on_release(const struct cgroup *cgrp)
227 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
231 * for_each_subsys - iterate all loaded cgroup subsystems
232 * @ss: the iteration cursor
233 * @i: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
235 * Should be called under cgroup_mutex.
237 #define for_each_subsys(ss, i) \
238 for ((i) = 0; (i) < CGROUP_SUBSYS_COUNT; (i)++) \
239 if (({ lockdep_assert_held(&cgroup_mutex); \
240 !((ss) = cgroup_subsys[i]); })) { } \
244 * for_each_builtin_subsys - iterate all built-in cgroup subsystems
245 * @ss: the iteration cursor
246 * @i: the index of @ss, CGROUP_BUILTIN_SUBSYS_COUNT after reaching the end
248 * Bulit-in subsystems are always present and iteration itself doesn't
249 * require any synchronization.
251 #define for_each_builtin_subsys(ss, i) \
252 for ((i) = 0; (i) < CGROUP_BUILTIN_SUBSYS_COUNT && \
253 (((ss) = cgroup_subsys[i]) || true); (i)++)
255 /* iterate each subsystem attached to a hierarchy */
256 #define for_each_root_subsys(root, ss) \
257 list_for_each_entry((ss), &(root)->subsys_list, sibling)
259 /* iterate across the active hierarchies */
260 #define for_each_active_root(root) \
261 list_for_each_entry((root), &cgroup_roots, root_list)
263 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
265 return dentry->d_fsdata;
268 static inline struct cfent *__d_cfe(struct dentry *dentry)
270 return dentry->d_fsdata;
273 static inline struct cftype *__d_cft(struct dentry *dentry)
275 return __d_cfe(dentry)->type;
279 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
280 * @cgrp: the cgroup to be checked for liveness
282 * On success, returns true; the mutex should be later unlocked. On
283 * failure returns false with no lock held.
285 static bool cgroup_lock_live_group(struct cgroup *cgrp)
287 mutex_lock(&cgroup_mutex);
288 if (cgroup_is_dead(cgrp)) {
289 mutex_unlock(&cgroup_mutex);
295 /* the list of cgroups eligible for automatic release. Protected by
296 * release_list_lock */
297 static LIST_HEAD(release_list);
298 static DEFINE_RAW_SPINLOCK(release_list_lock);
299 static void cgroup_release_agent(struct work_struct *work);
300 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
301 static void check_for_release(struct cgroup *cgrp);
304 * A cgroup can be associated with multiple css_sets as different tasks may
305 * belong to different cgroups on different hierarchies. In the other
306 * direction, a css_set is naturally associated with multiple cgroups.
307 * This M:N relationship is represented by the following link structure
308 * which exists for each association and allows traversing the associations
311 struct cgrp_cset_link {
312 /* the cgroup and css_set this link associates */
314 struct css_set *cset;
316 /* list of cgrp_cset_links anchored at cgrp->cset_links */
317 struct list_head cset_link;
319 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
320 struct list_head cgrp_link;
323 /* The default css_set - used by init and its children prior to any
324 * hierarchies being mounted. It contains a pointer to the root state
325 * for each subsystem. Also used to anchor the list of css_sets. Not
326 * reference-counted, to improve performance when child cgroups
327 * haven't been created.
330 static struct css_set init_css_set;
331 static struct cgrp_cset_link init_cgrp_cset_link;
334 * css_set_lock protects the list of css_set objects, and the chain of
335 * tasks off each css_set. Nests outside task->alloc_lock due to
336 * css_task_iter_start().
338 static DEFINE_RWLOCK(css_set_lock);
339 static int css_set_count;
342 * hash table for cgroup groups. This improves the performance to find
343 * an existing css_set. This hash doesn't (currently) take into
344 * account cgroups in empty hierarchies.
346 #define CSS_SET_HASH_BITS 7
347 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
349 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
351 unsigned long key = 0UL;
352 struct cgroup_subsys *ss;
355 for_each_subsys(ss, i)
356 key += (unsigned long)css[i];
357 key = (key >> 16) ^ key;
363 * We don't maintain the lists running through each css_set to its task
364 * until after the first call to css_task_iter_start(). This reduces the
365 * fork()/exit() overhead for people who have cgroups compiled into their
366 * kernel but not actually in use.
368 static int use_task_css_set_links __read_mostly;
370 static void __put_css_set(struct css_set *cset, int taskexit)
372 struct cgrp_cset_link *link, *tmp_link;
375 * Ensure that the refcount doesn't hit zero while any readers
376 * can see it. Similar to atomic_dec_and_lock(), but for an
379 if (atomic_add_unless(&cset->refcount, -1, 1))
381 write_lock(&css_set_lock);
382 if (!atomic_dec_and_test(&cset->refcount)) {
383 write_unlock(&css_set_lock);
387 /* This css_set is dead. unlink it and release cgroup refcounts */
388 hash_del(&cset->hlist);
391 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
392 struct cgroup *cgrp = link->cgrp;
394 list_del(&link->cset_link);
395 list_del(&link->cgrp_link);
397 /* @cgrp can't go away while we're holding css_set_lock */
398 if (list_empty(&cgrp->cset_links) && notify_on_release(cgrp)) {
400 set_bit(CGRP_RELEASABLE, &cgrp->flags);
401 check_for_release(cgrp);
407 write_unlock(&css_set_lock);
408 kfree_rcu(cset, rcu_head);
412 * refcounted get/put for css_set objects
414 static inline void get_css_set(struct css_set *cset)
416 atomic_inc(&cset->refcount);
419 static inline void put_css_set(struct css_set *cset)
421 __put_css_set(cset, 0);
424 static inline void put_css_set_taskexit(struct css_set *cset)
426 __put_css_set(cset, 1);
430 * compare_css_sets - helper function for find_existing_css_set().
431 * @cset: candidate css_set being tested
432 * @old_cset: existing css_set for a task
433 * @new_cgrp: cgroup that's being entered by the task
434 * @template: desired set of css pointers in css_set (pre-calculated)
436 * Returns true if "cset" matches "old_cset" except for the hierarchy
437 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
439 static bool compare_css_sets(struct css_set *cset,
440 struct css_set *old_cset,
441 struct cgroup *new_cgrp,
442 struct cgroup_subsys_state *template[])
444 struct list_head *l1, *l2;
446 if (memcmp(template, cset->subsys, sizeof(cset->subsys))) {
447 /* Not all subsystems matched */
452 * Compare cgroup pointers in order to distinguish between
453 * different cgroups in heirarchies with no subsystems. We
454 * could get by with just this check alone (and skip the
455 * memcmp above) but on most setups the memcmp check will
456 * avoid the need for this more expensive check on almost all
460 l1 = &cset->cgrp_links;
461 l2 = &old_cset->cgrp_links;
463 struct cgrp_cset_link *link1, *link2;
464 struct cgroup *cgrp1, *cgrp2;
468 /* See if we reached the end - both lists are equal length. */
469 if (l1 == &cset->cgrp_links) {
470 BUG_ON(l2 != &old_cset->cgrp_links);
473 BUG_ON(l2 == &old_cset->cgrp_links);
475 /* Locate the cgroups associated with these links. */
476 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
477 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
480 /* Hierarchies should be linked in the same order. */
481 BUG_ON(cgrp1->root != cgrp2->root);
484 * If this hierarchy is the hierarchy of the cgroup
485 * that's changing, then we need to check that this
486 * css_set points to the new cgroup; if it's any other
487 * hierarchy, then this css_set should point to the
488 * same cgroup as the old css_set.
490 if (cgrp1->root == new_cgrp->root) {
491 if (cgrp1 != new_cgrp)
502 * find_existing_css_set - init css array and find the matching css_set
503 * @old_cset: the css_set that we're using before the cgroup transition
504 * @cgrp: the cgroup that we're moving into
505 * @template: out param for the new set of csses, should be clear on entry
507 static struct css_set *find_existing_css_set(struct css_set *old_cset,
509 struct cgroup_subsys_state *template[])
511 struct cgroupfs_root *root = cgrp->root;
512 struct cgroup_subsys *ss;
513 struct css_set *cset;
518 * Build the set of subsystem state objects that we want to see in the
519 * new css_set. while subsystems can change globally, the entries here
520 * won't change, so no need for locking.
522 for_each_subsys(ss, i) {
523 if (root->subsys_mask & (1UL << i)) {
524 /* Subsystem is in this hierarchy. So we want
525 * the subsystem state from the new
527 template[i] = cgroup_css(cgrp, ss);
529 /* Subsystem is not in this hierarchy, so we
530 * don't want to change the subsystem state */
531 template[i] = old_cset->subsys[i];
535 key = css_set_hash(template);
536 hash_for_each_possible(css_set_table, cset, hlist, key) {
537 if (!compare_css_sets(cset, old_cset, cgrp, template))
540 /* This css_set matches what we need */
544 /* No existing cgroup group matched */
548 static void free_cgrp_cset_links(struct list_head *links_to_free)
550 struct cgrp_cset_link *link, *tmp_link;
552 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
553 list_del(&link->cset_link);
559 * allocate_cgrp_cset_links - allocate cgrp_cset_links
560 * @count: the number of links to allocate
561 * @tmp_links: list_head the allocated links are put on
563 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
564 * through ->cset_link. Returns 0 on success or -errno.
566 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
568 struct cgrp_cset_link *link;
571 INIT_LIST_HEAD(tmp_links);
573 for (i = 0; i < count; i++) {
574 link = kzalloc(sizeof(*link), GFP_KERNEL);
576 free_cgrp_cset_links(tmp_links);
579 list_add(&link->cset_link, tmp_links);
585 * link_css_set - a helper function to link a css_set to a cgroup
586 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
587 * @cset: the css_set to be linked
588 * @cgrp: the destination cgroup
590 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
593 struct cgrp_cset_link *link;
595 BUG_ON(list_empty(tmp_links));
596 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
599 list_move(&link->cset_link, &cgrp->cset_links);
601 * Always add links to the tail of the list so that the list
602 * is sorted by order of hierarchy creation
604 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
608 * find_css_set - return a new css_set with one cgroup updated
609 * @old_cset: the baseline css_set
610 * @cgrp: the cgroup to be updated
612 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
613 * substituted into the appropriate hierarchy.
615 static struct css_set *find_css_set(struct css_set *old_cset,
618 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
619 struct css_set *cset;
620 struct list_head tmp_links;
621 struct cgrp_cset_link *link;
624 lockdep_assert_held(&cgroup_mutex);
626 /* First see if we already have a cgroup group that matches
628 read_lock(&css_set_lock);
629 cset = find_existing_css_set(old_cset, cgrp, template);
632 read_unlock(&css_set_lock);
637 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
641 /* Allocate all the cgrp_cset_link objects that we'll need */
642 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
647 atomic_set(&cset->refcount, 1);
648 INIT_LIST_HEAD(&cset->cgrp_links);
649 INIT_LIST_HEAD(&cset->tasks);
650 INIT_HLIST_NODE(&cset->hlist);
652 /* Copy the set of subsystem state objects generated in
653 * find_existing_css_set() */
654 memcpy(cset->subsys, template, sizeof(cset->subsys));
656 write_lock(&css_set_lock);
657 /* Add reference counts and links from the new css_set. */
658 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
659 struct cgroup *c = link->cgrp;
661 if (c->root == cgrp->root)
663 link_css_set(&tmp_links, cset, c);
666 BUG_ON(!list_empty(&tmp_links));
670 /* Add this cgroup group to the hash table */
671 key = css_set_hash(cset->subsys);
672 hash_add(css_set_table, &cset->hlist, key);
674 write_unlock(&css_set_lock);
680 * Return the cgroup for "task" from the given hierarchy. Must be
681 * called with cgroup_mutex held.
683 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
684 struct cgroupfs_root *root)
686 struct css_set *cset;
687 struct cgroup *res = NULL;
689 BUG_ON(!mutex_is_locked(&cgroup_mutex));
690 read_lock(&css_set_lock);
692 * No need to lock the task - since we hold cgroup_mutex the
693 * task can't change groups, so the only thing that can happen
694 * is that it exits and its css is set back to init_css_set.
696 cset = task_css_set(task);
697 if (cset == &init_css_set) {
698 res = &root->top_cgroup;
700 struct cgrp_cset_link *link;
702 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
703 struct cgroup *c = link->cgrp;
705 if (c->root == root) {
711 read_unlock(&css_set_lock);
717 * There is one global cgroup mutex. We also require taking
718 * task_lock() when dereferencing a task's cgroup subsys pointers.
719 * See "The task_lock() exception", at the end of this comment.
721 * A task must hold cgroup_mutex to modify cgroups.
723 * Any task can increment and decrement the count field without lock.
724 * So in general, code holding cgroup_mutex can't rely on the count
725 * field not changing. However, if the count goes to zero, then only
726 * cgroup_attach_task() can increment it again. Because a count of zero
727 * means that no tasks are currently attached, therefore there is no
728 * way a task attached to that cgroup can fork (the other way to
729 * increment the count). So code holding cgroup_mutex can safely
730 * assume that if the count is zero, it will stay zero. Similarly, if
731 * a task holds cgroup_mutex on a cgroup with zero count, it
732 * knows that the cgroup won't be removed, as cgroup_rmdir()
735 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
736 * (usually) take cgroup_mutex. These are the two most performance
737 * critical pieces of code here. The exception occurs on cgroup_exit(),
738 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
739 * is taken, and if the cgroup count is zero, a usermode call made
740 * to the release agent with the name of the cgroup (path relative to
741 * the root of cgroup file system) as the argument.
743 * A cgroup can only be deleted if both its 'count' of using tasks
744 * is zero, and its list of 'children' cgroups is empty. Since all
745 * tasks in the system use _some_ cgroup, and since there is always at
746 * least one task in the system (init, pid == 1), therefore, top_cgroup
747 * always has either children cgroups and/or using tasks. So we don't
748 * need a special hack to ensure that top_cgroup cannot be deleted.
750 * The task_lock() exception
752 * The need for this exception arises from the action of
753 * cgroup_attach_task(), which overwrites one task's cgroup pointer with
754 * another. It does so using cgroup_mutex, however there are
755 * several performance critical places that need to reference
756 * task->cgroup without the expense of grabbing a system global
757 * mutex. Therefore except as noted below, when dereferencing or, as
758 * in cgroup_attach_task(), modifying a task's cgroup pointer we use
759 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
760 * the task_struct routinely used for such matters.
762 * P.S. One more locking exception. RCU is used to guard the
763 * update of a tasks cgroup pointer by cgroup_attach_task()
767 * A couple of forward declarations required, due to cyclic reference loop:
768 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
769 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
773 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode);
774 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
775 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask);
776 static const struct inode_operations cgroup_dir_inode_operations;
777 static const struct file_operations proc_cgroupstats_operations;
779 static struct backing_dev_info cgroup_backing_dev_info = {
781 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
784 static struct inode *cgroup_new_inode(umode_t mode, struct super_block *sb)
786 struct inode *inode = new_inode(sb);
789 inode->i_ino = get_next_ino();
790 inode->i_mode = mode;
791 inode->i_uid = current_fsuid();
792 inode->i_gid = current_fsgid();
793 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
794 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
799 static struct cgroup_name *cgroup_alloc_name(struct dentry *dentry)
801 struct cgroup_name *name;
803 name = kmalloc(sizeof(*name) + dentry->d_name.len + 1, GFP_KERNEL);
806 strcpy(name->name, dentry->d_name.name);
810 static void cgroup_free_fn(struct work_struct *work)
812 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
814 mutex_lock(&cgroup_mutex);
815 cgrp->root->number_of_cgroups--;
816 mutex_unlock(&cgroup_mutex);
819 * We get a ref to the parent's dentry, and put the ref when
820 * this cgroup is being freed, so it's guaranteed that the
821 * parent won't be destroyed before its children.
823 dput(cgrp->parent->dentry);
826 * Drop the active superblock reference that we took when we
827 * created the cgroup. This will free cgrp->root, if we are
828 * holding the last reference to @sb.
830 deactivate_super(cgrp->root->sb);
833 * if we're getting rid of the cgroup, refcount should ensure
834 * that there are no pidlists left.
836 BUG_ON(!list_empty(&cgrp->pidlists));
838 simple_xattrs_free(&cgrp->xattrs);
840 kfree(rcu_dereference_raw(cgrp->name));
844 static void cgroup_free_rcu(struct rcu_head *head)
846 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
848 INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
849 queue_work(cgroup_destroy_wq, &cgrp->destroy_work);
852 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
854 /* is dentry a directory ? if so, kfree() associated cgroup */
855 if (S_ISDIR(inode->i_mode)) {
856 struct cgroup *cgrp = dentry->d_fsdata;
858 BUG_ON(!(cgroup_is_dead(cgrp)));
859 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
861 struct cfent *cfe = __d_cfe(dentry);
862 struct cgroup *cgrp = dentry->d_parent->d_fsdata;
864 WARN_ONCE(!list_empty(&cfe->node) &&
865 cgrp != &cgrp->root->top_cgroup,
866 "cfe still linked for %s\n", cfe->type->name);
867 simple_xattrs_free(&cfe->xattrs);
873 static void remove_dir(struct dentry *d)
875 struct dentry *parent = dget(d->d_parent);
878 simple_rmdir(parent->d_inode, d);
882 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
886 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
887 lockdep_assert_held(&cgroup_mutex);
890 * If we're doing cleanup due to failure of cgroup_create(),
891 * the corresponding @cfe may not exist.
893 list_for_each_entry(cfe, &cgrp->files, node) {
894 struct dentry *d = cfe->dentry;
896 if (cft && cfe->type != cft)
901 simple_unlink(cgrp->dentry->d_inode, d);
902 list_del_init(&cfe->node);
910 * cgroup_clear_dir - remove subsys files in a cgroup directory
911 * @cgrp: target cgroup
912 * @subsys_mask: mask of the subsystem ids whose files should be removed
914 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned long subsys_mask)
916 struct cgroup_subsys *ss;
919 for_each_subsys(ss, i) {
920 struct cftype_set *set;
922 if (!test_bit(i, &subsys_mask))
924 list_for_each_entry(set, &ss->cftsets, node)
925 cgroup_addrm_files(cgrp, set->cfts, false);
930 * NOTE : the dentry must have been dget()'ed
932 static void cgroup_d_remove_dir(struct dentry *dentry)
934 struct dentry *parent;
936 parent = dentry->d_parent;
937 spin_lock(&parent->d_lock);
938 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
939 list_del_init(&dentry->d_u.d_child);
940 spin_unlock(&dentry->d_lock);
941 spin_unlock(&parent->d_lock);
946 * Call with cgroup_mutex held. Drops reference counts on modules, including
947 * any duplicate ones that parse_cgroupfs_options took. If this function
948 * returns an error, no reference counts are touched.
950 static int rebind_subsystems(struct cgroupfs_root *root,
951 unsigned long added_mask, unsigned removed_mask)
953 struct cgroup *cgrp = &root->top_cgroup;
954 struct cgroup_subsys *ss;
955 unsigned long pinned = 0;
958 BUG_ON(!mutex_is_locked(&cgroup_mutex));
959 BUG_ON(!mutex_is_locked(&cgroup_root_mutex));
961 /* Check that any added subsystems are currently free */
962 for_each_subsys(ss, i) {
963 if (!(added_mask & (1 << i)))
966 /* is the subsystem mounted elsewhere? */
967 if (ss->root != &cgroup_dummy_root) {
973 if (!try_module_get(ss->module)) {
980 /* subsys could be missing if unloaded between parsing and here */
981 if (added_mask != pinned) {
986 ret = cgroup_populate_dir(cgrp, added_mask);
991 * Nothing can fail from this point on. Remove files for the
992 * removed subsystems and rebind each subsystem.
994 cgroup_clear_dir(cgrp, removed_mask);
996 for_each_subsys(ss, i) {
997 unsigned long bit = 1UL << i;
999 if (bit & added_mask) {
1000 /* We're binding this subsystem to this hierarchy */
1001 BUG_ON(cgroup_css(cgrp, ss));
1002 BUG_ON(!cgroup_css(cgroup_dummy_top, ss));
1003 BUG_ON(cgroup_css(cgroup_dummy_top, ss)->cgroup != cgroup_dummy_top);
1005 rcu_assign_pointer(cgrp->subsys[i],
1006 cgroup_css(cgroup_dummy_top, ss));
1007 cgroup_css(cgrp, ss)->cgroup = cgrp;
1009 list_move(&ss->sibling, &root->subsys_list);
1012 ss->bind(cgroup_css(cgrp, ss));
1014 /* refcount was already taken, and we're keeping it */
1015 root->subsys_mask |= bit;
1016 } else if (bit & removed_mask) {
1017 /* We're removing this subsystem */
1018 BUG_ON(cgroup_css(cgrp, ss) != cgroup_css(cgroup_dummy_top, ss));
1019 BUG_ON(cgroup_css(cgrp, ss)->cgroup != cgrp);
1022 ss->bind(cgroup_css(cgroup_dummy_top, ss));
1024 cgroup_css(cgroup_dummy_top, ss)->cgroup = cgroup_dummy_top;
1025 RCU_INIT_POINTER(cgrp->subsys[i], NULL);
1027 cgroup_subsys[i]->root = &cgroup_dummy_root;
1028 list_move(&ss->sibling, &cgroup_dummy_root.subsys_list);
1030 /* subsystem is now free - drop reference on module */
1031 module_put(ss->module);
1032 root->subsys_mask &= ~bit;
1037 * Mark @root has finished binding subsystems. @root->subsys_mask
1038 * now matches the bound subsystems.
1040 root->flags |= CGRP_ROOT_SUBSYS_BOUND;
1045 for_each_subsys(ss, i)
1046 if (pinned & (1 << i))
1047 module_put(ss->module);
1051 static int cgroup_show_options(struct seq_file *seq, struct dentry *dentry)
1053 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
1054 struct cgroup_subsys *ss;
1056 mutex_lock(&cgroup_root_mutex);
1057 for_each_root_subsys(root, ss)
1058 seq_printf(seq, ",%s", ss->name);
1059 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1060 seq_puts(seq, ",sane_behavior");
1061 if (root->flags & CGRP_ROOT_NOPREFIX)
1062 seq_puts(seq, ",noprefix");
1063 if (root->flags & CGRP_ROOT_XATTR)
1064 seq_puts(seq, ",xattr");
1065 if (strlen(root->release_agent_path))
1066 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1067 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1068 seq_puts(seq, ",clone_children");
1069 if (strlen(root->name))
1070 seq_printf(seq, ",name=%s", root->name);
1071 mutex_unlock(&cgroup_root_mutex);
1075 struct cgroup_sb_opts {
1076 unsigned long subsys_mask;
1077 unsigned long flags;
1078 char *release_agent;
1079 bool cpuset_clone_children;
1081 /* User explicitly requested empty subsystem */
1084 struct cgroupfs_root *new_root;
1089 * Convert a hierarchy specifier into a bitmask of subsystems and
1090 * flags. Call with cgroup_mutex held to protect the cgroup_subsys[]
1091 * array. This function takes refcounts on subsystems to be used, unless it
1092 * returns error, in which case no refcounts are taken.
1094 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1096 char *token, *o = data;
1097 bool all_ss = false, one_ss = false;
1098 unsigned long mask = (unsigned long)-1;
1099 struct cgroup_subsys *ss;
1102 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1104 #ifdef CONFIG_CPUSETS
1105 mask = ~(1UL << cpuset_subsys_id);
1108 memset(opts, 0, sizeof(*opts));
1110 while ((token = strsep(&o, ",")) != NULL) {
1113 if (!strcmp(token, "none")) {
1114 /* Explicitly have no subsystems */
1118 if (!strcmp(token, "all")) {
1119 /* Mutually exclusive option 'all' + subsystem name */
1125 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1126 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1129 if (!strcmp(token, "noprefix")) {
1130 opts->flags |= CGRP_ROOT_NOPREFIX;
1133 if (!strcmp(token, "clone_children")) {
1134 opts->cpuset_clone_children = true;
1137 if (!strcmp(token, "xattr")) {
1138 opts->flags |= CGRP_ROOT_XATTR;
1141 if (!strncmp(token, "release_agent=", 14)) {
1142 /* Specifying two release agents is forbidden */
1143 if (opts->release_agent)
1145 opts->release_agent =
1146 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1147 if (!opts->release_agent)
1151 if (!strncmp(token, "name=", 5)) {
1152 const char *name = token + 5;
1153 /* Can't specify an empty name */
1156 /* Must match [\w.-]+ */
1157 for (i = 0; i < strlen(name); i++) {
1161 if ((c == '.') || (c == '-') || (c == '_'))
1165 /* Specifying two names is forbidden */
1168 opts->name = kstrndup(name,
1169 MAX_CGROUP_ROOT_NAMELEN - 1,
1177 for_each_subsys(ss, i) {
1178 if (strcmp(token, ss->name))
1183 /* Mutually exclusive option 'all' + subsystem name */
1186 set_bit(i, &opts->subsys_mask);
1191 if (i == CGROUP_SUBSYS_COUNT)
1196 * If the 'all' option was specified select all the subsystems,
1197 * otherwise if 'none', 'name=' and a subsystem name options
1198 * were not specified, let's default to 'all'
1200 if (all_ss || (!one_ss && !opts->none && !opts->name))
1201 for_each_subsys(ss, i)
1203 set_bit(i, &opts->subsys_mask);
1205 /* Consistency checks */
1207 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1208 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1210 if (opts->flags & CGRP_ROOT_NOPREFIX) {
1211 pr_err("cgroup: sane_behavior: noprefix is not allowed\n");
1215 if (opts->cpuset_clone_children) {
1216 pr_err("cgroup: sane_behavior: clone_children is not allowed\n");
1222 * Option noprefix was introduced just for backward compatibility
1223 * with the old cpuset, so we allow noprefix only if mounting just
1224 * the cpuset subsystem.
1226 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1230 /* Can't specify "none" and some subsystems */
1231 if (opts->subsys_mask && opts->none)
1235 * We either have to specify by name or by subsystems. (So all
1236 * empty hierarchies must have a name).
1238 if (!opts->subsys_mask && !opts->name)
1244 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1247 struct cgroupfs_root *root = sb->s_fs_info;
1248 struct cgroup *cgrp = &root->top_cgroup;
1249 struct cgroup_sb_opts opts;
1250 unsigned long added_mask, removed_mask;
1252 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1253 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1257 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1258 mutex_lock(&cgroup_mutex);
1259 mutex_lock(&cgroup_root_mutex);
1261 /* See what subsystems are wanted */
1262 ret = parse_cgroupfs_options(data, &opts);
1266 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1267 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1268 task_tgid_nr(current), current->comm);
1270 added_mask = opts.subsys_mask & ~root->subsys_mask;
1271 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1273 /* Don't allow flags or name to change at remount */
1274 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1275 (opts.name && strcmp(opts.name, root->name))) {
1276 pr_err("cgroup: option or name mismatch, new: 0x%lx \"%s\", old: 0x%lx \"%s\"\n",
1277 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1278 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1283 /* remounting is not allowed for populated hierarchies */
1284 if (root->number_of_cgroups > 1) {
1289 ret = rebind_subsystems(root, added_mask, removed_mask);
1293 if (opts.release_agent)
1294 strcpy(root->release_agent_path, opts.release_agent);
1296 kfree(opts.release_agent);
1298 mutex_unlock(&cgroup_root_mutex);
1299 mutex_unlock(&cgroup_mutex);
1300 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1304 static const struct super_operations cgroup_ops = {
1305 .statfs = simple_statfs,
1306 .drop_inode = generic_delete_inode,
1307 .show_options = cgroup_show_options,
1308 .remount_fs = cgroup_remount,
1311 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1313 INIT_LIST_HEAD(&cgrp->sibling);
1314 INIT_LIST_HEAD(&cgrp->children);
1315 INIT_LIST_HEAD(&cgrp->files);
1316 INIT_LIST_HEAD(&cgrp->cset_links);
1317 INIT_LIST_HEAD(&cgrp->release_list);
1318 INIT_LIST_HEAD(&cgrp->pidlists);
1319 mutex_init(&cgrp->pidlist_mutex);
1320 cgrp->dummy_css.cgroup = cgrp;
1321 simple_xattrs_init(&cgrp->xattrs);
1324 static void init_cgroup_root(struct cgroupfs_root *root)
1326 struct cgroup *cgrp = &root->top_cgroup;
1328 INIT_LIST_HEAD(&root->subsys_list);
1329 INIT_LIST_HEAD(&root->root_list);
1330 root->number_of_cgroups = 1;
1332 RCU_INIT_POINTER(cgrp->name, &root_cgroup_name);
1333 init_cgroup_housekeeping(cgrp);
1334 idr_init(&root->cgroup_idr);
1337 static int cgroup_init_root_id(struct cgroupfs_root *root, int start, int end)
1341 lockdep_assert_held(&cgroup_mutex);
1342 lockdep_assert_held(&cgroup_root_mutex);
1344 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, start, end,
1349 root->hierarchy_id = id;
1353 static void cgroup_exit_root_id(struct cgroupfs_root *root)
1355 lockdep_assert_held(&cgroup_mutex);
1356 lockdep_assert_held(&cgroup_root_mutex);
1358 if (root->hierarchy_id) {
1359 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1360 root->hierarchy_id = 0;
1364 static int cgroup_test_super(struct super_block *sb, void *data)
1366 struct cgroup_sb_opts *opts = data;
1367 struct cgroupfs_root *root = sb->s_fs_info;
1369 /* If we asked for a name then it must match */
1370 if (opts->name && strcmp(opts->name, root->name))
1374 * If we asked for subsystems (or explicitly for no
1375 * subsystems) then they must match
1377 if ((opts->subsys_mask || opts->none)
1378 && (opts->subsys_mask != root->subsys_mask))
1384 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1386 struct cgroupfs_root *root;
1388 if (!opts->subsys_mask && !opts->none)
1391 root = kzalloc(sizeof(*root), GFP_KERNEL);
1393 return ERR_PTR(-ENOMEM);
1395 init_cgroup_root(root);
1398 * We need to set @root->subsys_mask now so that @root can be
1399 * matched by cgroup_test_super() before it finishes
1400 * initialization; otherwise, competing mounts with the same
1401 * options may try to bind the same subsystems instead of waiting
1402 * for the first one leading to unexpected mount errors.
1403 * SUBSYS_BOUND will be set once actual binding is complete.
1405 root->subsys_mask = opts->subsys_mask;
1406 root->flags = opts->flags;
1407 if (opts->release_agent)
1408 strcpy(root->release_agent_path, opts->release_agent);
1410 strcpy(root->name, opts->name);
1411 if (opts->cpuset_clone_children)
1412 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1416 static void cgroup_free_root(struct cgroupfs_root *root)
1419 /* hierarhcy ID shoulid already have been released */
1420 WARN_ON_ONCE(root->hierarchy_id);
1422 idr_destroy(&root->cgroup_idr);
1427 static int cgroup_set_super(struct super_block *sb, void *data)
1430 struct cgroup_sb_opts *opts = data;
1432 /* If we don't have a new root, we can't set up a new sb */
1433 if (!opts->new_root)
1436 BUG_ON(!opts->subsys_mask && !opts->none);
1438 ret = set_anon_super(sb, NULL);
1442 sb->s_fs_info = opts->new_root;
1443 opts->new_root->sb = sb;
1445 sb->s_blocksize = PAGE_CACHE_SIZE;
1446 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1447 sb->s_magic = CGROUP_SUPER_MAGIC;
1448 sb->s_op = &cgroup_ops;
1453 static int cgroup_get_rootdir(struct super_block *sb)
1455 static const struct dentry_operations cgroup_dops = {
1456 .d_iput = cgroup_diput,
1457 .d_delete = always_delete_dentry,
1460 struct inode *inode =
1461 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1466 inode->i_fop = &simple_dir_operations;
1467 inode->i_op = &cgroup_dir_inode_operations;
1468 /* directories start off with i_nlink == 2 (for "." entry) */
1470 sb->s_root = d_make_root(inode);
1473 /* for everything else we want ->d_op set */
1474 sb->s_d_op = &cgroup_dops;
1478 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1479 int flags, const char *unused_dev_name,
1482 struct cgroup_sb_opts opts;
1483 struct cgroupfs_root *root;
1485 struct super_block *sb;
1486 struct cgroupfs_root *new_root;
1487 struct list_head tmp_links;
1488 struct inode *inode;
1489 const struct cred *cred;
1491 /* First find the desired set of subsystems */
1492 mutex_lock(&cgroup_mutex);
1493 ret = parse_cgroupfs_options(data, &opts);
1494 mutex_unlock(&cgroup_mutex);
1499 * Allocate a new cgroup root. We may not need it if we're
1500 * reusing an existing hierarchy.
1502 new_root = cgroup_root_from_opts(&opts);
1503 if (IS_ERR(new_root)) {
1504 ret = PTR_ERR(new_root);
1507 opts.new_root = new_root;
1509 /* Locate an existing or new sb for this hierarchy */
1510 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1513 cgroup_free_root(opts.new_root);
1517 root = sb->s_fs_info;
1519 if (root == opts.new_root) {
1520 /* We used the new root structure, so this is a new hierarchy */
1521 struct cgroup *root_cgrp = &root->top_cgroup;
1522 struct cgroupfs_root *existing_root;
1524 struct css_set *cset;
1526 BUG_ON(sb->s_root != NULL);
1528 ret = cgroup_get_rootdir(sb);
1530 goto drop_new_super;
1531 inode = sb->s_root->d_inode;
1533 mutex_lock(&inode->i_mutex);
1534 mutex_lock(&cgroup_mutex);
1535 mutex_lock(&cgroup_root_mutex);
1537 root_cgrp->id = idr_alloc(&root->cgroup_idr, root_cgrp,
1539 if (root_cgrp->id < 0)
1542 /* Check for name clashes with existing mounts */
1544 if (strlen(root->name))
1545 for_each_active_root(existing_root)
1546 if (!strcmp(existing_root->name, root->name))
1550 * We're accessing css_set_count without locking
1551 * css_set_lock here, but that's OK - it can only be
1552 * increased by someone holding cgroup_lock, and
1553 * that's us. The worst that can happen is that we
1554 * have some link structures left over
1556 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1560 /* ID 0 is reserved for dummy root, 1 for unified hierarchy */
1561 ret = cgroup_init_root_id(root, 2, 0);
1565 sb->s_root->d_fsdata = root_cgrp;
1566 root_cgrp->dentry = sb->s_root;
1569 * We're inside get_sb() and will call lookup_one_len() to
1570 * create the root files, which doesn't work if SELinux is
1571 * in use. The following cred dancing somehow works around
1572 * it. See 2ce9738ba ("cgroupfs: use init_cred when
1573 * populating new cgroupfs mount") for more details.
1575 cred = override_creds(&init_cred);
1577 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1581 ret = rebind_subsystems(root, root->subsys_mask, 0);
1588 * There must be no failure case after here, since rebinding
1589 * takes care of subsystems' refcounts, which are explicitly
1590 * dropped in the failure exit path.
1593 list_add(&root->root_list, &cgroup_roots);
1594 cgroup_root_count++;
1596 /* Link the top cgroup in this hierarchy into all
1597 * the css_set objects */
1598 write_lock(&css_set_lock);
1599 hash_for_each(css_set_table, i, cset, hlist)
1600 link_css_set(&tmp_links, cset, root_cgrp);
1601 write_unlock(&css_set_lock);
1603 free_cgrp_cset_links(&tmp_links);
1605 BUG_ON(!list_empty(&root_cgrp->children));
1606 BUG_ON(root->number_of_cgroups != 1);
1608 mutex_unlock(&cgroup_root_mutex);
1609 mutex_unlock(&cgroup_mutex);
1610 mutex_unlock(&inode->i_mutex);
1613 * We re-used an existing hierarchy - the new root (if
1614 * any) is not needed
1616 cgroup_free_root(opts.new_root);
1618 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1619 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1620 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1622 goto drop_new_super;
1624 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1629 kfree(opts.release_agent);
1631 return dget(sb->s_root);
1634 free_cgrp_cset_links(&tmp_links);
1635 cgroup_addrm_files(&root->top_cgroup, cgroup_base_files, false);
1638 cgroup_exit_root_id(root);
1639 mutex_unlock(&cgroup_root_mutex);
1640 mutex_unlock(&cgroup_mutex);
1641 mutex_unlock(&inode->i_mutex);
1643 deactivate_locked_super(sb);
1645 kfree(opts.release_agent);
1647 return ERR_PTR(ret);
1650 static void cgroup_kill_sb(struct super_block *sb) {
1651 struct cgroupfs_root *root = sb->s_fs_info;
1652 struct cgroup *cgrp = &root->top_cgroup;
1653 struct cgrp_cset_link *link, *tmp_link;
1658 BUG_ON(root->number_of_cgroups != 1);
1659 BUG_ON(!list_empty(&cgrp->children));
1661 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1662 mutex_lock(&cgroup_mutex);
1663 mutex_lock(&cgroup_root_mutex);
1665 /* Rebind all subsystems back to the default hierarchy */
1666 if (root->flags & CGRP_ROOT_SUBSYS_BOUND) {
1667 ret = rebind_subsystems(root, 0, root->subsys_mask);
1668 /* Shouldn't be able to fail ... */
1673 * Release all the links from cset_links to this hierarchy's
1676 write_lock(&css_set_lock);
1678 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1679 list_del(&link->cset_link);
1680 list_del(&link->cgrp_link);
1683 write_unlock(&css_set_lock);
1685 if (!list_empty(&root->root_list)) {
1686 list_del(&root->root_list);
1687 cgroup_root_count--;
1690 cgroup_exit_root_id(root);
1692 mutex_unlock(&cgroup_root_mutex);
1693 mutex_unlock(&cgroup_mutex);
1694 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1696 simple_xattrs_free(&cgrp->xattrs);
1698 kill_litter_super(sb);
1699 cgroup_free_root(root);
1702 static struct file_system_type cgroup_fs_type = {
1704 .mount = cgroup_mount,
1705 .kill_sb = cgroup_kill_sb,
1708 static struct kobject *cgroup_kobj;
1711 * cgroup_path - generate the path of a cgroup
1712 * @cgrp: the cgroup in question
1713 * @buf: the buffer to write the path into
1714 * @buflen: the length of the buffer
1716 * Writes path of cgroup into buf. Returns 0 on success, -errno on error.
1718 * We can't generate cgroup path using dentry->d_name, as accessing
1719 * dentry->name must be protected by irq-unsafe dentry->d_lock or parent
1720 * inode's i_mutex, while on the other hand cgroup_path() can be called
1721 * with some irq-safe spinlocks held.
1723 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1725 int ret = -ENAMETOOLONG;
1728 if (!cgrp->parent) {
1729 if (strlcpy(buf, "/", buflen) >= buflen)
1730 return -ENAMETOOLONG;
1734 start = buf + buflen - 1;
1739 const char *name = cgroup_name(cgrp);
1743 if ((start -= len) < buf)
1745 memcpy(start, name, len);
1751 cgrp = cgrp->parent;
1752 } while (cgrp->parent);
1754 memmove(buf, start, buf + buflen - start);
1759 EXPORT_SYMBOL_GPL(cgroup_path);
1762 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1763 * @task: target task
1764 * @buf: the buffer to write the path into
1765 * @buflen: the length of the buffer
1767 * Determine @task's cgroup on the first (the one with the lowest non-zero
1768 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1769 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1770 * cgroup controller callbacks.
1772 * Returns 0 on success, fails with -%ENAMETOOLONG if @buflen is too short.
1774 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1776 struct cgroupfs_root *root;
1777 struct cgroup *cgrp;
1778 int hierarchy_id = 1, ret = 0;
1781 return -ENAMETOOLONG;
1783 mutex_lock(&cgroup_mutex);
1785 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1788 cgrp = task_cgroup_from_root(task, root);
1789 ret = cgroup_path(cgrp, buf, buflen);
1791 /* if no hierarchy exists, everyone is in "/" */
1792 memcpy(buf, "/", 2);
1795 mutex_unlock(&cgroup_mutex);
1798 EXPORT_SYMBOL_GPL(task_cgroup_path);
1801 * Control Group taskset
1803 struct task_and_cgroup {
1804 struct task_struct *task;
1805 struct cgroup *cgrp;
1806 struct css_set *cset;
1809 struct cgroup_taskset {
1810 struct task_and_cgroup single;
1811 struct flex_array *tc_array;
1814 struct cgroup *cur_cgrp;
1818 * cgroup_taskset_first - reset taskset and return the first task
1819 * @tset: taskset of interest
1821 * @tset iteration is initialized and the first task is returned.
1823 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1825 if (tset->tc_array) {
1827 return cgroup_taskset_next(tset);
1829 tset->cur_cgrp = tset->single.cgrp;
1830 return tset->single.task;
1833 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1836 * cgroup_taskset_next - iterate to the next task in taskset
1837 * @tset: taskset of interest
1839 * Return the next task in @tset. Iteration must have been initialized
1840 * with cgroup_taskset_first().
1842 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1844 struct task_and_cgroup *tc;
1846 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1849 tc = flex_array_get(tset->tc_array, tset->idx++);
1850 tset->cur_cgrp = tc->cgrp;
1853 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1856 * cgroup_taskset_cur_css - return the matching css for the current task
1857 * @tset: taskset of interest
1858 * @subsys_id: the ID of the target subsystem
1860 * Return the css for the current (last returned) task of @tset for
1861 * subsystem specified by @subsys_id. This function must be preceded by
1862 * either cgroup_taskset_first() or cgroup_taskset_next().
1864 struct cgroup_subsys_state *cgroup_taskset_cur_css(struct cgroup_taskset *tset,
1867 return cgroup_css(tset->cur_cgrp, cgroup_subsys[subsys_id]);
1869 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_css);
1872 * cgroup_taskset_size - return the number of tasks in taskset
1873 * @tset: taskset of interest
1875 int cgroup_taskset_size(struct cgroup_taskset *tset)
1877 return tset->tc_array ? tset->tc_array_len : 1;
1879 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1883 * cgroup_task_migrate - move a task from one cgroup to another.
1885 * Must be called with cgroup_mutex and threadgroup locked.
1887 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1888 struct task_struct *tsk,
1889 struct css_set *new_cset)
1891 struct css_set *old_cset;
1894 * We are synchronized through threadgroup_lock() against PF_EXITING
1895 * setting such that we can't race against cgroup_exit() changing the
1896 * css_set to init_css_set and dropping the old one.
1898 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1899 old_cset = task_css_set(tsk);
1902 rcu_assign_pointer(tsk->cgroups, new_cset);
1905 /* Update the css_set linked lists if we're using them */
1906 write_lock(&css_set_lock);
1907 if (!list_empty(&tsk->cg_list))
1908 list_move(&tsk->cg_list, &new_cset->tasks);
1909 write_unlock(&css_set_lock);
1912 * We just gained a reference on old_cset by taking it from the
1913 * task. As trading it for new_cset is protected by cgroup_mutex,
1914 * we're safe to drop it here; it will be freed under RCU.
1916 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1917 put_css_set(old_cset);
1921 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1922 * @cgrp: the cgroup to attach to
1923 * @tsk: the task or the leader of the threadgroup to be attached
1924 * @threadgroup: attach the whole threadgroup?
1926 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
1927 * task_lock of @tsk or each thread in the threadgroup individually in turn.
1929 static int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk,
1932 int retval, i, group_size;
1933 struct cgroup_subsys *ss, *failed_ss = NULL;
1934 struct cgroupfs_root *root = cgrp->root;
1935 /* threadgroup list cursor and array */
1936 struct task_struct *leader = tsk;
1937 struct task_and_cgroup *tc;
1938 struct flex_array *group;
1939 struct cgroup_taskset tset = { };
1942 * step 0: in order to do expensive, possibly blocking operations for
1943 * every thread, we cannot iterate the thread group list, since it needs
1944 * rcu or tasklist locked. instead, build an array of all threads in the
1945 * group - group_rwsem prevents new threads from appearing, and if
1946 * threads exit, this will just be an over-estimate.
1949 group_size = get_nr_threads(tsk);
1952 /* flex_array supports very large thread-groups better than kmalloc. */
1953 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
1956 /* pre-allocate to guarantee space while iterating in rcu read-side. */
1957 retval = flex_array_prealloc(group, 0, group_size, GFP_KERNEL);
1959 goto out_free_group_list;
1963 * Prevent freeing of tasks while we take a snapshot. Tasks that are
1964 * already PF_EXITING could be freed from underneath us unless we
1965 * take an rcu_read_lock.
1969 struct task_and_cgroup ent;
1971 /* @tsk either already exited or can't exit until the end */
1972 if (tsk->flags & PF_EXITING)
1975 /* as per above, nr_threads may decrease, but not increase. */
1976 BUG_ON(i >= group_size);
1978 ent.cgrp = task_cgroup_from_root(tsk, root);
1979 /* nothing to do if this task is already in the cgroup */
1980 if (ent.cgrp == cgrp)
1983 * saying GFP_ATOMIC has no effect here because we did prealloc
1984 * earlier, but it's good form to communicate our expectations.
1986 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
1987 BUG_ON(retval != 0);
1992 } while_each_thread(leader, tsk);
1994 /* remember the number of threads in the array for later. */
1996 tset.tc_array = group;
1997 tset.tc_array_len = group_size;
1999 /* methods shouldn't be called if no task is actually migrating */
2002 goto out_free_group_list;
2005 * step 1: check that we can legitimately attach to the cgroup.
2007 for_each_root_subsys(root, ss) {
2008 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss);
2010 if (ss->can_attach) {
2011 retval = ss->can_attach(css, &tset);
2014 goto out_cancel_attach;
2020 * step 2: make sure css_sets exist for all threads to be migrated.
2021 * we use find_css_set, which allocates a new one if necessary.
2023 for (i = 0; i < group_size; i++) {
2024 struct css_set *old_cset;
2026 tc = flex_array_get(group, i);
2027 old_cset = task_css_set(tc->task);
2028 tc->cset = find_css_set(old_cset, cgrp);
2031 goto out_put_css_set_refs;
2036 * step 3: now that we're guaranteed success wrt the css_sets,
2037 * proceed to move all tasks to the new cgroup. There are no
2038 * failure cases after here, so this is the commit point.
2040 for (i = 0; i < group_size; i++) {
2041 tc = flex_array_get(group, i);
2042 cgroup_task_migrate(tc->cgrp, tc->task, tc->cset);
2044 /* nothing is sensitive to fork() after this point. */
2047 * step 4: do subsystem attach callbacks.
2049 for_each_root_subsys(root, ss) {
2050 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss);
2053 ss->attach(css, &tset);
2057 * step 5: success! and cleanup
2060 out_put_css_set_refs:
2062 for (i = 0; i < group_size; i++) {
2063 tc = flex_array_get(group, i);
2066 put_css_set(tc->cset);
2071 for_each_root_subsys(root, ss) {
2072 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss);
2074 if (ss == failed_ss)
2076 if (ss->cancel_attach)
2077 ss->cancel_attach(css, &tset);
2080 out_free_group_list:
2081 flex_array_free(group);
2086 * Find the task_struct of the task to attach by vpid and pass it along to the
2087 * function to attach either it or all tasks in its threadgroup. Will lock
2088 * cgroup_mutex and threadgroup; may take task_lock of task.
2090 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2092 struct task_struct *tsk;
2093 const struct cred *cred = current_cred(), *tcred;
2096 if (!cgroup_lock_live_group(cgrp))
2102 tsk = find_task_by_vpid(pid);
2106 goto out_unlock_cgroup;
2109 * even if we're attaching all tasks in the thread group, we
2110 * only need to check permissions on one of them.
2112 tcred = __task_cred(tsk);
2113 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2114 !uid_eq(cred->euid, tcred->uid) &&
2115 !uid_eq(cred->euid, tcred->suid)) {
2118 goto out_unlock_cgroup;
2124 tsk = tsk->group_leader;
2127 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2128 * trapped in a cpuset, or RT worker may be born in a cgroup
2129 * with no rt_runtime allocated. Just say no.
2131 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2134 goto out_unlock_cgroup;
2137 get_task_struct(tsk);
2140 threadgroup_lock(tsk);
2142 if (!thread_group_leader(tsk)) {
2144 * a race with de_thread from another thread's exec()
2145 * may strip us of our leadership, if this happens,
2146 * there is no choice but to throw this task away and
2147 * try again; this is
2148 * "double-double-toil-and-trouble-check locking".
2150 threadgroup_unlock(tsk);
2151 put_task_struct(tsk);
2152 goto retry_find_task;
2156 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2158 threadgroup_unlock(tsk);
2160 put_task_struct(tsk);
2162 mutex_unlock(&cgroup_mutex);
2167 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2168 * @from: attach to all cgroups of a given task
2169 * @tsk: the task to be attached
2171 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2173 struct cgroupfs_root *root;
2176 mutex_lock(&cgroup_mutex);
2177 for_each_active_root(root) {
2178 struct cgroup *from_cgrp = task_cgroup_from_root(from, root);
2180 retval = cgroup_attach_task(from_cgrp, tsk, false);
2184 mutex_unlock(&cgroup_mutex);
2188 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2190 static int cgroup_tasks_write(struct cgroup_subsys_state *css,
2191 struct cftype *cft, u64 pid)
2193 return attach_task_by_pid(css->cgroup, pid, false);
2196 static int cgroup_procs_write(struct cgroup_subsys_state *css,
2197 struct cftype *cft, u64 tgid)
2199 return attach_task_by_pid(css->cgroup, tgid, true);
2202 static int cgroup_release_agent_write(struct cgroup_subsys_state *css,
2203 struct cftype *cft, const char *buffer)
2205 BUILD_BUG_ON(sizeof(css->cgroup->root->release_agent_path) < PATH_MAX);
2206 if (strlen(buffer) >= PATH_MAX)
2208 if (!cgroup_lock_live_group(css->cgroup))
2210 mutex_lock(&cgroup_root_mutex);
2211 strcpy(css->cgroup->root->release_agent_path, buffer);
2212 mutex_unlock(&cgroup_root_mutex);
2213 mutex_unlock(&cgroup_mutex);
2217 static int cgroup_release_agent_show(struct cgroup_subsys_state *css,
2218 struct cftype *cft, struct seq_file *seq)
2220 struct cgroup *cgrp = css->cgroup;
2222 if (!cgroup_lock_live_group(cgrp))
2224 seq_puts(seq, cgrp->root->release_agent_path);
2225 seq_putc(seq, '\n');
2226 mutex_unlock(&cgroup_mutex);
2230 static int cgroup_sane_behavior_show(struct cgroup_subsys_state *css,
2231 struct cftype *cft, struct seq_file *seq)
2233 seq_printf(seq, "%d\n", cgroup_sane_behavior(css->cgroup));
2237 /* A buffer size big enough for numbers or short strings */
2238 #define CGROUP_LOCAL_BUFFER_SIZE 64
2240 static ssize_t cgroup_write_X64(struct cgroup_subsys_state *css,
2241 struct cftype *cft, struct file *file,
2242 const char __user *userbuf, size_t nbytes,
2243 loff_t *unused_ppos)
2245 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
2251 if (nbytes >= sizeof(buffer))
2253 if (copy_from_user(buffer, userbuf, nbytes))
2256 buffer[nbytes] = 0; /* nul-terminate */
2257 if (cft->write_u64) {
2258 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
2261 retval = cft->write_u64(css, cft, val);
2263 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
2266 retval = cft->write_s64(css, cft, val);
2273 static ssize_t cgroup_write_string(struct cgroup_subsys_state *css,
2274 struct cftype *cft, struct file *file,
2275 const char __user *userbuf, size_t nbytes,
2276 loff_t *unused_ppos)
2278 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
2280 size_t max_bytes = cft->max_write_len;
2281 char *buffer = local_buffer;
2284 max_bytes = sizeof(local_buffer) - 1;
2285 if (nbytes >= max_bytes)
2287 /* Allocate a dynamic buffer if we need one */
2288 if (nbytes >= sizeof(local_buffer)) {
2289 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2293 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2298 buffer[nbytes] = 0; /* nul-terminate */
2299 retval = cft->write_string(css, cft, strstrip(buffer));
2303 if (buffer != local_buffer)
2308 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2309 size_t nbytes, loff_t *ppos)
2311 struct cfent *cfe = __d_cfe(file->f_dentry);
2312 struct cftype *cft = __d_cft(file->f_dentry);
2313 struct cgroup_subsys_state *css = cfe->css;
2316 return cft->write(css, cft, file, buf, nbytes, ppos);
2317 if (cft->write_u64 || cft->write_s64)
2318 return cgroup_write_X64(css, cft, file, buf, nbytes, ppos);
2319 if (cft->write_string)
2320 return cgroup_write_string(css, cft, file, buf, nbytes, ppos);
2322 int ret = cft->trigger(css, (unsigned int)cft->private);
2323 return ret ? ret : nbytes;
2328 static ssize_t cgroup_read_u64(struct cgroup_subsys_state *css,
2329 struct cftype *cft, struct file *file,
2330 char __user *buf, size_t nbytes, loff_t *ppos)
2332 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2333 u64 val = cft->read_u64(css, cft);
2334 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2336 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2339 static ssize_t cgroup_read_s64(struct cgroup_subsys_state *css,
2340 struct cftype *cft, struct file *file,
2341 char __user *buf, size_t nbytes, loff_t *ppos)
2343 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2344 s64 val = cft->read_s64(css, cft);
2345 int len = sprintf(tmp, "%lld\n", (long long) val);
2347 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2350 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2351 size_t nbytes, loff_t *ppos)
2353 struct cfent *cfe = __d_cfe(file->f_dentry);
2354 struct cftype *cft = __d_cft(file->f_dentry);
2355 struct cgroup_subsys_state *css = cfe->css;
2358 return cft->read(css, cft, file, buf, nbytes, ppos);
2360 return cgroup_read_u64(css, cft, file, buf, nbytes, ppos);
2362 return cgroup_read_s64(css, cft, file, buf, nbytes, ppos);
2367 * seqfile ops/methods for returning structured data. Currently just
2368 * supports string->u64 maps, but can be extended in future.
2371 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2373 struct seq_file *sf = cb->state;
2374 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2377 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2379 struct cfent *cfe = m->private;
2380 struct cftype *cft = cfe->type;
2381 struct cgroup_subsys_state *css = cfe->css;
2383 if (cft->read_map) {
2384 struct cgroup_map_cb cb = {
2385 .fill = cgroup_map_add,
2388 return cft->read_map(css, cft, &cb);
2390 return cft->read_seq_string(css, cft, m);
2393 static const struct file_operations cgroup_seqfile_operations = {
2395 .write = cgroup_file_write,
2396 .llseek = seq_lseek,
2397 .release = single_release,
2400 static int cgroup_file_open(struct inode *inode, struct file *file)
2402 struct cfent *cfe = __d_cfe(file->f_dentry);
2403 struct cftype *cft = __d_cft(file->f_dentry);
2404 struct cgroup *cgrp = __d_cgrp(cfe->dentry->d_parent);
2405 struct cgroup_subsys_state *css;
2408 err = generic_file_open(inode, file);
2413 * If the file belongs to a subsystem, pin the css. Will be
2414 * unpinned either on open failure or release. This ensures that
2415 * @css stays alive for all file operations.
2418 css = cgroup_css(cgrp, cft->ss);
2419 if (cft->ss && !css_tryget(css))
2427 * @cfe->css is used by read/write/close to determine the
2428 * associated css. @file->private_data would be a better place but
2429 * that's already used by seqfile. Multiple accessors may use it
2430 * simultaneously which is okay as the association never changes.
2432 WARN_ON_ONCE(cfe->css && cfe->css != css);
2435 if (cft->read_map || cft->read_seq_string) {
2436 file->f_op = &cgroup_seqfile_operations;
2437 err = single_open(file, cgroup_seqfile_show, cfe);
2438 } else if (cft->open) {
2439 err = cft->open(inode, file);
2447 static int cgroup_file_release(struct inode *inode, struct file *file)
2449 struct cfent *cfe = __d_cfe(file->f_dentry);
2450 struct cftype *cft = __d_cft(file->f_dentry);
2451 struct cgroup_subsys_state *css = cfe->css;
2455 ret = cft->release(inode, file);
2462 * cgroup_rename - Only allow simple rename of directories in place.
2464 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2465 struct inode *new_dir, struct dentry *new_dentry)
2468 struct cgroup_name *name, *old_name;
2469 struct cgroup *cgrp;
2472 * It's convinient to use parent dir's i_mutex to protected
2475 lockdep_assert_held(&old_dir->i_mutex);
2477 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2479 if (new_dentry->d_inode)
2481 if (old_dir != new_dir)
2484 cgrp = __d_cgrp(old_dentry);
2487 * This isn't a proper migration and its usefulness is very
2488 * limited. Disallow if sane_behavior.
2490 if (cgroup_sane_behavior(cgrp))
2493 name = cgroup_alloc_name(new_dentry);
2497 ret = simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2503 old_name = rcu_dereference_protected(cgrp->name, true);
2504 rcu_assign_pointer(cgrp->name, name);
2506 kfree_rcu(old_name, rcu_head);
2510 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2512 if (S_ISDIR(dentry->d_inode->i_mode))
2513 return &__d_cgrp(dentry)->xattrs;
2515 return &__d_cfe(dentry)->xattrs;
2518 static inline int xattr_enabled(struct dentry *dentry)
2520 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2521 return root->flags & CGRP_ROOT_XATTR;
2524 static bool is_valid_xattr(const char *name)
2526 if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2527 !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2532 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2533 const void *val, size_t size, int flags)
2535 if (!xattr_enabled(dentry))
2537 if (!is_valid_xattr(name))
2539 return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2542 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2544 if (!xattr_enabled(dentry))
2546 if (!is_valid_xattr(name))
2548 return simple_xattr_remove(__d_xattrs(dentry), name);
2551 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2552 void *buf, size_t size)
2554 if (!xattr_enabled(dentry))
2556 if (!is_valid_xattr(name))
2558 return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2561 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2563 if (!xattr_enabled(dentry))
2565 return simple_xattr_list(__d_xattrs(dentry), buf, size);
2568 static const struct file_operations cgroup_file_operations = {
2569 .read = cgroup_file_read,
2570 .write = cgroup_file_write,
2571 .llseek = generic_file_llseek,
2572 .open = cgroup_file_open,
2573 .release = cgroup_file_release,
2576 static const struct inode_operations cgroup_file_inode_operations = {
2577 .setxattr = cgroup_setxattr,
2578 .getxattr = cgroup_getxattr,
2579 .listxattr = cgroup_listxattr,
2580 .removexattr = cgroup_removexattr,
2583 static const struct inode_operations cgroup_dir_inode_operations = {
2584 .lookup = simple_lookup,
2585 .mkdir = cgroup_mkdir,
2586 .rmdir = cgroup_rmdir,
2587 .rename = cgroup_rename,
2588 .setxattr = cgroup_setxattr,
2589 .getxattr = cgroup_getxattr,
2590 .listxattr = cgroup_listxattr,
2591 .removexattr = cgroup_removexattr,
2594 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2595 struct super_block *sb)
2597 struct inode *inode;
2601 if (dentry->d_inode)
2604 inode = cgroup_new_inode(mode, sb);
2608 if (S_ISDIR(mode)) {
2609 inode->i_op = &cgroup_dir_inode_operations;
2610 inode->i_fop = &simple_dir_operations;
2612 /* start off with i_nlink == 2 (for "." entry) */
2614 inc_nlink(dentry->d_parent->d_inode);
2617 * Control reaches here with cgroup_mutex held.
2618 * @inode->i_mutex should nest outside cgroup_mutex but we
2619 * want to populate it immediately without releasing
2620 * cgroup_mutex. As @inode isn't visible to anyone else
2621 * yet, trylock will always succeed without affecting
2624 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2625 } else if (S_ISREG(mode)) {
2627 inode->i_fop = &cgroup_file_operations;
2628 inode->i_op = &cgroup_file_inode_operations;
2630 d_instantiate(dentry, inode);
2631 dget(dentry); /* Extra count - pin the dentry in core */
2636 * cgroup_file_mode - deduce file mode of a control file
2637 * @cft: the control file in question
2639 * returns cft->mode if ->mode is not 0
2640 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2641 * returns S_IRUGO if it has only a read handler
2642 * returns S_IWUSR if it has only a write hander
2644 static umode_t cgroup_file_mode(const struct cftype *cft)
2651 if (cft->read || cft->read_u64 || cft->read_s64 ||
2652 cft->read_map || cft->read_seq_string)
2655 if (cft->write || cft->write_u64 || cft->write_s64 ||
2656 cft->write_string || cft->trigger)
2662 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2664 struct dentry *dir = cgrp->dentry;
2665 struct cgroup *parent = __d_cgrp(dir);
2666 struct dentry *dentry;
2670 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2672 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
2673 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
2674 strcpy(name, cft->ss->name);
2677 strcat(name, cft->name);
2679 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2681 cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2685 dentry = lookup_one_len(name, dir, strlen(name));
2686 if (IS_ERR(dentry)) {
2687 error = PTR_ERR(dentry);
2691 cfe->type = (void *)cft;
2692 cfe->dentry = dentry;
2693 dentry->d_fsdata = cfe;
2694 simple_xattrs_init(&cfe->xattrs);
2696 mode = cgroup_file_mode(cft);
2697 error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2699 list_add_tail(&cfe->node, &parent->files);
2709 * cgroup_addrm_files - add or remove files to a cgroup directory
2710 * @cgrp: the target cgroup
2711 * @cfts: array of cftypes to be added
2712 * @is_add: whether to add or remove
2714 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2715 * For removals, this function never fails. If addition fails, this
2716 * function doesn't remove files already added. The caller is responsible
2719 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2725 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
2726 lockdep_assert_held(&cgroup_mutex);
2728 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2729 /* does cft->flags tell us to skip this file on @cgrp? */
2730 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2732 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2734 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2738 ret = cgroup_add_file(cgrp, cft);
2740 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2745 cgroup_rm_file(cgrp, cft);
2751 static void cgroup_cfts_prepare(void)
2752 __acquires(&cgroup_mutex)
2755 * Thanks to the entanglement with vfs inode locking, we can't walk
2756 * the existing cgroups under cgroup_mutex and create files.
2757 * Instead, we use css_for_each_descendant_pre() and drop RCU read
2758 * lock before calling cgroup_addrm_files().
2760 mutex_lock(&cgroup_mutex);
2763 static int cgroup_cfts_commit(struct cftype *cfts, bool is_add)
2764 __releases(&cgroup_mutex)
2767 struct cgroup_subsys *ss = cfts[0].ss;
2768 struct cgroup *root = &ss->root->top_cgroup;
2769 struct super_block *sb = ss->root->sb;
2770 struct dentry *prev = NULL;
2771 struct inode *inode;
2772 struct cgroup_subsys_state *css;
2776 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2777 if (!cfts || ss->root == &cgroup_dummy_root ||
2778 !atomic_inc_not_zero(&sb->s_active)) {
2779 mutex_unlock(&cgroup_mutex);
2784 * All cgroups which are created after we drop cgroup_mutex will
2785 * have the updated set of files, so we only need to update the
2786 * cgroups created before the current @cgroup_serial_nr_next.
2788 update_before = cgroup_serial_nr_next;
2790 mutex_unlock(&cgroup_mutex);
2792 /* add/rm files for all cgroups created before */
2794 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2795 struct cgroup *cgrp = css->cgroup;
2797 if (cgroup_is_dead(cgrp))
2800 inode = cgrp->dentry->d_inode;
2805 prev = cgrp->dentry;
2807 mutex_lock(&inode->i_mutex);
2808 mutex_lock(&cgroup_mutex);
2809 if (cgrp->serial_nr < update_before && !cgroup_is_dead(cgrp))
2810 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2811 mutex_unlock(&cgroup_mutex);
2812 mutex_unlock(&inode->i_mutex);
2820 deactivate_super(sb);
2825 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2826 * @ss: target cgroup subsystem
2827 * @cfts: zero-length name terminated array of cftypes
2829 * Register @cfts to @ss. Files described by @cfts are created for all
2830 * existing cgroups to which @ss is attached and all future cgroups will
2831 * have them too. This function can be called anytime whether @ss is
2834 * Returns 0 on successful registration, -errno on failure. Note that this
2835 * function currently returns 0 as long as @cfts registration is successful
2836 * even if some file creation attempts on existing cgroups fail.
2838 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2840 struct cftype_set *set;
2844 set = kzalloc(sizeof(*set), GFP_KERNEL);
2848 for (cft = cfts; cft->name[0] != '\0'; cft++)
2851 cgroup_cfts_prepare();
2853 list_add_tail(&set->node, &ss->cftsets);
2854 ret = cgroup_cfts_commit(cfts, true);
2856 cgroup_rm_cftypes(cfts);
2859 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2862 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2863 * @cfts: zero-length name terminated array of cftypes
2865 * Unregister @cfts. Files described by @cfts are removed from all
2866 * existing cgroups and all future cgroups won't have them either. This
2867 * function can be called anytime whether @cfts' subsys is attached or not.
2869 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2872 int cgroup_rm_cftypes(struct cftype *cfts)
2874 struct cftype_set *set;
2876 if (!cfts || !cfts[0].ss)
2879 cgroup_cfts_prepare();
2881 list_for_each_entry(set, &cfts[0].ss->cftsets, node) {
2882 if (set->cfts == cfts) {
2883 list_del(&set->node);
2885 cgroup_cfts_commit(cfts, false);
2890 cgroup_cfts_commit(NULL, false);
2895 * cgroup_task_count - count the number of tasks in a cgroup.
2896 * @cgrp: the cgroup in question
2898 * Return the number of tasks in the cgroup.
2900 int cgroup_task_count(const struct cgroup *cgrp)
2903 struct cgrp_cset_link *link;
2905 read_lock(&css_set_lock);
2906 list_for_each_entry(link, &cgrp->cset_links, cset_link)
2907 count += atomic_read(&link->cset->refcount);
2908 read_unlock(&css_set_lock);
2913 * To reduce the fork() overhead for systems that are not actually using
2914 * their cgroups capability, we don't maintain the lists running through
2915 * each css_set to its tasks until we see the list actually used - in other
2916 * words after the first call to css_task_iter_start().
2918 static void cgroup_enable_task_cg_lists(void)
2920 struct task_struct *p, *g;
2921 write_lock(&css_set_lock);
2922 use_task_css_set_links = 1;
2924 * We need tasklist_lock because RCU is not safe against
2925 * while_each_thread(). Besides, a forking task that has passed
2926 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2927 * is not guaranteed to have its child immediately visible in the
2928 * tasklist if we walk through it with RCU.
2930 read_lock(&tasklist_lock);
2931 do_each_thread(g, p) {
2934 * We should check if the process is exiting, otherwise
2935 * it will race with cgroup_exit() in that the list
2936 * entry won't be deleted though the process has exited.
2938 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2939 list_add(&p->cg_list, &task_css_set(p)->tasks);
2941 } while_each_thread(g, p);
2942 read_unlock(&tasklist_lock);
2943 write_unlock(&css_set_lock);
2947 * css_next_child - find the next child of a given css
2948 * @pos_css: the current position (%NULL to initiate traversal)
2949 * @parent_css: css whose children to walk
2951 * This function returns the next child of @parent_css and should be called
2952 * under RCU read lock. The only requirement is that @parent_css and
2953 * @pos_css are accessible. The next sibling is guaranteed to be returned
2954 * regardless of their states.
2956 struct cgroup_subsys_state *
2957 css_next_child(struct cgroup_subsys_state *pos_css,
2958 struct cgroup_subsys_state *parent_css)
2960 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
2961 struct cgroup *cgrp = parent_css->cgroup;
2962 struct cgroup *next;
2964 WARN_ON_ONCE(!rcu_read_lock_held());
2967 * @pos could already have been removed. Once a cgroup is removed,
2968 * its ->sibling.next is no longer updated when its next sibling
2969 * changes. As CGRP_DEAD assertion is serialized and happens
2970 * before the cgroup is taken off the ->sibling list, if we see it
2971 * unasserted, it's guaranteed that the next sibling hasn't
2972 * finished its grace period even if it's already removed, and thus
2973 * safe to dereference from this RCU critical section. If
2974 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
2975 * to be visible as %true here.
2977 * If @pos is dead, its next pointer can't be dereferenced;
2978 * however, as each cgroup is given a monotonically increasing
2979 * unique serial number and always appended to the sibling list,
2980 * the next one can be found by walking the parent's children until
2981 * we see a cgroup with higher serial number than @pos's. While
2982 * this path can be slower, it's taken only when either the current
2983 * cgroup is removed or iteration and removal race.
2986 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
2987 } else if (likely(!cgroup_is_dead(pos))) {
2988 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
2990 list_for_each_entry_rcu(next, &cgrp->children, sibling)
2991 if (next->serial_nr > pos->serial_nr)
2995 if (&next->sibling == &cgrp->children)
2998 return cgroup_css(next, parent_css->ss);
3000 EXPORT_SYMBOL_GPL(css_next_child);
3003 * css_next_descendant_pre - find the next descendant for pre-order walk
3004 * @pos: the current position (%NULL to initiate traversal)
3005 * @root: css whose descendants to walk
3007 * To be used by css_for_each_descendant_pre(). Find the next descendant
3008 * to visit for pre-order traversal of @root's descendants. @root is
3009 * included in the iteration and the first node to be visited.
3011 * While this function requires RCU read locking, it doesn't require the
3012 * whole traversal to be contained in a single RCU critical section. This
3013 * function will return the correct next descendant as long as both @pos
3014 * and @root are accessible and @pos is a descendant of @root.
3016 struct cgroup_subsys_state *
3017 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3018 struct cgroup_subsys_state *root)
3020 struct cgroup_subsys_state *next;
3022 WARN_ON_ONCE(!rcu_read_lock_held());
3024 /* if first iteration, visit @root */
3028 /* visit the first child if exists */
3029 next = css_next_child(NULL, pos);
3033 /* no child, visit my or the closest ancestor's next sibling */
3034 while (pos != root) {
3035 next = css_next_child(pos, css_parent(pos));
3038 pos = css_parent(pos);
3043 EXPORT_SYMBOL_GPL(css_next_descendant_pre);
3046 * css_rightmost_descendant - return the rightmost descendant of a css
3047 * @pos: css of interest
3049 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3050 * is returned. This can be used during pre-order traversal to skip
3053 * While this function requires RCU read locking, it doesn't require the
3054 * whole traversal to be contained in a single RCU critical section. This
3055 * function will return the correct rightmost descendant as long as @pos is
3058 struct cgroup_subsys_state *
3059 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3061 struct cgroup_subsys_state *last, *tmp;
3063 WARN_ON_ONCE(!rcu_read_lock_held());
3067 /* ->prev isn't RCU safe, walk ->next till the end */
3069 css_for_each_child(tmp, last)
3075 EXPORT_SYMBOL_GPL(css_rightmost_descendant);
3077 static struct cgroup_subsys_state *
3078 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3080 struct cgroup_subsys_state *last;
3084 pos = css_next_child(NULL, pos);
3091 * css_next_descendant_post - find the next descendant for post-order walk
3092 * @pos: the current position (%NULL to initiate traversal)
3093 * @root: css whose descendants to walk
3095 * To be used by css_for_each_descendant_post(). Find the next descendant
3096 * to visit for post-order traversal of @root's descendants. @root is
3097 * included in the iteration and the last node to be visited.
3099 * While this function requires RCU read locking, it doesn't require the
3100 * whole traversal to be contained in a single RCU critical section. This
3101 * function will return the correct next descendant as long as both @pos
3102 * and @cgroup are accessible and @pos is a descendant of @cgroup.
3104 struct cgroup_subsys_state *
3105 css_next_descendant_post(struct cgroup_subsys_state *pos,
3106 struct cgroup_subsys_state *root)
3108 struct cgroup_subsys_state *next;
3110 WARN_ON_ONCE(!rcu_read_lock_held());
3112 /* if first iteration, visit leftmost descendant which may be @root */
3114 return css_leftmost_descendant(root);
3116 /* if we visited @root, we're done */
3120 /* if there's an unvisited sibling, visit its leftmost descendant */
3121 next = css_next_child(pos, css_parent(pos));
3123 return css_leftmost_descendant(next);
3125 /* no sibling left, visit parent */
3126 return css_parent(pos);
3128 EXPORT_SYMBOL_GPL(css_next_descendant_post);
3131 * css_advance_task_iter - advance a task itererator to the next css_set
3132 * @it: the iterator to advance
3134 * Advance @it to the next css_set to walk.
3136 static void css_advance_task_iter(struct css_task_iter *it)
3138 struct list_head *l = it->cset_link;
3139 struct cgrp_cset_link *link;
3140 struct css_set *cset;
3142 /* Advance to the next non-empty css_set */
3145 if (l == &it->origin_css->cgroup->cset_links) {
3146 it->cset_link = NULL;
3149 link = list_entry(l, struct cgrp_cset_link, cset_link);
3151 } while (list_empty(&cset->tasks));
3153 it->task = cset->tasks.next;
3157 * css_task_iter_start - initiate task iteration
3158 * @css: the css to walk tasks of
3159 * @it: the task iterator to use
3161 * Initiate iteration through the tasks of @css. The caller can call
3162 * css_task_iter_next() to walk through the tasks until the function
3163 * returns NULL. On completion of iteration, css_task_iter_end() must be
3166 * Note that this function acquires a lock which is released when the
3167 * iteration finishes. The caller can't sleep while iteration is in
3170 void css_task_iter_start(struct cgroup_subsys_state *css,
3171 struct css_task_iter *it)
3172 __acquires(css_set_lock)
3175 * The first time anyone tries to iterate across a css, we need to
3176 * enable the list linking each css_set to its tasks, and fix up
3177 * all existing tasks.
3179 if (!use_task_css_set_links)
3180 cgroup_enable_task_cg_lists();
3182 read_lock(&css_set_lock);
3184 it->origin_css = css;
3185 it->cset_link = &css->cgroup->cset_links;
3187 css_advance_task_iter(it);
3191 * css_task_iter_next - return the next task for the iterator
3192 * @it: the task iterator being iterated
3194 * The "next" function for task iteration. @it should have been
3195 * initialized via css_task_iter_start(). Returns NULL when the iteration
3198 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3200 struct task_struct *res;
3201 struct list_head *l = it->task;
3202 struct cgrp_cset_link *link;
3204 /* If the iterator cg is NULL, we have no tasks */
3207 res = list_entry(l, struct task_struct, cg_list);
3208 /* Advance iterator to find next entry */
3210 link = list_entry(it->cset_link, struct cgrp_cset_link, cset_link);
3211 if (l == &link->cset->tasks) {
3213 * We reached the end of this task list - move on to the
3214 * next cgrp_cset_link.
3216 css_advance_task_iter(it);
3224 * css_task_iter_end - finish task iteration
3225 * @it: the task iterator to finish
3227 * Finish task iteration started by css_task_iter_start().
3229 void css_task_iter_end(struct css_task_iter *it)
3230 __releases(css_set_lock)
3232 read_unlock(&css_set_lock);
3235 static inline int started_after_time(struct task_struct *t1,
3236 struct timespec *time,
3237 struct task_struct *t2)
3239 int start_diff = timespec_compare(&t1->start_time, time);
3240 if (start_diff > 0) {
3242 } else if (start_diff < 0) {
3246 * Arbitrarily, if two processes started at the same
3247 * time, we'll say that the lower pointer value
3248 * started first. Note that t2 may have exited by now
3249 * so this may not be a valid pointer any longer, but
3250 * that's fine - it still serves to distinguish
3251 * between two tasks started (effectively) simultaneously.
3258 * This function is a callback from heap_insert() and is used to order
3260 * In this case we order the heap in descending task start time.
3262 static inline int started_after(void *p1, void *p2)
3264 struct task_struct *t1 = p1;
3265 struct task_struct *t2 = p2;
3266 return started_after_time(t1, &t2->start_time, t2);
3270 * css_scan_tasks - iterate though all the tasks in a css
3271 * @css: the css to iterate tasks of
3272 * @test: optional test callback
3273 * @process: process callback
3274 * @data: data passed to @test and @process
3275 * @heap: optional pre-allocated heap used for task iteration
3277 * Iterate through all the tasks in @css, calling @test for each, and if it
3278 * returns %true, call @process for it also.
3280 * @test may be NULL, meaning always true (select all tasks), which
3281 * effectively duplicates css_task_iter_{start,next,end}() but does not
3282 * lock css_set_lock for the call to @process.
3284 * It is guaranteed that @process will act on every task that is a member
3285 * of @css for the duration of this call. This function may or may not
3286 * call @process for tasks that exit or move to a different css during the
3287 * call, or are forked or move into the css during the call.
3289 * Note that @test may be called with locks held, and may in some
3290 * situations be called multiple times for the same task, so it should be
3293 * If @heap is non-NULL, a heap has been pre-allocated and will be used for
3294 * heap operations (and its "gt" member will be overwritten), else a
3295 * temporary heap will be used (allocation of which may cause this function
3298 int css_scan_tasks(struct cgroup_subsys_state *css,
3299 bool (*test)(struct task_struct *, void *),
3300 void (*process)(struct task_struct *, void *),
3301 void *data, struct ptr_heap *heap)
3304 struct css_task_iter it;
3305 struct task_struct *p, *dropped;
3306 /* Never dereference latest_task, since it's not refcounted */
3307 struct task_struct *latest_task = NULL;
3308 struct ptr_heap tmp_heap;
3309 struct timespec latest_time = { 0, 0 };
3312 /* The caller supplied our heap and pre-allocated its memory */
3313 heap->gt = &started_after;
3315 /* We need to allocate our own heap memory */
3317 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3319 /* cannot allocate the heap */
3325 * Scan tasks in the css, using the @test callback to determine
3326 * which are of interest, and invoking @process callback on the
3327 * ones which need an update. Since we don't want to hold any
3328 * locks during the task updates, gather tasks to be processed in a
3329 * heap structure. The heap is sorted by descending task start
3330 * time. If the statically-sized heap fills up, we overflow tasks
3331 * that started later, and in future iterations only consider tasks
3332 * that started after the latest task in the previous pass. This
3333 * guarantees forward progress and that we don't miss any tasks.
3336 css_task_iter_start(css, &it);
3337 while ((p = css_task_iter_next(&it))) {
3339 * Only affect tasks that qualify per the caller's callback,
3340 * if he provided one
3342 if (test && !test(p, data))
3345 * Only process tasks that started after the last task
3348 if (!started_after_time(p, &latest_time, latest_task))
3350 dropped = heap_insert(heap, p);
3351 if (dropped == NULL) {
3353 * The new task was inserted; the heap wasn't
3357 } else if (dropped != p) {
3359 * The new task was inserted, and pushed out a
3363 put_task_struct(dropped);
3366 * Else the new task was newer than anything already in
3367 * the heap and wasn't inserted
3370 css_task_iter_end(&it);
3373 for (i = 0; i < heap->size; i++) {
3374 struct task_struct *q = heap->ptrs[i];
3376 latest_time = q->start_time;
3379 /* Process the task per the caller's callback */
3384 * If we had to process any tasks at all, scan again
3385 * in case some of them were in the middle of forking
3386 * children that didn't get processed.
3387 * Not the most efficient way to do it, but it avoids
3388 * having to take callback_mutex in the fork path
3392 if (heap == &tmp_heap)
3393 heap_free(&tmp_heap);
3397 static void cgroup_transfer_one_task(struct task_struct *task, void *data)
3399 struct cgroup *new_cgroup = data;
3401 mutex_lock(&cgroup_mutex);
3402 cgroup_attach_task(new_cgroup, task, false);
3403 mutex_unlock(&cgroup_mutex);
3407 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3408 * @to: cgroup to which the tasks will be moved
3409 * @from: cgroup in which the tasks currently reside
3411 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3413 return css_scan_tasks(&from->dummy_css, NULL, cgroup_transfer_one_task,
3418 * Stuff for reading the 'tasks'/'procs' files.
3420 * Reading this file can return large amounts of data if a cgroup has
3421 * *lots* of attached tasks. So it may need several calls to read(),
3422 * but we cannot guarantee that the information we produce is correct
3423 * unless we produce it entirely atomically.
3427 /* which pidlist file are we talking about? */
3428 enum cgroup_filetype {
3434 * A pidlist is a list of pids that virtually represents the contents of one
3435 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3436 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3439 struct cgroup_pidlist {
3441 * used to find which pidlist is wanted. doesn't change as long as
3442 * this particular list stays in the list.
3444 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3447 /* how many elements the above list has */
3449 /* how many files are using the current array */
3451 /* each of these stored in a list by its cgroup */
3452 struct list_head links;
3453 /* pointer to the cgroup we belong to, for list removal purposes */
3454 struct cgroup *owner;
3455 /* protects the other fields */
3456 struct rw_semaphore rwsem;
3460 * The following two functions "fix" the issue where there are more pids
3461 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3462 * TODO: replace with a kernel-wide solution to this problem
3464 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3465 static void *pidlist_allocate(int count)
3467 if (PIDLIST_TOO_LARGE(count))
3468 return vmalloc(count * sizeof(pid_t));
3470 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3472 static void pidlist_free(void *p)
3474 if (is_vmalloc_addr(p))
3481 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3482 * Returns the number of unique elements.
3484 static int pidlist_uniq(pid_t *list, int length)
3489 * we presume the 0th element is unique, so i starts at 1. trivial
3490 * edge cases first; no work needs to be done for either
3492 if (length == 0 || length == 1)
3494 /* src and dest walk down the list; dest counts unique elements */
3495 for (src = 1; src < length; src++) {
3496 /* find next unique element */
3497 while (list[src] == list[src-1]) {
3502 /* dest always points to where the next unique element goes */
3503 list[dest] = list[src];
3510 static int cmppid(const void *a, const void *b)
3512 return *(pid_t *)a - *(pid_t *)b;
3516 * find the appropriate pidlist for our purpose (given procs vs tasks)
3517 * returns with the lock on that pidlist already held, and takes care
3518 * of the use count, or returns NULL with no locks held if we're out of
3521 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3522 enum cgroup_filetype type)
3524 struct cgroup_pidlist *l;
3525 /* don't need task_nsproxy() if we're looking at ourself */
3526 struct pid_namespace *ns = task_active_pid_ns(current);
3529 * We can't drop the pidlist_mutex before taking the l->rwsem in case
3530 * the last ref-holder is trying to remove l from the list at the same
3531 * time. Holding the pidlist_mutex precludes somebody taking whichever
3532 * list we find out from under us - compare release_pid_array().
3534 mutex_lock(&cgrp->pidlist_mutex);
3535 list_for_each_entry(l, &cgrp->pidlists, links) {
3536 if (l->key.type == type && l->key.ns == ns) {
3537 /* make sure l doesn't vanish out from under us */
3538 down_write(&l->rwsem);
3539 mutex_unlock(&cgrp->pidlist_mutex);
3543 /* entry not found; create a new one */
3544 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3546 mutex_unlock(&cgrp->pidlist_mutex);
3549 init_rwsem(&l->rwsem);
3550 down_write(&l->rwsem);
3552 l->key.ns = get_pid_ns(ns);
3554 list_add(&l->links, &cgrp->pidlists);
3555 mutex_unlock(&cgrp->pidlist_mutex);
3560 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3562 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3563 struct cgroup_pidlist **lp)
3567 int pid, n = 0; /* used for populating the array */
3568 struct css_task_iter it;
3569 struct task_struct *tsk;
3570 struct cgroup_pidlist *l;
3573 * If cgroup gets more users after we read count, we won't have
3574 * enough space - tough. This race is indistinguishable to the
3575 * caller from the case that the additional cgroup users didn't
3576 * show up until sometime later on.
3578 length = cgroup_task_count(cgrp);
3579 array = pidlist_allocate(length);
3582 /* now, populate the array */
3583 css_task_iter_start(&cgrp->dummy_css, &it);
3584 while ((tsk = css_task_iter_next(&it))) {
3585 if (unlikely(n == length))
3587 /* get tgid or pid for procs or tasks file respectively */
3588 if (type == CGROUP_FILE_PROCS)
3589 pid = task_tgid_vnr(tsk);
3591 pid = task_pid_vnr(tsk);
3592 if (pid > 0) /* make sure to only use valid results */
3595 css_task_iter_end(&it);
3597 /* now sort & (if procs) strip out duplicates */
3598 sort(array, length, sizeof(pid_t), cmppid, NULL);
3599 if (type == CGROUP_FILE_PROCS)
3600 length = pidlist_uniq(array, length);
3601 l = cgroup_pidlist_find(cgrp, type);
3603 pidlist_free(array);
3606 /* store array, freeing old if necessary - lock already held */
3607 pidlist_free(l->list);
3611 up_write(&l->rwsem);
3617 * cgroupstats_build - build and fill cgroupstats
3618 * @stats: cgroupstats to fill information into
3619 * @dentry: A dentry entry belonging to the cgroup for which stats have
3622 * Build and fill cgroupstats so that taskstats can export it to user
3625 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3628 struct cgroup *cgrp;
3629 struct css_task_iter it;
3630 struct task_struct *tsk;
3633 * Validate dentry by checking the superblock operations,
3634 * and make sure it's a directory.
3636 if (dentry->d_sb->s_op != &cgroup_ops ||
3637 !S_ISDIR(dentry->d_inode->i_mode))
3641 cgrp = dentry->d_fsdata;
3643 css_task_iter_start(&cgrp->dummy_css, &it);
3644 while ((tsk = css_task_iter_next(&it))) {
3645 switch (tsk->state) {
3647 stats->nr_running++;
3649 case TASK_INTERRUPTIBLE:
3650 stats->nr_sleeping++;
3652 case TASK_UNINTERRUPTIBLE:
3653 stats->nr_uninterruptible++;
3656 stats->nr_stopped++;
3659 if (delayacct_is_task_waiting_on_io(tsk))
3660 stats->nr_io_wait++;
3664 css_task_iter_end(&it);
3672 * seq_file methods for the tasks/procs files. The seq_file position is the
3673 * next pid to display; the seq_file iterator is a pointer to the pid
3674 * in the cgroup->l->list array.
3677 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3680 * Initially we receive a position value that corresponds to
3681 * one more than the last pid shown (or 0 on the first call or
3682 * after a seek to the start). Use a binary-search to find the
3683 * next pid to display, if any
3685 struct cgroup_pidlist *l = s->private;
3686 int index = 0, pid = *pos;
3689 down_read(&l->rwsem);
3691 int end = l->length;
3693 while (index < end) {
3694 int mid = (index + end) / 2;
3695 if (l->list[mid] == pid) {
3698 } else if (l->list[mid] <= pid)
3704 /* If we're off the end of the array, we're done */
3705 if (index >= l->length)
3707 /* Update the abstract position to be the actual pid that we found */
3708 iter = l->list + index;
3713 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3715 struct cgroup_pidlist *l = s->private;
3719 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3721 struct cgroup_pidlist *l = s->private;
3723 pid_t *end = l->list + l->length;
3725 * Advance to the next pid in the array. If this goes off the
3737 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3739 return seq_printf(s, "%d\n", *(int *)v);
3743 * seq_operations functions for iterating on pidlists through seq_file -
3744 * independent of whether it's tasks or procs
3746 static const struct seq_operations cgroup_pidlist_seq_operations = {
3747 .start = cgroup_pidlist_start,
3748 .stop = cgroup_pidlist_stop,
3749 .next = cgroup_pidlist_next,
3750 .show = cgroup_pidlist_show,
3753 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
3756 * the case where we're the last user of this particular pidlist will
3757 * have us remove it from the cgroup's list, which entails taking the
3758 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3759 * pidlist_mutex, we have to take pidlist_mutex first.
3761 mutex_lock(&l->owner->pidlist_mutex);
3762 down_write(&l->rwsem);
3763 BUG_ON(!l->use_count);
3764 if (!--l->use_count) {
3765 /* we're the last user if refcount is 0; remove and free */
3766 list_del(&l->links);
3767 mutex_unlock(&l->owner->pidlist_mutex);
3768 pidlist_free(l->list);
3769 put_pid_ns(l->key.ns);
3770 up_write(&l->rwsem);
3774 mutex_unlock(&l->owner->pidlist_mutex);
3775 up_write(&l->rwsem);
3778 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
3780 struct cgroup_pidlist *l;
3781 if (!(file->f_mode & FMODE_READ))
3784 * the seq_file will only be initialized if the file was opened for
3785 * reading; hence we check if it's not null only in that case.
3787 l = ((struct seq_file *)file->private_data)->private;
3788 cgroup_release_pid_array(l);
3789 return seq_release(inode, file);
3792 static const struct file_operations cgroup_pidlist_operations = {
3794 .llseek = seq_lseek,
3795 .write = cgroup_file_write,
3796 .release = cgroup_pidlist_release,
3800 * The following functions handle opens on a file that displays a pidlist
3801 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3804 /* helper function for the two below it */
3805 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
3807 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
3808 struct cgroup_pidlist *l;
3811 /* Nothing to do for write-only files */
3812 if (!(file->f_mode & FMODE_READ))
3815 /* have the array populated */
3816 retval = pidlist_array_load(cgrp, type, &l);
3819 /* configure file information */
3820 file->f_op = &cgroup_pidlist_operations;
3822 retval = seq_open(file, &cgroup_pidlist_seq_operations);
3824 cgroup_release_pid_array(l);
3827 ((struct seq_file *)file->private_data)->private = l;
3830 static int cgroup_tasks_open(struct inode *unused, struct file *file)
3832 return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
3834 static int cgroup_procs_open(struct inode *unused, struct file *file)
3836 return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
3839 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3842 return notify_on_release(css->cgroup);
3845 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3846 struct cftype *cft, u64 val)
3848 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3850 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3852 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3857 * When dput() is called asynchronously, if umount has been done and
3858 * then deactivate_super() in cgroup_free_fn() kills the superblock,
3859 * there's a small window that vfs will see the root dentry with non-zero
3860 * refcnt and trigger BUG().
3862 * That's why we hold a reference before dput() and drop it right after.
3864 static void cgroup_dput(struct cgroup *cgrp)
3866 struct super_block *sb = cgrp->root->sb;
3868 atomic_inc(&sb->s_active);
3870 deactivate_super(sb);
3873 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3876 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3879 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3880 struct cftype *cft, u64 val)
3883 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3885 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3889 static struct cftype cgroup_base_files[] = {
3891 .name = "cgroup.procs",
3892 .open = cgroup_procs_open,
3893 .write_u64 = cgroup_procs_write,
3894 .release = cgroup_pidlist_release,
3895 .mode = S_IRUGO | S_IWUSR,
3898 .name = "cgroup.clone_children",
3899 .flags = CFTYPE_INSANE,
3900 .read_u64 = cgroup_clone_children_read,
3901 .write_u64 = cgroup_clone_children_write,
3904 .name = "cgroup.sane_behavior",
3905 .flags = CFTYPE_ONLY_ON_ROOT,
3906 .read_seq_string = cgroup_sane_behavior_show,
3910 * Historical crazy stuff. These don't have "cgroup." prefix and
3911 * don't exist if sane_behavior. If you're depending on these, be
3912 * prepared to be burned.
3916 .flags = CFTYPE_INSANE, /* use "procs" instead */
3917 .open = cgroup_tasks_open,
3918 .write_u64 = cgroup_tasks_write,
3919 .release = cgroup_pidlist_release,
3920 .mode = S_IRUGO | S_IWUSR,
3923 .name = "notify_on_release",
3924 .flags = CFTYPE_INSANE,
3925 .read_u64 = cgroup_read_notify_on_release,
3926 .write_u64 = cgroup_write_notify_on_release,
3929 .name = "release_agent",
3930 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
3931 .read_seq_string = cgroup_release_agent_show,
3932 .write_string = cgroup_release_agent_write,
3933 .max_write_len = PATH_MAX,
3939 * cgroup_populate_dir - create subsys files in a cgroup directory
3940 * @cgrp: target cgroup
3941 * @subsys_mask: mask of the subsystem ids whose files should be added
3943 * On failure, no file is added.
3945 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
3947 struct cgroup_subsys *ss;
3950 /* process cftsets of each subsystem */
3951 for_each_subsys(ss, i) {
3952 struct cftype_set *set;
3954 if (!test_bit(i, &subsys_mask))
3957 list_for_each_entry(set, &ss->cftsets, node) {
3958 ret = cgroup_addrm_files(cgrp, set->cfts, true);
3965 cgroup_clear_dir(cgrp, subsys_mask);
3970 * css destruction is four-stage process.
3972 * 1. Destruction starts. Killing of the percpu_ref is initiated.
3973 * Implemented in kill_css().
3975 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
3976 * and thus css_tryget() is guaranteed to fail, the css can be offlined
3977 * by invoking offline_css(). After offlining, the base ref is put.
3978 * Implemented in css_killed_work_fn().
3980 * 3. When the percpu_ref reaches zero, the only possible remaining
3981 * accessors are inside RCU read sections. css_release() schedules the
3984 * 4. After the grace period, the css can be freed. Implemented in
3985 * css_free_work_fn().
3987 * It is actually hairier because both step 2 and 4 require process context
3988 * and thus involve punting to css->destroy_work adding two additional
3989 * steps to the already complex sequence.
3991 static void css_free_work_fn(struct work_struct *work)
3993 struct cgroup_subsys_state *css =
3994 container_of(work, struct cgroup_subsys_state, destroy_work);
3995 struct cgroup *cgrp = css->cgroup;
3998 css_put(css->parent);
4000 css->ss->css_free(css);
4004 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4006 struct cgroup_subsys_state *css =
4007 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4010 * css holds an extra ref to @cgrp->dentry which is put on the last
4011 * css_put(). dput() requires process context which we don't have.
4013 INIT_WORK(&css->destroy_work, css_free_work_fn);
4014 queue_work(cgroup_destroy_wq, &css->destroy_work);
4017 static void css_release(struct percpu_ref *ref)
4019 struct cgroup_subsys_state *css =
4020 container_of(ref, struct cgroup_subsys_state, refcnt);
4022 call_rcu(&css->rcu_head, css_free_rcu_fn);
4025 static void init_css(struct cgroup_subsys_state *css, struct cgroup_subsys *ss,
4026 struct cgroup *cgrp)
4033 css->parent = cgroup_css(cgrp->parent, ss);
4035 css->flags |= CSS_ROOT;
4037 BUG_ON(cgroup_css(cgrp, ss));
4040 /* invoke ->css_online() on a new CSS and mark it online if successful */
4041 static int online_css(struct cgroup_subsys_state *css)
4043 struct cgroup_subsys *ss = css->ss;
4046 lockdep_assert_held(&cgroup_mutex);
4049 ret = ss->css_online(css);
4051 css->flags |= CSS_ONLINE;
4052 css->cgroup->nr_css++;
4053 rcu_assign_pointer(css->cgroup->subsys[ss->subsys_id], css);
4058 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4059 static void offline_css(struct cgroup_subsys_state *css)
4061 struct cgroup_subsys *ss = css->ss;
4063 lockdep_assert_held(&cgroup_mutex);
4065 if (!(css->flags & CSS_ONLINE))
4068 if (ss->css_offline)
4069 ss->css_offline(css);
4071 css->flags &= ~CSS_ONLINE;
4072 css->cgroup->nr_css--;
4073 RCU_INIT_POINTER(css->cgroup->subsys[ss->subsys_id], css);
4077 * cgroup_create - create a cgroup
4078 * @parent: cgroup that will be parent of the new cgroup
4079 * @dentry: dentry of the new cgroup
4080 * @mode: mode to set on new inode
4082 * Must be called with the mutex on the parent inode held
4084 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4087 struct cgroup_subsys_state *css_ar[CGROUP_SUBSYS_COUNT] = { };
4088 struct cgroup *cgrp;
4089 struct cgroup_name *name;
4090 struct cgroupfs_root *root = parent->root;
4092 struct cgroup_subsys *ss;
4093 struct super_block *sb = root->sb;
4095 /* allocate the cgroup and its ID, 0 is reserved for the root */
4096 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4100 name = cgroup_alloc_name(dentry);
4103 rcu_assign_pointer(cgrp->name, name);
4106 * Temporarily set the pointer to NULL, so idr_find() won't return
4107 * a half-baked cgroup.
4109 cgrp->id = idr_alloc(&root->cgroup_idr, NULL, 1, 0, GFP_KERNEL);
4114 * Only live parents can have children. Note that the liveliness
4115 * check isn't strictly necessary because cgroup_mkdir() and
4116 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4117 * anyway so that locking is contained inside cgroup proper and we
4118 * don't get nasty surprises if we ever grow another caller.
4120 if (!cgroup_lock_live_group(parent)) {
4125 /* Grab a reference on the superblock so the hierarchy doesn't
4126 * get deleted on unmount if there are child cgroups. This
4127 * can be done outside cgroup_mutex, since the sb can't
4128 * disappear while someone has an open control file on the
4130 atomic_inc(&sb->s_active);
4132 init_cgroup_housekeeping(cgrp);
4134 dentry->d_fsdata = cgrp;
4135 cgrp->dentry = dentry;
4137 cgrp->parent = parent;
4138 cgrp->dummy_css.parent = &parent->dummy_css;
4139 cgrp->root = parent->root;
4141 if (notify_on_release(parent))
4142 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4144 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4145 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4147 for_each_root_subsys(root, ss) {
4148 struct cgroup_subsys_state *css;
4150 css = ss->css_alloc(cgroup_css(parent, ss));
4155 css_ar[ss->subsys_id] = css;
4157 err = percpu_ref_init(&css->refcnt, css_release);
4161 init_css(css, ss, cgrp);
4165 * Create directory. cgroup_create_file() returns with the new
4166 * directory locked on success so that it can be populated without
4167 * dropping cgroup_mutex.
4169 err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4172 lockdep_assert_held(&dentry->d_inode->i_mutex);
4174 cgrp->serial_nr = cgroup_serial_nr_next++;
4176 /* allocation complete, commit to creation */
4177 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4178 root->number_of_cgroups++;
4180 /* each css holds a ref to the cgroup's dentry and the parent css */
4181 for_each_root_subsys(root, ss) {
4182 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4185 css_get(css->parent);
4188 /* hold a ref to the parent's dentry */
4189 dget(parent->dentry);
4191 /* creation succeeded, notify subsystems */
4192 for_each_root_subsys(root, ss) {
4193 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4195 err = online_css(css);
4199 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4201 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",
4202 current->comm, current->pid, ss->name);
4203 if (!strcmp(ss->name, "memory"))
4204 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4205 ss->warned_broken_hierarchy = true;
4209 idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4211 err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
4215 err = cgroup_populate_dir(cgrp, root->subsys_mask);
4219 mutex_unlock(&cgroup_mutex);
4220 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4225 for_each_root_subsys(root, ss) {
4226 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4229 percpu_ref_cancel_init(&css->refcnt);
4233 mutex_unlock(&cgroup_mutex);
4234 /* Release the reference count that we took on the superblock */
4235 deactivate_super(sb);
4237 idr_remove(&root->cgroup_idr, cgrp->id);
4239 kfree(rcu_dereference_raw(cgrp->name));
4245 cgroup_destroy_locked(cgrp);
4246 mutex_unlock(&cgroup_mutex);
4247 mutex_unlock(&dentry->d_inode->i_mutex);
4251 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4253 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4255 /* the vfs holds inode->i_mutex already */
4256 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4260 * This is called when the refcnt of a css is confirmed to be killed.
4261 * css_tryget() is now guaranteed to fail.
4263 static void css_killed_work_fn(struct work_struct *work)
4265 struct cgroup_subsys_state *css =
4266 container_of(work, struct cgroup_subsys_state, destroy_work);
4267 struct cgroup *cgrp = css->cgroup;
4269 mutex_lock(&cgroup_mutex);
4272 * css_tryget() is guaranteed to fail now. Tell subsystems to
4273 * initate destruction.
4278 * If @cgrp is marked dead, it's waiting for refs of all css's to
4279 * be disabled before proceeding to the second phase of cgroup
4280 * destruction. If we are the last one, kick it off.
4282 if (!cgrp->nr_css && cgroup_is_dead(cgrp))
4283 cgroup_destroy_css_killed(cgrp);
4285 mutex_unlock(&cgroup_mutex);
4288 * Put the css refs from kill_css(). Each css holds an extra
4289 * reference to the cgroup's dentry and cgroup removal proceeds
4290 * regardless of css refs. On the last put of each css, whenever
4291 * that may be, the extra dentry ref is put so that dentry
4292 * destruction happens only after all css's are released.
4297 /* css kill confirmation processing requires process context, bounce */
4298 static void css_killed_ref_fn(struct percpu_ref *ref)
4300 struct cgroup_subsys_state *css =
4301 container_of(ref, struct cgroup_subsys_state, refcnt);
4303 INIT_WORK(&css->destroy_work, css_killed_work_fn);
4304 queue_work(cgroup_destroy_wq, &css->destroy_work);
4308 * kill_css - destroy a css
4309 * @css: css to destroy
4311 * This function initiates destruction of @css by removing cgroup interface
4312 * files and putting its base reference. ->css_offline() will be invoked
4313 * asynchronously once css_tryget() is guaranteed to fail and when the
4314 * reference count reaches zero, @css will be released.
4316 static void kill_css(struct cgroup_subsys_state *css)
4318 cgroup_clear_dir(css->cgroup, 1 << css->ss->subsys_id);
4321 * Killing would put the base ref, but we need to keep it alive
4322 * until after ->css_offline().
4327 * cgroup core guarantees that, by the time ->css_offline() is
4328 * invoked, no new css reference will be given out via
4329 * css_tryget(). We can't simply call percpu_ref_kill() and
4330 * proceed to offlining css's because percpu_ref_kill() doesn't
4331 * guarantee that the ref is seen as killed on all CPUs on return.
4333 * Use percpu_ref_kill_and_confirm() to get notifications as each
4334 * css is confirmed to be seen as killed on all CPUs.
4336 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4340 * cgroup_destroy_locked - the first stage of cgroup destruction
4341 * @cgrp: cgroup to be destroyed
4343 * css's make use of percpu refcnts whose killing latency shouldn't be
4344 * exposed to userland and are RCU protected. Also, cgroup core needs to
4345 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
4346 * invoked. To satisfy all the requirements, destruction is implemented in
4347 * the following two steps.
4349 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4350 * userland visible parts and start killing the percpu refcnts of
4351 * css's. Set up so that the next stage will be kicked off once all
4352 * the percpu refcnts are confirmed to be killed.
4354 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4355 * rest of destruction. Once all cgroup references are gone, the
4356 * cgroup is RCU-freed.
4358 * This function implements s1. After this step, @cgrp is gone as far as
4359 * the userland is concerned and a new cgroup with the same name may be
4360 * created. As cgroup doesn't care about the names internally, this
4361 * doesn't cause any problem.
4363 static int cgroup_destroy_locked(struct cgroup *cgrp)
4364 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4366 struct dentry *d = cgrp->dentry;
4367 struct cgroup_subsys *ss;
4368 struct cgroup *child;
4371 lockdep_assert_held(&d->d_inode->i_mutex);
4372 lockdep_assert_held(&cgroup_mutex);
4375 * css_set_lock synchronizes access to ->cset_links and prevents
4376 * @cgrp from being removed while __put_css_set() is in progress.
4378 read_lock(&css_set_lock);
4379 empty = list_empty(&cgrp->cset_links);
4380 read_unlock(&css_set_lock);
4385 * Make sure there's no live children. We can't test ->children
4386 * emptiness as dead children linger on it while being destroyed;
4387 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
4391 list_for_each_entry_rcu(child, &cgrp->children, sibling) {
4392 empty = cgroup_is_dead(child);
4401 * Initiate massacre of all css's. cgroup_destroy_css_killed()
4402 * will be invoked to perform the rest of destruction once the
4403 * percpu refs of all css's are confirmed to be killed.
4405 for_each_root_subsys(cgrp->root, ss)
4406 kill_css(cgroup_css(cgrp, ss));
4409 * Mark @cgrp dead. This prevents further task migration and child
4410 * creation by disabling cgroup_lock_live_group(). Note that
4411 * CGRP_DEAD assertion is depended upon by css_next_child() to
4412 * resume iteration after dropping RCU read lock. See
4413 * css_next_child() for details.
4415 set_bit(CGRP_DEAD, &cgrp->flags);
4417 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4418 raw_spin_lock(&release_list_lock);
4419 if (!list_empty(&cgrp->release_list))
4420 list_del_init(&cgrp->release_list);
4421 raw_spin_unlock(&release_list_lock);
4424 * If @cgrp has css's attached, the second stage of cgroup
4425 * destruction is kicked off from css_killed_work_fn() after the
4426 * refs of all attached css's are killed. If @cgrp doesn't have
4427 * any css, we kick it off here.
4430 cgroup_destroy_css_killed(cgrp);
4433 * Clear the base files and remove @cgrp directory. The removal
4434 * puts the base ref but we aren't quite done with @cgrp yet, so
4437 cgroup_addrm_files(cgrp, cgroup_base_files, false);
4439 cgroup_d_remove_dir(d);
4445 * cgroup_destroy_css_killed - the second step of cgroup destruction
4446 * @work: cgroup->destroy_free_work
4448 * This function is invoked from a work item for a cgroup which is being
4449 * destroyed after all css's are offlined and performs the rest of
4450 * destruction. This is the second step of destruction described in the
4451 * comment above cgroup_destroy_locked().
4453 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
4455 struct cgroup *parent = cgrp->parent;
4456 struct dentry *d = cgrp->dentry;
4458 lockdep_assert_held(&cgroup_mutex);
4460 /* delete this cgroup from parent->children */
4461 list_del_rcu(&cgrp->sibling);
4464 * We should remove the cgroup object from idr before its grace
4465 * period starts, so we won't be looking up a cgroup while the
4466 * cgroup is being freed.
4468 idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4473 set_bit(CGRP_RELEASABLE, &parent->flags);
4474 check_for_release(parent);
4477 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4481 mutex_lock(&cgroup_mutex);
4482 ret = cgroup_destroy_locked(dentry->d_fsdata);
4483 mutex_unlock(&cgroup_mutex);
4488 static void __init_or_module cgroup_init_cftsets(struct cgroup_subsys *ss)
4490 INIT_LIST_HEAD(&ss->cftsets);
4493 * base_cftset is embedded in subsys itself, no need to worry about
4496 if (ss->base_cftypes) {
4499 for (cft = ss->base_cftypes; cft->name[0] != '\0'; cft++)
4502 ss->base_cftset.cfts = ss->base_cftypes;
4503 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4507 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4509 struct cgroup_subsys_state *css;
4511 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4513 mutex_lock(&cgroup_mutex);
4515 /* init base cftset */
4516 cgroup_init_cftsets(ss);
4518 /* Create the top cgroup state for this subsystem */
4519 list_add(&ss->sibling, &cgroup_dummy_root.subsys_list);
4520 ss->root = &cgroup_dummy_root;
4521 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
4522 /* We don't handle early failures gracefully */
4523 BUG_ON(IS_ERR(css));
4524 init_css(css, ss, cgroup_dummy_top);
4526 /* Update the init_css_set to contain a subsys
4527 * pointer to this state - since the subsystem is
4528 * newly registered, all tasks and hence the
4529 * init_css_set is in the subsystem's top cgroup. */
4530 init_css_set.subsys[ss->subsys_id] = css;
4532 need_forkexit_callback |= ss->fork || ss->exit;
4534 /* At system boot, before all subsystems have been
4535 * registered, no tasks have been forked, so we don't
4536 * need to invoke fork callbacks here. */
4537 BUG_ON(!list_empty(&init_task.tasks));
4539 BUG_ON(online_css(css));
4541 mutex_unlock(&cgroup_mutex);
4543 /* this function shouldn't be used with modular subsystems, since they
4544 * need to register a subsys_id, among other things */
4549 * cgroup_load_subsys: load and register a modular subsystem at runtime
4550 * @ss: the subsystem to load
4552 * This function should be called in a modular subsystem's initcall. If the
4553 * subsystem is built as a module, it will be assigned a new subsys_id and set
4554 * up for use. If the subsystem is built-in anyway, work is delegated to the
4555 * simpler cgroup_init_subsys.
4557 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
4559 struct cgroup_subsys_state *css;
4561 struct hlist_node *tmp;
4562 struct css_set *cset;
4565 /* check name and function validity */
4566 if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
4567 ss->css_alloc == NULL || ss->css_free == NULL)
4571 * we don't support callbacks in modular subsystems. this check is
4572 * before the ss->module check for consistency; a subsystem that could
4573 * be a module should still have no callbacks even if the user isn't
4574 * compiling it as one.
4576 if (ss->fork || ss->exit)
4580 * an optionally modular subsystem is built-in: we want to do nothing,
4581 * since cgroup_init_subsys will have already taken care of it.
4583 if (ss->module == NULL) {
4584 /* a sanity check */
4585 BUG_ON(cgroup_subsys[ss->subsys_id] != ss);
4589 /* init base cftset */
4590 cgroup_init_cftsets(ss);
4592 mutex_lock(&cgroup_mutex);
4593 cgroup_subsys[ss->subsys_id] = ss;
4596 * no ss->css_alloc seems to need anything important in the ss
4597 * struct, so this can happen first (i.e. before the dummy root
4600 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
4602 /* failure case - need to deassign the cgroup_subsys[] slot. */
4603 cgroup_subsys[ss->subsys_id] = NULL;
4604 mutex_unlock(&cgroup_mutex);
4605 return PTR_ERR(css);
4608 list_add(&ss->sibling, &cgroup_dummy_root.subsys_list);
4609 ss->root = &cgroup_dummy_root;
4611 /* our new subsystem will be attached to the dummy hierarchy. */
4612 init_css(css, ss, cgroup_dummy_top);
4615 * Now we need to entangle the css into the existing css_sets. unlike
4616 * in cgroup_init_subsys, there are now multiple css_sets, so each one
4617 * will need a new pointer to it; done by iterating the css_set_table.
4618 * furthermore, modifying the existing css_sets will corrupt the hash
4619 * table state, so each changed css_set will need its hash recomputed.
4620 * this is all done under the css_set_lock.
4622 write_lock(&css_set_lock);
4623 hash_for_each_safe(css_set_table, i, tmp, cset, hlist) {
4624 /* skip entries that we already rehashed */
4625 if (cset->subsys[ss->subsys_id])
4627 /* remove existing entry */
4628 hash_del(&cset->hlist);
4630 cset->subsys[ss->subsys_id] = css;
4631 /* recompute hash and restore entry */
4632 key = css_set_hash(cset->subsys);
4633 hash_add(css_set_table, &cset->hlist, key);
4635 write_unlock(&css_set_lock);
4637 ret = online_css(css);
4642 mutex_unlock(&cgroup_mutex);
4646 mutex_unlock(&cgroup_mutex);
4647 /* @ss can't be mounted here as try_module_get() would fail */
4648 cgroup_unload_subsys(ss);
4651 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
4654 * cgroup_unload_subsys: unload a modular subsystem
4655 * @ss: the subsystem to unload
4657 * This function should be called in a modular subsystem's exitcall. When this
4658 * function is invoked, the refcount on the subsystem's module will be 0, so
4659 * the subsystem will not be attached to any hierarchy.
4661 void cgroup_unload_subsys(struct cgroup_subsys *ss)
4663 struct cgrp_cset_link *link;
4665 BUG_ON(ss->module == NULL);
4668 * we shouldn't be called if the subsystem is in use, and the use of
4669 * try_module_get() in rebind_subsystems() should ensure that it
4670 * doesn't start being used while we're killing it off.
4672 BUG_ON(ss->root != &cgroup_dummy_root);
4674 mutex_lock(&cgroup_mutex);
4676 offline_css(cgroup_css(cgroup_dummy_top, ss));
4678 /* deassign the subsys_id */
4679 cgroup_subsys[ss->subsys_id] = NULL;
4681 /* remove subsystem from the dummy root's list of subsystems */
4682 list_del_init(&ss->sibling);
4685 * disentangle the css from all css_sets attached to the dummy
4686 * top. as in loading, we need to pay our respects to the hashtable
4689 write_lock(&css_set_lock);
4690 list_for_each_entry(link, &cgroup_dummy_top->cset_links, cset_link) {
4691 struct css_set *cset = link->cset;
4694 hash_del(&cset->hlist);
4695 cset->subsys[ss->subsys_id] = NULL;
4696 key = css_set_hash(cset->subsys);
4697 hash_add(css_set_table, &cset->hlist, key);
4699 write_unlock(&css_set_lock);
4702 * remove subsystem's css from the cgroup_dummy_top and free it -
4703 * need to free before marking as null because ss->css_free needs
4704 * the cgrp->subsys pointer to find their state.
4706 ss->css_free(cgroup_css(cgroup_dummy_top, ss));
4707 RCU_INIT_POINTER(cgroup_dummy_top->subsys[ss->subsys_id], NULL);
4709 mutex_unlock(&cgroup_mutex);
4711 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
4714 * cgroup_init_early - cgroup initialization at system boot
4716 * Initialize cgroups at system boot, and initialize any
4717 * subsystems that request early init.
4719 int __init cgroup_init_early(void)
4721 struct cgroup_subsys *ss;
4724 atomic_set(&init_css_set.refcount, 1);
4725 INIT_LIST_HEAD(&init_css_set.cgrp_links);
4726 INIT_LIST_HEAD(&init_css_set.tasks);
4727 INIT_HLIST_NODE(&init_css_set.hlist);
4729 init_cgroup_root(&cgroup_dummy_root);
4730 cgroup_root_count = 1;
4731 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4733 init_cgrp_cset_link.cset = &init_css_set;
4734 init_cgrp_cset_link.cgrp = cgroup_dummy_top;
4735 list_add(&init_cgrp_cset_link.cset_link, &cgroup_dummy_top->cset_links);
4736 list_add(&init_cgrp_cset_link.cgrp_link, &init_css_set.cgrp_links);
4738 /* at bootup time, we don't worry about modular subsystems */
4739 for_each_builtin_subsys(ss, i) {
4741 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
4742 BUG_ON(!ss->css_alloc);
4743 BUG_ON(!ss->css_free);
4744 if (ss->subsys_id != i) {
4745 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
4746 ss->name, ss->subsys_id);
4751 cgroup_init_subsys(ss);
4757 * cgroup_init - cgroup initialization
4759 * Register cgroup filesystem and /proc file, and initialize
4760 * any subsystems that didn't request early init.
4762 int __init cgroup_init(void)
4764 struct cgroup_subsys *ss;
4768 err = bdi_init(&cgroup_backing_dev_info);
4772 for_each_builtin_subsys(ss, i) {
4773 if (!ss->early_init)
4774 cgroup_init_subsys(ss);
4777 /* allocate id for the dummy hierarchy */
4778 mutex_lock(&cgroup_mutex);
4779 mutex_lock(&cgroup_root_mutex);
4781 /* Add init_css_set to the hash table */
4782 key = css_set_hash(init_css_set.subsys);
4783 hash_add(css_set_table, &init_css_set.hlist, key);
4785 BUG_ON(cgroup_init_root_id(&cgroup_dummy_root, 0, 1));
4787 err = idr_alloc(&cgroup_dummy_root.cgroup_idr, cgroup_dummy_top,
4791 mutex_unlock(&cgroup_root_mutex);
4792 mutex_unlock(&cgroup_mutex);
4794 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4800 err = register_filesystem(&cgroup_fs_type);
4802 kobject_put(cgroup_kobj);
4806 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4810 bdi_destroy(&cgroup_backing_dev_info);
4815 static int __init cgroup_wq_init(void)
4818 * There isn't much point in executing destruction path in
4819 * parallel. Good chunk is serialized with cgroup_mutex anyway.
4820 * Use 1 for @max_active.
4822 * We would prefer to do this in cgroup_init() above, but that
4823 * is called before init_workqueues(): so leave this until after.
4825 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
4826 BUG_ON(!cgroup_destroy_wq);
4829 core_initcall(cgroup_wq_init);
4832 * proc_cgroup_show()
4833 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4834 * - Used for /proc/<pid>/cgroup.
4835 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4836 * doesn't really matter if tsk->cgroup changes after we read it,
4837 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4838 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4839 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4840 * cgroup to top_cgroup.
4843 /* TODO: Use a proper seq_file iterator */
4844 int proc_cgroup_show(struct seq_file *m, void *v)
4847 struct task_struct *tsk;
4850 struct cgroupfs_root *root;
4853 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4859 tsk = get_pid_task(pid, PIDTYPE_PID);
4865 mutex_lock(&cgroup_mutex);
4867 for_each_active_root(root) {
4868 struct cgroup_subsys *ss;
4869 struct cgroup *cgrp;
4872 seq_printf(m, "%d:", root->hierarchy_id);
4873 for_each_root_subsys(root, ss)
4874 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4875 if (strlen(root->name))
4876 seq_printf(m, "%sname=%s", count ? "," : "",
4879 cgrp = task_cgroup_from_root(tsk, root);
4880 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
4888 mutex_unlock(&cgroup_mutex);
4889 put_task_struct(tsk);
4896 /* Display information about each subsystem and each hierarchy */
4897 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4899 struct cgroup_subsys *ss;
4902 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4904 * ideally we don't want subsystems moving around while we do this.
4905 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4906 * subsys/hierarchy state.
4908 mutex_lock(&cgroup_mutex);
4910 for_each_subsys(ss, i)
4911 seq_printf(m, "%s\t%d\t%d\t%d\n",
4912 ss->name, ss->root->hierarchy_id,
4913 ss->root->number_of_cgroups, !ss->disabled);
4915 mutex_unlock(&cgroup_mutex);
4919 static int cgroupstats_open(struct inode *inode, struct file *file)
4921 return single_open(file, proc_cgroupstats_show, NULL);
4924 static const struct file_operations proc_cgroupstats_operations = {
4925 .open = cgroupstats_open,
4927 .llseek = seq_lseek,
4928 .release = single_release,
4932 * cgroup_fork - attach newly forked task to its parents cgroup.
4933 * @child: pointer to task_struct of forking parent process.
4935 * Description: A task inherits its parent's cgroup at fork().
4937 * A pointer to the shared css_set was automatically copied in
4938 * fork.c by dup_task_struct(). However, we ignore that copy, since
4939 * it was not made under the protection of RCU or cgroup_mutex, so
4940 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
4941 * have already changed current->cgroups, allowing the previously
4942 * referenced cgroup group to be removed and freed.
4944 * At the point that cgroup_fork() is called, 'current' is the parent
4945 * task, and the passed argument 'child' points to the child task.
4947 void cgroup_fork(struct task_struct *child)
4950 get_css_set(task_css_set(current));
4951 child->cgroups = current->cgroups;
4952 task_unlock(current);
4953 INIT_LIST_HEAD(&child->cg_list);
4957 * cgroup_post_fork - called on a new task after adding it to the task list
4958 * @child: the task in question
4960 * Adds the task to the list running through its css_set if necessary and
4961 * call the subsystem fork() callbacks. Has to be after the task is
4962 * visible on the task list in case we race with the first call to
4963 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
4966 void cgroup_post_fork(struct task_struct *child)
4968 struct cgroup_subsys *ss;
4972 * use_task_css_set_links is set to 1 before we walk the tasklist
4973 * under the tasklist_lock and we read it here after we added the child
4974 * to the tasklist under the tasklist_lock as well. If the child wasn't
4975 * yet in the tasklist when we walked through it from
4976 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4977 * should be visible now due to the paired locking and barriers implied
4978 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4979 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4982 if (use_task_css_set_links) {
4983 write_lock(&css_set_lock);
4985 if (list_empty(&child->cg_list))
4986 list_add(&child->cg_list, &task_css_set(child)->tasks);
4988 write_unlock(&css_set_lock);
4992 * Call ss->fork(). This must happen after @child is linked on
4993 * css_set; otherwise, @child might change state between ->fork()
4994 * and addition to css_set.
4996 if (need_forkexit_callback) {
4998 * fork/exit callbacks are supported only for builtin
4999 * subsystems, and the builtin section of the subsys
5000 * array is immutable, so we don't need to lock the
5001 * subsys array here. On the other hand, modular section
5002 * of the array can be freed at module unload, so we
5005 for_each_builtin_subsys(ss, i)
5012 * cgroup_exit - detach cgroup from exiting task
5013 * @tsk: pointer to task_struct of exiting process
5014 * @run_callback: run exit callbacks?
5016 * Description: Detach cgroup from @tsk and release it.
5018 * Note that cgroups marked notify_on_release force every task in
5019 * them to take the global cgroup_mutex mutex when exiting.
5020 * This could impact scaling on very large systems. Be reluctant to
5021 * use notify_on_release cgroups where very high task exit scaling
5022 * is required on large systems.
5024 * the_top_cgroup_hack:
5026 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
5028 * We call cgroup_exit() while the task is still competent to
5029 * handle notify_on_release(), then leave the task attached to the
5030 * root cgroup in each hierarchy for the remainder of its exit.
5032 * To do this properly, we would increment the reference count on
5033 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
5034 * code we would add a second cgroup function call, to drop that
5035 * reference. This would just create an unnecessary hot spot on
5036 * the top_cgroup reference count, to no avail.
5038 * Normally, holding a reference to a cgroup without bumping its
5039 * count is unsafe. The cgroup could go away, or someone could
5040 * attach us to a different cgroup, decrementing the count on
5041 * the first cgroup that we never incremented. But in this case,
5042 * top_cgroup isn't going away, and either task has PF_EXITING set,
5043 * which wards off any cgroup_attach_task() attempts, or task is a failed
5044 * fork, never visible to cgroup_attach_task.
5046 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
5048 struct cgroup_subsys *ss;
5049 struct css_set *cset;
5053 * Unlink from the css_set task list if necessary.
5054 * Optimistically check cg_list before taking
5057 if (!list_empty(&tsk->cg_list)) {
5058 write_lock(&css_set_lock);
5059 if (!list_empty(&tsk->cg_list))
5060 list_del_init(&tsk->cg_list);
5061 write_unlock(&css_set_lock);
5064 /* Reassign the task to the init_css_set. */
5066 cset = task_css_set(tsk);
5067 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
5069 if (run_callbacks && need_forkexit_callback) {
5071 * fork/exit callbacks are supported only for builtin
5072 * subsystems, see cgroup_post_fork() for details.
5074 for_each_builtin_subsys(ss, i) {
5076 struct cgroup_subsys_state *old_css = cset->subsys[i];
5077 struct cgroup_subsys_state *css = task_css(tsk, i);
5079 ss->exit(css, old_css, tsk);
5085 put_css_set_taskexit(cset);
5088 static void check_for_release(struct cgroup *cgrp)
5090 if (cgroup_is_releasable(cgrp) &&
5091 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
5093 * Control Group is currently removeable. If it's not
5094 * already queued for a userspace notification, queue
5097 int need_schedule_work = 0;
5099 raw_spin_lock(&release_list_lock);
5100 if (!cgroup_is_dead(cgrp) &&
5101 list_empty(&cgrp->release_list)) {
5102 list_add(&cgrp->release_list, &release_list);
5103 need_schedule_work = 1;
5105 raw_spin_unlock(&release_list_lock);
5106 if (need_schedule_work)
5107 schedule_work(&release_agent_work);
5112 * Notify userspace when a cgroup is released, by running the
5113 * configured release agent with the name of the cgroup (path
5114 * relative to the root of cgroup file system) as the argument.
5116 * Most likely, this user command will try to rmdir this cgroup.
5118 * This races with the possibility that some other task will be
5119 * attached to this cgroup before it is removed, or that some other
5120 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5121 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5122 * unused, and this cgroup will be reprieved from its death sentence,
5123 * to continue to serve a useful existence. Next time it's released,
5124 * we will get notified again, if it still has 'notify_on_release' set.
5126 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5127 * means only wait until the task is successfully execve()'d. The
5128 * separate release agent task is forked by call_usermodehelper(),
5129 * then control in this thread returns here, without waiting for the
5130 * release agent task. We don't bother to wait because the caller of
5131 * this routine has no use for the exit status of the release agent
5132 * task, so no sense holding our caller up for that.
5134 static void cgroup_release_agent(struct work_struct *work)
5136 BUG_ON(work != &release_agent_work);
5137 mutex_lock(&cgroup_mutex);
5138 raw_spin_lock(&release_list_lock);
5139 while (!list_empty(&release_list)) {
5140 char *argv[3], *envp[3];
5142 char *pathbuf = NULL, *agentbuf = NULL;
5143 struct cgroup *cgrp = list_entry(release_list.next,
5146 list_del_init(&cgrp->release_list);
5147 raw_spin_unlock(&release_list_lock);
5148 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5151 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
5153 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5158 argv[i++] = agentbuf;
5159 argv[i++] = pathbuf;
5163 /* minimal command environment */
5164 envp[i++] = "HOME=/";
5165 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5168 /* Drop the lock while we invoke the usermode helper,
5169 * since the exec could involve hitting disk and hence
5170 * be a slow process */
5171 mutex_unlock(&cgroup_mutex);
5172 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5173 mutex_lock(&cgroup_mutex);
5177 raw_spin_lock(&release_list_lock);
5179 raw_spin_unlock(&release_list_lock);
5180 mutex_unlock(&cgroup_mutex);
5183 static int __init cgroup_disable(char *str)
5185 struct cgroup_subsys *ss;
5189 while ((token = strsep(&str, ",")) != NULL) {
5194 * cgroup_disable, being at boot time, can't know about
5195 * module subsystems, so we don't worry about them.
5197 for_each_builtin_subsys(ss, i) {
5198 if (!strcmp(token, ss->name)) {
5200 printk(KERN_INFO "Disabling %s control group"
5201 " subsystem\n", ss->name);
5208 __setup("cgroup_disable=", cgroup_disable);
5211 * css_from_dir - get corresponding css from the dentry of a cgroup dir
5212 * @dentry: directory dentry of interest
5213 * @ss: subsystem of interest
5215 * Must be called under RCU read lock. The caller is responsible for
5216 * pinning the returned css if it needs to be accessed outside the RCU
5219 struct cgroup_subsys_state *css_from_dir(struct dentry *dentry,
5220 struct cgroup_subsys *ss)
5222 struct cgroup *cgrp;
5224 WARN_ON_ONCE(!rcu_read_lock_held());
5226 /* is @dentry a cgroup dir? */
5227 if (!dentry->d_inode ||
5228 dentry->d_inode->i_op != &cgroup_dir_inode_operations)
5229 return ERR_PTR(-EBADF);
5231 cgrp = __d_cgrp(dentry);
5232 return cgroup_css(cgrp, ss) ?: ERR_PTR(-ENOENT);
5236 * css_from_id - lookup css by id
5237 * @id: the cgroup id
5238 * @ss: cgroup subsys to be looked into
5240 * Returns the css if there's valid one with @id, otherwise returns NULL.
5241 * Should be called under rcu_read_lock().
5243 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5245 struct cgroup *cgrp;
5247 rcu_lockdep_assert(rcu_read_lock_held() ||
5248 lockdep_is_held(&cgroup_mutex),
5249 "css_from_id() needs proper protection");
5251 cgrp = idr_find(&ss->root->cgroup_idr, id);
5253 return cgroup_css(cgrp, ss);
5257 #ifdef CONFIG_CGROUP_DEBUG
5258 static struct cgroup_subsys_state *
5259 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5261 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5264 return ERR_PTR(-ENOMEM);
5269 static void debug_css_free(struct cgroup_subsys_state *css)
5274 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5277 return cgroup_task_count(css->cgroup);
5280 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5283 return (u64)(unsigned long)current->cgroups;
5286 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5292 count = atomic_read(&task_css_set(current)->refcount);
5297 static int current_css_set_cg_links_read(struct cgroup_subsys_state *css,
5299 struct seq_file *seq)
5301 struct cgrp_cset_link *link;
5302 struct css_set *cset;
5304 read_lock(&css_set_lock);
5306 cset = rcu_dereference(current->cgroups);
5307 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5308 struct cgroup *c = link->cgrp;
5312 name = c->dentry->d_name.name;
5315 seq_printf(seq, "Root %d group %s\n",
5316 c->root->hierarchy_id, name);
5319 read_unlock(&css_set_lock);
5323 #define MAX_TASKS_SHOWN_PER_CSS 25
5324 static int cgroup_css_links_read(struct cgroup_subsys_state *css,
5325 struct cftype *cft, struct seq_file *seq)
5327 struct cgrp_cset_link *link;
5329 read_lock(&css_set_lock);
5330 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5331 struct css_set *cset = link->cset;
5332 struct task_struct *task;
5334 seq_printf(seq, "css_set %p\n", cset);
5335 list_for_each_entry(task, &cset->tasks, cg_list) {
5336 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5337 seq_puts(seq, " ...\n");
5340 seq_printf(seq, " task %d\n",
5341 task_pid_vnr(task));
5345 read_unlock(&css_set_lock);
5349 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5351 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
5354 static struct cftype debug_files[] = {
5356 .name = "taskcount",
5357 .read_u64 = debug_taskcount_read,
5361 .name = "current_css_set",
5362 .read_u64 = current_css_set_read,
5366 .name = "current_css_set_refcount",
5367 .read_u64 = current_css_set_refcount_read,
5371 .name = "current_css_set_cg_links",
5372 .read_seq_string = current_css_set_cg_links_read,
5376 .name = "cgroup_css_links",
5377 .read_seq_string = cgroup_css_links_read,
5381 .name = "releasable",
5382 .read_u64 = releasable_read,
5388 struct cgroup_subsys debug_subsys = {
5390 .css_alloc = debug_css_alloc,
5391 .css_free = debug_css_free,
5392 .subsys_id = debug_subsys_id,
5393 .base_cftypes = debug_files,
5395 #endif /* CONFIG_CGROUP_DEBUG */