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_idr and css_idr so that IDs can be released without
104 * grabbing cgroup_mutex.
106 static DEFINE_SPINLOCK(cgroup_idr_lock);
109 * Protects cgroup_subsys->release_agent_path. Modifying it also requires
110 * cgroup_mutex. Reading requires either cgroup_mutex or this spinlock.
112 static DEFINE_SPINLOCK(release_agent_path_lock);
114 #define cgroup_assert_mutexes_or_rcu_locked() \
115 rcu_lockdep_assert(rcu_read_lock_held() || \
116 lockdep_is_held(&cgroup_tree_mutex) || \
117 lockdep_is_held(&cgroup_mutex), \
118 "cgroup_[tree_]mutex or RCU read lock required");
121 * cgroup destruction makes heavy use of work items and there can be a lot
122 * of concurrent destructions. Use a separate workqueue so that cgroup
123 * destruction work items don't end up filling up max_active of system_wq
124 * which may lead to deadlock.
126 static struct workqueue_struct *cgroup_destroy_wq;
129 * pidlist destructions need to be flushed on cgroup destruction. Use a
130 * separate workqueue as flush domain.
132 static struct workqueue_struct *cgroup_pidlist_destroy_wq;
134 /* generate an array of cgroup subsystem pointers */
135 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
136 static struct cgroup_subsys *cgroup_subsys[] = {
137 #include <linux/cgroup_subsys.h>
141 /* array of cgroup subsystem names */
142 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
143 static const char *cgroup_subsys_name[] = {
144 #include <linux/cgroup_subsys.h>
149 * The default hierarchy, reserved for the subsystems that are otherwise
150 * unattached - it never has more than a single cgroup, and all tasks are
151 * part of that cgroup.
153 struct cgroup_root cgrp_dfl_root;
156 * The default hierarchy always exists but is hidden until mounted for the
157 * first time. This is for backward compatibility.
159 static bool cgrp_dfl_root_visible;
161 /* The list of hierarchy roots */
163 static LIST_HEAD(cgroup_roots);
164 static int cgroup_root_count;
166 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
167 static DEFINE_IDR(cgroup_hierarchy_idr);
170 * Assign a monotonically increasing serial number to cgroups. It
171 * guarantees cgroups with bigger numbers are newer than those with smaller
172 * numbers. Also, as cgroups are always appended to the parent's
173 * ->children list, it guarantees that sibling cgroups are always sorted in
174 * the ascending serial number order on the list. Protected by
177 static u64 cgroup_serial_nr_next = 1;
179 /* This flag indicates whether tasks in the fork and exit paths should
180 * check for fork/exit handlers to call. This avoids us having to do
181 * extra work in the fork/exit path if none of the subsystems need to
184 static int need_forkexit_callback __read_mostly;
186 static struct cftype cgroup_base_files[];
188 static void cgroup_put(struct cgroup *cgrp);
189 static int rebind_subsystems(struct cgroup_root *dst_root,
190 unsigned int ss_mask);
191 static void cgroup_destroy_css_killed(struct cgroup *cgrp);
192 static int cgroup_destroy_locked(struct cgroup *cgrp);
193 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss);
194 static void kill_css(struct cgroup_subsys_state *css);
195 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
197 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp);
199 /* IDR wrappers which synchronize using cgroup_idr_lock */
200 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
205 idr_preload(gfp_mask);
206 spin_lock_bh(&cgroup_idr_lock);
207 ret = idr_alloc(idr, ptr, start, end, gfp_mask);
208 spin_unlock_bh(&cgroup_idr_lock);
213 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
217 spin_lock_bh(&cgroup_idr_lock);
218 ret = idr_replace(idr, ptr, id);
219 spin_unlock_bh(&cgroup_idr_lock);
223 static void cgroup_idr_remove(struct idr *idr, int id)
225 spin_lock_bh(&cgroup_idr_lock);
227 spin_unlock_bh(&cgroup_idr_lock);
231 * cgroup_css - obtain a cgroup's css for the specified subsystem
232 * @cgrp: the cgroup of interest
233 * @ss: the subsystem of interest (%NULL returns the dummy_css)
235 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
236 * function must be called either under cgroup_mutex or rcu_read_lock() and
237 * the caller is responsible for pinning the returned css if it wants to
238 * keep accessing it outside the said locks. This function may return
239 * %NULL if @cgrp doesn't have @subsys_id enabled.
241 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
242 struct cgroup_subsys *ss)
245 return rcu_dereference_check(cgrp->subsys[ss->id],
246 lockdep_is_held(&cgroup_tree_mutex) ||
247 lockdep_is_held(&cgroup_mutex));
249 return &cgrp->dummy_css;
253 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
254 * @cgrp: the cgroup of interest
255 * @ss: the subsystem of interest (%NULL returns the dummy_css)
257 * Similar to cgroup_css() but returns the effctive css, which is defined
258 * as the matching css of the nearest ancestor including self which has @ss
259 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
260 * function is guaranteed to return non-NULL css.
262 static struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
263 struct cgroup_subsys *ss)
265 lockdep_assert_held(&cgroup_mutex);
268 return &cgrp->dummy_css;
270 if (!(cgrp->root->subsys_mask & (1 << ss->id)))
273 while (cgrp->parent &&
274 !(cgrp->parent->child_subsys_mask & (1 << ss->id)))
277 return cgroup_css(cgrp, ss);
280 /* convenient tests for these bits */
281 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
283 return test_bit(CGRP_DEAD, &cgrp->flags);
286 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
288 struct cgroup *cgrp = of->kn->parent->priv;
289 struct cftype *cft = of_cft(of);
292 * This is open and unprotected implementation of cgroup_css().
293 * seq_css() is only called from a kernfs file operation which has
294 * an active reference on the file. Because all the subsystem
295 * files are drained before a css is disassociated with a cgroup,
296 * the matching css from the cgroup's subsys table is guaranteed to
297 * be and stay valid until the enclosing operation is complete.
300 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
302 return &cgrp->dummy_css;
304 EXPORT_SYMBOL_GPL(of_css);
307 * cgroup_is_descendant - test ancestry
308 * @cgrp: the cgroup to be tested
309 * @ancestor: possible ancestor of @cgrp
311 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
312 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
313 * and @ancestor are accessible.
315 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
318 if (cgrp == ancestor)
325 static int cgroup_is_releasable(const struct cgroup *cgrp)
328 (1 << CGRP_RELEASABLE) |
329 (1 << CGRP_NOTIFY_ON_RELEASE);
330 return (cgrp->flags & bits) == bits;
333 static int notify_on_release(const struct cgroup *cgrp)
335 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
339 * for_each_css - iterate all css's of a cgroup
340 * @css: the iteration cursor
341 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
342 * @cgrp: the target cgroup to iterate css's of
344 * Should be called under cgroup_[tree_]mutex.
346 #define for_each_css(css, ssid, cgrp) \
347 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
348 if (!((css) = rcu_dereference_check( \
349 (cgrp)->subsys[(ssid)], \
350 lockdep_is_held(&cgroup_tree_mutex) || \
351 lockdep_is_held(&cgroup_mutex)))) { } \
355 * for_each_e_css - iterate all effective css's of a cgroup
356 * @css: the iteration cursor
357 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
358 * @cgrp: the target cgroup to iterate css's of
360 * Should be called under cgroup_[tree_]mutex.
362 #define for_each_e_css(css, ssid, cgrp) \
363 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
364 if (!((css) = cgroup_e_css(cgrp, cgroup_subsys[(ssid)]))) \
369 * for_each_subsys - iterate all enabled cgroup subsystems
370 * @ss: the iteration cursor
371 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
373 #define for_each_subsys(ss, ssid) \
374 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT && \
375 (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
377 /* iterate across the hierarchies */
378 #define for_each_root(root) \
379 list_for_each_entry((root), &cgroup_roots, root_list)
381 /* iterate over child cgrps, lock should be held throughout iteration */
382 #define cgroup_for_each_live_child(child, cgrp) \
383 list_for_each_entry((child), &(cgrp)->children, sibling) \
384 if (({ lockdep_assert_held(&cgroup_tree_mutex); \
385 cgroup_is_dead(child); })) \
389 /* the list of cgroups eligible for automatic release. Protected by
390 * release_list_lock */
391 static LIST_HEAD(release_list);
392 static DEFINE_RAW_SPINLOCK(release_list_lock);
393 static void cgroup_release_agent(struct work_struct *work);
394 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
395 static void check_for_release(struct cgroup *cgrp);
398 * A cgroup can be associated with multiple css_sets as different tasks may
399 * belong to different cgroups on different hierarchies. In the other
400 * direction, a css_set is naturally associated with multiple cgroups.
401 * This M:N relationship is represented by the following link structure
402 * which exists for each association and allows traversing the associations
405 struct cgrp_cset_link {
406 /* the cgroup and css_set this link associates */
408 struct css_set *cset;
410 /* list of cgrp_cset_links anchored at cgrp->cset_links */
411 struct list_head cset_link;
413 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
414 struct list_head cgrp_link;
418 * The default css_set - used by init and its children prior to any
419 * hierarchies being mounted. It contains a pointer to the root state
420 * for each subsystem. Also used to anchor the list of css_sets. Not
421 * reference-counted, to improve performance when child cgroups
422 * haven't been created.
424 struct css_set init_css_set = {
425 .refcount = ATOMIC_INIT(1),
426 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
427 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
428 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
429 .mg_preload_node = LIST_HEAD_INIT(init_css_set.mg_preload_node),
430 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
433 static int css_set_count = 1; /* 1 for init_css_set */
436 * cgroup_update_populated - updated populated count of a cgroup
437 * @cgrp: the target cgroup
438 * @populated: inc or dec populated count
440 * @cgrp is either getting the first task (css_set) or losing the last.
441 * Update @cgrp->populated_cnt accordingly. The count is propagated
442 * towards root so that a given cgroup's populated_cnt is zero iff the
443 * cgroup and all its descendants are empty.
445 * @cgrp's interface file "cgroup.populated" is zero if
446 * @cgrp->populated_cnt is zero and 1 otherwise. When @cgrp->populated_cnt
447 * changes from or to zero, userland is notified that the content of the
448 * interface file has changed. This can be used to detect when @cgrp and
449 * its descendants become populated or empty.
451 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
453 lockdep_assert_held(&css_set_rwsem);
459 trigger = !cgrp->populated_cnt++;
461 trigger = !--cgrp->populated_cnt;
466 if (cgrp->populated_kn)
467 kernfs_notify(cgrp->populated_kn);
473 * hash table for cgroup groups. This improves the performance to find
474 * an existing css_set. This hash doesn't (currently) take into
475 * account cgroups in empty hierarchies.
477 #define CSS_SET_HASH_BITS 7
478 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
480 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
482 unsigned long key = 0UL;
483 struct cgroup_subsys *ss;
486 for_each_subsys(ss, i)
487 key += (unsigned long)css[i];
488 key = (key >> 16) ^ key;
493 static void put_css_set_locked(struct css_set *cset, bool taskexit)
495 struct cgrp_cset_link *link, *tmp_link;
496 struct cgroup_subsys *ss;
499 lockdep_assert_held(&css_set_rwsem);
501 if (!atomic_dec_and_test(&cset->refcount))
504 /* This css_set is dead. unlink it and release cgroup refcounts */
505 for_each_subsys(ss, ssid)
506 list_del(&cset->e_cset_node[ssid]);
507 hash_del(&cset->hlist);
510 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
511 struct cgroup *cgrp = link->cgrp;
513 list_del(&link->cset_link);
514 list_del(&link->cgrp_link);
516 /* @cgrp can't go away while we're holding css_set_rwsem */
517 if (list_empty(&cgrp->cset_links)) {
518 cgroup_update_populated(cgrp, false);
519 if (notify_on_release(cgrp)) {
521 set_bit(CGRP_RELEASABLE, &cgrp->flags);
522 check_for_release(cgrp);
529 kfree_rcu(cset, rcu_head);
532 static void put_css_set(struct css_set *cset, bool taskexit)
535 * Ensure that the refcount doesn't hit zero while any readers
536 * can see it. Similar to atomic_dec_and_lock(), but for an
539 if (atomic_add_unless(&cset->refcount, -1, 1))
542 down_write(&css_set_rwsem);
543 put_css_set_locked(cset, taskexit);
544 up_write(&css_set_rwsem);
548 * refcounted get/put for css_set objects
550 static inline void get_css_set(struct css_set *cset)
552 atomic_inc(&cset->refcount);
556 * compare_css_sets - helper function for find_existing_css_set().
557 * @cset: candidate css_set being tested
558 * @old_cset: existing css_set for a task
559 * @new_cgrp: cgroup that's being entered by the task
560 * @template: desired set of css pointers in css_set (pre-calculated)
562 * Returns true if "cset" matches "old_cset" except for the hierarchy
563 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
565 static bool compare_css_sets(struct css_set *cset,
566 struct css_set *old_cset,
567 struct cgroup *new_cgrp,
568 struct cgroup_subsys_state *template[])
570 struct list_head *l1, *l2;
573 * On the default hierarchy, there can be csets which are
574 * associated with the same set of cgroups but different csses.
575 * Let's first ensure that csses match.
577 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
581 * Compare cgroup pointers in order to distinguish between
582 * different cgroups in hierarchies. As different cgroups may
583 * share the same effective css, this comparison is always
586 l1 = &cset->cgrp_links;
587 l2 = &old_cset->cgrp_links;
589 struct cgrp_cset_link *link1, *link2;
590 struct cgroup *cgrp1, *cgrp2;
594 /* See if we reached the end - both lists are equal length. */
595 if (l1 == &cset->cgrp_links) {
596 BUG_ON(l2 != &old_cset->cgrp_links);
599 BUG_ON(l2 == &old_cset->cgrp_links);
601 /* Locate the cgroups associated with these links. */
602 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
603 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
606 /* Hierarchies should be linked in the same order. */
607 BUG_ON(cgrp1->root != cgrp2->root);
610 * If this hierarchy is the hierarchy of the cgroup
611 * that's changing, then we need to check that this
612 * css_set points to the new cgroup; if it's any other
613 * hierarchy, then this css_set should point to the
614 * same cgroup as the old css_set.
616 if (cgrp1->root == new_cgrp->root) {
617 if (cgrp1 != new_cgrp)
628 * find_existing_css_set - init css array and find the matching css_set
629 * @old_cset: the css_set that we're using before the cgroup transition
630 * @cgrp: the cgroup that we're moving into
631 * @template: out param for the new set of csses, should be clear on entry
633 static struct css_set *find_existing_css_set(struct css_set *old_cset,
635 struct cgroup_subsys_state *template[])
637 struct cgroup_root *root = cgrp->root;
638 struct cgroup_subsys *ss;
639 struct css_set *cset;
644 * Build the set of subsystem state objects that we want to see in the
645 * new css_set. while subsystems can change globally, the entries here
646 * won't change, so no need for locking.
648 for_each_subsys(ss, i) {
649 if (root->subsys_mask & (1UL << i)) {
651 * @ss is in this hierarchy, so we want the
652 * effective css from @cgrp.
654 template[i] = cgroup_e_css(cgrp, ss);
657 * @ss is not in this hierarchy, so we don't want
660 template[i] = old_cset->subsys[i];
664 key = css_set_hash(template);
665 hash_for_each_possible(css_set_table, cset, hlist, key) {
666 if (!compare_css_sets(cset, old_cset, cgrp, template))
669 /* This css_set matches what we need */
673 /* No existing cgroup group matched */
677 static void free_cgrp_cset_links(struct list_head *links_to_free)
679 struct cgrp_cset_link *link, *tmp_link;
681 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
682 list_del(&link->cset_link);
688 * allocate_cgrp_cset_links - allocate cgrp_cset_links
689 * @count: the number of links to allocate
690 * @tmp_links: list_head the allocated links are put on
692 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
693 * through ->cset_link. Returns 0 on success or -errno.
695 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
697 struct cgrp_cset_link *link;
700 INIT_LIST_HEAD(tmp_links);
702 for (i = 0; i < count; i++) {
703 link = kzalloc(sizeof(*link), GFP_KERNEL);
705 free_cgrp_cset_links(tmp_links);
708 list_add(&link->cset_link, tmp_links);
714 * link_css_set - a helper function to link a css_set to a cgroup
715 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
716 * @cset: the css_set to be linked
717 * @cgrp: the destination cgroup
719 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
722 struct cgrp_cset_link *link;
724 BUG_ON(list_empty(tmp_links));
726 if (cgroup_on_dfl(cgrp))
727 cset->dfl_cgrp = cgrp;
729 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
733 if (list_empty(&cgrp->cset_links))
734 cgroup_update_populated(cgrp, true);
735 list_move(&link->cset_link, &cgrp->cset_links);
738 * Always add links to the tail of the list so that the list
739 * is sorted by order of hierarchy creation
741 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
745 * find_css_set - return a new css_set with one cgroup updated
746 * @old_cset: the baseline css_set
747 * @cgrp: the cgroup to be updated
749 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
750 * substituted into the appropriate hierarchy.
752 static struct css_set *find_css_set(struct css_set *old_cset,
755 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
756 struct css_set *cset;
757 struct list_head tmp_links;
758 struct cgrp_cset_link *link;
759 struct cgroup_subsys *ss;
763 lockdep_assert_held(&cgroup_mutex);
765 /* First see if we already have a cgroup group that matches
767 down_read(&css_set_rwsem);
768 cset = find_existing_css_set(old_cset, cgrp, template);
771 up_read(&css_set_rwsem);
776 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
780 /* Allocate all the cgrp_cset_link objects that we'll need */
781 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
786 atomic_set(&cset->refcount, 1);
787 INIT_LIST_HEAD(&cset->cgrp_links);
788 INIT_LIST_HEAD(&cset->tasks);
789 INIT_LIST_HEAD(&cset->mg_tasks);
790 INIT_LIST_HEAD(&cset->mg_preload_node);
791 INIT_LIST_HEAD(&cset->mg_node);
792 INIT_HLIST_NODE(&cset->hlist);
794 /* Copy the set of subsystem state objects generated in
795 * find_existing_css_set() */
796 memcpy(cset->subsys, template, sizeof(cset->subsys));
798 down_write(&css_set_rwsem);
799 /* Add reference counts and links from the new css_set. */
800 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
801 struct cgroup *c = link->cgrp;
803 if (c->root == cgrp->root)
805 link_css_set(&tmp_links, cset, c);
808 BUG_ON(!list_empty(&tmp_links));
812 /* Add @cset to the hash table */
813 key = css_set_hash(cset->subsys);
814 hash_add(css_set_table, &cset->hlist, key);
816 for_each_subsys(ss, ssid)
817 list_add_tail(&cset->e_cset_node[ssid],
818 &cset->subsys[ssid]->cgroup->e_csets[ssid]);
820 up_write(&css_set_rwsem);
825 static struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
827 struct cgroup *root_cgrp = kf_root->kn->priv;
829 return root_cgrp->root;
832 static int cgroup_init_root_id(struct cgroup_root *root)
836 lockdep_assert_held(&cgroup_mutex);
838 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
842 root->hierarchy_id = id;
846 static void cgroup_exit_root_id(struct cgroup_root *root)
848 lockdep_assert_held(&cgroup_mutex);
850 if (root->hierarchy_id) {
851 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
852 root->hierarchy_id = 0;
856 static void cgroup_free_root(struct cgroup_root *root)
859 /* hierarhcy ID shoulid already have been released */
860 WARN_ON_ONCE(root->hierarchy_id);
862 idr_destroy(&root->cgroup_idr);
867 static void cgroup_destroy_root(struct cgroup_root *root)
869 struct cgroup *cgrp = &root->cgrp;
870 struct cgrp_cset_link *link, *tmp_link;
872 mutex_lock(&cgroup_tree_mutex);
873 mutex_lock(&cgroup_mutex);
875 BUG_ON(atomic_read(&root->nr_cgrps));
876 BUG_ON(!list_empty(&cgrp->children));
878 /* Rebind all subsystems back to the default hierarchy */
879 rebind_subsystems(&cgrp_dfl_root, root->subsys_mask);
882 * Release all the links from cset_links to this hierarchy's
885 down_write(&css_set_rwsem);
887 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
888 list_del(&link->cset_link);
889 list_del(&link->cgrp_link);
892 up_write(&css_set_rwsem);
894 if (!list_empty(&root->root_list)) {
895 list_del(&root->root_list);
899 cgroup_exit_root_id(root);
901 mutex_unlock(&cgroup_mutex);
902 mutex_unlock(&cgroup_tree_mutex);
904 kernfs_destroy_root(root->kf_root);
905 cgroup_free_root(root);
908 /* look up cgroup associated with given css_set on the specified hierarchy */
909 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
910 struct cgroup_root *root)
912 struct cgroup *res = NULL;
914 lockdep_assert_held(&cgroup_mutex);
915 lockdep_assert_held(&css_set_rwsem);
917 if (cset == &init_css_set) {
920 struct cgrp_cset_link *link;
922 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
923 struct cgroup *c = link->cgrp;
925 if (c->root == root) {
937 * Return the cgroup for "task" from the given hierarchy. Must be
938 * called with cgroup_mutex and css_set_rwsem held.
940 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
941 struct cgroup_root *root)
944 * No need to lock the task - since we hold cgroup_mutex the
945 * task can't change groups, so the only thing that can happen
946 * is that it exits and its css is set back to init_css_set.
948 return cset_cgroup_from_root(task_css_set(task), root);
952 * A task must hold cgroup_mutex to modify cgroups.
954 * Any task can increment and decrement the count field without lock.
955 * So in general, code holding cgroup_mutex can't rely on the count
956 * field not changing. However, if the count goes to zero, then only
957 * cgroup_attach_task() can increment it again. Because a count of zero
958 * means that no tasks are currently attached, therefore there is no
959 * way a task attached to that cgroup can fork (the other way to
960 * increment the count). So code holding cgroup_mutex can safely
961 * assume that if the count is zero, it will stay zero. Similarly, if
962 * a task holds cgroup_mutex on a cgroup with zero count, it
963 * knows that the cgroup won't be removed, as cgroup_rmdir()
966 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
967 * (usually) take cgroup_mutex. These are the two most performance
968 * critical pieces of code here. The exception occurs on cgroup_exit(),
969 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
970 * is taken, and if the cgroup count is zero, a usermode call made
971 * to the release agent with the name of the cgroup (path relative to
972 * the root of cgroup file system) as the argument.
974 * A cgroup can only be deleted if both its 'count' of using tasks
975 * is zero, and its list of 'children' cgroups is empty. Since all
976 * tasks in the system use _some_ cgroup, and since there is always at
977 * least one task in the system (init, pid == 1), therefore, root cgroup
978 * always has either children cgroups and/or using tasks. So we don't
979 * need a special hack to ensure that root cgroup cannot be deleted.
981 * P.S. One more locking exception. RCU is used to guard the
982 * update of a tasks cgroup pointer by cgroup_attach_task()
985 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned int subsys_mask);
986 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
987 static const struct file_operations proc_cgroupstats_operations;
989 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
992 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
993 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
994 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
995 cft->ss->name, cft->name);
997 strncpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
1002 * cgroup_file_mode - deduce file mode of a control file
1003 * @cft: the control file in question
1005 * returns cft->mode if ->mode is not 0
1006 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
1007 * returns S_IRUGO if it has only a read handler
1008 * returns S_IWUSR if it has only a write hander
1010 static umode_t cgroup_file_mode(const struct cftype *cft)
1017 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1020 if (cft->write_u64 || cft->write_s64 || cft->write)
1026 static void cgroup_free_fn(struct work_struct *work)
1028 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
1030 atomic_dec(&cgrp->root->nr_cgrps);
1031 cgroup_pidlist_destroy_all(cgrp);
1035 * We get a ref to the parent, and put the ref when this
1036 * cgroup is being freed, so it's guaranteed that the
1037 * parent won't be destroyed before its children.
1039 cgroup_put(cgrp->parent);
1040 kernfs_put(cgrp->kn);
1044 * This is root cgroup's refcnt reaching zero, which
1045 * indicates that the root should be released.
1047 cgroup_destroy_root(cgrp->root);
1051 static void cgroup_free_rcu(struct rcu_head *head)
1053 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
1055 INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
1056 queue_work(cgroup_destroy_wq, &cgrp->destroy_work);
1059 static void cgroup_get(struct cgroup *cgrp)
1061 WARN_ON_ONCE(cgroup_is_dead(cgrp));
1062 WARN_ON_ONCE(atomic_read(&cgrp->refcnt) <= 0);
1063 atomic_inc(&cgrp->refcnt);
1066 static void cgroup_put(struct cgroup *cgrp)
1068 if (!atomic_dec_and_test(&cgrp->refcnt))
1070 if (WARN_ON_ONCE(cgrp->parent && !cgroup_is_dead(cgrp)))
1073 cgroup_idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
1076 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
1080 * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
1081 * @kn: the kernfs_node being serviced
1083 * This helper undoes cgroup_kn_lock_live() and should be invoked before
1084 * the method finishes if locking succeeded. Note that once this function
1085 * returns the cgroup returned by cgroup_kn_lock_live() may become
1086 * inaccessible any time. If the caller intends to continue to access the
1087 * cgroup, it should pin it before invoking this function.
1089 static void cgroup_kn_unlock(struct kernfs_node *kn)
1091 struct cgroup *cgrp;
1093 if (kernfs_type(kn) == KERNFS_DIR)
1096 cgrp = kn->parent->priv;
1098 mutex_unlock(&cgroup_mutex);
1099 mutex_unlock(&cgroup_tree_mutex);
1101 kernfs_unbreak_active_protection(kn);
1106 * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
1107 * @kn: the kernfs_node being serviced
1109 * This helper is to be used by a cgroup kernfs method currently servicing
1110 * @kn. It breaks the active protection, performs cgroup locking and
1111 * verifies that the associated cgroup is alive. Returns the cgroup if
1112 * alive; otherwise, %NULL. A successful return should be undone by a
1113 * matching cgroup_kn_unlock() invocation.
1115 * Any cgroup kernfs method implementation which requires locking the
1116 * associated cgroup should use this helper. It avoids nesting cgroup
1117 * locking under kernfs active protection and allows all kernfs operations
1118 * including self-removal.
1120 static struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn)
1122 struct cgroup *cgrp;
1124 if (kernfs_type(kn) == KERNFS_DIR)
1127 cgrp = kn->parent->priv;
1130 * We're gonna grab cgroup_tree_mutex which nests outside kernfs
1131 * active_ref. cgroup liveliness check alone provides enough
1132 * protection against removal. Ensure @cgrp stays accessible and
1133 * break the active_ref protection.
1136 kernfs_break_active_protection(kn);
1138 mutex_lock(&cgroup_tree_mutex);
1139 mutex_lock(&cgroup_mutex);
1141 if (!cgroup_is_dead(cgrp))
1144 cgroup_kn_unlock(kn);
1148 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1150 char name[CGROUP_FILE_NAME_MAX];
1152 lockdep_assert_held(&cgroup_tree_mutex);
1153 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1157 * cgroup_clear_dir - remove subsys files in a cgroup directory
1158 * @cgrp: target cgroup
1159 * @subsys_mask: mask of the subsystem ids whose files should be removed
1161 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned int subsys_mask)
1163 struct cgroup_subsys *ss;
1166 for_each_subsys(ss, i) {
1167 struct cftype *cfts;
1169 if (!(subsys_mask & (1 << i)))
1171 list_for_each_entry(cfts, &ss->cfts, node)
1172 cgroup_addrm_files(cgrp, cfts, false);
1176 static int rebind_subsystems(struct cgroup_root *dst_root, unsigned int ss_mask)
1178 struct cgroup_subsys *ss;
1181 lockdep_assert_held(&cgroup_tree_mutex);
1182 lockdep_assert_held(&cgroup_mutex);
1184 for_each_subsys(ss, ssid) {
1185 if (!(ss_mask & (1 << ssid)))
1188 /* if @ss has non-root csses attached to it, can't move */
1189 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)))
1192 /* can't move between two non-dummy roots either */
1193 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1197 ret = cgroup_populate_dir(&dst_root->cgrp, ss_mask);
1199 if (dst_root != &cgrp_dfl_root)
1203 * Rebinding back to the default root is not allowed to
1204 * fail. Using both default and non-default roots should
1205 * be rare. Moving subsystems back and forth even more so.
1206 * Just warn about it and continue.
1208 if (cgrp_dfl_root_visible) {
1209 pr_warn("failed to create files (%d) while rebinding 0x%x to default root\n",
1211 pr_warn("you may retry by moving them to a different hierarchy and unbinding\n");
1216 * Nothing can fail from this point on. Remove files for the
1217 * removed subsystems and rebind each subsystem.
1219 mutex_unlock(&cgroup_mutex);
1220 for_each_subsys(ss, ssid)
1221 if (ss_mask & (1 << ssid))
1222 cgroup_clear_dir(&ss->root->cgrp, 1 << ssid);
1223 mutex_lock(&cgroup_mutex);
1225 for_each_subsys(ss, ssid) {
1226 struct cgroup_root *src_root;
1227 struct cgroup_subsys_state *css;
1228 struct css_set *cset;
1230 if (!(ss_mask & (1 << ssid)))
1233 src_root = ss->root;
1234 css = cgroup_css(&src_root->cgrp, ss);
1236 WARN_ON(!css || cgroup_css(&dst_root->cgrp, ss));
1238 RCU_INIT_POINTER(src_root->cgrp.subsys[ssid], NULL);
1239 rcu_assign_pointer(dst_root->cgrp.subsys[ssid], css);
1240 ss->root = dst_root;
1241 css->cgroup = &dst_root->cgrp;
1243 down_write(&css_set_rwsem);
1244 hash_for_each(css_set_table, i, cset, hlist)
1245 list_move_tail(&cset->e_cset_node[ss->id],
1246 &dst_root->cgrp.e_csets[ss->id]);
1247 up_write(&css_set_rwsem);
1249 src_root->subsys_mask &= ~(1 << ssid);
1250 src_root->cgrp.child_subsys_mask &= ~(1 << ssid);
1252 /* default hierarchy doesn't enable controllers by default */
1253 dst_root->subsys_mask |= 1 << ssid;
1254 if (dst_root != &cgrp_dfl_root)
1255 dst_root->cgrp.child_subsys_mask |= 1 << ssid;
1261 kernfs_activate(dst_root->cgrp.kn);
1265 static int cgroup_show_options(struct seq_file *seq,
1266 struct kernfs_root *kf_root)
1268 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1269 struct cgroup_subsys *ss;
1272 for_each_subsys(ss, ssid)
1273 if (root->subsys_mask & (1 << ssid))
1274 seq_printf(seq, ",%s", ss->name);
1275 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1276 seq_puts(seq, ",sane_behavior");
1277 if (root->flags & CGRP_ROOT_NOPREFIX)
1278 seq_puts(seq, ",noprefix");
1279 if (root->flags & CGRP_ROOT_XATTR)
1280 seq_puts(seq, ",xattr");
1282 spin_lock(&release_agent_path_lock);
1283 if (strlen(root->release_agent_path))
1284 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1285 spin_unlock(&release_agent_path_lock);
1287 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags))
1288 seq_puts(seq, ",clone_children");
1289 if (strlen(root->name))
1290 seq_printf(seq, ",name=%s", root->name);
1294 struct cgroup_sb_opts {
1295 unsigned int subsys_mask;
1297 char *release_agent;
1298 bool cpuset_clone_children;
1300 /* User explicitly requested empty subsystem */
1304 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1306 char *token, *o = data;
1307 bool all_ss = false, one_ss = false;
1308 unsigned int mask = -1U;
1309 struct cgroup_subsys *ss;
1312 #ifdef CONFIG_CPUSETS
1313 mask = ~(1U << cpuset_cgrp_id);
1316 memset(opts, 0, sizeof(*opts));
1318 while ((token = strsep(&o, ",")) != NULL) {
1321 if (!strcmp(token, "none")) {
1322 /* Explicitly have no subsystems */
1326 if (!strcmp(token, "all")) {
1327 /* Mutually exclusive option 'all' + subsystem name */
1333 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1334 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1337 if (!strcmp(token, "noprefix")) {
1338 opts->flags |= CGRP_ROOT_NOPREFIX;
1341 if (!strcmp(token, "clone_children")) {
1342 opts->cpuset_clone_children = true;
1345 if (!strcmp(token, "xattr")) {
1346 opts->flags |= CGRP_ROOT_XATTR;
1349 if (!strncmp(token, "release_agent=", 14)) {
1350 /* Specifying two release agents is forbidden */
1351 if (opts->release_agent)
1353 opts->release_agent =
1354 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1355 if (!opts->release_agent)
1359 if (!strncmp(token, "name=", 5)) {
1360 const char *name = token + 5;
1361 /* Can't specify an empty name */
1364 /* Must match [\w.-]+ */
1365 for (i = 0; i < strlen(name); i++) {
1369 if ((c == '.') || (c == '-') || (c == '_'))
1373 /* Specifying two names is forbidden */
1376 opts->name = kstrndup(name,
1377 MAX_CGROUP_ROOT_NAMELEN - 1,
1385 for_each_subsys(ss, i) {
1386 if (strcmp(token, ss->name))
1391 /* Mutually exclusive option 'all' + subsystem name */
1394 opts->subsys_mask |= (1 << i);
1399 if (i == CGROUP_SUBSYS_COUNT)
1403 /* Consistency checks */
1405 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1406 pr_warn("sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1408 if ((opts->flags & (CGRP_ROOT_NOPREFIX | CGRP_ROOT_XATTR)) ||
1409 opts->cpuset_clone_children || opts->release_agent ||
1411 pr_err("sane_behavior: noprefix, xattr, clone_children, release_agent and name are not allowed\n");
1416 * If the 'all' option was specified select all the
1417 * subsystems, otherwise if 'none', 'name=' and a subsystem
1418 * name options were not specified, let's default to 'all'
1420 if (all_ss || (!one_ss && !opts->none && !opts->name))
1421 for_each_subsys(ss, i)
1423 opts->subsys_mask |= (1 << i);
1426 * We either have to specify by name or by subsystems. (So
1427 * all empty hierarchies must have a name).
1429 if (!opts->subsys_mask && !opts->name)
1434 * Option noprefix was introduced just for backward compatibility
1435 * with the old cpuset, so we allow noprefix only if mounting just
1436 * the cpuset subsystem.
1438 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1442 /* Can't specify "none" and some subsystems */
1443 if (opts->subsys_mask && opts->none)
1449 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1452 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1453 struct cgroup_sb_opts opts;
1454 unsigned int added_mask, removed_mask;
1456 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1457 pr_err("sane_behavior: remount is not allowed\n");
1461 mutex_lock(&cgroup_tree_mutex);
1462 mutex_lock(&cgroup_mutex);
1464 /* See what subsystems are wanted */
1465 ret = parse_cgroupfs_options(data, &opts);
1469 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1470 pr_warn("option changes via remount are deprecated (pid=%d comm=%s)\n",
1471 task_tgid_nr(current), current->comm);
1473 added_mask = opts.subsys_mask & ~root->subsys_mask;
1474 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1476 /* Don't allow flags or name to change at remount */
1477 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1478 (opts.name && strcmp(opts.name, root->name))) {
1479 pr_err("option or name mismatch, new: 0x%x \"%s\", old: 0x%x \"%s\"\n",
1480 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1481 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1486 /* remounting is not allowed for populated hierarchies */
1487 if (!list_empty(&root->cgrp.children)) {
1492 ret = rebind_subsystems(root, added_mask);
1496 rebind_subsystems(&cgrp_dfl_root, removed_mask);
1498 if (opts.release_agent) {
1499 spin_lock(&release_agent_path_lock);
1500 strcpy(root->release_agent_path, opts.release_agent);
1501 spin_unlock(&release_agent_path_lock);
1504 kfree(opts.release_agent);
1506 mutex_unlock(&cgroup_mutex);
1507 mutex_unlock(&cgroup_tree_mutex);
1512 * To reduce the fork() overhead for systems that are not actually using
1513 * their cgroups capability, we don't maintain the lists running through
1514 * each css_set to its tasks until we see the list actually used - in other
1515 * words after the first mount.
1517 static bool use_task_css_set_links __read_mostly;
1519 static void cgroup_enable_task_cg_lists(void)
1521 struct task_struct *p, *g;
1523 down_write(&css_set_rwsem);
1525 if (use_task_css_set_links)
1528 use_task_css_set_links = true;
1531 * We need tasklist_lock because RCU is not safe against
1532 * while_each_thread(). Besides, a forking task that has passed
1533 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1534 * is not guaranteed to have its child immediately visible in the
1535 * tasklist if we walk through it with RCU.
1537 read_lock(&tasklist_lock);
1538 do_each_thread(g, p) {
1539 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1540 task_css_set(p) != &init_css_set);
1543 * We should check if the process is exiting, otherwise
1544 * it will race with cgroup_exit() in that the list
1545 * entry won't be deleted though the process has exited.
1546 * Do it while holding siglock so that we don't end up
1547 * racing against cgroup_exit().
1549 spin_lock_irq(&p->sighand->siglock);
1550 if (!(p->flags & PF_EXITING)) {
1551 struct css_set *cset = task_css_set(p);
1553 list_add(&p->cg_list, &cset->tasks);
1556 spin_unlock_irq(&p->sighand->siglock);
1557 } while_each_thread(g, p);
1558 read_unlock(&tasklist_lock);
1560 up_write(&css_set_rwsem);
1563 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1565 struct cgroup_subsys *ss;
1568 atomic_set(&cgrp->refcnt, 1);
1569 INIT_LIST_HEAD(&cgrp->sibling);
1570 INIT_LIST_HEAD(&cgrp->children);
1571 INIT_LIST_HEAD(&cgrp->cset_links);
1572 INIT_LIST_HEAD(&cgrp->release_list);
1573 INIT_LIST_HEAD(&cgrp->pidlists);
1574 mutex_init(&cgrp->pidlist_mutex);
1575 cgrp->dummy_css.cgroup = cgrp;
1577 for_each_subsys(ss, ssid)
1578 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
1580 init_waitqueue_head(&cgrp->offline_waitq);
1583 static void init_cgroup_root(struct cgroup_root *root,
1584 struct cgroup_sb_opts *opts)
1586 struct cgroup *cgrp = &root->cgrp;
1588 INIT_LIST_HEAD(&root->root_list);
1589 atomic_set(&root->nr_cgrps, 1);
1591 init_cgroup_housekeeping(cgrp);
1592 idr_init(&root->cgroup_idr);
1594 root->flags = opts->flags;
1595 if (opts->release_agent)
1596 strcpy(root->release_agent_path, opts->release_agent);
1598 strcpy(root->name, opts->name);
1599 if (opts->cpuset_clone_children)
1600 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1603 static int cgroup_setup_root(struct cgroup_root *root, unsigned int ss_mask)
1605 LIST_HEAD(tmp_links);
1606 struct cgroup *root_cgrp = &root->cgrp;
1607 struct css_set *cset;
1610 lockdep_assert_held(&cgroup_tree_mutex);
1611 lockdep_assert_held(&cgroup_mutex);
1613 ret = cgroup_idr_alloc(&root->cgroup_idr, root_cgrp, 1, 2, GFP_NOWAIT);
1616 root_cgrp->id = ret;
1619 * We're accessing css_set_count without locking css_set_rwsem here,
1620 * but that's OK - it can only be increased by someone holding
1621 * cgroup_lock, and that's us. The worst that can happen is that we
1622 * have some link structures left over
1624 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1628 ret = cgroup_init_root_id(root);
1632 root->kf_root = kernfs_create_root(&cgroup_kf_syscall_ops,
1633 KERNFS_ROOT_CREATE_DEACTIVATED,
1635 if (IS_ERR(root->kf_root)) {
1636 ret = PTR_ERR(root->kf_root);
1639 root_cgrp->kn = root->kf_root->kn;
1641 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1645 ret = rebind_subsystems(root, ss_mask);
1650 * There must be no failure case after here, since rebinding takes
1651 * care of subsystems' refcounts, which are explicitly dropped in
1652 * the failure exit path.
1654 list_add(&root->root_list, &cgroup_roots);
1655 cgroup_root_count++;
1658 * Link the root cgroup in this hierarchy into all the css_set
1661 down_write(&css_set_rwsem);
1662 hash_for_each(css_set_table, i, cset, hlist)
1663 link_css_set(&tmp_links, cset, root_cgrp);
1664 up_write(&css_set_rwsem);
1666 BUG_ON(!list_empty(&root_cgrp->children));
1667 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
1669 kernfs_activate(root_cgrp->kn);
1674 kernfs_destroy_root(root->kf_root);
1675 root->kf_root = NULL;
1677 cgroup_exit_root_id(root);
1679 free_cgrp_cset_links(&tmp_links);
1683 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1684 int flags, const char *unused_dev_name,
1687 struct cgroup_root *root;
1688 struct cgroup_sb_opts opts;
1689 struct dentry *dentry;
1694 * The first time anyone tries to mount a cgroup, enable the list
1695 * linking each css_set to its tasks and fix up all existing tasks.
1697 if (!use_task_css_set_links)
1698 cgroup_enable_task_cg_lists();
1700 mutex_lock(&cgroup_tree_mutex);
1701 mutex_lock(&cgroup_mutex);
1703 /* First find the desired set of subsystems */
1704 ret = parse_cgroupfs_options(data, &opts);
1708 /* look for a matching existing root */
1709 if (!opts.subsys_mask && !opts.none && !opts.name) {
1710 cgrp_dfl_root_visible = true;
1711 root = &cgrp_dfl_root;
1712 cgroup_get(&root->cgrp);
1717 for_each_root(root) {
1718 bool name_match = false;
1720 if (root == &cgrp_dfl_root)
1724 * If we asked for a name then it must match. Also, if
1725 * name matches but sybsys_mask doesn't, we should fail.
1726 * Remember whether name matched.
1729 if (strcmp(opts.name, root->name))
1735 * If we asked for subsystems (or explicitly for no
1736 * subsystems) then they must match.
1738 if ((opts.subsys_mask || opts.none) &&
1739 (opts.subsys_mask != root->subsys_mask)) {
1746 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1747 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1748 pr_err("sane_behavior: new mount options should match the existing superblock\n");
1752 pr_warn("new mount options do not match the existing superblock, will be ignored\n");
1757 * A root's lifetime is governed by its root cgroup. Zero
1758 * ref indicate that the root is being destroyed. Wait for
1759 * destruction to complete so that the subsystems are free.
1760 * We can use wait_queue for the wait but this path is
1761 * super cold. Let's just sleep for a bit and retry.
1763 if (!atomic_inc_not_zero(&root->cgrp.refcnt)) {
1764 mutex_unlock(&cgroup_mutex);
1765 mutex_unlock(&cgroup_tree_mutex);
1767 mutex_lock(&cgroup_tree_mutex);
1768 mutex_lock(&cgroup_mutex);
1777 * No such thing, create a new one. name= matching without subsys
1778 * specification is allowed for already existing hierarchies but we
1779 * can't create new one without subsys specification.
1781 if (!opts.subsys_mask && !opts.none) {
1786 root = kzalloc(sizeof(*root), GFP_KERNEL);
1792 init_cgroup_root(root, &opts);
1794 ret = cgroup_setup_root(root, opts.subsys_mask);
1796 cgroup_free_root(root);
1799 mutex_unlock(&cgroup_mutex);
1800 mutex_unlock(&cgroup_tree_mutex);
1802 kfree(opts.release_agent);
1806 return ERR_PTR(ret);
1808 dentry = kernfs_mount(fs_type, flags, root->kf_root, &new_sb);
1809 if (IS_ERR(dentry) || !new_sb)
1810 cgroup_put(&root->cgrp);
1814 static void cgroup_kill_sb(struct super_block *sb)
1816 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
1817 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1819 cgroup_put(&root->cgrp);
1823 static struct file_system_type cgroup_fs_type = {
1825 .mount = cgroup_mount,
1826 .kill_sb = cgroup_kill_sb,
1829 static struct kobject *cgroup_kobj;
1832 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1833 * @task: target task
1834 * @buf: the buffer to write the path into
1835 * @buflen: the length of the buffer
1837 * Determine @task's cgroup on the first (the one with the lowest non-zero
1838 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1839 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1840 * cgroup controller callbacks.
1842 * Return value is the same as kernfs_path().
1844 char *task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1846 struct cgroup_root *root;
1847 struct cgroup *cgrp;
1848 int hierarchy_id = 1;
1851 mutex_lock(&cgroup_mutex);
1852 down_read(&css_set_rwsem);
1854 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1857 cgrp = task_cgroup_from_root(task, root);
1858 path = cgroup_path(cgrp, buf, buflen);
1860 /* if no hierarchy exists, everyone is in "/" */
1861 if (strlcpy(buf, "/", buflen) < buflen)
1865 up_read(&css_set_rwsem);
1866 mutex_unlock(&cgroup_mutex);
1869 EXPORT_SYMBOL_GPL(task_cgroup_path);
1871 /* used to track tasks and other necessary states during migration */
1872 struct cgroup_taskset {
1873 /* the src and dst cset list running through cset->mg_node */
1874 struct list_head src_csets;
1875 struct list_head dst_csets;
1878 * Fields for cgroup_taskset_*() iteration.
1880 * Before migration is committed, the target migration tasks are on
1881 * ->mg_tasks of the csets on ->src_csets. After, on ->mg_tasks of
1882 * the csets on ->dst_csets. ->csets point to either ->src_csets
1883 * or ->dst_csets depending on whether migration is committed.
1885 * ->cur_csets and ->cur_task point to the current task position
1888 struct list_head *csets;
1889 struct css_set *cur_cset;
1890 struct task_struct *cur_task;
1894 * cgroup_taskset_first - reset taskset and return the first task
1895 * @tset: taskset of interest
1897 * @tset iteration is initialized and the first task is returned.
1899 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1901 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
1902 tset->cur_task = NULL;
1904 return cgroup_taskset_next(tset);
1908 * cgroup_taskset_next - iterate to the next task in taskset
1909 * @tset: taskset of interest
1911 * Return the next task in @tset. Iteration must have been initialized
1912 * with cgroup_taskset_first().
1914 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1916 struct css_set *cset = tset->cur_cset;
1917 struct task_struct *task = tset->cur_task;
1919 while (&cset->mg_node != tset->csets) {
1921 task = list_first_entry(&cset->mg_tasks,
1922 struct task_struct, cg_list);
1924 task = list_next_entry(task, cg_list);
1926 if (&task->cg_list != &cset->mg_tasks) {
1927 tset->cur_cset = cset;
1928 tset->cur_task = task;
1932 cset = list_next_entry(cset, mg_node);
1940 * cgroup_task_migrate - move a task from one cgroup to another.
1941 * @old_cgrp: the cgroup @tsk is being migrated from
1942 * @tsk: the task being migrated
1943 * @new_cset: the new css_set @tsk is being attached to
1945 * Must be called with cgroup_mutex, threadgroup and css_set_rwsem locked.
1947 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1948 struct task_struct *tsk,
1949 struct css_set *new_cset)
1951 struct css_set *old_cset;
1953 lockdep_assert_held(&cgroup_mutex);
1954 lockdep_assert_held(&css_set_rwsem);
1957 * We are synchronized through threadgroup_lock() against PF_EXITING
1958 * setting such that we can't race against cgroup_exit() changing the
1959 * css_set to init_css_set and dropping the old one.
1961 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1962 old_cset = task_css_set(tsk);
1964 get_css_set(new_cset);
1965 rcu_assign_pointer(tsk->cgroups, new_cset);
1968 * Use move_tail so that cgroup_taskset_first() still returns the
1969 * leader after migration. This works because cgroup_migrate()
1970 * ensures that the dst_cset of the leader is the first on the
1971 * tset's dst_csets list.
1973 list_move_tail(&tsk->cg_list, &new_cset->mg_tasks);
1976 * We just gained a reference on old_cset by taking it from the
1977 * task. As trading it for new_cset is protected by cgroup_mutex,
1978 * we're safe to drop it here; it will be freed under RCU.
1980 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1981 put_css_set_locked(old_cset, false);
1985 * cgroup_migrate_finish - cleanup after attach
1986 * @preloaded_csets: list of preloaded css_sets
1988 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
1989 * those functions for details.
1991 static void cgroup_migrate_finish(struct list_head *preloaded_csets)
1993 struct css_set *cset, *tmp_cset;
1995 lockdep_assert_held(&cgroup_mutex);
1997 down_write(&css_set_rwsem);
1998 list_for_each_entry_safe(cset, tmp_cset, preloaded_csets, mg_preload_node) {
1999 cset->mg_src_cgrp = NULL;
2000 cset->mg_dst_cset = NULL;
2001 list_del_init(&cset->mg_preload_node);
2002 put_css_set_locked(cset, false);
2004 up_write(&css_set_rwsem);
2008 * cgroup_migrate_add_src - add a migration source css_set
2009 * @src_cset: the source css_set to add
2010 * @dst_cgrp: the destination cgroup
2011 * @preloaded_csets: list of preloaded css_sets
2013 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
2014 * @src_cset and add it to @preloaded_csets, which should later be cleaned
2015 * up by cgroup_migrate_finish().
2017 * This function may be called without holding threadgroup_lock even if the
2018 * target is a process. Threads may be created and destroyed but as long
2019 * as cgroup_mutex is not dropped, no new css_set can be put into play and
2020 * the preloaded css_sets are guaranteed to cover all migrations.
2022 static void cgroup_migrate_add_src(struct css_set *src_cset,
2023 struct cgroup *dst_cgrp,
2024 struct list_head *preloaded_csets)
2026 struct cgroup *src_cgrp;
2028 lockdep_assert_held(&cgroup_mutex);
2029 lockdep_assert_held(&css_set_rwsem);
2031 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2033 if (!list_empty(&src_cset->mg_preload_node))
2036 WARN_ON(src_cset->mg_src_cgrp);
2037 WARN_ON(!list_empty(&src_cset->mg_tasks));
2038 WARN_ON(!list_empty(&src_cset->mg_node));
2040 src_cset->mg_src_cgrp = src_cgrp;
2041 get_css_set(src_cset);
2042 list_add(&src_cset->mg_preload_node, preloaded_csets);
2046 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2047 * @dst_cgrp: the destination cgroup (may be %NULL)
2048 * @preloaded_csets: list of preloaded source css_sets
2050 * Tasks are about to be moved to @dst_cgrp and all the source css_sets
2051 * have been preloaded to @preloaded_csets. This function looks up and
2052 * pins all destination css_sets, links each to its source, and append them
2053 * to @preloaded_csets. If @dst_cgrp is %NULL, the destination of each
2054 * source css_set is assumed to be its cgroup on the default hierarchy.
2056 * This function must be called after cgroup_migrate_add_src() has been
2057 * called on each migration source css_set. After migration is performed
2058 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2061 static int cgroup_migrate_prepare_dst(struct cgroup *dst_cgrp,
2062 struct list_head *preloaded_csets)
2065 struct css_set *src_cset, *tmp_cset;
2067 lockdep_assert_held(&cgroup_mutex);
2070 * Except for the root, child_subsys_mask must be zero for a cgroup
2071 * with tasks so that child cgroups don't compete against tasks.
2073 if (dst_cgrp && cgroup_on_dfl(dst_cgrp) && dst_cgrp->parent &&
2074 dst_cgrp->child_subsys_mask)
2077 /* look up the dst cset for each src cset and link it to src */
2078 list_for_each_entry_safe(src_cset, tmp_cset, preloaded_csets, mg_preload_node) {
2079 struct css_set *dst_cset;
2081 dst_cset = find_css_set(src_cset,
2082 dst_cgrp ?: src_cset->dfl_cgrp);
2086 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2089 * If src cset equals dst, it's noop. Drop the src.
2090 * cgroup_migrate() will skip the cset too. Note that we
2091 * can't handle src == dst as some nodes are used by both.
2093 if (src_cset == dst_cset) {
2094 src_cset->mg_src_cgrp = NULL;
2095 list_del_init(&src_cset->mg_preload_node);
2096 put_css_set(src_cset, false);
2097 put_css_set(dst_cset, false);
2101 src_cset->mg_dst_cset = dst_cset;
2103 if (list_empty(&dst_cset->mg_preload_node))
2104 list_add(&dst_cset->mg_preload_node, &csets);
2106 put_css_set(dst_cset, false);
2109 list_splice_tail(&csets, preloaded_csets);
2112 cgroup_migrate_finish(&csets);
2117 * cgroup_migrate - migrate a process or task to a cgroup
2118 * @cgrp: the destination cgroup
2119 * @leader: the leader of the process or the task to migrate
2120 * @threadgroup: whether @leader points to the whole process or a single task
2122 * Migrate a process or task denoted by @leader to @cgrp. If migrating a
2123 * process, the caller must be holding threadgroup_lock of @leader. The
2124 * caller is also responsible for invoking cgroup_migrate_add_src() and
2125 * cgroup_migrate_prepare_dst() on the targets before invoking this
2126 * function and following up with cgroup_migrate_finish().
2128 * As long as a controller's ->can_attach() doesn't fail, this function is
2129 * guaranteed to succeed. This means that, excluding ->can_attach()
2130 * failure, when migrating multiple targets, the success or failure can be
2131 * decided for all targets by invoking group_migrate_prepare_dst() before
2132 * actually starting migrating.
2134 static int cgroup_migrate(struct cgroup *cgrp, struct task_struct *leader,
2137 struct cgroup_taskset tset = {
2138 .src_csets = LIST_HEAD_INIT(tset.src_csets),
2139 .dst_csets = LIST_HEAD_INIT(tset.dst_csets),
2140 .csets = &tset.src_csets,
2142 struct cgroup_subsys_state *css, *failed_css = NULL;
2143 struct css_set *cset, *tmp_cset;
2144 struct task_struct *task, *tmp_task;
2148 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2149 * already PF_EXITING could be freed from underneath us unless we
2150 * take an rcu_read_lock.
2152 down_write(&css_set_rwsem);
2156 /* @task either already exited or can't exit until the end */
2157 if (task->flags & PF_EXITING)
2160 /* leave @task alone if post_fork() hasn't linked it yet */
2161 if (list_empty(&task->cg_list))
2164 cset = task_css_set(task);
2165 if (!cset->mg_src_cgrp)
2169 * cgroup_taskset_first() must always return the leader.
2170 * Take care to avoid disturbing the ordering.
2172 list_move_tail(&task->cg_list, &cset->mg_tasks);
2173 if (list_empty(&cset->mg_node))
2174 list_add_tail(&cset->mg_node, &tset.src_csets);
2175 if (list_empty(&cset->mg_dst_cset->mg_node))
2176 list_move_tail(&cset->mg_dst_cset->mg_node,
2181 } while_each_thread(leader, task);
2183 up_write(&css_set_rwsem);
2185 /* methods shouldn't be called if no task is actually migrating */
2186 if (list_empty(&tset.src_csets))
2189 /* check that we can legitimately attach to the cgroup */
2190 for_each_e_css(css, i, cgrp) {
2191 if (css->ss->can_attach) {
2192 ret = css->ss->can_attach(css, &tset);
2195 goto out_cancel_attach;
2201 * Now that we're guaranteed success, proceed to move all tasks to
2202 * the new cgroup. There are no failure cases after here, so this
2203 * is the commit point.
2205 down_write(&css_set_rwsem);
2206 list_for_each_entry(cset, &tset.src_csets, mg_node) {
2207 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list)
2208 cgroup_task_migrate(cset->mg_src_cgrp, task,
2211 up_write(&css_set_rwsem);
2214 * Migration is committed, all target tasks are now on dst_csets.
2215 * Nothing is sensitive to fork() after this point. Notify
2216 * controllers that migration is complete.
2218 tset.csets = &tset.dst_csets;
2220 for_each_e_css(css, i, cgrp)
2221 if (css->ss->attach)
2222 css->ss->attach(css, &tset);
2225 goto out_release_tset;
2228 for_each_e_css(css, i, cgrp) {
2229 if (css == failed_css)
2231 if (css->ss->cancel_attach)
2232 css->ss->cancel_attach(css, &tset);
2235 down_write(&css_set_rwsem);
2236 list_splice_init(&tset.dst_csets, &tset.src_csets);
2237 list_for_each_entry_safe(cset, tmp_cset, &tset.src_csets, mg_node) {
2238 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2239 list_del_init(&cset->mg_node);
2241 up_write(&css_set_rwsem);
2246 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2247 * @dst_cgrp: the cgroup to attach to
2248 * @leader: the task or the leader of the threadgroup to be attached
2249 * @threadgroup: attach the whole threadgroup?
2251 * Call holding cgroup_mutex and threadgroup_lock of @leader.
2253 static int cgroup_attach_task(struct cgroup *dst_cgrp,
2254 struct task_struct *leader, bool threadgroup)
2256 LIST_HEAD(preloaded_csets);
2257 struct task_struct *task;
2260 /* look up all src csets */
2261 down_read(&css_set_rwsem);
2265 cgroup_migrate_add_src(task_css_set(task), dst_cgrp,
2269 } while_each_thread(leader, task);
2271 up_read(&css_set_rwsem);
2273 /* prepare dst csets and commit */
2274 ret = cgroup_migrate_prepare_dst(dst_cgrp, &preloaded_csets);
2276 ret = cgroup_migrate(dst_cgrp, leader, threadgroup);
2278 cgroup_migrate_finish(&preloaded_csets);
2283 * Find the task_struct of the task to attach by vpid and pass it along to the
2284 * function to attach either it or all tasks in its threadgroup. Will lock
2285 * cgroup_mutex and threadgroup.
2287 static ssize_t __cgroup_procs_write(struct kernfs_open_file *of, char *buf,
2288 size_t nbytes, loff_t off, bool threadgroup)
2290 struct task_struct *tsk;
2291 const struct cred *cred = current_cred(), *tcred;
2292 struct cgroup *cgrp;
2296 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2299 cgrp = cgroup_kn_lock_live(of->kn);
2306 tsk = find_task_by_vpid(pid);
2310 goto out_unlock_cgroup;
2313 * even if we're attaching all tasks in the thread group, we
2314 * only need to check permissions on one of them.
2316 tcred = __task_cred(tsk);
2317 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2318 !uid_eq(cred->euid, tcred->uid) &&
2319 !uid_eq(cred->euid, tcred->suid)) {
2322 goto out_unlock_cgroup;
2328 tsk = tsk->group_leader;
2331 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2332 * trapped in a cpuset, or RT worker may be born in a cgroup
2333 * with no rt_runtime allocated. Just say no.
2335 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2338 goto out_unlock_cgroup;
2341 get_task_struct(tsk);
2344 threadgroup_lock(tsk);
2346 if (!thread_group_leader(tsk)) {
2348 * a race with de_thread from another thread's exec()
2349 * may strip us of our leadership, if this happens,
2350 * there is no choice but to throw this task away and
2351 * try again; this is
2352 * "double-double-toil-and-trouble-check locking".
2354 threadgroup_unlock(tsk);
2355 put_task_struct(tsk);
2356 goto retry_find_task;
2360 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2362 threadgroup_unlock(tsk);
2364 put_task_struct(tsk);
2366 cgroup_kn_unlock(of->kn);
2367 return ret ?: nbytes;
2371 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2372 * @from: attach to all cgroups of a given task
2373 * @tsk: the task to be attached
2375 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2377 struct cgroup_root *root;
2380 mutex_lock(&cgroup_mutex);
2381 for_each_root(root) {
2382 struct cgroup *from_cgrp;
2384 if (root == &cgrp_dfl_root)
2387 down_read(&css_set_rwsem);
2388 from_cgrp = task_cgroup_from_root(from, root);
2389 up_read(&css_set_rwsem);
2391 retval = cgroup_attach_task(from_cgrp, tsk, false);
2395 mutex_unlock(&cgroup_mutex);
2399 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2401 static ssize_t cgroup_tasks_write(struct kernfs_open_file *of,
2402 char *buf, size_t nbytes, loff_t off)
2404 return __cgroup_procs_write(of, buf, nbytes, off, false);
2407 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
2408 char *buf, size_t nbytes, loff_t off)
2410 return __cgroup_procs_write(of, buf, nbytes, off, true);
2413 static ssize_t cgroup_release_agent_write(struct kernfs_open_file *of,
2414 char *buf, size_t nbytes, loff_t off)
2416 struct cgroup *cgrp;
2418 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
2420 cgrp = cgroup_kn_lock_live(of->kn);
2423 spin_lock(&release_agent_path_lock);
2424 strlcpy(cgrp->root->release_agent_path, strstrip(buf),
2425 sizeof(cgrp->root->release_agent_path));
2426 spin_unlock(&release_agent_path_lock);
2427 cgroup_kn_unlock(of->kn);
2431 static int cgroup_release_agent_show(struct seq_file *seq, void *v)
2433 struct cgroup *cgrp = seq_css(seq)->cgroup;
2435 spin_lock(&release_agent_path_lock);
2436 seq_puts(seq, cgrp->root->release_agent_path);
2437 spin_unlock(&release_agent_path_lock);
2438 seq_putc(seq, '\n');
2442 static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
2444 struct cgroup *cgrp = seq_css(seq)->cgroup;
2446 seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
2450 static void cgroup_print_ss_mask(struct seq_file *seq, unsigned int ss_mask)
2452 struct cgroup_subsys *ss;
2453 bool printed = false;
2456 for_each_subsys(ss, ssid) {
2457 if (ss_mask & (1 << ssid)) {
2460 seq_printf(seq, "%s", ss->name);
2465 seq_putc(seq, '\n');
2468 /* show controllers which are currently attached to the default hierarchy */
2469 static int cgroup_root_controllers_show(struct seq_file *seq, void *v)
2471 struct cgroup *cgrp = seq_css(seq)->cgroup;
2473 cgroup_print_ss_mask(seq, cgrp->root->subsys_mask);
2477 /* show controllers which are enabled from the parent */
2478 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2480 struct cgroup *cgrp = seq_css(seq)->cgroup;
2482 cgroup_print_ss_mask(seq, cgrp->parent->child_subsys_mask);
2486 /* show controllers which are enabled for a given cgroup's children */
2487 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2489 struct cgroup *cgrp = seq_css(seq)->cgroup;
2491 cgroup_print_ss_mask(seq, cgrp->child_subsys_mask);
2496 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2497 * @cgrp: root of the subtree to update csses for
2499 * @cgrp's child_subsys_mask has changed and its subtree's (self excluded)
2500 * css associations need to be updated accordingly. This function looks up
2501 * all css_sets which are attached to the subtree, creates the matching
2502 * updated css_sets and migrates the tasks to the new ones.
2504 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2506 LIST_HEAD(preloaded_csets);
2507 struct cgroup_subsys_state *css;
2508 struct css_set *src_cset;
2511 lockdep_assert_held(&cgroup_tree_mutex);
2512 lockdep_assert_held(&cgroup_mutex);
2514 /* look up all csses currently attached to @cgrp's subtree */
2515 down_read(&css_set_rwsem);
2516 css_for_each_descendant_pre(css, cgroup_css(cgrp, NULL)) {
2517 struct cgrp_cset_link *link;
2519 /* self is not affected by child_subsys_mask change */
2520 if (css->cgroup == cgrp)
2523 list_for_each_entry(link, &css->cgroup->cset_links, cset_link)
2524 cgroup_migrate_add_src(link->cset, cgrp,
2527 up_read(&css_set_rwsem);
2529 /* NULL dst indicates self on default hierarchy */
2530 ret = cgroup_migrate_prepare_dst(NULL, &preloaded_csets);
2534 list_for_each_entry(src_cset, &preloaded_csets, mg_preload_node) {
2535 struct task_struct *last_task = NULL, *task;
2537 /* src_csets precede dst_csets, break on the first dst_cset */
2538 if (!src_cset->mg_src_cgrp)
2542 * All tasks in src_cset need to be migrated to the
2543 * matching dst_cset. Empty it process by process. We
2544 * walk tasks but migrate processes. The leader might even
2545 * belong to a different cset but such src_cset would also
2546 * be among the target src_csets because the default
2547 * hierarchy enforces per-process membership.
2550 down_read(&css_set_rwsem);
2551 task = list_first_entry_or_null(&src_cset->tasks,
2552 struct task_struct, cg_list);
2554 task = task->group_leader;
2555 WARN_ON_ONCE(!task_css_set(task)->mg_src_cgrp);
2556 get_task_struct(task);
2558 up_read(&css_set_rwsem);
2563 /* guard against possible infinite loop */
2564 if (WARN(last_task == task,
2565 "cgroup: update_dfl_csses failed to make progress, aborting in inconsistent state\n"))
2569 threadgroup_lock(task);
2570 /* raced against de_thread() from another thread? */
2571 if (!thread_group_leader(task)) {
2572 threadgroup_unlock(task);
2573 put_task_struct(task);
2577 ret = cgroup_migrate(src_cset->dfl_cgrp, task, true);
2579 threadgroup_unlock(task);
2580 put_task_struct(task);
2582 if (WARN(ret, "cgroup: failed to update controllers for the default hierarchy (%d), further operations may crash or hang\n", ret))
2588 cgroup_migrate_finish(&preloaded_csets);
2592 /* change the enabled child controllers for a cgroup in the default hierarchy */
2593 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
2594 char *buf, size_t nbytes,
2597 unsigned int enable = 0, disable = 0;
2598 struct cgroup *cgrp, *child;
2599 struct cgroup_subsys *ss;
2604 * Parse input - space separated list of subsystem names prefixed
2605 * with either + or -.
2607 buf = strstrip(buf);
2608 while ((tok = strsep(&buf, " "))) {
2611 for_each_subsys(ss, ssid) {
2612 if (ss->disabled || strcmp(tok + 1, ss->name))
2616 enable |= 1 << ssid;
2617 disable &= ~(1 << ssid);
2618 } else if (*tok == '-') {
2619 disable |= 1 << ssid;
2620 enable &= ~(1 << ssid);
2626 if (ssid == CGROUP_SUBSYS_COUNT)
2630 cgrp = cgroup_kn_lock_live(of->kn);
2634 for_each_subsys(ss, ssid) {
2635 if (enable & (1 << ssid)) {
2636 if (cgrp->child_subsys_mask & (1 << ssid)) {
2637 enable &= ~(1 << ssid);
2642 * Because css offlining is asynchronous, userland
2643 * might try to re-enable the same controller while
2644 * the previous instance is still around. In such
2645 * cases, wait till it's gone using offline_waitq.
2647 cgroup_for_each_live_child(child, cgrp) {
2650 if (!cgroup_css(child, ss))
2654 prepare_to_wait(&child->offline_waitq, &wait,
2655 TASK_UNINTERRUPTIBLE);
2656 cgroup_kn_unlock(of->kn);
2658 finish_wait(&child->offline_waitq, &wait);
2661 return restart_syscall();
2664 /* unavailable or not enabled on the parent? */
2665 if (!(cgrp_dfl_root.subsys_mask & (1 << ssid)) ||
2667 !(cgrp->parent->child_subsys_mask & (1 << ssid)))) {
2671 } else if (disable & (1 << ssid)) {
2672 if (!(cgrp->child_subsys_mask & (1 << ssid))) {
2673 disable &= ~(1 << ssid);
2677 /* a child has it enabled? */
2678 cgroup_for_each_live_child(child, cgrp) {
2679 if (child->child_subsys_mask & (1 << ssid)) {
2687 if (!enable && !disable) {
2693 * Except for the root, child_subsys_mask must be zero for a cgroup
2694 * with tasks so that child cgroups don't compete against tasks.
2696 if (enable && cgrp->parent && !list_empty(&cgrp->cset_links)) {
2702 * Create csses for enables and update child_subsys_mask. This
2703 * changes cgroup_e_css() results which in turn makes the
2704 * subsequent cgroup_update_dfl_csses() associate all tasks in the
2705 * subtree to the updated csses.
2707 for_each_subsys(ss, ssid) {
2708 if (!(enable & (1 << ssid)))
2711 cgroup_for_each_live_child(child, cgrp) {
2712 ret = create_css(child, ss);
2718 cgrp->child_subsys_mask |= enable;
2719 cgrp->child_subsys_mask &= ~disable;
2721 ret = cgroup_update_dfl_csses(cgrp);
2725 /* all tasks are now migrated away from the old csses, kill them */
2726 for_each_subsys(ss, ssid) {
2727 if (!(disable & (1 << ssid)))
2730 cgroup_for_each_live_child(child, cgrp)
2731 kill_css(cgroup_css(child, ss));
2734 kernfs_activate(cgrp->kn);
2737 cgroup_kn_unlock(of->kn);
2738 return ret ?: nbytes;
2741 cgrp->child_subsys_mask &= ~enable;
2742 cgrp->child_subsys_mask |= disable;
2744 for_each_subsys(ss, ssid) {
2745 if (!(enable & (1 << ssid)))
2748 cgroup_for_each_live_child(child, cgrp) {
2749 struct cgroup_subsys_state *css = cgroup_css(child, ss);
2757 static int cgroup_populated_show(struct seq_file *seq, void *v)
2759 seq_printf(seq, "%d\n", (bool)seq_css(seq)->cgroup->populated_cnt);
2763 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
2764 size_t nbytes, loff_t off)
2766 struct cgroup *cgrp = of->kn->parent->priv;
2767 struct cftype *cft = of->kn->priv;
2768 struct cgroup_subsys_state *css;
2772 return cft->write(of, buf, nbytes, off);
2775 * kernfs guarantees that a file isn't deleted with operations in
2776 * flight, which means that the matching css is and stays alive and
2777 * doesn't need to be pinned. The RCU locking is not necessary
2778 * either. It's just for the convenience of using cgroup_css().
2781 css = cgroup_css(cgrp, cft->ss);
2784 if (cft->write_u64) {
2785 unsigned long long v;
2786 ret = kstrtoull(buf, 0, &v);
2788 ret = cft->write_u64(css, cft, v);
2789 } else if (cft->write_s64) {
2791 ret = kstrtoll(buf, 0, &v);
2793 ret = cft->write_s64(css, cft, v);
2798 return ret ?: nbytes;
2801 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
2803 return seq_cft(seq)->seq_start(seq, ppos);
2806 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
2808 return seq_cft(seq)->seq_next(seq, v, ppos);
2811 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
2813 seq_cft(seq)->seq_stop(seq, v);
2816 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2818 struct cftype *cft = seq_cft(m);
2819 struct cgroup_subsys_state *css = seq_css(m);
2822 return cft->seq_show(m, arg);
2825 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
2826 else if (cft->read_s64)
2827 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
2833 static struct kernfs_ops cgroup_kf_single_ops = {
2834 .atomic_write_len = PAGE_SIZE,
2835 .write = cgroup_file_write,
2836 .seq_show = cgroup_seqfile_show,
2839 static struct kernfs_ops cgroup_kf_ops = {
2840 .atomic_write_len = PAGE_SIZE,
2841 .write = cgroup_file_write,
2842 .seq_start = cgroup_seqfile_start,
2843 .seq_next = cgroup_seqfile_next,
2844 .seq_stop = cgroup_seqfile_stop,
2845 .seq_show = cgroup_seqfile_show,
2849 * cgroup_rename - Only allow simple rename of directories in place.
2851 static int cgroup_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
2852 const char *new_name_str)
2854 struct cgroup *cgrp = kn->priv;
2857 if (kernfs_type(kn) != KERNFS_DIR)
2859 if (kn->parent != new_parent)
2863 * This isn't a proper migration and its usefulness is very
2864 * limited. Disallow if sane_behavior.
2866 if (cgroup_sane_behavior(cgrp))
2870 * We're gonna grab cgroup_tree_mutex which nests outside kernfs
2871 * active_ref. kernfs_rename() doesn't require active_ref
2872 * protection. Break them before grabbing cgroup_tree_mutex.
2874 kernfs_break_active_protection(new_parent);
2875 kernfs_break_active_protection(kn);
2877 mutex_lock(&cgroup_tree_mutex);
2878 mutex_lock(&cgroup_mutex);
2880 ret = kernfs_rename(kn, new_parent, new_name_str);
2882 mutex_unlock(&cgroup_mutex);
2883 mutex_unlock(&cgroup_tree_mutex);
2885 kernfs_unbreak_active_protection(kn);
2886 kernfs_unbreak_active_protection(new_parent);
2890 /* set uid and gid of cgroup dirs and files to that of the creator */
2891 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
2893 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
2894 .ia_uid = current_fsuid(),
2895 .ia_gid = current_fsgid(), };
2897 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
2898 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
2901 return kernfs_setattr(kn, &iattr);
2904 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2906 char name[CGROUP_FILE_NAME_MAX];
2907 struct kernfs_node *kn;
2908 struct lock_class_key *key = NULL;
2911 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2912 key = &cft->lockdep_key;
2914 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
2915 cgroup_file_mode(cft), 0, cft->kf_ops, cft,
2920 ret = cgroup_kn_set_ugid(kn);
2926 if (cft->seq_show == cgroup_populated_show)
2927 cgrp->populated_kn = kn;
2932 * cgroup_addrm_files - add or remove files to a cgroup directory
2933 * @cgrp: the target cgroup
2934 * @cfts: array of cftypes to be added
2935 * @is_add: whether to add or remove
2937 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2938 * For removals, this function never fails. If addition fails, this
2939 * function doesn't remove files already added. The caller is responsible
2942 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2948 lockdep_assert_held(&cgroup_tree_mutex);
2950 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2951 /* does cft->flags tell us to skip this file on @cgrp? */
2952 if ((cft->flags & CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
2954 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2956 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2958 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2962 ret = cgroup_add_file(cgrp, cft);
2964 pr_warn("%s: failed to add %s, err=%d\n",
2965 __func__, cft->name, ret);
2969 cgroup_rm_file(cgrp, cft);
2975 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
2978 struct cgroup_subsys *ss = cfts[0].ss;
2979 struct cgroup *root = &ss->root->cgrp;
2980 struct cgroup_subsys_state *css;
2983 lockdep_assert_held(&cgroup_tree_mutex);
2985 /* add/rm files for all cgroups created before */
2986 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2987 struct cgroup *cgrp = css->cgroup;
2989 if (cgroup_is_dead(cgrp))
2992 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2998 kernfs_activate(root->kn);
3002 static void cgroup_exit_cftypes(struct cftype *cfts)
3006 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3007 /* free copy for custom atomic_write_len, see init_cftypes() */
3008 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
3015 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3019 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3020 struct kernfs_ops *kf_ops;
3022 WARN_ON(cft->ss || cft->kf_ops);
3025 kf_ops = &cgroup_kf_ops;
3027 kf_ops = &cgroup_kf_single_ops;
3030 * Ugh... if @cft wants a custom max_write_len, we need to
3031 * make a copy of kf_ops to set its atomic_write_len.
3033 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
3034 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
3036 cgroup_exit_cftypes(cfts);
3039 kf_ops->atomic_write_len = cft->max_write_len;
3042 cft->kf_ops = kf_ops;
3049 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
3051 lockdep_assert_held(&cgroup_tree_mutex);
3053 if (!cfts || !cfts[0].ss)
3056 list_del(&cfts->node);
3057 cgroup_apply_cftypes(cfts, false);
3058 cgroup_exit_cftypes(cfts);
3063 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
3064 * @cfts: zero-length name terminated array of cftypes
3066 * Unregister @cfts. Files described by @cfts are removed from all
3067 * existing cgroups and all future cgroups won't have them either. This
3068 * function can be called anytime whether @cfts' subsys is attached or not.
3070 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
3073 int cgroup_rm_cftypes(struct cftype *cfts)
3077 mutex_lock(&cgroup_tree_mutex);
3078 ret = cgroup_rm_cftypes_locked(cfts);
3079 mutex_unlock(&cgroup_tree_mutex);
3084 * cgroup_add_cftypes - add an array of cftypes to a subsystem
3085 * @ss: target cgroup subsystem
3086 * @cfts: zero-length name terminated array of cftypes
3088 * Register @cfts to @ss. Files described by @cfts are created for all
3089 * existing cgroups to which @ss is attached and all future cgroups will
3090 * have them too. This function can be called anytime whether @ss is
3093 * Returns 0 on successful registration, -errno on failure. Note that this
3094 * function currently returns 0 as long as @cfts registration is successful
3095 * even if some file creation attempts on existing cgroups fail.
3097 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3101 if (!cfts || cfts[0].name[0] == '\0')
3104 ret = cgroup_init_cftypes(ss, cfts);
3108 mutex_lock(&cgroup_tree_mutex);
3110 list_add_tail(&cfts->node, &ss->cfts);
3111 ret = cgroup_apply_cftypes(cfts, true);
3113 cgroup_rm_cftypes_locked(cfts);
3115 mutex_unlock(&cgroup_tree_mutex);
3120 * cgroup_task_count - count the number of tasks in a cgroup.
3121 * @cgrp: the cgroup in question
3123 * Return the number of tasks in the cgroup.
3125 static int cgroup_task_count(const struct cgroup *cgrp)
3128 struct cgrp_cset_link *link;
3130 down_read(&css_set_rwsem);
3131 list_for_each_entry(link, &cgrp->cset_links, cset_link)
3132 count += atomic_read(&link->cset->refcount);
3133 up_read(&css_set_rwsem);
3138 * css_next_child - find the next child of a given css
3139 * @pos_css: the current position (%NULL to initiate traversal)
3140 * @parent_css: css whose children to walk
3142 * This function returns the next child of @parent_css and should be called
3143 * under either cgroup_mutex or RCU read lock. The only requirement is
3144 * that @parent_css and @pos_css are accessible. The next sibling is
3145 * guaranteed to be returned regardless of their states.
3147 struct cgroup_subsys_state *
3148 css_next_child(struct cgroup_subsys_state *pos_css,
3149 struct cgroup_subsys_state *parent_css)
3151 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
3152 struct cgroup *cgrp = parent_css->cgroup;
3153 struct cgroup *next;
3155 cgroup_assert_mutexes_or_rcu_locked();
3158 * @pos could already have been removed. Once a cgroup is removed,
3159 * its ->sibling.next is no longer updated when its next sibling
3160 * changes. As CGRP_DEAD assertion is serialized and happens
3161 * before the cgroup is taken off the ->sibling list, if we see it
3162 * unasserted, it's guaranteed that the next sibling hasn't
3163 * finished its grace period even if it's already removed, and thus
3164 * safe to dereference from this RCU critical section. If
3165 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
3166 * to be visible as %true here.
3168 * If @pos is dead, its next pointer can't be dereferenced;
3169 * however, as each cgroup is given a monotonically increasing
3170 * unique serial number and always appended to the sibling list,
3171 * the next one can be found by walking the parent's children until
3172 * we see a cgroup with higher serial number than @pos's. While
3173 * this path can be slower, it's taken only when either the current
3174 * cgroup is removed or iteration and removal race.
3177 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
3178 } else if (likely(!cgroup_is_dead(pos))) {
3179 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3181 list_for_each_entry_rcu(next, &cgrp->children, sibling)
3182 if (next->serial_nr > pos->serial_nr)
3187 * @next, if not pointing to the head, can be dereferenced and is
3188 * the next sibling; however, it might have @ss disabled. If so,
3189 * fast-forward to the next enabled one.
3191 while (&next->sibling != &cgrp->children) {
3192 struct cgroup_subsys_state *next_css = cgroup_css(next, parent_css->ss);
3196 next = list_entry_rcu(next->sibling.next, struct cgroup, sibling);
3202 * css_next_descendant_pre - find the next descendant for pre-order walk
3203 * @pos: the current position (%NULL to initiate traversal)
3204 * @root: css whose descendants to walk
3206 * To be used by css_for_each_descendant_pre(). Find the next descendant
3207 * to visit for pre-order traversal of @root's descendants. @root is
3208 * included in the iteration and the first node to be visited.
3210 * While this function requires cgroup_mutex or RCU read locking, it
3211 * doesn't require the whole traversal to be contained in a single critical
3212 * section. This function will return the correct next descendant as long
3213 * as both @pos and @root are accessible and @pos is a descendant of @root.
3215 struct cgroup_subsys_state *
3216 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3217 struct cgroup_subsys_state *root)
3219 struct cgroup_subsys_state *next;
3221 cgroup_assert_mutexes_or_rcu_locked();
3223 /* if first iteration, visit @root */
3227 /* visit the first child if exists */
3228 next = css_next_child(NULL, pos);
3232 /* no child, visit my or the closest ancestor's next sibling */
3233 while (pos != root) {
3234 next = css_next_child(pos, css_parent(pos));
3237 pos = css_parent(pos);
3244 * css_rightmost_descendant - return the rightmost descendant of a css
3245 * @pos: css of interest
3247 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3248 * is returned. This can be used during pre-order traversal to skip
3251 * While this function requires cgroup_mutex or RCU read locking, it
3252 * doesn't require the whole traversal to be contained in a single critical
3253 * section. This function will return the correct rightmost descendant as
3254 * long as @pos is accessible.
3256 struct cgroup_subsys_state *
3257 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3259 struct cgroup_subsys_state *last, *tmp;
3261 cgroup_assert_mutexes_or_rcu_locked();
3265 /* ->prev isn't RCU safe, walk ->next till the end */
3267 css_for_each_child(tmp, last)
3274 static struct cgroup_subsys_state *
3275 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3277 struct cgroup_subsys_state *last;
3281 pos = css_next_child(NULL, pos);
3288 * css_next_descendant_post - find the next descendant for post-order walk
3289 * @pos: the current position (%NULL to initiate traversal)
3290 * @root: css whose descendants to walk
3292 * To be used by css_for_each_descendant_post(). Find the next descendant
3293 * to visit for post-order traversal of @root's descendants. @root is
3294 * included in the iteration and the last node to be visited.
3296 * While this function requires cgroup_mutex or RCU read locking, it
3297 * doesn't require the whole traversal to be contained in a single critical
3298 * section. This function will return the correct next descendant as long
3299 * as both @pos and @cgroup are accessible and @pos is a descendant of
3302 struct cgroup_subsys_state *
3303 css_next_descendant_post(struct cgroup_subsys_state *pos,
3304 struct cgroup_subsys_state *root)
3306 struct cgroup_subsys_state *next;
3308 cgroup_assert_mutexes_or_rcu_locked();
3310 /* if first iteration, visit leftmost descendant which may be @root */
3312 return css_leftmost_descendant(root);
3314 /* if we visited @root, we're done */
3318 /* if there's an unvisited sibling, visit its leftmost descendant */
3319 next = css_next_child(pos, css_parent(pos));
3321 return css_leftmost_descendant(next);
3323 /* no sibling left, visit parent */
3324 return css_parent(pos);
3328 * css_advance_task_iter - advance a task itererator to the next css_set
3329 * @it: the iterator to advance
3331 * Advance @it to the next css_set to walk.
3333 static void css_advance_task_iter(struct css_task_iter *it)
3335 struct list_head *l = it->cset_pos;
3336 struct cgrp_cset_link *link;
3337 struct css_set *cset;
3339 /* Advance to the next non-empty css_set */
3342 if (l == it->cset_head) {
3343 it->cset_pos = NULL;
3348 cset = container_of(l, struct css_set,
3349 e_cset_node[it->ss->id]);
3351 link = list_entry(l, struct cgrp_cset_link, cset_link);
3354 } while (list_empty(&cset->tasks) && list_empty(&cset->mg_tasks));
3358 if (!list_empty(&cset->tasks))
3359 it->task_pos = cset->tasks.next;
3361 it->task_pos = cset->mg_tasks.next;
3363 it->tasks_head = &cset->tasks;
3364 it->mg_tasks_head = &cset->mg_tasks;
3368 * css_task_iter_start - initiate task iteration
3369 * @css: the css to walk tasks of
3370 * @it: the task iterator to use
3372 * Initiate iteration through the tasks of @css. The caller can call
3373 * css_task_iter_next() to walk through the tasks until the function
3374 * returns NULL. On completion of iteration, css_task_iter_end() must be
3377 * Note that this function acquires a lock which is released when the
3378 * iteration finishes. The caller can't sleep while iteration is in
3381 void css_task_iter_start(struct cgroup_subsys_state *css,
3382 struct css_task_iter *it)
3383 __acquires(css_set_rwsem)
3385 /* no one should try to iterate before mounting cgroups */
3386 WARN_ON_ONCE(!use_task_css_set_links);
3388 down_read(&css_set_rwsem);
3393 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
3395 it->cset_pos = &css->cgroup->cset_links;
3397 it->cset_head = it->cset_pos;
3399 css_advance_task_iter(it);
3403 * css_task_iter_next - return the next task for the iterator
3404 * @it: the task iterator being iterated
3406 * The "next" function for task iteration. @it should have been
3407 * initialized via css_task_iter_start(). Returns NULL when the iteration
3410 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3412 struct task_struct *res;
3413 struct list_head *l = it->task_pos;
3415 /* If the iterator cg is NULL, we have no tasks */
3418 res = list_entry(l, struct task_struct, cg_list);
3421 * Advance iterator to find next entry. cset->tasks is consumed
3422 * first and then ->mg_tasks. After ->mg_tasks, we move onto the
3427 if (l == it->tasks_head)
3428 l = it->mg_tasks_head->next;
3430 if (l == it->mg_tasks_head)
3431 css_advance_task_iter(it);
3439 * css_task_iter_end - finish task iteration
3440 * @it: the task iterator to finish
3442 * Finish task iteration started by css_task_iter_start().
3444 void css_task_iter_end(struct css_task_iter *it)
3445 __releases(css_set_rwsem)
3447 up_read(&css_set_rwsem);
3451 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3452 * @to: cgroup to which the tasks will be moved
3453 * @from: cgroup in which the tasks currently reside
3455 * Locking rules between cgroup_post_fork() and the migration path
3456 * guarantee that, if a task is forking while being migrated, the new child
3457 * is guaranteed to be either visible in the source cgroup after the
3458 * parent's migration is complete or put into the target cgroup. No task
3459 * can slip out of migration through forking.
3461 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3463 LIST_HEAD(preloaded_csets);
3464 struct cgrp_cset_link *link;
3465 struct css_task_iter it;
3466 struct task_struct *task;
3469 mutex_lock(&cgroup_mutex);
3471 /* all tasks in @from are being moved, all csets are source */
3472 down_read(&css_set_rwsem);
3473 list_for_each_entry(link, &from->cset_links, cset_link)
3474 cgroup_migrate_add_src(link->cset, to, &preloaded_csets);
3475 up_read(&css_set_rwsem);
3477 ret = cgroup_migrate_prepare_dst(to, &preloaded_csets);
3482 * Migrate tasks one-by-one until @form is empty. This fails iff
3483 * ->can_attach() fails.
3486 css_task_iter_start(&from->dummy_css, &it);
3487 task = css_task_iter_next(&it);
3489 get_task_struct(task);
3490 css_task_iter_end(&it);
3493 ret = cgroup_migrate(to, task, false);
3494 put_task_struct(task);
3496 } while (task && !ret);
3498 cgroup_migrate_finish(&preloaded_csets);
3499 mutex_unlock(&cgroup_mutex);
3504 * Stuff for reading the 'tasks'/'procs' files.
3506 * Reading this file can return large amounts of data if a cgroup has
3507 * *lots* of attached tasks. So it may need several calls to read(),
3508 * but we cannot guarantee that the information we produce is correct
3509 * unless we produce it entirely atomically.
3513 /* which pidlist file are we talking about? */
3514 enum cgroup_filetype {
3520 * A pidlist is a list of pids that virtually represents the contents of one
3521 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3522 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3525 struct cgroup_pidlist {
3527 * used to find which pidlist is wanted. doesn't change as long as
3528 * this particular list stays in the list.
3530 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3533 /* how many elements the above list has */
3535 /* each of these stored in a list by its cgroup */
3536 struct list_head links;
3537 /* pointer to the cgroup we belong to, for list removal purposes */
3538 struct cgroup *owner;
3539 /* for delayed destruction */
3540 struct delayed_work destroy_dwork;
3544 * The following two functions "fix" the issue where there are more pids
3545 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3546 * TODO: replace with a kernel-wide solution to this problem
3548 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3549 static void *pidlist_allocate(int count)
3551 if (PIDLIST_TOO_LARGE(count))
3552 return vmalloc(count * sizeof(pid_t));
3554 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3557 static void pidlist_free(void *p)
3559 if (is_vmalloc_addr(p))
3566 * Used to destroy all pidlists lingering waiting for destroy timer. None
3567 * should be left afterwards.
3569 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
3571 struct cgroup_pidlist *l, *tmp_l;
3573 mutex_lock(&cgrp->pidlist_mutex);
3574 list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
3575 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
3576 mutex_unlock(&cgrp->pidlist_mutex);
3578 flush_workqueue(cgroup_pidlist_destroy_wq);
3579 BUG_ON(!list_empty(&cgrp->pidlists));
3582 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
3584 struct delayed_work *dwork = to_delayed_work(work);
3585 struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
3587 struct cgroup_pidlist *tofree = NULL;
3589 mutex_lock(&l->owner->pidlist_mutex);
3592 * Destroy iff we didn't get queued again. The state won't change
3593 * as destroy_dwork can only be queued while locked.
3595 if (!delayed_work_pending(dwork)) {
3596 list_del(&l->links);
3597 pidlist_free(l->list);
3598 put_pid_ns(l->key.ns);
3602 mutex_unlock(&l->owner->pidlist_mutex);
3607 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3608 * Returns the number of unique elements.
3610 static int pidlist_uniq(pid_t *list, int length)
3615 * we presume the 0th element is unique, so i starts at 1. trivial
3616 * edge cases first; no work needs to be done for either
3618 if (length == 0 || length == 1)
3620 /* src and dest walk down the list; dest counts unique elements */
3621 for (src = 1; src < length; src++) {
3622 /* find next unique element */
3623 while (list[src] == list[src-1]) {
3628 /* dest always points to where the next unique element goes */
3629 list[dest] = list[src];
3637 * The two pid files - task and cgroup.procs - guaranteed that the result
3638 * is sorted, which forced this whole pidlist fiasco. As pid order is
3639 * different per namespace, each namespace needs differently sorted list,
3640 * making it impossible to use, for example, single rbtree of member tasks
3641 * sorted by task pointer. As pidlists can be fairly large, allocating one
3642 * per open file is dangerous, so cgroup had to implement shared pool of
3643 * pidlists keyed by cgroup and namespace.
3645 * All this extra complexity was caused by the original implementation
3646 * committing to an entirely unnecessary property. In the long term, we
3647 * want to do away with it. Explicitly scramble sort order if
3648 * sane_behavior so that no such expectation exists in the new interface.
3650 * Scrambling is done by swapping every two consecutive bits, which is
3651 * non-identity one-to-one mapping which disturbs sort order sufficiently.
3653 static pid_t pid_fry(pid_t pid)
3655 unsigned a = pid & 0x55555555;
3656 unsigned b = pid & 0xAAAAAAAA;
3658 return (a << 1) | (b >> 1);
3661 static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
3663 if (cgroup_sane_behavior(cgrp))
3664 return pid_fry(pid);
3669 static int cmppid(const void *a, const void *b)
3671 return *(pid_t *)a - *(pid_t *)b;
3674 static int fried_cmppid(const void *a, const void *b)
3676 return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
3679 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3680 enum cgroup_filetype type)
3682 struct cgroup_pidlist *l;
3683 /* don't need task_nsproxy() if we're looking at ourself */
3684 struct pid_namespace *ns = task_active_pid_ns(current);
3686 lockdep_assert_held(&cgrp->pidlist_mutex);
3688 list_for_each_entry(l, &cgrp->pidlists, links)
3689 if (l->key.type == type && l->key.ns == ns)
3695 * find the appropriate pidlist for our purpose (given procs vs tasks)
3696 * returns with the lock on that pidlist already held, and takes care
3697 * of the use count, or returns NULL with no locks held if we're out of
3700 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
3701 enum cgroup_filetype type)
3703 struct cgroup_pidlist *l;
3705 lockdep_assert_held(&cgrp->pidlist_mutex);
3707 l = cgroup_pidlist_find(cgrp, type);
3711 /* entry not found; create a new one */
3712 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3716 INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
3718 /* don't need task_nsproxy() if we're looking at ourself */
3719 l->key.ns = get_pid_ns(task_active_pid_ns(current));
3721 list_add(&l->links, &cgrp->pidlists);
3726 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3728 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3729 struct cgroup_pidlist **lp)
3733 int pid, n = 0; /* used for populating the array */
3734 struct css_task_iter it;
3735 struct task_struct *tsk;
3736 struct cgroup_pidlist *l;
3738 lockdep_assert_held(&cgrp->pidlist_mutex);
3741 * If cgroup gets more users after we read count, we won't have
3742 * enough space - tough. This race is indistinguishable to the
3743 * caller from the case that the additional cgroup users didn't
3744 * show up until sometime later on.
3746 length = cgroup_task_count(cgrp);
3747 array = pidlist_allocate(length);
3750 /* now, populate the array */
3751 css_task_iter_start(&cgrp->dummy_css, &it);
3752 while ((tsk = css_task_iter_next(&it))) {
3753 if (unlikely(n == length))
3755 /* get tgid or pid for procs or tasks file respectively */
3756 if (type == CGROUP_FILE_PROCS)
3757 pid = task_tgid_vnr(tsk);
3759 pid = task_pid_vnr(tsk);
3760 if (pid > 0) /* make sure to only use valid results */
3763 css_task_iter_end(&it);
3765 /* now sort & (if procs) strip out duplicates */
3766 if (cgroup_sane_behavior(cgrp))
3767 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
3769 sort(array, length, sizeof(pid_t), cmppid, NULL);
3770 if (type == CGROUP_FILE_PROCS)
3771 length = pidlist_uniq(array, length);
3773 l = cgroup_pidlist_find_create(cgrp, type);
3775 mutex_unlock(&cgrp->pidlist_mutex);
3776 pidlist_free(array);
3780 /* store array, freeing old if necessary */
3781 pidlist_free(l->list);
3789 * cgroupstats_build - build and fill cgroupstats
3790 * @stats: cgroupstats to fill information into
3791 * @dentry: A dentry entry belonging to the cgroup for which stats have
3794 * Build and fill cgroupstats so that taskstats can export it to user
3797 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3799 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
3800 struct cgroup *cgrp;
3801 struct css_task_iter it;
3802 struct task_struct *tsk;
3804 /* it should be kernfs_node belonging to cgroupfs and is a directory */
3805 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
3806 kernfs_type(kn) != KERNFS_DIR)
3809 mutex_lock(&cgroup_mutex);
3812 * We aren't being called from kernfs and there's no guarantee on
3813 * @kn->priv's validity. For this and css_tryget_online_from_dir(),
3814 * @kn->priv is RCU safe. Let's do the RCU dancing.
3817 cgrp = rcu_dereference(kn->priv);
3818 if (!cgrp || cgroup_is_dead(cgrp)) {
3820 mutex_unlock(&cgroup_mutex);
3825 css_task_iter_start(&cgrp->dummy_css, &it);
3826 while ((tsk = css_task_iter_next(&it))) {
3827 switch (tsk->state) {
3829 stats->nr_running++;
3831 case TASK_INTERRUPTIBLE:
3832 stats->nr_sleeping++;
3834 case TASK_UNINTERRUPTIBLE:
3835 stats->nr_uninterruptible++;
3838 stats->nr_stopped++;
3841 if (delayacct_is_task_waiting_on_io(tsk))
3842 stats->nr_io_wait++;
3846 css_task_iter_end(&it);
3848 mutex_unlock(&cgroup_mutex);
3854 * seq_file methods for the tasks/procs files. The seq_file position is the
3855 * next pid to display; the seq_file iterator is a pointer to the pid
3856 * in the cgroup->l->list array.
3859 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3862 * Initially we receive a position value that corresponds to
3863 * one more than the last pid shown (or 0 on the first call or
3864 * after a seek to the start). Use a binary-search to find the
3865 * next pid to display, if any
3867 struct kernfs_open_file *of = s->private;
3868 struct cgroup *cgrp = seq_css(s)->cgroup;
3869 struct cgroup_pidlist *l;
3870 enum cgroup_filetype type = seq_cft(s)->private;
3871 int index = 0, pid = *pos;
3874 mutex_lock(&cgrp->pidlist_mutex);
3877 * !NULL @of->priv indicates that this isn't the first start()
3878 * after open. If the matching pidlist is around, we can use that.
3879 * Look for it. Note that @of->priv can't be used directly. It
3880 * could already have been destroyed.
3883 of->priv = cgroup_pidlist_find(cgrp, type);
3886 * Either this is the first start() after open or the matching
3887 * pidlist has been destroyed inbetween. Create a new one.
3890 ret = pidlist_array_load(cgrp, type,
3891 (struct cgroup_pidlist **)&of->priv);
3893 return ERR_PTR(ret);
3898 int end = l->length;
3900 while (index < end) {
3901 int mid = (index + end) / 2;
3902 if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
3905 } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
3911 /* If we're off the end of the array, we're done */
3912 if (index >= l->length)
3914 /* Update the abstract position to be the actual pid that we found */
3915 iter = l->list + index;
3916 *pos = cgroup_pid_fry(cgrp, *iter);
3920 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3922 struct kernfs_open_file *of = s->private;
3923 struct cgroup_pidlist *l = of->priv;
3926 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
3927 CGROUP_PIDLIST_DESTROY_DELAY);
3928 mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
3931 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3933 struct kernfs_open_file *of = s->private;
3934 struct cgroup_pidlist *l = of->priv;
3936 pid_t *end = l->list + l->length;
3938 * Advance to the next pid in the array. If this goes off the
3945 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
3950 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3952 return seq_printf(s, "%d\n", *(int *)v);
3955 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3958 return notify_on_release(css->cgroup);
3961 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3962 struct cftype *cft, u64 val)
3964 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3966 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3968 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3972 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3975 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3978 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3979 struct cftype *cft, u64 val)
3982 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3984 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3988 static struct cftype cgroup_base_files[] = {
3990 .name = "cgroup.procs",
3991 .seq_start = cgroup_pidlist_start,
3992 .seq_next = cgroup_pidlist_next,
3993 .seq_stop = cgroup_pidlist_stop,
3994 .seq_show = cgroup_pidlist_show,
3995 .private = CGROUP_FILE_PROCS,
3996 .write = cgroup_procs_write,
3997 .mode = S_IRUGO | S_IWUSR,
4000 .name = "cgroup.clone_children",
4001 .flags = CFTYPE_INSANE,
4002 .read_u64 = cgroup_clone_children_read,
4003 .write_u64 = cgroup_clone_children_write,
4006 .name = "cgroup.sane_behavior",
4007 .flags = CFTYPE_ONLY_ON_ROOT,
4008 .seq_show = cgroup_sane_behavior_show,
4011 .name = "cgroup.controllers",
4012 .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_ONLY_ON_ROOT,
4013 .seq_show = cgroup_root_controllers_show,
4016 .name = "cgroup.controllers",
4017 .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_NOT_ON_ROOT,
4018 .seq_show = cgroup_controllers_show,
4021 .name = "cgroup.subtree_control",
4022 .flags = CFTYPE_ONLY_ON_DFL,
4023 .seq_show = cgroup_subtree_control_show,
4024 .write = cgroup_subtree_control_write,
4027 .name = "cgroup.populated",
4028 .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_NOT_ON_ROOT,
4029 .seq_show = cgroup_populated_show,
4033 * Historical crazy stuff. These don't have "cgroup." prefix and
4034 * don't exist if sane_behavior. If you're depending on these, be
4035 * prepared to be burned.
4039 .flags = CFTYPE_INSANE, /* use "procs" instead */
4040 .seq_start = cgroup_pidlist_start,
4041 .seq_next = cgroup_pidlist_next,
4042 .seq_stop = cgroup_pidlist_stop,
4043 .seq_show = cgroup_pidlist_show,
4044 .private = CGROUP_FILE_TASKS,
4045 .write = cgroup_tasks_write,
4046 .mode = S_IRUGO | S_IWUSR,
4049 .name = "notify_on_release",
4050 .flags = CFTYPE_INSANE,
4051 .read_u64 = cgroup_read_notify_on_release,
4052 .write_u64 = cgroup_write_notify_on_release,
4055 .name = "release_agent",
4056 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
4057 .seq_show = cgroup_release_agent_show,
4058 .write = cgroup_release_agent_write,
4059 .max_write_len = PATH_MAX - 1,
4065 * cgroup_populate_dir - create subsys files in a cgroup directory
4066 * @cgrp: target cgroup
4067 * @subsys_mask: mask of the subsystem ids whose files should be added
4069 * On failure, no file is added.
4071 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned int subsys_mask)
4073 struct cgroup_subsys *ss;
4076 /* process cftsets of each subsystem */
4077 for_each_subsys(ss, i) {
4078 struct cftype *cfts;
4080 if (!(subsys_mask & (1 << i)))
4083 list_for_each_entry(cfts, &ss->cfts, node) {
4084 ret = cgroup_addrm_files(cgrp, cfts, true);
4091 cgroup_clear_dir(cgrp, subsys_mask);
4096 * css destruction is four-stage process.
4098 * 1. Destruction starts. Killing of the percpu_ref is initiated.
4099 * Implemented in kill_css().
4101 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4102 * and thus css_tryget_online() is guaranteed to fail, the css can be
4103 * offlined by invoking offline_css(). After offlining, the base ref is
4104 * put. Implemented in css_killed_work_fn().
4106 * 3. When the percpu_ref reaches zero, the only possible remaining
4107 * accessors are inside RCU read sections. css_release() schedules the
4110 * 4. After the grace period, the css can be freed. Implemented in
4111 * css_free_work_fn().
4113 * It is actually hairier because both step 2 and 4 require process context
4114 * and thus involve punting to css->destroy_work adding two additional
4115 * steps to the already complex sequence.
4117 static void css_free_work_fn(struct work_struct *work)
4119 struct cgroup_subsys_state *css =
4120 container_of(work, struct cgroup_subsys_state, destroy_work);
4121 struct cgroup *cgrp = css->cgroup;
4124 css_put(css->parent);
4126 css->ss->css_free(css);
4130 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4132 struct cgroup_subsys_state *css =
4133 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4135 INIT_WORK(&css->destroy_work, css_free_work_fn);
4136 queue_work(cgroup_destroy_wq, &css->destroy_work);
4139 static void css_release(struct percpu_ref *ref)
4141 struct cgroup_subsys_state *css =
4142 container_of(ref, struct cgroup_subsys_state, refcnt);
4143 struct cgroup_subsys *ss = css->ss;
4145 cgroup_idr_remove(&ss->css_idr, css->id);
4147 call_rcu(&css->rcu_head, css_free_rcu_fn);
4150 static void init_and_link_css(struct cgroup_subsys_state *css,
4151 struct cgroup_subsys *ss, struct cgroup *cgrp)
4160 css->parent = cgroup_css(cgrp->parent, ss);
4161 css_get(css->parent);
4163 css->flags |= CSS_ROOT;
4166 BUG_ON(cgroup_css(cgrp, ss));
4169 /* invoke ->css_online() on a new CSS and mark it online if successful */
4170 static int online_css(struct cgroup_subsys_state *css)
4172 struct cgroup_subsys *ss = css->ss;
4175 lockdep_assert_held(&cgroup_tree_mutex);
4176 lockdep_assert_held(&cgroup_mutex);
4179 ret = ss->css_online(css);
4181 css->flags |= CSS_ONLINE;
4182 css->cgroup->nr_css++;
4183 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
4188 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4189 static void offline_css(struct cgroup_subsys_state *css)
4191 struct cgroup_subsys *ss = css->ss;
4193 lockdep_assert_held(&cgroup_tree_mutex);
4194 lockdep_assert_held(&cgroup_mutex);
4196 if (!(css->flags & CSS_ONLINE))
4199 if (ss->css_offline)
4200 ss->css_offline(css);
4202 css->flags &= ~CSS_ONLINE;
4203 css->cgroup->nr_css--;
4204 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
4206 wake_up_all(&css->cgroup->offline_waitq);
4210 * create_css - create a cgroup_subsys_state
4211 * @cgrp: the cgroup new css will be associated with
4212 * @ss: the subsys of new css
4214 * Create a new css associated with @cgrp - @ss pair. On success, the new
4215 * css is online and installed in @cgrp with all interface files created.
4216 * Returns 0 on success, -errno on failure.
4218 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss)
4220 struct cgroup *parent = cgrp->parent;
4221 struct cgroup_subsys_state *css;
4224 lockdep_assert_held(&cgroup_mutex);
4226 css = ss->css_alloc(cgroup_css(parent, ss));
4228 return PTR_ERR(css);
4230 init_and_link_css(css, ss, cgrp);
4232 err = percpu_ref_init(&css->refcnt, css_release);
4236 err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_NOWAIT);
4238 goto err_free_percpu_ref;
4241 err = cgroup_populate_dir(cgrp, 1 << ss->id);
4245 /* @css is ready to be brought online now, make it visible */
4246 cgroup_idr_replace(&ss->css_idr, css, css->id);
4248 err = online_css(css);
4252 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4254 pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4255 current->comm, current->pid, ss->name);
4256 if (!strcmp(ss->name, "memory"))
4257 pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
4258 ss->warned_broken_hierarchy = true;
4264 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4266 cgroup_idr_remove(&ss->css_idr, css->id);
4267 err_free_percpu_ref:
4268 percpu_ref_cancel_init(&css->refcnt);
4270 call_rcu(&css->rcu_head, css_free_rcu_fn);
4274 static int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
4277 struct cgroup *parent, *cgrp;
4278 struct cgroup_root *root;
4279 struct cgroup_subsys *ss;
4280 struct kernfs_node *kn;
4283 parent = cgroup_kn_lock_live(parent_kn);
4286 root = parent->root;
4288 /* allocate the cgroup and its ID, 0 is reserved for the root */
4289 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4296 * Temporarily set the pointer to NULL, so idr_find() won't return
4297 * a half-baked cgroup.
4299 cgrp->id = cgroup_idr_alloc(&root->cgroup_idr, NULL, 2, 0, GFP_NOWAIT);
4305 init_cgroup_housekeeping(cgrp);
4307 cgrp->parent = parent;
4308 cgrp->dummy_css.parent = &parent->dummy_css;
4311 if (notify_on_release(parent))
4312 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4314 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4315 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4317 /* create the directory */
4318 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
4326 * This extra ref will be put in cgroup_free_fn() and guarantees
4327 * that @cgrp->kn is always accessible.
4331 cgrp->serial_nr = cgroup_serial_nr_next++;
4333 /* allocation complete, commit to creation */
4334 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4335 atomic_inc(&root->nr_cgrps);
4339 * @cgrp is now fully operational. If something fails after this
4340 * point, it'll be released via the normal destruction path.
4342 cgroup_idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4344 ret = cgroup_kn_set_ugid(kn);
4348 ret = cgroup_addrm_files(cgrp, cgroup_base_files, true);
4352 /* let's create and online css's */
4353 for_each_subsys(ss, ssid) {
4354 if (parent->child_subsys_mask & (1 << ssid)) {
4355 ret = create_css(cgrp, ss);
4362 * On the default hierarchy, a child doesn't automatically inherit
4363 * child_subsys_mask from the parent. Each is configured manually.
4365 if (!cgroup_on_dfl(cgrp))
4366 cgrp->child_subsys_mask = parent->child_subsys_mask;
4368 kernfs_activate(kn);
4374 cgroup_idr_remove(&root->cgroup_idr, cgrp->id);
4378 cgroup_kn_unlock(parent_kn);
4382 cgroup_destroy_locked(cgrp);
4387 * This is called when the refcnt of a css is confirmed to be killed.
4388 * css_tryget_online() is now guaranteed to fail.
4390 static void css_killed_work_fn(struct work_struct *work)
4392 struct cgroup_subsys_state *css =
4393 container_of(work, struct cgroup_subsys_state, destroy_work);
4394 struct cgroup *cgrp = css->cgroup;
4396 mutex_lock(&cgroup_tree_mutex);
4397 mutex_lock(&cgroup_mutex);
4400 * css_tryget_online() is guaranteed to fail now. Tell subsystems
4401 * to initate destruction.
4406 * If @cgrp is marked dead, it's waiting for refs of all css's to
4407 * be disabled before proceeding to the second phase of cgroup
4408 * destruction. If we are the last one, kick it off.
4410 if (!cgrp->nr_css && cgroup_is_dead(cgrp))
4411 cgroup_destroy_css_killed(cgrp);
4413 mutex_unlock(&cgroup_mutex);
4414 mutex_unlock(&cgroup_tree_mutex);
4417 * Put the css refs from kill_css(). Each css holds an extra
4418 * reference to the cgroup's dentry and cgroup removal proceeds
4419 * regardless of css refs. On the last put of each css, whenever
4420 * that may be, the extra dentry ref is put so that dentry
4421 * destruction happens only after all css's are released.
4426 /* css kill confirmation processing requires process context, bounce */
4427 static void css_killed_ref_fn(struct percpu_ref *ref)
4429 struct cgroup_subsys_state *css =
4430 container_of(ref, struct cgroup_subsys_state, refcnt);
4432 INIT_WORK(&css->destroy_work, css_killed_work_fn);
4433 queue_work(cgroup_destroy_wq, &css->destroy_work);
4437 * kill_css - destroy a css
4438 * @css: css to destroy
4440 * This function initiates destruction of @css by removing cgroup interface
4441 * files and putting its base reference. ->css_offline() will be invoked
4442 * asynchronously once css_tryget_online() is guaranteed to fail and when
4443 * the reference count reaches zero, @css will be released.
4445 static void kill_css(struct cgroup_subsys_state *css)
4447 lockdep_assert_held(&cgroup_tree_mutex);
4450 * This must happen before css is disassociated with its cgroup.
4451 * See seq_css() for details.
4453 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4456 * Killing would put the base ref, but we need to keep it alive
4457 * until after ->css_offline().
4462 * cgroup core guarantees that, by the time ->css_offline() is
4463 * invoked, no new css reference will be given out via
4464 * css_tryget_online(). We can't simply call percpu_ref_kill() and
4465 * proceed to offlining css's because percpu_ref_kill() doesn't
4466 * guarantee that the ref is seen as killed on all CPUs on return.
4468 * Use percpu_ref_kill_and_confirm() to get notifications as each
4469 * css is confirmed to be seen as killed on all CPUs.
4471 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4475 * cgroup_destroy_locked - the first stage of cgroup destruction
4476 * @cgrp: cgroup to be destroyed
4478 * css's make use of percpu refcnts whose killing latency shouldn't be
4479 * exposed to userland and are RCU protected. Also, cgroup core needs to
4480 * guarantee that css_tryget_online() won't succeed by the time
4481 * ->css_offline() is invoked. To satisfy all the requirements,
4482 * destruction is implemented in the following two steps.
4484 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4485 * userland visible parts and start killing the percpu refcnts of
4486 * css's. Set up so that the next stage will be kicked off once all
4487 * the percpu refcnts are confirmed to be killed.
4489 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4490 * rest of destruction. Once all cgroup references are gone, the
4491 * cgroup is RCU-freed.
4493 * This function implements s1. After this step, @cgrp is gone as far as
4494 * the userland is concerned and a new cgroup with the same name may be
4495 * created. As cgroup doesn't care about the names internally, this
4496 * doesn't cause any problem.
4498 static int cgroup_destroy_locked(struct cgroup *cgrp)
4499 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4501 struct cgroup *child;
4502 struct cgroup_subsys_state *css;
4506 lockdep_assert_held(&cgroup_tree_mutex);
4507 lockdep_assert_held(&cgroup_mutex);
4510 * css_set_rwsem synchronizes access to ->cset_links and prevents
4511 * @cgrp from being removed while put_css_set() is in progress.
4513 down_read(&css_set_rwsem);
4514 empty = list_empty(&cgrp->cset_links);
4515 up_read(&css_set_rwsem);
4520 * Make sure there's no live children. We can't test ->children
4521 * emptiness as dead children linger on it while being destroyed;
4522 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
4526 list_for_each_entry_rcu(child, &cgrp->children, sibling) {
4527 empty = cgroup_is_dead(child);
4536 * Mark @cgrp dead. This prevents further task migration and child
4537 * creation by disabling cgroup_lock_live_group(). Note that
4538 * CGRP_DEAD assertion is depended upon by css_next_child() to
4539 * resume iteration after dropping RCU read lock. See
4540 * css_next_child() for details.
4542 set_bit(CGRP_DEAD, &cgrp->flags);
4545 * Initiate massacre of all css's. cgroup_destroy_css_killed()
4546 * will be invoked to perform the rest of destruction once the
4547 * percpu refs of all css's are confirmed to be killed. This
4548 * involves removing the subsystem's files, drop cgroup_mutex.
4550 mutex_unlock(&cgroup_mutex);
4551 for_each_css(css, ssid, cgrp)
4553 mutex_lock(&cgroup_mutex);
4555 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4556 raw_spin_lock(&release_list_lock);
4557 if (!list_empty(&cgrp->release_list))
4558 list_del_init(&cgrp->release_list);
4559 raw_spin_unlock(&release_list_lock);
4562 * If @cgrp has css's attached, the second stage of cgroup
4563 * destruction is kicked off from css_killed_work_fn() after the
4564 * refs of all attached css's are killed. If @cgrp doesn't have
4565 * any css, we kick it off here.
4568 cgroup_destroy_css_killed(cgrp);
4570 /* remove @cgrp directory along with the base files */
4571 mutex_unlock(&cgroup_mutex);
4572 kernfs_remove(cgrp->kn); /* @cgrp has an extra ref on its kn */
4573 mutex_lock(&cgroup_mutex);
4579 * cgroup_destroy_css_killed - the second step of cgroup destruction
4580 * @cgrp: the cgroup whose csses have just finished offlining
4582 * This function is invoked from a work item for a cgroup which is being
4583 * destroyed after all css's are offlined and performs the rest of
4584 * destruction. This is the second step of destruction described in the
4585 * comment above cgroup_destroy_locked().
4587 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
4589 struct cgroup *parent = cgrp->parent;
4591 lockdep_assert_held(&cgroup_tree_mutex);
4592 lockdep_assert_held(&cgroup_mutex);
4594 /* delete this cgroup from parent->children */
4595 list_del_rcu(&cgrp->sibling);
4599 set_bit(CGRP_RELEASABLE, &parent->flags);
4600 check_for_release(parent);
4603 static int cgroup_rmdir(struct kernfs_node *kn)
4605 struct cgroup *cgrp;
4608 cgrp = cgroup_kn_lock_live(kn);
4611 cgroup_get(cgrp); /* for @kn->priv clearing */
4613 ret = cgroup_destroy_locked(cgrp);
4615 cgroup_kn_unlock(kn);
4618 * There are two control paths which try to determine cgroup from
4619 * dentry without going through kernfs - cgroupstats_build() and
4620 * css_tryget_online_from_dir(). Those are supported by RCU
4621 * protecting clearing of cgrp->kn->priv backpointer, which should
4622 * happen after all files under it have been removed.
4625 RCU_INIT_POINTER(*(void __rcu __force **)&kn->priv, NULL);
4631 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
4632 .remount_fs = cgroup_remount,
4633 .show_options = cgroup_show_options,
4634 .mkdir = cgroup_mkdir,
4635 .rmdir = cgroup_rmdir,
4636 .rename = cgroup_rename,
4639 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
4641 struct cgroup_subsys_state *css;
4643 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4645 mutex_lock(&cgroup_tree_mutex);
4646 mutex_lock(&cgroup_mutex);
4648 idr_init(&ss->css_idr);
4649 INIT_LIST_HEAD(&ss->cfts);
4651 /* Create the root cgroup state for this subsystem */
4652 ss->root = &cgrp_dfl_root;
4653 css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
4654 /* We don't handle early failures gracefully */
4655 BUG_ON(IS_ERR(css));
4656 init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
4658 /* idr_alloc() can't be called safely during early init */
4661 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
4662 BUG_ON(css->id < 0);
4665 /* Update the init_css_set to contain a subsys
4666 * pointer to this state - since the subsystem is
4667 * newly registered, all tasks and hence the
4668 * init_css_set is in the subsystem's root cgroup. */
4669 init_css_set.subsys[ss->id] = css;
4671 need_forkexit_callback |= ss->fork || ss->exit;
4673 /* At system boot, before all subsystems have been
4674 * registered, no tasks have been forked, so we don't
4675 * need to invoke fork callbacks here. */
4676 BUG_ON(!list_empty(&init_task.tasks));
4678 BUG_ON(online_css(css));
4680 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
4682 mutex_unlock(&cgroup_mutex);
4683 mutex_unlock(&cgroup_tree_mutex);
4687 * cgroup_init_early - cgroup initialization at system boot
4689 * Initialize cgroups at system boot, and initialize any
4690 * subsystems that request early init.
4692 int __init cgroup_init_early(void)
4694 static struct cgroup_sb_opts __initdata opts =
4695 { .flags = CGRP_ROOT_SANE_BEHAVIOR };
4696 struct cgroup_subsys *ss;
4699 init_cgroup_root(&cgrp_dfl_root, &opts);
4700 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4702 for_each_subsys(ss, i) {
4703 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
4704 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
4705 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
4707 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
4708 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
4711 ss->name = cgroup_subsys_name[i];
4714 cgroup_init_subsys(ss, true);
4720 * cgroup_init - cgroup initialization
4722 * Register cgroup filesystem and /proc file, and initialize
4723 * any subsystems that didn't request early init.
4725 int __init cgroup_init(void)
4727 struct cgroup_subsys *ss;
4731 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
4733 mutex_lock(&cgroup_tree_mutex);
4734 mutex_lock(&cgroup_mutex);
4736 /* Add init_css_set to the hash table */
4737 key = css_set_hash(init_css_set.subsys);
4738 hash_add(css_set_table, &init_css_set.hlist, key);
4740 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
4742 mutex_unlock(&cgroup_mutex);
4743 mutex_unlock(&cgroup_tree_mutex);
4745 for_each_subsys(ss, ssid) {
4746 if (ss->early_init) {
4747 struct cgroup_subsys_state *css =
4748 init_css_set.subsys[ss->id];
4750 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
4752 BUG_ON(css->id < 0);
4754 cgroup_init_subsys(ss, false);
4757 list_add_tail(&init_css_set.e_cset_node[ssid],
4758 &cgrp_dfl_root.cgrp.e_csets[ssid]);
4761 * cftype registration needs kmalloc and can't be done
4762 * during early_init. Register base cftypes separately.
4764 if (ss->base_cftypes)
4765 WARN_ON(cgroup_add_cftypes(ss, ss->base_cftypes));
4768 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4772 err = register_filesystem(&cgroup_fs_type);
4774 kobject_put(cgroup_kobj);
4778 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4782 static int __init cgroup_wq_init(void)
4785 * There isn't much point in executing destruction path in
4786 * parallel. Good chunk is serialized with cgroup_mutex anyway.
4787 * Use 1 for @max_active.
4789 * We would prefer to do this in cgroup_init() above, but that
4790 * is called before init_workqueues(): so leave this until after.
4792 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
4793 BUG_ON(!cgroup_destroy_wq);
4796 * Used to destroy pidlists and separate to serve as flush domain.
4797 * Cap @max_active to 1 too.
4799 cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
4801 BUG_ON(!cgroup_pidlist_destroy_wq);
4805 core_initcall(cgroup_wq_init);
4808 * proc_cgroup_show()
4809 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4810 * - Used for /proc/<pid>/cgroup.
4813 /* TODO: Use a proper seq_file iterator */
4814 int proc_cgroup_show(struct seq_file *m, void *v)
4817 struct task_struct *tsk;
4820 struct cgroup_root *root;
4823 buf = kmalloc(PATH_MAX, GFP_KERNEL);
4829 tsk = get_pid_task(pid, PIDTYPE_PID);
4835 mutex_lock(&cgroup_mutex);
4836 down_read(&css_set_rwsem);
4838 for_each_root(root) {
4839 struct cgroup_subsys *ss;
4840 struct cgroup *cgrp;
4841 int ssid, count = 0;
4843 if (root == &cgrp_dfl_root && !cgrp_dfl_root_visible)
4846 seq_printf(m, "%d:", root->hierarchy_id);
4847 for_each_subsys(ss, ssid)
4848 if (root->subsys_mask & (1 << ssid))
4849 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4850 if (strlen(root->name))
4851 seq_printf(m, "%sname=%s", count ? "," : "",
4854 cgrp = task_cgroup_from_root(tsk, root);
4855 path = cgroup_path(cgrp, buf, PATH_MAX);
4857 retval = -ENAMETOOLONG;
4865 up_read(&css_set_rwsem);
4866 mutex_unlock(&cgroup_mutex);
4867 put_task_struct(tsk);
4874 /* Display information about each subsystem and each hierarchy */
4875 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4877 struct cgroup_subsys *ss;
4880 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4882 * ideally we don't want subsystems moving around while we do this.
4883 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4884 * subsys/hierarchy state.
4886 mutex_lock(&cgroup_mutex);
4888 for_each_subsys(ss, i)
4889 seq_printf(m, "%s\t%d\t%d\t%d\n",
4890 ss->name, ss->root->hierarchy_id,
4891 atomic_read(&ss->root->nr_cgrps), !ss->disabled);
4893 mutex_unlock(&cgroup_mutex);
4897 static int cgroupstats_open(struct inode *inode, struct file *file)
4899 return single_open(file, proc_cgroupstats_show, NULL);
4902 static const struct file_operations proc_cgroupstats_operations = {
4903 .open = cgroupstats_open,
4905 .llseek = seq_lseek,
4906 .release = single_release,
4910 * cgroup_fork - initialize cgroup related fields during copy_process()
4911 * @child: pointer to task_struct of forking parent process.
4913 * A task is associated with the init_css_set until cgroup_post_fork()
4914 * attaches it to the parent's css_set. Empty cg_list indicates that
4915 * @child isn't holding reference to its css_set.
4917 void cgroup_fork(struct task_struct *child)
4919 RCU_INIT_POINTER(child->cgroups, &init_css_set);
4920 INIT_LIST_HEAD(&child->cg_list);
4924 * cgroup_post_fork - called on a new task after adding it to the task list
4925 * @child: the task in question
4927 * Adds the task to the list running through its css_set if necessary and
4928 * call the subsystem fork() callbacks. Has to be after the task is
4929 * visible on the task list in case we race with the first call to
4930 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
4933 void cgroup_post_fork(struct task_struct *child)
4935 struct cgroup_subsys *ss;
4939 * This may race against cgroup_enable_task_cg_links(). As that
4940 * function sets use_task_css_set_links before grabbing
4941 * tasklist_lock and we just went through tasklist_lock to add
4942 * @child, it's guaranteed that either we see the set
4943 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
4944 * @child during its iteration.
4946 * If we won the race, @child is associated with %current's
4947 * css_set. Grabbing css_set_rwsem guarantees both that the
4948 * association is stable, and, on completion of the parent's
4949 * migration, @child is visible in the source of migration or
4950 * already in the destination cgroup. This guarantee is necessary
4951 * when implementing operations which need to migrate all tasks of
4952 * a cgroup to another.
4954 * Note that if we lose to cgroup_enable_task_cg_links(), @child
4955 * will remain in init_css_set. This is safe because all tasks are
4956 * in the init_css_set before cg_links is enabled and there's no
4957 * operation which transfers all tasks out of init_css_set.
4959 if (use_task_css_set_links) {
4960 struct css_set *cset;
4962 down_write(&css_set_rwsem);
4963 cset = task_css_set(current);
4964 if (list_empty(&child->cg_list)) {
4965 rcu_assign_pointer(child->cgroups, cset);
4966 list_add(&child->cg_list, &cset->tasks);
4969 up_write(&css_set_rwsem);
4973 * Call ss->fork(). This must happen after @child is linked on
4974 * css_set; otherwise, @child might change state between ->fork()
4975 * and addition to css_set.
4977 if (need_forkexit_callback) {
4978 for_each_subsys(ss, i)
4985 * cgroup_exit - detach cgroup from exiting task
4986 * @tsk: pointer to task_struct of exiting process
4988 * Description: Detach cgroup from @tsk and release it.
4990 * Note that cgroups marked notify_on_release force every task in
4991 * them to take the global cgroup_mutex mutex when exiting.
4992 * This could impact scaling on very large systems. Be reluctant to
4993 * use notify_on_release cgroups where very high task exit scaling
4994 * is required on large systems.
4996 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
4997 * call cgroup_exit() while the task is still competent to handle
4998 * notify_on_release(), then leave the task attached to the root cgroup in
4999 * each hierarchy for the remainder of its exit. No need to bother with
5000 * init_css_set refcnting. init_css_set never goes away and we can't race
5001 * with migration path - PF_EXITING is visible to migration path.
5003 void cgroup_exit(struct task_struct *tsk)
5005 struct cgroup_subsys *ss;
5006 struct css_set *cset;
5007 bool put_cset = false;
5011 * Unlink from @tsk from its css_set. As migration path can't race
5012 * with us, we can check cg_list without grabbing css_set_rwsem.
5014 if (!list_empty(&tsk->cg_list)) {
5015 down_write(&css_set_rwsem);
5016 list_del_init(&tsk->cg_list);
5017 up_write(&css_set_rwsem);
5021 /* Reassign the task to the init_css_set. */
5022 cset = task_css_set(tsk);
5023 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
5025 if (need_forkexit_callback) {
5026 /* see cgroup_post_fork() for details */
5027 for_each_subsys(ss, i) {
5029 struct cgroup_subsys_state *old_css = cset->subsys[i];
5030 struct cgroup_subsys_state *css = task_css(tsk, i);
5032 ss->exit(css, old_css, tsk);
5038 put_css_set(cset, true);
5041 static void check_for_release(struct cgroup *cgrp)
5043 if (cgroup_is_releasable(cgrp) &&
5044 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
5046 * Control Group is currently removeable. If it's not
5047 * already queued for a userspace notification, queue
5050 int need_schedule_work = 0;
5052 raw_spin_lock(&release_list_lock);
5053 if (!cgroup_is_dead(cgrp) &&
5054 list_empty(&cgrp->release_list)) {
5055 list_add(&cgrp->release_list, &release_list);
5056 need_schedule_work = 1;
5058 raw_spin_unlock(&release_list_lock);
5059 if (need_schedule_work)
5060 schedule_work(&release_agent_work);
5065 * Notify userspace when a cgroup is released, by running the
5066 * configured release agent with the name of the cgroup (path
5067 * relative to the root of cgroup file system) as the argument.
5069 * Most likely, this user command will try to rmdir this cgroup.
5071 * This races with the possibility that some other task will be
5072 * attached to this cgroup before it is removed, or that some other
5073 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5074 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5075 * unused, and this cgroup will be reprieved from its death sentence,
5076 * to continue to serve a useful existence. Next time it's released,
5077 * we will get notified again, if it still has 'notify_on_release' set.
5079 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5080 * means only wait until the task is successfully execve()'d. The
5081 * separate release agent task is forked by call_usermodehelper(),
5082 * then control in this thread returns here, without waiting for the
5083 * release agent task. We don't bother to wait because the caller of
5084 * this routine has no use for the exit status of the release agent
5085 * task, so no sense holding our caller up for that.
5087 static void cgroup_release_agent(struct work_struct *work)
5089 BUG_ON(work != &release_agent_work);
5090 mutex_lock(&cgroup_mutex);
5091 raw_spin_lock(&release_list_lock);
5092 while (!list_empty(&release_list)) {
5093 char *argv[3], *envp[3];
5095 char *pathbuf = NULL, *agentbuf = NULL, *path;
5096 struct cgroup *cgrp = list_entry(release_list.next,
5099 list_del_init(&cgrp->release_list);
5100 raw_spin_unlock(&release_list_lock);
5101 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
5104 path = cgroup_path(cgrp, pathbuf, PATH_MAX);
5107 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5112 argv[i++] = agentbuf;
5117 /* minimal command environment */
5118 envp[i++] = "HOME=/";
5119 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5122 /* Drop the lock while we invoke the usermode helper,
5123 * since the exec could involve hitting disk and hence
5124 * be a slow process */
5125 mutex_unlock(&cgroup_mutex);
5126 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5127 mutex_lock(&cgroup_mutex);
5131 raw_spin_lock(&release_list_lock);
5133 raw_spin_unlock(&release_list_lock);
5134 mutex_unlock(&cgroup_mutex);
5137 static int __init cgroup_disable(char *str)
5139 struct cgroup_subsys *ss;
5143 while ((token = strsep(&str, ",")) != NULL) {
5147 for_each_subsys(ss, i) {
5148 if (!strcmp(token, ss->name)) {
5150 printk(KERN_INFO "Disabling %s control group"
5151 " subsystem\n", ss->name);
5158 __setup("cgroup_disable=", cgroup_disable);
5161 * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
5162 * @dentry: directory dentry of interest
5163 * @ss: subsystem of interest
5165 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
5166 * to get the corresponding css and return it. If such css doesn't exist
5167 * or can't be pinned, an ERR_PTR value is returned.
5169 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
5170 struct cgroup_subsys *ss)
5172 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
5173 struct cgroup_subsys_state *css = NULL;
5174 struct cgroup *cgrp;
5176 /* is @dentry a cgroup dir? */
5177 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
5178 kernfs_type(kn) != KERNFS_DIR)
5179 return ERR_PTR(-EBADF);
5184 * This path doesn't originate from kernfs and @kn could already
5185 * have been or be removed at any point. @kn->priv is RCU
5186 * protected for this access. See cgroup_rmdir() for details.
5188 cgrp = rcu_dereference(kn->priv);
5190 css = cgroup_css(cgrp, ss);
5192 if (!css || !css_tryget_online(css))
5193 css = ERR_PTR(-ENOENT);
5200 * css_from_id - lookup css by id
5201 * @id: the cgroup id
5202 * @ss: cgroup subsys to be looked into
5204 * Returns the css if there's valid one with @id, otherwise returns NULL.
5205 * Should be called under rcu_read_lock().
5207 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5209 WARN_ON_ONCE(!rcu_read_lock_held());
5210 return idr_find(&ss->css_idr, id);
5213 #ifdef CONFIG_CGROUP_DEBUG
5214 static struct cgroup_subsys_state *
5215 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5217 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5220 return ERR_PTR(-ENOMEM);
5225 static void debug_css_free(struct cgroup_subsys_state *css)
5230 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5233 return cgroup_task_count(css->cgroup);
5236 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5239 return (u64)(unsigned long)current->cgroups;
5242 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5248 count = atomic_read(&task_css_set(current)->refcount);
5253 static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
5255 struct cgrp_cset_link *link;
5256 struct css_set *cset;
5259 name_buf = kmalloc(NAME_MAX + 1, GFP_KERNEL);
5263 down_read(&css_set_rwsem);
5265 cset = rcu_dereference(current->cgroups);
5266 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5267 struct cgroup *c = link->cgrp;
5269 cgroup_name(c, name_buf, NAME_MAX + 1);
5270 seq_printf(seq, "Root %d group %s\n",
5271 c->root->hierarchy_id, name_buf);
5274 up_read(&css_set_rwsem);
5279 #define MAX_TASKS_SHOWN_PER_CSS 25
5280 static int cgroup_css_links_read(struct seq_file *seq, void *v)
5282 struct cgroup_subsys_state *css = seq_css(seq);
5283 struct cgrp_cset_link *link;
5285 down_read(&css_set_rwsem);
5286 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5287 struct css_set *cset = link->cset;
5288 struct task_struct *task;
5291 seq_printf(seq, "css_set %p\n", cset);
5293 list_for_each_entry(task, &cset->tasks, cg_list) {
5294 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5296 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5299 list_for_each_entry(task, &cset->mg_tasks, cg_list) {
5300 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5302 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5306 seq_puts(seq, " ...\n");
5308 up_read(&css_set_rwsem);
5312 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5314 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
5317 static struct cftype debug_files[] = {
5319 .name = "taskcount",
5320 .read_u64 = debug_taskcount_read,
5324 .name = "current_css_set",
5325 .read_u64 = current_css_set_read,
5329 .name = "current_css_set_refcount",
5330 .read_u64 = current_css_set_refcount_read,
5334 .name = "current_css_set_cg_links",
5335 .seq_show = current_css_set_cg_links_read,
5339 .name = "cgroup_css_links",
5340 .seq_show = cgroup_css_links_read,
5344 .name = "releasable",
5345 .read_u64 = releasable_read,
5351 struct cgroup_subsys debug_cgrp_subsys = {
5352 .css_alloc = debug_css_alloc,
5353 .css_free = debug_css_free,
5354 .base_cftypes = debug_files,
5356 #endif /* CONFIG_CGROUP_DEBUG */