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
);
279 /* bits in struct cgroupfs_root flags field */
281 ROOT_NOPREFIX
, /* mounted subsystems have no named prefix */
282 ROOT_XATTR
, /* supports extended attributes */
285 static int cgroup_is_releasable(const struct cgroup
*cgrp
)
288 (1 << CGRP_RELEASABLE
) |
289 (1 << CGRP_NOTIFY_ON_RELEASE
);
290 return (cgrp
->flags
& bits
) == bits
;
293 static int notify_on_release(const struct cgroup
*cgrp
)
295 return test_bit(CGRP_NOTIFY_ON_RELEASE
, &cgrp
->flags
);
299 * for_each_subsys() allows you to iterate on each subsystem attached to
300 * an active hierarchy
302 #define for_each_subsys(_root, _ss) \
303 list_for_each_entry(_ss, &_root->subsys_list, sibling)
305 /* for_each_active_root() allows you to iterate across the active hierarchies */
306 #define for_each_active_root(_root) \
307 list_for_each_entry(_root, &roots, root_list)
309 static inline struct cgroup
*__d_cgrp(struct dentry
*dentry
)
311 return dentry
->d_fsdata
;
314 static inline struct cfent
*__d_cfe(struct dentry
*dentry
)
316 return dentry
->d_fsdata
;
319 static inline struct cftype
*__d_cft(struct dentry
*dentry
)
321 return __d_cfe(dentry
)->type
;
325 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
326 * @cgrp: the cgroup to be checked for liveness
328 * On success, returns true; the mutex should be later unlocked. On
329 * failure returns false with no lock held.
331 static bool cgroup_lock_live_group(struct cgroup
*cgrp
)
333 mutex_lock(&cgroup_mutex
);
334 if (cgroup_is_removed(cgrp
)) {
335 mutex_unlock(&cgroup_mutex
);
341 /* the list of cgroups eligible for automatic release. Protected by
342 * release_list_lock */
343 static LIST_HEAD(release_list
);
344 static DEFINE_RAW_SPINLOCK(release_list_lock
);
345 static void cgroup_release_agent(struct work_struct
*work
);
346 static DECLARE_WORK(release_agent_work
, cgroup_release_agent
);
347 static void check_for_release(struct cgroup
*cgrp
);
349 /* Link structure for associating css_set objects with cgroups */
350 struct cg_cgroup_link
{
352 * List running through cg_cgroup_links associated with a
353 * cgroup, anchored on cgroup->css_sets
355 struct list_head cgrp_link_list
;
358 * List running through cg_cgroup_links pointing at a
359 * single css_set object, anchored on css_set->cg_links
361 struct list_head cg_link_list
;
365 /* The default css_set - used by init and its children prior to any
366 * hierarchies being mounted. It contains a pointer to the root state
367 * for each subsystem. Also used to anchor the list of css_sets. Not
368 * reference-counted, to improve performance when child cgroups
369 * haven't been created.
372 static struct css_set init_css_set
;
373 static struct cg_cgroup_link init_css_set_link
;
375 static int cgroup_init_idr(struct cgroup_subsys
*ss
,
376 struct cgroup_subsys_state
*css
);
378 /* css_set_lock protects the list of css_set objects, and the
379 * chain of tasks off each css_set. Nests outside task->alloc_lock
380 * due to cgroup_iter_start() */
381 static DEFINE_RWLOCK(css_set_lock
);
382 static int css_set_count
;
385 * hash table for cgroup groups. This improves the performance to find
386 * an existing css_set. This hash doesn't (currently) take into
387 * account cgroups in empty hierarchies.
389 #define CSS_SET_HASH_BITS 7
390 static DEFINE_HASHTABLE(css_set_table
, CSS_SET_HASH_BITS
);
392 static unsigned long css_set_hash(struct cgroup_subsys_state
*css
[])
395 unsigned long key
= 0UL;
397 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++)
398 key
+= (unsigned long)css
[i
];
399 key
= (key
>> 16) ^ key
;
404 /* We don't maintain the lists running through each css_set to its
405 * task until after the first call to cgroup_iter_start(). This
406 * reduces the fork()/exit() overhead for people who have cgroups
407 * compiled into their kernel but not actually in use */
408 static int use_task_css_set_links __read_mostly
;
410 static void __put_css_set(struct css_set
*cg
, int taskexit
)
412 struct cg_cgroup_link
*link
;
413 struct cg_cgroup_link
*saved_link
;
415 * Ensure that the refcount doesn't hit zero while any readers
416 * can see it. Similar to atomic_dec_and_lock(), but for an
419 if (atomic_add_unless(&cg
->refcount
, -1, 1))
421 write_lock(&css_set_lock
);
422 if (!atomic_dec_and_test(&cg
->refcount
)) {
423 write_unlock(&css_set_lock
);
427 /* This css_set is dead. unlink it and release cgroup refcounts */
428 hash_del(&cg
->hlist
);
431 list_for_each_entry_safe(link
, saved_link
, &cg
->cg_links
,
433 struct cgroup
*cgrp
= link
->cgrp
;
434 list_del(&link
->cg_link_list
);
435 list_del(&link
->cgrp_link_list
);
438 * We may not be holding cgroup_mutex, and if cgrp->count is
439 * dropped to 0 the cgroup can be destroyed at any time, hence
440 * rcu_read_lock is used to keep it alive.
443 if (atomic_dec_and_test(&cgrp
->count
) &&
444 notify_on_release(cgrp
)) {
446 set_bit(CGRP_RELEASABLE
, &cgrp
->flags
);
447 check_for_release(cgrp
);
454 write_unlock(&css_set_lock
);
455 kfree_rcu(cg
, rcu_head
);
459 * refcounted get/put for css_set objects
461 static inline void get_css_set(struct css_set
*cg
)
463 atomic_inc(&cg
->refcount
);
466 static inline void put_css_set(struct css_set
*cg
)
468 __put_css_set(cg
, 0);
471 static inline void put_css_set_taskexit(struct css_set
*cg
)
473 __put_css_set(cg
, 1);
477 * compare_css_sets - helper function for find_existing_css_set().
478 * @cg: candidate css_set being tested
479 * @old_cg: existing css_set for a task
480 * @new_cgrp: cgroup that's being entered by the task
481 * @template: desired set of css pointers in css_set (pre-calculated)
483 * Returns true if "cg" matches "old_cg" except for the hierarchy
484 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
486 static bool compare_css_sets(struct css_set
*cg
,
487 struct css_set
*old_cg
,
488 struct cgroup
*new_cgrp
,
489 struct cgroup_subsys_state
*template[])
491 struct list_head
*l1
, *l2
;
493 if (memcmp(template, cg
->subsys
, sizeof(cg
->subsys
))) {
494 /* Not all subsystems matched */
499 * Compare cgroup pointers in order to distinguish between
500 * different cgroups in heirarchies with no subsystems. We
501 * could get by with just this check alone (and skip the
502 * memcmp above) but on most setups the memcmp check will
503 * avoid the need for this more expensive check on almost all
508 l2
= &old_cg
->cg_links
;
510 struct cg_cgroup_link
*cgl1
, *cgl2
;
511 struct cgroup
*cg1
, *cg2
;
515 /* See if we reached the end - both lists are equal length. */
516 if (l1
== &cg
->cg_links
) {
517 BUG_ON(l2
!= &old_cg
->cg_links
);
520 BUG_ON(l2
== &old_cg
->cg_links
);
522 /* Locate the cgroups associated with these links. */
523 cgl1
= list_entry(l1
, struct cg_cgroup_link
, cg_link_list
);
524 cgl2
= list_entry(l2
, struct cg_cgroup_link
, cg_link_list
);
527 /* Hierarchies should be linked in the same order. */
528 BUG_ON(cg1
->root
!= cg2
->root
);
531 * If this hierarchy is the hierarchy of the cgroup
532 * that's changing, then we need to check that this
533 * css_set points to the new cgroup; if it's any other
534 * hierarchy, then this css_set should point to the
535 * same cgroup as the old css_set.
537 if (cg1
->root
== new_cgrp
->root
) {
549 * find_existing_css_set() is a helper for
550 * find_css_set(), and checks to see whether an existing
551 * css_set is suitable.
553 * oldcg: the cgroup group that we're using before the cgroup
556 * cgrp: the cgroup that we're moving into
558 * template: location in which to build the desired set of subsystem
559 * state objects for the new cgroup group
561 static struct css_set
*find_existing_css_set(
562 struct css_set
*oldcg
,
564 struct cgroup_subsys_state
*template[])
567 struct cgroupfs_root
*root
= cgrp
->root
;
572 * Build the set of subsystem state objects that we want to see in the
573 * new css_set. while subsystems can change globally, the entries here
574 * won't change, so no need for locking.
576 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++) {
577 if (root
->subsys_mask
& (1UL << i
)) {
578 /* Subsystem is in this hierarchy. So we want
579 * the subsystem state from the new
581 template[i
] = cgrp
->subsys
[i
];
583 /* Subsystem is not in this hierarchy, so we
584 * don't want to change the subsystem state */
585 template[i
] = oldcg
->subsys
[i
];
589 key
= css_set_hash(template);
590 hash_for_each_possible(css_set_table
, cg
, hlist
, key
) {
591 if (!compare_css_sets(cg
, oldcg
, cgrp
, template))
594 /* This css_set matches what we need */
598 /* No existing cgroup group matched */
602 static void free_cg_links(struct list_head
*tmp
)
604 struct cg_cgroup_link
*link
;
605 struct cg_cgroup_link
*saved_link
;
607 list_for_each_entry_safe(link
, saved_link
, tmp
, cgrp_link_list
) {
608 list_del(&link
->cgrp_link_list
);
614 * allocate_cg_links() allocates "count" cg_cgroup_link structures
615 * and chains them on tmp through their cgrp_link_list fields. Returns 0 on
616 * success or a negative error
618 static int allocate_cg_links(int count
, struct list_head
*tmp
)
620 struct cg_cgroup_link
*link
;
623 for (i
= 0; i
< count
; i
++) {
624 link
= kmalloc(sizeof(*link
), GFP_KERNEL
);
629 list_add(&link
->cgrp_link_list
, tmp
);
635 * link_css_set - a helper function to link a css_set to a cgroup
636 * @tmp_cg_links: cg_cgroup_link objects allocated by allocate_cg_links()
637 * @cg: the css_set to be linked
638 * @cgrp: the destination cgroup
640 static void link_css_set(struct list_head
*tmp_cg_links
,
641 struct css_set
*cg
, struct cgroup
*cgrp
)
643 struct cg_cgroup_link
*link
;
645 BUG_ON(list_empty(tmp_cg_links
));
646 link
= list_first_entry(tmp_cg_links
, struct cg_cgroup_link
,
650 atomic_inc(&cgrp
->count
);
651 list_move(&link
->cgrp_link_list
, &cgrp
->css_sets
);
653 * Always add links to the tail of the list so that the list
654 * is sorted by order of hierarchy creation
656 list_add_tail(&link
->cg_link_list
, &cg
->cg_links
);
660 * find_css_set() takes an existing cgroup group and a
661 * cgroup object, and returns a css_set object that's
662 * equivalent to the old group, but with the given cgroup
663 * substituted into the appropriate hierarchy. Must be called with
666 static struct css_set
*find_css_set(
667 struct css_set
*oldcg
, struct cgroup
*cgrp
)
670 struct cgroup_subsys_state
*template[CGROUP_SUBSYS_COUNT
];
672 struct list_head tmp_cg_links
;
674 struct cg_cgroup_link
*link
;
677 /* First see if we already have a cgroup group that matches
679 read_lock(&css_set_lock
);
680 res
= find_existing_css_set(oldcg
, cgrp
, template);
683 read_unlock(&css_set_lock
);
688 res
= kmalloc(sizeof(*res
), GFP_KERNEL
);
692 /* Allocate all the cg_cgroup_link objects that we'll need */
693 if (allocate_cg_links(root_count
, &tmp_cg_links
) < 0) {
698 atomic_set(&res
->refcount
, 1);
699 INIT_LIST_HEAD(&res
->cg_links
);
700 INIT_LIST_HEAD(&res
->tasks
);
701 INIT_HLIST_NODE(&res
->hlist
);
703 /* Copy the set of subsystem state objects generated in
704 * find_existing_css_set() */
705 memcpy(res
->subsys
, template, sizeof(res
->subsys
));
707 write_lock(&css_set_lock
);
708 /* Add reference counts and links from the new css_set. */
709 list_for_each_entry(link
, &oldcg
->cg_links
, cg_link_list
) {
710 struct cgroup
*c
= link
->cgrp
;
711 if (c
->root
== cgrp
->root
)
713 link_css_set(&tmp_cg_links
, res
, c
);
716 BUG_ON(!list_empty(&tmp_cg_links
));
720 /* Add this cgroup group to the hash table */
721 key
= css_set_hash(res
->subsys
);
722 hash_add(css_set_table
, &res
->hlist
, key
);
724 write_unlock(&css_set_lock
);
730 * Return the cgroup for "task" from the given hierarchy. Must be
731 * called with cgroup_mutex held.
733 static struct cgroup
*task_cgroup_from_root(struct task_struct
*task
,
734 struct cgroupfs_root
*root
)
737 struct cgroup
*res
= NULL
;
739 BUG_ON(!mutex_is_locked(&cgroup_mutex
));
740 read_lock(&css_set_lock
);
742 * No need to lock the task - since we hold cgroup_mutex the
743 * task can't change groups, so the only thing that can happen
744 * is that it exits and its css is set back to init_css_set.
747 if (css
== &init_css_set
) {
748 res
= &root
->top_cgroup
;
750 struct cg_cgroup_link
*link
;
751 list_for_each_entry(link
, &css
->cg_links
, cg_link_list
) {
752 struct cgroup
*c
= link
->cgrp
;
753 if (c
->root
== root
) {
759 read_unlock(&css_set_lock
);
765 * There is one global cgroup mutex. We also require taking
766 * task_lock() when dereferencing a task's cgroup subsys pointers.
767 * See "The task_lock() exception", at the end of this comment.
769 * A task must hold cgroup_mutex to modify cgroups.
771 * Any task can increment and decrement the count field without lock.
772 * So in general, code holding cgroup_mutex can't rely on the count
773 * field not changing. However, if the count goes to zero, then only
774 * cgroup_attach_task() can increment it again. Because a count of zero
775 * means that no tasks are currently attached, therefore there is no
776 * way a task attached to that cgroup can fork (the other way to
777 * increment the count). So code holding cgroup_mutex can safely
778 * assume that if the count is zero, it will stay zero. Similarly, if
779 * a task holds cgroup_mutex on a cgroup with zero count, it
780 * knows that the cgroup won't be removed, as cgroup_rmdir()
783 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
784 * (usually) take cgroup_mutex. These are the two most performance
785 * critical pieces of code here. The exception occurs on cgroup_exit(),
786 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
787 * is taken, and if the cgroup count is zero, a usermode call made
788 * to the release agent with the name of the cgroup (path relative to
789 * the root of cgroup file system) as the argument.
791 * A cgroup can only be deleted if both its 'count' of using tasks
792 * is zero, and its list of 'children' cgroups is empty. Since all
793 * tasks in the system use _some_ cgroup, and since there is always at
794 * least one task in the system (init, pid == 1), therefore, top_cgroup
795 * always has either children cgroups and/or using tasks. So we don't
796 * need a special hack to ensure that top_cgroup cannot be deleted.
798 * The task_lock() exception
800 * The need for this exception arises from the action of
801 * cgroup_attach_task(), which overwrites one task's cgroup pointer with
802 * another. It does so using cgroup_mutex, however there are
803 * several performance critical places that need to reference
804 * task->cgroup without the expense of grabbing a system global
805 * mutex. Therefore except as noted below, when dereferencing or, as
806 * in cgroup_attach_task(), modifying a task's cgroup pointer we use
807 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
808 * the task_struct routinely used for such matters.
810 * P.S. One more locking exception. RCU is used to guard the
811 * update of a tasks cgroup pointer by cgroup_attach_task()
815 * A couple of forward declarations required, due to cyclic reference loop:
816 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
817 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
821 static int cgroup_mkdir(struct inode
*dir
, struct dentry
*dentry
, umode_t mode
);
822 static struct dentry
*cgroup_lookup(struct inode
*, struct dentry
*, unsigned int);
823 static int cgroup_rmdir(struct inode
*unused_dir
, struct dentry
*dentry
);
824 static int cgroup_populate_dir(struct cgroup
*cgrp
, bool base_files
,
825 unsigned long subsys_mask
);
826 static const struct inode_operations cgroup_dir_inode_operations
;
827 static const struct file_operations proc_cgroupstats_operations
;
829 static struct backing_dev_info cgroup_backing_dev_info
= {
831 .capabilities
= BDI_CAP_NO_ACCT_AND_WRITEBACK
,
834 static int alloc_css_id(struct cgroup_subsys
*ss
,
835 struct cgroup
*parent
, struct cgroup
*child
);
837 static struct inode
*cgroup_new_inode(umode_t mode
, struct super_block
*sb
)
839 struct inode
*inode
= new_inode(sb
);
842 inode
->i_ino
= get_next_ino();
843 inode
->i_mode
= mode
;
844 inode
->i_uid
= current_fsuid();
845 inode
->i_gid
= current_fsgid();
846 inode
->i_atime
= inode
->i_mtime
= inode
->i_ctime
= CURRENT_TIME
;
847 inode
->i_mapping
->backing_dev_info
= &cgroup_backing_dev_info
;
852 static struct cgroup_name
*cgroup_alloc_name(struct dentry
*dentry
)
854 struct cgroup_name
*name
;
856 name
= kmalloc(sizeof(*name
) + dentry
->d_name
.len
+ 1, GFP_KERNEL
);
859 strcpy(name
->name
, dentry
->d_name
.name
);
863 static void cgroup_free_fn(struct work_struct
*work
)
865 struct cgroup
*cgrp
= container_of(work
, struct cgroup
, free_work
);
866 struct cgroup_subsys
*ss
;
868 mutex_lock(&cgroup_mutex
);
870 * Release the subsystem state objects.
872 for_each_subsys(cgrp
->root
, ss
)
875 cgrp
->root
->number_of_cgroups
--;
876 mutex_unlock(&cgroup_mutex
);
879 * Drop the active superblock reference that we took when we
882 deactivate_super(cgrp
->root
->sb
);
885 * if we're getting rid of the cgroup, refcount should ensure
886 * that there are no pidlists left.
888 BUG_ON(!list_empty(&cgrp
->pidlists
));
890 simple_xattrs_free(&cgrp
->xattrs
);
892 ida_simple_remove(&cgrp
->root
->cgroup_ida
, cgrp
->id
);
893 kfree(rcu_dereference_raw(cgrp
->name
));
897 static void cgroup_free_rcu(struct rcu_head
*head
)
899 struct cgroup
*cgrp
= container_of(head
, struct cgroup
, rcu_head
);
901 schedule_work(&cgrp
->free_work
);
904 static void cgroup_diput(struct dentry
*dentry
, struct inode
*inode
)
906 /* is dentry a directory ? if so, kfree() associated cgroup */
907 if (S_ISDIR(inode
->i_mode
)) {
908 struct cgroup
*cgrp
= dentry
->d_fsdata
;
910 BUG_ON(!(cgroup_is_removed(cgrp
)));
911 call_rcu(&cgrp
->rcu_head
, cgroup_free_rcu
);
913 struct cfent
*cfe
= __d_cfe(dentry
);
914 struct cgroup
*cgrp
= dentry
->d_parent
->d_fsdata
;
915 struct cftype
*cft
= cfe
->type
;
917 WARN_ONCE(!list_empty(&cfe
->node
) &&
918 cgrp
!= &cgrp
->root
->top_cgroup
,
919 "cfe still linked for %s\n", cfe
->type
->name
);
921 simple_xattrs_free(&cft
->xattrs
);
926 static int cgroup_delete(const struct dentry
*d
)
931 static void remove_dir(struct dentry
*d
)
933 struct dentry
*parent
= dget(d
->d_parent
);
936 simple_rmdir(parent
->d_inode
, d
);
940 static void cgroup_rm_file(struct cgroup
*cgrp
, const struct cftype
*cft
)
944 lockdep_assert_held(&cgrp
->dentry
->d_inode
->i_mutex
);
945 lockdep_assert_held(&cgroup_mutex
);
948 * If we're doing cleanup due to failure of cgroup_create(),
949 * the corresponding @cfe may not exist.
951 list_for_each_entry(cfe
, &cgrp
->files
, node
) {
952 struct dentry
*d
= cfe
->dentry
;
954 if (cft
&& cfe
->type
!= cft
)
959 simple_unlink(cgrp
->dentry
->d_inode
, d
);
960 list_del_init(&cfe
->node
);
968 * cgroup_clear_directory - selective removal of base and subsystem files
969 * @dir: directory containing the files
970 * @base_files: true if the base files should be removed
971 * @subsys_mask: mask of the subsystem ids whose files should be removed
973 static void cgroup_clear_directory(struct dentry
*dir
, bool base_files
,
974 unsigned long subsys_mask
)
976 struct cgroup
*cgrp
= __d_cgrp(dir
);
977 struct cgroup_subsys
*ss
;
979 for_each_subsys(cgrp
->root
, ss
) {
980 struct cftype_set
*set
;
981 if (!test_bit(ss
->subsys_id
, &subsys_mask
))
983 list_for_each_entry(set
, &ss
->cftsets
, node
)
984 cgroup_addrm_files(cgrp
, NULL
, set
->cfts
, false);
987 while (!list_empty(&cgrp
->files
))
988 cgroup_rm_file(cgrp
, NULL
);
993 * NOTE : the dentry must have been dget()'ed
995 static void cgroup_d_remove_dir(struct dentry
*dentry
)
997 struct dentry
*parent
;
998 struct cgroupfs_root
*root
= dentry
->d_sb
->s_fs_info
;
1000 cgroup_clear_directory(dentry
, true, root
->subsys_mask
);
1002 parent
= dentry
->d_parent
;
1003 spin_lock(&parent
->d_lock
);
1004 spin_lock_nested(&dentry
->d_lock
, DENTRY_D_LOCK_NESTED
);
1005 list_del_init(&dentry
->d_u
.d_child
);
1006 spin_unlock(&dentry
->d_lock
);
1007 spin_unlock(&parent
->d_lock
);
1012 * Call with cgroup_mutex held. Drops reference counts on modules, including
1013 * any duplicate ones that parse_cgroupfs_options took. If this function
1014 * returns an error, no reference counts are touched.
1016 static int rebind_subsystems(struct cgroupfs_root
*root
,
1017 unsigned long final_subsys_mask
)
1019 unsigned long added_mask
, removed_mask
;
1020 struct cgroup
*cgrp
= &root
->top_cgroup
;
1023 BUG_ON(!mutex_is_locked(&cgroup_mutex
));
1024 BUG_ON(!mutex_is_locked(&cgroup_root_mutex
));
1026 removed_mask
= root
->actual_subsys_mask
& ~final_subsys_mask
;
1027 added_mask
= final_subsys_mask
& ~root
->actual_subsys_mask
;
1028 /* Check that any added subsystems are currently free */
1029 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++) {
1030 unsigned long bit
= 1UL << i
;
1031 struct cgroup_subsys
*ss
= subsys
[i
];
1032 if (!(bit
& added_mask
))
1035 * Nobody should tell us to do a subsys that doesn't exist:
1036 * parse_cgroupfs_options should catch that case and refcounts
1037 * ensure that subsystems won't disappear once selected.
1040 if (ss
->root
!= &rootnode
) {
1041 /* Subsystem isn't free */
1046 /* Currently we don't handle adding/removing subsystems when
1047 * any child cgroups exist. This is theoretically supportable
1048 * but involves complex error handling, so it's being left until
1050 if (root
->number_of_cgroups
> 1)
1053 /* Process each subsystem */
1054 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++) {
1055 struct cgroup_subsys
*ss
= subsys
[i
];
1056 unsigned long bit
= 1UL << i
;
1057 if (bit
& added_mask
) {
1058 /* We're binding this subsystem to this hierarchy */
1060 BUG_ON(cgrp
->subsys
[i
]);
1061 BUG_ON(!dummytop
->subsys
[i
]);
1062 BUG_ON(dummytop
->subsys
[i
]->cgroup
!= dummytop
);
1063 cgrp
->subsys
[i
] = dummytop
->subsys
[i
];
1064 cgrp
->subsys
[i
]->cgroup
= cgrp
;
1065 list_move(&ss
->sibling
, &root
->subsys_list
);
1069 /* refcount was already taken, and we're keeping it */
1070 } else if (bit
& removed_mask
) {
1071 /* We're removing this subsystem */
1073 BUG_ON(cgrp
->subsys
[i
] != dummytop
->subsys
[i
]);
1074 BUG_ON(cgrp
->subsys
[i
]->cgroup
!= cgrp
);
1077 dummytop
->subsys
[i
]->cgroup
= dummytop
;
1078 cgrp
->subsys
[i
] = NULL
;
1079 subsys
[i
]->root
= &rootnode
;
1080 list_move(&ss
->sibling
, &rootnode
.subsys_list
);
1081 /* subsystem is now free - drop reference on module */
1082 module_put(ss
->module
);
1083 } else if (bit
& final_subsys_mask
) {
1084 /* Subsystem state should already exist */
1086 BUG_ON(!cgrp
->subsys
[i
]);
1088 * a refcount was taken, but we already had one, so
1089 * drop the extra reference.
1091 module_put(ss
->module
);
1092 #ifdef CONFIG_MODULE_UNLOAD
1093 BUG_ON(ss
->module
&& !module_refcount(ss
->module
));
1096 /* Subsystem state shouldn't exist */
1097 BUG_ON(cgrp
->subsys
[i
]);
1100 root
->subsys_mask
= root
->actual_subsys_mask
= final_subsys_mask
;
1105 static int cgroup_show_options(struct seq_file
*seq
, struct dentry
*dentry
)
1107 struct cgroupfs_root
*root
= dentry
->d_sb
->s_fs_info
;
1108 struct cgroup_subsys
*ss
;
1110 mutex_lock(&cgroup_root_mutex
);
1111 for_each_subsys(root
, ss
)
1112 seq_printf(seq
, ",%s", ss
->name
);
1113 if (test_bit(ROOT_NOPREFIX
, &root
->flags
))
1114 seq_puts(seq
, ",noprefix");
1115 if (test_bit(ROOT_XATTR
, &root
->flags
))
1116 seq_puts(seq
, ",xattr");
1117 if (strlen(root
->release_agent_path
))
1118 seq_printf(seq
, ",release_agent=%s", root
->release_agent_path
);
1119 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN
, &root
->top_cgroup
.flags
))
1120 seq_puts(seq
, ",clone_children");
1121 if (strlen(root
->name
))
1122 seq_printf(seq
, ",name=%s", root
->name
);
1123 mutex_unlock(&cgroup_root_mutex
);
1127 struct cgroup_sb_opts
{
1128 unsigned long subsys_mask
;
1129 unsigned long flags
;
1130 char *release_agent
;
1131 bool cpuset_clone_children
;
1133 /* User explicitly requested empty subsystem */
1136 struct cgroupfs_root
*new_root
;
1141 * Convert a hierarchy specifier into a bitmask of subsystems and flags. Call
1142 * with cgroup_mutex held to protect the subsys[] array. This function takes
1143 * refcounts on subsystems to be used, unless it returns error, in which case
1144 * no refcounts are taken.
1146 static int parse_cgroupfs_options(char *data
, struct cgroup_sb_opts
*opts
)
1148 char *token
, *o
= data
;
1149 bool all_ss
= false, one_ss
= false;
1150 unsigned long mask
= (unsigned long)-1;
1152 bool module_pin_failed
= false;
1154 BUG_ON(!mutex_is_locked(&cgroup_mutex
));
1156 #ifdef CONFIG_CPUSETS
1157 mask
= ~(1UL << cpuset_subsys_id
);
1160 memset(opts
, 0, sizeof(*opts
));
1162 while ((token
= strsep(&o
, ",")) != NULL
) {
1165 if (!strcmp(token
, "none")) {
1166 /* Explicitly have no subsystems */
1170 if (!strcmp(token
, "all")) {
1171 /* Mutually exclusive option 'all' + subsystem name */
1177 if (!strcmp(token
, "noprefix")) {
1178 set_bit(ROOT_NOPREFIX
, &opts
->flags
);
1181 if (!strcmp(token
, "clone_children")) {
1182 opts
->cpuset_clone_children
= true;
1185 if (!strcmp(token
, "xattr")) {
1186 set_bit(ROOT_XATTR
, &opts
->flags
);
1189 if (!strncmp(token
, "release_agent=", 14)) {
1190 /* Specifying two release agents is forbidden */
1191 if (opts
->release_agent
)
1193 opts
->release_agent
=
1194 kstrndup(token
+ 14, PATH_MAX
- 1, GFP_KERNEL
);
1195 if (!opts
->release_agent
)
1199 if (!strncmp(token
, "name=", 5)) {
1200 const char *name
= token
+ 5;
1201 /* Can't specify an empty name */
1204 /* Must match [\w.-]+ */
1205 for (i
= 0; i
< strlen(name
); i
++) {
1209 if ((c
== '.') || (c
== '-') || (c
== '_'))
1213 /* Specifying two names is forbidden */
1216 opts
->name
= kstrndup(name
,
1217 MAX_CGROUP_ROOT_NAMELEN
- 1,
1225 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++) {
1226 struct cgroup_subsys
*ss
= subsys
[i
];
1229 if (strcmp(token
, ss
->name
))
1234 /* Mutually exclusive option 'all' + subsystem name */
1237 set_bit(i
, &opts
->subsys_mask
);
1242 if (i
== CGROUP_SUBSYS_COUNT
)
1247 * If the 'all' option was specified select all the subsystems,
1248 * otherwise if 'none', 'name=' and a subsystem name options
1249 * were not specified, let's default to 'all'
1251 if (all_ss
|| (!one_ss
&& !opts
->none
&& !opts
->name
)) {
1252 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++) {
1253 struct cgroup_subsys
*ss
= subsys
[i
];
1258 set_bit(i
, &opts
->subsys_mask
);
1262 /* Consistency checks */
1265 * Option noprefix was introduced just for backward compatibility
1266 * with the old cpuset, so we allow noprefix only if mounting just
1267 * the cpuset subsystem.
1269 if (test_bit(ROOT_NOPREFIX
, &opts
->flags
) &&
1270 (opts
->subsys_mask
& mask
))
1274 /* Can't specify "none" and some subsystems */
1275 if (opts
->subsys_mask
&& opts
->none
)
1279 * We either have to specify by name or by subsystems. (So all
1280 * empty hierarchies must have a name).
1282 if (!opts
->subsys_mask
&& !opts
->name
)
1286 * Grab references on all the modules we'll need, so the subsystems
1287 * don't dance around before rebind_subsystems attaches them. This may
1288 * take duplicate reference counts on a subsystem that's already used,
1289 * but rebind_subsystems handles this case.
1291 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++) {
1292 unsigned long bit
= 1UL << i
;
1294 if (!(bit
& opts
->subsys_mask
))
1296 if (!try_module_get(subsys
[i
]->module
)) {
1297 module_pin_failed
= true;
1301 if (module_pin_failed
) {
1303 * oops, one of the modules was going away. this means that we
1304 * raced with a module_delete call, and to the user this is
1305 * essentially a "subsystem doesn't exist" case.
1307 for (i
--; i
>= 0; i
--) {
1308 /* drop refcounts only on the ones we took */
1309 unsigned long bit
= 1UL << i
;
1311 if (!(bit
& opts
->subsys_mask
))
1313 module_put(subsys
[i
]->module
);
1321 static void drop_parsed_module_refcounts(unsigned long subsys_mask
)
1324 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++) {
1325 unsigned long bit
= 1UL << i
;
1327 if (!(bit
& subsys_mask
))
1329 module_put(subsys
[i
]->module
);
1333 static int cgroup_remount(struct super_block
*sb
, int *flags
, char *data
)
1336 struct cgroupfs_root
*root
= sb
->s_fs_info
;
1337 struct cgroup
*cgrp
= &root
->top_cgroup
;
1338 struct cgroup_sb_opts opts
;
1339 unsigned long added_mask
, removed_mask
;
1341 mutex_lock(&cgrp
->dentry
->d_inode
->i_mutex
);
1342 mutex_lock(&cgroup_mutex
);
1343 mutex_lock(&cgroup_root_mutex
);
1345 /* See what subsystems are wanted */
1346 ret
= parse_cgroupfs_options(data
, &opts
);
1350 if (opts
.subsys_mask
!= root
->actual_subsys_mask
|| opts
.release_agent
)
1351 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1352 task_tgid_nr(current
), current
->comm
);
1354 added_mask
= opts
.subsys_mask
& ~root
->subsys_mask
;
1355 removed_mask
= root
->subsys_mask
& ~opts
.subsys_mask
;
1357 /* Don't allow flags or name to change at remount */
1358 if (opts
.flags
!= root
->flags
||
1359 (opts
.name
&& strcmp(opts
.name
, root
->name
))) {
1361 drop_parsed_module_refcounts(opts
.subsys_mask
);
1366 * Clear out the files of subsystems that should be removed, do
1367 * this before rebind_subsystems, since rebind_subsystems may
1368 * change this hierarchy's subsys_list.
1370 cgroup_clear_directory(cgrp
->dentry
, false, removed_mask
);
1372 ret
= rebind_subsystems(root
, opts
.subsys_mask
);
1374 /* rebind_subsystems failed, re-populate the removed files */
1375 cgroup_populate_dir(cgrp
, false, removed_mask
);
1376 drop_parsed_module_refcounts(opts
.subsys_mask
);
1380 /* re-populate subsystem files */
1381 cgroup_populate_dir(cgrp
, false, added_mask
);
1383 if (opts
.release_agent
)
1384 strcpy(root
->release_agent_path
, opts
.release_agent
);
1386 kfree(opts
.release_agent
);
1388 mutex_unlock(&cgroup_root_mutex
);
1389 mutex_unlock(&cgroup_mutex
);
1390 mutex_unlock(&cgrp
->dentry
->d_inode
->i_mutex
);
1394 static const struct super_operations cgroup_ops
= {
1395 .statfs
= simple_statfs
,
1396 .drop_inode
= generic_delete_inode
,
1397 .show_options
= cgroup_show_options
,
1398 .remount_fs
= cgroup_remount
,
1401 static void init_cgroup_housekeeping(struct cgroup
*cgrp
)
1403 INIT_LIST_HEAD(&cgrp
->sibling
);
1404 INIT_LIST_HEAD(&cgrp
->children
);
1405 INIT_LIST_HEAD(&cgrp
->files
);
1406 INIT_LIST_HEAD(&cgrp
->css_sets
);
1407 INIT_LIST_HEAD(&cgrp
->allcg_node
);
1408 INIT_LIST_HEAD(&cgrp
->release_list
);
1409 INIT_LIST_HEAD(&cgrp
->pidlists
);
1410 INIT_WORK(&cgrp
->free_work
, cgroup_free_fn
);
1411 mutex_init(&cgrp
->pidlist_mutex
);
1412 INIT_LIST_HEAD(&cgrp
->event_list
);
1413 spin_lock_init(&cgrp
->event_list_lock
);
1414 simple_xattrs_init(&cgrp
->xattrs
);
1417 static void init_cgroup_root(struct cgroupfs_root
*root
)
1419 struct cgroup
*cgrp
= &root
->top_cgroup
;
1421 INIT_LIST_HEAD(&root
->subsys_list
);
1422 INIT_LIST_HEAD(&root
->root_list
);
1423 INIT_LIST_HEAD(&root
->allcg_list
);
1424 root
->number_of_cgroups
= 1;
1426 cgrp
->name
= &root_cgroup_name
;
1427 cgrp
->top_cgroup
= cgrp
;
1428 init_cgroup_housekeeping(cgrp
);
1429 list_add_tail(&cgrp
->allcg_node
, &root
->allcg_list
);
1432 static bool init_root_id(struct cgroupfs_root
*root
)
1437 if (!ida_pre_get(&hierarchy_ida
, GFP_KERNEL
))
1439 spin_lock(&hierarchy_id_lock
);
1440 /* Try to allocate the next unused ID */
1441 ret
= ida_get_new_above(&hierarchy_ida
, next_hierarchy_id
,
1442 &root
->hierarchy_id
);
1444 /* Try again starting from 0 */
1445 ret
= ida_get_new(&hierarchy_ida
, &root
->hierarchy_id
);
1447 next_hierarchy_id
= root
->hierarchy_id
+ 1;
1448 } else if (ret
!= -EAGAIN
) {
1449 /* Can only get here if the 31-bit IDR is full ... */
1452 spin_unlock(&hierarchy_id_lock
);
1457 static int cgroup_test_super(struct super_block
*sb
, void *data
)
1459 struct cgroup_sb_opts
*opts
= data
;
1460 struct cgroupfs_root
*root
= sb
->s_fs_info
;
1462 /* If we asked for a name then it must match */
1463 if (opts
->name
&& strcmp(opts
->name
, root
->name
))
1467 * If we asked for subsystems (or explicitly for no
1468 * subsystems) then they must match
1470 if ((opts
->subsys_mask
|| opts
->none
)
1471 && (opts
->subsys_mask
!= root
->subsys_mask
))
1477 static struct cgroupfs_root
*cgroup_root_from_opts(struct cgroup_sb_opts
*opts
)
1479 struct cgroupfs_root
*root
;
1481 if (!opts
->subsys_mask
&& !opts
->none
)
1484 root
= kzalloc(sizeof(*root
), GFP_KERNEL
);
1486 return ERR_PTR(-ENOMEM
);
1488 if (!init_root_id(root
)) {
1490 return ERR_PTR(-ENOMEM
);
1492 init_cgroup_root(root
);
1494 root
->subsys_mask
= opts
->subsys_mask
;
1495 root
->flags
= opts
->flags
;
1496 ida_init(&root
->cgroup_ida
);
1497 if (opts
->release_agent
)
1498 strcpy(root
->release_agent_path
, opts
->release_agent
);
1500 strcpy(root
->name
, opts
->name
);
1501 if (opts
->cpuset_clone_children
)
1502 set_bit(CGRP_CPUSET_CLONE_CHILDREN
, &root
->top_cgroup
.flags
);
1506 static void cgroup_drop_root(struct cgroupfs_root
*root
)
1511 BUG_ON(!root
->hierarchy_id
);
1512 spin_lock(&hierarchy_id_lock
);
1513 ida_remove(&hierarchy_ida
, root
->hierarchy_id
);
1514 spin_unlock(&hierarchy_id_lock
);
1515 ida_destroy(&root
->cgroup_ida
);
1519 static int cgroup_set_super(struct super_block
*sb
, void *data
)
1522 struct cgroup_sb_opts
*opts
= data
;
1524 /* If we don't have a new root, we can't set up a new sb */
1525 if (!opts
->new_root
)
1528 BUG_ON(!opts
->subsys_mask
&& !opts
->none
);
1530 ret
= set_anon_super(sb
, NULL
);
1534 sb
->s_fs_info
= opts
->new_root
;
1535 opts
->new_root
->sb
= sb
;
1537 sb
->s_blocksize
= PAGE_CACHE_SIZE
;
1538 sb
->s_blocksize_bits
= PAGE_CACHE_SHIFT
;
1539 sb
->s_magic
= CGROUP_SUPER_MAGIC
;
1540 sb
->s_op
= &cgroup_ops
;
1545 static int cgroup_get_rootdir(struct super_block
*sb
)
1547 static const struct dentry_operations cgroup_dops
= {
1548 .d_iput
= cgroup_diput
,
1549 .d_delete
= cgroup_delete
,
1552 struct inode
*inode
=
1553 cgroup_new_inode(S_IFDIR
| S_IRUGO
| S_IXUGO
| S_IWUSR
, sb
);
1558 inode
->i_fop
= &simple_dir_operations
;
1559 inode
->i_op
= &cgroup_dir_inode_operations
;
1560 /* directories start off with i_nlink == 2 (for "." entry) */
1562 sb
->s_root
= d_make_root(inode
);
1565 /* for everything else we want ->d_op set */
1566 sb
->s_d_op
= &cgroup_dops
;
1570 static struct dentry
*cgroup_mount(struct file_system_type
*fs_type
,
1571 int flags
, const char *unused_dev_name
,
1574 struct cgroup_sb_opts opts
;
1575 struct cgroupfs_root
*root
;
1577 struct super_block
*sb
;
1578 struct cgroupfs_root
*new_root
;
1579 struct inode
*inode
;
1581 /* First find the desired set of subsystems */
1582 mutex_lock(&cgroup_mutex
);
1583 ret
= parse_cgroupfs_options(data
, &opts
);
1584 mutex_unlock(&cgroup_mutex
);
1589 * Allocate a new cgroup root. We may not need it if we're
1590 * reusing an existing hierarchy.
1592 new_root
= cgroup_root_from_opts(&opts
);
1593 if (IS_ERR(new_root
)) {
1594 ret
= PTR_ERR(new_root
);
1597 opts
.new_root
= new_root
;
1599 /* Locate an existing or new sb for this hierarchy */
1600 sb
= sget(fs_type
, cgroup_test_super
, cgroup_set_super
, 0, &opts
);
1603 cgroup_drop_root(opts
.new_root
);
1607 root
= sb
->s_fs_info
;
1609 if (root
== opts
.new_root
) {
1610 /* We used the new root structure, so this is a new hierarchy */
1611 struct list_head tmp_cg_links
;
1612 struct cgroup
*root_cgrp
= &root
->top_cgroup
;
1613 struct cgroupfs_root
*existing_root
;
1614 const struct cred
*cred
;
1618 BUG_ON(sb
->s_root
!= NULL
);
1620 ret
= cgroup_get_rootdir(sb
);
1622 goto drop_new_super
;
1623 inode
= sb
->s_root
->d_inode
;
1625 mutex_lock(&inode
->i_mutex
);
1626 mutex_lock(&cgroup_mutex
);
1627 mutex_lock(&cgroup_root_mutex
);
1629 /* Check for name clashes with existing mounts */
1631 if (strlen(root
->name
))
1632 for_each_active_root(existing_root
)
1633 if (!strcmp(existing_root
->name
, root
->name
))
1637 * We're accessing css_set_count without locking
1638 * css_set_lock here, but that's OK - it can only be
1639 * increased by someone holding cgroup_lock, and
1640 * that's us. The worst that can happen is that we
1641 * have some link structures left over
1643 ret
= allocate_cg_links(css_set_count
, &tmp_cg_links
);
1647 ret
= rebind_subsystems(root
, root
->subsys_mask
);
1648 if (ret
== -EBUSY
) {
1649 free_cg_links(&tmp_cg_links
);
1653 * There must be no failure case after here, since rebinding
1654 * takes care of subsystems' refcounts, which are explicitly
1655 * dropped in the failure exit path.
1658 /* EBUSY should be the only error here */
1661 list_add(&root
->root_list
, &roots
);
1664 sb
->s_root
->d_fsdata
= root_cgrp
;
1665 root
->top_cgroup
.dentry
= sb
->s_root
;
1667 /* Link the top cgroup in this hierarchy into all
1668 * the css_set objects */
1669 write_lock(&css_set_lock
);
1670 hash_for_each(css_set_table
, i
, cg
, hlist
)
1671 link_css_set(&tmp_cg_links
, cg
, root_cgrp
);
1672 write_unlock(&css_set_lock
);
1674 free_cg_links(&tmp_cg_links
);
1676 BUG_ON(!list_empty(&root_cgrp
->children
));
1677 BUG_ON(root
->number_of_cgroups
!= 1);
1679 cred
= override_creds(&init_cred
);
1680 cgroup_populate_dir(root_cgrp
, true, root
->subsys_mask
);
1682 mutex_unlock(&cgroup_root_mutex
);
1683 mutex_unlock(&cgroup_mutex
);
1684 mutex_unlock(&inode
->i_mutex
);
1687 * We re-used an existing hierarchy - the new root (if
1688 * any) is not needed
1690 cgroup_drop_root(opts
.new_root
);
1691 /* no subsys rebinding, so refcounts don't change */
1692 drop_parsed_module_refcounts(opts
.subsys_mask
);
1695 kfree(opts
.release_agent
);
1697 return dget(sb
->s_root
);
1700 mutex_unlock(&cgroup_root_mutex
);
1701 mutex_unlock(&cgroup_mutex
);
1702 mutex_unlock(&inode
->i_mutex
);
1704 deactivate_locked_super(sb
);
1706 drop_parsed_module_refcounts(opts
.subsys_mask
);
1708 kfree(opts
.release_agent
);
1710 return ERR_PTR(ret
);
1713 static void cgroup_kill_sb(struct super_block
*sb
) {
1714 struct cgroupfs_root
*root
= sb
->s_fs_info
;
1715 struct cgroup
*cgrp
= &root
->top_cgroup
;
1717 struct cg_cgroup_link
*link
;
1718 struct cg_cgroup_link
*saved_link
;
1722 BUG_ON(root
->number_of_cgroups
!= 1);
1723 BUG_ON(!list_empty(&cgrp
->children
));
1725 mutex_lock(&cgroup_mutex
);
1726 mutex_lock(&cgroup_root_mutex
);
1728 /* Rebind all subsystems back to the default hierarchy */
1729 ret
= rebind_subsystems(root
, 0);
1730 /* Shouldn't be able to fail ... */
1734 * Release all the links from css_sets to this hierarchy's
1737 write_lock(&css_set_lock
);
1739 list_for_each_entry_safe(link
, saved_link
, &cgrp
->css_sets
,
1741 list_del(&link
->cg_link_list
);
1742 list_del(&link
->cgrp_link_list
);
1745 write_unlock(&css_set_lock
);
1747 if (!list_empty(&root
->root_list
)) {
1748 list_del(&root
->root_list
);
1752 mutex_unlock(&cgroup_root_mutex
);
1753 mutex_unlock(&cgroup_mutex
);
1755 simple_xattrs_free(&cgrp
->xattrs
);
1757 kill_litter_super(sb
);
1758 cgroup_drop_root(root
);
1761 static struct file_system_type cgroup_fs_type
= {
1763 .mount
= cgroup_mount
,
1764 .kill_sb
= cgroup_kill_sb
,
1767 static struct kobject
*cgroup_kobj
;
1770 * cgroup_path - generate the path of a cgroup
1771 * @cgrp: the cgroup in question
1772 * @buf: the buffer to write the path into
1773 * @buflen: the length of the buffer
1775 * Writes path of cgroup into buf. Returns 0 on success, -errno on error.
1777 * We can't generate cgroup path using dentry->d_name, as accessing
1778 * dentry->name must be protected by irq-unsafe dentry->d_lock or parent
1779 * inode's i_mutex, while on the other hand cgroup_path() can be called
1780 * with some irq-safe spinlocks held.
1782 int cgroup_path(const struct cgroup
*cgrp
, char *buf
, int buflen
)
1784 int ret
= -ENAMETOOLONG
;
1787 start
= buf
+ buflen
- 1;
1792 const char *name
= cgroup_name(cgrp
);
1796 if ((start
-= len
) < buf
)
1798 memcpy(start
, name
, len
);
1807 cgrp
= cgrp
->parent
;
1810 memmove(buf
, start
, buf
+ buflen
- start
);
1815 EXPORT_SYMBOL_GPL(cgroup_path
);
1818 * Control Group taskset
1820 struct task_and_cgroup
{
1821 struct task_struct
*task
;
1822 struct cgroup
*cgrp
;
1826 struct cgroup_taskset
{
1827 struct task_and_cgroup single
;
1828 struct flex_array
*tc_array
;
1831 struct cgroup
*cur_cgrp
;
1835 * cgroup_taskset_first - reset taskset and return the first task
1836 * @tset: taskset of interest
1838 * @tset iteration is initialized and the first task is returned.
1840 struct task_struct
*cgroup_taskset_first(struct cgroup_taskset
*tset
)
1842 if (tset
->tc_array
) {
1844 return cgroup_taskset_next(tset
);
1846 tset
->cur_cgrp
= tset
->single
.cgrp
;
1847 return tset
->single
.task
;
1850 EXPORT_SYMBOL_GPL(cgroup_taskset_first
);
1853 * cgroup_taskset_next - iterate to the next task in taskset
1854 * @tset: taskset of interest
1856 * Return the next task in @tset. Iteration must have been initialized
1857 * with cgroup_taskset_first().
1859 struct task_struct
*cgroup_taskset_next(struct cgroup_taskset
*tset
)
1861 struct task_and_cgroup
*tc
;
1863 if (!tset
->tc_array
|| tset
->idx
>= tset
->tc_array_len
)
1866 tc
= flex_array_get(tset
->tc_array
, tset
->idx
++);
1867 tset
->cur_cgrp
= tc
->cgrp
;
1870 EXPORT_SYMBOL_GPL(cgroup_taskset_next
);
1873 * cgroup_taskset_cur_cgroup - return the matching cgroup for the current task
1874 * @tset: taskset of interest
1876 * Return the cgroup for the current (last returned) task of @tset. This
1877 * function must be preceded by either cgroup_taskset_first() or
1878 * cgroup_taskset_next().
1880 struct cgroup
*cgroup_taskset_cur_cgroup(struct cgroup_taskset
*tset
)
1882 return tset
->cur_cgrp
;
1884 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_cgroup
);
1887 * cgroup_taskset_size - return the number of tasks in taskset
1888 * @tset: taskset of interest
1890 int cgroup_taskset_size(struct cgroup_taskset
*tset
)
1892 return tset
->tc_array
? tset
->tc_array_len
: 1;
1894 EXPORT_SYMBOL_GPL(cgroup_taskset_size
);
1898 * cgroup_task_migrate - move a task from one cgroup to another.
1900 * Must be called with cgroup_mutex and threadgroup locked.
1902 static void cgroup_task_migrate(struct cgroup
*oldcgrp
,
1903 struct task_struct
*tsk
, struct css_set
*newcg
)
1905 struct css_set
*oldcg
;
1908 * We are synchronized through threadgroup_lock() against PF_EXITING
1909 * setting such that we can't race against cgroup_exit() changing the
1910 * css_set to init_css_set and dropping the old one.
1912 WARN_ON_ONCE(tsk
->flags
& PF_EXITING
);
1913 oldcg
= tsk
->cgroups
;
1916 rcu_assign_pointer(tsk
->cgroups
, newcg
);
1919 /* Update the css_set linked lists if we're using them */
1920 write_lock(&css_set_lock
);
1921 if (!list_empty(&tsk
->cg_list
))
1922 list_move(&tsk
->cg_list
, &newcg
->tasks
);
1923 write_unlock(&css_set_lock
);
1926 * We just gained a reference on oldcg by taking it from the task. As
1927 * trading it for newcg is protected by cgroup_mutex, we're safe to drop
1928 * it here; it will be freed under RCU.
1930 set_bit(CGRP_RELEASABLE
, &oldcgrp
->flags
);
1935 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1936 * @cgrp: the cgroup to attach to
1937 * @tsk: the task or the leader of the threadgroup to be attached
1938 * @threadgroup: attach the whole threadgroup?
1940 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
1941 * task_lock of @tsk or each thread in the threadgroup individually in turn.
1943 static int cgroup_attach_task(struct cgroup
*cgrp
, struct task_struct
*tsk
,
1946 int retval
, i
, group_size
;
1947 struct cgroup_subsys
*ss
, *failed_ss
= NULL
;
1948 struct cgroupfs_root
*root
= cgrp
->root
;
1949 /* threadgroup list cursor and array */
1950 struct task_struct
*leader
= tsk
;
1951 struct task_and_cgroup
*tc
;
1952 struct flex_array
*group
;
1953 struct cgroup_taskset tset
= { };
1956 * step 0: in order to do expensive, possibly blocking operations for
1957 * every thread, we cannot iterate the thread group list, since it needs
1958 * rcu or tasklist locked. instead, build an array of all threads in the
1959 * group - group_rwsem prevents new threads from appearing, and if
1960 * threads exit, this will just be an over-estimate.
1963 group_size
= get_nr_threads(tsk
);
1966 /* flex_array supports very large thread-groups better than kmalloc. */
1967 group
= flex_array_alloc(sizeof(*tc
), group_size
, GFP_KERNEL
);
1970 /* pre-allocate to guarantee space while iterating in rcu read-side. */
1971 retval
= flex_array_prealloc(group
, 0, group_size
, GFP_KERNEL
);
1973 goto out_free_group_list
;
1977 * Prevent freeing of tasks while we take a snapshot. Tasks that are
1978 * already PF_EXITING could be freed from underneath us unless we
1979 * take an rcu_read_lock.
1983 struct task_and_cgroup ent
;
1985 /* @tsk either already exited or can't exit until the end */
1986 if (tsk
->flags
& PF_EXITING
)
1989 /* as per above, nr_threads may decrease, but not increase. */
1990 BUG_ON(i
>= group_size
);
1992 ent
.cgrp
= task_cgroup_from_root(tsk
, root
);
1993 /* nothing to do if this task is already in the cgroup */
1994 if (ent
.cgrp
== cgrp
)
1997 * saying GFP_ATOMIC has no effect here because we did prealloc
1998 * earlier, but it's good form to communicate our expectations.
2000 retval
= flex_array_put(group
, i
, &ent
, GFP_ATOMIC
);
2001 BUG_ON(retval
!= 0);
2006 } while_each_thread(leader
, tsk
);
2008 /* remember the number of threads in the array for later. */
2010 tset
.tc_array
= group
;
2011 tset
.tc_array_len
= group_size
;
2013 /* methods shouldn't be called if no task is actually migrating */
2016 goto out_free_group_list
;
2019 * step 1: check that we can legitimately attach to the cgroup.
2021 for_each_subsys(root
, ss
) {
2022 if (ss
->can_attach
) {
2023 retval
= ss
->can_attach(cgrp
, &tset
);
2026 goto out_cancel_attach
;
2032 * step 2: make sure css_sets exist for all threads to be migrated.
2033 * we use find_css_set, which allocates a new one if necessary.
2035 for (i
= 0; i
< group_size
; i
++) {
2036 tc
= flex_array_get(group
, i
);
2037 tc
->cg
= find_css_set(tc
->task
->cgroups
, cgrp
);
2040 goto out_put_css_set_refs
;
2045 * step 3: now that we're guaranteed success wrt the css_sets,
2046 * proceed to move all tasks to the new cgroup. There are no
2047 * failure cases after here, so this is the commit point.
2049 for (i
= 0; i
< group_size
; i
++) {
2050 tc
= flex_array_get(group
, i
);
2051 cgroup_task_migrate(tc
->cgrp
, tc
->task
, tc
->cg
);
2053 /* nothing is sensitive to fork() after this point. */
2056 * step 4: do subsystem attach callbacks.
2058 for_each_subsys(root
, ss
) {
2060 ss
->attach(cgrp
, &tset
);
2064 * step 5: success! and cleanup
2067 out_put_css_set_refs
:
2069 for (i
= 0; i
< group_size
; i
++) {
2070 tc
= flex_array_get(group
, i
);
2073 put_css_set(tc
->cg
);
2078 for_each_subsys(root
, ss
) {
2079 if (ss
== failed_ss
)
2081 if (ss
->cancel_attach
)
2082 ss
->cancel_attach(cgrp
, &tset
);
2085 out_free_group_list
:
2086 flex_array_free(group
);
2091 * Find the task_struct of the task to attach by vpid and pass it along to the
2092 * function to attach either it or all tasks in its threadgroup. Will lock
2093 * cgroup_mutex and threadgroup; may take task_lock of task.
2095 static int attach_task_by_pid(struct cgroup
*cgrp
, u64 pid
, bool threadgroup
)
2097 struct task_struct
*tsk
;
2098 const struct cred
*cred
= current_cred(), *tcred
;
2101 if (!cgroup_lock_live_group(cgrp
))
2107 tsk
= find_task_by_vpid(pid
);
2111 goto out_unlock_cgroup
;
2114 * even if we're attaching all tasks in the thread group, we
2115 * only need to check permissions on one of them.
2117 tcred
= __task_cred(tsk
);
2118 if (!uid_eq(cred
->euid
, GLOBAL_ROOT_UID
) &&
2119 !uid_eq(cred
->euid
, tcred
->uid
) &&
2120 !uid_eq(cred
->euid
, tcred
->suid
)) {
2123 goto out_unlock_cgroup
;
2129 tsk
= tsk
->group_leader
;
2132 * Workqueue threads may acquire PF_THREAD_BOUND and become
2133 * trapped in a cpuset, or RT worker may be born in a cgroup
2134 * with no rt_runtime allocated. Just say no.
2136 if (tsk
== kthreadd_task
|| (tsk
->flags
& PF_THREAD_BOUND
)) {
2139 goto out_unlock_cgroup
;
2142 get_task_struct(tsk
);
2145 threadgroup_lock(tsk
);
2147 if (!thread_group_leader(tsk
)) {
2149 * a race with de_thread from another thread's exec()
2150 * may strip us of our leadership, if this happens,
2151 * there is no choice but to throw this task away and
2152 * try again; this is
2153 * "double-double-toil-and-trouble-check locking".
2155 threadgroup_unlock(tsk
);
2156 put_task_struct(tsk
);
2157 goto retry_find_task
;
2161 ret
= cgroup_attach_task(cgrp
, tsk
, threadgroup
);
2163 threadgroup_unlock(tsk
);
2165 put_task_struct(tsk
);
2167 mutex_unlock(&cgroup_mutex
);
2172 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2173 * @from: attach to all cgroups of a given task
2174 * @tsk: the task to be attached
2176 int cgroup_attach_task_all(struct task_struct
*from
, struct task_struct
*tsk
)
2178 struct cgroupfs_root
*root
;
2181 mutex_lock(&cgroup_mutex
);
2182 for_each_active_root(root
) {
2183 struct cgroup
*from_cg
= task_cgroup_from_root(from
, root
);
2185 retval
= cgroup_attach_task(from_cg
, tsk
, false);
2189 mutex_unlock(&cgroup_mutex
);
2193 EXPORT_SYMBOL_GPL(cgroup_attach_task_all
);
2195 static int cgroup_tasks_write(struct cgroup
*cgrp
, struct cftype
*cft
, u64 pid
)
2197 return attach_task_by_pid(cgrp
, pid
, false);
2200 static int cgroup_procs_write(struct cgroup
*cgrp
, struct cftype
*cft
, u64 tgid
)
2202 return attach_task_by_pid(cgrp
, tgid
, true);
2205 static int cgroup_release_agent_write(struct cgroup
*cgrp
, struct cftype
*cft
,
2208 BUILD_BUG_ON(sizeof(cgrp
->root
->release_agent_path
) < PATH_MAX
);
2209 if (strlen(buffer
) >= PATH_MAX
)
2211 if (!cgroup_lock_live_group(cgrp
))
2213 mutex_lock(&cgroup_root_mutex
);
2214 strcpy(cgrp
->root
->release_agent_path
, buffer
);
2215 mutex_unlock(&cgroup_root_mutex
);
2216 mutex_unlock(&cgroup_mutex
);
2220 static int cgroup_release_agent_show(struct cgroup
*cgrp
, struct cftype
*cft
,
2221 struct seq_file
*seq
)
2223 if (!cgroup_lock_live_group(cgrp
))
2225 seq_puts(seq
, cgrp
->root
->release_agent_path
);
2226 seq_putc(seq
, '\n');
2227 mutex_unlock(&cgroup_mutex
);
2231 /* A buffer size big enough for numbers or short strings */
2232 #define CGROUP_LOCAL_BUFFER_SIZE 64
2234 static ssize_t
cgroup_write_X64(struct cgroup
*cgrp
, struct cftype
*cft
,
2236 const char __user
*userbuf
,
2237 size_t nbytes
, loff_t
*unused_ppos
)
2239 char buffer
[CGROUP_LOCAL_BUFFER_SIZE
];
2245 if (nbytes
>= sizeof(buffer
))
2247 if (copy_from_user(buffer
, userbuf
, nbytes
))
2250 buffer
[nbytes
] = 0; /* nul-terminate */
2251 if (cft
->write_u64
) {
2252 u64 val
= simple_strtoull(strstrip(buffer
), &end
, 0);
2255 retval
= cft
->write_u64(cgrp
, cft
, val
);
2257 s64 val
= simple_strtoll(strstrip(buffer
), &end
, 0);
2260 retval
= cft
->write_s64(cgrp
, cft
, val
);
2267 static ssize_t
cgroup_write_string(struct cgroup
*cgrp
, struct cftype
*cft
,
2269 const char __user
*userbuf
,
2270 size_t nbytes
, loff_t
*unused_ppos
)
2272 char local_buffer
[CGROUP_LOCAL_BUFFER_SIZE
];
2274 size_t max_bytes
= cft
->max_write_len
;
2275 char *buffer
= local_buffer
;
2278 max_bytes
= sizeof(local_buffer
) - 1;
2279 if (nbytes
>= max_bytes
)
2281 /* Allocate a dynamic buffer if we need one */
2282 if (nbytes
>= sizeof(local_buffer
)) {
2283 buffer
= kmalloc(nbytes
+ 1, GFP_KERNEL
);
2287 if (nbytes
&& copy_from_user(buffer
, userbuf
, nbytes
)) {
2292 buffer
[nbytes
] = 0; /* nul-terminate */
2293 retval
= cft
->write_string(cgrp
, cft
, strstrip(buffer
));
2297 if (buffer
!= local_buffer
)
2302 static ssize_t
cgroup_file_write(struct file
*file
, const char __user
*buf
,
2303 size_t nbytes
, loff_t
*ppos
)
2305 struct cftype
*cft
= __d_cft(file
->f_dentry
);
2306 struct cgroup
*cgrp
= __d_cgrp(file
->f_dentry
->d_parent
);
2308 if (cgroup_is_removed(cgrp
))
2311 return cft
->write(cgrp
, cft
, file
, buf
, nbytes
, ppos
);
2312 if (cft
->write_u64
|| cft
->write_s64
)
2313 return cgroup_write_X64(cgrp
, cft
, file
, buf
, nbytes
, ppos
);
2314 if (cft
->write_string
)
2315 return cgroup_write_string(cgrp
, cft
, file
, buf
, nbytes
, ppos
);
2317 int ret
= cft
->trigger(cgrp
, (unsigned int)cft
->private);
2318 return ret
? ret
: nbytes
;
2323 static ssize_t
cgroup_read_u64(struct cgroup
*cgrp
, struct cftype
*cft
,
2325 char __user
*buf
, size_t nbytes
,
2328 char tmp
[CGROUP_LOCAL_BUFFER_SIZE
];
2329 u64 val
= cft
->read_u64(cgrp
, cft
);
2330 int len
= sprintf(tmp
, "%llu\n", (unsigned long long) val
);
2332 return simple_read_from_buffer(buf
, nbytes
, ppos
, tmp
, len
);
2335 static ssize_t
cgroup_read_s64(struct cgroup
*cgrp
, struct cftype
*cft
,
2337 char __user
*buf
, size_t nbytes
,
2340 char tmp
[CGROUP_LOCAL_BUFFER_SIZE
];
2341 s64 val
= cft
->read_s64(cgrp
, cft
);
2342 int len
= sprintf(tmp
, "%lld\n", (long long) val
);
2344 return simple_read_from_buffer(buf
, nbytes
, ppos
, tmp
, len
);
2347 static ssize_t
cgroup_file_read(struct file
*file
, char __user
*buf
,
2348 size_t nbytes
, loff_t
*ppos
)
2350 struct cftype
*cft
= __d_cft(file
->f_dentry
);
2351 struct cgroup
*cgrp
= __d_cgrp(file
->f_dentry
->d_parent
);
2353 if (cgroup_is_removed(cgrp
))
2357 return cft
->read(cgrp
, cft
, file
, buf
, nbytes
, ppos
);
2359 return cgroup_read_u64(cgrp
, cft
, file
, buf
, nbytes
, ppos
);
2361 return cgroup_read_s64(cgrp
, cft
, file
, buf
, nbytes
, ppos
);
2366 * seqfile ops/methods for returning structured data. Currently just
2367 * supports string->u64 maps, but can be extended in future.
2370 struct cgroup_seqfile_state
{
2372 struct cgroup
*cgroup
;
2375 static int cgroup_map_add(struct cgroup_map_cb
*cb
, const char *key
, u64 value
)
2377 struct seq_file
*sf
= cb
->state
;
2378 return seq_printf(sf
, "%s %llu\n", key
, (unsigned long long)value
);
2381 static int cgroup_seqfile_show(struct seq_file
*m
, void *arg
)
2383 struct cgroup_seqfile_state
*state
= m
->private;
2384 struct cftype
*cft
= state
->cft
;
2385 if (cft
->read_map
) {
2386 struct cgroup_map_cb cb
= {
2387 .fill
= cgroup_map_add
,
2390 return cft
->read_map(state
->cgroup
, cft
, &cb
);
2392 return cft
->read_seq_string(state
->cgroup
, cft
, m
);
2395 static int cgroup_seqfile_release(struct inode
*inode
, struct file
*file
)
2397 struct seq_file
*seq
= file
->private_data
;
2398 kfree(seq
->private);
2399 return single_release(inode
, file
);
2402 static const struct file_operations cgroup_seqfile_operations
= {
2404 .write
= cgroup_file_write
,
2405 .llseek
= seq_lseek
,
2406 .release
= cgroup_seqfile_release
,
2409 static int cgroup_file_open(struct inode
*inode
, struct file
*file
)
2414 err
= generic_file_open(inode
, file
);
2417 cft
= __d_cft(file
->f_dentry
);
2419 if (cft
->read_map
|| cft
->read_seq_string
) {
2420 struct cgroup_seqfile_state
*state
=
2421 kzalloc(sizeof(*state
), GFP_USER
);
2425 state
->cgroup
= __d_cgrp(file
->f_dentry
->d_parent
);
2426 file
->f_op
= &cgroup_seqfile_operations
;
2427 err
= single_open(file
, cgroup_seqfile_show
, state
);
2430 } else if (cft
->open
)
2431 err
= cft
->open(inode
, file
);
2438 static int cgroup_file_release(struct inode
*inode
, struct file
*file
)
2440 struct cftype
*cft
= __d_cft(file
->f_dentry
);
2442 return cft
->release(inode
, file
);
2447 * cgroup_rename - Only allow simple rename of directories in place.
2449 static int cgroup_rename(struct inode
*old_dir
, struct dentry
*old_dentry
,
2450 struct inode
*new_dir
, struct dentry
*new_dentry
)
2453 struct cgroup_name
*name
, *old_name
;
2454 struct cgroup
*cgrp
;
2457 * It's convinient to use parent dir's i_mutex to protected
2460 lockdep_assert_held(&old_dir
->i_mutex
);
2462 if (!S_ISDIR(old_dentry
->d_inode
->i_mode
))
2464 if (new_dentry
->d_inode
)
2466 if (old_dir
!= new_dir
)
2469 cgrp
= __d_cgrp(old_dentry
);
2471 name
= cgroup_alloc_name(new_dentry
);
2475 ret
= simple_rename(old_dir
, old_dentry
, new_dir
, new_dentry
);
2481 old_name
= cgrp
->name
;
2482 rcu_assign_pointer(cgrp
->name
, name
);
2484 kfree_rcu(old_name
, rcu_head
);
2488 static struct simple_xattrs
*__d_xattrs(struct dentry
*dentry
)
2490 if (S_ISDIR(dentry
->d_inode
->i_mode
))
2491 return &__d_cgrp(dentry
)->xattrs
;
2493 return &__d_cft(dentry
)->xattrs
;
2496 static inline int xattr_enabled(struct dentry
*dentry
)
2498 struct cgroupfs_root
*root
= dentry
->d_sb
->s_fs_info
;
2499 return test_bit(ROOT_XATTR
, &root
->flags
);
2502 static bool is_valid_xattr(const char *name
)
2504 if (!strncmp(name
, XATTR_TRUSTED_PREFIX
, XATTR_TRUSTED_PREFIX_LEN
) ||
2505 !strncmp(name
, XATTR_SECURITY_PREFIX
, XATTR_SECURITY_PREFIX_LEN
))
2510 static int cgroup_setxattr(struct dentry
*dentry
, const char *name
,
2511 const void *val
, size_t size
, int flags
)
2513 if (!xattr_enabled(dentry
))
2515 if (!is_valid_xattr(name
))
2517 return simple_xattr_set(__d_xattrs(dentry
), name
, val
, size
, flags
);
2520 static int cgroup_removexattr(struct dentry
*dentry
, const char *name
)
2522 if (!xattr_enabled(dentry
))
2524 if (!is_valid_xattr(name
))
2526 return simple_xattr_remove(__d_xattrs(dentry
), name
);
2529 static ssize_t
cgroup_getxattr(struct dentry
*dentry
, const char *name
,
2530 void *buf
, size_t size
)
2532 if (!xattr_enabled(dentry
))
2534 if (!is_valid_xattr(name
))
2536 return simple_xattr_get(__d_xattrs(dentry
), name
, buf
, size
);
2539 static ssize_t
cgroup_listxattr(struct dentry
*dentry
, char *buf
, size_t size
)
2541 if (!xattr_enabled(dentry
))
2543 return simple_xattr_list(__d_xattrs(dentry
), buf
, size
);
2546 static const struct file_operations cgroup_file_operations
= {
2547 .read
= cgroup_file_read
,
2548 .write
= cgroup_file_write
,
2549 .llseek
= generic_file_llseek
,
2550 .open
= cgroup_file_open
,
2551 .release
= cgroup_file_release
,
2554 static const struct inode_operations cgroup_file_inode_operations
= {
2555 .setxattr
= cgroup_setxattr
,
2556 .getxattr
= cgroup_getxattr
,
2557 .listxattr
= cgroup_listxattr
,
2558 .removexattr
= cgroup_removexattr
,
2561 static const struct inode_operations cgroup_dir_inode_operations
= {
2562 .lookup
= cgroup_lookup
,
2563 .mkdir
= cgroup_mkdir
,
2564 .rmdir
= cgroup_rmdir
,
2565 .rename
= cgroup_rename
,
2566 .setxattr
= cgroup_setxattr
,
2567 .getxattr
= cgroup_getxattr
,
2568 .listxattr
= cgroup_listxattr
,
2569 .removexattr
= cgroup_removexattr
,
2572 static struct dentry
*cgroup_lookup(struct inode
*dir
, struct dentry
*dentry
, unsigned int flags
)
2574 if (dentry
->d_name
.len
> NAME_MAX
)
2575 return ERR_PTR(-ENAMETOOLONG
);
2576 d_add(dentry
, NULL
);
2581 * Check if a file is a control file
2583 static inline struct cftype
*__file_cft(struct file
*file
)
2585 if (file_inode(file
)->i_fop
!= &cgroup_file_operations
)
2586 return ERR_PTR(-EINVAL
);
2587 return __d_cft(file
->f_dentry
);
2590 static int cgroup_create_file(struct dentry
*dentry
, umode_t mode
,
2591 struct super_block
*sb
)
2593 struct inode
*inode
;
2597 if (dentry
->d_inode
)
2600 inode
= cgroup_new_inode(mode
, sb
);
2604 if (S_ISDIR(mode
)) {
2605 inode
->i_op
= &cgroup_dir_inode_operations
;
2606 inode
->i_fop
= &simple_dir_operations
;
2608 /* start off with i_nlink == 2 (for "." entry) */
2610 inc_nlink(dentry
->d_parent
->d_inode
);
2613 * Control reaches here with cgroup_mutex held.
2614 * @inode->i_mutex should nest outside cgroup_mutex but we
2615 * want to populate it immediately without releasing
2616 * cgroup_mutex. As @inode isn't visible to anyone else
2617 * yet, trylock will always succeed without affecting
2620 WARN_ON_ONCE(!mutex_trylock(&inode
->i_mutex
));
2621 } else if (S_ISREG(mode
)) {
2623 inode
->i_fop
= &cgroup_file_operations
;
2624 inode
->i_op
= &cgroup_file_inode_operations
;
2626 d_instantiate(dentry
, inode
);
2627 dget(dentry
); /* Extra count - pin the dentry in core */
2632 * cgroup_file_mode - deduce file mode of a control file
2633 * @cft: the control file in question
2635 * returns cft->mode if ->mode is not 0
2636 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2637 * returns S_IRUGO if it has only a read handler
2638 * returns S_IWUSR if it has only a write hander
2640 static umode_t
cgroup_file_mode(const struct cftype
*cft
)
2647 if (cft
->read
|| cft
->read_u64
|| cft
->read_s64
||
2648 cft
->read_map
|| cft
->read_seq_string
)
2651 if (cft
->write
|| cft
->write_u64
|| cft
->write_s64
||
2652 cft
->write_string
|| cft
->trigger
)
2658 static int cgroup_add_file(struct cgroup
*cgrp
, struct cgroup_subsys
*subsys
,
2661 struct dentry
*dir
= cgrp
->dentry
;
2662 struct cgroup
*parent
= __d_cgrp(dir
);
2663 struct dentry
*dentry
;
2667 char name
[MAX_CGROUP_TYPE_NAMELEN
+ MAX_CFTYPE_NAME
+ 2] = { 0 };
2669 simple_xattrs_init(&cft
->xattrs
);
2671 if (subsys
&& !test_bit(ROOT_NOPREFIX
, &cgrp
->root
->flags
)) {
2672 strcpy(name
, subsys
->name
);
2675 strcat(name
, cft
->name
);
2677 BUG_ON(!mutex_is_locked(&dir
->d_inode
->i_mutex
));
2679 cfe
= kzalloc(sizeof(*cfe
), GFP_KERNEL
);
2683 dentry
= lookup_one_len(name
, dir
, strlen(name
));
2684 if (IS_ERR(dentry
)) {
2685 error
= PTR_ERR(dentry
);
2689 mode
= cgroup_file_mode(cft
);
2690 error
= cgroup_create_file(dentry
, mode
| S_IFREG
, cgrp
->root
->sb
);
2692 cfe
->type
= (void *)cft
;
2693 cfe
->dentry
= dentry
;
2694 dentry
->d_fsdata
= cfe
;
2695 list_add_tail(&cfe
->node
, &parent
->files
);
2704 static int cgroup_addrm_files(struct cgroup
*cgrp
, struct cgroup_subsys
*subsys
,
2705 struct cftype cfts
[], bool is_add
)
2710 for (cft
= cfts
; cft
->name
[0] != '\0'; cft
++) {
2711 /* does cft->flags tell us to skip this file on @cgrp? */
2712 if ((cft
->flags
& CFTYPE_NOT_ON_ROOT
) && !cgrp
->parent
)
2714 if ((cft
->flags
& CFTYPE_ONLY_ON_ROOT
) && cgrp
->parent
)
2718 err
= cgroup_add_file(cgrp
, subsys
, cft
);
2720 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2724 cgroup_rm_file(cgrp
, cft
);
2730 static DEFINE_MUTEX(cgroup_cft_mutex
);
2732 static void cgroup_cfts_prepare(void)
2733 __acquires(&cgroup_cft_mutex
) __acquires(&cgroup_mutex
)
2736 * Thanks to the entanglement with vfs inode locking, we can't walk
2737 * the existing cgroups under cgroup_mutex and create files.
2738 * Instead, we increment reference on all cgroups and build list of
2739 * them using @cgrp->cft_q_node. Grab cgroup_cft_mutex to ensure
2740 * exclusive access to the field.
2742 mutex_lock(&cgroup_cft_mutex
);
2743 mutex_lock(&cgroup_mutex
);
2746 static void cgroup_cfts_commit(struct cgroup_subsys
*ss
,
2747 struct cftype
*cfts
, bool is_add
)
2748 __releases(&cgroup_mutex
) __releases(&cgroup_cft_mutex
)
2751 struct cgroup
*cgrp
, *n
;
2753 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2754 if (cfts
&& ss
->root
!= &rootnode
) {
2755 list_for_each_entry(cgrp
, &ss
->root
->allcg_list
, allcg_node
) {
2757 list_add_tail(&cgrp
->cft_q_node
, &pending
);
2761 mutex_unlock(&cgroup_mutex
);
2764 * All new cgroups will see @cfts update on @ss->cftsets. Add/rm
2765 * files for all cgroups which were created before.
2767 list_for_each_entry_safe(cgrp
, n
, &pending
, cft_q_node
) {
2768 struct inode
*inode
= cgrp
->dentry
->d_inode
;
2770 mutex_lock(&inode
->i_mutex
);
2771 mutex_lock(&cgroup_mutex
);
2772 if (!cgroup_is_removed(cgrp
))
2773 cgroup_addrm_files(cgrp
, ss
, cfts
, is_add
);
2774 mutex_unlock(&cgroup_mutex
);
2775 mutex_unlock(&inode
->i_mutex
);
2777 list_del_init(&cgrp
->cft_q_node
);
2781 mutex_unlock(&cgroup_cft_mutex
);
2785 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2786 * @ss: target cgroup subsystem
2787 * @cfts: zero-length name terminated array of cftypes
2789 * Register @cfts to @ss. Files described by @cfts are created for all
2790 * existing cgroups to which @ss is attached and all future cgroups will
2791 * have them too. This function can be called anytime whether @ss is
2794 * Returns 0 on successful registration, -errno on failure. Note that this
2795 * function currently returns 0 as long as @cfts registration is successful
2796 * even if some file creation attempts on existing cgroups fail.
2798 int cgroup_add_cftypes(struct cgroup_subsys
*ss
, struct cftype
*cfts
)
2800 struct cftype_set
*set
;
2802 set
= kzalloc(sizeof(*set
), GFP_KERNEL
);
2806 cgroup_cfts_prepare();
2808 list_add_tail(&set
->node
, &ss
->cftsets
);
2809 cgroup_cfts_commit(ss
, cfts
, true);
2813 EXPORT_SYMBOL_GPL(cgroup_add_cftypes
);
2816 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2817 * @ss: target cgroup subsystem
2818 * @cfts: zero-length name terminated array of cftypes
2820 * Unregister @cfts from @ss. Files described by @cfts are removed from
2821 * all existing cgroups to which @ss is attached and all future cgroups
2822 * won't have them either. This function can be called anytime whether @ss
2823 * is attached or not.
2825 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2826 * registered with @ss.
2828 int cgroup_rm_cftypes(struct cgroup_subsys
*ss
, struct cftype
*cfts
)
2830 struct cftype_set
*set
;
2832 cgroup_cfts_prepare();
2834 list_for_each_entry(set
, &ss
->cftsets
, node
) {
2835 if (set
->cfts
== cfts
) {
2836 list_del_init(&set
->node
);
2837 cgroup_cfts_commit(ss
, cfts
, false);
2842 cgroup_cfts_commit(ss
, NULL
, false);
2847 * cgroup_task_count - count the number of tasks in a cgroup.
2848 * @cgrp: the cgroup in question
2850 * Return the number of tasks in the cgroup.
2852 int cgroup_task_count(const struct cgroup
*cgrp
)
2855 struct cg_cgroup_link
*link
;
2857 read_lock(&css_set_lock
);
2858 list_for_each_entry(link
, &cgrp
->css_sets
, cgrp_link_list
) {
2859 count
+= atomic_read(&link
->cg
->refcount
);
2861 read_unlock(&css_set_lock
);
2866 * Advance a list_head iterator. The iterator should be positioned at
2867 * the start of a css_set
2869 static void cgroup_advance_iter(struct cgroup
*cgrp
,
2870 struct cgroup_iter
*it
)
2872 struct list_head
*l
= it
->cg_link
;
2873 struct cg_cgroup_link
*link
;
2876 /* Advance to the next non-empty css_set */
2879 if (l
== &cgrp
->css_sets
) {
2883 link
= list_entry(l
, struct cg_cgroup_link
, cgrp_link_list
);
2885 } while (list_empty(&cg
->tasks
));
2887 it
->task
= cg
->tasks
.next
;
2891 * To reduce the fork() overhead for systems that are not actually
2892 * using their cgroups capability, we don't maintain the lists running
2893 * through each css_set to its tasks until we see the list actually
2894 * used - in other words after the first call to cgroup_iter_start().
2896 static void cgroup_enable_task_cg_lists(void)
2898 struct task_struct
*p
, *g
;
2899 write_lock(&css_set_lock
);
2900 use_task_css_set_links
= 1;
2902 * We need tasklist_lock because RCU is not safe against
2903 * while_each_thread(). Besides, a forking task that has passed
2904 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2905 * is not guaranteed to have its child immediately visible in the
2906 * tasklist if we walk through it with RCU.
2908 read_lock(&tasklist_lock
);
2909 do_each_thread(g
, p
) {
2912 * We should check if the process is exiting, otherwise
2913 * it will race with cgroup_exit() in that the list
2914 * entry won't be deleted though the process has exited.
2916 if (!(p
->flags
& PF_EXITING
) && list_empty(&p
->cg_list
))
2917 list_add(&p
->cg_list
, &p
->cgroups
->tasks
);
2919 } while_each_thread(g
, p
);
2920 read_unlock(&tasklist_lock
);
2921 write_unlock(&css_set_lock
);
2925 * cgroup_next_descendant_pre - find the next descendant for pre-order walk
2926 * @pos: the current position (%NULL to initiate traversal)
2927 * @cgroup: cgroup whose descendants to walk
2929 * To be used by cgroup_for_each_descendant_pre(). Find the next
2930 * descendant to visit for pre-order traversal of @cgroup's descendants.
2932 struct cgroup
*cgroup_next_descendant_pre(struct cgroup
*pos
,
2933 struct cgroup
*cgroup
)
2935 struct cgroup
*next
;
2937 WARN_ON_ONCE(!rcu_read_lock_held());
2939 /* if first iteration, pretend we just visited @cgroup */
2941 if (list_empty(&cgroup
->children
))
2946 /* visit the first child if exists */
2947 next
= list_first_or_null_rcu(&pos
->children
, struct cgroup
, sibling
);
2951 /* no child, visit my or the closest ancestor's next sibling */
2953 next
= list_entry_rcu(pos
->sibling
.next
, struct cgroup
,
2955 if (&next
->sibling
!= &pos
->parent
->children
)
2959 } while (pos
!= cgroup
);
2963 EXPORT_SYMBOL_GPL(cgroup_next_descendant_pre
);
2966 * cgroup_rightmost_descendant - return the rightmost descendant of a cgroup
2967 * @pos: cgroup of interest
2969 * Return the rightmost descendant of @pos. If there's no descendant,
2970 * @pos is returned. This can be used during pre-order traversal to skip
2973 struct cgroup
*cgroup_rightmost_descendant(struct cgroup
*pos
)
2975 struct cgroup
*last
, *tmp
;
2977 WARN_ON_ONCE(!rcu_read_lock_held());
2981 /* ->prev isn't RCU safe, walk ->next till the end */
2983 list_for_each_entry_rcu(tmp
, &last
->children
, sibling
)
2989 EXPORT_SYMBOL_GPL(cgroup_rightmost_descendant
);
2991 static struct cgroup
*cgroup_leftmost_descendant(struct cgroup
*pos
)
2993 struct cgroup
*last
;
2997 pos
= list_first_or_null_rcu(&pos
->children
, struct cgroup
,
3005 * cgroup_next_descendant_post - find the next descendant for post-order walk
3006 * @pos: the current position (%NULL to initiate traversal)
3007 * @cgroup: cgroup whose descendants to walk
3009 * To be used by cgroup_for_each_descendant_post(). Find the next
3010 * descendant to visit for post-order traversal of @cgroup's descendants.
3012 struct cgroup
*cgroup_next_descendant_post(struct cgroup
*pos
,
3013 struct cgroup
*cgroup
)
3015 struct cgroup
*next
;
3017 WARN_ON_ONCE(!rcu_read_lock_held());
3019 /* if first iteration, visit the leftmost descendant */
3021 next
= cgroup_leftmost_descendant(cgroup
);
3022 return next
!= cgroup
? next
: NULL
;
3025 /* if there's an unvisited sibling, visit its leftmost descendant */
3026 next
= list_entry_rcu(pos
->sibling
.next
, struct cgroup
, sibling
);
3027 if (&next
->sibling
!= &pos
->parent
->children
)
3028 return cgroup_leftmost_descendant(next
);
3030 /* no sibling left, visit parent */
3032 return next
!= cgroup
? next
: NULL
;
3034 EXPORT_SYMBOL_GPL(cgroup_next_descendant_post
);
3036 void cgroup_iter_start(struct cgroup
*cgrp
, struct cgroup_iter
*it
)
3037 __acquires(css_set_lock
)
3040 * The first time anyone tries to iterate across a cgroup,
3041 * we need to enable the list linking each css_set to its
3042 * tasks, and fix up all existing tasks.
3044 if (!use_task_css_set_links
)
3045 cgroup_enable_task_cg_lists();
3047 read_lock(&css_set_lock
);
3048 it
->cg_link
= &cgrp
->css_sets
;
3049 cgroup_advance_iter(cgrp
, it
);
3052 struct task_struct
*cgroup_iter_next(struct cgroup
*cgrp
,
3053 struct cgroup_iter
*it
)
3055 struct task_struct
*res
;
3056 struct list_head
*l
= it
->task
;
3057 struct cg_cgroup_link
*link
;
3059 /* If the iterator cg is NULL, we have no tasks */
3062 res
= list_entry(l
, struct task_struct
, cg_list
);
3063 /* Advance iterator to find next entry */
3065 link
= list_entry(it
->cg_link
, struct cg_cgroup_link
, cgrp_link_list
);
3066 if (l
== &link
->cg
->tasks
) {
3067 /* We reached the end of this task list - move on to
3068 * the next cg_cgroup_link */
3069 cgroup_advance_iter(cgrp
, it
);
3076 void cgroup_iter_end(struct cgroup
*cgrp
, struct cgroup_iter
*it
)
3077 __releases(css_set_lock
)
3079 read_unlock(&css_set_lock
);
3082 static inline int started_after_time(struct task_struct
*t1
,
3083 struct timespec
*time
,
3084 struct task_struct
*t2
)
3086 int start_diff
= timespec_compare(&t1
->start_time
, time
);
3087 if (start_diff
> 0) {
3089 } else if (start_diff
< 0) {
3093 * Arbitrarily, if two processes started at the same
3094 * time, we'll say that the lower pointer value
3095 * started first. Note that t2 may have exited by now
3096 * so this may not be a valid pointer any longer, but
3097 * that's fine - it still serves to distinguish
3098 * between two tasks started (effectively) simultaneously.
3105 * This function is a callback from heap_insert() and is used to order
3107 * In this case we order the heap in descending task start time.
3109 static inline int started_after(void *p1
, void *p2
)
3111 struct task_struct
*t1
= p1
;
3112 struct task_struct
*t2
= p2
;
3113 return started_after_time(t1
, &t2
->start_time
, t2
);
3117 * cgroup_scan_tasks - iterate though all the tasks in a cgroup
3118 * @scan: struct cgroup_scanner containing arguments for the scan
3120 * Arguments include pointers to callback functions test_task() and
3122 * Iterate through all the tasks in a cgroup, calling test_task() for each,
3123 * and if it returns true, call process_task() for it also.
3124 * The test_task pointer may be NULL, meaning always true (select all tasks).
3125 * Effectively duplicates cgroup_iter_{start,next,end}()
3126 * but does not lock css_set_lock for the call to process_task().
3127 * The struct cgroup_scanner may be embedded in any structure of the caller's
3129 * It is guaranteed that process_task() will act on every task that
3130 * is a member of the cgroup for the duration of this call. This
3131 * function may or may not call process_task() for tasks that exit
3132 * or move to a different cgroup during the call, or are forked or
3133 * move into the cgroup during the call.
3135 * Note that test_task() may be called with locks held, and may in some
3136 * situations be called multiple times for the same task, so it should
3138 * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
3139 * pre-allocated and will be used for heap operations (and its "gt" member will
3140 * be overwritten), else a temporary heap will be used (allocation of which
3141 * may cause this function to fail).
3143 int cgroup_scan_tasks(struct cgroup_scanner
*scan
)
3146 struct cgroup_iter it
;
3147 struct task_struct
*p
, *dropped
;
3148 /* Never dereference latest_task, since it's not refcounted */
3149 struct task_struct
*latest_task
= NULL
;
3150 struct ptr_heap tmp_heap
;
3151 struct ptr_heap
*heap
;
3152 struct timespec latest_time
= { 0, 0 };
3155 /* The caller supplied our heap and pre-allocated its memory */
3157 heap
->gt
= &started_after
;
3159 /* We need to allocate our own heap memory */
3161 retval
= heap_init(heap
, PAGE_SIZE
, GFP_KERNEL
, &started_after
);
3163 /* cannot allocate the heap */
3169 * Scan tasks in the cgroup, using the scanner's "test_task" callback
3170 * to determine which are of interest, and using the scanner's
3171 * "process_task" callback to process any of them that need an update.
3172 * Since we don't want to hold any locks during the task updates,
3173 * gather tasks to be processed in a heap structure.
3174 * The heap is sorted by descending task start time.
3175 * If the statically-sized heap fills up, we overflow tasks that
3176 * started later, and in future iterations only consider tasks that
3177 * started after the latest task in the previous pass. This
3178 * guarantees forward progress and that we don't miss any tasks.
3181 cgroup_iter_start(scan
->cg
, &it
);
3182 while ((p
= cgroup_iter_next(scan
->cg
, &it
))) {
3184 * Only affect tasks that qualify per the caller's callback,
3185 * if he provided one
3187 if (scan
->test_task
&& !scan
->test_task(p
, scan
))
3190 * Only process tasks that started after the last task
3193 if (!started_after_time(p
, &latest_time
, latest_task
))
3195 dropped
= heap_insert(heap
, p
);
3196 if (dropped
== NULL
) {
3198 * The new task was inserted; the heap wasn't
3202 } else if (dropped
!= p
) {
3204 * The new task was inserted, and pushed out a
3208 put_task_struct(dropped
);
3211 * Else the new task was newer than anything already in
3212 * the heap and wasn't inserted
3215 cgroup_iter_end(scan
->cg
, &it
);
3218 for (i
= 0; i
< heap
->size
; i
++) {
3219 struct task_struct
*q
= heap
->ptrs
[i
];
3221 latest_time
= q
->start_time
;
3224 /* Process the task per the caller's callback */
3225 scan
->process_task(q
, scan
);
3229 * If we had to process any tasks at all, scan again
3230 * in case some of them were in the middle of forking
3231 * children that didn't get processed.
3232 * Not the most efficient way to do it, but it avoids
3233 * having to take callback_mutex in the fork path
3237 if (heap
== &tmp_heap
)
3238 heap_free(&tmp_heap
);
3242 static void cgroup_transfer_one_task(struct task_struct
*task
,
3243 struct cgroup_scanner
*scan
)
3245 struct cgroup
*new_cgroup
= scan
->data
;
3247 mutex_lock(&cgroup_mutex
);
3248 cgroup_attach_task(new_cgroup
, task
, false);
3249 mutex_unlock(&cgroup_mutex
);
3253 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3254 * @to: cgroup to which the tasks will be moved
3255 * @from: cgroup in which the tasks currently reside
3257 int cgroup_transfer_tasks(struct cgroup
*to
, struct cgroup
*from
)
3259 struct cgroup_scanner scan
;
3262 scan
.test_task
= NULL
; /* select all tasks in cgroup */
3263 scan
.process_task
= cgroup_transfer_one_task
;
3267 return cgroup_scan_tasks(&scan
);
3271 * Stuff for reading the 'tasks'/'procs' files.
3273 * Reading this file can return large amounts of data if a cgroup has
3274 * *lots* of attached tasks. So it may need several calls to read(),
3275 * but we cannot guarantee that the information we produce is correct
3276 * unless we produce it entirely atomically.
3280 /* which pidlist file are we talking about? */
3281 enum cgroup_filetype
{
3287 * A pidlist is a list of pids that virtually represents the contents of one
3288 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3289 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3292 struct cgroup_pidlist
{
3294 * used to find which pidlist is wanted. doesn't change as long as
3295 * this particular list stays in the list.
3297 struct { enum cgroup_filetype type
; struct pid_namespace
*ns
; } key
;
3300 /* how many elements the above list has */
3302 /* how many files are using the current array */
3304 /* each of these stored in a list by its cgroup */
3305 struct list_head links
;
3306 /* pointer to the cgroup we belong to, for list removal purposes */
3307 struct cgroup
*owner
;
3308 /* protects the other fields */
3309 struct rw_semaphore mutex
;
3313 * The following two functions "fix" the issue where there are more pids
3314 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3315 * TODO: replace with a kernel-wide solution to this problem
3317 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3318 static void *pidlist_allocate(int count
)
3320 if (PIDLIST_TOO_LARGE(count
))
3321 return vmalloc(count
* sizeof(pid_t
));
3323 return kmalloc(count
* sizeof(pid_t
), GFP_KERNEL
);
3325 static void pidlist_free(void *p
)
3327 if (is_vmalloc_addr(p
))
3334 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3335 * Returns the number of unique elements.
3337 static int pidlist_uniq(pid_t
*list
, int length
)
3342 * we presume the 0th element is unique, so i starts at 1. trivial
3343 * edge cases first; no work needs to be done for either
3345 if (length
== 0 || length
== 1)
3347 /* src and dest walk down the list; dest counts unique elements */
3348 for (src
= 1; src
< length
; src
++) {
3349 /* find next unique element */
3350 while (list
[src
] == list
[src
-1]) {
3355 /* dest always points to where the next unique element goes */
3356 list
[dest
] = list
[src
];
3363 static int cmppid(const void *a
, const void *b
)
3365 return *(pid_t
*)a
- *(pid_t
*)b
;
3369 * find the appropriate pidlist for our purpose (given procs vs tasks)
3370 * returns with the lock on that pidlist already held, and takes care
3371 * of the use count, or returns NULL with no locks held if we're out of
3374 static struct cgroup_pidlist
*cgroup_pidlist_find(struct cgroup
*cgrp
,
3375 enum cgroup_filetype type
)
3377 struct cgroup_pidlist
*l
;
3378 /* don't need task_nsproxy() if we're looking at ourself */
3379 struct pid_namespace
*ns
= task_active_pid_ns(current
);
3382 * We can't drop the pidlist_mutex before taking the l->mutex in case
3383 * the last ref-holder is trying to remove l from the list at the same
3384 * time. Holding the pidlist_mutex precludes somebody taking whichever
3385 * list we find out from under us - compare release_pid_array().
3387 mutex_lock(&cgrp
->pidlist_mutex
);
3388 list_for_each_entry(l
, &cgrp
->pidlists
, links
) {
3389 if (l
->key
.type
== type
&& l
->key
.ns
== ns
) {
3390 /* make sure l doesn't vanish out from under us */
3391 down_write(&l
->mutex
);
3392 mutex_unlock(&cgrp
->pidlist_mutex
);
3396 /* entry not found; create a new one */
3397 l
= kmalloc(sizeof(struct cgroup_pidlist
), GFP_KERNEL
);
3399 mutex_unlock(&cgrp
->pidlist_mutex
);
3402 init_rwsem(&l
->mutex
);
3403 down_write(&l
->mutex
);
3405 l
->key
.ns
= get_pid_ns(ns
);
3406 l
->use_count
= 0; /* don't increment here */
3409 list_add(&l
->links
, &cgrp
->pidlists
);
3410 mutex_unlock(&cgrp
->pidlist_mutex
);
3415 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3417 static int pidlist_array_load(struct cgroup
*cgrp
, enum cgroup_filetype type
,
3418 struct cgroup_pidlist
**lp
)
3422 int pid
, n
= 0; /* used for populating the array */
3423 struct cgroup_iter it
;
3424 struct task_struct
*tsk
;
3425 struct cgroup_pidlist
*l
;
3428 * If cgroup gets more users after we read count, we won't have
3429 * enough space - tough. This race is indistinguishable to the
3430 * caller from the case that the additional cgroup users didn't
3431 * show up until sometime later on.
3433 length
= cgroup_task_count(cgrp
);
3434 array
= pidlist_allocate(length
);
3437 /* now, populate the array */
3438 cgroup_iter_start(cgrp
, &it
);
3439 while ((tsk
= cgroup_iter_next(cgrp
, &it
))) {
3440 if (unlikely(n
== length
))
3442 /* get tgid or pid for procs or tasks file respectively */
3443 if (type
== CGROUP_FILE_PROCS
)
3444 pid
= task_tgid_vnr(tsk
);
3446 pid
= task_pid_vnr(tsk
);
3447 if (pid
> 0) /* make sure to only use valid results */
3450 cgroup_iter_end(cgrp
, &it
);
3452 /* now sort & (if procs) strip out duplicates */
3453 sort(array
, length
, sizeof(pid_t
), cmppid
, NULL
);
3454 if (type
== CGROUP_FILE_PROCS
)
3455 length
= pidlist_uniq(array
, length
);
3456 l
= cgroup_pidlist_find(cgrp
, type
);
3458 pidlist_free(array
);
3461 /* store array, freeing old if necessary - lock already held */
3462 pidlist_free(l
->list
);
3466 up_write(&l
->mutex
);
3472 * cgroupstats_build - build and fill cgroupstats
3473 * @stats: cgroupstats to fill information into
3474 * @dentry: A dentry entry belonging to the cgroup for which stats have
3477 * Build and fill cgroupstats so that taskstats can export it to user
3480 int cgroupstats_build(struct cgroupstats
*stats
, struct dentry
*dentry
)
3483 struct cgroup
*cgrp
;
3484 struct cgroup_iter it
;
3485 struct task_struct
*tsk
;
3488 * Validate dentry by checking the superblock operations,
3489 * and make sure it's a directory.
3491 if (dentry
->d_sb
->s_op
!= &cgroup_ops
||
3492 !S_ISDIR(dentry
->d_inode
->i_mode
))
3496 cgrp
= dentry
->d_fsdata
;
3498 cgroup_iter_start(cgrp
, &it
);
3499 while ((tsk
= cgroup_iter_next(cgrp
, &it
))) {
3500 switch (tsk
->state
) {
3502 stats
->nr_running
++;
3504 case TASK_INTERRUPTIBLE
:
3505 stats
->nr_sleeping
++;
3507 case TASK_UNINTERRUPTIBLE
:
3508 stats
->nr_uninterruptible
++;
3511 stats
->nr_stopped
++;
3514 if (delayacct_is_task_waiting_on_io(tsk
))
3515 stats
->nr_io_wait
++;
3519 cgroup_iter_end(cgrp
, &it
);
3527 * seq_file methods for the tasks/procs files. The seq_file position is the
3528 * next pid to display; the seq_file iterator is a pointer to the pid
3529 * in the cgroup->l->list array.
3532 static void *cgroup_pidlist_start(struct seq_file
*s
, loff_t
*pos
)
3535 * Initially we receive a position value that corresponds to
3536 * one more than the last pid shown (or 0 on the first call or
3537 * after a seek to the start). Use a binary-search to find the
3538 * next pid to display, if any
3540 struct cgroup_pidlist
*l
= s
->private;
3541 int index
= 0, pid
= *pos
;
3544 down_read(&l
->mutex
);
3546 int end
= l
->length
;
3548 while (index
< end
) {
3549 int mid
= (index
+ end
) / 2;
3550 if (l
->list
[mid
] == pid
) {
3553 } else if (l
->list
[mid
] <= pid
)
3559 /* If we're off the end of the array, we're done */
3560 if (index
>= l
->length
)
3562 /* Update the abstract position to be the actual pid that we found */
3563 iter
= l
->list
+ index
;
3568 static void cgroup_pidlist_stop(struct seq_file
*s
, void *v
)
3570 struct cgroup_pidlist
*l
= s
->private;
3574 static void *cgroup_pidlist_next(struct seq_file
*s
, void *v
, loff_t
*pos
)
3576 struct cgroup_pidlist
*l
= s
->private;
3578 pid_t
*end
= l
->list
+ l
->length
;
3580 * Advance to the next pid in the array. If this goes off the
3592 static int cgroup_pidlist_show(struct seq_file
*s
, void *v
)
3594 return seq_printf(s
, "%d\n", *(int *)v
);
3598 * seq_operations functions for iterating on pidlists through seq_file -
3599 * independent of whether it's tasks or procs
3601 static const struct seq_operations cgroup_pidlist_seq_operations
= {
3602 .start
= cgroup_pidlist_start
,
3603 .stop
= cgroup_pidlist_stop
,
3604 .next
= cgroup_pidlist_next
,
3605 .show
= cgroup_pidlist_show
,
3608 static void cgroup_release_pid_array(struct cgroup_pidlist
*l
)
3611 * the case where we're the last user of this particular pidlist will
3612 * have us remove it from the cgroup's list, which entails taking the
3613 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3614 * pidlist_mutex, we have to take pidlist_mutex first.
3616 mutex_lock(&l
->owner
->pidlist_mutex
);
3617 down_write(&l
->mutex
);
3618 BUG_ON(!l
->use_count
);
3619 if (!--l
->use_count
) {
3620 /* we're the last user if refcount is 0; remove and free */
3621 list_del(&l
->links
);
3622 mutex_unlock(&l
->owner
->pidlist_mutex
);
3623 pidlist_free(l
->list
);
3624 put_pid_ns(l
->key
.ns
);
3625 up_write(&l
->mutex
);
3629 mutex_unlock(&l
->owner
->pidlist_mutex
);
3630 up_write(&l
->mutex
);
3633 static int cgroup_pidlist_release(struct inode
*inode
, struct file
*file
)
3635 struct cgroup_pidlist
*l
;
3636 if (!(file
->f_mode
& FMODE_READ
))
3639 * the seq_file will only be initialized if the file was opened for
3640 * reading; hence we check if it's not null only in that case.
3642 l
= ((struct seq_file
*)file
->private_data
)->private;
3643 cgroup_release_pid_array(l
);
3644 return seq_release(inode
, file
);
3647 static const struct file_operations cgroup_pidlist_operations
= {
3649 .llseek
= seq_lseek
,
3650 .write
= cgroup_file_write
,
3651 .release
= cgroup_pidlist_release
,
3655 * The following functions handle opens on a file that displays a pidlist
3656 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3659 /* helper function for the two below it */
3660 static int cgroup_pidlist_open(struct file
*file
, enum cgroup_filetype type
)
3662 struct cgroup
*cgrp
= __d_cgrp(file
->f_dentry
->d_parent
);
3663 struct cgroup_pidlist
*l
;
3666 /* Nothing to do for write-only files */
3667 if (!(file
->f_mode
& FMODE_READ
))
3670 /* have the array populated */
3671 retval
= pidlist_array_load(cgrp
, type
, &l
);
3674 /* configure file information */
3675 file
->f_op
= &cgroup_pidlist_operations
;
3677 retval
= seq_open(file
, &cgroup_pidlist_seq_operations
);
3679 cgroup_release_pid_array(l
);
3682 ((struct seq_file
*)file
->private_data
)->private = l
;
3685 static int cgroup_tasks_open(struct inode
*unused
, struct file
*file
)
3687 return cgroup_pidlist_open(file
, CGROUP_FILE_TASKS
);
3689 static int cgroup_procs_open(struct inode
*unused
, struct file
*file
)
3691 return cgroup_pidlist_open(file
, CGROUP_FILE_PROCS
);
3694 static u64
cgroup_read_notify_on_release(struct cgroup
*cgrp
,
3697 return notify_on_release(cgrp
);
3700 static int cgroup_write_notify_on_release(struct cgroup
*cgrp
,
3704 clear_bit(CGRP_RELEASABLE
, &cgrp
->flags
);
3706 set_bit(CGRP_NOTIFY_ON_RELEASE
, &cgrp
->flags
);
3708 clear_bit(CGRP_NOTIFY_ON_RELEASE
, &cgrp
->flags
);
3713 * Unregister event and free resources.
3715 * Gets called from workqueue.
3717 static void cgroup_event_remove(struct work_struct
*work
)
3719 struct cgroup_event
*event
= container_of(work
, struct cgroup_event
,
3721 struct cgroup
*cgrp
= event
->cgrp
;
3723 remove_wait_queue(event
->wqh
, &event
->wait
);
3725 event
->cft
->unregister_event(cgrp
, event
->cft
, event
->eventfd
);
3727 /* Notify userspace the event is going away. */
3728 eventfd_signal(event
->eventfd
, 1);
3730 eventfd_ctx_put(event
->eventfd
);
3736 * Gets called on POLLHUP on eventfd when user closes it.
3738 * Called with wqh->lock held and interrupts disabled.
3740 static int cgroup_event_wake(wait_queue_t
*wait
, unsigned mode
,
3741 int sync
, void *key
)
3743 struct cgroup_event
*event
= container_of(wait
,
3744 struct cgroup_event
, wait
);
3745 struct cgroup
*cgrp
= event
->cgrp
;
3746 unsigned long flags
= (unsigned long)key
;
3748 if (flags
& POLLHUP
) {
3750 * If the event has been detached at cgroup removal, we
3751 * can simply return knowing the other side will cleanup
3754 * We can't race against event freeing since the other
3755 * side will require wqh->lock via remove_wait_queue(),
3758 spin_lock(&cgrp
->event_list_lock
);
3759 if (!list_empty(&event
->list
)) {
3760 list_del_init(&event
->list
);
3762 * We are in atomic context, but cgroup_event_remove()
3763 * may sleep, so we have to call it in workqueue.
3765 schedule_work(&event
->remove
);
3767 spin_unlock(&cgrp
->event_list_lock
);
3773 static void cgroup_event_ptable_queue_proc(struct file
*file
,
3774 wait_queue_head_t
*wqh
, poll_table
*pt
)
3776 struct cgroup_event
*event
= container_of(pt
,
3777 struct cgroup_event
, pt
);
3780 add_wait_queue(wqh
, &event
->wait
);
3784 * Parse input and register new cgroup event handler.
3786 * Input must be in format '<event_fd> <control_fd> <args>'.
3787 * Interpretation of args is defined by control file implementation.
3789 static int cgroup_write_event_control(struct cgroup
*cgrp
, struct cftype
*cft
,
3792 struct cgroup_event
*event
= NULL
;
3793 struct cgroup
*cgrp_cfile
;
3794 unsigned int efd
, cfd
;
3795 struct file
*efile
= NULL
;
3796 struct file
*cfile
= NULL
;
3800 efd
= simple_strtoul(buffer
, &endp
, 10);
3805 cfd
= simple_strtoul(buffer
, &endp
, 10);
3806 if ((*endp
!= ' ') && (*endp
!= '\0'))
3810 event
= kzalloc(sizeof(*event
), GFP_KERNEL
);
3814 INIT_LIST_HEAD(&event
->list
);
3815 init_poll_funcptr(&event
->pt
, cgroup_event_ptable_queue_proc
);
3816 init_waitqueue_func_entry(&event
->wait
, cgroup_event_wake
);
3817 INIT_WORK(&event
->remove
, cgroup_event_remove
);
3819 efile
= eventfd_fget(efd
);
3820 if (IS_ERR(efile
)) {
3821 ret
= PTR_ERR(efile
);
3825 event
->eventfd
= eventfd_ctx_fileget(efile
);
3826 if (IS_ERR(event
->eventfd
)) {
3827 ret
= PTR_ERR(event
->eventfd
);
3837 /* the process need read permission on control file */
3838 /* AV: shouldn't we check that it's been opened for read instead? */
3839 ret
= inode_permission(file_inode(cfile
), MAY_READ
);
3843 event
->cft
= __file_cft(cfile
);
3844 if (IS_ERR(event
->cft
)) {
3845 ret
= PTR_ERR(event
->cft
);
3850 * The file to be monitored must be in the same cgroup as
3851 * cgroup.event_control is.
3853 cgrp_cfile
= __d_cgrp(cfile
->f_dentry
->d_parent
);
3854 if (cgrp_cfile
!= cgrp
) {
3859 if (!event
->cft
->register_event
|| !event
->cft
->unregister_event
) {
3864 ret
= event
->cft
->register_event(cgrp
, event
->cft
,
3865 event
->eventfd
, buffer
);
3870 * Events should be removed after rmdir of cgroup directory, but before
3871 * destroying subsystem state objects. Let's take reference to cgroup
3872 * directory dentry to do that.
3876 spin_lock(&cgrp
->event_list_lock
);
3877 list_add(&event
->list
, &cgrp
->event_list
);
3878 spin_unlock(&cgrp
->event_list_lock
);
3889 if (event
&& event
->eventfd
&& !IS_ERR(event
->eventfd
))
3890 eventfd_ctx_put(event
->eventfd
);
3892 if (!IS_ERR_OR_NULL(efile
))
3900 static u64
cgroup_clone_children_read(struct cgroup
*cgrp
,
3903 return test_bit(CGRP_CPUSET_CLONE_CHILDREN
, &cgrp
->flags
);
3906 static int cgroup_clone_children_write(struct cgroup
*cgrp
,
3911 set_bit(CGRP_CPUSET_CLONE_CHILDREN
, &cgrp
->flags
);
3913 clear_bit(CGRP_CPUSET_CLONE_CHILDREN
, &cgrp
->flags
);
3918 * for the common functions, 'private' gives the type of file
3920 /* for hysterical raisins, we can't put this on the older files */
3921 #define CGROUP_FILE_GENERIC_PREFIX "cgroup."
3922 static struct cftype files
[] = {
3925 .open
= cgroup_tasks_open
,
3926 .write_u64
= cgroup_tasks_write
,
3927 .release
= cgroup_pidlist_release
,
3928 .mode
= S_IRUGO
| S_IWUSR
,
3931 .name
= CGROUP_FILE_GENERIC_PREFIX
"procs",
3932 .open
= cgroup_procs_open
,
3933 .write_u64
= cgroup_procs_write
,
3934 .release
= cgroup_pidlist_release
,
3935 .mode
= S_IRUGO
| S_IWUSR
,
3938 .name
= "notify_on_release",
3939 .read_u64
= cgroup_read_notify_on_release
,
3940 .write_u64
= cgroup_write_notify_on_release
,
3943 .name
= CGROUP_FILE_GENERIC_PREFIX
"event_control",
3944 .write_string
= cgroup_write_event_control
,
3948 .name
= "cgroup.clone_children",
3949 .read_u64
= cgroup_clone_children_read
,
3950 .write_u64
= cgroup_clone_children_write
,
3953 .name
= "release_agent",
3954 .flags
= CFTYPE_ONLY_ON_ROOT
,
3955 .read_seq_string
= cgroup_release_agent_show
,
3956 .write_string
= cgroup_release_agent_write
,
3957 .max_write_len
= PATH_MAX
,
3963 * cgroup_populate_dir - selectively creation of files in a directory
3964 * @cgrp: target cgroup
3965 * @base_files: true if the base files should be added
3966 * @subsys_mask: mask of the subsystem ids whose files should be added
3968 static int cgroup_populate_dir(struct cgroup
*cgrp
, bool base_files
,
3969 unsigned long subsys_mask
)
3972 struct cgroup_subsys
*ss
;
3975 err
= cgroup_addrm_files(cgrp
, NULL
, files
, true);
3980 /* process cftsets of each subsystem */
3981 for_each_subsys(cgrp
->root
, ss
) {
3982 struct cftype_set
*set
;
3983 if (!test_bit(ss
->subsys_id
, &subsys_mask
))
3986 list_for_each_entry(set
, &ss
->cftsets
, node
)
3987 cgroup_addrm_files(cgrp
, ss
, set
->cfts
, true);
3990 /* This cgroup is ready now */
3991 for_each_subsys(cgrp
->root
, ss
) {
3992 struct cgroup_subsys_state
*css
= cgrp
->subsys
[ss
->subsys_id
];
3994 * Update id->css pointer and make this css visible from
3995 * CSS ID functions. This pointer will be dereferened
3996 * from RCU-read-side without locks.
3999 rcu_assign_pointer(css
->id
->css
, css
);
4005 static void css_dput_fn(struct work_struct
*work
)
4007 struct cgroup_subsys_state
*css
=
4008 container_of(work
, struct cgroup_subsys_state
, dput_work
);
4009 struct dentry
*dentry
= css
->cgroup
->dentry
;
4010 struct super_block
*sb
= dentry
->d_sb
;
4012 atomic_inc(&sb
->s_active
);
4014 deactivate_super(sb
);
4017 static void init_cgroup_css(struct cgroup_subsys_state
*css
,
4018 struct cgroup_subsys
*ss
,
4019 struct cgroup
*cgrp
)
4022 atomic_set(&css
->refcnt
, 1);
4025 if (cgrp
== dummytop
)
4026 css
->flags
|= CSS_ROOT
;
4027 BUG_ON(cgrp
->subsys
[ss
->subsys_id
]);
4028 cgrp
->subsys
[ss
->subsys_id
] = css
;
4031 * css holds an extra ref to @cgrp->dentry which is put on the last
4032 * css_put(). dput() requires process context, which css_put() may
4033 * be called without. @css->dput_work will be used to invoke
4034 * dput() asynchronously from css_put().
4036 INIT_WORK(&css
->dput_work
, css_dput_fn
);
4039 /* invoke ->post_create() on a new CSS and mark it online if successful */
4040 static int online_css(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
4044 lockdep_assert_held(&cgroup_mutex
);
4047 ret
= ss
->css_online(cgrp
);
4049 cgrp
->subsys
[ss
->subsys_id
]->flags
|= CSS_ONLINE
;
4053 /* if the CSS is online, invoke ->pre_destory() on it and mark it offline */
4054 static void offline_css(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
4055 __releases(&cgroup_mutex
) __acquires(&cgroup_mutex
)
4057 struct cgroup_subsys_state
*css
= cgrp
->subsys
[ss
->subsys_id
];
4059 lockdep_assert_held(&cgroup_mutex
);
4061 if (!(css
->flags
& CSS_ONLINE
))
4064 if (ss
->css_offline
)
4065 ss
->css_offline(cgrp
);
4067 cgrp
->subsys
[ss
->subsys_id
]->flags
&= ~CSS_ONLINE
;
4071 * cgroup_create - create a cgroup
4072 * @parent: cgroup that will be parent of the new cgroup
4073 * @dentry: dentry of the new cgroup
4074 * @mode: mode to set on new inode
4076 * Must be called with the mutex on the parent inode held
4078 static long cgroup_create(struct cgroup
*parent
, struct dentry
*dentry
,
4081 struct cgroup
*cgrp
;
4082 struct cgroup_name
*name
;
4083 struct cgroupfs_root
*root
= parent
->root
;
4085 struct cgroup_subsys
*ss
;
4086 struct super_block
*sb
= root
->sb
;
4088 /* allocate the cgroup and its ID, 0 is reserved for the root */
4089 cgrp
= kzalloc(sizeof(*cgrp
), GFP_KERNEL
);
4093 name
= cgroup_alloc_name(dentry
);
4096 rcu_assign_pointer(cgrp
->name
, name
);
4098 cgrp
->id
= ida_simple_get(&root
->cgroup_ida
, 1, 0, GFP_KERNEL
);
4103 * Only live parents can have children. Note that the liveliness
4104 * check isn't strictly necessary because cgroup_mkdir() and
4105 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4106 * anyway so that locking is contained inside cgroup proper and we
4107 * don't get nasty surprises if we ever grow another caller.
4109 if (!cgroup_lock_live_group(parent
)) {
4114 /* Grab a reference on the superblock so the hierarchy doesn't
4115 * get deleted on unmount if there are child cgroups. This
4116 * can be done outside cgroup_mutex, since the sb can't
4117 * disappear while someone has an open control file on the
4119 atomic_inc(&sb
->s_active
);
4121 init_cgroup_housekeeping(cgrp
);
4123 dentry
->d_fsdata
= cgrp
;
4124 cgrp
->dentry
= dentry
;
4126 cgrp
->parent
= parent
;
4127 cgrp
->root
= parent
->root
;
4128 cgrp
->top_cgroup
= parent
->top_cgroup
;
4130 if (notify_on_release(parent
))
4131 set_bit(CGRP_NOTIFY_ON_RELEASE
, &cgrp
->flags
);
4133 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN
, &parent
->flags
))
4134 set_bit(CGRP_CPUSET_CLONE_CHILDREN
, &cgrp
->flags
);
4136 for_each_subsys(root
, ss
) {
4137 struct cgroup_subsys_state
*css
;
4139 css
= ss
->css_alloc(cgrp
);
4144 init_cgroup_css(css
, ss
, cgrp
);
4146 err
= alloc_css_id(ss
, parent
, cgrp
);
4153 * Create directory. cgroup_create_file() returns with the new
4154 * directory locked on success so that it can be populated without
4155 * dropping cgroup_mutex.
4157 err
= cgroup_create_file(dentry
, S_IFDIR
| mode
, sb
);
4160 lockdep_assert_held(&dentry
->d_inode
->i_mutex
);
4162 /* allocation complete, commit to creation */
4163 list_add_tail(&cgrp
->allcg_node
, &root
->allcg_list
);
4164 list_add_tail_rcu(&cgrp
->sibling
, &cgrp
->parent
->children
);
4165 root
->number_of_cgroups
++;
4167 /* each css holds a ref to the cgroup's dentry */
4168 for_each_subsys(root
, ss
)
4171 /* creation succeeded, notify subsystems */
4172 for_each_subsys(root
, ss
) {
4173 err
= online_css(ss
, cgrp
);
4177 if (ss
->broken_hierarchy
&& !ss
->warned_broken_hierarchy
&&
4179 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",
4180 current
->comm
, current
->pid
, ss
->name
);
4181 if (!strcmp(ss
->name
, "memory"))
4182 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4183 ss
->warned_broken_hierarchy
= true;
4187 err
= cgroup_populate_dir(cgrp
, true, root
->subsys_mask
);
4191 mutex_unlock(&cgroup_mutex
);
4192 mutex_unlock(&cgrp
->dentry
->d_inode
->i_mutex
);
4197 for_each_subsys(root
, ss
) {
4198 if (cgrp
->subsys
[ss
->subsys_id
])
4201 mutex_unlock(&cgroup_mutex
);
4202 /* Release the reference count that we took on the superblock */
4203 deactivate_super(sb
);
4205 ida_simple_remove(&root
->cgroup_ida
, cgrp
->id
);
4207 kfree(rcu_dereference_raw(cgrp
->name
));
4213 cgroup_destroy_locked(cgrp
);
4214 mutex_unlock(&cgroup_mutex
);
4215 mutex_unlock(&dentry
->d_inode
->i_mutex
);
4219 static int cgroup_mkdir(struct inode
*dir
, struct dentry
*dentry
, umode_t mode
)
4221 struct cgroup
*c_parent
= dentry
->d_parent
->d_fsdata
;
4223 /* the vfs holds inode->i_mutex already */
4224 return cgroup_create(c_parent
, dentry
, mode
| S_IFDIR
);
4227 static int cgroup_destroy_locked(struct cgroup
*cgrp
)
4228 __releases(&cgroup_mutex
) __acquires(&cgroup_mutex
)
4230 struct dentry
*d
= cgrp
->dentry
;
4231 struct cgroup
*parent
= cgrp
->parent
;
4232 struct cgroup_event
*event
, *tmp
;
4233 struct cgroup_subsys
*ss
;
4235 lockdep_assert_held(&d
->d_inode
->i_mutex
);
4236 lockdep_assert_held(&cgroup_mutex
);
4238 if (atomic_read(&cgrp
->count
) || !list_empty(&cgrp
->children
))
4242 * Block new css_tryget() by deactivating refcnt and mark @cgrp
4243 * removed. This makes future css_tryget() and child creation
4244 * attempts fail thus maintaining the removal conditions verified
4247 for_each_subsys(cgrp
->root
, ss
) {
4248 struct cgroup_subsys_state
*css
= cgrp
->subsys
[ss
->subsys_id
];
4250 WARN_ON(atomic_read(&css
->refcnt
) < 0);
4251 atomic_add(CSS_DEACT_BIAS
, &css
->refcnt
);
4253 set_bit(CGRP_REMOVED
, &cgrp
->flags
);
4255 /* tell subsystems to initate destruction */
4256 for_each_subsys(cgrp
->root
, ss
)
4257 offline_css(ss
, cgrp
);
4260 * Put all the base refs. Each css holds an extra reference to the
4261 * cgroup's dentry and cgroup removal proceeds regardless of css
4262 * refs. On the last put of each css, whenever that may be, the
4263 * extra dentry ref is put so that dentry destruction happens only
4264 * after all css's are released.
4266 for_each_subsys(cgrp
->root
, ss
)
4267 css_put(cgrp
->subsys
[ss
->subsys_id
]);
4269 raw_spin_lock(&release_list_lock
);
4270 if (!list_empty(&cgrp
->release_list
))
4271 list_del_init(&cgrp
->release_list
);
4272 raw_spin_unlock(&release_list_lock
);
4274 /* delete this cgroup from parent->children */
4275 list_del_rcu(&cgrp
->sibling
);
4276 list_del_init(&cgrp
->allcg_node
);
4279 cgroup_d_remove_dir(d
);
4282 set_bit(CGRP_RELEASABLE
, &parent
->flags
);
4283 check_for_release(parent
);
4286 * Unregister events and notify userspace.
4287 * Notify userspace about cgroup removing only after rmdir of cgroup
4288 * directory to avoid race between userspace and kernelspace.
4290 spin_lock(&cgrp
->event_list_lock
);
4291 list_for_each_entry_safe(event
, tmp
, &cgrp
->event_list
, list
) {
4292 list_del_init(&event
->list
);
4293 schedule_work(&event
->remove
);
4295 spin_unlock(&cgrp
->event_list_lock
);
4300 static int cgroup_rmdir(struct inode
*unused_dir
, struct dentry
*dentry
)
4304 mutex_lock(&cgroup_mutex
);
4305 ret
= cgroup_destroy_locked(dentry
->d_fsdata
);
4306 mutex_unlock(&cgroup_mutex
);
4311 static void __init_or_module
cgroup_init_cftsets(struct cgroup_subsys
*ss
)
4313 INIT_LIST_HEAD(&ss
->cftsets
);
4316 * base_cftset is embedded in subsys itself, no need to worry about
4319 if (ss
->base_cftypes
) {
4320 ss
->base_cftset
.cfts
= ss
->base_cftypes
;
4321 list_add_tail(&ss
->base_cftset
.node
, &ss
->cftsets
);
4325 static void __init
cgroup_init_subsys(struct cgroup_subsys
*ss
)
4327 struct cgroup_subsys_state
*css
;
4329 printk(KERN_INFO
"Initializing cgroup subsys %s\n", ss
->name
);
4331 mutex_lock(&cgroup_mutex
);
4333 /* init base cftset */
4334 cgroup_init_cftsets(ss
);
4336 /* Create the top cgroup state for this subsystem */
4337 list_add(&ss
->sibling
, &rootnode
.subsys_list
);
4338 ss
->root
= &rootnode
;
4339 css
= ss
->css_alloc(dummytop
);
4340 /* We don't handle early failures gracefully */
4341 BUG_ON(IS_ERR(css
));
4342 init_cgroup_css(css
, ss
, dummytop
);
4344 /* Update the init_css_set to contain a subsys
4345 * pointer to this state - since the subsystem is
4346 * newly registered, all tasks and hence the
4347 * init_css_set is in the subsystem's top cgroup. */
4348 init_css_set
.subsys
[ss
->subsys_id
] = css
;
4350 need_forkexit_callback
|= ss
->fork
|| ss
->exit
;
4352 /* At system boot, before all subsystems have been
4353 * registered, no tasks have been forked, so we don't
4354 * need to invoke fork callbacks here. */
4355 BUG_ON(!list_empty(&init_task
.tasks
));
4358 BUG_ON(online_css(ss
, dummytop
));
4360 mutex_unlock(&cgroup_mutex
);
4362 /* this function shouldn't be used with modular subsystems, since they
4363 * need to register a subsys_id, among other things */
4368 * cgroup_load_subsys: load and register a modular subsystem at runtime
4369 * @ss: the subsystem to load
4371 * This function should be called in a modular subsystem's initcall. If the
4372 * subsystem is built as a module, it will be assigned a new subsys_id and set
4373 * up for use. If the subsystem is built-in anyway, work is delegated to the
4374 * simpler cgroup_init_subsys.
4376 int __init_or_module
cgroup_load_subsys(struct cgroup_subsys
*ss
)
4378 struct cgroup_subsys_state
*css
;
4380 struct hlist_node
*tmp
;
4384 /* check name and function validity */
4385 if (ss
->name
== NULL
|| strlen(ss
->name
) > MAX_CGROUP_TYPE_NAMELEN
||
4386 ss
->css_alloc
== NULL
|| ss
->css_free
== NULL
)
4390 * we don't support callbacks in modular subsystems. this check is
4391 * before the ss->module check for consistency; a subsystem that could
4392 * be a module should still have no callbacks even if the user isn't
4393 * compiling it as one.
4395 if (ss
->fork
|| ss
->exit
)
4399 * an optionally modular subsystem is built-in: we want to do nothing,
4400 * since cgroup_init_subsys will have already taken care of it.
4402 if (ss
->module
== NULL
) {
4403 /* a sanity check */
4404 BUG_ON(subsys
[ss
->subsys_id
] != ss
);
4408 /* init base cftset */
4409 cgroup_init_cftsets(ss
);
4411 mutex_lock(&cgroup_mutex
);
4412 subsys
[ss
->subsys_id
] = ss
;
4415 * no ss->css_alloc seems to need anything important in the ss
4416 * struct, so this can happen first (i.e. before the rootnode
4419 css
= ss
->css_alloc(dummytop
);
4421 /* failure case - need to deassign the subsys[] slot. */
4422 subsys
[ss
->subsys_id
] = NULL
;
4423 mutex_unlock(&cgroup_mutex
);
4424 return PTR_ERR(css
);
4427 list_add(&ss
->sibling
, &rootnode
.subsys_list
);
4428 ss
->root
= &rootnode
;
4430 /* our new subsystem will be attached to the dummy hierarchy. */
4431 init_cgroup_css(css
, ss
, dummytop
);
4432 /* init_idr must be after init_cgroup_css because it sets css->id. */
4434 ret
= cgroup_init_idr(ss
, css
);
4440 * Now we need to entangle the css into the existing css_sets. unlike
4441 * in cgroup_init_subsys, there are now multiple css_sets, so each one
4442 * will need a new pointer to it; done by iterating the css_set_table.
4443 * furthermore, modifying the existing css_sets will corrupt the hash
4444 * table state, so each changed css_set will need its hash recomputed.
4445 * this is all done under the css_set_lock.
4447 write_lock(&css_set_lock
);
4448 hash_for_each_safe(css_set_table
, i
, tmp
, cg
, hlist
) {
4449 /* skip entries that we already rehashed */
4450 if (cg
->subsys
[ss
->subsys_id
])
4452 /* remove existing entry */
4453 hash_del(&cg
->hlist
);
4455 cg
->subsys
[ss
->subsys_id
] = css
;
4456 /* recompute hash and restore entry */
4457 key
= css_set_hash(cg
->subsys
);
4458 hash_add(css_set_table
, &cg
->hlist
, key
);
4460 write_unlock(&css_set_lock
);
4463 ret
= online_css(ss
, dummytop
);
4468 mutex_unlock(&cgroup_mutex
);
4472 mutex_unlock(&cgroup_mutex
);
4473 /* @ss can't be mounted here as try_module_get() would fail */
4474 cgroup_unload_subsys(ss
);
4477 EXPORT_SYMBOL_GPL(cgroup_load_subsys
);
4480 * cgroup_unload_subsys: unload a modular subsystem
4481 * @ss: the subsystem to unload
4483 * This function should be called in a modular subsystem's exitcall. When this
4484 * function is invoked, the refcount on the subsystem's module will be 0, so
4485 * the subsystem will not be attached to any hierarchy.
4487 void cgroup_unload_subsys(struct cgroup_subsys
*ss
)
4489 struct cg_cgroup_link
*link
;
4491 BUG_ON(ss
->module
== NULL
);
4494 * we shouldn't be called if the subsystem is in use, and the use of
4495 * try_module_get in parse_cgroupfs_options should ensure that it
4496 * doesn't start being used while we're killing it off.
4498 BUG_ON(ss
->root
!= &rootnode
);
4500 mutex_lock(&cgroup_mutex
);
4502 offline_css(ss
, dummytop
);
4506 idr_destroy(&ss
->idr
);
4508 /* deassign the subsys_id */
4509 subsys
[ss
->subsys_id
] = NULL
;
4511 /* remove subsystem from rootnode's list of subsystems */
4512 list_del_init(&ss
->sibling
);
4515 * disentangle the css from all css_sets attached to the dummytop. as
4516 * in loading, we need to pay our respects to the hashtable gods.
4518 write_lock(&css_set_lock
);
4519 list_for_each_entry(link
, &dummytop
->css_sets
, cgrp_link_list
) {
4520 struct css_set
*cg
= link
->cg
;
4523 hash_del(&cg
->hlist
);
4524 cg
->subsys
[ss
->subsys_id
] = NULL
;
4525 key
= css_set_hash(cg
->subsys
);
4526 hash_add(css_set_table
, &cg
->hlist
, key
);
4528 write_unlock(&css_set_lock
);
4531 * remove subsystem's css from the dummytop and free it - need to
4532 * free before marking as null because ss->css_free needs the
4533 * cgrp->subsys pointer to find their state. note that this also
4534 * takes care of freeing the css_id.
4536 ss
->css_free(dummytop
);
4537 dummytop
->subsys
[ss
->subsys_id
] = NULL
;
4539 mutex_unlock(&cgroup_mutex
);
4541 EXPORT_SYMBOL_GPL(cgroup_unload_subsys
);
4544 * cgroup_init_early - cgroup initialization at system boot
4546 * Initialize cgroups at system boot, and initialize any
4547 * subsystems that request early init.
4549 int __init
cgroup_init_early(void)
4552 atomic_set(&init_css_set
.refcount
, 1);
4553 INIT_LIST_HEAD(&init_css_set
.cg_links
);
4554 INIT_LIST_HEAD(&init_css_set
.tasks
);
4555 INIT_HLIST_NODE(&init_css_set
.hlist
);
4557 init_cgroup_root(&rootnode
);
4559 init_task
.cgroups
= &init_css_set
;
4561 init_css_set_link
.cg
= &init_css_set
;
4562 init_css_set_link
.cgrp
= dummytop
;
4563 list_add(&init_css_set_link
.cgrp_link_list
,
4564 &rootnode
.top_cgroup
.css_sets
);
4565 list_add(&init_css_set_link
.cg_link_list
,
4566 &init_css_set
.cg_links
);
4568 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++) {
4569 struct cgroup_subsys
*ss
= subsys
[i
];
4571 /* at bootup time, we don't worry about modular subsystems */
4572 if (!ss
|| ss
->module
)
4576 BUG_ON(strlen(ss
->name
) > MAX_CGROUP_TYPE_NAMELEN
);
4577 BUG_ON(!ss
->css_alloc
);
4578 BUG_ON(!ss
->css_free
);
4579 if (ss
->subsys_id
!= i
) {
4580 printk(KERN_ERR
"cgroup: Subsys %s id == %d\n",
4581 ss
->name
, ss
->subsys_id
);
4586 cgroup_init_subsys(ss
);
4592 * cgroup_init - cgroup initialization
4594 * Register cgroup filesystem and /proc file, and initialize
4595 * any subsystems that didn't request early init.
4597 int __init
cgroup_init(void)
4603 err
= bdi_init(&cgroup_backing_dev_info
);
4607 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++) {
4608 struct cgroup_subsys
*ss
= subsys
[i
];
4610 /* at bootup time, we don't worry about modular subsystems */
4611 if (!ss
|| ss
->module
)
4613 if (!ss
->early_init
)
4614 cgroup_init_subsys(ss
);
4616 cgroup_init_idr(ss
, init_css_set
.subsys
[ss
->subsys_id
]);
4619 /* Add init_css_set to the hash table */
4620 key
= css_set_hash(init_css_set
.subsys
);
4621 hash_add(css_set_table
, &init_css_set
.hlist
, key
);
4622 BUG_ON(!init_root_id(&rootnode
));
4624 cgroup_kobj
= kobject_create_and_add("cgroup", fs_kobj
);
4630 err
= register_filesystem(&cgroup_fs_type
);
4632 kobject_put(cgroup_kobj
);
4636 proc_create("cgroups", 0, NULL
, &proc_cgroupstats_operations
);
4640 bdi_destroy(&cgroup_backing_dev_info
);
4646 * proc_cgroup_show()
4647 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4648 * - Used for /proc/<pid>/cgroup.
4649 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4650 * doesn't really matter if tsk->cgroup changes after we read it,
4651 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4652 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4653 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4654 * cgroup to top_cgroup.
4657 /* TODO: Use a proper seq_file iterator */
4658 static int proc_cgroup_show(struct seq_file
*m
, void *v
)
4661 struct task_struct
*tsk
;
4664 struct cgroupfs_root
*root
;
4667 buf
= kmalloc(PAGE_SIZE
, GFP_KERNEL
);
4673 tsk
= get_pid_task(pid
, PIDTYPE_PID
);
4679 mutex_lock(&cgroup_mutex
);
4681 for_each_active_root(root
) {
4682 struct cgroup_subsys
*ss
;
4683 struct cgroup
*cgrp
;
4686 seq_printf(m
, "%d:", root
->hierarchy_id
);
4687 for_each_subsys(root
, ss
)
4688 seq_printf(m
, "%s%s", count
++ ? "," : "", ss
->name
);
4689 if (strlen(root
->name
))
4690 seq_printf(m
, "%sname=%s", count
? "," : "",
4693 cgrp
= task_cgroup_from_root(tsk
, root
);
4694 retval
= cgroup_path(cgrp
, buf
, PAGE_SIZE
);
4702 mutex_unlock(&cgroup_mutex
);
4703 put_task_struct(tsk
);
4710 static int cgroup_open(struct inode
*inode
, struct file
*file
)
4712 struct pid
*pid
= PROC_I(inode
)->pid
;
4713 return single_open(file
, proc_cgroup_show
, pid
);
4716 const struct file_operations proc_cgroup_operations
= {
4717 .open
= cgroup_open
,
4719 .llseek
= seq_lseek
,
4720 .release
= single_release
,
4723 /* Display information about each subsystem and each hierarchy */
4724 static int proc_cgroupstats_show(struct seq_file
*m
, void *v
)
4728 seq_puts(m
, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4730 * ideally we don't want subsystems moving around while we do this.
4731 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4732 * subsys/hierarchy state.
4734 mutex_lock(&cgroup_mutex
);
4735 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++) {
4736 struct cgroup_subsys
*ss
= subsys
[i
];
4739 seq_printf(m
, "%s\t%d\t%d\t%d\n",
4740 ss
->name
, ss
->root
->hierarchy_id
,
4741 ss
->root
->number_of_cgroups
, !ss
->disabled
);
4743 mutex_unlock(&cgroup_mutex
);
4747 static int cgroupstats_open(struct inode
*inode
, struct file
*file
)
4749 return single_open(file
, proc_cgroupstats_show
, NULL
);
4752 static const struct file_operations proc_cgroupstats_operations
= {
4753 .open
= cgroupstats_open
,
4755 .llseek
= seq_lseek
,
4756 .release
= single_release
,
4760 * cgroup_fork - attach newly forked task to its parents cgroup.
4761 * @child: pointer to task_struct of forking parent process.
4763 * Description: A task inherits its parent's cgroup at fork().
4765 * A pointer to the shared css_set was automatically copied in
4766 * fork.c by dup_task_struct(). However, we ignore that copy, since
4767 * it was not made under the protection of RCU or cgroup_mutex, so
4768 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
4769 * have already changed current->cgroups, allowing the previously
4770 * referenced cgroup group to be removed and freed.
4772 * At the point that cgroup_fork() is called, 'current' is the parent
4773 * task, and the passed argument 'child' points to the child task.
4775 void cgroup_fork(struct task_struct
*child
)
4778 child
->cgroups
= current
->cgroups
;
4779 get_css_set(child
->cgroups
);
4780 task_unlock(current
);
4781 INIT_LIST_HEAD(&child
->cg_list
);
4785 * cgroup_post_fork - called on a new task after adding it to the task list
4786 * @child: the task in question
4788 * Adds the task to the list running through its css_set if necessary and
4789 * call the subsystem fork() callbacks. Has to be after the task is
4790 * visible on the task list in case we race with the first call to
4791 * cgroup_iter_start() - to guarantee that the new task ends up on its
4794 void cgroup_post_fork(struct task_struct
*child
)
4799 * use_task_css_set_links is set to 1 before we walk the tasklist
4800 * under the tasklist_lock and we read it here after we added the child
4801 * to the tasklist under the tasklist_lock as well. If the child wasn't
4802 * yet in the tasklist when we walked through it from
4803 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4804 * should be visible now due to the paired locking and barriers implied
4805 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4806 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4809 if (use_task_css_set_links
) {
4810 write_lock(&css_set_lock
);
4812 if (list_empty(&child
->cg_list
))
4813 list_add(&child
->cg_list
, &child
->cgroups
->tasks
);
4815 write_unlock(&css_set_lock
);
4819 * Call ss->fork(). This must happen after @child is linked on
4820 * css_set; otherwise, @child might change state between ->fork()
4821 * and addition to css_set.
4823 if (need_forkexit_callback
) {
4825 * fork/exit callbacks are supported only for builtin
4826 * subsystems, and the builtin section of the subsys
4827 * array is immutable, so we don't need to lock the
4828 * subsys array here. On the other hand, modular section
4829 * of the array can be freed at module unload, so we
4832 for (i
= 0; i
< CGROUP_BUILTIN_SUBSYS_COUNT
; i
++) {
4833 struct cgroup_subsys
*ss
= subsys
[i
];
4842 * cgroup_exit - detach cgroup from exiting task
4843 * @tsk: pointer to task_struct of exiting process
4844 * @run_callback: run exit callbacks?
4846 * Description: Detach cgroup from @tsk and release it.
4848 * Note that cgroups marked notify_on_release force every task in
4849 * them to take the global cgroup_mutex mutex when exiting.
4850 * This could impact scaling on very large systems. Be reluctant to
4851 * use notify_on_release cgroups where very high task exit scaling
4852 * is required on large systems.
4854 * the_top_cgroup_hack:
4856 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
4858 * We call cgroup_exit() while the task is still competent to
4859 * handle notify_on_release(), then leave the task attached to the
4860 * root cgroup in each hierarchy for the remainder of its exit.
4862 * To do this properly, we would increment the reference count on
4863 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
4864 * code we would add a second cgroup function call, to drop that
4865 * reference. This would just create an unnecessary hot spot on
4866 * the top_cgroup reference count, to no avail.
4868 * Normally, holding a reference to a cgroup without bumping its
4869 * count is unsafe. The cgroup could go away, or someone could
4870 * attach us to a different cgroup, decrementing the count on
4871 * the first cgroup that we never incremented. But in this case,
4872 * top_cgroup isn't going away, and either task has PF_EXITING set,
4873 * which wards off any cgroup_attach_task() attempts, or task is a failed
4874 * fork, never visible to cgroup_attach_task.
4876 void cgroup_exit(struct task_struct
*tsk
, int run_callbacks
)
4882 * Unlink from the css_set task list if necessary.
4883 * Optimistically check cg_list before taking
4886 if (!list_empty(&tsk
->cg_list
)) {
4887 write_lock(&css_set_lock
);
4888 if (!list_empty(&tsk
->cg_list
))
4889 list_del_init(&tsk
->cg_list
);
4890 write_unlock(&css_set_lock
);
4893 /* Reassign the task to the init_css_set. */
4896 tsk
->cgroups
= &init_css_set
;
4898 if (run_callbacks
&& need_forkexit_callback
) {
4900 * fork/exit callbacks are supported only for builtin
4901 * subsystems, see cgroup_post_fork() for details.
4903 for (i
= 0; i
< CGROUP_BUILTIN_SUBSYS_COUNT
; i
++) {
4904 struct cgroup_subsys
*ss
= subsys
[i
];
4907 struct cgroup
*old_cgrp
=
4908 rcu_dereference_raw(cg
->subsys
[i
])->cgroup
;
4909 struct cgroup
*cgrp
= task_cgroup(tsk
, i
);
4910 ss
->exit(cgrp
, old_cgrp
, tsk
);
4916 put_css_set_taskexit(cg
);
4919 static void check_for_release(struct cgroup
*cgrp
)
4921 /* All of these checks rely on RCU to keep the cgroup
4922 * structure alive */
4923 if (cgroup_is_releasable(cgrp
) &&
4924 !atomic_read(&cgrp
->count
) && list_empty(&cgrp
->children
)) {
4926 * Control Group is currently removeable. If it's not
4927 * already queued for a userspace notification, queue
4930 int need_schedule_work
= 0;
4932 raw_spin_lock(&release_list_lock
);
4933 if (!cgroup_is_removed(cgrp
) &&
4934 list_empty(&cgrp
->release_list
)) {
4935 list_add(&cgrp
->release_list
, &release_list
);
4936 need_schedule_work
= 1;
4938 raw_spin_unlock(&release_list_lock
);
4939 if (need_schedule_work
)
4940 schedule_work(&release_agent_work
);
4944 /* Caller must verify that the css is not for root cgroup */
4945 bool __css_tryget(struct cgroup_subsys_state
*css
)
4950 v
= css_refcnt(css
);
4951 t
= atomic_cmpxchg(&css
->refcnt
, v
, v
+ 1);
4959 EXPORT_SYMBOL_GPL(__css_tryget
);
4961 /* Caller must verify that the css is not for root cgroup */
4962 void __css_put(struct cgroup_subsys_state
*css
)
4966 v
= css_unbias_refcnt(atomic_dec_return(&css
->refcnt
));
4968 schedule_work(&css
->dput_work
);
4970 EXPORT_SYMBOL_GPL(__css_put
);
4973 * Notify userspace when a cgroup is released, by running the
4974 * configured release agent with the name of the cgroup (path
4975 * relative to the root of cgroup file system) as the argument.
4977 * Most likely, this user command will try to rmdir this cgroup.
4979 * This races with the possibility that some other task will be
4980 * attached to this cgroup before it is removed, or that some other
4981 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
4982 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
4983 * unused, and this cgroup will be reprieved from its death sentence,
4984 * to continue to serve a useful existence. Next time it's released,
4985 * we will get notified again, if it still has 'notify_on_release' set.
4987 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
4988 * means only wait until the task is successfully execve()'d. The
4989 * separate release agent task is forked by call_usermodehelper(),
4990 * then control in this thread returns here, without waiting for the
4991 * release agent task. We don't bother to wait because the caller of
4992 * this routine has no use for the exit status of the release agent
4993 * task, so no sense holding our caller up for that.
4995 static void cgroup_release_agent(struct work_struct
*work
)
4997 BUG_ON(work
!= &release_agent_work
);
4998 mutex_lock(&cgroup_mutex
);
4999 raw_spin_lock(&release_list_lock
);
5000 while (!list_empty(&release_list
)) {
5001 char *argv
[3], *envp
[3];
5003 char *pathbuf
= NULL
, *agentbuf
= NULL
;
5004 struct cgroup
*cgrp
= list_entry(release_list
.next
,
5007 list_del_init(&cgrp
->release_list
);
5008 raw_spin_unlock(&release_list_lock
);
5009 pathbuf
= kmalloc(PAGE_SIZE
, GFP_KERNEL
);
5012 if (cgroup_path(cgrp
, pathbuf
, PAGE_SIZE
) < 0)
5014 agentbuf
= kstrdup(cgrp
->root
->release_agent_path
, GFP_KERNEL
);
5019 argv
[i
++] = agentbuf
;
5020 argv
[i
++] = pathbuf
;
5024 /* minimal command environment */
5025 envp
[i
++] = "HOME=/";
5026 envp
[i
++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5029 /* Drop the lock while we invoke the usermode helper,
5030 * since the exec could involve hitting disk and hence
5031 * be a slow process */
5032 mutex_unlock(&cgroup_mutex
);
5033 call_usermodehelper(argv
[0], argv
, envp
, UMH_WAIT_EXEC
);
5034 mutex_lock(&cgroup_mutex
);
5038 raw_spin_lock(&release_list_lock
);
5040 raw_spin_unlock(&release_list_lock
);
5041 mutex_unlock(&cgroup_mutex
);
5044 static int __init
cgroup_disable(char *str
)
5049 while ((token
= strsep(&str
, ",")) != NULL
) {
5052 for (i
= 0; i
< CGROUP_SUBSYS_COUNT
; i
++) {
5053 struct cgroup_subsys
*ss
= subsys
[i
];
5056 * cgroup_disable, being at boot time, can't
5057 * know about module subsystems, so we don't
5060 if (!ss
|| ss
->module
)
5063 if (!strcmp(token
, ss
->name
)) {
5065 printk(KERN_INFO
"Disabling %s control group"
5066 " subsystem\n", ss
->name
);
5073 __setup("cgroup_disable=", cgroup_disable
);
5076 * Functons for CSS ID.
5080 *To get ID other than 0, this should be called when !cgroup_is_removed().
5082 unsigned short css_id(struct cgroup_subsys_state
*css
)
5084 struct css_id
*cssid
;
5087 * This css_id() can return correct value when somone has refcnt
5088 * on this or this is under rcu_read_lock(). Once css->id is allocated,
5089 * it's unchanged until freed.
5091 cssid
= rcu_dereference_check(css
->id
, css_refcnt(css
));
5097 EXPORT_SYMBOL_GPL(css_id
);
5099 unsigned short css_depth(struct cgroup_subsys_state
*css
)
5101 struct css_id
*cssid
;
5103 cssid
= rcu_dereference_check(css
->id
, css_refcnt(css
));
5106 return cssid
->depth
;
5109 EXPORT_SYMBOL_GPL(css_depth
);
5112 * css_is_ancestor - test "root" css is an ancestor of "child"
5113 * @child: the css to be tested.
5114 * @root: the css supporsed to be an ancestor of the child.
5116 * Returns true if "root" is an ancestor of "child" in its hierarchy. Because
5117 * this function reads css->id, the caller must hold rcu_read_lock().
5118 * But, considering usual usage, the csses should be valid objects after test.
5119 * Assuming that the caller will do some action to the child if this returns
5120 * returns true, the caller must take "child";s reference count.
5121 * If "child" is valid object and this returns true, "root" is valid, too.
5124 bool css_is_ancestor(struct cgroup_subsys_state
*child
,
5125 const struct cgroup_subsys_state
*root
)
5127 struct css_id
*child_id
;
5128 struct css_id
*root_id
;
5130 child_id
= rcu_dereference(child
->id
);
5133 root_id
= rcu_dereference(root
->id
);
5136 if (child_id
->depth
< root_id
->depth
)
5138 if (child_id
->stack
[root_id
->depth
] != root_id
->id
)
5143 void free_css_id(struct cgroup_subsys
*ss
, struct cgroup_subsys_state
*css
)
5145 struct css_id
*id
= css
->id
;
5146 /* When this is called before css_id initialization, id can be NULL */
5150 BUG_ON(!ss
->use_id
);
5152 rcu_assign_pointer(id
->css
, NULL
);
5153 rcu_assign_pointer(css
->id
, NULL
);
5154 spin_lock(&ss
->id_lock
);
5155 idr_remove(&ss
->idr
, id
->id
);
5156 spin_unlock(&ss
->id_lock
);
5157 kfree_rcu(id
, rcu_head
);
5159 EXPORT_SYMBOL_GPL(free_css_id
);
5162 * This is called by init or create(). Then, calls to this function are
5163 * always serialized (By cgroup_mutex() at create()).
5166 static struct css_id
*get_new_cssid(struct cgroup_subsys
*ss
, int depth
)
5168 struct css_id
*newid
;
5171 BUG_ON(!ss
->use_id
);
5173 size
= sizeof(*newid
) + sizeof(unsigned short) * (depth
+ 1);
5174 newid
= kzalloc(size
, GFP_KERNEL
);
5176 return ERR_PTR(-ENOMEM
);
5178 idr_preload(GFP_KERNEL
);
5179 spin_lock(&ss
->id_lock
);
5180 /* Don't use 0. allocates an ID of 1-65535 */
5181 ret
= idr_alloc(&ss
->idr
, newid
, 1, CSS_ID_MAX
+ 1, GFP_NOWAIT
);
5182 spin_unlock(&ss
->id_lock
);
5185 /* Returns error when there are no free spaces for new ID.*/
5190 newid
->depth
= depth
;
5194 return ERR_PTR(ret
);
5198 static int __init_or_module
cgroup_init_idr(struct cgroup_subsys
*ss
,
5199 struct cgroup_subsys_state
*rootcss
)
5201 struct css_id
*newid
;
5203 spin_lock_init(&ss
->id_lock
);
5206 newid
= get_new_cssid(ss
, 0);
5208 return PTR_ERR(newid
);
5210 newid
->stack
[0] = newid
->id
;
5211 newid
->css
= rootcss
;
5212 rootcss
->id
= newid
;
5216 static int alloc_css_id(struct cgroup_subsys
*ss
, struct cgroup
*parent
,
5217 struct cgroup
*child
)
5219 int subsys_id
, i
, depth
= 0;
5220 struct cgroup_subsys_state
*parent_css
, *child_css
;
5221 struct css_id
*child_id
, *parent_id
;
5223 subsys_id
= ss
->subsys_id
;
5224 parent_css
= parent
->subsys
[subsys_id
];
5225 child_css
= child
->subsys
[subsys_id
];
5226 parent_id
= parent_css
->id
;
5227 depth
= parent_id
->depth
+ 1;
5229 child_id
= get_new_cssid(ss
, depth
);
5230 if (IS_ERR(child_id
))
5231 return PTR_ERR(child_id
);
5233 for (i
= 0; i
< depth
; i
++)
5234 child_id
->stack
[i
] = parent_id
->stack
[i
];
5235 child_id
->stack
[depth
] = child_id
->id
;
5237 * child_id->css pointer will be set after this cgroup is available
5238 * see cgroup_populate_dir()
5240 rcu_assign_pointer(child_css
->id
, child_id
);
5246 * css_lookup - lookup css by id
5247 * @ss: cgroup subsys to be looked into.
5250 * Returns pointer to cgroup_subsys_state if there is valid one with id.
5251 * NULL if not. Should be called under rcu_read_lock()
5253 struct cgroup_subsys_state
*css_lookup(struct cgroup_subsys
*ss
, int id
)
5255 struct css_id
*cssid
= NULL
;
5257 BUG_ON(!ss
->use_id
);
5258 cssid
= idr_find(&ss
->idr
, id
);
5260 if (unlikely(!cssid
))
5263 return rcu_dereference(cssid
->css
);
5265 EXPORT_SYMBOL_GPL(css_lookup
);
5268 * css_get_next - lookup next cgroup under specified hierarchy.
5269 * @ss: pointer to subsystem
5270 * @id: current position of iteration.
5271 * @root: pointer to css. search tree under this.
5272 * @foundid: position of found object.
5274 * Search next css under the specified hierarchy of rootid. Calling under
5275 * rcu_read_lock() is necessary. Returns NULL if it reaches the end.
5277 struct cgroup_subsys_state
*
5278 css_get_next(struct cgroup_subsys
*ss
, int id
,
5279 struct cgroup_subsys_state
*root
, int *foundid
)
5281 struct cgroup_subsys_state
*ret
= NULL
;
5284 int rootid
= css_id(root
);
5285 int depth
= css_depth(root
);
5290 BUG_ON(!ss
->use_id
);
5291 WARN_ON_ONCE(!rcu_read_lock_held());
5293 /* fill start point for scan */
5297 * scan next entry from bitmap(tree), tmpid is updated after
5300 tmp
= idr_get_next(&ss
->idr
, &tmpid
);
5303 if (tmp
->depth
>= depth
&& tmp
->stack
[depth
] == rootid
) {
5304 ret
= rcu_dereference(tmp
->css
);
5310 /* continue to scan from next id */
5317 * get corresponding css from file open on cgroupfs directory
5319 struct cgroup_subsys_state
*cgroup_css_from_dir(struct file
*f
, int id
)
5321 struct cgroup
*cgrp
;
5322 struct inode
*inode
;
5323 struct cgroup_subsys_state
*css
;
5325 inode
= file_inode(f
);
5326 /* check in cgroup filesystem dir */
5327 if (inode
->i_op
!= &cgroup_dir_inode_operations
)
5328 return ERR_PTR(-EBADF
);
5330 if (id
< 0 || id
>= CGROUP_SUBSYS_COUNT
)
5331 return ERR_PTR(-EINVAL
);
5334 cgrp
= __d_cgrp(f
->f_dentry
);
5335 css
= cgrp
->subsys
[id
];
5336 return css
? css
: ERR_PTR(-ENOENT
);
5339 #ifdef CONFIG_CGROUP_DEBUG
5340 static struct cgroup_subsys_state
*debug_css_alloc(struct cgroup
*cont
)
5342 struct cgroup_subsys_state
*css
= kzalloc(sizeof(*css
), GFP_KERNEL
);
5345 return ERR_PTR(-ENOMEM
);
5350 static void debug_css_free(struct cgroup
*cont
)
5352 kfree(cont
->subsys
[debug_subsys_id
]);
5355 static u64
cgroup_refcount_read(struct cgroup
*cont
, struct cftype
*cft
)
5357 return atomic_read(&cont
->count
);
5360 static u64
debug_taskcount_read(struct cgroup
*cont
, struct cftype
*cft
)
5362 return cgroup_task_count(cont
);
5365 static u64
current_css_set_read(struct cgroup
*cont
, struct cftype
*cft
)
5367 return (u64
)(unsigned long)current
->cgroups
;
5370 static u64
current_css_set_refcount_read(struct cgroup
*cont
,
5376 count
= atomic_read(¤t
->cgroups
->refcount
);
5381 static int current_css_set_cg_links_read(struct cgroup
*cont
,
5383 struct seq_file
*seq
)
5385 struct cg_cgroup_link
*link
;
5388 read_lock(&css_set_lock
);
5390 cg
= rcu_dereference(current
->cgroups
);
5391 list_for_each_entry(link
, &cg
->cg_links
, cg_link_list
) {
5392 struct cgroup
*c
= link
->cgrp
;
5396 name
= c
->dentry
->d_name
.name
;
5399 seq_printf(seq
, "Root %d group %s\n",
5400 c
->root
->hierarchy_id
, name
);
5403 read_unlock(&css_set_lock
);
5407 #define MAX_TASKS_SHOWN_PER_CSS 25
5408 static int cgroup_css_links_read(struct cgroup
*cont
,
5410 struct seq_file
*seq
)
5412 struct cg_cgroup_link
*link
;
5414 read_lock(&css_set_lock
);
5415 list_for_each_entry(link
, &cont
->css_sets
, cgrp_link_list
) {
5416 struct css_set
*cg
= link
->cg
;
5417 struct task_struct
*task
;
5419 seq_printf(seq
, "css_set %p\n", cg
);
5420 list_for_each_entry(task
, &cg
->tasks
, cg_list
) {
5421 if (count
++ > MAX_TASKS_SHOWN_PER_CSS
) {
5422 seq_puts(seq
, " ...\n");
5425 seq_printf(seq
, " task %d\n",
5426 task_pid_vnr(task
));
5430 read_unlock(&css_set_lock
);
5434 static u64
releasable_read(struct cgroup
*cgrp
, struct cftype
*cft
)
5436 return test_bit(CGRP_RELEASABLE
, &cgrp
->flags
);
5439 static struct cftype debug_files
[] = {
5441 .name
= "cgroup_refcount",
5442 .read_u64
= cgroup_refcount_read
,
5445 .name
= "taskcount",
5446 .read_u64
= debug_taskcount_read
,
5450 .name
= "current_css_set",
5451 .read_u64
= current_css_set_read
,
5455 .name
= "current_css_set_refcount",
5456 .read_u64
= current_css_set_refcount_read
,
5460 .name
= "current_css_set_cg_links",
5461 .read_seq_string
= current_css_set_cg_links_read
,
5465 .name
= "cgroup_css_links",
5466 .read_seq_string
= cgroup_css_links_read
,
5470 .name
= "releasable",
5471 .read_u64
= releasable_read
,
5477 struct cgroup_subsys debug_subsys
= {
5479 .css_alloc
= debug_css_alloc
,
5480 .css_free
= debug_css_free
,
5481 .subsys_id
= debug_subsys_id
,
5482 .base_cftypes
= debug_files
,
5484 #endif /* CONFIG_CGROUP_DEBUG */