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 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
31 #include <linux/cgroup.h>
32 #include <linux/cred.h>
33 #include <linux/ctype.h>
34 #include <linux/errno.h>
35 #include <linux/init_task.h>
36 #include <linux/kernel.h>
37 #include <linux/list.h>
39 #include <linux/mutex.h>
40 #include <linux/mount.h>
41 #include <linux/pagemap.h>
42 #include <linux/proc_fs.h>
43 #include <linux/rcupdate.h>
44 #include <linux/sched.h>
45 #include <linux/slab.h>
46 #include <linux/spinlock.h>
47 #include <linux/rwsem.h>
48 #include <linux/string.h>
49 #include <linux/sort.h>
50 #include <linux/kmod.h>
51 #include <linux/delayacct.h>
52 #include <linux/cgroupstats.h>
53 #include <linux/hashtable.h>
54 #include <linux/pid_namespace.h>
55 #include <linux/idr.h>
56 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
57 #include <linux/kthread.h>
58 #include <linux/delay.h>
60 #include <linux/atomic.h>
63 * pidlists linger the following amount before being destroyed. The goal
64 * is avoiding frequent destruction in the middle of consecutive read calls
65 * Expiring in the middle is a performance problem not a correctness one.
66 * 1 sec should be enough.
68 #define CGROUP_PIDLIST_DESTROY_DELAY HZ
70 #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
74 * cgroup_tree_mutex nests above cgroup_mutex and protects cftypes, file
75 * creation/removal and hierarchy changing operations including cgroup
76 * creation, removal, css association and controller rebinding. This outer
77 * lock is needed mainly to resolve the circular dependency between kernfs
78 * active ref and cgroup_mutex. cgroup_tree_mutex nests above both.
80 static DEFINE_MUTEX(cgroup_tree_mutex);
83 * cgroup_mutex is the master lock. Any modification to cgroup or its
84 * hierarchy must be performed while holding it.
86 * css_set_rwsem protects task->cgroups pointer, the list of css_set
87 * objects, and the chain of tasks off each css_set.
89 * These locks are exported if CONFIG_PROVE_RCU so that accessors in
90 * cgroup.h can use them for lockdep annotations.
92 #ifdef CONFIG_PROVE_RCU
93 DEFINE_MUTEX(cgroup_mutex);
94 DECLARE_RWSEM(css_set_rwsem);
95 EXPORT_SYMBOL_GPL(cgroup_mutex);
96 EXPORT_SYMBOL_GPL(css_set_rwsem);
98 static DEFINE_MUTEX(cgroup_mutex);
99 static DECLARE_RWSEM(css_set_rwsem);
103 * Protects cgroup_subsys->release_agent_path. Modifying it also requires
104 * cgroup_mutex. Reading requires either cgroup_mutex or this spinlock.
106 static DEFINE_SPINLOCK(release_agent_path_lock);
108 #define cgroup_assert_mutexes_or_rcu_locked() \
109 rcu_lockdep_assert(rcu_read_lock_held() || \
110 lockdep_is_held(&cgroup_tree_mutex) || \
111 lockdep_is_held(&cgroup_mutex), \
112 "cgroup_[tree_]mutex or RCU read lock required");
115 * cgroup destruction makes heavy use of work items and there can be a lot
116 * of concurrent destructions. Use a separate workqueue so that cgroup
117 * destruction work items don't end up filling up max_active of system_wq
118 * which may lead to deadlock.
120 static struct workqueue_struct *cgroup_destroy_wq;
123 * pidlist destructions need to be flushed on cgroup destruction. Use a
124 * separate workqueue as flush domain.
126 static struct workqueue_struct *cgroup_pidlist_destroy_wq;
128 /* generate an array of cgroup subsystem pointers */
129 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
130 static struct cgroup_subsys *cgroup_subsys[] = {
131 #include <linux/cgroup_subsys.h>
135 /* array of cgroup subsystem names */
136 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
137 static const char *cgroup_subsys_name[] = {
138 #include <linux/cgroup_subsys.h>
143 * The default hierarchy, reserved for the subsystems that are otherwise
144 * unattached - it never has more than a single cgroup, and all tasks are
145 * part of that cgroup.
147 struct cgroup_root cgrp_dfl_root;
150 * The default hierarchy always exists but is hidden until mounted for the
151 * first time. This is for backward compatibility.
153 static bool cgrp_dfl_root_visible;
155 /* The list of hierarchy roots */
157 static LIST_HEAD(cgroup_roots);
158 static int cgroup_root_count;
160 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
161 static DEFINE_IDR(cgroup_hierarchy_idr);
164 * Assign a monotonically increasing serial number to cgroups. It
165 * guarantees cgroups with bigger numbers are newer than those with smaller
166 * numbers. Also, as cgroups are always appended to the parent's
167 * ->children list, it guarantees that sibling cgroups are always sorted in
168 * the ascending serial number order on the list. Protected by
171 static u64 cgroup_serial_nr_next = 1;
173 /* This flag indicates whether tasks in the fork and exit paths should
174 * check for fork/exit handlers to call. This avoids us having to do
175 * extra work in the fork/exit path if none of the subsystems need to
178 static int need_forkexit_callback __read_mostly;
180 static struct cftype cgroup_base_files[];
182 static void cgroup_put(struct cgroup *cgrp);
183 static int rebind_subsystems(struct cgroup_root *dst_root,
184 unsigned int ss_mask);
185 static void cgroup_destroy_css_killed(struct cgroup *cgrp);
186 static int cgroup_destroy_locked(struct cgroup *cgrp);
187 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss);
188 static void kill_css(struct cgroup_subsys_state *css);
189 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
191 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp);
194 * cgroup_css - obtain a cgroup's css for the specified subsystem
195 * @cgrp: the cgroup of interest
196 * @ss: the subsystem of interest (%NULL returns the dummy_css)
198 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
199 * function must be called either under cgroup_mutex or rcu_read_lock() and
200 * the caller is responsible for pinning the returned css if it wants to
201 * keep accessing it outside the said locks. This function may return
202 * %NULL if @cgrp doesn't have @subsys_id enabled.
204 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
205 struct cgroup_subsys *ss)
208 return rcu_dereference_check(cgrp->subsys[ss->id],
209 lockdep_is_held(&cgroup_tree_mutex) ||
210 lockdep_is_held(&cgroup_mutex));
212 return &cgrp->dummy_css;
216 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
217 * @cgrp: the cgroup of interest
218 * @ss: the subsystem of interest (%NULL returns the dummy_css)
220 * Similar to cgroup_css() but returns the effctive css, which is defined
221 * as the matching css of the nearest ancestor including self which has @ss
222 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
223 * function is guaranteed to return non-NULL css.
225 static struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
226 struct cgroup_subsys *ss)
228 lockdep_assert_held(&cgroup_mutex);
231 return &cgrp->dummy_css;
233 if (!(cgrp->root->subsys_mask & (1 << ss->id)))
236 while (cgrp->parent &&
237 !(cgrp->parent->child_subsys_mask & (1 << ss->id)))
240 return cgroup_css(cgrp, ss);
243 /* convenient tests for these bits */
244 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
246 return test_bit(CGRP_DEAD, &cgrp->flags);
249 struct cgroup_subsys_state *seq_css(struct seq_file *seq)
251 struct kernfs_open_file *of = seq->private;
252 struct cgroup *cgrp = of->kn->parent->priv;
253 struct cftype *cft = seq_cft(seq);
256 * This is open and unprotected implementation of cgroup_css().
257 * seq_css() is only called from a kernfs file operation which has
258 * an active reference on the file. Because all the subsystem
259 * files are drained before a css is disassociated with a cgroup,
260 * the matching css from the cgroup's subsys table is guaranteed to
261 * be and stay valid until the enclosing operation is complete.
264 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
266 return &cgrp->dummy_css;
268 EXPORT_SYMBOL_GPL(seq_css);
271 * cgroup_is_descendant - test ancestry
272 * @cgrp: the cgroup to be tested
273 * @ancestor: possible ancestor of @cgrp
275 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
276 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
277 * and @ancestor are accessible.
279 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
282 if (cgrp == ancestor)
289 static int cgroup_is_releasable(const struct cgroup *cgrp)
292 (1 << CGRP_RELEASABLE) |
293 (1 << CGRP_NOTIFY_ON_RELEASE);
294 return (cgrp->flags & bits) == bits;
297 static int notify_on_release(const struct cgroup *cgrp)
299 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
303 * for_each_css - iterate all css's of a cgroup
304 * @css: the iteration cursor
305 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
306 * @cgrp: the target cgroup to iterate css's of
308 * Should be called under cgroup_[tree_]mutex.
310 #define for_each_css(css, ssid, cgrp) \
311 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
312 if (!((css) = rcu_dereference_check( \
313 (cgrp)->subsys[(ssid)], \
314 lockdep_is_held(&cgroup_tree_mutex) || \
315 lockdep_is_held(&cgroup_mutex)))) { } \
319 * for_each_e_css - iterate all effective css's of a cgroup
320 * @css: the iteration cursor
321 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
322 * @cgrp: the target cgroup to iterate css's of
324 * Should be called under cgroup_[tree_]mutex.
326 #define for_each_e_css(css, ssid, cgrp) \
327 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
328 if (!((css) = cgroup_e_css(cgrp, cgroup_subsys[(ssid)]))) \
333 * for_each_subsys - iterate all enabled cgroup subsystems
334 * @ss: the iteration cursor
335 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
337 #define for_each_subsys(ss, ssid) \
338 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT && \
339 (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
341 /* iterate across the hierarchies */
342 #define for_each_root(root) \
343 list_for_each_entry((root), &cgroup_roots, root_list)
345 /* iterate over child cgrps, lock should be held throughout iteration */
346 #define cgroup_for_each_live_child(child, cgrp) \
347 list_for_each_entry((child), &(cgrp)->children, sibling) \
348 if (({ lockdep_assert_held(&cgroup_tree_mutex); \
349 cgroup_is_dead(child); })) \
354 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
355 * @cgrp: the cgroup to be checked for liveness
357 * On success, returns true; the mutex should be later unlocked. On
358 * failure returns false with no lock held.
360 static bool cgroup_lock_live_group(struct cgroup *cgrp)
362 mutex_lock(&cgroup_mutex);
363 if (cgroup_is_dead(cgrp)) {
364 mutex_unlock(&cgroup_mutex);
370 /* the list of cgroups eligible for automatic release. Protected by
371 * release_list_lock */
372 static LIST_HEAD(release_list);
373 static DEFINE_RAW_SPINLOCK(release_list_lock);
374 static void cgroup_release_agent(struct work_struct *work);
375 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
376 static void check_for_release(struct cgroup *cgrp);
379 * A cgroup can be associated with multiple css_sets as different tasks may
380 * belong to different cgroups on different hierarchies. In the other
381 * direction, a css_set is naturally associated with multiple cgroups.
382 * This M:N relationship is represented by the following link structure
383 * which exists for each association and allows traversing the associations
386 struct cgrp_cset_link {
387 /* the cgroup and css_set this link associates */
389 struct css_set *cset;
391 /* list of cgrp_cset_links anchored at cgrp->cset_links */
392 struct list_head cset_link;
394 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
395 struct list_head cgrp_link;
399 * The default css_set - used by init and its children prior to any
400 * hierarchies being mounted. It contains a pointer to the root state
401 * for each subsystem. Also used to anchor the list of css_sets. Not
402 * reference-counted, to improve performance when child cgroups
403 * haven't been created.
405 static struct css_set init_css_set = {
406 .refcount = ATOMIC_INIT(1),
407 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
408 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
409 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
410 .mg_preload_node = LIST_HEAD_INIT(init_css_set.mg_preload_node),
411 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
414 static int css_set_count = 1; /* 1 for init_css_set */
417 * cgroup_update_populated - updated populated count of a cgroup
418 * @cgrp: the target cgroup
419 * @populated: inc or dec populated count
421 * @cgrp is either getting the first task (css_set) or losing the last.
422 * Update @cgrp->populated_cnt accordingly. The count is propagated
423 * towards root so that a given cgroup's populated_cnt is zero iff the
424 * cgroup and all its descendants are empty.
426 * @cgrp's interface file "cgroup.populated" is zero if
427 * @cgrp->populated_cnt is zero and 1 otherwise. When @cgrp->populated_cnt
428 * changes from or to zero, userland is notified that the content of the
429 * interface file has changed. This can be used to detect when @cgrp and
430 * its descendants become populated or empty.
432 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
434 lockdep_assert_held(&css_set_rwsem);
440 trigger = !cgrp->populated_cnt++;
442 trigger = !--cgrp->populated_cnt;
447 if (cgrp->populated_kn)
448 kernfs_notify(cgrp->populated_kn);
454 * hash table for cgroup groups. This improves the performance to find
455 * an existing css_set. This hash doesn't (currently) take into
456 * account cgroups in empty hierarchies.
458 #define CSS_SET_HASH_BITS 7
459 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
461 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
463 unsigned long key = 0UL;
464 struct cgroup_subsys *ss;
467 for_each_subsys(ss, i)
468 key += (unsigned long)css[i];
469 key = (key >> 16) ^ key;
474 static void put_css_set_locked(struct css_set *cset, bool taskexit)
476 struct cgrp_cset_link *link, *tmp_link;
477 struct cgroup_subsys *ss;
480 lockdep_assert_held(&css_set_rwsem);
482 if (!atomic_dec_and_test(&cset->refcount))
485 /* This css_set is dead. unlink it and release cgroup refcounts */
486 for_each_subsys(ss, ssid)
487 list_del(&cset->e_cset_node[ssid]);
488 hash_del(&cset->hlist);
491 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
492 struct cgroup *cgrp = link->cgrp;
494 list_del(&link->cset_link);
495 list_del(&link->cgrp_link);
497 /* @cgrp can't go away while we're holding css_set_rwsem */
498 if (list_empty(&cgrp->cset_links)) {
499 cgroup_update_populated(cgrp, false);
500 if (notify_on_release(cgrp)) {
502 set_bit(CGRP_RELEASABLE, &cgrp->flags);
503 check_for_release(cgrp);
510 kfree_rcu(cset, rcu_head);
513 static void put_css_set(struct css_set *cset, bool taskexit)
516 * Ensure that the refcount doesn't hit zero while any readers
517 * can see it. Similar to atomic_dec_and_lock(), but for an
520 if (atomic_add_unless(&cset->refcount, -1, 1))
523 down_write(&css_set_rwsem);
524 put_css_set_locked(cset, taskexit);
525 up_write(&css_set_rwsem);
529 * refcounted get/put for css_set objects
531 static inline void get_css_set(struct css_set *cset)
533 atomic_inc(&cset->refcount);
537 * compare_css_sets - helper function for find_existing_css_set().
538 * @cset: candidate css_set being tested
539 * @old_cset: existing css_set for a task
540 * @new_cgrp: cgroup that's being entered by the task
541 * @template: desired set of css pointers in css_set (pre-calculated)
543 * Returns true if "cset" matches "old_cset" except for the hierarchy
544 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
546 static bool compare_css_sets(struct css_set *cset,
547 struct css_set *old_cset,
548 struct cgroup *new_cgrp,
549 struct cgroup_subsys_state *template[])
551 struct list_head *l1, *l2;
554 * On the default hierarchy, there can be csets which are
555 * associated with the same set of cgroups but different csses.
556 * Let's first ensure that csses match.
558 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
562 * Compare cgroup pointers in order to distinguish between
563 * different cgroups in hierarchies. As different cgroups may
564 * share the same effective css, this comparison is always
567 l1 = &cset->cgrp_links;
568 l2 = &old_cset->cgrp_links;
570 struct cgrp_cset_link *link1, *link2;
571 struct cgroup *cgrp1, *cgrp2;
575 /* See if we reached the end - both lists are equal length. */
576 if (l1 == &cset->cgrp_links) {
577 BUG_ON(l2 != &old_cset->cgrp_links);
580 BUG_ON(l2 == &old_cset->cgrp_links);
582 /* Locate the cgroups associated with these links. */
583 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
584 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
587 /* Hierarchies should be linked in the same order. */
588 BUG_ON(cgrp1->root != cgrp2->root);
591 * If this hierarchy is the hierarchy of the cgroup
592 * that's changing, then we need to check that this
593 * css_set points to the new cgroup; if it's any other
594 * hierarchy, then this css_set should point to the
595 * same cgroup as the old css_set.
597 if (cgrp1->root == new_cgrp->root) {
598 if (cgrp1 != new_cgrp)
609 * find_existing_css_set - init css array and find the matching css_set
610 * @old_cset: the css_set that we're using before the cgroup transition
611 * @cgrp: the cgroup that we're moving into
612 * @template: out param for the new set of csses, should be clear on entry
614 static struct css_set *find_existing_css_set(struct css_set *old_cset,
616 struct cgroup_subsys_state *template[])
618 struct cgroup_root *root = cgrp->root;
619 struct cgroup_subsys *ss;
620 struct css_set *cset;
625 * Build the set of subsystem state objects that we want to see in the
626 * new css_set. while subsystems can change globally, the entries here
627 * won't change, so no need for locking.
629 for_each_subsys(ss, i) {
630 if (root->subsys_mask & (1UL << i)) {
632 * @ss is in this hierarchy, so we want the
633 * effective css from @cgrp.
635 template[i] = cgroup_e_css(cgrp, ss);
638 * @ss is not in this hierarchy, so we don't want
641 template[i] = old_cset->subsys[i];
645 key = css_set_hash(template);
646 hash_for_each_possible(css_set_table, cset, hlist, key) {
647 if (!compare_css_sets(cset, old_cset, cgrp, template))
650 /* This css_set matches what we need */
654 /* No existing cgroup group matched */
658 static void free_cgrp_cset_links(struct list_head *links_to_free)
660 struct cgrp_cset_link *link, *tmp_link;
662 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
663 list_del(&link->cset_link);
669 * allocate_cgrp_cset_links - allocate cgrp_cset_links
670 * @count: the number of links to allocate
671 * @tmp_links: list_head the allocated links are put on
673 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
674 * through ->cset_link. Returns 0 on success or -errno.
676 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
678 struct cgrp_cset_link *link;
681 INIT_LIST_HEAD(tmp_links);
683 for (i = 0; i < count; i++) {
684 link = kzalloc(sizeof(*link), GFP_KERNEL);
686 free_cgrp_cset_links(tmp_links);
689 list_add(&link->cset_link, tmp_links);
695 * link_css_set - a helper function to link a css_set to a cgroup
696 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
697 * @cset: the css_set to be linked
698 * @cgrp: the destination cgroup
700 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
703 struct cgrp_cset_link *link;
705 BUG_ON(list_empty(tmp_links));
707 if (cgroup_on_dfl(cgrp))
708 cset->dfl_cgrp = cgrp;
710 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
714 if (list_empty(&cgrp->cset_links))
715 cgroup_update_populated(cgrp, true);
716 list_move(&link->cset_link, &cgrp->cset_links);
719 * Always add links to the tail of the list so that the list
720 * is sorted by order of hierarchy creation
722 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
726 * find_css_set - return a new css_set with one cgroup updated
727 * @old_cset: the baseline css_set
728 * @cgrp: the cgroup to be updated
730 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
731 * substituted into the appropriate hierarchy.
733 static struct css_set *find_css_set(struct css_set *old_cset,
736 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
737 struct css_set *cset;
738 struct list_head tmp_links;
739 struct cgrp_cset_link *link;
740 struct cgroup_subsys *ss;
744 lockdep_assert_held(&cgroup_mutex);
746 /* First see if we already have a cgroup group that matches
748 down_read(&css_set_rwsem);
749 cset = find_existing_css_set(old_cset, cgrp, template);
752 up_read(&css_set_rwsem);
757 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
761 /* Allocate all the cgrp_cset_link objects that we'll need */
762 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
767 atomic_set(&cset->refcount, 1);
768 INIT_LIST_HEAD(&cset->cgrp_links);
769 INIT_LIST_HEAD(&cset->tasks);
770 INIT_LIST_HEAD(&cset->mg_tasks);
771 INIT_LIST_HEAD(&cset->mg_preload_node);
772 INIT_LIST_HEAD(&cset->mg_node);
773 INIT_HLIST_NODE(&cset->hlist);
775 /* Copy the set of subsystem state objects generated in
776 * find_existing_css_set() */
777 memcpy(cset->subsys, template, sizeof(cset->subsys));
779 down_write(&css_set_rwsem);
780 /* Add reference counts and links from the new css_set. */
781 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
782 struct cgroup *c = link->cgrp;
784 if (c->root == cgrp->root)
786 link_css_set(&tmp_links, cset, c);
789 BUG_ON(!list_empty(&tmp_links));
793 /* Add @cset to the hash table */
794 key = css_set_hash(cset->subsys);
795 hash_add(css_set_table, &cset->hlist, key);
797 for_each_subsys(ss, ssid)
798 list_add_tail(&cset->e_cset_node[ssid],
799 &cset->subsys[ssid]->cgroup->e_csets[ssid]);
801 up_write(&css_set_rwsem);
806 static struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
808 struct cgroup *root_cgrp = kf_root->kn->priv;
810 return root_cgrp->root;
813 static int cgroup_init_root_id(struct cgroup_root *root)
817 lockdep_assert_held(&cgroup_mutex);
819 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
823 root->hierarchy_id = id;
827 static void cgroup_exit_root_id(struct cgroup_root *root)
829 lockdep_assert_held(&cgroup_mutex);
831 if (root->hierarchy_id) {
832 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
833 root->hierarchy_id = 0;
837 static void cgroup_free_root(struct cgroup_root *root)
840 /* hierarhcy ID shoulid already have been released */
841 WARN_ON_ONCE(root->hierarchy_id);
843 idr_destroy(&root->cgroup_idr);
848 static void cgroup_destroy_root(struct cgroup_root *root)
850 struct cgroup *cgrp = &root->cgrp;
851 struct cgrp_cset_link *link, *tmp_link;
853 mutex_lock(&cgroup_tree_mutex);
854 mutex_lock(&cgroup_mutex);
856 BUG_ON(atomic_read(&root->nr_cgrps));
857 BUG_ON(!list_empty(&cgrp->children));
859 /* Rebind all subsystems back to the default hierarchy */
860 rebind_subsystems(&cgrp_dfl_root, root->subsys_mask);
863 * Release all the links from cset_links to this hierarchy's
866 down_write(&css_set_rwsem);
868 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
869 list_del(&link->cset_link);
870 list_del(&link->cgrp_link);
873 up_write(&css_set_rwsem);
875 if (!list_empty(&root->root_list)) {
876 list_del(&root->root_list);
880 cgroup_exit_root_id(root);
882 mutex_unlock(&cgroup_mutex);
883 mutex_unlock(&cgroup_tree_mutex);
885 kernfs_destroy_root(root->kf_root);
886 cgroup_free_root(root);
889 /* look up cgroup associated with given css_set on the specified hierarchy */
890 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
891 struct cgroup_root *root)
893 struct cgroup *res = NULL;
895 lockdep_assert_held(&cgroup_mutex);
896 lockdep_assert_held(&css_set_rwsem);
898 if (cset == &init_css_set) {
901 struct cgrp_cset_link *link;
903 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
904 struct cgroup *c = link->cgrp;
906 if (c->root == root) {
918 * Return the cgroup for "task" from the given hierarchy. Must be
919 * called with cgroup_mutex and css_set_rwsem held.
921 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
922 struct cgroup_root *root)
925 * No need to lock the task - since we hold cgroup_mutex the
926 * task can't change groups, so the only thing that can happen
927 * is that it exits and its css is set back to init_css_set.
929 return cset_cgroup_from_root(task_css_set(task), root);
933 * A task must hold cgroup_mutex to modify cgroups.
935 * Any task can increment and decrement the count field without lock.
936 * So in general, code holding cgroup_mutex can't rely on the count
937 * field not changing. However, if the count goes to zero, then only
938 * cgroup_attach_task() can increment it again. Because a count of zero
939 * means that no tasks are currently attached, therefore there is no
940 * way a task attached to that cgroup can fork (the other way to
941 * increment the count). So code holding cgroup_mutex can safely
942 * assume that if the count is zero, it will stay zero. Similarly, if
943 * a task holds cgroup_mutex on a cgroup with zero count, it
944 * knows that the cgroup won't be removed, as cgroup_rmdir()
947 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
948 * (usually) take cgroup_mutex. These are the two most performance
949 * critical pieces of code here. The exception occurs on cgroup_exit(),
950 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
951 * is taken, and if the cgroup count is zero, a usermode call made
952 * to the release agent with the name of the cgroup (path relative to
953 * the root of cgroup file system) as the argument.
955 * A cgroup can only be deleted if both its 'count' of using tasks
956 * is zero, and its list of 'children' cgroups is empty. Since all
957 * tasks in the system use _some_ cgroup, and since there is always at
958 * least one task in the system (init, pid == 1), therefore, root cgroup
959 * always has either children cgroups and/or using tasks. So we don't
960 * need a special hack to ensure that root cgroup cannot be deleted.
962 * P.S. One more locking exception. RCU is used to guard the
963 * update of a tasks cgroup pointer by cgroup_attach_task()
966 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned int subsys_mask);
967 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
968 static const struct file_operations proc_cgroupstats_operations;
970 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
973 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
974 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
975 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
976 cft->ss->name, cft->name);
978 strncpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
983 * cgroup_file_mode - deduce file mode of a control file
984 * @cft: the control file in question
986 * returns cft->mode if ->mode is not 0
987 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
988 * returns S_IRUGO if it has only a read handler
989 * returns S_IWUSR if it has only a write hander
991 static umode_t cgroup_file_mode(const struct cftype *cft)
998 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1001 if (cft->write_u64 || cft->write_s64 || cft->write_string ||
1008 static void cgroup_free_fn(struct work_struct *work)
1010 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
1012 atomic_dec(&cgrp->root->nr_cgrps);
1013 cgroup_pidlist_destroy_all(cgrp);
1017 * We get a ref to the parent, and put the ref when this
1018 * cgroup is being freed, so it's guaranteed that the
1019 * parent won't be destroyed before its children.
1021 cgroup_put(cgrp->parent);
1022 kernfs_put(cgrp->kn);
1026 * This is root cgroup's refcnt reaching zero, which
1027 * indicates that the root should be released.
1029 cgroup_destroy_root(cgrp->root);
1033 static void cgroup_free_rcu(struct rcu_head *head)
1035 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
1037 INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
1038 queue_work(cgroup_destroy_wq, &cgrp->destroy_work);
1041 static void cgroup_get(struct cgroup *cgrp)
1043 WARN_ON_ONCE(cgroup_is_dead(cgrp));
1044 WARN_ON_ONCE(atomic_read(&cgrp->refcnt) <= 0);
1045 atomic_inc(&cgrp->refcnt);
1048 static void cgroup_put(struct cgroup *cgrp)
1050 if (!atomic_dec_and_test(&cgrp->refcnt))
1052 if (WARN_ON_ONCE(cgrp->parent && !cgroup_is_dead(cgrp)))
1056 * XXX: cgrp->id is only used to look up css's. As cgroup and
1057 * css's lifetimes will be decoupled, it should be made
1058 * per-subsystem and moved to css->id so that lookups are
1059 * successful until the target css is released.
1061 mutex_lock(&cgroup_mutex);
1062 idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
1063 mutex_unlock(&cgroup_mutex);
1066 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
1069 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1071 char name[CGROUP_FILE_NAME_MAX];
1073 lockdep_assert_held(&cgroup_tree_mutex);
1074 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1078 * cgroup_clear_dir - remove subsys files in a cgroup directory
1079 * @cgrp: target cgroup
1080 * @subsys_mask: mask of the subsystem ids whose files should be removed
1082 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned int subsys_mask)
1084 struct cgroup_subsys *ss;
1087 for_each_subsys(ss, i) {
1088 struct cftype *cfts;
1090 if (!(subsys_mask & (1 << i)))
1092 list_for_each_entry(cfts, &ss->cfts, node)
1093 cgroup_addrm_files(cgrp, cfts, false);
1097 static int rebind_subsystems(struct cgroup_root *dst_root, unsigned int ss_mask)
1099 struct cgroup_subsys *ss;
1102 lockdep_assert_held(&cgroup_tree_mutex);
1103 lockdep_assert_held(&cgroup_mutex);
1105 for_each_subsys(ss, ssid) {
1106 if (!(ss_mask & (1 << ssid)))
1109 /* if @ss has non-root csses attached to it, can't move */
1110 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)))
1113 /* can't move between two non-dummy roots either */
1114 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1118 ret = cgroup_populate_dir(&dst_root->cgrp, ss_mask);
1120 if (dst_root != &cgrp_dfl_root)
1124 * Rebinding back to the default root is not allowed to
1125 * fail. Using both default and non-default roots should
1126 * be rare. Moving subsystems back and forth even more so.
1127 * Just warn about it and continue.
1129 if (cgrp_dfl_root_visible) {
1130 pr_warn("failed to create files (%d) while rebinding 0x%x to default root\n",
1132 pr_warn("you may retry by moving them to a different hierarchy and unbinding\n");
1137 * Nothing can fail from this point on. Remove files for the
1138 * removed subsystems and rebind each subsystem.
1140 mutex_unlock(&cgroup_mutex);
1141 for_each_subsys(ss, ssid)
1142 if (ss_mask & (1 << ssid))
1143 cgroup_clear_dir(&ss->root->cgrp, 1 << ssid);
1144 mutex_lock(&cgroup_mutex);
1146 for_each_subsys(ss, ssid) {
1147 struct cgroup_root *src_root;
1148 struct cgroup_subsys_state *css;
1149 struct css_set *cset;
1151 if (!(ss_mask & (1 << ssid)))
1154 src_root = ss->root;
1155 css = cgroup_css(&src_root->cgrp, ss);
1157 WARN_ON(!css || cgroup_css(&dst_root->cgrp, ss));
1159 RCU_INIT_POINTER(src_root->cgrp.subsys[ssid], NULL);
1160 rcu_assign_pointer(dst_root->cgrp.subsys[ssid], css);
1161 ss->root = dst_root;
1162 css->cgroup = &dst_root->cgrp;
1164 down_write(&css_set_rwsem);
1165 hash_for_each(css_set_table, i, cset, hlist)
1166 list_move_tail(&cset->e_cset_node[ss->id],
1167 &dst_root->cgrp.e_csets[ss->id]);
1168 up_write(&css_set_rwsem);
1170 src_root->subsys_mask &= ~(1 << ssid);
1171 src_root->cgrp.child_subsys_mask &= ~(1 << ssid);
1173 /* default hierarchy doesn't enable controllers by default */
1174 dst_root->subsys_mask |= 1 << ssid;
1175 if (dst_root != &cgrp_dfl_root)
1176 dst_root->cgrp.child_subsys_mask |= 1 << ssid;
1182 kernfs_activate(dst_root->cgrp.kn);
1186 static int cgroup_show_options(struct seq_file *seq,
1187 struct kernfs_root *kf_root)
1189 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1190 struct cgroup_subsys *ss;
1193 for_each_subsys(ss, ssid)
1194 if (root->subsys_mask & (1 << ssid))
1195 seq_printf(seq, ",%s", ss->name);
1196 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1197 seq_puts(seq, ",sane_behavior");
1198 if (root->flags & CGRP_ROOT_NOPREFIX)
1199 seq_puts(seq, ",noprefix");
1200 if (root->flags & CGRP_ROOT_XATTR)
1201 seq_puts(seq, ",xattr");
1203 spin_lock(&release_agent_path_lock);
1204 if (strlen(root->release_agent_path))
1205 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1206 spin_unlock(&release_agent_path_lock);
1208 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags))
1209 seq_puts(seq, ",clone_children");
1210 if (strlen(root->name))
1211 seq_printf(seq, ",name=%s", root->name);
1215 struct cgroup_sb_opts {
1216 unsigned int subsys_mask;
1218 char *release_agent;
1219 bool cpuset_clone_children;
1221 /* User explicitly requested empty subsystem */
1225 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1227 char *token, *o = data;
1228 bool all_ss = false, one_ss = false;
1229 unsigned int mask = -1U;
1230 struct cgroup_subsys *ss;
1233 #ifdef CONFIG_CPUSETS
1234 mask = ~(1U << cpuset_cgrp_id);
1237 memset(opts, 0, sizeof(*opts));
1239 while ((token = strsep(&o, ",")) != NULL) {
1242 if (!strcmp(token, "none")) {
1243 /* Explicitly have no subsystems */
1247 if (!strcmp(token, "all")) {
1248 /* Mutually exclusive option 'all' + subsystem name */
1254 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1255 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1258 if (!strcmp(token, "noprefix")) {
1259 opts->flags |= CGRP_ROOT_NOPREFIX;
1262 if (!strcmp(token, "clone_children")) {
1263 opts->cpuset_clone_children = true;
1266 if (!strcmp(token, "xattr")) {
1267 opts->flags |= CGRP_ROOT_XATTR;
1270 if (!strncmp(token, "release_agent=", 14)) {
1271 /* Specifying two release agents is forbidden */
1272 if (opts->release_agent)
1274 opts->release_agent =
1275 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1276 if (!opts->release_agent)
1280 if (!strncmp(token, "name=", 5)) {
1281 const char *name = token + 5;
1282 /* Can't specify an empty name */
1285 /* Must match [\w.-]+ */
1286 for (i = 0; i < strlen(name); i++) {
1290 if ((c == '.') || (c == '-') || (c == '_'))
1294 /* Specifying two names is forbidden */
1297 opts->name = kstrndup(name,
1298 MAX_CGROUP_ROOT_NAMELEN - 1,
1306 for_each_subsys(ss, i) {
1307 if (strcmp(token, ss->name))
1312 /* Mutually exclusive option 'all' + subsystem name */
1315 opts->subsys_mask |= (1 << i);
1320 if (i == CGROUP_SUBSYS_COUNT)
1324 /* Consistency checks */
1326 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1327 pr_warn("sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1329 if ((opts->flags & (CGRP_ROOT_NOPREFIX | CGRP_ROOT_XATTR)) ||
1330 opts->cpuset_clone_children || opts->release_agent ||
1332 pr_err("sane_behavior: noprefix, xattr, clone_children, release_agent and name are not allowed\n");
1337 * If the 'all' option was specified select all the
1338 * subsystems, otherwise if 'none', 'name=' and a subsystem
1339 * name options were not specified, let's default to 'all'
1341 if (all_ss || (!one_ss && !opts->none && !opts->name))
1342 for_each_subsys(ss, i)
1344 opts->subsys_mask |= (1 << i);
1347 * We either have to specify by name or by subsystems. (So
1348 * all empty hierarchies must have a name).
1350 if (!opts->subsys_mask && !opts->name)
1355 * Option noprefix was introduced just for backward compatibility
1356 * with the old cpuset, so we allow noprefix only if mounting just
1357 * the cpuset subsystem.
1359 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1363 /* Can't specify "none" and some subsystems */
1364 if (opts->subsys_mask && opts->none)
1370 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1373 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1374 struct cgroup_sb_opts opts;
1375 unsigned int added_mask, removed_mask;
1377 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1378 pr_err("sane_behavior: remount is not allowed\n");
1382 mutex_lock(&cgroup_tree_mutex);
1383 mutex_lock(&cgroup_mutex);
1385 /* See what subsystems are wanted */
1386 ret = parse_cgroupfs_options(data, &opts);
1390 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1391 pr_warn("option changes via remount are deprecated (pid=%d comm=%s)\n",
1392 task_tgid_nr(current), current->comm);
1394 added_mask = opts.subsys_mask & ~root->subsys_mask;
1395 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1397 /* Don't allow flags or name to change at remount */
1398 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1399 (opts.name && strcmp(opts.name, root->name))) {
1400 pr_err("option or name mismatch, new: 0x%x \"%s\", old: 0x%x \"%s\"\n",
1401 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1402 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1407 /* remounting is not allowed for populated hierarchies */
1408 if (!list_empty(&root->cgrp.children)) {
1413 ret = rebind_subsystems(root, added_mask);
1417 rebind_subsystems(&cgrp_dfl_root, removed_mask);
1419 if (opts.release_agent) {
1420 spin_lock(&release_agent_path_lock);
1421 strcpy(root->release_agent_path, opts.release_agent);
1422 spin_unlock(&release_agent_path_lock);
1425 kfree(opts.release_agent);
1427 mutex_unlock(&cgroup_mutex);
1428 mutex_unlock(&cgroup_tree_mutex);
1433 * To reduce the fork() overhead for systems that are not actually using
1434 * their cgroups capability, we don't maintain the lists running through
1435 * each css_set to its tasks until we see the list actually used - in other
1436 * words after the first mount.
1438 static bool use_task_css_set_links __read_mostly;
1440 static void cgroup_enable_task_cg_lists(void)
1442 struct task_struct *p, *g;
1444 down_write(&css_set_rwsem);
1446 if (use_task_css_set_links)
1449 use_task_css_set_links = true;
1452 * We need tasklist_lock because RCU is not safe against
1453 * while_each_thread(). Besides, a forking task that has passed
1454 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1455 * is not guaranteed to have its child immediately visible in the
1456 * tasklist if we walk through it with RCU.
1458 read_lock(&tasklist_lock);
1459 do_each_thread(g, p) {
1460 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1461 task_css_set(p) != &init_css_set);
1464 * We should check if the process is exiting, otherwise
1465 * it will race with cgroup_exit() in that the list
1466 * entry won't be deleted though the process has exited.
1467 * Do it while holding siglock so that we don't end up
1468 * racing against cgroup_exit().
1470 spin_lock_irq(&p->sighand->siglock);
1471 if (!(p->flags & PF_EXITING)) {
1472 struct css_set *cset = task_css_set(p);
1474 list_add(&p->cg_list, &cset->tasks);
1477 spin_unlock_irq(&p->sighand->siglock);
1478 } while_each_thread(g, p);
1479 read_unlock(&tasklist_lock);
1481 up_write(&css_set_rwsem);
1484 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1486 struct cgroup_subsys *ss;
1489 atomic_set(&cgrp->refcnt, 1);
1490 INIT_LIST_HEAD(&cgrp->sibling);
1491 INIT_LIST_HEAD(&cgrp->children);
1492 INIT_LIST_HEAD(&cgrp->cset_links);
1493 INIT_LIST_HEAD(&cgrp->release_list);
1494 INIT_LIST_HEAD(&cgrp->pidlists);
1495 mutex_init(&cgrp->pidlist_mutex);
1496 cgrp->dummy_css.cgroup = cgrp;
1498 for_each_subsys(ss, ssid)
1499 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
1501 init_waitqueue_head(&cgrp->offline_waitq);
1504 static void init_cgroup_root(struct cgroup_root *root,
1505 struct cgroup_sb_opts *opts)
1507 struct cgroup *cgrp = &root->cgrp;
1509 INIT_LIST_HEAD(&root->root_list);
1510 atomic_set(&root->nr_cgrps, 1);
1512 init_cgroup_housekeeping(cgrp);
1513 idr_init(&root->cgroup_idr);
1515 root->flags = opts->flags;
1516 if (opts->release_agent)
1517 strcpy(root->release_agent_path, opts->release_agent);
1519 strcpy(root->name, opts->name);
1520 if (opts->cpuset_clone_children)
1521 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1524 static int cgroup_setup_root(struct cgroup_root *root, unsigned int ss_mask)
1526 LIST_HEAD(tmp_links);
1527 struct cgroup *root_cgrp = &root->cgrp;
1528 struct css_set *cset;
1531 lockdep_assert_held(&cgroup_tree_mutex);
1532 lockdep_assert_held(&cgroup_mutex);
1534 ret = idr_alloc(&root->cgroup_idr, root_cgrp, 0, 1, GFP_KERNEL);
1537 root_cgrp->id = ret;
1540 * We're accessing css_set_count without locking css_set_rwsem here,
1541 * but that's OK - it can only be increased by someone holding
1542 * cgroup_lock, and that's us. The worst that can happen is that we
1543 * have some link structures left over
1545 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1549 ret = cgroup_init_root_id(root);
1553 root->kf_root = kernfs_create_root(&cgroup_kf_syscall_ops,
1554 KERNFS_ROOT_CREATE_DEACTIVATED,
1556 if (IS_ERR(root->kf_root)) {
1557 ret = PTR_ERR(root->kf_root);
1560 root_cgrp->kn = root->kf_root->kn;
1562 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1566 ret = rebind_subsystems(root, ss_mask);
1571 * There must be no failure case after here, since rebinding takes
1572 * care of subsystems' refcounts, which are explicitly dropped in
1573 * the failure exit path.
1575 list_add(&root->root_list, &cgroup_roots);
1576 cgroup_root_count++;
1579 * Link the root cgroup in this hierarchy into all the css_set
1582 down_write(&css_set_rwsem);
1583 hash_for_each(css_set_table, i, cset, hlist)
1584 link_css_set(&tmp_links, cset, root_cgrp);
1585 up_write(&css_set_rwsem);
1587 BUG_ON(!list_empty(&root_cgrp->children));
1588 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
1590 kernfs_activate(root_cgrp->kn);
1595 kernfs_destroy_root(root->kf_root);
1596 root->kf_root = NULL;
1598 cgroup_exit_root_id(root);
1600 free_cgrp_cset_links(&tmp_links);
1604 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1605 int flags, const char *unused_dev_name,
1608 struct cgroup_root *root;
1609 struct cgroup_sb_opts opts;
1610 struct dentry *dentry;
1615 * The first time anyone tries to mount a cgroup, enable the list
1616 * linking each css_set to its tasks and fix up all existing tasks.
1618 if (!use_task_css_set_links)
1619 cgroup_enable_task_cg_lists();
1621 mutex_lock(&cgroup_tree_mutex);
1622 mutex_lock(&cgroup_mutex);
1624 /* First find the desired set of subsystems */
1625 ret = parse_cgroupfs_options(data, &opts);
1629 /* look for a matching existing root */
1630 if (!opts.subsys_mask && !opts.none && !opts.name) {
1631 cgrp_dfl_root_visible = true;
1632 root = &cgrp_dfl_root;
1633 cgroup_get(&root->cgrp);
1638 for_each_root(root) {
1639 bool name_match = false;
1641 if (root == &cgrp_dfl_root)
1645 * If we asked for a name then it must match. Also, if
1646 * name matches but sybsys_mask doesn't, we should fail.
1647 * Remember whether name matched.
1650 if (strcmp(opts.name, root->name))
1656 * If we asked for subsystems (or explicitly for no
1657 * subsystems) then they must match.
1659 if ((opts.subsys_mask || opts.none) &&
1660 (opts.subsys_mask != root->subsys_mask)) {
1667 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1668 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1669 pr_err("sane_behavior: new mount options should match the existing superblock\n");
1673 pr_warn("new mount options do not match the existing superblock, will be ignored\n");
1678 * A root's lifetime is governed by its root cgroup. Zero
1679 * ref indicate that the root is being destroyed. Wait for
1680 * destruction to complete so that the subsystems are free.
1681 * We can use wait_queue for the wait but this path is
1682 * super cold. Let's just sleep for a bit and retry.
1684 if (!atomic_inc_not_zero(&root->cgrp.refcnt)) {
1685 mutex_unlock(&cgroup_mutex);
1686 mutex_unlock(&cgroup_tree_mutex);
1688 mutex_lock(&cgroup_tree_mutex);
1689 mutex_lock(&cgroup_mutex);
1698 * No such thing, create a new one. name= matching without subsys
1699 * specification is allowed for already existing hierarchies but we
1700 * can't create new one without subsys specification.
1702 if (!opts.subsys_mask && !opts.none) {
1707 root = kzalloc(sizeof(*root), GFP_KERNEL);
1713 init_cgroup_root(root, &opts);
1715 ret = cgroup_setup_root(root, opts.subsys_mask);
1717 cgroup_free_root(root);
1720 mutex_unlock(&cgroup_mutex);
1721 mutex_unlock(&cgroup_tree_mutex);
1723 kfree(opts.release_agent);
1727 return ERR_PTR(ret);
1729 dentry = kernfs_mount(fs_type, flags, root->kf_root, &new_sb);
1730 if (IS_ERR(dentry) || !new_sb)
1731 cgroup_put(&root->cgrp);
1735 static void cgroup_kill_sb(struct super_block *sb)
1737 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
1738 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1740 cgroup_put(&root->cgrp);
1744 static struct file_system_type cgroup_fs_type = {
1746 .mount = cgroup_mount,
1747 .kill_sb = cgroup_kill_sb,
1750 static struct kobject *cgroup_kobj;
1753 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1754 * @task: target task
1755 * @buf: the buffer to write the path into
1756 * @buflen: the length of the buffer
1758 * Determine @task's cgroup on the first (the one with the lowest non-zero
1759 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1760 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1761 * cgroup controller callbacks.
1763 * Return value is the same as kernfs_path().
1765 char *task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1767 struct cgroup_root *root;
1768 struct cgroup *cgrp;
1769 int hierarchy_id = 1;
1772 mutex_lock(&cgroup_mutex);
1773 down_read(&css_set_rwsem);
1775 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1778 cgrp = task_cgroup_from_root(task, root);
1779 path = cgroup_path(cgrp, buf, buflen);
1781 /* if no hierarchy exists, everyone is in "/" */
1782 if (strlcpy(buf, "/", buflen) < buflen)
1786 up_read(&css_set_rwsem);
1787 mutex_unlock(&cgroup_mutex);
1790 EXPORT_SYMBOL_GPL(task_cgroup_path);
1792 /* used to track tasks and other necessary states during migration */
1793 struct cgroup_taskset {
1794 /* the src and dst cset list running through cset->mg_node */
1795 struct list_head src_csets;
1796 struct list_head dst_csets;
1799 * Fields for cgroup_taskset_*() iteration.
1801 * Before migration is committed, the target migration tasks are on
1802 * ->mg_tasks of the csets on ->src_csets. After, on ->mg_tasks of
1803 * the csets on ->dst_csets. ->csets point to either ->src_csets
1804 * or ->dst_csets depending on whether migration is committed.
1806 * ->cur_csets and ->cur_task point to the current task position
1809 struct list_head *csets;
1810 struct css_set *cur_cset;
1811 struct task_struct *cur_task;
1815 * cgroup_taskset_first - reset taskset and return the first task
1816 * @tset: taskset of interest
1818 * @tset iteration is initialized and the first task is returned.
1820 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1822 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
1823 tset->cur_task = NULL;
1825 return cgroup_taskset_next(tset);
1829 * cgroup_taskset_next - iterate to the next task in taskset
1830 * @tset: taskset of interest
1832 * Return the next task in @tset. Iteration must have been initialized
1833 * with cgroup_taskset_first().
1835 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1837 struct css_set *cset = tset->cur_cset;
1838 struct task_struct *task = tset->cur_task;
1840 while (&cset->mg_node != tset->csets) {
1842 task = list_first_entry(&cset->mg_tasks,
1843 struct task_struct, cg_list);
1845 task = list_next_entry(task, cg_list);
1847 if (&task->cg_list != &cset->mg_tasks) {
1848 tset->cur_cset = cset;
1849 tset->cur_task = task;
1853 cset = list_next_entry(cset, mg_node);
1861 * cgroup_task_migrate - move a task from one cgroup to another.
1862 * @old_cgrp; the cgroup @tsk is being migrated from
1863 * @tsk: the task being migrated
1864 * @new_cset: the new css_set @tsk is being attached to
1866 * Must be called with cgroup_mutex, threadgroup and css_set_rwsem locked.
1868 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1869 struct task_struct *tsk,
1870 struct css_set *new_cset)
1872 struct css_set *old_cset;
1874 lockdep_assert_held(&cgroup_mutex);
1875 lockdep_assert_held(&css_set_rwsem);
1878 * We are synchronized through threadgroup_lock() against PF_EXITING
1879 * setting such that we can't race against cgroup_exit() changing the
1880 * css_set to init_css_set and dropping the old one.
1882 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1883 old_cset = task_css_set(tsk);
1885 get_css_set(new_cset);
1886 rcu_assign_pointer(tsk->cgroups, new_cset);
1889 * Use move_tail so that cgroup_taskset_first() still returns the
1890 * leader after migration. This works because cgroup_migrate()
1891 * ensures that the dst_cset of the leader is the first on the
1892 * tset's dst_csets list.
1894 list_move_tail(&tsk->cg_list, &new_cset->mg_tasks);
1897 * We just gained a reference on old_cset by taking it from the
1898 * task. As trading it for new_cset is protected by cgroup_mutex,
1899 * we're safe to drop it here; it will be freed under RCU.
1901 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1902 put_css_set_locked(old_cset, false);
1906 * cgroup_migrate_finish - cleanup after attach
1907 * @preloaded_csets: list of preloaded css_sets
1909 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
1910 * those functions for details.
1912 static void cgroup_migrate_finish(struct list_head *preloaded_csets)
1914 struct css_set *cset, *tmp_cset;
1916 lockdep_assert_held(&cgroup_mutex);
1918 down_write(&css_set_rwsem);
1919 list_for_each_entry_safe(cset, tmp_cset, preloaded_csets, mg_preload_node) {
1920 cset->mg_src_cgrp = NULL;
1921 cset->mg_dst_cset = NULL;
1922 list_del_init(&cset->mg_preload_node);
1923 put_css_set_locked(cset, false);
1925 up_write(&css_set_rwsem);
1929 * cgroup_migrate_add_src - add a migration source css_set
1930 * @src_cset: the source css_set to add
1931 * @dst_cgrp: the destination cgroup
1932 * @preloaded_csets: list of preloaded css_sets
1934 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
1935 * @src_cset and add it to @preloaded_csets, which should later be cleaned
1936 * up by cgroup_migrate_finish().
1938 * This function may be called without holding threadgroup_lock even if the
1939 * target is a process. Threads may be created and destroyed but as long
1940 * as cgroup_mutex is not dropped, no new css_set can be put into play and
1941 * the preloaded css_sets are guaranteed to cover all migrations.
1943 static void cgroup_migrate_add_src(struct css_set *src_cset,
1944 struct cgroup *dst_cgrp,
1945 struct list_head *preloaded_csets)
1947 struct cgroup *src_cgrp;
1949 lockdep_assert_held(&cgroup_mutex);
1950 lockdep_assert_held(&css_set_rwsem);
1952 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
1954 if (!list_empty(&src_cset->mg_preload_node))
1957 WARN_ON(src_cset->mg_src_cgrp);
1958 WARN_ON(!list_empty(&src_cset->mg_tasks));
1959 WARN_ON(!list_empty(&src_cset->mg_node));
1961 src_cset->mg_src_cgrp = src_cgrp;
1962 get_css_set(src_cset);
1963 list_add(&src_cset->mg_preload_node, preloaded_csets);
1967 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
1968 * @dst_cgrp: the destination cgroup (may be %NULL)
1969 * @preloaded_csets: list of preloaded source css_sets
1971 * Tasks are about to be moved to @dst_cgrp and all the source css_sets
1972 * have been preloaded to @preloaded_csets. This function looks up and
1973 * pins all destination css_sets, links each to its source, and append them
1974 * to @preloaded_csets. If @dst_cgrp is %NULL, the destination of each
1975 * source css_set is assumed to be its cgroup on the default hierarchy.
1977 * This function must be called after cgroup_migrate_add_src() has been
1978 * called on each migration source css_set. After migration is performed
1979 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
1982 static int cgroup_migrate_prepare_dst(struct cgroup *dst_cgrp,
1983 struct list_head *preloaded_csets)
1986 struct css_set *src_cset, *tmp_cset;
1988 lockdep_assert_held(&cgroup_mutex);
1991 * Except for the root, child_subsys_mask must be zero for a cgroup
1992 * with tasks so that child cgroups don't compete against tasks.
1994 if (dst_cgrp && cgroup_on_dfl(dst_cgrp) && dst_cgrp->parent &&
1995 dst_cgrp->child_subsys_mask)
1998 /* look up the dst cset for each src cset and link it to src */
1999 list_for_each_entry_safe(src_cset, tmp_cset, preloaded_csets, mg_preload_node) {
2000 struct css_set *dst_cset;
2002 dst_cset = find_css_set(src_cset,
2003 dst_cgrp ?: src_cset->dfl_cgrp);
2007 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2010 * If src cset equals dst, it's noop. Drop the src.
2011 * cgroup_migrate() will skip the cset too. Note that we
2012 * can't handle src == dst as some nodes are used by both.
2014 if (src_cset == dst_cset) {
2015 src_cset->mg_src_cgrp = NULL;
2016 list_del_init(&src_cset->mg_preload_node);
2017 put_css_set(src_cset, false);
2018 put_css_set(dst_cset, false);
2022 src_cset->mg_dst_cset = dst_cset;
2024 if (list_empty(&dst_cset->mg_preload_node))
2025 list_add(&dst_cset->mg_preload_node, &csets);
2027 put_css_set(dst_cset, false);
2030 list_splice_tail(&csets, preloaded_csets);
2033 cgroup_migrate_finish(&csets);
2038 * cgroup_migrate - migrate a process or task to a cgroup
2039 * @cgrp: the destination cgroup
2040 * @leader: the leader of the process or the task to migrate
2041 * @threadgroup: whether @leader points to the whole process or a single task
2043 * Migrate a process or task denoted by @leader to @cgrp. If migrating a
2044 * process, the caller must be holding threadgroup_lock of @leader. The
2045 * caller is also responsible for invoking cgroup_migrate_add_src() and
2046 * cgroup_migrate_prepare_dst() on the targets before invoking this
2047 * function and following up with cgroup_migrate_finish().
2049 * As long as a controller's ->can_attach() doesn't fail, this function is
2050 * guaranteed to succeed. This means that, excluding ->can_attach()
2051 * failure, when migrating multiple targets, the success or failure can be
2052 * decided for all targets by invoking group_migrate_prepare_dst() before
2053 * actually starting migrating.
2055 static int cgroup_migrate(struct cgroup *cgrp, struct task_struct *leader,
2058 struct cgroup_taskset tset = {
2059 .src_csets = LIST_HEAD_INIT(tset.src_csets),
2060 .dst_csets = LIST_HEAD_INIT(tset.dst_csets),
2061 .csets = &tset.src_csets,
2063 struct cgroup_subsys_state *css, *failed_css = NULL;
2064 struct css_set *cset, *tmp_cset;
2065 struct task_struct *task, *tmp_task;
2069 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2070 * already PF_EXITING could be freed from underneath us unless we
2071 * take an rcu_read_lock.
2073 down_write(&css_set_rwsem);
2077 /* @task either already exited or can't exit until the end */
2078 if (task->flags & PF_EXITING)
2081 /* leave @task alone if post_fork() hasn't linked it yet */
2082 if (list_empty(&task->cg_list))
2085 cset = task_css_set(task);
2086 if (!cset->mg_src_cgrp)
2090 * cgroup_taskset_first() must always return the leader.
2091 * Take care to avoid disturbing the ordering.
2093 list_move_tail(&task->cg_list, &cset->mg_tasks);
2094 if (list_empty(&cset->mg_node))
2095 list_add_tail(&cset->mg_node, &tset.src_csets);
2096 if (list_empty(&cset->mg_dst_cset->mg_node))
2097 list_move_tail(&cset->mg_dst_cset->mg_node,
2102 } while_each_thread(leader, task);
2104 up_write(&css_set_rwsem);
2106 /* methods shouldn't be called if no task is actually migrating */
2107 if (list_empty(&tset.src_csets))
2110 /* check that we can legitimately attach to the cgroup */
2111 for_each_e_css(css, i, cgrp) {
2112 if (css->ss->can_attach) {
2113 ret = css->ss->can_attach(css, &tset);
2116 goto out_cancel_attach;
2122 * Now that we're guaranteed success, proceed to move all tasks to
2123 * the new cgroup. There are no failure cases after here, so this
2124 * is the commit point.
2126 down_write(&css_set_rwsem);
2127 list_for_each_entry(cset, &tset.src_csets, mg_node) {
2128 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list)
2129 cgroup_task_migrate(cset->mg_src_cgrp, task,
2132 up_write(&css_set_rwsem);
2135 * Migration is committed, all target tasks are now on dst_csets.
2136 * Nothing is sensitive to fork() after this point. Notify
2137 * controllers that migration is complete.
2139 tset.csets = &tset.dst_csets;
2141 for_each_e_css(css, i, cgrp)
2142 if (css->ss->attach)
2143 css->ss->attach(css, &tset);
2146 goto out_release_tset;
2149 for_each_e_css(css, i, cgrp) {
2150 if (css == failed_css)
2152 if (css->ss->cancel_attach)
2153 css->ss->cancel_attach(css, &tset);
2156 down_write(&css_set_rwsem);
2157 list_splice_init(&tset.dst_csets, &tset.src_csets);
2158 list_for_each_entry_safe(cset, tmp_cset, &tset.src_csets, mg_node) {
2159 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2160 list_del_init(&cset->mg_node);
2162 up_write(&css_set_rwsem);
2167 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2168 * @dst_cgrp: the cgroup to attach to
2169 * @leader: the task or the leader of the threadgroup to be attached
2170 * @threadgroup: attach the whole threadgroup?
2172 * Call holding cgroup_mutex and threadgroup_lock of @leader.
2174 static int cgroup_attach_task(struct cgroup *dst_cgrp,
2175 struct task_struct *leader, bool threadgroup)
2177 LIST_HEAD(preloaded_csets);
2178 struct task_struct *task;
2181 /* look up all src csets */
2182 down_read(&css_set_rwsem);
2186 cgroup_migrate_add_src(task_css_set(task), dst_cgrp,
2190 } while_each_thread(leader, task);
2192 up_read(&css_set_rwsem);
2194 /* prepare dst csets and commit */
2195 ret = cgroup_migrate_prepare_dst(dst_cgrp, &preloaded_csets);
2197 ret = cgroup_migrate(dst_cgrp, leader, threadgroup);
2199 cgroup_migrate_finish(&preloaded_csets);
2204 * Find the task_struct of the task to attach by vpid and pass it along to the
2205 * function to attach either it or all tasks in its threadgroup. Will lock
2206 * cgroup_mutex and threadgroup.
2208 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2210 struct task_struct *tsk;
2211 const struct cred *cred = current_cred(), *tcred;
2214 if (!cgroup_lock_live_group(cgrp))
2220 tsk = find_task_by_vpid(pid);
2224 goto out_unlock_cgroup;
2227 * even if we're attaching all tasks in the thread group, we
2228 * only need to check permissions on one of them.
2230 tcred = __task_cred(tsk);
2231 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2232 !uid_eq(cred->euid, tcred->uid) &&
2233 !uid_eq(cred->euid, tcred->suid)) {
2236 goto out_unlock_cgroup;
2242 tsk = tsk->group_leader;
2245 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2246 * trapped in a cpuset, or RT worker may be born in a cgroup
2247 * with no rt_runtime allocated. Just say no.
2249 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2252 goto out_unlock_cgroup;
2255 get_task_struct(tsk);
2258 threadgroup_lock(tsk);
2260 if (!thread_group_leader(tsk)) {
2262 * a race with de_thread from another thread's exec()
2263 * may strip us of our leadership, if this happens,
2264 * there is no choice but to throw this task away and
2265 * try again; this is
2266 * "double-double-toil-and-trouble-check locking".
2268 threadgroup_unlock(tsk);
2269 put_task_struct(tsk);
2270 goto retry_find_task;
2274 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2276 threadgroup_unlock(tsk);
2278 put_task_struct(tsk);
2280 mutex_unlock(&cgroup_mutex);
2285 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2286 * @from: attach to all cgroups of a given task
2287 * @tsk: the task to be attached
2289 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2291 struct cgroup_root *root;
2294 mutex_lock(&cgroup_mutex);
2295 for_each_root(root) {
2296 struct cgroup *from_cgrp;
2298 if (root == &cgrp_dfl_root)
2301 down_read(&css_set_rwsem);
2302 from_cgrp = task_cgroup_from_root(from, root);
2303 up_read(&css_set_rwsem);
2305 retval = cgroup_attach_task(from_cgrp, tsk, false);
2309 mutex_unlock(&cgroup_mutex);
2313 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2315 static int cgroup_tasks_write(struct cgroup_subsys_state *css,
2316 struct cftype *cft, u64 pid)
2318 return attach_task_by_pid(css->cgroup, pid, false);
2321 static int cgroup_procs_write(struct cgroup_subsys_state *css,
2322 struct cftype *cft, u64 tgid)
2324 return attach_task_by_pid(css->cgroup, tgid, true);
2327 static int cgroup_release_agent_write(struct cgroup_subsys_state *css,
2328 struct cftype *cft, char *buffer)
2330 struct cgroup_root *root = css->cgroup->root;
2332 BUILD_BUG_ON(sizeof(root->release_agent_path) < PATH_MAX);
2333 if (!cgroup_lock_live_group(css->cgroup))
2335 spin_lock(&release_agent_path_lock);
2336 strlcpy(root->release_agent_path, buffer,
2337 sizeof(root->release_agent_path));
2338 spin_unlock(&release_agent_path_lock);
2339 mutex_unlock(&cgroup_mutex);
2343 static int cgroup_release_agent_show(struct seq_file *seq, void *v)
2345 struct cgroup *cgrp = seq_css(seq)->cgroup;
2347 if (!cgroup_lock_live_group(cgrp))
2349 seq_puts(seq, cgrp->root->release_agent_path);
2350 seq_putc(seq, '\n');
2351 mutex_unlock(&cgroup_mutex);
2355 static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
2357 struct cgroup *cgrp = seq_css(seq)->cgroup;
2359 seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
2363 static void cgroup_print_ss_mask(struct seq_file *seq, unsigned int ss_mask)
2365 struct cgroup_subsys *ss;
2366 bool printed = false;
2369 for_each_subsys(ss, ssid) {
2370 if (ss_mask & (1 << ssid)) {
2373 seq_printf(seq, "%s", ss->name);
2378 seq_putc(seq, '\n');
2381 /* show controllers which are currently attached to the default hierarchy */
2382 static int cgroup_root_controllers_show(struct seq_file *seq, void *v)
2384 struct cgroup *cgrp = seq_css(seq)->cgroup;
2386 cgroup_print_ss_mask(seq, cgrp->root->subsys_mask);
2390 /* show controllers which are enabled from the parent */
2391 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2393 struct cgroup *cgrp = seq_css(seq)->cgroup;
2395 cgroup_print_ss_mask(seq, cgrp->parent->child_subsys_mask);
2399 /* show controllers which are enabled for a given cgroup's children */
2400 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2402 struct cgroup *cgrp = seq_css(seq)->cgroup;
2404 cgroup_print_ss_mask(seq, cgrp->child_subsys_mask);
2409 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2410 * @cgrp: root of the subtree to update csses for
2412 * @cgrp's child_subsys_mask has changed and its subtree's (self excluded)
2413 * css associations need to be updated accordingly. This function looks up
2414 * all css_sets which are attached to the subtree, creates the matching
2415 * updated css_sets and migrates the tasks to the new ones.
2417 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2419 LIST_HEAD(preloaded_csets);
2420 struct cgroup_subsys_state *css;
2421 struct css_set *src_cset;
2424 lockdep_assert_held(&cgroup_tree_mutex);
2425 lockdep_assert_held(&cgroup_mutex);
2427 /* look up all csses currently attached to @cgrp's subtree */
2428 down_read(&css_set_rwsem);
2429 css_for_each_descendant_pre(css, cgroup_css(cgrp, NULL)) {
2430 struct cgrp_cset_link *link;
2432 /* self is not affected by child_subsys_mask change */
2433 if (css->cgroup == cgrp)
2436 list_for_each_entry(link, &css->cgroup->cset_links, cset_link)
2437 cgroup_migrate_add_src(link->cset, cgrp,
2440 up_read(&css_set_rwsem);
2442 /* NULL dst indicates self on default hierarchy */
2443 ret = cgroup_migrate_prepare_dst(NULL, &preloaded_csets);
2447 list_for_each_entry(src_cset, &preloaded_csets, mg_preload_node) {
2448 struct task_struct *last_task = NULL, *task;
2450 /* src_csets precede dst_csets, break on the first dst_cset */
2451 if (!src_cset->mg_src_cgrp)
2455 * All tasks in src_cset need to be migrated to the
2456 * matching dst_cset. Empty it process by process. We
2457 * walk tasks but migrate processes. The leader might even
2458 * belong to a different cset but such src_cset would also
2459 * be among the target src_csets because the default
2460 * hierarchy enforces per-process membership.
2463 down_read(&css_set_rwsem);
2464 task = list_first_entry_or_null(&src_cset->tasks,
2465 struct task_struct, cg_list);
2467 task = task->group_leader;
2468 WARN_ON_ONCE(!task_css_set(task)->mg_src_cgrp);
2469 get_task_struct(task);
2471 up_read(&css_set_rwsem);
2476 /* guard against possible infinite loop */
2477 if (WARN(last_task == task,
2478 "cgroup: update_dfl_csses failed to make progress, aborting in inconsistent state\n"))
2482 threadgroup_lock(task);
2483 /* raced against de_thread() from another thread? */
2484 if (!thread_group_leader(task)) {
2485 threadgroup_unlock(task);
2486 put_task_struct(task);
2490 ret = cgroup_migrate(src_cset->dfl_cgrp, task, true);
2492 threadgroup_unlock(task);
2493 put_task_struct(task);
2495 if (WARN(ret, "cgroup: failed to update controllers for the default hierarchy (%d), further operations may crash or hang\n", ret))
2501 cgroup_migrate_finish(&preloaded_csets);
2505 /* change the enabled child controllers for a cgroup in the default hierarchy */
2506 static int cgroup_subtree_control_write(struct cgroup_subsys_state *dummy_css,
2507 struct cftype *cft, char *buffer)
2509 unsigned int enable_req = 0, disable_req = 0, enable, disable;
2510 struct cgroup *cgrp = dummy_css->cgroup, *child;
2511 struct cgroup_subsys *ss;
2516 * Parse input - white space separated list of subsystem names
2517 * prefixed with either + or -.
2520 while ((tok = strsep(&p, " \t\n"))) {
2521 for_each_subsys(ss, ssid) {
2522 if (ss->disabled || strcmp(tok + 1, ss->name))
2526 enable_req |= 1 << ssid;
2527 disable_req &= ~(1 << ssid);
2528 } else if (*tok == '-') {
2529 disable_req |= 1 << ssid;
2530 enable_req &= ~(1 << ssid);
2536 if (ssid == CGROUP_SUBSYS_COUNT)
2541 * We're gonna grab cgroup_tree_mutex which nests outside kernfs
2542 * active_ref. cgroup_lock_live_group() already provides enough
2543 * protection. Ensure @cgrp stays accessible and break the
2544 * active_ref protection.
2547 kernfs_break_active_protection(cgrp->control_kn);
2549 enable = enable_req;
2550 disable = disable_req;
2552 mutex_lock(&cgroup_tree_mutex);
2554 for_each_subsys(ss, ssid) {
2555 if (enable & (1 << ssid)) {
2556 if (cgrp->child_subsys_mask & (1 << ssid)) {
2557 enable &= ~(1 << ssid);
2562 * Because css offlining is asynchronous, userland
2563 * might try to re-enable the same controller while
2564 * the previous instance is still around. In such
2565 * cases, wait till it's gone using offline_waitq.
2567 cgroup_for_each_live_child(child, cgrp) {
2570 if (!cgroup_css(child, ss))
2573 prepare_to_wait(&child->offline_waitq, &wait,
2574 TASK_UNINTERRUPTIBLE);
2575 mutex_unlock(&cgroup_tree_mutex);
2577 finish_wait(&child->offline_waitq, &wait);
2581 /* unavailable or not enabled on the parent? */
2582 if (!(cgrp_dfl_root.subsys_mask & (1 << ssid)) ||
2584 !(cgrp->parent->child_subsys_mask & (1 << ssid)))) {
2586 goto out_unlock_tree;
2588 } else if (disable & (1 << ssid)) {
2589 if (!(cgrp->child_subsys_mask & (1 << ssid))) {
2590 disable &= ~(1 << ssid);
2594 /* a child has it enabled? */
2595 cgroup_for_each_live_child(child, cgrp) {
2596 if (child->child_subsys_mask & (1 << ssid)) {
2598 goto out_unlock_tree;
2604 if (!enable && !disable) {
2606 goto out_unlock_tree;
2609 if (!cgroup_lock_live_group(cgrp)) {
2611 goto out_unlock_tree;
2615 * Except for the root, child_subsys_mask must be zero for a cgroup
2616 * with tasks so that child cgroups don't compete against tasks.
2618 if (enable && cgrp->parent && !list_empty(&cgrp->cset_links)) {
2624 * Create csses for enables and update child_subsys_mask. This
2625 * changes cgroup_e_css() results which in turn makes the
2626 * subsequent cgroup_update_dfl_csses() associate all tasks in the
2627 * subtree to the updated csses.
2629 for_each_subsys(ss, ssid) {
2630 if (!(enable & (1 << ssid)))
2633 cgroup_for_each_live_child(child, cgrp) {
2634 ret = create_css(child, ss);
2640 cgrp->child_subsys_mask |= enable;
2641 cgrp->child_subsys_mask &= ~disable;
2643 ret = cgroup_update_dfl_csses(cgrp);
2647 /* all tasks are now migrated away from the old csses, kill them */
2648 for_each_subsys(ss, ssid) {
2649 if (!(disable & (1 << ssid)))
2652 cgroup_for_each_live_child(child, cgrp)
2653 kill_css(cgroup_css(child, ss));
2656 kernfs_activate(cgrp->kn);
2659 mutex_unlock(&cgroup_mutex);
2661 mutex_unlock(&cgroup_tree_mutex);
2662 kernfs_unbreak_active_protection(cgrp->control_kn);
2667 cgrp->child_subsys_mask &= ~enable;
2668 cgrp->child_subsys_mask |= disable;
2670 for_each_subsys(ss, ssid) {
2671 if (!(enable & (1 << ssid)))
2674 cgroup_for_each_live_child(child, cgrp) {
2675 struct cgroup_subsys_state *css = cgroup_css(child, ss);
2683 static int cgroup_populated_show(struct seq_file *seq, void *v)
2685 seq_printf(seq, "%d\n", (bool)seq_css(seq)->cgroup->populated_cnt);
2689 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
2690 size_t nbytes, loff_t off)
2692 struct cgroup *cgrp = of->kn->parent->priv;
2693 struct cftype *cft = of->kn->priv;
2694 struct cgroup_subsys_state *css;
2698 * kernfs guarantees that a file isn't deleted with operations in
2699 * flight, which means that the matching css is and stays alive and
2700 * doesn't need to be pinned. The RCU locking is not necessary
2701 * either. It's just for the convenience of using cgroup_css().
2704 css = cgroup_css(cgrp, cft->ss);
2707 if (cft->write_string) {
2708 ret = cft->write_string(css, cft, strstrip(buf));
2709 } else if (cft->write_u64) {
2710 unsigned long long v;
2711 ret = kstrtoull(buf, 0, &v);
2713 ret = cft->write_u64(css, cft, v);
2714 } else if (cft->write_s64) {
2716 ret = kstrtoll(buf, 0, &v);
2718 ret = cft->write_s64(css, cft, v);
2719 } else if (cft->trigger) {
2720 ret = cft->trigger(css, (unsigned int)cft->private);
2725 return ret ?: nbytes;
2728 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
2730 return seq_cft(seq)->seq_start(seq, ppos);
2733 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
2735 return seq_cft(seq)->seq_next(seq, v, ppos);
2738 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
2740 seq_cft(seq)->seq_stop(seq, v);
2743 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2745 struct cftype *cft = seq_cft(m);
2746 struct cgroup_subsys_state *css = seq_css(m);
2749 return cft->seq_show(m, arg);
2752 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
2753 else if (cft->read_s64)
2754 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
2760 static struct kernfs_ops cgroup_kf_single_ops = {
2761 .atomic_write_len = PAGE_SIZE,
2762 .write = cgroup_file_write,
2763 .seq_show = cgroup_seqfile_show,
2766 static struct kernfs_ops cgroup_kf_ops = {
2767 .atomic_write_len = PAGE_SIZE,
2768 .write = cgroup_file_write,
2769 .seq_start = cgroup_seqfile_start,
2770 .seq_next = cgroup_seqfile_next,
2771 .seq_stop = cgroup_seqfile_stop,
2772 .seq_show = cgroup_seqfile_show,
2776 * cgroup_rename - Only allow simple rename of directories in place.
2778 static int cgroup_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
2779 const char *new_name_str)
2781 struct cgroup *cgrp = kn->priv;
2784 if (kernfs_type(kn) != KERNFS_DIR)
2786 if (kn->parent != new_parent)
2790 * This isn't a proper migration and its usefulness is very
2791 * limited. Disallow if sane_behavior.
2793 if (cgroup_sane_behavior(cgrp))
2797 * We're gonna grab cgroup_tree_mutex which nests outside kernfs
2798 * active_ref. kernfs_rename() doesn't require active_ref
2799 * protection. Break them before grabbing cgroup_tree_mutex.
2801 kernfs_break_active_protection(new_parent);
2802 kernfs_break_active_protection(kn);
2804 mutex_lock(&cgroup_tree_mutex);
2805 mutex_lock(&cgroup_mutex);
2807 ret = kernfs_rename(kn, new_parent, new_name_str);
2809 mutex_unlock(&cgroup_mutex);
2810 mutex_unlock(&cgroup_tree_mutex);
2812 kernfs_unbreak_active_protection(kn);
2813 kernfs_unbreak_active_protection(new_parent);
2817 /* set uid and gid of cgroup dirs and files to that of the creator */
2818 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
2820 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
2821 .ia_uid = current_fsuid(),
2822 .ia_gid = current_fsgid(), };
2824 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
2825 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
2828 return kernfs_setattr(kn, &iattr);
2831 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2833 char name[CGROUP_FILE_NAME_MAX];
2834 struct kernfs_node *kn;
2835 struct lock_class_key *key = NULL;
2838 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2839 key = &cft->lockdep_key;
2841 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
2842 cgroup_file_mode(cft), 0, cft->kf_ops, cft,
2847 ret = cgroup_kn_set_ugid(kn);
2853 if (cft->seq_show == cgroup_subtree_control_show)
2854 cgrp->control_kn = kn;
2855 else if (cft->seq_show == cgroup_populated_show)
2856 cgrp->populated_kn = kn;
2861 * cgroup_addrm_files - add or remove files to a cgroup directory
2862 * @cgrp: the target cgroup
2863 * @cfts: array of cftypes to be added
2864 * @is_add: whether to add or remove
2866 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2867 * For removals, this function never fails. If addition fails, this
2868 * function doesn't remove files already added. The caller is responsible
2871 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2877 lockdep_assert_held(&cgroup_tree_mutex);
2879 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2880 /* does cft->flags tell us to skip this file on @cgrp? */
2881 if ((cft->flags & CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
2883 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2885 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2887 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2891 ret = cgroup_add_file(cgrp, cft);
2893 pr_warn("%s: failed to add %s, err=%d\n",
2894 __func__, cft->name, ret);
2898 cgroup_rm_file(cgrp, cft);
2904 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
2907 struct cgroup_subsys *ss = cfts[0].ss;
2908 struct cgroup *root = &ss->root->cgrp;
2909 struct cgroup_subsys_state *css;
2912 lockdep_assert_held(&cgroup_tree_mutex);
2914 /* add/rm files for all cgroups created before */
2915 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2916 struct cgroup *cgrp = css->cgroup;
2918 if (cgroup_is_dead(cgrp))
2921 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2927 kernfs_activate(root->kn);
2931 static void cgroup_exit_cftypes(struct cftype *cfts)
2935 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2936 /* free copy for custom atomic_write_len, see init_cftypes() */
2937 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
2944 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2948 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2949 struct kernfs_ops *kf_ops;
2951 WARN_ON(cft->ss || cft->kf_ops);
2954 kf_ops = &cgroup_kf_ops;
2956 kf_ops = &cgroup_kf_single_ops;
2959 * Ugh... if @cft wants a custom max_write_len, we need to
2960 * make a copy of kf_ops to set its atomic_write_len.
2962 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
2963 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
2965 cgroup_exit_cftypes(cfts);
2968 kf_ops->atomic_write_len = cft->max_write_len;
2971 cft->kf_ops = kf_ops;
2978 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
2980 lockdep_assert_held(&cgroup_tree_mutex);
2982 if (!cfts || !cfts[0].ss)
2985 list_del(&cfts->node);
2986 cgroup_apply_cftypes(cfts, false);
2987 cgroup_exit_cftypes(cfts);
2992 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2993 * @cfts: zero-length name terminated array of cftypes
2995 * Unregister @cfts. Files described by @cfts are removed from all
2996 * existing cgroups and all future cgroups won't have them either. This
2997 * function can be called anytime whether @cfts' subsys is attached or not.
2999 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
3002 int cgroup_rm_cftypes(struct cftype *cfts)
3006 mutex_lock(&cgroup_tree_mutex);
3007 ret = cgroup_rm_cftypes_locked(cfts);
3008 mutex_unlock(&cgroup_tree_mutex);
3013 * cgroup_add_cftypes - add an array of cftypes to a subsystem
3014 * @ss: target cgroup subsystem
3015 * @cfts: zero-length name terminated array of cftypes
3017 * Register @cfts to @ss. Files described by @cfts are created for all
3018 * existing cgroups to which @ss is attached and all future cgroups will
3019 * have them too. This function can be called anytime whether @ss is
3022 * Returns 0 on successful registration, -errno on failure. Note that this
3023 * function currently returns 0 as long as @cfts registration is successful
3024 * even if some file creation attempts on existing cgroups fail.
3026 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3030 if (!cfts || cfts[0].name[0] == '\0')
3033 ret = cgroup_init_cftypes(ss, cfts);
3037 mutex_lock(&cgroup_tree_mutex);
3039 list_add_tail(&cfts->node, &ss->cfts);
3040 ret = cgroup_apply_cftypes(cfts, true);
3042 cgroup_rm_cftypes_locked(cfts);
3044 mutex_unlock(&cgroup_tree_mutex);
3049 * cgroup_task_count - count the number of tasks in a cgroup.
3050 * @cgrp: the cgroup in question
3052 * Return the number of tasks in the cgroup.
3054 static int cgroup_task_count(const struct cgroup *cgrp)
3057 struct cgrp_cset_link *link;
3059 down_read(&css_set_rwsem);
3060 list_for_each_entry(link, &cgrp->cset_links, cset_link)
3061 count += atomic_read(&link->cset->refcount);
3062 up_read(&css_set_rwsem);
3067 * css_next_child - find the next child of a given css
3068 * @pos_css: the current position (%NULL to initiate traversal)
3069 * @parent_css: css whose children to walk
3071 * This function returns the next child of @parent_css and should be called
3072 * under either cgroup_mutex or RCU read lock. The only requirement is
3073 * that @parent_css and @pos_css are accessible. The next sibling is
3074 * guaranteed to be returned regardless of their states.
3076 struct cgroup_subsys_state *
3077 css_next_child(struct cgroup_subsys_state *pos_css,
3078 struct cgroup_subsys_state *parent_css)
3080 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
3081 struct cgroup *cgrp = parent_css->cgroup;
3082 struct cgroup *next;
3084 cgroup_assert_mutexes_or_rcu_locked();
3087 * @pos could already have been removed. Once a cgroup is removed,
3088 * its ->sibling.next is no longer updated when its next sibling
3089 * changes. As CGRP_DEAD assertion is serialized and happens
3090 * before the cgroup is taken off the ->sibling list, if we see it
3091 * unasserted, it's guaranteed that the next sibling hasn't
3092 * finished its grace period even if it's already removed, and thus
3093 * safe to dereference from this RCU critical section. If
3094 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
3095 * to be visible as %true here.
3097 * If @pos is dead, its next pointer can't be dereferenced;
3098 * however, as each cgroup is given a monotonically increasing
3099 * unique serial number and always appended to the sibling list,
3100 * the next one can be found by walking the parent's children until
3101 * we see a cgroup with higher serial number than @pos's. While
3102 * this path can be slower, it's taken only when either the current
3103 * cgroup is removed or iteration and removal race.
3106 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
3107 } else if (likely(!cgroup_is_dead(pos))) {
3108 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3110 list_for_each_entry_rcu(next, &cgrp->children, sibling)
3111 if (next->serial_nr > pos->serial_nr)
3116 * @next, if not pointing to the head, can be dereferenced and is
3117 * the next sibling; however, it might have @ss disabled. If so,
3118 * fast-forward to the next enabled one.
3120 while (&next->sibling != &cgrp->children) {
3121 struct cgroup_subsys_state *next_css = cgroup_css(next, parent_css->ss);
3125 next = list_entry_rcu(next->sibling.next, struct cgroup, sibling);
3131 * css_next_descendant_pre - find the next descendant for pre-order walk
3132 * @pos: the current position (%NULL to initiate traversal)
3133 * @root: css whose descendants to walk
3135 * To be used by css_for_each_descendant_pre(). Find the next descendant
3136 * to visit for pre-order traversal of @root's descendants. @root is
3137 * included in the iteration and the first node to be visited.
3139 * While this function requires cgroup_mutex or RCU read locking, it
3140 * doesn't require the whole traversal to be contained in a single critical
3141 * section. This function will return the correct next descendant as long
3142 * as both @pos and @root are accessible and @pos is a descendant of @root.
3144 struct cgroup_subsys_state *
3145 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3146 struct cgroup_subsys_state *root)
3148 struct cgroup_subsys_state *next;
3150 cgroup_assert_mutexes_or_rcu_locked();
3152 /* if first iteration, visit @root */
3156 /* visit the first child if exists */
3157 next = css_next_child(NULL, pos);
3161 /* no child, visit my or the closest ancestor's next sibling */
3162 while (pos != root) {
3163 next = css_next_child(pos, css_parent(pos));
3166 pos = css_parent(pos);
3173 * css_rightmost_descendant - return the rightmost descendant of a css
3174 * @pos: css of interest
3176 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3177 * is returned. This can be used during pre-order traversal to skip
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 rightmost descendant as
3183 * long as @pos is accessible.
3185 struct cgroup_subsys_state *
3186 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3188 struct cgroup_subsys_state *last, *tmp;
3190 cgroup_assert_mutexes_or_rcu_locked();
3194 /* ->prev isn't RCU safe, walk ->next till the end */
3196 css_for_each_child(tmp, last)
3203 static struct cgroup_subsys_state *
3204 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3206 struct cgroup_subsys_state *last;
3210 pos = css_next_child(NULL, pos);
3217 * css_next_descendant_post - find the next descendant for post-order walk
3218 * @pos: the current position (%NULL to initiate traversal)
3219 * @root: css whose descendants to walk
3221 * To be used by css_for_each_descendant_post(). Find the next descendant
3222 * to visit for post-order traversal of @root's descendants. @root is
3223 * included in the iteration and the last node to be visited.
3225 * While this function requires cgroup_mutex or RCU read locking, it
3226 * doesn't require the whole traversal to be contained in a single critical
3227 * section. This function will return the correct next descendant as long
3228 * as both @pos and @cgroup are accessible and @pos is a descendant of
3231 struct cgroup_subsys_state *
3232 css_next_descendant_post(struct cgroup_subsys_state *pos,
3233 struct cgroup_subsys_state *root)
3235 struct cgroup_subsys_state *next;
3237 cgroup_assert_mutexes_or_rcu_locked();
3239 /* if first iteration, visit leftmost descendant which may be @root */
3241 return css_leftmost_descendant(root);
3243 /* if we visited @root, we're done */
3247 /* if there's an unvisited sibling, visit its leftmost descendant */
3248 next = css_next_child(pos, css_parent(pos));
3250 return css_leftmost_descendant(next);
3252 /* no sibling left, visit parent */
3253 return css_parent(pos);
3257 * css_advance_task_iter - advance a task itererator to the next css_set
3258 * @it: the iterator to advance
3260 * Advance @it to the next css_set to walk.
3262 static void css_advance_task_iter(struct css_task_iter *it)
3264 struct list_head *l = it->cset_pos;
3265 struct cgrp_cset_link *link;
3266 struct css_set *cset;
3268 /* Advance to the next non-empty css_set */
3271 if (l == it->cset_head) {
3272 it->cset_pos = NULL;
3277 cset = container_of(l, struct css_set,
3278 e_cset_node[it->ss->id]);
3280 link = list_entry(l, struct cgrp_cset_link, cset_link);
3283 } while (list_empty(&cset->tasks) && list_empty(&cset->mg_tasks));
3287 if (!list_empty(&cset->tasks))
3288 it->task_pos = cset->tasks.next;
3290 it->task_pos = cset->mg_tasks.next;
3292 it->tasks_head = &cset->tasks;
3293 it->mg_tasks_head = &cset->mg_tasks;
3297 * css_task_iter_start - initiate task iteration
3298 * @css: the css to walk tasks of
3299 * @it: the task iterator to use
3301 * Initiate iteration through the tasks of @css. The caller can call
3302 * css_task_iter_next() to walk through the tasks until the function
3303 * returns NULL. On completion of iteration, css_task_iter_end() must be
3306 * Note that this function acquires a lock which is released when the
3307 * iteration finishes. The caller can't sleep while iteration is in
3310 void css_task_iter_start(struct cgroup_subsys_state *css,
3311 struct css_task_iter *it)
3312 __acquires(css_set_rwsem)
3314 /* no one should try to iterate before mounting cgroups */
3315 WARN_ON_ONCE(!use_task_css_set_links);
3317 down_read(&css_set_rwsem);
3322 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
3324 it->cset_pos = &css->cgroup->cset_links;
3326 it->cset_head = it->cset_pos;
3328 css_advance_task_iter(it);
3332 * css_task_iter_next - return the next task for the iterator
3333 * @it: the task iterator being iterated
3335 * The "next" function for task iteration. @it should have been
3336 * initialized via css_task_iter_start(). Returns NULL when the iteration
3339 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3341 struct task_struct *res;
3342 struct list_head *l = it->task_pos;
3344 /* If the iterator cg is NULL, we have no tasks */
3347 res = list_entry(l, struct task_struct, cg_list);
3350 * Advance iterator to find next entry. cset->tasks is consumed
3351 * first and then ->mg_tasks. After ->mg_tasks, we move onto the
3356 if (l == it->tasks_head)
3357 l = it->mg_tasks_head->next;
3359 if (l == it->mg_tasks_head)
3360 css_advance_task_iter(it);
3368 * css_task_iter_end - finish task iteration
3369 * @it: the task iterator to finish
3371 * Finish task iteration started by css_task_iter_start().
3373 void css_task_iter_end(struct css_task_iter *it)
3374 __releases(css_set_rwsem)
3376 up_read(&css_set_rwsem);
3380 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3381 * @to: cgroup to which the tasks will be moved
3382 * @from: cgroup in which the tasks currently reside
3384 * Locking rules between cgroup_post_fork() and the migration path
3385 * guarantee that, if a task is forking while being migrated, the new child
3386 * is guaranteed to be either visible in the source cgroup after the
3387 * parent's migration is complete or put into the target cgroup. No task
3388 * can slip out of migration through forking.
3390 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3392 LIST_HEAD(preloaded_csets);
3393 struct cgrp_cset_link *link;
3394 struct css_task_iter it;
3395 struct task_struct *task;
3398 mutex_lock(&cgroup_mutex);
3400 /* all tasks in @from are being moved, all csets are source */
3401 down_read(&css_set_rwsem);
3402 list_for_each_entry(link, &from->cset_links, cset_link)
3403 cgroup_migrate_add_src(link->cset, to, &preloaded_csets);
3404 up_read(&css_set_rwsem);
3406 ret = cgroup_migrate_prepare_dst(to, &preloaded_csets);
3411 * Migrate tasks one-by-one until @form is empty. This fails iff
3412 * ->can_attach() fails.
3415 css_task_iter_start(&from->dummy_css, &it);
3416 task = css_task_iter_next(&it);
3418 get_task_struct(task);
3419 css_task_iter_end(&it);
3422 ret = cgroup_migrate(to, task, false);
3423 put_task_struct(task);
3425 } while (task && !ret);
3427 cgroup_migrate_finish(&preloaded_csets);
3428 mutex_unlock(&cgroup_mutex);
3433 * Stuff for reading the 'tasks'/'procs' files.
3435 * Reading this file can return large amounts of data if a cgroup has
3436 * *lots* of attached tasks. So it may need several calls to read(),
3437 * but we cannot guarantee that the information we produce is correct
3438 * unless we produce it entirely atomically.
3442 /* which pidlist file are we talking about? */
3443 enum cgroup_filetype {
3449 * A pidlist is a list of pids that virtually represents the contents of one
3450 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3451 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3454 struct cgroup_pidlist {
3456 * used to find which pidlist is wanted. doesn't change as long as
3457 * this particular list stays in the list.
3459 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3462 /* how many elements the above list has */
3464 /* each of these stored in a list by its cgroup */
3465 struct list_head links;
3466 /* pointer to the cgroup we belong to, for list removal purposes */
3467 struct cgroup *owner;
3468 /* for delayed destruction */
3469 struct delayed_work destroy_dwork;
3473 * The following two functions "fix" the issue where there are more pids
3474 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3475 * TODO: replace with a kernel-wide solution to this problem
3477 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3478 static void *pidlist_allocate(int count)
3480 if (PIDLIST_TOO_LARGE(count))
3481 return vmalloc(count * sizeof(pid_t));
3483 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3486 static void pidlist_free(void *p)
3488 if (is_vmalloc_addr(p))
3495 * Used to destroy all pidlists lingering waiting for destroy timer. None
3496 * should be left afterwards.
3498 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
3500 struct cgroup_pidlist *l, *tmp_l;
3502 mutex_lock(&cgrp->pidlist_mutex);
3503 list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
3504 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
3505 mutex_unlock(&cgrp->pidlist_mutex);
3507 flush_workqueue(cgroup_pidlist_destroy_wq);
3508 BUG_ON(!list_empty(&cgrp->pidlists));
3511 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
3513 struct delayed_work *dwork = to_delayed_work(work);
3514 struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
3516 struct cgroup_pidlist *tofree = NULL;
3518 mutex_lock(&l->owner->pidlist_mutex);
3521 * Destroy iff we didn't get queued again. The state won't change
3522 * as destroy_dwork can only be queued while locked.
3524 if (!delayed_work_pending(dwork)) {
3525 list_del(&l->links);
3526 pidlist_free(l->list);
3527 put_pid_ns(l->key.ns);
3531 mutex_unlock(&l->owner->pidlist_mutex);
3536 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3537 * Returns the number of unique elements.
3539 static int pidlist_uniq(pid_t *list, int length)
3544 * we presume the 0th element is unique, so i starts at 1. trivial
3545 * edge cases first; no work needs to be done for either
3547 if (length == 0 || length == 1)
3549 /* src and dest walk down the list; dest counts unique elements */
3550 for (src = 1; src < length; src++) {
3551 /* find next unique element */
3552 while (list[src] == list[src-1]) {
3557 /* dest always points to where the next unique element goes */
3558 list[dest] = list[src];
3566 * The two pid files - task and cgroup.procs - guaranteed that the result
3567 * is sorted, which forced this whole pidlist fiasco. As pid order is
3568 * different per namespace, each namespace needs differently sorted list,
3569 * making it impossible to use, for example, single rbtree of member tasks
3570 * sorted by task pointer. As pidlists can be fairly large, allocating one
3571 * per open file is dangerous, so cgroup had to implement shared pool of
3572 * pidlists keyed by cgroup and namespace.
3574 * All this extra complexity was caused by the original implementation
3575 * committing to an entirely unnecessary property. In the long term, we
3576 * want to do away with it. Explicitly scramble sort order if
3577 * sane_behavior so that no such expectation exists in the new interface.
3579 * Scrambling is done by swapping every two consecutive bits, which is
3580 * non-identity one-to-one mapping which disturbs sort order sufficiently.
3582 static pid_t pid_fry(pid_t pid)
3584 unsigned a = pid & 0x55555555;
3585 unsigned b = pid & 0xAAAAAAAA;
3587 return (a << 1) | (b >> 1);
3590 static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
3592 if (cgroup_sane_behavior(cgrp))
3593 return pid_fry(pid);
3598 static int cmppid(const void *a, const void *b)
3600 return *(pid_t *)a - *(pid_t *)b;
3603 static int fried_cmppid(const void *a, const void *b)
3605 return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
3608 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3609 enum cgroup_filetype type)
3611 struct cgroup_pidlist *l;
3612 /* don't need task_nsproxy() if we're looking at ourself */
3613 struct pid_namespace *ns = task_active_pid_ns(current);
3615 lockdep_assert_held(&cgrp->pidlist_mutex);
3617 list_for_each_entry(l, &cgrp->pidlists, links)
3618 if (l->key.type == type && l->key.ns == ns)
3624 * find the appropriate pidlist for our purpose (given procs vs tasks)
3625 * returns with the lock on that pidlist already held, and takes care
3626 * of the use count, or returns NULL with no locks held if we're out of
3629 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
3630 enum cgroup_filetype type)
3632 struct cgroup_pidlist *l;
3634 lockdep_assert_held(&cgrp->pidlist_mutex);
3636 l = cgroup_pidlist_find(cgrp, type);
3640 /* entry not found; create a new one */
3641 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3645 INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
3647 /* don't need task_nsproxy() if we're looking at ourself */
3648 l->key.ns = get_pid_ns(task_active_pid_ns(current));
3650 list_add(&l->links, &cgrp->pidlists);
3655 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3657 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3658 struct cgroup_pidlist **lp)
3662 int pid, n = 0; /* used for populating the array */
3663 struct css_task_iter it;
3664 struct task_struct *tsk;
3665 struct cgroup_pidlist *l;
3667 lockdep_assert_held(&cgrp->pidlist_mutex);
3670 * If cgroup gets more users after we read count, we won't have
3671 * enough space - tough. This race is indistinguishable to the
3672 * caller from the case that the additional cgroup users didn't
3673 * show up until sometime later on.
3675 length = cgroup_task_count(cgrp);
3676 array = pidlist_allocate(length);
3679 /* now, populate the array */
3680 css_task_iter_start(&cgrp->dummy_css, &it);
3681 while ((tsk = css_task_iter_next(&it))) {
3682 if (unlikely(n == length))
3684 /* get tgid or pid for procs or tasks file respectively */
3685 if (type == CGROUP_FILE_PROCS)
3686 pid = task_tgid_vnr(tsk);
3688 pid = task_pid_vnr(tsk);
3689 if (pid > 0) /* make sure to only use valid results */
3692 css_task_iter_end(&it);
3694 /* now sort & (if procs) strip out duplicates */
3695 if (cgroup_sane_behavior(cgrp))
3696 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
3698 sort(array, length, sizeof(pid_t), cmppid, NULL);
3699 if (type == CGROUP_FILE_PROCS)
3700 length = pidlist_uniq(array, length);
3702 l = cgroup_pidlist_find_create(cgrp, type);
3704 mutex_unlock(&cgrp->pidlist_mutex);
3705 pidlist_free(array);
3709 /* store array, freeing old if necessary */
3710 pidlist_free(l->list);
3718 * cgroupstats_build - build and fill cgroupstats
3719 * @stats: cgroupstats to fill information into
3720 * @dentry: A dentry entry belonging to the cgroup for which stats have
3723 * Build and fill cgroupstats so that taskstats can export it to user
3726 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3728 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
3729 struct cgroup *cgrp;
3730 struct css_task_iter it;
3731 struct task_struct *tsk;
3733 /* it should be kernfs_node belonging to cgroupfs and is a directory */
3734 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
3735 kernfs_type(kn) != KERNFS_DIR)
3738 mutex_lock(&cgroup_mutex);
3741 * We aren't being called from kernfs and there's no guarantee on
3742 * @kn->priv's validity. For this and css_tryget_from_dir(),
3743 * @kn->priv is RCU safe. Let's do the RCU dancing.
3746 cgrp = rcu_dereference(kn->priv);
3747 if (!cgrp || cgroup_is_dead(cgrp)) {
3749 mutex_unlock(&cgroup_mutex);
3754 css_task_iter_start(&cgrp->dummy_css, &it);
3755 while ((tsk = css_task_iter_next(&it))) {
3756 switch (tsk->state) {
3758 stats->nr_running++;
3760 case TASK_INTERRUPTIBLE:
3761 stats->nr_sleeping++;
3763 case TASK_UNINTERRUPTIBLE:
3764 stats->nr_uninterruptible++;
3767 stats->nr_stopped++;
3770 if (delayacct_is_task_waiting_on_io(tsk))
3771 stats->nr_io_wait++;
3775 css_task_iter_end(&it);
3777 mutex_unlock(&cgroup_mutex);
3783 * seq_file methods for the tasks/procs files. The seq_file position is the
3784 * next pid to display; the seq_file iterator is a pointer to the pid
3785 * in the cgroup->l->list array.
3788 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3791 * Initially we receive a position value that corresponds to
3792 * one more than the last pid shown (or 0 on the first call or
3793 * after a seek to the start). Use a binary-search to find the
3794 * next pid to display, if any
3796 struct kernfs_open_file *of = s->private;
3797 struct cgroup *cgrp = seq_css(s)->cgroup;
3798 struct cgroup_pidlist *l;
3799 enum cgroup_filetype type = seq_cft(s)->private;
3800 int index = 0, pid = *pos;
3803 mutex_lock(&cgrp->pidlist_mutex);
3806 * !NULL @of->priv indicates that this isn't the first start()
3807 * after open. If the matching pidlist is around, we can use that.
3808 * Look for it. Note that @of->priv can't be used directly. It
3809 * could already have been destroyed.
3812 of->priv = cgroup_pidlist_find(cgrp, type);
3815 * Either this is the first start() after open or the matching
3816 * pidlist has been destroyed inbetween. Create a new one.
3819 ret = pidlist_array_load(cgrp, type,
3820 (struct cgroup_pidlist **)&of->priv);
3822 return ERR_PTR(ret);
3827 int end = l->length;
3829 while (index < end) {
3830 int mid = (index + end) / 2;
3831 if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
3834 } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
3840 /* If we're off the end of the array, we're done */
3841 if (index >= l->length)
3843 /* Update the abstract position to be the actual pid that we found */
3844 iter = l->list + index;
3845 *pos = cgroup_pid_fry(cgrp, *iter);
3849 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3851 struct kernfs_open_file *of = s->private;
3852 struct cgroup_pidlist *l = of->priv;
3855 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
3856 CGROUP_PIDLIST_DESTROY_DELAY);
3857 mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
3860 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3862 struct kernfs_open_file *of = s->private;
3863 struct cgroup_pidlist *l = of->priv;
3865 pid_t *end = l->list + l->length;
3867 * Advance to the next pid in the array. If this goes off the
3874 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
3879 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3881 return seq_printf(s, "%d\n", *(int *)v);
3884 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3887 return notify_on_release(css->cgroup);
3890 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3891 struct cftype *cft, u64 val)
3893 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3895 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3897 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3901 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3904 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3907 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3908 struct cftype *cft, u64 val)
3911 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3913 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3917 static struct cftype cgroup_base_files[] = {
3919 .name = "cgroup.procs",
3920 .seq_start = cgroup_pidlist_start,
3921 .seq_next = cgroup_pidlist_next,
3922 .seq_stop = cgroup_pidlist_stop,
3923 .seq_show = cgroup_pidlist_show,
3924 .private = CGROUP_FILE_PROCS,
3925 .write_u64 = cgroup_procs_write,
3926 .mode = S_IRUGO | S_IWUSR,
3929 .name = "cgroup.clone_children",
3930 .flags = CFTYPE_INSANE,
3931 .read_u64 = cgroup_clone_children_read,
3932 .write_u64 = cgroup_clone_children_write,
3935 .name = "cgroup.sane_behavior",
3936 .flags = CFTYPE_ONLY_ON_ROOT,
3937 .seq_show = cgroup_sane_behavior_show,
3940 .name = "cgroup.controllers",
3941 .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_ONLY_ON_ROOT,
3942 .seq_show = cgroup_root_controllers_show,
3945 .name = "cgroup.controllers",
3946 .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_NOT_ON_ROOT,
3947 .seq_show = cgroup_controllers_show,
3950 .name = "cgroup.subtree_control",
3951 .flags = CFTYPE_ONLY_ON_DFL,
3952 .seq_show = cgroup_subtree_control_show,
3953 .write_string = cgroup_subtree_control_write,
3956 .name = "cgroup.populated",
3957 .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_NOT_ON_ROOT,
3958 .seq_show = cgroup_populated_show,
3962 * Historical crazy stuff. These don't have "cgroup." prefix and
3963 * don't exist if sane_behavior. If you're depending on these, be
3964 * prepared to be burned.
3968 .flags = CFTYPE_INSANE, /* use "procs" instead */
3969 .seq_start = cgroup_pidlist_start,
3970 .seq_next = cgroup_pidlist_next,
3971 .seq_stop = cgroup_pidlist_stop,
3972 .seq_show = cgroup_pidlist_show,
3973 .private = CGROUP_FILE_TASKS,
3974 .write_u64 = cgroup_tasks_write,
3975 .mode = S_IRUGO | S_IWUSR,
3978 .name = "notify_on_release",
3979 .flags = CFTYPE_INSANE,
3980 .read_u64 = cgroup_read_notify_on_release,
3981 .write_u64 = cgroup_write_notify_on_release,
3984 .name = "release_agent",
3985 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
3986 .seq_show = cgroup_release_agent_show,
3987 .write_string = cgroup_release_agent_write,
3988 .max_write_len = PATH_MAX - 1,
3994 * cgroup_populate_dir - create subsys files in a cgroup directory
3995 * @cgrp: target cgroup
3996 * @subsys_mask: mask of the subsystem ids whose files should be added
3998 * On failure, no file is added.
4000 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned int subsys_mask)
4002 struct cgroup_subsys *ss;
4005 /* process cftsets of each subsystem */
4006 for_each_subsys(ss, i) {
4007 struct cftype *cfts;
4009 if (!(subsys_mask & (1 << i)))
4012 list_for_each_entry(cfts, &ss->cfts, node) {
4013 ret = cgroup_addrm_files(cgrp, cfts, true);
4020 cgroup_clear_dir(cgrp, subsys_mask);
4025 * css destruction is four-stage process.
4027 * 1. Destruction starts. Killing of the percpu_ref is initiated.
4028 * Implemented in kill_css().
4030 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4031 * and thus css_tryget() is guaranteed to fail, the css can be offlined
4032 * by invoking offline_css(). After offlining, the base ref is put.
4033 * Implemented in css_killed_work_fn().
4035 * 3. When the percpu_ref reaches zero, the only possible remaining
4036 * accessors are inside RCU read sections. css_release() schedules the
4039 * 4. After the grace period, the css can be freed. Implemented in
4040 * css_free_work_fn().
4042 * It is actually hairier because both step 2 and 4 require process context
4043 * and thus involve punting to css->destroy_work adding two additional
4044 * steps to the already complex sequence.
4046 static void css_free_work_fn(struct work_struct *work)
4048 struct cgroup_subsys_state *css =
4049 container_of(work, struct cgroup_subsys_state, destroy_work);
4050 struct cgroup *cgrp = css->cgroup;
4053 css_put(css->parent);
4055 css->ss->css_free(css);
4059 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4061 struct cgroup_subsys_state *css =
4062 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4064 INIT_WORK(&css->destroy_work, css_free_work_fn);
4065 queue_work(cgroup_destroy_wq, &css->destroy_work);
4068 static void css_release(struct percpu_ref *ref)
4070 struct cgroup_subsys_state *css =
4071 container_of(ref, struct cgroup_subsys_state, refcnt);
4073 RCU_INIT_POINTER(css->cgroup->subsys[css->ss->id], NULL);
4074 call_rcu(&css->rcu_head, css_free_rcu_fn);
4077 static void init_css(struct cgroup_subsys_state *css, struct cgroup_subsys *ss,
4078 struct cgroup *cgrp)
4085 css->parent = cgroup_css(cgrp->parent, ss);
4087 css->flags |= CSS_ROOT;
4089 BUG_ON(cgroup_css(cgrp, ss));
4092 /* invoke ->css_online() on a new CSS and mark it online if successful */
4093 static int online_css(struct cgroup_subsys_state *css)
4095 struct cgroup_subsys *ss = css->ss;
4098 lockdep_assert_held(&cgroup_tree_mutex);
4099 lockdep_assert_held(&cgroup_mutex);
4102 ret = ss->css_online(css);
4104 css->flags |= CSS_ONLINE;
4105 css->cgroup->nr_css++;
4106 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
4111 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4112 static void offline_css(struct cgroup_subsys_state *css)
4114 struct cgroup_subsys *ss = css->ss;
4116 lockdep_assert_held(&cgroup_tree_mutex);
4117 lockdep_assert_held(&cgroup_mutex);
4119 if (!(css->flags & CSS_ONLINE))
4122 if (ss->css_offline)
4123 ss->css_offline(css);
4125 css->flags &= ~CSS_ONLINE;
4126 css->cgroup->nr_css--;
4127 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
4129 wake_up_all(&css->cgroup->offline_waitq);
4133 * create_css - create a cgroup_subsys_state
4134 * @cgrp: the cgroup new css will be associated with
4135 * @ss: the subsys of new css
4137 * Create a new css associated with @cgrp - @ss pair. On success, the new
4138 * css is online and installed in @cgrp with all interface files created.
4139 * Returns 0 on success, -errno on failure.
4141 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss)
4143 struct cgroup *parent = cgrp->parent;
4144 struct cgroup_subsys_state *css;
4147 lockdep_assert_held(&cgroup_mutex);
4149 css = ss->css_alloc(cgroup_css(parent, ss));
4151 return PTR_ERR(css);
4153 err = percpu_ref_init(&css->refcnt, css_release);
4157 init_css(css, ss, cgrp);
4159 err = cgroup_populate_dir(cgrp, 1 << ss->id);
4161 goto err_free_percpu_ref;
4163 err = online_css(css);
4168 css_get(css->parent);
4170 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4172 pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4173 current->comm, current->pid, ss->name);
4174 if (!strcmp(ss->name, "memory"))
4175 pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
4176 ss->warned_broken_hierarchy = true;
4182 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4183 err_free_percpu_ref:
4184 percpu_ref_cancel_init(&css->refcnt);
4191 * cgroup_create - create a cgroup
4192 * @parent: cgroup that will be parent of the new cgroup
4193 * @name: name of the new cgroup
4194 * @mode: mode to set on new cgroup
4196 static long cgroup_create(struct cgroup *parent, const char *name,
4199 struct cgroup *cgrp;
4200 struct cgroup_root *root = parent->root;
4202 struct cgroup_subsys *ss;
4203 struct kernfs_node *kn;
4205 /* allocate the cgroup and its ID, 0 is reserved for the root */
4206 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4210 mutex_lock(&cgroup_tree_mutex);
4213 * Only live parents can have children. Note that the liveliness
4214 * check isn't strictly necessary because cgroup_mkdir() and
4215 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4216 * anyway so that locking is contained inside cgroup proper and we
4217 * don't get nasty surprises if we ever grow another caller.
4219 if (!cgroup_lock_live_group(parent)) {
4221 goto err_unlock_tree;
4225 * Temporarily set the pointer to NULL, so idr_find() won't return
4226 * a half-baked cgroup.
4228 cgrp->id = idr_alloc(&root->cgroup_idr, NULL, 1, 0, GFP_KERNEL);
4234 init_cgroup_housekeeping(cgrp);
4236 cgrp->parent = parent;
4237 cgrp->dummy_css.parent = &parent->dummy_css;
4238 cgrp->root = parent->root;
4240 if (notify_on_release(parent))
4241 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4243 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4244 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4246 /* create the directory */
4247 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
4255 * This extra ref will be put in cgroup_free_fn() and guarantees
4256 * that @cgrp->kn is always accessible.
4260 cgrp->serial_nr = cgroup_serial_nr_next++;
4262 /* allocation complete, commit to creation */
4263 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4264 atomic_inc(&root->nr_cgrps);
4268 * @cgrp is now fully operational. If something fails after this
4269 * point, it'll be released via the normal destruction path.
4271 idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4273 err = cgroup_kn_set_ugid(kn);
4277 err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
4281 /* let's create and online css's */
4282 for_each_subsys(ss, ssid) {
4283 if (parent->child_subsys_mask & (1 << ssid)) {
4284 err = create_css(cgrp, ss);
4291 * On the default hierarchy, a child doesn't automatically inherit
4292 * child_subsys_mask from the parent. Each is configured manually.
4294 if (!cgroup_on_dfl(cgrp))
4295 cgrp->child_subsys_mask = parent->child_subsys_mask;
4297 kernfs_activate(kn);
4299 mutex_unlock(&cgroup_mutex);
4300 mutex_unlock(&cgroup_tree_mutex);
4305 idr_remove(&root->cgroup_idr, cgrp->id);
4307 mutex_unlock(&cgroup_mutex);
4309 mutex_unlock(&cgroup_tree_mutex);
4314 cgroup_destroy_locked(cgrp);
4315 mutex_unlock(&cgroup_mutex);
4316 mutex_unlock(&cgroup_tree_mutex);
4320 static int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
4323 struct cgroup *parent = parent_kn->priv;
4327 * cgroup_create() grabs cgroup_tree_mutex which nests outside
4328 * kernfs active_ref and cgroup_create() already synchronizes
4329 * properly against removal through cgroup_lock_live_group().
4330 * Break it before calling cgroup_create().
4333 kernfs_break_active_protection(parent_kn);
4335 ret = cgroup_create(parent, name, mode);
4337 kernfs_unbreak_active_protection(parent_kn);
4343 * This is called when the refcnt of a css is confirmed to be killed.
4344 * css_tryget() is now guaranteed to fail.
4346 static void css_killed_work_fn(struct work_struct *work)
4348 struct cgroup_subsys_state *css =
4349 container_of(work, struct cgroup_subsys_state, destroy_work);
4350 struct cgroup *cgrp = css->cgroup;
4352 mutex_lock(&cgroup_tree_mutex);
4353 mutex_lock(&cgroup_mutex);
4356 * css_tryget() is guaranteed to fail now. Tell subsystems to
4357 * initate destruction.
4362 * If @cgrp is marked dead, it's waiting for refs of all css's to
4363 * be disabled before proceeding to the second phase of cgroup
4364 * destruction. If we are the last one, kick it off.
4366 if (!cgrp->nr_css && cgroup_is_dead(cgrp))
4367 cgroup_destroy_css_killed(cgrp);
4369 mutex_unlock(&cgroup_mutex);
4370 mutex_unlock(&cgroup_tree_mutex);
4373 * Put the css refs from kill_css(). Each css holds an extra
4374 * reference to the cgroup's dentry and cgroup removal proceeds
4375 * regardless of css refs. On the last put of each css, whenever
4376 * that may be, the extra dentry ref is put so that dentry
4377 * destruction happens only after all css's are released.
4382 /* css kill confirmation processing requires process context, bounce */
4383 static void css_killed_ref_fn(struct percpu_ref *ref)
4385 struct cgroup_subsys_state *css =
4386 container_of(ref, struct cgroup_subsys_state, refcnt);
4388 INIT_WORK(&css->destroy_work, css_killed_work_fn);
4389 queue_work(cgroup_destroy_wq, &css->destroy_work);
4393 * kill_css - destroy a css
4394 * @css: css to destroy
4396 * This function initiates destruction of @css by removing cgroup interface
4397 * files and putting its base reference. ->css_offline() will be invoked
4398 * asynchronously once css_tryget() is guaranteed to fail and when the
4399 * reference count reaches zero, @css will be released.
4401 static void kill_css(struct cgroup_subsys_state *css)
4403 lockdep_assert_held(&cgroup_tree_mutex);
4406 * This must happen before css is disassociated with its cgroup.
4407 * See seq_css() for details.
4409 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4412 * Killing would put the base ref, but we need to keep it alive
4413 * until after ->css_offline().
4418 * cgroup core guarantees that, by the time ->css_offline() is
4419 * invoked, no new css reference will be given out via
4420 * css_tryget(). We can't simply call percpu_ref_kill() and
4421 * proceed to offlining css's because percpu_ref_kill() doesn't
4422 * guarantee that the ref is seen as killed on all CPUs on return.
4424 * Use percpu_ref_kill_and_confirm() to get notifications as each
4425 * css is confirmed to be seen as killed on all CPUs.
4427 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4431 * cgroup_destroy_locked - the first stage of cgroup destruction
4432 * @cgrp: cgroup to be destroyed
4434 * css's make use of percpu refcnts whose killing latency shouldn't be
4435 * exposed to userland and are RCU protected. Also, cgroup core needs to
4436 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
4437 * invoked. To satisfy all the requirements, destruction is implemented in
4438 * the following two steps.
4440 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4441 * userland visible parts and start killing the percpu refcnts of
4442 * css's. Set up so that the next stage will be kicked off once all
4443 * the percpu refcnts are confirmed to be killed.
4445 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4446 * rest of destruction. Once all cgroup references are gone, the
4447 * cgroup is RCU-freed.
4449 * This function implements s1. After this step, @cgrp is gone as far as
4450 * the userland is concerned and a new cgroup with the same name may be
4451 * created. As cgroup doesn't care about the names internally, this
4452 * doesn't cause any problem.
4454 static int cgroup_destroy_locked(struct cgroup *cgrp)
4455 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4457 struct cgroup *child;
4458 struct cgroup_subsys_state *css;
4462 lockdep_assert_held(&cgroup_tree_mutex);
4463 lockdep_assert_held(&cgroup_mutex);
4466 * css_set_rwsem synchronizes access to ->cset_links and prevents
4467 * @cgrp from being removed while put_css_set() is in progress.
4469 down_read(&css_set_rwsem);
4470 empty = list_empty(&cgrp->cset_links);
4471 up_read(&css_set_rwsem);
4476 * Make sure there's no live children. We can't test ->children
4477 * emptiness as dead children linger on it while being destroyed;
4478 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
4482 list_for_each_entry_rcu(child, &cgrp->children, sibling) {
4483 empty = cgroup_is_dead(child);
4492 * Mark @cgrp dead. This prevents further task migration and child
4493 * creation by disabling cgroup_lock_live_group(). Note that
4494 * CGRP_DEAD assertion is depended upon by css_next_child() to
4495 * resume iteration after dropping RCU read lock. See
4496 * css_next_child() for details.
4498 set_bit(CGRP_DEAD, &cgrp->flags);
4501 * Initiate massacre of all css's. cgroup_destroy_css_killed()
4502 * will be invoked to perform the rest of destruction once the
4503 * percpu refs of all css's are confirmed to be killed. This
4504 * involves removing the subsystem's files, drop cgroup_mutex.
4506 mutex_unlock(&cgroup_mutex);
4507 for_each_css(css, ssid, cgrp)
4509 mutex_lock(&cgroup_mutex);
4511 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4512 raw_spin_lock(&release_list_lock);
4513 if (!list_empty(&cgrp->release_list))
4514 list_del_init(&cgrp->release_list);
4515 raw_spin_unlock(&release_list_lock);
4518 * If @cgrp has css's attached, the second stage of cgroup
4519 * destruction is kicked off from css_killed_work_fn() after the
4520 * refs of all attached css's are killed. If @cgrp doesn't have
4521 * any css, we kick it off here.
4524 cgroup_destroy_css_killed(cgrp);
4526 /* remove @cgrp directory along with the base files */
4527 mutex_unlock(&cgroup_mutex);
4530 * There are two control paths which try to determine cgroup from
4531 * dentry without going through kernfs - cgroupstats_build() and
4532 * css_tryget_from_dir(). Those are supported by RCU protecting
4533 * clearing of cgrp->kn->priv backpointer, which should happen
4534 * after all files under it have been removed.
4536 kernfs_remove(cgrp->kn); /* @cgrp has an extra ref on its kn */
4537 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv, NULL);
4539 mutex_lock(&cgroup_mutex);
4545 * cgroup_destroy_css_killed - the second step of cgroup destruction
4546 * @work: cgroup->destroy_free_work
4548 * This function is invoked from a work item for a cgroup which is being
4549 * destroyed after all css's are offlined and performs the rest of
4550 * destruction. This is the second step of destruction described in the
4551 * comment above cgroup_destroy_locked().
4553 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
4555 struct cgroup *parent = cgrp->parent;
4557 lockdep_assert_held(&cgroup_tree_mutex);
4558 lockdep_assert_held(&cgroup_mutex);
4560 /* delete this cgroup from parent->children */
4561 list_del_rcu(&cgrp->sibling);
4565 set_bit(CGRP_RELEASABLE, &parent->flags);
4566 check_for_release(parent);
4569 static int cgroup_rmdir(struct kernfs_node *kn)
4571 struct cgroup *cgrp = kn->priv;
4575 * This is self-destruction but @kn can't be removed while this
4576 * callback is in progress. Let's break active protection. Once
4577 * the protection is broken, @cgrp can be destroyed at any point.
4578 * Pin it so that it stays accessible.
4581 kernfs_break_active_protection(kn);
4583 mutex_lock(&cgroup_tree_mutex);
4584 mutex_lock(&cgroup_mutex);
4587 * @cgrp might already have been destroyed while we're trying to
4590 if (!cgroup_is_dead(cgrp))
4591 ret = cgroup_destroy_locked(cgrp);
4593 mutex_unlock(&cgroup_mutex);
4594 mutex_unlock(&cgroup_tree_mutex);
4596 kernfs_unbreak_active_protection(kn);
4601 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
4602 .remount_fs = cgroup_remount,
4603 .show_options = cgroup_show_options,
4604 .mkdir = cgroup_mkdir,
4605 .rmdir = cgroup_rmdir,
4606 .rename = cgroup_rename,
4609 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4611 struct cgroup_subsys_state *css;
4613 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4615 mutex_lock(&cgroup_tree_mutex);
4616 mutex_lock(&cgroup_mutex);
4618 INIT_LIST_HEAD(&ss->cfts);
4620 /* Create the root cgroup state for this subsystem */
4621 ss->root = &cgrp_dfl_root;
4622 css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
4623 /* We don't handle early failures gracefully */
4624 BUG_ON(IS_ERR(css));
4625 init_css(css, ss, &cgrp_dfl_root.cgrp);
4627 /* Update the init_css_set to contain a subsys
4628 * pointer to this state - since the subsystem is
4629 * newly registered, all tasks and hence the
4630 * init_css_set is in the subsystem's root cgroup. */
4631 init_css_set.subsys[ss->id] = css;
4633 need_forkexit_callback |= ss->fork || ss->exit;
4635 /* At system boot, before all subsystems have been
4636 * registered, no tasks have been forked, so we don't
4637 * need to invoke fork callbacks here. */
4638 BUG_ON(!list_empty(&init_task.tasks));
4640 BUG_ON(online_css(css));
4642 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
4644 mutex_unlock(&cgroup_mutex);
4645 mutex_unlock(&cgroup_tree_mutex);
4649 * cgroup_init_early - cgroup initialization at system boot
4651 * Initialize cgroups at system boot, and initialize any
4652 * subsystems that request early init.
4654 int __init cgroup_init_early(void)
4656 static struct cgroup_sb_opts __initdata opts =
4657 { .flags = CGRP_ROOT_SANE_BEHAVIOR };
4658 struct cgroup_subsys *ss;
4661 init_cgroup_root(&cgrp_dfl_root, &opts);
4662 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4664 for_each_subsys(ss, i) {
4665 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
4666 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
4667 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
4669 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
4670 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
4673 ss->name = cgroup_subsys_name[i];
4676 cgroup_init_subsys(ss);
4682 * cgroup_init - cgroup initialization
4684 * Register cgroup filesystem and /proc file, and initialize
4685 * any subsystems that didn't request early init.
4687 int __init cgroup_init(void)
4689 struct cgroup_subsys *ss;
4693 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
4695 mutex_lock(&cgroup_tree_mutex);
4696 mutex_lock(&cgroup_mutex);
4698 /* Add init_css_set to the hash table */
4699 key = css_set_hash(init_css_set.subsys);
4700 hash_add(css_set_table, &init_css_set.hlist, key);
4702 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
4704 mutex_unlock(&cgroup_mutex);
4705 mutex_unlock(&cgroup_tree_mutex);
4707 for_each_subsys(ss, ssid) {
4708 if (!ss->early_init)
4709 cgroup_init_subsys(ss);
4711 list_add_tail(&init_css_set.e_cset_node[ssid],
4712 &cgrp_dfl_root.cgrp.e_csets[ssid]);
4715 * cftype registration needs kmalloc and can't be done
4716 * during early_init. Register base cftypes separately.
4718 if (ss->base_cftypes)
4719 WARN_ON(cgroup_add_cftypes(ss, ss->base_cftypes));
4722 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4726 err = register_filesystem(&cgroup_fs_type);
4728 kobject_put(cgroup_kobj);
4732 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4736 static int __init cgroup_wq_init(void)
4739 * There isn't much point in executing destruction path in
4740 * parallel. Good chunk is serialized with cgroup_mutex anyway.
4741 * Use 1 for @max_active.
4743 * We would prefer to do this in cgroup_init() above, but that
4744 * is called before init_workqueues(): so leave this until after.
4746 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
4747 BUG_ON(!cgroup_destroy_wq);
4750 * Used to destroy pidlists and separate to serve as flush domain.
4751 * Cap @max_active to 1 too.
4753 cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
4755 BUG_ON(!cgroup_pidlist_destroy_wq);
4759 core_initcall(cgroup_wq_init);
4762 * proc_cgroup_show()
4763 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4764 * - Used for /proc/<pid>/cgroup.
4767 /* TODO: Use a proper seq_file iterator */
4768 int proc_cgroup_show(struct seq_file *m, void *v)
4771 struct task_struct *tsk;
4774 struct cgroup_root *root;
4777 buf = kmalloc(PATH_MAX, GFP_KERNEL);
4783 tsk = get_pid_task(pid, PIDTYPE_PID);
4789 mutex_lock(&cgroup_mutex);
4790 down_read(&css_set_rwsem);
4792 for_each_root(root) {
4793 struct cgroup_subsys *ss;
4794 struct cgroup *cgrp;
4795 int ssid, count = 0;
4797 if (root == &cgrp_dfl_root && !cgrp_dfl_root_visible)
4800 seq_printf(m, "%d:", root->hierarchy_id);
4801 for_each_subsys(ss, ssid)
4802 if (root->subsys_mask & (1 << ssid))
4803 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4804 if (strlen(root->name))
4805 seq_printf(m, "%sname=%s", count ? "," : "",
4808 cgrp = task_cgroup_from_root(tsk, root);
4809 path = cgroup_path(cgrp, buf, PATH_MAX);
4811 retval = -ENAMETOOLONG;
4819 up_read(&css_set_rwsem);
4820 mutex_unlock(&cgroup_mutex);
4821 put_task_struct(tsk);
4828 /* Display information about each subsystem and each hierarchy */
4829 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4831 struct cgroup_subsys *ss;
4834 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4836 * ideally we don't want subsystems moving around while we do this.
4837 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4838 * subsys/hierarchy state.
4840 mutex_lock(&cgroup_mutex);
4842 for_each_subsys(ss, i)
4843 seq_printf(m, "%s\t%d\t%d\t%d\n",
4844 ss->name, ss->root->hierarchy_id,
4845 atomic_read(&ss->root->nr_cgrps), !ss->disabled);
4847 mutex_unlock(&cgroup_mutex);
4851 static int cgroupstats_open(struct inode *inode, struct file *file)
4853 return single_open(file, proc_cgroupstats_show, NULL);
4856 static const struct file_operations proc_cgroupstats_operations = {
4857 .open = cgroupstats_open,
4859 .llseek = seq_lseek,
4860 .release = single_release,
4864 * cgroup_fork - initialize cgroup related fields during copy_process()
4865 * @child: pointer to task_struct of forking parent process.
4867 * A task is associated with the init_css_set until cgroup_post_fork()
4868 * attaches it to the parent's css_set. Empty cg_list indicates that
4869 * @child isn't holding reference to its css_set.
4871 void cgroup_fork(struct task_struct *child)
4873 RCU_INIT_POINTER(child->cgroups, &init_css_set);
4874 INIT_LIST_HEAD(&child->cg_list);
4878 * cgroup_post_fork - called on a new task after adding it to the task list
4879 * @child: the task in question
4881 * Adds the task to the list running through its css_set if necessary and
4882 * call the subsystem fork() callbacks. Has to be after the task is
4883 * visible on the task list in case we race with the first call to
4884 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
4887 void cgroup_post_fork(struct task_struct *child)
4889 struct cgroup_subsys *ss;
4893 * This may race against cgroup_enable_task_cg_links(). As that
4894 * function sets use_task_css_set_links before grabbing
4895 * tasklist_lock and we just went through tasklist_lock to add
4896 * @child, it's guaranteed that either we see the set
4897 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
4898 * @child during its iteration.
4900 * If we won the race, @child is associated with %current's
4901 * css_set. Grabbing css_set_rwsem guarantees both that the
4902 * association is stable, and, on completion of the parent's
4903 * migration, @child is visible in the source of migration or
4904 * already in the destination cgroup. This guarantee is necessary
4905 * when implementing operations which need to migrate all tasks of
4906 * a cgroup to another.
4908 * Note that if we lose to cgroup_enable_task_cg_links(), @child
4909 * will remain in init_css_set. This is safe because all tasks are
4910 * in the init_css_set before cg_links is enabled and there's no
4911 * operation which transfers all tasks out of init_css_set.
4913 if (use_task_css_set_links) {
4914 struct css_set *cset;
4916 down_write(&css_set_rwsem);
4917 cset = task_css_set(current);
4918 if (list_empty(&child->cg_list)) {
4919 rcu_assign_pointer(child->cgroups, cset);
4920 list_add(&child->cg_list, &cset->tasks);
4923 up_write(&css_set_rwsem);
4927 * Call ss->fork(). This must happen after @child is linked on
4928 * css_set; otherwise, @child might change state between ->fork()
4929 * and addition to css_set.
4931 if (need_forkexit_callback) {
4932 for_each_subsys(ss, i)
4939 * cgroup_exit - detach cgroup from exiting task
4940 * @tsk: pointer to task_struct of exiting process
4942 * Description: Detach cgroup from @tsk and release it.
4944 * Note that cgroups marked notify_on_release force every task in
4945 * them to take the global cgroup_mutex mutex when exiting.
4946 * This could impact scaling on very large systems. Be reluctant to
4947 * use notify_on_release cgroups where very high task exit scaling
4948 * is required on large systems.
4950 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
4951 * call cgroup_exit() while the task is still competent to handle
4952 * notify_on_release(), then leave the task attached to the root cgroup in
4953 * each hierarchy for the remainder of its exit. No need to bother with
4954 * init_css_set refcnting. init_css_set never goes away and we can't race
4955 * with migration path - PF_EXITING is visible to migration path.
4957 void cgroup_exit(struct task_struct *tsk)
4959 struct cgroup_subsys *ss;
4960 struct css_set *cset;
4961 bool put_cset = false;
4965 * Unlink from @tsk from its css_set. As migration path can't race
4966 * with us, we can check cg_list without grabbing css_set_rwsem.
4968 if (!list_empty(&tsk->cg_list)) {
4969 down_write(&css_set_rwsem);
4970 list_del_init(&tsk->cg_list);
4971 up_write(&css_set_rwsem);
4975 /* Reassign the task to the init_css_set. */
4976 cset = task_css_set(tsk);
4977 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
4979 if (need_forkexit_callback) {
4980 /* see cgroup_post_fork() for details */
4981 for_each_subsys(ss, i) {
4983 struct cgroup_subsys_state *old_css = cset->subsys[i];
4984 struct cgroup_subsys_state *css = task_css(tsk, i);
4986 ss->exit(css, old_css, tsk);
4992 put_css_set(cset, true);
4995 static void check_for_release(struct cgroup *cgrp)
4997 if (cgroup_is_releasable(cgrp) &&
4998 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
5000 * Control Group is currently removeable. If it's not
5001 * already queued for a userspace notification, queue
5004 int need_schedule_work = 0;
5006 raw_spin_lock(&release_list_lock);
5007 if (!cgroup_is_dead(cgrp) &&
5008 list_empty(&cgrp->release_list)) {
5009 list_add(&cgrp->release_list, &release_list);
5010 need_schedule_work = 1;
5012 raw_spin_unlock(&release_list_lock);
5013 if (need_schedule_work)
5014 schedule_work(&release_agent_work);
5019 * Notify userspace when a cgroup is released, by running the
5020 * configured release agent with the name of the cgroup (path
5021 * relative to the root of cgroup file system) as the argument.
5023 * Most likely, this user command will try to rmdir this cgroup.
5025 * This races with the possibility that some other task will be
5026 * attached to this cgroup before it is removed, or that some other
5027 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5028 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5029 * unused, and this cgroup will be reprieved from its death sentence,
5030 * to continue to serve a useful existence. Next time it's released,
5031 * we will get notified again, if it still has 'notify_on_release' set.
5033 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5034 * means only wait until the task is successfully execve()'d. The
5035 * separate release agent task is forked by call_usermodehelper(),
5036 * then control in this thread returns here, without waiting for the
5037 * release agent task. We don't bother to wait because the caller of
5038 * this routine has no use for the exit status of the release agent
5039 * task, so no sense holding our caller up for that.
5041 static void cgroup_release_agent(struct work_struct *work)
5043 BUG_ON(work != &release_agent_work);
5044 mutex_lock(&cgroup_mutex);
5045 raw_spin_lock(&release_list_lock);
5046 while (!list_empty(&release_list)) {
5047 char *argv[3], *envp[3];
5049 char *pathbuf = NULL, *agentbuf = NULL, *path;
5050 struct cgroup *cgrp = list_entry(release_list.next,
5053 list_del_init(&cgrp->release_list);
5054 raw_spin_unlock(&release_list_lock);
5055 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
5058 path = cgroup_path(cgrp, pathbuf, PATH_MAX);
5061 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5066 argv[i++] = agentbuf;
5071 /* minimal command environment */
5072 envp[i++] = "HOME=/";
5073 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5076 /* Drop the lock while we invoke the usermode helper,
5077 * since the exec could involve hitting disk and hence
5078 * be a slow process */
5079 mutex_unlock(&cgroup_mutex);
5080 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5081 mutex_lock(&cgroup_mutex);
5085 raw_spin_lock(&release_list_lock);
5087 raw_spin_unlock(&release_list_lock);
5088 mutex_unlock(&cgroup_mutex);
5091 static int __init cgroup_disable(char *str)
5093 struct cgroup_subsys *ss;
5097 while ((token = strsep(&str, ",")) != NULL) {
5101 for_each_subsys(ss, i) {
5102 if (!strcmp(token, ss->name)) {
5104 printk(KERN_INFO "Disabling %s control group"
5105 " subsystem\n", ss->name);
5112 __setup("cgroup_disable=", cgroup_disable);
5115 * css_tryget_from_dir - get corresponding css from the dentry of a cgroup dir
5116 * @dentry: directory dentry of interest
5117 * @ss: subsystem of interest
5119 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
5120 * to get the corresponding css and return it. If such css doesn't exist
5121 * or can't be pinned, an ERR_PTR value is returned.
5123 struct cgroup_subsys_state *css_tryget_from_dir(struct dentry *dentry,
5124 struct cgroup_subsys *ss)
5126 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
5127 struct cgroup_subsys_state *css = NULL;
5128 struct cgroup *cgrp;
5130 /* is @dentry a cgroup dir? */
5131 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
5132 kernfs_type(kn) != KERNFS_DIR)
5133 return ERR_PTR(-EBADF);
5138 * This path doesn't originate from kernfs and @kn could already
5139 * have been or be removed at any point. @kn->priv is RCU
5140 * protected for this access. See destroy_locked() for details.
5142 cgrp = rcu_dereference(kn->priv);
5144 css = cgroup_css(cgrp, ss);
5146 if (!css || !css_tryget(css))
5147 css = ERR_PTR(-ENOENT);
5154 * css_from_id - lookup css by id
5155 * @id: the cgroup id
5156 * @ss: cgroup subsys to be looked into
5158 * Returns the css if there's valid one with @id, otherwise returns NULL.
5159 * Should be called under rcu_read_lock().
5161 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5163 struct cgroup *cgrp;
5165 cgroup_assert_mutexes_or_rcu_locked();
5167 cgrp = idr_find(&ss->root->cgroup_idr, id);
5169 return cgroup_css(cgrp, ss);
5173 #ifdef CONFIG_CGROUP_DEBUG
5174 static struct cgroup_subsys_state *
5175 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5177 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5180 return ERR_PTR(-ENOMEM);
5185 static void debug_css_free(struct cgroup_subsys_state *css)
5190 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5193 return cgroup_task_count(css->cgroup);
5196 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5199 return (u64)(unsigned long)current->cgroups;
5202 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5208 count = atomic_read(&task_css_set(current)->refcount);
5213 static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
5215 struct cgrp_cset_link *link;
5216 struct css_set *cset;
5219 name_buf = kmalloc(NAME_MAX + 1, GFP_KERNEL);
5223 down_read(&css_set_rwsem);
5225 cset = rcu_dereference(current->cgroups);
5226 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5227 struct cgroup *c = link->cgrp;
5229 cgroup_name(c, name_buf, NAME_MAX + 1);
5230 seq_printf(seq, "Root %d group %s\n",
5231 c->root->hierarchy_id, name_buf);
5234 up_read(&css_set_rwsem);
5239 #define MAX_TASKS_SHOWN_PER_CSS 25
5240 static int cgroup_css_links_read(struct seq_file *seq, void *v)
5242 struct cgroup_subsys_state *css = seq_css(seq);
5243 struct cgrp_cset_link *link;
5245 down_read(&css_set_rwsem);
5246 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5247 struct css_set *cset = link->cset;
5248 struct task_struct *task;
5251 seq_printf(seq, "css_set %p\n", cset);
5253 list_for_each_entry(task, &cset->tasks, cg_list) {
5254 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5256 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5259 list_for_each_entry(task, &cset->mg_tasks, cg_list) {
5260 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5262 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5266 seq_puts(seq, " ...\n");
5268 up_read(&css_set_rwsem);
5272 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5274 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
5277 static struct cftype debug_files[] = {
5279 .name = "taskcount",
5280 .read_u64 = debug_taskcount_read,
5284 .name = "current_css_set",
5285 .read_u64 = current_css_set_read,
5289 .name = "current_css_set_refcount",
5290 .read_u64 = current_css_set_refcount_read,
5294 .name = "current_css_set_cg_links",
5295 .seq_show = current_css_set_cg_links_read,
5299 .name = "cgroup_css_links",
5300 .seq_show = cgroup_css_links_read,
5304 .name = "releasable",
5305 .read_u64 = releasable_read,
5311 struct cgroup_subsys debug_cgrp_subsys = {
5312 .css_alloc = debug_css_alloc,
5313 .css_free = debug_css_free,
5314 .base_cftypes = debug_files,
5316 #endif /* CONFIG_CGROUP_DEBUG */