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 so that IDs can be released without grabbing
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(&cgroup_idr_lock);
207 ret = idr_alloc(idr, ptr, start, end, gfp_mask);
208 spin_unlock(&cgroup_idr_lock);
213 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
217 spin_lock(&cgroup_idr_lock);
218 ret = idr_replace(idr, ptr, id);
219 spin_unlock(&cgroup_idr_lock);
223 static void cgroup_idr_remove(struct idr *idr, int id)
225 spin_lock(&cgroup_idr_lock);
227 spin_unlock(&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 *seq_css(struct seq_file *seq)
288 struct kernfs_open_file *of = seq->private;
289 struct cgroup *cgrp = of->kn->parent->priv;
290 struct cftype *cft = seq_cft(seq);
293 * This is open and unprotected implementation of cgroup_css().
294 * seq_css() is only called from a kernfs file operation which has
295 * an active reference on the file. Because all the subsystem
296 * files are drained before a css is disassociated with a cgroup,
297 * the matching css from the cgroup's subsys table is guaranteed to
298 * be and stay valid until the enclosing operation is complete.
301 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
303 return &cgrp->dummy_css;
305 EXPORT_SYMBOL_GPL(seq_css);
308 * cgroup_is_descendant - test ancestry
309 * @cgrp: the cgroup to be tested
310 * @ancestor: possible ancestor of @cgrp
312 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
313 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
314 * and @ancestor are accessible.
316 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
319 if (cgrp == ancestor)
326 static int cgroup_is_releasable(const struct cgroup *cgrp)
329 (1 << CGRP_RELEASABLE) |
330 (1 << CGRP_NOTIFY_ON_RELEASE);
331 return (cgrp->flags & bits) == bits;
334 static int notify_on_release(const struct cgroup *cgrp)
336 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
340 * for_each_css - iterate all css's of a cgroup
341 * @css: the iteration cursor
342 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
343 * @cgrp: the target cgroup to iterate css's of
345 * Should be called under cgroup_[tree_]mutex.
347 #define for_each_css(css, ssid, cgrp) \
348 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
349 if (!((css) = rcu_dereference_check( \
350 (cgrp)->subsys[(ssid)], \
351 lockdep_is_held(&cgroup_tree_mutex) || \
352 lockdep_is_held(&cgroup_mutex)))) { } \
356 * for_each_e_css - iterate all effective css's of a cgroup
357 * @css: the iteration cursor
358 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
359 * @cgrp: the target cgroup to iterate css's of
361 * Should be called under cgroup_[tree_]mutex.
363 #define for_each_e_css(css, ssid, cgrp) \
364 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
365 if (!((css) = cgroup_e_css(cgrp, cgroup_subsys[(ssid)]))) \
370 * for_each_subsys - iterate all enabled cgroup subsystems
371 * @ss: the iteration cursor
372 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
374 #define for_each_subsys(ss, ssid) \
375 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT && \
376 (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
378 /* iterate across the hierarchies */
379 #define for_each_root(root) \
380 list_for_each_entry((root), &cgroup_roots, root_list)
382 /* iterate over child cgrps, lock should be held throughout iteration */
383 #define cgroup_for_each_live_child(child, cgrp) \
384 list_for_each_entry((child), &(cgrp)->children, sibling) \
385 if (({ lockdep_assert_held(&cgroup_tree_mutex); \
386 cgroup_is_dead(child); })) \
391 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
392 * @cgrp: the cgroup to be checked for liveness
394 * On success, returns true; the mutex should be later unlocked. On
395 * failure returns false with no lock held.
397 static bool cgroup_lock_live_group(struct cgroup *cgrp)
399 mutex_lock(&cgroup_mutex);
400 if (cgroup_is_dead(cgrp)) {
401 mutex_unlock(&cgroup_mutex);
407 /* the list of cgroups eligible for automatic release. Protected by
408 * release_list_lock */
409 static LIST_HEAD(release_list);
410 static DEFINE_RAW_SPINLOCK(release_list_lock);
411 static void cgroup_release_agent(struct work_struct *work);
412 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
413 static void check_for_release(struct cgroup *cgrp);
416 * A cgroup can be associated with multiple css_sets as different tasks may
417 * belong to different cgroups on different hierarchies. In the other
418 * direction, a css_set is naturally associated with multiple cgroups.
419 * This M:N relationship is represented by the following link structure
420 * which exists for each association and allows traversing the associations
423 struct cgrp_cset_link {
424 /* the cgroup and css_set this link associates */
426 struct css_set *cset;
428 /* list of cgrp_cset_links anchored at cgrp->cset_links */
429 struct list_head cset_link;
431 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
432 struct list_head cgrp_link;
436 * The default css_set - used by init and its children prior to any
437 * hierarchies being mounted. It contains a pointer to the root state
438 * for each subsystem. Also used to anchor the list of css_sets. Not
439 * reference-counted, to improve performance when child cgroups
440 * haven't been created.
442 static struct css_set init_css_set = {
443 .refcount = ATOMIC_INIT(1),
444 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
445 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
446 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
447 .mg_preload_node = LIST_HEAD_INIT(init_css_set.mg_preload_node),
448 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
451 static int css_set_count = 1; /* 1 for init_css_set */
454 * cgroup_update_populated - updated populated count of a cgroup
455 * @cgrp: the target cgroup
456 * @populated: inc or dec populated count
458 * @cgrp is either getting the first task (css_set) or losing the last.
459 * Update @cgrp->populated_cnt accordingly. The count is propagated
460 * towards root so that a given cgroup's populated_cnt is zero iff the
461 * cgroup and all its descendants are empty.
463 * @cgrp's interface file "cgroup.populated" is zero if
464 * @cgrp->populated_cnt is zero and 1 otherwise. When @cgrp->populated_cnt
465 * changes from or to zero, userland is notified that the content of the
466 * interface file has changed. This can be used to detect when @cgrp and
467 * its descendants become populated or empty.
469 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
471 lockdep_assert_held(&css_set_rwsem);
477 trigger = !cgrp->populated_cnt++;
479 trigger = !--cgrp->populated_cnt;
484 if (cgrp->populated_kn)
485 kernfs_notify(cgrp->populated_kn);
491 * hash table for cgroup groups. This improves the performance to find
492 * an existing css_set. This hash doesn't (currently) take into
493 * account cgroups in empty hierarchies.
495 #define CSS_SET_HASH_BITS 7
496 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
498 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
500 unsigned long key = 0UL;
501 struct cgroup_subsys *ss;
504 for_each_subsys(ss, i)
505 key += (unsigned long)css[i];
506 key = (key >> 16) ^ key;
511 static void put_css_set_locked(struct css_set *cset, bool taskexit)
513 struct cgrp_cset_link *link, *tmp_link;
514 struct cgroup_subsys *ss;
517 lockdep_assert_held(&css_set_rwsem);
519 if (!atomic_dec_and_test(&cset->refcount))
522 /* This css_set is dead. unlink it and release cgroup refcounts */
523 for_each_subsys(ss, ssid)
524 list_del(&cset->e_cset_node[ssid]);
525 hash_del(&cset->hlist);
528 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
529 struct cgroup *cgrp = link->cgrp;
531 list_del(&link->cset_link);
532 list_del(&link->cgrp_link);
534 /* @cgrp can't go away while we're holding css_set_rwsem */
535 if (list_empty(&cgrp->cset_links)) {
536 cgroup_update_populated(cgrp, false);
537 if (notify_on_release(cgrp)) {
539 set_bit(CGRP_RELEASABLE, &cgrp->flags);
540 check_for_release(cgrp);
547 kfree_rcu(cset, rcu_head);
550 static void put_css_set(struct css_set *cset, bool taskexit)
553 * Ensure that the refcount doesn't hit zero while any readers
554 * can see it. Similar to atomic_dec_and_lock(), but for an
557 if (atomic_add_unless(&cset->refcount, -1, 1))
560 down_write(&css_set_rwsem);
561 put_css_set_locked(cset, taskexit);
562 up_write(&css_set_rwsem);
566 * refcounted get/put for css_set objects
568 static inline void get_css_set(struct css_set *cset)
570 atomic_inc(&cset->refcount);
574 * compare_css_sets - helper function for find_existing_css_set().
575 * @cset: candidate css_set being tested
576 * @old_cset: existing css_set for a task
577 * @new_cgrp: cgroup that's being entered by the task
578 * @template: desired set of css pointers in css_set (pre-calculated)
580 * Returns true if "cset" matches "old_cset" except for the hierarchy
581 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
583 static bool compare_css_sets(struct css_set *cset,
584 struct css_set *old_cset,
585 struct cgroup *new_cgrp,
586 struct cgroup_subsys_state *template[])
588 struct list_head *l1, *l2;
591 * On the default hierarchy, there can be csets which are
592 * associated with the same set of cgroups but different csses.
593 * Let's first ensure that csses match.
595 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
599 * Compare cgroup pointers in order to distinguish between
600 * different cgroups in hierarchies. As different cgroups may
601 * share the same effective css, this comparison is always
604 l1 = &cset->cgrp_links;
605 l2 = &old_cset->cgrp_links;
607 struct cgrp_cset_link *link1, *link2;
608 struct cgroup *cgrp1, *cgrp2;
612 /* See if we reached the end - both lists are equal length. */
613 if (l1 == &cset->cgrp_links) {
614 BUG_ON(l2 != &old_cset->cgrp_links);
617 BUG_ON(l2 == &old_cset->cgrp_links);
619 /* Locate the cgroups associated with these links. */
620 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
621 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
624 /* Hierarchies should be linked in the same order. */
625 BUG_ON(cgrp1->root != cgrp2->root);
628 * If this hierarchy is the hierarchy of the cgroup
629 * that's changing, then we need to check that this
630 * css_set points to the new cgroup; if it's any other
631 * hierarchy, then this css_set should point to the
632 * same cgroup as the old css_set.
634 if (cgrp1->root == new_cgrp->root) {
635 if (cgrp1 != new_cgrp)
646 * find_existing_css_set - init css array and find the matching css_set
647 * @old_cset: the css_set that we're using before the cgroup transition
648 * @cgrp: the cgroup that we're moving into
649 * @template: out param for the new set of csses, should be clear on entry
651 static struct css_set *find_existing_css_set(struct css_set *old_cset,
653 struct cgroup_subsys_state *template[])
655 struct cgroup_root *root = cgrp->root;
656 struct cgroup_subsys *ss;
657 struct css_set *cset;
662 * Build the set of subsystem state objects that we want to see in the
663 * new css_set. while subsystems can change globally, the entries here
664 * won't change, so no need for locking.
666 for_each_subsys(ss, i) {
667 if (root->subsys_mask & (1UL << i)) {
669 * @ss is in this hierarchy, so we want the
670 * effective css from @cgrp.
672 template[i] = cgroup_e_css(cgrp, ss);
675 * @ss is not in this hierarchy, so we don't want
678 template[i] = old_cset->subsys[i];
682 key = css_set_hash(template);
683 hash_for_each_possible(css_set_table, cset, hlist, key) {
684 if (!compare_css_sets(cset, old_cset, cgrp, template))
687 /* This css_set matches what we need */
691 /* No existing cgroup group matched */
695 static void free_cgrp_cset_links(struct list_head *links_to_free)
697 struct cgrp_cset_link *link, *tmp_link;
699 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
700 list_del(&link->cset_link);
706 * allocate_cgrp_cset_links - allocate cgrp_cset_links
707 * @count: the number of links to allocate
708 * @tmp_links: list_head the allocated links are put on
710 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
711 * through ->cset_link. Returns 0 on success or -errno.
713 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
715 struct cgrp_cset_link *link;
718 INIT_LIST_HEAD(tmp_links);
720 for (i = 0; i < count; i++) {
721 link = kzalloc(sizeof(*link), GFP_KERNEL);
723 free_cgrp_cset_links(tmp_links);
726 list_add(&link->cset_link, tmp_links);
732 * link_css_set - a helper function to link a css_set to a cgroup
733 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
734 * @cset: the css_set to be linked
735 * @cgrp: the destination cgroup
737 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
740 struct cgrp_cset_link *link;
742 BUG_ON(list_empty(tmp_links));
744 if (cgroup_on_dfl(cgrp))
745 cset->dfl_cgrp = cgrp;
747 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
751 if (list_empty(&cgrp->cset_links))
752 cgroup_update_populated(cgrp, true);
753 list_move(&link->cset_link, &cgrp->cset_links);
756 * Always add links to the tail of the list so that the list
757 * is sorted by order of hierarchy creation
759 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
763 * find_css_set - return a new css_set with one cgroup updated
764 * @old_cset: the baseline css_set
765 * @cgrp: the cgroup to be updated
767 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
768 * substituted into the appropriate hierarchy.
770 static struct css_set *find_css_set(struct css_set *old_cset,
773 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
774 struct css_set *cset;
775 struct list_head tmp_links;
776 struct cgrp_cset_link *link;
777 struct cgroup_subsys *ss;
781 lockdep_assert_held(&cgroup_mutex);
783 /* First see if we already have a cgroup group that matches
785 down_read(&css_set_rwsem);
786 cset = find_existing_css_set(old_cset, cgrp, template);
789 up_read(&css_set_rwsem);
794 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
798 /* Allocate all the cgrp_cset_link objects that we'll need */
799 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
804 atomic_set(&cset->refcount, 1);
805 INIT_LIST_HEAD(&cset->cgrp_links);
806 INIT_LIST_HEAD(&cset->tasks);
807 INIT_LIST_HEAD(&cset->mg_tasks);
808 INIT_LIST_HEAD(&cset->mg_preload_node);
809 INIT_LIST_HEAD(&cset->mg_node);
810 INIT_HLIST_NODE(&cset->hlist);
812 /* Copy the set of subsystem state objects generated in
813 * find_existing_css_set() */
814 memcpy(cset->subsys, template, sizeof(cset->subsys));
816 down_write(&css_set_rwsem);
817 /* Add reference counts and links from the new css_set. */
818 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
819 struct cgroup *c = link->cgrp;
821 if (c->root == cgrp->root)
823 link_css_set(&tmp_links, cset, c);
826 BUG_ON(!list_empty(&tmp_links));
830 /* Add @cset to the hash table */
831 key = css_set_hash(cset->subsys);
832 hash_add(css_set_table, &cset->hlist, key);
834 for_each_subsys(ss, ssid)
835 list_add_tail(&cset->e_cset_node[ssid],
836 &cset->subsys[ssid]->cgroup->e_csets[ssid]);
838 up_write(&css_set_rwsem);
843 static struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
845 struct cgroup *root_cgrp = kf_root->kn->priv;
847 return root_cgrp->root;
850 static int cgroup_init_root_id(struct cgroup_root *root)
854 lockdep_assert_held(&cgroup_mutex);
856 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
860 root->hierarchy_id = id;
864 static void cgroup_exit_root_id(struct cgroup_root *root)
866 lockdep_assert_held(&cgroup_mutex);
868 if (root->hierarchy_id) {
869 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
870 root->hierarchy_id = 0;
874 static void cgroup_free_root(struct cgroup_root *root)
877 /* hierarhcy ID shoulid already have been released */
878 WARN_ON_ONCE(root->hierarchy_id);
880 idr_destroy(&root->cgroup_idr);
885 static void cgroup_destroy_root(struct cgroup_root *root)
887 struct cgroup *cgrp = &root->cgrp;
888 struct cgrp_cset_link *link, *tmp_link;
890 mutex_lock(&cgroup_tree_mutex);
891 mutex_lock(&cgroup_mutex);
893 BUG_ON(atomic_read(&root->nr_cgrps));
894 BUG_ON(!list_empty(&cgrp->children));
896 /* Rebind all subsystems back to the default hierarchy */
897 rebind_subsystems(&cgrp_dfl_root, root->subsys_mask);
900 * Release all the links from cset_links to this hierarchy's
903 down_write(&css_set_rwsem);
905 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
906 list_del(&link->cset_link);
907 list_del(&link->cgrp_link);
910 up_write(&css_set_rwsem);
912 if (!list_empty(&root->root_list)) {
913 list_del(&root->root_list);
917 cgroup_exit_root_id(root);
919 mutex_unlock(&cgroup_mutex);
920 mutex_unlock(&cgroup_tree_mutex);
922 kernfs_destroy_root(root->kf_root);
923 cgroup_free_root(root);
926 /* look up cgroup associated with given css_set on the specified hierarchy */
927 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
928 struct cgroup_root *root)
930 struct cgroup *res = NULL;
932 lockdep_assert_held(&cgroup_mutex);
933 lockdep_assert_held(&css_set_rwsem);
935 if (cset == &init_css_set) {
938 struct cgrp_cset_link *link;
940 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
941 struct cgroup *c = link->cgrp;
943 if (c->root == root) {
955 * Return the cgroup for "task" from the given hierarchy. Must be
956 * called with cgroup_mutex and css_set_rwsem held.
958 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
959 struct cgroup_root *root)
962 * No need to lock the task - since we hold cgroup_mutex the
963 * task can't change groups, so the only thing that can happen
964 * is that it exits and its css is set back to init_css_set.
966 return cset_cgroup_from_root(task_css_set(task), root);
970 * A task must hold cgroup_mutex to modify cgroups.
972 * Any task can increment and decrement the count field without lock.
973 * So in general, code holding cgroup_mutex can't rely on the count
974 * field not changing. However, if the count goes to zero, then only
975 * cgroup_attach_task() can increment it again. Because a count of zero
976 * means that no tasks are currently attached, therefore there is no
977 * way a task attached to that cgroup can fork (the other way to
978 * increment the count). So code holding cgroup_mutex can safely
979 * assume that if the count is zero, it will stay zero. Similarly, if
980 * a task holds cgroup_mutex on a cgroup with zero count, it
981 * knows that the cgroup won't be removed, as cgroup_rmdir()
984 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
985 * (usually) take cgroup_mutex. These are the two most performance
986 * critical pieces of code here. The exception occurs on cgroup_exit(),
987 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
988 * is taken, and if the cgroup count is zero, a usermode call made
989 * to the release agent with the name of the cgroup (path relative to
990 * the root of cgroup file system) as the argument.
992 * A cgroup can only be deleted if both its 'count' of using tasks
993 * is zero, and its list of 'children' cgroups is empty. Since all
994 * tasks in the system use _some_ cgroup, and since there is always at
995 * least one task in the system (init, pid == 1), therefore, root cgroup
996 * always has either children cgroups and/or using tasks. So we don't
997 * need a special hack to ensure that root cgroup cannot be deleted.
999 * P.S. One more locking exception. RCU is used to guard the
1000 * update of a tasks cgroup pointer by cgroup_attach_task()
1003 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned int subsys_mask);
1004 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
1005 static const struct file_operations proc_cgroupstats_operations;
1007 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
1010 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
1011 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
1012 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
1013 cft->ss->name, cft->name);
1015 strncpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
1020 * cgroup_file_mode - deduce file mode of a control file
1021 * @cft: the control file in question
1023 * returns cft->mode if ->mode is not 0
1024 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
1025 * returns S_IRUGO if it has only a read handler
1026 * returns S_IWUSR if it has only a write hander
1028 static umode_t cgroup_file_mode(const struct cftype *cft)
1035 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1038 if (cft->write_u64 || cft->write_s64 || cft->write_string ||
1045 static void cgroup_free_fn(struct work_struct *work)
1047 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
1049 atomic_dec(&cgrp->root->nr_cgrps);
1050 cgroup_pidlist_destroy_all(cgrp);
1054 * We get a ref to the parent, and put the ref when this
1055 * cgroup is being freed, so it's guaranteed that the
1056 * parent won't be destroyed before its children.
1058 cgroup_put(cgrp->parent);
1059 kernfs_put(cgrp->kn);
1063 * This is root cgroup's refcnt reaching zero, which
1064 * indicates that the root should be released.
1066 cgroup_destroy_root(cgrp->root);
1070 static void cgroup_free_rcu(struct rcu_head *head)
1072 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
1074 INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
1075 queue_work(cgroup_destroy_wq, &cgrp->destroy_work);
1078 static void cgroup_get(struct cgroup *cgrp)
1080 WARN_ON_ONCE(cgroup_is_dead(cgrp));
1081 WARN_ON_ONCE(atomic_read(&cgrp->refcnt) <= 0);
1082 atomic_inc(&cgrp->refcnt);
1085 static void cgroup_put(struct cgroup *cgrp)
1087 if (!atomic_dec_and_test(&cgrp->refcnt))
1089 if (WARN_ON_ONCE(cgrp->parent && !cgroup_is_dead(cgrp)))
1093 * XXX: cgrp->id is only used to look up css's. As cgroup and
1094 * css's lifetimes will be decoupled, it should be made
1095 * per-subsystem and moved to css->id so that lookups are
1096 * successful until the target css is released.
1098 cgroup_idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
1101 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
1104 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1106 char name[CGROUP_FILE_NAME_MAX];
1108 lockdep_assert_held(&cgroup_tree_mutex);
1109 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1113 * cgroup_clear_dir - remove subsys files in a cgroup directory
1114 * @cgrp: target cgroup
1115 * @subsys_mask: mask of the subsystem ids whose files should be removed
1117 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned int subsys_mask)
1119 struct cgroup_subsys *ss;
1122 for_each_subsys(ss, i) {
1123 struct cftype *cfts;
1125 if (!(subsys_mask & (1 << i)))
1127 list_for_each_entry(cfts, &ss->cfts, node)
1128 cgroup_addrm_files(cgrp, cfts, false);
1132 static int rebind_subsystems(struct cgroup_root *dst_root, unsigned int ss_mask)
1134 struct cgroup_subsys *ss;
1137 lockdep_assert_held(&cgroup_tree_mutex);
1138 lockdep_assert_held(&cgroup_mutex);
1140 for_each_subsys(ss, ssid) {
1141 if (!(ss_mask & (1 << ssid)))
1144 /* if @ss has non-root csses attached to it, can't move */
1145 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)))
1148 /* can't move between two non-dummy roots either */
1149 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1153 ret = cgroup_populate_dir(&dst_root->cgrp, ss_mask);
1155 if (dst_root != &cgrp_dfl_root)
1159 * Rebinding back to the default root is not allowed to
1160 * fail. Using both default and non-default roots should
1161 * be rare. Moving subsystems back and forth even more so.
1162 * Just warn about it and continue.
1164 if (cgrp_dfl_root_visible) {
1165 pr_warn("failed to create files (%d) while rebinding 0x%x to default root\n",
1167 pr_warn("you may retry by moving them to a different hierarchy and unbinding\n");
1172 * Nothing can fail from this point on. Remove files for the
1173 * removed subsystems and rebind each subsystem.
1175 mutex_unlock(&cgroup_mutex);
1176 for_each_subsys(ss, ssid)
1177 if (ss_mask & (1 << ssid))
1178 cgroup_clear_dir(&ss->root->cgrp, 1 << ssid);
1179 mutex_lock(&cgroup_mutex);
1181 for_each_subsys(ss, ssid) {
1182 struct cgroup_root *src_root;
1183 struct cgroup_subsys_state *css;
1184 struct css_set *cset;
1186 if (!(ss_mask & (1 << ssid)))
1189 src_root = ss->root;
1190 css = cgroup_css(&src_root->cgrp, ss);
1192 WARN_ON(!css || cgroup_css(&dst_root->cgrp, ss));
1194 RCU_INIT_POINTER(src_root->cgrp.subsys[ssid], NULL);
1195 rcu_assign_pointer(dst_root->cgrp.subsys[ssid], css);
1196 ss->root = dst_root;
1197 css->cgroup = &dst_root->cgrp;
1199 down_write(&css_set_rwsem);
1200 hash_for_each(css_set_table, i, cset, hlist)
1201 list_move_tail(&cset->e_cset_node[ss->id],
1202 &dst_root->cgrp.e_csets[ss->id]);
1203 up_write(&css_set_rwsem);
1205 src_root->subsys_mask &= ~(1 << ssid);
1206 src_root->cgrp.child_subsys_mask &= ~(1 << ssid);
1208 /* default hierarchy doesn't enable controllers by default */
1209 dst_root->subsys_mask |= 1 << ssid;
1210 if (dst_root != &cgrp_dfl_root)
1211 dst_root->cgrp.child_subsys_mask |= 1 << ssid;
1217 kernfs_activate(dst_root->cgrp.kn);
1221 static int cgroup_show_options(struct seq_file *seq,
1222 struct kernfs_root *kf_root)
1224 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1225 struct cgroup_subsys *ss;
1228 for_each_subsys(ss, ssid)
1229 if (root->subsys_mask & (1 << ssid))
1230 seq_printf(seq, ",%s", ss->name);
1231 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1232 seq_puts(seq, ",sane_behavior");
1233 if (root->flags & CGRP_ROOT_NOPREFIX)
1234 seq_puts(seq, ",noprefix");
1235 if (root->flags & CGRP_ROOT_XATTR)
1236 seq_puts(seq, ",xattr");
1238 spin_lock(&release_agent_path_lock);
1239 if (strlen(root->release_agent_path))
1240 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1241 spin_unlock(&release_agent_path_lock);
1243 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags))
1244 seq_puts(seq, ",clone_children");
1245 if (strlen(root->name))
1246 seq_printf(seq, ",name=%s", root->name);
1250 struct cgroup_sb_opts {
1251 unsigned int subsys_mask;
1253 char *release_agent;
1254 bool cpuset_clone_children;
1256 /* User explicitly requested empty subsystem */
1260 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1262 char *token, *o = data;
1263 bool all_ss = false, one_ss = false;
1264 unsigned int mask = -1U;
1265 struct cgroup_subsys *ss;
1268 #ifdef CONFIG_CPUSETS
1269 mask = ~(1U << cpuset_cgrp_id);
1272 memset(opts, 0, sizeof(*opts));
1274 while ((token = strsep(&o, ",")) != NULL) {
1277 if (!strcmp(token, "none")) {
1278 /* Explicitly have no subsystems */
1282 if (!strcmp(token, "all")) {
1283 /* Mutually exclusive option 'all' + subsystem name */
1289 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1290 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1293 if (!strcmp(token, "noprefix")) {
1294 opts->flags |= CGRP_ROOT_NOPREFIX;
1297 if (!strcmp(token, "clone_children")) {
1298 opts->cpuset_clone_children = true;
1301 if (!strcmp(token, "xattr")) {
1302 opts->flags |= CGRP_ROOT_XATTR;
1305 if (!strncmp(token, "release_agent=", 14)) {
1306 /* Specifying two release agents is forbidden */
1307 if (opts->release_agent)
1309 opts->release_agent =
1310 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1311 if (!opts->release_agent)
1315 if (!strncmp(token, "name=", 5)) {
1316 const char *name = token + 5;
1317 /* Can't specify an empty name */
1320 /* Must match [\w.-]+ */
1321 for (i = 0; i < strlen(name); i++) {
1325 if ((c == '.') || (c == '-') || (c == '_'))
1329 /* Specifying two names is forbidden */
1332 opts->name = kstrndup(name,
1333 MAX_CGROUP_ROOT_NAMELEN - 1,
1341 for_each_subsys(ss, i) {
1342 if (strcmp(token, ss->name))
1347 /* Mutually exclusive option 'all' + subsystem name */
1350 opts->subsys_mask |= (1 << i);
1355 if (i == CGROUP_SUBSYS_COUNT)
1359 /* Consistency checks */
1361 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1362 pr_warn("sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1364 if ((opts->flags & (CGRP_ROOT_NOPREFIX | CGRP_ROOT_XATTR)) ||
1365 opts->cpuset_clone_children || opts->release_agent ||
1367 pr_err("sane_behavior: noprefix, xattr, clone_children, release_agent and name are not allowed\n");
1372 * If the 'all' option was specified select all the
1373 * subsystems, otherwise if 'none', 'name=' and a subsystem
1374 * name options were not specified, let's default to 'all'
1376 if (all_ss || (!one_ss && !opts->none && !opts->name))
1377 for_each_subsys(ss, i)
1379 opts->subsys_mask |= (1 << i);
1382 * We either have to specify by name or by subsystems. (So
1383 * all empty hierarchies must have a name).
1385 if (!opts->subsys_mask && !opts->name)
1390 * Option noprefix was introduced just for backward compatibility
1391 * with the old cpuset, so we allow noprefix only if mounting just
1392 * the cpuset subsystem.
1394 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1398 /* Can't specify "none" and some subsystems */
1399 if (opts->subsys_mask && opts->none)
1405 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1408 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1409 struct cgroup_sb_opts opts;
1410 unsigned int added_mask, removed_mask;
1412 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1413 pr_err("sane_behavior: remount is not allowed\n");
1417 mutex_lock(&cgroup_tree_mutex);
1418 mutex_lock(&cgroup_mutex);
1420 /* See what subsystems are wanted */
1421 ret = parse_cgroupfs_options(data, &opts);
1425 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1426 pr_warn("option changes via remount are deprecated (pid=%d comm=%s)\n",
1427 task_tgid_nr(current), current->comm);
1429 added_mask = opts.subsys_mask & ~root->subsys_mask;
1430 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1432 /* Don't allow flags or name to change at remount */
1433 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1434 (opts.name && strcmp(opts.name, root->name))) {
1435 pr_err("option or name mismatch, new: 0x%x \"%s\", old: 0x%x \"%s\"\n",
1436 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1437 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1442 /* remounting is not allowed for populated hierarchies */
1443 if (!list_empty(&root->cgrp.children)) {
1448 ret = rebind_subsystems(root, added_mask);
1452 rebind_subsystems(&cgrp_dfl_root, removed_mask);
1454 if (opts.release_agent) {
1455 spin_lock(&release_agent_path_lock);
1456 strcpy(root->release_agent_path, opts.release_agent);
1457 spin_unlock(&release_agent_path_lock);
1460 kfree(opts.release_agent);
1462 mutex_unlock(&cgroup_mutex);
1463 mutex_unlock(&cgroup_tree_mutex);
1468 * To reduce the fork() overhead for systems that are not actually using
1469 * their cgroups capability, we don't maintain the lists running through
1470 * each css_set to its tasks until we see the list actually used - in other
1471 * words after the first mount.
1473 static bool use_task_css_set_links __read_mostly;
1475 static void cgroup_enable_task_cg_lists(void)
1477 struct task_struct *p, *g;
1479 down_write(&css_set_rwsem);
1481 if (use_task_css_set_links)
1484 use_task_css_set_links = true;
1487 * We need tasklist_lock because RCU is not safe against
1488 * while_each_thread(). Besides, a forking task that has passed
1489 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1490 * is not guaranteed to have its child immediately visible in the
1491 * tasklist if we walk through it with RCU.
1493 read_lock(&tasklist_lock);
1494 do_each_thread(g, p) {
1495 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1496 task_css_set(p) != &init_css_set);
1499 * We should check if the process is exiting, otherwise
1500 * it will race with cgroup_exit() in that the list
1501 * entry won't be deleted though the process has exited.
1502 * Do it while holding siglock so that we don't end up
1503 * racing against cgroup_exit().
1505 spin_lock_irq(&p->sighand->siglock);
1506 if (!(p->flags & PF_EXITING)) {
1507 struct css_set *cset = task_css_set(p);
1509 list_add(&p->cg_list, &cset->tasks);
1512 spin_unlock_irq(&p->sighand->siglock);
1513 } while_each_thread(g, p);
1514 read_unlock(&tasklist_lock);
1516 up_write(&css_set_rwsem);
1519 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1521 struct cgroup_subsys *ss;
1524 atomic_set(&cgrp->refcnt, 1);
1525 INIT_LIST_HEAD(&cgrp->sibling);
1526 INIT_LIST_HEAD(&cgrp->children);
1527 INIT_LIST_HEAD(&cgrp->cset_links);
1528 INIT_LIST_HEAD(&cgrp->release_list);
1529 INIT_LIST_HEAD(&cgrp->pidlists);
1530 mutex_init(&cgrp->pidlist_mutex);
1531 cgrp->dummy_css.cgroup = cgrp;
1533 for_each_subsys(ss, ssid)
1534 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
1536 init_waitqueue_head(&cgrp->offline_waitq);
1539 static void init_cgroup_root(struct cgroup_root *root,
1540 struct cgroup_sb_opts *opts)
1542 struct cgroup *cgrp = &root->cgrp;
1544 INIT_LIST_HEAD(&root->root_list);
1545 atomic_set(&root->nr_cgrps, 1);
1547 init_cgroup_housekeeping(cgrp);
1548 idr_init(&root->cgroup_idr);
1550 root->flags = opts->flags;
1551 if (opts->release_agent)
1552 strcpy(root->release_agent_path, opts->release_agent);
1554 strcpy(root->name, opts->name);
1555 if (opts->cpuset_clone_children)
1556 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1559 static int cgroup_setup_root(struct cgroup_root *root, unsigned int ss_mask)
1561 LIST_HEAD(tmp_links);
1562 struct cgroup *root_cgrp = &root->cgrp;
1563 struct css_set *cset;
1566 lockdep_assert_held(&cgroup_tree_mutex);
1567 lockdep_assert_held(&cgroup_mutex);
1569 ret = cgroup_idr_alloc(&root->cgroup_idr, root_cgrp, 1, 2, GFP_NOWAIT);
1572 root_cgrp->id = ret;
1575 * We're accessing css_set_count without locking css_set_rwsem here,
1576 * but that's OK - it can only be increased by someone holding
1577 * cgroup_lock, and that's us. The worst that can happen is that we
1578 * have some link structures left over
1580 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1584 ret = cgroup_init_root_id(root);
1588 root->kf_root = kernfs_create_root(&cgroup_kf_syscall_ops,
1589 KERNFS_ROOT_CREATE_DEACTIVATED,
1591 if (IS_ERR(root->kf_root)) {
1592 ret = PTR_ERR(root->kf_root);
1595 root_cgrp->kn = root->kf_root->kn;
1597 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1601 ret = rebind_subsystems(root, ss_mask);
1606 * There must be no failure case after here, since rebinding takes
1607 * care of subsystems' refcounts, which are explicitly dropped in
1608 * the failure exit path.
1610 list_add(&root->root_list, &cgroup_roots);
1611 cgroup_root_count++;
1614 * Link the root cgroup in this hierarchy into all the css_set
1617 down_write(&css_set_rwsem);
1618 hash_for_each(css_set_table, i, cset, hlist)
1619 link_css_set(&tmp_links, cset, root_cgrp);
1620 up_write(&css_set_rwsem);
1622 BUG_ON(!list_empty(&root_cgrp->children));
1623 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
1625 kernfs_activate(root_cgrp->kn);
1630 kernfs_destroy_root(root->kf_root);
1631 root->kf_root = NULL;
1633 cgroup_exit_root_id(root);
1635 free_cgrp_cset_links(&tmp_links);
1639 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1640 int flags, const char *unused_dev_name,
1643 struct cgroup_root *root;
1644 struct cgroup_sb_opts opts;
1645 struct dentry *dentry;
1650 * The first time anyone tries to mount a cgroup, enable the list
1651 * linking each css_set to its tasks and fix up all existing tasks.
1653 if (!use_task_css_set_links)
1654 cgroup_enable_task_cg_lists();
1656 mutex_lock(&cgroup_tree_mutex);
1657 mutex_lock(&cgroup_mutex);
1659 /* First find the desired set of subsystems */
1660 ret = parse_cgroupfs_options(data, &opts);
1664 /* look for a matching existing root */
1665 if (!opts.subsys_mask && !opts.none && !opts.name) {
1666 cgrp_dfl_root_visible = true;
1667 root = &cgrp_dfl_root;
1668 cgroup_get(&root->cgrp);
1673 for_each_root(root) {
1674 bool name_match = false;
1676 if (root == &cgrp_dfl_root)
1680 * If we asked for a name then it must match. Also, if
1681 * name matches but sybsys_mask doesn't, we should fail.
1682 * Remember whether name matched.
1685 if (strcmp(opts.name, root->name))
1691 * If we asked for subsystems (or explicitly for no
1692 * subsystems) then they must match.
1694 if ((opts.subsys_mask || opts.none) &&
1695 (opts.subsys_mask != root->subsys_mask)) {
1702 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1703 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1704 pr_err("sane_behavior: new mount options should match the existing superblock\n");
1708 pr_warn("new mount options do not match the existing superblock, will be ignored\n");
1713 * A root's lifetime is governed by its root cgroup. Zero
1714 * ref indicate that the root is being destroyed. Wait for
1715 * destruction to complete so that the subsystems are free.
1716 * We can use wait_queue for the wait but this path is
1717 * super cold. Let's just sleep for a bit and retry.
1719 if (!atomic_inc_not_zero(&root->cgrp.refcnt)) {
1720 mutex_unlock(&cgroup_mutex);
1721 mutex_unlock(&cgroup_tree_mutex);
1723 mutex_lock(&cgroup_tree_mutex);
1724 mutex_lock(&cgroup_mutex);
1733 * No such thing, create a new one. name= matching without subsys
1734 * specification is allowed for already existing hierarchies but we
1735 * can't create new one without subsys specification.
1737 if (!opts.subsys_mask && !opts.none) {
1742 root = kzalloc(sizeof(*root), GFP_KERNEL);
1748 init_cgroup_root(root, &opts);
1750 ret = cgroup_setup_root(root, opts.subsys_mask);
1752 cgroup_free_root(root);
1755 mutex_unlock(&cgroup_mutex);
1756 mutex_unlock(&cgroup_tree_mutex);
1758 kfree(opts.release_agent);
1762 return ERR_PTR(ret);
1764 dentry = kernfs_mount(fs_type, flags, root->kf_root, &new_sb);
1765 if (IS_ERR(dentry) || !new_sb)
1766 cgroup_put(&root->cgrp);
1770 static void cgroup_kill_sb(struct super_block *sb)
1772 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
1773 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1775 cgroup_put(&root->cgrp);
1779 static struct file_system_type cgroup_fs_type = {
1781 .mount = cgroup_mount,
1782 .kill_sb = cgroup_kill_sb,
1785 static struct kobject *cgroup_kobj;
1788 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1789 * @task: target task
1790 * @buf: the buffer to write the path into
1791 * @buflen: the length of the buffer
1793 * Determine @task's cgroup on the first (the one with the lowest non-zero
1794 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1795 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1796 * cgroup controller callbacks.
1798 * Return value is the same as kernfs_path().
1800 char *task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1802 struct cgroup_root *root;
1803 struct cgroup *cgrp;
1804 int hierarchy_id = 1;
1807 mutex_lock(&cgroup_mutex);
1808 down_read(&css_set_rwsem);
1810 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1813 cgrp = task_cgroup_from_root(task, root);
1814 path = cgroup_path(cgrp, buf, buflen);
1816 /* if no hierarchy exists, everyone is in "/" */
1817 if (strlcpy(buf, "/", buflen) < buflen)
1821 up_read(&css_set_rwsem);
1822 mutex_unlock(&cgroup_mutex);
1825 EXPORT_SYMBOL_GPL(task_cgroup_path);
1827 /* used to track tasks and other necessary states during migration */
1828 struct cgroup_taskset {
1829 /* the src and dst cset list running through cset->mg_node */
1830 struct list_head src_csets;
1831 struct list_head dst_csets;
1834 * Fields for cgroup_taskset_*() iteration.
1836 * Before migration is committed, the target migration tasks are on
1837 * ->mg_tasks of the csets on ->src_csets. After, on ->mg_tasks of
1838 * the csets on ->dst_csets. ->csets point to either ->src_csets
1839 * or ->dst_csets depending on whether migration is committed.
1841 * ->cur_csets and ->cur_task point to the current task position
1844 struct list_head *csets;
1845 struct css_set *cur_cset;
1846 struct task_struct *cur_task;
1850 * cgroup_taskset_first - reset taskset and return the first task
1851 * @tset: taskset of interest
1853 * @tset iteration is initialized and the first task is returned.
1855 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1857 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
1858 tset->cur_task = NULL;
1860 return cgroup_taskset_next(tset);
1864 * cgroup_taskset_next - iterate to the next task in taskset
1865 * @tset: taskset of interest
1867 * Return the next task in @tset. Iteration must have been initialized
1868 * with cgroup_taskset_first().
1870 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1872 struct css_set *cset = tset->cur_cset;
1873 struct task_struct *task = tset->cur_task;
1875 while (&cset->mg_node != tset->csets) {
1877 task = list_first_entry(&cset->mg_tasks,
1878 struct task_struct, cg_list);
1880 task = list_next_entry(task, cg_list);
1882 if (&task->cg_list != &cset->mg_tasks) {
1883 tset->cur_cset = cset;
1884 tset->cur_task = task;
1888 cset = list_next_entry(cset, mg_node);
1896 * cgroup_task_migrate - move a task from one cgroup to another.
1897 * @old_cgrp; the cgroup @tsk is being migrated from
1898 * @tsk: the task being migrated
1899 * @new_cset: the new css_set @tsk is being attached to
1901 * Must be called with cgroup_mutex, threadgroup and css_set_rwsem locked.
1903 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1904 struct task_struct *tsk,
1905 struct css_set *new_cset)
1907 struct css_set *old_cset;
1909 lockdep_assert_held(&cgroup_mutex);
1910 lockdep_assert_held(&css_set_rwsem);
1913 * We are synchronized through threadgroup_lock() against PF_EXITING
1914 * setting such that we can't race against cgroup_exit() changing the
1915 * css_set to init_css_set and dropping the old one.
1917 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1918 old_cset = task_css_set(tsk);
1920 get_css_set(new_cset);
1921 rcu_assign_pointer(tsk->cgroups, new_cset);
1924 * Use move_tail so that cgroup_taskset_first() still returns the
1925 * leader after migration. This works because cgroup_migrate()
1926 * ensures that the dst_cset of the leader is the first on the
1927 * tset's dst_csets list.
1929 list_move_tail(&tsk->cg_list, &new_cset->mg_tasks);
1932 * We just gained a reference on old_cset by taking it from the
1933 * task. As trading it for new_cset is protected by cgroup_mutex,
1934 * we're safe to drop it here; it will be freed under RCU.
1936 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1937 put_css_set_locked(old_cset, false);
1941 * cgroup_migrate_finish - cleanup after attach
1942 * @preloaded_csets: list of preloaded css_sets
1944 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
1945 * those functions for details.
1947 static void cgroup_migrate_finish(struct list_head *preloaded_csets)
1949 struct css_set *cset, *tmp_cset;
1951 lockdep_assert_held(&cgroup_mutex);
1953 down_write(&css_set_rwsem);
1954 list_for_each_entry_safe(cset, tmp_cset, preloaded_csets, mg_preload_node) {
1955 cset->mg_src_cgrp = NULL;
1956 cset->mg_dst_cset = NULL;
1957 list_del_init(&cset->mg_preload_node);
1958 put_css_set_locked(cset, false);
1960 up_write(&css_set_rwsem);
1964 * cgroup_migrate_add_src - add a migration source css_set
1965 * @src_cset: the source css_set to add
1966 * @dst_cgrp: the destination cgroup
1967 * @preloaded_csets: list of preloaded css_sets
1969 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
1970 * @src_cset and add it to @preloaded_csets, which should later be cleaned
1971 * up by cgroup_migrate_finish().
1973 * This function may be called without holding threadgroup_lock even if the
1974 * target is a process. Threads may be created and destroyed but as long
1975 * as cgroup_mutex is not dropped, no new css_set can be put into play and
1976 * the preloaded css_sets are guaranteed to cover all migrations.
1978 static void cgroup_migrate_add_src(struct css_set *src_cset,
1979 struct cgroup *dst_cgrp,
1980 struct list_head *preloaded_csets)
1982 struct cgroup *src_cgrp;
1984 lockdep_assert_held(&cgroup_mutex);
1985 lockdep_assert_held(&css_set_rwsem);
1987 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
1989 if (!list_empty(&src_cset->mg_preload_node))
1992 WARN_ON(src_cset->mg_src_cgrp);
1993 WARN_ON(!list_empty(&src_cset->mg_tasks));
1994 WARN_ON(!list_empty(&src_cset->mg_node));
1996 src_cset->mg_src_cgrp = src_cgrp;
1997 get_css_set(src_cset);
1998 list_add(&src_cset->mg_preload_node, preloaded_csets);
2002 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2003 * @dst_cgrp: the destination cgroup (may be %NULL)
2004 * @preloaded_csets: list of preloaded source css_sets
2006 * Tasks are about to be moved to @dst_cgrp and all the source css_sets
2007 * have been preloaded to @preloaded_csets. This function looks up and
2008 * pins all destination css_sets, links each to its source, and append them
2009 * to @preloaded_csets. If @dst_cgrp is %NULL, the destination of each
2010 * source css_set is assumed to be its cgroup on the default hierarchy.
2012 * This function must be called after cgroup_migrate_add_src() has been
2013 * called on each migration source css_set. After migration is performed
2014 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2017 static int cgroup_migrate_prepare_dst(struct cgroup *dst_cgrp,
2018 struct list_head *preloaded_csets)
2021 struct css_set *src_cset, *tmp_cset;
2023 lockdep_assert_held(&cgroup_mutex);
2026 * Except for the root, child_subsys_mask must be zero for a cgroup
2027 * with tasks so that child cgroups don't compete against tasks.
2029 if (dst_cgrp && cgroup_on_dfl(dst_cgrp) && dst_cgrp->parent &&
2030 dst_cgrp->child_subsys_mask)
2033 /* look up the dst cset for each src cset and link it to src */
2034 list_for_each_entry_safe(src_cset, tmp_cset, preloaded_csets, mg_preload_node) {
2035 struct css_set *dst_cset;
2037 dst_cset = find_css_set(src_cset,
2038 dst_cgrp ?: src_cset->dfl_cgrp);
2042 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2045 * If src cset equals dst, it's noop. Drop the src.
2046 * cgroup_migrate() will skip the cset too. Note that we
2047 * can't handle src == dst as some nodes are used by both.
2049 if (src_cset == dst_cset) {
2050 src_cset->mg_src_cgrp = NULL;
2051 list_del_init(&src_cset->mg_preload_node);
2052 put_css_set(src_cset, false);
2053 put_css_set(dst_cset, false);
2057 src_cset->mg_dst_cset = dst_cset;
2059 if (list_empty(&dst_cset->mg_preload_node))
2060 list_add(&dst_cset->mg_preload_node, &csets);
2062 put_css_set(dst_cset, false);
2065 list_splice_tail(&csets, preloaded_csets);
2068 cgroup_migrate_finish(&csets);
2073 * cgroup_migrate - migrate a process or task to a cgroup
2074 * @cgrp: the destination cgroup
2075 * @leader: the leader of the process or the task to migrate
2076 * @threadgroup: whether @leader points to the whole process or a single task
2078 * Migrate a process or task denoted by @leader to @cgrp. If migrating a
2079 * process, the caller must be holding threadgroup_lock of @leader. The
2080 * caller is also responsible for invoking cgroup_migrate_add_src() and
2081 * cgroup_migrate_prepare_dst() on the targets before invoking this
2082 * function and following up with cgroup_migrate_finish().
2084 * As long as a controller's ->can_attach() doesn't fail, this function is
2085 * guaranteed to succeed. This means that, excluding ->can_attach()
2086 * failure, when migrating multiple targets, the success or failure can be
2087 * decided for all targets by invoking group_migrate_prepare_dst() before
2088 * actually starting migrating.
2090 static int cgroup_migrate(struct cgroup *cgrp, struct task_struct *leader,
2093 struct cgroup_taskset tset = {
2094 .src_csets = LIST_HEAD_INIT(tset.src_csets),
2095 .dst_csets = LIST_HEAD_INIT(tset.dst_csets),
2096 .csets = &tset.src_csets,
2098 struct cgroup_subsys_state *css, *failed_css = NULL;
2099 struct css_set *cset, *tmp_cset;
2100 struct task_struct *task, *tmp_task;
2104 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2105 * already PF_EXITING could be freed from underneath us unless we
2106 * take an rcu_read_lock.
2108 down_write(&css_set_rwsem);
2112 /* @task either already exited or can't exit until the end */
2113 if (task->flags & PF_EXITING)
2116 /* leave @task alone if post_fork() hasn't linked it yet */
2117 if (list_empty(&task->cg_list))
2120 cset = task_css_set(task);
2121 if (!cset->mg_src_cgrp)
2125 * cgroup_taskset_first() must always return the leader.
2126 * Take care to avoid disturbing the ordering.
2128 list_move_tail(&task->cg_list, &cset->mg_tasks);
2129 if (list_empty(&cset->mg_node))
2130 list_add_tail(&cset->mg_node, &tset.src_csets);
2131 if (list_empty(&cset->mg_dst_cset->mg_node))
2132 list_move_tail(&cset->mg_dst_cset->mg_node,
2137 } while_each_thread(leader, task);
2139 up_write(&css_set_rwsem);
2141 /* methods shouldn't be called if no task is actually migrating */
2142 if (list_empty(&tset.src_csets))
2145 /* check that we can legitimately attach to the cgroup */
2146 for_each_e_css(css, i, cgrp) {
2147 if (css->ss->can_attach) {
2148 ret = css->ss->can_attach(css, &tset);
2151 goto out_cancel_attach;
2157 * Now that we're guaranteed success, proceed to move all tasks to
2158 * the new cgroup. There are no failure cases after here, so this
2159 * is the commit point.
2161 down_write(&css_set_rwsem);
2162 list_for_each_entry(cset, &tset.src_csets, mg_node) {
2163 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list)
2164 cgroup_task_migrate(cset->mg_src_cgrp, task,
2167 up_write(&css_set_rwsem);
2170 * Migration is committed, all target tasks are now on dst_csets.
2171 * Nothing is sensitive to fork() after this point. Notify
2172 * controllers that migration is complete.
2174 tset.csets = &tset.dst_csets;
2176 for_each_e_css(css, i, cgrp)
2177 if (css->ss->attach)
2178 css->ss->attach(css, &tset);
2181 goto out_release_tset;
2184 for_each_e_css(css, i, cgrp) {
2185 if (css == failed_css)
2187 if (css->ss->cancel_attach)
2188 css->ss->cancel_attach(css, &tset);
2191 down_write(&css_set_rwsem);
2192 list_splice_init(&tset.dst_csets, &tset.src_csets);
2193 list_for_each_entry_safe(cset, tmp_cset, &tset.src_csets, mg_node) {
2194 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2195 list_del_init(&cset->mg_node);
2197 up_write(&css_set_rwsem);
2202 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2203 * @dst_cgrp: the cgroup to attach to
2204 * @leader: the task or the leader of the threadgroup to be attached
2205 * @threadgroup: attach the whole threadgroup?
2207 * Call holding cgroup_mutex and threadgroup_lock of @leader.
2209 static int cgroup_attach_task(struct cgroup *dst_cgrp,
2210 struct task_struct *leader, bool threadgroup)
2212 LIST_HEAD(preloaded_csets);
2213 struct task_struct *task;
2216 /* look up all src csets */
2217 down_read(&css_set_rwsem);
2221 cgroup_migrate_add_src(task_css_set(task), dst_cgrp,
2225 } while_each_thread(leader, task);
2227 up_read(&css_set_rwsem);
2229 /* prepare dst csets and commit */
2230 ret = cgroup_migrate_prepare_dst(dst_cgrp, &preloaded_csets);
2232 ret = cgroup_migrate(dst_cgrp, leader, threadgroup);
2234 cgroup_migrate_finish(&preloaded_csets);
2239 * Find the task_struct of the task to attach by vpid and pass it along to the
2240 * function to attach either it or all tasks in its threadgroup. Will lock
2241 * cgroup_mutex and threadgroup.
2243 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2245 struct task_struct *tsk;
2246 const struct cred *cred = current_cred(), *tcred;
2249 if (!cgroup_lock_live_group(cgrp))
2255 tsk = find_task_by_vpid(pid);
2259 goto out_unlock_cgroup;
2262 * even if we're attaching all tasks in the thread group, we
2263 * only need to check permissions on one of them.
2265 tcred = __task_cred(tsk);
2266 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2267 !uid_eq(cred->euid, tcred->uid) &&
2268 !uid_eq(cred->euid, tcred->suid)) {
2271 goto out_unlock_cgroup;
2277 tsk = tsk->group_leader;
2280 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2281 * trapped in a cpuset, or RT worker may be born in a cgroup
2282 * with no rt_runtime allocated. Just say no.
2284 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2287 goto out_unlock_cgroup;
2290 get_task_struct(tsk);
2293 threadgroup_lock(tsk);
2295 if (!thread_group_leader(tsk)) {
2297 * a race with de_thread from another thread's exec()
2298 * may strip us of our leadership, if this happens,
2299 * there is no choice but to throw this task away and
2300 * try again; this is
2301 * "double-double-toil-and-trouble-check locking".
2303 threadgroup_unlock(tsk);
2304 put_task_struct(tsk);
2305 goto retry_find_task;
2309 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2311 threadgroup_unlock(tsk);
2313 put_task_struct(tsk);
2315 mutex_unlock(&cgroup_mutex);
2320 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2321 * @from: attach to all cgroups of a given task
2322 * @tsk: the task to be attached
2324 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2326 struct cgroup_root *root;
2329 mutex_lock(&cgroup_mutex);
2330 for_each_root(root) {
2331 struct cgroup *from_cgrp;
2333 if (root == &cgrp_dfl_root)
2336 down_read(&css_set_rwsem);
2337 from_cgrp = task_cgroup_from_root(from, root);
2338 up_read(&css_set_rwsem);
2340 retval = cgroup_attach_task(from_cgrp, tsk, false);
2344 mutex_unlock(&cgroup_mutex);
2348 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2350 static int cgroup_tasks_write(struct cgroup_subsys_state *css,
2351 struct cftype *cft, u64 pid)
2353 return attach_task_by_pid(css->cgroup, pid, false);
2356 static int cgroup_procs_write(struct cgroup_subsys_state *css,
2357 struct cftype *cft, u64 tgid)
2359 return attach_task_by_pid(css->cgroup, tgid, true);
2362 static int cgroup_release_agent_write(struct cgroup_subsys_state *css,
2363 struct cftype *cft, char *buffer)
2365 struct cgroup_root *root = css->cgroup->root;
2367 BUILD_BUG_ON(sizeof(root->release_agent_path) < PATH_MAX);
2368 if (!cgroup_lock_live_group(css->cgroup))
2370 spin_lock(&release_agent_path_lock);
2371 strlcpy(root->release_agent_path, buffer,
2372 sizeof(root->release_agent_path));
2373 spin_unlock(&release_agent_path_lock);
2374 mutex_unlock(&cgroup_mutex);
2378 static int cgroup_release_agent_show(struct seq_file *seq, void *v)
2380 struct cgroup *cgrp = seq_css(seq)->cgroup;
2382 if (!cgroup_lock_live_group(cgrp))
2384 seq_puts(seq, cgrp->root->release_agent_path);
2385 seq_putc(seq, '\n');
2386 mutex_unlock(&cgroup_mutex);
2390 static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
2392 struct cgroup *cgrp = seq_css(seq)->cgroup;
2394 seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
2398 static void cgroup_print_ss_mask(struct seq_file *seq, unsigned int ss_mask)
2400 struct cgroup_subsys *ss;
2401 bool printed = false;
2404 for_each_subsys(ss, ssid) {
2405 if (ss_mask & (1 << ssid)) {
2408 seq_printf(seq, "%s", ss->name);
2413 seq_putc(seq, '\n');
2416 /* show controllers which are currently attached to the default hierarchy */
2417 static int cgroup_root_controllers_show(struct seq_file *seq, void *v)
2419 struct cgroup *cgrp = seq_css(seq)->cgroup;
2421 cgroup_print_ss_mask(seq, cgrp->root->subsys_mask);
2425 /* show controllers which are enabled from the parent */
2426 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2428 struct cgroup *cgrp = seq_css(seq)->cgroup;
2430 cgroup_print_ss_mask(seq, cgrp->parent->child_subsys_mask);
2434 /* show controllers which are enabled for a given cgroup's children */
2435 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2437 struct cgroup *cgrp = seq_css(seq)->cgroup;
2439 cgroup_print_ss_mask(seq, cgrp->child_subsys_mask);
2444 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2445 * @cgrp: root of the subtree to update csses for
2447 * @cgrp's child_subsys_mask has changed and its subtree's (self excluded)
2448 * css associations need to be updated accordingly. This function looks up
2449 * all css_sets which are attached to the subtree, creates the matching
2450 * updated css_sets and migrates the tasks to the new ones.
2452 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2454 LIST_HEAD(preloaded_csets);
2455 struct cgroup_subsys_state *css;
2456 struct css_set *src_cset;
2459 lockdep_assert_held(&cgroup_tree_mutex);
2460 lockdep_assert_held(&cgroup_mutex);
2462 /* look up all csses currently attached to @cgrp's subtree */
2463 down_read(&css_set_rwsem);
2464 css_for_each_descendant_pre(css, cgroup_css(cgrp, NULL)) {
2465 struct cgrp_cset_link *link;
2467 /* self is not affected by child_subsys_mask change */
2468 if (css->cgroup == cgrp)
2471 list_for_each_entry(link, &css->cgroup->cset_links, cset_link)
2472 cgroup_migrate_add_src(link->cset, cgrp,
2475 up_read(&css_set_rwsem);
2477 /* NULL dst indicates self on default hierarchy */
2478 ret = cgroup_migrate_prepare_dst(NULL, &preloaded_csets);
2482 list_for_each_entry(src_cset, &preloaded_csets, mg_preload_node) {
2483 struct task_struct *last_task = NULL, *task;
2485 /* src_csets precede dst_csets, break on the first dst_cset */
2486 if (!src_cset->mg_src_cgrp)
2490 * All tasks in src_cset need to be migrated to the
2491 * matching dst_cset. Empty it process by process. We
2492 * walk tasks but migrate processes. The leader might even
2493 * belong to a different cset but such src_cset would also
2494 * be among the target src_csets because the default
2495 * hierarchy enforces per-process membership.
2498 down_read(&css_set_rwsem);
2499 task = list_first_entry_or_null(&src_cset->tasks,
2500 struct task_struct, cg_list);
2502 task = task->group_leader;
2503 WARN_ON_ONCE(!task_css_set(task)->mg_src_cgrp);
2504 get_task_struct(task);
2506 up_read(&css_set_rwsem);
2511 /* guard against possible infinite loop */
2512 if (WARN(last_task == task,
2513 "cgroup: update_dfl_csses failed to make progress, aborting in inconsistent state\n"))
2517 threadgroup_lock(task);
2518 /* raced against de_thread() from another thread? */
2519 if (!thread_group_leader(task)) {
2520 threadgroup_unlock(task);
2521 put_task_struct(task);
2525 ret = cgroup_migrate(src_cset->dfl_cgrp, task, true);
2527 threadgroup_unlock(task);
2528 put_task_struct(task);
2530 if (WARN(ret, "cgroup: failed to update controllers for the default hierarchy (%d), further operations may crash or hang\n", ret))
2536 cgroup_migrate_finish(&preloaded_csets);
2540 /* change the enabled child controllers for a cgroup in the default hierarchy */
2541 static int cgroup_subtree_control_write(struct cgroup_subsys_state *dummy_css,
2542 struct cftype *cft, char *buffer)
2544 unsigned int enable_req = 0, disable_req = 0, enable, disable;
2545 struct cgroup *cgrp = dummy_css->cgroup, *child;
2546 struct cgroup_subsys *ss;
2551 * Parse input - white space separated list of subsystem names
2552 * prefixed with either + or -.
2555 while ((tok = strsep(&p, " \t\n"))) {
2556 for_each_subsys(ss, ssid) {
2557 if (ss->disabled || strcmp(tok + 1, ss->name))
2561 enable_req |= 1 << ssid;
2562 disable_req &= ~(1 << ssid);
2563 } else if (*tok == '-') {
2564 disable_req |= 1 << ssid;
2565 enable_req &= ~(1 << ssid);
2571 if (ssid == CGROUP_SUBSYS_COUNT)
2576 * We're gonna grab cgroup_tree_mutex which nests outside kernfs
2577 * active_ref. cgroup_lock_live_group() already provides enough
2578 * protection. Ensure @cgrp stays accessible and break the
2579 * active_ref protection.
2582 kernfs_break_active_protection(cgrp->control_kn);
2584 enable = enable_req;
2585 disable = disable_req;
2587 mutex_lock(&cgroup_tree_mutex);
2589 for_each_subsys(ss, ssid) {
2590 if (enable & (1 << ssid)) {
2591 if (cgrp->child_subsys_mask & (1 << ssid)) {
2592 enable &= ~(1 << ssid);
2597 * Because css offlining is asynchronous, userland
2598 * might try to re-enable the same controller while
2599 * the previous instance is still around. In such
2600 * cases, wait till it's gone using offline_waitq.
2602 cgroup_for_each_live_child(child, cgrp) {
2605 if (!cgroup_css(child, ss))
2608 prepare_to_wait(&child->offline_waitq, &wait,
2609 TASK_UNINTERRUPTIBLE);
2610 mutex_unlock(&cgroup_tree_mutex);
2612 finish_wait(&child->offline_waitq, &wait);
2616 /* unavailable or not enabled on the parent? */
2617 if (!(cgrp_dfl_root.subsys_mask & (1 << ssid)) ||
2619 !(cgrp->parent->child_subsys_mask & (1 << ssid)))) {
2621 goto out_unlock_tree;
2623 } else if (disable & (1 << ssid)) {
2624 if (!(cgrp->child_subsys_mask & (1 << ssid))) {
2625 disable &= ~(1 << ssid);
2629 /* a child has it enabled? */
2630 cgroup_for_each_live_child(child, cgrp) {
2631 if (child->child_subsys_mask & (1 << ssid)) {
2633 goto out_unlock_tree;
2639 if (!enable && !disable) {
2641 goto out_unlock_tree;
2644 if (!cgroup_lock_live_group(cgrp)) {
2646 goto out_unlock_tree;
2650 * Except for the root, child_subsys_mask must be zero for a cgroup
2651 * with tasks so that child cgroups don't compete against tasks.
2653 if (enable && cgrp->parent && !list_empty(&cgrp->cset_links)) {
2659 * Create csses for enables and update child_subsys_mask. This
2660 * changes cgroup_e_css() results which in turn makes the
2661 * subsequent cgroup_update_dfl_csses() associate all tasks in the
2662 * subtree to the updated csses.
2664 for_each_subsys(ss, ssid) {
2665 if (!(enable & (1 << ssid)))
2668 cgroup_for_each_live_child(child, cgrp) {
2669 ret = create_css(child, ss);
2675 cgrp->child_subsys_mask |= enable;
2676 cgrp->child_subsys_mask &= ~disable;
2678 ret = cgroup_update_dfl_csses(cgrp);
2682 /* all tasks are now migrated away from the old csses, kill them */
2683 for_each_subsys(ss, ssid) {
2684 if (!(disable & (1 << ssid)))
2687 cgroup_for_each_live_child(child, cgrp)
2688 kill_css(cgroup_css(child, ss));
2691 kernfs_activate(cgrp->kn);
2694 mutex_unlock(&cgroup_mutex);
2696 mutex_unlock(&cgroup_tree_mutex);
2697 kernfs_unbreak_active_protection(cgrp->control_kn);
2702 cgrp->child_subsys_mask &= ~enable;
2703 cgrp->child_subsys_mask |= disable;
2705 for_each_subsys(ss, ssid) {
2706 if (!(enable & (1 << ssid)))
2709 cgroup_for_each_live_child(child, cgrp) {
2710 struct cgroup_subsys_state *css = cgroup_css(child, ss);
2718 static int cgroup_populated_show(struct seq_file *seq, void *v)
2720 seq_printf(seq, "%d\n", (bool)seq_css(seq)->cgroup->populated_cnt);
2724 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
2725 size_t nbytes, loff_t off)
2727 struct cgroup *cgrp = of->kn->parent->priv;
2728 struct cftype *cft = of->kn->priv;
2729 struct cgroup_subsys_state *css;
2733 * kernfs guarantees that a file isn't deleted with operations in
2734 * flight, which means that the matching css is and stays alive and
2735 * doesn't need to be pinned. The RCU locking is not necessary
2736 * either. It's just for the convenience of using cgroup_css().
2739 css = cgroup_css(cgrp, cft->ss);
2742 if (cft->write_string) {
2743 ret = cft->write_string(css, cft, strstrip(buf));
2744 } else if (cft->write_u64) {
2745 unsigned long long v;
2746 ret = kstrtoull(buf, 0, &v);
2748 ret = cft->write_u64(css, cft, v);
2749 } else if (cft->write_s64) {
2751 ret = kstrtoll(buf, 0, &v);
2753 ret = cft->write_s64(css, cft, v);
2754 } else if (cft->trigger) {
2755 ret = cft->trigger(css, (unsigned int)cft->private);
2760 return ret ?: nbytes;
2763 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
2765 return seq_cft(seq)->seq_start(seq, ppos);
2768 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
2770 return seq_cft(seq)->seq_next(seq, v, ppos);
2773 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
2775 seq_cft(seq)->seq_stop(seq, v);
2778 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2780 struct cftype *cft = seq_cft(m);
2781 struct cgroup_subsys_state *css = seq_css(m);
2784 return cft->seq_show(m, arg);
2787 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
2788 else if (cft->read_s64)
2789 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
2795 static struct kernfs_ops cgroup_kf_single_ops = {
2796 .atomic_write_len = PAGE_SIZE,
2797 .write = cgroup_file_write,
2798 .seq_show = cgroup_seqfile_show,
2801 static struct kernfs_ops cgroup_kf_ops = {
2802 .atomic_write_len = PAGE_SIZE,
2803 .write = cgroup_file_write,
2804 .seq_start = cgroup_seqfile_start,
2805 .seq_next = cgroup_seqfile_next,
2806 .seq_stop = cgroup_seqfile_stop,
2807 .seq_show = cgroup_seqfile_show,
2811 * cgroup_rename - Only allow simple rename of directories in place.
2813 static int cgroup_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
2814 const char *new_name_str)
2816 struct cgroup *cgrp = kn->priv;
2819 if (kernfs_type(kn) != KERNFS_DIR)
2821 if (kn->parent != new_parent)
2825 * This isn't a proper migration and its usefulness is very
2826 * limited. Disallow if sane_behavior.
2828 if (cgroup_sane_behavior(cgrp))
2832 * We're gonna grab cgroup_tree_mutex which nests outside kernfs
2833 * active_ref. kernfs_rename() doesn't require active_ref
2834 * protection. Break them before grabbing cgroup_tree_mutex.
2836 kernfs_break_active_protection(new_parent);
2837 kernfs_break_active_protection(kn);
2839 mutex_lock(&cgroup_tree_mutex);
2840 mutex_lock(&cgroup_mutex);
2842 ret = kernfs_rename(kn, new_parent, new_name_str);
2844 mutex_unlock(&cgroup_mutex);
2845 mutex_unlock(&cgroup_tree_mutex);
2847 kernfs_unbreak_active_protection(kn);
2848 kernfs_unbreak_active_protection(new_parent);
2852 /* set uid and gid of cgroup dirs and files to that of the creator */
2853 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
2855 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
2856 .ia_uid = current_fsuid(),
2857 .ia_gid = current_fsgid(), };
2859 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
2860 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
2863 return kernfs_setattr(kn, &iattr);
2866 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2868 char name[CGROUP_FILE_NAME_MAX];
2869 struct kernfs_node *kn;
2870 struct lock_class_key *key = NULL;
2873 #ifdef CONFIG_DEBUG_LOCK_ALLOC
2874 key = &cft->lockdep_key;
2876 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
2877 cgroup_file_mode(cft), 0, cft->kf_ops, cft,
2882 ret = cgroup_kn_set_ugid(kn);
2888 if (cft->seq_show == cgroup_subtree_control_show)
2889 cgrp->control_kn = kn;
2890 else if (cft->seq_show == cgroup_populated_show)
2891 cgrp->populated_kn = kn;
2896 * cgroup_addrm_files - add or remove files to a cgroup directory
2897 * @cgrp: the target cgroup
2898 * @cfts: array of cftypes to be added
2899 * @is_add: whether to add or remove
2901 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2902 * For removals, this function never fails. If addition fails, this
2903 * function doesn't remove files already added. The caller is responsible
2906 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2912 lockdep_assert_held(&cgroup_tree_mutex);
2914 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2915 /* does cft->flags tell us to skip this file on @cgrp? */
2916 if ((cft->flags & CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
2918 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2920 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2922 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2926 ret = cgroup_add_file(cgrp, cft);
2928 pr_warn("%s: failed to add %s, err=%d\n",
2929 __func__, cft->name, ret);
2933 cgroup_rm_file(cgrp, cft);
2939 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
2942 struct cgroup_subsys *ss = cfts[0].ss;
2943 struct cgroup *root = &ss->root->cgrp;
2944 struct cgroup_subsys_state *css;
2947 lockdep_assert_held(&cgroup_tree_mutex);
2949 /* add/rm files for all cgroups created before */
2950 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2951 struct cgroup *cgrp = css->cgroup;
2953 if (cgroup_is_dead(cgrp))
2956 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2962 kernfs_activate(root->kn);
2966 static void cgroup_exit_cftypes(struct cftype *cfts)
2970 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2971 /* free copy for custom atomic_write_len, see init_cftypes() */
2972 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
2979 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2983 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2984 struct kernfs_ops *kf_ops;
2986 WARN_ON(cft->ss || cft->kf_ops);
2989 kf_ops = &cgroup_kf_ops;
2991 kf_ops = &cgroup_kf_single_ops;
2994 * Ugh... if @cft wants a custom max_write_len, we need to
2995 * make a copy of kf_ops to set its atomic_write_len.
2997 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
2998 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
3000 cgroup_exit_cftypes(cfts);
3003 kf_ops->atomic_write_len = cft->max_write_len;
3006 cft->kf_ops = kf_ops;
3013 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
3015 lockdep_assert_held(&cgroup_tree_mutex);
3017 if (!cfts || !cfts[0].ss)
3020 list_del(&cfts->node);
3021 cgroup_apply_cftypes(cfts, false);
3022 cgroup_exit_cftypes(cfts);
3027 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
3028 * @cfts: zero-length name terminated array of cftypes
3030 * Unregister @cfts. Files described by @cfts are removed from all
3031 * existing cgroups and all future cgroups won't have them either. This
3032 * function can be called anytime whether @cfts' subsys is attached or not.
3034 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
3037 int cgroup_rm_cftypes(struct cftype *cfts)
3041 mutex_lock(&cgroup_tree_mutex);
3042 ret = cgroup_rm_cftypes_locked(cfts);
3043 mutex_unlock(&cgroup_tree_mutex);
3048 * cgroup_add_cftypes - add an array of cftypes to a subsystem
3049 * @ss: target cgroup subsystem
3050 * @cfts: zero-length name terminated array of cftypes
3052 * Register @cfts to @ss. Files described by @cfts are created for all
3053 * existing cgroups to which @ss is attached and all future cgroups will
3054 * have them too. This function can be called anytime whether @ss is
3057 * Returns 0 on successful registration, -errno on failure. Note that this
3058 * function currently returns 0 as long as @cfts registration is successful
3059 * even if some file creation attempts on existing cgroups fail.
3061 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3065 if (!cfts || cfts[0].name[0] == '\0')
3068 ret = cgroup_init_cftypes(ss, cfts);
3072 mutex_lock(&cgroup_tree_mutex);
3074 list_add_tail(&cfts->node, &ss->cfts);
3075 ret = cgroup_apply_cftypes(cfts, true);
3077 cgroup_rm_cftypes_locked(cfts);
3079 mutex_unlock(&cgroup_tree_mutex);
3084 * cgroup_task_count - count the number of tasks in a cgroup.
3085 * @cgrp: the cgroup in question
3087 * Return the number of tasks in the cgroup.
3089 static int cgroup_task_count(const struct cgroup *cgrp)
3092 struct cgrp_cset_link *link;
3094 down_read(&css_set_rwsem);
3095 list_for_each_entry(link, &cgrp->cset_links, cset_link)
3096 count += atomic_read(&link->cset->refcount);
3097 up_read(&css_set_rwsem);
3102 * css_next_child - find the next child of a given css
3103 * @pos_css: the current position (%NULL to initiate traversal)
3104 * @parent_css: css whose children to walk
3106 * This function returns the next child of @parent_css and should be called
3107 * under either cgroup_mutex or RCU read lock. The only requirement is
3108 * that @parent_css and @pos_css are accessible. The next sibling is
3109 * guaranteed to be returned regardless of their states.
3111 struct cgroup_subsys_state *
3112 css_next_child(struct cgroup_subsys_state *pos_css,
3113 struct cgroup_subsys_state *parent_css)
3115 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
3116 struct cgroup *cgrp = parent_css->cgroup;
3117 struct cgroup *next;
3119 cgroup_assert_mutexes_or_rcu_locked();
3122 * @pos could already have been removed. Once a cgroup is removed,
3123 * its ->sibling.next is no longer updated when its next sibling
3124 * changes. As CGRP_DEAD assertion is serialized and happens
3125 * before the cgroup is taken off the ->sibling list, if we see it
3126 * unasserted, it's guaranteed that the next sibling hasn't
3127 * finished its grace period even if it's already removed, and thus
3128 * safe to dereference from this RCU critical section. If
3129 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
3130 * to be visible as %true here.
3132 * If @pos is dead, its next pointer can't be dereferenced;
3133 * however, as each cgroup is given a monotonically increasing
3134 * unique serial number and always appended to the sibling list,
3135 * the next one can be found by walking the parent's children until
3136 * we see a cgroup with higher serial number than @pos's. While
3137 * this path can be slower, it's taken only when either the current
3138 * cgroup is removed or iteration and removal race.
3141 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
3142 } else if (likely(!cgroup_is_dead(pos))) {
3143 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3145 list_for_each_entry_rcu(next, &cgrp->children, sibling)
3146 if (next->serial_nr > pos->serial_nr)
3151 * @next, if not pointing to the head, can be dereferenced and is
3152 * the next sibling; however, it might have @ss disabled. If so,
3153 * fast-forward to the next enabled one.
3155 while (&next->sibling != &cgrp->children) {
3156 struct cgroup_subsys_state *next_css = cgroup_css(next, parent_css->ss);
3160 next = list_entry_rcu(next->sibling.next, struct cgroup, sibling);
3166 * css_next_descendant_pre - find the next descendant for pre-order walk
3167 * @pos: the current position (%NULL to initiate traversal)
3168 * @root: css whose descendants to walk
3170 * To be used by css_for_each_descendant_pre(). Find the next descendant
3171 * to visit for pre-order traversal of @root's descendants. @root is
3172 * included in the iteration and the first node to be visited.
3174 * While this function requires cgroup_mutex or RCU read locking, it
3175 * doesn't require the whole traversal to be contained in a single critical
3176 * section. This function will return the correct next descendant as long
3177 * as both @pos and @root are accessible and @pos is a descendant of @root.
3179 struct cgroup_subsys_state *
3180 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3181 struct cgroup_subsys_state *root)
3183 struct cgroup_subsys_state *next;
3185 cgroup_assert_mutexes_or_rcu_locked();
3187 /* if first iteration, visit @root */
3191 /* visit the first child if exists */
3192 next = css_next_child(NULL, pos);
3196 /* no child, visit my or the closest ancestor's next sibling */
3197 while (pos != root) {
3198 next = css_next_child(pos, css_parent(pos));
3201 pos = css_parent(pos);
3208 * css_rightmost_descendant - return the rightmost descendant of a css
3209 * @pos: css of interest
3211 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3212 * is returned. This can be used during pre-order traversal to skip
3215 * While this function requires cgroup_mutex or RCU read locking, it
3216 * doesn't require the whole traversal to be contained in a single critical
3217 * section. This function will return the correct rightmost descendant as
3218 * long as @pos is accessible.
3220 struct cgroup_subsys_state *
3221 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3223 struct cgroup_subsys_state *last, *tmp;
3225 cgroup_assert_mutexes_or_rcu_locked();
3229 /* ->prev isn't RCU safe, walk ->next till the end */
3231 css_for_each_child(tmp, last)
3238 static struct cgroup_subsys_state *
3239 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3241 struct cgroup_subsys_state *last;
3245 pos = css_next_child(NULL, pos);
3252 * css_next_descendant_post - find the next descendant for post-order walk
3253 * @pos: the current position (%NULL to initiate traversal)
3254 * @root: css whose descendants to walk
3256 * To be used by css_for_each_descendant_post(). Find the next descendant
3257 * to visit for post-order traversal of @root's descendants. @root is
3258 * included in the iteration and the last node to be visited.
3260 * While this function requires cgroup_mutex or RCU read locking, it
3261 * doesn't require the whole traversal to be contained in a single critical
3262 * section. This function will return the correct next descendant as long
3263 * as both @pos and @cgroup are accessible and @pos is a descendant of
3266 struct cgroup_subsys_state *
3267 css_next_descendant_post(struct cgroup_subsys_state *pos,
3268 struct cgroup_subsys_state *root)
3270 struct cgroup_subsys_state *next;
3272 cgroup_assert_mutexes_or_rcu_locked();
3274 /* if first iteration, visit leftmost descendant which may be @root */
3276 return css_leftmost_descendant(root);
3278 /* if we visited @root, we're done */
3282 /* if there's an unvisited sibling, visit its leftmost descendant */
3283 next = css_next_child(pos, css_parent(pos));
3285 return css_leftmost_descendant(next);
3287 /* no sibling left, visit parent */
3288 return css_parent(pos);
3292 * css_advance_task_iter - advance a task itererator to the next css_set
3293 * @it: the iterator to advance
3295 * Advance @it to the next css_set to walk.
3297 static void css_advance_task_iter(struct css_task_iter *it)
3299 struct list_head *l = it->cset_pos;
3300 struct cgrp_cset_link *link;
3301 struct css_set *cset;
3303 /* Advance to the next non-empty css_set */
3306 if (l == it->cset_head) {
3307 it->cset_pos = NULL;
3312 cset = container_of(l, struct css_set,
3313 e_cset_node[it->ss->id]);
3315 link = list_entry(l, struct cgrp_cset_link, cset_link);
3318 } while (list_empty(&cset->tasks) && list_empty(&cset->mg_tasks));
3322 if (!list_empty(&cset->tasks))
3323 it->task_pos = cset->tasks.next;
3325 it->task_pos = cset->mg_tasks.next;
3327 it->tasks_head = &cset->tasks;
3328 it->mg_tasks_head = &cset->mg_tasks;
3332 * css_task_iter_start - initiate task iteration
3333 * @css: the css to walk tasks of
3334 * @it: the task iterator to use
3336 * Initiate iteration through the tasks of @css. The caller can call
3337 * css_task_iter_next() to walk through the tasks until the function
3338 * returns NULL. On completion of iteration, css_task_iter_end() must be
3341 * Note that this function acquires a lock which is released when the
3342 * iteration finishes. The caller can't sleep while iteration is in
3345 void css_task_iter_start(struct cgroup_subsys_state *css,
3346 struct css_task_iter *it)
3347 __acquires(css_set_rwsem)
3349 /* no one should try to iterate before mounting cgroups */
3350 WARN_ON_ONCE(!use_task_css_set_links);
3352 down_read(&css_set_rwsem);
3357 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
3359 it->cset_pos = &css->cgroup->cset_links;
3361 it->cset_head = it->cset_pos;
3363 css_advance_task_iter(it);
3367 * css_task_iter_next - return the next task for the iterator
3368 * @it: the task iterator being iterated
3370 * The "next" function for task iteration. @it should have been
3371 * initialized via css_task_iter_start(). Returns NULL when the iteration
3374 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3376 struct task_struct *res;
3377 struct list_head *l = it->task_pos;
3379 /* If the iterator cg is NULL, we have no tasks */
3382 res = list_entry(l, struct task_struct, cg_list);
3385 * Advance iterator to find next entry. cset->tasks is consumed
3386 * first and then ->mg_tasks. After ->mg_tasks, we move onto the
3391 if (l == it->tasks_head)
3392 l = it->mg_tasks_head->next;
3394 if (l == it->mg_tasks_head)
3395 css_advance_task_iter(it);
3403 * css_task_iter_end - finish task iteration
3404 * @it: the task iterator to finish
3406 * Finish task iteration started by css_task_iter_start().
3408 void css_task_iter_end(struct css_task_iter *it)
3409 __releases(css_set_rwsem)
3411 up_read(&css_set_rwsem);
3415 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3416 * @to: cgroup to which the tasks will be moved
3417 * @from: cgroup in which the tasks currently reside
3419 * Locking rules between cgroup_post_fork() and the migration path
3420 * guarantee that, if a task is forking while being migrated, the new child
3421 * is guaranteed to be either visible in the source cgroup after the
3422 * parent's migration is complete or put into the target cgroup. No task
3423 * can slip out of migration through forking.
3425 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3427 LIST_HEAD(preloaded_csets);
3428 struct cgrp_cset_link *link;
3429 struct css_task_iter it;
3430 struct task_struct *task;
3433 mutex_lock(&cgroup_mutex);
3435 /* all tasks in @from are being moved, all csets are source */
3436 down_read(&css_set_rwsem);
3437 list_for_each_entry(link, &from->cset_links, cset_link)
3438 cgroup_migrate_add_src(link->cset, to, &preloaded_csets);
3439 up_read(&css_set_rwsem);
3441 ret = cgroup_migrate_prepare_dst(to, &preloaded_csets);
3446 * Migrate tasks one-by-one until @form is empty. This fails iff
3447 * ->can_attach() fails.
3450 css_task_iter_start(&from->dummy_css, &it);
3451 task = css_task_iter_next(&it);
3453 get_task_struct(task);
3454 css_task_iter_end(&it);
3457 ret = cgroup_migrate(to, task, false);
3458 put_task_struct(task);
3460 } while (task && !ret);
3462 cgroup_migrate_finish(&preloaded_csets);
3463 mutex_unlock(&cgroup_mutex);
3468 * Stuff for reading the 'tasks'/'procs' files.
3470 * Reading this file can return large amounts of data if a cgroup has
3471 * *lots* of attached tasks. So it may need several calls to read(),
3472 * but we cannot guarantee that the information we produce is correct
3473 * unless we produce it entirely atomically.
3477 /* which pidlist file are we talking about? */
3478 enum cgroup_filetype {
3484 * A pidlist is a list of pids that virtually represents the contents of one
3485 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3486 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3489 struct cgroup_pidlist {
3491 * used to find which pidlist is wanted. doesn't change as long as
3492 * this particular list stays in the list.
3494 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3497 /* how many elements the above list has */
3499 /* each of these stored in a list by its cgroup */
3500 struct list_head links;
3501 /* pointer to the cgroup we belong to, for list removal purposes */
3502 struct cgroup *owner;
3503 /* for delayed destruction */
3504 struct delayed_work destroy_dwork;
3508 * The following two functions "fix" the issue where there are more pids
3509 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3510 * TODO: replace with a kernel-wide solution to this problem
3512 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3513 static void *pidlist_allocate(int count)
3515 if (PIDLIST_TOO_LARGE(count))
3516 return vmalloc(count * sizeof(pid_t));
3518 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3521 static void pidlist_free(void *p)
3523 if (is_vmalloc_addr(p))
3530 * Used to destroy all pidlists lingering waiting for destroy timer. None
3531 * should be left afterwards.
3533 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
3535 struct cgroup_pidlist *l, *tmp_l;
3537 mutex_lock(&cgrp->pidlist_mutex);
3538 list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
3539 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
3540 mutex_unlock(&cgrp->pidlist_mutex);
3542 flush_workqueue(cgroup_pidlist_destroy_wq);
3543 BUG_ON(!list_empty(&cgrp->pidlists));
3546 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
3548 struct delayed_work *dwork = to_delayed_work(work);
3549 struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
3551 struct cgroup_pidlist *tofree = NULL;
3553 mutex_lock(&l->owner->pidlist_mutex);
3556 * Destroy iff we didn't get queued again. The state won't change
3557 * as destroy_dwork can only be queued while locked.
3559 if (!delayed_work_pending(dwork)) {
3560 list_del(&l->links);
3561 pidlist_free(l->list);
3562 put_pid_ns(l->key.ns);
3566 mutex_unlock(&l->owner->pidlist_mutex);
3571 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3572 * Returns the number of unique elements.
3574 static int pidlist_uniq(pid_t *list, int length)
3579 * we presume the 0th element is unique, so i starts at 1. trivial
3580 * edge cases first; no work needs to be done for either
3582 if (length == 0 || length == 1)
3584 /* src and dest walk down the list; dest counts unique elements */
3585 for (src = 1; src < length; src++) {
3586 /* find next unique element */
3587 while (list[src] == list[src-1]) {
3592 /* dest always points to where the next unique element goes */
3593 list[dest] = list[src];
3601 * The two pid files - task and cgroup.procs - guaranteed that the result
3602 * is sorted, which forced this whole pidlist fiasco. As pid order is
3603 * different per namespace, each namespace needs differently sorted list,
3604 * making it impossible to use, for example, single rbtree of member tasks
3605 * sorted by task pointer. As pidlists can be fairly large, allocating one
3606 * per open file is dangerous, so cgroup had to implement shared pool of
3607 * pidlists keyed by cgroup and namespace.
3609 * All this extra complexity was caused by the original implementation
3610 * committing to an entirely unnecessary property. In the long term, we
3611 * want to do away with it. Explicitly scramble sort order if
3612 * sane_behavior so that no such expectation exists in the new interface.
3614 * Scrambling is done by swapping every two consecutive bits, which is
3615 * non-identity one-to-one mapping which disturbs sort order sufficiently.
3617 static pid_t pid_fry(pid_t pid)
3619 unsigned a = pid & 0x55555555;
3620 unsigned b = pid & 0xAAAAAAAA;
3622 return (a << 1) | (b >> 1);
3625 static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
3627 if (cgroup_sane_behavior(cgrp))
3628 return pid_fry(pid);
3633 static int cmppid(const void *a, const void *b)
3635 return *(pid_t *)a - *(pid_t *)b;
3638 static int fried_cmppid(const void *a, const void *b)
3640 return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
3643 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3644 enum cgroup_filetype type)
3646 struct cgroup_pidlist *l;
3647 /* don't need task_nsproxy() if we're looking at ourself */
3648 struct pid_namespace *ns = task_active_pid_ns(current);
3650 lockdep_assert_held(&cgrp->pidlist_mutex);
3652 list_for_each_entry(l, &cgrp->pidlists, links)
3653 if (l->key.type == type && l->key.ns == ns)
3659 * find the appropriate pidlist for our purpose (given procs vs tasks)
3660 * returns with the lock on that pidlist already held, and takes care
3661 * of the use count, or returns NULL with no locks held if we're out of
3664 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
3665 enum cgroup_filetype type)
3667 struct cgroup_pidlist *l;
3669 lockdep_assert_held(&cgrp->pidlist_mutex);
3671 l = cgroup_pidlist_find(cgrp, type);
3675 /* entry not found; create a new one */
3676 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3680 INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
3682 /* don't need task_nsproxy() if we're looking at ourself */
3683 l->key.ns = get_pid_ns(task_active_pid_ns(current));
3685 list_add(&l->links, &cgrp->pidlists);
3690 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3692 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3693 struct cgroup_pidlist **lp)
3697 int pid, n = 0; /* used for populating the array */
3698 struct css_task_iter it;
3699 struct task_struct *tsk;
3700 struct cgroup_pidlist *l;
3702 lockdep_assert_held(&cgrp->pidlist_mutex);
3705 * If cgroup gets more users after we read count, we won't have
3706 * enough space - tough. This race is indistinguishable to the
3707 * caller from the case that the additional cgroup users didn't
3708 * show up until sometime later on.
3710 length = cgroup_task_count(cgrp);
3711 array = pidlist_allocate(length);
3714 /* now, populate the array */
3715 css_task_iter_start(&cgrp->dummy_css, &it);
3716 while ((tsk = css_task_iter_next(&it))) {
3717 if (unlikely(n == length))
3719 /* get tgid or pid for procs or tasks file respectively */
3720 if (type == CGROUP_FILE_PROCS)
3721 pid = task_tgid_vnr(tsk);
3723 pid = task_pid_vnr(tsk);
3724 if (pid > 0) /* make sure to only use valid results */
3727 css_task_iter_end(&it);
3729 /* now sort & (if procs) strip out duplicates */
3730 if (cgroup_sane_behavior(cgrp))
3731 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
3733 sort(array, length, sizeof(pid_t), cmppid, NULL);
3734 if (type == CGROUP_FILE_PROCS)
3735 length = pidlist_uniq(array, length);
3737 l = cgroup_pidlist_find_create(cgrp, type);
3739 mutex_unlock(&cgrp->pidlist_mutex);
3740 pidlist_free(array);
3744 /* store array, freeing old if necessary */
3745 pidlist_free(l->list);
3753 * cgroupstats_build - build and fill cgroupstats
3754 * @stats: cgroupstats to fill information into
3755 * @dentry: A dentry entry belonging to the cgroup for which stats have
3758 * Build and fill cgroupstats so that taskstats can export it to user
3761 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3763 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
3764 struct cgroup *cgrp;
3765 struct css_task_iter it;
3766 struct task_struct *tsk;
3768 /* it should be kernfs_node belonging to cgroupfs and is a directory */
3769 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
3770 kernfs_type(kn) != KERNFS_DIR)
3773 mutex_lock(&cgroup_mutex);
3776 * We aren't being called from kernfs and there's no guarantee on
3777 * @kn->priv's validity. For this and css_tryget_from_dir(),
3778 * @kn->priv is RCU safe. Let's do the RCU dancing.
3781 cgrp = rcu_dereference(kn->priv);
3782 if (!cgrp || cgroup_is_dead(cgrp)) {
3784 mutex_unlock(&cgroup_mutex);
3789 css_task_iter_start(&cgrp->dummy_css, &it);
3790 while ((tsk = css_task_iter_next(&it))) {
3791 switch (tsk->state) {
3793 stats->nr_running++;
3795 case TASK_INTERRUPTIBLE:
3796 stats->nr_sleeping++;
3798 case TASK_UNINTERRUPTIBLE:
3799 stats->nr_uninterruptible++;
3802 stats->nr_stopped++;
3805 if (delayacct_is_task_waiting_on_io(tsk))
3806 stats->nr_io_wait++;
3810 css_task_iter_end(&it);
3812 mutex_unlock(&cgroup_mutex);
3818 * seq_file methods for the tasks/procs files. The seq_file position is the
3819 * next pid to display; the seq_file iterator is a pointer to the pid
3820 * in the cgroup->l->list array.
3823 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3826 * Initially we receive a position value that corresponds to
3827 * one more than the last pid shown (or 0 on the first call or
3828 * after a seek to the start). Use a binary-search to find the
3829 * next pid to display, if any
3831 struct kernfs_open_file *of = s->private;
3832 struct cgroup *cgrp = seq_css(s)->cgroup;
3833 struct cgroup_pidlist *l;
3834 enum cgroup_filetype type = seq_cft(s)->private;
3835 int index = 0, pid = *pos;
3838 mutex_lock(&cgrp->pidlist_mutex);
3841 * !NULL @of->priv indicates that this isn't the first start()
3842 * after open. If the matching pidlist is around, we can use that.
3843 * Look for it. Note that @of->priv can't be used directly. It
3844 * could already have been destroyed.
3847 of->priv = cgroup_pidlist_find(cgrp, type);
3850 * Either this is the first start() after open or the matching
3851 * pidlist has been destroyed inbetween. Create a new one.
3854 ret = pidlist_array_load(cgrp, type,
3855 (struct cgroup_pidlist **)&of->priv);
3857 return ERR_PTR(ret);
3862 int end = l->length;
3864 while (index < end) {
3865 int mid = (index + end) / 2;
3866 if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
3869 } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
3875 /* If we're off the end of the array, we're done */
3876 if (index >= l->length)
3878 /* Update the abstract position to be the actual pid that we found */
3879 iter = l->list + index;
3880 *pos = cgroup_pid_fry(cgrp, *iter);
3884 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3886 struct kernfs_open_file *of = s->private;
3887 struct cgroup_pidlist *l = of->priv;
3890 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
3891 CGROUP_PIDLIST_DESTROY_DELAY);
3892 mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
3895 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3897 struct kernfs_open_file *of = s->private;
3898 struct cgroup_pidlist *l = of->priv;
3900 pid_t *end = l->list + l->length;
3902 * Advance to the next pid in the array. If this goes off the
3909 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
3914 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3916 return seq_printf(s, "%d\n", *(int *)v);
3919 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3922 return notify_on_release(css->cgroup);
3925 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3926 struct cftype *cft, u64 val)
3928 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3930 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3932 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3936 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3939 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3942 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3943 struct cftype *cft, u64 val)
3946 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3948 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3952 static struct cftype cgroup_base_files[] = {
3954 .name = "cgroup.procs",
3955 .seq_start = cgroup_pidlist_start,
3956 .seq_next = cgroup_pidlist_next,
3957 .seq_stop = cgroup_pidlist_stop,
3958 .seq_show = cgroup_pidlist_show,
3959 .private = CGROUP_FILE_PROCS,
3960 .write_u64 = cgroup_procs_write,
3961 .mode = S_IRUGO | S_IWUSR,
3964 .name = "cgroup.clone_children",
3965 .flags = CFTYPE_INSANE,
3966 .read_u64 = cgroup_clone_children_read,
3967 .write_u64 = cgroup_clone_children_write,
3970 .name = "cgroup.sane_behavior",
3971 .flags = CFTYPE_ONLY_ON_ROOT,
3972 .seq_show = cgroup_sane_behavior_show,
3975 .name = "cgroup.controllers",
3976 .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_ONLY_ON_ROOT,
3977 .seq_show = cgroup_root_controllers_show,
3980 .name = "cgroup.controllers",
3981 .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_NOT_ON_ROOT,
3982 .seq_show = cgroup_controllers_show,
3985 .name = "cgroup.subtree_control",
3986 .flags = CFTYPE_ONLY_ON_DFL,
3987 .seq_show = cgroup_subtree_control_show,
3988 .write_string = cgroup_subtree_control_write,
3991 .name = "cgroup.populated",
3992 .flags = CFTYPE_ONLY_ON_DFL | CFTYPE_NOT_ON_ROOT,
3993 .seq_show = cgroup_populated_show,
3997 * Historical crazy stuff. These don't have "cgroup." prefix and
3998 * don't exist if sane_behavior. If you're depending on these, be
3999 * prepared to be burned.
4003 .flags = CFTYPE_INSANE, /* use "procs" instead */
4004 .seq_start = cgroup_pidlist_start,
4005 .seq_next = cgroup_pidlist_next,
4006 .seq_stop = cgroup_pidlist_stop,
4007 .seq_show = cgroup_pidlist_show,
4008 .private = CGROUP_FILE_TASKS,
4009 .write_u64 = cgroup_tasks_write,
4010 .mode = S_IRUGO | S_IWUSR,
4013 .name = "notify_on_release",
4014 .flags = CFTYPE_INSANE,
4015 .read_u64 = cgroup_read_notify_on_release,
4016 .write_u64 = cgroup_write_notify_on_release,
4019 .name = "release_agent",
4020 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
4021 .seq_show = cgroup_release_agent_show,
4022 .write_string = cgroup_release_agent_write,
4023 .max_write_len = PATH_MAX - 1,
4029 * cgroup_populate_dir - create subsys files in a cgroup directory
4030 * @cgrp: target cgroup
4031 * @subsys_mask: mask of the subsystem ids whose files should be added
4033 * On failure, no file is added.
4035 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned int subsys_mask)
4037 struct cgroup_subsys *ss;
4040 /* process cftsets of each subsystem */
4041 for_each_subsys(ss, i) {
4042 struct cftype *cfts;
4044 if (!(subsys_mask & (1 << i)))
4047 list_for_each_entry(cfts, &ss->cfts, node) {
4048 ret = cgroup_addrm_files(cgrp, cfts, true);
4055 cgroup_clear_dir(cgrp, subsys_mask);
4060 * css destruction is four-stage process.
4062 * 1. Destruction starts. Killing of the percpu_ref is initiated.
4063 * Implemented in kill_css().
4065 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4066 * and thus css_tryget() is guaranteed to fail, the css can be offlined
4067 * by invoking offline_css(). After offlining, the base ref is put.
4068 * Implemented in css_killed_work_fn().
4070 * 3. When the percpu_ref reaches zero, the only possible remaining
4071 * accessors are inside RCU read sections. css_release() schedules the
4074 * 4. After the grace period, the css can be freed. Implemented in
4075 * css_free_work_fn().
4077 * It is actually hairier because both step 2 and 4 require process context
4078 * and thus involve punting to css->destroy_work adding two additional
4079 * steps to the already complex sequence.
4081 static void css_free_work_fn(struct work_struct *work)
4083 struct cgroup_subsys_state *css =
4084 container_of(work, struct cgroup_subsys_state, destroy_work);
4085 struct cgroup *cgrp = css->cgroup;
4088 css_put(css->parent);
4090 css->ss->css_free(css);
4094 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4096 struct cgroup_subsys_state *css =
4097 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4099 INIT_WORK(&css->destroy_work, css_free_work_fn);
4100 queue_work(cgroup_destroy_wq, &css->destroy_work);
4103 static void css_release(struct percpu_ref *ref)
4105 struct cgroup_subsys_state *css =
4106 container_of(ref, struct cgroup_subsys_state, refcnt);
4108 RCU_INIT_POINTER(css->cgroup->subsys[css->ss->id], NULL);
4109 call_rcu(&css->rcu_head, css_free_rcu_fn);
4112 static void init_css(struct cgroup_subsys_state *css, struct cgroup_subsys *ss,
4113 struct cgroup *cgrp)
4120 css->parent = cgroup_css(cgrp->parent, ss);
4122 css->flags |= CSS_ROOT;
4124 BUG_ON(cgroup_css(cgrp, ss));
4127 /* invoke ->css_online() on a new CSS and mark it online if successful */
4128 static int online_css(struct cgroup_subsys_state *css)
4130 struct cgroup_subsys *ss = css->ss;
4133 lockdep_assert_held(&cgroup_tree_mutex);
4134 lockdep_assert_held(&cgroup_mutex);
4137 ret = ss->css_online(css);
4139 css->flags |= CSS_ONLINE;
4140 css->cgroup->nr_css++;
4141 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
4146 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4147 static void offline_css(struct cgroup_subsys_state *css)
4149 struct cgroup_subsys *ss = css->ss;
4151 lockdep_assert_held(&cgroup_tree_mutex);
4152 lockdep_assert_held(&cgroup_mutex);
4154 if (!(css->flags & CSS_ONLINE))
4157 if (ss->css_offline)
4158 ss->css_offline(css);
4160 css->flags &= ~CSS_ONLINE;
4161 css->cgroup->nr_css--;
4162 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
4164 wake_up_all(&css->cgroup->offline_waitq);
4168 * create_css - create a cgroup_subsys_state
4169 * @cgrp: the cgroup new css will be associated with
4170 * @ss: the subsys of new css
4172 * Create a new css associated with @cgrp - @ss pair. On success, the new
4173 * css is online and installed in @cgrp with all interface files created.
4174 * Returns 0 on success, -errno on failure.
4176 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss)
4178 struct cgroup *parent = cgrp->parent;
4179 struct cgroup_subsys_state *css;
4182 lockdep_assert_held(&cgroup_mutex);
4184 css = ss->css_alloc(cgroup_css(parent, ss));
4186 return PTR_ERR(css);
4188 init_css(css, ss, cgrp);
4190 css_get(css->parent);
4192 err = percpu_ref_init(&css->refcnt, css_release);
4196 err = cgroup_populate_dir(cgrp, 1 << ss->id);
4198 goto err_free_percpu_ref;
4200 err = online_css(css);
4204 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4206 pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4207 current->comm, current->pid, ss->name);
4208 if (!strcmp(ss->name, "memory"))
4209 pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
4210 ss->warned_broken_hierarchy = true;
4216 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4217 err_free_percpu_ref:
4218 percpu_ref_cancel_init(&css->refcnt);
4220 call_rcu(&css->rcu_head, css_free_rcu_fn);
4225 * cgroup_create - create a cgroup
4226 * @parent: cgroup that will be parent of the new cgroup
4227 * @name: name of the new cgroup
4228 * @mode: mode to set on new cgroup
4230 static long cgroup_create(struct cgroup *parent, const char *name,
4233 struct cgroup *cgrp;
4234 struct cgroup_root *root = parent->root;
4236 struct cgroup_subsys *ss;
4237 struct kernfs_node *kn;
4239 /* allocate the cgroup and its ID, 0 is reserved for the root */
4240 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4244 mutex_lock(&cgroup_tree_mutex);
4247 * Only live parents can have children. Note that the liveliness
4248 * check isn't strictly necessary because cgroup_mkdir() and
4249 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4250 * anyway so that locking is contained inside cgroup proper and we
4251 * don't get nasty surprises if we ever grow another caller.
4253 if (!cgroup_lock_live_group(parent)) {
4255 goto err_unlock_tree;
4259 * Temporarily set the pointer to NULL, so idr_find() won't return
4260 * a half-baked cgroup.
4262 cgrp->id = cgroup_idr_alloc(&root->cgroup_idr, NULL, 2, 0, GFP_NOWAIT);
4268 init_cgroup_housekeeping(cgrp);
4270 cgrp->parent = parent;
4271 cgrp->dummy_css.parent = &parent->dummy_css;
4272 cgrp->root = parent->root;
4274 if (notify_on_release(parent))
4275 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4277 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4278 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4280 /* create the directory */
4281 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
4289 * This extra ref will be put in cgroup_free_fn() and guarantees
4290 * that @cgrp->kn is always accessible.
4294 cgrp->serial_nr = cgroup_serial_nr_next++;
4296 /* allocation complete, commit to creation */
4297 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4298 atomic_inc(&root->nr_cgrps);
4302 * @cgrp is now fully operational. If something fails after this
4303 * point, it'll be released via the normal destruction path.
4305 cgroup_idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4307 err = cgroup_kn_set_ugid(kn);
4311 err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
4315 /* let's create and online css's */
4316 for_each_subsys(ss, ssid) {
4317 if (parent->child_subsys_mask & (1 << ssid)) {
4318 err = create_css(cgrp, ss);
4325 * On the default hierarchy, a child doesn't automatically inherit
4326 * child_subsys_mask from the parent. Each is configured manually.
4328 if (!cgroup_on_dfl(cgrp))
4329 cgrp->child_subsys_mask = parent->child_subsys_mask;
4331 kernfs_activate(kn);
4333 mutex_unlock(&cgroup_mutex);
4334 mutex_unlock(&cgroup_tree_mutex);
4339 cgroup_idr_remove(&root->cgroup_idr, cgrp->id);
4341 mutex_unlock(&cgroup_mutex);
4343 mutex_unlock(&cgroup_tree_mutex);
4348 cgroup_destroy_locked(cgrp);
4349 mutex_unlock(&cgroup_mutex);
4350 mutex_unlock(&cgroup_tree_mutex);
4354 static int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
4357 struct cgroup *parent = parent_kn->priv;
4361 * cgroup_create() grabs cgroup_tree_mutex which nests outside
4362 * kernfs active_ref and cgroup_create() already synchronizes
4363 * properly against removal through cgroup_lock_live_group().
4364 * Break it before calling cgroup_create().
4367 kernfs_break_active_protection(parent_kn);
4369 ret = cgroup_create(parent, name, mode);
4371 kernfs_unbreak_active_protection(parent_kn);
4377 * This is called when the refcnt of a css is confirmed to be killed.
4378 * css_tryget() is now guaranteed to fail.
4380 static void css_killed_work_fn(struct work_struct *work)
4382 struct cgroup_subsys_state *css =
4383 container_of(work, struct cgroup_subsys_state, destroy_work);
4384 struct cgroup *cgrp = css->cgroup;
4386 mutex_lock(&cgroup_tree_mutex);
4387 mutex_lock(&cgroup_mutex);
4390 * css_tryget() is guaranteed to fail now. Tell subsystems to
4391 * initate destruction.
4396 * If @cgrp is marked dead, it's waiting for refs of all css's to
4397 * be disabled before proceeding to the second phase of cgroup
4398 * destruction. If we are the last one, kick it off.
4400 if (!cgrp->nr_css && cgroup_is_dead(cgrp))
4401 cgroup_destroy_css_killed(cgrp);
4403 mutex_unlock(&cgroup_mutex);
4404 mutex_unlock(&cgroup_tree_mutex);
4407 * Put the css refs from kill_css(). Each css holds an extra
4408 * reference to the cgroup's dentry and cgroup removal proceeds
4409 * regardless of css refs. On the last put of each css, whenever
4410 * that may be, the extra dentry ref is put so that dentry
4411 * destruction happens only after all css's are released.
4416 /* css kill confirmation processing requires process context, bounce */
4417 static void css_killed_ref_fn(struct percpu_ref *ref)
4419 struct cgroup_subsys_state *css =
4420 container_of(ref, struct cgroup_subsys_state, refcnt);
4422 INIT_WORK(&css->destroy_work, css_killed_work_fn);
4423 queue_work(cgroup_destroy_wq, &css->destroy_work);
4427 * kill_css - destroy a css
4428 * @css: css to destroy
4430 * This function initiates destruction of @css by removing cgroup interface
4431 * files and putting its base reference. ->css_offline() will be invoked
4432 * asynchronously once css_tryget() is guaranteed to fail and when the
4433 * reference count reaches zero, @css will be released.
4435 static void kill_css(struct cgroup_subsys_state *css)
4437 lockdep_assert_held(&cgroup_tree_mutex);
4440 * This must happen before css is disassociated with its cgroup.
4441 * See seq_css() for details.
4443 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4446 * Killing would put the base ref, but we need to keep it alive
4447 * until after ->css_offline().
4452 * cgroup core guarantees that, by the time ->css_offline() is
4453 * invoked, no new css reference will be given out via
4454 * css_tryget(). We can't simply call percpu_ref_kill() and
4455 * proceed to offlining css's because percpu_ref_kill() doesn't
4456 * guarantee that the ref is seen as killed on all CPUs on return.
4458 * Use percpu_ref_kill_and_confirm() to get notifications as each
4459 * css is confirmed to be seen as killed on all CPUs.
4461 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4465 * cgroup_destroy_locked - the first stage of cgroup destruction
4466 * @cgrp: cgroup to be destroyed
4468 * css's make use of percpu refcnts whose killing latency shouldn't be
4469 * exposed to userland and are RCU protected. Also, cgroup core needs to
4470 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
4471 * invoked. To satisfy all the requirements, destruction is implemented in
4472 * the following two steps.
4474 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4475 * userland visible parts and start killing the percpu refcnts of
4476 * css's. Set up so that the next stage will be kicked off once all
4477 * the percpu refcnts are confirmed to be killed.
4479 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4480 * rest of destruction. Once all cgroup references are gone, the
4481 * cgroup is RCU-freed.
4483 * This function implements s1. After this step, @cgrp is gone as far as
4484 * the userland is concerned and a new cgroup with the same name may be
4485 * created. As cgroup doesn't care about the names internally, this
4486 * doesn't cause any problem.
4488 static int cgroup_destroy_locked(struct cgroup *cgrp)
4489 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4491 struct cgroup *child;
4492 struct cgroup_subsys_state *css;
4496 lockdep_assert_held(&cgroup_tree_mutex);
4497 lockdep_assert_held(&cgroup_mutex);
4500 * css_set_rwsem synchronizes access to ->cset_links and prevents
4501 * @cgrp from being removed while put_css_set() is in progress.
4503 down_read(&css_set_rwsem);
4504 empty = list_empty(&cgrp->cset_links);
4505 up_read(&css_set_rwsem);
4510 * Make sure there's no live children. We can't test ->children
4511 * emptiness as dead children linger on it while being destroyed;
4512 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
4516 list_for_each_entry_rcu(child, &cgrp->children, sibling) {
4517 empty = cgroup_is_dead(child);
4526 * Mark @cgrp dead. This prevents further task migration and child
4527 * creation by disabling cgroup_lock_live_group(). Note that
4528 * CGRP_DEAD assertion is depended upon by css_next_child() to
4529 * resume iteration after dropping RCU read lock. See
4530 * css_next_child() for details.
4532 set_bit(CGRP_DEAD, &cgrp->flags);
4535 * Initiate massacre of all css's. cgroup_destroy_css_killed()
4536 * will be invoked to perform the rest of destruction once the
4537 * percpu refs of all css's are confirmed to be killed. This
4538 * involves removing the subsystem's files, drop cgroup_mutex.
4540 mutex_unlock(&cgroup_mutex);
4541 for_each_css(css, ssid, cgrp)
4543 mutex_lock(&cgroup_mutex);
4545 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4546 raw_spin_lock(&release_list_lock);
4547 if (!list_empty(&cgrp->release_list))
4548 list_del_init(&cgrp->release_list);
4549 raw_spin_unlock(&release_list_lock);
4552 * If @cgrp has css's attached, the second stage of cgroup
4553 * destruction is kicked off from css_killed_work_fn() after the
4554 * refs of all attached css's are killed. If @cgrp doesn't have
4555 * any css, we kick it off here.
4558 cgroup_destroy_css_killed(cgrp);
4560 /* remove @cgrp directory along with the base files */
4561 mutex_unlock(&cgroup_mutex);
4564 * There are two control paths which try to determine cgroup from
4565 * dentry without going through kernfs - cgroupstats_build() and
4566 * css_tryget_from_dir(). Those are supported by RCU protecting
4567 * clearing of cgrp->kn->priv backpointer, which should happen
4568 * after all files under it have been removed.
4570 kernfs_remove(cgrp->kn); /* @cgrp has an extra ref on its kn */
4571 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv, NULL);
4573 mutex_lock(&cgroup_mutex);
4579 * cgroup_destroy_css_killed - the second step of cgroup destruction
4580 * @work: cgroup->destroy_free_work
4582 * This function is invoked from a work item for a cgroup which is being
4583 * destroyed after all css's are offlined and performs the rest of
4584 * destruction. This is the second step of destruction described in the
4585 * comment above cgroup_destroy_locked().
4587 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
4589 struct cgroup *parent = cgrp->parent;
4591 lockdep_assert_held(&cgroup_tree_mutex);
4592 lockdep_assert_held(&cgroup_mutex);
4594 /* delete this cgroup from parent->children */
4595 list_del_rcu(&cgrp->sibling);
4599 set_bit(CGRP_RELEASABLE, &parent->flags);
4600 check_for_release(parent);
4603 static int cgroup_rmdir(struct kernfs_node *kn)
4605 struct cgroup *cgrp = kn->priv;
4609 * This is self-destruction but @kn can't be removed while this
4610 * callback is in progress. Let's break active protection. Once
4611 * the protection is broken, @cgrp can be destroyed at any point.
4612 * Pin it so that it stays accessible.
4615 kernfs_break_active_protection(kn);
4617 mutex_lock(&cgroup_tree_mutex);
4618 mutex_lock(&cgroup_mutex);
4621 * @cgrp might already have been destroyed while we're trying to
4624 if (!cgroup_is_dead(cgrp))
4625 ret = cgroup_destroy_locked(cgrp);
4627 mutex_unlock(&cgroup_mutex);
4628 mutex_unlock(&cgroup_tree_mutex);
4630 kernfs_unbreak_active_protection(kn);
4635 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
4636 .remount_fs = cgroup_remount,
4637 .show_options = cgroup_show_options,
4638 .mkdir = cgroup_mkdir,
4639 .rmdir = cgroup_rmdir,
4640 .rename = cgroup_rename,
4643 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4645 struct cgroup_subsys_state *css;
4647 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4649 mutex_lock(&cgroup_tree_mutex);
4650 mutex_lock(&cgroup_mutex);
4652 INIT_LIST_HEAD(&ss->cfts);
4654 /* Create the root cgroup state for this subsystem */
4655 ss->root = &cgrp_dfl_root;
4656 css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
4657 /* We don't handle early failures gracefully */
4658 BUG_ON(IS_ERR(css));
4659 init_css(css, ss, &cgrp_dfl_root.cgrp);
4661 /* Update the init_css_set to contain a subsys
4662 * pointer to this state - since the subsystem is
4663 * newly registered, all tasks and hence the
4664 * init_css_set is in the subsystem's root cgroup. */
4665 init_css_set.subsys[ss->id] = css;
4667 need_forkexit_callback |= ss->fork || ss->exit;
4669 /* At system boot, before all subsystems have been
4670 * registered, no tasks have been forked, so we don't
4671 * need to invoke fork callbacks here. */
4672 BUG_ON(!list_empty(&init_task.tasks));
4674 BUG_ON(online_css(css));
4676 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
4678 mutex_unlock(&cgroup_mutex);
4679 mutex_unlock(&cgroup_tree_mutex);
4683 * cgroup_init_early - cgroup initialization at system boot
4685 * Initialize cgroups at system boot, and initialize any
4686 * subsystems that request early init.
4688 int __init cgroup_init_early(void)
4690 static struct cgroup_sb_opts __initdata opts =
4691 { .flags = CGRP_ROOT_SANE_BEHAVIOR };
4692 struct cgroup_subsys *ss;
4695 init_cgroup_root(&cgrp_dfl_root, &opts);
4696 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4698 for_each_subsys(ss, i) {
4699 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
4700 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
4701 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
4703 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
4704 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
4707 ss->name = cgroup_subsys_name[i];
4710 cgroup_init_subsys(ss);
4716 * cgroup_init - cgroup initialization
4718 * Register cgroup filesystem and /proc file, and initialize
4719 * any subsystems that didn't request early init.
4721 int __init cgroup_init(void)
4723 struct cgroup_subsys *ss;
4727 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
4729 mutex_lock(&cgroup_tree_mutex);
4730 mutex_lock(&cgroup_mutex);
4732 /* Add init_css_set to the hash table */
4733 key = css_set_hash(init_css_set.subsys);
4734 hash_add(css_set_table, &init_css_set.hlist, key);
4736 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
4738 mutex_unlock(&cgroup_mutex);
4739 mutex_unlock(&cgroup_tree_mutex);
4741 for_each_subsys(ss, ssid) {
4742 if (!ss->early_init)
4743 cgroup_init_subsys(ss);
4745 list_add_tail(&init_css_set.e_cset_node[ssid],
4746 &cgrp_dfl_root.cgrp.e_csets[ssid]);
4749 * cftype registration needs kmalloc and can't be done
4750 * during early_init. Register base cftypes separately.
4752 if (ss->base_cftypes)
4753 WARN_ON(cgroup_add_cftypes(ss, ss->base_cftypes));
4756 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4760 err = register_filesystem(&cgroup_fs_type);
4762 kobject_put(cgroup_kobj);
4766 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4770 static int __init cgroup_wq_init(void)
4773 * There isn't much point in executing destruction path in
4774 * parallel. Good chunk is serialized with cgroup_mutex anyway.
4775 * Use 1 for @max_active.
4777 * We would prefer to do this in cgroup_init() above, but that
4778 * is called before init_workqueues(): so leave this until after.
4780 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
4781 BUG_ON(!cgroup_destroy_wq);
4784 * Used to destroy pidlists and separate to serve as flush domain.
4785 * Cap @max_active to 1 too.
4787 cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
4789 BUG_ON(!cgroup_pidlist_destroy_wq);
4793 core_initcall(cgroup_wq_init);
4796 * proc_cgroup_show()
4797 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4798 * - Used for /proc/<pid>/cgroup.
4801 /* TODO: Use a proper seq_file iterator */
4802 int proc_cgroup_show(struct seq_file *m, void *v)
4805 struct task_struct *tsk;
4808 struct cgroup_root *root;
4811 buf = kmalloc(PATH_MAX, GFP_KERNEL);
4817 tsk = get_pid_task(pid, PIDTYPE_PID);
4823 mutex_lock(&cgroup_mutex);
4824 down_read(&css_set_rwsem);
4826 for_each_root(root) {
4827 struct cgroup_subsys *ss;
4828 struct cgroup *cgrp;
4829 int ssid, count = 0;
4831 if (root == &cgrp_dfl_root && !cgrp_dfl_root_visible)
4834 seq_printf(m, "%d:", root->hierarchy_id);
4835 for_each_subsys(ss, ssid)
4836 if (root->subsys_mask & (1 << ssid))
4837 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4838 if (strlen(root->name))
4839 seq_printf(m, "%sname=%s", count ? "," : "",
4842 cgrp = task_cgroup_from_root(tsk, root);
4843 path = cgroup_path(cgrp, buf, PATH_MAX);
4845 retval = -ENAMETOOLONG;
4853 up_read(&css_set_rwsem);
4854 mutex_unlock(&cgroup_mutex);
4855 put_task_struct(tsk);
4862 /* Display information about each subsystem and each hierarchy */
4863 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4865 struct cgroup_subsys *ss;
4868 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4870 * ideally we don't want subsystems moving around while we do this.
4871 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4872 * subsys/hierarchy state.
4874 mutex_lock(&cgroup_mutex);
4876 for_each_subsys(ss, i)
4877 seq_printf(m, "%s\t%d\t%d\t%d\n",
4878 ss->name, ss->root->hierarchy_id,
4879 atomic_read(&ss->root->nr_cgrps), !ss->disabled);
4881 mutex_unlock(&cgroup_mutex);
4885 static int cgroupstats_open(struct inode *inode, struct file *file)
4887 return single_open(file, proc_cgroupstats_show, NULL);
4890 static const struct file_operations proc_cgroupstats_operations = {
4891 .open = cgroupstats_open,
4893 .llseek = seq_lseek,
4894 .release = single_release,
4898 * cgroup_fork - initialize cgroup related fields during copy_process()
4899 * @child: pointer to task_struct of forking parent process.
4901 * A task is associated with the init_css_set until cgroup_post_fork()
4902 * attaches it to the parent's css_set. Empty cg_list indicates that
4903 * @child isn't holding reference to its css_set.
4905 void cgroup_fork(struct task_struct *child)
4907 RCU_INIT_POINTER(child->cgroups, &init_css_set);
4908 INIT_LIST_HEAD(&child->cg_list);
4912 * cgroup_post_fork - called on a new task after adding it to the task list
4913 * @child: the task in question
4915 * Adds the task to the list running through its css_set if necessary and
4916 * call the subsystem fork() callbacks. Has to be after the task is
4917 * visible on the task list in case we race with the first call to
4918 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
4921 void cgroup_post_fork(struct task_struct *child)
4923 struct cgroup_subsys *ss;
4927 * This may race against cgroup_enable_task_cg_links(). As that
4928 * function sets use_task_css_set_links before grabbing
4929 * tasklist_lock and we just went through tasklist_lock to add
4930 * @child, it's guaranteed that either we see the set
4931 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
4932 * @child during its iteration.
4934 * If we won the race, @child is associated with %current's
4935 * css_set. Grabbing css_set_rwsem guarantees both that the
4936 * association is stable, and, on completion of the parent's
4937 * migration, @child is visible in the source of migration or
4938 * already in the destination cgroup. This guarantee is necessary
4939 * when implementing operations which need to migrate all tasks of
4940 * a cgroup to another.
4942 * Note that if we lose to cgroup_enable_task_cg_links(), @child
4943 * will remain in init_css_set. This is safe because all tasks are
4944 * in the init_css_set before cg_links is enabled and there's no
4945 * operation which transfers all tasks out of init_css_set.
4947 if (use_task_css_set_links) {
4948 struct css_set *cset;
4950 down_write(&css_set_rwsem);
4951 cset = task_css_set(current);
4952 if (list_empty(&child->cg_list)) {
4953 rcu_assign_pointer(child->cgroups, cset);
4954 list_add(&child->cg_list, &cset->tasks);
4957 up_write(&css_set_rwsem);
4961 * Call ss->fork(). This must happen after @child is linked on
4962 * css_set; otherwise, @child might change state between ->fork()
4963 * and addition to css_set.
4965 if (need_forkexit_callback) {
4966 for_each_subsys(ss, i)
4973 * cgroup_exit - detach cgroup from exiting task
4974 * @tsk: pointer to task_struct of exiting process
4976 * Description: Detach cgroup from @tsk and release it.
4978 * Note that cgroups marked notify_on_release force every task in
4979 * them to take the global cgroup_mutex mutex when exiting.
4980 * This could impact scaling on very large systems. Be reluctant to
4981 * use notify_on_release cgroups where very high task exit scaling
4982 * is required on large systems.
4984 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
4985 * call cgroup_exit() while the task is still competent to handle
4986 * notify_on_release(), then leave the task attached to the root cgroup in
4987 * each hierarchy for the remainder of its exit. No need to bother with
4988 * init_css_set refcnting. init_css_set never goes away and we can't race
4989 * with migration path - PF_EXITING is visible to migration path.
4991 void cgroup_exit(struct task_struct *tsk)
4993 struct cgroup_subsys *ss;
4994 struct css_set *cset;
4995 bool put_cset = false;
4999 * Unlink from @tsk from its css_set. As migration path can't race
5000 * with us, we can check cg_list without grabbing css_set_rwsem.
5002 if (!list_empty(&tsk->cg_list)) {
5003 down_write(&css_set_rwsem);
5004 list_del_init(&tsk->cg_list);
5005 up_write(&css_set_rwsem);
5009 /* Reassign the task to the init_css_set. */
5010 cset = task_css_set(tsk);
5011 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
5013 if (need_forkexit_callback) {
5014 /* see cgroup_post_fork() for details */
5015 for_each_subsys(ss, i) {
5017 struct cgroup_subsys_state *old_css = cset->subsys[i];
5018 struct cgroup_subsys_state *css = task_css(tsk, i);
5020 ss->exit(css, old_css, tsk);
5026 put_css_set(cset, true);
5029 static void check_for_release(struct cgroup *cgrp)
5031 if (cgroup_is_releasable(cgrp) &&
5032 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
5034 * Control Group is currently removeable. If it's not
5035 * already queued for a userspace notification, queue
5038 int need_schedule_work = 0;
5040 raw_spin_lock(&release_list_lock);
5041 if (!cgroup_is_dead(cgrp) &&
5042 list_empty(&cgrp->release_list)) {
5043 list_add(&cgrp->release_list, &release_list);
5044 need_schedule_work = 1;
5046 raw_spin_unlock(&release_list_lock);
5047 if (need_schedule_work)
5048 schedule_work(&release_agent_work);
5053 * Notify userspace when a cgroup is released, by running the
5054 * configured release agent with the name of the cgroup (path
5055 * relative to the root of cgroup file system) as the argument.
5057 * Most likely, this user command will try to rmdir this cgroup.
5059 * This races with the possibility that some other task will be
5060 * attached to this cgroup before it is removed, or that some other
5061 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5062 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5063 * unused, and this cgroup will be reprieved from its death sentence,
5064 * to continue to serve a useful existence. Next time it's released,
5065 * we will get notified again, if it still has 'notify_on_release' set.
5067 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5068 * means only wait until the task is successfully execve()'d. The
5069 * separate release agent task is forked by call_usermodehelper(),
5070 * then control in this thread returns here, without waiting for the
5071 * release agent task. We don't bother to wait because the caller of
5072 * this routine has no use for the exit status of the release agent
5073 * task, so no sense holding our caller up for that.
5075 static void cgroup_release_agent(struct work_struct *work)
5077 BUG_ON(work != &release_agent_work);
5078 mutex_lock(&cgroup_mutex);
5079 raw_spin_lock(&release_list_lock);
5080 while (!list_empty(&release_list)) {
5081 char *argv[3], *envp[3];
5083 char *pathbuf = NULL, *agentbuf = NULL, *path;
5084 struct cgroup *cgrp = list_entry(release_list.next,
5087 list_del_init(&cgrp->release_list);
5088 raw_spin_unlock(&release_list_lock);
5089 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
5092 path = cgroup_path(cgrp, pathbuf, PATH_MAX);
5095 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5100 argv[i++] = agentbuf;
5105 /* minimal command environment */
5106 envp[i++] = "HOME=/";
5107 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5110 /* Drop the lock while we invoke the usermode helper,
5111 * since the exec could involve hitting disk and hence
5112 * be a slow process */
5113 mutex_unlock(&cgroup_mutex);
5114 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5115 mutex_lock(&cgroup_mutex);
5119 raw_spin_lock(&release_list_lock);
5121 raw_spin_unlock(&release_list_lock);
5122 mutex_unlock(&cgroup_mutex);
5125 static int __init cgroup_disable(char *str)
5127 struct cgroup_subsys *ss;
5131 while ((token = strsep(&str, ",")) != NULL) {
5135 for_each_subsys(ss, i) {
5136 if (!strcmp(token, ss->name)) {
5138 printk(KERN_INFO "Disabling %s control group"
5139 " subsystem\n", ss->name);
5146 __setup("cgroup_disable=", cgroup_disable);
5149 * css_tryget_from_dir - get corresponding css from the dentry of a cgroup dir
5150 * @dentry: directory dentry of interest
5151 * @ss: subsystem of interest
5153 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
5154 * to get the corresponding css and return it. If such css doesn't exist
5155 * or can't be pinned, an ERR_PTR value is returned.
5157 struct cgroup_subsys_state *css_tryget_from_dir(struct dentry *dentry,
5158 struct cgroup_subsys *ss)
5160 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
5161 struct cgroup_subsys_state *css = NULL;
5162 struct cgroup *cgrp;
5164 /* is @dentry a cgroup dir? */
5165 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
5166 kernfs_type(kn) != KERNFS_DIR)
5167 return ERR_PTR(-EBADF);
5172 * This path doesn't originate from kernfs and @kn could already
5173 * have been or be removed at any point. @kn->priv is RCU
5174 * protected for this access. See destroy_locked() for details.
5176 cgrp = rcu_dereference(kn->priv);
5178 css = cgroup_css(cgrp, ss);
5180 if (!css || !css_tryget(css))
5181 css = ERR_PTR(-ENOENT);
5188 * css_from_id - lookup css by id
5189 * @id: the cgroup id
5190 * @ss: cgroup subsys to be looked into
5192 * Returns the css if there's valid one with @id, otherwise returns NULL.
5193 * Should be called under rcu_read_lock().
5195 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5197 struct cgroup *cgrp;
5199 WARN_ON_ONCE(!rcu_read_lock_held());
5201 cgrp = idr_find(&ss->root->cgroup_idr, id);
5203 return cgroup_css(cgrp, ss);
5207 #ifdef CONFIG_CGROUP_DEBUG
5208 static struct cgroup_subsys_state *
5209 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5211 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5214 return ERR_PTR(-ENOMEM);
5219 static void debug_css_free(struct cgroup_subsys_state *css)
5224 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5227 return cgroup_task_count(css->cgroup);
5230 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5233 return (u64)(unsigned long)current->cgroups;
5236 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5242 count = atomic_read(&task_css_set(current)->refcount);
5247 static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
5249 struct cgrp_cset_link *link;
5250 struct css_set *cset;
5253 name_buf = kmalloc(NAME_MAX + 1, GFP_KERNEL);
5257 down_read(&css_set_rwsem);
5259 cset = rcu_dereference(current->cgroups);
5260 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5261 struct cgroup *c = link->cgrp;
5263 cgroup_name(c, name_buf, NAME_MAX + 1);
5264 seq_printf(seq, "Root %d group %s\n",
5265 c->root->hierarchy_id, name_buf);
5268 up_read(&css_set_rwsem);
5273 #define MAX_TASKS_SHOWN_PER_CSS 25
5274 static int cgroup_css_links_read(struct seq_file *seq, void *v)
5276 struct cgroup_subsys_state *css = seq_css(seq);
5277 struct cgrp_cset_link *link;
5279 down_read(&css_set_rwsem);
5280 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5281 struct css_set *cset = link->cset;
5282 struct task_struct *task;
5285 seq_printf(seq, "css_set %p\n", cset);
5287 list_for_each_entry(task, &cset->tasks, cg_list) {
5288 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5290 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5293 list_for_each_entry(task, &cset->mg_tasks, cg_list) {
5294 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5296 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5300 seq_puts(seq, " ...\n");
5302 up_read(&css_set_rwsem);
5306 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5308 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
5311 static struct cftype debug_files[] = {
5313 .name = "taskcount",
5314 .read_u64 = debug_taskcount_read,
5318 .name = "current_css_set",
5319 .read_u64 = current_css_set_read,
5323 .name = "current_css_set_refcount",
5324 .read_u64 = current_css_set_refcount_read,
5328 .name = "current_css_set_cg_links",
5329 .seq_show = current_css_set_cg_links_read,
5333 .name = "cgroup_css_links",
5334 .seq_show = cgroup_css_links_read,
5338 .name = "releasable",
5339 .read_u64 = releasable_read,
5345 struct cgroup_subsys debug_cgrp_subsys = {
5346 .css_alloc = debug_css_alloc,
5347 .css_free = debug_css_free,
5348 .base_cftypes = debug_files,
5350 #endif /* CONFIG_CGROUP_DEBUG */