Linux 4.2.6
[linux/fpc-iii.git] / kernel / cgroup.c
blobfe6f855de3d1cbb7d2417494603e9e69148c409d
1 /*
2 * Generic process-grouping system.
4 * Based originally on the cpuset system, extracted by Paul Menage
5 * Copyright (C) 2006 Google, Inc
7 * Notifications support
8 * Copyright (C) 2009 Nokia Corporation
9 * Author: Kirill A. Shutemov
11 * Copyright notices from the original cpuset code:
12 * --------------------------------------------------
13 * Copyright (C) 2003 BULL SA.
14 * Copyright (C) 2004-2006 Silicon Graphics, Inc.
16 * Portions derived from Patrick Mochel's sysfs code.
17 * sysfs is Copyright (c) 2001-3 Patrick Mochel
19 * 2003-10-10 Written by Simon Derr.
20 * 2003-10-22 Updates by Stephen Hemminger.
21 * 2004 May-July Rework by Paul Jackson.
22 * ---------------------------------------------------
24 * This file is subject to the terms and conditions of the GNU General Public
25 * License. See the file COPYING in the main directory of the Linux
26 * distribution for more details.
29 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
31 #include <linux/cgroup.h>
32 #include <linux/cred.h>
33 #include <linux/ctype.h>
34 #include <linux/errno.h>
35 #include <linux/init_task.h>
36 #include <linux/kernel.h>
37 #include <linux/list.h>
38 #include <linux/magic.h>
39 #include <linux/mm.h>
40 #include <linux/mutex.h>
41 #include <linux/mount.h>
42 #include <linux/pagemap.h>
43 #include <linux/proc_fs.h>
44 #include <linux/rcupdate.h>
45 #include <linux/sched.h>
46 #include <linux/slab.h>
47 #include <linux/spinlock.h>
48 #include <linux/rwsem.h>
49 #include <linux/string.h>
50 #include <linux/sort.h>
51 #include <linux/kmod.h>
52 #include <linux/delayacct.h>
53 #include <linux/cgroupstats.h>
54 #include <linux/hashtable.h>
55 #include <linux/pid_namespace.h>
56 #include <linux/idr.h>
57 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
58 #include <linux/kthread.h>
59 #include <linux/delay.h>
61 #include <linux/atomic.h>
64 * pidlists linger the following amount before being destroyed. The goal
65 * is avoiding frequent destruction in the middle of consecutive read calls
66 * Expiring in the middle is a performance problem not a correctness one.
67 * 1 sec should be enough.
69 #define CGROUP_PIDLIST_DESTROY_DELAY HZ
71 #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
72 MAX_CFTYPE_NAME + 2)
75 * cgroup_mutex is the master lock. Any modification to cgroup or its
76 * hierarchy must be performed while holding it.
78 * css_set_rwsem protects task->cgroups pointer, the list of css_set
79 * objects, and the chain of tasks off each css_set.
81 * These locks are exported if CONFIG_PROVE_RCU so that accessors in
82 * cgroup.h can use them for lockdep annotations.
84 #ifdef CONFIG_PROVE_RCU
85 DEFINE_MUTEX(cgroup_mutex);
86 DECLARE_RWSEM(css_set_rwsem);
87 EXPORT_SYMBOL_GPL(cgroup_mutex);
88 EXPORT_SYMBOL_GPL(css_set_rwsem);
89 #else
90 static DEFINE_MUTEX(cgroup_mutex);
91 static DECLARE_RWSEM(css_set_rwsem);
92 #endif
95 * Protects cgroup_idr and css_idr so that IDs can be released without
96 * grabbing cgroup_mutex.
98 static DEFINE_SPINLOCK(cgroup_idr_lock);
101 * Protects cgroup_subsys->release_agent_path. Modifying it also requires
102 * cgroup_mutex. Reading requires either cgroup_mutex or this spinlock.
104 static DEFINE_SPINLOCK(release_agent_path_lock);
106 #define cgroup_assert_mutex_or_rcu_locked() \
107 rcu_lockdep_assert(rcu_read_lock_held() || \
108 lockdep_is_held(&cgroup_mutex), \
109 "cgroup_mutex or RCU read lock required");
112 * cgroup destruction makes heavy use of work items and there can be a lot
113 * of concurrent destructions. Use a separate workqueue so that cgroup
114 * destruction work items don't end up filling up max_active of system_wq
115 * which may lead to deadlock.
117 static struct workqueue_struct *cgroup_destroy_wq;
120 * pidlist destructions need to be flushed on cgroup destruction. Use a
121 * separate workqueue as flush domain.
123 static struct workqueue_struct *cgroup_pidlist_destroy_wq;
125 /* generate an array of cgroup subsystem pointers */
126 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
127 static struct cgroup_subsys *cgroup_subsys[] = {
128 #include <linux/cgroup_subsys.h>
130 #undef SUBSYS
132 /* array of cgroup subsystem names */
133 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
134 static const char *cgroup_subsys_name[] = {
135 #include <linux/cgroup_subsys.h>
137 #undef SUBSYS
140 * The default hierarchy, reserved for the subsystems that are otherwise
141 * unattached - it never has more than a single cgroup, and all tasks are
142 * part of that cgroup.
144 struct cgroup_root cgrp_dfl_root;
147 * The default hierarchy always exists but is hidden until mounted for the
148 * first time. This is for backward compatibility.
150 static bool cgrp_dfl_root_visible;
153 * Set by the boot param of the same name and makes subsystems with NULL
154 * ->dfl_files to use ->legacy_files on the default hierarchy.
156 static bool cgroup_legacy_files_on_dfl;
158 /* some controllers are not supported in the default hierarchy */
159 static unsigned long cgrp_dfl_root_inhibit_ss_mask;
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 csses. It guarantees
171 * cgroups with bigger numbers are newer than those with smaller numbers.
172 * Also, as csses are always appended to the parent's ->children list, it
173 * guarantees that sibling csses are always sorted in the ascending serial
174 * number order on the list. Protected by cgroup_mutex.
176 static u64 css_serial_nr_next = 1;
179 * These bitmask flags indicate whether tasks in the fork and exit paths have
180 * fork/exit handlers to call. This avoids us having to do extra work in the
181 * fork/exit path to check which subsystems have fork/exit callbacks.
183 static unsigned long have_fork_callback __read_mostly;
184 static unsigned long have_exit_callback __read_mostly;
186 static struct cftype cgroup_dfl_base_files[];
187 static struct cftype cgroup_legacy_base_files[];
189 static int rebind_subsystems(struct cgroup_root *dst_root,
190 unsigned long ss_mask);
191 static int cgroup_destroy_locked(struct cgroup *cgrp);
192 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss,
193 bool visible);
194 static void css_release(struct percpu_ref *ref);
195 static void kill_css(struct cgroup_subsys_state *css);
196 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
197 bool is_add);
199 /* IDR wrappers which synchronize using cgroup_idr_lock */
200 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
201 gfp_t gfp_mask)
203 int ret;
205 idr_preload(gfp_mask);
206 spin_lock_bh(&cgroup_idr_lock);
207 ret = idr_alloc(idr, ptr, start, end, gfp_mask);
208 spin_unlock_bh(&cgroup_idr_lock);
209 idr_preload_end();
210 return ret;
213 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
215 void *ret;
217 spin_lock_bh(&cgroup_idr_lock);
218 ret = idr_replace(idr, ptr, id);
219 spin_unlock_bh(&cgroup_idr_lock);
220 return ret;
223 static void cgroup_idr_remove(struct idr *idr, int id)
225 spin_lock_bh(&cgroup_idr_lock);
226 idr_remove(idr, id);
227 spin_unlock_bh(&cgroup_idr_lock);
230 static struct cgroup *cgroup_parent(struct cgroup *cgrp)
232 struct cgroup_subsys_state *parent_css = cgrp->self.parent;
234 if (parent_css)
235 return container_of(parent_css, struct cgroup, self);
236 return NULL;
240 * cgroup_css - obtain a cgroup's css for the specified subsystem
241 * @cgrp: the cgroup of interest
242 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
244 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
245 * function must be called either under cgroup_mutex or rcu_read_lock() and
246 * the caller is responsible for pinning the returned css if it wants to
247 * keep accessing it outside the said locks. This function may return
248 * %NULL if @cgrp doesn't have @subsys_id enabled.
250 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
251 struct cgroup_subsys *ss)
253 if (ss)
254 return rcu_dereference_check(cgrp->subsys[ss->id],
255 lockdep_is_held(&cgroup_mutex));
256 else
257 return &cgrp->self;
261 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
262 * @cgrp: the cgroup of interest
263 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
265 * Similar to cgroup_css() but returns the effective css, which is defined
266 * as the matching css of the nearest ancestor including self which has @ss
267 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
268 * function is guaranteed to return non-NULL css.
270 static struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
271 struct cgroup_subsys *ss)
273 lockdep_assert_held(&cgroup_mutex);
275 if (!ss)
276 return &cgrp->self;
278 if (!(cgrp->root->subsys_mask & (1 << ss->id)))
279 return NULL;
282 * This function is used while updating css associations and thus
283 * can't test the csses directly. Use ->child_subsys_mask.
285 while (cgroup_parent(cgrp) &&
286 !(cgroup_parent(cgrp)->child_subsys_mask & (1 << ss->id)))
287 cgrp = cgroup_parent(cgrp);
289 return cgroup_css(cgrp, ss);
293 * cgroup_get_e_css - get a cgroup's effective css for the specified subsystem
294 * @cgrp: the cgroup of interest
295 * @ss: the subsystem of interest
297 * Find and get the effective css of @cgrp for @ss. The effective css is
298 * defined as the matching css of the nearest ancestor including self which
299 * has @ss enabled. If @ss is not mounted on the hierarchy @cgrp is on,
300 * the root css is returned, so this function always returns a valid css.
301 * The returned css must be put using css_put().
303 struct cgroup_subsys_state *cgroup_get_e_css(struct cgroup *cgrp,
304 struct cgroup_subsys *ss)
306 struct cgroup_subsys_state *css;
308 rcu_read_lock();
310 do {
311 css = cgroup_css(cgrp, ss);
313 if (css && css_tryget_online(css))
314 goto out_unlock;
315 cgrp = cgroup_parent(cgrp);
316 } while (cgrp);
318 css = init_css_set.subsys[ss->id];
319 css_get(css);
320 out_unlock:
321 rcu_read_unlock();
322 return css;
325 /* convenient tests for these bits */
326 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
328 return !(cgrp->self.flags & CSS_ONLINE);
331 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
333 struct cgroup *cgrp = of->kn->parent->priv;
334 struct cftype *cft = of_cft(of);
337 * This is open and unprotected implementation of cgroup_css().
338 * seq_css() is only called from a kernfs file operation which has
339 * an active reference on the file. Because all the subsystem
340 * files are drained before a css is disassociated with a cgroup,
341 * the matching css from the cgroup's subsys table is guaranteed to
342 * be and stay valid until the enclosing operation is complete.
344 if (cft->ss)
345 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
346 else
347 return &cgrp->self;
349 EXPORT_SYMBOL_GPL(of_css);
352 * cgroup_is_descendant - test ancestry
353 * @cgrp: the cgroup to be tested
354 * @ancestor: possible ancestor of @cgrp
356 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
357 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
358 * and @ancestor are accessible.
360 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
362 while (cgrp) {
363 if (cgrp == ancestor)
364 return true;
365 cgrp = cgroup_parent(cgrp);
367 return false;
370 static int notify_on_release(const struct cgroup *cgrp)
372 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
376 * for_each_css - iterate all css's of a cgroup
377 * @css: the iteration cursor
378 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
379 * @cgrp: the target cgroup to iterate css's of
381 * Should be called under cgroup_[tree_]mutex.
383 #define for_each_css(css, ssid, cgrp) \
384 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
385 if (!((css) = rcu_dereference_check( \
386 (cgrp)->subsys[(ssid)], \
387 lockdep_is_held(&cgroup_mutex)))) { } \
388 else
391 * for_each_e_css - iterate all effective css's of a cgroup
392 * @css: the iteration cursor
393 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
394 * @cgrp: the target cgroup to iterate css's of
396 * Should be called under cgroup_[tree_]mutex.
398 #define for_each_e_css(css, ssid, cgrp) \
399 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
400 if (!((css) = cgroup_e_css(cgrp, cgroup_subsys[(ssid)]))) \
402 else
405 * for_each_subsys - iterate all enabled cgroup subsystems
406 * @ss: the iteration cursor
407 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
409 #define for_each_subsys(ss, ssid) \
410 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT && \
411 (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
414 * for_each_subsys_which - filter for_each_subsys with a bitmask
415 * @ss: the iteration cursor
416 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
417 * @ss_maskp: a pointer to the bitmask
419 * The block will only run for cases where the ssid-th bit (1 << ssid) of
420 * mask is set to 1.
422 #define for_each_subsys_which(ss, ssid, ss_maskp) \
423 if (!CGROUP_SUBSYS_COUNT) /* to avoid spurious gcc warning */ \
424 (ssid) = 0; \
425 else \
426 for_each_set_bit(ssid, ss_maskp, CGROUP_SUBSYS_COUNT) \
427 if (((ss) = cgroup_subsys[ssid]) && false) \
428 break; \
429 else
431 /* iterate across the hierarchies */
432 #define for_each_root(root) \
433 list_for_each_entry((root), &cgroup_roots, root_list)
435 /* iterate over child cgrps, lock should be held throughout iteration */
436 #define cgroup_for_each_live_child(child, cgrp) \
437 list_for_each_entry((child), &(cgrp)->self.children, self.sibling) \
438 if (({ lockdep_assert_held(&cgroup_mutex); \
439 cgroup_is_dead(child); })) \
441 else
443 static void cgroup_release_agent(struct work_struct *work);
444 static void check_for_release(struct cgroup *cgrp);
447 * A cgroup can be associated with multiple css_sets as different tasks may
448 * belong to different cgroups on different hierarchies. In the other
449 * direction, a css_set is naturally associated with multiple cgroups.
450 * This M:N relationship is represented by the following link structure
451 * which exists for each association and allows traversing the associations
452 * from both sides.
454 struct cgrp_cset_link {
455 /* the cgroup and css_set this link associates */
456 struct cgroup *cgrp;
457 struct css_set *cset;
459 /* list of cgrp_cset_links anchored at cgrp->cset_links */
460 struct list_head cset_link;
462 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
463 struct list_head cgrp_link;
467 * The default css_set - used by init and its children prior to any
468 * hierarchies being mounted. It contains a pointer to the root state
469 * for each subsystem. Also used to anchor the list of css_sets. Not
470 * reference-counted, to improve performance when child cgroups
471 * haven't been created.
473 struct css_set init_css_set = {
474 .refcount = ATOMIC_INIT(1),
475 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
476 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
477 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
478 .mg_preload_node = LIST_HEAD_INIT(init_css_set.mg_preload_node),
479 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
482 static int css_set_count = 1; /* 1 for init_css_set */
485 * cgroup_update_populated - updated populated count of a cgroup
486 * @cgrp: the target cgroup
487 * @populated: inc or dec populated count
489 * @cgrp is either getting the first task (css_set) or losing the last.
490 * Update @cgrp->populated_cnt accordingly. The count is propagated
491 * towards root so that a given cgroup's populated_cnt is zero iff the
492 * cgroup and all its descendants are empty.
494 * @cgrp's interface file "cgroup.populated" is zero if
495 * @cgrp->populated_cnt is zero and 1 otherwise. When @cgrp->populated_cnt
496 * changes from or to zero, userland is notified that the content of the
497 * interface file has changed. This can be used to detect when @cgrp and
498 * its descendants become populated or empty.
500 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
502 lockdep_assert_held(&css_set_rwsem);
504 do {
505 bool trigger;
507 if (populated)
508 trigger = !cgrp->populated_cnt++;
509 else
510 trigger = !--cgrp->populated_cnt;
512 if (!trigger)
513 break;
515 if (cgrp->populated_kn)
516 kernfs_notify(cgrp->populated_kn);
517 cgrp = cgroup_parent(cgrp);
518 } while (cgrp);
522 * hash table for cgroup groups. This improves the performance to find
523 * an existing css_set. This hash doesn't (currently) take into
524 * account cgroups in empty hierarchies.
526 #define CSS_SET_HASH_BITS 7
527 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
529 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
531 unsigned long key = 0UL;
532 struct cgroup_subsys *ss;
533 int i;
535 for_each_subsys(ss, i)
536 key += (unsigned long)css[i];
537 key = (key >> 16) ^ key;
539 return key;
542 static void put_css_set_locked(struct css_set *cset)
544 struct cgrp_cset_link *link, *tmp_link;
545 struct cgroup_subsys *ss;
546 int ssid;
548 lockdep_assert_held(&css_set_rwsem);
550 if (!atomic_dec_and_test(&cset->refcount))
551 return;
553 /* This css_set is dead. unlink it and release cgroup refcounts */
554 for_each_subsys(ss, ssid)
555 list_del(&cset->e_cset_node[ssid]);
556 hash_del(&cset->hlist);
557 css_set_count--;
559 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
560 struct cgroup *cgrp = link->cgrp;
562 list_del(&link->cset_link);
563 list_del(&link->cgrp_link);
565 /* @cgrp can't go away while we're holding css_set_rwsem */
566 if (list_empty(&cgrp->cset_links)) {
567 cgroup_update_populated(cgrp, false);
568 check_for_release(cgrp);
571 kfree(link);
574 kfree_rcu(cset, rcu_head);
577 static void put_css_set(struct css_set *cset)
580 * Ensure that the refcount doesn't hit zero while any readers
581 * can see it. Similar to atomic_dec_and_lock(), but for an
582 * rwlock
584 if (atomic_add_unless(&cset->refcount, -1, 1))
585 return;
587 down_write(&css_set_rwsem);
588 put_css_set_locked(cset);
589 up_write(&css_set_rwsem);
593 * refcounted get/put for css_set objects
595 static inline void get_css_set(struct css_set *cset)
597 atomic_inc(&cset->refcount);
601 * compare_css_sets - helper function for find_existing_css_set().
602 * @cset: candidate css_set being tested
603 * @old_cset: existing css_set for a task
604 * @new_cgrp: cgroup that's being entered by the task
605 * @template: desired set of css pointers in css_set (pre-calculated)
607 * Returns true if "cset" matches "old_cset" except for the hierarchy
608 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
610 static bool compare_css_sets(struct css_set *cset,
611 struct css_set *old_cset,
612 struct cgroup *new_cgrp,
613 struct cgroup_subsys_state *template[])
615 struct list_head *l1, *l2;
618 * On the default hierarchy, there can be csets which are
619 * associated with the same set of cgroups but different csses.
620 * Let's first ensure that csses match.
622 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
623 return false;
626 * Compare cgroup pointers in order to distinguish between
627 * different cgroups in hierarchies. As different cgroups may
628 * share the same effective css, this comparison is always
629 * necessary.
631 l1 = &cset->cgrp_links;
632 l2 = &old_cset->cgrp_links;
633 while (1) {
634 struct cgrp_cset_link *link1, *link2;
635 struct cgroup *cgrp1, *cgrp2;
637 l1 = l1->next;
638 l2 = l2->next;
639 /* See if we reached the end - both lists are equal length. */
640 if (l1 == &cset->cgrp_links) {
641 BUG_ON(l2 != &old_cset->cgrp_links);
642 break;
643 } else {
644 BUG_ON(l2 == &old_cset->cgrp_links);
646 /* Locate the cgroups associated with these links. */
647 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
648 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
649 cgrp1 = link1->cgrp;
650 cgrp2 = link2->cgrp;
651 /* Hierarchies should be linked in the same order. */
652 BUG_ON(cgrp1->root != cgrp2->root);
655 * If this hierarchy is the hierarchy of the cgroup
656 * that's changing, then we need to check that this
657 * css_set points to the new cgroup; if it's any other
658 * hierarchy, then this css_set should point to the
659 * same cgroup as the old css_set.
661 if (cgrp1->root == new_cgrp->root) {
662 if (cgrp1 != new_cgrp)
663 return false;
664 } else {
665 if (cgrp1 != cgrp2)
666 return false;
669 return true;
673 * find_existing_css_set - init css array and find the matching css_set
674 * @old_cset: the css_set that we're using before the cgroup transition
675 * @cgrp: the cgroup that we're moving into
676 * @template: out param for the new set of csses, should be clear on entry
678 static struct css_set *find_existing_css_set(struct css_set *old_cset,
679 struct cgroup *cgrp,
680 struct cgroup_subsys_state *template[])
682 struct cgroup_root *root = cgrp->root;
683 struct cgroup_subsys *ss;
684 struct css_set *cset;
685 unsigned long key;
686 int i;
689 * Build the set of subsystem state objects that we want to see in the
690 * new css_set. while subsystems can change globally, the entries here
691 * won't change, so no need for locking.
693 for_each_subsys(ss, i) {
694 if (root->subsys_mask & (1UL << i)) {
696 * @ss is in this hierarchy, so we want the
697 * effective css from @cgrp.
699 template[i] = cgroup_e_css(cgrp, ss);
700 } else {
702 * @ss is not in this hierarchy, so we don't want
703 * to change the css.
705 template[i] = old_cset->subsys[i];
709 key = css_set_hash(template);
710 hash_for_each_possible(css_set_table, cset, hlist, key) {
711 if (!compare_css_sets(cset, old_cset, cgrp, template))
712 continue;
714 /* This css_set matches what we need */
715 return cset;
718 /* No existing cgroup group matched */
719 return NULL;
722 static void free_cgrp_cset_links(struct list_head *links_to_free)
724 struct cgrp_cset_link *link, *tmp_link;
726 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
727 list_del(&link->cset_link);
728 kfree(link);
733 * allocate_cgrp_cset_links - allocate cgrp_cset_links
734 * @count: the number of links to allocate
735 * @tmp_links: list_head the allocated links are put on
737 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
738 * through ->cset_link. Returns 0 on success or -errno.
740 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
742 struct cgrp_cset_link *link;
743 int i;
745 INIT_LIST_HEAD(tmp_links);
747 for (i = 0; i < count; i++) {
748 link = kzalloc(sizeof(*link), GFP_KERNEL);
749 if (!link) {
750 free_cgrp_cset_links(tmp_links);
751 return -ENOMEM;
753 list_add(&link->cset_link, tmp_links);
755 return 0;
759 * link_css_set - a helper function to link a css_set to a cgroup
760 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
761 * @cset: the css_set to be linked
762 * @cgrp: the destination cgroup
764 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
765 struct cgroup *cgrp)
767 struct cgrp_cset_link *link;
769 BUG_ON(list_empty(tmp_links));
771 if (cgroup_on_dfl(cgrp))
772 cset->dfl_cgrp = cgrp;
774 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
775 link->cset = cset;
776 link->cgrp = cgrp;
778 if (list_empty(&cgrp->cset_links))
779 cgroup_update_populated(cgrp, true);
780 list_move(&link->cset_link, &cgrp->cset_links);
783 * Always add links to the tail of the list so that the list
784 * is sorted by order of hierarchy creation
786 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
790 * find_css_set - return a new css_set with one cgroup updated
791 * @old_cset: the baseline css_set
792 * @cgrp: the cgroup to be updated
794 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
795 * substituted into the appropriate hierarchy.
797 static struct css_set *find_css_set(struct css_set *old_cset,
798 struct cgroup *cgrp)
800 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
801 struct css_set *cset;
802 struct list_head tmp_links;
803 struct cgrp_cset_link *link;
804 struct cgroup_subsys *ss;
805 unsigned long key;
806 int ssid;
808 lockdep_assert_held(&cgroup_mutex);
810 /* First see if we already have a cgroup group that matches
811 * the desired set */
812 down_read(&css_set_rwsem);
813 cset = find_existing_css_set(old_cset, cgrp, template);
814 if (cset)
815 get_css_set(cset);
816 up_read(&css_set_rwsem);
818 if (cset)
819 return cset;
821 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
822 if (!cset)
823 return NULL;
825 /* Allocate all the cgrp_cset_link objects that we'll need */
826 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
827 kfree(cset);
828 return NULL;
831 atomic_set(&cset->refcount, 1);
832 INIT_LIST_HEAD(&cset->cgrp_links);
833 INIT_LIST_HEAD(&cset->tasks);
834 INIT_LIST_HEAD(&cset->mg_tasks);
835 INIT_LIST_HEAD(&cset->mg_preload_node);
836 INIT_LIST_HEAD(&cset->mg_node);
837 INIT_HLIST_NODE(&cset->hlist);
839 /* Copy the set of subsystem state objects generated in
840 * find_existing_css_set() */
841 memcpy(cset->subsys, template, sizeof(cset->subsys));
843 down_write(&css_set_rwsem);
844 /* Add reference counts and links from the new css_set. */
845 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
846 struct cgroup *c = link->cgrp;
848 if (c->root == cgrp->root)
849 c = cgrp;
850 link_css_set(&tmp_links, cset, c);
853 BUG_ON(!list_empty(&tmp_links));
855 css_set_count++;
857 /* Add @cset to the hash table */
858 key = css_set_hash(cset->subsys);
859 hash_add(css_set_table, &cset->hlist, key);
861 for_each_subsys(ss, ssid)
862 list_add_tail(&cset->e_cset_node[ssid],
863 &cset->subsys[ssid]->cgroup->e_csets[ssid]);
865 up_write(&css_set_rwsem);
867 return cset;
870 void cgroup_threadgroup_change_begin(struct task_struct *tsk)
872 down_read(&tsk->signal->group_rwsem);
875 void cgroup_threadgroup_change_end(struct task_struct *tsk)
877 up_read(&tsk->signal->group_rwsem);
881 * threadgroup_lock - lock threadgroup
882 * @tsk: member task of the threadgroup to lock
884 * Lock the threadgroup @tsk belongs to. No new task is allowed to enter
885 * and member tasks aren't allowed to exit (as indicated by PF_EXITING) or
886 * change ->group_leader/pid. This is useful for cases where the threadgroup
887 * needs to stay stable across blockable operations.
889 * fork and exit explicitly call threadgroup_change_{begin|end}() for
890 * synchronization. While held, no new task will be added to threadgroup
891 * and no existing live task will have its PF_EXITING set.
893 * de_thread() does threadgroup_change_{begin|end}() when a non-leader
894 * sub-thread becomes a new leader.
896 static void threadgroup_lock(struct task_struct *tsk)
898 down_write(&tsk->signal->group_rwsem);
902 * threadgroup_unlock - unlock threadgroup
903 * @tsk: member task of the threadgroup to unlock
905 * Reverse threadgroup_lock().
907 static inline void threadgroup_unlock(struct task_struct *tsk)
909 up_write(&tsk->signal->group_rwsem);
912 static struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
914 struct cgroup *root_cgrp = kf_root->kn->priv;
916 return root_cgrp->root;
919 static int cgroup_init_root_id(struct cgroup_root *root)
921 int id;
923 lockdep_assert_held(&cgroup_mutex);
925 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
926 if (id < 0)
927 return id;
929 root->hierarchy_id = id;
930 return 0;
933 static void cgroup_exit_root_id(struct cgroup_root *root)
935 lockdep_assert_held(&cgroup_mutex);
937 if (root->hierarchy_id) {
938 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
939 root->hierarchy_id = 0;
943 static void cgroup_free_root(struct cgroup_root *root)
945 if (root) {
946 /* hierarchy ID should already have been released */
947 WARN_ON_ONCE(root->hierarchy_id);
949 idr_destroy(&root->cgroup_idr);
950 kfree(root);
954 static void cgroup_destroy_root(struct cgroup_root *root)
956 struct cgroup *cgrp = &root->cgrp;
957 struct cgrp_cset_link *link, *tmp_link;
959 mutex_lock(&cgroup_mutex);
961 BUG_ON(atomic_read(&root->nr_cgrps));
962 BUG_ON(!list_empty(&cgrp->self.children));
964 /* Rebind all subsystems back to the default hierarchy */
965 rebind_subsystems(&cgrp_dfl_root, root->subsys_mask);
968 * Release all the links from cset_links to this hierarchy's
969 * root cgroup
971 down_write(&css_set_rwsem);
973 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
974 list_del(&link->cset_link);
975 list_del(&link->cgrp_link);
976 kfree(link);
978 up_write(&css_set_rwsem);
980 if (!list_empty(&root->root_list)) {
981 list_del(&root->root_list);
982 cgroup_root_count--;
985 cgroup_exit_root_id(root);
987 mutex_unlock(&cgroup_mutex);
989 kernfs_destroy_root(root->kf_root);
990 cgroup_free_root(root);
993 /* look up cgroup associated with given css_set on the specified hierarchy */
994 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
995 struct cgroup_root *root)
997 struct cgroup *res = NULL;
999 lockdep_assert_held(&cgroup_mutex);
1000 lockdep_assert_held(&css_set_rwsem);
1002 if (cset == &init_css_set) {
1003 res = &root->cgrp;
1004 } else {
1005 struct cgrp_cset_link *link;
1007 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1008 struct cgroup *c = link->cgrp;
1010 if (c->root == root) {
1011 res = c;
1012 break;
1017 BUG_ON(!res);
1018 return res;
1022 * Return the cgroup for "task" from the given hierarchy. Must be
1023 * called with cgroup_mutex and css_set_rwsem held.
1025 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
1026 struct cgroup_root *root)
1029 * No need to lock the task - since we hold cgroup_mutex the
1030 * task can't change groups, so the only thing that can happen
1031 * is that it exits and its css is set back to init_css_set.
1033 return cset_cgroup_from_root(task_css_set(task), root);
1037 * A task must hold cgroup_mutex to modify cgroups.
1039 * Any task can increment and decrement the count field without lock.
1040 * So in general, code holding cgroup_mutex can't rely on the count
1041 * field not changing. However, if the count goes to zero, then only
1042 * cgroup_attach_task() can increment it again. Because a count of zero
1043 * means that no tasks are currently attached, therefore there is no
1044 * way a task attached to that cgroup can fork (the other way to
1045 * increment the count). So code holding cgroup_mutex can safely
1046 * assume that if the count is zero, it will stay zero. Similarly, if
1047 * a task holds cgroup_mutex on a cgroup with zero count, it
1048 * knows that the cgroup won't be removed, as cgroup_rmdir()
1049 * needs that mutex.
1051 * A cgroup can only be deleted if both its 'count' of using tasks
1052 * is zero, and its list of 'children' cgroups is empty. Since all
1053 * tasks in the system use _some_ cgroup, and since there is always at
1054 * least one task in the system (init, pid == 1), therefore, root cgroup
1055 * always has either children cgroups and/or using tasks. So we don't
1056 * need a special hack to ensure that root cgroup cannot be deleted.
1058 * P.S. One more locking exception. RCU is used to guard the
1059 * update of a tasks cgroup pointer by cgroup_attach_task()
1062 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask);
1063 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
1064 static const struct file_operations proc_cgroupstats_operations;
1066 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
1067 char *buf)
1069 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
1070 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
1071 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
1072 cft->ss->name, cft->name);
1073 else
1074 strncpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
1075 return buf;
1079 * cgroup_file_mode - deduce file mode of a control file
1080 * @cft: the control file in question
1082 * returns cft->mode if ->mode is not 0
1083 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
1084 * returns S_IRUGO if it has only a read handler
1085 * returns S_IWUSR if it has only a write hander
1087 static umode_t cgroup_file_mode(const struct cftype *cft)
1089 umode_t mode = 0;
1091 if (cft->mode)
1092 return cft->mode;
1094 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1095 mode |= S_IRUGO;
1097 if (cft->write_u64 || cft->write_s64 || cft->write)
1098 mode |= S_IWUSR;
1100 return mode;
1103 static void cgroup_get(struct cgroup *cgrp)
1105 WARN_ON_ONCE(cgroup_is_dead(cgrp));
1106 css_get(&cgrp->self);
1109 static bool cgroup_tryget(struct cgroup *cgrp)
1111 return css_tryget(&cgrp->self);
1114 static void cgroup_put(struct cgroup *cgrp)
1116 css_put(&cgrp->self);
1120 * cgroup_calc_child_subsys_mask - calculate child_subsys_mask
1121 * @cgrp: the target cgroup
1122 * @subtree_control: the new subtree_control mask to consider
1124 * On the default hierarchy, a subsystem may request other subsystems to be
1125 * enabled together through its ->depends_on mask. In such cases, more
1126 * subsystems than specified in "cgroup.subtree_control" may be enabled.
1128 * This function calculates which subsystems need to be enabled if
1129 * @subtree_control is to be applied to @cgrp. The returned mask is always
1130 * a superset of @subtree_control and follows the usual hierarchy rules.
1132 static unsigned long cgroup_calc_child_subsys_mask(struct cgroup *cgrp,
1133 unsigned long subtree_control)
1135 struct cgroup *parent = cgroup_parent(cgrp);
1136 unsigned long cur_ss_mask = subtree_control;
1137 struct cgroup_subsys *ss;
1138 int ssid;
1140 lockdep_assert_held(&cgroup_mutex);
1142 if (!cgroup_on_dfl(cgrp))
1143 return cur_ss_mask;
1145 while (true) {
1146 unsigned long new_ss_mask = cur_ss_mask;
1148 for_each_subsys_which(ss, ssid, &cur_ss_mask)
1149 new_ss_mask |= ss->depends_on;
1152 * Mask out subsystems which aren't available. This can
1153 * happen only if some depended-upon subsystems were bound
1154 * to non-default hierarchies.
1156 if (parent)
1157 new_ss_mask &= parent->child_subsys_mask;
1158 else
1159 new_ss_mask &= cgrp->root->subsys_mask;
1161 if (new_ss_mask == cur_ss_mask)
1162 break;
1163 cur_ss_mask = new_ss_mask;
1166 return cur_ss_mask;
1170 * cgroup_refresh_child_subsys_mask - update child_subsys_mask
1171 * @cgrp: the target cgroup
1173 * Update @cgrp->child_subsys_mask according to the current
1174 * @cgrp->subtree_control using cgroup_calc_child_subsys_mask().
1176 static void cgroup_refresh_child_subsys_mask(struct cgroup *cgrp)
1178 cgrp->child_subsys_mask =
1179 cgroup_calc_child_subsys_mask(cgrp, cgrp->subtree_control);
1183 * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
1184 * @kn: the kernfs_node being serviced
1186 * This helper undoes cgroup_kn_lock_live() and should be invoked before
1187 * the method finishes if locking succeeded. Note that once this function
1188 * returns the cgroup returned by cgroup_kn_lock_live() may become
1189 * inaccessible any time. If the caller intends to continue to access the
1190 * cgroup, it should pin it before invoking this function.
1192 static void cgroup_kn_unlock(struct kernfs_node *kn)
1194 struct cgroup *cgrp;
1196 if (kernfs_type(kn) == KERNFS_DIR)
1197 cgrp = kn->priv;
1198 else
1199 cgrp = kn->parent->priv;
1201 mutex_unlock(&cgroup_mutex);
1203 kernfs_unbreak_active_protection(kn);
1204 cgroup_put(cgrp);
1208 * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
1209 * @kn: the kernfs_node being serviced
1211 * This helper is to be used by a cgroup kernfs method currently servicing
1212 * @kn. It breaks the active protection, performs cgroup locking and
1213 * verifies that the associated cgroup is alive. Returns the cgroup if
1214 * alive; otherwise, %NULL. A successful return should be undone by a
1215 * matching cgroup_kn_unlock() invocation.
1217 * Any cgroup kernfs method implementation which requires locking the
1218 * associated cgroup should use this helper. It avoids nesting cgroup
1219 * locking under kernfs active protection and allows all kernfs operations
1220 * including self-removal.
1222 static struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn)
1224 struct cgroup *cgrp;
1226 if (kernfs_type(kn) == KERNFS_DIR)
1227 cgrp = kn->priv;
1228 else
1229 cgrp = kn->parent->priv;
1232 * We're gonna grab cgroup_mutex which nests outside kernfs
1233 * active_ref. cgroup liveliness check alone provides enough
1234 * protection against removal. Ensure @cgrp stays accessible and
1235 * break the active_ref protection.
1237 if (!cgroup_tryget(cgrp))
1238 return NULL;
1239 kernfs_break_active_protection(kn);
1241 mutex_lock(&cgroup_mutex);
1243 if (!cgroup_is_dead(cgrp))
1244 return cgrp;
1246 cgroup_kn_unlock(kn);
1247 return NULL;
1250 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1252 char name[CGROUP_FILE_NAME_MAX];
1254 lockdep_assert_held(&cgroup_mutex);
1255 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1259 * cgroup_clear_dir - remove subsys files in a cgroup directory
1260 * @cgrp: target cgroup
1261 * @subsys_mask: mask of the subsystem ids whose files should be removed
1263 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned long subsys_mask)
1265 struct cgroup_subsys *ss;
1266 int i;
1268 for_each_subsys(ss, i) {
1269 struct cftype *cfts;
1271 if (!(subsys_mask & (1 << i)))
1272 continue;
1273 list_for_each_entry(cfts, &ss->cfts, node)
1274 cgroup_addrm_files(cgrp, cfts, false);
1278 static int rebind_subsystems(struct cgroup_root *dst_root,
1279 unsigned long ss_mask)
1281 struct cgroup_subsys *ss;
1282 unsigned long tmp_ss_mask;
1283 int ssid, i, ret;
1285 lockdep_assert_held(&cgroup_mutex);
1287 for_each_subsys_which(ss, ssid, &ss_mask) {
1288 /* if @ss has non-root csses attached to it, can't move */
1289 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)))
1290 return -EBUSY;
1292 /* can't move between two non-dummy roots either */
1293 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1294 return -EBUSY;
1297 /* skip creating root files on dfl_root for inhibited subsystems */
1298 tmp_ss_mask = ss_mask;
1299 if (dst_root == &cgrp_dfl_root)
1300 tmp_ss_mask &= ~cgrp_dfl_root_inhibit_ss_mask;
1302 ret = cgroup_populate_dir(&dst_root->cgrp, tmp_ss_mask);
1303 if (ret) {
1304 if (dst_root != &cgrp_dfl_root)
1305 return ret;
1308 * Rebinding back to the default root is not allowed to
1309 * fail. Using both default and non-default roots should
1310 * be rare. Moving subsystems back and forth even more so.
1311 * Just warn about it and continue.
1313 if (cgrp_dfl_root_visible) {
1314 pr_warn("failed to create files (%d) while rebinding 0x%lx to default root\n",
1315 ret, ss_mask);
1316 pr_warn("you may retry by moving them to a different hierarchy and unbinding\n");
1321 * Nothing can fail from this point on. Remove files for the
1322 * removed subsystems and rebind each subsystem.
1324 for_each_subsys_which(ss, ssid, &ss_mask)
1325 cgroup_clear_dir(&ss->root->cgrp, 1 << ssid);
1327 for_each_subsys_which(ss, ssid, &ss_mask) {
1328 struct cgroup_root *src_root;
1329 struct cgroup_subsys_state *css;
1330 struct css_set *cset;
1332 src_root = ss->root;
1333 css = cgroup_css(&src_root->cgrp, ss);
1335 WARN_ON(!css || cgroup_css(&dst_root->cgrp, ss));
1337 RCU_INIT_POINTER(src_root->cgrp.subsys[ssid], NULL);
1338 rcu_assign_pointer(dst_root->cgrp.subsys[ssid], css);
1339 ss->root = dst_root;
1340 css->cgroup = &dst_root->cgrp;
1342 down_write(&css_set_rwsem);
1343 hash_for_each(css_set_table, i, cset, hlist)
1344 list_move_tail(&cset->e_cset_node[ss->id],
1345 &dst_root->cgrp.e_csets[ss->id]);
1346 up_write(&css_set_rwsem);
1348 src_root->subsys_mask &= ~(1 << ssid);
1349 src_root->cgrp.subtree_control &= ~(1 << ssid);
1350 cgroup_refresh_child_subsys_mask(&src_root->cgrp);
1352 /* default hierarchy doesn't enable controllers by default */
1353 dst_root->subsys_mask |= 1 << ssid;
1354 if (dst_root != &cgrp_dfl_root) {
1355 dst_root->cgrp.subtree_control |= 1 << ssid;
1356 cgroup_refresh_child_subsys_mask(&dst_root->cgrp);
1359 if (ss->bind)
1360 ss->bind(css);
1363 kernfs_activate(dst_root->cgrp.kn);
1364 return 0;
1367 static int cgroup_show_options(struct seq_file *seq,
1368 struct kernfs_root *kf_root)
1370 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1371 struct cgroup_subsys *ss;
1372 int ssid;
1374 for_each_subsys(ss, ssid)
1375 if (root->subsys_mask & (1 << ssid))
1376 seq_show_option(seq, ss->name, NULL);
1377 if (root->flags & CGRP_ROOT_NOPREFIX)
1378 seq_puts(seq, ",noprefix");
1379 if (root->flags & CGRP_ROOT_XATTR)
1380 seq_puts(seq, ",xattr");
1382 spin_lock(&release_agent_path_lock);
1383 if (strlen(root->release_agent_path))
1384 seq_show_option(seq, "release_agent",
1385 root->release_agent_path);
1386 spin_unlock(&release_agent_path_lock);
1388 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags))
1389 seq_puts(seq, ",clone_children");
1390 if (strlen(root->name))
1391 seq_show_option(seq, "name", root->name);
1392 return 0;
1395 struct cgroup_sb_opts {
1396 unsigned long subsys_mask;
1397 unsigned int flags;
1398 char *release_agent;
1399 bool cpuset_clone_children;
1400 char *name;
1401 /* User explicitly requested empty subsystem */
1402 bool none;
1405 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1407 char *token, *o = data;
1408 bool all_ss = false, one_ss = false;
1409 unsigned long mask = -1UL;
1410 struct cgroup_subsys *ss;
1411 int nr_opts = 0;
1412 int i;
1414 #ifdef CONFIG_CPUSETS
1415 mask = ~(1U << cpuset_cgrp_id);
1416 #endif
1418 memset(opts, 0, sizeof(*opts));
1420 while ((token = strsep(&o, ",")) != NULL) {
1421 nr_opts++;
1423 if (!*token)
1424 return -EINVAL;
1425 if (!strcmp(token, "none")) {
1426 /* Explicitly have no subsystems */
1427 opts->none = true;
1428 continue;
1430 if (!strcmp(token, "all")) {
1431 /* Mutually exclusive option 'all' + subsystem name */
1432 if (one_ss)
1433 return -EINVAL;
1434 all_ss = true;
1435 continue;
1437 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1438 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1439 continue;
1441 if (!strcmp(token, "noprefix")) {
1442 opts->flags |= CGRP_ROOT_NOPREFIX;
1443 continue;
1445 if (!strcmp(token, "clone_children")) {
1446 opts->cpuset_clone_children = true;
1447 continue;
1449 if (!strcmp(token, "xattr")) {
1450 opts->flags |= CGRP_ROOT_XATTR;
1451 continue;
1453 if (!strncmp(token, "release_agent=", 14)) {
1454 /* Specifying two release agents is forbidden */
1455 if (opts->release_agent)
1456 return -EINVAL;
1457 opts->release_agent =
1458 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1459 if (!opts->release_agent)
1460 return -ENOMEM;
1461 continue;
1463 if (!strncmp(token, "name=", 5)) {
1464 const char *name = token + 5;
1465 /* Can't specify an empty name */
1466 if (!strlen(name))
1467 return -EINVAL;
1468 /* Must match [\w.-]+ */
1469 for (i = 0; i < strlen(name); i++) {
1470 char c = name[i];
1471 if (isalnum(c))
1472 continue;
1473 if ((c == '.') || (c == '-') || (c == '_'))
1474 continue;
1475 return -EINVAL;
1477 /* Specifying two names is forbidden */
1478 if (opts->name)
1479 return -EINVAL;
1480 opts->name = kstrndup(name,
1481 MAX_CGROUP_ROOT_NAMELEN - 1,
1482 GFP_KERNEL);
1483 if (!opts->name)
1484 return -ENOMEM;
1486 continue;
1489 for_each_subsys(ss, i) {
1490 if (strcmp(token, ss->name))
1491 continue;
1492 if (ss->disabled)
1493 continue;
1495 /* Mutually exclusive option 'all' + subsystem name */
1496 if (all_ss)
1497 return -EINVAL;
1498 opts->subsys_mask |= (1 << i);
1499 one_ss = true;
1501 break;
1503 if (i == CGROUP_SUBSYS_COUNT)
1504 return -ENOENT;
1507 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1508 pr_warn("sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1509 if (nr_opts != 1) {
1510 pr_err("sane_behavior: no other mount options allowed\n");
1511 return -EINVAL;
1513 return 0;
1517 * If the 'all' option was specified select all the subsystems,
1518 * otherwise if 'none', 'name=' and a subsystem name options were
1519 * not specified, let's default to 'all'
1521 if (all_ss || (!one_ss && !opts->none && !opts->name))
1522 for_each_subsys(ss, i)
1523 if (!ss->disabled)
1524 opts->subsys_mask |= (1 << i);
1527 * We either have to specify by name or by subsystems. (So all
1528 * empty hierarchies must have a name).
1530 if (!opts->subsys_mask && !opts->name)
1531 return -EINVAL;
1534 * Option noprefix was introduced just for backward compatibility
1535 * with the old cpuset, so we allow noprefix only if mounting just
1536 * the cpuset subsystem.
1538 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1539 return -EINVAL;
1541 /* Can't specify "none" and some subsystems */
1542 if (opts->subsys_mask && opts->none)
1543 return -EINVAL;
1545 return 0;
1548 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1550 int ret = 0;
1551 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1552 struct cgroup_sb_opts opts;
1553 unsigned long added_mask, removed_mask;
1555 if (root == &cgrp_dfl_root) {
1556 pr_err("remount is not allowed\n");
1557 return -EINVAL;
1560 mutex_lock(&cgroup_mutex);
1562 /* See what subsystems are wanted */
1563 ret = parse_cgroupfs_options(data, &opts);
1564 if (ret)
1565 goto out_unlock;
1567 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1568 pr_warn("option changes via remount are deprecated (pid=%d comm=%s)\n",
1569 task_tgid_nr(current), current->comm);
1571 added_mask = opts.subsys_mask & ~root->subsys_mask;
1572 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1574 /* Don't allow flags or name to change at remount */
1575 if ((opts.flags ^ root->flags) ||
1576 (opts.name && strcmp(opts.name, root->name))) {
1577 pr_err("option or name mismatch, new: 0x%x \"%s\", old: 0x%x \"%s\"\n",
1578 opts.flags, opts.name ?: "", root->flags, root->name);
1579 ret = -EINVAL;
1580 goto out_unlock;
1583 /* remounting is not allowed for populated hierarchies */
1584 if (!list_empty(&root->cgrp.self.children)) {
1585 ret = -EBUSY;
1586 goto out_unlock;
1589 ret = rebind_subsystems(root, added_mask);
1590 if (ret)
1591 goto out_unlock;
1593 rebind_subsystems(&cgrp_dfl_root, removed_mask);
1595 if (opts.release_agent) {
1596 spin_lock(&release_agent_path_lock);
1597 strcpy(root->release_agent_path, opts.release_agent);
1598 spin_unlock(&release_agent_path_lock);
1600 out_unlock:
1601 kfree(opts.release_agent);
1602 kfree(opts.name);
1603 mutex_unlock(&cgroup_mutex);
1604 return ret;
1608 * To reduce the fork() overhead for systems that are not actually using
1609 * their cgroups capability, we don't maintain the lists running through
1610 * each css_set to its tasks until we see the list actually used - in other
1611 * words after the first mount.
1613 static bool use_task_css_set_links __read_mostly;
1615 static void cgroup_enable_task_cg_lists(void)
1617 struct task_struct *p, *g;
1619 down_write(&css_set_rwsem);
1621 if (use_task_css_set_links)
1622 goto out_unlock;
1624 use_task_css_set_links = true;
1627 * We need tasklist_lock because RCU is not safe against
1628 * while_each_thread(). Besides, a forking task that has passed
1629 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1630 * is not guaranteed to have its child immediately visible in the
1631 * tasklist if we walk through it with RCU.
1633 read_lock(&tasklist_lock);
1634 do_each_thread(g, p) {
1635 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1636 task_css_set(p) != &init_css_set);
1639 * We should check if the process is exiting, otherwise
1640 * it will race with cgroup_exit() in that the list
1641 * entry won't be deleted though the process has exited.
1642 * Do it while holding siglock so that we don't end up
1643 * racing against cgroup_exit().
1645 spin_lock_irq(&p->sighand->siglock);
1646 if (!(p->flags & PF_EXITING)) {
1647 struct css_set *cset = task_css_set(p);
1649 list_add(&p->cg_list, &cset->tasks);
1650 get_css_set(cset);
1652 spin_unlock_irq(&p->sighand->siglock);
1653 } while_each_thread(g, p);
1654 read_unlock(&tasklist_lock);
1655 out_unlock:
1656 up_write(&css_set_rwsem);
1659 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1661 struct cgroup_subsys *ss;
1662 int ssid;
1664 INIT_LIST_HEAD(&cgrp->self.sibling);
1665 INIT_LIST_HEAD(&cgrp->self.children);
1666 INIT_LIST_HEAD(&cgrp->cset_links);
1667 INIT_LIST_HEAD(&cgrp->pidlists);
1668 mutex_init(&cgrp->pidlist_mutex);
1669 cgrp->self.cgroup = cgrp;
1670 cgrp->self.flags |= CSS_ONLINE;
1672 for_each_subsys(ss, ssid)
1673 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
1675 init_waitqueue_head(&cgrp->offline_waitq);
1676 INIT_WORK(&cgrp->release_agent_work, cgroup_release_agent);
1679 static void init_cgroup_root(struct cgroup_root *root,
1680 struct cgroup_sb_opts *opts)
1682 struct cgroup *cgrp = &root->cgrp;
1684 INIT_LIST_HEAD(&root->root_list);
1685 atomic_set(&root->nr_cgrps, 1);
1686 cgrp->root = root;
1687 init_cgroup_housekeeping(cgrp);
1688 idr_init(&root->cgroup_idr);
1690 root->flags = opts->flags;
1691 if (opts->release_agent)
1692 strcpy(root->release_agent_path, opts->release_agent);
1693 if (opts->name)
1694 strcpy(root->name, opts->name);
1695 if (opts->cpuset_clone_children)
1696 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1699 static int cgroup_setup_root(struct cgroup_root *root, unsigned long ss_mask)
1701 LIST_HEAD(tmp_links);
1702 struct cgroup *root_cgrp = &root->cgrp;
1703 struct cftype *base_files;
1704 struct css_set *cset;
1705 int i, ret;
1707 lockdep_assert_held(&cgroup_mutex);
1709 ret = cgroup_idr_alloc(&root->cgroup_idr, root_cgrp, 1, 2, GFP_NOWAIT);
1710 if (ret < 0)
1711 goto out;
1712 root_cgrp->id = ret;
1714 ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release, 0,
1715 GFP_KERNEL);
1716 if (ret)
1717 goto out;
1720 * We're accessing css_set_count without locking css_set_rwsem here,
1721 * but that's OK - it can only be increased by someone holding
1722 * cgroup_lock, and that's us. The worst that can happen is that we
1723 * have some link structures left over
1725 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1726 if (ret)
1727 goto cancel_ref;
1729 ret = cgroup_init_root_id(root);
1730 if (ret)
1731 goto cancel_ref;
1733 root->kf_root = kernfs_create_root(&cgroup_kf_syscall_ops,
1734 KERNFS_ROOT_CREATE_DEACTIVATED,
1735 root_cgrp);
1736 if (IS_ERR(root->kf_root)) {
1737 ret = PTR_ERR(root->kf_root);
1738 goto exit_root_id;
1740 root_cgrp->kn = root->kf_root->kn;
1742 if (root == &cgrp_dfl_root)
1743 base_files = cgroup_dfl_base_files;
1744 else
1745 base_files = cgroup_legacy_base_files;
1747 ret = cgroup_addrm_files(root_cgrp, base_files, true);
1748 if (ret)
1749 goto destroy_root;
1751 ret = rebind_subsystems(root, ss_mask);
1752 if (ret)
1753 goto destroy_root;
1756 * There must be no failure case after here, since rebinding takes
1757 * care of subsystems' refcounts, which are explicitly dropped in
1758 * the failure exit path.
1760 list_add(&root->root_list, &cgroup_roots);
1761 cgroup_root_count++;
1764 * Link the root cgroup in this hierarchy into all the css_set
1765 * objects.
1767 down_write(&css_set_rwsem);
1768 hash_for_each(css_set_table, i, cset, hlist)
1769 link_css_set(&tmp_links, cset, root_cgrp);
1770 up_write(&css_set_rwsem);
1772 BUG_ON(!list_empty(&root_cgrp->self.children));
1773 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
1775 kernfs_activate(root_cgrp->kn);
1776 ret = 0;
1777 goto out;
1779 destroy_root:
1780 kernfs_destroy_root(root->kf_root);
1781 root->kf_root = NULL;
1782 exit_root_id:
1783 cgroup_exit_root_id(root);
1784 cancel_ref:
1785 percpu_ref_exit(&root_cgrp->self.refcnt);
1786 out:
1787 free_cgrp_cset_links(&tmp_links);
1788 return ret;
1791 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1792 int flags, const char *unused_dev_name,
1793 void *data)
1795 struct super_block *pinned_sb = NULL;
1796 struct cgroup_subsys *ss;
1797 struct cgroup_root *root;
1798 struct cgroup_sb_opts opts;
1799 struct dentry *dentry;
1800 int ret;
1801 int i;
1802 bool new_sb;
1805 * The first time anyone tries to mount a cgroup, enable the list
1806 * linking each css_set to its tasks and fix up all existing tasks.
1808 if (!use_task_css_set_links)
1809 cgroup_enable_task_cg_lists();
1811 mutex_lock(&cgroup_mutex);
1813 /* First find the desired set of subsystems */
1814 ret = parse_cgroupfs_options(data, &opts);
1815 if (ret)
1816 goto out_unlock;
1818 /* look for a matching existing root */
1819 if (opts.flags & CGRP_ROOT_SANE_BEHAVIOR) {
1820 cgrp_dfl_root_visible = true;
1821 root = &cgrp_dfl_root;
1822 cgroup_get(&root->cgrp);
1823 ret = 0;
1824 goto out_unlock;
1828 * Destruction of cgroup root is asynchronous, so subsystems may
1829 * still be dying after the previous unmount. Let's drain the
1830 * dying subsystems. We just need to ensure that the ones
1831 * unmounted previously finish dying and don't care about new ones
1832 * starting. Testing ref liveliness is good enough.
1834 for_each_subsys(ss, i) {
1835 if (!(opts.subsys_mask & (1 << i)) ||
1836 ss->root == &cgrp_dfl_root)
1837 continue;
1839 if (!percpu_ref_tryget_live(&ss->root->cgrp.self.refcnt)) {
1840 mutex_unlock(&cgroup_mutex);
1841 msleep(10);
1842 ret = restart_syscall();
1843 goto out_free;
1845 cgroup_put(&ss->root->cgrp);
1848 for_each_root(root) {
1849 bool name_match = false;
1851 if (root == &cgrp_dfl_root)
1852 continue;
1855 * If we asked for a name then it must match. Also, if
1856 * name matches but sybsys_mask doesn't, we should fail.
1857 * Remember whether name matched.
1859 if (opts.name) {
1860 if (strcmp(opts.name, root->name))
1861 continue;
1862 name_match = true;
1866 * If we asked for subsystems (or explicitly for no
1867 * subsystems) then they must match.
1869 if ((opts.subsys_mask || opts.none) &&
1870 (opts.subsys_mask != root->subsys_mask)) {
1871 if (!name_match)
1872 continue;
1873 ret = -EBUSY;
1874 goto out_unlock;
1877 if (root->flags ^ opts.flags)
1878 pr_warn("new mount options do not match the existing superblock, will be ignored\n");
1881 * We want to reuse @root whose lifetime is governed by its
1882 * ->cgrp. Let's check whether @root is alive and keep it
1883 * that way. As cgroup_kill_sb() can happen anytime, we
1884 * want to block it by pinning the sb so that @root doesn't
1885 * get killed before mount is complete.
1887 * With the sb pinned, tryget_live can reliably indicate
1888 * whether @root can be reused. If it's being killed,
1889 * drain it. We can use wait_queue for the wait but this
1890 * path is super cold. Let's just sleep a bit and retry.
1892 pinned_sb = kernfs_pin_sb(root->kf_root, NULL);
1893 if (IS_ERR(pinned_sb) ||
1894 !percpu_ref_tryget_live(&root->cgrp.self.refcnt)) {
1895 mutex_unlock(&cgroup_mutex);
1896 if (!IS_ERR_OR_NULL(pinned_sb))
1897 deactivate_super(pinned_sb);
1898 msleep(10);
1899 ret = restart_syscall();
1900 goto out_free;
1903 ret = 0;
1904 goto out_unlock;
1908 * No such thing, create a new one. name= matching without subsys
1909 * specification is allowed for already existing hierarchies but we
1910 * can't create new one without subsys specification.
1912 if (!opts.subsys_mask && !opts.none) {
1913 ret = -EINVAL;
1914 goto out_unlock;
1917 root = kzalloc(sizeof(*root), GFP_KERNEL);
1918 if (!root) {
1919 ret = -ENOMEM;
1920 goto out_unlock;
1923 init_cgroup_root(root, &opts);
1925 ret = cgroup_setup_root(root, opts.subsys_mask);
1926 if (ret)
1927 cgroup_free_root(root);
1929 out_unlock:
1930 mutex_unlock(&cgroup_mutex);
1931 out_free:
1932 kfree(opts.release_agent);
1933 kfree(opts.name);
1935 if (ret)
1936 return ERR_PTR(ret);
1938 dentry = kernfs_mount(fs_type, flags, root->kf_root,
1939 CGROUP_SUPER_MAGIC, &new_sb);
1940 if (IS_ERR(dentry) || !new_sb)
1941 cgroup_put(&root->cgrp);
1944 * If @pinned_sb, we're reusing an existing root and holding an
1945 * extra ref on its sb. Mount is complete. Put the extra ref.
1947 if (pinned_sb) {
1948 WARN_ON(new_sb);
1949 deactivate_super(pinned_sb);
1952 return dentry;
1955 static void cgroup_kill_sb(struct super_block *sb)
1957 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
1958 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1961 * If @root doesn't have any mounts or children, start killing it.
1962 * This prevents new mounts by disabling percpu_ref_tryget_live().
1963 * cgroup_mount() may wait for @root's release.
1965 * And don't kill the default root.
1967 if (!list_empty(&root->cgrp.self.children) ||
1968 root == &cgrp_dfl_root)
1969 cgroup_put(&root->cgrp);
1970 else
1971 percpu_ref_kill(&root->cgrp.self.refcnt);
1973 kernfs_kill_sb(sb);
1976 static struct file_system_type cgroup_fs_type = {
1977 .name = "cgroup",
1978 .mount = cgroup_mount,
1979 .kill_sb = cgroup_kill_sb,
1983 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1984 * @task: target task
1985 * @buf: the buffer to write the path into
1986 * @buflen: the length of the buffer
1988 * Determine @task's cgroup on the first (the one with the lowest non-zero
1989 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1990 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1991 * cgroup controller callbacks.
1993 * Return value is the same as kernfs_path().
1995 char *task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1997 struct cgroup_root *root;
1998 struct cgroup *cgrp;
1999 int hierarchy_id = 1;
2000 char *path = NULL;
2002 mutex_lock(&cgroup_mutex);
2003 down_read(&css_set_rwsem);
2005 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
2007 if (root) {
2008 cgrp = task_cgroup_from_root(task, root);
2009 path = cgroup_path(cgrp, buf, buflen);
2010 } else {
2011 /* if no hierarchy exists, everyone is in "/" */
2012 if (strlcpy(buf, "/", buflen) < buflen)
2013 path = buf;
2016 up_read(&css_set_rwsem);
2017 mutex_unlock(&cgroup_mutex);
2018 return path;
2020 EXPORT_SYMBOL_GPL(task_cgroup_path);
2022 /* used to track tasks and other necessary states during migration */
2023 struct cgroup_taskset {
2024 /* the src and dst cset list running through cset->mg_node */
2025 struct list_head src_csets;
2026 struct list_head dst_csets;
2029 * Fields for cgroup_taskset_*() iteration.
2031 * Before migration is committed, the target migration tasks are on
2032 * ->mg_tasks of the csets on ->src_csets. After, on ->mg_tasks of
2033 * the csets on ->dst_csets. ->csets point to either ->src_csets
2034 * or ->dst_csets depending on whether migration is committed.
2036 * ->cur_csets and ->cur_task point to the current task position
2037 * during iteration.
2039 struct list_head *csets;
2040 struct css_set *cur_cset;
2041 struct task_struct *cur_task;
2045 * cgroup_taskset_first - reset taskset and return the first task
2046 * @tset: taskset of interest
2048 * @tset iteration is initialized and the first task is returned.
2050 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
2052 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
2053 tset->cur_task = NULL;
2055 return cgroup_taskset_next(tset);
2059 * cgroup_taskset_next - iterate to the next task in taskset
2060 * @tset: taskset of interest
2062 * Return the next task in @tset. Iteration must have been initialized
2063 * with cgroup_taskset_first().
2065 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
2067 struct css_set *cset = tset->cur_cset;
2068 struct task_struct *task = tset->cur_task;
2070 while (&cset->mg_node != tset->csets) {
2071 if (!task)
2072 task = list_first_entry(&cset->mg_tasks,
2073 struct task_struct, cg_list);
2074 else
2075 task = list_next_entry(task, cg_list);
2077 if (&task->cg_list != &cset->mg_tasks) {
2078 tset->cur_cset = cset;
2079 tset->cur_task = task;
2080 return task;
2083 cset = list_next_entry(cset, mg_node);
2084 task = NULL;
2087 return NULL;
2091 * cgroup_task_migrate - move a task from one cgroup to another.
2092 * @old_cgrp: the cgroup @tsk is being migrated from
2093 * @tsk: the task being migrated
2094 * @new_cset: the new css_set @tsk is being attached to
2096 * Must be called with cgroup_mutex, threadgroup and css_set_rwsem locked.
2098 static void cgroup_task_migrate(struct cgroup *old_cgrp,
2099 struct task_struct *tsk,
2100 struct css_set *new_cset)
2102 struct css_set *old_cset;
2104 lockdep_assert_held(&cgroup_mutex);
2105 lockdep_assert_held(&css_set_rwsem);
2108 * We are synchronized through threadgroup_lock() against PF_EXITING
2109 * setting such that we can't race against cgroup_exit() changing the
2110 * css_set to init_css_set and dropping the old one.
2112 WARN_ON_ONCE(tsk->flags & PF_EXITING);
2113 old_cset = task_css_set(tsk);
2115 get_css_set(new_cset);
2116 rcu_assign_pointer(tsk->cgroups, new_cset);
2119 * Use move_tail so that cgroup_taskset_first() still returns the
2120 * leader after migration. This works because cgroup_migrate()
2121 * ensures that the dst_cset of the leader is the first on the
2122 * tset's dst_csets list.
2124 list_move_tail(&tsk->cg_list, &new_cset->mg_tasks);
2127 * We just gained a reference on old_cset by taking it from the
2128 * task. As trading it for new_cset is protected by cgroup_mutex,
2129 * we're safe to drop it here; it will be freed under RCU.
2131 put_css_set_locked(old_cset);
2135 * cgroup_migrate_finish - cleanup after attach
2136 * @preloaded_csets: list of preloaded css_sets
2138 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
2139 * those functions for details.
2141 static void cgroup_migrate_finish(struct list_head *preloaded_csets)
2143 struct css_set *cset, *tmp_cset;
2145 lockdep_assert_held(&cgroup_mutex);
2147 down_write(&css_set_rwsem);
2148 list_for_each_entry_safe(cset, tmp_cset, preloaded_csets, mg_preload_node) {
2149 cset->mg_src_cgrp = NULL;
2150 cset->mg_dst_cset = NULL;
2151 list_del_init(&cset->mg_preload_node);
2152 put_css_set_locked(cset);
2154 up_write(&css_set_rwsem);
2158 * cgroup_migrate_add_src - add a migration source css_set
2159 * @src_cset: the source css_set to add
2160 * @dst_cgrp: the destination cgroup
2161 * @preloaded_csets: list of preloaded css_sets
2163 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
2164 * @src_cset and add it to @preloaded_csets, which should later be cleaned
2165 * up by cgroup_migrate_finish().
2167 * This function may be called without holding threadgroup_lock even if the
2168 * target is a process. Threads may be created and destroyed but as long
2169 * as cgroup_mutex is not dropped, no new css_set can be put into play and
2170 * the preloaded css_sets are guaranteed to cover all migrations.
2172 static void cgroup_migrate_add_src(struct css_set *src_cset,
2173 struct cgroup *dst_cgrp,
2174 struct list_head *preloaded_csets)
2176 struct cgroup *src_cgrp;
2178 lockdep_assert_held(&cgroup_mutex);
2179 lockdep_assert_held(&css_set_rwsem);
2181 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2183 if (!list_empty(&src_cset->mg_preload_node))
2184 return;
2186 WARN_ON(src_cset->mg_src_cgrp);
2187 WARN_ON(!list_empty(&src_cset->mg_tasks));
2188 WARN_ON(!list_empty(&src_cset->mg_node));
2190 src_cset->mg_src_cgrp = src_cgrp;
2191 get_css_set(src_cset);
2192 list_add(&src_cset->mg_preload_node, preloaded_csets);
2196 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2197 * @dst_cgrp: the destination cgroup (may be %NULL)
2198 * @preloaded_csets: list of preloaded source css_sets
2200 * Tasks are about to be moved to @dst_cgrp and all the source css_sets
2201 * have been preloaded to @preloaded_csets. This function looks up and
2202 * pins all destination css_sets, links each to its source, and append them
2203 * to @preloaded_csets. If @dst_cgrp is %NULL, the destination of each
2204 * source css_set is assumed to be its cgroup on the default hierarchy.
2206 * This function must be called after cgroup_migrate_add_src() has been
2207 * called on each migration source css_set. After migration is performed
2208 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2209 * @preloaded_csets.
2211 static int cgroup_migrate_prepare_dst(struct cgroup *dst_cgrp,
2212 struct list_head *preloaded_csets)
2214 LIST_HEAD(csets);
2215 struct css_set *src_cset, *tmp_cset;
2217 lockdep_assert_held(&cgroup_mutex);
2220 * Except for the root, child_subsys_mask must be zero for a cgroup
2221 * with tasks so that child cgroups don't compete against tasks.
2223 if (dst_cgrp && cgroup_on_dfl(dst_cgrp) && cgroup_parent(dst_cgrp) &&
2224 dst_cgrp->child_subsys_mask)
2225 return -EBUSY;
2227 /* look up the dst cset for each src cset and link it to src */
2228 list_for_each_entry_safe(src_cset, tmp_cset, preloaded_csets, mg_preload_node) {
2229 struct css_set *dst_cset;
2231 dst_cset = find_css_set(src_cset,
2232 dst_cgrp ?: src_cset->dfl_cgrp);
2233 if (!dst_cset)
2234 goto err;
2236 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2239 * If src cset equals dst, it's noop. Drop the src.
2240 * cgroup_migrate() will skip the cset too. Note that we
2241 * can't handle src == dst as some nodes are used by both.
2243 if (src_cset == dst_cset) {
2244 src_cset->mg_src_cgrp = NULL;
2245 list_del_init(&src_cset->mg_preload_node);
2246 put_css_set(src_cset);
2247 put_css_set(dst_cset);
2248 continue;
2251 src_cset->mg_dst_cset = dst_cset;
2253 if (list_empty(&dst_cset->mg_preload_node))
2254 list_add(&dst_cset->mg_preload_node, &csets);
2255 else
2256 put_css_set(dst_cset);
2259 list_splice_tail(&csets, preloaded_csets);
2260 return 0;
2261 err:
2262 cgroup_migrate_finish(&csets);
2263 return -ENOMEM;
2267 * cgroup_migrate - migrate a process or task to a cgroup
2268 * @cgrp: the destination cgroup
2269 * @leader: the leader of the process or the task to migrate
2270 * @threadgroup: whether @leader points to the whole process or a single task
2272 * Migrate a process or task denoted by @leader to @cgrp. If migrating a
2273 * process, the caller must be holding threadgroup_lock of @leader. The
2274 * caller is also responsible for invoking cgroup_migrate_add_src() and
2275 * cgroup_migrate_prepare_dst() on the targets before invoking this
2276 * function and following up with cgroup_migrate_finish().
2278 * As long as a controller's ->can_attach() doesn't fail, this function is
2279 * guaranteed to succeed. This means that, excluding ->can_attach()
2280 * failure, when migrating multiple targets, the success or failure can be
2281 * decided for all targets by invoking group_migrate_prepare_dst() before
2282 * actually starting migrating.
2284 static int cgroup_migrate(struct cgroup *cgrp, struct task_struct *leader,
2285 bool threadgroup)
2287 struct cgroup_taskset tset = {
2288 .src_csets = LIST_HEAD_INIT(tset.src_csets),
2289 .dst_csets = LIST_HEAD_INIT(tset.dst_csets),
2290 .csets = &tset.src_csets,
2292 struct cgroup_subsys_state *css, *failed_css = NULL;
2293 struct css_set *cset, *tmp_cset;
2294 struct task_struct *task, *tmp_task;
2295 int i, ret;
2298 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2299 * already PF_EXITING could be freed from underneath us unless we
2300 * take an rcu_read_lock.
2302 down_write(&css_set_rwsem);
2303 rcu_read_lock();
2304 task = leader;
2305 do {
2306 /* @task either already exited or can't exit until the end */
2307 if (task->flags & PF_EXITING)
2308 goto next;
2310 /* leave @task alone if post_fork() hasn't linked it yet */
2311 if (list_empty(&task->cg_list))
2312 goto next;
2314 cset = task_css_set(task);
2315 if (!cset->mg_src_cgrp)
2316 goto next;
2319 * cgroup_taskset_first() must always return the leader.
2320 * Take care to avoid disturbing the ordering.
2322 list_move_tail(&task->cg_list, &cset->mg_tasks);
2323 if (list_empty(&cset->mg_node))
2324 list_add_tail(&cset->mg_node, &tset.src_csets);
2325 if (list_empty(&cset->mg_dst_cset->mg_node))
2326 list_move_tail(&cset->mg_dst_cset->mg_node,
2327 &tset.dst_csets);
2328 next:
2329 if (!threadgroup)
2330 break;
2331 } while_each_thread(leader, task);
2332 rcu_read_unlock();
2333 up_write(&css_set_rwsem);
2335 /* methods shouldn't be called if no task is actually migrating */
2336 if (list_empty(&tset.src_csets))
2337 return 0;
2339 /* check that we can legitimately attach to the cgroup */
2340 for_each_e_css(css, i, cgrp) {
2341 if (css->ss->can_attach) {
2342 ret = css->ss->can_attach(css, &tset);
2343 if (ret) {
2344 failed_css = css;
2345 goto out_cancel_attach;
2351 * Now that we're guaranteed success, proceed to move all tasks to
2352 * the new cgroup. There are no failure cases after here, so this
2353 * is the commit point.
2355 down_write(&css_set_rwsem);
2356 list_for_each_entry(cset, &tset.src_csets, mg_node) {
2357 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list)
2358 cgroup_task_migrate(cset->mg_src_cgrp, task,
2359 cset->mg_dst_cset);
2361 up_write(&css_set_rwsem);
2364 * Migration is committed, all target tasks are now on dst_csets.
2365 * Nothing is sensitive to fork() after this point. Notify
2366 * controllers that migration is complete.
2368 tset.csets = &tset.dst_csets;
2370 for_each_e_css(css, i, cgrp)
2371 if (css->ss->attach)
2372 css->ss->attach(css, &tset);
2374 ret = 0;
2375 goto out_release_tset;
2377 out_cancel_attach:
2378 for_each_e_css(css, i, cgrp) {
2379 if (css == failed_css)
2380 break;
2381 if (css->ss->cancel_attach)
2382 css->ss->cancel_attach(css, &tset);
2384 out_release_tset:
2385 down_write(&css_set_rwsem);
2386 list_splice_init(&tset.dst_csets, &tset.src_csets);
2387 list_for_each_entry_safe(cset, tmp_cset, &tset.src_csets, mg_node) {
2388 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2389 list_del_init(&cset->mg_node);
2391 up_write(&css_set_rwsem);
2392 return ret;
2396 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2397 * @dst_cgrp: the cgroup to attach to
2398 * @leader: the task or the leader of the threadgroup to be attached
2399 * @threadgroup: attach the whole threadgroup?
2401 * Call holding cgroup_mutex and threadgroup_lock of @leader.
2403 static int cgroup_attach_task(struct cgroup *dst_cgrp,
2404 struct task_struct *leader, bool threadgroup)
2406 LIST_HEAD(preloaded_csets);
2407 struct task_struct *task;
2408 int ret;
2410 /* look up all src csets */
2411 down_read(&css_set_rwsem);
2412 rcu_read_lock();
2413 task = leader;
2414 do {
2415 cgroup_migrate_add_src(task_css_set(task), dst_cgrp,
2416 &preloaded_csets);
2417 if (!threadgroup)
2418 break;
2419 } while_each_thread(leader, task);
2420 rcu_read_unlock();
2421 up_read(&css_set_rwsem);
2423 /* prepare dst csets and commit */
2424 ret = cgroup_migrate_prepare_dst(dst_cgrp, &preloaded_csets);
2425 if (!ret)
2426 ret = cgroup_migrate(dst_cgrp, leader, threadgroup);
2428 cgroup_migrate_finish(&preloaded_csets);
2429 return ret;
2432 static int cgroup_procs_write_permission(struct task_struct *task,
2433 struct cgroup *dst_cgrp,
2434 struct kernfs_open_file *of)
2436 const struct cred *cred = current_cred();
2437 const struct cred *tcred = get_task_cred(task);
2438 int ret = 0;
2441 * even if we're attaching all tasks in the thread group, we only
2442 * need to check permissions on one of them.
2444 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2445 !uid_eq(cred->euid, tcred->uid) &&
2446 !uid_eq(cred->euid, tcred->suid))
2447 ret = -EACCES;
2449 if (!ret && cgroup_on_dfl(dst_cgrp)) {
2450 struct super_block *sb = of->file->f_path.dentry->d_sb;
2451 struct cgroup *cgrp;
2452 struct inode *inode;
2454 down_read(&css_set_rwsem);
2455 cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
2456 up_read(&css_set_rwsem);
2458 while (!cgroup_is_descendant(dst_cgrp, cgrp))
2459 cgrp = cgroup_parent(cgrp);
2461 ret = -ENOMEM;
2462 inode = kernfs_get_inode(sb, cgrp->procs_kn);
2463 if (inode) {
2464 ret = inode_permission(inode, MAY_WRITE);
2465 iput(inode);
2469 put_cred(tcred);
2470 return ret;
2474 * Find the task_struct of the task to attach by vpid and pass it along to the
2475 * function to attach either it or all tasks in its threadgroup. Will lock
2476 * cgroup_mutex and threadgroup.
2478 static ssize_t __cgroup_procs_write(struct kernfs_open_file *of, char *buf,
2479 size_t nbytes, loff_t off, bool threadgroup)
2481 struct task_struct *tsk;
2482 struct cgroup *cgrp;
2483 pid_t pid;
2484 int ret;
2486 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2487 return -EINVAL;
2489 cgrp = cgroup_kn_lock_live(of->kn);
2490 if (!cgrp)
2491 return -ENODEV;
2493 retry_find_task:
2494 rcu_read_lock();
2495 if (pid) {
2496 tsk = find_task_by_vpid(pid);
2497 if (!tsk) {
2498 rcu_read_unlock();
2499 ret = -ESRCH;
2500 goto out_unlock_cgroup;
2502 } else {
2503 tsk = current;
2506 if (threadgroup)
2507 tsk = tsk->group_leader;
2510 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2511 * trapped in a cpuset, or RT worker may be born in a cgroup
2512 * with no rt_runtime allocated. Just say no.
2514 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2515 ret = -EINVAL;
2516 rcu_read_unlock();
2517 goto out_unlock_cgroup;
2520 get_task_struct(tsk);
2521 rcu_read_unlock();
2523 threadgroup_lock(tsk);
2524 if (threadgroup) {
2525 if (!thread_group_leader(tsk)) {
2527 * a race with de_thread from another thread's exec()
2528 * may strip us of our leadership, if this happens,
2529 * there is no choice but to throw this task away and
2530 * try again; this is
2531 * "double-double-toil-and-trouble-check locking".
2533 threadgroup_unlock(tsk);
2534 put_task_struct(tsk);
2535 goto retry_find_task;
2539 ret = cgroup_procs_write_permission(tsk, cgrp, of);
2540 if (!ret)
2541 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2543 threadgroup_unlock(tsk);
2545 put_task_struct(tsk);
2546 out_unlock_cgroup:
2547 cgroup_kn_unlock(of->kn);
2548 return ret ?: nbytes;
2552 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2553 * @from: attach to all cgroups of a given task
2554 * @tsk: the task to be attached
2556 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2558 struct cgroup_root *root;
2559 int retval = 0;
2561 mutex_lock(&cgroup_mutex);
2562 for_each_root(root) {
2563 struct cgroup *from_cgrp;
2565 if (root == &cgrp_dfl_root)
2566 continue;
2568 down_read(&css_set_rwsem);
2569 from_cgrp = task_cgroup_from_root(from, root);
2570 up_read(&css_set_rwsem);
2572 retval = cgroup_attach_task(from_cgrp, tsk, false);
2573 if (retval)
2574 break;
2576 mutex_unlock(&cgroup_mutex);
2578 return retval;
2580 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2582 static ssize_t cgroup_tasks_write(struct kernfs_open_file *of,
2583 char *buf, size_t nbytes, loff_t off)
2585 return __cgroup_procs_write(of, buf, nbytes, off, false);
2588 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
2589 char *buf, size_t nbytes, loff_t off)
2591 return __cgroup_procs_write(of, buf, nbytes, off, true);
2594 static ssize_t cgroup_release_agent_write(struct kernfs_open_file *of,
2595 char *buf, size_t nbytes, loff_t off)
2597 struct cgroup *cgrp;
2599 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
2601 cgrp = cgroup_kn_lock_live(of->kn);
2602 if (!cgrp)
2603 return -ENODEV;
2604 spin_lock(&release_agent_path_lock);
2605 strlcpy(cgrp->root->release_agent_path, strstrip(buf),
2606 sizeof(cgrp->root->release_agent_path));
2607 spin_unlock(&release_agent_path_lock);
2608 cgroup_kn_unlock(of->kn);
2609 return nbytes;
2612 static int cgroup_release_agent_show(struct seq_file *seq, void *v)
2614 struct cgroup *cgrp = seq_css(seq)->cgroup;
2616 spin_lock(&release_agent_path_lock);
2617 seq_puts(seq, cgrp->root->release_agent_path);
2618 spin_unlock(&release_agent_path_lock);
2619 seq_putc(seq, '\n');
2620 return 0;
2623 static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
2625 seq_puts(seq, "0\n");
2626 return 0;
2629 static void cgroup_print_ss_mask(struct seq_file *seq, unsigned long ss_mask)
2631 struct cgroup_subsys *ss;
2632 bool printed = false;
2633 int ssid;
2635 for_each_subsys_which(ss, ssid, &ss_mask) {
2636 if (printed)
2637 seq_putc(seq, ' ');
2638 seq_printf(seq, "%s", ss->name);
2639 printed = true;
2641 if (printed)
2642 seq_putc(seq, '\n');
2645 /* show controllers which are currently attached to the default hierarchy */
2646 static int cgroup_root_controllers_show(struct seq_file *seq, void *v)
2648 struct cgroup *cgrp = seq_css(seq)->cgroup;
2650 cgroup_print_ss_mask(seq, cgrp->root->subsys_mask &
2651 ~cgrp_dfl_root_inhibit_ss_mask);
2652 return 0;
2655 /* show controllers which are enabled from the parent */
2656 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2658 struct cgroup *cgrp = seq_css(seq)->cgroup;
2660 cgroup_print_ss_mask(seq, cgroup_parent(cgrp)->subtree_control);
2661 return 0;
2664 /* show controllers which are enabled for a given cgroup's children */
2665 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2667 struct cgroup *cgrp = seq_css(seq)->cgroup;
2669 cgroup_print_ss_mask(seq, cgrp->subtree_control);
2670 return 0;
2674 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2675 * @cgrp: root of the subtree to update csses for
2677 * @cgrp's child_subsys_mask has changed and its subtree's (self excluded)
2678 * css associations need to be updated accordingly. This function looks up
2679 * all css_sets which are attached to the subtree, creates the matching
2680 * updated css_sets and migrates the tasks to the new ones.
2682 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2684 LIST_HEAD(preloaded_csets);
2685 struct cgroup_subsys_state *css;
2686 struct css_set *src_cset;
2687 int ret;
2689 lockdep_assert_held(&cgroup_mutex);
2691 /* look up all csses currently attached to @cgrp's subtree */
2692 down_read(&css_set_rwsem);
2693 css_for_each_descendant_pre(css, cgroup_css(cgrp, NULL)) {
2694 struct cgrp_cset_link *link;
2696 /* self is not affected by child_subsys_mask change */
2697 if (css->cgroup == cgrp)
2698 continue;
2700 list_for_each_entry(link, &css->cgroup->cset_links, cset_link)
2701 cgroup_migrate_add_src(link->cset, cgrp,
2702 &preloaded_csets);
2704 up_read(&css_set_rwsem);
2706 /* NULL dst indicates self on default hierarchy */
2707 ret = cgroup_migrate_prepare_dst(NULL, &preloaded_csets);
2708 if (ret)
2709 goto out_finish;
2711 list_for_each_entry(src_cset, &preloaded_csets, mg_preload_node) {
2712 struct task_struct *last_task = NULL, *task;
2714 /* src_csets precede dst_csets, break on the first dst_cset */
2715 if (!src_cset->mg_src_cgrp)
2716 break;
2719 * All tasks in src_cset need to be migrated to the
2720 * matching dst_cset. Empty it process by process. We
2721 * walk tasks but migrate processes. The leader might even
2722 * belong to a different cset but such src_cset would also
2723 * be among the target src_csets because the default
2724 * hierarchy enforces per-process membership.
2726 while (true) {
2727 down_read(&css_set_rwsem);
2728 task = list_first_entry_or_null(&src_cset->tasks,
2729 struct task_struct, cg_list);
2730 if (task) {
2731 task = task->group_leader;
2732 WARN_ON_ONCE(!task_css_set(task)->mg_src_cgrp);
2733 get_task_struct(task);
2735 up_read(&css_set_rwsem);
2737 if (!task)
2738 break;
2740 /* guard against possible infinite loop */
2741 if (WARN(last_task == task,
2742 "cgroup: update_dfl_csses failed to make progress, aborting in inconsistent state\n"))
2743 goto out_finish;
2744 last_task = task;
2746 threadgroup_lock(task);
2747 /* raced against de_thread() from another thread? */
2748 if (!thread_group_leader(task)) {
2749 threadgroup_unlock(task);
2750 put_task_struct(task);
2751 continue;
2754 ret = cgroup_migrate(src_cset->dfl_cgrp, task, true);
2756 threadgroup_unlock(task);
2757 put_task_struct(task);
2759 if (WARN(ret, "cgroup: failed to update controllers for the default hierarchy (%d), further operations may crash or hang\n", ret))
2760 goto out_finish;
2764 out_finish:
2765 cgroup_migrate_finish(&preloaded_csets);
2766 return ret;
2769 /* change the enabled child controllers for a cgroup in the default hierarchy */
2770 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
2771 char *buf, size_t nbytes,
2772 loff_t off)
2774 unsigned long enable = 0, disable = 0;
2775 unsigned long css_enable, css_disable, old_sc, new_sc, old_ss, new_ss;
2776 struct cgroup *cgrp, *child;
2777 struct cgroup_subsys *ss;
2778 char *tok;
2779 int ssid, ret;
2782 * Parse input - space separated list of subsystem names prefixed
2783 * with either + or -.
2785 buf = strstrip(buf);
2786 while ((tok = strsep(&buf, " "))) {
2787 unsigned long tmp_ss_mask = ~cgrp_dfl_root_inhibit_ss_mask;
2789 if (tok[0] == '\0')
2790 continue;
2791 for_each_subsys_which(ss, ssid, &tmp_ss_mask) {
2792 if (ss->disabled || strcmp(tok + 1, ss->name))
2793 continue;
2795 if (*tok == '+') {
2796 enable |= 1 << ssid;
2797 disable &= ~(1 << ssid);
2798 } else if (*tok == '-') {
2799 disable |= 1 << ssid;
2800 enable &= ~(1 << ssid);
2801 } else {
2802 return -EINVAL;
2804 break;
2806 if (ssid == CGROUP_SUBSYS_COUNT)
2807 return -EINVAL;
2810 cgrp = cgroup_kn_lock_live(of->kn);
2811 if (!cgrp)
2812 return -ENODEV;
2814 for_each_subsys(ss, ssid) {
2815 if (enable & (1 << ssid)) {
2816 if (cgrp->subtree_control & (1 << ssid)) {
2817 enable &= ~(1 << ssid);
2818 continue;
2821 /* unavailable or not enabled on the parent? */
2822 if (!(cgrp_dfl_root.subsys_mask & (1 << ssid)) ||
2823 (cgroup_parent(cgrp) &&
2824 !(cgroup_parent(cgrp)->subtree_control & (1 << ssid)))) {
2825 ret = -ENOENT;
2826 goto out_unlock;
2828 } else if (disable & (1 << ssid)) {
2829 if (!(cgrp->subtree_control & (1 << ssid))) {
2830 disable &= ~(1 << ssid);
2831 continue;
2834 /* a child has it enabled? */
2835 cgroup_for_each_live_child(child, cgrp) {
2836 if (child->subtree_control & (1 << ssid)) {
2837 ret = -EBUSY;
2838 goto out_unlock;
2844 if (!enable && !disable) {
2845 ret = 0;
2846 goto out_unlock;
2850 * Except for the root, subtree_control must be zero for a cgroup
2851 * with tasks so that child cgroups don't compete against tasks.
2853 if (enable && cgroup_parent(cgrp) && !list_empty(&cgrp->cset_links)) {
2854 ret = -EBUSY;
2855 goto out_unlock;
2859 * Update subsys masks and calculate what needs to be done. More
2860 * subsystems than specified may need to be enabled or disabled
2861 * depending on subsystem dependencies.
2863 old_sc = cgrp->subtree_control;
2864 old_ss = cgrp->child_subsys_mask;
2865 new_sc = (old_sc | enable) & ~disable;
2866 new_ss = cgroup_calc_child_subsys_mask(cgrp, new_sc);
2868 css_enable = ~old_ss & new_ss;
2869 css_disable = old_ss & ~new_ss;
2870 enable |= css_enable;
2871 disable |= css_disable;
2874 * Because css offlining is asynchronous, userland might try to
2875 * re-enable the same controller while the previous instance is
2876 * still around. In such cases, wait till it's gone using
2877 * offline_waitq.
2879 for_each_subsys_which(ss, ssid, &css_enable) {
2880 cgroup_for_each_live_child(child, cgrp) {
2881 DEFINE_WAIT(wait);
2883 if (!cgroup_css(child, ss))
2884 continue;
2886 cgroup_get(child);
2887 prepare_to_wait(&child->offline_waitq, &wait,
2888 TASK_UNINTERRUPTIBLE);
2889 cgroup_kn_unlock(of->kn);
2890 schedule();
2891 finish_wait(&child->offline_waitq, &wait);
2892 cgroup_put(child);
2894 return restart_syscall();
2898 cgrp->subtree_control = new_sc;
2899 cgrp->child_subsys_mask = new_ss;
2902 * Create new csses or make the existing ones visible. A css is
2903 * created invisible if it's being implicitly enabled through
2904 * dependency. An invisible css is made visible when the userland
2905 * explicitly enables it.
2907 for_each_subsys(ss, ssid) {
2908 if (!(enable & (1 << ssid)))
2909 continue;
2911 cgroup_for_each_live_child(child, cgrp) {
2912 if (css_enable & (1 << ssid))
2913 ret = create_css(child, ss,
2914 cgrp->subtree_control & (1 << ssid));
2915 else
2916 ret = cgroup_populate_dir(child, 1 << ssid);
2917 if (ret)
2918 goto err_undo_css;
2923 * At this point, cgroup_e_css() results reflect the new csses
2924 * making the following cgroup_update_dfl_csses() properly update
2925 * css associations of all tasks in the subtree.
2927 ret = cgroup_update_dfl_csses(cgrp);
2928 if (ret)
2929 goto err_undo_css;
2932 * All tasks are migrated out of disabled csses. Kill or hide
2933 * them. A css is hidden when the userland requests it to be
2934 * disabled while other subsystems are still depending on it. The
2935 * css must not actively control resources and be in the vanilla
2936 * state if it's made visible again later. Controllers which may
2937 * be depended upon should provide ->css_reset() for this purpose.
2939 for_each_subsys(ss, ssid) {
2940 if (!(disable & (1 << ssid)))
2941 continue;
2943 cgroup_for_each_live_child(child, cgrp) {
2944 struct cgroup_subsys_state *css = cgroup_css(child, ss);
2946 if (css_disable & (1 << ssid)) {
2947 kill_css(css);
2948 } else {
2949 cgroup_clear_dir(child, 1 << ssid);
2950 if (ss->css_reset)
2951 ss->css_reset(css);
2957 * The effective csses of all the descendants (excluding @cgrp) may
2958 * have changed. Subsystems can optionally subscribe to this event
2959 * by implementing ->css_e_css_changed() which is invoked if any of
2960 * the effective csses seen from the css's cgroup may have changed.
2962 for_each_subsys(ss, ssid) {
2963 struct cgroup_subsys_state *this_css = cgroup_css(cgrp, ss);
2964 struct cgroup_subsys_state *css;
2966 if (!ss->css_e_css_changed || !this_css)
2967 continue;
2969 css_for_each_descendant_pre(css, this_css)
2970 if (css != this_css)
2971 ss->css_e_css_changed(css);
2974 kernfs_activate(cgrp->kn);
2975 ret = 0;
2976 out_unlock:
2977 cgroup_kn_unlock(of->kn);
2978 return ret ?: nbytes;
2980 err_undo_css:
2981 cgrp->subtree_control = old_sc;
2982 cgrp->child_subsys_mask = old_ss;
2984 for_each_subsys(ss, ssid) {
2985 if (!(enable & (1 << ssid)))
2986 continue;
2988 cgroup_for_each_live_child(child, cgrp) {
2989 struct cgroup_subsys_state *css = cgroup_css(child, ss);
2991 if (!css)
2992 continue;
2994 if (css_enable & (1 << ssid))
2995 kill_css(css);
2996 else
2997 cgroup_clear_dir(child, 1 << ssid);
3000 goto out_unlock;
3003 static int cgroup_populated_show(struct seq_file *seq, void *v)
3005 seq_printf(seq, "%d\n", (bool)seq_css(seq)->cgroup->populated_cnt);
3006 return 0;
3009 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
3010 size_t nbytes, loff_t off)
3012 struct cgroup *cgrp = of->kn->parent->priv;
3013 struct cftype *cft = of->kn->priv;
3014 struct cgroup_subsys_state *css;
3015 int ret;
3017 if (cft->write)
3018 return cft->write(of, buf, nbytes, off);
3021 * kernfs guarantees that a file isn't deleted with operations in
3022 * flight, which means that the matching css is and stays alive and
3023 * doesn't need to be pinned. The RCU locking is not necessary
3024 * either. It's just for the convenience of using cgroup_css().
3026 rcu_read_lock();
3027 css = cgroup_css(cgrp, cft->ss);
3028 rcu_read_unlock();
3030 if (cft->write_u64) {
3031 unsigned long long v;
3032 ret = kstrtoull(buf, 0, &v);
3033 if (!ret)
3034 ret = cft->write_u64(css, cft, v);
3035 } else if (cft->write_s64) {
3036 long long v;
3037 ret = kstrtoll(buf, 0, &v);
3038 if (!ret)
3039 ret = cft->write_s64(css, cft, v);
3040 } else {
3041 ret = -EINVAL;
3044 return ret ?: nbytes;
3047 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
3049 return seq_cft(seq)->seq_start(seq, ppos);
3052 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
3054 return seq_cft(seq)->seq_next(seq, v, ppos);
3057 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
3059 seq_cft(seq)->seq_stop(seq, v);
3062 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
3064 struct cftype *cft = seq_cft(m);
3065 struct cgroup_subsys_state *css = seq_css(m);
3067 if (cft->seq_show)
3068 return cft->seq_show(m, arg);
3070 if (cft->read_u64)
3071 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
3072 else if (cft->read_s64)
3073 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
3074 else
3075 return -EINVAL;
3076 return 0;
3079 static struct kernfs_ops cgroup_kf_single_ops = {
3080 .atomic_write_len = PAGE_SIZE,
3081 .write = cgroup_file_write,
3082 .seq_show = cgroup_seqfile_show,
3085 static struct kernfs_ops cgroup_kf_ops = {
3086 .atomic_write_len = PAGE_SIZE,
3087 .write = cgroup_file_write,
3088 .seq_start = cgroup_seqfile_start,
3089 .seq_next = cgroup_seqfile_next,
3090 .seq_stop = cgroup_seqfile_stop,
3091 .seq_show = cgroup_seqfile_show,
3095 * cgroup_rename - Only allow simple rename of directories in place.
3097 static int cgroup_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
3098 const char *new_name_str)
3100 struct cgroup *cgrp = kn->priv;
3101 int ret;
3103 if (kernfs_type(kn) != KERNFS_DIR)
3104 return -ENOTDIR;
3105 if (kn->parent != new_parent)
3106 return -EIO;
3109 * This isn't a proper migration and its usefulness is very
3110 * limited. Disallow on the default hierarchy.
3112 if (cgroup_on_dfl(cgrp))
3113 return -EPERM;
3116 * We're gonna grab cgroup_mutex which nests outside kernfs
3117 * active_ref. kernfs_rename() doesn't require active_ref
3118 * protection. Break them before grabbing cgroup_mutex.
3120 kernfs_break_active_protection(new_parent);
3121 kernfs_break_active_protection(kn);
3123 mutex_lock(&cgroup_mutex);
3125 ret = kernfs_rename(kn, new_parent, new_name_str);
3127 mutex_unlock(&cgroup_mutex);
3129 kernfs_unbreak_active_protection(kn);
3130 kernfs_unbreak_active_protection(new_parent);
3131 return ret;
3134 /* set uid and gid of cgroup dirs and files to that of the creator */
3135 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
3137 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
3138 .ia_uid = current_fsuid(),
3139 .ia_gid = current_fsgid(), };
3141 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
3142 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
3143 return 0;
3145 return kernfs_setattr(kn, &iattr);
3148 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
3150 char name[CGROUP_FILE_NAME_MAX];
3151 struct kernfs_node *kn;
3152 struct lock_class_key *key = NULL;
3153 int ret;
3155 #ifdef CONFIG_DEBUG_LOCK_ALLOC
3156 key = &cft->lockdep_key;
3157 #endif
3158 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
3159 cgroup_file_mode(cft), 0, cft->kf_ops, cft,
3160 NULL, key);
3161 if (IS_ERR(kn))
3162 return PTR_ERR(kn);
3164 ret = cgroup_kn_set_ugid(kn);
3165 if (ret) {
3166 kernfs_remove(kn);
3167 return ret;
3170 if (cft->write == cgroup_procs_write)
3171 cgrp->procs_kn = kn;
3172 else if (cft->seq_show == cgroup_populated_show)
3173 cgrp->populated_kn = kn;
3174 return 0;
3178 * cgroup_addrm_files - add or remove files to a cgroup directory
3179 * @cgrp: the target cgroup
3180 * @cfts: array of cftypes to be added
3181 * @is_add: whether to add or remove
3183 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
3184 * For removals, this function never fails. If addition fails, this
3185 * function doesn't remove files already added. The caller is responsible
3186 * for cleaning up.
3188 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
3189 bool is_add)
3191 struct cftype *cft;
3192 int ret;
3194 lockdep_assert_held(&cgroup_mutex);
3196 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3197 /* does cft->flags tell us to skip this file on @cgrp? */
3198 if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
3199 continue;
3200 if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
3201 continue;
3202 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
3203 continue;
3204 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
3205 continue;
3207 if (is_add) {
3208 ret = cgroup_add_file(cgrp, cft);
3209 if (ret) {
3210 pr_warn("%s: failed to add %s, err=%d\n",
3211 __func__, cft->name, ret);
3212 return ret;
3214 } else {
3215 cgroup_rm_file(cgrp, cft);
3218 return 0;
3221 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
3223 LIST_HEAD(pending);
3224 struct cgroup_subsys *ss = cfts[0].ss;
3225 struct cgroup *root = &ss->root->cgrp;
3226 struct cgroup_subsys_state *css;
3227 int ret = 0;
3229 lockdep_assert_held(&cgroup_mutex);
3231 /* add/rm files for all cgroups created before */
3232 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
3233 struct cgroup *cgrp = css->cgroup;
3235 if (cgroup_is_dead(cgrp))
3236 continue;
3238 ret = cgroup_addrm_files(cgrp, cfts, is_add);
3239 if (ret)
3240 break;
3243 if (is_add && !ret)
3244 kernfs_activate(root->kn);
3245 return ret;
3248 static void cgroup_exit_cftypes(struct cftype *cfts)
3250 struct cftype *cft;
3252 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3253 /* free copy for custom atomic_write_len, see init_cftypes() */
3254 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
3255 kfree(cft->kf_ops);
3256 cft->kf_ops = NULL;
3257 cft->ss = NULL;
3259 /* revert flags set by cgroup core while adding @cfts */
3260 cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL);
3264 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3266 struct cftype *cft;
3268 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3269 struct kernfs_ops *kf_ops;
3271 WARN_ON(cft->ss || cft->kf_ops);
3273 if (cft->seq_start)
3274 kf_ops = &cgroup_kf_ops;
3275 else
3276 kf_ops = &cgroup_kf_single_ops;
3279 * Ugh... if @cft wants a custom max_write_len, we need to
3280 * make a copy of kf_ops to set its atomic_write_len.
3282 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
3283 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
3284 if (!kf_ops) {
3285 cgroup_exit_cftypes(cfts);
3286 return -ENOMEM;
3288 kf_ops->atomic_write_len = cft->max_write_len;
3291 cft->kf_ops = kf_ops;
3292 cft->ss = ss;
3295 return 0;
3298 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
3300 lockdep_assert_held(&cgroup_mutex);
3302 if (!cfts || !cfts[0].ss)
3303 return -ENOENT;
3305 list_del(&cfts->node);
3306 cgroup_apply_cftypes(cfts, false);
3307 cgroup_exit_cftypes(cfts);
3308 return 0;
3312 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
3313 * @cfts: zero-length name terminated array of cftypes
3315 * Unregister @cfts. Files described by @cfts are removed from all
3316 * existing cgroups and all future cgroups won't have them either. This
3317 * function can be called anytime whether @cfts' subsys is attached or not.
3319 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
3320 * registered.
3322 int cgroup_rm_cftypes(struct cftype *cfts)
3324 int ret;
3326 mutex_lock(&cgroup_mutex);
3327 ret = cgroup_rm_cftypes_locked(cfts);
3328 mutex_unlock(&cgroup_mutex);
3329 return ret;
3333 * cgroup_add_cftypes - add an array of cftypes to a subsystem
3334 * @ss: target cgroup subsystem
3335 * @cfts: zero-length name terminated array of cftypes
3337 * Register @cfts to @ss. Files described by @cfts are created for all
3338 * existing cgroups to which @ss is attached and all future cgroups will
3339 * have them too. This function can be called anytime whether @ss is
3340 * attached or not.
3342 * Returns 0 on successful registration, -errno on failure. Note that this
3343 * function currently returns 0 as long as @cfts registration is successful
3344 * even if some file creation attempts on existing cgroups fail.
3346 static int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3348 int ret;
3350 if (ss->disabled)
3351 return 0;
3353 if (!cfts || cfts[0].name[0] == '\0')
3354 return 0;
3356 ret = cgroup_init_cftypes(ss, cfts);
3357 if (ret)
3358 return ret;
3360 mutex_lock(&cgroup_mutex);
3362 list_add_tail(&cfts->node, &ss->cfts);
3363 ret = cgroup_apply_cftypes(cfts, true);
3364 if (ret)
3365 cgroup_rm_cftypes_locked(cfts);
3367 mutex_unlock(&cgroup_mutex);
3368 return ret;
3372 * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
3373 * @ss: target cgroup subsystem
3374 * @cfts: zero-length name terminated array of cftypes
3376 * Similar to cgroup_add_cftypes() but the added files are only used for
3377 * the default hierarchy.
3379 int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3381 struct cftype *cft;
3383 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3384 cft->flags |= __CFTYPE_ONLY_ON_DFL;
3385 return cgroup_add_cftypes(ss, cfts);
3389 * cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies
3390 * @ss: target cgroup subsystem
3391 * @cfts: zero-length name terminated array of cftypes
3393 * Similar to cgroup_add_cftypes() but the added files are only used for
3394 * the legacy hierarchies.
3396 int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3398 struct cftype *cft;
3401 * If legacy_flies_on_dfl, we want to show the legacy files on the
3402 * dfl hierarchy but iff the target subsystem hasn't been updated
3403 * for the dfl hierarchy yet.
3405 if (!cgroup_legacy_files_on_dfl ||
3406 ss->dfl_cftypes != ss->legacy_cftypes) {
3407 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3408 cft->flags |= __CFTYPE_NOT_ON_DFL;
3411 return cgroup_add_cftypes(ss, cfts);
3415 * cgroup_task_count - count the number of tasks in a cgroup.
3416 * @cgrp: the cgroup in question
3418 * Return the number of tasks in the cgroup.
3420 static int cgroup_task_count(const struct cgroup *cgrp)
3422 int count = 0;
3423 struct cgrp_cset_link *link;
3425 down_read(&css_set_rwsem);
3426 list_for_each_entry(link, &cgrp->cset_links, cset_link)
3427 count += atomic_read(&link->cset->refcount);
3428 up_read(&css_set_rwsem);
3429 return count;
3433 * css_next_child - find the next child of a given css
3434 * @pos: the current position (%NULL to initiate traversal)
3435 * @parent: css whose children to walk
3437 * This function returns the next child of @parent and should be called
3438 * under either cgroup_mutex or RCU read lock. The only requirement is
3439 * that @parent and @pos are accessible. The next sibling is guaranteed to
3440 * be returned regardless of their states.
3442 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3443 * css which finished ->css_online() is guaranteed to be visible in the
3444 * future iterations and will stay visible until the last reference is put.
3445 * A css which hasn't finished ->css_online() or already finished
3446 * ->css_offline() may show up during traversal. It's each subsystem's
3447 * responsibility to synchronize against on/offlining.
3449 struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
3450 struct cgroup_subsys_state *parent)
3452 struct cgroup_subsys_state *next;
3454 cgroup_assert_mutex_or_rcu_locked();
3457 * @pos could already have been unlinked from the sibling list.
3458 * Once a cgroup is removed, its ->sibling.next is no longer
3459 * updated when its next sibling changes. CSS_RELEASED is set when
3460 * @pos is taken off list, at which time its next pointer is valid,
3461 * and, as releases are serialized, the one pointed to by the next
3462 * pointer is guaranteed to not have started release yet. This
3463 * implies that if we observe !CSS_RELEASED on @pos in this RCU
3464 * critical section, the one pointed to by its next pointer is
3465 * guaranteed to not have finished its RCU grace period even if we
3466 * have dropped rcu_read_lock() inbetween iterations.
3468 * If @pos has CSS_RELEASED set, its next pointer can't be
3469 * dereferenced; however, as each css is given a monotonically
3470 * increasing unique serial number and always appended to the
3471 * sibling list, the next one can be found by walking the parent's
3472 * children until the first css with higher serial number than
3473 * @pos's. While this path can be slower, it happens iff iteration
3474 * races against release and the race window is very small.
3476 if (!pos) {
3477 next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
3478 } else if (likely(!(pos->flags & CSS_RELEASED))) {
3479 next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
3480 } else {
3481 list_for_each_entry_rcu(next, &parent->children, sibling)
3482 if (next->serial_nr > pos->serial_nr)
3483 break;
3487 * @next, if not pointing to the head, can be dereferenced and is
3488 * the next sibling.
3490 if (&next->sibling != &parent->children)
3491 return next;
3492 return NULL;
3496 * css_next_descendant_pre - find the next descendant for pre-order walk
3497 * @pos: the current position (%NULL to initiate traversal)
3498 * @root: css whose descendants to walk
3500 * To be used by css_for_each_descendant_pre(). Find the next descendant
3501 * to visit for pre-order traversal of @root's descendants. @root is
3502 * included in the iteration and the first node to be visited.
3504 * While this function requires cgroup_mutex or RCU read locking, it
3505 * doesn't require the whole traversal to be contained in a single critical
3506 * section. This function will return the correct next descendant as long
3507 * as both @pos and @root are accessible and @pos is a descendant of @root.
3509 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3510 * css which finished ->css_online() is guaranteed to be visible in the
3511 * future iterations and will stay visible until the last reference is put.
3512 * A css which hasn't finished ->css_online() or already finished
3513 * ->css_offline() may show up during traversal. It's each subsystem's
3514 * responsibility to synchronize against on/offlining.
3516 struct cgroup_subsys_state *
3517 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3518 struct cgroup_subsys_state *root)
3520 struct cgroup_subsys_state *next;
3522 cgroup_assert_mutex_or_rcu_locked();
3524 /* if first iteration, visit @root */
3525 if (!pos)
3526 return root;
3528 /* visit the first child if exists */
3529 next = css_next_child(NULL, pos);
3530 if (next)
3531 return next;
3533 /* no child, visit my or the closest ancestor's next sibling */
3534 while (pos != root) {
3535 next = css_next_child(pos, pos->parent);
3536 if (next)
3537 return next;
3538 pos = pos->parent;
3541 return NULL;
3545 * css_rightmost_descendant - return the rightmost descendant of a css
3546 * @pos: css of interest
3548 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3549 * is returned. This can be used during pre-order traversal to skip
3550 * subtree of @pos.
3552 * While this function requires cgroup_mutex or RCU read locking, it
3553 * doesn't require the whole traversal to be contained in a single critical
3554 * section. This function will return the correct rightmost descendant as
3555 * long as @pos is accessible.
3557 struct cgroup_subsys_state *
3558 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3560 struct cgroup_subsys_state *last, *tmp;
3562 cgroup_assert_mutex_or_rcu_locked();
3564 do {
3565 last = pos;
3566 /* ->prev isn't RCU safe, walk ->next till the end */
3567 pos = NULL;
3568 css_for_each_child(tmp, last)
3569 pos = tmp;
3570 } while (pos);
3572 return last;
3575 static struct cgroup_subsys_state *
3576 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3578 struct cgroup_subsys_state *last;
3580 do {
3581 last = pos;
3582 pos = css_next_child(NULL, pos);
3583 } while (pos);
3585 return last;
3589 * css_next_descendant_post - find the next descendant for post-order walk
3590 * @pos: the current position (%NULL to initiate traversal)
3591 * @root: css whose descendants to walk
3593 * To be used by css_for_each_descendant_post(). Find the next descendant
3594 * to visit for post-order traversal of @root's descendants. @root is
3595 * included in the iteration and the last node to be visited.
3597 * While this function requires cgroup_mutex or RCU read locking, it
3598 * doesn't require the whole traversal to be contained in a single critical
3599 * section. This function will return the correct next descendant as long
3600 * as both @pos and @cgroup are accessible and @pos is a descendant of
3601 * @cgroup.
3603 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3604 * css which finished ->css_online() is guaranteed to be visible in the
3605 * future iterations and will stay visible until the last reference is put.
3606 * A css which hasn't finished ->css_online() or already finished
3607 * ->css_offline() may show up during traversal. It's each subsystem's
3608 * responsibility to synchronize against on/offlining.
3610 struct cgroup_subsys_state *
3611 css_next_descendant_post(struct cgroup_subsys_state *pos,
3612 struct cgroup_subsys_state *root)
3614 struct cgroup_subsys_state *next;
3616 cgroup_assert_mutex_or_rcu_locked();
3618 /* if first iteration, visit leftmost descendant which may be @root */
3619 if (!pos)
3620 return css_leftmost_descendant(root);
3622 /* if we visited @root, we're done */
3623 if (pos == root)
3624 return NULL;
3626 /* if there's an unvisited sibling, visit its leftmost descendant */
3627 next = css_next_child(pos, pos->parent);
3628 if (next)
3629 return css_leftmost_descendant(next);
3631 /* no sibling left, visit parent */
3632 return pos->parent;
3636 * css_has_online_children - does a css have online children
3637 * @css: the target css
3639 * Returns %true if @css has any online children; otherwise, %false. This
3640 * function can be called from any context but the caller is responsible
3641 * for synchronizing against on/offlining as necessary.
3643 bool css_has_online_children(struct cgroup_subsys_state *css)
3645 struct cgroup_subsys_state *child;
3646 bool ret = false;
3648 rcu_read_lock();
3649 css_for_each_child(child, css) {
3650 if (child->flags & CSS_ONLINE) {
3651 ret = true;
3652 break;
3655 rcu_read_unlock();
3656 return ret;
3660 * css_advance_task_iter - advance a task itererator to the next css_set
3661 * @it: the iterator to advance
3663 * Advance @it to the next css_set to walk.
3665 static void css_advance_task_iter(struct css_task_iter *it)
3667 struct list_head *l = it->cset_pos;
3668 struct cgrp_cset_link *link;
3669 struct css_set *cset;
3671 /* Advance to the next non-empty css_set */
3672 do {
3673 l = l->next;
3674 if (l == it->cset_head) {
3675 it->cset_pos = NULL;
3676 return;
3679 if (it->ss) {
3680 cset = container_of(l, struct css_set,
3681 e_cset_node[it->ss->id]);
3682 } else {
3683 link = list_entry(l, struct cgrp_cset_link, cset_link);
3684 cset = link->cset;
3686 } while (list_empty(&cset->tasks) && list_empty(&cset->mg_tasks));
3688 it->cset_pos = l;
3690 if (!list_empty(&cset->tasks))
3691 it->task_pos = cset->tasks.next;
3692 else
3693 it->task_pos = cset->mg_tasks.next;
3695 it->tasks_head = &cset->tasks;
3696 it->mg_tasks_head = &cset->mg_tasks;
3700 * css_task_iter_start - initiate task iteration
3701 * @css: the css to walk tasks of
3702 * @it: the task iterator to use
3704 * Initiate iteration through the tasks of @css. The caller can call
3705 * css_task_iter_next() to walk through the tasks until the function
3706 * returns NULL. On completion of iteration, css_task_iter_end() must be
3707 * called.
3709 * Note that this function acquires a lock which is released when the
3710 * iteration finishes. The caller can't sleep while iteration is in
3711 * progress.
3713 void css_task_iter_start(struct cgroup_subsys_state *css,
3714 struct css_task_iter *it)
3715 __acquires(css_set_rwsem)
3717 /* no one should try to iterate before mounting cgroups */
3718 WARN_ON_ONCE(!use_task_css_set_links);
3720 down_read(&css_set_rwsem);
3722 it->ss = css->ss;
3724 if (it->ss)
3725 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
3726 else
3727 it->cset_pos = &css->cgroup->cset_links;
3729 it->cset_head = it->cset_pos;
3731 css_advance_task_iter(it);
3735 * css_task_iter_next - return the next task for the iterator
3736 * @it: the task iterator being iterated
3738 * The "next" function for task iteration. @it should have been
3739 * initialized via css_task_iter_start(). Returns NULL when the iteration
3740 * reaches the end.
3742 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3744 struct task_struct *res;
3745 struct list_head *l = it->task_pos;
3747 /* If the iterator cg is NULL, we have no tasks */
3748 if (!it->cset_pos)
3749 return NULL;
3750 res = list_entry(l, struct task_struct, cg_list);
3753 * Advance iterator to find next entry. cset->tasks is consumed
3754 * first and then ->mg_tasks. After ->mg_tasks, we move onto the
3755 * next cset.
3757 l = l->next;
3759 if (l == it->tasks_head)
3760 l = it->mg_tasks_head->next;
3762 if (l == it->mg_tasks_head)
3763 css_advance_task_iter(it);
3764 else
3765 it->task_pos = l;
3767 return res;
3771 * css_task_iter_end - finish task iteration
3772 * @it: the task iterator to finish
3774 * Finish task iteration started by css_task_iter_start().
3776 void css_task_iter_end(struct css_task_iter *it)
3777 __releases(css_set_rwsem)
3779 up_read(&css_set_rwsem);
3783 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3784 * @to: cgroup to which the tasks will be moved
3785 * @from: cgroup in which the tasks currently reside
3787 * Locking rules between cgroup_post_fork() and the migration path
3788 * guarantee that, if a task is forking while being migrated, the new child
3789 * is guaranteed to be either visible in the source cgroup after the
3790 * parent's migration is complete or put into the target cgroup. No task
3791 * can slip out of migration through forking.
3793 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3795 LIST_HEAD(preloaded_csets);
3796 struct cgrp_cset_link *link;
3797 struct css_task_iter it;
3798 struct task_struct *task;
3799 int ret;
3801 mutex_lock(&cgroup_mutex);
3803 /* all tasks in @from are being moved, all csets are source */
3804 down_read(&css_set_rwsem);
3805 list_for_each_entry(link, &from->cset_links, cset_link)
3806 cgroup_migrate_add_src(link->cset, to, &preloaded_csets);
3807 up_read(&css_set_rwsem);
3809 ret = cgroup_migrate_prepare_dst(to, &preloaded_csets);
3810 if (ret)
3811 goto out_err;
3814 * Migrate tasks one-by-one until @form is empty. This fails iff
3815 * ->can_attach() fails.
3817 do {
3818 css_task_iter_start(&from->self, &it);
3819 task = css_task_iter_next(&it);
3820 if (task)
3821 get_task_struct(task);
3822 css_task_iter_end(&it);
3824 if (task) {
3825 ret = cgroup_migrate(to, task, false);
3826 put_task_struct(task);
3828 } while (task && !ret);
3829 out_err:
3830 cgroup_migrate_finish(&preloaded_csets);
3831 mutex_unlock(&cgroup_mutex);
3832 return ret;
3836 * Stuff for reading the 'tasks'/'procs' files.
3838 * Reading this file can return large amounts of data if a cgroup has
3839 * *lots* of attached tasks. So it may need several calls to read(),
3840 * but we cannot guarantee that the information we produce is correct
3841 * unless we produce it entirely atomically.
3845 /* which pidlist file are we talking about? */
3846 enum cgroup_filetype {
3847 CGROUP_FILE_PROCS,
3848 CGROUP_FILE_TASKS,
3852 * A pidlist is a list of pids that virtually represents the contents of one
3853 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3854 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3855 * to the cgroup.
3857 struct cgroup_pidlist {
3859 * used to find which pidlist is wanted. doesn't change as long as
3860 * this particular list stays in the list.
3862 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3863 /* array of xids */
3864 pid_t *list;
3865 /* how many elements the above list has */
3866 int length;
3867 /* each of these stored in a list by its cgroup */
3868 struct list_head links;
3869 /* pointer to the cgroup we belong to, for list removal purposes */
3870 struct cgroup *owner;
3871 /* for delayed destruction */
3872 struct delayed_work destroy_dwork;
3876 * The following two functions "fix" the issue where there are more pids
3877 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3878 * TODO: replace with a kernel-wide solution to this problem
3880 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3881 static void *pidlist_allocate(int count)
3883 if (PIDLIST_TOO_LARGE(count))
3884 return vmalloc(count * sizeof(pid_t));
3885 else
3886 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3889 static void pidlist_free(void *p)
3891 kvfree(p);
3895 * Used to destroy all pidlists lingering waiting for destroy timer. None
3896 * should be left afterwards.
3898 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
3900 struct cgroup_pidlist *l, *tmp_l;
3902 mutex_lock(&cgrp->pidlist_mutex);
3903 list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
3904 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
3905 mutex_unlock(&cgrp->pidlist_mutex);
3907 flush_workqueue(cgroup_pidlist_destroy_wq);
3908 BUG_ON(!list_empty(&cgrp->pidlists));
3911 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
3913 struct delayed_work *dwork = to_delayed_work(work);
3914 struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
3915 destroy_dwork);
3916 struct cgroup_pidlist *tofree = NULL;
3918 mutex_lock(&l->owner->pidlist_mutex);
3921 * Destroy iff we didn't get queued again. The state won't change
3922 * as destroy_dwork can only be queued while locked.
3924 if (!delayed_work_pending(dwork)) {
3925 list_del(&l->links);
3926 pidlist_free(l->list);
3927 put_pid_ns(l->key.ns);
3928 tofree = l;
3931 mutex_unlock(&l->owner->pidlist_mutex);
3932 kfree(tofree);
3936 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3937 * Returns the number of unique elements.
3939 static int pidlist_uniq(pid_t *list, int length)
3941 int src, dest = 1;
3944 * we presume the 0th element is unique, so i starts at 1. trivial
3945 * edge cases first; no work needs to be done for either
3947 if (length == 0 || length == 1)
3948 return length;
3949 /* src and dest walk down the list; dest counts unique elements */
3950 for (src = 1; src < length; src++) {
3951 /* find next unique element */
3952 while (list[src] == list[src-1]) {
3953 src++;
3954 if (src == length)
3955 goto after;
3957 /* dest always points to where the next unique element goes */
3958 list[dest] = list[src];
3959 dest++;
3961 after:
3962 return dest;
3966 * The two pid files - task and cgroup.procs - guaranteed that the result
3967 * is sorted, which forced this whole pidlist fiasco. As pid order is
3968 * different per namespace, each namespace needs differently sorted list,
3969 * making it impossible to use, for example, single rbtree of member tasks
3970 * sorted by task pointer. As pidlists can be fairly large, allocating one
3971 * per open file is dangerous, so cgroup had to implement shared pool of
3972 * pidlists keyed by cgroup and namespace.
3974 * All this extra complexity was caused by the original implementation
3975 * committing to an entirely unnecessary property. In the long term, we
3976 * want to do away with it. Explicitly scramble sort order if on the
3977 * default hierarchy so that no such expectation exists in the new
3978 * interface.
3980 * Scrambling is done by swapping every two consecutive bits, which is
3981 * non-identity one-to-one mapping which disturbs sort order sufficiently.
3983 static pid_t pid_fry(pid_t pid)
3985 unsigned a = pid & 0x55555555;
3986 unsigned b = pid & 0xAAAAAAAA;
3988 return (a << 1) | (b >> 1);
3991 static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
3993 if (cgroup_on_dfl(cgrp))
3994 return pid_fry(pid);
3995 else
3996 return pid;
3999 static int cmppid(const void *a, const void *b)
4001 return *(pid_t *)a - *(pid_t *)b;
4004 static int fried_cmppid(const void *a, const void *b)
4006 return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
4009 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
4010 enum cgroup_filetype type)
4012 struct cgroup_pidlist *l;
4013 /* don't need task_nsproxy() if we're looking at ourself */
4014 struct pid_namespace *ns = task_active_pid_ns(current);
4016 lockdep_assert_held(&cgrp->pidlist_mutex);
4018 list_for_each_entry(l, &cgrp->pidlists, links)
4019 if (l->key.type == type && l->key.ns == ns)
4020 return l;
4021 return NULL;
4025 * find the appropriate pidlist for our purpose (given procs vs tasks)
4026 * returns with the lock on that pidlist already held, and takes care
4027 * of the use count, or returns NULL with no locks held if we're out of
4028 * memory.
4030 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
4031 enum cgroup_filetype type)
4033 struct cgroup_pidlist *l;
4035 lockdep_assert_held(&cgrp->pidlist_mutex);
4037 l = cgroup_pidlist_find(cgrp, type);
4038 if (l)
4039 return l;
4041 /* entry not found; create a new one */
4042 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
4043 if (!l)
4044 return l;
4046 INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
4047 l->key.type = type;
4048 /* don't need task_nsproxy() if we're looking at ourself */
4049 l->key.ns = get_pid_ns(task_active_pid_ns(current));
4050 l->owner = cgrp;
4051 list_add(&l->links, &cgrp->pidlists);
4052 return l;
4056 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
4058 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
4059 struct cgroup_pidlist **lp)
4061 pid_t *array;
4062 int length;
4063 int pid, n = 0; /* used for populating the array */
4064 struct css_task_iter it;
4065 struct task_struct *tsk;
4066 struct cgroup_pidlist *l;
4068 lockdep_assert_held(&cgrp->pidlist_mutex);
4071 * If cgroup gets more users after we read count, we won't have
4072 * enough space - tough. This race is indistinguishable to the
4073 * caller from the case that the additional cgroup users didn't
4074 * show up until sometime later on.
4076 length = cgroup_task_count(cgrp);
4077 array = pidlist_allocate(length);
4078 if (!array)
4079 return -ENOMEM;
4080 /* now, populate the array */
4081 css_task_iter_start(&cgrp->self, &it);
4082 while ((tsk = css_task_iter_next(&it))) {
4083 if (unlikely(n == length))
4084 break;
4085 /* get tgid or pid for procs or tasks file respectively */
4086 if (type == CGROUP_FILE_PROCS)
4087 pid = task_tgid_vnr(tsk);
4088 else
4089 pid = task_pid_vnr(tsk);
4090 if (pid > 0) /* make sure to only use valid results */
4091 array[n++] = pid;
4093 css_task_iter_end(&it);
4094 length = n;
4095 /* now sort & (if procs) strip out duplicates */
4096 if (cgroup_on_dfl(cgrp))
4097 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
4098 else
4099 sort(array, length, sizeof(pid_t), cmppid, NULL);
4100 if (type == CGROUP_FILE_PROCS)
4101 length = pidlist_uniq(array, length);
4103 l = cgroup_pidlist_find_create(cgrp, type);
4104 if (!l) {
4105 pidlist_free(array);
4106 return -ENOMEM;
4109 /* store array, freeing old if necessary */
4110 pidlist_free(l->list);
4111 l->list = array;
4112 l->length = length;
4113 *lp = l;
4114 return 0;
4118 * cgroupstats_build - build and fill cgroupstats
4119 * @stats: cgroupstats to fill information into
4120 * @dentry: A dentry entry belonging to the cgroup for which stats have
4121 * been requested.
4123 * Build and fill cgroupstats so that taskstats can export it to user
4124 * space.
4126 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
4128 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
4129 struct cgroup *cgrp;
4130 struct css_task_iter it;
4131 struct task_struct *tsk;
4133 /* it should be kernfs_node belonging to cgroupfs and is a directory */
4134 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
4135 kernfs_type(kn) != KERNFS_DIR)
4136 return -EINVAL;
4138 mutex_lock(&cgroup_mutex);
4141 * We aren't being called from kernfs and there's no guarantee on
4142 * @kn->priv's validity. For this and css_tryget_online_from_dir(),
4143 * @kn->priv is RCU safe. Let's do the RCU dancing.
4145 rcu_read_lock();
4146 cgrp = rcu_dereference(kn->priv);
4147 if (!cgrp || cgroup_is_dead(cgrp)) {
4148 rcu_read_unlock();
4149 mutex_unlock(&cgroup_mutex);
4150 return -ENOENT;
4152 rcu_read_unlock();
4154 css_task_iter_start(&cgrp->self, &it);
4155 while ((tsk = css_task_iter_next(&it))) {
4156 switch (tsk->state) {
4157 case TASK_RUNNING:
4158 stats->nr_running++;
4159 break;
4160 case TASK_INTERRUPTIBLE:
4161 stats->nr_sleeping++;
4162 break;
4163 case TASK_UNINTERRUPTIBLE:
4164 stats->nr_uninterruptible++;
4165 break;
4166 case TASK_STOPPED:
4167 stats->nr_stopped++;
4168 break;
4169 default:
4170 if (delayacct_is_task_waiting_on_io(tsk))
4171 stats->nr_io_wait++;
4172 break;
4175 css_task_iter_end(&it);
4177 mutex_unlock(&cgroup_mutex);
4178 return 0;
4183 * seq_file methods for the tasks/procs files. The seq_file position is the
4184 * next pid to display; the seq_file iterator is a pointer to the pid
4185 * in the cgroup->l->list array.
4188 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
4191 * Initially we receive a position value that corresponds to
4192 * one more than the last pid shown (or 0 on the first call or
4193 * after a seek to the start). Use a binary-search to find the
4194 * next pid to display, if any
4196 struct kernfs_open_file *of = s->private;
4197 struct cgroup *cgrp = seq_css(s)->cgroup;
4198 struct cgroup_pidlist *l;
4199 enum cgroup_filetype type = seq_cft(s)->private;
4200 int index = 0, pid = *pos;
4201 int *iter, ret;
4203 mutex_lock(&cgrp->pidlist_mutex);
4206 * !NULL @of->priv indicates that this isn't the first start()
4207 * after open. If the matching pidlist is around, we can use that.
4208 * Look for it. Note that @of->priv can't be used directly. It
4209 * could already have been destroyed.
4211 if (of->priv)
4212 of->priv = cgroup_pidlist_find(cgrp, type);
4215 * Either this is the first start() after open or the matching
4216 * pidlist has been destroyed inbetween. Create a new one.
4218 if (!of->priv) {
4219 ret = pidlist_array_load(cgrp, type,
4220 (struct cgroup_pidlist **)&of->priv);
4221 if (ret)
4222 return ERR_PTR(ret);
4224 l = of->priv;
4226 if (pid) {
4227 int end = l->length;
4229 while (index < end) {
4230 int mid = (index + end) / 2;
4231 if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
4232 index = mid;
4233 break;
4234 } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
4235 index = mid + 1;
4236 else
4237 end = mid;
4240 /* If we're off the end of the array, we're done */
4241 if (index >= l->length)
4242 return NULL;
4243 /* Update the abstract position to be the actual pid that we found */
4244 iter = l->list + index;
4245 *pos = cgroup_pid_fry(cgrp, *iter);
4246 return iter;
4249 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
4251 struct kernfs_open_file *of = s->private;
4252 struct cgroup_pidlist *l = of->priv;
4254 if (l)
4255 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
4256 CGROUP_PIDLIST_DESTROY_DELAY);
4257 mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
4260 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
4262 struct kernfs_open_file *of = s->private;
4263 struct cgroup_pidlist *l = of->priv;
4264 pid_t *p = v;
4265 pid_t *end = l->list + l->length;
4267 * Advance to the next pid in the array. If this goes off the
4268 * end, we're done
4270 p++;
4271 if (p >= end) {
4272 return NULL;
4273 } else {
4274 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
4275 return p;
4279 static int cgroup_pidlist_show(struct seq_file *s, void *v)
4281 seq_printf(s, "%d\n", *(int *)v);
4283 return 0;
4286 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
4287 struct cftype *cft)
4289 return notify_on_release(css->cgroup);
4292 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
4293 struct cftype *cft, u64 val)
4295 if (val)
4296 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
4297 else
4298 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
4299 return 0;
4302 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
4303 struct cftype *cft)
4305 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4308 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
4309 struct cftype *cft, u64 val)
4311 if (val)
4312 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4313 else
4314 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4315 return 0;
4318 /* cgroup core interface files for the default hierarchy */
4319 static struct cftype cgroup_dfl_base_files[] = {
4321 .name = "cgroup.procs",
4322 .seq_start = cgroup_pidlist_start,
4323 .seq_next = cgroup_pidlist_next,
4324 .seq_stop = cgroup_pidlist_stop,
4325 .seq_show = cgroup_pidlist_show,
4326 .private = CGROUP_FILE_PROCS,
4327 .write = cgroup_procs_write,
4328 .mode = S_IRUGO | S_IWUSR,
4331 .name = "cgroup.controllers",
4332 .flags = CFTYPE_ONLY_ON_ROOT,
4333 .seq_show = cgroup_root_controllers_show,
4336 .name = "cgroup.controllers",
4337 .flags = CFTYPE_NOT_ON_ROOT,
4338 .seq_show = cgroup_controllers_show,
4341 .name = "cgroup.subtree_control",
4342 .seq_show = cgroup_subtree_control_show,
4343 .write = cgroup_subtree_control_write,
4346 .name = "cgroup.populated",
4347 .flags = CFTYPE_NOT_ON_ROOT,
4348 .seq_show = cgroup_populated_show,
4350 { } /* terminate */
4353 /* cgroup core interface files for the legacy hierarchies */
4354 static struct cftype cgroup_legacy_base_files[] = {
4356 .name = "cgroup.procs",
4357 .seq_start = cgroup_pidlist_start,
4358 .seq_next = cgroup_pidlist_next,
4359 .seq_stop = cgroup_pidlist_stop,
4360 .seq_show = cgroup_pidlist_show,
4361 .private = CGROUP_FILE_PROCS,
4362 .write = cgroup_procs_write,
4363 .mode = S_IRUGO | S_IWUSR,
4366 .name = "cgroup.clone_children",
4367 .read_u64 = cgroup_clone_children_read,
4368 .write_u64 = cgroup_clone_children_write,
4371 .name = "cgroup.sane_behavior",
4372 .flags = CFTYPE_ONLY_ON_ROOT,
4373 .seq_show = cgroup_sane_behavior_show,
4376 .name = "tasks",
4377 .seq_start = cgroup_pidlist_start,
4378 .seq_next = cgroup_pidlist_next,
4379 .seq_stop = cgroup_pidlist_stop,
4380 .seq_show = cgroup_pidlist_show,
4381 .private = CGROUP_FILE_TASKS,
4382 .write = cgroup_tasks_write,
4383 .mode = S_IRUGO | S_IWUSR,
4386 .name = "notify_on_release",
4387 .read_u64 = cgroup_read_notify_on_release,
4388 .write_u64 = cgroup_write_notify_on_release,
4391 .name = "release_agent",
4392 .flags = CFTYPE_ONLY_ON_ROOT,
4393 .seq_show = cgroup_release_agent_show,
4394 .write = cgroup_release_agent_write,
4395 .max_write_len = PATH_MAX - 1,
4397 { } /* terminate */
4401 * cgroup_populate_dir - create subsys files in a cgroup directory
4402 * @cgrp: target cgroup
4403 * @subsys_mask: mask of the subsystem ids whose files should be added
4405 * On failure, no file is added.
4407 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
4409 struct cgroup_subsys *ss;
4410 int i, ret = 0;
4412 /* process cftsets of each subsystem */
4413 for_each_subsys(ss, i) {
4414 struct cftype *cfts;
4416 if (!(subsys_mask & (1 << i)))
4417 continue;
4419 list_for_each_entry(cfts, &ss->cfts, node) {
4420 ret = cgroup_addrm_files(cgrp, cfts, true);
4421 if (ret < 0)
4422 goto err;
4425 return 0;
4426 err:
4427 cgroup_clear_dir(cgrp, subsys_mask);
4428 return ret;
4432 * css destruction is four-stage process.
4434 * 1. Destruction starts. Killing of the percpu_ref is initiated.
4435 * Implemented in kill_css().
4437 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4438 * and thus css_tryget_online() is guaranteed to fail, the css can be
4439 * offlined by invoking offline_css(). After offlining, the base ref is
4440 * put. Implemented in css_killed_work_fn().
4442 * 3. When the percpu_ref reaches zero, the only possible remaining
4443 * accessors are inside RCU read sections. css_release() schedules the
4444 * RCU callback.
4446 * 4. After the grace period, the css can be freed. Implemented in
4447 * css_free_work_fn().
4449 * It is actually hairier because both step 2 and 4 require process context
4450 * and thus involve punting to css->destroy_work adding two additional
4451 * steps to the already complex sequence.
4453 static void css_free_work_fn(struct work_struct *work)
4455 struct cgroup_subsys_state *css =
4456 container_of(work, struct cgroup_subsys_state, destroy_work);
4457 struct cgroup_subsys *ss = css->ss;
4458 struct cgroup *cgrp = css->cgroup;
4460 percpu_ref_exit(&css->refcnt);
4462 if (ss) {
4463 /* css free path */
4464 int id = css->id;
4466 if (css->parent)
4467 css_put(css->parent);
4469 ss->css_free(css);
4470 cgroup_idr_remove(&ss->css_idr, id);
4471 cgroup_put(cgrp);
4472 } else {
4473 /* cgroup free path */
4474 atomic_dec(&cgrp->root->nr_cgrps);
4475 cgroup_pidlist_destroy_all(cgrp);
4476 cancel_work_sync(&cgrp->release_agent_work);
4478 if (cgroup_parent(cgrp)) {
4480 * We get a ref to the parent, and put the ref when
4481 * this cgroup is being freed, so it's guaranteed
4482 * that the parent won't be destroyed before its
4483 * children.
4485 cgroup_put(cgroup_parent(cgrp));
4486 kernfs_put(cgrp->kn);
4487 kfree(cgrp);
4488 } else {
4490 * This is root cgroup's refcnt reaching zero,
4491 * which indicates that the root should be
4492 * released.
4494 cgroup_destroy_root(cgrp->root);
4499 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4501 struct cgroup_subsys_state *css =
4502 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4504 INIT_WORK(&css->destroy_work, css_free_work_fn);
4505 queue_work(cgroup_destroy_wq, &css->destroy_work);
4508 static void css_release_work_fn(struct work_struct *work)
4510 struct cgroup_subsys_state *css =
4511 container_of(work, struct cgroup_subsys_state, destroy_work);
4512 struct cgroup_subsys *ss = css->ss;
4513 struct cgroup *cgrp = css->cgroup;
4515 mutex_lock(&cgroup_mutex);
4517 css->flags |= CSS_RELEASED;
4518 list_del_rcu(&css->sibling);
4520 if (ss) {
4521 /* css release path */
4522 cgroup_idr_replace(&ss->css_idr, NULL, css->id);
4523 if (ss->css_released)
4524 ss->css_released(css);
4525 } else {
4526 /* cgroup release path */
4527 cgroup_idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4528 cgrp->id = -1;
4531 * There are two control paths which try to determine
4532 * cgroup from dentry without going through kernfs -
4533 * cgroupstats_build() and css_tryget_online_from_dir().
4534 * Those are supported by RCU protecting clearing of
4535 * cgrp->kn->priv backpointer.
4537 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv, NULL);
4540 mutex_unlock(&cgroup_mutex);
4542 call_rcu(&css->rcu_head, css_free_rcu_fn);
4545 static void css_release(struct percpu_ref *ref)
4547 struct cgroup_subsys_state *css =
4548 container_of(ref, struct cgroup_subsys_state, refcnt);
4550 INIT_WORK(&css->destroy_work, css_release_work_fn);
4551 queue_work(cgroup_destroy_wq, &css->destroy_work);
4554 static void init_and_link_css(struct cgroup_subsys_state *css,
4555 struct cgroup_subsys *ss, struct cgroup *cgrp)
4557 lockdep_assert_held(&cgroup_mutex);
4559 cgroup_get(cgrp);
4561 memset(css, 0, sizeof(*css));
4562 css->cgroup = cgrp;
4563 css->ss = ss;
4564 INIT_LIST_HEAD(&css->sibling);
4565 INIT_LIST_HEAD(&css->children);
4566 css->serial_nr = css_serial_nr_next++;
4568 if (cgroup_parent(cgrp)) {
4569 css->parent = cgroup_css(cgroup_parent(cgrp), ss);
4570 css_get(css->parent);
4573 BUG_ON(cgroup_css(cgrp, ss));
4576 /* invoke ->css_online() on a new CSS and mark it online if successful */
4577 static int online_css(struct cgroup_subsys_state *css)
4579 struct cgroup_subsys *ss = css->ss;
4580 int ret = 0;
4582 lockdep_assert_held(&cgroup_mutex);
4584 if (ss->css_online)
4585 ret = ss->css_online(css);
4586 if (!ret) {
4587 css->flags |= CSS_ONLINE;
4588 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
4590 return ret;
4593 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4594 static void offline_css(struct cgroup_subsys_state *css)
4596 struct cgroup_subsys *ss = css->ss;
4598 lockdep_assert_held(&cgroup_mutex);
4600 if (!(css->flags & CSS_ONLINE))
4601 return;
4603 if (ss->css_offline)
4604 ss->css_offline(css);
4606 css->flags &= ~CSS_ONLINE;
4607 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
4609 wake_up_all(&css->cgroup->offline_waitq);
4613 * create_css - create a cgroup_subsys_state
4614 * @cgrp: the cgroup new css will be associated with
4615 * @ss: the subsys of new css
4616 * @visible: whether to create control knobs for the new css or not
4618 * Create a new css associated with @cgrp - @ss pair. On success, the new
4619 * css is online and installed in @cgrp with all interface files created if
4620 * @visible. Returns 0 on success, -errno on failure.
4622 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss,
4623 bool visible)
4625 struct cgroup *parent = cgroup_parent(cgrp);
4626 struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
4627 struct cgroup_subsys_state *css;
4628 int err;
4630 lockdep_assert_held(&cgroup_mutex);
4632 css = ss->css_alloc(parent_css);
4633 if (IS_ERR(css))
4634 return PTR_ERR(css);
4636 init_and_link_css(css, ss, cgrp);
4638 err = percpu_ref_init(&css->refcnt, css_release, 0, GFP_KERNEL);
4639 if (err)
4640 goto err_free_css;
4642 err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_NOWAIT);
4643 if (err < 0)
4644 goto err_free_percpu_ref;
4645 css->id = err;
4647 if (visible) {
4648 err = cgroup_populate_dir(cgrp, 1 << ss->id);
4649 if (err)
4650 goto err_free_id;
4653 /* @css is ready to be brought online now, make it visible */
4654 list_add_tail_rcu(&css->sibling, &parent_css->children);
4655 cgroup_idr_replace(&ss->css_idr, css, css->id);
4657 err = online_css(css);
4658 if (err)
4659 goto err_list_del;
4661 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4662 cgroup_parent(parent)) {
4663 pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4664 current->comm, current->pid, ss->name);
4665 if (!strcmp(ss->name, "memory"))
4666 pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
4667 ss->warned_broken_hierarchy = true;
4670 return 0;
4672 err_list_del:
4673 list_del_rcu(&css->sibling);
4674 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4675 err_free_id:
4676 cgroup_idr_remove(&ss->css_idr, css->id);
4677 err_free_percpu_ref:
4678 percpu_ref_exit(&css->refcnt);
4679 err_free_css:
4680 call_rcu(&css->rcu_head, css_free_rcu_fn);
4681 return err;
4684 static int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
4685 umode_t mode)
4687 struct cgroup *parent, *cgrp;
4688 struct cgroup_root *root;
4689 struct cgroup_subsys *ss;
4690 struct kernfs_node *kn;
4691 struct cftype *base_files;
4692 int ssid, ret;
4694 /* Do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable.
4696 if (strchr(name, '\n'))
4697 return -EINVAL;
4699 parent = cgroup_kn_lock_live(parent_kn);
4700 if (!parent)
4701 return -ENODEV;
4702 root = parent->root;
4704 /* allocate the cgroup and its ID, 0 is reserved for the root */
4705 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4706 if (!cgrp) {
4707 ret = -ENOMEM;
4708 goto out_unlock;
4711 ret = percpu_ref_init(&cgrp->self.refcnt, css_release, 0, GFP_KERNEL);
4712 if (ret)
4713 goto out_free_cgrp;
4716 * Temporarily set the pointer to NULL, so idr_find() won't return
4717 * a half-baked cgroup.
4719 cgrp->id = cgroup_idr_alloc(&root->cgroup_idr, NULL, 2, 0, GFP_NOWAIT);
4720 if (cgrp->id < 0) {
4721 ret = -ENOMEM;
4722 goto out_cancel_ref;
4725 init_cgroup_housekeeping(cgrp);
4727 cgrp->self.parent = &parent->self;
4728 cgrp->root = root;
4730 if (notify_on_release(parent))
4731 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4733 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4734 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4736 /* create the directory */
4737 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
4738 if (IS_ERR(kn)) {
4739 ret = PTR_ERR(kn);
4740 goto out_free_id;
4742 cgrp->kn = kn;
4745 * This extra ref will be put in cgroup_free_fn() and guarantees
4746 * that @cgrp->kn is always accessible.
4748 kernfs_get(kn);
4750 cgrp->self.serial_nr = css_serial_nr_next++;
4752 /* allocation complete, commit to creation */
4753 list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
4754 atomic_inc(&root->nr_cgrps);
4755 cgroup_get(parent);
4758 * @cgrp is now fully operational. If something fails after this
4759 * point, it'll be released via the normal destruction path.
4761 cgroup_idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4763 ret = cgroup_kn_set_ugid(kn);
4764 if (ret)
4765 goto out_destroy;
4767 if (cgroup_on_dfl(cgrp))
4768 base_files = cgroup_dfl_base_files;
4769 else
4770 base_files = cgroup_legacy_base_files;
4772 ret = cgroup_addrm_files(cgrp, base_files, true);
4773 if (ret)
4774 goto out_destroy;
4776 /* let's create and online css's */
4777 for_each_subsys(ss, ssid) {
4778 if (parent->child_subsys_mask & (1 << ssid)) {
4779 ret = create_css(cgrp, ss,
4780 parent->subtree_control & (1 << ssid));
4781 if (ret)
4782 goto out_destroy;
4787 * On the default hierarchy, a child doesn't automatically inherit
4788 * subtree_control from the parent. Each is configured manually.
4790 if (!cgroup_on_dfl(cgrp)) {
4791 cgrp->subtree_control = parent->subtree_control;
4792 cgroup_refresh_child_subsys_mask(cgrp);
4795 kernfs_activate(kn);
4797 ret = 0;
4798 goto out_unlock;
4800 out_free_id:
4801 cgroup_idr_remove(&root->cgroup_idr, cgrp->id);
4802 out_cancel_ref:
4803 percpu_ref_exit(&cgrp->self.refcnt);
4804 out_free_cgrp:
4805 kfree(cgrp);
4806 out_unlock:
4807 cgroup_kn_unlock(parent_kn);
4808 return ret;
4810 out_destroy:
4811 cgroup_destroy_locked(cgrp);
4812 goto out_unlock;
4816 * This is called when the refcnt of a css is confirmed to be killed.
4817 * css_tryget_online() is now guaranteed to fail. Tell the subsystem to
4818 * initate destruction and put the css ref from kill_css().
4820 static void css_killed_work_fn(struct work_struct *work)
4822 struct cgroup_subsys_state *css =
4823 container_of(work, struct cgroup_subsys_state, destroy_work);
4825 mutex_lock(&cgroup_mutex);
4826 offline_css(css);
4827 mutex_unlock(&cgroup_mutex);
4829 css_put(css);
4832 /* css kill confirmation processing requires process context, bounce */
4833 static void css_killed_ref_fn(struct percpu_ref *ref)
4835 struct cgroup_subsys_state *css =
4836 container_of(ref, struct cgroup_subsys_state, refcnt);
4838 INIT_WORK(&css->destroy_work, css_killed_work_fn);
4839 queue_work(cgroup_destroy_wq, &css->destroy_work);
4843 * kill_css - destroy a css
4844 * @css: css to destroy
4846 * This function initiates destruction of @css by removing cgroup interface
4847 * files and putting its base reference. ->css_offline() will be invoked
4848 * asynchronously once css_tryget_online() is guaranteed to fail and when
4849 * the reference count reaches zero, @css will be released.
4851 static void kill_css(struct cgroup_subsys_state *css)
4853 lockdep_assert_held(&cgroup_mutex);
4856 * This must happen before css is disassociated with its cgroup.
4857 * See seq_css() for details.
4859 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4862 * Killing would put the base ref, but we need to keep it alive
4863 * until after ->css_offline().
4865 css_get(css);
4868 * cgroup core guarantees that, by the time ->css_offline() is
4869 * invoked, no new css reference will be given out via
4870 * css_tryget_online(). We can't simply call percpu_ref_kill() and
4871 * proceed to offlining css's because percpu_ref_kill() doesn't
4872 * guarantee that the ref is seen as killed on all CPUs on return.
4874 * Use percpu_ref_kill_and_confirm() to get notifications as each
4875 * css is confirmed to be seen as killed on all CPUs.
4877 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4881 * cgroup_destroy_locked - the first stage of cgroup destruction
4882 * @cgrp: cgroup to be destroyed
4884 * css's make use of percpu refcnts whose killing latency shouldn't be
4885 * exposed to userland and are RCU protected. Also, cgroup core needs to
4886 * guarantee that css_tryget_online() won't succeed by the time
4887 * ->css_offline() is invoked. To satisfy all the requirements,
4888 * destruction is implemented in the following two steps.
4890 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4891 * userland visible parts and start killing the percpu refcnts of
4892 * css's. Set up so that the next stage will be kicked off once all
4893 * the percpu refcnts are confirmed to be killed.
4895 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4896 * rest of destruction. Once all cgroup references are gone, the
4897 * cgroup is RCU-freed.
4899 * This function implements s1. After this step, @cgrp is gone as far as
4900 * the userland is concerned and a new cgroup with the same name may be
4901 * created. As cgroup doesn't care about the names internally, this
4902 * doesn't cause any problem.
4904 static int cgroup_destroy_locked(struct cgroup *cgrp)
4905 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4907 struct cgroup_subsys_state *css;
4908 bool empty;
4909 int ssid;
4911 lockdep_assert_held(&cgroup_mutex);
4914 * css_set_rwsem synchronizes access to ->cset_links and prevents
4915 * @cgrp from being removed while put_css_set() is in progress.
4917 down_read(&css_set_rwsem);
4918 empty = list_empty(&cgrp->cset_links);
4919 up_read(&css_set_rwsem);
4920 if (!empty)
4921 return -EBUSY;
4924 * Make sure there's no live children. We can't test emptiness of
4925 * ->self.children as dead children linger on it while being
4926 * drained; otherwise, "rmdir parent/child parent" may fail.
4928 if (css_has_online_children(&cgrp->self))
4929 return -EBUSY;
4932 * Mark @cgrp dead. This prevents further task migration and child
4933 * creation by disabling cgroup_lock_live_group().
4935 cgrp->self.flags &= ~CSS_ONLINE;
4937 /* initiate massacre of all css's */
4938 for_each_css(css, ssid, cgrp)
4939 kill_css(css);
4942 * Remove @cgrp directory along with the base files. @cgrp has an
4943 * extra ref on its kn.
4945 kernfs_remove(cgrp->kn);
4947 check_for_release(cgroup_parent(cgrp));
4949 /* put the base reference */
4950 percpu_ref_kill(&cgrp->self.refcnt);
4952 return 0;
4955 static int cgroup_rmdir(struct kernfs_node *kn)
4957 struct cgroup *cgrp;
4958 int ret = 0;
4960 cgrp = cgroup_kn_lock_live(kn);
4961 if (!cgrp)
4962 return 0;
4964 ret = cgroup_destroy_locked(cgrp);
4966 cgroup_kn_unlock(kn);
4967 return ret;
4970 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
4971 .remount_fs = cgroup_remount,
4972 .show_options = cgroup_show_options,
4973 .mkdir = cgroup_mkdir,
4974 .rmdir = cgroup_rmdir,
4975 .rename = cgroup_rename,
4978 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
4980 struct cgroup_subsys_state *css;
4982 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4984 mutex_lock(&cgroup_mutex);
4986 idr_init(&ss->css_idr);
4987 INIT_LIST_HEAD(&ss->cfts);
4989 /* Create the root cgroup state for this subsystem */
4990 ss->root = &cgrp_dfl_root;
4991 css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
4992 /* We don't handle early failures gracefully */
4993 BUG_ON(IS_ERR(css));
4994 init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
4997 * Root csses are never destroyed and we can't initialize
4998 * percpu_ref during early init. Disable refcnting.
5000 css->flags |= CSS_NO_REF;
5002 if (early) {
5003 /* allocation can't be done safely during early init */
5004 css->id = 1;
5005 } else {
5006 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
5007 BUG_ON(css->id < 0);
5010 /* Update the init_css_set to contain a subsys
5011 * pointer to this state - since the subsystem is
5012 * newly registered, all tasks and hence the
5013 * init_css_set is in the subsystem's root cgroup. */
5014 init_css_set.subsys[ss->id] = css;
5016 have_fork_callback |= (bool)ss->fork << ss->id;
5017 have_exit_callback |= (bool)ss->exit << ss->id;
5019 /* At system boot, before all subsystems have been
5020 * registered, no tasks have been forked, so we don't
5021 * need to invoke fork callbacks here. */
5022 BUG_ON(!list_empty(&init_task.tasks));
5024 BUG_ON(online_css(css));
5026 mutex_unlock(&cgroup_mutex);
5030 * cgroup_init_early - cgroup initialization at system boot
5032 * Initialize cgroups at system boot, and initialize any
5033 * subsystems that request early init.
5035 int __init cgroup_init_early(void)
5037 static struct cgroup_sb_opts __initdata opts;
5038 struct cgroup_subsys *ss;
5039 int i;
5041 init_cgroup_root(&cgrp_dfl_root, &opts);
5042 cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
5044 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
5046 for_each_subsys(ss, i) {
5047 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
5048 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
5049 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
5050 ss->id, ss->name);
5051 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
5052 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
5054 ss->id = i;
5055 ss->name = cgroup_subsys_name[i];
5057 if (ss->early_init)
5058 cgroup_init_subsys(ss, true);
5060 return 0;
5064 * cgroup_init - cgroup initialization
5066 * Register cgroup filesystem and /proc file, and initialize
5067 * any subsystems that didn't request early init.
5069 int __init cgroup_init(void)
5071 struct cgroup_subsys *ss;
5072 unsigned long key;
5073 int ssid, err;
5075 BUG_ON(cgroup_init_cftypes(NULL, cgroup_dfl_base_files));
5076 BUG_ON(cgroup_init_cftypes(NULL, cgroup_legacy_base_files));
5078 mutex_lock(&cgroup_mutex);
5080 /* Add init_css_set to the hash table */
5081 key = css_set_hash(init_css_set.subsys);
5082 hash_add(css_set_table, &init_css_set.hlist, key);
5084 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
5086 mutex_unlock(&cgroup_mutex);
5088 for_each_subsys(ss, ssid) {
5089 if (ss->early_init) {
5090 struct cgroup_subsys_state *css =
5091 init_css_set.subsys[ss->id];
5093 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
5094 GFP_KERNEL);
5095 BUG_ON(css->id < 0);
5096 } else {
5097 cgroup_init_subsys(ss, false);
5100 list_add_tail(&init_css_set.e_cset_node[ssid],
5101 &cgrp_dfl_root.cgrp.e_csets[ssid]);
5104 * Setting dfl_root subsys_mask needs to consider the
5105 * disabled flag and cftype registration needs kmalloc,
5106 * both of which aren't available during early_init.
5108 if (ss->disabled)
5109 continue;
5111 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
5113 if (cgroup_legacy_files_on_dfl && !ss->dfl_cftypes)
5114 ss->dfl_cftypes = ss->legacy_cftypes;
5116 if (!ss->dfl_cftypes)
5117 cgrp_dfl_root_inhibit_ss_mask |= 1 << ss->id;
5119 if (ss->dfl_cftypes == ss->legacy_cftypes) {
5120 WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes));
5121 } else {
5122 WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes));
5123 WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes));
5126 if (ss->bind)
5127 ss->bind(init_css_set.subsys[ssid]);
5130 err = sysfs_create_mount_point(fs_kobj, "cgroup");
5131 if (err)
5132 return err;
5134 err = register_filesystem(&cgroup_fs_type);
5135 if (err < 0) {
5136 sysfs_remove_mount_point(fs_kobj, "cgroup");
5137 return err;
5140 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
5141 return 0;
5144 static int __init cgroup_wq_init(void)
5147 * There isn't much point in executing destruction path in
5148 * parallel. Good chunk is serialized with cgroup_mutex anyway.
5149 * Use 1 for @max_active.
5151 * We would prefer to do this in cgroup_init() above, but that
5152 * is called before init_workqueues(): so leave this until after.
5154 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
5155 BUG_ON(!cgroup_destroy_wq);
5158 * Used to destroy pidlists and separate to serve as flush domain.
5159 * Cap @max_active to 1 too.
5161 cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
5162 0, 1);
5163 BUG_ON(!cgroup_pidlist_destroy_wq);
5165 return 0;
5167 core_initcall(cgroup_wq_init);
5170 * proc_cgroup_show()
5171 * - Print task's cgroup paths into seq_file, one line for each hierarchy
5172 * - Used for /proc/<pid>/cgroup.
5174 int proc_cgroup_show(struct seq_file *m, struct pid_namespace *ns,
5175 struct pid *pid, struct task_struct *tsk)
5177 char *buf, *path;
5178 int retval;
5179 struct cgroup_root *root;
5181 retval = -ENOMEM;
5182 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5183 if (!buf)
5184 goto out;
5186 mutex_lock(&cgroup_mutex);
5187 down_read(&css_set_rwsem);
5189 for_each_root(root) {
5190 struct cgroup_subsys *ss;
5191 struct cgroup *cgrp;
5192 int ssid, count = 0;
5194 if (root == &cgrp_dfl_root && !cgrp_dfl_root_visible)
5195 continue;
5197 seq_printf(m, "%d:", root->hierarchy_id);
5198 for_each_subsys(ss, ssid)
5199 if (root->subsys_mask & (1 << ssid))
5200 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
5201 if (strlen(root->name))
5202 seq_printf(m, "%sname=%s", count ? "," : "",
5203 root->name);
5204 seq_putc(m, ':');
5205 cgrp = task_cgroup_from_root(tsk, root);
5206 path = cgroup_path(cgrp, buf, PATH_MAX);
5207 if (!path) {
5208 retval = -ENAMETOOLONG;
5209 goto out_unlock;
5211 seq_puts(m, path);
5212 seq_putc(m, '\n');
5215 retval = 0;
5216 out_unlock:
5217 up_read(&css_set_rwsem);
5218 mutex_unlock(&cgroup_mutex);
5219 kfree(buf);
5220 out:
5221 return retval;
5224 /* Display information about each subsystem and each hierarchy */
5225 static int proc_cgroupstats_show(struct seq_file *m, void *v)
5227 struct cgroup_subsys *ss;
5228 int i;
5230 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
5232 * ideally we don't want subsystems moving around while we do this.
5233 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
5234 * subsys/hierarchy state.
5236 mutex_lock(&cgroup_mutex);
5238 for_each_subsys(ss, i)
5239 seq_printf(m, "%s\t%d\t%d\t%d\n",
5240 ss->name, ss->root->hierarchy_id,
5241 atomic_read(&ss->root->nr_cgrps), !ss->disabled);
5243 mutex_unlock(&cgroup_mutex);
5244 return 0;
5247 static int cgroupstats_open(struct inode *inode, struct file *file)
5249 return single_open(file, proc_cgroupstats_show, NULL);
5252 static const struct file_operations proc_cgroupstats_operations = {
5253 .open = cgroupstats_open,
5254 .read = seq_read,
5255 .llseek = seq_lseek,
5256 .release = single_release,
5260 * cgroup_fork - initialize cgroup related fields during copy_process()
5261 * @child: pointer to task_struct of forking parent process.
5263 * A task is associated with the init_css_set until cgroup_post_fork()
5264 * attaches it to the parent's css_set. Empty cg_list indicates that
5265 * @child isn't holding reference to its css_set.
5267 void cgroup_fork(struct task_struct *child)
5269 RCU_INIT_POINTER(child->cgroups, &init_css_set);
5270 INIT_LIST_HEAD(&child->cg_list);
5274 * cgroup_post_fork - called on a new task after adding it to the task list
5275 * @child: the task in question
5277 * Adds the task to the list running through its css_set if necessary and
5278 * call the subsystem fork() callbacks. Has to be after the task is
5279 * visible on the task list in case we race with the first call to
5280 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
5281 * list.
5283 void cgroup_post_fork(struct task_struct *child)
5285 struct cgroup_subsys *ss;
5286 int i;
5289 * This may race against cgroup_enable_task_cg_lists(). As that
5290 * function sets use_task_css_set_links before grabbing
5291 * tasklist_lock and we just went through tasklist_lock to add
5292 * @child, it's guaranteed that either we see the set
5293 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
5294 * @child during its iteration.
5296 * If we won the race, @child is associated with %current's
5297 * css_set. Grabbing css_set_rwsem guarantees both that the
5298 * association is stable, and, on completion of the parent's
5299 * migration, @child is visible in the source of migration or
5300 * already in the destination cgroup. This guarantee is necessary
5301 * when implementing operations which need to migrate all tasks of
5302 * a cgroup to another.
5304 * Note that if we lose to cgroup_enable_task_cg_lists(), @child
5305 * will remain in init_css_set. This is safe because all tasks are
5306 * in the init_css_set before cg_links is enabled and there's no
5307 * operation which transfers all tasks out of init_css_set.
5309 if (use_task_css_set_links) {
5310 struct css_set *cset;
5312 down_write(&css_set_rwsem);
5313 cset = task_css_set(current);
5314 if (list_empty(&child->cg_list)) {
5315 rcu_assign_pointer(child->cgroups, cset);
5316 list_add(&child->cg_list, &cset->tasks);
5317 get_css_set(cset);
5319 up_write(&css_set_rwsem);
5323 * Call ss->fork(). This must happen after @child is linked on
5324 * css_set; otherwise, @child might change state between ->fork()
5325 * and addition to css_set.
5327 for_each_subsys_which(ss, i, &have_fork_callback)
5328 ss->fork(child);
5332 * cgroup_exit - detach cgroup from exiting task
5333 * @tsk: pointer to task_struct of exiting process
5335 * Description: Detach cgroup from @tsk and release it.
5337 * Note that cgroups marked notify_on_release force every task in
5338 * them to take the global cgroup_mutex mutex when exiting.
5339 * This could impact scaling on very large systems. Be reluctant to
5340 * use notify_on_release cgroups where very high task exit scaling
5341 * is required on large systems.
5343 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
5344 * call cgroup_exit() while the task is still competent to handle
5345 * notify_on_release(), then leave the task attached to the root cgroup in
5346 * each hierarchy for the remainder of its exit. No need to bother with
5347 * init_css_set refcnting. init_css_set never goes away and we can't race
5348 * with migration path - PF_EXITING is visible to migration path.
5350 void cgroup_exit(struct task_struct *tsk)
5352 struct cgroup_subsys *ss;
5353 struct css_set *cset;
5354 bool put_cset = false;
5355 int i;
5358 * Unlink from @tsk from its css_set. As migration path can't race
5359 * with us, we can check cg_list without grabbing css_set_rwsem.
5361 if (!list_empty(&tsk->cg_list)) {
5362 down_write(&css_set_rwsem);
5363 list_del_init(&tsk->cg_list);
5364 up_write(&css_set_rwsem);
5365 put_cset = true;
5368 /* Reassign the task to the init_css_set. */
5369 cset = task_css_set(tsk);
5370 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
5372 /* see cgroup_post_fork() for details */
5373 for_each_subsys_which(ss, i, &have_exit_callback) {
5374 struct cgroup_subsys_state *old_css = cset->subsys[i];
5375 struct cgroup_subsys_state *css = task_css(tsk, i);
5377 ss->exit(css, old_css, tsk);
5380 if (put_cset)
5381 put_css_set(cset);
5384 static void check_for_release(struct cgroup *cgrp)
5386 if (notify_on_release(cgrp) && !cgroup_has_tasks(cgrp) &&
5387 !css_has_online_children(&cgrp->self) && !cgroup_is_dead(cgrp))
5388 schedule_work(&cgrp->release_agent_work);
5392 * Notify userspace when a cgroup is released, by running the
5393 * configured release agent with the name of the cgroup (path
5394 * relative to the root of cgroup file system) as the argument.
5396 * Most likely, this user command will try to rmdir this cgroup.
5398 * This races with the possibility that some other task will be
5399 * attached to this cgroup before it is removed, or that some other
5400 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5401 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5402 * unused, and this cgroup will be reprieved from its death sentence,
5403 * to continue to serve a useful existence. Next time it's released,
5404 * we will get notified again, if it still has 'notify_on_release' set.
5406 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5407 * means only wait until the task is successfully execve()'d. The
5408 * separate release agent task is forked by call_usermodehelper(),
5409 * then control in this thread returns here, without waiting for the
5410 * release agent task. We don't bother to wait because the caller of
5411 * this routine has no use for the exit status of the release agent
5412 * task, so no sense holding our caller up for that.
5414 static void cgroup_release_agent(struct work_struct *work)
5416 struct cgroup *cgrp =
5417 container_of(work, struct cgroup, release_agent_work);
5418 char *pathbuf = NULL, *agentbuf = NULL, *path;
5419 char *argv[3], *envp[3];
5421 mutex_lock(&cgroup_mutex);
5423 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
5424 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5425 if (!pathbuf || !agentbuf)
5426 goto out;
5428 path = cgroup_path(cgrp, pathbuf, PATH_MAX);
5429 if (!path)
5430 goto out;
5432 argv[0] = agentbuf;
5433 argv[1] = path;
5434 argv[2] = NULL;
5436 /* minimal command environment */
5437 envp[0] = "HOME=/";
5438 envp[1] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5439 envp[2] = NULL;
5441 mutex_unlock(&cgroup_mutex);
5442 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5443 goto out_free;
5444 out:
5445 mutex_unlock(&cgroup_mutex);
5446 out_free:
5447 kfree(agentbuf);
5448 kfree(pathbuf);
5451 static int __init cgroup_disable(char *str)
5453 struct cgroup_subsys *ss;
5454 char *token;
5455 int i;
5457 while ((token = strsep(&str, ",")) != NULL) {
5458 if (!*token)
5459 continue;
5461 for_each_subsys(ss, i) {
5462 if (!strcmp(token, ss->name)) {
5463 ss->disabled = 1;
5464 printk(KERN_INFO "Disabling %s control group"
5465 " subsystem\n", ss->name);
5466 break;
5470 return 1;
5472 __setup("cgroup_disable=", cgroup_disable);
5474 static int __init cgroup_set_legacy_files_on_dfl(char *str)
5476 printk("cgroup: using legacy files on the default hierarchy\n");
5477 cgroup_legacy_files_on_dfl = true;
5478 return 0;
5480 __setup("cgroup__DEVEL__legacy_files_on_dfl", cgroup_set_legacy_files_on_dfl);
5483 * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
5484 * @dentry: directory dentry of interest
5485 * @ss: subsystem of interest
5487 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
5488 * to get the corresponding css and return it. If such css doesn't exist
5489 * or can't be pinned, an ERR_PTR value is returned.
5491 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
5492 struct cgroup_subsys *ss)
5494 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
5495 struct cgroup_subsys_state *css = NULL;
5496 struct cgroup *cgrp;
5498 /* is @dentry a cgroup dir? */
5499 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
5500 kernfs_type(kn) != KERNFS_DIR)
5501 return ERR_PTR(-EBADF);
5503 rcu_read_lock();
5506 * This path doesn't originate from kernfs and @kn could already
5507 * have been or be removed at any point. @kn->priv is RCU
5508 * protected for this access. See css_release_work_fn() for details.
5510 cgrp = rcu_dereference(kn->priv);
5511 if (cgrp)
5512 css = cgroup_css(cgrp, ss);
5514 if (!css || !css_tryget_online(css))
5515 css = ERR_PTR(-ENOENT);
5517 rcu_read_unlock();
5518 return css;
5522 * css_from_id - lookup css by id
5523 * @id: the cgroup id
5524 * @ss: cgroup subsys to be looked into
5526 * Returns the css if there's valid one with @id, otherwise returns NULL.
5527 * Should be called under rcu_read_lock().
5529 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5531 WARN_ON_ONCE(!rcu_read_lock_held());
5532 return id > 0 ? idr_find(&ss->css_idr, id) : NULL;
5535 #ifdef CONFIG_CGROUP_DEBUG
5536 static struct cgroup_subsys_state *
5537 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5539 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5541 if (!css)
5542 return ERR_PTR(-ENOMEM);
5544 return css;
5547 static void debug_css_free(struct cgroup_subsys_state *css)
5549 kfree(css);
5552 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5553 struct cftype *cft)
5555 return cgroup_task_count(css->cgroup);
5558 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5559 struct cftype *cft)
5561 return (u64)(unsigned long)current->cgroups;
5564 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5565 struct cftype *cft)
5567 u64 count;
5569 rcu_read_lock();
5570 count = atomic_read(&task_css_set(current)->refcount);
5571 rcu_read_unlock();
5572 return count;
5575 static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
5577 struct cgrp_cset_link *link;
5578 struct css_set *cset;
5579 char *name_buf;
5581 name_buf = kmalloc(NAME_MAX + 1, GFP_KERNEL);
5582 if (!name_buf)
5583 return -ENOMEM;
5585 down_read(&css_set_rwsem);
5586 rcu_read_lock();
5587 cset = rcu_dereference(current->cgroups);
5588 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5589 struct cgroup *c = link->cgrp;
5591 cgroup_name(c, name_buf, NAME_MAX + 1);
5592 seq_printf(seq, "Root %d group %s\n",
5593 c->root->hierarchy_id, name_buf);
5595 rcu_read_unlock();
5596 up_read(&css_set_rwsem);
5597 kfree(name_buf);
5598 return 0;
5601 #define MAX_TASKS_SHOWN_PER_CSS 25
5602 static int cgroup_css_links_read(struct seq_file *seq, void *v)
5604 struct cgroup_subsys_state *css = seq_css(seq);
5605 struct cgrp_cset_link *link;
5607 down_read(&css_set_rwsem);
5608 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5609 struct css_set *cset = link->cset;
5610 struct task_struct *task;
5611 int count = 0;
5613 seq_printf(seq, "css_set %p\n", cset);
5615 list_for_each_entry(task, &cset->tasks, cg_list) {
5616 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5617 goto overflow;
5618 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5621 list_for_each_entry(task, &cset->mg_tasks, cg_list) {
5622 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5623 goto overflow;
5624 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5626 continue;
5627 overflow:
5628 seq_puts(seq, " ...\n");
5630 up_read(&css_set_rwsem);
5631 return 0;
5634 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5636 return (!cgroup_has_tasks(css->cgroup) &&
5637 !css_has_online_children(&css->cgroup->self));
5640 static struct cftype debug_files[] = {
5642 .name = "taskcount",
5643 .read_u64 = debug_taskcount_read,
5647 .name = "current_css_set",
5648 .read_u64 = current_css_set_read,
5652 .name = "current_css_set_refcount",
5653 .read_u64 = current_css_set_refcount_read,
5657 .name = "current_css_set_cg_links",
5658 .seq_show = current_css_set_cg_links_read,
5662 .name = "cgroup_css_links",
5663 .seq_show = cgroup_css_links_read,
5667 .name = "releasable",
5668 .read_u64 = releasable_read,
5671 { } /* terminate */
5674 struct cgroup_subsys debug_cgrp_subsys = {
5675 .css_alloc = debug_css_alloc,
5676 .css_free = debug_css_free,
5677 .legacy_cftypes = debug_files,
5679 #endif /* CONFIG_CGROUP_DEBUG */