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>
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/percpu-rwsem.h>
49 #include <linux/string.h>
50 #include <linux/sort.h>
51 #include <linux/kmod.h>
52 #include <linux/delayacct.h>
53 #include <linux/cgroupstats.h>
54 #include <linux/hashtable.h>
55 #include <linux/pid_namespace.h>
56 #include <linux/idr.h>
57 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
58 #include <linux/kthread.h>
59 #include <linux/delay.h>
61 #include <linux/atomic.h>
64 * pidlists linger the following amount before being destroyed. The goal
65 * is avoiding frequent destruction in the middle of consecutive read calls
66 * Expiring in the middle is a performance problem not a correctness one.
67 * 1 sec should be enough.
69 #define CGROUP_PIDLIST_DESTROY_DELAY HZ
71 #define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
75 * cgroup_mutex is the master lock. Any modification to cgroup or its
76 * hierarchy must be performed while holding it.
78 * css_set_lock protects task->cgroups pointer, the list of css_set
79 * objects, and the chain of tasks off each css_set.
81 * These locks are exported if CONFIG_PROVE_RCU so that accessors in
82 * cgroup.h can use them for lockdep annotations.
84 #ifdef CONFIG_PROVE_RCU
85 DEFINE_MUTEX(cgroup_mutex);
86 DEFINE_SPINLOCK(css_set_lock);
87 EXPORT_SYMBOL_GPL(cgroup_mutex);
88 EXPORT_SYMBOL_GPL(css_set_lock);
90 static DEFINE_MUTEX(cgroup_mutex);
91 static DEFINE_SPINLOCK(css_set_lock);
95 * Protects cgroup_idr and css_idr so that IDs can be released without
96 * grabbing cgroup_mutex.
98 static DEFINE_SPINLOCK(cgroup_idr_lock);
101 * Protects cgroup_file->kn for !self csses. It synchronizes notifications
102 * against file removal/re-creation across css hiding.
104 static DEFINE_SPINLOCK(cgroup_file_kn_lock);
107 * Protects cgroup_subsys->release_agent_path. Modifying it also requires
108 * cgroup_mutex. Reading requires either cgroup_mutex or this spinlock.
110 static DEFINE_SPINLOCK(release_agent_path_lock);
112 struct percpu_rw_semaphore cgroup_threadgroup_rwsem;
114 #define cgroup_assert_mutex_or_rcu_locked() \
115 RCU_LOCKDEP_WARN(!rcu_read_lock_held() && \
116 !lockdep_is_held(&cgroup_mutex), \
117 "cgroup_mutex or RCU read lock required");
120 * cgroup destruction makes heavy use of work items and there can be a lot
121 * of concurrent destructions. Use a separate workqueue so that cgroup
122 * destruction work items don't end up filling up max_active of system_wq
123 * which may lead to deadlock.
125 static struct workqueue_struct *cgroup_destroy_wq;
128 * pidlist destructions need to be flushed on cgroup destruction. Use a
129 * separate workqueue as flush domain.
131 static struct workqueue_struct *cgroup_pidlist_destroy_wq;
133 /* generate an array of cgroup subsystem pointers */
134 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
135 static struct cgroup_subsys *cgroup_subsys[] = {
136 #include <linux/cgroup_subsys.h>
140 /* array of cgroup subsystem names */
141 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
142 static const char *cgroup_subsys_name[] = {
143 #include <linux/cgroup_subsys.h>
147 /* array of static_keys for cgroup_subsys_enabled() and cgroup_subsys_on_dfl() */
149 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_enabled_key); \
150 DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_on_dfl_key); \
151 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_enabled_key); \
152 EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_on_dfl_key);
153 #include <linux/cgroup_subsys.h>
156 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_enabled_key,
157 static struct static_key_true *cgroup_subsys_enabled_key[] = {
158 #include <linux/cgroup_subsys.h>
162 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_on_dfl_key,
163 static struct static_key_true *cgroup_subsys_on_dfl_key[] = {
164 #include <linux/cgroup_subsys.h>
169 * The default hierarchy, reserved for the subsystems that are otherwise
170 * unattached - it never has more than a single cgroup, and all tasks are
171 * part of that cgroup.
173 struct cgroup_root cgrp_dfl_root;
174 EXPORT_SYMBOL_GPL(cgrp_dfl_root);
177 * The default hierarchy always exists but is hidden until mounted for the
178 * first time. This is for backward compatibility.
180 static bool cgrp_dfl_root_visible;
182 /* some controllers are not supported in the default hierarchy */
183 static unsigned long cgrp_dfl_root_inhibit_ss_mask;
185 /* The list of hierarchy roots */
187 static LIST_HEAD(cgroup_roots);
188 static int cgroup_root_count;
190 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
191 static DEFINE_IDR(cgroup_hierarchy_idr);
194 * Assign a monotonically increasing serial number to csses. It guarantees
195 * cgroups with bigger numbers are newer than those with smaller numbers.
196 * Also, as csses are always appended to the parent's ->children list, it
197 * guarantees that sibling csses are always sorted in the ascending serial
198 * number order on the list. Protected by cgroup_mutex.
200 static u64 css_serial_nr_next = 1;
203 * These bitmask flags indicate whether tasks in the fork and exit paths have
204 * fork/exit handlers to call. This avoids us having to do extra work in the
205 * fork/exit path to check which subsystems have fork/exit callbacks.
207 static unsigned long have_fork_callback __read_mostly;
208 static unsigned long have_exit_callback __read_mostly;
209 static unsigned long have_free_callback __read_mostly;
211 /* Ditto for the can_fork callback. */
212 static unsigned long have_canfork_callback __read_mostly;
214 static struct file_system_type cgroup2_fs_type;
215 static struct cftype cgroup_dfl_base_files[];
216 static struct cftype cgroup_legacy_base_files[];
218 static int rebind_subsystems(struct cgroup_root *dst_root,
219 unsigned long ss_mask);
220 static void css_task_iter_advance(struct css_task_iter *it);
221 static int cgroup_destroy_locked(struct cgroup *cgrp);
222 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss,
224 static void css_release(struct percpu_ref *ref);
225 static void kill_css(struct cgroup_subsys_state *css);
226 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
227 struct cgroup *cgrp, struct cftype cfts[],
231 * cgroup_ssid_enabled - cgroup subsys enabled test by subsys ID
232 * @ssid: subsys ID of interest
234 * cgroup_subsys_enabled() can only be used with literal subsys names which
235 * is fine for individual subsystems but unsuitable for cgroup core. This
236 * is slower static_key_enabled() based test indexed by @ssid.
238 static bool cgroup_ssid_enabled(int ssid)
240 return static_key_enabled(cgroup_subsys_enabled_key[ssid]);
244 * cgroup_on_dfl - test whether a cgroup is on the default hierarchy
245 * @cgrp: the cgroup of interest
247 * The default hierarchy is the v2 interface of cgroup and this function
248 * can be used to test whether a cgroup is on the default hierarchy for
249 * cases where a subsystem should behave differnetly depending on the
252 * The set of behaviors which change on the default hierarchy are still
253 * being determined and the mount option is prefixed with __DEVEL__.
255 * List of changed behaviors:
257 * - Mount options "noprefix", "xattr", "clone_children", "release_agent"
258 * and "name" are disallowed.
260 * - When mounting an existing superblock, mount options should match.
262 * - Remount is disallowed.
264 * - rename(2) is disallowed.
266 * - "tasks" is removed. Everything should be at process granularity. Use
267 * "cgroup.procs" instead.
269 * - "cgroup.procs" is not sorted. pids will be unique unless they got
270 * recycled inbetween reads.
272 * - "release_agent" and "notify_on_release" are removed. Replacement
273 * notification mechanism will be implemented.
275 * - "cgroup.clone_children" is removed.
277 * - "cgroup.subtree_populated" is available. Its value is 0 if the cgroup
278 * and its descendants contain no task; otherwise, 1. The file also
279 * generates kernfs notification which can be monitored through poll and
280 * [di]notify when the value of the file changes.
282 * - cpuset: tasks will be kept in empty cpusets when hotplug happens and
283 * take masks of ancestors with non-empty cpus/mems, instead of being
284 * moved to an ancestor.
286 * - cpuset: a task can be moved into an empty cpuset, and again it takes
287 * masks of ancestors.
289 * - memcg: use_hierarchy is on by default and the cgroup file for the flag
292 * - blkcg: blk-throttle becomes properly hierarchical.
294 * - debug: disallowed on the default hierarchy.
296 static bool cgroup_on_dfl(const struct cgroup *cgrp)
298 return cgrp->root == &cgrp_dfl_root;
301 /* IDR wrappers which synchronize using cgroup_idr_lock */
302 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
307 idr_preload(gfp_mask);
308 spin_lock_bh(&cgroup_idr_lock);
309 ret = idr_alloc(idr, ptr, start, end, gfp_mask & ~__GFP_DIRECT_RECLAIM);
310 spin_unlock_bh(&cgroup_idr_lock);
315 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
319 spin_lock_bh(&cgroup_idr_lock);
320 ret = idr_replace(idr, ptr, id);
321 spin_unlock_bh(&cgroup_idr_lock);
325 static void cgroup_idr_remove(struct idr *idr, int id)
327 spin_lock_bh(&cgroup_idr_lock);
329 spin_unlock_bh(&cgroup_idr_lock);
332 static struct cgroup *cgroup_parent(struct cgroup *cgrp)
334 struct cgroup_subsys_state *parent_css = cgrp->self.parent;
337 return container_of(parent_css, struct cgroup, self);
342 * cgroup_css - obtain a cgroup's css for the specified subsystem
343 * @cgrp: the cgroup of interest
344 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
346 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
347 * function must be called either under cgroup_mutex or rcu_read_lock() and
348 * the caller is responsible for pinning the returned css if it wants to
349 * keep accessing it outside the said locks. This function may return
350 * %NULL if @cgrp doesn't have @subsys_id enabled.
352 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
353 struct cgroup_subsys *ss)
356 return rcu_dereference_check(cgrp->subsys[ss->id],
357 lockdep_is_held(&cgroup_mutex));
363 * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
364 * @cgrp: the cgroup of interest
365 * @ss: the subsystem of interest (%NULL returns @cgrp->self)
367 * Similar to cgroup_css() but returns the effective css, which is defined
368 * as the matching css of the nearest ancestor including self which has @ss
369 * enabled. If @ss is associated with the hierarchy @cgrp is on, this
370 * function is guaranteed to return non-NULL css.
372 static struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
373 struct cgroup_subsys *ss)
375 lockdep_assert_held(&cgroup_mutex);
380 if (!(cgrp->root->subsys_mask & (1 << ss->id)))
384 * This function is used while updating css associations and thus
385 * can't test the csses directly. Use ->child_subsys_mask.
387 while (cgroup_parent(cgrp) &&
388 !(cgroup_parent(cgrp)->child_subsys_mask & (1 << ss->id)))
389 cgrp = cgroup_parent(cgrp);
391 return cgroup_css(cgrp, ss);
395 * cgroup_get_e_css - get a cgroup's effective css for the specified subsystem
396 * @cgrp: the cgroup of interest
397 * @ss: the subsystem of interest
399 * Find and get the effective css of @cgrp for @ss. The effective css is
400 * defined as the matching css of the nearest ancestor including self which
401 * has @ss enabled. If @ss is not mounted on the hierarchy @cgrp is on,
402 * the root css is returned, so this function always returns a valid css.
403 * The returned css must be put using css_put().
405 struct cgroup_subsys_state *cgroup_get_e_css(struct cgroup *cgrp,
406 struct cgroup_subsys *ss)
408 struct cgroup_subsys_state *css;
413 css = cgroup_css(cgrp, ss);
415 if (css && css_tryget_online(css))
417 cgrp = cgroup_parent(cgrp);
420 css = init_css_set.subsys[ss->id];
427 /* convenient tests for these bits */
428 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
430 return !(cgrp->self.flags & CSS_ONLINE);
433 static void cgroup_get(struct cgroup *cgrp)
435 WARN_ON_ONCE(cgroup_is_dead(cgrp));
436 css_get(&cgrp->self);
439 static bool cgroup_tryget(struct cgroup *cgrp)
441 return css_tryget(&cgrp->self);
444 static void cgroup_put(struct cgroup *cgrp)
446 css_put(&cgrp->self);
449 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
451 struct cgroup *cgrp = of->kn->parent->priv;
452 struct cftype *cft = of_cft(of);
455 * This is open and unprotected implementation of cgroup_css().
456 * seq_css() is only called from a kernfs file operation which has
457 * an active reference on the file. Because all the subsystem
458 * files are drained before a css is disassociated with a cgroup,
459 * the matching css from the cgroup's subsys table is guaranteed to
460 * be and stay valid until the enclosing operation is complete.
463 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
467 EXPORT_SYMBOL_GPL(of_css);
470 * cgroup_is_descendant - test ancestry
471 * @cgrp: the cgroup to be tested
472 * @ancestor: possible ancestor of @cgrp
474 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
475 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
476 * and @ancestor are accessible.
478 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
481 if (cgrp == ancestor)
483 cgrp = cgroup_parent(cgrp);
488 static int notify_on_release(const struct cgroup *cgrp)
490 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
494 * for_each_css - iterate all css's of a cgroup
495 * @css: the iteration cursor
496 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
497 * @cgrp: the target cgroup to iterate css's of
499 * Should be called under cgroup_[tree_]mutex.
501 #define for_each_css(css, ssid, cgrp) \
502 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
503 if (!((css) = rcu_dereference_check( \
504 (cgrp)->subsys[(ssid)], \
505 lockdep_is_held(&cgroup_mutex)))) { } \
509 * for_each_e_css - iterate all effective css's of a cgroup
510 * @css: the iteration cursor
511 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
512 * @cgrp: the target cgroup to iterate css's of
514 * Should be called under cgroup_[tree_]mutex.
516 #define for_each_e_css(css, ssid, cgrp) \
517 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
518 if (!((css) = cgroup_e_css(cgrp, cgroup_subsys[(ssid)]))) \
523 * for_each_subsys - iterate all enabled cgroup subsystems
524 * @ss: the iteration cursor
525 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
527 #define for_each_subsys(ss, ssid) \
528 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT && \
529 (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
532 * for_each_subsys_which - filter for_each_subsys with a bitmask
533 * @ss: the iteration cursor
534 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
535 * @ss_maskp: a pointer to the bitmask
537 * The block will only run for cases where the ssid-th bit (1 << ssid) of
540 #define for_each_subsys_which(ss, ssid, ss_maskp) \
541 if (!CGROUP_SUBSYS_COUNT) /* to avoid spurious gcc warning */ \
544 for_each_set_bit(ssid, ss_maskp, CGROUP_SUBSYS_COUNT) \
545 if (((ss) = cgroup_subsys[ssid]) && false) \
549 /* iterate across the hierarchies */
550 #define for_each_root(root) \
551 list_for_each_entry((root), &cgroup_roots, root_list)
553 /* iterate over child cgrps, lock should be held throughout iteration */
554 #define cgroup_for_each_live_child(child, cgrp) \
555 list_for_each_entry((child), &(cgrp)->self.children, self.sibling) \
556 if (({ lockdep_assert_held(&cgroup_mutex); \
557 cgroup_is_dead(child); })) \
561 static void cgroup_release_agent(struct work_struct *work);
562 static void check_for_release(struct cgroup *cgrp);
565 * A cgroup can be associated with multiple css_sets as different tasks may
566 * belong to different cgroups on different hierarchies. In the other
567 * direction, a css_set is naturally associated with multiple cgroups.
568 * This M:N relationship is represented by the following link structure
569 * which exists for each association and allows traversing the associations
572 struct cgrp_cset_link {
573 /* the cgroup and css_set this link associates */
575 struct css_set *cset;
577 /* list of cgrp_cset_links anchored at cgrp->cset_links */
578 struct list_head cset_link;
580 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
581 struct list_head cgrp_link;
585 * The default css_set - used by init and its children prior to any
586 * hierarchies being mounted. It contains a pointer to the root state
587 * for each subsystem. Also used to anchor the list of css_sets. Not
588 * reference-counted, to improve performance when child cgroups
589 * haven't been created.
591 struct css_set init_css_set = {
592 .refcount = ATOMIC_INIT(1),
593 .cgrp_links = LIST_HEAD_INIT(init_css_set.cgrp_links),
594 .tasks = LIST_HEAD_INIT(init_css_set.tasks),
595 .mg_tasks = LIST_HEAD_INIT(init_css_set.mg_tasks),
596 .mg_preload_node = LIST_HEAD_INIT(init_css_set.mg_preload_node),
597 .mg_node = LIST_HEAD_INIT(init_css_set.mg_node),
598 .task_iters = LIST_HEAD_INIT(init_css_set.task_iters),
601 static int css_set_count = 1; /* 1 for init_css_set */
604 * css_set_populated - does a css_set contain any tasks?
605 * @cset: target css_set
607 static bool css_set_populated(struct css_set *cset)
609 lockdep_assert_held(&css_set_lock);
611 return !list_empty(&cset->tasks) || !list_empty(&cset->mg_tasks);
615 * cgroup_update_populated - updated populated count of a cgroup
616 * @cgrp: the target cgroup
617 * @populated: inc or dec populated count
619 * One of the css_sets associated with @cgrp is either getting its first
620 * task or losing the last. Update @cgrp->populated_cnt accordingly. The
621 * count is propagated towards root so that a given cgroup's populated_cnt
622 * is zero iff the cgroup and all its descendants don't contain any tasks.
624 * @cgrp's interface file "cgroup.populated" is zero if
625 * @cgrp->populated_cnt is zero and 1 otherwise. When @cgrp->populated_cnt
626 * changes from or to zero, userland is notified that the content of the
627 * interface file has changed. This can be used to detect when @cgrp and
628 * its descendants become populated or empty.
630 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
632 lockdep_assert_held(&css_set_lock);
638 trigger = !cgrp->populated_cnt++;
640 trigger = !--cgrp->populated_cnt;
645 check_for_release(cgrp);
646 cgroup_file_notify(&cgrp->events_file);
648 cgrp = cgroup_parent(cgrp);
653 * css_set_update_populated - update populated state of a css_set
654 * @cset: target css_set
655 * @populated: whether @cset is populated or depopulated
657 * @cset is either getting the first task or losing the last. Update the
658 * ->populated_cnt of all associated cgroups accordingly.
660 static void css_set_update_populated(struct css_set *cset, bool populated)
662 struct cgrp_cset_link *link;
664 lockdep_assert_held(&css_set_lock);
666 list_for_each_entry(link, &cset->cgrp_links, cgrp_link)
667 cgroup_update_populated(link->cgrp, populated);
671 * css_set_move_task - move a task from one css_set to another
672 * @task: task being moved
673 * @from_cset: css_set @task currently belongs to (may be NULL)
674 * @to_cset: new css_set @task is being moved to (may be NULL)
675 * @use_mg_tasks: move to @to_cset->mg_tasks instead of ->tasks
677 * Move @task from @from_cset to @to_cset. If @task didn't belong to any
678 * css_set, @from_cset can be NULL. If @task is being disassociated
679 * instead of moved, @to_cset can be NULL.
681 * This function automatically handles populated_cnt updates and
682 * css_task_iter adjustments but the caller is responsible for managing
683 * @from_cset and @to_cset's reference counts.
685 static void css_set_move_task(struct task_struct *task,
686 struct css_set *from_cset, struct css_set *to_cset,
689 lockdep_assert_held(&css_set_lock);
692 struct css_task_iter *it, *pos;
694 WARN_ON_ONCE(list_empty(&task->cg_list));
697 * @task is leaving, advance task iterators which are
698 * pointing to it so that they can resume at the next
699 * position. Advancing an iterator might remove it from
700 * the list, use safe walk. See css_task_iter_advance*()
703 list_for_each_entry_safe(it, pos, &from_cset->task_iters,
705 if (it->task_pos == &task->cg_list)
706 css_task_iter_advance(it);
708 list_del_init(&task->cg_list);
709 if (!css_set_populated(from_cset))
710 css_set_update_populated(from_cset, false);
712 WARN_ON_ONCE(!list_empty(&task->cg_list));
717 * We are synchronized through cgroup_threadgroup_rwsem
718 * against PF_EXITING setting such that we can't race
719 * against cgroup_exit() changing the css_set to
720 * init_css_set and dropping the old one.
722 WARN_ON_ONCE(task->flags & PF_EXITING);
724 if (!css_set_populated(to_cset))
725 css_set_update_populated(to_cset, true);
726 rcu_assign_pointer(task->cgroups, to_cset);
727 list_add_tail(&task->cg_list, use_mg_tasks ? &to_cset->mg_tasks :
733 * hash table for cgroup groups. This improves the performance to find
734 * an existing css_set. This hash doesn't (currently) take into
735 * account cgroups in empty hierarchies.
737 #define CSS_SET_HASH_BITS 7
738 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
740 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
742 unsigned long key = 0UL;
743 struct cgroup_subsys *ss;
746 for_each_subsys(ss, i)
747 key += (unsigned long)css[i];
748 key = (key >> 16) ^ key;
753 static void put_css_set_locked(struct css_set *cset)
755 struct cgrp_cset_link *link, *tmp_link;
756 struct cgroup_subsys *ss;
759 lockdep_assert_held(&css_set_lock);
761 if (!atomic_dec_and_test(&cset->refcount))
764 /* This css_set is dead. unlink it and release cgroup refcounts */
765 for_each_subsys(ss, ssid)
766 list_del(&cset->e_cset_node[ssid]);
767 hash_del(&cset->hlist);
770 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
771 list_del(&link->cset_link);
772 list_del(&link->cgrp_link);
773 if (cgroup_parent(link->cgrp))
774 cgroup_put(link->cgrp);
778 kfree_rcu(cset, rcu_head);
781 static void put_css_set(struct css_set *cset)
784 * Ensure that the refcount doesn't hit zero while any readers
785 * can see it. Similar to atomic_dec_and_lock(), but for an
788 if (atomic_add_unless(&cset->refcount, -1, 1))
791 spin_lock_bh(&css_set_lock);
792 put_css_set_locked(cset);
793 spin_unlock_bh(&css_set_lock);
797 * refcounted get/put for css_set objects
799 static inline void get_css_set(struct css_set *cset)
801 atomic_inc(&cset->refcount);
805 * compare_css_sets - helper function for find_existing_css_set().
806 * @cset: candidate css_set being tested
807 * @old_cset: existing css_set for a task
808 * @new_cgrp: cgroup that's being entered by the task
809 * @template: desired set of css pointers in css_set (pre-calculated)
811 * Returns true if "cset" matches "old_cset" except for the hierarchy
812 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
814 static bool compare_css_sets(struct css_set *cset,
815 struct css_set *old_cset,
816 struct cgroup *new_cgrp,
817 struct cgroup_subsys_state *template[])
819 struct list_head *l1, *l2;
822 * On the default hierarchy, there can be csets which are
823 * associated with the same set of cgroups but different csses.
824 * Let's first ensure that csses match.
826 if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
830 * Compare cgroup pointers in order to distinguish between
831 * different cgroups in hierarchies. As different cgroups may
832 * share the same effective css, this comparison is always
835 l1 = &cset->cgrp_links;
836 l2 = &old_cset->cgrp_links;
838 struct cgrp_cset_link *link1, *link2;
839 struct cgroup *cgrp1, *cgrp2;
843 /* See if we reached the end - both lists are equal length. */
844 if (l1 == &cset->cgrp_links) {
845 BUG_ON(l2 != &old_cset->cgrp_links);
848 BUG_ON(l2 == &old_cset->cgrp_links);
850 /* Locate the cgroups associated with these links. */
851 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
852 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
855 /* Hierarchies should be linked in the same order. */
856 BUG_ON(cgrp1->root != cgrp2->root);
859 * If this hierarchy is the hierarchy of the cgroup
860 * that's changing, then we need to check that this
861 * css_set points to the new cgroup; if it's any other
862 * hierarchy, then this css_set should point to the
863 * same cgroup as the old css_set.
865 if (cgrp1->root == new_cgrp->root) {
866 if (cgrp1 != new_cgrp)
877 * find_existing_css_set - init css array and find the matching css_set
878 * @old_cset: the css_set that we're using before the cgroup transition
879 * @cgrp: the cgroup that we're moving into
880 * @template: out param for the new set of csses, should be clear on entry
882 static struct css_set *find_existing_css_set(struct css_set *old_cset,
884 struct cgroup_subsys_state *template[])
886 struct cgroup_root *root = cgrp->root;
887 struct cgroup_subsys *ss;
888 struct css_set *cset;
893 * Build the set of subsystem state objects that we want to see in the
894 * new css_set. while subsystems can change globally, the entries here
895 * won't change, so no need for locking.
897 for_each_subsys(ss, i) {
898 if (root->subsys_mask & (1UL << i)) {
900 * @ss is in this hierarchy, so we want the
901 * effective css from @cgrp.
903 template[i] = cgroup_e_css(cgrp, ss);
906 * @ss is not in this hierarchy, so we don't want
909 template[i] = old_cset->subsys[i];
913 key = css_set_hash(template);
914 hash_for_each_possible(css_set_table, cset, hlist, key) {
915 if (!compare_css_sets(cset, old_cset, cgrp, template))
918 /* This css_set matches what we need */
922 /* No existing cgroup group matched */
926 static void free_cgrp_cset_links(struct list_head *links_to_free)
928 struct cgrp_cset_link *link, *tmp_link;
930 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
931 list_del(&link->cset_link);
937 * allocate_cgrp_cset_links - allocate cgrp_cset_links
938 * @count: the number of links to allocate
939 * @tmp_links: list_head the allocated links are put on
941 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
942 * through ->cset_link. Returns 0 on success or -errno.
944 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
946 struct cgrp_cset_link *link;
949 INIT_LIST_HEAD(tmp_links);
951 for (i = 0; i < count; i++) {
952 link = kzalloc(sizeof(*link), GFP_KERNEL);
954 free_cgrp_cset_links(tmp_links);
957 list_add(&link->cset_link, tmp_links);
963 * link_css_set - a helper function to link a css_set to a cgroup
964 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
965 * @cset: the css_set to be linked
966 * @cgrp: the destination cgroup
968 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
971 struct cgrp_cset_link *link;
973 BUG_ON(list_empty(tmp_links));
975 if (cgroup_on_dfl(cgrp))
976 cset->dfl_cgrp = cgrp;
978 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
983 * Always add links to the tail of the lists so that the lists are
984 * in choronological order.
986 list_move_tail(&link->cset_link, &cgrp->cset_links);
987 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
989 if (cgroup_parent(cgrp))
994 * find_css_set - return a new css_set with one cgroup updated
995 * @old_cset: the baseline css_set
996 * @cgrp: the cgroup to be updated
998 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
999 * substituted into the appropriate hierarchy.
1001 static struct css_set *find_css_set(struct css_set *old_cset,
1002 struct cgroup *cgrp)
1004 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
1005 struct css_set *cset;
1006 struct list_head tmp_links;
1007 struct cgrp_cset_link *link;
1008 struct cgroup_subsys *ss;
1012 lockdep_assert_held(&cgroup_mutex);
1014 /* First see if we already have a cgroup group that matches
1015 * the desired set */
1016 spin_lock_bh(&css_set_lock);
1017 cset = find_existing_css_set(old_cset, cgrp, template);
1020 spin_unlock_bh(&css_set_lock);
1025 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
1029 /* Allocate all the cgrp_cset_link objects that we'll need */
1030 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
1035 atomic_set(&cset->refcount, 1);
1036 INIT_LIST_HEAD(&cset->cgrp_links);
1037 INIT_LIST_HEAD(&cset->tasks);
1038 INIT_LIST_HEAD(&cset->mg_tasks);
1039 INIT_LIST_HEAD(&cset->mg_preload_node);
1040 INIT_LIST_HEAD(&cset->mg_node);
1041 INIT_LIST_HEAD(&cset->task_iters);
1042 INIT_HLIST_NODE(&cset->hlist);
1044 /* Copy the set of subsystem state objects generated in
1045 * find_existing_css_set() */
1046 memcpy(cset->subsys, template, sizeof(cset->subsys));
1048 spin_lock_bh(&css_set_lock);
1049 /* Add reference counts and links from the new css_set. */
1050 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
1051 struct cgroup *c = link->cgrp;
1053 if (c->root == cgrp->root)
1055 link_css_set(&tmp_links, cset, c);
1058 BUG_ON(!list_empty(&tmp_links));
1062 /* Add @cset to the hash table */
1063 key = css_set_hash(cset->subsys);
1064 hash_add(css_set_table, &cset->hlist, key);
1066 for_each_subsys(ss, ssid)
1067 list_add_tail(&cset->e_cset_node[ssid],
1068 &cset->subsys[ssid]->cgroup->e_csets[ssid]);
1070 spin_unlock_bh(&css_set_lock);
1075 static struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
1077 struct cgroup *root_cgrp = kf_root->kn->priv;
1079 return root_cgrp->root;
1082 static int cgroup_init_root_id(struct cgroup_root *root)
1086 lockdep_assert_held(&cgroup_mutex);
1088 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
1092 root->hierarchy_id = id;
1096 static void cgroup_exit_root_id(struct cgroup_root *root)
1098 lockdep_assert_held(&cgroup_mutex);
1100 if (root->hierarchy_id) {
1101 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1102 root->hierarchy_id = 0;
1106 static void cgroup_free_root(struct cgroup_root *root)
1109 /* hierarchy ID should already have been released */
1110 WARN_ON_ONCE(root->hierarchy_id);
1112 idr_destroy(&root->cgroup_idr);
1117 static void cgroup_destroy_root(struct cgroup_root *root)
1119 struct cgroup *cgrp = &root->cgrp;
1120 struct cgrp_cset_link *link, *tmp_link;
1122 mutex_lock(&cgroup_mutex);
1124 BUG_ON(atomic_read(&root->nr_cgrps));
1125 BUG_ON(!list_empty(&cgrp->self.children));
1127 /* Rebind all subsystems back to the default hierarchy */
1128 rebind_subsystems(&cgrp_dfl_root, root->subsys_mask);
1131 * Release all the links from cset_links to this hierarchy's
1134 spin_lock_bh(&css_set_lock);
1136 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1137 list_del(&link->cset_link);
1138 list_del(&link->cgrp_link);
1142 spin_unlock_bh(&css_set_lock);
1144 if (!list_empty(&root->root_list)) {
1145 list_del(&root->root_list);
1146 cgroup_root_count--;
1149 cgroup_exit_root_id(root);
1151 mutex_unlock(&cgroup_mutex);
1153 kernfs_destroy_root(root->kf_root);
1154 cgroup_free_root(root);
1157 /* look up cgroup associated with given css_set on the specified hierarchy */
1158 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
1159 struct cgroup_root *root)
1161 struct cgroup *res = NULL;
1163 lockdep_assert_held(&cgroup_mutex);
1164 lockdep_assert_held(&css_set_lock);
1166 if (cset == &init_css_set) {
1169 struct cgrp_cset_link *link;
1171 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1172 struct cgroup *c = link->cgrp;
1174 if (c->root == root) {
1186 * Return the cgroup for "task" from the given hierarchy. Must be
1187 * called with cgroup_mutex and css_set_lock held.
1189 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
1190 struct cgroup_root *root)
1193 * No need to lock the task - since we hold cgroup_mutex the
1194 * task can't change groups, so the only thing that can happen
1195 * is that it exits and its css is set back to init_css_set.
1197 return cset_cgroup_from_root(task_css_set(task), root);
1201 * A task must hold cgroup_mutex to modify cgroups.
1203 * Any task can increment and decrement the count field without lock.
1204 * So in general, code holding cgroup_mutex can't rely on the count
1205 * field not changing. However, if the count goes to zero, then only
1206 * cgroup_attach_task() can increment it again. Because a count of zero
1207 * means that no tasks are currently attached, therefore there is no
1208 * way a task attached to that cgroup can fork (the other way to
1209 * increment the count). So code holding cgroup_mutex can safely
1210 * assume that if the count is zero, it will stay zero. Similarly, if
1211 * a task holds cgroup_mutex on a cgroup with zero count, it
1212 * knows that the cgroup won't be removed, as cgroup_rmdir()
1215 * A cgroup can only be deleted if both its 'count' of using tasks
1216 * is zero, and its list of 'children' cgroups is empty. Since all
1217 * tasks in the system use _some_ cgroup, and since there is always at
1218 * least one task in the system (init, pid == 1), therefore, root cgroup
1219 * always has either children cgroups and/or using tasks. So we don't
1220 * need a special hack to ensure that root cgroup cannot be deleted.
1222 * P.S. One more locking exception. RCU is used to guard the
1223 * update of a tasks cgroup pointer by cgroup_attach_task()
1226 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
1227 static const struct file_operations proc_cgroupstats_operations;
1229 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
1232 struct cgroup_subsys *ss = cft->ss;
1234 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
1235 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
1236 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
1237 cgroup_on_dfl(cgrp) ? ss->name : ss->legacy_name,
1240 strncpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
1245 * cgroup_file_mode - deduce file mode of a control file
1246 * @cft: the control file in question
1248 * S_IRUGO for read, S_IWUSR for write.
1250 static umode_t cgroup_file_mode(const struct cftype *cft)
1254 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1257 if (cft->write_u64 || cft->write_s64 || cft->write) {
1258 if (cft->flags & CFTYPE_WORLD_WRITABLE)
1268 * cgroup_calc_child_subsys_mask - calculate child_subsys_mask
1269 * @cgrp: the target cgroup
1270 * @subtree_control: the new subtree_control mask to consider
1272 * On the default hierarchy, a subsystem may request other subsystems to be
1273 * enabled together through its ->depends_on mask. In such cases, more
1274 * subsystems than specified in "cgroup.subtree_control" may be enabled.
1276 * This function calculates which subsystems need to be enabled if
1277 * @subtree_control is to be applied to @cgrp. The returned mask is always
1278 * a superset of @subtree_control and follows the usual hierarchy rules.
1280 static unsigned long cgroup_calc_child_subsys_mask(struct cgroup *cgrp,
1281 unsigned long subtree_control)
1283 struct cgroup *parent = cgroup_parent(cgrp);
1284 unsigned long cur_ss_mask = subtree_control;
1285 struct cgroup_subsys *ss;
1288 lockdep_assert_held(&cgroup_mutex);
1290 if (!cgroup_on_dfl(cgrp))
1294 unsigned long new_ss_mask = cur_ss_mask;
1296 for_each_subsys_which(ss, ssid, &cur_ss_mask)
1297 new_ss_mask |= ss->depends_on;
1300 * Mask out subsystems which aren't available. This can
1301 * happen only if some depended-upon subsystems were bound
1302 * to non-default hierarchies.
1305 new_ss_mask &= parent->child_subsys_mask;
1307 new_ss_mask &= cgrp->root->subsys_mask;
1309 if (new_ss_mask == cur_ss_mask)
1311 cur_ss_mask = new_ss_mask;
1318 * cgroup_refresh_child_subsys_mask - update child_subsys_mask
1319 * @cgrp: the target cgroup
1321 * Update @cgrp->child_subsys_mask according to the current
1322 * @cgrp->subtree_control using cgroup_calc_child_subsys_mask().
1324 static void cgroup_refresh_child_subsys_mask(struct cgroup *cgrp)
1326 cgrp->child_subsys_mask =
1327 cgroup_calc_child_subsys_mask(cgrp, cgrp->subtree_control);
1331 * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
1332 * @kn: the kernfs_node being serviced
1334 * This helper undoes cgroup_kn_lock_live() and should be invoked before
1335 * the method finishes if locking succeeded. Note that once this function
1336 * returns the cgroup returned by cgroup_kn_lock_live() may become
1337 * inaccessible any time. If the caller intends to continue to access the
1338 * cgroup, it should pin it before invoking this function.
1340 static void cgroup_kn_unlock(struct kernfs_node *kn)
1342 struct cgroup *cgrp;
1344 if (kernfs_type(kn) == KERNFS_DIR)
1347 cgrp = kn->parent->priv;
1349 mutex_unlock(&cgroup_mutex);
1351 kernfs_unbreak_active_protection(kn);
1356 * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
1357 * @kn: the kernfs_node being serviced
1359 * This helper is to be used by a cgroup kernfs method currently servicing
1360 * @kn. It breaks the active protection, performs cgroup locking and
1361 * verifies that the associated cgroup is alive. Returns the cgroup if
1362 * alive; otherwise, %NULL. A successful return should be undone by a
1363 * matching cgroup_kn_unlock() invocation.
1365 * Any cgroup kernfs method implementation which requires locking the
1366 * associated cgroup should use this helper. It avoids nesting cgroup
1367 * locking under kernfs active protection and allows all kernfs operations
1368 * including self-removal.
1370 static struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn)
1372 struct cgroup *cgrp;
1374 if (kernfs_type(kn) == KERNFS_DIR)
1377 cgrp = kn->parent->priv;
1380 * We're gonna grab cgroup_mutex which nests outside kernfs
1381 * active_ref. cgroup liveliness check alone provides enough
1382 * protection against removal. Ensure @cgrp stays accessible and
1383 * break the active_ref protection.
1385 if (!cgroup_tryget(cgrp))
1387 kernfs_break_active_protection(kn);
1389 mutex_lock(&cgroup_mutex);
1391 if (!cgroup_is_dead(cgrp))
1394 cgroup_kn_unlock(kn);
1398 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1400 char name[CGROUP_FILE_NAME_MAX];
1402 lockdep_assert_held(&cgroup_mutex);
1404 if (cft->file_offset) {
1405 struct cgroup_subsys_state *css = cgroup_css(cgrp, cft->ss);
1406 struct cgroup_file *cfile = (void *)css + cft->file_offset;
1408 spin_lock_irq(&cgroup_file_kn_lock);
1410 spin_unlock_irq(&cgroup_file_kn_lock);
1413 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1417 * css_clear_dir - remove subsys files in a cgroup directory
1419 * @cgrp_override: specify if target cgroup is different from css->cgroup
1421 static void css_clear_dir(struct cgroup_subsys_state *css,
1422 struct cgroup *cgrp_override)
1424 struct cgroup *cgrp = cgrp_override ?: css->cgroup;
1425 struct cftype *cfts;
1427 list_for_each_entry(cfts, &css->ss->cfts, node)
1428 cgroup_addrm_files(css, cgrp, cfts, false);
1432 * css_populate_dir - create subsys files in a cgroup directory
1434 * @cgrp_overried: specify if target cgroup is different from css->cgroup
1436 * On failure, no file is added.
1438 static int css_populate_dir(struct cgroup_subsys_state *css,
1439 struct cgroup *cgrp_override)
1441 struct cgroup *cgrp = cgrp_override ?: css->cgroup;
1442 struct cftype *cfts, *failed_cfts;
1446 if (cgroup_on_dfl(cgrp))
1447 cfts = cgroup_dfl_base_files;
1449 cfts = cgroup_legacy_base_files;
1451 return cgroup_addrm_files(&cgrp->self, cgrp, cfts, true);
1454 list_for_each_entry(cfts, &css->ss->cfts, node) {
1455 ret = cgroup_addrm_files(css, cgrp, cfts, true);
1463 list_for_each_entry(cfts, &css->ss->cfts, node) {
1464 if (cfts == failed_cfts)
1466 cgroup_addrm_files(css, cgrp, cfts, false);
1471 static int rebind_subsystems(struct cgroup_root *dst_root,
1472 unsigned long ss_mask)
1474 struct cgroup *dcgrp = &dst_root->cgrp;
1475 struct cgroup_subsys *ss;
1476 unsigned long tmp_ss_mask;
1479 lockdep_assert_held(&cgroup_mutex);
1481 for_each_subsys_which(ss, ssid, &ss_mask) {
1482 /* if @ss has non-root csses attached to it, can't move */
1483 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)))
1486 /* can't move between two non-dummy roots either */
1487 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1491 /* skip creating root files on dfl_root for inhibited subsystems */
1492 tmp_ss_mask = ss_mask;
1493 if (dst_root == &cgrp_dfl_root)
1494 tmp_ss_mask &= ~cgrp_dfl_root_inhibit_ss_mask;
1496 for_each_subsys_which(ss, ssid, &tmp_ss_mask) {
1497 struct cgroup *scgrp = &ss->root->cgrp;
1500 ret = css_populate_dir(cgroup_css(scgrp, ss), dcgrp);
1505 * Rebinding back to the default root is not allowed to
1506 * fail. Using both default and non-default roots should
1507 * be rare. Moving subsystems back and forth even more so.
1508 * Just warn about it and continue.
1510 if (dst_root == &cgrp_dfl_root) {
1511 if (cgrp_dfl_root_visible) {
1512 pr_warn("failed to create files (%d) while rebinding 0x%lx to default root\n",
1514 pr_warn("you may retry by moving them to a different hierarchy and unbinding\n");
1519 for_each_subsys_which(ss, tssid, &tmp_ss_mask) {
1522 css_clear_dir(cgroup_css(scgrp, ss), dcgrp);
1528 * Nothing can fail from this point on. Remove files for the
1529 * removed subsystems and rebind each subsystem.
1531 for_each_subsys_which(ss, ssid, &ss_mask) {
1532 struct cgroup_root *src_root = ss->root;
1533 struct cgroup *scgrp = &src_root->cgrp;
1534 struct cgroup_subsys_state *css = cgroup_css(scgrp, ss);
1535 struct css_set *cset;
1537 WARN_ON(!css || cgroup_css(dcgrp, ss));
1539 css_clear_dir(css, NULL);
1541 RCU_INIT_POINTER(scgrp->subsys[ssid], NULL);
1542 rcu_assign_pointer(dcgrp->subsys[ssid], css);
1543 ss->root = dst_root;
1544 css->cgroup = dcgrp;
1546 spin_lock_bh(&css_set_lock);
1547 hash_for_each(css_set_table, i, cset, hlist)
1548 list_move_tail(&cset->e_cset_node[ss->id],
1549 &dcgrp->e_csets[ss->id]);
1550 spin_unlock_bh(&css_set_lock);
1552 src_root->subsys_mask &= ~(1 << ssid);
1553 scgrp->subtree_control &= ~(1 << ssid);
1554 cgroup_refresh_child_subsys_mask(scgrp);
1556 /* default hierarchy doesn't enable controllers by default */
1557 dst_root->subsys_mask |= 1 << ssid;
1558 if (dst_root == &cgrp_dfl_root) {
1559 static_branch_enable(cgroup_subsys_on_dfl_key[ssid]);
1561 dcgrp->subtree_control |= 1 << ssid;
1562 cgroup_refresh_child_subsys_mask(dcgrp);
1563 static_branch_disable(cgroup_subsys_on_dfl_key[ssid]);
1570 kernfs_activate(dcgrp->kn);
1574 static int cgroup_show_options(struct seq_file *seq,
1575 struct kernfs_root *kf_root)
1577 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1578 struct cgroup_subsys *ss;
1581 if (root != &cgrp_dfl_root)
1582 for_each_subsys(ss, ssid)
1583 if (root->subsys_mask & (1 << ssid))
1584 seq_show_option(seq, ss->legacy_name, NULL);
1585 if (root->flags & CGRP_ROOT_NOPREFIX)
1586 seq_puts(seq, ",noprefix");
1587 if (root->flags & CGRP_ROOT_XATTR)
1588 seq_puts(seq, ",xattr");
1590 spin_lock(&release_agent_path_lock);
1591 if (strlen(root->release_agent_path))
1592 seq_show_option(seq, "release_agent",
1593 root->release_agent_path);
1594 spin_unlock(&release_agent_path_lock);
1596 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags))
1597 seq_puts(seq, ",clone_children");
1598 if (strlen(root->name))
1599 seq_show_option(seq, "name", root->name);
1603 struct cgroup_sb_opts {
1604 unsigned long subsys_mask;
1606 char *release_agent;
1607 bool cpuset_clone_children;
1609 /* User explicitly requested empty subsystem */
1613 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1615 char *token, *o = data;
1616 bool all_ss = false, one_ss = false;
1617 unsigned long mask = -1UL;
1618 struct cgroup_subsys *ss;
1622 #ifdef CONFIG_CPUSETS
1623 mask = ~(1U << cpuset_cgrp_id);
1626 memset(opts, 0, sizeof(*opts));
1628 while ((token = strsep(&o, ",")) != NULL) {
1633 if (!strcmp(token, "none")) {
1634 /* Explicitly have no subsystems */
1638 if (!strcmp(token, "all")) {
1639 /* Mutually exclusive option 'all' + subsystem name */
1645 if (!strcmp(token, "noprefix")) {
1646 opts->flags |= CGRP_ROOT_NOPREFIX;
1649 if (!strcmp(token, "clone_children")) {
1650 opts->cpuset_clone_children = true;
1653 if (!strcmp(token, "xattr")) {
1654 opts->flags |= CGRP_ROOT_XATTR;
1657 if (!strncmp(token, "release_agent=", 14)) {
1658 /* Specifying two release agents is forbidden */
1659 if (opts->release_agent)
1661 opts->release_agent =
1662 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1663 if (!opts->release_agent)
1667 if (!strncmp(token, "name=", 5)) {
1668 const char *name = token + 5;
1669 /* Can't specify an empty name */
1672 /* Must match [\w.-]+ */
1673 for (i = 0; i < strlen(name); i++) {
1677 if ((c == '.') || (c == '-') || (c == '_'))
1681 /* Specifying two names is forbidden */
1684 opts->name = kstrndup(name,
1685 MAX_CGROUP_ROOT_NAMELEN - 1,
1693 for_each_subsys(ss, i) {
1694 if (strcmp(token, ss->legacy_name))
1696 if (!cgroup_ssid_enabled(i))
1699 /* Mutually exclusive option 'all' + subsystem name */
1702 opts->subsys_mask |= (1 << i);
1707 if (i == CGROUP_SUBSYS_COUNT)
1712 * If the 'all' option was specified select all the subsystems,
1713 * otherwise if 'none', 'name=' and a subsystem name options were
1714 * not specified, let's default to 'all'
1716 if (all_ss || (!one_ss && !opts->none && !opts->name))
1717 for_each_subsys(ss, i)
1718 if (cgroup_ssid_enabled(i))
1719 opts->subsys_mask |= (1 << i);
1722 * We either have to specify by name or by subsystems. (So all
1723 * empty hierarchies must have a name).
1725 if (!opts->subsys_mask && !opts->name)
1729 * Option noprefix was introduced just for backward compatibility
1730 * with the old cpuset, so we allow noprefix only if mounting just
1731 * the cpuset subsystem.
1733 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1736 /* Can't specify "none" and some subsystems */
1737 if (opts->subsys_mask && opts->none)
1743 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1746 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
1747 struct cgroup_sb_opts opts;
1748 unsigned long added_mask, removed_mask;
1750 if (root == &cgrp_dfl_root) {
1751 pr_err("remount is not allowed\n");
1755 mutex_lock(&cgroup_mutex);
1757 /* See what subsystems are wanted */
1758 ret = parse_cgroupfs_options(data, &opts);
1762 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1763 pr_warn("option changes via remount are deprecated (pid=%d comm=%s)\n",
1764 task_tgid_nr(current), current->comm);
1766 added_mask = opts.subsys_mask & ~root->subsys_mask;
1767 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1769 /* Don't allow flags or name to change at remount */
1770 if ((opts.flags ^ root->flags) ||
1771 (opts.name && strcmp(opts.name, root->name))) {
1772 pr_err("option or name mismatch, new: 0x%x \"%s\", old: 0x%x \"%s\"\n",
1773 opts.flags, opts.name ?: "", root->flags, root->name);
1778 /* remounting is not allowed for populated hierarchies */
1779 if (!list_empty(&root->cgrp.self.children)) {
1784 ret = rebind_subsystems(root, added_mask);
1788 rebind_subsystems(&cgrp_dfl_root, removed_mask);
1790 if (opts.release_agent) {
1791 spin_lock(&release_agent_path_lock);
1792 strcpy(root->release_agent_path, opts.release_agent);
1793 spin_unlock(&release_agent_path_lock);
1796 kfree(opts.release_agent);
1798 mutex_unlock(&cgroup_mutex);
1803 * To reduce the fork() overhead for systems that are not actually using
1804 * their cgroups capability, we don't maintain the lists running through
1805 * each css_set to its tasks until we see the list actually used - in other
1806 * words after the first mount.
1808 static bool use_task_css_set_links __read_mostly;
1810 static void cgroup_enable_task_cg_lists(void)
1812 struct task_struct *p, *g;
1814 spin_lock_bh(&css_set_lock);
1816 if (use_task_css_set_links)
1819 use_task_css_set_links = true;
1822 * We need tasklist_lock because RCU is not safe against
1823 * while_each_thread(). Besides, a forking task that has passed
1824 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1825 * is not guaranteed to have its child immediately visible in the
1826 * tasklist if we walk through it with RCU.
1828 read_lock(&tasklist_lock);
1829 do_each_thread(g, p) {
1830 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1831 task_css_set(p) != &init_css_set);
1834 * We should check if the process is exiting, otherwise
1835 * it will race with cgroup_exit() in that the list
1836 * entry won't be deleted though the process has exited.
1837 * Do it while holding siglock so that we don't end up
1838 * racing against cgroup_exit().
1840 spin_lock_irq(&p->sighand->siglock);
1841 if (!(p->flags & PF_EXITING)) {
1842 struct css_set *cset = task_css_set(p);
1844 if (!css_set_populated(cset))
1845 css_set_update_populated(cset, true);
1846 list_add_tail(&p->cg_list, &cset->tasks);
1849 spin_unlock_irq(&p->sighand->siglock);
1850 } while_each_thread(g, p);
1851 read_unlock(&tasklist_lock);
1853 spin_unlock_bh(&css_set_lock);
1856 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1858 struct cgroup_subsys *ss;
1861 INIT_LIST_HEAD(&cgrp->self.sibling);
1862 INIT_LIST_HEAD(&cgrp->self.children);
1863 INIT_LIST_HEAD(&cgrp->cset_links);
1864 INIT_LIST_HEAD(&cgrp->pidlists);
1865 mutex_init(&cgrp->pidlist_mutex);
1866 cgrp->self.cgroup = cgrp;
1867 cgrp->self.flags |= CSS_ONLINE;
1869 for_each_subsys(ss, ssid)
1870 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
1872 init_waitqueue_head(&cgrp->offline_waitq);
1873 INIT_WORK(&cgrp->release_agent_work, cgroup_release_agent);
1876 static void init_cgroup_root(struct cgroup_root *root,
1877 struct cgroup_sb_opts *opts)
1879 struct cgroup *cgrp = &root->cgrp;
1881 INIT_LIST_HEAD(&root->root_list);
1882 atomic_set(&root->nr_cgrps, 1);
1884 init_cgroup_housekeeping(cgrp);
1885 idr_init(&root->cgroup_idr);
1887 root->flags = opts->flags;
1888 if (opts->release_agent)
1889 strcpy(root->release_agent_path, opts->release_agent);
1891 strcpy(root->name, opts->name);
1892 if (opts->cpuset_clone_children)
1893 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1896 static int cgroup_setup_root(struct cgroup_root *root, unsigned long ss_mask)
1898 LIST_HEAD(tmp_links);
1899 struct cgroup *root_cgrp = &root->cgrp;
1900 struct css_set *cset;
1903 lockdep_assert_held(&cgroup_mutex);
1905 ret = cgroup_idr_alloc(&root->cgroup_idr, root_cgrp, 1, 2, GFP_KERNEL);
1908 root_cgrp->id = ret;
1910 ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release, 0,
1916 * We're accessing css_set_count without locking css_set_lock here,
1917 * but that's OK - it can only be increased by someone holding
1918 * cgroup_lock, and that's us. The worst that can happen is that we
1919 * have some link structures left over
1921 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1925 ret = cgroup_init_root_id(root);
1929 root->kf_root = kernfs_create_root(&cgroup_kf_syscall_ops,
1930 KERNFS_ROOT_CREATE_DEACTIVATED,
1932 if (IS_ERR(root->kf_root)) {
1933 ret = PTR_ERR(root->kf_root);
1936 root_cgrp->kn = root->kf_root->kn;
1938 ret = css_populate_dir(&root_cgrp->self, NULL);
1942 ret = rebind_subsystems(root, ss_mask);
1947 * There must be no failure case after here, since rebinding takes
1948 * care of subsystems' refcounts, which are explicitly dropped in
1949 * the failure exit path.
1951 list_add(&root->root_list, &cgroup_roots);
1952 cgroup_root_count++;
1955 * Link the root cgroup in this hierarchy into all the css_set
1958 spin_lock_bh(&css_set_lock);
1959 hash_for_each(css_set_table, i, cset, hlist) {
1960 link_css_set(&tmp_links, cset, root_cgrp);
1961 if (css_set_populated(cset))
1962 cgroup_update_populated(root_cgrp, true);
1964 spin_unlock_bh(&css_set_lock);
1966 BUG_ON(!list_empty(&root_cgrp->self.children));
1967 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
1969 kernfs_activate(root_cgrp->kn);
1974 kernfs_destroy_root(root->kf_root);
1975 root->kf_root = NULL;
1977 cgroup_exit_root_id(root);
1979 percpu_ref_exit(&root_cgrp->self.refcnt);
1981 free_cgrp_cset_links(&tmp_links);
1985 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1986 int flags, const char *unused_dev_name,
1989 bool is_v2 = fs_type == &cgroup2_fs_type;
1990 struct super_block *pinned_sb = NULL;
1991 struct cgroup_subsys *ss;
1992 struct cgroup_root *root;
1993 struct cgroup_sb_opts opts;
1994 struct dentry *dentry;
2000 * The first time anyone tries to mount a cgroup, enable the list
2001 * linking each css_set to its tasks and fix up all existing tasks.
2003 if (!use_task_css_set_links)
2004 cgroup_enable_task_cg_lists();
2008 pr_err("cgroup2: unknown option \"%s\"\n", (char *)data);
2009 return ERR_PTR(-EINVAL);
2011 cgrp_dfl_root_visible = true;
2012 root = &cgrp_dfl_root;
2013 cgroup_get(&root->cgrp);
2017 mutex_lock(&cgroup_mutex);
2019 /* First find the desired set of subsystems */
2020 ret = parse_cgroupfs_options(data, &opts);
2025 * Destruction of cgroup root is asynchronous, so subsystems may
2026 * still be dying after the previous unmount. Let's drain the
2027 * dying subsystems. We just need to ensure that the ones
2028 * unmounted previously finish dying and don't care about new ones
2029 * starting. Testing ref liveliness is good enough.
2031 for_each_subsys(ss, i) {
2032 if (!(opts.subsys_mask & (1 << i)) ||
2033 ss->root == &cgrp_dfl_root)
2036 if (!percpu_ref_tryget_live(&ss->root->cgrp.self.refcnt)) {
2037 mutex_unlock(&cgroup_mutex);
2039 ret = restart_syscall();
2042 cgroup_put(&ss->root->cgrp);
2045 for_each_root(root) {
2046 bool name_match = false;
2048 if (root == &cgrp_dfl_root)
2052 * If we asked for a name then it must match. Also, if
2053 * name matches but sybsys_mask doesn't, we should fail.
2054 * Remember whether name matched.
2057 if (strcmp(opts.name, root->name))
2063 * If we asked for subsystems (or explicitly for no
2064 * subsystems) then they must match.
2066 if ((opts.subsys_mask || opts.none) &&
2067 (opts.subsys_mask != root->subsys_mask)) {
2074 if (root->flags ^ opts.flags)
2075 pr_warn("new mount options do not match the existing superblock, will be ignored\n");
2078 * We want to reuse @root whose lifetime is governed by its
2079 * ->cgrp. Let's check whether @root is alive and keep it
2080 * that way. As cgroup_kill_sb() can happen anytime, we
2081 * want to block it by pinning the sb so that @root doesn't
2082 * get killed before mount is complete.
2084 * With the sb pinned, tryget_live can reliably indicate
2085 * whether @root can be reused. If it's being killed,
2086 * drain it. We can use wait_queue for the wait but this
2087 * path is super cold. Let's just sleep a bit and retry.
2089 pinned_sb = kernfs_pin_sb(root->kf_root, NULL);
2090 if (IS_ERR(pinned_sb) ||
2091 !percpu_ref_tryget_live(&root->cgrp.self.refcnt)) {
2092 mutex_unlock(&cgroup_mutex);
2093 if (!IS_ERR_OR_NULL(pinned_sb))
2094 deactivate_super(pinned_sb);
2096 ret = restart_syscall();
2105 * No such thing, create a new one. name= matching without subsys
2106 * specification is allowed for already existing hierarchies but we
2107 * can't create new one without subsys specification.
2109 if (!opts.subsys_mask && !opts.none) {
2114 root = kzalloc(sizeof(*root), GFP_KERNEL);
2120 init_cgroup_root(root, &opts);
2122 ret = cgroup_setup_root(root, opts.subsys_mask);
2124 cgroup_free_root(root);
2127 mutex_unlock(&cgroup_mutex);
2129 kfree(opts.release_agent);
2133 return ERR_PTR(ret);
2135 dentry = kernfs_mount(fs_type, flags, root->kf_root,
2136 is_v2 ? CGROUP2_SUPER_MAGIC : CGROUP_SUPER_MAGIC,
2138 if (IS_ERR(dentry) || !new_sb)
2139 cgroup_put(&root->cgrp);
2142 * If @pinned_sb, we're reusing an existing root and holding an
2143 * extra ref on its sb. Mount is complete. Put the extra ref.
2147 deactivate_super(pinned_sb);
2153 static void cgroup_kill_sb(struct super_block *sb)
2155 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
2156 struct cgroup_root *root = cgroup_root_from_kf(kf_root);
2159 * If @root doesn't have any mounts or children, start killing it.
2160 * This prevents new mounts by disabling percpu_ref_tryget_live().
2161 * cgroup_mount() may wait for @root's release.
2163 * And don't kill the default root.
2165 if (!list_empty(&root->cgrp.self.children) ||
2166 root == &cgrp_dfl_root)
2167 cgroup_put(&root->cgrp);
2169 percpu_ref_kill(&root->cgrp.self.refcnt);
2174 static struct file_system_type cgroup_fs_type = {
2176 .mount = cgroup_mount,
2177 .kill_sb = cgroup_kill_sb,
2180 static struct file_system_type cgroup2_fs_type = {
2182 .mount = cgroup_mount,
2183 .kill_sb = cgroup_kill_sb,
2187 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
2188 * @task: target task
2189 * @buf: the buffer to write the path into
2190 * @buflen: the length of the buffer
2192 * Determine @task's cgroup on the first (the one with the lowest non-zero
2193 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
2194 * function grabs cgroup_mutex and shouldn't be used inside locks used by
2195 * cgroup controller callbacks.
2197 * Return value is the same as kernfs_path().
2199 char *task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
2201 struct cgroup_root *root;
2202 struct cgroup *cgrp;
2203 int hierarchy_id = 1;
2206 mutex_lock(&cgroup_mutex);
2207 spin_lock_bh(&css_set_lock);
2209 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
2212 cgrp = task_cgroup_from_root(task, root);
2213 path = cgroup_path(cgrp, buf, buflen);
2215 /* if no hierarchy exists, everyone is in "/" */
2216 if (strlcpy(buf, "/", buflen) < buflen)
2220 spin_unlock_bh(&css_set_lock);
2221 mutex_unlock(&cgroup_mutex);
2224 EXPORT_SYMBOL_GPL(task_cgroup_path);
2226 /* used to track tasks and other necessary states during migration */
2227 struct cgroup_taskset {
2228 /* the src and dst cset list running through cset->mg_node */
2229 struct list_head src_csets;
2230 struct list_head dst_csets;
2233 * Fields for cgroup_taskset_*() iteration.
2235 * Before migration is committed, the target migration tasks are on
2236 * ->mg_tasks of the csets on ->src_csets. After, on ->mg_tasks of
2237 * the csets on ->dst_csets. ->csets point to either ->src_csets
2238 * or ->dst_csets depending on whether migration is committed.
2240 * ->cur_csets and ->cur_task point to the current task position
2243 struct list_head *csets;
2244 struct css_set *cur_cset;
2245 struct task_struct *cur_task;
2248 #define CGROUP_TASKSET_INIT(tset) (struct cgroup_taskset){ \
2249 .src_csets = LIST_HEAD_INIT(tset.src_csets), \
2250 .dst_csets = LIST_HEAD_INIT(tset.dst_csets), \
2251 .csets = &tset.src_csets, \
2255 * cgroup_taskset_add - try to add a migration target task to a taskset
2256 * @task: target task
2257 * @tset: target taskset
2259 * Add @task, which is a migration target, to @tset. This function becomes
2260 * noop if @task doesn't need to be migrated. @task's css_set should have
2261 * been added as a migration source and @task->cg_list will be moved from
2262 * the css_set's tasks list to mg_tasks one.
2264 static void cgroup_taskset_add(struct task_struct *task,
2265 struct cgroup_taskset *tset)
2267 struct css_set *cset;
2269 lockdep_assert_held(&css_set_lock);
2271 /* @task either already exited or can't exit until the end */
2272 if (task->flags & PF_EXITING)
2275 /* leave @task alone if post_fork() hasn't linked it yet */
2276 if (list_empty(&task->cg_list))
2279 cset = task_css_set(task);
2280 if (!cset->mg_src_cgrp)
2283 list_move_tail(&task->cg_list, &cset->mg_tasks);
2284 if (list_empty(&cset->mg_node))
2285 list_add_tail(&cset->mg_node, &tset->src_csets);
2286 if (list_empty(&cset->mg_dst_cset->mg_node))
2287 list_move_tail(&cset->mg_dst_cset->mg_node,
2292 * cgroup_taskset_first - reset taskset and return the first task
2293 * @tset: taskset of interest
2295 * @tset iteration is initialized and the first task is returned.
2297 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
2299 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
2300 tset->cur_task = NULL;
2302 return cgroup_taskset_next(tset);
2306 * cgroup_taskset_next - iterate to the next task in taskset
2307 * @tset: taskset of interest
2309 * Return the next task in @tset. Iteration must have been initialized
2310 * with cgroup_taskset_first().
2312 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
2314 struct css_set *cset = tset->cur_cset;
2315 struct task_struct *task = tset->cur_task;
2317 while (&cset->mg_node != tset->csets) {
2319 task = list_first_entry(&cset->mg_tasks,
2320 struct task_struct, cg_list);
2322 task = list_next_entry(task, cg_list);
2324 if (&task->cg_list != &cset->mg_tasks) {
2325 tset->cur_cset = cset;
2326 tset->cur_task = task;
2330 cset = list_next_entry(cset, mg_node);
2338 * cgroup_taskset_migrate - migrate a taskset to a cgroup
2339 * @tset: taget taskset
2340 * @dst_cgrp: destination cgroup
2342 * Migrate tasks in @tset to @dst_cgrp. This function fails iff one of the
2343 * ->can_attach callbacks fails and guarantees that either all or none of
2344 * the tasks in @tset are migrated. @tset is consumed regardless of
2347 static int cgroup_taskset_migrate(struct cgroup_taskset *tset,
2348 struct cgroup *dst_cgrp)
2350 struct cgroup_subsys_state *css, *failed_css = NULL;
2351 struct task_struct *task, *tmp_task;
2352 struct css_set *cset, *tmp_cset;
2355 /* methods shouldn't be called if no task is actually migrating */
2356 if (list_empty(&tset->src_csets))
2359 /* check that we can legitimately attach to the cgroup */
2360 for_each_e_css(css, i, dst_cgrp) {
2361 if (css->ss->can_attach) {
2362 ret = css->ss->can_attach(css, tset);
2365 goto out_cancel_attach;
2371 * Now that we're guaranteed success, proceed to move all tasks to
2372 * the new cgroup. There are no failure cases after here, so this
2373 * is the commit point.
2375 spin_lock_bh(&css_set_lock);
2376 list_for_each_entry(cset, &tset->src_csets, mg_node) {
2377 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list) {
2378 struct css_set *from_cset = task_css_set(task);
2379 struct css_set *to_cset = cset->mg_dst_cset;
2381 get_css_set(to_cset);
2382 css_set_move_task(task, from_cset, to_cset, true);
2383 put_css_set_locked(from_cset);
2386 spin_unlock_bh(&css_set_lock);
2389 * Migration is committed, all target tasks are now on dst_csets.
2390 * Nothing is sensitive to fork() after this point. Notify
2391 * controllers that migration is complete.
2393 tset->csets = &tset->dst_csets;
2395 for_each_e_css(css, i, dst_cgrp)
2396 if (css->ss->attach)
2397 css->ss->attach(css, tset);
2400 goto out_release_tset;
2403 for_each_e_css(css, i, dst_cgrp) {
2404 if (css == failed_css)
2406 if (css->ss->cancel_attach)
2407 css->ss->cancel_attach(css, tset);
2410 spin_lock_bh(&css_set_lock);
2411 list_splice_init(&tset->dst_csets, &tset->src_csets);
2412 list_for_each_entry_safe(cset, tmp_cset, &tset->src_csets, mg_node) {
2413 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2414 list_del_init(&cset->mg_node);
2416 spin_unlock_bh(&css_set_lock);
2421 * cgroup_migrate_finish - cleanup after attach
2422 * @preloaded_csets: list of preloaded css_sets
2424 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
2425 * those functions for details.
2427 static void cgroup_migrate_finish(struct list_head *preloaded_csets)
2429 struct css_set *cset, *tmp_cset;
2431 lockdep_assert_held(&cgroup_mutex);
2433 spin_lock_bh(&css_set_lock);
2434 list_for_each_entry_safe(cset, tmp_cset, preloaded_csets, mg_preload_node) {
2435 cset->mg_src_cgrp = NULL;
2436 cset->mg_dst_cset = NULL;
2437 list_del_init(&cset->mg_preload_node);
2438 put_css_set_locked(cset);
2440 spin_unlock_bh(&css_set_lock);
2444 * cgroup_migrate_add_src - add a migration source css_set
2445 * @src_cset: the source css_set to add
2446 * @dst_cgrp: the destination cgroup
2447 * @preloaded_csets: list of preloaded css_sets
2449 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
2450 * @src_cset and add it to @preloaded_csets, which should later be cleaned
2451 * up by cgroup_migrate_finish().
2453 * This function may be called without holding cgroup_threadgroup_rwsem
2454 * even if the target is a process. Threads may be created and destroyed
2455 * but as long as cgroup_mutex is not dropped, no new css_set can be put
2456 * into play and the preloaded css_sets are guaranteed to cover all
2459 static void cgroup_migrate_add_src(struct css_set *src_cset,
2460 struct cgroup *dst_cgrp,
2461 struct list_head *preloaded_csets)
2463 struct cgroup *src_cgrp;
2465 lockdep_assert_held(&cgroup_mutex);
2466 lockdep_assert_held(&css_set_lock);
2468 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2470 if (!list_empty(&src_cset->mg_preload_node))
2473 WARN_ON(src_cset->mg_src_cgrp);
2474 WARN_ON(!list_empty(&src_cset->mg_tasks));
2475 WARN_ON(!list_empty(&src_cset->mg_node));
2477 src_cset->mg_src_cgrp = src_cgrp;
2478 get_css_set(src_cset);
2479 list_add(&src_cset->mg_preload_node, preloaded_csets);
2483 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2484 * @dst_cgrp: the destination cgroup (may be %NULL)
2485 * @preloaded_csets: list of preloaded source css_sets
2487 * Tasks are about to be moved to @dst_cgrp and all the source css_sets
2488 * have been preloaded to @preloaded_csets. This function looks up and
2489 * pins all destination css_sets, links each to its source, and append them
2490 * to @preloaded_csets. If @dst_cgrp is %NULL, the destination of each
2491 * source css_set is assumed to be its cgroup on the default hierarchy.
2493 * This function must be called after cgroup_migrate_add_src() has been
2494 * called on each migration source css_set. After migration is performed
2495 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2498 static int cgroup_migrate_prepare_dst(struct cgroup *dst_cgrp,
2499 struct list_head *preloaded_csets)
2502 struct css_set *src_cset, *tmp_cset;
2504 lockdep_assert_held(&cgroup_mutex);
2507 * Except for the root, child_subsys_mask must be zero for a cgroup
2508 * with tasks so that child cgroups don't compete against tasks.
2510 if (dst_cgrp && cgroup_on_dfl(dst_cgrp) && cgroup_parent(dst_cgrp) &&
2511 dst_cgrp->child_subsys_mask)
2514 /* look up the dst cset for each src cset and link it to src */
2515 list_for_each_entry_safe(src_cset, tmp_cset, preloaded_csets, mg_preload_node) {
2516 struct css_set *dst_cset;
2518 dst_cset = find_css_set(src_cset,
2519 dst_cgrp ?: src_cset->dfl_cgrp);
2523 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2526 * If src cset equals dst, it's noop. Drop the src.
2527 * cgroup_migrate() will skip the cset too. Note that we
2528 * can't handle src == dst as some nodes are used by both.
2530 if (src_cset == dst_cset) {
2531 src_cset->mg_src_cgrp = NULL;
2532 list_del_init(&src_cset->mg_preload_node);
2533 put_css_set(src_cset);
2534 put_css_set(dst_cset);
2538 src_cset->mg_dst_cset = dst_cset;
2540 if (list_empty(&dst_cset->mg_preload_node))
2541 list_add(&dst_cset->mg_preload_node, &csets);
2543 put_css_set(dst_cset);
2546 list_splice_tail(&csets, preloaded_csets);
2549 cgroup_migrate_finish(&csets);
2554 * cgroup_migrate - migrate a process or task to a cgroup
2555 * @leader: the leader of the process or the task to migrate
2556 * @threadgroup: whether @leader points to the whole process or a single task
2557 * @cgrp: the destination cgroup
2559 * Migrate a process or task denoted by @leader to @cgrp. If migrating a
2560 * process, the caller must be holding cgroup_threadgroup_rwsem. The
2561 * caller is also responsible for invoking cgroup_migrate_add_src() and
2562 * cgroup_migrate_prepare_dst() on the targets before invoking this
2563 * function and following up with cgroup_migrate_finish().
2565 * As long as a controller's ->can_attach() doesn't fail, this function is
2566 * guaranteed to succeed. This means that, excluding ->can_attach()
2567 * failure, when migrating multiple targets, the success or failure can be
2568 * decided for all targets by invoking group_migrate_prepare_dst() before
2569 * actually starting migrating.
2571 static int cgroup_migrate(struct task_struct *leader, bool threadgroup,
2572 struct cgroup *cgrp)
2574 struct cgroup_taskset tset = CGROUP_TASKSET_INIT(tset);
2575 struct task_struct *task;
2578 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2579 * already PF_EXITING could be freed from underneath us unless we
2580 * take an rcu_read_lock.
2582 spin_lock_bh(&css_set_lock);
2586 cgroup_taskset_add(task, &tset);
2589 } while_each_thread(leader, task);
2591 spin_unlock_bh(&css_set_lock);
2593 return cgroup_taskset_migrate(&tset, cgrp);
2597 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2598 * @dst_cgrp: the cgroup to attach to
2599 * @leader: the task or the leader of the threadgroup to be attached
2600 * @threadgroup: attach the whole threadgroup?
2602 * Call holding cgroup_mutex and cgroup_threadgroup_rwsem.
2604 static int cgroup_attach_task(struct cgroup *dst_cgrp,
2605 struct task_struct *leader, bool threadgroup)
2607 LIST_HEAD(preloaded_csets);
2608 struct task_struct *task;
2611 /* look up all src csets */
2612 spin_lock_bh(&css_set_lock);
2616 cgroup_migrate_add_src(task_css_set(task), dst_cgrp,
2620 } while_each_thread(leader, task);
2622 spin_unlock_bh(&css_set_lock);
2624 /* prepare dst csets and commit */
2625 ret = cgroup_migrate_prepare_dst(dst_cgrp, &preloaded_csets);
2627 ret = cgroup_migrate(leader, threadgroup, dst_cgrp);
2629 cgroup_migrate_finish(&preloaded_csets);
2633 static int cgroup_procs_write_permission(struct task_struct *task,
2634 struct cgroup *dst_cgrp,
2635 struct kernfs_open_file *of)
2637 const struct cred *cred = current_cred();
2638 const struct cred *tcred = get_task_cred(task);
2642 * even if we're attaching all tasks in the thread group, we only
2643 * need to check permissions on one of them.
2645 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2646 !uid_eq(cred->euid, tcred->uid) &&
2647 !uid_eq(cred->euid, tcred->suid))
2650 if (!ret && cgroup_on_dfl(dst_cgrp)) {
2651 struct super_block *sb = of->file->f_path.dentry->d_sb;
2652 struct cgroup *cgrp;
2653 struct inode *inode;
2655 spin_lock_bh(&css_set_lock);
2656 cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
2657 spin_unlock_bh(&css_set_lock);
2659 while (!cgroup_is_descendant(dst_cgrp, cgrp))
2660 cgrp = cgroup_parent(cgrp);
2663 inode = kernfs_get_inode(sb, cgrp->procs_file.kn);
2665 ret = inode_permission(inode, MAY_WRITE);
2675 * Find the task_struct of the task to attach by vpid and pass it along to the
2676 * function to attach either it or all tasks in its threadgroup. Will lock
2677 * cgroup_mutex and threadgroup.
2679 static ssize_t __cgroup_procs_write(struct kernfs_open_file *of, char *buf,
2680 size_t nbytes, loff_t off, bool threadgroup)
2682 struct task_struct *tsk;
2683 struct cgroup *cgrp;
2687 if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2690 cgrp = cgroup_kn_lock_live(of->kn);
2694 percpu_down_write(&cgroup_threadgroup_rwsem);
2697 tsk = find_task_by_vpid(pid);
2700 goto out_unlock_rcu;
2707 tsk = tsk->group_leader;
2710 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2711 * trapped in a cpuset, or RT worker may be born in a cgroup
2712 * with no rt_runtime allocated. Just say no.
2714 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2716 goto out_unlock_rcu;
2719 get_task_struct(tsk);
2722 ret = cgroup_procs_write_permission(tsk, cgrp, of);
2724 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2726 put_task_struct(tsk);
2727 goto out_unlock_threadgroup;
2731 out_unlock_threadgroup:
2732 percpu_up_write(&cgroup_threadgroup_rwsem);
2733 cgroup_kn_unlock(of->kn);
2734 return ret ?: nbytes;
2738 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2739 * @from: attach to all cgroups of a given task
2740 * @tsk: the task to be attached
2742 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2744 struct cgroup_root *root;
2747 mutex_lock(&cgroup_mutex);
2748 for_each_root(root) {
2749 struct cgroup *from_cgrp;
2751 if (root == &cgrp_dfl_root)
2754 spin_lock_bh(&css_set_lock);
2755 from_cgrp = task_cgroup_from_root(from, root);
2756 spin_unlock_bh(&css_set_lock);
2758 retval = cgroup_attach_task(from_cgrp, tsk, false);
2762 mutex_unlock(&cgroup_mutex);
2766 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2768 static ssize_t cgroup_tasks_write(struct kernfs_open_file *of,
2769 char *buf, size_t nbytes, loff_t off)
2771 return __cgroup_procs_write(of, buf, nbytes, off, false);
2774 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
2775 char *buf, size_t nbytes, loff_t off)
2777 return __cgroup_procs_write(of, buf, nbytes, off, true);
2780 static ssize_t cgroup_release_agent_write(struct kernfs_open_file *of,
2781 char *buf, size_t nbytes, loff_t off)
2783 struct cgroup *cgrp;
2785 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
2787 cgrp = cgroup_kn_lock_live(of->kn);
2790 spin_lock(&release_agent_path_lock);
2791 strlcpy(cgrp->root->release_agent_path, strstrip(buf),
2792 sizeof(cgrp->root->release_agent_path));
2793 spin_unlock(&release_agent_path_lock);
2794 cgroup_kn_unlock(of->kn);
2798 static int cgroup_release_agent_show(struct seq_file *seq, void *v)
2800 struct cgroup *cgrp = seq_css(seq)->cgroup;
2802 spin_lock(&release_agent_path_lock);
2803 seq_puts(seq, cgrp->root->release_agent_path);
2804 spin_unlock(&release_agent_path_lock);
2805 seq_putc(seq, '\n');
2809 static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
2811 seq_puts(seq, "0\n");
2815 static void cgroup_print_ss_mask(struct seq_file *seq, unsigned long ss_mask)
2817 struct cgroup_subsys *ss;
2818 bool printed = false;
2821 for_each_subsys_which(ss, ssid, &ss_mask) {
2824 seq_printf(seq, "%s", ss->name);
2828 seq_putc(seq, '\n');
2831 /* show controllers which are currently attached to the default hierarchy */
2832 static int cgroup_root_controllers_show(struct seq_file *seq, void *v)
2834 struct cgroup *cgrp = seq_css(seq)->cgroup;
2836 cgroup_print_ss_mask(seq, cgrp->root->subsys_mask &
2837 ~cgrp_dfl_root_inhibit_ss_mask);
2841 /* show controllers which are enabled from the parent */
2842 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2844 struct cgroup *cgrp = seq_css(seq)->cgroup;
2846 cgroup_print_ss_mask(seq, cgroup_parent(cgrp)->subtree_control);
2850 /* show controllers which are enabled for a given cgroup's children */
2851 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2853 struct cgroup *cgrp = seq_css(seq)->cgroup;
2855 cgroup_print_ss_mask(seq, cgrp->subtree_control);
2860 * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2861 * @cgrp: root of the subtree to update csses for
2863 * @cgrp's child_subsys_mask has changed and its subtree's (self excluded)
2864 * css associations need to be updated accordingly. This function looks up
2865 * all css_sets which are attached to the subtree, creates the matching
2866 * updated css_sets and migrates the tasks to the new ones.
2868 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2870 LIST_HEAD(preloaded_csets);
2871 struct cgroup_taskset tset = CGROUP_TASKSET_INIT(tset);
2872 struct cgroup_subsys_state *css;
2873 struct css_set *src_cset;
2876 lockdep_assert_held(&cgroup_mutex);
2878 percpu_down_write(&cgroup_threadgroup_rwsem);
2880 /* look up all csses currently attached to @cgrp's subtree */
2881 spin_lock_bh(&css_set_lock);
2882 css_for_each_descendant_pre(css, cgroup_css(cgrp, NULL)) {
2883 struct cgrp_cset_link *link;
2885 /* self is not affected by child_subsys_mask change */
2886 if (css->cgroup == cgrp)
2889 list_for_each_entry(link, &css->cgroup->cset_links, cset_link)
2890 cgroup_migrate_add_src(link->cset, cgrp,
2893 spin_unlock_bh(&css_set_lock);
2895 /* NULL dst indicates self on default hierarchy */
2896 ret = cgroup_migrate_prepare_dst(NULL, &preloaded_csets);
2900 spin_lock_bh(&css_set_lock);
2901 list_for_each_entry(src_cset, &preloaded_csets, mg_preload_node) {
2902 struct task_struct *task, *ntask;
2904 /* src_csets precede dst_csets, break on the first dst_cset */
2905 if (!src_cset->mg_src_cgrp)
2908 /* all tasks in src_csets need to be migrated */
2909 list_for_each_entry_safe(task, ntask, &src_cset->tasks, cg_list)
2910 cgroup_taskset_add(task, &tset);
2912 spin_unlock_bh(&css_set_lock);
2914 ret = cgroup_taskset_migrate(&tset, cgrp);
2916 cgroup_migrate_finish(&preloaded_csets);
2917 percpu_up_write(&cgroup_threadgroup_rwsem);
2921 /* change the enabled child controllers for a cgroup in the default hierarchy */
2922 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
2923 char *buf, size_t nbytes,
2926 unsigned long enable = 0, disable = 0;
2927 unsigned long css_enable, css_disable, old_sc, new_sc, old_ss, new_ss;
2928 struct cgroup *cgrp, *child;
2929 struct cgroup_subsys *ss;
2934 * Parse input - space separated list of subsystem names prefixed
2935 * with either + or -.
2937 buf = strstrip(buf);
2938 while ((tok = strsep(&buf, " "))) {
2939 unsigned long tmp_ss_mask = ~cgrp_dfl_root_inhibit_ss_mask;
2943 for_each_subsys_which(ss, ssid, &tmp_ss_mask) {
2944 if (!cgroup_ssid_enabled(ssid) ||
2945 strcmp(tok + 1, ss->name))
2949 enable |= 1 << ssid;
2950 disable &= ~(1 << ssid);
2951 } else if (*tok == '-') {
2952 disable |= 1 << ssid;
2953 enable &= ~(1 << ssid);
2959 if (ssid == CGROUP_SUBSYS_COUNT)
2963 cgrp = cgroup_kn_lock_live(of->kn);
2967 for_each_subsys(ss, ssid) {
2968 if (enable & (1 << ssid)) {
2969 if (cgrp->subtree_control & (1 << ssid)) {
2970 enable &= ~(1 << ssid);
2974 /* unavailable or not enabled on the parent? */
2975 if (!(cgrp_dfl_root.subsys_mask & (1 << ssid)) ||
2976 (cgroup_parent(cgrp) &&
2977 !(cgroup_parent(cgrp)->subtree_control & (1 << ssid)))) {
2981 } else if (disable & (1 << ssid)) {
2982 if (!(cgrp->subtree_control & (1 << ssid))) {
2983 disable &= ~(1 << ssid);
2987 /* a child has it enabled? */
2988 cgroup_for_each_live_child(child, cgrp) {
2989 if (child->subtree_control & (1 << ssid)) {
2997 if (!enable && !disable) {
3003 * Except for the root, subtree_control must be zero for a cgroup
3004 * with tasks so that child cgroups don't compete against tasks.
3006 if (enable && cgroup_parent(cgrp) && !list_empty(&cgrp->cset_links)) {
3012 * Update subsys masks and calculate what needs to be done. More
3013 * subsystems than specified may need to be enabled or disabled
3014 * depending on subsystem dependencies.
3016 old_sc = cgrp->subtree_control;
3017 old_ss = cgrp->child_subsys_mask;
3018 new_sc = (old_sc | enable) & ~disable;
3019 new_ss = cgroup_calc_child_subsys_mask(cgrp, new_sc);
3021 css_enable = ~old_ss & new_ss;
3022 css_disable = old_ss & ~new_ss;
3023 enable |= css_enable;
3024 disable |= css_disable;
3027 * Because css offlining is asynchronous, userland might try to
3028 * re-enable the same controller while the previous instance is
3029 * still around. In such cases, wait till it's gone using
3032 for_each_subsys_which(ss, ssid, &css_enable) {
3033 cgroup_for_each_live_child(child, cgrp) {
3036 if (!cgroup_css(child, ss))
3040 prepare_to_wait(&child->offline_waitq, &wait,
3041 TASK_UNINTERRUPTIBLE);
3042 cgroup_kn_unlock(of->kn);
3044 finish_wait(&child->offline_waitq, &wait);
3047 return restart_syscall();
3051 cgrp->subtree_control = new_sc;
3052 cgrp->child_subsys_mask = new_ss;
3055 * Create new csses or make the existing ones visible. A css is
3056 * created invisible if it's being implicitly enabled through
3057 * dependency. An invisible css is made visible when the userland
3058 * explicitly enables it.
3060 for_each_subsys(ss, ssid) {
3061 if (!(enable & (1 << ssid)))
3064 cgroup_for_each_live_child(child, cgrp) {
3065 if (css_enable & (1 << ssid))
3066 ret = create_css(child, ss,
3067 cgrp->subtree_control & (1 << ssid));
3069 ret = css_populate_dir(cgroup_css(child, ss),
3077 * At this point, cgroup_e_css() results reflect the new csses
3078 * making the following cgroup_update_dfl_csses() properly update
3079 * css associations of all tasks in the subtree.
3081 ret = cgroup_update_dfl_csses(cgrp);
3086 * All tasks are migrated out of disabled csses. Kill or hide
3087 * them. A css is hidden when the userland requests it to be
3088 * disabled while other subsystems are still depending on it. The
3089 * css must not actively control resources and be in the vanilla
3090 * state if it's made visible again later. Controllers which may
3091 * be depended upon should provide ->css_reset() for this purpose.
3093 for_each_subsys(ss, ssid) {
3094 if (!(disable & (1 << ssid)))
3097 cgroup_for_each_live_child(child, cgrp) {
3098 struct cgroup_subsys_state *css = cgroup_css(child, ss);
3100 if (css_disable & (1 << ssid)) {
3103 css_clear_dir(css, NULL);
3111 * The effective csses of all the descendants (excluding @cgrp) may
3112 * have changed. Subsystems can optionally subscribe to this event
3113 * by implementing ->css_e_css_changed() which is invoked if any of
3114 * the effective csses seen from the css's cgroup may have changed.
3116 for_each_subsys(ss, ssid) {
3117 struct cgroup_subsys_state *this_css = cgroup_css(cgrp, ss);
3118 struct cgroup_subsys_state *css;
3120 if (!ss->css_e_css_changed || !this_css)
3123 css_for_each_descendant_pre(css, this_css)
3124 if (css != this_css)
3125 ss->css_e_css_changed(css);
3128 kernfs_activate(cgrp->kn);
3131 cgroup_kn_unlock(of->kn);
3132 return ret ?: nbytes;
3135 cgrp->subtree_control = old_sc;
3136 cgrp->child_subsys_mask = old_ss;
3138 for_each_subsys(ss, ssid) {
3139 if (!(enable & (1 << ssid)))
3142 cgroup_for_each_live_child(child, cgrp) {
3143 struct cgroup_subsys_state *css = cgroup_css(child, ss);
3148 if (css_enable & (1 << ssid))
3151 css_clear_dir(css, NULL);
3157 static int cgroup_events_show(struct seq_file *seq, void *v)
3159 seq_printf(seq, "populated %d\n",
3160 cgroup_is_populated(seq_css(seq)->cgroup));
3164 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
3165 size_t nbytes, loff_t off)
3167 struct cgroup *cgrp = of->kn->parent->priv;
3168 struct cftype *cft = of->kn->priv;
3169 struct cgroup_subsys_state *css;
3173 return cft->write(of, buf, nbytes, off);
3176 * kernfs guarantees that a file isn't deleted with operations in
3177 * flight, which means that the matching css is and stays alive and
3178 * doesn't need to be pinned. The RCU locking is not necessary
3179 * either. It's just for the convenience of using cgroup_css().
3182 css = cgroup_css(cgrp, cft->ss);
3185 if (cft->write_u64) {
3186 unsigned long long v;
3187 ret = kstrtoull(buf, 0, &v);
3189 ret = cft->write_u64(css, cft, v);
3190 } else if (cft->write_s64) {
3192 ret = kstrtoll(buf, 0, &v);
3194 ret = cft->write_s64(css, cft, v);
3199 return ret ?: nbytes;
3202 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
3204 return seq_cft(seq)->seq_start(seq, ppos);
3207 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
3209 return seq_cft(seq)->seq_next(seq, v, ppos);
3212 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
3214 seq_cft(seq)->seq_stop(seq, v);
3217 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
3219 struct cftype *cft = seq_cft(m);
3220 struct cgroup_subsys_state *css = seq_css(m);
3223 return cft->seq_show(m, arg);
3226 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
3227 else if (cft->read_s64)
3228 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
3234 static struct kernfs_ops cgroup_kf_single_ops = {
3235 .atomic_write_len = PAGE_SIZE,
3236 .write = cgroup_file_write,
3237 .seq_show = cgroup_seqfile_show,
3240 static struct kernfs_ops cgroup_kf_ops = {
3241 .atomic_write_len = PAGE_SIZE,
3242 .write = cgroup_file_write,
3243 .seq_start = cgroup_seqfile_start,
3244 .seq_next = cgroup_seqfile_next,
3245 .seq_stop = cgroup_seqfile_stop,
3246 .seq_show = cgroup_seqfile_show,
3250 * cgroup_rename - Only allow simple rename of directories in place.
3252 static int cgroup_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
3253 const char *new_name_str)
3255 struct cgroup *cgrp = kn->priv;
3258 if (kernfs_type(kn) != KERNFS_DIR)
3260 if (kn->parent != new_parent)
3264 * This isn't a proper migration and its usefulness is very
3265 * limited. Disallow on the default hierarchy.
3267 if (cgroup_on_dfl(cgrp))
3271 * We're gonna grab cgroup_mutex which nests outside kernfs
3272 * active_ref. kernfs_rename() doesn't require active_ref
3273 * protection. Break them before grabbing cgroup_mutex.
3275 kernfs_break_active_protection(new_parent);
3276 kernfs_break_active_protection(kn);
3278 mutex_lock(&cgroup_mutex);
3280 ret = kernfs_rename(kn, new_parent, new_name_str);
3282 mutex_unlock(&cgroup_mutex);
3284 kernfs_unbreak_active_protection(kn);
3285 kernfs_unbreak_active_protection(new_parent);
3289 /* set uid and gid of cgroup dirs and files to that of the creator */
3290 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
3292 struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
3293 .ia_uid = current_fsuid(),
3294 .ia_gid = current_fsgid(), };
3296 if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
3297 gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
3300 return kernfs_setattr(kn, &iattr);
3303 static int cgroup_add_file(struct cgroup_subsys_state *css, struct cgroup *cgrp,
3306 char name[CGROUP_FILE_NAME_MAX];
3307 struct kernfs_node *kn;
3308 struct lock_class_key *key = NULL;
3311 #ifdef CONFIG_DEBUG_LOCK_ALLOC
3312 key = &cft->lockdep_key;
3314 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
3315 cgroup_file_mode(cft), 0, cft->kf_ops, cft,
3320 ret = cgroup_kn_set_ugid(kn);
3326 if (cft->file_offset) {
3327 struct cgroup_file *cfile = (void *)css + cft->file_offset;
3329 spin_lock_irq(&cgroup_file_kn_lock);
3331 spin_unlock_irq(&cgroup_file_kn_lock);
3338 * cgroup_addrm_files - add or remove files to a cgroup directory
3339 * @css: the target css
3340 * @cgrp: the target cgroup (usually css->cgroup)
3341 * @cfts: array of cftypes to be added
3342 * @is_add: whether to add or remove
3344 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
3345 * For removals, this function never fails.
3347 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
3348 struct cgroup *cgrp, struct cftype cfts[],
3351 struct cftype *cft, *cft_end = NULL;
3354 lockdep_assert_held(&cgroup_mutex);
3357 for (cft = cfts; cft != cft_end && cft->name[0] != '\0'; cft++) {
3358 /* does cft->flags tell us to skip this file on @cgrp? */
3359 if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
3361 if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
3363 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
3365 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
3369 ret = cgroup_add_file(css, cgrp, cft);
3371 pr_warn("%s: failed to add %s, err=%d\n",
3372 __func__, cft->name, ret);
3378 cgroup_rm_file(cgrp, cft);
3384 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
3387 struct cgroup_subsys *ss = cfts[0].ss;
3388 struct cgroup *root = &ss->root->cgrp;
3389 struct cgroup_subsys_state *css;
3392 lockdep_assert_held(&cgroup_mutex);
3394 /* add/rm files for all cgroups created before */
3395 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
3396 struct cgroup *cgrp = css->cgroup;
3398 if (cgroup_is_dead(cgrp))
3401 ret = cgroup_addrm_files(css, cgrp, cfts, is_add);
3407 kernfs_activate(root->kn);
3411 static void cgroup_exit_cftypes(struct cftype *cfts)
3415 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3416 /* free copy for custom atomic_write_len, see init_cftypes() */
3417 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
3422 /* revert flags set by cgroup core while adding @cfts */
3423 cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL);
3427 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3431 for (cft = cfts; cft->name[0] != '\0'; cft++) {
3432 struct kernfs_ops *kf_ops;
3434 WARN_ON(cft->ss || cft->kf_ops);
3437 kf_ops = &cgroup_kf_ops;
3439 kf_ops = &cgroup_kf_single_ops;
3442 * Ugh... if @cft wants a custom max_write_len, we need to
3443 * make a copy of kf_ops to set its atomic_write_len.
3445 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
3446 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
3448 cgroup_exit_cftypes(cfts);
3451 kf_ops->atomic_write_len = cft->max_write_len;
3454 cft->kf_ops = kf_ops;
3461 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
3463 lockdep_assert_held(&cgroup_mutex);
3465 if (!cfts || !cfts[0].ss)
3468 list_del(&cfts->node);
3469 cgroup_apply_cftypes(cfts, false);
3470 cgroup_exit_cftypes(cfts);
3475 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
3476 * @cfts: zero-length name terminated array of cftypes
3478 * Unregister @cfts. Files described by @cfts are removed from all
3479 * existing cgroups and all future cgroups won't have them either. This
3480 * function can be called anytime whether @cfts' subsys is attached or not.
3482 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
3485 int cgroup_rm_cftypes(struct cftype *cfts)
3489 mutex_lock(&cgroup_mutex);
3490 ret = cgroup_rm_cftypes_locked(cfts);
3491 mutex_unlock(&cgroup_mutex);
3496 * cgroup_add_cftypes - add an array of cftypes to a subsystem
3497 * @ss: target cgroup subsystem
3498 * @cfts: zero-length name terminated array of cftypes
3500 * Register @cfts to @ss. Files described by @cfts are created for all
3501 * existing cgroups to which @ss is attached and all future cgroups will
3502 * have them too. This function can be called anytime whether @ss is
3505 * Returns 0 on successful registration, -errno on failure. Note that this
3506 * function currently returns 0 as long as @cfts registration is successful
3507 * even if some file creation attempts on existing cgroups fail.
3509 static int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3513 if (!cgroup_ssid_enabled(ss->id))
3516 if (!cfts || cfts[0].name[0] == '\0')
3519 ret = cgroup_init_cftypes(ss, cfts);
3523 mutex_lock(&cgroup_mutex);
3525 list_add_tail(&cfts->node, &ss->cfts);
3526 ret = cgroup_apply_cftypes(cfts, true);
3528 cgroup_rm_cftypes_locked(cfts);
3530 mutex_unlock(&cgroup_mutex);
3535 * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
3536 * @ss: target cgroup subsystem
3537 * @cfts: zero-length name terminated array of cftypes
3539 * Similar to cgroup_add_cftypes() but the added files are only used for
3540 * the default hierarchy.
3542 int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3546 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3547 cft->flags |= __CFTYPE_ONLY_ON_DFL;
3548 return cgroup_add_cftypes(ss, cfts);
3552 * cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies
3553 * @ss: target cgroup subsystem
3554 * @cfts: zero-length name terminated array of cftypes
3556 * Similar to cgroup_add_cftypes() but the added files are only used for
3557 * the legacy hierarchies.
3559 int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3563 for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3564 cft->flags |= __CFTYPE_NOT_ON_DFL;
3565 return cgroup_add_cftypes(ss, cfts);
3569 * cgroup_file_notify - generate a file modified event for a cgroup_file
3570 * @cfile: target cgroup_file
3572 * @cfile must have been obtained by setting cftype->file_offset.
3574 void cgroup_file_notify(struct cgroup_file *cfile)
3576 unsigned long flags;
3578 spin_lock_irqsave(&cgroup_file_kn_lock, flags);
3580 kernfs_notify(cfile->kn);
3581 spin_unlock_irqrestore(&cgroup_file_kn_lock, flags);
3585 * cgroup_task_count - count the number of tasks in a cgroup.
3586 * @cgrp: the cgroup in question
3588 * Return the number of tasks in the cgroup.
3590 static int cgroup_task_count(const struct cgroup *cgrp)
3593 struct cgrp_cset_link *link;
3595 spin_lock_bh(&css_set_lock);
3596 list_for_each_entry(link, &cgrp->cset_links, cset_link)
3597 count += atomic_read(&link->cset->refcount);
3598 spin_unlock_bh(&css_set_lock);
3603 * css_next_child - find the next child of a given css
3604 * @pos: the current position (%NULL to initiate traversal)
3605 * @parent: css whose children to walk
3607 * This function returns the next child of @parent and should be called
3608 * under either cgroup_mutex or RCU read lock. The only requirement is
3609 * that @parent and @pos are accessible. The next sibling is guaranteed to
3610 * be returned regardless of their states.
3612 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3613 * css which finished ->css_online() is guaranteed to be visible in the
3614 * future iterations and will stay visible until the last reference is put.
3615 * A css which hasn't finished ->css_online() or already finished
3616 * ->css_offline() may show up during traversal. It's each subsystem's
3617 * responsibility to synchronize against on/offlining.
3619 struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
3620 struct cgroup_subsys_state *parent)
3622 struct cgroup_subsys_state *next;
3624 cgroup_assert_mutex_or_rcu_locked();
3627 * @pos could already have been unlinked from the sibling list.
3628 * Once a cgroup is removed, its ->sibling.next is no longer
3629 * updated when its next sibling changes. CSS_RELEASED is set when
3630 * @pos is taken off list, at which time its next pointer is valid,
3631 * and, as releases are serialized, the one pointed to by the next
3632 * pointer is guaranteed to not have started release yet. This
3633 * implies that if we observe !CSS_RELEASED on @pos in this RCU
3634 * critical section, the one pointed to by its next pointer is
3635 * guaranteed to not have finished its RCU grace period even if we
3636 * have dropped rcu_read_lock() inbetween iterations.
3638 * If @pos has CSS_RELEASED set, its next pointer can't be
3639 * dereferenced; however, as each css is given a monotonically
3640 * increasing unique serial number and always appended to the
3641 * sibling list, the next one can be found by walking the parent's
3642 * children until the first css with higher serial number than
3643 * @pos's. While this path can be slower, it happens iff iteration
3644 * races against release and the race window is very small.
3647 next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
3648 } else if (likely(!(pos->flags & CSS_RELEASED))) {
3649 next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
3651 list_for_each_entry_rcu(next, &parent->children, sibling)
3652 if (next->serial_nr > pos->serial_nr)
3657 * @next, if not pointing to the head, can be dereferenced and is
3660 if (&next->sibling != &parent->children)
3666 * css_next_descendant_pre - find the next descendant for pre-order walk
3667 * @pos: the current position (%NULL to initiate traversal)
3668 * @root: css whose descendants to walk
3670 * To be used by css_for_each_descendant_pre(). Find the next descendant
3671 * to visit for pre-order traversal of @root's descendants. @root is
3672 * included in the iteration and the first node to be visited.
3674 * While this function requires cgroup_mutex or RCU read locking, it
3675 * doesn't require the whole traversal to be contained in a single critical
3676 * section. This function will return the correct next descendant as long
3677 * as both @pos and @root are accessible and @pos is a descendant of @root.
3679 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3680 * css which finished ->css_online() is guaranteed to be visible in the
3681 * future iterations and will stay visible until the last reference is put.
3682 * A css which hasn't finished ->css_online() or already finished
3683 * ->css_offline() may show up during traversal. It's each subsystem's
3684 * responsibility to synchronize against on/offlining.
3686 struct cgroup_subsys_state *
3687 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3688 struct cgroup_subsys_state *root)
3690 struct cgroup_subsys_state *next;
3692 cgroup_assert_mutex_or_rcu_locked();
3694 /* if first iteration, visit @root */
3698 /* visit the first child if exists */
3699 next = css_next_child(NULL, pos);
3703 /* no child, visit my or the closest ancestor's next sibling */
3704 while (pos != root) {
3705 next = css_next_child(pos, pos->parent);
3715 * css_rightmost_descendant - return the rightmost descendant of a css
3716 * @pos: css of interest
3718 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3719 * is returned. This can be used during pre-order traversal to skip
3722 * While this function requires cgroup_mutex or RCU read locking, it
3723 * doesn't require the whole traversal to be contained in a single critical
3724 * section. This function will return the correct rightmost descendant as
3725 * long as @pos is accessible.
3727 struct cgroup_subsys_state *
3728 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3730 struct cgroup_subsys_state *last, *tmp;
3732 cgroup_assert_mutex_or_rcu_locked();
3736 /* ->prev isn't RCU safe, walk ->next till the end */
3738 css_for_each_child(tmp, last)
3745 static struct cgroup_subsys_state *
3746 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3748 struct cgroup_subsys_state *last;
3752 pos = css_next_child(NULL, pos);
3759 * css_next_descendant_post - find the next descendant for post-order walk
3760 * @pos: the current position (%NULL to initiate traversal)
3761 * @root: css whose descendants to walk
3763 * To be used by css_for_each_descendant_post(). Find the next descendant
3764 * to visit for post-order traversal of @root's descendants. @root is
3765 * included in the iteration and the last node to be visited.
3767 * While this function requires cgroup_mutex or RCU read locking, it
3768 * doesn't require the whole traversal to be contained in a single critical
3769 * section. This function will return the correct next descendant as long
3770 * as both @pos and @cgroup are accessible and @pos is a descendant of
3773 * If a subsystem synchronizes ->css_online() and the start of iteration, a
3774 * css which finished ->css_online() is guaranteed to be visible in the
3775 * future iterations and will stay visible until the last reference is put.
3776 * A css which hasn't finished ->css_online() or already finished
3777 * ->css_offline() may show up during traversal. It's each subsystem's
3778 * responsibility to synchronize against on/offlining.
3780 struct cgroup_subsys_state *
3781 css_next_descendant_post(struct cgroup_subsys_state *pos,
3782 struct cgroup_subsys_state *root)
3784 struct cgroup_subsys_state *next;
3786 cgroup_assert_mutex_or_rcu_locked();
3788 /* if first iteration, visit leftmost descendant which may be @root */
3790 return css_leftmost_descendant(root);
3792 /* if we visited @root, we're done */
3796 /* if there's an unvisited sibling, visit its leftmost descendant */
3797 next = css_next_child(pos, pos->parent);
3799 return css_leftmost_descendant(next);
3801 /* no sibling left, visit parent */
3806 * css_has_online_children - does a css have online children
3807 * @css: the target css
3809 * Returns %true if @css has any online children; otherwise, %false. This
3810 * function can be called from any context but the caller is responsible
3811 * for synchronizing against on/offlining as necessary.
3813 bool css_has_online_children(struct cgroup_subsys_state *css)
3815 struct cgroup_subsys_state *child;
3819 css_for_each_child(child, css) {
3820 if (child->flags & CSS_ONLINE) {
3830 * css_task_iter_advance_css_set - advance a task itererator to the next css_set
3831 * @it: the iterator to advance
3833 * Advance @it to the next css_set to walk.
3835 static void css_task_iter_advance_css_set(struct css_task_iter *it)
3837 struct list_head *l = it->cset_pos;
3838 struct cgrp_cset_link *link;
3839 struct css_set *cset;
3841 lockdep_assert_held(&css_set_lock);
3843 /* Advance to the next non-empty css_set */
3846 if (l == it->cset_head) {
3847 it->cset_pos = NULL;
3848 it->task_pos = NULL;
3853 cset = container_of(l, struct css_set,
3854 e_cset_node[it->ss->id]);
3856 link = list_entry(l, struct cgrp_cset_link, cset_link);
3859 } while (!css_set_populated(cset));
3863 if (!list_empty(&cset->tasks))
3864 it->task_pos = cset->tasks.next;
3866 it->task_pos = cset->mg_tasks.next;
3868 it->tasks_head = &cset->tasks;
3869 it->mg_tasks_head = &cset->mg_tasks;
3872 * We don't keep css_sets locked across iteration steps and thus
3873 * need to take steps to ensure that iteration can be resumed after
3874 * the lock is re-acquired. Iteration is performed at two levels -
3875 * css_sets and tasks in them.
3877 * Once created, a css_set never leaves its cgroup lists, so a
3878 * pinned css_set is guaranteed to stay put and we can resume
3879 * iteration afterwards.
3881 * Tasks may leave @cset across iteration steps. This is resolved
3882 * by registering each iterator with the css_set currently being
3883 * walked and making css_set_move_task() advance iterators whose
3884 * next task is leaving.
3887 list_del(&it->iters_node);
3888 put_css_set_locked(it->cur_cset);
3891 it->cur_cset = cset;
3892 list_add(&it->iters_node, &cset->task_iters);
3895 static void css_task_iter_advance(struct css_task_iter *it)
3897 struct list_head *l = it->task_pos;
3899 lockdep_assert_held(&css_set_lock);
3903 * Advance iterator to find next entry. cset->tasks is consumed
3904 * first and then ->mg_tasks. After ->mg_tasks, we move onto the
3909 if (l == it->tasks_head)
3910 l = it->mg_tasks_head->next;
3912 if (l == it->mg_tasks_head)
3913 css_task_iter_advance_css_set(it);
3919 * css_task_iter_start - initiate task iteration
3920 * @css: the css to walk tasks of
3921 * @it: the task iterator to use
3923 * Initiate iteration through the tasks of @css. The caller can call
3924 * css_task_iter_next() to walk through the tasks until the function
3925 * returns NULL. On completion of iteration, css_task_iter_end() must be
3928 void css_task_iter_start(struct cgroup_subsys_state *css,
3929 struct css_task_iter *it)
3931 /* no one should try to iterate before mounting cgroups */
3932 WARN_ON_ONCE(!use_task_css_set_links);
3934 memset(it, 0, sizeof(*it));
3936 spin_lock_bh(&css_set_lock);
3941 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
3943 it->cset_pos = &css->cgroup->cset_links;
3945 it->cset_head = it->cset_pos;
3947 css_task_iter_advance_css_set(it);
3949 spin_unlock_bh(&css_set_lock);
3953 * css_task_iter_next - return the next task for the iterator
3954 * @it: the task iterator being iterated
3956 * The "next" function for task iteration. @it should have been
3957 * initialized via css_task_iter_start(). Returns NULL when the iteration
3960 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3963 put_task_struct(it->cur_task);
3964 it->cur_task = NULL;
3967 spin_lock_bh(&css_set_lock);
3970 it->cur_task = list_entry(it->task_pos, struct task_struct,
3972 get_task_struct(it->cur_task);
3973 css_task_iter_advance(it);
3976 spin_unlock_bh(&css_set_lock);
3978 return it->cur_task;
3982 * css_task_iter_end - finish task iteration
3983 * @it: the task iterator to finish
3985 * Finish task iteration started by css_task_iter_start().
3987 void css_task_iter_end(struct css_task_iter *it)
3990 spin_lock_bh(&css_set_lock);
3991 list_del(&it->iters_node);
3992 put_css_set_locked(it->cur_cset);
3993 spin_unlock_bh(&css_set_lock);
3997 put_task_struct(it->cur_task);
4001 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
4002 * @to: cgroup to which the tasks will be moved
4003 * @from: cgroup in which the tasks currently reside
4005 * Locking rules between cgroup_post_fork() and the migration path
4006 * guarantee that, if a task is forking while being migrated, the new child
4007 * is guaranteed to be either visible in the source cgroup after the
4008 * parent's migration is complete or put into the target cgroup. No task
4009 * can slip out of migration through forking.
4011 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
4013 LIST_HEAD(preloaded_csets);
4014 struct cgrp_cset_link *link;
4015 struct css_task_iter it;
4016 struct task_struct *task;
4019 mutex_lock(&cgroup_mutex);
4021 /* all tasks in @from are being moved, all csets are source */
4022 spin_lock_bh(&css_set_lock);
4023 list_for_each_entry(link, &from->cset_links, cset_link)
4024 cgroup_migrate_add_src(link->cset, to, &preloaded_csets);
4025 spin_unlock_bh(&css_set_lock);
4027 ret = cgroup_migrate_prepare_dst(to, &preloaded_csets);
4032 * Migrate tasks one-by-one until @form is empty. This fails iff
4033 * ->can_attach() fails.
4036 css_task_iter_start(&from->self, &it);
4037 task = css_task_iter_next(&it);
4039 get_task_struct(task);
4040 css_task_iter_end(&it);
4043 ret = cgroup_migrate(task, false, to);
4044 put_task_struct(task);
4046 } while (task && !ret);
4048 cgroup_migrate_finish(&preloaded_csets);
4049 mutex_unlock(&cgroup_mutex);
4054 * Stuff for reading the 'tasks'/'procs' files.
4056 * Reading this file can return large amounts of data if a cgroup has
4057 * *lots* of attached tasks. So it may need several calls to read(),
4058 * but we cannot guarantee that the information we produce is correct
4059 * unless we produce it entirely atomically.
4063 /* which pidlist file are we talking about? */
4064 enum cgroup_filetype {
4070 * A pidlist is a list of pids that virtually represents the contents of one
4071 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
4072 * a pair (one each for procs, tasks) for each pid namespace that's relevant
4075 struct cgroup_pidlist {
4077 * used to find which pidlist is wanted. doesn't change as long as
4078 * this particular list stays in the list.
4080 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
4083 /* how many elements the above list has */
4085 /* each of these stored in a list by its cgroup */
4086 struct list_head links;
4087 /* pointer to the cgroup we belong to, for list removal purposes */
4088 struct cgroup *owner;
4089 /* for delayed destruction */
4090 struct delayed_work destroy_dwork;
4094 * The following two functions "fix" the issue where there are more pids
4095 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
4096 * TODO: replace with a kernel-wide solution to this problem
4098 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
4099 static void *pidlist_allocate(int count)
4101 if (PIDLIST_TOO_LARGE(count))
4102 return vmalloc(count * sizeof(pid_t));
4104 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
4107 static void pidlist_free(void *p)
4113 * Used to destroy all pidlists lingering waiting for destroy timer. None
4114 * should be left afterwards.
4116 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
4118 struct cgroup_pidlist *l, *tmp_l;
4120 mutex_lock(&cgrp->pidlist_mutex);
4121 list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
4122 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
4123 mutex_unlock(&cgrp->pidlist_mutex);
4125 flush_workqueue(cgroup_pidlist_destroy_wq);
4126 BUG_ON(!list_empty(&cgrp->pidlists));
4129 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
4131 struct delayed_work *dwork = to_delayed_work(work);
4132 struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
4134 struct cgroup_pidlist *tofree = NULL;
4136 mutex_lock(&l->owner->pidlist_mutex);
4139 * Destroy iff we didn't get queued again. The state won't change
4140 * as destroy_dwork can only be queued while locked.
4142 if (!delayed_work_pending(dwork)) {
4143 list_del(&l->links);
4144 pidlist_free(l->list);
4145 put_pid_ns(l->key.ns);
4149 mutex_unlock(&l->owner->pidlist_mutex);
4154 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
4155 * Returns the number of unique elements.
4157 static int pidlist_uniq(pid_t *list, int length)
4162 * we presume the 0th element is unique, so i starts at 1. trivial
4163 * edge cases first; no work needs to be done for either
4165 if (length == 0 || length == 1)
4167 /* src and dest walk down the list; dest counts unique elements */
4168 for (src = 1; src < length; src++) {
4169 /* find next unique element */
4170 while (list[src] == list[src-1]) {
4175 /* dest always points to where the next unique element goes */
4176 list[dest] = list[src];
4184 * The two pid files - task and cgroup.procs - guaranteed that the result
4185 * is sorted, which forced this whole pidlist fiasco. As pid order is
4186 * different per namespace, each namespace needs differently sorted list,
4187 * making it impossible to use, for example, single rbtree of member tasks
4188 * sorted by task pointer. As pidlists can be fairly large, allocating one
4189 * per open file is dangerous, so cgroup had to implement shared pool of
4190 * pidlists keyed by cgroup and namespace.
4192 * All this extra complexity was caused by the original implementation
4193 * committing to an entirely unnecessary property. In the long term, we
4194 * want to do away with it. Explicitly scramble sort order if on the
4195 * default hierarchy so that no such expectation exists in the new
4198 * Scrambling is done by swapping every two consecutive bits, which is
4199 * non-identity one-to-one mapping which disturbs sort order sufficiently.
4201 static pid_t pid_fry(pid_t pid)
4203 unsigned a = pid & 0x55555555;
4204 unsigned b = pid & 0xAAAAAAAA;
4206 return (a << 1) | (b >> 1);
4209 static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
4211 if (cgroup_on_dfl(cgrp))
4212 return pid_fry(pid);
4217 static int cmppid(const void *a, const void *b)
4219 return *(pid_t *)a - *(pid_t *)b;
4222 static int fried_cmppid(const void *a, const void *b)
4224 return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
4227 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
4228 enum cgroup_filetype type)
4230 struct cgroup_pidlist *l;
4231 /* don't need task_nsproxy() if we're looking at ourself */
4232 struct pid_namespace *ns = task_active_pid_ns(current);
4234 lockdep_assert_held(&cgrp->pidlist_mutex);
4236 list_for_each_entry(l, &cgrp->pidlists, links)
4237 if (l->key.type == type && l->key.ns == ns)
4243 * find the appropriate pidlist for our purpose (given procs vs tasks)
4244 * returns with the lock on that pidlist already held, and takes care
4245 * of the use count, or returns NULL with no locks held if we're out of
4248 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
4249 enum cgroup_filetype type)
4251 struct cgroup_pidlist *l;
4253 lockdep_assert_held(&cgrp->pidlist_mutex);
4255 l = cgroup_pidlist_find(cgrp, type);
4259 /* entry not found; create a new one */
4260 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
4264 INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
4266 /* don't need task_nsproxy() if we're looking at ourself */
4267 l->key.ns = get_pid_ns(task_active_pid_ns(current));
4269 list_add(&l->links, &cgrp->pidlists);
4274 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
4276 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
4277 struct cgroup_pidlist **lp)
4281 int pid, n = 0; /* used for populating the array */
4282 struct css_task_iter it;
4283 struct task_struct *tsk;
4284 struct cgroup_pidlist *l;
4286 lockdep_assert_held(&cgrp->pidlist_mutex);
4289 * If cgroup gets more users after we read count, we won't have
4290 * enough space - tough. This race is indistinguishable to the
4291 * caller from the case that the additional cgroup users didn't
4292 * show up until sometime later on.
4294 length = cgroup_task_count(cgrp);
4295 array = pidlist_allocate(length);
4298 /* now, populate the array */
4299 css_task_iter_start(&cgrp->self, &it);
4300 while ((tsk = css_task_iter_next(&it))) {
4301 if (unlikely(n == length))
4303 /* get tgid or pid for procs or tasks file respectively */
4304 if (type == CGROUP_FILE_PROCS)
4305 pid = task_tgid_vnr(tsk);
4307 pid = task_pid_vnr(tsk);
4308 if (pid > 0) /* make sure to only use valid results */
4311 css_task_iter_end(&it);
4313 /* now sort & (if procs) strip out duplicates */
4314 if (cgroup_on_dfl(cgrp))
4315 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
4317 sort(array, length, sizeof(pid_t), cmppid, NULL);
4318 if (type == CGROUP_FILE_PROCS)
4319 length = pidlist_uniq(array, length);
4321 l = cgroup_pidlist_find_create(cgrp, type);
4323 pidlist_free(array);
4327 /* store array, freeing old if necessary */
4328 pidlist_free(l->list);
4336 * cgroupstats_build - build and fill cgroupstats
4337 * @stats: cgroupstats to fill information into
4338 * @dentry: A dentry entry belonging to the cgroup for which stats have
4341 * Build and fill cgroupstats so that taskstats can export it to user
4344 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
4346 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
4347 struct cgroup *cgrp;
4348 struct css_task_iter it;
4349 struct task_struct *tsk;
4351 /* it should be kernfs_node belonging to cgroupfs and is a directory */
4352 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
4353 kernfs_type(kn) != KERNFS_DIR)
4356 mutex_lock(&cgroup_mutex);
4359 * We aren't being called from kernfs and there's no guarantee on
4360 * @kn->priv's validity. For this and css_tryget_online_from_dir(),
4361 * @kn->priv is RCU safe. Let's do the RCU dancing.
4364 cgrp = rcu_dereference(kn->priv);
4365 if (!cgrp || cgroup_is_dead(cgrp)) {
4367 mutex_unlock(&cgroup_mutex);
4372 css_task_iter_start(&cgrp->self, &it);
4373 while ((tsk = css_task_iter_next(&it))) {
4374 switch (tsk->state) {
4376 stats->nr_running++;
4378 case TASK_INTERRUPTIBLE:
4379 stats->nr_sleeping++;
4381 case TASK_UNINTERRUPTIBLE:
4382 stats->nr_uninterruptible++;
4385 stats->nr_stopped++;
4388 if (delayacct_is_task_waiting_on_io(tsk))
4389 stats->nr_io_wait++;
4393 css_task_iter_end(&it);
4395 mutex_unlock(&cgroup_mutex);
4401 * seq_file methods for the tasks/procs files. The seq_file position is the
4402 * next pid to display; the seq_file iterator is a pointer to the pid
4403 * in the cgroup->l->list array.
4406 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
4409 * Initially we receive a position value that corresponds to
4410 * one more than the last pid shown (or 0 on the first call or
4411 * after a seek to the start). Use a binary-search to find the
4412 * next pid to display, if any
4414 struct kernfs_open_file *of = s->private;
4415 struct cgroup *cgrp = seq_css(s)->cgroup;
4416 struct cgroup_pidlist *l;
4417 enum cgroup_filetype type = seq_cft(s)->private;
4418 int index = 0, pid = *pos;
4421 mutex_lock(&cgrp->pidlist_mutex);
4424 * !NULL @of->priv indicates that this isn't the first start()
4425 * after open. If the matching pidlist is around, we can use that.
4426 * Look for it. Note that @of->priv can't be used directly. It
4427 * could already have been destroyed.
4430 of->priv = cgroup_pidlist_find(cgrp, type);
4433 * Either this is the first start() after open or the matching
4434 * pidlist has been destroyed inbetween. Create a new one.
4437 ret = pidlist_array_load(cgrp, type,
4438 (struct cgroup_pidlist **)&of->priv);
4440 return ERR_PTR(ret);
4445 int end = l->length;
4447 while (index < end) {
4448 int mid = (index + end) / 2;
4449 if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
4452 } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
4458 /* If we're off the end of the array, we're done */
4459 if (index >= l->length)
4461 /* Update the abstract position to be the actual pid that we found */
4462 iter = l->list + index;
4463 *pos = cgroup_pid_fry(cgrp, *iter);
4467 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
4469 struct kernfs_open_file *of = s->private;
4470 struct cgroup_pidlist *l = of->priv;
4473 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
4474 CGROUP_PIDLIST_DESTROY_DELAY);
4475 mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
4478 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
4480 struct kernfs_open_file *of = s->private;
4481 struct cgroup_pidlist *l = of->priv;
4483 pid_t *end = l->list + l->length;
4485 * Advance to the next pid in the array. If this goes off the
4492 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
4497 static int cgroup_pidlist_show(struct seq_file *s, void *v)
4499 seq_printf(s, "%d\n", *(int *)v);
4504 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
4507 return notify_on_release(css->cgroup);
4510 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
4511 struct cftype *cft, u64 val)
4514 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
4516 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
4520 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
4523 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4526 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
4527 struct cftype *cft, u64 val)
4530 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4532 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4536 /* cgroup core interface files for the default hierarchy */
4537 static struct cftype cgroup_dfl_base_files[] = {
4539 .name = "cgroup.procs",
4540 .file_offset = offsetof(struct cgroup, procs_file),
4541 .seq_start = cgroup_pidlist_start,
4542 .seq_next = cgroup_pidlist_next,
4543 .seq_stop = cgroup_pidlist_stop,
4544 .seq_show = cgroup_pidlist_show,
4545 .private = CGROUP_FILE_PROCS,
4546 .write = cgroup_procs_write,
4549 .name = "cgroup.controllers",
4550 .flags = CFTYPE_ONLY_ON_ROOT,
4551 .seq_show = cgroup_root_controllers_show,
4554 .name = "cgroup.controllers",
4555 .flags = CFTYPE_NOT_ON_ROOT,
4556 .seq_show = cgroup_controllers_show,
4559 .name = "cgroup.subtree_control",
4560 .seq_show = cgroup_subtree_control_show,
4561 .write = cgroup_subtree_control_write,
4564 .name = "cgroup.events",
4565 .flags = CFTYPE_NOT_ON_ROOT,
4566 .file_offset = offsetof(struct cgroup, events_file),
4567 .seq_show = cgroup_events_show,
4572 /* cgroup core interface files for the legacy hierarchies */
4573 static struct cftype cgroup_legacy_base_files[] = {
4575 .name = "cgroup.procs",
4576 .seq_start = cgroup_pidlist_start,
4577 .seq_next = cgroup_pidlist_next,
4578 .seq_stop = cgroup_pidlist_stop,
4579 .seq_show = cgroup_pidlist_show,
4580 .private = CGROUP_FILE_PROCS,
4581 .write = cgroup_procs_write,
4584 .name = "cgroup.clone_children",
4585 .read_u64 = cgroup_clone_children_read,
4586 .write_u64 = cgroup_clone_children_write,
4589 .name = "cgroup.sane_behavior",
4590 .flags = CFTYPE_ONLY_ON_ROOT,
4591 .seq_show = cgroup_sane_behavior_show,
4595 .seq_start = cgroup_pidlist_start,
4596 .seq_next = cgroup_pidlist_next,
4597 .seq_stop = cgroup_pidlist_stop,
4598 .seq_show = cgroup_pidlist_show,
4599 .private = CGROUP_FILE_TASKS,
4600 .write = cgroup_tasks_write,
4603 .name = "notify_on_release",
4604 .read_u64 = cgroup_read_notify_on_release,
4605 .write_u64 = cgroup_write_notify_on_release,
4608 .name = "release_agent",
4609 .flags = CFTYPE_ONLY_ON_ROOT,
4610 .seq_show = cgroup_release_agent_show,
4611 .write = cgroup_release_agent_write,
4612 .max_write_len = PATH_MAX - 1,
4618 * css destruction is four-stage process.
4620 * 1. Destruction starts. Killing of the percpu_ref is initiated.
4621 * Implemented in kill_css().
4623 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4624 * and thus css_tryget_online() is guaranteed to fail, the css can be
4625 * offlined by invoking offline_css(). After offlining, the base ref is
4626 * put. Implemented in css_killed_work_fn().
4628 * 3. When the percpu_ref reaches zero, the only possible remaining
4629 * accessors are inside RCU read sections. css_release() schedules the
4632 * 4. After the grace period, the css can be freed. Implemented in
4633 * css_free_work_fn().
4635 * It is actually hairier because both step 2 and 4 require process context
4636 * and thus involve punting to css->destroy_work adding two additional
4637 * steps to the already complex sequence.
4639 static void css_free_work_fn(struct work_struct *work)
4641 struct cgroup_subsys_state *css =
4642 container_of(work, struct cgroup_subsys_state, destroy_work);
4643 struct cgroup_subsys *ss = css->ss;
4644 struct cgroup *cgrp = css->cgroup;
4646 percpu_ref_exit(&css->refcnt);
4653 css_put(css->parent);
4656 cgroup_idr_remove(&ss->css_idr, id);
4659 /* cgroup free path */
4660 atomic_dec(&cgrp->root->nr_cgrps);
4661 cgroup_pidlist_destroy_all(cgrp);
4662 cancel_work_sync(&cgrp->release_agent_work);
4664 if (cgroup_parent(cgrp)) {
4666 * We get a ref to the parent, and put the ref when
4667 * this cgroup is being freed, so it's guaranteed
4668 * that the parent won't be destroyed before its
4671 cgroup_put(cgroup_parent(cgrp));
4672 kernfs_put(cgrp->kn);
4676 * This is root cgroup's refcnt reaching zero,
4677 * which indicates that the root should be
4680 cgroup_destroy_root(cgrp->root);
4685 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4687 struct cgroup_subsys_state *css =
4688 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4690 INIT_WORK(&css->destroy_work, css_free_work_fn);
4691 queue_work(cgroup_destroy_wq, &css->destroy_work);
4694 static void css_release_work_fn(struct work_struct *work)
4696 struct cgroup_subsys_state *css =
4697 container_of(work, struct cgroup_subsys_state, destroy_work);
4698 struct cgroup_subsys *ss = css->ss;
4699 struct cgroup *cgrp = css->cgroup;
4701 mutex_lock(&cgroup_mutex);
4703 css->flags |= CSS_RELEASED;
4704 list_del_rcu(&css->sibling);
4707 /* css release path */
4708 cgroup_idr_replace(&ss->css_idr, NULL, css->id);
4709 if (ss->css_released)
4710 ss->css_released(css);
4712 /* cgroup release path */
4713 cgroup_idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4717 * There are two control paths which try to determine
4718 * cgroup from dentry without going through kernfs -
4719 * cgroupstats_build() and css_tryget_online_from_dir().
4720 * Those are supported by RCU protecting clearing of
4721 * cgrp->kn->priv backpointer.
4723 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv, NULL);
4726 mutex_unlock(&cgroup_mutex);
4728 call_rcu(&css->rcu_head, css_free_rcu_fn);
4731 static void css_release(struct percpu_ref *ref)
4733 struct cgroup_subsys_state *css =
4734 container_of(ref, struct cgroup_subsys_state, refcnt);
4736 INIT_WORK(&css->destroy_work, css_release_work_fn);
4737 queue_work(cgroup_destroy_wq, &css->destroy_work);
4740 static void init_and_link_css(struct cgroup_subsys_state *css,
4741 struct cgroup_subsys *ss, struct cgroup *cgrp)
4743 lockdep_assert_held(&cgroup_mutex);
4747 memset(css, 0, sizeof(*css));
4750 INIT_LIST_HEAD(&css->sibling);
4751 INIT_LIST_HEAD(&css->children);
4752 css->serial_nr = css_serial_nr_next++;
4754 if (cgroup_parent(cgrp)) {
4755 css->parent = cgroup_css(cgroup_parent(cgrp), ss);
4756 css_get(css->parent);
4759 BUG_ON(cgroup_css(cgrp, ss));
4762 /* invoke ->css_online() on a new CSS and mark it online if successful */
4763 static int online_css(struct cgroup_subsys_state *css)
4765 struct cgroup_subsys *ss = css->ss;
4768 lockdep_assert_held(&cgroup_mutex);
4771 ret = ss->css_online(css);
4773 css->flags |= CSS_ONLINE;
4774 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
4779 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4780 static void offline_css(struct cgroup_subsys_state *css)
4782 struct cgroup_subsys *ss = css->ss;
4784 lockdep_assert_held(&cgroup_mutex);
4786 if (!(css->flags & CSS_ONLINE))
4789 if (ss->css_offline)
4790 ss->css_offline(css);
4792 css->flags &= ~CSS_ONLINE;
4793 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
4795 wake_up_all(&css->cgroup->offline_waitq);
4799 * create_css - create a cgroup_subsys_state
4800 * @cgrp: the cgroup new css will be associated with
4801 * @ss: the subsys of new css
4802 * @visible: whether to create control knobs for the new css or not
4804 * Create a new css associated with @cgrp - @ss pair. On success, the new
4805 * css is online and installed in @cgrp with all interface files created if
4806 * @visible. Returns 0 on success, -errno on failure.
4808 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss,
4811 struct cgroup *parent = cgroup_parent(cgrp);
4812 struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
4813 struct cgroup_subsys_state *css;
4816 lockdep_assert_held(&cgroup_mutex);
4818 css = ss->css_alloc(parent_css);
4820 return PTR_ERR(css);
4822 init_and_link_css(css, ss, cgrp);
4824 err = percpu_ref_init(&css->refcnt, css_release, 0, GFP_KERNEL);
4828 err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_KERNEL);
4830 goto err_free_percpu_ref;
4834 err = css_populate_dir(css, NULL);
4839 /* @css is ready to be brought online now, make it visible */
4840 list_add_tail_rcu(&css->sibling, &parent_css->children);
4841 cgroup_idr_replace(&ss->css_idr, css, css->id);
4843 err = online_css(css);
4847 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4848 cgroup_parent(parent)) {
4849 pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4850 current->comm, current->pid, ss->name);
4851 if (!strcmp(ss->name, "memory"))
4852 pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
4853 ss->warned_broken_hierarchy = true;
4859 list_del_rcu(&css->sibling);
4860 css_clear_dir(css, NULL);
4862 cgroup_idr_remove(&ss->css_idr, css->id);
4863 err_free_percpu_ref:
4864 percpu_ref_exit(&css->refcnt);
4866 call_rcu(&css->rcu_head, css_free_rcu_fn);
4870 static int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
4873 struct cgroup *parent, *cgrp;
4874 struct cgroup_root *root;
4875 struct cgroup_subsys *ss;
4876 struct kernfs_node *kn;
4879 /* Do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable.
4881 if (strchr(name, '\n'))
4884 parent = cgroup_kn_lock_live(parent_kn);
4887 root = parent->root;
4889 /* allocate the cgroup and its ID, 0 is reserved for the root */
4890 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4896 ret = percpu_ref_init(&cgrp->self.refcnt, css_release, 0, GFP_KERNEL);
4901 * Temporarily set the pointer to NULL, so idr_find() won't return
4902 * a half-baked cgroup.
4904 cgrp->id = cgroup_idr_alloc(&root->cgroup_idr, NULL, 2, 0, GFP_KERNEL);
4907 goto out_cancel_ref;
4910 init_cgroup_housekeeping(cgrp);
4912 cgrp->self.parent = &parent->self;
4915 if (notify_on_release(parent))
4916 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4918 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4919 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4921 /* create the directory */
4922 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
4930 * This extra ref will be put in cgroup_free_fn() and guarantees
4931 * that @cgrp->kn is always accessible.
4935 cgrp->self.serial_nr = css_serial_nr_next++;
4937 /* allocation complete, commit to creation */
4938 list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
4939 atomic_inc(&root->nr_cgrps);
4943 * @cgrp is now fully operational. If something fails after this
4944 * point, it'll be released via the normal destruction path.
4946 cgroup_idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4948 ret = cgroup_kn_set_ugid(kn);
4952 ret = css_populate_dir(&cgrp->self, NULL);
4956 /* let's create and online css's */
4957 for_each_subsys(ss, ssid) {
4958 if (parent->child_subsys_mask & (1 << ssid)) {
4959 ret = create_css(cgrp, ss,
4960 parent->subtree_control & (1 << ssid));
4967 * On the default hierarchy, a child doesn't automatically inherit
4968 * subtree_control from the parent. Each is configured manually.
4970 if (!cgroup_on_dfl(cgrp)) {
4971 cgrp->subtree_control = parent->subtree_control;
4972 cgroup_refresh_child_subsys_mask(cgrp);
4975 kernfs_activate(kn);
4981 cgroup_idr_remove(&root->cgroup_idr, cgrp->id);
4983 percpu_ref_exit(&cgrp->self.refcnt);
4987 cgroup_kn_unlock(parent_kn);
4991 cgroup_destroy_locked(cgrp);
4996 * This is called when the refcnt of a css is confirmed to be killed.
4997 * css_tryget_online() is now guaranteed to fail. Tell the subsystem to
4998 * initate destruction and put the css ref from kill_css().
5000 static void css_killed_work_fn(struct work_struct *work)
5002 struct cgroup_subsys_state *css =
5003 container_of(work, struct cgroup_subsys_state, destroy_work);
5005 mutex_lock(&cgroup_mutex);
5007 mutex_unlock(&cgroup_mutex);
5012 /* css kill confirmation processing requires process context, bounce */
5013 static void css_killed_ref_fn(struct percpu_ref *ref)
5015 struct cgroup_subsys_state *css =
5016 container_of(ref, struct cgroup_subsys_state, refcnt);
5018 INIT_WORK(&css->destroy_work, css_killed_work_fn);
5019 queue_work(cgroup_destroy_wq, &css->destroy_work);
5023 * kill_css - destroy a css
5024 * @css: css to destroy
5026 * This function initiates destruction of @css by removing cgroup interface
5027 * files and putting its base reference. ->css_offline() will be invoked
5028 * asynchronously once css_tryget_online() is guaranteed to fail and when
5029 * the reference count reaches zero, @css will be released.
5031 static void kill_css(struct cgroup_subsys_state *css)
5033 lockdep_assert_held(&cgroup_mutex);
5036 * This must happen before css is disassociated with its cgroup.
5037 * See seq_css() for details.
5039 css_clear_dir(css, NULL);
5042 * Killing would put the base ref, but we need to keep it alive
5043 * until after ->css_offline().
5048 * cgroup core guarantees that, by the time ->css_offline() is
5049 * invoked, no new css reference will be given out via
5050 * css_tryget_online(). We can't simply call percpu_ref_kill() and
5051 * proceed to offlining css's because percpu_ref_kill() doesn't
5052 * guarantee that the ref is seen as killed on all CPUs on return.
5054 * Use percpu_ref_kill_and_confirm() to get notifications as each
5055 * css is confirmed to be seen as killed on all CPUs.
5057 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
5061 * cgroup_destroy_locked - the first stage of cgroup destruction
5062 * @cgrp: cgroup to be destroyed
5064 * css's make use of percpu refcnts whose killing latency shouldn't be
5065 * exposed to userland and are RCU protected. Also, cgroup core needs to
5066 * guarantee that css_tryget_online() won't succeed by the time
5067 * ->css_offline() is invoked. To satisfy all the requirements,
5068 * destruction is implemented in the following two steps.
5070 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
5071 * userland visible parts and start killing the percpu refcnts of
5072 * css's. Set up so that the next stage will be kicked off once all
5073 * the percpu refcnts are confirmed to be killed.
5075 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
5076 * rest of destruction. Once all cgroup references are gone, the
5077 * cgroup is RCU-freed.
5079 * This function implements s1. After this step, @cgrp is gone as far as
5080 * the userland is concerned and a new cgroup with the same name may be
5081 * created. As cgroup doesn't care about the names internally, this
5082 * doesn't cause any problem.
5084 static int cgroup_destroy_locked(struct cgroup *cgrp)
5085 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
5087 struct cgroup_subsys_state *css;
5090 lockdep_assert_held(&cgroup_mutex);
5093 * Only migration can raise populated from zero and we're already
5094 * holding cgroup_mutex.
5096 if (cgroup_is_populated(cgrp))
5100 * Make sure there's no live children. We can't test emptiness of
5101 * ->self.children as dead children linger on it while being
5102 * drained; otherwise, "rmdir parent/child parent" may fail.
5104 if (css_has_online_children(&cgrp->self))
5108 * Mark @cgrp dead. This prevents further task migration and child
5109 * creation by disabling cgroup_lock_live_group().
5111 cgrp->self.flags &= ~CSS_ONLINE;
5113 /* initiate massacre of all css's */
5114 for_each_css(css, ssid, cgrp)
5118 * Remove @cgrp directory along with the base files. @cgrp has an
5119 * extra ref on its kn.
5121 kernfs_remove(cgrp->kn);
5123 check_for_release(cgroup_parent(cgrp));
5125 /* put the base reference */
5126 percpu_ref_kill(&cgrp->self.refcnt);
5131 static int cgroup_rmdir(struct kernfs_node *kn)
5133 struct cgroup *cgrp;
5136 cgrp = cgroup_kn_lock_live(kn);
5140 ret = cgroup_destroy_locked(cgrp);
5142 cgroup_kn_unlock(kn);
5146 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
5147 .remount_fs = cgroup_remount,
5148 .show_options = cgroup_show_options,
5149 .mkdir = cgroup_mkdir,
5150 .rmdir = cgroup_rmdir,
5151 .rename = cgroup_rename,
5154 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
5156 struct cgroup_subsys_state *css;
5158 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
5160 mutex_lock(&cgroup_mutex);
5162 idr_init(&ss->css_idr);
5163 INIT_LIST_HEAD(&ss->cfts);
5165 /* Create the root cgroup state for this subsystem */
5166 ss->root = &cgrp_dfl_root;
5167 css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
5168 /* We don't handle early failures gracefully */
5169 BUG_ON(IS_ERR(css));
5170 init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
5173 * Root csses are never destroyed and we can't initialize
5174 * percpu_ref during early init. Disable refcnting.
5176 css->flags |= CSS_NO_REF;
5179 /* allocation can't be done safely during early init */
5182 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
5183 BUG_ON(css->id < 0);
5186 /* Update the init_css_set to contain a subsys
5187 * pointer to this state - since the subsystem is
5188 * newly registered, all tasks and hence the
5189 * init_css_set is in the subsystem's root cgroup. */
5190 init_css_set.subsys[ss->id] = css;
5192 have_fork_callback |= (bool)ss->fork << ss->id;
5193 have_exit_callback |= (bool)ss->exit << ss->id;
5194 have_free_callback |= (bool)ss->free << ss->id;
5195 have_canfork_callback |= (bool)ss->can_fork << ss->id;
5197 /* At system boot, before all subsystems have been
5198 * registered, no tasks have been forked, so we don't
5199 * need to invoke fork callbacks here. */
5200 BUG_ON(!list_empty(&init_task.tasks));
5202 BUG_ON(online_css(css));
5204 mutex_unlock(&cgroup_mutex);
5208 * cgroup_init_early - cgroup initialization at system boot
5210 * Initialize cgroups at system boot, and initialize any
5211 * subsystems that request early init.
5213 int __init cgroup_init_early(void)
5215 static struct cgroup_sb_opts __initdata opts;
5216 struct cgroup_subsys *ss;
5219 init_cgroup_root(&cgrp_dfl_root, &opts);
5220 cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
5222 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
5224 for_each_subsys(ss, i) {
5225 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
5226 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
5227 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
5229 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
5230 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
5233 ss->name = cgroup_subsys_name[i];
5234 if (!ss->legacy_name)
5235 ss->legacy_name = cgroup_subsys_name[i];
5238 cgroup_init_subsys(ss, true);
5243 static unsigned long cgroup_disable_mask __initdata;
5246 * cgroup_init - cgroup initialization
5248 * Register cgroup filesystem and /proc file, and initialize
5249 * any subsystems that didn't request early init.
5251 int __init cgroup_init(void)
5253 struct cgroup_subsys *ss;
5257 BUG_ON(percpu_init_rwsem(&cgroup_threadgroup_rwsem));
5258 BUG_ON(cgroup_init_cftypes(NULL, cgroup_dfl_base_files));
5259 BUG_ON(cgroup_init_cftypes(NULL, cgroup_legacy_base_files));
5261 mutex_lock(&cgroup_mutex);
5263 /* Add init_css_set to the hash table */
5264 key = css_set_hash(init_css_set.subsys);
5265 hash_add(css_set_table, &init_css_set.hlist, key);
5267 BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
5269 mutex_unlock(&cgroup_mutex);
5271 for_each_subsys(ss, ssid) {
5272 if (ss->early_init) {
5273 struct cgroup_subsys_state *css =
5274 init_css_set.subsys[ss->id];
5276 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
5278 BUG_ON(css->id < 0);
5280 cgroup_init_subsys(ss, false);
5283 list_add_tail(&init_css_set.e_cset_node[ssid],
5284 &cgrp_dfl_root.cgrp.e_csets[ssid]);
5287 * Setting dfl_root subsys_mask needs to consider the
5288 * disabled flag and cftype registration needs kmalloc,
5289 * both of which aren't available during early_init.
5291 if (cgroup_disable_mask & (1 << ssid)) {
5292 static_branch_disable(cgroup_subsys_enabled_key[ssid]);
5293 printk(KERN_INFO "Disabling %s control group subsystem\n",
5298 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
5300 if (!ss->dfl_cftypes)
5301 cgrp_dfl_root_inhibit_ss_mask |= 1 << ss->id;
5303 if (ss->dfl_cftypes == ss->legacy_cftypes) {
5304 WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes));
5306 WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes));
5307 WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes));
5311 ss->bind(init_css_set.subsys[ssid]);
5314 WARN_ON(sysfs_create_mount_point(fs_kobj, "cgroup"));
5315 WARN_ON(register_filesystem(&cgroup_fs_type));
5316 WARN_ON(register_filesystem(&cgroup2_fs_type));
5317 WARN_ON(!proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations));
5322 static int __init cgroup_wq_init(void)
5325 * There isn't much point in executing destruction path in
5326 * parallel. Good chunk is serialized with cgroup_mutex anyway.
5327 * Use 1 for @max_active.
5329 * We would prefer to do this in cgroup_init() above, but that
5330 * is called before init_workqueues(): so leave this until after.
5332 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
5333 BUG_ON(!cgroup_destroy_wq);
5336 * Used to destroy pidlists and separate to serve as flush domain.
5337 * Cap @max_active to 1 too.
5339 cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
5341 BUG_ON(!cgroup_pidlist_destroy_wq);
5345 core_initcall(cgroup_wq_init);
5348 * proc_cgroup_show()
5349 * - Print task's cgroup paths into seq_file, one line for each hierarchy
5350 * - Used for /proc/<pid>/cgroup.
5352 int proc_cgroup_show(struct seq_file *m, struct pid_namespace *ns,
5353 struct pid *pid, struct task_struct *tsk)
5357 struct cgroup_root *root;
5360 buf = kmalloc(PATH_MAX, GFP_KERNEL);
5364 mutex_lock(&cgroup_mutex);
5365 spin_lock_bh(&css_set_lock);
5367 for_each_root(root) {
5368 struct cgroup_subsys *ss;
5369 struct cgroup *cgrp;
5370 int ssid, count = 0;
5372 if (root == &cgrp_dfl_root && !cgrp_dfl_root_visible)
5375 seq_printf(m, "%d:", root->hierarchy_id);
5376 if (root != &cgrp_dfl_root)
5377 for_each_subsys(ss, ssid)
5378 if (root->subsys_mask & (1 << ssid))
5379 seq_printf(m, "%s%s", count++ ? "," : "",
5381 if (strlen(root->name))
5382 seq_printf(m, "%sname=%s", count ? "," : "",
5386 cgrp = task_cgroup_from_root(tsk, root);
5389 * On traditional hierarchies, all zombie tasks show up as
5390 * belonging to the root cgroup. On the default hierarchy,
5391 * while a zombie doesn't show up in "cgroup.procs" and
5392 * thus can't be migrated, its /proc/PID/cgroup keeps
5393 * reporting the cgroup it belonged to before exiting. If
5394 * the cgroup is removed before the zombie is reaped,
5395 * " (deleted)" is appended to the cgroup path.
5397 if (cgroup_on_dfl(cgrp) || !(tsk->flags & PF_EXITING)) {
5398 path = cgroup_path(cgrp, buf, PATH_MAX);
5400 retval = -ENAMETOOLONG;
5409 if (cgroup_on_dfl(cgrp) && cgroup_is_dead(cgrp))
5410 seq_puts(m, " (deleted)\n");
5417 spin_unlock_bh(&css_set_lock);
5418 mutex_unlock(&cgroup_mutex);
5424 /* Display information about each subsystem and each hierarchy */
5425 static int proc_cgroupstats_show(struct seq_file *m, void *v)
5427 struct cgroup_subsys *ss;
5430 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
5432 * ideally we don't want subsystems moving around while we do this.
5433 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
5434 * subsys/hierarchy state.
5436 mutex_lock(&cgroup_mutex);
5438 for_each_subsys(ss, i)
5439 seq_printf(m, "%s\t%d\t%d\t%d\n",
5440 ss->legacy_name, ss->root->hierarchy_id,
5441 atomic_read(&ss->root->nr_cgrps),
5442 cgroup_ssid_enabled(i));
5444 mutex_unlock(&cgroup_mutex);
5448 static int cgroupstats_open(struct inode *inode, struct file *file)
5450 return single_open(file, proc_cgroupstats_show, NULL);
5453 static const struct file_operations proc_cgroupstats_operations = {
5454 .open = cgroupstats_open,
5456 .llseek = seq_lseek,
5457 .release = single_release,
5460 static void **subsys_canfork_priv_p(void *ss_priv[CGROUP_CANFORK_COUNT], int i)
5462 if (CGROUP_CANFORK_START <= i && i < CGROUP_CANFORK_END)
5463 return &ss_priv[i - CGROUP_CANFORK_START];
5467 static void *subsys_canfork_priv(void *ss_priv[CGROUP_CANFORK_COUNT], int i)
5469 void **private = subsys_canfork_priv_p(ss_priv, i);
5470 return private ? *private : NULL;
5474 * cgroup_fork - initialize cgroup related fields during copy_process()
5475 * @child: pointer to task_struct of forking parent process.
5477 * A task is associated with the init_css_set until cgroup_post_fork()
5478 * attaches it to the parent's css_set. Empty cg_list indicates that
5479 * @child isn't holding reference to its css_set.
5481 void cgroup_fork(struct task_struct *child)
5483 RCU_INIT_POINTER(child->cgroups, &init_css_set);
5484 INIT_LIST_HEAD(&child->cg_list);
5488 * cgroup_can_fork - called on a new task before the process is exposed
5489 * @child: the task in question.
5491 * This calls the subsystem can_fork() callbacks. If the can_fork() callback
5492 * returns an error, the fork aborts with that error code. This allows for
5493 * a cgroup subsystem to conditionally allow or deny new forks.
5495 int cgroup_can_fork(struct task_struct *child,
5496 void *ss_priv[CGROUP_CANFORK_COUNT])
5498 struct cgroup_subsys *ss;
5501 for_each_subsys_which(ss, i, &have_canfork_callback) {
5502 ret = ss->can_fork(child, subsys_canfork_priv_p(ss_priv, i));
5510 for_each_subsys(ss, j) {
5513 if (ss->cancel_fork)
5514 ss->cancel_fork(child, subsys_canfork_priv(ss_priv, j));
5521 * cgroup_cancel_fork - called if a fork failed after cgroup_can_fork()
5522 * @child: the task in question
5524 * This calls the cancel_fork() callbacks if a fork failed *after*
5525 * cgroup_can_fork() succeded.
5527 void cgroup_cancel_fork(struct task_struct *child,
5528 void *ss_priv[CGROUP_CANFORK_COUNT])
5530 struct cgroup_subsys *ss;
5533 for_each_subsys(ss, i)
5534 if (ss->cancel_fork)
5535 ss->cancel_fork(child, subsys_canfork_priv(ss_priv, i));
5539 * cgroup_post_fork - called on a new task after adding it to the task list
5540 * @child: the task in question
5542 * Adds the task to the list running through its css_set if necessary and
5543 * call the subsystem fork() callbacks. Has to be after the task is
5544 * visible on the task list in case we race with the first call to
5545 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
5548 void cgroup_post_fork(struct task_struct *child,
5549 void *old_ss_priv[CGROUP_CANFORK_COUNT])
5551 struct cgroup_subsys *ss;
5555 * This may race against cgroup_enable_task_cg_lists(). As that
5556 * function sets use_task_css_set_links before grabbing
5557 * tasklist_lock and we just went through tasklist_lock to add
5558 * @child, it's guaranteed that either we see the set
5559 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
5560 * @child during its iteration.
5562 * If we won the race, @child is associated with %current's
5563 * css_set. Grabbing css_set_lock guarantees both that the
5564 * association is stable, and, on completion of the parent's
5565 * migration, @child is visible in the source of migration or
5566 * already in the destination cgroup. This guarantee is necessary
5567 * when implementing operations which need to migrate all tasks of
5568 * a cgroup to another.
5570 * Note that if we lose to cgroup_enable_task_cg_lists(), @child
5571 * will remain in init_css_set. This is safe because all tasks are
5572 * in the init_css_set before cg_links is enabled and there's no
5573 * operation which transfers all tasks out of init_css_set.
5575 if (use_task_css_set_links) {
5576 struct css_set *cset;
5578 spin_lock_bh(&css_set_lock);
5579 cset = task_css_set(current);
5580 if (list_empty(&child->cg_list)) {
5582 css_set_move_task(child, NULL, cset, false);
5584 spin_unlock_bh(&css_set_lock);
5588 * Call ss->fork(). This must happen after @child is linked on
5589 * css_set; otherwise, @child might change state between ->fork()
5590 * and addition to css_set.
5592 for_each_subsys_which(ss, i, &have_fork_callback)
5593 ss->fork(child, subsys_canfork_priv(old_ss_priv, i));
5597 * cgroup_exit - detach cgroup from exiting task
5598 * @tsk: pointer to task_struct of exiting process
5600 * Description: Detach cgroup from @tsk and release it.
5602 * Note that cgroups marked notify_on_release force every task in
5603 * them to take the global cgroup_mutex mutex when exiting.
5604 * This could impact scaling on very large systems. Be reluctant to
5605 * use notify_on_release cgroups where very high task exit scaling
5606 * is required on large systems.
5608 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
5609 * call cgroup_exit() while the task is still competent to handle
5610 * notify_on_release(), then leave the task attached to the root cgroup in
5611 * each hierarchy for the remainder of its exit. No need to bother with
5612 * init_css_set refcnting. init_css_set never goes away and we can't race
5613 * with migration path - PF_EXITING is visible to migration path.
5615 void cgroup_exit(struct task_struct *tsk)
5617 struct cgroup_subsys *ss;
5618 struct css_set *cset;
5622 * Unlink from @tsk from its css_set. As migration path can't race
5623 * with us, we can check css_set and cg_list without synchronization.
5625 cset = task_css_set(tsk);
5627 if (!list_empty(&tsk->cg_list)) {
5628 spin_lock_bh(&css_set_lock);
5629 css_set_move_task(tsk, cset, NULL, false);
5630 spin_unlock_bh(&css_set_lock);
5635 /* see cgroup_post_fork() for details */
5636 for_each_subsys_which(ss, i, &have_exit_callback)
5640 void cgroup_free(struct task_struct *task)
5642 struct css_set *cset = task_css_set(task);
5643 struct cgroup_subsys *ss;
5646 for_each_subsys_which(ss, ssid, &have_free_callback)
5652 static void check_for_release(struct cgroup *cgrp)
5654 if (notify_on_release(cgrp) && !cgroup_is_populated(cgrp) &&
5655 !css_has_online_children(&cgrp->self) && !cgroup_is_dead(cgrp))
5656 schedule_work(&cgrp->release_agent_work);
5660 * Notify userspace when a cgroup is released, by running the
5661 * configured release agent with the name of the cgroup (path
5662 * relative to the root of cgroup file system) as the argument.
5664 * Most likely, this user command will try to rmdir this cgroup.
5666 * This races with the possibility that some other task will be
5667 * attached to this cgroup before it is removed, or that some other
5668 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5669 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5670 * unused, and this cgroup will be reprieved from its death sentence,
5671 * to continue to serve a useful existence. Next time it's released,
5672 * we will get notified again, if it still has 'notify_on_release' set.
5674 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5675 * means only wait until the task is successfully execve()'d. The
5676 * separate release agent task is forked by call_usermodehelper(),
5677 * then control in this thread returns here, without waiting for the
5678 * release agent task. We don't bother to wait because the caller of
5679 * this routine has no use for the exit status of the release agent
5680 * task, so no sense holding our caller up for that.
5682 static void cgroup_release_agent(struct work_struct *work)
5684 struct cgroup *cgrp =
5685 container_of(work, struct cgroup, release_agent_work);
5686 char *pathbuf = NULL, *agentbuf = NULL, *path;
5687 char *argv[3], *envp[3];
5689 mutex_lock(&cgroup_mutex);
5691 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
5692 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5693 if (!pathbuf || !agentbuf)
5696 path = cgroup_path(cgrp, pathbuf, PATH_MAX);
5704 /* minimal command environment */
5706 envp[1] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5709 mutex_unlock(&cgroup_mutex);
5710 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5713 mutex_unlock(&cgroup_mutex);
5719 static int __init cgroup_disable(char *str)
5721 struct cgroup_subsys *ss;
5725 while ((token = strsep(&str, ",")) != NULL) {
5729 for_each_subsys(ss, i) {
5730 if (strcmp(token, ss->name) &&
5731 strcmp(token, ss->legacy_name))
5733 cgroup_disable_mask |= 1 << i;
5738 __setup("cgroup_disable=", cgroup_disable);
5741 * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
5742 * @dentry: directory dentry of interest
5743 * @ss: subsystem of interest
5745 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
5746 * to get the corresponding css and return it. If such css doesn't exist
5747 * or can't be pinned, an ERR_PTR value is returned.
5749 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
5750 struct cgroup_subsys *ss)
5752 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
5753 struct cgroup_subsys_state *css = NULL;
5754 struct cgroup *cgrp;
5756 /* is @dentry a cgroup dir? */
5757 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
5758 kernfs_type(kn) != KERNFS_DIR)
5759 return ERR_PTR(-EBADF);
5764 * This path doesn't originate from kernfs and @kn could already
5765 * have been or be removed at any point. @kn->priv is RCU
5766 * protected for this access. See css_release_work_fn() for details.
5768 cgrp = rcu_dereference(kn->priv);
5770 css = cgroup_css(cgrp, ss);
5772 if (!css || !css_tryget_online(css))
5773 css = ERR_PTR(-ENOENT);
5780 * css_from_id - lookup css by id
5781 * @id: the cgroup id
5782 * @ss: cgroup subsys to be looked into
5784 * Returns the css if there's valid one with @id, otherwise returns NULL.
5785 * Should be called under rcu_read_lock().
5787 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5789 WARN_ON_ONCE(!rcu_read_lock_held());
5790 return id > 0 ? idr_find(&ss->css_idr, id) : NULL;
5793 #ifdef CONFIG_CGROUP_DEBUG
5794 static struct cgroup_subsys_state *
5795 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5797 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5800 return ERR_PTR(-ENOMEM);
5805 static void debug_css_free(struct cgroup_subsys_state *css)
5810 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5813 return cgroup_task_count(css->cgroup);
5816 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5819 return (u64)(unsigned long)current->cgroups;
5822 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5828 count = atomic_read(&task_css_set(current)->refcount);
5833 static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
5835 struct cgrp_cset_link *link;
5836 struct css_set *cset;
5839 name_buf = kmalloc(NAME_MAX + 1, GFP_KERNEL);
5843 spin_lock_bh(&css_set_lock);
5845 cset = rcu_dereference(current->cgroups);
5846 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5847 struct cgroup *c = link->cgrp;
5849 cgroup_name(c, name_buf, NAME_MAX + 1);
5850 seq_printf(seq, "Root %d group %s\n",
5851 c->root->hierarchy_id, name_buf);
5854 spin_unlock_bh(&css_set_lock);
5859 #define MAX_TASKS_SHOWN_PER_CSS 25
5860 static int cgroup_css_links_read(struct seq_file *seq, void *v)
5862 struct cgroup_subsys_state *css = seq_css(seq);
5863 struct cgrp_cset_link *link;
5865 spin_lock_bh(&css_set_lock);
5866 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5867 struct css_set *cset = link->cset;
5868 struct task_struct *task;
5871 seq_printf(seq, "css_set %p\n", cset);
5873 list_for_each_entry(task, &cset->tasks, cg_list) {
5874 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5876 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5879 list_for_each_entry(task, &cset->mg_tasks, cg_list) {
5880 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
5882 seq_printf(seq, " task %d\n", task_pid_vnr(task));
5886 seq_puts(seq, " ...\n");
5888 spin_unlock_bh(&css_set_lock);
5892 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5894 return (!cgroup_is_populated(css->cgroup) &&
5895 !css_has_online_children(&css->cgroup->self));
5898 static struct cftype debug_files[] = {
5900 .name = "taskcount",
5901 .read_u64 = debug_taskcount_read,
5905 .name = "current_css_set",
5906 .read_u64 = current_css_set_read,
5910 .name = "current_css_set_refcount",
5911 .read_u64 = current_css_set_refcount_read,
5915 .name = "current_css_set_cg_links",
5916 .seq_show = current_css_set_cg_links_read,
5920 .name = "cgroup_css_links",
5921 .seq_show = cgroup_css_links_read,
5925 .name = "releasable",
5926 .read_u64 = releasable_read,
5932 struct cgroup_subsys debug_cgrp_subsys = {
5933 .css_alloc = debug_css_alloc,
5934 .css_free = debug_css_free,
5935 .legacy_cftypes = debug_files,
5937 #endif /* CONFIG_CGROUP_DEBUG */