Merge branch 'for-3.13/drivers' of git://git.kernel.dk/linux-block
[linux-2.6.git] / kernel / cgroup.c
blobe0839bcd48c8c2fdce9c13a3bfeba35a8e5f0e75
1 /*
2 * Generic process-grouping system.
4 * Based originally on the cpuset system, extracted by Paul Menage
5 * Copyright (C) 2006 Google, Inc
7 * Notifications support
8 * Copyright (C) 2009 Nokia Corporation
9 * Author: Kirill A. Shutemov
11 * Copyright notices from the original cpuset code:
12 * --------------------------------------------------
13 * Copyright (C) 2003 BULL SA.
14 * Copyright (C) 2004-2006 Silicon Graphics, Inc.
16 * Portions derived from Patrick Mochel's sysfs code.
17 * sysfs is Copyright (c) 2001-3 Patrick Mochel
19 * 2003-10-10 Written by Simon Derr.
20 * 2003-10-22 Updates by Stephen Hemminger.
21 * 2004 May-July Rework by Paul Jackson.
22 * ---------------------------------------------------
24 * This file is subject to the terms and conditions of the GNU General Public
25 * License. See the file COPYING in the main directory of the Linux
26 * distribution for more details.
29 #include <linux/cgroup.h>
30 #include <linux/cred.h>
31 #include <linux/ctype.h>
32 #include <linux/errno.h>
33 #include <linux/init_task.h>
34 #include <linux/kernel.h>
35 #include <linux/list.h>
36 #include <linux/mm.h>
37 #include <linux/mutex.h>
38 #include <linux/mount.h>
39 #include <linux/pagemap.h>
40 #include <linux/proc_fs.h>
41 #include <linux/rcupdate.h>
42 #include <linux/sched.h>
43 #include <linux/backing-dev.h>
44 #include <linux/seq_file.h>
45 #include <linux/slab.h>
46 #include <linux/magic.h>
47 #include <linux/spinlock.h>
48 #include <linux/string.h>
49 #include <linux/sort.h>
50 #include <linux/kmod.h>
51 #include <linux/module.h>
52 #include <linux/delayacct.h>
53 #include <linux/cgroupstats.h>
54 #include <linux/hashtable.h>
55 #include <linux/namei.h>
56 #include <linux/pid_namespace.h>
57 #include <linux/idr.h>
58 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
59 #include <linux/eventfd.h>
60 #include <linux/poll.h>
61 #include <linux/flex_array.h> /* used in cgroup_attach_task */
62 #include <linux/kthread.h>
63 #include <linux/file.h>
65 #include <linux/atomic.h>
68 * cgroup_mutex is the master lock. Any modification to cgroup or its
69 * hierarchy must be performed while holding it.
71 * cgroup_root_mutex nests inside cgroup_mutex and should be held to modify
72 * cgroupfs_root of any cgroup hierarchy - subsys list, flags,
73 * release_agent_path and so on. Modifying requires both cgroup_mutex and
74 * cgroup_root_mutex. Readers can acquire either of the two. This is to
75 * break the following locking order cycle.
77 * A. cgroup_mutex -> cred_guard_mutex -> s_type->i_mutex_key -> namespace_sem
78 * B. namespace_sem -> cgroup_mutex
80 * B happens only through cgroup_show_options() and using cgroup_root_mutex
81 * breaks it.
83 #ifdef CONFIG_PROVE_RCU
84 DEFINE_MUTEX(cgroup_mutex);
85 EXPORT_SYMBOL_GPL(cgroup_mutex); /* only for lockdep */
86 #else
87 static DEFINE_MUTEX(cgroup_mutex);
88 #endif
90 static DEFINE_MUTEX(cgroup_root_mutex);
93 * Generate an array of cgroup subsystem pointers. At boot time, this is
94 * populated with the built in subsystems, and modular subsystems are
95 * registered after that. The mutable section of this array is protected by
96 * cgroup_mutex.
98 #define SUBSYS(_x) [_x ## _subsys_id] = &_x ## _subsys,
99 #define IS_SUBSYS_ENABLED(option) IS_BUILTIN(option)
100 static struct cgroup_subsys *cgroup_subsys[CGROUP_SUBSYS_COUNT] = {
101 #include <linux/cgroup_subsys.h>
105 * The dummy hierarchy, reserved for the subsystems that are otherwise
106 * unattached - it never has more than a single cgroup, and all tasks are
107 * part of that cgroup.
109 static struct cgroupfs_root cgroup_dummy_root;
111 /* dummy_top is a shorthand for the dummy hierarchy's top cgroup */
112 static struct cgroup * const cgroup_dummy_top = &cgroup_dummy_root.top_cgroup;
115 * cgroupfs file entry, pointed to from leaf dentry->d_fsdata.
117 struct cfent {
118 struct list_head node;
119 struct dentry *dentry;
120 struct cftype *type;
121 struct cgroup_subsys_state *css;
123 /* file xattrs */
124 struct simple_xattrs xattrs;
128 * cgroup_event represents events which userspace want to receive.
130 struct cgroup_event {
132 * css which the event belongs to.
134 struct cgroup_subsys_state *css;
136 * Control file which the event associated.
138 struct cftype *cft;
140 * eventfd to signal userspace about the event.
142 struct eventfd_ctx *eventfd;
144 * Each of these stored in a list by the cgroup.
146 struct list_head list;
148 * All fields below needed to unregister event when
149 * userspace closes eventfd.
151 poll_table pt;
152 wait_queue_head_t *wqh;
153 wait_queue_t wait;
154 struct work_struct remove;
157 /* The list of hierarchy roots */
159 static LIST_HEAD(cgroup_roots);
160 static int cgroup_root_count;
163 * Hierarchy ID allocation and mapping. It follows the same exclusion
164 * rules as other root ops - both cgroup_mutex and cgroup_root_mutex for
165 * writes, either for reads.
167 static DEFINE_IDR(cgroup_hierarchy_idr);
169 static struct cgroup_name root_cgroup_name = { .name = "/" };
172 * Assign a monotonically increasing serial number to cgroups. It
173 * guarantees cgroups with bigger numbers are newer than those with smaller
174 * numbers. Also, as cgroups are always appended to the parent's
175 * ->children list, it guarantees that sibling cgroups are always sorted in
176 * the ascending serial number order on the list. Protected by
177 * cgroup_mutex.
179 static u64 cgroup_serial_nr_next = 1;
181 /* This flag indicates whether tasks in the fork and exit paths should
182 * check for fork/exit handlers to call. This avoids us having to do
183 * extra work in the fork/exit path if none of the subsystems need to
184 * be called.
186 static int need_forkexit_callback __read_mostly;
188 static struct cftype cgroup_base_files[];
190 static void cgroup_destroy_css_killed(struct cgroup *cgrp);
191 static int cgroup_destroy_locked(struct cgroup *cgrp);
192 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
193 bool is_add);
196 * cgroup_css - obtain a cgroup's css for the specified subsystem
197 * @cgrp: the cgroup of interest
198 * @ss: the subsystem of interest (%NULL returns the dummy_css)
200 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
201 * function must be called either under cgroup_mutex or rcu_read_lock() and
202 * the caller is responsible for pinning the returned css if it wants to
203 * keep accessing it outside the said locks. This function may return
204 * %NULL if @cgrp doesn't have @subsys_id enabled.
206 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
207 struct cgroup_subsys *ss)
209 if (ss)
210 return rcu_dereference_check(cgrp->subsys[ss->subsys_id],
211 lockdep_is_held(&cgroup_mutex));
212 else
213 return &cgrp->dummy_css;
216 /* convenient tests for these bits */
217 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
219 return test_bit(CGRP_DEAD, &cgrp->flags);
223 * cgroup_is_descendant - test ancestry
224 * @cgrp: the cgroup to be tested
225 * @ancestor: possible ancestor of @cgrp
227 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
228 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
229 * and @ancestor are accessible.
231 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
233 while (cgrp) {
234 if (cgrp == ancestor)
235 return true;
236 cgrp = cgrp->parent;
238 return false;
240 EXPORT_SYMBOL_GPL(cgroup_is_descendant);
242 static int cgroup_is_releasable(const struct cgroup *cgrp)
244 const int bits =
245 (1 << CGRP_RELEASABLE) |
246 (1 << CGRP_NOTIFY_ON_RELEASE);
247 return (cgrp->flags & bits) == bits;
250 static int notify_on_release(const struct cgroup *cgrp)
252 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
256 * for_each_subsys - iterate all loaded cgroup subsystems
257 * @ss: the iteration cursor
258 * @i: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
260 * Should be called under cgroup_mutex.
262 #define for_each_subsys(ss, i) \
263 for ((i) = 0; (i) < CGROUP_SUBSYS_COUNT; (i)++) \
264 if (({ lockdep_assert_held(&cgroup_mutex); \
265 !((ss) = cgroup_subsys[i]); })) { } \
266 else
269 * for_each_builtin_subsys - iterate all built-in cgroup subsystems
270 * @ss: the iteration cursor
271 * @i: the index of @ss, CGROUP_BUILTIN_SUBSYS_COUNT after reaching the end
273 * Bulit-in subsystems are always present and iteration itself doesn't
274 * require any synchronization.
276 #define for_each_builtin_subsys(ss, i) \
277 for ((i) = 0; (i) < CGROUP_BUILTIN_SUBSYS_COUNT && \
278 (((ss) = cgroup_subsys[i]) || true); (i)++)
280 /* iterate each subsystem attached to a hierarchy */
281 #define for_each_root_subsys(root, ss) \
282 list_for_each_entry((ss), &(root)->subsys_list, sibling)
284 /* iterate across the active hierarchies */
285 #define for_each_active_root(root) \
286 list_for_each_entry((root), &cgroup_roots, root_list)
288 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
290 return dentry->d_fsdata;
293 static inline struct cfent *__d_cfe(struct dentry *dentry)
295 return dentry->d_fsdata;
298 static inline struct cftype *__d_cft(struct dentry *dentry)
300 return __d_cfe(dentry)->type;
304 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
305 * @cgrp: the cgroup to be checked for liveness
307 * On success, returns true; the mutex should be later unlocked. On
308 * failure returns false with no lock held.
310 static bool cgroup_lock_live_group(struct cgroup *cgrp)
312 mutex_lock(&cgroup_mutex);
313 if (cgroup_is_dead(cgrp)) {
314 mutex_unlock(&cgroup_mutex);
315 return false;
317 return true;
320 /* the list of cgroups eligible for automatic release. Protected by
321 * release_list_lock */
322 static LIST_HEAD(release_list);
323 static DEFINE_RAW_SPINLOCK(release_list_lock);
324 static void cgroup_release_agent(struct work_struct *work);
325 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
326 static void check_for_release(struct cgroup *cgrp);
329 * A cgroup can be associated with multiple css_sets as different tasks may
330 * belong to different cgroups on different hierarchies. In the other
331 * direction, a css_set is naturally associated with multiple cgroups.
332 * This M:N relationship is represented by the following link structure
333 * which exists for each association and allows traversing the associations
334 * from both sides.
336 struct cgrp_cset_link {
337 /* the cgroup and css_set this link associates */
338 struct cgroup *cgrp;
339 struct css_set *cset;
341 /* list of cgrp_cset_links anchored at cgrp->cset_links */
342 struct list_head cset_link;
344 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
345 struct list_head cgrp_link;
348 /* The default css_set - used by init and its children prior to any
349 * hierarchies being mounted. It contains a pointer to the root state
350 * for each subsystem. Also used to anchor the list of css_sets. Not
351 * reference-counted, to improve performance when child cgroups
352 * haven't been created.
355 static struct css_set init_css_set;
356 static struct cgrp_cset_link init_cgrp_cset_link;
359 * css_set_lock protects the list of css_set objects, and the chain of
360 * tasks off each css_set. Nests outside task->alloc_lock due to
361 * css_task_iter_start().
363 static DEFINE_RWLOCK(css_set_lock);
364 static int css_set_count;
367 * hash table for cgroup groups. This improves the performance to find
368 * an existing css_set. This hash doesn't (currently) take into
369 * account cgroups in empty hierarchies.
371 #define CSS_SET_HASH_BITS 7
372 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
374 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
376 unsigned long key = 0UL;
377 struct cgroup_subsys *ss;
378 int i;
380 for_each_subsys(ss, i)
381 key += (unsigned long)css[i];
382 key = (key >> 16) ^ key;
384 return key;
388 * We don't maintain the lists running through each css_set to its task
389 * until after the first call to css_task_iter_start(). This reduces the
390 * fork()/exit() overhead for people who have cgroups compiled into their
391 * kernel but not actually in use.
393 static int use_task_css_set_links __read_mostly;
395 static void __put_css_set(struct css_set *cset, int taskexit)
397 struct cgrp_cset_link *link, *tmp_link;
400 * Ensure that the refcount doesn't hit zero while any readers
401 * can see it. Similar to atomic_dec_and_lock(), but for an
402 * rwlock
404 if (atomic_add_unless(&cset->refcount, -1, 1))
405 return;
406 write_lock(&css_set_lock);
407 if (!atomic_dec_and_test(&cset->refcount)) {
408 write_unlock(&css_set_lock);
409 return;
412 /* This css_set is dead. unlink it and release cgroup refcounts */
413 hash_del(&cset->hlist);
414 css_set_count--;
416 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
417 struct cgroup *cgrp = link->cgrp;
419 list_del(&link->cset_link);
420 list_del(&link->cgrp_link);
422 /* @cgrp can't go away while we're holding css_set_lock */
423 if (list_empty(&cgrp->cset_links) && notify_on_release(cgrp)) {
424 if (taskexit)
425 set_bit(CGRP_RELEASABLE, &cgrp->flags);
426 check_for_release(cgrp);
429 kfree(link);
432 write_unlock(&css_set_lock);
433 kfree_rcu(cset, rcu_head);
437 * refcounted get/put for css_set objects
439 static inline void get_css_set(struct css_set *cset)
441 atomic_inc(&cset->refcount);
444 static inline void put_css_set(struct css_set *cset)
446 __put_css_set(cset, 0);
449 static inline void put_css_set_taskexit(struct css_set *cset)
451 __put_css_set(cset, 1);
455 * compare_css_sets - helper function for find_existing_css_set().
456 * @cset: candidate css_set being tested
457 * @old_cset: existing css_set for a task
458 * @new_cgrp: cgroup that's being entered by the task
459 * @template: desired set of css pointers in css_set (pre-calculated)
461 * Returns true if "cset" matches "old_cset" except for the hierarchy
462 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
464 static bool compare_css_sets(struct css_set *cset,
465 struct css_set *old_cset,
466 struct cgroup *new_cgrp,
467 struct cgroup_subsys_state *template[])
469 struct list_head *l1, *l2;
471 if (memcmp(template, cset->subsys, sizeof(cset->subsys))) {
472 /* Not all subsystems matched */
473 return false;
477 * Compare cgroup pointers in order to distinguish between
478 * different cgroups in heirarchies with no subsystems. We
479 * could get by with just this check alone (and skip the
480 * memcmp above) but on most setups the memcmp check will
481 * avoid the need for this more expensive check on almost all
482 * candidates.
485 l1 = &cset->cgrp_links;
486 l2 = &old_cset->cgrp_links;
487 while (1) {
488 struct cgrp_cset_link *link1, *link2;
489 struct cgroup *cgrp1, *cgrp2;
491 l1 = l1->next;
492 l2 = l2->next;
493 /* See if we reached the end - both lists are equal length. */
494 if (l1 == &cset->cgrp_links) {
495 BUG_ON(l2 != &old_cset->cgrp_links);
496 break;
497 } else {
498 BUG_ON(l2 == &old_cset->cgrp_links);
500 /* Locate the cgroups associated with these links. */
501 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
502 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
503 cgrp1 = link1->cgrp;
504 cgrp2 = link2->cgrp;
505 /* Hierarchies should be linked in the same order. */
506 BUG_ON(cgrp1->root != cgrp2->root);
509 * If this hierarchy is the hierarchy of the cgroup
510 * that's changing, then we need to check that this
511 * css_set points to the new cgroup; if it's any other
512 * hierarchy, then this css_set should point to the
513 * same cgroup as the old css_set.
515 if (cgrp1->root == new_cgrp->root) {
516 if (cgrp1 != new_cgrp)
517 return false;
518 } else {
519 if (cgrp1 != cgrp2)
520 return false;
523 return true;
527 * find_existing_css_set - init css array and find the matching css_set
528 * @old_cset: the css_set that we're using before the cgroup transition
529 * @cgrp: the cgroup that we're moving into
530 * @template: out param for the new set of csses, should be clear on entry
532 static struct css_set *find_existing_css_set(struct css_set *old_cset,
533 struct cgroup *cgrp,
534 struct cgroup_subsys_state *template[])
536 struct cgroupfs_root *root = cgrp->root;
537 struct cgroup_subsys *ss;
538 struct css_set *cset;
539 unsigned long key;
540 int i;
543 * Build the set of subsystem state objects that we want to see in the
544 * new css_set. while subsystems can change globally, the entries here
545 * won't change, so no need for locking.
547 for_each_subsys(ss, i) {
548 if (root->subsys_mask & (1UL << i)) {
549 /* Subsystem is in this hierarchy. So we want
550 * the subsystem state from the new
551 * cgroup */
552 template[i] = cgroup_css(cgrp, ss);
553 } else {
554 /* Subsystem is not in this hierarchy, so we
555 * don't want to change the subsystem state */
556 template[i] = old_cset->subsys[i];
560 key = css_set_hash(template);
561 hash_for_each_possible(css_set_table, cset, hlist, key) {
562 if (!compare_css_sets(cset, old_cset, cgrp, template))
563 continue;
565 /* This css_set matches what we need */
566 return cset;
569 /* No existing cgroup group matched */
570 return NULL;
573 static void free_cgrp_cset_links(struct list_head *links_to_free)
575 struct cgrp_cset_link *link, *tmp_link;
577 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
578 list_del(&link->cset_link);
579 kfree(link);
584 * allocate_cgrp_cset_links - allocate cgrp_cset_links
585 * @count: the number of links to allocate
586 * @tmp_links: list_head the allocated links are put on
588 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
589 * through ->cset_link. Returns 0 on success or -errno.
591 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
593 struct cgrp_cset_link *link;
594 int i;
596 INIT_LIST_HEAD(tmp_links);
598 for (i = 0; i < count; i++) {
599 link = kzalloc(sizeof(*link), GFP_KERNEL);
600 if (!link) {
601 free_cgrp_cset_links(tmp_links);
602 return -ENOMEM;
604 list_add(&link->cset_link, tmp_links);
606 return 0;
610 * link_css_set - a helper function to link a css_set to a cgroup
611 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
612 * @cset: the css_set to be linked
613 * @cgrp: the destination cgroup
615 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
616 struct cgroup *cgrp)
618 struct cgrp_cset_link *link;
620 BUG_ON(list_empty(tmp_links));
621 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
622 link->cset = cset;
623 link->cgrp = cgrp;
624 list_move(&link->cset_link, &cgrp->cset_links);
626 * Always add links to the tail of the list so that the list
627 * is sorted by order of hierarchy creation
629 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
633 * find_css_set - return a new css_set with one cgroup updated
634 * @old_cset: the baseline css_set
635 * @cgrp: the cgroup to be updated
637 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
638 * substituted into the appropriate hierarchy.
640 static struct css_set *find_css_set(struct css_set *old_cset,
641 struct cgroup *cgrp)
643 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
644 struct css_set *cset;
645 struct list_head tmp_links;
646 struct cgrp_cset_link *link;
647 unsigned long key;
649 lockdep_assert_held(&cgroup_mutex);
651 /* First see if we already have a cgroup group that matches
652 * the desired set */
653 read_lock(&css_set_lock);
654 cset = find_existing_css_set(old_cset, cgrp, template);
655 if (cset)
656 get_css_set(cset);
657 read_unlock(&css_set_lock);
659 if (cset)
660 return cset;
662 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
663 if (!cset)
664 return NULL;
666 /* Allocate all the cgrp_cset_link objects that we'll need */
667 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
668 kfree(cset);
669 return NULL;
672 atomic_set(&cset->refcount, 1);
673 INIT_LIST_HEAD(&cset->cgrp_links);
674 INIT_LIST_HEAD(&cset->tasks);
675 INIT_HLIST_NODE(&cset->hlist);
677 /* Copy the set of subsystem state objects generated in
678 * find_existing_css_set() */
679 memcpy(cset->subsys, template, sizeof(cset->subsys));
681 write_lock(&css_set_lock);
682 /* Add reference counts and links from the new css_set. */
683 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
684 struct cgroup *c = link->cgrp;
686 if (c->root == cgrp->root)
687 c = cgrp;
688 link_css_set(&tmp_links, cset, c);
691 BUG_ON(!list_empty(&tmp_links));
693 css_set_count++;
695 /* Add this cgroup group to the hash table */
696 key = css_set_hash(cset->subsys);
697 hash_add(css_set_table, &cset->hlist, key);
699 write_unlock(&css_set_lock);
701 return cset;
705 * Return the cgroup for "task" from the given hierarchy. Must be
706 * called with cgroup_mutex held.
708 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
709 struct cgroupfs_root *root)
711 struct css_set *cset;
712 struct cgroup *res = NULL;
714 BUG_ON(!mutex_is_locked(&cgroup_mutex));
715 read_lock(&css_set_lock);
717 * No need to lock the task - since we hold cgroup_mutex the
718 * task can't change groups, so the only thing that can happen
719 * is that it exits and its css is set back to init_css_set.
721 cset = task_css_set(task);
722 if (cset == &init_css_set) {
723 res = &root->top_cgroup;
724 } else {
725 struct cgrp_cset_link *link;
727 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
728 struct cgroup *c = link->cgrp;
730 if (c->root == root) {
731 res = c;
732 break;
736 read_unlock(&css_set_lock);
737 BUG_ON(!res);
738 return res;
742 * There is one global cgroup mutex. We also require taking
743 * task_lock() when dereferencing a task's cgroup subsys pointers.
744 * See "The task_lock() exception", at the end of this comment.
746 * A task must hold cgroup_mutex to modify cgroups.
748 * Any task can increment and decrement the count field without lock.
749 * So in general, code holding cgroup_mutex can't rely on the count
750 * field not changing. However, if the count goes to zero, then only
751 * cgroup_attach_task() can increment it again. Because a count of zero
752 * means that no tasks are currently attached, therefore there is no
753 * way a task attached to that cgroup can fork (the other way to
754 * increment the count). So code holding cgroup_mutex can safely
755 * assume that if the count is zero, it will stay zero. Similarly, if
756 * a task holds cgroup_mutex on a cgroup with zero count, it
757 * knows that the cgroup won't be removed, as cgroup_rmdir()
758 * needs that mutex.
760 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
761 * (usually) take cgroup_mutex. These are the two most performance
762 * critical pieces of code here. The exception occurs on cgroup_exit(),
763 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
764 * is taken, and if the cgroup count is zero, a usermode call made
765 * to the release agent with the name of the cgroup (path relative to
766 * the root of cgroup file system) as the argument.
768 * A cgroup can only be deleted if both its 'count' of using tasks
769 * is zero, and its list of 'children' cgroups is empty. Since all
770 * tasks in the system use _some_ cgroup, and since there is always at
771 * least one task in the system (init, pid == 1), therefore, top_cgroup
772 * always has either children cgroups and/or using tasks. So we don't
773 * need a special hack to ensure that top_cgroup cannot be deleted.
775 * The task_lock() exception
777 * The need for this exception arises from the action of
778 * cgroup_attach_task(), which overwrites one task's cgroup pointer with
779 * another. It does so using cgroup_mutex, however there are
780 * several performance critical places that need to reference
781 * task->cgroup without the expense of grabbing a system global
782 * mutex. Therefore except as noted below, when dereferencing or, as
783 * in cgroup_attach_task(), modifying a task's cgroup pointer we use
784 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
785 * the task_struct routinely used for such matters.
787 * P.S. One more locking exception. RCU is used to guard the
788 * update of a tasks cgroup pointer by cgroup_attach_task()
792 * A couple of forward declarations required, due to cyclic reference loop:
793 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
794 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
795 * -> cgroup_mkdir.
798 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode);
799 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
800 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask);
801 static const struct inode_operations cgroup_dir_inode_operations;
802 static const struct file_operations proc_cgroupstats_operations;
804 static struct backing_dev_info cgroup_backing_dev_info = {
805 .name = "cgroup",
806 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
809 static struct inode *cgroup_new_inode(umode_t mode, struct super_block *sb)
811 struct inode *inode = new_inode(sb);
813 if (inode) {
814 inode->i_ino = get_next_ino();
815 inode->i_mode = mode;
816 inode->i_uid = current_fsuid();
817 inode->i_gid = current_fsgid();
818 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
819 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
821 return inode;
824 static struct cgroup_name *cgroup_alloc_name(struct dentry *dentry)
826 struct cgroup_name *name;
828 name = kmalloc(sizeof(*name) + dentry->d_name.len + 1, GFP_KERNEL);
829 if (!name)
830 return NULL;
831 strcpy(name->name, dentry->d_name.name);
832 return name;
835 static void cgroup_free_fn(struct work_struct *work)
837 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
839 mutex_lock(&cgroup_mutex);
840 cgrp->root->number_of_cgroups--;
841 mutex_unlock(&cgroup_mutex);
844 * We get a ref to the parent's dentry, and put the ref when
845 * this cgroup is being freed, so it's guaranteed that the
846 * parent won't be destroyed before its children.
848 dput(cgrp->parent->dentry);
851 * Drop the active superblock reference that we took when we
852 * created the cgroup. This will free cgrp->root, if we are
853 * holding the last reference to @sb.
855 deactivate_super(cgrp->root->sb);
858 * if we're getting rid of the cgroup, refcount should ensure
859 * that there are no pidlists left.
861 BUG_ON(!list_empty(&cgrp->pidlists));
863 simple_xattrs_free(&cgrp->xattrs);
865 kfree(rcu_dereference_raw(cgrp->name));
866 kfree(cgrp);
869 static void cgroup_free_rcu(struct rcu_head *head)
871 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
873 INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
874 schedule_work(&cgrp->destroy_work);
877 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
879 /* is dentry a directory ? if so, kfree() associated cgroup */
880 if (S_ISDIR(inode->i_mode)) {
881 struct cgroup *cgrp = dentry->d_fsdata;
883 BUG_ON(!(cgroup_is_dead(cgrp)));
884 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
885 } else {
886 struct cfent *cfe = __d_cfe(dentry);
887 struct cgroup *cgrp = dentry->d_parent->d_fsdata;
889 WARN_ONCE(!list_empty(&cfe->node) &&
890 cgrp != &cgrp->root->top_cgroup,
891 "cfe still linked for %s\n", cfe->type->name);
892 simple_xattrs_free(&cfe->xattrs);
893 kfree(cfe);
895 iput(inode);
898 static int cgroup_delete(const struct dentry *d)
900 return 1;
903 static void remove_dir(struct dentry *d)
905 struct dentry *parent = dget(d->d_parent);
907 d_delete(d);
908 simple_rmdir(parent->d_inode, d);
909 dput(parent);
912 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
914 struct cfent *cfe;
916 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
917 lockdep_assert_held(&cgroup_mutex);
920 * If we're doing cleanup due to failure of cgroup_create(),
921 * the corresponding @cfe may not exist.
923 list_for_each_entry(cfe, &cgrp->files, node) {
924 struct dentry *d = cfe->dentry;
926 if (cft && cfe->type != cft)
927 continue;
929 dget(d);
930 d_delete(d);
931 simple_unlink(cgrp->dentry->d_inode, d);
932 list_del_init(&cfe->node);
933 dput(d);
935 break;
940 * cgroup_clear_dir - remove subsys files in a cgroup directory
941 * @cgrp: target cgroup
942 * @subsys_mask: mask of the subsystem ids whose files should be removed
944 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned long subsys_mask)
946 struct cgroup_subsys *ss;
947 int i;
949 for_each_subsys(ss, i) {
950 struct cftype_set *set;
952 if (!test_bit(i, &subsys_mask))
953 continue;
954 list_for_each_entry(set, &ss->cftsets, node)
955 cgroup_addrm_files(cgrp, set->cfts, false);
960 * NOTE : the dentry must have been dget()'ed
962 static void cgroup_d_remove_dir(struct dentry *dentry)
964 struct dentry *parent;
966 parent = dentry->d_parent;
967 spin_lock(&parent->d_lock);
968 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
969 list_del_init(&dentry->d_u.d_child);
970 spin_unlock(&dentry->d_lock);
971 spin_unlock(&parent->d_lock);
972 remove_dir(dentry);
976 * Call with cgroup_mutex held. Drops reference counts on modules, including
977 * any duplicate ones that parse_cgroupfs_options took. If this function
978 * returns an error, no reference counts are touched.
980 static int rebind_subsystems(struct cgroupfs_root *root,
981 unsigned long added_mask, unsigned removed_mask)
983 struct cgroup *cgrp = &root->top_cgroup;
984 struct cgroup_subsys *ss;
985 unsigned long pinned = 0;
986 int i, ret;
988 BUG_ON(!mutex_is_locked(&cgroup_mutex));
989 BUG_ON(!mutex_is_locked(&cgroup_root_mutex));
991 /* Check that any added subsystems are currently free */
992 for_each_subsys(ss, i) {
993 if (!(added_mask & (1 << i)))
994 continue;
996 /* is the subsystem mounted elsewhere? */
997 if (ss->root != &cgroup_dummy_root) {
998 ret = -EBUSY;
999 goto out_put;
1002 /* pin the module */
1003 if (!try_module_get(ss->module)) {
1004 ret = -ENOENT;
1005 goto out_put;
1007 pinned |= 1 << i;
1010 /* subsys could be missing if unloaded between parsing and here */
1011 if (added_mask != pinned) {
1012 ret = -ENOENT;
1013 goto out_put;
1016 ret = cgroup_populate_dir(cgrp, added_mask);
1017 if (ret)
1018 goto out_put;
1021 * Nothing can fail from this point on. Remove files for the
1022 * removed subsystems and rebind each subsystem.
1024 cgroup_clear_dir(cgrp, removed_mask);
1026 for_each_subsys(ss, i) {
1027 unsigned long bit = 1UL << i;
1029 if (bit & added_mask) {
1030 /* We're binding this subsystem to this hierarchy */
1031 BUG_ON(cgroup_css(cgrp, ss));
1032 BUG_ON(!cgroup_css(cgroup_dummy_top, ss));
1033 BUG_ON(cgroup_css(cgroup_dummy_top, ss)->cgroup != cgroup_dummy_top);
1035 rcu_assign_pointer(cgrp->subsys[i],
1036 cgroup_css(cgroup_dummy_top, ss));
1037 cgroup_css(cgrp, ss)->cgroup = cgrp;
1039 list_move(&ss->sibling, &root->subsys_list);
1040 ss->root = root;
1041 if (ss->bind)
1042 ss->bind(cgroup_css(cgrp, ss));
1044 /* refcount was already taken, and we're keeping it */
1045 root->subsys_mask |= bit;
1046 } else if (bit & removed_mask) {
1047 /* We're removing this subsystem */
1048 BUG_ON(cgroup_css(cgrp, ss) != cgroup_css(cgroup_dummy_top, ss));
1049 BUG_ON(cgroup_css(cgrp, ss)->cgroup != cgrp);
1051 if (ss->bind)
1052 ss->bind(cgroup_css(cgroup_dummy_top, ss));
1054 cgroup_css(cgroup_dummy_top, ss)->cgroup = cgroup_dummy_top;
1055 RCU_INIT_POINTER(cgrp->subsys[i], NULL);
1057 cgroup_subsys[i]->root = &cgroup_dummy_root;
1058 list_move(&ss->sibling, &cgroup_dummy_root.subsys_list);
1060 /* subsystem is now free - drop reference on module */
1061 module_put(ss->module);
1062 root->subsys_mask &= ~bit;
1067 * Mark @root has finished binding subsystems. @root->subsys_mask
1068 * now matches the bound subsystems.
1070 root->flags |= CGRP_ROOT_SUBSYS_BOUND;
1072 return 0;
1074 out_put:
1075 for_each_subsys(ss, i)
1076 if (pinned & (1 << i))
1077 module_put(ss->module);
1078 return ret;
1081 static int cgroup_show_options(struct seq_file *seq, struct dentry *dentry)
1083 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
1084 struct cgroup_subsys *ss;
1086 mutex_lock(&cgroup_root_mutex);
1087 for_each_root_subsys(root, ss)
1088 seq_printf(seq, ",%s", ss->name);
1089 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1090 seq_puts(seq, ",sane_behavior");
1091 if (root->flags & CGRP_ROOT_NOPREFIX)
1092 seq_puts(seq, ",noprefix");
1093 if (root->flags & CGRP_ROOT_XATTR)
1094 seq_puts(seq, ",xattr");
1095 if (strlen(root->release_agent_path))
1096 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1097 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1098 seq_puts(seq, ",clone_children");
1099 if (strlen(root->name))
1100 seq_printf(seq, ",name=%s", root->name);
1101 mutex_unlock(&cgroup_root_mutex);
1102 return 0;
1105 struct cgroup_sb_opts {
1106 unsigned long subsys_mask;
1107 unsigned long flags;
1108 char *release_agent;
1109 bool cpuset_clone_children;
1110 char *name;
1111 /* User explicitly requested empty subsystem */
1112 bool none;
1114 struct cgroupfs_root *new_root;
1119 * Convert a hierarchy specifier into a bitmask of subsystems and
1120 * flags. Call with cgroup_mutex held to protect the cgroup_subsys[]
1121 * array. This function takes refcounts on subsystems to be used, unless it
1122 * returns error, in which case no refcounts are taken.
1124 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1126 char *token, *o = data;
1127 bool all_ss = false, one_ss = false;
1128 unsigned long mask = (unsigned long)-1;
1129 struct cgroup_subsys *ss;
1130 int i;
1132 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1134 #ifdef CONFIG_CPUSETS
1135 mask = ~(1UL << cpuset_subsys_id);
1136 #endif
1138 memset(opts, 0, sizeof(*opts));
1140 while ((token = strsep(&o, ",")) != NULL) {
1141 if (!*token)
1142 return -EINVAL;
1143 if (!strcmp(token, "none")) {
1144 /* Explicitly have no subsystems */
1145 opts->none = true;
1146 continue;
1148 if (!strcmp(token, "all")) {
1149 /* Mutually exclusive option 'all' + subsystem name */
1150 if (one_ss)
1151 return -EINVAL;
1152 all_ss = true;
1153 continue;
1155 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1156 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1157 continue;
1159 if (!strcmp(token, "noprefix")) {
1160 opts->flags |= CGRP_ROOT_NOPREFIX;
1161 continue;
1163 if (!strcmp(token, "clone_children")) {
1164 opts->cpuset_clone_children = true;
1165 continue;
1167 if (!strcmp(token, "xattr")) {
1168 opts->flags |= CGRP_ROOT_XATTR;
1169 continue;
1171 if (!strncmp(token, "release_agent=", 14)) {
1172 /* Specifying two release agents is forbidden */
1173 if (opts->release_agent)
1174 return -EINVAL;
1175 opts->release_agent =
1176 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1177 if (!opts->release_agent)
1178 return -ENOMEM;
1179 continue;
1181 if (!strncmp(token, "name=", 5)) {
1182 const char *name = token + 5;
1183 /* Can't specify an empty name */
1184 if (!strlen(name))
1185 return -EINVAL;
1186 /* Must match [\w.-]+ */
1187 for (i = 0; i < strlen(name); i++) {
1188 char c = name[i];
1189 if (isalnum(c))
1190 continue;
1191 if ((c == '.') || (c == '-') || (c == '_'))
1192 continue;
1193 return -EINVAL;
1195 /* Specifying two names is forbidden */
1196 if (opts->name)
1197 return -EINVAL;
1198 opts->name = kstrndup(name,
1199 MAX_CGROUP_ROOT_NAMELEN - 1,
1200 GFP_KERNEL);
1201 if (!opts->name)
1202 return -ENOMEM;
1204 continue;
1207 for_each_subsys(ss, i) {
1208 if (strcmp(token, ss->name))
1209 continue;
1210 if (ss->disabled)
1211 continue;
1213 /* Mutually exclusive option 'all' + subsystem name */
1214 if (all_ss)
1215 return -EINVAL;
1216 set_bit(i, &opts->subsys_mask);
1217 one_ss = true;
1219 break;
1221 if (i == CGROUP_SUBSYS_COUNT)
1222 return -ENOENT;
1226 * If the 'all' option was specified select all the subsystems,
1227 * otherwise if 'none', 'name=' and a subsystem name options
1228 * were not specified, let's default to 'all'
1230 if (all_ss || (!one_ss && !opts->none && !opts->name))
1231 for_each_subsys(ss, i)
1232 if (!ss->disabled)
1233 set_bit(i, &opts->subsys_mask);
1235 /* Consistency checks */
1237 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1238 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1240 if (opts->flags & CGRP_ROOT_NOPREFIX) {
1241 pr_err("cgroup: sane_behavior: noprefix is not allowed\n");
1242 return -EINVAL;
1245 if (opts->cpuset_clone_children) {
1246 pr_err("cgroup: sane_behavior: clone_children is not allowed\n");
1247 return -EINVAL;
1252 * Option noprefix was introduced just for backward compatibility
1253 * with the old cpuset, so we allow noprefix only if mounting just
1254 * the cpuset subsystem.
1256 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1257 return -EINVAL;
1260 /* Can't specify "none" and some subsystems */
1261 if (opts->subsys_mask && opts->none)
1262 return -EINVAL;
1265 * We either have to specify by name or by subsystems. (So all
1266 * empty hierarchies must have a name).
1268 if (!opts->subsys_mask && !opts->name)
1269 return -EINVAL;
1271 return 0;
1274 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1276 int ret = 0;
1277 struct cgroupfs_root *root = sb->s_fs_info;
1278 struct cgroup *cgrp = &root->top_cgroup;
1279 struct cgroup_sb_opts opts;
1280 unsigned long added_mask, removed_mask;
1282 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1283 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1284 return -EINVAL;
1287 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1288 mutex_lock(&cgroup_mutex);
1289 mutex_lock(&cgroup_root_mutex);
1291 /* See what subsystems are wanted */
1292 ret = parse_cgroupfs_options(data, &opts);
1293 if (ret)
1294 goto out_unlock;
1296 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1297 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1298 task_tgid_nr(current), current->comm);
1300 added_mask = opts.subsys_mask & ~root->subsys_mask;
1301 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1303 /* Don't allow flags or name to change at remount */
1304 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1305 (opts.name && strcmp(opts.name, root->name))) {
1306 pr_err("cgroup: option or name mismatch, new: 0x%lx \"%s\", old: 0x%lx \"%s\"\n",
1307 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1308 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1309 ret = -EINVAL;
1310 goto out_unlock;
1313 /* remounting is not allowed for populated hierarchies */
1314 if (root->number_of_cgroups > 1) {
1315 ret = -EBUSY;
1316 goto out_unlock;
1319 ret = rebind_subsystems(root, added_mask, removed_mask);
1320 if (ret)
1321 goto out_unlock;
1323 if (opts.release_agent)
1324 strcpy(root->release_agent_path, opts.release_agent);
1325 out_unlock:
1326 kfree(opts.release_agent);
1327 kfree(opts.name);
1328 mutex_unlock(&cgroup_root_mutex);
1329 mutex_unlock(&cgroup_mutex);
1330 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1331 return ret;
1334 static const struct super_operations cgroup_ops = {
1335 .statfs = simple_statfs,
1336 .drop_inode = generic_delete_inode,
1337 .show_options = cgroup_show_options,
1338 .remount_fs = cgroup_remount,
1341 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1343 INIT_LIST_HEAD(&cgrp->sibling);
1344 INIT_LIST_HEAD(&cgrp->children);
1345 INIT_LIST_HEAD(&cgrp->files);
1346 INIT_LIST_HEAD(&cgrp->cset_links);
1347 INIT_LIST_HEAD(&cgrp->release_list);
1348 INIT_LIST_HEAD(&cgrp->pidlists);
1349 mutex_init(&cgrp->pidlist_mutex);
1350 cgrp->dummy_css.cgroup = cgrp;
1351 INIT_LIST_HEAD(&cgrp->event_list);
1352 spin_lock_init(&cgrp->event_list_lock);
1353 simple_xattrs_init(&cgrp->xattrs);
1356 static void init_cgroup_root(struct cgroupfs_root *root)
1358 struct cgroup *cgrp = &root->top_cgroup;
1360 INIT_LIST_HEAD(&root->subsys_list);
1361 INIT_LIST_HEAD(&root->root_list);
1362 root->number_of_cgroups = 1;
1363 cgrp->root = root;
1364 RCU_INIT_POINTER(cgrp->name, &root_cgroup_name);
1365 init_cgroup_housekeeping(cgrp);
1366 idr_init(&root->cgroup_idr);
1369 static int cgroup_init_root_id(struct cgroupfs_root *root, int start, int end)
1371 int id;
1373 lockdep_assert_held(&cgroup_mutex);
1374 lockdep_assert_held(&cgroup_root_mutex);
1376 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, start, end,
1377 GFP_KERNEL);
1378 if (id < 0)
1379 return id;
1381 root->hierarchy_id = id;
1382 return 0;
1385 static void cgroup_exit_root_id(struct cgroupfs_root *root)
1387 lockdep_assert_held(&cgroup_mutex);
1388 lockdep_assert_held(&cgroup_root_mutex);
1390 if (root->hierarchy_id) {
1391 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1392 root->hierarchy_id = 0;
1396 static int cgroup_test_super(struct super_block *sb, void *data)
1398 struct cgroup_sb_opts *opts = data;
1399 struct cgroupfs_root *root = sb->s_fs_info;
1401 /* If we asked for a name then it must match */
1402 if (opts->name && strcmp(opts->name, root->name))
1403 return 0;
1406 * If we asked for subsystems (or explicitly for no
1407 * subsystems) then they must match
1409 if ((opts->subsys_mask || opts->none)
1410 && (opts->subsys_mask != root->subsys_mask))
1411 return 0;
1413 return 1;
1416 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1418 struct cgroupfs_root *root;
1420 if (!opts->subsys_mask && !opts->none)
1421 return NULL;
1423 root = kzalloc(sizeof(*root), GFP_KERNEL);
1424 if (!root)
1425 return ERR_PTR(-ENOMEM);
1427 init_cgroup_root(root);
1430 * We need to set @root->subsys_mask now so that @root can be
1431 * matched by cgroup_test_super() before it finishes
1432 * initialization; otherwise, competing mounts with the same
1433 * options may try to bind the same subsystems instead of waiting
1434 * for the first one leading to unexpected mount errors.
1435 * SUBSYS_BOUND will be set once actual binding is complete.
1437 root->subsys_mask = opts->subsys_mask;
1438 root->flags = opts->flags;
1439 if (opts->release_agent)
1440 strcpy(root->release_agent_path, opts->release_agent);
1441 if (opts->name)
1442 strcpy(root->name, opts->name);
1443 if (opts->cpuset_clone_children)
1444 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1445 return root;
1448 static void cgroup_free_root(struct cgroupfs_root *root)
1450 if (root) {
1451 /* hierarhcy ID shoulid already have been released */
1452 WARN_ON_ONCE(root->hierarchy_id);
1454 idr_destroy(&root->cgroup_idr);
1455 kfree(root);
1459 static int cgroup_set_super(struct super_block *sb, void *data)
1461 int ret;
1462 struct cgroup_sb_opts *opts = data;
1464 /* If we don't have a new root, we can't set up a new sb */
1465 if (!opts->new_root)
1466 return -EINVAL;
1468 BUG_ON(!opts->subsys_mask && !opts->none);
1470 ret = set_anon_super(sb, NULL);
1471 if (ret)
1472 return ret;
1474 sb->s_fs_info = opts->new_root;
1475 opts->new_root->sb = sb;
1477 sb->s_blocksize = PAGE_CACHE_SIZE;
1478 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1479 sb->s_magic = CGROUP_SUPER_MAGIC;
1480 sb->s_op = &cgroup_ops;
1482 return 0;
1485 static int cgroup_get_rootdir(struct super_block *sb)
1487 static const struct dentry_operations cgroup_dops = {
1488 .d_iput = cgroup_diput,
1489 .d_delete = cgroup_delete,
1492 struct inode *inode =
1493 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1495 if (!inode)
1496 return -ENOMEM;
1498 inode->i_fop = &simple_dir_operations;
1499 inode->i_op = &cgroup_dir_inode_operations;
1500 /* directories start off with i_nlink == 2 (for "." entry) */
1501 inc_nlink(inode);
1502 sb->s_root = d_make_root(inode);
1503 if (!sb->s_root)
1504 return -ENOMEM;
1505 /* for everything else we want ->d_op set */
1506 sb->s_d_op = &cgroup_dops;
1507 return 0;
1510 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1511 int flags, const char *unused_dev_name,
1512 void *data)
1514 struct cgroup_sb_opts opts;
1515 struct cgroupfs_root *root;
1516 int ret = 0;
1517 struct super_block *sb;
1518 struct cgroupfs_root *new_root;
1519 struct list_head tmp_links;
1520 struct inode *inode;
1521 const struct cred *cred;
1523 /* First find the desired set of subsystems */
1524 mutex_lock(&cgroup_mutex);
1525 ret = parse_cgroupfs_options(data, &opts);
1526 mutex_unlock(&cgroup_mutex);
1527 if (ret)
1528 goto out_err;
1531 * Allocate a new cgroup root. We may not need it if we're
1532 * reusing an existing hierarchy.
1534 new_root = cgroup_root_from_opts(&opts);
1535 if (IS_ERR(new_root)) {
1536 ret = PTR_ERR(new_root);
1537 goto out_err;
1539 opts.new_root = new_root;
1541 /* Locate an existing or new sb for this hierarchy */
1542 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1543 if (IS_ERR(sb)) {
1544 ret = PTR_ERR(sb);
1545 cgroup_free_root(opts.new_root);
1546 goto out_err;
1549 root = sb->s_fs_info;
1550 BUG_ON(!root);
1551 if (root == opts.new_root) {
1552 /* We used the new root structure, so this is a new hierarchy */
1553 struct cgroup *root_cgrp = &root->top_cgroup;
1554 struct cgroupfs_root *existing_root;
1555 int i;
1556 struct css_set *cset;
1558 BUG_ON(sb->s_root != NULL);
1560 ret = cgroup_get_rootdir(sb);
1561 if (ret)
1562 goto drop_new_super;
1563 inode = sb->s_root->d_inode;
1565 mutex_lock(&inode->i_mutex);
1566 mutex_lock(&cgroup_mutex);
1567 mutex_lock(&cgroup_root_mutex);
1569 root_cgrp->id = idr_alloc(&root->cgroup_idr, root_cgrp,
1570 0, 1, GFP_KERNEL);
1571 if (root_cgrp->id < 0)
1572 goto unlock_drop;
1574 /* Check for name clashes with existing mounts */
1575 ret = -EBUSY;
1576 if (strlen(root->name))
1577 for_each_active_root(existing_root)
1578 if (!strcmp(existing_root->name, root->name))
1579 goto unlock_drop;
1582 * We're accessing css_set_count without locking
1583 * css_set_lock here, but that's OK - it can only be
1584 * increased by someone holding cgroup_lock, and
1585 * that's us. The worst that can happen is that we
1586 * have some link structures left over
1588 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1589 if (ret)
1590 goto unlock_drop;
1592 /* ID 0 is reserved for dummy root, 1 for unified hierarchy */
1593 ret = cgroup_init_root_id(root, 2, 0);
1594 if (ret)
1595 goto unlock_drop;
1597 sb->s_root->d_fsdata = root_cgrp;
1598 root_cgrp->dentry = sb->s_root;
1601 * We're inside get_sb() and will call lookup_one_len() to
1602 * create the root files, which doesn't work if SELinux is
1603 * in use. The following cred dancing somehow works around
1604 * it. See 2ce9738ba ("cgroupfs: use init_cred when
1605 * populating new cgroupfs mount") for more details.
1607 cred = override_creds(&init_cred);
1609 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1610 if (ret)
1611 goto rm_base_files;
1613 ret = rebind_subsystems(root, root->subsys_mask, 0);
1614 if (ret)
1615 goto rm_base_files;
1617 revert_creds(cred);
1620 * There must be no failure case after here, since rebinding
1621 * takes care of subsystems' refcounts, which are explicitly
1622 * dropped in the failure exit path.
1625 list_add(&root->root_list, &cgroup_roots);
1626 cgroup_root_count++;
1628 /* Link the top cgroup in this hierarchy into all
1629 * the css_set objects */
1630 write_lock(&css_set_lock);
1631 hash_for_each(css_set_table, i, cset, hlist)
1632 link_css_set(&tmp_links, cset, root_cgrp);
1633 write_unlock(&css_set_lock);
1635 free_cgrp_cset_links(&tmp_links);
1637 BUG_ON(!list_empty(&root_cgrp->children));
1638 BUG_ON(root->number_of_cgroups != 1);
1640 mutex_unlock(&cgroup_root_mutex);
1641 mutex_unlock(&cgroup_mutex);
1642 mutex_unlock(&inode->i_mutex);
1643 } else {
1645 * We re-used an existing hierarchy - the new root (if
1646 * any) is not needed
1648 cgroup_free_root(opts.new_root);
1650 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1651 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1652 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1653 ret = -EINVAL;
1654 goto drop_new_super;
1655 } else {
1656 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1661 kfree(opts.release_agent);
1662 kfree(opts.name);
1663 return dget(sb->s_root);
1665 rm_base_files:
1666 free_cgrp_cset_links(&tmp_links);
1667 cgroup_addrm_files(&root->top_cgroup, cgroup_base_files, false);
1668 revert_creds(cred);
1669 unlock_drop:
1670 cgroup_exit_root_id(root);
1671 mutex_unlock(&cgroup_root_mutex);
1672 mutex_unlock(&cgroup_mutex);
1673 mutex_unlock(&inode->i_mutex);
1674 drop_new_super:
1675 deactivate_locked_super(sb);
1676 out_err:
1677 kfree(opts.release_agent);
1678 kfree(opts.name);
1679 return ERR_PTR(ret);
1682 static void cgroup_kill_sb(struct super_block *sb) {
1683 struct cgroupfs_root *root = sb->s_fs_info;
1684 struct cgroup *cgrp = &root->top_cgroup;
1685 struct cgrp_cset_link *link, *tmp_link;
1686 int ret;
1688 BUG_ON(!root);
1690 BUG_ON(root->number_of_cgroups != 1);
1691 BUG_ON(!list_empty(&cgrp->children));
1693 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1694 mutex_lock(&cgroup_mutex);
1695 mutex_lock(&cgroup_root_mutex);
1697 /* Rebind all subsystems back to the default hierarchy */
1698 if (root->flags & CGRP_ROOT_SUBSYS_BOUND) {
1699 ret = rebind_subsystems(root, 0, root->subsys_mask);
1700 /* Shouldn't be able to fail ... */
1701 BUG_ON(ret);
1705 * Release all the links from cset_links to this hierarchy's
1706 * root cgroup
1708 write_lock(&css_set_lock);
1710 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1711 list_del(&link->cset_link);
1712 list_del(&link->cgrp_link);
1713 kfree(link);
1715 write_unlock(&css_set_lock);
1717 if (!list_empty(&root->root_list)) {
1718 list_del(&root->root_list);
1719 cgroup_root_count--;
1722 cgroup_exit_root_id(root);
1724 mutex_unlock(&cgroup_root_mutex);
1725 mutex_unlock(&cgroup_mutex);
1726 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1728 simple_xattrs_free(&cgrp->xattrs);
1730 kill_litter_super(sb);
1731 cgroup_free_root(root);
1734 static struct file_system_type cgroup_fs_type = {
1735 .name = "cgroup",
1736 .mount = cgroup_mount,
1737 .kill_sb = cgroup_kill_sb,
1740 static struct kobject *cgroup_kobj;
1743 * cgroup_path - generate the path of a cgroup
1744 * @cgrp: the cgroup in question
1745 * @buf: the buffer to write the path into
1746 * @buflen: the length of the buffer
1748 * Writes path of cgroup into buf. Returns 0 on success, -errno on error.
1750 * We can't generate cgroup path using dentry->d_name, as accessing
1751 * dentry->name must be protected by irq-unsafe dentry->d_lock or parent
1752 * inode's i_mutex, while on the other hand cgroup_path() can be called
1753 * with some irq-safe spinlocks held.
1755 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1757 int ret = -ENAMETOOLONG;
1758 char *start;
1760 if (!cgrp->parent) {
1761 if (strlcpy(buf, "/", buflen) >= buflen)
1762 return -ENAMETOOLONG;
1763 return 0;
1766 start = buf + buflen - 1;
1767 *start = '\0';
1769 rcu_read_lock();
1770 do {
1771 const char *name = cgroup_name(cgrp);
1772 int len;
1774 len = strlen(name);
1775 if ((start -= len) < buf)
1776 goto out;
1777 memcpy(start, name, len);
1779 if (--start < buf)
1780 goto out;
1781 *start = '/';
1783 cgrp = cgrp->parent;
1784 } while (cgrp->parent);
1785 ret = 0;
1786 memmove(buf, start, buf + buflen - start);
1787 out:
1788 rcu_read_unlock();
1789 return ret;
1791 EXPORT_SYMBOL_GPL(cgroup_path);
1794 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1795 * @task: target task
1796 * @buf: the buffer to write the path into
1797 * @buflen: the length of the buffer
1799 * Determine @task's cgroup on the first (the one with the lowest non-zero
1800 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1801 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1802 * cgroup controller callbacks.
1804 * Returns 0 on success, fails with -%ENAMETOOLONG if @buflen is too short.
1806 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1808 struct cgroupfs_root *root;
1809 struct cgroup *cgrp;
1810 int hierarchy_id = 1, ret = 0;
1812 if (buflen < 2)
1813 return -ENAMETOOLONG;
1815 mutex_lock(&cgroup_mutex);
1817 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1819 if (root) {
1820 cgrp = task_cgroup_from_root(task, root);
1821 ret = cgroup_path(cgrp, buf, buflen);
1822 } else {
1823 /* if no hierarchy exists, everyone is in "/" */
1824 memcpy(buf, "/", 2);
1827 mutex_unlock(&cgroup_mutex);
1828 return ret;
1830 EXPORT_SYMBOL_GPL(task_cgroup_path);
1833 * Control Group taskset
1835 struct task_and_cgroup {
1836 struct task_struct *task;
1837 struct cgroup *cgrp;
1838 struct css_set *cset;
1841 struct cgroup_taskset {
1842 struct task_and_cgroup single;
1843 struct flex_array *tc_array;
1844 int tc_array_len;
1845 int idx;
1846 struct cgroup *cur_cgrp;
1850 * cgroup_taskset_first - reset taskset and return the first task
1851 * @tset: taskset of interest
1853 * @tset iteration is initialized and the first task is returned.
1855 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1857 if (tset->tc_array) {
1858 tset->idx = 0;
1859 return cgroup_taskset_next(tset);
1860 } else {
1861 tset->cur_cgrp = tset->single.cgrp;
1862 return tset->single.task;
1865 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1868 * cgroup_taskset_next - iterate to the next task in taskset
1869 * @tset: taskset of interest
1871 * Return the next task in @tset. Iteration must have been initialized
1872 * with cgroup_taskset_first().
1874 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1876 struct task_and_cgroup *tc;
1878 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1879 return NULL;
1881 tc = flex_array_get(tset->tc_array, tset->idx++);
1882 tset->cur_cgrp = tc->cgrp;
1883 return tc->task;
1885 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1888 * cgroup_taskset_cur_css - return the matching css for the current task
1889 * @tset: taskset of interest
1890 * @subsys_id: the ID of the target subsystem
1892 * Return the css for the current (last returned) task of @tset for
1893 * subsystem specified by @subsys_id. This function must be preceded by
1894 * either cgroup_taskset_first() or cgroup_taskset_next().
1896 struct cgroup_subsys_state *cgroup_taskset_cur_css(struct cgroup_taskset *tset,
1897 int subsys_id)
1899 return cgroup_css(tset->cur_cgrp, cgroup_subsys[subsys_id]);
1901 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_css);
1904 * cgroup_taskset_size - return the number of tasks in taskset
1905 * @tset: taskset of interest
1907 int cgroup_taskset_size(struct cgroup_taskset *tset)
1909 return tset->tc_array ? tset->tc_array_len : 1;
1911 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1915 * cgroup_task_migrate - move a task from one cgroup to another.
1917 * Must be called with cgroup_mutex and threadgroup locked.
1919 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1920 struct task_struct *tsk,
1921 struct css_set *new_cset)
1923 struct css_set *old_cset;
1926 * We are synchronized through threadgroup_lock() against PF_EXITING
1927 * setting such that we can't race against cgroup_exit() changing the
1928 * css_set to init_css_set and dropping the old one.
1930 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1931 old_cset = task_css_set(tsk);
1933 task_lock(tsk);
1934 rcu_assign_pointer(tsk->cgroups, new_cset);
1935 task_unlock(tsk);
1937 /* Update the css_set linked lists if we're using them */
1938 write_lock(&css_set_lock);
1939 if (!list_empty(&tsk->cg_list))
1940 list_move(&tsk->cg_list, &new_cset->tasks);
1941 write_unlock(&css_set_lock);
1944 * We just gained a reference on old_cset by taking it from the
1945 * task. As trading it for new_cset is protected by cgroup_mutex,
1946 * we're safe to drop it here; it will be freed under RCU.
1948 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1949 put_css_set(old_cset);
1953 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1954 * @cgrp: the cgroup to attach to
1955 * @tsk: the task or the leader of the threadgroup to be attached
1956 * @threadgroup: attach the whole threadgroup?
1958 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
1959 * task_lock of @tsk or each thread in the threadgroup individually in turn.
1961 static int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk,
1962 bool threadgroup)
1964 int retval, i, group_size;
1965 struct cgroup_subsys *ss, *failed_ss = NULL;
1966 struct cgroupfs_root *root = cgrp->root;
1967 /* threadgroup list cursor and array */
1968 struct task_struct *leader = tsk;
1969 struct task_and_cgroup *tc;
1970 struct flex_array *group;
1971 struct cgroup_taskset tset = { };
1974 * step 0: in order to do expensive, possibly blocking operations for
1975 * every thread, we cannot iterate the thread group list, since it needs
1976 * rcu or tasklist locked. instead, build an array of all threads in the
1977 * group - group_rwsem prevents new threads from appearing, and if
1978 * threads exit, this will just be an over-estimate.
1980 if (threadgroup)
1981 group_size = get_nr_threads(tsk);
1982 else
1983 group_size = 1;
1984 /* flex_array supports very large thread-groups better than kmalloc. */
1985 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
1986 if (!group)
1987 return -ENOMEM;
1988 /* pre-allocate to guarantee space while iterating in rcu read-side. */
1989 retval = flex_array_prealloc(group, 0, group_size, GFP_KERNEL);
1990 if (retval)
1991 goto out_free_group_list;
1993 i = 0;
1995 * Prevent freeing of tasks while we take a snapshot. Tasks that are
1996 * already PF_EXITING could be freed from underneath us unless we
1997 * take an rcu_read_lock.
1999 rcu_read_lock();
2000 do {
2001 struct task_and_cgroup ent;
2003 /* @tsk either already exited or can't exit until the end */
2004 if (tsk->flags & PF_EXITING)
2005 goto next;
2007 /* as per above, nr_threads may decrease, but not increase. */
2008 BUG_ON(i >= group_size);
2009 ent.task = tsk;
2010 ent.cgrp = task_cgroup_from_root(tsk, root);
2011 /* nothing to do if this task is already in the cgroup */
2012 if (ent.cgrp == cgrp)
2013 goto next;
2015 * saying GFP_ATOMIC has no effect here because we did prealloc
2016 * earlier, but it's good form to communicate our expectations.
2018 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
2019 BUG_ON(retval != 0);
2020 i++;
2021 next:
2022 if (!threadgroup)
2023 break;
2024 } while_each_thread(leader, tsk);
2025 rcu_read_unlock();
2026 /* remember the number of threads in the array for later. */
2027 group_size = i;
2028 tset.tc_array = group;
2029 tset.tc_array_len = group_size;
2031 /* methods shouldn't be called if no task is actually migrating */
2032 retval = 0;
2033 if (!group_size)
2034 goto out_free_group_list;
2037 * step 1: check that we can legitimately attach to the cgroup.
2039 for_each_root_subsys(root, ss) {
2040 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss);
2042 if (ss->can_attach) {
2043 retval = ss->can_attach(css, &tset);
2044 if (retval) {
2045 failed_ss = ss;
2046 goto out_cancel_attach;
2052 * step 2: make sure css_sets exist for all threads to be migrated.
2053 * we use find_css_set, which allocates a new one if necessary.
2055 for (i = 0; i < group_size; i++) {
2056 struct css_set *old_cset;
2058 tc = flex_array_get(group, i);
2059 old_cset = task_css_set(tc->task);
2060 tc->cset = find_css_set(old_cset, cgrp);
2061 if (!tc->cset) {
2062 retval = -ENOMEM;
2063 goto out_put_css_set_refs;
2068 * step 3: now that we're guaranteed success wrt the css_sets,
2069 * proceed to move all tasks to the new cgroup. There are no
2070 * failure cases after here, so this is the commit point.
2072 for (i = 0; i < group_size; i++) {
2073 tc = flex_array_get(group, i);
2074 cgroup_task_migrate(tc->cgrp, tc->task, tc->cset);
2076 /* nothing is sensitive to fork() after this point. */
2079 * step 4: do subsystem attach callbacks.
2081 for_each_root_subsys(root, ss) {
2082 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss);
2084 if (ss->attach)
2085 ss->attach(css, &tset);
2089 * step 5: success! and cleanup
2091 retval = 0;
2092 out_put_css_set_refs:
2093 if (retval) {
2094 for (i = 0; i < group_size; i++) {
2095 tc = flex_array_get(group, i);
2096 if (!tc->cset)
2097 break;
2098 put_css_set(tc->cset);
2101 out_cancel_attach:
2102 if (retval) {
2103 for_each_root_subsys(root, ss) {
2104 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss);
2106 if (ss == failed_ss)
2107 break;
2108 if (ss->cancel_attach)
2109 ss->cancel_attach(css, &tset);
2112 out_free_group_list:
2113 flex_array_free(group);
2114 return retval;
2118 * Find the task_struct of the task to attach by vpid and pass it along to the
2119 * function to attach either it or all tasks in its threadgroup. Will lock
2120 * cgroup_mutex and threadgroup; may take task_lock of task.
2122 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2124 struct task_struct *tsk;
2125 const struct cred *cred = current_cred(), *tcred;
2126 int ret;
2128 if (!cgroup_lock_live_group(cgrp))
2129 return -ENODEV;
2131 retry_find_task:
2132 rcu_read_lock();
2133 if (pid) {
2134 tsk = find_task_by_vpid(pid);
2135 if (!tsk) {
2136 rcu_read_unlock();
2137 ret= -ESRCH;
2138 goto out_unlock_cgroup;
2141 * even if we're attaching all tasks in the thread group, we
2142 * only need to check permissions on one of them.
2144 tcred = __task_cred(tsk);
2145 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2146 !uid_eq(cred->euid, tcred->uid) &&
2147 !uid_eq(cred->euid, tcred->suid)) {
2148 rcu_read_unlock();
2149 ret = -EACCES;
2150 goto out_unlock_cgroup;
2152 } else
2153 tsk = current;
2155 if (threadgroup)
2156 tsk = tsk->group_leader;
2159 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2160 * trapped in a cpuset, or RT worker may be born in a cgroup
2161 * with no rt_runtime allocated. Just say no.
2163 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2164 ret = -EINVAL;
2165 rcu_read_unlock();
2166 goto out_unlock_cgroup;
2169 get_task_struct(tsk);
2170 rcu_read_unlock();
2172 threadgroup_lock(tsk);
2173 if (threadgroup) {
2174 if (!thread_group_leader(tsk)) {
2176 * a race with de_thread from another thread's exec()
2177 * may strip us of our leadership, if this happens,
2178 * there is no choice but to throw this task away and
2179 * try again; this is
2180 * "double-double-toil-and-trouble-check locking".
2182 threadgroup_unlock(tsk);
2183 put_task_struct(tsk);
2184 goto retry_find_task;
2188 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2190 threadgroup_unlock(tsk);
2192 put_task_struct(tsk);
2193 out_unlock_cgroup:
2194 mutex_unlock(&cgroup_mutex);
2195 return ret;
2199 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2200 * @from: attach to all cgroups of a given task
2201 * @tsk: the task to be attached
2203 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2205 struct cgroupfs_root *root;
2206 int retval = 0;
2208 mutex_lock(&cgroup_mutex);
2209 for_each_active_root(root) {
2210 struct cgroup *from_cgrp = task_cgroup_from_root(from, root);
2212 retval = cgroup_attach_task(from_cgrp, tsk, false);
2213 if (retval)
2214 break;
2216 mutex_unlock(&cgroup_mutex);
2218 return retval;
2220 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2222 static int cgroup_tasks_write(struct cgroup_subsys_state *css,
2223 struct cftype *cft, u64 pid)
2225 return attach_task_by_pid(css->cgroup, pid, false);
2228 static int cgroup_procs_write(struct cgroup_subsys_state *css,
2229 struct cftype *cft, u64 tgid)
2231 return attach_task_by_pid(css->cgroup, tgid, true);
2234 static int cgroup_release_agent_write(struct cgroup_subsys_state *css,
2235 struct cftype *cft, const char *buffer)
2237 BUILD_BUG_ON(sizeof(css->cgroup->root->release_agent_path) < PATH_MAX);
2238 if (strlen(buffer) >= PATH_MAX)
2239 return -EINVAL;
2240 if (!cgroup_lock_live_group(css->cgroup))
2241 return -ENODEV;
2242 mutex_lock(&cgroup_root_mutex);
2243 strcpy(css->cgroup->root->release_agent_path, buffer);
2244 mutex_unlock(&cgroup_root_mutex);
2245 mutex_unlock(&cgroup_mutex);
2246 return 0;
2249 static int cgroup_release_agent_show(struct cgroup_subsys_state *css,
2250 struct cftype *cft, struct seq_file *seq)
2252 struct cgroup *cgrp = css->cgroup;
2254 if (!cgroup_lock_live_group(cgrp))
2255 return -ENODEV;
2256 seq_puts(seq, cgrp->root->release_agent_path);
2257 seq_putc(seq, '\n');
2258 mutex_unlock(&cgroup_mutex);
2259 return 0;
2262 static int cgroup_sane_behavior_show(struct cgroup_subsys_state *css,
2263 struct cftype *cft, struct seq_file *seq)
2265 seq_printf(seq, "%d\n", cgroup_sane_behavior(css->cgroup));
2266 return 0;
2269 /* A buffer size big enough for numbers or short strings */
2270 #define CGROUP_LOCAL_BUFFER_SIZE 64
2272 static ssize_t cgroup_write_X64(struct cgroup_subsys_state *css,
2273 struct cftype *cft, struct file *file,
2274 const char __user *userbuf, size_t nbytes,
2275 loff_t *unused_ppos)
2277 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
2278 int retval = 0;
2279 char *end;
2281 if (!nbytes)
2282 return -EINVAL;
2283 if (nbytes >= sizeof(buffer))
2284 return -E2BIG;
2285 if (copy_from_user(buffer, userbuf, nbytes))
2286 return -EFAULT;
2288 buffer[nbytes] = 0; /* nul-terminate */
2289 if (cft->write_u64) {
2290 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
2291 if (*end)
2292 return -EINVAL;
2293 retval = cft->write_u64(css, cft, val);
2294 } else {
2295 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
2296 if (*end)
2297 return -EINVAL;
2298 retval = cft->write_s64(css, cft, val);
2300 if (!retval)
2301 retval = nbytes;
2302 return retval;
2305 static ssize_t cgroup_write_string(struct cgroup_subsys_state *css,
2306 struct cftype *cft, struct file *file,
2307 const char __user *userbuf, size_t nbytes,
2308 loff_t *unused_ppos)
2310 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
2311 int retval = 0;
2312 size_t max_bytes = cft->max_write_len;
2313 char *buffer = local_buffer;
2315 if (!max_bytes)
2316 max_bytes = sizeof(local_buffer) - 1;
2317 if (nbytes >= max_bytes)
2318 return -E2BIG;
2319 /* Allocate a dynamic buffer if we need one */
2320 if (nbytes >= sizeof(local_buffer)) {
2321 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2322 if (buffer == NULL)
2323 return -ENOMEM;
2325 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2326 retval = -EFAULT;
2327 goto out;
2330 buffer[nbytes] = 0; /* nul-terminate */
2331 retval = cft->write_string(css, cft, strstrip(buffer));
2332 if (!retval)
2333 retval = nbytes;
2334 out:
2335 if (buffer != local_buffer)
2336 kfree(buffer);
2337 return retval;
2340 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2341 size_t nbytes, loff_t *ppos)
2343 struct cfent *cfe = __d_cfe(file->f_dentry);
2344 struct cftype *cft = __d_cft(file->f_dentry);
2345 struct cgroup_subsys_state *css = cfe->css;
2347 if (cft->write)
2348 return cft->write(css, cft, file, buf, nbytes, ppos);
2349 if (cft->write_u64 || cft->write_s64)
2350 return cgroup_write_X64(css, cft, file, buf, nbytes, ppos);
2351 if (cft->write_string)
2352 return cgroup_write_string(css, cft, file, buf, nbytes, ppos);
2353 if (cft->trigger) {
2354 int ret = cft->trigger(css, (unsigned int)cft->private);
2355 return ret ? ret : nbytes;
2357 return -EINVAL;
2360 static ssize_t cgroup_read_u64(struct cgroup_subsys_state *css,
2361 struct cftype *cft, struct file *file,
2362 char __user *buf, size_t nbytes, loff_t *ppos)
2364 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2365 u64 val = cft->read_u64(css, cft);
2366 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2368 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2371 static ssize_t cgroup_read_s64(struct cgroup_subsys_state *css,
2372 struct cftype *cft, struct file *file,
2373 char __user *buf, size_t nbytes, loff_t *ppos)
2375 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2376 s64 val = cft->read_s64(css, cft);
2377 int len = sprintf(tmp, "%lld\n", (long long) val);
2379 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2382 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2383 size_t nbytes, loff_t *ppos)
2385 struct cfent *cfe = __d_cfe(file->f_dentry);
2386 struct cftype *cft = __d_cft(file->f_dentry);
2387 struct cgroup_subsys_state *css = cfe->css;
2389 if (cft->read)
2390 return cft->read(css, cft, file, buf, nbytes, ppos);
2391 if (cft->read_u64)
2392 return cgroup_read_u64(css, cft, file, buf, nbytes, ppos);
2393 if (cft->read_s64)
2394 return cgroup_read_s64(css, cft, file, buf, nbytes, ppos);
2395 return -EINVAL;
2399 * seqfile ops/methods for returning structured data. Currently just
2400 * supports string->u64 maps, but can be extended in future.
2403 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2405 struct seq_file *sf = cb->state;
2406 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2409 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2411 struct cfent *cfe = m->private;
2412 struct cftype *cft = cfe->type;
2413 struct cgroup_subsys_state *css = cfe->css;
2415 if (cft->read_map) {
2416 struct cgroup_map_cb cb = {
2417 .fill = cgroup_map_add,
2418 .state = m,
2420 return cft->read_map(css, cft, &cb);
2422 return cft->read_seq_string(css, cft, m);
2425 static const struct file_operations cgroup_seqfile_operations = {
2426 .read = seq_read,
2427 .write = cgroup_file_write,
2428 .llseek = seq_lseek,
2429 .release = single_release,
2432 static int cgroup_file_open(struct inode *inode, struct file *file)
2434 struct cfent *cfe = __d_cfe(file->f_dentry);
2435 struct cftype *cft = __d_cft(file->f_dentry);
2436 struct cgroup *cgrp = __d_cgrp(cfe->dentry->d_parent);
2437 struct cgroup_subsys_state *css;
2438 int err;
2440 err = generic_file_open(inode, file);
2441 if (err)
2442 return err;
2445 * If the file belongs to a subsystem, pin the css. Will be
2446 * unpinned either on open failure or release. This ensures that
2447 * @css stays alive for all file operations.
2449 rcu_read_lock();
2450 css = cgroup_css(cgrp, cft->ss);
2451 if (cft->ss && !css_tryget(css))
2452 css = NULL;
2453 rcu_read_unlock();
2455 if (!css)
2456 return -ENODEV;
2459 * @cfe->css is used by read/write/close to determine the
2460 * associated css. @file->private_data would be a better place but
2461 * that's already used by seqfile. Multiple accessors may use it
2462 * simultaneously which is okay as the association never changes.
2464 WARN_ON_ONCE(cfe->css && cfe->css != css);
2465 cfe->css = css;
2467 if (cft->read_map || cft->read_seq_string) {
2468 file->f_op = &cgroup_seqfile_operations;
2469 err = single_open(file, cgroup_seqfile_show, cfe);
2470 } else if (cft->open) {
2471 err = cft->open(inode, file);
2474 if (css->ss && err)
2475 css_put(css);
2476 return err;
2479 static int cgroup_file_release(struct inode *inode, struct file *file)
2481 struct cfent *cfe = __d_cfe(file->f_dentry);
2482 struct cftype *cft = __d_cft(file->f_dentry);
2483 struct cgroup_subsys_state *css = cfe->css;
2484 int ret = 0;
2486 if (cft->release)
2487 ret = cft->release(inode, file);
2488 if (css->ss)
2489 css_put(css);
2490 return ret;
2494 * cgroup_rename - Only allow simple rename of directories in place.
2496 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2497 struct inode *new_dir, struct dentry *new_dentry)
2499 int ret;
2500 struct cgroup_name *name, *old_name;
2501 struct cgroup *cgrp;
2504 * It's convinient to use parent dir's i_mutex to protected
2505 * cgrp->name.
2507 lockdep_assert_held(&old_dir->i_mutex);
2509 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2510 return -ENOTDIR;
2511 if (new_dentry->d_inode)
2512 return -EEXIST;
2513 if (old_dir != new_dir)
2514 return -EIO;
2516 cgrp = __d_cgrp(old_dentry);
2519 * This isn't a proper migration and its usefulness is very
2520 * limited. Disallow if sane_behavior.
2522 if (cgroup_sane_behavior(cgrp))
2523 return -EPERM;
2525 name = cgroup_alloc_name(new_dentry);
2526 if (!name)
2527 return -ENOMEM;
2529 ret = simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2530 if (ret) {
2531 kfree(name);
2532 return ret;
2535 old_name = rcu_dereference_protected(cgrp->name, true);
2536 rcu_assign_pointer(cgrp->name, name);
2538 kfree_rcu(old_name, rcu_head);
2539 return 0;
2542 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2544 if (S_ISDIR(dentry->d_inode->i_mode))
2545 return &__d_cgrp(dentry)->xattrs;
2546 else
2547 return &__d_cfe(dentry)->xattrs;
2550 static inline int xattr_enabled(struct dentry *dentry)
2552 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2553 return root->flags & CGRP_ROOT_XATTR;
2556 static bool is_valid_xattr(const char *name)
2558 if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2559 !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2560 return true;
2561 return false;
2564 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2565 const void *val, size_t size, int flags)
2567 if (!xattr_enabled(dentry))
2568 return -EOPNOTSUPP;
2569 if (!is_valid_xattr(name))
2570 return -EINVAL;
2571 return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2574 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2576 if (!xattr_enabled(dentry))
2577 return -EOPNOTSUPP;
2578 if (!is_valid_xattr(name))
2579 return -EINVAL;
2580 return simple_xattr_remove(__d_xattrs(dentry), name);
2583 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2584 void *buf, size_t size)
2586 if (!xattr_enabled(dentry))
2587 return -EOPNOTSUPP;
2588 if (!is_valid_xattr(name))
2589 return -EINVAL;
2590 return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2593 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2595 if (!xattr_enabled(dentry))
2596 return -EOPNOTSUPP;
2597 return simple_xattr_list(__d_xattrs(dentry), buf, size);
2600 static const struct file_operations cgroup_file_operations = {
2601 .read = cgroup_file_read,
2602 .write = cgroup_file_write,
2603 .llseek = generic_file_llseek,
2604 .open = cgroup_file_open,
2605 .release = cgroup_file_release,
2608 static const struct inode_operations cgroup_file_inode_operations = {
2609 .setxattr = cgroup_setxattr,
2610 .getxattr = cgroup_getxattr,
2611 .listxattr = cgroup_listxattr,
2612 .removexattr = cgroup_removexattr,
2615 static const struct inode_operations cgroup_dir_inode_operations = {
2616 .lookup = simple_lookup,
2617 .mkdir = cgroup_mkdir,
2618 .rmdir = cgroup_rmdir,
2619 .rename = cgroup_rename,
2620 .setxattr = cgroup_setxattr,
2621 .getxattr = cgroup_getxattr,
2622 .listxattr = cgroup_listxattr,
2623 .removexattr = cgroup_removexattr,
2627 * Check if a file is a control file
2629 static inline struct cftype *__file_cft(struct file *file)
2631 if (file_inode(file)->i_fop != &cgroup_file_operations)
2632 return ERR_PTR(-EINVAL);
2633 return __d_cft(file->f_dentry);
2636 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2637 struct super_block *sb)
2639 struct inode *inode;
2641 if (!dentry)
2642 return -ENOENT;
2643 if (dentry->d_inode)
2644 return -EEXIST;
2646 inode = cgroup_new_inode(mode, sb);
2647 if (!inode)
2648 return -ENOMEM;
2650 if (S_ISDIR(mode)) {
2651 inode->i_op = &cgroup_dir_inode_operations;
2652 inode->i_fop = &simple_dir_operations;
2654 /* start off with i_nlink == 2 (for "." entry) */
2655 inc_nlink(inode);
2656 inc_nlink(dentry->d_parent->d_inode);
2659 * Control reaches here with cgroup_mutex held.
2660 * @inode->i_mutex should nest outside cgroup_mutex but we
2661 * want to populate it immediately without releasing
2662 * cgroup_mutex. As @inode isn't visible to anyone else
2663 * yet, trylock will always succeed without affecting
2664 * lockdep checks.
2666 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2667 } else if (S_ISREG(mode)) {
2668 inode->i_size = 0;
2669 inode->i_fop = &cgroup_file_operations;
2670 inode->i_op = &cgroup_file_inode_operations;
2672 d_instantiate(dentry, inode);
2673 dget(dentry); /* Extra count - pin the dentry in core */
2674 return 0;
2678 * cgroup_file_mode - deduce file mode of a control file
2679 * @cft: the control file in question
2681 * returns cft->mode if ->mode is not 0
2682 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2683 * returns S_IRUGO if it has only a read handler
2684 * returns S_IWUSR if it has only a write hander
2686 static umode_t cgroup_file_mode(const struct cftype *cft)
2688 umode_t mode = 0;
2690 if (cft->mode)
2691 return cft->mode;
2693 if (cft->read || cft->read_u64 || cft->read_s64 ||
2694 cft->read_map || cft->read_seq_string)
2695 mode |= S_IRUGO;
2697 if (cft->write || cft->write_u64 || cft->write_s64 ||
2698 cft->write_string || cft->trigger)
2699 mode |= S_IWUSR;
2701 return mode;
2704 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2706 struct dentry *dir = cgrp->dentry;
2707 struct cgroup *parent = __d_cgrp(dir);
2708 struct dentry *dentry;
2709 struct cfent *cfe;
2710 int error;
2711 umode_t mode;
2712 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2714 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
2715 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
2716 strcpy(name, cft->ss->name);
2717 strcat(name, ".");
2719 strcat(name, cft->name);
2721 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2723 cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2724 if (!cfe)
2725 return -ENOMEM;
2727 dentry = lookup_one_len(name, dir, strlen(name));
2728 if (IS_ERR(dentry)) {
2729 error = PTR_ERR(dentry);
2730 goto out;
2733 cfe->type = (void *)cft;
2734 cfe->dentry = dentry;
2735 dentry->d_fsdata = cfe;
2736 simple_xattrs_init(&cfe->xattrs);
2738 mode = cgroup_file_mode(cft);
2739 error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2740 if (!error) {
2741 list_add_tail(&cfe->node, &parent->files);
2742 cfe = NULL;
2744 dput(dentry);
2745 out:
2746 kfree(cfe);
2747 return error;
2751 * cgroup_addrm_files - add or remove files to a cgroup directory
2752 * @cgrp: the target cgroup
2753 * @cfts: array of cftypes to be added
2754 * @is_add: whether to add or remove
2756 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2757 * For removals, this function never fails. If addition fails, this
2758 * function doesn't remove files already added. The caller is responsible
2759 * for cleaning up.
2761 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2762 bool is_add)
2764 struct cftype *cft;
2765 int ret;
2767 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
2768 lockdep_assert_held(&cgroup_mutex);
2770 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2771 /* does cft->flags tell us to skip this file on @cgrp? */
2772 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2773 continue;
2774 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2775 continue;
2776 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2777 continue;
2779 if (is_add) {
2780 ret = cgroup_add_file(cgrp, cft);
2781 if (ret) {
2782 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2783 cft->name, ret);
2784 return ret;
2786 } else {
2787 cgroup_rm_file(cgrp, cft);
2790 return 0;
2793 static void cgroup_cfts_prepare(void)
2794 __acquires(&cgroup_mutex)
2797 * Thanks to the entanglement with vfs inode locking, we can't walk
2798 * the existing cgroups under cgroup_mutex and create files.
2799 * Instead, we use css_for_each_descendant_pre() and drop RCU read
2800 * lock before calling cgroup_addrm_files().
2802 mutex_lock(&cgroup_mutex);
2805 static int cgroup_cfts_commit(struct cftype *cfts, bool is_add)
2806 __releases(&cgroup_mutex)
2808 LIST_HEAD(pending);
2809 struct cgroup_subsys *ss = cfts[0].ss;
2810 struct cgroup *root = &ss->root->top_cgroup;
2811 struct super_block *sb = ss->root->sb;
2812 struct dentry *prev = NULL;
2813 struct inode *inode;
2814 struct cgroup_subsys_state *css;
2815 u64 update_before;
2816 int ret = 0;
2818 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2819 if (!cfts || ss->root == &cgroup_dummy_root ||
2820 !atomic_inc_not_zero(&sb->s_active)) {
2821 mutex_unlock(&cgroup_mutex);
2822 return 0;
2826 * All cgroups which are created after we drop cgroup_mutex will
2827 * have the updated set of files, so we only need to update the
2828 * cgroups created before the current @cgroup_serial_nr_next.
2830 update_before = cgroup_serial_nr_next;
2832 mutex_unlock(&cgroup_mutex);
2834 /* add/rm files for all cgroups created before */
2835 rcu_read_lock();
2836 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2837 struct cgroup *cgrp = css->cgroup;
2839 if (cgroup_is_dead(cgrp))
2840 continue;
2842 inode = cgrp->dentry->d_inode;
2843 dget(cgrp->dentry);
2844 rcu_read_unlock();
2846 dput(prev);
2847 prev = cgrp->dentry;
2849 mutex_lock(&inode->i_mutex);
2850 mutex_lock(&cgroup_mutex);
2851 if (cgrp->serial_nr < update_before && !cgroup_is_dead(cgrp))
2852 ret = cgroup_addrm_files(cgrp, cfts, is_add);
2853 mutex_unlock(&cgroup_mutex);
2854 mutex_unlock(&inode->i_mutex);
2856 rcu_read_lock();
2857 if (ret)
2858 break;
2860 rcu_read_unlock();
2861 dput(prev);
2862 deactivate_super(sb);
2863 return ret;
2867 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2868 * @ss: target cgroup subsystem
2869 * @cfts: zero-length name terminated array of cftypes
2871 * Register @cfts to @ss. Files described by @cfts are created for all
2872 * existing cgroups to which @ss is attached and all future cgroups will
2873 * have them too. This function can be called anytime whether @ss is
2874 * attached or not.
2876 * Returns 0 on successful registration, -errno on failure. Note that this
2877 * function currently returns 0 as long as @cfts registration is successful
2878 * even if some file creation attempts on existing cgroups fail.
2880 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2882 struct cftype_set *set;
2883 struct cftype *cft;
2884 int ret;
2886 set = kzalloc(sizeof(*set), GFP_KERNEL);
2887 if (!set)
2888 return -ENOMEM;
2890 for (cft = cfts; cft->name[0] != '\0'; cft++)
2891 cft->ss = ss;
2893 cgroup_cfts_prepare();
2894 set->cfts = cfts;
2895 list_add_tail(&set->node, &ss->cftsets);
2896 ret = cgroup_cfts_commit(cfts, true);
2897 if (ret)
2898 cgroup_rm_cftypes(cfts);
2899 return ret;
2901 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2904 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2905 * @cfts: zero-length name terminated array of cftypes
2907 * Unregister @cfts. Files described by @cfts are removed from all
2908 * existing cgroups and all future cgroups won't have them either. This
2909 * function can be called anytime whether @cfts' subsys is attached or not.
2911 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2912 * registered.
2914 int cgroup_rm_cftypes(struct cftype *cfts)
2916 struct cftype_set *set;
2918 if (!cfts || !cfts[0].ss)
2919 return -ENOENT;
2921 cgroup_cfts_prepare();
2923 list_for_each_entry(set, &cfts[0].ss->cftsets, node) {
2924 if (set->cfts == cfts) {
2925 list_del(&set->node);
2926 kfree(set);
2927 cgroup_cfts_commit(cfts, false);
2928 return 0;
2932 cgroup_cfts_commit(NULL, false);
2933 return -ENOENT;
2937 * cgroup_task_count - count the number of tasks in a cgroup.
2938 * @cgrp: the cgroup in question
2940 * Return the number of tasks in the cgroup.
2942 int cgroup_task_count(const struct cgroup *cgrp)
2944 int count = 0;
2945 struct cgrp_cset_link *link;
2947 read_lock(&css_set_lock);
2948 list_for_each_entry(link, &cgrp->cset_links, cset_link)
2949 count += atomic_read(&link->cset->refcount);
2950 read_unlock(&css_set_lock);
2951 return count;
2955 * To reduce the fork() overhead for systems that are not actually using
2956 * their cgroups capability, we don't maintain the lists running through
2957 * each css_set to its tasks until we see the list actually used - in other
2958 * words after the first call to css_task_iter_start().
2960 static void cgroup_enable_task_cg_lists(void)
2962 struct task_struct *p, *g;
2963 write_lock(&css_set_lock);
2964 use_task_css_set_links = 1;
2966 * We need tasklist_lock because RCU is not safe against
2967 * while_each_thread(). Besides, a forking task that has passed
2968 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2969 * is not guaranteed to have its child immediately visible in the
2970 * tasklist if we walk through it with RCU.
2972 read_lock(&tasklist_lock);
2973 do_each_thread(g, p) {
2974 task_lock(p);
2976 * We should check if the process is exiting, otherwise
2977 * it will race with cgroup_exit() in that the list
2978 * entry won't be deleted though the process has exited.
2980 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2981 list_add(&p->cg_list, &task_css_set(p)->tasks);
2982 task_unlock(p);
2983 } while_each_thread(g, p);
2984 read_unlock(&tasklist_lock);
2985 write_unlock(&css_set_lock);
2989 * css_next_child - find the next child of a given css
2990 * @pos_css: the current position (%NULL to initiate traversal)
2991 * @parent_css: css whose children to walk
2993 * This function returns the next child of @parent_css and should be called
2994 * under RCU read lock. The only requirement is that @parent_css and
2995 * @pos_css are accessible. The next sibling is guaranteed to be returned
2996 * regardless of their states.
2998 struct cgroup_subsys_state *
2999 css_next_child(struct cgroup_subsys_state *pos_css,
3000 struct cgroup_subsys_state *parent_css)
3002 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
3003 struct cgroup *cgrp = parent_css->cgroup;
3004 struct cgroup *next;
3006 WARN_ON_ONCE(!rcu_read_lock_held());
3009 * @pos could already have been removed. Once a cgroup is removed,
3010 * its ->sibling.next is no longer updated when its next sibling
3011 * changes. As CGRP_DEAD assertion is serialized and happens
3012 * before the cgroup is taken off the ->sibling list, if we see it
3013 * unasserted, it's guaranteed that the next sibling hasn't
3014 * finished its grace period even if it's already removed, and thus
3015 * safe to dereference from this RCU critical section. If
3016 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
3017 * to be visible as %true here.
3019 * If @pos is dead, its next pointer can't be dereferenced;
3020 * however, as each cgroup is given a monotonically increasing
3021 * unique serial number and always appended to the sibling list,
3022 * the next one can be found by walking the parent's children until
3023 * we see a cgroup with higher serial number than @pos's. While
3024 * this path can be slower, it's taken only when either the current
3025 * cgroup is removed or iteration and removal race.
3027 if (!pos) {
3028 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
3029 } else if (likely(!cgroup_is_dead(pos))) {
3030 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3031 } else {
3032 list_for_each_entry_rcu(next, &cgrp->children, sibling)
3033 if (next->serial_nr > pos->serial_nr)
3034 break;
3037 if (&next->sibling == &cgrp->children)
3038 return NULL;
3040 return cgroup_css(next, parent_css->ss);
3042 EXPORT_SYMBOL_GPL(css_next_child);
3045 * css_next_descendant_pre - find the next descendant for pre-order walk
3046 * @pos: the current position (%NULL to initiate traversal)
3047 * @root: css whose descendants to walk
3049 * To be used by css_for_each_descendant_pre(). Find the next descendant
3050 * to visit for pre-order traversal of @root's descendants. @root is
3051 * included in the iteration and the first node to be visited.
3053 * While this function requires RCU read locking, it doesn't require the
3054 * whole traversal to be contained in a single RCU critical section. This
3055 * function will return the correct next descendant as long as both @pos
3056 * and @root are accessible and @pos is a descendant of @root.
3058 struct cgroup_subsys_state *
3059 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3060 struct cgroup_subsys_state *root)
3062 struct cgroup_subsys_state *next;
3064 WARN_ON_ONCE(!rcu_read_lock_held());
3066 /* if first iteration, visit @root */
3067 if (!pos)
3068 return root;
3070 /* visit the first child if exists */
3071 next = css_next_child(NULL, pos);
3072 if (next)
3073 return next;
3075 /* no child, visit my or the closest ancestor's next sibling */
3076 while (pos != root) {
3077 next = css_next_child(pos, css_parent(pos));
3078 if (next)
3079 return next;
3080 pos = css_parent(pos);
3083 return NULL;
3085 EXPORT_SYMBOL_GPL(css_next_descendant_pre);
3088 * css_rightmost_descendant - return the rightmost descendant of a css
3089 * @pos: css of interest
3091 * Return the rightmost descendant of @pos. If there's no descendant, @pos
3092 * is returned. This can be used during pre-order traversal to skip
3093 * subtree of @pos.
3095 * While this function requires RCU read locking, it doesn't require the
3096 * whole traversal to be contained in a single RCU critical section. This
3097 * function will return the correct rightmost descendant as long as @pos is
3098 * accessible.
3100 struct cgroup_subsys_state *
3101 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3103 struct cgroup_subsys_state *last, *tmp;
3105 WARN_ON_ONCE(!rcu_read_lock_held());
3107 do {
3108 last = pos;
3109 /* ->prev isn't RCU safe, walk ->next till the end */
3110 pos = NULL;
3111 css_for_each_child(tmp, last)
3112 pos = tmp;
3113 } while (pos);
3115 return last;
3117 EXPORT_SYMBOL_GPL(css_rightmost_descendant);
3119 static struct cgroup_subsys_state *
3120 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3122 struct cgroup_subsys_state *last;
3124 do {
3125 last = pos;
3126 pos = css_next_child(NULL, pos);
3127 } while (pos);
3129 return last;
3133 * css_next_descendant_post - find the next descendant for post-order walk
3134 * @pos: the current position (%NULL to initiate traversal)
3135 * @root: css whose descendants to walk
3137 * To be used by css_for_each_descendant_post(). Find the next descendant
3138 * to visit for post-order traversal of @root's descendants. @root is
3139 * included in the iteration and the last node to be visited.
3141 * While this function requires RCU read locking, it doesn't require the
3142 * whole traversal to be contained in a single RCU critical section. This
3143 * function will return the correct next descendant as long as both @pos
3144 * and @cgroup are accessible and @pos is a descendant of @cgroup.
3146 struct cgroup_subsys_state *
3147 css_next_descendant_post(struct cgroup_subsys_state *pos,
3148 struct cgroup_subsys_state *root)
3150 struct cgroup_subsys_state *next;
3152 WARN_ON_ONCE(!rcu_read_lock_held());
3154 /* if first iteration, visit leftmost descendant which may be @root */
3155 if (!pos)
3156 return css_leftmost_descendant(root);
3158 /* if we visited @root, we're done */
3159 if (pos == root)
3160 return NULL;
3162 /* if there's an unvisited sibling, visit its leftmost descendant */
3163 next = css_next_child(pos, css_parent(pos));
3164 if (next)
3165 return css_leftmost_descendant(next);
3167 /* no sibling left, visit parent */
3168 return css_parent(pos);
3170 EXPORT_SYMBOL_GPL(css_next_descendant_post);
3173 * css_advance_task_iter - advance a task itererator to the next css_set
3174 * @it: the iterator to advance
3176 * Advance @it to the next css_set to walk.
3178 static void css_advance_task_iter(struct css_task_iter *it)
3180 struct list_head *l = it->cset_link;
3181 struct cgrp_cset_link *link;
3182 struct css_set *cset;
3184 /* Advance to the next non-empty css_set */
3185 do {
3186 l = l->next;
3187 if (l == &it->origin_css->cgroup->cset_links) {
3188 it->cset_link = NULL;
3189 return;
3191 link = list_entry(l, struct cgrp_cset_link, cset_link);
3192 cset = link->cset;
3193 } while (list_empty(&cset->tasks));
3194 it->cset_link = l;
3195 it->task = cset->tasks.next;
3199 * css_task_iter_start - initiate task iteration
3200 * @css: the css to walk tasks of
3201 * @it: the task iterator to use
3203 * Initiate iteration through the tasks of @css. The caller can call
3204 * css_task_iter_next() to walk through the tasks until the function
3205 * returns NULL. On completion of iteration, css_task_iter_end() must be
3206 * called.
3208 * Note that this function acquires a lock which is released when the
3209 * iteration finishes. The caller can't sleep while iteration is in
3210 * progress.
3212 void css_task_iter_start(struct cgroup_subsys_state *css,
3213 struct css_task_iter *it)
3214 __acquires(css_set_lock)
3217 * The first time anyone tries to iterate across a css, we need to
3218 * enable the list linking each css_set to its tasks, and fix up
3219 * all existing tasks.
3221 if (!use_task_css_set_links)
3222 cgroup_enable_task_cg_lists();
3224 read_lock(&css_set_lock);
3226 it->origin_css = css;
3227 it->cset_link = &css->cgroup->cset_links;
3229 css_advance_task_iter(it);
3233 * css_task_iter_next - return the next task for the iterator
3234 * @it: the task iterator being iterated
3236 * The "next" function for task iteration. @it should have been
3237 * initialized via css_task_iter_start(). Returns NULL when the iteration
3238 * reaches the end.
3240 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3242 struct task_struct *res;
3243 struct list_head *l = it->task;
3244 struct cgrp_cset_link *link;
3246 /* If the iterator cg is NULL, we have no tasks */
3247 if (!it->cset_link)
3248 return NULL;
3249 res = list_entry(l, struct task_struct, cg_list);
3250 /* Advance iterator to find next entry */
3251 l = l->next;
3252 link = list_entry(it->cset_link, struct cgrp_cset_link, cset_link);
3253 if (l == &link->cset->tasks) {
3255 * We reached the end of this task list - move on to the
3256 * next cgrp_cset_link.
3258 css_advance_task_iter(it);
3259 } else {
3260 it->task = l;
3262 return res;
3266 * css_task_iter_end - finish task iteration
3267 * @it: the task iterator to finish
3269 * Finish task iteration started by css_task_iter_start().
3271 void css_task_iter_end(struct css_task_iter *it)
3272 __releases(css_set_lock)
3274 read_unlock(&css_set_lock);
3277 static inline int started_after_time(struct task_struct *t1,
3278 struct timespec *time,
3279 struct task_struct *t2)
3281 int start_diff = timespec_compare(&t1->start_time, time);
3282 if (start_diff > 0) {
3283 return 1;
3284 } else if (start_diff < 0) {
3285 return 0;
3286 } else {
3288 * Arbitrarily, if two processes started at the same
3289 * time, we'll say that the lower pointer value
3290 * started first. Note that t2 may have exited by now
3291 * so this may not be a valid pointer any longer, but
3292 * that's fine - it still serves to distinguish
3293 * between two tasks started (effectively) simultaneously.
3295 return t1 > t2;
3300 * This function is a callback from heap_insert() and is used to order
3301 * the heap.
3302 * In this case we order the heap in descending task start time.
3304 static inline int started_after(void *p1, void *p2)
3306 struct task_struct *t1 = p1;
3307 struct task_struct *t2 = p2;
3308 return started_after_time(t1, &t2->start_time, t2);
3312 * css_scan_tasks - iterate though all the tasks in a css
3313 * @css: the css to iterate tasks of
3314 * @test: optional test callback
3315 * @process: process callback
3316 * @data: data passed to @test and @process
3317 * @heap: optional pre-allocated heap used for task iteration
3319 * Iterate through all the tasks in @css, calling @test for each, and if it
3320 * returns %true, call @process for it also.
3322 * @test may be NULL, meaning always true (select all tasks), which
3323 * effectively duplicates css_task_iter_{start,next,end}() but does not
3324 * lock css_set_lock for the call to @process.
3326 * It is guaranteed that @process will act on every task that is a member
3327 * of @css for the duration of this call. This function may or may not
3328 * call @process for tasks that exit or move to a different css during the
3329 * call, or are forked or move into the css during the call.
3331 * Note that @test may be called with locks held, and may in some
3332 * situations be called multiple times for the same task, so it should be
3333 * cheap.
3335 * If @heap is non-NULL, a heap has been pre-allocated and will be used for
3336 * heap operations (and its "gt" member will be overwritten), else a
3337 * temporary heap will be used (allocation of which may cause this function
3338 * to fail).
3340 int css_scan_tasks(struct cgroup_subsys_state *css,
3341 bool (*test)(struct task_struct *, void *),
3342 void (*process)(struct task_struct *, void *),
3343 void *data, struct ptr_heap *heap)
3345 int retval, i;
3346 struct css_task_iter it;
3347 struct task_struct *p, *dropped;
3348 /* Never dereference latest_task, since it's not refcounted */
3349 struct task_struct *latest_task = NULL;
3350 struct ptr_heap tmp_heap;
3351 struct timespec latest_time = { 0, 0 };
3353 if (heap) {
3354 /* The caller supplied our heap and pre-allocated its memory */
3355 heap->gt = &started_after;
3356 } else {
3357 /* We need to allocate our own heap memory */
3358 heap = &tmp_heap;
3359 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3360 if (retval)
3361 /* cannot allocate the heap */
3362 return retval;
3365 again:
3367 * Scan tasks in the css, using the @test callback to determine
3368 * which are of interest, and invoking @process callback on the
3369 * ones which need an update. Since we don't want to hold any
3370 * locks during the task updates, gather tasks to be processed in a
3371 * heap structure. The heap is sorted by descending task start
3372 * time. If the statically-sized heap fills up, we overflow tasks
3373 * that started later, and in future iterations only consider tasks
3374 * that started after the latest task in the previous pass. This
3375 * guarantees forward progress and that we don't miss any tasks.
3377 heap->size = 0;
3378 css_task_iter_start(css, &it);
3379 while ((p = css_task_iter_next(&it))) {
3381 * Only affect tasks that qualify per the caller's callback,
3382 * if he provided one
3384 if (test && !test(p, data))
3385 continue;
3387 * Only process tasks that started after the last task
3388 * we processed
3390 if (!started_after_time(p, &latest_time, latest_task))
3391 continue;
3392 dropped = heap_insert(heap, p);
3393 if (dropped == NULL) {
3395 * The new task was inserted; the heap wasn't
3396 * previously full
3398 get_task_struct(p);
3399 } else if (dropped != p) {
3401 * The new task was inserted, and pushed out a
3402 * different task
3404 get_task_struct(p);
3405 put_task_struct(dropped);
3408 * Else the new task was newer than anything already in
3409 * the heap and wasn't inserted
3412 css_task_iter_end(&it);
3414 if (heap->size) {
3415 for (i = 0; i < heap->size; i++) {
3416 struct task_struct *q = heap->ptrs[i];
3417 if (i == 0) {
3418 latest_time = q->start_time;
3419 latest_task = q;
3421 /* Process the task per the caller's callback */
3422 process(q, data);
3423 put_task_struct(q);
3426 * If we had to process any tasks at all, scan again
3427 * in case some of them were in the middle of forking
3428 * children that didn't get processed.
3429 * Not the most efficient way to do it, but it avoids
3430 * having to take callback_mutex in the fork path
3432 goto again;
3434 if (heap == &tmp_heap)
3435 heap_free(&tmp_heap);
3436 return 0;
3439 static void cgroup_transfer_one_task(struct task_struct *task, void *data)
3441 struct cgroup *new_cgroup = data;
3443 mutex_lock(&cgroup_mutex);
3444 cgroup_attach_task(new_cgroup, task, false);
3445 mutex_unlock(&cgroup_mutex);
3449 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3450 * @to: cgroup to which the tasks will be moved
3451 * @from: cgroup in which the tasks currently reside
3453 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3455 return css_scan_tasks(&from->dummy_css, NULL, cgroup_transfer_one_task,
3456 to, NULL);
3460 * Stuff for reading the 'tasks'/'procs' files.
3462 * Reading this file can return large amounts of data if a cgroup has
3463 * *lots* of attached tasks. So it may need several calls to read(),
3464 * but we cannot guarantee that the information we produce is correct
3465 * unless we produce it entirely atomically.
3469 /* which pidlist file are we talking about? */
3470 enum cgroup_filetype {
3471 CGROUP_FILE_PROCS,
3472 CGROUP_FILE_TASKS,
3476 * A pidlist is a list of pids that virtually represents the contents of one
3477 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3478 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3479 * to the cgroup.
3481 struct cgroup_pidlist {
3483 * used to find which pidlist is wanted. doesn't change as long as
3484 * this particular list stays in the list.
3486 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3487 /* array of xids */
3488 pid_t *list;
3489 /* how many elements the above list has */
3490 int length;
3491 /* how many files are using the current array */
3492 int use_count;
3493 /* each of these stored in a list by its cgroup */
3494 struct list_head links;
3495 /* pointer to the cgroup we belong to, for list removal purposes */
3496 struct cgroup *owner;
3497 /* protects the other fields */
3498 struct rw_semaphore rwsem;
3502 * The following two functions "fix" the issue where there are more pids
3503 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3504 * TODO: replace with a kernel-wide solution to this problem
3506 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3507 static void *pidlist_allocate(int count)
3509 if (PIDLIST_TOO_LARGE(count))
3510 return vmalloc(count * sizeof(pid_t));
3511 else
3512 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3514 static void pidlist_free(void *p)
3516 if (is_vmalloc_addr(p))
3517 vfree(p);
3518 else
3519 kfree(p);
3523 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3524 * Returns the number of unique elements.
3526 static int pidlist_uniq(pid_t *list, int length)
3528 int src, dest = 1;
3531 * we presume the 0th element is unique, so i starts at 1. trivial
3532 * edge cases first; no work needs to be done for either
3534 if (length == 0 || length == 1)
3535 return length;
3536 /* src and dest walk down the list; dest counts unique elements */
3537 for (src = 1; src < length; src++) {
3538 /* find next unique element */
3539 while (list[src] == list[src-1]) {
3540 src++;
3541 if (src == length)
3542 goto after;
3544 /* dest always points to where the next unique element goes */
3545 list[dest] = list[src];
3546 dest++;
3548 after:
3549 return dest;
3552 static int cmppid(const void *a, const void *b)
3554 return *(pid_t *)a - *(pid_t *)b;
3558 * find the appropriate pidlist for our purpose (given procs vs tasks)
3559 * returns with the lock on that pidlist already held, and takes care
3560 * of the use count, or returns NULL with no locks held if we're out of
3561 * memory.
3563 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3564 enum cgroup_filetype type)
3566 struct cgroup_pidlist *l;
3567 /* don't need task_nsproxy() if we're looking at ourself */
3568 struct pid_namespace *ns = task_active_pid_ns(current);
3571 * We can't drop the pidlist_mutex before taking the l->rwsem in case
3572 * the last ref-holder is trying to remove l from the list at the same
3573 * time. Holding the pidlist_mutex precludes somebody taking whichever
3574 * list we find out from under us - compare release_pid_array().
3576 mutex_lock(&cgrp->pidlist_mutex);
3577 list_for_each_entry(l, &cgrp->pidlists, links) {
3578 if (l->key.type == type && l->key.ns == ns) {
3579 /* make sure l doesn't vanish out from under us */
3580 down_write(&l->rwsem);
3581 mutex_unlock(&cgrp->pidlist_mutex);
3582 return l;
3585 /* entry not found; create a new one */
3586 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3587 if (!l) {
3588 mutex_unlock(&cgrp->pidlist_mutex);
3589 return l;
3591 init_rwsem(&l->rwsem);
3592 down_write(&l->rwsem);
3593 l->key.type = type;
3594 l->key.ns = get_pid_ns(ns);
3595 l->owner = cgrp;
3596 list_add(&l->links, &cgrp->pidlists);
3597 mutex_unlock(&cgrp->pidlist_mutex);
3598 return l;
3602 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3604 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3605 struct cgroup_pidlist **lp)
3607 pid_t *array;
3608 int length;
3609 int pid, n = 0; /* used for populating the array */
3610 struct css_task_iter it;
3611 struct task_struct *tsk;
3612 struct cgroup_pidlist *l;
3615 * If cgroup gets more users after we read count, we won't have
3616 * enough space - tough. This race is indistinguishable to the
3617 * caller from the case that the additional cgroup users didn't
3618 * show up until sometime later on.
3620 length = cgroup_task_count(cgrp);
3621 array = pidlist_allocate(length);
3622 if (!array)
3623 return -ENOMEM;
3624 /* now, populate the array */
3625 css_task_iter_start(&cgrp->dummy_css, &it);
3626 while ((tsk = css_task_iter_next(&it))) {
3627 if (unlikely(n == length))
3628 break;
3629 /* get tgid or pid for procs or tasks file respectively */
3630 if (type == CGROUP_FILE_PROCS)
3631 pid = task_tgid_vnr(tsk);
3632 else
3633 pid = task_pid_vnr(tsk);
3634 if (pid > 0) /* make sure to only use valid results */
3635 array[n++] = pid;
3637 css_task_iter_end(&it);
3638 length = n;
3639 /* now sort & (if procs) strip out duplicates */
3640 sort(array, length, sizeof(pid_t), cmppid, NULL);
3641 if (type == CGROUP_FILE_PROCS)
3642 length = pidlist_uniq(array, length);
3643 l = cgroup_pidlist_find(cgrp, type);
3644 if (!l) {
3645 pidlist_free(array);
3646 return -ENOMEM;
3648 /* store array, freeing old if necessary - lock already held */
3649 pidlist_free(l->list);
3650 l->list = array;
3651 l->length = length;
3652 l->use_count++;
3653 up_write(&l->rwsem);
3654 *lp = l;
3655 return 0;
3659 * cgroupstats_build - build and fill cgroupstats
3660 * @stats: cgroupstats to fill information into
3661 * @dentry: A dentry entry belonging to the cgroup for which stats have
3662 * been requested.
3664 * Build and fill cgroupstats so that taskstats can export it to user
3665 * space.
3667 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3669 int ret = -EINVAL;
3670 struct cgroup *cgrp;
3671 struct css_task_iter it;
3672 struct task_struct *tsk;
3675 * Validate dentry by checking the superblock operations,
3676 * and make sure it's a directory.
3678 if (dentry->d_sb->s_op != &cgroup_ops ||
3679 !S_ISDIR(dentry->d_inode->i_mode))
3680 goto err;
3682 ret = 0;
3683 cgrp = dentry->d_fsdata;
3685 css_task_iter_start(&cgrp->dummy_css, &it);
3686 while ((tsk = css_task_iter_next(&it))) {
3687 switch (tsk->state) {
3688 case TASK_RUNNING:
3689 stats->nr_running++;
3690 break;
3691 case TASK_INTERRUPTIBLE:
3692 stats->nr_sleeping++;
3693 break;
3694 case TASK_UNINTERRUPTIBLE:
3695 stats->nr_uninterruptible++;
3696 break;
3697 case TASK_STOPPED:
3698 stats->nr_stopped++;
3699 break;
3700 default:
3701 if (delayacct_is_task_waiting_on_io(tsk))
3702 stats->nr_io_wait++;
3703 break;
3706 css_task_iter_end(&it);
3708 err:
3709 return ret;
3714 * seq_file methods for the tasks/procs files. The seq_file position is the
3715 * next pid to display; the seq_file iterator is a pointer to the pid
3716 * in the cgroup->l->list array.
3719 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3722 * Initially we receive a position value that corresponds to
3723 * one more than the last pid shown (or 0 on the first call or
3724 * after a seek to the start). Use a binary-search to find the
3725 * next pid to display, if any
3727 struct cgroup_pidlist *l = s->private;
3728 int index = 0, pid = *pos;
3729 int *iter;
3731 down_read(&l->rwsem);
3732 if (pid) {
3733 int end = l->length;
3735 while (index < end) {
3736 int mid = (index + end) / 2;
3737 if (l->list[mid] == pid) {
3738 index = mid;
3739 break;
3740 } else if (l->list[mid] <= pid)
3741 index = mid + 1;
3742 else
3743 end = mid;
3746 /* If we're off the end of the array, we're done */
3747 if (index >= l->length)
3748 return NULL;
3749 /* Update the abstract position to be the actual pid that we found */
3750 iter = l->list + index;
3751 *pos = *iter;
3752 return iter;
3755 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3757 struct cgroup_pidlist *l = s->private;
3758 up_read(&l->rwsem);
3761 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3763 struct cgroup_pidlist *l = s->private;
3764 pid_t *p = v;
3765 pid_t *end = l->list + l->length;
3767 * Advance to the next pid in the array. If this goes off the
3768 * end, we're done
3770 p++;
3771 if (p >= end) {
3772 return NULL;
3773 } else {
3774 *pos = *p;
3775 return p;
3779 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3781 return seq_printf(s, "%d\n", *(int *)v);
3785 * seq_operations functions for iterating on pidlists through seq_file -
3786 * independent of whether it's tasks or procs
3788 static const struct seq_operations cgroup_pidlist_seq_operations = {
3789 .start = cgroup_pidlist_start,
3790 .stop = cgroup_pidlist_stop,
3791 .next = cgroup_pidlist_next,
3792 .show = cgroup_pidlist_show,
3795 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
3798 * the case where we're the last user of this particular pidlist will
3799 * have us remove it from the cgroup's list, which entails taking the
3800 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3801 * pidlist_mutex, we have to take pidlist_mutex first.
3803 mutex_lock(&l->owner->pidlist_mutex);
3804 down_write(&l->rwsem);
3805 BUG_ON(!l->use_count);
3806 if (!--l->use_count) {
3807 /* we're the last user if refcount is 0; remove and free */
3808 list_del(&l->links);
3809 mutex_unlock(&l->owner->pidlist_mutex);
3810 pidlist_free(l->list);
3811 put_pid_ns(l->key.ns);
3812 up_write(&l->rwsem);
3813 kfree(l);
3814 return;
3816 mutex_unlock(&l->owner->pidlist_mutex);
3817 up_write(&l->rwsem);
3820 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
3822 struct cgroup_pidlist *l;
3823 if (!(file->f_mode & FMODE_READ))
3824 return 0;
3826 * the seq_file will only be initialized if the file was opened for
3827 * reading; hence we check if it's not null only in that case.
3829 l = ((struct seq_file *)file->private_data)->private;
3830 cgroup_release_pid_array(l);
3831 return seq_release(inode, file);
3834 static const struct file_operations cgroup_pidlist_operations = {
3835 .read = seq_read,
3836 .llseek = seq_lseek,
3837 .write = cgroup_file_write,
3838 .release = cgroup_pidlist_release,
3842 * The following functions handle opens on a file that displays a pidlist
3843 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3844 * in the cgroup.
3846 /* helper function for the two below it */
3847 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
3849 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
3850 struct cgroup_pidlist *l;
3851 int retval;
3853 /* Nothing to do for write-only files */
3854 if (!(file->f_mode & FMODE_READ))
3855 return 0;
3857 /* have the array populated */
3858 retval = pidlist_array_load(cgrp, type, &l);
3859 if (retval)
3860 return retval;
3861 /* configure file information */
3862 file->f_op = &cgroup_pidlist_operations;
3864 retval = seq_open(file, &cgroup_pidlist_seq_operations);
3865 if (retval) {
3866 cgroup_release_pid_array(l);
3867 return retval;
3869 ((struct seq_file *)file->private_data)->private = l;
3870 return 0;
3872 static int cgroup_tasks_open(struct inode *unused, struct file *file)
3874 return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
3876 static int cgroup_procs_open(struct inode *unused, struct file *file)
3878 return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
3881 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3882 struct cftype *cft)
3884 return notify_on_release(css->cgroup);
3887 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3888 struct cftype *cft, u64 val)
3890 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3891 if (val)
3892 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3893 else
3894 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3895 return 0;
3899 * When dput() is called asynchronously, if umount has been done and
3900 * then deactivate_super() in cgroup_free_fn() kills the superblock,
3901 * there's a small window that vfs will see the root dentry with non-zero
3902 * refcnt and trigger BUG().
3904 * That's why we hold a reference before dput() and drop it right after.
3906 static void cgroup_dput(struct cgroup *cgrp)
3908 struct super_block *sb = cgrp->root->sb;
3910 atomic_inc(&sb->s_active);
3911 dput(cgrp->dentry);
3912 deactivate_super(sb);
3916 * Unregister event and free resources.
3918 * Gets called from workqueue.
3920 static void cgroup_event_remove(struct work_struct *work)
3922 struct cgroup_event *event = container_of(work, struct cgroup_event,
3923 remove);
3924 struct cgroup_subsys_state *css = event->css;
3926 remove_wait_queue(event->wqh, &event->wait);
3928 event->cft->unregister_event(css, event->cft, event->eventfd);
3930 /* Notify userspace the event is going away. */
3931 eventfd_signal(event->eventfd, 1);
3933 eventfd_ctx_put(event->eventfd);
3934 kfree(event);
3935 css_put(css);
3939 * Gets called on POLLHUP on eventfd when user closes it.
3941 * Called with wqh->lock held and interrupts disabled.
3943 static int cgroup_event_wake(wait_queue_t *wait, unsigned mode,
3944 int sync, void *key)
3946 struct cgroup_event *event = container_of(wait,
3947 struct cgroup_event, wait);
3948 struct cgroup *cgrp = event->css->cgroup;
3949 unsigned long flags = (unsigned long)key;
3951 if (flags & POLLHUP) {
3953 * If the event has been detached at cgroup removal, we
3954 * can simply return knowing the other side will cleanup
3955 * for us.
3957 * We can't race against event freeing since the other
3958 * side will require wqh->lock via remove_wait_queue(),
3959 * which we hold.
3961 spin_lock(&cgrp->event_list_lock);
3962 if (!list_empty(&event->list)) {
3963 list_del_init(&event->list);
3965 * We are in atomic context, but cgroup_event_remove()
3966 * may sleep, so we have to call it in workqueue.
3968 schedule_work(&event->remove);
3970 spin_unlock(&cgrp->event_list_lock);
3973 return 0;
3976 static void cgroup_event_ptable_queue_proc(struct file *file,
3977 wait_queue_head_t *wqh, poll_table *pt)
3979 struct cgroup_event *event = container_of(pt,
3980 struct cgroup_event, pt);
3982 event->wqh = wqh;
3983 add_wait_queue(wqh, &event->wait);
3987 * Parse input and register new cgroup event handler.
3989 * Input must be in format '<event_fd> <control_fd> <args>'.
3990 * Interpretation of args is defined by control file implementation.
3992 static int cgroup_write_event_control(struct cgroup_subsys_state *dummy_css,
3993 struct cftype *cft, const char *buffer)
3995 struct cgroup *cgrp = dummy_css->cgroup;
3996 struct cgroup_event *event;
3997 struct cgroup_subsys_state *cfile_css;
3998 unsigned int efd, cfd;
3999 struct fd efile;
4000 struct fd cfile;
4001 char *endp;
4002 int ret;
4004 efd = simple_strtoul(buffer, &endp, 10);
4005 if (*endp != ' ')
4006 return -EINVAL;
4007 buffer = endp + 1;
4009 cfd = simple_strtoul(buffer, &endp, 10);
4010 if ((*endp != ' ') && (*endp != '\0'))
4011 return -EINVAL;
4012 buffer = endp + 1;
4014 event = kzalloc(sizeof(*event), GFP_KERNEL);
4015 if (!event)
4016 return -ENOMEM;
4018 INIT_LIST_HEAD(&event->list);
4019 init_poll_funcptr(&event->pt, cgroup_event_ptable_queue_proc);
4020 init_waitqueue_func_entry(&event->wait, cgroup_event_wake);
4021 INIT_WORK(&event->remove, cgroup_event_remove);
4023 efile = fdget(efd);
4024 if (!efile.file) {
4025 ret = -EBADF;
4026 goto out_kfree;
4029 event->eventfd = eventfd_ctx_fileget(efile.file);
4030 if (IS_ERR(event->eventfd)) {
4031 ret = PTR_ERR(event->eventfd);
4032 goto out_put_efile;
4035 cfile = fdget(cfd);
4036 if (!cfile.file) {
4037 ret = -EBADF;
4038 goto out_put_eventfd;
4041 /* the process need read permission on control file */
4042 /* AV: shouldn't we check that it's been opened for read instead? */
4043 ret = inode_permission(file_inode(cfile.file), MAY_READ);
4044 if (ret < 0)
4045 goto out_put_cfile;
4047 event->cft = __file_cft(cfile.file);
4048 if (IS_ERR(event->cft)) {
4049 ret = PTR_ERR(event->cft);
4050 goto out_put_cfile;
4053 if (!event->cft->ss) {
4054 ret = -EBADF;
4055 goto out_put_cfile;
4059 * Determine the css of @cfile, verify it belongs to the same
4060 * cgroup as cgroup.event_control, and associate @event with it.
4061 * Remaining events are automatically removed on cgroup destruction
4062 * but the removal is asynchronous, so take an extra ref.
4064 rcu_read_lock();
4066 ret = -EINVAL;
4067 event->css = cgroup_css(cgrp, event->cft->ss);
4068 cfile_css = css_from_dir(cfile.file->f_dentry->d_parent, event->cft->ss);
4069 if (event->css && event->css == cfile_css && css_tryget(event->css))
4070 ret = 0;
4072 rcu_read_unlock();
4073 if (ret)
4074 goto out_put_cfile;
4076 if (!event->cft->register_event || !event->cft->unregister_event) {
4077 ret = -EINVAL;
4078 goto out_put_css;
4081 ret = event->cft->register_event(event->css, event->cft,
4082 event->eventfd, buffer);
4083 if (ret)
4084 goto out_put_css;
4086 efile.file->f_op->poll(efile.file, &event->pt);
4088 spin_lock(&cgrp->event_list_lock);
4089 list_add(&event->list, &cgrp->event_list);
4090 spin_unlock(&cgrp->event_list_lock);
4092 fdput(cfile);
4093 fdput(efile);
4095 return 0;
4097 out_put_css:
4098 css_put(event->css);
4099 out_put_cfile:
4100 fdput(cfile);
4101 out_put_eventfd:
4102 eventfd_ctx_put(event->eventfd);
4103 out_put_efile:
4104 fdput(efile);
4105 out_kfree:
4106 kfree(event);
4108 return ret;
4111 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
4112 struct cftype *cft)
4114 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4117 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
4118 struct cftype *cft, u64 val)
4120 if (val)
4121 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4122 else
4123 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4124 return 0;
4127 static struct cftype cgroup_base_files[] = {
4129 .name = "cgroup.procs",
4130 .open = cgroup_procs_open,
4131 .write_u64 = cgroup_procs_write,
4132 .release = cgroup_pidlist_release,
4133 .mode = S_IRUGO | S_IWUSR,
4136 .name = "cgroup.event_control",
4137 .write_string = cgroup_write_event_control,
4138 .mode = S_IWUGO,
4141 .name = "cgroup.clone_children",
4142 .flags = CFTYPE_INSANE,
4143 .read_u64 = cgroup_clone_children_read,
4144 .write_u64 = cgroup_clone_children_write,
4147 .name = "cgroup.sane_behavior",
4148 .flags = CFTYPE_ONLY_ON_ROOT,
4149 .read_seq_string = cgroup_sane_behavior_show,
4153 * Historical crazy stuff. These don't have "cgroup." prefix and
4154 * don't exist if sane_behavior. If you're depending on these, be
4155 * prepared to be burned.
4158 .name = "tasks",
4159 .flags = CFTYPE_INSANE, /* use "procs" instead */
4160 .open = cgroup_tasks_open,
4161 .write_u64 = cgroup_tasks_write,
4162 .release = cgroup_pidlist_release,
4163 .mode = S_IRUGO | S_IWUSR,
4166 .name = "notify_on_release",
4167 .flags = CFTYPE_INSANE,
4168 .read_u64 = cgroup_read_notify_on_release,
4169 .write_u64 = cgroup_write_notify_on_release,
4172 .name = "release_agent",
4173 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
4174 .read_seq_string = cgroup_release_agent_show,
4175 .write_string = cgroup_release_agent_write,
4176 .max_write_len = PATH_MAX,
4178 { } /* terminate */
4182 * cgroup_populate_dir - create subsys files in a cgroup directory
4183 * @cgrp: target cgroup
4184 * @subsys_mask: mask of the subsystem ids whose files should be added
4186 * On failure, no file is added.
4188 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
4190 struct cgroup_subsys *ss;
4191 int i, ret = 0;
4193 /* process cftsets of each subsystem */
4194 for_each_subsys(ss, i) {
4195 struct cftype_set *set;
4197 if (!test_bit(i, &subsys_mask))
4198 continue;
4200 list_for_each_entry(set, &ss->cftsets, node) {
4201 ret = cgroup_addrm_files(cgrp, set->cfts, true);
4202 if (ret < 0)
4203 goto err;
4206 return 0;
4207 err:
4208 cgroup_clear_dir(cgrp, subsys_mask);
4209 return ret;
4213 * css destruction is four-stage process.
4215 * 1. Destruction starts. Killing of the percpu_ref is initiated.
4216 * Implemented in kill_css().
4218 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4219 * and thus css_tryget() is guaranteed to fail, the css can be offlined
4220 * by invoking offline_css(). After offlining, the base ref is put.
4221 * Implemented in css_killed_work_fn().
4223 * 3. When the percpu_ref reaches zero, the only possible remaining
4224 * accessors are inside RCU read sections. css_release() schedules the
4225 * RCU callback.
4227 * 4. After the grace period, the css can be freed. Implemented in
4228 * css_free_work_fn().
4230 * It is actually hairier because both step 2 and 4 require process context
4231 * and thus involve punting to css->destroy_work adding two additional
4232 * steps to the already complex sequence.
4234 static void css_free_work_fn(struct work_struct *work)
4236 struct cgroup_subsys_state *css =
4237 container_of(work, struct cgroup_subsys_state, destroy_work);
4238 struct cgroup *cgrp = css->cgroup;
4240 if (css->parent)
4241 css_put(css->parent);
4243 css->ss->css_free(css);
4244 cgroup_dput(cgrp);
4247 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4249 struct cgroup_subsys_state *css =
4250 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4253 * css holds an extra ref to @cgrp->dentry which is put on the last
4254 * css_put(). dput() requires process context which we don't have.
4256 INIT_WORK(&css->destroy_work, css_free_work_fn);
4257 schedule_work(&css->destroy_work);
4260 static void css_release(struct percpu_ref *ref)
4262 struct cgroup_subsys_state *css =
4263 container_of(ref, struct cgroup_subsys_state, refcnt);
4265 call_rcu(&css->rcu_head, css_free_rcu_fn);
4268 static void init_css(struct cgroup_subsys_state *css, struct cgroup_subsys *ss,
4269 struct cgroup *cgrp)
4271 css->cgroup = cgrp;
4272 css->ss = ss;
4273 css->flags = 0;
4275 if (cgrp->parent)
4276 css->parent = cgroup_css(cgrp->parent, ss);
4277 else
4278 css->flags |= CSS_ROOT;
4280 BUG_ON(cgroup_css(cgrp, ss));
4283 /* invoke ->css_online() on a new CSS and mark it online if successful */
4284 static int online_css(struct cgroup_subsys_state *css)
4286 struct cgroup_subsys *ss = css->ss;
4287 int ret = 0;
4289 lockdep_assert_held(&cgroup_mutex);
4291 if (ss->css_online)
4292 ret = ss->css_online(css);
4293 if (!ret) {
4294 css->flags |= CSS_ONLINE;
4295 css->cgroup->nr_css++;
4296 rcu_assign_pointer(css->cgroup->subsys[ss->subsys_id], css);
4298 return ret;
4301 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4302 static void offline_css(struct cgroup_subsys_state *css)
4304 struct cgroup_subsys *ss = css->ss;
4306 lockdep_assert_held(&cgroup_mutex);
4308 if (!(css->flags & CSS_ONLINE))
4309 return;
4311 if (ss->css_offline)
4312 ss->css_offline(css);
4314 css->flags &= ~CSS_ONLINE;
4315 css->cgroup->nr_css--;
4316 RCU_INIT_POINTER(css->cgroup->subsys[ss->subsys_id], css);
4320 * cgroup_create - create a cgroup
4321 * @parent: cgroup that will be parent of the new cgroup
4322 * @dentry: dentry of the new cgroup
4323 * @mode: mode to set on new inode
4325 * Must be called with the mutex on the parent inode held
4327 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4328 umode_t mode)
4330 struct cgroup_subsys_state *css_ar[CGROUP_SUBSYS_COUNT] = { };
4331 struct cgroup *cgrp;
4332 struct cgroup_name *name;
4333 struct cgroupfs_root *root = parent->root;
4334 int err = 0;
4335 struct cgroup_subsys *ss;
4336 struct super_block *sb = root->sb;
4338 /* allocate the cgroup and its ID, 0 is reserved for the root */
4339 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4340 if (!cgrp)
4341 return -ENOMEM;
4343 name = cgroup_alloc_name(dentry);
4344 if (!name)
4345 goto err_free_cgrp;
4346 rcu_assign_pointer(cgrp->name, name);
4349 * Temporarily set the pointer to NULL, so idr_find() won't return
4350 * a half-baked cgroup.
4352 cgrp->id = idr_alloc(&root->cgroup_idr, NULL, 1, 0, GFP_KERNEL);
4353 if (cgrp->id < 0)
4354 goto err_free_name;
4357 * Only live parents can have children. Note that the liveliness
4358 * check isn't strictly necessary because cgroup_mkdir() and
4359 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4360 * anyway so that locking is contained inside cgroup proper and we
4361 * don't get nasty surprises if we ever grow another caller.
4363 if (!cgroup_lock_live_group(parent)) {
4364 err = -ENODEV;
4365 goto err_free_id;
4368 /* Grab a reference on the superblock so the hierarchy doesn't
4369 * get deleted on unmount if there are child cgroups. This
4370 * can be done outside cgroup_mutex, since the sb can't
4371 * disappear while someone has an open control file on the
4372 * fs */
4373 atomic_inc(&sb->s_active);
4375 init_cgroup_housekeeping(cgrp);
4377 dentry->d_fsdata = cgrp;
4378 cgrp->dentry = dentry;
4380 cgrp->parent = parent;
4381 cgrp->dummy_css.parent = &parent->dummy_css;
4382 cgrp->root = parent->root;
4384 if (notify_on_release(parent))
4385 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4387 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4388 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4390 for_each_root_subsys(root, ss) {
4391 struct cgroup_subsys_state *css;
4393 css = ss->css_alloc(cgroup_css(parent, ss));
4394 if (IS_ERR(css)) {
4395 err = PTR_ERR(css);
4396 goto err_free_all;
4398 css_ar[ss->subsys_id] = css;
4400 err = percpu_ref_init(&css->refcnt, css_release);
4401 if (err)
4402 goto err_free_all;
4404 init_css(css, ss, cgrp);
4408 * Create directory. cgroup_create_file() returns with the new
4409 * directory locked on success so that it can be populated without
4410 * dropping cgroup_mutex.
4412 err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4413 if (err < 0)
4414 goto err_free_all;
4415 lockdep_assert_held(&dentry->d_inode->i_mutex);
4417 cgrp->serial_nr = cgroup_serial_nr_next++;
4419 /* allocation complete, commit to creation */
4420 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4421 root->number_of_cgroups++;
4423 /* each css holds a ref to the cgroup's dentry and the parent css */
4424 for_each_root_subsys(root, ss) {
4425 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4427 dget(dentry);
4428 css_get(css->parent);
4431 /* hold a ref to the parent's dentry */
4432 dget(parent->dentry);
4434 /* creation succeeded, notify subsystems */
4435 for_each_root_subsys(root, ss) {
4436 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4438 err = online_css(css);
4439 if (err)
4440 goto err_destroy;
4442 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4443 parent->parent) {
4444 pr_warning("cgroup: %s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4445 current->comm, current->pid, ss->name);
4446 if (!strcmp(ss->name, "memory"))
4447 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4448 ss->warned_broken_hierarchy = true;
4452 idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4454 err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
4455 if (err)
4456 goto err_destroy;
4458 err = cgroup_populate_dir(cgrp, root->subsys_mask);
4459 if (err)
4460 goto err_destroy;
4462 mutex_unlock(&cgroup_mutex);
4463 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4465 return 0;
4467 err_free_all:
4468 for_each_root_subsys(root, ss) {
4469 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4471 if (css) {
4472 percpu_ref_cancel_init(&css->refcnt);
4473 ss->css_free(css);
4476 mutex_unlock(&cgroup_mutex);
4477 /* Release the reference count that we took on the superblock */
4478 deactivate_super(sb);
4479 err_free_id:
4480 idr_remove(&root->cgroup_idr, cgrp->id);
4481 err_free_name:
4482 kfree(rcu_dereference_raw(cgrp->name));
4483 err_free_cgrp:
4484 kfree(cgrp);
4485 return err;
4487 err_destroy:
4488 cgroup_destroy_locked(cgrp);
4489 mutex_unlock(&cgroup_mutex);
4490 mutex_unlock(&dentry->d_inode->i_mutex);
4491 return err;
4494 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4496 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4498 /* the vfs holds inode->i_mutex already */
4499 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4503 * This is called when the refcnt of a css is confirmed to be killed.
4504 * css_tryget() is now guaranteed to fail.
4506 static void css_killed_work_fn(struct work_struct *work)
4508 struct cgroup_subsys_state *css =
4509 container_of(work, struct cgroup_subsys_state, destroy_work);
4510 struct cgroup *cgrp = css->cgroup;
4512 mutex_lock(&cgroup_mutex);
4515 * css_tryget() is guaranteed to fail now. Tell subsystems to
4516 * initate destruction.
4518 offline_css(css);
4521 * If @cgrp is marked dead, it's waiting for refs of all css's to
4522 * be disabled before proceeding to the second phase of cgroup
4523 * destruction. If we are the last one, kick it off.
4525 if (!cgrp->nr_css && cgroup_is_dead(cgrp))
4526 cgroup_destroy_css_killed(cgrp);
4528 mutex_unlock(&cgroup_mutex);
4531 * Put the css refs from kill_css(). Each css holds an extra
4532 * reference to the cgroup's dentry and cgroup removal proceeds
4533 * regardless of css refs. On the last put of each css, whenever
4534 * that may be, the extra dentry ref is put so that dentry
4535 * destruction happens only after all css's are released.
4537 css_put(css);
4540 /* css kill confirmation processing requires process context, bounce */
4541 static void css_killed_ref_fn(struct percpu_ref *ref)
4543 struct cgroup_subsys_state *css =
4544 container_of(ref, struct cgroup_subsys_state, refcnt);
4546 INIT_WORK(&css->destroy_work, css_killed_work_fn);
4547 schedule_work(&css->destroy_work);
4551 * kill_css - destroy a css
4552 * @css: css to destroy
4554 * This function initiates destruction of @css by removing cgroup interface
4555 * files and putting its base reference. ->css_offline() will be invoked
4556 * asynchronously once css_tryget() is guaranteed to fail and when the
4557 * reference count reaches zero, @css will be released.
4559 static void kill_css(struct cgroup_subsys_state *css)
4561 cgroup_clear_dir(css->cgroup, 1 << css->ss->subsys_id);
4564 * Killing would put the base ref, but we need to keep it alive
4565 * until after ->css_offline().
4567 css_get(css);
4570 * cgroup core guarantees that, by the time ->css_offline() is
4571 * invoked, no new css reference will be given out via
4572 * css_tryget(). We can't simply call percpu_ref_kill() and
4573 * proceed to offlining css's because percpu_ref_kill() doesn't
4574 * guarantee that the ref is seen as killed on all CPUs on return.
4576 * Use percpu_ref_kill_and_confirm() to get notifications as each
4577 * css is confirmed to be seen as killed on all CPUs.
4579 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4583 * cgroup_destroy_locked - the first stage of cgroup destruction
4584 * @cgrp: cgroup to be destroyed
4586 * css's make use of percpu refcnts whose killing latency shouldn't be
4587 * exposed to userland and are RCU protected. Also, cgroup core needs to
4588 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
4589 * invoked. To satisfy all the requirements, destruction is implemented in
4590 * the following two steps.
4592 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
4593 * userland visible parts and start killing the percpu refcnts of
4594 * css's. Set up so that the next stage will be kicked off once all
4595 * the percpu refcnts are confirmed to be killed.
4597 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4598 * rest of destruction. Once all cgroup references are gone, the
4599 * cgroup is RCU-freed.
4601 * This function implements s1. After this step, @cgrp is gone as far as
4602 * the userland is concerned and a new cgroup with the same name may be
4603 * created. As cgroup doesn't care about the names internally, this
4604 * doesn't cause any problem.
4606 static int cgroup_destroy_locked(struct cgroup *cgrp)
4607 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4609 struct dentry *d = cgrp->dentry;
4610 struct cgroup_event *event, *tmp;
4611 struct cgroup_subsys *ss;
4612 struct cgroup *child;
4613 bool empty;
4615 lockdep_assert_held(&d->d_inode->i_mutex);
4616 lockdep_assert_held(&cgroup_mutex);
4619 * css_set_lock synchronizes access to ->cset_links and prevents
4620 * @cgrp from being removed while __put_css_set() is in progress.
4622 read_lock(&css_set_lock);
4623 empty = list_empty(&cgrp->cset_links);
4624 read_unlock(&css_set_lock);
4625 if (!empty)
4626 return -EBUSY;
4629 * Make sure there's no live children. We can't test ->children
4630 * emptiness as dead children linger on it while being destroyed;
4631 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
4633 empty = true;
4634 rcu_read_lock();
4635 list_for_each_entry_rcu(child, &cgrp->children, sibling) {
4636 empty = cgroup_is_dead(child);
4637 if (!empty)
4638 break;
4640 rcu_read_unlock();
4641 if (!empty)
4642 return -EBUSY;
4645 * Initiate massacre of all css's. cgroup_destroy_css_killed()
4646 * will be invoked to perform the rest of destruction once the
4647 * percpu refs of all css's are confirmed to be killed.
4649 for_each_root_subsys(cgrp->root, ss)
4650 kill_css(cgroup_css(cgrp, ss));
4653 * Mark @cgrp dead. This prevents further task migration and child
4654 * creation by disabling cgroup_lock_live_group(). Note that
4655 * CGRP_DEAD assertion is depended upon by css_next_child() to
4656 * resume iteration after dropping RCU read lock. See
4657 * css_next_child() for details.
4659 set_bit(CGRP_DEAD, &cgrp->flags);
4661 /* CGRP_DEAD is set, remove from ->release_list for the last time */
4662 raw_spin_lock(&release_list_lock);
4663 if (!list_empty(&cgrp->release_list))
4664 list_del_init(&cgrp->release_list);
4665 raw_spin_unlock(&release_list_lock);
4668 * If @cgrp has css's attached, the second stage of cgroup
4669 * destruction is kicked off from css_killed_work_fn() after the
4670 * refs of all attached css's are killed. If @cgrp doesn't have
4671 * any css, we kick it off here.
4673 if (!cgrp->nr_css)
4674 cgroup_destroy_css_killed(cgrp);
4677 * Clear the base files and remove @cgrp directory. The removal
4678 * puts the base ref but we aren't quite done with @cgrp yet, so
4679 * hold onto it.
4681 cgroup_addrm_files(cgrp, cgroup_base_files, false);
4682 dget(d);
4683 cgroup_d_remove_dir(d);
4686 * Unregister events and notify userspace.
4687 * Notify userspace about cgroup removing only after rmdir of cgroup
4688 * directory to avoid race between userspace and kernelspace.
4690 spin_lock(&cgrp->event_list_lock);
4691 list_for_each_entry_safe(event, tmp, &cgrp->event_list, list) {
4692 list_del_init(&event->list);
4693 schedule_work(&event->remove);
4695 spin_unlock(&cgrp->event_list_lock);
4697 return 0;
4701 * cgroup_destroy_css_killed - the second step of cgroup destruction
4702 * @work: cgroup->destroy_free_work
4704 * This function is invoked from a work item for a cgroup which is being
4705 * destroyed after all css's are offlined and performs the rest of
4706 * destruction. This is the second step of destruction described in the
4707 * comment above cgroup_destroy_locked().
4709 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
4711 struct cgroup *parent = cgrp->parent;
4712 struct dentry *d = cgrp->dentry;
4714 lockdep_assert_held(&cgroup_mutex);
4716 /* delete this cgroup from parent->children */
4717 list_del_rcu(&cgrp->sibling);
4720 * We should remove the cgroup object from idr before its grace
4721 * period starts, so we won't be looking up a cgroup while the
4722 * cgroup is being freed.
4724 idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4725 cgrp->id = -1;
4727 dput(d);
4729 set_bit(CGRP_RELEASABLE, &parent->flags);
4730 check_for_release(parent);
4733 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4735 int ret;
4737 mutex_lock(&cgroup_mutex);
4738 ret = cgroup_destroy_locked(dentry->d_fsdata);
4739 mutex_unlock(&cgroup_mutex);
4741 return ret;
4744 static void __init_or_module cgroup_init_cftsets(struct cgroup_subsys *ss)
4746 INIT_LIST_HEAD(&ss->cftsets);
4749 * base_cftset is embedded in subsys itself, no need to worry about
4750 * deregistration.
4752 if (ss->base_cftypes) {
4753 struct cftype *cft;
4755 for (cft = ss->base_cftypes; cft->name[0] != '\0'; cft++)
4756 cft->ss = ss;
4758 ss->base_cftset.cfts = ss->base_cftypes;
4759 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4763 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4765 struct cgroup_subsys_state *css;
4767 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4769 mutex_lock(&cgroup_mutex);
4771 /* init base cftset */
4772 cgroup_init_cftsets(ss);
4774 /* Create the top cgroup state for this subsystem */
4775 list_add(&ss->sibling, &cgroup_dummy_root.subsys_list);
4776 ss->root = &cgroup_dummy_root;
4777 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
4778 /* We don't handle early failures gracefully */
4779 BUG_ON(IS_ERR(css));
4780 init_css(css, ss, cgroup_dummy_top);
4782 /* Update the init_css_set to contain a subsys
4783 * pointer to this state - since the subsystem is
4784 * newly registered, all tasks and hence the
4785 * init_css_set is in the subsystem's top cgroup. */
4786 init_css_set.subsys[ss->subsys_id] = css;
4788 need_forkexit_callback |= ss->fork || ss->exit;
4790 /* At system boot, before all subsystems have been
4791 * registered, no tasks have been forked, so we don't
4792 * need to invoke fork callbacks here. */
4793 BUG_ON(!list_empty(&init_task.tasks));
4795 BUG_ON(online_css(css));
4797 mutex_unlock(&cgroup_mutex);
4799 /* this function shouldn't be used with modular subsystems, since they
4800 * need to register a subsys_id, among other things */
4801 BUG_ON(ss->module);
4805 * cgroup_load_subsys: load and register a modular subsystem at runtime
4806 * @ss: the subsystem to load
4808 * This function should be called in a modular subsystem's initcall. If the
4809 * subsystem is built as a module, it will be assigned a new subsys_id and set
4810 * up for use. If the subsystem is built-in anyway, work is delegated to the
4811 * simpler cgroup_init_subsys.
4813 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
4815 struct cgroup_subsys_state *css;
4816 int i, ret;
4817 struct hlist_node *tmp;
4818 struct css_set *cset;
4819 unsigned long key;
4821 /* check name and function validity */
4822 if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
4823 ss->css_alloc == NULL || ss->css_free == NULL)
4824 return -EINVAL;
4827 * we don't support callbacks in modular subsystems. this check is
4828 * before the ss->module check for consistency; a subsystem that could
4829 * be a module should still have no callbacks even if the user isn't
4830 * compiling it as one.
4832 if (ss->fork || ss->exit)
4833 return -EINVAL;
4836 * an optionally modular subsystem is built-in: we want to do nothing,
4837 * since cgroup_init_subsys will have already taken care of it.
4839 if (ss->module == NULL) {
4840 /* a sanity check */
4841 BUG_ON(cgroup_subsys[ss->subsys_id] != ss);
4842 return 0;
4845 /* init base cftset */
4846 cgroup_init_cftsets(ss);
4848 mutex_lock(&cgroup_mutex);
4849 cgroup_subsys[ss->subsys_id] = ss;
4852 * no ss->css_alloc seems to need anything important in the ss
4853 * struct, so this can happen first (i.e. before the dummy root
4854 * attachment).
4856 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
4857 if (IS_ERR(css)) {
4858 /* failure case - need to deassign the cgroup_subsys[] slot. */
4859 cgroup_subsys[ss->subsys_id] = NULL;
4860 mutex_unlock(&cgroup_mutex);
4861 return PTR_ERR(css);
4864 list_add(&ss->sibling, &cgroup_dummy_root.subsys_list);
4865 ss->root = &cgroup_dummy_root;
4867 /* our new subsystem will be attached to the dummy hierarchy. */
4868 init_css(css, ss, cgroup_dummy_top);
4871 * Now we need to entangle the css into the existing css_sets. unlike
4872 * in cgroup_init_subsys, there are now multiple css_sets, so each one
4873 * will need a new pointer to it; done by iterating the css_set_table.
4874 * furthermore, modifying the existing css_sets will corrupt the hash
4875 * table state, so each changed css_set will need its hash recomputed.
4876 * this is all done under the css_set_lock.
4878 write_lock(&css_set_lock);
4879 hash_for_each_safe(css_set_table, i, tmp, cset, hlist) {
4880 /* skip entries that we already rehashed */
4881 if (cset->subsys[ss->subsys_id])
4882 continue;
4883 /* remove existing entry */
4884 hash_del(&cset->hlist);
4885 /* set new value */
4886 cset->subsys[ss->subsys_id] = css;
4887 /* recompute hash and restore entry */
4888 key = css_set_hash(cset->subsys);
4889 hash_add(css_set_table, &cset->hlist, key);
4891 write_unlock(&css_set_lock);
4893 ret = online_css(css);
4894 if (ret)
4895 goto err_unload;
4897 /* success! */
4898 mutex_unlock(&cgroup_mutex);
4899 return 0;
4901 err_unload:
4902 mutex_unlock(&cgroup_mutex);
4903 /* @ss can't be mounted here as try_module_get() would fail */
4904 cgroup_unload_subsys(ss);
4905 return ret;
4907 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
4910 * cgroup_unload_subsys: unload a modular subsystem
4911 * @ss: the subsystem to unload
4913 * This function should be called in a modular subsystem's exitcall. When this
4914 * function is invoked, the refcount on the subsystem's module will be 0, so
4915 * the subsystem will not be attached to any hierarchy.
4917 void cgroup_unload_subsys(struct cgroup_subsys *ss)
4919 struct cgrp_cset_link *link;
4921 BUG_ON(ss->module == NULL);
4924 * we shouldn't be called if the subsystem is in use, and the use of
4925 * try_module_get() in rebind_subsystems() should ensure that it
4926 * doesn't start being used while we're killing it off.
4928 BUG_ON(ss->root != &cgroup_dummy_root);
4930 mutex_lock(&cgroup_mutex);
4932 offline_css(cgroup_css(cgroup_dummy_top, ss));
4934 /* deassign the subsys_id */
4935 cgroup_subsys[ss->subsys_id] = NULL;
4937 /* remove subsystem from the dummy root's list of subsystems */
4938 list_del_init(&ss->sibling);
4941 * disentangle the css from all css_sets attached to the dummy
4942 * top. as in loading, we need to pay our respects to the hashtable
4943 * gods.
4945 write_lock(&css_set_lock);
4946 list_for_each_entry(link, &cgroup_dummy_top->cset_links, cset_link) {
4947 struct css_set *cset = link->cset;
4948 unsigned long key;
4950 hash_del(&cset->hlist);
4951 cset->subsys[ss->subsys_id] = NULL;
4952 key = css_set_hash(cset->subsys);
4953 hash_add(css_set_table, &cset->hlist, key);
4955 write_unlock(&css_set_lock);
4958 * remove subsystem's css from the cgroup_dummy_top and free it -
4959 * need to free before marking as null because ss->css_free needs
4960 * the cgrp->subsys pointer to find their state.
4962 ss->css_free(cgroup_css(cgroup_dummy_top, ss));
4963 RCU_INIT_POINTER(cgroup_dummy_top->subsys[ss->subsys_id], NULL);
4965 mutex_unlock(&cgroup_mutex);
4967 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
4970 * cgroup_init_early - cgroup initialization at system boot
4972 * Initialize cgroups at system boot, and initialize any
4973 * subsystems that request early init.
4975 int __init cgroup_init_early(void)
4977 struct cgroup_subsys *ss;
4978 int i;
4980 atomic_set(&init_css_set.refcount, 1);
4981 INIT_LIST_HEAD(&init_css_set.cgrp_links);
4982 INIT_LIST_HEAD(&init_css_set.tasks);
4983 INIT_HLIST_NODE(&init_css_set.hlist);
4984 css_set_count = 1;
4985 init_cgroup_root(&cgroup_dummy_root);
4986 cgroup_root_count = 1;
4987 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4989 init_cgrp_cset_link.cset = &init_css_set;
4990 init_cgrp_cset_link.cgrp = cgroup_dummy_top;
4991 list_add(&init_cgrp_cset_link.cset_link, &cgroup_dummy_top->cset_links);
4992 list_add(&init_cgrp_cset_link.cgrp_link, &init_css_set.cgrp_links);
4994 /* at bootup time, we don't worry about modular subsystems */
4995 for_each_builtin_subsys(ss, i) {
4996 BUG_ON(!ss->name);
4997 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
4998 BUG_ON(!ss->css_alloc);
4999 BUG_ON(!ss->css_free);
5000 if (ss->subsys_id != i) {
5001 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
5002 ss->name, ss->subsys_id);
5003 BUG();
5006 if (ss->early_init)
5007 cgroup_init_subsys(ss);
5009 return 0;
5013 * cgroup_init - cgroup initialization
5015 * Register cgroup filesystem and /proc file, and initialize
5016 * any subsystems that didn't request early init.
5018 int __init cgroup_init(void)
5020 struct cgroup_subsys *ss;
5021 unsigned long key;
5022 int i, err;
5024 err = bdi_init(&cgroup_backing_dev_info);
5025 if (err)
5026 return err;
5028 for_each_builtin_subsys(ss, i) {
5029 if (!ss->early_init)
5030 cgroup_init_subsys(ss);
5033 /* allocate id for the dummy hierarchy */
5034 mutex_lock(&cgroup_mutex);
5035 mutex_lock(&cgroup_root_mutex);
5037 /* Add init_css_set to the hash table */
5038 key = css_set_hash(init_css_set.subsys);
5039 hash_add(css_set_table, &init_css_set.hlist, key);
5041 BUG_ON(cgroup_init_root_id(&cgroup_dummy_root, 0, 1));
5043 err = idr_alloc(&cgroup_dummy_root.cgroup_idr, cgroup_dummy_top,
5044 0, 1, GFP_KERNEL);
5045 BUG_ON(err < 0);
5047 mutex_unlock(&cgroup_root_mutex);
5048 mutex_unlock(&cgroup_mutex);
5050 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
5051 if (!cgroup_kobj) {
5052 err = -ENOMEM;
5053 goto out;
5056 err = register_filesystem(&cgroup_fs_type);
5057 if (err < 0) {
5058 kobject_put(cgroup_kobj);
5059 goto out;
5062 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
5064 out:
5065 if (err)
5066 bdi_destroy(&cgroup_backing_dev_info);
5068 return err;
5072 * proc_cgroup_show()
5073 * - Print task's cgroup paths into seq_file, one line for each hierarchy
5074 * - Used for /proc/<pid>/cgroup.
5075 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
5076 * doesn't really matter if tsk->cgroup changes after we read it,
5077 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
5078 * anyway. No need to check that tsk->cgroup != NULL, thanks to
5079 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
5080 * cgroup to top_cgroup.
5083 /* TODO: Use a proper seq_file iterator */
5084 int proc_cgroup_show(struct seq_file *m, void *v)
5086 struct pid *pid;
5087 struct task_struct *tsk;
5088 char *buf;
5089 int retval;
5090 struct cgroupfs_root *root;
5092 retval = -ENOMEM;
5093 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5094 if (!buf)
5095 goto out;
5097 retval = -ESRCH;
5098 pid = m->private;
5099 tsk = get_pid_task(pid, PIDTYPE_PID);
5100 if (!tsk)
5101 goto out_free;
5103 retval = 0;
5105 mutex_lock(&cgroup_mutex);
5107 for_each_active_root(root) {
5108 struct cgroup_subsys *ss;
5109 struct cgroup *cgrp;
5110 int count = 0;
5112 seq_printf(m, "%d:", root->hierarchy_id);
5113 for_each_root_subsys(root, ss)
5114 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
5115 if (strlen(root->name))
5116 seq_printf(m, "%sname=%s", count ? "," : "",
5117 root->name);
5118 seq_putc(m, ':');
5119 cgrp = task_cgroup_from_root(tsk, root);
5120 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
5121 if (retval < 0)
5122 goto out_unlock;
5123 seq_puts(m, buf);
5124 seq_putc(m, '\n');
5127 out_unlock:
5128 mutex_unlock(&cgroup_mutex);
5129 put_task_struct(tsk);
5130 out_free:
5131 kfree(buf);
5132 out:
5133 return retval;
5136 /* Display information about each subsystem and each hierarchy */
5137 static int proc_cgroupstats_show(struct seq_file *m, void *v)
5139 struct cgroup_subsys *ss;
5140 int i;
5142 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
5144 * ideally we don't want subsystems moving around while we do this.
5145 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
5146 * subsys/hierarchy state.
5148 mutex_lock(&cgroup_mutex);
5150 for_each_subsys(ss, i)
5151 seq_printf(m, "%s\t%d\t%d\t%d\n",
5152 ss->name, ss->root->hierarchy_id,
5153 ss->root->number_of_cgroups, !ss->disabled);
5155 mutex_unlock(&cgroup_mutex);
5156 return 0;
5159 static int cgroupstats_open(struct inode *inode, struct file *file)
5161 return single_open(file, proc_cgroupstats_show, NULL);
5164 static const struct file_operations proc_cgroupstats_operations = {
5165 .open = cgroupstats_open,
5166 .read = seq_read,
5167 .llseek = seq_lseek,
5168 .release = single_release,
5172 * cgroup_fork - attach newly forked task to its parents cgroup.
5173 * @child: pointer to task_struct of forking parent process.
5175 * Description: A task inherits its parent's cgroup at fork().
5177 * A pointer to the shared css_set was automatically copied in
5178 * fork.c by dup_task_struct(). However, we ignore that copy, since
5179 * it was not made under the protection of RCU or cgroup_mutex, so
5180 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
5181 * have already changed current->cgroups, allowing the previously
5182 * referenced cgroup group to be removed and freed.
5184 * At the point that cgroup_fork() is called, 'current' is the parent
5185 * task, and the passed argument 'child' points to the child task.
5187 void cgroup_fork(struct task_struct *child)
5189 task_lock(current);
5190 get_css_set(task_css_set(current));
5191 child->cgroups = current->cgroups;
5192 task_unlock(current);
5193 INIT_LIST_HEAD(&child->cg_list);
5197 * cgroup_post_fork - called on a new task after adding it to the task list
5198 * @child: the task in question
5200 * Adds the task to the list running through its css_set if necessary and
5201 * call the subsystem fork() callbacks. Has to be after the task is
5202 * visible on the task list in case we race with the first call to
5203 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
5204 * list.
5206 void cgroup_post_fork(struct task_struct *child)
5208 struct cgroup_subsys *ss;
5209 int i;
5212 * use_task_css_set_links is set to 1 before we walk the tasklist
5213 * under the tasklist_lock and we read it here after we added the child
5214 * to the tasklist under the tasklist_lock as well. If the child wasn't
5215 * yet in the tasklist when we walked through it from
5216 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
5217 * should be visible now due to the paired locking and barriers implied
5218 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
5219 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
5220 * lock on fork.
5222 if (use_task_css_set_links) {
5223 write_lock(&css_set_lock);
5224 task_lock(child);
5225 if (list_empty(&child->cg_list))
5226 list_add(&child->cg_list, &task_css_set(child)->tasks);
5227 task_unlock(child);
5228 write_unlock(&css_set_lock);
5232 * Call ss->fork(). This must happen after @child is linked on
5233 * css_set; otherwise, @child might change state between ->fork()
5234 * and addition to css_set.
5236 if (need_forkexit_callback) {
5238 * fork/exit callbacks are supported only for builtin
5239 * subsystems, and the builtin section of the subsys
5240 * array is immutable, so we don't need to lock the
5241 * subsys array here. On the other hand, modular section
5242 * of the array can be freed at module unload, so we
5243 * can't touch that.
5245 for_each_builtin_subsys(ss, i)
5246 if (ss->fork)
5247 ss->fork(child);
5252 * cgroup_exit - detach cgroup from exiting task
5253 * @tsk: pointer to task_struct of exiting process
5254 * @run_callback: run exit callbacks?
5256 * Description: Detach cgroup from @tsk and release it.
5258 * Note that cgroups marked notify_on_release force every task in
5259 * them to take the global cgroup_mutex mutex when exiting.
5260 * This could impact scaling on very large systems. Be reluctant to
5261 * use notify_on_release cgroups where very high task exit scaling
5262 * is required on large systems.
5264 * the_top_cgroup_hack:
5266 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
5268 * We call cgroup_exit() while the task is still competent to
5269 * handle notify_on_release(), then leave the task attached to the
5270 * root cgroup in each hierarchy for the remainder of its exit.
5272 * To do this properly, we would increment the reference count on
5273 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
5274 * code we would add a second cgroup function call, to drop that
5275 * reference. This would just create an unnecessary hot spot on
5276 * the top_cgroup reference count, to no avail.
5278 * Normally, holding a reference to a cgroup without bumping its
5279 * count is unsafe. The cgroup could go away, or someone could
5280 * attach us to a different cgroup, decrementing the count on
5281 * the first cgroup that we never incremented. But in this case,
5282 * top_cgroup isn't going away, and either task has PF_EXITING set,
5283 * which wards off any cgroup_attach_task() attempts, or task is a failed
5284 * fork, never visible to cgroup_attach_task.
5286 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
5288 struct cgroup_subsys *ss;
5289 struct css_set *cset;
5290 int i;
5293 * Unlink from the css_set task list if necessary.
5294 * Optimistically check cg_list before taking
5295 * css_set_lock
5297 if (!list_empty(&tsk->cg_list)) {
5298 write_lock(&css_set_lock);
5299 if (!list_empty(&tsk->cg_list))
5300 list_del_init(&tsk->cg_list);
5301 write_unlock(&css_set_lock);
5304 /* Reassign the task to the init_css_set. */
5305 task_lock(tsk);
5306 cset = task_css_set(tsk);
5307 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
5309 if (run_callbacks && need_forkexit_callback) {
5311 * fork/exit callbacks are supported only for builtin
5312 * subsystems, see cgroup_post_fork() for details.
5314 for_each_builtin_subsys(ss, i) {
5315 if (ss->exit) {
5316 struct cgroup_subsys_state *old_css = cset->subsys[i];
5317 struct cgroup_subsys_state *css = task_css(tsk, i);
5319 ss->exit(css, old_css, tsk);
5323 task_unlock(tsk);
5325 put_css_set_taskexit(cset);
5328 static void check_for_release(struct cgroup *cgrp)
5330 if (cgroup_is_releasable(cgrp) &&
5331 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
5333 * Control Group is currently removeable. If it's not
5334 * already queued for a userspace notification, queue
5335 * it now
5337 int need_schedule_work = 0;
5339 raw_spin_lock(&release_list_lock);
5340 if (!cgroup_is_dead(cgrp) &&
5341 list_empty(&cgrp->release_list)) {
5342 list_add(&cgrp->release_list, &release_list);
5343 need_schedule_work = 1;
5345 raw_spin_unlock(&release_list_lock);
5346 if (need_schedule_work)
5347 schedule_work(&release_agent_work);
5352 * Notify userspace when a cgroup is released, by running the
5353 * configured release agent with the name of the cgroup (path
5354 * relative to the root of cgroup file system) as the argument.
5356 * Most likely, this user command will try to rmdir this cgroup.
5358 * This races with the possibility that some other task will be
5359 * attached to this cgroup before it is removed, or that some other
5360 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5361 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5362 * unused, and this cgroup will be reprieved from its death sentence,
5363 * to continue to serve a useful existence. Next time it's released,
5364 * we will get notified again, if it still has 'notify_on_release' set.
5366 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5367 * means only wait until the task is successfully execve()'d. The
5368 * separate release agent task is forked by call_usermodehelper(),
5369 * then control in this thread returns here, without waiting for the
5370 * release agent task. We don't bother to wait because the caller of
5371 * this routine has no use for the exit status of the release agent
5372 * task, so no sense holding our caller up for that.
5374 static void cgroup_release_agent(struct work_struct *work)
5376 BUG_ON(work != &release_agent_work);
5377 mutex_lock(&cgroup_mutex);
5378 raw_spin_lock(&release_list_lock);
5379 while (!list_empty(&release_list)) {
5380 char *argv[3], *envp[3];
5381 int i;
5382 char *pathbuf = NULL, *agentbuf = NULL;
5383 struct cgroup *cgrp = list_entry(release_list.next,
5384 struct cgroup,
5385 release_list);
5386 list_del_init(&cgrp->release_list);
5387 raw_spin_unlock(&release_list_lock);
5388 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5389 if (!pathbuf)
5390 goto continue_free;
5391 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
5392 goto continue_free;
5393 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5394 if (!agentbuf)
5395 goto continue_free;
5397 i = 0;
5398 argv[i++] = agentbuf;
5399 argv[i++] = pathbuf;
5400 argv[i] = NULL;
5402 i = 0;
5403 /* minimal command environment */
5404 envp[i++] = "HOME=/";
5405 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5406 envp[i] = NULL;
5408 /* Drop the lock while we invoke the usermode helper,
5409 * since the exec could involve hitting disk and hence
5410 * be a slow process */
5411 mutex_unlock(&cgroup_mutex);
5412 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5413 mutex_lock(&cgroup_mutex);
5414 continue_free:
5415 kfree(pathbuf);
5416 kfree(agentbuf);
5417 raw_spin_lock(&release_list_lock);
5419 raw_spin_unlock(&release_list_lock);
5420 mutex_unlock(&cgroup_mutex);
5423 static int __init cgroup_disable(char *str)
5425 struct cgroup_subsys *ss;
5426 char *token;
5427 int i;
5429 while ((token = strsep(&str, ",")) != NULL) {
5430 if (!*token)
5431 continue;
5434 * cgroup_disable, being at boot time, can't know about
5435 * module subsystems, so we don't worry about them.
5437 for_each_builtin_subsys(ss, i) {
5438 if (!strcmp(token, ss->name)) {
5439 ss->disabled = 1;
5440 printk(KERN_INFO "Disabling %s control group"
5441 " subsystem\n", ss->name);
5442 break;
5446 return 1;
5448 __setup("cgroup_disable=", cgroup_disable);
5451 * css_from_dir - get corresponding css from the dentry of a cgroup dir
5452 * @dentry: directory dentry of interest
5453 * @ss: subsystem of interest
5455 * Must be called under RCU read lock. The caller is responsible for
5456 * pinning the returned css if it needs to be accessed outside the RCU
5457 * critical section.
5459 struct cgroup_subsys_state *css_from_dir(struct dentry *dentry,
5460 struct cgroup_subsys *ss)
5462 struct cgroup *cgrp;
5464 WARN_ON_ONCE(!rcu_read_lock_held());
5466 /* is @dentry a cgroup dir? */
5467 if (!dentry->d_inode ||
5468 dentry->d_inode->i_op != &cgroup_dir_inode_operations)
5469 return ERR_PTR(-EBADF);
5471 cgrp = __d_cgrp(dentry);
5472 return cgroup_css(cgrp, ss) ?: ERR_PTR(-ENOENT);
5476 * css_from_id - lookup css by id
5477 * @id: the cgroup id
5478 * @ss: cgroup subsys to be looked into
5480 * Returns the css if there's valid one with @id, otherwise returns NULL.
5481 * Should be called under rcu_read_lock().
5483 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5485 struct cgroup *cgrp;
5487 rcu_lockdep_assert(rcu_read_lock_held() ||
5488 lockdep_is_held(&cgroup_mutex),
5489 "css_from_id() needs proper protection");
5491 cgrp = idr_find(&ss->root->cgroup_idr, id);
5492 if (cgrp)
5493 return cgroup_css(cgrp, ss);
5494 return NULL;
5497 #ifdef CONFIG_CGROUP_DEBUG
5498 static struct cgroup_subsys_state *
5499 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5501 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5503 if (!css)
5504 return ERR_PTR(-ENOMEM);
5506 return css;
5509 static void debug_css_free(struct cgroup_subsys_state *css)
5511 kfree(css);
5514 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5515 struct cftype *cft)
5517 return cgroup_task_count(css->cgroup);
5520 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5521 struct cftype *cft)
5523 return (u64)(unsigned long)current->cgroups;
5526 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5527 struct cftype *cft)
5529 u64 count;
5531 rcu_read_lock();
5532 count = atomic_read(&task_css_set(current)->refcount);
5533 rcu_read_unlock();
5534 return count;
5537 static int current_css_set_cg_links_read(struct cgroup_subsys_state *css,
5538 struct cftype *cft,
5539 struct seq_file *seq)
5541 struct cgrp_cset_link *link;
5542 struct css_set *cset;
5544 read_lock(&css_set_lock);
5545 rcu_read_lock();
5546 cset = rcu_dereference(current->cgroups);
5547 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5548 struct cgroup *c = link->cgrp;
5549 const char *name;
5551 if (c->dentry)
5552 name = c->dentry->d_name.name;
5553 else
5554 name = "?";
5555 seq_printf(seq, "Root %d group %s\n",
5556 c->root->hierarchy_id, name);
5558 rcu_read_unlock();
5559 read_unlock(&css_set_lock);
5560 return 0;
5563 #define MAX_TASKS_SHOWN_PER_CSS 25
5564 static int cgroup_css_links_read(struct cgroup_subsys_state *css,
5565 struct cftype *cft, struct seq_file *seq)
5567 struct cgrp_cset_link *link;
5569 read_lock(&css_set_lock);
5570 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5571 struct css_set *cset = link->cset;
5572 struct task_struct *task;
5573 int count = 0;
5574 seq_printf(seq, "css_set %p\n", cset);
5575 list_for_each_entry(task, &cset->tasks, cg_list) {
5576 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5577 seq_puts(seq, " ...\n");
5578 break;
5579 } else {
5580 seq_printf(seq, " task %d\n",
5581 task_pid_vnr(task));
5585 read_unlock(&css_set_lock);
5586 return 0;
5589 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5591 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
5594 static struct cftype debug_files[] = {
5596 .name = "taskcount",
5597 .read_u64 = debug_taskcount_read,
5601 .name = "current_css_set",
5602 .read_u64 = current_css_set_read,
5606 .name = "current_css_set_refcount",
5607 .read_u64 = current_css_set_refcount_read,
5611 .name = "current_css_set_cg_links",
5612 .read_seq_string = current_css_set_cg_links_read,
5616 .name = "cgroup_css_links",
5617 .read_seq_string = cgroup_css_links_read,
5621 .name = "releasable",
5622 .read_u64 = releasable_read,
5625 { } /* terminate */
5628 struct cgroup_subsys debug_subsys = {
5629 .name = "debug",
5630 .css_alloc = debug_css_alloc,
5631 .css_free = debug_css_free,
5632 .subsys_id = debug_subsys_id,
5633 .base_cftypes = debug_files,
5635 #endif /* CONFIG_CGROUP_DEBUG */