2 * Generic process-grouping system.
4 * Based originally on the cpuset system, extracted by Paul Menage
5 * Copyright (C) 2006 Google, Inc
7 * Notifications support
8 * Copyright (C) 2009 Nokia Corporation
9 * Author: Kirill A. Shutemov
11 * Copyright notices from the original cpuset code:
12 * --------------------------------------------------
13 * Copyright (C) 2003 BULL SA.
14 * Copyright (C) 2004-2006 Silicon Graphics, Inc.
16 * Portions derived from Patrick Mochel's sysfs code.
17 * sysfs is Copyright (c) 2001-3 Patrick Mochel
19 * 2003-10-10 Written by Simon Derr.
20 * 2003-10-22 Updates by Stephen Hemminger.
21 * 2004 May-July Rework by Paul Jackson.
22 * ---------------------------------------------------
24 * This file is subject to the terms and conditions of the GNU General Public
25 * License. See the file COPYING in the main directory of the Linux
26 * distribution for more details.
29 #include <linux/cgroup.h>
30 #include <linux/cred.h>
31 #include <linux/ctype.h>
32 #include <linux/errno.h>
33 #include <linux/init_task.h>
34 #include <linux/kernel.h>
35 #include <linux/list.h>
37 #include <linux/mutex.h>
38 #include <linux/mount.h>
39 #include <linux/pagemap.h>
40 #include <linux/proc_fs.h>
41 #include <linux/rcupdate.h>
42 #include <linux/sched.h>
43 #include <linux/backing-dev.h>
44 #include <linux/slab.h>
45 #include <linux/magic.h>
46 #include <linux/spinlock.h>
47 #include <linux/string.h>
48 #include <linux/sort.h>
49 #include <linux/kmod.h>
50 #include <linux/module.h>
51 #include <linux/delayacct.h>
52 #include <linux/cgroupstats.h>
53 #include <linux/hashtable.h>
54 #include <linux/namei.h>
55 #include <linux/pid_namespace.h>
56 #include <linux/idr.h>
57 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
58 #include <linux/flex_array.h> /* used in cgroup_attach_task */
59 #include <linux/kthread.h>
61 #include <linux/atomic.h>
64 * pidlists linger the following amount before being destroyed. The goal
65 * is avoiding frequent destruction in the middle of consecutive read calls
66 * Expiring in the middle is a performance problem not a correctness one.
67 * 1 sec should be enough.
69 #define CGROUP_PIDLIST_DESTROY_DELAY HZ
72 * cgroup_mutex is the master lock. Any modification to cgroup or its
73 * hierarchy must be performed while holding it.
75 * cgroup_root_mutex nests inside cgroup_mutex and should be held to modify
76 * cgroupfs_root of any cgroup hierarchy - subsys list, flags,
77 * release_agent_path and so on. Modifying requires both cgroup_mutex and
78 * cgroup_root_mutex. Readers can acquire either of the two. This is to
79 * break the following locking order cycle.
81 * A. cgroup_mutex -> cred_guard_mutex -> s_type->i_mutex_key -> namespace_sem
82 * B. namespace_sem -> cgroup_mutex
84 * B happens only through cgroup_show_options() and using cgroup_root_mutex
87 #ifdef CONFIG_PROVE_RCU
88 DEFINE_MUTEX(cgroup_mutex
);
89 EXPORT_SYMBOL_GPL(cgroup_mutex
); /* only for lockdep */
91 static DEFINE_MUTEX(cgroup_mutex
);
94 static DEFINE_MUTEX(cgroup_root_mutex
);
97 * cgroup destruction makes heavy use of work items and there can be a lot
98 * of concurrent destructions. Use a separate workqueue so that cgroup
99 * destruction work items don't end up filling up max_active of system_wq
100 * which may lead to deadlock.
102 static struct workqueue_struct
*cgroup_destroy_wq
;
105 * pidlist destructions need to be flushed on cgroup destruction. Use a
106 * separate workqueue as flush domain.
108 static struct workqueue_struct
*cgroup_pidlist_destroy_wq
;
111 * Generate an array of cgroup subsystem pointers. At boot time, this is
112 * populated with the built in subsystems, and modular subsystems are
113 * registered after that. The mutable section of this array is protected by
116 #define SUBSYS(_x) [_x ## _subsys_id] = &_x ## _subsys,
117 #define IS_SUBSYS_ENABLED(option) IS_BUILTIN(option)
118 static struct cgroup_subsys
*cgroup_subsys
[CGROUP_SUBSYS_COUNT
] = {
119 #include <linux/cgroup_subsys.h>
123 * The dummy hierarchy, reserved for the subsystems that are otherwise
124 * unattached - it never has more than a single cgroup, and all tasks are
125 * part of that cgroup.
127 static struct cgroupfs_root cgroup_dummy_root
;
129 /* dummy_top is a shorthand for the dummy hierarchy's top cgroup */
130 static struct cgroup
* const cgroup_dummy_top
= &cgroup_dummy_root
.top_cgroup
;
132 /* The list of hierarchy roots */
134 static LIST_HEAD(cgroup_roots
);
135 static int cgroup_root_count
;
138 * Hierarchy ID allocation and mapping. It follows the same exclusion
139 * rules as other root ops - both cgroup_mutex and cgroup_root_mutex for
140 * writes, either for reads.
142 static DEFINE_IDR(cgroup_hierarchy_idr
);
144 static struct cgroup_name root_cgroup_name
= { .name
= "/" };
147 * Assign a monotonically increasing serial number to cgroups. It
148 * guarantees cgroups with bigger numbers are newer than those with smaller
149 * numbers. Also, as cgroups are always appended to the parent's
150 * ->children list, it guarantees that sibling cgroups are always sorted in
151 * the ascending serial number order on the list. Protected by
154 static u64 cgroup_serial_nr_next
= 1;
156 /* This flag indicates whether tasks in the fork and exit paths should
157 * check for fork/exit handlers to call. This avoids us having to do
158 * extra work in the fork/exit path if none of the subsystems need to
161 static int need_forkexit_callback __read_mostly
;
163 static struct cftype cgroup_base_files
[];
165 static void cgroup_destroy_css_killed(struct cgroup
*cgrp
);
166 static int cgroup_destroy_locked(struct cgroup
*cgrp
);
167 static int cgroup_addrm_files(struct cgroup
*cgrp
, struct cftype cfts
[],
169 static int cgroup_file_release(struct inode
*inode
, struct file
*file
);
170 static void cgroup_pidlist_destroy_all(struct cgroup
*cgrp
);
173 * cgroup_css - obtain a cgroup's css for the specified subsystem
174 * @cgrp: the cgroup of interest
175 * @ss: the subsystem of interest (%NULL returns the dummy_css)
177 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
178 * function must be called either under cgroup_mutex or rcu_read_lock() and
179 * the caller is responsible for pinning the returned css if it wants to
180 * keep accessing it outside the said locks. This function may return
181 * %NULL if @cgrp doesn't have @subsys_id enabled.
183 static struct cgroup_subsys_state
*cgroup_css(struct cgroup
*cgrp
,
184 struct cgroup_subsys
*ss
)
187 return rcu_dereference_check(cgrp
->subsys
[ss
->subsys_id
],
188 lockdep_is_held(&cgroup_mutex
));
190 return &cgrp
->dummy_css
;
193 /* convenient tests for these bits */
194 static inline bool cgroup_is_dead(const struct cgroup
*cgrp
)
196 return test_bit(CGRP_DEAD
, &cgrp
->flags
);
200 * cgroup_is_descendant - test ancestry
201 * @cgrp: the cgroup to be tested
202 * @ancestor: possible ancestor of @cgrp
204 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
205 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
206 * and @ancestor are accessible.
208 bool cgroup_is_descendant(struct cgroup
*cgrp
, struct cgroup
*ancestor
)
211 if (cgrp
== ancestor
)
217 EXPORT_SYMBOL_GPL(cgroup_is_descendant
);
219 static int cgroup_is_releasable(const struct cgroup
*cgrp
)
222 (1 << CGRP_RELEASABLE
) |
223 (1 << CGRP_NOTIFY_ON_RELEASE
);
224 return (cgrp
->flags
& bits
) == bits
;
227 static int notify_on_release(const struct cgroup
*cgrp
)
229 return test_bit(CGRP_NOTIFY_ON_RELEASE
, &cgrp
->flags
);
233 * for_each_subsys - iterate all loaded cgroup subsystems
234 * @ss: the iteration cursor
235 * @i: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
237 * Should be called under cgroup_mutex.
239 #define for_each_subsys(ss, i) \
240 for ((i) = 0; (i) < CGROUP_SUBSYS_COUNT; (i)++) \
241 if (({ lockdep_assert_held(&cgroup_mutex); \
242 !((ss) = cgroup_subsys[i]); })) { } \
246 * for_each_builtin_subsys - iterate all built-in cgroup subsystems
247 * @ss: the iteration cursor
248 * @i: the index of @ss, CGROUP_BUILTIN_SUBSYS_COUNT after reaching the end
250 * Bulit-in subsystems are always present and iteration itself doesn't
251 * require any synchronization.
253 #define for_each_builtin_subsys(ss, i) \
254 for ((i) = 0; (i) < CGROUP_BUILTIN_SUBSYS_COUNT && \
255 (((ss) = cgroup_subsys[i]) || true); (i)++)
257 /* iterate each subsystem attached to a hierarchy */
258 #define for_each_root_subsys(root, ss) \
259 list_for_each_entry((ss), &(root)->subsys_list, sibling)
261 /* iterate across the active hierarchies */
262 #define for_each_active_root(root) \
263 list_for_each_entry((root), &cgroup_roots, root_list)
265 static inline struct cgroup
*__d_cgrp(struct dentry
*dentry
)
267 return dentry
->d_fsdata
;
270 static inline struct cfent
*__d_cfe(struct dentry
*dentry
)
272 return dentry
->d_fsdata
;
275 static inline struct cftype
*__d_cft(struct dentry
*dentry
)
277 return __d_cfe(dentry
)->type
;
281 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
282 * @cgrp: the cgroup to be checked for liveness
284 * On success, returns true; the mutex should be later unlocked. On
285 * failure returns false with no lock held.
287 static bool cgroup_lock_live_group(struct cgroup
*cgrp
)
289 mutex_lock(&cgroup_mutex
);
290 if (cgroup_is_dead(cgrp
)) {
291 mutex_unlock(&cgroup_mutex
);
297 /* the list of cgroups eligible for automatic release. Protected by
298 * release_list_lock */
299 static LIST_HEAD(release_list
);
300 static DEFINE_RAW_SPINLOCK(release_list_lock
);
301 static void cgroup_release_agent(struct work_struct
*work
);
302 static DECLARE_WORK(release_agent_work
, cgroup_release_agent
);
303 static void check_for_release(struct cgroup
*cgrp
);
306 * A cgroup can be associated with multiple css_sets as different tasks may
307 * belong to different cgroups on different hierarchies. In the other
308 * direction, a css_set is naturally associated with multiple cgroups.
309 * This M:N relationship is represented by the following link structure
310 * which exists for each association and allows traversing the associations
313 struct cgrp_cset_link
{
314 /* the cgroup and css_set this link associates */
316 struct css_set
*cset
;
318 /* list of cgrp_cset_links anchored at cgrp->cset_links */
319 struct list_head cset_link
;
321 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
322 struct list_head cgrp_link
;
325 /* The default css_set - used by init and its children prior to any
326 * hierarchies being mounted. It contains a pointer to the root state
327 * for each subsystem. Also used to anchor the list of css_sets. Not
328 * reference-counted, to improve performance when child cgroups
329 * haven't been created.
332 static struct css_set init_css_set
;
333 static struct cgrp_cset_link init_cgrp_cset_link
;
336 * css_set_lock protects the list of css_set objects, and the chain of
337 * tasks off each css_set. Nests outside task->alloc_lock due to
338 * css_task_iter_start().
340 static DEFINE_RWLOCK(css_set_lock
);
341 static int css_set_count
;
344 * hash table for cgroup groups. This improves the performance to find
345 * an existing css_set. This hash doesn't (currently) take into
346 * account cgroups in empty hierarchies.
348 #define CSS_SET_HASH_BITS 7
349 static DEFINE_HASHTABLE(css_set_table
, CSS_SET_HASH_BITS
);
351 static unsigned long css_set_hash(struct cgroup_subsys_state
*css
[])
353 unsigned long key
= 0UL;
354 struct cgroup_subsys
*ss
;
357 for_each_subsys(ss
, i
)
358 key
+= (unsigned long)css
[i
];
359 key
= (key
>> 16) ^ key
;
365 * We don't maintain the lists running through each css_set to its task
366 * until after the first call to css_task_iter_start(). This reduces the
367 * fork()/exit() overhead for people who have cgroups compiled into their
368 * kernel but not actually in use.
370 static int use_task_css_set_links __read_mostly
;
372 static void __put_css_set(struct css_set
*cset
, int taskexit
)
374 struct cgrp_cset_link
*link
, *tmp_link
;
377 * Ensure that the refcount doesn't hit zero while any readers
378 * can see it. Similar to atomic_dec_and_lock(), but for an
381 if (atomic_add_unless(&cset
->refcount
, -1, 1))
383 write_lock(&css_set_lock
);
384 if (!atomic_dec_and_test(&cset
->refcount
)) {
385 write_unlock(&css_set_lock
);
389 /* This css_set is dead. unlink it and release cgroup refcounts */
390 hash_del(&cset
->hlist
);
393 list_for_each_entry_safe(link
, tmp_link
, &cset
->cgrp_links
, cgrp_link
) {
394 struct cgroup
*cgrp
= link
->cgrp
;
396 list_del(&link
->cset_link
);
397 list_del(&link
->cgrp_link
);
399 /* @cgrp can't go away while we're holding css_set_lock */
400 if (list_empty(&cgrp
->cset_links
) && notify_on_release(cgrp
)) {
402 set_bit(CGRP_RELEASABLE
, &cgrp
->flags
);
403 check_for_release(cgrp
);
409 write_unlock(&css_set_lock
);
410 kfree_rcu(cset
, rcu_head
);
414 * refcounted get/put for css_set objects
416 static inline void get_css_set(struct css_set
*cset
)
418 atomic_inc(&cset
->refcount
);
421 static inline void put_css_set(struct css_set
*cset
)
423 __put_css_set(cset
, 0);
426 static inline void put_css_set_taskexit(struct css_set
*cset
)
428 __put_css_set(cset
, 1);
432 * compare_css_sets - helper function for find_existing_css_set().
433 * @cset: candidate css_set being tested
434 * @old_cset: existing css_set for a task
435 * @new_cgrp: cgroup that's being entered by the task
436 * @template: desired set of css pointers in css_set (pre-calculated)
438 * Returns true if "cset" matches "old_cset" except for the hierarchy
439 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
441 static bool compare_css_sets(struct css_set
*cset
,
442 struct css_set
*old_cset
,
443 struct cgroup
*new_cgrp
,
444 struct cgroup_subsys_state
*template[])
446 struct list_head
*l1
, *l2
;
448 if (memcmp(template, cset
->subsys
, sizeof(cset
->subsys
))) {
449 /* Not all subsystems matched */
454 * Compare cgroup pointers in order to distinguish between
455 * different cgroups in heirarchies with no subsystems. We
456 * could get by with just this check alone (and skip the
457 * memcmp above) but on most setups the memcmp check will
458 * avoid the need for this more expensive check on almost all
462 l1
= &cset
->cgrp_links
;
463 l2
= &old_cset
->cgrp_links
;
465 struct cgrp_cset_link
*link1
, *link2
;
466 struct cgroup
*cgrp1
, *cgrp2
;
470 /* See if we reached the end - both lists are equal length. */
471 if (l1
== &cset
->cgrp_links
) {
472 BUG_ON(l2
!= &old_cset
->cgrp_links
);
475 BUG_ON(l2
== &old_cset
->cgrp_links
);
477 /* Locate the cgroups associated with these links. */
478 link1
= list_entry(l1
, struct cgrp_cset_link
, cgrp_link
);
479 link2
= list_entry(l2
, struct cgrp_cset_link
, cgrp_link
);
482 /* Hierarchies should be linked in the same order. */
483 BUG_ON(cgrp1
->root
!= cgrp2
->root
);
486 * If this hierarchy is the hierarchy of the cgroup
487 * that's changing, then we need to check that this
488 * css_set points to the new cgroup; if it's any other
489 * hierarchy, then this css_set should point to the
490 * same cgroup as the old css_set.
492 if (cgrp1
->root
== new_cgrp
->root
) {
493 if (cgrp1
!= new_cgrp
)
504 * find_existing_css_set - init css array and find the matching css_set
505 * @old_cset: the css_set that we're using before the cgroup transition
506 * @cgrp: the cgroup that we're moving into
507 * @template: out param for the new set of csses, should be clear on entry
509 static struct css_set
*find_existing_css_set(struct css_set
*old_cset
,
511 struct cgroup_subsys_state
*template[])
513 struct cgroupfs_root
*root
= cgrp
->root
;
514 struct cgroup_subsys
*ss
;
515 struct css_set
*cset
;
520 * Build the set of subsystem state objects that we want to see in the
521 * new css_set. while subsystems can change globally, the entries here
522 * won't change, so no need for locking.
524 for_each_subsys(ss
, i
) {
525 if (root
->subsys_mask
& (1UL << i
)) {
526 /* Subsystem is in this hierarchy. So we want
527 * the subsystem state from the new
529 template[i
] = cgroup_css(cgrp
, ss
);
531 /* Subsystem is not in this hierarchy, so we
532 * don't want to change the subsystem state */
533 template[i
] = old_cset
->subsys
[i
];
537 key
= css_set_hash(template);
538 hash_for_each_possible(css_set_table
, cset
, hlist
, key
) {
539 if (!compare_css_sets(cset
, old_cset
, cgrp
, template))
542 /* This css_set matches what we need */
546 /* No existing cgroup group matched */
550 static void free_cgrp_cset_links(struct list_head
*links_to_free
)
552 struct cgrp_cset_link
*link
, *tmp_link
;
554 list_for_each_entry_safe(link
, tmp_link
, links_to_free
, cset_link
) {
555 list_del(&link
->cset_link
);
561 * allocate_cgrp_cset_links - allocate cgrp_cset_links
562 * @count: the number of links to allocate
563 * @tmp_links: list_head the allocated links are put on
565 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
566 * through ->cset_link. Returns 0 on success or -errno.
568 static int allocate_cgrp_cset_links(int count
, struct list_head
*tmp_links
)
570 struct cgrp_cset_link
*link
;
573 INIT_LIST_HEAD(tmp_links
);
575 for (i
= 0; i
< count
; i
++) {
576 link
= kzalloc(sizeof(*link
), GFP_KERNEL
);
578 free_cgrp_cset_links(tmp_links
);
581 list_add(&link
->cset_link
, tmp_links
);
587 * link_css_set - a helper function to link a css_set to a cgroup
588 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
589 * @cset: the css_set to be linked
590 * @cgrp: the destination cgroup
592 static void link_css_set(struct list_head
*tmp_links
, struct css_set
*cset
,
595 struct cgrp_cset_link
*link
;
597 BUG_ON(list_empty(tmp_links
));
598 link
= list_first_entry(tmp_links
, struct cgrp_cset_link
, cset_link
);
601 list_move(&link
->cset_link
, &cgrp
->cset_links
);
603 * Always add links to the tail of the list so that the list
604 * is sorted by order of hierarchy creation
606 list_add_tail(&link
->cgrp_link
, &cset
->cgrp_links
);
610 * find_css_set - return a new css_set with one cgroup updated
611 * @old_cset: the baseline css_set
612 * @cgrp: the cgroup to be updated
614 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
615 * substituted into the appropriate hierarchy.
617 static struct css_set
*find_css_set(struct css_set
*old_cset
,
620 struct cgroup_subsys_state
*template[CGROUP_SUBSYS_COUNT
] = { };
621 struct css_set
*cset
;
622 struct list_head tmp_links
;
623 struct cgrp_cset_link
*link
;
626 lockdep_assert_held(&cgroup_mutex
);
628 /* First see if we already have a cgroup group that matches
630 read_lock(&css_set_lock
);
631 cset
= find_existing_css_set(old_cset
, cgrp
, template);
634 read_unlock(&css_set_lock
);
639 cset
= kzalloc(sizeof(*cset
), GFP_KERNEL
);
643 /* Allocate all the cgrp_cset_link objects that we'll need */
644 if (allocate_cgrp_cset_links(cgroup_root_count
, &tmp_links
) < 0) {
649 atomic_set(&cset
->refcount
, 1);
650 INIT_LIST_HEAD(&cset
->cgrp_links
);
651 INIT_LIST_HEAD(&cset
->tasks
);
652 INIT_HLIST_NODE(&cset
->hlist
);
654 /* Copy the set of subsystem state objects generated in
655 * find_existing_css_set() */
656 memcpy(cset
->subsys
, template, sizeof(cset
->subsys
));
658 write_lock(&css_set_lock
);
659 /* Add reference counts and links from the new css_set. */
660 list_for_each_entry(link
, &old_cset
->cgrp_links
, cgrp_link
) {
661 struct cgroup
*c
= link
->cgrp
;
663 if (c
->root
== cgrp
->root
)
665 link_css_set(&tmp_links
, cset
, c
);
668 BUG_ON(!list_empty(&tmp_links
));
672 /* Add this cgroup group to the hash table */
673 key
= css_set_hash(cset
->subsys
);
674 hash_add(css_set_table
, &cset
->hlist
, key
);
676 write_unlock(&css_set_lock
);
682 * Return the cgroup for "task" from the given hierarchy. Must be
683 * called with cgroup_mutex held.
685 static struct cgroup
*task_cgroup_from_root(struct task_struct
*task
,
686 struct cgroupfs_root
*root
)
688 struct css_set
*cset
;
689 struct cgroup
*res
= NULL
;
691 BUG_ON(!mutex_is_locked(&cgroup_mutex
));
692 read_lock(&css_set_lock
);
694 * No need to lock the task - since we hold cgroup_mutex the
695 * task can't change groups, so the only thing that can happen
696 * is that it exits and its css is set back to init_css_set.
698 cset
= task_css_set(task
);
699 if (cset
== &init_css_set
) {
700 res
= &root
->top_cgroup
;
702 struct cgrp_cset_link
*link
;
704 list_for_each_entry(link
, &cset
->cgrp_links
, cgrp_link
) {
705 struct cgroup
*c
= link
->cgrp
;
707 if (c
->root
== root
) {
713 read_unlock(&css_set_lock
);
719 * There is one global cgroup mutex. We also require taking
720 * task_lock() when dereferencing a task's cgroup subsys pointers.
721 * See "The task_lock() exception", at the end of this comment.
723 * A task must hold cgroup_mutex to modify cgroups.
725 * Any task can increment and decrement the count field without lock.
726 * So in general, code holding cgroup_mutex can't rely on the count
727 * field not changing. However, if the count goes to zero, then only
728 * cgroup_attach_task() can increment it again. Because a count of zero
729 * means that no tasks are currently attached, therefore there is no
730 * way a task attached to that cgroup can fork (the other way to
731 * increment the count). So code holding cgroup_mutex can safely
732 * assume that if the count is zero, it will stay zero. Similarly, if
733 * a task holds cgroup_mutex on a cgroup with zero count, it
734 * knows that the cgroup won't be removed, as cgroup_rmdir()
737 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
738 * (usually) take cgroup_mutex. These are the two most performance
739 * critical pieces of code here. The exception occurs on cgroup_exit(),
740 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
741 * is taken, and if the cgroup count is zero, a usermode call made
742 * to the release agent with the name of the cgroup (path relative to
743 * the root of cgroup file system) as the argument.
745 * A cgroup can only be deleted if both its 'count' of using tasks
746 * is zero, and its list of 'children' cgroups is empty. Since all
747 * tasks in the system use _some_ cgroup, and since there is always at
748 * least one task in the system (init, pid == 1), therefore, top_cgroup
749 * always has either children cgroups and/or using tasks. So we don't
750 * need a special hack to ensure that top_cgroup cannot be deleted.
752 * The task_lock() exception
754 * The need for this exception arises from the action of
755 * cgroup_attach_task(), which overwrites one task's cgroup pointer with
756 * another. It does so using cgroup_mutex, however there are
757 * several performance critical places that need to reference
758 * task->cgroup without the expense of grabbing a system global
759 * mutex. Therefore except as noted below, when dereferencing or, as
760 * in cgroup_attach_task(), modifying a task's cgroup pointer we use
761 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
762 * the task_struct routinely used for such matters.
764 * P.S. One more locking exception. RCU is used to guard the
765 * update of a tasks cgroup pointer by cgroup_attach_task()
769 * A couple of forward declarations required, due to cyclic reference loop:
770 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
771 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
775 static int cgroup_mkdir(struct inode
*dir
, struct dentry
*dentry
, umode_t mode
);
776 static int cgroup_rmdir(struct inode
*unused_dir
, struct dentry
*dentry
);
777 static int cgroup_populate_dir(struct cgroup
*cgrp
, unsigned long subsys_mask
);
778 static const struct inode_operations cgroup_dir_inode_operations
;
779 static const struct file_operations proc_cgroupstats_operations
;
781 static struct backing_dev_info cgroup_backing_dev_info
= {
783 .capabilities
= BDI_CAP_NO_ACCT_AND_WRITEBACK
,
786 static struct inode
*cgroup_new_inode(umode_t mode
, struct super_block
*sb
)
788 struct inode
*inode
= new_inode(sb
);
791 inode
->i_ino
= get_next_ino();
792 inode
->i_mode
= mode
;
793 inode
->i_uid
= current_fsuid();
794 inode
->i_gid
= current_fsgid();
795 inode
->i_atime
= inode
->i_mtime
= inode
->i_ctime
= CURRENT_TIME
;
796 inode
->i_mapping
->backing_dev_info
= &cgroup_backing_dev_info
;
801 static struct cgroup_name
*cgroup_alloc_name(struct dentry
*dentry
)
803 struct cgroup_name
*name
;
805 name
= kmalloc(sizeof(*name
) + dentry
->d_name
.len
+ 1, GFP_KERNEL
);
808 strcpy(name
->name
, dentry
->d_name
.name
);
812 static void cgroup_free_fn(struct work_struct
*work
)
814 struct cgroup
*cgrp
= container_of(work
, struct cgroup
, destroy_work
);
816 mutex_lock(&cgroup_mutex
);
817 cgrp
->root
->number_of_cgroups
--;
818 mutex_unlock(&cgroup_mutex
);
821 * We get a ref to the parent's dentry, and put the ref when
822 * this cgroup is being freed, so it's guaranteed that the
823 * parent won't be destroyed before its children.
825 dput(cgrp
->parent
->dentry
);
828 * Drop the active superblock reference that we took when we
829 * created the cgroup. This will free cgrp->root, if we are
830 * holding the last reference to @sb.
832 deactivate_super(cgrp
->root
->sb
);
834 cgroup_pidlist_destroy_all(cgrp
);
836 simple_xattrs_free(&cgrp
->xattrs
);
838 kfree(rcu_dereference_raw(cgrp
->name
));
842 static void cgroup_free_rcu(struct rcu_head
*head
)
844 struct cgroup
*cgrp
= container_of(head
, struct cgroup
, rcu_head
);
846 INIT_WORK(&cgrp
->destroy_work
, cgroup_free_fn
);
847 queue_work(cgroup_destroy_wq
, &cgrp
->destroy_work
);
850 static void cgroup_diput(struct dentry
*dentry
, struct inode
*inode
)
852 /* is dentry a directory ? if so, kfree() associated cgroup */
853 if (S_ISDIR(inode
->i_mode
)) {
854 struct cgroup
*cgrp
= dentry
->d_fsdata
;
856 BUG_ON(!(cgroup_is_dead(cgrp
)));
857 call_rcu(&cgrp
->rcu_head
, cgroup_free_rcu
);
859 struct cfent
*cfe
= __d_cfe(dentry
);
860 struct cgroup
*cgrp
= dentry
->d_parent
->d_fsdata
;
862 WARN_ONCE(!list_empty(&cfe
->node
) &&
863 cgrp
!= &cgrp
->root
->top_cgroup
,
864 "cfe still linked for %s\n", cfe
->type
->name
);
865 simple_xattrs_free(&cfe
->xattrs
);
871 static void remove_dir(struct dentry
*d
)
873 struct dentry
*parent
= dget(d
->d_parent
);
876 simple_rmdir(parent
->d_inode
, d
);
880 static void cgroup_rm_file(struct cgroup
*cgrp
, const struct cftype
*cft
)
884 lockdep_assert_held(&cgrp
->dentry
->d_inode
->i_mutex
);
885 lockdep_assert_held(&cgroup_mutex
);
888 * If we're doing cleanup due to failure of cgroup_create(),
889 * the corresponding @cfe may not exist.
891 list_for_each_entry(cfe
, &cgrp
->files
, node
) {
892 struct dentry
*d
= cfe
->dentry
;
894 if (cft
&& cfe
->type
!= cft
)
899 simple_unlink(cgrp
->dentry
->d_inode
, d
);
900 list_del_init(&cfe
->node
);
908 * cgroup_clear_dir - remove subsys files in a cgroup directory
909 * @cgrp: target cgroup
910 * @subsys_mask: mask of the subsystem ids whose files should be removed
912 static void cgroup_clear_dir(struct cgroup
*cgrp
, unsigned long subsys_mask
)
914 struct cgroup_subsys
*ss
;
917 for_each_subsys(ss
, i
) {
918 struct cftype_set
*set
;
920 if (!test_bit(i
, &subsys_mask
))
922 list_for_each_entry(set
, &ss
->cftsets
, node
)
923 cgroup_addrm_files(cgrp
, set
->cfts
, false);
928 * NOTE : the dentry must have been dget()'ed
930 static void cgroup_d_remove_dir(struct dentry
*dentry
)
932 struct dentry
*parent
;
934 parent
= dentry
->d_parent
;
935 spin_lock(&parent
->d_lock
);
936 spin_lock_nested(&dentry
->d_lock
, DENTRY_D_LOCK_NESTED
);
937 list_del_init(&dentry
->d_u
.d_child
);
938 spin_unlock(&dentry
->d_lock
);
939 spin_unlock(&parent
->d_lock
);
944 * Call with cgroup_mutex held. Drops reference counts on modules, including
945 * any duplicate ones that parse_cgroupfs_options took. If this function
946 * returns an error, no reference counts are touched.
948 static int rebind_subsystems(struct cgroupfs_root
*root
,
949 unsigned long added_mask
, unsigned removed_mask
)
951 struct cgroup
*cgrp
= &root
->top_cgroup
;
952 struct cgroup_subsys
*ss
;
953 unsigned long pinned
= 0;
956 BUG_ON(!mutex_is_locked(&cgroup_mutex
));
957 BUG_ON(!mutex_is_locked(&cgroup_root_mutex
));
959 /* Check that any added subsystems are currently free */
960 for_each_subsys(ss
, i
) {
961 if (!(added_mask
& (1 << i
)))
964 /* is the subsystem mounted elsewhere? */
965 if (ss
->root
!= &cgroup_dummy_root
) {
971 if (!try_module_get(ss
->module
)) {
978 /* subsys could be missing if unloaded between parsing and here */
979 if (added_mask
!= pinned
) {
984 ret
= cgroup_populate_dir(cgrp
, added_mask
);
989 * Nothing can fail from this point on. Remove files for the
990 * removed subsystems and rebind each subsystem.
992 cgroup_clear_dir(cgrp
, removed_mask
);
994 for_each_subsys(ss
, i
) {
995 unsigned long bit
= 1UL << i
;
997 if (bit
& added_mask
) {
998 /* We're binding this subsystem to this hierarchy */
999 BUG_ON(cgroup_css(cgrp
, ss
));
1000 BUG_ON(!cgroup_css(cgroup_dummy_top
, ss
));
1001 BUG_ON(cgroup_css(cgroup_dummy_top
, ss
)->cgroup
!= cgroup_dummy_top
);
1003 rcu_assign_pointer(cgrp
->subsys
[i
],
1004 cgroup_css(cgroup_dummy_top
, ss
));
1005 cgroup_css(cgrp
, ss
)->cgroup
= cgrp
;
1007 list_move(&ss
->sibling
, &root
->subsys_list
);
1010 ss
->bind(cgroup_css(cgrp
, ss
));
1012 /* refcount was already taken, and we're keeping it */
1013 root
->subsys_mask
|= bit
;
1014 } else if (bit
& removed_mask
) {
1015 /* We're removing this subsystem */
1016 BUG_ON(cgroup_css(cgrp
, ss
) != cgroup_css(cgroup_dummy_top
, ss
));
1017 BUG_ON(cgroup_css(cgrp
, ss
)->cgroup
!= cgrp
);
1020 ss
->bind(cgroup_css(cgroup_dummy_top
, ss
));
1022 cgroup_css(cgroup_dummy_top
, ss
)->cgroup
= cgroup_dummy_top
;
1023 RCU_INIT_POINTER(cgrp
->subsys
[i
], NULL
);
1025 cgroup_subsys
[i
]->root
= &cgroup_dummy_root
;
1026 list_move(&ss
->sibling
, &cgroup_dummy_root
.subsys_list
);
1028 /* subsystem is now free - drop reference on module */
1029 module_put(ss
->module
);
1030 root
->subsys_mask
&= ~bit
;
1035 * Mark @root has finished binding subsystems. @root->subsys_mask
1036 * now matches the bound subsystems.
1038 root
->flags
|= CGRP_ROOT_SUBSYS_BOUND
;
1043 for_each_subsys(ss
, i
)
1044 if (pinned
& (1 << i
))
1045 module_put(ss
->module
);
1049 static int cgroup_show_options(struct seq_file
*seq
, struct dentry
*dentry
)
1051 struct cgroupfs_root
*root
= dentry
->d_sb
->s_fs_info
;
1052 struct cgroup_subsys
*ss
;
1054 mutex_lock(&cgroup_root_mutex
);
1055 for_each_root_subsys(root
, ss
)
1056 seq_printf(seq
, ",%s", ss
->name
);
1057 if (root
->flags
& CGRP_ROOT_SANE_BEHAVIOR
)
1058 seq_puts(seq
, ",sane_behavior");
1059 if (root
->flags
& CGRP_ROOT_NOPREFIX
)
1060 seq_puts(seq
, ",noprefix");
1061 if (root
->flags
& CGRP_ROOT_XATTR
)
1062 seq_puts(seq
, ",xattr");
1063 if (strlen(root
->release_agent_path
))
1064 seq_printf(seq
, ",release_agent=%s", root
->release_agent_path
);
1065 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN
, &root
->top_cgroup
.flags
))
1066 seq_puts(seq
, ",clone_children");
1067 if (strlen(root
->name
))
1068 seq_printf(seq
, ",name=%s", root
->name
);
1069 mutex_unlock(&cgroup_root_mutex
);
1073 struct cgroup_sb_opts
{
1074 unsigned long subsys_mask
;
1075 unsigned long flags
;
1076 char *release_agent
;
1077 bool cpuset_clone_children
;
1079 /* User explicitly requested empty subsystem */
1082 struct cgroupfs_root
*new_root
;
1087 * Convert a hierarchy specifier into a bitmask of subsystems and
1088 * flags. Call with cgroup_mutex held to protect the cgroup_subsys[]
1089 * array. This function takes refcounts on subsystems to be used, unless it
1090 * returns error, in which case no refcounts are taken.
1092 static int parse_cgroupfs_options(char *data
, struct cgroup_sb_opts
*opts
)
1094 char *token
, *o
= data
;
1095 bool all_ss
= false, one_ss
= false;
1096 unsigned long mask
= (unsigned long)-1;
1097 struct cgroup_subsys
*ss
;
1100 BUG_ON(!mutex_is_locked(&cgroup_mutex
));
1102 #ifdef CONFIG_CPUSETS
1103 mask
= ~(1UL << cpuset_subsys_id
);
1106 memset(opts
, 0, sizeof(*opts
));
1108 while ((token
= strsep(&o
, ",")) != NULL
) {
1111 if (!strcmp(token
, "none")) {
1112 /* Explicitly have no subsystems */
1116 if (!strcmp(token
, "all")) {
1117 /* Mutually exclusive option 'all' + subsystem name */
1123 if (!strcmp(token
, "__DEVEL__sane_behavior")) {
1124 opts
->flags
|= CGRP_ROOT_SANE_BEHAVIOR
;
1127 if (!strcmp(token
, "noprefix")) {
1128 opts
->flags
|= CGRP_ROOT_NOPREFIX
;
1131 if (!strcmp(token
, "clone_children")) {
1132 opts
->cpuset_clone_children
= true;
1135 if (!strcmp(token
, "xattr")) {
1136 opts
->flags
|= CGRP_ROOT_XATTR
;
1139 if (!strncmp(token
, "release_agent=", 14)) {
1140 /* Specifying two release agents is forbidden */
1141 if (opts
->release_agent
)
1143 opts
->release_agent
=
1144 kstrndup(token
+ 14, PATH_MAX
- 1, GFP_KERNEL
);
1145 if (!opts
->release_agent
)
1149 if (!strncmp(token
, "name=", 5)) {
1150 const char *name
= token
+ 5;
1151 /* Can't specify an empty name */
1154 /* Must match [\w.-]+ */
1155 for (i
= 0; i
< strlen(name
); i
++) {
1159 if ((c
== '.') || (c
== '-') || (c
== '_'))
1163 /* Specifying two names is forbidden */
1166 opts
->name
= kstrndup(name
,
1167 MAX_CGROUP_ROOT_NAMELEN
- 1,
1175 for_each_subsys(ss
, i
) {
1176 if (strcmp(token
, ss
->name
))
1181 /* Mutually exclusive option 'all' + subsystem name */
1184 set_bit(i
, &opts
->subsys_mask
);
1189 if (i
== CGROUP_SUBSYS_COUNT
)
1194 * If the 'all' option was specified select all the subsystems,
1195 * otherwise if 'none', 'name=' and a subsystem name options
1196 * were not specified, let's default to 'all'
1198 if (all_ss
|| (!one_ss
&& !opts
->none
&& !opts
->name
))
1199 for_each_subsys(ss
, i
)
1201 set_bit(i
, &opts
->subsys_mask
);
1203 /* Consistency checks */
1205 if (opts
->flags
& CGRP_ROOT_SANE_BEHAVIOR
) {
1206 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1208 if (opts
->flags
& CGRP_ROOT_NOPREFIX
) {
1209 pr_err("cgroup: sane_behavior: noprefix is not allowed\n");
1213 if (opts
->cpuset_clone_children
) {
1214 pr_err("cgroup: sane_behavior: clone_children is not allowed\n");
1220 * Option noprefix was introduced just for backward compatibility
1221 * with the old cpuset, so we allow noprefix only if mounting just
1222 * the cpuset subsystem.
1224 if ((opts
->flags
& CGRP_ROOT_NOPREFIX
) && (opts
->subsys_mask
& mask
))
1228 /* Can't specify "none" and some subsystems */
1229 if (opts
->subsys_mask
&& opts
->none
)
1233 * We either have to specify by name or by subsystems. (So all
1234 * empty hierarchies must have a name).
1236 if (!opts
->subsys_mask
&& !opts
->name
)
1242 static int cgroup_remount(struct super_block
*sb
, int *flags
, char *data
)
1245 struct cgroupfs_root
*root
= sb
->s_fs_info
;
1246 struct cgroup
*cgrp
= &root
->top_cgroup
;
1247 struct cgroup_sb_opts opts
;
1248 unsigned long added_mask
, removed_mask
;
1250 if (root
->flags
& CGRP_ROOT_SANE_BEHAVIOR
) {
1251 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1255 mutex_lock(&cgrp
->dentry
->d_inode
->i_mutex
);
1256 mutex_lock(&cgroup_mutex
);
1257 mutex_lock(&cgroup_root_mutex
);
1259 /* See what subsystems are wanted */
1260 ret
= parse_cgroupfs_options(data
, &opts
);
1264 if (opts
.subsys_mask
!= root
->subsys_mask
|| opts
.release_agent
)
1265 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1266 task_tgid_nr(current
), current
->comm
);
1268 added_mask
= opts
.subsys_mask
& ~root
->subsys_mask
;
1269 removed_mask
= root
->subsys_mask
& ~opts
.subsys_mask
;
1271 /* Don't allow flags or name to change at remount */
1272 if (((opts
.flags
^ root
->flags
) & CGRP_ROOT_OPTION_MASK
) ||
1273 (opts
.name
&& strcmp(opts
.name
, root
->name
))) {
1274 pr_err("cgroup: option or name mismatch, new: 0x%lx \"%s\", old: 0x%lx \"%s\"\n",
1275 opts
.flags
& CGRP_ROOT_OPTION_MASK
, opts
.name
?: "",
1276 root
->flags
& CGRP_ROOT_OPTION_MASK
, root
->name
);
1281 /* remounting is not allowed for populated hierarchies */
1282 if (root
->number_of_cgroups
> 1) {
1287 ret
= rebind_subsystems(root
, added_mask
, removed_mask
);
1291 if (opts
.release_agent
)
1292 strcpy(root
->release_agent_path
, opts
.release_agent
);
1294 kfree(opts
.release_agent
);
1296 mutex_unlock(&cgroup_root_mutex
);
1297 mutex_unlock(&cgroup_mutex
);
1298 mutex_unlock(&cgrp
->dentry
->d_inode
->i_mutex
);
1302 static const struct super_operations cgroup_ops
= {
1303 .statfs
= simple_statfs
,
1304 .drop_inode
= generic_delete_inode
,
1305 .show_options
= cgroup_show_options
,
1306 .remount_fs
= cgroup_remount
,
1309 static void init_cgroup_housekeeping(struct cgroup
*cgrp
)
1311 INIT_LIST_HEAD(&cgrp
->sibling
);
1312 INIT_LIST_HEAD(&cgrp
->children
);
1313 INIT_LIST_HEAD(&cgrp
->files
);
1314 INIT_LIST_HEAD(&cgrp
->cset_links
);
1315 INIT_LIST_HEAD(&cgrp
->release_list
);
1316 INIT_LIST_HEAD(&cgrp
->pidlists
);
1317 mutex_init(&cgrp
->pidlist_mutex
);
1318 cgrp
->dummy_css
.cgroup
= cgrp
;
1319 simple_xattrs_init(&cgrp
->xattrs
);
1322 static void init_cgroup_root(struct cgroupfs_root
*root
)
1324 struct cgroup
*cgrp
= &root
->top_cgroup
;
1326 INIT_LIST_HEAD(&root
->subsys_list
);
1327 INIT_LIST_HEAD(&root
->root_list
);
1328 root
->number_of_cgroups
= 1;
1330 RCU_INIT_POINTER(cgrp
->name
, &root_cgroup_name
);
1331 init_cgroup_housekeeping(cgrp
);
1332 idr_init(&root
->cgroup_idr
);
1335 static int cgroup_init_root_id(struct cgroupfs_root
*root
, int start
, int end
)
1339 lockdep_assert_held(&cgroup_mutex
);
1340 lockdep_assert_held(&cgroup_root_mutex
);
1342 id
= idr_alloc_cyclic(&cgroup_hierarchy_idr
, root
, start
, end
,
1347 root
->hierarchy_id
= id
;
1351 static void cgroup_exit_root_id(struct cgroupfs_root
*root
)
1353 lockdep_assert_held(&cgroup_mutex
);
1354 lockdep_assert_held(&cgroup_root_mutex
);
1356 if (root
->hierarchy_id
) {
1357 idr_remove(&cgroup_hierarchy_idr
, root
->hierarchy_id
);
1358 root
->hierarchy_id
= 0;
1362 static int cgroup_test_super(struct super_block
*sb
, void *data
)
1364 struct cgroup_sb_opts
*opts
= data
;
1365 struct cgroupfs_root
*root
= sb
->s_fs_info
;
1367 /* If we asked for a name then it must match */
1368 if (opts
->name
&& strcmp(opts
->name
, root
->name
))
1372 * If we asked for subsystems (or explicitly for no
1373 * subsystems) then they must match
1375 if ((opts
->subsys_mask
|| opts
->none
)
1376 && (opts
->subsys_mask
!= root
->subsys_mask
))
1382 static struct cgroupfs_root
*cgroup_root_from_opts(struct cgroup_sb_opts
*opts
)
1384 struct cgroupfs_root
*root
;
1386 if (!opts
->subsys_mask
&& !opts
->none
)
1389 root
= kzalloc(sizeof(*root
), GFP_KERNEL
);
1391 return ERR_PTR(-ENOMEM
);
1393 init_cgroup_root(root
);
1396 * We need to set @root->subsys_mask now so that @root can be
1397 * matched by cgroup_test_super() before it finishes
1398 * initialization; otherwise, competing mounts with the same
1399 * options may try to bind the same subsystems instead of waiting
1400 * for the first one leading to unexpected mount errors.
1401 * SUBSYS_BOUND will be set once actual binding is complete.
1403 root
->subsys_mask
= opts
->subsys_mask
;
1404 root
->flags
= opts
->flags
;
1405 if (opts
->release_agent
)
1406 strcpy(root
->release_agent_path
, opts
->release_agent
);
1408 strcpy(root
->name
, opts
->name
);
1409 if (opts
->cpuset_clone_children
)
1410 set_bit(CGRP_CPUSET_CLONE_CHILDREN
, &root
->top_cgroup
.flags
);
1414 static void cgroup_free_root(struct cgroupfs_root
*root
)
1417 /* hierarhcy ID shoulid already have been released */
1418 WARN_ON_ONCE(root
->hierarchy_id
);
1420 idr_destroy(&root
->cgroup_idr
);
1425 static int cgroup_set_super(struct super_block
*sb
, void *data
)
1428 struct cgroup_sb_opts
*opts
= data
;
1430 /* If we don't have a new root, we can't set up a new sb */
1431 if (!opts
->new_root
)
1434 BUG_ON(!opts
->subsys_mask
&& !opts
->none
);
1436 ret
= set_anon_super(sb
, NULL
);
1440 sb
->s_fs_info
= opts
->new_root
;
1441 opts
->new_root
->sb
= sb
;
1443 sb
->s_blocksize
= PAGE_CACHE_SIZE
;
1444 sb
->s_blocksize_bits
= PAGE_CACHE_SHIFT
;
1445 sb
->s_magic
= CGROUP_SUPER_MAGIC
;
1446 sb
->s_op
= &cgroup_ops
;
1451 static int cgroup_get_rootdir(struct super_block
*sb
)
1453 static const struct dentry_operations cgroup_dops
= {
1454 .d_iput
= cgroup_diput
,
1455 .d_delete
= always_delete_dentry
,
1458 struct inode
*inode
=
1459 cgroup_new_inode(S_IFDIR
| S_IRUGO
| S_IXUGO
| S_IWUSR
, sb
);
1464 inode
->i_fop
= &simple_dir_operations
;
1465 inode
->i_op
= &cgroup_dir_inode_operations
;
1466 /* directories start off with i_nlink == 2 (for "." entry) */
1468 sb
->s_root
= d_make_root(inode
);
1471 /* for everything else we want ->d_op set */
1472 sb
->s_d_op
= &cgroup_dops
;
1476 static struct dentry
*cgroup_mount(struct file_system_type
*fs_type
,
1477 int flags
, const char *unused_dev_name
,
1480 struct cgroup_sb_opts opts
;
1481 struct cgroupfs_root
*root
;
1483 struct super_block
*sb
;
1484 struct cgroupfs_root
*new_root
;
1485 struct list_head tmp_links
;
1486 struct inode
*inode
;
1487 const struct cred
*cred
;
1489 /* First find the desired set of subsystems */
1490 mutex_lock(&cgroup_mutex
);
1491 ret
= parse_cgroupfs_options(data
, &opts
);
1492 mutex_unlock(&cgroup_mutex
);
1497 * Allocate a new cgroup root. We may not need it if we're
1498 * reusing an existing hierarchy.
1500 new_root
= cgroup_root_from_opts(&opts
);
1501 if (IS_ERR(new_root
)) {
1502 ret
= PTR_ERR(new_root
);
1505 opts
.new_root
= new_root
;
1507 /* Locate an existing or new sb for this hierarchy */
1508 sb
= sget(fs_type
, cgroup_test_super
, cgroup_set_super
, 0, &opts
);
1511 cgroup_free_root(opts
.new_root
);
1515 root
= sb
->s_fs_info
;
1517 if (root
== opts
.new_root
) {
1518 /* We used the new root structure, so this is a new hierarchy */
1519 struct cgroup
*root_cgrp
= &root
->top_cgroup
;
1520 struct cgroupfs_root
*existing_root
;
1522 struct css_set
*cset
;
1524 BUG_ON(sb
->s_root
!= NULL
);
1526 ret
= cgroup_get_rootdir(sb
);
1528 goto drop_new_super
;
1529 inode
= sb
->s_root
->d_inode
;
1531 mutex_lock(&inode
->i_mutex
);
1532 mutex_lock(&cgroup_mutex
);
1533 mutex_lock(&cgroup_root_mutex
);
1535 root_cgrp
->id
= idr_alloc(&root
->cgroup_idr
, root_cgrp
,
1537 if (root_cgrp
->id
< 0)
1540 /* Check for name clashes with existing mounts */
1542 if (strlen(root
->name
))
1543 for_each_active_root(existing_root
)
1544 if (!strcmp(existing_root
->name
, root
->name
))
1548 * We're accessing css_set_count without locking
1549 * css_set_lock here, but that's OK - it can only be
1550 * increased by someone holding cgroup_lock, and
1551 * that's us. The worst that can happen is that we
1552 * have some link structures left over
1554 ret
= allocate_cgrp_cset_links(css_set_count
, &tmp_links
);
1558 /* ID 0 is reserved for dummy root, 1 for unified hierarchy */
1559 ret
= cgroup_init_root_id(root
, 2, 0);
1563 sb
->s_root
->d_fsdata
= root_cgrp
;
1564 root_cgrp
->dentry
= sb
->s_root
;
1567 * We're inside get_sb() and will call lookup_one_len() to
1568 * create the root files, which doesn't work if SELinux is
1569 * in use. The following cred dancing somehow works around
1570 * it. See 2ce9738ba ("cgroupfs: use init_cred when
1571 * populating new cgroupfs mount") for more details.
1573 cred
= override_creds(&init_cred
);
1575 ret
= cgroup_addrm_files(root_cgrp
, cgroup_base_files
, true);
1579 ret
= rebind_subsystems(root
, root
->subsys_mask
, 0);
1586 * There must be no failure case after here, since rebinding
1587 * takes care of subsystems' refcounts, which are explicitly
1588 * dropped in the failure exit path.
1591 list_add(&root
->root_list
, &cgroup_roots
);
1592 cgroup_root_count
++;
1594 /* Link the top cgroup in this hierarchy into all
1595 * the css_set objects */
1596 write_lock(&css_set_lock
);
1597 hash_for_each(css_set_table
, i
, cset
, hlist
)
1598 link_css_set(&tmp_links
, cset
, root_cgrp
);
1599 write_unlock(&css_set_lock
);
1601 free_cgrp_cset_links(&tmp_links
);
1603 BUG_ON(!list_empty(&root_cgrp
->children
));
1604 BUG_ON(root
->number_of_cgroups
!= 1);
1606 mutex_unlock(&cgroup_root_mutex
);
1607 mutex_unlock(&cgroup_mutex
);
1608 mutex_unlock(&inode
->i_mutex
);
1611 * We re-used an existing hierarchy - the new root (if
1612 * any) is not needed
1614 cgroup_free_root(opts
.new_root
);
1616 if ((root
->flags
^ opts
.flags
) & CGRP_ROOT_OPTION_MASK
) {
1617 if ((root
->flags
| opts
.flags
) & CGRP_ROOT_SANE_BEHAVIOR
) {
1618 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1620 goto drop_new_super
;
1622 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1627 kfree(opts
.release_agent
);
1629 return dget(sb
->s_root
);
1632 free_cgrp_cset_links(&tmp_links
);
1633 cgroup_addrm_files(&root
->top_cgroup
, cgroup_base_files
, false);
1636 cgroup_exit_root_id(root
);
1637 mutex_unlock(&cgroup_root_mutex
);
1638 mutex_unlock(&cgroup_mutex
);
1639 mutex_unlock(&inode
->i_mutex
);
1641 deactivate_locked_super(sb
);
1643 kfree(opts
.release_agent
);
1645 return ERR_PTR(ret
);
1648 static void cgroup_kill_sb(struct super_block
*sb
) {
1649 struct cgroupfs_root
*root
= sb
->s_fs_info
;
1650 struct cgroup
*cgrp
= &root
->top_cgroup
;
1651 struct cgrp_cset_link
*link
, *tmp_link
;
1656 BUG_ON(root
->number_of_cgroups
!= 1);
1657 BUG_ON(!list_empty(&cgrp
->children
));
1659 mutex_lock(&cgrp
->dentry
->d_inode
->i_mutex
);
1660 mutex_lock(&cgroup_mutex
);
1661 mutex_lock(&cgroup_root_mutex
);
1663 /* Rebind all subsystems back to the default hierarchy */
1664 if (root
->flags
& CGRP_ROOT_SUBSYS_BOUND
) {
1665 ret
= rebind_subsystems(root
, 0, root
->subsys_mask
);
1666 /* Shouldn't be able to fail ... */
1671 * Release all the links from cset_links to this hierarchy's
1674 write_lock(&css_set_lock
);
1676 list_for_each_entry_safe(link
, tmp_link
, &cgrp
->cset_links
, cset_link
) {
1677 list_del(&link
->cset_link
);
1678 list_del(&link
->cgrp_link
);
1681 write_unlock(&css_set_lock
);
1683 if (!list_empty(&root
->root_list
)) {
1684 list_del(&root
->root_list
);
1685 cgroup_root_count
--;
1688 cgroup_exit_root_id(root
);
1690 mutex_unlock(&cgroup_root_mutex
);
1691 mutex_unlock(&cgroup_mutex
);
1692 mutex_unlock(&cgrp
->dentry
->d_inode
->i_mutex
);
1694 simple_xattrs_free(&cgrp
->xattrs
);
1696 kill_litter_super(sb
);
1697 cgroup_free_root(root
);
1700 static struct file_system_type cgroup_fs_type
= {
1702 .mount
= cgroup_mount
,
1703 .kill_sb
= cgroup_kill_sb
,
1706 static struct kobject
*cgroup_kobj
;
1709 * cgroup_path - generate the path of a cgroup
1710 * @cgrp: the cgroup in question
1711 * @buf: the buffer to write the path into
1712 * @buflen: the length of the buffer
1714 * Writes path of cgroup into buf. Returns 0 on success, -errno on error.
1716 * We can't generate cgroup path using dentry->d_name, as accessing
1717 * dentry->name must be protected by irq-unsafe dentry->d_lock or parent
1718 * inode's i_mutex, while on the other hand cgroup_path() can be called
1719 * with some irq-safe spinlocks held.
1721 int cgroup_path(const struct cgroup
*cgrp
, char *buf
, int buflen
)
1723 int ret
= -ENAMETOOLONG
;
1726 if (!cgrp
->parent
) {
1727 if (strlcpy(buf
, "/", buflen
) >= buflen
)
1728 return -ENAMETOOLONG
;
1732 start
= buf
+ buflen
- 1;
1737 const char *name
= cgroup_name(cgrp
);
1741 if ((start
-= len
) < buf
)
1743 memcpy(start
, name
, len
);
1749 cgrp
= cgrp
->parent
;
1750 } while (cgrp
->parent
);
1752 memmove(buf
, start
, buf
+ buflen
- start
);
1757 EXPORT_SYMBOL_GPL(cgroup_path
);
1760 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1761 * @task: target task
1762 * @buf: the buffer to write the path into
1763 * @buflen: the length of the buffer
1765 * Determine @task's cgroup on the first (the one with the lowest non-zero
1766 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1767 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1768 * cgroup controller callbacks.
1770 * Returns 0 on success, fails with -%ENAMETOOLONG if @buflen is too short.
1772 int task_cgroup_path(struct task_struct
*task
, char *buf
, size_t buflen
)
1774 struct cgroupfs_root
*root
;
1775 struct cgroup
*cgrp
;
1776 int hierarchy_id
= 1, ret
= 0;
1779 return -ENAMETOOLONG
;
1781 mutex_lock(&cgroup_mutex
);
1783 root
= idr_get_next(&cgroup_hierarchy_idr
, &hierarchy_id
);
1786 cgrp
= task_cgroup_from_root(task
, root
);
1787 ret
= cgroup_path(cgrp
, buf
, buflen
);
1789 /* if no hierarchy exists, everyone is in "/" */
1790 memcpy(buf
, "/", 2);
1793 mutex_unlock(&cgroup_mutex
);
1796 EXPORT_SYMBOL_GPL(task_cgroup_path
);
1799 * Control Group taskset
1801 struct task_and_cgroup
{
1802 struct task_struct
*task
;
1803 struct cgroup
*cgrp
;
1804 struct css_set
*cset
;
1807 struct cgroup_taskset
{
1808 struct task_and_cgroup single
;
1809 struct flex_array
*tc_array
;
1812 struct cgroup
*cur_cgrp
;
1816 * cgroup_taskset_first - reset taskset and return the first task
1817 * @tset: taskset of interest
1819 * @tset iteration is initialized and the first task is returned.
1821 struct task_struct
*cgroup_taskset_first(struct cgroup_taskset
*tset
)
1823 if (tset
->tc_array
) {
1825 return cgroup_taskset_next(tset
);
1827 tset
->cur_cgrp
= tset
->single
.cgrp
;
1828 return tset
->single
.task
;
1831 EXPORT_SYMBOL_GPL(cgroup_taskset_first
);
1834 * cgroup_taskset_next - iterate to the next task in taskset
1835 * @tset: taskset of interest
1837 * Return the next task in @tset. Iteration must have been initialized
1838 * with cgroup_taskset_first().
1840 struct task_struct
*cgroup_taskset_next(struct cgroup_taskset
*tset
)
1842 struct task_and_cgroup
*tc
;
1844 if (!tset
->tc_array
|| tset
->idx
>= tset
->tc_array_len
)
1847 tc
= flex_array_get(tset
->tc_array
, tset
->idx
++);
1848 tset
->cur_cgrp
= tc
->cgrp
;
1851 EXPORT_SYMBOL_GPL(cgroup_taskset_next
);
1854 * cgroup_taskset_cur_css - return the matching css for the current task
1855 * @tset: taskset of interest
1856 * @subsys_id: the ID of the target subsystem
1858 * Return the css for the current (last returned) task of @tset for
1859 * subsystem specified by @subsys_id. This function must be preceded by
1860 * either cgroup_taskset_first() or cgroup_taskset_next().
1862 struct cgroup_subsys_state
*cgroup_taskset_cur_css(struct cgroup_taskset
*tset
,
1865 return cgroup_css(tset
->cur_cgrp
, cgroup_subsys
[subsys_id
]);
1867 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_css
);
1870 * cgroup_taskset_size - return the number of tasks in taskset
1871 * @tset: taskset of interest
1873 int cgroup_taskset_size(struct cgroup_taskset
*tset
)
1875 return tset
->tc_array
? tset
->tc_array_len
: 1;
1877 EXPORT_SYMBOL_GPL(cgroup_taskset_size
);
1881 * cgroup_task_migrate - move a task from one cgroup to another.
1883 * Must be called with cgroup_mutex and threadgroup locked.
1885 static void cgroup_task_migrate(struct cgroup
*old_cgrp
,
1886 struct task_struct
*tsk
,
1887 struct css_set
*new_cset
)
1889 struct css_set
*old_cset
;
1892 * We are synchronized through threadgroup_lock() against PF_EXITING
1893 * setting such that we can't race against cgroup_exit() changing the
1894 * css_set to init_css_set and dropping the old one.
1896 WARN_ON_ONCE(tsk
->flags
& PF_EXITING
);
1897 old_cset
= task_css_set(tsk
);
1900 rcu_assign_pointer(tsk
->cgroups
, new_cset
);
1903 /* Update the css_set linked lists if we're using them */
1904 write_lock(&css_set_lock
);
1905 if (!list_empty(&tsk
->cg_list
))
1906 list_move(&tsk
->cg_list
, &new_cset
->tasks
);
1907 write_unlock(&css_set_lock
);
1910 * We just gained a reference on old_cset by taking it from the
1911 * task. As trading it for new_cset is protected by cgroup_mutex,
1912 * we're safe to drop it here; it will be freed under RCU.
1914 set_bit(CGRP_RELEASABLE
, &old_cgrp
->flags
);
1915 put_css_set(old_cset
);
1919 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1920 * @cgrp: the cgroup to attach to
1921 * @tsk: the task or the leader of the threadgroup to be attached
1922 * @threadgroup: attach the whole threadgroup?
1924 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
1925 * task_lock of @tsk or each thread in the threadgroup individually in turn.
1927 static int cgroup_attach_task(struct cgroup
*cgrp
, struct task_struct
*tsk
,
1930 int retval
, i
, group_size
;
1931 struct cgroup_subsys
*ss
, *failed_ss
= NULL
;
1932 struct cgroupfs_root
*root
= cgrp
->root
;
1933 /* threadgroup list cursor and array */
1934 struct task_struct
*leader
= tsk
;
1935 struct task_and_cgroup
*tc
;
1936 struct flex_array
*group
;
1937 struct cgroup_taskset tset
= { };
1940 * step 0: in order to do expensive, possibly blocking operations for
1941 * every thread, we cannot iterate the thread group list, since it needs
1942 * rcu or tasklist locked. instead, build an array of all threads in the
1943 * group - group_rwsem prevents new threads from appearing, and if
1944 * threads exit, this will just be an over-estimate.
1947 group_size
= get_nr_threads(tsk
);
1950 /* flex_array supports very large thread-groups better than kmalloc. */
1951 group
= flex_array_alloc(sizeof(*tc
), group_size
, GFP_KERNEL
);
1954 /* pre-allocate to guarantee space while iterating in rcu read-side. */
1955 retval
= flex_array_prealloc(group
, 0, group_size
, GFP_KERNEL
);
1957 goto out_free_group_list
;
1961 * Prevent freeing of tasks while we take a snapshot. Tasks that are
1962 * already PF_EXITING could be freed from underneath us unless we
1963 * take an rcu_read_lock.
1967 struct task_and_cgroup ent
;
1969 /* @tsk either already exited or can't exit until the end */
1970 if (tsk
->flags
& PF_EXITING
)
1973 /* as per above, nr_threads may decrease, but not increase. */
1974 BUG_ON(i
>= group_size
);
1976 ent
.cgrp
= task_cgroup_from_root(tsk
, root
);
1977 /* nothing to do if this task is already in the cgroup */
1978 if (ent
.cgrp
== cgrp
)
1981 * saying GFP_ATOMIC has no effect here because we did prealloc
1982 * earlier, but it's good form to communicate our expectations.
1984 retval
= flex_array_put(group
, i
, &ent
, GFP_ATOMIC
);
1985 BUG_ON(retval
!= 0);
1990 } while_each_thread(leader
, tsk
);
1992 /* remember the number of threads in the array for later. */
1994 tset
.tc_array
= group
;
1995 tset
.tc_array_len
= group_size
;
1997 /* methods shouldn't be called if no task is actually migrating */
2000 goto out_free_group_list
;
2003 * step 1: check that we can legitimately attach to the cgroup.
2005 for_each_root_subsys(root
, ss
) {
2006 struct cgroup_subsys_state
*css
= cgroup_css(cgrp
, ss
);
2008 if (ss
->can_attach
) {
2009 retval
= ss
->can_attach(css
, &tset
);
2012 goto out_cancel_attach
;
2018 * step 2: make sure css_sets exist for all threads to be migrated.
2019 * we use find_css_set, which allocates a new one if necessary.
2021 for (i
= 0; i
< group_size
; i
++) {
2022 struct css_set
*old_cset
;
2024 tc
= flex_array_get(group
, i
);
2025 old_cset
= task_css_set(tc
->task
);
2026 tc
->cset
= find_css_set(old_cset
, cgrp
);
2029 goto out_put_css_set_refs
;
2034 * step 3: now that we're guaranteed success wrt the css_sets,
2035 * proceed to move all tasks to the new cgroup. There are no
2036 * failure cases after here, so this is the commit point.
2038 for (i
= 0; i
< group_size
; i
++) {
2039 tc
= flex_array_get(group
, i
);
2040 cgroup_task_migrate(tc
->cgrp
, tc
->task
, tc
->cset
);
2042 /* nothing is sensitive to fork() after this point. */
2045 * step 4: do subsystem attach callbacks.
2047 for_each_root_subsys(root
, ss
) {
2048 struct cgroup_subsys_state
*css
= cgroup_css(cgrp
, ss
);
2051 ss
->attach(css
, &tset
);
2055 * step 5: success! and cleanup
2058 out_put_css_set_refs
:
2060 for (i
= 0; i
< group_size
; i
++) {
2061 tc
= flex_array_get(group
, i
);
2064 put_css_set(tc
->cset
);
2069 for_each_root_subsys(root
, ss
) {
2070 struct cgroup_subsys_state
*css
= cgroup_css(cgrp
, ss
);
2072 if (ss
== failed_ss
)
2074 if (ss
->cancel_attach
)
2075 ss
->cancel_attach(css
, &tset
);
2078 out_free_group_list
:
2079 flex_array_free(group
);
2084 * Find the task_struct of the task to attach by vpid and pass it along to the
2085 * function to attach either it or all tasks in its threadgroup. Will lock
2086 * cgroup_mutex and threadgroup; may take task_lock of task.
2088 static int attach_task_by_pid(struct cgroup
*cgrp
, u64 pid
, bool threadgroup
)
2090 struct task_struct
*tsk
;
2091 const struct cred
*cred
= current_cred(), *tcred
;
2094 if (!cgroup_lock_live_group(cgrp
))
2100 tsk
= find_task_by_vpid(pid
);
2104 goto out_unlock_cgroup
;
2107 * even if we're attaching all tasks in the thread group, we
2108 * only need to check permissions on one of them.
2110 tcred
= __task_cred(tsk
);
2111 if (!uid_eq(cred
->euid
, GLOBAL_ROOT_UID
) &&
2112 !uid_eq(cred
->euid
, tcred
->uid
) &&
2113 !uid_eq(cred
->euid
, tcred
->suid
)) {
2116 goto out_unlock_cgroup
;
2122 tsk
= tsk
->group_leader
;
2125 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2126 * trapped in a cpuset, or RT worker may be born in a cgroup
2127 * with no rt_runtime allocated. Just say no.
2129 if (tsk
== kthreadd_task
|| (tsk
->flags
& PF_NO_SETAFFINITY
)) {
2132 goto out_unlock_cgroup
;
2135 get_task_struct(tsk
);
2138 threadgroup_lock(tsk
);
2140 if (!thread_group_leader(tsk
)) {
2142 * a race with de_thread from another thread's exec()
2143 * may strip us of our leadership, if this happens,
2144 * there is no choice but to throw this task away and
2145 * try again; this is
2146 * "double-double-toil-and-trouble-check locking".
2148 threadgroup_unlock(tsk
);
2149 put_task_struct(tsk
);
2150 goto retry_find_task
;
2154 ret
= cgroup_attach_task(cgrp
, tsk
, threadgroup
);
2156 threadgroup_unlock(tsk
);
2158 put_task_struct(tsk
);
2160 mutex_unlock(&cgroup_mutex
);
2165 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2166 * @from: attach to all cgroups of a given task
2167 * @tsk: the task to be attached
2169 int cgroup_attach_task_all(struct task_struct
*from
, struct task_struct
*tsk
)
2171 struct cgroupfs_root
*root
;
2174 mutex_lock(&cgroup_mutex
);
2175 for_each_active_root(root
) {
2176 struct cgroup
*from_cgrp
= task_cgroup_from_root(from
, root
);
2178 retval
= cgroup_attach_task(from_cgrp
, tsk
, false);
2182 mutex_unlock(&cgroup_mutex
);
2186 EXPORT_SYMBOL_GPL(cgroup_attach_task_all
);
2188 static int cgroup_tasks_write(struct cgroup_subsys_state
*css
,
2189 struct cftype
*cft
, u64 pid
)
2191 return attach_task_by_pid(css
->cgroup
, pid
, false);
2194 static int cgroup_procs_write(struct cgroup_subsys_state
*css
,
2195 struct cftype
*cft
, u64 tgid
)
2197 return attach_task_by_pid(css
->cgroup
, tgid
, true);
2200 static int cgroup_release_agent_write(struct cgroup_subsys_state
*css
,
2201 struct cftype
*cft
, const char *buffer
)
2203 BUILD_BUG_ON(sizeof(css
->cgroup
->root
->release_agent_path
) < PATH_MAX
);
2204 if (strlen(buffer
) >= PATH_MAX
)
2206 if (!cgroup_lock_live_group(css
->cgroup
))
2208 mutex_lock(&cgroup_root_mutex
);
2209 strcpy(css
->cgroup
->root
->release_agent_path
, buffer
);
2210 mutex_unlock(&cgroup_root_mutex
);
2211 mutex_unlock(&cgroup_mutex
);
2215 static int cgroup_release_agent_show(struct seq_file
*seq
, void *v
)
2217 struct cgroup
*cgrp
= seq_css(seq
)->cgroup
;
2219 if (!cgroup_lock_live_group(cgrp
))
2221 seq_puts(seq
, cgrp
->root
->release_agent_path
);
2222 seq_putc(seq
, '\n');
2223 mutex_unlock(&cgroup_mutex
);
2227 static int cgroup_sane_behavior_show(struct seq_file
*seq
, void *v
)
2229 struct cgroup
*cgrp
= seq_css(seq
)->cgroup
;
2231 seq_printf(seq
, "%d\n", cgroup_sane_behavior(cgrp
));
2235 /* A buffer size big enough for numbers or short strings */
2236 #define CGROUP_LOCAL_BUFFER_SIZE 64
2238 static ssize_t
cgroup_file_write(struct file
*file
, const char __user
*userbuf
,
2239 size_t nbytes
, loff_t
*ppos
)
2241 struct cfent
*cfe
= __d_cfe(file
->f_dentry
);
2242 struct cftype
*cft
= __d_cft(file
->f_dentry
);
2243 struct cgroup_subsys_state
*css
= cfe
->css
;
2244 size_t max_bytes
= cft
->max_write_len
?: CGROUP_LOCAL_BUFFER_SIZE
- 1;
2248 if (nbytes
>= max_bytes
)
2251 buf
= kmalloc(nbytes
+ 1, GFP_KERNEL
);
2255 if (copy_from_user(buf
, userbuf
, nbytes
)) {
2262 if (cft
->write_string
) {
2263 ret
= cft
->write_string(css
, cft
, strstrip(buf
));
2264 } else if (cft
->write_u64
) {
2265 unsigned long long v
;
2266 ret
= kstrtoull(buf
, 0, &v
);
2268 ret
= cft
->write_u64(css
, cft
, v
);
2269 } else if (cft
->write_s64
) {
2271 ret
= kstrtoll(buf
, 0, &v
);
2273 ret
= cft
->write_s64(css
, cft
, v
);
2274 } else if (cft
->trigger
) {
2275 ret
= cft
->trigger(css
, (unsigned int)cft
->private);
2281 return ret
?: nbytes
;
2285 * seqfile ops/methods for returning structured data. Currently just
2286 * supports string->u64 maps, but can be extended in future.
2289 static int cgroup_seqfile_show(struct seq_file
*m
, void *arg
)
2291 struct cftype
*cft
= seq_cft(m
);
2292 struct cgroup_subsys_state
*css
= seq_css(m
);
2295 return cft
->seq_show(m
, arg
);
2298 seq_printf(m
, "%llu\n", cft
->read_u64(css
, cft
));
2299 else if (cft
->read_s64
)
2300 seq_printf(m
, "%lld\n", cft
->read_s64(css
, cft
));
2306 static int cgroup_file_open(struct inode
*inode
, struct file
*file
)
2308 struct cfent
*cfe
= __d_cfe(file
->f_dentry
);
2309 struct cftype
*cft
= __d_cft(file
->f_dentry
);
2310 struct cgroup
*cgrp
= __d_cgrp(cfe
->dentry
->d_parent
);
2311 struct cgroup_subsys_state
*css
;
2314 err
= generic_file_open(inode
, file
);
2319 * If the file belongs to a subsystem, pin the css. Will be
2320 * unpinned either on open failure or release. This ensures that
2321 * @css stays alive for all file operations.
2324 css
= cgroup_css(cgrp
, cft
->ss
);
2325 if (cft
->ss
&& !css_tryget(css
))
2333 * @cfe->css is used by read/write/close to determine the
2334 * associated css. @file->private_data would be a better place but
2335 * that's already used by seqfile. Multiple accessors may use it
2336 * simultaneously which is okay as the association never changes.
2338 WARN_ON_ONCE(cfe
->css
&& cfe
->css
!= css
);
2342 err
= cft
->open(inode
, file
);
2344 struct cgroup_open_file
*of
;
2347 of
= kzalloc(sizeof(*of
), GFP_KERNEL
);
2350 err
= single_open(file
, cgroup_seqfile_show
, of
);
2361 static int cgroup_file_release(struct inode
*inode
, struct file
*file
)
2363 struct cfent
*cfe
= __d_cfe(file
->f_dentry
);
2364 struct cgroup_subsys_state
*css
= cfe
->css
;
2368 kfree(((struct seq_file
*)file
->private_data
)->private);
2369 return single_release(inode
, file
);
2373 * cgroup_rename - Only allow simple rename of directories in place.
2375 static int cgroup_rename(struct inode
*old_dir
, struct dentry
*old_dentry
,
2376 struct inode
*new_dir
, struct dentry
*new_dentry
)
2379 struct cgroup_name
*name
, *old_name
;
2380 struct cgroup
*cgrp
;
2383 * It's convinient to use parent dir's i_mutex to protected
2386 lockdep_assert_held(&old_dir
->i_mutex
);
2388 if (!S_ISDIR(old_dentry
->d_inode
->i_mode
))
2390 if (new_dentry
->d_inode
)
2392 if (old_dir
!= new_dir
)
2395 cgrp
= __d_cgrp(old_dentry
);
2398 * This isn't a proper migration and its usefulness is very
2399 * limited. Disallow if sane_behavior.
2401 if (cgroup_sane_behavior(cgrp
))
2404 name
= cgroup_alloc_name(new_dentry
);
2408 ret
= simple_rename(old_dir
, old_dentry
, new_dir
, new_dentry
);
2414 old_name
= rcu_dereference_protected(cgrp
->name
, true);
2415 rcu_assign_pointer(cgrp
->name
, name
);
2417 kfree_rcu(old_name
, rcu_head
);
2421 static struct simple_xattrs
*__d_xattrs(struct dentry
*dentry
)
2423 if (S_ISDIR(dentry
->d_inode
->i_mode
))
2424 return &__d_cgrp(dentry
)->xattrs
;
2426 return &__d_cfe(dentry
)->xattrs
;
2429 static inline int xattr_enabled(struct dentry
*dentry
)
2431 struct cgroupfs_root
*root
= dentry
->d_sb
->s_fs_info
;
2432 return root
->flags
& CGRP_ROOT_XATTR
;
2435 static bool is_valid_xattr(const char *name
)
2437 if (!strncmp(name
, XATTR_TRUSTED_PREFIX
, XATTR_TRUSTED_PREFIX_LEN
) ||
2438 !strncmp(name
, XATTR_SECURITY_PREFIX
, XATTR_SECURITY_PREFIX_LEN
))
2443 static int cgroup_setxattr(struct dentry
*dentry
, const char *name
,
2444 const void *val
, size_t size
, int flags
)
2446 if (!xattr_enabled(dentry
))
2448 if (!is_valid_xattr(name
))
2450 return simple_xattr_set(__d_xattrs(dentry
), name
, val
, size
, flags
);
2453 static int cgroup_removexattr(struct dentry
*dentry
, const char *name
)
2455 if (!xattr_enabled(dentry
))
2457 if (!is_valid_xattr(name
))
2459 return simple_xattr_remove(__d_xattrs(dentry
), name
);
2462 static ssize_t
cgroup_getxattr(struct dentry
*dentry
, const char *name
,
2463 void *buf
, size_t size
)
2465 if (!xattr_enabled(dentry
))
2467 if (!is_valid_xattr(name
))
2469 return simple_xattr_get(__d_xattrs(dentry
), name
, buf
, size
);
2472 static ssize_t
cgroup_listxattr(struct dentry
*dentry
, char *buf
, size_t size
)
2474 if (!xattr_enabled(dentry
))
2476 return simple_xattr_list(__d_xattrs(dentry
), buf
, size
);
2479 static const struct file_operations cgroup_file_operations
= {
2481 .write
= cgroup_file_write
,
2482 .llseek
= generic_file_llseek
,
2483 .open
= cgroup_file_open
,
2484 .release
= cgroup_file_release
,
2487 static const struct inode_operations cgroup_file_inode_operations
= {
2488 .setxattr
= cgroup_setxattr
,
2489 .getxattr
= cgroup_getxattr
,
2490 .listxattr
= cgroup_listxattr
,
2491 .removexattr
= cgroup_removexattr
,
2494 static const struct inode_operations cgroup_dir_inode_operations
= {
2495 .lookup
= simple_lookup
,
2496 .mkdir
= cgroup_mkdir
,
2497 .rmdir
= cgroup_rmdir
,
2498 .rename
= cgroup_rename
,
2499 .setxattr
= cgroup_setxattr
,
2500 .getxattr
= cgroup_getxattr
,
2501 .listxattr
= cgroup_listxattr
,
2502 .removexattr
= cgroup_removexattr
,
2505 static int cgroup_create_file(struct dentry
*dentry
, umode_t mode
,
2506 struct super_block
*sb
)
2508 struct inode
*inode
;
2512 if (dentry
->d_inode
)
2515 inode
= cgroup_new_inode(mode
, sb
);
2519 if (S_ISDIR(mode
)) {
2520 inode
->i_op
= &cgroup_dir_inode_operations
;
2521 inode
->i_fop
= &simple_dir_operations
;
2523 /* start off with i_nlink == 2 (for "." entry) */
2525 inc_nlink(dentry
->d_parent
->d_inode
);
2528 * Control reaches here with cgroup_mutex held.
2529 * @inode->i_mutex should nest outside cgroup_mutex but we
2530 * want to populate it immediately without releasing
2531 * cgroup_mutex. As @inode isn't visible to anyone else
2532 * yet, trylock will always succeed without affecting
2535 WARN_ON_ONCE(!mutex_trylock(&inode
->i_mutex
));
2536 } else if (S_ISREG(mode
)) {
2538 inode
->i_fop
= &cgroup_file_operations
;
2539 inode
->i_op
= &cgroup_file_inode_operations
;
2541 d_instantiate(dentry
, inode
);
2542 dget(dentry
); /* Extra count - pin the dentry in core */
2547 * cgroup_file_mode - deduce file mode of a control file
2548 * @cft: the control file in question
2550 * returns cft->mode if ->mode is not 0
2551 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2552 * returns S_IRUGO if it has only a read handler
2553 * returns S_IWUSR if it has only a write hander
2555 static umode_t
cgroup_file_mode(const struct cftype
*cft
)
2562 if (cft
->read_u64
|| cft
->read_s64
|| cft
->seq_show
)
2565 if (cft
->write_u64
|| cft
->write_s64
|| cft
->write_string
||
2572 static int cgroup_add_file(struct cgroup
*cgrp
, struct cftype
*cft
)
2574 struct dentry
*dir
= cgrp
->dentry
;
2575 struct cgroup
*parent
= __d_cgrp(dir
);
2576 struct dentry
*dentry
;
2580 char name
[MAX_CGROUP_TYPE_NAMELEN
+ MAX_CFTYPE_NAME
+ 2] = { 0 };
2582 if (cft
->ss
&& !(cft
->flags
& CFTYPE_NO_PREFIX
) &&
2583 !(cgrp
->root
->flags
& CGRP_ROOT_NOPREFIX
)) {
2584 strcpy(name
, cft
->ss
->name
);
2587 strcat(name
, cft
->name
);
2589 BUG_ON(!mutex_is_locked(&dir
->d_inode
->i_mutex
));
2591 cfe
= kzalloc(sizeof(*cfe
), GFP_KERNEL
);
2595 dentry
= lookup_one_len(name
, dir
, strlen(name
));
2596 if (IS_ERR(dentry
)) {
2597 error
= PTR_ERR(dentry
);
2601 cfe
->type
= (void *)cft
;
2602 cfe
->dentry
= dentry
;
2603 dentry
->d_fsdata
= cfe
;
2604 simple_xattrs_init(&cfe
->xattrs
);
2606 mode
= cgroup_file_mode(cft
);
2607 error
= cgroup_create_file(dentry
, mode
| S_IFREG
, cgrp
->root
->sb
);
2609 list_add_tail(&cfe
->node
, &parent
->files
);
2619 * cgroup_addrm_files - add or remove files to a cgroup directory
2620 * @cgrp: the target cgroup
2621 * @cfts: array of cftypes to be added
2622 * @is_add: whether to add or remove
2624 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2625 * For removals, this function never fails. If addition fails, this
2626 * function doesn't remove files already added. The caller is responsible
2629 static int cgroup_addrm_files(struct cgroup
*cgrp
, struct cftype cfts
[],
2635 lockdep_assert_held(&cgrp
->dentry
->d_inode
->i_mutex
);
2636 lockdep_assert_held(&cgroup_mutex
);
2638 for (cft
= cfts
; cft
->name
[0] != '\0'; cft
++) {
2639 /* does cft->flags tell us to skip this file on @cgrp? */
2640 if ((cft
->flags
& CFTYPE_INSANE
) && cgroup_sane_behavior(cgrp
))
2642 if ((cft
->flags
& CFTYPE_NOT_ON_ROOT
) && !cgrp
->parent
)
2644 if ((cft
->flags
& CFTYPE_ONLY_ON_ROOT
) && cgrp
->parent
)
2648 ret
= cgroup_add_file(cgrp
, cft
);
2650 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2655 cgroup_rm_file(cgrp
, cft
);
2661 static void cgroup_cfts_prepare(void)
2662 __acquires(&cgroup_mutex
)
2665 * Thanks to the entanglement with vfs inode locking, we can't walk
2666 * the existing cgroups under cgroup_mutex and create files.
2667 * Instead, we use css_for_each_descendant_pre() and drop RCU read
2668 * lock before calling cgroup_addrm_files().
2670 mutex_lock(&cgroup_mutex
);
2673 static int cgroup_cfts_commit(struct cftype
*cfts
, bool is_add
)
2674 __releases(&cgroup_mutex
)
2677 struct cgroup_subsys
*ss
= cfts
[0].ss
;
2678 struct cgroup
*root
= &ss
->root
->top_cgroup
;
2679 struct super_block
*sb
= ss
->root
->sb
;
2680 struct dentry
*prev
= NULL
;
2681 struct inode
*inode
;
2682 struct cgroup_subsys_state
*css
;
2686 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2687 if (!cfts
|| ss
->root
== &cgroup_dummy_root
||
2688 !atomic_inc_not_zero(&sb
->s_active
)) {
2689 mutex_unlock(&cgroup_mutex
);
2694 * All cgroups which are created after we drop cgroup_mutex will
2695 * have the updated set of files, so we only need to update the
2696 * cgroups created before the current @cgroup_serial_nr_next.
2698 update_before
= cgroup_serial_nr_next
;
2700 mutex_unlock(&cgroup_mutex
);
2702 /* add/rm files for all cgroups created before */
2704 css_for_each_descendant_pre(css
, cgroup_css(root
, ss
)) {
2705 struct cgroup
*cgrp
= css
->cgroup
;
2707 if (cgroup_is_dead(cgrp
))
2710 inode
= cgrp
->dentry
->d_inode
;
2715 prev
= cgrp
->dentry
;
2717 mutex_lock(&inode
->i_mutex
);
2718 mutex_lock(&cgroup_mutex
);
2719 if (cgrp
->serial_nr
< update_before
&& !cgroup_is_dead(cgrp
))
2720 ret
= cgroup_addrm_files(cgrp
, cfts
, is_add
);
2721 mutex_unlock(&cgroup_mutex
);
2722 mutex_unlock(&inode
->i_mutex
);
2730 deactivate_super(sb
);
2735 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2736 * @ss: target cgroup subsystem
2737 * @cfts: zero-length name terminated array of cftypes
2739 * Register @cfts to @ss. Files described by @cfts are created for all
2740 * existing cgroups to which @ss is attached and all future cgroups will
2741 * have them too. This function can be called anytime whether @ss is
2744 * Returns 0 on successful registration, -errno on failure. Note that this
2745 * function currently returns 0 as long as @cfts registration is successful
2746 * even if some file creation attempts on existing cgroups fail.
2748 int cgroup_add_cftypes(struct cgroup_subsys
*ss
, struct cftype
*cfts
)
2750 struct cftype_set
*set
;
2754 set
= kzalloc(sizeof(*set
), GFP_KERNEL
);
2758 for (cft
= cfts
; cft
->name
[0] != '\0'; cft
++)
2761 cgroup_cfts_prepare();
2763 list_add_tail(&set
->node
, &ss
->cftsets
);
2764 ret
= cgroup_cfts_commit(cfts
, true);
2766 cgroup_rm_cftypes(cfts
);
2769 EXPORT_SYMBOL_GPL(cgroup_add_cftypes
);
2772 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2773 * @cfts: zero-length name terminated array of cftypes
2775 * Unregister @cfts. Files described by @cfts are removed from all
2776 * existing cgroups and all future cgroups won't have them either. This
2777 * function can be called anytime whether @cfts' subsys is attached or not.
2779 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2782 int cgroup_rm_cftypes(struct cftype
*cfts
)
2784 struct cftype_set
*set
;
2786 if (!cfts
|| !cfts
[0].ss
)
2789 cgroup_cfts_prepare();
2791 list_for_each_entry(set
, &cfts
[0].ss
->cftsets
, node
) {
2792 if (set
->cfts
== cfts
) {
2793 list_del(&set
->node
);
2795 cgroup_cfts_commit(cfts
, false);
2800 cgroup_cfts_commit(NULL
, false);
2805 * cgroup_task_count - count the number of tasks in a cgroup.
2806 * @cgrp: the cgroup in question
2808 * Return the number of tasks in the cgroup.
2810 int cgroup_task_count(const struct cgroup
*cgrp
)
2813 struct cgrp_cset_link
*link
;
2815 read_lock(&css_set_lock
);
2816 list_for_each_entry(link
, &cgrp
->cset_links
, cset_link
)
2817 count
+= atomic_read(&link
->cset
->refcount
);
2818 read_unlock(&css_set_lock
);
2823 * To reduce the fork() overhead for systems that are not actually using
2824 * their cgroups capability, we don't maintain the lists running through
2825 * each css_set to its tasks until we see the list actually used - in other
2826 * words after the first call to css_task_iter_start().
2828 static void cgroup_enable_task_cg_lists(void)
2830 struct task_struct
*p
, *g
;
2831 write_lock(&css_set_lock
);
2832 use_task_css_set_links
= 1;
2834 * We need tasklist_lock because RCU is not safe against
2835 * while_each_thread(). Besides, a forking task that has passed
2836 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2837 * is not guaranteed to have its child immediately visible in the
2838 * tasklist if we walk through it with RCU.
2840 read_lock(&tasklist_lock
);
2841 do_each_thread(g
, p
) {
2844 * We should check if the process is exiting, otherwise
2845 * it will race with cgroup_exit() in that the list
2846 * entry won't be deleted though the process has exited.
2848 if (!(p
->flags
& PF_EXITING
) && list_empty(&p
->cg_list
))
2849 list_add(&p
->cg_list
, &task_css_set(p
)->tasks
);
2851 } while_each_thread(g
, p
);
2852 read_unlock(&tasklist_lock
);
2853 write_unlock(&css_set_lock
);
2857 * css_next_child - find the next child of a given css
2858 * @pos_css: the current position (%NULL to initiate traversal)
2859 * @parent_css: css whose children to walk
2861 * This function returns the next child of @parent_css and should be called
2862 * under RCU read lock. The only requirement is that @parent_css and
2863 * @pos_css are accessible. The next sibling is guaranteed to be returned
2864 * regardless of their states.
2866 struct cgroup_subsys_state
*
2867 css_next_child(struct cgroup_subsys_state
*pos_css
,
2868 struct cgroup_subsys_state
*parent_css
)
2870 struct cgroup
*pos
= pos_css
? pos_css
->cgroup
: NULL
;
2871 struct cgroup
*cgrp
= parent_css
->cgroup
;
2872 struct cgroup
*next
;
2874 WARN_ON_ONCE(!rcu_read_lock_held());
2877 * @pos could already have been removed. Once a cgroup is removed,
2878 * its ->sibling.next is no longer updated when its next sibling
2879 * changes. As CGRP_DEAD assertion is serialized and happens
2880 * before the cgroup is taken off the ->sibling list, if we see it
2881 * unasserted, it's guaranteed that the next sibling hasn't
2882 * finished its grace period even if it's already removed, and thus
2883 * safe to dereference from this RCU critical section. If
2884 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
2885 * to be visible as %true here.
2887 * If @pos is dead, its next pointer can't be dereferenced;
2888 * however, as each cgroup is given a monotonically increasing
2889 * unique serial number and always appended to the sibling list,
2890 * the next one can be found by walking the parent's children until
2891 * we see a cgroup with higher serial number than @pos's. While
2892 * this path can be slower, it's taken only when either the current
2893 * cgroup is removed or iteration and removal race.
2896 next
= list_entry_rcu(cgrp
->children
.next
, struct cgroup
, sibling
);
2897 } else if (likely(!cgroup_is_dead(pos
))) {
2898 next
= list_entry_rcu(pos
->sibling
.next
, struct cgroup
, sibling
);
2900 list_for_each_entry_rcu(next
, &cgrp
->children
, sibling
)
2901 if (next
->serial_nr
> pos
->serial_nr
)
2905 if (&next
->sibling
== &cgrp
->children
)
2908 return cgroup_css(next
, parent_css
->ss
);
2910 EXPORT_SYMBOL_GPL(css_next_child
);
2913 * css_next_descendant_pre - find the next descendant for pre-order walk
2914 * @pos: the current position (%NULL to initiate traversal)
2915 * @root: css whose descendants to walk
2917 * To be used by css_for_each_descendant_pre(). Find the next descendant
2918 * to visit for pre-order traversal of @root's descendants. @root is
2919 * included in the iteration and the first node to be visited.
2921 * While this function requires RCU read locking, it doesn't require the
2922 * whole traversal to be contained in a single RCU critical section. This
2923 * function will return the correct next descendant as long as both @pos
2924 * and @root are accessible and @pos is a descendant of @root.
2926 struct cgroup_subsys_state
*
2927 css_next_descendant_pre(struct cgroup_subsys_state
*pos
,
2928 struct cgroup_subsys_state
*root
)
2930 struct cgroup_subsys_state
*next
;
2932 WARN_ON_ONCE(!rcu_read_lock_held());
2934 /* if first iteration, visit @root */
2938 /* visit the first child if exists */
2939 next
= css_next_child(NULL
, pos
);
2943 /* no child, visit my or the closest ancestor's next sibling */
2944 while (pos
!= root
) {
2945 next
= css_next_child(pos
, css_parent(pos
));
2948 pos
= css_parent(pos
);
2953 EXPORT_SYMBOL_GPL(css_next_descendant_pre
);
2956 * css_rightmost_descendant - return the rightmost descendant of a css
2957 * @pos: css of interest
2959 * Return the rightmost descendant of @pos. If there's no descendant, @pos
2960 * is returned. This can be used during pre-order traversal to skip
2963 * While this function requires RCU read locking, it doesn't require the
2964 * whole traversal to be contained in a single RCU critical section. This
2965 * function will return the correct rightmost descendant as long as @pos is
2968 struct cgroup_subsys_state
*
2969 css_rightmost_descendant(struct cgroup_subsys_state
*pos
)
2971 struct cgroup_subsys_state
*last
, *tmp
;
2973 WARN_ON_ONCE(!rcu_read_lock_held());
2977 /* ->prev isn't RCU safe, walk ->next till the end */
2979 css_for_each_child(tmp
, last
)
2985 EXPORT_SYMBOL_GPL(css_rightmost_descendant
);
2987 static struct cgroup_subsys_state
*
2988 css_leftmost_descendant(struct cgroup_subsys_state
*pos
)
2990 struct cgroup_subsys_state
*last
;
2994 pos
= css_next_child(NULL
, pos
);
3001 * css_next_descendant_post - find the next descendant for post-order walk
3002 * @pos: the current position (%NULL to initiate traversal)
3003 * @root: css whose descendants to walk
3005 * To be used by css_for_each_descendant_post(). Find the next descendant
3006 * to visit for post-order traversal of @root's descendants. @root is
3007 * included in the iteration and the last node to be visited.
3009 * While this function requires RCU read locking, it doesn't require the
3010 * whole traversal to be contained in a single RCU critical section. This
3011 * function will return the correct next descendant as long as both @pos
3012 * and @cgroup are accessible and @pos is a descendant of @cgroup.
3014 struct cgroup_subsys_state
*
3015 css_next_descendant_post(struct cgroup_subsys_state
*pos
,
3016 struct cgroup_subsys_state
*root
)
3018 struct cgroup_subsys_state
*next
;
3020 WARN_ON_ONCE(!rcu_read_lock_held());
3022 /* if first iteration, visit leftmost descendant which may be @root */
3024 return css_leftmost_descendant(root
);
3026 /* if we visited @root, we're done */
3030 /* if there's an unvisited sibling, visit its leftmost descendant */
3031 next
= css_next_child(pos
, css_parent(pos
));
3033 return css_leftmost_descendant(next
);
3035 /* no sibling left, visit parent */
3036 return css_parent(pos
);
3038 EXPORT_SYMBOL_GPL(css_next_descendant_post
);
3041 * css_advance_task_iter - advance a task itererator to the next css_set
3042 * @it: the iterator to advance
3044 * Advance @it to the next css_set to walk.
3046 static void css_advance_task_iter(struct css_task_iter
*it
)
3048 struct list_head
*l
= it
->cset_link
;
3049 struct cgrp_cset_link
*link
;
3050 struct css_set
*cset
;
3052 /* Advance to the next non-empty css_set */
3055 if (l
== &it
->origin_css
->cgroup
->cset_links
) {
3056 it
->cset_link
= NULL
;
3059 link
= list_entry(l
, struct cgrp_cset_link
, cset_link
);
3061 } while (list_empty(&cset
->tasks
));
3063 it
->task
= cset
->tasks
.next
;
3067 * css_task_iter_start - initiate task iteration
3068 * @css: the css to walk tasks of
3069 * @it: the task iterator to use
3071 * Initiate iteration through the tasks of @css. The caller can call
3072 * css_task_iter_next() to walk through the tasks until the function
3073 * returns NULL. On completion of iteration, css_task_iter_end() must be
3076 * Note that this function acquires a lock which is released when the
3077 * iteration finishes. The caller can't sleep while iteration is in
3080 void css_task_iter_start(struct cgroup_subsys_state
*css
,
3081 struct css_task_iter
*it
)
3082 __acquires(css_set_lock
)
3085 * The first time anyone tries to iterate across a css, we need to
3086 * enable the list linking each css_set to its tasks, and fix up
3087 * all existing tasks.
3089 if (!use_task_css_set_links
)
3090 cgroup_enable_task_cg_lists();
3092 read_lock(&css_set_lock
);
3094 it
->origin_css
= css
;
3095 it
->cset_link
= &css
->cgroup
->cset_links
;
3097 css_advance_task_iter(it
);
3101 * css_task_iter_next - return the next task for the iterator
3102 * @it: the task iterator being iterated
3104 * The "next" function for task iteration. @it should have been
3105 * initialized via css_task_iter_start(). Returns NULL when the iteration
3108 struct task_struct
*css_task_iter_next(struct css_task_iter
*it
)
3110 struct task_struct
*res
;
3111 struct list_head
*l
= it
->task
;
3112 struct cgrp_cset_link
*link
;
3114 /* If the iterator cg is NULL, we have no tasks */
3117 res
= list_entry(l
, struct task_struct
, cg_list
);
3118 /* Advance iterator to find next entry */
3120 link
= list_entry(it
->cset_link
, struct cgrp_cset_link
, cset_link
);
3121 if (l
== &link
->cset
->tasks
) {
3123 * We reached the end of this task list - move on to the
3124 * next cgrp_cset_link.
3126 css_advance_task_iter(it
);
3134 * css_task_iter_end - finish task iteration
3135 * @it: the task iterator to finish
3137 * Finish task iteration started by css_task_iter_start().
3139 void css_task_iter_end(struct css_task_iter
*it
)
3140 __releases(css_set_lock
)
3142 read_unlock(&css_set_lock
);
3145 static inline int started_after_time(struct task_struct
*t1
,
3146 struct timespec
*time
,
3147 struct task_struct
*t2
)
3149 int start_diff
= timespec_compare(&t1
->start_time
, time
);
3150 if (start_diff
> 0) {
3152 } else if (start_diff
< 0) {
3156 * Arbitrarily, if two processes started at the same
3157 * time, we'll say that the lower pointer value
3158 * started first. Note that t2 may have exited by now
3159 * so this may not be a valid pointer any longer, but
3160 * that's fine - it still serves to distinguish
3161 * between two tasks started (effectively) simultaneously.
3168 * This function is a callback from heap_insert() and is used to order
3170 * In this case we order the heap in descending task start time.
3172 static inline int started_after(void *p1
, void *p2
)
3174 struct task_struct
*t1
= p1
;
3175 struct task_struct
*t2
= p2
;
3176 return started_after_time(t1
, &t2
->start_time
, t2
);
3180 * css_scan_tasks - iterate though all the tasks in a css
3181 * @css: the css to iterate tasks of
3182 * @test: optional test callback
3183 * @process: process callback
3184 * @data: data passed to @test and @process
3185 * @heap: optional pre-allocated heap used for task iteration
3187 * Iterate through all the tasks in @css, calling @test for each, and if it
3188 * returns %true, call @process for it also.
3190 * @test may be NULL, meaning always true (select all tasks), which
3191 * effectively duplicates css_task_iter_{start,next,end}() but does not
3192 * lock css_set_lock for the call to @process.
3194 * It is guaranteed that @process will act on every task that is a member
3195 * of @css for the duration of this call. This function may or may not
3196 * call @process for tasks that exit or move to a different css during the
3197 * call, or are forked or move into the css during the call.
3199 * Note that @test may be called with locks held, and may in some
3200 * situations be called multiple times for the same task, so it should be
3203 * If @heap is non-NULL, a heap has been pre-allocated and will be used for
3204 * heap operations (and its "gt" member will be overwritten), else a
3205 * temporary heap will be used (allocation of which may cause this function
3208 int css_scan_tasks(struct cgroup_subsys_state
*css
,
3209 bool (*test
)(struct task_struct
*, void *),
3210 void (*process
)(struct task_struct
*, void *),
3211 void *data
, struct ptr_heap
*heap
)
3214 struct css_task_iter it
;
3215 struct task_struct
*p
, *dropped
;
3216 /* Never dereference latest_task, since it's not refcounted */
3217 struct task_struct
*latest_task
= NULL
;
3218 struct ptr_heap tmp_heap
;
3219 struct timespec latest_time
= { 0, 0 };
3222 /* The caller supplied our heap and pre-allocated its memory */
3223 heap
->gt
= &started_after
;
3225 /* We need to allocate our own heap memory */
3227 retval
= heap_init(heap
, PAGE_SIZE
, GFP_KERNEL
, &started_after
);
3229 /* cannot allocate the heap */
3235 * Scan tasks in the css, using the @test callback to determine
3236 * which are of interest, and invoking @process callback on the
3237 * ones which need an update. Since we don't want to hold any
3238 * locks during the task updates, gather tasks to be processed in a
3239 * heap structure. The heap is sorted by descending task start
3240 * time. If the statically-sized heap fills up, we overflow tasks
3241 * that started later, and in future iterations only consider tasks
3242 * that started after the latest task in the previous pass. This
3243 * guarantees forward progress and that we don't miss any tasks.
3246 css_task_iter_start(css
, &it
);
3247 while ((p
= css_task_iter_next(&it
))) {
3249 * Only affect tasks that qualify per the caller's callback,
3250 * if he provided one
3252 if (test
&& !test(p
, data
))
3255 * Only process tasks that started after the last task
3258 if (!started_after_time(p
, &latest_time
, latest_task
))
3260 dropped
= heap_insert(heap
, p
);
3261 if (dropped
== NULL
) {
3263 * The new task was inserted; the heap wasn't
3267 } else if (dropped
!= p
) {
3269 * The new task was inserted, and pushed out a
3273 put_task_struct(dropped
);
3276 * Else the new task was newer than anything already in
3277 * the heap and wasn't inserted
3280 css_task_iter_end(&it
);
3283 for (i
= 0; i
< heap
->size
; i
++) {
3284 struct task_struct
*q
= heap
->ptrs
[i
];
3286 latest_time
= q
->start_time
;
3289 /* Process the task per the caller's callback */
3294 * If we had to process any tasks at all, scan again
3295 * in case some of them were in the middle of forking
3296 * children that didn't get processed.
3297 * Not the most efficient way to do it, but it avoids
3298 * having to take callback_mutex in the fork path
3302 if (heap
== &tmp_heap
)
3303 heap_free(&tmp_heap
);
3307 static void cgroup_transfer_one_task(struct task_struct
*task
, void *data
)
3309 struct cgroup
*new_cgroup
= data
;
3311 mutex_lock(&cgroup_mutex
);
3312 cgroup_attach_task(new_cgroup
, task
, false);
3313 mutex_unlock(&cgroup_mutex
);
3317 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3318 * @to: cgroup to which the tasks will be moved
3319 * @from: cgroup in which the tasks currently reside
3321 int cgroup_transfer_tasks(struct cgroup
*to
, struct cgroup
*from
)
3323 return css_scan_tasks(&from
->dummy_css
, NULL
, cgroup_transfer_one_task
,
3328 * Stuff for reading the 'tasks'/'procs' files.
3330 * Reading this file can return large amounts of data if a cgroup has
3331 * *lots* of attached tasks. So it may need several calls to read(),
3332 * but we cannot guarantee that the information we produce is correct
3333 * unless we produce it entirely atomically.
3337 /* which pidlist file are we talking about? */
3338 enum cgroup_filetype
{
3344 * A pidlist is a list of pids that virtually represents the contents of one
3345 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3346 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3349 struct cgroup_pidlist
{
3351 * used to find which pidlist is wanted. doesn't change as long as
3352 * this particular list stays in the list.
3354 struct { enum cgroup_filetype type
; struct pid_namespace
*ns
; } key
;
3357 /* how many elements the above list has */
3359 /* each of these stored in a list by its cgroup */
3360 struct list_head links
;
3361 /* pointer to the cgroup we belong to, for list removal purposes */
3362 struct cgroup
*owner
;
3363 /* for delayed destruction */
3364 struct delayed_work destroy_dwork
;
3368 * The following two functions "fix" the issue where there are more pids
3369 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3370 * TODO: replace with a kernel-wide solution to this problem
3372 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3373 static void *pidlist_allocate(int count
)
3375 if (PIDLIST_TOO_LARGE(count
))
3376 return vmalloc(count
* sizeof(pid_t
));
3378 return kmalloc(count
* sizeof(pid_t
), GFP_KERNEL
);
3381 static void pidlist_free(void *p
)
3383 if (is_vmalloc_addr(p
))
3390 * Used to destroy all pidlists lingering waiting for destroy timer. None
3391 * should be left afterwards.
3393 static void cgroup_pidlist_destroy_all(struct cgroup
*cgrp
)
3395 struct cgroup_pidlist
*l
, *tmp_l
;
3397 mutex_lock(&cgrp
->pidlist_mutex
);
3398 list_for_each_entry_safe(l
, tmp_l
, &cgrp
->pidlists
, links
)
3399 mod_delayed_work(cgroup_pidlist_destroy_wq
, &l
->destroy_dwork
, 0);
3400 mutex_unlock(&cgrp
->pidlist_mutex
);
3402 flush_workqueue(cgroup_pidlist_destroy_wq
);
3403 BUG_ON(!list_empty(&cgrp
->pidlists
));
3406 static void cgroup_pidlist_destroy_work_fn(struct work_struct
*work
)
3408 struct delayed_work
*dwork
= to_delayed_work(work
);
3409 struct cgroup_pidlist
*l
= container_of(dwork
, struct cgroup_pidlist
,
3411 struct cgroup_pidlist
*tofree
= NULL
;
3413 mutex_lock(&l
->owner
->pidlist_mutex
);
3416 * Destroy iff we didn't get queued again. The state won't change
3417 * as destroy_dwork can only be queued while locked.
3419 if (!delayed_work_pending(dwork
)) {
3420 list_del(&l
->links
);
3421 pidlist_free(l
->list
);
3422 put_pid_ns(l
->key
.ns
);
3426 mutex_unlock(&l
->owner
->pidlist_mutex
);
3431 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3432 * Returns the number of unique elements.
3434 static int pidlist_uniq(pid_t
*list
, int length
)
3439 * we presume the 0th element is unique, so i starts at 1. trivial
3440 * edge cases first; no work needs to be done for either
3442 if (length
== 0 || length
== 1)
3444 /* src and dest walk down the list; dest counts unique elements */
3445 for (src
= 1; src
< length
; src
++) {
3446 /* find next unique element */
3447 while (list
[src
] == list
[src
-1]) {
3452 /* dest always points to where the next unique element goes */
3453 list
[dest
] = list
[src
];
3461 * The two pid files - task and cgroup.procs - guaranteed that the result
3462 * is sorted, which forced this whole pidlist fiasco. As pid order is
3463 * different per namespace, each namespace needs differently sorted list,
3464 * making it impossible to use, for example, single rbtree of member tasks
3465 * sorted by task pointer. As pidlists can be fairly large, allocating one
3466 * per open file is dangerous, so cgroup had to implement shared pool of
3467 * pidlists keyed by cgroup and namespace.
3469 * All this extra complexity was caused by the original implementation
3470 * committing to an entirely unnecessary property. In the long term, we
3471 * want to do away with it. Explicitly scramble sort order if
3472 * sane_behavior so that no such expectation exists in the new interface.
3474 * Scrambling is done by swapping every two consecutive bits, which is
3475 * non-identity one-to-one mapping which disturbs sort order sufficiently.
3477 static pid_t
pid_fry(pid_t pid
)
3479 unsigned a
= pid
& 0x55555555;
3480 unsigned b
= pid
& 0xAAAAAAAA;
3482 return (a
<< 1) | (b
>> 1);
3485 static pid_t
cgroup_pid_fry(struct cgroup
*cgrp
, pid_t pid
)
3487 if (cgroup_sane_behavior(cgrp
))
3488 return pid_fry(pid
);
3493 static int cmppid(const void *a
, const void *b
)
3495 return *(pid_t
*)a
- *(pid_t
*)b
;
3498 static int fried_cmppid(const void *a
, const void *b
)
3500 return pid_fry(*(pid_t
*)a
) - pid_fry(*(pid_t
*)b
);
3503 static struct cgroup_pidlist
*cgroup_pidlist_find(struct cgroup
*cgrp
,
3504 enum cgroup_filetype type
)
3506 struct cgroup_pidlist
*l
;
3507 /* don't need task_nsproxy() if we're looking at ourself */
3508 struct pid_namespace
*ns
= task_active_pid_ns(current
);
3510 lockdep_assert_held(&cgrp
->pidlist_mutex
);
3512 list_for_each_entry(l
, &cgrp
->pidlists
, links
)
3513 if (l
->key
.type
== type
&& l
->key
.ns
== ns
)
3519 * find the appropriate pidlist for our purpose (given procs vs tasks)
3520 * returns with the lock on that pidlist already held, and takes care
3521 * of the use count, or returns NULL with no locks held if we're out of
3524 static struct cgroup_pidlist
*cgroup_pidlist_find_create(struct cgroup
*cgrp
,
3525 enum cgroup_filetype type
)
3527 struct cgroup_pidlist
*l
;
3529 lockdep_assert_held(&cgrp
->pidlist_mutex
);
3531 l
= cgroup_pidlist_find(cgrp
, type
);
3535 /* entry not found; create a new one */
3536 l
= kzalloc(sizeof(struct cgroup_pidlist
), GFP_KERNEL
);
3540 INIT_DELAYED_WORK(&l
->destroy_dwork
, cgroup_pidlist_destroy_work_fn
);
3542 /* don't need task_nsproxy() if we're looking at ourself */
3543 l
->key
.ns
= get_pid_ns(task_active_pid_ns(current
));
3545 list_add(&l
->links
, &cgrp
->pidlists
);
3550 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3552 static int pidlist_array_load(struct cgroup
*cgrp
, enum cgroup_filetype type
,
3553 struct cgroup_pidlist
**lp
)
3557 int pid
, n
= 0; /* used for populating the array */
3558 struct css_task_iter it
;
3559 struct task_struct
*tsk
;
3560 struct cgroup_pidlist
*l
;
3562 lockdep_assert_held(&cgrp
->pidlist_mutex
);
3565 * If cgroup gets more users after we read count, we won't have
3566 * enough space - tough. This race is indistinguishable to the
3567 * caller from the case that the additional cgroup users didn't
3568 * show up until sometime later on.
3570 length
= cgroup_task_count(cgrp
);
3571 array
= pidlist_allocate(length
);
3574 /* now, populate the array */
3575 css_task_iter_start(&cgrp
->dummy_css
, &it
);
3576 while ((tsk
= css_task_iter_next(&it
))) {
3577 if (unlikely(n
== length
))
3579 /* get tgid or pid for procs or tasks file respectively */
3580 if (type
== CGROUP_FILE_PROCS
)
3581 pid
= task_tgid_vnr(tsk
);
3583 pid
= task_pid_vnr(tsk
);
3584 if (pid
> 0) /* make sure to only use valid results */
3587 css_task_iter_end(&it
);
3589 /* now sort & (if procs) strip out duplicates */
3590 if (cgroup_sane_behavior(cgrp
))
3591 sort(array
, length
, sizeof(pid_t
), fried_cmppid
, NULL
);
3593 sort(array
, length
, sizeof(pid_t
), cmppid
, NULL
);
3594 if (type
== CGROUP_FILE_PROCS
)
3595 length
= pidlist_uniq(array
, length
);
3597 l
= cgroup_pidlist_find_create(cgrp
, type
);
3599 mutex_unlock(&cgrp
->pidlist_mutex
);
3600 pidlist_free(array
);
3604 /* store array, freeing old if necessary */
3605 pidlist_free(l
->list
);
3613 * cgroupstats_build - build and fill cgroupstats
3614 * @stats: cgroupstats to fill information into
3615 * @dentry: A dentry entry belonging to the cgroup for which stats have
3618 * Build and fill cgroupstats so that taskstats can export it to user
3621 int cgroupstats_build(struct cgroupstats
*stats
, struct dentry
*dentry
)
3624 struct cgroup
*cgrp
;
3625 struct css_task_iter it
;
3626 struct task_struct
*tsk
;
3629 * Validate dentry by checking the superblock operations,
3630 * and make sure it's a directory.
3632 if (dentry
->d_sb
->s_op
!= &cgroup_ops
||
3633 !S_ISDIR(dentry
->d_inode
->i_mode
))
3637 cgrp
= dentry
->d_fsdata
;
3639 css_task_iter_start(&cgrp
->dummy_css
, &it
);
3640 while ((tsk
= css_task_iter_next(&it
))) {
3641 switch (tsk
->state
) {
3643 stats
->nr_running
++;
3645 case TASK_INTERRUPTIBLE
:
3646 stats
->nr_sleeping
++;
3648 case TASK_UNINTERRUPTIBLE
:
3649 stats
->nr_uninterruptible
++;
3652 stats
->nr_stopped
++;
3655 if (delayacct_is_task_waiting_on_io(tsk
))
3656 stats
->nr_io_wait
++;
3660 css_task_iter_end(&it
);
3668 * seq_file methods for the tasks/procs files. The seq_file position is the
3669 * next pid to display; the seq_file iterator is a pointer to the pid
3670 * in the cgroup->l->list array.
3673 static void *cgroup_pidlist_start(struct seq_file
*s
, loff_t
*pos
)
3676 * Initially we receive a position value that corresponds to
3677 * one more than the last pid shown (or 0 on the first call or
3678 * after a seek to the start). Use a binary-search to find the
3679 * next pid to display, if any
3681 struct cgroup_open_file
*of
= s
->private;
3682 struct cgroup
*cgrp
= seq_css(s
)->cgroup
;
3683 struct cgroup_pidlist
*l
;
3684 enum cgroup_filetype type
= seq_cft(s
)->private;
3685 int index
= 0, pid
= *pos
;
3688 mutex_lock(&cgrp
->pidlist_mutex
);
3691 * !NULL @of->priv indicates that this isn't the first start()
3692 * after open. If the matching pidlist is around, we can use that.
3693 * Look for it. Note that @of->priv can't be used directly. It
3694 * could already have been destroyed.
3697 of
->priv
= cgroup_pidlist_find(cgrp
, type
);
3700 * Either this is the first start() after open or the matching
3701 * pidlist has been destroyed inbetween. Create a new one.
3704 ret
= pidlist_array_load(cgrp
, type
,
3705 (struct cgroup_pidlist
**)&of
->priv
);
3707 return ERR_PTR(ret
);
3712 int end
= l
->length
;
3714 while (index
< end
) {
3715 int mid
= (index
+ end
) / 2;
3716 if (cgroup_pid_fry(cgrp
, l
->list
[mid
]) == pid
) {
3719 } else if (cgroup_pid_fry(cgrp
, l
->list
[mid
]) <= pid
)
3725 /* If we're off the end of the array, we're done */
3726 if (index
>= l
->length
)
3728 /* Update the abstract position to be the actual pid that we found */
3729 iter
= l
->list
+ index
;
3730 *pos
= cgroup_pid_fry(cgrp
, *iter
);
3734 static void cgroup_pidlist_stop(struct seq_file
*s
, void *v
)
3736 struct cgroup_open_file
*of
= s
->private;
3737 struct cgroup_pidlist
*l
= of
->priv
;
3740 mod_delayed_work(cgroup_pidlist_destroy_wq
, &l
->destroy_dwork
,
3741 CGROUP_PIDLIST_DESTROY_DELAY
);
3742 mutex_unlock(&seq_css(s
)->cgroup
->pidlist_mutex
);
3745 static void *cgroup_pidlist_next(struct seq_file
*s
, void *v
, loff_t
*pos
)
3747 struct cgroup_open_file
*of
= s
->private;
3748 struct cgroup_pidlist
*l
= of
->priv
;
3750 pid_t
*end
= l
->list
+ l
->length
;
3752 * Advance to the next pid in the array. If this goes off the
3759 *pos
= cgroup_pid_fry(seq_css(s
)->cgroup
, *p
);
3764 static int cgroup_pidlist_show(struct seq_file
*s
, void *v
)
3766 return seq_printf(s
, "%d\n", *(int *)v
);
3770 * seq_operations functions for iterating on pidlists through seq_file -
3771 * independent of whether it's tasks or procs
3773 static const struct seq_operations cgroup_pidlist_seq_operations
= {
3774 .start
= cgroup_pidlist_start
,
3775 .stop
= cgroup_pidlist_stop
,
3776 .next
= cgroup_pidlist_next
,
3777 .show
= cgroup_pidlist_show
,
3780 static const struct file_operations cgroup_pidlist_operations
= {
3782 .llseek
= seq_lseek
,
3783 .write
= cgroup_file_write
,
3784 .release
= seq_release_private
,
3788 * The following functions handle opens on a file that displays a pidlist
3789 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3792 /* helper function for the two below it */
3793 static int cgroup_pidlist_open(struct inode
*unused
, struct file
*file
)
3795 struct cfent
*cfe
= __d_cfe(file
->f_dentry
);
3796 struct cgroup_open_file
*of
;
3798 /* configure file information */
3799 file
->f_op
= &cgroup_pidlist_operations
;
3801 of
= __seq_open_private(file
, &cgroup_pidlist_seq_operations
,
3810 static u64
cgroup_read_notify_on_release(struct cgroup_subsys_state
*css
,
3813 return notify_on_release(css
->cgroup
);
3816 static int cgroup_write_notify_on_release(struct cgroup_subsys_state
*css
,
3817 struct cftype
*cft
, u64 val
)
3819 clear_bit(CGRP_RELEASABLE
, &css
->cgroup
->flags
);
3821 set_bit(CGRP_NOTIFY_ON_RELEASE
, &css
->cgroup
->flags
);
3823 clear_bit(CGRP_NOTIFY_ON_RELEASE
, &css
->cgroup
->flags
);
3828 * When dput() is called asynchronously, if umount has been done and
3829 * then deactivate_super() in cgroup_free_fn() kills the superblock,
3830 * there's a small window that vfs will see the root dentry with non-zero
3831 * refcnt and trigger BUG().
3833 * That's why we hold a reference before dput() and drop it right after.
3835 static void cgroup_dput(struct cgroup
*cgrp
)
3837 struct super_block
*sb
= cgrp
->root
->sb
;
3839 atomic_inc(&sb
->s_active
);
3841 deactivate_super(sb
);
3844 static u64
cgroup_clone_children_read(struct cgroup_subsys_state
*css
,
3847 return test_bit(CGRP_CPUSET_CLONE_CHILDREN
, &css
->cgroup
->flags
);
3850 static int cgroup_clone_children_write(struct cgroup_subsys_state
*css
,
3851 struct cftype
*cft
, u64 val
)
3854 set_bit(CGRP_CPUSET_CLONE_CHILDREN
, &css
->cgroup
->flags
);
3856 clear_bit(CGRP_CPUSET_CLONE_CHILDREN
, &css
->cgroup
->flags
);
3860 static struct cftype cgroup_base_files
[] = {
3862 .name
= "cgroup.procs",
3863 .open
= cgroup_pidlist_open
,
3864 .private = CGROUP_FILE_PROCS
,
3865 .write_u64
= cgroup_procs_write
,
3866 .mode
= S_IRUGO
| S_IWUSR
,
3869 .name
= "cgroup.clone_children",
3870 .flags
= CFTYPE_INSANE
,
3871 .read_u64
= cgroup_clone_children_read
,
3872 .write_u64
= cgroup_clone_children_write
,
3875 .name
= "cgroup.sane_behavior",
3876 .flags
= CFTYPE_ONLY_ON_ROOT
,
3877 .seq_show
= cgroup_sane_behavior_show
,
3881 * Historical crazy stuff. These don't have "cgroup." prefix and
3882 * don't exist if sane_behavior. If you're depending on these, be
3883 * prepared to be burned.
3887 .flags
= CFTYPE_INSANE
, /* use "procs" instead */
3888 .open
= cgroup_pidlist_open
,
3889 .private = CGROUP_FILE_TASKS
,
3890 .write_u64
= cgroup_tasks_write
,
3891 .mode
= S_IRUGO
| S_IWUSR
,
3894 .name
= "notify_on_release",
3895 .flags
= CFTYPE_INSANE
,
3896 .read_u64
= cgroup_read_notify_on_release
,
3897 .write_u64
= cgroup_write_notify_on_release
,
3900 .name
= "release_agent",
3901 .flags
= CFTYPE_INSANE
| CFTYPE_ONLY_ON_ROOT
,
3902 .seq_show
= cgroup_release_agent_show
,
3903 .write_string
= cgroup_release_agent_write
,
3904 .max_write_len
= PATH_MAX
,
3910 * cgroup_populate_dir - create subsys files in a cgroup directory
3911 * @cgrp: target cgroup
3912 * @subsys_mask: mask of the subsystem ids whose files should be added
3914 * On failure, no file is added.
3916 static int cgroup_populate_dir(struct cgroup
*cgrp
, unsigned long subsys_mask
)
3918 struct cgroup_subsys
*ss
;
3921 /* process cftsets of each subsystem */
3922 for_each_subsys(ss
, i
) {
3923 struct cftype_set
*set
;
3925 if (!test_bit(i
, &subsys_mask
))
3928 list_for_each_entry(set
, &ss
->cftsets
, node
) {
3929 ret
= cgroup_addrm_files(cgrp
, set
->cfts
, true);
3936 cgroup_clear_dir(cgrp
, subsys_mask
);
3941 * css destruction is four-stage process.
3943 * 1. Destruction starts. Killing of the percpu_ref is initiated.
3944 * Implemented in kill_css().
3946 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
3947 * and thus css_tryget() is guaranteed to fail, the css can be offlined
3948 * by invoking offline_css(). After offlining, the base ref is put.
3949 * Implemented in css_killed_work_fn().
3951 * 3. When the percpu_ref reaches zero, the only possible remaining
3952 * accessors are inside RCU read sections. css_release() schedules the
3955 * 4. After the grace period, the css can be freed. Implemented in
3956 * css_free_work_fn().
3958 * It is actually hairier because both step 2 and 4 require process context
3959 * and thus involve punting to css->destroy_work adding two additional
3960 * steps to the already complex sequence.
3962 static void css_free_work_fn(struct work_struct
*work
)
3964 struct cgroup_subsys_state
*css
=
3965 container_of(work
, struct cgroup_subsys_state
, destroy_work
);
3966 struct cgroup
*cgrp
= css
->cgroup
;
3969 css_put(css
->parent
);
3971 css
->ss
->css_free(css
);
3975 static void css_free_rcu_fn(struct rcu_head
*rcu_head
)
3977 struct cgroup_subsys_state
*css
=
3978 container_of(rcu_head
, struct cgroup_subsys_state
, rcu_head
);
3981 * css holds an extra ref to @cgrp->dentry which is put on the last
3982 * css_put(). dput() requires process context which we don't have.
3984 INIT_WORK(&css
->destroy_work
, css_free_work_fn
);
3985 queue_work(cgroup_destroy_wq
, &css
->destroy_work
);
3988 static void css_release(struct percpu_ref
*ref
)
3990 struct cgroup_subsys_state
*css
=
3991 container_of(ref
, struct cgroup_subsys_state
, refcnt
);
3993 call_rcu(&css
->rcu_head
, css_free_rcu_fn
);
3996 static void init_css(struct cgroup_subsys_state
*css
, struct cgroup_subsys
*ss
,
3997 struct cgroup
*cgrp
)
4004 css
->parent
= cgroup_css(cgrp
->parent
, ss
);
4006 css
->flags
|= CSS_ROOT
;
4008 BUG_ON(cgroup_css(cgrp
, ss
));
4011 /* invoke ->css_online() on a new CSS and mark it online if successful */
4012 static int online_css(struct cgroup_subsys_state
*css
)
4014 struct cgroup_subsys
*ss
= css
->ss
;
4017 lockdep_assert_held(&cgroup_mutex
);
4020 ret
= ss
->css_online(css
);
4022 css
->flags
|= CSS_ONLINE
;
4023 css
->cgroup
->nr_css
++;
4024 rcu_assign_pointer(css
->cgroup
->subsys
[ss
->subsys_id
], css
);
4029 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4030 static void offline_css(struct cgroup_subsys_state
*css
)
4032 struct cgroup_subsys
*ss
= css
->ss
;
4034 lockdep_assert_held(&cgroup_mutex
);
4036 if (!(css
->flags
& CSS_ONLINE
))
4039 if (ss
->css_offline
)
4040 ss
->css_offline(css
);
4042 css
->flags
&= ~CSS_ONLINE
;
4043 css
->cgroup
->nr_css
--;
4044 RCU_INIT_POINTER(css
->cgroup
->subsys
[ss
->subsys_id
], css
);
4048 * cgroup_create - create a cgroup
4049 * @parent: cgroup that will be parent of the new cgroup
4050 * @dentry: dentry of the new cgroup
4051 * @mode: mode to set on new inode
4053 * Must be called with the mutex on the parent inode held
4055 static long cgroup_create(struct cgroup
*parent
, struct dentry
*dentry
,
4058 struct cgroup_subsys_state
*css_ar
[CGROUP_SUBSYS_COUNT
] = { };
4059 struct cgroup
*cgrp
;
4060 struct cgroup_name
*name
;
4061 struct cgroupfs_root
*root
= parent
->root
;
4063 struct cgroup_subsys
*ss
;
4064 struct super_block
*sb
= root
->sb
;
4066 /* allocate the cgroup and its ID, 0 is reserved for the root */
4067 cgrp
= kzalloc(sizeof(*cgrp
), GFP_KERNEL
);
4071 name
= cgroup_alloc_name(dentry
);
4074 rcu_assign_pointer(cgrp
->name
, name
);
4077 * Temporarily set the pointer to NULL, so idr_find() won't return
4078 * a half-baked cgroup.
4080 cgrp
->id
= idr_alloc(&root
->cgroup_idr
, NULL
, 1, 0, GFP_KERNEL
);
4085 * Only live parents can have children. Note that the liveliness
4086 * check isn't strictly necessary because cgroup_mkdir() and
4087 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4088 * anyway so that locking is contained inside cgroup proper and we
4089 * don't get nasty surprises if we ever grow another caller.
4091 if (!cgroup_lock_live_group(parent
)) {
4096 /* Grab a reference on the superblock so the hierarchy doesn't
4097 * get deleted on unmount if there are child cgroups. This
4098 * can be done outside cgroup_mutex, since the sb can't
4099 * disappear while someone has an open control file on the
4101 atomic_inc(&sb
->s_active
);
4103 init_cgroup_housekeeping(cgrp
);
4105 dentry
->d_fsdata
= cgrp
;
4106 cgrp
->dentry
= dentry
;
4108 cgrp
->parent
= parent
;
4109 cgrp
->dummy_css
.parent
= &parent
->dummy_css
;
4110 cgrp
->root
= parent
->root
;
4112 if (notify_on_release(parent
))
4113 set_bit(CGRP_NOTIFY_ON_RELEASE
, &cgrp
->flags
);
4115 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN
, &parent
->flags
))
4116 set_bit(CGRP_CPUSET_CLONE_CHILDREN
, &cgrp
->flags
);
4118 for_each_root_subsys(root
, ss
) {
4119 struct cgroup_subsys_state
*css
;
4121 css
= ss
->css_alloc(cgroup_css(parent
, ss
));
4126 css_ar
[ss
->subsys_id
] = css
;
4128 err
= percpu_ref_init(&css
->refcnt
, css_release
);
4132 init_css(css
, ss
, cgrp
);
4136 * Create directory. cgroup_create_file() returns with the new
4137 * directory locked on success so that it can be populated without
4138 * dropping cgroup_mutex.
4140 err
= cgroup_create_file(dentry
, S_IFDIR
| mode
, sb
);
4143 lockdep_assert_held(&dentry
->d_inode
->i_mutex
);
4145 cgrp
->serial_nr
= cgroup_serial_nr_next
++;
4147 /* allocation complete, commit to creation */
4148 list_add_tail_rcu(&cgrp
->sibling
, &cgrp
->parent
->children
);
4149 root
->number_of_cgroups
++;
4151 /* each css holds a ref to the cgroup's dentry and the parent css */
4152 for_each_root_subsys(root
, ss
) {
4153 struct cgroup_subsys_state
*css
= css_ar
[ss
->subsys_id
];
4156 css_get(css
->parent
);
4159 /* hold a ref to the parent's dentry */
4160 dget(parent
->dentry
);
4162 /* creation succeeded, notify subsystems */
4163 for_each_root_subsys(root
, ss
) {
4164 struct cgroup_subsys_state
*css
= css_ar
[ss
->subsys_id
];
4166 err
= online_css(css
);
4170 if (ss
->broken_hierarchy
&& !ss
->warned_broken_hierarchy
&&
4172 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",
4173 current
->comm
, current
->pid
, ss
->name
);
4174 if (!strcmp(ss
->name
, "memory"))
4175 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4176 ss
->warned_broken_hierarchy
= true;
4180 idr_replace(&root
->cgroup_idr
, cgrp
, cgrp
->id
);
4182 err
= cgroup_addrm_files(cgrp
, cgroup_base_files
, true);
4186 err
= cgroup_populate_dir(cgrp
, root
->subsys_mask
);
4190 mutex_unlock(&cgroup_mutex
);
4191 mutex_unlock(&cgrp
->dentry
->d_inode
->i_mutex
);
4196 for_each_root_subsys(root
, ss
) {
4197 struct cgroup_subsys_state
*css
= css_ar
[ss
->subsys_id
];
4200 percpu_ref_cancel_init(&css
->refcnt
);
4204 mutex_unlock(&cgroup_mutex
);
4205 /* Release the reference count that we took on the superblock */
4206 deactivate_super(sb
);
4208 idr_remove(&root
->cgroup_idr
, cgrp
->id
);
4210 kfree(rcu_dereference_raw(cgrp
->name
));
4216 cgroup_destroy_locked(cgrp
);
4217 mutex_unlock(&cgroup_mutex
);
4218 mutex_unlock(&dentry
->d_inode
->i_mutex
);
4222 static int cgroup_mkdir(struct inode
*dir
, struct dentry
*dentry
, umode_t mode
)
4224 struct cgroup
*c_parent
= dentry
->d_parent
->d_fsdata
;
4226 /* the vfs holds inode->i_mutex already */
4227 return cgroup_create(c_parent
, dentry
, mode
| S_IFDIR
);
4231 * This is called when the refcnt of a css is confirmed to be killed.
4232 * css_tryget() is now guaranteed to fail.
4234 static void css_killed_work_fn(struct work_struct
*work
)
4236 struct cgroup_subsys_state
*css
=
4237 container_of(work
, struct cgroup_subsys_state
, destroy_work
);
4238 struct cgroup
*cgrp
= css
->cgroup
;
4240 mutex_lock(&cgroup_mutex
);
4243 * css_tryget() is guaranteed to fail now. Tell subsystems to
4244 * initate destruction.
4249 * If @cgrp is marked dead, it's waiting for refs of all css's to
4250 * be disabled before proceeding to the second phase of cgroup
4251 * destruction. If we are the last one, kick it off.
4253 if (!cgrp
->nr_css
&& cgroup_is_dead(cgrp
))
4254 cgroup_destroy_css_killed(cgrp
);
4256 mutex_unlock(&cgroup_mutex
);
4259 * Put the css refs from kill_css(). Each css holds an extra
4260 * reference to the cgroup's dentry and cgroup removal proceeds
4261 * regardless of css refs. On the last put of each css, whenever
4262 * that may be, the extra dentry ref is put so that dentry
4263 * destruction happens only after all css's are released.
4268 /* css kill confirmation processing requires process context, bounce */
4269 static void css_killed_ref_fn(struct percpu_ref
*ref
)
4271 struct cgroup_subsys_state
*css
=
4272 container_of(ref
, struct cgroup_subsys_state
, refcnt
);
4274 INIT_WORK(&css
->destroy_work
, css_killed_work_fn
);
4275 queue_work(cgroup_destroy_wq
, &css
->destroy_work
);
4279 * kill_css - destroy a css
4280 * @css: css to destroy
4282 * This function initiates destruction of @css by removing cgroup interface
4283 * files and putting its base reference. ->css_offline() will be invoked
4284 * asynchronously once css_tryget() is guaranteed to fail and when the
4285 * reference count reaches zero, @css will be released.
4287 static void kill_css(struct cgroup_subsys_state
*css
)
4289 cgroup_clear_dir(css
->cgroup
, 1 << css
->ss
->subsys_id
);
4292 * Killing would put the base ref, but we need to keep it alive
4293 * until after ->css_offline().
4298 * cgroup core guarantees that, by the time ->css_offline() is
4299 * invoked, no new css reference will be given out via
4300 * css_tryget(). We can't simply call percpu_ref_kill() and
4301 * proceed to offlining css's because percpu_ref_kill() doesn't
4302 * guarantee that the ref is seen as killed on all CPUs on return.
4304 * Use percpu_ref_kill_and_confirm() to get notifications as each
4305 * css is confirmed to be seen as killed on all CPUs.
4307 percpu_ref_kill_and_confirm(&css
->refcnt
, css_killed_ref_fn
);
4311 * cgroup_destroy_locked - the first stage of cgroup destruction
4312 * @cgrp: cgroup to be destroyed
4314 * css's make use of percpu refcnts whose killing latency shouldn't be
4315 * exposed to userland and are RCU protected. Also, cgroup core needs to
4316 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
4317 * invoked. To satisfy all the requirements, destruction is implemented in
4318 * the following two steps.
4320 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4321 * userland visible parts and start killing the percpu refcnts of
4322 * css's. Set up so that the next stage will be kicked off once all
4323 * the percpu refcnts are confirmed to be killed.
4325 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4326 * rest of destruction. Once all cgroup references are gone, the
4327 * cgroup is RCU-freed.
4329 * This function implements s1. After this step, @cgrp is gone as far as
4330 * the userland is concerned and a new cgroup with the same name may be
4331 * created. As cgroup doesn't care about the names internally, this
4332 * doesn't cause any problem.
4334 static int cgroup_destroy_locked(struct cgroup
*cgrp
)
4335 __releases(&cgroup_mutex
) __acquires(&cgroup_mutex
)
4337 struct dentry
*d
= cgrp
->dentry
;
4338 struct cgroup_subsys
*ss
;
4339 struct cgroup
*child
;
4342 lockdep_assert_held(&d
->d_inode
->i_mutex
);
4343 lockdep_assert_held(&cgroup_mutex
);
4346 * css_set_lock synchronizes access to ->cset_links and prevents
4347 * @cgrp from being removed while __put_css_set() is in progress.
4349 read_lock(&css_set_lock
);
4350 empty
= list_empty(&cgrp
->cset_links
);
4351 read_unlock(&css_set_lock
);
4356 * Make sure there's no live children. We can't test ->children
4357 * emptiness as dead children linger on it while being destroyed;
4358 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
4362 list_for_each_entry_rcu(child
, &cgrp
->children
, sibling
) {
4363 empty
= cgroup_is_dead(child
);
4372 * Initiate massacre of all css's. cgroup_destroy_css_killed()
4373 * will be invoked to perform the rest of destruction once the
4374 * percpu refs of all css's are confirmed to be killed.
4376 for_each_root_subsys(cgrp
->root
, ss
)
4377 kill_css(cgroup_css(cgrp
, ss
));
4380 * Mark @cgrp dead. This prevents further task migration and child
4381 * creation by disabling cgroup_lock_live_group(). Note that
4382 * CGRP_DEAD assertion is depended upon by css_next_child() to
4383 * resume iteration after dropping RCU read lock. See
4384 * css_next_child() for details.
4386 set_bit(CGRP_DEAD
, &cgrp
->flags
);
4388 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4389 raw_spin_lock(&release_list_lock
);
4390 if (!list_empty(&cgrp
->release_list
))
4391 list_del_init(&cgrp
->release_list
);
4392 raw_spin_unlock(&release_list_lock
);
4395 * If @cgrp has css's attached, the second stage of cgroup
4396 * destruction is kicked off from css_killed_work_fn() after the
4397 * refs of all attached css's are killed. If @cgrp doesn't have
4398 * any css, we kick it off here.
4401 cgroup_destroy_css_killed(cgrp
);
4404 * Clear the base files and remove @cgrp directory. The removal
4405 * puts the base ref but we aren't quite done with @cgrp yet, so
4408 cgroup_addrm_files(cgrp
, cgroup_base_files
, false);
4410 cgroup_d_remove_dir(d
);
4416 * cgroup_destroy_css_killed - the second step of cgroup destruction
4417 * @work: cgroup->destroy_free_work
4419 * This function is invoked from a work item for a cgroup which is being
4420 * destroyed after all css's are offlined and performs the rest of
4421 * destruction. This is the second step of destruction described in the
4422 * comment above cgroup_destroy_locked().
4424 static void cgroup_destroy_css_killed(struct cgroup
*cgrp
)
4426 struct cgroup
*parent
= cgrp
->parent
;
4427 struct dentry
*d
= cgrp
->dentry
;
4429 lockdep_assert_held(&cgroup_mutex
);
4431 /* delete this cgroup from parent->children */
4432 list_del_rcu(&cgrp
->sibling
);
4435 * We should remove the cgroup object from idr before its grace
4436 * period starts, so we won't be looking up a cgroup while the
4437 * cgroup is being freed.
4439 idr_remove(&cgrp
->root
->cgroup_idr
, cgrp
->id
);
4444 set_bit(CGRP_RELEASABLE
, &parent
->flags
);
4445 check_for_release(parent
);
4448 static int cgroup_rmdir(struct inode
*unused_dir
, struct dentry
*dentry
)
4452 mutex_lock(&cgroup_mutex
);
4453 ret
= cgroup_destroy_locked(dentry
->d_fsdata
);
4454 mutex_unlock(&cgroup_mutex
);
4459 static void __init_or_module
cgroup_init_cftsets(struct cgroup_subsys
*ss
)
4461 INIT_LIST_HEAD(&ss
->cftsets
);
4464 * base_cftset is embedded in subsys itself, no need to worry about
4467 if (ss
->base_cftypes
) {
4470 for (cft
= ss
->base_cftypes
; cft
->name
[0] != '\0'; cft
++)
4473 ss
->base_cftset
.cfts
= ss
->base_cftypes
;
4474 list_add_tail(&ss
->base_cftset
.node
, &ss
->cftsets
);
4478 static void __init
cgroup_init_subsys(struct cgroup_subsys
*ss
)
4480 struct cgroup_subsys_state
*css
;
4482 printk(KERN_INFO
"Initializing cgroup subsys %s\n", ss
->name
);
4484 mutex_lock(&cgroup_mutex
);
4486 /* init base cftset */
4487 cgroup_init_cftsets(ss
);
4489 /* Create the top cgroup state for this subsystem */
4490 list_add(&ss
->sibling
, &cgroup_dummy_root
.subsys_list
);
4491 ss
->root
= &cgroup_dummy_root
;
4492 css
= ss
->css_alloc(cgroup_css(cgroup_dummy_top
, ss
));
4493 /* We don't handle early failures gracefully */
4494 BUG_ON(IS_ERR(css
));
4495 init_css(css
, ss
, cgroup_dummy_top
);
4497 /* Update the init_css_set to contain a subsys
4498 * pointer to this state - since the subsystem is
4499 * newly registered, all tasks and hence the
4500 * init_css_set is in the subsystem's top cgroup. */
4501 init_css_set
.subsys
[ss
->subsys_id
] = css
;
4503 need_forkexit_callback
|= ss
->fork
|| ss
->exit
;
4505 /* At system boot, before all subsystems have been
4506 * registered, no tasks have been forked, so we don't
4507 * need to invoke fork callbacks here. */
4508 BUG_ON(!list_empty(&init_task
.tasks
));
4510 BUG_ON(online_css(css
));
4512 mutex_unlock(&cgroup_mutex
);
4514 /* this function shouldn't be used with modular subsystems, since they
4515 * need to register a subsys_id, among other things */
4520 * cgroup_load_subsys: load and register a modular subsystem at runtime
4521 * @ss: the subsystem to load
4523 * This function should be called in a modular subsystem's initcall. If the
4524 * subsystem is built as a module, it will be assigned a new subsys_id and set
4525 * up for use. If the subsystem is built-in anyway, work is delegated to the
4526 * simpler cgroup_init_subsys.
4528 int __init_or_module
cgroup_load_subsys(struct cgroup_subsys
*ss
)
4530 struct cgroup_subsys_state
*css
;
4532 struct hlist_node
*tmp
;
4533 struct css_set
*cset
;
4536 /* check name and function validity */
4537 if (ss
->name
== NULL
|| strlen(ss
->name
) > MAX_CGROUP_TYPE_NAMELEN
||
4538 ss
->css_alloc
== NULL
|| ss
->css_free
== NULL
)
4542 * we don't support callbacks in modular subsystems. this check is
4543 * before the ss->module check for consistency; a subsystem that could
4544 * be a module should still have no callbacks even if the user isn't
4545 * compiling it as one.
4547 if (ss
->fork
|| ss
->exit
)
4551 * an optionally modular subsystem is built-in: we want to do nothing,
4552 * since cgroup_init_subsys will have already taken care of it.
4554 if (ss
->module
== NULL
) {
4555 /* a sanity check */
4556 BUG_ON(cgroup_subsys
[ss
->subsys_id
] != ss
);
4560 /* init base cftset */
4561 cgroup_init_cftsets(ss
);
4563 mutex_lock(&cgroup_mutex
);
4564 cgroup_subsys
[ss
->subsys_id
] = ss
;
4567 * no ss->css_alloc seems to need anything important in the ss
4568 * struct, so this can happen first (i.e. before the dummy root
4571 css
= ss
->css_alloc(cgroup_css(cgroup_dummy_top
, ss
));
4573 /* failure case - need to deassign the cgroup_subsys[] slot. */
4574 cgroup_subsys
[ss
->subsys_id
] = NULL
;
4575 mutex_unlock(&cgroup_mutex
);
4576 return PTR_ERR(css
);
4579 list_add(&ss
->sibling
, &cgroup_dummy_root
.subsys_list
);
4580 ss
->root
= &cgroup_dummy_root
;
4582 /* our new subsystem will be attached to the dummy hierarchy. */
4583 init_css(css
, ss
, cgroup_dummy_top
);
4586 * Now we need to entangle the css into the existing css_sets. unlike
4587 * in cgroup_init_subsys, there are now multiple css_sets, so each one
4588 * will need a new pointer to it; done by iterating the css_set_table.
4589 * furthermore, modifying the existing css_sets will corrupt the hash
4590 * table state, so each changed css_set will need its hash recomputed.
4591 * this is all done under the css_set_lock.
4593 write_lock(&css_set_lock
);
4594 hash_for_each_safe(css_set_table
, i
, tmp
, cset
, hlist
) {
4595 /* skip entries that we already rehashed */
4596 if (cset
->subsys
[ss
->subsys_id
])
4598 /* remove existing entry */
4599 hash_del(&cset
->hlist
);
4601 cset
->subsys
[ss
->subsys_id
] = css
;
4602 /* recompute hash and restore entry */
4603 key
= css_set_hash(cset
->subsys
);
4604 hash_add(css_set_table
, &cset
->hlist
, key
);
4606 write_unlock(&css_set_lock
);
4608 ret
= online_css(css
);
4613 mutex_unlock(&cgroup_mutex
);
4617 mutex_unlock(&cgroup_mutex
);
4618 /* @ss can't be mounted here as try_module_get() would fail */
4619 cgroup_unload_subsys(ss
);
4622 EXPORT_SYMBOL_GPL(cgroup_load_subsys
);
4625 * cgroup_unload_subsys: unload a modular subsystem
4626 * @ss: the subsystem to unload
4628 * This function should be called in a modular subsystem's exitcall. When this
4629 * function is invoked, the refcount on the subsystem's module will be 0, so
4630 * the subsystem will not be attached to any hierarchy.
4632 void cgroup_unload_subsys(struct cgroup_subsys
*ss
)
4634 struct cgrp_cset_link
*link
;
4636 BUG_ON(ss
->module
== NULL
);
4639 * we shouldn't be called if the subsystem is in use, and the use of
4640 * try_module_get() in rebind_subsystems() should ensure that it
4641 * doesn't start being used while we're killing it off.
4643 BUG_ON(ss
->root
!= &cgroup_dummy_root
);
4645 mutex_lock(&cgroup_mutex
);
4647 offline_css(cgroup_css(cgroup_dummy_top
, ss
));
4649 /* deassign the subsys_id */
4650 cgroup_subsys
[ss
->subsys_id
] = NULL
;
4652 /* remove subsystem from the dummy root's list of subsystems */
4653 list_del_init(&ss
->sibling
);
4656 * disentangle the css from all css_sets attached to the dummy
4657 * top. as in loading, we need to pay our respects to the hashtable
4660 write_lock(&css_set_lock
);
4661 list_for_each_entry(link
, &cgroup_dummy_top
->cset_links
, cset_link
) {
4662 struct css_set
*cset
= link
->cset
;
4665 hash_del(&cset
->hlist
);
4666 cset
->subsys
[ss
->subsys_id
] = NULL
;
4667 key
= css_set_hash(cset
->subsys
);
4668 hash_add(css_set_table
, &cset
->hlist
, key
);
4670 write_unlock(&css_set_lock
);
4673 * remove subsystem's css from the cgroup_dummy_top and free it -
4674 * need to free before marking as null because ss->css_free needs
4675 * the cgrp->subsys pointer to find their state.
4677 ss
->css_free(cgroup_css(cgroup_dummy_top
, ss
));
4678 RCU_INIT_POINTER(cgroup_dummy_top
->subsys
[ss
->subsys_id
], NULL
);
4680 mutex_unlock(&cgroup_mutex
);
4682 EXPORT_SYMBOL_GPL(cgroup_unload_subsys
);
4685 * cgroup_init_early - cgroup initialization at system boot
4687 * Initialize cgroups at system boot, and initialize any
4688 * subsystems that request early init.
4690 int __init
cgroup_init_early(void)
4692 struct cgroup_subsys
*ss
;
4695 atomic_set(&init_css_set
.refcount
, 1);
4696 INIT_LIST_HEAD(&init_css_set
.cgrp_links
);
4697 INIT_LIST_HEAD(&init_css_set
.tasks
);
4698 INIT_HLIST_NODE(&init_css_set
.hlist
);
4700 init_cgroup_root(&cgroup_dummy_root
);
4701 cgroup_root_count
= 1;
4702 RCU_INIT_POINTER(init_task
.cgroups
, &init_css_set
);
4704 init_cgrp_cset_link
.cset
= &init_css_set
;
4705 init_cgrp_cset_link
.cgrp
= cgroup_dummy_top
;
4706 list_add(&init_cgrp_cset_link
.cset_link
, &cgroup_dummy_top
->cset_links
);
4707 list_add(&init_cgrp_cset_link
.cgrp_link
, &init_css_set
.cgrp_links
);
4709 /* at bootup time, we don't worry about modular subsystems */
4710 for_each_builtin_subsys(ss
, i
) {
4712 BUG_ON(strlen(ss
->name
) > MAX_CGROUP_TYPE_NAMELEN
);
4713 BUG_ON(!ss
->css_alloc
);
4714 BUG_ON(!ss
->css_free
);
4715 if (ss
->subsys_id
!= i
) {
4716 printk(KERN_ERR
"cgroup: Subsys %s id == %d\n",
4717 ss
->name
, ss
->subsys_id
);
4722 cgroup_init_subsys(ss
);
4728 * cgroup_init - cgroup initialization
4730 * Register cgroup filesystem and /proc file, and initialize
4731 * any subsystems that didn't request early init.
4733 int __init
cgroup_init(void)
4735 struct cgroup_subsys
*ss
;
4739 err
= bdi_init(&cgroup_backing_dev_info
);
4743 for_each_builtin_subsys(ss
, i
) {
4744 if (!ss
->early_init
)
4745 cgroup_init_subsys(ss
);
4748 /* allocate id for the dummy hierarchy */
4749 mutex_lock(&cgroup_mutex
);
4750 mutex_lock(&cgroup_root_mutex
);
4752 /* Add init_css_set to the hash table */
4753 key
= css_set_hash(init_css_set
.subsys
);
4754 hash_add(css_set_table
, &init_css_set
.hlist
, key
);
4756 BUG_ON(cgroup_init_root_id(&cgroup_dummy_root
, 0, 1));
4758 err
= idr_alloc(&cgroup_dummy_root
.cgroup_idr
, cgroup_dummy_top
,
4762 mutex_unlock(&cgroup_root_mutex
);
4763 mutex_unlock(&cgroup_mutex
);
4765 cgroup_kobj
= kobject_create_and_add("cgroup", fs_kobj
);
4771 err
= register_filesystem(&cgroup_fs_type
);
4773 kobject_put(cgroup_kobj
);
4777 proc_create("cgroups", 0, NULL
, &proc_cgroupstats_operations
);
4781 bdi_destroy(&cgroup_backing_dev_info
);
4786 static int __init
cgroup_wq_init(void)
4789 * There isn't much point in executing destruction path in
4790 * parallel. Good chunk is serialized with cgroup_mutex anyway.
4791 * Use 1 for @max_active.
4793 * We would prefer to do this in cgroup_init() above, but that
4794 * is called before init_workqueues(): so leave this until after.
4796 cgroup_destroy_wq
= alloc_workqueue("cgroup_destroy", 0, 1);
4797 BUG_ON(!cgroup_destroy_wq
);
4800 * Used to destroy pidlists and separate to serve as flush domain.
4801 * Cap @max_active to 1 too.
4803 cgroup_pidlist_destroy_wq
= alloc_workqueue("cgroup_pidlist_destroy",
4805 BUG_ON(!cgroup_pidlist_destroy_wq
);
4809 core_initcall(cgroup_wq_init
);
4812 * proc_cgroup_show()
4813 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4814 * - Used for /proc/<pid>/cgroup.
4815 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4816 * doesn't really matter if tsk->cgroup changes after we read it,
4817 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4818 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4819 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4820 * cgroup to top_cgroup.
4823 /* TODO: Use a proper seq_file iterator */
4824 int proc_cgroup_show(struct seq_file
*m
, void *v
)
4827 struct task_struct
*tsk
;
4830 struct cgroupfs_root
*root
;
4833 buf
= kmalloc(PAGE_SIZE
, GFP_KERNEL
);
4839 tsk
= get_pid_task(pid
, PIDTYPE_PID
);
4845 mutex_lock(&cgroup_mutex
);
4847 for_each_active_root(root
) {
4848 struct cgroup_subsys
*ss
;
4849 struct cgroup
*cgrp
;
4852 seq_printf(m
, "%d:", root
->hierarchy_id
);
4853 for_each_root_subsys(root
, ss
)
4854 seq_printf(m
, "%s%s", count
++ ? "," : "", ss
->name
);
4855 if (strlen(root
->name
))
4856 seq_printf(m
, "%sname=%s", count
? "," : "",
4859 cgrp
= task_cgroup_from_root(tsk
, root
);
4860 retval
= cgroup_path(cgrp
, buf
, PAGE_SIZE
);
4868 mutex_unlock(&cgroup_mutex
);
4869 put_task_struct(tsk
);
4876 /* Display information about each subsystem and each hierarchy */
4877 static int proc_cgroupstats_show(struct seq_file
*m
, void *v
)
4879 struct cgroup_subsys
*ss
;
4882 seq_puts(m
, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4884 * ideally we don't want subsystems moving around while we do this.
4885 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4886 * subsys/hierarchy state.
4888 mutex_lock(&cgroup_mutex
);
4890 for_each_subsys(ss
, i
)
4891 seq_printf(m
, "%s\t%d\t%d\t%d\n",
4892 ss
->name
, ss
->root
->hierarchy_id
,
4893 ss
->root
->number_of_cgroups
, !ss
->disabled
);
4895 mutex_unlock(&cgroup_mutex
);
4899 static int cgroupstats_open(struct inode
*inode
, struct file
*file
)
4901 return single_open(file
, proc_cgroupstats_show
, NULL
);
4904 static const struct file_operations proc_cgroupstats_operations
= {
4905 .open
= cgroupstats_open
,
4907 .llseek
= seq_lseek
,
4908 .release
= single_release
,
4912 * cgroup_fork - attach newly forked task to its parents cgroup.
4913 * @child: pointer to task_struct of forking parent process.
4915 * Description: A task inherits its parent's cgroup at fork().
4917 * A pointer to the shared css_set was automatically copied in
4918 * fork.c by dup_task_struct(). However, we ignore that copy, since
4919 * it was not made under the protection of RCU or cgroup_mutex, so
4920 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
4921 * have already changed current->cgroups, allowing the previously
4922 * referenced cgroup group to be removed and freed.
4924 * At the point that cgroup_fork() is called, 'current' is the parent
4925 * task, and the passed argument 'child' points to the child task.
4927 void cgroup_fork(struct task_struct
*child
)
4930 get_css_set(task_css_set(current
));
4931 child
->cgroups
= current
->cgroups
;
4932 task_unlock(current
);
4933 INIT_LIST_HEAD(&child
->cg_list
);
4937 * cgroup_post_fork - called on a new task after adding it to the task list
4938 * @child: the task in question
4940 * Adds the task to the list running through its css_set if necessary and
4941 * call the subsystem fork() callbacks. Has to be after the task is
4942 * visible on the task list in case we race with the first call to
4943 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
4946 void cgroup_post_fork(struct task_struct
*child
)
4948 struct cgroup_subsys
*ss
;
4952 * use_task_css_set_links is set to 1 before we walk the tasklist
4953 * under the tasklist_lock and we read it here after we added the child
4954 * to the tasklist under the tasklist_lock as well. If the child wasn't
4955 * yet in the tasklist when we walked through it from
4956 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4957 * should be visible now due to the paired locking and barriers implied
4958 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4959 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4962 if (use_task_css_set_links
) {
4963 write_lock(&css_set_lock
);
4965 if (list_empty(&child
->cg_list
))
4966 list_add(&child
->cg_list
, &task_css_set(child
)->tasks
);
4968 write_unlock(&css_set_lock
);
4972 * Call ss->fork(). This must happen after @child is linked on
4973 * css_set; otherwise, @child might change state between ->fork()
4974 * and addition to css_set.
4976 if (need_forkexit_callback
) {
4978 * fork/exit callbacks are supported only for builtin
4979 * subsystems, and the builtin section of the subsys
4980 * array is immutable, so we don't need to lock the
4981 * subsys array here. On the other hand, modular section
4982 * of the array can be freed at module unload, so we
4985 for_each_builtin_subsys(ss
, i
)
4992 * cgroup_exit - detach cgroup from exiting task
4993 * @tsk: pointer to task_struct of exiting process
4994 * @run_callback: run exit callbacks?
4996 * Description: Detach cgroup from @tsk and release it.
4998 * Note that cgroups marked notify_on_release force every task in
4999 * them to take the global cgroup_mutex mutex when exiting.
5000 * This could impact scaling on very large systems. Be reluctant to
5001 * use notify_on_release cgroups where very high task exit scaling
5002 * is required on large systems.
5004 * the_top_cgroup_hack:
5006 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
5008 * We call cgroup_exit() while the task is still competent to
5009 * handle notify_on_release(), then leave the task attached to the
5010 * root cgroup in each hierarchy for the remainder of its exit.
5012 * To do this properly, we would increment the reference count on
5013 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
5014 * code we would add a second cgroup function call, to drop that
5015 * reference. This would just create an unnecessary hot spot on
5016 * the top_cgroup reference count, to no avail.
5018 * Normally, holding a reference to a cgroup without bumping its
5019 * count is unsafe. The cgroup could go away, or someone could
5020 * attach us to a different cgroup, decrementing the count on
5021 * the first cgroup that we never incremented. But in this case,
5022 * top_cgroup isn't going away, and either task has PF_EXITING set,
5023 * which wards off any cgroup_attach_task() attempts, or task is a failed
5024 * fork, never visible to cgroup_attach_task.
5026 void cgroup_exit(struct task_struct
*tsk
, int run_callbacks
)
5028 struct cgroup_subsys
*ss
;
5029 struct css_set
*cset
;
5033 * Unlink from the css_set task list if necessary.
5034 * Optimistically check cg_list before taking
5037 if (!list_empty(&tsk
->cg_list
)) {
5038 write_lock(&css_set_lock
);
5039 if (!list_empty(&tsk
->cg_list
))
5040 list_del_init(&tsk
->cg_list
);
5041 write_unlock(&css_set_lock
);
5044 /* Reassign the task to the init_css_set. */
5046 cset
= task_css_set(tsk
);
5047 RCU_INIT_POINTER(tsk
->cgroups
, &init_css_set
);
5049 if (run_callbacks
&& need_forkexit_callback
) {
5051 * fork/exit callbacks are supported only for builtin
5052 * subsystems, see cgroup_post_fork() for details.
5054 for_each_builtin_subsys(ss
, i
) {
5056 struct cgroup_subsys_state
*old_css
= cset
->subsys
[i
];
5057 struct cgroup_subsys_state
*css
= task_css(tsk
, i
);
5059 ss
->exit(css
, old_css
, tsk
);
5065 put_css_set_taskexit(cset
);
5068 static void check_for_release(struct cgroup
*cgrp
)
5070 if (cgroup_is_releasable(cgrp
) &&
5071 list_empty(&cgrp
->cset_links
) && list_empty(&cgrp
->children
)) {
5073 * Control Group is currently removeable. If it's not
5074 * already queued for a userspace notification, queue
5077 int need_schedule_work
= 0;
5079 raw_spin_lock(&release_list_lock
);
5080 if (!cgroup_is_dead(cgrp
) &&
5081 list_empty(&cgrp
->release_list
)) {
5082 list_add(&cgrp
->release_list
, &release_list
);
5083 need_schedule_work
= 1;
5085 raw_spin_unlock(&release_list_lock
);
5086 if (need_schedule_work
)
5087 schedule_work(&release_agent_work
);
5092 * Notify userspace when a cgroup is released, by running the
5093 * configured release agent with the name of the cgroup (path
5094 * relative to the root of cgroup file system) as the argument.
5096 * Most likely, this user command will try to rmdir this cgroup.
5098 * This races with the possibility that some other task will be
5099 * attached to this cgroup before it is removed, or that some other
5100 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5101 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5102 * unused, and this cgroup will be reprieved from its death sentence,
5103 * to continue to serve a useful existence. Next time it's released,
5104 * we will get notified again, if it still has 'notify_on_release' set.
5106 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5107 * means only wait until the task is successfully execve()'d. The
5108 * separate release agent task is forked by call_usermodehelper(),
5109 * then control in this thread returns here, without waiting for the
5110 * release agent task. We don't bother to wait because the caller of
5111 * this routine has no use for the exit status of the release agent
5112 * task, so no sense holding our caller up for that.
5114 static void cgroup_release_agent(struct work_struct
*work
)
5116 BUG_ON(work
!= &release_agent_work
);
5117 mutex_lock(&cgroup_mutex
);
5118 raw_spin_lock(&release_list_lock
);
5119 while (!list_empty(&release_list
)) {
5120 char *argv
[3], *envp
[3];
5122 char *pathbuf
= NULL
, *agentbuf
= NULL
;
5123 struct cgroup
*cgrp
= list_entry(release_list
.next
,
5126 list_del_init(&cgrp
->release_list
);
5127 raw_spin_unlock(&release_list_lock
);
5128 pathbuf
= kmalloc(PAGE_SIZE
, GFP_KERNEL
);
5131 if (cgroup_path(cgrp
, pathbuf
, PAGE_SIZE
) < 0)
5133 agentbuf
= kstrdup(cgrp
->root
->release_agent_path
, GFP_KERNEL
);
5138 argv
[i
++] = agentbuf
;
5139 argv
[i
++] = pathbuf
;
5143 /* minimal command environment */
5144 envp
[i
++] = "HOME=/";
5145 envp
[i
++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5148 /* Drop the lock while we invoke the usermode helper,
5149 * since the exec could involve hitting disk and hence
5150 * be a slow process */
5151 mutex_unlock(&cgroup_mutex
);
5152 call_usermodehelper(argv
[0], argv
, envp
, UMH_WAIT_EXEC
);
5153 mutex_lock(&cgroup_mutex
);
5157 raw_spin_lock(&release_list_lock
);
5159 raw_spin_unlock(&release_list_lock
);
5160 mutex_unlock(&cgroup_mutex
);
5163 static int __init
cgroup_disable(char *str
)
5165 struct cgroup_subsys
*ss
;
5169 while ((token
= strsep(&str
, ",")) != NULL
) {
5174 * cgroup_disable, being at boot time, can't know about
5175 * module subsystems, so we don't worry about them.
5177 for_each_builtin_subsys(ss
, i
) {
5178 if (!strcmp(token
, ss
->name
)) {
5180 printk(KERN_INFO
"Disabling %s control group"
5181 " subsystem\n", ss
->name
);
5188 __setup("cgroup_disable=", cgroup_disable
);
5191 * css_from_dir - get corresponding css from the dentry of a cgroup dir
5192 * @dentry: directory dentry of interest
5193 * @ss: subsystem of interest
5195 * Must be called under RCU read lock. The caller is responsible for
5196 * pinning the returned css if it needs to be accessed outside the RCU
5199 struct cgroup_subsys_state
*css_from_dir(struct dentry
*dentry
,
5200 struct cgroup_subsys
*ss
)
5202 struct cgroup
*cgrp
;
5204 WARN_ON_ONCE(!rcu_read_lock_held());
5206 /* is @dentry a cgroup dir? */
5207 if (!dentry
->d_inode
||
5208 dentry
->d_inode
->i_op
!= &cgroup_dir_inode_operations
)
5209 return ERR_PTR(-EBADF
);
5211 cgrp
= __d_cgrp(dentry
);
5212 return cgroup_css(cgrp
, ss
) ?: ERR_PTR(-ENOENT
);
5216 * css_from_id - lookup css by id
5217 * @id: the cgroup id
5218 * @ss: cgroup subsys to be looked into
5220 * Returns the css if there's valid one with @id, otherwise returns NULL.
5221 * Should be called under rcu_read_lock().
5223 struct cgroup_subsys_state
*css_from_id(int id
, struct cgroup_subsys
*ss
)
5225 struct cgroup
*cgrp
;
5227 rcu_lockdep_assert(rcu_read_lock_held() ||
5228 lockdep_is_held(&cgroup_mutex
),
5229 "css_from_id() needs proper protection");
5231 cgrp
= idr_find(&ss
->root
->cgroup_idr
, id
);
5233 return cgroup_css(cgrp
, ss
);
5237 #ifdef CONFIG_CGROUP_DEBUG
5238 static struct cgroup_subsys_state
*
5239 debug_css_alloc(struct cgroup_subsys_state
*parent_css
)
5241 struct cgroup_subsys_state
*css
= kzalloc(sizeof(*css
), GFP_KERNEL
);
5244 return ERR_PTR(-ENOMEM
);
5249 static void debug_css_free(struct cgroup_subsys_state
*css
)
5254 static u64
debug_taskcount_read(struct cgroup_subsys_state
*css
,
5257 return cgroup_task_count(css
->cgroup
);
5260 static u64
current_css_set_read(struct cgroup_subsys_state
*css
,
5263 return (u64
)(unsigned long)current
->cgroups
;
5266 static u64
current_css_set_refcount_read(struct cgroup_subsys_state
*css
,
5272 count
= atomic_read(&task_css_set(current
)->refcount
);
5277 static int current_css_set_cg_links_read(struct seq_file
*seq
, void *v
)
5279 struct cgrp_cset_link
*link
;
5280 struct css_set
*cset
;
5282 read_lock(&css_set_lock
);
5284 cset
= rcu_dereference(current
->cgroups
);
5285 list_for_each_entry(link
, &cset
->cgrp_links
, cgrp_link
) {
5286 struct cgroup
*c
= link
->cgrp
;
5290 name
= c
->dentry
->d_name
.name
;
5293 seq_printf(seq
, "Root %d group %s\n",
5294 c
->root
->hierarchy_id
, name
);
5297 read_unlock(&css_set_lock
);
5301 #define MAX_TASKS_SHOWN_PER_CSS 25
5302 static int cgroup_css_links_read(struct seq_file
*seq
, void *v
)
5304 struct cgroup_subsys_state
*css
= seq_css(seq
);
5305 struct cgrp_cset_link
*link
;
5307 read_lock(&css_set_lock
);
5308 list_for_each_entry(link
, &css
->cgroup
->cset_links
, cset_link
) {
5309 struct css_set
*cset
= link
->cset
;
5310 struct task_struct
*task
;
5312 seq_printf(seq
, "css_set %p\n", cset
);
5313 list_for_each_entry(task
, &cset
->tasks
, cg_list
) {
5314 if (count
++ > MAX_TASKS_SHOWN_PER_CSS
) {
5315 seq_puts(seq
, " ...\n");
5318 seq_printf(seq
, " task %d\n",
5319 task_pid_vnr(task
));
5323 read_unlock(&css_set_lock
);
5327 static u64
releasable_read(struct cgroup_subsys_state
*css
, struct cftype
*cft
)
5329 return test_bit(CGRP_RELEASABLE
, &css
->cgroup
->flags
);
5332 static struct cftype debug_files
[] = {
5334 .name
= "taskcount",
5335 .read_u64
= debug_taskcount_read
,
5339 .name
= "current_css_set",
5340 .read_u64
= current_css_set_read
,
5344 .name
= "current_css_set_refcount",
5345 .read_u64
= current_css_set_refcount_read
,
5349 .name
= "current_css_set_cg_links",
5350 .seq_show
= current_css_set_cg_links_read
,
5354 .name
= "cgroup_css_links",
5355 .seq_show
= cgroup_css_links_read
,
5359 .name
= "releasable",
5360 .read_u64
= releasable_read
,
5366 struct cgroup_subsys debug_subsys
= {
5368 .css_alloc
= debug_css_alloc
,
5369 .css_free
= debug_css_free
,
5370 .subsys_id
= debug_subsys_id
,
5371 .base_cftypes
= debug_files
,
5373 #endif /* CONFIG_CGROUP_DEBUG */