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 task_subsys_state_check() */
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;
122 struct simple_xattrs xattrs;
126 * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when
127 * cgroup_subsys->use_id != 0.
129 #define CSS_ID_MAX (65535)
132 * The css to which this ID points. This pointer is set to valid value
133 * after cgroup is populated. If cgroup is removed, this will be NULL.
134 * This pointer is expected to be RCU-safe because destroy()
135 * is called after synchronize_rcu(). But for safe use, css_tryget()
136 * should be used for avoiding race.
138 struct cgroup_subsys_state __rcu *css;
144 * Depth in hierarchy which this ID belongs to.
146 unsigned short depth;
148 * ID is freed by RCU. (and lookup routine is RCU safe.)
150 struct rcu_head rcu_head;
152 * Hierarchy of CSS ID belongs to.
154 unsigned short stack[0]; /* Array of Length (depth+1) */
158 * cgroup_event represents events which userspace want to receive.
160 struct cgroup_event {
162 * Cgroup which the event belongs to.
166 * Control file which the event associated.
170 * eventfd to signal userspace about the event.
172 struct eventfd_ctx *eventfd;
174 * Each of these stored in a list by the cgroup.
176 struct list_head list;
178 * All fields below needed to unregister event when
179 * userspace closes eventfd.
182 wait_queue_head_t *wqh;
184 struct work_struct remove;
187 /* The list of hierarchy roots */
189 static LIST_HEAD(cgroup_roots);
190 static int cgroup_root_count;
193 * Hierarchy ID allocation and mapping. It follows the same exclusion
194 * rules as other root ops - both cgroup_mutex and cgroup_root_mutex for
195 * writes, either for reads.
197 static DEFINE_IDR(cgroup_hierarchy_idr);
199 static struct cgroup_name root_cgroup_name = { .name = "/" };
202 * Assign a monotonically increasing serial number to cgroups. It
203 * guarantees cgroups with bigger numbers are newer than those with smaller
204 * numbers. Also, as cgroups are always appended to the parent's
205 * ->children list, it guarantees that sibling cgroups are always sorted in
206 * the ascending serial number order on the list. Protected by
209 static u64 cgroup_serial_nr_next = 1;
211 /* This flag indicates whether tasks in the fork and exit paths should
212 * check for fork/exit handlers to call. This avoids us having to do
213 * extra work in the fork/exit path if none of the subsystems need to
216 static int need_forkexit_callback __read_mostly;
218 static struct cftype cgroup_base_files[];
220 static void cgroup_offline_fn(struct work_struct *work);
221 static int cgroup_destroy_locked(struct cgroup *cgrp);
222 static int cgroup_addrm_files(struct cgroup *cgrp, struct cgroup_subsys *subsys,
223 struct cftype cfts[], bool is_add);
225 /* convenient tests for these bits */
226 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
228 return test_bit(CGRP_DEAD, &cgrp->flags);
232 * cgroup_is_descendant - test ancestry
233 * @cgrp: the cgroup to be tested
234 * @ancestor: possible ancestor of @cgrp
236 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
237 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
238 * and @ancestor are accessible.
240 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
243 if (cgrp == ancestor)
249 EXPORT_SYMBOL_GPL(cgroup_is_descendant);
251 static int cgroup_is_releasable(const struct cgroup *cgrp)
254 (1 << CGRP_RELEASABLE) |
255 (1 << CGRP_NOTIFY_ON_RELEASE);
256 return (cgrp->flags & bits) == bits;
259 static int notify_on_release(const struct cgroup *cgrp)
261 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
265 * for_each_subsys - iterate all loaded cgroup subsystems
266 * @ss: the iteration cursor
267 * @i: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
269 * Should be called under cgroup_mutex.
271 #define for_each_subsys(ss, i) \
272 for ((i) = 0; (i) < CGROUP_SUBSYS_COUNT; (i)++) \
273 if (({ lockdep_assert_held(&cgroup_mutex); \
274 !((ss) = cgroup_subsys[i]); })) { } \
278 * for_each_builtin_subsys - iterate all built-in cgroup subsystems
279 * @ss: the iteration cursor
280 * @i: the index of @ss, CGROUP_BUILTIN_SUBSYS_COUNT after reaching the end
282 * Bulit-in subsystems are always present and iteration itself doesn't
283 * require any synchronization.
285 #define for_each_builtin_subsys(ss, i) \
286 for ((i) = 0; (i) < CGROUP_BUILTIN_SUBSYS_COUNT && \
287 (((ss) = cgroup_subsys[i]) || true); (i)++)
289 /* iterate each subsystem attached to a hierarchy */
290 #define for_each_root_subsys(root, ss) \
291 list_for_each_entry((ss), &(root)->subsys_list, sibling)
293 /* iterate across the active hierarchies */
294 #define for_each_active_root(root) \
295 list_for_each_entry((root), &cgroup_roots, root_list)
297 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
299 return dentry->d_fsdata;
302 static inline struct cfent *__d_cfe(struct dentry *dentry)
304 return dentry->d_fsdata;
307 static inline struct cftype *__d_cft(struct dentry *dentry)
309 return __d_cfe(dentry)->type;
313 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
314 * @cgrp: the cgroup to be checked for liveness
316 * On success, returns true; the mutex should be later unlocked. On
317 * failure returns false with no lock held.
319 static bool cgroup_lock_live_group(struct cgroup *cgrp)
321 mutex_lock(&cgroup_mutex);
322 if (cgroup_is_dead(cgrp)) {
323 mutex_unlock(&cgroup_mutex);
329 /* the list of cgroups eligible for automatic release. Protected by
330 * release_list_lock */
331 static LIST_HEAD(release_list);
332 static DEFINE_RAW_SPINLOCK(release_list_lock);
333 static void cgroup_release_agent(struct work_struct *work);
334 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
335 static void check_for_release(struct cgroup *cgrp);
338 * A cgroup can be associated with multiple css_sets as different tasks may
339 * belong to different cgroups on different hierarchies. In the other
340 * direction, a css_set is naturally associated with multiple cgroups.
341 * This M:N relationship is represented by the following link structure
342 * which exists for each association and allows traversing the associations
345 struct cgrp_cset_link {
346 /* the cgroup and css_set this link associates */
348 struct css_set *cset;
350 /* list of cgrp_cset_links anchored at cgrp->cset_links */
351 struct list_head cset_link;
353 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
354 struct list_head cgrp_link;
357 /* The default css_set - used by init and its children prior to any
358 * hierarchies being mounted. It contains a pointer to the root state
359 * for each subsystem. Also used to anchor the list of css_sets. Not
360 * reference-counted, to improve performance when child cgroups
361 * haven't been created.
364 static struct css_set init_css_set;
365 static struct cgrp_cset_link init_cgrp_cset_link;
367 static int cgroup_init_idr(struct cgroup_subsys *ss,
368 struct cgroup_subsys_state *css);
370 /* css_set_lock protects the list of css_set objects, and the
371 * chain of tasks off each css_set. Nests outside task->alloc_lock
372 * due to cgroup_iter_start() */
373 static DEFINE_RWLOCK(css_set_lock);
374 static int css_set_count;
377 * hash table for cgroup groups. This improves the performance to find
378 * an existing css_set. This hash doesn't (currently) take into
379 * account cgroups in empty hierarchies.
381 #define CSS_SET_HASH_BITS 7
382 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
384 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
386 unsigned long key = 0UL;
387 struct cgroup_subsys *ss;
390 for_each_subsys(ss, i)
391 key += (unsigned long)css[i];
392 key = (key >> 16) ^ key;
397 /* We don't maintain the lists running through each css_set to its
398 * task until after the first call to cgroup_iter_start(). This
399 * reduces the fork()/exit() overhead for people who have cgroups
400 * compiled into their kernel but not actually in use */
401 static int use_task_css_set_links __read_mostly;
403 static void __put_css_set(struct css_set *cset, int taskexit)
405 struct cgrp_cset_link *link, *tmp_link;
408 * Ensure that the refcount doesn't hit zero while any readers
409 * can see it. Similar to atomic_dec_and_lock(), but for an
412 if (atomic_add_unless(&cset->refcount, -1, 1))
414 write_lock(&css_set_lock);
415 if (!atomic_dec_and_test(&cset->refcount)) {
416 write_unlock(&css_set_lock);
420 /* This css_set is dead. unlink it and release cgroup refcounts */
421 hash_del(&cset->hlist);
424 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
425 struct cgroup *cgrp = link->cgrp;
427 list_del(&link->cset_link);
428 list_del(&link->cgrp_link);
430 /* @cgrp can't go away while we're holding css_set_lock */
431 if (list_empty(&cgrp->cset_links) && notify_on_release(cgrp)) {
433 set_bit(CGRP_RELEASABLE, &cgrp->flags);
434 check_for_release(cgrp);
440 write_unlock(&css_set_lock);
441 kfree_rcu(cset, rcu_head);
445 * refcounted get/put for css_set objects
447 static inline void get_css_set(struct css_set *cset)
449 atomic_inc(&cset->refcount);
452 static inline void put_css_set(struct css_set *cset)
454 __put_css_set(cset, 0);
457 static inline void put_css_set_taskexit(struct css_set *cset)
459 __put_css_set(cset, 1);
463 * compare_css_sets - helper function for find_existing_css_set().
464 * @cset: candidate css_set being tested
465 * @old_cset: existing css_set for a task
466 * @new_cgrp: cgroup that's being entered by the task
467 * @template: desired set of css pointers in css_set (pre-calculated)
469 * Returns true if "cg" matches "old_cg" except for the hierarchy
470 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
472 static bool compare_css_sets(struct css_set *cset,
473 struct css_set *old_cset,
474 struct cgroup *new_cgrp,
475 struct cgroup_subsys_state *template[])
477 struct list_head *l1, *l2;
479 if (memcmp(template, cset->subsys, sizeof(cset->subsys))) {
480 /* Not all subsystems matched */
485 * Compare cgroup pointers in order to distinguish between
486 * different cgroups in heirarchies with no subsystems. We
487 * could get by with just this check alone (and skip the
488 * memcmp above) but on most setups the memcmp check will
489 * avoid the need for this more expensive check on almost all
493 l1 = &cset->cgrp_links;
494 l2 = &old_cset->cgrp_links;
496 struct cgrp_cset_link *link1, *link2;
497 struct cgroup *cgrp1, *cgrp2;
501 /* See if we reached the end - both lists are equal length. */
502 if (l1 == &cset->cgrp_links) {
503 BUG_ON(l2 != &old_cset->cgrp_links);
506 BUG_ON(l2 == &old_cset->cgrp_links);
508 /* Locate the cgroups associated with these links. */
509 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
510 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
513 /* Hierarchies should be linked in the same order. */
514 BUG_ON(cgrp1->root != cgrp2->root);
517 * If this hierarchy is the hierarchy of the cgroup
518 * that's changing, then we need to check that this
519 * css_set points to the new cgroup; if it's any other
520 * hierarchy, then this css_set should point to the
521 * same cgroup as the old css_set.
523 if (cgrp1->root == new_cgrp->root) {
524 if (cgrp1 != new_cgrp)
535 * find_existing_css_set - init css array and find the matching css_set
536 * @old_cset: the css_set that we're using before the cgroup transition
537 * @cgrp: the cgroup that we're moving into
538 * @template: out param for the new set of csses, should be clear on entry
540 static struct css_set *find_existing_css_set(struct css_set *old_cset,
542 struct cgroup_subsys_state *template[])
544 struct cgroupfs_root *root = cgrp->root;
545 struct cgroup_subsys *ss;
546 struct css_set *cset;
551 * Build the set of subsystem state objects that we want to see in the
552 * new css_set. while subsystems can change globally, the entries here
553 * won't change, so no need for locking.
555 for_each_subsys(ss, i) {
556 if (root->subsys_mask & (1UL << i)) {
557 /* Subsystem is in this hierarchy. So we want
558 * the subsystem state from the new
560 template[i] = cgrp->subsys[i];
562 /* Subsystem is not in this hierarchy, so we
563 * don't want to change the subsystem state */
564 template[i] = old_cset->subsys[i];
568 key = css_set_hash(template);
569 hash_for_each_possible(css_set_table, cset, hlist, key) {
570 if (!compare_css_sets(cset, old_cset, cgrp, template))
573 /* This css_set matches what we need */
577 /* No existing cgroup group matched */
581 static void free_cgrp_cset_links(struct list_head *links_to_free)
583 struct cgrp_cset_link *link, *tmp_link;
585 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
586 list_del(&link->cset_link);
592 * allocate_cgrp_cset_links - allocate cgrp_cset_links
593 * @count: the number of links to allocate
594 * @tmp_links: list_head the allocated links are put on
596 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
597 * through ->cset_link. Returns 0 on success or -errno.
599 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
601 struct cgrp_cset_link *link;
604 INIT_LIST_HEAD(tmp_links);
606 for (i = 0; i < count; i++) {
607 link = kzalloc(sizeof(*link), GFP_KERNEL);
609 free_cgrp_cset_links(tmp_links);
612 list_add(&link->cset_link, tmp_links);
618 * link_css_set - a helper function to link a css_set to a cgroup
619 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
620 * @cset: the css_set to be linked
621 * @cgrp: the destination cgroup
623 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
626 struct cgrp_cset_link *link;
628 BUG_ON(list_empty(tmp_links));
629 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
632 list_move(&link->cset_link, &cgrp->cset_links);
634 * Always add links to the tail of the list so that the list
635 * is sorted by order of hierarchy creation
637 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
641 * find_css_set - return a new css_set with one cgroup updated
642 * @old_cset: the baseline css_set
643 * @cgrp: the cgroup to be updated
645 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
646 * substituted into the appropriate hierarchy.
648 static struct css_set *find_css_set(struct css_set *old_cset,
651 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
652 struct css_set *cset;
653 struct list_head tmp_links;
654 struct cgrp_cset_link *link;
657 lockdep_assert_held(&cgroup_mutex);
659 /* First see if we already have a cgroup group that matches
661 read_lock(&css_set_lock);
662 cset = find_existing_css_set(old_cset, cgrp, template);
665 read_unlock(&css_set_lock);
670 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
674 /* Allocate all the cgrp_cset_link objects that we'll need */
675 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
680 atomic_set(&cset->refcount, 1);
681 INIT_LIST_HEAD(&cset->cgrp_links);
682 INIT_LIST_HEAD(&cset->tasks);
683 INIT_HLIST_NODE(&cset->hlist);
685 /* Copy the set of subsystem state objects generated in
686 * find_existing_css_set() */
687 memcpy(cset->subsys, template, sizeof(cset->subsys));
689 write_lock(&css_set_lock);
690 /* Add reference counts and links from the new css_set. */
691 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
692 struct cgroup *c = link->cgrp;
694 if (c->root == cgrp->root)
696 link_css_set(&tmp_links, cset, c);
699 BUG_ON(!list_empty(&tmp_links));
703 /* Add this cgroup group to the hash table */
704 key = css_set_hash(cset->subsys);
705 hash_add(css_set_table, &cset->hlist, key);
707 write_unlock(&css_set_lock);
713 * Return the cgroup for "task" from the given hierarchy. Must be
714 * called with cgroup_mutex held.
716 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
717 struct cgroupfs_root *root)
719 struct css_set *cset;
720 struct cgroup *res = NULL;
722 BUG_ON(!mutex_is_locked(&cgroup_mutex));
723 read_lock(&css_set_lock);
725 * No need to lock the task - since we hold cgroup_mutex the
726 * task can't change groups, so the only thing that can happen
727 * is that it exits and its css is set back to init_css_set.
729 cset = task_css_set(task);
730 if (cset == &init_css_set) {
731 res = &root->top_cgroup;
733 struct cgrp_cset_link *link;
735 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
736 struct cgroup *c = link->cgrp;
738 if (c->root == root) {
744 read_unlock(&css_set_lock);
750 * There is one global cgroup mutex. We also require taking
751 * task_lock() when dereferencing a task's cgroup subsys pointers.
752 * See "The task_lock() exception", at the end of this comment.
754 * A task must hold cgroup_mutex to modify cgroups.
756 * Any task can increment and decrement the count field without lock.
757 * So in general, code holding cgroup_mutex can't rely on the count
758 * field not changing. However, if the count goes to zero, then only
759 * cgroup_attach_task() can increment it again. Because a count of zero
760 * means that no tasks are currently attached, therefore there is no
761 * way a task attached to that cgroup can fork (the other way to
762 * increment the count). So code holding cgroup_mutex can safely
763 * assume that if the count is zero, it will stay zero. Similarly, if
764 * a task holds cgroup_mutex on a cgroup with zero count, it
765 * knows that the cgroup won't be removed, as cgroup_rmdir()
768 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
769 * (usually) take cgroup_mutex. These are the two most performance
770 * critical pieces of code here. The exception occurs on cgroup_exit(),
771 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
772 * is taken, and if the cgroup count is zero, a usermode call made
773 * to the release agent with the name of the cgroup (path relative to
774 * the root of cgroup file system) as the argument.
776 * A cgroup can only be deleted if both its 'count' of using tasks
777 * is zero, and its list of 'children' cgroups is empty. Since all
778 * tasks in the system use _some_ cgroup, and since there is always at
779 * least one task in the system (init, pid == 1), therefore, top_cgroup
780 * always has either children cgroups and/or using tasks. So we don't
781 * need a special hack to ensure that top_cgroup cannot be deleted.
783 * The task_lock() exception
785 * The need for this exception arises from the action of
786 * cgroup_attach_task(), which overwrites one task's cgroup pointer with
787 * another. It does so using cgroup_mutex, however there are
788 * several performance critical places that need to reference
789 * task->cgroup without the expense of grabbing a system global
790 * mutex. Therefore except as noted below, when dereferencing or, as
791 * in cgroup_attach_task(), modifying a task's cgroup pointer we use
792 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
793 * the task_struct routinely used for such matters.
795 * P.S. One more locking exception. RCU is used to guard the
796 * update of a tasks cgroup pointer by cgroup_attach_task()
800 * A couple of forward declarations required, due to cyclic reference loop:
801 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
802 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
806 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode);
807 static struct dentry *cgroup_lookup(struct inode *, struct dentry *, unsigned int);
808 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
809 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask);
810 static const struct inode_operations cgroup_dir_inode_operations;
811 static const struct file_operations proc_cgroupstats_operations;
813 static struct backing_dev_info cgroup_backing_dev_info = {
815 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
818 static int alloc_css_id(struct cgroup_subsys *ss,
819 struct cgroup *parent, struct cgroup *child);
821 static struct inode *cgroup_new_inode(umode_t mode, struct super_block *sb)
823 struct inode *inode = new_inode(sb);
826 inode->i_ino = get_next_ino();
827 inode->i_mode = mode;
828 inode->i_uid = current_fsuid();
829 inode->i_gid = current_fsgid();
830 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
831 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
836 static struct cgroup_name *cgroup_alloc_name(struct dentry *dentry)
838 struct cgroup_name *name;
840 name = kmalloc(sizeof(*name) + dentry->d_name.len + 1, GFP_KERNEL);
843 strcpy(name->name, dentry->d_name.name);
847 static void cgroup_free_fn(struct work_struct *work)
849 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
850 struct cgroup_subsys *ss;
852 mutex_lock(&cgroup_mutex);
854 * Release the subsystem state objects.
856 for_each_root_subsys(cgrp->root, ss)
859 cgrp->root->number_of_cgroups--;
860 mutex_unlock(&cgroup_mutex);
863 * We get a ref to the parent's dentry, and put the ref when
864 * this cgroup is being freed, so it's guaranteed that the
865 * parent won't be destroyed before its children.
867 dput(cgrp->parent->dentry);
869 ida_simple_remove(&cgrp->root->cgroup_ida, cgrp->id);
872 * Drop the active superblock reference that we took when we
873 * created the cgroup. This will free cgrp->root, if we are
874 * holding the last reference to @sb.
876 deactivate_super(cgrp->root->sb);
879 * if we're getting rid of the cgroup, refcount should ensure
880 * that there are no pidlists left.
882 BUG_ON(!list_empty(&cgrp->pidlists));
884 simple_xattrs_free(&cgrp->xattrs);
886 kfree(rcu_dereference_raw(cgrp->name));
890 static void cgroup_free_rcu(struct rcu_head *head)
892 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
894 INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
895 schedule_work(&cgrp->destroy_work);
898 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
900 /* is dentry a directory ? if so, kfree() associated cgroup */
901 if (S_ISDIR(inode->i_mode)) {
902 struct cgroup *cgrp = dentry->d_fsdata;
904 BUG_ON(!(cgroup_is_dead(cgrp)));
905 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
907 struct cfent *cfe = __d_cfe(dentry);
908 struct cgroup *cgrp = dentry->d_parent->d_fsdata;
910 WARN_ONCE(!list_empty(&cfe->node) &&
911 cgrp != &cgrp->root->top_cgroup,
912 "cfe still linked for %s\n", cfe->type->name);
913 simple_xattrs_free(&cfe->xattrs);
919 static int cgroup_delete(const struct dentry *d)
924 static void remove_dir(struct dentry *d)
926 struct dentry *parent = dget(d->d_parent);
929 simple_rmdir(parent->d_inode, d);
933 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
937 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
938 lockdep_assert_held(&cgroup_mutex);
941 * If we're doing cleanup due to failure of cgroup_create(),
942 * the corresponding @cfe may not exist.
944 list_for_each_entry(cfe, &cgrp->files, node) {
945 struct dentry *d = cfe->dentry;
947 if (cft && cfe->type != cft)
952 simple_unlink(cgrp->dentry->d_inode, d);
953 list_del_init(&cfe->node);
961 * cgroup_clear_dir - remove subsys files in a cgroup directory
962 * @cgrp: target cgroup
963 * @subsys_mask: mask of the subsystem ids whose files should be removed
965 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned long subsys_mask)
967 struct cgroup_subsys *ss;
969 for_each_root_subsys(cgrp->root, ss) {
970 struct cftype_set *set;
971 if (!test_bit(ss->subsys_id, &subsys_mask))
973 list_for_each_entry(set, &ss->cftsets, node)
974 cgroup_addrm_files(cgrp, NULL, set->cfts, false);
979 * NOTE : the dentry must have been dget()'ed
981 static void cgroup_d_remove_dir(struct dentry *dentry)
983 struct dentry *parent;
985 parent = dentry->d_parent;
986 spin_lock(&parent->d_lock);
987 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
988 list_del_init(&dentry->d_u.d_child);
989 spin_unlock(&dentry->d_lock);
990 spin_unlock(&parent->d_lock);
995 * Call with cgroup_mutex held. Drops reference counts on modules, including
996 * any duplicate ones that parse_cgroupfs_options took. If this function
997 * returns an error, no reference counts are touched.
999 static int rebind_subsystems(struct cgroupfs_root *root,
1000 unsigned long added_mask, unsigned removed_mask)
1002 struct cgroup *cgrp = &root->top_cgroup;
1003 struct cgroup_subsys *ss;
1006 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1007 BUG_ON(!mutex_is_locked(&cgroup_root_mutex));
1009 /* Check that any added subsystems are currently free */
1010 for_each_subsys(ss, i) {
1011 unsigned long bit = 1UL << i;
1013 if (!(bit & added_mask))
1016 if (ss->root != &cgroup_dummy_root) {
1017 /* Subsystem isn't free */
1022 /* Currently we don't handle adding/removing subsystems when
1023 * any child cgroups exist. This is theoretically supportable
1024 * but involves complex error handling, so it's being left until
1026 if (root->number_of_cgroups > 1)
1029 /* Process each subsystem */
1030 for_each_subsys(ss, i) {
1031 unsigned long bit = 1UL << i;
1033 if (bit & added_mask) {
1034 /* We're binding this subsystem to this hierarchy */
1035 BUG_ON(cgrp->subsys[i]);
1036 BUG_ON(!cgroup_dummy_top->subsys[i]);
1037 BUG_ON(cgroup_dummy_top->subsys[i]->cgroup != cgroup_dummy_top);
1039 cgrp->subsys[i] = cgroup_dummy_top->subsys[i];
1040 cgrp->subsys[i]->cgroup = cgrp;
1041 list_move(&ss->sibling, &root->subsys_list);
1046 /* refcount was already taken, and we're keeping it */
1047 root->subsys_mask |= bit;
1048 } else if (bit & removed_mask) {
1049 /* We're removing this subsystem */
1050 BUG_ON(cgrp->subsys[i] != cgroup_dummy_top->subsys[i]);
1051 BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
1054 ss->bind(cgroup_dummy_top);
1055 cgroup_dummy_top->subsys[i]->cgroup = cgroup_dummy_top;
1056 cgrp->subsys[i] = NULL;
1057 cgroup_subsys[i]->root = &cgroup_dummy_root;
1058 list_move(&ss->sibling, &cgroup_dummy_root.subsys_list);
1060 /* subsystem is now free - drop reference on module */
1061 module_put(ss->module);
1062 root->subsys_mask &= ~bit;
1063 } else if (bit & root->subsys_mask) {
1064 /* Subsystem state should already exist */
1065 BUG_ON(!cgrp->subsys[i]);
1067 * a refcount was taken, but we already had one, so
1068 * drop the extra reference.
1070 module_put(ss->module);
1071 #ifdef CONFIG_MODULE_UNLOAD
1072 BUG_ON(ss->module && !module_refcount(ss->module));
1075 /* Subsystem state shouldn't exist */
1076 BUG_ON(cgrp->subsys[i]);
1081 * Mark @root has finished binding subsystems. @root->subsys_mask
1082 * now matches the bound subsystems.
1084 root->flags |= CGRP_ROOT_SUBSYS_BOUND;
1089 static int cgroup_show_options(struct seq_file *seq, struct dentry *dentry)
1091 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
1092 struct cgroup_subsys *ss;
1094 mutex_lock(&cgroup_root_mutex);
1095 for_each_root_subsys(root, ss)
1096 seq_printf(seq, ",%s", ss->name);
1097 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1098 seq_puts(seq, ",sane_behavior");
1099 if (root->flags & CGRP_ROOT_NOPREFIX)
1100 seq_puts(seq, ",noprefix");
1101 if (root->flags & CGRP_ROOT_XATTR)
1102 seq_puts(seq, ",xattr");
1103 if (strlen(root->release_agent_path))
1104 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1105 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1106 seq_puts(seq, ",clone_children");
1107 if (strlen(root->name))
1108 seq_printf(seq, ",name=%s", root->name);
1109 mutex_unlock(&cgroup_root_mutex);
1113 struct cgroup_sb_opts {
1114 unsigned long subsys_mask;
1115 unsigned long flags;
1116 char *release_agent;
1117 bool cpuset_clone_children;
1119 /* User explicitly requested empty subsystem */
1122 struct cgroupfs_root *new_root;
1127 * Convert a hierarchy specifier into a bitmask of subsystems and
1128 * flags. Call with cgroup_mutex held to protect the cgroup_subsys[]
1129 * array. This function takes refcounts on subsystems to be used, unless it
1130 * returns error, in which case no refcounts are taken.
1132 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1134 char *token, *o = data;
1135 bool all_ss = false, one_ss = false;
1136 unsigned long mask = (unsigned long)-1;
1137 bool module_pin_failed = false;
1138 struct cgroup_subsys *ss;
1141 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1143 #ifdef CONFIG_CPUSETS
1144 mask = ~(1UL << cpuset_subsys_id);
1147 memset(opts, 0, sizeof(*opts));
1149 while ((token = strsep(&o, ",")) != NULL) {
1152 if (!strcmp(token, "none")) {
1153 /* Explicitly have no subsystems */
1157 if (!strcmp(token, "all")) {
1158 /* Mutually exclusive option 'all' + subsystem name */
1164 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1165 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1168 if (!strcmp(token, "noprefix")) {
1169 opts->flags |= CGRP_ROOT_NOPREFIX;
1172 if (!strcmp(token, "clone_children")) {
1173 opts->cpuset_clone_children = true;
1176 if (!strcmp(token, "xattr")) {
1177 opts->flags |= CGRP_ROOT_XATTR;
1180 if (!strncmp(token, "release_agent=", 14)) {
1181 /* Specifying two release agents is forbidden */
1182 if (opts->release_agent)
1184 opts->release_agent =
1185 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1186 if (!opts->release_agent)
1190 if (!strncmp(token, "name=", 5)) {
1191 const char *name = token + 5;
1192 /* Can't specify an empty name */
1195 /* Must match [\w.-]+ */
1196 for (i = 0; i < strlen(name); i++) {
1200 if ((c == '.') || (c == '-') || (c == '_'))
1204 /* Specifying two names is forbidden */
1207 opts->name = kstrndup(name,
1208 MAX_CGROUP_ROOT_NAMELEN - 1,
1216 for_each_subsys(ss, i) {
1217 if (strcmp(token, ss->name))
1222 /* Mutually exclusive option 'all' + subsystem name */
1225 set_bit(i, &opts->subsys_mask);
1230 if (i == CGROUP_SUBSYS_COUNT)
1235 * If the 'all' option was specified select all the subsystems,
1236 * otherwise if 'none', 'name=' and a subsystem name options
1237 * were not specified, let's default to 'all'
1239 if (all_ss || (!one_ss && !opts->none && !opts->name))
1240 for_each_subsys(ss, i)
1242 set_bit(i, &opts->subsys_mask);
1244 /* Consistency checks */
1246 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1247 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1249 if (opts->flags & CGRP_ROOT_NOPREFIX) {
1250 pr_err("cgroup: sane_behavior: noprefix is not allowed\n");
1254 if (opts->cpuset_clone_children) {
1255 pr_err("cgroup: sane_behavior: clone_children is not allowed\n");
1261 * Option noprefix was introduced just for backward compatibility
1262 * with the old cpuset, so we allow noprefix only if mounting just
1263 * the cpuset subsystem.
1265 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1269 /* Can't specify "none" and some subsystems */
1270 if (opts->subsys_mask && opts->none)
1274 * We either have to specify by name or by subsystems. (So all
1275 * empty hierarchies must have a name).
1277 if (!opts->subsys_mask && !opts->name)
1281 * Grab references on all the modules we'll need, so the subsystems
1282 * don't dance around before rebind_subsystems attaches them. This may
1283 * take duplicate reference counts on a subsystem that's already used,
1284 * but rebind_subsystems handles this case.
1286 for_each_subsys(ss, i) {
1287 if (!(opts->subsys_mask & (1UL << i)))
1289 if (!try_module_get(cgroup_subsys[i]->module)) {
1290 module_pin_failed = true;
1294 if (module_pin_failed) {
1296 * oops, one of the modules was going away. this means that we
1297 * raced with a module_delete call, and to the user this is
1298 * essentially a "subsystem doesn't exist" case.
1300 for (i--; i >= 0; i--) {
1301 /* drop refcounts only on the ones we took */
1302 unsigned long bit = 1UL << i;
1304 if (!(bit & opts->subsys_mask))
1306 module_put(cgroup_subsys[i]->module);
1314 static void drop_parsed_module_refcounts(unsigned long subsys_mask)
1316 struct cgroup_subsys *ss;
1319 mutex_lock(&cgroup_mutex);
1320 for_each_subsys(ss, i)
1321 if (subsys_mask & (1UL << i))
1322 module_put(cgroup_subsys[i]->module);
1323 mutex_unlock(&cgroup_mutex);
1326 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1329 struct cgroupfs_root *root = sb->s_fs_info;
1330 struct cgroup *cgrp = &root->top_cgroup;
1331 struct cgroup_sb_opts opts;
1332 unsigned long added_mask, removed_mask;
1334 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1335 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1339 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1340 mutex_lock(&cgroup_mutex);
1341 mutex_lock(&cgroup_root_mutex);
1343 /* See what subsystems are wanted */
1344 ret = parse_cgroupfs_options(data, &opts);
1348 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1349 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1350 task_tgid_nr(current), current->comm);
1352 added_mask = opts.subsys_mask & ~root->subsys_mask;
1353 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1355 /* Don't allow flags or name to change at remount */
1356 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1357 (opts.name && strcmp(opts.name, root->name))) {
1358 pr_err("cgroup: option or name mismatch, new: 0x%lx \"%s\", old: 0x%lx \"%s\"\n",
1359 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1360 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1366 * Clear out the files of subsystems that should be removed, do
1367 * this before rebind_subsystems, since rebind_subsystems may
1368 * change this hierarchy's subsys_list.
1370 cgroup_clear_dir(cgrp, removed_mask);
1372 ret = rebind_subsystems(root, added_mask, removed_mask);
1374 /* rebind_subsystems failed, re-populate the removed files */
1375 cgroup_populate_dir(cgrp, removed_mask);
1379 /* re-populate subsystem files */
1380 cgroup_populate_dir(cgrp, added_mask);
1382 if (opts.release_agent)
1383 strcpy(root->release_agent_path, opts.release_agent);
1385 kfree(opts.release_agent);
1387 mutex_unlock(&cgroup_root_mutex);
1388 mutex_unlock(&cgroup_mutex);
1389 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1391 drop_parsed_module_refcounts(opts.subsys_mask);
1395 static const struct super_operations cgroup_ops = {
1396 .statfs = simple_statfs,
1397 .drop_inode = generic_delete_inode,
1398 .show_options = cgroup_show_options,
1399 .remount_fs = cgroup_remount,
1402 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1404 INIT_LIST_HEAD(&cgrp->sibling);
1405 INIT_LIST_HEAD(&cgrp->children);
1406 INIT_LIST_HEAD(&cgrp->files);
1407 INIT_LIST_HEAD(&cgrp->cset_links);
1408 INIT_LIST_HEAD(&cgrp->release_list);
1409 INIT_LIST_HEAD(&cgrp->pidlists);
1410 mutex_init(&cgrp->pidlist_mutex);
1411 INIT_LIST_HEAD(&cgrp->event_list);
1412 spin_lock_init(&cgrp->event_list_lock);
1413 simple_xattrs_init(&cgrp->xattrs);
1416 static void init_cgroup_root(struct cgroupfs_root *root)
1418 struct cgroup *cgrp = &root->top_cgroup;
1420 INIT_LIST_HEAD(&root->subsys_list);
1421 INIT_LIST_HEAD(&root->root_list);
1422 root->number_of_cgroups = 1;
1424 RCU_INIT_POINTER(cgrp->name, &root_cgroup_name);
1425 init_cgroup_housekeeping(cgrp);
1428 static int cgroup_init_root_id(struct cgroupfs_root *root, int start, int end)
1432 lockdep_assert_held(&cgroup_mutex);
1433 lockdep_assert_held(&cgroup_root_mutex);
1435 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, start, end,
1440 root->hierarchy_id = id;
1444 static void cgroup_exit_root_id(struct cgroupfs_root *root)
1446 lockdep_assert_held(&cgroup_mutex);
1447 lockdep_assert_held(&cgroup_root_mutex);
1449 if (root->hierarchy_id) {
1450 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1451 root->hierarchy_id = 0;
1455 static int cgroup_test_super(struct super_block *sb, void *data)
1457 struct cgroup_sb_opts *opts = data;
1458 struct cgroupfs_root *root = sb->s_fs_info;
1460 /* If we asked for a name then it must match */
1461 if (opts->name && strcmp(opts->name, root->name))
1465 * If we asked for subsystems (or explicitly for no
1466 * subsystems) then they must match
1468 if ((opts->subsys_mask || opts->none)
1469 && (opts->subsys_mask != root->subsys_mask))
1475 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1477 struct cgroupfs_root *root;
1479 if (!opts->subsys_mask && !opts->none)
1482 root = kzalloc(sizeof(*root), GFP_KERNEL);
1484 return ERR_PTR(-ENOMEM);
1486 init_cgroup_root(root);
1489 * We need to set @root->subsys_mask now so that @root can be
1490 * matched by cgroup_test_super() before it finishes
1491 * initialization; otherwise, competing mounts with the same
1492 * options may try to bind the same subsystems instead of waiting
1493 * for the first one leading to unexpected mount errors.
1494 * SUBSYS_BOUND will be set once actual binding is complete.
1496 root->subsys_mask = opts->subsys_mask;
1497 root->flags = opts->flags;
1498 ida_init(&root->cgroup_ida);
1499 if (opts->release_agent)
1500 strcpy(root->release_agent_path, opts->release_agent);
1502 strcpy(root->name, opts->name);
1503 if (opts->cpuset_clone_children)
1504 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1508 static void cgroup_free_root(struct cgroupfs_root *root)
1511 /* hierarhcy ID shoulid already have been released */
1512 WARN_ON_ONCE(root->hierarchy_id);
1514 ida_destroy(&root->cgroup_ida);
1519 static int cgroup_set_super(struct super_block *sb, void *data)
1522 struct cgroup_sb_opts *opts = data;
1524 /* If we don't have a new root, we can't set up a new sb */
1525 if (!opts->new_root)
1528 BUG_ON(!opts->subsys_mask && !opts->none);
1530 ret = set_anon_super(sb, NULL);
1534 sb->s_fs_info = opts->new_root;
1535 opts->new_root->sb = sb;
1537 sb->s_blocksize = PAGE_CACHE_SIZE;
1538 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1539 sb->s_magic = CGROUP_SUPER_MAGIC;
1540 sb->s_op = &cgroup_ops;
1545 static int cgroup_get_rootdir(struct super_block *sb)
1547 static const struct dentry_operations cgroup_dops = {
1548 .d_iput = cgroup_diput,
1549 .d_delete = cgroup_delete,
1552 struct inode *inode =
1553 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1558 inode->i_fop = &simple_dir_operations;
1559 inode->i_op = &cgroup_dir_inode_operations;
1560 /* directories start off with i_nlink == 2 (for "." entry) */
1562 sb->s_root = d_make_root(inode);
1565 /* for everything else we want ->d_op set */
1566 sb->s_d_op = &cgroup_dops;
1570 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1571 int flags, const char *unused_dev_name,
1574 struct cgroup_sb_opts opts;
1575 struct cgroupfs_root *root;
1577 struct super_block *sb;
1578 struct cgroupfs_root *new_root;
1579 struct inode *inode;
1581 /* First find the desired set of subsystems */
1582 mutex_lock(&cgroup_mutex);
1583 ret = parse_cgroupfs_options(data, &opts);
1584 mutex_unlock(&cgroup_mutex);
1589 * Allocate a new cgroup root. We may not need it if we're
1590 * reusing an existing hierarchy.
1592 new_root = cgroup_root_from_opts(&opts);
1593 if (IS_ERR(new_root)) {
1594 ret = PTR_ERR(new_root);
1597 opts.new_root = new_root;
1599 /* Locate an existing or new sb for this hierarchy */
1600 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1603 cgroup_free_root(opts.new_root);
1607 root = sb->s_fs_info;
1609 if (root == opts.new_root) {
1610 /* We used the new root structure, so this is a new hierarchy */
1611 struct list_head tmp_links;
1612 struct cgroup *root_cgrp = &root->top_cgroup;
1613 struct cgroupfs_root *existing_root;
1614 const struct cred *cred;
1616 struct css_set *cset;
1618 BUG_ON(sb->s_root != NULL);
1620 ret = cgroup_get_rootdir(sb);
1622 goto drop_new_super;
1623 inode = sb->s_root->d_inode;
1625 mutex_lock(&inode->i_mutex);
1626 mutex_lock(&cgroup_mutex);
1627 mutex_lock(&cgroup_root_mutex);
1629 /* Check for name clashes with existing mounts */
1631 if (strlen(root->name))
1632 for_each_active_root(existing_root)
1633 if (!strcmp(existing_root->name, root->name))
1637 * We're accessing css_set_count without locking
1638 * css_set_lock here, but that's OK - it can only be
1639 * increased by someone holding cgroup_lock, and
1640 * that's us. The worst that can happen is that we
1641 * have some link structures left over
1643 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1647 /* ID 0 is reserved for dummy root, 1 for unified hierarchy */
1648 ret = cgroup_init_root_id(root, 2, 0);
1652 ret = rebind_subsystems(root, root->subsys_mask, 0);
1653 if (ret == -EBUSY) {
1654 free_cgrp_cset_links(&tmp_links);
1658 * There must be no failure case after here, since rebinding
1659 * takes care of subsystems' refcounts, which are explicitly
1660 * dropped in the failure exit path.
1663 /* EBUSY should be the only error here */
1666 list_add(&root->root_list, &cgroup_roots);
1667 cgroup_root_count++;
1669 sb->s_root->d_fsdata = root_cgrp;
1670 root->top_cgroup.dentry = sb->s_root;
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 cred = override_creds(&init_cred);
1685 cgroup_addrm_files(root_cgrp, NULL, cgroup_base_files, true);
1686 cgroup_populate_dir(root_cgrp, root->subsys_mask);
1688 mutex_unlock(&cgroup_root_mutex);
1689 mutex_unlock(&cgroup_mutex);
1690 mutex_unlock(&inode->i_mutex);
1693 * We re-used an existing hierarchy - the new root (if
1694 * any) is not needed
1696 cgroup_free_root(opts.new_root);
1698 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1699 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1700 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1702 goto drop_new_super;
1704 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1708 /* no subsys rebinding, so refcounts don't change */
1709 drop_parsed_module_refcounts(opts.subsys_mask);
1712 kfree(opts.release_agent);
1714 return dget(sb->s_root);
1717 cgroup_exit_root_id(root);
1718 mutex_unlock(&cgroup_root_mutex);
1719 mutex_unlock(&cgroup_mutex);
1720 mutex_unlock(&inode->i_mutex);
1722 deactivate_locked_super(sb);
1724 drop_parsed_module_refcounts(opts.subsys_mask);
1726 kfree(opts.release_agent);
1728 return ERR_PTR(ret);
1731 static void cgroup_kill_sb(struct super_block *sb) {
1732 struct cgroupfs_root *root = sb->s_fs_info;
1733 struct cgroup *cgrp = &root->top_cgroup;
1734 struct cgrp_cset_link *link, *tmp_link;
1739 BUG_ON(root->number_of_cgroups != 1);
1740 BUG_ON(!list_empty(&cgrp->children));
1742 mutex_lock(&cgroup_mutex);
1743 mutex_lock(&cgroup_root_mutex);
1745 /* Rebind all subsystems back to the default hierarchy */
1746 if (root->flags & CGRP_ROOT_SUBSYS_BOUND) {
1747 ret = rebind_subsystems(root, 0, root->subsys_mask);
1748 /* Shouldn't be able to fail ... */
1753 * Release all the links from cset_links to this hierarchy's
1756 write_lock(&css_set_lock);
1758 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1759 list_del(&link->cset_link);
1760 list_del(&link->cgrp_link);
1763 write_unlock(&css_set_lock);
1765 if (!list_empty(&root->root_list)) {
1766 list_del(&root->root_list);
1767 cgroup_root_count--;
1770 cgroup_exit_root_id(root);
1772 mutex_unlock(&cgroup_root_mutex);
1773 mutex_unlock(&cgroup_mutex);
1775 simple_xattrs_free(&cgrp->xattrs);
1777 kill_litter_super(sb);
1778 cgroup_free_root(root);
1781 static struct file_system_type cgroup_fs_type = {
1783 .mount = cgroup_mount,
1784 .kill_sb = cgroup_kill_sb,
1787 static struct kobject *cgroup_kobj;
1790 * cgroup_path - generate the path of a cgroup
1791 * @cgrp: the cgroup in question
1792 * @buf: the buffer to write the path into
1793 * @buflen: the length of the buffer
1795 * Writes path of cgroup into buf. Returns 0 on success, -errno on error.
1797 * We can't generate cgroup path using dentry->d_name, as accessing
1798 * dentry->name must be protected by irq-unsafe dentry->d_lock or parent
1799 * inode's i_mutex, while on the other hand cgroup_path() can be called
1800 * with some irq-safe spinlocks held.
1802 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1804 int ret = -ENAMETOOLONG;
1807 if (!cgrp->parent) {
1808 if (strlcpy(buf, "/", buflen) >= buflen)
1809 return -ENAMETOOLONG;
1813 start = buf + buflen - 1;
1818 const char *name = cgroup_name(cgrp);
1822 if ((start -= len) < buf)
1824 memcpy(start, name, len);
1830 cgrp = cgrp->parent;
1831 } while (cgrp->parent);
1833 memmove(buf, start, buf + buflen - start);
1838 EXPORT_SYMBOL_GPL(cgroup_path);
1841 * task_cgroup_path_from_hierarchy - cgroup path of a task on a hierarchy
1842 * @task: target task
1843 * @hierarchy_id: the hierarchy to look up @task's cgroup from
1844 * @buf: the buffer to write the path into
1845 * @buflen: the length of the buffer
1847 * Determine @task's cgroup on the hierarchy specified by @hierarchy_id and
1848 * copy its path into @buf. This function grabs cgroup_mutex and shouldn't
1849 * be used inside locks used by cgroup controller callbacks.
1851 int task_cgroup_path_from_hierarchy(struct task_struct *task, int hierarchy_id,
1852 char *buf, size_t buflen)
1854 struct cgroupfs_root *root;
1855 struct cgroup *cgrp = NULL;
1858 mutex_lock(&cgroup_mutex);
1860 root = idr_find(&cgroup_hierarchy_idr, hierarchy_id);
1862 cgrp = task_cgroup_from_root(task, root);
1863 ret = cgroup_path(cgrp, buf, buflen);
1866 mutex_unlock(&cgroup_mutex);
1870 EXPORT_SYMBOL_GPL(task_cgroup_path_from_hierarchy);
1873 * Control Group taskset
1875 struct task_and_cgroup {
1876 struct task_struct *task;
1877 struct cgroup *cgrp;
1881 struct cgroup_taskset {
1882 struct task_and_cgroup single;
1883 struct flex_array *tc_array;
1886 struct cgroup *cur_cgrp;
1890 * cgroup_taskset_first - reset taskset and return the first task
1891 * @tset: taskset of interest
1893 * @tset iteration is initialized and the first task is returned.
1895 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1897 if (tset->tc_array) {
1899 return cgroup_taskset_next(tset);
1901 tset->cur_cgrp = tset->single.cgrp;
1902 return tset->single.task;
1905 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1908 * cgroup_taskset_next - iterate to the next task in taskset
1909 * @tset: taskset of interest
1911 * Return the next task in @tset. Iteration must have been initialized
1912 * with cgroup_taskset_first().
1914 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1916 struct task_and_cgroup *tc;
1918 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1921 tc = flex_array_get(tset->tc_array, tset->idx++);
1922 tset->cur_cgrp = tc->cgrp;
1925 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1928 * cgroup_taskset_cur_cgroup - return the matching cgroup for the current task
1929 * @tset: taskset of interest
1931 * Return the cgroup for the current (last returned) task of @tset. This
1932 * function must be preceded by either cgroup_taskset_first() or
1933 * cgroup_taskset_next().
1935 struct cgroup *cgroup_taskset_cur_cgroup(struct cgroup_taskset *tset)
1937 return tset->cur_cgrp;
1939 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_cgroup);
1942 * cgroup_taskset_size - return the number of tasks in taskset
1943 * @tset: taskset of interest
1945 int cgroup_taskset_size(struct cgroup_taskset *tset)
1947 return tset->tc_array ? tset->tc_array_len : 1;
1949 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1953 * cgroup_task_migrate - move a task from one cgroup to another.
1955 * Must be called with cgroup_mutex and threadgroup locked.
1957 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1958 struct task_struct *tsk,
1959 struct css_set *new_cset)
1961 struct css_set *old_cset;
1964 * We are synchronized through threadgroup_lock() against PF_EXITING
1965 * setting such that we can't race against cgroup_exit() changing the
1966 * css_set to init_css_set and dropping the old one.
1968 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1969 old_cset = task_css_set(tsk);
1972 rcu_assign_pointer(tsk->cgroups, new_cset);
1975 /* Update the css_set linked lists if we're using them */
1976 write_lock(&css_set_lock);
1977 if (!list_empty(&tsk->cg_list))
1978 list_move(&tsk->cg_list, &new_cset->tasks);
1979 write_unlock(&css_set_lock);
1982 * We just gained a reference on old_cset by taking it from the
1983 * task. As trading it for new_cset is protected by cgroup_mutex,
1984 * we're safe to drop it here; it will be freed under RCU.
1986 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1987 put_css_set(old_cset);
1991 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1992 * @cgrp: the cgroup to attach to
1993 * @tsk: the task or the leader of the threadgroup to be attached
1994 * @threadgroup: attach the whole threadgroup?
1996 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
1997 * task_lock of @tsk or each thread in the threadgroup individually in turn.
1999 static int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk,
2002 int retval, i, group_size;
2003 struct cgroup_subsys *ss, *failed_ss = NULL;
2004 struct cgroupfs_root *root = cgrp->root;
2005 /* threadgroup list cursor and array */
2006 struct task_struct *leader = tsk;
2007 struct task_and_cgroup *tc;
2008 struct flex_array *group;
2009 struct cgroup_taskset tset = { };
2012 * step 0: in order to do expensive, possibly blocking operations for
2013 * every thread, we cannot iterate the thread group list, since it needs
2014 * rcu or tasklist locked. instead, build an array of all threads in the
2015 * group - group_rwsem prevents new threads from appearing, and if
2016 * threads exit, this will just be an over-estimate.
2019 group_size = get_nr_threads(tsk);
2022 /* flex_array supports very large thread-groups better than kmalloc. */
2023 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
2026 /* pre-allocate to guarantee space while iterating in rcu read-side. */
2027 retval = flex_array_prealloc(group, 0, group_size, GFP_KERNEL);
2029 goto out_free_group_list;
2033 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2034 * already PF_EXITING could be freed from underneath us unless we
2035 * take an rcu_read_lock.
2039 struct task_and_cgroup ent;
2041 /* @tsk either already exited or can't exit until the end */
2042 if (tsk->flags & PF_EXITING)
2045 /* as per above, nr_threads may decrease, but not increase. */
2046 BUG_ON(i >= group_size);
2048 ent.cgrp = task_cgroup_from_root(tsk, root);
2049 /* nothing to do if this task is already in the cgroup */
2050 if (ent.cgrp == cgrp)
2053 * saying GFP_ATOMIC has no effect here because we did prealloc
2054 * earlier, but it's good form to communicate our expectations.
2056 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
2057 BUG_ON(retval != 0);
2062 } while_each_thread(leader, tsk);
2064 /* remember the number of threads in the array for later. */
2066 tset.tc_array = group;
2067 tset.tc_array_len = group_size;
2069 /* methods shouldn't be called if no task is actually migrating */
2072 goto out_free_group_list;
2075 * step 1: check that we can legitimately attach to the cgroup.
2077 for_each_root_subsys(root, ss) {
2078 if (ss->can_attach) {
2079 retval = ss->can_attach(cgrp, &tset);
2082 goto out_cancel_attach;
2088 * step 2: make sure css_sets exist for all threads to be migrated.
2089 * we use find_css_set, which allocates a new one if necessary.
2091 for (i = 0; i < group_size; i++) {
2092 struct css_set *old_cset;
2094 tc = flex_array_get(group, i);
2095 old_cset = task_css_set(tc->task);
2096 tc->cg = find_css_set(old_cset, cgrp);
2099 goto out_put_css_set_refs;
2104 * step 3: now that we're guaranteed success wrt the css_sets,
2105 * proceed to move all tasks to the new cgroup. There are no
2106 * failure cases after here, so this is the commit point.
2108 for (i = 0; i < group_size; i++) {
2109 tc = flex_array_get(group, i);
2110 cgroup_task_migrate(tc->cgrp, tc->task, tc->cg);
2112 /* nothing is sensitive to fork() after this point. */
2115 * step 4: do subsystem attach callbacks.
2117 for_each_root_subsys(root, ss) {
2119 ss->attach(cgrp, &tset);
2123 * step 5: success! and cleanup
2126 out_put_css_set_refs:
2128 for (i = 0; i < group_size; i++) {
2129 tc = flex_array_get(group, i);
2132 put_css_set(tc->cg);
2137 for_each_root_subsys(root, ss) {
2138 if (ss == failed_ss)
2140 if (ss->cancel_attach)
2141 ss->cancel_attach(cgrp, &tset);
2144 out_free_group_list:
2145 flex_array_free(group);
2150 * Find the task_struct of the task to attach by vpid and pass it along to the
2151 * function to attach either it or all tasks in its threadgroup. Will lock
2152 * cgroup_mutex and threadgroup; may take task_lock of task.
2154 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2156 struct task_struct *tsk;
2157 const struct cred *cred = current_cred(), *tcred;
2160 if (!cgroup_lock_live_group(cgrp))
2166 tsk = find_task_by_vpid(pid);
2170 goto out_unlock_cgroup;
2173 * even if we're attaching all tasks in the thread group, we
2174 * only need to check permissions on one of them.
2176 tcred = __task_cred(tsk);
2177 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2178 !uid_eq(cred->euid, tcred->uid) &&
2179 !uid_eq(cred->euid, tcred->suid)) {
2182 goto out_unlock_cgroup;
2188 tsk = tsk->group_leader;
2191 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2192 * trapped in a cpuset, or RT worker may be born in a cgroup
2193 * with no rt_runtime allocated. Just say no.
2195 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2198 goto out_unlock_cgroup;
2201 get_task_struct(tsk);
2204 threadgroup_lock(tsk);
2206 if (!thread_group_leader(tsk)) {
2208 * a race with de_thread from another thread's exec()
2209 * may strip us of our leadership, if this happens,
2210 * there is no choice but to throw this task away and
2211 * try again; this is
2212 * "double-double-toil-and-trouble-check locking".
2214 threadgroup_unlock(tsk);
2215 put_task_struct(tsk);
2216 goto retry_find_task;
2220 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2222 threadgroup_unlock(tsk);
2224 put_task_struct(tsk);
2226 mutex_unlock(&cgroup_mutex);
2231 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2232 * @from: attach to all cgroups of a given task
2233 * @tsk: the task to be attached
2235 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2237 struct cgroupfs_root *root;
2240 mutex_lock(&cgroup_mutex);
2241 for_each_active_root(root) {
2242 struct cgroup *from_cg = task_cgroup_from_root(from, root);
2244 retval = cgroup_attach_task(from_cg, tsk, false);
2248 mutex_unlock(&cgroup_mutex);
2252 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2254 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
2256 return attach_task_by_pid(cgrp, pid, false);
2259 static int cgroup_procs_write(struct cgroup *cgrp, struct cftype *cft, u64 tgid)
2261 return attach_task_by_pid(cgrp, tgid, true);
2264 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
2267 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
2268 if (strlen(buffer) >= PATH_MAX)
2270 if (!cgroup_lock_live_group(cgrp))
2272 mutex_lock(&cgroup_root_mutex);
2273 strcpy(cgrp->root->release_agent_path, buffer);
2274 mutex_unlock(&cgroup_root_mutex);
2275 mutex_unlock(&cgroup_mutex);
2279 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
2280 struct seq_file *seq)
2282 if (!cgroup_lock_live_group(cgrp))
2284 seq_puts(seq, cgrp->root->release_agent_path);
2285 seq_putc(seq, '\n');
2286 mutex_unlock(&cgroup_mutex);
2290 static int cgroup_sane_behavior_show(struct cgroup *cgrp, struct cftype *cft,
2291 struct seq_file *seq)
2293 seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
2297 /* A buffer size big enough for numbers or short strings */
2298 #define CGROUP_LOCAL_BUFFER_SIZE 64
2300 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
2302 const char __user *userbuf,
2303 size_t nbytes, loff_t *unused_ppos)
2305 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
2311 if (nbytes >= sizeof(buffer))
2313 if (copy_from_user(buffer, userbuf, nbytes))
2316 buffer[nbytes] = 0; /* nul-terminate */
2317 if (cft->write_u64) {
2318 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
2321 retval = cft->write_u64(cgrp, cft, val);
2323 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
2326 retval = cft->write_s64(cgrp, cft, val);
2333 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
2335 const char __user *userbuf,
2336 size_t nbytes, loff_t *unused_ppos)
2338 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
2340 size_t max_bytes = cft->max_write_len;
2341 char *buffer = local_buffer;
2344 max_bytes = sizeof(local_buffer) - 1;
2345 if (nbytes >= max_bytes)
2347 /* Allocate a dynamic buffer if we need one */
2348 if (nbytes >= sizeof(local_buffer)) {
2349 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2353 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2358 buffer[nbytes] = 0; /* nul-terminate */
2359 retval = cft->write_string(cgrp, cft, strstrip(buffer));
2363 if (buffer != local_buffer)
2368 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2369 size_t nbytes, loff_t *ppos)
2371 struct cftype *cft = __d_cft(file->f_dentry);
2372 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2374 if (cgroup_is_dead(cgrp))
2377 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
2378 if (cft->write_u64 || cft->write_s64)
2379 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
2380 if (cft->write_string)
2381 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
2383 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
2384 return ret ? ret : nbytes;
2389 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
2391 char __user *buf, size_t nbytes,
2394 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2395 u64 val = cft->read_u64(cgrp, cft);
2396 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2398 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2401 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
2403 char __user *buf, size_t nbytes,
2406 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2407 s64 val = cft->read_s64(cgrp, cft);
2408 int len = sprintf(tmp, "%lld\n", (long long) val);
2410 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2413 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2414 size_t nbytes, loff_t *ppos)
2416 struct cftype *cft = __d_cft(file->f_dentry);
2417 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2419 if (cgroup_is_dead(cgrp))
2423 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
2425 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
2427 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
2432 * seqfile ops/methods for returning structured data. Currently just
2433 * supports string->u64 maps, but can be extended in future.
2436 struct cgroup_seqfile_state {
2438 struct cgroup *cgroup;
2441 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2443 struct seq_file *sf = cb->state;
2444 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2447 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2449 struct cgroup_seqfile_state *state = m->private;
2450 struct cftype *cft = state->cft;
2451 if (cft->read_map) {
2452 struct cgroup_map_cb cb = {
2453 .fill = cgroup_map_add,
2456 return cft->read_map(state->cgroup, cft, &cb);
2458 return cft->read_seq_string(state->cgroup, cft, m);
2461 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
2463 struct seq_file *seq = file->private_data;
2464 kfree(seq->private);
2465 return single_release(inode, file);
2468 static const struct file_operations cgroup_seqfile_operations = {
2470 .write = cgroup_file_write,
2471 .llseek = seq_lseek,
2472 .release = cgroup_seqfile_release,
2475 static int cgroup_file_open(struct inode *inode, struct file *file)
2480 err = generic_file_open(inode, file);
2483 cft = __d_cft(file->f_dentry);
2485 if (cft->read_map || cft->read_seq_string) {
2486 struct cgroup_seqfile_state *state;
2488 state = kzalloc(sizeof(*state), GFP_USER);
2493 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
2494 file->f_op = &cgroup_seqfile_operations;
2495 err = single_open(file, cgroup_seqfile_show, state);
2498 } else if (cft->open)
2499 err = cft->open(inode, file);
2506 static int cgroup_file_release(struct inode *inode, struct file *file)
2508 struct cftype *cft = __d_cft(file->f_dentry);
2510 return cft->release(inode, file);
2515 * cgroup_rename - Only allow simple rename of directories in place.
2517 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2518 struct inode *new_dir, struct dentry *new_dentry)
2521 struct cgroup_name *name, *old_name;
2522 struct cgroup *cgrp;
2525 * It's convinient to use parent dir's i_mutex to protected
2528 lockdep_assert_held(&old_dir->i_mutex);
2530 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2532 if (new_dentry->d_inode)
2534 if (old_dir != new_dir)
2537 cgrp = __d_cgrp(old_dentry);
2540 * This isn't a proper migration and its usefulness is very
2541 * limited. Disallow if sane_behavior.
2543 if (cgroup_sane_behavior(cgrp))
2546 name = cgroup_alloc_name(new_dentry);
2550 ret = simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2556 old_name = rcu_dereference_protected(cgrp->name, true);
2557 rcu_assign_pointer(cgrp->name, name);
2559 kfree_rcu(old_name, rcu_head);
2563 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2565 if (S_ISDIR(dentry->d_inode->i_mode))
2566 return &__d_cgrp(dentry)->xattrs;
2568 return &__d_cfe(dentry)->xattrs;
2571 static inline int xattr_enabled(struct dentry *dentry)
2573 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2574 return root->flags & CGRP_ROOT_XATTR;
2577 static bool is_valid_xattr(const char *name)
2579 if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2580 !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2585 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2586 const void *val, size_t size, int flags)
2588 if (!xattr_enabled(dentry))
2590 if (!is_valid_xattr(name))
2592 return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2595 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2597 if (!xattr_enabled(dentry))
2599 if (!is_valid_xattr(name))
2601 return simple_xattr_remove(__d_xattrs(dentry), name);
2604 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2605 void *buf, size_t size)
2607 if (!xattr_enabled(dentry))
2609 if (!is_valid_xattr(name))
2611 return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2614 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2616 if (!xattr_enabled(dentry))
2618 return simple_xattr_list(__d_xattrs(dentry), buf, size);
2621 static const struct file_operations cgroup_file_operations = {
2622 .read = cgroup_file_read,
2623 .write = cgroup_file_write,
2624 .llseek = generic_file_llseek,
2625 .open = cgroup_file_open,
2626 .release = cgroup_file_release,
2629 static const struct inode_operations cgroup_file_inode_operations = {
2630 .setxattr = cgroup_setxattr,
2631 .getxattr = cgroup_getxattr,
2632 .listxattr = cgroup_listxattr,
2633 .removexattr = cgroup_removexattr,
2636 static const struct inode_operations cgroup_dir_inode_operations = {
2637 .lookup = cgroup_lookup,
2638 .mkdir = cgroup_mkdir,
2639 .rmdir = cgroup_rmdir,
2640 .rename = cgroup_rename,
2641 .setxattr = cgroup_setxattr,
2642 .getxattr = cgroup_getxattr,
2643 .listxattr = cgroup_listxattr,
2644 .removexattr = cgroup_removexattr,
2647 static struct dentry *cgroup_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
2649 if (dentry->d_name.len > NAME_MAX)
2650 return ERR_PTR(-ENAMETOOLONG);
2651 d_add(dentry, NULL);
2656 * Check if a file is a control file
2658 static inline struct cftype *__file_cft(struct file *file)
2660 if (file_inode(file)->i_fop != &cgroup_file_operations)
2661 return ERR_PTR(-EINVAL);
2662 return __d_cft(file->f_dentry);
2665 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2666 struct super_block *sb)
2668 struct inode *inode;
2672 if (dentry->d_inode)
2675 inode = cgroup_new_inode(mode, sb);
2679 if (S_ISDIR(mode)) {
2680 inode->i_op = &cgroup_dir_inode_operations;
2681 inode->i_fop = &simple_dir_operations;
2683 /* start off with i_nlink == 2 (for "." entry) */
2685 inc_nlink(dentry->d_parent->d_inode);
2688 * Control reaches here with cgroup_mutex held.
2689 * @inode->i_mutex should nest outside cgroup_mutex but we
2690 * want to populate it immediately without releasing
2691 * cgroup_mutex. As @inode isn't visible to anyone else
2692 * yet, trylock will always succeed without affecting
2695 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2696 } else if (S_ISREG(mode)) {
2698 inode->i_fop = &cgroup_file_operations;
2699 inode->i_op = &cgroup_file_inode_operations;
2701 d_instantiate(dentry, inode);
2702 dget(dentry); /* Extra count - pin the dentry in core */
2707 * cgroup_file_mode - deduce file mode of a control file
2708 * @cft: the control file in question
2710 * returns cft->mode if ->mode is not 0
2711 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2712 * returns S_IRUGO if it has only a read handler
2713 * returns S_IWUSR if it has only a write hander
2715 static umode_t cgroup_file_mode(const struct cftype *cft)
2722 if (cft->read || cft->read_u64 || cft->read_s64 ||
2723 cft->read_map || cft->read_seq_string)
2726 if (cft->write || cft->write_u64 || cft->write_s64 ||
2727 cft->write_string || cft->trigger)
2733 static int cgroup_add_file(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2736 struct dentry *dir = cgrp->dentry;
2737 struct cgroup *parent = __d_cgrp(dir);
2738 struct dentry *dentry;
2742 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2744 if (subsys && !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
2745 strcpy(name, subsys->name);
2748 strcat(name, cft->name);
2750 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2752 cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2756 dentry = lookup_one_len(name, dir, strlen(name));
2757 if (IS_ERR(dentry)) {
2758 error = PTR_ERR(dentry);
2762 cfe->type = (void *)cft;
2763 cfe->dentry = dentry;
2764 dentry->d_fsdata = cfe;
2765 simple_xattrs_init(&cfe->xattrs);
2767 mode = cgroup_file_mode(cft);
2768 error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2770 list_add_tail(&cfe->node, &parent->files);
2780 * cgroup_addrm_files - add or remove files to a cgroup directory
2781 * @cgrp: the target cgroup
2782 * @subsys: the subsystem of files to be added
2783 * @cfts: array of cftypes to be added
2784 * @is_add: whether to add or remove
2786 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2787 * All @cfts should belong to @subsys. For removals, this function never
2788 * fails. If addition fails, this function doesn't remove files already
2789 * added. The caller is responsible for cleaning up.
2791 static int cgroup_addrm_files(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2792 struct cftype cfts[], bool is_add)
2797 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
2798 lockdep_assert_held(&cgroup_mutex);
2800 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2801 /* does cft->flags tell us to skip this file on @cgrp? */
2802 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2804 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2806 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2810 ret = cgroup_add_file(cgrp, subsys, cft);
2812 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2817 cgroup_rm_file(cgrp, cft);
2823 static void cgroup_cfts_prepare(void)
2824 __acquires(&cgroup_mutex)
2827 * Thanks to the entanglement with vfs inode locking, we can't walk
2828 * the existing cgroups under cgroup_mutex and create files.
2829 * Instead, we use cgroup_for_each_descendant_pre() and drop RCU
2830 * read lock before calling cgroup_addrm_files().
2832 mutex_lock(&cgroup_mutex);
2835 static int cgroup_cfts_commit(struct cgroup_subsys *ss,
2836 struct cftype *cfts, bool is_add)
2837 __releases(&cgroup_mutex)
2840 struct cgroup *cgrp, *root = &ss->root->top_cgroup;
2841 struct super_block *sb = ss->root->sb;
2842 struct dentry *prev = NULL;
2843 struct inode *inode;
2847 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2848 if (!cfts || ss->root == &cgroup_dummy_root ||
2849 !atomic_inc_not_zero(&sb->s_active)) {
2850 mutex_unlock(&cgroup_mutex);
2855 * All cgroups which are created after we drop cgroup_mutex will
2856 * have the updated set of files, so we only need to update the
2857 * cgroups created before the current @cgroup_serial_nr_next.
2859 update_before = cgroup_serial_nr_next;
2861 mutex_unlock(&cgroup_mutex);
2863 /* @root always needs to be updated */
2864 inode = root->dentry->d_inode;
2865 mutex_lock(&inode->i_mutex);
2866 mutex_lock(&cgroup_mutex);
2867 ret = cgroup_addrm_files(root, ss, cfts, is_add);
2868 mutex_unlock(&cgroup_mutex);
2869 mutex_unlock(&inode->i_mutex);
2874 /* add/rm files for all cgroups created before */
2876 cgroup_for_each_descendant_pre(cgrp, root) {
2877 if (cgroup_is_dead(cgrp))
2880 inode = cgrp->dentry->d_inode;
2885 prev = cgrp->dentry;
2887 mutex_lock(&inode->i_mutex);
2888 mutex_lock(&cgroup_mutex);
2889 if (cgrp->serial_nr < update_before && !cgroup_is_dead(cgrp))
2890 ret = cgroup_addrm_files(cgrp, ss, cfts, is_add);
2891 mutex_unlock(&cgroup_mutex);
2892 mutex_unlock(&inode->i_mutex);
2901 deactivate_super(sb);
2906 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2907 * @ss: target cgroup subsystem
2908 * @cfts: zero-length name terminated array of cftypes
2910 * Register @cfts to @ss. Files described by @cfts are created for all
2911 * existing cgroups to which @ss is attached and all future cgroups will
2912 * have them too. This function can be called anytime whether @ss is
2915 * Returns 0 on successful registration, -errno on failure. Note that this
2916 * function currently returns 0 as long as @cfts registration is successful
2917 * even if some file creation attempts on existing cgroups fail.
2919 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2921 struct cftype_set *set;
2924 set = kzalloc(sizeof(*set), GFP_KERNEL);
2928 cgroup_cfts_prepare();
2930 list_add_tail(&set->node, &ss->cftsets);
2931 ret = cgroup_cfts_commit(ss, cfts, true);
2933 cgroup_rm_cftypes(ss, cfts);
2936 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2939 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2940 * @ss: target cgroup subsystem
2941 * @cfts: zero-length name terminated array of cftypes
2943 * Unregister @cfts from @ss. Files described by @cfts are removed from
2944 * all existing cgroups to which @ss is attached and all future cgroups
2945 * won't have them either. This function can be called anytime whether @ss
2946 * is attached or not.
2948 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2949 * registered with @ss.
2951 int cgroup_rm_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2953 struct cftype_set *set;
2955 cgroup_cfts_prepare();
2957 list_for_each_entry(set, &ss->cftsets, node) {
2958 if (set->cfts == cfts) {
2959 list_del(&set->node);
2961 cgroup_cfts_commit(ss, cfts, false);
2966 cgroup_cfts_commit(ss, NULL, false);
2971 * cgroup_task_count - count the number of tasks in a cgroup.
2972 * @cgrp: the cgroup in question
2974 * Return the number of tasks in the cgroup.
2976 int cgroup_task_count(const struct cgroup *cgrp)
2979 struct cgrp_cset_link *link;
2981 read_lock(&css_set_lock);
2982 list_for_each_entry(link, &cgrp->cset_links, cset_link)
2983 count += atomic_read(&link->cset->refcount);
2984 read_unlock(&css_set_lock);
2989 * Advance a list_head iterator. The iterator should be positioned at
2990 * the start of a css_set
2992 static void cgroup_advance_iter(struct cgroup *cgrp, struct cgroup_iter *it)
2994 struct list_head *l = it->cset_link;
2995 struct cgrp_cset_link *link;
2996 struct css_set *cset;
2998 /* Advance to the next non-empty css_set */
3001 if (l == &cgrp->cset_links) {
3002 it->cset_link = NULL;
3005 link = list_entry(l, struct cgrp_cset_link, cset_link);
3007 } while (list_empty(&cset->tasks));
3009 it->task = cset->tasks.next;
3013 * To reduce the fork() overhead for systems that are not actually
3014 * using their cgroups capability, we don't maintain the lists running
3015 * through each css_set to its tasks until we see the list actually
3016 * used - in other words after the first call to cgroup_iter_start().
3018 static void cgroup_enable_task_cg_lists(void)
3020 struct task_struct *p, *g;
3021 write_lock(&css_set_lock);
3022 use_task_css_set_links = 1;
3024 * We need tasklist_lock because RCU is not safe against
3025 * while_each_thread(). Besides, a forking task that has passed
3026 * cgroup_post_fork() without seeing use_task_css_set_links = 1
3027 * is not guaranteed to have its child immediately visible in the
3028 * tasklist if we walk through it with RCU.
3030 read_lock(&tasklist_lock);
3031 do_each_thread(g, p) {
3034 * We should check if the process is exiting, otherwise
3035 * it will race with cgroup_exit() in that the list
3036 * entry won't be deleted though the process has exited.
3038 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
3039 list_add(&p->cg_list, &task_css_set(p)->tasks);
3041 } while_each_thread(g, p);
3042 read_unlock(&tasklist_lock);
3043 write_unlock(&css_set_lock);
3047 * cgroup_next_sibling - find the next sibling of a given cgroup
3048 * @pos: the current cgroup
3050 * This function returns the next sibling of @pos and should be called
3051 * under RCU read lock. The only requirement is that @pos is accessible.
3052 * The next sibling is guaranteed to be returned regardless of @pos's
3055 struct cgroup *cgroup_next_sibling(struct cgroup *pos)
3057 struct cgroup *next;
3059 WARN_ON_ONCE(!rcu_read_lock_held());
3062 * @pos could already have been removed. Once a cgroup is removed,
3063 * its ->sibling.next is no longer updated when its next sibling
3064 * changes. As CGRP_DEAD assertion is serialized and happens
3065 * before the cgroup is taken off the ->sibling list, if we see it
3066 * unasserted, it's guaranteed that the next sibling hasn't
3067 * finished its grace period even if it's already removed, and thus
3068 * safe to dereference from this RCU critical section. If
3069 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
3070 * to be visible as %true here.
3072 if (likely(!cgroup_is_dead(pos))) {
3073 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3074 if (&next->sibling != &pos->parent->children)
3080 * Can't dereference the next pointer. Each cgroup is given a
3081 * monotonically increasing unique serial number and always
3082 * appended to the sibling list, so the next one can be found by
3083 * walking the parent's children until we see a cgroup with higher
3084 * serial number than @pos's.
3086 * While this path can be slow, it's taken only when either the
3087 * current cgroup is removed or iteration and removal race.
3089 list_for_each_entry_rcu(next, &pos->parent->children, sibling)
3090 if (next->serial_nr > pos->serial_nr)
3094 EXPORT_SYMBOL_GPL(cgroup_next_sibling);
3097 * cgroup_next_descendant_pre - find the next descendant for pre-order walk
3098 * @pos: the current position (%NULL to initiate traversal)
3099 * @cgroup: cgroup whose descendants to walk
3101 * To be used by cgroup_for_each_descendant_pre(). Find the next
3102 * descendant to visit for pre-order traversal of @cgroup's descendants.
3104 * While this function requires RCU read locking, it doesn't require the
3105 * whole traversal to be contained in a single RCU critical section. This
3106 * function will return the correct next descendant as long as both @pos
3107 * and @cgroup are accessible and @pos is a descendant of @cgroup.
3109 struct cgroup *cgroup_next_descendant_pre(struct cgroup *pos,
3110 struct cgroup *cgroup)
3112 struct cgroup *next;
3114 WARN_ON_ONCE(!rcu_read_lock_held());
3116 /* if first iteration, pretend we just visited @cgroup */
3120 /* visit the first child if exists */
3121 next = list_first_or_null_rcu(&pos->children, struct cgroup, sibling);
3125 /* no child, visit my or the closest ancestor's next sibling */
3126 while (pos != cgroup) {
3127 next = cgroup_next_sibling(pos);
3135 EXPORT_SYMBOL_GPL(cgroup_next_descendant_pre);
3138 * cgroup_rightmost_descendant - return the rightmost descendant of a cgroup
3139 * @pos: cgroup of interest
3141 * Return the rightmost descendant of @pos. If there's no descendant,
3142 * @pos is returned. This can be used during pre-order traversal to skip
3145 * While this function requires RCU read locking, it doesn't require the
3146 * whole traversal to be contained in a single RCU critical section. This
3147 * function will return the correct rightmost descendant as long as @pos is
3150 struct cgroup *cgroup_rightmost_descendant(struct cgroup *pos)
3152 struct cgroup *last, *tmp;
3154 WARN_ON_ONCE(!rcu_read_lock_held());
3158 /* ->prev isn't RCU safe, walk ->next till the end */
3160 list_for_each_entry_rcu(tmp, &last->children, sibling)
3166 EXPORT_SYMBOL_GPL(cgroup_rightmost_descendant);
3168 static struct cgroup *cgroup_leftmost_descendant(struct cgroup *pos)
3170 struct cgroup *last;
3174 pos = list_first_or_null_rcu(&pos->children, struct cgroup,
3182 * cgroup_next_descendant_post - find the next descendant for post-order walk
3183 * @pos: the current position (%NULL to initiate traversal)
3184 * @cgroup: cgroup whose descendants to walk
3186 * To be used by cgroup_for_each_descendant_post(). Find the next
3187 * descendant to visit for post-order traversal of @cgroup's descendants.
3189 * While this function requires RCU read locking, it doesn't require the
3190 * whole traversal to be contained in a single RCU critical section. This
3191 * function will return the correct next descendant as long as both @pos
3192 * and @cgroup are accessible and @pos is a descendant of @cgroup.
3194 struct cgroup *cgroup_next_descendant_post(struct cgroup *pos,
3195 struct cgroup *cgroup)
3197 struct cgroup *next;
3199 WARN_ON_ONCE(!rcu_read_lock_held());
3201 /* if first iteration, visit the leftmost descendant */
3203 next = cgroup_leftmost_descendant(cgroup);
3204 return next != cgroup ? next : NULL;
3207 /* if there's an unvisited sibling, visit its leftmost descendant */
3208 next = cgroup_next_sibling(pos);
3210 return cgroup_leftmost_descendant(next);
3212 /* no sibling left, visit parent */
3214 return next != cgroup ? next : NULL;
3216 EXPORT_SYMBOL_GPL(cgroup_next_descendant_post);
3218 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
3219 __acquires(css_set_lock)
3222 * The first time anyone tries to iterate across a cgroup,
3223 * we need to enable the list linking each css_set to its
3224 * tasks, and fix up all existing tasks.
3226 if (!use_task_css_set_links)
3227 cgroup_enable_task_cg_lists();
3229 read_lock(&css_set_lock);
3230 it->cset_link = &cgrp->cset_links;
3231 cgroup_advance_iter(cgrp, it);
3234 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
3235 struct cgroup_iter *it)
3237 struct task_struct *res;
3238 struct list_head *l = it->task;
3239 struct cgrp_cset_link *link;
3241 /* If the iterator cg is NULL, we have no tasks */
3244 res = list_entry(l, struct task_struct, cg_list);
3245 /* Advance iterator to find next entry */
3247 link = list_entry(it->cset_link, struct cgrp_cset_link, cset_link);
3248 if (l == &link->cset->tasks) {
3249 /* We reached the end of this task list - move on to
3250 * the next cg_cgroup_link */
3251 cgroup_advance_iter(cgrp, it);
3258 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
3259 __releases(css_set_lock)
3261 read_unlock(&css_set_lock);
3264 static inline int started_after_time(struct task_struct *t1,
3265 struct timespec *time,
3266 struct task_struct *t2)
3268 int start_diff = timespec_compare(&t1->start_time, time);
3269 if (start_diff > 0) {
3271 } else if (start_diff < 0) {
3275 * Arbitrarily, if two processes started at the same
3276 * time, we'll say that the lower pointer value
3277 * started first. Note that t2 may have exited by now
3278 * so this may not be a valid pointer any longer, but
3279 * that's fine - it still serves to distinguish
3280 * between two tasks started (effectively) simultaneously.
3287 * This function is a callback from heap_insert() and is used to order
3289 * In this case we order the heap in descending task start time.
3291 static inline int started_after(void *p1, void *p2)
3293 struct task_struct *t1 = p1;
3294 struct task_struct *t2 = p2;
3295 return started_after_time(t1, &t2->start_time, t2);
3299 * cgroup_scan_tasks - iterate though all the tasks in a cgroup
3300 * @scan: struct cgroup_scanner containing arguments for the scan
3302 * Arguments include pointers to callback functions test_task() and
3304 * Iterate through all the tasks in a cgroup, calling test_task() for each,
3305 * and if it returns true, call process_task() for it also.
3306 * The test_task pointer may be NULL, meaning always true (select all tasks).
3307 * Effectively duplicates cgroup_iter_{start,next,end}()
3308 * but does not lock css_set_lock for the call to process_task().
3309 * The struct cgroup_scanner may be embedded in any structure of the caller's
3311 * It is guaranteed that process_task() will act on every task that
3312 * is a member of the cgroup for the duration of this call. This
3313 * function may or may not call process_task() for tasks that exit
3314 * or move to a different cgroup during the call, or are forked or
3315 * move into the cgroup during the call.
3317 * Note that test_task() may be called with locks held, and may in some
3318 * situations be called multiple times for the same task, so it should
3320 * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
3321 * pre-allocated and will be used for heap operations (and its "gt" member will
3322 * be overwritten), else a temporary heap will be used (allocation of which
3323 * may cause this function to fail).
3325 int cgroup_scan_tasks(struct cgroup_scanner *scan)
3328 struct cgroup_iter it;
3329 struct task_struct *p, *dropped;
3330 /* Never dereference latest_task, since it's not refcounted */
3331 struct task_struct *latest_task = NULL;
3332 struct ptr_heap tmp_heap;
3333 struct ptr_heap *heap;
3334 struct timespec latest_time = { 0, 0 };
3337 /* The caller supplied our heap and pre-allocated its memory */
3339 heap->gt = &started_after;
3341 /* We need to allocate our own heap memory */
3343 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3345 /* cannot allocate the heap */
3351 * Scan tasks in the cgroup, using the scanner's "test_task" callback
3352 * to determine which are of interest, and using the scanner's
3353 * "process_task" callback to process any of them that need an update.
3354 * Since we don't want to hold any locks during the task updates,
3355 * gather tasks to be processed in a heap structure.
3356 * The heap is sorted by descending task start time.
3357 * If the statically-sized heap fills up, we overflow tasks that
3358 * started later, and in future iterations only consider tasks that
3359 * started after the latest task in the previous pass. This
3360 * guarantees forward progress and that we don't miss any tasks.
3363 cgroup_iter_start(scan->cg, &it);
3364 while ((p = cgroup_iter_next(scan->cg, &it))) {
3366 * Only affect tasks that qualify per the caller's callback,
3367 * if he provided one
3369 if (scan->test_task && !scan->test_task(p, scan))
3372 * Only process tasks that started after the last task
3375 if (!started_after_time(p, &latest_time, latest_task))
3377 dropped = heap_insert(heap, p);
3378 if (dropped == NULL) {
3380 * The new task was inserted; the heap wasn't
3384 } else if (dropped != p) {
3386 * The new task was inserted, and pushed out a
3390 put_task_struct(dropped);
3393 * Else the new task was newer than anything already in
3394 * the heap and wasn't inserted
3397 cgroup_iter_end(scan->cg, &it);
3400 for (i = 0; i < heap->size; i++) {
3401 struct task_struct *q = heap->ptrs[i];
3403 latest_time = q->start_time;
3406 /* Process the task per the caller's callback */
3407 scan->process_task(q, scan);
3411 * If we had to process any tasks at all, scan again
3412 * in case some of them were in the middle of forking
3413 * children that didn't get processed.
3414 * Not the most efficient way to do it, but it avoids
3415 * having to take callback_mutex in the fork path
3419 if (heap == &tmp_heap)
3420 heap_free(&tmp_heap);
3424 static void cgroup_transfer_one_task(struct task_struct *task,
3425 struct cgroup_scanner *scan)
3427 struct cgroup *new_cgroup = scan->data;
3429 mutex_lock(&cgroup_mutex);
3430 cgroup_attach_task(new_cgroup, task, false);
3431 mutex_unlock(&cgroup_mutex);
3435 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3436 * @to: cgroup to which the tasks will be moved
3437 * @from: cgroup in which the tasks currently reside
3439 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3441 struct cgroup_scanner scan;
3444 scan.test_task = NULL; /* select all tasks in cgroup */
3445 scan.process_task = cgroup_transfer_one_task;
3449 return cgroup_scan_tasks(&scan);
3453 * Stuff for reading the 'tasks'/'procs' files.
3455 * Reading this file can return large amounts of data if a cgroup has
3456 * *lots* of attached tasks. So it may need several calls to read(),
3457 * but we cannot guarantee that the information we produce is correct
3458 * unless we produce it entirely atomically.
3462 /* which pidlist file are we talking about? */
3463 enum cgroup_filetype {
3469 * A pidlist is a list of pids that virtually represents the contents of one
3470 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3471 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3474 struct cgroup_pidlist {
3476 * used to find which pidlist is wanted. doesn't change as long as
3477 * this particular list stays in the list.
3479 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3482 /* how many elements the above list has */
3484 /* how many files are using the current array */
3486 /* each of these stored in a list by its cgroup */
3487 struct list_head links;
3488 /* pointer to the cgroup we belong to, for list removal purposes */
3489 struct cgroup *owner;
3490 /* protects the other fields */
3491 struct rw_semaphore mutex;
3495 * The following two functions "fix" the issue where there are more pids
3496 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3497 * TODO: replace with a kernel-wide solution to this problem
3499 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3500 static void *pidlist_allocate(int count)
3502 if (PIDLIST_TOO_LARGE(count))
3503 return vmalloc(count * sizeof(pid_t));
3505 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3507 static void pidlist_free(void *p)
3509 if (is_vmalloc_addr(p))
3516 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3517 * Returns the number of unique elements.
3519 static int pidlist_uniq(pid_t *list, int length)
3524 * we presume the 0th element is unique, so i starts at 1. trivial
3525 * edge cases first; no work needs to be done for either
3527 if (length == 0 || length == 1)
3529 /* src and dest walk down the list; dest counts unique elements */
3530 for (src = 1; src < length; src++) {
3531 /* find next unique element */
3532 while (list[src] == list[src-1]) {
3537 /* dest always points to where the next unique element goes */
3538 list[dest] = list[src];
3545 static int cmppid(const void *a, const void *b)
3547 return *(pid_t *)a - *(pid_t *)b;
3551 * find the appropriate pidlist for our purpose (given procs vs tasks)
3552 * returns with the lock on that pidlist already held, and takes care
3553 * of the use count, or returns NULL with no locks held if we're out of
3556 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3557 enum cgroup_filetype type)
3559 struct cgroup_pidlist *l;
3560 /* don't need task_nsproxy() if we're looking at ourself */
3561 struct pid_namespace *ns = task_active_pid_ns(current);
3564 * We can't drop the pidlist_mutex before taking the l->mutex in case
3565 * the last ref-holder is trying to remove l from the list at the same
3566 * time. Holding the pidlist_mutex precludes somebody taking whichever
3567 * list we find out from under us - compare release_pid_array().
3569 mutex_lock(&cgrp->pidlist_mutex);
3570 list_for_each_entry(l, &cgrp->pidlists, links) {
3571 if (l->key.type == type && l->key.ns == ns) {
3572 /* make sure l doesn't vanish out from under us */
3573 down_write(&l->mutex);
3574 mutex_unlock(&cgrp->pidlist_mutex);
3578 /* entry not found; create a new one */
3579 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3581 mutex_unlock(&cgrp->pidlist_mutex);
3584 init_rwsem(&l->mutex);
3585 down_write(&l->mutex);
3587 l->key.ns = get_pid_ns(ns);
3589 list_add(&l->links, &cgrp->pidlists);
3590 mutex_unlock(&cgrp->pidlist_mutex);
3595 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3597 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3598 struct cgroup_pidlist **lp)
3602 int pid, n = 0; /* used for populating the array */
3603 struct cgroup_iter it;
3604 struct task_struct *tsk;
3605 struct cgroup_pidlist *l;
3608 * If cgroup gets more users after we read count, we won't have
3609 * enough space - tough. This race is indistinguishable to the
3610 * caller from the case that the additional cgroup users didn't
3611 * show up until sometime later on.
3613 length = cgroup_task_count(cgrp);
3614 array = pidlist_allocate(length);
3617 /* now, populate the array */
3618 cgroup_iter_start(cgrp, &it);
3619 while ((tsk = cgroup_iter_next(cgrp, &it))) {
3620 if (unlikely(n == length))
3622 /* get tgid or pid for procs or tasks file respectively */
3623 if (type == CGROUP_FILE_PROCS)
3624 pid = task_tgid_vnr(tsk);
3626 pid = task_pid_vnr(tsk);
3627 if (pid > 0) /* make sure to only use valid results */
3630 cgroup_iter_end(cgrp, &it);
3632 /* now sort & (if procs) strip out duplicates */
3633 sort(array, length, sizeof(pid_t), cmppid, NULL);
3634 if (type == CGROUP_FILE_PROCS)
3635 length = pidlist_uniq(array, length);
3636 l = cgroup_pidlist_find(cgrp, type);
3638 pidlist_free(array);
3641 /* store array, freeing old if necessary - lock already held */
3642 pidlist_free(l->list);
3646 up_write(&l->mutex);
3652 * cgroupstats_build - build and fill cgroupstats
3653 * @stats: cgroupstats to fill information into
3654 * @dentry: A dentry entry belonging to the cgroup for which stats have
3657 * Build and fill cgroupstats so that taskstats can export it to user
3660 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3663 struct cgroup *cgrp;
3664 struct cgroup_iter it;
3665 struct task_struct *tsk;
3668 * Validate dentry by checking the superblock operations,
3669 * and make sure it's a directory.
3671 if (dentry->d_sb->s_op != &cgroup_ops ||
3672 !S_ISDIR(dentry->d_inode->i_mode))
3676 cgrp = dentry->d_fsdata;
3678 cgroup_iter_start(cgrp, &it);
3679 while ((tsk = cgroup_iter_next(cgrp, &it))) {
3680 switch (tsk->state) {
3682 stats->nr_running++;
3684 case TASK_INTERRUPTIBLE:
3685 stats->nr_sleeping++;
3687 case TASK_UNINTERRUPTIBLE:
3688 stats->nr_uninterruptible++;
3691 stats->nr_stopped++;
3694 if (delayacct_is_task_waiting_on_io(tsk))
3695 stats->nr_io_wait++;
3699 cgroup_iter_end(cgrp, &it);
3707 * seq_file methods for the tasks/procs files. The seq_file position is the
3708 * next pid to display; the seq_file iterator is a pointer to the pid
3709 * in the cgroup->l->list array.
3712 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3715 * Initially we receive a position value that corresponds to
3716 * one more than the last pid shown (or 0 on the first call or
3717 * after a seek to the start). Use a binary-search to find the
3718 * next pid to display, if any
3720 struct cgroup_pidlist *l = s->private;
3721 int index = 0, pid = *pos;
3724 down_read(&l->mutex);
3726 int end = l->length;
3728 while (index < end) {
3729 int mid = (index + end) / 2;
3730 if (l->list[mid] == pid) {
3733 } else if (l->list[mid] <= pid)
3739 /* If we're off the end of the array, we're done */
3740 if (index >= l->length)
3742 /* Update the abstract position to be the actual pid that we found */
3743 iter = l->list + index;
3748 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3750 struct cgroup_pidlist *l = s->private;
3754 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3756 struct cgroup_pidlist *l = s->private;
3758 pid_t *end = l->list + l->length;
3760 * Advance to the next pid in the array. If this goes off the
3772 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3774 return seq_printf(s, "%d\n", *(int *)v);
3778 * seq_operations functions for iterating on pidlists through seq_file -
3779 * independent of whether it's tasks or procs
3781 static const struct seq_operations cgroup_pidlist_seq_operations = {
3782 .start = cgroup_pidlist_start,
3783 .stop = cgroup_pidlist_stop,
3784 .next = cgroup_pidlist_next,
3785 .show = cgroup_pidlist_show,
3788 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
3791 * the case where we're the last user of this particular pidlist will
3792 * have us remove it from the cgroup's list, which entails taking the
3793 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3794 * pidlist_mutex, we have to take pidlist_mutex first.
3796 mutex_lock(&l->owner->pidlist_mutex);
3797 down_write(&l->mutex);
3798 BUG_ON(!l->use_count);
3799 if (!--l->use_count) {
3800 /* we're the last user if refcount is 0; remove and free */
3801 list_del(&l->links);
3802 mutex_unlock(&l->owner->pidlist_mutex);
3803 pidlist_free(l->list);
3804 put_pid_ns(l->key.ns);
3805 up_write(&l->mutex);
3809 mutex_unlock(&l->owner->pidlist_mutex);
3810 up_write(&l->mutex);
3813 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
3815 struct cgroup_pidlist *l;
3816 if (!(file->f_mode & FMODE_READ))
3819 * the seq_file will only be initialized if the file was opened for
3820 * reading; hence we check if it's not null only in that case.
3822 l = ((struct seq_file *)file->private_data)->private;
3823 cgroup_release_pid_array(l);
3824 return seq_release(inode, file);
3827 static const struct file_operations cgroup_pidlist_operations = {
3829 .llseek = seq_lseek,
3830 .write = cgroup_file_write,
3831 .release = cgroup_pidlist_release,
3835 * The following functions handle opens on a file that displays a pidlist
3836 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3839 /* helper function for the two below it */
3840 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
3842 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
3843 struct cgroup_pidlist *l;
3846 /* Nothing to do for write-only files */
3847 if (!(file->f_mode & FMODE_READ))
3850 /* have the array populated */
3851 retval = pidlist_array_load(cgrp, type, &l);
3854 /* configure file information */
3855 file->f_op = &cgroup_pidlist_operations;
3857 retval = seq_open(file, &cgroup_pidlist_seq_operations);
3859 cgroup_release_pid_array(l);
3862 ((struct seq_file *)file->private_data)->private = l;
3865 static int cgroup_tasks_open(struct inode *unused, struct file *file)
3867 return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
3869 static int cgroup_procs_open(struct inode *unused, struct file *file)
3871 return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
3874 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
3877 return notify_on_release(cgrp);
3880 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
3884 clear_bit(CGRP_RELEASABLE, &cgrp->flags);
3886 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3888 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3893 * When dput() is called asynchronously, if umount has been done and
3894 * then deactivate_super() in cgroup_free_fn() kills the superblock,
3895 * there's a small window that vfs will see the root dentry with non-zero
3896 * refcnt and trigger BUG().
3898 * That's why we hold a reference before dput() and drop it right after.
3900 static void cgroup_dput(struct cgroup *cgrp)
3902 struct super_block *sb = cgrp->root->sb;
3904 atomic_inc(&sb->s_active);
3906 deactivate_super(sb);
3910 * Unregister event and free resources.
3912 * Gets called from workqueue.
3914 static void cgroup_event_remove(struct work_struct *work)
3916 struct cgroup_event *event = container_of(work, struct cgroup_event,
3918 struct cgroup *cgrp = event->cgrp;
3920 remove_wait_queue(event->wqh, &event->wait);
3922 event->cft->unregister_event(cgrp, event->cft, event->eventfd);
3924 /* Notify userspace the event is going away. */
3925 eventfd_signal(event->eventfd, 1);
3927 eventfd_ctx_put(event->eventfd);
3933 * Gets called on POLLHUP on eventfd when user closes it.
3935 * Called with wqh->lock held and interrupts disabled.
3937 static int cgroup_event_wake(wait_queue_t *wait, unsigned mode,
3938 int sync, void *key)
3940 struct cgroup_event *event = container_of(wait,
3941 struct cgroup_event, wait);
3942 struct cgroup *cgrp = event->cgrp;
3943 unsigned long flags = (unsigned long)key;
3945 if (flags & POLLHUP) {
3947 * If the event has been detached at cgroup removal, we
3948 * can simply return knowing the other side will cleanup
3951 * We can't race against event freeing since the other
3952 * side will require wqh->lock via remove_wait_queue(),
3955 spin_lock(&cgrp->event_list_lock);
3956 if (!list_empty(&event->list)) {
3957 list_del_init(&event->list);
3959 * We are in atomic context, but cgroup_event_remove()
3960 * may sleep, so we have to call it in workqueue.
3962 schedule_work(&event->remove);
3964 spin_unlock(&cgrp->event_list_lock);
3970 static void cgroup_event_ptable_queue_proc(struct file *file,
3971 wait_queue_head_t *wqh, poll_table *pt)
3973 struct cgroup_event *event = container_of(pt,
3974 struct cgroup_event, pt);
3977 add_wait_queue(wqh, &event->wait);
3981 * Parse input and register new cgroup event handler.
3983 * Input must be in format '<event_fd> <control_fd> <args>'.
3984 * Interpretation of args is defined by control file implementation.
3986 static int cgroup_write_event_control(struct cgroup *cgrp, struct cftype *cft,
3989 struct cgroup_event *event = NULL;
3990 struct cgroup *cgrp_cfile;
3991 unsigned int efd, cfd;
3992 struct file *efile = NULL;
3993 struct file *cfile = NULL;
3997 efd = simple_strtoul(buffer, &endp, 10);
4002 cfd = simple_strtoul(buffer, &endp, 10);
4003 if ((*endp != ' ') && (*endp != '\0'))
4007 event = kzalloc(sizeof(*event), GFP_KERNEL);
4011 INIT_LIST_HEAD(&event->list);
4012 init_poll_funcptr(&event->pt, cgroup_event_ptable_queue_proc);
4013 init_waitqueue_func_entry(&event->wait, cgroup_event_wake);
4014 INIT_WORK(&event->remove, cgroup_event_remove);
4016 efile = eventfd_fget(efd);
4017 if (IS_ERR(efile)) {
4018 ret = PTR_ERR(efile);
4022 event->eventfd = eventfd_ctx_fileget(efile);
4023 if (IS_ERR(event->eventfd)) {
4024 ret = PTR_ERR(event->eventfd);
4034 /* the process need read permission on control file */
4035 /* AV: shouldn't we check that it's been opened for read instead? */
4036 ret = inode_permission(file_inode(cfile), MAY_READ);
4040 event->cft = __file_cft(cfile);
4041 if (IS_ERR(event->cft)) {
4042 ret = PTR_ERR(event->cft);
4047 * The file to be monitored must be in the same cgroup as
4048 * cgroup.event_control is.
4050 cgrp_cfile = __d_cgrp(cfile->f_dentry->d_parent);
4051 if (cgrp_cfile != cgrp) {
4056 if (!event->cft->register_event || !event->cft->unregister_event) {
4061 ret = event->cft->register_event(cgrp, event->cft,
4062 event->eventfd, buffer);
4066 efile->f_op->poll(efile, &event->pt);
4069 * Events should be removed after rmdir of cgroup directory, but before
4070 * destroying subsystem state objects. Let's take reference to cgroup
4071 * directory dentry to do that.
4075 spin_lock(&cgrp->event_list_lock);
4076 list_add(&event->list, &cgrp->event_list);
4077 spin_unlock(&cgrp->event_list_lock);
4088 if (event && event->eventfd && !IS_ERR(event->eventfd))
4089 eventfd_ctx_put(event->eventfd);
4091 if (!IS_ERR_OR_NULL(efile))
4099 static u64 cgroup_clone_children_read(struct cgroup *cgrp,
4102 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4105 static int cgroup_clone_children_write(struct cgroup *cgrp,
4110 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4112 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4116 static struct cftype cgroup_base_files[] = {
4118 .name = "cgroup.procs",
4119 .open = cgroup_procs_open,
4120 .write_u64 = cgroup_procs_write,
4121 .release = cgroup_pidlist_release,
4122 .mode = S_IRUGO | S_IWUSR,
4125 .name = "cgroup.event_control",
4126 .write_string = cgroup_write_event_control,
4130 .name = "cgroup.clone_children",
4131 .flags = CFTYPE_INSANE,
4132 .read_u64 = cgroup_clone_children_read,
4133 .write_u64 = cgroup_clone_children_write,
4136 .name = "cgroup.sane_behavior",
4137 .flags = CFTYPE_ONLY_ON_ROOT,
4138 .read_seq_string = cgroup_sane_behavior_show,
4142 * Historical crazy stuff. These don't have "cgroup." prefix and
4143 * don't exist if sane_behavior. If you're depending on these, be
4144 * prepared to be burned.
4148 .flags = CFTYPE_INSANE, /* use "procs" instead */
4149 .open = cgroup_tasks_open,
4150 .write_u64 = cgroup_tasks_write,
4151 .release = cgroup_pidlist_release,
4152 .mode = S_IRUGO | S_IWUSR,
4155 .name = "notify_on_release",
4156 .flags = CFTYPE_INSANE,
4157 .read_u64 = cgroup_read_notify_on_release,
4158 .write_u64 = cgroup_write_notify_on_release,
4161 .name = "release_agent",
4162 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
4163 .read_seq_string = cgroup_release_agent_show,
4164 .write_string = cgroup_release_agent_write,
4165 .max_write_len = PATH_MAX,
4171 * cgroup_populate_dir - create subsys files in a cgroup directory
4172 * @cgrp: target cgroup
4173 * @subsys_mask: mask of the subsystem ids whose files should be added
4175 * On failure, no file is added.
4177 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
4179 struct cgroup_subsys *ss;
4182 /* process cftsets of each subsystem */
4183 for_each_root_subsys(cgrp->root, ss) {
4184 struct cftype_set *set;
4185 if (!test_bit(ss->subsys_id, &subsys_mask))
4188 list_for_each_entry(set, &ss->cftsets, node) {
4189 ret = cgroup_addrm_files(cgrp, ss, set->cfts, true);
4195 /* This cgroup is ready now */
4196 for_each_root_subsys(cgrp->root, ss) {
4197 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4198 struct css_id *id = rcu_dereference_protected(css->id, true);
4201 * Update id->css pointer and make this css visible from
4202 * CSS ID functions. This pointer will be dereferened
4203 * from RCU-read-side without locks.
4206 rcu_assign_pointer(id->css, css);
4211 cgroup_clear_dir(cgrp, subsys_mask);
4215 static void css_dput_fn(struct work_struct *work)
4217 struct cgroup_subsys_state *css =
4218 container_of(work, struct cgroup_subsys_state, dput_work);
4220 cgroup_dput(css->cgroup);
4223 static void css_release(struct percpu_ref *ref)
4225 struct cgroup_subsys_state *css =
4226 container_of(ref, struct cgroup_subsys_state, refcnt);
4228 schedule_work(&css->dput_work);
4231 static void init_cgroup_css(struct cgroup_subsys_state *css,
4232 struct cgroup_subsys *ss,
4233 struct cgroup *cgrp)
4238 if (cgrp == cgroup_dummy_top)
4239 css->flags |= CSS_ROOT;
4240 BUG_ON(cgrp->subsys[ss->subsys_id]);
4241 cgrp->subsys[ss->subsys_id] = css;
4244 * css holds an extra ref to @cgrp->dentry which is put on the last
4245 * css_put(). dput() requires process context, which css_put() may
4246 * be called without. @css->dput_work will be used to invoke
4247 * dput() asynchronously from css_put().
4249 INIT_WORK(&css->dput_work, css_dput_fn);
4252 /* invoke ->post_create() on a new CSS and mark it online if successful */
4253 static int online_css(struct cgroup_subsys *ss, struct cgroup *cgrp)
4257 lockdep_assert_held(&cgroup_mutex);
4260 ret = ss->css_online(cgrp);
4262 cgrp->subsys[ss->subsys_id]->flags |= CSS_ONLINE;
4266 /* if the CSS is online, invoke ->pre_destory() on it and mark it offline */
4267 static void offline_css(struct cgroup_subsys *ss, struct cgroup *cgrp)
4268 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4270 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4272 lockdep_assert_held(&cgroup_mutex);
4274 if (!(css->flags & CSS_ONLINE))
4277 if (ss->css_offline)
4278 ss->css_offline(cgrp);
4280 cgrp->subsys[ss->subsys_id]->flags &= ~CSS_ONLINE;
4284 * cgroup_create - create a cgroup
4285 * @parent: cgroup that will be parent of the new cgroup
4286 * @dentry: dentry of the new cgroup
4287 * @mode: mode to set on new inode
4289 * Must be called with the mutex on the parent inode held
4291 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4294 struct cgroup *cgrp;
4295 struct cgroup_name *name;
4296 struct cgroupfs_root *root = parent->root;
4298 struct cgroup_subsys *ss;
4299 struct super_block *sb = root->sb;
4301 /* allocate the cgroup and its ID, 0 is reserved for the root */
4302 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4306 name = cgroup_alloc_name(dentry);
4309 rcu_assign_pointer(cgrp->name, name);
4311 cgrp->id = ida_simple_get(&root->cgroup_ida, 1, 0, GFP_KERNEL);
4316 * Only live parents can have children. Note that the liveliness
4317 * check isn't strictly necessary because cgroup_mkdir() and
4318 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4319 * anyway so that locking is contained inside cgroup proper and we
4320 * don't get nasty surprises if we ever grow another caller.
4322 if (!cgroup_lock_live_group(parent)) {
4327 /* Grab a reference on the superblock so the hierarchy doesn't
4328 * get deleted on unmount if there are child cgroups. This
4329 * can be done outside cgroup_mutex, since the sb can't
4330 * disappear while someone has an open control file on the
4332 atomic_inc(&sb->s_active);
4334 init_cgroup_housekeeping(cgrp);
4336 dentry->d_fsdata = cgrp;
4337 cgrp->dentry = dentry;
4339 cgrp->parent = parent;
4340 cgrp->root = parent->root;
4342 if (notify_on_release(parent))
4343 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4345 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4346 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4348 for_each_root_subsys(root, ss) {
4349 struct cgroup_subsys_state *css;
4351 css = ss->css_alloc(cgrp);
4357 err = percpu_ref_init(&css->refcnt, css_release);
4361 init_cgroup_css(css, ss, cgrp);
4364 err = alloc_css_id(ss, parent, cgrp);
4371 * Create directory. cgroup_create_file() returns with the new
4372 * directory locked on success so that it can be populated without
4373 * dropping cgroup_mutex.
4375 err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4378 lockdep_assert_held(&dentry->d_inode->i_mutex);
4380 cgrp->serial_nr = cgroup_serial_nr_next++;
4382 /* allocation complete, commit to creation */
4383 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4384 root->number_of_cgroups++;
4386 /* each css holds a ref to the cgroup's dentry */
4387 for_each_root_subsys(root, ss)
4390 /* hold a ref to the parent's dentry */
4391 dget(parent->dentry);
4393 /* creation succeeded, notify subsystems */
4394 for_each_root_subsys(root, ss) {
4395 err = online_css(ss, cgrp);
4399 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4401 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",
4402 current->comm, current->pid, ss->name);
4403 if (!strcmp(ss->name, "memory"))
4404 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4405 ss->warned_broken_hierarchy = true;
4409 err = cgroup_addrm_files(cgrp, NULL, cgroup_base_files, true);
4413 err = cgroup_populate_dir(cgrp, root->subsys_mask);
4417 mutex_unlock(&cgroup_mutex);
4418 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4423 for_each_root_subsys(root, ss) {
4424 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4427 percpu_ref_cancel_init(&css->refcnt);
4431 mutex_unlock(&cgroup_mutex);
4432 /* Release the reference count that we took on the superblock */
4433 deactivate_super(sb);
4435 ida_simple_remove(&root->cgroup_ida, cgrp->id);
4437 kfree(rcu_dereference_raw(cgrp->name));
4443 cgroup_destroy_locked(cgrp);
4444 mutex_unlock(&cgroup_mutex);
4445 mutex_unlock(&dentry->d_inode->i_mutex);
4449 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4451 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4453 /* the vfs holds inode->i_mutex already */
4454 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4457 static void cgroup_css_killed(struct cgroup *cgrp)
4459 if (!atomic_dec_and_test(&cgrp->css_kill_cnt))
4462 /* percpu ref's of all css's are killed, kick off the next step */
4463 INIT_WORK(&cgrp->destroy_work, cgroup_offline_fn);
4464 schedule_work(&cgrp->destroy_work);
4467 static void css_ref_killed_fn(struct percpu_ref *ref)
4469 struct cgroup_subsys_state *css =
4470 container_of(ref, struct cgroup_subsys_state, refcnt);
4472 cgroup_css_killed(css->cgroup);
4476 * cgroup_destroy_locked - the first stage of cgroup destruction
4477 * @cgrp: cgroup to be destroyed
4479 * css's make use of percpu refcnts whose killing latency shouldn't be
4480 * exposed to userland and are RCU protected. Also, cgroup core needs to
4481 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
4482 * invoked. To satisfy all the requirements, destruction is implemented in
4483 * the following two steps.
4485 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4486 * userland visible parts and start killing the percpu refcnts of
4487 * css's. Set up so that the next stage will be kicked off once all
4488 * the percpu refcnts are confirmed to be killed.
4490 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4491 * rest of destruction. Once all cgroup references are gone, the
4492 * cgroup is RCU-freed.
4494 * This function implements s1. After this step, @cgrp is gone as far as
4495 * the userland is concerned and a new cgroup with the same name may be
4496 * created. As cgroup doesn't care about the names internally, this
4497 * doesn't cause any problem.
4499 static int cgroup_destroy_locked(struct cgroup *cgrp)
4500 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4502 struct dentry *d = cgrp->dentry;
4503 struct cgroup_event *event, *tmp;
4504 struct cgroup_subsys *ss;
4507 lockdep_assert_held(&d->d_inode->i_mutex);
4508 lockdep_assert_held(&cgroup_mutex);
4511 * css_set_lock synchronizes access to ->cset_links and prevents
4512 * @cgrp from being removed while __put_css_set() is in progress.
4514 read_lock(&css_set_lock);
4515 empty = list_empty(&cgrp->cset_links) && list_empty(&cgrp->children);
4516 read_unlock(&css_set_lock);
4521 * Block new css_tryget() by killing css refcnts. cgroup core
4522 * guarantees that, by the time ->css_offline() is invoked, no new
4523 * css reference will be given out via css_tryget(). We can't
4524 * simply call percpu_ref_kill() and proceed to offlining css's
4525 * because percpu_ref_kill() doesn't guarantee that the ref is seen
4526 * as killed on all CPUs on return.
4528 * Use percpu_ref_kill_and_confirm() to get notifications as each
4529 * css is confirmed to be seen as killed on all CPUs. The
4530 * notification callback keeps track of the number of css's to be
4531 * killed and schedules cgroup_offline_fn() to perform the rest of
4532 * destruction once the percpu refs of all css's are confirmed to
4535 atomic_set(&cgrp->css_kill_cnt, 1);
4536 for_each_root_subsys(cgrp->root, ss) {
4537 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4540 * Killing would put the base ref, but we need to keep it
4541 * alive until after ->css_offline.
4543 percpu_ref_get(&css->refcnt);
4545 atomic_inc(&cgrp->css_kill_cnt);
4546 percpu_ref_kill_and_confirm(&css->refcnt, css_ref_killed_fn);
4548 cgroup_css_killed(cgrp);
4551 * Mark @cgrp dead. This prevents further task migration and child
4552 * creation by disabling cgroup_lock_live_group(). Note that
4553 * CGRP_DEAD assertion is depended upon by cgroup_next_sibling() to
4554 * resume iteration after dropping RCU read lock. See
4555 * cgroup_next_sibling() for details.
4557 set_bit(CGRP_DEAD, &cgrp->flags);
4559 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4560 raw_spin_lock(&release_list_lock);
4561 if (!list_empty(&cgrp->release_list))
4562 list_del_init(&cgrp->release_list);
4563 raw_spin_unlock(&release_list_lock);
4566 * Clear and remove @cgrp directory. The removal puts the base ref
4567 * but we aren't quite done with @cgrp yet, so hold onto it.
4569 cgroup_clear_dir(cgrp, cgrp->root->subsys_mask);
4570 cgroup_addrm_files(cgrp, NULL, cgroup_base_files, false);
4572 cgroup_d_remove_dir(d);
4575 * Unregister events and notify userspace.
4576 * Notify userspace about cgroup removing only after rmdir of cgroup
4577 * directory to avoid race between userspace and kernelspace.
4579 spin_lock(&cgrp->event_list_lock);
4580 list_for_each_entry_safe(event, tmp, &cgrp->event_list, list) {
4581 list_del_init(&event->list);
4582 schedule_work(&event->remove);
4584 spin_unlock(&cgrp->event_list_lock);
4590 * cgroup_offline_fn - the second step of cgroup destruction
4591 * @work: cgroup->destroy_free_work
4593 * This function is invoked from a work item for a cgroup which is being
4594 * destroyed after the percpu refcnts of all css's are guaranteed to be
4595 * seen as killed on all CPUs, and performs the rest of destruction. This
4596 * is the second step of destruction described in the comment above
4597 * cgroup_destroy_locked().
4599 static void cgroup_offline_fn(struct work_struct *work)
4601 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
4602 struct cgroup *parent = cgrp->parent;
4603 struct dentry *d = cgrp->dentry;
4604 struct cgroup_subsys *ss;
4606 mutex_lock(&cgroup_mutex);
4609 * css_tryget() is guaranteed to fail now. Tell subsystems to
4610 * initate destruction.
4612 for_each_root_subsys(cgrp->root, ss)
4613 offline_css(ss, cgrp);
4616 * Put the css refs from cgroup_destroy_locked(). Each css holds
4617 * an extra reference to the cgroup's dentry and cgroup removal
4618 * proceeds regardless of css refs. On the last put of each css,
4619 * whenever that may be, the extra dentry ref is put so that dentry
4620 * destruction happens only after all css's are released.
4622 for_each_root_subsys(cgrp->root, ss)
4623 css_put(cgrp->subsys[ss->subsys_id]);
4625 /* delete this cgroup from parent->children */
4626 list_del_rcu(&cgrp->sibling);
4630 set_bit(CGRP_RELEASABLE, &parent->flags);
4631 check_for_release(parent);
4633 mutex_unlock(&cgroup_mutex);
4636 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4640 mutex_lock(&cgroup_mutex);
4641 ret = cgroup_destroy_locked(dentry->d_fsdata);
4642 mutex_unlock(&cgroup_mutex);
4647 static void __init_or_module cgroup_init_cftsets(struct cgroup_subsys *ss)
4649 INIT_LIST_HEAD(&ss->cftsets);
4652 * base_cftset is embedded in subsys itself, no need to worry about
4655 if (ss->base_cftypes) {
4656 ss->base_cftset.cfts = ss->base_cftypes;
4657 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4661 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4663 struct cgroup_subsys_state *css;
4665 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4667 mutex_lock(&cgroup_mutex);
4669 /* init base cftset */
4670 cgroup_init_cftsets(ss);
4672 /* Create the top cgroup state for this subsystem */
4673 list_add(&ss->sibling, &cgroup_dummy_root.subsys_list);
4674 ss->root = &cgroup_dummy_root;
4675 css = ss->css_alloc(cgroup_dummy_top);
4676 /* We don't handle early failures gracefully */
4677 BUG_ON(IS_ERR(css));
4678 init_cgroup_css(css, ss, cgroup_dummy_top);
4680 /* Update the init_css_set to contain a subsys
4681 * pointer to this state - since the subsystem is
4682 * newly registered, all tasks and hence the
4683 * init_css_set is in the subsystem's top cgroup. */
4684 init_css_set.subsys[ss->subsys_id] = css;
4686 need_forkexit_callback |= ss->fork || ss->exit;
4688 /* At system boot, before all subsystems have been
4689 * registered, no tasks have been forked, so we don't
4690 * need to invoke fork callbacks here. */
4691 BUG_ON(!list_empty(&init_task.tasks));
4693 BUG_ON(online_css(ss, cgroup_dummy_top));
4695 mutex_unlock(&cgroup_mutex);
4697 /* this function shouldn't be used with modular subsystems, since they
4698 * need to register a subsys_id, among other things */
4703 * cgroup_load_subsys: load and register a modular subsystem at runtime
4704 * @ss: the subsystem to load
4706 * This function should be called in a modular subsystem's initcall. If the
4707 * subsystem is built as a module, it will be assigned a new subsys_id and set
4708 * up for use. If the subsystem is built-in anyway, work is delegated to the
4709 * simpler cgroup_init_subsys.
4711 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
4713 struct cgroup_subsys_state *css;
4715 struct hlist_node *tmp;
4716 struct css_set *cset;
4719 /* check name and function validity */
4720 if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
4721 ss->css_alloc == NULL || ss->css_free == NULL)
4725 * we don't support callbacks in modular subsystems. this check is
4726 * before the ss->module check for consistency; a subsystem that could
4727 * be a module should still have no callbacks even if the user isn't
4728 * compiling it as one.
4730 if (ss->fork || ss->exit)
4734 * an optionally modular subsystem is built-in: we want to do nothing,
4735 * since cgroup_init_subsys will have already taken care of it.
4737 if (ss->module == NULL) {
4738 /* a sanity check */
4739 BUG_ON(cgroup_subsys[ss->subsys_id] != ss);
4743 /* init base cftset */
4744 cgroup_init_cftsets(ss);
4746 mutex_lock(&cgroup_mutex);
4747 cgroup_subsys[ss->subsys_id] = ss;
4750 * no ss->css_alloc seems to need anything important in the ss
4751 * struct, so this can happen first (i.e. before the dummy root
4754 css = ss->css_alloc(cgroup_dummy_top);
4756 /* failure case - need to deassign the cgroup_subsys[] slot. */
4757 cgroup_subsys[ss->subsys_id] = NULL;
4758 mutex_unlock(&cgroup_mutex);
4759 return PTR_ERR(css);
4762 list_add(&ss->sibling, &cgroup_dummy_root.subsys_list);
4763 ss->root = &cgroup_dummy_root;
4765 /* our new subsystem will be attached to the dummy hierarchy. */
4766 init_cgroup_css(css, ss, cgroup_dummy_top);
4767 /* init_idr must be after init_cgroup_css because it sets css->id. */
4769 ret = cgroup_init_idr(ss, css);
4775 * Now we need to entangle the css into the existing css_sets. unlike
4776 * in cgroup_init_subsys, there are now multiple css_sets, so each one
4777 * will need a new pointer to it; done by iterating the css_set_table.
4778 * furthermore, modifying the existing css_sets will corrupt the hash
4779 * table state, so each changed css_set will need its hash recomputed.
4780 * this is all done under the css_set_lock.
4782 write_lock(&css_set_lock);
4783 hash_for_each_safe(css_set_table, i, tmp, cset, hlist) {
4784 /* skip entries that we already rehashed */
4785 if (cset->subsys[ss->subsys_id])
4787 /* remove existing entry */
4788 hash_del(&cset->hlist);
4790 cset->subsys[ss->subsys_id] = css;
4791 /* recompute hash and restore entry */
4792 key = css_set_hash(cset->subsys);
4793 hash_add(css_set_table, &cset->hlist, key);
4795 write_unlock(&css_set_lock);
4797 ret = online_css(ss, cgroup_dummy_top);
4802 mutex_unlock(&cgroup_mutex);
4806 mutex_unlock(&cgroup_mutex);
4807 /* @ss can't be mounted here as try_module_get() would fail */
4808 cgroup_unload_subsys(ss);
4811 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
4814 * cgroup_unload_subsys: unload a modular subsystem
4815 * @ss: the subsystem to unload
4817 * This function should be called in a modular subsystem's exitcall. When this
4818 * function is invoked, the refcount on the subsystem's module will be 0, so
4819 * the subsystem will not be attached to any hierarchy.
4821 void cgroup_unload_subsys(struct cgroup_subsys *ss)
4823 struct cgrp_cset_link *link;
4825 BUG_ON(ss->module == NULL);
4828 * we shouldn't be called if the subsystem is in use, and the use of
4829 * try_module_get in parse_cgroupfs_options should ensure that it
4830 * doesn't start being used while we're killing it off.
4832 BUG_ON(ss->root != &cgroup_dummy_root);
4834 mutex_lock(&cgroup_mutex);
4836 offline_css(ss, cgroup_dummy_top);
4839 idr_destroy(&ss->idr);
4841 /* deassign the subsys_id */
4842 cgroup_subsys[ss->subsys_id] = NULL;
4844 /* remove subsystem from the dummy root's list of subsystems */
4845 list_del_init(&ss->sibling);
4848 * disentangle the css from all css_sets attached to the dummy
4849 * top. as in loading, we need to pay our respects to the hashtable
4852 write_lock(&css_set_lock);
4853 list_for_each_entry(link, &cgroup_dummy_top->cset_links, cset_link) {
4854 struct css_set *cset = link->cset;
4857 hash_del(&cset->hlist);
4858 cset->subsys[ss->subsys_id] = NULL;
4859 key = css_set_hash(cset->subsys);
4860 hash_add(css_set_table, &cset->hlist, key);
4862 write_unlock(&css_set_lock);
4865 * remove subsystem's css from the cgroup_dummy_top and free it -
4866 * need to free before marking as null because ss->css_free needs
4867 * the cgrp->subsys pointer to find their state. note that this
4868 * also takes care of freeing the css_id.
4870 ss->css_free(cgroup_dummy_top);
4871 cgroup_dummy_top->subsys[ss->subsys_id] = NULL;
4873 mutex_unlock(&cgroup_mutex);
4875 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
4878 * cgroup_init_early - cgroup initialization at system boot
4880 * Initialize cgroups at system boot, and initialize any
4881 * subsystems that request early init.
4883 int __init cgroup_init_early(void)
4885 struct cgroup_subsys *ss;
4888 atomic_set(&init_css_set.refcount, 1);
4889 INIT_LIST_HEAD(&init_css_set.cgrp_links);
4890 INIT_LIST_HEAD(&init_css_set.tasks);
4891 INIT_HLIST_NODE(&init_css_set.hlist);
4893 init_cgroup_root(&cgroup_dummy_root);
4894 cgroup_root_count = 1;
4895 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4897 init_cgrp_cset_link.cset = &init_css_set;
4898 init_cgrp_cset_link.cgrp = cgroup_dummy_top;
4899 list_add(&init_cgrp_cset_link.cset_link, &cgroup_dummy_top->cset_links);
4900 list_add(&init_cgrp_cset_link.cgrp_link, &init_css_set.cgrp_links);
4902 /* at bootup time, we don't worry about modular subsystems */
4903 for_each_builtin_subsys(ss, i) {
4905 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
4906 BUG_ON(!ss->css_alloc);
4907 BUG_ON(!ss->css_free);
4908 if (ss->subsys_id != i) {
4909 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
4910 ss->name, ss->subsys_id);
4915 cgroup_init_subsys(ss);
4921 * cgroup_init - cgroup initialization
4923 * Register cgroup filesystem and /proc file, and initialize
4924 * any subsystems that didn't request early init.
4926 int __init cgroup_init(void)
4928 struct cgroup_subsys *ss;
4932 err = bdi_init(&cgroup_backing_dev_info);
4936 for_each_builtin_subsys(ss, i) {
4937 if (!ss->early_init)
4938 cgroup_init_subsys(ss);
4940 cgroup_init_idr(ss, init_css_set.subsys[ss->subsys_id]);
4943 /* allocate id for the dummy hierarchy */
4944 mutex_lock(&cgroup_mutex);
4945 mutex_lock(&cgroup_root_mutex);
4947 /* Add init_css_set to the hash table */
4948 key = css_set_hash(init_css_set.subsys);
4949 hash_add(css_set_table, &init_css_set.hlist, key);
4951 BUG_ON(cgroup_init_root_id(&cgroup_dummy_root, 0, 1));
4953 mutex_unlock(&cgroup_root_mutex);
4954 mutex_unlock(&cgroup_mutex);
4956 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4962 err = register_filesystem(&cgroup_fs_type);
4964 kobject_put(cgroup_kobj);
4968 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4972 bdi_destroy(&cgroup_backing_dev_info);
4978 * proc_cgroup_show()
4979 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4980 * - Used for /proc/<pid>/cgroup.
4981 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4982 * doesn't really matter if tsk->cgroup changes after we read it,
4983 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4984 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4985 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4986 * cgroup to top_cgroup.
4989 /* TODO: Use a proper seq_file iterator */
4990 int proc_cgroup_show(struct seq_file *m, void *v)
4993 struct task_struct *tsk;
4996 struct cgroupfs_root *root;
4999 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5005 tsk = get_pid_task(pid, PIDTYPE_PID);
5011 mutex_lock(&cgroup_mutex);
5013 for_each_active_root(root) {
5014 struct cgroup_subsys *ss;
5015 struct cgroup *cgrp;
5018 seq_printf(m, "%d:", root->hierarchy_id);
5019 for_each_root_subsys(root, ss)
5020 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
5021 if (strlen(root->name))
5022 seq_printf(m, "%sname=%s", count ? "," : "",
5025 cgrp = task_cgroup_from_root(tsk, root);
5026 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
5034 mutex_unlock(&cgroup_mutex);
5035 put_task_struct(tsk);
5042 /* Display information about each subsystem and each hierarchy */
5043 static int proc_cgroupstats_show(struct seq_file *m, void *v)
5045 struct cgroup_subsys *ss;
5048 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
5050 * ideally we don't want subsystems moving around while we do this.
5051 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
5052 * subsys/hierarchy state.
5054 mutex_lock(&cgroup_mutex);
5056 for_each_subsys(ss, i)
5057 seq_printf(m, "%s\t%d\t%d\t%d\n",
5058 ss->name, ss->root->hierarchy_id,
5059 ss->root->number_of_cgroups, !ss->disabled);
5061 mutex_unlock(&cgroup_mutex);
5065 static int cgroupstats_open(struct inode *inode, struct file *file)
5067 return single_open(file, proc_cgroupstats_show, NULL);
5070 static const struct file_operations proc_cgroupstats_operations = {
5071 .open = cgroupstats_open,
5073 .llseek = seq_lseek,
5074 .release = single_release,
5078 * cgroup_fork - attach newly forked task to its parents cgroup.
5079 * @child: pointer to task_struct of forking parent process.
5081 * Description: A task inherits its parent's cgroup at fork().
5083 * A pointer to the shared css_set was automatically copied in
5084 * fork.c by dup_task_struct(). However, we ignore that copy, since
5085 * it was not made under the protection of RCU or cgroup_mutex, so
5086 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
5087 * have already changed current->cgroups, allowing the previously
5088 * referenced cgroup group to be removed and freed.
5090 * At the point that cgroup_fork() is called, 'current' is the parent
5091 * task, and the passed argument 'child' points to the child task.
5093 void cgroup_fork(struct task_struct *child)
5096 get_css_set(task_css_set(current));
5097 child->cgroups = current->cgroups;
5098 task_unlock(current);
5099 INIT_LIST_HEAD(&child->cg_list);
5103 * cgroup_post_fork - called on a new task after adding it to the task list
5104 * @child: the task in question
5106 * Adds the task to the list running through its css_set if necessary and
5107 * call the subsystem fork() callbacks. Has to be after the task is
5108 * visible on the task list in case we race with the first call to
5109 * cgroup_iter_start() - to guarantee that the new task ends up on its
5112 void cgroup_post_fork(struct task_struct *child)
5114 struct cgroup_subsys *ss;
5118 * use_task_css_set_links is set to 1 before we walk the tasklist
5119 * under the tasklist_lock and we read it here after we added the child
5120 * to the tasklist under the tasklist_lock as well. If the child wasn't
5121 * yet in the tasklist when we walked through it from
5122 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
5123 * should be visible now due to the paired locking and barriers implied
5124 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
5125 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
5128 if (use_task_css_set_links) {
5129 write_lock(&css_set_lock);
5131 if (list_empty(&child->cg_list))
5132 list_add(&child->cg_list, &task_css_set(child)->tasks);
5134 write_unlock(&css_set_lock);
5138 * Call ss->fork(). This must happen after @child is linked on
5139 * css_set; otherwise, @child might change state between ->fork()
5140 * and addition to css_set.
5142 if (need_forkexit_callback) {
5144 * fork/exit callbacks are supported only for builtin
5145 * subsystems, and the builtin section of the subsys
5146 * array is immutable, so we don't need to lock the
5147 * subsys array here. On the other hand, modular section
5148 * of the array can be freed at module unload, so we
5151 for_each_builtin_subsys(ss, i)
5158 * cgroup_exit - detach cgroup from exiting task
5159 * @tsk: pointer to task_struct of exiting process
5160 * @run_callback: run exit callbacks?
5162 * Description: Detach cgroup from @tsk and release it.
5164 * Note that cgroups marked notify_on_release force every task in
5165 * them to take the global cgroup_mutex mutex when exiting.
5166 * This could impact scaling on very large systems. Be reluctant to
5167 * use notify_on_release cgroups where very high task exit scaling
5168 * is required on large systems.
5170 * the_top_cgroup_hack:
5172 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
5174 * We call cgroup_exit() while the task is still competent to
5175 * handle notify_on_release(), then leave the task attached to the
5176 * root cgroup in each hierarchy for the remainder of its exit.
5178 * To do this properly, we would increment the reference count on
5179 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
5180 * code we would add a second cgroup function call, to drop that
5181 * reference. This would just create an unnecessary hot spot on
5182 * the top_cgroup reference count, to no avail.
5184 * Normally, holding a reference to a cgroup without bumping its
5185 * count is unsafe. The cgroup could go away, or someone could
5186 * attach us to a different cgroup, decrementing the count on
5187 * the first cgroup that we never incremented. But in this case,
5188 * top_cgroup isn't going away, and either task has PF_EXITING set,
5189 * which wards off any cgroup_attach_task() attempts, or task is a failed
5190 * fork, never visible to cgroup_attach_task.
5192 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
5194 struct cgroup_subsys *ss;
5195 struct css_set *cset;
5199 * Unlink from the css_set task list if necessary.
5200 * Optimistically check cg_list before taking
5203 if (!list_empty(&tsk->cg_list)) {
5204 write_lock(&css_set_lock);
5205 if (!list_empty(&tsk->cg_list))
5206 list_del_init(&tsk->cg_list);
5207 write_unlock(&css_set_lock);
5210 /* Reassign the task to the init_css_set. */
5212 cset = task_css_set(tsk);
5213 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
5215 if (run_callbacks && need_forkexit_callback) {
5217 * fork/exit callbacks are supported only for builtin
5218 * subsystems, see cgroup_post_fork() for details.
5220 for_each_builtin_subsys(ss, i) {
5222 struct cgroup *old_cgrp = cset->subsys[i]->cgroup;
5223 struct cgroup *cgrp = task_cgroup(tsk, i);
5225 ss->exit(cgrp, old_cgrp, tsk);
5231 put_css_set_taskexit(cset);
5234 static void check_for_release(struct cgroup *cgrp)
5236 if (cgroup_is_releasable(cgrp) &&
5237 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
5239 * Control Group is currently removeable. If it's not
5240 * already queued for a userspace notification, queue
5243 int need_schedule_work = 0;
5245 raw_spin_lock(&release_list_lock);
5246 if (!cgroup_is_dead(cgrp) &&
5247 list_empty(&cgrp->release_list)) {
5248 list_add(&cgrp->release_list, &release_list);
5249 need_schedule_work = 1;
5251 raw_spin_unlock(&release_list_lock);
5252 if (need_schedule_work)
5253 schedule_work(&release_agent_work);
5258 * Notify userspace when a cgroup is released, by running the
5259 * configured release agent with the name of the cgroup (path
5260 * relative to the root of cgroup file system) as the argument.
5262 * Most likely, this user command will try to rmdir this cgroup.
5264 * This races with the possibility that some other task will be
5265 * attached to this cgroup before it is removed, or that some other
5266 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5267 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5268 * unused, and this cgroup will be reprieved from its death sentence,
5269 * to continue to serve a useful existence. Next time it's released,
5270 * we will get notified again, if it still has 'notify_on_release' set.
5272 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5273 * means only wait until the task is successfully execve()'d. The
5274 * separate release agent task is forked by call_usermodehelper(),
5275 * then control in this thread returns here, without waiting for the
5276 * release agent task. We don't bother to wait because the caller of
5277 * this routine has no use for the exit status of the release agent
5278 * task, so no sense holding our caller up for that.
5280 static void cgroup_release_agent(struct work_struct *work)
5282 BUG_ON(work != &release_agent_work);
5283 mutex_lock(&cgroup_mutex);
5284 raw_spin_lock(&release_list_lock);
5285 while (!list_empty(&release_list)) {
5286 char *argv[3], *envp[3];
5288 char *pathbuf = NULL, *agentbuf = NULL;
5289 struct cgroup *cgrp = list_entry(release_list.next,
5292 list_del_init(&cgrp->release_list);
5293 raw_spin_unlock(&release_list_lock);
5294 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5297 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
5299 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5304 argv[i++] = agentbuf;
5305 argv[i++] = pathbuf;
5309 /* minimal command environment */
5310 envp[i++] = "HOME=/";
5311 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5314 /* Drop the lock while we invoke the usermode helper,
5315 * since the exec could involve hitting disk and hence
5316 * be a slow process */
5317 mutex_unlock(&cgroup_mutex);
5318 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5319 mutex_lock(&cgroup_mutex);
5323 raw_spin_lock(&release_list_lock);
5325 raw_spin_unlock(&release_list_lock);
5326 mutex_unlock(&cgroup_mutex);
5329 static int __init cgroup_disable(char *str)
5331 struct cgroup_subsys *ss;
5335 while ((token = strsep(&str, ",")) != NULL) {
5340 * cgroup_disable, being at boot time, can't know about
5341 * module subsystems, so we don't worry about them.
5343 for_each_builtin_subsys(ss, i) {
5344 if (!strcmp(token, ss->name)) {
5346 printk(KERN_INFO "Disabling %s control group"
5347 " subsystem\n", ss->name);
5354 __setup("cgroup_disable=", cgroup_disable);
5357 * Functons for CSS ID.
5360 /* to get ID other than 0, this should be called when !cgroup_is_dead() */
5361 unsigned short css_id(struct cgroup_subsys_state *css)
5363 struct css_id *cssid;
5366 * This css_id() can return correct value when somone has refcnt
5367 * on this or this is under rcu_read_lock(). Once css->id is allocated,
5368 * it's unchanged until freed.
5370 cssid = rcu_dereference_raw(css->id);
5376 EXPORT_SYMBOL_GPL(css_id);
5379 * css_is_ancestor - test "root" css is an ancestor of "child"
5380 * @child: the css to be tested.
5381 * @root: the css supporsed to be an ancestor of the child.
5383 * Returns true if "root" is an ancestor of "child" in its hierarchy. Because
5384 * this function reads css->id, the caller must hold rcu_read_lock().
5385 * But, considering usual usage, the csses should be valid objects after test.
5386 * Assuming that the caller will do some action to the child if this returns
5387 * returns true, the caller must take "child";s reference count.
5388 * If "child" is valid object and this returns true, "root" is valid, too.
5391 bool css_is_ancestor(struct cgroup_subsys_state *child,
5392 const struct cgroup_subsys_state *root)
5394 struct css_id *child_id;
5395 struct css_id *root_id;
5397 child_id = rcu_dereference(child->id);
5400 root_id = rcu_dereference(root->id);
5403 if (child_id->depth < root_id->depth)
5405 if (child_id->stack[root_id->depth] != root_id->id)
5410 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
5412 struct css_id *id = rcu_dereference_protected(css->id, true);
5414 /* When this is called before css_id initialization, id can be NULL */
5418 BUG_ON(!ss->use_id);
5420 rcu_assign_pointer(id->css, NULL);
5421 rcu_assign_pointer(css->id, NULL);
5422 spin_lock(&ss->id_lock);
5423 idr_remove(&ss->idr, id->id);
5424 spin_unlock(&ss->id_lock);
5425 kfree_rcu(id, rcu_head);
5427 EXPORT_SYMBOL_GPL(free_css_id);
5430 * This is called by init or create(). Then, calls to this function are
5431 * always serialized (By cgroup_mutex() at create()).
5434 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
5436 struct css_id *newid;
5439 BUG_ON(!ss->use_id);
5441 size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
5442 newid = kzalloc(size, GFP_KERNEL);
5444 return ERR_PTR(-ENOMEM);
5446 idr_preload(GFP_KERNEL);
5447 spin_lock(&ss->id_lock);
5448 /* Don't use 0. allocates an ID of 1-65535 */
5449 ret = idr_alloc(&ss->idr, newid, 1, CSS_ID_MAX + 1, GFP_NOWAIT);
5450 spin_unlock(&ss->id_lock);
5453 /* Returns error when there are no free spaces for new ID.*/
5458 newid->depth = depth;
5462 return ERR_PTR(ret);
5466 static int __init_or_module cgroup_init_idr(struct cgroup_subsys *ss,
5467 struct cgroup_subsys_state *rootcss)
5469 struct css_id *newid;
5471 spin_lock_init(&ss->id_lock);
5474 newid = get_new_cssid(ss, 0);
5476 return PTR_ERR(newid);
5478 newid->stack[0] = newid->id;
5479 RCU_INIT_POINTER(newid->css, rootcss);
5480 RCU_INIT_POINTER(rootcss->id, newid);
5484 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
5485 struct cgroup *child)
5487 int subsys_id, i, depth = 0;
5488 struct cgroup_subsys_state *parent_css, *child_css;
5489 struct css_id *child_id, *parent_id;
5491 subsys_id = ss->subsys_id;
5492 parent_css = parent->subsys[subsys_id];
5493 child_css = child->subsys[subsys_id];
5494 parent_id = rcu_dereference_protected(parent_css->id, true);
5495 depth = parent_id->depth + 1;
5497 child_id = get_new_cssid(ss, depth);
5498 if (IS_ERR(child_id))
5499 return PTR_ERR(child_id);
5501 for (i = 0; i < depth; i++)
5502 child_id->stack[i] = parent_id->stack[i];
5503 child_id->stack[depth] = child_id->id;
5505 * child_id->css pointer will be set after this cgroup is available
5506 * see cgroup_populate_dir()
5508 rcu_assign_pointer(child_css->id, child_id);
5514 * css_lookup - lookup css by id
5515 * @ss: cgroup subsys to be looked into.
5518 * Returns pointer to cgroup_subsys_state if there is valid one with id.
5519 * NULL if not. Should be called under rcu_read_lock()
5521 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
5523 struct css_id *cssid = NULL;
5525 BUG_ON(!ss->use_id);
5526 cssid = idr_find(&ss->idr, id);
5528 if (unlikely(!cssid))
5531 return rcu_dereference(cssid->css);
5533 EXPORT_SYMBOL_GPL(css_lookup);
5536 * get corresponding css from file open on cgroupfs directory
5538 struct cgroup_subsys_state *cgroup_css_from_dir(struct file *f, int id)
5540 struct cgroup *cgrp;
5541 struct inode *inode;
5542 struct cgroup_subsys_state *css;
5544 inode = file_inode(f);
5545 /* check in cgroup filesystem dir */
5546 if (inode->i_op != &cgroup_dir_inode_operations)
5547 return ERR_PTR(-EBADF);
5549 if (id < 0 || id >= CGROUP_SUBSYS_COUNT)
5550 return ERR_PTR(-EINVAL);
5553 cgrp = __d_cgrp(f->f_dentry);
5554 css = cgrp->subsys[id];
5555 return css ? css : ERR_PTR(-ENOENT);
5558 #ifdef CONFIG_CGROUP_DEBUG
5559 static struct cgroup_subsys_state *debug_css_alloc(struct cgroup *cgrp)
5561 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5564 return ERR_PTR(-ENOMEM);
5569 static void debug_css_free(struct cgroup *cgrp)
5571 kfree(cgrp->subsys[debug_subsys_id]);
5574 static u64 debug_taskcount_read(struct cgroup *cgrp, struct cftype *cft)
5576 return cgroup_task_count(cgrp);
5579 static u64 current_css_set_read(struct cgroup *cgrp, struct cftype *cft)
5581 return (u64)(unsigned long)current->cgroups;
5584 static u64 current_css_set_refcount_read(struct cgroup *cgrp,
5590 count = atomic_read(&task_css_set(current)->refcount);
5595 static int current_css_set_cg_links_read(struct cgroup *cgrp,
5597 struct seq_file *seq)
5599 struct cgrp_cset_link *link;
5600 struct css_set *cset;
5602 read_lock(&css_set_lock);
5604 cset = rcu_dereference(current->cgroups);
5605 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5606 struct cgroup *c = link->cgrp;
5610 name = c->dentry->d_name.name;
5613 seq_printf(seq, "Root %d group %s\n",
5614 c->root->hierarchy_id, name);
5617 read_unlock(&css_set_lock);
5621 #define MAX_TASKS_SHOWN_PER_CSS 25
5622 static int cgroup_css_links_read(struct cgroup *cgrp,
5624 struct seq_file *seq)
5626 struct cgrp_cset_link *link;
5628 read_lock(&css_set_lock);
5629 list_for_each_entry(link, &cgrp->cset_links, cset_link) {
5630 struct css_set *cset = link->cset;
5631 struct task_struct *task;
5633 seq_printf(seq, "css_set %p\n", cset);
5634 list_for_each_entry(task, &cset->tasks, cg_list) {
5635 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5636 seq_puts(seq, " ...\n");
5639 seq_printf(seq, " task %d\n",
5640 task_pid_vnr(task));
5644 read_unlock(&css_set_lock);
5648 static u64 releasable_read(struct cgroup *cgrp, struct cftype *cft)
5650 return test_bit(CGRP_RELEASABLE, &cgrp->flags);
5653 static struct cftype debug_files[] = {
5655 .name = "taskcount",
5656 .read_u64 = debug_taskcount_read,
5660 .name = "current_css_set",
5661 .read_u64 = current_css_set_read,
5665 .name = "current_css_set_refcount",
5666 .read_u64 = current_css_set_refcount_read,
5670 .name = "current_css_set_cg_links",
5671 .read_seq_string = current_css_set_cg_links_read,
5675 .name = "cgroup_css_links",
5676 .read_seq_string = cgroup_css_links_read,
5680 .name = "releasable",
5681 .read_u64 = releasable_read,
5687 struct cgroup_subsys debug_subsys = {
5689 .css_alloc = debug_css_alloc,
5690 .css_free = debug_css_free,
5691 .subsys_id = debug_subsys_id,
5692 .base_cftypes = debug_files,
5694 #endif /* CONFIG_CGROUP_DEBUG */