2 * Generic process-grouping system.
4 * Based originally on the cpuset system, extracted by Paul Menage
5 * Copyright (C) 2006 Google, Inc
7 * Notifications support
8 * Copyright (C) 2009 Nokia Corporation
9 * Author: Kirill A. Shutemov
11 * Copyright notices from the original cpuset code:
12 * --------------------------------------------------
13 * Copyright (C) 2003 BULL SA.
14 * Copyright (C) 2004-2006 Silicon Graphics, Inc.
16 * Portions derived from Patrick Mochel's sysfs code.
17 * sysfs is Copyright (c) 2001-3 Patrick Mochel
19 * 2003-10-10 Written by Simon Derr.
20 * 2003-10-22 Updates by Stephen Hemminger.
21 * 2004 May-July Rework by Paul Jackson.
22 * ---------------------------------------------------
24 * This file is subject to the terms and conditions of the GNU General Public
25 * License. See the file COPYING in the main directory of the Linux
26 * distribution for more details.
29 #include <linux/cgroup.h>
30 #include <linux/cred.h>
31 #include <linux/ctype.h>
32 #include <linux/errno.h>
33 #include <linux/init_task.h>
34 #include <linux/kernel.h>
35 #include <linux/list.h>
37 #include <linux/mutex.h>
38 #include <linux/mount.h>
39 #include <linux/pagemap.h>
40 #include <linux/proc_fs.h>
41 #include <linux/rcupdate.h>
42 #include <linux/sched.h>
43 #include <linux/backing-dev.h>
44 #include <linux/seq_file.h>
45 #include <linux/slab.h>
46 #include <linux/magic.h>
47 #include <linux/spinlock.h>
48 #include <linux/string.h>
49 #include <linux/sort.h>
50 #include <linux/kmod.h>
51 #include <linux/module.h>
52 #include <linux/delayacct.h>
53 #include <linux/cgroupstats.h>
54 #include <linux/hashtable.h>
55 #include <linux/namei.h>
56 #include <linux/pid_namespace.h>
57 #include <linux/idr.h>
58 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
59 #include <linux/eventfd.h>
60 #include <linux/poll.h>
61 #include <linux/flex_array.h> /* used in cgroup_attach_task */
62 #include <linux/kthread.h>
64 #include <linux/atomic.h>
67 * cgroup_mutex is the master lock. Any modification to cgroup or its
68 * hierarchy must be performed while holding it.
70 * cgroup_root_mutex nests inside cgroup_mutex and should be held to modify
71 * cgroupfs_root of any cgroup hierarchy - subsys list, flags,
72 * release_agent_path and so on. Modifying requires both cgroup_mutex and
73 * cgroup_root_mutex. Readers can acquire either of the two. This is to
74 * break the following locking order cycle.
76 * A. cgroup_mutex -> cred_guard_mutex -> s_type->i_mutex_key -> namespace_sem
77 * B. namespace_sem -> cgroup_mutex
79 * B happens only through cgroup_show_options() and using cgroup_root_mutex
82 #ifdef CONFIG_PROVE_RCU
83 DEFINE_MUTEX(cgroup_mutex);
84 EXPORT_SYMBOL_GPL(cgroup_mutex); /* only for lockdep */
86 static DEFINE_MUTEX(cgroup_mutex);
89 static DEFINE_MUTEX(cgroup_root_mutex);
92 * Generate an array of cgroup subsystem pointers. At boot time, this is
93 * populated with the built in subsystems, and modular subsystems are
94 * registered after that. The mutable section of this array is protected by
97 #define SUBSYS(_x) [_x ## _subsys_id] = &_x ## _subsys,
98 #define IS_SUBSYS_ENABLED(option) IS_BUILTIN(option)
99 static struct cgroup_subsys *cgroup_subsys[CGROUP_SUBSYS_COUNT] = {
100 #include <linux/cgroup_subsys.h>
104 * The dummy hierarchy, reserved for the subsystems that are otherwise
105 * unattached - it never has more than a single cgroup, and all tasks are
106 * part of that cgroup.
108 static struct cgroupfs_root cgroup_dummy_root;
110 /* dummy_top is a shorthand for the dummy hierarchy's top cgroup */
111 static struct cgroup * const cgroup_dummy_top = &cgroup_dummy_root.top_cgroup;
114 * cgroupfs file entry, pointed to from leaf dentry->d_fsdata.
117 struct list_head node;
118 struct dentry *dentry;
120 struct cgroup_subsys_state *css;
123 struct simple_xattrs xattrs;
127 * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when
128 * cgroup_subsys->use_id != 0.
130 #define CSS_ID_MAX (65535)
133 * The css to which this ID points. This pointer is set to valid value
134 * after cgroup is populated. If cgroup is removed, this will be NULL.
135 * This pointer is expected to be RCU-safe because destroy()
136 * is called after synchronize_rcu(). But for safe use, css_tryget()
137 * should be used for avoiding race.
139 struct cgroup_subsys_state __rcu *css;
145 * Depth in hierarchy which this ID belongs to.
147 unsigned short depth;
149 * ID is freed by RCU. (and lookup routine is RCU safe.)
151 struct rcu_head rcu_head;
153 * Hierarchy of CSS ID belongs to.
155 unsigned short stack[0]; /* Array of Length (depth+1) */
159 * cgroup_event represents events which userspace want to receive.
161 struct cgroup_event {
163 * css which the event belongs to.
165 struct cgroup_subsys_state *css;
167 * Control file which the event associated.
171 * eventfd to signal userspace about the event.
173 struct eventfd_ctx *eventfd;
175 * Each of these stored in a list by the cgroup.
177 struct list_head list;
179 * All fields below needed to unregister event when
180 * userspace closes eventfd.
183 wait_queue_head_t *wqh;
185 struct work_struct remove;
188 /* The list of hierarchy roots */
190 static LIST_HEAD(cgroup_roots);
191 static int cgroup_root_count;
194 * Hierarchy ID allocation and mapping. It follows the same exclusion
195 * rules as other root ops - both cgroup_mutex and cgroup_root_mutex for
196 * writes, either for reads.
198 static DEFINE_IDR(cgroup_hierarchy_idr);
200 static struct cgroup_name root_cgroup_name = { .name = "/" };
203 * Assign a monotonically increasing serial number to cgroups. It
204 * guarantees cgroups with bigger numbers are newer than those with smaller
205 * numbers. Also, as cgroups are always appended to the parent's
206 * ->children list, it guarantees that sibling cgroups are always sorted in
207 * the ascending serial number order on the list. Protected by
210 static u64 cgroup_serial_nr_next = 1;
212 /* This flag indicates whether tasks in the fork and exit paths should
213 * check for fork/exit handlers to call. This avoids us having to do
214 * extra work in the fork/exit path if none of the subsystems need to
217 static int need_forkexit_callback __read_mostly;
219 static struct cftype cgroup_base_files[];
221 static void cgroup_destroy_css_killed(struct cgroup *cgrp);
222 static int cgroup_destroy_locked(struct cgroup *cgrp);
223 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
227 * cgroup_css - obtain a cgroup's css for the specified subsystem
228 * @cgrp: the cgroup of interest
229 * @subsys_id: the subsystem of interest
231 * Return @cgrp's css (cgroup_subsys_state) associated with @subsys_id.
232 * This function must be called either under cgroup_mutex or
233 * rcu_read_lock() and the caller is responsible for pinning the returned
234 * css if it wants to keep accessing it outside the said locks. This
235 * function may return %NULL if @cgrp doesn't have @subsys_id enabled.
237 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
240 return rcu_dereference_check(cgrp->subsys[subsys_id],
241 lockdep_is_held(&cgroup_mutex));
244 /* convenient tests for these bits */
245 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
247 return test_bit(CGRP_DEAD, &cgrp->flags);
251 * cgroup_is_descendant - test ancestry
252 * @cgrp: the cgroup to be tested
253 * @ancestor: possible ancestor of @cgrp
255 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
256 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
257 * and @ancestor are accessible.
259 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
262 if (cgrp == ancestor)
268 EXPORT_SYMBOL_GPL(cgroup_is_descendant);
270 static int cgroup_is_releasable(const struct cgroup *cgrp)
273 (1 << CGRP_RELEASABLE) |
274 (1 << CGRP_NOTIFY_ON_RELEASE);
275 return (cgrp->flags & bits) == bits;
278 static int notify_on_release(const struct cgroup *cgrp)
280 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
284 * for_each_subsys - iterate all loaded cgroup subsystems
285 * @ss: the iteration cursor
286 * @i: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
288 * Should be called under cgroup_mutex.
290 #define for_each_subsys(ss, i) \
291 for ((i) = 0; (i) < CGROUP_SUBSYS_COUNT; (i)++) \
292 if (({ lockdep_assert_held(&cgroup_mutex); \
293 !((ss) = cgroup_subsys[i]); })) { } \
297 * for_each_builtin_subsys - iterate all built-in cgroup subsystems
298 * @ss: the iteration cursor
299 * @i: the index of @ss, CGROUP_BUILTIN_SUBSYS_COUNT after reaching the end
301 * Bulit-in subsystems are always present and iteration itself doesn't
302 * require any synchronization.
304 #define for_each_builtin_subsys(ss, i) \
305 for ((i) = 0; (i) < CGROUP_BUILTIN_SUBSYS_COUNT && \
306 (((ss) = cgroup_subsys[i]) || true); (i)++)
308 /* iterate each subsystem attached to a hierarchy */
309 #define for_each_root_subsys(root, ss) \
310 list_for_each_entry((ss), &(root)->subsys_list, sibling)
312 /* iterate across the active hierarchies */
313 #define for_each_active_root(root) \
314 list_for_each_entry((root), &cgroup_roots, root_list)
316 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
318 return dentry->d_fsdata;
321 static inline struct cfent *__d_cfe(struct dentry *dentry)
323 return dentry->d_fsdata;
326 static inline struct cftype *__d_cft(struct dentry *dentry)
328 return __d_cfe(dentry)->type;
332 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
333 * @cgrp: the cgroup to be checked for liveness
335 * On success, returns true; the mutex should be later unlocked. On
336 * failure returns false with no lock held.
338 static bool cgroup_lock_live_group(struct cgroup *cgrp)
340 mutex_lock(&cgroup_mutex);
341 if (cgroup_is_dead(cgrp)) {
342 mutex_unlock(&cgroup_mutex);
348 /* the list of cgroups eligible for automatic release. Protected by
349 * release_list_lock */
350 static LIST_HEAD(release_list);
351 static DEFINE_RAW_SPINLOCK(release_list_lock);
352 static void cgroup_release_agent(struct work_struct *work);
353 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
354 static void check_for_release(struct cgroup *cgrp);
357 * A cgroup can be associated with multiple css_sets as different tasks may
358 * belong to different cgroups on different hierarchies. In the other
359 * direction, a css_set is naturally associated with multiple cgroups.
360 * This M:N relationship is represented by the following link structure
361 * which exists for each association and allows traversing the associations
364 struct cgrp_cset_link {
365 /* the cgroup and css_set this link associates */
367 struct css_set *cset;
369 /* list of cgrp_cset_links anchored at cgrp->cset_links */
370 struct list_head cset_link;
372 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
373 struct list_head cgrp_link;
376 /* The default css_set - used by init and its children prior to any
377 * hierarchies being mounted. It contains a pointer to the root state
378 * for each subsystem. Also used to anchor the list of css_sets. Not
379 * reference-counted, to improve performance when child cgroups
380 * haven't been created.
383 static struct css_set init_css_set;
384 static struct cgrp_cset_link init_cgrp_cset_link;
386 static int cgroup_init_idr(struct cgroup_subsys *ss,
387 struct cgroup_subsys_state *css);
390 * css_set_lock protects the list of css_set objects, and the chain of
391 * tasks off each css_set. Nests outside task->alloc_lock due to
392 * css_task_iter_start().
394 static DEFINE_RWLOCK(css_set_lock);
395 static int css_set_count;
398 * hash table for cgroup groups. This improves the performance to find
399 * an existing css_set. This hash doesn't (currently) take into
400 * account cgroups in empty hierarchies.
402 #define CSS_SET_HASH_BITS 7
403 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
405 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
407 unsigned long key = 0UL;
408 struct cgroup_subsys *ss;
411 for_each_subsys(ss, i)
412 key += (unsigned long)css[i];
413 key = (key >> 16) ^ key;
419 * We don't maintain the lists running through each css_set to its task
420 * until after the first call to css_task_iter_start(). This reduces the
421 * fork()/exit() overhead for people who have cgroups compiled into their
422 * kernel but not actually in use.
424 static int use_task_css_set_links __read_mostly;
426 static void __put_css_set(struct css_set *cset, int taskexit)
428 struct cgrp_cset_link *link, *tmp_link;
431 * Ensure that the refcount doesn't hit zero while any readers
432 * can see it. Similar to atomic_dec_and_lock(), but for an
435 if (atomic_add_unless(&cset->refcount, -1, 1))
437 write_lock(&css_set_lock);
438 if (!atomic_dec_and_test(&cset->refcount)) {
439 write_unlock(&css_set_lock);
443 /* This css_set is dead. unlink it and release cgroup refcounts */
444 hash_del(&cset->hlist);
447 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
448 struct cgroup *cgrp = link->cgrp;
450 list_del(&link->cset_link);
451 list_del(&link->cgrp_link);
453 /* @cgrp can't go away while we're holding css_set_lock */
454 if (list_empty(&cgrp->cset_links) && notify_on_release(cgrp)) {
456 set_bit(CGRP_RELEASABLE, &cgrp->flags);
457 check_for_release(cgrp);
463 write_unlock(&css_set_lock);
464 kfree_rcu(cset, rcu_head);
468 * refcounted get/put for css_set objects
470 static inline void get_css_set(struct css_set *cset)
472 atomic_inc(&cset->refcount);
475 static inline void put_css_set(struct css_set *cset)
477 __put_css_set(cset, 0);
480 static inline void put_css_set_taskexit(struct css_set *cset)
482 __put_css_set(cset, 1);
486 * compare_css_sets - helper function for find_existing_css_set().
487 * @cset: candidate css_set being tested
488 * @old_cset: existing css_set for a task
489 * @new_cgrp: cgroup that's being entered by the task
490 * @template: desired set of css pointers in css_set (pre-calculated)
492 * Returns true if "cset" matches "old_cset" except for the hierarchy
493 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
495 static bool compare_css_sets(struct css_set *cset,
496 struct css_set *old_cset,
497 struct cgroup *new_cgrp,
498 struct cgroup_subsys_state *template[])
500 struct list_head *l1, *l2;
502 if (memcmp(template, cset->subsys, sizeof(cset->subsys))) {
503 /* Not all subsystems matched */
508 * Compare cgroup pointers in order to distinguish between
509 * different cgroups in heirarchies with no subsystems. We
510 * could get by with just this check alone (and skip the
511 * memcmp above) but on most setups the memcmp check will
512 * avoid the need for this more expensive check on almost all
516 l1 = &cset->cgrp_links;
517 l2 = &old_cset->cgrp_links;
519 struct cgrp_cset_link *link1, *link2;
520 struct cgroup *cgrp1, *cgrp2;
524 /* See if we reached the end - both lists are equal length. */
525 if (l1 == &cset->cgrp_links) {
526 BUG_ON(l2 != &old_cset->cgrp_links);
529 BUG_ON(l2 == &old_cset->cgrp_links);
531 /* Locate the cgroups associated with these links. */
532 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
533 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
536 /* Hierarchies should be linked in the same order. */
537 BUG_ON(cgrp1->root != cgrp2->root);
540 * If this hierarchy is the hierarchy of the cgroup
541 * that's changing, then we need to check that this
542 * css_set points to the new cgroup; if it's any other
543 * hierarchy, then this css_set should point to the
544 * same cgroup as the old css_set.
546 if (cgrp1->root == new_cgrp->root) {
547 if (cgrp1 != new_cgrp)
558 * find_existing_css_set - init css array and find the matching css_set
559 * @old_cset: the css_set that we're using before the cgroup transition
560 * @cgrp: the cgroup that we're moving into
561 * @template: out param for the new set of csses, should be clear on entry
563 static struct css_set *find_existing_css_set(struct css_set *old_cset,
565 struct cgroup_subsys_state *template[])
567 struct cgroupfs_root *root = cgrp->root;
568 struct cgroup_subsys *ss;
569 struct css_set *cset;
574 * Build the set of subsystem state objects that we want to see in the
575 * new css_set. while subsystems can change globally, the entries here
576 * won't change, so no need for locking.
578 for_each_subsys(ss, i) {
579 if (root->subsys_mask & (1UL << i)) {
580 /* Subsystem is in this hierarchy. So we want
581 * the subsystem state from the new
583 template[i] = cgroup_css(cgrp, i);
585 /* Subsystem is not in this hierarchy, so we
586 * don't want to change the subsystem state */
587 template[i] = old_cset->subsys[i];
591 key = css_set_hash(template);
592 hash_for_each_possible(css_set_table, cset, hlist, key) {
593 if (!compare_css_sets(cset, old_cset, cgrp, template))
596 /* This css_set matches what we need */
600 /* No existing cgroup group matched */
604 static void free_cgrp_cset_links(struct list_head *links_to_free)
606 struct cgrp_cset_link *link, *tmp_link;
608 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
609 list_del(&link->cset_link);
615 * allocate_cgrp_cset_links - allocate cgrp_cset_links
616 * @count: the number of links to allocate
617 * @tmp_links: list_head the allocated links are put on
619 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
620 * through ->cset_link. Returns 0 on success or -errno.
622 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
624 struct cgrp_cset_link *link;
627 INIT_LIST_HEAD(tmp_links);
629 for (i = 0; i < count; i++) {
630 link = kzalloc(sizeof(*link), GFP_KERNEL);
632 free_cgrp_cset_links(tmp_links);
635 list_add(&link->cset_link, tmp_links);
641 * link_css_set - a helper function to link a css_set to a cgroup
642 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
643 * @cset: the css_set to be linked
644 * @cgrp: the destination cgroup
646 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
649 struct cgrp_cset_link *link;
651 BUG_ON(list_empty(tmp_links));
652 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
655 list_move(&link->cset_link, &cgrp->cset_links);
657 * Always add links to the tail of the list so that the list
658 * is sorted by order of hierarchy creation
660 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
664 * find_css_set - return a new css_set with one cgroup updated
665 * @old_cset: the baseline css_set
666 * @cgrp: the cgroup to be updated
668 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
669 * substituted into the appropriate hierarchy.
671 static struct css_set *find_css_set(struct css_set *old_cset,
674 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
675 struct css_set *cset;
676 struct list_head tmp_links;
677 struct cgrp_cset_link *link;
680 lockdep_assert_held(&cgroup_mutex);
682 /* First see if we already have a cgroup group that matches
684 read_lock(&css_set_lock);
685 cset = find_existing_css_set(old_cset, cgrp, template);
688 read_unlock(&css_set_lock);
693 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
697 /* Allocate all the cgrp_cset_link objects that we'll need */
698 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
703 atomic_set(&cset->refcount, 1);
704 INIT_LIST_HEAD(&cset->cgrp_links);
705 INIT_LIST_HEAD(&cset->tasks);
706 INIT_HLIST_NODE(&cset->hlist);
708 /* Copy the set of subsystem state objects generated in
709 * find_existing_css_set() */
710 memcpy(cset->subsys, template, sizeof(cset->subsys));
712 write_lock(&css_set_lock);
713 /* Add reference counts and links from the new css_set. */
714 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
715 struct cgroup *c = link->cgrp;
717 if (c->root == cgrp->root)
719 link_css_set(&tmp_links, cset, c);
722 BUG_ON(!list_empty(&tmp_links));
726 /* Add this cgroup group to the hash table */
727 key = css_set_hash(cset->subsys);
728 hash_add(css_set_table, &cset->hlist, key);
730 write_unlock(&css_set_lock);
736 * Return the cgroup for "task" from the given hierarchy. Must be
737 * called with cgroup_mutex held.
739 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
740 struct cgroupfs_root *root)
742 struct css_set *cset;
743 struct cgroup *res = NULL;
745 BUG_ON(!mutex_is_locked(&cgroup_mutex));
746 read_lock(&css_set_lock);
748 * No need to lock the task - since we hold cgroup_mutex the
749 * task can't change groups, so the only thing that can happen
750 * is that it exits and its css is set back to init_css_set.
752 cset = task_css_set(task);
753 if (cset == &init_css_set) {
754 res = &root->top_cgroup;
756 struct cgrp_cset_link *link;
758 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
759 struct cgroup *c = link->cgrp;
761 if (c->root == root) {
767 read_unlock(&css_set_lock);
773 * There is one global cgroup mutex. We also require taking
774 * task_lock() when dereferencing a task's cgroup subsys pointers.
775 * See "The task_lock() exception", at the end of this comment.
777 * A task must hold cgroup_mutex to modify cgroups.
779 * Any task can increment and decrement the count field without lock.
780 * So in general, code holding cgroup_mutex can't rely on the count
781 * field not changing. However, if the count goes to zero, then only
782 * cgroup_attach_task() can increment it again. Because a count of zero
783 * means that no tasks are currently attached, therefore there is no
784 * way a task attached to that cgroup can fork (the other way to
785 * increment the count). So code holding cgroup_mutex can safely
786 * assume that if the count is zero, it will stay zero. Similarly, if
787 * a task holds cgroup_mutex on a cgroup with zero count, it
788 * knows that the cgroup won't be removed, as cgroup_rmdir()
791 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
792 * (usually) take cgroup_mutex. These are the two most performance
793 * critical pieces of code here. The exception occurs on cgroup_exit(),
794 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
795 * is taken, and if the cgroup count is zero, a usermode call made
796 * to the release agent with the name of the cgroup (path relative to
797 * the root of cgroup file system) as the argument.
799 * A cgroup can only be deleted if both its 'count' of using tasks
800 * is zero, and its list of 'children' cgroups is empty. Since all
801 * tasks in the system use _some_ cgroup, and since there is always at
802 * least one task in the system (init, pid == 1), therefore, top_cgroup
803 * always has either children cgroups and/or using tasks. So we don't
804 * need a special hack to ensure that top_cgroup cannot be deleted.
806 * The task_lock() exception
808 * The need for this exception arises from the action of
809 * cgroup_attach_task(), which overwrites one task's cgroup pointer with
810 * another. It does so using cgroup_mutex, however there are
811 * several performance critical places that need to reference
812 * task->cgroup without the expense of grabbing a system global
813 * mutex. Therefore except as noted below, when dereferencing or, as
814 * in cgroup_attach_task(), modifying a task's cgroup pointer we use
815 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
816 * the task_struct routinely used for such matters.
818 * P.S. One more locking exception. RCU is used to guard the
819 * update of a tasks cgroup pointer by cgroup_attach_task()
823 * A couple of forward declarations required, due to cyclic reference loop:
824 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
825 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
829 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode);
830 static struct dentry *cgroup_lookup(struct inode *, struct dentry *, unsigned int);
831 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
832 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask);
833 static const struct inode_operations cgroup_dir_inode_operations;
834 static const struct file_operations proc_cgroupstats_operations;
836 static struct backing_dev_info cgroup_backing_dev_info = {
838 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
841 static int alloc_css_id(struct cgroup_subsys_state *child_css);
843 static struct inode *cgroup_new_inode(umode_t mode, struct super_block *sb)
845 struct inode *inode = new_inode(sb);
848 inode->i_ino = get_next_ino();
849 inode->i_mode = mode;
850 inode->i_uid = current_fsuid();
851 inode->i_gid = current_fsgid();
852 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
853 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
858 static struct cgroup_name *cgroup_alloc_name(struct dentry *dentry)
860 struct cgroup_name *name;
862 name = kmalloc(sizeof(*name) + dentry->d_name.len + 1, GFP_KERNEL);
865 strcpy(name->name, dentry->d_name.name);
869 static void cgroup_free_fn(struct work_struct *work)
871 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
872 struct cgroup_subsys *ss;
874 mutex_lock(&cgroup_mutex);
876 * Release the subsystem state objects.
878 for_each_root_subsys(cgrp->root, ss) {
879 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss->subsys_id);
884 cgrp->root->number_of_cgroups--;
885 mutex_unlock(&cgroup_mutex);
888 * We get a ref to the parent's dentry, and put the ref when
889 * this cgroup is being freed, so it's guaranteed that the
890 * parent won't be destroyed before its children.
892 dput(cgrp->parent->dentry);
895 * Drop the active superblock reference that we took when we
896 * created the cgroup. This will free cgrp->root, if we are
897 * holding the last reference to @sb.
899 deactivate_super(cgrp->root->sb);
902 * if we're getting rid of the cgroup, refcount should ensure
903 * that there are no pidlists left.
905 BUG_ON(!list_empty(&cgrp->pidlists));
907 simple_xattrs_free(&cgrp->xattrs);
909 kfree(rcu_dereference_raw(cgrp->name));
913 static void cgroup_free_rcu(struct rcu_head *head)
915 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
917 INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
918 schedule_work(&cgrp->destroy_work);
921 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
923 /* is dentry a directory ? if so, kfree() associated cgroup */
924 if (S_ISDIR(inode->i_mode)) {
925 struct cgroup *cgrp = dentry->d_fsdata;
927 BUG_ON(!(cgroup_is_dead(cgrp)));
928 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
930 struct cfent *cfe = __d_cfe(dentry);
931 struct cgroup *cgrp = dentry->d_parent->d_fsdata;
933 WARN_ONCE(!list_empty(&cfe->node) &&
934 cgrp != &cgrp->root->top_cgroup,
935 "cfe still linked for %s\n", cfe->type->name);
936 simple_xattrs_free(&cfe->xattrs);
942 static int cgroup_delete(const struct dentry *d)
947 static void remove_dir(struct dentry *d)
949 struct dentry *parent = dget(d->d_parent);
952 simple_rmdir(parent->d_inode, d);
956 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
960 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
961 lockdep_assert_held(&cgroup_mutex);
964 * If we're doing cleanup due to failure of cgroup_create(),
965 * the corresponding @cfe may not exist.
967 list_for_each_entry(cfe, &cgrp->files, node) {
968 struct dentry *d = cfe->dentry;
970 if (cft && cfe->type != cft)
975 simple_unlink(cgrp->dentry->d_inode, d);
976 list_del_init(&cfe->node);
984 * cgroup_clear_dir - remove subsys files in a cgroup directory
985 * @cgrp: target cgroup
986 * @subsys_mask: mask of the subsystem ids whose files should be removed
988 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned long subsys_mask)
990 struct cgroup_subsys *ss;
993 for_each_subsys(ss, i) {
994 struct cftype_set *set;
996 if (!test_bit(i, &subsys_mask))
998 list_for_each_entry(set, &ss->cftsets, node)
999 cgroup_addrm_files(cgrp, set->cfts, false);
1004 * NOTE : the dentry must have been dget()'ed
1006 static void cgroup_d_remove_dir(struct dentry *dentry)
1008 struct dentry *parent;
1010 parent = dentry->d_parent;
1011 spin_lock(&parent->d_lock);
1012 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
1013 list_del_init(&dentry->d_u.d_child);
1014 spin_unlock(&dentry->d_lock);
1015 spin_unlock(&parent->d_lock);
1020 * Call with cgroup_mutex held. Drops reference counts on modules, including
1021 * any duplicate ones that parse_cgroupfs_options took. If this function
1022 * returns an error, no reference counts are touched.
1024 static int rebind_subsystems(struct cgroupfs_root *root,
1025 unsigned long added_mask, unsigned removed_mask)
1027 struct cgroup *cgrp = &root->top_cgroup;
1028 struct cgroup_subsys *ss;
1029 unsigned long pinned = 0;
1032 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1033 BUG_ON(!mutex_is_locked(&cgroup_root_mutex));
1035 /* Check that any added subsystems are currently free */
1036 for_each_subsys(ss, i) {
1037 if (!(added_mask & (1 << i)))
1040 /* is the subsystem mounted elsewhere? */
1041 if (ss->root != &cgroup_dummy_root) {
1046 /* pin the module */
1047 if (!try_module_get(ss->module)) {
1054 /* subsys could be missing if unloaded between parsing and here */
1055 if (added_mask != pinned) {
1060 ret = cgroup_populate_dir(cgrp, added_mask);
1065 * Nothing can fail from this point on. Remove files for the
1066 * removed subsystems and rebind each subsystem.
1068 cgroup_clear_dir(cgrp, removed_mask);
1070 for_each_subsys(ss, i) {
1071 unsigned long bit = 1UL << i;
1073 if (bit & added_mask) {
1074 /* We're binding this subsystem to this hierarchy */
1075 BUG_ON(cgroup_css(cgrp, i));
1076 BUG_ON(!cgroup_css(cgroup_dummy_top, i));
1077 BUG_ON(cgroup_css(cgroup_dummy_top, i)->cgroup != cgroup_dummy_top);
1079 rcu_assign_pointer(cgrp->subsys[i],
1080 cgroup_css(cgroup_dummy_top, i));
1081 cgroup_css(cgrp, i)->cgroup = cgrp;
1083 list_move(&ss->sibling, &root->subsys_list);
1086 ss->bind(cgroup_css(cgrp, i));
1088 /* refcount was already taken, and we're keeping it */
1089 root->subsys_mask |= bit;
1090 } else if (bit & removed_mask) {
1091 /* We're removing this subsystem */
1092 BUG_ON(cgroup_css(cgrp, i) != cgroup_css(cgroup_dummy_top, i));
1093 BUG_ON(cgroup_css(cgrp, i)->cgroup != cgrp);
1096 ss->bind(cgroup_css(cgroup_dummy_top, i));
1098 cgroup_css(cgroup_dummy_top, i)->cgroup = cgroup_dummy_top;
1099 RCU_INIT_POINTER(cgrp->subsys[i], NULL);
1101 cgroup_subsys[i]->root = &cgroup_dummy_root;
1102 list_move(&ss->sibling, &cgroup_dummy_root.subsys_list);
1104 /* subsystem is now free - drop reference on module */
1105 module_put(ss->module);
1106 root->subsys_mask &= ~bit;
1111 * Mark @root has finished binding subsystems. @root->subsys_mask
1112 * now matches the bound subsystems.
1114 root->flags |= CGRP_ROOT_SUBSYS_BOUND;
1119 for_each_subsys(ss, i)
1120 if (pinned & (1 << i))
1121 module_put(ss->module);
1125 static int cgroup_show_options(struct seq_file *seq, struct dentry *dentry)
1127 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
1128 struct cgroup_subsys *ss;
1130 mutex_lock(&cgroup_root_mutex);
1131 for_each_root_subsys(root, ss)
1132 seq_printf(seq, ",%s", ss->name);
1133 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1134 seq_puts(seq, ",sane_behavior");
1135 if (root->flags & CGRP_ROOT_NOPREFIX)
1136 seq_puts(seq, ",noprefix");
1137 if (root->flags & CGRP_ROOT_XATTR)
1138 seq_puts(seq, ",xattr");
1139 if (strlen(root->release_agent_path))
1140 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1141 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1142 seq_puts(seq, ",clone_children");
1143 if (strlen(root->name))
1144 seq_printf(seq, ",name=%s", root->name);
1145 mutex_unlock(&cgroup_root_mutex);
1149 struct cgroup_sb_opts {
1150 unsigned long subsys_mask;
1151 unsigned long flags;
1152 char *release_agent;
1153 bool cpuset_clone_children;
1155 /* User explicitly requested empty subsystem */
1158 struct cgroupfs_root *new_root;
1163 * Convert a hierarchy specifier into a bitmask of subsystems and
1164 * flags. Call with cgroup_mutex held to protect the cgroup_subsys[]
1165 * array. This function takes refcounts on subsystems to be used, unless it
1166 * returns error, in which case no refcounts are taken.
1168 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1170 char *token, *o = data;
1171 bool all_ss = false, one_ss = false;
1172 unsigned long mask = (unsigned long)-1;
1173 struct cgroup_subsys *ss;
1176 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1178 #ifdef CONFIG_CPUSETS
1179 mask = ~(1UL << cpuset_subsys_id);
1182 memset(opts, 0, sizeof(*opts));
1184 while ((token = strsep(&o, ",")) != NULL) {
1187 if (!strcmp(token, "none")) {
1188 /* Explicitly have no subsystems */
1192 if (!strcmp(token, "all")) {
1193 /* Mutually exclusive option 'all' + subsystem name */
1199 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1200 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1203 if (!strcmp(token, "noprefix")) {
1204 opts->flags |= CGRP_ROOT_NOPREFIX;
1207 if (!strcmp(token, "clone_children")) {
1208 opts->cpuset_clone_children = true;
1211 if (!strcmp(token, "xattr")) {
1212 opts->flags |= CGRP_ROOT_XATTR;
1215 if (!strncmp(token, "release_agent=", 14)) {
1216 /* Specifying two release agents is forbidden */
1217 if (opts->release_agent)
1219 opts->release_agent =
1220 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1221 if (!opts->release_agent)
1225 if (!strncmp(token, "name=", 5)) {
1226 const char *name = token + 5;
1227 /* Can't specify an empty name */
1230 /* Must match [\w.-]+ */
1231 for (i = 0; i < strlen(name); i++) {
1235 if ((c == '.') || (c == '-') || (c == '_'))
1239 /* Specifying two names is forbidden */
1242 opts->name = kstrndup(name,
1243 MAX_CGROUP_ROOT_NAMELEN - 1,
1251 for_each_subsys(ss, i) {
1252 if (strcmp(token, ss->name))
1257 /* Mutually exclusive option 'all' + subsystem name */
1260 set_bit(i, &opts->subsys_mask);
1265 if (i == CGROUP_SUBSYS_COUNT)
1270 * If the 'all' option was specified select all the subsystems,
1271 * otherwise if 'none', 'name=' and a subsystem name options
1272 * were not specified, let's default to 'all'
1274 if (all_ss || (!one_ss && !opts->none && !opts->name))
1275 for_each_subsys(ss, i)
1277 set_bit(i, &opts->subsys_mask);
1279 /* Consistency checks */
1281 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1282 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1284 if (opts->flags & CGRP_ROOT_NOPREFIX) {
1285 pr_err("cgroup: sane_behavior: noprefix is not allowed\n");
1289 if (opts->cpuset_clone_children) {
1290 pr_err("cgroup: sane_behavior: clone_children is not allowed\n");
1296 * Option noprefix was introduced just for backward compatibility
1297 * with the old cpuset, so we allow noprefix only if mounting just
1298 * the cpuset subsystem.
1300 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1304 /* Can't specify "none" and some subsystems */
1305 if (opts->subsys_mask && opts->none)
1309 * We either have to specify by name or by subsystems. (So all
1310 * empty hierarchies must have a name).
1312 if (!opts->subsys_mask && !opts->name)
1318 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1321 struct cgroupfs_root *root = sb->s_fs_info;
1322 struct cgroup *cgrp = &root->top_cgroup;
1323 struct cgroup_sb_opts opts;
1324 unsigned long added_mask, removed_mask;
1326 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1327 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1331 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1332 mutex_lock(&cgroup_mutex);
1333 mutex_lock(&cgroup_root_mutex);
1335 /* See what subsystems are wanted */
1336 ret = parse_cgroupfs_options(data, &opts);
1340 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1341 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1342 task_tgid_nr(current), current->comm);
1344 added_mask = opts.subsys_mask & ~root->subsys_mask;
1345 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1347 /* Don't allow flags or name to change at remount */
1348 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1349 (opts.name && strcmp(opts.name, root->name))) {
1350 pr_err("cgroup: option or name mismatch, new: 0x%lx \"%s\", old: 0x%lx \"%s\"\n",
1351 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1352 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1357 /* remounting is not allowed for populated hierarchies */
1358 if (root->number_of_cgroups > 1) {
1363 ret = rebind_subsystems(root, added_mask, removed_mask);
1367 if (opts.release_agent)
1368 strcpy(root->release_agent_path, opts.release_agent);
1370 kfree(opts.release_agent);
1372 mutex_unlock(&cgroup_root_mutex);
1373 mutex_unlock(&cgroup_mutex);
1374 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1378 static const struct super_operations cgroup_ops = {
1379 .statfs = simple_statfs,
1380 .drop_inode = generic_delete_inode,
1381 .show_options = cgroup_show_options,
1382 .remount_fs = cgroup_remount,
1385 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1387 INIT_LIST_HEAD(&cgrp->sibling);
1388 INIT_LIST_HEAD(&cgrp->children);
1389 INIT_LIST_HEAD(&cgrp->files);
1390 INIT_LIST_HEAD(&cgrp->cset_links);
1391 INIT_LIST_HEAD(&cgrp->release_list);
1392 INIT_LIST_HEAD(&cgrp->pidlists);
1393 mutex_init(&cgrp->pidlist_mutex);
1394 cgrp->dummy_css.cgroup = cgrp;
1395 INIT_LIST_HEAD(&cgrp->event_list);
1396 spin_lock_init(&cgrp->event_list_lock);
1397 simple_xattrs_init(&cgrp->xattrs);
1400 static void init_cgroup_root(struct cgroupfs_root *root)
1402 struct cgroup *cgrp = &root->top_cgroup;
1404 INIT_LIST_HEAD(&root->subsys_list);
1405 INIT_LIST_HEAD(&root->root_list);
1406 root->number_of_cgroups = 1;
1408 RCU_INIT_POINTER(cgrp->name, &root_cgroup_name);
1409 init_cgroup_housekeeping(cgrp);
1410 idr_init(&root->cgroup_idr);
1413 static int cgroup_init_root_id(struct cgroupfs_root *root, int start, int end)
1417 lockdep_assert_held(&cgroup_mutex);
1418 lockdep_assert_held(&cgroup_root_mutex);
1420 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, start, end,
1425 root->hierarchy_id = id;
1429 static void cgroup_exit_root_id(struct cgroupfs_root *root)
1431 lockdep_assert_held(&cgroup_mutex);
1432 lockdep_assert_held(&cgroup_root_mutex);
1434 if (root->hierarchy_id) {
1435 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1436 root->hierarchy_id = 0;
1440 static int cgroup_test_super(struct super_block *sb, void *data)
1442 struct cgroup_sb_opts *opts = data;
1443 struct cgroupfs_root *root = sb->s_fs_info;
1445 /* If we asked for a name then it must match */
1446 if (opts->name && strcmp(opts->name, root->name))
1450 * If we asked for subsystems (or explicitly for no
1451 * subsystems) then they must match
1453 if ((opts->subsys_mask || opts->none)
1454 && (opts->subsys_mask != root->subsys_mask))
1460 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1462 struct cgroupfs_root *root;
1464 if (!opts->subsys_mask && !opts->none)
1467 root = kzalloc(sizeof(*root), GFP_KERNEL);
1469 return ERR_PTR(-ENOMEM);
1471 init_cgroup_root(root);
1474 * We need to set @root->subsys_mask now so that @root can be
1475 * matched by cgroup_test_super() before it finishes
1476 * initialization; otherwise, competing mounts with the same
1477 * options may try to bind the same subsystems instead of waiting
1478 * for the first one leading to unexpected mount errors.
1479 * SUBSYS_BOUND will be set once actual binding is complete.
1481 root->subsys_mask = opts->subsys_mask;
1482 root->flags = opts->flags;
1483 if (opts->release_agent)
1484 strcpy(root->release_agent_path, opts->release_agent);
1486 strcpy(root->name, opts->name);
1487 if (opts->cpuset_clone_children)
1488 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1492 static void cgroup_free_root(struct cgroupfs_root *root)
1495 /* hierarhcy ID shoulid already have been released */
1496 WARN_ON_ONCE(root->hierarchy_id);
1498 idr_destroy(&root->cgroup_idr);
1503 static int cgroup_set_super(struct super_block *sb, void *data)
1506 struct cgroup_sb_opts *opts = data;
1508 /* If we don't have a new root, we can't set up a new sb */
1509 if (!opts->new_root)
1512 BUG_ON(!opts->subsys_mask && !opts->none);
1514 ret = set_anon_super(sb, NULL);
1518 sb->s_fs_info = opts->new_root;
1519 opts->new_root->sb = sb;
1521 sb->s_blocksize = PAGE_CACHE_SIZE;
1522 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1523 sb->s_magic = CGROUP_SUPER_MAGIC;
1524 sb->s_op = &cgroup_ops;
1529 static int cgroup_get_rootdir(struct super_block *sb)
1531 static const struct dentry_operations cgroup_dops = {
1532 .d_iput = cgroup_diput,
1533 .d_delete = cgroup_delete,
1536 struct inode *inode =
1537 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1542 inode->i_fop = &simple_dir_operations;
1543 inode->i_op = &cgroup_dir_inode_operations;
1544 /* directories start off with i_nlink == 2 (for "." entry) */
1546 sb->s_root = d_make_root(inode);
1549 /* for everything else we want ->d_op set */
1550 sb->s_d_op = &cgroup_dops;
1554 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1555 int flags, const char *unused_dev_name,
1558 struct cgroup_sb_opts opts;
1559 struct cgroupfs_root *root;
1561 struct super_block *sb;
1562 struct cgroupfs_root *new_root;
1563 struct list_head tmp_links;
1564 struct inode *inode;
1565 const struct cred *cred;
1567 /* First find the desired set of subsystems */
1568 mutex_lock(&cgroup_mutex);
1569 ret = parse_cgroupfs_options(data, &opts);
1570 mutex_unlock(&cgroup_mutex);
1575 * Allocate a new cgroup root. We may not need it if we're
1576 * reusing an existing hierarchy.
1578 new_root = cgroup_root_from_opts(&opts);
1579 if (IS_ERR(new_root)) {
1580 ret = PTR_ERR(new_root);
1583 opts.new_root = new_root;
1585 /* Locate an existing or new sb for this hierarchy */
1586 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1589 cgroup_free_root(opts.new_root);
1593 root = sb->s_fs_info;
1595 if (root == opts.new_root) {
1596 /* We used the new root structure, so this is a new hierarchy */
1597 struct cgroup *root_cgrp = &root->top_cgroup;
1598 struct cgroupfs_root *existing_root;
1600 struct css_set *cset;
1602 BUG_ON(sb->s_root != NULL);
1604 ret = cgroup_get_rootdir(sb);
1606 goto drop_new_super;
1607 inode = sb->s_root->d_inode;
1609 mutex_lock(&inode->i_mutex);
1610 mutex_lock(&cgroup_mutex);
1611 mutex_lock(&cgroup_root_mutex);
1613 root_cgrp->id = idr_alloc(&root->cgroup_idr, root_cgrp,
1615 if (root_cgrp->id < 0)
1618 /* Check for name clashes with existing mounts */
1620 if (strlen(root->name))
1621 for_each_active_root(existing_root)
1622 if (!strcmp(existing_root->name, root->name))
1626 * We're accessing css_set_count without locking
1627 * css_set_lock here, but that's OK - it can only be
1628 * increased by someone holding cgroup_lock, and
1629 * that's us. The worst that can happen is that we
1630 * have some link structures left over
1632 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1636 /* ID 0 is reserved for dummy root, 1 for unified hierarchy */
1637 ret = cgroup_init_root_id(root, 2, 0);
1641 sb->s_root->d_fsdata = root_cgrp;
1642 root_cgrp->dentry = sb->s_root;
1645 * We're inside get_sb() and will call lookup_one_len() to
1646 * create the root files, which doesn't work if SELinux is
1647 * in use. The following cred dancing somehow works around
1648 * it. See 2ce9738ba ("cgroupfs: use init_cred when
1649 * populating new cgroupfs mount") for more details.
1651 cred = override_creds(&init_cred);
1653 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1657 ret = rebind_subsystems(root, root->subsys_mask, 0);
1664 * There must be no failure case after here, since rebinding
1665 * takes care of subsystems' refcounts, which are explicitly
1666 * dropped in the failure exit path.
1669 list_add(&root->root_list, &cgroup_roots);
1670 cgroup_root_count++;
1672 /* Link the top cgroup in this hierarchy into all
1673 * the css_set objects */
1674 write_lock(&css_set_lock);
1675 hash_for_each(css_set_table, i, cset, hlist)
1676 link_css_set(&tmp_links, cset, root_cgrp);
1677 write_unlock(&css_set_lock);
1679 free_cgrp_cset_links(&tmp_links);
1681 BUG_ON(!list_empty(&root_cgrp->children));
1682 BUG_ON(root->number_of_cgroups != 1);
1684 mutex_unlock(&cgroup_root_mutex);
1685 mutex_unlock(&cgroup_mutex);
1686 mutex_unlock(&inode->i_mutex);
1689 * We re-used an existing hierarchy - the new root (if
1690 * any) is not needed
1692 cgroup_free_root(opts.new_root);
1694 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1695 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1696 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1698 goto drop_new_super;
1700 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1705 kfree(opts.release_agent);
1707 return dget(sb->s_root);
1710 free_cgrp_cset_links(&tmp_links);
1711 cgroup_addrm_files(&root->top_cgroup, cgroup_base_files, false);
1714 cgroup_exit_root_id(root);
1715 mutex_unlock(&cgroup_root_mutex);
1716 mutex_unlock(&cgroup_mutex);
1717 mutex_unlock(&inode->i_mutex);
1719 deactivate_locked_super(sb);
1721 kfree(opts.release_agent);
1723 return ERR_PTR(ret);
1726 static void cgroup_kill_sb(struct super_block *sb) {
1727 struct cgroupfs_root *root = sb->s_fs_info;
1728 struct cgroup *cgrp = &root->top_cgroup;
1729 struct cgrp_cset_link *link, *tmp_link;
1734 BUG_ON(root->number_of_cgroups != 1);
1735 BUG_ON(!list_empty(&cgrp->children));
1737 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1738 mutex_lock(&cgroup_mutex);
1739 mutex_lock(&cgroup_root_mutex);
1741 /* Rebind all subsystems back to the default hierarchy */
1742 if (root->flags & CGRP_ROOT_SUBSYS_BOUND) {
1743 ret = rebind_subsystems(root, 0, root->subsys_mask);
1744 /* Shouldn't be able to fail ... */
1749 * Release all the links from cset_links to this hierarchy's
1752 write_lock(&css_set_lock);
1754 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1755 list_del(&link->cset_link);
1756 list_del(&link->cgrp_link);
1759 write_unlock(&css_set_lock);
1761 if (!list_empty(&root->root_list)) {
1762 list_del(&root->root_list);
1763 cgroup_root_count--;
1766 cgroup_exit_root_id(root);
1768 mutex_unlock(&cgroup_root_mutex);
1769 mutex_unlock(&cgroup_mutex);
1770 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1772 simple_xattrs_free(&cgrp->xattrs);
1774 kill_litter_super(sb);
1775 cgroup_free_root(root);
1778 static struct file_system_type cgroup_fs_type = {
1780 .mount = cgroup_mount,
1781 .kill_sb = cgroup_kill_sb,
1784 static struct kobject *cgroup_kobj;
1787 * cgroup_path - generate the path of a cgroup
1788 * @cgrp: the cgroup in question
1789 * @buf: the buffer to write the path into
1790 * @buflen: the length of the buffer
1792 * Writes path of cgroup into buf. Returns 0 on success, -errno on error.
1794 * We can't generate cgroup path using dentry->d_name, as accessing
1795 * dentry->name must be protected by irq-unsafe dentry->d_lock or parent
1796 * inode's i_mutex, while on the other hand cgroup_path() can be called
1797 * with some irq-safe spinlocks held.
1799 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1801 int ret = -ENAMETOOLONG;
1804 if (!cgrp->parent) {
1805 if (strlcpy(buf, "/", buflen) >= buflen)
1806 return -ENAMETOOLONG;
1810 start = buf + buflen - 1;
1815 const char *name = cgroup_name(cgrp);
1819 if ((start -= len) < buf)
1821 memcpy(start, name, len);
1827 cgrp = cgrp->parent;
1828 } while (cgrp->parent);
1830 memmove(buf, start, buf + buflen - start);
1835 EXPORT_SYMBOL_GPL(cgroup_path);
1838 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1839 * @task: target task
1840 * @buf: the buffer to write the path into
1841 * @buflen: the length of the buffer
1843 * Determine @task's cgroup on the first (the one with the lowest non-zero
1844 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1845 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1846 * cgroup controller callbacks.
1848 * Returns 0 on success, fails with -%ENAMETOOLONG if @buflen is too short.
1850 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1852 struct cgroupfs_root *root;
1853 struct cgroup *cgrp;
1854 int hierarchy_id = 1, ret = 0;
1857 return -ENAMETOOLONG;
1859 mutex_lock(&cgroup_mutex);
1861 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1864 cgrp = task_cgroup_from_root(task, root);
1865 ret = cgroup_path(cgrp, buf, buflen);
1867 /* if no hierarchy exists, everyone is in "/" */
1868 memcpy(buf, "/", 2);
1871 mutex_unlock(&cgroup_mutex);
1874 EXPORT_SYMBOL_GPL(task_cgroup_path);
1877 * Control Group taskset
1879 struct task_and_cgroup {
1880 struct task_struct *task;
1881 struct cgroup *cgrp;
1882 struct css_set *cset;
1885 struct cgroup_taskset {
1886 struct task_and_cgroup single;
1887 struct flex_array *tc_array;
1890 struct cgroup *cur_cgrp;
1894 * cgroup_taskset_first - reset taskset and return the first task
1895 * @tset: taskset of interest
1897 * @tset iteration is initialized and the first task is returned.
1899 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1901 if (tset->tc_array) {
1903 return cgroup_taskset_next(tset);
1905 tset->cur_cgrp = tset->single.cgrp;
1906 return tset->single.task;
1909 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1912 * cgroup_taskset_next - iterate to the next task in taskset
1913 * @tset: taskset of interest
1915 * Return the next task in @tset. Iteration must have been initialized
1916 * with cgroup_taskset_first().
1918 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1920 struct task_and_cgroup *tc;
1922 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1925 tc = flex_array_get(tset->tc_array, tset->idx++);
1926 tset->cur_cgrp = tc->cgrp;
1929 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1932 * cgroup_taskset_cur_css - return the matching css for the current task
1933 * @tset: taskset of interest
1934 * @subsys_id: the ID of the target subsystem
1936 * Return the css for the current (last returned) task of @tset for
1937 * subsystem specified by @subsys_id. This function must be preceded by
1938 * either cgroup_taskset_first() or cgroup_taskset_next().
1940 struct cgroup_subsys_state *cgroup_taskset_cur_css(struct cgroup_taskset *tset,
1943 return cgroup_css(tset->cur_cgrp, subsys_id);
1945 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_css);
1948 * cgroup_taskset_size - return the number of tasks in taskset
1949 * @tset: taskset of interest
1951 int cgroup_taskset_size(struct cgroup_taskset *tset)
1953 return tset->tc_array ? tset->tc_array_len : 1;
1955 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1959 * cgroup_task_migrate - move a task from one cgroup to another.
1961 * Must be called with cgroup_mutex and threadgroup locked.
1963 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1964 struct task_struct *tsk,
1965 struct css_set *new_cset)
1967 struct css_set *old_cset;
1970 * We are synchronized through threadgroup_lock() against PF_EXITING
1971 * setting such that we can't race against cgroup_exit() changing the
1972 * css_set to init_css_set and dropping the old one.
1974 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1975 old_cset = task_css_set(tsk);
1978 rcu_assign_pointer(tsk->cgroups, new_cset);
1981 /* Update the css_set linked lists if we're using them */
1982 write_lock(&css_set_lock);
1983 if (!list_empty(&tsk->cg_list))
1984 list_move(&tsk->cg_list, &new_cset->tasks);
1985 write_unlock(&css_set_lock);
1988 * We just gained a reference on old_cset by taking it from the
1989 * task. As trading it for new_cset is protected by cgroup_mutex,
1990 * we're safe to drop it here; it will be freed under RCU.
1992 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1993 put_css_set(old_cset);
1997 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1998 * @cgrp: the cgroup to attach to
1999 * @tsk: the task or the leader of the threadgroup to be attached
2000 * @threadgroup: attach the whole threadgroup?
2002 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
2003 * task_lock of @tsk or each thread in the threadgroup individually in turn.
2005 static int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk,
2008 int retval, i, group_size;
2009 struct cgroup_subsys *ss, *failed_ss = NULL;
2010 struct cgroupfs_root *root = cgrp->root;
2011 /* threadgroup list cursor and array */
2012 struct task_struct *leader = tsk;
2013 struct task_and_cgroup *tc;
2014 struct flex_array *group;
2015 struct cgroup_taskset tset = { };
2018 * step 0: in order to do expensive, possibly blocking operations for
2019 * every thread, we cannot iterate the thread group list, since it needs
2020 * rcu or tasklist locked. instead, build an array of all threads in the
2021 * group - group_rwsem prevents new threads from appearing, and if
2022 * threads exit, this will just be an over-estimate.
2025 group_size = get_nr_threads(tsk);
2028 /* flex_array supports very large thread-groups better than kmalloc. */
2029 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
2032 /* pre-allocate to guarantee space while iterating in rcu read-side. */
2033 retval = flex_array_prealloc(group, 0, group_size, GFP_KERNEL);
2035 goto out_free_group_list;
2039 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2040 * already PF_EXITING could be freed from underneath us unless we
2041 * take an rcu_read_lock.
2045 struct task_and_cgroup ent;
2047 /* @tsk either already exited or can't exit until the end */
2048 if (tsk->flags & PF_EXITING)
2051 /* as per above, nr_threads may decrease, but not increase. */
2052 BUG_ON(i >= group_size);
2054 ent.cgrp = task_cgroup_from_root(tsk, root);
2055 /* nothing to do if this task is already in the cgroup */
2056 if (ent.cgrp == cgrp)
2059 * saying GFP_ATOMIC has no effect here because we did prealloc
2060 * earlier, but it's good form to communicate our expectations.
2062 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
2063 BUG_ON(retval != 0);
2068 } while_each_thread(leader, tsk);
2070 /* remember the number of threads in the array for later. */
2072 tset.tc_array = group;
2073 tset.tc_array_len = group_size;
2075 /* methods shouldn't be called if no task is actually migrating */
2078 goto out_free_group_list;
2081 * step 1: check that we can legitimately attach to the cgroup.
2083 for_each_root_subsys(root, ss) {
2084 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss->subsys_id);
2086 if (ss->can_attach) {
2087 retval = ss->can_attach(css, &tset);
2090 goto out_cancel_attach;
2096 * step 2: make sure css_sets exist for all threads to be migrated.
2097 * we use find_css_set, which allocates a new one if necessary.
2099 for (i = 0; i < group_size; i++) {
2100 struct css_set *old_cset;
2102 tc = flex_array_get(group, i);
2103 old_cset = task_css_set(tc->task);
2104 tc->cset = find_css_set(old_cset, cgrp);
2107 goto out_put_css_set_refs;
2112 * step 3: now that we're guaranteed success wrt the css_sets,
2113 * proceed to move all tasks to the new cgroup. There are no
2114 * failure cases after here, so this is the commit point.
2116 for (i = 0; i < group_size; i++) {
2117 tc = flex_array_get(group, i);
2118 cgroup_task_migrate(tc->cgrp, tc->task, tc->cset);
2120 /* nothing is sensitive to fork() after this point. */
2123 * step 4: do subsystem attach callbacks.
2125 for_each_root_subsys(root, ss) {
2126 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss->subsys_id);
2129 ss->attach(css, &tset);
2133 * step 5: success! and cleanup
2136 out_put_css_set_refs:
2138 for (i = 0; i < group_size; i++) {
2139 tc = flex_array_get(group, i);
2142 put_css_set(tc->cset);
2147 for_each_root_subsys(root, ss) {
2148 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss->subsys_id);
2150 if (ss == failed_ss)
2152 if (ss->cancel_attach)
2153 ss->cancel_attach(css, &tset);
2156 out_free_group_list:
2157 flex_array_free(group);
2162 * Find the task_struct of the task to attach by vpid and pass it along to the
2163 * function to attach either it or all tasks in its threadgroup. Will lock
2164 * cgroup_mutex and threadgroup; may take task_lock of task.
2166 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2168 struct task_struct *tsk;
2169 const struct cred *cred = current_cred(), *tcred;
2172 if (!cgroup_lock_live_group(cgrp))
2178 tsk = find_task_by_vpid(pid);
2182 goto out_unlock_cgroup;
2185 * even if we're attaching all tasks in the thread group, we
2186 * only need to check permissions on one of them.
2188 tcred = __task_cred(tsk);
2189 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2190 !uid_eq(cred->euid, tcred->uid) &&
2191 !uid_eq(cred->euid, tcred->suid)) {
2194 goto out_unlock_cgroup;
2200 tsk = tsk->group_leader;
2203 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2204 * trapped in a cpuset, or RT worker may be born in a cgroup
2205 * with no rt_runtime allocated. Just say no.
2207 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2210 goto out_unlock_cgroup;
2213 get_task_struct(tsk);
2216 threadgroup_lock(tsk);
2218 if (!thread_group_leader(tsk)) {
2220 * a race with de_thread from another thread's exec()
2221 * may strip us of our leadership, if this happens,
2222 * there is no choice but to throw this task away and
2223 * try again; this is
2224 * "double-double-toil-and-trouble-check locking".
2226 threadgroup_unlock(tsk);
2227 put_task_struct(tsk);
2228 goto retry_find_task;
2232 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2234 threadgroup_unlock(tsk);
2236 put_task_struct(tsk);
2238 mutex_unlock(&cgroup_mutex);
2243 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2244 * @from: attach to all cgroups of a given task
2245 * @tsk: the task to be attached
2247 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2249 struct cgroupfs_root *root;
2252 mutex_lock(&cgroup_mutex);
2253 for_each_active_root(root) {
2254 struct cgroup *from_cgrp = task_cgroup_from_root(from, root);
2256 retval = cgroup_attach_task(from_cgrp, tsk, false);
2260 mutex_unlock(&cgroup_mutex);
2264 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2266 static int cgroup_tasks_write(struct cgroup_subsys_state *css,
2267 struct cftype *cft, u64 pid)
2269 return attach_task_by_pid(css->cgroup, pid, false);
2272 static int cgroup_procs_write(struct cgroup_subsys_state *css,
2273 struct cftype *cft, u64 tgid)
2275 return attach_task_by_pid(css->cgroup, tgid, true);
2278 static int cgroup_release_agent_write(struct cgroup_subsys_state *css,
2279 struct cftype *cft, const char *buffer)
2281 BUILD_BUG_ON(sizeof(css->cgroup->root->release_agent_path) < PATH_MAX);
2282 if (strlen(buffer) >= PATH_MAX)
2284 if (!cgroup_lock_live_group(css->cgroup))
2286 mutex_lock(&cgroup_root_mutex);
2287 strcpy(css->cgroup->root->release_agent_path, buffer);
2288 mutex_unlock(&cgroup_root_mutex);
2289 mutex_unlock(&cgroup_mutex);
2293 static int cgroup_release_agent_show(struct cgroup_subsys_state *css,
2294 struct cftype *cft, struct seq_file *seq)
2296 struct cgroup *cgrp = css->cgroup;
2298 if (!cgroup_lock_live_group(cgrp))
2300 seq_puts(seq, cgrp->root->release_agent_path);
2301 seq_putc(seq, '\n');
2302 mutex_unlock(&cgroup_mutex);
2306 static int cgroup_sane_behavior_show(struct cgroup_subsys_state *css,
2307 struct cftype *cft, struct seq_file *seq)
2309 seq_printf(seq, "%d\n", cgroup_sane_behavior(css->cgroup));
2313 /* A buffer size big enough for numbers or short strings */
2314 #define CGROUP_LOCAL_BUFFER_SIZE 64
2316 static ssize_t cgroup_write_X64(struct cgroup_subsys_state *css,
2317 struct cftype *cft, struct file *file,
2318 const char __user *userbuf, size_t nbytes,
2319 loff_t *unused_ppos)
2321 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
2327 if (nbytes >= sizeof(buffer))
2329 if (copy_from_user(buffer, userbuf, nbytes))
2332 buffer[nbytes] = 0; /* nul-terminate */
2333 if (cft->write_u64) {
2334 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
2337 retval = cft->write_u64(css, cft, val);
2339 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
2342 retval = cft->write_s64(css, cft, val);
2349 static ssize_t cgroup_write_string(struct cgroup_subsys_state *css,
2350 struct cftype *cft, struct file *file,
2351 const char __user *userbuf, size_t nbytes,
2352 loff_t *unused_ppos)
2354 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
2356 size_t max_bytes = cft->max_write_len;
2357 char *buffer = local_buffer;
2360 max_bytes = sizeof(local_buffer) - 1;
2361 if (nbytes >= max_bytes)
2363 /* Allocate a dynamic buffer if we need one */
2364 if (nbytes >= sizeof(local_buffer)) {
2365 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2369 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2374 buffer[nbytes] = 0; /* nul-terminate */
2375 retval = cft->write_string(css, cft, strstrip(buffer));
2379 if (buffer != local_buffer)
2384 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2385 size_t nbytes, loff_t *ppos)
2387 struct cfent *cfe = __d_cfe(file->f_dentry);
2388 struct cftype *cft = __d_cft(file->f_dentry);
2389 struct cgroup_subsys_state *css = cfe->css;
2392 return cft->write(css, cft, file, buf, nbytes, ppos);
2393 if (cft->write_u64 || cft->write_s64)
2394 return cgroup_write_X64(css, cft, file, buf, nbytes, ppos);
2395 if (cft->write_string)
2396 return cgroup_write_string(css, cft, file, buf, nbytes, ppos);
2398 int ret = cft->trigger(css, (unsigned int)cft->private);
2399 return ret ? ret : nbytes;
2404 static ssize_t cgroup_read_u64(struct cgroup_subsys_state *css,
2405 struct cftype *cft, struct file *file,
2406 char __user *buf, size_t nbytes, loff_t *ppos)
2408 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2409 u64 val = cft->read_u64(css, cft);
2410 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2412 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2415 static ssize_t cgroup_read_s64(struct cgroup_subsys_state *css,
2416 struct cftype *cft, struct file *file,
2417 char __user *buf, size_t nbytes, loff_t *ppos)
2419 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2420 s64 val = cft->read_s64(css, cft);
2421 int len = sprintf(tmp, "%lld\n", (long long) val);
2423 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2426 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2427 size_t nbytes, loff_t *ppos)
2429 struct cfent *cfe = __d_cfe(file->f_dentry);
2430 struct cftype *cft = __d_cft(file->f_dentry);
2431 struct cgroup_subsys_state *css = cfe->css;
2434 return cft->read(css, cft, file, buf, nbytes, ppos);
2436 return cgroup_read_u64(css, cft, file, buf, nbytes, ppos);
2438 return cgroup_read_s64(css, cft, file, buf, nbytes, ppos);
2443 * seqfile ops/methods for returning structured data. Currently just
2444 * supports string->u64 maps, but can be extended in future.
2447 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2449 struct seq_file *sf = cb->state;
2450 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2453 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2455 struct cfent *cfe = m->private;
2456 struct cftype *cft = cfe->type;
2457 struct cgroup_subsys_state *css = cfe->css;
2459 if (cft->read_map) {
2460 struct cgroup_map_cb cb = {
2461 .fill = cgroup_map_add,
2464 return cft->read_map(css, cft, &cb);
2466 return cft->read_seq_string(css, cft, m);
2469 static const struct file_operations cgroup_seqfile_operations = {
2471 .write = cgroup_file_write,
2472 .llseek = seq_lseek,
2473 .release = single_release,
2476 static int cgroup_file_open(struct inode *inode, struct file *file)
2478 struct cfent *cfe = __d_cfe(file->f_dentry);
2479 struct cftype *cft = __d_cft(file->f_dentry);
2480 struct cgroup *cgrp = __d_cgrp(cfe->dentry->d_parent);
2481 struct cgroup_subsys_state *css;
2484 err = generic_file_open(inode, file);
2489 * If the file belongs to a subsystem, pin the css. Will be
2490 * unpinned either on open failure or release. This ensures that
2491 * @css stays alive for all file operations.
2495 css = cgroup_css(cgrp, cft->ss->subsys_id);
2496 if (!css_tryget(css))
2499 css = &cgrp->dummy_css;
2503 /* css should match @cfe->css, see cgroup_add_file() for details */
2504 if (!css || WARN_ON_ONCE(css != cfe->css))
2507 if (cft->read_map || cft->read_seq_string) {
2508 file->f_op = &cgroup_seqfile_operations;
2509 err = single_open(file, cgroup_seqfile_show, cfe);
2510 } else if (cft->open) {
2511 err = cft->open(inode, file);
2519 static int cgroup_file_release(struct inode *inode, struct file *file)
2521 struct cfent *cfe = __d_cfe(file->f_dentry);
2522 struct cftype *cft = __d_cft(file->f_dentry);
2523 struct cgroup_subsys_state *css = cfe->css;
2527 ret = cft->release(inode, file);
2534 * cgroup_rename - Only allow simple rename of directories in place.
2536 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2537 struct inode *new_dir, struct dentry *new_dentry)
2540 struct cgroup_name *name, *old_name;
2541 struct cgroup *cgrp;
2544 * It's convinient to use parent dir's i_mutex to protected
2547 lockdep_assert_held(&old_dir->i_mutex);
2549 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2551 if (new_dentry->d_inode)
2553 if (old_dir != new_dir)
2556 cgrp = __d_cgrp(old_dentry);
2559 * This isn't a proper migration and its usefulness is very
2560 * limited. Disallow if sane_behavior.
2562 if (cgroup_sane_behavior(cgrp))
2565 name = cgroup_alloc_name(new_dentry);
2569 ret = simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2575 old_name = rcu_dereference_protected(cgrp->name, true);
2576 rcu_assign_pointer(cgrp->name, name);
2578 kfree_rcu(old_name, rcu_head);
2582 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2584 if (S_ISDIR(dentry->d_inode->i_mode))
2585 return &__d_cgrp(dentry)->xattrs;
2587 return &__d_cfe(dentry)->xattrs;
2590 static inline int xattr_enabled(struct dentry *dentry)
2592 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2593 return root->flags & CGRP_ROOT_XATTR;
2596 static bool is_valid_xattr(const char *name)
2598 if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2599 !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2604 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2605 const void *val, size_t size, int flags)
2607 if (!xattr_enabled(dentry))
2609 if (!is_valid_xattr(name))
2611 return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2614 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2616 if (!xattr_enabled(dentry))
2618 if (!is_valid_xattr(name))
2620 return simple_xattr_remove(__d_xattrs(dentry), name);
2623 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2624 void *buf, size_t size)
2626 if (!xattr_enabled(dentry))
2628 if (!is_valid_xattr(name))
2630 return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2633 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2635 if (!xattr_enabled(dentry))
2637 return simple_xattr_list(__d_xattrs(dentry), buf, size);
2640 static const struct file_operations cgroup_file_operations = {
2641 .read = cgroup_file_read,
2642 .write = cgroup_file_write,
2643 .llseek = generic_file_llseek,
2644 .open = cgroup_file_open,
2645 .release = cgroup_file_release,
2648 static const struct inode_operations cgroup_file_inode_operations = {
2649 .setxattr = cgroup_setxattr,
2650 .getxattr = cgroup_getxattr,
2651 .listxattr = cgroup_listxattr,
2652 .removexattr = cgroup_removexattr,
2655 static const struct inode_operations cgroup_dir_inode_operations = {
2656 .lookup = cgroup_lookup,
2657 .mkdir = cgroup_mkdir,
2658 .rmdir = cgroup_rmdir,
2659 .rename = cgroup_rename,
2660 .setxattr = cgroup_setxattr,
2661 .getxattr = cgroup_getxattr,
2662 .listxattr = cgroup_listxattr,
2663 .removexattr = cgroup_removexattr,
2666 static struct dentry *cgroup_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
2668 if (dentry->d_name.len > NAME_MAX)
2669 return ERR_PTR(-ENAMETOOLONG);
2670 d_add(dentry, NULL);
2675 * Check if a file is a control file
2677 static inline struct cftype *__file_cft(struct file *file)
2679 if (file_inode(file)->i_fop != &cgroup_file_operations)
2680 return ERR_PTR(-EINVAL);
2681 return __d_cft(file->f_dentry);
2684 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2685 struct super_block *sb)
2687 struct inode *inode;
2691 if (dentry->d_inode)
2694 inode = cgroup_new_inode(mode, sb);
2698 if (S_ISDIR(mode)) {
2699 inode->i_op = &cgroup_dir_inode_operations;
2700 inode->i_fop = &simple_dir_operations;
2702 /* start off with i_nlink == 2 (for "." entry) */
2704 inc_nlink(dentry->d_parent->d_inode);
2707 * Control reaches here with cgroup_mutex held.
2708 * @inode->i_mutex should nest outside cgroup_mutex but we
2709 * want to populate it immediately without releasing
2710 * cgroup_mutex. As @inode isn't visible to anyone else
2711 * yet, trylock will always succeed without affecting
2714 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2715 } else if (S_ISREG(mode)) {
2717 inode->i_fop = &cgroup_file_operations;
2718 inode->i_op = &cgroup_file_inode_operations;
2720 d_instantiate(dentry, inode);
2721 dget(dentry); /* Extra count - pin the dentry in core */
2726 * cgroup_file_mode - deduce file mode of a control file
2727 * @cft: the control file in question
2729 * returns cft->mode if ->mode is not 0
2730 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2731 * returns S_IRUGO if it has only a read handler
2732 * returns S_IWUSR if it has only a write hander
2734 static umode_t cgroup_file_mode(const struct cftype *cft)
2741 if (cft->read || cft->read_u64 || cft->read_s64 ||
2742 cft->read_map || cft->read_seq_string)
2745 if (cft->write || cft->write_u64 || cft->write_s64 ||
2746 cft->write_string || cft->trigger)
2752 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2754 struct dentry *dir = cgrp->dentry;
2755 struct cgroup *parent = __d_cgrp(dir);
2756 struct dentry *dentry;
2760 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2762 if (cft->ss && !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
2763 strcpy(name, cft->ss->name);
2766 strcat(name, cft->name);
2768 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2770 cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2774 dentry = lookup_one_len(name, dir, strlen(name));
2775 if (IS_ERR(dentry)) {
2776 error = PTR_ERR(dentry);
2780 cfe->type = (void *)cft;
2781 cfe->dentry = dentry;
2782 dentry->d_fsdata = cfe;
2783 simple_xattrs_init(&cfe->xattrs);
2786 * cfe->css is used by read/write/close to determine the associated
2787 * css. file->private_data would be a better place but that's
2788 * already used by seqfile. Note that open will use the usual
2789 * cgroup_css() and css_tryget() to acquire the css and this
2790 * caching doesn't affect css lifetime management.
2793 cfe->css = cgroup_css(cgrp, cft->ss->subsys_id);
2795 cfe->css = &cgrp->dummy_css;
2797 mode = cgroup_file_mode(cft);
2798 error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2800 list_add_tail(&cfe->node, &parent->files);
2810 * cgroup_addrm_files - add or remove files to a cgroup directory
2811 * @cgrp: the target cgroup
2812 * @cfts: array of cftypes to be added
2813 * @is_add: whether to add or remove
2815 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2816 * For removals, this function never fails. If addition fails, this
2817 * function doesn't remove files already added. The caller is responsible
2820 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2826 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
2827 lockdep_assert_held(&cgroup_mutex);
2829 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2830 /* does cft->flags tell us to skip this file on @cgrp? */
2831 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2833 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2835 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2839 ret = cgroup_add_file(cgrp, cft);
2841 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2846 cgroup_rm_file(cgrp, cft);
2852 static void cgroup_cfts_prepare(void)
2853 __acquires(&cgroup_mutex)
2856 * Thanks to the entanglement with vfs inode locking, we can't walk
2857 * the existing cgroups under cgroup_mutex and create files.
2858 * Instead, we use css_for_each_descendant_pre() and drop RCU read
2859 * lock before calling cgroup_addrm_files().
2861 mutex_lock(&cgroup_mutex);
2864 static int cgroup_cfts_commit(struct cftype *cfts, bool is_add)
2865 __releases(&cgroup_mutex)
2868 struct cgroup_subsys *ss = cfts[0].ss;
2869 struct cgroup *root = &ss->root->top_cgroup;
2870 struct super_block *sb = ss->root->sb;
2871 struct dentry *prev = NULL;
2872 struct inode *inode;
2873 struct cgroup_subsys_state *css;
2877 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2878 if (!cfts || ss->root == &cgroup_dummy_root ||
2879 !atomic_inc_not_zero(&sb->s_active)) {
2880 mutex_unlock(&cgroup_mutex);
2885 * All cgroups which are created after we drop cgroup_mutex will
2886 * have the updated set of files, so we only need to update the
2887 * cgroups created before the current @cgroup_serial_nr_next.
2889 update_before = cgroup_serial_nr_next;
2891 mutex_unlock(&cgroup_mutex);
2893 /* add/rm files for all cgroups created before */
2895 css_for_each_descendant_pre(css, cgroup_css(root, ss->subsys_id)) {
2896 struct cgroup *cgrp = css->cgroup;
2898 if (cgroup_is_dead(cgrp))
2901 inode = cgrp->dentry->d_inode;
2906 prev = cgrp->dentry;
2908 mutex_lock(&inode->i_mutex);
2909 mutex_lock(&cgroup_mutex);
2910 if (cgrp->serial_nr < update_before && !cgroup_is_dead(cgrp))
2911 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2912 mutex_unlock(&cgroup_mutex);
2913 mutex_unlock(&inode->i_mutex);
2921 deactivate_super(sb);
2926 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2927 * @ss: target cgroup subsystem
2928 * @cfts: zero-length name terminated array of cftypes
2930 * Register @cfts to @ss. Files described by @cfts are created for all
2931 * existing cgroups to which @ss is attached and all future cgroups will
2932 * have them too. This function can be called anytime whether @ss is
2935 * Returns 0 on successful registration, -errno on failure. Note that this
2936 * function currently returns 0 as long as @cfts registration is successful
2937 * even if some file creation attempts on existing cgroups fail.
2939 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2941 struct cftype_set *set;
2945 set = kzalloc(sizeof(*set), GFP_KERNEL);
2949 for (cft = cfts; cft->name[0] != '\0'; cft++)
2952 cgroup_cfts_prepare();
2954 list_add_tail(&set->node, &ss->cftsets);
2955 ret = cgroup_cfts_commit(cfts, true);
2957 cgroup_rm_cftypes(cfts);
2960 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2963 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2964 * @cfts: zero-length name terminated array of cftypes
2966 * Unregister @cfts. Files described by @cfts are removed from all
2967 * existing cgroups and all future cgroups won't have them either. This
2968 * function can be called anytime whether @cfts' subsys is attached or not.
2970 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2973 int cgroup_rm_cftypes(struct cftype *cfts)
2975 struct cftype_set *set;
2977 if (!cfts || !cfts[0].ss)
2980 cgroup_cfts_prepare();
2982 list_for_each_entry(set, &cfts[0].ss->cftsets, node) {
2983 if (set->cfts == cfts) {
2984 list_del(&set->node);
2986 cgroup_cfts_commit(cfts, false);
2991 cgroup_cfts_commit(NULL, false);
2996 * cgroup_task_count - count the number of tasks in a cgroup.
2997 * @cgrp: the cgroup in question
2999 * Return the number of tasks in the cgroup.
3001 int cgroup_task_count(const struct cgroup *cgrp)
3004 struct cgrp_cset_link *link;
3006 read_lock(&css_set_lock);
3007 list_for_each_entry(link, &cgrp->cset_links, cset_link)
3008 count += atomic_read(&link->cset->refcount);
3009 read_unlock(&css_set_lock);
3014 * To reduce the fork() overhead for systems that are not actually using
3015 * their cgroups capability, we don't maintain the lists running through
3016 * each css_set to its tasks until we see the list actually used - in other
3017 * words after the first call to css_task_iter_start().
3019 static void cgroup_enable_task_cg_lists(void)
3021 struct task_struct *p, *g;
3022 write_lock(&css_set_lock);
3023 use_task_css_set_links = 1;
3025 * We need tasklist_lock because RCU is not safe against
3026 * while_each_thread(). Besides, a forking task that has passed
3027 * cgroup_post_fork() without seeing use_task_css_set_links = 1
3028 * is not guaranteed to have its child immediately visible in the
3029 * tasklist if we walk through it with RCU.
3031 read_lock(&tasklist_lock);
3032 do_each_thread(g, p) {
3035 * We should check if the process is exiting, otherwise
3036 * it will race with cgroup_exit() in that the list
3037 * entry won't be deleted though the process has exited.
3039 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
3040 list_add(&p->cg_list, &task_css_set(p)->tasks);
3042 } while_each_thread(g, p);
3043 read_unlock(&tasklist_lock);
3044 write_unlock(&css_set_lock);
3048 * css_next_child - find the next child of a given css
3049 * @pos_css: the current position (%NULL to initiate traversal)
3050 * @parent_css: css whose children to walk
3052 * This function returns the next child of @parent_css and should be called
3053 * under RCU read lock. The only requirement is that @parent_css and
3054 * @pos_css are accessible. The next sibling is guaranteed to be returned
3055 * regardless of their states.
3057 struct cgroup_subsys_state *
3058 css_next_child(struct cgroup_subsys_state *pos_css,
3059 struct cgroup_subsys_state *parent_css)
3061 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
3062 struct cgroup *cgrp = parent_css->cgroup;
3063 struct cgroup *next;
3065 WARN_ON_ONCE(!rcu_read_lock_held());
3068 * @pos could already have been removed. Once a cgroup is removed,
3069 * its ->sibling.next is no longer updated when its next sibling
3070 * changes. As CGRP_DEAD assertion is serialized and happens
3071 * before the cgroup is taken off the ->sibling list, if we see it
3072 * unasserted, it's guaranteed that the next sibling hasn't
3073 * finished its grace period even if it's already removed, and thus
3074 * safe to dereference from this RCU critical section. If
3075 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
3076 * to be visible as %true here.
3078 * If @pos is dead, its next pointer can't be dereferenced;
3079 * however, as each cgroup is given a monotonically increasing
3080 * unique serial number and always appended to the sibling list,
3081 * the next one can be found by walking the parent's children until
3082 * we see a cgroup with higher serial number than @pos's. While
3083 * this path can be slower, it's taken only when either the current
3084 * cgroup is removed or iteration and removal race.
3087 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
3088 } else if (likely(!cgroup_is_dead(pos))) {
3089 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3091 list_for_each_entry_rcu(next, &cgrp->children, sibling)
3092 if (next->serial_nr > pos->serial_nr)
3096 if (&next->sibling == &cgrp->children)
3100 return cgroup_css(next, parent_css->ss->subsys_id);
3102 return &next->dummy_css;
3104 EXPORT_SYMBOL_GPL(css_next_child);
3107 * css_next_descendant_pre - find the next descendant for pre-order walk
3108 * @pos: the current position (%NULL to initiate traversal)
3109 * @root: css whose descendants to walk
3111 * To be used by css_for_each_descendant_pre(). Find the next descendant
3112 * to visit for pre-order traversal of @root's descendants. @root is
3113 * included in the iteration and the first node to be visited.
3115 * While this function requires RCU read locking, it doesn't require the
3116 * whole traversal to be contained in a single RCU critical section. This
3117 * function will return the correct next descendant as long as both @pos
3118 * and @root are accessible and @pos is a descendant of @root.
3120 struct cgroup_subsys_state *
3121 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3122 struct cgroup_subsys_state *root)
3124 struct cgroup_subsys_state *next;
3126 WARN_ON_ONCE(!rcu_read_lock_held());
3128 /* if first iteration, visit @root */
3132 /* visit the first child if exists */
3133 next = css_next_child(NULL, pos);
3137 /* no child, visit my or the closest ancestor's next sibling */
3138 while (pos != root) {
3139 next = css_next_child(pos, css_parent(pos));
3142 pos = css_parent(pos);
3147 EXPORT_SYMBOL_GPL(css_next_descendant_pre);
3150 * css_rightmost_descendant - return the rightmost descendant of a css
3151 * @pos: css of interest
3153 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3154 * is returned. This can be used during pre-order traversal to skip
3157 * While this function requires RCU read locking, it doesn't require the
3158 * whole traversal to be contained in a single RCU critical section. This
3159 * function will return the correct rightmost descendant as long as @pos is
3162 struct cgroup_subsys_state *
3163 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3165 struct cgroup_subsys_state *last, *tmp;
3167 WARN_ON_ONCE(!rcu_read_lock_held());
3171 /* ->prev isn't RCU safe, walk ->next till the end */
3173 css_for_each_child(tmp, last)
3179 EXPORT_SYMBOL_GPL(css_rightmost_descendant);
3181 static struct cgroup_subsys_state *
3182 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3184 struct cgroup_subsys_state *last;
3188 pos = css_next_child(NULL, pos);
3195 * css_next_descendant_post - find the next descendant for post-order walk
3196 * @pos: the current position (%NULL to initiate traversal)
3197 * @root: css whose descendants to walk
3199 * To be used by css_for_each_descendant_post(). Find the next descendant
3200 * to visit for post-order traversal of @root's descendants. @root is
3201 * included in the iteration and the last node to be visited.
3203 * While this function requires RCU read locking, it doesn't require the
3204 * whole traversal to be contained in a single RCU critical section. This
3205 * function will return the correct next descendant as long as both @pos
3206 * and @cgroup are accessible and @pos is a descendant of @cgroup.
3208 struct cgroup_subsys_state *
3209 css_next_descendant_post(struct cgroup_subsys_state *pos,
3210 struct cgroup_subsys_state *root)
3212 struct cgroup_subsys_state *next;
3214 WARN_ON_ONCE(!rcu_read_lock_held());
3216 /* if first iteration, visit the leftmost descendant */
3218 next = css_leftmost_descendant(root);
3219 return next != root ? next : NULL;
3222 /* if we visited @root, we're done */
3226 /* if there's an unvisited sibling, visit its leftmost descendant */
3227 next = css_next_child(pos, css_parent(pos));
3229 return css_leftmost_descendant(next);
3231 /* no sibling left, visit parent */
3232 return css_parent(pos);
3234 EXPORT_SYMBOL_GPL(css_next_descendant_post);
3237 * css_advance_task_iter - advance a task itererator to the next css_set
3238 * @it: the iterator to advance
3240 * Advance @it to the next css_set to walk.
3242 static void css_advance_task_iter(struct css_task_iter *it)
3244 struct list_head *l = it->cset_link;
3245 struct cgrp_cset_link *link;
3246 struct css_set *cset;
3248 /* Advance to the next non-empty css_set */
3251 if (l == &it->origin_css->cgroup->cset_links) {
3252 it->cset_link = NULL;
3255 link = list_entry(l, struct cgrp_cset_link, cset_link);
3257 } while (list_empty(&cset->tasks));
3259 it->task = cset->tasks.next;
3263 * css_task_iter_start - initiate task iteration
3264 * @css: the css to walk tasks of
3265 * @it: the task iterator to use
3267 * Initiate iteration through the tasks of @css. The caller can call
3268 * css_task_iter_next() to walk through the tasks until the function
3269 * returns NULL. On completion of iteration, css_task_iter_end() must be
3272 * Note that this function acquires a lock which is released when the
3273 * iteration finishes. The caller can't sleep while iteration is in
3276 void css_task_iter_start(struct cgroup_subsys_state *css,
3277 struct css_task_iter *it)
3278 __acquires(css_set_lock)
3281 * The first time anyone tries to iterate across a css, we need to
3282 * enable the list linking each css_set to its tasks, and fix up
3283 * all existing tasks.
3285 if (!use_task_css_set_links)
3286 cgroup_enable_task_cg_lists();
3288 read_lock(&css_set_lock);
3290 it->origin_css = css;
3291 it->cset_link = &css->cgroup->cset_links;
3293 css_advance_task_iter(it);
3297 * css_task_iter_next - return the next task for the iterator
3298 * @it: the task iterator being iterated
3300 * The "next" function for task iteration. @it should have been
3301 * initialized via css_task_iter_start(). Returns NULL when the iteration
3304 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3306 struct task_struct *res;
3307 struct list_head *l = it->task;
3308 struct cgrp_cset_link *link;
3310 /* If the iterator cg is NULL, we have no tasks */
3313 res = list_entry(l, struct task_struct, cg_list);
3314 /* Advance iterator to find next entry */
3316 link = list_entry(it->cset_link, struct cgrp_cset_link, cset_link);
3317 if (l == &link->cset->tasks) {
3319 * We reached the end of this task list - move on to the
3320 * next cgrp_cset_link.
3322 css_advance_task_iter(it);
3330 * css_task_iter_end - finish task iteration
3331 * @it: the task iterator to finish
3333 * Finish task iteration started by css_task_iter_start().
3335 void css_task_iter_end(struct css_task_iter *it)
3336 __releases(css_set_lock)
3338 read_unlock(&css_set_lock);
3341 static inline int started_after_time(struct task_struct *t1,
3342 struct timespec *time,
3343 struct task_struct *t2)
3345 int start_diff = timespec_compare(&t1->start_time, time);
3346 if (start_diff > 0) {
3348 } else if (start_diff < 0) {
3352 * Arbitrarily, if two processes started at the same
3353 * time, we'll say that the lower pointer value
3354 * started first. Note that t2 may have exited by now
3355 * so this may not be a valid pointer any longer, but
3356 * that's fine - it still serves to distinguish
3357 * between two tasks started (effectively) simultaneously.
3364 * This function is a callback from heap_insert() and is used to order
3366 * In this case we order the heap in descending task start time.
3368 static inline int started_after(void *p1, void *p2)
3370 struct task_struct *t1 = p1;
3371 struct task_struct *t2 = p2;
3372 return started_after_time(t1, &t2->start_time, t2);
3376 * css_scan_tasks - iterate though all the tasks in a css
3377 * @css: the css to iterate tasks of
3378 * @test: optional test callback
3379 * @process: process callback
3380 * @data: data passed to @test and @process
3381 * @heap: optional pre-allocated heap used for task iteration
3383 * Iterate through all the tasks in @css, calling @test for each, and if it
3384 * returns %true, call @process for it also.
3386 * @test may be NULL, meaning always true (select all tasks), which
3387 * effectively duplicates css_task_iter_{start,next,end}() but does not
3388 * lock css_set_lock for the call to @process.
3390 * It is guaranteed that @process will act on every task that is a member
3391 * of @css for the duration of this call. This function may or may not
3392 * call @process for tasks that exit or move to a different css during the
3393 * call, or are forked or move into the css during the call.
3395 * Note that @test may be called with locks held, and may in some
3396 * situations be called multiple times for the same task, so it should be
3399 * If @heap is non-NULL, a heap has been pre-allocated and will be used for
3400 * heap operations (and its "gt" member will be overwritten), else a
3401 * temporary heap will be used (allocation of which may cause this function
3404 int css_scan_tasks(struct cgroup_subsys_state *css,
3405 bool (*test)(struct task_struct *, void *),
3406 void (*process)(struct task_struct *, void *),
3407 void *data, struct ptr_heap *heap)
3410 struct css_task_iter it;
3411 struct task_struct *p, *dropped;
3412 /* Never dereference latest_task, since it's not refcounted */
3413 struct task_struct *latest_task = NULL;
3414 struct ptr_heap tmp_heap;
3415 struct timespec latest_time = { 0, 0 };
3418 /* The caller supplied our heap and pre-allocated its memory */
3419 heap->gt = &started_after;
3421 /* We need to allocate our own heap memory */
3423 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3425 /* cannot allocate the heap */
3431 * Scan tasks in the css, using the @test callback to determine
3432 * which are of interest, and invoking @process callback on the
3433 * ones which need an update. Since we don't want to hold any
3434 * locks during the task updates, gather tasks to be processed in a
3435 * heap structure. The heap is sorted by descending task start
3436 * time. If the statically-sized heap fills up, we overflow tasks
3437 * that started later, and in future iterations only consider tasks
3438 * that started after the latest task in the previous pass. This
3439 * guarantees forward progress and that we don't miss any tasks.
3442 css_task_iter_start(css, &it);
3443 while ((p = css_task_iter_next(&it))) {
3445 * Only affect tasks that qualify per the caller's callback,
3446 * if he provided one
3448 if (test && !test(p, data))
3451 * Only process tasks that started after the last task
3454 if (!started_after_time(p, &latest_time, latest_task))
3456 dropped = heap_insert(heap, p);
3457 if (dropped == NULL) {
3459 * The new task was inserted; the heap wasn't
3463 } else if (dropped != p) {
3465 * The new task was inserted, and pushed out a
3469 put_task_struct(dropped);
3472 * Else the new task was newer than anything already in
3473 * the heap and wasn't inserted
3476 css_task_iter_end(&it);
3479 for (i = 0; i < heap->size; i++) {
3480 struct task_struct *q = heap->ptrs[i];
3482 latest_time = q->start_time;
3485 /* Process the task per the caller's callback */
3490 * If we had to process any tasks at all, scan again
3491 * in case some of them were in the middle of forking
3492 * children that didn't get processed.
3493 * Not the most efficient way to do it, but it avoids
3494 * having to take callback_mutex in the fork path
3498 if (heap == &tmp_heap)
3499 heap_free(&tmp_heap);
3503 static void cgroup_transfer_one_task(struct task_struct *task, void *data)
3505 struct cgroup *new_cgroup = data;
3507 mutex_lock(&cgroup_mutex);
3508 cgroup_attach_task(new_cgroup, task, false);
3509 mutex_unlock(&cgroup_mutex);
3513 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3514 * @to: cgroup to which the tasks will be moved
3515 * @from: cgroup in which the tasks currently reside
3517 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3519 return css_scan_tasks(&from->dummy_css, NULL, cgroup_transfer_one_task,
3524 * Stuff for reading the 'tasks'/'procs' files.
3526 * Reading this file can return large amounts of data if a cgroup has
3527 * *lots* of attached tasks. So it may need several calls to read(),
3528 * but we cannot guarantee that the information we produce is correct
3529 * unless we produce it entirely atomically.
3533 /* which pidlist file are we talking about? */
3534 enum cgroup_filetype {
3540 * A pidlist is a list of pids that virtually represents the contents of one
3541 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3542 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3545 struct cgroup_pidlist {
3547 * used to find which pidlist is wanted. doesn't change as long as
3548 * this particular list stays in the list.
3550 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3553 /* how many elements the above list has */
3555 /* how many files are using the current array */
3557 /* each of these stored in a list by its cgroup */
3558 struct list_head links;
3559 /* pointer to the cgroup we belong to, for list removal purposes */
3560 struct cgroup *owner;
3561 /* protects the other fields */
3562 struct rw_semaphore rwsem;
3566 * The following two functions "fix" the issue where there are more pids
3567 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3568 * TODO: replace with a kernel-wide solution to this problem
3570 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3571 static void *pidlist_allocate(int count)
3573 if (PIDLIST_TOO_LARGE(count))
3574 return vmalloc(count * sizeof(pid_t));
3576 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3578 static void pidlist_free(void *p)
3580 if (is_vmalloc_addr(p))
3587 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3588 * Returns the number of unique elements.
3590 static int pidlist_uniq(pid_t *list, int length)
3595 * we presume the 0th element is unique, so i starts at 1. trivial
3596 * edge cases first; no work needs to be done for either
3598 if (length == 0 || length == 1)
3600 /* src and dest walk down the list; dest counts unique elements */
3601 for (src = 1; src < length; src++) {
3602 /* find next unique element */
3603 while (list[src] == list[src-1]) {
3608 /* dest always points to where the next unique element goes */
3609 list[dest] = list[src];
3616 static int cmppid(const void *a, const void *b)
3618 return *(pid_t *)a - *(pid_t *)b;
3622 * find the appropriate pidlist for our purpose (given procs vs tasks)
3623 * returns with the lock on that pidlist already held, and takes care
3624 * of the use count, or returns NULL with no locks held if we're out of
3627 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3628 enum cgroup_filetype type)
3630 struct cgroup_pidlist *l;
3631 /* don't need task_nsproxy() if we're looking at ourself */
3632 struct pid_namespace *ns = task_active_pid_ns(current);
3635 * We can't drop the pidlist_mutex before taking the l->rwsem in case
3636 * the last ref-holder is trying to remove l from the list at the same
3637 * time. Holding the pidlist_mutex precludes somebody taking whichever
3638 * list we find out from under us - compare release_pid_array().
3640 mutex_lock(&cgrp->pidlist_mutex);
3641 list_for_each_entry(l, &cgrp->pidlists, links) {
3642 if (l->key.type == type && l->key.ns == ns) {
3643 /* make sure l doesn't vanish out from under us */
3644 down_write(&l->rwsem);
3645 mutex_unlock(&cgrp->pidlist_mutex);
3649 /* entry not found; create a new one */
3650 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3652 mutex_unlock(&cgrp->pidlist_mutex);
3655 init_rwsem(&l->rwsem);
3656 down_write(&l->rwsem);
3658 l->key.ns = get_pid_ns(ns);
3660 list_add(&l->links, &cgrp->pidlists);
3661 mutex_unlock(&cgrp->pidlist_mutex);
3666 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3668 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3669 struct cgroup_pidlist **lp)
3673 int pid, n = 0; /* used for populating the array */
3674 struct css_task_iter it;
3675 struct task_struct *tsk;
3676 struct cgroup_pidlist *l;
3679 * If cgroup gets more users after we read count, we won't have
3680 * enough space - tough. This race is indistinguishable to the
3681 * caller from the case that the additional cgroup users didn't
3682 * show up until sometime later on.
3684 length = cgroup_task_count(cgrp);
3685 array = pidlist_allocate(length);
3688 /* now, populate the array */
3689 css_task_iter_start(&cgrp->dummy_css, &it);
3690 while ((tsk = css_task_iter_next(&it))) {
3691 if (unlikely(n == length))
3693 /* get tgid or pid for procs or tasks file respectively */
3694 if (type == CGROUP_FILE_PROCS)
3695 pid = task_tgid_vnr(tsk);
3697 pid = task_pid_vnr(tsk);
3698 if (pid > 0) /* make sure to only use valid results */
3701 css_task_iter_end(&it);
3703 /* now sort & (if procs) strip out duplicates */
3704 sort(array, length, sizeof(pid_t), cmppid, NULL);
3705 if (type == CGROUP_FILE_PROCS)
3706 length = pidlist_uniq(array, length);
3707 l = cgroup_pidlist_find(cgrp, type);
3709 pidlist_free(array);
3712 /* store array, freeing old if necessary - lock already held */
3713 pidlist_free(l->list);
3717 up_write(&l->rwsem);
3723 * cgroupstats_build - build and fill cgroupstats
3724 * @stats: cgroupstats to fill information into
3725 * @dentry: A dentry entry belonging to the cgroup for which stats have
3728 * Build and fill cgroupstats so that taskstats can export it to user
3731 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3734 struct cgroup *cgrp;
3735 struct css_task_iter it;
3736 struct task_struct *tsk;
3739 * Validate dentry by checking the superblock operations,
3740 * and make sure it's a directory.
3742 if (dentry->d_sb->s_op != &cgroup_ops ||
3743 !S_ISDIR(dentry->d_inode->i_mode))
3747 cgrp = dentry->d_fsdata;
3749 css_task_iter_start(&cgrp->dummy_css, &it);
3750 while ((tsk = css_task_iter_next(&it))) {
3751 switch (tsk->state) {
3753 stats->nr_running++;
3755 case TASK_INTERRUPTIBLE:
3756 stats->nr_sleeping++;
3758 case TASK_UNINTERRUPTIBLE:
3759 stats->nr_uninterruptible++;
3762 stats->nr_stopped++;
3765 if (delayacct_is_task_waiting_on_io(tsk))
3766 stats->nr_io_wait++;
3770 css_task_iter_end(&it);
3778 * seq_file methods for the tasks/procs files. The seq_file position is the
3779 * next pid to display; the seq_file iterator is a pointer to the pid
3780 * in the cgroup->l->list array.
3783 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3786 * Initially we receive a position value that corresponds to
3787 * one more than the last pid shown (or 0 on the first call or
3788 * after a seek to the start). Use a binary-search to find the
3789 * next pid to display, if any
3791 struct cgroup_pidlist *l = s->private;
3792 int index = 0, pid = *pos;
3795 down_read(&l->rwsem);
3797 int end = l->length;
3799 while (index < end) {
3800 int mid = (index + end) / 2;
3801 if (l->list[mid] == pid) {
3804 } else if (l->list[mid] <= pid)
3810 /* If we're off the end of the array, we're done */
3811 if (index >= l->length)
3813 /* Update the abstract position to be the actual pid that we found */
3814 iter = l->list + index;
3819 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3821 struct cgroup_pidlist *l = s->private;
3825 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3827 struct cgroup_pidlist *l = s->private;
3829 pid_t *end = l->list + l->length;
3831 * Advance to the next pid in the array. If this goes off the
3843 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3845 return seq_printf(s, "%d\n", *(int *)v);
3849 * seq_operations functions for iterating on pidlists through seq_file -
3850 * independent of whether it's tasks or procs
3852 static const struct seq_operations cgroup_pidlist_seq_operations = {
3853 .start = cgroup_pidlist_start,
3854 .stop = cgroup_pidlist_stop,
3855 .next = cgroup_pidlist_next,
3856 .show = cgroup_pidlist_show,
3859 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
3862 * the case where we're the last user of this particular pidlist will
3863 * have us remove it from the cgroup's list, which entails taking the
3864 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3865 * pidlist_mutex, we have to take pidlist_mutex first.
3867 mutex_lock(&l->owner->pidlist_mutex);
3868 down_write(&l->rwsem);
3869 BUG_ON(!l->use_count);
3870 if (!--l->use_count) {
3871 /* we're the last user if refcount is 0; remove and free */
3872 list_del(&l->links);
3873 mutex_unlock(&l->owner->pidlist_mutex);
3874 pidlist_free(l->list);
3875 put_pid_ns(l->key.ns);
3876 up_write(&l->rwsem);
3880 mutex_unlock(&l->owner->pidlist_mutex);
3881 up_write(&l->rwsem);
3884 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
3886 struct cgroup_pidlist *l;
3887 if (!(file->f_mode & FMODE_READ))
3890 * the seq_file will only be initialized if the file was opened for
3891 * reading; hence we check if it's not null only in that case.
3893 l = ((struct seq_file *)file->private_data)->private;
3894 cgroup_release_pid_array(l);
3895 return seq_release(inode, file);
3898 static const struct file_operations cgroup_pidlist_operations = {
3900 .llseek = seq_lseek,
3901 .write = cgroup_file_write,
3902 .release = cgroup_pidlist_release,
3906 * The following functions handle opens on a file that displays a pidlist
3907 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3910 /* helper function for the two below it */
3911 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
3913 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
3914 struct cgroup_pidlist *l;
3917 /* Nothing to do for write-only files */
3918 if (!(file->f_mode & FMODE_READ))
3921 /* have the array populated */
3922 retval = pidlist_array_load(cgrp, type, &l);
3925 /* configure file information */
3926 file->f_op = &cgroup_pidlist_operations;
3928 retval = seq_open(file, &cgroup_pidlist_seq_operations);
3930 cgroup_release_pid_array(l);
3933 ((struct seq_file *)file->private_data)->private = l;
3936 static int cgroup_tasks_open(struct inode *unused, struct file *file)
3938 return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
3940 static int cgroup_procs_open(struct inode *unused, struct file *file)
3942 return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
3945 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3948 return notify_on_release(css->cgroup);
3951 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3952 struct cftype *cft, u64 val)
3954 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3956 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3958 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3963 * When dput() is called asynchronously, if umount has been done and
3964 * then deactivate_super() in cgroup_free_fn() kills the superblock,
3965 * there's a small window that vfs will see the root dentry with non-zero
3966 * refcnt and trigger BUG().
3968 * That's why we hold a reference before dput() and drop it right after.
3970 static void cgroup_dput(struct cgroup *cgrp)
3972 struct super_block *sb = cgrp->root->sb;
3974 atomic_inc(&sb->s_active);
3976 deactivate_super(sb);
3980 * Unregister event and free resources.
3982 * Gets called from workqueue.
3984 static void cgroup_event_remove(struct work_struct *work)
3986 struct cgroup_event *event = container_of(work, struct cgroup_event,
3988 struct cgroup_subsys_state *css = event->css;
3989 struct cgroup *cgrp = css->cgroup;
3991 remove_wait_queue(event->wqh, &event->wait);
3993 event->cft->unregister_event(css, event->cft, event->eventfd);
3995 /* Notify userspace the event is going away. */
3996 eventfd_signal(event->eventfd, 1);
3998 eventfd_ctx_put(event->eventfd);
4004 * Gets called on POLLHUP on eventfd when user closes it.
4006 * Called with wqh->lock held and interrupts disabled.
4008 static int cgroup_event_wake(wait_queue_t *wait, unsigned mode,
4009 int sync, void *key)
4011 struct cgroup_event *event = container_of(wait,
4012 struct cgroup_event, wait);
4013 struct cgroup *cgrp = event->css->cgroup;
4014 unsigned long flags = (unsigned long)key;
4016 if (flags & POLLHUP) {
4018 * If the event has been detached at cgroup removal, we
4019 * can simply return knowing the other side will cleanup
4022 * We can't race against event freeing since the other
4023 * side will require wqh->lock via remove_wait_queue(),
4026 spin_lock(&cgrp->event_list_lock);
4027 if (!list_empty(&event->list)) {
4028 list_del_init(&event->list);
4030 * We are in atomic context, but cgroup_event_remove()
4031 * may sleep, so we have to call it in workqueue.
4033 schedule_work(&event->remove);
4035 spin_unlock(&cgrp->event_list_lock);
4041 static void cgroup_event_ptable_queue_proc(struct file *file,
4042 wait_queue_head_t *wqh, poll_table *pt)
4044 struct cgroup_event *event = container_of(pt,
4045 struct cgroup_event, pt);
4048 add_wait_queue(wqh, &event->wait);
4052 * Parse input and register new cgroup event handler.
4054 * Input must be in format '<event_fd> <control_fd> <args>'.
4055 * Interpretation of args is defined by control file implementation.
4057 static int cgroup_write_event_control(struct cgroup_subsys_state *css,
4058 struct cftype *cft, const char *buffer)
4060 struct cgroup *cgrp = css->cgroup;
4061 struct cgroup_event *event;
4062 struct cgroup *cgrp_cfile;
4063 unsigned int efd, cfd;
4069 efd = simple_strtoul(buffer, &endp, 10);
4074 cfd = simple_strtoul(buffer, &endp, 10);
4075 if ((*endp != ' ') && (*endp != '\0'))
4079 event = kzalloc(sizeof(*event), GFP_KERNEL);
4083 INIT_LIST_HEAD(&event->list);
4084 init_poll_funcptr(&event->pt, cgroup_event_ptable_queue_proc);
4085 init_waitqueue_func_entry(&event->wait, cgroup_event_wake);
4086 INIT_WORK(&event->remove, cgroup_event_remove);
4088 efile = eventfd_fget(efd);
4089 if (IS_ERR(efile)) {
4090 ret = PTR_ERR(efile);
4094 event->eventfd = eventfd_ctx_fileget(efile);
4095 if (IS_ERR(event->eventfd)) {
4096 ret = PTR_ERR(event->eventfd);
4103 goto out_put_eventfd;
4106 /* the process need read permission on control file */
4107 /* AV: shouldn't we check that it's been opened for read instead? */
4108 ret = inode_permission(file_inode(cfile), MAY_READ);
4112 event->cft = __file_cft(cfile);
4113 if (IS_ERR(event->cft)) {
4114 ret = PTR_ERR(event->cft);
4119 * The file to be monitored must be in the same cgroup as
4120 * cgroup.event_control is.
4122 cgrp_cfile = __d_cgrp(cfile->f_dentry->d_parent);
4123 if (cgrp_cfile != cgrp) {
4128 if (!event->cft->register_event || !event->cft->unregister_event) {
4133 ret = event->cft->register_event(css, event->cft,
4134 event->eventfd, buffer);
4138 efile->f_op->poll(efile, &event->pt);
4141 * Events should be removed after rmdir of cgroup directory, but before
4142 * destroying subsystem state objects. Let's take reference to cgroup
4143 * directory dentry to do that.
4147 spin_lock(&cgrp->event_list_lock);
4148 list_add(&event->list, &cgrp->event_list);
4149 spin_unlock(&cgrp->event_list_lock);
4159 eventfd_ctx_put(event->eventfd);
4168 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
4171 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4174 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
4175 struct cftype *cft, u64 val)
4178 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4180 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4184 static struct cftype cgroup_base_files[] = {
4186 .name = "cgroup.procs",
4187 .open = cgroup_procs_open,
4188 .write_u64 = cgroup_procs_write,
4189 .release = cgroup_pidlist_release,
4190 .mode = S_IRUGO | S_IWUSR,
4193 .name = "cgroup.event_control",
4194 .write_string = cgroup_write_event_control,
4198 .name = "cgroup.clone_children",
4199 .flags = CFTYPE_INSANE,
4200 .read_u64 = cgroup_clone_children_read,
4201 .write_u64 = cgroup_clone_children_write,
4204 .name = "cgroup.sane_behavior",
4205 .flags = CFTYPE_ONLY_ON_ROOT,
4206 .read_seq_string = cgroup_sane_behavior_show,
4210 * Historical crazy stuff. These don't have "cgroup." prefix and
4211 * don't exist if sane_behavior. If you're depending on these, be
4212 * prepared to be burned.
4216 .flags = CFTYPE_INSANE, /* use "procs" instead */
4217 .open = cgroup_tasks_open,
4218 .write_u64 = cgroup_tasks_write,
4219 .release = cgroup_pidlist_release,
4220 .mode = S_IRUGO | S_IWUSR,
4223 .name = "notify_on_release",
4224 .flags = CFTYPE_INSANE,
4225 .read_u64 = cgroup_read_notify_on_release,
4226 .write_u64 = cgroup_write_notify_on_release,
4229 .name = "release_agent",
4230 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
4231 .read_seq_string = cgroup_release_agent_show,
4232 .write_string = cgroup_release_agent_write,
4233 .max_write_len = PATH_MAX,
4239 * cgroup_populate_dir - create subsys files in a cgroup directory
4240 * @cgrp: target cgroup
4241 * @subsys_mask: mask of the subsystem ids whose files should be added
4243 * On failure, no file is added.
4245 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
4247 struct cgroup_subsys *ss;
4250 /* process cftsets of each subsystem */
4251 for_each_subsys(ss, i) {
4252 struct cftype_set *set;
4254 if (!test_bit(i, &subsys_mask))
4257 list_for_each_entry(set, &ss->cftsets, node) {
4258 ret = cgroup_addrm_files(cgrp, set->cfts, true);
4264 /* This cgroup is ready now */
4265 for_each_root_subsys(cgrp->root, ss) {
4266 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss->subsys_id);
4267 struct css_id *id = rcu_dereference_protected(css->id, true);
4270 * Update id->css pointer and make this css visible from
4271 * CSS ID functions. This pointer will be dereferened
4272 * from RCU-read-side without locks.
4275 rcu_assign_pointer(id->css, css);
4280 cgroup_clear_dir(cgrp, subsys_mask);
4284 static void css_free_work_fn(struct work_struct *work)
4286 struct cgroup_subsys_state *css =
4287 container_of(work, struct cgroup_subsys_state, destroy_work);
4290 css_put(css->parent);
4292 cgroup_dput(css->cgroup);
4295 static void css_release(struct percpu_ref *ref)
4297 struct cgroup_subsys_state *css =
4298 container_of(ref, struct cgroup_subsys_state, refcnt);
4301 * css holds an extra ref to @cgrp->dentry which is put on the last
4302 * css_put(). dput() requires process context, which css_put() may
4303 * be called without. @css->destroy_work will be used to invoke
4304 * dput() asynchronously from css_put().
4306 INIT_WORK(&css->destroy_work, css_free_work_fn);
4307 schedule_work(&css->destroy_work);
4310 static void init_css(struct cgroup_subsys_state *css, struct cgroup_subsys *ss,
4311 struct cgroup *cgrp)
4319 css->parent = cgroup_css(cgrp->parent, ss->subsys_id);
4321 css->flags |= CSS_ROOT;
4323 BUG_ON(cgroup_css(cgrp, ss->subsys_id));
4326 /* invoke ->css_online() on a new CSS and mark it online if successful */
4327 static int online_css(struct cgroup_subsys_state *css)
4329 struct cgroup_subsys *ss = css->ss;
4332 lockdep_assert_held(&cgroup_mutex);
4335 ret = ss->css_online(css);
4337 css->flags |= CSS_ONLINE;
4338 css->cgroup->nr_css++;
4339 rcu_assign_pointer(css->cgroup->subsys[ss->subsys_id], css);
4344 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4345 static void offline_css(struct cgroup_subsys_state *css)
4347 struct cgroup_subsys *ss = css->ss;
4349 lockdep_assert_held(&cgroup_mutex);
4351 if (!(css->flags & CSS_ONLINE))
4354 if (ss->css_offline)
4355 ss->css_offline(css);
4357 css->flags &= ~CSS_ONLINE;
4358 css->cgroup->nr_css--;
4362 * cgroup_create - create a cgroup
4363 * @parent: cgroup that will be parent of the new cgroup
4364 * @dentry: dentry of the new cgroup
4365 * @mode: mode to set on new inode
4367 * Must be called with the mutex on the parent inode held
4369 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4372 struct cgroup_subsys_state *css_ar[CGROUP_SUBSYS_COUNT] = { };
4373 struct cgroup *cgrp;
4374 struct cgroup_name *name;
4375 struct cgroupfs_root *root = parent->root;
4377 struct cgroup_subsys *ss;
4378 struct super_block *sb = root->sb;
4380 /* allocate the cgroup and its ID, 0 is reserved for the root */
4381 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4385 name = cgroup_alloc_name(dentry);
4388 rcu_assign_pointer(cgrp->name, name);
4391 * Temporarily set the pointer to NULL, so idr_find() won't return
4392 * a half-baked cgroup.
4394 cgrp->id = idr_alloc(&root->cgroup_idr, NULL, 1, 0, GFP_KERNEL);
4399 * Only live parents can have children. Note that the liveliness
4400 * check isn't strictly necessary because cgroup_mkdir() and
4401 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4402 * anyway so that locking is contained inside cgroup proper and we
4403 * don't get nasty surprises if we ever grow another caller.
4405 if (!cgroup_lock_live_group(parent)) {
4410 /* Grab a reference on the superblock so the hierarchy doesn't
4411 * get deleted on unmount if there are child cgroups. This
4412 * can be done outside cgroup_mutex, since the sb can't
4413 * disappear while someone has an open control file on the
4415 atomic_inc(&sb->s_active);
4417 init_cgroup_housekeeping(cgrp);
4419 dentry->d_fsdata = cgrp;
4420 cgrp->dentry = dentry;
4422 cgrp->parent = parent;
4423 cgrp->dummy_css.parent = &parent->dummy_css;
4424 cgrp->root = parent->root;
4426 if (notify_on_release(parent))
4427 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4429 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4430 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4432 for_each_root_subsys(root, ss) {
4433 struct cgroup_subsys_state *css;
4435 css = ss->css_alloc(cgroup_css(parent, ss->subsys_id));
4440 css_ar[ss->subsys_id] = css;
4442 err = percpu_ref_init(&css->refcnt, css_release);
4446 init_css(css, ss, cgrp);
4449 err = alloc_css_id(css);
4456 * Create directory. cgroup_create_file() returns with the new
4457 * directory locked on success so that it can be populated without
4458 * dropping cgroup_mutex.
4460 err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4463 lockdep_assert_held(&dentry->d_inode->i_mutex);
4465 cgrp->serial_nr = cgroup_serial_nr_next++;
4467 /* allocation complete, commit to creation */
4468 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4469 root->number_of_cgroups++;
4471 /* each css holds a ref to the cgroup's dentry and the parent css */
4472 for_each_root_subsys(root, ss) {
4473 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4476 percpu_ref_get(&css->parent->refcnt);
4479 /* hold a ref to the parent's dentry */
4480 dget(parent->dentry);
4482 /* creation succeeded, notify subsystems */
4483 for_each_root_subsys(root, ss) {
4484 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4486 err = online_css(css);
4490 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4492 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",
4493 current->comm, current->pid, ss->name);
4494 if (!strcmp(ss->name, "memory"))
4495 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4496 ss->warned_broken_hierarchy = true;
4500 idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4502 err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
4506 err = cgroup_populate_dir(cgrp, root->subsys_mask);
4510 mutex_unlock(&cgroup_mutex);
4511 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4516 for_each_root_subsys(root, ss) {
4517 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4520 percpu_ref_cancel_init(&css->refcnt);
4524 mutex_unlock(&cgroup_mutex);
4525 /* Release the reference count that we took on the superblock */
4526 deactivate_super(sb);
4528 idr_remove(&root->cgroup_idr, cgrp->id);
4530 kfree(rcu_dereference_raw(cgrp->name));
4536 cgroup_destroy_locked(cgrp);
4537 mutex_unlock(&cgroup_mutex);
4538 mutex_unlock(&dentry->d_inode->i_mutex);
4542 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4544 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4546 /* the vfs holds inode->i_mutex already */
4547 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4551 * This is called when the refcnt of a css is confirmed to be killed.
4552 * css_tryget() is now guaranteed to fail.
4554 static void css_killed_work_fn(struct work_struct *work)
4556 struct cgroup_subsys_state *css =
4557 container_of(work, struct cgroup_subsys_state, destroy_work);
4558 struct cgroup *cgrp = css->cgroup;
4560 mutex_lock(&cgroup_mutex);
4563 * css_tryget() is guaranteed to fail now. Tell subsystems to
4564 * initate destruction.
4569 * If @cgrp is marked dead, it's waiting for refs of all css's to
4570 * be disabled before proceeding to the second phase of cgroup
4571 * destruction. If we are the last one, kick it off.
4573 if (!cgrp->nr_css && cgroup_is_dead(cgrp))
4574 cgroup_destroy_css_killed(cgrp);
4576 mutex_unlock(&cgroup_mutex);
4579 * Put the css refs from kill_css(). Each css holds an extra
4580 * reference to the cgroup's dentry and cgroup removal proceeds
4581 * regardless of css refs. On the last put of each css, whenever
4582 * that may be, the extra dentry ref is put so that dentry
4583 * destruction happens only after all css's are released.
4588 /* css kill confirmation processing requires process context, bounce */
4589 static void css_killed_ref_fn(struct percpu_ref *ref)
4591 struct cgroup_subsys_state *css =
4592 container_of(ref, struct cgroup_subsys_state, refcnt);
4594 INIT_WORK(&css->destroy_work, css_killed_work_fn);
4595 schedule_work(&css->destroy_work);
4599 * cgroup_destroy_locked - the first stage of cgroup destruction
4600 * @cgrp: cgroup to be destroyed
4602 * css's make use of percpu refcnts whose killing latency shouldn't be
4603 * exposed to userland and are RCU protected. Also, cgroup core needs to
4604 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
4605 * invoked. To satisfy all the requirements, destruction is implemented in
4606 * the following two steps.
4608 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4609 * userland visible parts and start killing the percpu refcnts of
4610 * css's. Set up so that the next stage will be kicked off once all
4611 * the percpu refcnts are confirmed to be killed.
4613 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4614 * rest of destruction. Once all cgroup references are gone, the
4615 * cgroup is RCU-freed.
4617 * This function implements s1. After this step, @cgrp is gone as far as
4618 * the userland is concerned and a new cgroup with the same name may be
4619 * created. As cgroup doesn't care about the names internally, this
4620 * doesn't cause any problem.
4622 static int cgroup_destroy_locked(struct cgroup *cgrp)
4623 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4625 struct dentry *d = cgrp->dentry;
4626 struct cgroup_event *event, *tmp;
4627 struct cgroup_subsys *ss;
4630 lockdep_assert_held(&d->d_inode->i_mutex);
4631 lockdep_assert_held(&cgroup_mutex);
4634 * css_set_lock synchronizes access to ->cset_links and prevents
4635 * @cgrp from being removed while __put_css_set() is in progress.
4637 read_lock(&css_set_lock);
4638 empty = list_empty(&cgrp->cset_links) && list_empty(&cgrp->children);
4639 read_unlock(&css_set_lock);
4644 * Block new css_tryget() by killing css refcnts. cgroup core
4645 * guarantees that, by the time ->css_offline() is invoked, no new
4646 * css reference will be given out via css_tryget(). We can't
4647 * simply call percpu_ref_kill() and proceed to offlining css's
4648 * because percpu_ref_kill() doesn't guarantee that the ref is seen
4649 * as killed on all CPUs on return.
4651 * Use percpu_ref_kill_and_confirm() to get notifications as each
4652 * css is confirmed to be seen as killed on all CPUs.
4653 * cgroup_destroy_css_killed() will be invoked to perform the rest
4654 * of destruction once the percpu refs of all css's are confirmed
4657 for_each_root_subsys(cgrp->root, ss) {
4658 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss->subsys_id);
4661 * Killing would put the base ref, but we need to keep it
4662 * alive until after ->css_offline.
4664 percpu_ref_get(&css->refcnt);
4666 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4670 * Mark @cgrp dead. This prevents further task migration and child
4671 * creation by disabling cgroup_lock_live_group(). Note that
4672 * CGRP_DEAD assertion is depended upon by css_next_child() to
4673 * resume iteration after dropping RCU read lock. See
4674 * css_next_child() for details.
4676 set_bit(CGRP_DEAD, &cgrp->flags);
4678 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4679 raw_spin_lock(&release_list_lock);
4680 if (!list_empty(&cgrp->release_list))
4681 list_del_init(&cgrp->release_list);
4682 raw_spin_unlock(&release_list_lock);
4685 * If @cgrp has css's attached, the second stage of cgroup
4686 * destruction is kicked off from css_killed_work_fn() after the
4687 * refs of all attached css's are killed. If @cgrp doesn't have
4688 * any css, we kick it off here.
4691 cgroup_destroy_css_killed(cgrp);
4694 * Clear and remove @cgrp directory. The removal puts the base ref
4695 * but we aren't quite done with @cgrp yet, so hold onto it.
4697 cgroup_clear_dir(cgrp, cgrp->root->subsys_mask);
4698 cgroup_addrm_files(cgrp, cgroup_base_files, false);
4700 cgroup_d_remove_dir(d);
4703 * Unregister events and notify userspace.
4704 * Notify userspace about cgroup removing only after rmdir of cgroup
4705 * directory to avoid race between userspace and kernelspace.
4707 spin_lock(&cgrp->event_list_lock);
4708 list_for_each_entry_safe(event, tmp, &cgrp->event_list, list) {
4709 list_del_init(&event->list);
4710 schedule_work(&event->remove);
4712 spin_unlock(&cgrp->event_list_lock);
4718 * cgroup_destroy_css_killed - the second step of cgroup destruction
4719 * @work: cgroup->destroy_free_work
4721 * This function is invoked from a work item for a cgroup which is being
4722 * destroyed after all css's are offlined and performs the rest of
4723 * destruction. This is the second step of destruction described in the
4724 * comment above cgroup_destroy_locked().
4726 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
4728 struct cgroup *parent = cgrp->parent;
4729 struct dentry *d = cgrp->dentry;
4731 lockdep_assert_held(&cgroup_mutex);
4733 /* delete this cgroup from parent->children */
4734 list_del_rcu(&cgrp->sibling);
4737 * We should remove the cgroup object from idr before its grace
4738 * period starts, so we won't be looking up a cgroup while the
4739 * cgroup is being freed.
4741 idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4746 set_bit(CGRP_RELEASABLE, &parent->flags);
4747 check_for_release(parent);
4750 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4754 mutex_lock(&cgroup_mutex);
4755 ret = cgroup_destroy_locked(dentry->d_fsdata);
4756 mutex_unlock(&cgroup_mutex);
4761 static void __init_or_module cgroup_init_cftsets(struct cgroup_subsys *ss)
4763 INIT_LIST_HEAD(&ss->cftsets);
4766 * base_cftset is embedded in subsys itself, no need to worry about
4769 if (ss->base_cftypes) {
4772 for (cft = ss->base_cftypes; cft->name[0] != '\0'; cft++)
4775 ss->base_cftset.cfts = ss->base_cftypes;
4776 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4780 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4782 struct cgroup_subsys_state *css;
4784 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4786 mutex_lock(&cgroup_mutex);
4788 /* init base cftset */
4789 cgroup_init_cftsets(ss);
4791 /* Create the top cgroup state for this subsystem */
4792 list_add(&ss->sibling, &cgroup_dummy_root.subsys_list);
4793 ss->root = &cgroup_dummy_root;
4794 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss->subsys_id));
4795 /* We don't handle early failures gracefully */
4796 BUG_ON(IS_ERR(css));
4797 init_css(css, ss, cgroup_dummy_top);
4799 /* Update the init_css_set to contain a subsys
4800 * pointer to this state - since the subsystem is
4801 * newly registered, all tasks and hence the
4802 * init_css_set is in the subsystem's top cgroup. */
4803 init_css_set.subsys[ss->subsys_id] = css;
4805 need_forkexit_callback |= ss->fork || ss->exit;
4807 /* At system boot, before all subsystems have been
4808 * registered, no tasks have been forked, so we don't
4809 * need to invoke fork callbacks here. */
4810 BUG_ON(!list_empty(&init_task.tasks));
4812 BUG_ON(online_css(css));
4814 mutex_unlock(&cgroup_mutex);
4816 /* this function shouldn't be used with modular subsystems, since they
4817 * need to register a subsys_id, among other things */
4822 * cgroup_load_subsys: load and register a modular subsystem at runtime
4823 * @ss: the subsystem to load
4825 * This function should be called in a modular subsystem's initcall. If the
4826 * subsystem is built as a module, it will be assigned a new subsys_id and set
4827 * up for use. If the subsystem is built-in anyway, work is delegated to the
4828 * simpler cgroup_init_subsys.
4830 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
4832 struct cgroup_subsys_state *css;
4834 struct hlist_node *tmp;
4835 struct css_set *cset;
4838 /* check name and function validity */
4839 if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
4840 ss->css_alloc == NULL || ss->css_free == NULL)
4844 * we don't support callbacks in modular subsystems. this check is
4845 * before the ss->module check for consistency; a subsystem that could
4846 * be a module should still have no callbacks even if the user isn't
4847 * compiling it as one.
4849 if (ss->fork || ss->exit)
4853 * an optionally modular subsystem is built-in: we want to do nothing,
4854 * since cgroup_init_subsys will have already taken care of it.
4856 if (ss->module == NULL) {
4857 /* a sanity check */
4858 BUG_ON(cgroup_subsys[ss->subsys_id] != ss);
4862 /* init base cftset */
4863 cgroup_init_cftsets(ss);
4865 mutex_lock(&cgroup_mutex);
4866 cgroup_subsys[ss->subsys_id] = ss;
4869 * no ss->css_alloc seems to need anything important in the ss
4870 * struct, so this can happen first (i.e. before the dummy root
4873 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss->subsys_id));
4875 /* failure case - need to deassign the cgroup_subsys[] slot. */
4876 cgroup_subsys[ss->subsys_id] = NULL;
4877 mutex_unlock(&cgroup_mutex);
4878 return PTR_ERR(css);
4881 list_add(&ss->sibling, &cgroup_dummy_root.subsys_list);
4882 ss->root = &cgroup_dummy_root;
4884 /* our new subsystem will be attached to the dummy hierarchy. */
4885 init_css(css, ss, cgroup_dummy_top);
4886 /* init_idr must be after init_css() because it sets css->id. */
4888 ret = cgroup_init_idr(ss, css);
4894 * Now we need to entangle the css into the existing css_sets. unlike
4895 * in cgroup_init_subsys, there are now multiple css_sets, so each one
4896 * will need a new pointer to it; done by iterating the css_set_table.
4897 * furthermore, modifying the existing css_sets will corrupt the hash
4898 * table state, so each changed css_set will need its hash recomputed.
4899 * this is all done under the css_set_lock.
4901 write_lock(&css_set_lock);
4902 hash_for_each_safe(css_set_table, i, tmp, cset, hlist) {
4903 /* skip entries that we already rehashed */
4904 if (cset->subsys[ss->subsys_id])
4906 /* remove existing entry */
4907 hash_del(&cset->hlist);
4909 cset->subsys[ss->subsys_id] = css;
4910 /* recompute hash and restore entry */
4911 key = css_set_hash(cset->subsys);
4912 hash_add(css_set_table, &cset->hlist, key);
4914 write_unlock(&css_set_lock);
4916 ret = online_css(css);
4921 mutex_unlock(&cgroup_mutex);
4925 mutex_unlock(&cgroup_mutex);
4926 /* @ss can't be mounted here as try_module_get() would fail */
4927 cgroup_unload_subsys(ss);
4930 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
4933 * cgroup_unload_subsys: unload a modular subsystem
4934 * @ss: the subsystem to unload
4936 * This function should be called in a modular subsystem's exitcall. When this
4937 * function is invoked, the refcount on the subsystem's module will be 0, so
4938 * the subsystem will not be attached to any hierarchy.
4940 void cgroup_unload_subsys(struct cgroup_subsys *ss)
4942 struct cgrp_cset_link *link;
4944 BUG_ON(ss->module == NULL);
4947 * we shouldn't be called if the subsystem is in use, and the use of
4948 * try_module_get() in rebind_subsystems() should ensure that it
4949 * doesn't start being used while we're killing it off.
4951 BUG_ON(ss->root != &cgroup_dummy_root);
4953 mutex_lock(&cgroup_mutex);
4955 offline_css(cgroup_css(cgroup_dummy_top, ss->subsys_id));
4958 idr_destroy(&ss->idr);
4960 /* deassign the subsys_id */
4961 cgroup_subsys[ss->subsys_id] = NULL;
4963 /* remove subsystem from the dummy root's list of subsystems */
4964 list_del_init(&ss->sibling);
4967 * disentangle the css from all css_sets attached to the dummy
4968 * top. as in loading, we need to pay our respects to the hashtable
4971 write_lock(&css_set_lock);
4972 list_for_each_entry(link, &cgroup_dummy_top->cset_links, cset_link) {
4973 struct css_set *cset = link->cset;
4976 hash_del(&cset->hlist);
4977 cset->subsys[ss->subsys_id] = NULL;
4978 key = css_set_hash(cset->subsys);
4979 hash_add(css_set_table, &cset->hlist, key);
4981 write_unlock(&css_set_lock);
4984 * remove subsystem's css from the cgroup_dummy_top and free it -
4985 * need to free before marking as null because ss->css_free needs
4986 * the cgrp->subsys pointer to find their state. note that this
4987 * also takes care of freeing the css_id.
4989 ss->css_free(cgroup_css(cgroup_dummy_top, ss->subsys_id));
4990 RCU_INIT_POINTER(cgroup_dummy_top->subsys[ss->subsys_id], NULL);
4992 mutex_unlock(&cgroup_mutex);
4994 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
4997 * cgroup_init_early - cgroup initialization at system boot
4999 * Initialize cgroups at system boot, and initialize any
5000 * subsystems that request early init.
5002 int __init cgroup_init_early(void)
5004 struct cgroup_subsys *ss;
5007 atomic_set(&init_css_set.refcount, 1);
5008 INIT_LIST_HEAD(&init_css_set.cgrp_links);
5009 INIT_LIST_HEAD(&init_css_set.tasks);
5010 INIT_HLIST_NODE(&init_css_set.hlist);
5012 init_cgroup_root(&cgroup_dummy_root);
5013 cgroup_root_count = 1;
5014 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
5016 init_cgrp_cset_link.cset = &init_css_set;
5017 init_cgrp_cset_link.cgrp = cgroup_dummy_top;
5018 list_add(&init_cgrp_cset_link.cset_link, &cgroup_dummy_top->cset_links);
5019 list_add(&init_cgrp_cset_link.cgrp_link, &init_css_set.cgrp_links);
5021 /* at bootup time, we don't worry about modular subsystems */
5022 for_each_builtin_subsys(ss, i) {
5024 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
5025 BUG_ON(!ss->css_alloc);
5026 BUG_ON(!ss->css_free);
5027 if (ss->subsys_id != i) {
5028 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
5029 ss->name, ss->subsys_id);
5034 cgroup_init_subsys(ss);
5040 * cgroup_init - cgroup initialization
5042 * Register cgroup filesystem and /proc file, and initialize
5043 * any subsystems that didn't request early init.
5045 int __init cgroup_init(void)
5047 struct cgroup_subsys *ss;
5051 err = bdi_init(&cgroup_backing_dev_info);
5055 for_each_builtin_subsys(ss, i) {
5056 if (!ss->early_init)
5057 cgroup_init_subsys(ss);
5059 cgroup_init_idr(ss, init_css_set.subsys[ss->subsys_id]);
5062 /* allocate id for the dummy hierarchy */
5063 mutex_lock(&cgroup_mutex);
5064 mutex_lock(&cgroup_root_mutex);
5066 /* Add init_css_set to the hash table */
5067 key = css_set_hash(init_css_set.subsys);
5068 hash_add(css_set_table, &init_css_set.hlist, key);
5070 BUG_ON(cgroup_init_root_id(&cgroup_dummy_root, 0, 1));
5072 err = idr_alloc(&cgroup_dummy_root.cgroup_idr, cgroup_dummy_top,
5076 mutex_unlock(&cgroup_root_mutex);
5077 mutex_unlock(&cgroup_mutex);
5079 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
5085 err = register_filesystem(&cgroup_fs_type);
5087 kobject_put(cgroup_kobj);
5091 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
5095 bdi_destroy(&cgroup_backing_dev_info);
5101 * proc_cgroup_show()
5102 * - Print task's cgroup paths into seq_file, one line for each hierarchy
5103 * - Used for /proc/<pid>/cgroup.
5104 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
5105 * doesn't really matter if tsk->cgroup changes after we read it,
5106 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
5107 * anyway. No need to check that tsk->cgroup != NULL, thanks to
5108 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
5109 * cgroup to top_cgroup.
5112 /* TODO: Use a proper seq_file iterator */
5113 int proc_cgroup_show(struct seq_file *m, void *v)
5116 struct task_struct *tsk;
5119 struct cgroupfs_root *root;
5122 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5128 tsk = get_pid_task(pid, PIDTYPE_PID);
5134 mutex_lock(&cgroup_mutex);
5136 for_each_active_root(root) {
5137 struct cgroup_subsys *ss;
5138 struct cgroup *cgrp;
5141 seq_printf(m, "%d:", root->hierarchy_id);
5142 for_each_root_subsys(root, ss)
5143 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
5144 if (strlen(root->name))
5145 seq_printf(m, "%sname=%s", count ? "," : "",
5148 cgrp = task_cgroup_from_root(tsk, root);
5149 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
5157 mutex_unlock(&cgroup_mutex);
5158 put_task_struct(tsk);
5165 /* Display information about each subsystem and each hierarchy */
5166 static int proc_cgroupstats_show(struct seq_file *m, void *v)
5168 struct cgroup_subsys *ss;
5171 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
5173 * ideally we don't want subsystems moving around while we do this.
5174 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
5175 * subsys/hierarchy state.
5177 mutex_lock(&cgroup_mutex);
5179 for_each_subsys(ss, i)
5180 seq_printf(m, "%s\t%d\t%d\t%d\n",
5181 ss->name, ss->root->hierarchy_id,
5182 ss->root->number_of_cgroups, !ss->disabled);
5184 mutex_unlock(&cgroup_mutex);
5188 static int cgroupstats_open(struct inode *inode, struct file *file)
5190 return single_open(file, proc_cgroupstats_show, NULL);
5193 static const struct file_operations proc_cgroupstats_operations = {
5194 .open = cgroupstats_open,
5196 .llseek = seq_lseek,
5197 .release = single_release,
5201 * cgroup_fork - attach newly forked task to its parents cgroup.
5202 * @child: pointer to task_struct of forking parent process.
5204 * Description: A task inherits its parent's cgroup at fork().
5206 * A pointer to the shared css_set was automatically copied in
5207 * fork.c by dup_task_struct(). However, we ignore that copy, since
5208 * it was not made under the protection of RCU or cgroup_mutex, so
5209 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
5210 * have already changed current->cgroups, allowing the previously
5211 * referenced cgroup group to be removed and freed.
5213 * At the point that cgroup_fork() is called, 'current' is the parent
5214 * task, and the passed argument 'child' points to the child task.
5216 void cgroup_fork(struct task_struct *child)
5219 get_css_set(task_css_set(current));
5220 child->cgroups = current->cgroups;
5221 task_unlock(current);
5222 INIT_LIST_HEAD(&child->cg_list);
5226 * cgroup_post_fork - called on a new task after adding it to the task list
5227 * @child: the task in question
5229 * Adds the task to the list running through its css_set if necessary and
5230 * call the subsystem fork() callbacks. Has to be after the task is
5231 * visible on the task list in case we race with the first call to
5232 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
5235 void cgroup_post_fork(struct task_struct *child)
5237 struct cgroup_subsys *ss;
5241 * use_task_css_set_links is set to 1 before we walk the tasklist
5242 * under the tasklist_lock and we read it here after we added the child
5243 * to the tasklist under the tasklist_lock as well. If the child wasn't
5244 * yet in the tasklist when we walked through it from
5245 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
5246 * should be visible now due to the paired locking and barriers implied
5247 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
5248 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
5251 if (use_task_css_set_links) {
5252 write_lock(&css_set_lock);
5254 if (list_empty(&child->cg_list))
5255 list_add(&child->cg_list, &task_css_set(child)->tasks);
5257 write_unlock(&css_set_lock);
5261 * Call ss->fork(). This must happen after @child is linked on
5262 * css_set; otherwise, @child might change state between ->fork()
5263 * and addition to css_set.
5265 if (need_forkexit_callback) {
5267 * fork/exit callbacks are supported only for builtin
5268 * subsystems, and the builtin section of the subsys
5269 * array is immutable, so we don't need to lock the
5270 * subsys array here. On the other hand, modular section
5271 * of the array can be freed at module unload, so we
5274 for_each_builtin_subsys(ss, i)
5281 * cgroup_exit - detach cgroup from exiting task
5282 * @tsk: pointer to task_struct of exiting process
5283 * @run_callback: run exit callbacks?
5285 * Description: Detach cgroup from @tsk and release it.
5287 * Note that cgroups marked notify_on_release force every task in
5288 * them to take the global cgroup_mutex mutex when exiting.
5289 * This could impact scaling on very large systems. Be reluctant to
5290 * use notify_on_release cgroups where very high task exit scaling
5291 * is required on large systems.
5293 * the_top_cgroup_hack:
5295 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
5297 * We call cgroup_exit() while the task is still competent to
5298 * handle notify_on_release(), then leave the task attached to the
5299 * root cgroup in each hierarchy for the remainder of its exit.
5301 * To do this properly, we would increment the reference count on
5302 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
5303 * code we would add a second cgroup function call, to drop that
5304 * reference. This would just create an unnecessary hot spot on
5305 * the top_cgroup reference count, to no avail.
5307 * Normally, holding a reference to a cgroup without bumping its
5308 * count is unsafe. The cgroup could go away, or someone could
5309 * attach us to a different cgroup, decrementing the count on
5310 * the first cgroup that we never incremented. But in this case,
5311 * top_cgroup isn't going away, and either task has PF_EXITING set,
5312 * which wards off any cgroup_attach_task() attempts, or task is a failed
5313 * fork, never visible to cgroup_attach_task.
5315 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
5317 struct cgroup_subsys *ss;
5318 struct css_set *cset;
5322 * Unlink from the css_set task list if necessary.
5323 * Optimistically check cg_list before taking
5326 if (!list_empty(&tsk->cg_list)) {
5327 write_lock(&css_set_lock);
5328 if (!list_empty(&tsk->cg_list))
5329 list_del_init(&tsk->cg_list);
5330 write_unlock(&css_set_lock);
5333 /* Reassign the task to the init_css_set. */
5335 cset = task_css_set(tsk);
5336 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
5338 if (run_callbacks && need_forkexit_callback) {
5340 * fork/exit callbacks are supported only for builtin
5341 * subsystems, see cgroup_post_fork() for details.
5343 for_each_builtin_subsys(ss, i) {
5345 struct cgroup_subsys_state *old_css = cset->subsys[i];
5346 struct cgroup_subsys_state *css = task_css(tsk, i);
5348 ss->exit(css, old_css, tsk);
5354 put_css_set_taskexit(cset);
5357 static void check_for_release(struct cgroup *cgrp)
5359 if (cgroup_is_releasable(cgrp) &&
5360 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
5362 * Control Group is currently removeable. If it's not
5363 * already queued for a userspace notification, queue
5366 int need_schedule_work = 0;
5368 raw_spin_lock(&release_list_lock);
5369 if (!cgroup_is_dead(cgrp) &&
5370 list_empty(&cgrp->release_list)) {
5371 list_add(&cgrp->release_list, &release_list);
5372 need_schedule_work = 1;
5374 raw_spin_unlock(&release_list_lock);
5375 if (need_schedule_work)
5376 schedule_work(&release_agent_work);
5381 * Notify userspace when a cgroup is released, by running the
5382 * configured release agent with the name of the cgroup (path
5383 * relative to the root of cgroup file system) as the argument.
5385 * Most likely, this user command will try to rmdir this cgroup.
5387 * This races with the possibility that some other task will be
5388 * attached to this cgroup before it is removed, or that some other
5389 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5390 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5391 * unused, and this cgroup will be reprieved from its death sentence,
5392 * to continue to serve a useful existence. Next time it's released,
5393 * we will get notified again, if it still has 'notify_on_release' set.
5395 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5396 * means only wait until the task is successfully execve()'d. The
5397 * separate release agent task is forked by call_usermodehelper(),
5398 * then control in this thread returns here, without waiting for the
5399 * release agent task. We don't bother to wait because the caller of
5400 * this routine has no use for the exit status of the release agent
5401 * task, so no sense holding our caller up for that.
5403 static void cgroup_release_agent(struct work_struct *work)
5405 BUG_ON(work != &release_agent_work);
5406 mutex_lock(&cgroup_mutex);
5407 raw_spin_lock(&release_list_lock);
5408 while (!list_empty(&release_list)) {
5409 char *argv[3], *envp[3];
5411 char *pathbuf = NULL, *agentbuf = NULL;
5412 struct cgroup *cgrp = list_entry(release_list.next,
5415 list_del_init(&cgrp->release_list);
5416 raw_spin_unlock(&release_list_lock);
5417 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5420 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
5422 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5427 argv[i++] = agentbuf;
5428 argv[i++] = pathbuf;
5432 /* minimal command environment */
5433 envp[i++] = "HOME=/";
5434 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5437 /* Drop the lock while we invoke the usermode helper,
5438 * since the exec could involve hitting disk and hence
5439 * be a slow process */
5440 mutex_unlock(&cgroup_mutex);
5441 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5442 mutex_lock(&cgroup_mutex);
5446 raw_spin_lock(&release_list_lock);
5448 raw_spin_unlock(&release_list_lock);
5449 mutex_unlock(&cgroup_mutex);
5452 static int __init cgroup_disable(char *str)
5454 struct cgroup_subsys *ss;
5458 while ((token = strsep(&str, ",")) != NULL) {
5463 * cgroup_disable, being at boot time, can't know about
5464 * module subsystems, so we don't worry about them.
5466 for_each_builtin_subsys(ss, i) {
5467 if (!strcmp(token, ss->name)) {
5469 printk(KERN_INFO "Disabling %s control group"
5470 " subsystem\n", ss->name);
5477 __setup("cgroup_disable=", cgroup_disable);
5480 * Functons for CSS ID.
5483 /* to get ID other than 0, this should be called when !cgroup_is_dead() */
5484 unsigned short css_id(struct cgroup_subsys_state *css)
5486 struct css_id *cssid;
5489 * This css_id() can return correct value when somone has refcnt
5490 * on this or this is under rcu_read_lock(). Once css->id is allocated,
5491 * it's unchanged until freed.
5493 cssid = rcu_dereference_raw(css->id);
5499 EXPORT_SYMBOL_GPL(css_id);
5502 * css_is_ancestor - test "root" css is an ancestor of "child"
5503 * @child: the css to be tested.
5504 * @root: the css supporsed to be an ancestor of the child.
5506 * Returns true if "root" is an ancestor of "child" in its hierarchy. Because
5507 * this function reads css->id, the caller must hold rcu_read_lock().
5508 * But, considering usual usage, the csses should be valid objects after test.
5509 * Assuming that the caller will do some action to the child if this returns
5510 * returns true, the caller must take "child";s reference count.
5511 * If "child" is valid object and this returns true, "root" is valid, too.
5514 bool css_is_ancestor(struct cgroup_subsys_state *child,
5515 const struct cgroup_subsys_state *root)
5517 struct css_id *child_id;
5518 struct css_id *root_id;
5520 child_id = rcu_dereference(child->id);
5523 root_id = rcu_dereference(root->id);
5526 if (child_id->depth < root_id->depth)
5528 if (child_id->stack[root_id->depth] != root_id->id)
5533 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
5535 struct css_id *id = rcu_dereference_protected(css->id, true);
5537 /* When this is called before css_id initialization, id can be NULL */
5541 BUG_ON(!ss->use_id);
5543 rcu_assign_pointer(id->css, NULL);
5544 rcu_assign_pointer(css->id, NULL);
5545 spin_lock(&ss->id_lock);
5546 idr_remove(&ss->idr, id->id);
5547 spin_unlock(&ss->id_lock);
5548 kfree_rcu(id, rcu_head);
5550 EXPORT_SYMBOL_GPL(free_css_id);
5553 * This is called by init or create(). Then, calls to this function are
5554 * always serialized (By cgroup_mutex() at create()).
5557 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
5559 struct css_id *newid;
5562 BUG_ON(!ss->use_id);
5564 size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
5565 newid = kzalloc(size, GFP_KERNEL);
5567 return ERR_PTR(-ENOMEM);
5569 idr_preload(GFP_KERNEL);
5570 spin_lock(&ss->id_lock);
5571 /* Don't use 0. allocates an ID of 1-65535 */
5572 ret = idr_alloc(&ss->idr, newid, 1, CSS_ID_MAX + 1, GFP_NOWAIT);
5573 spin_unlock(&ss->id_lock);
5576 /* Returns error when there are no free spaces for new ID.*/
5581 newid->depth = depth;
5585 return ERR_PTR(ret);
5589 static int __init_or_module cgroup_init_idr(struct cgroup_subsys *ss,
5590 struct cgroup_subsys_state *rootcss)
5592 struct css_id *newid;
5594 spin_lock_init(&ss->id_lock);
5597 newid = get_new_cssid(ss, 0);
5599 return PTR_ERR(newid);
5601 newid->stack[0] = newid->id;
5602 RCU_INIT_POINTER(newid->css, rootcss);
5603 RCU_INIT_POINTER(rootcss->id, newid);
5607 static int alloc_css_id(struct cgroup_subsys_state *child_css)
5609 struct cgroup_subsys_state *parent_css = css_parent(child_css);
5610 struct css_id *child_id, *parent_id;
5613 parent_id = rcu_dereference_protected(parent_css->id, true);
5614 depth = parent_id->depth + 1;
5616 child_id = get_new_cssid(child_css->ss, depth);
5617 if (IS_ERR(child_id))
5618 return PTR_ERR(child_id);
5620 for (i = 0; i < depth; i++)
5621 child_id->stack[i] = parent_id->stack[i];
5622 child_id->stack[depth] = child_id->id;
5624 * child_id->css pointer will be set after this cgroup is available
5625 * see cgroup_populate_dir()
5627 rcu_assign_pointer(child_css->id, child_id);
5633 * css_lookup - lookup css by id
5634 * @ss: cgroup subsys to be looked into.
5637 * Returns pointer to cgroup_subsys_state if there is valid one with id.
5638 * NULL if not. Should be called under rcu_read_lock()
5640 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
5642 struct css_id *cssid = NULL;
5644 BUG_ON(!ss->use_id);
5645 cssid = idr_find(&ss->idr, id);
5647 if (unlikely(!cssid))
5650 return rcu_dereference(cssid->css);
5652 EXPORT_SYMBOL_GPL(css_lookup);
5655 * cgroup_css_from_dir - get corresponding css from file open on cgroup dir
5656 * @f: directory file of interest
5657 * @id: subsystem id of interest
5659 * Must be called under RCU read lock. The caller is responsible for
5660 * pinning the returned css if it needs to be accessed outside the RCU
5663 struct cgroup_subsys_state *cgroup_css_from_dir(struct file *f, int id)
5665 struct cgroup *cgrp;
5666 struct inode *inode;
5667 struct cgroup_subsys_state *css;
5669 WARN_ON_ONCE(!rcu_read_lock_held());
5671 inode = file_inode(f);
5672 /* check in cgroup filesystem dir */
5673 if (inode->i_op != &cgroup_dir_inode_operations)
5674 return ERR_PTR(-EBADF);
5676 if (id < 0 || id >= CGROUP_SUBSYS_COUNT)
5677 return ERR_PTR(-EINVAL);
5680 cgrp = __d_cgrp(f->f_dentry);
5681 css = cgroup_css(cgrp, id);
5682 return css ? css : ERR_PTR(-ENOENT);
5685 #ifdef CONFIG_CGROUP_DEBUG
5686 static struct cgroup_subsys_state *
5687 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5689 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5692 return ERR_PTR(-ENOMEM);
5697 static void debug_css_free(struct cgroup_subsys_state *css)
5702 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5705 return cgroup_task_count(css->cgroup);
5708 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5711 return (u64)(unsigned long)current->cgroups;
5714 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5720 count = atomic_read(&task_css_set(current)->refcount);
5725 static int current_css_set_cg_links_read(struct cgroup_subsys_state *css,
5727 struct seq_file *seq)
5729 struct cgrp_cset_link *link;
5730 struct css_set *cset;
5732 read_lock(&css_set_lock);
5734 cset = rcu_dereference(current->cgroups);
5735 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5736 struct cgroup *c = link->cgrp;
5740 name = c->dentry->d_name.name;
5743 seq_printf(seq, "Root %d group %s\n",
5744 c->root->hierarchy_id, name);
5747 read_unlock(&css_set_lock);
5751 #define MAX_TASKS_SHOWN_PER_CSS 25
5752 static int cgroup_css_links_read(struct cgroup_subsys_state *css,
5753 struct cftype *cft, struct seq_file *seq)
5755 struct cgrp_cset_link *link;
5757 read_lock(&css_set_lock);
5758 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5759 struct css_set *cset = link->cset;
5760 struct task_struct *task;
5762 seq_printf(seq, "css_set %p\n", cset);
5763 list_for_each_entry(task, &cset->tasks, cg_list) {
5764 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5765 seq_puts(seq, " ...\n");
5768 seq_printf(seq, " task %d\n",
5769 task_pid_vnr(task));
5773 read_unlock(&css_set_lock);
5777 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5779 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
5782 static struct cftype debug_files[] = {
5784 .name = "taskcount",
5785 .read_u64 = debug_taskcount_read,
5789 .name = "current_css_set",
5790 .read_u64 = current_css_set_read,
5794 .name = "current_css_set_refcount",
5795 .read_u64 = current_css_set_refcount_read,
5799 .name = "current_css_set_cg_links",
5800 .read_seq_string = current_css_set_cg_links_read,
5804 .name = "cgroup_css_links",
5805 .read_seq_string = cgroup_css_links_read,
5809 .name = "releasable",
5810 .read_u64 = releasable_read,
5816 struct cgroup_subsys debug_subsys = {
5818 .css_alloc = debug_css_alloc,
5819 .css_free = debug_css_free,
5820 .subsys_id = debug_subsys_id,
5821 .base_cftypes = debug_files,
5823 #endif /* CONFIG_CGROUP_DEBUG */