fs: create and use seq_show_option for escaping
[linux/fpc-iii.git] / kernel / cgroup.c
blobc6c4240e7d286a30fbaa870755a7d9ff03d86661
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/percpu-rwsem.h>
50 #include <linux/string.h>
51 #include <linux/sort.h>
52 #include <linux/kmod.h>
53 #include <linux/delayacct.h>
54 #include <linux/cgroupstats.h>
55 #include <linux/hashtable.h>
56 #include <linux/pid_namespace.h>
57 #include <linux/idr.h>
58 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
59 #include <linux/kthread.h>
60 #include <linux/delay.h>
62 #include <linux/atomic.h>
65 * pidlists linger the following amount before being destroyed. The goal
66 * is avoiding frequent destruction in the middle of consecutive read calls
67 * Expiring in the middle is a performance problem not a correctness one.
68 * 1 sec should be enough.
70 #define CGROUP_PIDLIST_DESTROY_DELAY HZ
72 #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
73 MAX_CFTYPE_NAME + 2)
76 * cgroup_mutex is the master lock. Any modification to cgroup or its
77 * hierarchy must be performed while holding it.
79 * css_set_rwsem protects task->cgroups pointer, the list of css_set
80 * objects, and the chain of tasks off each css_set.
82 * These locks are exported if CONFIG_PROVE_RCU so that accessors in
83 * cgroup.h can use them for lockdep annotations.
85 #ifdef CONFIG_PROVE_RCU
86 DEFINE_MUTEX(cgroup_mutex);
87 DECLARE_RWSEM(css_set_rwsem);
88 EXPORT_SYMBOL_GPL(cgroup_mutex);
89 EXPORT_SYMBOL_GPL(css_set_rwsem);
90 #else
91 static DEFINE_MUTEX(cgroup_mutex);
92 static DECLARE_RWSEM(css_set_rwsem);
93 #endif
96 * Protects cgroup_idr and css_idr so that IDs can be released without
97 * grabbing cgroup_mutex.
99 static DEFINE_SPINLOCK(cgroup_idr_lock);
102 * Protects cgroup_subsys->release_agent_path. Modifying it also requires
103 * cgroup_mutex. Reading requires either cgroup_mutex or this spinlock.
105 static DEFINE_SPINLOCK(release_agent_path_lock);
107 struct percpu_rw_semaphore cgroup_threadgroup_rwsem;
109 #define cgroup_assert_mutex_or_rcu_locked() \
110 rcu_lockdep_assert(rcu_read_lock_held() || \
111 lockdep_is_held(&cgroup_mutex), \
112 "cgroup_mutex or RCU read lock required");
115 * cgroup destruction makes heavy use of work items and there can be a lot
116 * of concurrent destructions. Use a separate workqueue so that cgroup
117 * destruction work items don't end up filling up max_active of system_wq
118 * which may lead to deadlock.
120 static struct workqueue_struct *cgroup_destroy_wq;
123 * pidlist destructions need to be flushed on cgroup destruction. Use a
124 * separate workqueue as flush domain.
126 static struct workqueue_struct *cgroup_pidlist_destroy_wq;
128 /* generate an array of cgroup subsystem pointers */
129 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
130 static struct cgroup_subsys *cgroup_subsys[] = {
131 #include <linux/cgroup_subsys.h>
133 #undef SUBSYS
135 /* array of cgroup subsystem names */
136 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
137 static const char *cgroup_subsys_name[] = {
138 #include <linux/cgroup_subsys.h>
140 #undef SUBSYS
143 * The default hierarchy, reserved for the subsystems that are otherwise
144 * unattached - it never has more than a single cgroup, and all tasks are
145 * part of that cgroup.
147 struct cgroup_root cgrp_dfl_root;
150 * The default hierarchy always exists but is hidden until mounted for the
151 * first time. This is for backward compatibility.
153 static bool cgrp_dfl_root_visible;
156 * Set by the boot param of the same name and makes subsystems with NULL
157 * ->dfl_files to use ->legacy_files on the default hierarchy.
159 static bool cgroup_legacy_files_on_dfl;
161 /* some controllers are not supported in the default hierarchy */
162 static unsigned long cgrp_dfl_root_inhibit_ss_mask;
164 /* The list of hierarchy roots */
166 static LIST_HEAD(cgroup_roots);
167 static int cgroup_root_count;
169 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
170 static DEFINE_IDR(cgroup_hierarchy_idr);
173 * Assign a monotonically increasing serial number to csses. It guarantees
174 * cgroups with bigger numbers are newer than those with smaller numbers.
175 * Also, as csses are always appended to the parent's ->children list, it
176 * guarantees that sibling csses are always sorted in the ascending serial
177 * number order on the list. Protected by cgroup_mutex.
179 static u64 css_serial_nr_next = 1;
182 * These bitmask flags indicate whether tasks in the fork and exit paths have
183 * fork/exit handlers to call. This avoids us having to do extra work in the
184 * fork/exit path to check which subsystems have fork/exit callbacks.
186 static unsigned long have_fork_callback __read_mostly;
187 static unsigned long have_exit_callback __read_mostly;
189 static struct cftype cgroup_dfl_base_files[];
190 static struct cftype cgroup_legacy_base_files[];
192 static int rebind_subsystems(struct cgroup_root *dst_root,
193 unsigned long ss_mask);
194 static int cgroup_destroy_locked(struct cgroup *cgrp);
195 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss,
196 bool visible);
197 static void css_release(struct percpu_ref *ref);
198 static void kill_css(struct cgroup_subsys_state *css);
199 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
200 bool is_add);
202 /* IDR wrappers which synchronize using cgroup_idr_lock */
203 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
204 gfp_t gfp_mask)
206 int ret;
208 idr_preload(gfp_mask);
209 spin_lock_bh(&cgroup_idr_lock);
210 ret = idr_alloc(idr, ptr, start, end, gfp_mask);
211 spin_unlock_bh(&cgroup_idr_lock);
212 idr_preload_end();
213 return ret;
216 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
218 void *ret;
220 spin_lock_bh(&cgroup_idr_lock);
221 ret = idr_replace(idr, ptr, id);
222 spin_unlock_bh(&cgroup_idr_lock);
223 return ret;
226 static void cgroup_idr_remove(struct idr *idr, int id)
228 spin_lock_bh(&cgroup_idr_lock);
229 idr_remove(idr, id);
230 spin_unlock_bh(&cgroup_idr_lock);
233 static struct cgroup *cgroup_parent(struct cgroup *cgrp)
235 struct cgroup_subsys_state *parent_css = cgrp->self.parent;
237 if (parent_css)
238 return container_of(parent_css, struct cgroup, self);
239 return NULL;
243 * cgroup_css - obtain a cgroup's css for the specified subsystem
244 * @cgrp: the cgroup of interest
245 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
247 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
248 * function must be called either under cgroup_mutex or rcu_read_lock() and
249 * the caller is responsible for pinning the returned css if it wants to
250 * keep accessing it outside the said locks. This function may return
251 * %NULL if @cgrp doesn't have @subsys_id enabled.
253 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
254 struct cgroup_subsys *ss)
256 if (ss)
257 return rcu_dereference_check(cgrp->subsys[ss->id],
258 lockdep_is_held(&cgroup_mutex));
259 else
260 return &cgrp->self;
264 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
265 * @cgrp: the cgroup of interest
266 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
268 * Similar to cgroup_css() but returns the effective css, which is defined
269 * as the matching css of the nearest ancestor including self which has @ss
270 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
271 * function is guaranteed to return non-NULL css.
273 static struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
274 struct cgroup_subsys *ss)
276 lockdep_assert_held(&cgroup_mutex);
278 if (!ss)
279 return &cgrp->self;
281 if (!(cgrp->root->subsys_mask & (1 << ss->id)))
282 return NULL;
285 * This function is used while updating css associations and thus
286 * can't test the csses directly. Use ->child_subsys_mask.
288 while (cgroup_parent(cgrp) &&
289 !(cgroup_parent(cgrp)->child_subsys_mask & (1 << ss->id)))
290 cgrp = cgroup_parent(cgrp);
292 return cgroup_css(cgrp, ss);
296 * cgroup_get_e_css - get a cgroup's effective css for the specified subsystem
297 * @cgrp: the cgroup of interest
298 * @ss: the subsystem of interest
300 * Find and get the effective css of @cgrp for @ss. The effective css is
301 * defined as the matching css of the nearest ancestor including self which
302 * has @ss enabled. If @ss is not mounted on the hierarchy @cgrp is on,
303 * the root css is returned, so this function always returns a valid css.
304 * The returned css must be put using css_put().
306 struct cgroup_subsys_state *cgroup_get_e_css(struct cgroup *cgrp,
307 struct cgroup_subsys *ss)
309 struct cgroup_subsys_state *css;
311 rcu_read_lock();
313 do {
314 css = cgroup_css(cgrp, ss);
316 if (css && css_tryget_online(css))
317 goto out_unlock;
318 cgrp = cgroup_parent(cgrp);
319 } while (cgrp);
321 css = init_css_set.subsys[ss->id];
322 css_get(css);
323 out_unlock:
324 rcu_read_unlock();
325 return css;
328 /* convenient tests for these bits */
329 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
331 return !(cgrp->self.flags & CSS_ONLINE);
334 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
336 struct cgroup *cgrp = of->kn->parent->priv;
337 struct cftype *cft = of_cft(of);
340 * This is open and unprotected implementation of cgroup_css().
341 * seq_css() is only called from a kernfs file operation which has
342 * an active reference on the file. Because all the subsystem
343 * files are drained before a css is disassociated with a cgroup,
344 * the matching css from the cgroup's subsys table is guaranteed to
345 * be and stay valid until the enclosing operation is complete.
347 if (cft->ss)
348 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
349 else
350 return &cgrp->self;
352 EXPORT_SYMBOL_GPL(of_css);
355 * cgroup_is_descendant - test ancestry
356 * @cgrp: the cgroup to be tested
357 * @ancestor: possible ancestor of @cgrp
359 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
360 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
361 * and @ancestor are accessible.
363 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
365 while (cgrp) {
366 if (cgrp == ancestor)
367 return true;
368 cgrp = cgroup_parent(cgrp);
370 return false;
373 static int notify_on_release(const struct cgroup *cgrp)
375 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
379 * for_each_css - iterate all css's of a cgroup
380 * @css: the iteration cursor
381 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
382 * @cgrp: the target cgroup to iterate css's of
384 * Should be called under cgroup_[tree_]mutex.
386 #define for_each_css(css, ssid, cgrp) \
387 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
388 if (!((css) = rcu_dereference_check( \
389 (cgrp)->subsys[(ssid)], \
390 lockdep_is_held(&cgroup_mutex)))) { } \
391 else
394 * for_each_e_css - iterate all effective css's of a cgroup
395 * @css: the iteration cursor
396 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
397 * @cgrp: the target cgroup to iterate css's of
399 * Should be called under cgroup_[tree_]mutex.
401 #define for_each_e_css(css, ssid, cgrp) \
402 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
403 if (!((css) = cgroup_e_css(cgrp, cgroup_subsys[(ssid)]))) \
405 else
408 * for_each_subsys - iterate all enabled cgroup subsystems
409 * @ss: the iteration cursor
410 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
412 #define for_each_subsys(ss, ssid) \
413 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT && \
414 (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
417 * for_each_subsys_which - filter for_each_subsys with a bitmask
418 * @ss: the iteration cursor
419 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
420 * @ss_maskp: a pointer to the bitmask
422 * The block will only run for cases where the ssid-th bit (1 << ssid) of
423 * mask is set to 1.
425 #define for_each_subsys_which(ss, ssid, ss_maskp) \
426 if (!CGROUP_SUBSYS_COUNT) /* to avoid spurious gcc warning */ \
427 (ssid) = 0; \
428 else \
429 for_each_set_bit(ssid, ss_maskp, CGROUP_SUBSYS_COUNT) \
430 if (((ss) = cgroup_subsys[ssid]) && false) \
431 break; \
432 else
434 /* iterate across the hierarchies */
435 #define for_each_root(root) \
436 list_for_each_entry((root), &cgroup_roots, root_list)
438 /* iterate over child cgrps, lock should be held throughout iteration */
439 #define cgroup_for_each_live_child(child, cgrp) \
440 list_for_each_entry((child), &(cgrp)->self.children, self.sibling) \
441 if (({ lockdep_assert_held(&cgroup_mutex); \
442 cgroup_is_dead(child); })) \
444 else
446 static void cgroup_release_agent(struct work_struct *work);
447 static void check_for_release(struct cgroup *cgrp);
450 * A cgroup can be associated with multiple css_sets as different tasks may
451 * belong to different cgroups on different hierarchies. In the other
452 * direction, a css_set is naturally associated with multiple cgroups.
453 * This M:N relationship is represented by the following link structure
454 * which exists for each association and allows traversing the associations
455 * from both sides.
457 struct cgrp_cset_link {
458 /* the cgroup and css_set this link associates */
459 struct cgroup *cgrp;
460 struct css_set *cset;
462 /* list of cgrp_cset_links anchored at cgrp->cset_links */
463 struct list_head cset_link;
465 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
466 struct list_head cgrp_link;
470 * The default css_set - used by init and its children prior to any
471 * hierarchies being mounted. It contains a pointer to the root state
472 * for each subsystem. Also used to anchor the list of css_sets. Not
473 * reference-counted, to improve performance when child cgroups
474 * haven't been created.
476 struct css_set init_css_set = {
477 .refcount = ATOMIC_INIT(1),
478 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
479 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
480 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
481 .mg_preload_node = LIST_HEAD_INIT(init_css_set.mg_preload_node),
482 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
485 static int css_set_count = 1; /* 1 for init_css_set */
488 * cgroup_update_populated - updated populated count of a cgroup
489 * @cgrp: the target cgroup
490 * @populated: inc or dec populated count
492 * @cgrp is either getting the first task (css_set) or losing the last.
493 * Update @cgrp->populated_cnt accordingly. The count is propagated
494 * towards root so that a given cgroup's populated_cnt is zero iff the
495 * cgroup and all its descendants are empty.
497 * @cgrp's interface file "cgroup.populated" is zero if
498 * @cgrp->populated_cnt is zero and 1 otherwise. When @cgrp->populated_cnt
499 * changes from or to zero, userland is notified that the content of the
500 * interface file has changed. This can be used to detect when @cgrp and
501 * its descendants become populated or empty.
503 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
505 lockdep_assert_held(&css_set_rwsem);
507 do {
508 bool trigger;
510 if (populated)
511 trigger = !cgrp->populated_cnt++;
512 else
513 trigger = !--cgrp->populated_cnt;
515 if (!trigger)
516 break;
518 if (cgrp->populated_kn)
519 kernfs_notify(cgrp->populated_kn);
520 cgrp = cgroup_parent(cgrp);
521 } while (cgrp);
525 * hash table for cgroup groups. This improves the performance to find
526 * an existing css_set. This hash doesn't (currently) take into
527 * account cgroups in empty hierarchies.
529 #define CSS_SET_HASH_BITS 7
530 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
532 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
534 unsigned long key = 0UL;
535 struct cgroup_subsys *ss;
536 int i;
538 for_each_subsys(ss, i)
539 key += (unsigned long)css[i];
540 key = (key >> 16) ^ key;
542 return key;
545 static void put_css_set_locked(struct css_set *cset)
547 struct cgrp_cset_link *link, *tmp_link;
548 struct cgroup_subsys *ss;
549 int ssid;
551 lockdep_assert_held(&css_set_rwsem);
553 if (!atomic_dec_and_test(&cset->refcount))
554 return;
556 /* This css_set is dead. unlink it and release cgroup refcounts */
557 for_each_subsys(ss, ssid)
558 list_del(&cset->e_cset_node[ssid]);
559 hash_del(&cset->hlist);
560 css_set_count--;
562 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
563 struct cgroup *cgrp = link->cgrp;
565 list_del(&link->cset_link);
566 list_del(&link->cgrp_link);
568 /* @cgrp can't go away while we're holding css_set_rwsem */
569 if (list_empty(&cgrp->cset_links)) {
570 cgroup_update_populated(cgrp, false);
571 check_for_release(cgrp);
574 kfree(link);
577 kfree_rcu(cset, rcu_head);
580 static void put_css_set(struct css_set *cset)
583 * Ensure that the refcount doesn't hit zero while any readers
584 * can see it. Similar to atomic_dec_and_lock(), but for an
585 * rwlock
587 if (atomic_add_unless(&cset->refcount, -1, 1))
588 return;
590 down_write(&css_set_rwsem);
591 put_css_set_locked(cset);
592 up_write(&css_set_rwsem);
596 * refcounted get/put for css_set objects
598 static inline void get_css_set(struct css_set *cset)
600 atomic_inc(&cset->refcount);
604 * compare_css_sets - helper function for find_existing_css_set().
605 * @cset: candidate css_set being tested
606 * @old_cset: existing css_set for a task
607 * @new_cgrp: cgroup that's being entered by the task
608 * @template: desired set of css pointers in css_set (pre-calculated)
610 * Returns true if "cset" matches "old_cset" except for the hierarchy
611 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
613 static bool compare_css_sets(struct css_set *cset,
614 struct css_set *old_cset,
615 struct cgroup *new_cgrp,
616 struct cgroup_subsys_state *template[])
618 struct list_head *l1, *l2;
621 * On the default hierarchy, there can be csets which are
622 * associated with the same set of cgroups but different csses.
623 * Let's first ensure that csses match.
625 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
626 return false;
629 * Compare cgroup pointers in order to distinguish between
630 * different cgroups in hierarchies. As different cgroups may
631 * share the same effective css, this comparison is always
632 * necessary.
634 l1 = &cset->cgrp_links;
635 l2 = &old_cset->cgrp_links;
636 while (1) {
637 struct cgrp_cset_link *link1, *link2;
638 struct cgroup *cgrp1, *cgrp2;
640 l1 = l1->next;
641 l2 = l2->next;
642 /* See if we reached the end - both lists are equal length. */
643 if (l1 == &cset->cgrp_links) {
644 BUG_ON(l2 != &old_cset->cgrp_links);
645 break;
646 } else {
647 BUG_ON(l2 == &old_cset->cgrp_links);
649 /* Locate the cgroups associated with these links. */
650 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
651 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
652 cgrp1 = link1->cgrp;
653 cgrp2 = link2->cgrp;
654 /* Hierarchies should be linked in the same order. */
655 BUG_ON(cgrp1->root != cgrp2->root);
658 * If this hierarchy is the hierarchy of the cgroup
659 * that's changing, then we need to check that this
660 * css_set points to the new cgroup; if it's any other
661 * hierarchy, then this css_set should point to the
662 * same cgroup as the old css_set.
664 if (cgrp1->root == new_cgrp->root) {
665 if (cgrp1 != new_cgrp)
666 return false;
667 } else {
668 if (cgrp1 != cgrp2)
669 return false;
672 return true;
676 * find_existing_css_set - init css array and find the matching css_set
677 * @old_cset: the css_set that we're using before the cgroup transition
678 * @cgrp: the cgroup that we're moving into
679 * @template: out param for the new set of csses, should be clear on entry
681 static struct css_set *find_existing_css_set(struct css_set *old_cset,
682 struct cgroup *cgrp,
683 struct cgroup_subsys_state *template[])
685 struct cgroup_root *root = cgrp->root;
686 struct cgroup_subsys *ss;
687 struct css_set *cset;
688 unsigned long key;
689 int i;
692 * Build the set of subsystem state objects that we want to see in the
693 * new css_set. while subsystems can change globally, the entries here
694 * won't change, so no need for locking.
696 for_each_subsys(ss, i) {
697 if (root->subsys_mask & (1UL << i)) {
699 * @ss is in this hierarchy, so we want the
700 * effective css from @cgrp.
702 template[i] = cgroup_e_css(cgrp, ss);
703 } else {
705 * @ss is not in this hierarchy, so we don't want
706 * to change the css.
708 template[i] = old_cset->subsys[i];
712 key = css_set_hash(template);
713 hash_for_each_possible(css_set_table, cset, hlist, key) {
714 if (!compare_css_sets(cset, old_cset, cgrp, template))
715 continue;
717 /* This css_set matches what we need */
718 return cset;
721 /* No existing cgroup group matched */
722 return NULL;
725 static void free_cgrp_cset_links(struct list_head *links_to_free)
727 struct cgrp_cset_link *link, *tmp_link;
729 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
730 list_del(&link->cset_link);
731 kfree(link);
736 * allocate_cgrp_cset_links - allocate cgrp_cset_links
737 * @count: the number of links to allocate
738 * @tmp_links: list_head the allocated links are put on
740 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
741 * through ->cset_link. Returns 0 on success or -errno.
743 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
745 struct cgrp_cset_link *link;
746 int i;
748 INIT_LIST_HEAD(tmp_links);
750 for (i = 0; i < count; i++) {
751 link = kzalloc(sizeof(*link), GFP_KERNEL);
752 if (!link) {
753 free_cgrp_cset_links(tmp_links);
754 return -ENOMEM;
756 list_add(&link->cset_link, tmp_links);
758 return 0;
762 * link_css_set - a helper function to link a css_set to a cgroup
763 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
764 * @cset: the css_set to be linked
765 * @cgrp: the destination cgroup
767 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
768 struct cgroup *cgrp)
770 struct cgrp_cset_link *link;
772 BUG_ON(list_empty(tmp_links));
774 if (cgroup_on_dfl(cgrp))
775 cset->dfl_cgrp = cgrp;
777 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
778 link->cset = cset;
779 link->cgrp = cgrp;
781 if (list_empty(&cgrp->cset_links))
782 cgroup_update_populated(cgrp, true);
783 list_move(&link->cset_link, &cgrp->cset_links);
786 * Always add links to the tail of the list so that the list
787 * is sorted by order of hierarchy creation
789 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
793 * find_css_set - return a new css_set with one cgroup updated
794 * @old_cset: the baseline css_set
795 * @cgrp: the cgroup to be updated
797 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
798 * substituted into the appropriate hierarchy.
800 static struct css_set *find_css_set(struct css_set *old_cset,
801 struct cgroup *cgrp)
803 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
804 struct css_set *cset;
805 struct list_head tmp_links;
806 struct cgrp_cset_link *link;
807 struct cgroup_subsys *ss;
808 unsigned long key;
809 int ssid;
811 lockdep_assert_held(&cgroup_mutex);
813 /* First see if we already have a cgroup group that matches
814 * the desired set */
815 down_read(&css_set_rwsem);
816 cset = find_existing_css_set(old_cset, cgrp, template);
817 if (cset)
818 get_css_set(cset);
819 up_read(&css_set_rwsem);
821 if (cset)
822 return cset;
824 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
825 if (!cset)
826 return NULL;
828 /* Allocate all the cgrp_cset_link objects that we'll need */
829 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
830 kfree(cset);
831 return NULL;
834 atomic_set(&cset->refcount, 1);
835 INIT_LIST_HEAD(&cset->cgrp_links);
836 INIT_LIST_HEAD(&cset->tasks);
837 INIT_LIST_HEAD(&cset->mg_tasks);
838 INIT_LIST_HEAD(&cset->mg_preload_node);
839 INIT_LIST_HEAD(&cset->mg_node);
840 INIT_HLIST_NODE(&cset->hlist);
842 /* Copy the set of subsystem state objects generated in
843 * find_existing_css_set() */
844 memcpy(cset->subsys, template, sizeof(cset->subsys));
846 down_write(&css_set_rwsem);
847 /* Add reference counts and links from the new css_set. */
848 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
849 struct cgroup *c = link->cgrp;
851 if (c->root == cgrp->root)
852 c = cgrp;
853 link_css_set(&tmp_links, cset, c);
856 BUG_ON(!list_empty(&tmp_links));
858 css_set_count++;
860 /* Add @cset to the hash table */
861 key = css_set_hash(cset->subsys);
862 hash_add(css_set_table, &cset->hlist, key);
864 for_each_subsys(ss, ssid)
865 list_add_tail(&cset->e_cset_node[ssid],
866 &cset->subsys[ssid]->cgroup->e_csets[ssid]);
868 up_write(&css_set_rwsem);
870 return cset;
873 static struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
875 struct cgroup *root_cgrp = kf_root->kn->priv;
877 return root_cgrp->root;
880 static int cgroup_init_root_id(struct cgroup_root *root)
882 int id;
884 lockdep_assert_held(&cgroup_mutex);
886 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
887 if (id < 0)
888 return id;
890 root->hierarchy_id = id;
891 return 0;
894 static void cgroup_exit_root_id(struct cgroup_root *root)
896 lockdep_assert_held(&cgroup_mutex);
898 if (root->hierarchy_id) {
899 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
900 root->hierarchy_id = 0;
904 static void cgroup_free_root(struct cgroup_root *root)
906 if (root) {
907 /* hierarchy ID should already have been released */
908 WARN_ON_ONCE(root->hierarchy_id);
910 idr_destroy(&root->cgroup_idr);
911 kfree(root);
915 static void cgroup_destroy_root(struct cgroup_root *root)
917 struct cgroup *cgrp = &root->cgrp;
918 struct cgrp_cset_link *link, *tmp_link;
920 mutex_lock(&cgroup_mutex);
922 BUG_ON(atomic_read(&root->nr_cgrps));
923 BUG_ON(!list_empty(&cgrp->self.children));
925 /* Rebind all subsystems back to the default hierarchy */
926 rebind_subsystems(&cgrp_dfl_root, root->subsys_mask);
929 * Release all the links from cset_links to this hierarchy's
930 * root cgroup
932 down_write(&css_set_rwsem);
934 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
935 list_del(&link->cset_link);
936 list_del(&link->cgrp_link);
937 kfree(link);
939 up_write(&css_set_rwsem);
941 if (!list_empty(&root->root_list)) {
942 list_del(&root->root_list);
943 cgroup_root_count--;
946 cgroup_exit_root_id(root);
948 mutex_unlock(&cgroup_mutex);
950 kernfs_destroy_root(root->kf_root);
951 cgroup_free_root(root);
954 /* look up cgroup associated with given css_set on the specified hierarchy */
955 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
956 struct cgroup_root *root)
958 struct cgroup *res = NULL;
960 lockdep_assert_held(&cgroup_mutex);
961 lockdep_assert_held(&css_set_rwsem);
963 if (cset == &init_css_set) {
964 res = &root->cgrp;
965 } else {
966 struct cgrp_cset_link *link;
968 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
969 struct cgroup *c = link->cgrp;
971 if (c->root == root) {
972 res = c;
973 break;
978 BUG_ON(!res);
979 return res;
983 * Return the cgroup for "task" from the given hierarchy. Must be
984 * called with cgroup_mutex and css_set_rwsem held.
986 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
987 struct cgroup_root *root)
990 * No need to lock the task - since we hold cgroup_mutex the
991 * task can't change groups, so the only thing that can happen
992 * is that it exits and its css is set back to init_css_set.
994 return cset_cgroup_from_root(task_css_set(task), root);
998 * A task must hold cgroup_mutex to modify cgroups.
1000 * Any task can increment and decrement the count field without lock.
1001 * So in general, code holding cgroup_mutex can't rely on the count
1002 * field not changing. However, if the count goes to zero, then only
1003 * cgroup_attach_task() can increment it again. Because a count of zero
1004 * means that no tasks are currently attached, therefore there is no
1005 * way a task attached to that cgroup can fork (the other way to
1006 * increment the count). So code holding cgroup_mutex can safely
1007 * assume that if the count is zero, it will stay zero. Similarly, if
1008 * a task holds cgroup_mutex on a cgroup with zero count, it
1009 * knows that the cgroup won't be removed, as cgroup_rmdir()
1010 * needs that mutex.
1012 * A cgroup can only be deleted if both its 'count' of using tasks
1013 * is zero, and its list of 'children' cgroups is empty. Since all
1014 * tasks in the system use _some_ cgroup, and since there is always at
1015 * least one task in the system (init, pid == 1), therefore, root cgroup
1016 * always has either children cgroups and/or using tasks. So we don't
1017 * need a special hack to ensure that root cgroup cannot be deleted.
1019 * P.S. One more locking exception. RCU is used to guard the
1020 * update of a tasks cgroup pointer by cgroup_attach_task()
1023 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask);
1024 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
1025 static const struct file_operations proc_cgroupstats_operations;
1027 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
1028 char *buf)
1030 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
1031 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
1032 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
1033 cft->ss->name, cft->name);
1034 else
1035 strncpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
1036 return buf;
1040 * cgroup_file_mode - deduce file mode of a control file
1041 * @cft: the control file in question
1043 * returns cft->mode if ->mode is not 0
1044 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
1045 * returns S_IRUGO if it has only a read handler
1046 * returns S_IWUSR if it has only a write hander
1048 static umode_t cgroup_file_mode(const struct cftype *cft)
1050 umode_t mode = 0;
1052 if (cft->mode)
1053 return cft->mode;
1055 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1056 mode |= S_IRUGO;
1058 if (cft->write_u64 || cft->write_s64 || cft->write)
1059 mode |= S_IWUSR;
1061 return mode;
1064 static void cgroup_get(struct cgroup *cgrp)
1066 WARN_ON_ONCE(cgroup_is_dead(cgrp));
1067 css_get(&cgrp->self);
1070 static bool cgroup_tryget(struct cgroup *cgrp)
1072 return css_tryget(&cgrp->self);
1075 static void cgroup_put(struct cgroup *cgrp)
1077 css_put(&cgrp->self);
1081 * cgroup_calc_child_subsys_mask - calculate child_subsys_mask
1082 * @cgrp: the target cgroup
1083 * @subtree_control: the new subtree_control mask to consider
1085 * On the default hierarchy, a subsystem may request other subsystems to be
1086 * enabled together through its ->depends_on mask. In such cases, more
1087 * subsystems than specified in "cgroup.subtree_control" may be enabled.
1089 * This function calculates which subsystems need to be enabled if
1090 * @subtree_control is to be applied to @cgrp. The returned mask is always
1091 * a superset of @subtree_control and follows the usual hierarchy rules.
1093 static unsigned long cgroup_calc_child_subsys_mask(struct cgroup *cgrp,
1094 unsigned long subtree_control)
1096 struct cgroup *parent = cgroup_parent(cgrp);
1097 unsigned long cur_ss_mask = subtree_control;
1098 struct cgroup_subsys *ss;
1099 int ssid;
1101 lockdep_assert_held(&cgroup_mutex);
1103 if (!cgroup_on_dfl(cgrp))
1104 return cur_ss_mask;
1106 while (true) {
1107 unsigned long new_ss_mask = cur_ss_mask;
1109 for_each_subsys_which(ss, ssid, &cur_ss_mask)
1110 new_ss_mask |= ss->depends_on;
1113 * Mask out subsystems which aren't available. This can
1114 * happen only if some depended-upon subsystems were bound
1115 * to non-default hierarchies.
1117 if (parent)
1118 new_ss_mask &= parent->child_subsys_mask;
1119 else
1120 new_ss_mask &= cgrp->root->subsys_mask;
1122 if (new_ss_mask == cur_ss_mask)
1123 break;
1124 cur_ss_mask = new_ss_mask;
1127 return cur_ss_mask;
1131 * cgroup_refresh_child_subsys_mask - update child_subsys_mask
1132 * @cgrp: the target cgroup
1134 * Update @cgrp->child_subsys_mask according to the current
1135 * @cgrp->subtree_control using cgroup_calc_child_subsys_mask().
1137 static void cgroup_refresh_child_subsys_mask(struct cgroup *cgrp)
1139 cgrp->child_subsys_mask =
1140 cgroup_calc_child_subsys_mask(cgrp, cgrp->subtree_control);
1144 * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
1145 * @kn: the kernfs_node being serviced
1147 * This helper undoes cgroup_kn_lock_live() and should be invoked before
1148 * the method finishes if locking succeeded. Note that once this function
1149 * returns the cgroup returned by cgroup_kn_lock_live() may become
1150 * inaccessible any time. If the caller intends to continue to access the
1151 * cgroup, it should pin it before invoking this function.
1153 static void cgroup_kn_unlock(struct kernfs_node *kn)
1155 struct cgroup *cgrp;
1157 if (kernfs_type(kn) == KERNFS_DIR)
1158 cgrp = kn->priv;
1159 else
1160 cgrp = kn->parent->priv;
1162 mutex_unlock(&cgroup_mutex);
1164 kernfs_unbreak_active_protection(kn);
1165 cgroup_put(cgrp);
1169 * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
1170 * @kn: the kernfs_node being serviced
1172 * This helper is to be used by a cgroup kernfs method currently servicing
1173 * @kn. It breaks the active protection, performs cgroup locking and
1174 * verifies that the associated cgroup is alive. Returns the cgroup if
1175 * alive; otherwise, %NULL. A successful return should be undone by a
1176 * matching cgroup_kn_unlock() invocation.
1178 * Any cgroup kernfs method implementation which requires locking the
1179 * associated cgroup should use this helper. It avoids nesting cgroup
1180 * locking under kernfs active protection and allows all kernfs operations
1181 * including self-removal.
1183 static struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn)
1185 struct cgroup *cgrp;
1187 if (kernfs_type(kn) == KERNFS_DIR)
1188 cgrp = kn->priv;
1189 else
1190 cgrp = kn->parent->priv;
1193 * We're gonna grab cgroup_mutex which nests outside kernfs
1194 * active_ref. cgroup liveliness check alone provides enough
1195 * protection against removal. Ensure @cgrp stays accessible and
1196 * break the active_ref protection.
1198 if (!cgroup_tryget(cgrp))
1199 return NULL;
1200 kernfs_break_active_protection(kn);
1202 mutex_lock(&cgroup_mutex);
1204 if (!cgroup_is_dead(cgrp))
1205 return cgrp;
1207 cgroup_kn_unlock(kn);
1208 return NULL;
1211 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1213 char name[CGROUP_FILE_NAME_MAX];
1215 lockdep_assert_held(&cgroup_mutex);
1216 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1220 * cgroup_clear_dir - remove subsys files in a cgroup directory
1221 * @cgrp: target cgroup
1222 * @subsys_mask: mask of the subsystem ids whose files should be removed
1224 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned long subsys_mask)
1226 struct cgroup_subsys *ss;
1227 int i;
1229 for_each_subsys(ss, i) {
1230 struct cftype *cfts;
1232 if (!(subsys_mask & (1 << i)))
1233 continue;
1234 list_for_each_entry(cfts, &ss->cfts, node)
1235 cgroup_addrm_files(cgrp, cfts, false);
1239 static int rebind_subsystems(struct cgroup_root *dst_root,
1240 unsigned long ss_mask)
1242 struct cgroup_subsys *ss;
1243 unsigned long tmp_ss_mask;
1244 int ssid, i, ret;
1246 lockdep_assert_held(&cgroup_mutex);
1248 for_each_subsys_which(ss, ssid, &ss_mask) {
1249 /* if @ss has non-root csses attached to it, can't move */
1250 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)))
1251 return -EBUSY;
1253 /* can't move between two non-dummy roots either */
1254 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1255 return -EBUSY;
1258 /* skip creating root files on dfl_root for inhibited subsystems */
1259 tmp_ss_mask = ss_mask;
1260 if (dst_root == &cgrp_dfl_root)
1261 tmp_ss_mask &= ~cgrp_dfl_root_inhibit_ss_mask;
1263 ret = cgroup_populate_dir(&dst_root->cgrp, tmp_ss_mask);
1264 if (ret) {
1265 if (dst_root != &cgrp_dfl_root)
1266 return ret;
1269 * Rebinding back to the default root is not allowed to
1270 * fail. Using both default and non-default roots should
1271 * be rare. Moving subsystems back and forth even more so.
1272 * Just warn about it and continue.
1274 if (cgrp_dfl_root_visible) {
1275 pr_warn("failed to create files (%d) while rebinding 0x%lx to default root\n",
1276 ret, ss_mask);
1277 pr_warn("you may retry by moving them to a different hierarchy and unbinding\n");
1282 * Nothing can fail from this point on. Remove files for the
1283 * removed subsystems and rebind each subsystem.
1285 for_each_subsys_which(ss, ssid, &ss_mask)
1286 cgroup_clear_dir(&ss->root->cgrp, 1 << ssid);
1288 for_each_subsys_which(ss, ssid, &ss_mask) {
1289 struct cgroup_root *src_root;
1290 struct cgroup_subsys_state *css;
1291 struct css_set *cset;
1293 src_root = ss->root;
1294 css = cgroup_css(&src_root->cgrp, ss);
1296 WARN_ON(!css || cgroup_css(&dst_root->cgrp, ss));
1298 RCU_INIT_POINTER(src_root->cgrp.subsys[ssid], NULL);
1299 rcu_assign_pointer(dst_root->cgrp.subsys[ssid], css);
1300 ss->root = dst_root;
1301 css->cgroup = &dst_root->cgrp;
1303 down_write(&css_set_rwsem);
1304 hash_for_each(css_set_table, i, cset, hlist)
1305 list_move_tail(&cset->e_cset_node[ss->id],
1306 &dst_root->cgrp.e_csets[ss->id]);
1307 up_write(&css_set_rwsem);
1309 src_root->subsys_mask &= ~(1 << ssid);
1310 src_root->cgrp.subtree_control &= ~(1 << ssid);
1311 cgroup_refresh_child_subsys_mask(&src_root->cgrp);
1313 /* default hierarchy doesn't enable controllers by default */
1314 dst_root->subsys_mask |= 1 << ssid;
1315 if (dst_root != &cgrp_dfl_root) {
1316 dst_root->cgrp.subtree_control |= 1 << ssid;
1317 cgroup_refresh_child_subsys_mask(&dst_root->cgrp);
1320 if (ss->bind)
1321 ss->bind(css);
1324 kernfs_activate(dst_root->cgrp.kn);
1325 return 0;
1328 static int cgroup_show_options(struct seq_file *seq,
1329 struct kernfs_root *kf_root)
1331 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1332 struct cgroup_subsys *ss;
1333 int ssid;
1335 for_each_subsys(ss, ssid)
1336 if (root->subsys_mask & (1 << ssid))
1337 seq_show_option(seq, ss->name, NULL);
1338 if (root->flags & CGRP_ROOT_NOPREFIX)
1339 seq_puts(seq, ",noprefix");
1340 if (root->flags & CGRP_ROOT_XATTR)
1341 seq_puts(seq, ",xattr");
1343 spin_lock(&release_agent_path_lock);
1344 if (strlen(root->release_agent_path))
1345 seq_show_option(seq, "release_agent",
1346 root->release_agent_path);
1347 spin_unlock(&release_agent_path_lock);
1349 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags))
1350 seq_puts(seq, ",clone_children");
1351 if (strlen(root->name))
1352 seq_show_option(seq, "name", root->name);
1353 return 0;
1356 struct cgroup_sb_opts {
1357 unsigned long subsys_mask;
1358 unsigned int flags;
1359 char *release_agent;
1360 bool cpuset_clone_children;
1361 char *name;
1362 /* User explicitly requested empty subsystem */
1363 bool none;
1366 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1368 char *token, *o = data;
1369 bool all_ss = false, one_ss = false;
1370 unsigned long mask = -1UL;
1371 struct cgroup_subsys *ss;
1372 int nr_opts = 0;
1373 int i;
1375 #ifdef CONFIG_CPUSETS
1376 mask = ~(1U << cpuset_cgrp_id);
1377 #endif
1379 memset(opts, 0, sizeof(*opts));
1381 while ((token = strsep(&o, ",")) != NULL) {
1382 nr_opts++;
1384 if (!*token)
1385 return -EINVAL;
1386 if (!strcmp(token, "none")) {
1387 /* Explicitly have no subsystems */
1388 opts->none = true;
1389 continue;
1391 if (!strcmp(token, "all")) {
1392 /* Mutually exclusive option 'all' + subsystem name */
1393 if (one_ss)
1394 return -EINVAL;
1395 all_ss = true;
1396 continue;
1398 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1399 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1400 continue;
1402 if (!strcmp(token, "noprefix")) {
1403 opts->flags |= CGRP_ROOT_NOPREFIX;
1404 continue;
1406 if (!strcmp(token, "clone_children")) {
1407 opts->cpuset_clone_children = true;
1408 continue;
1410 if (!strcmp(token, "xattr")) {
1411 opts->flags |= CGRP_ROOT_XATTR;
1412 continue;
1414 if (!strncmp(token, "release_agent=", 14)) {
1415 /* Specifying two release agents is forbidden */
1416 if (opts->release_agent)
1417 return -EINVAL;
1418 opts->release_agent =
1419 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1420 if (!opts->release_agent)
1421 return -ENOMEM;
1422 continue;
1424 if (!strncmp(token, "name=", 5)) {
1425 const char *name = token + 5;
1426 /* Can't specify an empty name */
1427 if (!strlen(name))
1428 return -EINVAL;
1429 /* Must match [\w.-]+ */
1430 for (i = 0; i < strlen(name); i++) {
1431 char c = name[i];
1432 if (isalnum(c))
1433 continue;
1434 if ((c == '.') || (c == '-') || (c == '_'))
1435 continue;
1436 return -EINVAL;
1438 /* Specifying two names is forbidden */
1439 if (opts->name)
1440 return -EINVAL;
1441 opts->name = kstrndup(name,
1442 MAX_CGROUP_ROOT_NAMELEN - 1,
1443 GFP_KERNEL);
1444 if (!opts->name)
1445 return -ENOMEM;
1447 continue;
1450 for_each_subsys(ss, i) {
1451 if (strcmp(token, ss->name))
1452 continue;
1453 if (ss->disabled)
1454 continue;
1456 /* Mutually exclusive option 'all' + subsystem name */
1457 if (all_ss)
1458 return -EINVAL;
1459 opts->subsys_mask |= (1 << i);
1460 one_ss = true;
1462 break;
1464 if (i == CGROUP_SUBSYS_COUNT)
1465 return -ENOENT;
1468 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1469 pr_warn("sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1470 if (nr_opts != 1) {
1471 pr_err("sane_behavior: no other mount options allowed\n");
1472 return -EINVAL;
1474 return 0;
1478 * If the 'all' option was specified select all the subsystems,
1479 * otherwise if 'none', 'name=' and a subsystem name options were
1480 * not specified, let's default to 'all'
1482 if (all_ss || (!one_ss && !opts->none && !opts->name))
1483 for_each_subsys(ss, i)
1484 if (!ss->disabled)
1485 opts->subsys_mask |= (1 << i);
1488 * We either have to specify by name or by subsystems. (So all
1489 * empty hierarchies must have a name).
1491 if (!opts->subsys_mask && !opts->name)
1492 return -EINVAL;
1495 * Option noprefix was introduced just for backward compatibility
1496 * with the old cpuset, so we allow noprefix only if mounting just
1497 * the cpuset subsystem.
1499 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1500 return -EINVAL;
1502 /* Can't specify "none" and some subsystems */
1503 if (opts->subsys_mask && opts->none)
1504 return -EINVAL;
1506 return 0;
1509 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1511 int ret = 0;
1512 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1513 struct cgroup_sb_opts opts;
1514 unsigned long added_mask, removed_mask;
1516 if (root == &cgrp_dfl_root) {
1517 pr_err("remount is not allowed\n");
1518 return -EINVAL;
1521 mutex_lock(&cgroup_mutex);
1523 /* See what subsystems are wanted */
1524 ret = parse_cgroupfs_options(data, &opts);
1525 if (ret)
1526 goto out_unlock;
1528 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1529 pr_warn("option changes via remount are deprecated (pid=%d comm=%s)\n",
1530 task_tgid_nr(current), current->comm);
1532 added_mask = opts.subsys_mask & ~root->subsys_mask;
1533 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1535 /* Don't allow flags or name to change at remount */
1536 if ((opts.flags ^ root->flags) ||
1537 (opts.name && strcmp(opts.name, root->name))) {
1538 pr_err("option or name mismatch, new: 0x%x \"%s\", old: 0x%x \"%s\"\n",
1539 opts.flags, opts.name ?: "", root->flags, root->name);
1540 ret = -EINVAL;
1541 goto out_unlock;
1544 /* remounting is not allowed for populated hierarchies */
1545 if (!list_empty(&root->cgrp.self.children)) {
1546 ret = -EBUSY;
1547 goto out_unlock;
1550 ret = rebind_subsystems(root, added_mask);
1551 if (ret)
1552 goto out_unlock;
1554 rebind_subsystems(&cgrp_dfl_root, removed_mask);
1556 if (opts.release_agent) {
1557 spin_lock(&release_agent_path_lock);
1558 strcpy(root->release_agent_path, opts.release_agent);
1559 spin_unlock(&release_agent_path_lock);
1561 out_unlock:
1562 kfree(opts.release_agent);
1563 kfree(opts.name);
1564 mutex_unlock(&cgroup_mutex);
1565 return ret;
1569 * To reduce the fork() overhead for systems that are not actually using
1570 * their cgroups capability, we don't maintain the lists running through
1571 * each css_set to its tasks until we see the list actually used - in other
1572 * words after the first mount.
1574 static bool use_task_css_set_links __read_mostly;
1576 static void cgroup_enable_task_cg_lists(void)
1578 struct task_struct *p, *g;
1580 down_write(&css_set_rwsem);
1582 if (use_task_css_set_links)
1583 goto out_unlock;
1585 use_task_css_set_links = true;
1588 * We need tasklist_lock because RCU is not safe against
1589 * while_each_thread(). Besides, a forking task that has passed
1590 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1591 * is not guaranteed to have its child immediately visible in the
1592 * tasklist if we walk through it with RCU.
1594 read_lock(&tasklist_lock);
1595 do_each_thread(g, p) {
1596 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1597 task_css_set(p) != &init_css_set);
1600 * We should check if the process is exiting, otherwise
1601 * it will race with cgroup_exit() in that the list
1602 * entry won't be deleted though the process has exited.
1603 * Do it while holding siglock so that we don't end up
1604 * racing against cgroup_exit().
1606 spin_lock_irq(&p->sighand->siglock);
1607 if (!(p->flags & PF_EXITING)) {
1608 struct css_set *cset = task_css_set(p);
1610 list_add(&p->cg_list, &cset->tasks);
1611 get_css_set(cset);
1613 spin_unlock_irq(&p->sighand->siglock);
1614 } while_each_thread(g, p);
1615 read_unlock(&tasklist_lock);
1616 out_unlock:
1617 up_write(&css_set_rwsem);
1620 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1622 struct cgroup_subsys *ss;
1623 int ssid;
1625 INIT_LIST_HEAD(&cgrp->self.sibling);
1626 INIT_LIST_HEAD(&cgrp->self.children);
1627 INIT_LIST_HEAD(&cgrp->cset_links);
1628 INIT_LIST_HEAD(&cgrp->pidlists);
1629 mutex_init(&cgrp->pidlist_mutex);
1630 cgrp->self.cgroup = cgrp;
1631 cgrp->self.flags |= CSS_ONLINE;
1633 for_each_subsys(ss, ssid)
1634 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
1636 init_waitqueue_head(&cgrp->offline_waitq);
1637 INIT_WORK(&cgrp->release_agent_work, cgroup_release_agent);
1640 static void init_cgroup_root(struct cgroup_root *root,
1641 struct cgroup_sb_opts *opts)
1643 struct cgroup *cgrp = &root->cgrp;
1645 INIT_LIST_HEAD(&root->root_list);
1646 atomic_set(&root->nr_cgrps, 1);
1647 cgrp->root = root;
1648 init_cgroup_housekeeping(cgrp);
1649 idr_init(&root->cgroup_idr);
1651 root->flags = opts->flags;
1652 if (opts->release_agent)
1653 strcpy(root->release_agent_path, opts->release_agent);
1654 if (opts->name)
1655 strcpy(root->name, opts->name);
1656 if (opts->cpuset_clone_children)
1657 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1660 static int cgroup_setup_root(struct cgroup_root *root, unsigned long ss_mask)
1662 LIST_HEAD(tmp_links);
1663 struct cgroup *root_cgrp = &root->cgrp;
1664 struct cftype *base_files;
1665 struct css_set *cset;
1666 int i, ret;
1668 lockdep_assert_held(&cgroup_mutex);
1670 ret = cgroup_idr_alloc(&root->cgroup_idr, root_cgrp, 1, 2, GFP_NOWAIT);
1671 if (ret < 0)
1672 goto out;
1673 root_cgrp->id = ret;
1675 ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release, 0,
1676 GFP_KERNEL);
1677 if (ret)
1678 goto out;
1681 * We're accessing css_set_count without locking css_set_rwsem here,
1682 * but that's OK - it can only be increased by someone holding
1683 * cgroup_lock, and that's us. The worst that can happen is that we
1684 * have some link structures left over
1686 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1687 if (ret)
1688 goto cancel_ref;
1690 ret = cgroup_init_root_id(root);
1691 if (ret)
1692 goto cancel_ref;
1694 root->kf_root = kernfs_create_root(&cgroup_kf_syscall_ops,
1695 KERNFS_ROOT_CREATE_DEACTIVATED,
1696 root_cgrp);
1697 if (IS_ERR(root->kf_root)) {
1698 ret = PTR_ERR(root->kf_root);
1699 goto exit_root_id;
1701 root_cgrp->kn = root->kf_root->kn;
1703 if (root == &cgrp_dfl_root)
1704 base_files = cgroup_dfl_base_files;
1705 else
1706 base_files = cgroup_legacy_base_files;
1708 ret = cgroup_addrm_files(root_cgrp, base_files, true);
1709 if (ret)
1710 goto destroy_root;
1712 ret = rebind_subsystems(root, ss_mask);
1713 if (ret)
1714 goto destroy_root;
1717 * There must be no failure case after here, since rebinding takes
1718 * care of subsystems' refcounts, which are explicitly dropped in
1719 * the failure exit path.
1721 list_add(&root->root_list, &cgroup_roots);
1722 cgroup_root_count++;
1725 * Link the root cgroup in this hierarchy into all the css_set
1726 * objects.
1728 down_write(&css_set_rwsem);
1729 hash_for_each(css_set_table, i, cset, hlist)
1730 link_css_set(&tmp_links, cset, root_cgrp);
1731 up_write(&css_set_rwsem);
1733 BUG_ON(!list_empty(&root_cgrp->self.children));
1734 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
1736 kernfs_activate(root_cgrp->kn);
1737 ret = 0;
1738 goto out;
1740 destroy_root:
1741 kernfs_destroy_root(root->kf_root);
1742 root->kf_root = NULL;
1743 exit_root_id:
1744 cgroup_exit_root_id(root);
1745 cancel_ref:
1746 percpu_ref_exit(&root_cgrp->self.refcnt);
1747 out:
1748 free_cgrp_cset_links(&tmp_links);
1749 return ret;
1752 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1753 int flags, const char *unused_dev_name,
1754 void *data)
1756 struct super_block *pinned_sb = NULL;
1757 struct cgroup_subsys *ss;
1758 struct cgroup_root *root;
1759 struct cgroup_sb_opts opts;
1760 struct dentry *dentry;
1761 int ret;
1762 int i;
1763 bool new_sb;
1766 * The first time anyone tries to mount a cgroup, enable the list
1767 * linking each css_set to its tasks and fix up all existing tasks.
1769 if (!use_task_css_set_links)
1770 cgroup_enable_task_cg_lists();
1772 mutex_lock(&cgroup_mutex);
1774 /* First find the desired set of subsystems */
1775 ret = parse_cgroupfs_options(data, &opts);
1776 if (ret)
1777 goto out_unlock;
1779 /* look for a matching existing root */
1780 if (opts.flags & CGRP_ROOT_SANE_BEHAVIOR) {
1781 cgrp_dfl_root_visible = true;
1782 root = &cgrp_dfl_root;
1783 cgroup_get(&root->cgrp);
1784 ret = 0;
1785 goto out_unlock;
1789 * Destruction of cgroup root is asynchronous, so subsystems may
1790 * still be dying after the previous unmount. Let's drain the
1791 * dying subsystems. We just need to ensure that the ones
1792 * unmounted previously finish dying and don't care about new ones
1793 * starting. Testing ref liveliness is good enough.
1795 for_each_subsys(ss, i) {
1796 if (!(opts.subsys_mask & (1 << i)) ||
1797 ss->root == &cgrp_dfl_root)
1798 continue;
1800 if (!percpu_ref_tryget_live(&ss->root->cgrp.self.refcnt)) {
1801 mutex_unlock(&cgroup_mutex);
1802 msleep(10);
1803 ret = restart_syscall();
1804 goto out_free;
1806 cgroup_put(&ss->root->cgrp);
1809 for_each_root(root) {
1810 bool name_match = false;
1812 if (root == &cgrp_dfl_root)
1813 continue;
1816 * If we asked for a name then it must match. Also, if
1817 * name matches but sybsys_mask doesn't, we should fail.
1818 * Remember whether name matched.
1820 if (opts.name) {
1821 if (strcmp(opts.name, root->name))
1822 continue;
1823 name_match = true;
1827 * If we asked for subsystems (or explicitly for no
1828 * subsystems) then they must match.
1830 if ((opts.subsys_mask || opts.none) &&
1831 (opts.subsys_mask != root->subsys_mask)) {
1832 if (!name_match)
1833 continue;
1834 ret = -EBUSY;
1835 goto out_unlock;
1838 if (root->flags ^ opts.flags)
1839 pr_warn("new mount options do not match the existing superblock, will be ignored\n");
1842 * We want to reuse @root whose lifetime is governed by its
1843 * ->cgrp. Let's check whether @root is alive and keep it
1844 * that way. As cgroup_kill_sb() can happen anytime, we
1845 * want to block it by pinning the sb so that @root doesn't
1846 * get killed before mount is complete.
1848 * With the sb pinned, tryget_live can reliably indicate
1849 * whether @root can be reused. If it's being killed,
1850 * drain it. We can use wait_queue for the wait but this
1851 * path is super cold. Let's just sleep a bit and retry.
1853 pinned_sb = kernfs_pin_sb(root->kf_root, NULL);
1854 if (IS_ERR(pinned_sb) ||
1855 !percpu_ref_tryget_live(&root->cgrp.self.refcnt)) {
1856 mutex_unlock(&cgroup_mutex);
1857 if (!IS_ERR_OR_NULL(pinned_sb))
1858 deactivate_super(pinned_sb);
1859 msleep(10);
1860 ret = restart_syscall();
1861 goto out_free;
1864 ret = 0;
1865 goto out_unlock;
1869 * No such thing, create a new one. name= matching without subsys
1870 * specification is allowed for already existing hierarchies but we
1871 * can't create new one without subsys specification.
1873 if (!opts.subsys_mask && !opts.none) {
1874 ret = -EINVAL;
1875 goto out_unlock;
1878 root = kzalloc(sizeof(*root), GFP_KERNEL);
1879 if (!root) {
1880 ret = -ENOMEM;
1881 goto out_unlock;
1884 init_cgroup_root(root, &opts);
1886 ret = cgroup_setup_root(root, opts.subsys_mask);
1887 if (ret)
1888 cgroup_free_root(root);
1890 out_unlock:
1891 mutex_unlock(&cgroup_mutex);
1892 out_free:
1893 kfree(opts.release_agent);
1894 kfree(opts.name);
1896 if (ret)
1897 return ERR_PTR(ret);
1899 dentry = kernfs_mount(fs_type, flags, root->kf_root,
1900 CGROUP_SUPER_MAGIC, &new_sb);
1901 if (IS_ERR(dentry) || !new_sb)
1902 cgroup_put(&root->cgrp);
1905 * If @pinned_sb, we're reusing an existing root and holding an
1906 * extra ref on its sb. Mount is complete. Put the extra ref.
1908 if (pinned_sb) {
1909 WARN_ON(new_sb);
1910 deactivate_super(pinned_sb);
1913 return dentry;
1916 static void cgroup_kill_sb(struct super_block *sb)
1918 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
1919 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1922 * If @root doesn't have any mounts or children, start killing it.
1923 * This prevents new mounts by disabling percpu_ref_tryget_live().
1924 * cgroup_mount() may wait for @root's release.
1926 * And don't kill the default root.
1928 if (!list_empty(&root->cgrp.self.children) ||
1929 root == &cgrp_dfl_root)
1930 cgroup_put(&root->cgrp);
1931 else
1932 percpu_ref_kill(&root->cgrp.self.refcnt);
1934 kernfs_kill_sb(sb);
1937 static struct file_system_type cgroup_fs_type = {
1938 .name = "cgroup",
1939 .mount = cgroup_mount,
1940 .kill_sb = cgroup_kill_sb,
1944 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1945 * @task: target task
1946 * @buf: the buffer to write the path into
1947 * @buflen: the length of the buffer
1949 * Determine @task's cgroup on the first (the one with the lowest non-zero
1950 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1951 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1952 * cgroup controller callbacks.
1954 * Return value is the same as kernfs_path().
1956 char *task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1958 struct cgroup_root *root;
1959 struct cgroup *cgrp;
1960 int hierarchy_id = 1;
1961 char *path = NULL;
1963 mutex_lock(&cgroup_mutex);
1964 down_read(&css_set_rwsem);
1966 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1968 if (root) {
1969 cgrp = task_cgroup_from_root(task, root);
1970 path = cgroup_path(cgrp, buf, buflen);
1971 } else {
1972 /* if no hierarchy exists, everyone is in "/" */
1973 if (strlcpy(buf, "/", buflen) < buflen)
1974 path = buf;
1977 up_read(&css_set_rwsem);
1978 mutex_unlock(&cgroup_mutex);
1979 return path;
1981 EXPORT_SYMBOL_GPL(task_cgroup_path);
1983 /* used to track tasks and other necessary states during migration */
1984 struct cgroup_taskset {
1985 /* the src and dst cset list running through cset->mg_node */
1986 struct list_head src_csets;
1987 struct list_head dst_csets;
1990 * Fields for cgroup_taskset_*() iteration.
1992 * Before migration is committed, the target migration tasks are on
1993 * ->mg_tasks of the csets on ->src_csets. After, on ->mg_tasks of
1994 * the csets on ->dst_csets. ->csets point to either ->src_csets
1995 * or ->dst_csets depending on whether migration is committed.
1997 * ->cur_csets and ->cur_task point to the current task position
1998 * during iteration.
2000 struct list_head *csets;
2001 struct css_set *cur_cset;
2002 struct task_struct *cur_task;
2006 * cgroup_taskset_first - reset taskset and return the first task
2007 * @tset: taskset of interest
2009 * @tset iteration is initialized and the first task is returned.
2011 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
2013 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
2014 tset->cur_task = NULL;
2016 return cgroup_taskset_next(tset);
2020 * cgroup_taskset_next - iterate to the next task in taskset
2021 * @tset: taskset of interest
2023 * Return the next task in @tset. Iteration must have been initialized
2024 * with cgroup_taskset_first().
2026 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
2028 struct css_set *cset = tset->cur_cset;
2029 struct task_struct *task = tset->cur_task;
2031 while (&cset->mg_node != tset->csets) {
2032 if (!task)
2033 task = list_first_entry(&cset->mg_tasks,
2034 struct task_struct, cg_list);
2035 else
2036 task = list_next_entry(task, cg_list);
2038 if (&task->cg_list != &cset->mg_tasks) {
2039 tset->cur_cset = cset;
2040 tset->cur_task = task;
2041 return task;
2044 cset = list_next_entry(cset, mg_node);
2045 task = NULL;
2048 return NULL;
2052 * cgroup_task_migrate - move a task from one cgroup to another.
2053 * @old_cgrp: the cgroup @tsk is being migrated from
2054 * @tsk: the task being migrated
2055 * @new_cset: the new css_set @tsk is being attached to
2057 * Must be called with cgroup_mutex, threadgroup and css_set_rwsem locked.
2059 static void cgroup_task_migrate(struct cgroup *old_cgrp,
2060 struct task_struct *tsk,
2061 struct css_set *new_cset)
2063 struct css_set *old_cset;
2065 lockdep_assert_held(&cgroup_mutex);
2066 lockdep_assert_held(&css_set_rwsem);
2069 * We are synchronized through cgroup_threadgroup_rwsem against
2070 * PF_EXITING setting such that we can't race against cgroup_exit()
2071 * changing the css_set to init_css_set and dropping the old one.
2073 WARN_ON_ONCE(tsk->flags & PF_EXITING);
2074 old_cset = task_css_set(tsk);
2076 get_css_set(new_cset);
2077 rcu_assign_pointer(tsk->cgroups, new_cset);
2080 * Use move_tail so that cgroup_taskset_first() still returns the
2081 * leader after migration. This works because cgroup_migrate()
2082 * ensures that the dst_cset of the leader is the first on the
2083 * tset's dst_csets list.
2085 list_move_tail(&tsk->cg_list, &new_cset->mg_tasks);
2088 * We just gained a reference on old_cset by taking it from the
2089 * task. As trading it for new_cset is protected by cgroup_mutex,
2090 * we're safe to drop it here; it will be freed under RCU.
2092 put_css_set_locked(old_cset);
2096 * cgroup_migrate_finish - cleanup after attach
2097 * @preloaded_csets: list of preloaded css_sets
2099 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
2100 * those functions for details.
2102 static void cgroup_migrate_finish(struct list_head *preloaded_csets)
2104 struct css_set *cset, *tmp_cset;
2106 lockdep_assert_held(&cgroup_mutex);
2108 down_write(&css_set_rwsem);
2109 list_for_each_entry_safe(cset, tmp_cset, preloaded_csets, mg_preload_node) {
2110 cset->mg_src_cgrp = NULL;
2111 cset->mg_dst_cset = NULL;
2112 list_del_init(&cset->mg_preload_node);
2113 put_css_set_locked(cset);
2115 up_write(&css_set_rwsem);
2119 * cgroup_migrate_add_src - add a migration source css_set
2120 * @src_cset: the source css_set to add
2121 * @dst_cgrp: the destination cgroup
2122 * @preloaded_csets: list of preloaded css_sets
2124 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
2125 * @src_cset and add it to @preloaded_csets, which should later be cleaned
2126 * up by cgroup_migrate_finish().
2128 * This function may be called without holding cgroup_threadgroup_rwsem
2129 * even if the target is a process. Threads may be created and destroyed
2130 * but as long as cgroup_mutex is not dropped, no new css_set can be put
2131 * into play and the preloaded css_sets are guaranteed to cover all
2132 * migrations.
2134 static void cgroup_migrate_add_src(struct css_set *src_cset,
2135 struct cgroup *dst_cgrp,
2136 struct list_head *preloaded_csets)
2138 struct cgroup *src_cgrp;
2140 lockdep_assert_held(&cgroup_mutex);
2141 lockdep_assert_held(&css_set_rwsem);
2143 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2145 if (!list_empty(&src_cset->mg_preload_node))
2146 return;
2148 WARN_ON(src_cset->mg_src_cgrp);
2149 WARN_ON(!list_empty(&src_cset->mg_tasks));
2150 WARN_ON(!list_empty(&src_cset->mg_node));
2152 src_cset->mg_src_cgrp = src_cgrp;
2153 get_css_set(src_cset);
2154 list_add(&src_cset->mg_preload_node, preloaded_csets);
2158 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2159 * @dst_cgrp: the destination cgroup (may be %NULL)
2160 * @preloaded_csets: list of preloaded source css_sets
2162 * Tasks are about to be moved to @dst_cgrp and all the source css_sets
2163 * have been preloaded to @preloaded_csets. This function looks up and
2164 * pins all destination css_sets, links each to its source, and append them
2165 * to @preloaded_csets. If @dst_cgrp is %NULL, the destination of each
2166 * source css_set is assumed to be its cgroup on the default hierarchy.
2168 * This function must be called after cgroup_migrate_add_src() has been
2169 * called on each migration source css_set. After migration is performed
2170 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2171 * @preloaded_csets.
2173 static int cgroup_migrate_prepare_dst(struct cgroup *dst_cgrp,
2174 struct list_head *preloaded_csets)
2176 LIST_HEAD(csets);
2177 struct css_set *src_cset, *tmp_cset;
2179 lockdep_assert_held(&cgroup_mutex);
2182 * Except for the root, child_subsys_mask must be zero for a cgroup
2183 * with tasks so that child cgroups don't compete against tasks.
2185 if (dst_cgrp && cgroup_on_dfl(dst_cgrp) && cgroup_parent(dst_cgrp) &&
2186 dst_cgrp->child_subsys_mask)
2187 return -EBUSY;
2189 /* look up the dst cset for each src cset and link it to src */
2190 list_for_each_entry_safe(src_cset, tmp_cset, preloaded_csets, mg_preload_node) {
2191 struct css_set *dst_cset;
2193 dst_cset = find_css_set(src_cset,
2194 dst_cgrp ?: src_cset->dfl_cgrp);
2195 if (!dst_cset)
2196 goto err;
2198 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2201 * If src cset equals dst, it's noop. Drop the src.
2202 * cgroup_migrate() will skip the cset too. Note that we
2203 * can't handle src == dst as some nodes are used by both.
2205 if (src_cset == dst_cset) {
2206 src_cset->mg_src_cgrp = NULL;
2207 list_del_init(&src_cset->mg_preload_node);
2208 put_css_set(src_cset);
2209 put_css_set(dst_cset);
2210 continue;
2213 src_cset->mg_dst_cset = dst_cset;
2215 if (list_empty(&dst_cset->mg_preload_node))
2216 list_add(&dst_cset->mg_preload_node, &csets);
2217 else
2218 put_css_set(dst_cset);
2221 list_splice_tail(&csets, preloaded_csets);
2222 return 0;
2223 err:
2224 cgroup_migrate_finish(&csets);
2225 return -ENOMEM;
2229 * cgroup_migrate - migrate a process or task to a cgroup
2230 * @cgrp: the destination cgroup
2231 * @leader: the leader of the process or the task to migrate
2232 * @threadgroup: whether @leader points to the whole process or a single task
2234 * Migrate a process or task denoted by @leader to @cgrp. If migrating a
2235 * process, the caller must be holding cgroup_threadgroup_rwsem. The
2236 * caller is also responsible for invoking cgroup_migrate_add_src() and
2237 * cgroup_migrate_prepare_dst() on the targets before invoking this
2238 * function and following up with cgroup_migrate_finish().
2240 * As long as a controller's ->can_attach() doesn't fail, this function is
2241 * guaranteed to succeed. This means that, excluding ->can_attach()
2242 * failure, when migrating multiple targets, the success or failure can be
2243 * decided for all targets by invoking group_migrate_prepare_dst() before
2244 * actually starting migrating.
2246 static int cgroup_migrate(struct cgroup *cgrp, struct task_struct *leader,
2247 bool threadgroup)
2249 struct cgroup_taskset tset = {
2250 .src_csets = LIST_HEAD_INIT(tset.src_csets),
2251 .dst_csets = LIST_HEAD_INIT(tset.dst_csets),
2252 .csets = &tset.src_csets,
2254 struct cgroup_subsys_state *css, *failed_css = NULL;
2255 struct css_set *cset, *tmp_cset;
2256 struct task_struct *task, *tmp_task;
2257 int i, ret;
2260 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2261 * already PF_EXITING could be freed from underneath us unless we
2262 * take an rcu_read_lock.
2264 down_write(&css_set_rwsem);
2265 rcu_read_lock();
2266 task = leader;
2267 do {
2268 /* @task either already exited or can't exit until the end */
2269 if (task->flags & PF_EXITING)
2270 goto next;
2272 /* leave @task alone if post_fork() hasn't linked it yet */
2273 if (list_empty(&task->cg_list))
2274 goto next;
2276 cset = task_css_set(task);
2277 if (!cset->mg_src_cgrp)
2278 goto next;
2281 * cgroup_taskset_first() must always return the leader.
2282 * Take care to avoid disturbing the ordering.
2284 list_move_tail(&task->cg_list, &cset->mg_tasks);
2285 if (list_empty(&cset->mg_node))
2286 list_add_tail(&cset->mg_node, &tset.src_csets);
2287 if (list_empty(&cset->mg_dst_cset->mg_node))
2288 list_move_tail(&cset->mg_dst_cset->mg_node,
2289 &tset.dst_csets);
2290 next:
2291 if (!threadgroup)
2292 break;
2293 } while_each_thread(leader, task);
2294 rcu_read_unlock();
2295 up_write(&css_set_rwsem);
2297 /* methods shouldn't be called if no task is actually migrating */
2298 if (list_empty(&tset.src_csets))
2299 return 0;
2301 /* check that we can legitimately attach to the cgroup */
2302 for_each_e_css(css, i, cgrp) {
2303 if (css->ss->can_attach) {
2304 ret = css->ss->can_attach(css, &tset);
2305 if (ret) {
2306 failed_css = css;
2307 goto out_cancel_attach;
2313 * Now that we're guaranteed success, proceed to move all tasks to
2314 * the new cgroup. There are no failure cases after here, so this
2315 * is the commit point.
2317 down_write(&css_set_rwsem);
2318 list_for_each_entry(cset, &tset.src_csets, mg_node) {
2319 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list)
2320 cgroup_task_migrate(cset->mg_src_cgrp, task,
2321 cset->mg_dst_cset);
2323 up_write(&css_set_rwsem);
2326 * Migration is committed, all target tasks are now on dst_csets.
2327 * Nothing is sensitive to fork() after this point. Notify
2328 * controllers that migration is complete.
2330 tset.csets = &tset.dst_csets;
2332 for_each_e_css(css, i, cgrp)
2333 if (css->ss->attach)
2334 css->ss->attach(css, &tset);
2336 ret = 0;
2337 goto out_release_tset;
2339 out_cancel_attach:
2340 for_each_e_css(css, i, cgrp) {
2341 if (css == failed_css)
2342 break;
2343 if (css->ss->cancel_attach)
2344 css->ss->cancel_attach(css, &tset);
2346 out_release_tset:
2347 down_write(&css_set_rwsem);
2348 list_splice_init(&tset.dst_csets, &tset.src_csets);
2349 list_for_each_entry_safe(cset, tmp_cset, &tset.src_csets, mg_node) {
2350 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2351 list_del_init(&cset->mg_node);
2353 up_write(&css_set_rwsem);
2354 return ret;
2358 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2359 * @dst_cgrp: the cgroup to attach to
2360 * @leader: the task or the leader of the threadgroup to be attached
2361 * @threadgroup: attach the whole threadgroup?
2363 * Call holding cgroup_mutex and cgroup_threadgroup_rwsem.
2365 static int cgroup_attach_task(struct cgroup *dst_cgrp,
2366 struct task_struct *leader, bool threadgroup)
2368 LIST_HEAD(preloaded_csets);
2369 struct task_struct *task;
2370 int ret;
2372 /* look up all src csets */
2373 down_read(&css_set_rwsem);
2374 rcu_read_lock();
2375 task = leader;
2376 do {
2377 cgroup_migrate_add_src(task_css_set(task), dst_cgrp,
2378 &preloaded_csets);
2379 if (!threadgroup)
2380 break;
2381 } while_each_thread(leader, task);
2382 rcu_read_unlock();
2383 up_read(&css_set_rwsem);
2385 /* prepare dst csets and commit */
2386 ret = cgroup_migrate_prepare_dst(dst_cgrp, &preloaded_csets);
2387 if (!ret)
2388 ret = cgroup_migrate(dst_cgrp, leader, threadgroup);
2390 cgroup_migrate_finish(&preloaded_csets);
2391 return ret;
2394 static int cgroup_procs_write_permission(struct task_struct *task,
2395 struct cgroup *dst_cgrp,
2396 struct kernfs_open_file *of)
2398 const struct cred *cred = current_cred();
2399 const struct cred *tcred = get_task_cred(task);
2400 int ret = 0;
2403 * even if we're attaching all tasks in the thread group, we only
2404 * need to check permissions on one of them.
2406 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2407 !uid_eq(cred->euid, tcred->uid) &&
2408 !uid_eq(cred->euid, tcred->suid))
2409 ret = -EACCES;
2411 if (!ret && cgroup_on_dfl(dst_cgrp)) {
2412 struct super_block *sb = of->file->f_path.dentry->d_sb;
2413 struct cgroup *cgrp;
2414 struct inode *inode;
2416 down_read(&css_set_rwsem);
2417 cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
2418 up_read(&css_set_rwsem);
2420 while (!cgroup_is_descendant(dst_cgrp, cgrp))
2421 cgrp = cgroup_parent(cgrp);
2423 ret = -ENOMEM;
2424 inode = kernfs_get_inode(sb, cgrp->procs_kn);
2425 if (inode) {
2426 ret = inode_permission(inode, MAY_WRITE);
2427 iput(inode);
2431 put_cred(tcred);
2432 return ret;
2436 * Find the task_struct of the task to attach by vpid and pass it along to the
2437 * function to attach either it or all tasks in its threadgroup. Will lock
2438 * cgroup_mutex and threadgroup.
2440 static ssize_t __cgroup_procs_write(struct kernfs_open_file *of, char *buf,
2441 size_t nbytes, loff_t off, bool threadgroup)
2443 struct task_struct *tsk;
2444 struct cgroup *cgrp;
2445 pid_t pid;
2446 int ret;
2448 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2449 return -EINVAL;
2451 cgrp = cgroup_kn_lock_live(of->kn);
2452 if (!cgrp)
2453 return -ENODEV;
2455 percpu_down_write(&cgroup_threadgroup_rwsem);
2456 rcu_read_lock();
2457 if (pid) {
2458 tsk = find_task_by_vpid(pid);
2459 if (!tsk) {
2460 ret = -ESRCH;
2461 goto out_unlock_rcu;
2463 } else {
2464 tsk = current;
2467 if (threadgroup)
2468 tsk = tsk->group_leader;
2471 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2472 * trapped in a cpuset, or RT worker may be born in a cgroup
2473 * with no rt_runtime allocated. Just say no.
2475 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2476 ret = -EINVAL;
2477 goto out_unlock_rcu;
2480 get_task_struct(tsk);
2481 rcu_read_unlock();
2483 ret = cgroup_procs_write_permission(tsk, cgrp, of);
2484 if (!ret)
2485 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2487 put_task_struct(tsk);
2488 goto out_unlock_threadgroup;
2490 out_unlock_rcu:
2491 rcu_read_unlock();
2492 out_unlock_threadgroup:
2493 percpu_up_write(&cgroup_threadgroup_rwsem);
2494 cgroup_kn_unlock(of->kn);
2495 return ret ?: nbytes;
2499 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2500 * @from: attach to all cgroups of a given task
2501 * @tsk: the task to be attached
2503 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2505 struct cgroup_root *root;
2506 int retval = 0;
2508 mutex_lock(&cgroup_mutex);
2509 for_each_root(root) {
2510 struct cgroup *from_cgrp;
2512 if (root == &cgrp_dfl_root)
2513 continue;
2515 down_read(&css_set_rwsem);
2516 from_cgrp = task_cgroup_from_root(from, root);
2517 up_read(&css_set_rwsem);
2519 retval = cgroup_attach_task(from_cgrp, tsk, false);
2520 if (retval)
2521 break;
2523 mutex_unlock(&cgroup_mutex);
2525 return retval;
2527 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2529 static ssize_t cgroup_tasks_write(struct kernfs_open_file *of,
2530 char *buf, size_t nbytes, loff_t off)
2532 return __cgroup_procs_write(of, buf, nbytes, off, false);
2535 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
2536 char *buf, size_t nbytes, loff_t off)
2538 return __cgroup_procs_write(of, buf, nbytes, off, true);
2541 static ssize_t cgroup_release_agent_write(struct kernfs_open_file *of,
2542 char *buf, size_t nbytes, loff_t off)
2544 struct cgroup *cgrp;
2546 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
2548 cgrp = cgroup_kn_lock_live(of->kn);
2549 if (!cgrp)
2550 return -ENODEV;
2551 spin_lock(&release_agent_path_lock);
2552 strlcpy(cgrp->root->release_agent_path, strstrip(buf),
2553 sizeof(cgrp->root->release_agent_path));
2554 spin_unlock(&release_agent_path_lock);
2555 cgroup_kn_unlock(of->kn);
2556 return nbytes;
2559 static int cgroup_release_agent_show(struct seq_file *seq, void *v)
2561 struct cgroup *cgrp = seq_css(seq)->cgroup;
2563 spin_lock(&release_agent_path_lock);
2564 seq_puts(seq, cgrp->root->release_agent_path);
2565 spin_unlock(&release_agent_path_lock);
2566 seq_putc(seq, '\n');
2567 return 0;
2570 static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
2572 seq_puts(seq, "0\n");
2573 return 0;
2576 static void cgroup_print_ss_mask(struct seq_file *seq, unsigned long ss_mask)
2578 struct cgroup_subsys *ss;
2579 bool printed = false;
2580 int ssid;
2582 for_each_subsys_which(ss, ssid, &ss_mask) {
2583 if (printed)
2584 seq_putc(seq, ' ');
2585 seq_printf(seq, "%s", ss->name);
2586 printed = true;
2588 if (printed)
2589 seq_putc(seq, '\n');
2592 /* show controllers which are currently attached to the default hierarchy */
2593 static int cgroup_root_controllers_show(struct seq_file *seq, void *v)
2595 struct cgroup *cgrp = seq_css(seq)->cgroup;
2597 cgroup_print_ss_mask(seq, cgrp->root->subsys_mask &
2598 ~cgrp_dfl_root_inhibit_ss_mask);
2599 return 0;
2602 /* show controllers which are enabled from the parent */
2603 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2605 struct cgroup *cgrp = seq_css(seq)->cgroup;
2607 cgroup_print_ss_mask(seq, cgroup_parent(cgrp)->subtree_control);
2608 return 0;
2611 /* show controllers which are enabled for a given cgroup's children */
2612 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2614 struct cgroup *cgrp = seq_css(seq)->cgroup;
2616 cgroup_print_ss_mask(seq, cgrp->subtree_control);
2617 return 0;
2621 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2622 * @cgrp: root of the subtree to update csses for
2624 * @cgrp's child_subsys_mask has changed and its subtree's (self excluded)
2625 * css associations need to be updated accordingly. This function looks up
2626 * all css_sets which are attached to the subtree, creates the matching
2627 * updated css_sets and migrates the tasks to the new ones.
2629 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2631 LIST_HEAD(preloaded_csets);
2632 struct cgroup_subsys_state *css;
2633 struct css_set *src_cset;
2634 int ret;
2636 lockdep_assert_held(&cgroup_mutex);
2638 percpu_down_write(&cgroup_threadgroup_rwsem);
2640 /* look up all csses currently attached to @cgrp's subtree */
2641 down_read(&css_set_rwsem);
2642 css_for_each_descendant_pre(css, cgroup_css(cgrp, NULL)) {
2643 struct cgrp_cset_link *link;
2645 /* self is not affected by child_subsys_mask change */
2646 if (css->cgroup == cgrp)
2647 continue;
2649 list_for_each_entry(link, &css->cgroup->cset_links, cset_link)
2650 cgroup_migrate_add_src(link->cset, cgrp,
2651 &preloaded_csets);
2653 up_read(&css_set_rwsem);
2655 /* NULL dst indicates self on default hierarchy */
2656 ret = cgroup_migrate_prepare_dst(NULL, &preloaded_csets);
2657 if (ret)
2658 goto out_finish;
2660 list_for_each_entry(src_cset, &preloaded_csets, mg_preload_node) {
2661 struct task_struct *last_task = NULL, *task;
2663 /* src_csets precede dst_csets, break on the first dst_cset */
2664 if (!src_cset->mg_src_cgrp)
2665 break;
2668 * All tasks in src_cset need to be migrated to the
2669 * matching dst_cset. Empty it process by process. We
2670 * walk tasks but migrate processes. The leader might even
2671 * belong to a different cset but such src_cset would also
2672 * be among the target src_csets because the default
2673 * hierarchy enforces per-process membership.
2675 while (true) {
2676 down_read(&css_set_rwsem);
2677 task = list_first_entry_or_null(&src_cset->tasks,
2678 struct task_struct, cg_list);
2679 if (task) {
2680 task = task->group_leader;
2681 WARN_ON_ONCE(!task_css_set(task)->mg_src_cgrp);
2682 get_task_struct(task);
2684 up_read(&css_set_rwsem);
2686 if (!task)
2687 break;
2689 /* guard against possible infinite loop */
2690 if (WARN(last_task == task,
2691 "cgroup: update_dfl_csses failed to make progress, aborting in inconsistent state\n"))
2692 goto out_finish;
2693 last_task = task;
2695 ret = cgroup_migrate(src_cset->dfl_cgrp, task, true);
2697 put_task_struct(task);
2699 if (WARN(ret, "cgroup: failed to update controllers for the default hierarchy (%d), further operations may crash or hang\n", ret))
2700 goto out_finish;
2704 out_finish:
2705 cgroup_migrate_finish(&preloaded_csets);
2706 percpu_up_write(&cgroup_threadgroup_rwsem);
2707 return ret;
2710 /* change the enabled child controllers for a cgroup in the default hierarchy */
2711 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
2712 char *buf, size_t nbytes,
2713 loff_t off)
2715 unsigned long enable = 0, disable = 0;
2716 unsigned long css_enable, css_disable, old_sc, new_sc, old_ss, new_ss;
2717 struct cgroup *cgrp, *child;
2718 struct cgroup_subsys *ss;
2719 char *tok;
2720 int ssid, ret;
2723 * Parse input - space separated list of subsystem names prefixed
2724 * with either + or -.
2726 buf = strstrip(buf);
2727 while ((tok = strsep(&buf, " "))) {
2728 unsigned long tmp_ss_mask = ~cgrp_dfl_root_inhibit_ss_mask;
2730 if (tok[0] == '\0')
2731 continue;
2732 for_each_subsys_which(ss, ssid, &tmp_ss_mask) {
2733 if (ss->disabled || strcmp(tok + 1, ss->name))
2734 continue;
2736 if (*tok == '+') {
2737 enable |= 1 << ssid;
2738 disable &= ~(1 << ssid);
2739 } else if (*tok == '-') {
2740 disable |= 1 << ssid;
2741 enable &= ~(1 << ssid);
2742 } else {
2743 return -EINVAL;
2745 break;
2747 if (ssid == CGROUP_SUBSYS_COUNT)
2748 return -EINVAL;
2751 cgrp = cgroup_kn_lock_live(of->kn);
2752 if (!cgrp)
2753 return -ENODEV;
2755 for_each_subsys(ss, ssid) {
2756 if (enable & (1 << ssid)) {
2757 if (cgrp->subtree_control & (1 << ssid)) {
2758 enable &= ~(1 << ssid);
2759 continue;
2762 /* unavailable or not enabled on the parent? */
2763 if (!(cgrp_dfl_root.subsys_mask & (1 << ssid)) ||
2764 (cgroup_parent(cgrp) &&
2765 !(cgroup_parent(cgrp)->subtree_control & (1 << ssid)))) {
2766 ret = -ENOENT;
2767 goto out_unlock;
2769 } else if (disable & (1 << ssid)) {
2770 if (!(cgrp->subtree_control & (1 << ssid))) {
2771 disable &= ~(1 << ssid);
2772 continue;
2775 /* a child has it enabled? */
2776 cgroup_for_each_live_child(child, cgrp) {
2777 if (child->subtree_control & (1 << ssid)) {
2778 ret = -EBUSY;
2779 goto out_unlock;
2785 if (!enable && !disable) {
2786 ret = 0;
2787 goto out_unlock;
2791 * Except for the root, subtree_control must be zero for a cgroup
2792 * with tasks so that child cgroups don't compete against tasks.
2794 if (enable && cgroup_parent(cgrp) && !list_empty(&cgrp->cset_links)) {
2795 ret = -EBUSY;
2796 goto out_unlock;
2800 * Update subsys masks and calculate what needs to be done. More
2801 * subsystems than specified may need to be enabled or disabled
2802 * depending on subsystem dependencies.
2804 old_sc = cgrp->subtree_control;
2805 old_ss = cgrp->child_subsys_mask;
2806 new_sc = (old_sc | enable) & ~disable;
2807 new_ss = cgroup_calc_child_subsys_mask(cgrp, new_sc);
2809 css_enable = ~old_ss & new_ss;
2810 css_disable = old_ss & ~new_ss;
2811 enable |= css_enable;
2812 disable |= css_disable;
2815 * Because css offlining is asynchronous, userland might try to
2816 * re-enable the same controller while the previous instance is
2817 * still around. In such cases, wait till it's gone using
2818 * offline_waitq.
2820 for_each_subsys_which(ss, ssid, &css_enable) {
2821 cgroup_for_each_live_child(child, cgrp) {
2822 DEFINE_WAIT(wait);
2824 if (!cgroup_css(child, ss))
2825 continue;
2827 cgroup_get(child);
2828 prepare_to_wait(&child->offline_waitq, &wait,
2829 TASK_UNINTERRUPTIBLE);
2830 cgroup_kn_unlock(of->kn);
2831 schedule();
2832 finish_wait(&child->offline_waitq, &wait);
2833 cgroup_put(child);
2835 return restart_syscall();
2839 cgrp->subtree_control = new_sc;
2840 cgrp->child_subsys_mask = new_ss;
2843 * Create new csses or make the existing ones visible. A css is
2844 * created invisible if it's being implicitly enabled through
2845 * dependency. An invisible css is made visible when the userland
2846 * explicitly enables it.
2848 for_each_subsys(ss, ssid) {
2849 if (!(enable & (1 << ssid)))
2850 continue;
2852 cgroup_for_each_live_child(child, cgrp) {
2853 if (css_enable & (1 << ssid))
2854 ret = create_css(child, ss,
2855 cgrp->subtree_control & (1 << ssid));
2856 else
2857 ret = cgroup_populate_dir(child, 1 << ssid);
2858 if (ret)
2859 goto err_undo_css;
2864 * At this point, cgroup_e_css() results reflect the new csses
2865 * making the following cgroup_update_dfl_csses() properly update
2866 * css associations of all tasks in the subtree.
2868 ret = cgroup_update_dfl_csses(cgrp);
2869 if (ret)
2870 goto err_undo_css;
2873 * All tasks are migrated out of disabled csses. Kill or hide
2874 * them. A css is hidden when the userland requests it to be
2875 * disabled while other subsystems are still depending on it. The
2876 * css must not actively control resources and be in the vanilla
2877 * state if it's made visible again later. Controllers which may
2878 * be depended upon should provide ->css_reset() for this purpose.
2880 for_each_subsys(ss, ssid) {
2881 if (!(disable & (1 << ssid)))
2882 continue;
2884 cgroup_for_each_live_child(child, cgrp) {
2885 struct cgroup_subsys_state *css = cgroup_css(child, ss);
2887 if (css_disable & (1 << ssid)) {
2888 kill_css(css);
2889 } else {
2890 cgroup_clear_dir(child, 1 << ssid);
2891 if (ss->css_reset)
2892 ss->css_reset(css);
2898 * The effective csses of all the descendants (excluding @cgrp) may
2899 * have changed. Subsystems can optionally subscribe to this event
2900 * by implementing ->css_e_css_changed() which is invoked if any of
2901 * the effective csses seen from the css's cgroup may have changed.
2903 for_each_subsys(ss, ssid) {
2904 struct cgroup_subsys_state *this_css = cgroup_css(cgrp, ss);
2905 struct cgroup_subsys_state *css;
2907 if (!ss->css_e_css_changed || !this_css)
2908 continue;
2910 css_for_each_descendant_pre(css, this_css)
2911 if (css != this_css)
2912 ss->css_e_css_changed(css);
2915 kernfs_activate(cgrp->kn);
2916 ret = 0;
2917 out_unlock:
2918 cgroup_kn_unlock(of->kn);
2919 return ret ?: nbytes;
2921 err_undo_css:
2922 cgrp->subtree_control = old_sc;
2923 cgrp->child_subsys_mask = old_ss;
2925 for_each_subsys(ss, ssid) {
2926 if (!(enable & (1 << ssid)))
2927 continue;
2929 cgroup_for_each_live_child(child, cgrp) {
2930 struct cgroup_subsys_state *css = cgroup_css(child, ss);
2932 if (!css)
2933 continue;
2935 if (css_enable & (1 << ssid))
2936 kill_css(css);
2937 else
2938 cgroup_clear_dir(child, 1 << ssid);
2941 goto out_unlock;
2944 static int cgroup_populated_show(struct seq_file *seq, void *v)
2946 seq_printf(seq, "%d\n", (bool)seq_css(seq)->cgroup->populated_cnt);
2947 return 0;
2950 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
2951 size_t nbytes, loff_t off)
2953 struct cgroup *cgrp = of->kn->parent->priv;
2954 struct cftype *cft = of->kn->priv;
2955 struct cgroup_subsys_state *css;
2956 int ret;
2958 if (cft->write)
2959 return cft->write(of, buf, nbytes, off);
2962 * kernfs guarantees that a file isn't deleted with operations in
2963 * flight, which means that the matching css is and stays alive and
2964 * doesn't need to be pinned. The RCU locking is not necessary
2965 * either. It's just for the convenience of using cgroup_css().
2967 rcu_read_lock();
2968 css = cgroup_css(cgrp, cft->ss);
2969 rcu_read_unlock();
2971 if (cft->write_u64) {
2972 unsigned long long v;
2973 ret = kstrtoull(buf, 0, &v);
2974 if (!ret)
2975 ret = cft->write_u64(css, cft, v);
2976 } else if (cft->write_s64) {
2977 long long v;
2978 ret = kstrtoll(buf, 0, &v);
2979 if (!ret)
2980 ret = cft->write_s64(css, cft, v);
2981 } else {
2982 ret = -EINVAL;
2985 return ret ?: nbytes;
2988 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
2990 return seq_cft(seq)->seq_start(seq, ppos);
2993 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
2995 return seq_cft(seq)->seq_next(seq, v, ppos);
2998 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
3000 seq_cft(seq)->seq_stop(seq, v);
3003 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
3005 struct cftype *cft = seq_cft(m);
3006 struct cgroup_subsys_state *css = seq_css(m);
3008 if (cft->seq_show)
3009 return cft->seq_show(m, arg);
3011 if (cft->read_u64)
3012 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
3013 else if (cft->read_s64)
3014 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
3015 else
3016 return -EINVAL;
3017 return 0;
3020 static struct kernfs_ops cgroup_kf_single_ops = {
3021 .atomic_write_len = PAGE_SIZE,
3022 .write = cgroup_file_write,
3023 .seq_show = cgroup_seqfile_show,
3026 static struct kernfs_ops cgroup_kf_ops = {
3027 .atomic_write_len = PAGE_SIZE,
3028 .write = cgroup_file_write,
3029 .seq_start = cgroup_seqfile_start,
3030 .seq_next = cgroup_seqfile_next,
3031 .seq_stop = cgroup_seqfile_stop,
3032 .seq_show = cgroup_seqfile_show,
3036 * cgroup_rename - Only allow simple rename of directories in place.
3038 static int cgroup_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
3039 const char *new_name_str)
3041 struct cgroup *cgrp = kn->priv;
3042 int ret;
3044 if (kernfs_type(kn) != KERNFS_DIR)
3045 return -ENOTDIR;
3046 if (kn->parent != new_parent)
3047 return -EIO;
3050 * This isn't a proper migration and its usefulness is very
3051 * limited. Disallow on the default hierarchy.
3053 if (cgroup_on_dfl(cgrp))
3054 return -EPERM;
3057 * We're gonna grab cgroup_mutex which nests outside kernfs
3058 * active_ref. kernfs_rename() doesn't require active_ref
3059 * protection. Break them before grabbing cgroup_mutex.
3061 kernfs_break_active_protection(new_parent);
3062 kernfs_break_active_protection(kn);
3064 mutex_lock(&cgroup_mutex);
3066 ret = kernfs_rename(kn, new_parent, new_name_str);
3068 mutex_unlock(&cgroup_mutex);
3070 kernfs_unbreak_active_protection(kn);
3071 kernfs_unbreak_active_protection(new_parent);
3072 return ret;
3075 /* set uid and gid of cgroup dirs and files to that of the creator */
3076 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
3078 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
3079 .ia_uid = current_fsuid(),
3080 .ia_gid = current_fsgid(), };
3082 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
3083 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
3084 return 0;
3086 return kernfs_setattr(kn, &iattr);
3089 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
3091 char name[CGROUP_FILE_NAME_MAX];
3092 struct kernfs_node *kn;
3093 struct lock_class_key *key = NULL;
3094 int ret;
3096 #ifdef CONFIG_DEBUG_LOCK_ALLOC
3097 key = &cft->lockdep_key;
3098 #endif
3099 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
3100 cgroup_file_mode(cft), 0, cft->kf_ops, cft,
3101 NULL, key);
3102 if (IS_ERR(kn))
3103 return PTR_ERR(kn);
3105 ret = cgroup_kn_set_ugid(kn);
3106 if (ret) {
3107 kernfs_remove(kn);
3108 return ret;
3111 if (cft->write == cgroup_procs_write)
3112 cgrp->procs_kn = kn;
3113 else if (cft->seq_show == cgroup_populated_show)
3114 cgrp->populated_kn = kn;
3115 return 0;
3119 * cgroup_addrm_files - add or remove files to a cgroup directory
3120 * @cgrp: the target cgroup
3121 * @cfts: array of cftypes to be added
3122 * @is_add: whether to add or remove
3124 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
3125 * For removals, this function never fails. If addition fails, this
3126 * function doesn't remove files already added. The caller is responsible
3127 * for cleaning up.
3129 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
3130 bool is_add)
3132 struct cftype *cft;
3133 int ret;
3135 lockdep_assert_held(&cgroup_mutex);
3137 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3138 /* does cft->flags tell us to skip this file on @cgrp? */
3139 if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
3140 continue;
3141 if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
3142 continue;
3143 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
3144 continue;
3145 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
3146 continue;
3148 if (is_add) {
3149 ret = cgroup_add_file(cgrp, cft);
3150 if (ret) {
3151 pr_warn("%s: failed to add %s, err=%d\n",
3152 __func__, cft->name, ret);
3153 return ret;
3155 } else {
3156 cgroup_rm_file(cgrp, cft);
3159 return 0;
3162 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
3164 LIST_HEAD(pending);
3165 struct cgroup_subsys *ss = cfts[0].ss;
3166 struct cgroup *root = &ss->root->cgrp;
3167 struct cgroup_subsys_state *css;
3168 int ret = 0;
3170 lockdep_assert_held(&cgroup_mutex);
3172 /* add/rm files for all cgroups created before */
3173 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
3174 struct cgroup *cgrp = css->cgroup;
3176 if (cgroup_is_dead(cgrp))
3177 continue;
3179 ret = cgroup_addrm_files(cgrp, cfts, is_add);
3180 if (ret)
3181 break;
3184 if (is_add && !ret)
3185 kernfs_activate(root->kn);
3186 return ret;
3189 static void cgroup_exit_cftypes(struct cftype *cfts)
3191 struct cftype *cft;
3193 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3194 /* free copy for custom atomic_write_len, see init_cftypes() */
3195 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
3196 kfree(cft->kf_ops);
3197 cft->kf_ops = NULL;
3198 cft->ss = NULL;
3200 /* revert flags set by cgroup core while adding @cfts */
3201 cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL);
3205 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3207 struct cftype *cft;
3209 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3210 struct kernfs_ops *kf_ops;
3212 WARN_ON(cft->ss || cft->kf_ops);
3214 if (cft->seq_start)
3215 kf_ops = &cgroup_kf_ops;
3216 else
3217 kf_ops = &cgroup_kf_single_ops;
3220 * Ugh... if @cft wants a custom max_write_len, we need to
3221 * make a copy of kf_ops to set its atomic_write_len.
3223 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
3224 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
3225 if (!kf_ops) {
3226 cgroup_exit_cftypes(cfts);
3227 return -ENOMEM;
3229 kf_ops->atomic_write_len = cft->max_write_len;
3232 cft->kf_ops = kf_ops;
3233 cft->ss = ss;
3236 return 0;
3239 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
3241 lockdep_assert_held(&cgroup_mutex);
3243 if (!cfts || !cfts[0].ss)
3244 return -ENOENT;
3246 list_del(&cfts->node);
3247 cgroup_apply_cftypes(cfts, false);
3248 cgroup_exit_cftypes(cfts);
3249 return 0;
3253 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
3254 * @cfts: zero-length name terminated array of cftypes
3256 * Unregister @cfts. Files described by @cfts are removed from all
3257 * existing cgroups and all future cgroups won't have them either. This
3258 * function can be called anytime whether @cfts' subsys is attached or not.
3260 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
3261 * registered.
3263 int cgroup_rm_cftypes(struct cftype *cfts)
3265 int ret;
3267 mutex_lock(&cgroup_mutex);
3268 ret = cgroup_rm_cftypes_locked(cfts);
3269 mutex_unlock(&cgroup_mutex);
3270 return ret;
3274 * cgroup_add_cftypes - add an array of cftypes to a subsystem
3275 * @ss: target cgroup subsystem
3276 * @cfts: zero-length name terminated array of cftypes
3278 * Register @cfts to @ss. Files described by @cfts are created for all
3279 * existing cgroups to which @ss is attached and all future cgroups will
3280 * have them too. This function can be called anytime whether @ss is
3281 * attached or not.
3283 * Returns 0 on successful registration, -errno on failure. Note that this
3284 * function currently returns 0 as long as @cfts registration is successful
3285 * even if some file creation attempts on existing cgroups fail.
3287 static int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3289 int ret;
3291 if (ss->disabled)
3292 return 0;
3294 if (!cfts || cfts[0].name[0] == '\0')
3295 return 0;
3297 ret = cgroup_init_cftypes(ss, cfts);
3298 if (ret)
3299 return ret;
3301 mutex_lock(&cgroup_mutex);
3303 list_add_tail(&cfts->node, &ss->cfts);
3304 ret = cgroup_apply_cftypes(cfts, true);
3305 if (ret)
3306 cgroup_rm_cftypes_locked(cfts);
3308 mutex_unlock(&cgroup_mutex);
3309 return ret;
3313 * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
3314 * @ss: target cgroup subsystem
3315 * @cfts: zero-length name terminated array of cftypes
3317 * Similar to cgroup_add_cftypes() but the added files are only used for
3318 * the default hierarchy.
3320 int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3322 struct cftype *cft;
3324 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3325 cft->flags |= __CFTYPE_ONLY_ON_DFL;
3326 return cgroup_add_cftypes(ss, cfts);
3330 * cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies
3331 * @ss: target cgroup subsystem
3332 * @cfts: zero-length name terminated array of cftypes
3334 * Similar to cgroup_add_cftypes() but the added files are only used for
3335 * the legacy hierarchies.
3337 int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3339 struct cftype *cft;
3342 * If legacy_flies_on_dfl, we want to show the legacy files on the
3343 * dfl hierarchy but iff the target subsystem hasn't been updated
3344 * for the dfl hierarchy yet.
3346 if (!cgroup_legacy_files_on_dfl ||
3347 ss->dfl_cftypes != ss->legacy_cftypes) {
3348 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3349 cft->flags |= __CFTYPE_NOT_ON_DFL;
3352 return cgroup_add_cftypes(ss, cfts);
3356 * cgroup_task_count - count the number of tasks in a cgroup.
3357 * @cgrp: the cgroup in question
3359 * Return the number of tasks in the cgroup.
3361 static int cgroup_task_count(const struct cgroup *cgrp)
3363 int count = 0;
3364 struct cgrp_cset_link *link;
3366 down_read(&css_set_rwsem);
3367 list_for_each_entry(link, &cgrp->cset_links, cset_link)
3368 count += atomic_read(&link->cset->refcount);
3369 up_read(&css_set_rwsem);
3370 return count;
3374 * css_next_child - find the next child of a given css
3375 * @pos: the current position (%NULL to initiate traversal)
3376 * @parent: css whose children to walk
3378 * This function returns the next child of @parent and should be called
3379 * under either cgroup_mutex or RCU read lock. The only requirement is
3380 * that @parent and @pos are accessible. The next sibling is guaranteed to
3381 * be returned regardless of their states.
3383 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3384 * css which finished ->css_online() is guaranteed to be visible in the
3385 * future iterations and will stay visible until the last reference is put.
3386 * A css which hasn't finished ->css_online() or already finished
3387 * ->css_offline() may show up during traversal. It's each subsystem's
3388 * responsibility to synchronize against on/offlining.
3390 struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
3391 struct cgroup_subsys_state *parent)
3393 struct cgroup_subsys_state *next;
3395 cgroup_assert_mutex_or_rcu_locked();
3398 * @pos could already have been unlinked from the sibling list.
3399 * Once a cgroup is removed, its ->sibling.next is no longer
3400 * updated when its next sibling changes. CSS_RELEASED is set when
3401 * @pos is taken off list, at which time its next pointer is valid,
3402 * and, as releases are serialized, the one pointed to by the next
3403 * pointer is guaranteed to not have started release yet. This
3404 * implies that if we observe !CSS_RELEASED on @pos in this RCU
3405 * critical section, the one pointed to by its next pointer is
3406 * guaranteed to not have finished its RCU grace period even if we
3407 * have dropped rcu_read_lock() inbetween iterations.
3409 * If @pos has CSS_RELEASED set, its next pointer can't be
3410 * dereferenced; however, as each css is given a monotonically
3411 * increasing unique serial number and always appended to the
3412 * sibling list, the next one can be found by walking the parent's
3413 * children until the first css with higher serial number than
3414 * @pos's. While this path can be slower, it happens iff iteration
3415 * races against release and the race window is very small.
3417 if (!pos) {
3418 next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
3419 } else if (likely(!(pos->flags & CSS_RELEASED))) {
3420 next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
3421 } else {
3422 list_for_each_entry_rcu(next, &parent->children, sibling)
3423 if (next->serial_nr > pos->serial_nr)
3424 break;
3428 * @next, if not pointing to the head, can be dereferenced and is
3429 * the next sibling.
3431 if (&next->sibling != &parent->children)
3432 return next;
3433 return NULL;
3437 * css_next_descendant_pre - find the next descendant for pre-order walk
3438 * @pos: the current position (%NULL to initiate traversal)
3439 * @root: css whose descendants to walk
3441 * To be used by css_for_each_descendant_pre(). Find the next descendant
3442 * to visit for pre-order traversal of @root's descendants. @root is
3443 * included in the iteration and the first node to be visited.
3445 * While this function requires cgroup_mutex or RCU read locking, it
3446 * doesn't require the whole traversal to be contained in a single critical
3447 * section. This function will return the correct next descendant as long
3448 * as both @pos and @root are accessible and @pos is a descendant of @root.
3450 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3451 * css which finished ->css_online() is guaranteed to be visible in the
3452 * future iterations and will stay visible until the last reference is put.
3453 * A css which hasn't finished ->css_online() or already finished
3454 * ->css_offline() may show up during traversal. It's each subsystem's
3455 * responsibility to synchronize against on/offlining.
3457 struct cgroup_subsys_state *
3458 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3459 struct cgroup_subsys_state *root)
3461 struct cgroup_subsys_state *next;
3463 cgroup_assert_mutex_or_rcu_locked();
3465 /* if first iteration, visit @root */
3466 if (!pos)
3467 return root;
3469 /* visit the first child if exists */
3470 next = css_next_child(NULL, pos);
3471 if (next)
3472 return next;
3474 /* no child, visit my or the closest ancestor's next sibling */
3475 while (pos != root) {
3476 next = css_next_child(pos, pos->parent);
3477 if (next)
3478 return next;
3479 pos = pos->parent;
3482 return NULL;
3486 * css_rightmost_descendant - return the rightmost descendant of a css
3487 * @pos: css of interest
3489 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3490 * is returned. This can be used during pre-order traversal to skip
3491 * subtree of @pos.
3493 * While this function requires cgroup_mutex or RCU read locking, it
3494 * doesn't require the whole traversal to be contained in a single critical
3495 * section. This function will return the correct rightmost descendant as
3496 * long as @pos is accessible.
3498 struct cgroup_subsys_state *
3499 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3501 struct cgroup_subsys_state *last, *tmp;
3503 cgroup_assert_mutex_or_rcu_locked();
3505 do {
3506 last = pos;
3507 /* ->prev isn't RCU safe, walk ->next till the end */
3508 pos = NULL;
3509 css_for_each_child(tmp, last)
3510 pos = tmp;
3511 } while (pos);
3513 return last;
3516 static struct cgroup_subsys_state *
3517 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3519 struct cgroup_subsys_state *last;
3521 do {
3522 last = pos;
3523 pos = css_next_child(NULL, pos);
3524 } while (pos);
3526 return last;
3530 * css_next_descendant_post - find the next descendant for post-order walk
3531 * @pos: the current position (%NULL to initiate traversal)
3532 * @root: css whose descendants to walk
3534 * To be used by css_for_each_descendant_post(). Find the next descendant
3535 * to visit for post-order traversal of @root's descendants. @root is
3536 * included in the iteration and the last node to be visited.
3538 * While this function requires cgroup_mutex or RCU read locking, it
3539 * doesn't require the whole traversal to be contained in a single critical
3540 * section. This function will return the correct next descendant as long
3541 * as both @pos and @cgroup are accessible and @pos is a descendant of
3542 * @cgroup.
3544 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3545 * css which finished ->css_online() is guaranteed to be visible in the
3546 * future iterations and will stay visible until the last reference is put.
3547 * A css which hasn't finished ->css_online() or already finished
3548 * ->css_offline() may show up during traversal. It's each subsystem's
3549 * responsibility to synchronize against on/offlining.
3551 struct cgroup_subsys_state *
3552 css_next_descendant_post(struct cgroup_subsys_state *pos,
3553 struct cgroup_subsys_state *root)
3555 struct cgroup_subsys_state *next;
3557 cgroup_assert_mutex_or_rcu_locked();
3559 /* if first iteration, visit leftmost descendant which may be @root */
3560 if (!pos)
3561 return css_leftmost_descendant(root);
3563 /* if we visited @root, we're done */
3564 if (pos == root)
3565 return NULL;
3567 /* if there's an unvisited sibling, visit its leftmost descendant */
3568 next = css_next_child(pos, pos->parent);
3569 if (next)
3570 return css_leftmost_descendant(next);
3572 /* no sibling left, visit parent */
3573 return pos->parent;
3577 * css_has_online_children - does a css have online children
3578 * @css: the target css
3580 * Returns %true if @css has any online children; otherwise, %false. This
3581 * function can be called from any context but the caller is responsible
3582 * for synchronizing against on/offlining as necessary.
3584 bool css_has_online_children(struct cgroup_subsys_state *css)
3586 struct cgroup_subsys_state *child;
3587 bool ret = false;
3589 rcu_read_lock();
3590 css_for_each_child(child, css) {
3591 if (child->flags & CSS_ONLINE) {
3592 ret = true;
3593 break;
3596 rcu_read_unlock();
3597 return ret;
3601 * css_advance_task_iter - advance a task itererator to the next css_set
3602 * @it: the iterator to advance
3604 * Advance @it to the next css_set to walk.
3606 static void css_advance_task_iter(struct css_task_iter *it)
3608 struct list_head *l = it->cset_pos;
3609 struct cgrp_cset_link *link;
3610 struct css_set *cset;
3612 /* Advance to the next non-empty css_set */
3613 do {
3614 l = l->next;
3615 if (l == it->cset_head) {
3616 it->cset_pos = NULL;
3617 return;
3620 if (it->ss) {
3621 cset = container_of(l, struct css_set,
3622 e_cset_node[it->ss->id]);
3623 } else {
3624 link = list_entry(l, struct cgrp_cset_link, cset_link);
3625 cset = link->cset;
3627 } while (list_empty(&cset->tasks) && list_empty(&cset->mg_tasks));
3629 it->cset_pos = l;
3631 if (!list_empty(&cset->tasks))
3632 it->task_pos = cset->tasks.next;
3633 else
3634 it->task_pos = cset->mg_tasks.next;
3636 it->tasks_head = &cset->tasks;
3637 it->mg_tasks_head = &cset->mg_tasks;
3641 * css_task_iter_start - initiate task iteration
3642 * @css: the css to walk tasks of
3643 * @it: the task iterator to use
3645 * Initiate iteration through the tasks of @css. The caller can call
3646 * css_task_iter_next() to walk through the tasks until the function
3647 * returns NULL. On completion of iteration, css_task_iter_end() must be
3648 * called.
3650 * Note that this function acquires a lock which is released when the
3651 * iteration finishes. The caller can't sleep while iteration is in
3652 * progress.
3654 void css_task_iter_start(struct cgroup_subsys_state *css,
3655 struct css_task_iter *it)
3656 __acquires(css_set_rwsem)
3658 /* no one should try to iterate before mounting cgroups */
3659 WARN_ON_ONCE(!use_task_css_set_links);
3661 down_read(&css_set_rwsem);
3663 it->ss = css->ss;
3665 if (it->ss)
3666 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
3667 else
3668 it->cset_pos = &css->cgroup->cset_links;
3670 it->cset_head = it->cset_pos;
3672 css_advance_task_iter(it);
3676 * css_task_iter_next - return the next task for the iterator
3677 * @it: the task iterator being iterated
3679 * The "next" function for task iteration. @it should have been
3680 * initialized via css_task_iter_start(). Returns NULL when the iteration
3681 * reaches the end.
3683 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3685 struct task_struct *res;
3686 struct list_head *l = it->task_pos;
3688 /* If the iterator cg is NULL, we have no tasks */
3689 if (!it->cset_pos)
3690 return NULL;
3691 res = list_entry(l, struct task_struct, cg_list);
3694 * Advance iterator to find next entry. cset->tasks is consumed
3695 * first and then ->mg_tasks. After ->mg_tasks, we move onto the
3696 * next cset.
3698 l = l->next;
3700 if (l == it->tasks_head)
3701 l = it->mg_tasks_head->next;
3703 if (l == it->mg_tasks_head)
3704 css_advance_task_iter(it);
3705 else
3706 it->task_pos = l;
3708 return res;
3712 * css_task_iter_end - finish task iteration
3713 * @it: the task iterator to finish
3715 * Finish task iteration started by css_task_iter_start().
3717 void css_task_iter_end(struct css_task_iter *it)
3718 __releases(css_set_rwsem)
3720 up_read(&css_set_rwsem);
3724 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3725 * @to: cgroup to which the tasks will be moved
3726 * @from: cgroup in which the tasks currently reside
3728 * Locking rules between cgroup_post_fork() and the migration path
3729 * guarantee that, if a task is forking while being migrated, the new child
3730 * is guaranteed to be either visible in the source cgroup after the
3731 * parent's migration is complete or put into the target cgroup. No task
3732 * can slip out of migration through forking.
3734 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3736 LIST_HEAD(preloaded_csets);
3737 struct cgrp_cset_link *link;
3738 struct css_task_iter it;
3739 struct task_struct *task;
3740 int ret;
3742 mutex_lock(&cgroup_mutex);
3744 /* all tasks in @from are being moved, all csets are source */
3745 down_read(&css_set_rwsem);
3746 list_for_each_entry(link, &from->cset_links, cset_link)
3747 cgroup_migrate_add_src(link->cset, to, &preloaded_csets);
3748 up_read(&css_set_rwsem);
3750 ret = cgroup_migrate_prepare_dst(to, &preloaded_csets);
3751 if (ret)
3752 goto out_err;
3755 * Migrate tasks one-by-one until @form is empty. This fails iff
3756 * ->can_attach() fails.
3758 do {
3759 css_task_iter_start(&from->self, &it);
3760 task = css_task_iter_next(&it);
3761 if (task)
3762 get_task_struct(task);
3763 css_task_iter_end(&it);
3765 if (task) {
3766 ret = cgroup_migrate(to, task, false);
3767 put_task_struct(task);
3769 } while (task && !ret);
3770 out_err:
3771 cgroup_migrate_finish(&preloaded_csets);
3772 mutex_unlock(&cgroup_mutex);
3773 return ret;
3777 * Stuff for reading the 'tasks'/'procs' files.
3779 * Reading this file can return large amounts of data if a cgroup has
3780 * *lots* of attached tasks. So it may need several calls to read(),
3781 * but we cannot guarantee that the information we produce is correct
3782 * unless we produce it entirely atomically.
3786 /* which pidlist file are we talking about? */
3787 enum cgroup_filetype {
3788 CGROUP_FILE_PROCS,
3789 CGROUP_FILE_TASKS,
3793 * A pidlist is a list of pids that virtually represents the contents of one
3794 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3795 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3796 * to the cgroup.
3798 struct cgroup_pidlist {
3800 * used to find which pidlist is wanted. doesn't change as long as
3801 * this particular list stays in the list.
3803 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3804 /* array of xids */
3805 pid_t *list;
3806 /* how many elements the above list has */
3807 int length;
3808 /* each of these stored in a list by its cgroup */
3809 struct list_head links;
3810 /* pointer to the cgroup we belong to, for list removal purposes */
3811 struct cgroup *owner;
3812 /* for delayed destruction */
3813 struct delayed_work destroy_dwork;
3817 * The following two functions "fix" the issue where there are more pids
3818 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3819 * TODO: replace with a kernel-wide solution to this problem
3821 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3822 static void *pidlist_allocate(int count)
3824 if (PIDLIST_TOO_LARGE(count))
3825 return vmalloc(count * sizeof(pid_t));
3826 else
3827 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3830 static void pidlist_free(void *p)
3832 kvfree(p);
3836 * Used to destroy all pidlists lingering waiting for destroy timer. None
3837 * should be left afterwards.
3839 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
3841 struct cgroup_pidlist *l, *tmp_l;
3843 mutex_lock(&cgrp->pidlist_mutex);
3844 list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
3845 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
3846 mutex_unlock(&cgrp->pidlist_mutex);
3848 flush_workqueue(cgroup_pidlist_destroy_wq);
3849 BUG_ON(!list_empty(&cgrp->pidlists));
3852 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
3854 struct delayed_work *dwork = to_delayed_work(work);
3855 struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
3856 destroy_dwork);
3857 struct cgroup_pidlist *tofree = NULL;
3859 mutex_lock(&l->owner->pidlist_mutex);
3862 * Destroy iff we didn't get queued again. The state won't change
3863 * as destroy_dwork can only be queued while locked.
3865 if (!delayed_work_pending(dwork)) {
3866 list_del(&l->links);
3867 pidlist_free(l->list);
3868 put_pid_ns(l->key.ns);
3869 tofree = l;
3872 mutex_unlock(&l->owner->pidlist_mutex);
3873 kfree(tofree);
3877 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3878 * Returns the number of unique elements.
3880 static int pidlist_uniq(pid_t *list, int length)
3882 int src, dest = 1;
3885 * we presume the 0th element is unique, so i starts at 1. trivial
3886 * edge cases first; no work needs to be done for either
3888 if (length == 0 || length == 1)
3889 return length;
3890 /* src and dest walk down the list; dest counts unique elements */
3891 for (src = 1; src < length; src++) {
3892 /* find next unique element */
3893 while (list[src] == list[src-1]) {
3894 src++;
3895 if (src == length)
3896 goto after;
3898 /* dest always points to where the next unique element goes */
3899 list[dest] = list[src];
3900 dest++;
3902 after:
3903 return dest;
3907 * The two pid files - task and cgroup.procs - guaranteed that the result
3908 * is sorted, which forced this whole pidlist fiasco. As pid order is
3909 * different per namespace, each namespace needs differently sorted list,
3910 * making it impossible to use, for example, single rbtree of member tasks
3911 * sorted by task pointer. As pidlists can be fairly large, allocating one
3912 * per open file is dangerous, so cgroup had to implement shared pool of
3913 * pidlists keyed by cgroup and namespace.
3915 * All this extra complexity was caused by the original implementation
3916 * committing to an entirely unnecessary property. In the long term, we
3917 * want to do away with it. Explicitly scramble sort order if on the
3918 * default hierarchy so that no such expectation exists in the new
3919 * interface.
3921 * Scrambling is done by swapping every two consecutive bits, which is
3922 * non-identity one-to-one mapping which disturbs sort order sufficiently.
3924 static pid_t pid_fry(pid_t pid)
3926 unsigned a = pid & 0x55555555;
3927 unsigned b = pid & 0xAAAAAAAA;
3929 return (a << 1) | (b >> 1);
3932 static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
3934 if (cgroup_on_dfl(cgrp))
3935 return pid_fry(pid);
3936 else
3937 return pid;
3940 static int cmppid(const void *a, const void *b)
3942 return *(pid_t *)a - *(pid_t *)b;
3945 static int fried_cmppid(const void *a, const void *b)
3947 return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
3950 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3951 enum cgroup_filetype type)
3953 struct cgroup_pidlist *l;
3954 /* don't need task_nsproxy() if we're looking at ourself */
3955 struct pid_namespace *ns = task_active_pid_ns(current);
3957 lockdep_assert_held(&cgrp->pidlist_mutex);
3959 list_for_each_entry(l, &cgrp->pidlists, links)
3960 if (l->key.type == type && l->key.ns == ns)
3961 return l;
3962 return NULL;
3966 * find the appropriate pidlist for our purpose (given procs vs tasks)
3967 * returns with the lock on that pidlist already held, and takes care
3968 * of the use count, or returns NULL with no locks held if we're out of
3969 * memory.
3971 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
3972 enum cgroup_filetype type)
3974 struct cgroup_pidlist *l;
3976 lockdep_assert_held(&cgrp->pidlist_mutex);
3978 l = cgroup_pidlist_find(cgrp, type);
3979 if (l)
3980 return l;
3982 /* entry not found; create a new one */
3983 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3984 if (!l)
3985 return l;
3987 INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
3988 l->key.type = type;
3989 /* don't need task_nsproxy() if we're looking at ourself */
3990 l->key.ns = get_pid_ns(task_active_pid_ns(current));
3991 l->owner = cgrp;
3992 list_add(&l->links, &cgrp->pidlists);
3993 return l;
3997 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3999 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
4000 struct cgroup_pidlist **lp)
4002 pid_t *array;
4003 int length;
4004 int pid, n = 0; /* used for populating the array */
4005 struct css_task_iter it;
4006 struct task_struct *tsk;
4007 struct cgroup_pidlist *l;
4009 lockdep_assert_held(&cgrp->pidlist_mutex);
4012 * If cgroup gets more users after we read count, we won't have
4013 * enough space - tough. This race is indistinguishable to the
4014 * caller from the case that the additional cgroup users didn't
4015 * show up until sometime later on.
4017 length = cgroup_task_count(cgrp);
4018 array = pidlist_allocate(length);
4019 if (!array)
4020 return -ENOMEM;
4021 /* now, populate the array */
4022 css_task_iter_start(&cgrp->self, &it);
4023 while ((tsk = css_task_iter_next(&it))) {
4024 if (unlikely(n == length))
4025 break;
4026 /* get tgid or pid for procs or tasks file respectively */
4027 if (type == CGROUP_FILE_PROCS)
4028 pid = task_tgid_vnr(tsk);
4029 else
4030 pid = task_pid_vnr(tsk);
4031 if (pid > 0) /* make sure to only use valid results */
4032 array[n++] = pid;
4034 css_task_iter_end(&it);
4035 length = n;
4036 /* now sort & (if procs) strip out duplicates */
4037 if (cgroup_on_dfl(cgrp))
4038 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
4039 else
4040 sort(array, length, sizeof(pid_t), cmppid, NULL);
4041 if (type == CGROUP_FILE_PROCS)
4042 length = pidlist_uniq(array, length);
4044 l = cgroup_pidlist_find_create(cgrp, type);
4045 if (!l) {
4046 pidlist_free(array);
4047 return -ENOMEM;
4050 /* store array, freeing old if necessary */
4051 pidlist_free(l->list);
4052 l->list = array;
4053 l->length = length;
4054 *lp = l;
4055 return 0;
4059 * cgroupstats_build - build and fill cgroupstats
4060 * @stats: cgroupstats to fill information into
4061 * @dentry: A dentry entry belonging to the cgroup for which stats have
4062 * been requested.
4064 * Build and fill cgroupstats so that taskstats can export it to user
4065 * space.
4067 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
4069 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
4070 struct cgroup *cgrp;
4071 struct css_task_iter it;
4072 struct task_struct *tsk;
4074 /* it should be kernfs_node belonging to cgroupfs and is a directory */
4075 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
4076 kernfs_type(kn) != KERNFS_DIR)
4077 return -EINVAL;
4079 mutex_lock(&cgroup_mutex);
4082 * We aren't being called from kernfs and there's no guarantee on
4083 * @kn->priv's validity. For this and css_tryget_online_from_dir(),
4084 * @kn->priv is RCU safe. Let's do the RCU dancing.
4086 rcu_read_lock();
4087 cgrp = rcu_dereference(kn->priv);
4088 if (!cgrp || cgroup_is_dead(cgrp)) {
4089 rcu_read_unlock();
4090 mutex_unlock(&cgroup_mutex);
4091 return -ENOENT;
4093 rcu_read_unlock();
4095 css_task_iter_start(&cgrp->self, &it);
4096 while ((tsk = css_task_iter_next(&it))) {
4097 switch (tsk->state) {
4098 case TASK_RUNNING:
4099 stats->nr_running++;
4100 break;
4101 case TASK_INTERRUPTIBLE:
4102 stats->nr_sleeping++;
4103 break;
4104 case TASK_UNINTERRUPTIBLE:
4105 stats->nr_uninterruptible++;
4106 break;
4107 case TASK_STOPPED:
4108 stats->nr_stopped++;
4109 break;
4110 default:
4111 if (delayacct_is_task_waiting_on_io(tsk))
4112 stats->nr_io_wait++;
4113 break;
4116 css_task_iter_end(&it);
4118 mutex_unlock(&cgroup_mutex);
4119 return 0;
4124 * seq_file methods for the tasks/procs files. The seq_file position is the
4125 * next pid to display; the seq_file iterator is a pointer to the pid
4126 * in the cgroup->l->list array.
4129 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
4132 * Initially we receive a position value that corresponds to
4133 * one more than the last pid shown (or 0 on the first call or
4134 * after a seek to the start). Use a binary-search to find the
4135 * next pid to display, if any
4137 struct kernfs_open_file *of = s->private;
4138 struct cgroup *cgrp = seq_css(s)->cgroup;
4139 struct cgroup_pidlist *l;
4140 enum cgroup_filetype type = seq_cft(s)->private;
4141 int index = 0, pid = *pos;
4142 int *iter, ret;
4144 mutex_lock(&cgrp->pidlist_mutex);
4147 * !NULL @of->priv indicates that this isn't the first start()
4148 * after open. If the matching pidlist is around, we can use that.
4149 * Look for it. Note that @of->priv can't be used directly. It
4150 * could already have been destroyed.
4152 if (of->priv)
4153 of->priv = cgroup_pidlist_find(cgrp, type);
4156 * Either this is the first start() after open or the matching
4157 * pidlist has been destroyed inbetween. Create a new one.
4159 if (!of->priv) {
4160 ret = pidlist_array_load(cgrp, type,
4161 (struct cgroup_pidlist **)&of->priv);
4162 if (ret)
4163 return ERR_PTR(ret);
4165 l = of->priv;
4167 if (pid) {
4168 int end = l->length;
4170 while (index < end) {
4171 int mid = (index + end) / 2;
4172 if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
4173 index = mid;
4174 break;
4175 } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
4176 index = mid + 1;
4177 else
4178 end = mid;
4181 /* If we're off the end of the array, we're done */
4182 if (index >= l->length)
4183 return NULL;
4184 /* Update the abstract position to be the actual pid that we found */
4185 iter = l->list + index;
4186 *pos = cgroup_pid_fry(cgrp, *iter);
4187 return iter;
4190 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
4192 struct kernfs_open_file *of = s->private;
4193 struct cgroup_pidlist *l = of->priv;
4195 if (l)
4196 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
4197 CGROUP_PIDLIST_DESTROY_DELAY);
4198 mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
4201 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
4203 struct kernfs_open_file *of = s->private;
4204 struct cgroup_pidlist *l = of->priv;
4205 pid_t *p = v;
4206 pid_t *end = l->list + l->length;
4208 * Advance to the next pid in the array. If this goes off the
4209 * end, we're done
4211 p++;
4212 if (p >= end) {
4213 return NULL;
4214 } else {
4215 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
4216 return p;
4220 static int cgroup_pidlist_show(struct seq_file *s, void *v)
4222 seq_printf(s, "%d\n", *(int *)v);
4224 return 0;
4227 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
4228 struct cftype *cft)
4230 return notify_on_release(css->cgroup);
4233 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
4234 struct cftype *cft, u64 val)
4236 if (val)
4237 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
4238 else
4239 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
4240 return 0;
4243 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
4244 struct cftype *cft)
4246 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4249 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
4250 struct cftype *cft, u64 val)
4252 if (val)
4253 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4254 else
4255 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4256 return 0;
4259 /* cgroup core interface files for the default hierarchy */
4260 static struct cftype cgroup_dfl_base_files[] = {
4262 .name = "cgroup.procs",
4263 .seq_start = cgroup_pidlist_start,
4264 .seq_next = cgroup_pidlist_next,
4265 .seq_stop = cgroup_pidlist_stop,
4266 .seq_show = cgroup_pidlist_show,
4267 .private = CGROUP_FILE_PROCS,
4268 .write = cgroup_procs_write,
4269 .mode = S_IRUGO | S_IWUSR,
4272 .name = "cgroup.controllers",
4273 .flags = CFTYPE_ONLY_ON_ROOT,
4274 .seq_show = cgroup_root_controllers_show,
4277 .name = "cgroup.controllers",
4278 .flags = CFTYPE_NOT_ON_ROOT,
4279 .seq_show = cgroup_controllers_show,
4282 .name = "cgroup.subtree_control",
4283 .seq_show = cgroup_subtree_control_show,
4284 .write = cgroup_subtree_control_write,
4287 .name = "cgroup.populated",
4288 .flags = CFTYPE_NOT_ON_ROOT,
4289 .seq_show = cgroup_populated_show,
4291 { } /* terminate */
4294 /* cgroup core interface files for the legacy hierarchies */
4295 static struct cftype cgroup_legacy_base_files[] = {
4297 .name = "cgroup.procs",
4298 .seq_start = cgroup_pidlist_start,
4299 .seq_next = cgroup_pidlist_next,
4300 .seq_stop = cgroup_pidlist_stop,
4301 .seq_show = cgroup_pidlist_show,
4302 .private = CGROUP_FILE_PROCS,
4303 .write = cgroup_procs_write,
4304 .mode = S_IRUGO | S_IWUSR,
4307 .name = "cgroup.clone_children",
4308 .read_u64 = cgroup_clone_children_read,
4309 .write_u64 = cgroup_clone_children_write,
4312 .name = "cgroup.sane_behavior",
4313 .flags = CFTYPE_ONLY_ON_ROOT,
4314 .seq_show = cgroup_sane_behavior_show,
4317 .name = "tasks",
4318 .seq_start = cgroup_pidlist_start,
4319 .seq_next = cgroup_pidlist_next,
4320 .seq_stop = cgroup_pidlist_stop,
4321 .seq_show = cgroup_pidlist_show,
4322 .private = CGROUP_FILE_TASKS,
4323 .write = cgroup_tasks_write,
4324 .mode = S_IRUGO | S_IWUSR,
4327 .name = "notify_on_release",
4328 .read_u64 = cgroup_read_notify_on_release,
4329 .write_u64 = cgroup_write_notify_on_release,
4332 .name = "release_agent",
4333 .flags = CFTYPE_ONLY_ON_ROOT,
4334 .seq_show = cgroup_release_agent_show,
4335 .write = cgroup_release_agent_write,
4336 .max_write_len = PATH_MAX - 1,
4338 { } /* terminate */
4342 * cgroup_populate_dir - create subsys files in a cgroup directory
4343 * @cgrp: target cgroup
4344 * @subsys_mask: mask of the subsystem ids whose files should be added
4346 * On failure, no file is added.
4348 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
4350 struct cgroup_subsys *ss;
4351 int i, ret = 0;
4353 /* process cftsets of each subsystem */
4354 for_each_subsys(ss, i) {
4355 struct cftype *cfts;
4357 if (!(subsys_mask & (1 << i)))
4358 continue;
4360 list_for_each_entry(cfts, &ss->cfts, node) {
4361 ret = cgroup_addrm_files(cgrp, cfts, true);
4362 if (ret < 0)
4363 goto err;
4366 return 0;
4367 err:
4368 cgroup_clear_dir(cgrp, subsys_mask);
4369 return ret;
4373 * css destruction is four-stage process.
4375 * 1. Destruction starts. Killing of the percpu_ref is initiated.
4376 * Implemented in kill_css().
4378 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4379 * and thus css_tryget_online() is guaranteed to fail, the css can be
4380 * offlined by invoking offline_css(). After offlining, the base ref is
4381 * put. Implemented in css_killed_work_fn().
4383 * 3. When the percpu_ref reaches zero, the only possible remaining
4384 * accessors are inside RCU read sections. css_release() schedules the
4385 * RCU callback.
4387 * 4. After the grace period, the css can be freed. Implemented in
4388 * css_free_work_fn().
4390 * It is actually hairier because both step 2 and 4 require process context
4391 * and thus involve punting to css->destroy_work adding two additional
4392 * steps to the already complex sequence.
4394 static void css_free_work_fn(struct work_struct *work)
4396 struct cgroup_subsys_state *css =
4397 container_of(work, struct cgroup_subsys_state, destroy_work);
4398 struct cgroup_subsys *ss = css->ss;
4399 struct cgroup *cgrp = css->cgroup;
4401 percpu_ref_exit(&css->refcnt);
4403 if (ss) {
4404 /* css free path */
4405 int id = css->id;
4407 if (css->parent)
4408 css_put(css->parent);
4410 ss->css_free(css);
4411 cgroup_idr_remove(&ss->css_idr, id);
4412 cgroup_put(cgrp);
4413 } else {
4414 /* cgroup free path */
4415 atomic_dec(&cgrp->root->nr_cgrps);
4416 cgroup_pidlist_destroy_all(cgrp);
4417 cancel_work_sync(&cgrp->release_agent_work);
4419 if (cgroup_parent(cgrp)) {
4421 * We get a ref to the parent, and put the ref when
4422 * this cgroup is being freed, so it's guaranteed
4423 * that the parent won't be destroyed before its
4424 * children.
4426 cgroup_put(cgroup_parent(cgrp));
4427 kernfs_put(cgrp->kn);
4428 kfree(cgrp);
4429 } else {
4431 * This is root cgroup's refcnt reaching zero,
4432 * which indicates that the root should be
4433 * released.
4435 cgroup_destroy_root(cgrp->root);
4440 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4442 struct cgroup_subsys_state *css =
4443 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4445 INIT_WORK(&css->destroy_work, css_free_work_fn);
4446 queue_work(cgroup_destroy_wq, &css->destroy_work);
4449 static void css_release_work_fn(struct work_struct *work)
4451 struct cgroup_subsys_state *css =
4452 container_of(work, struct cgroup_subsys_state, destroy_work);
4453 struct cgroup_subsys *ss = css->ss;
4454 struct cgroup *cgrp = css->cgroup;
4456 mutex_lock(&cgroup_mutex);
4458 css->flags |= CSS_RELEASED;
4459 list_del_rcu(&css->sibling);
4461 if (ss) {
4462 /* css release path */
4463 cgroup_idr_replace(&ss->css_idr, NULL, css->id);
4464 if (ss->css_released)
4465 ss->css_released(css);
4466 } else {
4467 /* cgroup release path */
4468 cgroup_idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4469 cgrp->id = -1;
4472 * There are two control paths which try to determine
4473 * cgroup from dentry without going through kernfs -
4474 * cgroupstats_build() and css_tryget_online_from_dir().
4475 * Those are supported by RCU protecting clearing of
4476 * cgrp->kn->priv backpointer.
4478 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv, NULL);
4481 mutex_unlock(&cgroup_mutex);
4483 call_rcu(&css->rcu_head, css_free_rcu_fn);
4486 static void css_release(struct percpu_ref *ref)
4488 struct cgroup_subsys_state *css =
4489 container_of(ref, struct cgroup_subsys_state, refcnt);
4491 INIT_WORK(&css->destroy_work, css_release_work_fn);
4492 queue_work(cgroup_destroy_wq, &css->destroy_work);
4495 static void init_and_link_css(struct cgroup_subsys_state *css,
4496 struct cgroup_subsys *ss, struct cgroup *cgrp)
4498 lockdep_assert_held(&cgroup_mutex);
4500 cgroup_get(cgrp);
4502 memset(css, 0, sizeof(*css));
4503 css->cgroup = cgrp;
4504 css->ss = ss;
4505 INIT_LIST_HEAD(&css->sibling);
4506 INIT_LIST_HEAD(&css->children);
4507 css->serial_nr = css_serial_nr_next++;
4509 if (cgroup_parent(cgrp)) {
4510 css->parent = cgroup_css(cgroup_parent(cgrp), ss);
4511 css_get(css->parent);
4514 BUG_ON(cgroup_css(cgrp, ss));
4517 /* invoke ->css_online() on a new CSS and mark it online if successful */
4518 static int online_css(struct cgroup_subsys_state *css)
4520 struct cgroup_subsys *ss = css->ss;
4521 int ret = 0;
4523 lockdep_assert_held(&cgroup_mutex);
4525 if (ss->css_online)
4526 ret = ss->css_online(css);
4527 if (!ret) {
4528 css->flags |= CSS_ONLINE;
4529 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
4531 return ret;
4534 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4535 static void offline_css(struct cgroup_subsys_state *css)
4537 struct cgroup_subsys *ss = css->ss;
4539 lockdep_assert_held(&cgroup_mutex);
4541 if (!(css->flags & CSS_ONLINE))
4542 return;
4544 if (ss->css_offline)
4545 ss->css_offline(css);
4547 css->flags &= ~CSS_ONLINE;
4548 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
4550 wake_up_all(&css->cgroup->offline_waitq);
4554 * create_css - create a cgroup_subsys_state
4555 * @cgrp: the cgroup new css will be associated with
4556 * @ss: the subsys of new css
4557 * @visible: whether to create control knobs for the new css or not
4559 * Create a new css associated with @cgrp - @ss pair. On success, the new
4560 * css is online and installed in @cgrp with all interface files created if
4561 * @visible. Returns 0 on success, -errno on failure.
4563 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss,
4564 bool visible)
4566 struct cgroup *parent = cgroup_parent(cgrp);
4567 struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
4568 struct cgroup_subsys_state *css;
4569 int err;
4571 lockdep_assert_held(&cgroup_mutex);
4573 css = ss->css_alloc(parent_css);
4574 if (IS_ERR(css))
4575 return PTR_ERR(css);
4577 init_and_link_css(css, ss, cgrp);
4579 err = percpu_ref_init(&css->refcnt, css_release, 0, GFP_KERNEL);
4580 if (err)
4581 goto err_free_css;
4583 err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_NOWAIT);
4584 if (err < 0)
4585 goto err_free_percpu_ref;
4586 css->id = err;
4588 if (visible) {
4589 err = cgroup_populate_dir(cgrp, 1 << ss->id);
4590 if (err)
4591 goto err_free_id;
4594 /* @css is ready to be brought online now, make it visible */
4595 list_add_tail_rcu(&css->sibling, &parent_css->children);
4596 cgroup_idr_replace(&ss->css_idr, css, css->id);
4598 err = online_css(css);
4599 if (err)
4600 goto err_list_del;
4602 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4603 cgroup_parent(parent)) {
4604 pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4605 current->comm, current->pid, ss->name);
4606 if (!strcmp(ss->name, "memory"))
4607 pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
4608 ss->warned_broken_hierarchy = true;
4611 return 0;
4613 err_list_del:
4614 list_del_rcu(&css->sibling);
4615 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4616 err_free_id:
4617 cgroup_idr_remove(&ss->css_idr, css->id);
4618 err_free_percpu_ref:
4619 percpu_ref_exit(&css->refcnt);
4620 err_free_css:
4621 call_rcu(&css->rcu_head, css_free_rcu_fn);
4622 return err;
4625 static int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
4626 umode_t mode)
4628 struct cgroup *parent, *cgrp;
4629 struct cgroup_root *root;
4630 struct cgroup_subsys *ss;
4631 struct kernfs_node *kn;
4632 struct cftype *base_files;
4633 int ssid, ret;
4635 /* Do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable.
4637 if (strchr(name, '\n'))
4638 return -EINVAL;
4640 parent = cgroup_kn_lock_live(parent_kn);
4641 if (!parent)
4642 return -ENODEV;
4643 root = parent->root;
4645 /* allocate the cgroup and its ID, 0 is reserved for the root */
4646 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4647 if (!cgrp) {
4648 ret = -ENOMEM;
4649 goto out_unlock;
4652 ret = percpu_ref_init(&cgrp->self.refcnt, css_release, 0, GFP_KERNEL);
4653 if (ret)
4654 goto out_free_cgrp;
4657 * Temporarily set the pointer to NULL, so idr_find() won't return
4658 * a half-baked cgroup.
4660 cgrp->id = cgroup_idr_alloc(&root->cgroup_idr, NULL, 2, 0, GFP_NOWAIT);
4661 if (cgrp->id < 0) {
4662 ret = -ENOMEM;
4663 goto out_cancel_ref;
4666 init_cgroup_housekeeping(cgrp);
4668 cgrp->self.parent = &parent->self;
4669 cgrp->root = root;
4671 if (notify_on_release(parent))
4672 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4674 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4675 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4677 /* create the directory */
4678 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
4679 if (IS_ERR(kn)) {
4680 ret = PTR_ERR(kn);
4681 goto out_free_id;
4683 cgrp->kn = kn;
4686 * This extra ref will be put in cgroup_free_fn() and guarantees
4687 * that @cgrp->kn is always accessible.
4689 kernfs_get(kn);
4691 cgrp->self.serial_nr = css_serial_nr_next++;
4693 /* allocation complete, commit to creation */
4694 list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
4695 atomic_inc(&root->nr_cgrps);
4696 cgroup_get(parent);
4699 * @cgrp is now fully operational. If something fails after this
4700 * point, it'll be released via the normal destruction path.
4702 cgroup_idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4704 ret = cgroup_kn_set_ugid(kn);
4705 if (ret)
4706 goto out_destroy;
4708 if (cgroup_on_dfl(cgrp))
4709 base_files = cgroup_dfl_base_files;
4710 else
4711 base_files = cgroup_legacy_base_files;
4713 ret = cgroup_addrm_files(cgrp, base_files, true);
4714 if (ret)
4715 goto out_destroy;
4717 /* let's create and online css's */
4718 for_each_subsys(ss, ssid) {
4719 if (parent->child_subsys_mask & (1 << ssid)) {
4720 ret = create_css(cgrp, ss,
4721 parent->subtree_control & (1 << ssid));
4722 if (ret)
4723 goto out_destroy;
4728 * On the default hierarchy, a child doesn't automatically inherit
4729 * subtree_control from the parent. Each is configured manually.
4731 if (!cgroup_on_dfl(cgrp)) {
4732 cgrp->subtree_control = parent->subtree_control;
4733 cgroup_refresh_child_subsys_mask(cgrp);
4736 kernfs_activate(kn);
4738 ret = 0;
4739 goto out_unlock;
4741 out_free_id:
4742 cgroup_idr_remove(&root->cgroup_idr, cgrp->id);
4743 out_cancel_ref:
4744 percpu_ref_exit(&cgrp->self.refcnt);
4745 out_free_cgrp:
4746 kfree(cgrp);
4747 out_unlock:
4748 cgroup_kn_unlock(parent_kn);
4749 return ret;
4751 out_destroy:
4752 cgroup_destroy_locked(cgrp);
4753 goto out_unlock;
4757 * This is called when the refcnt of a css is confirmed to be killed.
4758 * css_tryget_online() is now guaranteed to fail. Tell the subsystem to
4759 * initate destruction and put the css ref from kill_css().
4761 static void css_killed_work_fn(struct work_struct *work)
4763 struct cgroup_subsys_state *css =
4764 container_of(work, struct cgroup_subsys_state, destroy_work);
4766 mutex_lock(&cgroup_mutex);
4767 offline_css(css);
4768 mutex_unlock(&cgroup_mutex);
4770 css_put(css);
4773 /* css kill confirmation processing requires process context, bounce */
4774 static void css_killed_ref_fn(struct percpu_ref *ref)
4776 struct cgroup_subsys_state *css =
4777 container_of(ref, struct cgroup_subsys_state, refcnt);
4779 INIT_WORK(&css->destroy_work, css_killed_work_fn);
4780 queue_work(cgroup_destroy_wq, &css->destroy_work);
4784 * kill_css - destroy a css
4785 * @css: css to destroy
4787 * This function initiates destruction of @css by removing cgroup interface
4788 * files and putting its base reference. ->css_offline() will be invoked
4789 * asynchronously once css_tryget_online() is guaranteed to fail and when
4790 * the reference count reaches zero, @css will be released.
4792 static void kill_css(struct cgroup_subsys_state *css)
4794 lockdep_assert_held(&cgroup_mutex);
4797 * This must happen before css is disassociated with its cgroup.
4798 * See seq_css() for details.
4800 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4803 * Killing would put the base ref, but we need to keep it alive
4804 * until after ->css_offline().
4806 css_get(css);
4809 * cgroup core guarantees that, by the time ->css_offline() is
4810 * invoked, no new css reference will be given out via
4811 * css_tryget_online(). We can't simply call percpu_ref_kill() and
4812 * proceed to offlining css's because percpu_ref_kill() doesn't
4813 * guarantee that the ref is seen as killed on all CPUs on return.
4815 * Use percpu_ref_kill_and_confirm() to get notifications as each
4816 * css is confirmed to be seen as killed on all CPUs.
4818 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4822 * cgroup_destroy_locked - the first stage of cgroup destruction
4823 * @cgrp: cgroup to be destroyed
4825 * css's make use of percpu refcnts whose killing latency shouldn't be
4826 * exposed to userland and are RCU protected. Also, cgroup core needs to
4827 * guarantee that css_tryget_online() won't succeed by the time
4828 * ->css_offline() is invoked. To satisfy all the requirements,
4829 * destruction is implemented in the following two steps.
4831 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4832 * userland visible parts and start killing the percpu refcnts of
4833 * css's. Set up so that the next stage will be kicked off once all
4834 * the percpu refcnts are confirmed to be killed.
4836 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4837 * rest of destruction. Once all cgroup references are gone, the
4838 * cgroup is RCU-freed.
4840 * This function implements s1. After this step, @cgrp is gone as far as
4841 * the userland is concerned and a new cgroup with the same name may be
4842 * created. As cgroup doesn't care about the names internally, this
4843 * doesn't cause any problem.
4845 static int cgroup_destroy_locked(struct cgroup *cgrp)
4846 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4848 struct cgroup_subsys_state *css;
4849 bool empty;
4850 int ssid;
4852 lockdep_assert_held(&cgroup_mutex);
4855 * css_set_rwsem synchronizes access to ->cset_links and prevents
4856 * @cgrp from being removed while put_css_set() is in progress.
4858 down_read(&css_set_rwsem);
4859 empty = list_empty(&cgrp->cset_links);
4860 up_read(&css_set_rwsem);
4861 if (!empty)
4862 return -EBUSY;
4865 * Make sure there's no live children. We can't test emptiness of
4866 * ->self.children as dead children linger on it while being
4867 * drained; otherwise, "rmdir parent/child parent" may fail.
4869 if (css_has_online_children(&cgrp->self))
4870 return -EBUSY;
4873 * Mark @cgrp dead. This prevents further task migration and child
4874 * creation by disabling cgroup_lock_live_group().
4876 cgrp->self.flags &= ~CSS_ONLINE;
4878 /* initiate massacre of all css's */
4879 for_each_css(css, ssid, cgrp)
4880 kill_css(css);
4883 * Remove @cgrp directory along with the base files. @cgrp has an
4884 * extra ref on its kn.
4886 kernfs_remove(cgrp->kn);
4888 check_for_release(cgroup_parent(cgrp));
4890 /* put the base reference */
4891 percpu_ref_kill(&cgrp->self.refcnt);
4893 return 0;
4896 static int cgroup_rmdir(struct kernfs_node *kn)
4898 struct cgroup *cgrp;
4899 int ret = 0;
4901 cgrp = cgroup_kn_lock_live(kn);
4902 if (!cgrp)
4903 return 0;
4905 ret = cgroup_destroy_locked(cgrp);
4907 cgroup_kn_unlock(kn);
4908 return ret;
4911 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
4912 .remount_fs = cgroup_remount,
4913 .show_options = cgroup_show_options,
4914 .mkdir = cgroup_mkdir,
4915 .rmdir = cgroup_rmdir,
4916 .rename = cgroup_rename,
4919 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
4921 struct cgroup_subsys_state *css;
4923 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4925 mutex_lock(&cgroup_mutex);
4927 idr_init(&ss->css_idr);
4928 INIT_LIST_HEAD(&ss->cfts);
4930 /* Create the root cgroup state for this subsystem */
4931 ss->root = &cgrp_dfl_root;
4932 css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
4933 /* We don't handle early failures gracefully */
4934 BUG_ON(IS_ERR(css));
4935 init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
4938 * Root csses are never destroyed and we can't initialize
4939 * percpu_ref during early init. Disable refcnting.
4941 css->flags |= CSS_NO_REF;
4943 if (early) {
4944 /* allocation can't be done safely during early init */
4945 css->id = 1;
4946 } else {
4947 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
4948 BUG_ON(css->id < 0);
4951 /* Update the init_css_set to contain a subsys
4952 * pointer to this state - since the subsystem is
4953 * newly registered, all tasks and hence the
4954 * init_css_set is in the subsystem's root cgroup. */
4955 init_css_set.subsys[ss->id] = css;
4957 have_fork_callback |= (bool)ss->fork << ss->id;
4958 have_exit_callback |= (bool)ss->exit << ss->id;
4960 /* At system boot, before all subsystems have been
4961 * registered, no tasks have been forked, so we don't
4962 * need to invoke fork callbacks here. */
4963 BUG_ON(!list_empty(&init_task.tasks));
4965 BUG_ON(online_css(css));
4967 mutex_unlock(&cgroup_mutex);
4971 * cgroup_init_early - cgroup initialization at system boot
4973 * Initialize cgroups at system boot, and initialize any
4974 * subsystems that request early init.
4976 int __init cgroup_init_early(void)
4978 static struct cgroup_sb_opts __initdata opts;
4979 struct cgroup_subsys *ss;
4980 int i;
4982 init_cgroup_root(&cgrp_dfl_root, &opts);
4983 cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
4985 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4987 for_each_subsys(ss, i) {
4988 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
4989 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
4990 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
4991 ss->id, ss->name);
4992 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
4993 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
4995 ss->id = i;
4996 ss->name = cgroup_subsys_name[i];
4998 if (ss->early_init)
4999 cgroup_init_subsys(ss, true);
5001 return 0;
5005 * cgroup_init - cgroup initialization
5007 * Register cgroup filesystem and /proc file, and initialize
5008 * any subsystems that didn't request early init.
5010 int __init cgroup_init(void)
5012 struct cgroup_subsys *ss;
5013 unsigned long key;
5014 int ssid, err;
5016 BUG_ON(percpu_init_rwsem(&cgroup_threadgroup_rwsem));
5017 BUG_ON(cgroup_init_cftypes(NULL, cgroup_dfl_base_files));
5018 BUG_ON(cgroup_init_cftypes(NULL, cgroup_legacy_base_files));
5020 mutex_lock(&cgroup_mutex);
5022 /* Add init_css_set to the hash table */
5023 key = css_set_hash(init_css_set.subsys);
5024 hash_add(css_set_table, &init_css_set.hlist, key);
5026 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
5028 mutex_unlock(&cgroup_mutex);
5030 for_each_subsys(ss, ssid) {
5031 if (ss->early_init) {
5032 struct cgroup_subsys_state *css =
5033 init_css_set.subsys[ss->id];
5035 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
5036 GFP_KERNEL);
5037 BUG_ON(css->id < 0);
5038 } else {
5039 cgroup_init_subsys(ss, false);
5042 list_add_tail(&init_css_set.e_cset_node[ssid],
5043 &cgrp_dfl_root.cgrp.e_csets[ssid]);
5046 * Setting dfl_root subsys_mask needs to consider the
5047 * disabled flag and cftype registration needs kmalloc,
5048 * both of which aren't available during early_init.
5050 if (ss->disabled)
5051 continue;
5053 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
5055 if (cgroup_legacy_files_on_dfl && !ss->dfl_cftypes)
5056 ss->dfl_cftypes = ss->legacy_cftypes;
5058 if (!ss->dfl_cftypes)
5059 cgrp_dfl_root_inhibit_ss_mask |= 1 << ss->id;
5061 if (ss->dfl_cftypes == ss->legacy_cftypes) {
5062 WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes));
5063 } else {
5064 WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes));
5065 WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes));
5068 if (ss->bind)
5069 ss->bind(init_css_set.subsys[ssid]);
5072 err = sysfs_create_mount_point(fs_kobj, "cgroup");
5073 if (err)
5074 return err;
5076 err = register_filesystem(&cgroup_fs_type);
5077 if (err < 0) {
5078 sysfs_remove_mount_point(fs_kobj, "cgroup");
5079 return err;
5082 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
5083 return 0;
5086 static int __init cgroup_wq_init(void)
5089 * There isn't much point in executing destruction path in
5090 * parallel. Good chunk is serialized with cgroup_mutex anyway.
5091 * Use 1 for @max_active.
5093 * We would prefer to do this in cgroup_init() above, but that
5094 * is called before init_workqueues(): so leave this until after.
5096 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
5097 BUG_ON(!cgroup_destroy_wq);
5100 * Used to destroy pidlists and separate to serve as flush domain.
5101 * Cap @max_active to 1 too.
5103 cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
5104 0, 1);
5105 BUG_ON(!cgroup_pidlist_destroy_wq);
5107 return 0;
5109 core_initcall(cgroup_wq_init);
5112 * proc_cgroup_show()
5113 * - Print task's cgroup paths into seq_file, one line for each hierarchy
5114 * - Used for /proc/<pid>/cgroup.
5116 int proc_cgroup_show(struct seq_file *m, struct pid_namespace *ns,
5117 struct pid *pid, struct task_struct *tsk)
5119 char *buf, *path;
5120 int retval;
5121 struct cgroup_root *root;
5123 retval = -ENOMEM;
5124 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5125 if (!buf)
5126 goto out;
5128 mutex_lock(&cgroup_mutex);
5129 down_read(&css_set_rwsem);
5131 for_each_root(root) {
5132 struct cgroup_subsys *ss;
5133 struct cgroup *cgrp;
5134 int ssid, count = 0;
5136 if (root == &cgrp_dfl_root && !cgrp_dfl_root_visible)
5137 continue;
5139 seq_printf(m, "%d:", root->hierarchy_id);
5140 for_each_subsys(ss, ssid)
5141 if (root->subsys_mask & (1 << ssid))
5142 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
5143 if (strlen(root->name))
5144 seq_printf(m, "%sname=%s", count ? "," : "",
5145 root->name);
5146 seq_putc(m, ':');
5147 cgrp = task_cgroup_from_root(tsk, root);
5148 path = cgroup_path(cgrp, buf, PATH_MAX);
5149 if (!path) {
5150 retval = -ENAMETOOLONG;
5151 goto out_unlock;
5153 seq_puts(m, path);
5154 seq_putc(m, '\n');
5157 retval = 0;
5158 out_unlock:
5159 up_read(&css_set_rwsem);
5160 mutex_unlock(&cgroup_mutex);
5161 kfree(buf);
5162 out:
5163 return retval;
5166 /* Display information about each subsystem and each hierarchy */
5167 static int proc_cgroupstats_show(struct seq_file *m, void *v)
5169 struct cgroup_subsys *ss;
5170 int i;
5172 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
5174 * ideally we don't want subsystems moving around while we do this.
5175 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
5176 * subsys/hierarchy state.
5178 mutex_lock(&cgroup_mutex);
5180 for_each_subsys(ss, i)
5181 seq_printf(m, "%s\t%d\t%d\t%d\n",
5182 ss->name, ss->root->hierarchy_id,
5183 atomic_read(&ss->root->nr_cgrps), !ss->disabled);
5185 mutex_unlock(&cgroup_mutex);
5186 return 0;
5189 static int cgroupstats_open(struct inode *inode, struct file *file)
5191 return single_open(file, proc_cgroupstats_show, NULL);
5194 static const struct file_operations proc_cgroupstats_operations = {
5195 .open = cgroupstats_open,
5196 .read = seq_read,
5197 .llseek = seq_lseek,
5198 .release = single_release,
5202 * cgroup_fork - initialize cgroup related fields during copy_process()
5203 * @child: pointer to task_struct of forking parent process.
5205 * A task is associated with the init_css_set until cgroup_post_fork()
5206 * attaches it to the parent's css_set. Empty cg_list indicates that
5207 * @child isn't holding reference to its css_set.
5209 void cgroup_fork(struct task_struct *child)
5211 RCU_INIT_POINTER(child->cgroups, &init_css_set);
5212 INIT_LIST_HEAD(&child->cg_list);
5216 * cgroup_post_fork - called on a new task after adding it to the task list
5217 * @child: the task in question
5219 * Adds the task to the list running through its css_set if necessary and
5220 * call the subsystem fork() callbacks. Has to be after the task is
5221 * visible on the task list in case we race with the first call to
5222 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
5223 * list.
5225 void cgroup_post_fork(struct task_struct *child)
5227 struct cgroup_subsys *ss;
5228 int i;
5231 * This may race against cgroup_enable_task_cg_lists(). As that
5232 * function sets use_task_css_set_links before grabbing
5233 * tasklist_lock and we just went through tasklist_lock to add
5234 * @child, it's guaranteed that either we see the set
5235 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
5236 * @child during its iteration.
5238 * If we won the race, @child is associated with %current's
5239 * css_set. Grabbing css_set_rwsem guarantees both that the
5240 * association is stable, and, on completion of the parent's
5241 * migration, @child is visible in the source of migration or
5242 * already in the destination cgroup. This guarantee is necessary
5243 * when implementing operations which need to migrate all tasks of
5244 * a cgroup to another.
5246 * Note that if we lose to cgroup_enable_task_cg_lists(), @child
5247 * will remain in init_css_set. This is safe because all tasks are
5248 * in the init_css_set before cg_links is enabled and there's no
5249 * operation which transfers all tasks out of init_css_set.
5251 if (use_task_css_set_links) {
5252 struct css_set *cset;
5254 down_write(&css_set_rwsem);
5255 cset = task_css_set(current);
5256 if (list_empty(&child->cg_list)) {
5257 rcu_assign_pointer(child->cgroups, cset);
5258 list_add(&child->cg_list, &cset->tasks);
5259 get_css_set(cset);
5261 up_write(&css_set_rwsem);
5265 * Call ss->fork(). This must happen after @child is linked on
5266 * css_set; otherwise, @child might change state between ->fork()
5267 * and addition to css_set.
5269 for_each_subsys_which(ss, i, &have_fork_callback)
5270 ss->fork(child);
5274 * cgroup_exit - detach cgroup from exiting task
5275 * @tsk: pointer to task_struct of exiting process
5277 * Description: Detach cgroup from @tsk and release it.
5279 * Note that cgroups marked notify_on_release force every task in
5280 * them to take the global cgroup_mutex mutex when exiting.
5281 * This could impact scaling on very large systems. Be reluctant to
5282 * use notify_on_release cgroups where very high task exit scaling
5283 * is required on large systems.
5285 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
5286 * call cgroup_exit() while the task is still competent to handle
5287 * notify_on_release(), then leave the task attached to the root cgroup in
5288 * each hierarchy for the remainder of its exit. No need to bother with
5289 * init_css_set refcnting. init_css_set never goes away and we can't race
5290 * with migration path - PF_EXITING is visible to migration path.
5292 void cgroup_exit(struct task_struct *tsk)
5294 struct cgroup_subsys *ss;
5295 struct css_set *cset;
5296 bool put_cset = false;
5297 int i;
5300 * Unlink from @tsk from its css_set. As migration path can't race
5301 * with us, we can check cg_list without grabbing css_set_rwsem.
5303 if (!list_empty(&tsk->cg_list)) {
5304 down_write(&css_set_rwsem);
5305 list_del_init(&tsk->cg_list);
5306 up_write(&css_set_rwsem);
5307 put_cset = true;
5310 /* Reassign the task to the init_css_set. */
5311 cset = task_css_set(tsk);
5312 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
5314 /* see cgroup_post_fork() for details */
5315 for_each_subsys_which(ss, i, &have_exit_callback) {
5316 struct cgroup_subsys_state *old_css = cset->subsys[i];
5317 struct cgroup_subsys_state *css = task_css(tsk, i);
5319 ss->exit(css, old_css, tsk);
5322 if (put_cset)
5323 put_css_set(cset);
5326 static void check_for_release(struct cgroup *cgrp)
5328 if (notify_on_release(cgrp) && !cgroup_has_tasks(cgrp) &&
5329 !css_has_online_children(&cgrp->self) && !cgroup_is_dead(cgrp))
5330 schedule_work(&cgrp->release_agent_work);
5334 * Notify userspace when a cgroup is released, by running the
5335 * configured release agent with the name of the cgroup (path
5336 * relative to the root of cgroup file system) as the argument.
5338 * Most likely, this user command will try to rmdir this cgroup.
5340 * This races with the possibility that some other task will be
5341 * attached to this cgroup before it is removed, or that some other
5342 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5343 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5344 * unused, and this cgroup will be reprieved from its death sentence,
5345 * to continue to serve a useful existence. Next time it's released,
5346 * we will get notified again, if it still has 'notify_on_release' set.
5348 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5349 * means only wait until the task is successfully execve()'d. The
5350 * separate release agent task is forked by call_usermodehelper(),
5351 * then control in this thread returns here, without waiting for the
5352 * release agent task. We don't bother to wait because the caller of
5353 * this routine has no use for the exit status of the release agent
5354 * task, so no sense holding our caller up for that.
5356 static void cgroup_release_agent(struct work_struct *work)
5358 struct cgroup *cgrp =
5359 container_of(work, struct cgroup, release_agent_work);
5360 char *pathbuf = NULL, *agentbuf = NULL, *path;
5361 char *argv[3], *envp[3];
5363 mutex_lock(&cgroup_mutex);
5365 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
5366 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5367 if (!pathbuf || !agentbuf)
5368 goto out;
5370 path = cgroup_path(cgrp, pathbuf, PATH_MAX);
5371 if (!path)
5372 goto out;
5374 argv[0] = agentbuf;
5375 argv[1] = path;
5376 argv[2] = NULL;
5378 /* minimal command environment */
5379 envp[0] = "HOME=/";
5380 envp[1] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5381 envp[2] = NULL;
5383 mutex_unlock(&cgroup_mutex);
5384 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5385 goto out_free;
5386 out:
5387 mutex_unlock(&cgroup_mutex);
5388 out_free:
5389 kfree(agentbuf);
5390 kfree(pathbuf);
5393 static int __init cgroup_disable(char *str)
5395 struct cgroup_subsys *ss;
5396 char *token;
5397 int i;
5399 while ((token = strsep(&str, ",")) != NULL) {
5400 if (!*token)
5401 continue;
5403 for_each_subsys(ss, i) {
5404 if (!strcmp(token, ss->name)) {
5405 ss->disabled = 1;
5406 printk(KERN_INFO "Disabling %s control group"
5407 " subsystem\n", ss->name);
5408 break;
5412 return 1;
5414 __setup("cgroup_disable=", cgroup_disable);
5416 static int __init cgroup_set_legacy_files_on_dfl(char *str)
5418 printk("cgroup: using legacy files on the default hierarchy\n");
5419 cgroup_legacy_files_on_dfl = true;
5420 return 0;
5422 __setup("cgroup__DEVEL__legacy_files_on_dfl", cgroup_set_legacy_files_on_dfl);
5425 * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
5426 * @dentry: directory dentry of interest
5427 * @ss: subsystem of interest
5429 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
5430 * to get the corresponding css and return it. If such css doesn't exist
5431 * or can't be pinned, an ERR_PTR value is returned.
5433 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
5434 struct cgroup_subsys *ss)
5436 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
5437 struct cgroup_subsys_state *css = NULL;
5438 struct cgroup *cgrp;
5440 /* is @dentry a cgroup dir? */
5441 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
5442 kernfs_type(kn) != KERNFS_DIR)
5443 return ERR_PTR(-EBADF);
5445 rcu_read_lock();
5448 * This path doesn't originate from kernfs and @kn could already
5449 * have been or be removed at any point. @kn->priv is RCU
5450 * protected for this access. See css_release_work_fn() for details.
5452 cgrp = rcu_dereference(kn->priv);
5453 if (cgrp)
5454 css = cgroup_css(cgrp, ss);
5456 if (!css || !css_tryget_online(css))
5457 css = ERR_PTR(-ENOENT);
5459 rcu_read_unlock();
5460 return css;
5464 * css_from_id - lookup css by id
5465 * @id: the cgroup id
5466 * @ss: cgroup subsys to be looked into
5468 * Returns the css if there's valid one with @id, otherwise returns NULL.
5469 * Should be called under rcu_read_lock().
5471 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5473 WARN_ON_ONCE(!rcu_read_lock_held());
5474 return id > 0 ? idr_find(&ss->css_idr, id) : NULL;
5477 #ifdef CONFIG_CGROUP_DEBUG
5478 static struct cgroup_subsys_state *
5479 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5481 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5483 if (!css)
5484 return ERR_PTR(-ENOMEM);
5486 return css;
5489 static void debug_css_free(struct cgroup_subsys_state *css)
5491 kfree(css);
5494 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5495 struct cftype *cft)
5497 return cgroup_task_count(css->cgroup);
5500 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5501 struct cftype *cft)
5503 return (u64)(unsigned long)current->cgroups;
5506 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5507 struct cftype *cft)
5509 u64 count;
5511 rcu_read_lock();
5512 count = atomic_read(&task_css_set(current)->refcount);
5513 rcu_read_unlock();
5514 return count;
5517 static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
5519 struct cgrp_cset_link *link;
5520 struct css_set *cset;
5521 char *name_buf;
5523 name_buf = kmalloc(NAME_MAX + 1, GFP_KERNEL);
5524 if (!name_buf)
5525 return -ENOMEM;
5527 down_read(&css_set_rwsem);
5528 rcu_read_lock();
5529 cset = rcu_dereference(current->cgroups);
5530 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5531 struct cgroup *c = link->cgrp;
5533 cgroup_name(c, name_buf, NAME_MAX + 1);
5534 seq_printf(seq, "Root %d group %s\n",
5535 c->root->hierarchy_id, name_buf);
5537 rcu_read_unlock();
5538 up_read(&css_set_rwsem);
5539 kfree(name_buf);
5540 return 0;
5543 #define MAX_TASKS_SHOWN_PER_CSS 25
5544 static int cgroup_css_links_read(struct seq_file *seq, void *v)
5546 struct cgroup_subsys_state *css = seq_css(seq);
5547 struct cgrp_cset_link *link;
5549 down_read(&css_set_rwsem);
5550 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5551 struct css_set *cset = link->cset;
5552 struct task_struct *task;
5553 int count = 0;
5555 seq_printf(seq, "css_set %p\n", cset);
5557 list_for_each_entry(task, &cset->tasks, cg_list) {
5558 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5559 goto overflow;
5560 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5563 list_for_each_entry(task, &cset->mg_tasks, cg_list) {
5564 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5565 goto overflow;
5566 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5568 continue;
5569 overflow:
5570 seq_puts(seq, " ...\n");
5572 up_read(&css_set_rwsem);
5573 return 0;
5576 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5578 return (!cgroup_has_tasks(css->cgroup) &&
5579 !css_has_online_children(&css->cgroup->self));
5582 static struct cftype debug_files[] = {
5584 .name = "taskcount",
5585 .read_u64 = debug_taskcount_read,
5589 .name = "current_css_set",
5590 .read_u64 = current_css_set_read,
5594 .name = "current_css_set_refcount",
5595 .read_u64 = current_css_set_refcount_read,
5599 .name = "current_css_set_cg_links",
5600 .seq_show = current_css_set_cg_links_read,
5604 .name = "cgroup_css_links",
5605 .seq_show = cgroup_css_links_read,
5609 .name = "releasable",
5610 .read_u64 = releasable_read,
5613 { } /* terminate */
5616 struct cgroup_subsys debug_cgrp_subsys = {
5617 .css_alloc = debug_css_alloc,
5618 .css_free = debug_css_free,
5619 .legacy_cftypes = debug_files,
5621 #endif /* CONFIG_CGROUP_DEBUG */