2 * Generic process-grouping system.
4 * Based originally on the cpuset system, extracted by Paul Menage
5 * Copyright (C) 2006 Google, Inc
7 * Notifications support
8 * Copyright (C) 2009 Nokia Corporation
9 * Author: Kirill A. Shutemov
11 * Copyright notices from the original cpuset code:
12 * --------------------------------------------------
13 * Copyright (C) 2003 BULL SA.
14 * Copyright (C) 2004-2006 Silicon Graphics, Inc.
16 * Portions derived from Patrick Mochel's sysfs code.
17 * sysfs is Copyright (c) 2001-3 Patrick Mochel
19 * 2003-10-10 Written by Simon Derr.
20 * 2003-10-22 Updates by Stephen Hemminger.
21 * 2004 May-July Rework by Paul Jackson.
22 * ---------------------------------------------------
24 * This file is subject to the terms and conditions of the GNU General Public
25 * License. See the file COPYING in the main directory of the Linux
26 * distribution for more details.
29 #include <linux/cgroup.h>
30 #include <linux/cred.h>
31 #include <linux/ctype.h>
32 #include <linux/errno.h>
33 #include <linux/init_task.h>
34 #include <linux/kernel.h>
35 #include <linux/list.h>
37 #include <linux/mutex.h>
38 #include <linux/mount.h>
39 #include <linux/pagemap.h>
40 #include <linux/proc_fs.h>
41 #include <linux/rcupdate.h>
42 #include <linux/sched.h>
43 #include <linux/slab.h>
44 #include <linux/spinlock.h>
45 #include <linux/rwsem.h>
46 #include <linux/string.h>
47 #include <linux/sort.h>
48 #include <linux/kmod.h>
49 #include <linux/delayacct.h>
50 #include <linux/cgroupstats.h>
51 #include <linux/hashtable.h>
52 #include <linux/pid_namespace.h>
53 #include <linux/idr.h>
54 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
55 #include <linux/kthread.h>
56 #include <linux/delay.h>
58 #include <linux/atomic.h>
61 * pidlists linger the following amount before being destroyed. The goal
62 * is avoiding frequent destruction in the middle of consecutive read calls
63 * Expiring in the middle is a performance problem not a correctness one.
64 * 1 sec should be enough.
66 #define CGROUP_PIDLIST_DESTROY_DELAY HZ
68 #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
72 * cgroup_tree_mutex nests above cgroup_mutex and protects cftypes, file
73 * creation/removal and hierarchy changing operations including cgroup
74 * creation, removal, css association and controller rebinding. This outer
75 * lock is needed mainly to resolve the circular dependency between kernfs
76 * active ref and cgroup_mutex. cgroup_tree_mutex nests above both.
78 static DEFINE_MUTEX(cgroup_tree_mutex);
81 * cgroup_mutex is the master lock. Any modification to cgroup or its
82 * hierarchy must be performed while holding it.
84 * css_set_rwsem protects task->cgroups pointer, the list of css_set
85 * objects, and the chain of tasks off each css_set.
87 * These locks are exported if CONFIG_PROVE_RCU so that accessors in
88 * cgroup.h can use them for lockdep annotations.
90 #ifdef CONFIG_PROVE_RCU
91 DEFINE_MUTEX(cgroup_mutex);
92 DECLARE_RWSEM(css_set_rwsem);
93 EXPORT_SYMBOL_GPL(cgroup_mutex);
94 EXPORT_SYMBOL_GPL(css_set_rwsem);
96 static DEFINE_MUTEX(cgroup_mutex);
97 static DECLARE_RWSEM(css_set_rwsem);
101 * Protects cgroup_subsys->release_agent_path. Modifying it also requires
102 * cgroup_mutex. Reading requires either cgroup_mutex or this spinlock.
104 static DEFINE_SPINLOCK(release_agent_path_lock);
106 #define cgroup_assert_mutexes_or_rcu_locked() \
107 rcu_lockdep_assert(rcu_read_lock_held() || \
108 lockdep_is_held(&cgroup_tree_mutex) || \
109 lockdep_is_held(&cgroup_mutex), \
110 "cgroup_[tree_]mutex or RCU read lock required");
113 * cgroup destruction makes heavy use of work items and there can be a lot
114 * of concurrent destructions. Use a separate workqueue so that cgroup
115 * destruction work items don't end up filling up max_active of system_wq
116 * which may lead to deadlock.
118 static struct workqueue_struct *cgroup_destroy_wq;
121 * pidlist destructions need to be flushed on cgroup destruction. Use a
122 * separate workqueue as flush domain.
124 static struct workqueue_struct *cgroup_pidlist_destroy_wq;
126 /* generate an array of cgroup subsystem pointers */
127 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
128 static struct cgroup_subsys *cgroup_subsys[] = {
129 #include <linux/cgroup_subsys.h>
133 /* array of cgroup subsystem names */
134 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
135 static const char *cgroup_subsys_name[] = {
136 #include <linux/cgroup_subsys.h>
141 * The default hierarchy, reserved for the subsystems that are otherwise
142 * unattached - it never has more than a single cgroup, and all tasks are
143 * part of that cgroup.
145 struct cgroup_root cgrp_dfl_root;
148 * The default hierarchy always exists but is hidden until mounted for the
149 * first time. This is for backward compatibility.
151 static bool cgrp_dfl_root_visible;
153 /* The list of hierarchy roots */
155 static LIST_HEAD(cgroup_roots);
156 static int cgroup_root_count;
158 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
159 static DEFINE_IDR(cgroup_hierarchy_idr);
162 * Assign a monotonically increasing serial number to cgroups. It
163 * guarantees cgroups with bigger numbers are newer than those with smaller
164 * numbers. Also, as cgroups are always appended to the parent's
165 * ->children list, it guarantees that sibling cgroups are always sorted in
166 * the ascending serial number order on the list. Protected by
169 static u64 cgroup_serial_nr_next = 1;
171 /* This flag indicates whether tasks in the fork and exit paths should
172 * check for fork/exit handlers to call. This avoids us having to do
173 * extra work in the fork/exit path if none of the subsystems need to
176 static int need_forkexit_callback __read_mostly;
178 static struct cftype cgroup_base_files[];
180 static void cgroup_put(struct cgroup *cgrp);
181 static int rebind_subsystems(struct cgroup_root *dst_root,
182 unsigned long ss_mask);
183 static void cgroup_destroy_css_killed(struct cgroup *cgrp);
184 static int cgroup_destroy_locked(struct cgroup *cgrp);
185 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
187 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp);
190 * cgroup_css - obtain a cgroup's css for the specified subsystem
191 * @cgrp: the cgroup of interest
192 * @ss: the subsystem of interest (%NULL returns the dummy_css)
194 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
195 * function must be called either under cgroup_mutex or rcu_read_lock() and
196 * the caller is responsible for pinning the returned css if it wants to
197 * keep accessing it outside the said locks. This function may return
198 * %NULL if @cgrp doesn't have @subsys_id enabled.
200 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
201 struct cgroup_subsys *ss)
204 return rcu_dereference_check(cgrp->subsys[ss->id],
205 lockdep_is_held(&cgroup_tree_mutex) ||
206 lockdep_is_held(&cgroup_mutex));
208 return &cgrp->dummy_css;
212 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
213 * @cgrp: the cgroup of interest
214 * @ss: the subsystem of interest (%NULL returns the dummy_css)
216 * Similar to cgroup_css() but returns the effctive css, which is defined
217 * as the matching css of the nearest ancestor including self which has @ss
218 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
219 * function is guaranteed to return non-NULL css.
221 static struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
222 struct cgroup_subsys *ss)
224 lockdep_assert_held(&cgroup_mutex);
227 return &cgrp->dummy_css;
229 if (!(cgrp->root->subsys_mask & (1 << ss->id)))
232 while (cgrp->parent &&
233 !(cgrp->parent->child_subsys_mask & (1 << ss->id)))
236 return cgroup_css(cgrp, ss);
239 /* convenient tests for these bits */
240 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
242 return test_bit(CGRP_DEAD, &cgrp->flags);
245 struct cgroup_subsys_state *seq_css(struct seq_file *seq)
247 struct kernfs_open_file *of = seq->private;
248 struct cgroup *cgrp = of->kn->parent->priv;
249 struct cftype *cft = seq_cft(seq);
252 * This is open and unprotected implementation of cgroup_css().
253 * seq_css() is only called from a kernfs file operation which has
254 * an active reference on the file. Because all the subsystem
255 * files are drained before a css is disassociated with a cgroup,
256 * the matching css from the cgroup's subsys table is guaranteed to
257 * be and stay valid until the enclosing operation is complete.
260 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
262 return &cgrp->dummy_css;
264 EXPORT_SYMBOL_GPL(seq_css);
267 * cgroup_is_descendant - test ancestry
268 * @cgrp: the cgroup to be tested
269 * @ancestor: possible ancestor of @cgrp
271 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
272 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
273 * and @ancestor are accessible.
275 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
278 if (cgrp == ancestor)
285 static int cgroup_is_releasable(const struct cgroup *cgrp)
288 (1 << CGRP_RELEASABLE) |
289 (1 << CGRP_NOTIFY_ON_RELEASE);
290 return (cgrp->flags & bits) == bits;
293 static int notify_on_release(const struct cgroup *cgrp)
295 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
299 * for_each_css - iterate all css's of a cgroup
300 * @css: the iteration cursor
301 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
302 * @cgrp: the target cgroup to iterate css's of
304 * Should be called under cgroup_[tree_]mutex.
306 #define for_each_css(css, ssid, cgrp) \
307 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
308 if (!((css) = rcu_dereference_check( \
309 (cgrp)->subsys[(ssid)], \
310 lockdep_is_held(&cgroup_tree_mutex) || \
311 lockdep_is_held(&cgroup_mutex)))) { } \
315 * for_each_e_css - iterate all effective css's of a cgroup
316 * @css: the iteration cursor
317 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
318 * @cgrp: the target cgroup to iterate css's of
320 * Should be called under cgroup_[tree_]mutex.
322 #define for_each_e_css(css, ssid, cgrp) \
323 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
324 if (!((css) = cgroup_e_css(cgrp, cgroup_subsys[(ssid)]))) \
329 * for_each_subsys - iterate all enabled cgroup subsystems
330 * @ss: the iteration cursor
331 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
333 #define for_each_subsys(ss, ssid) \
334 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT && \
335 (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
337 /* iterate across the hierarchies */
338 #define for_each_root(root) \
339 list_for_each_entry((root), &cgroup_roots, root_list)
342 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
343 * @cgrp: the cgroup to be checked for liveness
345 * On success, returns true; the mutex should be later unlocked. On
346 * failure returns false with no lock held.
348 static bool cgroup_lock_live_group(struct cgroup *cgrp)
350 mutex_lock(&cgroup_mutex);
351 if (cgroup_is_dead(cgrp)) {
352 mutex_unlock(&cgroup_mutex);
358 /* the list of cgroups eligible for automatic release. Protected by
359 * release_list_lock */
360 static LIST_HEAD(release_list);
361 static DEFINE_RAW_SPINLOCK(release_list_lock);
362 static void cgroup_release_agent(struct work_struct *work);
363 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
364 static void check_for_release(struct cgroup *cgrp);
367 * A cgroup can be associated with multiple css_sets as different tasks may
368 * belong to different cgroups on different hierarchies. In the other
369 * direction, a css_set is naturally associated with multiple cgroups.
370 * This M:N relationship is represented by the following link structure
371 * which exists for each association and allows traversing the associations
374 struct cgrp_cset_link {
375 /* the cgroup and css_set this link associates */
377 struct css_set *cset;
379 /* list of cgrp_cset_links anchored at cgrp->cset_links */
380 struct list_head cset_link;
382 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
383 struct list_head cgrp_link;
387 * The default css_set - used by init and its children prior to any
388 * hierarchies being mounted. It contains a pointer to the root state
389 * for each subsystem. Also used to anchor the list of css_sets. Not
390 * reference-counted, to improve performance when child cgroups
391 * haven't been created.
393 static struct css_set init_css_set = {
394 .refcount = ATOMIC_INIT(1),
395 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
396 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
397 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
398 .mg_preload_node = LIST_HEAD_INIT(init_css_set.mg_preload_node),
399 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
402 static int css_set_count = 1; /* 1 for init_css_set */
405 * hash table for cgroup groups. This improves the performance to find
406 * an existing css_set. This hash doesn't (currently) take into
407 * account cgroups in empty hierarchies.
409 #define CSS_SET_HASH_BITS 7
410 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
412 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
414 unsigned long key = 0UL;
415 struct cgroup_subsys *ss;
418 for_each_subsys(ss, i)
419 key += (unsigned long)css[i];
420 key = (key >> 16) ^ key;
425 static void put_css_set_locked(struct css_set *cset, bool taskexit)
427 struct cgrp_cset_link *link, *tmp_link;
429 lockdep_assert_held(&css_set_rwsem);
431 if (!atomic_dec_and_test(&cset->refcount))
434 /* This css_set is dead. unlink it and release cgroup refcounts */
435 hash_del(&cset->hlist);
438 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
439 struct cgroup *cgrp = link->cgrp;
441 list_del(&link->cset_link);
442 list_del(&link->cgrp_link);
444 /* @cgrp can't go away while we're holding css_set_rwsem */
445 if (list_empty(&cgrp->cset_links) && notify_on_release(cgrp)) {
447 set_bit(CGRP_RELEASABLE, &cgrp->flags);
448 check_for_release(cgrp);
454 kfree_rcu(cset, rcu_head);
457 static void put_css_set(struct css_set *cset, bool taskexit)
460 * Ensure that the refcount doesn't hit zero while any readers
461 * can see it. Similar to atomic_dec_and_lock(), but for an
464 if (atomic_add_unless(&cset->refcount, -1, 1))
467 down_write(&css_set_rwsem);
468 put_css_set_locked(cset, taskexit);
469 up_write(&css_set_rwsem);
473 * refcounted get/put for css_set objects
475 static inline void get_css_set(struct css_set *cset)
477 atomic_inc(&cset->refcount);
481 * compare_css_sets - helper function for find_existing_css_set().
482 * @cset: candidate css_set being tested
483 * @old_cset: existing css_set for a task
484 * @new_cgrp: cgroup that's being entered by the task
485 * @template: desired set of css pointers in css_set (pre-calculated)
487 * Returns true if "cset" matches "old_cset" except for the hierarchy
488 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
490 static bool compare_css_sets(struct css_set *cset,
491 struct css_set *old_cset,
492 struct cgroup *new_cgrp,
493 struct cgroup_subsys_state *template[])
495 struct list_head *l1, *l2;
498 * On the default hierarchy, there can be csets which are
499 * associated with the same set of cgroups but different csses.
500 * Let's first ensure that csses match.
502 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
506 * Compare cgroup pointers in order to distinguish between
507 * different cgroups in hierarchies. As different cgroups may
508 * share the same effective css, this comparison is always
511 l1 = &cset->cgrp_links;
512 l2 = &old_cset->cgrp_links;
514 struct cgrp_cset_link *link1, *link2;
515 struct cgroup *cgrp1, *cgrp2;
519 /* See if we reached the end - both lists are equal length. */
520 if (l1 == &cset->cgrp_links) {
521 BUG_ON(l2 != &old_cset->cgrp_links);
524 BUG_ON(l2 == &old_cset->cgrp_links);
526 /* Locate the cgroups associated with these links. */
527 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
528 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
531 /* Hierarchies should be linked in the same order. */
532 BUG_ON(cgrp1->root != cgrp2->root);
535 * If this hierarchy is the hierarchy of the cgroup
536 * that's changing, then we need to check that this
537 * css_set points to the new cgroup; if it's any other
538 * hierarchy, then this css_set should point to the
539 * same cgroup as the old css_set.
541 if (cgrp1->root == new_cgrp->root) {
542 if (cgrp1 != new_cgrp)
553 * find_existing_css_set - init css array and find the matching css_set
554 * @old_cset: the css_set that we're using before the cgroup transition
555 * @cgrp: the cgroup that we're moving into
556 * @template: out param for the new set of csses, should be clear on entry
558 static struct css_set *find_existing_css_set(struct css_set *old_cset,
560 struct cgroup_subsys_state *template[])
562 struct cgroup_root *root = cgrp->root;
563 struct cgroup_subsys *ss;
564 struct css_set *cset;
569 * Build the set of subsystem state objects that we want to see in the
570 * new css_set. while subsystems can change globally, the entries here
571 * won't change, so no need for locking.
573 for_each_subsys(ss, i) {
574 if (root->subsys_mask & (1UL << i)) {
576 * @ss is in this hierarchy, so we want the
577 * effective css from @cgrp.
579 template[i] = cgroup_e_css(cgrp, ss);
582 * @ss is not in this hierarchy, so we don't want
585 template[i] = old_cset->subsys[i];
589 key = css_set_hash(template);
590 hash_for_each_possible(css_set_table, cset, hlist, key) {
591 if (!compare_css_sets(cset, old_cset, cgrp, template))
594 /* This css_set matches what we need */
598 /* No existing cgroup group matched */
602 static void free_cgrp_cset_links(struct list_head *links_to_free)
604 struct cgrp_cset_link *link, *tmp_link;
606 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
607 list_del(&link->cset_link);
613 * allocate_cgrp_cset_links - allocate cgrp_cset_links
614 * @count: the number of links to allocate
615 * @tmp_links: list_head the allocated links are put on
617 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
618 * through ->cset_link. Returns 0 on success or -errno.
620 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
622 struct cgrp_cset_link *link;
625 INIT_LIST_HEAD(tmp_links);
627 for (i = 0; i < count; i++) {
628 link = kzalloc(sizeof(*link), GFP_KERNEL);
630 free_cgrp_cset_links(tmp_links);
633 list_add(&link->cset_link, tmp_links);
639 * link_css_set - a helper function to link a css_set to a cgroup
640 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
641 * @cset: the css_set to be linked
642 * @cgrp: the destination cgroup
644 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
647 struct cgrp_cset_link *link;
649 BUG_ON(list_empty(tmp_links));
650 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
653 list_move(&link->cset_link, &cgrp->cset_links);
655 * Always add links to the tail of the list so that the list
656 * is sorted by order of hierarchy creation
658 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
662 * find_css_set - return a new css_set with one cgroup updated
663 * @old_cset: the baseline css_set
664 * @cgrp: the cgroup to be updated
666 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
667 * substituted into the appropriate hierarchy.
669 static struct css_set *find_css_set(struct css_set *old_cset,
672 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
673 struct css_set *cset;
674 struct list_head tmp_links;
675 struct cgrp_cset_link *link;
678 lockdep_assert_held(&cgroup_mutex);
680 /* First see if we already have a cgroup group that matches
682 down_read(&css_set_rwsem);
683 cset = find_existing_css_set(old_cset, cgrp, template);
686 up_read(&css_set_rwsem);
691 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
695 /* Allocate all the cgrp_cset_link objects that we'll need */
696 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
701 atomic_set(&cset->refcount, 1);
702 INIT_LIST_HEAD(&cset->cgrp_links);
703 INIT_LIST_HEAD(&cset->tasks);
704 INIT_LIST_HEAD(&cset->mg_tasks);
705 INIT_LIST_HEAD(&cset->mg_preload_node);
706 INIT_LIST_HEAD(&cset->mg_node);
707 INIT_HLIST_NODE(&cset->hlist);
709 /* Copy the set of subsystem state objects generated in
710 * find_existing_css_set() */
711 memcpy(cset->subsys, template, sizeof(cset->subsys));
713 down_write(&css_set_rwsem);
714 /* Add reference counts and links from the new css_set. */
715 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
716 struct cgroup *c = link->cgrp;
718 if (c->root == cgrp->root)
720 link_css_set(&tmp_links, cset, c);
723 BUG_ON(!list_empty(&tmp_links));
727 /* Add this cgroup group to the hash table */
728 key = css_set_hash(cset->subsys);
729 hash_add(css_set_table, &cset->hlist, key);
731 up_write(&css_set_rwsem);
736 static struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
738 struct cgroup *root_cgrp = kf_root->kn->priv;
740 return root_cgrp->root;
743 static int cgroup_init_root_id(struct cgroup_root *root)
747 lockdep_assert_held(&cgroup_mutex);
749 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
753 root->hierarchy_id = id;
757 static void cgroup_exit_root_id(struct cgroup_root *root)
759 lockdep_assert_held(&cgroup_mutex);
761 if (root->hierarchy_id) {
762 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
763 root->hierarchy_id = 0;
767 static void cgroup_free_root(struct cgroup_root *root)
770 /* hierarhcy ID shoulid already have been released */
771 WARN_ON_ONCE(root->hierarchy_id);
773 idr_destroy(&root->cgroup_idr);
778 static void cgroup_destroy_root(struct cgroup_root *root)
780 struct cgroup *cgrp = &root->cgrp;
781 struct cgrp_cset_link *link, *tmp_link;
783 mutex_lock(&cgroup_tree_mutex);
784 mutex_lock(&cgroup_mutex);
786 BUG_ON(atomic_read(&root->nr_cgrps));
787 BUG_ON(!list_empty(&cgrp->children));
789 /* Rebind all subsystems back to the default hierarchy */
790 rebind_subsystems(&cgrp_dfl_root, root->subsys_mask);
793 * Release all the links from cset_links to this hierarchy's
796 down_write(&css_set_rwsem);
798 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
799 list_del(&link->cset_link);
800 list_del(&link->cgrp_link);
803 up_write(&css_set_rwsem);
805 if (!list_empty(&root->root_list)) {
806 list_del(&root->root_list);
810 cgroup_exit_root_id(root);
812 mutex_unlock(&cgroup_mutex);
813 mutex_unlock(&cgroup_tree_mutex);
815 kernfs_destroy_root(root->kf_root);
816 cgroup_free_root(root);
819 /* look up cgroup associated with given css_set on the specified hierarchy */
820 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
821 struct cgroup_root *root)
823 struct cgroup *res = NULL;
825 lockdep_assert_held(&cgroup_mutex);
826 lockdep_assert_held(&css_set_rwsem);
828 if (cset == &init_css_set) {
831 struct cgrp_cset_link *link;
833 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
834 struct cgroup *c = link->cgrp;
836 if (c->root == root) {
848 * Return the cgroup for "task" from the given hierarchy. Must be
849 * called with cgroup_mutex and css_set_rwsem held.
851 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
852 struct cgroup_root *root)
855 * No need to lock the task - since we hold cgroup_mutex the
856 * task can't change groups, so the only thing that can happen
857 * is that it exits and its css is set back to init_css_set.
859 return cset_cgroup_from_root(task_css_set(task), root);
863 * A task must hold cgroup_mutex to modify cgroups.
865 * Any task can increment and decrement the count field without lock.
866 * So in general, code holding cgroup_mutex can't rely on the count
867 * field not changing. However, if the count goes to zero, then only
868 * cgroup_attach_task() can increment it again. Because a count of zero
869 * means that no tasks are currently attached, therefore there is no
870 * way a task attached to that cgroup can fork (the other way to
871 * increment the count). So code holding cgroup_mutex can safely
872 * assume that if the count is zero, it will stay zero. Similarly, if
873 * a task holds cgroup_mutex on a cgroup with zero count, it
874 * knows that the cgroup won't be removed, as cgroup_rmdir()
877 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
878 * (usually) take cgroup_mutex. These are the two most performance
879 * critical pieces of code here. The exception occurs on cgroup_exit(),
880 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
881 * is taken, and if the cgroup count is zero, a usermode call made
882 * to the release agent with the name of the cgroup (path relative to
883 * the root of cgroup file system) as the argument.
885 * A cgroup can only be deleted if both its 'count' of using tasks
886 * is zero, and its list of 'children' cgroups is empty. Since all
887 * tasks in the system use _some_ cgroup, and since there is always at
888 * least one task in the system (init, pid == 1), therefore, root cgroup
889 * always has either children cgroups and/or using tasks. So we don't
890 * need a special hack to ensure that root cgroup cannot be deleted.
892 * P.S. One more locking exception. RCU is used to guard the
893 * update of a tasks cgroup pointer by cgroup_attach_task()
896 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask);
897 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
898 static const struct file_operations proc_cgroupstats_operations;
900 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
903 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
904 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
905 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
906 cft->ss->name, cft->name);
908 strncpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
913 * cgroup_file_mode - deduce file mode of a control file
914 * @cft: the control file in question
916 * returns cft->mode if ->mode is not 0
917 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
918 * returns S_IRUGO if it has only a read handler
919 * returns S_IWUSR if it has only a write hander
921 static umode_t cgroup_file_mode(const struct cftype *cft)
928 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
931 if (cft->write_u64 || cft->write_s64 || cft->write_string ||
938 static void cgroup_free_fn(struct work_struct *work)
940 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
942 atomic_dec(&cgrp->root->nr_cgrps);
943 cgroup_pidlist_destroy_all(cgrp);
947 * We get a ref to the parent, and put the ref when this
948 * cgroup is being freed, so it's guaranteed that the
949 * parent won't be destroyed before its children.
951 cgroup_put(cgrp->parent);
952 kernfs_put(cgrp->kn);
956 * This is root cgroup's refcnt reaching zero, which
957 * indicates that the root should be released.
959 cgroup_destroy_root(cgrp->root);
963 static void cgroup_free_rcu(struct rcu_head *head)
965 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
967 INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
968 queue_work(cgroup_destroy_wq, &cgrp->destroy_work);
971 static void cgroup_get(struct cgroup *cgrp)
973 WARN_ON_ONCE(cgroup_is_dead(cgrp));
974 WARN_ON_ONCE(atomic_read(&cgrp->refcnt) <= 0);
975 atomic_inc(&cgrp->refcnt);
978 static void cgroup_put(struct cgroup *cgrp)
980 if (!atomic_dec_and_test(&cgrp->refcnt))
982 if (WARN_ON_ONCE(cgrp->parent && !cgroup_is_dead(cgrp)))
986 * XXX: cgrp->id is only used to look up css's. As cgroup and
987 * css's lifetimes will be decoupled, it should be made
988 * per-subsystem and moved to css->id so that lookups are
989 * successful until the target css is released.
991 mutex_lock(&cgroup_mutex);
992 idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
993 mutex_unlock(&cgroup_mutex);
996 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
999 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1001 char name[CGROUP_FILE_NAME_MAX];
1003 lockdep_assert_held(&cgroup_tree_mutex);
1004 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1008 * cgroup_clear_dir - remove subsys files in a cgroup directory
1009 * @cgrp: target cgroup
1010 * @subsys_mask: mask of the subsystem ids whose files should be removed
1012 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned long subsys_mask)
1014 struct cgroup_subsys *ss;
1017 for_each_subsys(ss, i) {
1018 struct cftype *cfts;
1020 if (!test_bit(i, &subsys_mask))
1022 list_for_each_entry(cfts, &ss->cfts, node)
1023 cgroup_addrm_files(cgrp, cfts, false);
1027 static int rebind_subsystems(struct cgroup_root *dst_root,
1028 unsigned long ss_mask)
1030 struct cgroup_subsys *ss;
1033 lockdep_assert_held(&cgroup_tree_mutex);
1034 lockdep_assert_held(&cgroup_mutex);
1036 for_each_subsys(ss, ssid) {
1037 if (!(ss_mask & (1 << ssid)))
1040 /* if @ss is on the dummy_root, we can always move it */
1041 if (ss->root == &cgrp_dfl_root)
1044 /* if @ss has non-root cgroups attached to it, can't move */
1045 if (!list_empty(&ss->root->cgrp.children))
1048 /* can't move between two non-dummy roots either */
1049 if (dst_root != &cgrp_dfl_root)
1053 ret = cgroup_populate_dir(&dst_root->cgrp, ss_mask);
1055 if (dst_root != &cgrp_dfl_root)
1059 * Rebinding back to the default root is not allowed to
1060 * fail. Using both default and non-default roots should
1061 * be rare. Moving subsystems back and forth even more so.
1062 * Just warn about it and continue.
1064 if (cgrp_dfl_root_visible) {
1065 pr_warning("cgroup: failed to create files (%d) while rebinding 0x%lx to default root\n",
1067 pr_warning("cgroup: you may retry by moving them to a different hierarchy and unbinding\n");
1072 * Nothing can fail from this point on. Remove files for the
1073 * removed subsystems and rebind each subsystem.
1075 mutex_unlock(&cgroup_mutex);
1076 for_each_subsys(ss, ssid)
1077 if (ss_mask & (1 << ssid))
1078 cgroup_clear_dir(&ss->root->cgrp, 1 << ssid);
1079 mutex_lock(&cgroup_mutex);
1081 for_each_subsys(ss, ssid) {
1082 struct cgroup_root *src_root;
1083 struct cgroup_subsys_state *css;
1085 if (!(ss_mask & (1 << ssid)))
1088 src_root = ss->root;
1089 css = cgroup_css(&src_root->cgrp, ss);
1091 WARN_ON(!css || cgroup_css(&dst_root->cgrp, ss));
1093 RCU_INIT_POINTER(src_root->cgrp.subsys[ssid], NULL);
1094 rcu_assign_pointer(dst_root->cgrp.subsys[ssid], css);
1095 ss->root = dst_root;
1096 css->cgroup = &dst_root->cgrp;
1098 src_root->subsys_mask &= ~(1 << ssid);
1099 src_root->cgrp.child_subsys_mask &= ~(1 << ssid);
1101 dst_root->subsys_mask |= 1 << ssid;
1102 dst_root->cgrp.child_subsys_mask |= 1 << ssid;
1108 kernfs_activate(dst_root->cgrp.kn);
1112 static int cgroup_show_options(struct seq_file *seq,
1113 struct kernfs_root *kf_root)
1115 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1116 struct cgroup_subsys *ss;
1119 for_each_subsys(ss, ssid)
1120 if (root->subsys_mask & (1 << ssid))
1121 seq_printf(seq, ",%s", ss->name);
1122 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1123 seq_puts(seq, ",sane_behavior");
1124 if (root->flags & CGRP_ROOT_NOPREFIX)
1125 seq_puts(seq, ",noprefix");
1126 if (root->flags & CGRP_ROOT_XATTR)
1127 seq_puts(seq, ",xattr");
1129 spin_lock(&release_agent_path_lock);
1130 if (strlen(root->release_agent_path))
1131 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1132 spin_unlock(&release_agent_path_lock);
1134 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags))
1135 seq_puts(seq, ",clone_children");
1136 if (strlen(root->name))
1137 seq_printf(seq, ",name=%s", root->name);
1141 struct cgroup_sb_opts {
1142 unsigned long subsys_mask;
1143 unsigned long flags;
1144 char *release_agent;
1145 bool cpuset_clone_children;
1147 /* User explicitly requested empty subsystem */
1152 * Convert a hierarchy specifier into a bitmask of subsystems and
1153 * flags. Call with cgroup_mutex held to protect the cgroup_subsys[]
1154 * array. This function takes refcounts on subsystems to be used, unless it
1155 * returns error, in which case no refcounts are taken.
1157 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1159 char *token, *o = data;
1160 bool all_ss = false, one_ss = false;
1161 unsigned long mask = (unsigned long)-1;
1162 struct cgroup_subsys *ss;
1165 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1167 #ifdef CONFIG_CPUSETS
1168 mask = ~(1UL << cpuset_cgrp_id);
1171 memset(opts, 0, sizeof(*opts));
1173 while ((token = strsep(&o, ",")) != NULL) {
1176 if (!strcmp(token, "none")) {
1177 /* Explicitly have no subsystems */
1181 if (!strcmp(token, "all")) {
1182 /* Mutually exclusive option 'all' + subsystem name */
1188 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1189 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1192 if (!strcmp(token, "noprefix")) {
1193 opts->flags |= CGRP_ROOT_NOPREFIX;
1196 if (!strcmp(token, "clone_children")) {
1197 opts->cpuset_clone_children = true;
1200 if (!strcmp(token, "xattr")) {
1201 opts->flags |= CGRP_ROOT_XATTR;
1204 if (!strncmp(token, "release_agent=", 14)) {
1205 /* Specifying two release agents is forbidden */
1206 if (opts->release_agent)
1208 opts->release_agent =
1209 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1210 if (!opts->release_agent)
1214 if (!strncmp(token, "name=", 5)) {
1215 const char *name = token + 5;
1216 /* Can't specify an empty name */
1219 /* Must match [\w.-]+ */
1220 for (i = 0; i < strlen(name); i++) {
1224 if ((c == '.') || (c == '-') || (c == '_'))
1228 /* Specifying two names is forbidden */
1231 opts->name = kstrndup(name,
1232 MAX_CGROUP_ROOT_NAMELEN - 1,
1240 for_each_subsys(ss, i) {
1241 if (strcmp(token, ss->name))
1246 /* Mutually exclusive option 'all' + subsystem name */
1249 set_bit(i, &opts->subsys_mask);
1254 if (i == CGROUP_SUBSYS_COUNT)
1258 /* Consistency checks */
1260 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1261 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1263 if ((opts->flags & (CGRP_ROOT_NOPREFIX | CGRP_ROOT_XATTR)) ||
1264 opts->cpuset_clone_children || opts->release_agent ||
1266 pr_err("cgroup: sane_behavior: noprefix, xattr, clone_children, release_agent and name are not allowed\n");
1271 * If the 'all' option was specified select all the
1272 * subsystems, otherwise if 'none', 'name=' and a subsystem
1273 * name options were not specified, let's default to 'all'
1275 if (all_ss || (!one_ss && !opts->none && !opts->name))
1276 for_each_subsys(ss, i)
1278 set_bit(i, &opts->subsys_mask);
1281 * We either have to specify by name or by subsystems. (So
1282 * all empty hierarchies must have a name).
1284 if (!opts->subsys_mask && !opts->name)
1289 * Option noprefix was introduced just for backward compatibility
1290 * with the old cpuset, so we allow noprefix only if mounting just
1291 * the cpuset subsystem.
1293 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1297 /* Can't specify "none" and some subsystems */
1298 if (opts->subsys_mask && opts->none)
1304 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1307 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1308 struct cgroup_sb_opts opts;
1309 unsigned long added_mask, removed_mask;
1311 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1312 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1316 mutex_lock(&cgroup_tree_mutex);
1317 mutex_lock(&cgroup_mutex);
1319 /* See what subsystems are wanted */
1320 ret = parse_cgroupfs_options(data, &opts);
1324 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1325 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1326 task_tgid_nr(current), current->comm);
1328 added_mask = opts.subsys_mask & ~root->subsys_mask;
1329 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1331 /* Don't allow flags or name to change at remount */
1332 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1333 (opts.name && strcmp(opts.name, root->name))) {
1334 pr_err("cgroup: option or name mismatch, new: 0x%lx \"%s\", old: 0x%lx \"%s\"\n",
1335 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1336 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1341 /* remounting is not allowed for populated hierarchies */
1342 if (!list_empty(&root->cgrp.children)) {
1347 ret = rebind_subsystems(root, added_mask);
1351 rebind_subsystems(&cgrp_dfl_root, removed_mask);
1353 if (opts.release_agent) {
1354 spin_lock(&release_agent_path_lock);
1355 strcpy(root->release_agent_path, opts.release_agent);
1356 spin_unlock(&release_agent_path_lock);
1359 kfree(opts.release_agent);
1361 mutex_unlock(&cgroup_mutex);
1362 mutex_unlock(&cgroup_tree_mutex);
1367 * To reduce the fork() overhead for systems that are not actually using
1368 * their cgroups capability, we don't maintain the lists running through
1369 * each css_set to its tasks until we see the list actually used - in other
1370 * words after the first mount.
1372 static bool use_task_css_set_links __read_mostly;
1374 static void cgroup_enable_task_cg_lists(void)
1376 struct task_struct *p, *g;
1378 down_write(&css_set_rwsem);
1380 if (use_task_css_set_links)
1383 use_task_css_set_links = true;
1386 * We need tasklist_lock because RCU is not safe against
1387 * while_each_thread(). Besides, a forking task that has passed
1388 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1389 * is not guaranteed to have its child immediately visible in the
1390 * tasklist if we walk through it with RCU.
1392 read_lock(&tasklist_lock);
1393 do_each_thread(g, p) {
1394 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1395 task_css_set(p) != &init_css_set);
1398 * We should check if the process is exiting, otherwise
1399 * it will race with cgroup_exit() in that the list
1400 * entry won't be deleted though the process has exited.
1401 * Do it while holding siglock so that we don't end up
1402 * racing against cgroup_exit().
1404 spin_lock_irq(&p->sighand->siglock);
1405 if (!(p->flags & PF_EXITING)) {
1406 struct css_set *cset = task_css_set(p);
1408 list_add(&p->cg_list, &cset->tasks);
1411 spin_unlock_irq(&p->sighand->siglock);
1412 } while_each_thread(g, p);
1413 read_unlock(&tasklist_lock);
1415 up_write(&css_set_rwsem);
1418 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1420 atomic_set(&cgrp->refcnt, 1);
1421 INIT_LIST_HEAD(&cgrp->sibling);
1422 INIT_LIST_HEAD(&cgrp->children);
1423 INIT_LIST_HEAD(&cgrp->cset_links);
1424 INIT_LIST_HEAD(&cgrp->release_list);
1425 INIT_LIST_HEAD(&cgrp->pidlists);
1426 mutex_init(&cgrp->pidlist_mutex);
1427 cgrp->dummy_css.cgroup = cgrp;
1430 static void init_cgroup_root(struct cgroup_root *root,
1431 struct cgroup_sb_opts *opts)
1433 struct cgroup *cgrp = &root->cgrp;
1435 INIT_LIST_HEAD(&root->root_list);
1436 atomic_set(&root->nr_cgrps, 1);
1438 init_cgroup_housekeeping(cgrp);
1439 idr_init(&root->cgroup_idr);
1441 root->flags = opts->flags;
1442 if (opts->release_agent)
1443 strcpy(root->release_agent_path, opts->release_agent);
1445 strcpy(root->name, opts->name);
1446 if (opts->cpuset_clone_children)
1447 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1450 static int cgroup_setup_root(struct cgroup_root *root, unsigned long ss_mask)
1452 LIST_HEAD(tmp_links);
1453 struct cgroup *root_cgrp = &root->cgrp;
1454 struct css_set *cset;
1457 lockdep_assert_held(&cgroup_tree_mutex);
1458 lockdep_assert_held(&cgroup_mutex);
1460 ret = idr_alloc(&root->cgroup_idr, root_cgrp, 0, 1, GFP_KERNEL);
1463 root_cgrp->id = ret;
1466 * We're accessing css_set_count without locking css_set_rwsem here,
1467 * but that's OK - it can only be increased by someone holding
1468 * cgroup_lock, and that's us. The worst that can happen is that we
1469 * have some link structures left over
1471 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1475 ret = cgroup_init_root_id(root);
1479 root->kf_root = kernfs_create_root(&cgroup_kf_syscall_ops,
1480 KERNFS_ROOT_CREATE_DEACTIVATED,
1482 if (IS_ERR(root->kf_root)) {
1483 ret = PTR_ERR(root->kf_root);
1486 root_cgrp->kn = root->kf_root->kn;
1488 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1492 ret = rebind_subsystems(root, ss_mask);
1497 * There must be no failure case after here, since rebinding takes
1498 * care of subsystems' refcounts, which are explicitly dropped in
1499 * the failure exit path.
1501 list_add(&root->root_list, &cgroup_roots);
1502 cgroup_root_count++;
1505 * Link the root cgroup in this hierarchy into all the css_set
1508 down_write(&css_set_rwsem);
1509 hash_for_each(css_set_table, i, cset, hlist)
1510 link_css_set(&tmp_links, cset, root_cgrp);
1511 up_write(&css_set_rwsem);
1513 BUG_ON(!list_empty(&root_cgrp->children));
1514 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
1516 kernfs_activate(root_cgrp->kn);
1521 kernfs_destroy_root(root->kf_root);
1522 root->kf_root = NULL;
1524 cgroup_exit_root_id(root);
1526 free_cgrp_cset_links(&tmp_links);
1530 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1531 int flags, const char *unused_dev_name,
1534 struct cgroup_root *root;
1535 struct cgroup_sb_opts opts;
1536 struct dentry *dentry;
1541 * The first time anyone tries to mount a cgroup, enable the list
1542 * linking each css_set to its tasks and fix up all existing tasks.
1544 if (!use_task_css_set_links)
1545 cgroup_enable_task_cg_lists();
1547 mutex_lock(&cgroup_tree_mutex);
1548 mutex_lock(&cgroup_mutex);
1550 /* First find the desired set of subsystems */
1551 ret = parse_cgroupfs_options(data, &opts);
1555 /* look for a matching existing root */
1556 if (!opts.subsys_mask && !opts.none && !opts.name) {
1557 cgrp_dfl_root_visible = true;
1558 root = &cgrp_dfl_root;
1559 cgroup_get(&root->cgrp);
1564 for_each_root(root) {
1565 bool name_match = false;
1567 if (root == &cgrp_dfl_root)
1571 * If we asked for a name then it must match. Also, if
1572 * name matches but sybsys_mask doesn't, we should fail.
1573 * Remember whether name matched.
1576 if (strcmp(opts.name, root->name))
1582 * If we asked for subsystems (or explicitly for no
1583 * subsystems) then they must match.
1585 if ((opts.subsys_mask || opts.none) &&
1586 (opts.subsys_mask != root->subsys_mask)) {
1593 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1594 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1595 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1599 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1604 * A root's lifetime is governed by its root cgroup. Zero
1605 * ref indicate that the root is being destroyed. Wait for
1606 * destruction to complete so that the subsystems are free.
1607 * We can use wait_queue for the wait but this path is
1608 * super cold. Let's just sleep for a bit and retry.
1610 if (!atomic_inc_not_zero(&root->cgrp.refcnt)) {
1611 mutex_unlock(&cgroup_mutex);
1612 mutex_unlock(&cgroup_tree_mutex);
1614 mutex_lock(&cgroup_tree_mutex);
1615 mutex_lock(&cgroup_mutex);
1624 * No such thing, create a new one. name= matching without subsys
1625 * specification is allowed for already existing hierarchies but we
1626 * can't create new one without subsys specification.
1628 if (!opts.subsys_mask && !opts.none) {
1633 root = kzalloc(sizeof(*root), GFP_KERNEL);
1639 init_cgroup_root(root, &opts);
1641 ret = cgroup_setup_root(root, opts.subsys_mask);
1643 cgroup_free_root(root);
1646 mutex_unlock(&cgroup_mutex);
1647 mutex_unlock(&cgroup_tree_mutex);
1649 kfree(opts.release_agent);
1653 return ERR_PTR(ret);
1655 dentry = kernfs_mount(fs_type, flags, root->kf_root, &new_sb);
1656 if (IS_ERR(dentry) || !new_sb)
1657 cgroup_put(&root->cgrp);
1661 static void cgroup_kill_sb(struct super_block *sb)
1663 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
1664 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1666 cgroup_put(&root->cgrp);
1670 static struct file_system_type cgroup_fs_type = {
1672 .mount = cgroup_mount,
1673 .kill_sb = cgroup_kill_sb,
1676 static struct kobject *cgroup_kobj;
1679 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1680 * @task: target task
1681 * @buf: the buffer to write the path into
1682 * @buflen: the length of the buffer
1684 * Determine @task's cgroup on the first (the one with the lowest non-zero
1685 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1686 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1687 * cgroup controller callbacks.
1689 * Return value is the same as kernfs_path().
1691 char *task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1693 struct cgroup_root *root;
1694 struct cgroup *cgrp;
1695 int hierarchy_id = 1;
1698 mutex_lock(&cgroup_mutex);
1699 down_read(&css_set_rwsem);
1701 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1704 cgrp = task_cgroup_from_root(task, root);
1705 path = cgroup_path(cgrp, buf, buflen);
1707 /* if no hierarchy exists, everyone is in "/" */
1708 if (strlcpy(buf, "/", buflen) < buflen)
1712 up_read(&css_set_rwsem);
1713 mutex_unlock(&cgroup_mutex);
1716 EXPORT_SYMBOL_GPL(task_cgroup_path);
1718 /* used to track tasks and other necessary states during migration */
1719 struct cgroup_taskset {
1720 /* the src and dst cset list running through cset->mg_node */
1721 struct list_head src_csets;
1722 struct list_head dst_csets;
1725 * Fields for cgroup_taskset_*() iteration.
1727 * Before migration is committed, the target migration tasks are on
1728 * ->mg_tasks of the csets on ->src_csets. After, on ->mg_tasks of
1729 * the csets on ->dst_csets. ->csets point to either ->src_csets
1730 * or ->dst_csets depending on whether migration is committed.
1732 * ->cur_csets and ->cur_task point to the current task position
1735 struct list_head *csets;
1736 struct css_set *cur_cset;
1737 struct task_struct *cur_task;
1741 * cgroup_taskset_first - reset taskset and return the first task
1742 * @tset: taskset of interest
1744 * @tset iteration is initialized and the first task is returned.
1746 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1748 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
1749 tset->cur_task = NULL;
1751 return cgroup_taskset_next(tset);
1755 * cgroup_taskset_next - iterate to the next task in taskset
1756 * @tset: taskset of interest
1758 * Return the next task in @tset. Iteration must have been initialized
1759 * with cgroup_taskset_first().
1761 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1763 struct css_set *cset = tset->cur_cset;
1764 struct task_struct *task = tset->cur_task;
1766 while (&cset->mg_node != tset->csets) {
1768 task = list_first_entry(&cset->mg_tasks,
1769 struct task_struct, cg_list);
1771 task = list_next_entry(task, cg_list);
1773 if (&task->cg_list != &cset->mg_tasks) {
1774 tset->cur_cset = cset;
1775 tset->cur_task = task;
1779 cset = list_next_entry(cset, mg_node);
1787 * cgroup_task_migrate - move a task from one cgroup to another.
1788 * @old_cgrp; the cgroup @tsk is being migrated from
1789 * @tsk: the task being migrated
1790 * @new_cset: the new css_set @tsk is being attached to
1792 * Must be called with cgroup_mutex, threadgroup and css_set_rwsem locked.
1794 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1795 struct task_struct *tsk,
1796 struct css_set *new_cset)
1798 struct css_set *old_cset;
1800 lockdep_assert_held(&cgroup_mutex);
1801 lockdep_assert_held(&css_set_rwsem);
1804 * We are synchronized through threadgroup_lock() against PF_EXITING
1805 * setting such that we can't race against cgroup_exit() changing the
1806 * css_set to init_css_set and dropping the old one.
1808 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1809 old_cset = task_css_set(tsk);
1811 get_css_set(new_cset);
1812 rcu_assign_pointer(tsk->cgroups, new_cset);
1815 * Use move_tail so that cgroup_taskset_first() still returns the
1816 * leader after migration. This works because cgroup_migrate()
1817 * ensures that the dst_cset of the leader is the first on the
1818 * tset's dst_csets list.
1820 list_move_tail(&tsk->cg_list, &new_cset->mg_tasks);
1823 * We just gained a reference on old_cset by taking it from the
1824 * task. As trading it for new_cset is protected by cgroup_mutex,
1825 * we're safe to drop it here; it will be freed under RCU.
1827 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1828 put_css_set_locked(old_cset, false);
1832 * cgroup_migrate_finish - cleanup after attach
1833 * @preloaded_csets: list of preloaded css_sets
1835 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
1836 * those functions for details.
1838 static void cgroup_migrate_finish(struct list_head *preloaded_csets)
1840 struct css_set *cset, *tmp_cset;
1842 lockdep_assert_held(&cgroup_mutex);
1844 down_write(&css_set_rwsem);
1845 list_for_each_entry_safe(cset, tmp_cset, preloaded_csets, mg_preload_node) {
1846 cset->mg_src_cgrp = NULL;
1847 cset->mg_dst_cset = NULL;
1848 list_del_init(&cset->mg_preload_node);
1849 put_css_set_locked(cset, false);
1851 up_write(&css_set_rwsem);
1855 * cgroup_migrate_add_src - add a migration source css_set
1856 * @src_cset: the source css_set to add
1857 * @dst_cgrp: the destination cgroup
1858 * @preloaded_csets: list of preloaded css_sets
1860 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
1861 * @src_cset and add it to @preloaded_csets, which should later be cleaned
1862 * up by cgroup_migrate_finish().
1864 * This function may be called without holding threadgroup_lock even if the
1865 * target is a process. Threads may be created and destroyed but as long
1866 * as cgroup_mutex is not dropped, no new css_set can be put into play and
1867 * the preloaded css_sets are guaranteed to cover all migrations.
1869 static void cgroup_migrate_add_src(struct css_set *src_cset,
1870 struct cgroup *dst_cgrp,
1871 struct list_head *preloaded_csets)
1873 struct cgroup *src_cgrp;
1875 lockdep_assert_held(&cgroup_mutex);
1876 lockdep_assert_held(&css_set_rwsem);
1878 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
1880 /* nothing to do if this cset already belongs to the cgroup */
1881 if (src_cgrp == dst_cgrp)
1884 if (!list_empty(&src_cset->mg_preload_node))
1887 WARN_ON(src_cset->mg_src_cgrp);
1888 WARN_ON(!list_empty(&src_cset->mg_tasks));
1889 WARN_ON(!list_empty(&src_cset->mg_node));
1891 src_cset->mg_src_cgrp = src_cgrp;
1892 get_css_set(src_cset);
1893 list_add(&src_cset->mg_preload_node, preloaded_csets);
1897 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
1898 * @dst_cgrp: the destination cgroup
1899 * @preloaded_csets: list of preloaded source css_sets
1901 * Tasks are about to be moved to @dst_cgrp and all the source css_sets
1902 * have been preloaded to @preloaded_csets. This function looks up and
1903 * pins all destination css_sets, links each to its source, and put them on
1906 * This function must be called after cgroup_migrate_add_src() has been
1907 * called on each migration source css_set. After migration is performed
1908 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
1911 static int cgroup_migrate_prepare_dst(struct cgroup *dst_cgrp,
1912 struct list_head *preloaded_csets)
1915 struct css_set *src_cset;
1917 lockdep_assert_held(&cgroup_mutex);
1919 /* look up the dst cset for each src cset and link it to src */
1920 list_for_each_entry(src_cset, preloaded_csets, mg_preload_node) {
1921 struct css_set *dst_cset;
1923 dst_cset = find_css_set(src_cset, dst_cgrp);
1927 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
1928 src_cset->mg_dst_cset = dst_cset;
1930 if (list_empty(&dst_cset->mg_preload_node))
1931 list_add(&dst_cset->mg_preload_node, &csets);
1933 put_css_set(dst_cset, false);
1936 list_splice(&csets, preloaded_csets);
1939 cgroup_migrate_finish(&csets);
1944 * cgroup_migrate - migrate a process or task to a cgroup
1945 * @cgrp: the destination cgroup
1946 * @leader: the leader of the process or the task to migrate
1947 * @threadgroup: whether @leader points to the whole process or a single task
1949 * Migrate a process or task denoted by @leader to @cgrp. If migrating a
1950 * process, the caller must be holding threadgroup_lock of @leader. The
1951 * caller is also responsible for invoking cgroup_migrate_add_src() and
1952 * cgroup_migrate_prepare_dst() on the targets before invoking this
1953 * function and following up with cgroup_migrate_finish().
1955 * As long as a controller's ->can_attach() doesn't fail, this function is
1956 * guaranteed to succeed. This means that, excluding ->can_attach()
1957 * failure, when migrating multiple targets, the success or failure can be
1958 * decided for all targets by invoking group_migrate_prepare_dst() before
1959 * actually starting migrating.
1961 static int cgroup_migrate(struct cgroup *cgrp, struct task_struct *leader,
1964 struct cgroup_taskset tset = {
1965 .src_csets = LIST_HEAD_INIT(tset.src_csets),
1966 .dst_csets = LIST_HEAD_INIT(tset.dst_csets),
1967 .csets = &tset.src_csets,
1969 struct cgroup_subsys_state *css, *failed_css = NULL;
1970 struct css_set *cset, *tmp_cset;
1971 struct task_struct *task, *tmp_task;
1975 * Prevent freeing of tasks while we take a snapshot. Tasks that are
1976 * already PF_EXITING could be freed from underneath us unless we
1977 * take an rcu_read_lock.
1979 down_write(&css_set_rwsem);
1983 /* @task either already exited or can't exit until the end */
1984 if (task->flags & PF_EXITING)
1987 /* leave @task alone if post_fork() hasn't linked it yet */
1988 if (list_empty(&task->cg_list))
1991 cset = task_css_set(task);
1992 if (!cset->mg_src_cgrp)
1996 * cgroup_taskset_first() must always return the leader.
1997 * Take care to avoid disturbing the ordering.
1999 list_move_tail(&task->cg_list, &cset->mg_tasks);
2000 if (list_empty(&cset->mg_node))
2001 list_add_tail(&cset->mg_node, &tset.src_csets);
2002 if (list_empty(&cset->mg_dst_cset->mg_node))
2003 list_move_tail(&cset->mg_dst_cset->mg_node,
2008 } while_each_thread(leader, task);
2010 up_write(&css_set_rwsem);
2012 /* methods shouldn't be called if no task is actually migrating */
2013 if (list_empty(&tset.src_csets))
2016 /* check that we can legitimately attach to the cgroup */
2017 for_each_e_css(css, i, cgrp) {
2018 if (css->ss->can_attach) {
2019 ret = css->ss->can_attach(css, &tset);
2022 goto out_cancel_attach;
2028 * Now that we're guaranteed success, proceed to move all tasks to
2029 * the new cgroup. There are no failure cases after here, so this
2030 * is the commit point.
2032 down_write(&css_set_rwsem);
2033 list_for_each_entry(cset, &tset.src_csets, mg_node) {
2034 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list)
2035 cgroup_task_migrate(cset->mg_src_cgrp, task,
2038 up_write(&css_set_rwsem);
2041 * Migration is committed, all target tasks are now on dst_csets.
2042 * Nothing is sensitive to fork() after this point. Notify
2043 * controllers that migration is complete.
2045 tset.csets = &tset.dst_csets;
2047 for_each_e_css(css, i, cgrp)
2048 if (css->ss->attach)
2049 css->ss->attach(css, &tset);
2052 goto out_release_tset;
2055 for_each_e_css(css, i, cgrp) {
2056 if (css == failed_css)
2058 if (css->ss->cancel_attach)
2059 css->ss->cancel_attach(css, &tset);
2062 down_write(&css_set_rwsem);
2063 list_splice_init(&tset.dst_csets, &tset.src_csets);
2064 list_for_each_entry_safe(cset, tmp_cset, &tset.src_csets, mg_node) {
2065 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2066 list_del_init(&cset->mg_node);
2068 up_write(&css_set_rwsem);
2073 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2074 * @dst_cgrp: the cgroup to attach to
2075 * @leader: the task or the leader of the threadgroup to be attached
2076 * @threadgroup: attach the whole threadgroup?
2078 * Call holding cgroup_mutex and threadgroup_lock of @leader.
2080 static int cgroup_attach_task(struct cgroup *dst_cgrp,
2081 struct task_struct *leader, bool threadgroup)
2083 LIST_HEAD(preloaded_csets);
2084 struct task_struct *task;
2087 /* look up all src csets */
2088 down_read(&css_set_rwsem);
2092 cgroup_migrate_add_src(task_css_set(task), dst_cgrp,
2096 } while_each_thread(leader, task);
2098 up_read(&css_set_rwsem);
2100 /* prepare dst csets and commit */
2101 ret = cgroup_migrate_prepare_dst(dst_cgrp, &preloaded_csets);
2103 ret = cgroup_migrate(dst_cgrp, leader, threadgroup);
2105 cgroup_migrate_finish(&preloaded_csets);
2110 * Find the task_struct of the task to attach by vpid and pass it along to the
2111 * function to attach either it or all tasks in its threadgroup. Will lock
2112 * cgroup_mutex and threadgroup.
2114 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2116 struct task_struct *tsk;
2117 const struct cred *cred = current_cred(), *tcred;
2120 if (!cgroup_lock_live_group(cgrp))
2126 tsk = find_task_by_vpid(pid);
2130 goto out_unlock_cgroup;
2133 * even if we're attaching all tasks in the thread group, we
2134 * only need to check permissions on one of them.
2136 tcred = __task_cred(tsk);
2137 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2138 !uid_eq(cred->euid, tcred->uid) &&
2139 !uid_eq(cred->euid, tcred->suid)) {
2142 goto out_unlock_cgroup;
2148 tsk = tsk->group_leader;
2151 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2152 * trapped in a cpuset, or RT worker may be born in a cgroup
2153 * with no rt_runtime allocated. Just say no.
2155 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2158 goto out_unlock_cgroup;
2161 get_task_struct(tsk);
2164 threadgroup_lock(tsk);
2166 if (!thread_group_leader(tsk)) {
2168 * a race with de_thread from another thread's exec()
2169 * may strip us of our leadership, if this happens,
2170 * there is no choice but to throw this task away and
2171 * try again; this is
2172 * "double-double-toil-and-trouble-check locking".
2174 threadgroup_unlock(tsk);
2175 put_task_struct(tsk);
2176 goto retry_find_task;
2180 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2182 threadgroup_unlock(tsk);
2184 put_task_struct(tsk);
2186 mutex_unlock(&cgroup_mutex);
2191 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2192 * @from: attach to all cgroups of a given task
2193 * @tsk: the task to be attached
2195 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2197 struct cgroup_root *root;
2200 mutex_lock(&cgroup_mutex);
2201 for_each_root(root) {
2202 struct cgroup *from_cgrp;
2204 if (root == &cgrp_dfl_root)
2207 down_read(&css_set_rwsem);
2208 from_cgrp = task_cgroup_from_root(from, root);
2209 up_read(&css_set_rwsem);
2211 retval = cgroup_attach_task(from_cgrp, tsk, false);
2215 mutex_unlock(&cgroup_mutex);
2219 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2221 static int cgroup_tasks_write(struct cgroup_subsys_state *css,
2222 struct cftype *cft, u64 pid)
2224 return attach_task_by_pid(css->cgroup, pid, false);
2227 static int cgroup_procs_write(struct cgroup_subsys_state *css,
2228 struct cftype *cft, u64 tgid)
2230 return attach_task_by_pid(css->cgroup, tgid, true);
2233 static int cgroup_release_agent_write(struct cgroup_subsys_state *css,
2234 struct cftype *cft, char *buffer)
2236 struct cgroup_root *root = css->cgroup->root;
2238 BUILD_BUG_ON(sizeof(root->release_agent_path) < PATH_MAX);
2239 if (!cgroup_lock_live_group(css->cgroup))
2241 spin_lock(&release_agent_path_lock);
2242 strlcpy(root->release_agent_path, buffer,
2243 sizeof(root->release_agent_path));
2244 spin_unlock(&release_agent_path_lock);
2245 mutex_unlock(&cgroup_mutex);
2249 static int cgroup_release_agent_show(struct seq_file *seq, void *v)
2251 struct cgroup *cgrp = seq_css(seq)->cgroup;
2253 if (!cgroup_lock_live_group(cgrp))
2255 seq_puts(seq, cgrp->root->release_agent_path);
2256 seq_putc(seq, '\n');
2257 mutex_unlock(&cgroup_mutex);
2261 static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
2263 struct cgroup *cgrp = seq_css(seq)->cgroup;
2265 seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
2269 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
2270 size_t nbytes, loff_t off)
2272 struct cgroup *cgrp = of->kn->parent->priv;
2273 struct cftype *cft = of->kn->priv;
2274 struct cgroup_subsys_state *css;
2278 * kernfs guarantees that a file isn't deleted with operations in
2279 * flight, which means that the matching css is and stays alive and
2280 * doesn't need to be pinned. The RCU locking is not necessary
2281 * either. It's just for the convenience of using cgroup_css().
2284 css = cgroup_css(cgrp, cft->ss);
2287 if (cft->write_string) {
2288 ret = cft->write_string(css, cft, strstrip(buf));
2289 } else if (cft->write_u64) {
2290 unsigned long long v;
2291 ret = kstrtoull(buf, 0, &v);
2293 ret = cft->write_u64(css, cft, v);
2294 } else if (cft->write_s64) {
2296 ret = kstrtoll(buf, 0, &v);
2298 ret = cft->write_s64(css, cft, v);
2299 } else if (cft->trigger) {
2300 ret = cft->trigger(css, (unsigned int)cft->private);
2305 return ret ?: nbytes;
2308 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
2310 return seq_cft(seq)->seq_start(seq, ppos);
2313 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
2315 return seq_cft(seq)->seq_next(seq, v, ppos);
2318 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
2320 seq_cft(seq)->seq_stop(seq, v);
2323 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2325 struct cftype *cft = seq_cft(m);
2326 struct cgroup_subsys_state *css = seq_css(m);
2329 return cft->seq_show(m, arg);
2332 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
2333 else if (cft->read_s64)
2334 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
2340 static struct kernfs_ops cgroup_kf_single_ops = {
2341 .atomic_write_len = PAGE_SIZE,
2342 .write = cgroup_file_write,
2343 .seq_show = cgroup_seqfile_show,
2346 static struct kernfs_ops cgroup_kf_ops = {
2347 .atomic_write_len = PAGE_SIZE,
2348 .write = cgroup_file_write,
2349 .seq_start = cgroup_seqfile_start,
2350 .seq_next = cgroup_seqfile_next,
2351 .seq_stop = cgroup_seqfile_stop,
2352 .seq_show = cgroup_seqfile_show,
2356 * cgroup_rename - Only allow simple rename of directories in place.
2358 static int cgroup_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
2359 const char *new_name_str)
2361 struct cgroup *cgrp = kn->priv;
2364 if (kernfs_type(kn) != KERNFS_DIR)
2366 if (kn->parent != new_parent)
2370 * This isn't a proper migration and its usefulness is very
2371 * limited. Disallow if sane_behavior.
2373 if (cgroup_sane_behavior(cgrp))
2377 * We're gonna grab cgroup_tree_mutex which nests outside kernfs
2378 * active_ref. kernfs_rename() doesn't require active_ref
2379 * protection. Break them before grabbing cgroup_tree_mutex.
2381 kernfs_break_active_protection(new_parent);
2382 kernfs_break_active_protection(kn);
2384 mutex_lock(&cgroup_tree_mutex);
2385 mutex_lock(&cgroup_mutex);
2387 ret = kernfs_rename(kn, new_parent, new_name_str);
2389 mutex_unlock(&cgroup_mutex);
2390 mutex_unlock(&cgroup_tree_mutex);
2392 kernfs_unbreak_active_protection(kn);
2393 kernfs_unbreak_active_protection(new_parent);
2397 /* set uid and gid of cgroup dirs and files to that of the creator */
2398 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
2400 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
2401 .ia_uid = current_fsuid(),
2402 .ia_gid = current_fsgid(), };
2404 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
2405 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
2408 return kernfs_setattr(kn, &iattr);
2411 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2413 char name[CGROUP_FILE_NAME_MAX];
2414 struct kernfs_node *kn;
2415 struct lock_class_key *key = NULL;
2418 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2419 key = &cft->lockdep_key;
2421 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
2422 cgroup_file_mode(cft), 0, cft->kf_ops, cft,
2427 ret = cgroup_kn_set_ugid(kn);
2434 * cgroup_addrm_files - add or remove files to a cgroup directory
2435 * @cgrp: the target cgroup
2436 * @cfts: array of cftypes to be added
2437 * @is_add: whether to add or remove
2439 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2440 * For removals, this function never fails. If addition fails, this
2441 * function doesn't remove files already added. The caller is responsible
2444 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2450 lockdep_assert_held(&cgroup_tree_mutex);
2452 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2453 /* does cft->flags tell us to skip this file on @cgrp? */
2454 if ((cft->flags & CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
2456 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2458 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2460 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2464 ret = cgroup_add_file(cgrp, cft);
2466 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2471 cgroup_rm_file(cgrp, cft);
2477 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
2480 struct cgroup_subsys *ss = cfts[0].ss;
2481 struct cgroup *root = &ss->root->cgrp;
2482 struct cgroup_subsys_state *css;
2485 lockdep_assert_held(&cgroup_tree_mutex);
2487 /* add/rm files for all cgroups created before */
2488 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2489 struct cgroup *cgrp = css->cgroup;
2491 if (cgroup_is_dead(cgrp))
2494 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2500 kernfs_activate(root->kn);
2504 static void cgroup_exit_cftypes(struct cftype *cfts)
2508 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2509 /* free copy for custom atomic_write_len, see init_cftypes() */
2510 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
2517 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2521 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2522 struct kernfs_ops *kf_ops;
2524 WARN_ON(cft->ss || cft->kf_ops);
2527 kf_ops = &cgroup_kf_ops;
2529 kf_ops = &cgroup_kf_single_ops;
2532 * Ugh... if @cft wants a custom max_write_len, we need to
2533 * make a copy of kf_ops to set its atomic_write_len.
2535 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
2536 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
2538 cgroup_exit_cftypes(cfts);
2541 kf_ops->atomic_write_len = cft->max_write_len;
2544 cft->kf_ops = kf_ops;
2551 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
2553 lockdep_assert_held(&cgroup_tree_mutex);
2555 if (!cfts || !cfts[0].ss)
2558 list_del(&cfts->node);
2559 cgroup_apply_cftypes(cfts, false);
2560 cgroup_exit_cftypes(cfts);
2565 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2566 * @cfts: zero-length name terminated array of cftypes
2568 * Unregister @cfts. Files described by @cfts are removed from all
2569 * existing cgroups and all future cgroups won't have them either. This
2570 * function can be called anytime whether @cfts' subsys is attached or not.
2572 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2575 int cgroup_rm_cftypes(struct cftype *cfts)
2579 mutex_lock(&cgroup_tree_mutex);
2580 ret = cgroup_rm_cftypes_locked(cfts);
2581 mutex_unlock(&cgroup_tree_mutex);
2586 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2587 * @ss: target cgroup subsystem
2588 * @cfts: zero-length name terminated array of cftypes
2590 * Register @cfts to @ss. Files described by @cfts are created for all
2591 * existing cgroups to which @ss is attached and all future cgroups will
2592 * have them too. This function can be called anytime whether @ss is
2595 * Returns 0 on successful registration, -errno on failure. Note that this
2596 * function currently returns 0 as long as @cfts registration is successful
2597 * even if some file creation attempts on existing cgroups fail.
2599 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2603 if (!cfts || cfts[0].name[0] == '\0')
2606 ret = cgroup_init_cftypes(ss, cfts);
2610 mutex_lock(&cgroup_tree_mutex);
2612 list_add_tail(&cfts->node, &ss->cfts);
2613 ret = cgroup_apply_cftypes(cfts, true);
2615 cgroup_rm_cftypes_locked(cfts);
2617 mutex_unlock(&cgroup_tree_mutex);
2622 * cgroup_task_count - count the number of tasks in a cgroup.
2623 * @cgrp: the cgroup in question
2625 * Return the number of tasks in the cgroup.
2627 static int cgroup_task_count(const struct cgroup *cgrp)
2630 struct cgrp_cset_link *link;
2632 down_read(&css_set_rwsem);
2633 list_for_each_entry(link, &cgrp->cset_links, cset_link)
2634 count += atomic_read(&link->cset->refcount);
2635 up_read(&css_set_rwsem);
2640 * css_next_child - find the next child of a given css
2641 * @pos_css: the current position (%NULL to initiate traversal)
2642 * @parent_css: css whose children to walk
2644 * This function returns the next child of @parent_css and should be called
2645 * under either cgroup_mutex or RCU read lock. The only requirement is
2646 * that @parent_css and @pos_css are accessible. The next sibling is
2647 * guaranteed to be returned regardless of their states.
2649 struct cgroup_subsys_state *
2650 css_next_child(struct cgroup_subsys_state *pos_css,
2651 struct cgroup_subsys_state *parent_css)
2653 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
2654 struct cgroup *cgrp = parent_css->cgroup;
2655 struct cgroup *next;
2657 cgroup_assert_mutexes_or_rcu_locked();
2660 * @pos could already have been removed. Once a cgroup is removed,
2661 * its ->sibling.next is no longer updated when its next sibling
2662 * changes. As CGRP_DEAD assertion is serialized and happens
2663 * before the cgroup is taken off the ->sibling list, if we see it
2664 * unasserted, it's guaranteed that the next sibling hasn't
2665 * finished its grace period even if it's already removed, and thus
2666 * safe to dereference from this RCU critical section. If
2667 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
2668 * to be visible as %true here.
2670 * If @pos is dead, its next pointer can't be dereferenced;
2671 * however, as each cgroup is given a monotonically increasing
2672 * unique serial number and always appended to the sibling list,
2673 * the next one can be found by walking the parent's children until
2674 * we see a cgroup with higher serial number than @pos's. While
2675 * this path can be slower, it's taken only when either the current
2676 * cgroup is removed or iteration and removal race.
2679 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
2680 } else if (likely(!cgroup_is_dead(pos))) {
2681 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
2683 list_for_each_entry_rcu(next, &cgrp->children, sibling)
2684 if (next->serial_nr > pos->serial_nr)
2688 if (&next->sibling == &cgrp->children)
2691 return cgroup_css(next, parent_css->ss);
2695 * css_next_descendant_pre - find the next descendant for pre-order walk
2696 * @pos: the current position (%NULL to initiate traversal)
2697 * @root: css whose descendants to walk
2699 * To be used by css_for_each_descendant_pre(). Find the next descendant
2700 * to visit for pre-order traversal of @root's descendants. @root is
2701 * included in the iteration and the first node to be visited.
2703 * While this function requires cgroup_mutex or RCU read locking, it
2704 * doesn't require the whole traversal to be contained in a single critical
2705 * section. This function will return the correct next descendant as long
2706 * as both @pos and @root are accessible and @pos is a descendant of @root.
2708 struct cgroup_subsys_state *
2709 css_next_descendant_pre(struct cgroup_subsys_state *pos,
2710 struct cgroup_subsys_state *root)
2712 struct cgroup_subsys_state *next;
2714 cgroup_assert_mutexes_or_rcu_locked();
2716 /* if first iteration, visit @root */
2720 /* visit the first child if exists */
2721 next = css_next_child(NULL, pos);
2725 /* no child, visit my or the closest ancestor's next sibling */
2726 while (pos != root) {
2727 next = css_next_child(pos, css_parent(pos));
2730 pos = css_parent(pos);
2737 * css_rightmost_descendant - return the rightmost descendant of a css
2738 * @pos: css of interest
2740 * Return the rightmost descendant of @pos. If there's no descendant, @pos
2741 * is returned. This can be used during pre-order traversal to skip
2744 * While this function requires cgroup_mutex or RCU read locking, it
2745 * doesn't require the whole traversal to be contained in a single critical
2746 * section. This function will return the correct rightmost descendant as
2747 * long as @pos is accessible.
2749 struct cgroup_subsys_state *
2750 css_rightmost_descendant(struct cgroup_subsys_state *pos)
2752 struct cgroup_subsys_state *last, *tmp;
2754 cgroup_assert_mutexes_or_rcu_locked();
2758 /* ->prev isn't RCU safe, walk ->next till the end */
2760 css_for_each_child(tmp, last)
2767 static struct cgroup_subsys_state *
2768 css_leftmost_descendant(struct cgroup_subsys_state *pos)
2770 struct cgroup_subsys_state *last;
2774 pos = css_next_child(NULL, pos);
2781 * css_next_descendant_post - find the next descendant for post-order walk
2782 * @pos: the current position (%NULL to initiate traversal)
2783 * @root: css whose descendants to walk
2785 * To be used by css_for_each_descendant_post(). Find the next descendant
2786 * to visit for post-order traversal of @root's descendants. @root is
2787 * included in the iteration and the last node to be visited.
2789 * While this function requires cgroup_mutex or RCU read locking, it
2790 * doesn't require the whole traversal to be contained in a single critical
2791 * section. This function will return the correct next descendant as long
2792 * as both @pos and @cgroup are accessible and @pos is a descendant of
2795 struct cgroup_subsys_state *
2796 css_next_descendant_post(struct cgroup_subsys_state *pos,
2797 struct cgroup_subsys_state *root)
2799 struct cgroup_subsys_state *next;
2801 cgroup_assert_mutexes_or_rcu_locked();
2803 /* if first iteration, visit leftmost descendant which may be @root */
2805 return css_leftmost_descendant(root);
2807 /* if we visited @root, we're done */
2811 /* if there's an unvisited sibling, visit its leftmost descendant */
2812 next = css_next_child(pos, css_parent(pos));
2814 return css_leftmost_descendant(next);
2816 /* no sibling left, visit parent */
2817 return css_parent(pos);
2821 * css_advance_task_iter - advance a task itererator to the next css_set
2822 * @it: the iterator to advance
2824 * Advance @it to the next css_set to walk.
2826 static void css_advance_task_iter(struct css_task_iter *it)
2828 struct list_head *l = it->cset_link;
2829 struct cgrp_cset_link *link;
2830 struct css_set *cset;
2832 /* Advance to the next non-empty css_set */
2835 if (l == &it->origin_css->cgroup->cset_links) {
2836 it->cset_link = NULL;
2839 link = list_entry(l, struct cgrp_cset_link, cset_link);
2841 } while (list_empty(&cset->tasks) && list_empty(&cset->mg_tasks));
2845 if (!list_empty(&cset->tasks))
2846 it->task = cset->tasks.next;
2848 it->task = cset->mg_tasks.next;
2852 * css_task_iter_start - initiate task iteration
2853 * @css: the css to walk tasks of
2854 * @it: the task iterator to use
2856 * Initiate iteration through the tasks of @css. The caller can call
2857 * css_task_iter_next() to walk through the tasks until the function
2858 * returns NULL. On completion of iteration, css_task_iter_end() must be
2861 * Note that this function acquires a lock which is released when the
2862 * iteration finishes. The caller can't sleep while iteration is in
2865 void css_task_iter_start(struct cgroup_subsys_state *css,
2866 struct css_task_iter *it)
2867 __acquires(css_set_rwsem)
2869 /* no one should try to iterate before mounting cgroups */
2870 WARN_ON_ONCE(!use_task_css_set_links);
2872 down_read(&css_set_rwsem);
2874 it->origin_css = css;
2875 it->cset_link = &css->cgroup->cset_links;
2877 css_advance_task_iter(it);
2881 * css_task_iter_next - return the next task for the iterator
2882 * @it: the task iterator being iterated
2884 * The "next" function for task iteration. @it should have been
2885 * initialized via css_task_iter_start(). Returns NULL when the iteration
2888 struct task_struct *css_task_iter_next(struct css_task_iter *it)
2890 struct task_struct *res;
2891 struct list_head *l = it->task;
2892 struct cgrp_cset_link *link = list_entry(it->cset_link,
2893 struct cgrp_cset_link, cset_link);
2895 /* If the iterator cg is NULL, we have no tasks */
2898 res = list_entry(l, struct task_struct, cg_list);
2901 * Advance iterator to find next entry. cset->tasks is consumed
2902 * first and then ->mg_tasks. After ->mg_tasks, we move onto the
2907 if (l == &link->cset->tasks)
2908 l = link->cset->mg_tasks.next;
2910 if (l == &link->cset->mg_tasks)
2911 css_advance_task_iter(it);
2919 * css_task_iter_end - finish task iteration
2920 * @it: the task iterator to finish
2922 * Finish task iteration started by css_task_iter_start().
2924 void css_task_iter_end(struct css_task_iter *it)
2925 __releases(css_set_rwsem)
2927 up_read(&css_set_rwsem);
2931 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
2932 * @to: cgroup to which the tasks will be moved
2933 * @from: cgroup in which the tasks currently reside
2935 * Locking rules between cgroup_post_fork() and the migration path
2936 * guarantee that, if a task is forking while being migrated, the new child
2937 * is guaranteed to be either visible in the source cgroup after the
2938 * parent's migration is complete or put into the target cgroup. No task
2939 * can slip out of migration through forking.
2941 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
2943 LIST_HEAD(preloaded_csets);
2944 struct cgrp_cset_link *link;
2945 struct css_task_iter it;
2946 struct task_struct *task;
2949 mutex_lock(&cgroup_mutex);
2951 /* all tasks in @from are being moved, all csets are source */
2952 down_read(&css_set_rwsem);
2953 list_for_each_entry(link, &from->cset_links, cset_link)
2954 cgroup_migrate_add_src(link->cset, to, &preloaded_csets);
2955 up_read(&css_set_rwsem);
2957 ret = cgroup_migrate_prepare_dst(to, &preloaded_csets);
2962 * Migrate tasks one-by-one until @form is empty. This fails iff
2963 * ->can_attach() fails.
2966 css_task_iter_start(&from->dummy_css, &it);
2967 task = css_task_iter_next(&it);
2969 get_task_struct(task);
2970 css_task_iter_end(&it);
2973 ret = cgroup_migrate(to, task, false);
2974 put_task_struct(task);
2976 } while (task && !ret);
2978 cgroup_migrate_finish(&preloaded_csets);
2979 mutex_unlock(&cgroup_mutex);
2984 * Stuff for reading the 'tasks'/'procs' files.
2986 * Reading this file can return large amounts of data if a cgroup has
2987 * *lots* of attached tasks. So it may need several calls to read(),
2988 * but we cannot guarantee that the information we produce is correct
2989 * unless we produce it entirely atomically.
2993 /* which pidlist file are we talking about? */
2994 enum cgroup_filetype {
3000 * A pidlist is a list of pids that virtually represents the contents of one
3001 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3002 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3005 struct cgroup_pidlist {
3007 * used to find which pidlist is wanted. doesn't change as long as
3008 * this particular list stays in the list.
3010 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3013 /* how many elements the above list has */
3015 /* each of these stored in a list by its cgroup */
3016 struct list_head links;
3017 /* pointer to the cgroup we belong to, for list removal purposes */
3018 struct cgroup *owner;
3019 /* for delayed destruction */
3020 struct delayed_work destroy_dwork;
3024 * The following two functions "fix" the issue where there are more pids
3025 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3026 * TODO: replace with a kernel-wide solution to this problem
3028 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3029 static void *pidlist_allocate(int count)
3031 if (PIDLIST_TOO_LARGE(count))
3032 return vmalloc(count * sizeof(pid_t));
3034 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3037 static void pidlist_free(void *p)
3039 if (is_vmalloc_addr(p))
3046 * Used to destroy all pidlists lingering waiting for destroy timer. None
3047 * should be left afterwards.
3049 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
3051 struct cgroup_pidlist *l, *tmp_l;
3053 mutex_lock(&cgrp->pidlist_mutex);
3054 list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
3055 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
3056 mutex_unlock(&cgrp->pidlist_mutex);
3058 flush_workqueue(cgroup_pidlist_destroy_wq);
3059 BUG_ON(!list_empty(&cgrp->pidlists));
3062 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
3064 struct delayed_work *dwork = to_delayed_work(work);
3065 struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
3067 struct cgroup_pidlist *tofree = NULL;
3069 mutex_lock(&l->owner->pidlist_mutex);
3072 * Destroy iff we didn't get queued again. The state won't change
3073 * as destroy_dwork can only be queued while locked.
3075 if (!delayed_work_pending(dwork)) {
3076 list_del(&l->links);
3077 pidlist_free(l->list);
3078 put_pid_ns(l->key.ns);
3082 mutex_unlock(&l->owner->pidlist_mutex);
3087 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3088 * Returns the number of unique elements.
3090 static int pidlist_uniq(pid_t *list, int length)
3095 * we presume the 0th element is unique, so i starts at 1. trivial
3096 * edge cases first; no work needs to be done for either
3098 if (length == 0 || length == 1)
3100 /* src and dest walk down the list; dest counts unique elements */
3101 for (src = 1; src < length; src++) {
3102 /* find next unique element */
3103 while (list[src] == list[src-1]) {
3108 /* dest always points to where the next unique element goes */
3109 list[dest] = list[src];
3117 * The two pid files - task and cgroup.procs - guaranteed that the result
3118 * is sorted, which forced this whole pidlist fiasco. As pid order is
3119 * different per namespace, each namespace needs differently sorted list,
3120 * making it impossible to use, for example, single rbtree of member tasks
3121 * sorted by task pointer. As pidlists can be fairly large, allocating one
3122 * per open file is dangerous, so cgroup had to implement shared pool of
3123 * pidlists keyed by cgroup and namespace.
3125 * All this extra complexity was caused by the original implementation
3126 * committing to an entirely unnecessary property. In the long term, we
3127 * want to do away with it. Explicitly scramble sort order if
3128 * sane_behavior so that no such expectation exists in the new interface.
3130 * Scrambling is done by swapping every two consecutive bits, which is
3131 * non-identity one-to-one mapping which disturbs sort order sufficiently.
3133 static pid_t pid_fry(pid_t pid)
3135 unsigned a = pid & 0x55555555;
3136 unsigned b = pid & 0xAAAAAAAA;
3138 return (a << 1) | (b >> 1);
3141 static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
3143 if (cgroup_sane_behavior(cgrp))
3144 return pid_fry(pid);
3149 static int cmppid(const void *a, const void *b)
3151 return *(pid_t *)a - *(pid_t *)b;
3154 static int fried_cmppid(const void *a, const void *b)
3156 return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
3159 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3160 enum cgroup_filetype type)
3162 struct cgroup_pidlist *l;
3163 /* don't need task_nsproxy() if we're looking at ourself */
3164 struct pid_namespace *ns = task_active_pid_ns(current);
3166 lockdep_assert_held(&cgrp->pidlist_mutex);
3168 list_for_each_entry(l, &cgrp->pidlists, links)
3169 if (l->key.type == type && l->key.ns == ns)
3175 * find the appropriate pidlist for our purpose (given procs vs tasks)
3176 * returns with the lock on that pidlist already held, and takes care
3177 * of the use count, or returns NULL with no locks held if we're out of
3180 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
3181 enum cgroup_filetype type)
3183 struct cgroup_pidlist *l;
3185 lockdep_assert_held(&cgrp->pidlist_mutex);
3187 l = cgroup_pidlist_find(cgrp, type);
3191 /* entry not found; create a new one */
3192 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3196 INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
3198 /* don't need task_nsproxy() if we're looking at ourself */
3199 l->key.ns = get_pid_ns(task_active_pid_ns(current));
3201 list_add(&l->links, &cgrp->pidlists);
3206 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3208 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3209 struct cgroup_pidlist **lp)
3213 int pid, n = 0; /* used for populating the array */
3214 struct css_task_iter it;
3215 struct task_struct *tsk;
3216 struct cgroup_pidlist *l;
3218 lockdep_assert_held(&cgrp->pidlist_mutex);
3221 * If cgroup gets more users after we read count, we won't have
3222 * enough space - tough. This race is indistinguishable to the
3223 * caller from the case that the additional cgroup users didn't
3224 * show up until sometime later on.
3226 length = cgroup_task_count(cgrp);
3227 array = pidlist_allocate(length);
3230 /* now, populate the array */
3231 css_task_iter_start(&cgrp->dummy_css, &it);
3232 while ((tsk = css_task_iter_next(&it))) {
3233 if (unlikely(n == length))
3235 /* get tgid or pid for procs or tasks file respectively */
3236 if (type == CGROUP_FILE_PROCS)
3237 pid = task_tgid_vnr(tsk);
3239 pid = task_pid_vnr(tsk);
3240 if (pid > 0) /* make sure to only use valid results */
3243 css_task_iter_end(&it);
3245 /* now sort & (if procs) strip out duplicates */
3246 if (cgroup_sane_behavior(cgrp))
3247 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
3249 sort(array, length, sizeof(pid_t), cmppid, NULL);
3250 if (type == CGROUP_FILE_PROCS)
3251 length = pidlist_uniq(array, length);
3253 l = cgroup_pidlist_find_create(cgrp, type);
3255 mutex_unlock(&cgrp->pidlist_mutex);
3256 pidlist_free(array);
3260 /* store array, freeing old if necessary */
3261 pidlist_free(l->list);
3269 * cgroupstats_build - build and fill cgroupstats
3270 * @stats: cgroupstats to fill information into
3271 * @dentry: A dentry entry belonging to the cgroup for which stats have
3274 * Build and fill cgroupstats so that taskstats can export it to user
3277 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3279 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
3280 struct cgroup *cgrp;
3281 struct css_task_iter it;
3282 struct task_struct *tsk;
3284 /* it should be kernfs_node belonging to cgroupfs and is a directory */
3285 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
3286 kernfs_type(kn) != KERNFS_DIR)
3289 mutex_lock(&cgroup_mutex);
3292 * We aren't being called from kernfs and there's no guarantee on
3293 * @kn->priv's validity. For this and css_tryget_from_dir(),
3294 * @kn->priv is RCU safe. Let's do the RCU dancing.
3297 cgrp = rcu_dereference(kn->priv);
3298 if (!cgrp || cgroup_is_dead(cgrp)) {
3300 mutex_unlock(&cgroup_mutex);
3305 css_task_iter_start(&cgrp->dummy_css, &it);
3306 while ((tsk = css_task_iter_next(&it))) {
3307 switch (tsk->state) {
3309 stats->nr_running++;
3311 case TASK_INTERRUPTIBLE:
3312 stats->nr_sleeping++;
3314 case TASK_UNINTERRUPTIBLE:
3315 stats->nr_uninterruptible++;
3318 stats->nr_stopped++;
3321 if (delayacct_is_task_waiting_on_io(tsk))
3322 stats->nr_io_wait++;
3326 css_task_iter_end(&it);
3328 mutex_unlock(&cgroup_mutex);
3334 * seq_file methods for the tasks/procs files. The seq_file position is the
3335 * next pid to display; the seq_file iterator is a pointer to the pid
3336 * in the cgroup->l->list array.
3339 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3342 * Initially we receive a position value that corresponds to
3343 * one more than the last pid shown (or 0 on the first call or
3344 * after a seek to the start). Use a binary-search to find the
3345 * next pid to display, if any
3347 struct kernfs_open_file *of = s->private;
3348 struct cgroup *cgrp = seq_css(s)->cgroup;
3349 struct cgroup_pidlist *l;
3350 enum cgroup_filetype type = seq_cft(s)->private;
3351 int index = 0, pid = *pos;
3354 mutex_lock(&cgrp->pidlist_mutex);
3357 * !NULL @of->priv indicates that this isn't the first start()
3358 * after open. If the matching pidlist is around, we can use that.
3359 * Look for it. Note that @of->priv can't be used directly. It
3360 * could already have been destroyed.
3363 of->priv = cgroup_pidlist_find(cgrp, type);
3366 * Either this is the first start() after open or the matching
3367 * pidlist has been destroyed inbetween. Create a new one.
3370 ret = pidlist_array_load(cgrp, type,
3371 (struct cgroup_pidlist **)&of->priv);
3373 return ERR_PTR(ret);
3378 int end = l->length;
3380 while (index < end) {
3381 int mid = (index + end) / 2;
3382 if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
3385 } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
3391 /* If we're off the end of the array, we're done */
3392 if (index >= l->length)
3394 /* Update the abstract position to be the actual pid that we found */
3395 iter = l->list + index;
3396 *pos = cgroup_pid_fry(cgrp, *iter);
3400 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3402 struct kernfs_open_file *of = s->private;
3403 struct cgroup_pidlist *l = of->priv;
3406 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
3407 CGROUP_PIDLIST_DESTROY_DELAY);
3408 mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
3411 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3413 struct kernfs_open_file *of = s->private;
3414 struct cgroup_pidlist *l = of->priv;
3416 pid_t *end = l->list + l->length;
3418 * Advance to the next pid in the array. If this goes off the
3425 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
3430 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3432 return seq_printf(s, "%d\n", *(int *)v);
3436 * seq_operations functions for iterating on pidlists through seq_file -
3437 * independent of whether it's tasks or procs
3439 static const struct seq_operations cgroup_pidlist_seq_operations = {
3440 .start = cgroup_pidlist_start,
3441 .stop = cgroup_pidlist_stop,
3442 .next = cgroup_pidlist_next,
3443 .show = cgroup_pidlist_show,
3446 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3449 return notify_on_release(css->cgroup);
3452 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3453 struct cftype *cft, u64 val)
3455 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3457 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3459 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3463 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3466 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3469 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3470 struct cftype *cft, u64 val)
3473 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3475 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3479 static struct cftype cgroup_base_files[] = {
3481 .name = "cgroup.procs",
3482 .seq_start = cgroup_pidlist_start,
3483 .seq_next = cgroup_pidlist_next,
3484 .seq_stop = cgroup_pidlist_stop,
3485 .seq_show = cgroup_pidlist_show,
3486 .private = CGROUP_FILE_PROCS,
3487 .write_u64 = cgroup_procs_write,
3488 .mode = S_IRUGO | S_IWUSR,
3491 .name = "cgroup.clone_children",
3492 .flags = CFTYPE_INSANE,
3493 .read_u64 = cgroup_clone_children_read,
3494 .write_u64 = cgroup_clone_children_write,
3497 .name = "cgroup.sane_behavior",
3498 .flags = CFTYPE_ONLY_ON_ROOT,
3499 .seq_show = cgroup_sane_behavior_show,
3503 * Historical crazy stuff. These don't have "cgroup." prefix and
3504 * don't exist if sane_behavior. If you're depending on these, be
3505 * prepared to be burned.
3509 .flags = CFTYPE_INSANE, /* use "procs" instead */
3510 .seq_start = cgroup_pidlist_start,
3511 .seq_next = cgroup_pidlist_next,
3512 .seq_stop = cgroup_pidlist_stop,
3513 .seq_show = cgroup_pidlist_show,
3514 .private = CGROUP_FILE_TASKS,
3515 .write_u64 = cgroup_tasks_write,
3516 .mode = S_IRUGO | S_IWUSR,
3519 .name = "notify_on_release",
3520 .flags = CFTYPE_INSANE,
3521 .read_u64 = cgroup_read_notify_on_release,
3522 .write_u64 = cgroup_write_notify_on_release,
3525 .name = "release_agent",
3526 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
3527 .seq_show = cgroup_release_agent_show,
3528 .write_string = cgroup_release_agent_write,
3529 .max_write_len = PATH_MAX - 1,
3535 * cgroup_populate_dir - create subsys files in a cgroup directory
3536 * @cgrp: target cgroup
3537 * @subsys_mask: mask of the subsystem ids whose files should be added
3539 * On failure, no file is added.
3541 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
3543 struct cgroup_subsys *ss;
3546 /* process cftsets of each subsystem */
3547 for_each_subsys(ss, i) {
3548 struct cftype *cfts;
3550 if (!test_bit(i, &subsys_mask))
3553 list_for_each_entry(cfts, &ss->cfts, node) {
3554 ret = cgroup_addrm_files(cgrp, cfts, true);
3561 cgroup_clear_dir(cgrp, subsys_mask);
3566 * css destruction is four-stage process.
3568 * 1. Destruction starts. Killing of the percpu_ref is initiated.
3569 * Implemented in kill_css().
3571 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
3572 * and thus css_tryget() is guaranteed to fail, the css can be offlined
3573 * by invoking offline_css(). After offlining, the base ref is put.
3574 * Implemented in css_killed_work_fn().
3576 * 3. When the percpu_ref reaches zero, the only possible remaining
3577 * accessors are inside RCU read sections. css_release() schedules the
3580 * 4. After the grace period, the css can be freed. Implemented in
3581 * css_free_work_fn().
3583 * It is actually hairier because both step 2 and 4 require process context
3584 * and thus involve punting to css->destroy_work adding two additional
3585 * steps to the already complex sequence.
3587 static void css_free_work_fn(struct work_struct *work)
3589 struct cgroup_subsys_state *css =
3590 container_of(work, struct cgroup_subsys_state, destroy_work);
3591 struct cgroup *cgrp = css->cgroup;
3594 css_put(css->parent);
3596 css->ss->css_free(css);
3600 static void css_free_rcu_fn(struct rcu_head *rcu_head)
3602 struct cgroup_subsys_state *css =
3603 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
3605 INIT_WORK(&css->destroy_work, css_free_work_fn);
3606 queue_work(cgroup_destroy_wq, &css->destroy_work);
3609 static void css_release(struct percpu_ref *ref)
3611 struct cgroup_subsys_state *css =
3612 container_of(ref, struct cgroup_subsys_state, refcnt);
3614 RCU_INIT_POINTER(css->cgroup->subsys[css->ss->id], NULL);
3615 call_rcu(&css->rcu_head, css_free_rcu_fn);
3618 static void init_css(struct cgroup_subsys_state *css, struct cgroup_subsys *ss,
3619 struct cgroup *cgrp)
3626 css->parent = cgroup_css(cgrp->parent, ss);
3628 css->flags |= CSS_ROOT;
3630 BUG_ON(cgroup_css(cgrp, ss));
3633 /* invoke ->css_online() on a new CSS and mark it online if successful */
3634 static int online_css(struct cgroup_subsys_state *css)
3636 struct cgroup_subsys *ss = css->ss;
3639 lockdep_assert_held(&cgroup_tree_mutex);
3640 lockdep_assert_held(&cgroup_mutex);
3643 ret = ss->css_online(css);
3645 css->flags |= CSS_ONLINE;
3646 css->cgroup->nr_css++;
3647 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
3652 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
3653 static void offline_css(struct cgroup_subsys_state *css)
3655 struct cgroup_subsys *ss = css->ss;
3657 lockdep_assert_held(&cgroup_tree_mutex);
3658 lockdep_assert_held(&cgroup_mutex);
3660 if (!(css->flags & CSS_ONLINE))
3663 if (ss->css_offline)
3664 ss->css_offline(css);
3666 css->flags &= ~CSS_ONLINE;
3667 css->cgroup->nr_css--;
3668 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], css);
3672 * create_css - create a cgroup_subsys_state
3673 * @cgrp: the cgroup new css will be associated with
3674 * @ss: the subsys of new css
3676 * Create a new css associated with @cgrp - @ss pair. On success, the new
3677 * css is online and installed in @cgrp with all interface files created.
3678 * Returns 0 on success, -errno on failure.
3680 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss)
3682 struct cgroup *parent = cgrp->parent;
3683 struct cgroup_subsys_state *css;
3686 lockdep_assert_held(&cgroup_mutex);
3688 css = ss->css_alloc(cgroup_css(parent, ss));
3690 return PTR_ERR(css);
3692 err = percpu_ref_init(&css->refcnt, css_release);
3696 init_css(css, ss, cgrp);
3698 err = cgroup_populate_dir(cgrp, 1 << ss->id);
3700 goto err_free_percpu_ref;
3702 err = online_css(css);
3707 css_get(css->parent);
3709 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
3711 pr_warning("cgroup: %s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
3712 current->comm, current->pid, ss->name);
3713 if (!strcmp(ss->name, "memory"))
3714 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
3715 ss->warned_broken_hierarchy = true;
3721 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
3722 err_free_percpu_ref:
3723 percpu_ref_cancel_init(&css->refcnt);
3730 * cgroup_create - create a cgroup
3731 * @parent: cgroup that will be parent of the new cgroup
3732 * @name: name of the new cgroup
3733 * @mode: mode to set on new cgroup
3735 static long cgroup_create(struct cgroup *parent, const char *name,
3738 struct cgroup *cgrp;
3739 struct cgroup_root *root = parent->root;
3741 struct cgroup_subsys *ss;
3742 struct kernfs_node *kn;
3745 * XXX: The default hierarchy isn't fully implemented yet. Block
3746 * !root cgroup creation on it for now.
3748 if (root == &cgrp_dfl_root)
3751 /* allocate the cgroup and its ID, 0 is reserved for the root */
3752 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
3756 mutex_lock(&cgroup_tree_mutex);
3759 * Only live parents can have children. Note that the liveliness
3760 * check isn't strictly necessary because cgroup_mkdir() and
3761 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
3762 * anyway so that locking is contained inside cgroup proper and we
3763 * don't get nasty surprises if we ever grow another caller.
3765 if (!cgroup_lock_live_group(parent)) {
3767 goto err_unlock_tree;
3771 * Temporarily set the pointer to NULL, so idr_find() won't return
3772 * a half-baked cgroup.
3774 cgrp->id = idr_alloc(&root->cgroup_idr, NULL, 1, 0, GFP_KERNEL);
3780 init_cgroup_housekeeping(cgrp);
3782 cgrp->parent = parent;
3783 cgrp->dummy_css.parent = &parent->dummy_css;
3784 cgrp->root = parent->root;
3786 if (notify_on_release(parent))
3787 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3789 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
3790 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3792 /* create the directory */
3793 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
3801 * This extra ref will be put in cgroup_free_fn() and guarantees
3802 * that @cgrp->kn is always accessible.
3806 cgrp->serial_nr = cgroup_serial_nr_next++;
3808 /* allocation complete, commit to creation */
3809 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
3810 atomic_inc(&root->nr_cgrps);
3814 * @cgrp is now fully operational. If something fails after this
3815 * point, it'll be released via the normal destruction path.
3817 idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
3819 err = cgroup_kn_set_ugid(kn);
3823 err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
3827 /* let's create and online css's */
3828 for_each_subsys(ss, ssid) {
3829 if (parent->child_subsys_mask & (1 << ssid)) {
3830 err = create_css(cgrp, ss);
3836 cgrp->child_subsys_mask = parent->child_subsys_mask;
3838 kernfs_activate(kn);
3840 mutex_unlock(&cgroup_mutex);
3841 mutex_unlock(&cgroup_tree_mutex);
3846 idr_remove(&root->cgroup_idr, cgrp->id);
3848 mutex_unlock(&cgroup_mutex);
3850 mutex_unlock(&cgroup_tree_mutex);
3855 cgroup_destroy_locked(cgrp);
3856 mutex_unlock(&cgroup_mutex);
3857 mutex_unlock(&cgroup_tree_mutex);
3861 static int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
3864 struct cgroup *parent = parent_kn->priv;
3868 * cgroup_create() grabs cgroup_tree_mutex which nests outside
3869 * kernfs active_ref and cgroup_create() already synchronizes
3870 * properly against removal through cgroup_lock_live_group().
3871 * Break it before calling cgroup_create().
3874 kernfs_break_active_protection(parent_kn);
3876 ret = cgroup_create(parent, name, mode);
3878 kernfs_unbreak_active_protection(parent_kn);
3884 * This is called when the refcnt of a css is confirmed to be killed.
3885 * css_tryget() is now guaranteed to fail.
3887 static void css_killed_work_fn(struct work_struct *work)
3889 struct cgroup_subsys_state *css =
3890 container_of(work, struct cgroup_subsys_state, destroy_work);
3891 struct cgroup *cgrp = css->cgroup;
3893 mutex_lock(&cgroup_tree_mutex);
3894 mutex_lock(&cgroup_mutex);
3897 * css_tryget() is guaranteed to fail now. Tell subsystems to
3898 * initate destruction.
3903 * If @cgrp is marked dead, it's waiting for refs of all css's to
3904 * be disabled before proceeding to the second phase of cgroup
3905 * destruction. If we are the last one, kick it off.
3907 if (!cgrp->nr_css && cgroup_is_dead(cgrp))
3908 cgroup_destroy_css_killed(cgrp);
3910 mutex_unlock(&cgroup_mutex);
3911 mutex_unlock(&cgroup_tree_mutex);
3914 * Put the css refs from kill_css(). Each css holds an extra
3915 * reference to the cgroup's dentry and cgroup removal proceeds
3916 * regardless of css refs. On the last put of each css, whenever
3917 * that may be, the extra dentry ref is put so that dentry
3918 * destruction happens only after all css's are released.
3923 /* css kill confirmation processing requires process context, bounce */
3924 static void css_killed_ref_fn(struct percpu_ref *ref)
3926 struct cgroup_subsys_state *css =
3927 container_of(ref, struct cgroup_subsys_state, refcnt);
3929 INIT_WORK(&css->destroy_work, css_killed_work_fn);
3930 queue_work(cgroup_destroy_wq, &css->destroy_work);
3934 * kill_css - destroy a css
3935 * @css: css to destroy
3937 * This function initiates destruction of @css by removing cgroup interface
3938 * files and putting its base reference. ->css_offline() will be invoked
3939 * asynchronously once css_tryget() is guaranteed to fail and when the
3940 * reference count reaches zero, @css will be released.
3942 static void kill_css(struct cgroup_subsys_state *css)
3944 lockdep_assert_held(&cgroup_tree_mutex);
3947 * This must happen before css is disassociated with its cgroup.
3948 * See seq_css() for details.
3950 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
3953 * Killing would put the base ref, but we need to keep it alive
3954 * until after ->css_offline().
3959 * cgroup core guarantees that, by the time ->css_offline() is
3960 * invoked, no new css reference will be given out via
3961 * css_tryget(). We can't simply call percpu_ref_kill() and
3962 * proceed to offlining css's because percpu_ref_kill() doesn't
3963 * guarantee that the ref is seen as killed on all CPUs on return.
3965 * Use percpu_ref_kill_and_confirm() to get notifications as each
3966 * css is confirmed to be seen as killed on all CPUs.
3968 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
3972 * cgroup_destroy_locked - the first stage of cgroup destruction
3973 * @cgrp: cgroup to be destroyed
3975 * css's make use of percpu refcnts whose killing latency shouldn't be
3976 * exposed to userland and are RCU protected. Also, cgroup core needs to
3977 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
3978 * invoked. To satisfy all the requirements, destruction is implemented in
3979 * the following two steps.
3981 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
3982 * userland visible parts and start killing the percpu refcnts of
3983 * css's. Set up so that the next stage will be kicked off once all
3984 * the percpu refcnts are confirmed to be killed.
3986 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
3987 * rest of destruction. Once all cgroup references are gone, the
3988 * cgroup is RCU-freed.
3990 * This function implements s1. After this step, @cgrp is gone as far as
3991 * the userland is concerned and a new cgroup with the same name may be
3992 * created. As cgroup doesn't care about the names internally, this
3993 * doesn't cause any problem.
3995 static int cgroup_destroy_locked(struct cgroup *cgrp)
3996 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
3998 struct cgroup *child;
3999 struct cgroup_subsys_state *css;
4003 lockdep_assert_held(&cgroup_tree_mutex);
4004 lockdep_assert_held(&cgroup_mutex);
4007 * css_set_rwsem synchronizes access to ->cset_links and prevents
4008 * @cgrp from being removed while put_css_set() is in progress.
4010 down_read(&css_set_rwsem);
4011 empty = list_empty(&cgrp->cset_links);
4012 up_read(&css_set_rwsem);
4017 * Make sure there's no live children. We can't test ->children
4018 * emptiness as dead children linger on it while being destroyed;
4019 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
4023 list_for_each_entry_rcu(child, &cgrp->children, sibling) {
4024 empty = cgroup_is_dead(child);
4033 * Mark @cgrp dead. This prevents further task migration and child
4034 * creation by disabling cgroup_lock_live_group(). Note that
4035 * CGRP_DEAD assertion is depended upon by css_next_child() to
4036 * resume iteration after dropping RCU read lock. See
4037 * css_next_child() for details.
4039 set_bit(CGRP_DEAD, &cgrp->flags);
4042 * Initiate massacre of all css's. cgroup_destroy_css_killed()
4043 * will be invoked to perform the rest of destruction once the
4044 * percpu refs of all css's are confirmed to be killed. This
4045 * involves removing the subsystem's files, drop cgroup_mutex.
4047 mutex_unlock(&cgroup_mutex);
4048 for_each_css(css, ssid, cgrp)
4050 mutex_lock(&cgroup_mutex);
4052 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4053 raw_spin_lock(&release_list_lock);
4054 if (!list_empty(&cgrp->release_list))
4055 list_del_init(&cgrp->release_list);
4056 raw_spin_unlock(&release_list_lock);
4059 * If @cgrp has css's attached, the second stage of cgroup
4060 * destruction is kicked off from css_killed_work_fn() after the
4061 * refs of all attached css's are killed. If @cgrp doesn't have
4062 * any css, we kick it off here.
4065 cgroup_destroy_css_killed(cgrp);
4067 /* remove @cgrp directory along with the base files */
4068 mutex_unlock(&cgroup_mutex);
4071 * There are two control paths which try to determine cgroup from
4072 * dentry without going through kernfs - cgroupstats_build() and
4073 * css_tryget_from_dir(). Those are supported by RCU protecting
4074 * clearing of cgrp->kn->priv backpointer, which should happen
4075 * after all files under it have been removed.
4077 kernfs_remove(cgrp->kn); /* @cgrp has an extra ref on its kn */
4078 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv, NULL);
4080 mutex_lock(&cgroup_mutex);
4086 * cgroup_destroy_css_killed - the second step of cgroup destruction
4087 * @work: cgroup->destroy_free_work
4089 * This function is invoked from a work item for a cgroup which is being
4090 * destroyed after all css's are offlined and performs the rest of
4091 * destruction. This is the second step of destruction described in the
4092 * comment above cgroup_destroy_locked().
4094 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
4096 struct cgroup *parent = cgrp->parent;
4098 lockdep_assert_held(&cgroup_tree_mutex);
4099 lockdep_assert_held(&cgroup_mutex);
4101 /* delete this cgroup from parent->children */
4102 list_del_rcu(&cgrp->sibling);
4106 set_bit(CGRP_RELEASABLE, &parent->flags);
4107 check_for_release(parent);
4110 static int cgroup_rmdir(struct kernfs_node *kn)
4112 struct cgroup *cgrp = kn->priv;
4116 * This is self-destruction but @kn can't be removed while this
4117 * callback is in progress. Let's break active protection. Once
4118 * the protection is broken, @cgrp can be destroyed at any point.
4119 * Pin it so that it stays accessible.
4122 kernfs_break_active_protection(kn);
4124 mutex_lock(&cgroup_tree_mutex);
4125 mutex_lock(&cgroup_mutex);
4128 * @cgrp might already have been destroyed while we're trying to
4131 if (!cgroup_is_dead(cgrp))
4132 ret = cgroup_destroy_locked(cgrp);
4134 mutex_unlock(&cgroup_mutex);
4135 mutex_unlock(&cgroup_tree_mutex);
4137 kernfs_unbreak_active_protection(kn);
4142 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
4143 .remount_fs = cgroup_remount,
4144 .show_options = cgroup_show_options,
4145 .mkdir = cgroup_mkdir,
4146 .rmdir = cgroup_rmdir,
4147 .rename = cgroup_rename,
4150 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4152 struct cgroup_subsys_state *css;
4154 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4156 mutex_lock(&cgroup_tree_mutex);
4157 mutex_lock(&cgroup_mutex);
4159 INIT_LIST_HEAD(&ss->cfts);
4161 /* Create the root cgroup state for this subsystem */
4162 ss->root = &cgrp_dfl_root;
4163 css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
4164 /* We don't handle early failures gracefully */
4165 BUG_ON(IS_ERR(css));
4166 init_css(css, ss, &cgrp_dfl_root.cgrp);
4168 /* Update the init_css_set to contain a subsys
4169 * pointer to this state - since the subsystem is
4170 * newly registered, all tasks and hence the
4171 * init_css_set is in the subsystem's root cgroup. */
4172 init_css_set.subsys[ss->id] = css;
4174 need_forkexit_callback |= ss->fork || ss->exit;
4176 /* At system boot, before all subsystems have been
4177 * registered, no tasks have been forked, so we don't
4178 * need to invoke fork callbacks here. */
4179 BUG_ON(!list_empty(&init_task.tasks));
4181 BUG_ON(online_css(css));
4183 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
4185 mutex_unlock(&cgroup_mutex);
4186 mutex_unlock(&cgroup_tree_mutex);
4190 * cgroup_init_early - cgroup initialization at system boot
4192 * Initialize cgroups at system boot, and initialize any
4193 * subsystems that request early init.
4195 int __init cgroup_init_early(void)
4197 static struct cgroup_sb_opts __initdata opts =
4198 { .flags = CGRP_ROOT_SANE_BEHAVIOR };
4199 struct cgroup_subsys *ss;
4202 init_cgroup_root(&cgrp_dfl_root, &opts);
4203 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4205 for_each_subsys(ss, i) {
4206 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
4207 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
4208 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
4210 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
4211 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
4214 ss->name = cgroup_subsys_name[i];
4217 cgroup_init_subsys(ss);
4223 * cgroup_init - cgroup initialization
4225 * Register cgroup filesystem and /proc file, and initialize
4226 * any subsystems that didn't request early init.
4228 int __init cgroup_init(void)
4230 struct cgroup_subsys *ss;
4234 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
4236 mutex_lock(&cgroup_tree_mutex);
4237 mutex_lock(&cgroup_mutex);
4239 /* Add init_css_set to the hash table */
4240 key = css_set_hash(init_css_set.subsys);
4241 hash_add(css_set_table, &init_css_set.hlist, key);
4243 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
4245 mutex_unlock(&cgroup_mutex);
4246 mutex_unlock(&cgroup_tree_mutex);
4248 for_each_subsys(ss, ssid) {
4249 if (!ss->early_init)
4250 cgroup_init_subsys(ss);
4253 * cftype registration needs kmalloc and can't be done
4254 * during early_init. Register base cftypes separately.
4256 if (ss->base_cftypes)
4257 WARN_ON(cgroup_add_cftypes(ss, ss->base_cftypes));
4260 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4264 err = register_filesystem(&cgroup_fs_type);
4266 kobject_put(cgroup_kobj);
4270 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4274 static int __init cgroup_wq_init(void)
4277 * There isn't much point in executing destruction path in
4278 * parallel. Good chunk is serialized with cgroup_mutex anyway.
4279 * Use 1 for @max_active.
4281 * We would prefer to do this in cgroup_init() above, but that
4282 * is called before init_workqueues(): so leave this until after.
4284 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
4285 BUG_ON(!cgroup_destroy_wq);
4288 * Used to destroy pidlists and separate to serve as flush domain.
4289 * Cap @max_active to 1 too.
4291 cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
4293 BUG_ON(!cgroup_pidlist_destroy_wq);
4297 core_initcall(cgroup_wq_init);
4300 * proc_cgroup_show()
4301 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4302 * - Used for /proc/<pid>/cgroup.
4305 /* TODO: Use a proper seq_file iterator */
4306 int proc_cgroup_show(struct seq_file *m, void *v)
4309 struct task_struct *tsk;
4312 struct cgroup_root *root;
4315 buf = kmalloc(PATH_MAX, GFP_KERNEL);
4321 tsk = get_pid_task(pid, PIDTYPE_PID);
4327 mutex_lock(&cgroup_mutex);
4328 down_read(&css_set_rwsem);
4330 for_each_root(root) {
4331 struct cgroup_subsys *ss;
4332 struct cgroup *cgrp;
4333 int ssid, count = 0;
4335 if (root == &cgrp_dfl_root && !cgrp_dfl_root_visible)
4338 seq_printf(m, "%d:", root->hierarchy_id);
4339 for_each_subsys(ss, ssid)
4340 if (root->subsys_mask & (1 << ssid))
4341 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4342 if (strlen(root->name))
4343 seq_printf(m, "%sname=%s", count ? "," : "",
4346 cgrp = task_cgroup_from_root(tsk, root);
4347 path = cgroup_path(cgrp, buf, PATH_MAX);
4349 retval = -ENAMETOOLONG;
4357 up_read(&css_set_rwsem);
4358 mutex_unlock(&cgroup_mutex);
4359 put_task_struct(tsk);
4366 /* Display information about each subsystem and each hierarchy */
4367 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4369 struct cgroup_subsys *ss;
4372 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4374 * ideally we don't want subsystems moving around while we do this.
4375 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4376 * subsys/hierarchy state.
4378 mutex_lock(&cgroup_mutex);
4380 for_each_subsys(ss, i)
4381 seq_printf(m, "%s\t%d\t%d\t%d\n",
4382 ss->name, ss->root->hierarchy_id,
4383 atomic_read(&ss->root->nr_cgrps), !ss->disabled);
4385 mutex_unlock(&cgroup_mutex);
4389 static int cgroupstats_open(struct inode *inode, struct file *file)
4391 return single_open(file, proc_cgroupstats_show, NULL);
4394 static const struct file_operations proc_cgroupstats_operations = {
4395 .open = cgroupstats_open,
4397 .llseek = seq_lseek,
4398 .release = single_release,
4402 * cgroup_fork - initialize cgroup related fields during copy_process()
4403 * @child: pointer to task_struct of forking parent process.
4405 * A task is associated with the init_css_set until cgroup_post_fork()
4406 * attaches it to the parent's css_set. Empty cg_list indicates that
4407 * @child isn't holding reference to its css_set.
4409 void cgroup_fork(struct task_struct *child)
4411 RCU_INIT_POINTER(child->cgroups, &init_css_set);
4412 INIT_LIST_HEAD(&child->cg_list);
4416 * cgroup_post_fork - called on a new task after adding it to the task list
4417 * @child: the task in question
4419 * Adds the task to the list running through its css_set if necessary and
4420 * call the subsystem fork() callbacks. Has to be after the task is
4421 * visible on the task list in case we race with the first call to
4422 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
4425 void cgroup_post_fork(struct task_struct *child)
4427 struct cgroup_subsys *ss;
4431 * This may race against cgroup_enable_task_cg_links(). As that
4432 * function sets use_task_css_set_links before grabbing
4433 * tasklist_lock and we just went through tasklist_lock to add
4434 * @child, it's guaranteed that either we see the set
4435 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
4436 * @child during its iteration.
4438 * If we won the race, @child is associated with %current's
4439 * css_set. Grabbing css_set_rwsem guarantees both that the
4440 * association is stable, and, on completion of the parent's
4441 * migration, @child is visible in the source of migration or
4442 * already in the destination cgroup. This guarantee is necessary
4443 * when implementing operations which need to migrate all tasks of
4444 * a cgroup to another.
4446 * Note that if we lose to cgroup_enable_task_cg_links(), @child
4447 * will remain in init_css_set. This is safe because all tasks are
4448 * in the init_css_set before cg_links is enabled and there's no
4449 * operation which transfers all tasks out of init_css_set.
4451 if (use_task_css_set_links) {
4452 struct css_set *cset;
4454 down_write(&css_set_rwsem);
4455 cset = task_css_set(current);
4456 if (list_empty(&child->cg_list)) {
4457 rcu_assign_pointer(child->cgroups, cset);
4458 list_add(&child->cg_list, &cset->tasks);
4461 up_write(&css_set_rwsem);
4465 * Call ss->fork(). This must happen after @child is linked on
4466 * css_set; otherwise, @child might change state between ->fork()
4467 * and addition to css_set.
4469 if (need_forkexit_callback) {
4470 for_each_subsys(ss, i)
4477 * cgroup_exit - detach cgroup from exiting task
4478 * @tsk: pointer to task_struct of exiting process
4480 * Description: Detach cgroup from @tsk and release it.
4482 * Note that cgroups marked notify_on_release force every task in
4483 * them to take the global cgroup_mutex mutex when exiting.
4484 * This could impact scaling on very large systems. Be reluctant to
4485 * use notify_on_release cgroups where very high task exit scaling
4486 * is required on large systems.
4488 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
4489 * call cgroup_exit() while the task is still competent to handle
4490 * notify_on_release(), then leave the task attached to the root cgroup in
4491 * each hierarchy for the remainder of its exit. No need to bother with
4492 * init_css_set refcnting. init_css_set never goes away and we can't race
4493 * with migration path - PF_EXITING is visible to migration path.
4495 void cgroup_exit(struct task_struct *tsk)
4497 struct cgroup_subsys *ss;
4498 struct css_set *cset;
4499 bool put_cset = false;
4503 * Unlink from @tsk from its css_set. As migration path can't race
4504 * with us, we can check cg_list without grabbing css_set_rwsem.
4506 if (!list_empty(&tsk->cg_list)) {
4507 down_write(&css_set_rwsem);
4508 list_del_init(&tsk->cg_list);
4509 up_write(&css_set_rwsem);
4513 /* Reassign the task to the init_css_set. */
4514 cset = task_css_set(tsk);
4515 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
4517 if (need_forkexit_callback) {
4518 /* see cgroup_post_fork() for details */
4519 for_each_subsys(ss, i) {
4521 struct cgroup_subsys_state *old_css = cset->subsys[i];
4522 struct cgroup_subsys_state *css = task_css(tsk, i);
4524 ss->exit(css, old_css, tsk);
4530 put_css_set(cset, true);
4533 static void check_for_release(struct cgroup *cgrp)
4535 if (cgroup_is_releasable(cgrp) &&
4536 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
4538 * Control Group is currently removeable. If it's not
4539 * already queued for a userspace notification, queue
4542 int need_schedule_work = 0;
4544 raw_spin_lock(&release_list_lock);
4545 if (!cgroup_is_dead(cgrp) &&
4546 list_empty(&cgrp->release_list)) {
4547 list_add(&cgrp->release_list, &release_list);
4548 need_schedule_work = 1;
4550 raw_spin_unlock(&release_list_lock);
4551 if (need_schedule_work)
4552 schedule_work(&release_agent_work);
4557 * Notify userspace when a cgroup is released, by running the
4558 * configured release agent with the name of the cgroup (path
4559 * relative to the root of cgroup file system) as the argument.
4561 * Most likely, this user command will try to rmdir this cgroup.
4563 * This races with the possibility that some other task will be
4564 * attached to this cgroup before it is removed, or that some other
4565 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
4566 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
4567 * unused, and this cgroup will be reprieved from its death sentence,
4568 * to continue to serve a useful existence. Next time it's released,
4569 * we will get notified again, if it still has 'notify_on_release' set.
4571 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
4572 * means only wait until the task is successfully execve()'d. The
4573 * separate release agent task is forked by call_usermodehelper(),
4574 * then control in this thread returns here, without waiting for the
4575 * release agent task. We don't bother to wait because the caller of
4576 * this routine has no use for the exit status of the release agent
4577 * task, so no sense holding our caller up for that.
4579 static void cgroup_release_agent(struct work_struct *work)
4581 BUG_ON(work != &release_agent_work);
4582 mutex_lock(&cgroup_mutex);
4583 raw_spin_lock(&release_list_lock);
4584 while (!list_empty(&release_list)) {
4585 char *argv[3], *envp[3];
4587 char *pathbuf = NULL, *agentbuf = NULL, *path;
4588 struct cgroup *cgrp = list_entry(release_list.next,
4591 list_del_init(&cgrp->release_list);
4592 raw_spin_unlock(&release_list_lock);
4593 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
4596 path = cgroup_path(cgrp, pathbuf, PATH_MAX);
4599 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
4604 argv[i++] = agentbuf;
4609 /* minimal command environment */
4610 envp[i++] = "HOME=/";
4611 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
4614 /* Drop the lock while we invoke the usermode helper,
4615 * since the exec could involve hitting disk and hence
4616 * be a slow process */
4617 mutex_unlock(&cgroup_mutex);
4618 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
4619 mutex_lock(&cgroup_mutex);
4623 raw_spin_lock(&release_list_lock);
4625 raw_spin_unlock(&release_list_lock);
4626 mutex_unlock(&cgroup_mutex);
4629 static int __init cgroup_disable(char *str)
4631 struct cgroup_subsys *ss;
4635 while ((token = strsep(&str, ",")) != NULL) {
4639 for_each_subsys(ss, i) {
4640 if (!strcmp(token, ss->name)) {
4642 printk(KERN_INFO "Disabling %s control group"
4643 " subsystem\n", ss->name);
4650 __setup("cgroup_disable=", cgroup_disable);
4653 * css_tryget_from_dir - get corresponding css from the dentry of a cgroup dir
4654 * @dentry: directory dentry of interest
4655 * @ss: subsystem of interest
4657 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
4658 * to get the corresponding css and return it. If such css doesn't exist
4659 * or can't be pinned, an ERR_PTR value is returned.
4661 struct cgroup_subsys_state *css_tryget_from_dir(struct dentry *dentry,
4662 struct cgroup_subsys *ss)
4664 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
4665 struct cgroup_subsys_state *css = NULL;
4666 struct cgroup *cgrp;
4668 /* is @dentry a cgroup dir? */
4669 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
4670 kernfs_type(kn) != KERNFS_DIR)
4671 return ERR_PTR(-EBADF);
4676 * This path doesn't originate from kernfs and @kn could already
4677 * have been or be removed at any point. @kn->priv is RCU
4678 * protected for this access. See destroy_locked() for details.
4680 cgrp = rcu_dereference(kn->priv);
4682 css = cgroup_css(cgrp, ss);
4684 if (!css || !css_tryget(css))
4685 css = ERR_PTR(-ENOENT);
4692 * css_from_id - lookup css by id
4693 * @id: the cgroup id
4694 * @ss: cgroup subsys to be looked into
4696 * Returns the css if there's valid one with @id, otherwise returns NULL.
4697 * Should be called under rcu_read_lock().
4699 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
4701 struct cgroup *cgrp;
4703 cgroup_assert_mutexes_or_rcu_locked();
4705 cgrp = idr_find(&ss->root->cgroup_idr, id);
4707 return cgroup_css(cgrp, ss);
4711 #ifdef CONFIG_CGROUP_DEBUG
4712 static struct cgroup_subsys_state *
4713 debug_css_alloc(struct cgroup_subsys_state *parent_css)
4715 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
4718 return ERR_PTR(-ENOMEM);
4723 static void debug_css_free(struct cgroup_subsys_state *css)
4728 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
4731 return cgroup_task_count(css->cgroup);
4734 static u64 current_css_set_read(struct cgroup_subsys_state *css,
4737 return (u64)(unsigned long)current->cgroups;
4740 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
4746 count = atomic_read(&task_css_set(current)->refcount);
4751 static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
4753 struct cgrp_cset_link *link;
4754 struct css_set *cset;
4757 name_buf = kmalloc(NAME_MAX + 1, GFP_KERNEL);
4761 down_read(&css_set_rwsem);
4763 cset = rcu_dereference(current->cgroups);
4764 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
4765 struct cgroup *c = link->cgrp;
4767 cgroup_name(c, name_buf, NAME_MAX + 1);
4768 seq_printf(seq, "Root %d group %s\n",
4769 c->root->hierarchy_id, name_buf);
4772 up_read(&css_set_rwsem);
4777 #define MAX_TASKS_SHOWN_PER_CSS 25
4778 static int cgroup_css_links_read(struct seq_file *seq, void *v)
4780 struct cgroup_subsys_state *css = seq_css(seq);
4781 struct cgrp_cset_link *link;
4783 down_read(&css_set_rwsem);
4784 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
4785 struct css_set *cset = link->cset;
4786 struct task_struct *task;
4789 seq_printf(seq, "css_set %p\n", cset);
4791 list_for_each_entry(task, &cset->tasks, cg_list) {
4792 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
4794 seq_printf(seq, " task %d\n", task_pid_vnr(task));
4797 list_for_each_entry(task, &cset->mg_tasks, cg_list) {
4798 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
4800 seq_printf(seq, " task %d\n", task_pid_vnr(task));
4804 seq_puts(seq, " ...\n");
4806 up_read(&css_set_rwsem);
4810 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
4812 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
4815 static struct cftype debug_files[] = {
4817 .name = "taskcount",
4818 .read_u64 = debug_taskcount_read,
4822 .name = "current_css_set",
4823 .read_u64 = current_css_set_read,
4827 .name = "current_css_set_refcount",
4828 .read_u64 = current_css_set_refcount_read,
4832 .name = "current_css_set_cg_links",
4833 .seq_show = current_css_set_cg_links_read,
4837 .name = "cgroup_css_links",
4838 .seq_show = cgroup_css_links_read,
4842 .name = "releasable",
4843 .read_u64 = releasable_read,
4849 struct cgroup_subsys debug_cgrp_subsys = {
4850 .css_alloc = debug_css_alloc,
4851 .css_free = debug_css_free,
4852 .base_cftypes = debug_files,
4854 #endif /* CONFIG_CGROUP_DEBUG */