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>
34 #include <linux/init_task.h>
35 #include <linux/kernel.h>
36 #include <linux/list.h>
38 #include <linux/mutex.h>
39 #include <linux/mount.h>
40 #include <linux/pagemap.h>
41 #include <linux/proc_fs.h>
42 #include <linux/rcupdate.h>
43 #include <linux/sched.h>
44 #include <linux/backing-dev.h>
45 #include <linux/seq_file.h>
46 #include <linux/slab.h>
47 #include <linux/magic.h>
48 #include <linux/spinlock.h>
49 #include <linux/string.h>
50 #include <linux/sort.h>
51 #include <linux/kmod.h>
52 #include <linux/module.h>
53 #include <linux/delayacct.h>
54 #include <linux/cgroupstats.h>
55 #include <linux/hashtable.h>
56 #include <linux/namei.h>
57 #include <linux/pid_namespace.h>
58 #include <linux/idr.h>
59 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
60 #include <linux/eventfd.h>
61 #include <linux/poll.h>
62 #include <linux/flex_array.h> /* used in cgroup_attach_task */
63 #include <linux/kthread.h>
65 #include <linux/atomic.h>
67 /* css deactivation bias, makes css->refcnt negative to deny new trygets */
68 #define CSS_DEACT_BIAS INT_MIN
71 * cgroup_mutex is the master lock. Any modification to cgroup or its
72 * hierarchy must be performed while holding it.
74 * cgroup_root_mutex nests inside cgroup_mutex and should be held to modify
75 * cgroupfs_root of any cgroup hierarchy - subsys list, flags,
76 * release_agent_path and so on. Modifying requires both cgroup_mutex and
77 * cgroup_root_mutex. Readers can acquire either of the two. This is to
78 * break the following locking order cycle.
80 * A. cgroup_mutex -> cred_guard_mutex -> s_type->i_mutex_key -> namespace_sem
81 * B. namespace_sem -> cgroup_mutex
83 * B happens only through cgroup_show_options() and using cgroup_root_mutex
86 #ifdef CONFIG_PROVE_RCU
87 DEFINE_MUTEX(cgroup_mutex
);
88 EXPORT_SYMBOL_GPL(cgroup_mutex
); /* only for task_subsys_state_check() */
90 static DEFINE_MUTEX(cgroup_mutex
);
93 static DEFINE_MUTEX(cgroup_root_mutex
);
96 * Generate an array of cgroup subsystem pointers. At boot time, this is
97 * populated with the built in subsystems, and modular subsystems are
98 * registered after that. The mutable section of this array is protected by
101 #define SUBSYS(_x) [_x ## _subsys_id] = &_x ## _subsys,
102 #define IS_SUBSYS_ENABLED(option) IS_BUILTIN(option)
103 static struct cgroup_subsys
*subsys
[CGROUP_SUBSYS_COUNT
] = {
104 #include <linux/cgroup_subsys.h>
107 #define MAX_CGROUP_ROOT_NAMELEN 64
110 * A cgroupfs_root represents the root of a cgroup hierarchy,
111 * and may be associated with a superblock to form an active
114 struct cgroupfs_root
{
115 struct super_block
*sb
;
118 * The bitmask of subsystems intended to be attached to this
121 unsigned long subsys_mask
;
123 /* Unique id for this hierarchy. */
126 /* The bitmask of subsystems currently attached to this hierarchy */
127 unsigned long actual_subsys_mask
;
129 /* A list running through the attached subsystems */
130 struct list_head subsys_list
;
132 /* The root cgroup for this hierarchy */
133 struct cgroup top_cgroup
;
135 /* Tracks how many cgroups are currently defined in hierarchy.*/
136 int number_of_cgroups
;
138 /* A list running through the active hierarchies */
139 struct list_head root_list
;
141 /* All cgroups on this root, cgroup_mutex protected */
142 struct list_head allcg_list
;
144 /* Hierarchy-specific flags */
147 /* IDs for cgroups in this hierarchy */
148 struct ida cgroup_ida
;
150 /* The path to use for release notifications. */
151 char release_agent_path
[PATH_MAX
];
153 /* The name for this hierarchy - may be empty */
154 char name
[MAX_CGROUP_ROOT_NAMELEN
];
158 * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the
159 * subsystems that are otherwise unattached - it never has more than a
160 * single cgroup, and all tasks are part of that cgroup.
162 static struct cgroupfs_root rootnode
;
165 * cgroupfs file entry, pointed to from leaf dentry->d_fsdata.
168 struct list_head node
;
169 struct dentry
*dentry
;
174 * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when
175 * cgroup_subsys->use_id != 0.
177 #define CSS_ID_MAX (65535)
180 * The css to which this ID points. This pointer is set to valid value
181 * after cgroup is populated. If cgroup is removed, this will be NULL.
182 * This pointer is expected to be RCU-safe because destroy()
183 * is called after synchronize_rcu(). But for safe use, css_tryget()
184 * should be used for avoiding race.
186 struct cgroup_subsys_state __rcu
*css
;
192 * Depth in hierarchy which this ID belongs to.
194 unsigned short depth
;
196 * ID is freed by RCU. (and lookup routine is RCU safe.)
198 struct rcu_head rcu_head
;
200 * Hierarchy of CSS ID belongs to.
202 unsigned short stack
[0]; /* Array of Length (depth+1) */
206 * cgroup_event represents events which userspace want to receive.
208 struct cgroup_event
{
210 * Cgroup which the event belongs to.
214 * Control file which the event associated.
218 * eventfd to signal userspace about the event.
220 struct eventfd_ctx
*eventfd
;
222 * Each of these stored in a list by the cgroup.
224 struct list_head list
;
226 * All fields below needed to unregister event when
227 * userspace closes eventfd.
230 wait_queue_head_t
*wqh
;
232 struct work_struct remove
;
235 /* The list of hierarchy roots */
237 static LIST_HEAD(roots
);
238 static int root_count
;
240 static DEFINE_IDA(hierarchy_ida
);
241 static int next_hierarchy_id
;
242 static DEFINE_SPINLOCK(hierarchy_id_lock
);
244 /* dummytop is a shorthand for the dummy hierarchy's top cgroup */
245 #define dummytop (&rootnode.top_cgroup)
247 static struct cgroup_name root_cgroup_name
= { .name
= "/" };
249 /* This flag indicates whether tasks in the fork and exit paths should
250 * check for fork/exit handlers to call. This avoids us having to do
251 * extra work in the fork/exit path if none of the subsystems need to
254 static int need_forkexit_callback __read_mostly
;
256 static int cgroup_destroy_locked(struct cgroup
*cgrp
);
257 static int cgroup_addrm_files(struct cgroup
*cgrp
, struct cgroup_subsys
*subsys
,
258 struct cftype cfts
[], bool is_add
);
260 static int css_unbias_refcnt(int refcnt
)
262 return refcnt
>= 0 ? refcnt
: refcnt
- CSS_DEACT_BIAS
;
265 /* the current nr of refs, always >= 0 whether @css is deactivated or not */
266 static int css_refcnt(struct cgroup_subsys_state
*css
)
268 int v
= atomic_read(&css
->refcnt
);
270 return css_unbias_refcnt(v
);
273 /* convenient tests for these bits */
274 inline int cgroup_is_removed(const struct cgroup
*cgrp
)
276 return test_bit(CGRP_REMOVED
, &cgrp
->flags
);
280 * cgroup_is_descendant - test ancestry
281 * @cgrp: the cgroup to be tested
282 * @ancestor: possible ancestor of @cgrp
284 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
285 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
286 * and @ancestor are accessible.
288 bool cgroup_is_descendant(struct cgroup
*cgrp
, struct cgroup
*ancestor
)
291 if (cgrp
== ancestor
)
297 EXPORT_SYMBOL_GPL(cgroup_is_descendant
);
299 /* bits in struct cgroupfs_root flags field */
301 ROOT_NOPREFIX
, /* mounted subsystems have no named prefix */
302 ROOT_XATTR
, /* supports extended attributes */
305 static int cgroup_is_releasable(const struct cgroup
*cgrp
)
308 (1 << CGRP_RELEASABLE
) |
309 (1 << CGRP_NOTIFY_ON_RELEASE
);
310 return (cgrp
->flags
& bits
) == bits
;
313 static int notify_on_release(const struct cgroup
*cgrp
)
315 return test_bit(CGRP_NOTIFY_ON_RELEASE
, &cgrp
->flags
);
319 * for_each_subsys() allows you to iterate on each subsystem attached to
320 * an active hierarchy
322 #define for_each_subsys(_root, _ss) \
323 list_for_each_entry(_ss, &_root->subsys_list, sibling)
325 /* for_each_active_root() allows you to iterate across the active hierarchies */
326 #define for_each_active_root(_root) \
327 list_for_each_entry(_root, &roots, root_list)
329 static inline struct cgroup
*__d_cgrp(struct dentry
*dentry
)
331 return dentry
->d_fsdata
;
334 static inline struct cfent
*__d_cfe(struct dentry
*dentry
)
336 return dentry
->d_fsdata
;
339 static inline struct cftype
*__d_cft(struct dentry
*dentry
)
341 return __d_cfe(dentry
)->type
;
345 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
346 * @cgrp: the cgroup to be checked for liveness
348 * On success, returns true; the mutex should be later unlocked. On
349 * failure returns false with no lock held.
351 static bool cgroup_lock_live_group(struct cgroup
*cgrp
)
353 mutex_lock(&cgroup_mutex
);
354 if (cgroup_is_removed(cgrp
)) {
355 mutex_unlock(&cgroup_mutex
);
361 /* the list of cgroups eligible for automatic release. Protected by
362 * release_list_lock */
363 static LIST_HEAD(release_list
);
364 static DEFINE_RAW_SPINLOCK(release_list_lock
);
365 static void cgroup_release_agent(struct work_struct
*work
);
366 static DECLARE_WORK(release_agent_work
, cgroup_release_agent
);
367 static void check_for_release(struct cgroup
*cgrp
);
369 /* Link structure for associating css_set objects with cgroups */
370 struct cg_cgroup_link
{
372 * List running through cg_cgroup_links associated with a
373 * cgroup, anchored on cgroup->css_sets
375 struct list_head cgrp_link_list
;
378 * List running through cg_cgroup_links pointing at a
379 * single css_set object, anchored on css_set->cg_links
381 struct list_head cg_link_list
;
385 /* The default css_set - used by init and its children prior to any
386 * hierarchies being mounted. It contains a pointer to the root state
387 * for each subsystem. Also used to anchor the list of css_sets. Not
388 * reference-counted, to improve performance when child cgroups
389 * haven't been created.
392 static struct css_set init_css_set
;
393 static struct cg_cgroup_link init_css_set_link
;
395 static int cgroup_init_idr(struct cgroup_subsys
*ss
,
396 struct cgroup_subsys_state
*css
);
398 /* css_set_lock protects the list of css_set objects, and the
399 * chain of tasks off each css_set. Nests outside task->alloc_lock
400 * due to cgroup_iter_start() */
401 static DEFINE_RWLOCK(css_set_lock
);
402 static int css_set_count
;
405 * hash table for cgroup groups. This improves the performance to find
406 * an existing css_set. This hash doesn't (currently) take into
407 * account cgroups in empty hierarchies.
409 #define CSS_SET_HASH_BITS 7
410 static DEFINE_HASHTABLE(css_set_table
, CSS_SET_HASH_BITS
);
412 static unsigned long css_set_hash(struct cgroup_subsys_state
*css
[])
415 unsigned long key
= 0UL;
417 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++)
418 key
+= (unsigned long)css
[i
];
419 key
= (key
>> 16) ^ key
;
424 /* We don't maintain the lists running through each css_set to its
425 * task until after the first call to cgroup_iter_start(). This
426 * reduces the fork()/exit() overhead for people who have cgroups
427 * compiled into their kernel but not actually in use */
428 static int use_task_css_set_links __read_mostly
;
430 static void __put_css_set(struct css_set
*cg
, int taskexit
)
432 struct cg_cgroup_link
*link
;
433 struct cg_cgroup_link
*saved_link
;
435 * Ensure that the refcount doesn't hit zero while any readers
436 * can see it. Similar to atomic_dec_and_lock(), but for an
439 if (atomic_add_unless(&cg
->refcount
, -1, 1))
441 write_lock(&css_set_lock
);
442 if (!atomic_dec_and_test(&cg
->refcount
)) {
443 write_unlock(&css_set_lock
);
447 /* This css_set is dead. unlink it and release cgroup refcounts */
448 hash_del(&cg
->hlist
);
451 list_for_each_entry_safe(link
, saved_link
, &cg
->cg_links
,
453 struct cgroup
*cgrp
= link
->cgrp
;
454 list_del(&link
->cg_link_list
);
455 list_del(&link
->cgrp_link_list
);
458 * We may not be holding cgroup_mutex, and if cgrp->count is
459 * dropped to 0 the cgroup can be destroyed at any time, hence
460 * rcu_read_lock is used to keep it alive.
463 if (atomic_dec_and_test(&cgrp
->count
) &&
464 notify_on_release(cgrp
)) {
466 set_bit(CGRP_RELEASABLE
, &cgrp
->flags
);
467 check_for_release(cgrp
);
474 write_unlock(&css_set_lock
);
475 kfree_rcu(cg
, rcu_head
);
479 * refcounted get/put for css_set objects
481 static inline void get_css_set(struct css_set
*cg
)
483 atomic_inc(&cg
->refcount
);
486 static inline void put_css_set(struct css_set
*cg
)
488 __put_css_set(cg
, 0);
491 static inline void put_css_set_taskexit(struct css_set
*cg
)
493 __put_css_set(cg
, 1);
497 * compare_css_sets - helper function for find_existing_css_set().
498 * @cg: candidate css_set being tested
499 * @old_cg: existing css_set for a task
500 * @new_cgrp: cgroup that's being entered by the task
501 * @template: desired set of css pointers in css_set (pre-calculated)
503 * Returns true if "cg" matches "old_cg" except for the hierarchy
504 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
506 static bool compare_css_sets(struct css_set
*cg
,
507 struct css_set
*old_cg
,
508 struct cgroup
*new_cgrp
,
509 struct cgroup_subsys_state
*template[])
511 struct list_head
*l1
, *l2
;
513 if (memcmp(template, cg
->subsys
, sizeof(cg
->subsys
))) {
514 /* Not all subsystems matched */
519 * Compare cgroup pointers in order to distinguish between
520 * different cgroups in heirarchies with no subsystems. We
521 * could get by with just this check alone (and skip the
522 * memcmp above) but on most setups the memcmp check will
523 * avoid the need for this more expensive check on almost all
528 l2
= &old_cg
->cg_links
;
530 struct cg_cgroup_link
*cgl1
, *cgl2
;
531 struct cgroup
*cg1
, *cg2
;
535 /* See if we reached the end - both lists are equal length. */
536 if (l1
== &cg
->cg_links
) {
537 BUG_ON(l2
!= &old_cg
->cg_links
);
540 BUG_ON(l2
== &old_cg
->cg_links
);
542 /* Locate the cgroups associated with these links. */
543 cgl1
= list_entry(l1
, struct cg_cgroup_link
, cg_link_list
);
544 cgl2
= list_entry(l2
, struct cg_cgroup_link
, cg_link_list
);
547 /* Hierarchies should be linked in the same order. */
548 BUG_ON(cg1
->root
!= cg2
->root
);
551 * If this hierarchy is the hierarchy of the cgroup
552 * that's changing, then we need to check that this
553 * css_set points to the new cgroup; if it's any other
554 * hierarchy, then this css_set should point to the
555 * same cgroup as the old css_set.
557 if (cg1
->root
== new_cgrp
->root
) {
569 * find_existing_css_set() is a helper for
570 * find_css_set(), and checks to see whether an existing
571 * css_set is suitable.
573 * oldcg: the cgroup group that we're using before the cgroup
576 * cgrp: the cgroup that we're moving into
578 * template: location in which to build the desired set of subsystem
579 * state objects for the new cgroup group
581 static struct css_set
*find_existing_css_set(
582 struct css_set
*oldcg
,
584 struct cgroup_subsys_state
*template[])
587 struct cgroupfs_root
*root
= cgrp
->root
;
592 * Build the set of subsystem state objects that we want to see in the
593 * new css_set. while subsystems can change globally, the entries here
594 * won't change, so no need for locking.
596 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++) {
597 if (root
->subsys_mask
& (1UL << i
)) {
598 /* Subsystem is in this hierarchy. So we want
599 * the subsystem state from the new
601 template[i
] = cgrp
->subsys
[i
];
603 /* Subsystem is not in this hierarchy, so we
604 * don't want to change the subsystem state */
605 template[i
] = oldcg
->subsys
[i
];
609 key
= css_set_hash(template);
610 hash_for_each_possible(css_set_table
, cg
, hlist
, key
) {
611 if (!compare_css_sets(cg
, oldcg
, cgrp
, template))
614 /* This css_set matches what we need */
618 /* No existing cgroup group matched */
622 static void free_cg_links(struct list_head
*tmp
)
624 struct cg_cgroup_link
*link
;
625 struct cg_cgroup_link
*saved_link
;
627 list_for_each_entry_safe(link
, saved_link
, tmp
, cgrp_link_list
) {
628 list_del(&link
->cgrp_link_list
);
634 * allocate_cg_links() allocates "count" cg_cgroup_link structures
635 * and chains them on tmp through their cgrp_link_list fields. Returns 0 on
636 * success or a negative error
638 static int allocate_cg_links(int count
, struct list_head
*tmp
)
640 struct cg_cgroup_link
*link
;
643 for (i
= 0; i
< count
; i
++) {
644 link
= kmalloc(sizeof(*link
), GFP_KERNEL
);
649 list_add(&link
->cgrp_link_list
, tmp
);
655 * link_css_set - a helper function to link a css_set to a cgroup
656 * @tmp_cg_links: cg_cgroup_link objects allocated by allocate_cg_links()
657 * @cg: the css_set to be linked
658 * @cgrp: the destination cgroup
660 static void link_css_set(struct list_head
*tmp_cg_links
,
661 struct css_set
*cg
, struct cgroup
*cgrp
)
663 struct cg_cgroup_link
*link
;
665 BUG_ON(list_empty(tmp_cg_links
));
666 link
= list_first_entry(tmp_cg_links
, struct cg_cgroup_link
,
670 atomic_inc(&cgrp
->count
);
671 list_move(&link
->cgrp_link_list
, &cgrp
->css_sets
);
673 * Always add links to the tail of the list so that the list
674 * is sorted by order of hierarchy creation
676 list_add_tail(&link
->cg_link_list
, &cg
->cg_links
);
680 * find_css_set() takes an existing cgroup group and a
681 * cgroup object, and returns a css_set object that's
682 * equivalent to the old group, but with the given cgroup
683 * substituted into the appropriate hierarchy. Must be called with
686 static struct css_set
*find_css_set(
687 struct css_set
*oldcg
, struct cgroup
*cgrp
)
690 struct cgroup_subsys_state
*template[CGROUP_SUBSYS_COUNT
];
692 struct list_head tmp_cg_links
;
694 struct cg_cgroup_link
*link
;
697 /* First see if we already have a cgroup group that matches
699 read_lock(&css_set_lock
);
700 res
= find_existing_css_set(oldcg
, cgrp
, template);
703 read_unlock(&css_set_lock
);
708 res
= kmalloc(sizeof(*res
), GFP_KERNEL
);
712 /* Allocate all the cg_cgroup_link objects that we'll need */
713 if (allocate_cg_links(root_count
, &tmp_cg_links
) < 0) {
718 atomic_set(&res
->refcount
, 1);
719 INIT_LIST_HEAD(&res
->cg_links
);
720 INIT_LIST_HEAD(&res
->tasks
);
721 INIT_HLIST_NODE(&res
->hlist
);
723 /* Copy the set of subsystem state objects generated in
724 * find_existing_css_set() */
725 memcpy(res
->subsys
, template, sizeof(res
->subsys
));
727 write_lock(&css_set_lock
);
728 /* Add reference counts and links from the new css_set. */
729 list_for_each_entry(link
, &oldcg
->cg_links
, cg_link_list
) {
730 struct cgroup
*c
= link
->cgrp
;
731 if (c
->root
== cgrp
->root
)
733 link_css_set(&tmp_cg_links
, res
, c
);
736 BUG_ON(!list_empty(&tmp_cg_links
));
740 /* Add this cgroup group to the hash table */
741 key
= css_set_hash(res
->subsys
);
742 hash_add(css_set_table
, &res
->hlist
, key
);
744 write_unlock(&css_set_lock
);
750 * Return the cgroup for "task" from the given hierarchy. Must be
751 * called with cgroup_mutex held.
753 static struct cgroup
*task_cgroup_from_root(struct task_struct
*task
,
754 struct cgroupfs_root
*root
)
757 struct cgroup
*res
= NULL
;
759 BUG_ON(!mutex_is_locked(&cgroup_mutex
));
760 read_lock(&css_set_lock
);
762 * No need to lock the task - since we hold cgroup_mutex the
763 * task can't change groups, so the only thing that can happen
764 * is that it exits and its css is set back to init_css_set.
767 if (css
== &init_css_set
) {
768 res
= &root
->top_cgroup
;
770 struct cg_cgroup_link
*link
;
771 list_for_each_entry(link
, &css
->cg_links
, cg_link_list
) {
772 struct cgroup
*c
= link
->cgrp
;
773 if (c
->root
== root
) {
779 read_unlock(&css_set_lock
);
785 * There is one global cgroup mutex. We also require taking
786 * task_lock() when dereferencing a task's cgroup subsys pointers.
787 * See "The task_lock() exception", at the end of this comment.
789 * A task must hold cgroup_mutex to modify cgroups.
791 * Any task can increment and decrement the count field without lock.
792 * So in general, code holding cgroup_mutex can't rely on the count
793 * field not changing. However, if the count goes to zero, then only
794 * cgroup_attach_task() can increment it again. Because a count of zero
795 * means that no tasks are currently attached, therefore there is no
796 * way a task attached to that cgroup can fork (the other way to
797 * increment the count). So code holding cgroup_mutex can safely
798 * assume that if the count is zero, it will stay zero. Similarly, if
799 * a task holds cgroup_mutex on a cgroup with zero count, it
800 * knows that the cgroup won't be removed, as cgroup_rmdir()
803 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
804 * (usually) take cgroup_mutex. These are the two most performance
805 * critical pieces of code here. The exception occurs on cgroup_exit(),
806 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
807 * is taken, and if the cgroup count is zero, a usermode call made
808 * to the release agent with the name of the cgroup (path relative to
809 * the root of cgroup file system) as the argument.
811 * A cgroup can only be deleted if both its 'count' of using tasks
812 * is zero, and its list of 'children' cgroups is empty. Since all
813 * tasks in the system use _some_ cgroup, and since there is always at
814 * least one task in the system (init, pid == 1), therefore, top_cgroup
815 * always has either children cgroups and/or using tasks. So we don't
816 * need a special hack to ensure that top_cgroup cannot be deleted.
818 * The task_lock() exception
820 * The need for this exception arises from the action of
821 * cgroup_attach_task(), which overwrites one task's cgroup pointer with
822 * another. It does so using cgroup_mutex, however there are
823 * several performance critical places that need to reference
824 * task->cgroup without the expense of grabbing a system global
825 * mutex. Therefore except as noted below, when dereferencing or, as
826 * in cgroup_attach_task(), modifying a task's cgroup pointer we use
827 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
828 * the task_struct routinely used for such matters.
830 * P.S. One more locking exception. RCU is used to guard the
831 * update of a tasks cgroup pointer by cgroup_attach_task()
835 * A couple of forward declarations required, due to cyclic reference loop:
836 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
837 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
841 static int cgroup_mkdir(struct inode
*dir
, struct dentry
*dentry
, umode_t mode
);
842 static struct dentry
*cgroup_lookup(struct inode
*, struct dentry
*, unsigned int);
843 static int cgroup_rmdir(struct inode
*unused_dir
, struct dentry
*dentry
);
844 static int cgroup_populate_dir(struct cgroup
*cgrp
, bool base_files
,
845 unsigned long subsys_mask
);
846 static const struct inode_operations cgroup_dir_inode_operations
;
847 static const struct file_operations proc_cgroupstats_operations
;
849 static struct backing_dev_info cgroup_backing_dev_info
= {
851 .capabilities
= BDI_CAP_NO_ACCT_AND_WRITEBACK
,
854 static int alloc_css_id(struct cgroup_subsys
*ss
,
855 struct cgroup
*parent
, struct cgroup
*child
);
857 static struct inode
*cgroup_new_inode(umode_t mode
, struct super_block
*sb
)
859 struct inode
*inode
= new_inode(sb
);
862 inode
->i_ino
= get_next_ino();
863 inode
->i_mode
= mode
;
864 inode
->i_uid
= current_fsuid();
865 inode
->i_gid
= current_fsgid();
866 inode
->i_atime
= inode
->i_mtime
= inode
->i_ctime
= CURRENT_TIME
;
867 inode
->i_mapping
->backing_dev_info
= &cgroup_backing_dev_info
;
872 static struct cgroup_name
*cgroup_alloc_name(struct dentry
*dentry
)
874 struct cgroup_name
*name
;
876 name
= kmalloc(sizeof(*name
) + dentry
->d_name
.len
+ 1, GFP_KERNEL
);
879 strcpy(name
->name
, dentry
->d_name
.name
);
883 static void cgroup_free_fn(struct work_struct
*work
)
885 struct cgroup
*cgrp
= container_of(work
, struct cgroup
, free_work
);
886 struct cgroup_subsys
*ss
;
888 mutex_lock(&cgroup_mutex
);
890 * Release the subsystem state objects.
892 for_each_subsys(cgrp
->root
, ss
)
895 cgrp
->root
->number_of_cgroups
--;
896 mutex_unlock(&cgroup_mutex
);
899 * We get a ref to the parent's dentry, and put the ref when
900 * this cgroup is being freed, so it's guaranteed that the
901 * parent won't be destroyed before its children.
903 dput(cgrp
->parent
->dentry
);
906 * Drop the active superblock reference that we took when we
909 deactivate_super(cgrp
->root
->sb
);
912 * if we're getting rid of the cgroup, refcount should ensure
913 * that there are no pidlists left.
915 BUG_ON(!list_empty(&cgrp
->pidlists
));
917 simple_xattrs_free(&cgrp
->xattrs
);
919 ida_simple_remove(&cgrp
->root
->cgroup_ida
, cgrp
->id
);
920 kfree(rcu_dereference_raw(cgrp
->name
));
924 static void cgroup_free_rcu(struct rcu_head
*head
)
926 struct cgroup
*cgrp
= container_of(head
, struct cgroup
, rcu_head
);
928 schedule_work(&cgrp
->free_work
);
931 static void cgroup_diput(struct dentry
*dentry
, struct inode
*inode
)
933 /* is dentry a directory ? if so, kfree() associated cgroup */
934 if (S_ISDIR(inode
->i_mode
)) {
935 struct cgroup
*cgrp
= dentry
->d_fsdata
;
937 BUG_ON(!(cgroup_is_removed(cgrp
)));
938 call_rcu(&cgrp
->rcu_head
, cgroup_free_rcu
);
940 struct cfent
*cfe
= __d_cfe(dentry
);
941 struct cgroup
*cgrp
= dentry
->d_parent
->d_fsdata
;
942 struct cftype
*cft
= cfe
->type
;
944 WARN_ONCE(!list_empty(&cfe
->node
) &&
945 cgrp
!= &cgrp
->root
->top_cgroup
,
946 "cfe still linked for %s\n", cfe
->type
->name
);
948 simple_xattrs_free(&cft
->xattrs
);
953 static int cgroup_delete(const struct dentry
*d
)
958 static void remove_dir(struct dentry
*d
)
960 struct dentry
*parent
= dget(d
->d_parent
);
963 simple_rmdir(parent
->d_inode
, d
);
967 static void cgroup_rm_file(struct cgroup
*cgrp
, const struct cftype
*cft
)
971 lockdep_assert_held(&cgrp
->dentry
->d_inode
->i_mutex
);
972 lockdep_assert_held(&cgroup_mutex
);
975 * If we're doing cleanup due to failure of cgroup_create(),
976 * the corresponding @cfe may not exist.
978 list_for_each_entry(cfe
, &cgrp
->files
, node
) {
979 struct dentry
*d
= cfe
->dentry
;
981 if (cft
&& cfe
->type
!= cft
)
986 simple_unlink(cgrp
->dentry
->d_inode
, d
);
987 list_del_init(&cfe
->node
);
995 * cgroup_clear_directory - selective removal of base and subsystem files
996 * @dir: directory containing the files
997 * @base_files: true if the base files should be removed
998 * @subsys_mask: mask of the subsystem ids whose files should be removed
1000 static void cgroup_clear_directory(struct dentry
*dir
, bool base_files
,
1001 unsigned long subsys_mask
)
1003 struct cgroup
*cgrp
= __d_cgrp(dir
);
1004 struct cgroup_subsys
*ss
;
1006 for_each_subsys(cgrp
->root
, ss
) {
1007 struct cftype_set
*set
;
1008 if (!test_bit(ss
->subsys_id
, &subsys_mask
))
1010 list_for_each_entry(set
, &ss
->cftsets
, node
)
1011 cgroup_addrm_files(cgrp
, NULL
, set
->cfts
, false);
1014 while (!list_empty(&cgrp
->files
))
1015 cgroup_rm_file(cgrp
, NULL
);
1020 * NOTE : the dentry must have been dget()'ed
1022 static void cgroup_d_remove_dir(struct dentry
*dentry
)
1024 struct dentry
*parent
;
1025 struct cgroupfs_root
*root
= dentry
->d_sb
->s_fs_info
;
1027 cgroup_clear_directory(dentry
, true, root
->subsys_mask
);
1029 parent
= dentry
->d_parent
;
1030 spin_lock(&parent
->d_lock
);
1031 spin_lock_nested(&dentry
->d_lock
, DENTRY_D_LOCK_NESTED
);
1032 list_del_init(&dentry
->d_u
.d_child
);
1033 spin_unlock(&dentry
->d_lock
);
1034 spin_unlock(&parent
->d_lock
);
1039 * Call with cgroup_mutex held. Drops reference counts on modules, including
1040 * any duplicate ones that parse_cgroupfs_options took. If this function
1041 * returns an error, no reference counts are touched.
1043 static int rebind_subsystems(struct cgroupfs_root
*root
,
1044 unsigned long final_subsys_mask
)
1046 unsigned long added_mask
, removed_mask
;
1047 struct cgroup
*cgrp
= &root
->top_cgroup
;
1050 BUG_ON(!mutex_is_locked(&cgroup_mutex
));
1051 BUG_ON(!mutex_is_locked(&cgroup_root_mutex
));
1053 removed_mask
= root
->actual_subsys_mask
& ~final_subsys_mask
;
1054 added_mask
= final_subsys_mask
& ~root
->actual_subsys_mask
;
1055 /* Check that any added subsystems are currently free */
1056 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++) {
1057 unsigned long bit
= 1UL << i
;
1058 struct cgroup_subsys
*ss
= subsys
[i
];
1059 if (!(bit
& added_mask
))
1062 * Nobody should tell us to do a subsys that doesn't exist:
1063 * parse_cgroupfs_options should catch that case and refcounts
1064 * ensure that subsystems won't disappear once selected.
1067 if (ss
->root
!= &rootnode
) {
1068 /* Subsystem isn't free */
1073 /* Currently we don't handle adding/removing subsystems when
1074 * any child cgroups exist. This is theoretically supportable
1075 * but involves complex error handling, so it's being left until
1077 if (root
->number_of_cgroups
> 1)
1080 /* Process each subsystem */
1081 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++) {
1082 struct cgroup_subsys
*ss
= subsys
[i
];
1083 unsigned long bit
= 1UL << i
;
1084 if (bit
& added_mask
) {
1085 /* We're binding this subsystem to this hierarchy */
1087 BUG_ON(cgrp
->subsys
[i
]);
1088 BUG_ON(!dummytop
->subsys
[i
]);
1089 BUG_ON(dummytop
->subsys
[i
]->cgroup
!= dummytop
);
1090 cgrp
->subsys
[i
] = dummytop
->subsys
[i
];
1091 cgrp
->subsys
[i
]->cgroup
= cgrp
;
1092 list_move(&ss
->sibling
, &root
->subsys_list
);
1094 /* refcount was already taken, and we're keeping it */
1095 } else if (bit
& removed_mask
) {
1096 /* We're removing this subsystem */
1098 BUG_ON(cgrp
->subsys
[i
] != dummytop
->subsys
[i
]);
1099 BUG_ON(cgrp
->subsys
[i
]->cgroup
!= cgrp
);
1100 dummytop
->subsys
[i
]->cgroup
= dummytop
;
1101 cgrp
->subsys
[i
] = NULL
;
1102 subsys
[i
]->root
= &rootnode
;
1103 list_move(&ss
->sibling
, &rootnode
.subsys_list
);
1104 /* subsystem is now free - drop reference on module */
1105 module_put(ss
->module
);
1106 } else if (bit
& final_subsys_mask
) {
1107 /* Subsystem state should already exist */
1109 BUG_ON(!cgrp
->subsys
[i
]);
1111 * a refcount was taken, but we already had one, so
1112 * drop the extra reference.
1114 module_put(ss
->module
);
1115 #ifdef CONFIG_MODULE_UNLOAD
1116 BUG_ON(ss
->module
&& !module_refcount(ss
->module
));
1119 /* Subsystem state shouldn't exist */
1120 BUG_ON(cgrp
->subsys
[i
]);
1123 root
->subsys_mask
= root
->actual_subsys_mask
= final_subsys_mask
;
1128 static int cgroup_show_options(struct seq_file
*seq
, struct dentry
*dentry
)
1130 struct cgroupfs_root
*root
= dentry
->d_sb
->s_fs_info
;
1131 struct cgroup_subsys
*ss
;
1133 mutex_lock(&cgroup_root_mutex
);
1134 for_each_subsys(root
, ss
)
1135 seq_printf(seq
, ",%s", ss
->name
);
1136 if (test_bit(ROOT_NOPREFIX
, &root
->flags
))
1137 seq_puts(seq
, ",noprefix");
1138 if (test_bit(ROOT_XATTR
, &root
->flags
))
1139 seq_puts(seq
, ",xattr");
1140 if (strlen(root
->release_agent_path
))
1141 seq_printf(seq
, ",release_agent=%s", root
->release_agent_path
);
1142 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN
, &root
->top_cgroup
.flags
))
1143 seq_puts(seq
, ",clone_children");
1144 if (strlen(root
->name
))
1145 seq_printf(seq
, ",name=%s", root
->name
);
1146 mutex_unlock(&cgroup_root_mutex
);
1150 struct cgroup_sb_opts
{
1151 unsigned long subsys_mask
;
1152 unsigned long flags
;
1153 char *release_agent
;
1154 bool cpuset_clone_children
;
1156 /* User explicitly requested empty subsystem */
1159 struct cgroupfs_root
*new_root
;
1164 * Convert a hierarchy specifier into a bitmask of subsystems and flags. Call
1165 * with cgroup_mutex held to protect the subsys[] array. This function takes
1166 * refcounts on subsystems to be used, unless it returns error, in which case
1167 * no refcounts are taken.
1169 static int parse_cgroupfs_options(char *data
, struct cgroup_sb_opts
*opts
)
1171 char *token
, *o
= data
;
1172 bool all_ss
= false, one_ss
= false;
1173 unsigned long mask
= (unsigned long)-1;
1175 bool module_pin_failed
= false;
1177 BUG_ON(!mutex_is_locked(&cgroup_mutex
));
1179 #ifdef CONFIG_CPUSETS
1180 mask
= ~(1UL << cpuset_subsys_id
);
1183 memset(opts
, 0, sizeof(*opts
));
1185 while ((token
= strsep(&o
, ",")) != NULL
) {
1188 if (!strcmp(token
, "none")) {
1189 /* Explicitly have no subsystems */
1193 if (!strcmp(token
, "all")) {
1194 /* Mutually exclusive option 'all' + subsystem name */
1200 if (!strcmp(token
, "noprefix")) {
1201 set_bit(ROOT_NOPREFIX
, &opts
->flags
);
1204 if (!strcmp(token
, "clone_children")) {
1205 opts
->cpuset_clone_children
= true;
1208 if (!strcmp(token
, "xattr")) {
1209 set_bit(ROOT_XATTR
, &opts
->flags
);
1212 if (!strncmp(token
, "release_agent=", 14)) {
1213 /* Specifying two release agents is forbidden */
1214 if (opts
->release_agent
)
1216 opts
->release_agent
=
1217 kstrndup(token
+ 14, PATH_MAX
- 1, GFP_KERNEL
);
1218 if (!opts
->release_agent
)
1222 if (!strncmp(token
, "name=", 5)) {
1223 const char *name
= token
+ 5;
1224 /* Can't specify an empty name */
1227 /* Must match [\w.-]+ */
1228 for (i
= 0; i
< strlen(name
); i
++) {
1232 if ((c
== '.') || (c
== '-') || (c
== '_'))
1236 /* Specifying two names is forbidden */
1239 opts
->name
= kstrndup(name
,
1240 MAX_CGROUP_ROOT_NAMELEN
- 1,
1248 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++) {
1249 struct cgroup_subsys
*ss
= subsys
[i
];
1252 if (strcmp(token
, ss
->name
))
1257 /* Mutually exclusive option 'all' + subsystem name */
1260 set_bit(i
, &opts
->subsys_mask
);
1265 if (i
== CGROUP_SUBSYS_COUNT
)
1270 * If the 'all' option was specified select all the subsystems,
1271 * otherwise if 'none', 'name=' and a subsystem name options
1272 * were not specified, let's default to 'all'
1274 if (all_ss
|| (!one_ss
&& !opts
->none
&& !opts
->name
)) {
1275 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++) {
1276 struct cgroup_subsys
*ss
= subsys
[i
];
1281 set_bit(i
, &opts
->subsys_mask
);
1285 /* Consistency checks */
1288 * Option noprefix was introduced just for backward compatibility
1289 * with the old cpuset, so we allow noprefix only if mounting just
1290 * the cpuset subsystem.
1292 if (test_bit(ROOT_NOPREFIX
, &opts
->flags
) &&
1293 (opts
->subsys_mask
& mask
))
1297 /* Can't specify "none" and some subsystems */
1298 if (opts
->subsys_mask
&& opts
->none
)
1302 * We either have to specify by name or by subsystems. (So all
1303 * empty hierarchies must have a name).
1305 if (!opts
->subsys_mask
&& !opts
->name
)
1309 * Grab references on all the modules we'll need, so the subsystems
1310 * don't dance around before rebind_subsystems attaches them. This may
1311 * take duplicate reference counts on a subsystem that's already used,
1312 * but rebind_subsystems handles this case.
1314 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++) {
1315 unsigned long bit
= 1UL << i
;
1317 if (!(bit
& opts
->subsys_mask
))
1319 if (!try_module_get(subsys
[i
]->module
)) {
1320 module_pin_failed
= true;
1324 if (module_pin_failed
) {
1326 * oops, one of the modules was going away. this means that we
1327 * raced with a module_delete call, and to the user this is
1328 * essentially a "subsystem doesn't exist" case.
1330 for (i
--; i
>= 0; i
--) {
1331 /* drop refcounts only on the ones we took */
1332 unsigned long bit
= 1UL << i
;
1334 if (!(bit
& opts
->subsys_mask
))
1336 module_put(subsys
[i
]->module
);
1344 static void drop_parsed_module_refcounts(unsigned long subsys_mask
)
1347 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++) {
1348 unsigned long bit
= 1UL << i
;
1350 if (!(bit
& subsys_mask
))
1352 module_put(subsys
[i
]->module
);
1356 static int cgroup_remount(struct super_block
*sb
, int *flags
, char *data
)
1359 struct cgroupfs_root
*root
= sb
->s_fs_info
;
1360 struct cgroup
*cgrp
= &root
->top_cgroup
;
1361 struct cgroup_sb_opts opts
;
1362 unsigned long added_mask
, removed_mask
;
1364 mutex_lock(&cgrp
->dentry
->d_inode
->i_mutex
);
1365 mutex_lock(&cgroup_mutex
);
1366 mutex_lock(&cgroup_root_mutex
);
1368 /* See what subsystems are wanted */
1369 ret
= parse_cgroupfs_options(data
, &opts
);
1373 if (opts
.subsys_mask
!= root
->actual_subsys_mask
|| opts
.release_agent
)
1374 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1375 task_tgid_nr(current
), current
->comm
);
1377 added_mask
= opts
.subsys_mask
& ~root
->subsys_mask
;
1378 removed_mask
= root
->subsys_mask
& ~opts
.subsys_mask
;
1380 /* Don't allow flags or name to change at remount */
1381 if (opts
.flags
!= root
->flags
||
1382 (opts
.name
&& strcmp(opts
.name
, root
->name
))) {
1384 drop_parsed_module_refcounts(opts
.subsys_mask
);
1389 * Clear out the files of subsystems that should be removed, do
1390 * this before rebind_subsystems, since rebind_subsystems may
1391 * change this hierarchy's subsys_list.
1393 cgroup_clear_directory(cgrp
->dentry
, false, removed_mask
);
1395 ret
= rebind_subsystems(root
, opts
.subsys_mask
);
1397 /* rebind_subsystems failed, re-populate the removed files */
1398 cgroup_populate_dir(cgrp
, false, removed_mask
);
1399 drop_parsed_module_refcounts(opts
.subsys_mask
);
1403 /* re-populate subsystem files */
1404 cgroup_populate_dir(cgrp
, false, added_mask
);
1406 if (opts
.release_agent
)
1407 strcpy(root
->release_agent_path
, opts
.release_agent
);
1409 kfree(opts
.release_agent
);
1411 mutex_unlock(&cgroup_root_mutex
);
1412 mutex_unlock(&cgroup_mutex
);
1413 mutex_unlock(&cgrp
->dentry
->d_inode
->i_mutex
);
1417 static const struct super_operations cgroup_ops
= {
1418 .statfs
= simple_statfs
,
1419 .drop_inode
= generic_delete_inode
,
1420 .show_options
= cgroup_show_options
,
1421 .remount_fs
= cgroup_remount
,
1424 static void init_cgroup_housekeeping(struct cgroup
*cgrp
)
1426 INIT_LIST_HEAD(&cgrp
->sibling
);
1427 INIT_LIST_HEAD(&cgrp
->children
);
1428 INIT_LIST_HEAD(&cgrp
->files
);
1429 INIT_LIST_HEAD(&cgrp
->css_sets
);
1430 INIT_LIST_HEAD(&cgrp
->allcg_node
);
1431 INIT_LIST_HEAD(&cgrp
->release_list
);
1432 INIT_LIST_HEAD(&cgrp
->pidlists
);
1433 INIT_WORK(&cgrp
->free_work
, cgroup_free_fn
);
1434 mutex_init(&cgrp
->pidlist_mutex
);
1435 INIT_LIST_HEAD(&cgrp
->event_list
);
1436 spin_lock_init(&cgrp
->event_list_lock
);
1437 simple_xattrs_init(&cgrp
->xattrs
);
1440 static void init_cgroup_root(struct cgroupfs_root
*root
)
1442 struct cgroup
*cgrp
= &root
->top_cgroup
;
1444 INIT_LIST_HEAD(&root
->subsys_list
);
1445 INIT_LIST_HEAD(&root
->root_list
);
1446 INIT_LIST_HEAD(&root
->allcg_list
);
1447 root
->number_of_cgroups
= 1;
1449 cgrp
->name
= &root_cgroup_name
;
1450 cgrp
->top_cgroup
= cgrp
;
1451 init_cgroup_housekeeping(cgrp
);
1452 list_add_tail(&cgrp
->allcg_node
, &root
->allcg_list
);
1455 static bool init_root_id(struct cgroupfs_root
*root
)
1460 if (!ida_pre_get(&hierarchy_ida
, GFP_KERNEL
))
1462 spin_lock(&hierarchy_id_lock
);
1463 /* Try to allocate the next unused ID */
1464 ret
= ida_get_new_above(&hierarchy_ida
, next_hierarchy_id
,
1465 &root
->hierarchy_id
);
1467 /* Try again starting from 0 */
1468 ret
= ida_get_new(&hierarchy_ida
, &root
->hierarchy_id
);
1470 next_hierarchy_id
= root
->hierarchy_id
+ 1;
1471 } else if (ret
!= -EAGAIN
) {
1472 /* Can only get here if the 31-bit IDR is full ... */
1475 spin_unlock(&hierarchy_id_lock
);
1480 static int cgroup_test_super(struct super_block
*sb
, void *data
)
1482 struct cgroup_sb_opts
*opts
= data
;
1483 struct cgroupfs_root
*root
= sb
->s_fs_info
;
1485 /* If we asked for a name then it must match */
1486 if (opts
->name
&& strcmp(opts
->name
, root
->name
))
1490 * If we asked for subsystems (or explicitly for no
1491 * subsystems) then they must match
1493 if ((opts
->subsys_mask
|| opts
->none
)
1494 && (opts
->subsys_mask
!= root
->subsys_mask
))
1500 static struct cgroupfs_root
*cgroup_root_from_opts(struct cgroup_sb_opts
*opts
)
1502 struct cgroupfs_root
*root
;
1504 if (!opts
->subsys_mask
&& !opts
->none
)
1507 root
= kzalloc(sizeof(*root
), GFP_KERNEL
);
1509 return ERR_PTR(-ENOMEM
);
1511 if (!init_root_id(root
)) {
1513 return ERR_PTR(-ENOMEM
);
1515 init_cgroup_root(root
);
1517 root
->subsys_mask
= opts
->subsys_mask
;
1518 root
->flags
= opts
->flags
;
1519 ida_init(&root
->cgroup_ida
);
1520 if (opts
->release_agent
)
1521 strcpy(root
->release_agent_path
, opts
->release_agent
);
1523 strcpy(root
->name
, opts
->name
);
1524 if (opts
->cpuset_clone_children
)
1525 set_bit(CGRP_CPUSET_CLONE_CHILDREN
, &root
->top_cgroup
.flags
);
1529 static void cgroup_drop_root(struct cgroupfs_root
*root
)
1534 BUG_ON(!root
->hierarchy_id
);
1535 spin_lock(&hierarchy_id_lock
);
1536 ida_remove(&hierarchy_ida
, root
->hierarchy_id
);
1537 spin_unlock(&hierarchy_id_lock
);
1538 ida_destroy(&root
->cgroup_ida
);
1542 static int cgroup_set_super(struct super_block
*sb
, void *data
)
1545 struct cgroup_sb_opts
*opts
= data
;
1547 /* If we don't have a new root, we can't set up a new sb */
1548 if (!opts
->new_root
)
1551 BUG_ON(!opts
->subsys_mask
&& !opts
->none
);
1553 ret
= set_anon_super(sb
, NULL
);
1557 sb
->s_fs_info
= opts
->new_root
;
1558 opts
->new_root
->sb
= sb
;
1560 sb
->s_blocksize
= PAGE_CACHE_SIZE
;
1561 sb
->s_blocksize_bits
= PAGE_CACHE_SHIFT
;
1562 sb
->s_magic
= CGROUP_SUPER_MAGIC
;
1563 sb
->s_op
= &cgroup_ops
;
1568 static int cgroup_get_rootdir(struct super_block
*sb
)
1570 static const struct dentry_operations cgroup_dops
= {
1571 .d_iput
= cgroup_diput
,
1572 .d_delete
= cgroup_delete
,
1575 struct inode
*inode
=
1576 cgroup_new_inode(S_IFDIR
| S_IRUGO
| S_IXUGO
| S_IWUSR
, sb
);
1581 inode
->i_fop
= &simple_dir_operations
;
1582 inode
->i_op
= &cgroup_dir_inode_operations
;
1583 /* directories start off with i_nlink == 2 (for "." entry) */
1585 sb
->s_root
= d_make_root(inode
);
1588 /* for everything else we want ->d_op set */
1589 sb
->s_d_op
= &cgroup_dops
;
1593 static struct dentry
*cgroup_mount(struct file_system_type
*fs_type
,
1594 int flags
, const char *unused_dev_name
,
1597 struct cgroup_sb_opts opts
;
1598 struct cgroupfs_root
*root
;
1600 struct super_block
*sb
;
1601 struct cgroupfs_root
*new_root
;
1602 struct inode
*inode
;
1604 /* First find the desired set of subsystems */
1605 mutex_lock(&cgroup_mutex
);
1606 ret
= parse_cgroupfs_options(data
, &opts
);
1607 mutex_unlock(&cgroup_mutex
);
1612 * Allocate a new cgroup root. We may not need it if we're
1613 * reusing an existing hierarchy.
1615 new_root
= cgroup_root_from_opts(&opts
);
1616 if (IS_ERR(new_root
)) {
1617 ret
= PTR_ERR(new_root
);
1620 opts
.new_root
= new_root
;
1622 /* Locate an existing or new sb for this hierarchy */
1623 sb
= sget(fs_type
, cgroup_test_super
, cgroup_set_super
, 0, &opts
);
1626 cgroup_drop_root(opts
.new_root
);
1630 root
= sb
->s_fs_info
;
1632 if (root
== opts
.new_root
) {
1633 /* We used the new root structure, so this is a new hierarchy */
1634 struct list_head tmp_cg_links
;
1635 struct cgroup
*root_cgrp
= &root
->top_cgroup
;
1636 struct cgroupfs_root
*existing_root
;
1637 const struct cred
*cred
;
1641 BUG_ON(sb
->s_root
!= NULL
);
1643 ret
= cgroup_get_rootdir(sb
);
1645 goto drop_new_super
;
1646 inode
= sb
->s_root
->d_inode
;
1648 mutex_lock(&inode
->i_mutex
);
1649 mutex_lock(&cgroup_mutex
);
1650 mutex_lock(&cgroup_root_mutex
);
1652 /* Check for name clashes with existing mounts */
1654 if (strlen(root
->name
))
1655 for_each_active_root(existing_root
)
1656 if (!strcmp(existing_root
->name
, root
->name
))
1660 * We're accessing css_set_count without locking
1661 * css_set_lock here, but that's OK - it can only be
1662 * increased by someone holding cgroup_lock, and
1663 * that's us. The worst that can happen is that we
1664 * have some link structures left over
1666 ret
= allocate_cg_links(css_set_count
, &tmp_cg_links
);
1670 ret
= rebind_subsystems(root
, root
->subsys_mask
);
1671 if (ret
== -EBUSY
) {
1672 free_cg_links(&tmp_cg_links
);
1676 * There must be no failure case after here, since rebinding
1677 * takes care of subsystems' refcounts, which are explicitly
1678 * dropped in the failure exit path.
1681 /* EBUSY should be the only error here */
1684 list_add(&root
->root_list
, &roots
);
1687 sb
->s_root
->d_fsdata
= root_cgrp
;
1688 root
->top_cgroup
.dentry
= sb
->s_root
;
1690 /* Link the top cgroup in this hierarchy into all
1691 * the css_set objects */
1692 write_lock(&css_set_lock
);
1693 hash_for_each(css_set_table
, i
, cg
, hlist
)
1694 link_css_set(&tmp_cg_links
, cg
, root_cgrp
);
1695 write_unlock(&css_set_lock
);
1697 free_cg_links(&tmp_cg_links
);
1699 BUG_ON(!list_empty(&root_cgrp
->children
));
1700 BUG_ON(root
->number_of_cgroups
!= 1);
1702 cred
= override_creds(&init_cred
);
1703 cgroup_populate_dir(root_cgrp
, true, root
->subsys_mask
);
1705 mutex_unlock(&cgroup_root_mutex
);
1706 mutex_unlock(&cgroup_mutex
);
1707 mutex_unlock(&inode
->i_mutex
);
1710 * We re-used an existing hierarchy - the new root (if
1711 * any) is not needed
1713 cgroup_drop_root(opts
.new_root
);
1714 /* no subsys rebinding, so refcounts don't change */
1715 drop_parsed_module_refcounts(opts
.subsys_mask
);
1718 kfree(opts
.release_agent
);
1720 return dget(sb
->s_root
);
1723 mutex_unlock(&cgroup_root_mutex
);
1724 mutex_unlock(&cgroup_mutex
);
1725 mutex_unlock(&inode
->i_mutex
);
1727 deactivate_locked_super(sb
);
1729 drop_parsed_module_refcounts(opts
.subsys_mask
);
1731 kfree(opts
.release_agent
);
1733 return ERR_PTR(ret
);
1736 static void cgroup_kill_sb(struct super_block
*sb
) {
1737 struct cgroupfs_root
*root
= sb
->s_fs_info
;
1738 struct cgroup
*cgrp
= &root
->top_cgroup
;
1740 struct cg_cgroup_link
*link
;
1741 struct cg_cgroup_link
*saved_link
;
1745 BUG_ON(root
->number_of_cgroups
!= 1);
1746 BUG_ON(!list_empty(&cgrp
->children
));
1748 mutex_lock(&cgroup_mutex
);
1749 mutex_lock(&cgroup_root_mutex
);
1751 /* Rebind all subsystems back to the default hierarchy */
1752 ret
= rebind_subsystems(root
, 0);
1753 /* Shouldn't be able to fail ... */
1757 * Release all the links from css_sets to this hierarchy's
1760 write_lock(&css_set_lock
);
1762 list_for_each_entry_safe(link
, saved_link
, &cgrp
->css_sets
,
1764 list_del(&link
->cg_link_list
);
1765 list_del(&link
->cgrp_link_list
);
1768 write_unlock(&css_set_lock
);
1770 if (!list_empty(&root
->root_list
)) {
1771 list_del(&root
->root_list
);
1775 mutex_unlock(&cgroup_root_mutex
);
1776 mutex_unlock(&cgroup_mutex
);
1778 simple_xattrs_free(&cgrp
->xattrs
);
1780 kill_litter_super(sb
);
1781 cgroup_drop_root(root
);
1784 static struct file_system_type cgroup_fs_type
= {
1786 .mount
= cgroup_mount
,
1787 .kill_sb
= cgroup_kill_sb
,
1790 static struct kobject
*cgroup_kobj
;
1793 * cgroup_path - generate the path of a cgroup
1794 * @cgrp: the cgroup in question
1795 * @buf: the buffer to write the path into
1796 * @buflen: the length of the buffer
1798 * Writes path of cgroup into buf. Returns 0 on success, -errno on error.
1800 * We can't generate cgroup path using dentry->d_name, as accessing
1801 * dentry->name must be protected by irq-unsafe dentry->d_lock or parent
1802 * inode's i_mutex, while on the other hand cgroup_path() can be called
1803 * with some irq-safe spinlocks held.
1805 int cgroup_path(const struct cgroup
*cgrp
, char *buf
, int buflen
)
1807 int ret
= -ENAMETOOLONG
;
1810 start
= buf
+ buflen
- 1;
1815 const char *name
= cgroup_name(cgrp
);
1819 if ((start
-= len
) < buf
)
1821 memcpy(start
, name
, len
);
1830 cgrp
= cgrp
->parent
;
1833 memmove(buf
, start
, buf
+ buflen
- start
);
1838 EXPORT_SYMBOL_GPL(cgroup_path
);
1841 * Control Group taskset
1843 struct task_and_cgroup
{
1844 struct task_struct
*task
;
1845 struct cgroup
*cgrp
;
1849 struct cgroup_taskset
{
1850 struct task_and_cgroup single
;
1851 struct flex_array
*tc_array
;
1854 struct cgroup
*cur_cgrp
;
1858 * cgroup_taskset_first - reset taskset and return the first task
1859 * @tset: taskset of interest
1861 * @tset iteration is initialized and the first task is returned.
1863 struct task_struct
*cgroup_taskset_first(struct cgroup_taskset
*tset
)
1865 if (tset
->tc_array
) {
1867 return cgroup_taskset_next(tset
);
1869 tset
->cur_cgrp
= tset
->single
.cgrp
;
1870 return tset
->single
.task
;
1873 EXPORT_SYMBOL_GPL(cgroup_taskset_first
);
1876 * cgroup_taskset_next - iterate to the next task in taskset
1877 * @tset: taskset of interest
1879 * Return the next task in @tset. Iteration must have been initialized
1880 * with cgroup_taskset_first().
1882 struct task_struct
*cgroup_taskset_next(struct cgroup_taskset
*tset
)
1884 struct task_and_cgroup
*tc
;
1886 if (!tset
->tc_array
|| tset
->idx
>= tset
->tc_array_len
)
1889 tc
= flex_array_get(tset
->tc_array
, tset
->idx
++);
1890 tset
->cur_cgrp
= tc
->cgrp
;
1893 EXPORT_SYMBOL_GPL(cgroup_taskset_next
);
1896 * cgroup_taskset_cur_cgroup - return the matching cgroup for the current task
1897 * @tset: taskset of interest
1899 * Return the cgroup for the current (last returned) task of @tset. This
1900 * function must be preceded by either cgroup_taskset_first() or
1901 * cgroup_taskset_next().
1903 struct cgroup
*cgroup_taskset_cur_cgroup(struct cgroup_taskset
*tset
)
1905 return tset
->cur_cgrp
;
1907 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_cgroup
);
1910 * cgroup_taskset_size - return the number of tasks in taskset
1911 * @tset: taskset of interest
1913 int cgroup_taskset_size(struct cgroup_taskset
*tset
)
1915 return tset
->tc_array
? tset
->tc_array_len
: 1;
1917 EXPORT_SYMBOL_GPL(cgroup_taskset_size
);
1921 * cgroup_task_migrate - move a task from one cgroup to another.
1923 * Must be called with cgroup_mutex and threadgroup locked.
1925 static void cgroup_task_migrate(struct cgroup
*oldcgrp
,
1926 struct task_struct
*tsk
, struct css_set
*newcg
)
1928 struct css_set
*oldcg
;
1931 * We are synchronized through threadgroup_lock() against PF_EXITING
1932 * setting such that we can't race against cgroup_exit() changing the
1933 * css_set to init_css_set and dropping the old one.
1935 WARN_ON_ONCE(tsk
->flags
& PF_EXITING
);
1936 oldcg
= tsk
->cgroups
;
1939 rcu_assign_pointer(tsk
->cgroups
, newcg
);
1942 /* Update the css_set linked lists if we're using them */
1943 write_lock(&css_set_lock
);
1944 if (!list_empty(&tsk
->cg_list
))
1945 list_move(&tsk
->cg_list
, &newcg
->tasks
);
1946 write_unlock(&css_set_lock
);
1949 * We just gained a reference on oldcg by taking it from the task. As
1950 * trading it for newcg is protected by cgroup_mutex, we're safe to drop
1951 * it here; it will be freed under RCU.
1953 set_bit(CGRP_RELEASABLE
, &oldcgrp
->flags
);
1958 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1959 * @cgrp: the cgroup to attach to
1960 * @tsk: the task or the leader of the threadgroup to be attached
1961 * @threadgroup: attach the whole threadgroup?
1963 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
1964 * task_lock of @tsk or each thread in the threadgroup individually in turn.
1966 static int cgroup_attach_task(struct cgroup
*cgrp
, struct task_struct
*tsk
,
1969 int retval
, i
, group_size
;
1970 struct cgroup_subsys
*ss
, *failed_ss
= NULL
;
1971 struct cgroupfs_root
*root
= cgrp
->root
;
1972 /* threadgroup list cursor and array */
1973 struct task_struct
*leader
= tsk
;
1974 struct task_and_cgroup
*tc
;
1975 struct flex_array
*group
;
1976 struct cgroup_taskset tset
= { };
1979 * step 0: in order to do expensive, possibly blocking operations for
1980 * every thread, we cannot iterate the thread group list, since it needs
1981 * rcu or tasklist locked. instead, build an array of all threads in the
1982 * group - group_rwsem prevents new threads from appearing, and if
1983 * threads exit, this will just be an over-estimate.
1986 group_size
= get_nr_threads(tsk
);
1989 /* flex_array supports very large thread-groups better than kmalloc. */
1990 group
= flex_array_alloc(sizeof(*tc
), group_size
, GFP_KERNEL
);
1993 /* pre-allocate to guarantee space while iterating in rcu read-side. */
1994 retval
= flex_array_prealloc(group
, 0, group_size
, GFP_KERNEL
);
1996 goto out_free_group_list
;
2000 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2001 * already PF_EXITING could be freed from underneath us unless we
2002 * take an rcu_read_lock.
2006 struct task_and_cgroup ent
;
2008 /* @tsk either already exited or can't exit until the end */
2009 if (tsk
->flags
& PF_EXITING
)
2012 /* as per above, nr_threads may decrease, but not increase. */
2013 BUG_ON(i
>= group_size
);
2015 ent
.cgrp
= task_cgroup_from_root(tsk
, root
);
2016 /* nothing to do if this task is already in the cgroup */
2017 if (ent
.cgrp
== cgrp
)
2020 * saying GFP_ATOMIC has no effect here because we did prealloc
2021 * earlier, but it's good form to communicate our expectations.
2023 retval
= flex_array_put(group
, i
, &ent
, GFP_ATOMIC
);
2024 BUG_ON(retval
!= 0);
2029 } while_each_thread(leader
, tsk
);
2031 /* remember the number of threads in the array for later. */
2033 tset
.tc_array
= group
;
2034 tset
.tc_array_len
= group_size
;
2036 /* methods shouldn't be called if no task is actually migrating */
2039 goto out_free_group_list
;
2042 * step 1: check that we can legitimately attach to the cgroup.
2044 for_each_subsys(root
, ss
) {
2045 if (ss
->can_attach
) {
2046 retval
= ss
->can_attach(cgrp
, &tset
);
2049 goto out_cancel_attach
;
2055 * step 2: make sure css_sets exist for all threads to be migrated.
2056 * we use find_css_set, which allocates a new one if necessary.
2058 for (i
= 0; i
< group_size
; i
++) {
2059 tc
= flex_array_get(group
, i
);
2060 tc
->cg
= find_css_set(tc
->task
->cgroups
, cgrp
);
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
->cg
);
2076 /* nothing is sensitive to fork() after this point. */
2079 * step 4: do subsystem attach callbacks.
2081 for_each_subsys(root
, ss
) {
2083 ss
->attach(cgrp
, &tset
);
2087 * step 5: success! and cleanup
2090 out_put_css_set_refs
:
2092 for (i
= 0; i
< group_size
; i
++) {
2093 tc
= flex_array_get(group
, i
);
2096 put_css_set(tc
->cg
);
2101 for_each_subsys(root
, ss
) {
2102 if (ss
== failed_ss
)
2104 if (ss
->cancel_attach
)
2105 ss
->cancel_attach(cgrp
, &tset
);
2108 out_free_group_list
:
2109 flex_array_free(group
);
2114 * Find the task_struct of the task to attach by vpid and pass it along to the
2115 * function to attach either it or all tasks in its threadgroup. Will lock
2116 * cgroup_mutex and threadgroup; may take task_lock of task.
2118 static int attach_task_by_pid(struct cgroup
*cgrp
, u64 pid
, bool threadgroup
)
2120 struct task_struct
*tsk
;
2121 const struct cred
*cred
= current_cred(), *tcred
;
2124 if (!cgroup_lock_live_group(cgrp
))
2130 tsk
= find_task_by_vpid(pid
);
2134 goto out_unlock_cgroup
;
2137 * even if we're attaching all tasks in the thread group, we
2138 * only need to check permissions on one of them.
2140 tcred
= __task_cred(tsk
);
2141 if (!uid_eq(cred
->euid
, GLOBAL_ROOT_UID
) &&
2142 !uid_eq(cred
->euid
, tcred
->uid
) &&
2143 !uid_eq(cred
->euid
, tcred
->suid
)) {
2146 goto out_unlock_cgroup
;
2152 tsk
= tsk
->group_leader
;
2155 * Workqueue threads may acquire PF_THREAD_BOUND and become
2156 * trapped in a cpuset, or RT worker may be born in a cgroup
2157 * with no rt_runtime allocated. Just say no.
2159 if (tsk
== kthreadd_task
|| (tsk
->flags
& PF_THREAD_BOUND
)) {
2162 goto out_unlock_cgroup
;
2165 get_task_struct(tsk
);
2168 threadgroup_lock(tsk
);
2170 if (!thread_group_leader(tsk
)) {
2172 * a race with de_thread from another thread's exec()
2173 * may strip us of our leadership, if this happens,
2174 * there is no choice but to throw this task away and
2175 * try again; this is
2176 * "double-double-toil-and-trouble-check locking".
2178 threadgroup_unlock(tsk
);
2179 put_task_struct(tsk
);
2180 goto retry_find_task
;
2184 ret
= cgroup_attach_task(cgrp
, tsk
, threadgroup
);
2186 threadgroup_unlock(tsk
);
2188 put_task_struct(tsk
);
2190 mutex_unlock(&cgroup_mutex
);
2195 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2196 * @from: attach to all cgroups of a given task
2197 * @tsk: the task to be attached
2199 int cgroup_attach_task_all(struct task_struct
*from
, struct task_struct
*tsk
)
2201 struct cgroupfs_root
*root
;
2204 mutex_lock(&cgroup_mutex
);
2205 for_each_active_root(root
) {
2206 struct cgroup
*from_cg
= task_cgroup_from_root(from
, root
);
2208 retval
= cgroup_attach_task(from_cg
, tsk
, false);
2212 mutex_unlock(&cgroup_mutex
);
2216 EXPORT_SYMBOL_GPL(cgroup_attach_task_all
);
2218 static int cgroup_tasks_write(struct cgroup
*cgrp
, struct cftype
*cft
, u64 pid
)
2220 return attach_task_by_pid(cgrp
, pid
, false);
2223 static int cgroup_procs_write(struct cgroup
*cgrp
, struct cftype
*cft
, u64 tgid
)
2225 return attach_task_by_pid(cgrp
, tgid
, true);
2228 static int cgroup_release_agent_write(struct cgroup
*cgrp
, struct cftype
*cft
,
2231 BUILD_BUG_ON(sizeof(cgrp
->root
->release_agent_path
) < PATH_MAX
);
2232 if (strlen(buffer
) >= PATH_MAX
)
2234 if (!cgroup_lock_live_group(cgrp
))
2236 mutex_lock(&cgroup_root_mutex
);
2237 strcpy(cgrp
->root
->release_agent_path
, buffer
);
2238 mutex_unlock(&cgroup_root_mutex
);
2239 mutex_unlock(&cgroup_mutex
);
2243 static int cgroup_release_agent_show(struct cgroup
*cgrp
, struct cftype
*cft
,
2244 struct seq_file
*seq
)
2246 if (!cgroup_lock_live_group(cgrp
))
2248 seq_puts(seq
, cgrp
->root
->release_agent_path
);
2249 seq_putc(seq
, '\n');
2250 mutex_unlock(&cgroup_mutex
);
2254 /* A buffer size big enough for numbers or short strings */
2255 #define CGROUP_LOCAL_BUFFER_SIZE 64
2257 static ssize_t
cgroup_write_X64(struct cgroup
*cgrp
, struct cftype
*cft
,
2259 const char __user
*userbuf
,
2260 size_t nbytes
, loff_t
*unused_ppos
)
2262 char buffer
[CGROUP_LOCAL_BUFFER_SIZE
];
2268 if (nbytes
>= sizeof(buffer
))
2270 if (copy_from_user(buffer
, userbuf
, nbytes
))
2273 buffer
[nbytes
] = 0; /* nul-terminate */
2274 if (cft
->write_u64
) {
2275 u64 val
= simple_strtoull(strstrip(buffer
), &end
, 0);
2278 retval
= cft
->write_u64(cgrp
, cft
, val
);
2280 s64 val
= simple_strtoll(strstrip(buffer
), &end
, 0);
2283 retval
= cft
->write_s64(cgrp
, cft
, val
);
2290 static ssize_t
cgroup_write_string(struct cgroup
*cgrp
, struct cftype
*cft
,
2292 const char __user
*userbuf
,
2293 size_t nbytes
, loff_t
*unused_ppos
)
2295 char local_buffer
[CGROUP_LOCAL_BUFFER_SIZE
];
2297 size_t max_bytes
= cft
->max_write_len
;
2298 char *buffer
= local_buffer
;
2301 max_bytes
= sizeof(local_buffer
) - 1;
2302 if (nbytes
>= max_bytes
)
2304 /* Allocate a dynamic buffer if we need one */
2305 if (nbytes
>= sizeof(local_buffer
)) {
2306 buffer
= kmalloc(nbytes
+ 1, GFP_KERNEL
);
2310 if (nbytes
&& copy_from_user(buffer
, userbuf
, nbytes
)) {
2315 buffer
[nbytes
] = 0; /* nul-terminate */
2316 retval
= cft
->write_string(cgrp
, cft
, strstrip(buffer
));
2320 if (buffer
!= local_buffer
)
2325 static ssize_t
cgroup_file_write(struct file
*file
, const char __user
*buf
,
2326 size_t nbytes
, loff_t
*ppos
)
2328 struct cftype
*cft
= __d_cft(file
->f_dentry
);
2329 struct cgroup
*cgrp
= __d_cgrp(file
->f_dentry
->d_parent
);
2331 if (cgroup_is_removed(cgrp
))
2334 return cft
->write(cgrp
, cft
, file
, buf
, nbytes
, ppos
);
2335 if (cft
->write_u64
|| cft
->write_s64
)
2336 return cgroup_write_X64(cgrp
, cft
, file
, buf
, nbytes
, ppos
);
2337 if (cft
->write_string
)
2338 return cgroup_write_string(cgrp
, cft
, file
, buf
, nbytes
, ppos
);
2340 int ret
= cft
->trigger(cgrp
, (unsigned int)cft
->private);
2341 return ret
? ret
: nbytes
;
2346 static ssize_t
cgroup_read_u64(struct cgroup
*cgrp
, struct cftype
*cft
,
2348 char __user
*buf
, size_t nbytes
,
2351 char tmp
[CGROUP_LOCAL_BUFFER_SIZE
];
2352 u64 val
= cft
->read_u64(cgrp
, cft
);
2353 int len
= sprintf(tmp
, "%llu\n", (unsigned long long) val
);
2355 return simple_read_from_buffer(buf
, nbytes
, ppos
, tmp
, len
);
2358 static ssize_t
cgroup_read_s64(struct cgroup
*cgrp
, struct cftype
*cft
,
2360 char __user
*buf
, size_t nbytes
,
2363 char tmp
[CGROUP_LOCAL_BUFFER_SIZE
];
2364 s64 val
= cft
->read_s64(cgrp
, cft
);
2365 int len
= sprintf(tmp
, "%lld\n", (long long) val
);
2367 return simple_read_from_buffer(buf
, nbytes
, ppos
, tmp
, len
);
2370 static ssize_t
cgroup_file_read(struct file
*file
, char __user
*buf
,
2371 size_t nbytes
, loff_t
*ppos
)
2373 struct cftype
*cft
= __d_cft(file
->f_dentry
);
2374 struct cgroup
*cgrp
= __d_cgrp(file
->f_dentry
->d_parent
);
2376 if (cgroup_is_removed(cgrp
))
2380 return cft
->read(cgrp
, cft
, file
, buf
, nbytes
, ppos
);
2382 return cgroup_read_u64(cgrp
, cft
, file
, buf
, nbytes
, ppos
);
2384 return cgroup_read_s64(cgrp
, cft
, file
, buf
, nbytes
, ppos
);
2389 * seqfile ops/methods for returning structured data. Currently just
2390 * supports string->u64 maps, but can be extended in future.
2393 struct cgroup_seqfile_state
{
2395 struct cgroup
*cgroup
;
2398 static int cgroup_map_add(struct cgroup_map_cb
*cb
, const char *key
, u64 value
)
2400 struct seq_file
*sf
= cb
->state
;
2401 return seq_printf(sf
, "%s %llu\n", key
, (unsigned long long)value
);
2404 static int cgroup_seqfile_show(struct seq_file
*m
, void *arg
)
2406 struct cgroup_seqfile_state
*state
= m
->private;
2407 struct cftype
*cft
= state
->cft
;
2408 if (cft
->read_map
) {
2409 struct cgroup_map_cb cb
= {
2410 .fill
= cgroup_map_add
,
2413 return cft
->read_map(state
->cgroup
, cft
, &cb
);
2415 return cft
->read_seq_string(state
->cgroup
, cft
, m
);
2418 static int cgroup_seqfile_release(struct inode
*inode
, struct file
*file
)
2420 struct seq_file
*seq
= file
->private_data
;
2421 kfree(seq
->private);
2422 return single_release(inode
, file
);
2425 static const struct file_operations cgroup_seqfile_operations
= {
2427 .write
= cgroup_file_write
,
2428 .llseek
= seq_lseek
,
2429 .release
= cgroup_seqfile_release
,
2432 static int cgroup_file_open(struct inode
*inode
, struct file
*file
)
2437 err
= generic_file_open(inode
, file
);
2440 cft
= __d_cft(file
->f_dentry
);
2442 if (cft
->read_map
|| cft
->read_seq_string
) {
2443 struct cgroup_seqfile_state
*state
=
2444 kzalloc(sizeof(*state
), GFP_USER
);
2448 state
->cgroup
= __d_cgrp(file
->f_dentry
->d_parent
);
2449 file
->f_op
= &cgroup_seqfile_operations
;
2450 err
= single_open(file
, cgroup_seqfile_show
, state
);
2453 } else if (cft
->open
)
2454 err
= cft
->open(inode
, file
);
2461 static int cgroup_file_release(struct inode
*inode
, struct file
*file
)
2463 struct cftype
*cft
= __d_cft(file
->f_dentry
);
2465 return cft
->release(inode
, file
);
2470 * cgroup_rename - Only allow simple rename of directories in place.
2472 static int cgroup_rename(struct inode
*old_dir
, struct dentry
*old_dentry
,
2473 struct inode
*new_dir
, struct dentry
*new_dentry
)
2476 struct cgroup_name
*name
, *old_name
;
2477 struct cgroup
*cgrp
;
2480 * It's convinient to use parent dir's i_mutex to protected
2483 lockdep_assert_held(&old_dir
->i_mutex
);
2485 if (!S_ISDIR(old_dentry
->d_inode
->i_mode
))
2487 if (new_dentry
->d_inode
)
2489 if (old_dir
!= new_dir
)
2492 cgrp
= __d_cgrp(old_dentry
);
2494 name
= cgroup_alloc_name(new_dentry
);
2498 ret
= simple_rename(old_dir
, old_dentry
, new_dir
, new_dentry
);
2504 old_name
= cgrp
->name
;
2505 rcu_assign_pointer(cgrp
->name
, name
);
2507 kfree_rcu(old_name
, rcu_head
);
2511 static struct simple_xattrs
*__d_xattrs(struct dentry
*dentry
)
2513 if (S_ISDIR(dentry
->d_inode
->i_mode
))
2514 return &__d_cgrp(dentry
)->xattrs
;
2516 return &__d_cft(dentry
)->xattrs
;
2519 static inline int xattr_enabled(struct dentry
*dentry
)
2521 struct cgroupfs_root
*root
= dentry
->d_sb
->s_fs_info
;
2522 return test_bit(ROOT_XATTR
, &root
->flags
);
2525 static bool is_valid_xattr(const char *name
)
2527 if (!strncmp(name
, XATTR_TRUSTED_PREFIX
, XATTR_TRUSTED_PREFIX_LEN
) ||
2528 !strncmp(name
, XATTR_SECURITY_PREFIX
, XATTR_SECURITY_PREFIX_LEN
))
2533 static int cgroup_setxattr(struct dentry
*dentry
, const char *name
,
2534 const void *val
, size_t size
, int flags
)
2536 if (!xattr_enabled(dentry
))
2538 if (!is_valid_xattr(name
))
2540 return simple_xattr_set(__d_xattrs(dentry
), name
, val
, size
, flags
);
2543 static int cgroup_removexattr(struct dentry
*dentry
, const char *name
)
2545 if (!xattr_enabled(dentry
))
2547 if (!is_valid_xattr(name
))
2549 return simple_xattr_remove(__d_xattrs(dentry
), name
);
2552 static ssize_t
cgroup_getxattr(struct dentry
*dentry
, const char *name
,
2553 void *buf
, size_t size
)
2555 if (!xattr_enabled(dentry
))
2557 if (!is_valid_xattr(name
))
2559 return simple_xattr_get(__d_xattrs(dentry
), name
, buf
, size
);
2562 static ssize_t
cgroup_listxattr(struct dentry
*dentry
, char *buf
, size_t size
)
2564 if (!xattr_enabled(dentry
))
2566 return simple_xattr_list(__d_xattrs(dentry
), buf
, size
);
2569 static const struct file_operations cgroup_file_operations
= {
2570 .read
= cgroup_file_read
,
2571 .write
= cgroup_file_write
,
2572 .llseek
= generic_file_llseek
,
2573 .open
= cgroup_file_open
,
2574 .release
= cgroup_file_release
,
2577 static const struct inode_operations cgroup_file_inode_operations
= {
2578 .setxattr
= cgroup_setxattr
,
2579 .getxattr
= cgroup_getxattr
,
2580 .listxattr
= cgroup_listxattr
,
2581 .removexattr
= cgroup_removexattr
,
2584 static const struct inode_operations cgroup_dir_inode_operations
= {
2585 .lookup
= cgroup_lookup
,
2586 .mkdir
= cgroup_mkdir
,
2587 .rmdir
= cgroup_rmdir
,
2588 .rename
= cgroup_rename
,
2589 .setxattr
= cgroup_setxattr
,
2590 .getxattr
= cgroup_getxattr
,
2591 .listxattr
= cgroup_listxattr
,
2592 .removexattr
= cgroup_removexattr
,
2595 static struct dentry
*cgroup_lookup(struct inode
*dir
, struct dentry
*dentry
, unsigned int flags
)
2597 if (dentry
->d_name
.len
> NAME_MAX
)
2598 return ERR_PTR(-ENAMETOOLONG
);
2599 d_add(dentry
, NULL
);
2604 * Check if a file is a control file
2606 static inline struct cftype
*__file_cft(struct file
*file
)
2608 if (file_inode(file
)->i_fop
!= &cgroup_file_operations
)
2609 return ERR_PTR(-EINVAL
);
2610 return __d_cft(file
->f_dentry
);
2613 static int cgroup_create_file(struct dentry
*dentry
, umode_t mode
,
2614 struct super_block
*sb
)
2616 struct inode
*inode
;
2620 if (dentry
->d_inode
)
2623 inode
= cgroup_new_inode(mode
, sb
);
2627 if (S_ISDIR(mode
)) {
2628 inode
->i_op
= &cgroup_dir_inode_operations
;
2629 inode
->i_fop
= &simple_dir_operations
;
2631 /* start off with i_nlink == 2 (for "." entry) */
2633 inc_nlink(dentry
->d_parent
->d_inode
);
2636 * Control reaches here with cgroup_mutex held.
2637 * @inode->i_mutex should nest outside cgroup_mutex but we
2638 * want to populate it immediately without releasing
2639 * cgroup_mutex. As @inode isn't visible to anyone else
2640 * yet, trylock will always succeed without affecting
2643 WARN_ON_ONCE(!mutex_trylock(&inode
->i_mutex
));
2644 } else if (S_ISREG(mode
)) {
2646 inode
->i_fop
= &cgroup_file_operations
;
2647 inode
->i_op
= &cgroup_file_inode_operations
;
2649 d_instantiate(dentry
, inode
);
2650 dget(dentry
); /* Extra count - pin the dentry in core */
2655 * cgroup_file_mode - deduce file mode of a control file
2656 * @cft: the control file in question
2658 * returns cft->mode if ->mode is not 0
2659 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2660 * returns S_IRUGO if it has only a read handler
2661 * returns S_IWUSR if it has only a write hander
2663 static umode_t
cgroup_file_mode(const struct cftype
*cft
)
2670 if (cft
->read
|| cft
->read_u64
|| cft
->read_s64
||
2671 cft
->read_map
|| cft
->read_seq_string
)
2674 if (cft
->write
|| cft
->write_u64
|| cft
->write_s64
||
2675 cft
->write_string
|| cft
->trigger
)
2681 static int cgroup_add_file(struct cgroup
*cgrp
, struct cgroup_subsys
*subsys
,
2684 struct dentry
*dir
= cgrp
->dentry
;
2685 struct cgroup
*parent
= __d_cgrp(dir
);
2686 struct dentry
*dentry
;
2690 char name
[MAX_CGROUP_TYPE_NAMELEN
+ MAX_CFTYPE_NAME
+ 2] = { 0 };
2692 simple_xattrs_init(&cft
->xattrs
);
2694 if (subsys
&& !test_bit(ROOT_NOPREFIX
, &cgrp
->root
->flags
)) {
2695 strcpy(name
, subsys
->name
);
2698 strcat(name
, cft
->name
);
2700 BUG_ON(!mutex_is_locked(&dir
->d_inode
->i_mutex
));
2702 cfe
= kzalloc(sizeof(*cfe
), GFP_KERNEL
);
2706 dentry
= lookup_one_len(name
, dir
, strlen(name
));
2707 if (IS_ERR(dentry
)) {
2708 error
= PTR_ERR(dentry
);
2712 mode
= cgroup_file_mode(cft
);
2713 error
= cgroup_create_file(dentry
, mode
| S_IFREG
, cgrp
->root
->sb
);
2715 cfe
->type
= (void *)cft
;
2716 cfe
->dentry
= dentry
;
2717 dentry
->d_fsdata
= cfe
;
2718 list_add_tail(&cfe
->node
, &parent
->files
);
2727 static int cgroup_addrm_files(struct cgroup
*cgrp
, struct cgroup_subsys
*subsys
,
2728 struct cftype cfts
[], bool is_add
)
2733 for (cft
= cfts
; cft
->name
[0] != '\0'; cft
++) {
2734 /* does cft->flags tell us to skip this file on @cgrp? */
2735 if ((cft
->flags
& CFTYPE_NOT_ON_ROOT
) && !cgrp
->parent
)
2737 if ((cft
->flags
& CFTYPE_ONLY_ON_ROOT
) && cgrp
->parent
)
2741 err
= cgroup_add_file(cgrp
, subsys
, cft
);
2743 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2747 cgroup_rm_file(cgrp
, cft
);
2753 static DEFINE_MUTEX(cgroup_cft_mutex
);
2755 static void cgroup_cfts_prepare(void)
2756 __acquires(&cgroup_cft_mutex
) __acquires(&cgroup_mutex
)
2759 * Thanks to the entanglement with vfs inode locking, we can't walk
2760 * the existing cgroups under cgroup_mutex and create files.
2761 * Instead, we increment reference on all cgroups and build list of
2762 * them using @cgrp->cft_q_node. Grab cgroup_cft_mutex to ensure
2763 * exclusive access to the field.
2765 mutex_lock(&cgroup_cft_mutex
);
2766 mutex_lock(&cgroup_mutex
);
2769 static void cgroup_cfts_commit(struct cgroup_subsys
*ss
,
2770 struct cftype
*cfts
, bool is_add
)
2771 __releases(&cgroup_mutex
) __releases(&cgroup_cft_mutex
)
2774 struct cgroup
*cgrp
, *n
;
2776 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2777 if (cfts
&& ss
->root
!= &rootnode
) {
2778 list_for_each_entry(cgrp
, &ss
->root
->allcg_list
, allcg_node
) {
2780 list_add_tail(&cgrp
->cft_q_node
, &pending
);
2784 mutex_unlock(&cgroup_mutex
);
2787 * All new cgroups will see @cfts update on @ss->cftsets. Add/rm
2788 * files for all cgroups which were created before.
2790 list_for_each_entry_safe(cgrp
, n
, &pending
, cft_q_node
) {
2791 struct inode
*inode
= cgrp
->dentry
->d_inode
;
2793 mutex_lock(&inode
->i_mutex
);
2794 mutex_lock(&cgroup_mutex
);
2795 if (!cgroup_is_removed(cgrp
))
2796 cgroup_addrm_files(cgrp
, ss
, cfts
, is_add
);
2797 mutex_unlock(&cgroup_mutex
);
2798 mutex_unlock(&inode
->i_mutex
);
2800 list_del_init(&cgrp
->cft_q_node
);
2804 mutex_unlock(&cgroup_cft_mutex
);
2808 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2809 * @ss: target cgroup subsystem
2810 * @cfts: zero-length name terminated array of cftypes
2812 * Register @cfts to @ss. Files described by @cfts are created for all
2813 * existing cgroups to which @ss is attached and all future cgroups will
2814 * have them too. This function can be called anytime whether @ss is
2817 * Returns 0 on successful registration, -errno on failure. Note that this
2818 * function currently returns 0 as long as @cfts registration is successful
2819 * even if some file creation attempts on existing cgroups fail.
2821 int cgroup_add_cftypes(struct cgroup_subsys
*ss
, struct cftype
*cfts
)
2823 struct cftype_set
*set
;
2825 set
= kzalloc(sizeof(*set
), GFP_KERNEL
);
2829 cgroup_cfts_prepare();
2831 list_add_tail(&set
->node
, &ss
->cftsets
);
2832 cgroup_cfts_commit(ss
, cfts
, true);
2836 EXPORT_SYMBOL_GPL(cgroup_add_cftypes
);
2839 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2840 * @ss: target cgroup subsystem
2841 * @cfts: zero-length name terminated array of cftypes
2843 * Unregister @cfts from @ss. Files described by @cfts are removed from
2844 * all existing cgroups to which @ss is attached and all future cgroups
2845 * won't have them either. This function can be called anytime whether @ss
2846 * is attached or not.
2848 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2849 * registered with @ss.
2851 int cgroup_rm_cftypes(struct cgroup_subsys
*ss
, struct cftype
*cfts
)
2853 struct cftype_set
*set
;
2855 cgroup_cfts_prepare();
2857 list_for_each_entry(set
, &ss
->cftsets
, node
) {
2858 if (set
->cfts
== cfts
) {
2859 list_del_init(&set
->node
);
2860 cgroup_cfts_commit(ss
, cfts
, false);
2865 cgroup_cfts_commit(ss
, NULL
, false);
2870 * cgroup_task_count - count the number of tasks in a cgroup.
2871 * @cgrp: the cgroup in question
2873 * Return the number of tasks in the cgroup.
2875 int cgroup_task_count(const struct cgroup
*cgrp
)
2878 struct cg_cgroup_link
*link
;
2880 read_lock(&css_set_lock
);
2881 list_for_each_entry(link
, &cgrp
->css_sets
, cgrp_link_list
) {
2882 count
+= atomic_read(&link
->cg
->refcount
);
2884 read_unlock(&css_set_lock
);
2889 * Advance a list_head iterator. The iterator should be positioned at
2890 * the start of a css_set
2892 static void cgroup_advance_iter(struct cgroup
*cgrp
,
2893 struct cgroup_iter
*it
)
2895 struct list_head
*l
= it
->cg_link
;
2896 struct cg_cgroup_link
*link
;
2899 /* Advance to the next non-empty css_set */
2902 if (l
== &cgrp
->css_sets
) {
2906 link
= list_entry(l
, struct cg_cgroup_link
, cgrp_link_list
);
2908 } while (list_empty(&cg
->tasks
));
2910 it
->task
= cg
->tasks
.next
;
2914 * To reduce the fork() overhead for systems that are not actually
2915 * using their cgroups capability, we don't maintain the lists running
2916 * through each css_set to its tasks until we see the list actually
2917 * used - in other words after the first call to cgroup_iter_start().
2919 static void cgroup_enable_task_cg_lists(void)
2921 struct task_struct
*p
, *g
;
2922 write_lock(&css_set_lock
);
2923 use_task_css_set_links
= 1;
2925 * We need tasklist_lock because RCU is not safe against
2926 * while_each_thread(). Besides, a forking task that has passed
2927 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2928 * is not guaranteed to have its child immediately visible in the
2929 * tasklist if we walk through it with RCU.
2931 read_lock(&tasklist_lock
);
2932 do_each_thread(g
, p
) {
2935 * We should check if the process is exiting, otherwise
2936 * it will race with cgroup_exit() in that the list
2937 * entry won't be deleted though the process has exited.
2939 if (!(p
->flags
& PF_EXITING
) && list_empty(&p
->cg_list
))
2940 list_add(&p
->cg_list
, &p
->cgroups
->tasks
);
2942 } while_each_thread(g
, p
);
2943 read_unlock(&tasklist_lock
);
2944 write_unlock(&css_set_lock
);
2948 * cgroup_next_descendant_pre - find the next descendant for pre-order walk
2949 * @pos: the current position (%NULL to initiate traversal)
2950 * @cgroup: cgroup whose descendants to walk
2952 * To be used by cgroup_for_each_descendant_pre(). Find the next
2953 * descendant to visit for pre-order traversal of @cgroup's descendants.
2955 struct cgroup
*cgroup_next_descendant_pre(struct cgroup
*pos
,
2956 struct cgroup
*cgroup
)
2958 struct cgroup
*next
;
2960 WARN_ON_ONCE(!rcu_read_lock_held());
2962 /* if first iteration, pretend we just visited @cgroup */
2964 if (list_empty(&cgroup
->children
))
2969 /* visit the first child if exists */
2970 next
= list_first_or_null_rcu(&pos
->children
, struct cgroup
, sibling
);
2974 /* no child, visit my or the closest ancestor's next sibling */
2976 next
= list_entry_rcu(pos
->sibling
.next
, struct cgroup
,
2978 if (&next
->sibling
!= &pos
->parent
->children
)
2982 } while (pos
!= cgroup
);
2986 EXPORT_SYMBOL_GPL(cgroup_next_descendant_pre
);
2989 * cgroup_rightmost_descendant - return the rightmost descendant of a cgroup
2990 * @pos: cgroup of interest
2992 * Return the rightmost descendant of @pos. If there's no descendant,
2993 * @pos is returned. This can be used during pre-order traversal to skip
2996 struct cgroup
*cgroup_rightmost_descendant(struct cgroup
*pos
)
2998 struct cgroup
*last
, *tmp
;
3000 WARN_ON_ONCE(!rcu_read_lock_held());
3004 /* ->prev isn't RCU safe, walk ->next till the end */
3006 list_for_each_entry_rcu(tmp
, &last
->children
, sibling
)
3012 EXPORT_SYMBOL_GPL(cgroup_rightmost_descendant
);
3014 static struct cgroup
*cgroup_leftmost_descendant(struct cgroup
*pos
)
3016 struct cgroup
*last
;
3020 pos
= list_first_or_null_rcu(&pos
->children
, struct cgroup
,
3028 * cgroup_next_descendant_post - find the next descendant for post-order walk
3029 * @pos: the current position (%NULL to initiate traversal)
3030 * @cgroup: cgroup whose descendants to walk
3032 * To be used by cgroup_for_each_descendant_post(). Find the next
3033 * descendant to visit for post-order traversal of @cgroup's descendants.
3035 struct cgroup
*cgroup_next_descendant_post(struct cgroup
*pos
,
3036 struct cgroup
*cgroup
)
3038 struct cgroup
*next
;
3040 WARN_ON_ONCE(!rcu_read_lock_held());
3042 /* if first iteration, visit the leftmost descendant */
3044 next
= cgroup_leftmost_descendant(cgroup
);
3045 return next
!= cgroup
? next
: NULL
;
3048 /* if there's an unvisited sibling, visit its leftmost descendant */
3049 next
= list_entry_rcu(pos
->sibling
.next
, struct cgroup
, sibling
);
3050 if (&next
->sibling
!= &pos
->parent
->children
)
3051 return cgroup_leftmost_descendant(next
);
3053 /* no sibling left, visit parent */
3055 return next
!= cgroup
? next
: NULL
;
3057 EXPORT_SYMBOL_GPL(cgroup_next_descendant_post
);
3059 void cgroup_iter_start(struct cgroup
*cgrp
, struct cgroup_iter
*it
)
3060 __acquires(css_set_lock
)
3063 * The first time anyone tries to iterate across a cgroup,
3064 * we need to enable the list linking each css_set to its
3065 * tasks, and fix up all existing tasks.
3067 if (!use_task_css_set_links
)
3068 cgroup_enable_task_cg_lists();
3070 read_lock(&css_set_lock
);
3071 it
->cg_link
= &cgrp
->css_sets
;
3072 cgroup_advance_iter(cgrp
, it
);
3075 struct task_struct
*cgroup_iter_next(struct cgroup
*cgrp
,
3076 struct cgroup_iter
*it
)
3078 struct task_struct
*res
;
3079 struct list_head
*l
= it
->task
;
3080 struct cg_cgroup_link
*link
;
3082 /* If the iterator cg is NULL, we have no tasks */
3085 res
= list_entry(l
, struct task_struct
, cg_list
);
3086 /* Advance iterator to find next entry */
3088 link
= list_entry(it
->cg_link
, struct cg_cgroup_link
, cgrp_link_list
);
3089 if (l
== &link
->cg
->tasks
) {
3090 /* We reached the end of this task list - move on to
3091 * the next cg_cgroup_link */
3092 cgroup_advance_iter(cgrp
, it
);
3099 void cgroup_iter_end(struct cgroup
*cgrp
, struct cgroup_iter
*it
)
3100 __releases(css_set_lock
)
3102 read_unlock(&css_set_lock
);
3105 static inline int started_after_time(struct task_struct
*t1
,
3106 struct timespec
*time
,
3107 struct task_struct
*t2
)
3109 int start_diff
= timespec_compare(&t1
->start_time
, time
);
3110 if (start_diff
> 0) {
3112 } else if (start_diff
< 0) {
3116 * Arbitrarily, if two processes started at the same
3117 * time, we'll say that the lower pointer value
3118 * started first. Note that t2 may have exited by now
3119 * so this may not be a valid pointer any longer, but
3120 * that's fine - it still serves to distinguish
3121 * between two tasks started (effectively) simultaneously.
3128 * This function is a callback from heap_insert() and is used to order
3130 * In this case we order the heap in descending task start time.
3132 static inline int started_after(void *p1
, void *p2
)
3134 struct task_struct
*t1
= p1
;
3135 struct task_struct
*t2
= p2
;
3136 return started_after_time(t1
, &t2
->start_time
, t2
);
3140 * cgroup_scan_tasks - iterate though all the tasks in a cgroup
3141 * @scan: struct cgroup_scanner containing arguments for the scan
3143 * Arguments include pointers to callback functions test_task() and
3145 * Iterate through all the tasks in a cgroup, calling test_task() for each,
3146 * and if it returns true, call process_task() for it also.
3147 * The test_task pointer may be NULL, meaning always true (select all tasks).
3148 * Effectively duplicates cgroup_iter_{start,next,end}()
3149 * but does not lock css_set_lock for the call to process_task().
3150 * The struct cgroup_scanner may be embedded in any structure of the caller's
3152 * It is guaranteed that process_task() will act on every task that
3153 * is a member of the cgroup for the duration of this call. This
3154 * function may or may not call process_task() for tasks that exit
3155 * or move to a different cgroup during the call, or are forked or
3156 * move into the cgroup during the call.
3158 * Note that test_task() may be called with locks held, and may in some
3159 * situations be called multiple times for the same task, so it should
3161 * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
3162 * pre-allocated and will be used for heap operations (and its "gt" member will
3163 * be overwritten), else a temporary heap will be used (allocation of which
3164 * may cause this function to fail).
3166 int cgroup_scan_tasks(struct cgroup_scanner
*scan
)
3169 struct cgroup_iter it
;
3170 struct task_struct
*p
, *dropped
;
3171 /* Never dereference latest_task, since it's not refcounted */
3172 struct task_struct
*latest_task
= NULL
;
3173 struct ptr_heap tmp_heap
;
3174 struct ptr_heap
*heap
;
3175 struct timespec latest_time
= { 0, 0 };
3178 /* The caller supplied our heap and pre-allocated its memory */
3180 heap
->gt
= &started_after
;
3182 /* We need to allocate our own heap memory */
3184 retval
= heap_init(heap
, PAGE_SIZE
, GFP_KERNEL
, &started_after
);
3186 /* cannot allocate the heap */
3192 * Scan tasks in the cgroup, using the scanner's "test_task" callback
3193 * to determine which are of interest, and using the scanner's
3194 * "process_task" callback to process any of them that need an update.
3195 * Since we don't want to hold any locks during the task updates,
3196 * gather tasks to be processed in a heap structure.
3197 * The heap is sorted by descending task start time.
3198 * If the statically-sized heap fills up, we overflow tasks that
3199 * started later, and in future iterations only consider tasks that
3200 * started after the latest task in the previous pass. This
3201 * guarantees forward progress and that we don't miss any tasks.
3204 cgroup_iter_start(scan
->cg
, &it
);
3205 while ((p
= cgroup_iter_next(scan
->cg
, &it
))) {
3207 * Only affect tasks that qualify per the caller's callback,
3208 * if he provided one
3210 if (scan
->test_task
&& !scan
->test_task(p
, scan
))
3213 * Only process tasks that started after the last task
3216 if (!started_after_time(p
, &latest_time
, latest_task
))
3218 dropped
= heap_insert(heap
, p
);
3219 if (dropped
== NULL
) {
3221 * The new task was inserted; the heap wasn't
3225 } else if (dropped
!= p
) {
3227 * The new task was inserted, and pushed out a
3231 put_task_struct(dropped
);
3234 * Else the new task was newer than anything already in
3235 * the heap and wasn't inserted
3238 cgroup_iter_end(scan
->cg
, &it
);
3241 for (i
= 0; i
< heap
->size
; i
++) {
3242 struct task_struct
*q
= heap
->ptrs
[i
];
3244 latest_time
= q
->start_time
;
3247 /* Process the task per the caller's callback */
3248 scan
->process_task(q
, scan
);
3252 * If we had to process any tasks at all, scan again
3253 * in case some of them were in the middle of forking
3254 * children that didn't get processed.
3255 * Not the most efficient way to do it, but it avoids
3256 * having to take callback_mutex in the fork path
3260 if (heap
== &tmp_heap
)
3261 heap_free(&tmp_heap
);
3265 static void cgroup_transfer_one_task(struct task_struct
*task
,
3266 struct cgroup_scanner
*scan
)
3268 struct cgroup
*new_cgroup
= scan
->data
;
3270 mutex_lock(&cgroup_mutex
);
3271 cgroup_attach_task(new_cgroup
, task
, false);
3272 mutex_unlock(&cgroup_mutex
);
3276 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3277 * @to: cgroup to which the tasks will be moved
3278 * @from: cgroup in which the tasks currently reside
3280 int cgroup_transfer_tasks(struct cgroup
*to
, struct cgroup
*from
)
3282 struct cgroup_scanner scan
;
3285 scan
.test_task
= NULL
; /* select all tasks in cgroup */
3286 scan
.process_task
= cgroup_transfer_one_task
;
3290 return cgroup_scan_tasks(&scan
);
3294 * Stuff for reading the 'tasks'/'procs' files.
3296 * Reading this file can return large amounts of data if a cgroup has
3297 * *lots* of attached tasks. So it may need several calls to read(),
3298 * but we cannot guarantee that the information we produce is correct
3299 * unless we produce it entirely atomically.
3303 /* which pidlist file are we talking about? */
3304 enum cgroup_filetype
{
3310 * A pidlist is a list of pids that virtually represents the contents of one
3311 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3312 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3315 struct cgroup_pidlist
{
3317 * used to find which pidlist is wanted. doesn't change as long as
3318 * this particular list stays in the list.
3320 struct { enum cgroup_filetype type
; struct pid_namespace
*ns
; } key
;
3323 /* how many elements the above list has */
3325 /* how many files are using the current array */
3327 /* each of these stored in a list by its cgroup */
3328 struct list_head links
;
3329 /* pointer to the cgroup we belong to, for list removal purposes */
3330 struct cgroup
*owner
;
3331 /* protects the other fields */
3332 struct rw_semaphore mutex
;
3336 * The following two functions "fix" the issue where there are more pids
3337 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3338 * TODO: replace with a kernel-wide solution to this problem
3340 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3341 static void *pidlist_allocate(int count
)
3343 if (PIDLIST_TOO_LARGE(count
))
3344 return vmalloc(count
* sizeof(pid_t
));
3346 return kmalloc(count
* sizeof(pid_t
), GFP_KERNEL
);
3348 static void pidlist_free(void *p
)
3350 if (is_vmalloc_addr(p
))
3357 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3358 * Returns the number of unique elements.
3360 static int pidlist_uniq(pid_t
*list
, int length
)
3365 * we presume the 0th element is unique, so i starts at 1. trivial
3366 * edge cases first; no work needs to be done for either
3368 if (length
== 0 || length
== 1)
3370 /* src and dest walk down the list; dest counts unique elements */
3371 for (src
= 1; src
< length
; src
++) {
3372 /* find next unique element */
3373 while (list
[src
] == list
[src
-1]) {
3378 /* dest always points to where the next unique element goes */
3379 list
[dest
] = list
[src
];
3386 static int cmppid(const void *a
, const void *b
)
3388 return *(pid_t
*)a
- *(pid_t
*)b
;
3392 * find the appropriate pidlist for our purpose (given procs vs tasks)
3393 * returns with the lock on that pidlist already held, and takes care
3394 * of the use count, or returns NULL with no locks held if we're out of
3397 static struct cgroup_pidlist
*cgroup_pidlist_find(struct cgroup
*cgrp
,
3398 enum cgroup_filetype type
)
3400 struct cgroup_pidlist
*l
;
3401 /* don't need task_nsproxy() if we're looking at ourself */
3402 struct pid_namespace
*ns
= task_active_pid_ns(current
);
3405 * We can't drop the pidlist_mutex before taking the l->mutex in case
3406 * the last ref-holder is trying to remove l from the list at the same
3407 * time. Holding the pidlist_mutex precludes somebody taking whichever
3408 * list we find out from under us - compare release_pid_array().
3410 mutex_lock(&cgrp
->pidlist_mutex
);
3411 list_for_each_entry(l
, &cgrp
->pidlists
, links
) {
3412 if (l
->key
.type
== type
&& l
->key
.ns
== ns
) {
3413 /* make sure l doesn't vanish out from under us */
3414 down_write(&l
->mutex
);
3415 mutex_unlock(&cgrp
->pidlist_mutex
);
3419 /* entry not found; create a new one */
3420 l
= kmalloc(sizeof(struct cgroup_pidlist
), GFP_KERNEL
);
3422 mutex_unlock(&cgrp
->pidlist_mutex
);
3425 init_rwsem(&l
->mutex
);
3426 down_write(&l
->mutex
);
3428 l
->key
.ns
= get_pid_ns(ns
);
3429 l
->use_count
= 0; /* don't increment here */
3432 list_add(&l
->links
, &cgrp
->pidlists
);
3433 mutex_unlock(&cgrp
->pidlist_mutex
);
3438 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3440 static int pidlist_array_load(struct cgroup
*cgrp
, enum cgroup_filetype type
,
3441 struct cgroup_pidlist
**lp
)
3445 int pid
, n
= 0; /* used for populating the array */
3446 struct cgroup_iter it
;
3447 struct task_struct
*tsk
;
3448 struct cgroup_pidlist
*l
;
3451 * If cgroup gets more users after we read count, we won't have
3452 * enough space - tough. This race is indistinguishable to the
3453 * caller from the case that the additional cgroup users didn't
3454 * show up until sometime later on.
3456 length
= cgroup_task_count(cgrp
);
3457 array
= pidlist_allocate(length
);
3460 /* now, populate the array */
3461 cgroup_iter_start(cgrp
, &it
);
3462 while ((tsk
= cgroup_iter_next(cgrp
, &it
))) {
3463 if (unlikely(n
== length
))
3465 /* get tgid or pid for procs or tasks file respectively */
3466 if (type
== CGROUP_FILE_PROCS
)
3467 pid
= task_tgid_vnr(tsk
);
3469 pid
= task_pid_vnr(tsk
);
3470 if (pid
> 0) /* make sure to only use valid results */
3473 cgroup_iter_end(cgrp
, &it
);
3475 /* now sort & (if procs) strip out duplicates */
3476 sort(array
, length
, sizeof(pid_t
), cmppid
, NULL
);
3477 if (type
== CGROUP_FILE_PROCS
)
3478 length
= pidlist_uniq(array
, length
);
3479 l
= cgroup_pidlist_find(cgrp
, type
);
3481 pidlist_free(array
);
3484 /* store array, freeing old if necessary - lock already held */
3485 pidlist_free(l
->list
);
3489 up_write(&l
->mutex
);
3495 * cgroupstats_build - build and fill cgroupstats
3496 * @stats: cgroupstats to fill information into
3497 * @dentry: A dentry entry belonging to the cgroup for which stats have
3500 * Build and fill cgroupstats so that taskstats can export it to user
3503 int cgroupstats_build(struct cgroupstats
*stats
, struct dentry
*dentry
)
3506 struct cgroup
*cgrp
;
3507 struct cgroup_iter it
;
3508 struct task_struct
*tsk
;
3511 * Validate dentry by checking the superblock operations,
3512 * and make sure it's a directory.
3514 if (dentry
->d_sb
->s_op
!= &cgroup_ops
||
3515 !S_ISDIR(dentry
->d_inode
->i_mode
))
3519 cgrp
= dentry
->d_fsdata
;
3521 cgroup_iter_start(cgrp
, &it
);
3522 while ((tsk
= cgroup_iter_next(cgrp
, &it
))) {
3523 switch (tsk
->state
) {
3525 stats
->nr_running
++;
3527 case TASK_INTERRUPTIBLE
:
3528 stats
->nr_sleeping
++;
3530 case TASK_UNINTERRUPTIBLE
:
3531 stats
->nr_uninterruptible
++;
3534 stats
->nr_stopped
++;
3537 if (delayacct_is_task_waiting_on_io(tsk
))
3538 stats
->nr_io_wait
++;
3542 cgroup_iter_end(cgrp
, &it
);
3550 * seq_file methods for the tasks/procs files. The seq_file position is the
3551 * next pid to display; the seq_file iterator is a pointer to the pid
3552 * in the cgroup->l->list array.
3555 static void *cgroup_pidlist_start(struct seq_file
*s
, loff_t
*pos
)
3558 * Initially we receive a position value that corresponds to
3559 * one more than the last pid shown (or 0 on the first call or
3560 * after a seek to the start). Use a binary-search to find the
3561 * next pid to display, if any
3563 struct cgroup_pidlist
*l
= s
->private;
3564 int index
= 0, pid
= *pos
;
3567 down_read(&l
->mutex
);
3569 int end
= l
->length
;
3571 while (index
< end
) {
3572 int mid
= (index
+ end
) / 2;
3573 if (l
->list
[mid
] == pid
) {
3576 } else if (l
->list
[mid
] <= pid
)
3582 /* If we're off the end of the array, we're done */
3583 if (index
>= l
->length
)
3585 /* Update the abstract position to be the actual pid that we found */
3586 iter
= l
->list
+ index
;
3591 static void cgroup_pidlist_stop(struct seq_file
*s
, void *v
)
3593 struct cgroup_pidlist
*l
= s
->private;
3597 static void *cgroup_pidlist_next(struct seq_file
*s
, void *v
, loff_t
*pos
)
3599 struct cgroup_pidlist
*l
= s
->private;
3601 pid_t
*end
= l
->list
+ l
->length
;
3603 * Advance to the next pid in the array. If this goes off the
3615 static int cgroup_pidlist_show(struct seq_file
*s
, void *v
)
3617 return seq_printf(s
, "%d\n", *(int *)v
);
3621 * seq_operations functions for iterating on pidlists through seq_file -
3622 * independent of whether it's tasks or procs
3624 static const struct seq_operations cgroup_pidlist_seq_operations
= {
3625 .start
= cgroup_pidlist_start
,
3626 .stop
= cgroup_pidlist_stop
,
3627 .next
= cgroup_pidlist_next
,
3628 .show
= cgroup_pidlist_show
,
3631 static void cgroup_release_pid_array(struct cgroup_pidlist
*l
)
3634 * the case where we're the last user of this particular pidlist will
3635 * have us remove it from the cgroup's list, which entails taking the
3636 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3637 * pidlist_mutex, we have to take pidlist_mutex first.
3639 mutex_lock(&l
->owner
->pidlist_mutex
);
3640 down_write(&l
->mutex
);
3641 BUG_ON(!l
->use_count
);
3642 if (!--l
->use_count
) {
3643 /* we're the last user if refcount is 0; remove and free */
3644 list_del(&l
->links
);
3645 mutex_unlock(&l
->owner
->pidlist_mutex
);
3646 pidlist_free(l
->list
);
3647 put_pid_ns(l
->key
.ns
);
3648 up_write(&l
->mutex
);
3652 mutex_unlock(&l
->owner
->pidlist_mutex
);
3653 up_write(&l
->mutex
);
3656 static int cgroup_pidlist_release(struct inode
*inode
, struct file
*file
)
3658 struct cgroup_pidlist
*l
;
3659 if (!(file
->f_mode
& FMODE_READ
))
3662 * the seq_file will only be initialized if the file was opened for
3663 * reading; hence we check if it's not null only in that case.
3665 l
= ((struct seq_file
*)file
->private_data
)->private;
3666 cgroup_release_pid_array(l
);
3667 return seq_release(inode
, file
);
3670 static const struct file_operations cgroup_pidlist_operations
= {
3672 .llseek
= seq_lseek
,
3673 .write
= cgroup_file_write
,
3674 .release
= cgroup_pidlist_release
,
3678 * The following functions handle opens on a file that displays a pidlist
3679 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3682 /* helper function for the two below it */
3683 static int cgroup_pidlist_open(struct file
*file
, enum cgroup_filetype type
)
3685 struct cgroup
*cgrp
= __d_cgrp(file
->f_dentry
->d_parent
);
3686 struct cgroup_pidlist
*l
;
3689 /* Nothing to do for write-only files */
3690 if (!(file
->f_mode
& FMODE_READ
))
3693 /* have the array populated */
3694 retval
= pidlist_array_load(cgrp
, type
, &l
);
3697 /* configure file information */
3698 file
->f_op
= &cgroup_pidlist_operations
;
3700 retval
= seq_open(file
, &cgroup_pidlist_seq_operations
);
3702 cgroup_release_pid_array(l
);
3705 ((struct seq_file
*)file
->private_data
)->private = l
;
3708 static int cgroup_tasks_open(struct inode
*unused
, struct file
*file
)
3710 return cgroup_pidlist_open(file
, CGROUP_FILE_TASKS
);
3712 static int cgroup_procs_open(struct inode
*unused
, struct file
*file
)
3714 return cgroup_pidlist_open(file
, CGROUP_FILE_PROCS
);
3717 static u64
cgroup_read_notify_on_release(struct cgroup
*cgrp
,
3720 return notify_on_release(cgrp
);
3723 static int cgroup_write_notify_on_release(struct cgroup
*cgrp
,
3727 clear_bit(CGRP_RELEASABLE
, &cgrp
->flags
);
3729 set_bit(CGRP_NOTIFY_ON_RELEASE
, &cgrp
->flags
);
3731 clear_bit(CGRP_NOTIFY_ON_RELEASE
, &cgrp
->flags
);
3736 * Unregister event and free resources.
3738 * Gets called from workqueue.
3740 static void cgroup_event_remove(struct work_struct
*work
)
3742 struct cgroup_event
*event
= container_of(work
, struct cgroup_event
,
3744 struct cgroup
*cgrp
= event
->cgrp
;
3746 remove_wait_queue(event
->wqh
, &event
->wait
);
3748 event
->cft
->unregister_event(cgrp
, event
->cft
, event
->eventfd
);
3750 /* Notify userspace the event is going away. */
3751 eventfd_signal(event
->eventfd
, 1);
3753 eventfd_ctx_put(event
->eventfd
);
3759 * Gets called on POLLHUP on eventfd when user closes it.
3761 * Called with wqh->lock held and interrupts disabled.
3763 static int cgroup_event_wake(wait_queue_t
*wait
, unsigned mode
,
3764 int sync
, void *key
)
3766 struct cgroup_event
*event
= container_of(wait
,
3767 struct cgroup_event
, wait
);
3768 struct cgroup
*cgrp
= event
->cgrp
;
3769 unsigned long flags
= (unsigned long)key
;
3771 if (flags
& POLLHUP
) {
3773 * If the event has been detached at cgroup removal, we
3774 * can simply return knowing the other side will cleanup
3777 * We can't race against event freeing since the other
3778 * side will require wqh->lock via remove_wait_queue(),
3781 spin_lock(&cgrp
->event_list_lock
);
3782 if (!list_empty(&event
->list
)) {
3783 list_del_init(&event
->list
);
3785 * We are in atomic context, but cgroup_event_remove()
3786 * may sleep, so we have to call it in workqueue.
3788 schedule_work(&event
->remove
);
3790 spin_unlock(&cgrp
->event_list_lock
);
3796 static void cgroup_event_ptable_queue_proc(struct file
*file
,
3797 wait_queue_head_t
*wqh
, poll_table
*pt
)
3799 struct cgroup_event
*event
= container_of(pt
,
3800 struct cgroup_event
, pt
);
3803 add_wait_queue(wqh
, &event
->wait
);
3807 * Parse input and register new cgroup event handler.
3809 * Input must be in format '<event_fd> <control_fd> <args>'.
3810 * Interpretation of args is defined by control file implementation.
3812 static int cgroup_write_event_control(struct cgroup
*cgrp
, struct cftype
*cft
,
3815 struct cgroup_event
*event
= NULL
;
3816 struct cgroup
*cgrp_cfile
;
3817 unsigned int efd
, cfd
;
3818 struct file
*efile
= NULL
;
3819 struct file
*cfile
= NULL
;
3823 efd
= simple_strtoul(buffer
, &endp
, 10);
3828 cfd
= simple_strtoul(buffer
, &endp
, 10);
3829 if ((*endp
!= ' ') && (*endp
!= '\0'))
3833 event
= kzalloc(sizeof(*event
), GFP_KERNEL
);
3837 INIT_LIST_HEAD(&event
->list
);
3838 init_poll_funcptr(&event
->pt
, cgroup_event_ptable_queue_proc
);
3839 init_waitqueue_func_entry(&event
->wait
, cgroup_event_wake
);
3840 INIT_WORK(&event
->remove
, cgroup_event_remove
);
3842 efile
= eventfd_fget(efd
);
3843 if (IS_ERR(efile
)) {
3844 ret
= PTR_ERR(efile
);
3848 event
->eventfd
= eventfd_ctx_fileget(efile
);
3849 if (IS_ERR(event
->eventfd
)) {
3850 ret
= PTR_ERR(event
->eventfd
);
3860 /* the process need read permission on control file */
3861 /* AV: shouldn't we check that it's been opened for read instead? */
3862 ret
= inode_permission(file_inode(cfile
), MAY_READ
);
3866 event
->cft
= __file_cft(cfile
);
3867 if (IS_ERR(event
->cft
)) {
3868 ret
= PTR_ERR(event
->cft
);
3873 * The file to be monitored must be in the same cgroup as
3874 * cgroup.event_control is.
3876 cgrp_cfile
= __d_cgrp(cfile
->f_dentry
->d_parent
);
3877 if (cgrp_cfile
!= cgrp
) {
3882 if (!event
->cft
->register_event
|| !event
->cft
->unregister_event
) {
3887 ret
= event
->cft
->register_event(cgrp
, event
->cft
,
3888 event
->eventfd
, buffer
);
3893 * Events should be removed after rmdir of cgroup directory, but before
3894 * destroying subsystem state objects. Let's take reference to cgroup
3895 * directory dentry to do that.
3899 spin_lock(&cgrp
->event_list_lock
);
3900 list_add(&event
->list
, &cgrp
->event_list
);
3901 spin_unlock(&cgrp
->event_list_lock
);
3912 if (event
&& event
->eventfd
&& !IS_ERR(event
->eventfd
))
3913 eventfd_ctx_put(event
->eventfd
);
3915 if (!IS_ERR_OR_NULL(efile
))
3923 static u64
cgroup_clone_children_read(struct cgroup
*cgrp
,
3926 return test_bit(CGRP_CPUSET_CLONE_CHILDREN
, &cgrp
->flags
);
3929 static int cgroup_clone_children_write(struct cgroup
*cgrp
,
3934 set_bit(CGRP_CPUSET_CLONE_CHILDREN
, &cgrp
->flags
);
3936 clear_bit(CGRP_CPUSET_CLONE_CHILDREN
, &cgrp
->flags
);
3941 * for the common functions, 'private' gives the type of file
3943 /* for hysterical raisins, we can't put this on the older files */
3944 #define CGROUP_FILE_GENERIC_PREFIX "cgroup."
3945 static struct cftype files
[] = {
3948 .open
= cgroup_tasks_open
,
3949 .write_u64
= cgroup_tasks_write
,
3950 .release
= cgroup_pidlist_release
,
3951 .mode
= S_IRUGO
| S_IWUSR
,
3954 .name
= CGROUP_FILE_GENERIC_PREFIX
"procs",
3955 .open
= cgroup_procs_open
,
3956 .write_u64
= cgroup_procs_write
,
3957 .release
= cgroup_pidlist_release
,
3958 .mode
= S_IRUGO
| S_IWUSR
,
3961 .name
= "notify_on_release",
3962 .read_u64
= cgroup_read_notify_on_release
,
3963 .write_u64
= cgroup_write_notify_on_release
,
3966 .name
= CGROUP_FILE_GENERIC_PREFIX
"event_control",
3967 .write_string
= cgroup_write_event_control
,
3971 .name
= "cgroup.clone_children",
3972 .read_u64
= cgroup_clone_children_read
,
3973 .write_u64
= cgroup_clone_children_write
,
3976 .name
= "release_agent",
3977 .flags
= CFTYPE_ONLY_ON_ROOT
,
3978 .read_seq_string
= cgroup_release_agent_show
,
3979 .write_string
= cgroup_release_agent_write
,
3980 .max_write_len
= PATH_MAX
,
3986 * cgroup_populate_dir - selectively creation of files in a directory
3987 * @cgrp: target cgroup
3988 * @base_files: true if the base files should be added
3989 * @subsys_mask: mask of the subsystem ids whose files should be added
3991 static int cgroup_populate_dir(struct cgroup
*cgrp
, bool base_files
,
3992 unsigned long subsys_mask
)
3995 struct cgroup_subsys
*ss
;
3998 err
= cgroup_addrm_files(cgrp
, NULL
, files
, true);
4003 /* process cftsets of each subsystem */
4004 for_each_subsys(cgrp
->root
, ss
) {
4005 struct cftype_set
*set
;
4006 if (!test_bit(ss
->subsys_id
, &subsys_mask
))
4009 list_for_each_entry(set
, &ss
->cftsets
, node
)
4010 cgroup_addrm_files(cgrp
, ss
, set
->cfts
, true);
4013 /* This cgroup is ready now */
4014 for_each_subsys(cgrp
->root
, ss
) {
4015 struct cgroup_subsys_state
*css
= cgrp
->subsys
[ss
->subsys_id
];
4017 * Update id->css pointer and make this css visible from
4018 * CSS ID functions. This pointer will be dereferened
4019 * from RCU-read-side without locks.
4022 rcu_assign_pointer(css
->id
->css
, css
);
4028 static void css_dput_fn(struct work_struct
*work
)
4030 struct cgroup_subsys_state
*css
=
4031 container_of(work
, struct cgroup_subsys_state
, dput_work
);
4032 struct dentry
*dentry
= css
->cgroup
->dentry
;
4033 struct super_block
*sb
= dentry
->d_sb
;
4035 atomic_inc(&sb
->s_active
);
4037 deactivate_super(sb
);
4040 static void init_cgroup_css(struct cgroup_subsys_state
*css
,
4041 struct cgroup_subsys
*ss
,
4042 struct cgroup
*cgrp
)
4045 atomic_set(&css
->refcnt
, 1);
4048 if (cgrp
== dummytop
)
4049 css
->flags
|= CSS_ROOT
;
4050 BUG_ON(cgrp
->subsys
[ss
->subsys_id
]);
4051 cgrp
->subsys
[ss
->subsys_id
] = css
;
4054 * css holds an extra ref to @cgrp->dentry which is put on the last
4055 * css_put(). dput() requires process context, which css_put() may
4056 * be called without. @css->dput_work will be used to invoke
4057 * dput() asynchronously from css_put().
4059 INIT_WORK(&css
->dput_work
, css_dput_fn
);
4062 /* invoke ->post_create() on a new CSS and mark it online if successful */
4063 static int online_css(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
4067 lockdep_assert_held(&cgroup_mutex
);
4070 ret
= ss
->css_online(cgrp
);
4072 cgrp
->subsys
[ss
->subsys_id
]->flags
|= CSS_ONLINE
;
4076 /* if the CSS is online, invoke ->pre_destory() on it and mark it offline */
4077 static void offline_css(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
4078 __releases(&cgroup_mutex
) __acquires(&cgroup_mutex
)
4080 struct cgroup_subsys_state
*css
= cgrp
->subsys
[ss
->subsys_id
];
4082 lockdep_assert_held(&cgroup_mutex
);
4084 if (!(css
->flags
& CSS_ONLINE
))
4087 if (ss
->css_offline
)
4088 ss
->css_offline(cgrp
);
4090 cgrp
->subsys
[ss
->subsys_id
]->flags
&= ~CSS_ONLINE
;
4094 * cgroup_create - create a cgroup
4095 * @parent: cgroup that will be parent of the new cgroup
4096 * @dentry: dentry of the new cgroup
4097 * @mode: mode to set on new inode
4099 * Must be called with the mutex on the parent inode held
4101 static long cgroup_create(struct cgroup
*parent
, struct dentry
*dentry
,
4104 struct cgroup
*cgrp
;
4105 struct cgroup_name
*name
;
4106 struct cgroupfs_root
*root
= parent
->root
;
4108 struct cgroup_subsys
*ss
;
4109 struct super_block
*sb
= root
->sb
;
4111 /* allocate the cgroup and its ID, 0 is reserved for the root */
4112 cgrp
= kzalloc(sizeof(*cgrp
), GFP_KERNEL
);
4116 name
= cgroup_alloc_name(dentry
);
4119 rcu_assign_pointer(cgrp
->name
, name
);
4121 cgrp
->id
= ida_simple_get(&root
->cgroup_ida
, 1, 0, GFP_KERNEL
);
4126 * Only live parents can have children. Note that the liveliness
4127 * check isn't strictly necessary because cgroup_mkdir() and
4128 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4129 * anyway so that locking is contained inside cgroup proper and we
4130 * don't get nasty surprises if we ever grow another caller.
4132 if (!cgroup_lock_live_group(parent
)) {
4137 /* Grab a reference on the superblock so the hierarchy doesn't
4138 * get deleted on unmount if there are child cgroups. This
4139 * can be done outside cgroup_mutex, since the sb can't
4140 * disappear while someone has an open control file on the
4142 atomic_inc(&sb
->s_active
);
4144 init_cgroup_housekeeping(cgrp
);
4146 dentry
->d_fsdata
= cgrp
;
4147 cgrp
->dentry
= dentry
;
4149 cgrp
->parent
= parent
;
4150 cgrp
->root
= parent
->root
;
4151 cgrp
->top_cgroup
= parent
->top_cgroup
;
4153 if (notify_on_release(parent
))
4154 set_bit(CGRP_NOTIFY_ON_RELEASE
, &cgrp
->flags
);
4156 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN
, &parent
->flags
))
4157 set_bit(CGRP_CPUSET_CLONE_CHILDREN
, &cgrp
->flags
);
4159 for_each_subsys(root
, ss
) {
4160 struct cgroup_subsys_state
*css
;
4162 css
= ss
->css_alloc(cgrp
);
4167 init_cgroup_css(css
, ss
, cgrp
);
4169 err
= alloc_css_id(ss
, parent
, cgrp
);
4176 * Create directory. cgroup_create_file() returns with the new
4177 * directory locked on success so that it can be populated without
4178 * dropping cgroup_mutex.
4180 err
= cgroup_create_file(dentry
, S_IFDIR
| mode
, sb
);
4183 lockdep_assert_held(&dentry
->d_inode
->i_mutex
);
4185 /* allocation complete, commit to creation */
4186 list_add_tail(&cgrp
->allcg_node
, &root
->allcg_list
);
4187 list_add_tail_rcu(&cgrp
->sibling
, &cgrp
->parent
->children
);
4188 root
->number_of_cgroups
++;
4190 /* each css holds a ref to the cgroup's dentry */
4191 for_each_subsys(root
, ss
)
4194 /* hold a ref to the parent's dentry */
4195 dget(parent
->dentry
);
4197 /* creation succeeded, notify subsystems */
4198 for_each_subsys(root
, ss
) {
4199 err
= online_css(ss
, cgrp
);
4203 if (ss
->broken_hierarchy
&& !ss
->warned_broken_hierarchy
&&
4205 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",
4206 current
->comm
, current
->pid
, ss
->name
);
4207 if (!strcmp(ss
->name
, "memory"))
4208 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4209 ss
->warned_broken_hierarchy
= true;
4213 err
= cgroup_populate_dir(cgrp
, true, root
->subsys_mask
);
4217 mutex_unlock(&cgroup_mutex
);
4218 mutex_unlock(&cgrp
->dentry
->d_inode
->i_mutex
);
4223 for_each_subsys(root
, ss
) {
4224 if (cgrp
->subsys
[ss
->subsys_id
])
4227 mutex_unlock(&cgroup_mutex
);
4228 /* Release the reference count that we took on the superblock */
4229 deactivate_super(sb
);
4231 ida_simple_remove(&root
->cgroup_ida
, cgrp
->id
);
4233 kfree(rcu_dereference_raw(cgrp
->name
));
4239 cgroup_destroy_locked(cgrp
);
4240 mutex_unlock(&cgroup_mutex
);
4241 mutex_unlock(&dentry
->d_inode
->i_mutex
);
4245 static int cgroup_mkdir(struct inode
*dir
, struct dentry
*dentry
, umode_t mode
)
4247 struct cgroup
*c_parent
= dentry
->d_parent
->d_fsdata
;
4249 /* the vfs holds inode->i_mutex already */
4250 return cgroup_create(c_parent
, dentry
, mode
| S_IFDIR
);
4253 static int cgroup_destroy_locked(struct cgroup
*cgrp
)
4254 __releases(&cgroup_mutex
) __acquires(&cgroup_mutex
)
4256 struct dentry
*d
= cgrp
->dentry
;
4257 struct cgroup
*parent
= cgrp
->parent
;
4258 struct cgroup_event
*event
, *tmp
;
4259 struct cgroup_subsys
*ss
;
4261 lockdep_assert_held(&d
->d_inode
->i_mutex
);
4262 lockdep_assert_held(&cgroup_mutex
);
4264 if (atomic_read(&cgrp
->count
) || !list_empty(&cgrp
->children
))
4268 * Block new css_tryget() by deactivating refcnt and mark @cgrp
4269 * removed. This makes future css_tryget() and child creation
4270 * attempts fail thus maintaining the removal conditions verified
4273 for_each_subsys(cgrp
->root
, ss
) {
4274 struct cgroup_subsys_state
*css
= cgrp
->subsys
[ss
->subsys_id
];
4276 WARN_ON(atomic_read(&css
->refcnt
) < 0);
4277 atomic_add(CSS_DEACT_BIAS
, &css
->refcnt
);
4279 set_bit(CGRP_REMOVED
, &cgrp
->flags
);
4281 /* tell subsystems to initate destruction */
4282 for_each_subsys(cgrp
->root
, ss
)
4283 offline_css(ss
, cgrp
);
4286 * Put all the base refs. Each css holds an extra reference to the
4287 * cgroup's dentry and cgroup removal proceeds regardless of css
4288 * refs. On the last put of each css, whenever that may be, the
4289 * extra dentry ref is put so that dentry destruction happens only
4290 * after all css's are released.
4292 for_each_subsys(cgrp
->root
, ss
)
4293 css_put(cgrp
->subsys
[ss
->subsys_id
]);
4295 raw_spin_lock(&release_list_lock
);
4296 if (!list_empty(&cgrp
->release_list
))
4297 list_del_init(&cgrp
->release_list
);
4298 raw_spin_unlock(&release_list_lock
);
4300 /* delete this cgroup from parent->children */
4301 list_del_rcu(&cgrp
->sibling
);
4302 list_del_init(&cgrp
->allcg_node
);
4305 cgroup_d_remove_dir(d
);
4308 set_bit(CGRP_RELEASABLE
, &parent
->flags
);
4309 check_for_release(parent
);
4312 * Unregister events and notify userspace.
4313 * Notify userspace about cgroup removing only after rmdir of cgroup
4314 * directory to avoid race between userspace and kernelspace.
4316 spin_lock(&cgrp
->event_list_lock
);
4317 list_for_each_entry_safe(event
, tmp
, &cgrp
->event_list
, list
) {
4318 list_del_init(&event
->list
);
4319 schedule_work(&event
->remove
);
4321 spin_unlock(&cgrp
->event_list_lock
);
4326 static int cgroup_rmdir(struct inode
*unused_dir
, struct dentry
*dentry
)
4330 mutex_lock(&cgroup_mutex
);
4331 ret
= cgroup_destroy_locked(dentry
->d_fsdata
);
4332 mutex_unlock(&cgroup_mutex
);
4337 static void __init_or_module
cgroup_init_cftsets(struct cgroup_subsys
*ss
)
4339 INIT_LIST_HEAD(&ss
->cftsets
);
4342 * base_cftset is embedded in subsys itself, no need to worry about
4345 if (ss
->base_cftypes
) {
4346 ss
->base_cftset
.cfts
= ss
->base_cftypes
;
4347 list_add_tail(&ss
->base_cftset
.node
, &ss
->cftsets
);
4351 static void __init
cgroup_init_subsys(struct cgroup_subsys
*ss
)
4353 struct cgroup_subsys_state
*css
;
4355 printk(KERN_INFO
"Initializing cgroup subsys %s\n", ss
->name
);
4357 mutex_lock(&cgroup_mutex
);
4359 /* init base cftset */
4360 cgroup_init_cftsets(ss
);
4362 /* Create the top cgroup state for this subsystem */
4363 list_add(&ss
->sibling
, &rootnode
.subsys_list
);
4364 ss
->root
= &rootnode
;
4365 css
= ss
->css_alloc(dummytop
);
4366 /* We don't handle early failures gracefully */
4367 BUG_ON(IS_ERR(css
));
4368 init_cgroup_css(css
, ss
, dummytop
);
4370 /* Update the init_css_set to contain a subsys
4371 * pointer to this state - since the subsystem is
4372 * newly registered, all tasks and hence the
4373 * init_css_set is in the subsystem's top cgroup. */
4374 init_css_set
.subsys
[ss
->subsys_id
] = css
;
4376 need_forkexit_callback
|= ss
->fork
|| ss
->exit
;
4378 /* At system boot, before all subsystems have been
4379 * registered, no tasks have been forked, so we don't
4380 * need to invoke fork callbacks here. */
4381 BUG_ON(!list_empty(&init_task
.tasks
));
4384 BUG_ON(online_css(ss
, dummytop
));
4386 mutex_unlock(&cgroup_mutex
);
4388 /* this function shouldn't be used with modular subsystems, since they
4389 * need to register a subsys_id, among other things */
4394 * cgroup_load_subsys: load and register a modular subsystem at runtime
4395 * @ss: the subsystem to load
4397 * This function should be called in a modular subsystem's initcall. If the
4398 * subsystem is built as a module, it will be assigned a new subsys_id and set
4399 * up for use. If the subsystem is built-in anyway, work is delegated to the
4400 * simpler cgroup_init_subsys.
4402 int __init_or_module
cgroup_load_subsys(struct cgroup_subsys
*ss
)
4404 struct cgroup_subsys_state
*css
;
4406 struct hlist_node
*tmp
;
4410 /* check name and function validity */
4411 if (ss
->name
== NULL
|| strlen(ss
->name
) > MAX_CGROUP_TYPE_NAMELEN
||
4412 ss
->css_alloc
== NULL
|| ss
->css_free
== NULL
)
4416 * we don't support callbacks in modular subsystems. this check is
4417 * before the ss->module check for consistency; a subsystem that could
4418 * be a module should still have no callbacks even if the user isn't
4419 * compiling it as one.
4421 if (ss
->fork
|| ss
->exit
)
4425 * an optionally modular subsystem is built-in: we want to do nothing,
4426 * since cgroup_init_subsys will have already taken care of it.
4428 if (ss
->module
== NULL
) {
4429 /* a sanity check */
4430 BUG_ON(subsys
[ss
->subsys_id
] != ss
);
4434 /* init base cftset */
4435 cgroup_init_cftsets(ss
);
4437 mutex_lock(&cgroup_mutex
);
4438 subsys
[ss
->subsys_id
] = ss
;
4441 * no ss->css_alloc seems to need anything important in the ss
4442 * struct, so this can happen first (i.e. before the rootnode
4445 css
= ss
->css_alloc(dummytop
);
4447 /* failure case - need to deassign the subsys[] slot. */
4448 subsys
[ss
->subsys_id
] = NULL
;
4449 mutex_unlock(&cgroup_mutex
);
4450 return PTR_ERR(css
);
4453 list_add(&ss
->sibling
, &rootnode
.subsys_list
);
4454 ss
->root
= &rootnode
;
4456 /* our new subsystem will be attached to the dummy hierarchy. */
4457 init_cgroup_css(css
, ss
, dummytop
);
4458 /* init_idr must be after init_cgroup_css because it sets css->id. */
4460 ret
= cgroup_init_idr(ss
, css
);
4466 * Now we need to entangle the css into the existing css_sets. unlike
4467 * in cgroup_init_subsys, there are now multiple css_sets, so each one
4468 * will need a new pointer to it; done by iterating the css_set_table.
4469 * furthermore, modifying the existing css_sets will corrupt the hash
4470 * table state, so each changed css_set will need its hash recomputed.
4471 * this is all done under the css_set_lock.
4473 write_lock(&css_set_lock
);
4474 hash_for_each_safe(css_set_table
, i
, tmp
, cg
, hlist
) {
4475 /* skip entries that we already rehashed */
4476 if (cg
->subsys
[ss
->subsys_id
])
4478 /* remove existing entry */
4479 hash_del(&cg
->hlist
);
4481 cg
->subsys
[ss
->subsys_id
] = css
;
4482 /* recompute hash and restore entry */
4483 key
= css_set_hash(cg
->subsys
);
4484 hash_add(css_set_table
, &cg
->hlist
, key
);
4486 write_unlock(&css_set_lock
);
4489 ret
= online_css(ss
, dummytop
);
4494 mutex_unlock(&cgroup_mutex
);
4498 mutex_unlock(&cgroup_mutex
);
4499 /* @ss can't be mounted here as try_module_get() would fail */
4500 cgroup_unload_subsys(ss
);
4503 EXPORT_SYMBOL_GPL(cgroup_load_subsys
);
4506 * cgroup_unload_subsys: unload a modular subsystem
4507 * @ss: the subsystem to unload
4509 * This function should be called in a modular subsystem's exitcall. When this
4510 * function is invoked, the refcount on the subsystem's module will be 0, so
4511 * the subsystem will not be attached to any hierarchy.
4513 void cgroup_unload_subsys(struct cgroup_subsys
*ss
)
4515 struct cg_cgroup_link
*link
;
4517 BUG_ON(ss
->module
== NULL
);
4520 * we shouldn't be called if the subsystem is in use, and the use of
4521 * try_module_get in parse_cgroupfs_options should ensure that it
4522 * doesn't start being used while we're killing it off.
4524 BUG_ON(ss
->root
!= &rootnode
);
4526 mutex_lock(&cgroup_mutex
);
4528 offline_css(ss
, dummytop
);
4532 idr_destroy(&ss
->idr
);
4534 /* deassign the subsys_id */
4535 subsys
[ss
->subsys_id
] = NULL
;
4537 /* remove subsystem from rootnode's list of subsystems */
4538 list_del_init(&ss
->sibling
);
4541 * disentangle the css from all css_sets attached to the dummytop. as
4542 * in loading, we need to pay our respects to the hashtable gods.
4544 write_lock(&css_set_lock
);
4545 list_for_each_entry(link
, &dummytop
->css_sets
, cgrp_link_list
) {
4546 struct css_set
*cg
= link
->cg
;
4549 hash_del(&cg
->hlist
);
4550 cg
->subsys
[ss
->subsys_id
] = NULL
;
4551 key
= css_set_hash(cg
->subsys
);
4552 hash_add(css_set_table
, &cg
->hlist
, key
);
4554 write_unlock(&css_set_lock
);
4557 * remove subsystem's css from the dummytop and free it - need to
4558 * free before marking as null because ss->css_free needs the
4559 * cgrp->subsys pointer to find their state. note that this also
4560 * takes care of freeing the css_id.
4562 ss
->css_free(dummytop
);
4563 dummytop
->subsys
[ss
->subsys_id
] = NULL
;
4565 mutex_unlock(&cgroup_mutex
);
4567 EXPORT_SYMBOL_GPL(cgroup_unload_subsys
);
4570 * cgroup_init_early - cgroup initialization at system boot
4572 * Initialize cgroups at system boot, and initialize any
4573 * subsystems that request early init.
4575 int __init
cgroup_init_early(void)
4578 atomic_set(&init_css_set
.refcount
, 1);
4579 INIT_LIST_HEAD(&init_css_set
.cg_links
);
4580 INIT_LIST_HEAD(&init_css_set
.tasks
);
4581 INIT_HLIST_NODE(&init_css_set
.hlist
);
4583 init_cgroup_root(&rootnode
);
4585 init_task
.cgroups
= &init_css_set
;
4587 init_css_set_link
.cg
= &init_css_set
;
4588 init_css_set_link
.cgrp
= dummytop
;
4589 list_add(&init_css_set_link
.cgrp_link_list
,
4590 &rootnode
.top_cgroup
.css_sets
);
4591 list_add(&init_css_set_link
.cg_link_list
,
4592 &init_css_set
.cg_links
);
4594 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++) {
4595 struct cgroup_subsys
*ss
= subsys
[i
];
4597 /* at bootup time, we don't worry about modular subsystems */
4598 if (!ss
|| ss
->module
)
4602 BUG_ON(strlen(ss
->name
) > MAX_CGROUP_TYPE_NAMELEN
);
4603 BUG_ON(!ss
->css_alloc
);
4604 BUG_ON(!ss
->css_free
);
4605 if (ss
->subsys_id
!= i
) {
4606 printk(KERN_ERR
"cgroup: Subsys %s id == %d\n",
4607 ss
->name
, ss
->subsys_id
);
4612 cgroup_init_subsys(ss
);
4618 * cgroup_init - cgroup initialization
4620 * Register cgroup filesystem and /proc file, and initialize
4621 * any subsystems that didn't request early init.
4623 int __init
cgroup_init(void)
4629 err
= bdi_init(&cgroup_backing_dev_info
);
4633 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++) {
4634 struct cgroup_subsys
*ss
= subsys
[i
];
4636 /* at bootup time, we don't worry about modular subsystems */
4637 if (!ss
|| ss
->module
)
4639 if (!ss
->early_init
)
4640 cgroup_init_subsys(ss
);
4642 cgroup_init_idr(ss
, init_css_set
.subsys
[ss
->subsys_id
]);
4645 /* Add init_css_set to the hash table */
4646 key
= css_set_hash(init_css_set
.subsys
);
4647 hash_add(css_set_table
, &init_css_set
.hlist
, key
);
4648 BUG_ON(!init_root_id(&rootnode
));
4650 cgroup_kobj
= kobject_create_and_add("cgroup", fs_kobj
);
4656 err
= register_filesystem(&cgroup_fs_type
);
4658 kobject_put(cgroup_kobj
);
4662 proc_create("cgroups", 0, NULL
, &proc_cgroupstats_operations
);
4666 bdi_destroy(&cgroup_backing_dev_info
);
4672 * proc_cgroup_show()
4673 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4674 * - Used for /proc/<pid>/cgroup.
4675 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4676 * doesn't really matter if tsk->cgroup changes after we read it,
4677 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4678 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4679 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4680 * cgroup to top_cgroup.
4683 /* TODO: Use a proper seq_file iterator */
4684 static int proc_cgroup_show(struct seq_file
*m
, void *v
)
4687 struct task_struct
*tsk
;
4690 struct cgroupfs_root
*root
;
4693 buf
= kmalloc(PAGE_SIZE
, GFP_KERNEL
);
4699 tsk
= get_pid_task(pid
, PIDTYPE_PID
);
4705 mutex_lock(&cgroup_mutex
);
4707 for_each_active_root(root
) {
4708 struct cgroup_subsys
*ss
;
4709 struct cgroup
*cgrp
;
4712 seq_printf(m
, "%d:", root
->hierarchy_id
);
4713 for_each_subsys(root
, ss
)
4714 seq_printf(m
, "%s%s", count
++ ? "," : "", ss
->name
);
4715 if (strlen(root
->name
))
4716 seq_printf(m
, "%sname=%s", count
? "," : "",
4719 cgrp
= task_cgroup_from_root(tsk
, root
);
4720 retval
= cgroup_path(cgrp
, buf
, PAGE_SIZE
);
4728 mutex_unlock(&cgroup_mutex
);
4729 put_task_struct(tsk
);
4736 static int cgroup_open(struct inode
*inode
, struct file
*file
)
4738 struct pid
*pid
= PROC_I(inode
)->pid
;
4739 return single_open(file
, proc_cgroup_show
, pid
);
4742 const struct file_operations proc_cgroup_operations
= {
4743 .open
= cgroup_open
,
4745 .llseek
= seq_lseek
,
4746 .release
= single_release
,
4749 /* Display information about each subsystem and each hierarchy */
4750 static int proc_cgroupstats_show(struct seq_file
*m
, void *v
)
4754 seq_puts(m
, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4756 * ideally we don't want subsystems moving around while we do this.
4757 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4758 * subsys/hierarchy state.
4760 mutex_lock(&cgroup_mutex
);
4761 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++) {
4762 struct cgroup_subsys
*ss
= subsys
[i
];
4765 seq_printf(m
, "%s\t%d\t%d\t%d\n",
4766 ss
->name
, ss
->root
->hierarchy_id
,
4767 ss
->root
->number_of_cgroups
, !ss
->disabled
);
4769 mutex_unlock(&cgroup_mutex
);
4773 static int cgroupstats_open(struct inode
*inode
, struct file
*file
)
4775 return single_open(file
, proc_cgroupstats_show
, NULL
);
4778 static const struct file_operations proc_cgroupstats_operations
= {
4779 .open
= cgroupstats_open
,
4781 .llseek
= seq_lseek
,
4782 .release
= single_release
,
4786 * cgroup_fork - attach newly forked task to its parents cgroup.
4787 * @child: pointer to task_struct of forking parent process.
4789 * Description: A task inherits its parent's cgroup at fork().
4791 * A pointer to the shared css_set was automatically copied in
4792 * fork.c by dup_task_struct(). However, we ignore that copy, since
4793 * it was not made under the protection of RCU or cgroup_mutex, so
4794 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
4795 * have already changed current->cgroups, allowing the previously
4796 * referenced cgroup group to be removed and freed.
4798 * At the point that cgroup_fork() is called, 'current' is the parent
4799 * task, and the passed argument 'child' points to the child task.
4801 void cgroup_fork(struct task_struct
*child
)
4804 child
->cgroups
= current
->cgroups
;
4805 get_css_set(child
->cgroups
);
4806 task_unlock(current
);
4807 INIT_LIST_HEAD(&child
->cg_list
);
4811 * cgroup_post_fork - called on a new task after adding it to the task list
4812 * @child: the task in question
4814 * Adds the task to the list running through its css_set if necessary and
4815 * call the subsystem fork() callbacks. Has to be after the task is
4816 * visible on the task list in case we race with the first call to
4817 * cgroup_iter_start() - to guarantee that the new task ends up on its
4820 void cgroup_post_fork(struct task_struct
*child
)
4825 * use_task_css_set_links is set to 1 before we walk the tasklist
4826 * under the tasklist_lock and we read it here after we added the child
4827 * to the tasklist under the tasklist_lock as well. If the child wasn't
4828 * yet in the tasklist when we walked through it from
4829 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4830 * should be visible now due to the paired locking and barriers implied
4831 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4832 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4835 if (use_task_css_set_links
) {
4836 write_lock(&css_set_lock
);
4838 if (list_empty(&child
->cg_list
))
4839 list_add(&child
->cg_list
, &child
->cgroups
->tasks
);
4841 write_unlock(&css_set_lock
);
4845 * Call ss->fork(). This must happen after @child is linked on
4846 * css_set; otherwise, @child might change state between ->fork()
4847 * and addition to css_set.
4849 if (need_forkexit_callback
) {
4851 * fork/exit callbacks are supported only for builtin
4852 * subsystems, and the builtin section of the subsys
4853 * array is immutable, so we don't need to lock the
4854 * subsys array here. On the other hand, modular section
4855 * of the array can be freed at module unload, so we
4858 for (i
= 0; i
< CGROUP_BUILTIN_SUBSYS_COUNT
; i
++) {
4859 struct cgroup_subsys
*ss
= subsys
[i
];
4868 * cgroup_exit - detach cgroup from exiting task
4869 * @tsk: pointer to task_struct of exiting process
4870 * @run_callback: run exit callbacks?
4872 * Description: Detach cgroup from @tsk and release it.
4874 * Note that cgroups marked notify_on_release force every task in
4875 * them to take the global cgroup_mutex mutex when exiting.
4876 * This could impact scaling on very large systems. Be reluctant to
4877 * use notify_on_release cgroups where very high task exit scaling
4878 * is required on large systems.
4880 * the_top_cgroup_hack:
4882 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
4884 * We call cgroup_exit() while the task is still competent to
4885 * handle notify_on_release(), then leave the task attached to the
4886 * root cgroup in each hierarchy for the remainder of its exit.
4888 * To do this properly, we would increment the reference count on
4889 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
4890 * code we would add a second cgroup function call, to drop that
4891 * reference. This would just create an unnecessary hot spot on
4892 * the top_cgroup reference count, to no avail.
4894 * Normally, holding a reference to a cgroup without bumping its
4895 * count is unsafe. The cgroup could go away, or someone could
4896 * attach us to a different cgroup, decrementing the count on
4897 * the first cgroup that we never incremented. But in this case,
4898 * top_cgroup isn't going away, and either task has PF_EXITING set,
4899 * which wards off any cgroup_attach_task() attempts, or task is a failed
4900 * fork, never visible to cgroup_attach_task.
4902 void cgroup_exit(struct task_struct
*tsk
, int run_callbacks
)
4908 * Unlink from the css_set task list if necessary.
4909 * Optimistically check cg_list before taking
4912 if (!list_empty(&tsk
->cg_list
)) {
4913 write_lock(&css_set_lock
);
4914 if (!list_empty(&tsk
->cg_list
))
4915 list_del_init(&tsk
->cg_list
);
4916 write_unlock(&css_set_lock
);
4919 /* Reassign the task to the init_css_set. */
4922 tsk
->cgroups
= &init_css_set
;
4924 if (run_callbacks
&& need_forkexit_callback
) {
4926 * fork/exit callbacks are supported only for builtin
4927 * subsystems, see cgroup_post_fork() for details.
4929 for (i
= 0; i
< CGROUP_BUILTIN_SUBSYS_COUNT
; i
++) {
4930 struct cgroup_subsys
*ss
= subsys
[i
];
4933 struct cgroup
*old_cgrp
=
4934 rcu_dereference_raw(cg
->subsys
[i
])->cgroup
;
4935 struct cgroup
*cgrp
= task_cgroup(tsk
, i
);
4936 ss
->exit(cgrp
, old_cgrp
, tsk
);
4942 put_css_set_taskexit(cg
);
4945 static void check_for_release(struct cgroup
*cgrp
)
4947 /* All of these checks rely on RCU to keep the cgroup
4948 * structure alive */
4949 if (cgroup_is_releasable(cgrp
) &&
4950 !atomic_read(&cgrp
->count
) && list_empty(&cgrp
->children
)) {
4952 * Control Group is currently removeable. If it's not
4953 * already queued for a userspace notification, queue
4956 int need_schedule_work
= 0;
4958 raw_spin_lock(&release_list_lock
);
4959 if (!cgroup_is_removed(cgrp
) &&
4960 list_empty(&cgrp
->release_list
)) {
4961 list_add(&cgrp
->release_list
, &release_list
);
4962 need_schedule_work
= 1;
4964 raw_spin_unlock(&release_list_lock
);
4965 if (need_schedule_work
)
4966 schedule_work(&release_agent_work
);
4970 /* Caller must verify that the css is not for root cgroup */
4971 bool __css_tryget(struct cgroup_subsys_state
*css
)
4976 v
= css_refcnt(css
);
4977 t
= atomic_cmpxchg(&css
->refcnt
, v
, v
+ 1);
4985 EXPORT_SYMBOL_GPL(__css_tryget
);
4987 /* Caller must verify that the css is not for root cgroup */
4988 void __css_put(struct cgroup_subsys_state
*css
)
4992 v
= css_unbias_refcnt(atomic_dec_return(&css
->refcnt
));
4994 schedule_work(&css
->dput_work
);
4996 EXPORT_SYMBOL_GPL(__css_put
);
4999 * Notify userspace when a cgroup is released, by running the
5000 * configured release agent with the name of the cgroup (path
5001 * relative to the root of cgroup file system) as the argument.
5003 * Most likely, this user command will try to rmdir this cgroup.
5005 * This races with the possibility that some other task will be
5006 * attached to this cgroup before it is removed, or that some other
5007 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5008 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5009 * unused, and this cgroup will be reprieved from its death sentence,
5010 * to continue to serve a useful existence. Next time it's released,
5011 * we will get notified again, if it still has 'notify_on_release' set.
5013 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5014 * means only wait until the task is successfully execve()'d. The
5015 * separate release agent task is forked by call_usermodehelper(),
5016 * then control in this thread returns here, without waiting for the
5017 * release agent task. We don't bother to wait because the caller of
5018 * this routine has no use for the exit status of the release agent
5019 * task, so no sense holding our caller up for that.
5021 static void cgroup_release_agent(struct work_struct
*work
)
5023 BUG_ON(work
!= &release_agent_work
);
5024 mutex_lock(&cgroup_mutex
);
5025 raw_spin_lock(&release_list_lock
);
5026 while (!list_empty(&release_list
)) {
5027 char *argv
[3], *envp
[3];
5029 char *pathbuf
= NULL
, *agentbuf
= NULL
;
5030 struct cgroup
*cgrp
= list_entry(release_list
.next
,
5033 list_del_init(&cgrp
->release_list
);
5034 raw_spin_unlock(&release_list_lock
);
5035 pathbuf
= kmalloc(PAGE_SIZE
, GFP_KERNEL
);
5038 if (cgroup_path(cgrp
, pathbuf
, PAGE_SIZE
) < 0)
5040 agentbuf
= kstrdup(cgrp
->root
->release_agent_path
, GFP_KERNEL
);
5045 argv
[i
++] = agentbuf
;
5046 argv
[i
++] = pathbuf
;
5050 /* minimal command environment */
5051 envp
[i
++] = "HOME=/";
5052 envp
[i
++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5055 /* Drop the lock while we invoke the usermode helper,
5056 * since the exec could involve hitting disk and hence
5057 * be a slow process */
5058 mutex_unlock(&cgroup_mutex
);
5059 call_usermodehelper(argv
[0], argv
, envp
, UMH_WAIT_EXEC
);
5060 mutex_lock(&cgroup_mutex
);
5064 raw_spin_lock(&release_list_lock
);
5066 raw_spin_unlock(&release_list_lock
);
5067 mutex_unlock(&cgroup_mutex
);
5070 static int __init
cgroup_disable(char *str
)
5075 while ((token
= strsep(&str
, ",")) != NULL
) {
5078 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++) {
5079 struct cgroup_subsys
*ss
= subsys
[i
];
5082 * cgroup_disable, being at boot time, can't
5083 * know about module subsystems, so we don't
5086 if (!ss
|| ss
->module
)
5089 if (!strcmp(token
, ss
->name
)) {
5091 printk(KERN_INFO
"Disabling %s control group"
5092 " subsystem\n", ss
->name
);
5099 __setup("cgroup_disable=", cgroup_disable
);
5102 * Functons for CSS ID.
5106 *To get ID other than 0, this should be called when !cgroup_is_removed().
5108 unsigned short css_id(struct cgroup_subsys_state
*css
)
5110 struct css_id
*cssid
;
5113 * This css_id() can return correct value when somone has refcnt
5114 * on this or this is under rcu_read_lock(). Once css->id is allocated,
5115 * it's unchanged until freed.
5117 cssid
= rcu_dereference_check(css
->id
, css_refcnt(css
));
5123 EXPORT_SYMBOL_GPL(css_id
);
5125 unsigned short css_depth(struct cgroup_subsys_state
*css
)
5127 struct css_id
*cssid
;
5129 cssid
= rcu_dereference_check(css
->id
, css_refcnt(css
));
5132 return cssid
->depth
;
5135 EXPORT_SYMBOL_GPL(css_depth
);
5138 * css_is_ancestor - test "root" css is an ancestor of "child"
5139 * @child: the css to be tested.
5140 * @root: the css supporsed to be an ancestor of the child.
5142 * Returns true if "root" is an ancestor of "child" in its hierarchy. Because
5143 * this function reads css->id, the caller must hold rcu_read_lock().
5144 * But, considering usual usage, the csses should be valid objects after test.
5145 * Assuming that the caller will do some action to the child if this returns
5146 * returns true, the caller must take "child";s reference count.
5147 * If "child" is valid object and this returns true, "root" is valid, too.
5150 bool css_is_ancestor(struct cgroup_subsys_state
*child
,
5151 const struct cgroup_subsys_state
*root
)
5153 struct css_id
*child_id
;
5154 struct css_id
*root_id
;
5156 child_id
= rcu_dereference(child
->id
);
5159 root_id
= rcu_dereference(root
->id
);
5162 if (child_id
->depth
< root_id
->depth
)
5164 if (child_id
->stack
[root_id
->depth
] != root_id
->id
)
5169 void free_css_id(struct cgroup_subsys
*ss
, struct cgroup_subsys_state
*css
)
5171 struct css_id
*id
= css
->id
;
5172 /* When this is called before css_id initialization, id can be NULL */
5176 BUG_ON(!ss
->use_id
);
5178 rcu_assign_pointer(id
->css
, NULL
);
5179 rcu_assign_pointer(css
->id
, NULL
);
5180 spin_lock(&ss
->id_lock
);
5181 idr_remove(&ss
->idr
, id
->id
);
5182 spin_unlock(&ss
->id_lock
);
5183 kfree_rcu(id
, rcu_head
);
5185 EXPORT_SYMBOL_GPL(free_css_id
);
5188 * This is called by init or create(). Then, calls to this function are
5189 * always serialized (By cgroup_mutex() at create()).
5192 static struct css_id
*get_new_cssid(struct cgroup_subsys
*ss
, int depth
)
5194 struct css_id
*newid
;
5197 BUG_ON(!ss
->use_id
);
5199 size
= sizeof(*newid
) + sizeof(unsigned short) * (depth
+ 1);
5200 newid
= kzalloc(size
, GFP_KERNEL
);
5202 return ERR_PTR(-ENOMEM
);
5204 idr_preload(GFP_KERNEL
);
5205 spin_lock(&ss
->id_lock
);
5206 /* Don't use 0. allocates an ID of 1-65535 */
5207 ret
= idr_alloc(&ss
->idr
, newid
, 1, CSS_ID_MAX
+ 1, GFP_NOWAIT
);
5208 spin_unlock(&ss
->id_lock
);
5211 /* Returns error when there are no free spaces for new ID.*/
5216 newid
->depth
= depth
;
5220 return ERR_PTR(ret
);
5224 static int __init_or_module
cgroup_init_idr(struct cgroup_subsys
*ss
,
5225 struct cgroup_subsys_state
*rootcss
)
5227 struct css_id
*newid
;
5229 spin_lock_init(&ss
->id_lock
);
5232 newid
= get_new_cssid(ss
, 0);
5234 return PTR_ERR(newid
);
5236 newid
->stack
[0] = newid
->id
;
5237 newid
->css
= rootcss
;
5238 rootcss
->id
= newid
;
5242 static int alloc_css_id(struct cgroup_subsys
*ss
, struct cgroup
*parent
,
5243 struct cgroup
*child
)
5245 int subsys_id
, i
, depth
= 0;
5246 struct cgroup_subsys_state
*parent_css
, *child_css
;
5247 struct css_id
*child_id
, *parent_id
;
5249 subsys_id
= ss
->subsys_id
;
5250 parent_css
= parent
->subsys
[subsys_id
];
5251 child_css
= child
->subsys
[subsys_id
];
5252 parent_id
= parent_css
->id
;
5253 depth
= parent_id
->depth
+ 1;
5255 child_id
= get_new_cssid(ss
, depth
);
5256 if (IS_ERR(child_id
))
5257 return PTR_ERR(child_id
);
5259 for (i
= 0; i
< depth
; i
++)
5260 child_id
->stack
[i
] = parent_id
->stack
[i
];
5261 child_id
->stack
[depth
] = child_id
->id
;
5263 * child_id->css pointer will be set after this cgroup is available
5264 * see cgroup_populate_dir()
5266 rcu_assign_pointer(child_css
->id
, child_id
);
5272 * css_lookup - lookup css by id
5273 * @ss: cgroup subsys to be looked into.
5276 * Returns pointer to cgroup_subsys_state if there is valid one with id.
5277 * NULL if not. Should be called under rcu_read_lock()
5279 struct cgroup_subsys_state
*css_lookup(struct cgroup_subsys
*ss
, int id
)
5281 struct css_id
*cssid
= NULL
;
5283 BUG_ON(!ss
->use_id
);
5284 cssid
= idr_find(&ss
->idr
, id
);
5286 if (unlikely(!cssid
))
5289 return rcu_dereference(cssid
->css
);
5291 EXPORT_SYMBOL_GPL(css_lookup
);
5294 * css_get_next - lookup next cgroup under specified hierarchy.
5295 * @ss: pointer to subsystem
5296 * @id: current position of iteration.
5297 * @root: pointer to css. search tree under this.
5298 * @foundid: position of found object.
5300 * Search next css under the specified hierarchy of rootid. Calling under
5301 * rcu_read_lock() is necessary. Returns NULL if it reaches the end.
5303 struct cgroup_subsys_state
*
5304 css_get_next(struct cgroup_subsys
*ss
, int id
,
5305 struct cgroup_subsys_state
*root
, int *foundid
)
5307 struct cgroup_subsys_state
*ret
= NULL
;
5310 int rootid
= css_id(root
);
5311 int depth
= css_depth(root
);
5316 BUG_ON(!ss
->use_id
);
5317 WARN_ON_ONCE(!rcu_read_lock_held());
5319 /* fill start point for scan */
5323 * scan next entry from bitmap(tree), tmpid is updated after
5326 tmp
= idr_get_next(&ss
->idr
, &tmpid
);
5329 if (tmp
->depth
>= depth
&& tmp
->stack
[depth
] == rootid
) {
5330 ret
= rcu_dereference(tmp
->css
);
5336 /* continue to scan from next id */
5343 * get corresponding css from file open on cgroupfs directory
5345 struct cgroup_subsys_state
*cgroup_css_from_dir(struct file
*f
, int id
)
5347 struct cgroup
*cgrp
;
5348 struct inode
*inode
;
5349 struct cgroup_subsys_state
*css
;
5351 inode
= file_inode(f
);
5352 /* check in cgroup filesystem dir */
5353 if (inode
->i_op
!= &cgroup_dir_inode_operations
)
5354 return ERR_PTR(-EBADF
);
5356 if (id
< 0 || id
>= CGROUP_SUBSYS_COUNT
)
5357 return ERR_PTR(-EINVAL
);
5360 cgrp
= __d_cgrp(f
->f_dentry
);
5361 css
= cgrp
->subsys
[id
];
5362 return css
? css
: ERR_PTR(-ENOENT
);
5365 #ifdef CONFIG_CGROUP_DEBUG
5366 static struct cgroup_subsys_state
*debug_css_alloc(struct cgroup
*cont
)
5368 struct cgroup_subsys_state
*css
= kzalloc(sizeof(*css
), GFP_KERNEL
);
5371 return ERR_PTR(-ENOMEM
);
5376 static void debug_css_free(struct cgroup
*cont
)
5378 kfree(cont
->subsys
[debug_subsys_id
]);
5381 static u64
cgroup_refcount_read(struct cgroup
*cont
, struct cftype
*cft
)
5383 return atomic_read(&cont
->count
);
5386 static u64
debug_taskcount_read(struct cgroup
*cont
, struct cftype
*cft
)
5388 return cgroup_task_count(cont
);
5391 static u64
current_css_set_read(struct cgroup
*cont
, struct cftype
*cft
)
5393 return (u64
)(unsigned long)current
->cgroups
;
5396 static u64
current_css_set_refcount_read(struct cgroup
*cont
,
5402 count
= atomic_read(¤t
->cgroups
->refcount
);
5407 static int current_css_set_cg_links_read(struct cgroup
*cont
,
5409 struct seq_file
*seq
)
5411 struct cg_cgroup_link
*link
;
5414 read_lock(&css_set_lock
);
5416 cg
= rcu_dereference(current
->cgroups
);
5417 list_for_each_entry(link
, &cg
->cg_links
, cg_link_list
) {
5418 struct cgroup
*c
= link
->cgrp
;
5422 name
= c
->dentry
->d_name
.name
;
5425 seq_printf(seq
, "Root %d group %s\n",
5426 c
->root
->hierarchy_id
, name
);
5429 read_unlock(&css_set_lock
);
5433 #define MAX_TASKS_SHOWN_PER_CSS 25
5434 static int cgroup_css_links_read(struct cgroup
*cont
,
5436 struct seq_file
*seq
)
5438 struct cg_cgroup_link
*link
;
5440 read_lock(&css_set_lock
);
5441 list_for_each_entry(link
, &cont
->css_sets
, cgrp_link_list
) {
5442 struct css_set
*cg
= link
->cg
;
5443 struct task_struct
*task
;
5445 seq_printf(seq
, "css_set %p\n", cg
);
5446 list_for_each_entry(task
, &cg
->tasks
, cg_list
) {
5447 if (count
++ > MAX_TASKS_SHOWN_PER_CSS
) {
5448 seq_puts(seq
, " ...\n");
5451 seq_printf(seq
, " task %d\n",
5452 task_pid_vnr(task
));
5456 read_unlock(&css_set_lock
);
5460 static u64
releasable_read(struct cgroup
*cgrp
, struct cftype
*cft
)
5462 return test_bit(CGRP_RELEASABLE
, &cgrp
->flags
);
5465 static struct cftype debug_files
[] = {
5467 .name
= "cgroup_refcount",
5468 .read_u64
= cgroup_refcount_read
,
5471 .name
= "taskcount",
5472 .read_u64
= debug_taskcount_read
,
5476 .name
= "current_css_set",
5477 .read_u64
= current_css_set_read
,
5481 .name
= "current_css_set_refcount",
5482 .read_u64
= current_css_set_refcount_read
,
5486 .name
= "current_css_set_cg_links",
5487 .read_seq_string
= current_css_set_cg_links_read
,
5491 .name
= "cgroup_css_links",
5492 .read_seq_string
= cgroup_css_links_read
,
5496 .name
= "releasable",
5497 .read_u64
= releasable_read
,
5503 struct cgroup_subsys debug_subsys
= {
5505 .css_alloc
= debug_css_alloc
,
5506 .css_free
= debug_css_free
,
5507 .subsys_id
= debug_subsys_id
,
5508 .base_cftypes
= debug_files
,
5510 #endif /* CONFIG_CGROUP_DEBUG */