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 #ifdef CONFIG_PROVE_RCU
75 DEFINE_MUTEX(cgroup_mutex);
76 EXPORT_SYMBOL_GPL(cgroup_mutex); /* only for lockdep */
78 static DEFINE_MUTEX(cgroup_mutex);
82 * Protects cgroup_subsys->release_agent_path. Modifying it also requires
83 * cgroup_mutex. Reading requires either cgroup_mutex or this spinlock.
85 static DEFINE_SPINLOCK(release_agent_path_lock);
87 #define cgroup_assert_mutex_or_rcu_locked() \
88 rcu_lockdep_assert(rcu_read_lock_held() || \
89 lockdep_is_held(&cgroup_mutex), \
90 "cgroup_mutex or RCU read lock required");
93 * cgroup destruction makes heavy use of work items and there can be a lot
94 * of concurrent destructions. Use a separate workqueue so that cgroup
95 * destruction work items don't end up filling up max_active of system_wq
96 * which may lead to deadlock.
98 static struct workqueue_struct *cgroup_destroy_wq;
101 * pidlist destructions need to be flushed on cgroup destruction. Use a
102 * separate workqueue as flush domain.
104 static struct workqueue_struct *cgroup_pidlist_destroy_wq;
106 /* generate an array of cgroup subsystem pointers */
107 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
108 static struct cgroup_subsys *cgroup_subsys[] = {
109 #include <linux/cgroup_subsys.h>
113 /* array of cgroup subsystem names */
114 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
115 static const char *cgroup_subsys_name[] = {
116 #include <linux/cgroup_subsys.h>
121 * The dummy hierarchy, reserved for the subsystems that are otherwise
122 * unattached - it never has more than a single cgroup, and all tasks are
123 * part of that cgroup.
125 static struct cgroupfs_root cgroup_dummy_root;
127 /* dummy_top is a shorthand for the dummy hierarchy's top cgroup */
128 static struct cgroup * const cgroup_dummy_top = &cgroup_dummy_root.top_cgroup;
130 /* The list of hierarchy roots */
132 static LIST_HEAD(cgroup_roots);
133 static int cgroup_root_count;
135 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
136 static DEFINE_IDR(cgroup_hierarchy_idr);
138 static struct cgroup_name root_cgroup_name = { .name = "/" };
141 * Assign a monotonically increasing serial number to cgroups. It
142 * guarantees cgroups with bigger numbers are newer than those with smaller
143 * numbers. Also, as cgroups are always appended to the parent's
144 * ->children list, it guarantees that sibling cgroups are always sorted in
145 * the ascending serial number order on the list. Protected by
148 static u64 cgroup_serial_nr_next = 1;
150 /* This flag indicates whether tasks in the fork and exit paths should
151 * check for fork/exit handlers to call. This avoids us having to do
152 * extra work in the fork/exit path if none of the subsystems need to
155 static int need_forkexit_callback __read_mostly;
157 static struct cftype cgroup_base_files[];
159 static void cgroup_destroy_css_killed(struct cgroup *cgrp);
160 static int cgroup_destroy_locked(struct cgroup *cgrp);
161 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
163 static int cgroup_file_release(struct inode *inode, struct file *file);
164 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp);
167 * cgroup_css - obtain a cgroup's css for the specified subsystem
168 * @cgrp: the cgroup of interest
169 * @ss: the subsystem of interest (%NULL returns the dummy_css)
171 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
172 * function must be called either under cgroup_mutex or rcu_read_lock() and
173 * the caller is responsible for pinning the returned css if it wants to
174 * keep accessing it outside the said locks. This function may return
175 * %NULL if @cgrp doesn't have @subsys_id enabled.
177 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
178 struct cgroup_subsys *ss)
181 return rcu_dereference_check(cgrp->subsys[ss->id],
182 lockdep_is_held(&cgroup_mutex));
184 return &cgrp->dummy_css;
187 /* convenient tests for these bits */
188 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
190 return test_bit(CGRP_DEAD, &cgrp->flags);
194 * cgroup_is_descendant - test ancestry
195 * @cgrp: the cgroup to be tested
196 * @ancestor: possible ancestor of @cgrp
198 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
199 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
200 * and @ancestor are accessible.
202 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
205 if (cgrp == ancestor)
211 EXPORT_SYMBOL_GPL(cgroup_is_descendant);
213 static int cgroup_is_releasable(const struct cgroup *cgrp)
216 (1 << CGRP_RELEASABLE) |
217 (1 << CGRP_NOTIFY_ON_RELEASE);
218 return (cgrp->flags & bits) == bits;
221 static int notify_on_release(const struct cgroup *cgrp)
223 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
227 * for_each_css - iterate all css's of a cgroup
228 * @css: the iteration cursor
229 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
230 * @cgrp: the target cgroup to iterate css's of
232 * Should be called under cgroup_mutex.
234 #define for_each_css(css, ssid, cgrp) \
235 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
236 if (!((css) = rcu_dereference_check( \
237 (cgrp)->subsys[(ssid)], \
238 lockdep_is_held(&cgroup_mutex)))) { } \
242 * for_each_subsys - iterate all enabled cgroup subsystems
243 * @ss: the iteration cursor
244 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
246 #define for_each_subsys(ss, ssid) \
247 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT && \
248 (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
250 /* iterate across the active hierarchies */
251 #define for_each_active_root(root) \
252 list_for_each_entry((root), &cgroup_roots, root_list)
254 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
256 return dentry->d_fsdata;
259 static inline struct cfent *__d_cfe(struct dentry *dentry)
261 return dentry->d_fsdata;
264 static inline struct cftype *__d_cft(struct dentry *dentry)
266 return __d_cfe(dentry)->type;
270 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
271 * @cgrp: the cgroup to be checked for liveness
273 * On success, returns true; the mutex should be later unlocked. On
274 * failure returns false with no lock held.
276 static bool cgroup_lock_live_group(struct cgroup *cgrp)
278 mutex_lock(&cgroup_mutex);
279 if (cgroup_is_dead(cgrp)) {
280 mutex_unlock(&cgroup_mutex);
286 /* the list of cgroups eligible for automatic release. Protected by
287 * release_list_lock */
288 static LIST_HEAD(release_list);
289 static DEFINE_RAW_SPINLOCK(release_list_lock);
290 static void cgroup_release_agent(struct work_struct *work);
291 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
292 static void check_for_release(struct cgroup *cgrp);
295 * A cgroup can be associated with multiple css_sets as different tasks may
296 * belong to different cgroups on different hierarchies. In the other
297 * direction, a css_set is naturally associated with multiple cgroups.
298 * This M:N relationship is represented by the following link structure
299 * which exists for each association and allows traversing the associations
302 struct cgrp_cset_link {
303 /* the cgroup and css_set this link associates */
305 struct css_set *cset;
307 /* list of cgrp_cset_links anchored at cgrp->cset_links */
308 struct list_head cset_link;
310 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
311 struct list_head cgrp_link;
314 /* The default css_set - used by init and its children prior to any
315 * hierarchies being mounted. It contains a pointer to the root state
316 * for each subsystem. Also used to anchor the list of css_sets. Not
317 * reference-counted, to improve performance when child cgroups
318 * haven't been created.
321 static struct css_set init_css_set;
322 static struct cgrp_cset_link init_cgrp_cset_link;
325 * css_set_lock protects the list of css_set objects, and the chain of
326 * tasks off each css_set. Nests outside task->alloc_lock due to
327 * css_task_iter_start().
329 static DEFINE_RWLOCK(css_set_lock);
330 static int css_set_count;
333 * hash table for cgroup groups. This improves the performance to find
334 * an existing css_set. This hash doesn't (currently) take into
335 * account cgroups in empty hierarchies.
337 #define CSS_SET_HASH_BITS 7
338 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
340 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
342 unsigned long key = 0UL;
343 struct cgroup_subsys *ss;
346 for_each_subsys(ss, i)
347 key += (unsigned long)css[i];
348 key = (key >> 16) ^ key;
354 * We don't maintain the lists running through each css_set to its task
355 * until after the first call to css_task_iter_start(). This reduces the
356 * fork()/exit() overhead for people who have cgroups compiled into their
357 * kernel but not actually in use.
359 static int use_task_css_set_links __read_mostly;
361 static void __put_css_set(struct css_set *cset, int taskexit)
363 struct cgrp_cset_link *link, *tmp_link;
366 * Ensure that the refcount doesn't hit zero while any readers
367 * can see it. Similar to atomic_dec_and_lock(), but for an
370 if (atomic_add_unless(&cset->refcount, -1, 1))
372 write_lock(&css_set_lock);
373 if (!atomic_dec_and_test(&cset->refcount)) {
374 write_unlock(&css_set_lock);
378 /* This css_set is dead. unlink it and release cgroup refcounts */
379 hash_del(&cset->hlist);
382 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
383 struct cgroup *cgrp = link->cgrp;
385 list_del(&link->cset_link);
386 list_del(&link->cgrp_link);
388 /* @cgrp can't go away while we're holding css_set_lock */
389 if (list_empty(&cgrp->cset_links) && notify_on_release(cgrp)) {
391 set_bit(CGRP_RELEASABLE, &cgrp->flags);
392 check_for_release(cgrp);
398 write_unlock(&css_set_lock);
399 kfree_rcu(cset, rcu_head);
403 * refcounted get/put for css_set objects
405 static inline void get_css_set(struct css_set *cset)
407 atomic_inc(&cset->refcount);
410 static inline void put_css_set(struct css_set *cset)
412 __put_css_set(cset, 0);
415 static inline void put_css_set_taskexit(struct css_set *cset)
417 __put_css_set(cset, 1);
421 * compare_css_sets - helper function for find_existing_css_set().
422 * @cset: candidate css_set being tested
423 * @old_cset: existing css_set for a task
424 * @new_cgrp: cgroup that's being entered by the task
425 * @template: desired set of css pointers in css_set (pre-calculated)
427 * Returns true if "cset" matches "old_cset" except for the hierarchy
428 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
430 static bool compare_css_sets(struct css_set *cset,
431 struct css_set *old_cset,
432 struct cgroup *new_cgrp,
433 struct cgroup_subsys_state *template[])
435 struct list_head *l1, *l2;
437 if (memcmp(template, cset->subsys, sizeof(cset->subsys))) {
438 /* Not all subsystems matched */
443 * Compare cgroup pointers in order to distinguish between
444 * different cgroups in heirarchies with no subsystems. We
445 * could get by with just this check alone (and skip the
446 * memcmp above) but on most setups the memcmp check will
447 * avoid the need for this more expensive check on almost all
451 l1 = &cset->cgrp_links;
452 l2 = &old_cset->cgrp_links;
454 struct cgrp_cset_link *link1, *link2;
455 struct cgroup *cgrp1, *cgrp2;
459 /* See if we reached the end - both lists are equal length. */
460 if (l1 == &cset->cgrp_links) {
461 BUG_ON(l2 != &old_cset->cgrp_links);
464 BUG_ON(l2 == &old_cset->cgrp_links);
466 /* Locate the cgroups associated with these links. */
467 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
468 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
471 /* Hierarchies should be linked in the same order. */
472 BUG_ON(cgrp1->root != cgrp2->root);
475 * If this hierarchy is the hierarchy of the cgroup
476 * that's changing, then we need to check that this
477 * css_set points to the new cgroup; if it's any other
478 * hierarchy, then this css_set should point to the
479 * same cgroup as the old css_set.
481 if (cgrp1->root == new_cgrp->root) {
482 if (cgrp1 != new_cgrp)
493 * find_existing_css_set - init css array and find the matching css_set
494 * @old_cset: the css_set that we're using before the cgroup transition
495 * @cgrp: the cgroup that we're moving into
496 * @template: out param for the new set of csses, should be clear on entry
498 static struct css_set *find_existing_css_set(struct css_set *old_cset,
500 struct cgroup_subsys_state *template[])
502 struct cgroupfs_root *root = cgrp->root;
503 struct cgroup_subsys *ss;
504 struct css_set *cset;
509 * Build the set of subsystem state objects that we want to see in the
510 * new css_set. while subsystems can change globally, the entries here
511 * won't change, so no need for locking.
513 for_each_subsys(ss, i) {
514 if (root->subsys_mask & (1UL << i)) {
515 /* Subsystem is in this hierarchy. So we want
516 * the subsystem state from the new
518 template[i] = cgroup_css(cgrp, ss);
520 /* Subsystem is not in this hierarchy, so we
521 * don't want to change the subsystem state */
522 template[i] = old_cset->subsys[i];
526 key = css_set_hash(template);
527 hash_for_each_possible(css_set_table, cset, hlist, key) {
528 if (!compare_css_sets(cset, old_cset, cgrp, template))
531 /* This css_set matches what we need */
535 /* No existing cgroup group matched */
539 static void free_cgrp_cset_links(struct list_head *links_to_free)
541 struct cgrp_cset_link *link, *tmp_link;
543 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
544 list_del(&link->cset_link);
550 * allocate_cgrp_cset_links - allocate cgrp_cset_links
551 * @count: the number of links to allocate
552 * @tmp_links: list_head the allocated links are put on
554 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
555 * through ->cset_link. Returns 0 on success or -errno.
557 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
559 struct cgrp_cset_link *link;
562 INIT_LIST_HEAD(tmp_links);
564 for (i = 0; i < count; i++) {
565 link = kzalloc(sizeof(*link), GFP_KERNEL);
567 free_cgrp_cset_links(tmp_links);
570 list_add(&link->cset_link, tmp_links);
576 * link_css_set - a helper function to link a css_set to a cgroup
577 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
578 * @cset: the css_set to be linked
579 * @cgrp: the destination cgroup
581 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
584 struct cgrp_cset_link *link;
586 BUG_ON(list_empty(tmp_links));
587 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
590 list_move(&link->cset_link, &cgrp->cset_links);
592 * Always add links to the tail of the list so that the list
593 * is sorted by order of hierarchy creation
595 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
599 * find_css_set - return a new css_set with one cgroup updated
600 * @old_cset: the baseline css_set
601 * @cgrp: the cgroup to be updated
603 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
604 * substituted into the appropriate hierarchy.
606 static struct css_set *find_css_set(struct css_set *old_cset,
609 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
610 struct css_set *cset;
611 struct list_head tmp_links;
612 struct cgrp_cset_link *link;
615 lockdep_assert_held(&cgroup_mutex);
617 /* First see if we already have a cgroup group that matches
619 read_lock(&css_set_lock);
620 cset = find_existing_css_set(old_cset, cgrp, template);
623 read_unlock(&css_set_lock);
628 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
632 /* Allocate all the cgrp_cset_link objects that we'll need */
633 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
638 atomic_set(&cset->refcount, 1);
639 INIT_LIST_HEAD(&cset->cgrp_links);
640 INIT_LIST_HEAD(&cset->tasks);
641 INIT_HLIST_NODE(&cset->hlist);
643 /* Copy the set of subsystem state objects generated in
644 * find_existing_css_set() */
645 memcpy(cset->subsys, template, sizeof(cset->subsys));
647 write_lock(&css_set_lock);
648 /* Add reference counts and links from the new css_set. */
649 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
650 struct cgroup *c = link->cgrp;
652 if (c->root == cgrp->root)
654 link_css_set(&tmp_links, cset, c);
657 BUG_ON(!list_empty(&tmp_links));
661 /* Add this cgroup group to the hash table */
662 key = css_set_hash(cset->subsys);
663 hash_add(css_set_table, &cset->hlist, key);
665 write_unlock(&css_set_lock);
671 * Return the cgroup for "task" from the given hierarchy. Must be
672 * called with cgroup_mutex held.
674 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
675 struct cgroupfs_root *root)
677 struct css_set *cset;
678 struct cgroup *res = NULL;
680 BUG_ON(!mutex_is_locked(&cgroup_mutex));
681 read_lock(&css_set_lock);
683 * No need to lock the task - since we hold cgroup_mutex the
684 * task can't change groups, so the only thing that can happen
685 * is that it exits and its css is set back to init_css_set.
687 cset = task_css_set(task);
688 if (cset == &init_css_set) {
689 res = &root->top_cgroup;
691 struct cgrp_cset_link *link;
693 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
694 struct cgroup *c = link->cgrp;
696 if (c->root == root) {
702 read_unlock(&css_set_lock);
708 * There is one global cgroup mutex. We also require taking
709 * task_lock() when dereferencing a task's cgroup subsys pointers.
710 * See "The task_lock() exception", at the end of this comment.
712 * A task must hold cgroup_mutex to modify cgroups.
714 * Any task can increment and decrement the count field without lock.
715 * So in general, code holding cgroup_mutex can't rely on the count
716 * field not changing. However, if the count goes to zero, then only
717 * cgroup_attach_task() can increment it again. Because a count of zero
718 * means that no tasks are currently attached, therefore there is no
719 * way a task attached to that cgroup can fork (the other way to
720 * increment the count). So code holding cgroup_mutex can safely
721 * assume that if the count is zero, it will stay zero. Similarly, if
722 * a task holds cgroup_mutex on a cgroup with zero count, it
723 * knows that the cgroup won't be removed, as cgroup_rmdir()
726 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
727 * (usually) take cgroup_mutex. These are the two most performance
728 * critical pieces of code here. The exception occurs on cgroup_exit(),
729 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
730 * is taken, and if the cgroup count is zero, a usermode call made
731 * to the release agent with the name of the cgroup (path relative to
732 * the root of cgroup file system) as the argument.
734 * A cgroup can only be deleted if both its 'count' of using tasks
735 * is zero, and its list of 'children' cgroups is empty. Since all
736 * tasks in the system use _some_ cgroup, and since there is always at
737 * least one task in the system (init, pid == 1), therefore, top_cgroup
738 * always has either children cgroups and/or using tasks. So we don't
739 * need a special hack to ensure that top_cgroup cannot be deleted.
741 * The task_lock() exception
743 * The need for this exception arises from the action of
744 * cgroup_attach_task(), which overwrites one task's cgroup pointer with
745 * another. It does so using cgroup_mutex, however there are
746 * several performance critical places that need to reference
747 * task->cgroup without the expense of grabbing a system global
748 * mutex. Therefore except as noted below, when dereferencing or, as
749 * in cgroup_attach_task(), modifying a task's cgroup pointer we use
750 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
751 * the task_struct routinely used for such matters.
753 * P.S. One more locking exception. RCU is used to guard the
754 * update of a tasks cgroup pointer by cgroup_attach_task()
758 * A couple of forward declarations required, due to cyclic reference loop:
759 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
760 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
764 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode);
765 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
766 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask);
767 static const struct inode_operations cgroup_dir_inode_operations;
768 static const struct file_operations proc_cgroupstats_operations;
770 static struct backing_dev_info cgroup_backing_dev_info = {
772 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
775 static struct inode *cgroup_new_inode(umode_t mode, struct super_block *sb)
777 struct inode *inode = new_inode(sb);
780 inode->i_ino = get_next_ino();
781 inode->i_mode = mode;
782 inode->i_uid = current_fsuid();
783 inode->i_gid = current_fsgid();
784 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
785 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
790 static struct cgroup_name *cgroup_alloc_name(struct dentry *dentry)
792 struct cgroup_name *name;
794 name = kmalloc(sizeof(*name) + dentry->d_name.len + 1, GFP_KERNEL);
797 strcpy(name->name, dentry->d_name.name);
801 static void cgroup_free_fn(struct work_struct *work)
803 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
805 mutex_lock(&cgroup_mutex);
806 cgrp->root->number_of_cgroups--;
807 mutex_unlock(&cgroup_mutex);
810 * We get a ref to the parent's dentry, and put the ref when
811 * this cgroup is being freed, so it's guaranteed that the
812 * parent won't be destroyed before its children.
814 dput(cgrp->parent->dentry);
817 * Drop the active superblock reference that we took when we
818 * created the cgroup. This will free cgrp->root, if we are
819 * holding the last reference to @sb.
821 deactivate_super(cgrp->root->sb);
823 cgroup_pidlist_destroy_all(cgrp);
825 simple_xattrs_free(&cgrp->xattrs);
827 kfree(rcu_dereference_raw(cgrp->name));
831 static void cgroup_free_rcu(struct rcu_head *head)
833 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
835 INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
836 queue_work(cgroup_destroy_wq, &cgrp->destroy_work);
839 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
841 /* is dentry a directory ? if so, kfree() associated cgroup */
842 if (S_ISDIR(inode->i_mode)) {
843 struct cgroup *cgrp = dentry->d_fsdata;
845 BUG_ON(!(cgroup_is_dead(cgrp)));
848 * XXX: cgrp->id is only used to look up css's. As cgroup
849 * and css's lifetimes will be decoupled, it should be made
850 * per-subsystem and moved to css->id so that lookups are
851 * successful until the target css is released.
853 idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
856 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
858 struct cfent *cfe = __d_cfe(dentry);
859 struct cgroup *cgrp = dentry->d_parent->d_fsdata;
861 WARN_ONCE(!list_empty(&cfe->node) &&
862 cgrp != &cgrp->root->top_cgroup,
863 "cfe still linked for %s\n", cfe->type->name);
864 simple_xattrs_free(&cfe->xattrs);
870 static void remove_dir(struct dentry *d)
872 struct dentry *parent = dget(d->d_parent);
875 simple_rmdir(parent->d_inode, d);
879 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
883 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
884 lockdep_assert_held(&cgroup_mutex);
887 * If we're doing cleanup due to failure of cgroup_create(),
888 * the corresponding @cfe may not exist.
890 list_for_each_entry(cfe, &cgrp->files, node) {
891 struct dentry *d = cfe->dentry;
893 if (cft && cfe->type != cft)
898 simple_unlink(cgrp->dentry->d_inode, d);
899 list_del_init(&cfe->node);
907 * cgroup_clear_dir - remove subsys files in a cgroup directory
908 * @cgrp: target cgroup
909 * @subsys_mask: mask of the subsystem ids whose files should be removed
911 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned long subsys_mask)
913 struct cgroup_subsys *ss;
916 for_each_subsys(ss, i) {
917 struct cftype_set *set;
919 if (!test_bit(i, &subsys_mask))
921 list_for_each_entry(set, &ss->cftsets, node)
922 cgroup_addrm_files(cgrp, set->cfts, false);
927 * NOTE : the dentry must have been dget()'ed
929 static void cgroup_d_remove_dir(struct dentry *dentry)
931 struct dentry *parent;
933 parent = dentry->d_parent;
934 spin_lock(&parent->d_lock);
935 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
936 list_del_init(&dentry->d_u.d_child);
937 spin_unlock(&dentry->d_lock);
938 spin_unlock(&parent->d_lock);
942 static int rebind_subsystems(struct cgroupfs_root *root,
943 unsigned long added_mask, unsigned removed_mask)
945 struct cgroup *cgrp = &root->top_cgroup;
946 struct cgroup_subsys *ss;
949 BUG_ON(!mutex_is_locked(&cgroup_mutex));
951 /* Check that any added subsystems are currently free */
952 for_each_subsys(ss, i)
953 if ((added_mask & (1 << i)) && ss->root != &cgroup_dummy_root)
956 ret = cgroup_populate_dir(cgrp, added_mask);
961 * Nothing can fail from this point on. Remove files for the
962 * removed subsystems and rebind each subsystem.
964 cgroup_clear_dir(cgrp, removed_mask);
966 for_each_subsys(ss, i) {
967 unsigned long bit = 1UL << i;
969 if (bit & added_mask) {
970 /* We're binding this subsystem to this hierarchy */
971 BUG_ON(cgroup_css(cgrp, ss));
972 BUG_ON(!cgroup_css(cgroup_dummy_top, ss));
973 BUG_ON(cgroup_css(cgroup_dummy_top, ss)->cgroup != cgroup_dummy_top);
975 rcu_assign_pointer(cgrp->subsys[i],
976 cgroup_css(cgroup_dummy_top, ss));
977 cgroup_css(cgrp, ss)->cgroup = cgrp;
981 ss->bind(cgroup_css(cgrp, ss));
983 /* refcount was already taken, and we're keeping it */
984 root->subsys_mask |= bit;
985 } else if (bit & removed_mask) {
986 /* We're removing this subsystem */
987 BUG_ON(cgroup_css(cgrp, ss) != cgroup_css(cgroup_dummy_top, ss));
988 BUG_ON(cgroup_css(cgrp, ss)->cgroup != cgrp);
991 ss->bind(cgroup_css(cgroup_dummy_top, ss));
993 cgroup_css(cgroup_dummy_top, ss)->cgroup = cgroup_dummy_top;
994 RCU_INIT_POINTER(cgrp->subsys[i], NULL);
996 cgroup_subsys[i]->root = &cgroup_dummy_root;
997 root->subsys_mask &= ~bit;
1002 * Mark @root has finished binding subsystems. @root->subsys_mask
1003 * now matches the bound subsystems.
1005 root->flags |= CGRP_ROOT_SUBSYS_BOUND;
1010 static int cgroup_show_options(struct seq_file *seq, struct dentry *dentry)
1012 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
1013 struct cgroup_subsys *ss;
1016 for_each_subsys(ss, ssid)
1017 if (root->subsys_mask & (1 << ssid))
1018 seq_printf(seq, ",%s", ss->name);
1019 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1020 seq_puts(seq, ",sane_behavior");
1021 if (root->flags & CGRP_ROOT_NOPREFIX)
1022 seq_puts(seq, ",noprefix");
1023 if (root->flags & CGRP_ROOT_XATTR)
1024 seq_puts(seq, ",xattr");
1026 spin_lock(&release_agent_path_lock);
1027 if (strlen(root->release_agent_path))
1028 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1029 spin_unlock(&release_agent_path_lock);
1031 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1032 seq_puts(seq, ",clone_children");
1033 if (strlen(root->name))
1034 seq_printf(seq, ",name=%s", root->name);
1038 struct cgroup_sb_opts {
1039 unsigned long subsys_mask;
1040 unsigned long flags;
1041 char *release_agent;
1042 bool cpuset_clone_children;
1044 /* User explicitly requested empty subsystem */
1047 struct cgroupfs_root *new_root;
1052 * Convert a hierarchy specifier into a bitmask of subsystems and
1053 * flags. Call with cgroup_mutex held to protect the cgroup_subsys[]
1054 * array. This function takes refcounts on subsystems to be used, unless it
1055 * returns error, in which case no refcounts are taken.
1057 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1059 char *token, *o = data;
1060 bool all_ss = false, one_ss = false;
1061 unsigned long mask = (unsigned long)-1;
1062 struct cgroup_subsys *ss;
1065 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1067 #ifdef CONFIG_CPUSETS
1068 mask = ~(1UL << cpuset_cgrp_id);
1071 memset(opts, 0, sizeof(*opts));
1073 while ((token = strsep(&o, ",")) != NULL) {
1076 if (!strcmp(token, "none")) {
1077 /* Explicitly have no subsystems */
1081 if (!strcmp(token, "all")) {
1082 /* Mutually exclusive option 'all' + subsystem name */
1088 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1089 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1092 if (!strcmp(token, "noprefix")) {
1093 opts->flags |= CGRP_ROOT_NOPREFIX;
1096 if (!strcmp(token, "clone_children")) {
1097 opts->cpuset_clone_children = true;
1100 if (!strcmp(token, "xattr")) {
1101 opts->flags |= CGRP_ROOT_XATTR;
1104 if (!strncmp(token, "release_agent=", 14)) {
1105 /* Specifying two release agents is forbidden */
1106 if (opts->release_agent)
1108 opts->release_agent =
1109 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1110 if (!opts->release_agent)
1114 if (!strncmp(token, "name=", 5)) {
1115 const char *name = token + 5;
1116 /* Can't specify an empty name */
1119 /* Must match [\w.-]+ */
1120 for (i = 0; i < strlen(name); i++) {
1124 if ((c == '.') || (c == '-') || (c == '_'))
1128 /* Specifying two names is forbidden */
1131 opts->name = kstrndup(name,
1132 MAX_CGROUP_ROOT_NAMELEN - 1,
1140 for_each_subsys(ss, i) {
1141 if (strcmp(token, ss->name))
1146 /* Mutually exclusive option 'all' + subsystem name */
1149 set_bit(i, &opts->subsys_mask);
1154 if (i == CGROUP_SUBSYS_COUNT)
1159 * If the 'all' option was specified select all the subsystems,
1160 * otherwise if 'none', 'name=' and a subsystem name options
1161 * were not specified, let's default to 'all'
1163 if (all_ss || (!one_ss && !opts->none && !opts->name))
1164 for_each_subsys(ss, i)
1166 set_bit(i, &opts->subsys_mask);
1168 /* Consistency checks */
1170 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1171 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1173 if (opts->flags & CGRP_ROOT_NOPREFIX) {
1174 pr_err("cgroup: sane_behavior: noprefix is not allowed\n");
1178 if (opts->cpuset_clone_children) {
1179 pr_err("cgroup: sane_behavior: clone_children is not allowed\n");
1185 * Option noprefix was introduced just for backward compatibility
1186 * with the old cpuset, so we allow noprefix only if mounting just
1187 * the cpuset subsystem.
1189 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1193 /* Can't specify "none" and some subsystems */
1194 if (opts->subsys_mask && opts->none)
1198 * We either have to specify by name or by subsystems. (So all
1199 * empty hierarchies must have a name).
1201 if (!opts->subsys_mask && !opts->name)
1207 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1210 struct cgroupfs_root *root = sb->s_fs_info;
1211 struct cgroup *cgrp = &root->top_cgroup;
1212 struct cgroup_sb_opts opts;
1213 unsigned long added_mask, removed_mask;
1215 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1216 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1220 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1221 mutex_lock(&cgroup_mutex);
1223 /* See what subsystems are wanted */
1224 ret = parse_cgroupfs_options(data, &opts);
1228 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1229 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1230 task_tgid_nr(current), current->comm);
1232 added_mask = opts.subsys_mask & ~root->subsys_mask;
1233 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1235 /* Don't allow flags or name to change at remount */
1236 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1237 (opts.name && strcmp(opts.name, root->name))) {
1238 pr_err("cgroup: option or name mismatch, new: 0x%lx \"%s\", old: 0x%lx \"%s\"\n",
1239 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1240 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1245 /* remounting is not allowed for populated hierarchies */
1246 if (root->number_of_cgroups > 1) {
1251 ret = rebind_subsystems(root, added_mask, removed_mask);
1255 if (opts.release_agent) {
1256 spin_lock(&release_agent_path_lock);
1257 strcpy(root->release_agent_path, opts.release_agent);
1258 spin_unlock(&release_agent_path_lock);
1261 kfree(opts.release_agent);
1263 mutex_unlock(&cgroup_mutex);
1264 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1268 static const struct super_operations cgroup_ops = {
1269 .statfs = simple_statfs,
1270 .drop_inode = generic_delete_inode,
1271 .show_options = cgroup_show_options,
1272 .remount_fs = cgroup_remount,
1275 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1277 INIT_LIST_HEAD(&cgrp->sibling);
1278 INIT_LIST_HEAD(&cgrp->children);
1279 INIT_LIST_HEAD(&cgrp->files);
1280 INIT_LIST_HEAD(&cgrp->cset_links);
1281 INIT_LIST_HEAD(&cgrp->release_list);
1282 INIT_LIST_HEAD(&cgrp->pidlists);
1283 mutex_init(&cgrp->pidlist_mutex);
1284 cgrp->dummy_css.cgroup = cgrp;
1285 simple_xattrs_init(&cgrp->xattrs);
1288 static void init_cgroup_root(struct cgroupfs_root *root)
1290 struct cgroup *cgrp = &root->top_cgroup;
1292 INIT_LIST_HEAD(&root->root_list);
1293 root->number_of_cgroups = 1;
1295 RCU_INIT_POINTER(cgrp->name, &root_cgroup_name);
1296 init_cgroup_housekeeping(cgrp);
1297 idr_init(&root->cgroup_idr);
1300 static int cgroup_init_root_id(struct cgroupfs_root *root, int start, int end)
1304 lockdep_assert_held(&cgroup_mutex);
1306 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, start, end,
1311 root->hierarchy_id = id;
1315 static void cgroup_exit_root_id(struct cgroupfs_root *root)
1317 lockdep_assert_held(&cgroup_mutex);
1319 if (root->hierarchy_id) {
1320 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1321 root->hierarchy_id = 0;
1325 static int cgroup_test_super(struct super_block *sb, void *data)
1327 struct cgroup_sb_opts *opts = data;
1328 struct cgroupfs_root *root = sb->s_fs_info;
1330 /* If we asked for a name then it must match */
1331 if (opts->name && strcmp(opts->name, root->name))
1335 * If we asked for subsystems (or explicitly for no
1336 * subsystems) then they must match
1338 if ((opts->subsys_mask || opts->none)
1339 && (opts->subsys_mask != root->subsys_mask))
1345 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1347 struct cgroupfs_root *root;
1349 if (!opts->subsys_mask && !opts->none)
1352 root = kzalloc(sizeof(*root), GFP_KERNEL);
1354 return ERR_PTR(-ENOMEM);
1356 init_cgroup_root(root);
1359 * We need to set @root->subsys_mask now so that @root can be
1360 * matched by cgroup_test_super() before it finishes
1361 * initialization; otherwise, competing mounts with the same
1362 * options may try to bind the same subsystems instead of waiting
1363 * for the first one leading to unexpected mount errors.
1364 * SUBSYS_BOUND will be set once actual binding is complete.
1366 root->subsys_mask = opts->subsys_mask;
1367 root->flags = opts->flags;
1368 if (opts->release_agent)
1369 strcpy(root->release_agent_path, opts->release_agent);
1371 strcpy(root->name, opts->name);
1372 if (opts->cpuset_clone_children)
1373 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1377 static void cgroup_free_root(struct cgroupfs_root *root)
1380 /* hierarhcy ID shoulid already have been released */
1381 WARN_ON_ONCE(root->hierarchy_id);
1383 idr_destroy(&root->cgroup_idr);
1388 static int cgroup_set_super(struct super_block *sb, void *data)
1391 struct cgroup_sb_opts *opts = data;
1393 /* If we don't have a new root, we can't set up a new sb */
1394 if (!opts->new_root)
1397 BUG_ON(!opts->subsys_mask && !opts->none);
1399 ret = set_anon_super(sb, NULL);
1403 sb->s_fs_info = opts->new_root;
1404 opts->new_root->sb = sb;
1406 sb->s_blocksize = PAGE_CACHE_SIZE;
1407 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1408 sb->s_magic = CGROUP_SUPER_MAGIC;
1409 sb->s_op = &cgroup_ops;
1414 static int cgroup_get_rootdir(struct super_block *sb)
1416 static const struct dentry_operations cgroup_dops = {
1417 .d_iput = cgroup_diput,
1418 .d_delete = always_delete_dentry,
1421 struct inode *inode =
1422 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1427 inode->i_fop = &simple_dir_operations;
1428 inode->i_op = &cgroup_dir_inode_operations;
1429 /* directories start off with i_nlink == 2 (for "." entry) */
1431 sb->s_root = d_make_root(inode);
1434 /* for everything else we want ->d_op set */
1435 sb->s_d_op = &cgroup_dops;
1439 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1440 int flags, const char *unused_dev_name,
1443 struct cgroup_sb_opts opts;
1444 struct cgroupfs_root *root;
1446 struct super_block *sb;
1447 struct cgroupfs_root *new_root;
1448 struct list_head tmp_links;
1449 struct inode *inode;
1450 const struct cred *cred;
1452 /* First find the desired set of subsystems */
1453 mutex_lock(&cgroup_mutex);
1454 ret = parse_cgroupfs_options(data, &opts);
1455 mutex_unlock(&cgroup_mutex);
1460 * Allocate a new cgroup root. We may not need it if we're
1461 * reusing an existing hierarchy.
1463 new_root = cgroup_root_from_opts(&opts);
1464 if (IS_ERR(new_root)) {
1465 ret = PTR_ERR(new_root);
1468 opts.new_root = new_root;
1470 /* Locate an existing or new sb for this hierarchy */
1471 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1474 cgroup_free_root(opts.new_root);
1478 root = sb->s_fs_info;
1480 if (root == opts.new_root) {
1481 /* We used the new root structure, so this is a new hierarchy */
1482 struct cgroup *root_cgrp = &root->top_cgroup;
1483 struct cgroupfs_root *existing_root;
1485 struct css_set *cset;
1487 BUG_ON(sb->s_root != NULL);
1489 ret = cgroup_get_rootdir(sb);
1491 goto drop_new_super;
1492 inode = sb->s_root->d_inode;
1494 mutex_lock(&inode->i_mutex);
1495 mutex_lock(&cgroup_mutex);
1497 ret = idr_alloc(&root->cgroup_idr, root_cgrp, 0, 1, GFP_KERNEL);
1500 root_cgrp->id = ret;
1502 /* Check for name clashes with existing mounts */
1504 if (strlen(root->name))
1505 for_each_active_root(existing_root)
1506 if (!strcmp(existing_root->name, root->name))
1510 * We're accessing css_set_count without locking
1511 * css_set_lock here, but that's OK - it can only be
1512 * increased by someone holding cgroup_lock, and
1513 * that's us. The worst that can happen is that we
1514 * have some link structures left over
1516 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1520 /* ID 0 is reserved for dummy root, 1 for unified hierarchy */
1521 ret = cgroup_init_root_id(root, 2, 0);
1525 sb->s_root->d_fsdata = root_cgrp;
1526 root_cgrp->dentry = sb->s_root;
1529 * We're inside get_sb() and will call lookup_one_len() to
1530 * create the root files, which doesn't work if SELinux is
1531 * in use. The following cred dancing somehow works around
1532 * it. See 2ce9738ba ("cgroupfs: use init_cred when
1533 * populating new cgroupfs mount") for more details.
1535 cred = override_creds(&init_cred);
1537 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1541 ret = rebind_subsystems(root, root->subsys_mask, 0);
1548 * There must be no failure case after here, since rebinding
1549 * takes care of subsystems' refcounts, which are explicitly
1550 * dropped in the failure exit path.
1553 list_add(&root->root_list, &cgroup_roots);
1554 cgroup_root_count++;
1556 /* Link the top cgroup in this hierarchy into all
1557 * the css_set objects */
1558 write_lock(&css_set_lock);
1559 hash_for_each(css_set_table, i, cset, hlist)
1560 link_css_set(&tmp_links, cset, root_cgrp);
1561 write_unlock(&css_set_lock);
1563 free_cgrp_cset_links(&tmp_links);
1565 BUG_ON(!list_empty(&root_cgrp->children));
1566 BUG_ON(root->number_of_cgroups != 1);
1568 mutex_unlock(&cgroup_mutex);
1569 mutex_unlock(&inode->i_mutex);
1572 * We re-used an existing hierarchy - the new root (if
1573 * any) is not needed
1575 cgroup_free_root(opts.new_root);
1577 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1578 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1579 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1581 goto drop_new_super;
1583 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1588 kfree(opts.release_agent);
1590 return dget(sb->s_root);
1593 free_cgrp_cset_links(&tmp_links);
1594 cgroup_addrm_files(&root->top_cgroup, cgroup_base_files, false);
1597 cgroup_exit_root_id(root);
1598 mutex_unlock(&cgroup_mutex);
1599 mutex_unlock(&inode->i_mutex);
1601 deactivate_locked_super(sb);
1603 kfree(opts.release_agent);
1605 return ERR_PTR(ret);
1608 static void cgroup_kill_sb(struct super_block *sb)
1610 struct cgroupfs_root *root = sb->s_fs_info;
1611 struct cgroup *cgrp = &root->top_cgroup;
1612 struct cgrp_cset_link *link, *tmp_link;
1617 BUG_ON(root->number_of_cgroups != 1);
1618 BUG_ON(!list_empty(&cgrp->children));
1620 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1621 mutex_lock(&cgroup_mutex);
1623 /* Rebind all subsystems back to the default hierarchy */
1624 if (root->flags & CGRP_ROOT_SUBSYS_BOUND) {
1625 ret = rebind_subsystems(root, 0, root->subsys_mask);
1626 /* Shouldn't be able to fail ... */
1631 * Release all the links from cset_links to this hierarchy's
1634 write_lock(&css_set_lock);
1636 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1637 list_del(&link->cset_link);
1638 list_del(&link->cgrp_link);
1641 write_unlock(&css_set_lock);
1643 if (!list_empty(&root->root_list)) {
1644 list_del(&root->root_list);
1645 cgroup_root_count--;
1648 cgroup_exit_root_id(root);
1650 mutex_unlock(&cgroup_mutex);
1651 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1653 simple_xattrs_free(&cgrp->xattrs);
1655 kill_litter_super(sb);
1656 cgroup_free_root(root);
1659 static struct file_system_type cgroup_fs_type = {
1661 .mount = cgroup_mount,
1662 .kill_sb = cgroup_kill_sb,
1665 static struct kobject *cgroup_kobj;
1668 * cgroup_path - generate the path of a cgroup
1669 * @cgrp: the cgroup in question
1670 * @buf: the buffer to write the path into
1671 * @buflen: the length of the buffer
1673 * Writes path of cgroup into buf. Returns 0 on success, -errno on error.
1675 * We can't generate cgroup path using dentry->d_name, as accessing
1676 * dentry->name must be protected by irq-unsafe dentry->d_lock or parent
1677 * inode's i_mutex, while on the other hand cgroup_path() can be called
1678 * with some irq-safe spinlocks held.
1680 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1682 int ret = -ENAMETOOLONG;
1685 if (!cgrp->parent) {
1686 if (strlcpy(buf, "/", buflen) >= buflen)
1687 return -ENAMETOOLONG;
1691 start = buf + buflen - 1;
1696 const char *name = cgroup_name(cgrp);
1700 if ((start -= len) < buf)
1702 memcpy(start, name, len);
1708 cgrp = cgrp->parent;
1709 } while (cgrp->parent);
1711 memmove(buf, start, buf + buflen - start);
1716 EXPORT_SYMBOL_GPL(cgroup_path);
1719 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1720 * @task: target task
1721 * @buf: the buffer to write the path into
1722 * @buflen: the length of the buffer
1724 * Determine @task's cgroup on the first (the one with the lowest non-zero
1725 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1726 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1727 * cgroup controller callbacks.
1729 * Returns 0 on success, fails with -%ENAMETOOLONG if @buflen is too short.
1731 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1733 struct cgroupfs_root *root;
1734 struct cgroup *cgrp;
1735 int hierarchy_id = 1, ret = 0;
1738 return -ENAMETOOLONG;
1740 mutex_lock(&cgroup_mutex);
1742 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1745 cgrp = task_cgroup_from_root(task, root);
1746 ret = cgroup_path(cgrp, buf, buflen);
1748 /* if no hierarchy exists, everyone is in "/" */
1749 memcpy(buf, "/", 2);
1752 mutex_unlock(&cgroup_mutex);
1755 EXPORT_SYMBOL_GPL(task_cgroup_path);
1758 * Control Group taskset
1760 struct task_and_cgroup {
1761 struct task_struct *task;
1762 struct cgroup *cgrp;
1763 struct css_set *cset;
1766 struct cgroup_taskset {
1767 struct task_and_cgroup single;
1768 struct flex_array *tc_array;
1771 struct cgroup *cur_cgrp;
1775 * cgroup_taskset_first - reset taskset and return the first task
1776 * @tset: taskset of interest
1778 * @tset iteration is initialized and the first task is returned.
1780 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1782 if (tset->tc_array) {
1784 return cgroup_taskset_next(tset);
1786 tset->cur_cgrp = tset->single.cgrp;
1787 return tset->single.task;
1790 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1793 * cgroup_taskset_next - iterate to the next task in taskset
1794 * @tset: taskset of interest
1796 * Return the next task in @tset. Iteration must have been initialized
1797 * with cgroup_taskset_first().
1799 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1801 struct task_and_cgroup *tc;
1803 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1806 tc = flex_array_get(tset->tc_array, tset->idx++);
1807 tset->cur_cgrp = tc->cgrp;
1810 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1813 * cgroup_taskset_cur_css - return the matching css for the current task
1814 * @tset: taskset of interest
1815 * @subsys_id: the ID of the target subsystem
1817 * Return the css for the current (last returned) task of @tset for
1818 * subsystem specified by @subsys_id. This function must be preceded by
1819 * either cgroup_taskset_first() or cgroup_taskset_next().
1821 struct cgroup_subsys_state *cgroup_taskset_cur_css(struct cgroup_taskset *tset,
1824 return cgroup_css(tset->cur_cgrp, cgroup_subsys[subsys_id]);
1826 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_css);
1829 * cgroup_taskset_size - return the number of tasks in taskset
1830 * @tset: taskset of interest
1832 int cgroup_taskset_size(struct cgroup_taskset *tset)
1834 return tset->tc_array ? tset->tc_array_len : 1;
1836 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1840 * cgroup_task_migrate - move a task from one cgroup to another.
1842 * Must be called with cgroup_mutex and threadgroup locked.
1844 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1845 struct task_struct *tsk,
1846 struct css_set *new_cset)
1848 struct css_set *old_cset;
1851 * We are synchronized through threadgroup_lock() against PF_EXITING
1852 * setting such that we can't race against cgroup_exit() changing the
1853 * css_set to init_css_set and dropping the old one.
1855 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1856 old_cset = task_css_set(tsk);
1859 rcu_assign_pointer(tsk->cgroups, new_cset);
1862 /* Update the css_set linked lists if we're using them */
1863 write_lock(&css_set_lock);
1864 if (!list_empty(&tsk->cg_list))
1865 list_move(&tsk->cg_list, &new_cset->tasks);
1866 write_unlock(&css_set_lock);
1869 * We just gained a reference on old_cset by taking it from the
1870 * task. As trading it for new_cset is protected by cgroup_mutex,
1871 * we're safe to drop it here; it will be freed under RCU.
1873 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1874 put_css_set(old_cset);
1878 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1879 * @cgrp: the cgroup to attach to
1880 * @tsk: the task or the leader of the threadgroup to be attached
1881 * @threadgroup: attach the whole threadgroup?
1883 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
1884 * task_lock of @tsk or each thread in the threadgroup individually in turn.
1886 static int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk,
1889 int retval, i, group_size;
1890 struct cgroupfs_root *root = cgrp->root;
1891 struct cgroup_subsys_state *css, *failed_css = NULL;
1892 /* threadgroup list cursor and array */
1893 struct task_struct *leader = tsk;
1894 struct task_and_cgroup *tc;
1895 struct flex_array *group;
1896 struct cgroup_taskset tset = { };
1899 * step 0: in order to do expensive, possibly blocking operations for
1900 * every thread, we cannot iterate the thread group list, since it needs
1901 * rcu or tasklist locked. instead, build an array of all threads in the
1902 * group - group_rwsem prevents new threads from appearing, and if
1903 * threads exit, this will just be an over-estimate.
1906 group_size = get_nr_threads(tsk);
1909 /* flex_array supports very large thread-groups better than kmalloc. */
1910 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
1913 /* pre-allocate to guarantee space while iterating in rcu read-side. */
1914 retval = flex_array_prealloc(group, 0, group_size, GFP_KERNEL);
1916 goto out_free_group_list;
1920 * Prevent freeing of tasks while we take a snapshot. Tasks that are
1921 * already PF_EXITING could be freed from underneath us unless we
1922 * take an rcu_read_lock.
1926 struct task_and_cgroup ent;
1928 /* @tsk either already exited or can't exit until the end */
1929 if (tsk->flags & PF_EXITING)
1932 /* as per above, nr_threads may decrease, but not increase. */
1933 BUG_ON(i >= group_size);
1935 ent.cgrp = task_cgroup_from_root(tsk, root);
1936 /* nothing to do if this task is already in the cgroup */
1937 if (ent.cgrp == cgrp)
1940 * saying GFP_ATOMIC has no effect here because we did prealloc
1941 * earlier, but it's good form to communicate our expectations.
1943 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
1944 BUG_ON(retval != 0);
1949 } while_each_thread(leader, tsk);
1951 /* remember the number of threads in the array for later. */
1953 tset.tc_array = group;
1954 tset.tc_array_len = group_size;
1956 /* methods shouldn't be called if no task is actually migrating */
1959 goto out_free_group_list;
1962 * step 1: check that we can legitimately attach to the cgroup.
1964 for_each_css(css, i, cgrp) {
1965 if (css->ss->can_attach) {
1966 retval = css->ss->can_attach(css, &tset);
1969 goto out_cancel_attach;
1975 * step 2: make sure css_sets exist for all threads to be migrated.
1976 * we use find_css_set, which allocates a new one if necessary.
1978 for (i = 0; i < group_size; i++) {
1979 struct css_set *old_cset;
1981 tc = flex_array_get(group, i);
1982 old_cset = task_css_set(tc->task);
1983 tc->cset = find_css_set(old_cset, cgrp);
1986 goto out_put_css_set_refs;
1991 * step 3: now that we're guaranteed success wrt the css_sets,
1992 * proceed to move all tasks to the new cgroup. There are no
1993 * failure cases after here, so this is the commit point.
1995 for (i = 0; i < group_size; i++) {
1996 tc = flex_array_get(group, i);
1997 cgroup_task_migrate(tc->cgrp, tc->task, tc->cset);
1999 /* nothing is sensitive to fork() after this point. */
2002 * step 4: do subsystem attach callbacks.
2004 for_each_css(css, i, cgrp)
2005 if (css->ss->attach)
2006 css->ss->attach(css, &tset);
2009 * step 5: success! and cleanup
2012 out_put_css_set_refs:
2014 for (i = 0; i < group_size; i++) {
2015 tc = flex_array_get(group, i);
2018 put_css_set(tc->cset);
2023 for_each_css(css, i, cgrp) {
2024 if (css == failed_css)
2026 if (css->ss->cancel_attach)
2027 css->ss->cancel_attach(css, &tset);
2030 out_free_group_list:
2031 flex_array_free(group);
2036 * Find the task_struct of the task to attach by vpid and pass it along to the
2037 * function to attach either it or all tasks in its threadgroup. Will lock
2038 * cgroup_mutex and threadgroup; may take task_lock of task.
2040 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2042 struct task_struct *tsk;
2043 const struct cred *cred = current_cred(), *tcred;
2046 if (!cgroup_lock_live_group(cgrp))
2052 tsk = find_task_by_vpid(pid);
2056 goto out_unlock_cgroup;
2059 * even if we're attaching all tasks in the thread group, we
2060 * only need to check permissions on one of them.
2062 tcred = __task_cred(tsk);
2063 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2064 !uid_eq(cred->euid, tcred->uid) &&
2065 !uid_eq(cred->euid, tcred->suid)) {
2068 goto out_unlock_cgroup;
2074 tsk = tsk->group_leader;
2077 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2078 * trapped in a cpuset, or RT worker may be born in a cgroup
2079 * with no rt_runtime allocated. Just say no.
2081 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2084 goto out_unlock_cgroup;
2087 get_task_struct(tsk);
2090 threadgroup_lock(tsk);
2092 if (!thread_group_leader(tsk)) {
2094 * a race with de_thread from another thread's exec()
2095 * may strip us of our leadership, if this happens,
2096 * there is no choice but to throw this task away and
2097 * try again; this is
2098 * "double-double-toil-and-trouble-check locking".
2100 threadgroup_unlock(tsk);
2101 put_task_struct(tsk);
2102 goto retry_find_task;
2106 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2108 threadgroup_unlock(tsk);
2110 put_task_struct(tsk);
2112 mutex_unlock(&cgroup_mutex);
2117 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2118 * @from: attach to all cgroups of a given task
2119 * @tsk: the task to be attached
2121 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2123 struct cgroupfs_root *root;
2126 mutex_lock(&cgroup_mutex);
2127 for_each_active_root(root) {
2128 struct cgroup *from_cgrp = task_cgroup_from_root(from, root);
2130 retval = cgroup_attach_task(from_cgrp, tsk, false);
2134 mutex_unlock(&cgroup_mutex);
2138 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2140 static int cgroup_tasks_write(struct cgroup_subsys_state *css,
2141 struct cftype *cft, u64 pid)
2143 return attach_task_by_pid(css->cgroup, pid, false);
2146 static int cgroup_procs_write(struct cgroup_subsys_state *css,
2147 struct cftype *cft, u64 tgid)
2149 return attach_task_by_pid(css->cgroup, tgid, true);
2152 static int cgroup_release_agent_write(struct cgroup_subsys_state *css,
2153 struct cftype *cft, const char *buffer)
2155 BUILD_BUG_ON(sizeof(css->cgroup->root->release_agent_path) < PATH_MAX);
2156 if (strlen(buffer) >= PATH_MAX)
2158 if (!cgroup_lock_live_group(css->cgroup))
2160 spin_lock(&release_agent_path_lock);
2161 strcpy(css->cgroup->root->release_agent_path, buffer);
2162 spin_unlock(&release_agent_path_lock);
2163 mutex_unlock(&cgroup_mutex);
2167 static int cgroup_release_agent_show(struct seq_file *seq, void *v)
2169 struct cgroup *cgrp = seq_css(seq)->cgroup;
2171 if (!cgroup_lock_live_group(cgrp))
2173 seq_puts(seq, cgrp->root->release_agent_path);
2174 seq_putc(seq, '\n');
2175 mutex_unlock(&cgroup_mutex);
2179 static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
2181 struct cgroup *cgrp = seq_css(seq)->cgroup;
2183 seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
2187 /* A buffer size big enough for numbers or short strings */
2188 #define CGROUP_LOCAL_BUFFER_SIZE 64
2190 static ssize_t cgroup_file_write(struct file *file, const char __user *userbuf,
2191 size_t nbytes, loff_t *ppos)
2193 struct cfent *cfe = __d_cfe(file->f_dentry);
2194 struct cftype *cft = __d_cft(file->f_dentry);
2195 struct cgroup_subsys_state *css = cfe->css;
2196 size_t max_bytes = cft->max_write_len ?: CGROUP_LOCAL_BUFFER_SIZE - 1;
2200 if (nbytes >= max_bytes)
2203 buf = kmalloc(nbytes + 1, GFP_KERNEL);
2207 if (copy_from_user(buf, userbuf, nbytes)) {
2214 if (cft->write_string) {
2215 ret = cft->write_string(css, cft, strstrip(buf));
2216 } else if (cft->write_u64) {
2217 unsigned long long v;
2218 ret = kstrtoull(buf, 0, &v);
2220 ret = cft->write_u64(css, cft, v);
2221 } else if (cft->write_s64) {
2223 ret = kstrtoll(buf, 0, &v);
2225 ret = cft->write_s64(css, cft, v);
2226 } else if (cft->trigger) {
2227 ret = cft->trigger(css, (unsigned int)cft->private);
2233 return ret ?: nbytes;
2237 * seqfile ops/methods for returning structured data. Currently just
2238 * supports string->u64 maps, but can be extended in future.
2241 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
2243 struct cftype *cft = seq_cft(seq);
2245 if (cft->seq_start) {
2246 return cft->seq_start(seq, ppos);
2249 * The same behavior and code as single_open(). Returns
2250 * !NULL if pos is at the beginning; otherwise, NULL.
2252 return NULL + !*ppos;
2256 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
2258 struct cftype *cft = seq_cft(seq);
2260 if (cft->seq_next) {
2261 return cft->seq_next(seq, v, ppos);
2264 * The same behavior and code as single_open(), always
2265 * terminate after the initial read.
2272 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
2274 struct cftype *cft = seq_cft(seq);
2277 cft->seq_stop(seq, v);
2280 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2282 struct cftype *cft = seq_cft(m);
2283 struct cgroup_subsys_state *css = seq_css(m);
2286 return cft->seq_show(m, arg);
2289 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
2290 else if (cft->read_s64)
2291 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
2297 static struct seq_operations cgroup_seq_operations = {
2298 .start = cgroup_seqfile_start,
2299 .next = cgroup_seqfile_next,
2300 .stop = cgroup_seqfile_stop,
2301 .show = cgroup_seqfile_show,
2304 static int cgroup_file_open(struct inode *inode, struct file *file)
2306 struct cfent *cfe = __d_cfe(file->f_dentry);
2307 struct cftype *cft = __d_cft(file->f_dentry);
2308 struct cgroup *cgrp = __d_cgrp(cfe->dentry->d_parent);
2309 struct cgroup_subsys_state *css;
2310 struct cgroup_open_file *of;
2313 err = generic_file_open(inode, file);
2318 * If the file belongs to a subsystem, pin the css. Will be
2319 * unpinned either on open failure or release. This ensures that
2320 * @css stays alive for all file operations.
2323 css = cgroup_css(cgrp, cft->ss);
2324 if (cft->ss && !css_tryget(css))
2332 * @cfe->css is used by read/write/close to determine the
2333 * associated css. @file->private_data would be a better place but
2334 * that's already used by seqfile. Multiple accessors may use it
2335 * simultaneously which is okay as the association never changes.
2337 WARN_ON_ONCE(cfe->css && cfe->css != css);
2340 of = __seq_open_private(file, &cgroup_seq_operations,
2341 sizeof(struct cgroup_open_file));
2352 static int cgroup_file_release(struct inode *inode, struct file *file)
2354 struct cfent *cfe = __d_cfe(file->f_dentry);
2355 struct cgroup_subsys_state *css = cfe->css;
2359 return seq_release_private(inode, file);
2363 * cgroup_rename - Only allow simple rename of directories in place.
2365 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2366 struct inode *new_dir, struct dentry *new_dentry)
2369 struct cgroup_name *name, *old_name;
2370 struct cgroup *cgrp;
2373 * It's convinient to use parent dir's i_mutex to protected
2376 lockdep_assert_held(&old_dir->i_mutex);
2378 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2380 if (new_dentry->d_inode)
2382 if (old_dir != new_dir)
2385 cgrp = __d_cgrp(old_dentry);
2388 * This isn't a proper migration and its usefulness is very
2389 * limited. Disallow if sane_behavior.
2391 if (cgroup_sane_behavior(cgrp))
2394 name = cgroup_alloc_name(new_dentry);
2398 ret = simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2404 old_name = rcu_dereference_protected(cgrp->name, true);
2405 rcu_assign_pointer(cgrp->name, name);
2407 kfree_rcu(old_name, rcu_head);
2411 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2413 if (S_ISDIR(dentry->d_inode->i_mode))
2414 return &__d_cgrp(dentry)->xattrs;
2416 return &__d_cfe(dentry)->xattrs;
2419 static inline int xattr_enabled(struct dentry *dentry)
2421 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2422 return root->flags & CGRP_ROOT_XATTR;
2425 static bool is_valid_xattr(const char *name)
2427 if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2428 !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2433 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2434 const void *val, size_t size, int flags)
2436 if (!xattr_enabled(dentry))
2438 if (!is_valid_xattr(name))
2440 return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2443 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2445 if (!xattr_enabled(dentry))
2447 if (!is_valid_xattr(name))
2449 return simple_xattr_remove(__d_xattrs(dentry), name);
2452 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2453 void *buf, size_t size)
2455 if (!xattr_enabled(dentry))
2457 if (!is_valid_xattr(name))
2459 return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2462 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2464 if (!xattr_enabled(dentry))
2466 return simple_xattr_list(__d_xattrs(dentry), buf, size);
2469 static const struct file_operations cgroup_file_operations = {
2471 .write = cgroup_file_write,
2472 .llseek = generic_file_llseek,
2473 .open = cgroup_file_open,
2474 .release = cgroup_file_release,
2477 static const struct inode_operations cgroup_file_inode_operations = {
2478 .setxattr = cgroup_setxattr,
2479 .getxattr = cgroup_getxattr,
2480 .listxattr = cgroup_listxattr,
2481 .removexattr = cgroup_removexattr,
2484 static const struct inode_operations cgroup_dir_inode_operations = {
2485 .lookup = simple_lookup,
2486 .mkdir = cgroup_mkdir,
2487 .rmdir = cgroup_rmdir,
2488 .rename = cgroup_rename,
2489 .setxattr = cgroup_setxattr,
2490 .getxattr = cgroup_getxattr,
2491 .listxattr = cgroup_listxattr,
2492 .removexattr = cgroup_removexattr,
2495 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2496 struct super_block *sb)
2498 struct inode *inode;
2502 if (dentry->d_inode)
2505 inode = cgroup_new_inode(mode, sb);
2509 if (S_ISDIR(mode)) {
2510 inode->i_op = &cgroup_dir_inode_operations;
2511 inode->i_fop = &simple_dir_operations;
2513 /* start off with i_nlink == 2 (for "." entry) */
2515 inc_nlink(dentry->d_parent->d_inode);
2518 * Control reaches here with cgroup_mutex held.
2519 * @inode->i_mutex should nest outside cgroup_mutex but we
2520 * want to populate it immediately without releasing
2521 * cgroup_mutex. As @inode isn't visible to anyone else
2522 * yet, trylock will always succeed without affecting
2525 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2526 } else if (S_ISREG(mode)) {
2528 inode->i_fop = &cgroup_file_operations;
2529 inode->i_op = &cgroup_file_inode_operations;
2531 d_instantiate(dentry, inode);
2532 dget(dentry); /* Extra count - pin the dentry in core */
2537 * cgroup_file_mode - deduce file mode of a control file
2538 * @cft: the control file in question
2540 * returns cft->mode if ->mode is not 0
2541 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2542 * returns S_IRUGO if it has only a read handler
2543 * returns S_IWUSR if it has only a write hander
2545 static umode_t cgroup_file_mode(const struct cftype *cft)
2552 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
2555 if (cft->write_u64 || cft->write_s64 || cft->write_string ||
2562 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2564 struct dentry *dir = cgrp->dentry;
2565 struct cgroup *parent = __d_cgrp(dir);
2566 struct dentry *dentry;
2570 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2572 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
2573 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
2574 strcpy(name, cft->ss->name);
2577 strcat(name, cft->name);
2579 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2581 cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2585 dentry = lookup_one_len(name, dir, strlen(name));
2586 if (IS_ERR(dentry)) {
2587 error = PTR_ERR(dentry);
2591 cfe->type = (void *)cft;
2592 cfe->dentry = dentry;
2593 dentry->d_fsdata = cfe;
2594 simple_xattrs_init(&cfe->xattrs);
2596 mode = cgroup_file_mode(cft);
2597 error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2599 list_add_tail(&cfe->node, &parent->files);
2609 * cgroup_addrm_files - add or remove files to a cgroup directory
2610 * @cgrp: the target cgroup
2611 * @cfts: array of cftypes to be added
2612 * @is_add: whether to add or remove
2614 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2615 * For removals, this function never fails. If addition fails, this
2616 * function doesn't remove files already added. The caller is responsible
2619 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2625 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
2626 lockdep_assert_held(&cgroup_mutex);
2628 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2629 /* does cft->flags tell us to skip this file on @cgrp? */
2630 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2632 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2634 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2638 ret = cgroup_add_file(cgrp, cft);
2640 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2645 cgroup_rm_file(cgrp, cft);
2651 static void cgroup_cfts_prepare(void)
2652 __acquires(&cgroup_mutex)
2655 * Thanks to the entanglement with vfs inode locking, we can't walk
2656 * the existing cgroups under cgroup_mutex and create files.
2657 * Instead, we use css_for_each_descendant_pre() and drop RCU read
2658 * lock before calling cgroup_addrm_files().
2660 mutex_lock(&cgroup_mutex);
2663 static int cgroup_cfts_commit(struct cftype *cfts, bool is_add)
2664 __releases(&cgroup_mutex)
2667 struct cgroup_subsys *ss = cfts[0].ss;
2668 struct cgroup *root = &ss->root->top_cgroup;
2669 struct super_block *sb = ss->root->sb;
2670 struct dentry *prev = NULL;
2671 struct inode *inode;
2672 struct cgroup_subsys_state *css;
2676 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2677 if (!cfts || ss->root == &cgroup_dummy_root ||
2678 !atomic_inc_not_zero(&sb->s_active)) {
2679 mutex_unlock(&cgroup_mutex);
2684 * All cgroups which are created after we drop cgroup_mutex will
2685 * have the updated set of files, so we only need to update the
2686 * cgroups created before the current @cgroup_serial_nr_next.
2688 update_before = cgroup_serial_nr_next;
2690 /* add/rm files for all cgroups created before */
2691 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2692 struct cgroup *cgrp = css->cgroup;
2694 if (cgroup_is_dead(cgrp))
2697 inode = cgrp->dentry->d_inode;
2700 prev = cgrp->dentry;
2702 mutex_unlock(&cgroup_mutex);
2703 mutex_lock(&inode->i_mutex);
2704 mutex_lock(&cgroup_mutex);
2705 if (cgrp->serial_nr < update_before && !cgroup_is_dead(cgrp))
2706 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2707 mutex_unlock(&inode->i_mutex);
2711 mutex_unlock(&cgroup_mutex);
2713 deactivate_super(sb);
2718 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2719 * @ss: target cgroup subsystem
2720 * @cfts: zero-length name terminated array of cftypes
2722 * Register @cfts to @ss. Files described by @cfts are created for all
2723 * existing cgroups to which @ss is attached and all future cgroups will
2724 * have them too. This function can be called anytime whether @ss is
2727 * Returns 0 on successful registration, -errno on failure. Note that this
2728 * function currently returns 0 as long as @cfts registration is successful
2729 * even if some file creation attempts on existing cgroups fail.
2731 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2733 struct cftype_set *set;
2737 set = kzalloc(sizeof(*set), GFP_KERNEL);
2741 for (cft = cfts; cft->name[0] != '\0'; cft++)
2744 cgroup_cfts_prepare();
2746 list_add_tail(&set->node, &ss->cftsets);
2747 ret = cgroup_cfts_commit(cfts, true);
2749 cgroup_rm_cftypes(cfts);
2752 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2755 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2756 * @cfts: zero-length name terminated array of cftypes
2758 * Unregister @cfts. Files described by @cfts are removed from all
2759 * existing cgroups and all future cgroups won't have them either. This
2760 * function can be called anytime whether @cfts' subsys is attached or not.
2762 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2765 int cgroup_rm_cftypes(struct cftype *cfts)
2767 struct cftype_set *set;
2769 if (!cfts || !cfts[0].ss)
2772 cgroup_cfts_prepare();
2774 list_for_each_entry(set, &cfts[0].ss->cftsets, node) {
2775 if (set->cfts == cfts) {
2776 list_del(&set->node);
2778 cgroup_cfts_commit(cfts, false);
2783 cgroup_cfts_commit(NULL, false);
2788 * cgroup_task_count - count the number of tasks in a cgroup.
2789 * @cgrp: the cgroup in question
2791 * Return the number of tasks in the cgroup.
2793 int cgroup_task_count(const struct cgroup *cgrp)
2796 struct cgrp_cset_link *link;
2798 read_lock(&css_set_lock);
2799 list_for_each_entry(link, &cgrp->cset_links, cset_link)
2800 count += atomic_read(&link->cset->refcount);
2801 read_unlock(&css_set_lock);
2806 * To reduce the fork() overhead for systems that are not actually using
2807 * their cgroups capability, we don't maintain the lists running through
2808 * each css_set to its tasks until we see the list actually used - in other
2809 * words after the first call to css_task_iter_start().
2811 static void cgroup_enable_task_cg_lists(void)
2813 struct task_struct *p, *g;
2814 write_lock(&css_set_lock);
2815 use_task_css_set_links = 1;
2817 * We need tasklist_lock because RCU is not safe against
2818 * while_each_thread(). Besides, a forking task that has passed
2819 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2820 * is not guaranteed to have its child immediately visible in the
2821 * tasklist if we walk through it with RCU.
2823 read_lock(&tasklist_lock);
2824 do_each_thread(g, p) {
2827 * We should check if the process is exiting, otherwise
2828 * it will race with cgroup_exit() in that the list
2829 * entry won't be deleted though the process has exited.
2831 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2832 list_add(&p->cg_list, &task_css_set(p)->tasks);
2834 } while_each_thread(g, p);
2835 read_unlock(&tasklist_lock);
2836 write_unlock(&css_set_lock);
2840 * css_next_child - find the next child of a given css
2841 * @pos_css: the current position (%NULL to initiate traversal)
2842 * @parent_css: css whose children to walk
2844 * This function returns the next child of @parent_css and should be called
2845 * under either cgroup_mutex or RCU read lock. The only requirement is
2846 * that @parent_css and @pos_css are accessible. The next sibling is
2847 * guaranteed to be returned regardless of their states.
2849 struct cgroup_subsys_state *
2850 css_next_child(struct cgroup_subsys_state *pos_css,
2851 struct cgroup_subsys_state *parent_css)
2853 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
2854 struct cgroup *cgrp = parent_css->cgroup;
2855 struct cgroup *next;
2857 cgroup_assert_mutex_or_rcu_locked();
2860 * @pos could already have been removed. Once a cgroup is removed,
2861 * its ->sibling.next is no longer updated when its next sibling
2862 * changes. As CGRP_DEAD assertion is serialized and happens
2863 * before the cgroup is taken off the ->sibling list, if we see it
2864 * unasserted, it's guaranteed that the next sibling hasn't
2865 * finished its grace period even if it's already removed, and thus
2866 * safe to dereference from this RCU critical section. If
2867 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
2868 * to be visible as %true here.
2870 * If @pos is dead, its next pointer can't be dereferenced;
2871 * however, as each cgroup is given a monotonically increasing
2872 * unique serial number and always appended to the sibling list,
2873 * the next one can be found by walking the parent's children until
2874 * we see a cgroup with higher serial number than @pos's. While
2875 * this path can be slower, it's taken only when either the current
2876 * cgroup is removed or iteration and removal race.
2879 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
2880 } else if (likely(!cgroup_is_dead(pos))) {
2881 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
2883 list_for_each_entry_rcu(next, &cgrp->children, sibling)
2884 if (next->serial_nr > pos->serial_nr)
2888 if (&next->sibling == &cgrp->children)
2891 return cgroup_css(next, parent_css->ss);
2893 EXPORT_SYMBOL_GPL(css_next_child);
2896 * css_next_descendant_pre - find the next descendant for pre-order walk
2897 * @pos: the current position (%NULL to initiate traversal)
2898 * @root: css whose descendants to walk
2900 * To be used by css_for_each_descendant_pre(). Find the next descendant
2901 * to visit for pre-order traversal of @root's descendants. @root is
2902 * included in the iteration and the first node to be visited.
2904 * While this function requires cgroup_mutex or RCU read locking, it
2905 * doesn't require the whole traversal to be contained in a single critical
2906 * section. This function will return the correct next descendant as long
2907 * as both @pos and @root are accessible and @pos is a descendant of @root.
2909 struct cgroup_subsys_state *
2910 css_next_descendant_pre(struct cgroup_subsys_state *pos,
2911 struct cgroup_subsys_state *root)
2913 struct cgroup_subsys_state *next;
2915 cgroup_assert_mutex_or_rcu_locked();
2917 /* if first iteration, visit @root */
2921 /* visit the first child if exists */
2922 next = css_next_child(NULL, pos);
2926 /* no child, visit my or the closest ancestor's next sibling */
2927 while (pos != root) {
2928 next = css_next_child(pos, css_parent(pos));
2931 pos = css_parent(pos);
2936 EXPORT_SYMBOL_GPL(css_next_descendant_pre);
2939 * css_rightmost_descendant - return the rightmost descendant of a css
2940 * @pos: css of interest
2942 * Return the rightmost descendant of @pos. If there's no descendant, @pos
2943 * is returned. This can be used during pre-order traversal to skip
2946 * While this function requires cgroup_mutex or RCU read locking, it
2947 * doesn't require the whole traversal to be contained in a single critical
2948 * section. This function will return the correct rightmost descendant as
2949 * long as @pos is accessible.
2951 struct cgroup_subsys_state *
2952 css_rightmost_descendant(struct cgroup_subsys_state *pos)
2954 struct cgroup_subsys_state *last, *tmp;
2956 cgroup_assert_mutex_or_rcu_locked();
2960 /* ->prev isn't RCU safe, walk ->next till the end */
2962 css_for_each_child(tmp, last)
2968 EXPORT_SYMBOL_GPL(css_rightmost_descendant);
2970 static struct cgroup_subsys_state *
2971 css_leftmost_descendant(struct cgroup_subsys_state *pos)
2973 struct cgroup_subsys_state *last;
2977 pos = css_next_child(NULL, pos);
2984 * css_next_descendant_post - find the next descendant for post-order walk
2985 * @pos: the current position (%NULL to initiate traversal)
2986 * @root: css whose descendants to walk
2988 * To be used by css_for_each_descendant_post(). Find the next descendant
2989 * to visit for post-order traversal of @root's descendants. @root is
2990 * included in the iteration and the last node to be visited.
2992 * While this function requires cgroup_mutex or RCU read locking, it
2993 * doesn't require the whole traversal to be contained in a single critical
2994 * section. This function will return the correct next descendant as long
2995 * as both @pos and @cgroup are accessible and @pos is a descendant of
2998 struct cgroup_subsys_state *
2999 css_next_descendant_post(struct cgroup_subsys_state *pos,
3000 struct cgroup_subsys_state *root)
3002 struct cgroup_subsys_state *next;
3004 cgroup_assert_mutex_or_rcu_locked();
3006 /* if first iteration, visit leftmost descendant which may be @root */
3008 return css_leftmost_descendant(root);
3010 /* if we visited @root, we're done */
3014 /* if there's an unvisited sibling, visit its leftmost descendant */
3015 next = css_next_child(pos, css_parent(pos));
3017 return css_leftmost_descendant(next);
3019 /* no sibling left, visit parent */
3020 return css_parent(pos);
3022 EXPORT_SYMBOL_GPL(css_next_descendant_post);
3025 * css_advance_task_iter - advance a task itererator to the next css_set
3026 * @it: the iterator to advance
3028 * Advance @it to the next css_set to walk.
3030 static void css_advance_task_iter(struct css_task_iter *it)
3032 struct list_head *l = it->cset_link;
3033 struct cgrp_cset_link *link;
3034 struct css_set *cset;
3036 /* Advance to the next non-empty css_set */
3039 if (l == &it->origin_css->cgroup->cset_links) {
3040 it->cset_link = NULL;
3043 link = list_entry(l, struct cgrp_cset_link, cset_link);
3045 } while (list_empty(&cset->tasks));
3047 it->task = cset->tasks.next;
3051 * css_task_iter_start - initiate task iteration
3052 * @css: the css to walk tasks of
3053 * @it: the task iterator to use
3055 * Initiate iteration through the tasks of @css. The caller can call
3056 * css_task_iter_next() to walk through the tasks until the function
3057 * returns NULL. On completion of iteration, css_task_iter_end() must be
3060 * Note that this function acquires a lock which is released when the
3061 * iteration finishes. The caller can't sleep while iteration is in
3064 void css_task_iter_start(struct cgroup_subsys_state *css,
3065 struct css_task_iter *it)
3066 __acquires(css_set_lock)
3069 * The first time anyone tries to iterate across a css, we need to
3070 * enable the list linking each css_set to its tasks, and fix up
3071 * all existing tasks.
3073 if (!use_task_css_set_links)
3074 cgroup_enable_task_cg_lists();
3076 read_lock(&css_set_lock);
3078 it->origin_css = css;
3079 it->cset_link = &css->cgroup->cset_links;
3081 css_advance_task_iter(it);
3085 * css_task_iter_next - return the next task for the iterator
3086 * @it: the task iterator being iterated
3088 * The "next" function for task iteration. @it should have been
3089 * initialized via css_task_iter_start(). Returns NULL when the iteration
3092 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3094 struct task_struct *res;
3095 struct list_head *l = it->task;
3096 struct cgrp_cset_link *link;
3098 /* If the iterator cg is NULL, we have no tasks */
3101 res = list_entry(l, struct task_struct, cg_list);
3102 /* Advance iterator to find next entry */
3104 link = list_entry(it->cset_link, struct cgrp_cset_link, cset_link);
3105 if (l == &link->cset->tasks) {
3107 * We reached the end of this task list - move on to the
3108 * next cgrp_cset_link.
3110 css_advance_task_iter(it);
3118 * css_task_iter_end - finish task iteration
3119 * @it: the task iterator to finish
3121 * Finish task iteration started by css_task_iter_start().
3123 void css_task_iter_end(struct css_task_iter *it)
3124 __releases(css_set_lock)
3126 read_unlock(&css_set_lock);
3129 static inline int started_after_time(struct task_struct *t1,
3130 struct timespec *time,
3131 struct task_struct *t2)
3133 int start_diff = timespec_compare(&t1->start_time, time);
3134 if (start_diff > 0) {
3136 } else if (start_diff < 0) {
3140 * Arbitrarily, if two processes started at the same
3141 * time, we'll say that the lower pointer value
3142 * started first. Note that t2 may have exited by now
3143 * so this may not be a valid pointer any longer, but
3144 * that's fine - it still serves to distinguish
3145 * between two tasks started (effectively) simultaneously.
3152 * This function is a callback from heap_insert() and is used to order
3154 * In this case we order the heap in descending task start time.
3156 static inline int started_after(void *p1, void *p2)
3158 struct task_struct *t1 = p1;
3159 struct task_struct *t2 = p2;
3160 return started_after_time(t1, &t2->start_time, t2);
3164 * css_scan_tasks - iterate though all the tasks in a css
3165 * @css: the css to iterate tasks of
3166 * @test: optional test callback
3167 * @process: process callback
3168 * @data: data passed to @test and @process
3169 * @heap: optional pre-allocated heap used for task iteration
3171 * Iterate through all the tasks in @css, calling @test for each, and if it
3172 * returns %true, call @process for it also.
3174 * @test may be NULL, meaning always true (select all tasks), which
3175 * effectively duplicates css_task_iter_{start,next,end}() but does not
3176 * lock css_set_lock for the call to @process.
3178 * It is guaranteed that @process will act on every task that is a member
3179 * of @css for the duration of this call. This function may or may not
3180 * call @process for tasks that exit or move to a different css during the
3181 * call, or are forked or move into the css during the call.
3183 * Note that @test may be called with locks held, and may in some
3184 * situations be called multiple times for the same task, so it should be
3187 * If @heap is non-NULL, a heap has been pre-allocated and will be used for
3188 * heap operations (and its "gt" member will be overwritten), else a
3189 * temporary heap will be used (allocation of which may cause this function
3192 int css_scan_tasks(struct cgroup_subsys_state *css,
3193 bool (*test)(struct task_struct *, void *),
3194 void (*process)(struct task_struct *, void *),
3195 void *data, struct ptr_heap *heap)
3198 struct css_task_iter it;
3199 struct task_struct *p, *dropped;
3200 /* Never dereference latest_task, since it's not refcounted */
3201 struct task_struct *latest_task = NULL;
3202 struct ptr_heap tmp_heap;
3203 struct timespec latest_time = { 0, 0 };
3206 /* The caller supplied our heap and pre-allocated its memory */
3207 heap->gt = &started_after;
3209 /* We need to allocate our own heap memory */
3211 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3213 /* cannot allocate the heap */
3219 * Scan tasks in the css, using the @test callback to determine
3220 * which are of interest, and invoking @process callback on the
3221 * ones which need an update. Since we don't want to hold any
3222 * locks during the task updates, gather tasks to be processed in a
3223 * heap structure. The heap is sorted by descending task start
3224 * time. If the statically-sized heap fills up, we overflow tasks
3225 * that started later, and in future iterations only consider tasks
3226 * that started after the latest task in the previous pass. This
3227 * guarantees forward progress and that we don't miss any tasks.
3230 css_task_iter_start(css, &it);
3231 while ((p = css_task_iter_next(&it))) {
3233 * Only affect tasks that qualify per the caller's callback,
3234 * if he provided one
3236 if (test && !test(p, data))
3239 * Only process tasks that started after the last task
3242 if (!started_after_time(p, &latest_time, latest_task))
3244 dropped = heap_insert(heap, p);
3245 if (dropped == NULL) {
3247 * The new task was inserted; the heap wasn't
3251 } else if (dropped != p) {
3253 * The new task was inserted, and pushed out a
3257 put_task_struct(dropped);
3260 * Else the new task was newer than anything already in
3261 * the heap and wasn't inserted
3264 css_task_iter_end(&it);
3267 for (i = 0; i < heap->size; i++) {
3268 struct task_struct *q = heap->ptrs[i];
3270 latest_time = q->start_time;
3273 /* Process the task per the caller's callback */
3278 * If we had to process any tasks at all, scan again
3279 * in case some of them were in the middle of forking
3280 * children that didn't get processed.
3281 * Not the most efficient way to do it, but it avoids
3282 * having to take callback_mutex in the fork path
3286 if (heap == &tmp_heap)
3287 heap_free(&tmp_heap);
3291 static void cgroup_transfer_one_task(struct task_struct *task, void *data)
3293 struct cgroup *new_cgroup = data;
3295 mutex_lock(&cgroup_mutex);
3296 cgroup_attach_task(new_cgroup, task, false);
3297 mutex_unlock(&cgroup_mutex);
3301 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3302 * @to: cgroup to which the tasks will be moved
3303 * @from: cgroup in which the tasks currently reside
3305 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3307 return css_scan_tasks(&from->dummy_css, NULL, cgroup_transfer_one_task,
3312 * Stuff for reading the 'tasks'/'procs' files.
3314 * Reading this file can return large amounts of data if a cgroup has
3315 * *lots* of attached tasks. So it may need several calls to read(),
3316 * but we cannot guarantee that the information we produce is correct
3317 * unless we produce it entirely atomically.
3321 /* which pidlist file are we talking about? */
3322 enum cgroup_filetype {
3328 * A pidlist is a list of pids that virtually represents the contents of one
3329 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3330 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3333 struct cgroup_pidlist {
3335 * used to find which pidlist is wanted. doesn't change as long as
3336 * this particular list stays in the list.
3338 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3341 /* how many elements the above list has */
3343 /* each of these stored in a list by its cgroup */
3344 struct list_head links;
3345 /* pointer to the cgroup we belong to, for list removal purposes */
3346 struct cgroup *owner;
3347 /* for delayed destruction */
3348 struct delayed_work destroy_dwork;
3352 * The following two functions "fix" the issue where there are more pids
3353 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3354 * TODO: replace with a kernel-wide solution to this problem
3356 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3357 static void *pidlist_allocate(int count)
3359 if (PIDLIST_TOO_LARGE(count))
3360 return vmalloc(count * sizeof(pid_t));
3362 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3365 static void pidlist_free(void *p)
3367 if (is_vmalloc_addr(p))
3374 * Used to destroy all pidlists lingering waiting for destroy timer. None
3375 * should be left afterwards.
3377 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
3379 struct cgroup_pidlist *l, *tmp_l;
3381 mutex_lock(&cgrp->pidlist_mutex);
3382 list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
3383 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
3384 mutex_unlock(&cgrp->pidlist_mutex);
3386 flush_workqueue(cgroup_pidlist_destroy_wq);
3387 BUG_ON(!list_empty(&cgrp->pidlists));
3390 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
3392 struct delayed_work *dwork = to_delayed_work(work);
3393 struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
3395 struct cgroup_pidlist *tofree = NULL;
3397 mutex_lock(&l->owner->pidlist_mutex);
3400 * Destroy iff we didn't get queued again. The state won't change
3401 * as destroy_dwork can only be queued while locked.
3403 if (!delayed_work_pending(dwork)) {
3404 list_del(&l->links);
3405 pidlist_free(l->list);
3406 put_pid_ns(l->key.ns);
3410 mutex_unlock(&l->owner->pidlist_mutex);
3415 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3416 * Returns the number of unique elements.
3418 static int pidlist_uniq(pid_t *list, int length)
3423 * we presume the 0th element is unique, so i starts at 1. trivial
3424 * edge cases first; no work needs to be done for either
3426 if (length == 0 || length == 1)
3428 /* src and dest walk down the list; dest counts unique elements */
3429 for (src = 1; src < length; src++) {
3430 /* find next unique element */
3431 while (list[src] == list[src-1]) {
3436 /* dest always points to where the next unique element goes */
3437 list[dest] = list[src];
3445 * The two pid files - task and cgroup.procs - guaranteed that the result
3446 * is sorted, which forced this whole pidlist fiasco. As pid order is
3447 * different per namespace, each namespace needs differently sorted list,
3448 * making it impossible to use, for example, single rbtree of member tasks
3449 * sorted by task pointer. As pidlists can be fairly large, allocating one
3450 * per open file is dangerous, so cgroup had to implement shared pool of
3451 * pidlists keyed by cgroup and namespace.
3453 * All this extra complexity was caused by the original implementation
3454 * committing to an entirely unnecessary property. In the long term, we
3455 * want to do away with it. Explicitly scramble sort order if
3456 * sane_behavior so that no such expectation exists in the new interface.
3458 * Scrambling is done by swapping every two consecutive bits, which is
3459 * non-identity one-to-one mapping which disturbs sort order sufficiently.
3461 static pid_t pid_fry(pid_t pid)
3463 unsigned a = pid & 0x55555555;
3464 unsigned b = pid & 0xAAAAAAAA;
3466 return (a << 1) | (b >> 1);
3469 static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
3471 if (cgroup_sane_behavior(cgrp))
3472 return pid_fry(pid);
3477 static int cmppid(const void *a, const void *b)
3479 return *(pid_t *)a - *(pid_t *)b;
3482 static int fried_cmppid(const void *a, const void *b)
3484 return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
3487 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3488 enum cgroup_filetype type)
3490 struct cgroup_pidlist *l;
3491 /* don't need task_nsproxy() if we're looking at ourself */
3492 struct pid_namespace *ns = task_active_pid_ns(current);
3494 lockdep_assert_held(&cgrp->pidlist_mutex);
3496 list_for_each_entry(l, &cgrp->pidlists, links)
3497 if (l->key.type == type && l->key.ns == ns)
3503 * find the appropriate pidlist for our purpose (given procs vs tasks)
3504 * returns with the lock on that pidlist already held, and takes care
3505 * of the use count, or returns NULL with no locks held if we're out of
3508 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
3509 enum cgroup_filetype type)
3511 struct cgroup_pidlist *l;
3513 lockdep_assert_held(&cgrp->pidlist_mutex);
3515 l = cgroup_pidlist_find(cgrp, type);
3519 /* entry not found; create a new one */
3520 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3524 INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
3526 /* don't need task_nsproxy() if we're looking at ourself */
3527 l->key.ns = get_pid_ns(task_active_pid_ns(current));
3529 list_add(&l->links, &cgrp->pidlists);
3534 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3536 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3537 struct cgroup_pidlist **lp)
3541 int pid, n = 0; /* used for populating the array */
3542 struct css_task_iter it;
3543 struct task_struct *tsk;
3544 struct cgroup_pidlist *l;
3546 lockdep_assert_held(&cgrp->pidlist_mutex);
3549 * If cgroup gets more users after we read count, we won't have
3550 * enough space - tough. This race is indistinguishable to the
3551 * caller from the case that the additional cgroup users didn't
3552 * show up until sometime later on.
3554 length = cgroup_task_count(cgrp);
3555 array = pidlist_allocate(length);
3558 /* now, populate the array */
3559 css_task_iter_start(&cgrp->dummy_css, &it);
3560 while ((tsk = css_task_iter_next(&it))) {
3561 if (unlikely(n == length))
3563 /* get tgid or pid for procs or tasks file respectively */
3564 if (type == CGROUP_FILE_PROCS)
3565 pid = task_tgid_vnr(tsk);
3567 pid = task_pid_vnr(tsk);
3568 if (pid > 0) /* make sure to only use valid results */
3571 css_task_iter_end(&it);
3573 /* now sort & (if procs) strip out duplicates */
3574 if (cgroup_sane_behavior(cgrp))
3575 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
3577 sort(array, length, sizeof(pid_t), cmppid, NULL);
3578 if (type == CGROUP_FILE_PROCS)
3579 length = pidlist_uniq(array, length);
3581 l = cgroup_pidlist_find_create(cgrp, type);
3583 mutex_unlock(&cgrp->pidlist_mutex);
3584 pidlist_free(array);
3588 /* store array, freeing old if necessary */
3589 pidlist_free(l->list);
3597 * cgroupstats_build - build and fill cgroupstats
3598 * @stats: cgroupstats to fill information into
3599 * @dentry: A dentry entry belonging to the cgroup for which stats have
3602 * Build and fill cgroupstats so that taskstats can export it to user
3605 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3608 struct cgroup *cgrp;
3609 struct css_task_iter it;
3610 struct task_struct *tsk;
3613 * Validate dentry by checking the superblock operations,
3614 * and make sure it's a directory.
3616 if (dentry->d_sb->s_op != &cgroup_ops ||
3617 !S_ISDIR(dentry->d_inode->i_mode))
3621 cgrp = dentry->d_fsdata;
3623 css_task_iter_start(&cgrp->dummy_css, &it);
3624 while ((tsk = css_task_iter_next(&it))) {
3625 switch (tsk->state) {
3627 stats->nr_running++;
3629 case TASK_INTERRUPTIBLE:
3630 stats->nr_sleeping++;
3632 case TASK_UNINTERRUPTIBLE:
3633 stats->nr_uninterruptible++;
3636 stats->nr_stopped++;
3639 if (delayacct_is_task_waiting_on_io(tsk))
3640 stats->nr_io_wait++;
3644 css_task_iter_end(&it);
3652 * seq_file methods for the tasks/procs files. The seq_file position is the
3653 * next pid to display; the seq_file iterator is a pointer to the pid
3654 * in the cgroup->l->list array.
3657 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3660 * Initially we receive a position value that corresponds to
3661 * one more than the last pid shown (or 0 on the first call or
3662 * after a seek to the start). Use a binary-search to find the
3663 * next pid to display, if any
3665 struct cgroup_open_file *of = s->private;
3666 struct cgroup *cgrp = seq_css(s)->cgroup;
3667 struct cgroup_pidlist *l;
3668 enum cgroup_filetype type = seq_cft(s)->private;
3669 int index = 0, pid = *pos;
3672 mutex_lock(&cgrp->pidlist_mutex);
3675 * !NULL @of->priv indicates that this isn't the first start()
3676 * after open. If the matching pidlist is around, we can use that.
3677 * Look for it. Note that @of->priv can't be used directly. It
3678 * could already have been destroyed.
3681 of->priv = cgroup_pidlist_find(cgrp, type);
3684 * Either this is the first start() after open or the matching
3685 * pidlist has been destroyed inbetween. Create a new one.
3688 ret = pidlist_array_load(cgrp, type,
3689 (struct cgroup_pidlist **)&of->priv);
3691 return ERR_PTR(ret);
3696 int end = l->length;
3698 while (index < end) {
3699 int mid = (index + end) / 2;
3700 if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
3703 } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
3709 /* If we're off the end of the array, we're done */
3710 if (index >= l->length)
3712 /* Update the abstract position to be the actual pid that we found */
3713 iter = l->list + index;
3714 *pos = cgroup_pid_fry(cgrp, *iter);
3718 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3720 struct cgroup_open_file *of = s->private;
3721 struct cgroup_pidlist *l = of->priv;
3724 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
3725 CGROUP_PIDLIST_DESTROY_DELAY);
3726 mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
3729 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3731 struct cgroup_open_file *of = s->private;
3732 struct cgroup_pidlist *l = of->priv;
3734 pid_t *end = l->list + l->length;
3736 * Advance to the next pid in the array. If this goes off the
3743 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
3748 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3750 return seq_printf(s, "%d\n", *(int *)v);
3754 * seq_operations functions for iterating on pidlists through seq_file -
3755 * independent of whether it's tasks or procs
3757 static const struct seq_operations cgroup_pidlist_seq_operations = {
3758 .start = cgroup_pidlist_start,
3759 .stop = cgroup_pidlist_stop,
3760 .next = cgroup_pidlist_next,
3761 .show = cgroup_pidlist_show,
3764 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3767 return notify_on_release(css->cgroup);
3770 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3771 struct cftype *cft, u64 val)
3773 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3775 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3777 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3782 * When dput() is called asynchronously, if umount has been done and
3783 * then deactivate_super() in cgroup_free_fn() kills the superblock,
3784 * there's a small window that vfs will see the root dentry with non-zero
3785 * refcnt and trigger BUG().
3787 * That's why we hold a reference before dput() and drop it right after.
3789 static void cgroup_dput(struct cgroup *cgrp)
3791 struct super_block *sb = cgrp->root->sb;
3793 atomic_inc(&sb->s_active);
3795 deactivate_super(sb);
3798 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3801 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3804 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3805 struct cftype *cft, u64 val)
3808 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3810 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3814 static struct cftype cgroup_base_files[] = {
3816 .name = "cgroup.procs",
3817 .seq_start = cgroup_pidlist_start,
3818 .seq_next = cgroup_pidlist_next,
3819 .seq_stop = cgroup_pidlist_stop,
3820 .seq_show = cgroup_pidlist_show,
3821 .private = CGROUP_FILE_PROCS,
3822 .write_u64 = cgroup_procs_write,
3823 .mode = S_IRUGO | S_IWUSR,
3826 .name = "cgroup.clone_children",
3827 .flags = CFTYPE_INSANE,
3828 .read_u64 = cgroup_clone_children_read,
3829 .write_u64 = cgroup_clone_children_write,
3832 .name = "cgroup.sane_behavior",
3833 .flags = CFTYPE_ONLY_ON_ROOT,
3834 .seq_show = cgroup_sane_behavior_show,
3838 * Historical crazy stuff. These don't have "cgroup." prefix and
3839 * don't exist if sane_behavior. If you're depending on these, be
3840 * prepared to be burned.
3844 .flags = CFTYPE_INSANE, /* use "procs" instead */
3845 .seq_start = cgroup_pidlist_start,
3846 .seq_next = cgroup_pidlist_next,
3847 .seq_stop = cgroup_pidlist_stop,
3848 .seq_show = cgroup_pidlist_show,
3849 .private = CGROUP_FILE_TASKS,
3850 .write_u64 = cgroup_tasks_write,
3851 .mode = S_IRUGO | S_IWUSR,
3854 .name = "notify_on_release",
3855 .flags = CFTYPE_INSANE,
3856 .read_u64 = cgroup_read_notify_on_release,
3857 .write_u64 = cgroup_write_notify_on_release,
3860 .name = "release_agent",
3861 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
3862 .seq_show = cgroup_release_agent_show,
3863 .write_string = cgroup_release_agent_write,
3864 .max_write_len = PATH_MAX,
3870 * cgroup_populate_dir - create subsys files in a cgroup directory
3871 * @cgrp: target cgroup
3872 * @subsys_mask: mask of the subsystem ids whose files should be added
3874 * On failure, no file is added.
3876 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
3878 struct cgroup_subsys *ss;
3881 /* process cftsets of each subsystem */
3882 for_each_subsys(ss, i) {
3883 struct cftype_set *set;
3885 if (!test_bit(i, &subsys_mask))
3888 list_for_each_entry(set, &ss->cftsets, node) {
3889 ret = cgroup_addrm_files(cgrp, set->cfts, true);
3896 cgroup_clear_dir(cgrp, subsys_mask);
3901 * css destruction is four-stage process.
3903 * 1. Destruction starts. Killing of the percpu_ref is initiated.
3904 * Implemented in kill_css().
3906 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
3907 * and thus css_tryget() is guaranteed to fail, the css can be offlined
3908 * by invoking offline_css(). After offlining, the base ref is put.
3909 * Implemented in css_killed_work_fn().
3911 * 3. When the percpu_ref reaches zero, the only possible remaining
3912 * accessors are inside RCU read sections. css_release() schedules the
3915 * 4. After the grace period, the css can be freed. Implemented in
3916 * css_free_work_fn().
3918 * It is actually hairier because both step 2 and 4 require process context
3919 * and thus involve punting to css->destroy_work adding two additional
3920 * steps to the already complex sequence.
3922 static void css_free_work_fn(struct work_struct *work)
3924 struct cgroup_subsys_state *css =
3925 container_of(work, struct cgroup_subsys_state, destroy_work);
3926 struct cgroup *cgrp = css->cgroup;
3929 css_put(css->parent);
3931 css->ss->css_free(css);
3935 static void css_free_rcu_fn(struct rcu_head *rcu_head)
3937 struct cgroup_subsys_state *css =
3938 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
3941 * css holds an extra ref to @cgrp->dentry which is put on the last
3942 * css_put(). dput() requires process context which we don't have.
3944 INIT_WORK(&css->destroy_work, css_free_work_fn);
3945 queue_work(cgroup_destroy_wq, &css->destroy_work);
3948 static void css_release(struct percpu_ref *ref)
3950 struct cgroup_subsys_state *css =
3951 container_of(ref, struct cgroup_subsys_state, refcnt);
3953 rcu_assign_pointer(css->cgroup->subsys[css->ss->id], NULL);
3954 call_rcu(&css->rcu_head, css_free_rcu_fn);
3957 static void init_css(struct cgroup_subsys_state *css, struct cgroup_subsys *ss,
3958 struct cgroup *cgrp)
3965 css->parent = cgroup_css(cgrp->parent, ss);
3967 css->flags |= CSS_ROOT;
3969 BUG_ON(cgroup_css(cgrp, ss));
3972 /* invoke ->css_online() on a new CSS and mark it online if successful */
3973 static int online_css(struct cgroup_subsys_state *css)
3975 struct cgroup_subsys *ss = css->ss;
3978 lockdep_assert_held(&cgroup_mutex);
3981 ret = ss->css_online(css);
3983 css->flags |= CSS_ONLINE;
3984 css->cgroup->nr_css++;
3985 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
3990 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
3991 static void offline_css(struct cgroup_subsys_state *css)
3993 struct cgroup_subsys *ss = css->ss;
3995 lockdep_assert_held(&cgroup_mutex);
3997 if (!(css->flags & CSS_ONLINE))
4000 if (ss->css_offline)
4001 ss->css_offline(css);
4003 css->flags &= ~CSS_ONLINE;
4004 css->cgroup->nr_css--;
4005 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], css);
4009 * create_css - create a cgroup_subsys_state
4010 * @cgrp: the cgroup new css will be associated with
4011 * @ss: the subsys of new css
4013 * Create a new css associated with @cgrp - @ss pair. On success, the new
4014 * css is online and installed in @cgrp with all interface files created.
4015 * Returns 0 on success, -errno on failure.
4017 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss)
4019 struct cgroup *parent = cgrp->parent;
4020 struct cgroup_subsys_state *css;
4023 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
4024 lockdep_assert_held(&cgroup_mutex);
4026 css = ss->css_alloc(cgroup_css(parent, ss));
4028 return PTR_ERR(css);
4030 err = percpu_ref_init(&css->refcnt, css_release);
4034 init_css(css, ss, cgrp);
4036 err = cgroup_populate_dir(cgrp, 1 << ss->id);
4040 err = online_css(css);
4045 css_get(css->parent);
4047 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4049 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",
4050 current->comm, current->pid, ss->name);
4051 if (!strcmp(ss->name, "memory"))
4052 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4053 ss->warned_broken_hierarchy = true;
4059 percpu_ref_cancel_init(&css->refcnt);
4065 * cgroup_create - create a cgroup
4066 * @parent: cgroup that will be parent of the new cgroup
4067 * @dentry: dentry of the new cgroup
4068 * @mode: mode to set on new inode
4070 * Must be called with the mutex on the parent inode held
4072 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4075 struct cgroup *cgrp;
4076 struct cgroup_name *name;
4077 struct cgroupfs_root *root = parent->root;
4079 struct cgroup_subsys *ss;
4080 struct super_block *sb = root->sb;
4082 /* allocate the cgroup and its ID, 0 is reserved for the root */
4083 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4087 name = cgroup_alloc_name(dentry);
4092 rcu_assign_pointer(cgrp->name, name);
4095 * Temporarily set the pointer to NULL, so idr_find() won't return
4096 * a half-baked cgroup.
4098 cgrp->id = idr_alloc(&root->cgroup_idr, NULL, 1, 0, GFP_KERNEL);
4105 * Only live parents can have children. Note that the liveliness
4106 * check isn't strictly necessary because cgroup_mkdir() and
4107 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4108 * anyway so that locking is contained inside cgroup proper and we
4109 * don't get nasty surprises if we ever grow another caller.
4111 if (!cgroup_lock_live_group(parent)) {
4116 /* Grab a reference on the superblock so the hierarchy doesn't
4117 * get deleted on unmount if there are child cgroups. This
4118 * can be done outside cgroup_mutex, since the sb can't
4119 * disappear while someone has an open control file on the
4121 atomic_inc(&sb->s_active);
4123 init_cgroup_housekeeping(cgrp);
4125 dentry->d_fsdata = cgrp;
4126 cgrp->dentry = dentry;
4128 cgrp->parent = parent;
4129 cgrp->dummy_css.parent = &parent->dummy_css;
4130 cgrp->root = parent->root;
4132 if (notify_on_release(parent))
4133 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4135 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4136 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4139 * Create directory. cgroup_create_file() returns with the new
4140 * directory locked on success so that it can be populated without
4141 * dropping cgroup_mutex.
4143 err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4146 lockdep_assert_held(&dentry->d_inode->i_mutex);
4148 cgrp->serial_nr = cgroup_serial_nr_next++;
4150 /* allocation complete, commit to creation */
4151 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4152 root->number_of_cgroups++;
4154 /* hold a ref to the parent's dentry */
4155 dget(parent->dentry);
4158 * @cgrp is now fully operational. If something fails after this
4159 * point, it'll be released via the normal destruction path.
4161 idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4163 err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
4167 /* let's create and online css's */
4168 for_each_subsys(ss, ssid) {
4169 if (root->subsys_mask & (1 << ssid)) {
4170 err = create_css(cgrp, ss);
4176 mutex_unlock(&cgroup_mutex);
4177 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4182 mutex_unlock(&cgroup_mutex);
4183 /* Release the reference count that we took on the superblock */
4184 deactivate_super(sb);
4186 idr_remove(&root->cgroup_idr, cgrp->id);
4188 kfree(rcu_dereference_raw(cgrp->name));
4194 cgroup_destroy_locked(cgrp);
4195 mutex_unlock(&cgroup_mutex);
4196 mutex_unlock(&dentry->d_inode->i_mutex);
4200 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4202 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4204 /* the vfs holds inode->i_mutex already */
4205 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4209 * This is called when the refcnt of a css is confirmed to be killed.
4210 * css_tryget() is now guaranteed to fail.
4212 static void css_killed_work_fn(struct work_struct *work)
4214 struct cgroup_subsys_state *css =
4215 container_of(work, struct cgroup_subsys_state, destroy_work);
4216 struct cgroup *cgrp = css->cgroup;
4218 mutex_lock(&cgroup_mutex);
4221 * css_tryget() is guaranteed to fail now. Tell subsystems to
4222 * initate destruction.
4227 * If @cgrp is marked dead, it's waiting for refs of all css's to
4228 * be disabled before proceeding to the second phase of cgroup
4229 * destruction. If we are the last one, kick it off.
4231 if (!cgrp->nr_css && cgroup_is_dead(cgrp))
4232 cgroup_destroy_css_killed(cgrp);
4234 mutex_unlock(&cgroup_mutex);
4237 * Put the css refs from kill_css(). Each css holds an extra
4238 * reference to the cgroup's dentry and cgroup removal proceeds
4239 * regardless of css refs. On the last put of each css, whenever
4240 * that may be, the extra dentry ref is put so that dentry
4241 * destruction happens only after all css's are released.
4246 /* css kill confirmation processing requires process context, bounce */
4247 static void css_killed_ref_fn(struct percpu_ref *ref)
4249 struct cgroup_subsys_state *css =
4250 container_of(ref, struct cgroup_subsys_state, refcnt);
4252 INIT_WORK(&css->destroy_work, css_killed_work_fn);
4253 queue_work(cgroup_destroy_wq, &css->destroy_work);
4257 * kill_css - destroy a css
4258 * @css: css to destroy
4260 * This function initiates destruction of @css by removing cgroup interface
4261 * files and putting its base reference. ->css_offline() will be invoked
4262 * asynchronously once css_tryget() is guaranteed to fail and when the
4263 * reference count reaches zero, @css will be released.
4265 static void kill_css(struct cgroup_subsys_state *css)
4267 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4270 * Killing would put the base ref, but we need to keep it alive
4271 * until after ->css_offline().
4276 * cgroup core guarantees that, by the time ->css_offline() is
4277 * invoked, no new css reference will be given out via
4278 * css_tryget(). We can't simply call percpu_ref_kill() and
4279 * proceed to offlining css's because percpu_ref_kill() doesn't
4280 * guarantee that the ref is seen as killed on all CPUs on return.
4282 * Use percpu_ref_kill_and_confirm() to get notifications as each
4283 * css is confirmed to be seen as killed on all CPUs.
4285 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4289 * cgroup_destroy_locked - the first stage of cgroup destruction
4290 * @cgrp: cgroup to be destroyed
4292 * css's make use of percpu refcnts whose killing latency shouldn't be
4293 * exposed to userland and are RCU protected. Also, cgroup core needs to
4294 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
4295 * invoked. To satisfy all the requirements, destruction is implemented in
4296 * the following two steps.
4298 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4299 * userland visible parts and start killing the percpu refcnts of
4300 * css's. Set up so that the next stage will be kicked off once all
4301 * the percpu refcnts are confirmed to be killed.
4303 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4304 * rest of destruction. Once all cgroup references are gone, the
4305 * cgroup is RCU-freed.
4307 * This function implements s1. After this step, @cgrp is gone as far as
4308 * the userland is concerned and a new cgroup with the same name may be
4309 * created. As cgroup doesn't care about the names internally, this
4310 * doesn't cause any problem.
4312 static int cgroup_destroy_locked(struct cgroup *cgrp)
4313 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4315 struct dentry *d = cgrp->dentry;
4316 struct cgroup_subsys_state *css;
4317 struct cgroup *child;
4321 lockdep_assert_held(&d->d_inode->i_mutex);
4322 lockdep_assert_held(&cgroup_mutex);
4325 * css_set_lock synchronizes access to ->cset_links and prevents
4326 * @cgrp from being removed while __put_css_set() is in progress.
4328 read_lock(&css_set_lock);
4329 empty = list_empty(&cgrp->cset_links);
4330 read_unlock(&css_set_lock);
4335 * Make sure there's no live children. We can't test ->children
4336 * emptiness as dead children linger on it while being destroyed;
4337 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
4341 list_for_each_entry_rcu(child, &cgrp->children, sibling) {
4342 empty = cgroup_is_dead(child);
4351 * Initiate massacre of all css's. cgroup_destroy_css_killed()
4352 * will be invoked to perform the rest of destruction once the
4353 * percpu refs of all css's are confirmed to be killed.
4355 for_each_css(css, ssid, cgrp)
4359 * Mark @cgrp dead. This prevents further task migration and child
4360 * creation by disabling cgroup_lock_live_group(). Note that
4361 * CGRP_DEAD assertion is depended upon by css_next_child() to
4362 * resume iteration after dropping RCU read lock. See
4363 * css_next_child() for details.
4365 set_bit(CGRP_DEAD, &cgrp->flags);
4367 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4368 raw_spin_lock(&release_list_lock);
4369 if (!list_empty(&cgrp->release_list))
4370 list_del_init(&cgrp->release_list);
4371 raw_spin_unlock(&release_list_lock);
4374 * If @cgrp has css's attached, the second stage of cgroup
4375 * destruction is kicked off from css_killed_work_fn() after the
4376 * refs of all attached css's are killed. If @cgrp doesn't have
4377 * any css, we kick it off here.
4380 cgroup_destroy_css_killed(cgrp);
4383 * Clear the base files and remove @cgrp directory. The removal
4384 * puts the base ref but we aren't quite done with @cgrp yet, so
4387 cgroup_addrm_files(cgrp, cgroup_base_files, false);
4389 cgroup_d_remove_dir(d);
4395 * cgroup_destroy_css_killed - the second step of cgroup destruction
4396 * @work: cgroup->destroy_free_work
4398 * This function is invoked from a work item for a cgroup which is being
4399 * destroyed after all css's are offlined and performs the rest of
4400 * destruction. This is the second step of destruction described in the
4401 * comment above cgroup_destroy_locked().
4403 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
4405 struct cgroup *parent = cgrp->parent;
4406 struct dentry *d = cgrp->dentry;
4408 lockdep_assert_held(&cgroup_mutex);
4410 /* delete this cgroup from parent->children */
4411 list_del_rcu(&cgrp->sibling);
4415 set_bit(CGRP_RELEASABLE, &parent->flags);
4416 check_for_release(parent);
4419 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4423 mutex_lock(&cgroup_mutex);
4424 ret = cgroup_destroy_locked(dentry->d_fsdata);
4425 mutex_unlock(&cgroup_mutex);
4430 static void __init cgroup_init_cftsets(struct cgroup_subsys *ss)
4432 INIT_LIST_HEAD(&ss->cftsets);
4435 * base_cftset is embedded in subsys itself, no need to worry about
4438 if (ss->base_cftypes) {
4441 for (cft = ss->base_cftypes; cft->name[0] != '\0'; cft++)
4444 ss->base_cftset.cfts = ss->base_cftypes;
4445 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4449 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4451 struct cgroup_subsys_state *css;
4453 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4455 mutex_lock(&cgroup_mutex);
4457 /* init base cftset */
4458 cgroup_init_cftsets(ss);
4460 /* Create the top cgroup state for this subsystem */
4461 ss->root = &cgroup_dummy_root;
4462 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
4463 /* We don't handle early failures gracefully */
4464 BUG_ON(IS_ERR(css));
4465 init_css(css, ss, cgroup_dummy_top);
4467 /* Update the init_css_set to contain a subsys
4468 * pointer to this state - since the subsystem is
4469 * newly registered, all tasks and hence the
4470 * init_css_set is in the subsystem's top cgroup. */
4471 init_css_set.subsys[ss->id] = css;
4473 need_forkexit_callback |= ss->fork || ss->exit;
4475 /* At system boot, before all subsystems have been
4476 * registered, no tasks have been forked, so we don't
4477 * need to invoke fork callbacks here. */
4478 BUG_ON(!list_empty(&init_task.tasks));
4480 BUG_ON(online_css(css));
4482 mutex_unlock(&cgroup_mutex);
4486 * cgroup_init_early - cgroup initialization at system boot
4488 * Initialize cgroups at system boot, and initialize any
4489 * subsystems that request early init.
4491 int __init cgroup_init_early(void)
4493 struct cgroup_subsys *ss;
4496 atomic_set(&init_css_set.refcount, 1);
4497 INIT_LIST_HEAD(&init_css_set.cgrp_links);
4498 INIT_LIST_HEAD(&init_css_set.tasks);
4499 INIT_HLIST_NODE(&init_css_set.hlist);
4501 init_cgroup_root(&cgroup_dummy_root);
4502 cgroup_root_count = 1;
4503 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4505 init_cgrp_cset_link.cset = &init_css_set;
4506 init_cgrp_cset_link.cgrp = cgroup_dummy_top;
4507 list_add(&init_cgrp_cset_link.cset_link, &cgroup_dummy_top->cset_links);
4508 list_add(&init_cgrp_cset_link.cgrp_link, &init_css_set.cgrp_links);
4510 for_each_subsys(ss, i) {
4511 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
4512 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
4513 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
4515 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
4516 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
4519 ss->name = cgroup_subsys_name[i];
4522 cgroup_init_subsys(ss);
4528 * cgroup_init - cgroup initialization
4530 * Register cgroup filesystem and /proc file, and initialize
4531 * any subsystems that didn't request early init.
4533 int __init cgroup_init(void)
4535 struct cgroup_subsys *ss;
4539 err = bdi_init(&cgroup_backing_dev_info);
4543 for_each_subsys(ss, i) {
4544 if (!ss->early_init)
4545 cgroup_init_subsys(ss);
4548 /* allocate id for the dummy hierarchy */
4549 mutex_lock(&cgroup_mutex);
4551 /* Add init_css_set to the hash table */
4552 key = css_set_hash(init_css_set.subsys);
4553 hash_add(css_set_table, &init_css_set.hlist, key);
4555 BUG_ON(cgroup_init_root_id(&cgroup_dummy_root, 0, 1));
4557 err = idr_alloc(&cgroup_dummy_root.cgroup_idr, cgroup_dummy_top,
4561 mutex_unlock(&cgroup_mutex);
4563 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4569 err = register_filesystem(&cgroup_fs_type);
4571 kobject_put(cgroup_kobj);
4575 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4579 bdi_destroy(&cgroup_backing_dev_info);
4584 static int __init cgroup_wq_init(void)
4587 * There isn't much point in executing destruction path in
4588 * parallel. Good chunk is serialized with cgroup_mutex anyway.
4590 * XXX: Must be ordered to make sure parent is offlined after
4591 * children. The ordering requirement is for memcg where a
4592 * parent's offline may wait for a child's leading to deadlock. In
4593 * the long term, this should be fixed from memcg side.
4595 * We would prefer to do this in cgroup_init() above, but that
4596 * is called before init_workqueues(): so leave this until after.
4598 cgroup_destroy_wq = alloc_ordered_workqueue("cgroup_destroy", 0);
4599 BUG_ON(!cgroup_destroy_wq);
4602 * Used to destroy pidlists and separate to serve as flush domain.
4603 * Cap @max_active to 1 too.
4605 cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
4607 BUG_ON(!cgroup_pidlist_destroy_wq);
4611 core_initcall(cgroup_wq_init);
4614 * proc_cgroup_show()
4615 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4616 * - Used for /proc/<pid>/cgroup.
4617 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4618 * doesn't really matter if tsk->cgroup changes after we read it,
4619 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4620 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4621 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4622 * cgroup to top_cgroup.
4625 /* TODO: Use a proper seq_file iterator */
4626 int proc_cgroup_show(struct seq_file *m, void *v)
4629 struct task_struct *tsk;
4632 struct cgroupfs_root *root;
4635 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4641 tsk = get_pid_task(pid, PIDTYPE_PID);
4647 mutex_lock(&cgroup_mutex);
4649 for_each_active_root(root) {
4650 struct cgroup_subsys *ss;
4651 struct cgroup *cgrp;
4652 int ssid, count = 0;
4654 seq_printf(m, "%d:", root->hierarchy_id);
4655 for_each_subsys(ss, ssid)
4656 if (root->subsys_mask & (1 << ssid))
4657 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4658 if (strlen(root->name))
4659 seq_printf(m, "%sname=%s", count ? "," : "",
4662 cgrp = task_cgroup_from_root(tsk, root);
4663 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
4671 mutex_unlock(&cgroup_mutex);
4672 put_task_struct(tsk);
4679 /* Display information about each subsystem and each hierarchy */
4680 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4682 struct cgroup_subsys *ss;
4685 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4687 * ideally we don't want subsystems moving around while we do this.
4688 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4689 * subsys/hierarchy state.
4691 mutex_lock(&cgroup_mutex);
4693 for_each_subsys(ss, i)
4694 seq_printf(m, "%s\t%d\t%d\t%d\n",
4695 ss->name, ss->root->hierarchy_id,
4696 ss->root->number_of_cgroups, !ss->disabled);
4698 mutex_unlock(&cgroup_mutex);
4702 static int cgroupstats_open(struct inode *inode, struct file *file)
4704 return single_open(file, proc_cgroupstats_show, NULL);
4707 static const struct file_operations proc_cgroupstats_operations = {
4708 .open = cgroupstats_open,
4710 .llseek = seq_lseek,
4711 .release = single_release,
4715 * cgroup_fork - attach newly forked task to its parents cgroup.
4716 * @child: pointer to task_struct of forking parent process.
4718 * Description: A task inherits its parent's cgroup at fork().
4720 * A pointer to the shared css_set was automatically copied in
4721 * fork.c by dup_task_struct(). However, we ignore that copy, since
4722 * it was not made under the protection of RCU or cgroup_mutex, so
4723 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
4724 * have already changed current->cgroups, allowing the previously
4725 * referenced cgroup group to be removed and freed.
4727 * At the point that cgroup_fork() is called, 'current' is the parent
4728 * task, and the passed argument 'child' points to the child task.
4730 void cgroup_fork(struct task_struct *child)
4733 get_css_set(task_css_set(current));
4734 child->cgroups = current->cgroups;
4735 task_unlock(current);
4736 INIT_LIST_HEAD(&child->cg_list);
4740 * cgroup_post_fork - called on a new task after adding it to the task list
4741 * @child: the task in question
4743 * Adds the task to the list running through its css_set if necessary and
4744 * call the subsystem fork() callbacks. Has to be after the task is
4745 * visible on the task list in case we race with the first call to
4746 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
4749 void cgroup_post_fork(struct task_struct *child)
4751 struct cgroup_subsys *ss;
4755 * use_task_css_set_links is set to 1 before we walk the tasklist
4756 * under the tasklist_lock and we read it here after we added the child
4757 * to the tasklist under the tasklist_lock as well. If the child wasn't
4758 * yet in the tasklist when we walked through it from
4759 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4760 * should be visible now due to the paired locking and barriers implied
4761 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4762 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4765 if (use_task_css_set_links) {
4766 write_lock(&css_set_lock);
4768 if (list_empty(&child->cg_list))
4769 list_add(&child->cg_list, &task_css_set(child)->tasks);
4771 write_unlock(&css_set_lock);
4775 * Call ss->fork(). This must happen after @child is linked on
4776 * css_set; otherwise, @child might change state between ->fork()
4777 * and addition to css_set.
4779 if (need_forkexit_callback) {
4780 for_each_subsys(ss, i)
4787 * cgroup_exit - detach cgroup from exiting task
4788 * @tsk: pointer to task_struct of exiting process
4789 * @run_callback: run exit callbacks?
4791 * Description: Detach cgroup from @tsk and release it.
4793 * Note that cgroups marked notify_on_release force every task in
4794 * them to take the global cgroup_mutex mutex when exiting.
4795 * This could impact scaling on very large systems. Be reluctant to
4796 * use notify_on_release cgroups where very high task exit scaling
4797 * is required on large systems.
4799 * the_top_cgroup_hack:
4801 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
4803 * We call cgroup_exit() while the task is still competent to
4804 * handle notify_on_release(), then leave the task attached to the
4805 * root cgroup in each hierarchy for the remainder of its exit.
4807 * To do this properly, we would increment the reference count on
4808 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
4809 * code we would add a second cgroup function call, to drop that
4810 * reference. This would just create an unnecessary hot spot on
4811 * the top_cgroup reference count, to no avail.
4813 * Normally, holding a reference to a cgroup without bumping its
4814 * count is unsafe. The cgroup could go away, or someone could
4815 * attach us to a different cgroup, decrementing the count on
4816 * the first cgroup that we never incremented. But in this case,
4817 * top_cgroup isn't going away, and either task has PF_EXITING set,
4818 * which wards off any cgroup_attach_task() attempts, or task is a failed
4819 * fork, never visible to cgroup_attach_task.
4821 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
4823 struct cgroup_subsys *ss;
4824 struct css_set *cset;
4828 * Unlink from the css_set task list if necessary.
4829 * Optimistically check cg_list before taking
4832 if (!list_empty(&tsk->cg_list)) {
4833 write_lock(&css_set_lock);
4834 if (!list_empty(&tsk->cg_list))
4835 list_del_init(&tsk->cg_list);
4836 write_unlock(&css_set_lock);
4839 /* Reassign the task to the init_css_set. */
4841 cset = task_css_set(tsk);
4842 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
4844 if (run_callbacks && need_forkexit_callback) {
4845 /* see cgroup_post_fork() for details */
4846 for_each_subsys(ss, i) {
4848 struct cgroup_subsys_state *old_css = cset->subsys[i];
4849 struct cgroup_subsys_state *css = task_css(tsk, i);
4851 ss->exit(css, old_css, tsk);
4857 put_css_set_taskexit(cset);
4860 static void check_for_release(struct cgroup *cgrp)
4862 if (cgroup_is_releasable(cgrp) &&
4863 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
4865 * Control Group is currently removeable. If it's not
4866 * already queued for a userspace notification, queue
4869 int need_schedule_work = 0;
4871 raw_spin_lock(&release_list_lock);
4872 if (!cgroup_is_dead(cgrp) &&
4873 list_empty(&cgrp->release_list)) {
4874 list_add(&cgrp->release_list, &release_list);
4875 need_schedule_work = 1;
4877 raw_spin_unlock(&release_list_lock);
4878 if (need_schedule_work)
4879 schedule_work(&release_agent_work);
4884 * Notify userspace when a cgroup is released, by running the
4885 * configured release agent with the name of the cgroup (path
4886 * relative to the root of cgroup file system) as the argument.
4888 * Most likely, this user command will try to rmdir this cgroup.
4890 * This races with the possibility that some other task will be
4891 * attached to this cgroup before it is removed, or that some other
4892 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
4893 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
4894 * unused, and this cgroup will be reprieved from its death sentence,
4895 * to continue to serve a useful existence. Next time it's released,
4896 * we will get notified again, if it still has 'notify_on_release' set.
4898 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
4899 * means only wait until the task is successfully execve()'d. The
4900 * separate release agent task is forked by call_usermodehelper(),
4901 * then control in this thread returns here, without waiting for the
4902 * release agent task. We don't bother to wait because the caller of
4903 * this routine has no use for the exit status of the release agent
4904 * task, so no sense holding our caller up for that.
4906 static void cgroup_release_agent(struct work_struct *work)
4908 BUG_ON(work != &release_agent_work);
4909 mutex_lock(&cgroup_mutex);
4910 raw_spin_lock(&release_list_lock);
4911 while (!list_empty(&release_list)) {
4912 char *argv[3], *envp[3];
4914 char *pathbuf = NULL, *agentbuf = NULL;
4915 struct cgroup *cgrp = list_entry(release_list.next,
4918 list_del_init(&cgrp->release_list);
4919 raw_spin_unlock(&release_list_lock);
4920 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4923 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
4925 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
4930 argv[i++] = agentbuf;
4931 argv[i++] = pathbuf;
4935 /* minimal command environment */
4936 envp[i++] = "HOME=/";
4937 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
4940 /* Drop the lock while we invoke the usermode helper,
4941 * since the exec could involve hitting disk and hence
4942 * be a slow process */
4943 mutex_unlock(&cgroup_mutex);
4944 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
4945 mutex_lock(&cgroup_mutex);
4949 raw_spin_lock(&release_list_lock);
4951 raw_spin_unlock(&release_list_lock);
4952 mutex_unlock(&cgroup_mutex);
4955 static int __init cgroup_disable(char *str)
4957 struct cgroup_subsys *ss;
4961 while ((token = strsep(&str, ",")) != NULL) {
4965 for_each_subsys(ss, i) {
4966 if (!strcmp(token, ss->name)) {
4968 printk(KERN_INFO "Disabling %s control group"
4969 " subsystem\n", ss->name);
4976 __setup("cgroup_disable=", cgroup_disable);
4979 * css_from_dir - get corresponding css from the dentry of a cgroup dir
4980 * @dentry: directory dentry of interest
4981 * @ss: subsystem of interest
4983 * Must be called under cgroup_mutex or RCU read lock. The caller is
4984 * responsible for pinning the returned css if it needs to be accessed
4985 * outside the critical section.
4987 struct cgroup_subsys_state *css_from_dir(struct dentry *dentry,
4988 struct cgroup_subsys *ss)
4990 struct cgroup *cgrp;
4992 cgroup_assert_mutex_or_rcu_locked();
4994 /* is @dentry a cgroup dir? */
4995 if (!dentry->d_inode ||
4996 dentry->d_inode->i_op != &cgroup_dir_inode_operations)
4997 return ERR_PTR(-EBADF);
4999 cgrp = __d_cgrp(dentry);
5000 return cgroup_css(cgrp, ss) ?: ERR_PTR(-ENOENT);
5004 * css_from_id - lookup css by id
5005 * @id: the cgroup id
5006 * @ss: cgroup subsys to be looked into
5008 * Returns the css if there's valid one with @id, otherwise returns NULL.
5009 * Should be called under rcu_read_lock().
5011 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5013 struct cgroup *cgrp;
5015 cgroup_assert_mutex_or_rcu_locked();
5017 cgrp = idr_find(&ss->root->cgroup_idr, id);
5019 return cgroup_css(cgrp, ss);
5023 #ifdef CONFIG_CGROUP_DEBUG
5024 static struct cgroup_subsys_state *
5025 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5027 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5030 return ERR_PTR(-ENOMEM);
5035 static void debug_css_free(struct cgroup_subsys_state *css)
5040 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5043 return cgroup_task_count(css->cgroup);
5046 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5049 return (u64)(unsigned long)current->cgroups;
5052 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5058 count = atomic_read(&task_css_set(current)->refcount);
5063 static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
5065 struct cgrp_cset_link *link;
5066 struct css_set *cset;
5068 read_lock(&css_set_lock);
5070 cset = rcu_dereference(current->cgroups);
5071 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5072 struct cgroup *c = link->cgrp;
5076 name = c->dentry->d_name.name;
5079 seq_printf(seq, "Root %d group %s\n",
5080 c->root->hierarchy_id, name);
5083 read_unlock(&css_set_lock);
5087 #define MAX_TASKS_SHOWN_PER_CSS 25
5088 static int cgroup_css_links_read(struct seq_file *seq, void *v)
5090 struct cgroup_subsys_state *css = seq_css(seq);
5091 struct cgrp_cset_link *link;
5093 read_lock(&css_set_lock);
5094 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5095 struct css_set *cset = link->cset;
5096 struct task_struct *task;
5098 seq_printf(seq, "css_set %p\n", cset);
5099 list_for_each_entry(task, &cset->tasks, cg_list) {
5100 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5101 seq_puts(seq, " ...\n");
5104 seq_printf(seq, " task %d\n",
5105 task_pid_vnr(task));
5109 read_unlock(&css_set_lock);
5113 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5115 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
5118 static struct cftype debug_files[] = {
5120 .name = "taskcount",
5121 .read_u64 = debug_taskcount_read,
5125 .name = "current_css_set",
5126 .read_u64 = current_css_set_read,
5130 .name = "current_css_set_refcount",
5131 .read_u64 = current_css_set_refcount_read,
5135 .name = "current_css_set_cg_links",
5136 .seq_show = current_css_set_cg_links_read,
5140 .name = "cgroup_css_links",
5141 .seq_show = cgroup_css_links_read,
5145 .name = "releasable",
5146 .read_u64 = releasable_read,
5152 struct cgroup_subsys debug_cgrp_subsys = {
5153 .css_alloc = debug_css_alloc,
5154 .css_free = debug_css_free,
5155 .base_cftypes = debug_files,
5157 #endif /* CONFIG_CGROUP_DEBUG */