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>
38 #include <linux/magic.h>
40 #include <linux/mutex.h>
41 #include <linux/mount.h>
42 #include <linux/pagemap.h>
43 #include <linux/proc_fs.h>
44 #include <linux/rcupdate.h>
45 #include <linux/sched.h>
46 #include <linux/slab.h>
47 #include <linux/spinlock.h>
48 #include <linux/rwsem.h>
49 #include <linux/string.h>
50 #include <linux/sort.h>
51 #include <linux/kmod.h>
52 #include <linux/delayacct.h>
53 #include <linux/cgroupstats.h>
54 #include <linux/hashtable.h>
55 #include <linux/pid_namespace.h>
56 #include <linux/idr.h>
57 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
58 #include <linux/kthread.h>
59 #include <linux/delay.h>
61 #include <linux/atomic.h>
64 * pidlists linger the following amount before being destroyed. The goal
65 * is avoiding frequent destruction in the middle of consecutive read calls
66 * Expiring in the middle is a performance problem not a correctness one.
67 * 1 sec should be enough.
69 #define CGROUP_PIDLIST_DESTROY_DELAY HZ
71 #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
75 * cgroup_mutex is the master lock. Any modification to cgroup or its
76 * hierarchy must be performed while holding it.
78 * css_set_rwsem protects task->cgroups pointer, the list of css_set
79 * objects, and the chain of tasks off each css_set.
81 * These locks are exported if CONFIG_PROVE_RCU so that accessors in
82 * cgroup.h can use them for lockdep annotations.
84 #ifdef CONFIG_PROVE_RCU
85 DEFINE_MUTEX(cgroup_mutex);
86 DECLARE_RWSEM(css_set_rwsem);
87 EXPORT_SYMBOL_GPL(cgroup_mutex);
88 EXPORT_SYMBOL_GPL(css_set_rwsem);
90 static DEFINE_MUTEX(cgroup_mutex);
91 static DECLARE_RWSEM(css_set_rwsem);
95 * Protects cgroup_idr and css_idr so that IDs can be released without
96 * grabbing cgroup_mutex.
98 static DEFINE_SPINLOCK(cgroup_idr_lock);
101 * Protects cgroup_subsys->release_agent_path. Modifying it also requires
102 * cgroup_mutex. Reading requires either cgroup_mutex or this spinlock.
104 static DEFINE_SPINLOCK(release_agent_path_lock);
106 #define cgroup_assert_mutex_or_rcu_locked() \
107 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
108 !lockdep_is_held(&cgroup_mutex), \
109 "cgroup_mutex or RCU read lock required");
112 * cgroup destruction makes heavy use of work items and there can be a lot
113 * of concurrent destructions. Use a separate workqueue so that cgroup
114 * destruction work items don't end up filling up max_active of system_wq
115 * which may lead to deadlock.
117 static struct workqueue_struct *cgroup_destroy_wq;
120 * pidlist destructions need to be flushed on cgroup destruction. Use a
121 * separate workqueue as flush domain.
123 static struct workqueue_struct *cgroup_pidlist_destroy_wq;
125 /* generate an array of cgroup subsystem pointers */
126 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
127 static struct cgroup_subsys *cgroup_subsys[] = {
128 #include <linux/cgroup_subsys.h>
132 /* array of cgroup subsystem names */
133 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
134 static const char *cgroup_subsys_name[] = {
135 #include <linux/cgroup_subsys.h>
140 * The default hierarchy, reserved for the subsystems that are otherwise
141 * unattached - it never has more than a single cgroup, and all tasks are
142 * part of that cgroup.
144 struct cgroup_root cgrp_dfl_root;
145 EXPORT_SYMBOL_GPL(cgrp_dfl_root);
148 * The default hierarchy always exists but is hidden until mounted for the
149 * first time. This is for backward compatibility.
151 static bool cgrp_dfl_root_visible;
154 * Set by the boot param of the same name and makes subsystems with NULL
155 * ->dfl_files to use ->legacy_files on the default hierarchy.
157 static bool cgroup_legacy_files_on_dfl;
159 /* some controllers are not supported in the default hierarchy */
160 static unsigned long cgrp_dfl_root_inhibit_ss_mask;
162 /* The list of hierarchy roots */
164 static LIST_HEAD(cgroup_roots);
165 static int cgroup_root_count;
167 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
168 static DEFINE_IDR(cgroup_hierarchy_idr);
171 * Assign a monotonically increasing serial number to csses. It guarantees
172 * cgroups with bigger numbers are newer than those with smaller numbers.
173 * Also, as csses are always appended to the parent's ->children list, it
174 * guarantees that sibling csses are always sorted in the ascending serial
175 * number order on the list. Protected by cgroup_mutex.
177 static u64 css_serial_nr_next = 1;
180 * These bitmask flags indicate whether tasks in the fork and exit paths have
181 * fork/exit handlers to call. This avoids us having to do extra work in the
182 * fork/exit path to check which subsystems have fork/exit callbacks.
184 static unsigned long have_fork_callback __read_mostly;
185 static unsigned long have_exit_callback __read_mostly;
187 /* Ditto for the can_fork callback. */
188 static unsigned long have_canfork_callback __read_mostly;
190 static struct cftype cgroup_dfl_base_files[];
191 static struct cftype cgroup_legacy_base_files[];
193 static int rebind_subsystems(struct cgroup_root *dst_root,
194 unsigned long ss_mask);
195 static int cgroup_destroy_locked(struct cgroup *cgrp);
196 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss,
198 static void css_release(struct percpu_ref *ref);
199 static void kill_css(struct cgroup_subsys_state *css);
200 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
203 /* IDR wrappers which synchronize using cgroup_idr_lock */
204 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
209 idr_preload(gfp_mask);
210 spin_lock_bh(&cgroup_idr_lock);
211 ret = idr_alloc(idr, ptr, start, end, gfp_mask & ~__GFP_WAIT);
212 spin_unlock_bh(&cgroup_idr_lock);
217 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
221 spin_lock_bh(&cgroup_idr_lock);
222 ret = idr_replace(idr, ptr, id);
223 spin_unlock_bh(&cgroup_idr_lock);
227 static void cgroup_idr_remove(struct idr *idr, int id)
229 spin_lock_bh(&cgroup_idr_lock);
231 spin_unlock_bh(&cgroup_idr_lock);
234 static struct cgroup *cgroup_parent(struct cgroup *cgrp)
236 struct cgroup_subsys_state *parent_css = cgrp->self.parent;
239 return container_of(parent_css, struct cgroup, self);
244 * cgroup_css - obtain a cgroup's css for the specified subsystem
245 * @cgrp: the cgroup of interest
246 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
248 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
249 * function must be called either under cgroup_mutex or rcu_read_lock() and
250 * the caller is responsible for pinning the returned css if it wants to
251 * keep accessing it outside the said locks. This function may return
252 * %NULL if @cgrp doesn't have @subsys_id enabled.
254 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
255 struct cgroup_subsys *ss)
258 return rcu_dereference_check(cgrp->subsys[ss->id],
259 lockdep_is_held(&cgroup_mutex));
265 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
266 * @cgrp: the cgroup of interest
267 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
269 * Similar to cgroup_css() but returns the effective css, which is defined
270 * as the matching css of the nearest ancestor including self which has @ss
271 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
272 * function is guaranteed to return non-NULL css.
274 static struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
275 struct cgroup_subsys *ss)
277 lockdep_assert_held(&cgroup_mutex);
282 if (!(cgrp->root->subsys_mask & (1 << ss->id)))
286 * This function is used while updating css associations and thus
287 * can't test the csses directly. Use ->child_subsys_mask.
289 while (cgroup_parent(cgrp) &&
290 !(cgroup_parent(cgrp)->child_subsys_mask & (1 << ss->id)))
291 cgrp = cgroup_parent(cgrp);
293 return cgroup_css(cgrp, ss);
297 * cgroup_get_e_css - get a cgroup's effective css for the specified subsystem
298 * @cgrp: the cgroup of interest
299 * @ss: the subsystem of interest
301 * Find and get the effective css of @cgrp for @ss. The effective css is
302 * defined as the matching css of the nearest ancestor including self which
303 * has @ss enabled. If @ss is not mounted on the hierarchy @cgrp is on,
304 * the root css is returned, so this function always returns a valid css.
305 * The returned css must be put using css_put().
307 struct cgroup_subsys_state *cgroup_get_e_css(struct cgroup *cgrp,
308 struct cgroup_subsys *ss)
310 struct cgroup_subsys_state *css;
315 css = cgroup_css(cgrp, ss);
317 if (css && css_tryget_online(css))
319 cgrp = cgroup_parent(cgrp);
322 css = init_css_set.subsys[ss->id];
329 /* convenient tests for these bits */
330 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
332 return !(cgrp->self.flags & CSS_ONLINE);
335 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
337 struct cgroup *cgrp = of->kn->parent->priv;
338 struct cftype *cft = of_cft(of);
341 * This is open and unprotected implementation of cgroup_css().
342 * seq_css() is only called from a kernfs file operation which has
343 * an active reference on the file. Because all the subsystem
344 * files are drained before a css is disassociated with a cgroup,
345 * the matching css from the cgroup's subsys table is guaranteed to
346 * be and stay valid until the enclosing operation is complete.
349 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
353 EXPORT_SYMBOL_GPL(of_css);
356 * cgroup_is_descendant - test ancestry
357 * @cgrp: the cgroup to be tested
358 * @ancestor: possible ancestor of @cgrp
360 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
361 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
362 * and @ancestor are accessible.
364 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
367 if (cgrp == ancestor)
369 cgrp = cgroup_parent(cgrp);
374 static int notify_on_release(const struct cgroup *cgrp)
376 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
380 * for_each_css - iterate all css's of a cgroup
381 * @css: the iteration cursor
382 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
383 * @cgrp: the target cgroup to iterate css's of
385 * Should be called under cgroup_[tree_]mutex.
387 #define for_each_css(css, ssid, cgrp) \
388 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
389 if (!((css) = rcu_dereference_check( \
390 (cgrp)->subsys[(ssid)], \
391 lockdep_is_held(&cgroup_mutex)))) { } \
395 * for_each_e_css - iterate all effective css's of a cgroup
396 * @css: the iteration cursor
397 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
398 * @cgrp: the target cgroup to iterate css's of
400 * Should be called under cgroup_[tree_]mutex.
402 #define for_each_e_css(css, ssid, cgrp) \
403 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
404 if (!((css) = cgroup_e_css(cgrp, cgroup_subsys[(ssid)]))) \
409 * for_each_subsys - iterate all enabled cgroup subsystems
410 * @ss: the iteration cursor
411 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
413 #define for_each_subsys(ss, ssid) \
414 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT && \
415 (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
418 * for_each_subsys_which - filter for_each_subsys with a bitmask
419 * @ss: the iteration cursor
420 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
421 * @ss_maskp: a pointer to the bitmask
423 * The block will only run for cases where the ssid-th bit (1 << ssid) of
426 #define for_each_subsys_which(ss, ssid, ss_maskp) \
427 if (!CGROUP_SUBSYS_COUNT) /* to avoid spurious gcc warning */ \
430 for_each_set_bit(ssid, ss_maskp, CGROUP_SUBSYS_COUNT) \
431 if (((ss) = cgroup_subsys[ssid]) && false) \
435 /* iterate across the hierarchies */
436 #define for_each_root(root) \
437 list_for_each_entry((root), &cgroup_roots, root_list)
439 /* iterate over child cgrps, lock should be held throughout iteration */
440 #define cgroup_for_each_live_child(child, cgrp) \
441 list_for_each_entry((child), &(cgrp)->self.children, self.sibling) \
442 if (({ lockdep_assert_held(&cgroup_mutex); \
443 cgroup_is_dead(child); })) \
447 static void cgroup_release_agent(struct work_struct *work);
448 static void check_for_release(struct cgroup *cgrp);
451 * A cgroup can be associated with multiple css_sets as different tasks may
452 * belong to different cgroups on different hierarchies. In the other
453 * direction, a css_set is naturally associated with multiple cgroups.
454 * This M:N relationship is represented by the following link structure
455 * which exists for each association and allows traversing the associations
458 struct cgrp_cset_link {
459 /* the cgroup and css_set this link associates */
461 struct css_set *cset;
463 /* list of cgrp_cset_links anchored at cgrp->cset_links */
464 struct list_head cset_link;
466 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
467 struct list_head cgrp_link;
471 * The default css_set - used by init and its children prior to any
472 * hierarchies being mounted. It contains a pointer to the root state
473 * for each subsystem. Also used to anchor the list of css_sets. Not
474 * reference-counted, to improve performance when child cgroups
475 * haven't been created.
477 struct css_set init_css_set = {
478 .refcount = ATOMIC_INIT(1),
479 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
480 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
481 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
482 .mg_preload_node = LIST_HEAD_INIT(init_css_set.mg_preload_node),
483 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
486 static int css_set_count = 1; /* 1 for init_css_set */
489 * cgroup_update_populated - updated populated count of a cgroup
490 * @cgrp: the target cgroup
491 * @populated: inc or dec populated count
493 * @cgrp is either getting the first task (css_set) or losing the last.
494 * Update @cgrp->populated_cnt accordingly. The count is propagated
495 * towards root so that a given cgroup's populated_cnt is zero iff the
496 * cgroup and all its descendants are empty.
498 * @cgrp's interface file "cgroup.populated" is zero if
499 * @cgrp->populated_cnt is zero and 1 otherwise. When @cgrp->populated_cnt
500 * changes from or to zero, userland is notified that the content of the
501 * interface file has changed. This can be used to detect when @cgrp and
502 * its descendants become populated or empty.
504 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
506 lockdep_assert_held(&css_set_rwsem);
512 trigger = !cgrp->populated_cnt++;
514 trigger = !--cgrp->populated_cnt;
519 if (cgrp->populated_kn)
520 kernfs_notify(cgrp->populated_kn);
521 cgrp = cgroup_parent(cgrp);
526 * hash table for cgroup groups. This improves the performance to find
527 * an existing css_set. This hash doesn't (currently) take into
528 * account cgroups in empty hierarchies.
530 #define CSS_SET_HASH_BITS 7
531 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
533 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
535 unsigned long key = 0UL;
536 struct cgroup_subsys *ss;
539 for_each_subsys(ss, i)
540 key += (unsigned long)css[i];
541 key = (key >> 16) ^ key;
546 static void put_css_set_locked(struct css_set *cset)
548 struct cgrp_cset_link *link, *tmp_link;
549 struct cgroup_subsys *ss;
552 lockdep_assert_held(&css_set_rwsem);
554 if (!atomic_dec_and_test(&cset->refcount))
557 /* This css_set is dead. unlink it and release cgroup refcounts */
558 for_each_subsys(ss, ssid)
559 list_del(&cset->e_cset_node[ssid]);
560 hash_del(&cset->hlist);
563 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
564 struct cgroup *cgrp = link->cgrp;
566 list_del(&link->cset_link);
567 list_del(&link->cgrp_link);
569 /* @cgrp can't go away while we're holding css_set_rwsem */
570 if (list_empty(&cgrp->cset_links)) {
571 cgroup_update_populated(cgrp, false);
572 check_for_release(cgrp);
578 kfree_rcu(cset, rcu_head);
581 static void put_css_set(struct css_set *cset)
584 * Ensure that the refcount doesn't hit zero while any readers
585 * can see it. Similar to atomic_dec_and_lock(), but for an
588 if (atomic_add_unless(&cset->refcount, -1, 1))
591 down_write(&css_set_rwsem);
592 put_css_set_locked(cset);
593 up_write(&css_set_rwsem);
597 * refcounted get/put for css_set objects
599 static inline void get_css_set(struct css_set *cset)
601 atomic_inc(&cset->refcount);
605 * compare_css_sets - helper function for find_existing_css_set().
606 * @cset: candidate css_set being tested
607 * @old_cset: existing css_set for a task
608 * @new_cgrp: cgroup that's being entered by the task
609 * @template: desired set of css pointers in css_set (pre-calculated)
611 * Returns true if "cset" matches "old_cset" except for the hierarchy
612 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
614 static bool compare_css_sets(struct css_set *cset,
615 struct css_set *old_cset,
616 struct cgroup *new_cgrp,
617 struct cgroup_subsys_state *template[])
619 struct list_head *l1, *l2;
622 * On the default hierarchy, there can be csets which are
623 * associated with the same set of cgroups but different csses.
624 * Let's first ensure that csses match.
626 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
630 * Compare cgroup pointers in order to distinguish between
631 * different cgroups in hierarchies. As different cgroups may
632 * share the same effective css, this comparison is always
635 l1 = &cset->cgrp_links;
636 l2 = &old_cset->cgrp_links;
638 struct cgrp_cset_link *link1, *link2;
639 struct cgroup *cgrp1, *cgrp2;
643 /* See if we reached the end - both lists are equal length. */
644 if (l1 == &cset->cgrp_links) {
645 BUG_ON(l2 != &old_cset->cgrp_links);
648 BUG_ON(l2 == &old_cset->cgrp_links);
650 /* Locate the cgroups associated with these links. */
651 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
652 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
655 /* Hierarchies should be linked in the same order. */
656 BUG_ON(cgrp1->root != cgrp2->root);
659 * If this hierarchy is the hierarchy of the cgroup
660 * that's changing, then we need to check that this
661 * css_set points to the new cgroup; if it's any other
662 * hierarchy, then this css_set should point to the
663 * same cgroup as the old css_set.
665 if (cgrp1->root == new_cgrp->root) {
666 if (cgrp1 != new_cgrp)
677 * find_existing_css_set - init css array and find the matching css_set
678 * @old_cset: the css_set that we're using before the cgroup transition
679 * @cgrp: the cgroup that we're moving into
680 * @template: out param for the new set of csses, should be clear on entry
682 static struct css_set *find_existing_css_set(struct css_set *old_cset,
684 struct cgroup_subsys_state *template[])
686 struct cgroup_root *root = cgrp->root;
687 struct cgroup_subsys *ss;
688 struct css_set *cset;
693 * Build the set of subsystem state objects that we want to see in the
694 * new css_set. while subsystems can change globally, the entries here
695 * won't change, so no need for locking.
697 for_each_subsys(ss, i) {
698 if (root->subsys_mask & (1UL << i)) {
700 * @ss is in this hierarchy, so we want the
701 * effective css from @cgrp.
703 template[i] = cgroup_e_css(cgrp, ss);
706 * @ss is not in this hierarchy, so we don't want
709 template[i] = old_cset->subsys[i];
713 key = css_set_hash(template);
714 hash_for_each_possible(css_set_table, cset, hlist, key) {
715 if (!compare_css_sets(cset, old_cset, cgrp, template))
718 /* This css_set matches what we need */
722 /* No existing cgroup group matched */
726 static void free_cgrp_cset_links(struct list_head *links_to_free)
728 struct cgrp_cset_link *link, *tmp_link;
730 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
731 list_del(&link->cset_link);
737 * allocate_cgrp_cset_links - allocate cgrp_cset_links
738 * @count: the number of links to allocate
739 * @tmp_links: list_head the allocated links are put on
741 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
742 * through ->cset_link. Returns 0 on success or -errno.
744 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
746 struct cgrp_cset_link *link;
749 INIT_LIST_HEAD(tmp_links);
751 for (i = 0; i < count; i++) {
752 link = kzalloc(sizeof(*link), GFP_KERNEL);
754 free_cgrp_cset_links(tmp_links);
757 list_add(&link->cset_link, tmp_links);
763 * link_css_set - a helper function to link a css_set to a cgroup
764 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
765 * @cset: the css_set to be linked
766 * @cgrp: the destination cgroup
768 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
771 struct cgrp_cset_link *link;
773 BUG_ON(list_empty(tmp_links));
775 if (cgroup_on_dfl(cgrp))
776 cset->dfl_cgrp = cgrp;
778 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
782 if (list_empty(&cgrp->cset_links))
783 cgroup_update_populated(cgrp, true);
784 list_move(&link->cset_link, &cgrp->cset_links);
787 * Always add links to the tail of the list so that the list
788 * is sorted by order of hierarchy creation
790 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
794 * find_css_set - return a new css_set with one cgroup updated
795 * @old_cset: the baseline css_set
796 * @cgrp: the cgroup to be updated
798 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
799 * substituted into the appropriate hierarchy.
801 static struct css_set *find_css_set(struct css_set *old_cset,
804 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
805 struct css_set *cset;
806 struct list_head tmp_links;
807 struct cgrp_cset_link *link;
808 struct cgroup_subsys *ss;
812 lockdep_assert_held(&cgroup_mutex);
814 /* First see if we already have a cgroup group that matches
816 down_read(&css_set_rwsem);
817 cset = find_existing_css_set(old_cset, cgrp, template);
820 up_read(&css_set_rwsem);
825 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
829 /* Allocate all the cgrp_cset_link objects that we'll need */
830 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
835 atomic_set(&cset->refcount, 1);
836 INIT_LIST_HEAD(&cset->cgrp_links);
837 INIT_LIST_HEAD(&cset->tasks);
838 INIT_LIST_HEAD(&cset->mg_tasks);
839 INIT_LIST_HEAD(&cset->mg_preload_node);
840 INIT_LIST_HEAD(&cset->mg_node);
841 INIT_HLIST_NODE(&cset->hlist);
843 /* Copy the set of subsystem state objects generated in
844 * find_existing_css_set() */
845 memcpy(cset->subsys, template, sizeof(cset->subsys));
847 down_write(&css_set_rwsem);
848 /* Add reference counts and links from the new css_set. */
849 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
850 struct cgroup *c = link->cgrp;
852 if (c->root == cgrp->root)
854 link_css_set(&tmp_links, cset, c);
857 BUG_ON(!list_empty(&tmp_links));
861 /* Add @cset to the hash table */
862 key = css_set_hash(cset->subsys);
863 hash_add(css_set_table, &cset->hlist, key);
865 for_each_subsys(ss, ssid)
866 list_add_tail(&cset->e_cset_node[ssid],
867 &cset->subsys[ssid]->cgroup->e_csets[ssid]);
869 up_write(&css_set_rwsem);
874 void cgroup_threadgroup_change_begin(struct task_struct *tsk)
876 down_read(&tsk->signal->group_rwsem);
879 void cgroup_threadgroup_change_end(struct task_struct *tsk)
881 up_read(&tsk->signal->group_rwsem);
885 * threadgroup_lock - lock threadgroup
886 * @tsk: member task of the threadgroup to lock
888 * Lock the threadgroup @tsk belongs to. No new task is allowed to enter
889 * and member tasks aren't allowed to exit (as indicated by PF_EXITING) or
890 * change ->group_leader/pid. This is useful for cases where the threadgroup
891 * needs to stay stable across blockable operations.
893 * fork and exit explicitly call threadgroup_change_{begin|end}() for
894 * synchronization. While held, no new task will be added to threadgroup
895 * and no existing live task will have its PF_EXITING set.
897 * de_thread() does threadgroup_change_{begin|end}() when a non-leader
898 * sub-thread becomes a new leader.
900 static void threadgroup_lock(struct task_struct *tsk)
902 down_write(&tsk->signal->group_rwsem);
906 * threadgroup_unlock - unlock threadgroup
907 * @tsk: member task of the threadgroup to unlock
909 * Reverse threadgroup_lock().
911 static inline void threadgroup_unlock(struct task_struct *tsk)
913 up_write(&tsk->signal->group_rwsem);
916 static struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
918 struct cgroup *root_cgrp = kf_root->kn->priv;
920 return root_cgrp->root;
923 static int cgroup_init_root_id(struct cgroup_root *root)
927 lockdep_assert_held(&cgroup_mutex);
929 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
933 root->hierarchy_id = id;
937 static void cgroup_exit_root_id(struct cgroup_root *root)
939 lockdep_assert_held(&cgroup_mutex);
941 if (root->hierarchy_id) {
942 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
943 root->hierarchy_id = 0;
947 static void cgroup_free_root(struct cgroup_root *root)
950 /* hierarchy ID should already have been released */
951 WARN_ON_ONCE(root->hierarchy_id);
953 idr_destroy(&root->cgroup_idr);
958 static void cgroup_destroy_root(struct cgroup_root *root)
960 struct cgroup *cgrp = &root->cgrp;
961 struct cgrp_cset_link *link, *tmp_link;
963 mutex_lock(&cgroup_mutex);
965 BUG_ON(atomic_read(&root->nr_cgrps));
966 BUG_ON(!list_empty(&cgrp->self.children));
968 /* Rebind all subsystems back to the default hierarchy */
969 rebind_subsystems(&cgrp_dfl_root, root->subsys_mask);
972 * Release all the links from cset_links to this hierarchy's
975 down_write(&css_set_rwsem);
977 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
978 list_del(&link->cset_link);
979 list_del(&link->cgrp_link);
982 up_write(&css_set_rwsem);
984 if (!list_empty(&root->root_list)) {
985 list_del(&root->root_list);
989 cgroup_exit_root_id(root);
991 mutex_unlock(&cgroup_mutex);
993 kernfs_destroy_root(root->kf_root);
994 cgroup_free_root(root);
997 /* look up cgroup associated with given css_set on the specified hierarchy */
998 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
999 struct cgroup_root *root)
1001 struct cgroup *res = NULL;
1003 lockdep_assert_held(&cgroup_mutex);
1004 lockdep_assert_held(&css_set_rwsem);
1006 if (cset == &init_css_set) {
1009 struct cgrp_cset_link *link;
1011 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1012 struct cgroup *c = link->cgrp;
1014 if (c->root == root) {
1026 * Return the cgroup for "task" from the given hierarchy. Must be
1027 * called with cgroup_mutex and css_set_rwsem held.
1029 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
1030 struct cgroup_root *root)
1033 * No need to lock the task - since we hold cgroup_mutex the
1034 * task can't change groups, so the only thing that can happen
1035 * is that it exits and its css is set back to init_css_set.
1037 return cset_cgroup_from_root(task_css_set(task), root);
1041 * A task must hold cgroup_mutex to modify cgroups.
1043 * Any task can increment and decrement the count field without lock.
1044 * So in general, code holding cgroup_mutex can't rely on the count
1045 * field not changing. However, if the count goes to zero, then only
1046 * cgroup_attach_task() can increment it again. Because a count of zero
1047 * means that no tasks are currently attached, therefore there is no
1048 * way a task attached to that cgroup can fork (the other way to
1049 * increment the count). So code holding cgroup_mutex can safely
1050 * assume that if the count is zero, it will stay zero. Similarly, if
1051 * a task holds cgroup_mutex on a cgroup with zero count, it
1052 * knows that the cgroup won't be removed, as cgroup_rmdir()
1055 * A cgroup can only be deleted if both its 'count' of using tasks
1056 * is zero, and its list of 'children' cgroups is empty. Since all
1057 * tasks in the system use _some_ cgroup, and since there is always at
1058 * least one task in the system (init, pid == 1), therefore, root cgroup
1059 * always has either children cgroups and/or using tasks. So we don't
1060 * need a special hack to ensure that root cgroup cannot be deleted.
1062 * P.S. One more locking exception. RCU is used to guard the
1063 * update of a tasks cgroup pointer by cgroup_attach_task()
1066 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask);
1067 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
1068 static const struct file_operations proc_cgroupstats_operations;
1070 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
1073 struct cgroup_subsys *ss = cft->ss;
1075 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
1076 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
1077 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
1078 cgroup_on_dfl(cgrp) ? ss->name : ss->legacy_name,
1081 strncpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
1086 * cgroup_file_mode - deduce file mode of a control file
1087 * @cft: the control file in question
1089 * returns cft->mode if ->mode is not 0
1090 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
1091 * returns S_IRUGO if it has only a read handler
1092 * returns S_IWUSR if it has only a write hander
1094 static umode_t cgroup_file_mode(const struct cftype *cft)
1101 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1104 if (cft->write_u64 || cft->write_s64 || cft->write)
1110 static void cgroup_get(struct cgroup *cgrp)
1112 WARN_ON_ONCE(cgroup_is_dead(cgrp));
1113 css_get(&cgrp->self);
1116 static bool cgroup_tryget(struct cgroup *cgrp)
1118 return css_tryget(&cgrp->self);
1121 static void cgroup_put(struct cgroup *cgrp)
1123 css_put(&cgrp->self);
1127 * cgroup_calc_child_subsys_mask - calculate child_subsys_mask
1128 * @cgrp: the target cgroup
1129 * @subtree_control: the new subtree_control mask to consider
1131 * On the default hierarchy, a subsystem may request other subsystems to be
1132 * enabled together through its ->depends_on mask. In such cases, more
1133 * subsystems than specified in "cgroup.subtree_control" may be enabled.
1135 * This function calculates which subsystems need to be enabled if
1136 * @subtree_control is to be applied to @cgrp. The returned mask is always
1137 * a superset of @subtree_control and follows the usual hierarchy rules.
1139 static unsigned long cgroup_calc_child_subsys_mask(struct cgroup *cgrp,
1140 unsigned long subtree_control)
1142 struct cgroup *parent = cgroup_parent(cgrp);
1143 unsigned long cur_ss_mask = subtree_control;
1144 struct cgroup_subsys *ss;
1147 lockdep_assert_held(&cgroup_mutex);
1149 if (!cgroup_on_dfl(cgrp))
1153 unsigned long new_ss_mask = cur_ss_mask;
1155 for_each_subsys_which(ss, ssid, &cur_ss_mask)
1156 new_ss_mask |= ss->depends_on;
1159 * Mask out subsystems which aren't available. This can
1160 * happen only if some depended-upon subsystems were bound
1161 * to non-default hierarchies.
1164 new_ss_mask &= parent->child_subsys_mask;
1166 new_ss_mask &= cgrp->root->subsys_mask;
1168 if (new_ss_mask == cur_ss_mask)
1170 cur_ss_mask = new_ss_mask;
1177 * cgroup_refresh_child_subsys_mask - update child_subsys_mask
1178 * @cgrp: the target cgroup
1180 * Update @cgrp->child_subsys_mask according to the current
1181 * @cgrp->subtree_control using cgroup_calc_child_subsys_mask().
1183 static void cgroup_refresh_child_subsys_mask(struct cgroup *cgrp)
1185 cgrp->child_subsys_mask =
1186 cgroup_calc_child_subsys_mask(cgrp, cgrp->subtree_control);
1190 * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
1191 * @kn: the kernfs_node being serviced
1193 * This helper undoes cgroup_kn_lock_live() and should be invoked before
1194 * the method finishes if locking succeeded. Note that once this function
1195 * returns the cgroup returned by cgroup_kn_lock_live() may become
1196 * inaccessible any time. If the caller intends to continue to access the
1197 * cgroup, it should pin it before invoking this function.
1199 static void cgroup_kn_unlock(struct kernfs_node *kn)
1201 struct cgroup *cgrp;
1203 if (kernfs_type(kn) == KERNFS_DIR)
1206 cgrp = kn->parent->priv;
1208 mutex_unlock(&cgroup_mutex);
1210 kernfs_unbreak_active_protection(kn);
1215 * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
1216 * @kn: the kernfs_node being serviced
1218 * This helper is to be used by a cgroup kernfs method currently servicing
1219 * @kn. It breaks the active protection, performs cgroup locking and
1220 * verifies that the associated cgroup is alive. Returns the cgroup if
1221 * alive; otherwise, %NULL. A successful return should be undone by a
1222 * matching cgroup_kn_unlock() invocation.
1224 * Any cgroup kernfs method implementation which requires locking the
1225 * associated cgroup should use this helper. It avoids nesting cgroup
1226 * locking under kernfs active protection and allows all kernfs operations
1227 * including self-removal.
1229 static struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn)
1231 struct cgroup *cgrp;
1233 if (kernfs_type(kn) == KERNFS_DIR)
1236 cgrp = kn->parent->priv;
1239 * We're gonna grab cgroup_mutex which nests outside kernfs
1240 * active_ref. cgroup liveliness check alone provides enough
1241 * protection against removal. Ensure @cgrp stays accessible and
1242 * break the active_ref protection.
1244 if (!cgroup_tryget(cgrp))
1246 kernfs_break_active_protection(kn);
1248 mutex_lock(&cgroup_mutex);
1250 if (!cgroup_is_dead(cgrp))
1253 cgroup_kn_unlock(kn);
1257 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1259 char name[CGROUP_FILE_NAME_MAX];
1261 lockdep_assert_held(&cgroup_mutex);
1262 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1266 * cgroup_clear_dir - remove subsys files in a cgroup directory
1267 * @cgrp: target cgroup
1268 * @subsys_mask: mask of the subsystem ids whose files should be removed
1270 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned long subsys_mask)
1272 struct cgroup_subsys *ss;
1275 for_each_subsys(ss, i) {
1276 struct cftype *cfts;
1278 if (!(subsys_mask & (1 << i)))
1280 list_for_each_entry(cfts, &ss->cfts, node)
1281 cgroup_addrm_files(cgrp, cfts, false);
1285 static int rebind_subsystems(struct cgroup_root *dst_root,
1286 unsigned long ss_mask)
1288 struct cgroup_subsys *ss;
1289 unsigned long tmp_ss_mask;
1292 lockdep_assert_held(&cgroup_mutex);
1294 for_each_subsys_which(ss, ssid, &ss_mask) {
1295 /* if @ss has non-root csses attached to it, can't move */
1296 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)))
1299 /* can't move between two non-dummy roots either */
1300 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1304 /* skip creating root files on dfl_root for inhibited subsystems */
1305 tmp_ss_mask = ss_mask;
1306 if (dst_root == &cgrp_dfl_root)
1307 tmp_ss_mask &= ~cgrp_dfl_root_inhibit_ss_mask;
1309 ret = cgroup_populate_dir(&dst_root->cgrp, tmp_ss_mask);
1311 if (dst_root != &cgrp_dfl_root)
1315 * Rebinding back to the default root is not allowed to
1316 * fail. Using both default and non-default roots should
1317 * be rare. Moving subsystems back and forth even more so.
1318 * Just warn about it and continue.
1320 if (cgrp_dfl_root_visible) {
1321 pr_warn("failed to create files (%d) while rebinding 0x%lx to default root\n",
1323 pr_warn("you may retry by moving them to a different hierarchy and unbinding\n");
1328 * Nothing can fail from this point on. Remove files for the
1329 * removed subsystems and rebind each subsystem.
1331 for_each_subsys_which(ss, ssid, &ss_mask)
1332 cgroup_clear_dir(&ss->root->cgrp, 1 << ssid);
1334 for_each_subsys_which(ss, ssid, &ss_mask) {
1335 struct cgroup_root *src_root;
1336 struct cgroup_subsys_state *css;
1337 struct css_set *cset;
1339 src_root = ss->root;
1340 css = cgroup_css(&src_root->cgrp, ss);
1342 WARN_ON(!css || cgroup_css(&dst_root->cgrp, ss));
1344 RCU_INIT_POINTER(src_root->cgrp.subsys[ssid], NULL);
1345 rcu_assign_pointer(dst_root->cgrp.subsys[ssid], css);
1346 ss->root = dst_root;
1347 css->cgroup = &dst_root->cgrp;
1349 down_write(&css_set_rwsem);
1350 hash_for_each(css_set_table, i, cset, hlist)
1351 list_move_tail(&cset->e_cset_node[ss->id],
1352 &dst_root->cgrp.e_csets[ss->id]);
1353 up_write(&css_set_rwsem);
1355 src_root->subsys_mask &= ~(1 << ssid);
1356 src_root->cgrp.subtree_control &= ~(1 << ssid);
1357 cgroup_refresh_child_subsys_mask(&src_root->cgrp);
1359 /* default hierarchy doesn't enable controllers by default */
1360 dst_root->subsys_mask |= 1 << ssid;
1361 if (dst_root != &cgrp_dfl_root) {
1362 dst_root->cgrp.subtree_control |= 1 << ssid;
1363 cgroup_refresh_child_subsys_mask(&dst_root->cgrp);
1370 kernfs_activate(dst_root->cgrp.kn);
1374 static int cgroup_show_options(struct seq_file *seq,
1375 struct kernfs_root *kf_root)
1377 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1378 struct cgroup_subsys *ss;
1381 if (root != &cgrp_dfl_root)
1382 for_each_subsys(ss, ssid)
1383 if (root->subsys_mask & (1 << ssid))
1384 seq_show_option(seq, ss->legacy_name, NULL);
1385 if (root->flags & CGRP_ROOT_NOPREFIX)
1386 seq_puts(seq, ",noprefix");
1387 if (root->flags & CGRP_ROOT_XATTR)
1388 seq_puts(seq, ",xattr");
1390 spin_lock(&release_agent_path_lock);
1391 if (strlen(root->release_agent_path))
1392 seq_show_option(seq, "release_agent",
1393 root->release_agent_path);
1394 spin_unlock(&release_agent_path_lock);
1396 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags))
1397 seq_puts(seq, ",clone_children");
1398 if (strlen(root->name))
1399 seq_show_option(seq, "name", root->name);
1403 struct cgroup_sb_opts {
1404 unsigned long subsys_mask;
1406 char *release_agent;
1407 bool cpuset_clone_children;
1409 /* User explicitly requested empty subsystem */
1413 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1415 char *token, *o = data;
1416 bool all_ss = false, one_ss = false;
1417 unsigned long mask = -1UL;
1418 struct cgroup_subsys *ss;
1422 #ifdef CONFIG_CPUSETS
1423 mask = ~(1U << cpuset_cgrp_id);
1426 memset(opts, 0, sizeof(*opts));
1428 while ((token = strsep(&o, ",")) != NULL) {
1433 if (!strcmp(token, "none")) {
1434 /* Explicitly have no subsystems */
1438 if (!strcmp(token, "all")) {
1439 /* Mutually exclusive option 'all' + subsystem name */
1445 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1446 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1449 if (!strcmp(token, "noprefix")) {
1450 opts->flags |= CGRP_ROOT_NOPREFIX;
1453 if (!strcmp(token, "clone_children")) {
1454 opts->cpuset_clone_children = true;
1457 if (!strcmp(token, "xattr")) {
1458 opts->flags |= CGRP_ROOT_XATTR;
1461 if (!strncmp(token, "release_agent=", 14)) {
1462 /* Specifying two release agents is forbidden */
1463 if (opts->release_agent)
1465 opts->release_agent =
1466 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1467 if (!opts->release_agent)
1471 if (!strncmp(token, "name=", 5)) {
1472 const char *name = token + 5;
1473 /* Can't specify an empty name */
1476 /* Must match [\w.-]+ */
1477 for (i = 0; i < strlen(name); i++) {
1481 if ((c == '.') || (c == '-') || (c == '_'))
1485 /* Specifying two names is forbidden */
1488 opts->name = kstrndup(name,
1489 MAX_CGROUP_ROOT_NAMELEN - 1,
1497 for_each_subsys(ss, i) {
1498 if (strcmp(token, ss->legacy_name))
1503 /* Mutually exclusive option 'all' + subsystem name */
1506 opts->subsys_mask |= (1 << i);
1511 if (i == CGROUP_SUBSYS_COUNT)
1515 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1516 pr_warn("sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1518 pr_err("sane_behavior: no other mount options allowed\n");
1525 * If the 'all' option was specified select all the subsystems,
1526 * otherwise if 'none', 'name=' and a subsystem name options were
1527 * not specified, let's default to 'all'
1529 if (all_ss || (!one_ss && !opts->none && !opts->name))
1530 for_each_subsys(ss, i)
1532 opts->subsys_mask |= (1 << i);
1535 * We either have to specify by name or by subsystems. (So all
1536 * empty hierarchies must have a name).
1538 if (!opts->subsys_mask && !opts->name)
1542 * Option noprefix was introduced just for backward compatibility
1543 * with the old cpuset, so we allow noprefix only if mounting just
1544 * the cpuset subsystem.
1546 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1549 /* Can't specify "none" and some subsystems */
1550 if (opts->subsys_mask && opts->none)
1556 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1559 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1560 struct cgroup_sb_opts opts;
1561 unsigned long added_mask, removed_mask;
1563 if (root == &cgrp_dfl_root) {
1564 pr_err("remount is not allowed\n");
1568 mutex_lock(&cgroup_mutex);
1570 /* See what subsystems are wanted */
1571 ret = parse_cgroupfs_options(data, &opts);
1575 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1576 pr_warn("option changes via remount are deprecated (pid=%d comm=%s)\n",
1577 task_tgid_nr(current), current->comm);
1579 added_mask = opts.subsys_mask & ~root->subsys_mask;
1580 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1582 /* Don't allow flags or name to change at remount */
1583 if ((opts.flags ^ root->flags) ||
1584 (opts.name && strcmp(opts.name, root->name))) {
1585 pr_err("option or name mismatch, new: 0x%x \"%s\", old: 0x%x \"%s\"\n",
1586 opts.flags, opts.name ?: "", root->flags, root->name);
1591 /* remounting is not allowed for populated hierarchies */
1592 if (!list_empty(&root->cgrp.self.children)) {
1597 ret = rebind_subsystems(root, added_mask);
1601 rebind_subsystems(&cgrp_dfl_root, removed_mask);
1603 if (opts.release_agent) {
1604 spin_lock(&release_agent_path_lock);
1605 strcpy(root->release_agent_path, opts.release_agent);
1606 spin_unlock(&release_agent_path_lock);
1609 kfree(opts.release_agent);
1611 mutex_unlock(&cgroup_mutex);
1616 * To reduce the fork() overhead for systems that are not actually using
1617 * their cgroups capability, we don't maintain the lists running through
1618 * each css_set to its tasks until we see the list actually used - in other
1619 * words after the first mount.
1621 static bool use_task_css_set_links __read_mostly;
1623 static void cgroup_enable_task_cg_lists(void)
1625 struct task_struct *p, *g;
1627 down_write(&css_set_rwsem);
1629 if (use_task_css_set_links)
1632 use_task_css_set_links = true;
1635 * We need tasklist_lock because RCU is not safe against
1636 * while_each_thread(). Besides, a forking task that has passed
1637 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1638 * is not guaranteed to have its child immediately visible in the
1639 * tasklist if we walk through it with RCU.
1641 read_lock(&tasklist_lock);
1642 do_each_thread(g, p) {
1643 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1644 task_css_set(p) != &init_css_set);
1647 * We should check if the process is exiting, otherwise
1648 * it will race with cgroup_exit() in that the list
1649 * entry won't be deleted though the process has exited.
1650 * Do it while holding siglock so that we don't end up
1651 * racing against cgroup_exit().
1653 spin_lock_irq(&p->sighand->siglock);
1654 if (!(p->flags & PF_EXITING)) {
1655 struct css_set *cset = task_css_set(p);
1657 list_add(&p->cg_list, &cset->tasks);
1660 spin_unlock_irq(&p->sighand->siglock);
1661 } while_each_thread(g, p);
1662 read_unlock(&tasklist_lock);
1664 up_write(&css_set_rwsem);
1667 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1669 struct cgroup_subsys *ss;
1672 INIT_LIST_HEAD(&cgrp->self.sibling);
1673 INIT_LIST_HEAD(&cgrp->self.children);
1674 INIT_LIST_HEAD(&cgrp->cset_links);
1675 INIT_LIST_HEAD(&cgrp->pidlists);
1676 mutex_init(&cgrp->pidlist_mutex);
1677 cgrp->self.cgroup = cgrp;
1678 cgrp->self.flags |= CSS_ONLINE;
1680 for_each_subsys(ss, ssid)
1681 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
1683 init_waitqueue_head(&cgrp->offline_waitq);
1684 INIT_WORK(&cgrp->release_agent_work, cgroup_release_agent);
1687 static void init_cgroup_root(struct cgroup_root *root,
1688 struct cgroup_sb_opts *opts)
1690 struct cgroup *cgrp = &root->cgrp;
1692 INIT_LIST_HEAD(&root->root_list);
1693 atomic_set(&root->nr_cgrps, 1);
1695 init_cgroup_housekeeping(cgrp);
1696 idr_init(&root->cgroup_idr);
1698 root->flags = opts->flags;
1699 if (opts->release_agent)
1700 strcpy(root->release_agent_path, opts->release_agent);
1702 strcpy(root->name, opts->name);
1703 if (opts->cpuset_clone_children)
1704 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1707 static int cgroup_setup_root(struct cgroup_root *root, unsigned long ss_mask)
1709 LIST_HEAD(tmp_links);
1710 struct cgroup *root_cgrp = &root->cgrp;
1711 struct cftype *base_files;
1712 struct css_set *cset;
1715 lockdep_assert_held(&cgroup_mutex);
1717 ret = cgroup_idr_alloc(&root->cgroup_idr, root_cgrp, 1, 2, GFP_KERNEL);
1720 root_cgrp->id = ret;
1722 ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release, 0,
1728 * We're accessing css_set_count without locking css_set_rwsem here,
1729 * but that's OK - it can only be increased by someone holding
1730 * cgroup_lock, and that's us. The worst that can happen is that we
1731 * have some link structures left over
1733 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1737 ret = cgroup_init_root_id(root);
1741 root->kf_root = kernfs_create_root(&cgroup_kf_syscall_ops,
1742 KERNFS_ROOT_CREATE_DEACTIVATED,
1744 if (IS_ERR(root->kf_root)) {
1745 ret = PTR_ERR(root->kf_root);
1748 root_cgrp->kn = root->kf_root->kn;
1750 if (root == &cgrp_dfl_root)
1751 base_files = cgroup_dfl_base_files;
1753 base_files = cgroup_legacy_base_files;
1755 ret = cgroup_addrm_files(root_cgrp, base_files, true);
1759 ret = rebind_subsystems(root, ss_mask);
1764 * There must be no failure case after here, since rebinding takes
1765 * care of subsystems' refcounts, which are explicitly dropped in
1766 * the failure exit path.
1768 list_add(&root->root_list, &cgroup_roots);
1769 cgroup_root_count++;
1772 * Link the root cgroup in this hierarchy into all the css_set
1775 down_write(&css_set_rwsem);
1776 hash_for_each(css_set_table, i, cset, hlist)
1777 link_css_set(&tmp_links, cset, root_cgrp);
1778 up_write(&css_set_rwsem);
1780 BUG_ON(!list_empty(&root_cgrp->self.children));
1781 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
1783 kernfs_activate(root_cgrp->kn);
1788 kernfs_destroy_root(root->kf_root);
1789 root->kf_root = NULL;
1791 cgroup_exit_root_id(root);
1793 percpu_ref_exit(&root_cgrp->self.refcnt);
1795 free_cgrp_cset_links(&tmp_links);
1799 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1800 int flags, const char *unused_dev_name,
1803 struct super_block *pinned_sb = NULL;
1804 struct cgroup_subsys *ss;
1805 struct cgroup_root *root;
1806 struct cgroup_sb_opts opts;
1807 struct dentry *dentry;
1813 * The first time anyone tries to mount a cgroup, enable the list
1814 * linking each css_set to its tasks and fix up all existing tasks.
1816 if (!use_task_css_set_links)
1817 cgroup_enable_task_cg_lists();
1819 mutex_lock(&cgroup_mutex);
1821 /* First find the desired set of subsystems */
1822 ret = parse_cgroupfs_options(data, &opts);
1826 /* look for a matching existing root */
1827 if (opts.flags & CGRP_ROOT_SANE_BEHAVIOR) {
1828 cgrp_dfl_root_visible = true;
1829 root = &cgrp_dfl_root;
1830 cgroup_get(&root->cgrp);
1836 * Destruction of cgroup root is asynchronous, so subsystems may
1837 * still be dying after the previous unmount. Let's drain the
1838 * dying subsystems. We just need to ensure that the ones
1839 * unmounted previously finish dying and don't care about new ones
1840 * starting. Testing ref liveliness is good enough.
1842 for_each_subsys(ss, i) {
1843 if (!(opts.subsys_mask & (1 << i)) ||
1844 ss->root == &cgrp_dfl_root)
1847 if (!percpu_ref_tryget_live(&ss->root->cgrp.self.refcnt)) {
1848 mutex_unlock(&cgroup_mutex);
1850 ret = restart_syscall();
1853 cgroup_put(&ss->root->cgrp);
1856 for_each_root(root) {
1857 bool name_match = false;
1859 if (root == &cgrp_dfl_root)
1863 * If we asked for a name then it must match. Also, if
1864 * name matches but sybsys_mask doesn't, we should fail.
1865 * Remember whether name matched.
1868 if (strcmp(opts.name, root->name))
1874 * If we asked for subsystems (or explicitly for no
1875 * subsystems) then they must match.
1877 if ((opts.subsys_mask || opts.none) &&
1878 (opts.subsys_mask != root->subsys_mask)) {
1885 if (root->flags ^ opts.flags)
1886 pr_warn("new mount options do not match the existing superblock, will be ignored\n");
1889 * We want to reuse @root whose lifetime is governed by its
1890 * ->cgrp. Let's check whether @root is alive and keep it
1891 * that way. As cgroup_kill_sb() can happen anytime, we
1892 * want to block it by pinning the sb so that @root doesn't
1893 * get killed before mount is complete.
1895 * With the sb pinned, tryget_live can reliably indicate
1896 * whether @root can be reused. If it's being killed,
1897 * drain it. We can use wait_queue for the wait but this
1898 * path is super cold. Let's just sleep a bit and retry.
1900 pinned_sb = kernfs_pin_sb(root->kf_root, NULL);
1901 if (IS_ERR(pinned_sb) ||
1902 !percpu_ref_tryget_live(&root->cgrp.self.refcnt)) {
1903 mutex_unlock(&cgroup_mutex);
1904 if (!IS_ERR_OR_NULL(pinned_sb))
1905 deactivate_super(pinned_sb);
1907 ret = restart_syscall();
1916 * No such thing, create a new one. name= matching without subsys
1917 * specification is allowed for already existing hierarchies but we
1918 * can't create new one without subsys specification.
1920 if (!opts.subsys_mask && !opts.none) {
1925 root = kzalloc(sizeof(*root), GFP_KERNEL);
1931 init_cgroup_root(root, &opts);
1933 ret = cgroup_setup_root(root, opts.subsys_mask);
1935 cgroup_free_root(root);
1938 mutex_unlock(&cgroup_mutex);
1940 kfree(opts.release_agent);
1944 return ERR_PTR(ret);
1946 dentry = kernfs_mount(fs_type, flags, root->kf_root,
1947 CGROUP_SUPER_MAGIC, &new_sb);
1948 if (IS_ERR(dentry) || !new_sb)
1949 cgroup_put(&root->cgrp);
1952 * If @pinned_sb, we're reusing an existing root and holding an
1953 * extra ref on its sb. Mount is complete. Put the extra ref.
1957 deactivate_super(pinned_sb);
1963 static void cgroup_kill_sb(struct super_block *sb)
1965 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
1966 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1969 * If @root doesn't have any mounts or children, start killing it.
1970 * This prevents new mounts by disabling percpu_ref_tryget_live().
1971 * cgroup_mount() may wait for @root's release.
1973 * And don't kill the default root.
1975 if (!list_empty(&root->cgrp.self.children) ||
1976 root == &cgrp_dfl_root)
1977 cgroup_put(&root->cgrp);
1979 percpu_ref_kill(&root->cgrp.self.refcnt);
1984 static struct file_system_type cgroup_fs_type = {
1986 .mount = cgroup_mount,
1987 .kill_sb = cgroup_kill_sb,
1991 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1992 * @task: target task
1993 * @buf: the buffer to write the path into
1994 * @buflen: the length of the buffer
1996 * Determine @task's cgroup on the first (the one with the lowest non-zero
1997 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1998 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1999 * cgroup controller callbacks.
2001 * Return value is the same as kernfs_path().
2003 char *task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
2005 struct cgroup_root *root;
2006 struct cgroup *cgrp;
2007 int hierarchy_id = 1;
2010 mutex_lock(&cgroup_mutex);
2011 down_read(&css_set_rwsem);
2013 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
2016 cgrp = task_cgroup_from_root(task, root);
2017 path = cgroup_path(cgrp, buf, buflen);
2019 /* if no hierarchy exists, everyone is in "/" */
2020 if (strlcpy(buf, "/", buflen) < buflen)
2024 up_read(&css_set_rwsem);
2025 mutex_unlock(&cgroup_mutex);
2028 EXPORT_SYMBOL_GPL(task_cgroup_path);
2030 /* used to track tasks and other necessary states during migration */
2031 struct cgroup_taskset {
2032 /* the src and dst cset list running through cset->mg_node */
2033 struct list_head src_csets;
2034 struct list_head dst_csets;
2037 * Fields for cgroup_taskset_*() iteration.
2039 * Before migration is committed, the target migration tasks are on
2040 * ->mg_tasks of the csets on ->src_csets. After, on ->mg_tasks of
2041 * the csets on ->dst_csets. ->csets point to either ->src_csets
2042 * or ->dst_csets depending on whether migration is committed.
2044 * ->cur_csets and ->cur_task point to the current task position
2047 struct list_head *csets;
2048 struct css_set *cur_cset;
2049 struct task_struct *cur_task;
2053 * cgroup_taskset_first - reset taskset and return the first task
2054 * @tset: taskset of interest
2056 * @tset iteration is initialized and the first task is returned.
2058 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
2060 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
2061 tset->cur_task = NULL;
2063 return cgroup_taskset_next(tset);
2067 * cgroup_taskset_next - iterate to the next task in taskset
2068 * @tset: taskset of interest
2070 * Return the next task in @tset. Iteration must have been initialized
2071 * with cgroup_taskset_first().
2073 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
2075 struct css_set *cset = tset->cur_cset;
2076 struct task_struct *task = tset->cur_task;
2078 while (&cset->mg_node != tset->csets) {
2080 task = list_first_entry(&cset->mg_tasks,
2081 struct task_struct, cg_list);
2083 task = list_next_entry(task, cg_list);
2085 if (&task->cg_list != &cset->mg_tasks) {
2086 tset->cur_cset = cset;
2087 tset->cur_task = task;
2091 cset = list_next_entry(cset, mg_node);
2099 * cgroup_task_migrate - move a task from one cgroup to another.
2100 * @old_cgrp: the cgroup @tsk is being migrated from
2101 * @tsk: the task being migrated
2102 * @new_cset: the new css_set @tsk is being attached to
2104 * Must be called with cgroup_mutex, threadgroup and css_set_rwsem locked.
2106 static void cgroup_task_migrate(struct cgroup *old_cgrp,
2107 struct task_struct *tsk,
2108 struct css_set *new_cset)
2110 struct css_set *old_cset;
2112 lockdep_assert_held(&cgroup_mutex);
2113 lockdep_assert_held(&css_set_rwsem);
2116 * We are synchronized through threadgroup_lock() against PF_EXITING
2117 * setting such that we can't race against cgroup_exit() changing the
2118 * css_set to init_css_set and dropping the old one.
2120 WARN_ON_ONCE(tsk->flags & PF_EXITING);
2121 old_cset = task_css_set(tsk);
2123 get_css_set(new_cset);
2124 rcu_assign_pointer(tsk->cgroups, new_cset);
2127 * Use move_tail so that cgroup_taskset_first() still returns the
2128 * leader after migration. This works because cgroup_migrate()
2129 * ensures that the dst_cset of the leader is the first on the
2130 * tset's dst_csets list.
2132 list_move_tail(&tsk->cg_list, &new_cset->mg_tasks);
2135 * We just gained a reference on old_cset by taking it from the
2136 * task. As trading it for new_cset is protected by cgroup_mutex,
2137 * we're safe to drop it here; it will be freed under RCU.
2139 put_css_set_locked(old_cset);
2143 * cgroup_migrate_finish - cleanup after attach
2144 * @preloaded_csets: list of preloaded css_sets
2146 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
2147 * those functions for details.
2149 static void cgroup_migrate_finish(struct list_head *preloaded_csets)
2151 struct css_set *cset, *tmp_cset;
2153 lockdep_assert_held(&cgroup_mutex);
2155 down_write(&css_set_rwsem);
2156 list_for_each_entry_safe(cset, tmp_cset, preloaded_csets, mg_preload_node) {
2157 cset->mg_src_cgrp = NULL;
2158 cset->mg_dst_cset = NULL;
2159 list_del_init(&cset->mg_preload_node);
2160 put_css_set_locked(cset);
2162 up_write(&css_set_rwsem);
2166 * cgroup_migrate_add_src - add a migration source css_set
2167 * @src_cset: the source css_set to add
2168 * @dst_cgrp: the destination cgroup
2169 * @preloaded_csets: list of preloaded css_sets
2171 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
2172 * @src_cset and add it to @preloaded_csets, which should later be cleaned
2173 * up by cgroup_migrate_finish().
2175 * This function may be called without holding threadgroup_lock even if the
2176 * target is a process. Threads may be created and destroyed but as long
2177 * as cgroup_mutex is not dropped, no new css_set can be put into play and
2178 * the preloaded css_sets are guaranteed to cover all migrations.
2180 static void cgroup_migrate_add_src(struct css_set *src_cset,
2181 struct cgroup *dst_cgrp,
2182 struct list_head *preloaded_csets)
2184 struct cgroup *src_cgrp;
2186 lockdep_assert_held(&cgroup_mutex);
2187 lockdep_assert_held(&css_set_rwsem);
2189 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2191 if (!list_empty(&src_cset->mg_preload_node))
2194 WARN_ON(src_cset->mg_src_cgrp);
2195 WARN_ON(!list_empty(&src_cset->mg_tasks));
2196 WARN_ON(!list_empty(&src_cset->mg_node));
2198 src_cset->mg_src_cgrp = src_cgrp;
2199 get_css_set(src_cset);
2200 list_add(&src_cset->mg_preload_node, preloaded_csets);
2204 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2205 * @dst_cgrp: the destination cgroup (may be %NULL)
2206 * @preloaded_csets: list of preloaded source css_sets
2208 * Tasks are about to be moved to @dst_cgrp and all the source css_sets
2209 * have been preloaded to @preloaded_csets. This function looks up and
2210 * pins all destination css_sets, links each to its source, and append them
2211 * to @preloaded_csets. If @dst_cgrp is %NULL, the destination of each
2212 * source css_set is assumed to be its cgroup on the default hierarchy.
2214 * This function must be called after cgroup_migrate_add_src() has been
2215 * called on each migration source css_set. After migration is performed
2216 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2219 static int cgroup_migrate_prepare_dst(struct cgroup *dst_cgrp,
2220 struct list_head *preloaded_csets)
2223 struct css_set *src_cset, *tmp_cset;
2225 lockdep_assert_held(&cgroup_mutex);
2228 * Except for the root, child_subsys_mask must be zero for a cgroup
2229 * with tasks so that child cgroups don't compete against tasks.
2231 if (dst_cgrp && cgroup_on_dfl(dst_cgrp) && cgroup_parent(dst_cgrp) &&
2232 dst_cgrp->child_subsys_mask)
2235 /* look up the dst cset for each src cset and link it to src */
2236 list_for_each_entry_safe(src_cset, tmp_cset, preloaded_csets, mg_preload_node) {
2237 struct css_set *dst_cset;
2239 dst_cset = find_css_set(src_cset,
2240 dst_cgrp ?: src_cset->dfl_cgrp);
2244 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2247 * If src cset equals dst, it's noop. Drop the src.
2248 * cgroup_migrate() will skip the cset too. Note that we
2249 * can't handle src == dst as some nodes are used by both.
2251 if (src_cset == dst_cset) {
2252 src_cset->mg_src_cgrp = NULL;
2253 list_del_init(&src_cset->mg_preload_node);
2254 put_css_set(src_cset);
2255 put_css_set(dst_cset);
2259 src_cset->mg_dst_cset = dst_cset;
2261 if (list_empty(&dst_cset->mg_preload_node))
2262 list_add(&dst_cset->mg_preload_node, &csets);
2264 put_css_set(dst_cset);
2267 list_splice_tail(&csets, preloaded_csets);
2270 cgroup_migrate_finish(&csets);
2275 * cgroup_migrate - migrate a process or task to a cgroup
2276 * @cgrp: the destination cgroup
2277 * @leader: the leader of the process or the task to migrate
2278 * @threadgroup: whether @leader points to the whole process or a single task
2280 * Migrate a process or task denoted by @leader to @cgrp. If migrating a
2281 * process, the caller must be holding threadgroup_lock of @leader. The
2282 * caller is also responsible for invoking cgroup_migrate_add_src() and
2283 * cgroup_migrate_prepare_dst() on the targets before invoking this
2284 * function and following up with cgroup_migrate_finish().
2286 * As long as a controller's ->can_attach() doesn't fail, this function is
2287 * guaranteed to succeed. This means that, excluding ->can_attach()
2288 * failure, when migrating multiple targets, the success or failure can be
2289 * decided for all targets by invoking group_migrate_prepare_dst() before
2290 * actually starting migrating.
2292 static int cgroup_migrate(struct cgroup *cgrp, struct task_struct *leader,
2295 struct cgroup_taskset tset = {
2296 .src_csets = LIST_HEAD_INIT(tset.src_csets),
2297 .dst_csets = LIST_HEAD_INIT(tset.dst_csets),
2298 .csets = &tset.src_csets,
2300 struct cgroup_subsys_state *css, *failed_css = NULL;
2301 struct css_set *cset, *tmp_cset;
2302 struct task_struct *task, *tmp_task;
2306 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2307 * already PF_EXITING could be freed from underneath us unless we
2308 * take an rcu_read_lock.
2310 down_write(&css_set_rwsem);
2314 /* @task either already exited or can't exit until the end */
2315 if (task->flags & PF_EXITING)
2318 /* leave @task alone if post_fork() hasn't linked it yet */
2319 if (list_empty(&task->cg_list))
2322 cset = task_css_set(task);
2323 if (!cset->mg_src_cgrp)
2327 * cgroup_taskset_first() must always return the leader.
2328 * Take care to avoid disturbing the ordering.
2330 list_move_tail(&task->cg_list, &cset->mg_tasks);
2331 if (list_empty(&cset->mg_node))
2332 list_add_tail(&cset->mg_node, &tset.src_csets);
2333 if (list_empty(&cset->mg_dst_cset->mg_node))
2334 list_move_tail(&cset->mg_dst_cset->mg_node,
2339 } while_each_thread(leader, task);
2341 up_write(&css_set_rwsem);
2343 /* methods shouldn't be called if no task is actually migrating */
2344 if (list_empty(&tset.src_csets))
2347 /* check that we can legitimately attach to the cgroup */
2348 for_each_e_css(css, i, cgrp) {
2349 if (css->ss->can_attach) {
2350 ret = css->ss->can_attach(css, &tset);
2353 goto out_cancel_attach;
2359 * Now that we're guaranteed success, proceed to move all tasks to
2360 * the new cgroup. There are no failure cases after here, so this
2361 * is the commit point.
2363 down_write(&css_set_rwsem);
2364 list_for_each_entry(cset, &tset.src_csets, mg_node) {
2365 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list)
2366 cgroup_task_migrate(cset->mg_src_cgrp, task,
2369 up_write(&css_set_rwsem);
2372 * Migration is committed, all target tasks are now on dst_csets.
2373 * Nothing is sensitive to fork() after this point. Notify
2374 * controllers that migration is complete.
2376 tset.csets = &tset.dst_csets;
2378 for_each_e_css(css, i, cgrp)
2379 if (css->ss->attach)
2380 css->ss->attach(css, &tset);
2383 goto out_release_tset;
2386 for_each_e_css(css, i, cgrp) {
2387 if (css == failed_css)
2389 if (css->ss->cancel_attach)
2390 css->ss->cancel_attach(css, &tset);
2393 down_write(&css_set_rwsem);
2394 list_splice_init(&tset.dst_csets, &tset.src_csets);
2395 list_for_each_entry_safe(cset, tmp_cset, &tset.src_csets, mg_node) {
2396 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2397 list_del_init(&cset->mg_node);
2399 up_write(&css_set_rwsem);
2404 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2405 * @dst_cgrp: the cgroup to attach to
2406 * @leader: the task or the leader of the threadgroup to be attached
2407 * @threadgroup: attach the whole threadgroup?
2409 * Call holding cgroup_mutex and threadgroup_lock of @leader.
2411 static int cgroup_attach_task(struct cgroup *dst_cgrp,
2412 struct task_struct *leader, bool threadgroup)
2414 LIST_HEAD(preloaded_csets);
2415 struct task_struct *task;
2418 /* look up all src csets */
2419 down_read(&css_set_rwsem);
2423 cgroup_migrate_add_src(task_css_set(task), dst_cgrp,
2427 } while_each_thread(leader, task);
2429 up_read(&css_set_rwsem);
2431 /* prepare dst csets and commit */
2432 ret = cgroup_migrate_prepare_dst(dst_cgrp, &preloaded_csets);
2434 ret = cgroup_migrate(dst_cgrp, leader, threadgroup);
2436 cgroup_migrate_finish(&preloaded_csets);
2440 static int cgroup_procs_write_permission(struct task_struct *task,
2441 struct cgroup *dst_cgrp,
2442 struct kernfs_open_file *of)
2444 const struct cred *cred = current_cred();
2445 const struct cred *tcred = get_task_cred(task);
2449 * even if we're attaching all tasks in the thread group, we only
2450 * need to check permissions on one of them.
2452 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2453 !uid_eq(cred->euid, tcred->uid) &&
2454 !uid_eq(cred->euid, tcred->suid))
2457 if (!ret && cgroup_on_dfl(dst_cgrp)) {
2458 struct super_block *sb = of->file->f_path.dentry->d_sb;
2459 struct cgroup *cgrp;
2460 struct inode *inode;
2462 down_read(&css_set_rwsem);
2463 cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
2464 up_read(&css_set_rwsem);
2466 while (!cgroup_is_descendant(dst_cgrp, cgrp))
2467 cgrp = cgroup_parent(cgrp);
2470 inode = kernfs_get_inode(sb, cgrp->procs_kn);
2472 ret = inode_permission(inode, MAY_WRITE);
2482 * Find the task_struct of the task to attach by vpid and pass it along to the
2483 * function to attach either it or all tasks in its threadgroup. Will lock
2484 * cgroup_mutex and threadgroup.
2486 static ssize_t __cgroup_procs_write(struct kernfs_open_file *of, char *buf,
2487 size_t nbytes, loff_t off, bool threadgroup)
2489 struct task_struct *tsk;
2490 struct cgroup *cgrp;
2494 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2497 cgrp = cgroup_kn_lock_live(of->kn);
2504 tsk = find_task_by_vpid(pid);
2508 goto out_unlock_cgroup;
2515 tsk = tsk->group_leader;
2518 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2519 * trapped in a cpuset, or RT worker may be born in a cgroup
2520 * with no rt_runtime allocated. Just say no.
2522 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2525 goto out_unlock_cgroup;
2528 get_task_struct(tsk);
2531 threadgroup_lock(tsk);
2533 if (!thread_group_leader(tsk)) {
2535 * a race with de_thread from another thread's exec()
2536 * may strip us of our leadership, if this happens,
2537 * there is no choice but to throw this task away and
2538 * try again; this is
2539 * "double-double-toil-and-trouble-check locking".
2541 threadgroup_unlock(tsk);
2542 put_task_struct(tsk);
2543 goto retry_find_task;
2547 ret = cgroup_procs_write_permission(tsk, cgrp, of);
2549 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2551 threadgroup_unlock(tsk);
2553 put_task_struct(tsk);
2555 cgroup_kn_unlock(of->kn);
2556 return ret ?: nbytes;
2560 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2561 * @from: attach to all cgroups of a given task
2562 * @tsk: the task to be attached
2564 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2566 struct cgroup_root *root;
2569 mutex_lock(&cgroup_mutex);
2570 for_each_root(root) {
2571 struct cgroup *from_cgrp;
2573 if (root == &cgrp_dfl_root)
2576 down_read(&css_set_rwsem);
2577 from_cgrp = task_cgroup_from_root(from, root);
2578 up_read(&css_set_rwsem);
2580 retval = cgroup_attach_task(from_cgrp, tsk, false);
2584 mutex_unlock(&cgroup_mutex);
2588 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2590 static ssize_t cgroup_tasks_write(struct kernfs_open_file *of,
2591 char *buf, size_t nbytes, loff_t off)
2593 return __cgroup_procs_write(of, buf, nbytes, off, false);
2596 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
2597 char *buf, size_t nbytes, loff_t off)
2599 return __cgroup_procs_write(of, buf, nbytes, off, true);
2602 static ssize_t cgroup_release_agent_write(struct kernfs_open_file *of,
2603 char *buf, size_t nbytes, loff_t off)
2605 struct cgroup *cgrp;
2607 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
2609 cgrp = cgroup_kn_lock_live(of->kn);
2612 spin_lock(&release_agent_path_lock);
2613 strlcpy(cgrp->root->release_agent_path, strstrip(buf),
2614 sizeof(cgrp->root->release_agent_path));
2615 spin_unlock(&release_agent_path_lock);
2616 cgroup_kn_unlock(of->kn);
2620 static int cgroup_release_agent_show(struct seq_file *seq, void *v)
2622 struct cgroup *cgrp = seq_css(seq)->cgroup;
2624 spin_lock(&release_agent_path_lock);
2625 seq_puts(seq, cgrp->root->release_agent_path);
2626 spin_unlock(&release_agent_path_lock);
2627 seq_putc(seq, '\n');
2631 static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
2633 seq_puts(seq, "0\n");
2637 static void cgroup_print_ss_mask(struct seq_file *seq, unsigned long ss_mask)
2639 struct cgroup_subsys *ss;
2640 bool printed = false;
2643 for_each_subsys_which(ss, ssid, &ss_mask) {
2646 seq_printf(seq, "%s", ss->name);
2650 seq_putc(seq, '\n');
2653 /* show controllers which are currently attached to the default hierarchy */
2654 static int cgroup_root_controllers_show(struct seq_file *seq, void *v)
2656 struct cgroup *cgrp = seq_css(seq)->cgroup;
2658 cgroup_print_ss_mask(seq, cgrp->root->subsys_mask &
2659 ~cgrp_dfl_root_inhibit_ss_mask);
2663 /* show controllers which are enabled from the parent */
2664 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2666 struct cgroup *cgrp = seq_css(seq)->cgroup;
2668 cgroup_print_ss_mask(seq, cgroup_parent(cgrp)->subtree_control);
2672 /* show controllers which are enabled for a given cgroup's children */
2673 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2675 struct cgroup *cgrp = seq_css(seq)->cgroup;
2677 cgroup_print_ss_mask(seq, cgrp->subtree_control);
2682 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2683 * @cgrp: root of the subtree to update csses for
2685 * @cgrp's child_subsys_mask has changed and its subtree's (self excluded)
2686 * css associations need to be updated accordingly. This function looks up
2687 * all css_sets which are attached to the subtree, creates the matching
2688 * updated css_sets and migrates the tasks to the new ones.
2690 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2692 LIST_HEAD(preloaded_csets);
2693 struct cgroup_subsys_state *css;
2694 struct css_set *src_cset;
2697 lockdep_assert_held(&cgroup_mutex);
2699 /* look up all csses currently attached to @cgrp's subtree */
2700 down_read(&css_set_rwsem);
2701 css_for_each_descendant_pre(css, cgroup_css(cgrp, NULL)) {
2702 struct cgrp_cset_link *link;
2704 /* self is not affected by child_subsys_mask change */
2705 if (css->cgroup == cgrp)
2708 list_for_each_entry(link, &css->cgroup->cset_links, cset_link)
2709 cgroup_migrate_add_src(link->cset, cgrp,
2712 up_read(&css_set_rwsem);
2714 /* NULL dst indicates self on default hierarchy */
2715 ret = cgroup_migrate_prepare_dst(NULL, &preloaded_csets);
2719 list_for_each_entry(src_cset, &preloaded_csets, mg_preload_node) {
2720 struct task_struct *last_task = NULL, *task;
2722 /* src_csets precede dst_csets, break on the first dst_cset */
2723 if (!src_cset->mg_src_cgrp)
2727 * All tasks in src_cset need to be migrated to the
2728 * matching dst_cset. Empty it process by process. We
2729 * walk tasks but migrate processes. The leader might even
2730 * belong to a different cset but such src_cset would also
2731 * be among the target src_csets because the default
2732 * hierarchy enforces per-process membership.
2735 down_read(&css_set_rwsem);
2736 task = list_first_entry_or_null(&src_cset->tasks,
2737 struct task_struct, cg_list);
2739 task = task->group_leader;
2740 WARN_ON_ONCE(!task_css_set(task)->mg_src_cgrp);
2741 get_task_struct(task);
2743 up_read(&css_set_rwsem);
2748 /* guard against possible infinite loop */
2749 if (WARN(last_task == task,
2750 "cgroup: update_dfl_csses failed to make progress, aborting in inconsistent state\n"))
2754 threadgroup_lock(task);
2755 /* raced against de_thread() from another thread? */
2756 if (!thread_group_leader(task)) {
2757 threadgroup_unlock(task);
2758 put_task_struct(task);
2762 ret = cgroup_migrate(src_cset->dfl_cgrp, task, true);
2764 threadgroup_unlock(task);
2765 put_task_struct(task);
2767 if (WARN(ret, "cgroup: failed to update controllers for the default hierarchy (%d), further operations may crash or hang\n", ret))
2773 cgroup_migrate_finish(&preloaded_csets);
2777 /* change the enabled child controllers for a cgroup in the default hierarchy */
2778 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
2779 char *buf, size_t nbytes,
2782 unsigned long enable = 0, disable = 0;
2783 unsigned long css_enable, css_disable, old_sc, new_sc, old_ss, new_ss;
2784 struct cgroup *cgrp, *child;
2785 struct cgroup_subsys *ss;
2790 * Parse input - space separated list of subsystem names prefixed
2791 * with either + or -.
2793 buf = strstrip(buf);
2794 while ((tok = strsep(&buf, " "))) {
2795 unsigned long tmp_ss_mask = ~cgrp_dfl_root_inhibit_ss_mask;
2799 for_each_subsys_which(ss, ssid, &tmp_ss_mask) {
2800 if (ss->disabled || strcmp(tok + 1, ss->name))
2804 enable |= 1 << ssid;
2805 disable &= ~(1 << ssid);
2806 } else if (*tok == '-') {
2807 disable |= 1 << ssid;
2808 enable &= ~(1 << ssid);
2814 if (ssid == CGROUP_SUBSYS_COUNT)
2818 cgrp = cgroup_kn_lock_live(of->kn);
2822 for_each_subsys(ss, ssid) {
2823 if (enable & (1 << ssid)) {
2824 if (cgrp->subtree_control & (1 << ssid)) {
2825 enable &= ~(1 << ssid);
2829 /* unavailable or not enabled on the parent? */
2830 if (!(cgrp_dfl_root.subsys_mask & (1 << ssid)) ||
2831 (cgroup_parent(cgrp) &&
2832 !(cgroup_parent(cgrp)->subtree_control & (1 << ssid)))) {
2836 } else if (disable & (1 << ssid)) {
2837 if (!(cgrp->subtree_control & (1 << ssid))) {
2838 disable &= ~(1 << ssid);
2842 /* a child has it enabled? */
2843 cgroup_for_each_live_child(child, cgrp) {
2844 if (child->subtree_control & (1 << ssid)) {
2852 if (!enable && !disable) {
2858 * Except for the root, subtree_control must be zero for a cgroup
2859 * with tasks so that child cgroups don't compete against tasks.
2861 if (enable && cgroup_parent(cgrp) && !list_empty(&cgrp->cset_links)) {
2867 * Update subsys masks and calculate what needs to be done. More
2868 * subsystems than specified may need to be enabled or disabled
2869 * depending on subsystem dependencies.
2871 old_sc = cgrp->subtree_control;
2872 old_ss = cgrp->child_subsys_mask;
2873 new_sc = (old_sc | enable) & ~disable;
2874 new_ss = cgroup_calc_child_subsys_mask(cgrp, new_sc);
2876 css_enable = ~old_ss & new_ss;
2877 css_disable = old_ss & ~new_ss;
2878 enable |= css_enable;
2879 disable |= css_disable;
2882 * Because css offlining is asynchronous, userland might try to
2883 * re-enable the same controller while the previous instance is
2884 * still around. In such cases, wait till it's gone using
2887 for_each_subsys_which(ss, ssid, &css_enable) {
2888 cgroup_for_each_live_child(child, cgrp) {
2891 if (!cgroup_css(child, ss))
2895 prepare_to_wait(&child->offline_waitq, &wait,
2896 TASK_UNINTERRUPTIBLE);
2897 cgroup_kn_unlock(of->kn);
2899 finish_wait(&child->offline_waitq, &wait);
2902 return restart_syscall();
2906 cgrp->subtree_control = new_sc;
2907 cgrp->child_subsys_mask = new_ss;
2910 * Create new csses or make the existing ones visible. A css is
2911 * created invisible if it's being implicitly enabled through
2912 * dependency. An invisible css is made visible when the userland
2913 * explicitly enables it.
2915 for_each_subsys(ss, ssid) {
2916 if (!(enable & (1 << ssid)))
2919 cgroup_for_each_live_child(child, cgrp) {
2920 if (css_enable & (1 << ssid))
2921 ret = create_css(child, ss,
2922 cgrp->subtree_control & (1 << ssid));
2924 ret = cgroup_populate_dir(child, 1 << ssid);
2931 * At this point, cgroup_e_css() results reflect the new csses
2932 * making the following cgroup_update_dfl_csses() properly update
2933 * css associations of all tasks in the subtree.
2935 ret = cgroup_update_dfl_csses(cgrp);
2940 * All tasks are migrated out of disabled csses. Kill or hide
2941 * them. A css is hidden when the userland requests it to be
2942 * disabled while other subsystems are still depending on it. The
2943 * css must not actively control resources and be in the vanilla
2944 * state if it's made visible again later. Controllers which may
2945 * be depended upon should provide ->css_reset() for this purpose.
2947 for_each_subsys(ss, ssid) {
2948 if (!(disable & (1 << ssid)))
2951 cgroup_for_each_live_child(child, cgrp) {
2952 struct cgroup_subsys_state *css = cgroup_css(child, ss);
2954 if (css_disable & (1 << ssid)) {
2957 cgroup_clear_dir(child, 1 << ssid);
2965 * The effective csses of all the descendants (excluding @cgrp) may
2966 * have changed. Subsystems can optionally subscribe to this event
2967 * by implementing ->css_e_css_changed() which is invoked if any of
2968 * the effective csses seen from the css's cgroup may have changed.
2970 for_each_subsys(ss, ssid) {
2971 struct cgroup_subsys_state *this_css = cgroup_css(cgrp, ss);
2972 struct cgroup_subsys_state *css;
2974 if (!ss->css_e_css_changed || !this_css)
2977 css_for_each_descendant_pre(css, this_css)
2978 if (css != this_css)
2979 ss->css_e_css_changed(css);
2982 kernfs_activate(cgrp->kn);
2985 cgroup_kn_unlock(of->kn);
2986 return ret ?: nbytes;
2989 cgrp->subtree_control = old_sc;
2990 cgrp->child_subsys_mask = old_ss;
2992 for_each_subsys(ss, ssid) {
2993 if (!(enable & (1 << ssid)))
2996 cgroup_for_each_live_child(child, cgrp) {
2997 struct cgroup_subsys_state *css = cgroup_css(child, ss);
3002 if (css_enable & (1 << ssid))
3005 cgroup_clear_dir(child, 1 << ssid);
3011 static int cgroup_populated_show(struct seq_file *seq, void *v)
3013 seq_printf(seq, "%d\n", (bool)seq_css(seq)->cgroup->populated_cnt);
3017 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
3018 size_t nbytes, loff_t off)
3020 struct cgroup *cgrp = of->kn->parent->priv;
3021 struct cftype *cft = of->kn->priv;
3022 struct cgroup_subsys_state *css;
3026 return cft->write(of, buf, nbytes, off);
3029 * kernfs guarantees that a file isn't deleted with operations in
3030 * flight, which means that the matching css is and stays alive and
3031 * doesn't need to be pinned. The RCU locking is not necessary
3032 * either. It's just for the convenience of using cgroup_css().
3035 css = cgroup_css(cgrp, cft->ss);
3038 if (cft->write_u64) {
3039 unsigned long long v;
3040 ret = kstrtoull(buf, 0, &v);
3042 ret = cft->write_u64(css, cft, v);
3043 } else if (cft->write_s64) {
3045 ret = kstrtoll(buf, 0, &v);
3047 ret = cft->write_s64(css, cft, v);
3052 return ret ?: nbytes;
3055 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
3057 return seq_cft(seq)->seq_start(seq, ppos);
3060 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
3062 return seq_cft(seq)->seq_next(seq, v, ppos);
3065 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
3067 seq_cft(seq)->seq_stop(seq, v);
3070 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
3072 struct cftype *cft = seq_cft(m);
3073 struct cgroup_subsys_state *css = seq_css(m);
3076 return cft->seq_show(m, arg);
3079 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
3080 else if (cft->read_s64)
3081 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
3087 static struct kernfs_ops cgroup_kf_single_ops = {
3088 .atomic_write_len = PAGE_SIZE,
3089 .write = cgroup_file_write,
3090 .seq_show = cgroup_seqfile_show,
3093 static struct kernfs_ops cgroup_kf_ops = {
3094 .atomic_write_len = PAGE_SIZE,
3095 .write = cgroup_file_write,
3096 .seq_start = cgroup_seqfile_start,
3097 .seq_next = cgroup_seqfile_next,
3098 .seq_stop = cgroup_seqfile_stop,
3099 .seq_show = cgroup_seqfile_show,
3103 * cgroup_rename - Only allow simple rename of directories in place.
3105 static int cgroup_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
3106 const char *new_name_str)
3108 struct cgroup *cgrp = kn->priv;
3111 if (kernfs_type(kn) != KERNFS_DIR)
3113 if (kn->parent != new_parent)
3117 * This isn't a proper migration and its usefulness is very
3118 * limited. Disallow on the default hierarchy.
3120 if (cgroup_on_dfl(cgrp))
3124 * We're gonna grab cgroup_mutex which nests outside kernfs
3125 * active_ref. kernfs_rename() doesn't require active_ref
3126 * protection. Break them before grabbing cgroup_mutex.
3128 kernfs_break_active_protection(new_parent);
3129 kernfs_break_active_protection(kn);
3131 mutex_lock(&cgroup_mutex);
3133 ret = kernfs_rename(kn, new_parent, new_name_str);
3135 mutex_unlock(&cgroup_mutex);
3137 kernfs_unbreak_active_protection(kn);
3138 kernfs_unbreak_active_protection(new_parent);
3142 /* set uid and gid of cgroup dirs and files to that of the creator */
3143 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
3145 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
3146 .ia_uid = current_fsuid(),
3147 .ia_gid = current_fsgid(), };
3149 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
3150 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
3153 return kernfs_setattr(kn, &iattr);
3156 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
3158 char name[CGROUP_FILE_NAME_MAX];
3159 struct kernfs_node *kn;
3160 struct lock_class_key *key = NULL;
3163 #ifdef CONFIG_DEBUG_LOCK_ALLOC
3164 key = &cft->lockdep_key;
3166 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
3167 cgroup_file_mode(cft), 0, cft->kf_ops, cft,
3172 ret = cgroup_kn_set_ugid(kn);
3178 if (cft->write == cgroup_procs_write)
3179 cgrp->procs_kn = kn;
3180 else if (cft->seq_show == cgroup_populated_show)
3181 cgrp->populated_kn = kn;
3186 * cgroup_addrm_files - add or remove files to a cgroup directory
3187 * @cgrp: the target cgroup
3188 * @cfts: array of cftypes to be added
3189 * @is_add: whether to add or remove
3191 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
3192 * For removals, this function never fails. If addition fails, this
3193 * function doesn't remove files already added. The caller is responsible
3196 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
3202 lockdep_assert_held(&cgroup_mutex);
3204 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3205 /* does cft->flags tell us to skip this file on @cgrp? */
3206 if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
3208 if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
3210 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
3212 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
3216 ret = cgroup_add_file(cgrp, cft);
3218 pr_warn("%s: failed to add %s, err=%d\n",
3219 __func__, cft->name, ret);
3223 cgroup_rm_file(cgrp, cft);
3229 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
3232 struct cgroup_subsys *ss = cfts[0].ss;
3233 struct cgroup *root = &ss->root->cgrp;
3234 struct cgroup_subsys_state *css;
3237 lockdep_assert_held(&cgroup_mutex);
3239 /* add/rm files for all cgroups created before */
3240 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
3241 struct cgroup *cgrp = css->cgroup;
3243 if (cgroup_is_dead(cgrp))
3246 ret = cgroup_addrm_files(cgrp, cfts, is_add);
3252 kernfs_activate(root->kn);
3256 static void cgroup_exit_cftypes(struct cftype *cfts)
3260 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3261 /* free copy for custom atomic_write_len, see init_cftypes() */
3262 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
3267 /* revert flags set by cgroup core while adding @cfts */
3268 cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL);
3272 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3276 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3277 struct kernfs_ops *kf_ops;
3279 WARN_ON(cft->ss || cft->kf_ops);
3282 kf_ops = &cgroup_kf_ops;
3284 kf_ops = &cgroup_kf_single_ops;
3287 * Ugh... if @cft wants a custom max_write_len, we need to
3288 * make a copy of kf_ops to set its atomic_write_len.
3290 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
3291 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
3293 cgroup_exit_cftypes(cfts);
3296 kf_ops->atomic_write_len = cft->max_write_len;
3299 cft->kf_ops = kf_ops;
3306 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
3308 lockdep_assert_held(&cgroup_mutex);
3310 if (!cfts || !cfts[0].ss)
3313 list_del(&cfts->node);
3314 cgroup_apply_cftypes(cfts, false);
3315 cgroup_exit_cftypes(cfts);
3320 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
3321 * @cfts: zero-length name terminated array of cftypes
3323 * Unregister @cfts. Files described by @cfts are removed from all
3324 * existing cgroups and all future cgroups won't have them either. This
3325 * function can be called anytime whether @cfts' subsys is attached or not.
3327 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
3330 int cgroup_rm_cftypes(struct cftype *cfts)
3334 mutex_lock(&cgroup_mutex);
3335 ret = cgroup_rm_cftypes_locked(cfts);
3336 mutex_unlock(&cgroup_mutex);
3341 * cgroup_add_cftypes - add an array of cftypes to a subsystem
3342 * @ss: target cgroup subsystem
3343 * @cfts: zero-length name terminated array of cftypes
3345 * Register @cfts to @ss. Files described by @cfts are created for all
3346 * existing cgroups to which @ss is attached and all future cgroups will
3347 * have them too. This function can be called anytime whether @ss is
3350 * Returns 0 on successful registration, -errno on failure. Note that this
3351 * function currently returns 0 as long as @cfts registration is successful
3352 * even if some file creation attempts on existing cgroups fail.
3354 static int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3361 if (!cfts || cfts[0].name[0] == '\0')
3364 ret = cgroup_init_cftypes(ss, cfts);
3368 mutex_lock(&cgroup_mutex);
3370 list_add_tail(&cfts->node, &ss->cfts);
3371 ret = cgroup_apply_cftypes(cfts, true);
3373 cgroup_rm_cftypes_locked(cfts);
3375 mutex_unlock(&cgroup_mutex);
3380 * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
3381 * @ss: target cgroup subsystem
3382 * @cfts: zero-length name terminated array of cftypes
3384 * Similar to cgroup_add_cftypes() but the added files are only used for
3385 * the default hierarchy.
3387 int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3391 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3392 cft->flags |= __CFTYPE_ONLY_ON_DFL;
3393 return cgroup_add_cftypes(ss, cfts);
3397 * cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies
3398 * @ss: target cgroup subsystem
3399 * @cfts: zero-length name terminated array of cftypes
3401 * Similar to cgroup_add_cftypes() but the added files are only used for
3402 * the legacy hierarchies.
3404 int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3409 * If legacy_flies_on_dfl, we want to show the legacy files on the
3410 * dfl hierarchy but iff the target subsystem hasn't been updated
3411 * for the dfl hierarchy yet.
3413 if (!cgroup_legacy_files_on_dfl ||
3414 ss->dfl_cftypes != ss->legacy_cftypes) {
3415 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3416 cft->flags |= __CFTYPE_NOT_ON_DFL;
3419 return cgroup_add_cftypes(ss, cfts);
3423 * cgroup_task_count - count the number of tasks in a cgroup.
3424 * @cgrp: the cgroup in question
3426 * Return the number of tasks in the cgroup.
3428 static int cgroup_task_count(const struct cgroup *cgrp)
3431 struct cgrp_cset_link *link;
3433 down_read(&css_set_rwsem);
3434 list_for_each_entry(link, &cgrp->cset_links, cset_link)
3435 count += atomic_read(&link->cset->refcount);
3436 up_read(&css_set_rwsem);
3441 * css_next_child - find the next child of a given css
3442 * @pos: the current position (%NULL to initiate traversal)
3443 * @parent: css whose children to walk
3445 * This function returns the next child of @parent and should be called
3446 * under either cgroup_mutex or RCU read lock. The only requirement is
3447 * that @parent and @pos are accessible. The next sibling is guaranteed to
3448 * be returned regardless of their states.
3450 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3451 * css which finished ->css_online() is guaranteed to be visible in the
3452 * future iterations and will stay visible until the last reference is put.
3453 * A css which hasn't finished ->css_online() or already finished
3454 * ->css_offline() may show up during traversal. It's each subsystem's
3455 * responsibility to synchronize against on/offlining.
3457 struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
3458 struct cgroup_subsys_state *parent)
3460 struct cgroup_subsys_state *next;
3462 cgroup_assert_mutex_or_rcu_locked();
3465 * @pos could already have been unlinked from the sibling list.
3466 * Once a cgroup is removed, its ->sibling.next is no longer
3467 * updated when its next sibling changes. CSS_RELEASED is set when
3468 * @pos is taken off list, at which time its next pointer is valid,
3469 * and, as releases are serialized, the one pointed to by the next
3470 * pointer is guaranteed to not have started release yet. This
3471 * implies that if we observe !CSS_RELEASED on @pos in this RCU
3472 * critical section, the one pointed to by its next pointer is
3473 * guaranteed to not have finished its RCU grace period even if we
3474 * have dropped rcu_read_lock() inbetween iterations.
3476 * If @pos has CSS_RELEASED set, its next pointer can't be
3477 * dereferenced; however, as each css is given a monotonically
3478 * increasing unique serial number and always appended to the
3479 * sibling list, the next one can be found by walking the parent's
3480 * children until the first css with higher serial number than
3481 * @pos's. While this path can be slower, it happens iff iteration
3482 * races against release and the race window is very small.
3485 next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
3486 } else if (likely(!(pos->flags & CSS_RELEASED))) {
3487 next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
3489 list_for_each_entry_rcu(next, &parent->children, sibling)
3490 if (next->serial_nr > pos->serial_nr)
3495 * @next, if not pointing to the head, can be dereferenced and is
3498 if (&next->sibling != &parent->children)
3504 * css_next_descendant_pre - find the next descendant for pre-order walk
3505 * @pos: the current position (%NULL to initiate traversal)
3506 * @root: css whose descendants to walk
3508 * To be used by css_for_each_descendant_pre(). Find the next descendant
3509 * to visit for pre-order traversal of @root's descendants. @root is
3510 * included in the iteration and the first node to be visited.
3512 * While this function requires cgroup_mutex or RCU read locking, it
3513 * doesn't require the whole traversal to be contained in a single critical
3514 * section. This function will return the correct next descendant as long
3515 * as both @pos and @root are accessible and @pos is a descendant of @root.
3517 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3518 * css which finished ->css_online() is guaranteed to be visible in the
3519 * future iterations and will stay visible until the last reference is put.
3520 * A css which hasn't finished ->css_online() or already finished
3521 * ->css_offline() may show up during traversal. It's each subsystem's
3522 * responsibility to synchronize against on/offlining.
3524 struct cgroup_subsys_state *
3525 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3526 struct cgroup_subsys_state *root)
3528 struct cgroup_subsys_state *next;
3530 cgroup_assert_mutex_or_rcu_locked();
3532 /* if first iteration, visit @root */
3536 /* visit the first child if exists */
3537 next = css_next_child(NULL, pos);
3541 /* no child, visit my or the closest ancestor's next sibling */
3542 while (pos != root) {
3543 next = css_next_child(pos, pos->parent);
3553 * css_rightmost_descendant - return the rightmost descendant of a css
3554 * @pos: css of interest
3556 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3557 * is returned. This can be used during pre-order traversal to skip
3560 * While this function requires cgroup_mutex or RCU read locking, it
3561 * doesn't require the whole traversal to be contained in a single critical
3562 * section. This function will return the correct rightmost descendant as
3563 * long as @pos is accessible.
3565 struct cgroup_subsys_state *
3566 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3568 struct cgroup_subsys_state *last, *tmp;
3570 cgroup_assert_mutex_or_rcu_locked();
3574 /* ->prev isn't RCU safe, walk ->next till the end */
3576 css_for_each_child(tmp, last)
3583 static struct cgroup_subsys_state *
3584 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3586 struct cgroup_subsys_state *last;
3590 pos = css_next_child(NULL, pos);
3597 * css_next_descendant_post - find the next descendant for post-order walk
3598 * @pos: the current position (%NULL to initiate traversal)
3599 * @root: css whose descendants to walk
3601 * To be used by css_for_each_descendant_post(). Find the next descendant
3602 * to visit for post-order traversal of @root's descendants. @root is
3603 * included in the iteration and the last node to be visited.
3605 * While this function requires cgroup_mutex or RCU read locking, it
3606 * doesn't require the whole traversal to be contained in a single critical
3607 * section. This function will return the correct next descendant as long
3608 * as both @pos and @cgroup are accessible and @pos is a descendant of
3611 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3612 * css which finished ->css_online() is guaranteed to be visible in the
3613 * future iterations and will stay visible until the last reference is put.
3614 * A css which hasn't finished ->css_online() or already finished
3615 * ->css_offline() may show up during traversal. It's each subsystem's
3616 * responsibility to synchronize against on/offlining.
3618 struct cgroup_subsys_state *
3619 css_next_descendant_post(struct cgroup_subsys_state *pos,
3620 struct cgroup_subsys_state *root)
3622 struct cgroup_subsys_state *next;
3624 cgroup_assert_mutex_or_rcu_locked();
3626 /* if first iteration, visit leftmost descendant which may be @root */
3628 return css_leftmost_descendant(root);
3630 /* if we visited @root, we're done */
3634 /* if there's an unvisited sibling, visit its leftmost descendant */
3635 next = css_next_child(pos, pos->parent);
3637 return css_leftmost_descendant(next);
3639 /* no sibling left, visit parent */
3644 * css_has_online_children - does a css have online children
3645 * @css: the target css
3647 * Returns %true if @css has any online children; otherwise, %false. This
3648 * function can be called from any context but the caller is responsible
3649 * for synchronizing against on/offlining as necessary.
3651 bool css_has_online_children(struct cgroup_subsys_state *css)
3653 struct cgroup_subsys_state *child;
3657 css_for_each_child(child, css) {
3658 if (child->flags & CSS_ONLINE) {
3668 * css_advance_task_iter - advance a task itererator to the next css_set
3669 * @it: the iterator to advance
3671 * Advance @it to the next css_set to walk.
3673 static void css_advance_task_iter(struct css_task_iter *it)
3675 struct list_head *l = it->cset_pos;
3676 struct cgrp_cset_link *link;
3677 struct css_set *cset;
3679 /* Advance to the next non-empty css_set */
3682 if (l == it->cset_head) {
3683 it->cset_pos = NULL;
3688 cset = container_of(l, struct css_set,
3689 e_cset_node[it->ss->id]);
3691 link = list_entry(l, struct cgrp_cset_link, cset_link);
3694 } while (list_empty(&cset->tasks) && list_empty(&cset->mg_tasks));
3698 if (!list_empty(&cset->tasks))
3699 it->task_pos = cset->tasks.next;
3701 it->task_pos = cset->mg_tasks.next;
3703 it->tasks_head = &cset->tasks;
3704 it->mg_tasks_head = &cset->mg_tasks;
3708 * css_task_iter_start - initiate task iteration
3709 * @css: the css to walk tasks of
3710 * @it: the task iterator to use
3712 * Initiate iteration through the tasks of @css. The caller can call
3713 * css_task_iter_next() to walk through the tasks until the function
3714 * returns NULL. On completion of iteration, css_task_iter_end() must be
3717 * Note that this function acquires a lock which is released when the
3718 * iteration finishes. The caller can't sleep while iteration is in
3721 void css_task_iter_start(struct cgroup_subsys_state *css,
3722 struct css_task_iter *it)
3723 __acquires(css_set_rwsem)
3725 /* no one should try to iterate before mounting cgroups */
3726 WARN_ON_ONCE(!use_task_css_set_links);
3728 down_read(&css_set_rwsem);
3733 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
3735 it->cset_pos = &css->cgroup->cset_links;
3737 it->cset_head = it->cset_pos;
3739 css_advance_task_iter(it);
3743 * css_task_iter_next - return the next task for the iterator
3744 * @it: the task iterator being iterated
3746 * The "next" function for task iteration. @it should have been
3747 * initialized via css_task_iter_start(). Returns NULL when the iteration
3750 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3752 struct task_struct *res;
3753 struct list_head *l = it->task_pos;
3755 /* If the iterator cg is NULL, we have no tasks */
3758 res = list_entry(l, struct task_struct, cg_list);
3761 * Advance iterator to find next entry. cset->tasks is consumed
3762 * first and then ->mg_tasks. After ->mg_tasks, we move onto the
3767 if (l == it->tasks_head)
3768 l = it->mg_tasks_head->next;
3770 if (l == it->mg_tasks_head)
3771 css_advance_task_iter(it);
3779 * css_task_iter_end - finish task iteration
3780 * @it: the task iterator to finish
3782 * Finish task iteration started by css_task_iter_start().
3784 void css_task_iter_end(struct css_task_iter *it)
3785 __releases(css_set_rwsem)
3787 up_read(&css_set_rwsem);
3791 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3792 * @to: cgroup to which the tasks will be moved
3793 * @from: cgroup in which the tasks currently reside
3795 * Locking rules between cgroup_post_fork() and the migration path
3796 * guarantee that, if a task is forking while being migrated, the new child
3797 * is guaranteed to be either visible in the source cgroup after the
3798 * parent's migration is complete or put into the target cgroup. No task
3799 * can slip out of migration through forking.
3801 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3803 LIST_HEAD(preloaded_csets);
3804 struct cgrp_cset_link *link;
3805 struct css_task_iter it;
3806 struct task_struct *task;
3809 mutex_lock(&cgroup_mutex);
3811 /* all tasks in @from are being moved, all csets are source */
3812 down_read(&css_set_rwsem);
3813 list_for_each_entry(link, &from->cset_links, cset_link)
3814 cgroup_migrate_add_src(link->cset, to, &preloaded_csets);
3815 up_read(&css_set_rwsem);
3817 ret = cgroup_migrate_prepare_dst(to, &preloaded_csets);
3822 * Migrate tasks one-by-one until @form is empty. This fails iff
3823 * ->can_attach() fails.
3826 css_task_iter_start(&from->self, &it);
3827 task = css_task_iter_next(&it);
3829 get_task_struct(task);
3830 css_task_iter_end(&it);
3833 ret = cgroup_migrate(to, task, false);
3834 put_task_struct(task);
3836 } while (task && !ret);
3838 cgroup_migrate_finish(&preloaded_csets);
3839 mutex_unlock(&cgroup_mutex);
3844 * Stuff for reading the 'tasks'/'procs' files.
3846 * Reading this file can return large amounts of data if a cgroup has
3847 * *lots* of attached tasks. So it may need several calls to read(),
3848 * but we cannot guarantee that the information we produce is correct
3849 * unless we produce it entirely atomically.
3853 /* which pidlist file are we talking about? */
3854 enum cgroup_filetype {
3860 * A pidlist is a list of pids that virtually represents the contents of one
3861 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3862 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3865 struct cgroup_pidlist {
3867 * used to find which pidlist is wanted. doesn't change as long as
3868 * this particular list stays in the list.
3870 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3873 /* how many elements the above list has */
3875 /* each of these stored in a list by its cgroup */
3876 struct list_head links;
3877 /* pointer to the cgroup we belong to, for list removal purposes */
3878 struct cgroup *owner;
3879 /* for delayed destruction */
3880 struct delayed_work destroy_dwork;
3884 * The following two functions "fix" the issue where there are more pids
3885 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3886 * TODO: replace with a kernel-wide solution to this problem
3888 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3889 static void *pidlist_allocate(int count)
3891 if (PIDLIST_TOO_LARGE(count))
3892 return vmalloc(count * sizeof(pid_t));
3894 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3897 static void pidlist_free(void *p)
3903 * Used to destroy all pidlists lingering waiting for destroy timer. None
3904 * should be left afterwards.
3906 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
3908 struct cgroup_pidlist *l, *tmp_l;
3910 mutex_lock(&cgrp->pidlist_mutex);
3911 list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
3912 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
3913 mutex_unlock(&cgrp->pidlist_mutex);
3915 flush_workqueue(cgroup_pidlist_destroy_wq);
3916 BUG_ON(!list_empty(&cgrp->pidlists));
3919 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
3921 struct delayed_work *dwork = to_delayed_work(work);
3922 struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
3924 struct cgroup_pidlist *tofree = NULL;
3926 mutex_lock(&l->owner->pidlist_mutex);
3929 * Destroy iff we didn't get queued again. The state won't change
3930 * as destroy_dwork can only be queued while locked.
3932 if (!delayed_work_pending(dwork)) {
3933 list_del(&l->links);
3934 pidlist_free(l->list);
3935 put_pid_ns(l->key.ns);
3939 mutex_unlock(&l->owner->pidlist_mutex);
3944 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3945 * Returns the number of unique elements.
3947 static int pidlist_uniq(pid_t *list, int length)
3952 * we presume the 0th element is unique, so i starts at 1. trivial
3953 * edge cases first; no work needs to be done for either
3955 if (length == 0 || length == 1)
3957 /* src and dest walk down the list; dest counts unique elements */
3958 for (src = 1; src < length; src++) {
3959 /* find next unique element */
3960 while (list[src] == list[src-1]) {
3965 /* dest always points to where the next unique element goes */
3966 list[dest] = list[src];
3974 * The two pid files - task and cgroup.procs - guaranteed that the result
3975 * is sorted, which forced this whole pidlist fiasco. As pid order is
3976 * different per namespace, each namespace needs differently sorted list,
3977 * making it impossible to use, for example, single rbtree of member tasks
3978 * sorted by task pointer. As pidlists can be fairly large, allocating one
3979 * per open file is dangerous, so cgroup had to implement shared pool of
3980 * pidlists keyed by cgroup and namespace.
3982 * All this extra complexity was caused by the original implementation
3983 * committing to an entirely unnecessary property. In the long term, we
3984 * want to do away with it. Explicitly scramble sort order if on the
3985 * default hierarchy so that no such expectation exists in the new
3988 * Scrambling is done by swapping every two consecutive bits, which is
3989 * non-identity one-to-one mapping which disturbs sort order sufficiently.
3991 static pid_t pid_fry(pid_t pid)
3993 unsigned a = pid & 0x55555555;
3994 unsigned b = pid & 0xAAAAAAAA;
3996 return (a << 1) | (b >> 1);
3999 static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
4001 if (cgroup_on_dfl(cgrp))
4002 return pid_fry(pid);
4007 static int cmppid(const void *a, const void *b)
4009 return *(pid_t *)a - *(pid_t *)b;
4012 static int fried_cmppid(const void *a, const void *b)
4014 return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
4017 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
4018 enum cgroup_filetype type)
4020 struct cgroup_pidlist *l;
4021 /* don't need task_nsproxy() if we're looking at ourself */
4022 struct pid_namespace *ns = task_active_pid_ns(current);
4024 lockdep_assert_held(&cgrp->pidlist_mutex);
4026 list_for_each_entry(l, &cgrp->pidlists, links)
4027 if (l->key.type == type && l->key.ns == ns)
4033 * find the appropriate pidlist for our purpose (given procs vs tasks)
4034 * returns with the lock on that pidlist already held, and takes care
4035 * of the use count, or returns NULL with no locks held if we're out of
4038 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
4039 enum cgroup_filetype type)
4041 struct cgroup_pidlist *l;
4043 lockdep_assert_held(&cgrp->pidlist_mutex);
4045 l = cgroup_pidlist_find(cgrp, type);
4049 /* entry not found; create a new one */
4050 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
4054 INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
4056 /* don't need task_nsproxy() if we're looking at ourself */
4057 l->key.ns = get_pid_ns(task_active_pid_ns(current));
4059 list_add(&l->links, &cgrp->pidlists);
4064 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
4066 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
4067 struct cgroup_pidlist **lp)
4071 int pid, n = 0; /* used for populating the array */
4072 struct css_task_iter it;
4073 struct task_struct *tsk;
4074 struct cgroup_pidlist *l;
4076 lockdep_assert_held(&cgrp->pidlist_mutex);
4079 * If cgroup gets more users after we read count, we won't have
4080 * enough space - tough. This race is indistinguishable to the
4081 * caller from the case that the additional cgroup users didn't
4082 * show up until sometime later on.
4084 length = cgroup_task_count(cgrp);
4085 array = pidlist_allocate(length);
4088 /* now, populate the array */
4089 css_task_iter_start(&cgrp->self, &it);
4090 while ((tsk = css_task_iter_next(&it))) {
4091 if (unlikely(n == length))
4093 /* get tgid or pid for procs or tasks file respectively */
4094 if (type == CGROUP_FILE_PROCS)
4095 pid = task_tgid_vnr(tsk);
4097 pid = task_pid_vnr(tsk);
4098 if (pid > 0) /* make sure to only use valid results */
4101 css_task_iter_end(&it);
4103 /* now sort & (if procs) strip out duplicates */
4104 if (cgroup_on_dfl(cgrp))
4105 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
4107 sort(array, length, sizeof(pid_t), cmppid, NULL);
4108 if (type == CGROUP_FILE_PROCS)
4109 length = pidlist_uniq(array, length);
4111 l = cgroup_pidlist_find_create(cgrp, type);
4113 pidlist_free(array);
4117 /* store array, freeing old if necessary */
4118 pidlist_free(l->list);
4126 * cgroupstats_build - build and fill cgroupstats
4127 * @stats: cgroupstats to fill information into
4128 * @dentry: A dentry entry belonging to the cgroup for which stats have
4131 * Build and fill cgroupstats so that taskstats can export it to user
4134 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
4136 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
4137 struct cgroup *cgrp;
4138 struct css_task_iter it;
4139 struct task_struct *tsk;
4141 /* it should be kernfs_node belonging to cgroupfs and is a directory */
4142 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
4143 kernfs_type(kn) != KERNFS_DIR)
4146 mutex_lock(&cgroup_mutex);
4149 * We aren't being called from kernfs and there's no guarantee on
4150 * @kn->priv's validity. For this and css_tryget_online_from_dir(),
4151 * @kn->priv is RCU safe. Let's do the RCU dancing.
4154 cgrp = rcu_dereference(kn->priv);
4155 if (!cgrp || cgroup_is_dead(cgrp)) {
4157 mutex_unlock(&cgroup_mutex);
4162 css_task_iter_start(&cgrp->self, &it);
4163 while ((tsk = css_task_iter_next(&it))) {
4164 switch (tsk->state) {
4166 stats->nr_running++;
4168 case TASK_INTERRUPTIBLE:
4169 stats->nr_sleeping++;
4171 case TASK_UNINTERRUPTIBLE:
4172 stats->nr_uninterruptible++;
4175 stats->nr_stopped++;
4178 if (delayacct_is_task_waiting_on_io(tsk))
4179 stats->nr_io_wait++;
4183 css_task_iter_end(&it);
4185 mutex_unlock(&cgroup_mutex);
4191 * seq_file methods for the tasks/procs files. The seq_file position is the
4192 * next pid to display; the seq_file iterator is a pointer to the pid
4193 * in the cgroup->l->list array.
4196 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
4199 * Initially we receive a position value that corresponds to
4200 * one more than the last pid shown (or 0 on the first call or
4201 * after a seek to the start). Use a binary-search to find the
4202 * next pid to display, if any
4204 struct kernfs_open_file *of = s->private;
4205 struct cgroup *cgrp = seq_css(s)->cgroup;
4206 struct cgroup_pidlist *l;
4207 enum cgroup_filetype type = seq_cft(s)->private;
4208 int index = 0, pid = *pos;
4211 mutex_lock(&cgrp->pidlist_mutex);
4214 * !NULL @of->priv indicates that this isn't the first start()
4215 * after open. If the matching pidlist is around, we can use that.
4216 * Look for it. Note that @of->priv can't be used directly. It
4217 * could already have been destroyed.
4220 of->priv = cgroup_pidlist_find(cgrp, type);
4223 * Either this is the first start() after open or the matching
4224 * pidlist has been destroyed inbetween. Create a new one.
4227 ret = pidlist_array_load(cgrp, type,
4228 (struct cgroup_pidlist **)&of->priv);
4230 return ERR_PTR(ret);
4235 int end = l->length;
4237 while (index < end) {
4238 int mid = (index + end) / 2;
4239 if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
4242 } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
4248 /* If we're off the end of the array, we're done */
4249 if (index >= l->length)
4251 /* Update the abstract position to be the actual pid that we found */
4252 iter = l->list + index;
4253 *pos = cgroup_pid_fry(cgrp, *iter);
4257 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
4259 struct kernfs_open_file *of = s->private;
4260 struct cgroup_pidlist *l = of->priv;
4263 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
4264 CGROUP_PIDLIST_DESTROY_DELAY);
4265 mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
4268 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
4270 struct kernfs_open_file *of = s->private;
4271 struct cgroup_pidlist *l = of->priv;
4273 pid_t *end = l->list + l->length;
4275 * Advance to the next pid in the array. If this goes off the
4282 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
4287 static int cgroup_pidlist_show(struct seq_file *s, void *v)
4289 seq_printf(s, "%d\n", *(int *)v);
4294 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
4297 return notify_on_release(css->cgroup);
4300 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
4301 struct cftype *cft, u64 val)
4304 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
4306 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
4310 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
4313 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4316 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
4317 struct cftype *cft, u64 val)
4320 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4322 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4326 /* cgroup core interface files for the default hierarchy */
4327 static struct cftype cgroup_dfl_base_files[] = {
4329 .name = "cgroup.procs",
4330 .seq_start = cgroup_pidlist_start,
4331 .seq_next = cgroup_pidlist_next,
4332 .seq_stop = cgroup_pidlist_stop,
4333 .seq_show = cgroup_pidlist_show,
4334 .private = CGROUP_FILE_PROCS,
4335 .write = cgroup_procs_write,
4336 .mode = S_IRUGO | S_IWUSR,
4339 .name = "cgroup.controllers",
4340 .flags = CFTYPE_ONLY_ON_ROOT,
4341 .seq_show = cgroup_root_controllers_show,
4344 .name = "cgroup.controllers",
4345 .flags = CFTYPE_NOT_ON_ROOT,
4346 .seq_show = cgroup_controllers_show,
4349 .name = "cgroup.subtree_control",
4350 .seq_show = cgroup_subtree_control_show,
4351 .write = cgroup_subtree_control_write,
4354 .name = "cgroup.populated",
4355 .flags = CFTYPE_NOT_ON_ROOT,
4356 .seq_show = cgroup_populated_show,
4361 /* cgroup core interface files for the legacy hierarchies */
4362 static struct cftype cgroup_legacy_base_files[] = {
4364 .name = "cgroup.procs",
4365 .seq_start = cgroup_pidlist_start,
4366 .seq_next = cgroup_pidlist_next,
4367 .seq_stop = cgroup_pidlist_stop,
4368 .seq_show = cgroup_pidlist_show,
4369 .private = CGROUP_FILE_PROCS,
4370 .write = cgroup_procs_write,
4371 .mode = S_IRUGO | S_IWUSR,
4374 .name = "cgroup.clone_children",
4375 .read_u64 = cgroup_clone_children_read,
4376 .write_u64 = cgroup_clone_children_write,
4379 .name = "cgroup.sane_behavior",
4380 .flags = CFTYPE_ONLY_ON_ROOT,
4381 .seq_show = cgroup_sane_behavior_show,
4385 .seq_start = cgroup_pidlist_start,
4386 .seq_next = cgroup_pidlist_next,
4387 .seq_stop = cgroup_pidlist_stop,
4388 .seq_show = cgroup_pidlist_show,
4389 .private = CGROUP_FILE_TASKS,
4390 .write = cgroup_tasks_write,
4391 .mode = S_IRUGO | S_IWUSR,
4394 .name = "notify_on_release",
4395 .read_u64 = cgroup_read_notify_on_release,
4396 .write_u64 = cgroup_write_notify_on_release,
4399 .name = "release_agent",
4400 .flags = CFTYPE_ONLY_ON_ROOT,
4401 .seq_show = cgroup_release_agent_show,
4402 .write = cgroup_release_agent_write,
4403 .max_write_len = PATH_MAX - 1,
4409 * cgroup_populate_dir - create subsys files in a cgroup directory
4410 * @cgrp: target cgroup
4411 * @subsys_mask: mask of the subsystem ids whose files should be added
4413 * On failure, no file is added.
4415 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
4417 struct cgroup_subsys *ss;
4420 /* process cftsets of each subsystem */
4421 for_each_subsys(ss, i) {
4422 struct cftype *cfts;
4424 if (!(subsys_mask & (1 << i)))
4427 list_for_each_entry(cfts, &ss->cfts, node) {
4428 ret = cgroup_addrm_files(cgrp, cfts, true);
4435 cgroup_clear_dir(cgrp, subsys_mask);
4440 * css destruction is four-stage process.
4442 * 1. Destruction starts. Killing of the percpu_ref is initiated.
4443 * Implemented in kill_css().
4445 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4446 * and thus css_tryget_online() is guaranteed to fail, the css can be
4447 * offlined by invoking offline_css(). After offlining, the base ref is
4448 * put. Implemented in css_killed_work_fn().
4450 * 3. When the percpu_ref reaches zero, the only possible remaining
4451 * accessors are inside RCU read sections. css_release() schedules the
4454 * 4. After the grace period, the css can be freed. Implemented in
4455 * css_free_work_fn().
4457 * It is actually hairier because both step 2 and 4 require process context
4458 * and thus involve punting to css->destroy_work adding two additional
4459 * steps to the already complex sequence.
4461 static void css_free_work_fn(struct work_struct *work)
4463 struct cgroup_subsys_state *css =
4464 container_of(work, struct cgroup_subsys_state, destroy_work);
4465 struct cgroup_subsys *ss = css->ss;
4466 struct cgroup *cgrp = css->cgroup;
4468 percpu_ref_exit(&css->refcnt);
4475 css_put(css->parent);
4478 cgroup_idr_remove(&ss->css_idr, id);
4481 /* cgroup free path */
4482 atomic_dec(&cgrp->root->nr_cgrps);
4483 cgroup_pidlist_destroy_all(cgrp);
4484 cancel_work_sync(&cgrp->release_agent_work);
4486 if (cgroup_parent(cgrp)) {
4488 * We get a ref to the parent, and put the ref when
4489 * this cgroup is being freed, so it's guaranteed
4490 * that the parent won't be destroyed before its
4493 cgroup_put(cgroup_parent(cgrp));
4494 kernfs_put(cgrp->kn);
4498 * This is root cgroup's refcnt reaching zero,
4499 * which indicates that the root should be
4502 cgroup_destroy_root(cgrp->root);
4507 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4509 struct cgroup_subsys_state *css =
4510 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4512 INIT_WORK(&css->destroy_work, css_free_work_fn);
4513 queue_work(cgroup_destroy_wq, &css->destroy_work);
4516 static void css_release_work_fn(struct work_struct *work)
4518 struct cgroup_subsys_state *css =
4519 container_of(work, struct cgroup_subsys_state, destroy_work);
4520 struct cgroup_subsys *ss = css->ss;
4521 struct cgroup *cgrp = css->cgroup;
4523 mutex_lock(&cgroup_mutex);
4525 css->flags |= CSS_RELEASED;
4526 list_del_rcu(&css->sibling);
4529 /* css release path */
4530 cgroup_idr_replace(&ss->css_idr, NULL, css->id);
4531 if (ss->css_released)
4532 ss->css_released(css);
4534 /* cgroup release path */
4535 cgroup_idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4539 * There are two control paths which try to determine
4540 * cgroup from dentry without going through kernfs -
4541 * cgroupstats_build() and css_tryget_online_from_dir().
4542 * Those are supported by RCU protecting clearing of
4543 * cgrp->kn->priv backpointer.
4545 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv, NULL);
4548 mutex_unlock(&cgroup_mutex);
4550 call_rcu(&css->rcu_head, css_free_rcu_fn);
4553 static void css_release(struct percpu_ref *ref)
4555 struct cgroup_subsys_state *css =
4556 container_of(ref, struct cgroup_subsys_state, refcnt);
4558 INIT_WORK(&css->destroy_work, css_release_work_fn);
4559 queue_work(cgroup_destroy_wq, &css->destroy_work);
4562 static void init_and_link_css(struct cgroup_subsys_state *css,
4563 struct cgroup_subsys *ss, struct cgroup *cgrp)
4565 lockdep_assert_held(&cgroup_mutex);
4569 memset(css, 0, sizeof(*css));
4572 INIT_LIST_HEAD(&css->sibling);
4573 INIT_LIST_HEAD(&css->children);
4574 css->serial_nr = css_serial_nr_next++;
4576 if (cgroup_parent(cgrp)) {
4577 css->parent = cgroup_css(cgroup_parent(cgrp), ss);
4578 css_get(css->parent);
4581 BUG_ON(cgroup_css(cgrp, ss));
4584 /* invoke ->css_online() on a new CSS and mark it online if successful */
4585 static int online_css(struct cgroup_subsys_state *css)
4587 struct cgroup_subsys *ss = css->ss;
4590 lockdep_assert_held(&cgroup_mutex);
4593 ret = ss->css_online(css);
4595 css->flags |= CSS_ONLINE;
4596 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
4601 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4602 static void offline_css(struct cgroup_subsys_state *css)
4604 struct cgroup_subsys *ss = css->ss;
4606 lockdep_assert_held(&cgroup_mutex);
4608 if (!(css->flags & CSS_ONLINE))
4611 if (ss->css_offline)
4612 ss->css_offline(css);
4614 css->flags &= ~CSS_ONLINE;
4615 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
4617 wake_up_all(&css->cgroup->offline_waitq);
4621 * create_css - create a cgroup_subsys_state
4622 * @cgrp: the cgroup new css will be associated with
4623 * @ss: the subsys of new css
4624 * @visible: whether to create control knobs for the new css or not
4626 * Create a new css associated with @cgrp - @ss pair. On success, the new
4627 * css is online and installed in @cgrp with all interface files created if
4628 * @visible. Returns 0 on success, -errno on failure.
4630 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss,
4633 struct cgroup *parent = cgroup_parent(cgrp);
4634 struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
4635 struct cgroup_subsys_state *css;
4638 lockdep_assert_held(&cgroup_mutex);
4640 css = ss->css_alloc(parent_css);
4642 return PTR_ERR(css);
4644 init_and_link_css(css, ss, cgrp);
4646 err = percpu_ref_init(&css->refcnt, css_release, 0, GFP_KERNEL);
4650 err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_KERNEL);
4652 goto err_free_percpu_ref;
4656 err = cgroup_populate_dir(cgrp, 1 << ss->id);
4661 /* @css is ready to be brought online now, make it visible */
4662 list_add_tail_rcu(&css->sibling, &parent_css->children);
4663 cgroup_idr_replace(&ss->css_idr, css, css->id);
4665 err = online_css(css);
4669 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4670 cgroup_parent(parent)) {
4671 pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4672 current->comm, current->pid, ss->name);
4673 if (!strcmp(ss->name, "memory"))
4674 pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
4675 ss->warned_broken_hierarchy = true;
4681 list_del_rcu(&css->sibling);
4682 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4684 cgroup_idr_remove(&ss->css_idr, css->id);
4685 err_free_percpu_ref:
4686 percpu_ref_exit(&css->refcnt);
4688 call_rcu(&css->rcu_head, css_free_rcu_fn);
4692 static int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
4695 struct cgroup *parent, *cgrp;
4696 struct cgroup_root *root;
4697 struct cgroup_subsys *ss;
4698 struct kernfs_node *kn;
4699 struct cftype *base_files;
4702 /* Do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable.
4704 if (strchr(name, '\n'))
4707 parent = cgroup_kn_lock_live(parent_kn);
4710 root = parent->root;
4712 /* allocate the cgroup and its ID, 0 is reserved for the root */
4713 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4719 ret = percpu_ref_init(&cgrp->self.refcnt, css_release, 0, GFP_KERNEL);
4724 * Temporarily set the pointer to NULL, so idr_find() won't return
4725 * a half-baked cgroup.
4727 cgrp->id = cgroup_idr_alloc(&root->cgroup_idr, NULL, 2, 0, GFP_KERNEL);
4730 goto out_cancel_ref;
4733 init_cgroup_housekeeping(cgrp);
4735 cgrp->self.parent = &parent->self;
4738 if (notify_on_release(parent))
4739 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4741 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4742 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4744 /* create the directory */
4745 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
4753 * This extra ref will be put in cgroup_free_fn() and guarantees
4754 * that @cgrp->kn is always accessible.
4758 cgrp->self.serial_nr = css_serial_nr_next++;
4760 /* allocation complete, commit to creation */
4761 list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
4762 atomic_inc(&root->nr_cgrps);
4766 * @cgrp is now fully operational. If something fails after this
4767 * point, it'll be released via the normal destruction path.
4769 cgroup_idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4771 ret = cgroup_kn_set_ugid(kn);
4775 if (cgroup_on_dfl(cgrp))
4776 base_files = cgroup_dfl_base_files;
4778 base_files = cgroup_legacy_base_files;
4780 ret = cgroup_addrm_files(cgrp, base_files, true);
4784 /* let's create and online css's */
4785 for_each_subsys(ss, ssid) {
4786 if (parent->child_subsys_mask & (1 << ssid)) {
4787 ret = create_css(cgrp, ss,
4788 parent->subtree_control & (1 << ssid));
4795 * On the default hierarchy, a child doesn't automatically inherit
4796 * subtree_control from the parent. Each is configured manually.
4798 if (!cgroup_on_dfl(cgrp)) {
4799 cgrp->subtree_control = parent->subtree_control;
4800 cgroup_refresh_child_subsys_mask(cgrp);
4803 kernfs_activate(kn);
4809 cgroup_idr_remove(&root->cgroup_idr, cgrp->id);
4811 percpu_ref_exit(&cgrp->self.refcnt);
4815 cgroup_kn_unlock(parent_kn);
4819 cgroup_destroy_locked(cgrp);
4824 * This is called when the refcnt of a css is confirmed to be killed.
4825 * css_tryget_online() is now guaranteed to fail. Tell the subsystem to
4826 * initate destruction and put the css ref from kill_css().
4828 static void css_killed_work_fn(struct work_struct *work)
4830 struct cgroup_subsys_state *css =
4831 container_of(work, struct cgroup_subsys_state, destroy_work);
4833 mutex_lock(&cgroup_mutex);
4835 mutex_unlock(&cgroup_mutex);
4840 /* css kill confirmation processing requires process context, bounce */
4841 static void css_killed_ref_fn(struct percpu_ref *ref)
4843 struct cgroup_subsys_state *css =
4844 container_of(ref, struct cgroup_subsys_state, refcnt);
4846 INIT_WORK(&css->destroy_work, css_killed_work_fn);
4847 queue_work(cgroup_destroy_wq, &css->destroy_work);
4851 * kill_css - destroy a css
4852 * @css: css to destroy
4854 * This function initiates destruction of @css by removing cgroup interface
4855 * files and putting its base reference. ->css_offline() will be invoked
4856 * asynchronously once css_tryget_online() is guaranteed to fail and when
4857 * the reference count reaches zero, @css will be released.
4859 static void kill_css(struct cgroup_subsys_state *css)
4861 lockdep_assert_held(&cgroup_mutex);
4864 * This must happen before css is disassociated with its cgroup.
4865 * See seq_css() for details.
4867 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4870 * Killing would put the base ref, but we need to keep it alive
4871 * until after ->css_offline().
4876 * cgroup core guarantees that, by the time ->css_offline() is
4877 * invoked, no new css reference will be given out via
4878 * css_tryget_online(). We can't simply call percpu_ref_kill() and
4879 * proceed to offlining css's because percpu_ref_kill() doesn't
4880 * guarantee that the ref is seen as killed on all CPUs on return.
4882 * Use percpu_ref_kill_and_confirm() to get notifications as each
4883 * css is confirmed to be seen as killed on all CPUs.
4885 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4889 * cgroup_destroy_locked - the first stage of cgroup destruction
4890 * @cgrp: cgroup to be destroyed
4892 * css's make use of percpu refcnts whose killing latency shouldn't be
4893 * exposed to userland and are RCU protected. Also, cgroup core needs to
4894 * guarantee that css_tryget_online() won't succeed by the time
4895 * ->css_offline() is invoked. To satisfy all the requirements,
4896 * destruction is implemented in the following two steps.
4898 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4899 * userland visible parts and start killing the percpu refcnts of
4900 * css's. Set up so that the next stage will be kicked off once all
4901 * the percpu refcnts are confirmed to be killed.
4903 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4904 * rest of destruction. Once all cgroup references are gone, the
4905 * cgroup is RCU-freed.
4907 * This function implements s1. After this step, @cgrp is gone as far as
4908 * the userland is concerned and a new cgroup with the same name may be
4909 * created. As cgroup doesn't care about the names internally, this
4910 * doesn't cause any problem.
4912 static int cgroup_destroy_locked(struct cgroup *cgrp)
4913 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4915 struct cgroup_subsys_state *css;
4919 lockdep_assert_held(&cgroup_mutex);
4922 * css_set_rwsem synchronizes access to ->cset_links and prevents
4923 * @cgrp from being removed while put_css_set() is in progress.
4925 down_read(&css_set_rwsem);
4926 empty = list_empty(&cgrp->cset_links);
4927 up_read(&css_set_rwsem);
4932 * Make sure there's no live children. We can't test emptiness of
4933 * ->self.children as dead children linger on it while being
4934 * drained; otherwise, "rmdir parent/child parent" may fail.
4936 if (css_has_online_children(&cgrp->self))
4940 * Mark @cgrp dead. This prevents further task migration and child
4941 * creation by disabling cgroup_lock_live_group().
4943 cgrp->self.flags &= ~CSS_ONLINE;
4945 /* initiate massacre of all css's */
4946 for_each_css(css, ssid, cgrp)
4950 * Remove @cgrp directory along with the base files. @cgrp has an
4951 * extra ref on its kn.
4953 kernfs_remove(cgrp->kn);
4955 check_for_release(cgroup_parent(cgrp));
4957 /* put the base reference */
4958 percpu_ref_kill(&cgrp->self.refcnt);
4963 static int cgroup_rmdir(struct kernfs_node *kn)
4965 struct cgroup *cgrp;
4968 cgrp = cgroup_kn_lock_live(kn);
4972 ret = cgroup_destroy_locked(cgrp);
4974 cgroup_kn_unlock(kn);
4978 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
4979 .remount_fs = cgroup_remount,
4980 .show_options = cgroup_show_options,
4981 .mkdir = cgroup_mkdir,
4982 .rmdir = cgroup_rmdir,
4983 .rename = cgroup_rename,
4986 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
4988 struct cgroup_subsys_state *css;
4990 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4992 mutex_lock(&cgroup_mutex);
4994 idr_init(&ss->css_idr);
4995 INIT_LIST_HEAD(&ss->cfts);
4997 /* Create the root cgroup state for this subsystem */
4998 ss->root = &cgrp_dfl_root;
4999 css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
5000 /* We don't handle early failures gracefully */
5001 BUG_ON(IS_ERR(css));
5002 init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
5005 * Root csses are never destroyed and we can't initialize
5006 * percpu_ref during early init. Disable refcnting.
5008 css->flags |= CSS_NO_REF;
5011 /* allocation can't be done safely during early init */
5014 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
5015 BUG_ON(css->id < 0);
5018 /* Update the init_css_set to contain a subsys
5019 * pointer to this state - since the subsystem is
5020 * newly registered, all tasks and hence the
5021 * init_css_set is in the subsystem's root cgroup. */
5022 init_css_set.subsys[ss->id] = css;
5024 have_fork_callback |= (bool)ss->fork << ss->id;
5025 have_exit_callback |= (bool)ss->exit << ss->id;
5026 have_canfork_callback |= (bool)ss->can_fork << ss->id;
5028 /* At system boot, before all subsystems have been
5029 * registered, no tasks have been forked, so we don't
5030 * need to invoke fork callbacks here. */
5031 BUG_ON(!list_empty(&init_task.tasks));
5033 BUG_ON(online_css(css));
5035 mutex_unlock(&cgroup_mutex);
5039 * cgroup_init_early - cgroup initialization at system boot
5041 * Initialize cgroups at system boot, and initialize any
5042 * subsystems that request early init.
5044 int __init cgroup_init_early(void)
5046 static struct cgroup_sb_opts __initdata opts;
5047 struct cgroup_subsys *ss;
5050 init_cgroup_root(&cgrp_dfl_root, &opts);
5051 cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
5053 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
5055 for_each_subsys(ss, i) {
5056 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
5057 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
5058 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
5060 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
5061 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
5064 ss->name = cgroup_subsys_name[i];
5065 if (!ss->legacy_name)
5066 ss->legacy_name = cgroup_subsys_name[i];
5069 cgroup_init_subsys(ss, true);
5075 * cgroup_init - cgroup initialization
5077 * Register cgroup filesystem and /proc file, and initialize
5078 * any subsystems that didn't request early init.
5080 int __init cgroup_init(void)
5082 struct cgroup_subsys *ss;
5086 BUG_ON(cgroup_init_cftypes(NULL, cgroup_dfl_base_files));
5087 BUG_ON(cgroup_init_cftypes(NULL, cgroup_legacy_base_files));
5089 mutex_lock(&cgroup_mutex);
5091 /* Add init_css_set to the hash table */
5092 key = css_set_hash(init_css_set.subsys);
5093 hash_add(css_set_table, &init_css_set.hlist, key);
5095 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
5097 mutex_unlock(&cgroup_mutex);
5099 for_each_subsys(ss, ssid) {
5100 if (ss->early_init) {
5101 struct cgroup_subsys_state *css =
5102 init_css_set.subsys[ss->id];
5104 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
5106 BUG_ON(css->id < 0);
5108 cgroup_init_subsys(ss, false);
5111 list_add_tail(&init_css_set.e_cset_node[ssid],
5112 &cgrp_dfl_root.cgrp.e_csets[ssid]);
5115 * Setting dfl_root subsys_mask needs to consider the
5116 * disabled flag and cftype registration needs kmalloc,
5117 * both of which aren't available during early_init.
5122 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
5124 if (cgroup_legacy_files_on_dfl && !ss->dfl_cftypes)
5125 ss->dfl_cftypes = ss->legacy_cftypes;
5127 if (!ss->dfl_cftypes)
5128 cgrp_dfl_root_inhibit_ss_mask |= 1 << ss->id;
5130 if (ss->dfl_cftypes == ss->legacy_cftypes) {
5131 WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes));
5133 WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes));
5134 WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes));
5138 ss->bind(init_css_set.subsys[ssid]);
5141 err = sysfs_create_mount_point(fs_kobj, "cgroup");
5145 err = register_filesystem(&cgroup_fs_type);
5147 sysfs_remove_mount_point(fs_kobj, "cgroup");
5151 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
5155 static int __init cgroup_wq_init(void)
5158 * There isn't much point in executing destruction path in
5159 * parallel. Good chunk is serialized with cgroup_mutex anyway.
5160 * Use 1 for @max_active.
5162 * We would prefer to do this in cgroup_init() above, but that
5163 * is called before init_workqueues(): so leave this until after.
5165 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
5166 BUG_ON(!cgroup_destroy_wq);
5169 * Used to destroy pidlists and separate to serve as flush domain.
5170 * Cap @max_active to 1 too.
5172 cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
5174 BUG_ON(!cgroup_pidlist_destroy_wq);
5178 core_initcall(cgroup_wq_init);
5181 * proc_cgroup_show()
5182 * - Print task's cgroup paths into seq_file, one line for each hierarchy
5183 * - Used for /proc/<pid>/cgroup.
5185 int proc_cgroup_show(struct seq_file *m, struct pid_namespace *ns,
5186 struct pid *pid, struct task_struct *tsk)
5190 struct cgroup_root *root;
5193 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5197 mutex_lock(&cgroup_mutex);
5198 down_read(&css_set_rwsem);
5200 for_each_root(root) {
5201 struct cgroup_subsys *ss;
5202 struct cgroup *cgrp;
5203 int ssid, count = 0;
5205 if (root == &cgrp_dfl_root && !cgrp_dfl_root_visible)
5208 seq_printf(m, "%d:", root->hierarchy_id);
5209 if (root != &cgrp_dfl_root)
5210 for_each_subsys(ss, ssid)
5211 if (root->subsys_mask & (1 << ssid))
5212 seq_printf(m, "%s%s", count++ ? "," : "",
5214 if (strlen(root->name))
5215 seq_printf(m, "%sname=%s", count ? "," : "",
5218 cgrp = task_cgroup_from_root(tsk, root);
5219 path = cgroup_path(cgrp, buf, PATH_MAX);
5221 retval = -ENAMETOOLONG;
5230 up_read(&css_set_rwsem);
5231 mutex_unlock(&cgroup_mutex);
5237 /* Display information about each subsystem and each hierarchy */
5238 static int proc_cgroupstats_show(struct seq_file *m, void *v)
5240 struct cgroup_subsys *ss;
5243 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
5245 * ideally we don't want subsystems moving around while we do this.
5246 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
5247 * subsys/hierarchy state.
5249 mutex_lock(&cgroup_mutex);
5251 for_each_subsys(ss, i)
5252 seq_printf(m, "%s\t%d\t%d\t%d\n",
5253 ss->legacy_name, ss->root->hierarchy_id,
5254 atomic_read(&ss->root->nr_cgrps), !ss->disabled);
5256 mutex_unlock(&cgroup_mutex);
5260 static int cgroupstats_open(struct inode *inode, struct file *file)
5262 return single_open(file, proc_cgroupstats_show, NULL);
5265 static const struct file_operations proc_cgroupstats_operations = {
5266 .open = cgroupstats_open,
5268 .llseek = seq_lseek,
5269 .release = single_release,
5272 static void **subsys_canfork_priv_p(void *ss_priv[CGROUP_CANFORK_COUNT], int i)
5274 if (CGROUP_CANFORK_START <= i && i < CGROUP_CANFORK_END)
5275 return &ss_priv[i - CGROUP_CANFORK_START];
5279 static void *subsys_canfork_priv(void *ss_priv[CGROUP_CANFORK_COUNT], int i)
5281 void **private = subsys_canfork_priv_p(ss_priv, i);
5282 return private ? *private : NULL;
5286 * cgroup_fork - initialize cgroup related fields during copy_process()
5287 * @child: pointer to task_struct of forking parent process.
5289 * A task is associated with the init_css_set until cgroup_post_fork()
5290 * attaches it to the parent's css_set. Empty cg_list indicates that
5291 * @child isn't holding reference to its css_set.
5293 void cgroup_fork(struct task_struct *child)
5295 RCU_INIT_POINTER(child->cgroups, &init_css_set);
5296 INIT_LIST_HEAD(&child->cg_list);
5300 * cgroup_can_fork - called on a new task before the process is exposed
5301 * @child: the task in question.
5303 * This calls the subsystem can_fork() callbacks. If the can_fork() callback
5304 * returns an error, the fork aborts with that error code. This allows for
5305 * a cgroup subsystem to conditionally allow or deny new forks.
5307 int cgroup_can_fork(struct task_struct *child,
5308 void *ss_priv[CGROUP_CANFORK_COUNT])
5310 struct cgroup_subsys *ss;
5313 for_each_subsys_which(ss, i, &have_canfork_callback) {
5314 ret = ss->can_fork(child, subsys_canfork_priv_p(ss_priv, i));
5322 for_each_subsys(ss, j) {
5325 if (ss->cancel_fork)
5326 ss->cancel_fork(child, subsys_canfork_priv(ss_priv, j));
5333 * cgroup_cancel_fork - called if a fork failed after cgroup_can_fork()
5334 * @child: the task in question
5336 * This calls the cancel_fork() callbacks if a fork failed *after*
5337 * cgroup_can_fork() succeded.
5339 void cgroup_cancel_fork(struct task_struct *child,
5340 void *ss_priv[CGROUP_CANFORK_COUNT])
5342 struct cgroup_subsys *ss;
5345 for_each_subsys(ss, i)
5346 if (ss->cancel_fork)
5347 ss->cancel_fork(child, subsys_canfork_priv(ss_priv, i));
5351 * cgroup_post_fork - called on a new task after adding it to the task list
5352 * @child: the task in question
5354 * Adds the task to the list running through its css_set if necessary and
5355 * call the subsystem fork() callbacks. Has to be after the task is
5356 * visible on the task list in case we race with the first call to
5357 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
5360 void cgroup_post_fork(struct task_struct *child,
5361 void *old_ss_priv[CGROUP_CANFORK_COUNT])
5363 struct cgroup_subsys *ss;
5367 * This may race against cgroup_enable_task_cg_lists(). As that
5368 * function sets use_task_css_set_links before grabbing
5369 * tasklist_lock and we just went through tasklist_lock to add
5370 * @child, it's guaranteed that either we see the set
5371 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
5372 * @child during its iteration.
5374 * If we won the race, @child is associated with %current's
5375 * css_set. Grabbing css_set_rwsem guarantees both that the
5376 * association is stable, and, on completion of the parent's
5377 * migration, @child is visible in the source of migration or
5378 * already in the destination cgroup. This guarantee is necessary
5379 * when implementing operations which need to migrate all tasks of
5380 * a cgroup to another.
5382 * Note that if we lose to cgroup_enable_task_cg_lists(), @child
5383 * will remain in init_css_set. This is safe because all tasks are
5384 * in the init_css_set before cg_links is enabled and there's no
5385 * operation which transfers all tasks out of init_css_set.
5387 if (use_task_css_set_links) {
5388 struct css_set *cset;
5390 down_write(&css_set_rwsem);
5391 cset = task_css_set(current);
5392 if (list_empty(&child->cg_list)) {
5393 rcu_assign_pointer(child->cgroups, cset);
5394 list_add(&child->cg_list, &cset->tasks);
5397 up_write(&css_set_rwsem);
5401 * Call ss->fork(). This must happen after @child is linked on
5402 * css_set; otherwise, @child might change state between ->fork()
5403 * and addition to css_set.
5405 for_each_subsys_which(ss, i, &have_fork_callback)
5406 ss->fork(child, subsys_canfork_priv(old_ss_priv, i));
5410 * cgroup_exit - detach cgroup from exiting task
5411 * @tsk: pointer to task_struct of exiting process
5413 * Description: Detach cgroup from @tsk and release it.
5415 * Note that cgroups marked notify_on_release force every task in
5416 * them to take the global cgroup_mutex mutex when exiting.
5417 * This could impact scaling on very large systems. Be reluctant to
5418 * use notify_on_release cgroups where very high task exit scaling
5419 * is required on large systems.
5421 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
5422 * call cgroup_exit() while the task is still competent to handle
5423 * notify_on_release(), then leave the task attached to the root cgroup in
5424 * each hierarchy for the remainder of its exit. No need to bother with
5425 * init_css_set refcnting. init_css_set never goes away and we can't race
5426 * with migration path - PF_EXITING is visible to migration path.
5428 void cgroup_exit(struct task_struct *tsk)
5430 struct cgroup_subsys *ss;
5431 struct css_set *cset;
5432 bool put_cset = false;
5436 * Unlink from @tsk from its css_set. As migration path can't race
5437 * with us, we can check cg_list without grabbing css_set_rwsem.
5439 if (!list_empty(&tsk->cg_list)) {
5440 down_write(&css_set_rwsem);
5441 list_del_init(&tsk->cg_list);
5442 up_write(&css_set_rwsem);
5446 /* Reassign the task to the init_css_set. */
5447 cset = task_css_set(tsk);
5448 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
5450 /* see cgroup_post_fork() for details */
5451 for_each_subsys_which(ss, i, &have_exit_callback) {
5452 struct cgroup_subsys_state *old_css = cset->subsys[i];
5453 struct cgroup_subsys_state *css = task_css(tsk, i);
5455 ss->exit(css, old_css, tsk);
5462 static void check_for_release(struct cgroup *cgrp)
5464 if (notify_on_release(cgrp) && !cgroup_has_tasks(cgrp) &&
5465 !css_has_online_children(&cgrp->self) && !cgroup_is_dead(cgrp))
5466 schedule_work(&cgrp->release_agent_work);
5470 * Notify userspace when a cgroup is released, by running the
5471 * configured release agent with the name of the cgroup (path
5472 * relative to the root of cgroup file system) as the argument.
5474 * Most likely, this user command will try to rmdir this cgroup.
5476 * This races with the possibility that some other task will be
5477 * attached to this cgroup before it is removed, or that some other
5478 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5479 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5480 * unused, and this cgroup will be reprieved from its death sentence,
5481 * to continue to serve a useful existence. Next time it's released,
5482 * we will get notified again, if it still has 'notify_on_release' set.
5484 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5485 * means only wait until the task is successfully execve()'d. The
5486 * separate release agent task is forked by call_usermodehelper(),
5487 * then control in this thread returns here, without waiting for the
5488 * release agent task. We don't bother to wait because the caller of
5489 * this routine has no use for the exit status of the release agent
5490 * task, so no sense holding our caller up for that.
5492 static void cgroup_release_agent(struct work_struct *work)
5494 struct cgroup *cgrp =
5495 container_of(work, struct cgroup, release_agent_work);
5496 char *pathbuf = NULL, *agentbuf = NULL, *path;
5497 char *argv[3], *envp[3];
5499 mutex_lock(&cgroup_mutex);
5501 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
5502 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5503 if (!pathbuf || !agentbuf)
5506 path = cgroup_path(cgrp, pathbuf, PATH_MAX);
5514 /* minimal command environment */
5516 envp[1] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5519 mutex_unlock(&cgroup_mutex);
5520 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5523 mutex_unlock(&cgroup_mutex);
5529 static int __init cgroup_disable(char *str)
5531 struct cgroup_subsys *ss;
5535 while ((token = strsep(&str, ",")) != NULL) {
5539 for_each_subsys(ss, i) {
5540 if (strcmp(token, ss->name) &&
5541 strcmp(token, ss->legacy_name))
5545 printk(KERN_INFO "Disabling %s control group subsystem\n",
5552 __setup("cgroup_disable=", cgroup_disable);
5554 static int __init cgroup_set_legacy_files_on_dfl(char *str)
5556 printk("cgroup: using legacy files on the default hierarchy\n");
5557 cgroup_legacy_files_on_dfl = true;
5560 __setup("cgroup__DEVEL__legacy_files_on_dfl", cgroup_set_legacy_files_on_dfl);
5563 * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
5564 * @dentry: directory dentry of interest
5565 * @ss: subsystem of interest
5567 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
5568 * to get the corresponding css and return it. If such css doesn't exist
5569 * or can't be pinned, an ERR_PTR value is returned.
5571 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
5572 struct cgroup_subsys *ss)
5574 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
5575 struct cgroup_subsys_state *css = NULL;
5576 struct cgroup *cgrp;
5578 /* is @dentry a cgroup dir? */
5579 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
5580 kernfs_type(kn) != KERNFS_DIR)
5581 return ERR_PTR(-EBADF);
5586 * This path doesn't originate from kernfs and @kn could already
5587 * have been or be removed at any point. @kn->priv is RCU
5588 * protected for this access. See css_release_work_fn() for details.
5590 cgrp = rcu_dereference(kn->priv);
5592 css = cgroup_css(cgrp, ss);
5594 if (!css || !css_tryget_online(css))
5595 css = ERR_PTR(-ENOENT);
5602 * css_from_id - lookup css by id
5603 * @id: the cgroup id
5604 * @ss: cgroup subsys to be looked into
5606 * Returns the css if there's valid one with @id, otherwise returns NULL.
5607 * Should be called under rcu_read_lock().
5609 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5611 WARN_ON_ONCE(!rcu_read_lock_held());
5612 return id > 0 ? idr_find(&ss->css_idr, id) : NULL;
5615 #ifdef CONFIG_CGROUP_DEBUG
5616 static struct cgroup_subsys_state *
5617 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5619 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5622 return ERR_PTR(-ENOMEM);
5627 static void debug_css_free(struct cgroup_subsys_state *css)
5632 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5635 return cgroup_task_count(css->cgroup);
5638 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5641 return (u64)(unsigned long)current->cgroups;
5644 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5650 count = atomic_read(&task_css_set(current)->refcount);
5655 static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
5657 struct cgrp_cset_link *link;
5658 struct css_set *cset;
5661 name_buf = kmalloc(NAME_MAX + 1, GFP_KERNEL);
5665 down_read(&css_set_rwsem);
5667 cset = rcu_dereference(current->cgroups);
5668 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5669 struct cgroup *c = link->cgrp;
5671 cgroup_name(c, name_buf, NAME_MAX + 1);
5672 seq_printf(seq, "Root %d group %s\n",
5673 c->root->hierarchy_id, name_buf);
5676 up_read(&css_set_rwsem);
5681 #define MAX_TASKS_SHOWN_PER_CSS 25
5682 static int cgroup_css_links_read(struct seq_file *seq, void *v)
5684 struct cgroup_subsys_state *css = seq_css(seq);
5685 struct cgrp_cset_link *link;
5687 down_read(&css_set_rwsem);
5688 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5689 struct css_set *cset = link->cset;
5690 struct task_struct *task;
5693 seq_printf(seq, "css_set %p\n", cset);
5695 list_for_each_entry(task, &cset->tasks, cg_list) {
5696 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5698 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5701 list_for_each_entry(task, &cset->mg_tasks, cg_list) {
5702 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5704 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5708 seq_puts(seq, " ...\n");
5710 up_read(&css_set_rwsem);
5714 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5716 return (!cgroup_has_tasks(css->cgroup) &&
5717 !css_has_online_children(&css->cgroup->self));
5720 static struct cftype debug_files[] = {
5722 .name = "taskcount",
5723 .read_u64 = debug_taskcount_read,
5727 .name = "current_css_set",
5728 .read_u64 = current_css_set_read,
5732 .name = "current_css_set_refcount",
5733 .read_u64 = current_css_set_refcount_read,
5737 .name = "current_css_set_cg_links",
5738 .seq_show = current_css_set_cg_links_read,
5742 .name = "cgroup_css_links",
5743 .seq_show = cgroup_css_links_read,
5747 .name = "releasable",
5748 .read_u64 = releasable_read,
5754 struct cgroup_subsys debug_cgrp_subsys = {
5755 .css_alloc = debug_css_alloc,
5756 .css_free = debug_css_free,
5757 .legacy_cftypes = debug_files,
5759 #endif /* CONFIG_CGROUP_DEBUG */