2 * Generic process-grouping system.
4 * Based originally on the cpuset system, extracted by Paul Menage
5 * Copyright (C) 2006 Google, Inc
7 * Notifications support
8 * Copyright (C) 2009 Nokia Corporation
9 * Author: Kirill A. Shutemov
11 * Copyright notices from the original cpuset code:
12 * --------------------------------------------------
13 * Copyright (C) 2003 BULL SA.
14 * Copyright (C) 2004-2006 Silicon Graphics, Inc.
16 * Portions derived from Patrick Mochel's sysfs code.
17 * sysfs is Copyright (c) 2001-3 Patrick Mochel
19 * 2003-10-10 Written by Simon Derr.
20 * 2003-10-22 Updates by Stephen Hemminger.
21 * 2004 May-July Rework by Paul Jackson.
22 * ---------------------------------------------------
24 * This file is subject to the terms and conditions of the GNU General Public
25 * License. See the file COPYING in the main directory of the Linux
26 * distribution for more details.
29 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
31 #include <linux/cgroup.h>
32 #include <linux/cred.h>
33 #include <linux/ctype.h>
34 #include <linux/errno.h>
35 #include <linux/init_task.h>
36 #include <linux/kernel.h>
37 #include <linux/list.h>
39 #include <linux/mutex.h>
40 #include <linux/mount.h>
41 #include <linux/pagemap.h>
42 #include <linux/proc_fs.h>
43 #include <linux/rcupdate.h>
44 #include <linux/sched.h>
45 #include <linux/slab.h>
46 #include <linux/spinlock.h>
47 #include <linux/rwsem.h>
48 #include <linux/string.h>
49 #include <linux/sort.h>
50 #include <linux/kmod.h>
51 #include <linux/delayacct.h>
52 #include <linux/cgroupstats.h>
53 #include <linux/hashtable.h>
54 #include <linux/pid_namespace.h>
55 #include <linux/idr.h>
56 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
57 #include <linux/kthread.h>
58 #include <linux/delay.h>
60 #include <linux/atomic.h>
63 * pidlists linger the following amount before being destroyed. The goal
64 * is avoiding frequent destruction in the middle of consecutive read calls
65 * Expiring in the middle is a performance problem not a correctness one.
66 * 1 sec should be enough.
68 #define CGROUP_PIDLIST_DESTROY_DELAY HZ
70 #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
74 * cgroup_tree_mutex nests above cgroup_mutex and protects cftypes, file
75 * creation/removal and hierarchy changing operations including cgroup
76 * creation, removal, css association and controller rebinding. This outer
77 * lock is needed mainly to resolve the circular dependency between kernfs
78 * active ref and cgroup_mutex. cgroup_tree_mutex nests above both.
80 static DEFINE_MUTEX(cgroup_tree_mutex);
83 * cgroup_mutex is the master lock. Any modification to cgroup or its
84 * hierarchy must be performed while holding it.
86 * css_set_rwsem protects task->cgroups pointer, the list of css_set
87 * objects, and the chain of tasks off each css_set.
89 * These locks are exported if CONFIG_PROVE_RCU so that accessors in
90 * cgroup.h can use them for lockdep annotations.
92 #ifdef CONFIG_PROVE_RCU
93 DEFINE_MUTEX(cgroup_mutex);
94 DECLARE_RWSEM(css_set_rwsem);
95 EXPORT_SYMBOL_GPL(cgroup_mutex);
96 EXPORT_SYMBOL_GPL(css_set_rwsem);
98 static DEFINE_MUTEX(cgroup_mutex);
99 static DECLARE_RWSEM(css_set_rwsem);
103 * Protects cgroup_idr and css_idr so that IDs can be released without
104 * grabbing cgroup_mutex.
106 static DEFINE_SPINLOCK(cgroup_idr_lock);
109 * Protects cgroup_subsys->release_agent_path. Modifying it also requires
110 * cgroup_mutex. Reading requires either cgroup_mutex or this spinlock.
112 static DEFINE_SPINLOCK(release_agent_path_lock);
114 #define cgroup_assert_mutexes_or_rcu_locked() \
115 rcu_lockdep_assert(rcu_read_lock_held() || \
116 lockdep_is_held(&cgroup_tree_mutex) || \
117 lockdep_is_held(&cgroup_mutex), \
118 "cgroup_[tree_]mutex or RCU read lock required");
121 * cgroup destruction makes heavy use of work items and there can be a lot
122 * of concurrent destructions. Use a separate workqueue so that cgroup
123 * destruction work items don't end up filling up max_active of system_wq
124 * which may lead to deadlock.
126 static struct workqueue_struct *cgroup_destroy_wq;
129 * pidlist destructions need to be flushed on cgroup destruction. Use a
130 * separate workqueue as flush domain.
132 static struct workqueue_struct *cgroup_pidlist_destroy_wq;
134 /* generate an array of cgroup subsystem pointers */
135 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
136 static struct cgroup_subsys *cgroup_subsys[] = {
137 #include <linux/cgroup_subsys.h>
141 /* array of cgroup subsystem names */
142 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
143 static const char *cgroup_subsys_name[] = {
144 #include <linux/cgroup_subsys.h>
149 * The default hierarchy, reserved for the subsystems that are otherwise
150 * unattached - it never has more than a single cgroup, and all tasks are
151 * part of that cgroup.
153 struct cgroup_root cgrp_dfl_root;
156 * The default hierarchy always exists but is hidden until mounted for the
157 * first time. This is for backward compatibility.
159 static bool cgrp_dfl_root_visible;
161 /* The list of hierarchy roots */
163 static LIST_HEAD(cgroup_roots);
164 static int cgroup_root_count;
166 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
167 static DEFINE_IDR(cgroup_hierarchy_idr);
170 * Assign a monotonically increasing serial number to cgroups. It
171 * guarantees cgroups with bigger numbers are newer than those with smaller
172 * numbers. Also, as cgroups are always appended to the parent's
173 * ->children list, it guarantees that sibling cgroups are always sorted in
174 * the ascending serial number order on the list. Protected by
177 static u64 cgroup_serial_nr_next = 1;
179 /* This flag indicates whether tasks in the fork and exit paths should
180 * check for fork/exit handlers to call. This avoids us having to do
181 * extra work in the fork/exit path if none of the subsystems need to
184 static int need_forkexit_callback __read_mostly;
186 static struct cftype cgroup_base_files[];
188 static void cgroup_put(struct cgroup *cgrp);
189 static int rebind_subsystems(struct cgroup_root *dst_root,
190 unsigned int ss_mask);
191 static void cgroup_destroy_css_killed(struct cgroup *cgrp);
192 static int cgroup_destroy_locked(struct cgroup *cgrp);
193 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss);
194 static void kill_css(struct cgroup_subsys_state *css);
195 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
197 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp);
199 /* IDR wrappers which synchronize using cgroup_idr_lock */
200 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
205 idr_preload(gfp_mask);
206 spin_lock_bh(&cgroup_idr_lock);
207 ret = idr_alloc(idr, ptr, start, end, gfp_mask);
208 spin_unlock_bh(&cgroup_idr_lock);
213 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
217 spin_lock_bh(&cgroup_idr_lock);
218 ret = idr_replace(idr, ptr, id);
219 spin_unlock_bh(&cgroup_idr_lock);
223 static void cgroup_idr_remove(struct idr *idr, int id)
225 spin_lock_bh(&cgroup_idr_lock);
227 spin_unlock_bh(&cgroup_idr_lock);
231 * cgroup_css - obtain a cgroup's css for the specified subsystem
232 * @cgrp: the cgroup of interest
233 * @ss: the subsystem of interest (%NULL returns the dummy_css)
235 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
236 * function must be called either under cgroup_mutex or rcu_read_lock() and
237 * the caller is responsible for pinning the returned css if it wants to
238 * keep accessing it outside the said locks. This function may return
239 * %NULL if @cgrp doesn't have @subsys_id enabled.
241 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
242 struct cgroup_subsys *ss)
245 return rcu_dereference_check(cgrp->subsys[ss->id],
246 lockdep_is_held(&cgroup_tree_mutex) ||
247 lockdep_is_held(&cgroup_mutex));
249 return &cgrp->dummy_css;
253 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
254 * @cgrp: the cgroup of interest
255 * @ss: the subsystem of interest (%NULL returns the dummy_css)
257 * Similar to cgroup_css() but returns the effctive css, which is defined
258 * as the matching css of the nearest ancestor including self which has @ss
259 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
260 * function is guaranteed to return non-NULL css.
262 static struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
263 struct cgroup_subsys *ss)
265 lockdep_assert_held(&cgroup_mutex);
268 return &cgrp->dummy_css;
270 if (!(cgrp->root->subsys_mask & (1 << ss->id)))
273 while (cgrp->parent &&
274 !(cgrp->parent->child_subsys_mask & (1 << ss->id)))
277 return cgroup_css(cgrp, ss);
280 /* convenient tests for these bits */
281 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
283 return test_bit(CGRP_DEAD, &cgrp->flags);
286 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
288 struct cgroup *cgrp = of->kn->parent->priv;
289 struct cftype *cft = of_cft(of);
292 * This is open and unprotected implementation of cgroup_css().
293 * seq_css() is only called from a kernfs file operation which has
294 * an active reference on the file. Because all the subsystem
295 * files are drained before a css is disassociated with a cgroup,
296 * the matching css from the cgroup's subsys table is guaranteed to
297 * be and stay valid until the enclosing operation is complete.
300 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
302 return &cgrp->dummy_css;
304 EXPORT_SYMBOL_GPL(of_css);
307 * cgroup_is_descendant - test ancestry
308 * @cgrp: the cgroup to be tested
309 * @ancestor: possible ancestor of @cgrp
311 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
312 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
313 * and @ancestor are accessible.
315 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
318 if (cgrp == ancestor)
325 static int cgroup_is_releasable(const struct cgroup *cgrp)
328 (1 << CGRP_RELEASABLE) |
329 (1 << CGRP_NOTIFY_ON_RELEASE);
330 return (cgrp->flags & bits) == bits;
333 static int notify_on_release(const struct cgroup *cgrp)
335 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
339 * for_each_css - iterate all css's of a cgroup
340 * @css: the iteration cursor
341 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
342 * @cgrp: the target cgroup to iterate css's of
344 * Should be called under cgroup_[tree_]mutex.
346 #define for_each_css(css, ssid, cgrp) \
347 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
348 if (!((css) = rcu_dereference_check( \
349 (cgrp)->subsys[(ssid)], \
350 lockdep_is_held(&cgroup_tree_mutex) || \
351 lockdep_is_held(&cgroup_mutex)))) { } \
355 * for_each_e_css - iterate all effective css's of a cgroup
356 * @css: the iteration cursor
357 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
358 * @cgrp: the target cgroup to iterate css's of
360 * Should be called under cgroup_[tree_]mutex.
362 #define for_each_e_css(css, ssid, cgrp) \
363 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
364 if (!((css) = cgroup_e_css(cgrp, cgroup_subsys[(ssid)]))) \
369 * for_each_subsys - iterate all enabled cgroup subsystems
370 * @ss: the iteration cursor
371 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
373 #define for_each_subsys(ss, ssid) \
374 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT && \
375 (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
377 /* iterate across the hierarchies */
378 #define for_each_root(root) \
379 list_for_each_entry((root), &cgroup_roots, root_list)
381 /* iterate over child cgrps, lock should be held throughout iteration */
382 #define cgroup_for_each_live_child(child, cgrp) \
383 list_for_each_entry((child), &(cgrp)->children, sibling) \
384 if (({ lockdep_assert_held(&cgroup_tree_mutex); \
385 cgroup_is_dead(child); })) \
390 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
391 * @cgrp: the cgroup to be checked for liveness
393 * On success, returns true; the mutex should be later unlocked. On
394 * failure returns false with no lock held.
396 static bool cgroup_lock_live_group(struct cgroup *cgrp)
398 mutex_lock(&cgroup_mutex);
399 if (cgroup_is_dead(cgrp)) {
400 mutex_unlock(&cgroup_mutex);
406 /* the list of cgroups eligible for automatic release. Protected by
407 * release_list_lock */
408 static LIST_HEAD(release_list);
409 static DEFINE_RAW_SPINLOCK(release_list_lock);
410 static void cgroup_release_agent(struct work_struct *work);
411 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
412 static void check_for_release(struct cgroup *cgrp);
415 * A cgroup can be associated with multiple css_sets as different tasks may
416 * belong to different cgroups on different hierarchies. In the other
417 * direction, a css_set is naturally associated with multiple cgroups.
418 * This M:N relationship is represented by the following link structure
419 * which exists for each association and allows traversing the associations
422 struct cgrp_cset_link {
423 /* the cgroup and css_set this link associates */
425 struct css_set *cset;
427 /* list of cgrp_cset_links anchored at cgrp->cset_links */
428 struct list_head cset_link;
430 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
431 struct list_head cgrp_link;
435 * The default css_set - used by init and its children prior to any
436 * hierarchies being mounted. It contains a pointer to the root state
437 * for each subsystem. Also used to anchor the list of css_sets. Not
438 * reference-counted, to improve performance when child cgroups
439 * haven't been created.
441 struct css_set init_css_set = {
442 .refcount = ATOMIC_INIT(1),
443 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
444 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
445 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
446 .mg_preload_node = LIST_HEAD_INIT(init_css_set.mg_preload_node),
447 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
450 static int css_set_count = 1; /* 1 for init_css_set */
453 * cgroup_update_populated - updated populated count of a cgroup
454 * @cgrp: the target cgroup
455 * @populated: inc or dec populated count
457 * @cgrp is either getting the first task (css_set) or losing the last.
458 * Update @cgrp->populated_cnt accordingly. The count is propagated
459 * towards root so that a given cgroup's populated_cnt is zero iff the
460 * cgroup and all its descendants are empty.
462 * @cgrp's interface file "cgroup.populated" is zero if
463 * @cgrp->populated_cnt is zero and 1 otherwise. When @cgrp->populated_cnt
464 * changes from or to zero, userland is notified that the content of the
465 * interface file has changed. This can be used to detect when @cgrp and
466 * its descendants become populated or empty.
468 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
470 lockdep_assert_held(&css_set_rwsem);
476 trigger = !cgrp->populated_cnt++;
478 trigger = !--cgrp->populated_cnt;
483 if (cgrp->populated_kn)
484 kernfs_notify(cgrp->populated_kn);
490 * hash table for cgroup groups. This improves the performance to find
491 * an existing css_set. This hash doesn't (currently) take into
492 * account cgroups in empty hierarchies.
494 #define CSS_SET_HASH_BITS 7
495 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
497 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
499 unsigned long key = 0UL;
500 struct cgroup_subsys *ss;
503 for_each_subsys(ss, i)
504 key += (unsigned long)css[i];
505 key = (key >> 16) ^ key;
510 static void put_css_set_locked(struct css_set *cset, bool taskexit)
512 struct cgrp_cset_link *link, *tmp_link;
513 struct cgroup_subsys *ss;
516 lockdep_assert_held(&css_set_rwsem);
518 if (!atomic_dec_and_test(&cset->refcount))
521 /* This css_set is dead. unlink it and release cgroup refcounts */
522 for_each_subsys(ss, ssid)
523 list_del(&cset->e_cset_node[ssid]);
524 hash_del(&cset->hlist);
527 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
528 struct cgroup *cgrp = link->cgrp;
530 list_del(&link->cset_link);
531 list_del(&link->cgrp_link);
533 /* @cgrp can't go away while we're holding css_set_rwsem */
534 if (list_empty(&cgrp->cset_links)) {
535 cgroup_update_populated(cgrp, false);
536 if (notify_on_release(cgrp)) {
538 set_bit(CGRP_RELEASABLE, &cgrp->flags);
539 check_for_release(cgrp);
546 kfree_rcu(cset, rcu_head);
549 static void put_css_set(struct css_set *cset, bool taskexit)
552 * Ensure that the refcount doesn't hit zero while any readers
553 * can see it. Similar to atomic_dec_and_lock(), but for an
556 if (atomic_add_unless(&cset->refcount, -1, 1))
559 down_write(&css_set_rwsem);
560 put_css_set_locked(cset, taskexit);
561 up_write(&css_set_rwsem);
565 * refcounted get/put for css_set objects
567 static inline void get_css_set(struct css_set *cset)
569 atomic_inc(&cset->refcount);
573 * compare_css_sets - helper function for find_existing_css_set().
574 * @cset: candidate css_set being tested
575 * @old_cset: existing css_set for a task
576 * @new_cgrp: cgroup that's being entered by the task
577 * @template: desired set of css pointers in css_set (pre-calculated)
579 * Returns true if "cset" matches "old_cset" except for the hierarchy
580 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
582 static bool compare_css_sets(struct css_set *cset,
583 struct css_set *old_cset,
584 struct cgroup *new_cgrp,
585 struct cgroup_subsys_state *template[])
587 struct list_head *l1, *l2;
590 * On the default hierarchy, there can be csets which are
591 * associated with the same set of cgroups but different csses.
592 * Let's first ensure that csses match.
594 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
598 * Compare cgroup pointers in order to distinguish between
599 * different cgroups in hierarchies. As different cgroups may
600 * share the same effective css, this comparison is always
603 l1 = &cset->cgrp_links;
604 l2 = &old_cset->cgrp_links;
606 struct cgrp_cset_link *link1, *link2;
607 struct cgroup *cgrp1, *cgrp2;
611 /* See if we reached the end - both lists are equal length. */
612 if (l1 == &cset->cgrp_links) {
613 BUG_ON(l2 != &old_cset->cgrp_links);
616 BUG_ON(l2 == &old_cset->cgrp_links);
618 /* Locate the cgroups associated with these links. */
619 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
620 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
623 /* Hierarchies should be linked in the same order. */
624 BUG_ON(cgrp1->root != cgrp2->root);
627 * If this hierarchy is the hierarchy of the cgroup
628 * that's changing, then we need to check that this
629 * css_set points to the new cgroup; if it's any other
630 * hierarchy, then this css_set should point to the
631 * same cgroup as the old css_set.
633 if (cgrp1->root == new_cgrp->root) {
634 if (cgrp1 != new_cgrp)
645 * find_existing_css_set - init css array and find the matching css_set
646 * @old_cset: the css_set that we're using before the cgroup transition
647 * @cgrp: the cgroup that we're moving into
648 * @template: out param for the new set of csses, should be clear on entry
650 static struct css_set *find_existing_css_set(struct css_set *old_cset,
652 struct cgroup_subsys_state *template[])
654 struct cgroup_root *root = cgrp->root;
655 struct cgroup_subsys *ss;
656 struct css_set *cset;
661 * Build the set of subsystem state objects that we want to see in the
662 * new css_set. while subsystems can change globally, the entries here
663 * won't change, so no need for locking.
665 for_each_subsys(ss, i) {
666 if (root->subsys_mask & (1UL << i)) {
668 * @ss is in this hierarchy, so we want the
669 * effective css from @cgrp.
671 template[i] = cgroup_e_css(cgrp, ss);
674 * @ss is not in this hierarchy, so we don't want
677 template[i] = old_cset->subsys[i];
681 key = css_set_hash(template);
682 hash_for_each_possible(css_set_table, cset, hlist, key) {
683 if (!compare_css_sets(cset, old_cset, cgrp, template))
686 /* This css_set matches what we need */
690 /* No existing cgroup group matched */
694 static void free_cgrp_cset_links(struct list_head *links_to_free)
696 struct cgrp_cset_link *link, *tmp_link;
698 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
699 list_del(&link->cset_link);
705 * allocate_cgrp_cset_links - allocate cgrp_cset_links
706 * @count: the number of links to allocate
707 * @tmp_links: list_head the allocated links are put on
709 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
710 * through ->cset_link. Returns 0 on success or -errno.
712 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
714 struct cgrp_cset_link *link;
717 INIT_LIST_HEAD(tmp_links);
719 for (i = 0; i < count; i++) {
720 link = kzalloc(sizeof(*link), GFP_KERNEL);
722 free_cgrp_cset_links(tmp_links);
725 list_add(&link->cset_link, tmp_links);
731 * link_css_set - a helper function to link a css_set to a cgroup
732 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
733 * @cset: the css_set to be linked
734 * @cgrp: the destination cgroup
736 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
739 struct cgrp_cset_link *link;
741 BUG_ON(list_empty(tmp_links));
743 if (cgroup_on_dfl(cgrp))
744 cset->dfl_cgrp = cgrp;
746 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
750 if (list_empty(&cgrp->cset_links))
751 cgroup_update_populated(cgrp, true);
752 list_move(&link->cset_link, &cgrp->cset_links);
755 * Always add links to the tail of the list so that the list
756 * is sorted by order of hierarchy creation
758 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
762 * find_css_set - return a new css_set with one cgroup updated
763 * @old_cset: the baseline css_set
764 * @cgrp: the cgroup to be updated
766 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
767 * substituted into the appropriate hierarchy.
769 static struct css_set *find_css_set(struct css_set *old_cset,
772 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
773 struct css_set *cset;
774 struct list_head tmp_links;
775 struct cgrp_cset_link *link;
776 struct cgroup_subsys *ss;
780 lockdep_assert_held(&cgroup_mutex);
782 /* First see if we already have a cgroup group that matches
784 down_read(&css_set_rwsem);
785 cset = find_existing_css_set(old_cset, cgrp, template);
788 up_read(&css_set_rwsem);
793 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
797 /* Allocate all the cgrp_cset_link objects that we'll need */
798 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
803 atomic_set(&cset->refcount, 1);
804 INIT_LIST_HEAD(&cset->cgrp_links);
805 INIT_LIST_HEAD(&cset->tasks);
806 INIT_LIST_HEAD(&cset->mg_tasks);
807 INIT_LIST_HEAD(&cset->mg_preload_node);
808 INIT_LIST_HEAD(&cset->mg_node);
809 INIT_HLIST_NODE(&cset->hlist);
811 /* Copy the set of subsystem state objects generated in
812 * find_existing_css_set() */
813 memcpy(cset->subsys, template, sizeof(cset->subsys));
815 down_write(&css_set_rwsem);
816 /* Add reference counts and links from the new css_set. */
817 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
818 struct cgroup *c = link->cgrp;
820 if (c->root == cgrp->root)
822 link_css_set(&tmp_links, cset, c);
825 BUG_ON(!list_empty(&tmp_links));
829 /* Add @cset to the hash table */
830 key = css_set_hash(cset->subsys);
831 hash_add(css_set_table, &cset->hlist, key);
833 for_each_subsys(ss, ssid)
834 list_add_tail(&cset->e_cset_node[ssid],
835 &cset->subsys[ssid]->cgroup->e_csets[ssid]);
837 up_write(&css_set_rwsem);
842 static struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
844 struct cgroup *root_cgrp = kf_root->kn->priv;
846 return root_cgrp->root;
849 static int cgroup_init_root_id(struct cgroup_root *root)
853 lockdep_assert_held(&cgroup_mutex);
855 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
859 root->hierarchy_id = id;
863 static void cgroup_exit_root_id(struct cgroup_root *root)
865 lockdep_assert_held(&cgroup_mutex);
867 if (root->hierarchy_id) {
868 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
869 root->hierarchy_id = 0;
873 static void cgroup_free_root(struct cgroup_root *root)
876 /* hierarhcy ID shoulid already have been released */
877 WARN_ON_ONCE(root->hierarchy_id);
879 idr_destroy(&root->cgroup_idr);
884 static void cgroup_destroy_root(struct cgroup_root *root)
886 struct cgroup *cgrp = &root->cgrp;
887 struct cgrp_cset_link *link, *tmp_link;
889 mutex_lock(&cgroup_tree_mutex);
890 mutex_lock(&cgroup_mutex);
892 BUG_ON(atomic_read(&root->nr_cgrps));
893 BUG_ON(!list_empty(&cgrp->children));
895 /* Rebind all subsystems back to the default hierarchy */
896 rebind_subsystems(&cgrp_dfl_root, root->subsys_mask);
899 * Release all the links from cset_links to this hierarchy's
902 down_write(&css_set_rwsem);
904 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
905 list_del(&link->cset_link);
906 list_del(&link->cgrp_link);
909 up_write(&css_set_rwsem);
911 if (!list_empty(&root->root_list)) {
912 list_del(&root->root_list);
916 cgroup_exit_root_id(root);
918 mutex_unlock(&cgroup_mutex);
919 mutex_unlock(&cgroup_tree_mutex);
921 kernfs_destroy_root(root->kf_root);
922 cgroup_free_root(root);
925 /* look up cgroup associated with given css_set on the specified hierarchy */
926 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
927 struct cgroup_root *root)
929 struct cgroup *res = NULL;
931 lockdep_assert_held(&cgroup_mutex);
932 lockdep_assert_held(&css_set_rwsem);
934 if (cset == &init_css_set) {
937 struct cgrp_cset_link *link;
939 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
940 struct cgroup *c = link->cgrp;
942 if (c->root == root) {
954 * Return the cgroup for "task" from the given hierarchy. Must be
955 * called with cgroup_mutex and css_set_rwsem held.
957 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
958 struct cgroup_root *root)
961 * No need to lock the task - since we hold cgroup_mutex the
962 * task can't change groups, so the only thing that can happen
963 * is that it exits and its css is set back to init_css_set.
965 return cset_cgroup_from_root(task_css_set(task), root);
969 * A task must hold cgroup_mutex to modify cgroups.
971 * Any task can increment and decrement the count field without lock.
972 * So in general, code holding cgroup_mutex can't rely on the count
973 * field not changing. However, if the count goes to zero, then only
974 * cgroup_attach_task() can increment it again. Because a count of zero
975 * means that no tasks are currently attached, therefore there is no
976 * way a task attached to that cgroup can fork (the other way to
977 * increment the count). So code holding cgroup_mutex can safely
978 * assume that if the count is zero, it will stay zero. Similarly, if
979 * a task holds cgroup_mutex on a cgroup with zero count, it
980 * knows that the cgroup won't be removed, as cgroup_rmdir()
983 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
984 * (usually) take cgroup_mutex. These are the two most performance
985 * critical pieces of code here. The exception occurs on cgroup_exit(),
986 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
987 * is taken, and if the cgroup count is zero, a usermode call made
988 * to the release agent with the name of the cgroup (path relative to
989 * the root of cgroup file system) as the argument.
991 * A cgroup can only be deleted if both its 'count' of using tasks
992 * is zero, and its list of 'children' cgroups is empty. Since all
993 * tasks in the system use _some_ cgroup, and since there is always at
994 * least one task in the system (init, pid == 1), therefore, root cgroup
995 * always has either children cgroups and/or using tasks. So we don't
996 * need a special hack to ensure that root cgroup cannot be deleted.
998 * P.S. One more locking exception. RCU is used to guard the
999 * update of a tasks cgroup pointer by cgroup_attach_task()
1002 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned int subsys_mask);
1003 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
1004 static const struct file_operations proc_cgroupstats_operations;
1006 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
1009 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
1010 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
1011 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
1012 cft->ss->name, cft->name);
1014 strncpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
1019 * cgroup_file_mode - deduce file mode of a control file
1020 * @cft: the control file in question
1022 * returns cft->mode if ->mode is not 0
1023 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
1024 * returns S_IRUGO if it has only a read handler
1025 * returns S_IWUSR if it has only a write hander
1027 static umode_t cgroup_file_mode(const struct cftype *cft)
1034 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1037 if (cft->write_u64 || cft->write_s64 || cft->write ||
1038 cft->write_string || cft->trigger)
1044 static void cgroup_free_fn(struct work_struct *work)
1046 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
1048 atomic_dec(&cgrp->root->nr_cgrps);
1049 cgroup_pidlist_destroy_all(cgrp);
1053 * We get a ref to the parent, and put the ref when this
1054 * cgroup is being freed, so it's guaranteed that the
1055 * parent won't be destroyed before its children.
1057 cgroup_put(cgrp->parent);
1058 kernfs_put(cgrp->kn);
1062 * This is root cgroup's refcnt reaching zero, which
1063 * indicates that the root should be released.
1065 cgroup_destroy_root(cgrp->root);
1069 static void cgroup_free_rcu(struct rcu_head *head)
1071 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
1073 INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
1074 queue_work(cgroup_destroy_wq, &cgrp->destroy_work);
1077 static void cgroup_get(struct cgroup *cgrp)
1079 WARN_ON_ONCE(cgroup_is_dead(cgrp));
1080 WARN_ON_ONCE(atomic_read(&cgrp->refcnt) <= 0);
1081 atomic_inc(&cgrp->refcnt);
1084 static void cgroup_put(struct cgroup *cgrp)
1086 if (!atomic_dec_and_test(&cgrp->refcnt))
1088 if (WARN_ON_ONCE(cgrp->parent && !cgroup_is_dead(cgrp)))
1091 cgroup_idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
1094 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
1097 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1099 char name[CGROUP_FILE_NAME_MAX];
1101 lockdep_assert_held(&cgroup_tree_mutex);
1102 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1106 * cgroup_clear_dir - remove subsys files in a cgroup directory
1107 * @cgrp: target cgroup
1108 * @subsys_mask: mask of the subsystem ids whose files should be removed
1110 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned int subsys_mask)
1112 struct cgroup_subsys *ss;
1115 for_each_subsys(ss, i) {
1116 struct cftype *cfts;
1118 if (!(subsys_mask & (1 << i)))
1120 list_for_each_entry(cfts, &ss->cfts, node)
1121 cgroup_addrm_files(cgrp, cfts, false);
1125 static int rebind_subsystems(struct cgroup_root *dst_root, unsigned int ss_mask)
1127 struct cgroup_subsys *ss;
1130 lockdep_assert_held(&cgroup_tree_mutex);
1131 lockdep_assert_held(&cgroup_mutex);
1133 for_each_subsys(ss, ssid) {
1134 if (!(ss_mask & (1 << ssid)))
1137 /* if @ss has non-root csses attached to it, can't move */
1138 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)))
1141 /* can't move between two non-dummy roots either */
1142 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1146 ret = cgroup_populate_dir(&dst_root->cgrp, ss_mask);
1148 if (dst_root != &cgrp_dfl_root)
1152 * Rebinding back to the default root is not allowed to
1153 * fail. Using both default and non-default roots should
1154 * be rare. Moving subsystems back and forth even more so.
1155 * Just warn about it and continue.
1157 if (cgrp_dfl_root_visible) {
1158 pr_warn("failed to create files (%d) while rebinding 0x%x to default root\n",
1160 pr_warn("you may retry by moving them to a different hierarchy and unbinding\n");
1165 * Nothing can fail from this point on. Remove files for the
1166 * removed subsystems and rebind each subsystem.
1168 mutex_unlock(&cgroup_mutex);
1169 for_each_subsys(ss, ssid)
1170 if (ss_mask & (1 << ssid))
1171 cgroup_clear_dir(&ss->root->cgrp, 1 << ssid);
1172 mutex_lock(&cgroup_mutex);
1174 for_each_subsys(ss, ssid) {
1175 struct cgroup_root *src_root;
1176 struct cgroup_subsys_state *css;
1177 struct css_set *cset;
1179 if (!(ss_mask & (1 << ssid)))
1182 src_root = ss->root;
1183 css = cgroup_css(&src_root->cgrp, ss);
1185 WARN_ON(!css || cgroup_css(&dst_root->cgrp, ss));
1187 RCU_INIT_POINTER(src_root->cgrp.subsys[ssid], NULL);
1188 rcu_assign_pointer(dst_root->cgrp.subsys[ssid], css);
1189 ss->root = dst_root;
1190 css->cgroup = &dst_root->cgrp;
1192 down_write(&css_set_rwsem);
1193 hash_for_each(css_set_table, i, cset, hlist)
1194 list_move_tail(&cset->e_cset_node[ss->id],
1195 &dst_root->cgrp.e_csets[ss->id]);
1196 up_write(&css_set_rwsem);
1198 src_root->subsys_mask &= ~(1 << ssid);
1199 src_root->cgrp.child_subsys_mask &= ~(1 << ssid);
1201 /* default hierarchy doesn't enable controllers by default */
1202 dst_root->subsys_mask |= 1 << ssid;
1203 if (dst_root != &cgrp_dfl_root)
1204 dst_root->cgrp.child_subsys_mask |= 1 << ssid;
1210 kernfs_activate(dst_root->cgrp.kn);
1214 static int cgroup_show_options(struct seq_file *seq,
1215 struct kernfs_root *kf_root)
1217 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1218 struct cgroup_subsys *ss;
1221 for_each_subsys(ss, ssid)
1222 if (root->subsys_mask & (1 << ssid))
1223 seq_printf(seq, ",%s", ss->name);
1224 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1225 seq_puts(seq, ",sane_behavior");
1226 if (root->flags & CGRP_ROOT_NOPREFIX)
1227 seq_puts(seq, ",noprefix");
1228 if (root->flags & CGRP_ROOT_XATTR)
1229 seq_puts(seq, ",xattr");
1231 spin_lock(&release_agent_path_lock);
1232 if (strlen(root->release_agent_path))
1233 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1234 spin_unlock(&release_agent_path_lock);
1236 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags))
1237 seq_puts(seq, ",clone_children");
1238 if (strlen(root->name))
1239 seq_printf(seq, ",name=%s", root->name);
1243 struct cgroup_sb_opts {
1244 unsigned int subsys_mask;
1246 char *release_agent;
1247 bool cpuset_clone_children;
1249 /* User explicitly requested empty subsystem */
1253 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1255 char *token, *o = data;
1256 bool all_ss = false, one_ss = false;
1257 unsigned int mask = -1U;
1258 struct cgroup_subsys *ss;
1261 #ifdef CONFIG_CPUSETS
1262 mask = ~(1U << cpuset_cgrp_id);
1265 memset(opts, 0, sizeof(*opts));
1267 while ((token = strsep(&o, ",")) != NULL) {
1270 if (!strcmp(token, "none")) {
1271 /* Explicitly have no subsystems */
1275 if (!strcmp(token, "all")) {
1276 /* Mutually exclusive option 'all' + subsystem name */
1282 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1283 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1286 if (!strcmp(token, "noprefix")) {
1287 opts->flags |= CGRP_ROOT_NOPREFIX;
1290 if (!strcmp(token, "clone_children")) {
1291 opts->cpuset_clone_children = true;
1294 if (!strcmp(token, "xattr")) {
1295 opts->flags |= CGRP_ROOT_XATTR;
1298 if (!strncmp(token, "release_agent=", 14)) {
1299 /* Specifying two release agents is forbidden */
1300 if (opts->release_agent)
1302 opts->release_agent =
1303 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1304 if (!opts->release_agent)
1308 if (!strncmp(token, "name=", 5)) {
1309 const char *name = token + 5;
1310 /* Can't specify an empty name */
1313 /* Must match [\w.-]+ */
1314 for (i = 0; i < strlen(name); i++) {
1318 if ((c == '.') || (c == '-') || (c == '_'))
1322 /* Specifying two names is forbidden */
1325 opts->name = kstrndup(name,
1326 MAX_CGROUP_ROOT_NAMELEN - 1,
1334 for_each_subsys(ss, i) {
1335 if (strcmp(token, ss->name))
1340 /* Mutually exclusive option 'all' + subsystem name */
1343 opts->subsys_mask |= (1 << i);
1348 if (i == CGROUP_SUBSYS_COUNT)
1352 /* Consistency checks */
1354 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1355 pr_warn("sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1357 if ((opts->flags & (CGRP_ROOT_NOPREFIX | CGRP_ROOT_XATTR)) ||
1358 opts->cpuset_clone_children || opts->release_agent ||
1360 pr_err("sane_behavior: noprefix, xattr, clone_children, release_agent and name are not allowed\n");
1365 * If the 'all' option was specified select all the
1366 * subsystems, otherwise if 'none', 'name=' and a subsystem
1367 * name options were not specified, let's default to 'all'
1369 if (all_ss || (!one_ss && !opts->none && !opts->name))
1370 for_each_subsys(ss, i)
1372 opts->subsys_mask |= (1 << i);
1375 * We either have to specify by name or by subsystems. (So
1376 * all empty hierarchies must have a name).
1378 if (!opts->subsys_mask && !opts->name)
1383 * Option noprefix was introduced just for backward compatibility
1384 * with the old cpuset, so we allow noprefix only if mounting just
1385 * the cpuset subsystem.
1387 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1391 /* Can't specify "none" and some subsystems */
1392 if (opts->subsys_mask && opts->none)
1398 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1401 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1402 struct cgroup_sb_opts opts;
1403 unsigned int added_mask, removed_mask;
1405 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1406 pr_err("sane_behavior: remount is not allowed\n");
1410 mutex_lock(&cgroup_tree_mutex);
1411 mutex_lock(&cgroup_mutex);
1413 /* See what subsystems are wanted */
1414 ret = parse_cgroupfs_options(data, &opts);
1418 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1419 pr_warn("option changes via remount are deprecated (pid=%d comm=%s)\n",
1420 task_tgid_nr(current), current->comm);
1422 added_mask = opts.subsys_mask & ~root->subsys_mask;
1423 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1425 /* Don't allow flags or name to change at remount */
1426 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1427 (opts.name && strcmp(opts.name, root->name))) {
1428 pr_err("option or name mismatch, new: 0x%x \"%s\", old: 0x%x \"%s\"\n",
1429 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1430 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1435 /* remounting is not allowed for populated hierarchies */
1436 if (!list_empty(&root->cgrp.children)) {
1441 ret = rebind_subsystems(root, added_mask);
1445 rebind_subsystems(&cgrp_dfl_root, removed_mask);
1447 if (opts.release_agent) {
1448 spin_lock(&release_agent_path_lock);
1449 strcpy(root->release_agent_path, opts.release_agent);
1450 spin_unlock(&release_agent_path_lock);
1453 kfree(opts.release_agent);
1455 mutex_unlock(&cgroup_mutex);
1456 mutex_unlock(&cgroup_tree_mutex);
1461 * To reduce the fork() overhead for systems that are not actually using
1462 * their cgroups capability, we don't maintain the lists running through
1463 * each css_set to its tasks until we see the list actually used - in other
1464 * words after the first mount.
1466 static bool use_task_css_set_links __read_mostly;
1468 static void cgroup_enable_task_cg_lists(void)
1470 struct task_struct *p, *g;
1472 down_write(&css_set_rwsem);
1474 if (use_task_css_set_links)
1477 use_task_css_set_links = true;
1480 * We need tasklist_lock because RCU is not safe against
1481 * while_each_thread(). Besides, a forking task that has passed
1482 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1483 * is not guaranteed to have its child immediately visible in the
1484 * tasklist if we walk through it with RCU.
1486 read_lock(&tasklist_lock);
1487 do_each_thread(g, p) {
1488 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1489 task_css_set(p) != &init_css_set);
1492 * We should check if the process is exiting, otherwise
1493 * it will race with cgroup_exit() in that the list
1494 * entry won't be deleted though the process has exited.
1495 * Do it while holding siglock so that we don't end up
1496 * racing against cgroup_exit().
1498 spin_lock_irq(&p->sighand->siglock);
1499 if (!(p->flags & PF_EXITING)) {
1500 struct css_set *cset = task_css_set(p);
1502 list_add(&p->cg_list, &cset->tasks);
1505 spin_unlock_irq(&p->sighand->siglock);
1506 } while_each_thread(g, p);
1507 read_unlock(&tasklist_lock);
1509 up_write(&css_set_rwsem);
1512 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1514 struct cgroup_subsys *ss;
1517 atomic_set(&cgrp->refcnt, 1);
1518 INIT_LIST_HEAD(&cgrp->sibling);
1519 INIT_LIST_HEAD(&cgrp->children);
1520 INIT_LIST_HEAD(&cgrp->cset_links);
1521 INIT_LIST_HEAD(&cgrp->release_list);
1522 INIT_LIST_HEAD(&cgrp->pidlists);
1523 mutex_init(&cgrp->pidlist_mutex);
1524 cgrp->dummy_css.cgroup = cgrp;
1526 for_each_subsys(ss, ssid)
1527 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
1529 init_waitqueue_head(&cgrp->offline_waitq);
1532 static void init_cgroup_root(struct cgroup_root *root,
1533 struct cgroup_sb_opts *opts)
1535 struct cgroup *cgrp = &root->cgrp;
1537 INIT_LIST_HEAD(&root->root_list);
1538 atomic_set(&root->nr_cgrps, 1);
1540 init_cgroup_housekeeping(cgrp);
1541 idr_init(&root->cgroup_idr);
1543 root->flags = opts->flags;
1544 if (opts->release_agent)
1545 strcpy(root->release_agent_path, opts->release_agent);
1547 strcpy(root->name, opts->name);
1548 if (opts->cpuset_clone_children)
1549 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1552 static int cgroup_setup_root(struct cgroup_root *root, unsigned int ss_mask)
1554 LIST_HEAD(tmp_links);
1555 struct cgroup *root_cgrp = &root->cgrp;
1556 struct css_set *cset;
1559 lockdep_assert_held(&cgroup_tree_mutex);
1560 lockdep_assert_held(&cgroup_mutex);
1562 ret = cgroup_idr_alloc(&root->cgroup_idr, root_cgrp, 1, 2, GFP_NOWAIT);
1565 root_cgrp->id = ret;
1568 * We're accessing css_set_count without locking css_set_rwsem here,
1569 * but that's OK - it can only be increased by someone holding
1570 * cgroup_lock, and that's us. The worst that can happen is that we
1571 * have some link structures left over
1573 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1577 ret = cgroup_init_root_id(root);
1581 root->kf_root = kernfs_create_root(&cgroup_kf_syscall_ops,
1582 KERNFS_ROOT_CREATE_DEACTIVATED,
1584 if (IS_ERR(root->kf_root)) {
1585 ret = PTR_ERR(root->kf_root);
1588 root_cgrp->kn = root->kf_root->kn;
1590 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1594 ret = rebind_subsystems(root, ss_mask);
1599 * There must be no failure case after here, since rebinding takes
1600 * care of subsystems' refcounts, which are explicitly dropped in
1601 * the failure exit path.
1603 list_add(&root->root_list, &cgroup_roots);
1604 cgroup_root_count++;
1607 * Link the root cgroup in this hierarchy into all the css_set
1610 down_write(&css_set_rwsem);
1611 hash_for_each(css_set_table, i, cset, hlist)
1612 link_css_set(&tmp_links, cset, root_cgrp);
1613 up_write(&css_set_rwsem);
1615 BUG_ON(!list_empty(&root_cgrp->children));
1616 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
1618 kernfs_activate(root_cgrp->kn);
1623 kernfs_destroy_root(root->kf_root);
1624 root->kf_root = NULL;
1626 cgroup_exit_root_id(root);
1628 free_cgrp_cset_links(&tmp_links);
1632 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1633 int flags, const char *unused_dev_name,
1636 struct cgroup_root *root;
1637 struct cgroup_sb_opts opts;
1638 struct dentry *dentry;
1643 * The first time anyone tries to mount a cgroup, enable the list
1644 * linking each css_set to its tasks and fix up all existing tasks.
1646 if (!use_task_css_set_links)
1647 cgroup_enable_task_cg_lists();
1649 mutex_lock(&cgroup_tree_mutex);
1650 mutex_lock(&cgroup_mutex);
1652 /* First find the desired set of subsystems */
1653 ret = parse_cgroupfs_options(data, &opts);
1657 /* look for a matching existing root */
1658 if (!opts.subsys_mask && !opts.none && !opts.name) {
1659 cgrp_dfl_root_visible = true;
1660 root = &cgrp_dfl_root;
1661 cgroup_get(&root->cgrp);
1666 for_each_root(root) {
1667 bool name_match = false;
1669 if (root == &cgrp_dfl_root)
1673 * If we asked for a name then it must match. Also, if
1674 * name matches but sybsys_mask doesn't, we should fail.
1675 * Remember whether name matched.
1678 if (strcmp(opts.name, root->name))
1684 * If we asked for subsystems (or explicitly for no
1685 * subsystems) then they must match.
1687 if ((opts.subsys_mask || opts.none) &&
1688 (opts.subsys_mask != root->subsys_mask)) {
1695 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1696 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1697 pr_err("sane_behavior: new mount options should match the existing superblock\n");
1701 pr_warn("new mount options do not match the existing superblock, will be ignored\n");
1706 * A root's lifetime is governed by its root cgroup. Zero
1707 * ref indicate that the root is being destroyed. Wait for
1708 * destruction to complete so that the subsystems are free.
1709 * We can use wait_queue for the wait but this path is
1710 * super cold. Let's just sleep for a bit and retry.
1712 if (!atomic_inc_not_zero(&root->cgrp.refcnt)) {
1713 mutex_unlock(&cgroup_mutex);
1714 mutex_unlock(&cgroup_tree_mutex);
1716 mutex_lock(&cgroup_tree_mutex);
1717 mutex_lock(&cgroup_mutex);
1726 * No such thing, create a new one. name= matching without subsys
1727 * specification is allowed for already existing hierarchies but we
1728 * can't create new one without subsys specification.
1730 if (!opts.subsys_mask && !opts.none) {
1735 root = kzalloc(sizeof(*root), GFP_KERNEL);
1741 init_cgroup_root(root, &opts);
1743 ret = cgroup_setup_root(root, opts.subsys_mask);
1745 cgroup_free_root(root);
1748 mutex_unlock(&cgroup_mutex);
1749 mutex_unlock(&cgroup_tree_mutex);
1751 kfree(opts.release_agent);
1755 return ERR_PTR(ret);
1757 dentry = kernfs_mount(fs_type, flags, root->kf_root, &new_sb);
1758 if (IS_ERR(dentry) || !new_sb)
1759 cgroup_put(&root->cgrp);
1763 static void cgroup_kill_sb(struct super_block *sb)
1765 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
1766 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1768 cgroup_put(&root->cgrp);
1772 static struct file_system_type cgroup_fs_type = {
1774 .mount = cgroup_mount,
1775 .kill_sb = cgroup_kill_sb,
1778 static struct kobject *cgroup_kobj;
1781 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1782 * @task: target task
1783 * @buf: the buffer to write the path into
1784 * @buflen: the length of the buffer
1786 * Determine @task's cgroup on the first (the one with the lowest non-zero
1787 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1788 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1789 * cgroup controller callbacks.
1791 * Return value is the same as kernfs_path().
1793 char *task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1795 struct cgroup_root *root;
1796 struct cgroup *cgrp;
1797 int hierarchy_id = 1;
1800 mutex_lock(&cgroup_mutex);
1801 down_read(&css_set_rwsem);
1803 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1806 cgrp = task_cgroup_from_root(task, root);
1807 path = cgroup_path(cgrp, buf, buflen);
1809 /* if no hierarchy exists, everyone is in "/" */
1810 if (strlcpy(buf, "/", buflen) < buflen)
1814 up_read(&css_set_rwsem);
1815 mutex_unlock(&cgroup_mutex);
1818 EXPORT_SYMBOL_GPL(task_cgroup_path);
1820 /* used to track tasks and other necessary states during migration */
1821 struct cgroup_taskset {
1822 /* the src and dst cset list running through cset->mg_node */
1823 struct list_head src_csets;
1824 struct list_head dst_csets;
1827 * Fields for cgroup_taskset_*() iteration.
1829 * Before migration is committed, the target migration tasks are on
1830 * ->mg_tasks of the csets on ->src_csets. After, on ->mg_tasks of
1831 * the csets on ->dst_csets. ->csets point to either ->src_csets
1832 * or ->dst_csets depending on whether migration is committed.
1834 * ->cur_csets and ->cur_task point to the current task position
1837 struct list_head *csets;
1838 struct css_set *cur_cset;
1839 struct task_struct *cur_task;
1843 * cgroup_taskset_first - reset taskset and return the first task
1844 * @tset: taskset of interest
1846 * @tset iteration is initialized and the first task is returned.
1848 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1850 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
1851 tset->cur_task = NULL;
1853 return cgroup_taskset_next(tset);
1857 * cgroup_taskset_next - iterate to the next task in taskset
1858 * @tset: taskset of interest
1860 * Return the next task in @tset. Iteration must have been initialized
1861 * with cgroup_taskset_first().
1863 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1865 struct css_set *cset = tset->cur_cset;
1866 struct task_struct *task = tset->cur_task;
1868 while (&cset->mg_node != tset->csets) {
1870 task = list_first_entry(&cset->mg_tasks,
1871 struct task_struct, cg_list);
1873 task = list_next_entry(task, cg_list);
1875 if (&task->cg_list != &cset->mg_tasks) {
1876 tset->cur_cset = cset;
1877 tset->cur_task = task;
1881 cset = list_next_entry(cset, mg_node);
1889 * cgroup_task_migrate - move a task from one cgroup to another.
1890 * @old_cgrp: the cgroup @tsk is being migrated from
1891 * @tsk: the task being migrated
1892 * @new_cset: the new css_set @tsk is being attached to
1894 * Must be called with cgroup_mutex, threadgroup and css_set_rwsem locked.
1896 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1897 struct task_struct *tsk,
1898 struct css_set *new_cset)
1900 struct css_set *old_cset;
1902 lockdep_assert_held(&cgroup_mutex);
1903 lockdep_assert_held(&css_set_rwsem);
1906 * We are synchronized through threadgroup_lock() against PF_EXITING
1907 * setting such that we can't race against cgroup_exit() changing the
1908 * css_set to init_css_set and dropping the old one.
1910 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1911 old_cset = task_css_set(tsk);
1913 get_css_set(new_cset);
1914 rcu_assign_pointer(tsk->cgroups, new_cset);
1917 * Use move_tail so that cgroup_taskset_first() still returns the
1918 * leader after migration. This works because cgroup_migrate()
1919 * ensures that the dst_cset of the leader is the first on the
1920 * tset's dst_csets list.
1922 list_move_tail(&tsk->cg_list, &new_cset->mg_tasks);
1925 * We just gained a reference on old_cset by taking it from the
1926 * task. As trading it for new_cset is protected by cgroup_mutex,
1927 * we're safe to drop it here; it will be freed under RCU.
1929 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1930 put_css_set_locked(old_cset, false);
1934 * cgroup_migrate_finish - cleanup after attach
1935 * @preloaded_csets: list of preloaded css_sets
1937 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
1938 * those functions for details.
1940 static void cgroup_migrate_finish(struct list_head *preloaded_csets)
1942 struct css_set *cset, *tmp_cset;
1944 lockdep_assert_held(&cgroup_mutex);
1946 down_write(&css_set_rwsem);
1947 list_for_each_entry_safe(cset, tmp_cset, preloaded_csets, mg_preload_node) {
1948 cset->mg_src_cgrp = NULL;
1949 cset->mg_dst_cset = NULL;
1950 list_del_init(&cset->mg_preload_node);
1951 put_css_set_locked(cset, false);
1953 up_write(&css_set_rwsem);
1957 * cgroup_migrate_add_src - add a migration source css_set
1958 * @src_cset: the source css_set to add
1959 * @dst_cgrp: the destination cgroup
1960 * @preloaded_csets: list of preloaded css_sets
1962 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
1963 * @src_cset and add it to @preloaded_csets, which should later be cleaned
1964 * up by cgroup_migrate_finish().
1966 * This function may be called without holding threadgroup_lock even if the
1967 * target is a process. Threads may be created and destroyed but as long
1968 * as cgroup_mutex is not dropped, no new css_set can be put into play and
1969 * the preloaded css_sets are guaranteed to cover all migrations.
1971 static void cgroup_migrate_add_src(struct css_set *src_cset,
1972 struct cgroup *dst_cgrp,
1973 struct list_head *preloaded_csets)
1975 struct cgroup *src_cgrp;
1977 lockdep_assert_held(&cgroup_mutex);
1978 lockdep_assert_held(&css_set_rwsem);
1980 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
1982 if (!list_empty(&src_cset->mg_preload_node))
1985 WARN_ON(src_cset->mg_src_cgrp);
1986 WARN_ON(!list_empty(&src_cset->mg_tasks));
1987 WARN_ON(!list_empty(&src_cset->mg_node));
1989 src_cset->mg_src_cgrp = src_cgrp;
1990 get_css_set(src_cset);
1991 list_add(&src_cset->mg_preload_node, preloaded_csets);
1995 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
1996 * @dst_cgrp: the destination cgroup (may be %NULL)
1997 * @preloaded_csets: list of preloaded source css_sets
1999 * Tasks are about to be moved to @dst_cgrp and all the source css_sets
2000 * have been preloaded to @preloaded_csets. This function looks up and
2001 * pins all destination css_sets, links each to its source, and append them
2002 * to @preloaded_csets. If @dst_cgrp is %NULL, the destination of each
2003 * source css_set is assumed to be its cgroup on the default hierarchy.
2005 * This function must be called after cgroup_migrate_add_src() has been
2006 * called on each migration source css_set. After migration is performed
2007 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2010 static int cgroup_migrate_prepare_dst(struct cgroup *dst_cgrp,
2011 struct list_head *preloaded_csets)
2014 struct css_set *src_cset, *tmp_cset;
2016 lockdep_assert_held(&cgroup_mutex);
2019 * Except for the root, child_subsys_mask must be zero for a cgroup
2020 * with tasks so that child cgroups don't compete against tasks.
2022 if (dst_cgrp && cgroup_on_dfl(dst_cgrp) && dst_cgrp->parent &&
2023 dst_cgrp->child_subsys_mask)
2026 /* look up the dst cset for each src cset and link it to src */
2027 list_for_each_entry_safe(src_cset, tmp_cset, preloaded_csets, mg_preload_node) {
2028 struct css_set *dst_cset;
2030 dst_cset = find_css_set(src_cset,
2031 dst_cgrp ?: src_cset->dfl_cgrp);
2035 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2038 * If src cset equals dst, it's noop. Drop the src.
2039 * cgroup_migrate() will skip the cset too. Note that we
2040 * can't handle src == dst as some nodes are used by both.
2042 if (src_cset == dst_cset) {
2043 src_cset->mg_src_cgrp = NULL;
2044 list_del_init(&src_cset->mg_preload_node);
2045 put_css_set(src_cset, false);
2046 put_css_set(dst_cset, false);
2050 src_cset->mg_dst_cset = dst_cset;
2052 if (list_empty(&dst_cset->mg_preload_node))
2053 list_add(&dst_cset->mg_preload_node, &csets);
2055 put_css_set(dst_cset, false);
2058 list_splice_tail(&csets, preloaded_csets);
2061 cgroup_migrate_finish(&csets);
2066 * cgroup_migrate - migrate a process or task to a cgroup
2067 * @cgrp: the destination cgroup
2068 * @leader: the leader of the process or the task to migrate
2069 * @threadgroup: whether @leader points to the whole process or a single task
2071 * Migrate a process or task denoted by @leader to @cgrp. If migrating a
2072 * process, the caller must be holding threadgroup_lock of @leader. The
2073 * caller is also responsible for invoking cgroup_migrate_add_src() and
2074 * cgroup_migrate_prepare_dst() on the targets before invoking this
2075 * function and following up with cgroup_migrate_finish().
2077 * As long as a controller's ->can_attach() doesn't fail, this function is
2078 * guaranteed to succeed. This means that, excluding ->can_attach()
2079 * failure, when migrating multiple targets, the success or failure can be
2080 * decided for all targets by invoking group_migrate_prepare_dst() before
2081 * actually starting migrating.
2083 static int cgroup_migrate(struct cgroup *cgrp, struct task_struct *leader,
2086 struct cgroup_taskset tset = {
2087 .src_csets = LIST_HEAD_INIT(tset.src_csets),
2088 .dst_csets = LIST_HEAD_INIT(tset.dst_csets),
2089 .csets = &tset.src_csets,
2091 struct cgroup_subsys_state *css, *failed_css = NULL;
2092 struct css_set *cset, *tmp_cset;
2093 struct task_struct *task, *tmp_task;
2097 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2098 * already PF_EXITING could be freed from underneath us unless we
2099 * take an rcu_read_lock.
2101 down_write(&css_set_rwsem);
2105 /* @task either already exited or can't exit until the end */
2106 if (task->flags & PF_EXITING)
2109 /* leave @task alone if post_fork() hasn't linked it yet */
2110 if (list_empty(&task->cg_list))
2113 cset = task_css_set(task);
2114 if (!cset->mg_src_cgrp)
2118 * cgroup_taskset_first() must always return the leader.
2119 * Take care to avoid disturbing the ordering.
2121 list_move_tail(&task->cg_list, &cset->mg_tasks);
2122 if (list_empty(&cset->mg_node))
2123 list_add_tail(&cset->mg_node, &tset.src_csets);
2124 if (list_empty(&cset->mg_dst_cset->mg_node))
2125 list_move_tail(&cset->mg_dst_cset->mg_node,
2130 } while_each_thread(leader, task);
2132 up_write(&css_set_rwsem);
2134 /* methods shouldn't be called if no task is actually migrating */
2135 if (list_empty(&tset.src_csets))
2138 /* check that we can legitimately attach to the cgroup */
2139 for_each_e_css(css, i, cgrp) {
2140 if (css->ss->can_attach) {
2141 ret = css->ss->can_attach(css, &tset);
2144 goto out_cancel_attach;
2150 * Now that we're guaranteed success, proceed to move all tasks to
2151 * the new cgroup. There are no failure cases after here, so this
2152 * is the commit point.
2154 down_write(&css_set_rwsem);
2155 list_for_each_entry(cset, &tset.src_csets, mg_node) {
2156 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list)
2157 cgroup_task_migrate(cset->mg_src_cgrp, task,
2160 up_write(&css_set_rwsem);
2163 * Migration is committed, all target tasks are now on dst_csets.
2164 * Nothing is sensitive to fork() after this point. Notify
2165 * controllers that migration is complete.
2167 tset.csets = &tset.dst_csets;
2169 for_each_e_css(css, i, cgrp)
2170 if (css->ss->attach)
2171 css->ss->attach(css, &tset);
2174 goto out_release_tset;
2177 for_each_e_css(css, i, cgrp) {
2178 if (css == failed_css)
2180 if (css->ss->cancel_attach)
2181 css->ss->cancel_attach(css, &tset);
2184 down_write(&css_set_rwsem);
2185 list_splice_init(&tset.dst_csets, &tset.src_csets);
2186 list_for_each_entry_safe(cset, tmp_cset, &tset.src_csets, mg_node) {
2187 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2188 list_del_init(&cset->mg_node);
2190 up_write(&css_set_rwsem);
2195 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2196 * @dst_cgrp: the cgroup to attach to
2197 * @leader: the task or the leader of the threadgroup to be attached
2198 * @threadgroup: attach the whole threadgroup?
2200 * Call holding cgroup_mutex and threadgroup_lock of @leader.
2202 static int cgroup_attach_task(struct cgroup *dst_cgrp,
2203 struct task_struct *leader, bool threadgroup)
2205 LIST_HEAD(preloaded_csets);
2206 struct task_struct *task;
2209 /* look up all src csets */
2210 down_read(&css_set_rwsem);
2214 cgroup_migrate_add_src(task_css_set(task), dst_cgrp,
2218 } while_each_thread(leader, task);
2220 up_read(&css_set_rwsem);
2222 /* prepare dst csets and commit */
2223 ret = cgroup_migrate_prepare_dst(dst_cgrp, &preloaded_csets);
2225 ret = cgroup_migrate(dst_cgrp, leader, threadgroup);
2227 cgroup_migrate_finish(&preloaded_csets);
2232 * Find the task_struct of the task to attach by vpid and pass it along to the
2233 * function to attach either it or all tasks in its threadgroup. Will lock
2234 * cgroup_mutex and threadgroup.
2236 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2238 struct task_struct *tsk;
2239 const struct cred *cred = current_cred(), *tcred;
2242 if (!cgroup_lock_live_group(cgrp))
2248 tsk = find_task_by_vpid(pid);
2252 goto out_unlock_cgroup;
2255 * even if we're attaching all tasks in the thread group, we
2256 * only need to check permissions on one of them.
2258 tcred = __task_cred(tsk);
2259 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2260 !uid_eq(cred->euid, tcred->uid) &&
2261 !uid_eq(cred->euid, tcred->suid)) {
2264 goto out_unlock_cgroup;
2270 tsk = tsk->group_leader;
2273 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2274 * trapped in a cpuset, or RT worker may be born in a cgroup
2275 * with no rt_runtime allocated. Just say no.
2277 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2280 goto out_unlock_cgroup;
2283 get_task_struct(tsk);
2286 threadgroup_lock(tsk);
2288 if (!thread_group_leader(tsk)) {
2290 * a race with de_thread from another thread's exec()
2291 * may strip us of our leadership, if this happens,
2292 * there is no choice but to throw this task away and
2293 * try again; this is
2294 * "double-double-toil-and-trouble-check locking".
2296 threadgroup_unlock(tsk);
2297 put_task_struct(tsk);
2298 goto retry_find_task;
2302 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2304 threadgroup_unlock(tsk);
2306 put_task_struct(tsk);
2308 mutex_unlock(&cgroup_mutex);
2313 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2314 * @from: attach to all cgroups of a given task
2315 * @tsk: the task to be attached
2317 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2319 struct cgroup_root *root;
2322 mutex_lock(&cgroup_mutex);
2323 for_each_root(root) {
2324 struct cgroup *from_cgrp;
2326 if (root == &cgrp_dfl_root)
2329 down_read(&css_set_rwsem);
2330 from_cgrp = task_cgroup_from_root(from, root);
2331 up_read(&css_set_rwsem);
2333 retval = cgroup_attach_task(from_cgrp, tsk, false);
2337 mutex_unlock(&cgroup_mutex);
2341 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2343 static int cgroup_tasks_write(struct cgroup_subsys_state *css,
2344 struct cftype *cft, u64 pid)
2346 return attach_task_by_pid(css->cgroup, pid, false);
2349 static int cgroup_procs_write(struct cgroup_subsys_state *css,
2350 struct cftype *cft, u64 tgid)
2352 return attach_task_by_pid(css->cgroup, tgid, true);
2355 static int cgroup_release_agent_write(struct cgroup_subsys_state *css,
2356 struct cftype *cft, char *buffer)
2358 struct cgroup_root *root = css->cgroup->root;
2360 BUILD_BUG_ON(sizeof(root->release_agent_path) < PATH_MAX);
2361 if (!cgroup_lock_live_group(css->cgroup))
2363 spin_lock(&release_agent_path_lock);
2364 strlcpy(root->release_agent_path, buffer,
2365 sizeof(root->release_agent_path));
2366 spin_unlock(&release_agent_path_lock);
2367 mutex_unlock(&cgroup_mutex);
2371 static int cgroup_release_agent_show(struct seq_file *seq, void *v)
2373 struct cgroup *cgrp = seq_css(seq)->cgroup;
2375 spin_lock(&release_agent_path_lock);
2376 seq_puts(seq, cgrp->root->release_agent_path);
2377 spin_unlock(&release_agent_path_lock);
2378 seq_putc(seq, '\n');
2382 static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
2384 struct cgroup *cgrp = seq_css(seq)->cgroup;
2386 seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
2390 static void cgroup_print_ss_mask(struct seq_file *seq, unsigned int ss_mask)
2392 struct cgroup_subsys *ss;
2393 bool printed = false;
2396 for_each_subsys(ss, ssid) {
2397 if (ss_mask & (1 << ssid)) {
2400 seq_printf(seq, "%s", ss->name);
2405 seq_putc(seq, '\n');
2408 /* show controllers which are currently attached to the default hierarchy */
2409 static int cgroup_root_controllers_show(struct seq_file *seq, void *v)
2411 struct cgroup *cgrp = seq_css(seq)->cgroup;
2413 cgroup_print_ss_mask(seq, cgrp->root->subsys_mask);
2417 /* show controllers which are enabled from the parent */
2418 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2420 struct cgroup *cgrp = seq_css(seq)->cgroup;
2422 cgroup_print_ss_mask(seq, cgrp->parent->child_subsys_mask);
2426 /* show controllers which are enabled for a given cgroup's children */
2427 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2429 struct cgroup *cgrp = seq_css(seq)->cgroup;
2431 cgroup_print_ss_mask(seq, cgrp->child_subsys_mask);
2436 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2437 * @cgrp: root of the subtree to update csses for
2439 * @cgrp's child_subsys_mask has changed and its subtree's (self excluded)
2440 * css associations need to be updated accordingly. This function looks up
2441 * all css_sets which are attached to the subtree, creates the matching
2442 * updated css_sets and migrates the tasks to the new ones.
2444 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2446 LIST_HEAD(preloaded_csets);
2447 struct cgroup_subsys_state *css;
2448 struct css_set *src_cset;
2451 lockdep_assert_held(&cgroup_tree_mutex);
2452 lockdep_assert_held(&cgroup_mutex);
2454 /* look up all csses currently attached to @cgrp's subtree */
2455 down_read(&css_set_rwsem);
2456 css_for_each_descendant_pre(css, cgroup_css(cgrp, NULL)) {
2457 struct cgrp_cset_link *link;
2459 /* self is not affected by child_subsys_mask change */
2460 if (css->cgroup == cgrp)
2463 list_for_each_entry(link, &css->cgroup->cset_links, cset_link)
2464 cgroup_migrate_add_src(link->cset, cgrp,
2467 up_read(&css_set_rwsem);
2469 /* NULL dst indicates self on default hierarchy */
2470 ret = cgroup_migrate_prepare_dst(NULL, &preloaded_csets);
2474 list_for_each_entry(src_cset, &preloaded_csets, mg_preload_node) {
2475 struct task_struct *last_task = NULL, *task;
2477 /* src_csets precede dst_csets, break on the first dst_cset */
2478 if (!src_cset->mg_src_cgrp)
2482 * All tasks in src_cset need to be migrated to the
2483 * matching dst_cset. Empty it process by process. We
2484 * walk tasks but migrate processes. The leader might even
2485 * belong to a different cset but such src_cset would also
2486 * be among the target src_csets because the default
2487 * hierarchy enforces per-process membership.
2490 down_read(&css_set_rwsem);
2491 task = list_first_entry_or_null(&src_cset->tasks,
2492 struct task_struct, cg_list);
2494 task = task->group_leader;
2495 WARN_ON_ONCE(!task_css_set(task)->mg_src_cgrp);
2496 get_task_struct(task);
2498 up_read(&css_set_rwsem);
2503 /* guard against possible infinite loop */
2504 if (WARN(last_task == task,
2505 "cgroup: update_dfl_csses failed to make progress, aborting in inconsistent state\n"))
2509 threadgroup_lock(task);
2510 /* raced against de_thread() from another thread? */
2511 if (!thread_group_leader(task)) {
2512 threadgroup_unlock(task);
2513 put_task_struct(task);
2517 ret = cgroup_migrate(src_cset->dfl_cgrp, task, true);
2519 threadgroup_unlock(task);
2520 put_task_struct(task);
2522 if (WARN(ret, "cgroup: failed to update controllers for the default hierarchy (%d), further operations may crash or hang\n", ret))
2528 cgroup_migrate_finish(&preloaded_csets);
2532 /* change the enabled child controllers for a cgroup in the default hierarchy */
2533 static int cgroup_subtree_control_write(struct cgroup_subsys_state *dummy_css,
2534 struct cftype *cft, char *buffer)
2536 unsigned int enable = 0, disable = 0;
2537 struct cgroup *cgrp = dummy_css->cgroup, *child;
2538 struct cgroup_subsys *ss;
2543 * Parse input - space separated list of subsystem names prefixed
2544 * with either + or -.
2547 while ((tok = strsep(&p, " "))) {
2550 for_each_subsys(ss, ssid) {
2551 if (ss->disabled || strcmp(tok + 1, ss->name))
2555 enable |= 1 << ssid;
2556 disable &= ~(1 << ssid);
2557 } else if (*tok == '-') {
2558 disable |= 1 << ssid;
2559 enable &= ~(1 << ssid);
2565 if (ssid == CGROUP_SUBSYS_COUNT)
2570 * We're gonna grab cgroup_tree_mutex which nests outside kernfs
2571 * active_ref. cgroup_lock_live_group() already provides enough
2572 * protection. Ensure @cgrp stays accessible and break the
2573 * active_ref protection.
2576 kernfs_break_active_protection(cgrp->control_kn);
2578 mutex_lock(&cgroup_tree_mutex);
2580 for_each_subsys(ss, ssid) {
2581 if (enable & (1 << ssid)) {
2582 if (cgrp->child_subsys_mask & (1 << ssid)) {
2583 enable &= ~(1 << ssid);
2588 * Because css offlining is asynchronous, userland
2589 * might try to re-enable the same controller while
2590 * the previous instance is still around. In such
2591 * cases, wait till it's gone using offline_waitq.
2593 cgroup_for_each_live_child(child, cgrp) {
2596 if (!cgroup_css(child, ss))
2600 prepare_to_wait(&child->offline_waitq, &wait,
2601 TASK_UNINTERRUPTIBLE);
2602 mutex_unlock(&cgroup_tree_mutex);
2604 finish_wait(&child->offline_waitq, &wait);
2607 ret = restart_syscall();
2611 /* unavailable or not enabled on the parent? */
2612 if (!(cgrp_dfl_root.subsys_mask & (1 << ssid)) ||
2614 !(cgrp->parent->child_subsys_mask & (1 << ssid)))) {
2616 goto out_unlock_tree;
2618 } else if (disable & (1 << ssid)) {
2619 if (!(cgrp->child_subsys_mask & (1 << ssid))) {
2620 disable &= ~(1 << ssid);
2624 /* a child has it enabled? */
2625 cgroup_for_each_live_child(child, cgrp) {
2626 if (child->child_subsys_mask & (1 << ssid)) {
2628 goto out_unlock_tree;
2634 if (!enable && !disable) {
2636 goto out_unlock_tree;
2639 if (!cgroup_lock_live_group(cgrp)) {
2641 goto out_unlock_tree;
2645 * Except for the root, child_subsys_mask must be zero for a cgroup
2646 * with tasks so that child cgroups don't compete against tasks.
2648 if (enable && cgrp->parent && !list_empty(&cgrp->cset_links)) {
2654 * Create csses for enables and update child_subsys_mask. This
2655 * changes cgroup_e_css() results which in turn makes the
2656 * subsequent cgroup_update_dfl_csses() associate all tasks in the
2657 * subtree to the updated csses.
2659 for_each_subsys(ss, ssid) {
2660 if (!(enable & (1 << ssid)))
2663 cgroup_for_each_live_child(child, cgrp) {
2664 ret = create_css(child, ss);
2670 cgrp->child_subsys_mask |= enable;
2671 cgrp->child_subsys_mask &= ~disable;
2673 ret = cgroup_update_dfl_csses(cgrp);
2677 /* all tasks are now migrated away from the old csses, kill them */
2678 for_each_subsys(ss, ssid) {
2679 if (!(disable & (1 << ssid)))
2682 cgroup_for_each_live_child(child, cgrp)
2683 kill_css(cgroup_css(child, ss));
2686 kernfs_activate(cgrp->kn);
2689 mutex_unlock(&cgroup_mutex);
2691 mutex_unlock(&cgroup_tree_mutex);
2693 kernfs_unbreak_active_protection(cgrp->control_kn);
2698 cgrp->child_subsys_mask &= ~enable;
2699 cgrp->child_subsys_mask |= disable;
2701 for_each_subsys(ss, ssid) {
2702 if (!(enable & (1 << ssid)))
2705 cgroup_for_each_live_child(child, cgrp) {
2706 struct cgroup_subsys_state *css = cgroup_css(child, ss);
2714 static int cgroup_populated_show(struct seq_file *seq, void *v)
2716 seq_printf(seq, "%d\n", (bool)seq_css(seq)->cgroup->populated_cnt);
2720 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
2721 size_t nbytes, loff_t off)
2723 struct cgroup *cgrp = of->kn->parent->priv;
2724 struct cftype *cft = of->kn->priv;
2725 struct cgroup_subsys_state *css;
2729 return cft->write(of, buf, nbytes, off);
2732 * kernfs guarantees that a file isn't deleted with operations in
2733 * flight, which means that the matching css is and stays alive and
2734 * doesn't need to be pinned. The RCU locking is not necessary
2735 * either. It's just for the convenience of using cgroup_css().
2738 css = cgroup_css(cgrp, cft->ss);
2741 if (cft->write_string) {
2742 ret = cft->write_string(css, cft, strstrip(buf));
2743 } else if (cft->write_u64) {
2744 unsigned long long v;
2745 ret = kstrtoull(buf, 0, &v);
2747 ret = cft->write_u64(css, cft, v);
2748 } else if (cft->write_s64) {
2750 ret = kstrtoll(buf, 0, &v);
2752 ret = cft->write_s64(css, cft, v);
2753 } else if (cft->trigger) {
2754 ret = cft->trigger(css, (unsigned int)cft->private);
2759 return ret ?: nbytes;
2762 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
2764 return seq_cft(seq)->seq_start(seq, ppos);
2767 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
2769 return seq_cft(seq)->seq_next(seq, v, ppos);
2772 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
2774 seq_cft(seq)->seq_stop(seq, v);
2777 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2779 struct cftype *cft = seq_cft(m);
2780 struct cgroup_subsys_state *css = seq_css(m);
2783 return cft->seq_show(m, arg);
2786 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
2787 else if (cft->read_s64)
2788 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
2794 static struct kernfs_ops cgroup_kf_single_ops = {
2795 .atomic_write_len = PAGE_SIZE,
2796 .write = cgroup_file_write,
2797 .seq_show = cgroup_seqfile_show,
2800 static struct kernfs_ops cgroup_kf_ops = {
2801 .atomic_write_len = PAGE_SIZE,
2802 .write = cgroup_file_write,
2803 .seq_start = cgroup_seqfile_start,
2804 .seq_next = cgroup_seqfile_next,
2805 .seq_stop = cgroup_seqfile_stop,
2806 .seq_show = cgroup_seqfile_show,
2810 * cgroup_rename - Only allow simple rename of directories in place.
2812 static int cgroup_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
2813 const char *new_name_str)
2815 struct cgroup *cgrp = kn->priv;
2818 if (kernfs_type(kn) != KERNFS_DIR)
2820 if (kn->parent != new_parent)
2824 * This isn't a proper migration and its usefulness is very
2825 * limited. Disallow if sane_behavior.
2827 if (cgroup_sane_behavior(cgrp))
2831 * We're gonna grab cgroup_tree_mutex which nests outside kernfs
2832 * active_ref. kernfs_rename() doesn't require active_ref
2833 * protection. Break them before grabbing cgroup_tree_mutex.
2835 kernfs_break_active_protection(new_parent);
2836 kernfs_break_active_protection(kn);
2838 mutex_lock(&cgroup_tree_mutex);
2839 mutex_lock(&cgroup_mutex);
2841 ret = kernfs_rename(kn, new_parent, new_name_str);
2843 mutex_unlock(&cgroup_mutex);
2844 mutex_unlock(&cgroup_tree_mutex);
2846 kernfs_unbreak_active_protection(kn);
2847 kernfs_unbreak_active_protection(new_parent);
2851 /* set uid and gid of cgroup dirs and files to that of the creator */
2852 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
2854 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
2855 .ia_uid = current_fsuid(),
2856 .ia_gid = current_fsgid(), };
2858 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
2859 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
2862 return kernfs_setattr(kn, &iattr);
2865 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2867 char name[CGROUP_FILE_NAME_MAX];
2868 struct kernfs_node *kn;
2869 struct lock_class_key *key = NULL;
2872 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2873 key = &cft->lockdep_key;
2875 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
2876 cgroup_file_mode(cft), 0, cft->kf_ops, cft,
2881 ret = cgroup_kn_set_ugid(kn);
2887 if (cft->seq_show == cgroup_subtree_control_show)
2888 cgrp->control_kn = kn;
2889 else if (cft->seq_show == cgroup_populated_show)
2890 cgrp->populated_kn = kn;
2895 * cgroup_addrm_files - add or remove files to a cgroup directory
2896 * @cgrp: the target cgroup
2897 * @cfts: array of cftypes to be added
2898 * @is_add: whether to add or remove
2900 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2901 * For removals, this function never fails. If addition fails, this
2902 * function doesn't remove files already added. The caller is responsible
2905 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2911 lockdep_assert_held(&cgroup_tree_mutex);
2913 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2914 /* does cft->flags tell us to skip this file on @cgrp? */
2915 if ((cft->flags & CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
2917 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2919 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2921 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2925 ret = cgroup_add_file(cgrp, cft);
2927 pr_warn("%s: failed to add %s, err=%d\n",
2928 __func__, cft->name, ret);
2932 cgroup_rm_file(cgrp, cft);
2938 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
2941 struct cgroup_subsys *ss = cfts[0].ss;
2942 struct cgroup *root = &ss->root->cgrp;
2943 struct cgroup_subsys_state *css;
2946 lockdep_assert_held(&cgroup_tree_mutex);
2948 /* add/rm files for all cgroups created before */
2949 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2950 struct cgroup *cgrp = css->cgroup;
2952 if (cgroup_is_dead(cgrp))
2955 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2961 kernfs_activate(root->kn);
2965 static void cgroup_exit_cftypes(struct cftype *cfts)
2969 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2970 /* free copy for custom atomic_write_len, see init_cftypes() */
2971 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
2978 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2982 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2983 struct kernfs_ops *kf_ops;
2985 WARN_ON(cft->ss || cft->kf_ops);
2988 kf_ops = &cgroup_kf_ops;
2990 kf_ops = &cgroup_kf_single_ops;
2993 * Ugh... if @cft wants a custom max_write_len, we need to
2994 * make a copy of kf_ops to set its atomic_write_len.
2996 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
2997 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
2999 cgroup_exit_cftypes(cfts);
3002 kf_ops->atomic_write_len = cft->max_write_len;
3005 cft->kf_ops = kf_ops;
3012 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
3014 lockdep_assert_held(&cgroup_tree_mutex);
3016 if (!cfts || !cfts[0].ss)
3019 list_del(&cfts->node);
3020 cgroup_apply_cftypes(cfts, false);
3021 cgroup_exit_cftypes(cfts);
3026 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
3027 * @cfts: zero-length name terminated array of cftypes
3029 * Unregister @cfts. Files described by @cfts are removed from all
3030 * existing cgroups and all future cgroups won't have them either. This
3031 * function can be called anytime whether @cfts' subsys is attached or not.
3033 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
3036 int cgroup_rm_cftypes(struct cftype *cfts)
3040 mutex_lock(&cgroup_tree_mutex);
3041 ret = cgroup_rm_cftypes_locked(cfts);
3042 mutex_unlock(&cgroup_tree_mutex);
3047 * cgroup_add_cftypes - add an array of cftypes to a subsystem
3048 * @ss: target cgroup subsystem
3049 * @cfts: zero-length name terminated array of cftypes
3051 * Register @cfts to @ss. Files described by @cfts are created for all
3052 * existing cgroups to which @ss is attached and all future cgroups will
3053 * have them too. This function can be called anytime whether @ss is
3056 * Returns 0 on successful registration, -errno on failure. Note that this
3057 * function currently returns 0 as long as @cfts registration is successful
3058 * even if some file creation attempts on existing cgroups fail.
3060 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3064 if (!cfts || cfts[0].name[0] == '\0')
3067 ret = cgroup_init_cftypes(ss, cfts);
3071 mutex_lock(&cgroup_tree_mutex);
3073 list_add_tail(&cfts->node, &ss->cfts);
3074 ret = cgroup_apply_cftypes(cfts, true);
3076 cgroup_rm_cftypes_locked(cfts);
3078 mutex_unlock(&cgroup_tree_mutex);
3083 * cgroup_task_count - count the number of tasks in a cgroup.
3084 * @cgrp: the cgroup in question
3086 * Return the number of tasks in the cgroup.
3088 static int cgroup_task_count(const struct cgroup *cgrp)
3091 struct cgrp_cset_link *link;
3093 down_read(&css_set_rwsem);
3094 list_for_each_entry(link, &cgrp->cset_links, cset_link)
3095 count += atomic_read(&link->cset->refcount);
3096 up_read(&css_set_rwsem);
3101 * css_next_child - find the next child of a given css
3102 * @pos_css: the current position (%NULL to initiate traversal)
3103 * @parent_css: css whose children to walk
3105 * This function returns the next child of @parent_css and should be called
3106 * under either cgroup_mutex or RCU read lock. The only requirement is
3107 * that @parent_css and @pos_css are accessible. The next sibling is
3108 * guaranteed to be returned regardless of their states.
3110 struct cgroup_subsys_state *
3111 css_next_child(struct cgroup_subsys_state *pos_css,
3112 struct cgroup_subsys_state *parent_css)
3114 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
3115 struct cgroup *cgrp = parent_css->cgroup;
3116 struct cgroup *next;
3118 cgroup_assert_mutexes_or_rcu_locked();
3121 * @pos could already have been removed. Once a cgroup is removed,
3122 * its ->sibling.next is no longer updated when its next sibling
3123 * changes. As CGRP_DEAD assertion is serialized and happens
3124 * before the cgroup is taken off the ->sibling list, if we see it
3125 * unasserted, it's guaranteed that the next sibling hasn't
3126 * finished its grace period even if it's already removed, and thus
3127 * safe to dereference from this RCU critical section. If
3128 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
3129 * to be visible as %true here.
3131 * If @pos is dead, its next pointer can't be dereferenced;
3132 * however, as each cgroup is given a monotonically increasing
3133 * unique serial number and always appended to the sibling list,
3134 * the next one can be found by walking the parent's children until
3135 * we see a cgroup with higher serial number than @pos's. While
3136 * this path can be slower, it's taken only when either the current
3137 * cgroup is removed or iteration and removal race.
3140 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
3141 } else if (likely(!cgroup_is_dead(pos))) {
3142 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3144 list_for_each_entry_rcu(next, &cgrp->children, sibling)
3145 if (next->serial_nr > pos->serial_nr)
3150 * @next, if not pointing to the head, can be dereferenced and is
3151 * the next sibling; however, it might have @ss disabled. If so,
3152 * fast-forward to the next enabled one.
3154 while (&next->sibling != &cgrp->children) {
3155 struct cgroup_subsys_state *next_css = cgroup_css(next, parent_css->ss);
3159 next = list_entry_rcu(next->sibling.next, struct cgroup, sibling);
3165 * css_next_descendant_pre - find the next descendant for pre-order walk
3166 * @pos: the current position (%NULL to initiate traversal)
3167 * @root: css whose descendants to walk
3169 * To be used by css_for_each_descendant_pre(). Find the next descendant
3170 * to visit for pre-order traversal of @root's descendants. @root is
3171 * included in the iteration and the first node to be visited.
3173 * While this function requires cgroup_mutex or RCU read locking, it
3174 * doesn't require the whole traversal to be contained in a single critical
3175 * section. This function will return the correct next descendant as long
3176 * as both @pos and @root are accessible and @pos is a descendant of @root.
3178 struct cgroup_subsys_state *
3179 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3180 struct cgroup_subsys_state *root)
3182 struct cgroup_subsys_state *next;
3184 cgroup_assert_mutexes_or_rcu_locked();
3186 /* if first iteration, visit @root */
3190 /* visit the first child if exists */
3191 next = css_next_child(NULL, pos);
3195 /* no child, visit my or the closest ancestor's next sibling */
3196 while (pos != root) {
3197 next = css_next_child(pos, css_parent(pos));
3200 pos = css_parent(pos);
3207 * css_rightmost_descendant - return the rightmost descendant of a css
3208 * @pos: css of interest
3210 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3211 * is returned. This can be used during pre-order traversal to skip
3214 * While this function requires cgroup_mutex or RCU read locking, it
3215 * doesn't require the whole traversal to be contained in a single critical
3216 * section. This function will return the correct rightmost descendant as
3217 * long as @pos is accessible.
3219 struct cgroup_subsys_state *
3220 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3222 struct cgroup_subsys_state *last, *tmp;
3224 cgroup_assert_mutexes_or_rcu_locked();
3228 /* ->prev isn't RCU safe, walk ->next till the end */
3230 css_for_each_child(tmp, last)
3237 static struct cgroup_subsys_state *
3238 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3240 struct cgroup_subsys_state *last;
3244 pos = css_next_child(NULL, pos);
3251 * css_next_descendant_post - find the next descendant for post-order walk
3252 * @pos: the current position (%NULL to initiate traversal)
3253 * @root: css whose descendants to walk
3255 * To be used by css_for_each_descendant_post(). Find the next descendant
3256 * to visit for post-order traversal of @root's descendants. @root is
3257 * included in the iteration and the last node to be visited.
3259 * While this function requires cgroup_mutex or RCU read locking, it
3260 * doesn't require the whole traversal to be contained in a single critical
3261 * section. This function will return the correct next descendant as long
3262 * as both @pos and @cgroup are accessible and @pos is a descendant of
3265 struct cgroup_subsys_state *
3266 css_next_descendant_post(struct cgroup_subsys_state *pos,
3267 struct cgroup_subsys_state *root)
3269 struct cgroup_subsys_state *next;
3271 cgroup_assert_mutexes_or_rcu_locked();
3273 /* if first iteration, visit leftmost descendant which may be @root */
3275 return css_leftmost_descendant(root);
3277 /* if we visited @root, we're done */
3281 /* if there's an unvisited sibling, visit its leftmost descendant */
3282 next = css_next_child(pos, css_parent(pos));
3284 return css_leftmost_descendant(next);
3286 /* no sibling left, visit parent */
3287 return css_parent(pos);
3291 * css_advance_task_iter - advance a task itererator to the next css_set
3292 * @it: the iterator to advance
3294 * Advance @it to the next css_set to walk.
3296 static void css_advance_task_iter(struct css_task_iter *it)
3298 struct list_head *l = it->cset_pos;
3299 struct cgrp_cset_link *link;
3300 struct css_set *cset;
3302 /* Advance to the next non-empty css_set */
3305 if (l == it->cset_head) {
3306 it->cset_pos = NULL;
3311 cset = container_of(l, struct css_set,
3312 e_cset_node[it->ss->id]);
3314 link = list_entry(l, struct cgrp_cset_link, cset_link);
3317 } while (list_empty(&cset->tasks) && list_empty(&cset->mg_tasks));
3321 if (!list_empty(&cset->tasks))
3322 it->task_pos = cset->tasks.next;
3324 it->task_pos = cset->mg_tasks.next;
3326 it->tasks_head = &cset->tasks;
3327 it->mg_tasks_head = &cset->mg_tasks;
3331 * css_task_iter_start - initiate task iteration
3332 * @css: the css to walk tasks of
3333 * @it: the task iterator to use
3335 * Initiate iteration through the tasks of @css. The caller can call
3336 * css_task_iter_next() to walk through the tasks until the function
3337 * returns NULL. On completion of iteration, css_task_iter_end() must be
3340 * Note that this function acquires a lock which is released when the
3341 * iteration finishes. The caller can't sleep while iteration is in
3344 void css_task_iter_start(struct cgroup_subsys_state *css,
3345 struct css_task_iter *it)
3346 __acquires(css_set_rwsem)
3348 /* no one should try to iterate before mounting cgroups */
3349 WARN_ON_ONCE(!use_task_css_set_links);
3351 down_read(&css_set_rwsem);
3356 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
3358 it->cset_pos = &css->cgroup->cset_links;
3360 it->cset_head = it->cset_pos;
3362 css_advance_task_iter(it);
3366 * css_task_iter_next - return the next task for the iterator
3367 * @it: the task iterator being iterated
3369 * The "next" function for task iteration. @it should have been
3370 * initialized via css_task_iter_start(). Returns NULL when the iteration
3373 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3375 struct task_struct *res;
3376 struct list_head *l = it->task_pos;
3378 /* If the iterator cg is NULL, we have no tasks */
3381 res = list_entry(l, struct task_struct, cg_list);
3384 * Advance iterator to find next entry. cset->tasks is consumed
3385 * first and then ->mg_tasks. After ->mg_tasks, we move onto the
3390 if (l == it->tasks_head)
3391 l = it->mg_tasks_head->next;
3393 if (l == it->mg_tasks_head)
3394 css_advance_task_iter(it);
3402 * css_task_iter_end - finish task iteration
3403 * @it: the task iterator to finish
3405 * Finish task iteration started by css_task_iter_start().
3407 void css_task_iter_end(struct css_task_iter *it)
3408 __releases(css_set_rwsem)
3410 up_read(&css_set_rwsem);
3414 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3415 * @to: cgroup to which the tasks will be moved
3416 * @from: cgroup in which the tasks currently reside
3418 * Locking rules between cgroup_post_fork() and the migration path
3419 * guarantee that, if a task is forking while being migrated, the new child
3420 * is guaranteed to be either visible in the source cgroup after the
3421 * parent's migration is complete or put into the target cgroup. No task
3422 * can slip out of migration through forking.
3424 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3426 LIST_HEAD(preloaded_csets);
3427 struct cgrp_cset_link *link;
3428 struct css_task_iter it;
3429 struct task_struct *task;
3432 mutex_lock(&cgroup_mutex);
3434 /* all tasks in @from are being moved, all csets are source */
3435 down_read(&css_set_rwsem);
3436 list_for_each_entry(link, &from->cset_links, cset_link)
3437 cgroup_migrate_add_src(link->cset, to, &preloaded_csets);
3438 up_read(&css_set_rwsem);
3440 ret = cgroup_migrate_prepare_dst(to, &preloaded_csets);
3445 * Migrate tasks one-by-one until @form is empty. This fails iff
3446 * ->can_attach() fails.
3449 css_task_iter_start(&from->dummy_css, &it);
3450 task = css_task_iter_next(&it);
3452 get_task_struct(task);
3453 css_task_iter_end(&it);
3456 ret = cgroup_migrate(to, task, false);
3457 put_task_struct(task);
3459 } while (task && !ret);
3461 cgroup_migrate_finish(&preloaded_csets);
3462 mutex_unlock(&cgroup_mutex);
3467 * Stuff for reading the 'tasks'/'procs' files.
3469 * Reading this file can return large amounts of data if a cgroup has
3470 * *lots* of attached tasks. So it may need several calls to read(),
3471 * but we cannot guarantee that the information we produce is correct
3472 * unless we produce it entirely atomically.
3476 /* which pidlist file are we talking about? */
3477 enum cgroup_filetype {
3483 * A pidlist is a list of pids that virtually represents the contents of one
3484 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3485 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3488 struct cgroup_pidlist {
3490 * used to find which pidlist is wanted. doesn't change as long as
3491 * this particular list stays in the list.
3493 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3496 /* how many elements the above list has */
3498 /* each of these stored in a list by its cgroup */
3499 struct list_head links;
3500 /* pointer to the cgroup we belong to, for list removal purposes */
3501 struct cgroup *owner;
3502 /* for delayed destruction */
3503 struct delayed_work destroy_dwork;
3507 * The following two functions "fix" the issue where there are more pids
3508 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3509 * TODO: replace with a kernel-wide solution to this problem
3511 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3512 static void *pidlist_allocate(int count)
3514 if (PIDLIST_TOO_LARGE(count))
3515 return vmalloc(count * sizeof(pid_t));
3517 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3520 static void pidlist_free(void *p)
3522 if (is_vmalloc_addr(p))
3529 * Used to destroy all pidlists lingering waiting for destroy timer. None
3530 * should be left afterwards.
3532 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
3534 struct cgroup_pidlist *l, *tmp_l;
3536 mutex_lock(&cgrp->pidlist_mutex);
3537 list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
3538 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
3539 mutex_unlock(&cgrp->pidlist_mutex);
3541 flush_workqueue(cgroup_pidlist_destroy_wq);
3542 BUG_ON(!list_empty(&cgrp->pidlists));
3545 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
3547 struct delayed_work *dwork = to_delayed_work(work);
3548 struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
3550 struct cgroup_pidlist *tofree = NULL;
3552 mutex_lock(&l->owner->pidlist_mutex);
3555 * Destroy iff we didn't get queued again. The state won't change
3556 * as destroy_dwork can only be queued while locked.
3558 if (!delayed_work_pending(dwork)) {
3559 list_del(&l->links);
3560 pidlist_free(l->list);
3561 put_pid_ns(l->key.ns);
3565 mutex_unlock(&l->owner->pidlist_mutex);
3570 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3571 * Returns the number of unique elements.
3573 static int pidlist_uniq(pid_t *list, int length)
3578 * we presume the 0th element is unique, so i starts at 1. trivial
3579 * edge cases first; no work needs to be done for either
3581 if (length == 0 || length == 1)
3583 /* src and dest walk down the list; dest counts unique elements */
3584 for (src = 1; src < length; src++) {
3585 /* find next unique element */
3586 while (list[src] == list[src-1]) {
3591 /* dest always points to where the next unique element goes */
3592 list[dest] = list[src];
3600 * The two pid files - task and cgroup.procs - guaranteed that the result
3601 * is sorted, which forced this whole pidlist fiasco. As pid order is
3602 * different per namespace, each namespace needs differently sorted list,
3603 * making it impossible to use, for example, single rbtree of member tasks
3604 * sorted by task pointer. As pidlists can be fairly large, allocating one
3605 * per open file is dangerous, so cgroup had to implement shared pool of
3606 * pidlists keyed by cgroup and namespace.
3608 * All this extra complexity was caused by the original implementation
3609 * committing to an entirely unnecessary property. In the long term, we
3610 * want to do away with it. Explicitly scramble sort order if
3611 * sane_behavior so that no such expectation exists in the new interface.
3613 * Scrambling is done by swapping every two consecutive bits, which is
3614 * non-identity one-to-one mapping which disturbs sort order sufficiently.
3616 static pid_t pid_fry(pid_t pid)
3618 unsigned a = pid & 0x55555555;
3619 unsigned b = pid & 0xAAAAAAAA;
3621 return (a << 1) | (b >> 1);
3624 static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
3626 if (cgroup_sane_behavior(cgrp))
3627 return pid_fry(pid);
3632 static int cmppid(const void *a, const void *b)
3634 return *(pid_t *)a - *(pid_t *)b;
3637 static int fried_cmppid(const void *a, const void *b)
3639 return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
3642 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3643 enum cgroup_filetype type)
3645 struct cgroup_pidlist *l;
3646 /* don't need task_nsproxy() if we're looking at ourself */
3647 struct pid_namespace *ns = task_active_pid_ns(current);
3649 lockdep_assert_held(&cgrp->pidlist_mutex);
3651 list_for_each_entry(l, &cgrp->pidlists, links)
3652 if (l->key.type == type && l->key.ns == ns)
3658 * find the appropriate pidlist for our purpose (given procs vs tasks)
3659 * returns with the lock on that pidlist already held, and takes care
3660 * of the use count, or returns NULL with no locks held if we're out of
3663 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
3664 enum cgroup_filetype type)
3666 struct cgroup_pidlist *l;
3668 lockdep_assert_held(&cgrp->pidlist_mutex);
3670 l = cgroup_pidlist_find(cgrp, type);
3674 /* entry not found; create a new one */
3675 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3679 INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
3681 /* don't need task_nsproxy() if we're looking at ourself */
3682 l->key.ns = get_pid_ns(task_active_pid_ns(current));
3684 list_add(&l->links, &cgrp->pidlists);
3689 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3691 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3692 struct cgroup_pidlist **lp)
3696 int pid, n = 0; /* used for populating the array */
3697 struct css_task_iter it;
3698 struct task_struct *tsk;
3699 struct cgroup_pidlist *l;
3701 lockdep_assert_held(&cgrp->pidlist_mutex);
3704 * If cgroup gets more users after we read count, we won't have
3705 * enough space - tough. This race is indistinguishable to the
3706 * caller from the case that the additional cgroup users didn't
3707 * show up until sometime later on.
3709 length = cgroup_task_count(cgrp);
3710 array = pidlist_allocate(length);
3713 /* now, populate the array */
3714 css_task_iter_start(&cgrp->dummy_css, &it);
3715 while ((tsk = css_task_iter_next(&it))) {
3716 if (unlikely(n == length))
3718 /* get tgid or pid for procs or tasks file respectively */
3719 if (type == CGROUP_FILE_PROCS)
3720 pid = task_tgid_vnr(tsk);
3722 pid = task_pid_vnr(tsk);
3723 if (pid > 0) /* make sure to only use valid results */
3726 css_task_iter_end(&it);
3728 /* now sort & (if procs) strip out duplicates */
3729 if (cgroup_sane_behavior(cgrp))
3730 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
3732 sort(array, length, sizeof(pid_t), cmppid, NULL);
3733 if (type == CGROUP_FILE_PROCS)
3734 length = pidlist_uniq(array, length);
3736 l = cgroup_pidlist_find_create(cgrp, type);
3738 mutex_unlock(&cgrp->pidlist_mutex);
3739 pidlist_free(array);
3743 /* store array, freeing old if necessary */
3744 pidlist_free(l->list);
3752 * cgroupstats_build - build and fill cgroupstats
3753 * @stats: cgroupstats to fill information into
3754 * @dentry: A dentry entry belonging to the cgroup for which stats have
3757 * Build and fill cgroupstats so that taskstats can export it to user
3760 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3762 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
3763 struct cgroup *cgrp;
3764 struct css_task_iter it;
3765 struct task_struct *tsk;
3767 /* it should be kernfs_node belonging to cgroupfs and is a directory */
3768 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
3769 kernfs_type(kn) != KERNFS_DIR)
3772 mutex_lock(&cgroup_mutex);
3775 * We aren't being called from kernfs and there's no guarantee on
3776 * @kn->priv's validity. For this and css_tryget_online_from_dir(),
3777 * @kn->priv is RCU safe. Let's do the RCU dancing.
3780 cgrp = rcu_dereference(kn->priv);
3781 if (!cgrp || cgroup_is_dead(cgrp)) {
3783 mutex_unlock(&cgroup_mutex);
3788 css_task_iter_start(&cgrp->dummy_css, &it);
3789 while ((tsk = css_task_iter_next(&it))) {
3790 switch (tsk->state) {
3792 stats->nr_running++;
3794 case TASK_INTERRUPTIBLE:
3795 stats->nr_sleeping++;
3797 case TASK_UNINTERRUPTIBLE:
3798 stats->nr_uninterruptible++;
3801 stats->nr_stopped++;
3804 if (delayacct_is_task_waiting_on_io(tsk))
3805 stats->nr_io_wait++;
3809 css_task_iter_end(&it);
3811 mutex_unlock(&cgroup_mutex);
3817 * seq_file methods for the tasks/procs files. The seq_file position is the
3818 * next pid to display; the seq_file iterator is a pointer to the pid
3819 * in the cgroup->l->list array.
3822 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3825 * Initially we receive a position value that corresponds to
3826 * one more than the last pid shown (or 0 on the first call or
3827 * after a seek to the start). Use a binary-search to find the
3828 * next pid to display, if any
3830 struct kernfs_open_file *of = s->private;
3831 struct cgroup *cgrp = seq_css(s)->cgroup;
3832 struct cgroup_pidlist *l;
3833 enum cgroup_filetype type = seq_cft(s)->private;
3834 int index = 0, pid = *pos;
3837 mutex_lock(&cgrp->pidlist_mutex);
3840 * !NULL @of->priv indicates that this isn't the first start()
3841 * after open. If the matching pidlist is around, we can use that.
3842 * Look for it. Note that @of->priv can't be used directly. It
3843 * could already have been destroyed.
3846 of->priv = cgroup_pidlist_find(cgrp, type);
3849 * Either this is the first start() after open or the matching
3850 * pidlist has been destroyed inbetween. Create a new one.
3853 ret = pidlist_array_load(cgrp, type,
3854 (struct cgroup_pidlist **)&of->priv);
3856 return ERR_PTR(ret);
3861 int end = l->length;
3863 while (index < end) {
3864 int mid = (index + end) / 2;
3865 if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
3868 } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
3874 /* If we're off the end of the array, we're done */
3875 if (index >= l->length)
3877 /* Update the abstract position to be the actual pid that we found */
3878 iter = l->list + index;
3879 *pos = cgroup_pid_fry(cgrp, *iter);
3883 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3885 struct kernfs_open_file *of = s->private;
3886 struct cgroup_pidlist *l = of->priv;
3889 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
3890 CGROUP_PIDLIST_DESTROY_DELAY);
3891 mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
3894 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3896 struct kernfs_open_file *of = s->private;
3897 struct cgroup_pidlist *l = of->priv;
3899 pid_t *end = l->list + l->length;
3901 * Advance to the next pid in the array. If this goes off the
3908 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
3913 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3915 return seq_printf(s, "%d\n", *(int *)v);
3918 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3921 return notify_on_release(css->cgroup);
3924 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3925 struct cftype *cft, u64 val)
3927 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3929 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3931 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3935 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3938 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3941 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3942 struct cftype *cft, u64 val)
3945 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3947 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3951 static struct cftype cgroup_base_files[] = {
3953 .name = "cgroup.procs",
3954 .seq_start = cgroup_pidlist_start,
3955 .seq_next = cgroup_pidlist_next,
3956 .seq_stop = cgroup_pidlist_stop,
3957 .seq_show = cgroup_pidlist_show,
3958 .private = CGROUP_FILE_PROCS,
3959 .write_u64 = cgroup_procs_write,
3960 .mode = S_IRUGO | S_IWUSR,
3963 .name = "cgroup.clone_children",
3964 .flags = CFTYPE_INSANE,
3965 .read_u64 = cgroup_clone_children_read,
3966 .write_u64 = cgroup_clone_children_write,
3969 .name = "cgroup.sane_behavior",
3970 .flags = CFTYPE_ONLY_ON_ROOT,
3971 .seq_show = cgroup_sane_behavior_show,
3974 .name = "cgroup.controllers",
3975 .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_ONLY_ON_ROOT,
3976 .seq_show = cgroup_root_controllers_show,
3979 .name = "cgroup.controllers",
3980 .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_NOT_ON_ROOT,
3981 .seq_show = cgroup_controllers_show,
3984 .name = "cgroup.subtree_control",
3985 .flags = CFTYPE_ONLY_ON_DFL,
3986 .seq_show = cgroup_subtree_control_show,
3987 .write_string = cgroup_subtree_control_write,
3990 .name = "cgroup.populated",
3991 .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_NOT_ON_ROOT,
3992 .seq_show = cgroup_populated_show,
3996 * Historical crazy stuff. These don't have "cgroup." prefix and
3997 * don't exist if sane_behavior. If you're depending on these, be
3998 * prepared to be burned.
4002 .flags = CFTYPE_INSANE, /* use "procs" instead */
4003 .seq_start = cgroup_pidlist_start,
4004 .seq_next = cgroup_pidlist_next,
4005 .seq_stop = cgroup_pidlist_stop,
4006 .seq_show = cgroup_pidlist_show,
4007 .private = CGROUP_FILE_TASKS,
4008 .write_u64 = cgroup_tasks_write,
4009 .mode = S_IRUGO | S_IWUSR,
4012 .name = "notify_on_release",
4013 .flags = CFTYPE_INSANE,
4014 .read_u64 = cgroup_read_notify_on_release,
4015 .write_u64 = cgroup_write_notify_on_release,
4018 .name = "release_agent",
4019 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
4020 .seq_show = cgroup_release_agent_show,
4021 .write_string = cgroup_release_agent_write,
4022 .max_write_len = PATH_MAX - 1,
4028 * cgroup_populate_dir - create subsys files in a cgroup directory
4029 * @cgrp: target cgroup
4030 * @subsys_mask: mask of the subsystem ids whose files should be added
4032 * On failure, no file is added.
4034 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned int subsys_mask)
4036 struct cgroup_subsys *ss;
4039 /* process cftsets of each subsystem */
4040 for_each_subsys(ss, i) {
4041 struct cftype *cfts;
4043 if (!(subsys_mask & (1 << i)))
4046 list_for_each_entry(cfts, &ss->cfts, node) {
4047 ret = cgroup_addrm_files(cgrp, cfts, true);
4054 cgroup_clear_dir(cgrp, subsys_mask);
4059 * css destruction is four-stage process.
4061 * 1. Destruction starts. Killing of the percpu_ref is initiated.
4062 * Implemented in kill_css().
4064 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4065 * and thus css_tryget_online() is guaranteed to fail, the css can be
4066 * offlined by invoking offline_css(). After offlining, the base ref is
4067 * put. Implemented in css_killed_work_fn().
4069 * 3. When the percpu_ref reaches zero, the only possible remaining
4070 * accessors are inside RCU read sections. css_release() schedules the
4073 * 4. After the grace period, the css can be freed. Implemented in
4074 * css_free_work_fn().
4076 * It is actually hairier because both step 2 and 4 require process context
4077 * and thus involve punting to css->destroy_work adding two additional
4078 * steps to the already complex sequence.
4080 static void css_free_work_fn(struct work_struct *work)
4082 struct cgroup_subsys_state *css =
4083 container_of(work, struct cgroup_subsys_state, destroy_work);
4084 struct cgroup *cgrp = css->cgroup;
4087 css_put(css->parent);
4089 css->ss->css_free(css);
4093 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4095 struct cgroup_subsys_state *css =
4096 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4098 INIT_WORK(&css->destroy_work, css_free_work_fn);
4099 queue_work(cgroup_destroy_wq, &css->destroy_work);
4102 static void css_release(struct percpu_ref *ref)
4104 struct cgroup_subsys_state *css =
4105 container_of(ref, struct cgroup_subsys_state, refcnt);
4106 struct cgroup_subsys *ss = css->ss;
4108 cgroup_idr_remove(&ss->css_idr, css->id);
4110 call_rcu(&css->rcu_head, css_free_rcu_fn);
4113 static void init_and_link_css(struct cgroup_subsys_state *css,
4114 struct cgroup_subsys *ss, struct cgroup *cgrp)
4123 css->parent = cgroup_css(cgrp->parent, ss);
4124 css_get(css->parent);
4126 css->flags |= CSS_ROOT;
4129 BUG_ON(cgroup_css(cgrp, ss));
4132 /* invoke ->css_online() on a new CSS and mark it online if successful */
4133 static int online_css(struct cgroup_subsys_state *css)
4135 struct cgroup_subsys *ss = css->ss;
4138 lockdep_assert_held(&cgroup_tree_mutex);
4139 lockdep_assert_held(&cgroup_mutex);
4142 ret = ss->css_online(css);
4144 css->flags |= CSS_ONLINE;
4145 css->cgroup->nr_css++;
4146 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
4151 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4152 static void offline_css(struct cgroup_subsys_state *css)
4154 struct cgroup_subsys *ss = css->ss;
4156 lockdep_assert_held(&cgroup_tree_mutex);
4157 lockdep_assert_held(&cgroup_mutex);
4159 if (!(css->flags & CSS_ONLINE))
4162 if (ss->css_offline)
4163 ss->css_offline(css);
4165 css->flags &= ~CSS_ONLINE;
4166 css->cgroup->nr_css--;
4167 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
4169 wake_up_all(&css->cgroup->offline_waitq);
4173 * create_css - create a cgroup_subsys_state
4174 * @cgrp: the cgroup new css will be associated with
4175 * @ss: the subsys of new css
4177 * Create a new css associated with @cgrp - @ss pair. On success, the new
4178 * css is online and installed in @cgrp with all interface files created.
4179 * Returns 0 on success, -errno on failure.
4181 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss)
4183 struct cgroup *parent = cgrp->parent;
4184 struct cgroup_subsys_state *css;
4187 lockdep_assert_held(&cgroup_mutex);
4189 css = ss->css_alloc(cgroup_css(parent, ss));
4191 return PTR_ERR(css);
4193 init_and_link_css(css, ss, cgrp);
4195 err = percpu_ref_init(&css->refcnt, css_release);
4199 err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_NOWAIT);
4201 goto err_free_percpu_ref;
4204 err = cgroup_populate_dir(cgrp, 1 << ss->id);
4208 /* @css is ready to be brought online now, make it visible */
4209 cgroup_idr_replace(&ss->css_idr, css, css->id);
4211 err = online_css(css);
4215 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4217 pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4218 current->comm, current->pid, ss->name);
4219 if (!strcmp(ss->name, "memory"))
4220 pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
4221 ss->warned_broken_hierarchy = true;
4227 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4229 cgroup_idr_remove(&ss->css_idr, css->id);
4230 err_free_percpu_ref:
4231 percpu_ref_cancel_init(&css->refcnt);
4233 call_rcu(&css->rcu_head, css_free_rcu_fn);
4238 * cgroup_create - create a cgroup
4239 * @parent: cgroup that will be parent of the new cgroup
4240 * @name: name of the new cgroup
4241 * @mode: mode to set on new cgroup
4243 static long cgroup_create(struct cgroup *parent, const char *name,
4246 struct cgroup *cgrp;
4247 struct cgroup_root *root = parent->root;
4249 struct cgroup_subsys *ss;
4250 struct kernfs_node *kn;
4252 /* allocate the cgroup and its ID, 0 is reserved for the root */
4253 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4257 mutex_lock(&cgroup_tree_mutex);
4260 * Only live parents can have children. Note that the liveliness
4261 * check isn't strictly necessary because cgroup_mkdir() and
4262 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4263 * anyway so that locking is contained inside cgroup proper and we
4264 * don't get nasty surprises if we ever grow another caller.
4266 if (!cgroup_lock_live_group(parent)) {
4268 goto err_unlock_tree;
4272 * Temporarily set the pointer to NULL, so idr_find() won't return
4273 * a half-baked cgroup.
4275 cgrp->id = cgroup_idr_alloc(&root->cgroup_idr, NULL, 2, 0, GFP_NOWAIT);
4281 init_cgroup_housekeeping(cgrp);
4283 cgrp->parent = parent;
4284 cgrp->dummy_css.parent = &parent->dummy_css;
4285 cgrp->root = parent->root;
4287 if (notify_on_release(parent))
4288 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4290 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4291 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4293 /* create the directory */
4294 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
4302 * This extra ref will be put in cgroup_free_fn() and guarantees
4303 * that @cgrp->kn is always accessible.
4307 cgrp->serial_nr = cgroup_serial_nr_next++;
4309 /* allocation complete, commit to creation */
4310 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4311 atomic_inc(&root->nr_cgrps);
4315 * @cgrp is now fully operational. If something fails after this
4316 * point, it'll be released via the normal destruction path.
4318 cgroup_idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4320 err = cgroup_kn_set_ugid(kn);
4324 err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
4328 /* let's create and online css's */
4329 for_each_subsys(ss, ssid) {
4330 if (parent->child_subsys_mask & (1 << ssid)) {
4331 err = create_css(cgrp, ss);
4338 * On the default hierarchy, a child doesn't automatically inherit
4339 * child_subsys_mask from the parent. Each is configured manually.
4341 if (!cgroup_on_dfl(cgrp))
4342 cgrp->child_subsys_mask = parent->child_subsys_mask;
4344 kernfs_activate(kn);
4346 mutex_unlock(&cgroup_mutex);
4347 mutex_unlock(&cgroup_tree_mutex);
4352 cgroup_idr_remove(&root->cgroup_idr, cgrp->id);
4354 mutex_unlock(&cgroup_mutex);
4356 mutex_unlock(&cgroup_tree_mutex);
4361 cgroup_destroy_locked(cgrp);
4362 mutex_unlock(&cgroup_mutex);
4363 mutex_unlock(&cgroup_tree_mutex);
4367 static int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
4370 struct cgroup *parent = parent_kn->priv;
4374 * cgroup_create() grabs cgroup_tree_mutex which nests outside
4375 * kernfs active_ref and cgroup_create() already synchronizes
4376 * properly against removal through cgroup_lock_live_group().
4377 * Break it before calling cgroup_create().
4380 kernfs_break_active_protection(parent_kn);
4382 ret = cgroup_create(parent, name, mode);
4384 kernfs_unbreak_active_protection(parent_kn);
4390 * This is called when the refcnt of a css is confirmed to be killed.
4391 * css_tryget_online() is now guaranteed to fail.
4393 static void css_killed_work_fn(struct work_struct *work)
4395 struct cgroup_subsys_state *css =
4396 container_of(work, struct cgroup_subsys_state, destroy_work);
4397 struct cgroup *cgrp = css->cgroup;
4399 mutex_lock(&cgroup_tree_mutex);
4400 mutex_lock(&cgroup_mutex);
4403 * css_tryget_online() is guaranteed to fail now. Tell subsystems
4404 * to initate destruction.
4409 * If @cgrp is marked dead, it's waiting for refs of all css's to
4410 * be disabled before proceeding to the second phase of cgroup
4411 * destruction. If we are the last one, kick it off.
4413 if (!cgrp->nr_css && cgroup_is_dead(cgrp))
4414 cgroup_destroy_css_killed(cgrp);
4416 mutex_unlock(&cgroup_mutex);
4417 mutex_unlock(&cgroup_tree_mutex);
4420 * Put the css refs from kill_css(). Each css holds an extra
4421 * reference to the cgroup's dentry and cgroup removal proceeds
4422 * regardless of css refs. On the last put of each css, whenever
4423 * that may be, the extra dentry ref is put so that dentry
4424 * destruction happens only after all css's are released.
4429 /* css kill confirmation processing requires process context, bounce */
4430 static void css_killed_ref_fn(struct percpu_ref *ref)
4432 struct cgroup_subsys_state *css =
4433 container_of(ref, struct cgroup_subsys_state, refcnt);
4435 INIT_WORK(&css->destroy_work, css_killed_work_fn);
4436 queue_work(cgroup_destroy_wq, &css->destroy_work);
4440 * kill_css - destroy a css
4441 * @css: css to destroy
4443 * This function initiates destruction of @css by removing cgroup interface
4444 * files and putting its base reference. ->css_offline() will be invoked
4445 * asynchronously once css_tryget_online() is guaranteed to fail and when
4446 * the reference count reaches zero, @css will be released.
4448 static void kill_css(struct cgroup_subsys_state *css)
4450 lockdep_assert_held(&cgroup_tree_mutex);
4453 * This must happen before css is disassociated with its cgroup.
4454 * See seq_css() for details.
4456 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4459 * Killing would put the base ref, but we need to keep it alive
4460 * until after ->css_offline().
4465 * cgroup core guarantees that, by the time ->css_offline() is
4466 * invoked, no new css reference will be given out via
4467 * css_tryget_online(). We can't simply call percpu_ref_kill() and
4468 * proceed to offlining css's because percpu_ref_kill() doesn't
4469 * guarantee that the ref is seen as killed on all CPUs on return.
4471 * Use percpu_ref_kill_and_confirm() to get notifications as each
4472 * css is confirmed to be seen as killed on all CPUs.
4474 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4478 * cgroup_destroy_locked - the first stage of cgroup destruction
4479 * @cgrp: cgroup to be destroyed
4481 * css's make use of percpu refcnts whose killing latency shouldn't be
4482 * exposed to userland and are RCU protected. Also, cgroup core needs to
4483 * guarantee that css_tryget_online() won't succeed by the time
4484 * ->css_offline() is invoked. To satisfy all the requirements,
4485 * destruction is implemented in the following two steps.
4487 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4488 * userland visible parts and start killing the percpu refcnts of
4489 * css's. Set up so that the next stage will be kicked off once all
4490 * the percpu refcnts are confirmed to be killed.
4492 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4493 * rest of destruction. Once all cgroup references are gone, the
4494 * cgroup is RCU-freed.
4496 * This function implements s1. After this step, @cgrp is gone as far as
4497 * the userland is concerned and a new cgroup with the same name may be
4498 * created. As cgroup doesn't care about the names internally, this
4499 * doesn't cause any problem.
4501 static int cgroup_destroy_locked(struct cgroup *cgrp)
4502 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4504 struct cgroup *child;
4505 struct cgroup_subsys_state *css;
4509 lockdep_assert_held(&cgroup_tree_mutex);
4510 lockdep_assert_held(&cgroup_mutex);
4513 * css_set_rwsem synchronizes access to ->cset_links and prevents
4514 * @cgrp from being removed while put_css_set() is in progress.
4516 down_read(&css_set_rwsem);
4517 empty = list_empty(&cgrp->cset_links);
4518 up_read(&css_set_rwsem);
4523 * Make sure there's no live children. We can't test ->children
4524 * emptiness as dead children linger on it while being destroyed;
4525 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
4529 list_for_each_entry_rcu(child, &cgrp->children, sibling) {
4530 empty = cgroup_is_dead(child);
4539 * Mark @cgrp dead. This prevents further task migration and child
4540 * creation by disabling cgroup_lock_live_group(). Note that
4541 * CGRP_DEAD assertion is depended upon by css_next_child() to
4542 * resume iteration after dropping RCU read lock. See
4543 * css_next_child() for details.
4545 set_bit(CGRP_DEAD, &cgrp->flags);
4548 * Initiate massacre of all css's. cgroup_destroy_css_killed()
4549 * will be invoked to perform the rest of destruction once the
4550 * percpu refs of all css's are confirmed to be killed. This
4551 * involves removing the subsystem's files, drop cgroup_mutex.
4553 mutex_unlock(&cgroup_mutex);
4554 for_each_css(css, ssid, cgrp)
4556 mutex_lock(&cgroup_mutex);
4558 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4559 raw_spin_lock(&release_list_lock);
4560 if (!list_empty(&cgrp->release_list))
4561 list_del_init(&cgrp->release_list);
4562 raw_spin_unlock(&release_list_lock);
4565 * If @cgrp has css's attached, the second stage of cgroup
4566 * destruction is kicked off from css_killed_work_fn() after the
4567 * refs of all attached css's are killed. If @cgrp doesn't have
4568 * any css, we kick it off here.
4571 cgroup_destroy_css_killed(cgrp);
4573 /* remove @cgrp directory along with the base files */
4574 mutex_unlock(&cgroup_mutex);
4577 * There are two control paths which try to determine cgroup from
4578 * dentry without going through kernfs - cgroupstats_build() and
4579 * css_tryget_online_from_dir(). Those are supported by RCU
4580 * protecting clearing of cgrp->kn->priv backpointer, which should
4581 * happen after all files under it have been removed.
4583 kernfs_remove(cgrp->kn); /* @cgrp has an extra ref on its kn */
4584 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv, NULL);
4586 mutex_lock(&cgroup_mutex);
4592 * cgroup_destroy_css_killed - the second step of cgroup destruction
4593 * @cgrp: the cgroup whose csses have just finished offlining
4595 * This function is invoked from a work item for a cgroup which is being
4596 * destroyed after all css's are offlined and performs the rest of
4597 * destruction. This is the second step of destruction described in the
4598 * comment above cgroup_destroy_locked().
4600 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
4602 struct cgroup *parent = cgrp->parent;
4604 lockdep_assert_held(&cgroup_tree_mutex);
4605 lockdep_assert_held(&cgroup_mutex);
4607 /* delete this cgroup from parent->children */
4608 list_del_rcu(&cgrp->sibling);
4612 set_bit(CGRP_RELEASABLE, &parent->flags);
4613 check_for_release(parent);
4616 static int cgroup_rmdir(struct kernfs_node *kn)
4618 struct cgroup *cgrp = kn->priv;
4622 * This is self-destruction but @kn can't be removed while this
4623 * callback is in progress. Let's break active protection. Once
4624 * the protection is broken, @cgrp can be destroyed at any point.
4625 * Pin it so that it stays accessible.
4628 kernfs_break_active_protection(kn);
4630 mutex_lock(&cgroup_tree_mutex);
4631 mutex_lock(&cgroup_mutex);
4634 * @cgrp might already have been destroyed while we're trying to
4637 if (!cgroup_is_dead(cgrp))
4638 ret = cgroup_destroy_locked(cgrp);
4640 mutex_unlock(&cgroup_mutex);
4641 mutex_unlock(&cgroup_tree_mutex);
4643 kernfs_unbreak_active_protection(kn);
4648 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
4649 .remount_fs = cgroup_remount,
4650 .show_options = cgroup_show_options,
4651 .mkdir = cgroup_mkdir,
4652 .rmdir = cgroup_rmdir,
4653 .rename = cgroup_rename,
4656 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
4658 struct cgroup_subsys_state *css;
4660 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4662 mutex_lock(&cgroup_tree_mutex);
4663 mutex_lock(&cgroup_mutex);
4665 idr_init(&ss->css_idr);
4666 INIT_LIST_HEAD(&ss->cfts);
4668 /* Create the root cgroup state for this subsystem */
4669 ss->root = &cgrp_dfl_root;
4670 css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
4671 /* We don't handle early failures gracefully */
4672 BUG_ON(IS_ERR(css));
4673 init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
4675 /* idr_alloc() can't be called safely during early init */
4678 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
4679 BUG_ON(css->id < 0);
4682 /* Update the init_css_set to contain a subsys
4683 * pointer to this state - since the subsystem is
4684 * newly registered, all tasks and hence the
4685 * init_css_set is in the subsystem's root cgroup. */
4686 init_css_set.subsys[ss->id] = css;
4688 need_forkexit_callback |= ss->fork || ss->exit;
4690 /* At system boot, before all subsystems have been
4691 * registered, no tasks have been forked, so we don't
4692 * need to invoke fork callbacks here. */
4693 BUG_ON(!list_empty(&init_task.tasks));
4695 BUG_ON(online_css(css));
4697 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
4699 mutex_unlock(&cgroup_mutex);
4700 mutex_unlock(&cgroup_tree_mutex);
4704 * cgroup_init_early - cgroup initialization at system boot
4706 * Initialize cgroups at system boot, and initialize any
4707 * subsystems that request early init.
4709 int __init cgroup_init_early(void)
4711 static struct cgroup_sb_opts __initdata opts =
4712 { .flags = CGRP_ROOT_SANE_BEHAVIOR };
4713 struct cgroup_subsys *ss;
4716 init_cgroup_root(&cgrp_dfl_root, &opts);
4717 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4719 for_each_subsys(ss, i) {
4720 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
4721 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
4722 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
4724 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
4725 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
4728 ss->name = cgroup_subsys_name[i];
4731 cgroup_init_subsys(ss, true);
4737 * cgroup_init - cgroup initialization
4739 * Register cgroup filesystem and /proc file, and initialize
4740 * any subsystems that didn't request early init.
4742 int __init cgroup_init(void)
4744 struct cgroup_subsys *ss;
4748 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
4750 mutex_lock(&cgroup_tree_mutex);
4751 mutex_lock(&cgroup_mutex);
4753 /* Add init_css_set to the hash table */
4754 key = css_set_hash(init_css_set.subsys);
4755 hash_add(css_set_table, &init_css_set.hlist, key);
4757 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
4759 mutex_unlock(&cgroup_mutex);
4760 mutex_unlock(&cgroup_tree_mutex);
4762 for_each_subsys(ss, ssid) {
4763 if (ss->early_init) {
4764 struct cgroup_subsys_state *css =
4765 init_css_set.subsys[ss->id];
4767 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
4769 BUG_ON(css->id < 0);
4771 cgroup_init_subsys(ss, false);
4774 list_add_tail(&init_css_set.e_cset_node[ssid],
4775 &cgrp_dfl_root.cgrp.e_csets[ssid]);
4778 * cftype registration needs kmalloc and can't be done
4779 * during early_init. Register base cftypes separately.
4781 if (ss->base_cftypes)
4782 WARN_ON(cgroup_add_cftypes(ss, ss->base_cftypes));
4785 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4789 err = register_filesystem(&cgroup_fs_type);
4791 kobject_put(cgroup_kobj);
4795 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4799 static int __init cgroup_wq_init(void)
4802 * There isn't much point in executing destruction path in
4803 * parallel. Good chunk is serialized with cgroup_mutex anyway.
4804 * Use 1 for @max_active.
4806 * We would prefer to do this in cgroup_init() above, but that
4807 * is called before init_workqueues(): so leave this until after.
4809 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
4810 BUG_ON(!cgroup_destroy_wq);
4813 * Used to destroy pidlists and separate to serve as flush domain.
4814 * Cap @max_active to 1 too.
4816 cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
4818 BUG_ON(!cgroup_pidlist_destroy_wq);
4822 core_initcall(cgroup_wq_init);
4825 * proc_cgroup_show()
4826 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4827 * - Used for /proc/<pid>/cgroup.
4830 /* TODO: Use a proper seq_file iterator */
4831 int proc_cgroup_show(struct seq_file *m, void *v)
4834 struct task_struct *tsk;
4837 struct cgroup_root *root;
4840 buf = kmalloc(PATH_MAX, GFP_KERNEL);
4846 tsk = get_pid_task(pid, PIDTYPE_PID);
4852 mutex_lock(&cgroup_mutex);
4853 down_read(&css_set_rwsem);
4855 for_each_root(root) {
4856 struct cgroup_subsys *ss;
4857 struct cgroup *cgrp;
4858 int ssid, count = 0;
4860 if (root == &cgrp_dfl_root && !cgrp_dfl_root_visible)
4863 seq_printf(m, "%d:", root->hierarchy_id);
4864 for_each_subsys(ss, ssid)
4865 if (root->subsys_mask & (1 << ssid))
4866 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4867 if (strlen(root->name))
4868 seq_printf(m, "%sname=%s", count ? "," : "",
4871 cgrp = task_cgroup_from_root(tsk, root);
4872 path = cgroup_path(cgrp, buf, PATH_MAX);
4874 retval = -ENAMETOOLONG;
4882 up_read(&css_set_rwsem);
4883 mutex_unlock(&cgroup_mutex);
4884 put_task_struct(tsk);
4891 /* Display information about each subsystem and each hierarchy */
4892 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4894 struct cgroup_subsys *ss;
4897 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4899 * ideally we don't want subsystems moving around while we do this.
4900 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4901 * subsys/hierarchy state.
4903 mutex_lock(&cgroup_mutex);
4905 for_each_subsys(ss, i)
4906 seq_printf(m, "%s\t%d\t%d\t%d\n",
4907 ss->name, ss->root->hierarchy_id,
4908 atomic_read(&ss->root->nr_cgrps), !ss->disabled);
4910 mutex_unlock(&cgroup_mutex);
4914 static int cgroupstats_open(struct inode *inode, struct file *file)
4916 return single_open(file, proc_cgroupstats_show, NULL);
4919 static const struct file_operations proc_cgroupstats_operations = {
4920 .open = cgroupstats_open,
4922 .llseek = seq_lseek,
4923 .release = single_release,
4927 * cgroup_fork - initialize cgroup related fields during copy_process()
4928 * @child: pointer to task_struct of forking parent process.
4930 * A task is associated with the init_css_set until cgroup_post_fork()
4931 * attaches it to the parent's css_set. Empty cg_list indicates that
4932 * @child isn't holding reference to its css_set.
4934 void cgroup_fork(struct task_struct *child)
4936 RCU_INIT_POINTER(child->cgroups, &init_css_set);
4937 INIT_LIST_HEAD(&child->cg_list);
4941 * cgroup_post_fork - called on a new task after adding it to the task list
4942 * @child: the task in question
4944 * Adds the task to the list running through its css_set if necessary and
4945 * call the subsystem fork() callbacks. Has to be after the task is
4946 * visible on the task list in case we race with the first call to
4947 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
4950 void cgroup_post_fork(struct task_struct *child)
4952 struct cgroup_subsys *ss;
4956 * This may race against cgroup_enable_task_cg_links(). As that
4957 * function sets use_task_css_set_links before grabbing
4958 * tasklist_lock and we just went through tasklist_lock to add
4959 * @child, it's guaranteed that either we see the set
4960 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
4961 * @child during its iteration.
4963 * If we won the race, @child is associated with %current's
4964 * css_set. Grabbing css_set_rwsem guarantees both that the
4965 * association is stable, and, on completion of the parent's
4966 * migration, @child is visible in the source of migration or
4967 * already in the destination cgroup. This guarantee is necessary
4968 * when implementing operations which need to migrate all tasks of
4969 * a cgroup to another.
4971 * Note that if we lose to cgroup_enable_task_cg_links(), @child
4972 * will remain in init_css_set. This is safe because all tasks are
4973 * in the init_css_set before cg_links is enabled and there's no
4974 * operation which transfers all tasks out of init_css_set.
4976 if (use_task_css_set_links) {
4977 struct css_set *cset;
4979 down_write(&css_set_rwsem);
4980 cset = task_css_set(current);
4981 if (list_empty(&child->cg_list)) {
4982 rcu_assign_pointer(child->cgroups, cset);
4983 list_add(&child->cg_list, &cset->tasks);
4986 up_write(&css_set_rwsem);
4990 * Call ss->fork(). This must happen after @child is linked on
4991 * css_set; otherwise, @child might change state between ->fork()
4992 * and addition to css_set.
4994 if (need_forkexit_callback) {
4995 for_each_subsys(ss, i)
5002 * cgroup_exit - detach cgroup from exiting task
5003 * @tsk: pointer to task_struct of exiting process
5005 * Description: Detach cgroup from @tsk and release it.
5007 * Note that cgroups marked notify_on_release force every task in
5008 * them to take the global cgroup_mutex mutex when exiting.
5009 * This could impact scaling on very large systems. Be reluctant to
5010 * use notify_on_release cgroups where very high task exit scaling
5011 * is required on large systems.
5013 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
5014 * call cgroup_exit() while the task is still competent to handle
5015 * notify_on_release(), then leave the task attached to the root cgroup in
5016 * each hierarchy for the remainder of its exit. No need to bother with
5017 * init_css_set refcnting. init_css_set never goes away and we can't race
5018 * with migration path - PF_EXITING is visible to migration path.
5020 void cgroup_exit(struct task_struct *tsk)
5022 struct cgroup_subsys *ss;
5023 struct css_set *cset;
5024 bool put_cset = false;
5028 * Unlink from @tsk from its css_set. As migration path can't race
5029 * with us, we can check cg_list without grabbing css_set_rwsem.
5031 if (!list_empty(&tsk->cg_list)) {
5032 down_write(&css_set_rwsem);
5033 list_del_init(&tsk->cg_list);
5034 up_write(&css_set_rwsem);
5038 /* Reassign the task to the init_css_set. */
5039 cset = task_css_set(tsk);
5040 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
5042 if (need_forkexit_callback) {
5043 /* see cgroup_post_fork() for details */
5044 for_each_subsys(ss, i) {
5046 struct cgroup_subsys_state *old_css = cset->subsys[i];
5047 struct cgroup_subsys_state *css = task_css(tsk, i);
5049 ss->exit(css, old_css, tsk);
5055 put_css_set(cset, true);
5058 static void check_for_release(struct cgroup *cgrp)
5060 if (cgroup_is_releasable(cgrp) &&
5061 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
5063 * Control Group is currently removeable. If it's not
5064 * already queued for a userspace notification, queue
5067 int need_schedule_work = 0;
5069 raw_spin_lock(&release_list_lock);
5070 if (!cgroup_is_dead(cgrp) &&
5071 list_empty(&cgrp->release_list)) {
5072 list_add(&cgrp->release_list, &release_list);
5073 need_schedule_work = 1;
5075 raw_spin_unlock(&release_list_lock);
5076 if (need_schedule_work)
5077 schedule_work(&release_agent_work);
5082 * Notify userspace when a cgroup is released, by running the
5083 * configured release agent with the name of the cgroup (path
5084 * relative to the root of cgroup file system) as the argument.
5086 * Most likely, this user command will try to rmdir this cgroup.
5088 * This races with the possibility that some other task will be
5089 * attached to this cgroup before it is removed, or that some other
5090 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5091 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5092 * unused, and this cgroup will be reprieved from its death sentence,
5093 * to continue to serve a useful existence. Next time it's released,
5094 * we will get notified again, if it still has 'notify_on_release' set.
5096 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5097 * means only wait until the task is successfully execve()'d. The
5098 * separate release agent task is forked by call_usermodehelper(),
5099 * then control in this thread returns here, without waiting for the
5100 * release agent task. We don't bother to wait because the caller of
5101 * this routine has no use for the exit status of the release agent
5102 * task, so no sense holding our caller up for that.
5104 static void cgroup_release_agent(struct work_struct *work)
5106 BUG_ON(work != &release_agent_work);
5107 mutex_lock(&cgroup_mutex);
5108 raw_spin_lock(&release_list_lock);
5109 while (!list_empty(&release_list)) {
5110 char *argv[3], *envp[3];
5112 char *pathbuf = NULL, *agentbuf = NULL, *path;
5113 struct cgroup *cgrp = list_entry(release_list.next,
5116 list_del_init(&cgrp->release_list);
5117 raw_spin_unlock(&release_list_lock);
5118 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
5121 path = cgroup_path(cgrp, pathbuf, PATH_MAX);
5124 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5129 argv[i++] = agentbuf;
5134 /* minimal command environment */
5135 envp[i++] = "HOME=/";
5136 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5139 /* Drop the lock while we invoke the usermode helper,
5140 * since the exec could involve hitting disk and hence
5141 * be a slow process */
5142 mutex_unlock(&cgroup_mutex);
5143 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5144 mutex_lock(&cgroup_mutex);
5148 raw_spin_lock(&release_list_lock);
5150 raw_spin_unlock(&release_list_lock);
5151 mutex_unlock(&cgroup_mutex);
5154 static int __init cgroup_disable(char *str)
5156 struct cgroup_subsys *ss;
5160 while ((token = strsep(&str, ",")) != NULL) {
5164 for_each_subsys(ss, i) {
5165 if (!strcmp(token, ss->name)) {
5167 printk(KERN_INFO "Disabling %s control group"
5168 " subsystem\n", ss->name);
5175 __setup("cgroup_disable=", cgroup_disable);
5178 * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
5179 * @dentry: directory dentry of interest
5180 * @ss: subsystem of interest
5182 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
5183 * to get the corresponding css and return it. If such css doesn't exist
5184 * or can't be pinned, an ERR_PTR value is returned.
5186 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
5187 struct cgroup_subsys *ss)
5189 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
5190 struct cgroup_subsys_state *css = NULL;
5191 struct cgroup *cgrp;
5193 /* is @dentry a cgroup dir? */
5194 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
5195 kernfs_type(kn) != KERNFS_DIR)
5196 return ERR_PTR(-EBADF);
5201 * This path doesn't originate from kernfs and @kn could already
5202 * have been or be removed at any point. @kn->priv is RCU
5203 * protected for this access. See destroy_locked() for details.
5205 cgrp = rcu_dereference(kn->priv);
5207 css = cgroup_css(cgrp, ss);
5209 if (!css || !css_tryget_online(css))
5210 css = ERR_PTR(-ENOENT);
5217 * css_from_id - lookup css by id
5218 * @id: the cgroup id
5219 * @ss: cgroup subsys to be looked into
5221 * Returns the css if there's valid one with @id, otherwise returns NULL.
5222 * Should be called under rcu_read_lock().
5224 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5226 WARN_ON_ONCE(!rcu_read_lock_held());
5227 return idr_find(&ss->css_idr, id);
5230 #ifdef CONFIG_CGROUP_DEBUG
5231 static struct cgroup_subsys_state *
5232 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5234 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5237 return ERR_PTR(-ENOMEM);
5242 static void debug_css_free(struct cgroup_subsys_state *css)
5247 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5250 return cgroup_task_count(css->cgroup);
5253 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5256 return (u64)(unsigned long)current->cgroups;
5259 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5265 count = atomic_read(&task_css_set(current)->refcount);
5270 static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
5272 struct cgrp_cset_link *link;
5273 struct css_set *cset;
5276 name_buf = kmalloc(NAME_MAX + 1, GFP_KERNEL);
5280 down_read(&css_set_rwsem);
5282 cset = rcu_dereference(current->cgroups);
5283 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5284 struct cgroup *c = link->cgrp;
5286 cgroup_name(c, name_buf, NAME_MAX + 1);
5287 seq_printf(seq, "Root %d group %s\n",
5288 c->root->hierarchy_id, name_buf);
5291 up_read(&css_set_rwsem);
5296 #define MAX_TASKS_SHOWN_PER_CSS 25
5297 static int cgroup_css_links_read(struct seq_file *seq, void *v)
5299 struct cgroup_subsys_state *css = seq_css(seq);
5300 struct cgrp_cset_link *link;
5302 down_read(&css_set_rwsem);
5303 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5304 struct css_set *cset = link->cset;
5305 struct task_struct *task;
5308 seq_printf(seq, "css_set %p\n", cset);
5310 list_for_each_entry(task, &cset->tasks, cg_list) {
5311 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5313 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5316 list_for_each_entry(task, &cset->mg_tasks, cg_list) {
5317 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5319 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5323 seq_puts(seq, " ...\n");
5325 up_read(&css_set_rwsem);
5329 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5331 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
5334 static struct cftype debug_files[] = {
5336 .name = "taskcount",
5337 .read_u64 = debug_taskcount_read,
5341 .name = "current_css_set",
5342 .read_u64 = current_css_set_read,
5346 .name = "current_css_set_refcount",
5347 .read_u64 = current_css_set_refcount_read,
5351 .name = "current_css_set_cg_links",
5352 .seq_show = current_css_set_cg_links_read,
5356 .name = "cgroup_css_links",
5357 .seq_show = cgroup_css_links_read,
5361 .name = "releasable",
5362 .read_u64 = releasable_read,
5368 struct cgroup_subsys debug_cgrp_subsys = {
5369 .css_alloc = debug_css_alloc,
5370 .css_free = debug_css_free,
5371 .base_cftypes = debug_files,
5373 #endif /* CONFIG_CGROUP_DEBUG */