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/slab.h>
45 #include <linux/magic.h>
46 #include <linux/spinlock.h>
47 #include <linux/string.h>
48 #include <linux/sort.h>
49 #include <linux/kmod.h>
50 #include <linux/delayacct.h>
51 #include <linux/cgroupstats.h>
52 #include <linux/hashtable.h>
53 #include <linux/namei.h>
54 #include <linux/pid_namespace.h>
55 #include <linux/idr.h>
56 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
57 #include <linux/flex_array.h> /* used in cgroup_attach_task */
58 #include <linux/kthread.h>
60 #include <linux/atomic.h>
63 * pidlists linger the following amount before being destroyed. The goal
64 * is avoiding frequent destruction in the middle of consecutive read calls
65 * Expiring in the middle is a performance problem not a correctness one.
66 * 1 sec should be enough.
68 #define CGROUP_PIDLIST_DESTROY_DELAY HZ
71 * cgroup_mutex is the master lock. Any modification to cgroup or its
72 * hierarchy must be performed while holding it.
74 * cgroup_root_mutex nests inside cgroup_mutex and should be held to modify
75 * cgroupfs_root of any cgroup hierarchy - subsys list, flags,
76 * release_agent_path and so on. Modifying requires both cgroup_mutex and
77 * cgroup_root_mutex. Readers can acquire either of the two. This is to
78 * break the following locking order cycle.
80 * A. cgroup_mutex -> cred_guard_mutex -> s_type->i_mutex_key -> namespace_sem
81 * B. namespace_sem -> cgroup_mutex
83 * B happens only through cgroup_show_options() and using cgroup_root_mutex
86 #ifdef CONFIG_PROVE_RCU
87 DEFINE_MUTEX(cgroup_mutex);
88 EXPORT_SYMBOL_GPL(cgroup_mutex); /* only for lockdep */
90 static DEFINE_MUTEX(cgroup_mutex);
93 static DEFINE_MUTEX(cgroup_root_mutex);
95 #define cgroup_assert_mutex_or_rcu_locked() \
96 rcu_lockdep_assert(rcu_read_lock_held() || \
97 lockdep_is_held(&cgroup_mutex), \
98 "cgroup_mutex or RCU read lock required");
100 #ifdef CONFIG_LOCKDEP
101 #define cgroup_assert_mutex_or_root_locked() \
102 WARN_ON_ONCE(debug_locks && (!lockdep_is_held(&cgroup_mutex) && \
103 !lockdep_is_held(&cgroup_root_mutex)))
105 #define cgroup_assert_mutex_or_root_locked() do { } while (0)
109 * cgroup destruction makes heavy use of work items and there can be a lot
110 * of concurrent destructions. Use a separate workqueue so that cgroup
111 * destruction work items don't end up filling up max_active of system_wq
112 * which may lead to deadlock.
114 static struct workqueue_struct *cgroup_destroy_wq;
117 * pidlist destructions need to be flushed on cgroup destruction. Use a
118 * separate workqueue as flush domain.
120 static struct workqueue_struct *cgroup_pidlist_destroy_wq;
122 /* generate an array of cgroup subsystem pointers */
123 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
124 static struct cgroup_subsys *cgroup_subsys[] = {
125 #include <linux/cgroup_subsys.h>
129 /* array of cgroup subsystem names */
130 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
131 static const char *cgroup_subsys_name[] = {
132 #include <linux/cgroup_subsys.h>
137 * The dummy hierarchy, reserved for the subsystems that are otherwise
138 * unattached - it never has more than a single cgroup, and all tasks are
139 * part of that cgroup.
141 static struct cgroupfs_root cgroup_dummy_root;
143 /* dummy_top is a shorthand for the dummy hierarchy's top cgroup */
144 static struct cgroup * const cgroup_dummy_top = &cgroup_dummy_root.top_cgroup;
146 /* The list of hierarchy roots */
148 static LIST_HEAD(cgroup_roots);
149 static int cgroup_root_count;
152 * Hierarchy ID allocation and mapping. It follows the same exclusion
153 * rules as other root ops - both cgroup_mutex and cgroup_root_mutex for
154 * writes, either for reads.
156 static DEFINE_IDR(cgroup_hierarchy_idr);
158 static struct cgroup_name root_cgroup_name = { .name = "/" };
161 * Assign a monotonically increasing serial number to cgroups. It
162 * guarantees cgroups with bigger numbers are newer than those with smaller
163 * numbers. Also, as cgroups are always appended to the parent's
164 * ->children list, it guarantees that sibling cgroups are always sorted in
165 * the ascending serial number order on the list. Protected by
168 static u64 cgroup_serial_nr_next = 1;
170 /* This flag indicates whether tasks in the fork and exit paths should
171 * check for fork/exit handlers to call. This avoids us having to do
172 * extra work in the fork/exit path if none of the subsystems need to
175 static int need_forkexit_callback __read_mostly;
177 static struct cftype cgroup_base_files[];
179 static void cgroup_destroy_css_killed(struct cgroup *cgrp);
180 static int cgroup_destroy_locked(struct cgroup *cgrp);
181 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
183 static int cgroup_file_release(struct inode *inode, struct file *file);
184 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp);
187 * cgroup_css - obtain a cgroup's css for the specified subsystem
188 * @cgrp: the cgroup of interest
189 * @ss: the subsystem of interest (%NULL returns the dummy_css)
191 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
192 * function must be called either under cgroup_mutex or rcu_read_lock() and
193 * the caller is responsible for pinning the returned css if it wants to
194 * keep accessing it outside the said locks. This function may return
195 * %NULL if @cgrp doesn't have @subsys_id enabled.
197 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
198 struct cgroup_subsys *ss)
201 return rcu_dereference_check(cgrp->subsys[ss->id],
202 lockdep_is_held(&cgroup_mutex));
204 return &cgrp->dummy_css;
207 /* convenient tests for these bits */
208 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
210 return test_bit(CGRP_DEAD, &cgrp->flags);
214 * cgroup_is_descendant - test ancestry
215 * @cgrp: the cgroup to be tested
216 * @ancestor: possible ancestor of @cgrp
218 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
219 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
220 * and @ancestor are accessible.
222 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
225 if (cgrp == ancestor)
231 EXPORT_SYMBOL_GPL(cgroup_is_descendant);
233 static int cgroup_is_releasable(const struct cgroup *cgrp)
236 (1 << CGRP_RELEASABLE) |
237 (1 << CGRP_NOTIFY_ON_RELEASE);
238 return (cgrp->flags & bits) == bits;
241 static int notify_on_release(const struct cgroup *cgrp)
243 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
247 * for_each_css - iterate all css's of a cgroup
248 * @css: the iteration cursor
249 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
250 * @cgrp: the target cgroup to iterate css's of
252 * Should be called under cgroup_mutex.
254 #define for_each_css(css, ssid, cgrp) \
255 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
256 if (!((css) = rcu_dereference_check( \
257 (cgrp)->subsys[(ssid)], \
258 lockdep_is_held(&cgroup_mutex)))) { } \
262 * for_each_subsys - iterate all enabled cgroup subsystems
263 * @ss: the iteration cursor
264 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
266 #define for_each_subsys(ss, ssid) \
267 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT && \
268 (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
270 /* iterate across the active hierarchies */
271 #define for_each_active_root(root) \
272 list_for_each_entry((root), &cgroup_roots, root_list)
274 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
276 return dentry->d_fsdata;
279 static inline struct cfent *__d_cfe(struct dentry *dentry)
281 return dentry->d_fsdata;
284 static inline struct cftype *__d_cft(struct dentry *dentry)
286 return __d_cfe(dentry)->type;
290 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
291 * @cgrp: the cgroup to be checked for liveness
293 * On success, returns true; the mutex should be later unlocked. On
294 * failure returns false with no lock held.
296 static bool cgroup_lock_live_group(struct cgroup *cgrp)
298 mutex_lock(&cgroup_mutex);
299 if (cgroup_is_dead(cgrp)) {
300 mutex_unlock(&cgroup_mutex);
306 /* the list of cgroups eligible for automatic release. Protected by
307 * release_list_lock */
308 static LIST_HEAD(release_list);
309 static DEFINE_RAW_SPINLOCK(release_list_lock);
310 static void cgroup_release_agent(struct work_struct *work);
311 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
312 static void check_for_release(struct cgroup *cgrp);
315 * A cgroup can be associated with multiple css_sets as different tasks may
316 * belong to different cgroups on different hierarchies. In the other
317 * direction, a css_set is naturally associated with multiple cgroups.
318 * This M:N relationship is represented by the following link structure
319 * which exists for each association and allows traversing the associations
322 struct cgrp_cset_link {
323 /* the cgroup and css_set this link associates */
325 struct css_set *cset;
327 /* list of cgrp_cset_links anchored at cgrp->cset_links */
328 struct list_head cset_link;
330 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
331 struct list_head cgrp_link;
334 /* The default css_set - used by init and its children prior to any
335 * hierarchies being mounted. It contains a pointer to the root state
336 * for each subsystem. Also used to anchor the list of css_sets. Not
337 * reference-counted, to improve performance when child cgroups
338 * haven't been created.
341 static struct css_set init_css_set;
342 static struct cgrp_cset_link init_cgrp_cset_link;
345 * css_set_lock protects the list of css_set objects, and the chain of
346 * tasks off each css_set. Nests outside task->alloc_lock due to
347 * css_task_iter_start().
349 static DEFINE_RWLOCK(css_set_lock);
350 static int css_set_count;
353 * hash table for cgroup groups. This improves the performance to find
354 * an existing css_set. This hash doesn't (currently) take into
355 * account cgroups in empty hierarchies.
357 #define CSS_SET_HASH_BITS 7
358 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
360 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
362 unsigned long key = 0UL;
363 struct cgroup_subsys *ss;
366 for_each_subsys(ss, i)
367 key += (unsigned long)css[i];
368 key = (key >> 16) ^ key;
374 * We don't maintain the lists running through each css_set to its task
375 * until after the first call to css_task_iter_start(). This reduces the
376 * fork()/exit() overhead for people who have cgroups compiled into their
377 * kernel but not actually in use.
379 static int use_task_css_set_links __read_mostly;
381 static void __put_css_set(struct css_set *cset, int taskexit)
383 struct cgrp_cset_link *link, *tmp_link;
386 * Ensure that the refcount doesn't hit zero while any readers
387 * can see it. Similar to atomic_dec_and_lock(), but for an
390 if (atomic_add_unless(&cset->refcount, -1, 1))
392 write_lock(&css_set_lock);
393 if (!atomic_dec_and_test(&cset->refcount)) {
394 write_unlock(&css_set_lock);
398 /* This css_set is dead. unlink it and release cgroup refcounts */
399 hash_del(&cset->hlist);
402 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
403 struct cgroup *cgrp = link->cgrp;
405 list_del(&link->cset_link);
406 list_del(&link->cgrp_link);
408 /* @cgrp can't go away while we're holding css_set_lock */
409 if (list_empty(&cgrp->cset_links) && notify_on_release(cgrp)) {
411 set_bit(CGRP_RELEASABLE, &cgrp->flags);
412 check_for_release(cgrp);
418 write_unlock(&css_set_lock);
419 kfree_rcu(cset, rcu_head);
423 * refcounted get/put for css_set objects
425 static inline void get_css_set(struct css_set *cset)
427 atomic_inc(&cset->refcount);
430 static inline void put_css_set(struct css_set *cset)
432 __put_css_set(cset, 0);
435 static inline void put_css_set_taskexit(struct css_set *cset)
437 __put_css_set(cset, 1);
441 * compare_css_sets - helper function for find_existing_css_set().
442 * @cset: candidate css_set being tested
443 * @old_cset: existing css_set for a task
444 * @new_cgrp: cgroup that's being entered by the task
445 * @template: desired set of css pointers in css_set (pre-calculated)
447 * Returns true if "cset" matches "old_cset" except for the hierarchy
448 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
450 static bool compare_css_sets(struct css_set *cset,
451 struct css_set *old_cset,
452 struct cgroup *new_cgrp,
453 struct cgroup_subsys_state *template[])
455 struct list_head *l1, *l2;
457 if (memcmp(template, cset->subsys, sizeof(cset->subsys))) {
458 /* Not all subsystems matched */
463 * Compare cgroup pointers in order to distinguish between
464 * different cgroups in heirarchies with no subsystems. We
465 * could get by with just this check alone (and skip the
466 * memcmp above) but on most setups the memcmp check will
467 * avoid the need for this more expensive check on almost all
471 l1 = &cset->cgrp_links;
472 l2 = &old_cset->cgrp_links;
474 struct cgrp_cset_link *link1, *link2;
475 struct cgroup *cgrp1, *cgrp2;
479 /* See if we reached the end - both lists are equal length. */
480 if (l1 == &cset->cgrp_links) {
481 BUG_ON(l2 != &old_cset->cgrp_links);
484 BUG_ON(l2 == &old_cset->cgrp_links);
486 /* Locate the cgroups associated with these links. */
487 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
488 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
491 /* Hierarchies should be linked in the same order. */
492 BUG_ON(cgrp1->root != cgrp2->root);
495 * If this hierarchy is the hierarchy of the cgroup
496 * that's changing, then we need to check that this
497 * css_set points to the new cgroup; if it's any other
498 * hierarchy, then this css_set should point to the
499 * same cgroup as the old css_set.
501 if (cgrp1->root == new_cgrp->root) {
502 if (cgrp1 != new_cgrp)
513 * find_existing_css_set - init css array and find the matching css_set
514 * @old_cset: the css_set that we're using before the cgroup transition
515 * @cgrp: the cgroup that we're moving into
516 * @template: out param for the new set of csses, should be clear on entry
518 static struct css_set *find_existing_css_set(struct css_set *old_cset,
520 struct cgroup_subsys_state *template[])
522 struct cgroupfs_root *root = cgrp->root;
523 struct cgroup_subsys *ss;
524 struct css_set *cset;
529 * Build the set of subsystem state objects that we want to see in the
530 * new css_set. while subsystems can change globally, the entries here
531 * won't change, so no need for locking.
533 for_each_subsys(ss, i) {
534 if (root->subsys_mask & (1UL << i)) {
535 /* Subsystem is in this hierarchy. So we want
536 * the subsystem state from the new
538 template[i] = cgroup_css(cgrp, ss);
540 /* Subsystem is not in this hierarchy, so we
541 * don't want to change the subsystem state */
542 template[i] = old_cset->subsys[i];
546 key = css_set_hash(template);
547 hash_for_each_possible(css_set_table, cset, hlist, key) {
548 if (!compare_css_sets(cset, old_cset, cgrp, template))
551 /* This css_set matches what we need */
555 /* No existing cgroup group matched */
559 static void free_cgrp_cset_links(struct list_head *links_to_free)
561 struct cgrp_cset_link *link, *tmp_link;
563 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
564 list_del(&link->cset_link);
570 * allocate_cgrp_cset_links - allocate cgrp_cset_links
571 * @count: the number of links to allocate
572 * @tmp_links: list_head the allocated links are put on
574 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
575 * through ->cset_link. Returns 0 on success or -errno.
577 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
579 struct cgrp_cset_link *link;
582 INIT_LIST_HEAD(tmp_links);
584 for (i = 0; i < count; i++) {
585 link = kzalloc(sizeof(*link), GFP_KERNEL);
587 free_cgrp_cset_links(tmp_links);
590 list_add(&link->cset_link, tmp_links);
596 * link_css_set - a helper function to link a css_set to a cgroup
597 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
598 * @cset: the css_set to be linked
599 * @cgrp: the destination cgroup
601 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
604 struct cgrp_cset_link *link;
606 BUG_ON(list_empty(tmp_links));
607 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
610 list_move(&link->cset_link, &cgrp->cset_links);
612 * Always add links to the tail of the list so that the list
613 * is sorted by order of hierarchy creation
615 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
619 * find_css_set - return a new css_set with one cgroup updated
620 * @old_cset: the baseline css_set
621 * @cgrp: the cgroup to be updated
623 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
624 * substituted into the appropriate hierarchy.
626 static struct css_set *find_css_set(struct css_set *old_cset,
629 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
630 struct css_set *cset;
631 struct list_head tmp_links;
632 struct cgrp_cset_link *link;
635 lockdep_assert_held(&cgroup_mutex);
637 /* First see if we already have a cgroup group that matches
639 read_lock(&css_set_lock);
640 cset = find_existing_css_set(old_cset, cgrp, template);
643 read_unlock(&css_set_lock);
648 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
652 /* Allocate all the cgrp_cset_link objects that we'll need */
653 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
658 atomic_set(&cset->refcount, 1);
659 INIT_LIST_HEAD(&cset->cgrp_links);
660 INIT_LIST_HEAD(&cset->tasks);
661 INIT_HLIST_NODE(&cset->hlist);
663 /* Copy the set of subsystem state objects generated in
664 * find_existing_css_set() */
665 memcpy(cset->subsys, template, sizeof(cset->subsys));
667 write_lock(&css_set_lock);
668 /* Add reference counts and links from the new css_set. */
669 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
670 struct cgroup *c = link->cgrp;
672 if (c->root == cgrp->root)
674 link_css_set(&tmp_links, cset, c);
677 BUG_ON(!list_empty(&tmp_links));
681 /* Add this cgroup group to the hash table */
682 key = css_set_hash(cset->subsys);
683 hash_add(css_set_table, &cset->hlist, key);
685 write_unlock(&css_set_lock);
691 * Return the cgroup for "task" from the given hierarchy. Must be
692 * called with cgroup_mutex held.
694 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
695 struct cgroupfs_root *root)
697 struct css_set *cset;
698 struct cgroup *res = NULL;
700 BUG_ON(!mutex_is_locked(&cgroup_mutex));
701 read_lock(&css_set_lock);
703 * No need to lock the task - since we hold cgroup_mutex the
704 * task can't change groups, so the only thing that can happen
705 * is that it exits and its css is set back to init_css_set.
707 cset = task_css_set(task);
708 if (cset == &init_css_set) {
709 res = &root->top_cgroup;
711 struct cgrp_cset_link *link;
713 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
714 struct cgroup *c = link->cgrp;
716 if (c->root == root) {
722 read_unlock(&css_set_lock);
728 * There is one global cgroup mutex. We also require taking
729 * task_lock() when dereferencing a task's cgroup subsys pointers.
730 * See "The task_lock() exception", at the end of this comment.
732 * A task must hold cgroup_mutex to modify cgroups.
734 * Any task can increment and decrement the count field without lock.
735 * So in general, code holding cgroup_mutex can't rely on the count
736 * field not changing. However, if the count goes to zero, then only
737 * cgroup_attach_task() can increment it again. Because a count of zero
738 * means that no tasks are currently attached, therefore there is no
739 * way a task attached to that cgroup can fork (the other way to
740 * increment the count). So code holding cgroup_mutex can safely
741 * assume that if the count is zero, it will stay zero. Similarly, if
742 * a task holds cgroup_mutex on a cgroup with zero count, it
743 * knows that the cgroup won't be removed, as cgroup_rmdir()
746 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
747 * (usually) take cgroup_mutex. These are the two most performance
748 * critical pieces of code here. The exception occurs on cgroup_exit(),
749 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
750 * is taken, and if the cgroup count is zero, a usermode call made
751 * to the release agent with the name of the cgroup (path relative to
752 * the root of cgroup file system) as the argument.
754 * A cgroup can only be deleted if both its 'count' of using tasks
755 * is zero, and its list of 'children' cgroups is empty. Since all
756 * tasks in the system use _some_ cgroup, and since there is always at
757 * least one task in the system (init, pid == 1), therefore, top_cgroup
758 * always has either children cgroups and/or using tasks. So we don't
759 * need a special hack to ensure that top_cgroup cannot be deleted.
761 * The task_lock() exception
763 * The need for this exception arises from the action of
764 * cgroup_attach_task(), which overwrites one task's cgroup pointer with
765 * another. It does so using cgroup_mutex, however there are
766 * several performance critical places that need to reference
767 * task->cgroup without the expense of grabbing a system global
768 * mutex. Therefore except as noted below, when dereferencing or, as
769 * in cgroup_attach_task(), modifying a task's cgroup pointer we use
770 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
771 * the task_struct routinely used for such matters.
773 * P.S. One more locking exception. RCU is used to guard the
774 * update of a tasks cgroup pointer by cgroup_attach_task()
778 * A couple of forward declarations required, due to cyclic reference loop:
779 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
780 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
784 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode);
785 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
786 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask);
787 static const struct inode_operations cgroup_dir_inode_operations;
788 static const struct file_operations proc_cgroupstats_operations;
790 static struct backing_dev_info cgroup_backing_dev_info = {
792 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
795 static struct inode *cgroup_new_inode(umode_t mode, struct super_block *sb)
797 struct inode *inode = new_inode(sb);
800 inode->i_ino = get_next_ino();
801 inode->i_mode = mode;
802 inode->i_uid = current_fsuid();
803 inode->i_gid = current_fsgid();
804 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
805 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
810 static struct cgroup_name *cgroup_alloc_name(struct dentry *dentry)
812 struct cgroup_name *name;
814 name = kmalloc(sizeof(*name) + dentry->d_name.len + 1, GFP_KERNEL);
817 strcpy(name->name, dentry->d_name.name);
821 static void cgroup_free_fn(struct work_struct *work)
823 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
825 mutex_lock(&cgroup_mutex);
826 cgrp->root->number_of_cgroups--;
827 mutex_unlock(&cgroup_mutex);
830 * We get a ref to the parent's dentry, and put the ref when
831 * this cgroup is being freed, so it's guaranteed that the
832 * parent won't be destroyed before its children.
834 dput(cgrp->parent->dentry);
837 * Drop the active superblock reference that we took when we
838 * created the cgroup. This will free cgrp->root, if we are
839 * holding the last reference to @sb.
841 deactivate_super(cgrp->root->sb);
843 cgroup_pidlist_destroy_all(cgrp);
845 simple_xattrs_free(&cgrp->xattrs);
847 kfree(rcu_dereference_raw(cgrp->name));
851 static void cgroup_free_rcu(struct rcu_head *head)
853 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
855 INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
856 queue_work(cgroup_destroy_wq, &cgrp->destroy_work);
859 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
861 /* is dentry a directory ? if so, kfree() associated cgroup */
862 if (S_ISDIR(inode->i_mode)) {
863 struct cgroup *cgrp = dentry->d_fsdata;
865 BUG_ON(!(cgroup_is_dead(cgrp)));
868 * XXX: cgrp->id is only used to look up css's. As cgroup
869 * and css's lifetimes will be decoupled, it should be made
870 * per-subsystem and moved to css->id so that lookups are
871 * successful until the target css is released.
873 idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
876 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
878 struct cfent *cfe = __d_cfe(dentry);
879 struct cgroup *cgrp = dentry->d_parent->d_fsdata;
881 WARN_ONCE(!list_empty(&cfe->node) &&
882 cgrp != &cgrp->root->top_cgroup,
883 "cfe still linked for %s\n", cfe->type->name);
884 simple_xattrs_free(&cfe->xattrs);
890 static void remove_dir(struct dentry *d)
892 struct dentry *parent = dget(d->d_parent);
895 simple_rmdir(parent->d_inode, d);
899 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
903 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
904 lockdep_assert_held(&cgroup_mutex);
907 * If we're doing cleanup due to failure of cgroup_create(),
908 * the corresponding @cfe may not exist.
910 list_for_each_entry(cfe, &cgrp->files, node) {
911 struct dentry *d = cfe->dentry;
913 if (cft && cfe->type != cft)
918 simple_unlink(cgrp->dentry->d_inode, d);
919 list_del_init(&cfe->node);
927 * cgroup_clear_dir - remove subsys files in a cgroup directory
928 * @cgrp: target cgroup
929 * @subsys_mask: mask of the subsystem ids whose files should be removed
931 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned long subsys_mask)
933 struct cgroup_subsys *ss;
936 for_each_subsys(ss, i) {
937 struct cftype_set *set;
939 if (!test_bit(i, &subsys_mask))
941 list_for_each_entry(set, &ss->cftsets, node)
942 cgroup_addrm_files(cgrp, set->cfts, false);
947 * NOTE : the dentry must have been dget()'ed
949 static void cgroup_d_remove_dir(struct dentry *dentry)
951 struct dentry *parent;
953 parent = dentry->d_parent;
954 spin_lock(&parent->d_lock);
955 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
956 list_del_init(&dentry->d_u.d_child);
957 spin_unlock(&dentry->d_lock);
958 spin_unlock(&parent->d_lock);
962 static int rebind_subsystems(struct cgroupfs_root *root,
963 unsigned long added_mask, unsigned removed_mask)
965 struct cgroup *cgrp = &root->top_cgroup;
966 struct cgroup_subsys *ss;
969 BUG_ON(!mutex_is_locked(&cgroup_mutex));
970 BUG_ON(!mutex_is_locked(&cgroup_root_mutex));
972 /* Check that any added subsystems are currently free */
973 for_each_subsys(ss, i)
974 if ((added_mask & (1 << i)) && ss->root != &cgroup_dummy_root)
977 ret = cgroup_populate_dir(cgrp, added_mask);
982 * Nothing can fail from this point on. Remove files for the
983 * removed subsystems and rebind each subsystem.
985 cgroup_clear_dir(cgrp, removed_mask);
987 for_each_subsys(ss, i) {
988 unsigned long bit = 1UL << i;
990 if (bit & added_mask) {
991 /* We're binding this subsystem to this hierarchy */
992 BUG_ON(cgroup_css(cgrp, ss));
993 BUG_ON(!cgroup_css(cgroup_dummy_top, ss));
994 BUG_ON(cgroup_css(cgroup_dummy_top, ss)->cgroup != cgroup_dummy_top);
996 rcu_assign_pointer(cgrp->subsys[i],
997 cgroup_css(cgroup_dummy_top, ss));
998 cgroup_css(cgrp, ss)->cgroup = cgrp;
1002 ss->bind(cgroup_css(cgrp, ss));
1004 /* refcount was already taken, and we're keeping it */
1005 root->subsys_mask |= bit;
1006 } else if (bit & removed_mask) {
1007 /* We're removing this subsystem */
1008 BUG_ON(cgroup_css(cgrp, ss) != cgroup_css(cgroup_dummy_top, ss));
1009 BUG_ON(cgroup_css(cgrp, ss)->cgroup != cgrp);
1012 ss->bind(cgroup_css(cgroup_dummy_top, ss));
1014 cgroup_css(cgroup_dummy_top, ss)->cgroup = cgroup_dummy_top;
1015 RCU_INIT_POINTER(cgrp->subsys[i], NULL);
1017 cgroup_subsys[i]->root = &cgroup_dummy_root;
1018 root->subsys_mask &= ~bit;
1023 * Mark @root has finished binding subsystems. @root->subsys_mask
1024 * now matches the bound subsystems.
1026 root->flags |= CGRP_ROOT_SUBSYS_BOUND;
1031 static int cgroup_show_options(struct seq_file *seq, struct dentry *dentry)
1033 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
1034 struct cgroup_subsys *ss;
1037 mutex_lock(&cgroup_root_mutex);
1038 for_each_subsys(ss, ssid)
1039 if (root->subsys_mask & (1 << ssid))
1040 seq_printf(seq, ",%s", ss->name);
1041 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1042 seq_puts(seq, ",sane_behavior");
1043 if (root->flags & CGRP_ROOT_NOPREFIX)
1044 seq_puts(seq, ",noprefix");
1045 if (root->flags & CGRP_ROOT_XATTR)
1046 seq_puts(seq, ",xattr");
1047 if (strlen(root->release_agent_path))
1048 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1049 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1050 seq_puts(seq, ",clone_children");
1051 if (strlen(root->name))
1052 seq_printf(seq, ",name=%s", root->name);
1053 mutex_unlock(&cgroup_root_mutex);
1057 struct cgroup_sb_opts {
1058 unsigned long subsys_mask;
1059 unsigned long flags;
1060 char *release_agent;
1061 bool cpuset_clone_children;
1063 /* User explicitly requested empty subsystem */
1066 struct cgroupfs_root *new_root;
1071 * Convert a hierarchy specifier into a bitmask of subsystems and
1072 * flags. Call with cgroup_mutex held to protect the cgroup_subsys[]
1073 * array. This function takes refcounts on subsystems to be used, unless it
1074 * returns error, in which case no refcounts are taken.
1076 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1078 char *token, *o = data;
1079 bool all_ss = false, one_ss = false;
1080 unsigned long mask = (unsigned long)-1;
1081 struct cgroup_subsys *ss;
1084 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1086 #ifdef CONFIG_CPUSETS
1087 mask = ~(1UL << cpuset_cgrp_id);
1090 memset(opts, 0, sizeof(*opts));
1092 while ((token = strsep(&o, ",")) != NULL) {
1095 if (!strcmp(token, "none")) {
1096 /* Explicitly have no subsystems */
1100 if (!strcmp(token, "all")) {
1101 /* Mutually exclusive option 'all' + subsystem name */
1107 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1108 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1111 if (!strcmp(token, "noprefix")) {
1112 opts->flags |= CGRP_ROOT_NOPREFIX;
1115 if (!strcmp(token, "clone_children")) {
1116 opts->cpuset_clone_children = true;
1119 if (!strcmp(token, "xattr")) {
1120 opts->flags |= CGRP_ROOT_XATTR;
1123 if (!strncmp(token, "release_agent=", 14)) {
1124 /* Specifying two release agents is forbidden */
1125 if (opts->release_agent)
1127 opts->release_agent =
1128 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1129 if (!opts->release_agent)
1133 if (!strncmp(token, "name=", 5)) {
1134 const char *name = token + 5;
1135 /* Can't specify an empty name */
1138 /* Must match [\w.-]+ */
1139 for (i = 0; i < strlen(name); i++) {
1143 if ((c == '.') || (c == '-') || (c == '_'))
1147 /* Specifying two names is forbidden */
1150 opts->name = kstrndup(name,
1151 MAX_CGROUP_ROOT_NAMELEN - 1,
1159 for_each_subsys(ss, i) {
1160 if (strcmp(token, ss->name))
1165 /* Mutually exclusive option 'all' + subsystem name */
1168 set_bit(i, &opts->subsys_mask);
1173 if (i == CGROUP_SUBSYS_COUNT)
1178 * If the 'all' option was specified select all the subsystems,
1179 * otherwise if 'none', 'name=' and a subsystem name options
1180 * were not specified, let's default to 'all'
1182 if (all_ss || (!one_ss && !opts->none && !opts->name))
1183 for_each_subsys(ss, i)
1185 set_bit(i, &opts->subsys_mask);
1187 /* Consistency checks */
1189 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1190 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1192 if (opts->flags & CGRP_ROOT_NOPREFIX) {
1193 pr_err("cgroup: sane_behavior: noprefix is not allowed\n");
1197 if (opts->cpuset_clone_children) {
1198 pr_err("cgroup: sane_behavior: clone_children is not allowed\n");
1204 * Option noprefix was introduced just for backward compatibility
1205 * with the old cpuset, so we allow noprefix only if mounting just
1206 * the cpuset subsystem.
1208 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1212 /* Can't specify "none" and some subsystems */
1213 if (opts->subsys_mask && opts->none)
1217 * We either have to specify by name or by subsystems. (So all
1218 * empty hierarchies must have a name).
1220 if (!opts->subsys_mask && !opts->name)
1226 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1229 struct cgroupfs_root *root = sb->s_fs_info;
1230 struct cgroup *cgrp = &root->top_cgroup;
1231 struct cgroup_sb_opts opts;
1232 unsigned long added_mask, removed_mask;
1234 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1235 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1239 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1240 mutex_lock(&cgroup_mutex);
1241 mutex_lock(&cgroup_root_mutex);
1243 /* See what subsystems are wanted */
1244 ret = parse_cgroupfs_options(data, &opts);
1248 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1249 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1250 task_tgid_nr(current), current->comm);
1252 added_mask = opts.subsys_mask & ~root->subsys_mask;
1253 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1255 /* Don't allow flags or name to change at remount */
1256 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1257 (opts.name && strcmp(opts.name, root->name))) {
1258 pr_err("cgroup: option or name mismatch, new: 0x%lx \"%s\", old: 0x%lx \"%s\"\n",
1259 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1260 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1265 /* remounting is not allowed for populated hierarchies */
1266 if (root->number_of_cgroups > 1) {
1271 ret = rebind_subsystems(root, added_mask, removed_mask);
1275 if (opts.release_agent)
1276 strcpy(root->release_agent_path, opts.release_agent);
1278 kfree(opts.release_agent);
1280 mutex_unlock(&cgroup_root_mutex);
1281 mutex_unlock(&cgroup_mutex);
1282 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1286 static const struct super_operations cgroup_ops = {
1287 .statfs = simple_statfs,
1288 .drop_inode = generic_delete_inode,
1289 .show_options = cgroup_show_options,
1290 .remount_fs = cgroup_remount,
1293 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1295 INIT_LIST_HEAD(&cgrp->sibling);
1296 INIT_LIST_HEAD(&cgrp->children);
1297 INIT_LIST_HEAD(&cgrp->files);
1298 INIT_LIST_HEAD(&cgrp->cset_links);
1299 INIT_LIST_HEAD(&cgrp->release_list);
1300 INIT_LIST_HEAD(&cgrp->pidlists);
1301 mutex_init(&cgrp->pidlist_mutex);
1302 cgrp->dummy_css.cgroup = cgrp;
1303 simple_xattrs_init(&cgrp->xattrs);
1306 static void init_cgroup_root(struct cgroupfs_root *root)
1308 struct cgroup *cgrp = &root->top_cgroup;
1310 INIT_LIST_HEAD(&root->root_list);
1311 root->number_of_cgroups = 1;
1313 RCU_INIT_POINTER(cgrp->name, &root_cgroup_name);
1314 init_cgroup_housekeeping(cgrp);
1315 idr_init(&root->cgroup_idr);
1318 static int cgroup_init_root_id(struct cgroupfs_root *root, int start, int end)
1322 lockdep_assert_held(&cgroup_mutex);
1323 lockdep_assert_held(&cgroup_root_mutex);
1325 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, start, end,
1330 root->hierarchy_id = id;
1334 static void cgroup_exit_root_id(struct cgroupfs_root *root)
1336 lockdep_assert_held(&cgroup_mutex);
1337 lockdep_assert_held(&cgroup_root_mutex);
1339 if (root->hierarchy_id) {
1340 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1341 root->hierarchy_id = 0;
1345 static int cgroup_test_super(struct super_block *sb, void *data)
1347 struct cgroup_sb_opts *opts = data;
1348 struct cgroupfs_root *root = sb->s_fs_info;
1350 /* If we asked for a name then it must match */
1351 if (opts->name && strcmp(opts->name, root->name))
1355 * If we asked for subsystems (or explicitly for no
1356 * subsystems) then they must match
1358 if ((opts->subsys_mask || opts->none)
1359 && (opts->subsys_mask != root->subsys_mask))
1365 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1367 struct cgroupfs_root *root;
1369 if (!opts->subsys_mask && !opts->none)
1372 root = kzalloc(sizeof(*root), GFP_KERNEL);
1374 return ERR_PTR(-ENOMEM);
1376 init_cgroup_root(root);
1379 * We need to set @root->subsys_mask now so that @root can be
1380 * matched by cgroup_test_super() before it finishes
1381 * initialization; otherwise, competing mounts with the same
1382 * options may try to bind the same subsystems instead of waiting
1383 * for the first one leading to unexpected mount errors.
1384 * SUBSYS_BOUND will be set once actual binding is complete.
1386 root->subsys_mask = opts->subsys_mask;
1387 root->flags = opts->flags;
1388 if (opts->release_agent)
1389 strcpy(root->release_agent_path, opts->release_agent);
1391 strcpy(root->name, opts->name);
1392 if (opts->cpuset_clone_children)
1393 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1397 static void cgroup_free_root(struct cgroupfs_root *root)
1400 /* hierarhcy ID shoulid already have been released */
1401 WARN_ON_ONCE(root->hierarchy_id);
1403 idr_destroy(&root->cgroup_idr);
1408 static int cgroup_set_super(struct super_block *sb, void *data)
1411 struct cgroup_sb_opts *opts = data;
1413 /* If we don't have a new root, we can't set up a new sb */
1414 if (!opts->new_root)
1417 BUG_ON(!opts->subsys_mask && !opts->none);
1419 ret = set_anon_super(sb, NULL);
1423 sb->s_fs_info = opts->new_root;
1424 opts->new_root->sb = sb;
1426 sb->s_blocksize = PAGE_CACHE_SIZE;
1427 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1428 sb->s_magic = CGROUP_SUPER_MAGIC;
1429 sb->s_op = &cgroup_ops;
1434 static int cgroup_get_rootdir(struct super_block *sb)
1436 static const struct dentry_operations cgroup_dops = {
1437 .d_iput = cgroup_diput,
1438 .d_delete = always_delete_dentry,
1441 struct inode *inode =
1442 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1447 inode->i_fop = &simple_dir_operations;
1448 inode->i_op = &cgroup_dir_inode_operations;
1449 /* directories start off with i_nlink == 2 (for "." entry) */
1451 sb->s_root = d_make_root(inode);
1454 /* for everything else we want ->d_op set */
1455 sb->s_d_op = &cgroup_dops;
1459 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1460 int flags, const char *unused_dev_name,
1463 struct cgroup_sb_opts opts;
1464 struct cgroupfs_root *root;
1466 struct super_block *sb;
1467 struct cgroupfs_root *new_root;
1468 struct list_head tmp_links;
1469 struct inode *inode;
1470 const struct cred *cred;
1472 /* First find the desired set of subsystems */
1473 mutex_lock(&cgroup_mutex);
1474 ret = parse_cgroupfs_options(data, &opts);
1475 mutex_unlock(&cgroup_mutex);
1480 * Allocate a new cgroup root. We may not need it if we're
1481 * reusing an existing hierarchy.
1483 new_root = cgroup_root_from_opts(&opts);
1484 if (IS_ERR(new_root)) {
1485 ret = PTR_ERR(new_root);
1488 opts.new_root = new_root;
1490 /* Locate an existing or new sb for this hierarchy */
1491 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1494 cgroup_free_root(opts.new_root);
1498 root = sb->s_fs_info;
1500 if (root == opts.new_root) {
1501 /* We used the new root structure, so this is a new hierarchy */
1502 struct cgroup *root_cgrp = &root->top_cgroup;
1503 struct cgroupfs_root *existing_root;
1505 struct css_set *cset;
1507 BUG_ON(sb->s_root != NULL);
1509 ret = cgroup_get_rootdir(sb);
1511 goto drop_new_super;
1512 inode = sb->s_root->d_inode;
1514 mutex_lock(&inode->i_mutex);
1515 mutex_lock(&cgroup_mutex);
1516 mutex_lock(&cgroup_root_mutex);
1518 root_cgrp->id = idr_alloc(&root->cgroup_idr, root_cgrp,
1520 if (root_cgrp->id < 0)
1523 /* Check for name clashes with existing mounts */
1525 if (strlen(root->name))
1526 for_each_active_root(existing_root)
1527 if (!strcmp(existing_root->name, root->name))
1531 * We're accessing css_set_count without locking
1532 * css_set_lock here, but that's OK - it can only be
1533 * increased by someone holding cgroup_lock, and
1534 * that's us. The worst that can happen is that we
1535 * have some link structures left over
1537 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1541 /* ID 0 is reserved for dummy root, 1 for unified hierarchy */
1542 ret = cgroup_init_root_id(root, 2, 0);
1546 sb->s_root->d_fsdata = root_cgrp;
1547 root_cgrp->dentry = sb->s_root;
1550 * We're inside get_sb() and will call lookup_one_len() to
1551 * create the root files, which doesn't work if SELinux is
1552 * in use. The following cred dancing somehow works around
1553 * it. See 2ce9738ba ("cgroupfs: use init_cred when
1554 * populating new cgroupfs mount") for more details.
1556 cred = override_creds(&init_cred);
1558 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1562 ret = rebind_subsystems(root, root->subsys_mask, 0);
1569 * There must be no failure case after here, since rebinding
1570 * takes care of subsystems' refcounts, which are explicitly
1571 * dropped in the failure exit path.
1574 list_add(&root->root_list, &cgroup_roots);
1575 cgroup_root_count++;
1577 /* Link the top cgroup in this hierarchy into all
1578 * the css_set objects */
1579 write_lock(&css_set_lock);
1580 hash_for_each(css_set_table, i, cset, hlist)
1581 link_css_set(&tmp_links, cset, root_cgrp);
1582 write_unlock(&css_set_lock);
1584 free_cgrp_cset_links(&tmp_links);
1586 BUG_ON(!list_empty(&root_cgrp->children));
1587 BUG_ON(root->number_of_cgroups != 1);
1589 mutex_unlock(&cgroup_root_mutex);
1590 mutex_unlock(&cgroup_mutex);
1591 mutex_unlock(&inode->i_mutex);
1594 * We re-used an existing hierarchy - the new root (if
1595 * any) is not needed
1597 cgroup_free_root(opts.new_root);
1599 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1600 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1601 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1603 goto drop_new_super;
1605 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1610 kfree(opts.release_agent);
1612 return dget(sb->s_root);
1615 free_cgrp_cset_links(&tmp_links);
1616 cgroup_addrm_files(&root->top_cgroup, cgroup_base_files, false);
1619 cgroup_exit_root_id(root);
1620 mutex_unlock(&cgroup_root_mutex);
1621 mutex_unlock(&cgroup_mutex);
1622 mutex_unlock(&inode->i_mutex);
1624 deactivate_locked_super(sb);
1626 kfree(opts.release_agent);
1628 return ERR_PTR(ret);
1631 static void cgroup_kill_sb(struct super_block *sb)
1633 struct cgroupfs_root *root = sb->s_fs_info;
1634 struct cgroup *cgrp = &root->top_cgroup;
1635 struct cgrp_cset_link *link, *tmp_link;
1640 BUG_ON(root->number_of_cgroups != 1);
1641 BUG_ON(!list_empty(&cgrp->children));
1643 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1644 mutex_lock(&cgroup_mutex);
1645 mutex_lock(&cgroup_root_mutex);
1647 /* Rebind all subsystems back to the default hierarchy */
1648 if (root->flags & CGRP_ROOT_SUBSYS_BOUND) {
1649 ret = rebind_subsystems(root, 0, root->subsys_mask);
1650 /* Shouldn't be able to fail ... */
1655 * Release all the links from cset_links to this hierarchy's
1658 write_lock(&css_set_lock);
1660 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1661 list_del(&link->cset_link);
1662 list_del(&link->cgrp_link);
1665 write_unlock(&css_set_lock);
1667 if (!list_empty(&root->root_list)) {
1668 list_del(&root->root_list);
1669 cgroup_root_count--;
1672 cgroup_exit_root_id(root);
1674 mutex_unlock(&cgroup_root_mutex);
1675 mutex_unlock(&cgroup_mutex);
1676 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1678 simple_xattrs_free(&cgrp->xattrs);
1680 kill_litter_super(sb);
1681 cgroup_free_root(root);
1684 static struct file_system_type cgroup_fs_type = {
1686 .mount = cgroup_mount,
1687 .kill_sb = cgroup_kill_sb,
1690 static struct kobject *cgroup_kobj;
1693 * cgroup_path - generate the path of a cgroup
1694 * @cgrp: the cgroup in question
1695 * @buf: the buffer to write the path into
1696 * @buflen: the length of the buffer
1698 * Writes path of cgroup into buf. Returns 0 on success, -errno on error.
1700 * We can't generate cgroup path using dentry->d_name, as accessing
1701 * dentry->name must be protected by irq-unsafe dentry->d_lock or parent
1702 * inode's i_mutex, while on the other hand cgroup_path() can be called
1703 * with some irq-safe spinlocks held.
1705 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1707 int ret = -ENAMETOOLONG;
1710 if (!cgrp->parent) {
1711 if (strlcpy(buf, "/", buflen) >= buflen)
1712 return -ENAMETOOLONG;
1716 start = buf + buflen - 1;
1721 const char *name = cgroup_name(cgrp);
1725 if ((start -= len) < buf)
1727 memcpy(start, name, len);
1733 cgrp = cgrp->parent;
1734 } while (cgrp->parent);
1736 memmove(buf, start, buf + buflen - start);
1741 EXPORT_SYMBOL_GPL(cgroup_path);
1744 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1745 * @task: target task
1746 * @buf: the buffer to write the path into
1747 * @buflen: the length of the buffer
1749 * Determine @task's cgroup on the first (the one with the lowest non-zero
1750 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1751 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1752 * cgroup controller callbacks.
1754 * Returns 0 on success, fails with -%ENAMETOOLONG if @buflen is too short.
1756 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1758 struct cgroupfs_root *root;
1759 struct cgroup *cgrp;
1760 int hierarchy_id = 1, ret = 0;
1763 return -ENAMETOOLONG;
1765 mutex_lock(&cgroup_mutex);
1767 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1770 cgrp = task_cgroup_from_root(task, root);
1771 ret = cgroup_path(cgrp, buf, buflen);
1773 /* if no hierarchy exists, everyone is in "/" */
1774 memcpy(buf, "/", 2);
1777 mutex_unlock(&cgroup_mutex);
1780 EXPORT_SYMBOL_GPL(task_cgroup_path);
1783 * Control Group taskset
1785 struct task_and_cgroup {
1786 struct task_struct *task;
1787 struct cgroup *cgrp;
1788 struct css_set *cset;
1791 struct cgroup_taskset {
1792 struct task_and_cgroup single;
1793 struct flex_array *tc_array;
1796 struct cgroup *cur_cgrp;
1800 * cgroup_taskset_first - reset taskset and return the first task
1801 * @tset: taskset of interest
1803 * @tset iteration is initialized and the first task is returned.
1805 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1807 if (tset->tc_array) {
1809 return cgroup_taskset_next(tset);
1811 tset->cur_cgrp = tset->single.cgrp;
1812 return tset->single.task;
1815 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1818 * cgroup_taskset_next - iterate to the next task in taskset
1819 * @tset: taskset of interest
1821 * Return the next task in @tset. Iteration must have been initialized
1822 * with cgroup_taskset_first().
1824 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1826 struct task_and_cgroup *tc;
1828 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1831 tc = flex_array_get(tset->tc_array, tset->idx++);
1832 tset->cur_cgrp = tc->cgrp;
1835 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1838 * cgroup_taskset_cur_css - return the matching css for the current task
1839 * @tset: taskset of interest
1840 * @subsys_id: the ID of the target subsystem
1842 * Return the css for the current (last returned) task of @tset for
1843 * subsystem specified by @subsys_id. This function must be preceded by
1844 * either cgroup_taskset_first() or cgroup_taskset_next().
1846 struct cgroup_subsys_state *cgroup_taskset_cur_css(struct cgroup_taskset *tset,
1849 return cgroup_css(tset->cur_cgrp, cgroup_subsys[subsys_id]);
1851 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_css);
1854 * cgroup_taskset_size - return the number of tasks in taskset
1855 * @tset: taskset of interest
1857 int cgroup_taskset_size(struct cgroup_taskset *tset)
1859 return tset->tc_array ? tset->tc_array_len : 1;
1861 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1865 * cgroup_task_migrate - move a task from one cgroup to another.
1867 * Must be called with cgroup_mutex and threadgroup locked.
1869 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1870 struct task_struct *tsk,
1871 struct css_set *new_cset)
1873 struct css_set *old_cset;
1876 * We are synchronized through threadgroup_lock() against PF_EXITING
1877 * setting such that we can't race against cgroup_exit() changing the
1878 * css_set to init_css_set and dropping the old one.
1880 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1881 old_cset = task_css_set(tsk);
1884 rcu_assign_pointer(tsk->cgroups, new_cset);
1887 /* Update the css_set linked lists if we're using them */
1888 write_lock(&css_set_lock);
1889 if (!list_empty(&tsk->cg_list))
1890 list_move(&tsk->cg_list, &new_cset->tasks);
1891 write_unlock(&css_set_lock);
1894 * We just gained a reference on old_cset by taking it from the
1895 * task. As trading it for new_cset is protected by cgroup_mutex,
1896 * we're safe to drop it here; it will be freed under RCU.
1898 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1899 put_css_set(old_cset);
1903 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1904 * @cgrp: the cgroup to attach to
1905 * @tsk: the task or the leader of the threadgroup to be attached
1906 * @threadgroup: attach the whole threadgroup?
1908 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
1909 * task_lock of @tsk or each thread in the threadgroup individually in turn.
1911 static int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk,
1914 int retval, i, group_size;
1915 struct cgroupfs_root *root = cgrp->root;
1916 struct cgroup_subsys_state *css, *failed_css = NULL;
1917 /* threadgroup list cursor and array */
1918 struct task_struct *leader = tsk;
1919 struct task_and_cgroup *tc;
1920 struct flex_array *group;
1921 struct cgroup_taskset tset = { };
1924 * step 0: in order to do expensive, possibly blocking operations for
1925 * every thread, we cannot iterate the thread group list, since it needs
1926 * rcu or tasklist locked. instead, build an array of all threads in the
1927 * group - group_rwsem prevents new threads from appearing, and if
1928 * threads exit, this will just be an over-estimate.
1931 group_size = get_nr_threads(tsk);
1934 /* flex_array supports very large thread-groups better than kmalloc. */
1935 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
1938 /* pre-allocate to guarantee space while iterating in rcu read-side. */
1939 retval = flex_array_prealloc(group, 0, group_size, GFP_KERNEL);
1941 goto out_free_group_list;
1945 * Prevent freeing of tasks while we take a snapshot. Tasks that are
1946 * already PF_EXITING could be freed from underneath us unless we
1947 * take an rcu_read_lock.
1951 struct task_and_cgroup ent;
1953 /* @tsk either already exited or can't exit until the end */
1954 if (tsk->flags & PF_EXITING)
1957 /* as per above, nr_threads may decrease, but not increase. */
1958 BUG_ON(i >= group_size);
1960 ent.cgrp = task_cgroup_from_root(tsk, root);
1961 /* nothing to do if this task is already in the cgroup */
1962 if (ent.cgrp == cgrp)
1965 * saying GFP_ATOMIC has no effect here because we did prealloc
1966 * earlier, but it's good form to communicate our expectations.
1968 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
1969 BUG_ON(retval != 0);
1974 } while_each_thread(leader, tsk);
1976 /* remember the number of threads in the array for later. */
1978 tset.tc_array = group;
1979 tset.tc_array_len = group_size;
1981 /* methods shouldn't be called if no task is actually migrating */
1984 goto out_free_group_list;
1987 * step 1: check that we can legitimately attach to the cgroup.
1989 for_each_css(css, i, cgrp) {
1990 if (css->ss->can_attach) {
1991 retval = css->ss->can_attach(css, &tset);
1994 goto out_cancel_attach;
2000 * step 2: make sure css_sets exist for all threads to be migrated.
2001 * we use find_css_set, which allocates a new one if necessary.
2003 for (i = 0; i < group_size; i++) {
2004 struct css_set *old_cset;
2006 tc = flex_array_get(group, i);
2007 old_cset = task_css_set(tc->task);
2008 tc->cset = find_css_set(old_cset, cgrp);
2011 goto out_put_css_set_refs;
2016 * step 3: now that we're guaranteed success wrt the css_sets,
2017 * proceed to move all tasks to the new cgroup. There are no
2018 * failure cases after here, so this is the commit point.
2020 for (i = 0; i < group_size; i++) {
2021 tc = flex_array_get(group, i);
2022 cgroup_task_migrate(tc->cgrp, tc->task, tc->cset);
2024 /* nothing is sensitive to fork() after this point. */
2027 * step 4: do subsystem attach callbacks.
2029 for_each_css(css, i, cgrp)
2030 if (css->ss->attach)
2031 css->ss->attach(css, &tset);
2034 * step 5: success! and cleanup
2037 out_put_css_set_refs:
2039 for (i = 0; i < group_size; i++) {
2040 tc = flex_array_get(group, i);
2043 put_css_set(tc->cset);
2048 for_each_css(css, i, cgrp) {
2049 if (css == failed_css)
2051 if (css->ss->cancel_attach)
2052 css->ss->cancel_attach(css, &tset);
2055 out_free_group_list:
2056 flex_array_free(group);
2061 * Find the task_struct of the task to attach by vpid and pass it along to the
2062 * function to attach either it or all tasks in its threadgroup. Will lock
2063 * cgroup_mutex and threadgroup; may take task_lock of task.
2065 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2067 struct task_struct *tsk;
2068 const struct cred *cred = current_cred(), *tcred;
2071 if (!cgroup_lock_live_group(cgrp))
2077 tsk = find_task_by_vpid(pid);
2081 goto out_unlock_cgroup;
2084 * even if we're attaching all tasks in the thread group, we
2085 * only need to check permissions on one of them.
2087 tcred = __task_cred(tsk);
2088 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2089 !uid_eq(cred->euid, tcred->uid) &&
2090 !uid_eq(cred->euid, tcred->suid)) {
2093 goto out_unlock_cgroup;
2099 tsk = tsk->group_leader;
2102 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2103 * trapped in a cpuset, or RT worker may be born in a cgroup
2104 * with no rt_runtime allocated. Just say no.
2106 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2109 goto out_unlock_cgroup;
2112 get_task_struct(tsk);
2115 threadgroup_lock(tsk);
2117 if (!thread_group_leader(tsk)) {
2119 * a race with de_thread from another thread's exec()
2120 * may strip us of our leadership, if this happens,
2121 * there is no choice but to throw this task away and
2122 * try again; this is
2123 * "double-double-toil-and-trouble-check locking".
2125 threadgroup_unlock(tsk);
2126 put_task_struct(tsk);
2127 goto retry_find_task;
2131 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2133 threadgroup_unlock(tsk);
2135 put_task_struct(tsk);
2137 mutex_unlock(&cgroup_mutex);
2142 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2143 * @from: attach to all cgroups of a given task
2144 * @tsk: the task to be attached
2146 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2148 struct cgroupfs_root *root;
2151 mutex_lock(&cgroup_mutex);
2152 for_each_active_root(root) {
2153 struct cgroup *from_cgrp = task_cgroup_from_root(from, root);
2155 retval = cgroup_attach_task(from_cgrp, tsk, false);
2159 mutex_unlock(&cgroup_mutex);
2163 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2165 static int cgroup_tasks_write(struct cgroup_subsys_state *css,
2166 struct cftype *cft, u64 pid)
2168 return attach_task_by_pid(css->cgroup, pid, false);
2171 static int cgroup_procs_write(struct cgroup_subsys_state *css,
2172 struct cftype *cft, u64 tgid)
2174 return attach_task_by_pid(css->cgroup, tgid, true);
2177 static int cgroup_release_agent_write(struct cgroup_subsys_state *css,
2178 struct cftype *cft, const char *buffer)
2180 BUILD_BUG_ON(sizeof(css->cgroup->root->release_agent_path) < PATH_MAX);
2181 if (strlen(buffer) >= PATH_MAX)
2183 if (!cgroup_lock_live_group(css->cgroup))
2185 mutex_lock(&cgroup_root_mutex);
2186 strcpy(css->cgroup->root->release_agent_path, buffer);
2187 mutex_unlock(&cgroup_root_mutex);
2188 mutex_unlock(&cgroup_mutex);
2192 static int cgroup_release_agent_show(struct seq_file *seq, void *v)
2194 struct cgroup *cgrp = seq_css(seq)->cgroup;
2196 if (!cgroup_lock_live_group(cgrp))
2198 seq_puts(seq, cgrp->root->release_agent_path);
2199 seq_putc(seq, '\n');
2200 mutex_unlock(&cgroup_mutex);
2204 static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
2206 struct cgroup *cgrp = seq_css(seq)->cgroup;
2208 seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
2212 /* A buffer size big enough for numbers or short strings */
2213 #define CGROUP_LOCAL_BUFFER_SIZE 64
2215 static ssize_t cgroup_file_write(struct file *file, const char __user *userbuf,
2216 size_t nbytes, loff_t *ppos)
2218 struct cfent *cfe = __d_cfe(file->f_dentry);
2219 struct cftype *cft = __d_cft(file->f_dentry);
2220 struct cgroup_subsys_state *css = cfe->css;
2221 size_t max_bytes = cft->max_write_len ?: CGROUP_LOCAL_BUFFER_SIZE - 1;
2225 if (nbytes >= max_bytes)
2228 buf = kmalloc(nbytes + 1, GFP_KERNEL);
2232 if (copy_from_user(buf, userbuf, nbytes)) {
2239 if (cft->write_string) {
2240 ret = cft->write_string(css, cft, strstrip(buf));
2241 } else if (cft->write_u64) {
2242 unsigned long long v;
2243 ret = kstrtoull(buf, 0, &v);
2245 ret = cft->write_u64(css, cft, v);
2246 } else if (cft->write_s64) {
2248 ret = kstrtoll(buf, 0, &v);
2250 ret = cft->write_s64(css, cft, v);
2251 } else if (cft->trigger) {
2252 ret = cft->trigger(css, (unsigned int)cft->private);
2258 return ret ?: nbytes;
2262 * seqfile ops/methods for returning structured data. Currently just
2263 * supports string->u64 maps, but can be extended in future.
2266 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
2268 struct cftype *cft = seq_cft(seq);
2270 if (cft->seq_start) {
2271 return cft->seq_start(seq, ppos);
2274 * The same behavior and code as single_open(). Returns
2275 * !NULL if pos is at the beginning; otherwise, NULL.
2277 return NULL + !*ppos;
2281 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
2283 struct cftype *cft = seq_cft(seq);
2285 if (cft->seq_next) {
2286 return cft->seq_next(seq, v, ppos);
2289 * The same behavior and code as single_open(), always
2290 * terminate after the initial read.
2297 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
2299 struct cftype *cft = seq_cft(seq);
2302 cft->seq_stop(seq, v);
2305 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2307 struct cftype *cft = seq_cft(m);
2308 struct cgroup_subsys_state *css = seq_css(m);
2311 return cft->seq_show(m, arg);
2314 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
2315 else if (cft->read_s64)
2316 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
2322 static struct seq_operations cgroup_seq_operations = {
2323 .start = cgroup_seqfile_start,
2324 .next = cgroup_seqfile_next,
2325 .stop = cgroup_seqfile_stop,
2326 .show = cgroup_seqfile_show,
2329 static int cgroup_file_open(struct inode *inode, struct file *file)
2331 struct cfent *cfe = __d_cfe(file->f_dentry);
2332 struct cftype *cft = __d_cft(file->f_dentry);
2333 struct cgroup *cgrp = __d_cgrp(cfe->dentry->d_parent);
2334 struct cgroup_subsys_state *css;
2335 struct cgroup_open_file *of;
2338 err = generic_file_open(inode, file);
2343 * If the file belongs to a subsystem, pin the css. Will be
2344 * unpinned either on open failure or release. This ensures that
2345 * @css stays alive for all file operations.
2348 css = cgroup_css(cgrp, cft->ss);
2349 if (cft->ss && !css_tryget(css))
2357 * @cfe->css is used by read/write/close to determine the
2358 * associated css. @file->private_data would be a better place but
2359 * that's already used by seqfile. Multiple accessors may use it
2360 * simultaneously which is okay as the association never changes.
2362 WARN_ON_ONCE(cfe->css && cfe->css != css);
2365 of = __seq_open_private(file, &cgroup_seq_operations,
2366 sizeof(struct cgroup_open_file));
2377 static int cgroup_file_release(struct inode *inode, struct file *file)
2379 struct cfent *cfe = __d_cfe(file->f_dentry);
2380 struct cgroup_subsys_state *css = cfe->css;
2384 return seq_release_private(inode, file);
2388 * cgroup_rename - Only allow simple rename of directories in place.
2390 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2391 struct inode *new_dir, struct dentry *new_dentry)
2394 struct cgroup_name *name, *old_name;
2395 struct cgroup *cgrp;
2398 * It's convinient to use parent dir's i_mutex to protected
2401 lockdep_assert_held(&old_dir->i_mutex);
2403 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2405 if (new_dentry->d_inode)
2407 if (old_dir != new_dir)
2410 cgrp = __d_cgrp(old_dentry);
2413 * This isn't a proper migration and its usefulness is very
2414 * limited. Disallow if sane_behavior.
2416 if (cgroup_sane_behavior(cgrp))
2419 name = cgroup_alloc_name(new_dentry);
2423 ret = simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2429 old_name = rcu_dereference_protected(cgrp->name, true);
2430 rcu_assign_pointer(cgrp->name, name);
2432 kfree_rcu(old_name, rcu_head);
2436 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2438 if (S_ISDIR(dentry->d_inode->i_mode))
2439 return &__d_cgrp(dentry)->xattrs;
2441 return &__d_cfe(dentry)->xattrs;
2444 static inline int xattr_enabled(struct dentry *dentry)
2446 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2447 return root->flags & CGRP_ROOT_XATTR;
2450 static bool is_valid_xattr(const char *name)
2452 if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2453 !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2458 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2459 const void *val, size_t size, int flags)
2461 if (!xattr_enabled(dentry))
2463 if (!is_valid_xattr(name))
2465 return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2468 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2470 if (!xattr_enabled(dentry))
2472 if (!is_valid_xattr(name))
2474 return simple_xattr_remove(__d_xattrs(dentry), name);
2477 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2478 void *buf, size_t size)
2480 if (!xattr_enabled(dentry))
2482 if (!is_valid_xattr(name))
2484 return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2487 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2489 if (!xattr_enabled(dentry))
2491 return simple_xattr_list(__d_xattrs(dentry), buf, size);
2494 static const struct file_operations cgroup_file_operations = {
2496 .write = cgroup_file_write,
2497 .llseek = generic_file_llseek,
2498 .open = cgroup_file_open,
2499 .release = cgroup_file_release,
2502 static const struct inode_operations cgroup_file_inode_operations = {
2503 .setxattr = cgroup_setxattr,
2504 .getxattr = cgroup_getxattr,
2505 .listxattr = cgroup_listxattr,
2506 .removexattr = cgroup_removexattr,
2509 static const struct inode_operations cgroup_dir_inode_operations = {
2510 .lookup = simple_lookup,
2511 .mkdir = cgroup_mkdir,
2512 .rmdir = cgroup_rmdir,
2513 .rename = cgroup_rename,
2514 .setxattr = cgroup_setxattr,
2515 .getxattr = cgroup_getxattr,
2516 .listxattr = cgroup_listxattr,
2517 .removexattr = cgroup_removexattr,
2520 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2521 struct super_block *sb)
2523 struct inode *inode;
2527 if (dentry->d_inode)
2530 inode = cgroup_new_inode(mode, sb);
2534 if (S_ISDIR(mode)) {
2535 inode->i_op = &cgroup_dir_inode_operations;
2536 inode->i_fop = &simple_dir_operations;
2538 /* start off with i_nlink == 2 (for "." entry) */
2540 inc_nlink(dentry->d_parent->d_inode);
2543 * Control reaches here with cgroup_mutex held.
2544 * @inode->i_mutex should nest outside cgroup_mutex but we
2545 * want to populate it immediately without releasing
2546 * cgroup_mutex. As @inode isn't visible to anyone else
2547 * yet, trylock will always succeed without affecting
2550 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2551 } else if (S_ISREG(mode)) {
2553 inode->i_fop = &cgroup_file_operations;
2554 inode->i_op = &cgroup_file_inode_operations;
2556 d_instantiate(dentry, inode);
2557 dget(dentry); /* Extra count - pin the dentry in core */
2562 * cgroup_file_mode - deduce file mode of a control file
2563 * @cft: the control file in question
2565 * returns cft->mode if ->mode is not 0
2566 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2567 * returns S_IRUGO if it has only a read handler
2568 * returns S_IWUSR if it has only a write hander
2570 static umode_t cgroup_file_mode(const struct cftype *cft)
2577 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
2580 if (cft->write_u64 || cft->write_s64 || cft->write_string ||
2587 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2589 struct dentry *dir = cgrp->dentry;
2590 struct cgroup *parent = __d_cgrp(dir);
2591 struct dentry *dentry;
2595 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2597 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
2598 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
2599 strcpy(name, cft->ss->name);
2602 strcat(name, cft->name);
2604 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2606 cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2610 dentry = lookup_one_len(name, dir, strlen(name));
2611 if (IS_ERR(dentry)) {
2612 error = PTR_ERR(dentry);
2616 cfe->type = (void *)cft;
2617 cfe->dentry = dentry;
2618 dentry->d_fsdata = cfe;
2619 simple_xattrs_init(&cfe->xattrs);
2621 mode = cgroup_file_mode(cft);
2622 error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2624 list_add_tail(&cfe->node, &parent->files);
2634 * cgroup_addrm_files - add or remove files to a cgroup directory
2635 * @cgrp: the target cgroup
2636 * @cfts: array of cftypes to be added
2637 * @is_add: whether to add or remove
2639 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2640 * For removals, this function never fails. If addition fails, this
2641 * function doesn't remove files already added. The caller is responsible
2644 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2650 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
2651 lockdep_assert_held(&cgroup_mutex);
2653 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2654 /* does cft->flags tell us to skip this file on @cgrp? */
2655 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2657 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2659 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2663 ret = cgroup_add_file(cgrp, cft);
2665 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2670 cgroup_rm_file(cgrp, cft);
2676 static void cgroup_cfts_prepare(void)
2677 __acquires(&cgroup_mutex)
2680 * Thanks to the entanglement with vfs inode locking, we can't walk
2681 * the existing cgroups under cgroup_mutex and create files.
2682 * Instead, we use css_for_each_descendant_pre() and drop RCU read
2683 * lock before calling cgroup_addrm_files().
2685 mutex_lock(&cgroup_mutex);
2688 static int cgroup_cfts_commit(struct cftype *cfts, bool is_add)
2689 __releases(&cgroup_mutex)
2692 struct cgroup_subsys *ss = cfts[0].ss;
2693 struct cgroup *root = &ss->root->top_cgroup;
2694 struct super_block *sb = ss->root->sb;
2695 struct dentry *prev = NULL;
2696 struct inode *inode;
2697 struct cgroup_subsys_state *css;
2701 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2702 if (!cfts || ss->root == &cgroup_dummy_root ||
2703 !atomic_inc_not_zero(&sb->s_active)) {
2704 mutex_unlock(&cgroup_mutex);
2709 * All cgroups which are created after we drop cgroup_mutex will
2710 * have the updated set of files, so we only need to update the
2711 * cgroups created before the current @cgroup_serial_nr_next.
2713 update_before = cgroup_serial_nr_next;
2715 mutex_unlock(&cgroup_mutex);
2717 /* add/rm files for all cgroups created before */
2719 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2720 struct cgroup *cgrp = css->cgroup;
2722 if (cgroup_is_dead(cgrp))
2725 inode = cgrp->dentry->d_inode;
2730 prev = cgrp->dentry;
2732 mutex_lock(&inode->i_mutex);
2733 mutex_lock(&cgroup_mutex);
2734 if (cgrp->serial_nr < update_before && !cgroup_is_dead(cgrp))
2735 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2736 mutex_unlock(&cgroup_mutex);
2737 mutex_unlock(&inode->i_mutex);
2745 deactivate_super(sb);
2750 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2751 * @ss: target cgroup subsystem
2752 * @cfts: zero-length name terminated array of cftypes
2754 * Register @cfts to @ss. Files described by @cfts are created for all
2755 * existing cgroups to which @ss is attached and all future cgroups will
2756 * have them too. This function can be called anytime whether @ss is
2759 * Returns 0 on successful registration, -errno on failure. Note that this
2760 * function currently returns 0 as long as @cfts registration is successful
2761 * even if some file creation attempts on existing cgroups fail.
2763 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2765 struct cftype_set *set;
2769 set = kzalloc(sizeof(*set), GFP_KERNEL);
2773 for (cft = cfts; cft->name[0] != '\0'; cft++)
2776 cgroup_cfts_prepare();
2778 list_add_tail(&set->node, &ss->cftsets);
2779 ret = cgroup_cfts_commit(cfts, true);
2781 cgroup_rm_cftypes(cfts);
2784 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2787 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2788 * @cfts: zero-length name terminated array of cftypes
2790 * Unregister @cfts. Files described by @cfts are removed from all
2791 * existing cgroups and all future cgroups won't have them either. This
2792 * function can be called anytime whether @cfts' subsys is attached or not.
2794 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2797 int cgroup_rm_cftypes(struct cftype *cfts)
2799 struct cftype_set *set;
2801 if (!cfts || !cfts[0].ss)
2804 cgroup_cfts_prepare();
2806 list_for_each_entry(set, &cfts[0].ss->cftsets, node) {
2807 if (set->cfts == cfts) {
2808 list_del(&set->node);
2810 cgroup_cfts_commit(cfts, false);
2815 cgroup_cfts_commit(NULL, false);
2820 * cgroup_task_count - count the number of tasks in a cgroup.
2821 * @cgrp: the cgroup in question
2823 * Return the number of tasks in the cgroup.
2825 int cgroup_task_count(const struct cgroup *cgrp)
2828 struct cgrp_cset_link *link;
2830 read_lock(&css_set_lock);
2831 list_for_each_entry(link, &cgrp->cset_links, cset_link)
2832 count += atomic_read(&link->cset->refcount);
2833 read_unlock(&css_set_lock);
2838 * To reduce the fork() overhead for systems that are not actually using
2839 * their cgroups capability, we don't maintain the lists running through
2840 * each css_set to its tasks until we see the list actually used - in other
2841 * words after the first call to css_task_iter_start().
2843 static void cgroup_enable_task_cg_lists(void)
2845 struct task_struct *p, *g;
2846 write_lock(&css_set_lock);
2847 use_task_css_set_links = 1;
2849 * We need tasklist_lock because RCU is not safe against
2850 * while_each_thread(). Besides, a forking task that has passed
2851 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2852 * is not guaranteed to have its child immediately visible in the
2853 * tasklist if we walk through it with RCU.
2855 read_lock(&tasklist_lock);
2856 do_each_thread(g, p) {
2859 * We should check if the process is exiting, otherwise
2860 * it will race with cgroup_exit() in that the list
2861 * entry won't be deleted though the process has exited.
2863 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2864 list_add(&p->cg_list, &task_css_set(p)->tasks);
2866 } while_each_thread(g, p);
2867 read_unlock(&tasklist_lock);
2868 write_unlock(&css_set_lock);
2872 * css_next_child - find the next child of a given css
2873 * @pos_css: the current position (%NULL to initiate traversal)
2874 * @parent_css: css whose children to walk
2876 * This function returns the next child of @parent_css and should be called
2877 * under either cgroup_mutex or RCU read lock. The only requirement is
2878 * that @parent_css and @pos_css are accessible. The next sibling is
2879 * guaranteed to be returned regardless of their states.
2881 struct cgroup_subsys_state *
2882 css_next_child(struct cgroup_subsys_state *pos_css,
2883 struct cgroup_subsys_state *parent_css)
2885 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
2886 struct cgroup *cgrp = parent_css->cgroup;
2887 struct cgroup *next;
2889 cgroup_assert_mutex_or_rcu_locked();
2892 * @pos could already have been removed. Once a cgroup is removed,
2893 * its ->sibling.next is no longer updated when its next sibling
2894 * changes. As CGRP_DEAD assertion is serialized and happens
2895 * before the cgroup is taken off the ->sibling list, if we see it
2896 * unasserted, it's guaranteed that the next sibling hasn't
2897 * finished its grace period even if it's already removed, and thus
2898 * safe to dereference from this RCU critical section. If
2899 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
2900 * to be visible as %true here.
2902 * If @pos is dead, its next pointer can't be dereferenced;
2903 * however, as each cgroup is given a monotonically increasing
2904 * unique serial number and always appended to the sibling list,
2905 * the next one can be found by walking the parent's children until
2906 * we see a cgroup with higher serial number than @pos's. While
2907 * this path can be slower, it's taken only when either the current
2908 * cgroup is removed or iteration and removal race.
2911 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
2912 } else if (likely(!cgroup_is_dead(pos))) {
2913 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
2915 list_for_each_entry_rcu(next, &cgrp->children, sibling)
2916 if (next->serial_nr > pos->serial_nr)
2920 if (&next->sibling == &cgrp->children)
2923 return cgroup_css(next, parent_css->ss);
2925 EXPORT_SYMBOL_GPL(css_next_child);
2928 * css_next_descendant_pre - find the next descendant for pre-order walk
2929 * @pos: the current position (%NULL to initiate traversal)
2930 * @root: css whose descendants to walk
2932 * To be used by css_for_each_descendant_pre(). Find the next descendant
2933 * to visit for pre-order traversal of @root's descendants. @root is
2934 * included in the iteration and the first node to be visited.
2936 * While this function requires cgroup_mutex or RCU read locking, it
2937 * doesn't require the whole traversal to be contained in a single critical
2938 * section. This function will return the correct next descendant as long
2939 * as both @pos and @root are accessible and @pos is a descendant of @root.
2941 struct cgroup_subsys_state *
2942 css_next_descendant_pre(struct cgroup_subsys_state *pos,
2943 struct cgroup_subsys_state *root)
2945 struct cgroup_subsys_state *next;
2947 cgroup_assert_mutex_or_rcu_locked();
2949 /* if first iteration, visit @root */
2953 /* visit the first child if exists */
2954 next = css_next_child(NULL, pos);
2958 /* no child, visit my or the closest ancestor's next sibling */
2959 while (pos != root) {
2960 next = css_next_child(pos, css_parent(pos));
2963 pos = css_parent(pos);
2968 EXPORT_SYMBOL_GPL(css_next_descendant_pre);
2971 * css_rightmost_descendant - return the rightmost descendant of a css
2972 * @pos: css of interest
2974 * Return the rightmost descendant of @pos. If there's no descendant, @pos
2975 * is returned. This can be used during pre-order traversal to skip
2978 * While this function requires cgroup_mutex or RCU read locking, it
2979 * doesn't require the whole traversal to be contained in a single critical
2980 * section. This function will return the correct rightmost descendant as
2981 * long as @pos is accessible.
2983 struct cgroup_subsys_state *
2984 css_rightmost_descendant(struct cgroup_subsys_state *pos)
2986 struct cgroup_subsys_state *last, *tmp;
2988 cgroup_assert_mutex_or_rcu_locked();
2992 /* ->prev isn't RCU safe, walk ->next till the end */
2994 css_for_each_child(tmp, last)
3000 EXPORT_SYMBOL_GPL(css_rightmost_descendant);
3002 static struct cgroup_subsys_state *
3003 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3005 struct cgroup_subsys_state *last;
3009 pos = css_next_child(NULL, pos);
3016 * css_next_descendant_post - find the next descendant for post-order walk
3017 * @pos: the current position (%NULL to initiate traversal)
3018 * @root: css whose descendants to walk
3020 * To be used by css_for_each_descendant_post(). Find the next descendant
3021 * to visit for post-order traversal of @root's descendants. @root is
3022 * included in the iteration and the last node to be visited.
3024 * While this function requires cgroup_mutex or RCU read locking, it
3025 * doesn't require the whole traversal to be contained in a single critical
3026 * section. This function will return the correct next descendant as long
3027 * as both @pos and @cgroup are accessible and @pos is a descendant of
3030 struct cgroup_subsys_state *
3031 css_next_descendant_post(struct cgroup_subsys_state *pos,
3032 struct cgroup_subsys_state *root)
3034 struct cgroup_subsys_state *next;
3036 cgroup_assert_mutex_or_rcu_locked();
3038 /* if first iteration, visit leftmost descendant which may be @root */
3040 return css_leftmost_descendant(root);
3042 /* if we visited @root, we're done */
3046 /* if there's an unvisited sibling, visit its leftmost descendant */
3047 next = css_next_child(pos, css_parent(pos));
3049 return css_leftmost_descendant(next);
3051 /* no sibling left, visit parent */
3052 return css_parent(pos);
3054 EXPORT_SYMBOL_GPL(css_next_descendant_post);
3057 * css_advance_task_iter - advance a task itererator to the next css_set
3058 * @it: the iterator to advance
3060 * Advance @it to the next css_set to walk.
3062 static void css_advance_task_iter(struct css_task_iter *it)
3064 struct list_head *l = it->cset_link;
3065 struct cgrp_cset_link *link;
3066 struct css_set *cset;
3068 /* Advance to the next non-empty css_set */
3071 if (l == &it->origin_css->cgroup->cset_links) {
3072 it->cset_link = NULL;
3075 link = list_entry(l, struct cgrp_cset_link, cset_link);
3077 } while (list_empty(&cset->tasks));
3079 it->task = cset->tasks.next;
3083 * css_task_iter_start - initiate task iteration
3084 * @css: the css to walk tasks of
3085 * @it: the task iterator to use
3087 * Initiate iteration through the tasks of @css. The caller can call
3088 * css_task_iter_next() to walk through the tasks until the function
3089 * returns NULL. On completion of iteration, css_task_iter_end() must be
3092 * Note that this function acquires a lock which is released when the
3093 * iteration finishes. The caller can't sleep while iteration is in
3096 void css_task_iter_start(struct cgroup_subsys_state *css,
3097 struct css_task_iter *it)
3098 __acquires(css_set_lock)
3101 * The first time anyone tries to iterate across a css, we need to
3102 * enable the list linking each css_set to its tasks, and fix up
3103 * all existing tasks.
3105 if (!use_task_css_set_links)
3106 cgroup_enable_task_cg_lists();
3108 read_lock(&css_set_lock);
3110 it->origin_css = css;
3111 it->cset_link = &css->cgroup->cset_links;
3113 css_advance_task_iter(it);
3117 * css_task_iter_next - return the next task for the iterator
3118 * @it: the task iterator being iterated
3120 * The "next" function for task iteration. @it should have been
3121 * initialized via css_task_iter_start(). Returns NULL when the iteration
3124 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3126 struct task_struct *res;
3127 struct list_head *l = it->task;
3128 struct cgrp_cset_link *link;
3130 /* If the iterator cg is NULL, we have no tasks */
3133 res = list_entry(l, struct task_struct, cg_list);
3134 /* Advance iterator to find next entry */
3136 link = list_entry(it->cset_link, struct cgrp_cset_link, cset_link);
3137 if (l == &link->cset->tasks) {
3139 * We reached the end of this task list - move on to the
3140 * next cgrp_cset_link.
3142 css_advance_task_iter(it);
3150 * css_task_iter_end - finish task iteration
3151 * @it: the task iterator to finish
3153 * Finish task iteration started by css_task_iter_start().
3155 void css_task_iter_end(struct css_task_iter *it)
3156 __releases(css_set_lock)
3158 read_unlock(&css_set_lock);
3161 static inline int started_after_time(struct task_struct *t1,
3162 struct timespec *time,
3163 struct task_struct *t2)
3165 int start_diff = timespec_compare(&t1->start_time, time);
3166 if (start_diff > 0) {
3168 } else if (start_diff < 0) {
3172 * Arbitrarily, if two processes started at the same
3173 * time, we'll say that the lower pointer value
3174 * started first. Note that t2 may have exited by now
3175 * so this may not be a valid pointer any longer, but
3176 * that's fine - it still serves to distinguish
3177 * between two tasks started (effectively) simultaneously.
3184 * This function is a callback from heap_insert() and is used to order
3186 * In this case we order the heap in descending task start time.
3188 static inline int started_after(void *p1, void *p2)
3190 struct task_struct *t1 = p1;
3191 struct task_struct *t2 = p2;
3192 return started_after_time(t1, &t2->start_time, t2);
3196 * css_scan_tasks - iterate though all the tasks in a css
3197 * @css: the css to iterate tasks of
3198 * @test: optional test callback
3199 * @process: process callback
3200 * @data: data passed to @test and @process
3201 * @heap: optional pre-allocated heap used for task iteration
3203 * Iterate through all the tasks in @css, calling @test for each, and if it
3204 * returns %true, call @process for it also.
3206 * @test may be NULL, meaning always true (select all tasks), which
3207 * effectively duplicates css_task_iter_{start,next,end}() but does not
3208 * lock css_set_lock for the call to @process.
3210 * It is guaranteed that @process will act on every task that is a member
3211 * of @css for the duration of this call. This function may or may not
3212 * call @process for tasks that exit or move to a different css during the
3213 * call, or are forked or move into the css during the call.
3215 * Note that @test may be called with locks held, and may in some
3216 * situations be called multiple times for the same task, so it should be
3219 * If @heap is non-NULL, a heap has been pre-allocated and will be used for
3220 * heap operations (and its "gt" member will be overwritten), else a
3221 * temporary heap will be used (allocation of which may cause this function
3224 int css_scan_tasks(struct cgroup_subsys_state *css,
3225 bool (*test)(struct task_struct *, void *),
3226 void (*process)(struct task_struct *, void *),
3227 void *data, struct ptr_heap *heap)
3230 struct css_task_iter it;
3231 struct task_struct *p, *dropped;
3232 /* Never dereference latest_task, since it's not refcounted */
3233 struct task_struct *latest_task = NULL;
3234 struct ptr_heap tmp_heap;
3235 struct timespec latest_time = { 0, 0 };
3238 /* The caller supplied our heap and pre-allocated its memory */
3239 heap->gt = &started_after;
3241 /* We need to allocate our own heap memory */
3243 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3245 /* cannot allocate the heap */
3251 * Scan tasks in the css, using the @test callback to determine
3252 * which are of interest, and invoking @process callback on the
3253 * ones which need an update. Since we don't want to hold any
3254 * locks during the task updates, gather tasks to be processed in a
3255 * heap structure. The heap is sorted by descending task start
3256 * time. If the statically-sized heap fills up, we overflow tasks
3257 * that started later, and in future iterations only consider tasks
3258 * that started after the latest task in the previous pass. This
3259 * guarantees forward progress and that we don't miss any tasks.
3262 css_task_iter_start(css, &it);
3263 while ((p = css_task_iter_next(&it))) {
3265 * Only affect tasks that qualify per the caller's callback,
3266 * if he provided one
3268 if (test && !test(p, data))
3271 * Only process tasks that started after the last task
3274 if (!started_after_time(p, &latest_time, latest_task))
3276 dropped = heap_insert(heap, p);
3277 if (dropped == NULL) {
3279 * The new task was inserted; the heap wasn't
3283 } else if (dropped != p) {
3285 * The new task was inserted, and pushed out a
3289 put_task_struct(dropped);
3292 * Else the new task was newer than anything already in
3293 * the heap and wasn't inserted
3296 css_task_iter_end(&it);
3299 for (i = 0; i < heap->size; i++) {
3300 struct task_struct *q = heap->ptrs[i];
3302 latest_time = q->start_time;
3305 /* Process the task per the caller's callback */
3310 * If we had to process any tasks at all, scan again
3311 * in case some of them were in the middle of forking
3312 * children that didn't get processed.
3313 * Not the most efficient way to do it, but it avoids
3314 * having to take callback_mutex in the fork path
3318 if (heap == &tmp_heap)
3319 heap_free(&tmp_heap);
3323 static void cgroup_transfer_one_task(struct task_struct *task, void *data)
3325 struct cgroup *new_cgroup = data;
3327 mutex_lock(&cgroup_mutex);
3328 cgroup_attach_task(new_cgroup, task, false);
3329 mutex_unlock(&cgroup_mutex);
3333 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3334 * @to: cgroup to which the tasks will be moved
3335 * @from: cgroup in which the tasks currently reside
3337 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3339 return css_scan_tasks(&from->dummy_css, NULL, cgroup_transfer_one_task,
3344 * Stuff for reading the 'tasks'/'procs' files.
3346 * Reading this file can return large amounts of data if a cgroup has
3347 * *lots* of attached tasks. So it may need several calls to read(),
3348 * but we cannot guarantee that the information we produce is correct
3349 * unless we produce it entirely atomically.
3353 /* which pidlist file are we talking about? */
3354 enum cgroup_filetype {
3360 * A pidlist is a list of pids that virtually represents the contents of one
3361 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3362 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3365 struct cgroup_pidlist {
3367 * used to find which pidlist is wanted. doesn't change as long as
3368 * this particular list stays in the list.
3370 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3373 /* how many elements the above list has */
3375 /* each of these stored in a list by its cgroup */
3376 struct list_head links;
3377 /* pointer to the cgroup we belong to, for list removal purposes */
3378 struct cgroup *owner;
3379 /* for delayed destruction */
3380 struct delayed_work destroy_dwork;
3384 * The following two functions "fix" the issue where there are more pids
3385 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3386 * TODO: replace with a kernel-wide solution to this problem
3388 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3389 static void *pidlist_allocate(int count)
3391 if (PIDLIST_TOO_LARGE(count))
3392 return vmalloc(count * sizeof(pid_t));
3394 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3397 static void pidlist_free(void *p)
3399 if (is_vmalloc_addr(p))
3406 * Used to destroy all pidlists lingering waiting for destroy timer. None
3407 * should be left afterwards.
3409 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
3411 struct cgroup_pidlist *l, *tmp_l;
3413 mutex_lock(&cgrp->pidlist_mutex);
3414 list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
3415 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
3416 mutex_unlock(&cgrp->pidlist_mutex);
3418 flush_workqueue(cgroup_pidlist_destroy_wq);
3419 BUG_ON(!list_empty(&cgrp->pidlists));
3422 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
3424 struct delayed_work *dwork = to_delayed_work(work);
3425 struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
3427 struct cgroup_pidlist *tofree = NULL;
3429 mutex_lock(&l->owner->pidlist_mutex);
3432 * Destroy iff we didn't get queued again. The state won't change
3433 * as destroy_dwork can only be queued while locked.
3435 if (!delayed_work_pending(dwork)) {
3436 list_del(&l->links);
3437 pidlist_free(l->list);
3438 put_pid_ns(l->key.ns);
3442 mutex_unlock(&l->owner->pidlist_mutex);
3447 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3448 * Returns the number of unique elements.
3450 static int pidlist_uniq(pid_t *list, int length)
3455 * we presume the 0th element is unique, so i starts at 1. trivial
3456 * edge cases first; no work needs to be done for either
3458 if (length == 0 || length == 1)
3460 /* src and dest walk down the list; dest counts unique elements */
3461 for (src = 1; src < length; src++) {
3462 /* find next unique element */
3463 while (list[src] == list[src-1]) {
3468 /* dest always points to where the next unique element goes */
3469 list[dest] = list[src];
3477 * The two pid files - task and cgroup.procs - guaranteed that the result
3478 * is sorted, which forced this whole pidlist fiasco. As pid order is
3479 * different per namespace, each namespace needs differently sorted list,
3480 * making it impossible to use, for example, single rbtree of member tasks
3481 * sorted by task pointer. As pidlists can be fairly large, allocating one
3482 * per open file is dangerous, so cgroup had to implement shared pool of
3483 * pidlists keyed by cgroup and namespace.
3485 * All this extra complexity was caused by the original implementation
3486 * committing to an entirely unnecessary property. In the long term, we
3487 * want to do away with it. Explicitly scramble sort order if
3488 * sane_behavior so that no such expectation exists in the new interface.
3490 * Scrambling is done by swapping every two consecutive bits, which is
3491 * non-identity one-to-one mapping which disturbs sort order sufficiently.
3493 static pid_t pid_fry(pid_t pid)
3495 unsigned a = pid & 0x55555555;
3496 unsigned b = pid & 0xAAAAAAAA;
3498 return (a << 1) | (b >> 1);
3501 static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
3503 if (cgroup_sane_behavior(cgrp))
3504 return pid_fry(pid);
3509 static int cmppid(const void *a, const void *b)
3511 return *(pid_t *)a - *(pid_t *)b;
3514 static int fried_cmppid(const void *a, const void *b)
3516 return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
3519 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3520 enum cgroup_filetype type)
3522 struct cgroup_pidlist *l;
3523 /* don't need task_nsproxy() if we're looking at ourself */
3524 struct pid_namespace *ns = task_active_pid_ns(current);
3526 lockdep_assert_held(&cgrp->pidlist_mutex);
3528 list_for_each_entry(l, &cgrp->pidlists, links)
3529 if (l->key.type == type && l->key.ns == ns)
3535 * find the appropriate pidlist for our purpose (given procs vs tasks)
3536 * returns with the lock on that pidlist already held, and takes care
3537 * of the use count, or returns NULL with no locks held if we're out of
3540 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
3541 enum cgroup_filetype type)
3543 struct cgroup_pidlist *l;
3545 lockdep_assert_held(&cgrp->pidlist_mutex);
3547 l = cgroup_pidlist_find(cgrp, type);
3551 /* entry not found; create a new one */
3552 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3556 INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
3558 /* don't need task_nsproxy() if we're looking at ourself */
3559 l->key.ns = get_pid_ns(task_active_pid_ns(current));
3561 list_add(&l->links, &cgrp->pidlists);
3566 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3568 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3569 struct cgroup_pidlist **lp)
3573 int pid, n = 0; /* used for populating the array */
3574 struct css_task_iter it;
3575 struct task_struct *tsk;
3576 struct cgroup_pidlist *l;
3578 lockdep_assert_held(&cgrp->pidlist_mutex);
3581 * If cgroup gets more users after we read count, we won't have
3582 * enough space - tough. This race is indistinguishable to the
3583 * caller from the case that the additional cgroup users didn't
3584 * show up until sometime later on.
3586 length = cgroup_task_count(cgrp);
3587 array = pidlist_allocate(length);
3590 /* now, populate the array */
3591 css_task_iter_start(&cgrp->dummy_css, &it);
3592 while ((tsk = css_task_iter_next(&it))) {
3593 if (unlikely(n == length))
3595 /* get tgid or pid for procs or tasks file respectively */
3596 if (type == CGROUP_FILE_PROCS)
3597 pid = task_tgid_vnr(tsk);
3599 pid = task_pid_vnr(tsk);
3600 if (pid > 0) /* make sure to only use valid results */
3603 css_task_iter_end(&it);
3605 /* now sort & (if procs) strip out duplicates */
3606 if (cgroup_sane_behavior(cgrp))
3607 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
3609 sort(array, length, sizeof(pid_t), cmppid, NULL);
3610 if (type == CGROUP_FILE_PROCS)
3611 length = pidlist_uniq(array, length);
3613 l = cgroup_pidlist_find_create(cgrp, type);
3615 mutex_unlock(&cgrp->pidlist_mutex);
3616 pidlist_free(array);
3620 /* store array, freeing old if necessary */
3621 pidlist_free(l->list);
3629 * cgroupstats_build - build and fill cgroupstats
3630 * @stats: cgroupstats to fill information into
3631 * @dentry: A dentry entry belonging to the cgroup for which stats have
3634 * Build and fill cgroupstats so that taskstats can export it to user
3637 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3640 struct cgroup *cgrp;
3641 struct css_task_iter it;
3642 struct task_struct *tsk;
3645 * Validate dentry by checking the superblock operations,
3646 * and make sure it's a directory.
3648 if (dentry->d_sb->s_op != &cgroup_ops ||
3649 !S_ISDIR(dentry->d_inode->i_mode))
3653 cgrp = dentry->d_fsdata;
3655 css_task_iter_start(&cgrp->dummy_css, &it);
3656 while ((tsk = css_task_iter_next(&it))) {
3657 switch (tsk->state) {
3659 stats->nr_running++;
3661 case TASK_INTERRUPTIBLE:
3662 stats->nr_sleeping++;
3664 case TASK_UNINTERRUPTIBLE:
3665 stats->nr_uninterruptible++;
3668 stats->nr_stopped++;
3671 if (delayacct_is_task_waiting_on_io(tsk))
3672 stats->nr_io_wait++;
3676 css_task_iter_end(&it);
3684 * seq_file methods for the tasks/procs files. The seq_file position is the
3685 * next pid to display; the seq_file iterator is a pointer to the pid
3686 * in the cgroup->l->list array.
3689 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3692 * Initially we receive a position value that corresponds to
3693 * one more than the last pid shown (or 0 on the first call or
3694 * after a seek to the start). Use a binary-search to find the
3695 * next pid to display, if any
3697 struct cgroup_open_file *of = s->private;
3698 struct cgroup *cgrp = seq_css(s)->cgroup;
3699 struct cgroup_pidlist *l;
3700 enum cgroup_filetype type = seq_cft(s)->private;
3701 int index = 0, pid = *pos;
3704 mutex_lock(&cgrp->pidlist_mutex);
3707 * !NULL @of->priv indicates that this isn't the first start()
3708 * after open. If the matching pidlist is around, we can use that.
3709 * Look for it. Note that @of->priv can't be used directly. It
3710 * could already have been destroyed.
3713 of->priv = cgroup_pidlist_find(cgrp, type);
3716 * Either this is the first start() after open or the matching
3717 * pidlist has been destroyed inbetween. Create a new one.
3720 ret = pidlist_array_load(cgrp, type,
3721 (struct cgroup_pidlist **)&of->priv);
3723 return ERR_PTR(ret);
3728 int end = l->length;
3730 while (index < end) {
3731 int mid = (index + end) / 2;
3732 if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
3735 } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
3741 /* If we're off the end of the array, we're done */
3742 if (index >= l->length)
3744 /* Update the abstract position to be the actual pid that we found */
3745 iter = l->list + index;
3746 *pos = cgroup_pid_fry(cgrp, *iter);
3750 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3752 struct cgroup_open_file *of = s->private;
3753 struct cgroup_pidlist *l = of->priv;
3756 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
3757 CGROUP_PIDLIST_DESTROY_DELAY);
3758 mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
3761 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3763 struct cgroup_open_file *of = s->private;
3764 struct cgroup_pidlist *l = of->priv;
3766 pid_t *end = l->list + l->length;
3768 * Advance to the next pid in the array. If this goes off the
3775 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
3780 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3782 return seq_printf(s, "%d\n", *(int *)v);
3786 * seq_operations functions for iterating on pidlists through seq_file -
3787 * independent of whether it's tasks or procs
3789 static const struct seq_operations cgroup_pidlist_seq_operations = {
3790 .start = cgroup_pidlist_start,
3791 .stop = cgroup_pidlist_stop,
3792 .next = cgroup_pidlist_next,
3793 .show = cgroup_pidlist_show,
3796 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3799 return notify_on_release(css->cgroup);
3802 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3803 struct cftype *cft, u64 val)
3805 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3807 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3809 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3814 * When dput() is called asynchronously, if umount has been done and
3815 * then deactivate_super() in cgroup_free_fn() kills the superblock,
3816 * there's a small window that vfs will see the root dentry with non-zero
3817 * refcnt and trigger BUG().
3819 * That's why we hold a reference before dput() and drop it right after.
3821 static void cgroup_dput(struct cgroup *cgrp)
3823 struct super_block *sb = cgrp->root->sb;
3825 atomic_inc(&sb->s_active);
3827 deactivate_super(sb);
3830 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3833 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3836 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3837 struct cftype *cft, u64 val)
3840 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3842 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3846 static struct cftype cgroup_base_files[] = {
3848 .name = "cgroup.procs",
3849 .seq_start = cgroup_pidlist_start,
3850 .seq_next = cgroup_pidlist_next,
3851 .seq_stop = cgroup_pidlist_stop,
3852 .seq_show = cgroup_pidlist_show,
3853 .private = CGROUP_FILE_PROCS,
3854 .write_u64 = cgroup_procs_write,
3855 .mode = S_IRUGO | S_IWUSR,
3858 .name = "cgroup.clone_children",
3859 .flags = CFTYPE_INSANE,
3860 .read_u64 = cgroup_clone_children_read,
3861 .write_u64 = cgroup_clone_children_write,
3864 .name = "cgroup.sane_behavior",
3865 .flags = CFTYPE_ONLY_ON_ROOT,
3866 .seq_show = cgroup_sane_behavior_show,
3870 * Historical crazy stuff. These don't have "cgroup." prefix and
3871 * don't exist if sane_behavior. If you're depending on these, be
3872 * prepared to be burned.
3876 .flags = CFTYPE_INSANE, /* use "procs" instead */
3877 .seq_start = cgroup_pidlist_start,
3878 .seq_next = cgroup_pidlist_next,
3879 .seq_stop = cgroup_pidlist_stop,
3880 .seq_show = cgroup_pidlist_show,
3881 .private = CGROUP_FILE_TASKS,
3882 .write_u64 = cgroup_tasks_write,
3883 .mode = S_IRUGO | S_IWUSR,
3886 .name = "notify_on_release",
3887 .flags = CFTYPE_INSANE,
3888 .read_u64 = cgroup_read_notify_on_release,
3889 .write_u64 = cgroup_write_notify_on_release,
3892 .name = "release_agent",
3893 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
3894 .seq_show = cgroup_release_agent_show,
3895 .write_string = cgroup_release_agent_write,
3896 .max_write_len = PATH_MAX,
3902 * cgroup_populate_dir - create subsys files in a cgroup directory
3903 * @cgrp: target cgroup
3904 * @subsys_mask: mask of the subsystem ids whose files should be added
3906 * On failure, no file is added.
3908 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
3910 struct cgroup_subsys *ss;
3913 /* process cftsets of each subsystem */
3914 for_each_subsys(ss, i) {
3915 struct cftype_set *set;
3917 if (!test_bit(i, &subsys_mask))
3920 list_for_each_entry(set, &ss->cftsets, node) {
3921 ret = cgroup_addrm_files(cgrp, set->cfts, true);
3928 cgroup_clear_dir(cgrp, subsys_mask);
3933 * css destruction is four-stage process.
3935 * 1. Destruction starts. Killing of the percpu_ref is initiated.
3936 * Implemented in kill_css().
3938 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
3939 * and thus css_tryget() is guaranteed to fail, the css can be offlined
3940 * by invoking offline_css(). After offlining, the base ref is put.
3941 * Implemented in css_killed_work_fn().
3943 * 3. When the percpu_ref reaches zero, the only possible remaining
3944 * accessors are inside RCU read sections. css_release() schedules the
3947 * 4. After the grace period, the css can be freed. Implemented in
3948 * css_free_work_fn().
3950 * It is actually hairier because both step 2 and 4 require process context
3951 * and thus involve punting to css->destroy_work adding two additional
3952 * steps to the already complex sequence.
3954 static void css_free_work_fn(struct work_struct *work)
3956 struct cgroup_subsys_state *css =
3957 container_of(work, struct cgroup_subsys_state, destroy_work);
3958 struct cgroup *cgrp = css->cgroup;
3961 css_put(css->parent);
3963 css->ss->css_free(css);
3967 static void css_free_rcu_fn(struct rcu_head *rcu_head)
3969 struct cgroup_subsys_state *css =
3970 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
3973 * css holds an extra ref to @cgrp->dentry which is put on the last
3974 * css_put(). dput() requires process context which we don't have.
3976 INIT_WORK(&css->destroy_work, css_free_work_fn);
3977 queue_work(cgroup_destroy_wq, &css->destroy_work);
3980 static void css_release(struct percpu_ref *ref)
3982 struct cgroup_subsys_state *css =
3983 container_of(ref, struct cgroup_subsys_state, refcnt);
3985 rcu_assign_pointer(css->cgroup->subsys[css->ss->id], NULL);
3986 call_rcu(&css->rcu_head, css_free_rcu_fn);
3989 static void init_css(struct cgroup_subsys_state *css, struct cgroup_subsys *ss,
3990 struct cgroup *cgrp)
3997 css->parent = cgroup_css(cgrp->parent, ss);
3999 css->flags |= CSS_ROOT;
4001 BUG_ON(cgroup_css(cgrp, ss));
4004 /* invoke ->css_online() on a new CSS and mark it online if successful */
4005 static int online_css(struct cgroup_subsys_state *css)
4007 struct cgroup_subsys *ss = css->ss;
4010 lockdep_assert_held(&cgroup_mutex);
4013 ret = ss->css_online(css);
4015 css->flags |= CSS_ONLINE;
4016 css->cgroup->nr_css++;
4017 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
4022 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4023 static void offline_css(struct cgroup_subsys_state *css)
4025 struct cgroup_subsys *ss = css->ss;
4027 lockdep_assert_held(&cgroup_mutex);
4029 if (!(css->flags & CSS_ONLINE))
4032 if (ss->css_offline)
4033 ss->css_offline(css);
4035 css->flags &= ~CSS_ONLINE;
4036 css->cgroup->nr_css--;
4037 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], css);
4041 * create_css - create a cgroup_subsys_state
4042 * @cgrp: the cgroup new css will be associated with
4043 * @ss: the subsys of new css
4045 * Create a new css associated with @cgrp - @ss pair. On success, the new
4046 * css is online and installed in @cgrp with all interface files created.
4047 * Returns 0 on success, -errno on failure.
4049 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss)
4051 struct cgroup *parent = cgrp->parent;
4052 struct cgroup_subsys_state *css;
4055 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
4056 lockdep_assert_held(&cgroup_mutex);
4058 css = ss->css_alloc(cgroup_css(parent, ss));
4060 return PTR_ERR(css);
4062 err = percpu_ref_init(&css->refcnt, css_release);
4066 init_css(css, ss, cgrp);
4068 err = cgroup_populate_dir(cgrp, 1 << ss->id);
4072 err = online_css(css);
4077 css_get(css->parent);
4079 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4081 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",
4082 current->comm, current->pid, ss->name);
4083 if (!strcmp(ss->name, "memory"))
4084 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4085 ss->warned_broken_hierarchy = true;
4091 percpu_ref_cancel_init(&css->refcnt);
4097 * cgroup_create - create a cgroup
4098 * @parent: cgroup that will be parent of the new cgroup
4099 * @dentry: dentry of the new cgroup
4100 * @mode: mode to set on new inode
4102 * Must be called with the mutex on the parent inode held
4104 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4107 struct cgroup *cgrp;
4108 struct cgroup_name *name;
4109 struct cgroupfs_root *root = parent->root;
4111 struct cgroup_subsys *ss;
4112 struct super_block *sb = root->sb;
4114 /* allocate the cgroup and its ID, 0 is reserved for the root */
4115 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4119 name = cgroup_alloc_name(dentry);
4122 rcu_assign_pointer(cgrp->name, name);
4125 * Temporarily set the pointer to NULL, so idr_find() won't return
4126 * a half-baked cgroup.
4128 cgrp->id = idr_alloc(&root->cgroup_idr, NULL, 1, 0, GFP_KERNEL);
4133 * Only live parents can have children. Note that the liveliness
4134 * check isn't strictly necessary because cgroup_mkdir() and
4135 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4136 * anyway so that locking is contained inside cgroup proper and we
4137 * don't get nasty surprises if we ever grow another caller.
4139 if (!cgroup_lock_live_group(parent)) {
4144 /* Grab a reference on the superblock so the hierarchy doesn't
4145 * get deleted on unmount if there are child cgroups. This
4146 * can be done outside cgroup_mutex, since the sb can't
4147 * disappear while someone has an open control file on the
4149 atomic_inc(&sb->s_active);
4151 init_cgroup_housekeeping(cgrp);
4153 dentry->d_fsdata = cgrp;
4154 cgrp->dentry = dentry;
4156 cgrp->parent = parent;
4157 cgrp->dummy_css.parent = &parent->dummy_css;
4158 cgrp->root = parent->root;
4160 if (notify_on_release(parent))
4161 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4163 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4164 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4167 * Create directory. cgroup_create_file() returns with the new
4168 * directory locked on success so that it can be populated without
4169 * dropping cgroup_mutex.
4171 err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4174 lockdep_assert_held(&dentry->d_inode->i_mutex);
4176 cgrp->serial_nr = cgroup_serial_nr_next++;
4178 /* allocation complete, commit to creation */
4179 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4180 root->number_of_cgroups++;
4182 /* hold a ref to the parent's dentry */
4183 dget(parent->dentry);
4186 * @cgrp is now fully operational. If something fails after this
4187 * point, it'll be released via the normal destruction path.
4189 idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4191 err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
4195 /* let's create and online css's */
4196 for_each_subsys(ss, ssid) {
4197 if (root->subsys_mask & (1 << ssid)) {
4198 err = create_css(cgrp, ss);
4204 mutex_unlock(&cgroup_mutex);
4205 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4210 mutex_unlock(&cgroup_mutex);
4211 /* Release the reference count that we took on the superblock */
4212 deactivate_super(sb);
4214 idr_remove(&root->cgroup_idr, cgrp->id);
4216 kfree(rcu_dereference_raw(cgrp->name));
4222 cgroup_destroy_locked(cgrp);
4223 mutex_unlock(&cgroup_mutex);
4224 mutex_unlock(&dentry->d_inode->i_mutex);
4228 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4230 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4232 /* the vfs holds inode->i_mutex already */
4233 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4237 * This is called when the refcnt of a css is confirmed to be killed.
4238 * css_tryget() is now guaranteed to fail.
4240 static void css_killed_work_fn(struct work_struct *work)
4242 struct cgroup_subsys_state *css =
4243 container_of(work, struct cgroup_subsys_state, destroy_work);
4244 struct cgroup *cgrp = css->cgroup;
4246 mutex_lock(&cgroup_mutex);
4249 * css_tryget() is guaranteed to fail now. Tell subsystems to
4250 * initate destruction.
4255 * If @cgrp is marked dead, it's waiting for refs of all css's to
4256 * be disabled before proceeding to the second phase of cgroup
4257 * destruction. If we are the last one, kick it off.
4259 if (!cgrp->nr_css && cgroup_is_dead(cgrp))
4260 cgroup_destroy_css_killed(cgrp);
4262 mutex_unlock(&cgroup_mutex);
4265 * Put the css refs from kill_css(). Each css holds an extra
4266 * reference to the cgroup's dentry and cgroup removal proceeds
4267 * regardless of css refs. On the last put of each css, whenever
4268 * that may be, the extra dentry ref is put so that dentry
4269 * destruction happens only after all css's are released.
4274 /* css kill confirmation processing requires process context, bounce */
4275 static void css_killed_ref_fn(struct percpu_ref *ref)
4277 struct cgroup_subsys_state *css =
4278 container_of(ref, struct cgroup_subsys_state, refcnt);
4280 INIT_WORK(&css->destroy_work, css_killed_work_fn);
4281 queue_work(cgroup_destroy_wq, &css->destroy_work);
4285 * kill_css - destroy a css
4286 * @css: css to destroy
4288 * This function initiates destruction of @css by removing cgroup interface
4289 * files and putting its base reference. ->css_offline() will be invoked
4290 * asynchronously once css_tryget() is guaranteed to fail and when the
4291 * reference count reaches zero, @css will be released.
4293 static void kill_css(struct cgroup_subsys_state *css)
4295 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4298 * Killing would put the base ref, but we need to keep it alive
4299 * until after ->css_offline().
4304 * cgroup core guarantees that, by the time ->css_offline() is
4305 * invoked, no new css reference will be given out via
4306 * css_tryget(). We can't simply call percpu_ref_kill() and
4307 * proceed to offlining css's because percpu_ref_kill() doesn't
4308 * guarantee that the ref is seen as killed on all CPUs on return.
4310 * Use percpu_ref_kill_and_confirm() to get notifications as each
4311 * css is confirmed to be seen as killed on all CPUs.
4313 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4317 * cgroup_destroy_locked - the first stage of cgroup destruction
4318 * @cgrp: cgroup to be destroyed
4320 * css's make use of percpu refcnts whose killing latency shouldn't be
4321 * exposed to userland and are RCU protected. Also, cgroup core needs to
4322 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
4323 * invoked. To satisfy all the requirements, destruction is implemented in
4324 * the following two steps.
4326 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4327 * userland visible parts and start killing the percpu refcnts of
4328 * css's. Set up so that the next stage will be kicked off once all
4329 * the percpu refcnts are confirmed to be killed.
4331 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4332 * rest of destruction. Once all cgroup references are gone, the
4333 * cgroup is RCU-freed.
4335 * This function implements s1. After this step, @cgrp is gone as far as
4336 * the userland is concerned and a new cgroup with the same name may be
4337 * created. As cgroup doesn't care about the names internally, this
4338 * doesn't cause any problem.
4340 static int cgroup_destroy_locked(struct cgroup *cgrp)
4341 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4343 struct dentry *d = cgrp->dentry;
4344 struct cgroup_subsys_state *css;
4345 struct cgroup *child;
4349 lockdep_assert_held(&d->d_inode->i_mutex);
4350 lockdep_assert_held(&cgroup_mutex);
4353 * css_set_lock synchronizes access to ->cset_links and prevents
4354 * @cgrp from being removed while __put_css_set() is in progress.
4356 read_lock(&css_set_lock);
4357 empty = list_empty(&cgrp->cset_links);
4358 read_unlock(&css_set_lock);
4363 * Make sure there's no live children. We can't test ->children
4364 * emptiness as dead children linger on it while being destroyed;
4365 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
4369 list_for_each_entry_rcu(child, &cgrp->children, sibling) {
4370 empty = cgroup_is_dead(child);
4379 * Initiate massacre of all css's. cgroup_destroy_css_killed()
4380 * will be invoked to perform the rest of destruction once the
4381 * percpu refs of all css's are confirmed to be killed.
4383 for_each_css(css, ssid, cgrp)
4387 * Mark @cgrp dead. This prevents further task migration and child
4388 * creation by disabling cgroup_lock_live_group(). Note that
4389 * CGRP_DEAD assertion is depended upon by css_next_child() to
4390 * resume iteration after dropping RCU read lock. See
4391 * css_next_child() for details.
4393 set_bit(CGRP_DEAD, &cgrp->flags);
4395 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4396 raw_spin_lock(&release_list_lock);
4397 if (!list_empty(&cgrp->release_list))
4398 list_del_init(&cgrp->release_list);
4399 raw_spin_unlock(&release_list_lock);
4402 * If @cgrp has css's attached, the second stage of cgroup
4403 * destruction is kicked off from css_killed_work_fn() after the
4404 * refs of all attached css's are killed. If @cgrp doesn't have
4405 * any css, we kick it off here.
4408 cgroup_destroy_css_killed(cgrp);
4411 * Clear the base files and remove @cgrp directory. The removal
4412 * puts the base ref but we aren't quite done with @cgrp yet, so
4415 cgroup_addrm_files(cgrp, cgroup_base_files, false);
4417 cgroup_d_remove_dir(d);
4423 * cgroup_destroy_css_killed - the second step of cgroup destruction
4424 * @work: cgroup->destroy_free_work
4426 * This function is invoked from a work item for a cgroup which is being
4427 * destroyed after all css's are offlined and performs the rest of
4428 * destruction. This is the second step of destruction described in the
4429 * comment above cgroup_destroy_locked().
4431 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
4433 struct cgroup *parent = cgrp->parent;
4434 struct dentry *d = cgrp->dentry;
4436 lockdep_assert_held(&cgroup_mutex);
4438 /* delete this cgroup from parent->children */
4439 list_del_rcu(&cgrp->sibling);
4443 set_bit(CGRP_RELEASABLE, &parent->flags);
4444 check_for_release(parent);
4447 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4451 mutex_lock(&cgroup_mutex);
4452 ret = cgroup_destroy_locked(dentry->d_fsdata);
4453 mutex_unlock(&cgroup_mutex);
4458 static void __init cgroup_init_cftsets(struct cgroup_subsys *ss)
4460 INIT_LIST_HEAD(&ss->cftsets);
4463 * base_cftset is embedded in subsys itself, no need to worry about
4466 if (ss->base_cftypes) {
4469 for (cft = ss->base_cftypes; cft->name[0] != '\0'; cft++)
4472 ss->base_cftset.cfts = ss->base_cftypes;
4473 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4477 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4479 struct cgroup_subsys_state *css;
4481 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4483 mutex_lock(&cgroup_mutex);
4485 /* init base cftset */
4486 cgroup_init_cftsets(ss);
4488 /* Create the top cgroup state for this subsystem */
4489 ss->root = &cgroup_dummy_root;
4490 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
4491 /* We don't handle early failures gracefully */
4492 BUG_ON(IS_ERR(css));
4493 init_css(css, ss, cgroup_dummy_top);
4495 /* Update the init_css_set to contain a subsys
4496 * pointer to this state - since the subsystem is
4497 * newly registered, all tasks and hence the
4498 * init_css_set is in the subsystem's top cgroup. */
4499 init_css_set.subsys[ss->id] = css;
4501 need_forkexit_callback |= ss->fork || ss->exit;
4503 /* At system boot, before all subsystems have been
4504 * registered, no tasks have been forked, so we don't
4505 * need to invoke fork callbacks here. */
4506 BUG_ON(!list_empty(&init_task.tasks));
4508 BUG_ON(online_css(css));
4510 mutex_unlock(&cgroup_mutex);
4514 * cgroup_init_early - cgroup initialization at system boot
4516 * Initialize cgroups at system boot, and initialize any
4517 * subsystems that request early init.
4519 int __init cgroup_init_early(void)
4521 struct cgroup_subsys *ss;
4524 atomic_set(&init_css_set.refcount, 1);
4525 INIT_LIST_HEAD(&init_css_set.cgrp_links);
4526 INIT_LIST_HEAD(&init_css_set.tasks);
4527 INIT_HLIST_NODE(&init_css_set.hlist);
4529 init_cgroup_root(&cgroup_dummy_root);
4530 cgroup_root_count = 1;
4531 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4533 init_cgrp_cset_link.cset = &init_css_set;
4534 init_cgrp_cset_link.cgrp = cgroup_dummy_top;
4535 list_add(&init_cgrp_cset_link.cset_link, &cgroup_dummy_top->cset_links);
4536 list_add(&init_cgrp_cset_link.cgrp_link, &init_css_set.cgrp_links);
4538 for_each_subsys(ss, i) {
4539 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
4540 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
4541 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
4543 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
4544 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
4547 ss->name = cgroup_subsys_name[i];
4550 cgroup_init_subsys(ss);
4556 * cgroup_init - cgroup initialization
4558 * Register cgroup filesystem and /proc file, and initialize
4559 * any subsystems that didn't request early init.
4561 int __init cgroup_init(void)
4563 struct cgroup_subsys *ss;
4567 err = bdi_init(&cgroup_backing_dev_info);
4571 for_each_subsys(ss, i) {
4572 if (!ss->early_init)
4573 cgroup_init_subsys(ss);
4576 /* allocate id for the dummy hierarchy */
4577 mutex_lock(&cgroup_mutex);
4578 mutex_lock(&cgroup_root_mutex);
4580 /* Add init_css_set to the hash table */
4581 key = css_set_hash(init_css_set.subsys);
4582 hash_add(css_set_table, &init_css_set.hlist, key);
4584 BUG_ON(cgroup_init_root_id(&cgroup_dummy_root, 0, 1));
4586 err = idr_alloc(&cgroup_dummy_root.cgroup_idr, cgroup_dummy_top,
4590 mutex_unlock(&cgroup_root_mutex);
4591 mutex_unlock(&cgroup_mutex);
4593 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4599 err = register_filesystem(&cgroup_fs_type);
4601 kobject_put(cgroup_kobj);
4605 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4609 bdi_destroy(&cgroup_backing_dev_info);
4614 static int __init cgroup_wq_init(void)
4617 * There isn't much point in executing destruction path in
4618 * parallel. Good chunk is serialized with cgroup_mutex anyway.
4619 * Use 1 for @max_active.
4621 * We would prefer to do this in cgroup_init() above, but that
4622 * is called before init_workqueues(): so leave this until after.
4624 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
4625 BUG_ON(!cgroup_destroy_wq);
4628 * Used to destroy pidlists and separate to serve as flush domain.
4629 * Cap @max_active to 1 too.
4631 cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
4633 BUG_ON(!cgroup_pidlist_destroy_wq);
4637 core_initcall(cgroup_wq_init);
4640 * proc_cgroup_show()
4641 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4642 * - Used for /proc/<pid>/cgroup.
4643 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4644 * doesn't really matter if tsk->cgroup changes after we read it,
4645 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4646 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4647 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4648 * cgroup to top_cgroup.
4651 /* TODO: Use a proper seq_file iterator */
4652 int proc_cgroup_show(struct seq_file *m, void *v)
4655 struct task_struct *tsk;
4658 struct cgroupfs_root *root;
4661 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4667 tsk = get_pid_task(pid, PIDTYPE_PID);
4673 mutex_lock(&cgroup_mutex);
4675 for_each_active_root(root) {
4676 struct cgroup_subsys *ss;
4677 struct cgroup *cgrp;
4678 int ssid, count = 0;
4680 seq_printf(m, "%d:", root->hierarchy_id);
4681 for_each_subsys(ss, ssid)
4682 if (root->subsys_mask & (1 << ssid))
4683 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4684 if (strlen(root->name))
4685 seq_printf(m, "%sname=%s", count ? "," : "",
4688 cgrp = task_cgroup_from_root(tsk, root);
4689 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
4697 mutex_unlock(&cgroup_mutex);
4698 put_task_struct(tsk);
4705 /* Display information about each subsystem and each hierarchy */
4706 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4708 struct cgroup_subsys *ss;
4711 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4713 * ideally we don't want subsystems moving around while we do this.
4714 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4715 * subsys/hierarchy state.
4717 mutex_lock(&cgroup_mutex);
4719 for_each_subsys(ss, i)
4720 seq_printf(m, "%s\t%d\t%d\t%d\n",
4721 ss->name, ss->root->hierarchy_id,
4722 ss->root->number_of_cgroups, !ss->disabled);
4724 mutex_unlock(&cgroup_mutex);
4728 static int cgroupstats_open(struct inode *inode, struct file *file)
4730 return single_open(file, proc_cgroupstats_show, NULL);
4733 static const struct file_operations proc_cgroupstats_operations = {
4734 .open = cgroupstats_open,
4736 .llseek = seq_lseek,
4737 .release = single_release,
4741 * cgroup_fork - attach newly forked task to its parents cgroup.
4742 * @child: pointer to task_struct of forking parent process.
4744 * Description: A task inherits its parent's cgroup at fork().
4746 * A pointer to the shared css_set was automatically copied in
4747 * fork.c by dup_task_struct(). However, we ignore that copy, since
4748 * it was not made under the protection of RCU or cgroup_mutex, so
4749 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
4750 * have already changed current->cgroups, allowing the previously
4751 * referenced cgroup group to be removed and freed.
4753 * At the point that cgroup_fork() is called, 'current' is the parent
4754 * task, and the passed argument 'child' points to the child task.
4756 void cgroup_fork(struct task_struct *child)
4759 get_css_set(task_css_set(current));
4760 child->cgroups = current->cgroups;
4761 task_unlock(current);
4762 INIT_LIST_HEAD(&child->cg_list);
4766 * cgroup_post_fork - called on a new task after adding it to the task list
4767 * @child: the task in question
4769 * Adds the task to the list running through its css_set if necessary and
4770 * call the subsystem fork() callbacks. Has to be after the task is
4771 * visible on the task list in case we race with the first call to
4772 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
4775 void cgroup_post_fork(struct task_struct *child)
4777 struct cgroup_subsys *ss;
4781 * use_task_css_set_links is set to 1 before we walk the tasklist
4782 * under the tasklist_lock and we read it here after we added the child
4783 * to the tasklist under the tasklist_lock as well. If the child wasn't
4784 * yet in the tasklist when we walked through it from
4785 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4786 * should be visible now due to the paired locking and barriers implied
4787 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4788 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4791 if (use_task_css_set_links) {
4792 write_lock(&css_set_lock);
4794 if (list_empty(&child->cg_list))
4795 list_add(&child->cg_list, &task_css_set(child)->tasks);
4797 write_unlock(&css_set_lock);
4801 * Call ss->fork(). This must happen after @child is linked on
4802 * css_set; otherwise, @child might change state between ->fork()
4803 * and addition to css_set.
4805 if (need_forkexit_callback) {
4806 for_each_subsys(ss, i)
4813 * cgroup_exit - detach cgroup from exiting task
4814 * @tsk: pointer to task_struct of exiting process
4815 * @run_callback: run exit callbacks?
4817 * Description: Detach cgroup from @tsk and release it.
4819 * Note that cgroups marked notify_on_release force every task in
4820 * them to take the global cgroup_mutex mutex when exiting.
4821 * This could impact scaling on very large systems. Be reluctant to
4822 * use notify_on_release cgroups where very high task exit scaling
4823 * is required on large systems.
4825 * the_top_cgroup_hack:
4827 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
4829 * We call cgroup_exit() while the task is still competent to
4830 * handle notify_on_release(), then leave the task attached to the
4831 * root cgroup in each hierarchy for the remainder of its exit.
4833 * To do this properly, we would increment the reference count on
4834 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
4835 * code we would add a second cgroup function call, to drop that
4836 * reference. This would just create an unnecessary hot spot on
4837 * the top_cgroup reference count, to no avail.
4839 * Normally, holding a reference to a cgroup without bumping its
4840 * count is unsafe. The cgroup could go away, or someone could
4841 * attach us to a different cgroup, decrementing the count on
4842 * the first cgroup that we never incremented. But in this case,
4843 * top_cgroup isn't going away, and either task has PF_EXITING set,
4844 * which wards off any cgroup_attach_task() attempts, or task is a failed
4845 * fork, never visible to cgroup_attach_task.
4847 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
4849 struct cgroup_subsys *ss;
4850 struct css_set *cset;
4854 * Unlink from the css_set task list if necessary.
4855 * Optimistically check cg_list before taking
4858 if (!list_empty(&tsk->cg_list)) {
4859 write_lock(&css_set_lock);
4860 if (!list_empty(&tsk->cg_list))
4861 list_del_init(&tsk->cg_list);
4862 write_unlock(&css_set_lock);
4865 /* Reassign the task to the init_css_set. */
4867 cset = task_css_set(tsk);
4868 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
4870 if (run_callbacks && need_forkexit_callback) {
4871 /* see cgroup_post_fork() for details */
4872 for_each_subsys(ss, i) {
4874 struct cgroup_subsys_state *old_css = cset->subsys[i];
4875 struct cgroup_subsys_state *css = task_css(tsk, i);
4877 ss->exit(css, old_css, tsk);
4883 put_css_set_taskexit(cset);
4886 static void check_for_release(struct cgroup *cgrp)
4888 if (cgroup_is_releasable(cgrp) &&
4889 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
4891 * Control Group is currently removeable. If it's not
4892 * already queued for a userspace notification, queue
4895 int need_schedule_work = 0;
4897 raw_spin_lock(&release_list_lock);
4898 if (!cgroup_is_dead(cgrp) &&
4899 list_empty(&cgrp->release_list)) {
4900 list_add(&cgrp->release_list, &release_list);
4901 need_schedule_work = 1;
4903 raw_spin_unlock(&release_list_lock);
4904 if (need_schedule_work)
4905 schedule_work(&release_agent_work);
4910 * Notify userspace when a cgroup is released, by running the
4911 * configured release agent with the name of the cgroup (path
4912 * relative to the root of cgroup file system) as the argument.
4914 * Most likely, this user command will try to rmdir this cgroup.
4916 * This races with the possibility that some other task will be
4917 * attached to this cgroup before it is removed, or that some other
4918 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
4919 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
4920 * unused, and this cgroup will be reprieved from its death sentence,
4921 * to continue to serve a useful existence. Next time it's released,
4922 * we will get notified again, if it still has 'notify_on_release' set.
4924 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
4925 * means only wait until the task is successfully execve()'d. The
4926 * separate release agent task is forked by call_usermodehelper(),
4927 * then control in this thread returns here, without waiting for the
4928 * release agent task. We don't bother to wait because the caller of
4929 * this routine has no use for the exit status of the release agent
4930 * task, so no sense holding our caller up for that.
4932 static void cgroup_release_agent(struct work_struct *work)
4934 BUG_ON(work != &release_agent_work);
4935 mutex_lock(&cgroup_mutex);
4936 raw_spin_lock(&release_list_lock);
4937 while (!list_empty(&release_list)) {
4938 char *argv[3], *envp[3];
4940 char *pathbuf = NULL, *agentbuf = NULL;
4941 struct cgroup *cgrp = list_entry(release_list.next,
4944 list_del_init(&cgrp->release_list);
4945 raw_spin_unlock(&release_list_lock);
4946 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4949 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
4951 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
4956 argv[i++] = agentbuf;
4957 argv[i++] = pathbuf;
4961 /* minimal command environment */
4962 envp[i++] = "HOME=/";
4963 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
4966 /* Drop the lock while we invoke the usermode helper,
4967 * since the exec could involve hitting disk and hence
4968 * be a slow process */
4969 mutex_unlock(&cgroup_mutex);
4970 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
4971 mutex_lock(&cgroup_mutex);
4975 raw_spin_lock(&release_list_lock);
4977 raw_spin_unlock(&release_list_lock);
4978 mutex_unlock(&cgroup_mutex);
4981 static int __init cgroup_disable(char *str)
4983 struct cgroup_subsys *ss;
4987 while ((token = strsep(&str, ",")) != NULL) {
4991 for_each_subsys(ss, i) {
4992 if (!strcmp(token, ss->name)) {
4994 printk(KERN_INFO "Disabling %s control group"
4995 " subsystem\n", ss->name);
5002 __setup("cgroup_disable=", cgroup_disable);
5005 * css_from_dir - get corresponding css from the dentry of a cgroup dir
5006 * @dentry: directory dentry of interest
5007 * @ss: subsystem of interest
5009 * Must be called under cgroup_mutex or RCU read lock. The caller is
5010 * responsible for pinning the returned css if it needs to be accessed
5011 * outside the critical section.
5013 struct cgroup_subsys_state *css_from_dir(struct dentry *dentry,
5014 struct cgroup_subsys *ss)
5016 struct cgroup *cgrp;
5018 cgroup_assert_mutex_or_rcu_locked();
5020 /* is @dentry a cgroup dir? */
5021 if (!dentry->d_inode ||
5022 dentry->d_inode->i_op != &cgroup_dir_inode_operations)
5023 return ERR_PTR(-EBADF);
5025 cgrp = __d_cgrp(dentry);
5026 return cgroup_css(cgrp, ss) ?: ERR_PTR(-ENOENT);
5030 * css_from_id - lookup css by id
5031 * @id: the cgroup id
5032 * @ss: cgroup subsys to be looked into
5034 * Returns the css if there's valid one with @id, otherwise returns NULL.
5035 * Should be called under rcu_read_lock().
5037 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5039 struct cgroup *cgrp;
5041 cgroup_assert_mutex_or_rcu_locked();
5043 cgrp = idr_find(&ss->root->cgroup_idr, id);
5045 return cgroup_css(cgrp, ss);
5049 #ifdef CONFIG_CGROUP_DEBUG
5050 static struct cgroup_subsys_state *
5051 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5053 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5056 return ERR_PTR(-ENOMEM);
5061 static void debug_css_free(struct cgroup_subsys_state *css)
5066 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5069 return cgroup_task_count(css->cgroup);
5072 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5075 return (u64)(unsigned long)current->cgroups;
5078 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5084 count = atomic_read(&task_css_set(current)->refcount);
5089 static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
5091 struct cgrp_cset_link *link;
5092 struct css_set *cset;
5094 read_lock(&css_set_lock);
5096 cset = rcu_dereference(current->cgroups);
5097 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5098 struct cgroup *c = link->cgrp;
5102 name = c->dentry->d_name.name;
5105 seq_printf(seq, "Root %d group %s\n",
5106 c->root->hierarchy_id, name);
5109 read_unlock(&css_set_lock);
5113 #define MAX_TASKS_SHOWN_PER_CSS 25
5114 static int cgroup_css_links_read(struct seq_file *seq, void *v)
5116 struct cgroup_subsys_state *css = seq_css(seq);
5117 struct cgrp_cset_link *link;
5119 read_lock(&css_set_lock);
5120 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5121 struct css_set *cset = link->cset;
5122 struct task_struct *task;
5124 seq_printf(seq, "css_set %p\n", cset);
5125 list_for_each_entry(task, &cset->tasks, cg_list) {
5126 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5127 seq_puts(seq, " ...\n");
5130 seq_printf(seq, " task %d\n",
5131 task_pid_vnr(task));
5135 read_unlock(&css_set_lock);
5139 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5141 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
5144 static struct cftype debug_files[] = {
5146 .name = "taskcount",
5147 .read_u64 = debug_taskcount_read,
5151 .name = "current_css_set",
5152 .read_u64 = current_css_set_read,
5156 .name = "current_css_set_refcount",
5157 .read_u64 = current_css_set_refcount_read,
5161 .name = "current_css_set_cg_links",
5162 .seq_show = current_css_set_cg_links_read,
5166 .name = "cgroup_css_links",
5167 .seq_show = cgroup_css_links_read,
5171 .name = "releasable",
5172 .read_u64 = releasable_read,
5178 struct cgroup_subsys debug_cgrp_subsys = {
5179 .css_alloc = debug_css_alloc,
5180 .css_free = debug_css_free,
5181 .base_cftypes = debug_files,
5183 #endif /* CONFIG_CGROUP_DEBUG */