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 mutex_lock(&cgroup_mutex);
854 idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
855 mutex_unlock(&cgroup_mutex);
858 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
860 struct cfent *cfe = __d_cfe(dentry);
861 struct cgroup *cgrp = dentry->d_parent->d_fsdata;
863 WARN_ONCE(!list_empty(&cfe->node) &&
864 cgrp != &cgrp->root->top_cgroup,
865 "cfe still linked for %s\n", cfe->type->name);
866 simple_xattrs_free(&cfe->xattrs);
872 static void remove_dir(struct dentry *d)
874 struct dentry *parent = dget(d->d_parent);
877 simple_rmdir(parent->d_inode, d);
881 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
885 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
886 lockdep_assert_held(&cgroup_mutex);
889 * If we're doing cleanup due to failure of cgroup_create(),
890 * the corresponding @cfe may not exist.
892 list_for_each_entry(cfe, &cgrp->files, node) {
893 struct dentry *d = cfe->dentry;
895 if (cft && cfe->type != cft)
900 simple_unlink(cgrp->dentry->d_inode, d);
901 list_del_init(&cfe->node);
909 * cgroup_clear_dir - remove subsys files in a cgroup directory
910 * @cgrp: target cgroup
911 * @subsys_mask: mask of the subsystem ids whose files should be removed
913 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned long subsys_mask)
915 struct cgroup_subsys *ss;
918 for_each_subsys(ss, i) {
919 struct cftype_set *set;
921 if (!test_bit(i, &subsys_mask))
923 list_for_each_entry(set, &ss->cftsets, node)
924 cgroup_addrm_files(cgrp, set->cfts, false);
929 * NOTE : the dentry must have been dget()'ed
931 static void cgroup_d_remove_dir(struct dentry *dentry)
933 struct dentry *parent;
935 parent = dentry->d_parent;
936 spin_lock(&parent->d_lock);
937 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
938 list_del_init(&dentry->d_u.d_child);
939 spin_unlock(&dentry->d_lock);
940 spin_unlock(&parent->d_lock);
944 static int rebind_subsystems(struct cgroupfs_root *root,
945 unsigned long added_mask, unsigned removed_mask)
947 struct cgroup *cgrp = &root->top_cgroup;
948 struct cgroup_subsys *ss;
951 BUG_ON(!mutex_is_locked(&cgroup_mutex));
953 /* Check that any added subsystems are currently free */
954 for_each_subsys(ss, i)
955 if ((added_mask & (1 << i)) && ss->root != &cgroup_dummy_root)
958 ret = cgroup_populate_dir(cgrp, added_mask);
963 * Nothing can fail from this point on. Remove files for the
964 * removed subsystems and rebind each subsystem.
966 cgroup_clear_dir(cgrp, removed_mask);
968 for_each_subsys(ss, i) {
969 unsigned long bit = 1UL << i;
971 if (bit & added_mask) {
972 /* We're binding this subsystem to this hierarchy */
973 BUG_ON(cgroup_css(cgrp, ss));
974 BUG_ON(!cgroup_css(cgroup_dummy_top, ss));
975 BUG_ON(cgroup_css(cgroup_dummy_top, ss)->cgroup != cgroup_dummy_top);
977 rcu_assign_pointer(cgrp->subsys[i],
978 cgroup_css(cgroup_dummy_top, ss));
979 cgroup_css(cgrp, ss)->cgroup = cgrp;
983 ss->bind(cgroup_css(cgrp, ss));
985 /* refcount was already taken, and we're keeping it */
986 root->subsys_mask |= bit;
987 } else if (bit & removed_mask) {
988 /* We're removing this subsystem */
989 BUG_ON(cgroup_css(cgrp, ss) != cgroup_css(cgroup_dummy_top, ss));
990 BUG_ON(cgroup_css(cgrp, ss)->cgroup != cgrp);
993 ss->bind(cgroup_css(cgroup_dummy_top, ss));
995 cgroup_css(cgroup_dummy_top, ss)->cgroup = cgroup_dummy_top;
996 RCU_INIT_POINTER(cgrp->subsys[i], NULL);
998 cgroup_subsys[i]->root = &cgroup_dummy_root;
999 root->subsys_mask &= ~bit;
1004 * Mark @root has finished binding subsystems. @root->subsys_mask
1005 * now matches the bound subsystems.
1007 root->flags |= CGRP_ROOT_SUBSYS_BOUND;
1012 static int cgroup_show_options(struct seq_file *seq, struct dentry *dentry)
1014 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
1015 struct cgroup_subsys *ss;
1018 for_each_subsys(ss, ssid)
1019 if (root->subsys_mask & (1 << ssid))
1020 seq_printf(seq, ",%s", ss->name);
1021 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1022 seq_puts(seq, ",sane_behavior");
1023 if (root->flags & CGRP_ROOT_NOPREFIX)
1024 seq_puts(seq, ",noprefix");
1025 if (root->flags & CGRP_ROOT_XATTR)
1026 seq_puts(seq, ",xattr");
1028 spin_lock(&release_agent_path_lock);
1029 if (strlen(root->release_agent_path))
1030 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1031 spin_unlock(&release_agent_path_lock);
1033 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1034 seq_puts(seq, ",clone_children");
1035 if (strlen(root->name))
1036 seq_printf(seq, ",name=%s", root->name);
1040 struct cgroup_sb_opts {
1041 unsigned long subsys_mask;
1042 unsigned long flags;
1043 char *release_agent;
1044 bool cpuset_clone_children;
1046 /* User explicitly requested empty subsystem */
1049 struct cgroupfs_root *new_root;
1054 * Convert a hierarchy specifier into a bitmask of subsystems and
1055 * flags. Call with cgroup_mutex held to protect the cgroup_subsys[]
1056 * array. This function takes refcounts on subsystems to be used, unless it
1057 * returns error, in which case no refcounts are taken.
1059 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1061 char *token, *o = data;
1062 bool all_ss = false, one_ss = false;
1063 unsigned long mask = (unsigned long)-1;
1064 struct cgroup_subsys *ss;
1067 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1069 #ifdef CONFIG_CPUSETS
1070 mask = ~(1UL << cpuset_cgrp_id);
1073 memset(opts, 0, sizeof(*opts));
1075 while ((token = strsep(&o, ",")) != NULL) {
1078 if (!strcmp(token, "none")) {
1079 /* Explicitly have no subsystems */
1083 if (!strcmp(token, "all")) {
1084 /* Mutually exclusive option 'all' + subsystem name */
1090 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1091 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1094 if (!strcmp(token, "noprefix")) {
1095 opts->flags |= CGRP_ROOT_NOPREFIX;
1098 if (!strcmp(token, "clone_children")) {
1099 opts->cpuset_clone_children = true;
1102 if (!strcmp(token, "xattr")) {
1103 opts->flags |= CGRP_ROOT_XATTR;
1106 if (!strncmp(token, "release_agent=", 14)) {
1107 /* Specifying two release agents is forbidden */
1108 if (opts->release_agent)
1110 opts->release_agent =
1111 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1112 if (!opts->release_agent)
1116 if (!strncmp(token, "name=", 5)) {
1117 const char *name = token + 5;
1118 /* Can't specify an empty name */
1121 /* Must match [\w.-]+ */
1122 for (i = 0; i < strlen(name); i++) {
1126 if ((c == '.') || (c == '-') || (c == '_'))
1130 /* Specifying two names is forbidden */
1133 opts->name = kstrndup(name,
1134 MAX_CGROUP_ROOT_NAMELEN - 1,
1142 for_each_subsys(ss, i) {
1143 if (strcmp(token, ss->name))
1148 /* Mutually exclusive option 'all' + subsystem name */
1151 set_bit(i, &opts->subsys_mask);
1156 if (i == CGROUP_SUBSYS_COUNT)
1161 * If the 'all' option was specified select all the subsystems,
1162 * otherwise if 'none', 'name=' and a subsystem name options
1163 * were not specified, let's default to 'all'
1165 if (all_ss || (!one_ss && !opts->none && !opts->name))
1166 for_each_subsys(ss, i)
1168 set_bit(i, &opts->subsys_mask);
1170 /* Consistency checks */
1172 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1173 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1175 if (opts->flags & CGRP_ROOT_NOPREFIX) {
1176 pr_err("cgroup: sane_behavior: noprefix is not allowed\n");
1180 if (opts->cpuset_clone_children) {
1181 pr_err("cgroup: sane_behavior: clone_children is not allowed\n");
1187 * Option noprefix was introduced just for backward compatibility
1188 * with the old cpuset, so we allow noprefix only if mounting just
1189 * the cpuset subsystem.
1191 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1195 /* Can't specify "none" and some subsystems */
1196 if (opts->subsys_mask && opts->none)
1200 * We either have to specify by name or by subsystems. (So all
1201 * empty hierarchies must have a name).
1203 if (!opts->subsys_mask && !opts->name)
1209 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1212 struct cgroupfs_root *root = sb->s_fs_info;
1213 struct cgroup *cgrp = &root->top_cgroup;
1214 struct cgroup_sb_opts opts;
1215 unsigned long added_mask, removed_mask;
1217 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1218 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1222 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1223 mutex_lock(&cgroup_mutex);
1225 /* See what subsystems are wanted */
1226 ret = parse_cgroupfs_options(data, &opts);
1230 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1231 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1232 task_tgid_nr(current), current->comm);
1234 added_mask = opts.subsys_mask & ~root->subsys_mask;
1235 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1237 /* Don't allow flags or name to change at remount */
1238 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1239 (opts.name && strcmp(opts.name, root->name))) {
1240 pr_err("cgroup: option or name mismatch, new: 0x%lx \"%s\", old: 0x%lx \"%s\"\n",
1241 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1242 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1247 /* remounting is not allowed for populated hierarchies */
1248 if (root->number_of_cgroups > 1) {
1253 ret = rebind_subsystems(root, added_mask, removed_mask);
1257 if (opts.release_agent) {
1258 spin_lock(&release_agent_path_lock);
1259 strcpy(root->release_agent_path, opts.release_agent);
1260 spin_unlock(&release_agent_path_lock);
1263 kfree(opts.release_agent);
1265 mutex_unlock(&cgroup_mutex);
1266 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1270 static const struct super_operations cgroup_ops = {
1271 .statfs = simple_statfs,
1272 .drop_inode = generic_delete_inode,
1273 .show_options = cgroup_show_options,
1274 .remount_fs = cgroup_remount,
1277 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1279 INIT_LIST_HEAD(&cgrp->sibling);
1280 INIT_LIST_HEAD(&cgrp->children);
1281 INIT_LIST_HEAD(&cgrp->files);
1282 INIT_LIST_HEAD(&cgrp->cset_links);
1283 INIT_LIST_HEAD(&cgrp->release_list);
1284 INIT_LIST_HEAD(&cgrp->pidlists);
1285 mutex_init(&cgrp->pidlist_mutex);
1286 cgrp->dummy_css.cgroup = cgrp;
1287 simple_xattrs_init(&cgrp->xattrs);
1290 static void init_cgroup_root(struct cgroupfs_root *root)
1292 struct cgroup *cgrp = &root->top_cgroup;
1294 INIT_LIST_HEAD(&root->root_list);
1295 root->number_of_cgroups = 1;
1297 RCU_INIT_POINTER(cgrp->name, &root_cgroup_name);
1298 init_cgroup_housekeeping(cgrp);
1299 idr_init(&root->cgroup_idr);
1302 static int cgroup_init_root_id(struct cgroupfs_root *root, int start, int end)
1306 lockdep_assert_held(&cgroup_mutex);
1308 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, start, end,
1313 root->hierarchy_id = id;
1317 static void cgroup_exit_root_id(struct cgroupfs_root *root)
1319 lockdep_assert_held(&cgroup_mutex);
1321 if (root->hierarchy_id) {
1322 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1323 root->hierarchy_id = 0;
1327 static int cgroup_test_super(struct super_block *sb, void *data)
1329 struct cgroup_sb_opts *opts = data;
1330 struct cgroupfs_root *root = sb->s_fs_info;
1332 /* If we asked for a name then it must match */
1333 if (opts->name && strcmp(opts->name, root->name))
1337 * If we asked for subsystems (or explicitly for no
1338 * subsystems) then they must match
1340 if ((opts->subsys_mask || opts->none)
1341 && (opts->subsys_mask != root->subsys_mask))
1347 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1349 struct cgroupfs_root *root;
1351 if (!opts->subsys_mask && !opts->none)
1354 root = kzalloc(sizeof(*root), GFP_KERNEL);
1356 return ERR_PTR(-ENOMEM);
1358 init_cgroup_root(root);
1361 * We need to set @root->subsys_mask now so that @root can be
1362 * matched by cgroup_test_super() before it finishes
1363 * initialization; otherwise, competing mounts with the same
1364 * options may try to bind the same subsystems instead of waiting
1365 * for the first one leading to unexpected mount errors.
1366 * SUBSYS_BOUND will be set once actual binding is complete.
1368 root->subsys_mask = opts->subsys_mask;
1369 root->flags = opts->flags;
1370 if (opts->release_agent)
1371 strcpy(root->release_agent_path, opts->release_agent);
1373 strcpy(root->name, opts->name);
1374 if (opts->cpuset_clone_children)
1375 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1379 static void cgroup_free_root(struct cgroupfs_root *root)
1382 /* hierarhcy ID shoulid already have been released */
1383 WARN_ON_ONCE(root->hierarchy_id);
1385 idr_destroy(&root->cgroup_idr);
1390 static int cgroup_set_super(struct super_block *sb, void *data)
1393 struct cgroup_sb_opts *opts = data;
1395 /* If we don't have a new root, we can't set up a new sb */
1396 if (!opts->new_root)
1399 BUG_ON(!opts->subsys_mask && !opts->none);
1401 ret = set_anon_super(sb, NULL);
1405 sb->s_fs_info = opts->new_root;
1406 opts->new_root->sb = sb;
1408 sb->s_blocksize = PAGE_CACHE_SIZE;
1409 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1410 sb->s_magic = CGROUP_SUPER_MAGIC;
1411 sb->s_op = &cgroup_ops;
1416 static int cgroup_get_rootdir(struct super_block *sb)
1418 static const struct dentry_operations cgroup_dops = {
1419 .d_iput = cgroup_diput,
1420 .d_delete = always_delete_dentry,
1423 struct inode *inode =
1424 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1429 inode->i_fop = &simple_dir_operations;
1430 inode->i_op = &cgroup_dir_inode_operations;
1431 /* directories start off with i_nlink == 2 (for "." entry) */
1433 sb->s_root = d_make_root(inode);
1436 /* for everything else we want ->d_op set */
1437 sb->s_d_op = &cgroup_dops;
1441 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1442 int flags, const char *unused_dev_name,
1445 struct cgroup_sb_opts opts;
1446 struct cgroupfs_root *root;
1448 struct super_block *sb;
1449 struct cgroupfs_root *new_root;
1450 struct list_head tmp_links;
1451 struct inode *inode;
1452 const struct cred *cred;
1454 /* First find the desired set of subsystems */
1455 mutex_lock(&cgroup_mutex);
1456 ret = parse_cgroupfs_options(data, &opts);
1457 mutex_unlock(&cgroup_mutex);
1462 * Allocate a new cgroup root. We may not need it if we're
1463 * reusing an existing hierarchy.
1465 new_root = cgroup_root_from_opts(&opts);
1466 if (IS_ERR(new_root)) {
1467 ret = PTR_ERR(new_root);
1470 opts.new_root = new_root;
1472 /* Locate an existing or new sb for this hierarchy */
1473 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1476 cgroup_free_root(opts.new_root);
1480 root = sb->s_fs_info;
1482 if (root == opts.new_root) {
1483 /* We used the new root structure, so this is a new hierarchy */
1484 struct cgroup *root_cgrp = &root->top_cgroup;
1485 struct cgroupfs_root *existing_root;
1487 struct css_set *cset;
1489 BUG_ON(sb->s_root != NULL);
1491 ret = cgroup_get_rootdir(sb);
1493 goto drop_new_super;
1494 inode = sb->s_root->d_inode;
1496 mutex_lock(&inode->i_mutex);
1497 mutex_lock(&cgroup_mutex);
1499 ret = idr_alloc(&root->cgroup_idr, root_cgrp, 0, 1, GFP_KERNEL);
1502 root_cgrp->id = ret;
1504 /* Check for name clashes with existing mounts */
1506 if (strlen(root->name))
1507 for_each_active_root(existing_root)
1508 if (!strcmp(existing_root->name, root->name))
1512 * We're accessing css_set_count without locking
1513 * css_set_lock here, but that's OK - it can only be
1514 * increased by someone holding cgroup_lock, and
1515 * that's us. The worst that can happen is that we
1516 * have some link structures left over
1518 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1522 /* ID 0 is reserved for dummy root, 1 for unified hierarchy */
1523 ret = cgroup_init_root_id(root, 2, 0);
1527 sb->s_root->d_fsdata = root_cgrp;
1528 root_cgrp->dentry = sb->s_root;
1531 * We're inside get_sb() and will call lookup_one_len() to
1532 * create the root files, which doesn't work if SELinux is
1533 * in use. The following cred dancing somehow works around
1534 * it. See 2ce9738ba ("cgroupfs: use init_cred when
1535 * populating new cgroupfs mount") for more details.
1537 cred = override_creds(&init_cred);
1539 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1543 ret = rebind_subsystems(root, root->subsys_mask, 0);
1550 * There must be no failure case after here, since rebinding
1551 * takes care of subsystems' refcounts, which are explicitly
1552 * dropped in the failure exit path.
1555 list_add(&root->root_list, &cgroup_roots);
1556 cgroup_root_count++;
1558 /* Link the top cgroup in this hierarchy into all
1559 * the css_set objects */
1560 write_lock(&css_set_lock);
1561 hash_for_each(css_set_table, i, cset, hlist)
1562 link_css_set(&tmp_links, cset, root_cgrp);
1563 write_unlock(&css_set_lock);
1565 free_cgrp_cset_links(&tmp_links);
1567 BUG_ON(!list_empty(&root_cgrp->children));
1568 BUG_ON(root->number_of_cgroups != 1);
1570 mutex_unlock(&cgroup_mutex);
1571 mutex_unlock(&inode->i_mutex);
1574 * We re-used an existing hierarchy - the new root (if
1575 * any) is not needed
1577 cgroup_free_root(opts.new_root);
1579 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1580 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1581 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1583 goto drop_new_super;
1585 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1590 kfree(opts.release_agent);
1592 return dget(sb->s_root);
1595 free_cgrp_cset_links(&tmp_links);
1596 cgroup_addrm_files(&root->top_cgroup, cgroup_base_files, false);
1599 cgroup_exit_root_id(root);
1600 mutex_unlock(&cgroup_mutex);
1601 mutex_unlock(&inode->i_mutex);
1603 deactivate_locked_super(sb);
1605 kfree(opts.release_agent);
1607 return ERR_PTR(ret);
1610 static void cgroup_kill_sb(struct super_block *sb)
1612 struct cgroupfs_root *root = sb->s_fs_info;
1613 struct cgroup *cgrp = &root->top_cgroup;
1614 struct cgrp_cset_link *link, *tmp_link;
1619 BUG_ON(root->number_of_cgroups != 1);
1620 BUG_ON(!list_empty(&cgrp->children));
1622 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1623 mutex_lock(&cgroup_mutex);
1625 /* Rebind all subsystems back to the default hierarchy */
1626 if (root->flags & CGRP_ROOT_SUBSYS_BOUND) {
1627 ret = rebind_subsystems(root, 0, root->subsys_mask);
1628 /* Shouldn't be able to fail ... */
1633 * Release all the links from cset_links to this hierarchy's
1636 write_lock(&css_set_lock);
1638 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1639 list_del(&link->cset_link);
1640 list_del(&link->cgrp_link);
1643 write_unlock(&css_set_lock);
1645 if (!list_empty(&root->root_list)) {
1646 list_del(&root->root_list);
1647 cgroup_root_count--;
1650 cgroup_exit_root_id(root);
1652 mutex_unlock(&cgroup_mutex);
1653 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1655 simple_xattrs_free(&cgrp->xattrs);
1657 kill_litter_super(sb);
1658 cgroup_free_root(root);
1661 static struct file_system_type cgroup_fs_type = {
1663 .mount = cgroup_mount,
1664 .kill_sb = cgroup_kill_sb,
1667 static struct kobject *cgroup_kobj;
1670 * cgroup_path - generate the path of a cgroup
1671 * @cgrp: the cgroup in question
1672 * @buf: the buffer to write the path into
1673 * @buflen: the length of the buffer
1675 * Writes path of cgroup into buf. Returns 0 on success, -errno on error.
1677 * We can't generate cgroup path using dentry->d_name, as accessing
1678 * dentry->name must be protected by irq-unsafe dentry->d_lock or parent
1679 * inode's i_mutex, while on the other hand cgroup_path() can be called
1680 * with some irq-safe spinlocks held.
1682 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1684 int ret = -ENAMETOOLONG;
1687 if (!cgrp->parent) {
1688 if (strlcpy(buf, "/", buflen) >= buflen)
1689 return -ENAMETOOLONG;
1693 start = buf + buflen - 1;
1698 const char *name = cgroup_name(cgrp);
1702 if ((start -= len) < buf)
1704 memcpy(start, name, len);
1710 cgrp = cgrp->parent;
1711 } while (cgrp->parent);
1713 memmove(buf, start, buf + buflen - start);
1718 EXPORT_SYMBOL_GPL(cgroup_path);
1721 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1722 * @task: target task
1723 * @buf: the buffer to write the path into
1724 * @buflen: the length of the buffer
1726 * Determine @task's cgroup on the first (the one with the lowest non-zero
1727 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1728 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1729 * cgroup controller callbacks.
1731 * Returns 0 on success, fails with -%ENAMETOOLONG if @buflen is too short.
1733 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1735 struct cgroupfs_root *root;
1736 struct cgroup *cgrp;
1737 int hierarchy_id = 1, ret = 0;
1740 return -ENAMETOOLONG;
1742 mutex_lock(&cgroup_mutex);
1744 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1747 cgrp = task_cgroup_from_root(task, root);
1748 ret = cgroup_path(cgrp, buf, buflen);
1750 /* if no hierarchy exists, everyone is in "/" */
1751 memcpy(buf, "/", 2);
1754 mutex_unlock(&cgroup_mutex);
1757 EXPORT_SYMBOL_GPL(task_cgroup_path);
1760 * Control Group taskset
1762 struct task_and_cgroup {
1763 struct task_struct *task;
1764 struct cgroup *cgrp;
1765 struct css_set *cset;
1768 struct cgroup_taskset {
1769 struct task_and_cgroup single;
1770 struct flex_array *tc_array;
1773 struct cgroup *cur_cgrp;
1777 * cgroup_taskset_first - reset taskset and return the first task
1778 * @tset: taskset of interest
1780 * @tset iteration is initialized and the first task is returned.
1782 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1784 if (tset->tc_array) {
1786 return cgroup_taskset_next(tset);
1788 tset->cur_cgrp = tset->single.cgrp;
1789 return tset->single.task;
1792 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1795 * cgroup_taskset_next - iterate to the next task in taskset
1796 * @tset: taskset of interest
1798 * Return the next task in @tset. Iteration must have been initialized
1799 * with cgroup_taskset_first().
1801 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1803 struct task_and_cgroup *tc;
1805 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1808 tc = flex_array_get(tset->tc_array, tset->idx++);
1809 tset->cur_cgrp = tc->cgrp;
1812 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1815 * cgroup_taskset_cur_css - return the matching css for the current task
1816 * @tset: taskset of interest
1817 * @subsys_id: the ID of the target subsystem
1819 * Return the css for the current (last returned) task of @tset for
1820 * subsystem specified by @subsys_id. This function must be preceded by
1821 * either cgroup_taskset_first() or cgroup_taskset_next().
1823 struct cgroup_subsys_state *cgroup_taskset_cur_css(struct cgroup_taskset *tset,
1826 return cgroup_css(tset->cur_cgrp, cgroup_subsys[subsys_id]);
1828 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_css);
1831 * cgroup_taskset_size - return the number of tasks in taskset
1832 * @tset: taskset of interest
1834 int cgroup_taskset_size(struct cgroup_taskset *tset)
1836 return tset->tc_array ? tset->tc_array_len : 1;
1838 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1842 * cgroup_task_migrate - move a task from one cgroup to another.
1844 * Must be called with cgroup_mutex and threadgroup locked.
1846 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1847 struct task_struct *tsk,
1848 struct css_set *new_cset)
1850 struct css_set *old_cset;
1853 * We are synchronized through threadgroup_lock() against PF_EXITING
1854 * setting such that we can't race against cgroup_exit() changing the
1855 * css_set to init_css_set and dropping the old one.
1857 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1858 old_cset = task_css_set(tsk);
1861 rcu_assign_pointer(tsk->cgroups, new_cset);
1864 /* Update the css_set linked lists if we're using them */
1865 write_lock(&css_set_lock);
1866 if (!list_empty(&tsk->cg_list))
1867 list_move(&tsk->cg_list, &new_cset->tasks);
1868 write_unlock(&css_set_lock);
1871 * We just gained a reference on old_cset by taking it from the
1872 * task. As trading it for new_cset is protected by cgroup_mutex,
1873 * we're safe to drop it here; it will be freed under RCU.
1875 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1876 put_css_set(old_cset);
1880 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1881 * @cgrp: the cgroup to attach to
1882 * @tsk: the task or the leader of the threadgroup to be attached
1883 * @threadgroup: attach the whole threadgroup?
1885 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
1886 * task_lock of @tsk or each thread in the threadgroup individually in turn.
1888 static int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk,
1891 int retval, i, group_size;
1892 struct cgroupfs_root *root = cgrp->root;
1893 struct cgroup_subsys_state *css, *failed_css = NULL;
1894 /* threadgroup list cursor and array */
1895 struct task_struct *leader = tsk;
1896 struct task_and_cgroup *tc;
1897 struct flex_array *group;
1898 struct cgroup_taskset tset = { };
1901 * step 0: in order to do expensive, possibly blocking operations for
1902 * every thread, we cannot iterate the thread group list, since it needs
1903 * rcu or tasklist locked. instead, build an array of all threads in the
1904 * group - group_rwsem prevents new threads from appearing, and if
1905 * threads exit, this will just be an over-estimate.
1908 group_size = get_nr_threads(tsk);
1911 /* flex_array supports very large thread-groups better than kmalloc. */
1912 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
1915 /* pre-allocate to guarantee space while iterating in rcu read-side. */
1916 retval = flex_array_prealloc(group, 0, group_size, GFP_KERNEL);
1918 goto out_free_group_list;
1922 * Prevent freeing of tasks while we take a snapshot. Tasks that are
1923 * already PF_EXITING could be freed from underneath us unless we
1924 * take an rcu_read_lock.
1928 struct task_and_cgroup ent;
1930 /* @tsk either already exited or can't exit until the end */
1931 if (tsk->flags & PF_EXITING)
1934 /* as per above, nr_threads may decrease, but not increase. */
1935 BUG_ON(i >= group_size);
1937 ent.cgrp = task_cgroup_from_root(tsk, root);
1938 /* nothing to do if this task is already in the cgroup */
1939 if (ent.cgrp == cgrp)
1942 * saying GFP_ATOMIC has no effect here because we did prealloc
1943 * earlier, but it's good form to communicate our expectations.
1945 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
1946 BUG_ON(retval != 0);
1951 } while_each_thread(leader, tsk);
1953 /* remember the number of threads in the array for later. */
1955 tset.tc_array = group;
1956 tset.tc_array_len = group_size;
1958 /* methods shouldn't be called if no task is actually migrating */
1961 goto out_free_group_list;
1964 * step 1: check that we can legitimately attach to the cgroup.
1966 for_each_css(css, i, cgrp) {
1967 if (css->ss->can_attach) {
1968 retval = css->ss->can_attach(css, &tset);
1971 goto out_cancel_attach;
1977 * step 2: make sure css_sets exist for all threads to be migrated.
1978 * we use find_css_set, which allocates a new one if necessary.
1980 for (i = 0; i < group_size; i++) {
1981 struct css_set *old_cset;
1983 tc = flex_array_get(group, i);
1984 old_cset = task_css_set(tc->task);
1985 tc->cset = find_css_set(old_cset, cgrp);
1988 goto out_put_css_set_refs;
1993 * step 3: now that we're guaranteed success wrt the css_sets,
1994 * proceed to move all tasks to the new cgroup. There are no
1995 * failure cases after here, so this is the commit point.
1997 for (i = 0; i < group_size; i++) {
1998 tc = flex_array_get(group, i);
1999 cgroup_task_migrate(tc->cgrp, tc->task, tc->cset);
2001 /* nothing is sensitive to fork() after this point. */
2004 * step 4: do subsystem attach callbacks.
2006 for_each_css(css, i, cgrp)
2007 if (css->ss->attach)
2008 css->ss->attach(css, &tset);
2011 * step 5: success! and cleanup
2014 out_put_css_set_refs:
2016 for (i = 0; i < group_size; i++) {
2017 tc = flex_array_get(group, i);
2020 put_css_set(tc->cset);
2025 for_each_css(css, i, cgrp) {
2026 if (css == failed_css)
2028 if (css->ss->cancel_attach)
2029 css->ss->cancel_attach(css, &tset);
2032 out_free_group_list:
2033 flex_array_free(group);
2038 * Find the task_struct of the task to attach by vpid and pass it along to the
2039 * function to attach either it or all tasks in its threadgroup. Will lock
2040 * cgroup_mutex and threadgroup; may take task_lock of task.
2042 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2044 struct task_struct *tsk;
2045 const struct cred *cred = current_cred(), *tcred;
2048 if (!cgroup_lock_live_group(cgrp))
2054 tsk = find_task_by_vpid(pid);
2058 goto out_unlock_cgroup;
2061 * even if we're attaching all tasks in the thread group, we
2062 * only need to check permissions on one of them.
2064 tcred = __task_cred(tsk);
2065 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2066 !uid_eq(cred->euid, tcred->uid) &&
2067 !uid_eq(cred->euid, tcred->suid)) {
2070 goto out_unlock_cgroup;
2076 tsk = tsk->group_leader;
2079 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2080 * trapped in a cpuset, or RT worker may be born in a cgroup
2081 * with no rt_runtime allocated. Just say no.
2083 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2086 goto out_unlock_cgroup;
2089 get_task_struct(tsk);
2092 threadgroup_lock(tsk);
2094 if (!thread_group_leader(tsk)) {
2096 * a race with de_thread from another thread's exec()
2097 * may strip us of our leadership, if this happens,
2098 * there is no choice but to throw this task away and
2099 * try again; this is
2100 * "double-double-toil-and-trouble-check locking".
2102 threadgroup_unlock(tsk);
2103 put_task_struct(tsk);
2104 goto retry_find_task;
2108 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2110 threadgroup_unlock(tsk);
2112 put_task_struct(tsk);
2114 mutex_unlock(&cgroup_mutex);
2119 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2120 * @from: attach to all cgroups of a given task
2121 * @tsk: the task to be attached
2123 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2125 struct cgroupfs_root *root;
2128 mutex_lock(&cgroup_mutex);
2129 for_each_active_root(root) {
2130 struct cgroup *from_cgrp = task_cgroup_from_root(from, root);
2132 retval = cgroup_attach_task(from_cgrp, tsk, false);
2136 mutex_unlock(&cgroup_mutex);
2140 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2142 static int cgroup_tasks_write(struct cgroup_subsys_state *css,
2143 struct cftype *cft, u64 pid)
2145 return attach_task_by_pid(css->cgroup, pid, false);
2148 static int cgroup_procs_write(struct cgroup_subsys_state *css,
2149 struct cftype *cft, u64 tgid)
2151 return attach_task_by_pid(css->cgroup, tgid, true);
2154 static int cgroup_release_agent_write(struct cgroup_subsys_state *css,
2155 struct cftype *cft, const char *buffer)
2157 BUILD_BUG_ON(sizeof(css->cgroup->root->release_agent_path) < PATH_MAX);
2158 if (strlen(buffer) >= PATH_MAX)
2160 if (!cgroup_lock_live_group(css->cgroup))
2162 spin_lock(&release_agent_path_lock);
2163 strcpy(css->cgroup->root->release_agent_path, buffer);
2164 spin_unlock(&release_agent_path_lock);
2165 mutex_unlock(&cgroup_mutex);
2169 static int cgroup_release_agent_show(struct seq_file *seq, void *v)
2171 struct cgroup *cgrp = seq_css(seq)->cgroup;
2173 if (!cgroup_lock_live_group(cgrp))
2175 seq_puts(seq, cgrp->root->release_agent_path);
2176 seq_putc(seq, '\n');
2177 mutex_unlock(&cgroup_mutex);
2181 static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
2183 struct cgroup *cgrp = seq_css(seq)->cgroup;
2185 seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
2189 /* A buffer size big enough for numbers or short strings */
2190 #define CGROUP_LOCAL_BUFFER_SIZE 64
2192 static ssize_t cgroup_file_write(struct file *file, const char __user *userbuf,
2193 size_t nbytes, loff_t *ppos)
2195 struct cfent *cfe = __d_cfe(file->f_dentry);
2196 struct cftype *cft = __d_cft(file->f_dentry);
2197 struct cgroup_subsys_state *css = cfe->css;
2198 size_t max_bytes = cft->max_write_len ?: CGROUP_LOCAL_BUFFER_SIZE - 1;
2202 if (nbytes >= max_bytes)
2205 buf = kmalloc(nbytes + 1, GFP_KERNEL);
2209 if (copy_from_user(buf, userbuf, nbytes)) {
2216 if (cft->write_string) {
2217 ret = cft->write_string(css, cft, strstrip(buf));
2218 } else if (cft->write_u64) {
2219 unsigned long long v;
2220 ret = kstrtoull(buf, 0, &v);
2222 ret = cft->write_u64(css, cft, v);
2223 } else if (cft->write_s64) {
2225 ret = kstrtoll(buf, 0, &v);
2227 ret = cft->write_s64(css, cft, v);
2228 } else if (cft->trigger) {
2229 ret = cft->trigger(css, (unsigned int)cft->private);
2235 return ret ?: nbytes;
2239 * seqfile ops/methods for returning structured data. Currently just
2240 * supports string->u64 maps, but can be extended in future.
2243 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
2245 struct cftype *cft = seq_cft(seq);
2247 if (cft->seq_start) {
2248 return cft->seq_start(seq, ppos);
2251 * The same behavior and code as single_open(). Returns
2252 * !NULL if pos is at the beginning; otherwise, NULL.
2254 return NULL + !*ppos;
2258 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
2260 struct cftype *cft = seq_cft(seq);
2262 if (cft->seq_next) {
2263 return cft->seq_next(seq, v, ppos);
2266 * The same behavior and code as single_open(), always
2267 * terminate after the initial read.
2274 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
2276 struct cftype *cft = seq_cft(seq);
2279 cft->seq_stop(seq, v);
2282 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2284 struct cftype *cft = seq_cft(m);
2285 struct cgroup_subsys_state *css = seq_css(m);
2288 return cft->seq_show(m, arg);
2291 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
2292 else if (cft->read_s64)
2293 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
2299 static struct seq_operations cgroup_seq_operations = {
2300 .start = cgroup_seqfile_start,
2301 .next = cgroup_seqfile_next,
2302 .stop = cgroup_seqfile_stop,
2303 .show = cgroup_seqfile_show,
2306 static int cgroup_file_open(struct inode *inode, struct file *file)
2308 struct cfent *cfe = __d_cfe(file->f_dentry);
2309 struct cftype *cft = __d_cft(file->f_dentry);
2310 struct cgroup *cgrp = __d_cgrp(cfe->dentry->d_parent);
2311 struct cgroup_subsys_state *css;
2312 struct cgroup_open_file *of;
2315 err = generic_file_open(inode, file);
2320 * If the file belongs to a subsystem, pin the css. Will be
2321 * unpinned either on open failure or release. This ensures that
2322 * @css stays alive for all file operations.
2325 css = cgroup_css(cgrp, cft->ss);
2326 if (cft->ss && !css_tryget(css))
2334 * @cfe->css is used by read/write/close to determine the
2335 * associated css. @file->private_data would be a better place but
2336 * that's already used by seqfile. Multiple accessors may use it
2337 * simultaneously which is okay as the association never changes.
2339 WARN_ON_ONCE(cfe->css && cfe->css != css);
2342 of = __seq_open_private(file, &cgroup_seq_operations,
2343 sizeof(struct cgroup_open_file));
2354 static int cgroup_file_release(struct inode *inode, struct file *file)
2356 struct cfent *cfe = __d_cfe(file->f_dentry);
2357 struct cgroup_subsys_state *css = cfe->css;
2361 return seq_release_private(inode, file);
2365 * cgroup_rename - Only allow simple rename of directories in place.
2367 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2368 struct inode *new_dir, struct dentry *new_dentry)
2371 struct cgroup_name *name, *old_name;
2372 struct cgroup *cgrp;
2375 * It's convinient to use parent dir's i_mutex to protected
2378 lockdep_assert_held(&old_dir->i_mutex);
2380 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2382 if (new_dentry->d_inode)
2384 if (old_dir != new_dir)
2387 cgrp = __d_cgrp(old_dentry);
2390 * This isn't a proper migration and its usefulness is very
2391 * limited. Disallow if sane_behavior.
2393 if (cgroup_sane_behavior(cgrp))
2396 name = cgroup_alloc_name(new_dentry);
2400 ret = simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2406 old_name = rcu_dereference_protected(cgrp->name, true);
2407 rcu_assign_pointer(cgrp->name, name);
2409 kfree_rcu(old_name, rcu_head);
2413 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2415 if (S_ISDIR(dentry->d_inode->i_mode))
2416 return &__d_cgrp(dentry)->xattrs;
2418 return &__d_cfe(dentry)->xattrs;
2421 static inline int xattr_enabled(struct dentry *dentry)
2423 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2424 return root->flags & CGRP_ROOT_XATTR;
2427 static bool is_valid_xattr(const char *name)
2429 if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2430 !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2435 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2436 const void *val, size_t size, int flags)
2438 if (!xattr_enabled(dentry))
2440 if (!is_valid_xattr(name))
2442 return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2445 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2447 if (!xattr_enabled(dentry))
2449 if (!is_valid_xattr(name))
2451 return simple_xattr_remove(__d_xattrs(dentry), name);
2454 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2455 void *buf, size_t size)
2457 if (!xattr_enabled(dentry))
2459 if (!is_valid_xattr(name))
2461 return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2464 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2466 if (!xattr_enabled(dentry))
2468 return simple_xattr_list(__d_xattrs(dentry), buf, size);
2471 static const struct file_operations cgroup_file_operations = {
2473 .write = cgroup_file_write,
2474 .llseek = generic_file_llseek,
2475 .open = cgroup_file_open,
2476 .release = cgroup_file_release,
2479 static const struct inode_operations cgroup_file_inode_operations = {
2480 .setxattr = cgroup_setxattr,
2481 .getxattr = cgroup_getxattr,
2482 .listxattr = cgroup_listxattr,
2483 .removexattr = cgroup_removexattr,
2486 static const struct inode_operations cgroup_dir_inode_operations = {
2487 .lookup = simple_lookup,
2488 .mkdir = cgroup_mkdir,
2489 .rmdir = cgroup_rmdir,
2490 .rename = cgroup_rename,
2491 .setxattr = cgroup_setxattr,
2492 .getxattr = cgroup_getxattr,
2493 .listxattr = cgroup_listxattr,
2494 .removexattr = cgroup_removexattr,
2497 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2498 struct super_block *sb)
2500 struct inode *inode;
2504 if (dentry->d_inode)
2507 inode = cgroup_new_inode(mode, sb);
2511 if (S_ISDIR(mode)) {
2512 inode->i_op = &cgroup_dir_inode_operations;
2513 inode->i_fop = &simple_dir_operations;
2515 /* start off with i_nlink == 2 (for "." entry) */
2517 inc_nlink(dentry->d_parent->d_inode);
2520 * Control reaches here with cgroup_mutex held.
2521 * @inode->i_mutex should nest outside cgroup_mutex but we
2522 * want to populate it immediately without releasing
2523 * cgroup_mutex. As @inode isn't visible to anyone else
2524 * yet, trylock will always succeed without affecting
2527 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2528 } else if (S_ISREG(mode)) {
2530 inode->i_fop = &cgroup_file_operations;
2531 inode->i_op = &cgroup_file_inode_operations;
2533 d_instantiate(dentry, inode);
2534 dget(dentry); /* Extra count - pin the dentry in core */
2539 * cgroup_file_mode - deduce file mode of a control file
2540 * @cft: the control file in question
2542 * returns cft->mode if ->mode is not 0
2543 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2544 * returns S_IRUGO if it has only a read handler
2545 * returns S_IWUSR if it has only a write hander
2547 static umode_t cgroup_file_mode(const struct cftype *cft)
2554 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
2557 if (cft->write_u64 || cft->write_s64 || cft->write_string ||
2564 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2566 struct dentry *dir = cgrp->dentry;
2567 struct cgroup *parent = __d_cgrp(dir);
2568 struct dentry *dentry;
2572 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2574 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
2575 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
2576 strcpy(name, cft->ss->name);
2579 strcat(name, cft->name);
2581 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2583 cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2587 dentry = lookup_one_len(name, dir, strlen(name));
2588 if (IS_ERR(dentry)) {
2589 error = PTR_ERR(dentry);
2593 cfe->type = (void *)cft;
2594 cfe->dentry = dentry;
2595 dentry->d_fsdata = cfe;
2596 simple_xattrs_init(&cfe->xattrs);
2598 mode = cgroup_file_mode(cft);
2599 error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2601 list_add_tail(&cfe->node, &parent->files);
2611 * cgroup_addrm_files - add or remove files to a cgroup directory
2612 * @cgrp: the target cgroup
2613 * @cfts: array of cftypes to be added
2614 * @is_add: whether to add or remove
2616 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2617 * For removals, this function never fails. If addition fails, this
2618 * function doesn't remove files already added. The caller is responsible
2621 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2627 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
2628 lockdep_assert_held(&cgroup_mutex);
2630 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2631 /* does cft->flags tell us to skip this file on @cgrp? */
2632 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2634 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2636 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2640 ret = cgroup_add_file(cgrp, cft);
2642 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2647 cgroup_rm_file(cgrp, cft);
2653 static void cgroup_cfts_prepare(void)
2654 __acquires(&cgroup_mutex)
2657 * Thanks to the entanglement with vfs inode locking, we can't walk
2658 * the existing cgroups under cgroup_mutex and create files.
2659 * Instead, we use css_for_each_descendant_pre() and drop RCU read
2660 * lock before calling cgroup_addrm_files().
2662 mutex_lock(&cgroup_mutex);
2665 static int cgroup_cfts_commit(struct cftype *cfts, bool is_add)
2666 __releases(&cgroup_mutex)
2669 struct cgroup_subsys *ss = cfts[0].ss;
2670 struct cgroup *root = &ss->root->top_cgroup;
2671 struct super_block *sb = ss->root->sb;
2672 struct dentry *prev = NULL;
2673 struct inode *inode;
2674 struct cgroup_subsys_state *css;
2678 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2679 if (!cfts || ss->root == &cgroup_dummy_root ||
2680 !atomic_inc_not_zero(&sb->s_active)) {
2681 mutex_unlock(&cgroup_mutex);
2686 * All cgroups which are created after we drop cgroup_mutex will
2687 * have the updated set of files, so we only need to update the
2688 * cgroups created before the current @cgroup_serial_nr_next.
2690 update_before = cgroup_serial_nr_next;
2692 /* add/rm files for all cgroups created before */
2693 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2694 struct cgroup *cgrp = css->cgroup;
2696 if (cgroup_is_dead(cgrp))
2699 inode = cgrp->dentry->d_inode;
2702 prev = cgrp->dentry;
2704 mutex_unlock(&cgroup_mutex);
2705 mutex_lock(&inode->i_mutex);
2706 mutex_lock(&cgroup_mutex);
2707 if (cgrp->serial_nr < update_before && !cgroup_is_dead(cgrp))
2708 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2709 mutex_unlock(&inode->i_mutex);
2713 mutex_unlock(&cgroup_mutex);
2715 deactivate_super(sb);
2720 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2721 * @ss: target cgroup subsystem
2722 * @cfts: zero-length name terminated array of cftypes
2724 * Register @cfts to @ss. Files described by @cfts are created for all
2725 * existing cgroups to which @ss is attached and all future cgroups will
2726 * have them too. This function can be called anytime whether @ss is
2729 * Returns 0 on successful registration, -errno on failure. Note that this
2730 * function currently returns 0 as long as @cfts registration is successful
2731 * even if some file creation attempts on existing cgroups fail.
2733 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2735 struct cftype_set *set;
2739 set = kzalloc(sizeof(*set), GFP_KERNEL);
2743 for (cft = cfts; cft->name[0] != '\0'; cft++)
2746 cgroup_cfts_prepare();
2748 list_add_tail(&set->node, &ss->cftsets);
2749 ret = cgroup_cfts_commit(cfts, true);
2751 cgroup_rm_cftypes(cfts);
2754 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2757 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2758 * @cfts: zero-length name terminated array of cftypes
2760 * Unregister @cfts. Files described by @cfts are removed from all
2761 * existing cgroups and all future cgroups won't have them either. This
2762 * function can be called anytime whether @cfts' subsys is attached or not.
2764 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2767 int cgroup_rm_cftypes(struct cftype *cfts)
2769 struct cftype_set *set;
2771 if (!cfts || !cfts[0].ss)
2774 cgroup_cfts_prepare();
2776 list_for_each_entry(set, &cfts[0].ss->cftsets, node) {
2777 if (set->cfts == cfts) {
2778 list_del(&set->node);
2780 cgroup_cfts_commit(cfts, false);
2785 cgroup_cfts_commit(NULL, false);
2790 * cgroup_task_count - count the number of tasks in a cgroup.
2791 * @cgrp: the cgroup in question
2793 * Return the number of tasks in the cgroup.
2795 int cgroup_task_count(const struct cgroup *cgrp)
2798 struct cgrp_cset_link *link;
2800 read_lock(&css_set_lock);
2801 list_for_each_entry(link, &cgrp->cset_links, cset_link)
2802 count += atomic_read(&link->cset->refcount);
2803 read_unlock(&css_set_lock);
2808 * To reduce the fork() overhead for systems that are not actually using
2809 * their cgroups capability, we don't maintain the lists running through
2810 * each css_set to its tasks until we see the list actually used - in other
2811 * words after the first call to css_task_iter_start().
2813 static void cgroup_enable_task_cg_lists(void)
2815 struct task_struct *p, *g;
2816 write_lock(&css_set_lock);
2817 use_task_css_set_links = 1;
2819 * We need tasklist_lock because RCU is not safe against
2820 * while_each_thread(). Besides, a forking task that has passed
2821 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2822 * is not guaranteed to have its child immediately visible in the
2823 * tasklist if we walk through it with RCU.
2825 read_lock(&tasklist_lock);
2826 do_each_thread(g, p) {
2829 * We should check if the process is exiting, otherwise
2830 * it will race with cgroup_exit() in that the list
2831 * entry won't be deleted though the process has exited.
2833 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2834 list_add(&p->cg_list, &task_css_set(p)->tasks);
2836 } while_each_thread(g, p);
2837 read_unlock(&tasklist_lock);
2838 write_unlock(&css_set_lock);
2842 * css_next_child - find the next child of a given css
2843 * @pos_css: the current position (%NULL to initiate traversal)
2844 * @parent_css: css whose children to walk
2846 * This function returns the next child of @parent_css and should be called
2847 * under either cgroup_mutex or RCU read lock. The only requirement is
2848 * that @parent_css and @pos_css are accessible. The next sibling is
2849 * guaranteed to be returned regardless of their states.
2851 struct cgroup_subsys_state *
2852 css_next_child(struct cgroup_subsys_state *pos_css,
2853 struct cgroup_subsys_state *parent_css)
2855 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
2856 struct cgroup *cgrp = parent_css->cgroup;
2857 struct cgroup *next;
2859 cgroup_assert_mutex_or_rcu_locked();
2862 * @pos could already have been removed. Once a cgroup is removed,
2863 * its ->sibling.next is no longer updated when its next sibling
2864 * changes. As CGRP_DEAD assertion is serialized and happens
2865 * before the cgroup is taken off the ->sibling list, if we see it
2866 * unasserted, it's guaranteed that the next sibling hasn't
2867 * finished its grace period even if it's already removed, and thus
2868 * safe to dereference from this RCU critical section. If
2869 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
2870 * to be visible as %true here.
2872 * If @pos is dead, its next pointer can't be dereferenced;
2873 * however, as each cgroup is given a monotonically increasing
2874 * unique serial number and always appended to the sibling list,
2875 * the next one can be found by walking the parent's children until
2876 * we see a cgroup with higher serial number than @pos's. While
2877 * this path can be slower, it's taken only when either the current
2878 * cgroup is removed or iteration and removal race.
2881 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
2882 } else if (likely(!cgroup_is_dead(pos))) {
2883 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
2885 list_for_each_entry_rcu(next, &cgrp->children, sibling)
2886 if (next->serial_nr > pos->serial_nr)
2890 if (&next->sibling == &cgrp->children)
2893 return cgroup_css(next, parent_css->ss);
2895 EXPORT_SYMBOL_GPL(css_next_child);
2898 * css_next_descendant_pre - find the next descendant for pre-order walk
2899 * @pos: the current position (%NULL to initiate traversal)
2900 * @root: css whose descendants to walk
2902 * To be used by css_for_each_descendant_pre(). Find the next descendant
2903 * to visit for pre-order traversal of @root's descendants. @root is
2904 * included in the iteration and the first node to be visited.
2906 * While this function requires cgroup_mutex or RCU read locking, it
2907 * doesn't require the whole traversal to be contained in a single critical
2908 * section. This function will return the correct next descendant as long
2909 * as both @pos and @root are accessible and @pos is a descendant of @root.
2911 struct cgroup_subsys_state *
2912 css_next_descendant_pre(struct cgroup_subsys_state *pos,
2913 struct cgroup_subsys_state *root)
2915 struct cgroup_subsys_state *next;
2917 cgroup_assert_mutex_or_rcu_locked();
2919 /* if first iteration, visit @root */
2923 /* visit the first child if exists */
2924 next = css_next_child(NULL, pos);
2928 /* no child, visit my or the closest ancestor's next sibling */
2929 while (pos != root) {
2930 next = css_next_child(pos, css_parent(pos));
2933 pos = css_parent(pos);
2938 EXPORT_SYMBOL_GPL(css_next_descendant_pre);
2941 * css_rightmost_descendant - return the rightmost descendant of a css
2942 * @pos: css of interest
2944 * Return the rightmost descendant of @pos. If there's no descendant, @pos
2945 * is returned. This can be used during pre-order traversal to skip
2948 * While this function requires cgroup_mutex or RCU read locking, it
2949 * doesn't require the whole traversal to be contained in a single critical
2950 * section. This function will return the correct rightmost descendant as
2951 * long as @pos is accessible.
2953 struct cgroup_subsys_state *
2954 css_rightmost_descendant(struct cgroup_subsys_state *pos)
2956 struct cgroup_subsys_state *last, *tmp;
2958 cgroup_assert_mutex_or_rcu_locked();
2962 /* ->prev isn't RCU safe, walk ->next till the end */
2964 css_for_each_child(tmp, last)
2970 EXPORT_SYMBOL_GPL(css_rightmost_descendant);
2972 static struct cgroup_subsys_state *
2973 css_leftmost_descendant(struct cgroup_subsys_state *pos)
2975 struct cgroup_subsys_state *last;
2979 pos = css_next_child(NULL, pos);
2986 * css_next_descendant_post - find the next descendant for post-order walk
2987 * @pos: the current position (%NULL to initiate traversal)
2988 * @root: css whose descendants to walk
2990 * To be used by css_for_each_descendant_post(). Find the next descendant
2991 * to visit for post-order traversal of @root's descendants. @root is
2992 * included in the iteration and the last node to be visited.
2994 * While this function requires cgroup_mutex or RCU read locking, it
2995 * doesn't require the whole traversal to be contained in a single critical
2996 * section. This function will return the correct next descendant as long
2997 * as both @pos and @cgroup are accessible and @pos is a descendant of
3000 struct cgroup_subsys_state *
3001 css_next_descendant_post(struct cgroup_subsys_state *pos,
3002 struct cgroup_subsys_state *root)
3004 struct cgroup_subsys_state *next;
3006 cgroup_assert_mutex_or_rcu_locked();
3008 /* if first iteration, visit leftmost descendant which may be @root */
3010 return css_leftmost_descendant(root);
3012 /* if we visited @root, we're done */
3016 /* if there's an unvisited sibling, visit its leftmost descendant */
3017 next = css_next_child(pos, css_parent(pos));
3019 return css_leftmost_descendant(next);
3021 /* no sibling left, visit parent */
3022 return css_parent(pos);
3024 EXPORT_SYMBOL_GPL(css_next_descendant_post);
3027 * css_advance_task_iter - advance a task itererator to the next css_set
3028 * @it: the iterator to advance
3030 * Advance @it to the next css_set to walk.
3032 static void css_advance_task_iter(struct css_task_iter *it)
3034 struct list_head *l = it->cset_link;
3035 struct cgrp_cset_link *link;
3036 struct css_set *cset;
3038 /* Advance to the next non-empty css_set */
3041 if (l == &it->origin_css->cgroup->cset_links) {
3042 it->cset_link = NULL;
3045 link = list_entry(l, struct cgrp_cset_link, cset_link);
3047 } while (list_empty(&cset->tasks));
3049 it->task = cset->tasks.next;
3053 * css_task_iter_start - initiate task iteration
3054 * @css: the css to walk tasks of
3055 * @it: the task iterator to use
3057 * Initiate iteration through the tasks of @css. The caller can call
3058 * css_task_iter_next() to walk through the tasks until the function
3059 * returns NULL. On completion of iteration, css_task_iter_end() must be
3062 * Note that this function acquires a lock which is released when the
3063 * iteration finishes. The caller can't sleep while iteration is in
3066 void css_task_iter_start(struct cgroup_subsys_state *css,
3067 struct css_task_iter *it)
3068 __acquires(css_set_lock)
3071 * The first time anyone tries to iterate across a css, we need to
3072 * enable the list linking each css_set to its tasks, and fix up
3073 * all existing tasks.
3075 if (!use_task_css_set_links)
3076 cgroup_enable_task_cg_lists();
3078 read_lock(&css_set_lock);
3080 it->origin_css = css;
3081 it->cset_link = &css->cgroup->cset_links;
3083 css_advance_task_iter(it);
3087 * css_task_iter_next - return the next task for the iterator
3088 * @it: the task iterator being iterated
3090 * The "next" function for task iteration. @it should have been
3091 * initialized via css_task_iter_start(). Returns NULL when the iteration
3094 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3096 struct task_struct *res;
3097 struct list_head *l = it->task;
3098 struct cgrp_cset_link *link;
3100 /* If the iterator cg is NULL, we have no tasks */
3103 res = list_entry(l, struct task_struct, cg_list);
3104 /* Advance iterator to find next entry */
3106 link = list_entry(it->cset_link, struct cgrp_cset_link, cset_link);
3107 if (l == &link->cset->tasks) {
3109 * We reached the end of this task list - move on to the
3110 * next cgrp_cset_link.
3112 css_advance_task_iter(it);
3120 * css_task_iter_end - finish task iteration
3121 * @it: the task iterator to finish
3123 * Finish task iteration started by css_task_iter_start().
3125 void css_task_iter_end(struct css_task_iter *it)
3126 __releases(css_set_lock)
3128 read_unlock(&css_set_lock);
3131 static inline int started_after_time(struct task_struct *t1,
3132 struct timespec *time,
3133 struct task_struct *t2)
3135 int start_diff = timespec_compare(&t1->start_time, time);
3136 if (start_diff > 0) {
3138 } else if (start_diff < 0) {
3142 * Arbitrarily, if two processes started at the same
3143 * time, we'll say that the lower pointer value
3144 * started first. Note that t2 may have exited by now
3145 * so this may not be a valid pointer any longer, but
3146 * that's fine - it still serves to distinguish
3147 * between two tasks started (effectively) simultaneously.
3154 * This function is a callback from heap_insert() and is used to order
3156 * In this case we order the heap in descending task start time.
3158 static inline int started_after(void *p1, void *p2)
3160 struct task_struct *t1 = p1;
3161 struct task_struct *t2 = p2;
3162 return started_after_time(t1, &t2->start_time, t2);
3166 * css_scan_tasks - iterate though all the tasks in a css
3167 * @css: the css to iterate tasks of
3168 * @test: optional test callback
3169 * @process: process callback
3170 * @data: data passed to @test and @process
3171 * @heap: optional pre-allocated heap used for task iteration
3173 * Iterate through all the tasks in @css, calling @test for each, and if it
3174 * returns %true, call @process for it also.
3176 * @test may be NULL, meaning always true (select all tasks), which
3177 * effectively duplicates css_task_iter_{start,next,end}() but does not
3178 * lock css_set_lock for the call to @process.
3180 * It is guaranteed that @process will act on every task that is a member
3181 * of @css for the duration of this call. This function may or may not
3182 * call @process for tasks that exit or move to a different css during the
3183 * call, or are forked or move into the css during the call.
3185 * Note that @test may be called with locks held, and may in some
3186 * situations be called multiple times for the same task, so it should be
3189 * If @heap is non-NULL, a heap has been pre-allocated and will be used for
3190 * heap operations (and its "gt" member will be overwritten), else a
3191 * temporary heap will be used (allocation of which may cause this function
3194 int css_scan_tasks(struct cgroup_subsys_state *css,
3195 bool (*test)(struct task_struct *, void *),
3196 void (*process)(struct task_struct *, void *),
3197 void *data, struct ptr_heap *heap)
3200 struct css_task_iter it;
3201 struct task_struct *p, *dropped;
3202 /* Never dereference latest_task, since it's not refcounted */
3203 struct task_struct *latest_task = NULL;
3204 struct ptr_heap tmp_heap;
3205 struct timespec latest_time = { 0, 0 };
3208 /* The caller supplied our heap and pre-allocated its memory */
3209 heap->gt = &started_after;
3211 /* We need to allocate our own heap memory */
3213 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3215 /* cannot allocate the heap */
3221 * Scan tasks in the css, using the @test callback to determine
3222 * which are of interest, and invoking @process callback on the
3223 * ones which need an update. Since we don't want to hold any
3224 * locks during the task updates, gather tasks to be processed in a
3225 * heap structure. The heap is sorted by descending task start
3226 * time. If the statically-sized heap fills up, we overflow tasks
3227 * that started later, and in future iterations only consider tasks
3228 * that started after the latest task in the previous pass. This
3229 * guarantees forward progress and that we don't miss any tasks.
3232 css_task_iter_start(css, &it);
3233 while ((p = css_task_iter_next(&it))) {
3235 * Only affect tasks that qualify per the caller's callback,
3236 * if he provided one
3238 if (test && !test(p, data))
3241 * Only process tasks that started after the last task
3244 if (!started_after_time(p, &latest_time, latest_task))
3246 dropped = heap_insert(heap, p);
3247 if (dropped == NULL) {
3249 * The new task was inserted; the heap wasn't
3253 } else if (dropped != p) {
3255 * The new task was inserted, and pushed out a
3259 put_task_struct(dropped);
3262 * Else the new task was newer than anything already in
3263 * the heap and wasn't inserted
3266 css_task_iter_end(&it);
3269 for (i = 0; i < heap->size; i++) {
3270 struct task_struct *q = heap->ptrs[i];
3272 latest_time = q->start_time;
3275 /* Process the task per the caller's callback */
3280 * If we had to process any tasks at all, scan again
3281 * in case some of them were in the middle of forking
3282 * children that didn't get processed.
3283 * Not the most efficient way to do it, but it avoids
3284 * having to take callback_mutex in the fork path
3288 if (heap == &tmp_heap)
3289 heap_free(&tmp_heap);
3293 static void cgroup_transfer_one_task(struct task_struct *task, void *data)
3295 struct cgroup *new_cgroup = data;
3297 mutex_lock(&cgroup_mutex);
3298 cgroup_attach_task(new_cgroup, task, false);
3299 mutex_unlock(&cgroup_mutex);
3303 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3304 * @to: cgroup to which the tasks will be moved
3305 * @from: cgroup in which the tasks currently reside
3307 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3309 return css_scan_tasks(&from->dummy_css, NULL, cgroup_transfer_one_task,
3314 * Stuff for reading the 'tasks'/'procs' files.
3316 * Reading this file can return large amounts of data if a cgroup has
3317 * *lots* of attached tasks. So it may need several calls to read(),
3318 * but we cannot guarantee that the information we produce is correct
3319 * unless we produce it entirely atomically.
3323 /* which pidlist file are we talking about? */
3324 enum cgroup_filetype {
3330 * A pidlist is a list of pids that virtually represents the contents of one
3331 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3332 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3335 struct cgroup_pidlist {
3337 * used to find which pidlist is wanted. doesn't change as long as
3338 * this particular list stays in the list.
3340 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3343 /* how many elements the above list has */
3345 /* each of these stored in a list by its cgroup */
3346 struct list_head links;
3347 /* pointer to the cgroup we belong to, for list removal purposes */
3348 struct cgroup *owner;
3349 /* for delayed destruction */
3350 struct delayed_work destroy_dwork;
3354 * The following two functions "fix" the issue where there are more pids
3355 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3356 * TODO: replace with a kernel-wide solution to this problem
3358 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3359 static void *pidlist_allocate(int count)
3361 if (PIDLIST_TOO_LARGE(count))
3362 return vmalloc(count * sizeof(pid_t));
3364 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3367 static void pidlist_free(void *p)
3369 if (is_vmalloc_addr(p))
3376 * Used to destroy all pidlists lingering waiting for destroy timer. None
3377 * should be left afterwards.
3379 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
3381 struct cgroup_pidlist *l, *tmp_l;
3383 mutex_lock(&cgrp->pidlist_mutex);
3384 list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
3385 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
3386 mutex_unlock(&cgrp->pidlist_mutex);
3388 flush_workqueue(cgroup_pidlist_destroy_wq);
3389 BUG_ON(!list_empty(&cgrp->pidlists));
3392 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
3394 struct delayed_work *dwork = to_delayed_work(work);
3395 struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
3397 struct cgroup_pidlist *tofree = NULL;
3399 mutex_lock(&l->owner->pidlist_mutex);
3402 * Destroy iff we didn't get queued again. The state won't change
3403 * as destroy_dwork can only be queued while locked.
3405 if (!delayed_work_pending(dwork)) {
3406 list_del(&l->links);
3407 pidlist_free(l->list);
3408 put_pid_ns(l->key.ns);
3412 mutex_unlock(&l->owner->pidlist_mutex);
3417 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3418 * Returns the number of unique elements.
3420 static int pidlist_uniq(pid_t *list, int length)
3425 * we presume the 0th element is unique, so i starts at 1. trivial
3426 * edge cases first; no work needs to be done for either
3428 if (length == 0 || length == 1)
3430 /* src and dest walk down the list; dest counts unique elements */
3431 for (src = 1; src < length; src++) {
3432 /* find next unique element */
3433 while (list[src] == list[src-1]) {
3438 /* dest always points to where the next unique element goes */
3439 list[dest] = list[src];
3447 * The two pid files - task and cgroup.procs - guaranteed that the result
3448 * is sorted, which forced this whole pidlist fiasco. As pid order is
3449 * different per namespace, each namespace needs differently sorted list,
3450 * making it impossible to use, for example, single rbtree of member tasks
3451 * sorted by task pointer. As pidlists can be fairly large, allocating one
3452 * per open file is dangerous, so cgroup had to implement shared pool of
3453 * pidlists keyed by cgroup and namespace.
3455 * All this extra complexity was caused by the original implementation
3456 * committing to an entirely unnecessary property. In the long term, we
3457 * want to do away with it. Explicitly scramble sort order if
3458 * sane_behavior so that no such expectation exists in the new interface.
3460 * Scrambling is done by swapping every two consecutive bits, which is
3461 * non-identity one-to-one mapping which disturbs sort order sufficiently.
3463 static pid_t pid_fry(pid_t pid)
3465 unsigned a = pid & 0x55555555;
3466 unsigned b = pid & 0xAAAAAAAA;
3468 return (a << 1) | (b >> 1);
3471 static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
3473 if (cgroup_sane_behavior(cgrp))
3474 return pid_fry(pid);
3479 static int cmppid(const void *a, const void *b)
3481 return *(pid_t *)a - *(pid_t *)b;
3484 static int fried_cmppid(const void *a, const void *b)
3486 return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
3489 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3490 enum cgroup_filetype type)
3492 struct cgroup_pidlist *l;
3493 /* don't need task_nsproxy() if we're looking at ourself */
3494 struct pid_namespace *ns = task_active_pid_ns(current);
3496 lockdep_assert_held(&cgrp->pidlist_mutex);
3498 list_for_each_entry(l, &cgrp->pidlists, links)
3499 if (l->key.type == type && l->key.ns == ns)
3505 * find the appropriate pidlist for our purpose (given procs vs tasks)
3506 * returns with the lock on that pidlist already held, and takes care
3507 * of the use count, or returns NULL with no locks held if we're out of
3510 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
3511 enum cgroup_filetype type)
3513 struct cgroup_pidlist *l;
3515 lockdep_assert_held(&cgrp->pidlist_mutex);
3517 l = cgroup_pidlist_find(cgrp, type);
3521 /* entry not found; create a new one */
3522 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3526 INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
3528 /* don't need task_nsproxy() if we're looking at ourself */
3529 l->key.ns = get_pid_ns(task_active_pid_ns(current));
3531 list_add(&l->links, &cgrp->pidlists);
3536 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3538 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3539 struct cgroup_pidlist **lp)
3543 int pid, n = 0; /* used for populating the array */
3544 struct css_task_iter it;
3545 struct task_struct *tsk;
3546 struct cgroup_pidlist *l;
3548 lockdep_assert_held(&cgrp->pidlist_mutex);
3551 * If cgroup gets more users after we read count, we won't have
3552 * enough space - tough. This race is indistinguishable to the
3553 * caller from the case that the additional cgroup users didn't
3554 * show up until sometime later on.
3556 length = cgroup_task_count(cgrp);
3557 array = pidlist_allocate(length);
3560 /* now, populate the array */
3561 css_task_iter_start(&cgrp->dummy_css, &it);
3562 while ((tsk = css_task_iter_next(&it))) {
3563 if (unlikely(n == length))
3565 /* get tgid or pid for procs or tasks file respectively */
3566 if (type == CGROUP_FILE_PROCS)
3567 pid = task_tgid_vnr(tsk);
3569 pid = task_pid_vnr(tsk);
3570 if (pid > 0) /* make sure to only use valid results */
3573 css_task_iter_end(&it);
3575 /* now sort & (if procs) strip out duplicates */
3576 if (cgroup_sane_behavior(cgrp))
3577 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
3579 sort(array, length, sizeof(pid_t), cmppid, NULL);
3580 if (type == CGROUP_FILE_PROCS)
3581 length = pidlist_uniq(array, length);
3583 l = cgroup_pidlist_find_create(cgrp, type);
3585 mutex_unlock(&cgrp->pidlist_mutex);
3586 pidlist_free(array);
3590 /* store array, freeing old if necessary */
3591 pidlist_free(l->list);
3599 * cgroupstats_build - build and fill cgroupstats
3600 * @stats: cgroupstats to fill information into
3601 * @dentry: A dentry entry belonging to the cgroup for which stats have
3604 * Build and fill cgroupstats so that taskstats can export it to user
3607 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3610 struct cgroup *cgrp;
3611 struct css_task_iter it;
3612 struct task_struct *tsk;
3615 * Validate dentry by checking the superblock operations,
3616 * and make sure it's a directory.
3618 if (dentry->d_sb->s_op != &cgroup_ops ||
3619 !S_ISDIR(dentry->d_inode->i_mode))
3623 cgrp = dentry->d_fsdata;
3625 css_task_iter_start(&cgrp->dummy_css, &it);
3626 while ((tsk = css_task_iter_next(&it))) {
3627 switch (tsk->state) {
3629 stats->nr_running++;
3631 case TASK_INTERRUPTIBLE:
3632 stats->nr_sleeping++;
3634 case TASK_UNINTERRUPTIBLE:
3635 stats->nr_uninterruptible++;
3638 stats->nr_stopped++;
3641 if (delayacct_is_task_waiting_on_io(tsk))
3642 stats->nr_io_wait++;
3646 css_task_iter_end(&it);
3654 * seq_file methods for the tasks/procs files. The seq_file position is the
3655 * next pid to display; the seq_file iterator is a pointer to the pid
3656 * in the cgroup->l->list array.
3659 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3662 * Initially we receive a position value that corresponds to
3663 * one more than the last pid shown (or 0 on the first call or
3664 * after a seek to the start). Use a binary-search to find the
3665 * next pid to display, if any
3667 struct cgroup_open_file *of = s->private;
3668 struct cgroup *cgrp = seq_css(s)->cgroup;
3669 struct cgroup_pidlist *l;
3670 enum cgroup_filetype type = seq_cft(s)->private;
3671 int index = 0, pid = *pos;
3674 mutex_lock(&cgrp->pidlist_mutex);
3677 * !NULL @of->priv indicates that this isn't the first start()
3678 * after open. If the matching pidlist is around, we can use that.
3679 * Look for it. Note that @of->priv can't be used directly. It
3680 * could already have been destroyed.
3683 of->priv = cgroup_pidlist_find(cgrp, type);
3686 * Either this is the first start() after open or the matching
3687 * pidlist has been destroyed inbetween. Create a new one.
3690 ret = pidlist_array_load(cgrp, type,
3691 (struct cgroup_pidlist **)&of->priv);
3693 return ERR_PTR(ret);
3698 int end = l->length;
3700 while (index < end) {
3701 int mid = (index + end) / 2;
3702 if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
3705 } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
3711 /* If we're off the end of the array, we're done */
3712 if (index >= l->length)
3714 /* Update the abstract position to be the actual pid that we found */
3715 iter = l->list + index;
3716 *pos = cgroup_pid_fry(cgrp, *iter);
3720 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3722 struct cgroup_open_file *of = s->private;
3723 struct cgroup_pidlist *l = of->priv;
3726 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
3727 CGROUP_PIDLIST_DESTROY_DELAY);
3728 mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
3731 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3733 struct cgroup_open_file *of = s->private;
3734 struct cgroup_pidlist *l = of->priv;
3736 pid_t *end = l->list + l->length;
3738 * Advance to the next pid in the array. If this goes off the
3745 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
3750 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3752 return seq_printf(s, "%d\n", *(int *)v);
3756 * seq_operations functions for iterating on pidlists through seq_file -
3757 * independent of whether it's tasks or procs
3759 static const struct seq_operations cgroup_pidlist_seq_operations = {
3760 .start = cgroup_pidlist_start,
3761 .stop = cgroup_pidlist_stop,
3762 .next = cgroup_pidlist_next,
3763 .show = cgroup_pidlist_show,
3766 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3769 return notify_on_release(css->cgroup);
3772 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3773 struct cftype *cft, u64 val)
3775 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3777 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3779 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3784 * When dput() is called asynchronously, if umount has been done and
3785 * then deactivate_super() in cgroup_free_fn() kills the superblock,
3786 * there's a small window that vfs will see the root dentry with non-zero
3787 * refcnt and trigger BUG().
3789 * That's why we hold a reference before dput() and drop it right after.
3791 static void cgroup_dput(struct cgroup *cgrp)
3793 struct super_block *sb = cgrp->root->sb;
3795 atomic_inc(&sb->s_active);
3797 deactivate_super(sb);
3800 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3803 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3806 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3807 struct cftype *cft, u64 val)
3810 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3812 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3816 static struct cftype cgroup_base_files[] = {
3818 .name = "cgroup.procs",
3819 .seq_start = cgroup_pidlist_start,
3820 .seq_next = cgroup_pidlist_next,
3821 .seq_stop = cgroup_pidlist_stop,
3822 .seq_show = cgroup_pidlist_show,
3823 .private = CGROUP_FILE_PROCS,
3824 .write_u64 = cgroup_procs_write,
3825 .mode = S_IRUGO | S_IWUSR,
3828 .name = "cgroup.clone_children",
3829 .flags = CFTYPE_INSANE,
3830 .read_u64 = cgroup_clone_children_read,
3831 .write_u64 = cgroup_clone_children_write,
3834 .name = "cgroup.sane_behavior",
3835 .flags = CFTYPE_ONLY_ON_ROOT,
3836 .seq_show = cgroup_sane_behavior_show,
3840 * Historical crazy stuff. These don't have "cgroup." prefix and
3841 * don't exist if sane_behavior. If you're depending on these, be
3842 * prepared to be burned.
3846 .flags = CFTYPE_INSANE, /* use "procs" instead */
3847 .seq_start = cgroup_pidlist_start,
3848 .seq_next = cgroup_pidlist_next,
3849 .seq_stop = cgroup_pidlist_stop,
3850 .seq_show = cgroup_pidlist_show,
3851 .private = CGROUP_FILE_TASKS,
3852 .write_u64 = cgroup_tasks_write,
3853 .mode = S_IRUGO | S_IWUSR,
3856 .name = "notify_on_release",
3857 .flags = CFTYPE_INSANE,
3858 .read_u64 = cgroup_read_notify_on_release,
3859 .write_u64 = cgroup_write_notify_on_release,
3862 .name = "release_agent",
3863 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
3864 .seq_show = cgroup_release_agent_show,
3865 .write_string = cgroup_release_agent_write,
3866 .max_write_len = PATH_MAX,
3872 * cgroup_populate_dir - create subsys files in a cgroup directory
3873 * @cgrp: target cgroup
3874 * @subsys_mask: mask of the subsystem ids whose files should be added
3876 * On failure, no file is added.
3878 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
3880 struct cgroup_subsys *ss;
3883 /* process cftsets of each subsystem */
3884 for_each_subsys(ss, i) {
3885 struct cftype_set *set;
3887 if (!test_bit(i, &subsys_mask))
3890 list_for_each_entry(set, &ss->cftsets, node) {
3891 ret = cgroup_addrm_files(cgrp, set->cfts, true);
3898 cgroup_clear_dir(cgrp, subsys_mask);
3903 * css destruction is four-stage process.
3905 * 1. Destruction starts. Killing of the percpu_ref is initiated.
3906 * Implemented in kill_css().
3908 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
3909 * and thus css_tryget() is guaranteed to fail, the css can be offlined
3910 * by invoking offline_css(). After offlining, the base ref is put.
3911 * Implemented in css_killed_work_fn().
3913 * 3. When the percpu_ref reaches zero, the only possible remaining
3914 * accessors are inside RCU read sections. css_release() schedules the
3917 * 4. After the grace period, the css can be freed. Implemented in
3918 * css_free_work_fn().
3920 * It is actually hairier because both step 2 and 4 require process context
3921 * and thus involve punting to css->destroy_work adding two additional
3922 * steps to the already complex sequence.
3924 static void css_free_work_fn(struct work_struct *work)
3926 struct cgroup_subsys_state *css =
3927 container_of(work, struct cgroup_subsys_state, destroy_work);
3928 struct cgroup *cgrp = css->cgroup;
3931 css_put(css->parent);
3933 css->ss->css_free(css);
3937 static void css_free_rcu_fn(struct rcu_head *rcu_head)
3939 struct cgroup_subsys_state *css =
3940 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
3943 * css holds an extra ref to @cgrp->dentry which is put on the last
3944 * css_put(). dput() requires process context which we don't have.
3946 INIT_WORK(&css->destroy_work, css_free_work_fn);
3947 queue_work(cgroup_destroy_wq, &css->destroy_work);
3950 static void css_release(struct percpu_ref *ref)
3952 struct cgroup_subsys_state *css =
3953 container_of(ref, struct cgroup_subsys_state, refcnt);
3955 rcu_assign_pointer(css->cgroup->subsys[css->ss->id], NULL);
3956 call_rcu(&css->rcu_head, css_free_rcu_fn);
3959 static void init_css(struct cgroup_subsys_state *css, struct cgroup_subsys *ss,
3960 struct cgroup *cgrp)
3967 css->parent = cgroup_css(cgrp->parent, ss);
3969 css->flags |= CSS_ROOT;
3971 BUG_ON(cgroup_css(cgrp, ss));
3974 /* invoke ->css_online() on a new CSS and mark it online if successful */
3975 static int online_css(struct cgroup_subsys_state *css)
3977 struct cgroup_subsys *ss = css->ss;
3980 lockdep_assert_held(&cgroup_mutex);
3983 ret = ss->css_online(css);
3985 css->flags |= CSS_ONLINE;
3986 css->cgroup->nr_css++;
3987 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
3992 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
3993 static void offline_css(struct cgroup_subsys_state *css)
3995 struct cgroup_subsys *ss = css->ss;
3997 lockdep_assert_held(&cgroup_mutex);
3999 if (!(css->flags & CSS_ONLINE))
4002 if (ss->css_offline)
4003 ss->css_offline(css);
4005 css->flags &= ~CSS_ONLINE;
4006 css->cgroup->nr_css--;
4007 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], css);
4011 * create_css - create a cgroup_subsys_state
4012 * @cgrp: the cgroup new css will be associated with
4013 * @ss: the subsys of new css
4015 * Create a new css associated with @cgrp - @ss pair. On success, the new
4016 * css is online and installed in @cgrp with all interface files created.
4017 * Returns 0 on success, -errno on failure.
4019 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss)
4021 struct cgroup *parent = cgrp->parent;
4022 struct cgroup_subsys_state *css;
4025 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
4026 lockdep_assert_held(&cgroup_mutex);
4028 css = ss->css_alloc(cgroup_css(parent, ss));
4030 return PTR_ERR(css);
4032 err = percpu_ref_init(&css->refcnt, css_release);
4036 init_css(css, ss, cgrp);
4038 err = cgroup_populate_dir(cgrp, 1 << ss->id);
4042 err = online_css(css);
4047 css_get(css->parent);
4049 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4051 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",
4052 current->comm, current->pid, ss->name);
4053 if (!strcmp(ss->name, "memory"))
4054 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4055 ss->warned_broken_hierarchy = true;
4061 percpu_ref_cancel_init(&css->refcnt);
4067 * cgroup_create - create a cgroup
4068 * @parent: cgroup that will be parent of the new cgroup
4069 * @dentry: dentry of the new cgroup
4070 * @mode: mode to set on new inode
4072 * Must be called with the mutex on the parent inode held
4074 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4077 struct cgroup *cgrp;
4078 struct cgroup_name *name;
4079 struct cgroupfs_root *root = parent->root;
4081 struct cgroup_subsys *ss;
4082 struct super_block *sb = root->sb;
4084 /* allocate the cgroup and its ID, 0 is reserved for the root */
4085 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4089 name = cgroup_alloc_name(dentry);
4094 rcu_assign_pointer(cgrp->name, name);
4097 * Only live parents can have children. Note that the liveliness
4098 * check isn't strictly necessary because cgroup_mkdir() and
4099 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4100 * anyway so that locking is contained inside cgroup proper and we
4101 * don't get nasty surprises if we ever grow another caller.
4103 if (!cgroup_lock_live_group(parent)) {
4109 * Temporarily set the pointer to NULL, so idr_find() won't return
4110 * a half-baked cgroup.
4112 cgrp->id = idr_alloc(&root->cgroup_idr, NULL, 1, 0, GFP_KERNEL);
4118 /* Grab a reference on the superblock so the hierarchy doesn't
4119 * get deleted on unmount if there are child cgroups. This
4120 * can be done outside cgroup_mutex, since the sb can't
4121 * disappear while someone has an open control file on the
4123 atomic_inc(&sb->s_active);
4125 init_cgroup_housekeeping(cgrp);
4127 dentry->d_fsdata = cgrp;
4128 cgrp->dentry = dentry;
4130 cgrp->parent = parent;
4131 cgrp->dummy_css.parent = &parent->dummy_css;
4132 cgrp->root = parent->root;
4134 if (notify_on_release(parent))
4135 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4137 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4138 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4141 * Create directory. cgroup_create_file() returns with the new
4142 * directory locked on success so that it can be populated without
4143 * dropping cgroup_mutex.
4145 err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4148 lockdep_assert_held(&dentry->d_inode->i_mutex);
4150 cgrp->serial_nr = cgroup_serial_nr_next++;
4152 /* allocation complete, commit to creation */
4153 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4154 root->number_of_cgroups++;
4156 /* hold a ref to the parent's dentry */
4157 dget(parent->dentry);
4160 * @cgrp is now fully operational. If something fails after this
4161 * point, it'll be released via the normal destruction path.
4163 idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4165 err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
4169 /* let's create and online css's */
4170 for_each_subsys(ss, ssid) {
4171 if (root->subsys_mask & (1 << ssid)) {
4172 err = create_css(cgrp, ss);
4178 mutex_unlock(&cgroup_mutex);
4179 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4184 idr_remove(&root->cgroup_idr, cgrp->id);
4185 /* Release the reference count that we took on the superblock */
4186 deactivate_super(sb);
4188 mutex_unlock(&cgroup_mutex);
4190 kfree(rcu_dereference_raw(cgrp->name));
4196 cgroup_destroy_locked(cgrp);
4197 mutex_unlock(&cgroup_mutex);
4198 mutex_unlock(&dentry->d_inode->i_mutex);
4202 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4204 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4206 /* the vfs holds inode->i_mutex already */
4207 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4211 * This is called when the refcnt of a css is confirmed to be killed.
4212 * css_tryget() is now guaranteed to fail.
4214 static void css_killed_work_fn(struct work_struct *work)
4216 struct cgroup_subsys_state *css =
4217 container_of(work, struct cgroup_subsys_state, destroy_work);
4218 struct cgroup *cgrp = css->cgroup;
4220 mutex_lock(&cgroup_mutex);
4223 * css_tryget() is guaranteed to fail now. Tell subsystems to
4224 * initate destruction.
4229 * If @cgrp is marked dead, it's waiting for refs of all css's to
4230 * be disabled before proceeding to the second phase of cgroup
4231 * destruction. If we are the last one, kick it off.
4233 if (!cgrp->nr_css && cgroup_is_dead(cgrp))
4234 cgroup_destroy_css_killed(cgrp);
4236 mutex_unlock(&cgroup_mutex);
4239 * Put the css refs from kill_css(). Each css holds an extra
4240 * reference to the cgroup's dentry and cgroup removal proceeds
4241 * regardless of css refs. On the last put of each css, whenever
4242 * that may be, the extra dentry ref is put so that dentry
4243 * destruction happens only after all css's are released.
4248 /* css kill confirmation processing requires process context, bounce */
4249 static void css_killed_ref_fn(struct percpu_ref *ref)
4251 struct cgroup_subsys_state *css =
4252 container_of(ref, struct cgroup_subsys_state, refcnt);
4254 INIT_WORK(&css->destroy_work, css_killed_work_fn);
4255 queue_work(cgroup_destroy_wq, &css->destroy_work);
4259 * kill_css - destroy a css
4260 * @css: css to destroy
4262 * This function initiates destruction of @css by removing cgroup interface
4263 * files and putting its base reference. ->css_offline() will be invoked
4264 * asynchronously once css_tryget() is guaranteed to fail and when the
4265 * reference count reaches zero, @css will be released.
4267 static void kill_css(struct cgroup_subsys_state *css)
4269 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4272 * Killing would put the base ref, but we need to keep it alive
4273 * until after ->css_offline().
4278 * cgroup core guarantees that, by the time ->css_offline() is
4279 * invoked, no new css reference will be given out via
4280 * css_tryget(). We can't simply call percpu_ref_kill() and
4281 * proceed to offlining css's because percpu_ref_kill() doesn't
4282 * guarantee that the ref is seen as killed on all CPUs on return.
4284 * Use percpu_ref_kill_and_confirm() to get notifications as each
4285 * css is confirmed to be seen as killed on all CPUs.
4287 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4291 * cgroup_destroy_locked - the first stage of cgroup destruction
4292 * @cgrp: cgroup to be destroyed
4294 * css's make use of percpu refcnts whose killing latency shouldn't be
4295 * exposed to userland and are RCU protected. Also, cgroup core needs to
4296 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
4297 * invoked. To satisfy all the requirements, destruction is implemented in
4298 * the following two steps.
4300 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4301 * userland visible parts and start killing the percpu refcnts of
4302 * css's. Set up so that the next stage will be kicked off once all
4303 * the percpu refcnts are confirmed to be killed.
4305 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4306 * rest of destruction. Once all cgroup references are gone, the
4307 * cgroup is RCU-freed.
4309 * This function implements s1. After this step, @cgrp is gone as far as
4310 * the userland is concerned and a new cgroup with the same name may be
4311 * created. As cgroup doesn't care about the names internally, this
4312 * doesn't cause any problem.
4314 static int cgroup_destroy_locked(struct cgroup *cgrp)
4315 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4317 struct dentry *d = cgrp->dentry;
4318 struct cgroup_subsys_state *css;
4319 struct cgroup *child;
4323 lockdep_assert_held(&d->d_inode->i_mutex);
4324 lockdep_assert_held(&cgroup_mutex);
4327 * css_set_lock synchronizes access to ->cset_links and prevents
4328 * @cgrp from being removed while __put_css_set() is in progress.
4330 read_lock(&css_set_lock);
4331 empty = list_empty(&cgrp->cset_links);
4332 read_unlock(&css_set_lock);
4337 * Make sure there's no live children. We can't test ->children
4338 * emptiness as dead children linger on it while being destroyed;
4339 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
4343 list_for_each_entry_rcu(child, &cgrp->children, sibling) {
4344 empty = cgroup_is_dead(child);
4353 * Initiate massacre of all css's. cgroup_destroy_css_killed()
4354 * will be invoked to perform the rest of destruction once the
4355 * percpu refs of all css's are confirmed to be killed.
4357 for_each_css(css, ssid, cgrp)
4361 * Mark @cgrp dead. This prevents further task migration and child
4362 * creation by disabling cgroup_lock_live_group(). Note that
4363 * CGRP_DEAD assertion is depended upon by css_next_child() to
4364 * resume iteration after dropping RCU read lock. See
4365 * css_next_child() for details.
4367 set_bit(CGRP_DEAD, &cgrp->flags);
4369 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4370 raw_spin_lock(&release_list_lock);
4371 if (!list_empty(&cgrp->release_list))
4372 list_del_init(&cgrp->release_list);
4373 raw_spin_unlock(&release_list_lock);
4376 * If @cgrp has css's attached, the second stage of cgroup
4377 * destruction is kicked off from css_killed_work_fn() after the
4378 * refs of all attached css's are killed. If @cgrp doesn't have
4379 * any css, we kick it off here.
4382 cgroup_destroy_css_killed(cgrp);
4385 * Clear the base files and remove @cgrp directory. The removal
4386 * puts the base ref but we aren't quite done with @cgrp yet, so
4389 cgroup_addrm_files(cgrp, cgroup_base_files, false);
4391 cgroup_d_remove_dir(d);
4397 * cgroup_destroy_css_killed - the second step of cgroup destruction
4398 * @work: cgroup->destroy_free_work
4400 * This function is invoked from a work item for a cgroup which is being
4401 * destroyed after all css's are offlined and performs the rest of
4402 * destruction. This is the second step of destruction described in the
4403 * comment above cgroup_destroy_locked().
4405 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
4407 struct cgroup *parent = cgrp->parent;
4408 struct dentry *d = cgrp->dentry;
4410 lockdep_assert_held(&cgroup_mutex);
4412 /* delete this cgroup from parent->children */
4413 list_del_rcu(&cgrp->sibling);
4417 set_bit(CGRP_RELEASABLE, &parent->flags);
4418 check_for_release(parent);
4421 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4425 mutex_lock(&cgroup_mutex);
4426 ret = cgroup_destroy_locked(dentry->d_fsdata);
4427 mutex_unlock(&cgroup_mutex);
4432 static void __init cgroup_init_cftsets(struct cgroup_subsys *ss)
4434 INIT_LIST_HEAD(&ss->cftsets);
4437 * base_cftset is embedded in subsys itself, no need to worry about
4440 if (ss->base_cftypes) {
4443 for (cft = ss->base_cftypes; cft->name[0] != '\0'; cft++)
4446 ss->base_cftset.cfts = ss->base_cftypes;
4447 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4451 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4453 struct cgroup_subsys_state *css;
4455 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4457 mutex_lock(&cgroup_mutex);
4459 /* init base cftset */
4460 cgroup_init_cftsets(ss);
4462 /* Create the top cgroup state for this subsystem */
4463 ss->root = &cgroup_dummy_root;
4464 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
4465 /* We don't handle early failures gracefully */
4466 BUG_ON(IS_ERR(css));
4467 init_css(css, ss, cgroup_dummy_top);
4469 /* Update the init_css_set to contain a subsys
4470 * pointer to this state - since the subsystem is
4471 * newly registered, all tasks and hence the
4472 * init_css_set is in the subsystem's top cgroup. */
4473 init_css_set.subsys[ss->id] = css;
4475 need_forkexit_callback |= ss->fork || ss->exit;
4477 /* At system boot, before all subsystems have been
4478 * registered, no tasks have been forked, so we don't
4479 * need to invoke fork callbacks here. */
4480 BUG_ON(!list_empty(&init_task.tasks));
4482 BUG_ON(online_css(css));
4484 mutex_unlock(&cgroup_mutex);
4488 * cgroup_init_early - cgroup initialization at system boot
4490 * Initialize cgroups at system boot, and initialize any
4491 * subsystems that request early init.
4493 int __init cgroup_init_early(void)
4495 struct cgroup_subsys *ss;
4498 atomic_set(&init_css_set.refcount, 1);
4499 INIT_LIST_HEAD(&init_css_set.cgrp_links);
4500 INIT_LIST_HEAD(&init_css_set.tasks);
4501 INIT_HLIST_NODE(&init_css_set.hlist);
4503 init_cgroup_root(&cgroup_dummy_root);
4504 cgroup_root_count = 1;
4505 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4507 init_cgrp_cset_link.cset = &init_css_set;
4508 init_cgrp_cset_link.cgrp = cgroup_dummy_top;
4509 list_add(&init_cgrp_cset_link.cset_link, &cgroup_dummy_top->cset_links);
4510 list_add(&init_cgrp_cset_link.cgrp_link, &init_css_set.cgrp_links);
4512 for_each_subsys(ss, i) {
4513 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
4514 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
4515 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
4517 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
4518 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
4521 ss->name = cgroup_subsys_name[i];
4524 cgroup_init_subsys(ss);
4530 * cgroup_init - cgroup initialization
4532 * Register cgroup filesystem and /proc file, and initialize
4533 * any subsystems that didn't request early init.
4535 int __init cgroup_init(void)
4537 struct cgroup_subsys *ss;
4541 err = bdi_init(&cgroup_backing_dev_info);
4545 for_each_subsys(ss, i) {
4546 if (!ss->early_init)
4547 cgroup_init_subsys(ss);
4550 /* allocate id for the dummy hierarchy */
4551 mutex_lock(&cgroup_mutex);
4553 /* Add init_css_set to the hash table */
4554 key = css_set_hash(init_css_set.subsys);
4555 hash_add(css_set_table, &init_css_set.hlist, key);
4557 BUG_ON(cgroup_init_root_id(&cgroup_dummy_root, 0, 1));
4559 err = idr_alloc(&cgroup_dummy_root.cgroup_idr, cgroup_dummy_top,
4563 mutex_unlock(&cgroup_mutex);
4565 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4571 err = register_filesystem(&cgroup_fs_type);
4573 kobject_put(cgroup_kobj);
4577 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4581 bdi_destroy(&cgroup_backing_dev_info);
4586 static int __init cgroup_wq_init(void)
4589 * There isn't much point in executing destruction path in
4590 * parallel. Good chunk is serialized with cgroup_mutex anyway.
4592 * XXX: Must be ordered to make sure parent is offlined after
4593 * children. The ordering requirement is for memcg where a
4594 * parent's offline may wait for a child's leading to deadlock. In
4595 * the long term, this should be fixed from memcg side.
4597 * We would prefer to do this in cgroup_init() above, but that
4598 * is called before init_workqueues(): so leave this until after.
4600 cgroup_destroy_wq = alloc_ordered_workqueue("cgroup_destroy", 0);
4601 BUG_ON(!cgroup_destroy_wq);
4604 * Used to destroy pidlists and separate to serve as flush domain.
4605 * Cap @max_active to 1 too.
4607 cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
4609 BUG_ON(!cgroup_pidlist_destroy_wq);
4613 core_initcall(cgroup_wq_init);
4616 * proc_cgroup_show()
4617 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4618 * - Used for /proc/<pid>/cgroup.
4619 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4620 * doesn't really matter if tsk->cgroup changes after we read it,
4621 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4622 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4623 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4624 * cgroup to top_cgroup.
4627 /* TODO: Use a proper seq_file iterator */
4628 int proc_cgroup_show(struct seq_file *m, void *v)
4631 struct task_struct *tsk;
4634 struct cgroupfs_root *root;
4637 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4643 tsk = get_pid_task(pid, PIDTYPE_PID);
4649 mutex_lock(&cgroup_mutex);
4651 for_each_active_root(root) {
4652 struct cgroup_subsys *ss;
4653 struct cgroup *cgrp;
4654 int ssid, count = 0;
4656 seq_printf(m, "%d:", root->hierarchy_id);
4657 for_each_subsys(ss, ssid)
4658 if (root->subsys_mask & (1 << ssid))
4659 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4660 if (strlen(root->name))
4661 seq_printf(m, "%sname=%s", count ? "," : "",
4664 cgrp = task_cgroup_from_root(tsk, root);
4665 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
4673 mutex_unlock(&cgroup_mutex);
4674 put_task_struct(tsk);
4681 /* Display information about each subsystem and each hierarchy */
4682 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4684 struct cgroup_subsys *ss;
4687 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4689 * ideally we don't want subsystems moving around while we do this.
4690 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4691 * subsys/hierarchy state.
4693 mutex_lock(&cgroup_mutex);
4695 for_each_subsys(ss, i)
4696 seq_printf(m, "%s\t%d\t%d\t%d\n",
4697 ss->name, ss->root->hierarchy_id,
4698 ss->root->number_of_cgroups, !ss->disabled);
4700 mutex_unlock(&cgroup_mutex);
4704 static int cgroupstats_open(struct inode *inode, struct file *file)
4706 return single_open(file, proc_cgroupstats_show, NULL);
4709 static const struct file_operations proc_cgroupstats_operations = {
4710 .open = cgroupstats_open,
4712 .llseek = seq_lseek,
4713 .release = single_release,
4717 * cgroup_fork - attach newly forked task to its parents cgroup.
4718 * @child: pointer to task_struct of forking parent process.
4720 * Description: A task inherits its parent's cgroup at fork().
4722 * A pointer to the shared css_set was automatically copied in
4723 * fork.c by dup_task_struct(). However, we ignore that copy, since
4724 * it was not made under the protection of RCU or cgroup_mutex, so
4725 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
4726 * have already changed current->cgroups, allowing the previously
4727 * referenced cgroup group to be removed and freed.
4729 * At the point that cgroup_fork() is called, 'current' is the parent
4730 * task, and the passed argument 'child' points to the child task.
4732 void cgroup_fork(struct task_struct *child)
4735 get_css_set(task_css_set(current));
4736 child->cgroups = current->cgroups;
4737 task_unlock(current);
4738 INIT_LIST_HEAD(&child->cg_list);
4742 * cgroup_post_fork - called on a new task after adding it to the task list
4743 * @child: the task in question
4745 * Adds the task to the list running through its css_set if necessary and
4746 * call the subsystem fork() callbacks. Has to be after the task is
4747 * visible on the task list in case we race with the first call to
4748 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
4751 void cgroup_post_fork(struct task_struct *child)
4753 struct cgroup_subsys *ss;
4757 * use_task_css_set_links is set to 1 before we walk the tasklist
4758 * under the tasklist_lock and we read it here after we added the child
4759 * to the tasklist under the tasklist_lock as well. If the child wasn't
4760 * yet in the tasklist when we walked through it from
4761 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4762 * should be visible now due to the paired locking and barriers implied
4763 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4764 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4767 if (use_task_css_set_links) {
4768 write_lock(&css_set_lock);
4770 if (list_empty(&child->cg_list))
4771 list_add(&child->cg_list, &task_css_set(child)->tasks);
4773 write_unlock(&css_set_lock);
4777 * Call ss->fork(). This must happen after @child is linked on
4778 * css_set; otherwise, @child might change state between ->fork()
4779 * and addition to css_set.
4781 if (need_forkexit_callback) {
4782 for_each_subsys(ss, i)
4789 * cgroup_exit - detach cgroup from exiting task
4790 * @tsk: pointer to task_struct of exiting process
4791 * @run_callback: run exit callbacks?
4793 * Description: Detach cgroup from @tsk and release it.
4795 * Note that cgroups marked notify_on_release force every task in
4796 * them to take the global cgroup_mutex mutex when exiting.
4797 * This could impact scaling on very large systems. Be reluctant to
4798 * use notify_on_release cgroups where very high task exit scaling
4799 * is required on large systems.
4801 * the_top_cgroup_hack:
4803 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
4805 * We call cgroup_exit() while the task is still competent to
4806 * handle notify_on_release(), then leave the task attached to the
4807 * root cgroup in each hierarchy for the remainder of its exit.
4809 * To do this properly, we would increment the reference count on
4810 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
4811 * code we would add a second cgroup function call, to drop that
4812 * reference. This would just create an unnecessary hot spot on
4813 * the top_cgroup reference count, to no avail.
4815 * Normally, holding a reference to a cgroup without bumping its
4816 * count is unsafe. The cgroup could go away, or someone could
4817 * attach us to a different cgroup, decrementing the count on
4818 * the first cgroup that we never incremented. But in this case,
4819 * top_cgroup isn't going away, and either task has PF_EXITING set,
4820 * which wards off any cgroup_attach_task() attempts, or task is a failed
4821 * fork, never visible to cgroup_attach_task.
4823 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
4825 struct cgroup_subsys *ss;
4826 struct css_set *cset;
4830 * Unlink from the css_set task list if necessary.
4831 * Optimistically check cg_list before taking
4834 if (!list_empty(&tsk->cg_list)) {
4835 write_lock(&css_set_lock);
4836 if (!list_empty(&tsk->cg_list))
4837 list_del_init(&tsk->cg_list);
4838 write_unlock(&css_set_lock);
4841 /* Reassign the task to the init_css_set. */
4843 cset = task_css_set(tsk);
4844 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
4846 if (run_callbacks && need_forkexit_callback) {
4847 /* see cgroup_post_fork() for details */
4848 for_each_subsys(ss, i) {
4850 struct cgroup_subsys_state *old_css = cset->subsys[i];
4851 struct cgroup_subsys_state *css = task_css(tsk, i);
4853 ss->exit(css, old_css, tsk);
4859 put_css_set_taskexit(cset);
4862 static void check_for_release(struct cgroup *cgrp)
4864 if (cgroup_is_releasable(cgrp) &&
4865 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
4867 * Control Group is currently removeable. If it's not
4868 * already queued for a userspace notification, queue
4871 int need_schedule_work = 0;
4873 raw_spin_lock(&release_list_lock);
4874 if (!cgroup_is_dead(cgrp) &&
4875 list_empty(&cgrp->release_list)) {
4876 list_add(&cgrp->release_list, &release_list);
4877 need_schedule_work = 1;
4879 raw_spin_unlock(&release_list_lock);
4880 if (need_schedule_work)
4881 schedule_work(&release_agent_work);
4886 * Notify userspace when a cgroup is released, by running the
4887 * configured release agent with the name of the cgroup (path
4888 * relative to the root of cgroup file system) as the argument.
4890 * Most likely, this user command will try to rmdir this cgroup.
4892 * This races with the possibility that some other task will be
4893 * attached to this cgroup before it is removed, or that some other
4894 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
4895 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
4896 * unused, and this cgroup will be reprieved from its death sentence,
4897 * to continue to serve a useful existence. Next time it's released,
4898 * we will get notified again, if it still has 'notify_on_release' set.
4900 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
4901 * means only wait until the task is successfully execve()'d. The
4902 * separate release agent task is forked by call_usermodehelper(),
4903 * then control in this thread returns here, without waiting for the
4904 * release agent task. We don't bother to wait because the caller of
4905 * this routine has no use for the exit status of the release agent
4906 * task, so no sense holding our caller up for that.
4908 static void cgroup_release_agent(struct work_struct *work)
4910 BUG_ON(work != &release_agent_work);
4911 mutex_lock(&cgroup_mutex);
4912 raw_spin_lock(&release_list_lock);
4913 while (!list_empty(&release_list)) {
4914 char *argv[3], *envp[3];
4916 char *pathbuf = NULL, *agentbuf = NULL;
4917 struct cgroup *cgrp = list_entry(release_list.next,
4920 list_del_init(&cgrp->release_list);
4921 raw_spin_unlock(&release_list_lock);
4922 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4925 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
4927 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
4932 argv[i++] = agentbuf;
4933 argv[i++] = pathbuf;
4937 /* minimal command environment */
4938 envp[i++] = "HOME=/";
4939 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
4942 /* Drop the lock while we invoke the usermode helper,
4943 * since the exec could involve hitting disk and hence
4944 * be a slow process */
4945 mutex_unlock(&cgroup_mutex);
4946 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
4947 mutex_lock(&cgroup_mutex);
4951 raw_spin_lock(&release_list_lock);
4953 raw_spin_unlock(&release_list_lock);
4954 mutex_unlock(&cgroup_mutex);
4957 static int __init cgroup_disable(char *str)
4959 struct cgroup_subsys *ss;
4963 while ((token = strsep(&str, ",")) != NULL) {
4967 for_each_subsys(ss, i) {
4968 if (!strcmp(token, ss->name)) {
4970 printk(KERN_INFO "Disabling %s control group"
4971 " subsystem\n", ss->name);
4978 __setup("cgroup_disable=", cgroup_disable);
4981 * css_tryget_from_dir - get corresponding css from the dentry of a cgroup dir
4982 * @dentry: directory dentry of interest
4983 * @ss: subsystem of interest
4985 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
4986 * to get the corresponding css and return it. If such css doesn't exist
4987 * or can't be pinned, an ERR_PTR value is returned.
4989 struct cgroup_subsys_state *css_tryget_from_dir(struct dentry *dentry,
4990 struct cgroup_subsys *ss)
4992 struct cgroup *cgrp;
4993 struct cgroup_subsys_state *css;
4995 /* is @dentry a cgroup dir? */
4996 if (!dentry->d_inode ||
4997 dentry->d_inode->i_op != &cgroup_dir_inode_operations)
4998 return ERR_PTR(-EBADF);
5002 cgrp = __d_cgrp(dentry);
5003 css = cgroup_css(cgrp, ss);
5005 if (!css || !css_tryget(css))
5006 css = ERR_PTR(-ENOENT);
5013 * css_from_id - lookup css by id
5014 * @id: the cgroup id
5015 * @ss: cgroup subsys to be looked into
5017 * Returns the css if there's valid one with @id, otherwise returns NULL.
5018 * Should be called under rcu_read_lock().
5020 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5022 struct cgroup *cgrp;
5024 cgroup_assert_mutex_or_rcu_locked();
5026 cgrp = idr_find(&ss->root->cgroup_idr, id);
5028 return cgroup_css(cgrp, ss);
5032 #ifdef CONFIG_CGROUP_DEBUG
5033 static struct cgroup_subsys_state *
5034 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5036 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5039 return ERR_PTR(-ENOMEM);
5044 static void debug_css_free(struct cgroup_subsys_state *css)
5049 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5052 return cgroup_task_count(css->cgroup);
5055 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5058 return (u64)(unsigned long)current->cgroups;
5061 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5067 count = atomic_read(&task_css_set(current)->refcount);
5072 static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
5074 struct cgrp_cset_link *link;
5075 struct css_set *cset;
5077 read_lock(&css_set_lock);
5079 cset = rcu_dereference(current->cgroups);
5080 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5081 struct cgroup *c = link->cgrp;
5085 name = c->dentry->d_name.name;
5088 seq_printf(seq, "Root %d group %s\n",
5089 c->root->hierarchy_id, name);
5092 read_unlock(&css_set_lock);
5096 #define MAX_TASKS_SHOWN_PER_CSS 25
5097 static int cgroup_css_links_read(struct seq_file *seq, void *v)
5099 struct cgroup_subsys_state *css = seq_css(seq);
5100 struct cgrp_cset_link *link;
5102 read_lock(&css_set_lock);
5103 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5104 struct css_set *cset = link->cset;
5105 struct task_struct *task;
5107 seq_printf(seq, "css_set %p\n", cset);
5108 list_for_each_entry(task, &cset->tasks, cg_list) {
5109 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5110 seq_puts(seq, " ...\n");
5113 seq_printf(seq, " task %d\n",
5114 task_pid_vnr(task));
5118 read_unlock(&css_set_lock);
5122 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5124 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
5127 static struct cftype debug_files[] = {
5129 .name = "taskcount",
5130 .read_u64 = debug_taskcount_read,
5134 .name = "current_css_set",
5135 .read_u64 = current_css_set_read,
5139 .name = "current_css_set_refcount",
5140 .read_u64 = current_css_set_refcount_read,
5144 .name = "current_css_set_cg_links",
5145 .seq_show = current_css_set_cg_links_read,
5149 .name = "cgroup_css_links",
5150 .seq_show = cgroup_css_links_read,
5154 .name = "releasable",
5155 .read_u64 = releasable_read,
5161 struct cgroup_subsys debug_cgrp_subsys = {
5162 .css_alloc = debug_css_alloc,
5163 .css_free = debug_css_free,
5164 .base_cftypes = debug_files,
5166 #endif /* CONFIG_CGROUP_DEBUG */