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[],
169 static int cgroup_file_release(struct inode *inode, struct file *file);
172 * cgroup_css - obtain a cgroup's css for the specified subsystem
173 * @cgrp: the cgroup of interest
174 * @ss: the subsystem of interest (%NULL returns the dummy_css)
176 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
177 * function must be called either under cgroup_mutex or rcu_read_lock() and
178 * the caller is responsible for pinning the returned css if it wants to
179 * keep accessing it outside the said locks. This function may return
180 * %NULL if @cgrp doesn't have @subsys_id enabled.
182 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
183 struct cgroup_subsys *ss)
186 return rcu_dereference_check(cgrp->subsys[ss->subsys_id],
187 lockdep_is_held(&cgroup_mutex));
189 return &cgrp->dummy_css;
192 /* convenient tests for these bits */
193 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
195 return test_bit(CGRP_DEAD, &cgrp->flags);
199 * cgroup_is_descendant - test ancestry
200 * @cgrp: the cgroup to be tested
201 * @ancestor: possible ancestor of @cgrp
203 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
204 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
205 * and @ancestor are accessible.
207 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
210 if (cgrp == ancestor)
216 EXPORT_SYMBOL_GPL(cgroup_is_descendant);
218 static int cgroup_is_releasable(const struct cgroup *cgrp)
221 (1 << CGRP_RELEASABLE) |
222 (1 << CGRP_NOTIFY_ON_RELEASE);
223 return (cgrp->flags & bits) == bits;
226 static int notify_on_release(const struct cgroup *cgrp)
228 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
232 * for_each_subsys - iterate all loaded cgroup subsystems
233 * @ss: the iteration cursor
234 * @i: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
236 * Should be called under cgroup_mutex.
238 #define for_each_subsys(ss, i) \
239 for ((i) = 0; (i) < CGROUP_SUBSYS_COUNT; (i)++) \
240 if (({ lockdep_assert_held(&cgroup_mutex); \
241 !((ss) = cgroup_subsys[i]); })) { } \
245 * for_each_builtin_subsys - iterate all built-in cgroup subsystems
246 * @ss: the iteration cursor
247 * @i: the index of @ss, CGROUP_BUILTIN_SUBSYS_COUNT after reaching the end
249 * Bulit-in subsystems are always present and iteration itself doesn't
250 * require any synchronization.
252 #define for_each_builtin_subsys(ss, i) \
253 for ((i) = 0; (i) < CGROUP_BUILTIN_SUBSYS_COUNT && \
254 (((ss) = cgroup_subsys[i]) || true); (i)++)
256 /* iterate each subsystem attached to a hierarchy */
257 #define for_each_root_subsys(root, ss) \
258 list_for_each_entry((ss), &(root)->subsys_list, sibling)
260 /* iterate across the active hierarchies */
261 #define for_each_active_root(root) \
262 list_for_each_entry((root), &cgroup_roots, root_list)
264 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
266 return dentry->d_fsdata;
269 static inline struct cfent *__d_cfe(struct dentry *dentry)
271 return dentry->d_fsdata;
274 static inline struct cftype *__d_cft(struct dentry *dentry)
276 return __d_cfe(dentry)->type;
280 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
281 * @cgrp: the cgroup to be checked for liveness
283 * On success, returns true; the mutex should be later unlocked. On
284 * failure returns false with no lock held.
286 static bool cgroup_lock_live_group(struct cgroup *cgrp)
288 mutex_lock(&cgroup_mutex);
289 if (cgroup_is_dead(cgrp)) {
290 mutex_unlock(&cgroup_mutex);
296 /* the list of cgroups eligible for automatic release. Protected by
297 * release_list_lock */
298 static LIST_HEAD(release_list);
299 static DEFINE_RAW_SPINLOCK(release_list_lock);
300 static void cgroup_release_agent(struct work_struct *work);
301 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
302 static void check_for_release(struct cgroup *cgrp);
305 * A cgroup can be associated with multiple css_sets as different tasks may
306 * belong to different cgroups on different hierarchies. In the other
307 * direction, a css_set is naturally associated with multiple cgroups.
308 * This M:N relationship is represented by the following link structure
309 * which exists for each association and allows traversing the associations
312 struct cgrp_cset_link {
313 /* the cgroup and css_set this link associates */
315 struct css_set *cset;
317 /* list of cgrp_cset_links anchored at cgrp->cset_links */
318 struct list_head cset_link;
320 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
321 struct list_head cgrp_link;
324 /* The default css_set - used by init and its children prior to any
325 * hierarchies being mounted. It contains a pointer to the root state
326 * for each subsystem. Also used to anchor the list of css_sets. Not
327 * reference-counted, to improve performance when child cgroups
328 * haven't been created.
331 static struct css_set init_css_set;
332 static struct cgrp_cset_link init_cgrp_cset_link;
335 * css_set_lock protects the list of css_set objects, and the chain of
336 * tasks off each css_set. Nests outside task->alloc_lock due to
337 * css_task_iter_start().
339 static DEFINE_RWLOCK(css_set_lock);
340 static int css_set_count;
343 * hash table for cgroup groups. This improves the performance to find
344 * an existing css_set. This hash doesn't (currently) take into
345 * account cgroups in empty hierarchies.
347 #define CSS_SET_HASH_BITS 7
348 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
350 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
352 unsigned long key = 0UL;
353 struct cgroup_subsys *ss;
356 for_each_subsys(ss, i)
357 key += (unsigned long)css[i];
358 key = (key >> 16) ^ key;
364 * We don't maintain the lists running through each css_set to its task
365 * until after the first call to css_task_iter_start(). This reduces the
366 * fork()/exit() overhead for people who have cgroups compiled into their
367 * kernel but not actually in use.
369 static int use_task_css_set_links __read_mostly;
371 static void __put_css_set(struct css_set *cset, int taskexit)
373 struct cgrp_cset_link *link, *tmp_link;
376 * Ensure that the refcount doesn't hit zero while any readers
377 * can see it. Similar to atomic_dec_and_lock(), but for an
380 if (atomic_add_unless(&cset->refcount, -1, 1))
382 write_lock(&css_set_lock);
383 if (!atomic_dec_and_test(&cset->refcount)) {
384 write_unlock(&css_set_lock);
388 /* This css_set is dead. unlink it and release cgroup refcounts */
389 hash_del(&cset->hlist);
392 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
393 struct cgroup *cgrp = link->cgrp;
395 list_del(&link->cset_link);
396 list_del(&link->cgrp_link);
398 /* @cgrp can't go away while we're holding css_set_lock */
399 if (list_empty(&cgrp->cset_links) && notify_on_release(cgrp)) {
401 set_bit(CGRP_RELEASABLE, &cgrp->flags);
402 check_for_release(cgrp);
408 write_unlock(&css_set_lock);
409 kfree_rcu(cset, rcu_head);
413 * refcounted get/put for css_set objects
415 static inline void get_css_set(struct css_set *cset)
417 atomic_inc(&cset->refcount);
420 static inline void put_css_set(struct css_set *cset)
422 __put_css_set(cset, 0);
425 static inline void put_css_set_taskexit(struct css_set *cset)
427 __put_css_set(cset, 1);
431 * compare_css_sets - helper function for find_existing_css_set().
432 * @cset: candidate css_set being tested
433 * @old_cset: existing css_set for a task
434 * @new_cgrp: cgroup that's being entered by the task
435 * @template: desired set of css pointers in css_set (pre-calculated)
437 * Returns true if "cset" matches "old_cset" except for the hierarchy
438 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
440 static bool compare_css_sets(struct css_set *cset,
441 struct css_set *old_cset,
442 struct cgroup *new_cgrp,
443 struct cgroup_subsys_state *template[])
445 struct list_head *l1, *l2;
447 if (memcmp(template, cset->subsys, sizeof(cset->subsys))) {
448 /* Not all subsystems matched */
453 * Compare cgroup pointers in order to distinguish between
454 * different cgroups in heirarchies with no subsystems. We
455 * could get by with just this check alone (and skip the
456 * memcmp above) but on most setups the memcmp check will
457 * avoid the need for this more expensive check on almost all
461 l1 = &cset->cgrp_links;
462 l2 = &old_cset->cgrp_links;
464 struct cgrp_cset_link *link1, *link2;
465 struct cgroup *cgrp1, *cgrp2;
469 /* See if we reached the end - both lists are equal length. */
470 if (l1 == &cset->cgrp_links) {
471 BUG_ON(l2 != &old_cset->cgrp_links);
474 BUG_ON(l2 == &old_cset->cgrp_links);
476 /* Locate the cgroups associated with these links. */
477 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
478 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
481 /* Hierarchies should be linked in the same order. */
482 BUG_ON(cgrp1->root != cgrp2->root);
485 * If this hierarchy is the hierarchy of the cgroup
486 * that's changing, then we need to check that this
487 * css_set points to the new cgroup; if it's any other
488 * hierarchy, then this css_set should point to the
489 * same cgroup as the old css_set.
491 if (cgrp1->root == new_cgrp->root) {
492 if (cgrp1 != new_cgrp)
503 * find_existing_css_set - init css array and find the matching css_set
504 * @old_cset: the css_set that we're using before the cgroup transition
505 * @cgrp: the cgroup that we're moving into
506 * @template: out param for the new set of csses, should be clear on entry
508 static struct css_set *find_existing_css_set(struct css_set *old_cset,
510 struct cgroup_subsys_state *template[])
512 struct cgroupfs_root *root = cgrp->root;
513 struct cgroup_subsys *ss;
514 struct css_set *cset;
519 * Build the set of subsystem state objects that we want to see in the
520 * new css_set. while subsystems can change globally, the entries here
521 * won't change, so no need for locking.
523 for_each_subsys(ss, i) {
524 if (root->subsys_mask & (1UL << i)) {
525 /* Subsystem is in this hierarchy. So we want
526 * the subsystem state from the new
528 template[i] = cgroup_css(cgrp, ss);
530 /* Subsystem is not in this hierarchy, so we
531 * don't want to change the subsystem state */
532 template[i] = old_cset->subsys[i];
536 key = css_set_hash(template);
537 hash_for_each_possible(css_set_table, cset, hlist, key) {
538 if (!compare_css_sets(cset, old_cset, cgrp, template))
541 /* This css_set matches what we need */
545 /* No existing cgroup group matched */
549 static void free_cgrp_cset_links(struct list_head *links_to_free)
551 struct cgrp_cset_link *link, *tmp_link;
553 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
554 list_del(&link->cset_link);
560 * allocate_cgrp_cset_links - allocate cgrp_cset_links
561 * @count: the number of links to allocate
562 * @tmp_links: list_head the allocated links are put on
564 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
565 * through ->cset_link. Returns 0 on success or -errno.
567 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
569 struct cgrp_cset_link *link;
572 INIT_LIST_HEAD(tmp_links);
574 for (i = 0; i < count; i++) {
575 link = kzalloc(sizeof(*link), GFP_KERNEL);
577 free_cgrp_cset_links(tmp_links);
580 list_add(&link->cset_link, tmp_links);
586 * link_css_set - a helper function to link a css_set to a cgroup
587 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
588 * @cset: the css_set to be linked
589 * @cgrp: the destination cgroup
591 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
594 struct cgrp_cset_link *link;
596 BUG_ON(list_empty(tmp_links));
597 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
600 list_move(&link->cset_link, &cgrp->cset_links);
602 * Always add links to the tail of the list so that the list
603 * is sorted by order of hierarchy creation
605 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
609 * find_css_set - return a new css_set with one cgroup updated
610 * @old_cset: the baseline css_set
611 * @cgrp: the cgroup to be updated
613 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
614 * substituted into the appropriate hierarchy.
616 static struct css_set *find_css_set(struct css_set *old_cset,
619 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
620 struct css_set *cset;
621 struct list_head tmp_links;
622 struct cgrp_cset_link *link;
625 lockdep_assert_held(&cgroup_mutex);
627 /* First see if we already have a cgroup group that matches
629 read_lock(&css_set_lock);
630 cset = find_existing_css_set(old_cset, cgrp, template);
633 read_unlock(&css_set_lock);
638 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
642 /* Allocate all the cgrp_cset_link objects that we'll need */
643 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
648 atomic_set(&cset->refcount, 1);
649 INIT_LIST_HEAD(&cset->cgrp_links);
650 INIT_LIST_HEAD(&cset->tasks);
651 INIT_HLIST_NODE(&cset->hlist);
653 /* Copy the set of subsystem state objects generated in
654 * find_existing_css_set() */
655 memcpy(cset->subsys, template, sizeof(cset->subsys));
657 write_lock(&css_set_lock);
658 /* Add reference counts and links from the new css_set. */
659 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
660 struct cgroup *c = link->cgrp;
662 if (c->root == cgrp->root)
664 link_css_set(&tmp_links, cset, c);
667 BUG_ON(!list_empty(&tmp_links));
671 /* Add this cgroup group to the hash table */
672 key = css_set_hash(cset->subsys);
673 hash_add(css_set_table, &cset->hlist, key);
675 write_unlock(&css_set_lock);
681 * Return the cgroup for "task" from the given hierarchy. Must be
682 * called with cgroup_mutex held.
684 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
685 struct cgroupfs_root *root)
687 struct css_set *cset;
688 struct cgroup *res = NULL;
690 BUG_ON(!mutex_is_locked(&cgroup_mutex));
691 read_lock(&css_set_lock);
693 * No need to lock the task - since we hold cgroup_mutex the
694 * task can't change groups, so the only thing that can happen
695 * is that it exits and its css is set back to init_css_set.
697 cset = task_css_set(task);
698 if (cset == &init_css_set) {
699 res = &root->top_cgroup;
701 struct cgrp_cset_link *link;
703 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
704 struct cgroup *c = link->cgrp;
706 if (c->root == root) {
712 read_unlock(&css_set_lock);
718 * There is one global cgroup mutex. We also require taking
719 * task_lock() when dereferencing a task's cgroup subsys pointers.
720 * See "The task_lock() exception", at the end of this comment.
722 * A task must hold cgroup_mutex to modify cgroups.
724 * Any task can increment and decrement the count field without lock.
725 * So in general, code holding cgroup_mutex can't rely on the count
726 * field not changing. However, if the count goes to zero, then only
727 * cgroup_attach_task() can increment it again. Because a count of zero
728 * means that no tasks are currently attached, therefore there is no
729 * way a task attached to that cgroup can fork (the other way to
730 * increment the count). So code holding cgroup_mutex can safely
731 * assume that if the count is zero, it will stay zero. Similarly, if
732 * a task holds cgroup_mutex on a cgroup with zero count, it
733 * knows that the cgroup won't be removed, as cgroup_rmdir()
736 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
737 * (usually) take cgroup_mutex. These are the two most performance
738 * critical pieces of code here. The exception occurs on cgroup_exit(),
739 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
740 * is taken, and if the cgroup count is zero, a usermode call made
741 * to the release agent with the name of the cgroup (path relative to
742 * the root of cgroup file system) as the argument.
744 * A cgroup can only be deleted if both its 'count' of using tasks
745 * is zero, and its list of 'children' cgroups is empty. Since all
746 * tasks in the system use _some_ cgroup, and since there is always at
747 * least one task in the system (init, pid == 1), therefore, top_cgroup
748 * always has either children cgroups and/or using tasks. So we don't
749 * need a special hack to ensure that top_cgroup cannot be deleted.
751 * The task_lock() exception
753 * The need for this exception arises from the action of
754 * cgroup_attach_task(), which overwrites one task's cgroup pointer with
755 * another. It does so using cgroup_mutex, however there are
756 * several performance critical places that need to reference
757 * task->cgroup without the expense of grabbing a system global
758 * mutex. Therefore except as noted below, when dereferencing or, as
759 * in cgroup_attach_task(), modifying a task's cgroup pointer we use
760 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
761 * the task_struct routinely used for such matters.
763 * P.S. One more locking exception. RCU is used to guard the
764 * update of a tasks cgroup pointer by cgroup_attach_task()
768 * A couple of forward declarations required, due to cyclic reference loop:
769 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
770 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
774 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode);
775 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
776 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask);
777 static const struct inode_operations cgroup_dir_inode_operations;
778 static const struct file_operations proc_cgroupstats_operations;
780 static struct backing_dev_info cgroup_backing_dev_info = {
782 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
785 static struct inode *cgroup_new_inode(umode_t mode, struct super_block *sb)
787 struct inode *inode = new_inode(sb);
790 inode->i_ino = get_next_ino();
791 inode->i_mode = mode;
792 inode->i_uid = current_fsuid();
793 inode->i_gid = current_fsgid();
794 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
795 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
800 static struct cgroup_name *cgroup_alloc_name(struct dentry *dentry)
802 struct cgroup_name *name;
804 name = kmalloc(sizeof(*name) + dentry->d_name.len + 1, GFP_KERNEL);
807 strcpy(name->name, dentry->d_name.name);
811 static void cgroup_free_fn(struct work_struct *work)
813 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
815 mutex_lock(&cgroup_mutex);
816 cgrp->root->number_of_cgroups--;
817 mutex_unlock(&cgroup_mutex);
820 * We get a ref to the parent's dentry, and put the ref when
821 * this cgroup is being freed, so it's guaranteed that the
822 * parent won't be destroyed before its children.
824 dput(cgrp->parent->dentry);
827 * Drop the active superblock reference that we took when we
828 * created the cgroup. This will free cgrp->root, if we are
829 * holding the last reference to @sb.
831 deactivate_super(cgrp->root->sb);
834 * if we're getting rid of the cgroup, refcount should ensure
835 * that there are no pidlists left.
837 BUG_ON(!list_empty(&cgrp->pidlists));
839 simple_xattrs_free(&cgrp->xattrs);
841 kfree(rcu_dereference_raw(cgrp->name));
845 static void cgroup_free_rcu(struct rcu_head *head)
847 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
849 INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
850 queue_work(cgroup_destroy_wq, &cgrp->destroy_work);
853 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
855 /* is dentry a directory ? if so, kfree() associated cgroup */
856 if (S_ISDIR(inode->i_mode)) {
857 struct cgroup *cgrp = dentry->d_fsdata;
859 BUG_ON(!(cgroup_is_dead(cgrp)));
860 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
862 struct cfent *cfe = __d_cfe(dentry);
863 struct cgroup *cgrp = dentry->d_parent->d_fsdata;
865 WARN_ONCE(!list_empty(&cfe->node) &&
866 cgrp != &cgrp->root->top_cgroup,
867 "cfe still linked for %s\n", cfe->type->name);
868 simple_xattrs_free(&cfe->xattrs);
874 static void remove_dir(struct dentry *d)
876 struct dentry *parent = dget(d->d_parent);
879 simple_rmdir(parent->d_inode, d);
883 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
887 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
888 lockdep_assert_held(&cgroup_mutex);
891 * If we're doing cleanup due to failure of cgroup_create(),
892 * the corresponding @cfe may not exist.
894 list_for_each_entry(cfe, &cgrp->files, node) {
895 struct dentry *d = cfe->dentry;
897 if (cft && cfe->type != cft)
902 simple_unlink(cgrp->dentry->d_inode, d);
903 list_del_init(&cfe->node);
911 * cgroup_clear_dir - remove subsys files in a cgroup directory
912 * @cgrp: target cgroup
913 * @subsys_mask: mask of the subsystem ids whose files should be removed
915 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned long subsys_mask)
917 struct cgroup_subsys *ss;
920 for_each_subsys(ss, i) {
921 struct cftype_set *set;
923 if (!test_bit(i, &subsys_mask))
925 list_for_each_entry(set, &ss->cftsets, node)
926 cgroup_addrm_files(cgrp, set->cfts, false);
931 * NOTE : the dentry must have been dget()'ed
933 static void cgroup_d_remove_dir(struct dentry *dentry)
935 struct dentry *parent;
937 parent = dentry->d_parent;
938 spin_lock(&parent->d_lock);
939 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
940 list_del_init(&dentry->d_u.d_child);
941 spin_unlock(&dentry->d_lock);
942 spin_unlock(&parent->d_lock);
947 * Call with cgroup_mutex held. Drops reference counts on modules, including
948 * any duplicate ones that parse_cgroupfs_options took. If this function
949 * returns an error, no reference counts are touched.
951 static int rebind_subsystems(struct cgroupfs_root *root,
952 unsigned long added_mask, unsigned removed_mask)
954 struct cgroup *cgrp = &root->top_cgroup;
955 struct cgroup_subsys *ss;
956 unsigned long pinned = 0;
959 BUG_ON(!mutex_is_locked(&cgroup_mutex));
960 BUG_ON(!mutex_is_locked(&cgroup_root_mutex));
962 /* Check that any added subsystems are currently free */
963 for_each_subsys(ss, i) {
964 if (!(added_mask & (1 << i)))
967 /* is the subsystem mounted elsewhere? */
968 if (ss->root != &cgroup_dummy_root) {
974 if (!try_module_get(ss->module)) {
981 /* subsys could be missing if unloaded between parsing and here */
982 if (added_mask != pinned) {
987 ret = cgroup_populate_dir(cgrp, added_mask);
992 * Nothing can fail from this point on. Remove files for the
993 * removed subsystems and rebind each subsystem.
995 cgroup_clear_dir(cgrp, removed_mask);
997 for_each_subsys(ss, i) {
998 unsigned long bit = 1UL << i;
1000 if (bit & added_mask) {
1001 /* We're binding this subsystem to this hierarchy */
1002 BUG_ON(cgroup_css(cgrp, ss));
1003 BUG_ON(!cgroup_css(cgroup_dummy_top, ss));
1004 BUG_ON(cgroup_css(cgroup_dummy_top, ss)->cgroup != cgroup_dummy_top);
1006 rcu_assign_pointer(cgrp->subsys[i],
1007 cgroup_css(cgroup_dummy_top, ss));
1008 cgroup_css(cgrp, ss)->cgroup = cgrp;
1010 list_move(&ss->sibling, &root->subsys_list);
1013 ss->bind(cgroup_css(cgrp, ss));
1015 /* refcount was already taken, and we're keeping it */
1016 root->subsys_mask |= bit;
1017 } else if (bit & removed_mask) {
1018 /* We're removing this subsystem */
1019 BUG_ON(cgroup_css(cgrp, ss) != cgroup_css(cgroup_dummy_top, ss));
1020 BUG_ON(cgroup_css(cgrp, ss)->cgroup != cgrp);
1023 ss->bind(cgroup_css(cgroup_dummy_top, ss));
1025 cgroup_css(cgroup_dummy_top, ss)->cgroup = cgroup_dummy_top;
1026 RCU_INIT_POINTER(cgrp->subsys[i], NULL);
1028 cgroup_subsys[i]->root = &cgroup_dummy_root;
1029 list_move(&ss->sibling, &cgroup_dummy_root.subsys_list);
1031 /* subsystem is now free - drop reference on module */
1032 module_put(ss->module);
1033 root->subsys_mask &= ~bit;
1038 * Mark @root has finished binding subsystems. @root->subsys_mask
1039 * now matches the bound subsystems.
1041 root->flags |= CGRP_ROOT_SUBSYS_BOUND;
1046 for_each_subsys(ss, i)
1047 if (pinned & (1 << i))
1048 module_put(ss->module);
1052 static int cgroup_show_options(struct seq_file *seq, struct dentry *dentry)
1054 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
1055 struct cgroup_subsys *ss;
1057 mutex_lock(&cgroup_root_mutex);
1058 for_each_root_subsys(root, ss)
1059 seq_printf(seq, ",%s", ss->name);
1060 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1061 seq_puts(seq, ",sane_behavior");
1062 if (root->flags & CGRP_ROOT_NOPREFIX)
1063 seq_puts(seq, ",noprefix");
1064 if (root->flags & CGRP_ROOT_XATTR)
1065 seq_puts(seq, ",xattr");
1066 if (strlen(root->release_agent_path))
1067 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1068 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1069 seq_puts(seq, ",clone_children");
1070 if (strlen(root->name))
1071 seq_printf(seq, ",name=%s", root->name);
1072 mutex_unlock(&cgroup_root_mutex);
1076 struct cgroup_sb_opts {
1077 unsigned long subsys_mask;
1078 unsigned long flags;
1079 char *release_agent;
1080 bool cpuset_clone_children;
1082 /* User explicitly requested empty subsystem */
1085 struct cgroupfs_root *new_root;
1090 * Convert a hierarchy specifier into a bitmask of subsystems and
1091 * flags. Call with cgroup_mutex held to protect the cgroup_subsys[]
1092 * array. This function takes refcounts on subsystems to be used, unless it
1093 * returns error, in which case no refcounts are taken.
1095 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1097 char *token, *o = data;
1098 bool all_ss = false, one_ss = false;
1099 unsigned long mask = (unsigned long)-1;
1100 struct cgroup_subsys *ss;
1103 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1105 #ifdef CONFIG_CPUSETS
1106 mask = ~(1UL << cpuset_subsys_id);
1109 memset(opts, 0, sizeof(*opts));
1111 while ((token = strsep(&o, ",")) != NULL) {
1114 if (!strcmp(token, "none")) {
1115 /* Explicitly have no subsystems */
1119 if (!strcmp(token, "all")) {
1120 /* Mutually exclusive option 'all' + subsystem name */
1126 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1127 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1130 if (!strcmp(token, "noprefix")) {
1131 opts->flags |= CGRP_ROOT_NOPREFIX;
1134 if (!strcmp(token, "clone_children")) {
1135 opts->cpuset_clone_children = true;
1138 if (!strcmp(token, "xattr")) {
1139 opts->flags |= CGRP_ROOT_XATTR;
1142 if (!strncmp(token, "release_agent=", 14)) {
1143 /* Specifying two release agents is forbidden */
1144 if (opts->release_agent)
1146 opts->release_agent =
1147 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1148 if (!opts->release_agent)
1152 if (!strncmp(token, "name=", 5)) {
1153 const char *name = token + 5;
1154 /* Can't specify an empty name */
1157 /* Must match [\w.-]+ */
1158 for (i = 0; i < strlen(name); i++) {
1162 if ((c == '.') || (c == '-') || (c == '_'))
1166 /* Specifying two names is forbidden */
1169 opts->name = kstrndup(name,
1170 MAX_CGROUP_ROOT_NAMELEN - 1,
1178 for_each_subsys(ss, i) {
1179 if (strcmp(token, ss->name))
1184 /* Mutually exclusive option 'all' + subsystem name */
1187 set_bit(i, &opts->subsys_mask);
1192 if (i == CGROUP_SUBSYS_COUNT)
1197 * If the 'all' option was specified select all the subsystems,
1198 * otherwise if 'none', 'name=' and a subsystem name options
1199 * were not specified, let's default to 'all'
1201 if (all_ss || (!one_ss && !opts->none && !opts->name))
1202 for_each_subsys(ss, i)
1204 set_bit(i, &opts->subsys_mask);
1206 /* Consistency checks */
1208 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1209 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1211 if (opts->flags & CGRP_ROOT_NOPREFIX) {
1212 pr_err("cgroup: sane_behavior: noprefix is not allowed\n");
1216 if (opts->cpuset_clone_children) {
1217 pr_err("cgroup: sane_behavior: clone_children is not allowed\n");
1223 * Option noprefix was introduced just for backward compatibility
1224 * with the old cpuset, so we allow noprefix only if mounting just
1225 * the cpuset subsystem.
1227 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1231 /* Can't specify "none" and some subsystems */
1232 if (opts->subsys_mask && opts->none)
1236 * We either have to specify by name or by subsystems. (So all
1237 * empty hierarchies must have a name).
1239 if (!opts->subsys_mask && !opts->name)
1245 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1248 struct cgroupfs_root *root = sb->s_fs_info;
1249 struct cgroup *cgrp = &root->top_cgroup;
1250 struct cgroup_sb_opts opts;
1251 unsigned long added_mask, removed_mask;
1253 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1254 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1258 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1259 mutex_lock(&cgroup_mutex);
1260 mutex_lock(&cgroup_root_mutex);
1262 /* See what subsystems are wanted */
1263 ret = parse_cgroupfs_options(data, &opts);
1267 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1268 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1269 task_tgid_nr(current), current->comm);
1271 added_mask = opts.subsys_mask & ~root->subsys_mask;
1272 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1274 /* Don't allow flags or name to change at remount */
1275 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1276 (opts.name && strcmp(opts.name, root->name))) {
1277 pr_err("cgroup: option or name mismatch, new: 0x%lx \"%s\", old: 0x%lx \"%s\"\n",
1278 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1279 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1284 /* remounting is not allowed for populated hierarchies */
1285 if (root->number_of_cgroups > 1) {
1290 ret = rebind_subsystems(root, added_mask, removed_mask);
1294 if (opts.release_agent)
1295 strcpy(root->release_agent_path, opts.release_agent);
1297 kfree(opts.release_agent);
1299 mutex_unlock(&cgroup_root_mutex);
1300 mutex_unlock(&cgroup_mutex);
1301 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1305 static const struct super_operations cgroup_ops = {
1306 .statfs = simple_statfs,
1307 .drop_inode = generic_delete_inode,
1308 .show_options = cgroup_show_options,
1309 .remount_fs = cgroup_remount,
1312 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1314 INIT_LIST_HEAD(&cgrp->sibling);
1315 INIT_LIST_HEAD(&cgrp->children);
1316 INIT_LIST_HEAD(&cgrp->files);
1317 INIT_LIST_HEAD(&cgrp->cset_links);
1318 INIT_LIST_HEAD(&cgrp->release_list);
1319 INIT_LIST_HEAD(&cgrp->pidlists);
1320 mutex_init(&cgrp->pidlist_mutex);
1321 cgrp->dummy_css.cgroup = cgrp;
1322 simple_xattrs_init(&cgrp->xattrs);
1325 static void init_cgroup_root(struct cgroupfs_root *root)
1327 struct cgroup *cgrp = &root->top_cgroup;
1329 INIT_LIST_HEAD(&root->subsys_list);
1330 INIT_LIST_HEAD(&root->root_list);
1331 root->number_of_cgroups = 1;
1333 RCU_INIT_POINTER(cgrp->name, &root_cgroup_name);
1334 init_cgroup_housekeeping(cgrp);
1335 idr_init(&root->cgroup_idr);
1338 static int cgroup_init_root_id(struct cgroupfs_root *root, int start, int end)
1342 lockdep_assert_held(&cgroup_mutex);
1343 lockdep_assert_held(&cgroup_root_mutex);
1345 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, start, end,
1350 root->hierarchy_id = id;
1354 static void cgroup_exit_root_id(struct cgroupfs_root *root)
1356 lockdep_assert_held(&cgroup_mutex);
1357 lockdep_assert_held(&cgroup_root_mutex);
1359 if (root->hierarchy_id) {
1360 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1361 root->hierarchy_id = 0;
1365 static int cgroup_test_super(struct super_block *sb, void *data)
1367 struct cgroup_sb_opts *opts = data;
1368 struct cgroupfs_root *root = sb->s_fs_info;
1370 /* If we asked for a name then it must match */
1371 if (opts->name && strcmp(opts->name, root->name))
1375 * If we asked for subsystems (or explicitly for no
1376 * subsystems) then they must match
1378 if ((opts->subsys_mask || opts->none)
1379 && (opts->subsys_mask != root->subsys_mask))
1385 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1387 struct cgroupfs_root *root;
1389 if (!opts->subsys_mask && !opts->none)
1392 root = kzalloc(sizeof(*root), GFP_KERNEL);
1394 return ERR_PTR(-ENOMEM);
1396 init_cgroup_root(root);
1399 * We need to set @root->subsys_mask now so that @root can be
1400 * matched by cgroup_test_super() before it finishes
1401 * initialization; otherwise, competing mounts with the same
1402 * options may try to bind the same subsystems instead of waiting
1403 * for the first one leading to unexpected mount errors.
1404 * SUBSYS_BOUND will be set once actual binding is complete.
1406 root->subsys_mask = opts->subsys_mask;
1407 root->flags = opts->flags;
1408 if (opts->release_agent)
1409 strcpy(root->release_agent_path, opts->release_agent);
1411 strcpy(root->name, opts->name);
1412 if (opts->cpuset_clone_children)
1413 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1417 static void cgroup_free_root(struct cgroupfs_root *root)
1420 /* hierarhcy ID shoulid already have been released */
1421 WARN_ON_ONCE(root->hierarchy_id);
1423 idr_destroy(&root->cgroup_idr);
1428 static int cgroup_set_super(struct super_block *sb, void *data)
1431 struct cgroup_sb_opts *opts = data;
1433 /* If we don't have a new root, we can't set up a new sb */
1434 if (!opts->new_root)
1437 BUG_ON(!opts->subsys_mask && !opts->none);
1439 ret = set_anon_super(sb, NULL);
1443 sb->s_fs_info = opts->new_root;
1444 opts->new_root->sb = sb;
1446 sb->s_blocksize = PAGE_CACHE_SIZE;
1447 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1448 sb->s_magic = CGROUP_SUPER_MAGIC;
1449 sb->s_op = &cgroup_ops;
1454 static int cgroup_get_rootdir(struct super_block *sb)
1456 static const struct dentry_operations cgroup_dops = {
1457 .d_iput = cgroup_diput,
1458 .d_delete = always_delete_dentry,
1461 struct inode *inode =
1462 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1467 inode->i_fop = &simple_dir_operations;
1468 inode->i_op = &cgroup_dir_inode_operations;
1469 /* directories start off with i_nlink == 2 (for "." entry) */
1471 sb->s_root = d_make_root(inode);
1474 /* for everything else we want ->d_op set */
1475 sb->s_d_op = &cgroup_dops;
1479 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1480 int flags, const char *unused_dev_name,
1483 struct cgroup_sb_opts opts;
1484 struct cgroupfs_root *root;
1486 struct super_block *sb;
1487 struct cgroupfs_root *new_root;
1488 struct list_head tmp_links;
1489 struct inode *inode;
1490 const struct cred *cred;
1492 /* First find the desired set of subsystems */
1493 mutex_lock(&cgroup_mutex);
1494 ret = parse_cgroupfs_options(data, &opts);
1495 mutex_unlock(&cgroup_mutex);
1500 * Allocate a new cgroup root. We may not need it if we're
1501 * reusing an existing hierarchy.
1503 new_root = cgroup_root_from_opts(&opts);
1504 if (IS_ERR(new_root)) {
1505 ret = PTR_ERR(new_root);
1508 opts.new_root = new_root;
1510 /* Locate an existing or new sb for this hierarchy */
1511 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1514 cgroup_free_root(opts.new_root);
1518 root = sb->s_fs_info;
1520 if (root == opts.new_root) {
1521 /* We used the new root structure, so this is a new hierarchy */
1522 struct cgroup *root_cgrp = &root->top_cgroup;
1523 struct cgroupfs_root *existing_root;
1525 struct css_set *cset;
1527 BUG_ON(sb->s_root != NULL);
1529 ret = cgroup_get_rootdir(sb);
1531 goto drop_new_super;
1532 inode = sb->s_root->d_inode;
1534 mutex_lock(&inode->i_mutex);
1535 mutex_lock(&cgroup_mutex);
1536 mutex_lock(&cgroup_root_mutex);
1538 root_cgrp->id = idr_alloc(&root->cgroup_idr, root_cgrp,
1540 if (root_cgrp->id < 0)
1543 /* Check for name clashes with existing mounts */
1545 if (strlen(root->name))
1546 for_each_active_root(existing_root)
1547 if (!strcmp(existing_root->name, root->name))
1551 * We're accessing css_set_count without locking
1552 * css_set_lock here, but that's OK - it can only be
1553 * increased by someone holding cgroup_lock, and
1554 * that's us. The worst that can happen is that we
1555 * have some link structures left over
1557 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1561 /* ID 0 is reserved for dummy root, 1 for unified hierarchy */
1562 ret = cgroup_init_root_id(root, 2, 0);
1566 sb->s_root->d_fsdata = root_cgrp;
1567 root_cgrp->dentry = sb->s_root;
1570 * We're inside get_sb() and will call lookup_one_len() to
1571 * create the root files, which doesn't work if SELinux is
1572 * in use. The following cred dancing somehow works around
1573 * it. See 2ce9738ba ("cgroupfs: use init_cred when
1574 * populating new cgroupfs mount") for more details.
1576 cred = override_creds(&init_cred);
1578 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1582 ret = rebind_subsystems(root, root->subsys_mask, 0);
1589 * There must be no failure case after here, since rebinding
1590 * takes care of subsystems' refcounts, which are explicitly
1591 * dropped in the failure exit path.
1594 list_add(&root->root_list, &cgroup_roots);
1595 cgroup_root_count++;
1597 /* Link the top cgroup in this hierarchy into all
1598 * the css_set objects */
1599 write_lock(&css_set_lock);
1600 hash_for_each(css_set_table, i, cset, hlist)
1601 link_css_set(&tmp_links, cset, root_cgrp);
1602 write_unlock(&css_set_lock);
1604 free_cgrp_cset_links(&tmp_links);
1606 BUG_ON(!list_empty(&root_cgrp->children));
1607 BUG_ON(root->number_of_cgroups != 1);
1609 mutex_unlock(&cgroup_root_mutex);
1610 mutex_unlock(&cgroup_mutex);
1611 mutex_unlock(&inode->i_mutex);
1614 * We re-used an existing hierarchy - the new root (if
1615 * any) is not needed
1617 cgroup_free_root(opts.new_root);
1619 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1620 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1621 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1623 goto drop_new_super;
1625 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1630 kfree(opts.release_agent);
1632 return dget(sb->s_root);
1635 free_cgrp_cset_links(&tmp_links);
1636 cgroup_addrm_files(&root->top_cgroup, cgroup_base_files, false);
1639 cgroup_exit_root_id(root);
1640 mutex_unlock(&cgroup_root_mutex);
1641 mutex_unlock(&cgroup_mutex);
1642 mutex_unlock(&inode->i_mutex);
1644 deactivate_locked_super(sb);
1646 kfree(opts.release_agent);
1648 return ERR_PTR(ret);
1651 static void cgroup_kill_sb(struct super_block *sb) {
1652 struct cgroupfs_root *root = sb->s_fs_info;
1653 struct cgroup *cgrp = &root->top_cgroup;
1654 struct cgrp_cset_link *link, *tmp_link;
1659 BUG_ON(root->number_of_cgroups != 1);
1660 BUG_ON(!list_empty(&cgrp->children));
1662 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1663 mutex_lock(&cgroup_mutex);
1664 mutex_lock(&cgroup_root_mutex);
1666 /* Rebind all subsystems back to the default hierarchy */
1667 if (root->flags & CGRP_ROOT_SUBSYS_BOUND) {
1668 ret = rebind_subsystems(root, 0, root->subsys_mask);
1669 /* Shouldn't be able to fail ... */
1674 * Release all the links from cset_links to this hierarchy's
1677 write_lock(&css_set_lock);
1679 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1680 list_del(&link->cset_link);
1681 list_del(&link->cgrp_link);
1684 write_unlock(&css_set_lock);
1686 if (!list_empty(&root->root_list)) {
1687 list_del(&root->root_list);
1688 cgroup_root_count--;
1691 cgroup_exit_root_id(root);
1693 mutex_unlock(&cgroup_root_mutex);
1694 mutex_unlock(&cgroup_mutex);
1695 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1697 simple_xattrs_free(&cgrp->xattrs);
1699 kill_litter_super(sb);
1700 cgroup_free_root(root);
1703 static struct file_system_type cgroup_fs_type = {
1705 .mount = cgroup_mount,
1706 .kill_sb = cgroup_kill_sb,
1709 static struct kobject *cgroup_kobj;
1712 * cgroup_path - generate the path of a cgroup
1713 * @cgrp: the cgroup in question
1714 * @buf: the buffer to write the path into
1715 * @buflen: the length of the buffer
1717 * Writes path of cgroup into buf. Returns 0 on success, -errno on error.
1719 * We can't generate cgroup path using dentry->d_name, as accessing
1720 * dentry->name must be protected by irq-unsafe dentry->d_lock or parent
1721 * inode's i_mutex, while on the other hand cgroup_path() can be called
1722 * with some irq-safe spinlocks held.
1724 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1726 int ret = -ENAMETOOLONG;
1729 if (!cgrp->parent) {
1730 if (strlcpy(buf, "/", buflen) >= buflen)
1731 return -ENAMETOOLONG;
1735 start = buf + buflen - 1;
1740 const char *name = cgroup_name(cgrp);
1744 if ((start -= len) < buf)
1746 memcpy(start, name, len);
1752 cgrp = cgrp->parent;
1753 } while (cgrp->parent);
1755 memmove(buf, start, buf + buflen - start);
1760 EXPORT_SYMBOL_GPL(cgroup_path);
1763 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1764 * @task: target task
1765 * @buf: the buffer to write the path into
1766 * @buflen: the length of the buffer
1768 * Determine @task's cgroup on the first (the one with the lowest non-zero
1769 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1770 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1771 * cgroup controller callbacks.
1773 * Returns 0 on success, fails with -%ENAMETOOLONG if @buflen is too short.
1775 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1777 struct cgroupfs_root *root;
1778 struct cgroup *cgrp;
1779 int hierarchy_id = 1, ret = 0;
1782 return -ENAMETOOLONG;
1784 mutex_lock(&cgroup_mutex);
1786 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1789 cgrp = task_cgroup_from_root(task, root);
1790 ret = cgroup_path(cgrp, buf, buflen);
1792 /* if no hierarchy exists, everyone is in "/" */
1793 memcpy(buf, "/", 2);
1796 mutex_unlock(&cgroup_mutex);
1799 EXPORT_SYMBOL_GPL(task_cgroup_path);
1802 * Control Group taskset
1804 struct task_and_cgroup {
1805 struct task_struct *task;
1806 struct cgroup *cgrp;
1807 struct css_set *cset;
1810 struct cgroup_taskset {
1811 struct task_and_cgroup single;
1812 struct flex_array *tc_array;
1815 struct cgroup *cur_cgrp;
1819 * cgroup_taskset_first - reset taskset and return the first task
1820 * @tset: taskset of interest
1822 * @tset iteration is initialized and the first task is returned.
1824 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1826 if (tset->tc_array) {
1828 return cgroup_taskset_next(tset);
1830 tset->cur_cgrp = tset->single.cgrp;
1831 return tset->single.task;
1834 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1837 * cgroup_taskset_next - iterate to the next task in taskset
1838 * @tset: taskset of interest
1840 * Return the next task in @tset. Iteration must have been initialized
1841 * with cgroup_taskset_first().
1843 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1845 struct task_and_cgroup *tc;
1847 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1850 tc = flex_array_get(tset->tc_array, tset->idx++);
1851 tset->cur_cgrp = tc->cgrp;
1854 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1857 * cgroup_taskset_cur_css - return the matching css for the current task
1858 * @tset: taskset of interest
1859 * @subsys_id: the ID of the target subsystem
1861 * Return the css for the current (last returned) task of @tset for
1862 * subsystem specified by @subsys_id. This function must be preceded by
1863 * either cgroup_taskset_first() or cgroup_taskset_next().
1865 struct cgroup_subsys_state *cgroup_taskset_cur_css(struct cgroup_taskset *tset,
1868 return cgroup_css(tset->cur_cgrp, cgroup_subsys[subsys_id]);
1870 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_css);
1873 * cgroup_taskset_size - return the number of tasks in taskset
1874 * @tset: taskset of interest
1876 int cgroup_taskset_size(struct cgroup_taskset *tset)
1878 return tset->tc_array ? tset->tc_array_len : 1;
1880 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1884 * cgroup_task_migrate - move a task from one cgroup to another.
1886 * Must be called with cgroup_mutex and threadgroup locked.
1888 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1889 struct task_struct *tsk,
1890 struct css_set *new_cset)
1892 struct css_set *old_cset;
1895 * We are synchronized through threadgroup_lock() against PF_EXITING
1896 * setting such that we can't race against cgroup_exit() changing the
1897 * css_set to init_css_set and dropping the old one.
1899 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1900 old_cset = task_css_set(tsk);
1903 rcu_assign_pointer(tsk->cgroups, new_cset);
1906 /* Update the css_set linked lists if we're using them */
1907 write_lock(&css_set_lock);
1908 if (!list_empty(&tsk->cg_list))
1909 list_move(&tsk->cg_list, &new_cset->tasks);
1910 write_unlock(&css_set_lock);
1913 * We just gained a reference on old_cset by taking it from the
1914 * task. As trading it for new_cset is protected by cgroup_mutex,
1915 * we're safe to drop it here; it will be freed under RCU.
1917 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1918 put_css_set(old_cset);
1922 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1923 * @cgrp: the cgroup to attach to
1924 * @tsk: the task or the leader of the threadgroup to be attached
1925 * @threadgroup: attach the whole threadgroup?
1927 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
1928 * task_lock of @tsk or each thread in the threadgroup individually in turn.
1930 static int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk,
1933 int retval, i, group_size;
1934 struct cgroup_subsys *ss, *failed_ss = NULL;
1935 struct cgroupfs_root *root = cgrp->root;
1936 /* threadgroup list cursor and array */
1937 struct task_struct *leader = tsk;
1938 struct task_and_cgroup *tc;
1939 struct flex_array *group;
1940 struct cgroup_taskset tset = { };
1943 * step 0: in order to do expensive, possibly blocking operations for
1944 * every thread, we cannot iterate the thread group list, since it needs
1945 * rcu or tasklist locked. instead, build an array of all threads in the
1946 * group - group_rwsem prevents new threads from appearing, and if
1947 * threads exit, this will just be an over-estimate.
1950 group_size = get_nr_threads(tsk);
1953 /* flex_array supports very large thread-groups better than kmalloc. */
1954 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
1957 /* pre-allocate to guarantee space while iterating in rcu read-side. */
1958 retval = flex_array_prealloc(group, 0, group_size, GFP_KERNEL);
1960 goto out_free_group_list;
1964 * Prevent freeing of tasks while we take a snapshot. Tasks that are
1965 * already PF_EXITING could be freed from underneath us unless we
1966 * take an rcu_read_lock.
1970 struct task_and_cgroup ent;
1972 /* @tsk either already exited or can't exit until the end */
1973 if (tsk->flags & PF_EXITING)
1976 /* as per above, nr_threads may decrease, but not increase. */
1977 BUG_ON(i >= group_size);
1979 ent.cgrp = task_cgroup_from_root(tsk, root);
1980 /* nothing to do if this task is already in the cgroup */
1981 if (ent.cgrp == cgrp)
1984 * saying GFP_ATOMIC has no effect here because we did prealloc
1985 * earlier, but it's good form to communicate our expectations.
1987 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
1988 BUG_ON(retval != 0);
1993 } while_each_thread(leader, tsk);
1995 /* remember the number of threads in the array for later. */
1997 tset.tc_array = group;
1998 tset.tc_array_len = group_size;
2000 /* methods shouldn't be called if no task is actually migrating */
2003 goto out_free_group_list;
2006 * step 1: check that we can legitimately attach to the cgroup.
2008 for_each_root_subsys(root, ss) {
2009 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss);
2011 if (ss->can_attach) {
2012 retval = ss->can_attach(css, &tset);
2015 goto out_cancel_attach;
2021 * step 2: make sure css_sets exist for all threads to be migrated.
2022 * we use find_css_set, which allocates a new one if necessary.
2024 for (i = 0; i < group_size; i++) {
2025 struct css_set *old_cset;
2027 tc = flex_array_get(group, i);
2028 old_cset = task_css_set(tc->task);
2029 tc->cset = find_css_set(old_cset, cgrp);
2032 goto out_put_css_set_refs;
2037 * step 3: now that we're guaranteed success wrt the css_sets,
2038 * proceed to move all tasks to the new cgroup. There are no
2039 * failure cases after here, so this is the commit point.
2041 for (i = 0; i < group_size; i++) {
2042 tc = flex_array_get(group, i);
2043 cgroup_task_migrate(tc->cgrp, tc->task, tc->cset);
2045 /* nothing is sensitive to fork() after this point. */
2048 * step 4: do subsystem attach callbacks.
2050 for_each_root_subsys(root, ss) {
2051 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss);
2054 ss->attach(css, &tset);
2058 * step 5: success! and cleanup
2061 out_put_css_set_refs:
2063 for (i = 0; i < group_size; i++) {
2064 tc = flex_array_get(group, i);
2067 put_css_set(tc->cset);
2072 for_each_root_subsys(root, ss) {
2073 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss);
2075 if (ss == failed_ss)
2077 if (ss->cancel_attach)
2078 ss->cancel_attach(css, &tset);
2081 out_free_group_list:
2082 flex_array_free(group);
2087 * Find the task_struct of the task to attach by vpid and pass it along to the
2088 * function to attach either it or all tasks in its threadgroup. Will lock
2089 * cgroup_mutex and threadgroup; may take task_lock of task.
2091 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2093 struct task_struct *tsk;
2094 const struct cred *cred = current_cred(), *tcred;
2097 if (!cgroup_lock_live_group(cgrp))
2103 tsk = find_task_by_vpid(pid);
2107 goto out_unlock_cgroup;
2110 * even if we're attaching all tasks in the thread group, we
2111 * only need to check permissions on one of them.
2113 tcred = __task_cred(tsk);
2114 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2115 !uid_eq(cred->euid, tcred->uid) &&
2116 !uid_eq(cred->euid, tcred->suid)) {
2119 goto out_unlock_cgroup;
2125 tsk = tsk->group_leader;
2128 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2129 * trapped in a cpuset, or RT worker may be born in a cgroup
2130 * with no rt_runtime allocated. Just say no.
2132 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2135 goto out_unlock_cgroup;
2138 get_task_struct(tsk);
2141 threadgroup_lock(tsk);
2143 if (!thread_group_leader(tsk)) {
2145 * a race with de_thread from another thread's exec()
2146 * may strip us of our leadership, if this happens,
2147 * there is no choice but to throw this task away and
2148 * try again; this is
2149 * "double-double-toil-and-trouble-check locking".
2151 threadgroup_unlock(tsk);
2152 put_task_struct(tsk);
2153 goto retry_find_task;
2157 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2159 threadgroup_unlock(tsk);
2161 put_task_struct(tsk);
2163 mutex_unlock(&cgroup_mutex);
2168 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2169 * @from: attach to all cgroups of a given task
2170 * @tsk: the task to be attached
2172 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2174 struct cgroupfs_root *root;
2177 mutex_lock(&cgroup_mutex);
2178 for_each_active_root(root) {
2179 struct cgroup *from_cgrp = task_cgroup_from_root(from, root);
2181 retval = cgroup_attach_task(from_cgrp, tsk, false);
2185 mutex_unlock(&cgroup_mutex);
2189 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2191 static int cgroup_tasks_write(struct cgroup_subsys_state *css,
2192 struct cftype *cft, u64 pid)
2194 return attach_task_by_pid(css->cgroup, pid, false);
2197 static int cgroup_procs_write(struct cgroup_subsys_state *css,
2198 struct cftype *cft, u64 tgid)
2200 return attach_task_by_pid(css->cgroup, tgid, true);
2203 static int cgroup_release_agent_write(struct cgroup_subsys_state *css,
2204 struct cftype *cft, const char *buffer)
2206 BUILD_BUG_ON(sizeof(css->cgroup->root->release_agent_path) < PATH_MAX);
2207 if (strlen(buffer) >= PATH_MAX)
2209 if (!cgroup_lock_live_group(css->cgroup))
2211 mutex_lock(&cgroup_root_mutex);
2212 strcpy(css->cgroup->root->release_agent_path, buffer);
2213 mutex_unlock(&cgroup_root_mutex);
2214 mutex_unlock(&cgroup_mutex);
2218 static int cgroup_release_agent_show(struct cgroup_subsys_state *css,
2219 struct cftype *cft, struct seq_file *seq)
2221 struct cgroup *cgrp = css->cgroup;
2223 if (!cgroup_lock_live_group(cgrp))
2225 seq_puts(seq, cgrp->root->release_agent_path);
2226 seq_putc(seq, '\n');
2227 mutex_unlock(&cgroup_mutex);
2231 static int cgroup_sane_behavior_show(struct cgroup_subsys_state *css,
2232 struct cftype *cft, struct seq_file *seq)
2234 seq_printf(seq, "%d\n", cgroup_sane_behavior(css->cgroup));
2238 /* A buffer size big enough for numbers or short strings */
2239 #define CGROUP_LOCAL_BUFFER_SIZE 64
2241 static ssize_t cgroup_write_X64(struct cgroup_subsys_state *css,
2242 struct cftype *cft, struct file *file,
2243 const char __user *userbuf, size_t nbytes,
2244 loff_t *unused_ppos)
2246 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
2252 if (nbytes >= sizeof(buffer))
2254 if (copy_from_user(buffer, userbuf, nbytes))
2257 buffer[nbytes] = 0; /* nul-terminate */
2258 if (cft->write_u64) {
2259 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
2262 retval = cft->write_u64(css, cft, val);
2264 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
2267 retval = cft->write_s64(css, cft, val);
2274 static ssize_t cgroup_write_string(struct cgroup_subsys_state *css,
2275 struct cftype *cft, struct file *file,
2276 const char __user *userbuf, size_t nbytes,
2277 loff_t *unused_ppos)
2279 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
2281 size_t max_bytes = cft->max_write_len;
2282 char *buffer = local_buffer;
2285 max_bytes = sizeof(local_buffer) - 1;
2286 if (nbytes >= max_bytes)
2288 /* Allocate a dynamic buffer if we need one */
2289 if (nbytes >= sizeof(local_buffer)) {
2290 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2294 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2299 buffer[nbytes] = 0; /* nul-terminate */
2300 retval = cft->write_string(css, cft, strstrip(buffer));
2304 if (buffer != local_buffer)
2309 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2310 size_t nbytes, loff_t *ppos)
2312 struct cfent *cfe = __d_cfe(file->f_dentry);
2313 struct cftype *cft = __d_cft(file->f_dentry);
2314 struct cgroup_subsys_state *css = cfe->css;
2317 return cft->write(css, cft, file, buf, nbytes, ppos);
2318 if (cft->write_u64 || cft->write_s64)
2319 return cgroup_write_X64(css, cft, file, buf, nbytes, ppos);
2320 if (cft->write_string)
2321 return cgroup_write_string(css, cft, file, buf, nbytes, ppos);
2323 int ret = cft->trigger(css, (unsigned int)cft->private);
2324 return ret ? ret : nbytes;
2329 static ssize_t cgroup_read_u64(struct cgroup_subsys_state *css,
2330 struct cftype *cft, struct file *file,
2331 char __user *buf, size_t nbytes, loff_t *ppos)
2333 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2334 u64 val = cft->read_u64(css, cft);
2335 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2337 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2340 static ssize_t cgroup_read_s64(struct cgroup_subsys_state *css,
2341 struct cftype *cft, struct file *file,
2342 char __user *buf, size_t nbytes, loff_t *ppos)
2344 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2345 s64 val = cft->read_s64(css, cft);
2346 int len = sprintf(tmp, "%lld\n", (long long) val);
2348 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2351 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2352 size_t nbytes, loff_t *ppos)
2354 struct cfent *cfe = __d_cfe(file->f_dentry);
2355 struct cftype *cft = __d_cft(file->f_dentry);
2356 struct cgroup_subsys_state *css = cfe->css;
2359 return cft->read(css, cft, file, buf, nbytes, ppos);
2361 return cgroup_read_u64(css, cft, file, buf, nbytes, ppos);
2363 return cgroup_read_s64(css, cft, file, buf, nbytes, ppos);
2368 * seqfile ops/methods for returning structured data. Currently just
2369 * supports string->u64 maps, but can be extended in future.
2372 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2374 struct seq_file *sf = cb->state;
2375 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2378 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2380 struct cfent *cfe = m->private;
2381 struct cftype *cft = cfe->type;
2382 struct cgroup_subsys_state *css = cfe->css;
2384 if (cft->read_map) {
2385 struct cgroup_map_cb cb = {
2386 .fill = cgroup_map_add,
2389 return cft->read_map(css, cft, &cb);
2391 return cft->read_seq_string(css, cft, m);
2394 static const struct file_operations cgroup_seqfile_operations = {
2396 .write = cgroup_file_write,
2397 .llseek = seq_lseek,
2398 .release = cgroup_file_release,
2401 static int cgroup_file_open(struct inode *inode, struct file *file)
2403 struct cfent *cfe = __d_cfe(file->f_dentry);
2404 struct cftype *cft = __d_cft(file->f_dentry);
2405 struct cgroup *cgrp = __d_cgrp(cfe->dentry->d_parent);
2406 struct cgroup_subsys_state *css;
2409 err = generic_file_open(inode, file);
2414 * If the file belongs to a subsystem, pin the css. Will be
2415 * unpinned either on open failure or release. This ensures that
2416 * @css stays alive for all file operations.
2419 css = cgroup_css(cgrp, cft->ss);
2420 if (cft->ss && !css_tryget(css))
2428 * @cfe->css is used by read/write/close to determine the
2429 * associated css. @file->private_data would be a better place but
2430 * that's already used by seqfile. Multiple accessors may use it
2431 * simultaneously which is okay as the association never changes.
2433 WARN_ON_ONCE(cfe->css && cfe->css != css);
2436 if (cft->read_map || cft->read_seq_string) {
2437 file->f_op = &cgroup_seqfile_operations;
2438 err = single_open(file, cgroup_seqfile_show, cfe);
2439 } else if (cft->open) {
2440 err = cft->open(inode, file);
2448 static int cgroup_file_release(struct inode *inode, struct file *file)
2450 struct cfent *cfe = __d_cfe(file->f_dentry);
2451 struct cftype *cft = __d_cft(file->f_dentry);
2452 struct cgroup_subsys_state *css = cfe->css;
2456 ret = cft->release(inode, file);
2459 if (file->f_op == &cgroup_seqfile_operations)
2460 single_release(inode, file);
2465 * cgroup_rename - Only allow simple rename of directories in place.
2467 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2468 struct inode *new_dir, struct dentry *new_dentry)
2471 struct cgroup_name *name, *old_name;
2472 struct cgroup *cgrp;
2475 * It's convinient to use parent dir's i_mutex to protected
2478 lockdep_assert_held(&old_dir->i_mutex);
2480 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2482 if (new_dentry->d_inode)
2484 if (old_dir != new_dir)
2487 cgrp = __d_cgrp(old_dentry);
2490 * This isn't a proper migration and its usefulness is very
2491 * limited. Disallow if sane_behavior.
2493 if (cgroup_sane_behavior(cgrp))
2496 name = cgroup_alloc_name(new_dentry);
2500 ret = simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2506 old_name = rcu_dereference_protected(cgrp->name, true);
2507 rcu_assign_pointer(cgrp->name, name);
2509 kfree_rcu(old_name, rcu_head);
2513 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2515 if (S_ISDIR(dentry->d_inode->i_mode))
2516 return &__d_cgrp(dentry)->xattrs;
2518 return &__d_cfe(dentry)->xattrs;
2521 static inline int xattr_enabled(struct dentry *dentry)
2523 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2524 return root->flags & CGRP_ROOT_XATTR;
2527 static bool is_valid_xattr(const char *name)
2529 if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2530 !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2535 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2536 const void *val, size_t size, int flags)
2538 if (!xattr_enabled(dentry))
2540 if (!is_valid_xattr(name))
2542 return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2545 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2547 if (!xattr_enabled(dentry))
2549 if (!is_valid_xattr(name))
2551 return simple_xattr_remove(__d_xattrs(dentry), name);
2554 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2555 void *buf, size_t size)
2557 if (!xattr_enabled(dentry))
2559 if (!is_valid_xattr(name))
2561 return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2564 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2566 if (!xattr_enabled(dentry))
2568 return simple_xattr_list(__d_xattrs(dentry), buf, size);
2571 static const struct file_operations cgroup_file_operations = {
2572 .read = cgroup_file_read,
2573 .write = cgroup_file_write,
2574 .llseek = generic_file_llseek,
2575 .open = cgroup_file_open,
2576 .release = cgroup_file_release,
2579 static const struct inode_operations cgroup_file_inode_operations = {
2580 .setxattr = cgroup_setxattr,
2581 .getxattr = cgroup_getxattr,
2582 .listxattr = cgroup_listxattr,
2583 .removexattr = cgroup_removexattr,
2586 static const struct inode_operations cgroup_dir_inode_operations = {
2587 .lookup = simple_lookup,
2588 .mkdir = cgroup_mkdir,
2589 .rmdir = cgroup_rmdir,
2590 .rename = cgroup_rename,
2591 .setxattr = cgroup_setxattr,
2592 .getxattr = cgroup_getxattr,
2593 .listxattr = cgroup_listxattr,
2594 .removexattr = cgroup_removexattr,
2597 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2598 struct super_block *sb)
2600 struct inode *inode;
2604 if (dentry->d_inode)
2607 inode = cgroup_new_inode(mode, sb);
2611 if (S_ISDIR(mode)) {
2612 inode->i_op = &cgroup_dir_inode_operations;
2613 inode->i_fop = &simple_dir_operations;
2615 /* start off with i_nlink == 2 (for "." entry) */
2617 inc_nlink(dentry->d_parent->d_inode);
2620 * Control reaches here with cgroup_mutex held.
2621 * @inode->i_mutex should nest outside cgroup_mutex but we
2622 * want to populate it immediately without releasing
2623 * cgroup_mutex. As @inode isn't visible to anyone else
2624 * yet, trylock will always succeed without affecting
2627 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2628 } else if (S_ISREG(mode)) {
2630 inode->i_fop = &cgroup_file_operations;
2631 inode->i_op = &cgroup_file_inode_operations;
2633 d_instantiate(dentry, inode);
2634 dget(dentry); /* Extra count - pin the dentry in core */
2639 * cgroup_file_mode - deduce file mode of a control file
2640 * @cft: the control file in question
2642 * returns cft->mode if ->mode is not 0
2643 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2644 * returns S_IRUGO if it has only a read handler
2645 * returns S_IWUSR if it has only a write hander
2647 static umode_t cgroup_file_mode(const struct cftype *cft)
2654 if (cft->read || cft->read_u64 || cft->read_s64 ||
2655 cft->read_map || cft->read_seq_string)
2658 if (cft->write || cft->write_u64 || cft->write_s64 ||
2659 cft->write_string || cft->trigger)
2665 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2667 struct dentry *dir = cgrp->dentry;
2668 struct cgroup *parent = __d_cgrp(dir);
2669 struct dentry *dentry;
2673 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2675 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
2676 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
2677 strcpy(name, cft->ss->name);
2680 strcat(name, cft->name);
2682 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2684 cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2688 dentry = lookup_one_len(name, dir, strlen(name));
2689 if (IS_ERR(dentry)) {
2690 error = PTR_ERR(dentry);
2694 cfe->type = (void *)cft;
2695 cfe->dentry = dentry;
2696 dentry->d_fsdata = cfe;
2697 simple_xattrs_init(&cfe->xattrs);
2699 mode = cgroup_file_mode(cft);
2700 error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2702 list_add_tail(&cfe->node, &parent->files);
2712 * cgroup_addrm_files - add or remove files to a cgroup directory
2713 * @cgrp: the target cgroup
2714 * @cfts: array of cftypes to be added
2715 * @is_add: whether to add or remove
2717 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2718 * For removals, this function never fails. If addition fails, this
2719 * function doesn't remove files already added. The caller is responsible
2722 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2728 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
2729 lockdep_assert_held(&cgroup_mutex);
2731 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2732 /* does cft->flags tell us to skip this file on @cgrp? */
2733 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2735 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2737 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2741 ret = cgroup_add_file(cgrp, cft);
2743 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2748 cgroup_rm_file(cgrp, cft);
2754 static void cgroup_cfts_prepare(void)
2755 __acquires(&cgroup_mutex)
2758 * Thanks to the entanglement with vfs inode locking, we can't walk
2759 * the existing cgroups under cgroup_mutex and create files.
2760 * Instead, we use css_for_each_descendant_pre() and drop RCU read
2761 * lock before calling cgroup_addrm_files().
2763 mutex_lock(&cgroup_mutex);
2766 static int cgroup_cfts_commit(struct cftype *cfts, bool is_add)
2767 __releases(&cgroup_mutex)
2770 struct cgroup_subsys *ss = cfts[0].ss;
2771 struct cgroup *root = &ss->root->top_cgroup;
2772 struct super_block *sb = ss->root->sb;
2773 struct dentry *prev = NULL;
2774 struct inode *inode;
2775 struct cgroup_subsys_state *css;
2779 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2780 if (!cfts || ss->root == &cgroup_dummy_root ||
2781 !atomic_inc_not_zero(&sb->s_active)) {
2782 mutex_unlock(&cgroup_mutex);
2787 * All cgroups which are created after we drop cgroup_mutex will
2788 * have the updated set of files, so we only need to update the
2789 * cgroups created before the current @cgroup_serial_nr_next.
2791 update_before = cgroup_serial_nr_next;
2793 mutex_unlock(&cgroup_mutex);
2795 /* add/rm files for all cgroups created before */
2797 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2798 struct cgroup *cgrp = css->cgroup;
2800 if (cgroup_is_dead(cgrp))
2803 inode = cgrp->dentry->d_inode;
2808 prev = cgrp->dentry;
2810 mutex_lock(&inode->i_mutex);
2811 mutex_lock(&cgroup_mutex);
2812 if (cgrp->serial_nr < update_before && !cgroup_is_dead(cgrp))
2813 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2814 mutex_unlock(&cgroup_mutex);
2815 mutex_unlock(&inode->i_mutex);
2823 deactivate_super(sb);
2828 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2829 * @ss: target cgroup subsystem
2830 * @cfts: zero-length name terminated array of cftypes
2832 * Register @cfts to @ss. Files described by @cfts are created for all
2833 * existing cgroups to which @ss is attached and all future cgroups will
2834 * have them too. This function can be called anytime whether @ss is
2837 * Returns 0 on successful registration, -errno on failure. Note that this
2838 * function currently returns 0 as long as @cfts registration is successful
2839 * even if some file creation attempts on existing cgroups fail.
2841 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2843 struct cftype_set *set;
2847 set = kzalloc(sizeof(*set), GFP_KERNEL);
2851 for (cft = cfts; cft->name[0] != '\0'; cft++)
2854 cgroup_cfts_prepare();
2856 list_add_tail(&set->node, &ss->cftsets);
2857 ret = cgroup_cfts_commit(cfts, true);
2859 cgroup_rm_cftypes(cfts);
2862 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2865 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2866 * @cfts: zero-length name terminated array of cftypes
2868 * Unregister @cfts. Files described by @cfts are removed from all
2869 * existing cgroups and all future cgroups won't have them either. This
2870 * function can be called anytime whether @cfts' subsys is attached or not.
2872 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2875 int cgroup_rm_cftypes(struct cftype *cfts)
2877 struct cftype_set *set;
2879 if (!cfts || !cfts[0].ss)
2882 cgroup_cfts_prepare();
2884 list_for_each_entry(set, &cfts[0].ss->cftsets, node) {
2885 if (set->cfts == cfts) {
2886 list_del(&set->node);
2888 cgroup_cfts_commit(cfts, false);
2893 cgroup_cfts_commit(NULL, false);
2898 * cgroup_task_count - count the number of tasks in a cgroup.
2899 * @cgrp: the cgroup in question
2901 * Return the number of tasks in the cgroup.
2903 int cgroup_task_count(const struct cgroup *cgrp)
2906 struct cgrp_cset_link *link;
2908 read_lock(&css_set_lock);
2909 list_for_each_entry(link, &cgrp->cset_links, cset_link)
2910 count += atomic_read(&link->cset->refcount);
2911 read_unlock(&css_set_lock);
2916 * To reduce the fork() overhead for systems that are not actually using
2917 * their cgroups capability, we don't maintain the lists running through
2918 * each css_set to its tasks until we see the list actually used - in other
2919 * words after the first call to css_task_iter_start().
2921 static void cgroup_enable_task_cg_lists(void)
2923 struct task_struct *p, *g;
2924 write_lock(&css_set_lock);
2925 use_task_css_set_links = 1;
2927 * We need tasklist_lock because RCU is not safe against
2928 * while_each_thread(). Besides, a forking task that has passed
2929 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2930 * is not guaranteed to have its child immediately visible in the
2931 * tasklist if we walk through it with RCU.
2933 read_lock(&tasklist_lock);
2934 do_each_thread(g, p) {
2937 * We should check if the process is exiting, otherwise
2938 * it will race with cgroup_exit() in that the list
2939 * entry won't be deleted though the process has exited.
2941 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2942 list_add(&p->cg_list, &task_css_set(p)->tasks);
2944 } while_each_thread(g, p);
2945 read_unlock(&tasklist_lock);
2946 write_unlock(&css_set_lock);
2950 * css_next_child - find the next child of a given css
2951 * @pos_css: the current position (%NULL to initiate traversal)
2952 * @parent_css: css whose children to walk
2954 * This function returns the next child of @parent_css and should be called
2955 * under RCU read lock. The only requirement is that @parent_css and
2956 * @pos_css are accessible. The next sibling is guaranteed to be returned
2957 * regardless of their states.
2959 struct cgroup_subsys_state *
2960 css_next_child(struct cgroup_subsys_state *pos_css,
2961 struct cgroup_subsys_state *parent_css)
2963 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
2964 struct cgroup *cgrp = parent_css->cgroup;
2965 struct cgroup *next;
2967 WARN_ON_ONCE(!rcu_read_lock_held());
2970 * @pos could already have been removed. Once a cgroup is removed,
2971 * its ->sibling.next is no longer updated when its next sibling
2972 * changes. As CGRP_DEAD assertion is serialized and happens
2973 * before the cgroup is taken off the ->sibling list, if we see it
2974 * unasserted, it's guaranteed that the next sibling hasn't
2975 * finished its grace period even if it's already removed, and thus
2976 * safe to dereference from this RCU critical section. If
2977 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
2978 * to be visible as %true here.
2980 * If @pos is dead, its next pointer can't be dereferenced;
2981 * however, as each cgroup is given a monotonically increasing
2982 * unique serial number and always appended to the sibling list,
2983 * the next one can be found by walking the parent's children until
2984 * we see a cgroup with higher serial number than @pos's. While
2985 * this path can be slower, it's taken only when either the current
2986 * cgroup is removed or iteration and removal race.
2989 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
2990 } else if (likely(!cgroup_is_dead(pos))) {
2991 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
2993 list_for_each_entry_rcu(next, &cgrp->children, sibling)
2994 if (next->serial_nr > pos->serial_nr)
2998 if (&next->sibling == &cgrp->children)
3001 return cgroup_css(next, parent_css->ss);
3003 EXPORT_SYMBOL_GPL(css_next_child);
3006 * css_next_descendant_pre - find the next descendant for pre-order walk
3007 * @pos: the current position (%NULL to initiate traversal)
3008 * @root: css whose descendants to walk
3010 * To be used by css_for_each_descendant_pre(). Find the next descendant
3011 * to visit for pre-order traversal of @root's descendants. @root is
3012 * included in the iteration and the first node to be visited.
3014 * While this function requires RCU read locking, it doesn't require the
3015 * whole traversal to be contained in a single RCU critical section. This
3016 * function will return the correct next descendant as long as both @pos
3017 * and @root are accessible and @pos is a descendant of @root.
3019 struct cgroup_subsys_state *
3020 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3021 struct cgroup_subsys_state *root)
3023 struct cgroup_subsys_state *next;
3025 WARN_ON_ONCE(!rcu_read_lock_held());
3027 /* if first iteration, visit @root */
3031 /* visit the first child if exists */
3032 next = css_next_child(NULL, pos);
3036 /* no child, visit my or the closest ancestor's next sibling */
3037 while (pos != root) {
3038 next = css_next_child(pos, css_parent(pos));
3041 pos = css_parent(pos);
3046 EXPORT_SYMBOL_GPL(css_next_descendant_pre);
3049 * css_rightmost_descendant - return the rightmost descendant of a css
3050 * @pos: css of interest
3052 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3053 * is returned. This can be used during pre-order traversal to skip
3056 * While this function requires RCU read locking, it doesn't require the
3057 * whole traversal to be contained in a single RCU critical section. This
3058 * function will return the correct rightmost descendant as long as @pos is
3061 struct cgroup_subsys_state *
3062 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3064 struct cgroup_subsys_state *last, *tmp;
3066 WARN_ON_ONCE(!rcu_read_lock_held());
3070 /* ->prev isn't RCU safe, walk ->next till the end */
3072 css_for_each_child(tmp, last)
3078 EXPORT_SYMBOL_GPL(css_rightmost_descendant);
3080 static struct cgroup_subsys_state *
3081 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3083 struct cgroup_subsys_state *last;
3087 pos = css_next_child(NULL, pos);
3094 * css_next_descendant_post - find the next descendant for post-order walk
3095 * @pos: the current position (%NULL to initiate traversal)
3096 * @root: css whose descendants to walk
3098 * To be used by css_for_each_descendant_post(). Find the next descendant
3099 * to visit for post-order traversal of @root's descendants. @root is
3100 * included in the iteration and the last node to be visited.
3102 * While this function requires RCU read locking, it doesn't require the
3103 * whole traversal to be contained in a single RCU critical section. This
3104 * function will return the correct next descendant as long as both @pos
3105 * and @cgroup are accessible and @pos is a descendant of @cgroup.
3107 struct cgroup_subsys_state *
3108 css_next_descendant_post(struct cgroup_subsys_state *pos,
3109 struct cgroup_subsys_state *root)
3111 struct cgroup_subsys_state *next;
3113 WARN_ON_ONCE(!rcu_read_lock_held());
3115 /* if first iteration, visit leftmost descendant which may be @root */
3117 return css_leftmost_descendant(root);
3119 /* if we visited @root, we're done */
3123 /* if there's an unvisited sibling, visit its leftmost descendant */
3124 next = css_next_child(pos, css_parent(pos));
3126 return css_leftmost_descendant(next);
3128 /* no sibling left, visit parent */
3129 return css_parent(pos);
3131 EXPORT_SYMBOL_GPL(css_next_descendant_post);
3134 * css_advance_task_iter - advance a task itererator to the next css_set
3135 * @it: the iterator to advance
3137 * Advance @it to the next css_set to walk.
3139 static void css_advance_task_iter(struct css_task_iter *it)
3141 struct list_head *l = it->cset_link;
3142 struct cgrp_cset_link *link;
3143 struct css_set *cset;
3145 /* Advance to the next non-empty css_set */
3148 if (l == &it->origin_css->cgroup->cset_links) {
3149 it->cset_link = NULL;
3152 link = list_entry(l, struct cgrp_cset_link, cset_link);
3154 } while (list_empty(&cset->tasks));
3156 it->task = cset->tasks.next;
3160 * css_task_iter_start - initiate task iteration
3161 * @css: the css to walk tasks of
3162 * @it: the task iterator to use
3164 * Initiate iteration through the tasks of @css. The caller can call
3165 * css_task_iter_next() to walk through the tasks until the function
3166 * returns NULL. On completion of iteration, css_task_iter_end() must be
3169 * Note that this function acquires a lock which is released when the
3170 * iteration finishes. The caller can't sleep while iteration is in
3173 void css_task_iter_start(struct cgroup_subsys_state *css,
3174 struct css_task_iter *it)
3175 __acquires(css_set_lock)
3178 * The first time anyone tries to iterate across a css, we need to
3179 * enable the list linking each css_set to its tasks, and fix up
3180 * all existing tasks.
3182 if (!use_task_css_set_links)
3183 cgroup_enable_task_cg_lists();
3185 read_lock(&css_set_lock);
3187 it->origin_css = css;
3188 it->cset_link = &css->cgroup->cset_links;
3190 css_advance_task_iter(it);
3194 * css_task_iter_next - return the next task for the iterator
3195 * @it: the task iterator being iterated
3197 * The "next" function for task iteration. @it should have been
3198 * initialized via css_task_iter_start(). Returns NULL when the iteration
3201 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3203 struct task_struct *res;
3204 struct list_head *l = it->task;
3205 struct cgrp_cset_link *link;
3207 /* If the iterator cg is NULL, we have no tasks */
3210 res = list_entry(l, struct task_struct, cg_list);
3211 /* Advance iterator to find next entry */
3213 link = list_entry(it->cset_link, struct cgrp_cset_link, cset_link);
3214 if (l == &link->cset->tasks) {
3216 * We reached the end of this task list - move on to the
3217 * next cgrp_cset_link.
3219 css_advance_task_iter(it);
3227 * css_task_iter_end - finish task iteration
3228 * @it: the task iterator to finish
3230 * Finish task iteration started by css_task_iter_start().
3232 void css_task_iter_end(struct css_task_iter *it)
3233 __releases(css_set_lock)
3235 read_unlock(&css_set_lock);
3238 static inline int started_after_time(struct task_struct *t1,
3239 struct timespec *time,
3240 struct task_struct *t2)
3242 int start_diff = timespec_compare(&t1->start_time, time);
3243 if (start_diff > 0) {
3245 } else if (start_diff < 0) {
3249 * Arbitrarily, if two processes started at the same
3250 * time, we'll say that the lower pointer value
3251 * started first. Note that t2 may have exited by now
3252 * so this may not be a valid pointer any longer, but
3253 * that's fine - it still serves to distinguish
3254 * between two tasks started (effectively) simultaneously.
3261 * This function is a callback from heap_insert() and is used to order
3263 * In this case we order the heap in descending task start time.
3265 static inline int started_after(void *p1, void *p2)
3267 struct task_struct *t1 = p1;
3268 struct task_struct *t2 = p2;
3269 return started_after_time(t1, &t2->start_time, t2);
3273 * css_scan_tasks - iterate though all the tasks in a css
3274 * @css: the css to iterate tasks of
3275 * @test: optional test callback
3276 * @process: process callback
3277 * @data: data passed to @test and @process
3278 * @heap: optional pre-allocated heap used for task iteration
3280 * Iterate through all the tasks in @css, calling @test for each, and if it
3281 * returns %true, call @process for it also.
3283 * @test may be NULL, meaning always true (select all tasks), which
3284 * effectively duplicates css_task_iter_{start,next,end}() but does not
3285 * lock css_set_lock for the call to @process.
3287 * It is guaranteed that @process will act on every task that is a member
3288 * of @css for the duration of this call. This function may or may not
3289 * call @process for tasks that exit or move to a different css during the
3290 * call, or are forked or move into the css during the call.
3292 * Note that @test may be called with locks held, and may in some
3293 * situations be called multiple times for the same task, so it should be
3296 * If @heap is non-NULL, a heap has been pre-allocated and will be used for
3297 * heap operations (and its "gt" member will be overwritten), else a
3298 * temporary heap will be used (allocation of which may cause this function
3301 int css_scan_tasks(struct cgroup_subsys_state *css,
3302 bool (*test)(struct task_struct *, void *),
3303 void (*process)(struct task_struct *, void *),
3304 void *data, struct ptr_heap *heap)
3307 struct css_task_iter it;
3308 struct task_struct *p, *dropped;
3309 /* Never dereference latest_task, since it's not refcounted */
3310 struct task_struct *latest_task = NULL;
3311 struct ptr_heap tmp_heap;
3312 struct timespec latest_time = { 0, 0 };
3315 /* The caller supplied our heap and pre-allocated its memory */
3316 heap->gt = &started_after;
3318 /* We need to allocate our own heap memory */
3320 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3322 /* cannot allocate the heap */
3328 * Scan tasks in the css, using the @test callback to determine
3329 * which are of interest, and invoking @process callback on the
3330 * ones which need an update. Since we don't want to hold any
3331 * locks during the task updates, gather tasks to be processed in a
3332 * heap structure. The heap is sorted by descending task start
3333 * time. If the statically-sized heap fills up, we overflow tasks
3334 * that started later, and in future iterations only consider tasks
3335 * that started after the latest task in the previous pass. This
3336 * guarantees forward progress and that we don't miss any tasks.
3339 css_task_iter_start(css, &it);
3340 while ((p = css_task_iter_next(&it))) {
3342 * Only affect tasks that qualify per the caller's callback,
3343 * if he provided one
3345 if (test && !test(p, data))
3348 * Only process tasks that started after the last task
3351 if (!started_after_time(p, &latest_time, latest_task))
3353 dropped = heap_insert(heap, p);
3354 if (dropped == NULL) {
3356 * The new task was inserted; the heap wasn't
3360 } else if (dropped != p) {
3362 * The new task was inserted, and pushed out a
3366 put_task_struct(dropped);
3369 * Else the new task was newer than anything already in
3370 * the heap and wasn't inserted
3373 css_task_iter_end(&it);
3376 for (i = 0; i < heap->size; i++) {
3377 struct task_struct *q = heap->ptrs[i];
3379 latest_time = q->start_time;
3382 /* Process the task per the caller's callback */
3387 * If we had to process any tasks at all, scan again
3388 * in case some of them were in the middle of forking
3389 * children that didn't get processed.
3390 * Not the most efficient way to do it, but it avoids
3391 * having to take callback_mutex in the fork path
3395 if (heap == &tmp_heap)
3396 heap_free(&tmp_heap);
3400 static void cgroup_transfer_one_task(struct task_struct *task, void *data)
3402 struct cgroup *new_cgroup = data;
3404 mutex_lock(&cgroup_mutex);
3405 cgroup_attach_task(new_cgroup, task, false);
3406 mutex_unlock(&cgroup_mutex);
3410 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3411 * @to: cgroup to which the tasks will be moved
3412 * @from: cgroup in which the tasks currently reside
3414 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3416 return css_scan_tasks(&from->dummy_css, NULL, cgroup_transfer_one_task,
3421 * Stuff for reading the 'tasks'/'procs' files.
3423 * Reading this file can return large amounts of data if a cgroup has
3424 * *lots* of attached tasks. So it may need several calls to read(),
3425 * but we cannot guarantee that the information we produce is correct
3426 * unless we produce it entirely atomically.
3430 /* which pidlist file are we talking about? */
3431 enum cgroup_filetype {
3437 * A pidlist is a list of pids that virtually represents the contents of one
3438 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3439 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3442 struct cgroup_pidlist {
3444 * used to find which pidlist is wanted. doesn't change as long as
3445 * this particular list stays in the list.
3447 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3450 /* how many elements the above list has */
3452 /* how many files are using the current array */
3454 /* each of these stored in a list by its cgroup */
3455 struct list_head links;
3456 /* pointer to the cgroup we belong to, for list removal purposes */
3457 struct cgroup *owner;
3458 /* protects the other fields */
3459 struct rw_semaphore rwsem;
3463 * The following two functions "fix" the issue where there are more pids
3464 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3465 * TODO: replace with a kernel-wide solution to this problem
3467 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3468 static void *pidlist_allocate(int count)
3470 if (PIDLIST_TOO_LARGE(count))
3471 return vmalloc(count * sizeof(pid_t));
3473 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3475 static void pidlist_free(void *p)
3477 if (is_vmalloc_addr(p))
3484 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3485 * Returns the number of unique elements.
3487 static int pidlist_uniq(pid_t *list, int length)
3492 * we presume the 0th element is unique, so i starts at 1. trivial
3493 * edge cases first; no work needs to be done for either
3495 if (length == 0 || length == 1)
3497 /* src and dest walk down the list; dest counts unique elements */
3498 for (src = 1; src < length; src++) {
3499 /* find next unique element */
3500 while (list[src] == list[src-1]) {
3505 /* dest always points to where the next unique element goes */
3506 list[dest] = list[src];
3513 static int cmppid(const void *a, const void *b)
3515 return *(pid_t *)a - *(pid_t *)b;
3519 * find the appropriate pidlist for our purpose (given procs vs tasks)
3520 * returns with the lock on that pidlist already held, and takes care
3521 * of the use count, or returns NULL with no locks held if we're out of
3524 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3525 enum cgroup_filetype type)
3527 struct cgroup_pidlist *l;
3528 /* don't need task_nsproxy() if we're looking at ourself */
3529 struct pid_namespace *ns = task_active_pid_ns(current);
3532 * We can't drop the pidlist_mutex before taking the l->rwsem in case
3533 * the last ref-holder is trying to remove l from the list at the same
3534 * time. Holding the pidlist_mutex precludes somebody taking whichever
3535 * list we find out from under us - compare release_pid_array().
3537 mutex_lock(&cgrp->pidlist_mutex);
3538 list_for_each_entry(l, &cgrp->pidlists, links) {
3539 if (l->key.type == type && l->key.ns == ns) {
3540 /* make sure l doesn't vanish out from under us */
3541 down_write(&l->rwsem);
3542 mutex_unlock(&cgrp->pidlist_mutex);
3546 /* entry not found; create a new one */
3547 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3549 mutex_unlock(&cgrp->pidlist_mutex);
3552 init_rwsem(&l->rwsem);
3553 down_write(&l->rwsem);
3555 l->key.ns = get_pid_ns(ns);
3557 list_add(&l->links, &cgrp->pidlists);
3558 mutex_unlock(&cgrp->pidlist_mutex);
3563 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3565 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3566 struct cgroup_pidlist **lp)
3570 int pid, n = 0; /* used for populating the array */
3571 struct css_task_iter it;
3572 struct task_struct *tsk;
3573 struct cgroup_pidlist *l;
3576 * If cgroup gets more users after we read count, we won't have
3577 * enough space - tough. This race is indistinguishable to the
3578 * caller from the case that the additional cgroup users didn't
3579 * show up until sometime later on.
3581 length = cgroup_task_count(cgrp);
3582 array = pidlist_allocate(length);
3585 /* now, populate the array */
3586 css_task_iter_start(&cgrp->dummy_css, &it);
3587 while ((tsk = css_task_iter_next(&it))) {
3588 if (unlikely(n == length))
3590 /* get tgid or pid for procs or tasks file respectively */
3591 if (type == CGROUP_FILE_PROCS)
3592 pid = task_tgid_vnr(tsk);
3594 pid = task_pid_vnr(tsk);
3595 if (pid > 0) /* make sure to only use valid results */
3598 css_task_iter_end(&it);
3600 /* now sort & (if procs) strip out duplicates */
3601 sort(array, length, sizeof(pid_t), cmppid, NULL);
3602 if (type == CGROUP_FILE_PROCS)
3603 length = pidlist_uniq(array, length);
3604 l = cgroup_pidlist_find(cgrp, type);
3606 pidlist_free(array);
3609 /* store array, freeing old if necessary - lock already held */
3610 pidlist_free(l->list);
3614 up_write(&l->rwsem);
3620 * cgroupstats_build - build and fill cgroupstats
3621 * @stats: cgroupstats to fill information into
3622 * @dentry: A dentry entry belonging to the cgroup for which stats have
3625 * Build and fill cgroupstats so that taskstats can export it to user
3628 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3631 struct cgroup *cgrp;
3632 struct css_task_iter it;
3633 struct task_struct *tsk;
3636 * Validate dentry by checking the superblock operations,
3637 * and make sure it's a directory.
3639 if (dentry->d_sb->s_op != &cgroup_ops ||
3640 !S_ISDIR(dentry->d_inode->i_mode))
3644 cgrp = dentry->d_fsdata;
3646 css_task_iter_start(&cgrp->dummy_css, &it);
3647 while ((tsk = css_task_iter_next(&it))) {
3648 switch (tsk->state) {
3650 stats->nr_running++;
3652 case TASK_INTERRUPTIBLE:
3653 stats->nr_sleeping++;
3655 case TASK_UNINTERRUPTIBLE:
3656 stats->nr_uninterruptible++;
3659 stats->nr_stopped++;
3662 if (delayacct_is_task_waiting_on_io(tsk))
3663 stats->nr_io_wait++;
3667 css_task_iter_end(&it);
3675 * seq_file methods for the tasks/procs files. The seq_file position is the
3676 * next pid to display; the seq_file iterator is a pointer to the pid
3677 * in the cgroup->l->list array.
3680 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3683 * Initially we receive a position value that corresponds to
3684 * one more than the last pid shown (or 0 on the first call or
3685 * after a seek to the start). Use a binary-search to find the
3686 * next pid to display, if any
3688 struct cgroup_pidlist *l = s->private;
3689 int index = 0, pid = *pos;
3692 down_read(&l->rwsem);
3694 int end = l->length;
3696 while (index < end) {
3697 int mid = (index + end) / 2;
3698 if (l->list[mid] == pid) {
3701 } else if (l->list[mid] <= pid)
3707 /* If we're off the end of the array, we're done */
3708 if (index >= l->length)
3710 /* Update the abstract position to be the actual pid that we found */
3711 iter = l->list + index;
3716 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3718 struct cgroup_pidlist *l = s->private;
3722 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3724 struct cgroup_pidlist *l = s->private;
3726 pid_t *end = l->list + l->length;
3728 * Advance to the next pid in the array. If this goes off the
3740 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3742 return seq_printf(s, "%d\n", *(int *)v);
3746 * seq_operations functions for iterating on pidlists through seq_file -
3747 * independent of whether it's tasks or procs
3749 static const struct seq_operations cgroup_pidlist_seq_operations = {
3750 .start = cgroup_pidlist_start,
3751 .stop = cgroup_pidlist_stop,
3752 .next = cgroup_pidlist_next,
3753 .show = cgroup_pidlist_show,
3756 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
3759 * the case where we're the last user of this particular pidlist will
3760 * have us remove it from the cgroup's list, which entails taking the
3761 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3762 * pidlist_mutex, we have to take pidlist_mutex first.
3764 mutex_lock(&l->owner->pidlist_mutex);
3765 down_write(&l->rwsem);
3766 BUG_ON(!l->use_count);
3767 if (!--l->use_count) {
3768 /* we're the last user if refcount is 0; remove and free */
3769 list_del(&l->links);
3770 mutex_unlock(&l->owner->pidlist_mutex);
3771 pidlist_free(l->list);
3772 put_pid_ns(l->key.ns);
3773 up_write(&l->rwsem);
3777 mutex_unlock(&l->owner->pidlist_mutex);
3778 up_write(&l->rwsem);
3781 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
3783 struct cgroup_pidlist *l;
3784 if (!(file->f_mode & FMODE_READ))
3787 * the seq_file will only be initialized if the file was opened for
3788 * reading; hence we check if it's not null only in that case.
3790 l = ((struct seq_file *)file->private_data)->private;
3791 cgroup_release_pid_array(l);
3792 return seq_release(inode, file);
3795 static const struct file_operations cgroup_pidlist_operations = {
3797 .llseek = seq_lseek,
3798 .write = cgroup_file_write,
3799 .release = cgroup_pidlist_release,
3803 * The following functions handle opens on a file that displays a pidlist
3804 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3807 /* helper function for the two below it */
3808 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
3810 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
3811 struct cgroup_pidlist *l;
3814 /* Nothing to do for write-only files */
3815 if (!(file->f_mode & FMODE_READ))
3818 /* have the array populated */
3819 retval = pidlist_array_load(cgrp, type, &l);
3822 /* configure file information */
3823 file->f_op = &cgroup_pidlist_operations;
3825 retval = seq_open(file, &cgroup_pidlist_seq_operations);
3827 cgroup_release_pid_array(l);
3830 ((struct seq_file *)file->private_data)->private = l;
3833 static int cgroup_tasks_open(struct inode *unused, struct file *file)
3835 return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
3837 static int cgroup_procs_open(struct inode *unused, struct file *file)
3839 return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
3842 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3845 return notify_on_release(css->cgroup);
3848 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3849 struct cftype *cft, u64 val)
3851 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3853 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3855 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3860 * When dput() is called asynchronously, if umount has been done and
3861 * then deactivate_super() in cgroup_free_fn() kills the superblock,
3862 * there's a small window that vfs will see the root dentry with non-zero
3863 * refcnt and trigger BUG().
3865 * That's why we hold a reference before dput() and drop it right after.
3867 static void cgroup_dput(struct cgroup *cgrp)
3869 struct super_block *sb = cgrp->root->sb;
3871 atomic_inc(&sb->s_active);
3873 deactivate_super(sb);
3876 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3879 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3882 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3883 struct cftype *cft, u64 val)
3886 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3888 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3892 static struct cftype cgroup_base_files[] = {
3894 .name = "cgroup.procs",
3895 .open = cgroup_procs_open,
3896 .write_u64 = cgroup_procs_write,
3897 .release = cgroup_pidlist_release,
3898 .mode = S_IRUGO | S_IWUSR,
3901 .name = "cgroup.clone_children",
3902 .flags = CFTYPE_INSANE,
3903 .read_u64 = cgroup_clone_children_read,
3904 .write_u64 = cgroup_clone_children_write,
3907 .name = "cgroup.sane_behavior",
3908 .flags = CFTYPE_ONLY_ON_ROOT,
3909 .read_seq_string = cgroup_sane_behavior_show,
3913 * Historical crazy stuff. These don't have "cgroup." prefix and
3914 * don't exist if sane_behavior. If you're depending on these, be
3915 * prepared to be burned.
3919 .flags = CFTYPE_INSANE, /* use "procs" instead */
3920 .open = cgroup_tasks_open,
3921 .write_u64 = cgroup_tasks_write,
3922 .release = cgroup_pidlist_release,
3923 .mode = S_IRUGO | S_IWUSR,
3926 .name = "notify_on_release",
3927 .flags = CFTYPE_INSANE,
3928 .read_u64 = cgroup_read_notify_on_release,
3929 .write_u64 = cgroup_write_notify_on_release,
3932 .name = "release_agent",
3933 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
3934 .read_seq_string = cgroup_release_agent_show,
3935 .write_string = cgroup_release_agent_write,
3936 .max_write_len = PATH_MAX,
3942 * cgroup_populate_dir - create subsys files in a cgroup directory
3943 * @cgrp: target cgroup
3944 * @subsys_mask: mask of the subsystem ids whose files should be added
3946 * On failure, no file is added.
3948 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
3950 struct cgroup_subsys *ss;
3953 /* process cftsets of each subsystem */
3954 for_each_subsys(ss, i) {
3955 struct cftype_set *set;
3957 if (!test_bit(i, &subsys_mask))
3960 list_for_each_entry(set, &ss->cftsets, node) {
3961 ret = cgroup_addrm_files(cgrp, set->cfts, true);
3968 cgroup_clear_dir(cgrp, subsys_mask);
3973 * css destruction is four-stage process.
3975 * 1. Destruction starts. Killing of the percpu_ref is initiated.
3976 * Implemented in kill_css().
3978 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
3979 * and thus css_tryget() is guaranteed to fail, the css can be offlined
3980 * by invoking offline_css(). After offlining, the base ref is put.
3981 * Implemented in css_killed_work_fn().
3983 * 3. When the percpu_ref reaches zero, the only possible remaining
3984 * accessors are inside RCU read sections. css_release() schedules the
3987 * 4. After the grace period, the css can be freed. Implemented in
3988 * css_free_work_fn().
3990 * It is actually hairier because both step 2 and 4 require process context
3991 * and thus involve punting to css->destroy_work adding two additional
3992 * steps to the already complex sequence.
3994 static void css_free_work_fn(struct work_struct *work)
3996 struct cgroup_subsys_state *css =
3997 container_of(work, struct cgroup_subsys_state, destroy_work);
3998 struct cgroup *cgrp = css->cgroup;
4001 css_put(css->parent);
4003 css->ss->css_free(css);
4007 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4009 struct cgroup_subsys_state *css =
4010 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4013 * css holds an extra ref to @cgrp->dentry which is put on the last
4014 * css_put(). dput() requires process context which we don't have.
4016 INIT_WORK(&css->destroy_work, css_free_work_fn);
4017 queue_work(cgroup_destroy_wq, &css->destroy_work);
4020 static void css_release(struct percpu_ref *ref)
4022 struct cgroup_subsys_state *css =
4023 container_of(ref, struct cgroup_subsys_state, refcnt);
4025 call_rcu(&css->rcu_head, css_free_rcu_fn);
4028 static void init_css(struct cgroup_subsys_state *css, struct cgroup_subsys *ss,
4029 struct cgroup *cgrp)
4036 css->parent = cgroup_css(cgrp->parent, ss);
4038 css->flags |= CSS_ROOT;
4040 BUG_ON(cgroup_css(cgrp, ss));
4043 /* invoke ->css_online() on a new CSS and mark it online if successful */
4044 static int online_css(struct cgroup_subsys_state *css)
4046 struct cgroup_subsys *ss = css->ss;
4049 lockdep_assert_held(&cgroup_mutex);
4052 ret = ss->css_online(css);
4054 css->flags |= CSS_ONLINE;
4055 css->cgroup->nr_css++;
4056 rcu_assign_pointer(css->cgroup->subsys[ss->subsys_id], css);
4061 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4062 static void offline_css(struct cgroup_subsys_state *css)
4064 struct cgroup_subsys *ss = css->ss;
4066 lockdep_assert_held(&cgroup_mutex);
4068 if (!(css->flags & CSS_ONLINE))
4071 if (ss->css_offline)
4072 ss->css_offline(css);
4074 css->flags &= ~CSS_ONLINE;
4075 css->cgroup->nr_css--;
4076 RCU_INIT_POINTER(css->cgroup->subsys[ss->subsys_id], css);
4080 * cgroup_create - create a cgroup
4081 * @parent: cgroup that will be parent of the new cgroup
4082 * @dentry: dentry of the new cgroup
4083 * @mode: mode to set on new inode
4085 * Must be called with the mutex on the parent inode held
4087 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4090 struct cgroup_subsys_state *css_ar[CGROUP_SUBSYS_COUNT] = { };
4091 struct cgroup *cgrp;
4092 struct cgroup_name *name;
4093 struct cgroupfs_root *root = parent->root;
4095 struct cgroup_subsys *ss;
4096 struct super_block *sb = root->sb;
4098 /* allocate the cgroup and its ID, 0 is reserved for the root */
4099 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4103 name = cgroup_alloc_name(dentry);
4106 rcu_assign_pointer(cgrp->name, name);
4109 * Temporarily set the pointer to NULL, so idr_find() won't return
4110 * a half-baked cgroup.
4112 cgrp->id = idr_alloc(&root->cgroup_idr, NULL, 1, 0, GFP_KERNEL);
4117 * Only live parents can have children. Note that the liveliness
4118 * check isn't strictly necessary because cgroup_mkdir() and
4119 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4120 * anyway so that locking is contained inside cgroup proper and we
4121 * don't get nasty surprises if we ever grow another caller.
4123 if (!cgroup_lock_live_group(parent)) {
4128 /* Grab a reference on the superblock so the hierarchy doesn't
4129 * get deleted on unmount if there are child cgroups. This
4130 * can be done outside cgroup_mutex, since the sb can't
4131 * disappear while someone has an open control file on the
4133 atomic_inc(&sb->s_active);
4135 init_cgroup_housekeeping(cgrp);
4137 dentry->d_fsdata = cgrp;
4138 cgrp->dentry = dentry;
4140 cgrp->parent = parent;
4141 cgrp->dummy_css.parent = &parent->dummy_css;
4142 cgrp->root = parent->root;
4144 if (notify_on_release(parent))
4145 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4147 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4148 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4150 for_each_root_subsys(root, ss) {
4151 struct cgroup_subsys_state *css;
4153 css = ss->css_alloc(cgroup_css(parent, ss));
4158 css_ar[ss->subsys_id] = css;
4160 err = percpu_ref_init(&css->refcnt, css_release);
4164 init_css(css, ss, cgrp);
4168 * Create directory. cgroup_create_file() returns with the new
4169 * directory locked on success so that it can be populated without
4170 * dropping cgroup_mutex.
4172 err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4175 lockdep_assert_held(&dentry->d_inode->i_mutex);
4177 cgrp->serial_nr = cgroup_serial_nr_next++;
4179 /* allocation complete, commit to creation */
4180 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4181 root->number_of_cgroups++;
4183 /* each css holds a ref to the cgroup's dentry and the parent css */
4184 for_each_root_subsys(root, ss) {
4185 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4188 css_get(css->parent);
4191 /* hold a ref to the parent's dentry */
4192 dget(parent->dentry);
4194 /* creation succeeded, notify subsystems */
4195 for_each_root_subsys(root, ss) {
4196 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4198 err = online_css(css);
4202 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4204 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",
4205 current->comm, current->pid, ss->name);
4206 if (!strcmp(ss->name, "memory"))
4207 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4208 ss->warned_broken_hierarchy = true;
4212 idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4214 err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
4218 err = cgroup_populate_dir(cgrp, root->subsys_mask);
4222 mutex_unlock(&cgroup_mutex);
4223 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4228 for_each_root_subsys(root, ss) {
4229 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4232 percpu_ref_cancel_init(&css->refcnt);
4236 mutex_unlock(&cgroup_mutex);
4237 /* Release the reference count that we took on the superblock */
4238 deactivate_super(sb);
4240 idr_remove(&root->cgroup_idr, cgrp->id);
4242 kfree(rcu_dereference_raw(cgrp->name));
4248 cgroup_destroy_locked(cgrp);
4249 mutex_unlock(&cgroup_mutex);
4250 mutex_unlock(&dentry->d_inode->i_mutex);
4254 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4256 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4258 /* the vfs holds inode->i_mutex already */
4259 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4263 * This is called when the refcnt of a css is confirmed to be killed.
4264 * css_tryget() is now guaranteed to fail.
4266 static void css_killed_work_fn(struct work_struct *work)
4268 struct cgroup_subsys_state *css =
4269 container_of(work, struct cgroup_subsys_state, destroy_work);
4270 struct cgroup *cgrp = css->cgroup;
4272 mutex_lock(&cgroup_mutex);
4275 * css_tryget() is guaranteed to fail now. Tell subsystems to
4276 * initate destruction.
4281 * If @cgrp is marked dead, it's waiting for refs of all css's to
4282 * be disabled before proceeding to the second phase of cgroup
4283 * destruction. If we are the last one, kick it off.
4285 if (!cgrp->nr_css && cgroup_is_dead(cgrp))
4286 cgroup_destroy_css_killed(cgrp);
4288 mutex_unlock(&cgroup_mutex);
4291 * Put the css refs from kill_css(). Each css holds an extra
4292 * reference to the cgroup's dentry and cgroup removal proceeds
4293 * regardless of css refs. On the last put of each css, whenever
4294 * that may be, the extra dentry ref is put so that dentry
4295 * destruction happens only after all css's are released.
4300 /* css kill confirmation processing requires process context, bounce */
4301 static void css_killed_ref_fn(struct percpu_ref *ref)
4303 struct cgroup_subsys_state *css =
4304 container_of(ref, struct cgroup_subsys_state, refcnt);
4306 INIT_WORK(&css->destroy_work, css_killed_work_fn);
4307 queue_work(cgroup_destroy_wq, &css->destroy_work);
4311 * kill_css - destroy a css
4312 * @css: css to destroy
4314 * This function initiates destruction of @css by removing cgroup interface
4315 * files and putting its base reference. ->css_offline() will be invoked
4316 * asynchronously once css_tryget() is guaranteed to fail and when the
4317 * reference count reaches zero, @css will be released.
4319 static void kill_css(struct cgroup_subsys_state *css)
4321 cgroup_clear_dir(css->cgroup, 1 << css->ss->subsys_id);
4324 * Killing would put the base ref, but we need to keep it alive
4325 * until after ->css_offline().
4330 * cgroup core guarantees that, by the time ->css_offline() is
4331 * invoked, no new css reference will be given out via
4332 * css_tryget(). We can't simply call percpu_ref_kill() and
4333 * proceed to offlining css's because percpu_ref_kill() doesn't
4334 * guarantee that the ref is seen as killed on all CPUs on return.
4336 * Use percpu_ref_kill_and_confirm() to get notifications as each
4337 * css is confirmed to be seen as killed on all CPUs.
4339 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4343 * cgroup_destroy_locked - the first stage of cgroup destruction
4344 * @cgrp: cgroup to be destroyed
4346 * css's make use of percpu refcnts whose killing latency shouldn't be
4347 * exposed to userland and are RCU protected. Also, cgroup core needs to
4348 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
4349 * invoked. To satisfy all the requirements, destruction is implemented in
4350 * the following two steps.
4352 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4353 * userland visible parts and start killing the percpu refcnts of
4354 * css's. Set up so that the next stage will be kicked off once all
4355 * the percpu refcnts are confirmed to be killed.
4357 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4358 * rest of destruction. Once all cgroup references are gone, the
4359 * cgroup is RCU-freed.
4361 * This function implements s1. After this step, @cgrp is gone as far as
4362 * the userland is concerned and a new cgroup with the same name may be
4363 * created. As cgroup doesn't care about the names internally, this
4364 * doesn't cause any problem.
4366 static int cgroup_destroy_locked(struct cgroup *cgrp)
4367 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4369 struct dentry *d = cgrp->dentry;
4370 struct cgroup_subsys *ss;
4371 struct cgroup *child;
4374 lockdep_assert_held(&d->d_inode->i_mutex);
4375 lockdep_assert_held(&cgroup_mutex);
4378 * css_set_lock synchronizes access to ->cset_links and prevents
4379 * @cgrp from being removed while __put_css_set() is in progress.
4381 read_lock(&css_set_lock);
4382 empty = list_empty(&cgrp->cset_links);
4383 read_unlock(&css_set_lock);
4388 * Make sure there's no live children. We can't test ->children
4389 * emptiness as dead children linger on it while being destroyed;
4390 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
4394 list_for_each_entry_rcu(child, &cgrp->children, sibling) {
4395 empty = cgroup_is_dead(child);
4404 * Initiate massacre of all css's. cgroup_destroy_css_killed()
4405 * will be invoked to perform the rest of destruction once the
4406 * percpu refs of all css's are confirmed to be killed.
4408 for_each_root_subsys(cgrp->root, ss)
4409 kill_css(cgroup_css(cgrp, ss));
4412 * Mark @cgrp dead. This prevents further task migration and child
4413 * creation by disabling cgroup_lock_live_group(). Note that
4414 * CGRP_DEAD assertion is depended upon by css_next_child() to
4415 * resume iteration after dropping RCU read lock. See
4416 * css_next_child() for details.
4418 set_bit(CGRP_DEAD, &cgrp->flags);
4420 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4421 raw_spin_lock(&release_list_lock);
4422 if (!list_empty(&cgrp->release_list))
4423 list_del_init(&cgrp->release_list);
4424 raw_spin_unlock(&release_list_lock);
4427 * If @cgrp has css's attached, the second stage of cgroup
4428 * destruction is kicked off from css_killed_work_fn() after the
4429 * refs of all attached css's are killed. If @cgrp doesn't have
4430 * any css, we kick it off here.
4433 cgroup_destroy_css_killed(cgrp);
4436 * Clear the base files and remove @cgrp directory. The removal
4437 * puts the base ref but we aren't quite done with @cgrp yet, so
4440 cgroup_addrm_files(cgrp, cgroup_base_files, false);
4442 cgroup_d_remove_dir(d);
4448 * cgroup_destroy_css_killed - the second step of cgroup destruction
4449 * @work: cgroup->destroy_free_work
4451 * This function is invoked from a work item for a cgroup which is being
4452 * destroyed after all css's are offlined and performs the rest of
4453 * destruction. This is the second step of destruction described in the
4454 * comment above cgroup_destroy_locked().
4456 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
4458 struct cgroup *parent = cgrp->parent;
4459 struct dentry *d = cgrp->dentry;
4461 lockdep_assert_held(&cgroup_mutex);
4463 /* delete this cgroup from parent->children */
4464 list_del_rcu(&cgrp->sibling);
4467 * We should remove the cgroup object from idr before its grace
4468 * period starts, so we won't be looking up a cgroup while the
4469 * cgroup is being freed.
4471 idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4476 set_bit(CGRP_RELEASABLE, &parent->flags);
4477 check_for_release(parent);
4480 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4484 mutex_lock(&cgroup_mutex);
4485 ret = cgroup_destroy_locked(dentry->d_fsdata);
4486 mutex_unlock(&cgroup_mutex);
4491 static void __init_or_module cgroup_init_cftsets(struct cgroup_subsys *ss)
4493 INIT_LIST_HEAD(&ss->cftsets);
4496 * base_cftset is embedded in subsys itself, no need to worry about
4499 if (ss->base_cftypes) {
4502 for (cft = ss->base_cftypes; cft->name[0] != '\0'; cft++)
4505 ss->base_cftset.cfts = ss->base_cftypes;
4506 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4510 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4512 struct cgroup_subsys_state *css;
4514 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4516 mutex_lock(&cgroup_mutex);
4518 /* init base cftset */
4519 cgroup_init_cftsets(ss);
4521 /* Create the top cgroup state for this subsystem */
4522 list_add(&ss->sibling, &cgroup_dummy_root.subsys_list);
4523 ss->root = &cgroup_dummy_root;
4524 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
4525 /* We don't handle early failures gracefully */
4526 BUG_ON(IS_ERR(css));
4527 init_css(css, ss, cgroup_dummy_top);
4529 /* Update the init_css_set to contain a subsys
4530 * pointer to this state - since the subsystem is
4531 * newly registered, all tasks and hence the
4532 * init_css_set is in the subsystem's top cgroup. */
4533 init_css_set.subsys[ss->subsys_id] = css;
4535 need_forkexit_callback |= ss->fork || ss->exit;
4537 /* At system boot, before all subsystems have been
4538 * registered, no tasks have been forked, so we don't
4539 * need to invoke fork callbacks here. */
4540 BUG_ON(!list_empty(&init_task.tasks));
4542 BUG_ON(online_css(css));
4544 mutex_unlock(&cgroup_mutex);
4546 /* this function shouldn't be used with modular subsystems, since they
4547 * need to register a subsys_id, among other things */
4552 * cgroup_load_subsys: load and register a modular subsystem at runtime
4553 * @ss: the subsystem to load
4555 * This function should be called in a modular subsystem's initcall. If the
4556 * subsystem is built as a module, it will be assigned a new subsys_id and set
4557 * up for use. If the subsystem is built-in anyway, work is delegated to the
4558 * simpler cgroup_init_subsys.
4560 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
4562 struct cgroup_subsys_state *css;
4564 struct hlist_node *tmp;
4565 struct css_set *cset;
4568 /* check name and function validity */
4569 if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
4570 ss->css_alloc == NULL || ss->css_free == NULL)
4574 * we don't support callbacks in modular subsystems. this check is
4575 * before the ss->module check for consistency; a subsystem that could
4576 * be a module should still have no callbacks even if the user isn't
4577 * compiling it as one.
4579 if (ss->fork || ss->exit)
4583 * an optionally modular subsystem is built-in: we want to do nothing,
4584 * since cgroup_init_subsys will have already taken care of it.
4586 if (ss->module == NULL) {
4587 /* a sanity check */
4588 BUG_ON(cgroup_subsys[ss->subsys_id] != ss);
4592 /* init base cftset */
4593 cgroup_init_cftsets(ss);
4595 mutex_lock(&cgroup_mutex);
4596 cgroup_subsys[ss->subsys_id] = ss;
4599 * no ss->css_alloc seems to need anything important in the ss
4600 * struct, so this can happen first (i.e. before the dummy root
4603 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
4605 /* failure case - need to deassign the cgroup_subsys[] slot. */
4606 cgroup_subsys[ss->subsys_id] = NULL;
4607 mutex_unlock(&cgroup_mutex);
4608 return PTR_ERR(css);
4611 list_add(&ss->sibling, &cgroup_dummy_root.subsys_list);
4612 ss->root = &cgroup_dummy_root;
4614 /* our new subsystem will be attached to the dummy hierarchy. */
4615 init_css(css, ss, cgroup_dummy_top);
4618 * Now we need to entangle the css into the existing css_sets. unlike
4619 * in cgroup_init_subsys, there are now multiple css_sets, so each one
4620 * will need a new pointer to it; done by iterating the css_set_table.
4621 * furthermore, modifying the existing css_sets will corrupt the hash
4622 * table state, so each changed css_set will need its hash recomputed.
4623 * this is all done under the css_set_lock.
4625 write_lock(&css_set_lock);
4626 hash_for_each_safe(css_set_table, i, tmp, cset, hlist) {
4627 /* skip entries that we already rehashed */
4628 if (cset->subsys[ss->subsys_id])
4630 /* remove existing entry */
4631 hash_del(&cset->hlist);
4633 cset->subsys[ss->subsys_id] = css;
4634 /* recompute hash and restore entry */
4635 key = css_set_hash(cset->subsys);
4636 hash_add(css_set_table, &cset->hlist, key);
4638 write_unlock(&css_set_lock);
4640 ret = online_css(css);
4645 mutex_unlock(&cgroup_mutex);
4649 mutex_unlock(&cgroup_mutex);
4650 /* @ss can't be mounted here as try_module_get() would fail */
4651 cgroup_unload_subsys(ss);
4654 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
4657 * cgroup_unload_subsys: unload a modular subsystem
4658 * @ss: the subsystem to unload
4660 * This function should be called in a modular subsystem's exitcall. When this
4661 * function is invoked, the refcount on the subsystem's module will be 0, so
4662 * the subsystem will not be attached to any hierarchy.
4664 void cgroup_unload_subsys(struct cgroup_subsys *ss)
4666 struct cgrp_cset_link *link;
4668 BUG_ON(ss->module == NULL);
4671 * we shouldn't be called if the subsystem is in use, and the use of
4672 * try_module_get() in rebind_subsystems() should ensure that it
4673 * doesn't start being used while we're killing it off.
4675 BUG_ON(ss->root != &cgroup_dummy_root);
4677 mutex_lock(&cgroup_mutex);
4679 offline_css(cgroup_css(cgroup_dummy_top, ss));
4681 /* deassign the subsys_id */
4682 cgroup_subsys[ss->subsys_id] = NULL;
4684 /* remove subsystem from the dummy root's list of subsystems */
4685 list_del_init(&ss->sibling);
4688 * disentangle the css from all css_sets attached to the dummy
4689 * top. as in loading, we need to pay our respects to the hashtable
4692 write_lock(&css_set_lock);
4693 list_for_each_entry(link, &cgroup_dummy_top->cset_links, cset_link) {
4694 struct css_set *cset = link->cset;
4697 hash_del(&cset->hlist);
4698 cset->subsys[ss->subsys_id] = NULL;
4699 key = css_set_hash(cset->subsys);
4700 hash_add(css_set_table, &cset->hlist, key);
4702 write_unlock(&css_set_lock);
4705 * remove subsystem's css from the cgroup_dummy_top and free it -
4706 * need to free before marking as null because ss->css_free needs
4707 * the cgrp->subsys pointer to find their state.
4709 ss->css_free(cgroup_css(cgroup_dummy_top, ss));
4710 RCU_INIT_POINTER(cgroup_dummy_top->subsys[ss->subsys_id], NULL);
4712 mutex_unlock(&cgroup_mutex);
4714 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
4717 * cgroup_init_early - cgroup initialization at system boot
4719 * Initialize cgroups at system boot, and initialize any
4720 * subsystems that request early init.
4722 int __init cgroup_init_early(void)
4724 struct cgroup_subsys *ss;
4727 atomic_set(&init_css_set.refcount, 1);
4728 INIT_LIST_HEAD(&init_css_set.cgrp_links);
4729 INIT_LIST_HEAD(&init_css_set.tasks);
4730 INIT_HLIST_NODE(&init_css_set.hlist);
4732 init_cgroup_root(&cgroup_dummy_root);
4733 cgroup_root_count = 1;
4734 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4736 init_cgrp_cset_link.cset = &init_css_set;
4737 init_cgrp_cset_link.cgrp = cgroup_dummy_top;
4738 list_add(&init_cgrp_cset_link.cset_link, &cgroup_dummy_top->cset_links);
4739 list_add(&init_cgrp_cset_link.cgrp_link, &init_css_set.cgrp_links);
4741 /* at bootup time, we don't worry about modular subsystems */
4742 for_each_builtin_subsys(ss, i) {
4744 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
4745 BUG_ON(!ss->css_alloc);
4746 BUG_ON(!ss->css_free);
4747 if (ss->subsys_id != i) {
4748 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
4749 ss->name, ss->subsys_id);
4754 cgroup_init_subsys(ss);
4760 * cgroup_init - cgroup initialization
4762 * Register cgroup filesystem and /proc file, and initialize
4763 * any subsystems that didn't request early init.
4765 int __init cgroup_init(void)
4767 struct cgroup_subsys *ss;
4771 err = bdi_init(&cgroup_backing_dev_info);
4775 for_each_builtin_subsys(ss, i) {
4776 if (!ss->early_init)
4777 cgroup_init_subsys(ss);
4780 /* allocate id for the dummy hierarchy */
4781 mutex_lock(&cgroup_mutex);
4782 mutex_lock(&cgroup_root_mutex);
4784 /* Add init_css_set to the hash table */
4785 key = css_set_hash(init_css_set.subsys);
4786 hash_add(css_set_table, &init_css_set.hlist, key);
4788 BUG_ON(cgroup_init_root_id(&cgroup_dummy_root, 0, 1));
4790 err = idr_alloc(&cgroup_dummy_root.cgroup_idr, cgroup_dummy_top,
4794 mutex_unlock(&cgroup_root_mutex);
4795 mutex_unlock(&cgroup_mutex);
4797 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4803 err = register_filesystem(&cgroup_fs_type);
4805 kobject_put(cgroup_kobj);
4809 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4813 bdi_destroy(&cgroup_backing_dev_info);
4818 static int __init cgroup_wq_init(void)
4821 * There isn't much point in executing destruction path in
4822 * parallel. Good chunk is serialized with cgroup_mutex anyway.
4823 * Use 1 for @max_active.
4825 * We would prefer to do this in cgroup_init() above, but that
4826 * is called before init_workqueues(): so leave this until after.
4828 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
4829 BUG_ON(!cgroup_destroy_wq);
4832 core_initcall(cgroup_wq_init);
4835 * proc_cgroup_show()
4836 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4837 * - Used for /proc/<pid>/cgroup.
4838 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4839 * doesn't really matter if tsk->cgroup changes after we read it,
4840 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4841 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4842 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4843 * cgroup to top_cgroup.
4846 /* TODO: Use a proper seq_file iterator */
4847 int proc_cgroup_show(struct seq_file *m, void *v)
4850 struct task_struct *tsk;
4853 struct cgroupfs_root *root;
4856 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4862 tsk = get_pid_task(pid, PIDTYPE_PID);
4868 mutex_lock(&cgroup_mutex);
4870 for_each_active_root(root) {
4871 struct cgroup_subsys *ss;
4872 struct cgroup *cgrp;
4875 seq_printf(m, "%d:", root->hierarchy_id);
4876 for_each_root_subsys(root, ss)
4877 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4878 if (strlen(root->name))
4879 seq_printf(m, "%sname=%s", count ? "," : "",
4882 cgrp = task_cgroup_from_root(tsk, root);
4883 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
4891 mutex_unlock(&cgroup_mutex);
4892 put_task_struct(tsk);
4899 /* Display information about each subsystem and each hierarchy */
4900 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4902 struct cgroup_subsys *ss;
4905 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4907 * ideally we don't want subsystems moving around while we do this.
4908 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4909 * subsys/hierarchy state.
4911 mutex_lock(&cgroup_mutex);
4913 for_each_subsys(ss, i)
4914 seq_printf(m, "%s\t%d\t%d\t%d\n",
4915 ss->name, ss->root->hierarchy_id,
4916 ss->root->number_of_cgroups, !ss->disabled);
4918 mutex_unlock(&cgroup_mutex);
4922 static int cgroupstats_open(struct inode *inode, struct file *file)
4924 return single_open(file, proc_cgroupstats_show, NULL);
4927 static const struct file_operations proc_cgroupstats_operations = {
4928 .open = cgroupstats_open,
4930 .llseek = seq_lseek,
4931 .release = single_release,
4935 * cgroup_fork - attach newly forked task to its parents cgroup.
4936 * @child: pointer to task_struct of forking parent process.
4938 * Description: A task inherits its parent's cgroup at fork().
4940 * A pointer to the shared css_set was automatically copied in
4941 * fork.c by dup_task_struct(). However, we ignore that copy, since
4942 * it was not made under the protection of RCU or cgroup_mutex, so
4943 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
4944 * have already changed current->cgroups, allowing the previously
4945 * referenced cgroup group to be removed and freed.
4947 * At the point that cgroup_fork() is called, 'current' is the parent
4948 * task, and the passed argument 'child' points to the child task.
4950 void cgroup_fork(struct task_struct *child)
4953 get_css_set(task_css_set(current));
4954 child->cgroups = current->cgroups;
4955 task_unlock(current);
4956 INIT_LIST_HEAD(&child->cg_list);
4960 * cgroup_post_fork - called on a new task after adding it to the task list
4961 * @child: the task in question
4963 * Adds the task to the list running through its css_set if necessary and
4964 * call the subsystem fork() callbacks. Has to be after the task is
4965 * visible on the task list in case we race with the first call to
4966 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
4969 void cgroup_post_fork(struct task_struct *child)
4971 struct cgroup_subsys *ss;
4975 * use_task_css_set_links is set to 1 before we walk the tasklist
4976 * under the tasklist_lock and we read it here after we added the child
4977 * to the tasklist under the tasklist_lock as well. If the child wasn't
4978 * yet in the tasklist when we walked through it from
4979 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4980 * should be visible now due to the paired locking and barriers implied
4981 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4982 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4985 if (use_task_css_set_links) {
4986 write_lock(&css_set_lock);
4988 if (list_empty(&child->cg_list))
4989 list_add(&child->cg_list, &task_css_set(child)->tasks);
4991 write_unlock(&css_set_lock);
4995 * Call ss->fork(). This must happen after @child is linked on
4996 * css_set; otherwise, @child might change state between ->fork()
4997 * and addition to css_set.
4999 if (need_forkexit_callback) {
5001 * fork/exit callbacks are supported only for builtin
5002 * subsystems, and the builtin section of the subsys
5003 * array is immutable, so we don't need to lock the
5004 * subsys array here. On the other hand, modular section
5005 * of the array can be freed at module unload, so we
5008 for_each_builtin_subsys(ss, i)
5015 * cgroup_exit - detach cgroup from exiting task
5016 * @tsk: pointer to task_struct of exiting process
5017 * @run_callback: run exit callbacks?
5019 * Description: Detach cgroup from @tsk and release it.
5021 * Note that cgroups marked notify_on_release force every task in
5022 * them to take the global cgroup_mutex mutex when exiting.
5023 * This could impact scaling on very large systems. Be reluctant to
5024 * use notify_on_release cgroups where very high task exit scaling
5025 * is required on large systems.
5027 * the_top_cgroup_hack:
5029 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
5031 * We call cgroup_exit() while the task is still competent to
5032 * handle notify_on_release(), then leave the task attached to the
5033 * root cgroup in each hierarchy for the remainder of its exit.
5035 * To do this properly, we would increment the reference count on
5036 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
5037 * code we would add a second cgroup function call, to drop that
5038 * reference. This would just create an unnecessary hot spot on
5039 * the top_cgroup reference count, to no avail.
5041 * Normally, holding a reference to a cgroup without bumping its
5042 * count is unsafe. The cgroup could go away, or someone could
5043 * attach us to a different cgroup, decrementing the count on
5044 * the first cgroup that we never incremented. But in this case,
5045 * top_cgroup isn't going away, and either task has PF_EXITING set,
5046 * which wards off any cgroup_attach_task() attempts, or task is a failed
5047 * fork, never visible to cgroup_attach_task.
5049 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
5051 struct cgroup_subsys *ss;
5052 struct css_set *cset;
5056 * Unlink from the css_set task list if necessary.
5057 * Optimistically check cg_list before taking
5060 if (!list_empty(&tsk->cg_list)) {
5061 write_lock(&css_set_lock);
5062 if (!list_empty(&tsk->cg_list))
5063 list_del_init(&tsk->cg_list);
5064 write_unlock(&css_set_lock);
5067 /* Reassign the task to the init_css_set. */
5069 cset = task_css_set(tsk);
5070 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
5072 if (run_callbacks && need_forkexit_callback) {
5074 * fork/exit callbacks are supported only for builtin
5075 * subsystems, see cgroup_post_fork() for details.
5077 for_each_builtin_subsys(ss, i) {
5079 struct cgroup_subsys_state *old_css = cset->subsys[i];
5080 struct cgroup_subsys_state *css = task_css(tsk, i);
5082 ss->exit(css, old_css, tsk);
5088 put_css_set_taskexit(cset);
5091 static void check_for_release(struct cgroup *cgrp)
5093 if (cgroup_is_releasable(cgrp) &&
5094 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
5096 * Control Group is currently removeable. If it's not
5097 * already queued for a userspace notification, queue
5100 int need_schedule_work = 0;
5102 raw_spin_lock(&release_list_lock);
5103 if (!cgroup_is_dead(cgrp) &&
5104 list_empty(&cgrp->release_list)) {
5105 list_add(&cgrp->release_list, &release_list);
5106 need_schedule_work = 1;
5108 raw_spin_unlock(&release_list_lock);
5109 if (need_schedule_work)
5110 schedule_work(&release_agent_work);
5115 * Notify userspace when a cgroup is released, by running the
5116 * configured release agent with the name of the cgroup (path
5117 * relative to the root of cgroup file system) as the argument.
5119 * Most likely, this user command will try to rmdir this cgroup.
5121 * This races with the possibility that some other task will be
5122 * attached to this cgroup before it is removed, or that some other
5123 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5124 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5125 * unused, and this cgroup will be reprieved from its death sentence,
5126 * to continue to serve a useful existence. Next time it's released,
5127 * we will get notified again, if it still has 'notify_on_release' set.
5129 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5130 * means only wait until the task is successfully execve()'d. The
5131 * separate release agent task is forked by call_usermodehelper(),
5132 * then control in this thread returns here, without waiting for the
5133 * release agent task. We don't bother to wait because the caller of
5134 * this routine has no use for the exit status of the release agent
5135 * task, so no sense holding our caller up for that.
5137 static void cgroup_release_agent(struct work_struct *work)
5139 BUG_ON(work != &release_agent_work);
5140 mutex_lock(&cgroup_mutex);
5141 raw_spin_lock(&release_list_lock);
5142 while (!list_empty(&release_list)) {
5143 char *argv[3], *envp[3];
5145 char *pathbuf = NULL, *agentbuf = NULL;
5146 struct cgroup *cgrp = list_entry(release_list.next,
5149 list_del_init(&cgrp->release_list);
5150 raw_spin_unlock(&release_list_lock);
5151 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5154 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
5156 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5161 argv[i++] = agentbuf;
5162 argv[i++] = pathbuf;
5166 /* minimal command environment */
5167 envp[i++] = "HOME=/";
5168 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5171 /* Drop the lock while we invoke the usermode helper,
5172 * since the exec could involve hitting disk and hence
5173 * be a slow process */
5174 mutex_unlock(&cgroup_mutex);
5175 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5176 mutex_lock(&cgroup_mutex);
5180 raw_spin_lock(&release_list_lock);
5182 raw_spin_unlock(&release_list_lock);
5183 mutex_unlock(&cgroup_mutex);
5186 static int __init cgroup_disable(char *str)
5188 struct cgroup_subsys *ss;
5192 while ((token = strsep(&str, ",")) != NULL) {
5197 * cgroup_disable, being at boot time, can't know about
5198 * module subsystems, so we don't worry about them.
5200 for_each_builtin_subsys(ss, i) {
5201 if (!strcmp(token, ss->name)) {
5203 printk(KERN_INFO "Disabling %s control group"
5204 " subsystem\n", ss->name);
5211 __setup("cgroup_disable=", cgroup_disable);
5214 * css_from_dir - get corresponding css from the dentry of a cgroup dir
5215 * @dentry: directory dentry of interest
5216 * @ss: subsystem of interest
5218 * Must be called under RCU read lock. The caller is responsible for
5219 * pinning the returned css if it needs to be accessed outside the RCU
5222 struct cgroup_subsys_state *css_from_dir(struct dentry *dentry,
5223 struct cgroup_subsys *ss)
5225 struct cgroup *cgrp;
5227 WARN_ON_ONCE(!rcu_read_lock_held());
5229 /* is @dentry a cgroup dir? */
5230 if (!dentry->d_inode ||
5231 dentry->d_inode->i_op != &cgroup_dir_inode_operations)
5232 return ERR_PTR(-EBADF);
5234 cgrp = __d_cgrp(dentry);
5235 return cgroup_css(cgrp, ss) ?: ERR_PTR(-ENOENT);
5239 * css_from_id - lookup css by id
5240 * @id: the cgroup id
5241 * @ss: cgroup subsys to be looked into
5243 * Returns the css if there's valid one with @id, otherwise returns NULL.
5244 * Should be called under rcu_read_lock().
5246 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5248 struct cgroup *cgrp;
5250 rcu_lockdep_assert(rcu_read_lock_held() ||
5251 lockdep_is_held(&cgroup_mutex),
5252 "css_from_id() needs proper protection");
5254 cgrp = idr_find(&ss->root->cgroup_idr, id);
5256 return cgroup_css(cgrp, ss);
5260 #ifdef CONFIG_CGROUP_DEBUG
5261 static struct cgroup_subsys_state *
5262 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5264 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5267 return ERR_PTR(-ENOMEM);
5272 static void debug_css_free(struct cgroup_subsys_state *css)
5277 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5280 return cgroup_task_count(css->cgroup);
5283 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5286 return (u64)(unsigned long)current->cgroups;
5289 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5295 count = atomic_read(&task_css_set(current)->refcount);
5300 static int current_css_set_cg_links_read(struct cgroup_subsys_state *css,
5302 struct seq_file *seq)
5304 struct cgrp_cset_link *link;
5305 struct css_set *cset;
5307 read_lock(&css_set_lock);
5309 cset = rcu_dereference(current->cgroups);
5310 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5311 struct cgroup *c = link->cgrp;
5315 name = c->dentry->d_name.name;
5318 seq_printf(seq, "Root %d group %s\n",
5319 c->root->hierarchy_id, name);
5322 read_unlock(&css_set_lock);
5326 #define MAX_TASKS_SHOWN_PER_CSS 25
5327 static int cgroup_css_links_read(struct cgroup_subsys_state *css,
5328 struct cftype *cft, struct seq_file *seq)
5330 struct cgrp_cset_link *link;
5332 read_lock(&css_set_lock);
5333 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5334 struct css_set *cset = link->cset;
5335 struct task_struct *task;
5337 seq_printf(seq, "css_set %p\n", cset);
5338 list_for_each_entry(task, &cset->tasks, cg_list) {
5339 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5340 seq_puts(seq, " ...\n");
5343 seq_printf(seq, " task %d\n",
5344 task_pid_vnr(task));
5348 read_unlock(&css_set_lock);
5352 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5354 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
5357 static struct cftype debug_files[] = {
5359 .name = "taskcount",
5360 .read_u64 = debug_taskcount_read,
5364 .name = "current_css_set",
5365 .read_u64 = current_css_set_read,
5369 .name = "current_css_set_refcount",
5370 .read_u64 = current_css_set_refcount_read,
5374 .name = "current_css_set_cg_links",
5375 .read_seq_string = current_css_set_cg_links_read,
5379 .name = "cgroup_css_links",
5380 .read_seq_string = cgroup_css_links_read,
5384 .name = "releasable",
5385 .read_u64 = releasable_read,
5391 struct cgroup_subsys debug_subsys = {
5393 .css_alloc = debug_css_alloc,
5394 .css_free = debug_css_free,
5395 .subsys_id = debug_subsys_id,
5396 .base_cftypes = debug_files,
5398 #endif /* CONFIG_CGROUP_DEBUG */