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 root_cgrp->id = idr_alloc(&root->cgroup_idr, root_cgrp,
1499 if (root_cgrp->id < 0)
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 mutex_unlock(&cgroup_mutex);
2692 /* add/rm files for all cgroups created before */
2694 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2695 struct cgroup *cgrp = css->cgroup;
2697 if (cgroup_is_dead(cgrp))
2700 inode = cgrp->dentry->d_inode;
2705 prev = cgrp->dentry;
2707 mutex_lock(&inode->i_mutex);
2708 mutex_lock(&cgroup_mutex);
2709 if (cgrp->serial_nr < update_before && !cgroup_is_dead(cgrp))
2710 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2711 mutex_unlock(&cgroup_mutex);
2712 mutex_unlock(&inode->i_mutex);
2720 deactivate_super(sb);
2725 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2726 * @ss: target cgroup subsystem
2727 * @cfts: zero-length name terminated array of cftypes
2729 * Register @cfts to @ss. Files described by @cfts are created for all
2730 * existing cgroups to which @ss is attached and all future cgroups will
2731 * have them too. This function can be called anytime whether @ss is
2734 * Returns 0 on successful registration, -errno on failure. Note that this
2735 * function currently returns 0 as long as @cfts registration is successful
2736 * even if some file creation attempts on existing cgroups fail.
2738 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2740 struct cftype_set *set;
2744 set = kzalloc(sizeof(*set), GFP_KERNEL);
2748 for (cft = cfts; cft->name[0] != '\0'; cft++)
2751 cgroup_cfts_prepare();
2753 list_add_tail(&set->node, &ss->cftsets);
2754 ret = cgroup_cfts_commit(cfts, true);
2756 cgroup_rm_cftypes(cfts);
2759 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2762 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2763 * @cfts: zero-length name terminated array of cftypes
2765 * Unregister @cfts. Files described by @cfts are removed from all
2766 * existing cgroups and all future cgroups won't have them either. This
2767 * function can be called anytime whether @cfts' subsys is attached or not.
2769 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2772 int cgroup_rm_cftypes(struct cftype *cfts)
2774 struct cftype_set *set;
2776 if (!cfts || !cfts[0].ss)
2779 cgroup_cfts_prepare();
2781 list_for_each_entry(set, &cfts[0].ss->cftsets, node) {
2782 if (set->cfts == cfts) {
2783 list_del(&set->node);
2785 cgroup_cfts_commit(cfts, false);
2790 cgroup_cfts_commit(NULL, false);
2795 * cgroup_task_count - count the number of tasks in a cgroup.
2796 * @cgrp: the cgroup in question
2798 * Return the number of tasks in the cgroup.
2800 int cgroup_task_count(const struct cgroup *cgrp)
2803 struct cgrp_cset_link *link;
2805 read_lock(&css_set_lock);
2806 list_for_each_entry(link, &cgrp->cset_links, cset_link)
2807 count += atomic_read(&link->cset->refcount);
2808 read_unlock(&css_set_lock);
2813 * To reduce the fork() overhead for systems that are not actually using
2814 * their cgroups capability, we don't maintain the lists running through
2815 * each css_set to its tasks until we see the list actually used - in other
2816 * words after the first call to css_task_iter_start().
2818 static void cgroup_enable_task_cg_lists(void)
2820 struct task_struct *p, *g;
2821 write_lock(&css_set_lock);
2822 use_task_css_set_links = 1;
2824 * We need tasklist_lock because RCU is not safe against
2825 * while_each_thread(). Besides, a forking task that has passed
2826 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2827 * is not guaranteed to have its child immediately visible in the
2828 * tasklist if we walk through it with RCU.
2830 read_lock(&tasklist_lock);
2831 do_each_thread(g, p) {
2834 * We should check if the process is exiting, otherwise
2835 * it will race with cgroup_exit() in that the list
2836 * entry won't be deleted though the process has exited.
2838 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2839 list_add(&p->cg_list, &task_css_set(p)->tasks);
2841 } while_each_thread(g, p);
2842 read_unlock(&tasklist_lock);
2843 write_unlock(&css_set_lock);
2847 * css_next_child - find the next child of a given css
2848 * @pos_css: the current position (%NULL to initiate traversal)
2849 * @parent_css: css whose children to walk
2851 * This function returns the next child of @parent_css and should be called
2852 * under either cgroup_mutex or RCU read lock. The only requirement is
2853 * that @parent_css and @pos_css are accessible. The next sibling is
2854 * guaranteed to be returned regardless of their states.
2856 struct cgroup_subsys_state *
2857 css_next_child(struct cgroup_subsys_state *pos_css,
2858 struct cgroup_subsys_state *parent_css)
2860 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
2861 struct cgroup *cgrp = parent_css->cgroup;
2862 struct cgroup *next;
2864 cgroup_assert_mutex_or_rcu_locked();
2867 * @pos could already have been removed. Once a cgroup is removed,
2868 * its ->sibling.next is no longer updated when its next sibling
2869 * changes. As CGRP_DEAD assertion is serialized and happens
2870 * before the cgroup is taken off the ->sibling list, if we see it
2871 * unasserted, it's guaranteed that the next sibling hasn't
2872 * finished its grace period even if it's already removed, and thus
2873 * safe to dereference from this RCU critical section. If
2874 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
2875 * to be visible as %true here.
2877 * If @pos is dead, its next pointer can't be dereferenced;
2878 * however, as each cgroup is given a monotonically increasing
2879 * unique serial number and always appended to the sibling list,
2880 * the next one can be found by walking the parent's children until
2881 * we see a cgroup with higher serial number than @pos's. While
2882 * this path can be slower, it's taken only when either the current
2883 * cgroup is removed or iteration and removal race.
2886 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
2887 } else if (likely(!cgroup_is_dead(pos))) {
2888 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
2890 list_for_each_entry_rcu(next, &cgrp->children, sibling)
2891 if (next->serial_nr > pos->serial_nr)
2895 if (&next->sibling == &cgrp->children)
2898 return cgroup_css(next, parent_css->ss);
2900 EXPORT_SYMBOL_GPL(css_next_child);
2903 * css_next_descendant_pre - find the next descendant for pre-order walk
2904 * @pos: the current position (%NULL to initiate traversal)
2905 * @root: css whose descendants to walk
2907 * To be used by css_for_each_descendant_pre(). Find the next descendant
2908 * to visit for pre-order traversal of @root's descendants. @root is
2909 * included in the iteration and the first node to be visited.
2911 * While this function requires cgroup_mutex or RCU read locking, it
2912 * doesn't require the whole traversal to be contained in a single critical
2913 * section. This function will return the correct next descendant as long
2914 * as both @pos and @root are accessible and @pos is a descendant of @root.
2916 struct cgroup_subsys_state *
2917 css_next_descendant_pre(struct cgroup_subsys_state *pos,
2918 struct cgroup_subsys_state *root)
2920 struct cgroup_subsys_state *next;
2922 cgroup_assert_mutex_or_rcu_locked();
2924 /* if first iteration, visit @root */
2928 /* visit the first child if exists */
2929 next = css_next_child(NULL, pos);
2933 /* no child, visit my or the closest ancestor's next sibling */
2934 while (pos != root) {
2935 next = css_next_child(pos, css_parent(pos));
2938 pos = css_parent(pos);
2943 EXPORT_SYMBOL_GPL(css_next_descendant_pre);
2946 * css_rightmost_descendant - return the rightmost descendant of a css
2947 * @pos: css of interest
2949 * Return the rightmost descendant of @pos. If there's no descendant, @pos
2950 * is returned. This can be used during pre-order traversal to skip
2953 * While this function requires cgroup_mutex or RCU read locking, it
2954 * doesn't require the whole traversal to be contained in a single critical
2955 * section. This function will return the correct rightmost descendant as
2956 * long as @pos is accessible.
2958 struct cgroup_subsys_state *
2959 css_rightmost_descendant(struct cgroup_subsys_state *pos)
2961 struct cgroup_subsys_state *last, *tmp;
2963 cgroup_assert_mutex_or_rcu_locked();
2967 /* ->prev isn't RCU safe, walk ->next till the end */
2969 css_for_each_child(tmp, last)
2975 EXPORT_SYMBOL_GPL(css_rightmost_descendant);
2977 static struct cgroup_subsys_state *
2978 css_leftmost_descendant(struct cgroup_subsys_state *pos)
2980 struct cgroup_subsys_state *last;
2984 pos = css_next_child(NULL, pos);
2991 * css_next_descendant_post - find the next descendant for post-order walk
2992 * @pos: the current position (%NULL to initiate traversal)
2993 * @root: css whose descendants to walk
2995 * To be used by css_for_each_descendant_post(). Find the next descendant
2996 * to visit for post-order traversal of @root's descendants. @root is
2997 * included in the iteration and the last node to be visited.
2999 * While this function requires cgroup_mutex or RCU read locking, it
3000 * doesn't require the whole traversal to be contained in a single critical
3001 * section. This function will return the correct next descendant as long
3002 * as both @pos and @cgroup are accessible and @pos is a descendant of
3005 struct cgroup_subsys_state *
3006 css_next_descendant_post(struct cgroup_subsys_state *pos,
3007 struct cgroup_subsys_state *root)
3009 struct cgroup_subsys_state *next;
3011 cgroup_assert_mutex_or_rcu_locked();
3013 /* if first iteration, visit leftmost descendant which may be @root */
3015 return css_leftmost_descendant(root);
3017 /* if we visited @root, we're done */
3021 /* if there's an unvisited sibling, visit its leftmost descendant */
3022 next = css_next_child(pos, css_parent(pos));
3024 return css_leftmost_descendant(next);
3026 /* no sibling left, visit parent */
3027 return css_parent(pos);
3029 EXPORT_SYMBOL_GPL(css_next_descendant_post);
3032 * css_advance_task_iter - advance a task itererator to the next css_set
3033 * @it: the iterator to advance
3035 * Advance @it to the next css_set to walk.
3037 static void css_advance_task_iter(struct css_task_iter *it)
3039 struct list_head *l = it->cset_link;
3040 struct cgrp_cset_link *link;
3041 struct css_set *cset;
3043 /* Advance to the next non-empty css_set */
3046 if (l == &it->origin_css->cgroup->cset_links) {
3047 it->cset_link = NULL;
3050 link = list_entry(l, struct cgrp_cset_link, cset_link);
3052 } while (list_empty(&cset->tasks));
3054 it->task = cset->tasks.next;
3058 * css_task_iter_start - initiate task iteration
3059 * @css: the css to walk tasks of
3060 * @it: the task iterator to use
3062 * Initiate iteration through the tasks of @css. The caller can call
3063 * css_task_iter_next() to walk through the tasks until the function
3064 * returns NULL. On completion of iteration, css_task_iter_end() must be
3067 * Note that this function acquires a lock which is released when the
3068 * iteration finishes. The caller can't sleep while iteration is in
3071 void css_task_iter_start(struct cgroup_subsys_state *css,
3072 struct css_task_iter *it)
3073 __acquires(css_set_lock)
3076 * The first time anyone tries to iterate across a css, we need to
3077 * enable the list linking each css_set to its tasks, and fix up
3078 * all existing tasks.
3080 if (!use_task_css_set_links)
3081 cgroup_enable_task_cg_lists();
3083 read_lock(&css_set_lock);
3085 it->origin_css = css;
3086 it->cset_link = &css->cgroup->cset_links;
3088 css_advance_task_iter(it);
3092 * css_task_iter_next - return the next task for the iterator
3093 * @it: the task iterator being iterated
3095 * The "next" function for task iteration. @it should have been
3096 * initialized via css_task_iter_start(). Returns NULL when the iteration
3099 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3101 struct task_struct *res;
3102 struct list_head *l = it->task;
3103 struct cgrp_cset_link *link;
3105 /* If the iterator cg is NULL, we have no tasks */
3108 res = list_entry(l, struct task_struct, cg_list);
3109 /* Advance iterator to find next entry */
3111 link = list_entry(it->cset_link, struct cgrp_cset_link, cset_link);
3112 if (l == &link->cset->tasks) {
3114 * We reached the end of this task list - move on to the
3115 * next cgrp_cset_link.
3117 css_advance_task_iter(it);
3125 * css_task_iter_end - finish task iteration
3126 * @it: the task iterator to finish
3128 * Finish task iteration started by css_task_iter_start().
3130 void css_task_iter_end(struct css_task_iter *it)
3131 __releases(css_set_lock)
3133 read_unlock(&css_set_lock);
3136 static inline int started_after_time(struct task_struct *t1,
3137 struct timespec *time,
3138 struct task_struct *t2)
3140 int start_diff = timespec_compare(&t1->start_time, time);
3141 if (start_diff > 0) {
3143 } else if (start_diff < 0) {
3147 * Arbitrarily, if two processes started at the same
3148 * time, we'll say that the lower pointer value
3149 * started first. Note that t2 may have exited by now
3150 * so this may not be a valid pointer any longer, but
3151 * that's fine - it still serves to distinguish
3152 * between two tasks started (effectively) simultaneously.
3159 * This function is a callback from heap_insert() and is used to order
3161 * In this case we order the heap in descending task start time.
3163 static inline int started_after(void *p1, void *p2)
3165 struct task_struct *t1 = p1;
3166 struct task_struct *t2 = p2;
3167 return started_after_time(t1, &t2->start_time, t2);
3171 * css_scan_tasks - iterate though all the tasks in a css
3172 * @css: the css to iterate tasks of
3173 * @test: optional test callback
3174 * @process: process callback
3175 * @data: data passed to @test and @process
3176 * @heap: optional pre-allocated heap used for task iteration
3178 * Iterate through all the tasks in @css, calling @test for each, and if it
3179 * returns %true, call @process for it also.
3181 * @test may be NULL, meaning always true (select all tasks), which
3182 * effectively duplicates css_task_iter_{start,next,end}() but does not
3183 * lock css_set_lock for the call to @process.
3185 * It is guaranteed that @process will act on every task that is a member
3186 * of @css for the duration of this call. This function may or may not
3187 * call @process for tasks that exit or move to a different css during the
3188 * call, or are forked or move into the css during the call.
3190 * Note that @test may be called with locks held, and may in some
3191 * situations be called multiple times for the same task, so it should be
3194 * If @heap is non-NULL, a heap has been pre-allocated and will be used for
3195 * heap operations (and its "gt" member will be overwritten), else a
3196 * temporary heap will be used (allocation of which may cause this function
3199 int css_scan_tasks(struct cgroup_subsys_state *css,
3200 bool (*test)(struct task_struct *, void *),
3201 void (*process)(struct task_struct *, void *),
3202 void *data, struct ptr_heap *heap)
3205 struct css_task_iter it;
3206 struct task_struct *p, *dropped;
3207 /* Never dereference latest_task, since it's not refcounted */
3208 struct task_struct *latest_task = NULL;
3209 struct ptr_heap tmp_heap;
3210 struct timespec latest_time = { 0, 0 };
3213 /* The caller supplied our heap and pre-allocated its memory */
3214 heap->gt = &started_after;
3216 /* We need to allocate our own heap memory */
3218 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3220 /* cannot allocate the heap */
3226 * Scan tasks in the css, using the @test callback to determine
3227 * which are of interest, and invoking @process callback on the
3228 * ones which need an update. Since we don't want to hold any
3229 * locks during the task updates, gather tasks to be processed in a
3230 * heap structure. The heap is sorted by descending task start
3231 * time. If the statically-sized heap fills up, we overflow tasks
3232 * that started later, and in future iterations only consider tasks
3233 * that started after the latest task in the previous pass. This
3234 * guarantees forward progress and that we don't miss any tasks.
3237 css_task_iter_start(css, &it);
3238 while ((p = css_task_iter_next(&it))) {
3240 * Only affect tasks that qualify per the caller's callback,
3241 * if he provided one
3243 if (test && !test(p, data))
3246 * Only process tasks that started after the last task
3249 if (!started_after_time(p, &latest_time, latest_task))
3251 dropped = heap_insert(heap, p);
3252 if (dropped == NULL) {
3254 * The new task was inserted; the heap wasn't
3258 } else if (dropped != p) {
3260 * The new task was inserted, and pushed out a
3264 put_task_struct(dropped);
3267 * Else the new task was newer than anything already in
3268 * the heap and wasn't inserted
3271 css_task_iter_end(&it);
3274 for (i = 0; i < heap->size; i++) {
3275 struct task_struct *q = heap->ptrs[i];
3277 latest_time = q->start_time;
3280 /* Process the task per the caller's callback */
3285 * If we had to process any tasks at all, scan again
3286 * in case some of them were in the middle of forking
3287 * children that didn't get processed.
3288 * Not the most efficient way to do it, but it avoids
3289 * having to take callback_mutex in the fork path
3293 if (heap == &tmp_heap)
3294 heap_free(&tmp_heap);
3298 static void cgroup_transfer_one_task(struct task_struct *task, void *data)
3300 struct cgroup *new_cgroup = data;
3302 mutex_lock(&cgroup_mutex);
3303 cgroup_attach_task(new_cgroup, task, false);
3304 mutex_unlock(&cgroup_mutex);
3308 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3309 * @to: cgroup to which the tasks will be moved
3310 * @from: cgroup in which the tasks currently reside
3312 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3314 return css_scan_tasks(&from->dummy_css, NULL, cgroup_transfer_one_task,
3319 * Stuff for reading the 'tasks'/'procs' files.
3321 * Reading this file can return large amounts of data if a cgroup has
3322 * *lots* of attached tasks. So it may need several calls to read(),
3323 * but we cannot guarantee that the information we produce is correct
3324 * unless we produce it entirely atomically.
3328 /* which pidlist file are we talking about? */
3329 enum cgroup_filetype {
3335 * A pidlist is a list of pids that virtually represents the contents of one
3336 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3337 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3340 struct cgroup_pidlist {
3342 * used to find which pidlist is wanted. doesn't change as long as
3343 * this particular list stays in the list.
3345 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3348 /* how many elements the above list has */
3350 /* each of these stored in a list by its cgroup */
3351 struct list_head links;
3352 /* pointer to the cgroup we belong to, for list removal purposes */
3353 struct cgroup *owner;
3354 /* for delayed destruction */
3355 struct delayed_work destroy_dwork;
3359 * The following two functions "fix" the issue where there are more pids
3360 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3361 * TODO: replace with a kernel-wide solution to this problem
3363 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3364 static void *pidlist_allocate(int count)
3366 if (PIDLIST_TOO_LARGE(count))
3367 return vmalloc(count * sizeof(pid_t));
3369 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3372 static void pidlist_free(void *p)
3374 if (is_vmalloc_addr(p))
3381 * Used to destroy all pidlists lingering waiting for destroy timer. None
3382 * should be left afterwards.
3384 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
3386 struct cgroup_pidlist *l, *tmp_l;
3388 mutex_lock(&cgrp->pidlist_mutex);
3389 list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
3390 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
3391 mutex_unlock(&cgrp->pidlist_mutex);
3393 flush_workqueue(cgroup_pidlist_destroy_wq);
3394 BUG_ON(!list_empty(&cgrp->pidlists));
3397 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
3399 struct delayed_work *dwork = to_delayed_work(work);
3400 struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
3402 struct cgroup_pidlist *tofree = NULL;
3404 mutex_lock(&l->owner->pidlist_mutex);
3407 * Destroy iff we didn't get queued again. The state won't change
3408 * as destroy_dwork can only be queued while locked.
3410 if (!delayed_work_pending(dwork)) {
3411 list_del(&l->links);
3412 pidlist_free(l->list);
3413 put_pid_ns(l->key.ns);
3417 mutex_unlock(&l->owner->pidlist_mutex);
3422 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3423 * Returns the number of unique elements.
3425 static int pidlist_uniq(pid_t *list, int length)
3430 * we presume the 0th element is unique, so i starts at 1. trivial
3431 * edge cases first; no work needs to be done for either
3433 if (length == 0 || length == 1)
3435 /* src and dest walk down the list; dest counts unique elements */
3436 for (src = 1; src < length; src++) {
3437 /* find next unique element */
3438 while (list[src] == list[src-1]) {
3443 /* dest always points to where the next unique element goes */
3444 list[dest] = list[src];
3452 * The two pid files - task and cgroup.procs - guaranteed that the result
3453 * is sorted, which forced this whole pidlist fiasco. As pid order is
3454 * different per namespace, each namespace needs differently sorted list,
3455 * making it impossible to use, for example, single rbtree of member tasks
3456 * sorted by task pointer. As pidlists can be fairly large, allocating one
3457 * per open file is dangerous, so cgroup had to implement shared pool of
3458 * pidlists keyed by cgroup and namespace.
3460 * All this extra complexity was caused by the original implementation
3461 * committing to an entirely unnecessary property. In the long term, we
3462 * want to do away with it. Explicitly scramble sort order if
3463 * sane_behavior so that no such expectation exists in the new interface.
3465 * Scrambling is done by swapping every two consecutive bits, which is
3466 * non-identity one-to-one mapping which disturbs sort order sufficiently.
3468 static pid_t pid_fry(pid_t pid)
3470 unsigned a = pid & 0x55555555;
3471 unsigned b = pid & 0xAAAAAAAA;
3473 return (a << 1) | (b >> 1);
3476 static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
3478 if (cgroup_sane_behavior(cgrp))
3479 return pid_fry(pid);
3484 static int cmppid(const void *a, const void *b)
3486 return *(pid_t *)a - *(pid_t *)b;
3489 static int fried_cmppid(const void *a, const void *b)
3491 return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
3494 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3495 enum cgroup_filetype type)
3497 struct cgroup_pidlist *l;
3498 /* don't need task_nsproxy() if we're looking at ourself */
3499 struct pid_namespace *ns = task_active_pid_ns(current);
3501 lockdep_assert_held(&cgrp->pidlist_mutex);
3503 list_for_each_entry(l, &cgrp->pidlists, links)
3504 if (l->key.type == type && l->key.ns == ns)
3510 * find the appropriate pidlist for our purpose (given procs vs tasks)
3511 * returns with the lock on that pidlist already held, and takes care
3512 * of the use count, or returns NULL with no locks held if we're out of
3515 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
3516 enum cgroup_filetype type)
3518 struct cgroup_pidlist *l;
3520 lockdep_assert_held(&cgrp->pidlist_mutex);
3522 l = cgroup_pidlist_find(cgrp, type);
3526 /* entry not found; create a new one */
3527 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3531 INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
3533 /* don't need task_nsproxy() if we're looking at ourself */
3534 l->key.ns = get_pid_ns(task_active_pid_ns(current));
3536 list_add(&l->links, &cgrp->pidlists);
3541 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3543 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3544 struct cgroup_pidlist **lp)
3548 int pid, n = 0; /* used for populating the array */
3549 struct css_task_iter it;
3550 struct task_struct *tsk;
3551 struct cgroup_pidlist *l;
3553 lockdep_assert_held(&cgrp->pidlist_mutex);
3556 * If cgroup gets more users after we read count, we won't have
3557 * enough space - tough. This race is indistinguishable to the
3558 * caller from the case that the additional cgroup users didn't
3559 * show up until sometime later on.
3561 length = cgroup_task_count(cgrp);
3562 array = pidlist_allocate(length);
3565 /* now, populate the array */
3566 css_task_iter_start(&cgrp->dummy_css, &it);
3567 while ((tsk = css_task_iter_next(&it))) {
3568 if (unlikely(n == length))
3570 /* get tgid or pid for procs or tasks file respectively */
3571 if (type == CGROUP_FILE_PROCS)
3572 pid = task_tgid_vnr(tsk);
3574 pid = task_pid_vnr(tsk);
3575 if (pid > 0) /* make sure to only use valid results */
3578 css_task_iter_end(&it);
3580 /* now sort & (if procs) strip out duplicates */
3581 if (cgroup_sane_behavior(cgrp))
3582 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
3584 sort(array, length, sizeof(pid_t), cmppid, NULL);
3585 if (type == CGROUP_FILE_PROCS)
3586 length = pidlist_uniq(array, length);
3588 l = cgroup_pidlist_find_create(cgrp, type);
3590 mutex_unlock(&cgrp->pidlist_mutex);
3591 pidlist_free(array);
3595 /* store array, freeing old if necessary */
3596 pidlist_free(l->list);
3604 * cgroupstats_build - build and fill cgroupstats
3605 * @stats: cgroupstats to fill information into
3606 * @dentry: A dentry entry belonging to the cgroup for which stats have
3609 * Build and fill cgroupstats so that taskstats can export it to user
3612 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3615 struct cgroup *cgrp;
3616 struct css_task_iter it;
3617 struct task_struct *tsk;
3620 * Validate dentry by checking the superblock operations,
3621 * and make sure it's a directory.
3623 if (dentry->d_sb->s_op != &cgroup_ops ||
3624 !S_ISDIR(dentry->d_inode->i_mode))
3628 cgrp = dentry->d_fsdata;
3630 css_task_iter_start(&cgrp->dummy_css, &it);
3631 while ((tsk = css_task_iter_next(&it))) {
3632 switch (tsk->state) {
3634 stats->nr_running++;
3636 case TASK_INTERRUPTIBLE:
3637 stats->nr_sleeping++;
3639 case TASK_UNINTERRUPTIBLE:
3640 stats->nr_uninterruptible++;
3643 stats->nr_stopped++;
3646 if (delayacct_is_task_waiting_on_io(tsk))
3647 stats->nr_io_wait++;
3651 css_task_iter_end(&it);
3659 * seq_file methods for the tasks/procs files. The seq_file position is the
3660 * next pid to display; the seq_file iterator is a pointer to the pid
3661 * in the cgroup->l->list array.
3664 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3667 * Initially we receive a position value that corresponds to
3668 * one more than the last pid shown (or 0 on the first call or
3669 * after a seek to the start). Use a binary-search to find the
3670 * next pid to display, if any
3672 struct cgroup_open_file *of = s->private;
3673 struct cgroup *cgrp = seq_css(s)->cgroup;
3674 struct cgroup_pidlist *l;
3675 enum cgroup_filetype type = seq_cft(s)->private;
3676 int index = 0, pid = *pos;
3679 mutex_lock(&cgrp->pidlist_mutex);
3682 * !NULL @of->priv indicates that this isn't the first start()
3683 * after open. If the matching pidlist is around, we can use that.
3684 * Look for it. Note that @of->priv can't be used directly. It
3685 * could already have been destroyed.
3688 of->priv = cgroup_pidlist_find(cgrp, type);
3691 * Either this is the first start() after open or the matching
3692 * pidlist has been destroyed inbetween. Create a new one.
3695 ret = pidlist_array_load(cgrp, type,
3696 (struct cgroup_pidlist **)&of->priv);
3698 return ERR_PTR(ret);
3703 int end = l->length;
3705 while (index < end) {
3706 int mid = (index + end) / 2;
3707 if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
3710 } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
3716 /* If we're off the end of the array, we're done */
3717 if (index >= l->length)
3719 /* Update the abstract position to be the actual pid that we found */
3720 iter = l->list + index;
3721 *pos = cgroup_pid_fry(cgrp, *iter);
3725 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3727 struct cgroup_open_file *of = s->private;
3728 struct cgroup_pidlist *l = of->priv;
3731 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
3732 CGROUP_PIDLIST_DESTROY_DELAY);
3733 mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
3736 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3738 struct cgroup_open_file *of = s->private;
3739 struct cgroup_pidlist *l = of->priv;
3741 pid_t *end = l->list + l->length;
3743 * Advance to the next pid in the array. If this goes off the
3750 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
3755 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3757 return seq_printf(s, "%d\n", *(int *)v);
3761 * seq_operations functions for iterating on pidlists through seq_file -
3762 * independent of whether it's tasks or procs
3764 static const struct seq_operations cgroup_pidlist_seq_operations = {
3765 .start = cgroup_pidlist_start,
3766 .stop = cgroup_pidlist_stop,
3767 .next = cgroup_pidlist_next,
3768 .show = cgroup_pidlist_show,
3771 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3774 return notify_on_release(css->cgroup);
3777 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3778 struct cftype *cft, u64 val)
3780 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3782 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3784 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3789 * When dput() is called asynchronously, if umount has been done and
3790 * then deactivate_super() in cgroup_free_fn() kills the superblock,
3791 * there's a small window that vfs will see the root dentry with non-zero
3792 * refcnt and trigger BUG().
3794 * That's why we hold a reference before dput() and drop it right after.
3796 static void cgroup_dput(struct cgroup *cgrp)
3798 struct super_block *sb = cgrp->root->sb;
3800 atomic_inc(&sb->s_active);
3802 deactivate_super(sb);
3805 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3808 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3811 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3812 struct cftype *cft, u64 val)
3815 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3817 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3821 static struct cftype cgroup_base_files[] = {
3823 .name = "cgroup.procs",
3824 .seq_start = cgroup_pidlist_start,
3825 .seq_next = cgroup_pidlist_next,
3826 .seq_stop = cgroup_pidlist_stop,
3827 .seq_show = cgroup_pidlist_show,
3828 .private = CGROUP_FILE_PROCS,
3829 .write_u64 = cgroup_procs_write,
3830 .mode = S_IRUGO | S_IWUSR,
3833 .name = "cgroup.clone_children",
3834 .flags = CFTYPE_INSANE,
3835 .read_u64 = cgroup_clone_children_read,
3836 .write_u64 = cgroup_clone_children_write,
3839 .name = "cgroup.sane_behavior",
3840 .flags = CFTYPE_ONLY_ON_ROOT,
3841 .seq_show = cgroup_sane_behavior_show,
3845 * Historical crazy stuff. These don't have "cgroup." prefix and
3846 * don't exist if sane_behavior. If you're depending on these, be
3847 * prepared to be burned.
3851 .flags = CFTYPE_INSANE, /* use "procs" instead */
3852 .seq_start = cgroup_pidlist_start,
3853 .seq_next = cgroup_pidlist_next,
3854 .seq_stop = cgroup_pidlist_stop,
3855 .seq_show = cgroup_pidlist_show,
3856 .private = CGROUP_FILE_TASKS,
3857 .write_u64 = cgroup_tasks_write,
3858 .mode = S_IRUGO | S_IWUSR,
3861 .name = "notify_on_release",
3862 .flags = CFTYPE_INSANE,
3863 .read_u64 = cgroup_read_notify_on_release,
3864 .write_u64 = cgroup_write_notify_on_release,
3867 .name = "release_agent",
3868 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
3869 .seq_show = cgroup_release_agent_show,
3870 .write_string = cgroup_release_agent_write,
3871 .max_write_len = PATH_MAX,
3877 * cgroup_populate_dir - create subsys files in a cgroup directory
3878 * @cgrp: target cgroup
3879 * @subsys_mask: mask of the subsystem ids whose files should be added
3881 * On failure, no file is added.
3883 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
3885 struct cgroup_subsys *ss;
3888 /* process cftsets of each subsystem */
3889 for_each_subsys(ss, i) {
3890 struct cftype_set *set;
3892 if (!test_bit(i, &subsys_mask))
3895 list_for_each_entry(set, &ss->cftsets, node) {
3896 ret = cgroup_addrm_files(cgrp, set->cfts, true);
3903 cgroup_clear_dir(cgrp, subsys_mask);
3908 * css destruction is four-stage process.
3910 * 1. Destruction starts. Killing of the percpu_ref is initiated.
3911 * Implemented in kill_css().
3913 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
3914 * and thus css_tryget() is guaranteed to fail, the css can be offlined
3915 * by invoking offline_css(). After offlining, the base ref is put.
3916 * Implemented in css_killed_work_fn().
3918 * 3. When the percpu_ref reaches zero, the only possible remaining
3919 * accessors are inside RCU read sections. css_release() schedules the
3922 * 4. After the grace period, the css can be freed. Implemented in
3923 * css_free_work_fn().
3925 * It is actually hairier because both step 2 and 4 require process context
3926 * and thus involve punting to css->destroy_work adding two additional
3927 * steps to the already complex sequence.
3929 static void css_free_work_fn(struct work_struct *work)
3931 struct cgroup_subsys_state *css =
3932 container_of(work, struct cgroup_subsys_state, destroy_work);
3933 struct cgroup *cgrp = css->cgroup;
3936 css_put(css->parent);
3938 css->ss->css_free(css);
3942 static void css_free_rcu_fn(struct rcu_head *rcu_head)
3944 struct cgroup_subsys_state *css =
3945 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
3948 * css holds an extra ref to @cgrp->dentry which is put on the last
3949 * css_put(). dput() requires process context which we don't have.
3951 INIT_WORK(&css->destroy_work, css_free_work_fn);
3952 queue_work(cgroup_destroy_wq, &css->destroy_work);
3955 static void css_release(struct percpu_ref *ref)
3957 struct cgroup_subsys_state *css =
3958 container_of(ref, struct cgroup_subsys_state, refcnt);
3960 rcu_assign_pointer(css->cgroup->subsys[css->ss->id], NULL);
3961 call_rcu(&css->rcu_head, css_free_rcu_fn);
3964 static void init_css(struct cgroup_subsys_state *css, struct cgroup_subsys *ss,
3965 struct cgroup *cgrp)
3972 css->parent = cgroup_css(cgrp->parent, ss);
3974 css->flags |= CSS_ROOT;
3976 BUG_ON(cgroup_css(cgrp, ss));
3979 /* invoke ->css_online() on a new CSS and mark it online if successful */
3980 static int online_css(struct cgroup_subsys_state *css)
3982 struct cgroup_subsys *ss = css->ss;
3985 lockdep_assert_held(&cgroup_mutex);
3988 ret = ss->css_online(css);
3990 css->flags |= CSS_ONLINE;
3991 css->cgroup->nr_css++;
3992 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
3997 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
3998 static void offline_css(struct cgroup_subsys_state *css)
4000 struct cgroup_subsys *ss = css->ss;
4002 lockdep_assert_held(&cgroup_mutex);
4004 if (!(css->flags & CSS_ONLINE))
4007 if (ss->css_offline)
4008 ss->css_offline(css);
4010 css->flags &= ~CSS_ONLINE;
4011 css->cgroup->nr_css--;
4012 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], css);
4016 * create_css - create a cgroup_subsys_state
4017 * @cgrp: the cgroup new css will be associated with
4018 * @ss: the subsys of new css
4020 * Create a new css associated with @cgrp - @ss pair. On success, the new
4021 * css is online and installed in @cgrp with all interface files created.
4022 * Returns 0 on success, -errno on failure.
4024 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss)
4026 struct cgroup *parent = cgrp->parent;
4027 struct cgroup_subsys_state *css;
4030 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
4031 lockdep_assert_held(&cgroup_mutex);
4033 css = ss->css_alloc(cgroup_css(parent, ss));
4035 return PTR_ERR(css);
4037 err = percpu_ref_init(&css->refcnt, css_release);
4041 init_css(css, ss, cgrp);
4043 err = cgroup_populate_dir(cgrp, 1 << ss->id);
4047 err = online_css(css);
4052 css_get(css->parent);
4054 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4056 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",
4057 current->comm, current->pid, ss->name);
4058 if (!strcmp(ss->name, "memory"))
4059 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4060 ss->warned_broken_hierarchy = true;
4066 percpu_ref_cancel_init(&css->refcnt);
4072 * cgroup_create - create a cgroup
4073 * @parent: cgroup that will be parent of the new cgroup
4074 * @dentry: dentry of the new cgroup
4075 * @mode: mode to set on new inode
4077 * Must be called with the mutex on the parent inode held
4079 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4082 struct cgroup *cgrp;
4083 struct cgroup_name *name;
4084 struct cgroupfs_root *root = parent->root;
4086 struct cgroup_subsys *ss;
4087 struct super_block *sb = root->sb;
4089 /* allocate the cgroup and its ID, 0 is reserved for the root */
4090 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4094 name = cgroup_alloc_name(dentry);
4097 rcu_assign_pointer(cgrp->name, name);
4100 * Temporarily set the pointer to NULL, so idr_find() won't return
4101 * a half-baked cgroup.
4103 cgrp->id = idr_alloc(&root->cgroup_idr, NULL, 1, 0, GFP_KERNEL);
4108 * Only live parents can have children. Note that the liveliness
4109 * check isn't strictly necessary because cgroup_mkdir() and
4110 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4111 * anyway so that locking is contained inside cgroup proper and we
4112 * don't get nasty surprises if we ever grow another caller.
4114 if (!cgroup_lock_live_group(parent)) {
4119 /* Grab a reference on the superblock so the hierarchy doesn't
4120 * get deleted on unmount if there are child cgroups. This
4121 * can be done outside cgroup_mutex, since the sb can't
4122 * disappear while someone has an open control file on the
4124 atomic_inc(&sb->s_active);
4126 init_cgroup_housekeeping(cgrp);
4128 dentry->d_fsdata = cgrp;
4129 cgrp->dentry = dentry;
4131 cgrp->parent = parent;
4132 cgrp->dummy_css.parent = &parent->dummy_css;
4133 cgrp->root = parent->root;
4135 if (notify_on_release(parent))
4136 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4138 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4139 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4142 * Create directory. cgroup_create_file() returns with the new
4143 * directory locked on success so that it can be populated without
4144 * dropping cgroup_mutex.
4146 err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4149 lockdep_assert_held(&dentry->d_inode->i_mutex);
4151 cgrp->serial_nr = cgroup_serial_nr_next++;
4153 /* allocation complete, commit to creation */
4154 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4155 root->number_of_cgroups++;
4157 /* hold a ref to the parent's dentry */
4158 dget(parent->dentry);
4161 * @cgrp is now fully operational. If something fails after this
4162 * point, it'll be released via the normal destruction path.
4164 idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4166 err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
4170 /* let's create and online css's */
4171 for_each_subsys(ss, ssid) {
4172 if (root->subsys_mask & (1 << ssid)) {
4173 err = create_css(cgrp, ss);
4179 mutex_unlock(&cgroup_mutex);
4180 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4185 mutex_unlock(&cgroup_mutex);
4186 /* Release the reference count that we took on the superblock */
4187 deactivate_super(sb);
4189 idr_remove(&root->cgroup_idr, cgrp->id);
4191 kfree(rcu_dereference_raw(cgrp->name));
4197 cgroup_destroy_locked(cgrp);
4198 mutex_unlock(&cgroup_mutex);
4199 mutex_unlock(&dentry->d_inode->i_mutex);
4203 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4205 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4207 /* the vfs holds inode->i_mutex already */
4208 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4212 * This is called when the refcnt of a css is confirmed to be killed.
4213 * css_tryget() is now guaranteed to fail.
4215 static void css_killed_work_fn(struct work_struct *work)
4217 struct cgroup_subsys_state *css =
4218 container_of(work, struct cgroup_subsys_state, destroy_work);
4219 struct cgroup *cgrp = css->cgroup;
4221 mutex_lock(&cgroup_mutex);
4224 * css_tryget() is guaranteed to fail now. Tell subsystems to
4225 * initate destruction.
4230 * If @cgrp is marked dead, it's waiting for refs of all css's to
4231 * be disabled before proceeding to the second phase of cgroup
4232 * destruction. If we are the last one, kick it off.
4234 if (!cgrp->nr_css && cgroup_is_dead(cgrp))
4235 cgroup_destroy_css_killed(cgrp);
4237 mutex_unlock(&cgroup_mutex);
4240 * Put the css refs from kill_css(). Each css holds an extra
4241 * reference to the cgroup's dentry and cgroup removal proceeds
4242 * regardless of css refs. On the last put of each css, whenever
4243 * that may be, the extra dentry ref is put so that dentry
4244 * destruction happens only after all css's are released.
4249 /* css kill confirmation processing requires process context, bounce */
4250 static void css_killed_ref_fn(struct percpu_ref *ref)
4252 struct cgroup_subsys_state *css =
4253 container_of(ref, struct cgroup_subsys_state, refcnt);
4255 INIT_WORK(&css->destroy_work, css_killed_work_fn);
4256 queue_work(cgroup_destroy_wq, &css->destroy_work);
4260 * kill_css - destroy a css
4261 * @css: css to destroy
4263 * This function initiates destruction of @css by removing cgroup interface
4264 * files and putting its base reference. ->css_offline() will be invoked
4265 * asynchronously once css_tryget() is guaranteed to fail and when the
4266 * reference count reaches zero, @css will be released.
4268 static void kill_css(struct cgroup_subsys_state *css)
4270 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4273 * Killing would put the base ref, but we need to keep it alive
4274 * until after ->css_offline().
4279 * cgroup core guarantees that, by the time ->css_offline() is
4280 * invoked, no new css reference will be given out via
4281 * css_tryget(). We can't simply call percpu_ref_kill() and
4282 * proceed to offlining css's because percpu_ref_kill() doesn't
4283 * guarantee that the ref is seen as killed on all CPUs on return.
4285 * Use percpu_ref_kill_and_confirm() to get notifications as each
4286 * css is confirmed to be seen as killed on all CPUs.
4288 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4292 * cgroup_destroy_locked - the first stage of cgroup destruction
4293 * @cgrp: cgroup to be destroyed
4295 * css's make use of percpu refcnts whose killing latency shouldn't be
4296 * exposed to userland and are RCU protected. Also, cgroup core needs to
4297 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
4298 * invoked. To satisfy all the requirements, destruction is implemented in
4299 * the following two steps.
4301 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4302 * userland visible parts and start killing the percpu refcnts of
4303 * css's. Set up so that the next stage will be kicked off once all
4304 * the percpu refcnts are confirmed to be killed.
4306 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4307 * rest of destruction. Once all cgroup references are gone, the
4308 * cgroup is RCU-freed.
4310 * This function implements s1. After this step, @cgrp is gone as far as
4311 * the userland is concerned and a new cgroup with the same name may be
4312 * created. As cgroup doesn't care about the names internally, this
4313 * doesn't cause any problem.
4315 static int cgroup_destroy_locked(struct cgroup *cgrp)
4316 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4318 struct dentry *d = cgrp->dentry;
4319 struct cgroup_subsys_state *css;
4320 struct cgroup *child;
4324 lockdep_assert_held(&d->d_inode->i_mutex);
4325 lockdep_assert_held(&cgroup_mutex);
4328 * css_set_lock synchronizes access to ->cset_links and prevents
4329 * @cgrp from being removed while __put_css_set() is in progress.
4331 read_lock(&css_set_lock);
4332 empty = list_empty(&cgrp->cset_links);
4333 read_unlock(&css_set_lock);
4338 * Make sure there's no live children. We can't test ->children
4339 * emptiness as dead children linger on it while being destroyed;
4340 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
4344 list_for_each_entry_rcu(child, &cgrp->children, sibling) {
4345 empty = cgroup_is_dead(child);
4354 * Initiate massacre of all css's. cgroup_destroy_css_killed()
4355 * will be invoked to perform the rest of destruction once the
4356 * percpu refs of all css's are confirmed to be killed.
4358 for_each_css(css, ssid, cgrp)
4362 * Mark @cgrp dead. This prevents further task migration and child
4363 * creation by disabling cgroup_lock_live_group(). Note that
4364 * CGRP_DEAD assertion is depended upon by css_next_child() to
4365 * resume iteration after dropping RCU read lock. See
4366 * css_next_child() for details.
4368 set_bit(CGRP_DEAD, &cgrp->flags);
4370 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4371 raw_spin_lock(&release_list_lock);
4372 if (!list_empty(&cgrp->release_list))
4373 list_del_init(&cgrp->release_list);
4374 raw_spin_unlock(&release_list_lock);
4377 * If @cgrp has css's attached, the second stage of cgroup
4378 * destruction is kicked off from css_killed_work_fn() after the
4379 * refs of all attached css's are killed. If @cgrp doesn't have
4380 * any css, we kick it off here.
4383 cgroup_destroy_css_killed(cgrp);
4386 * Clear the base files and remove @cgrp directory. The removal
4387 * puts the base ref but we aren't quite done with @cgrp yet, so
4390 cgroup_addrm_files(cgrp, cgroup_base_files, false);
4392 cgroup_d_remove_dir(d);
4398 * cgroup_destroy_css_killed - the second step of cgroup destruction
4399 * @work: cgroup->destroy_free_work
4401 * This function is invoked from a work item for a cgroup which is being
4402 * destroyed after all css's are offlined and performs the rest of
4403 * destruction. This is the second step of destruction described in the
4404 * comment above cgroup_destroy_locked().
4406 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
4408 struct cgroup *parent = cgrp->parent;
4409 struct dentry *d = cgrp->dentry;
4411 lockdep_assert_held(&cgroup_mutex);
4413 /* delete this cgroup from parent->children */
4414 list_del_rcu(&cgrp->sibling);
4418 set_bit(CGRP_RELEASABLE, &parent->flags);
4419 check_for_release(parent);
4422 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4426 mutex_lock(&cgroup_mutex);
4427 ret = cgroup_destroy_locked(dentry->d_fsdata);
4428 mutex_unlock(&cgroup_mutex);
4433 static void __init cgroup_init_cftsets(struct cgroup_subsys *ss)
4435 INIT_LIST_HEAD(&ss->cftsets);
4438 * base_cftset is embedded in subsys itself, no need to worry about
4441 if (ss->base_cftypes) {
4444 for (cft = ss->base_cftypes; cft->name[0] != '\0'; cft++)
4447 ss->base_cftset.cfts = ss->base_cftypes;
4448 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4452 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4454 struct cgroup_subsys_state *css;
4456 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4458 mutex_lock(&cgroup_mutex);
4460 /* init base cftset */
4461 cgroup_init_cftsets(ss);
4463 /* Create the top cgroup state for this subsystem */
4464 ss->root = &cgroup_dummy_root;
4465 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
4466 /* We don't handle early failures gracefully */
4467 BUG_ON(IS_ERR(css));
4468 init_css(css, ss, cgroup_dummy_top);
4470 /* Update the init_css_set to contain a subsys
4471 * pointer to this state - since the subsystem is
4472 * newly registered, all tasks and hence the
4473 * init_css_set is in the subsystem's top cgroup. */
4474 init_css_set.subsys[ss->id] = css;
4476 need_forkexit_callback |= ss->fork || ss->exit;
4478 /* At system boot, before all subsystems have been
4479 * registered, no tasks have been forked, so we don't
4480 * need to invoke fork callbacks here. */
4481 BUG_ON(!list_empty(&init_task.tasks));
4483 BUG_ON(online_css(css));
4485 mutex_unlock(&cgroup_mutex);
4489 * cgroup_init_early - cgroup initialization at system boot
4491 * Initialize cgroups at system boot, and initialize any
4492 * subsystems that request early init.
4494 int __init cgroup_init_early(void)
4496 struct cgroup_subsys *ss;
4499 atomic_set(&init_css_set.refcount, 1);
4500 INIT_LIST_HEAD(&init_css_set.cgrp_links);
4501 INIT_LIST_HEAD(&init_css_set.tasks);
4502 INIT_HLIST_NODE(&init_css_set.hlist);
4504 init_cgroup_root(&cgroup_dummy_root);
4505 cgroup_root_count = 1;
4506 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4508 init_cgrp_cset_link.cset = &init_css_set;
4509 init_cgrp_cset_link.cgrp = cgroup_dummy_top;
4510 list_add(&init_cgrp_cset_link.cset_link, &cgroup_dummy_top->cset_links);
4511 list_add(&init_cgrp_cset_link.cgrp_link, &init_css_set.cgrp_links);
4513 for_each_subsys(ss, i) {
4514 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
4515 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
4516 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
4518 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
4519 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
4522 ss->name = cgroup_subsys_name[i];
4525 cgroup_init_subsys(ss);
4531 * cgroup_init - cgroup initialization
4533 * Register cgroup filesystem and /proc file, and initialize
4534 * any subsystems that didn't request early init.
4536 int __init cgroup_init(void)
4538 struct cgroup_subsys *ss;
4542 err = bdi_init(&cgroup_backing_dev_info);
4546 for_each_subsys(ss, i) {
4547 if (!ss->early_init)
4548 cgroup_init_subsys(ss);
4551 /* allocate id for the dummy hierarchy */
4552 mutex_lock(&cgroup_mutex);
4554 /* Add init_css_set to the hash table */
4555 key = css_set_hash(init_css_set.subsys);
4556 hash_add(css_set_table, &init_css_set.hlist, key);
4558 BUG_ON(cgroup_init_root_id(&cgroup_dummy_root, 0, 1));
4560 err = idr_alloc(&cgroup_dummy_root.cgroup_idr, cgroup_dummy_top,
4564 mutex_unlock(&cgroup_mutex);
4566 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4572 err = register_filesystem(&cgroup_fs_type);
4574 kobject_put(cgroup_kobj);
4578 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4582 bdi_destroy(&cgroup_backing_dev_info);
4587 static int __init cgroup_wq_init(void)
4590 * There isn't much point in executing destruction path in
4591 * parallel. Good chunk is serialized with cgroup_mutex anyway.
4592 * Use 1 for @max_active.
4594 * We would prefer to do this in cgroup_init() above, but that
4595 * is called before init_workqueues(): so leave this until after.
4597 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
4598 BUG_ON(!cgroup_destroy_wq);
4601 * Used to destroy pidlists and separate to serve as flush domain.
4602 * Cap @max_active to 1 too.
4604 cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
4606 BUG_ON(!cgroup_pidlist_destroy_wq);
4610 core_initcall(cgroup_wq_init);
4613 * proc_cgroup_show()
4614 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4615 * - Used for /proc/<pid>/cgroup.
4616 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4617 * doesn't really matter if tsk->cgroup changes after we read it,
4618 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4619 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4620 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4621 * cgroup to top_cgroup.
4624 /* TODO: Use a proper seq_file iterator */
4625 int proc_cgroup_show(struct seq_file *m, void *v)
4628 struct task_struct *tsk;
4631 struct cgroupfs_root *root;
4634 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4640 tsk = get_pid_task(pid, PIDTYPE_PID);
4646 mutex_lock(&cgroup_mutex);
4648 for_each_active_root(root) {
4649 struct cgroup_subsys *ss;
4650 struct cgroup *cgrp;
4651 int ssid, count = 0;
4653 seq_printf(m, "%d:", root->hierarchy_id);
4654 for_each_subsys(ss, ssid)
4655 if (root->subsys_mask & (1 << ssid))
4656 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4657 if (strlen(root->name))
4658 seq_printf(m, "%sname=%s", count ? "," : "",
4661 cgrp = task_cgroup_from_root(tsk, root);
4662 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
4670 mutex_unlock(&cgroup_mutex);
4671 put_task_struct(tsk);
4678 /* Display information about each subsystem and each hierarchy */
4679 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4681 struct cgroup_subsys *ss;
4684 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4686 * ideally we don't want subsystems moving around while we do this.
4687 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4688 * subsys/hierarchy state.
4690 mutex_lock(&cgroup_mutex);
4692 for_each_subsys(ss, i)
4693 seq_printf(m, "%s\t%d\t%d\t%d\n",
4694 ss->name, ss->root->hierarchy_id,
4695 ss->root->number_of_cgroups, !ss->disabled);
4697 mutex_unlock(&cgroup_mutex);
4701 static int cgroupstats_open(struct inode *inode, struct file *file)
4703 return single_open(file, proc_cgroupstats_show, NULL);
4706 static const struct file_operations proc_cgroupstats_operations = {
4707 .open = cgroupstats_open,
4709 .llseek = seq_lseek,
4710 .release = single_release,
4714 * cgroup_fork - attach newly forked task to its parents cgroup.
4715 * @child: pointer to task_struct of forking parent process.
4717 * Description: A task inherits its parent's cgroup at fork().
4719 * A pointer to the shared css_set was automatically copied in
4720 * fork.c by dup_task_struct(). However, we ignore that copy, since
4721 * it was not made under the protection of RCU or cgroup_mutex, so
4722 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
4723 * have already changed current->cgroups, allowing the previously
4724 * referenced cgroup group to be removed and freed.
4726 * At the point that cgroup_fork() is called, 'current' is the parent
4727 * task, and the passed argument 'child' points to the child task.
4729 void cgroup_fork(struct task_struct *child)
4732 get_css_set(task_css_set(current));
4733 child->cgroups = current->cgroups;
4734 task_unlock(current);
4735 INIT_LIST_HEAD(&child->cg_list);
4739 * cgroup_post_fork - called on a new task after adding it to the task list
4740 * @child: the task in question
4742 * Adds the task to the list running through its css_set if necessary and
4743 * call the subsystem fork() callbacks. Has to be after the task is
4744 * visible on the task list in case we race with the first call to
4745 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
4748 void cgroup_post_fork(struct task_struct *child)
4750 struct cgroup_subsys *ss;
4754 * use_task_css_set_links is set to 1 before we walk the tasklist
4755 * under the tasklist_lock and we read it here after we added the child
4756 * to the tasklist under the tasklist_lock as well. If the child wasn't
4757 * yet in the tasklist when we walked through it from
4758 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4759 * should be visible now due to the paired locking and barriers implied
4760 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4761 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4764 if (use_task_css_set_links) {
4765 write_lock(&css_set_lock);
4767 if (list_empty(&child->cg_list))
4768 list_add(&child->cg_list, &task_css_set(child)->tasks);
4770 write_unlock(&css_set_lock);
4774 * Call ss->fork(). This must happen after @child is linked on
4775 * css_set; otherwise, @child might change state between ->fork()
4776 * and addition to css_set.
4778 if (need_forkexit_callback) {
4779 for_each_subsys(ss, i)
4786 * cgroup_exit - detach cgroup from exiting task
4787 * @tsk: pointer to task_struct of exiting process
4788 * @run_callback: run exit callbacks?
4790 * Description: Detach cgroup from @tsk and release it.
4792 * Note that cgroups marked notify_on_release force every task in
4793 * them to take the global cgroup_mutex mutex when exiting.
4794 * This could impact scaling on very large systems. Be reluctant to
4795 * use notify_on_release cgroups where very high task exit scaling
4796 * is required on large systems.
4798 * the_top_cgroup_hack:
4800 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
4802 * We call cgroup_exit() while the task is still competent to
4803 * handle notify_on_release(), then leave the task attached to the
4804 * root cgroup in each hierarchy for the remainder of its exit.
4806 * To do this properly, we would increment the reference count on
4807 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
4808 * code we would add a second cgroup function call, to drop that
4809 * reference. This would just create an unnecessary hot spot on
4810 * the top_cgroup reference count, to no avail.
4812 * Normally, holding a reference to a cgroup without bumping its
4813 * count is unsafe. The cgroup could go away, or someone could
4814 * attach us to a different cgroup, decrementing the count on
4815 * the first cgroup that we never incremented. But in this case,
4816 * top_cgroup isn't going away, and either task has PF_EXITING set,
4817 * which wards off any cgroup_attach_task() attempts, or task is a failed
4818 * fork, never visible to cgroup_attach_task.
4820 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
4822 struct cgroup_subsys *ss;
4823 struct css_set *cset;
4827 * Unlink from the css_set task list if necessary.
4828 * Optimistically check cg_list before taking
4831 if (!list_empty(&tsk->cg_list)) {
4832 write_lock(&css_set_lock);
4833 if (!list_empty(&tsk->cg_list))
4834 list_del_init(&tsk->cg_list);
4835 write_unlock(&css_set_lock);
4838 /* Reassign the task to the init_css_set. */
4840 cset = task_css_set(tsk);
4841 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
4843 if (run_callbacks && need_forkexit_callback) {
4844 /* see cgroup_post_fork() for details */
4845 for_each_subsys(ss, i) {
4847 struct cgroup_subsys_state *old_css = cset->subsys[i];
4848 struct cgroup_subsys_state *css = task_css(tsk, i);
4850 ss->exit(css, old_css, tsk);
4856 put_css_set_taskexit(cset);
4859 static void check_for_release(struct cgroup *cgrp)
4861 if (cgroup_is_releasable(cgrp) &&
4862 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
4864 * Control Group is currently removeable. If it's not
4865 * already queued for a userspace notification, queue
4868 int need_schedule_work = 0;
4870 raw_spin_lock(&release_list_lock);
4871 if (!cgroup_is_dead(cgrp) &&
4872 list_empty(&cgrp->release_list)) {
4873 list_add(&cgrp->release_list, &release_list);
4874 need_schedule_work = 1;
4876 raw_spin_unlock(&release_list_lock);
4877 if (need_schedule_work)
4878 schedule_work(&release_agent_work);
4883 * Notify userspace when a cgroup is released, by running the
4884 * configured release agent with the name of the cgroup (path
4885 * relative to the root of cgroup file system) as the argument.
4887 * Most likely, this user command will try to rmdir this cgroup.
4889 * This races with the possibility that some other task will be
4890 * attached to this cgroup before it is removed, or that some other
4891 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
4892 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
4893 * unused, and this cgroup will be reprieved from its death sentence,
4894 * to continue to serve a useful existence. Next time it's released,
4895 * we will get notified again, if it still has 'notify_on_release' set.
4897 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
4898 * means only wait until the task is successfully execve()'d. The
4899 * separate release agent task is forked by call_usermodehelper(),
4900 * then control in this thread returns here, without waiting for the
4901 * release agent task. We don't bother to wait because the caller of
4902 * this routine has no use for the exit status of the release agent
4903 * task, so no sense holding our caller up for that.
4905 static void cgroup_release_agent(struct work_struct *work)
4907 BUG_ON(work != &release_agent_work);
4908 mutex_lock(&cgroup_mutex);
4909 raw_spin_lock(&release_list_lock);
4910 while (!list_empty(&release_list)) {
4911 char *argv[3], *envp[3];
4913 char *pathbuf = NULL, *agentbuf = NULL;
4914 struct cgroup *cgrp = list_entry(release_list.next,
4917 list_del_init(&cgrp->release_list);
4918 raw_spin_unlock(&release_list_lock);
4919 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4922 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
4924 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
4929 argv[i++] = agentbuf;
4930 argv[i++] = pathbuf;
4934 /* minimal command environment */
4935 envp[i++] = "HOME=/";
4936 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
4939 /* Drop the lock while we invoke the usermode helper,
4940 * since the exec could involve hitting disk and hence
4941 * be a slow process */
4942 mutex_unlock(&cgroup_mutex);
4943 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
4944 mutex_lock(&cgroup_mutex);
4948 raw_spin_lock(&release_list_lock);
4950 raw_spin_unlock(&release_list_lock);
4951 mutex_unlock(&cgroup_mutex);
4954 static int __init cgroup_disable(char *str)
4956 struct cgroup_subsys *ss;
4960 while ((token = strsep(&str, ",")) != NULL) {
4964 for_each_subsys(ss, i) {
4965 if (!strcmp(token, ss->name)) {
4967 printk(KERN_INFO "Disabling %s control group"
4968 " subsystem\n", ss->name);
4975 __setup("cgroup_disable=", cgroup_disable);
4978 * css_from_dir - get corresponding css from the dentry of a cgroup dir
4979 * @dentry: directory dentry of interest
4980 * @ss: subsystem of interest
4982 * Must be called under cgroup_mutex or RCU read lock. The caller is
4983 * responsible for pinning the returned css if it needs to be accessed
4984 * outside the critical section.
4986 struct cgroup_subsys_state *css_from_dir(struct dentry *dentry,
4987 struct cgroup_subsys *ss)
4989 struct cgroup *cgrp;
4991 cgroup_assert_mutex_or_rcu_locked();
4993 /* is @dentry a cgroup dir? */
4994 if (!dentry->d_inode ||
4995 dentry->d_inode->i_op != &cgroup_dir_inode_operations)
4996 return ERR_PTR(-EBADF);
4998 cgrp = __d_cgrp(dentry);
4999 return cgroup_css(cgrp, ss) ?: ERR_PTR(-ENOENT);
5003 * css_from_id - lookup css by id
5004 * @id: the cgroup id
5005 * @ss: cgroup subsys to be looked into
5007 * Returns the css if there's valid one with @id, otherwise returns NULL.
5008 * Should be called under rcu_read_lock().
5010 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5012 struct cgroup *cgrp;
5014 cgroup_assert_mutex_or_rcu_locked();
5016 cgrp = idr_find(&ss->root->cgroup_idr, id);
5018 return cgroup_css(cgrp, ss);
5022 #ifdef CONFIG_CGROUP_DEBUG
5023 static struct cgroup_subsys_state *
5024 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5026 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5029 return ERR_PTR(-ENOMEM);
5034 static void debug_css_free(struct cgroup_subsys_state *css)
5039 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5042 return cgroup_task_count(css->cgroup);
5045 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5048 return (u64)(unsigned long)current->cgroups;
5051 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5057 count = atomic_read(&task_css_set(current)->refcount);
5062 static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
5064 struct cgrp_cset_link *link;
5065 struct css_set *cset;
5067 read_lock(&css_set_lock);
5069 cset = rcu_dereference(current->cgroups);
5070 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5071 struct cgroup *c = link->cgrp;
5075 name = c->dentry->d_name.name;
5078 seq_printf(seq, "Root %d group %s\n",
5079 c->root->hierarchy_id, name);
5082 read_unlock(&css_set_lock);
5086 #define MAX_TASKS_SHOWN_PER_CSS 25
5087 static int cgroup_css_links_read(struct seq_file *seq, void *v)
5089 struct cgroup_subsys_state *css = seq_css(seq);
5090 struct cgrp_cset_link *link;
5092 read_lock(&css_set_lock);
5093 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5094 struct css_set *cset = link->cset;
5095 struct task_struct *task;
5097 seq_printf(seq, "css_set %p\n", cset);
5098 list_for_each_entry(task, &cset->tasks, cg_list) {
5099 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5100 seq_puts(seq, " ...\n");
5103 seq_printf(seq, " task %d\n",
5104 task_pid_vnr(task));
5108 read_unlock(&css_set_lock);
5112 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5114 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
5117 static struct cftype debug_files[] = {
5119 .name = "taskcount",
5120 .read_u64 = debug_taskcount_read,
5124 .name = "current_css_set",
5125 .read_u64 = current_css_set_read,
5129 .name = "current_css_set_refcount",
5130 .read_u64 = current_css_set_refcount_read,
5134 .name = "current_css_set_cg_links",
5135 .seq_show = current_css_set_cg_links_read,
5139 .name = "cgroup_css_links",
5140 .seq_show = cgroup_css_links_read,
5144 .name = "releasable",
5145 .read_u64 = releasable_read,
5151 struct cgroup_subsys debug_cgrp_subsys = {
5152 .css_alloc = debug_css_alloc,
5153 .css_free = debug_css_free,
5154 .base_cftypes = debug_files,
5156 #endif /* CONFIG_CGROUP_DEBUG */