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/slab.h>
44 #include <linux/spinlock.h>
45 #include <linux/rwsem.h>
46 #include <linux/string.h>
47 #include <linux/sort.h>
48 #include <linux/kmod.h>
49 #include <linux/delayacct.h>
50 #include <linux/cgroupstats.h>
51 #include <linux/hashtable.h>
52 #include <linux/pid_namespace.h>
53 #include <linux/idr.h>
54 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
55 #include <linux/kthread.h>
56 #include <linux/delay.h>
58 #include <linux/atomic.h>
61 * pidlists linger the following amount before being destroyed. The goal
62 * is avoiding frequent destruction in the middle of consecutive read calls
63 * Expiring in the middle is a performance problem not a correctness one.
64 * 1 sec should be enough.
66 #define CGROUP_PIDLIST_DESTROY_DELAY HZ
68 #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
72 * cgroup_tree_mutex nests above cgroup_mutex and protects cftypes, file
73 * creation/removal and hierarchy changing operations including cgroup
74 * creation, removal, css association and controller rebinding. This outer
75 * lock is needed mainly to resolve the circular dependency between kernfs
76 * active ref and cgroup_mutex. cgroup_tree_mutex nests above both.
78 static DEFINE_MUTEX(cgroup_tree_mutex
);
81 * cgroup_mutex is the master lock. Any modification to cgroup or its
82 * hierarchy must be performed while holding it.
84 * css_set_rwsem protects task->cgroups pointer, the list of css_set
85 * objects, and the chain of tasks off each css_set.
87 * These locks are exported if CONFIG_PROVE_RCU so that accessors in
88 * cgroup.h can use them for lockdep annotations.
90 #ifdef CONFIG_PROVE_RCU
91 DEFINE_MUTEX(cgroup_mutex
);
92 DECLARE_RWSEM(css_set_rwsem
);
93 EXPORT_SYMBOL_GPL(cgroup_mutex
);
94 EXPORT_SYMBOL_GPL(css_set_rwsem
);
96 static DEFINE_MUTEX(cgroup_mutex
);
97 static DECLARE_RWSEM(css_set_rwsem
);
101 * Protects cgroup_subsys->release_agent_path. Modifying it also requires
102 * cgroup_mutex. Reading requires either cgroup_mutex or this spinlock.
104 static DEFINE_SPINLOCK(release_agent_path_lock
);
106 #define cgroup_assert_mutexes_or_rcu_locked() \
107 rcu_lockdep_assert(rcu_read_lock_held() || \
108 lockdep_is_held(&cgroup_tree_mutex) || \
109 lockdep_is_held(&cgroup_mutex), \
110 "cgroup_[tree_]mutex or RCU read lock required");
113 * cgroup destruction makes heavy use of work items and there can be a lot
114 * of concurrent destructions. Use a separate workqueue so that cgroup
115 * destruction work items don't end up filling up max_active of system_wq
116 * which may lead to deadlock.
118 static struct workqueue_struct
*cgroup_destroy_wq
;
121 * pidlist destructions need to be flushed on cgroup destruction. Use a
122 * separate workqueue as flush domain.
124 static struct workqueue_struct
*cgroup_pidlist_destroy_wq
;
126 /* generate an array of cgroup subsystem pointers */
127 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
128 static struct cgroup_subsys
*cgroup_subsys
[] = {
129 #include <linux/cgroup_subsys.h>
133 /* array of cgroup subsystem names */
134 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
135 static const char *cgroup_subsys_name
[] = {
136 #include <linux/cgroup_subsys.h>
141 * The default hierarchy, reserved for the subsystems that are otherwise
142 * unattached - it never has more than a single cgroup, and all tasks are
143 * part of that cgroup.
145 struct cgroup_root cgrp_dfl_root
;
148 * The default hierarchy always exists but is hidden until mounted for the
149 * first time. This is for backward compatibility.
151 static bool cgrp_dfl_root_visible
;
153 /* The list of hierarchy roots */
155 static LIST_HEAD(cgroup_roots
);
156 static int cgroup_root_count
;
158 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
159 static DEFINE_IDR(cgroup_hierarchy_idr
);
162 * Assign a monotonically increasing serial number to cgroups. It
163 * guarantees cgroups with bigger numbers are newer than those with smaller
164 * numbers. Also, as cgroups are always appended to the parent's
165 * ->children list, it guarantees that sibling cgroups are always sorted in
166 * the ascending serial number order on the list. Protected by
169 static u64 cgroup_serial_nr_next
= 1;
171 /* This flag indicates whether tasks in the fork and exit paths should
172 * check for fork/exit handlers to call. This avoids us having to do
173 * extra work in the fork/exit path if none of the subsystems need to
176 static int need_forkexit_callback __read_mostly
;
178 static struct cftype cgroup_base_files
[];
180 static void cgroup_put(struct cgroup
*cgrp
);
181 static int rebind_subsystems(struct cgroup_root
*dst_root
,
182 unsigned long ss_mask
);
183 static void cgroup_destroy_css_killed(struct cgroup
*cgrp
);
184 static int cgroup_destroy_locked(struct cgroup
*cgrp
);
185 static int create_css(struct cgroup
*cgrp
, struct cgroup_subsys
*ss
);
186 static void kill_css(struct cgroup_subsys_state
*css
);
187 static int cgroup_addrm_files(struct cgroup
*cgrp
, struct cftype cfts
[],
189 static void cgroup_pidlist_destroy_all(struct cgroup
*cgrp
);
192 * cgroup_css - obtain a cgroup's css for the specified subsystem
193 * @cgrp: the cgroup of interest
194 * @ss: the subsystem of interest (%NULL returns the dummy_css)
196 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
197 * function must be called either under cgroup_mutex or rcu_read_lock() and
198 * the caller is responsible for pinning the returned css if it wants to
199 * keep accessing it outside the said locks. This function may return
200 * %NULL if @cgrp doesn't have @subsys_id enabled.
202 static struct cgroup_subsys_state
*cgroup_css(struct cgroup
*cgrp
,
203 struct cgroup_subsys
*ss
)
206 return rcu_dereference_check(cgrp
->subsys
[ss
->id
],
207 lockdep_is_held(&cgroup_tree_mutex
) ||
208 lockdep_is_held(&cgroup_mutex
));
210 return &cgrp
->dummy_css
;
214 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
215 * @cgrp: the cgroup of interest
216 * @ss: the subsystem of interest (%NULL returns the dummy_css)
218 * Similar to cgroup_css() but returns the effctive css, which is defined
219 * as the matching css of the nearest ancestor including self which has @ss
220 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
221 * function is guaranteed to return non-NULL css.
223 static struct cgroup_subsys_state
*cgroup_e_css(struct cgroup
*cgrp
,
224 struct cgroup_subsys
*ss
)
226 lockdep_assert_held(&cgroup_mutex
);
229 return &cgrp
->dummy_css
;
231 if (!(cgrp
->root
->subsys_mask
& (1 << ss
->id
)))
234 while (cgrp
->parent
&&
235 !(cgrp
->parent
->child_subsys_mask
& (1 << ss
->id
)))
238 return cgroup_css(cgrp
, ss
);
241 /* convenient tests for these bits */
242 static inline bool cgroup_is_dead(const struct cgroup
*cgrp
)
244 return test_bit(CGRP_DEAD
, &cgrp
->flags
);
247 struct cgroup_subsys_state
*seq_css(struct seq_file
*seq
)
249 struct kernfs_open_file
*of
= seq
->private;
250 struct cgroup
*cgrp
= of
->kn
->parent
->priv
;
251 struct cftype
*cft
= seq_cft(seq
);
254 * This is open and unprotected implementation of cgroup_css().
255 * seq_css() is only called from a kernfs file operation which has
256 * an active reference on the file. Because all the subsystem
257 * files are drained before a css is disassociated with a cgroup,
258 * the matching css from the cgroup's subsys table is guaranteed to
259 * be and stay valid until the enclosing operation is complete.
262 return rcu_dereference_raw(cgrp
->subsys
[cft
->ss
->id
]);
264 return &cgrp
->dummy_css
;
266 EXPORT_SYMBOL_GPL(seq_css
);
269 * cgroup_is_descendant - test ancestry
270 * @cgrp: the cgroup to be tested
271 * @ancestor: possible ancestor of @cgrp
273 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
274 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
275 * and @ancestor are accessible.
277 bool cgroup_is_descendant(struct cgroup
*cgrp
, struct cgroup
*ancestor
)
280 if (cgrp
== ancestor
)
287 static int cgroup_is_releasable(const struct cgroup
*cgrp
)
290 (1 << CGRP_RELEASABLE
) |
291 (1 << CGRP_NOTIFY_ON_RELEASE
);
292 return (cgrp
->flags
& bits
) == bits
;
295 static int notify_on_release(const struct cgroup
*cgrp
)
297 return test_bit(CGRP_NOTIFY_ON_RELEASE
, &cgrp
->flags
);
301 * for_each_css - iterate all css's of a cgroup
302 * @css: the iteration cursor
303 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
304 * @cgrp: the target cgroup to iterate css's of
306 * Should be called under cgroup_[tree_]mutex.
308 #define for_each_css(css, ssid, cgrp) \
309 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
310 if (!((css) = rcu_dereference_check( \
311 (cgrp)->subsys[(ssid)], \
312 lockdep_is_held(&cgroup_tree_mutex) || \
313 lockdep_is_held(&cgroup_mutex)))) { } \
317 * for_each_e_css - iterate all effective css's of a cgroup
318 * @css: the iteration cursor
319 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
320 * @cgrp: the target cgroup to iterate css's of
322 * Should be called under cgroup_[tree_]mutex.
324 #define for_each_e_css(css, ssid, cgrp) \
325 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
326 if (!((css) = cgroup_e_css(cgrp, cgroup_subsys[(ssid)]))) \
331 * for_each_subsys - iterate all enabled cgroup subsystems
332 * @ss: the iteration cursor
333 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
335 #define for_each_subsys(ss, ssid) \
336 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT && \
337 (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
339 /* iterate across the hierarchies */
340 #define for_each_root(root) \
341 list_for_each_entry((root), &cgroup_roots, root_list)
343 /* iterate over child cgrps, lock should be held throughout iteration */
344 #define cgroup_for_each_live_child(child, cgrp) \
345 list_for_each_entry((child), &(cgrp)->children, sibling) \
346 if (({ lockdep_assert_held(&cgroup_tree_mutex); \
347 cgroup_is_dead(child); })) \
352 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
353 * @cgrp: the cgroup to be checked for liveness
355 * On success, returns true; the mutex should be later unlocked. On
356 * failure returns false with no lock held.
358 static bool cgroup_lock_live_group(struct cgroup
*cgrp
)
360 mutex_lock(&cgroup_mutex
);
361 if (cgroup_is_dead(cgrp
)) {
362 mutex_unlock(&cgroup_mutex
);
368 /* the list of cgroups eligible for automatic release. Protected by
369 * release_list_lock */
370 static LIST_HEAD(release_list
);
371 static DEFINE_RAW_SPINLOCK(release_list_lock
);
372 static void cgroup_release_agent(struct work_struct
*work
);
373 static DECLARE_WORK(release_agent_work
, cgroup_release_agent
);
374 static void check_for_release(struct cgroup
*cgrp
);
377 * A cgroup can be associated with multiple css_sets as different tasks may
378 * belong to different cgroups on different hierarchies. In the other
379 * direction, a css_set is naturally associated with multiple cgroups.
380 * This M:N relationship is represented by the following link structure
381 * which exists for each association and allows traversing the associations
384 struct cgrp_cset_link
{
385 /* the cgroup and css_set this link associates */
387 struct css_set
*cset
;
389 /* list of cgrp_cset_links anchored at cgrp->cset_links */
390 struct list_head cset_link
;
392 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
393 struct list_head cgrp_link
;
397 * The default css_set - used by init and its children prior to any
398 * hierarchies being mounted. It contains a pointer to the root state
399 * for each subsystem. Also used to anchor the list of css_sets. Not
400 * reference-counted, to improve performance when child cgroups
401 * haven't been created.
403 static struct css_set init_css_set
= {
404 .refcount
= ATOMIC_INIT(1),
405 .cgrp_links
= LIST_HEAD_INIT(init_css_set
.cgrp_links
),
406 .tasks
= LIST_HEAD_INIT(init_css_set
.tasks
),
407 .mg_tasks
= LIST_HEAD_INIT(init_css_set
.mg_tasks
),
408 .mg_preload_node
= LIST_HEAD_INIT(init_css_set
.mg_preload_node
),
409 .mg_node
= LIST_HEAD_INIT(init_css_set
.mg_node
),
412 static int css_set_count
= 1; /* 1 for init_css_set */
415 * hash table for cgroup groups. This improves the performance to find
416 * an existing css_set. This hash doesn't (currently) take into
417 * account cgroups in empty hierarchies.
419 #define CSS_SET_HASH_BITS 7
420 static DEFINE_HASHTABLE(css_set_table
, CSS_SET_HASH_BITS
);
422 static unsigned long css_set_hash(struct cgroup_subsys_state
*css
[])
424 unsigned long key
= 0UL;
425 struct cgroup_subsys
*ss
;
428 for_each_subsys(ss
, i
)
429 key
+= (unsigned long)css
[i
];
430 key
= (key
>> 16) ^ key
;
435 static void put_css_set_locked(struct css_set
*cset
, bool taskexit
)
437 struct cgrp_cset_link
*link
, *tmp_link
;
438 struct cgroup_subsys
*ss
;
441 lockdep_assert_held(&css_set_rwsem
);
443 if (!atomic_dec_and_test(&cset
->refcount
))
446 /* This css_set is dead. unlink it and release cgroup refcounts */
447 for_each_subsys(ss
, ssid
)
448 list_del(&cset
->e_cset_node
[ssid
]);
449 hash_del(&cset
->hlist
);
452 list_for_each_entry_safe(link
, tmp_link
, &cset
->cgrp_links
, cgrp_link
) {
453 struct cgroup
*cgrp
= link
->cgrp
;
455 list_del(&link
->cset_link
);
456 list_del(&link
->cgrp_link
);
458 /* @cgrp can't go away while we're holding css_set_rwsem */
459 if (list_empty(&cgrp
->cset_links
) && notify_on_release(cgrp
)) {
461 set_bit(CGRP_RELEASABLE
, &cgrp
->flags
);
462 check_for_release(cgrp
);
468 kfree_rcu(cset
, rcu_head
);
471 static void put_css_set(struct css_set
*cset
, bool taskexit
)
474 * Ensure that the refcount doesn't hit zero while any readers
475 * can see it. Similar to atomic_dec_and_lock(), but for an
478 if (atomic_add_unless(&cset
->refcount
, -1, 1))
481 down_write(&css_set_rwsem
);
482 put_css_set_locked(cset
, taskexit
);
483 up_write(&css_set_rwsem
);
487 * refcounted get/put for css_set objects
489 static inline void get_css_set(struct css_set
*cset
)
491 atomic_inc(&cset
->refcount
);
495 * compare_css_sets - helper function for find_existing_css_set().
496 * @cset: candidate css_set being tested
497 * @old_cset: existing css_set for a task
498 * @new_cgrp: cgroup that's being entered by the task
499 * @template: desired set of css pointers in css_set (pre-calculated)
501 * Returns true if "cset" matches "old_cset" except for the hierarchy
502 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
504 static bool compare_css_sets(struct css_set
*cset
,
505 struct css_set
*old_cset
,
506 struct cgroup
*new_cgrp
,
507 struct cgroup_subsys_state
*template[])
509 struct list_head
*l1
, *l2
;
512 * On the default hierarchy, there can be csets which are
513 * associated with the same set of cgroups but different csses.
514 * Let's first ensure that csses match.
516 if (memcmp(template, cset
->subsys
, sizeof(cset
->subsys
)))
520 * Compare cgroup pointers in order to distinguish between
521 * different cgroups in hierarchies. As different cgroups may
522 * share the same effective css, this comparison is always
525 l1
= &cset
->cgrp_links
;
526 l2
= &old_cset
->cgrp_links
;
528 struct cgrp_cset_link
*link1
, *link2
;
529 struct cgroup
*cgrp1
, *cgrp2
;
533 /* See if we reached the end - both lists are equal length. */
534 if (l1
== &cset
->cgrp_links
) {
535 BUG_ON(l2
!= &old_cset
->cgrp_links
);
538 BUG_ON(l2
== &old_cset
->cgrp_links
);
540 /* Locate the cgroups associated with these links. */
541 link1
= list_entry(l1
, struct cgrp_cset_link
, cgrp_link
);
542 link2
= list_entry(l2
, struct cgrp_cset_link
, cgrp_link
);
545 /* Hierarchies should be linked in the same order. */
546 BUG_ON(cgrp1
->root
!= cgrp2
->root
);
549 * If this hierarchy is the hierarchy of the cgroup
550 * that's changing, then we need to check that this
551 * css_set points to the new cgroup; if it's any other
552 * hierarchy, then this css_set should point to the
553 * same cgroup as the old css_set.
555 if (cgrp1
->root
== new_cgrp
->root
) {
556 if (cgrp1
!= new_cgrp
)
567 * find_existing_css_set - init css array and find the matching css_set
568 * @old_cset: the css_set that we're using before the cgroup transition
569 * @cgrp: the cgroup that we're moving into
570 * @template: out param for the new set of csses, should be clear on entry
572 static struct css_set
*find_existing_css_set(struct css_set
*old_cset
,
574 struct cgroup_subsys_state
*template[])
576 struct cgroup_root
*root
= cgrp
->root
;
577 struct cgroup_subsys
*ss
;
578 struct css_set
*cset
;
583 * Build the set of subsystem state objects that we want to see in the
584 * new css_set. while subsystems can change globally, the entries here
585 * won't change, so no need for locking.
587 for_each_subsys(ss
, i
) {
588 if (root
->subsys_mask
& (1UL << i
)) {
590 * @ss is in this hierarchy, so we want the
591 * effective css from @cgrp.
593 template[i
] = cgroup_e_css(cgrp
, ss
);
596 * @ss is not in this hierarchy, so we don't want
599 template[i
] = old_cset
->subsys
[i
];
603 key
= css_set_hash(template);
604 hash_for_each_possible(css_set_table
, cset
, hlist
, key
) {
605 if (!compare_css_sets(cset
, old_cset
, cgrp
, template))
608 /* This css_set matches what we need */
612 /* No existing cgroup group matched */
616 static void free_cgrp_cset_links(struct list_head
*links_to_free
)
618 struct cgrp_cset_link
*link
, *tmp_link
;
620 list_for_each_entry_safe(link
, tmp_link
, links_to_free
, cset_link
) {
621 list_del(&link
->cset_link
);
627 * allocate_cgrp_cset_links - allocate cgrp_cset_links
628 * @count: the number of links to allocate
629 * @tmp_links: list_head the allocated links are put on
631 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
632 * through ->cset_link. Returns 0 on success or -errno.
634 static int allocate_cgrp_cset_links(int count
, struct list_head
*tmp_links
)
636 struct cgrp_cset_link
*link
;
639 INIT_LIST_HEAD(tmp_links
);
641 for (i
= 0; i
< count
; i
++) {
642 link
= kzalloc(sizeof(*link
), GFP_KERNEL
);
644 free_cgrp_cset_links(tmp_links
);
647 list_add(&link
->cset_link
, tmp_links
);
653 * link_css_set - a helper function to link a css_set to a cgroup
654 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
655 * @cset: the css_set to be linked
656 * @cgrp: the destination cgroup
658 static void link_css_set(struct list_head
*tmp_links
, struct css_set
*cset
,
661 struct cgrp_cset_link
*link
;
663 BUG_ON(list_empty(tmp_links
));
665 if (cgroup_on_dfl(cgrp
))
666 cset
->dfl_cgrp
= cgrp
;
668 link
= list_first_entry(tmp_links
, struct cgrp_cset_link
, cset_link
);
671 list_move(&link
->cset_link
, &cgrp
->cset_links
);
673 * Always add links to the tail of the list so that the list
674 * is sorted by order of hierarchy creation
676 list_add_tail(&link
->cgrp_link
, &cset
->cgrp_links
);
680 * find_css_set - return a new css_set with one cgroup updated
681 * @old_cset: the baseline css_set
682 * @cgrp: the cgroup to be updated
684 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
685 * substituted into the appropriate hierarchy.
687 static struct css_set
*find_css_set(struct css_set
*old_cset
,
690 struct cgroup_subsys_state
*template[CGROUP_SUBSYS_COUNT
] = { };
691 struct css_set
*cset
;
692 struct list_head tmp_links
;
693 struct cgrp_cset_link
*link
;
694 struct cgroup_subsys
*ss
;
698 lockdep_assert_held(&cgroup_mutex
);
700 /* First see if we already have a cgroup group that matches
702 down_read(&css_set_rwsem
);
703 cset
= find_existing_css_set(old_cset
, cgrp
, template);
706 up_read(&css_set_rwsem
);
711 cset
= kzalloc(sizeof(*cset
), GFP_KERNEL
);
715 /* Allocate all the cgrp_cset_link objects that we'll need */
716 if (allocate_cgrp_cset_links(cgroup_root_count
, &tmp_links
) < 0) {
721 atomic_set(&cset
->refcount
, 1);
722 INIT_LIST_HEAD(&cset
->cgrp_links
);
723 INIT_LIST_HEAD(&cset
->tasks
);
724 INIT_LIST_HEAD(&cset
->mg_tasks
);
725 INIT_LIST_HEAD(&cset
->mg_preload_node
);
726 INIT_LIST_HEAD(&cset
->mg_node
);
727 INIT_HLIST_NODE(&cset
->hlist
);
729 /* Copy the set of subsystem state objects generated in
730 * find_existing_css_set() */
731 memcpy(cset
->subsys
, template, sizeof(cset
->subsys
));
733 down_write(&css_set_rwsem
);
734 /* Add reference counts and links from the new css_set. */
735 list_for_each_entry(link
, &old_cset
->cgrp_links
, cgrp_link
) {
736 struct cgroup
*c
= link
->cgrp
;
738 if (c
->root
== cgrp
->root
)
740 link_css_set(&tmp_links
, cset
, c
);
743 BUG_ON(!list_empty(&tmp_links
));
747 /* Add @cset to the hash table */
748 key
= css_set_hash(cset
->subsys
);
749 hash_add(css_set_table
, &cset
->hlist
, key
);
751 for_each_subsys(ss
, ssid
)
752 list_add_tail(&cset
->e_cset_node
[ssid
],
753 &cset
->subsys
[ssid
]->cgroup
->e_csets
[ssid
]);
755 up_write(&css_set_rwsem
);
760 static struct cgroup_root
*cgroup_root_from_kf(struct kernfs_root
*kf_root
)
762 struct cgroup
*root_cgrp
= kf_root
->kn
->priv
;
764 return root_cgrp
->root
;
767 static int cgroup_init_root_id(struct cgroup_root
*root
)
771 lockdep_assert_held(&cgroup_mutex
);
773 id
= idr_alloc_cyclic(&cgroup_hierarchy_idr
, root
, 0, 0, GFP_KERNEL
);
777 root
->hierarchy_id
= id
;
781 static void cgroup_exit_root_id(struct cgroup_root
*root
)
783 lockdep_assert_held(&cgroup_mutex
);
785 if (root
->hierarchy_id
) {
786 idr_remove(&cgroup_hierarchy_idr
, root
->hierarchy_id
);
787 root
->hierarchy_id
= 0;
791 static void cgroup_free_root(struct cgroup_root
*root
)
794 /* hierarhcy ID shoulid already have been released */
795 WARN_ON_ONCE(root
->hierarchy_id
);
797 idr_destroy(&root
->cgroup_idr
);
802 static void cgroup_destroy_root(struct cgroup_root
*root
)
804 struct cgroup
*cgrp
= &root
->cgrp
;
805 struct cgrp_cset_link
*link
, *tmp_link
;
807 mutex_lock(&cgroup_tree_mutex
);
808 mutex_lock(&cgroup_mutex
);
810 BUG_ON(atomic_read(&root
->nr_cgrps
));
811 BUG_ON(!list_empty(&cgrp
->children
));
813 /* Rebind all subsystems back to the default hierarchy */
814 rebind_subsystems(&cgrp_dfl_root
, root
->subsys_mask
);
817 * Release all the links from cset_links to this hierarchy's
820 down_write(&css_set_rwsem
);
822 list_for_each_entry_safe(link
, tmp_link
, &cgrp
->cset_links
, cset_link
) {
823 list_del(&link
->cset_link
);
824 list_del(&link
->cgrp_link
);
827 up_write(&css_set_rwsem
);
829 if (!list_empty(&root
->root_list
)) {
830 list_del(&root
->root_list
);
834 cgroup_exit_root_id(root
);
836 mutex_unlock(&cgroup_mutex
);
837 mutex_unlock(&cgroup_tree_mutex
);
839 kernfs_destroy_root(root
->kf_root
);
840 cgroup_free_root(root
);
843 /* look up cgroup associated with given css_set on the specified hierarchy */
844 static struct cgroup
*cset_cgroup_from_root(struct css_set
*cset
,
845 struct cgroup_root
*root
)
847 struct cgroup
*res
= NULL
;
849 lockdep_assert_held(&cgroup_mutex
);
850 lockdep_assert_held(&css_set_rwsem
);
852 if (cset
== &init_css_set
) {
855 struct cgrp_cset_link
*link
;
857 list_for_each_entry(link
, &cset
->cgrp_links
, cgrp_link
) {
858 struct cgroup
*c
= link
->cgrp
;
860 if (c
->root
== root
) {
872 * Return the cgroup for "task" from the given hierarchy. Must be
873 * called with cgroup_mutex and css_set_rwsem held.
875 static struct cgroup
*task_cgroup_from_root(struct task_struct
*task
,
876 struct cgroup_root
*root
)
879 * No need to lock the task - since we hold cgroup_mutex the
880 * task can't change groups, so the only thing that can happen
881 * is that it exits and its css is set back to init_css_set.
883 return cset_cgroup_from_root(task_css_set(task
), root
);
887 * A task must hold cgroup_mutex to modify cgroups.
889 * Any task can increment and decrement the count field without lock.
890 * So in general, code holding cgroup_mutex can't rely on the count
891 * field not changing. However, if the count goes to zero, then only
892 * cgroup_attach_task() can increment it again. Because a count of zero
893 * means that no tasks are currently attached, therefore there is no
894 * way a task attached to that cgroup can fork (the other way to
895 * increment the count). So code holding cgroup_mutex can safely
896 * assume that if the count is zero, it will stay zero. Similarly, if
897 * a task holds cgroup_mutex on a cgroup with zero count, it
898 * knows that the cgroup won't be removed, as cgroup_rmdir()
901 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
902 * (usually) take cgroup_mutex. These are the two most performance
903 * critical pieces of code here. The exception occurs on cgroup_exit(),
904 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
905 * is taken, and if the cgroup count is zero, a usermode call made
906 * to the release agent with the name of the cgroup (path relative to
907 * the root of cgroup file system) as the argument.
909 * A cgroup can only be deleted if both its 'count' of using tasks
910 * is zero, and its list of 'children' cgroups is empty. Since all
911 * tasks in the system use _some_ cgroup, and since there is always at
912 * least one task in the system (init, pid == 1), therefore, root cgroup
913 * always has either children cgroups and/or using tasks. So we don't
914 * need a special hack to ensure that root cgroup cannot be deleted.
916 * P.S. One more locking exception. RCU is used to guard the
917 * update of a tasks cgroup pointer by cgroup_attach_task()
920 static int cgroup_populate_dir(struct cgroup
*cgrp
, unsigned long subsys_mask
);
921 static struct kernfs_syscall_ops cgroup_kf_syscall_ops
;
922 static const struct file_operations proc_cgroupstats_operations
;
924 static char *cgroup_file_name(struct cgroup
*cgrp
, const struct cftype
*cft
,
927 if (cft
->ss
&& !(cft
->flags
& CFTYPE_NO_PREFIX
) &&
928 !(cgrp
->root
->flags
& CGRP_ROOT_NOPREFIX
))
929 snprintf(buf
, CGROUP_FILE_NAME_MAX
, "%s.%s",
930 cft
->ss
->name
, cft
->name
);
932 strncpy(buf
, cft
->name
, CGROUP_FILE_NAME_MAX
);
937 * cgroup_file_mode - deduce file mode of a control file
938 * @cft: the control file in question
940 * returns cft->mode if ->mode is not 0
941 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
942 * returns S_IRUGO if it has only a read handler
943 * returns S_IWUSR if it has only a write hander
945 static umode_t
cgroup_file_mode(const struct cftype
*cft
)
952 if (cft
->read_u64
|| cft
->read_s64
|| cft
->seq_show
)
955 if (cft
->write_u64
|| cft
->write_s64
|| cft
->write_string
||
962 static void cgroup_free_fn(struct work_struct
*work
)
964 struct cgroup
*cgrp
= container_of(work
, struct cgroup
, destroy_work
);
966 atomic_dec(&cgrp
->root
->nr_cgrps
);
967 cgroup_pidlist_destroy_all(cgrp
);
971 * We get a ref to the parent, and put the ref when this
972 * cgroup is being freed, so it's guaranteed that the
973 * parent won't be destroyed before its children.
975 cgroup_put(cgrp
->parent
);
976 kernfs_put(cgrp
->kn
);
980 * This is root cgroup's refcnt reaching zero, which
981 * indicates that the root should be released.
983 cgroup_destroy_root(cgrp
->root
);
987 static void cgroup_free_rcu(struct rcu_head
*head
)
989 struct cgroup
*cgrp
= container_of(head
, struct cgroup
, rcu_head
);
991 INIT_WORK(&cgrp
->destroy_work
, cgroup_free_fn
);
992 queue_work(cgroup_destroy_wq
, &cgrp
->destroy_work
);
995 static void cgroup_get(struct cgroup
*cgrp
)
997 WARN_ON_ONCE(cgroup_is_dead(cgrp
));
998 WARN_ON_ONCE(atomic_read(&cgrp
->refcnt
) <= 0);
999 atomic_inc(&cgrp
->refcnt
);
1002 static void cgroup_put(struct cgroup
*cgrp
)
1004 if (!atomic_dec_and_test(&cgrp
->refcnt
))
1006 if (WARN_ON_ONCE(cgrp
->parent
&& !cgroup_is_dead(cgrp
)))
1010 * XXX: cgrp->id is only used to look up css's. As cgroup and
1011 * css's lifetimes will be decoupled, it should be made
1012 * per-subsystem and moved to css->id so that lookups are
1013 * successful until the target css is released.
1015 mutex_lock(&cgroup_mutex
);
1016 idr_remove(&cgrp
->root
->cgroup_idr
, cgrp
->id
);
1017 mutex_unlock(&cgroup_mutex
);
1020 call_rcu(&cgrp
->rcu_head
, cgroup_free_rcu
);
1023 static void cgroup_rm_file(struct cgroup
*cgrp
, const struct cftype
*cft
)
1025 char name
[CGROUP_FILE_NAME_MAX
];
1027 lockdep_assert_held(&cgroup_tree_mutex
);
1028 kernfs_remove_by_name(cgrp
->kn
, cgroup_file_name(cgrp
, cft
, name
));
1032 * cgroup_clear_dir - remove subsys files in a cgroup directory
1033 * @cgrp: target cgroup
1034 * @subsys_mask: mask of the subsystem ids whose files should be removed
1036 static void cgroup_clear_dir(struct cgroup
*cgrp
, unsigned long subsys_mask
)
1038 struct cgroup_subsys
*ss
;
1041 for_each_subsys(ss
, i
) {
1042 struct cftype
*cfts
;
1044 if (!test_bit(i
, &subsys_mask
))
1046 list_for_each_entry(cfts
, &ss
->cfts
, node
)
1047 cgroup_addrm_files(cgrp
, cfts
, false);
1051 static int rebind_subsystems(struct cgroup_root
*dst_root
,
1052 unsigned long ss_mask
)
1054 struct cgroup_subsys
*ss
;
1057 lockdep_assert_held(&cgroup_tree_mutex
);
1058 lockdep_assert_held(&cgroup_mutex
);
1060 for_each_subsys(ss
, ssid
) {
1061 if (!(ss_mask
& (1 << ssid
)))
1064 /* if @ss has non-root csses attached to it, can't move */
1065 if (css_next_child(NULL
, cgroup_css(&ss
->root
->cgrp
, ss
)))
1068 /* can't move between two non-dummy roots either */
1069 if (ss
->root
!= &cgrp_dfl_root
&& dst_root
!= &cgrp_dfl_root
)
1073 ret
= cgroup_populate_dir(&dst_root
->cgrp
, ss_mask
);
1075 if (dst_root
!= &cgrp_dfl_root
)
1079 * Rebinding back to the default root is not allowed to
1080 * fail. Using both default and non-default roots should
1081 * be rare. Moving subsystems back and forth even more so.
1082 * Just warn about it and continue.
1084 if (cgrp_dfl_root_visible
) {
1085 pr_warning("cgroup: failed to create files (%d) while rebinding 0x%lx to default root\n",
1087 pr_warning("cgroup: you may retry by moving them to a different hierarchy and unbinding\n");
1092 * Nothing can fail from this point on. Remove files for the
1093 * removed subsystems and rebind each subsystem.
1095 mutex_unlock(&cgroup_mutex
);
1096 for_each_subsys(ss
, ssid
)
1097 if (ss_mask
& (1 << ssid
))
1098 cgroup_clear_dir(&ss
->root
->cgrp
, 1 << ssid
);
1099 mutex_lock(&cgroup_mutex
);
1101 for_each_subsys(ss
, ssid
) {
1102 struct cgroup_root
*src_root
;
1103 struct cgroup_subsys_state
*css
;
1104 struct css_set
*cset
;
1106 if (!(ss_mask
& (1 << ssid
)))
1109 src_root
= ss
->root
;
1110 css
= cgroup_css(&src_root
->cgrp
, ss
);
1112 WARN_ON(!css
|| cgroup_css(&dst_root
->cgrp
, ss
));
1114 RCU_INIT_POINTER(src_root
->cgrp
.subsys
[ssid
], NULL
);
1115 rcu_assign_pointer(dst_root
->cgrp
.subsys
[ssid
], css
);
1116 ss
->root
= dst_root
;
1117 css
->cgroup
= &dst_root
->cgrp
;
1119 down_write(&css_set_rwsem
);
1120 hash_for_each(css_set_table
, i
, cset
, hlist
)
1121 list_move_tail(&cset
->e_cset_node
[ss
->id
],
1122 &dst_root
->cgrp
.e_csets
[ss
->id
]);
1123 up_write(&css_set_rwsem
);
1125 src_root
->subsys_mask
&= ~(1 << ssid
);
1126 src_root
->cgrp
.child_subsys_mask
&= ~(1 << ssid
);
1128 /* default hierarchy doesn't enable controllers by default */
1129 dst_root
->subsys_mask
|= 1 << ssid
;
1130 if (dst_root
!= &cgrp_dfl_root
)
1131 dst_root
->cgrp
.child_subsys_mask
|= 1 << ssid
;
1137 kernfs_activate(dst_root
->cgrp
.kn
);
1141 static int cgroup_show_options(struct seq_file
*seq
,
1142 struct kernfs_root
*kf_root
)
1144 struct cgroup_root
*root
= cgroup_root_from_kf(kf_root
);
1145 struct cgroup_subsys
*ss
;
1148 for_each_subsys(ss
, ssid
)
1149 if (root
->subsys_mask
& (1 << ssid
))
1150 seq_printf(seq
, ",%s", ss
->name
);
1151 if (root
->flags
& CGRP_ROOT_SANE_BEHAVIOR
)
1152 seq_puts(seq
, ",sane_behavior");
1153 if (root
->flags
& CGRP_ROOT_NOPREFIX
)
1154 seq_puts(seq
, ",noprefix");
1155 if (root
->flags
& CGRP_ROOT_XATTR
)
1156 seq_puts(seq
, ",xattr");
1158 spin_lock(&release_agent_path_lock
);
1159 if (strlen(root
->release_agent_path
))
1160 seq_printf(seq
, ",release_agent=%s", root
->release_agent_path
);
1161 spin_unlock(&release_agent_path_lock
);
1163 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN
, &root
->cgrp
.flags
))
1164 seq_puts(seq
, ",clone_children");
1165 if (strlen(root
->name
))
1166 seq_printf(seq
, ",name=%s", root
->name
);
1170 struct cgroup_sb_opts
{
1171 unsigned long subsys_mask
;
1172 unsigned long flags
;
1173 char *release_agent
;
1174 bool cpuset_clone_children
;
1176 /* User explicitly requested empty subsystem */
1181 * Convert a hierarchy specifier into a bitmask of subsystems and
1182 * flags. Call with cgroup_mutex held to protect the cgroup_subsys[]
1183 * array. This function takes refcounts on subsystems to be used, unless it
1184 * returns error, in which case no refcounts are taken.
1186 static int parse_cgroupfs_options(char *data
, struct cgroup_sb_opts
*opts
)
1188 char *token
, *o
= data
;
1189 bool all_ss
= false, one_ss
= false;
1190 unsigned long mask
= (unsigned long)-1;
1191 struct cgroup_subsys
*ss
;
1194 BUG_ON(!mutex_is_locked(&cgroup_mutex
));
1196 #ifdef CONFIG_CPUSETS
1197 mask
= ~(1UL << cpuset_cgrp_id
);
1200 memset(opts
, 0, sizeof(*opts
));
1202 while ((token
= strsep(&o
, ",")) != NULL
) {
1205 if (!strcmp(token
, "none")) {
1206 /* Explicitly have no subsystems */
1210 if (!strcmp(token
, "all")) {
1211 /* Mutually exclusive option 'all' + subsystem name */
1217 if (!strcmp(token
, "__DEVEL__sane_behavior")) {
1218 opts
->flags
|= CGRP_ROOT_SANE_BEHAVIOR
;
1221 if (!strcmp(token
, "noprefix")) {
1222 opts
->flags
|= CGRP_ROOT_NOPREFIX
;
1225 if (!strcmp(token
, "clone_children")) {
1226 opts
->cpuset_clone_children
= true;
1229 if (!strcmp(token
, "xattr")) {
1230 opts
->flags
|= CGRP_ROOT_XATTR
;
1233 if (!strncmp(token
, "release_agent=", 14)) {
1234 /* Specifying two release agents is forbidden */
1235 if (opts
->release_agent
)
1237 opts
->release_agent
=
1238 kstrndup(token
+ 14, PATH_MAX
- 1, GFP_KERNEL
);
1239 if (!opts
->release_agent
)
1243 if (!strncmp(token
, "name=", 5)) {
1244 const char *name
= token
+ 5;
1245 /* Can't specify an empty name */
1248 /* Must match [\w.-]+ */
1249 for (i
= 0; i
< strlen(name
); i
++) {
1253 if ((c
== '.') || (c
== '-') || (c
== '_'))
1257 /* Specifying two names is forbidden */
1260 opts
->name
= kstrndup(name
,
1261 MAX_CGROUP_ROOT_NAMELEN
- 1,
1269 for_each_subsys(ss
, i
) {
1270 if (strcmp(token
, ss
->name
))
1275 /* Mutually exclusive option 'all' + subsystem name */
1278 set_bit(i
, &opts
->subsys_mask
);
1283 if (i
== CGROUP_SUBSYS_COUNT
)
1287 /* Consistency checks */
1289 if (opts
->flags
& CGRP_ROOT_SANE_BEHAVIOR
) {
1290 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1292 if ((opts
->flags
& (CGRP_ROOT_NOPREFIX
| CGRP_ROOT_XATTR
)) ||
1293 opts
->cpuset_clone_children
|| opts
->release_agent
||
1295 pr_err("cgroup: sane_behavior: noprefix, xattr, clone_children, release_agent and name are not allowed\n");
1300 * If the 'all' option was specified select all the
1301 * subsystems, otherwise if 'none', 'name=' and a subsystem
1302 * name options were not specified, let's default to 'all'
1304 if (all_ss
|| (!one_ss
&& !opts
->none
&& !opts
->name
))
1305 for_each_subsys(ss
, i
)
1307 set_bit(i
, &opts
->subsys_mask
);
1310 * We either have to specify by name or by subsystems. (So
1311 * all empty hierarchies must have a name).
1313 if (!opts
->subsys_mask
&& !opts
->name
)
1318 * Option noprefix was introduced just for backward compatibility
1319 * with the old cpuset, so we allow noprefix only if mounting just
1320 * the cpuset subsystem.
1322 if ((opts
->flags
& CGRP_ROOT_NOPREFIX
) && (opts
->subsys_mask
& mask
))
1326 /* Can't specify "none" and some subsystems */
1327 if (opts
->subsys_mask
&& opts
->none
)
1333 static int cgroup_remount(struct kernfs_root
*kf_root
, int *flags
, char *data
)
1336 struct cgroup_root
*root
= cgroup_root_from_kf(kf_root
);
1337 struct cgroup_sb_opts opts
;
1338 unsigned long added_mask
, removed_mask
;
1340 if (root
->flags
& CGRP_ROOT_SANE_BEHAVIOR
) {
1341 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1345 mutex_lock(&cgroup_tree_mutex
);
1346 mutex_lock(&cgroup_mutex
);
1348 /* See what subsystems are wanted */
1349 ret
= parse_cgroupfs_options(data
, &opts
);
1353 if (opts
.subsys_mask
!= root
->subsys_mask
|| opts
.release_agent
)
1354 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1355 task_tgid_nr(current
), current
->comm
);
1357 added_mask
= opts
.subsys_mask
& ~root
->subsys_mask
;
1358 removed_mask
= root
->subsys_mask
& ~opts
.subsys_mask
;
1360 /* Don't allow flags or name to change at remount */
1361 if (((opts
.flags
^ root
->flags
) & CGRP_ROOT_OPTION_MASK
) ||
1362 (opts
.name
&& strcmp(opts
.name
, root
->name
))) {
1363 pr_err("cgroup: option or name mismatch, new: 0x%lx \"%s\", old: 0x%lx \"%s\"\n",
1364 opts
.flags
& CGRP_ROOT_OPTION_MASK
, opts
.name
?: "",
1365 root
->flags
& CGRP_ROOT_OPTION_MASK
, root
->name
);
1370 /* remounting is not allowed for populated hierarchies */
1371 if (!list_empty(&root
->cgrp
.children
)) {
1376 ret
= rebind_subsystems(root
, added_mask
);
1380 rebind_subsystems(&cgrp_dfl_root
, removed_mask
);
1382 if (opts
.release_agent
) {
1383 spin_lock(&release_agent_path_lock
);
1384 strcpy(root
->release_agent_path
, opts
.release_agent
);
1385 spin_unlock(&release_agent_path_lock
);
1388 kfree(opts
.release_agent
);
1390 mutex_unlock(&cgroup_mutex
);
1391 mutex_unlock(&cgroup_tree_mutex
);
1396 * To reduce the fork() overhead for systems that are not actually using
1397 * their cgroups capability, we don't maintain the lists running through
1398 * each css_set to its tasks until we see the list actually used - in other
1399 * words after the first mount.
1401 static bool use_task_css_set_links __read_mostly
;
1403 static void cgroup_enable_task_cg_lists(void)
1405 struct task_struct
*p
, *g
;
1407 down_write(&css_set_rwsem
);
1409 if (use_task_css_set_links
)
1412 use_task_css_set_links
= true;
1415 * We need tasklist_lock because RCU is not safe against
1416 * while_each_thread(). Besides, a forking task that has passed
1417 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1418 * is not guaranteed to have its child immediately visible in the
1419 * tasklist if we walk through it with RCU.
1421 read_lock(&tasklist_lock
);
1422 do_each_thread(g
, p
) {
1423 WARN_ON_ONCE(!list_empty(&p
->cg_list
) ||
1424 task_css_set(p
) != &init_css_set
);
1427 * We should check if the process is exiting, otherwise
1428 * it will race with cgroup_exit() in that the list
1429 * entry won't be deleted though the process has exited.
1430 * Do it while holding siglock so that we don't end up
1431 * racing against cgroup_exit().
1433 spin_lock_irq(&p
->sighand
->siglock
);
1434 if (!(p
->flags
& PF_EXITING
)) {
1435 struct css_set
*cset
= task_css_set(p
);
1437 list_add(&p
->cg_list
, &cset
->tasks
);
1440 spin_unlock_irq(&p
->sighand
->siglock
);
1441 } while_each_thread(g
, p
);
1442 read_unlock(&tasklist_lock
);
1444 up_write(&css_set_rwsem
);
1447 static void init_cgroup_housekeeping(struct cgroup
*cgrp
)
1449 struct cgroup_subsys
*ss
;
1452 atomic_set(&cgrp
->refcnt
, 1);
1453 INIT_LIST_HEAD(&cgrp
->sibling
);
1454 INIT_LIST_HEAD(&cgrp
->children
);
1455 INIT_LIST_HEAD(&cgrp
->cset_links
);
1456 INIT_LIST_HEAD(&cgrp
->release_list
);
1457 INIT_LIST_HEAD(&cgrp
->pidlists
);
1458 mutex_init(&cgrp
->pidlist_mutex
);
1459 cgrp
->dummy_css
.cgroup
= cgrp
;
1461 for_each_subsys(ss
, ssid
)
1462 INIT_LIST_HEAD(&cgrp
->e_csets
[ssid
]);
1464 init_waitqueue_head(&cgrp
->offline_waitq
);
1467 static void init_cgroup_root(struct cgroup_root
*root
,
1468 struct cgroup_sb_opts
*opts
)
1470 struct cgroup
*cgrp
= &root
->cgrp
;
1472 INIT_LIST_HEAD(&root
->root_list
);
1473 atomic_set(&root
->nr_cgrps
, 1);
1475 init_cgroup_housekeeping(cgrp
);
1476 idr_init(&root
->cgroup_idr
);
1478 root
->flags
= opts
->flags
;
1479 if (opts
->release_agent
)
1480 strcpy(root
->release_agent_path
, opts
->release_agent
);
1482 strcpy(root
->name
, opts
->name
);
1483 if (opts
->cpuset_clone_children
)
1484 set_bit(CGRP_CPUSET_CLONE_CHILDREN
, &root
->cgrp
.flags
);
1487 static int cgroup_setup_root(struct cgroup_root
*root
, unsigned long ss_mask
)
1489 LIST_HEAD(tmp_links
);
1490 struct cgroup
*root_cgrp
= &root
->cgrp
;
1491 struct css_set
*cset
;
1494 lockdep_assert_held(&cgroup_tree_mutex
);
1495 lockdep_assert_held(&cgroup_mutex
);
1497 ret
= idr_alloc(&root
->cgroup_idr
, root_cgrp
, 0, 1, GFP_KERNEL
);
1500 root_cgrp
->id
= ret
;
1503 * We're accessing css_set_count without locking css_set_rwsem here,
1504 * but that's OK - it can only be increased by someone holding
1505 * cgroup_lock, and that's us. The worst that can happen is that we
1506 * have some link structures left over
1508 ret
= allocate_cgrp_cset_links(css_set_count
, &tmp_links
);
1512 ret
= cgroup_init_root_id(root
);
1516 root
->kf_root
= kernfs_create_root(&cgroup_kf_syscall_ops
,
1517 KERNFS_ROOT_CREATE_DEACTIVATED
,
1519 if (IS_ERR(root
->kf_root
)) {
1520 ret
= PTR_ERR(root
->kf_root
);
1523 root_cgrp
->kn
= root
->kf_root
->kn
;
1525 ret
= cgroup_addrm_files(root_cgrp
, cgroup_base_files
, true);
1529 ret
= rebind_subsystems(root
, ss_mask
);
1534 * There must be no failure case after here, since rebinding takes
1535 * care of subsystems' refcounts, which are explicitly dropped in
1536 * the failure exit path.
1538 list_add(&root
->root_list
, &cgroup_roots
);
1539 cgroup_root_count
++;
1542 * Link the root cgroup in this hierarchy into all the css_set
1545 down_write(&css_set_rwsem
);
1546 hash_for_each(css_set_table
, i
, cset
, hlist
)
1547 link_css_set(&tmp_links
, cset
, root_cgrp
);
1548 up_write(&css_set_rwsem
);
1550 BUG_ON(!list_empty(&root_cgrp
->children
));
1551 BUG_ON(atomic_read(&root
->nr_cgrps
) != 1);
1553 kernfs_activate(root_cgrp
->kn
);
1558 kernfs_destroy_root(root
->kf_root
);
1559 root
->kf_root
= NULL
;
1561 cgroup_exit_root_id(root
);
1563 free_cgrp_cset_links(&tmp_links
);
1567 static struct dentry
*cgroup_mount(struct file_system_type
*fs_type
,
1568 int flags
, const char *unused_dev_name
,
1571 struct cgroup_root
*root
;
1572 struct cgroup_sb_opts opts
;
1573 struct dentry
*dentry
;
1578 * The first time anyone tries to mount a cgroup, enable the list
1579 * linking each css_set to its tasks and fix up all existing tasks.
1581 if (!use_task_css_set_links
)
1582 cgroup_enable_task_cg_lists();
1584 mutex_lock(&cgroup_tree_mutex
);
1585 mutex_lock(&cgroup_mutex
);
1587 /* First find the desired set of subsystems */
1588 ret
= parse_cgroupfs_options(data
, &opts
);
1592 /* look for a matching existing root */
1593 if (!opts
.subsys_mask
&& !opts
.none
&& !opts
.name
) {
1594 cgrp_dfl_root_visible
= true;
1595 root
= &cgrp_dfl_root
;
1596 cgroup_get(&root
->cgrp
);
1601 for_each_root(root
) {
1602 bool name_match
= false;
1604 if (root
== &cgrp_dfl_root
)
1608 * If we asked for a name then it must match. Also, if
1609 * name matches but sybsys_mask doesn't, we should fail.
1610 * Remember whether name matched.
1613 if (strcmp(opts
.name
, root
->name
))
1619 * If we asked for subsystems (or explicitly for no
1620 * subsystems) then they must match.
1622 if ((opts
.subsys_mask
|| opts
.none
) &&
1623 (opts
.subsys_mask
!= root
->subsys_mask
)) {
1630 if ((root
->flags
^ opts
.flags
) & CGRP_ROOT_OPTION_MASK
) {
1631 if ((root
->flags
| opts
.flags
) & CGRP_ROOT_SANE_BEHAVIOR
) {
1632 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1636 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1641 * A root's lifetime is governed by its root cgroup. Zero
1642 * ref indicate that the root is being destroyed. Wait for
1643 * destruction to complete so that the subsystems are free.
1644 * We can use wait_queue for the wait but this path is
1645 * super cold. Let's just sleep for a bit and retry.
1647 if (!atomic_inc_not_zero(&root
->cgrp
.refcnt
)) {
1648 mutex_unlock(&cgroup_mutex
);
1649 mutex_unlock(&cgroup_tree_mutex
);
1651 mutex_lock(&cgroup_tree_mutex
);
1652 mutex_lock(&cgroup_mutex
);
1661 * No such thing, create a new one. name= matching without subsys
1662 * specification is allowed for already existing hierarchies but we
1663 * can't create new one without subsys specification.
1665 if (!opts
.subsys_mask
&& !opts
.none
) {
1670 root
= kzalloc(sizeof(*root
), GFP_KERNEL
);
1676 init_cgroup_root(root
, &opts
);
1678 ret
= cgroup_setup_root(root
, opts
.subsys_mask
);
1680 cgroup_free_root(root
);
1683 mutex_unlock(&cgroup_mutex
);
1684 mutex_unlock(&cgroup_tree_mutex
);
1686 kfree(opts
.release_agent
);
1690 return ERR_PTR(ret
);
1692 dentry
= kernfs_mount(fs_type
, flags
, root
->kf_root
, &new_sb
);
1693 if (IS_ERR(dentry
) || !new_sb
)
1694 cgroup_put(&root
->cgrp
);
1698 static void cgroup_kill_sb(struct super_block
*sb
)
1700 struct kernfs_root
*kf_root
= kernfs_root_from_sb(sb
);
1701 struct cgroup_root
*root
= cgroup_root_from_kf(kf_root
);
1703 cgroup_put(&root
->cgrp
);
1707 static struct file_system_type cgroup_fs_type
= {
1709 .mount
= cgroup_mount
,
1710 .kill_sb
= cgroup_kill_sb
,
1713 static struct kobject
*cgroup_kobj
;
1716 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1717 * @task: target task
1718 * @buf: the buffer to write the path into
1719 * @buflen: the length of the buffer
1721 * Determine @task's cgroup on the first (the one with the lowest non-zero
1722 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1723 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1724 * cgroup controller callbacks.
1726 * Return value is the same as kernfs_path().
1728 char *task_cgroup_path(struct task_struct
*task
, char *buf
, size_t buflen
)
1730 struct cgroup_root
*root
;
1731 struct cgroup
*cgrp
;
1732 int hierarchy_id
= 1;
1735 mutex_lock(&cgroup_mutex
);
1736 down_read(&css_set_rwsem
);
1738 root
= idr_get_next(&cgroup_hierarchy_idr
, &hierarchy_id
);
1741 cgrp
= task_cgroup_from_root(task
, root
);
1742 path
= cgroup_path(cgrp
, buf
, buflen
);
1744 /* if no hierarchy exists, everyone is in "/" */
1745 if (strlcpy(buf
, "/", buflen
) < buflen
)
1749 up_read(&css_set_rwsem
);
1750 mutex_unlock(&cgroup_mutex
);
1753 EXPORT_SYMBOL_GPL(task_cgroup_path
);
1755 /* used to track tasks and other necessary states during migration */
1756 struct cgroup_taskset
{
1757 /* the src and dst cset list running through cset->mg_node */
1758 struct list_head src_csets
;
1759 struct list_head dst_csets
;
1762 * Fields for cgroup_taskset_*() iteration.
1764 * Before migration is committed, the target migration tasks are on
1765 * ->mg_tasks of the csets on ->src_csets. After, on ->mg_tasks of
1766 * the csets on ->dst_csets. ->csets point to either ->src_csets
1767 * or ->dst_csets depending on whether migration is committed.
1769 * ->cur_csets and ->cur_task point to the current task position
1772 struct list_head
*csets
;
1773 struct css_set
*cur_cset
;
1774 struct task_struct
*cur_task
;
1778 * cgroup_taskset_first - reset taskset and return the first task
1779 * @tset: taskset of interest
1781 * @tset iteration is initialized and the first task is returned.
1783 struct task_struct
*cgroup_taskset_first(struct cgroup_taskset
*tset
)
1785 tset
->cur_cset
= list_first_entry(tset
->csets
, struct css_set
, mg_node
);
1786 tset
->cur_task
= NULL
;
1788 return cgroup_taskset_next(tset
);
1792 * cgroup_taskset_next - iterate to the next task in taskset
1793 * @tset: taskset of interest
1795 * Return the next task in @tset. Iteration must have been initialized
1796 * with cgroup_taskset_first().
1798 struct task_struct
*cgroup_taskset_next(struct cgroup_taskset
*tset
)
1800 struct css_set
*cset
= tset
->cur_cset
;
1801 struct task_struct
*task
= tset
->cur_task
;
1803 while (&cset
->mg_node
!= tset
->csets
) {
1805 task
= list_first_entry(&cset
->mg_tasks
,
1806 struct task_struct
, cg_list
);
1808 task
= list_next_entry(task
, cg_list
);
1810 if (&task
->cg_list
!= &cset
->mg_tasks
) {
1811 tset
->cur_cset
= cset
;
1812 tset
->cur_task
= task
;
1816 cset
= list_next_entry(cset
, mg_node
);
1824 * cgroup_task_migrate - move a task from one cgroup to another.
1825 * @old_cgrp; the cgroup @tsk is being migrated from
1826 * @tsk: the task being migrated
1827 * @new_cset: the new css_set @tsk is being attached to
1829 * Must be called with cgroup_mutex, threadgroup and css_set_rwsem locked.
1831 static void cgroup_task_migrate(struct cgroup
*old_cgrp
,
1832 struct task_struct
*tsk
,
1833 struct css_set
*new_cset
)
1835 struct css_set
*old_cset
;
1837 lockdep_assert_held(&cgroup_mutex
);
1838 lockdep_assert_held(&css_set_rwsem
);
1841 * We are synchronized through threadgroup_lock() against PF_EXITING
1842 * setting such that we can't race against cgroup_exit() changing the
1843 * css_set to init_css_set and dropping the old one.
1845 WARN_ON_ONCE(tsk
->flags
& PF_EXITING
);
1846 old_cset
= task_css_set(tsk
);
1848 get_css_set(new_cset
);
1849 rcu_assign_pointer(tsk
->cgroups
, new_cset
);
1852 * Use move_tail so that cgroup_taskset_first() still returns the
1853 * leader after migration. This works because cgroup_migrate()
1854 * ensures that the dst_cset of the leader is the first on the
1855 * tset's dst_csets list.
1857 list_move_tail(&tsk
->cg_list
, &new_cset
->mg_tasks
);
1860 * We just gained a reference on old_cset by taking it from the
1861 * task. As trading it for new_cset is protected by cgroup_mutex,
1862 * we're safe to drop it here; it will be freed under RCU.
1864 set_bit(CGRP_RELEASABLE
, &old_cgrp
->flags
);
1865 put_css_set_locked(old_cset
, false);
1869 * cgroup_migrate_finish - cleanup after attach
1870 * @preloaded_csets: list of preloaded css_sets
1872 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
1873 * those functions for details.
1875 static void cgroup_migrate_finish(struct list_head
*preloaded_csets
)
1877 struct css_set
*cset
, *tmp_cset
;
1879 lockdep_assert_held(&cgroup_mutex
);
1881 down_write(&css_set_rwsem
);
1882 list_for_each_entry_safe(cset
, tmp_cset
, preloaded_csets
, mg_preload_node
) {
1883 cset
->mg_src_cgrp
= NULL
;
1884 cset
->mg_dst_cset
= NULL
;
1885 list_del_init(&cset
->mg_preload_node
);
1886 put_css_set_locked(cset
, false);
1888 up_write(&css_set_rwsem
);
1892 * cgroup_migrate_add_src - add a migration source css_set
1893 * @src_cset: the source css_set to add
1894 * @dst_cgrp: the destination cgroup
1895 * @preloaded_csets: list of preloaded css_sets
1897 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
1898 * @src_cset and add it to @preloaded_csets, which should later be cleaned
1899 * up by cgroup_migrate_finish().
1901 * This function may be called without holding threadgroup_lock even if the
1902 * target is a process. Threads may be created and destroyed but as long
1903 * as cgroup_mutex is not dropped, no new css_set can be put into play and
1904 * the preloaded css_sets are guaranteed to cover all migrations.
1906 static void cgroup_migrate_add_src(struct css_set
*src_cset
,
1907 struct cgroup
*dst_cgrp
,
1908 struct list_head
*preloaded_csets
)
1910 struct cgroup
*src_cgrp
;
1912 lockdep_assert_held(&cgroup_mutex
);
1913 lockdep_assert_held(&css_set_rwsem
);
1915 src_cgrp
= cset_cgroup_from_root(src_cset
, dst_cgrp
->root
);
1917 if (!list_empty(&src_cset
->mg_preload_node
))
1920 WARN_ON(src_cset
->mg_src_cgrp
);
1921 WARN_ON(!list_empty(&src_cset
->mg_tasks
));
1922 WARN_ON(!list_empty(&src_cset
->mg_node
));
1924 src_cset
->mg_src_cgrp
= src_cgrp
;
1925 get_css_set(src_cset
);
1926 list_add(&src_cset
->mg_preload_node
, preloaded_csets
);
1930 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
1931 * @dst_cgrp: the destination cgroup (may be %NULL)
1932 * @preloaded_csets: list of preloaded source css_sets
1934 * Tasks are about to be moved to @dst_cgrp and all the source css_sets
1935 * have been preloaded to @preloaded_csets. This function looks up and
1936 * pins all destination css_sets, links each to its source, and append them
1937 * to @preloaded_csets. If @dst_cgrp is %NULL, the destination of each
1938 * source css_set is assumed to be its cgroup on the default hierarchy.
1940 * This function must be called after cgroup_migrate_add_src() has been
1941 * called on each migration source css_set. After migration is performed
1942 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
1945 static int cgroup_migrate_prepare_dst(struct cgroup
*dst_cgrp
,
1946 struct list_head
*preloaded_csets
)
1949 struct css_set
*src_cset
, *tmp_cset
;
1951 lockdep_assert_held(&cgroup_mutex
);
1954 * Except for the root, child_subsys_mask must be zero for a cgroup
1955 * with tasks so that child cgroups don't compete against tasks.
1957 if (dst_cgrp
&& cgroup_on_dfl(dst_cgrp
) && dst_cgrp
->parent
&&
1958 dst_cgrp
->child_subsys_mask
)
1961 /* look up the dst cset for each src cset and link it to src */
1962 list_for_each_entry_safe(src_cset
, tmp_cset
, preloaded_csets
, mg_preload_node
) {
1963 struct css_set
*dst_cset
;
1965 dst_cset
= find_css_set(src_cset
,
1966 dst_cgrp
?: src_cset
->dfl_cgrp
);
1970 WARN_ON_ONCE(src_cset
->mg_dst_cset
|| dst_cset
->mg_dst_cset
);
1973 * If src cset equals dst, it's noop. Drop the src.
1974 * cgroup_migrate() will skip the cset too. Note that we
1975 * can't handle src == dst as some nodes are used by both.
1977 if (src_cset
== dst_cset
) {
1978 src_cset
->mg_src_cgrp
= NULL
;
1979 list_del_init(&src_cset
->mg_preload_node
);
1980 put_css_set(src_cset
, false);
1981 put_css_set(dst_cset
, false);
1985 src_cset
->mg_dst_cset
= dst_cset
;
1987 if (list_empty(&dst_cset
->mg_preload_node
))
1988 list_add(&dst_cset
->mg_preload_node
, &csets
);
1990 put_css_set(dst_cset
, false);
1993 list_splice_tail(&csets
, preloaded_csets
);
1996 cgroup_migrate_finish(&csets
);
2001 * cgroup_migrate - migrate a process or task to a cgroup
2002 * @cgrp: the destination cgroup
2003 * @leader: the leader of the process or the task to migrate
2004 * @threadgroup: whether @leader points to the whole process or a single task
2006 * Migrate a process or task denoted by @leader to @cgrp. If migrating a
2007 * process, the caller must be holding threadgroup_lock of @leader. The
2008 * caller is also responsible for invoking cgroup_migrate_add_src() and
2009 * cgroup_migrate_prepare_dst() on the targets before invoking this
2010 * function and following up with cgroup_migrate_finish().
2012 * As long as a controller's ->can_attach() doesn't fail, this function is
2013 * guaranteed to succeed. This means that, excluding ->can_attach()
2014 * failure, when migrating multiple targets, the success or failure can be
2015 * decided for all targets by invoking group_migrate_prepare_dst() before
2016 * actually starting migrating.
2018 static int cgroup_migrate(struct cgroup
*cgrp
, struct task_struct
*leader
,
2021 struct cgroup_taskset tset
= {
2022 .src_csets
= LIST_HEAD_INIT(tset
.src_csets
),
2023 .dst_csets
= LIST_HEAD_INIT(tset
.dst_csets
),
2024 .csets
= &tset
.src_csets
,
2026 struct cgroup_subsys_state
*css
, *failed_css
= NULL
;
2027 struct css_set
*cset
, *tmp_cset
;
2028 struct task_struct
*task
, *tmp_task
;
2032 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2033 * already PF_EXITING could be freed from underneath us unless we
2034 * take an rcu_read_lock.
2036 down_write(&css_set_rwsem
);
2040 /* @task either already exited or can't exit until the end */
2041 if (task
->flags
& PF_EXITING
)
2044 /* leave @task alone if post_fork() hasn't linked it yet */
2045 if (list_empty(&task
->cg_list
))
2048 cset
= task_css_set(task
);
2049 if (!cset
->mg_src_cgrp
)
2053 * cgroup_taskset_first() must always return the leader.
2054 * Take care to avoid disturbing the ordering.
2056 list_move_tail(&task
->cg_list
, &cset
->mg_tasks
);
2057 if (list_empty(&cset
->mg_node
))
2058 list_add_tail(&cset
->mg_node
, &tset
.src_csets
);
2059 if (list_empty(&cset
->mg_dst_cset
->mg_node
))
2060 list_move_tail(&cset
->mg_dst_cset
->mg_node
,
2065 } while_each_thread(leader
, task
);
2067 up_write(&css_set_rwsem
);
2069 /* methods shouldn't be called if no task is actually migrating */
2070 if (list_empty(&tset
.src_csets
))
2073 /* check that we can legitimately attach to the cgroup */
2074 for_each_e_css(css
, i
, cgrp
) {
2075 if (css
->ss
->can_attach
) {
2076 ret
= css
->ss
->can_attach(css
, &tset
);
2079 goto out_cancel_attach
;
2085 * Now that we're guaranteed success, proceed to move all tasks to
2086 * the new cgroup. There are no failure cases after here, so this
2087 * is the commit point.
2089 down_write(&css_set_rwsem
);
2090 list_for_each_entry(cset
, &tset
.src_csets
, mg_node
) {
2091 list_for_each_entry_safe(task
, tmp_task
, &cset
->mg_tasks
, cg_list
)
2092 cgroup_task_migrate(cset
->mg_src_cgrp
, task
,
2095 up_write(&css_set_rwsem
);
2098 * Migration is committed, all target tasks are now on dst_csets.
2099 * Nothing is sensitive to fork() after this point. Notify
2100 * controllers that migration is complete.
2102 tset
.csets
= &tset
.dst_csets
;
2104 for_each_e_css(css
, i
, cgrp
)
2105 if (css
->ss
->attach
)
2106 css
->ss
->attach(css
, &tset
);
2109 goto out_release_tset
;
2112 for_each_e_css(css
, i
, cgrp
) {
2113 if (css
== failed_css
)
2115 if (css
->ss
->cancel_attach
)
2116 css
->ss
->cancel_attach(css
, &tset
);
2119 down_write(&css_set_rwsem
);
2120 list_splice_init(&tset
.dst_csets
, &tset
.src_csets
);
2121 list_for_each_entry_safe(cset
, tmp_cset
, &tset
.src_csets
, mg_node
) {
2122 list_splice_tail_init(&cset
->mg_tasks
, &cset
->tasks
);
2123 list_del_init(&cset
->mg_node
);
2125 up_write(&css_set_rwsem
);
2130 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2131 * @dst_cgrp: the cgroup to attach to
2132 * @leader: the task or the leader of the threadgroup to be attached
2133 * @threadgroup: attach the whole threadgroup?
2135 * Call holding cgroup_mutex and threadgroup_lock of @leader.
2137 static int cgroup_attach_task(struct cgroup
*dst_cgrp
,
2138 struct task_struct
*leader
, bool threadgroup
)
2140 LIST_HEAD(preloaded_csets
);
2141 struct task_struct
*task
;
2144 /* look up all src csets */
2145 down_read(&css_set_rwsem
);
2149 cgroup_migrate_add_src(task_css_set(task
), dst_cgrp
,
2153 } while_each_thread(leader
, task
);
2155 up_read(&css_set_rwsem
);
2157 /* prepare dst csets and commit */
2158 ret
= cgroup_migrate_prepare_dst(dst_cgrp
, &preloaded_csets
);
2160 ret
= cgroup_migrate(dst_cgrp
, leader
, threadgroup
);
2162 cgroup_migrate_finish(&preloaded_csets
);
2167 * Find the task_struct of the task to attach by vpid and pass it along to the
2168 * function to attach either it or all tasks in its threadgroup. Will lock
2169 * cgroup_mutex and threadgroup.
2171 static int attach_task_by_pid(struct cgroup
*cgrp
, u64 pid
, bool threadgroup
)
2173 struct task_struct
*tsk
;
2174 const struct cred
*cred
= current_cred(), *tcred
;
2177 if (!cgroup_lock_live_group(cgrp
))
2183 tsk
= find_task_by_vpid(pid
);
2187 goto out_unlock_cgroup
;
2190 * even if we're attaching all tasks in the thread group, we
2191 * only need to check permissions on one of them.
2193 tcred
= __task_cred(tsk
);
2194 if (!uid_eq(cred
->euid
, GLOBAL_ROOT_UID
) &&
2195 !uid_eq(cred
->euid
, tcred
->uid
) &&
2196 !uid_eq(cred
->euid
, tcred
->suid
)) {
2199 goto out_unlock_cgroup
;
2205 tsk
= tsk
->group_leader
;
2208 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2209 * trapped in a cpuset, or RT worker may be born in a cgroup
2210 * with no rt_runtime allocated. Just say no.
2212 if (tsk
== kthreadd_task
|| (tsk
->flags
& PF_NO_SETAFFINITY
)) {
2215 goto out_unlock_cgroup
;
2218 get_task_struct(tsk
);
2221 threadgroup_lock(tsk
);
2223 if (!thread_group_leader(tsk
)) {
2225 * a race with de_thread from another thread's exec()
2226 * may strip us of our leadership, if this happens,
2227 * there is no choice but to throw this task away and
2228 * try again; this is
2229 * "double-double-toil-and-trouble-check locking".
2231 threadgroup_unlock(tsk
);
2232 put_task_struct(tsk
);
2233 goto retry_find_task
;
2237 ret
= cgroup_attach_task(cgrp
, tsk
, threadgroup
);
2239 threadgroup_unlock(tsk
);
2241 put_task_struct(tsk
);
2243 mutex_unlock(&cgroup_mutex
);
2248 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2249 * @from: attach to all cgroups of a given task
2250 * @tsk: the task to be attached
2252 int cgroup_attach_task_all(struct task_struct
*from
, struct task_struct
*tsk
)
2254 struct cgroup_root
*root
;
2257 mutex_lock(&cgroup_mutex
);
2258 for_each_root(root
) {
2259 struct cgroup
*from_cgrp
;
2261 if (root
== &cgrp_dfl_root
)
2264 down_read(&css_set_rwsem
);
2265 from_cgrp
= task_cgroup_from_root(from
, root
);
2266 up_read(&css_set_rwsem
);
2268 retval
= cgroup_attach_task(from_cgrp
, tsk
, false);
2272 mutex_unlock(&cgroup_mutex
);
2276 EXPORT_SYMBOL_GPL(cgroup_attach_task_all
);
2278 static int cgroup_tasks_write(struct cgroup_subsys_state
*css
,
2279 struct cftype
*cft
, u64 pid
)
2281 return attach_task_by_pid(css
->cgroup
, pid
, false);
2284 static int cgroup_procs_write(struct cgroup_subsys_state
*css
,
2285 struct cftype
*cft
, u64 tgid
)
2287 return attach_task_by_pid(css
->cgroup
, tgid
, true);
2290 static int cgroup_release_agent_write(struct cgroup_subsys_state
*css
,
2291 struct cftype
*cft
, char *buffer
)
2293 struct cgroup_root
*root
= css
->cgroup
->root
;
2295 BUILD_BUG_ON(sizeof(root
->release_agent_path
) < PATH_MAX
);
2296 if (!cgroup_lock_live_group(css
->cgroup
))
2298 spin_lock(&release_agent_path_lock
);
2299 strlcpy(root
->release_agent_path
, buffer
,
2300 sizeof(root
->release_agent_path
));
2301 spin_unlock(&release_agent_path_lock
);
2302 mutex_unlock(&cgroup_mutex
);
2306 static int cgroup_release_agent_show(struct seq_file
*seq
, void *v
)
2308 struct cgroup
*cgrp
= seq_css(seq
)->cgroup
;
2310 if (!cgroup_lock_live_group(cgrp
))
2312 seq_puts(seq
, cgrp
->root
->release_agent_path
);
2313 seq_putc(seq
, '\n');
2314 mutex_unlock(&cgroup_mutex
);
2318 static int cgroup_sane_behavior_show(struct seq_file
*seq
, void *v
)
2320 struct cgroup
*cgrp
= seq_css(seq
)->cgroup
;
2322 seq_printf(seq
, "%d\n", cgroup_sane_behavior(cgrp
));
2326 static void cgroup_print_ss_mask(struct seq_file
*seq
, unsigned int ss_mask
)
2328 struct cgroup_subsys
*ss
;
2329 bool printed
= false;
2332 for_each_subsys(ss
, ssid
) {
2333 if (ss_mask
& (1 << ssid
)) {
2336 seq_printf(seq
, "%s", ss
->name
);
2341 seq_putc(seq
, '\n');
2344 /* show controllers which are currently attached to the default hierarchy */
2345 static int cgroup_root_controllers_show(struct seq_file
*seq
, void *v
)
2347 struct cgroup
*cgrp
= seq_css(seq
)->cgroup
;
2349 cgroup_print_ss_mask(seq
, cgrp
->root
->subsys_mask
);
2353 /* show controllers which are enabled from the parent */
2354 static int cgroup_controllers_show(struct seq_file
*seq
, void *v
)
2356 struct cgroup
*cgrp
= seq_css(seq
)->cgroup
;
2358 cgroup_print_ss_mask(seq
, cgrp
->parent
->child_subsys_mask
);
2362 /* show controllers which are enabled for a given cgroup's children */
2363 static int cgroup_subtree_control_show(struct seq_file
*seq
, void *v
)
2365 struct cgroup
*cgrp
= seq_css(seq
)->cgroup
;
2367 cgroup_print_ss_mask(seq
, cgrp
->child_subsys_mask
);
2372 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2373 * @cgrp: root of the subtree to update csses for
2375 * @cgrp's child_subsys_mask has changed and its subtree's (self excluded)
2376 * css associations need to be updated accordingly. This function looks up
2377 * all css_sets which are attached to the subtree, creates the matching
2378 * updated css_sets and migrates the tasks to the new ones.
2380 static int cgroup_update_dfl_csses(struct cgroup
*cgrp
)
2382 LIST_HEAD(preloaded_csets
);
2383 struct cgroup_subsys_state
*css
;
2384 struct css_set
*src_cset
;
2387 lockdep_assert_held(&cgroup_tree_mutex
);
2388 lockdep_assert_held(&cgroup_mutex
);
2390 /* look up all csses currently attached to @cgrp's subtree */
2391 down_read(&css_set_rwsem
);
2392 css_for_each_descendant_pre(css
, cgroup_css(cgrp
, NULL
)) {
2393 struct cgrp_cset_link
*link
;
2395 /* self is not affected by child_subsys_mask change */
2396 if (css
->cgroup
== cgrp
)
2399 list_for_each_entry(link
, &css
->cgroup
->cset_links
, cset_link
)
2400 cgroup_migrate_add_src(link
->cset
, cgrp
,
2403 up_read(&css_set_rwsem
);
2405 /* NULL dst indicates self on default hierarchy */
2406 ret
= cgroup_migrate_prepare_dst(NULL
, &preloaded_csets
);
2410 list_for_each_entry(src_cset
, &preloaded_csets
, mg_preload_node
) {
2411 struct task_struct
*last_task
= NULL
, *task
;
2413 /* src_csets precede dst_csets, break on the first dst_cset */
2414 if (!src_cset
->mg_src_cgrp
)
2418 * All tasks in src_cset need to be migrated to the
2419 * matching dst_cset. Empty it process by process. We
2420 * walk tasks but migrate processes. The leader might even
2421 * belong to a different cset but such src_cset would also
2422 * be among the target src_csets because the default
2423 * hierarchy enforces per-process membership.
2426 down_read(&css_set_rwsem
);
2427 task
= list_first_entry_or_null(&src_cset
->tasks
,
2428 struct task_struct
, cg_list
);
2430 task
= task
->group_leader
;
2431 WARN_ON_ONCE(!task_css_set(task
)->mg_src_cgrp
);
2432 get_task_struct(task
);
2434 up_read(&css_set_rwsem
);
2439 /* guard against possible infinite loop */
2440 if (WARN(last_task
== task
,
2441 "cgroup: update_dfl_csses failed to make progress, aborting in inconsistent state\n"))
2445 threadgroup_lock(task
);
2446 /* raced against de_thread() from another thread? */
2447 if (!thread_group_leader(task
)) {
2448 threadgroup_unlock(task
);
2449 put_task_struct(task
);
2453 ret
= cgroup_migrate(src_cset
->dfl_cgrp
, task
, true);
2455 threadgroup_unlock(task
);
2456 put_task_struct(task
);
2458 if (WARN(ret
, "cgroup: failed to update controllers for the default hierarchy (%d), further operations may crash or hang\n", ret
))
2464 cgroup_migrate_finish(&preloaded_csets
);
2468 /* change the enabled child controllers for a cgroup in the default hierarchy */
2469 static int cgroup_subtree_control_write(struct cgroup_subsys_state
*dummy_css
,
2470 struct cftype
*cft
, char *buffer
)
2472 unsigned long enable_req
= 0, disable_req
= 0, enable
, disable
;
2473 struct cgroup
*cgrp
= dummy_css
->cgroup
, *child
;
2474 struct cgroup_subsys
*ss
;
2479 * Parse input - white space separated list of subsystem names
2480 * prefixed with either + or -.
2483 while ((tok
= strsep(&p
, " \t\n"))) {
2484 for_each_subsys(ss
, ssid
) {
2485 if (ss
->disabled
|| strcmp(tok
+ 1, ss
->name
))
2489 enable_req
|= 1 << ssid
;
2490 disable_req
&= ~(1 << ssid
);
2491 } else if (*tok
== '-') {
2492 disable_req
|= 1 << ssid
;
2493 enable_req
&= ~(1 << ssid
);
2499 if (ssid
== CGROUP_SUBSYS_COUNT
)
2504 * We're gonna grab cgroup_tree_mutex which nests outside kernfs
2505 * active_ref. cgroup_lock_live_group() already provides enough
2506 * protection. Ensure @cgrp stays accessible and break the
2507 * active_ref protection.
2510 kernfs_break_active_protection(cgrp
->control_kn
);
2512 enable
= enable_req
;
2513 disable
= disable_req
;
2515 mutex_lock(&cgroup_tree_mutex
);
2517 for_each_subsys(ss
, ssid
) {
2518 if (enable
& (1 << ssid
)) {
2519 if (cgrp
->child_subsys_mask
& (1 << ssid
)) {
2520 enable
&= ~(1 << ssid
);
2525 * Because css offlining is asynchronous, userland
2526 * might try to re-enable the same controller while
2527 * the previous instance is still around. In such
2528 * cases, wait till it's gone using offline_waitq.
2530 cgroup_for_each_live_child(child
, cgrp
) {
2533 if (!cgroup_css(child
, ss
))
2536 prepare_to_wait(&child
->offline_waitq
, &wait
,
2537 TASK_UNINTERRUPTIBLE
);
2538 mutex_unlock(&cgroup_tree_mutex
);
2540 finish_wait(&child
->offline_waitq
, &wait
);
2544 /* unavailable or not enabled on the parent? */
2545 if (!(cgrp_dfl_root
.subsys_mask
& (1 << ssid
)) ||
2547 !(cgrp
->parent
->child_subsys_mask
& (1 << ssid
)))) {
2549 goto out_unlock_tree
;
2551 } else if (disable
& (1 << ssid
)) {
2552 if (!(cgrp
->child_subsys_mask
& (1 << ssid
))) {
2553 disable
&= ~(1 << ssid
);
2557 /* a child has it enabled? */
2558 cgroup_for_each_live_child(child
, cgrp
) {
2559 if (child
->child_subsys_mask
& (1 << ssid
)) {
2561 goto out_unlock_tree
;
2567 if (!enable
&& !disable
) {
2569 goto out_unlock_tree
;
2572 if (!cgroup_lock_live_group(cgrp
)) {
2574 goto out_unlock_tree
;
2578 * Except for the root, child_subsys_mask must be zero for a cgroup
2579 * with tasks so that child cgroups don't compete against tasks.
2581 if (enable
&& cgrp
->parent
&& !list_empty(&cgrp
->cset_links
)) {
2587 * Create csses for enables and update child_subsys_mask. This
2588 * changes cgroup_e_css() results which in turn makes the
2589 * subsequent cgroup_update_dfl_csses() associate all tasks in the
2590 * subtree to the updated csses.
2592 for_each_subsys(ss
, ssid
) {
2593 if (!(enable
& (1 << ssid
)))
2596 cgroup_for_each_live_child(child
, cgrp
) {
2597 ret
= create_css(child
, ss
);
2603 cgrp
->child_subsys_mask
|= enable
;
2604 cgrp
->child_subsys_mask
&= ~disable
;
2606 ret
= cgroup_update_dfl_csses(cgrp
);
2610 /* all tasks are now migrated away from the old csses, kill them */
2611 for_each_subsys(ss
, ssid
) {
2612 if (!(disable
& (1 << ssid
)))
2615 cgroup_for_each_live_child(child
, cgrp
)
2616 kill_css(cgroup_css(child
, ss
));
2619 kernfs_activate(cgrp
->kn
);
2622 mutex_unlock(&cgroup_mutex
);
2624 mutex_unlock(&cgroup_tree_mutex
);
2625 kernfs_unbreak_active_protection(cgrp
->control_kn
);
2630 cgrp
->child_subsys_mask
&= ~enable
;
2631 cgrp
->child_subsys_mask
|= disable
;
2633 for_each_subsys(ss
, ssid
) {
2634 if (!(enable
& (1 << ssid
)))
2637 cgroup_for_each_live_child(child
, cgrp
) {
2638 struct cgroup_subsys_state
*css
= cgroup_css(child
, ss
);
2646 static ssize_t
cgroup_file_write(struct kernfs_open_file
*of
, char *buf
,
2647 size_t nbytes
, loff_t off
)
2649 struct cgroup
*cgrp
= of
->kn
->parent
->priv
;
2650 struct cftype
*cft
= of
->kn
->priv
;
2651 struct cgroup_subsys_state
*css
;
2655 * kernfs guarantees that a file isn't deleted with operations in
2656 * flight, which means that the matching css is and stays alive and
2657 * doesn't need to be pinned. The RCU locking is not necessary
2658 * either. It's just for the convenience of using cgroup_css().
2661 css
= cgroup_css(cgrp
, cft
->ss
);
2664 if (cft
->write_string
) {
2665 ret
= cft
->write_string(css
, cft
, strstrip(buf
));
2666 } else if (cft
->write_u64
) {
2667 unsigned long long v
;
2668 ret
= kstrtoull(buf
, 0, &v
);
2670 ret
= cft
->write_u64(css
, cft
, v
);
2671 } else if (cft
->write_s64
) {
2673 ret
= kstrtoll(buf
, 0, &v
);
2675 ret
= cft
->write_s64(css
, cft
, v
);
2676 } else if (cft
->trigger
) {
2677 ret
= cft
->trigger(css
, (unsigned int)cft
->private);
2682 return ret
?: nbytes
;
2685 static void *cgroup_seqfile_start(struct seq_file
*seq
, loff_t
*ppos
)
2687 return seq_cft(seq
)->seq_start(seq
, ppos
);
2690 static void *cgroup_seqfile_next(struct seq_file
*seq
, void *v
, loff_t
*ppos
)
2692 return seq_cft(seq
)->seq_next(seq
, v
, ppos
);
2695 static void cgroup_seqfile_stop(struct seq_file
*seq
, void *v
)
2697 seq_cft(seq
)->seq_stop(seq
, v
);
2700 static int cgroup_seqfile_show(struct seq_file
*m
, void *arg
)
2702 struct cftype
*cft
= seq_cft(m
);
2703 struct cgroup_subsys_state
*css
= seq_css(m
);
2706 return cft
->seq_show(m
, arg
);
2709 seq_printf(m
, "%llu\n", cft
->read_u64(css
, cft
));
2710 else if (cft
->read_s64
)
2711 seq_printf(m
, "%lld\n", cft
->read_s64(css
, cft
));
2717 static struct kernfs_ops cgroup_kf_single_ops
= {
2718 .atomic_write_len
= PAGE_SIZE
,
2719 .write
= cgroup_file_write
,
2720 .seq_show
= cgroup_seqfile_show
,
2723 static struct kernfs_ops cgroup_kf_ops
= {
2724 .atomic_write_len
= PAGE_SIZE
,
2725 .write
= cgroup_file_write
,
2726 .seq_start
= cgroup_seqfile_start
,
2727 .seq_next
= cgroup_seqfile_next
,
2728 .seq_stop
= cgroup_seqfile_stop
,
2729 .seq_show
= cgroup_seqfile_show
,
2733 * cgroup_rename - Only allow simple rename of directories in place.
2735 static int cgroup_rename(struct kernfs_node
*kn
, struct kernfs_node
*new_parent
,
2736 const char *new_name_str
)
2738 struct cgroup
*cgrp
= kn
->priv
;
2741 if (kernfs_type(kn
) != KERNFS_DIR
)
2743 if (kn
->parent
!= new_parent
)
2747 * This isn't a proper migration and its usefulness is very
2748 * limited. Disallow if sane_behavior.
2750 if (cgroup_sane_behavior(cgrp
))
2754 * We're gonna grab cgroup_tree_mutex which nests outside kernfs
2755 * active_ref. kernfs_rename() doesn't require active_ref
2756 * protection. Break them before grabbing cgroup_tree_mutex.
2758 kernfs_break_active_protection(new_parent
);
2759 kernfs_break_active_protection(kn
);
2761 mutex_lock(&cgroup_tree_mutex
);
2762 mutex_lock(&cgroup_mutex
);
2764 ret
= kernfs_rename(kn
, new_parent
, new_name_str
);
2766 mutex_unlock(&cgroup_mutex
);
2767 mutex_unlock(&cgroup_tree_mutex
);
2769 kernfs_unbreak_active_protection(kn
);
2770 kernfs_unbreak_active_protection(new_parent
);
2774 /* set uid and gid of cgroup dirs and files to that of the creator */
2775 static int cgroup_kn_set_ugid(struct kernfs_node
*kn
)
2777 struct iattr iattr
= { .ia_valid
= ATTR_UID
| ATTR_GID
,
2778 .ia_uid
= current_fsuid(),
2779 .ia_gid
= current_fsgid(), };
2781 if (uid_eq(iattr
.ia_uid
, GLOBAL_ROOT_UID
) &&
2782 gid_eq(iattr
.ia_gid
, GLOBAL_ROOT_GID
))
2785 return kernfs_setattr(kn
, &iattr
);
2788 static int cgroup_add_file(struct cgroup
*cgrp
, struct cftype
*cft
)
2790 char name
[CGROUP_FILE_NAME_MAX
];
2791 struct kernfs_node
*kn
;
2792 struct lock_class_key
*key
= NULL
;
2795 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2796 key
= &cft
->lockdep_key
;
2798 kn
= __kernfs_create_file(cgrp
->kn
, cgroup_file_name(cgrp
, cft
, name
),
2799 cgroup_file_mode(cft
), 0, cft
->kf_ops
, cft
,
2804 ret
= cgroup_kn_set_ugid(kn
);
2810 if (cft
->seq_show
== cgroup_subtree_control_show
)
2811 cgrp
->control_kn
= kn
;
2816 * cgroup_addrm_files - add or remove files to a cgroup directory
2817 * @cgrp: the target cgroup
2818 * @cfts: array of cftypes to be added
2819 * @is_add: whether to add or remove
2821 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2822 * For removals, this function never fails. If addition fails, this
2823 * function doesn't remove files already added. The caller is responsible
2826 static int cgroup_addrm_files(struct cgroup
*cgrp
, struct cftype cfts
[],
2832 lockdep_assert_held(&cgroup_tree_mutex
);
2834 for (cft
= cfts
; cft
->name
[0] != '\0'; cft
++) {
2835 /* does cft->flags tell us to skip this file on @cgrp? */
2836 if ((cft
->flags
& CFTYPE_ONLY_ON_DFL
) && !cgroup_on_dfl(cgrp
))
2838 if ((cft
->flags
& CFTYPE_INSANE
) && cgroup_sane_behavior(cgrp
))
2840 if ((cft
->flags
& CFTYPE_NOT_ON_ROOT
) && !cgrp
->parent
)
2842 if ((cft
->flags
& CFTYPE_ONLY_ON_ROOT
) && cgrp
->parent
)
2846 ret
= cgroup_add_file(cgrp
, cft
);
2848 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2853 cgroup_rm_file(cgrp
, cft
);
2859 static int cgroup_apply_cftypes(struct cftype
*cfts
, bool is_add
)
2862 struct cgroup_subsys
*ss
= cfts
[0].ss
;
2863 struct cgroup
*root
= &ss
->root
->cgrp
;
2864 struct cgroup_subsys_state
*css
;
2867 lockdep_assert_held(&cgroup_tree_mutex
);
2869 /* add/rm files for all cgroups created before */
2870 css_for_each_descendant_pre(css
, cgroup_css(root
, ss
)) {
2871 struct cgroup
*cgrp
= css
->cgroup
;
2873 if (cgroup_is_dead(cgrp
))
2876 ret
= cgroup_addrm_files(cgrp
, cfts
, is_add
);
2882 kernfs_activate(root
->kn
);
2886 static void cgroup_exit_cftypes(struct cftype
*cfts
)
2890 for (cft
= cfts
; cft
->name
[0] != '\0'; cft
++) {
2891 /* free copy for custom atomic_write_len, see init_cftypes() */
2892 if (cft
->max_write_len
&& cft
->max_write_len
!= PAGE_SIZE
)
2899 static int cgroup_init_cftypes(struct cgroup_subsys
*ss
, struct cftype
*cfts
)
2903 for (cft
= cfts
; cft
->name
[0] != '\0'; cft
++) {
2904 struct kernfs_ops
*kf_ops
;
2906 WARN_ON(cft
->ss
|| cft
->kf_ops
);
2909 kf_ops
= &cgroup_kf_ops
;
2911 kf_ops
= &cgroup_kf_single_ops
;
2914 * Ugh... if @cft wants a custom max_write_len, we need to
2915 * make a copy of kf_ops to set its atomic_write_len.
2917 if (cft
->max_write_len
&& cft
->max_write_len
!= PAGE_SIZE
) {
2918 kf_ops
= kmemdup(kf_ops
, sizeof(*kf_ops
), GFP_KERNEL
);
2920 cgroup_exit_cftypes(cfts
);
2923 kf_ops
->atomic_write_len
= cft
->max_write_len
;
2926 cft
->kf_ops
= kf_ops
;
2933 static int cgroup_rm_cftypes_locked(struct cftype
*cfts
)
2935 lockdep_assert_held(&cgroup_tree_mutex
);
2937 if (!cfts
|| !cfts
[0].ss
)
2940 list_del(&cfts
->node
);
2941 cgroup_apply_cftypes(cfts
, false);
2942 cgroup_exit_cftypes(cfts
);
2947 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2948 * @cfts: zero-length name terminated array of cftypes
2950 * Unregister @cfts. Files described by @cfts are removed from all
2951 * existing cgroups and all future cgroups won't have them either. This
2952 * function can be called anytime whether @cfts' subsys is attached or not.
2954 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2957 int cgroup_rm_cftypes(struct cftype
*cfts
)
2961 mutex_lock(&cgroup_tree_mutex
);
2962 ret
= cgroup_rm_cftypes_locked(cfts
);
2963 mutex_unlock(&cgroup_tree_mutex
);
2968 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2969 * @ss: target cgroup subsystem
2970 * @cfts: zero-length name terminated array of cftypes
2972 * Register @cfts to @ss. Files described by @cfts are created for all
2973 * existing cgroups to which @ss is attached and all future cgroups will
2974 * have them too. This function can be called anytime whether @ss is
2977 * Returns 0 on successful registration, -errno on failure. Note that this
2978 * function currently returns 0 as long as @cfts registration is successful
2979 * even if some file creation attempts on existing cgroups fail.
2981 int cgroup_add_cftypes(struct cgroup_subsys
*ss
, struct cftype
*cfts
)
2985 if (!cfts
|| cfts
[0].name
[0] == '\0')
2988 ret
= cgroup_init_cftypes(ss
, cfts
);
2992 mutex_lock(&cgroup_tree_mutex
);
2994 list_add_tail(&cfts
->node
, &ss
->cfts
);
2995 ret
= cgroup_apply_cftypes(cfts
, true);
2997 cgroup_rm_cftypes_locked(cfts
);
2999 mutex_unlock(&cgroup_tree_mutex
);
3004 * cgroup_task_count - count the number of tasks in a cgroup.
3005 * @cgrp: the cgroup in question
3007 * Return the number of tasks in the cgroup.
3009 static int cgroup_task_count(const struct cgroup
*cgrp
)
3012 struct cgrp_cset_link
*link
;
3014 down_read(&css_set_rwsem
);
3015 list_for_each_entry(link
, &cgrp
->cset_links
, cset_link
)
3016 count
+= atomic_read(&link
->cset
->refcount
);
3017 up_read(&css_set_rwsem
);
3022 * css_next_child - find the next child of a given css
3023 * @pos_css: the current position (%NULL to initiate traversal)
3024 * @parent_css: css whose children to walk
3026 * This function returns the next child of @parent_css and should be called
3027 * under either cgroup_mutex or RCU read lock. The only requirement is
3028 * that @parent_css and @pos_css are accessible. The next sibling is
3029 * guaranteed to be returned regardless of their states.
3031 struct cgroup_subsys_state
*
3032 css_next_child(struct cgroup_subsys_state
*pos_css
,
3033 struct cgroup_subsys_state
*parent_css
)
3035 struct cgroup
*pos
= pos_css
? pos_css
->cgroup
: NULL
;
3036 struct cgroup
*cgrp
= parent_css
->cgroup
;
3037 struct cgroup
*next
;
3039 cgroup_assert_mutexes_or_rcu_locked();
3042 * @pos could already have been removed. Once a cgroup is removed,
3043 * its ->sibling.next is no longer updated when its next sibling
3044 * changes. As CGRP_DEAD assertion is serialized and happens
3045 * before the cgroup is taken off the ->sibling list, if we see it
3046 * unasserted, it's guaranteed that the next sibling hasn't
3047 * finished its grace period even if it's already removed, and thus
3048 * safe to dereference from this RCU critical section. If
3049 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
3050 * to be visible as %true here.
3052 * If @pos is dead, its next pointer can't be dereferenced;
3053 * however, as each cgroup is given a monotonically increasing
3054 * unique serial number and always appended to the sibling list,
3055 * the next one can be found by walking the parent's children until
3056 * we see a cgroup with higher serial number than @pos's. While
3057 * this path can be slower, it's taken only when either the current
3058 * cgroup is removed or iteration and removal race.
3061 next
= list_entry_rcu(cgrp
->children
.next
, struct cgroup
, sibling
);
3062 } else if (likely(!cgroup_is_dead(pos
))) {
3063 next
= list_entry_rcu(pos
->sibling
.next
, struct cgroup
, sibling
);
3065 list_for_each_entry_rcu(next
, &cgrp
->children
, sibling
)
3066 if (next
->serial_nr
> pos
->serial_nr
)
3071 * @next, if not pointing to the head, can be dereferenced and is
3072 * the next sibling; however, it might have @ss disabled. If so,
3073 * fast-forward to the next enabled one.
3075 while (&next
->sibling
!= &cgrp
->children
) {
3076 struct cgroup_subsys_state
*next_css
= cgroup_css(next
, parent_css
->ss
);
3080 next
= list_entry_rcu(next
->sibling
.next
, struct cgroup
, sibling
);
3086 * css_next_descendant_pre - find the next descendant for pre-order walk
3087 * @pos: the current position (%NULL to initiate traversal)
3088 * @root: css whose descendants to walk
3090 * To be used by css_for_each_descendant_pre(). Find the next descendant
3091 * to visit for pre-order traversal of @root's descendants. @root is
3092 * included in the iteration and the first node to be visited.
3094 * While this function requires cgroup_mutex or RCU read locking, it
3095 * doesn't require the whole traversal to be contained in a single critical
3096 * section. This function will return the correct next descendant as long
3097 * as both @pos and @root are accessible and @pos is a descendant of @root.
3099 struct cgroup_subsys_state
*
3100 css_next_descendant_pre(struct cgroup_subsys_state
*pos
,
3101 struct cgroup_subsys_state
*root
)
3103 struct cgroup_subsys_state
*next
;
3105 cgroup_assert_mutexes_or_rcu_locked();
3107 /* if first iteration, visit @root */
3111 /* visit the first child if exists */
3112 next
= css_next_child(NULL
, pos
);
3116 /* no child, visit my or the closest ancestor's next sibling */
3117 while (pos
!= root
) {
3118 next
= css_next_child(pos
, css_parent(pos
));
3121 pos
= css_parent(pos
);
3128 * css_rightmost_descendant - return the rightmost descendant of a css
3129 * @pos: css of interest
3131 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3132 * is returned. This can be used during pre-order traversal to skip
3135 * While this function requires cgroup_mutex or RCU read locking, it
3136 * doesn't require the whole traversal to be contained in a single critical
3137 * section. This function will return the correct rightmost descendant as
3138 * long as @pos is accessible.
3140 struct cgroup_subsys_state
*
3141 css_rightmost_descendant(struct cgroup_subsys_state
*pos
)
3143 struct cgroup_subsys_state
*last
, *tmp
;
3145 cgroup_assert_mutexes_or_rcu_locked();
3149 /* ->prev isn't RCU safe, walk ->next till the end */
3151 css_for_each_child(tmp
, last
)
3158 static struct cgroup_subsys_state
*
3159 css_leftmost_descendant(struct cgroup_subsys_state
*pos
)
3161 struct cgroup_subsys_state
*last
;
3165 pos
= css_next_child(NULL
, pos
);
3172 * css_next_descendant_post - find the next descendant for post-order walk
3173 * @pos: the current position (%NULL to initiate traversal)
3174 * @root: css whose descendants to walk
3176 * To be used by css_for_each_descendant_post(). Find the next descendant
3177 * to visit for post-order traversal of @root's descendants. @root is
3178 * included in the iteration and the last node to be visited.
3180 * While this function requires cgroup_mutex or RCU read locking, it
3181 * doesn't require the whole traversal to be contained in a single critical
3182 * section. This function will return the correct next descendant as long
3183 * as both @pos and @cgroup are accessible and @pos is a descendant of
3186 struct cgroup_subsys_state
*
3187 css_next_descendant_post(struct cgroup_subsys_state
*pos
,
3188 struct cgroup_subsys_state
*root
)
3190 struct cgroup_subsys_state
*next
;
3192 cgroup_assert_mutexes_or_rcu_locked();
3194 /* if first iteration, visit leftmost descendant which may be @root */
3196 return css_leftmost_descendant(root
);
3198 /* if we visited @root, we're done */
3202 /* if there's an unvisited sibling, visit its leftmost descendant */
3203 next
= css_next_child(pos
, css_parent(pos
));
3205 return css_leftmost_descendant(next
);
3207 /* no sibling left, visit parent */
3208 return css_parent(pos
);
3212 * css_advance_task_iter - advance a task itererator to the next css_set
3213 * @it: the iterator to advance
3215 * Advance @it to the next css_set to walk.
3217 static void css_advance_task_iter(struct css_task_iter
*it
)
3219 struct list_head
*l
= it
->cset_pos
;
3220 struct cgrp_cset_link
*link
;
3221 struct css_set
*cset
;
3223 /* Advance to the next non-empty css_set */
3226 if (l
== it
->cset_head
) {
3227 it
->cset_pos
= NULL
;
3232 cset
= container_of(l
, struct css_set
,
3233 e_cset_node
[it
->ss
->id
]);
3235 link
= list_entry(l
, struct cgrp_cset_link
, cset_link
);
3238 } while (list_empty(&cset
->tasks
) && list_empty(&cset
->mg_tasks
));
3242 if (!list_empty(&cset
->tasks
))
3243 it
->task_pos
= cset
->tasks
.next
;
3245 it
->task_pos
= cset
->mg_tasks
.next
;
3247 it
->tasks_head
= &cset
->tasks
;
3248 it
->mg_tasks_head
= &cset
->mg_tasks
;
3252 * css_task_iter_start - initiate task iteration
3253 * @css: the css to walk tasks of
3254 * @it: the task iterator to use
3256 * Initiate iteration through the tasks of @css. The caller can call
3257 * css_task_iter_next() to walk through the tasks until the function
3258 * returns NULL. On completion of iteration, css_task_iter_end() must be
3261 * Note that this function acquires a lock which is released when the
3262 * iteration finishes. The caller can't sleep while iteration is in
3265 void css_task_iter_start(struct cgroup_subsys_state
*css
,
3266 struct css_task_iter
*it
)
3267 __acquires(css_set_rwsem
)
3269 /* no one should try to iterate before mounting cgroups */
3270 WARN_ON_ONCE(!use_task_css_set_links
);
3272 down_read(&css_set_rwsem
);
3277 it
->cset_pos
= &css
->cgroup
->e_csets
[css
->ss
->id
];
3279 it
->cset_pos
= &css
->cgroup
->cset_links
;
3281 it
->cset_head
= it
->cset_pos
;
3283 css_advance_task_iter(it
);
3287 * css_task_iter_next - return the next task for the iterator
3288 * @it: the task iterator being iterated
3290 * The "next" function for task iteration. @it should have been
3291 * initialized via css_task_iter_start(). Returns NULL when the iteration
3294 struct task_struct
*css_task_iter_next(struct css_task_iter
*it
)
3296 struct task_struct
*res
;
3297 struct list_head
*l
= it
->task_pos
;
3299 /* If the iterator cg is NULL, we have no tasks */
3302 res
= list_entry(l
, struct task_struct
, cg_list
);
3305 * Advance iterator to find next entry. cset->tasks is consumed
3306 * first and then ->mg_tasks. After ->mg_tasks, we move onto the
3311 if (l
== it
->tasks_head
)
3312 l
= it
->mg_tasks_head
->next
;
3314 if (l
== it
->mg_tasks_head
)
3315 css_advance_task_iter(it
);
3323 * css_task_iter_end - finish task iteration
3324 * @it: the task iterator to finish
3326 * Finish task iteration started by css_task_iter_start().
3328 void css_task_iter_end(struct css_task_iter
*it
)
3329 __releases(css_set_rwsem
)
3331 up_read(&css_set_rwsem
);
3335 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3336 * @to: cgroup to which the tasks will be moved
3337 * @from: cgroup in which the tasks currently reside
3339 * Locking rules between cgroup_post_fork() and the migration path
3340 * guarantee that, if a task is forking while being migrated, the new child
3341 * is guaranteed to be either visible in the source cgroup after the
3342 * parent's migration is complete or put into the target cgroup. No task
3343 * can slip out of migration through forking.
3345 int cgroup_transfer_tasks(struct cgroup
*to
, struct cgroup
*from
)
3347 LIST_HEAD(preloaded_csets
);
3348 struct cgrp_cset_link
*link
;
3349 struct css_task_iter it
;
3350 struct task_struct
*task
;
3353 mutex_lock(&cgroup_mutex
);
3355 /* all tasks in @from are being moved, all csets are source */
3356 down_read(&css_set_rwsem
);
3357 list_for_each_entry(link
, &from
->cset_links
, cset_link
)
3358 cgroup_migrate_add_src(link
->cset
, to
, &preloaded_csets
);
3359 up_read(&css_set_rwsem
);
3361 ret
= cgroup_migrate_prepare_dst(to
, &preloaded_csets
);
3366 * Migrate tasks one-by-one until @form is empty. This fails iff
3367 * ->can_attach() fails.
3370 css_task_iter_start(&from
->dummy_css
, &it
);
3371 task
= css_task_iter_next(&it
);
3373 get_task_struct(task
);
3374 css_task_iter_end(&it
);
3377 ret
= cgroup_migrate(to
, task
, false);
3378 put_task_struct(task
);
3380 } while (task
&& !ret
);
3382 cgroup_migrate_finish(&preloaded_csets
);
3383 mutex_unlock(&cgroup_mutex
);
3388 * Stuff for reading the 'tasks'/'procs' files.
3390 * Reading this file can return large amounts of data if a cgroup has
3391 * *lots* of attached tasks. So it may need several calls to read(),
3392 * but we cannot guarantee that the information we produce is correct
3393 * unless we produce it entirely atomically.
3397 /* which pidlist file are we talking about? */
3398 enum cgroup_filetype
{
3404 * A pidlist is a list of pids that virtually represents the contents of one
3405 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3406 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3409 struct cgroup_pidlist
{
3411 * used to find which pidlist is wanted. doesn't change as long as
3412 * this particular list stays in the list.
3414 struct { enum cgroup_filetype type
; struct pid_namespace
*ns
; } key
;
3417 /* how many elements the above list has */
3419 /* each of these stored in a list by its cgroup */
3420 struct list_head links
;
3421 /* pointer to the cgroup we belong to, for list removal purposes */
3422 struct cgroup
*owner
;
3423 /* for delayed destruction */
3424 struct delayed_work destroy_dwork
;
3428 * The following two functions "fix" the issue where there are more pids
3429 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3430 * TODO: replace with a kernel-wide solution to this problem
3432 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3433 static void *pidlist_allocate(int count
)
3435 if (PIDLIST_TOO_LARGE(count
))
3436 return vmalloc(count
* sizeof(pid_t
));
3438 return kmalloc(count
* sizeof(pid_t
), GFP_KERNEL
);
3441 static void pidlist_free(void *p
)
3443 if (is_vmalloc_addr(p
))
3450 * Used to destroy all pidlists lingering waiting for destroy timer. None
3451 * should be left afterwards.
3453 static void cgroup_pidlist_destroy_all(struct cgroup
*cgrp
)
3455 struct cgroup_pidlist
*l
, *tmp_l
;
3457 mutex_lock(&cgrp
->pidlist_mutex
);
3458 list_for_each_entry_safe(l
, tmp_l
, &cgrp
->pidlists
, links
)
3459 mod_delayed_work(cgroup_pidlist_destroy_wq
, &l
->destroy_dwork
, 0);
3460 mutex_unlock(&cgrp
->pidlist_mutex
);
3462 flush_workqueue(cgroup_pidlist_destroy_wq
);
3463 BUG_ON(!list_empty(&cgrp
->pidlists
));
3466 static void cgroup_pidlist_destroy_work_fn(struct work_struct
*work
)
3468 struct delayed_work
*dwork
= to_delayed_work(work
);
3469 struct cgroup_pidlist
*l
= container_of(dwork
, struct cgroup_pidlist
,
3471 struct cgroup_pidlist
*tofree
= NULL
;
3473 mutex_lock(&l
->owner
->pidlist_mutex
);
3476 * Destroy iff we didn't get queued again. The state won't change
3477 * as destroy_dwork can only be queued while locked.
3479 if (!delayed_work_pending(dwork
)) {
3480 list_del(&l
->links
);
3481 pidlist_free(l
->list
);
3482 put_pid_ns(l
->key
.ns
);
3486 mutex_unlock(&l
->owner
->pidlist_mutex
);
3491 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3492 * Returns the number of unique elements.
3494 static int pidlist_uniq(pid_t
*list
, int length
)
3499 * we presume the 0th element is unique, so i starts at 1. trivial
3500 * edge cases first; no work needs to be done for either
3502 if (length
== 0 || length
== 1)
3504 /* src and dest walk down the list; dest counts unique elements */
3505 for (src
= 1; src
< length
; src
++) {
3506 /* find next unique element */
3507 while (list
[src
] == list
[src
-1]) {
3512 /* dest always points to where the next unique element goes */
3513 list
[dest
] = list
[src
];
3521 * The two pid files - task and cgroup.procs - guaranteed that the result
3522 * is sorted, which forced this whole pidlist fiasco. As pid order is
3523 * different per namespace, each namespace needs differently sorted list,
3524 * making it impossible to use, for example, single rbtree of member tasks
3525 * sorted by task pointer. As pidlists can be fairly large, allocating one
3526 * per open file is dangerous, so cgroup had to implement shared pool of
3527 * pidlists keyed by cgroup and namespace.
3529 * All this extra complexity was caused by the original implementation
3530 * committing to an entirely unnecessary property. In the long term, we
3531 * want to do away with it. Explicitly scramble sort order if
3532 * sane_behavior so that no such expectation exists in the new interface.
3534 * Scrambling is done by swapping every two consecutive bits, which is
3535 * non-identity one-to-one mapping which disturbs sort order sufficiently.
3537 static pid_t
pid_fry(pid_t pid
)
3539 unsigned a
= pid
& 0x55555555;
3540 unsigned b
= pid
& 0xAAAAAAAA;
3542 return (a
<< 1) | (b
>> 1);
3545 static pid_t
cgroup_pid_fry(struct cgroup
*cgrp
, pid_t pid
)
3547 if (cgroup_sane_behavior(cgrp
))
3548 return pid_fry(pid
);
3553 static int cmppid(const void *a
, const void *b
)
3555 return *(pid_t
*)a
- *(pid_t
*)b
;
3558 static int fried_cmppid(const void *a
, const void *b
)
3560 return pid_fry(*(pid_t
*)a
) - pid_fry(*(pid_t
*)b
);
3563 static struct cgroup_pidlist
*cgroup_pidlist_find(struct cgroup
*cgrp
,
3564 enum cgroup_filetype type
)
3566 struct cgroup_pidlist
*l
;
3567 /* don't need task_nsproxy() if we're looking at ourself */
3568 struct pid_namespace
*ns
= task_active_pid_ns(current
);
3570 lockdep_assert_held(&cgrp
->pidlist_mutex
);
3572 list_for_each_entry(l
, &cgrp
->pidlists
, links
)
3573 if (l
->key
.type
== type
&& l
->key
.ns
== ns
)
3579 * find the appropriate pidlist for our purpose (given procs vs tasks)
3580 * returns with the lock on that pidlist already held, and takes care
3581 * of the use count, or returns NULL with no locks held if we're out of
3584 static struct cgroup_pidlist
*cgroup_pidlist_find_create(struct cgroup
*cgrp
,
3585 enum cgroup_filetype type
)
3587 struct cgroup_pidlist
*l
;
3589 lockdep_assert_held(&cgrp
->pidlist_mutex
);
3591 l
= cgroup_pidlist_find(cgrp
, type
);
3595 /* entry not found; create a new one */
3596 l
= kzalloc(sizeof(struct cgroup_pidlist
), GFP_KERNEL
);
3600 INIT_DELAYED_WORK(&l
->destroy_dwork
, cgroup_pidlist_destroy_work_fn
);
3602 /* don't need task_nsproxy() if we're looking at ourself */
3603 l
->key
.ns
= get_pid_ns(task_active_pid_ns(current
));
3605 list_add(&l
->links
, &cgrp
->pidlists
);
3610 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3612 static int pidlist_array_load(struct cgroup
*cgrp
, enum cgroup_filetype type
,
3613 struct cgroup_pidlist
**lp
)
3617 int pid
, n
= 0; /* used for populating the array */
3618 struct css_task_iter it
;
3619 struct task_struct
*tsk
;
3620 struct cgroup_pidlist
*l
;
3622 lockdep_assert_held(&cgrp
->pidlist_mutex
);
3625 * If cgroup gets more users after we read count, we won't have
3626 * enough space - tough. This race is indistinguishable to the
3627 * caller from the case that the additional cgroup users didn't
3628 * show up until sometime later on.
3630 length
= cgroup_task_count(cgrp
);
3631 array
= pidlist_allocate(length
);
3634 /* now, populate the array */
3635 css_task_iter_start(&cgrp
->dummy_css
, &it
);
3636 while ((tsk
= css_task_iter_next(&it
))) {
3637 if (unlikely(n
== length
))
3639 /* get tgid or pid for procs or tasks file respectively */
3640 if (type
== CGROUP_FILE_PROCS
)
3641 pid
= task_tgid_vnr(tsk
);
3643 pid
= task_pid_vnr(tsk
);
3644 if (pid
> 0) /* make sure to only use valid results */
3647 css_task_iter_end(&it
);
3649 /* now sort & (if procs) strip out duplicates */
3650 if (cgroup_sane_behavior(cgrp
))
3651 sort(array
, length
, sizeof(pid_t
), fried_cmppid
, NULL
);
3653 sort(array
, length
, sizeof(pid_t
), cmppid
, NULL
);
3654 if (type
== CGROUP_FILE_PROCS
)
3655 length
= pidlist_uniq(array
, length
);
3657 l
= cgroup_pidlist_find_create(cgrp
, type
);
3659 mutex_unlock(&cgrp
->pidlist_mutex
);
3660 pidlist_free(array
);
3664 /* store array, freeing old if necessary */
3665 pidlist_free(l
->list
);
3673 * cgroupstats_build - build and fill cgroupstats
3674 * @stats: cgroupstats to fill information into
3675 * @dentry: A dentry entry belonging to the cgroup for which stats have
3678 * Build and fill cgroupstats so that taskstats can export it to user
3681 int cgroupstats_build(struct cgroupstats
*stats
, struct dentry
*dentry
)
3683 struct kernfs_node
*kn
= kernfs_node_from_dentry(dentry
);
3684 struct cgroup
*cgrp
;
3685 struct css_task_iter it
;
3686 struct task_struct
*tsk
;
3688 /* it should be kernfs_node belonging to cgroupfs and is a directory */
3689 if (dentry
->d_sb
->s_type
!= &cgroup_fs_type
|| !kn
||
3690 kernfs_type(kn
) != KERNFS_DIR
)
3693 mutex_lock(&cgroup_mutex
);
3696 * We aren't being called from kernfs and there's no guarantee on
3697 * @kn->priv's validity. For this and css_tryget_from_dir(),
3698 * @kn->priv is RCU safe. Let's do the RCU dancing.
3701 cgrp
= rcu_dereference(kn
->priv
);
3702 if (!cgrp
|| cgroup_is_dead(cgrp
)) {
3704 mutex_unlock(&cgroup_mutex
);
3709 css_task_iter_start(&cgrp
->dummy_css
, &it
);
3710 while ((tsk
= css_task_iter_next(&it
))) {
3711 switch (tsk
->state
) {
3713 stats
->nr_running
++;
3715 case TASK_INTERRUPTIBLE
:
3716 stats
->nr_sleeping
++;
3718 case TASK_UNINTERRUPTIBLE
:
3719 stats
->nr_uninterruptible
++;
3722 stats
->nr_stopped
++;
3725 if (delayacct_is_task_waiting_on_io(tsk
))
3726 stats
->nr_io_wait
++;
3730 css_task_iter_end(&it
);
3732 mutex_unlock(&cgroup_mutex
);
3738 * seq_file methods for the tasks/procs files. The seq_file position is the
3739 * next pid to display; the seq_file iterator is a pointer to the pid
3740 * in the cgroup->l->list array.
3743 static void *cgroup_pidlist_start(struct seq_file
*s
, loff_t
*pos
)
3746 * Initially we receive a position value that corresponds to
3747 * one more than the last pid shown (or 0 on the first call or
3748 * after a seek to the start). Use a binary-search to find the
3749 * next pid to display, if any
3751 struct kernfs_open_file
*of
= s
->private;
3752 struct cgroup
*cgrp
= seq_css(s
)->cgroup
;
3753 struct cgroup_pidlist
*l
;
3754 enum cgroup_filetype type
= seq_cft(s
)->private;
3755 int index
= 0, pid
= *pos
;
3758 mutex_lock(&cgrp
->pidlist_mutex
);
3761 * !NULL @of->priv indicates that this isn't the first start()
3762 * after open. If the matching pidlist is around, we can use that.
3763 * Look for it. Note that @of->priv can't be used directly. It
3764 * could already have been destroyed.
3767 of
->priv
= cgroup_pidlist_find(cgrp
, type
);
3770 * Either this is the first start() after open or the matching
3771 * pidlist has been destroyed inbetween. Create a new one.
3774 ret
= pidlist_array_load(cgrp
, type
,
3775 (struct cgroup_pidlist
**)&of
->priv
);
3777 return ERR_PTR(ret
);
3782 int end
= l
->length
;
3784 while (index
< end
) {
3785 int mid
= (index
+ end
) / 2;
3786 if (cgroup_pid_fry(cgrp
, l
->list
[mid
]) == pid
) {
3789 } else if (cgroup_pid_fry(cgrp
, l
->list
[mid
]) <= pid
)
3795 /* If we're off the end of the array, we're done */
3796 if (index
>= l
->length
)
3798 /* Update the abstract position to be the actual pid that we found */
3799 iter
= l
->list
+ index
;
3800 *pos
= cgroup_pid_fry(cgrp
, *iter
);
3804 static void cgroup_pidlist_stop(struct seq_file
*s
, void *v
)
3806 struct kernfs_open_file
*of
= s
->private;
3807 struct cgroup_pidlist
*l
= of
->priv
;
3810 mod_delayed_work(cgroup_pidlist_destroy_wq
, &l
->destroy_dwork
,
3811 CGROUP_PIDLIST_DESTROY_DELAY
);
3812 mutex_unlock(&seq_css(s
)->cgroup
->pidlist_mutex
);
3815 static void *cgroup_pidlist_next(struct seq_file
*s
, void *v
, loff_t
*pos
)
3817 struct kernfs_open_file
*of
= s
->private;
3818 struct cgroup_pidlist
*l
= of
->priv
;
3820 pid_t
*end
= l
->list
+ l
->length
;
3822 * Advance to the next pid in the array. If this goes off the
3829 *pos
= cgroup_pid_fry(seq_css(s
)->cgroup
, *p
);
3834 static int cgroup_pidlist_show(struct seq_file
*s
, void *v
)
3836 return seq_printf(s
, "%d\n", *(int *)v
);
3840 * seq_operations functions for iterating on pidlists through seq_file -
3841 * independent of whether it's tasks or procs
3843 static const struct seq_operations cgroup_pidlist_seq_operations
= {
3844 .start
= cgroup_pidlist_start
,
3845 .stop
= cgroup_pidlist_stop
,
3846 .next
= cgroup_pidlist_next
,
3847 .show
= cgroup_pidlist_show
,
3850 static u64
cgroup_read_notify_on_release(struct cgroup_subsys_state
*css
,
3853 return notify_on_release(css
->cgroup
);
3856 static int cgroup_write_notify_on_release(struct cgroup_subsys_state
*css
,
3857 struct cftype
*cft
, u64 val
)
3859 clear_bit(CGRP_RELEASABLE
, &css
->cgroup
->flags
);
3861 set_bit(CGRP_NOTIFY_ON_RELEASE
, &css
->cgroup
->flags
);
3863 clear_bit(CGRP_NOTIFY_ON_RELEASE
, &css
->cgroup
->flags
);
3867 static u64
cgroup_clone_children_read(struct cgroup_subsys_state
*css
,
3870 return test_bit(CGRP_CPUSET_CLONE_CHILDREN
, &css
->cgroup
->flags
);
3873 static int cgroup_clone_children_write(struct cgroup_subsys_state
*css
,
3874 struct cftype
*cft
, u64 val
)
3877 set_bit(CGRP_CPUSET_CLONE_CHILDREN
, &css
->cgroup
->flags
);
3879 clear_bit(CGRP_CPUSET_CLONE_CHILDREN
, &css
->cgroup
->flags
);
3883 static struct cftype cgroup_base_files
[] = {
3885 .name
= "cgroup.procs",
3886 .seq_start
= cgroup_pidlist_start
,
3887 .seq_next
= cgroup_pidlist_next
,
3888 .seq_stop
= cgroup_pidlist_stop
,
3889 .seq_show
= cgroup_pidlist_show
,
3890 .private = CGROUP_FILE_PROCS
,
3891 .write_u64
= cgroup_procs_write
,
3892 .mode
= S_IRUGO
| S_IWUSR
,
3895 .name
= "cgroup.clone_children",
3896 .flags
= CFTYPE_INSANE
,
3897 .read_u64
= cgroup_clone_children_read
,
3898 .write_u64
= cgroup_clone_children_write
,
3901 .name
= "cgroup.sane_behavior",
3902 .flags
= CFTYPE_ONLY_ON_ROOT
,
3903 .seq_show
= cgroup_sane_behavior_show
,
3906 .name
= "cgroup.controllers",
3907 .flags
= CFTYPE_ONLY_ON_DFL
| CFTYPE_ONLY_ON_ROOT
,
3908 .seq_show
= cgroup_root_controllers_show
,
3911 .name
= "cgroup.controllers",
3912 .flags
= CFTYPE_ONLY_ON_DFL
| CFTYPE_NOT_ON_ROOT
,
3913 .seq_show
= cgroup_controllers_show
,
3916 .name
= "cgroup.subtree_control",
3917 .flags
= CFTYPE_ONLY_ON_DFL
,
3918 .seq_show
= cgroup_subtree_control_show
,
3919 .write_string
= cgroup_subtree_control_write
,
3923 * Historical crazy stuff. These don't have "cgroup." prefix and
3924 * don't exist if sane_behavior. If you're depending on these, be
3925 * prepared to be burned.
3929 .flags
= CFTYPE_INSANE
, /* use "procs" instead */
3930 .seq_start
= cgroup_pidlist_start
,
3931 .seq_next
= cgroup_pidlist_next
,
3932 .seq_stop
= cgroup_pidlist_stop
,
3933 .seq_show
= cgroup_pidlist_show
,
3934 .private = CGROUP_FILE_TASKS
,
3935 .write_u64
= cgroup_tasks_write
,
3936 .mode
= S_IRUGO
| S_IWUSR
,
3939 .name
= "notify_on_release",
3940 .flags
= CFTYPE_INSANE
,
3941 .read_u64
= cgroup_read_notify_on_release
,
3942 .write_u64
= cgroup_write_notify_on_release
,
3945 .name
= "release_agent",
3946 .flags
= CFTYPE_INSANE
| CFTYPE_ONLY_ON_ROOT
,
3947 .seq_show
= cgroup_release_agent_show
,
3948 .write_string
= cgroup_release_agent_write
,
3949 .max_write_len
= PATH_MAX
- 1,
3955 * cgroup_populate_dir - create subsys files in a cgroup directory
3956 * @cgrp: target cgroup
3957 * @subsys_mask: mask of the subsystem ids whose files should be added
3959 * On failure, no file is added.
3961 static int cgroup_populate_dir(struct cgroup
*cgrp
, unsigned long subsys_mask
)
3963 struct cgroup_subsys
*ss
;
3966 /* process cftsets of each subsystem */
3967 for_each_subsys(ss
, i
) {
3968 struct cftype
*cfts
;
3970 if (!test_bit(i
, &subsys_mask
))
3973 list_for_each_entry(cfts
, &ss
->cfts
, node
) {
3974 ret
= cgroup_addrm_files(cgrp
, cfts
, true);
3981 cgroup_clear_dir(cgrp
, subsys_mask
);
3986 * css destruction is four-stage process.
3988 * 1. Destruction starts. Killing of the percpu_ref is initiated.
3989 * Implemented in kill_css().
3991 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
3992 * and thus css_tryget() is guaranteed to fail, the css can be offlined
3993 * by invoking offline_css(). After offlining, the base ref is put.
3994 * Implemented in css_killed_work_fn().
3996 * 3. When the percpu_ref reaches zero, the only possible remaining
3997 * accessors are inside RCU read sections. css_release() schedules the
4000 * 4. After the grace period, the css can be freed. Implemented in
4001 * css_free_work_fn().
4003 * It is actually hairier because both step 2 and 4 require process context
4004 * and thus involve punting to css->destroy_work adding two additional
4005 * steps to the already complex sequence.
4007 static void css_free_work_fn(struct work_struct
*work
)
4009 struct cgroup_subsys_state
*css
=
4010 container_of(work
, struct cgroup_subsys_state
, destroy_work
);
4011 struct cgroup
*cgrp
= css
->cgroup
;
4014 css_put(css
->parent
);
4016 css
->ss
->css_free(css
);
4020 static void css_free_rcu_fn(struct rcu_head
*rcu_head
)
4022 struct cgroup_subsys_state
*css
=
4023 container_of(rcu_head
, struct cgroup_subsys_state
, rcu_head
);
4025 INIT_WORK(&css
->destroy_work
, css_free_work_fn
);
4026 queue_work(cgroup_destroy_wq
, &css
->destroy_work
);
4029 static void css_release(struct percpu_ref
*ref
)
4031 struct cgroup_subsys_state
*css
=
4032 container_of(ref
, struct cgroup_subsys_state
, refcnt
);
4034 RCU_INIT_POINTER(css
->cgroup
->subsys
[css
->ss
->id
], NULL
);
4035 call_rcu(&css
->rcu_head
, css_free_rcu_fn
);
4038 static void init_css(struct cgroup_subsys_state
*css
, struct cgroup_subsys
*ss
,
4039 struct cgroup
*cgrp
)
4046 css
->parent
= cgroup_css(cgrp
->parent
, ss
);
4048 css
->flags
|= CSS_ROOT
;
4050 BUG_ON(cgroup_css(cgrp
, ss
));
4053 /* invoke ->css_online() on a new CSS and mark it online if successful */
4054 static int online_css(struct cgroup_subsys_state
*css
)
4056 struct cgroup_subsys
*ss
= css
->ss
;
4059 lockdep_assert_held(&cgroup_tree_mutex
);
4060 lockdep_assert_held(&cgroup_mutex
);
4063 ret
= ss
->css_online(css
);
4065 css
->flags
|= CSS_ONLINE
;
4066 css
->cgroup
->nr_css
++;
4067 rcu_assign_pointer(css
->cgroup
->subsys
[ss
->id
], css
);
4072 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4073 static void offline_css(struct cgroup_subsys_state
*css
)
4075 struct cgroup_subsys
*ss
= css
->ss
;
4077 lockdep_assert_held(&cgroup_tree_mutex
);
4078 lockdep_assert_held(&cgroup_mutex
);
4080 if (!(css
->flags
& CSS_ONLINE
))
4083 if (ss
->css_offline
)
4084 ss
->css_offline(css
);
4086 css
->flags
&= ~CSS_ONLINE
;
4087 css
->cgroup
->nr_css
--;
4088 RCU_INIT_POINTER(css
->cgroup
->subsys
[ss
->id
], NULL
);
4090 wake_up_all(&css
->cgroup
->offline_waitq
);
4094 * create_css - create a cgroup_subsys_state
4095 * @cgrp: the cgroup new css will be associated with
4096 * @ss: the subsys of new css
4098 * Create a new css associated with @cgrp - @ss pair. On success, the new
4099 * css is online and installed in @cgrp with all interface files created.
4100 * Returns 0 on success, -errno on failure.
4102 static int create_css(struct cgroup
*cgrp
, struct cgroup_subsys
*ss
)
4104 struct cgroup
*parent
= cgrp
->parent
;
4105 struct cgroup_subsys_state
*css
;
4108 lockdep_assert_held(&cgroup_mutex
);
4110 css
= ss
->css_alloc(cgroup_css(parent
, ss
));
4112 return PTR_ERR(css
);
4114 err
= percpu_ref_init(&css
->refcnt
, css_release
);
4118 init_css(css
, ss
, cgrp
);
4120 err
= cgroup_populate_dir(cgrp
, 1 << ss
->id
);
4122 goto err_free_percpu_ref
;
4124 err
= online_css(css
);
4129 css_get(css
->parent
);
4131 if (ss
->broken_hierarchy
&& !ss
->warned_broken_hierarchy
&&
4133 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",
4134 current
->comm
, current
->pid
, ss
->name
);
4135 if (!strcmp(ss
->name
, "memory"))
4136 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4137 ss
->warned_broken_hierarchy
= true;
4143 cgroup_clear_dir(css
->cgroup
, 1 << css
->ss
->id
);
4144 err_free_percpu_ref
:
4145 percpu_ref_cancel_init(&css
->refcnt
);
4152 * cgroup_create - create a cgroup
4153 * @parent: cgroup that will be parent of the new cgroup
4154 * @name: name of the new cgroup
4155 * @mode: mode to set on new cgroup
4157 static long cgroup_create(struct cgroup
*parent
, const char *name
,
4160 struct cgroup
*cgrp
;
4161 struct cgroup_root
*root
= parent
->root
;
4163 struct cgroup_subsys
*ss
;
4164 struct kernfs_node
*kn
;
4166 /* allocate the cgroup and its ID, 0 is reserved for the root */
4167 cgrp
= kzalloc(sizeof(*cgrp
), GFP_KERNEL
);
4171 mutex_lock(&cgroup_tree_mutex
);
4174 * Only live parents can have children. Note that the liveliness
4175 * check isn't strictly necessary because cgroup_mkdir() and
4176 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4177 * anyway so that locking is contained inside cgroup proper and we
4178 * don't get nasty surprises if we ever grow another caller.
4180 if (!cgroup_lock_live_group(parent
)) {
4182 goto err_unlock_tree
;
4186 * Temporarily set the pointer to NULL, so idr_find() won't return
4187 * a half-baked cgroup.
4189 cgrp
->id
= idr_alloc(&root
->cgroup_idr
, NULL
, 1, 0, GFP_KERNEL
);
4195 init_cgroup_housekeeping(cgrp
);
4197 cgrp
->parent
= parent
;
4198 cgrp
->dummy_css
.parent
= &parent
->dummy_css
;
4199 cgrp
->root
= parent
->root
;
4201 if (notify_on_release(parent
))
4202 set_bit(CGRP_NOTIFY_ON_RELEASE
, &cgrp
->flags
);
4204 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN
, &parent
->flags
))
4205 set_bit(CGRP_CPUSET_CLONE_CHILDREN
, &cgrp
->flags
);
4207 /* create the directory */
4208 kn
= kernfs_create_dir(parent
->kn
, name
, mode
, cgrp
);
4216 * This extra ref will be put in cgroup_free_fn() and guarantees
4217 * that @cgrp->kn is always accessible.
4221 cgrp
->serial_nr
= cgroup_serial_nr_next
++;
4223 /* allocation complete, commit to creation */
4224 list_add_tail_rcu(&cgrp
->sibling
, &cgrp
->parent
->children
);
4225 atomic_inc(&root
->nr_cgrps
);
4229 * @cgrp is now fully operational. If something fails after this
4230 * point, it'll be released via the normal destruction path.
4232 idr_replace(&root
->cgroup_idr
, cgrp
, cgrp
->id
);
4234 err
= cgroup_kn_set_ugid(kn
);
4238 err
= cgroup_addrm_files(cgrp
, cgroup_base_files
, true);
4242 /* let's create and online css's */
4243 for_each_subsys(ss
, ssid
) {
4244 if (parent
->child_subsys_mask
& (1 << ssid
)) {
4245 err
= create_css(cgrp
, ss
);
4252 * On the default hierarchy, a child doesn't automatically inherit
4253 * child_subsys_mask from the parent. Each is configured manually.
4255 if (!cgroup_on_dfl(cgrp
))
4256 cgrp
->child_subsys_mask
= parent
->child_subsys_mask
;
4258 kernfs_activate(kn
);
4260 mutex_unlock(&cgroup_mutex
);
4261 mutex_unlock(&cgroup_tree_mutex
);
4266 idr_remove(&root
->cgroup_idr
, cgrp
->id
);
4268 mutex_unlock(&cgroup_mutex
);
4270 mutex_unlock(&cgroup_tree_mutex
);
4275 cgroup_destroy_locked(cgrp
);
4276 mutex_unlock(&cgroup_mutex
);
4277 mutex_unlock(&cgroup_tree_mutex
);
4281 static int cgroup_mkdir(struct kernfs_node
*parent_kn
, const char *name
,
4284 struct cgroup
*parent
= parent_kn
->priv
;
4288 * cgroup_create() grabs cgroup_tree_mutex which nests outside
4289 * kernfs active_ref and cgroup_create() already synchronizes
4290 * properly against removal through cgroup_lock_live_group().
4291 * Break it before calling cgroup_create().
4294 kernfs_break_active_protection(parent_kn
);
4296 ret
= cgroup_create(parent
, name
, mode
);
4298 kernfs_unbreak_active_protection(parent_kn
);
4304 * This is called when the refcnt of a css is confirmed to be killed.
4305 * css_tryget() is now guaranteed to fail.
4307 static void css_killed_work_fn(struct work_struct
*work
)
4309 struct cgroup_subsys_state
*css
=
4310 container_of(work
, struct cgroup_subsys_state
, destroy_work
);
4311 struct cgroup
*cgrp
= css
->cgroup
;
4313 mutex_lock(&cgroup_tree_mutex
);
4314 mutex_lock(&cgroup_mutex
);
4317 * css_tryget() is guaranteed to fail now. Tell subsystems to
4318 * initate destruction.
4323 * If @cgrp is marked dead, it's waiting for refs of all css's to
4324 * be disabled before proceeding to the second phase of cgroup
4325 * destruction. If we are the last one, kick it off.
4327 if (!cgrp
->nr_css
&& cgroup_is_dead(cgrp
))
4328 cgroup_destroy_css_killed(cgrp
);
4330 mutex_unlock(&cgroup_mutex
);
4331 mutex_unlock(&cgroup_tree_mutex
);
4334 * Put the css refs from kill_css(). Each css holds an extra
4335 * reference to the cgroup's dentry and cgroup removal proceeds
4336 * regardless of css refs. On the last put of each css, whenever
4337 * that may be, the extra dentry ref is put so that dentry
4338 * destruction happens only after all css's are released.
4343 /* css kill confirmation processing requires process context, bounce */
4344 static void css_killed_ref_fn(struct percpu_ref
*ref
)
4346 struct cgroup_subsys_state
*css
=
4347 container_of(ref
, struct cgroup_subsys_state
, refcnt
);
4349 INIT_WORK(&css
->destroy_work
, css_killed_work_fn
);
4350 queue_work(cgroup_destroy_wq
, &css
->destroy_work
);
4354 * kill_css - destroy a css
4355 * @css: css to destroy
4357 * This function initiates destruction of @css by removing cgroup interface
4358 * files and putting its base reference. ->css_offline() will be invoked
4359 * asynchronously once css_tryget() is guaranteed to fail and when the
4360 * reference count reaches zero, @css will be released.
4362 static void kill_css(struct cgroup_subsys_state
*css
)
4364 lockdep_assert_held(&cgroup_tree_mutex
);
4367 * This must happen before css is disassociated with its cgroup.
4368 * See seq_css() for details.
4370 cgroup_clear_dir(css
->cgroup
, 1 << css
->ss
->id
);
4373 * Killing would put the base ref, but we need to keep it alive
4374 * until after ->css_offline().
4379 * cgroup core guarantees that, by the time ->css_offline() is
4380 * invoked, no new css reference will be given out via
4381 * css_tryget(). We can't simply call percpu_ref_kill() and
4382 * proceed to offlining css's because percpu_ref_kill() doesn't
4383 * guarantee that the ref is seen as killed on all CPUs on return.
4385 * Use percpu_ref_kill_and_confirm() to get notifications as each
4386 * css is confirmed to be seen as killed on all CPUs.
4388 percpu_ref_kill_and_confirm(&css
->refcnt
, css_killed_ref_fn
);
4392 * cgroup_destroy_locked - the first stage of cgroup destruction
4393 * @cgrp: cgroup to be destroyed
4395 * css's make use of percpu refcnts whose killing latency shouldn't be
4396 * exposed to userland and are RCU protected. Also, cgroup core needs to
4397 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
4398 * invoked. To satisfy all the requirements, destruction is implemented in
4399 * the following two steps.
4401 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4402 * userland visible parts and start killing the percpu refcnts of
4403 * css's. Set up so that the next stage will be kicked off once all
4404 * the percpu refcnts are confirmed to be killed.
4406 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4407 * rest of destruction. Once all cgroup references are gone, the
4408 * cgroup is RCU-freed.
4410 * This function implements s1. After this step, @cgrp is gone as far as
4411 * the userland is concerned and a new cgroup with the same name may be
4412 * created. As cgroup doesn't care about the names internally, this
4413 * doesn't cause any problem.
4415 static int cgroup_destroy_locked(struct cgroup
*cgrp
)
4416 __releases(&cgroup_mutex
) __acquires(&cgroup_mutex
)
4418 struct cgroup
*child
;
4419 struct cgroup_subsys_state
*css
;
4423 lockdep_assert_held(&cgroup_tree_mutex
);
4424 lockdep_assert_held(&cgroup_mutex
);
4427 * css_set_rwsem synchronizes access to ->cset_links and prevents
4428 * @cgrp from being removed while put_css_set() is in progress.
4430 down_read(&css_set_rwsem
);
4431 empty
= list_empty(&cgrp
->cset_links
);
4432 up_read(&css_set_rwsem
);
4437 * Make sure there's no live children. We can't test ->children
4438 * emptiness as dead children linger on it while being destroyed;
4439 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
4443 list_for_each_entry_rcu(child
, &cgrp
->children
, sibling
) {
4444 empty
= cgroup_is_dead(child
);
4453 * Mark @cgrp dead. This prevents further task migration and child
4454 * creation by disabling cgroup_lock_live_group(). Note that
4455 * CGRP_DEAD assertion is depended upon by css_next_child() to
4456 * resume iteration after dropping RCU read lock. See
4457 * css_next_child() for details.
4459 set_bit(CGRP_DEAD
, &cgrp
->flags
);
4462 * Initiate massacre of all css's. cgroup_destroy_css_killed()
4463 * will be invoked to perform the rest of destruction once the
4464 * percpu refs of all css's are confirmed to be killed. This
4465 * involves removing the subsystem's files, drop cgroup_mutex.
4467 mutex_unlock(&cgroup_mutex
);
4468 for_each_css(css
, ssid
, cgrp
)
4470 mutex_lock(&cgroup_mutex
);
4472 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4473 raw_spin_lock(&release_list_lock
);
4474 if (!list_empty(&cgrp
->release_list
))
4475 list_del_init(&cgrp
->release_list
);
4476 raw_spin_unlock(&release_list_lock
);
4479 * If @cgrp has css's attached, the second stage of cgroup
4480 * destruction is kicked off from css_killed_work_fn() after the
4481 * refs of all attached css's are killed. If @cgrp doesn't have
4482 * any css, we kick it off here.
4485 cgroup_destroy_css_killed(cgrp
);
4487 /* remove @cgrp directory along with the base files */
4488 mutex_unlock(&cgroup_mutex
);
4491 * There are two control paths which try to determine cgroup from
4492 * dentry without going through kernfs - cgroupstats_build() and
4493 * css_tryget_from_dir(). Those are supported by RCU protecting
4494 * clearing of cgrp->kn->priv backpointer, which should happen
4495 * after all files under it have been removed.
4497 kernfs_remove(cgrp
->kn
); /* @cgrp has an extra ref on its kn */
4498 RCU_INIT_POINTER(*(void __rcu __force
**)&cgrp
->kn
->priv
, NULL
);
4500 mutex_lock(&cgroup_mutex
);
4506 * cgroup_destroy_css_killed - the second step of cgroup destruction
4507 * @work: cgroup->destroy_free_work
4509 * This function is invoked from a work item for a cgroup which is being
4510 * destroyed after all css's are offlined and performs the rest of
4511 * destruction. This is the second step of destruction described in the
4512 * comment above cgroup_destroy_locked().
4514 static void cgroup_destroy_css_killed(struct cgroup
*cgrp
)
4516 struct cgroup
*parent
= cgrp
->parent
;
4518 lockdep_assert_held(&cgroup_tree_mutex
);
4519 lockdep_assert_held(&cgroup_mutex
);
4521 /* delete this cgroup from parent->children */
4522 list_del_rcu(&cgrp
->sibling
);
4526 set_bit(CGRP_RELEASABLE
, &parent
->flags
);
4527 check_for_release(parent
);
4530 static int cgroup_rmdir(struct kernfs_node
*kn
)
4532 struct cgroup
*cgrp
= kn
->priv
;
4536 * This is self-destruction but @kn can't be removed while this
4537 * callback is in progress. Let's break active protection. Once
4538 * the protection is broken, @cgrp can be destroyed at any point.
4539 * Pin it so that it stays accessible.
4542 kernfs_break_active_protection(kn
);
4544 mutex_lock(&cgroup_tree_mutex
);
4545 mutex_lock(&cgroup_mutex
);
4548 * @cgrp might already have been destroyed while we're trying to
4551 if (!cgroup_is_dead(cgrp
))
4552 ret
= cgroup_destroy_locked(cgrp
);
4554 mutex_unlock(&cgroup_mutex
);
4555 mutex_unlock(&cgroup_tree_mutex
);
4557 kernfs_unbreak_active_protection(kn
);
4562 static struct kernfs_syscall_ops cgroup_kf_syscall_ops
= {
4563 .remount_fs
= cgroup_remount
,
4564 .show_options
= cgroup_show_options
,
4565 .mkdir
= cgroup_mkdir
,
4566 .rmdir
= cgroup_rmdir
,
4567 .rename
= cgroup_rename
,
4570 static void __init
cgroup_init_subsys(struct cgroup_subsys
*ss
)
4572 struct cgroup_subsys_state
*css
;
4574 printk(KERN_INFO
"Initializing cgroup subsys %s\n", ss
->name
);
4576 mutex_lock(&cgroup_tree_mutex
);
4577 mutex_lock(&cgroup_mutex
);
4579 INIT_LIST_HEAD(&ss
->cfts
);
4581 /* Create the root cgroup state for this subsystem */
4582 ss
->root
= &cgrp_dfl_root
;
4583 css
= ss
->css_alloc(cgroup_css(&cgrp_dfl_root
.cgrp
, ss
));
4584 /* We don't handle early failures gracefully */
4585 BUG_ON(IS_ERR(css
));
4586 init_css(css
, ss
, &cgrp_dfl_root
.cgrp
);
4588 /* Update the init_css_set to contain a subsys
4589 * pointer to this state - since the subsystem is
4590 * newly registered, all tasks and hence the
4591 * init_css_set is in the subsystem's root cgroup. */
4592 init_css_set
.subsys
[ss
->id
] = css
;
4594 need_forkexit_callback
|= ss
->fork
|| ss
->exit
;
4596 /* At system boot, before all subsystems have been
4597 * registered, no tasks have been forked, so we don't
4598 * need to invoke fork callbacks here. */
4599 BUG_ON(!list_empty(&init_task
.tasks
));
4601 BUG_ON(online_css(css
));
4603 cgrp_dfl_root
.subsys_mask
|= 1 << ss
->id
;
4605 mutex_unlock(&cgroup_mutex
);
4606 mutex_unlock(&cgroup_tree_mutex
);
4610 * cgroup_init_early - cgroup initialization at system boot
4612 * Initialize cgroups at system boot, and initialize any
4613 * subsystems that request early init.
4615 int __init
cgroup_init_early(void)
4617 static struct cgroup_sb_opts __initdata opts
=
4618 { .flags
= CGRP_ROOT_SANE_BEHAVIOR
};
4619 struct cgroup_subsys
*ss
;
4622 init_cgroup_root(&cgrp_dfl_root
, &opts
);
4623 RCU_INIT_POINTER(init_task
.cgroups
, &init_css_set
);
4625 for_each_subsys(ss
, i
) {
4626 WARN(!ss
->css_alloc
|| !ss
->css_free
|| ss
->name
|| ss
->id
,
4627 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
4628 i
, cgroup_subsys_name
[i
], ss
->css_alloc
, ss
->css_free
,
4630 WARN(strlen(cgroup_subsys_name
[i
]) > MAX_CGROUP_TYPE_NAMELEN
,
4631 "cgroup_subsys_name %s too long\n", cgroup_subsys_name
[i
]);
4634 ss
->name
= cgroup_subsys_name
[i
];
4637 cgroup_init_subsys(ss
);
4643 * cgroup_init - cgroup initialization
4645 * Register cgroup filesystem and /proc file, and initialize
4646 * any subsystems that didn't request early init.
4648 int __init
cgroup_init(void)
4650 struct cgroup_subsys
*ss
;
4654 BUG_ON(cgroup_init_cftypes(NULL
, cgroup_base_files
));
4656 mutex_lock(&cgroup_tree_mutex
);
4657 mutex_lock(&cgroup_mutex
);
4659 /* Add init_css_set to the hash table */
4660 key
= css_set_hash(init_css_set
.subsys
);
4661 hash_add(css_set_table
, &init_css_set
.hlist
, key
);
4663 BUG_ON(cgroup_setup_root(&cgrp_dfl_root
, 0));
4665 mutex_unlock(&cgroup_mutex
);
4666 mutex_unlock(&cgroup_tree_mutex
);
4668 for_each_subsys(ss
, ssid
) {
4669 if (!ss
->early_init
)
4670 cgroup_init_subsys(ss
);
4672 list_add_tail(&init_css_set
.e_cset_node
[ssid
],
4673 &cgrp_dfl_root
.cgrp
.e_csets
[ssid
]);
4676 * cftype registration needs kmalloc and can't be done
4677 * during early_init. Register base cftypes separately.
4679 if (ss
->base_cftypes
)
4680 WARN_ON(cgroup_add_cftypes(ss
, ss
->base_cftypes
));
4683 cgroup_kobj
= kobject_create_and_add("cgroup", fs_kobj
);
4687 err
= register_filesystem(&cgroup_fs_type
);
4689 kobject_put(cgroup_kobj
);
4693 proc_create("cgroups", 0, NULL
, &proc_cgroupstats_operations
);
4697 static int __init
cgroup_wq_init(void)
4700 * There isn't much point in executing destruction path in
4701 * parallel. Good chunk is serialized with cgroup_mutex anyway.
4702 * Use 1 for @max_active.
4704 * We would prefer to do this in cgroup_init() above, but that
4705 * is called before init_workqueues(): so leave this until after.
4707 cgroup_destroy_wq
= alloc_workqueue("cgroup_destroy", 0, 1);
4708 BUG_ON(!cgroup_destroy_wq
);
4711 * Used to destroy pidlists and separate to serve as flush domain.
4712 * Cap @max_active to 1 too.
4714 cgroup_pidlist_destroy_wq
= alloc_workqueue("cgroup_pidlist_destroy",
4716 BUG_ON(!cgroup_pidlist_destroy_wq
);
4720 core_initcall(cgroup_wq_init
);
4723 * proc_cgroup_show()
4724 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4725 * - Used for /proc/<pid>/cgroup.
4728 /* TODO: Use a proper seq_file iterator */
4729 int proc_cgroup_show(struct seq_file
*m
, void *v
)
4732 struct task_struct
*tsk
;
4735 struct cgroup_root
*root
;
4738 buf
= kmalloc(PATH_MAX
, GFP_KERNEL
);
4744 tsk
= get_pid_task(pid
, PIDTYPE_PID
);
4750 mutex_lock(&cgroup_mutex
);
4751 down_read(&css_set_rwsem
);
4753 for_each_root(root
) {
4754 struct cgroup_subsys
*ss
;
4755 struct cgroup
*cgrp
;
4756 int ssid
, count
= 0;
4758 if (root
== &cgrp_dfl_root
&& !cgrp_dfl_root_visible
)
4761 seq_printf(m
, "%d:", root
->hierarchy_id
);
4762 for_each_subsys(ss
, ssid
)
4763 if (root
->subsys_mask
& (1 << ssid
))
4764 seq_printf(m
, "%s%s", count
++ ? "," : "", ss
->name
);
4765 if (strlen(root
->name
))
4766 seq_printf(m
, "%sname=%s", count
? "," : "",
4769 cgrp
= task_cgroup_from_root(tsk
, root
);
4770 path
= cgroup_path(cgrp
, buf
, PATH_MAX
);
4772 retval
= -ENAMETOOLONG
;
4780 up_read(&css_set_rwsem
);
4781 mutex_unlock(&cgroup_mutex
);
4782 put_task_struct(tsk
);
4789 /* Display information about each subsystem and each hierarchy */
4790 static int proc_cgroupstats_show(struct seq_file
*m
, void *v
)
4792 struct cgroup_subsys
*ss
;
4795 seq_puts(m
, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4797 * ideally we don't want subsystems moving around while we do this.
4798 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4799 * subsys/hierarchy state.
4801 mutex_lock(&cgroup_mutex
);
4803 for_each_subsys(ss
, i
)
4804 seq_printf(m
, "%s\t%d\t%d\t%d\n",
4805 ss
->name
, ss
->root
->hierarchy_id
,
4806 atomic_read(&ss
->root
->nr_cgrps
), !ss
->disabled
);
4808 mutex_unlock(&cgroup_mutex
);
4812 static int cgroupstats_open(struct inode
*inode
, struct file
*file
)
4814 return single_open(file
, proc_cgroupstats_show
, NULL
);
4817 static const struct file_operations proc_cgroupstats_operations
= {
4818 .open
= cgroupstats_open
,
4820 .llseek
= seq_lseek
,
4821 .release
= single_release
,
4825 * cgroup_fork - initialize cgroup related fields during copy_process()
4826 * @child: pointer to task_struct of forking parent process.
4828 * A task is associated with the init_css_set until cgroup_post_fork()
4829 * attaches it to the parent's css_set. Empty cg_list indicates that
4830 * @child isn't holding reference to its css_set.
4832 void cgroup_fork(struct task_struct
*child
)
4834 RCU_INIT_POINTER(child
->cgroups
, &init_css_set
);
4835 INIT_LIST_HEAD(&child
->cg_list
);
4839 * cgroup_post_fork - called on a new task after adding it to the task list
4840 * @child: the task in question
4842 * Adds the task to the list running through its css_set if necessary and
4843 * call the subsystem fork() callbacks. Has to be after the task is
4844 * visible on the task list in case we race with the first call to
4845 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
4848 void cgroup_post_fork(struct task_struct
*child
)
4850 struct cgroup_subsys
*ss
;
4854 * This may race against cgroup_enable_task_cg_links(). As that
4855 * function sets use_task_css_set_links before grabbing
4856 * tasklist_lock and we just went through tasklist_lock to add
4857 * @child, it's guaranteed that either we see the set
4858 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
4859 * @child during its iteration.
4861 * If we won the race, @child is associated with %current's
4862 * css_set. Grabbing css_set_rwsem guarantees both that the
4863 * association is stable, and, on completion of the parent's
4864 * migration, @child is visible in the source of migration or
4865 * already in the destination cgroup. This guarantee is necessary
4866 * when implementing operations which need to migrate all tasks of
4867 * a cgroup to another.
4869 * Note that if we lose to cgroup_enable_task_cg_links(), @child
4870 * will remain in init_css_set. This is safe because all tasks are
4871 * in the init_css_set before cg_links is enabled and there's no
4872 * operation which transfers all tasks out of init_css_set.
4874 if (use_task_css_set_links
) {
4875 struct css_set
*cset
;
4877 down_write(&css_set_rwsem
);
4878 cset
= task_css_set(current
);
4879 if (list_empty(&child
->cg_list
)) {
4880 rcu_assign_pointer(child
->cgroups
, cset
);
4881 list_add(&child
->cg_list
, &cset
->tasks
);
4884 up_write(&css_set_rwsem
);
4888 * Call ss->fork(). This must happen after @child is linked on
4889 * css_set; otherwise, @child might change state between ->fork()
4890 * and addition to css_set.
4892 if (need_forkexit_callback
) {
4893 for_each_subsys(ss
, i
)
4900 * cgroup_exit - detach cgroup from exiting task
4901 * @tsk: pointer to task_struct of exiting process
4903 * Description: Detach cgroup from @tsk and release it.
4905 * Note that cgroups marked notify_on_release force every task in
4906 * them to take the global cgroup_mutex mutex when exiting.
4907 * This could impact scaling on very large systems. Be reluctant to
4908 * use notify_on_release cgroups where very high task exit scaling
4909 * is required on large systems.
4911 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
4912 * call cgroup_exit() while the task is still competent to handle
4913 * notify_on_release(), then leave the task attached to the root cgroup in
4914 * each hierarchy for the remainder of its exit. No need to bother with
4915 * init_css_set refcnting. init_css_set never goes away and we can't race
4916 * with migration path - PF_EXITING is visible to migration path.
4918 void cgroup_exit(struct task_struct
*tsk
)
4920 struct cgroup_subsys
*ss
;
4921 struct css_set
*cset
;
4922 bool put_cset
= false;
4926 * Unlink from @tsk from its css_set. As migration path can't race
4927 * with us, we can check cg_list without grabbing css_set_rwsem.
4929 if (!list_empty(&tsk
->cg_list
)) {
4930 down_write(&css_set_rwsem
);
4931 list_del_init(&tsk
->cg_list
);
4932 up_write(&css_set_rwsem
);
4936 /* Reassign the task to the init_css_set. */
4937 cset
= task_css_set(tsk
);
4938 RCU_INIT_POINTER(tsk
->cgroups
, &init_css_set
);
4940 if (need_forkexit_callback
) {
4941 /* see cgroup_post_fork() for details */
4942 for_each_subsys(ss
, i
) {
4944 struct cgroup_subsys_state
*old_css
= cset
->subsys
[i
];
4945 struct cgroup_subsys_state
*css
= task_css(tsk
, i
);
4947 ss
->exit(css
, old_css
, tsk
);
4953 put_css_set(cset
, true);
4956 static void check_for_release(struct cgroup
*cgrp
)
4958 if (cgroup_is_releasable(cgrp
) &&
4959 list_empty(&cgrp
->cset_links
) && list_empty(&cgrp
->children
)) {
4961 * Control Group is currently removeable. If it's not
4962 * already queued for a userspace notification, queue
4965 int need_schedule_work
= 0;
4967 raw_spin_lock(&release_list_lock
);
4968 if (!cgroup_is_dead(cgrp
) &&
4969 list_empty(&cgrp
->release_list
)) {
4970 list_add(&cgrp
->release_list
, &release_list
);
4971 need_schedule_work
= 1;
4973 raw_spin_unlock(&release_list_lock
);
4974 if (need_schedule_work
)
4975 schedule_work(&release_agent_work
);
4980 * Notify userspace when a cgroup is released, by running the
4981 * configured release agent with the name of the cgroup (path
4982 * relative to the root of cgroup file system) as the argument.
4984 * Most likely, this user command will try to rmdir this cgroup.
4986 * This races with the possibility that some other task will be
4987 * attached to this cgroup before it is removed, or that some other
4988 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
4989 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
4990 * unused, and this cgroup will be reprieved from its death sentence,
4991 * to continue to serve a useful existence. Next time it's released,
4992 * we will get notified again, if it still has 'notify_on_release' set.
4994 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
4995 * means only wait until the task is successfully execve()'d. The
4996 * separate release agent task is forked by call_usermodehelper(),
4997 * then control in this thread returns here, without waiting for the
4998 * release agent task. We don't bother to wait because the caller of
4999 * this routine has no use for the exit status of the release agent
5000 * task, so no sense holding our caller up for that.
5002 static void cgroup_release_agent(struct work_struct
*work
)
5004 BUG_ON(work
!= &release_agent_work
);
5005 mutex_lock(&cgroup_mutex
);
5006 raw_spin_lock(&release_list_lock
);
5007 while (!list_empty(&release_list
)) {
5008 char *argv
[3], *envp
[3];
5010 char *pathbuf
= NULL
, *agentbuf
= NULL
, *path
;
5011 struct cgroup
*cgrp
= list_entry(release_list
.next
,
5014 list_del_init(&cgrp
->release_list
);
5015 raw_spin_unlock(&release_list_lock
);
5016 pathbuf
= kmalloc(PATH_MAX
, GFP_KERNEL
);
5019 path
= cgroup_path(cgrp
, pathbuf
, PATH_MAX
);
5022 agentbuf
= kstrdup(cgrp
->root
->release_agent_path
, GFP_KERNEL
);
5027 argv
[i
++] = agentbuf
;
5032 /* minimal command environment */
5033 envp
[i
++] = "HOME=/";
5034 envp
[i
++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5037 /* Drop the lock while we invoke the usermode helper,
5038 * since the exec could involve hitting disk and hence
5039 * be a slow process */
5040 mutex_unlock(&cgroup_mutex
);
5041 call_usermodehelper(argv
[0], argv
, envp
, UMH_WAIT_EXEC
);
5042 mutex_lock(&cgroup_mutex
);
5046 raw_spin_lock(&release_list_lock
);
5048 raw_spin_unlock(&release_list_lock
);
5049 mutex_unlock(&cgroup_mutex
);
5052 static int __init
cgroup_disable(char *str
)
5054 struct cgroup_subsys
*ss
;
5058 while ((token
= strsep(&str
, ",")) != NULL
) {
5062 for_each_subsys(ss
, i
) {
5063 if (!strcmp(token
, ss
->name
)) {
5065 printk(KERN_INFO
"Disabling %s control group"
5066 " subsystem\n", ss
->name
);
5073 __setup("cgroup_disable=", cgroup_disable
);
5076 * css_tryget_from_dir - get corresponding css from the dentry of a cgroup dir
5077 * @dentry: directory dentry of interest
5078 * @ss: subsystem of interest
5080 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
5081 * to get the corresponding css and return it. If such css doesn't exist
5082 * or can't be pinned, an ERR_PTR value is returned.
5084 struct cgroup_subsys_state
*css_tryget_from_dir(struct dentry
*dentry
,
5085 struct cgroup_subsys
*ss
)
5087 struct kernfs_node
*kn
= kernfs_node_from_dentry(dentry
);
5088 struct cgroup_subsys_state
*css
= NULL
;
5089 struct cgroup
*cgrp
;
5091 /* is @dentry a cgroup dir? */
5092 if (dentry
->d_sb
->s_type
!= &cgroup_fs_type
|| !kn
||
5093 kernfs_type(kn
) != KERNFS_DIR
)
5094 return ERR_PTR(-EBADF
);
5099 * This path doesn't originate from kernfs and @kn could already
5100 * have been or be removed at any point. @kn->priv is RCU
5101 * protected for this access. See destroy_locked() for details.
5103 cgrp
= rcu_dereference(kn
->priv
);
5105 css
= cgroup_css(cgrp
, ss
);
5107 if (!css
|| !css_tryget(css
))
5108 css
= ERR_PTR(-ENOENT
);
5115 * css_from_id - lookup css by id
5116 * @id: the cgroup id
5117 * @ss: cgroup subsys to be looked into
5119 * Returns the css if there's valid one with @id, otherwise returns NULL.
5120 * Should be called under rcu_read_lock().
5122 struct cgroup_subsys_state
*css_from_id(int id
, struct cgroup_subsys
*ss
)
5124 struct cgroup
*cgrp
;
5126 cgroup_assert_mutexes_or_rcu_locked();
5128 cgrp
= idr_find(&ss
->root
->cgroup_idr
, id
);
5130 return cgroup_css(cgrp
, ss
);
5134 #ifdef CONFIG_CGROUP_DEBUG
5135 static struct cgroup_subsys_state
*
5136 debug_css_alloc(struct cgroup_subsys_state
*parent_css
)
5138 struct cgroup_subsys_state
*css
= kzalloc(sizeof(*css
), GFP_KERNEL
);
5141 return ERR_PTR(-ENOMEM
);
5146 static void debug_css_free(struct cgroup_subsys_state
*css
)
5151 static u64
debug_taskcount_read(struct cgroup_subsys_state
*css
,
5154 return cgroup_task_count(css
->cgroup
);
5157 static u64
current_css_set_read(struct cgroup_subsys_state
*css
,
5160 return (u64
)(unsigned long)current
->cgroups
;
5163 static u64
current_css_set_refcount_read(struct cgroup_subsys_state
*css
,
5169 count
= atomic_read(&task_css_set(current
)->refcount
);
5174 static int current_css_set_cg_links_read(struct seq_file
*seq
, void *v
)
5176 struct cgrp_cset_link
*link
;
5177 struct css_set
*cset
;
5180 name_buf
= kmalloc(NAME_MAX
+ 1, GFP_KERNEL
);
5184 down_read(&css_set_rwsem
);
5186 cset
= rcu_dereference(current
->cgroups
);
5187 list_for_each_entry(link
, &cset
->cgrp_links
, cgrp_link
) {
5188 struct cgroup
*c
= link
->cgrp
;
5190 cgroup_name(c
, name_buf
, NAME_MAX
+ 1);
5191 seq_printf(seq
, "Root %d group %s\n",
5192 c
->root
->hierarchy_id
, name_buf
);
5195 up_read(&css_set_rwsem
);
5200 #define MAX_TASKS_SHOWN_PER_CSS 25
5201 static int cgroup_css_links_read(struct seq_file
*seq
, void *v
)
5203 struct cgroup_subsys_state
*css
= seq_css(seq
);
5204 struct cgrp_cset_link
*link
;
5206 down_read(&css_set_rwsem
);
5207 list_for_each_entry(link
, &css
->cgroup
->cset_links
, cset_link
) {
5208 struct css_set
*cset
= link
->cset
;
5209 struct task_struct
*task
;
5212 seq_printf(seq
, "css_set %p\n", cset
);
5214 list_for_each_entry(task
, &cset
->tasks
, cg_list
) {
5215 if (count
++ > MAX_TASKS_SHOWN_PER_CSS
)
5217 seq_printf(seq
, " task %d\n", task_pid_vnr(task
));
5220 list_for_each_entry(task
, &cset
->mg_tasks
, cg_list
) {
5221 if (count
++ > MAX_TASKS_SHOWN_PER_CSS
)
5223 seq_printf(seq
, " task %d\n", task_pid_vnr(task
));
5227 seq_puts(seq
, " ...\n");
5229 up_read(&css_set_rwsem
);
5233 static u64
releasable_read(struct cgroup_subsys_state
*css
, struct cftype
*cft
)
5235 return test_bit(CGRP_RELEASABLE
, &css
->cgroup
->flags
);
5238 static struct cftype debug_files
[] = {
5240 .name
= "taskcount",
5241 .read_u64
= debug_taskcount_read
,
5245 .name
= "current_css_set",
5246 .read_u64
= current_css_set_read
,
5250 .name
= "current_css_set_refcount",
5251 .read_u64
= current_css_set_refcount_read
,
5255 .name
= "current_css_set_cg_links",
5256 .seq_show
= current_css_set_cg_links_read
,
5260 .name
= "cgroup_css_links",
5261 .seq_show
= cgroup_css_links_read
,
5265 .name
= "releasable",
5266 .read_u64
= releasable_read
,
5272 struct cgroup_subsys debug_cgrp_subsys
= {
5273 .css_alloc
= debug_css_alloc
,
5274 .css_free
= debug_css_free
,
5275 .base_cftypes
= debug_files
,
5277 #endif /* CONFIG_CGROUP_DEBUG */