cddf1d9983812b2b4af28d7f87ab71105ef0e27d
1 /*
2 * Generic process-grouping system.
3 *
4 * Based originally on the cpuset system, extracted by Paul Menage
5 * Copyright (C) 2006 Google, Inc
6 *
7 * Notifications support
8 * Copyright (C) 2009 Nokia Corporation
9 * Author: Kirill A. Shutemov
10 *
11 * Copyright notices from the original cpuset code:
12 * --------------------------------------------------
13 * Copyright (C) 2003 BULL SA.
14 * Copyright (C) 2004-2006 Silicon Graphics, Inc.
15 *
16 * Portions derived from Patrick Mochel's sysfs code.
17 * sysfs is Copyright (c) 2001-3 Patrick Mochel
18 *
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 * ---------------------------------------------------
23 *
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.
27 */
29 #include <linux/cgroup.h>
30 #include <linux/cred.h>
31 #include <linux/ctype.h>
32 #include <linux/errno.h>
33 #include <linux/fs.h>
34 #include <linux/init_task.h>
35 #include <linux/kernel.h>
36 #include <linux/list.h>
37 #include <linux/mm.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/hash.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_proc */
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
70 /*
71 * cgroup_mutex is the master lock. Any modification to cgroup or its
72 * hierarchy must be performed while holding it.
73 *
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.
79 *
80 * A. cgroup_mutex -> cred_guard_mutex -> s_type->i_mutex_key -> namespace_sem
81 * B. namespace_sem -> cgroup_mutex
82 *
83 * B happens only through cgroup_show_options() and using cgroup_root_mutex
84 * breaks it.
85 */
86 static DEFINE_MUTEX(cgroup_mutex);
87 static DEFINE_MUTEX(cgroup_root_mutex);
89 /*
90 * Generate an array of cgroup subsystem pointers. At boot time, this is
91 * populated with the built in subsystems, and modular subsystems are
92 * registered after that. The mutable section of this array is protected by
93 * cgroup_mutex.
94 */
95 #define SUBSYS(_x) [_x ## _subsys_id] = &_x ## _subsys,
96 #define IS_SUBSYS_ENABLED(option) IS_BUILTIN(option)
97 static struct cgroup_subsys *subsys[CGROUP_SUBSYS_COUNT] = {
98 #include <linux/cgroup_subsys.h>
99 };
101 #define MAX_CGROUP_ROOT_NAMELEN 64
103 /*
104 * A cgroupfs_root represents the root of a cgroup hierarchy,
105 * and may be associated with a superblock to form an active
106 * hierarchy
107 */
108 struct cgroupfs_root {
109 struct super_block *sb;
111 /*
112 * The bitmask of subsystems intended to be attached to this
113 * hierarchy
114 */
115 unsigned long subsys_mask;
117 /* Unique id for this hierarchy. */
118 int hierarchy_id;
120 /* The bitmask of subsystems currently attached to this hierarchy */
121 unsigned long actual_subsys_mask;
123 /* A list running through the attached subsystems */
124 struct list_head subsys_list;
126 /* The root cgroup for this hierarchy */
127 struct cgroup top_cgroup;
129 /* Tracks how many cgroups are currently defined in hierarchy.*/
130 int number_of_cgroups;
132 /* A list running through the active hierarchies */
133 struct list_head root_list;
135 /* All cgroups on this root, cgroup_mutex protected */
136 struct list_head allcg_list;
138 /* Hierarchy-specific flags */
139 unsigned long flags;
141 /* IDs for cgroups in this hierarchy */
142 struct ida cgroup_ida;
144 /* The path to use for release notifications. */
145 char release_agent_path[PATH_MAX];
147 /* The name for this hierarchy - may be empty */
148 char name[MAX_CGROUP_ROOT_NAMELEN];
149 };
151 /*
152 * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the
153 * subsystems that are otherwise unattached - it never has more than a
154 * single cgroup, and all tasks are part of that cgroup.
155 */
156 static struct cgroupfs_root rootnode;
158 /*
159 * cgroupfs file entry, pointed to from leaf dentry->d_fsdata.
160 */
161 struct cfent {
162 struct list_head node;
163 struct dentry *dentry;
164 struct cftype *type;
166 /* file xattrs */
167 struct simple_xattrs xattrs;
168 };
170 /*
171 * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when
172 * cgroup_subsys->use_id != 0.
173 */
174 #define CSS_ID_MAX (65535)
175 struct css_id {
176 /*
177 * The css to which this ID points. This pointer is set to valid value
178 * after cgroup is populated. If cgroup is removed, this will be NULL.
179 * This pointer is expected to be RCU-safe because destroy()
180 * is called after synchronize_rcu(). But for safe use, css_tryget()
181 * should be used for avoiding race.
182 */
183 struct cgroup_subsys_state __rcu *css;
184 /*
185 * ID of this css.
186 */
187 unsigned short id;
188 /*
189 * Depth in hierarchy which this ID belongs to.
190 */
191 unsigned short depth;
192 /*
193 * ID is freed by RCU. (and lookup routine is RCU safe.)
194 */
195 struct rcu_head rcu_head;
196 /*
197 * Hierarchy of CSS ID belongs to.
198 */
199 unsigned short stack[0]; /* Array of Length (depth+1) */
200 };
202 /*
203 * cgroup_event represents events which userspace want to receive.
204 */
205 struct cgroup_event {
206 /*
207 * Cgroup which the event belongs to.
208 */
209 struct cgroup *cgrp;
210 /*
211 * Control file which the event associated.
212 */
213 struct cftype *cft;
214 /*
215 * eventfd to signal userspace about the event.
216 */
217 struct eventfd_ctx *eventfd;
218 /*
219 * Each of these stored in a list by the cgroup.
220 */
221 struct list_head list;
222 /*
223 * All fields below needed to unregister event when
224 * userspace closes eventfd.
225 */
226 poll_table pt;
227 wait_queue_head_t *wqh;
228 wait_queue_t wait;
229 struct work_struct remove;
230 };
232 /* The list of hierarchy roots */
234 static LIST_HEAD(roots);
235 static int root_count;
237 static DEFINE_IDA(hierarchy_ida);
238 static int next_hierarchy_id;
239 static DEFINE_SPINLOCK(hierarchy_id_lock);
241 /* dummytop is a shorthand for the dummy hierarchy's top cgroup */
242 #define dummytop (&rootnode.top_cgroup)
244 /* This flag indicates whether tasks in the fork and exit paths should
245 * check for fork/exit handlers to call. This avoids us having to do
246 * extra work in the fork/exit path if none of the subsystems need to
247 * be called.
248 */
249 static int need_forkexit_callback __read_mostly;
251 static int cgroup_destroy_locked(struct cgroup *cgrp);
252 static int cgroup_addrm_files(struct cgroup *cgrp, struct cgroup_subsys *subsys,
253 struct cftype cfts[], bool is_add);
255 #ifdef CONFIG_PROVE_LOCKING
256 int cgroup_lock_is_held(void)
257 {
258 return lockdep_is_held(&cgroup_mutex);
259 }
260 #else /* #ifdef CONFIG_PROVE_LOCKING */
261 int cgroup_lock_is_held(void)
262 {
263 return mutex_is_locked(&cgroup_mutex);
264 }
265 #endif /* #else #ifdef CONFIG_PROVE_LOCKING */
267 EXPORT_SYMBOL_GPL(cgroup_lock_is_held);
269 static int css_unbias_refcnt(int refcnt)
270 {
271 return refcnt >= 0 ? refcnt : refcnt - CSS_DEACT_BIAS;
272 }
274 /* the current nr of refs, always >= 0 whether @css is deactivated or not */
275 static int css_refcnt(struct cgroup_subsys_state *css)
276 {
277 int v = atomic_read(&css->refcnt);
279 return css_unbias_refcnt(v);
280 }
282 /* convenient tests for these bits */
283 inline int cgroup_is_removed(const struct cgroup *cgrp)
284 {
285 return test_bit(CGRP_REMOVED, &cgrp->flags);
286 }
288 /* bits in struct cgroupfs_root flags field */
289 enum {
290 ROOT_NOPREFIX, /* mounted subsystems have no named prefix */
291 ROOT_XATTR, /* supports extended attributes */
292 };
294 static int cgroup_is_releasable(const struct cgroup *cgrp)
295 {
296 const int bits =
297 (1 << CGRP_RELEASABLE) |
298 (1 << CGRP_NOTIFY_ON_RELEASE);
299 return (cgrp->flags & bits) == bits;
300 }
302 static int notify_on_release(const struct cgroup *cgrp)
303 {
304 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
305 }
307 /*
308 * for_each_subsys() allows you to iterate on each subsystem attached to
309 * an active hierarchy
310 */
311 #define for_each_subsys(_root, _ss) \
312 list_for_each_entry(_ss, &_root->subsys_list, sibling)
314 /* for_each_active_root() allows you to iterate across the active hierarchies */
315 #define for_each_active_root(_root) \
316 list_for_each_entry(_root, &roots, root_list)
318 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
319 {
320 return dentry->d_fsdata;
321 }
323 static inline struct cfent *__d_cfe(struct dentry *dentry)
324 {
325 return dentry->d_fsdata;
326 }
328 static inline struct cftype *__d_cft(struct dentry *dentry)
329 {
330 return __d_cfe(dentry)->type;
331 }
333 /* the list of cgroups eligible for automatic release. Protected by
334 * release_list_lock */
335 static LIST_HEAD(release_list);
336 static DEFINE_RAW_SPINLOCK(release_list_lock);
337 static void cgroup_release_agent(struct work_struct *work);
338 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
339 static void check_for_release(struct cgroup *cgrp);
341 /* Link structure for associating css_set objects with cgroups */
342 struct cg_cgroup_link {
343 /*
344 * List running through cg_cgroup_links associated with a
345 * cgroup, anchored on cgroup->css_sets
346 */
347 struct list_head cgrp_link_list;
348 struct cgroup *cgrp;
349 /*
350 * List running through cg_cgroup_links pointing at a
351 * single css_set object, anchored on css_set->cg_links
352 */
353 struct list_head cg_link_list;
354 struct css_set *cg;
355 };
357 /* The default css_set - used by init and its children prior to any
358 * hierarchies being mounted. It contains a pointer to the root state
359 * for each subsystem. Also used to anchor the list of css_sets. Not
360 * reference-counted, to improve performance when child cgroups
361 * haven't been created.
362 */
364 static struct css_set init_css_set;
365 static struct cg_cgroup_link init_css_set_link;
367 static int cgroup_init_idr(struct cgroup_subsys *ss,
368 struct cgroup_subsys_state *css);
370 /* css_set_lock protects the list of css_set objects, and the
371 * chain of tasks off each css_set. Nests outside task->alloc_lock
372 * due to cgroup_iter_start() */
373 static DEFINE_RWLOCK(css_set_lock);
374 static int css_set_count;
376 /*
377 * hash table for cgroup groups. This improves the performance to find
378 * an existing css_set. This hash doesn't (currently) take into
379 * account cgroups in empty hierarchies.
380 */
381 #define CSS_SET_HASH_BITS 7
382 #define CSS_SET_TABLE_SIZE (1 << CSS_SET_HASH_BITS)
383 static struct hlist_head css_set_table[CSS_SET_TABLE_SIZE];
385 static struct hlist_head *css_set_hash(struct cgroup_subsys_state *css[])
386 {
387 int i;
388 int index;
389 unsigned long tmp = 0UL;
391 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++)
392 tmp += (unsigned long)css[i];
393 tmp = (tmp >> 16) ^ tmp;
395 index = hash_long(tmp, CSS_SET_HASH_BITS);
397 return &css_set_table[index];
398 }
400 /* We don't maintain the lists running through each css_set to its
401 * task until after the first call to cgroup_iter_start(). This
402 * reduces the fork()/exit() overhead for people who have cgroups
403 * compiled into their kernel but not actually in use */
404 static int use_task_css_set_links __read_mostly;
406 static void __put_css_set(struct css_set *cg, int taskexit)
407 {
408 struct cg_cgroup_link *link;
409 struct cg_cgroup_link *saved_link;
410 /*
411 * Ensure that the refcount doesn't hit zero while any readers
412 * can see it. Similar to atomic_dec_and_lock(), but for an
413 * rwlock
414 */
415 if (atomic_add_unless(&cg->refcount, -1, 1))
416 return;
417 write_lock(&css_set_lock);
418 if (!atomic_dec_and_test(&cg->refcount)) {
419 write_unlock(&css_set_lock);
420 return;
421 }
423 /* This css_set is dead. unlink it and release cgroup refcounts */
424 hlist_del(&cg->hlist);
425 css_set_count--;
427 list_for_each_entry_safe(link, saved_link, &cg->cg_links,
428 cg_link_list) {
429 struct cgroup *cgrp = link->cgrp;
430 list_del(&link->cg_link_list);
431 list_del(&link->cgrp_link_list);
433 /*
434 * We may not be holding cgroup_mutex, and if cgrp->count is
435 * dropped to 0 the cgroup can be destroyed at any time, hence
436 * rcu_read_lock is used to keep it alive.
437 */
438 rcu_read_lock();
439 if (atomic_dec_and_test(&cgrp->count) &&
440 notify_on_release(cgrp)) {
441 if (taskexit)
442 set_bit(CGRP_RELEASABLE, &cgrp->flags);
443 check_for_release(cgrp);
444 }
445 rcu_read_unlock();
447 kfree(link);
448 }
450 write_unlock(&css_set_lock);
451 kfree_rcu(cg, rcu_head);
452 }
454 /*
455 * refcounted get/put for css_set objects
456 */
457 static inline void get_css_set(struct css_set *cg)
458 {
459 atomic_inc(&cg->refcount);
460 }
462 static inline void put_css_set(struct css_set *cg)
463 {
464 __put_css_set(cg, 0);
465 }
467 static inline void put_css_set_taskexit(struct css_set *cg)
468 {
469 __put_css_set(cg, 1);
470 }
472 /*
473 * compare_css_sets - helper function for find_existing_css_set().
474 * @cg: candidate css_set being tested
475 * @old_cg: existing css_set for a task
476 * @new_cgrp: cgroup that's being entered by the task
477 * @template: desired set of css pointers in css_set (pre-calculated)
478 *
479 * Returns true if "cg" matches "old_cg" except for the hierarchy
480 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
481 */
482 static bool compare_css_sets(struct css_set *cg,
483 struct css_set *old_cg,
484 struct cgroup *new_cgrp,
485 struct cgroup_subsys_state *template[])
486 {
487 struct list_head *l1, *l2;
489 if (memcmp(template, cg->subsys, sizeof(cg->subsys))) {
490 /* Not all subsystems matched */
491 return false;
492 }
494 /*
495 * Compare cgroup pointers in order to distinguish between
496 * different cgroups in heirarchies with no subsystems. We
497 * could get by with just this check alone (and skip the
498 * memcmp above) but on most setups the memcmp check will
499 * avoid the need for this more expensive check on almost all
500 * candidates.
501 */
503 l1 = &cg->cg_links;
504 l2 = &old_cg->cg_links;
505 while (1) {
506 struct cg_cgroup_link *cgl1, *cgl2;
507 struct cgroup *cg1, *cg2;
509 l1 = l1->next;
510 l2 = l2->next;
511 /* See if we reached the end - both lists are equal length. */
512 if (l1 == &cg->cg_links) {
513 BUG_ON(l2 != &old_cg->cg_links);
514 break;
515 } else {
516 BUG_ON(l2 == &old_cg->cg_links);
517 }
518 /* Locate the cgroups associated with these links. */
519 cgl1 = list_entry(l1, struct cg_cgroup_link, cg_link_list);
520 cgl2 = list_entry(l2, struct cg_cgroup_link, cg_link_list);
521 cg1 = cgl1->cgrp;
522 cg2 = cgl2->cgrp;
523 /* Hierarchies should be linked in the same order. */
524 BUG_ON(cg1->root != cg2->root);
526 /*
527 * If this hierarchy is the hierarchy of the cgroup
528 * that's changing, then we need to check that this
529 * css_set points to the new cgroup; if it's any other
530 * hierarchy, then this css_set should point to the
531 * same cgroup as the old css_set.
532 */
533 if (cg1->root == new_cgrp->root) {
534 if (cg1 != new_cgrp)
535 return false;
536 } else {
537 if (cg1 != cg2)
538 return false;
539 }
540 }
541 return true;
542 }
544 /*
545 * find_existing_css_set() is a helper for
546 * find_css_set(), and checks to see whether an existing
547 * css_set is suitable.
548 *
549 * oldcg: the cgroup group that we're using before the cgroup
550 * transition
551 *
552 * cgrp: the cgroup that we're moving into
553 *
554 * template: location in which to build the desired set of subsystem
555 * state objects for the new cgroup group
556 */
557 static struct css_set *find_existing_css_set(
558 struct css_set *oldcg,
559 struct cgroup *cgrp,
560 struct cgroup_subsys_state *template[])
561 {
562 int i;
563 struct cgroupfs_root *root = cgrp->root;
564 struct hlist_head *hhead;
565 struct hlist_node *node;
566 struct css_set *cg;
568 /*
569 * Build the set of subsystem state objects that we want to see in the
570 * new css_set. while subsystems can change globally, the entries here
571 * won't change, so no need for locking.
572 */
573 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
574 if (root->subsys_mask & (1UL << i)) {
575 /* Subsystem is in this hierarchy. So we want
576 * the subsystem state from the new
577 * cgroup */
578 template[i] = cgrp->subsys[i];
579 } else {
580 /* Subsystem is not in this hierarchy, so we
581 * don't want to change the subsystem state */
582 template[i] = oldcg->subsys[i];
583 }
584 }
586 hhead = css_set_hash(template);
587 hlist_for_each_entry(cg, node, hhead, hlist) {
588 if (!compare_css_sets(cg, oldcg, cgrp, template))
589 continue;
591 /* This css_set matches what we need */
592 return cg;
593 }
595 /* No existing cgroup group matched */
596 return NULL;
597 }
599 static void free_cg_links(struct list_head *tmp)
600 {
601 struct cg_cgroup_link *link;
602 struct cg_cgroup_link *saved_link;
604 list_for_each_entry_safe(link, saved_link, tmp, cgrp_link_list) {
605 list_del(&link->cgrp_link_list);
606 kfree(link);
607 }
608 }
610 /*
611 * allocate_cg_links() allocates "count" cg_cgroup_link structures
612 * and chains them on tmp through their cgrp_link_list fields. Returns 0 on
613 * success or a negative error
614 */
615 static int allocate_cg_links(int count, struct list_head *tmp)
616 {
617 struct cg_cgroup_link *link;
618 int i;
619 INIT_LIST_HEAD(tmp);
620 for (i = 0; i < count; i++) {
621 link = kmalloc(sizeof(*link), GFP_KERNEL);
622 if (!link) {
623 free_cg_links(tmp);
624 return -ENOMEM;
625 }
626 list_add(&link->cgrp_link_list, tmp);
627 }
628 return 0;
629 }
631 /**
632 * link_css_set - a helper function to link a css_set to a cgroup
633 * @tmp_cg_links: cg_cgroup_link objects allocated by allocate_cg_links()
634 * @cg: the css_set to be linked
635 * @cgrp: the destination cgroup
636 */
637 static void link_css_set(struct list_head *tmp_cg_links,
638 struct css_set *cg, struct cgroup *cgrp)
639 {
640 struct cg_cgroup_link *link;
642 BUG_ON(list_empty(tmp_cg_links));
643 link = list_first_entry(tmp_cg_links, struct cg_cgroup_link,
644 cgrp_link_list);
645 link->cg = cg;
646 link->cgrp = cgrp;
647 atomic_inc(&cgrp->count);
648 list_move(&link->cgrp_link_list, &cgrp->css_sets);
649 /*
650 * Always add links to the tail of the list so that the list
651 * is sorted by order of hierarchy creation
652 */
653 list_add_tail(&link->cg_link_list, &cg->cg_links);
654 }
656 /*
657 * find_css_set() takes an existing cgroup group and a
658 * cgroup object, and returns a css_set object that's
659 * equivalent to the old group, but with the given cgroup
660 * substituted into the appropriate hierarchy. Must be called with
661 * cgroup_mutex held
662 */
663 static struct css_set *find_css_set(
664 struct css_set *oldcg, struct cgroup *cgrp)
665 {
666 struct css_set *res;
667 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT];
669 struct list_head tmp_cg_links;
671 struct hlist_head *hhead;
672 struct cg_cgroup_link *link;
674 /* First see if we already have a cgroup group that matches
675 * the desired set */
676 read_lock(&css_set_lock);
677 res = find_existing_css_set(oldcg, cgrp, template);
678 if (res)
679 get_css_set(res);
680 read_unlock(&css_set_lock);
682 if (res)
683 return res;
685 res = kmalloc(sizeof(*res), GFP_KERNEL);
686 if (!res)
687 return NULL;
689 /* Allocate all the cg_cgroup_link objects that we'll need */
690 if (allocate_cg_links(root_count, &tmp_cg_links) < 0) {
691 kfree(res);
692 return NULL;
693 }
695 atomic_set(&res->refcount, 1);
696 INIT_LIST_HEAD(&res->cg_links);
697 INIT_LIST_HEAD(&res->tasks);
698 INIT_HLIST_NODE(&res->hlist);
700 /* Copy the set of subsystem state objects generated in
701 * find_existing_css_set() */
702 memcpy(res->subsys, template, sizeof(res->subsys));
704 write_lock(&css_set_lock);
705 /* Add reference counts and links from the new css_set. */
706 list_for_each_entry(link, &oldcg->cg_links, cg_link_list) {
707 struct cgroup *c = link->cgrp;
708 if (c->root == cgrp->root)
709 c = cgrp;
710 link_css_set(&tmp_cg_links, res, c);
711 }
713 BUG_ON(!list_empty(&tmp_cg_links));
715 css_set_count++;
717 /* Add this cgroup group to the hash table */
718 hhead = css_set_hash(res->subsys);
719 hlist_add_head(&res->hlist, hhead);
721 write_unlock(&css_set_lock);
723 return res;
724 }
726 /*
727 * Return the cgroup for "task" from the given hierarchy. Must be
728 * called with cgroup_mutex held.
729 */
730 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
731 struct cgroupfs_root *root)
732 {
733 struct css_set *css;
734 struct cgroup *res = NULL;
736 BUG_ON(!mutex_is_locked(&cgroup_mutex));
737 read_lock(&css_set_lock);
738 /*
739 * No need to lock the task - since we hold cgroup_mutex the
740 * task can't change groups, so the only thing that can happen
741 * is that it exits and its css is set back to init_css_set.
742 */
743 css = task->cgroups;
744 if (css == &init_css_set) {
745 res = &root->top_cgroup;
746 } else {
747 struct cg_cgroup_link *link;
748 list_for_each_entry(link, &css->cg_links, cg_link_list) {
749 struct cgroup *c = link->cgrp;
750 if (c->root == root) {
751 res = c;
752 break;
753 }
754 }
755 }
756 read_unlock(&css_set_lock);
757 BUG_ON(!res);
758 return res;
759 }
761 /*
762 * There is one global cgroup mutex. We also require taking
763 * task_lock() when dereferencing a task's cgroup subsys pointers.
764 * See "The task_lock() exception", at the end of this comment.
765 *
766 * A task must hold cgroup_mutex to modify cgroups.
767 *
768 * Any task can increment and decrement the count field without lock.
769 * So in general, code holding cgroup_mutex can't rely on the count
770 * field not changing. However, if the count goes to zero, then only
771 * cgroup_attach_task() can increment it again. Because a count of zero
772 * means that no tasks are currently attached, therefore there is no
773 * way a task attached to that cgroup can fork (the other way to
774 * increment the count). So code holding cgroup_mutex can safely
775 * assume that if the count is zero, it will stay zero. Similarly, if
776 * a task holds cgroup_mutex on a cgroup with zero count, it
777 * knows that the cgroup won't be removed, as cgroup_rmdir()
778 * needs that mutex.
779 *
780 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
781 * (usually) take cgroup_mutex. These are the two most performance
782 * critical pieces of code here. The exception occurs on cgroup_exit(),
783 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
784 * is taken, and if the cgroup count is zero, a usermode call made
785 * to the release agent with the name of the cgroup (path relative to
786 * the root of cgroup file system) as the argument.
787 *
788 * A cgroup can only be deleted if both its 'count' of using tasks
789 * is zero, and its list of 'children' cgroups is empty. Since all
790 * tasks in the system use _some_ cgroup, and since there is always at
791 * least one task in the system (init, pid == 1), therefore, top_cgroup
792 * always has either children cgroups and/or using tasks. So we don't
793 * need a special hack to ensure that top_cgroup cannot be deleted.
794 *
795 * The task_lock() exception
796 *
797 * The need for this exception arises from the action of
798 * cgroup_attach_task(), which overwrites one task's cgroup pointer with
799 * another. It does so using cgroup_mutex, however there are
800 * several performance critical places that need to reference
801 * task->cgroup without the expense of grabbing a system global
802 * mutex. Therefore except as noted below, when dereferencing or, as
803 * in cgroup_attach_task(), modifying a task's cgroup pointer we use
804 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
805 * the task_struct routinely used for such matters.
806 *
807 * P.S. One more locking exception. RCU is used to guard the
808 * update of a tasks cgroup pointer by cgroup_attach_task()
809 */
811 /**
812 * cgroup_lock - lock out any changes to cgroup structures
813 *
814 */
815 void cgroup_lock(void)
816 {
817 mutex_lock(&cgroup_mutex);
818 }
819 EXPORT_SYMBOL_GPL(cgroup_lock);
821 /**
822 * cgroup_unlock - release lock on cgroup changes
823 *
824 * Undo the lock taken in a previous cgroup_lock() call.
825 */
826 void cgroup_unlock(void)
827 {
828 mutex_unlock(&cgroup_mutex);
829 }
830 EXPORT_SYMBOL_GPL(cgroup_unlock);
832 /*
833 * A couple of forward declarations required, due to cyclic reference loop:
834 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
835 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
836 * -> cgroup_mkdir.
837 */
839 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode);
840 static struct dentry *cgroup_lookup(struct inode *, struct dentry *, unsigned int);
841 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
842 static int cgroup_populate_dir(struct cgroup *cgrp, bool base_files,
843 unsigned long subsys_mask);
844 static const struct inode_operations cgroup_dir_inode_operations;
845 static const struct file_operations proc_cgroupstats_operations;
847 static struct backing_dev_info cgroup_backing_dev_info = {
848 .name = "cgroup",
849 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
850 };
852 static int alloc_css_id(struct cgroup_subsys *ss,
853 struct cgroup *parent, struct cgroup *child);
855 static struct inode *cgroup_new_inode(umode_t mode, struct super_block *sb)
856 {
857 struct inode *inode = new_inode(sb);
859 if (inode) {
860 inode->i_ino = get_next_ino();
861 inode->i_mode = mode;
862 inode->i_uid = current_fsuid();
863 inode->i_gid = current_fsgid();
864 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
865 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
866 }
867 return inode;
868 }
870 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
871 {
872 /* is dentry a directory ? if so, kfree() associated cgroup */
873 if (S_ISDIR(inode->i_mode)) {
874 struct cgroup *cgrp = dentry->d_fsdata;
875 struct cgroup_subsys *ss;
876 BUG_ON(!(cgroup_is_removed(cgrp)));
877 /* It's possible for external users to be holding css
878 * reference counts on a cgroup; css_put() needs to
879 * be able to access the cgroup after decrementing
880 * the reference count in order to know if it needs to
881 * queue the cgroup to be handled by the release
882 * agent */
883 synchronize_rcu();
885 mutex_lock(&cgroup_mutex);
886 /*
887 * Release the subsystem state objects.
888 */
889 for_each_subsys(cgrp->root, ss)
890 ss->css_free(cgrp);
892 cgrp->root->number_of_cgroups--;
893 mutex_unlock(&cgroup_mutex);
895 /*
896 * Drop the active superblock reference that we took when we
897 * created the cgroup
898 */
899 deactivate_super(cgrp->root->sb);
901 /*
902 * if we're getting rid of the cgroup, refcount should ensure
903 * that there are no pidlists left.
904 */
905 BUG_ON(!list_empty(&cgrp->pidlists));
907 simple_xattrs_free(&cgrp->xattrs);
909 ida_simple_remove(&cgrp->root->cgroup_ida, cgrp->id);
910 kfree_rcu(cgrp, rcu_head);
911 } else {
912 struct cfent *cfe = __d_cfe(dentry);
913 struct cgroup *cgrp = dentry->d_parent->d_fsdata;
915 WARN_ONCE(!list_empty(&cfe->node) &&
916 cgrp != &cgrp->root->top_cgroup,
917 "cfe still linked for %s\n", cfe->type->name);
918 simple_xattrs_free(&cfe->xattrs);
919 kfree(cfe);
920 }
921 iput(inode);
922 }
924 static int cgroup_delete(const struct dentry *d)
925 {
926 return 1;
927 }
929 static void remove_dir(struct dentry *d)
930 {
931 struct dentry *parent = dget(d->d_parent);
933 d_delete(d);
934 simple_rmdir(parent->d_inode, d);
935 dput(parent);
936 }
938 static int cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
939 {
940 struct cfent *cfe;
942 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
943 lockdep_assert_held(&cgroup_mutex);
945 list_for_each_entry(cfe, &cgrp->files, node) {
946 struct dentry *d = cfe->dentry;
948 if (cft && cfe->type != cft)
949 continue;
951 dget(d);
952 d_delete(d);
953 simple_unlink(cgrp->dentry->d_inode, d);
954 list_del_init(&cfe->node);
955 dput(d);
957 return 0;
958 }
959 return -ENOENT;
960 }
962 /**
963 * cgroup_clear_directory - selective removal of base and subsystem files
964 * @dir: directory containing the files
965 * @base_files: true if the base files should be removed
966 * @subsys_mask: mask of the subsystem ids whose files should be removed
967 */
968 static void cgroup_clear_directory(struct dentry *dir, bool base_files,
969 unsigned long subsys_mask)
970 {
971 struct cgroup *cgrp = __d_cgrp(dir);
972 struct cgroup_subsys *ss;
974 for_each_subsys(cgrp->root, ss) {
975 struct cftype_set *set;
976 if (!test_bit(ss->subsys_id, &subsys_mask))
977 continue;
978 list_for_each_entry(set, &ss->cftsets, node)
979 cgroup_addrm_files(cgrp, NULL, set->cfts, false);
980 }
981 if (base_files) {
982 while (!list_empty(&cgrp->files))
983 cgroup_rm_file(cgrp, NULL);
984 }
985 }
987 /*
988 * NOTE : the dentry must have been dget()'ed
989 */
990 static void cgroup_d_remove_dir(struct dentry *dentry)
991 {
992 struct dentry *parent;
993 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
995 cgroup_clear_directory(dentry, true, root->subsys_mask);
997 parent = dentry->d_parent;
998 spin_lock(&parent->d_lock);
999 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
1000 list_del_init(&dentry->d_u.d_child);
1001 spin_unlock(&dentry->d_lock);
1002 spin_unlock(&parent->d_lock);
1003 remove_dir(dentry);
1004 }
1006 /*
1007 * Call with cgroup_mutex held. Drops reference counts on modules, including
1008 * any duplicate ones that parse_cgroupfs_options took. If this function
1009 * returns an error, no reference counts are touched.
1010 */
1011 static int rebind_subsystems(struct cgroupfs_root *root,
1012 unsigned long final_subsys_mask)
1013 {
1014 unsigned long added_mask, removed_mask;
1015 struct cgroup *cgrp = &root->top_cgroup;
1016 int i;
1018 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1019 BUG_ON(!mutex_is_locked(&cgroup_root_mutex));
1021 removed_mask = root->actual_subsys_mask & ~final_subsys_mask;
1022 added_mask = final_subsys_mask & ~root->actual_subsys_mask;
1023 /* Check that any added subsystems are currently free */
1024 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1025 unsigned long bit = 1UL << i;
1026 struct cgroup_subsys *ss = subsys[i];
1027 if (!(bit & added_mask))
1028 continue;
1029 /*
1030 * Nobody should tell us to do a subsys that doesn't exist:
1031 * parse_cgroupfs_options should catch that case and refcounts
1032 * ensure that subsystems won't disappear once selected.
1033 */
1034 BUG_ON(ss == NULL);
1035 if (ss->root != &rootnode) {
1036 /* Subsystem isn't free */
1037 return -EBUSY;
1038 }
1039 }
1041 /* Currently we don't handle adding/removing subsystems when
1042 * any child cgroups exist. This is theoretically supportable
1043 * but involves complex error handling, so it's being left until
1044 * later */
1045 if (root->number_of_cgroups > 1)
1046 return -EBUSY;
1048 /* Process each subsystem */
1049 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1050 struct cgroup_subsys *ss = subsys[i];
1051 unsigned long bit = 1UL << i;
1052 if (bit & added_mask) {
1053 /* We're binding this subsystem to this hierarchy */
1054 BUG_ON(ss == NULL);
1055 BUG_ON(cgrp->subsys[i]);
1056 BUG_ON(!dummytop->subsys[i]);
1057 BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
1058 cgrp->subsys[i] = dummytop->subsys[i];
1059 cgrp->subsys[i]->cgroup = cgrp;
1060 list_move(&ss->sibling, &root->subsys_list);
1061 ss->root = root;
1062 if (ss->bind)
1063 ss->bind(cgrp);
1064 /* refcount was already taken, and we're keeping it */
1065 } else if (bit & removed_mask) {
1066 /* We're removing this subsystem */
1067 BUG_ON(ss == NULL);
1068 BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
1069 BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
1070 if (ss->bind)
1071 ss->bind(dummytop);
1072 dummytop->subsys[i]->cgroup = dummytop;
1073 cgrp->subsys[i] = NULL;
1074 subsys[i]->root = &rootnode;
1075 list_move(&ss->sibling, &rootnode.subsys_list);
1076 /* subsystem is now free - drop reference on module */
1077 module_put(ss->module);
1078 } else if (bit & final_subsys_mask) {
1079 /* Subsystem state should already exist */
1080 BUG_ON(ss == NULL);
1081 BUG_ON(!cgrp->subsys[i]);
1082 /*
1083 * a refcount was taken, but we already had one, so
1084 * drop the extra reference.
1085 */
1086 module_put(ss->module);
1087 #ifdef CONFIG_MODULE_UNLOAD
1088 BUG_ON(ss->module && !module_refcount(ss->module));
1089 #endif
1090 } else {
1091 /* Subsystem state shouldn't exist */
1092 BUG_ON(cgrp->subsys[i]);
1093 }
1094 }
1095 root->subsys_mask = root->actual_subsys_mask = final_subsys_mask;
1096 synchronize_rcu();
1098 return 0;
1099 }
1101 static int cgroup_show_options(struct seq_file *seq, struct dentry *dentry)
1102 {
1103 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
1104 struct cgroup_subsys *ss;
1106 mutex_lock(&cgroup_root_mutex);
1107 for_each_subsys(root, ss)
1108 seq_printf(seq, ",%s", ss->name);
1109 if (test_bit(ROOT_NOPREFIX, &root->flags))
1110 seq_puts(seq, ",noprefix");
1111 if (test_bit(ROOT_XATTR, &root->flags))
1112 seq_puts(seq, ",xattr");
1113 if (strlen(root->release_agent_path))
1114 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1115 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1116 seq_puts(seq, ",clone_children");
1117 if (strlen(root->name))
1118 seq_printf(seq, ",name=%s", root->name);
1119 mutex_unlock(&cgroup_root_mutex);
1120 return 0;
1121 }
1123 struct cgroup_sb_opts {
1124 unsigned long subsys_mask;
1125 unsigned long flags;
1126 char *release_agent;
1127 bool cpuset_clone_children;
1128 char *name;
1129 /* User explicitly requested empty subsystem */
1130 bool none;
1132 struct cgroupfs_root *new_root;
1134 };
1136 /*
1137 * Convert a hierarchy specifier into a bitmask of subsystems and flags. Call
1138 * with cgroup_mutex held to protect the subsys[] array. This function takes
1139 * refcounts on subsystems to be used, unless it returns error, in which case
1140 * no refcounts are taken.
1141 */
1142 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1143 {
1144 char *token, *o = data;
1145 bool all_ss = false, one_ss = false;
1146 unsigned long mask = (unsigned long)-1;
1147 int i;
1148 bool module_pin_failed = false;
1150 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1152 #ifdef CONFIG_CPUSETS
1153 mask = ~(1UL << cpuset_subsys_id);
1154 #endif
1156 memset(opts, 0, sizeof(*opts));
1158 while ((token = strsep(&o, ",")) != NULL) {
1159 if (!*token)
1160 return -EINVAL;
1161 if (!strcmp(token, "none")) {
1162 /* Explicitly have no subsystems */
1163 opts->none = true;
1164 continue;
1165 }
1166 if (!strcmp(token, "all")) {
1167 /* Mutually exclusive option 'all' + subsystem name */
1168 if (one_ss)
1169 return -EINVAL;
1170 all_ss = true;
1171 continue;
1172 }
1173 if (!strcmp(token, "noprefix")) {
1174 set_bit(ROOT_NOPREFIX, &opts->flags);
1175 continue;
1176 }
1177 if (!strcmp(token, "clone_children")) {
1178 opts->cpuset_clone_children = true;
1179 continue;
1180 }
1181 if (!strcmp(token, "xattr")) {
1182 set_bit(ROOT_XATTR, &opts->flags);
1183 continue;
1184 }
1185 if (!strncmp(token, "release_agent=", 14)) {
1186 /* Specifying two release agents is forbidden */
1187 if (opts->release_agent)
1188 return -EINVAL;
1189 opts->release_agent =
1190 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1191 if (!opts->release_agent)
1192 return -ENOMEM;
1193 continue;
1194 }
1195 if (!strncmp(token, "name=", 5)) {
1196 const char *name = token + 5;
1197 /* Can't specify an empty name */
1198 if (!strlen(name))
1199 return -EINVAL;
1200 /* Must match [\w.-]+ */
1201 for (i = 0; i < strlen(name); i++) {
1202 char c = name[i];
1203 if (isalnum(c))
1204 continue;
1205 if ((c == '.') || (c == '-') || (c == '_'))
1206 continue;
1207 return -EINVAL;
1208 }
1209 /* Specifying two names is forbidden */
1210 if (opts->name)
1211 return -EINVAL;
1212 opts->name = kstrndup(name,
1213 MAX_CGROUP_ROOT_NAMELEN - 1,
1214 GFP_KERNEL);
1215 if (!opts->name)
1216 return -ENOMEM;
1218 continue;
1219 }
1221 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1222 struct cgroup_subsys *ss = subsys[i];
1223 if (ss == NULL)
1224 continue;
1225 if (strcmp(token, ss->name))
1226 continue;
1227 if (ss->disabled)
1228 continue;
1230 /* Mutually exclusive option 'all' + subsystem name */
1231 if (all_ss)
1232 return -EINVAL;
1233 set_bit(i, &opts->subsys_mask);
1234 one_ss = true;
1236 break;
1237 }
1238 if (i == CGROUP_SUBSYS_COUNT)
1239 return -ENOENT;
1240 }
1242 /*
1243 * If the 'all' option was specified select all the subsystems,
1244 * otherwise if 'none', 'name=' and a subsystem name options
1245 * were not specified, let's default to 'all'
1246 */
1247 if (all_ss || (!one_ss && !opts->none && !opts->name)) {
1248 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1249 struct cgroup_subsys *ss = subsys[i];
1250 if (ss == NULL)
1251 continue;
1252 if (ss->disabled)
1253 continue;
1254 set_bit(i, &opts->subsys_mask);
1255 }
1256 }
1258 /* Consistency checks */
1260 /*
1261 * Option noprefix was introduced just for backward compatibility
1262 * with the old cpuset, so we allow noprefix only if mounting just
1263 * the cpuset subsystem.
1264 */
1265 if (test_bit(ROOT_NOPREFIX, &opts->flags) &&
1266 (opts->subsys_mask & mask))
1267 return -EINVAL;
1270 /* Can't specify "none" and some subsystems */
1271 if (opts->subsys_mask && opts->none)
1272 return -EINVAL;
1274 /*
1275 * We either have to specify by name or by subsystems. (So all
1276 * empty hierarchies must have a name).
1277 */
1278 if (!opts->subsys_mask && !opts->name)
1279 return -EINVAL;
1281 /*
1282 * Grab references on all the modules we'll need, so the subsystems
1283 * don't dance around before rebind_subsystems attaches them. This may
1284 * take duplicate reference counts on a subsystem that's already used,
1285 * but rebind_subsystems handles this case.
1286 */
1287 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1288 unsigned long bit = 1UL << i;
1290 if (!(bit & opts->subsys_mask))
1291 continue;
1292 if (!try_module_get(subsys[i]->module)) {
1293 module_pin_failed = true;
1294 break;
1295 }
1296 }
1297 if (module_pin_failed) {
1298 /*
1299 * oops, one of the modules was going away. this means that we
1300 * raced with a module_delete call, and to the user this is
1301 * essentially a "subsystem doesn't exist" case.
1302 */
1303 for (i--; i >= 0; i--) {
1304 /* drop refcounts only on the ones we took */
1305 unsigned long bit = 1UL << i;
1307 if (!(bit & opts->subsys_mask))
1308 continue;
1309 module_put(subsys[i]->module);
1310 }
1311 return -ENOENT;
1312 }
1314 return 0;
1315 }
1317 static void drop_parsed_module_refcounts(unsigned long subsys_mask)
1318 {
1319 int i;
1320 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1321 unsigned long bit = 1UL << i;
1323 if (!(bit & subsys_mask))
1324 continue;
1325 module_put(subsys[i]->module);
1326 }
1327 }
1329 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1330 {
1331 int ret = 0;
1332 struct cgroupfs_root *root = sb->s_fs_info;
1333 struct cgroup *cgrp = &root->top_cgroup;
1334 struct cgroup_sb_opts opts;
1335 unsigned long added_mask, removed_mask;
1337 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1338 mutex_lock(&cgroup_mutex);
1339 mutex_lock(&cgroup_root_mutex);
1341 /* See what subsystems are wanted */
1342 ret = parse_cgroupfs_options(data, &opts);
1343 if (ret)
1344 goto out_unlock;
1346 if (opts.subsys_mask != root->actual_subsys_mask || opts.release_agent)
1347 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1348 task_tgid_nr(current), current->comm);
1350 added_mask = opts.subsys_mask & ~root->subsys_mask;
1351 removed_mask = root->subsys_mask & ~opts.subsys_mask;
1353 /* Don't allow flags or name to change at remount */
1354 if (opts.flags != root->flags ||
1355 (opts.name && strcmp(opts.name, root->name))) {
1356 ret = -EINVAL;
1357 drop_parsed_module_refcounts(opts.subsys_mask);
1358 goto out_unlock;
1359 }
1361 /*
1362 * Clear out the files of subsystems that should be removed, do
1363 * this before rebind_subsystems, since rebind_subsystems may
1364 * change this hierarchy's subsys_list.
1365 */
1366 cgroup_clear_directory(cgrp->dentry, false, removed_mask);
1368 ret = rebind_subsystems(root, opts.subsys_mask);
1369 if (ret) {
1370 /* rebind_subsystems failed, re-populate the removed files */
1371 cgroup_populate_dir(cgrp, false, removed_mask);
1372 drop_parsed_module_refcounts(opts.subsys_mask);
1373 goto out_unlock;
1374 }
1376 /* re-populate subsystem files */
1377 cgroup_populate_dir(cgrp, false, added_mask);
1379 if (opts.release_agent)
1380 strcpy(root->release_agent_path, opts.release_agent);
1381 out_unlock:
1382 kfree(opts.release_agent);
1383 kfree(opts.name);
1384 mutex_unlock(&cgroup_root_mutex);
1385 mutex_unlock(&cgroup_mutex);
1386 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1387 return ret;
1388 }
1390 static const struct super_operations cgroup_ops = {
1391 .statfs = simple_statfs,
1392 .drop_inode = generic_delete_inode,
1393 .show_options = cgroup_show_options,
1394 .remount_fs = cgroup_remount,
1395 };
1397 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1398 {
1399 INIT_LIST_HEAD(&cgrp->sibling);
1400 INIT_LIST_HEAD(&cgrp->children);
1401 INIT_LIST_HEAD(&cgrp->files);
1402 INIT_LIST_HEAD(&cgrp->css_sets);
1403 INIT_LIST_HEAD(&cgrp->allcg_node);
1404 INIT_LIST_HEAD(&cgrp->release_list);
1405 INIT_LIST_HEAD(&cgrp->pidlists);
1406 mutex_init(&cgrp->pidlist_mutex);
1407 INIT_LIST_HEAD(&cgrp->event_list);
1408 spin_lock_init(&cgrp->event_list_lock);
1409 simple_xattrs_init(&cgrp->xattrs);
1410 }
1412 static void init_cgroup_root(struct cgroupfs_root *root)
1413 {
1414 struct cgroup *cgrp = &root->top_cgroup;
1416 INIT_LIST_HEAD(&root->subsys_list);
1417 INIT_LIST_HEAD(&root->root_list);
1418 INIT_LIST_HEAD(&root->allcg_list);
1419 root->number_of_cgroups = 1;
1420 cgrp->root = root;
1421 cgrp->top_cgroup = cgrp;
1422 init_cgroup_housekeeping(cgrp);
1423 list_add_tail(&cgrp->allcg_node, &root->allcg_list);
1424 }
1426 static bool init_root_id(struct cgroupfs_root *root)
1427 {
1428 int ret = 0;
1430 do {
1431 if (!ida_pre_get(&hierarchy_ida, GFP_KERNEL))
1432 return false;
1433 spin_lock(&hierarchy_id_lock);
1434 /* Try to allocate the next unused ID */
1435 ret = ida_get_new_above(&hierarchy_ida, next_hierarchy_id,
1436 &root->hierarchy_id);
1437 if (ret == -ENOSPC)
1438 /* Try again starting from 0 */
1439 ret = ida_get_new(&hierarchy_ida, &root->hierarchy_id);
1440 if (!ret) {
1441 next_hierarchy_id = root->hierarchy_id + 1;
1442 } else if (ret != -EAGAIN) {
1443 /* Can only get here if the 31-bit IDR is full ... */
1444 BUG_ON(ret);
1445 }
1446 spin_unlock(&hierarchy_id_lock);
1447 } while (ret);
1448 return true;
1449 }
1451 static int cgroup_test_super(struct super_block *sb, void *data)
1452 {
1453 struct cgroup_sb_opts *opts = data;
1454 struct cgroupfs_root *root = sb->s_fs_info;
1456 /* If we asked for a name then it must match */
1457 if (opts->name && strcmp(opts->name, root->name))
1458 return 0;
1460 /*
1461 * If we asked for subsystems (or explicitly for no
1462 * subsystems) then they must match
1463 */
1464 if ((opts->subsys_mask || opts->none)
1465 && (opts->subsys_mask != root->subsys_mask))
1466 return 0;
1468 return 1;
1469 }
1471 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1472 {
1473 struct cgroupfs_root *root;
1475 if (!opts->subsys_mask && !opts->none)
1476 return NULL;
1478 root = kzalloc(sizeof(*root), GFP_KERNEL);
1479 if (!root)
1480 return ERR_PTR(-ENOMEM);
1482 if (!init_root_id(root)) {
1483 kfree(root);
1484 return ERR_PTR(-ENOMEM);
1485 }
1486 init_cgroup_root(root);
1488 root->subsys_mask = opts->subsys_mask;
1489 root->flags = opts->flags;
1490 ida_init(&root->cgroup_ida);
1491 if (opts->release_agent)
1492 strcpy(root->release_agent_path, opts->release_agent);
1493 if (opts->name)
1494 strcpy(root->name, opts->name);
1495 if (opts->cpuset_clone_children)
1496 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1497 return root;
1498 }
1500 static void cgroup_drop_root(struct cgroupfs_root *root)
1501 {
1502 if (!root)
1503 return;
1505 BUG_ON(!root->hierarchy_id);
1506 spin_lock(&hierarchy_id_lock);
1507 ida_remove(&hierarchy_ida, root->hierarchy_id);
1508 spin_unlock(&hierarchy_id_lock);
1509 ida_destroy(&root->cgroup_ida);
1510 kfree(root);
1511 }
1513 static int cgroup_set_super(struct super_block *sb, void *data)
1514 {
1515 int ret;
1516 struct cgroup_sb_opts *opts = data;
1518 /* If we don't have a new root, we can't set up a new sb */
1519 if (!opts->new_root)
1520 return -EINVAL;
1522 BUG_ON(!opts->subsys_mask && !opts->none);
1524 ret = set_anon_super(sb, NULL);
1525 if (ret)
1526 return ret;
1528 sb->s_fs_info = opts->new_root;
1529 opts->new_root->sb = sb;
1531 sb->s_blocksize = PAGE_CACHE_SIZE;
1532 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1533 sb->s_magic = CGROUP_SUPER_MAGIC;
1534 sb->s_op = &cgroup_ops;
1536 return 0;
1537 }
1539 static int cgroup_get_rootdir(struct super_block *sb)
1540 {
1541 static const struct dentry_operations cgroup_dops = {
1542 .d_iput = cgroup_diput,
1543 .d_delete = cgroup_delete,
1544 };
1546 struct inode *inode =
1547 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1549 if (!inode)
1550 return -ENOMEM;
1552 inode->i_fop = &simple_dir_operations;
1553 inode->i_op = &cgroup_dir_inode_operations;
1554 /* directories start off with i_nlink == 2 (for "." entry) */
1555 inc_nlink(inode);
1556 sb->s_root = d_make_root(inode);
1557 if (!sb->s_root)
1558 return -ENOMEM;
1559 /* for everything else we want ->d_op set */
1560 sb->s_d_op = &cgroup_dops;
1561 return 0;
1562 }
1564 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1565 int flags, const char *unused_dev_name,
1566 void *data)
1567 {
1568 struct cgroup_sb_opts opts;
1569 struct cgroupfs_root *root;
1570 int ret = 0;
1571 struct super_block *sb;
1572 struct cgroupfs_root *new_root;
1573 struct inode *inode;
1575 /* First find the desired set of subsystems */
1576 mutex_lock(&cgroup_mutex);
1577 ret = parse_cgroupfs_options(data, &opts);
1578 mutex_unlock(&cgroup_mutex);
1579 if (ret)
1580 goto out_err;
1582 /*
1583 * Allocate a new cgroup root. We may not need it if we're
1584 * reusing an existing hierarchy.
1585 */
1586 new_root = cgroup_root_from_opts(&opts);
1587 if (IS_ERR(new_root)) {
1588 ret = PTR_ERR(new_root);
1589 goto drop_modules;
1590 }
1591 opts.new_root = new_root;
1593 /* Locate an existing or new sb for this hierarchy */
1594 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1595 if (IS_ERR(sb)) {
1596 ret = PTR_ERR(sb);
1597 cgroup_drop_root(opts.new_root);
1598 goto drop_modules;
1599 }
1601 root = sb->s_fs_info;
1602 BUG_ON(!root);
1603 if (root == opts.new_root) {
1604 /* We used the new root structure, so this is a new hierarchy */
1605 struct list_head tmp_cg_links;
1606 struct cgroup *root_cgrp = &root->top_cgroup;
1607 struct cgroupfs_root *existing_root;
1608 const struct cred *cred;
1609 int i;
1611 BUG_ON(sb->s_root != NULL);
1613 ret = cgroup_get_rootdir(sb);
1614 if (ret)
1615 goto drop_new_super;
1616 inode = sb->s_root->d_inode;
1618 mutex_lock(&inode->i_mutex);
1619 mutex_lock(&cgroup_mutex);
1620 mutex_lock(&cgroup_root_mutex);
1622 /* Check for name clashes with existing mounts */
1623 ret = -EBUSY;
1624 if (strlen(root->name))
1625 for_each_active_root(existing_root)
1626 if (!strcmp(existing_root->name, root->name))
1627 goto unlock_drop;
1629 /*
1630 * We're accessing css_set_count without locking
1631 * css_set_lock here, but that's OK - it can only be
1632 * increased by someone holding cgroup_lock, and
1633 * that's us. The worst that can happen is that we
1634 * have some link structures left over
1635 */
1636 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
1637 if (ret)
1638 goto unlock_drop;
1640 ret = rebind_subsystems(root, root->subsys_mask);
1641 if (ret == -EBUSY) {
1642 free_cg_links(&tmp_cg_links);
1643 goto unlock_drop;
1644 }
1645 /*
1646 * There must be no failure case after here, since rebinding
1647 * takes care of subsystems' refcounts, which are explicitly
1648 * dropped in the failure exit path.
1649 */
1651 /* EBUSY should be the only error here */
1652 BUG_ON(ret);
1654 list_add(&root->root_list, &roots);
1655 root_count++;
1657 sb->s_root->d_fsdata = root_cgrp;
1658 root->top_cgroup.dentry = sb->s_root;
1660 /* Link the top cgroup in this hierarchy into all
1661 * the css_set objects */
1662 write_lock(&css_set_lock);
1663 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
1664 struct hlist_head *hhead = &css_set_table[i];
1665 struct hlist_node *node;
1666 struct css_set *cg;
1668 hlist_for_each_entry(cg, node, hhead, hlist)
1669 link_css_set(&tmp_cg_links, cg, root_cgrp);
1670 }
1671 write_unlock(&css_set_lock);
1673 free_cg_links(&tmp_cg_links);
1675 BUG_ON(!list_empty(&root_cgrp->children));
1676 BUG_ON(root->number_of_cgroups != 1);
1678 cred = override_creds(&init_cred);
1679 cgroup_populate_dir(root_cgrp, true, root->subsys_mask);
1680 revert_creds(cred);
1681 mutex_unlock(&cgroup_root_mutex);
1682 mutex_unlock(&cgroup_mutex);
1683 mutex_unlock(&inode->i_mutex);
1684 } else {
1685 /*
1686 * We re-used an existing hierarchy - the new root (if
1687 * any) is not needed
1688 */
1689 cgroup_drop_root(opts.new_root);
1690 /* no subsys rebinding, so refcounts don't change */
1691 drop_parsed_module_refcounts(opts.subsys_mask);
1692 }
1694 kfree(opts.release_agent);
1695 kfree(opts.name);
1696 return dget(sb->s_root);
1698 unlock_drop:
1699 mutex_unlock(&cgroup_root_mutex);
1700 mutex_unlock(&cgroup_mutex);
1701 mutex_unlock(&inode->i_mutex);
1702 drop_new_super:
1703 deactivate_locked_super(sb);
1704 drop_modules:
1705 drop_parsed_module_refcounts(opts.subsys_mask);
1706 out_err:
1707 kfree(opts.release_agent);
1708 kfree(opts.name);
1709 return ERR_PTR(ret);
1710 }
1712 static void cgroup_kill_sb(struct super_block *sb) {
1713 struct cgroupfs_root *root = sb->s_fs_info;
1714 struct cgroup *cgrp = &root->top_cgroup;
1715 int ret;
1716 struct cg_cgroup_link *link;
1717 struct cg_cgroup_link *saved_link;
1719 BUG_ON(!root);
1721 BUG_ON(root->number_of_cgroups != 1);
1722 BUG_ON(!list_empty(&cgrp->children));
1724 mutex_lock(&cgroup_mutex);
1725 mutex_lock(&cgroup_root_mutex);
1727 /* Rebind all subsystems back to the default hierarchy */
1728 ret = rebind_subsystems(root, 0);
1729 /* Shouldn't be able to fail ... */
1730 BUG_ON(ret);
1732 /*
1733 * Release all the links from css_sets to this hierarchy's
1734 * root cgroup
1735 */
1736 write_lock(&css_set_lock);
1738 list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1739 cgrp_link_list) {
1740 list_del(&link->cg_link_list);
1741 list_del(&link->cgrp_link_list);
1742 kfree(link);
1743 }
1744 write_unlock(&css_set_lock);
1746 if (!list_empty(&root->root_list)) {
1747 list_del(&root->root_list);
1748 root_count--;
1749 }
1751 mutex_unlock(&cgroup_root_mutex);
1752 mutex_unlock(&cgroup_mutex);
1754 simple_xattrs_free(&cgrp->xattrs);
1756 kill_litter_super(sb);
1757 cgroup_drop_root(root);
1758 }
1760 static struct file_system_type cgroup_fs_type = {
1761 .name = "cgroup",
1762 .mount = cgroup_mount,
1763 .kill_sb = cgroup_kill_sb,
1764 };
1766 static struct kobject *cgroup_kobj;
1768 /**
1769 * cgroup_path - generate the path of a cgroup
1770 * @cgrp: the cgroup in question
1771 * @buf: the buffer to write the path into
1772 * @buflen: the length of the buffer
1773 *
1774 * Called with cgroup_mutex held or else with an RCU-protected cgroup
1775 * reference. Writes path of cgroup into buf. Returns 0 on success,
1776 * -errno on error.
1777 */
1778 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1779 {
1780 struct dentry *dentry = cgrp->dentry;
1781 char *start;
1783 rcu_lockdep_assert(rcu_read_lock_held() || cgroup_lock_is_held(),
1784 "cgroup_path() called without proper locking");
1786 if (!dentry || cgrp == dummytop) {
1787 /*
1788 * Inactive subsystems have no dentry for their root
1789 * cgroup
1790 */
1791 strcpy(buf, "/");
1792 return 0;
1793 }
1795 start = buf + buflen - 1;
1797 *start = '\0';
1798 for (;;) {
1799 int len = dentry->d_name.len;
1801 if ((start -= len) < buf)
1802 return -ENAMETOOLONG;
1803 memcpy(start, dentry->d_name.name, len);
1804 cgrp = cgrp->parent;
1805 if (!cgrp)
1806 break;
1808 dentry = cgrp->dentry;
1809 if (!cgrp->parent)
1810 continue;
1811 if (--start < buf)
1812 return -ENAMETOOLONG;
1813 *start = '/';
1814 }
1815 memmove(buf, start, buf + buflen - start);
1816 return 0;
1817 }
1818 EXPORT_SYMBOL_GPL(cgroup_path);
1820 /*
1821 * Control Group taskset
1822 */
1823 struct task_and_cgroup {
1824 struct task_struct *task;
1825 struct cgroup *cgrp;
1826 struct css_set *cg;
1827 };
1829 struct cgroup_taskset {
1830 struct task_and_cgroup single;
1831 struct flex_array *tc_array;
1832 int tc_array_len;
1833 int idx;
1834 struct cgroup *cur_cgrp;
1835 };
1837 /**
1838 * cgroup_taskset_first - reset taskset and return the first task
1839 * @tset: taskset of interest
1840 *
1841 * @tset iteration is initialized and the first task is returned.
1842 */
1843 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1844 {
1845 if (tset->tc_array) {
1846 tset->idx = 0;
1847 return cgroup_taskset_next(tset);
1848 } else {
1849 tset->cur_cgrp = tset->single.cgrp;
1850 return tset->single.task;
1851 }
1852 }
1853 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1855 /**
1856 * cgroup_taskset_next - iterate to the next task in taskset
1857 * @tset: taskset of interest
1858 *
1859 * Return the next task in @tset. Iteration must have been initialized
1860 * with cgroup_taskset_first().
1861 */
1862 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1863 {
1864 struct task_and_cgroup *tc;
1866 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1867 return NULL;
1869 tc = flex_array_get(tset->tc_array, tset->idx++);
1870 tset->cur_cgrp = tc->cgrp;
1871 return tc->task;
1872 }
1873 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1875 /**
1876 * cgroup_taskset_cur_cgroup - return the matching cgroup for the current task
1877 * @tset: taskset of interest
1878 *
1879 * Return the cgroup for the current (last returned) task of @tset. This
1880 * function must be preceded by either cgroup_taskset_first() or
1881 * cgroup_taskset_next().
1882 */
1883 struct cgroup *cgroup_taskset_cur_cgroup(struct cgroup_taskset *tset)
1884 {
1885 return tset->cur_cgrp;
1886 }
1887 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_cgroup);
1889 /**
1890 * cgroup_taskset_size - return the number of tasks in taskset
1891 * @tset: taskset of interest
1892 */
1893 int cgroup_taskset_size(struct cgroup_taskset *tset)
1894 {
1895 return tset->tc_array ? tset->tc_array_len : 1;
1896 }
1897 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1900 /*
1901 * cgroup_task_migrate - move a task from one cgroup to another.
1902 *
1903 * Must be called with cgroup_mutex and threadgroup locked.
1904 */
1905 static void cgroup_task_migrate(struct cgroup *cgrp, struct cgroup *oldcgrp,
1906 struct task_struct *tsk, struct css_set *newcg)
1907 {
1908 struct css_set *oldcg;
1910 /*
1911 * We are synchronized through threadgroup_lock() against PF_EXITING
1912 * setting such that we can't race against cgroup_exit() changing the
1913 * css_set to init_css_set and dropping the old one.
1914 */
1915 WARN_ON_ONCE(tsk->flags & PF_EXITING);
1916 oldcg = tsk->cgroups;
1918 task_lock(tsk);
1919 rcu_assign_pointer(tsk->cgroups, newcg);
1920 task_unlock(tsk);
1922 /* Update the css_set linked lists if we're using them */
1923 write_lock(&css_set_lock);
1924 if (!list_empty(&tsk->cg_list))
1925 list_move(&tsk->cg_list, &newcg->tasks);
1926 write_unlock(&css_set_lock);
1928 /*
1929 * We just gained a reference on oldcg by taking it from the task. As
1930 * trading it for newcg is protected by cgroup_mutex, we're safe to drop
1931 * it here; it will be freed under RCU.
1932 */
1933 set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1934 put_css_set(oldcg);
1935 }
1937 /**
1938 * cgroup_attach_task - attach task 'tsk' to cgroup 'cgrp'
1939 * @cgrp: the cgroup the task is attaching to
1940 * @tsk: the task to be attached
1941 *
1942 * Call with cgroup_mutex and threadgroup locked. May take task_lock of
1943 * @tsk during call.
1944 */
1945 int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
1946 {
1947 int retval = 0;
1948 struct cgroup_subsys *ss, *failed_ss = NULL;
1949 struct cgroup *oldcgrp;
1950 struct cgroupfs_root *root = cgrp->root;
1951 struct cgroup_taskset tset = { };
1952 struct css_set *newcg;
1954 /* @tsk either already exited or can't exit until the end */
1955 if (tsk->flags & PF_EXITING)
1956 return -ESRCH;
1958 /* Nothing to do if the task is already in that cgroup */
1959 oldcgrp = task_cgroup_from_root(tsk, root);
1960 if (cgrp == oldcgrp)
1961 return 0;
1963 tset.single.task = tsk;
1964 tset.single.cgrp = oldcgrp;
1966 for_each_subsys(root, ss) {
1967 if (ss->can_attach) {
1968 retval = ss->can_attach(cgrp, &tset);
1969 if (retval) {
1970 /*
1971 * Remember on which subsystem the can_attach()
1972 * failed, so that we only call cancel_attach()
1973 * against the subsystems whose can_attach()
1974 * succeeded. (See below)
1975 */
1976 failed_ss = ss;
1977 goto out;
1978 }
1979 }
1980 }
1982 newcg = find_css_set(tsk->cgroups, cgrp);
1983 if (!newcg) {
1984 retval = -ENOMEM;
1985 goto out;
1986 }
1988 cgroup_task_migrate(cgrp, oldcgrp, tsk, newcg);
1990 for_each_subsys(root, ss) {
1991 if (ss->attach)
1992 ss->attach(cgrp, &tset);
1993 }
1995 synchronize_rcu();
1996 out:
1997 if (retval) {
1998 for_each_subsys(root, ss) {
1999 if (ss == failed_ss)
2000 /*
2001 * This subsystem was the one that failed the
2002 * can_attach() check earlier, so we don't need
2003 * to call cancel_attach() against it or any
2004 * remaining subsystems.
2005 */
2006 break;
2007 if (ss->cancel_attach)
2008 ss->cancel_attach(cgrp, &tset);
2009 }
2010 }
2011 return retval;
2012 }
2014 /**
2015 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2016 * @from: attach to all cgroups of a given task
2017 * @tsk: the task to be attached
2018 */
2019 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2020 {
2021 struct cgroupfs_root *root;
2022 int retval = 0;
2024 cgroup_lock();
2025 for_each_active_root(root) {
2026 struct cgroup *from_cg = task_cgroup_from_root(from, root);
2028 retval = cgroup_attach_task(from_cg, tsk);
2029 if (retval)
2030 break;
2031 }
2032 cgroup_unlock();
2034 return retval;
2035 }
2036 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2038 /**
2039 * cgroup_attach_proc - attach all threads in a threadgroup to a cgroup
2040 * @cgrp: the cgroup to attach to
2041 * @leader: the threadgroup leader task_struct of the group to be attached
2042 *
2043 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
2044 * task_lock of each thread in leader's threadgroup individually in turn.
2045 */
2046 static int cgroup_attach_proc(struct cgroup *cgrp, struct task_struct *leader)
2047 {
2048 int retval, i, group_size;
2049 struct cgroup_subsys *ss, *failed_ss = NULL;
2050 /* guaranteed to be initialized later, but the compiler needs this */
2051 struct cgroupfs_root *root = cgrp->root;
2052 /* threadgroup list cursor and array */
2053 struct task_struct *tsk;
2054 struct task_and_cgroup *tc;
2055 struct flex_array *group;
2056 struct cgroup_taskset tset = { };
2058 /*
2059 * step 0: in order to do expensive, possibly blocking operations for
2060 * every thread, we cannot iterate the thread group list, since it needs
2061 * rcu or tasklist locked. instead, build an array of all threads in the
2062 * group - group_rwsem prevents new threads from appearing, and if
2063 * threads exit, this will just be an over-estimate.
2064 */
2065 group_size = get_nr_threads(leader);
2066 /* flex_array supports very large thread-groups better than kmalloc. */
2067 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
2068 if (!group)
2069 return -ENOMEM;
2070 /* pre-allocate to guarantee space while iterating in rcu read-side. */
2071 retval = flex_array_prealloc(group, 0, group_size, GFP_KERNEL);
2072 if (retval)
2073 goto out_free_group_list;
2075 tsk = leader;
2076 i = 0;
2077 /*
2078 * Prevent freeing of tasks while we take a snapshot. Tasks that are
2079 * already PF_EXITING could be freed from underneath us unless we
2080 * take an rcu_read_lock.
2081 */
2082 rcu_read_lock();
2083 do {
2084 struct task_and_cgroup ent;
2086 /* @tsk either already exited or can't exit until the end */
2087 if (tsk->flags & PF_EXITING)
2088 continue;
2090 /* as per above, nr_threads may decrease, but not increase. */
2091 BUG_ON(i >= group_size);
2092 ent.task = tsk;
2093 ent.cgrp = task_cgroup_from_root(tsk, root);
2094 /* nothing to do if this task is already in the cgroup */
2095 if (ent.cgrp == cgrp)
2096 continue;
2097 /*
2098 * saying GFP_ATOMIC has no effect here because we did prealloc
2099 * earlier, but it's good form to communicate our expectations.
2100 */
2101 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
2102 BUG_ON(retval != 0);
2103 i++;
2104 } while_each_thread(leader, tsk);
2105 rcu_read_unlock();
2106 /* remember the number of threads in the array for later. */
2107 group_size = i;
2108 tset.tc_array = group;
2109 tset.tc_array_len = group_size;
2111 /* methods shouldn't be called if no task is actually migrating */
2112 retval = 0;
2113 if (!group_size)
2114 goto out_free_group_list;
2116 /*
2117 * step 1: check that we can legitimately attach to the cgroup.
2118 */
2119 for_each_subsys(root, ss) {
2120 if (ss->can_attach) {
2121 retval = ss->can_attach(cgrp, &tset);
2122 if (retval) {
2123 failed_ss = ss;
2124 goto out_cancel_attach;
2125 }
2126 }
2127 }
2129 /*
2130 * step 2: make sure css_sets exist for all threads to be migrated.
2131 * we use find_css_set, which allocates a new one if necessary.
2132 */
2133 for (i = 0; i < group_size; i++) {
2134 tc = flex_array_get(group, i);
2135 tc->cg = find_css_set(tc->task->cgroups, cgrp);
2136 if (!tc->cg) {
2137 retval = -ENOMEM;
2138 goto out_put_css_set_refs;
2139 }
2140 }
2142 /*
2143 * step 3: now that we're guaranteed success wrt the css_sets,
2144 * proceed to move all tasks to the new cgroup. There are no
2145 * failure cases after here, so this is the commit point.
2146 */
2147 for (i = 0; i < group_size; i++) {
2148 tc = flex_array_get(group, i);
2149 cgroup_task_migrate(cgrp, tc->cgrp, tc->task, tc->cg);
2150 }
2151 /* nothing is sensitive to fork() after this point. */
2153 /*
2154 * step 4: do subsystem attach callbacks.
2155 */
2156 for_each_subsys(root, ss) {
2157 if (ss->attach)
2158 ss->attach(cgrp, &tset);
2159 }
2161 /*
2162 * step 5: success! and cleanup
2163 */
2164 synchronize_rcu();
2165 retval = 0;
2166 out_put_css_set_refs:
2167 if (retval) {
2168 for (i = 0; i < group_size; i++) {
2169 tc = flex_array_get(group, i);
2170 if (!tc->cg)
2171 break;
2172 put_css_set(tc->cg);
2173 }
2174 }
2175 out_cancel_attach:
2176 if (retval) {
2177 for_each_subsys(root, ss) {
2178 if (ss == failed_ss)
2179 break;
2180 if (ss->cancel_attach)
2181 ss->cancel_attach(cgrp, &tset);
2182 }
2183 }
2184 out_free_group_list:
2185 flex_array_free(group);
2186 return retval;
2187 }
2189 /*
2190 * Find the task_struct of the task to attach by vpid and pass it along to the
2191 * function to attach either it or all tasks in its threadgroup. Will lock
2192 * cgroup_mutex and threadgroup; may take task_lock of task.
2193 */
2194 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2195 {
2196 struct task_struct *tsk;
2197 const struct cred *cred = current_cred(), *tcred;
2198 int ret;
2200 if (!cgroup_lock_live_group(cgrp))
2201 return -ENODEV;
2203 retry_find_task:
2204 rcu_read_lock();
2205 if (pid) {
2206 tsk = find_task_by_vpid(pid);
2207 if (!tsk) {
2208 rcu_read_unlock();
2209 ret= -ESRCH;
2210 goto out_unlock_cgroup;
2211 }
2212 /*
2213 * even if we're attaching all tasks in the thread group, we
2214 * only need to check permissions on one of them.
2215 */
2216 tcred = __task_cred(tsk);
2217 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2218 !uid_eq(cred->euid, tcred->uid) &&
2219 !uid_eq(cred->euid, tcred->suid)) {
2220 rcu_read_unlock();
2221 ret = -EACCES;
2222 goto out_unlock_cgroup;
2223 }
2224 } else
2225 tsk = current;
2227 if (threadgroup)
2228 tsk = tsk->group_leader;
2230 /*
2231 * Workqueue threads may acquire PF_THREAD_BOUND and become
2232 * trapped in a cpuset, or RT worker may be born in a cgroup
2233 * with no rt_runtime allocated. Just say no.
2234 */
2235 if (tsk == kthreadd_task || (tsk->flags & PF_THREAD_BOUND)) {
2236 ret = -EINVAL;
2237 rcu_read_unlock();
2238 goto out_unlock_cgroup;
2239 }
2241 get_task_struct(tsk);
2242 rcu_read_unlock();
2244 threadgroup_lock(tsk);
2245 if (threadgroup) {
2246 if (!thread_group_leader(tsk)) {
2247 /*
2248 * a race with de_thread from another thread's exec()
2249 * may strip us of our leadership, if this happens,
2250 * there is no choice but to throw this task away and
2251 * try again; this is
2252 * "double-double-toil-and-trouble-check locking".
2253 */
2254 threadgroup_unlock(tsk);
2255 put_task_struct(tsk);
2256 goto retry_find_task;
2257 }
2258 ret = cgroup_attach_proc(cgrp, tsk);
2259 } else
2260 ret = cgroup_attach_task(cgrp, tsk);
2261 threadgroup_unlock(tsk);
2263 put_task_struct(tsk);
2264 out_unlock_cgroup:
2265 cgroup_unlock();
2266 return ret;
2267 }
2269 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
2270 {
2271 return attach_task_by_pid(cgrp, pid, false);
2272 }
2274 static int cgroup_procs_write(struct cgroup *cgrp, struct cftype *cft, u64 tgid)
2275 {
2276 return attach_task_by_pid(cgrp, tgid, true);
2277 }
2279 /**
2280 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
2281 * @cgrp: the cgroup to be checked for liveness
2282 *
2283 * On success, returns true; the lock should be later released with
2284 * cgroup_unlock(). On failure returns false with no lock held.
2285 */
2286 bool cgroup_lock_live_group(struct cgroup *cgrp)
2287 {
2288 mutex_lock(&cgroup_mutex);
2289 if (cgroup_is_removed(cgrp)) {
2290 mutex_unlock(&cgroup_mutex);
2291 return false;
2292 }
2293 return true;
2294 }
2295 EXPORT_SYMBOL_GPL(cgroup_lock_live_group);
2297 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
2298 const char *buffer)
2299 {
2300 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
2301 if (strlen(buffer) >= PATH_MAX)
2302 return -EINVAL;
2303 if (!cgroup_lock_live_group(cgrp))
2304 return -ENODEV;
2305 mutex_lock(&cgroup_root_mutex);
2306 strcpy(cgrp->root->release_agent_path, buffer);
2307 mutex_unlock(&cgroup_root_mutex);
2308 cgroup_unlock();
2309 return 0;
2310 }
2312 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
2313 struct seq_file *seq)
2314 {
2315 if (!cgroup_lock_live_group(cgrp))
2316 return -ENODEV;
2317 seq_puts(seq, cgrp->root->release_agent_path);
2318 seq_putc(seq, '\n');
2319 cgroup_unlock();
2320 return 0;
2321 }
2323 /* A buffer size big enough for numbers or short strings */
2324 #define CGROUP_LOCAL_BUFFER_SIZE 64
2326 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
2327 struct file *file,
2328 const char __user *userbuf,
2329 size_t nbytes, loff_t *unused_ppos)
2330 {
2331 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
2332 int retval = 0;
2333 char *end;
2335 if (!nbytes)
2336 return -EINVAL;
2337 if (nbytes >= sizeof(buffer))
2338 return -E2BIG;
2339 if (copy_from_user(buffer, userbuf, nbytes))
2340 return -EFAULT;
2342 buffer[nbytes] = 0; /* nul-terminate */
2343 if (cft->write_u64) {
2344 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
2345 if (*end)
2346 return -EINVAL;
2347 retval = cft->write_u64(cgrp, cft, val);
2348 } else {
2349 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
2350 if (*end)
2351 return -EINVAL;
2352 retval = cft->write_s64(cgrp, cft, val);
2353 }
2354 if (!retval)
2355 retval = nbytes;
2356 return retval;
2357 }
2359 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
2360 struct file *file,
2361 const char __user *userbuf,
2362 size_t nbytes, loff_t *unused_ppos)
2363 {
2364 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
2365 int retval = 0;
2366 size_t max_bytes = cft->max_write_len;
2367 char *buffer = local_buffer;
2369 if (!max_bytes)
2370 max_bytes = sizeof(local_buffer) - 1;
2371 if (nbytes >= max_bytes)
2372 return -E2BIG;
2373 /* Allocate a dynamic buffer if we need one */
2374 if (nbytes >= sizeof(local_buffer)) {
2375 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2376 if (buffer == NULL)
2377 return -ENOMEM;
2378 }
2379 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2380 retval = -EFAULT;
2381 goto out;
2382 }
2384 buffer[nbytes] = 0; /* nul-terminate */
2385 retval = cft->write_string(cgrp, cft, strstrip(buffer));
2386 if (!retval)
2387 retval = nbytes;
2388 out:
2389 if (buffer != local_buffer)
2390 kfree(buffer);
2391 return retval;
2392 }
2394 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2395 size_t nbytes, loff_t *ppos)
2396 {
2397 struct cftype *cft = __d_cft(file->f_dentry);
2398 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2400 if (cgroup_is_removed(cgrp))
2401 return -ENODEV;
2402 if (cft->write)
2403 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
2404 if (cft->write_u64 || cft->write_s64)
2405 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
2406 if (cft->write_string)
2407 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
2408 if (cft->trigger) {
2409 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
2410 return ret ? ret : nbytes;
2411 }
2412 return -EINVAL;
2413 }
2415 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
2416 struct file *file,
2417 char __user *buf, size_t nbytes,
2418 loff_t *ppos)
2419 {
2420 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2421 u64 val = cft->read_u64(cgrp, cft);
2422 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2424 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2425 }
2427 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
2428 struct file *file,
2429 char __user *buf, size_t nbytes,
2430 loff_t *ppos)
2431 {
2432 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2433 s64 val = cft->read_s64(cgrp, cft);
2434 int len = sprintf(tmp, "%lld\n", (long long) val);
2436 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2437 }
2439 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2440 size_t nbytes, loff_t *ppos)
2441 {
2442 struct cftype *cft = __d_cft(file->f_dentry);
2443 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2445 if (cgroup_is_removed(cgrp))
2446 return -ENODEV;
2448 if (cft->read)
2449 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
2450 if (cft->read_u64)
2451 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
2452 if (cft->read_s64)
2453 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
2454 return -EINVAL;
2455 }
2457 /*
2458 * seqfile ops/methods for returning structured data. Currently just
2459 * supports string->u64 maps, but can be extended in future.
2460 */
2462 struct cgroup_seqfile_state {
2463 struct cftype *cft;
2464 struct cgroup *cgroup;
2465 };
2467 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2468 {
2469 struct seq_file *sf = cb->state;
2470 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2471 }
2473 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2474 {
2475 struct cgroup_seqfile_state *state = m->private;
2476 struct cftype *cft = state->cft;
2477 if (cft->read_map) {
2478 struct cgroup_map_cb cb = {
2479 .fill = cgroup_map_add,
2480 .state = m,
2481 };
2482 return cft->read_map(state->cgroup, cft, &cb);
2483 }
2484 return cft->read_seq_string(state->cgroup, cft, m);
2485 }
2487 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
2488 {
2489 struct seq_file *seq = file->private_data;
2490 kfree(seq->private);
2491 return single_release(inode, file);
2492 }
2494 static const struct file_operations cgroup_seqfile_operations = {
2495 .read = seq_read,
2496 .write = cgroup_file_write,
2497 .llseek = seq_lseek,
2498 .release = cgroup_seqfile_release,
2499 };
2501 static int cgroup_file_open(struct inode *inode, struct file *file)
2502 {
2503 int err;
2504 struct cftype *cft;
2506 err = generic_file_open(inode, file);
2507 if (err)
2508 return err;
2509 cft = __d_cft(file->f_dentry);
2511 if (cft->read_map || cft->read_seq_string) {
2512 struct cgroup_seqfile_state *state =
2513 kzalloc(sizeof(*state), GFP_USER);
2514 if (!state)
2515 return -ENOMEM;
2516 state->cft = cft;
2517 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
2518 file->f_op = &cgroup_seqfile_operations;
2519 err = single_open(file, cgroup_seqfile_show, state);
2520 if (err < 0)
2521 kfree(state);
2522 } else if (cft->open)
2523 err = cft->open(inode, file);
2524 else
2525 err = 0;
2527 return err;
2528 }
2530 static int cgroup_file_release(struct inode *inode, struct file *file)
2531 {
2532 struct cftype *cft = __d_cft(file->f_dentry);
2533 if (cft->release)
2534 return cft->release(inode, file);
2535 return 0;
2536 }
2538 /*
2539 * cgroup_rename - Only allow simple rename of directories in place.
2540 */
2541 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2542 struct inode *new_dir, struct dentry *new_dentry)
2543 {
2544 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2545 return -ENOTDIR;
2546 if (new_dentry->d_inode)
2547 return -EEXIST;
2548 if (old_dir != new_dir)
2549 return -EIO;
2550 return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2551 }
2553 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2554 {
2555 if (S_ISDIR(dentry->d_inode->i_mode))
2556 return &__d_cgrp(dentry)->xattrs;
2557 else
2558 return &__d_cfe(dentry)->xattrs;
2559 }
2561 static inline int xattr_enabled(struct dentry *dentry)
2562 {
2563 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2564 return test_bit(ROOT_XATTR, &root->flags);
2565 }
2567 static bool is_valid_xattr(const char *name)
2568 {
2569 if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2570 !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2571 return true;
2572 return false;
2573 }
2575 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2576 const void *val, size_t size, int flags)
2577 {
2578 if (!xattr_enabled(dentry))
2579 return -EOPNOTSUPP;
2580 if (!is_valid_xattr(name))
2581 return -EINVAL;
2582 return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2583 }
2585 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2586 {
2587 if (!xattr_enabled(dentry))
2588 return -EOPNOTSUPP;
2589 if (!is_valid_xattr(name))
2590 return -EINVAL;
2591 return simple_xattr_remove(__d_xattrs(dentry), name);
2592 }
2594 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2595 void *buf, size_t size)
2596 {
2597 if (!xattr_enabled(dentry))
2598 return -EOPNOTSUPP;
2599 if (!is_valid_xattr(name))
2600 return -EINVAL;
2601 return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2602 }
2604 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2605 {
2606 if (!xattr_enabled(dentry))
2607 return -EOPNOTSUPP;
2608 return simple_xattr_list(__d_xattrs(dentry), buf, size);
2609 }
2611 static const struct file_operations cgroup_file_operations = {
2612 .read = cgroup_file_read,
2613 .write = cgroup_file_write,
2614 .llseek = generic_file_llseek,
2615 .open = cgroup_file_open,
2616 .release = cgroup_file_release,
2617 };
2619 static const struct inode_operations cgroup_file_inode_operations = {
2620 .setxattr = cgroup_setxattr,
2621 .getxattr = cgroup_getxattr,
2622 .listxattr = cgroup_listxattr,
2623 .removexattr = cgroup_removexattr,
2624 };
2626 static const struct inode_operations cgroup_dir_inode_operations = {
2627 .lookup = cgroup_lookup,
2628 .mkdir = cgroup_mkdir,
2629 .rmdir = cgroup_rmdir,
2630 .rename = cgroup_rename,
2631 .setxattr = cgroup_setxattr,
2632 .getxattr = cgroup_getxattr,
2633 .listxattr = cgroup_listxattr,
2634 .removexattr = cgroup_removexattr,
2635 };
2637 static struct dentry *cgroup_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
2638 {
2639 if (dentry->d_name.len > NAME_MAX)
2640 return ERR_PTR(-ENAMETOOLONG);
2641 d_add(dentry, NULL);
2642 return NULL;
2643 }
2645 /*
2646 * Check if a file is a control file
2647 */
2648 static inline struct cftype *__file_cft(struct file *file)
2649 {
2650 if (file->f_dentry->d_inode->i_fop != &cgroup_file_operations)
2651 return ERR_PTR(-EINVAL);
2652 return __d_cft(file->f_dentry);
2653 }
2655 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2656 struct super_block *sb)
2657 {
2658 struct inode *inode;
2660 if (!dentry)
2661 return -ENOENT;
2662 if (dentry->d_inode)
2663 return -EEXIST;
2665 inode = cgroup_new_inode(mode, sb);
2666 if (!inode)
2667 return -ENOMEM;
2669 if (S_ISDIR(mode)) {
2670 inode->i_op = &cgroup_dir_inode_operations;
2671 inode->i_fop = &simple_dir_operations;
2673 /* start off with i_nlink == 2 (for "." entry) */
2674 inc_nlink(inode);
2675 inc_nlink(dentry->d_parent->d_inode);
2677 /*
2678 * Control reaches here with cgroup_mutex held.
2679 * @inode->i_mutex should nest outside cgroup_mutex but we
2680 * want to populate it immediately without releasing
2681 * cgroup_mutex. As @inode isn't visible to anyone else
2682 * yet, trylock will always succeed without affecting
2683 * lockdep checks.
2684 */
2685 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2686 } else if (S_ISREG(mode)) {
2687 inode->i_size = 0;
2688 inode->i_fop = &cgroup_file_operations;
2689 inode->i_op = &cgroup_file_inode_operations;
2690 }
2691 d_instantiate(dentry, inode);
2692 dget(dentry); /* Extra count - pin the dentry in core */
2693 return 0;
2694 }
2696 /**
2697 * cgroup_file_mode - deduce file mode of a control file
2698 * @cft: the control file in question
2699 *
2700 * returns cft->mode if ->mode is not 0
2701 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2702 * returns S_IRUGO if it has only a read handler
2703 * returns S_IWUSR if it has only a write hander
2704 */
2705 static umode_t cgroup_file_mode(const struct cftype *cft)
2706 {
2707 umode_t mode = 0;
2709 if (cft->mode)
2710 return cft->mode;
2712 if (cft->read || cft->read_u64 || cft->read_s64 ||
2713 cft->read_map || cft->read_seq_string)
2714 mode |= S_IRUGO;
2716 if (cft->write || cft->write_u64 || cft->write_s64 ||
2717 cft->write_string || cft->trigger)
2718 mode |= S_IWUSR;
2720 return mode;
2721 }
2723 static int cgroup_add_file(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2724 struct cftype *cft)
2725 {
2726 struct dentry *dir = cgrp->dentry;
2727 struct cgroup *parent = __d_cgrp(dir);
2728 struct dentry *dentry;
2729 struct cfent *cfe;
2730 int error;
2731 umode_t mode;
2732 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2734 if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) {
2735 strcpy(name, subsys->name);
2736 strcat(name, ".");
2737 }
2738 strcat(name, cft->name);
2740 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2742 cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2743 if (!cfe)
2744 return -ENOMEM;
2746 dentry = lookup_one_len(name, dir, strlen(name));
2747 if (IS_ERR(dentry)) {
2748 error = PTR_ERR(dentry);
2749 goto out;
2750 }
2752 mode = cgroup_file_mode(cft);
2753 error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2754 if (!error) {
2755 cfe->type = (void *)cft;
2756 cfe->dentry = dentry;
2757 dentry->d_fsdata = cfe;
2758 simple_xattrs_init(&cfe->xattrs);
2759 list_add_tail(&cfe->node, &parent->files);
2760 cfe = NULL;
2761 }
2762 dput(dentry);
2763 out:
2764 kfree(cfe);
2765 return error;
2766 }
2768 static int cgroup_addrm_files(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2769 struct cftype cfts[], bool is_add)
2770 {
2771 struct cftype *cft;
2772 int err, ret = 0;
2774 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2775 /* does cft->flags tell us to skip this file on @cgrp? */
2776 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2777 continue;
2778 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2779 continue;
2781 if (is_add)
2782 err = cgroup_add_file(cgrp, subsys, cft);
2783 else
2784 err = cgroup_rm_file(cgrp, cft);
2785 if (err) {
2786 pr_warning("cgroup_addrm_files: failed to %s %s, err=%d\n",
2787 is_add ? "add" : "remove", cft->name, err);
2788 ret = err;
2789 }
2790 }
2791 return ret;
2792 }
2794 static DEFINE_MUTEX(cgroup_cft_mutex);
2796 static void cgroup_cfts_prepare(void)
2797 __acquires(&cgroup_cft_mutex) __acquires(&cgroup_mutex)
2798 {
2799 /*
2800 * Thanks to the entanglement with vfs inode locking, we can't walk
2801 * the existing cgroups under cgroup_mutex and create files.
2802 * Instead, we increment reference on all cgroups and build list of
2803 * them using @cgrp->cft_q_node. Grab cgroup_cft_mutex to ensure
2804 * exclusive access to the field.
2805 */
2806 mutex_lock(&cgroup_cft_mutex);
2807 mutex_lock(&cgroup_mutex);
2808 }
2810 static void cgroup_cfts_commit(struct cgroup_subsys *ss,
2811 struct cftype *cfts, bool is_add)
2812 __releases(&cgroup_mutex) __releases(&cgroup_cft_mutex)
2813 {
2814 LIST_HEAD(pending);
2815 struct cgroup *cgrp, *n;
2817 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2818 if (cfts && ss->root != &rootnode) {
2819 list_for_each_entry(cgrp, &ss->root->allcg_list, allcg_node) {
2820 dget(cgrp->dentry);
2821 list_add_tail(&cgrp->cft_q_node, &pending);
2822 }
2823 }
2825 mutex_unlock(&cgroup_mutex);
2827 /*
2828 * All new cgroups will see @cfts update on @ss->cftsets. Add/rm
2829 * files for all cgroups which were created before.
2830 */
2831 list_for_each_entry_safe(cgrp, n, &pending, cft_q_node) {
2832 struct inode *inode = cgrp->dentry->d_inode;
2834 mutex_lock(&inode->i_mutex);
2835 mutex_lock(&cgroup_mutex);
2836 if (!cgroup_is_removed(cgrp))
2837 cgroup_addrm_files(cgrp, ss, cfts, is_add);
2838 mutex_unlock(&cgroup_mutex);
2839 mutex_unlock(&inode->i_mutex);
2841 list_del_init(&cgrp->cft_q_node);
2842 dput(cgrp->dentry);
2843 }
2845 mutex_unlock(&cgroup_cft_mutex);
2846 }
2848 /**
2849 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2850 * @ss: target cgroup subsystem
2851 * @cfts: zero-length name terminated array of cftypes
2852 *
2853 * Register @cfts to @ss. Files described by @cfts are created for all
2854 * existing cgroups to which @ss is attached and all future cgroups will
2855 * have them too. This function can be called anytime whether @ss is
2856 * attached or not.
2857 *
2858 * Returns 0 on successful registration, -errno on failure. Note that this
2859 * function currently returns 0 as long as @cfts registration is successful
2860 * even if some file creation attempts on existing cgroups fail.
2861 */
2862 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2863 {
2864 struct cftype_set *set;
2866 set = kzalloc(sizeof(*set), GFP_KERNEL);
2867 if (!set)
2868 return -ENOMEM;
2870 cgroup_cfts_prepare();
2871 set->cfts = cfts;
2872 list_add_tail(&set->node, &ss->cftsets);
2873 cgroup_cfts_commit(ss, cfts, true);
2875 return 0;
2876 }
2877 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2879 /**
2880 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2881 * @ss: target cgroup subsystem
2882 * @cfts: zero-length name terminated array of cftypes
2883 *
2884 * Unregister @cfts from @ss. Files described by @cfts are removed from
2885 * all existing cgroups to which @ss is attached and all future cgroups
2886 * won't have them either. This function can be called anytime whether @ss
2887 * is attached or not.
2888 *
2889 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2890 * registered with @ss.
2891 */
2892 int cgroup_rm_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2893 {
2894 struct cftype_set *set;
2896 cgroup_cfts_prepare();
2898 list_for_each_entry(set, &ss->cftsets, node) {
2899 if (set->cfts == cfts) {
2900 list_del_init(&set->node);
2901 cgroup_cfts_commit(ss, cfts, false);
2902 return 0;
2903 }
2904 }
2906 cgroup_cfts_commit(ss, NULL, false);
2907 return -ENOENT;
2908 }
2910 /**
2911 * cgroup_task_count - count the number of tasks in a cgroup.
2912 * @cgrp: the cgroup in question
2913 *
2914 * Return the number of tasks in the cgroup.
2915 */
2916 int cgroup_task_count(const struct cgroup *cgrp)
2917 {
2918 int count = 0;
2919 struct cg_cgroup_link *link;
2921 read_lock(&css_set_lock);
2922 list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
2923 count += atomic_read(&link->cg->refcount);
2924 }
2925 read_unlock(&css_set_lock);
2926 return count;
2927 }
2929 /*
2930 * Advance a list_head iterator. The iterator should be positioned at
2931 * the start of a css_set
2932 */
2933 static void cgroup_advance_iter(struct cgroup *cgrp,
2934 struct cgroup_iter *it)
2935 {
2936 struct list_head *l = it->cg_link;
2937 struct cg_cgroup_link *link;
2938 struct css_set *cg;
2940 /* Advance to the next non-empty css_set */
2941 do {
2942 l = l->next;
2943 if (l == &cgrp->css_sets) {
2944 it->cg_link = NULL;
2945 return;
2946 }
2947 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
2948 cg = link->cg;
2949 } while (list_empty(&cg->tasks));
2950 it->cg_link = l;
2951 it->task = cg->tasks.next;
2952 }
2954 /*
2955 * To reduce the fork() overhead for systems that are not actually
2956 * using their cgroups capability, we don't maintain the lists running
2957 * through each css_set to its tasks until we see the list actually
2958 * used - in other words after the first call to cgroup_iter_start().
2959 */
2960 static void cgroup_enable_task_cg_lists(void)
2961 {
2962 struct task_struct *p, *g;
2963 write_lock(&css_set_lock);
2964 use_task_css_set_links = 1;
2965 /*
2966 * We need tasklist_lock because RCU is not safe against
2967 * while_each_thread(). Besides, a forking task that has passed
2968 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2969 * is not guaranteed to have its child immediately visible in the
2970 * tasklist if we walk through it with RCU.
2971 */
2972 read_lock(&tasklist_lock);
2973 do_each_thread(g, p) {
2974 task_lock(p);
2975 /*
2976 * We should check if the process is exiting, otherwise
2977 * it will race with cgroup_exit() in that the list
2978 * entry won't be deleted though the process has exited.
2979 */
2980 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2981 list_add(&p->cg_list, &p->cgroups->tasks);
2982 task_unlock(p);
2983 } while_each_thread(g, p);
2984 read_unlock(&tasklist_lock);
2985 write_unlock(&css_set_lock);
2986 }
2988 /**
2989 * cgroup_next_descendant_pre - find the next descendant for pre-order walk
2990 * @pos: the current position (%NULL to initiate traversal)
2991 * @cgroup: cgroup whose descendants to walk
2992 *
2993 * To be used by cgroup_for_each_descendant_pre(). Find the next
2994 * descendant to visit for pre-order traversal of @cgroup's descendants.
2995 */
2996 struct cgroup *cgroup_next_descendant_pre(struct cgroup *pos,
2997 struct cgroup *cgroup)
2998 {
2999 struct cgroup *next;
3001 WARN_ON_ONCE(!rcu_read_lock_held());
3003 /* if first iteration, pretend we just visited @cgroup */
3004 if (!pos) {
3005 if (list_empty(&cgroup->children))
3006 return NULL;
3007 pos = cgroup;
3008 }
3010 /* visit the first child if exists */
3011 next = list_first_or_null_rcu(&pos->children, struct cgroup, sibling);
3012 if (next)
3013 return next;
3015 /* no child, visit my or the closest ancestor's next sibling */
3016 do {
3017 next = list_entry_rcu(pos->sibling.next, struct cgroup,
3018 sibling);
3019 if (&next->sibling != &pos->parent->children)
3020 return next;
3022 pos = pos->parent;
3023 } while (pos != cgroup);
3025 return NULL;
3026 }
3027 EXPORT_SYMBOL_GPL(cgroup_next_descendant_pre);
3029 static struct cgroup *cgroup_leftmost_descendant(struct cgroup *pos)
3030 {
3031 struct cgroup *last;
3033 do {
3034 last = pos;
3035 pos = list_first_or_null_rcu(&pos->children, struct cgroup,
3036 sibling);
3037 } while (pos);
3039 return last;
3040 }
3042 /**
3043 * cgroup_next_descendant_post - find the next descendant for post-order walk
3044 * @pos: the current position (%NULL to initiate traversal)
3045 * @cgroup: cgroup whose descendants to walk
3046 *
3047 * To be used by cgroup_for_each_descendant_post(). Find the next
3048 * descendant to visit for post-order traversal of @cgroup's descendants.
3049 */
3050 struct cgroup *cgroup_next_descendant_post(struct cgroup *pos,
3051 struct cgroup *cgroup)
3052 {
3053 struct cgroup *next;
3055 WARN_ON_ONCE(!rcu_read_lock_held());
3057 /* if first iteration, visit the leftmost descendant */
3058 if (!pos) {
3059 next = cgroup_leftmost_descendant(cgroup);
3060 return next != cgroup ? next : NULL;
3061 }
3063 /* if there's an unvisited sibling, visit its leftmost descendant */
3064 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3065 if (&next->sibling != &pos->parent->children)
3066 return cgroup_leftmost_descendant(next);
3068 /* no sibling left, visit parent */
3069 next = pos->parent;
3070 return next != cgroup ? next : NULL;
3071 }
3072 EXPORT_SYMBOL_GPL(cgroup_next_descendant_post);
3074 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
3075 __acquires(css_set_lock)
3076 {
3077 /*
3078 * The first time anyone tries to iterate across a cgroup,
3079 * we need to enable the list linking each css_set to its
3080 * tasks, and fix up all existing tasks.
3081 */
3082 if (!use_task_css_set_links)
3083 cgroup_enable_task_cg_lists();
3085 read_lock(&css_set_lock);
3086 it->cg_link = &cgrp->css_sets;
3087 cgroup_advance_iter(cgrp, it);
3088 }
3090 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
3091 struct cgroup_iter *it)
3092 {
3093 struct task_struct *res;
3094 struct list_head *l = it->task;
3095 struct cg_cgroup_link *link;
3097 /* If the iterator cg is NULL, we have no tasks */
3098 if (!it->cg_link)
3099 return NULL;
3100 res = list_entry(l, struct task_struct, cg_list);
3101 /* Advance iterator to find next entry */
3102 l = l->next;
3103 link = list_entry(it->cg_link, struct cg_cgroup_link, cgrp_link_list);
3104 if (l == &link->cg->tasks) {
3105 /* We reached the end of this task list - move on to
3106 * the next cg_cgroup_link */
3107 cgroup_advance_iter(cgrp, it);
3108 } else {
3109 it->task = l;
3110 }
3111 return res;
3112 }
3114 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
3115 __releases(css_set_lock)
3116 {
3117 read_unlock(&css_set_lock);
3118 }
3120 static inline int started_after_time(struct task_struct *t1,
3121 struct timespec *time,
3122 struct task_struct *t2)
3123 {
3124 int start_diff = timespec_compare(&t1->start_time, time);
3125 if (start_diff > 0) {
3126 return 1;
3127 } else if (start_diff < 0) {
3128 return 0;
3129 } else {
3130 /*
3131 * Arbitrarily, if two processes started at the same
3132 * time, we'll say that the lower pointer value
3133 * started first. Note that t2 may have exited by now
3134 * so this may not be a valid pointer any longer, but
3135 * that's fine - it still serves to distinguish
3136 * between two tasks started (effectively) simultaneously.
3137 */
3138 return t1 > t2;
3139 }
3140 }
3142 /*
3143 * This function is a callback from heap_insert() and is used to order
3144 * the heap.
3145 * In this case we order the heap in descending task start time.
3146 */
3147 static inline int started_after(void *p1, void *p2)
3148 {
3149 struct task_struct *t1 = p1;
3150 struct task_struct *t2 = p2;
3151 return started_after_time(t1, &t2->start_time, t2);
3152 }
3154 /**
3155 * cgroup_scan_tasks - iterate though all the tasks in a cgroup
3156 * @scan: struct cgroup_scanner containing arguments for the scan
3157 *
3158 * Arguments include pointers to callback functions test_task() and
3159 * process_task().
3160 * Iterate through all the tasks in a cgroup, calling test_task() for each,
3161 * and if it returns true, call process_task() for it also.
3162 * The test_task pointer may be NULL, meaning always true (select all tasks).
3163 * Effectively duplicates cgroup_iter_{start,next,end}()
3164 * but does not lock css_set_lock for the call to process_task().
3165 * The struct cgroup_scanner may be embedded in any structure of the caller's
3166 * creation.
3167 * It is guaranteed that process_task() will act on every task that
3168 * is a member of the cgroup for the duration of this call. This
3169 * function may or may not call process_task() for tasks that exit
3170 * or move to a different cgroup during the call, or are forked or
3171 * move into the cgroup during the call.
3172 *
3173 * Note that test_task() may be called with locks held, and may in some
3174 * situations be called multiple times for the same task, so it should
3175 * be cheap.
3176 * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
3177 * pre-allocated and will be used for heap operations (and its "gt" member will
3178 * be overwritten), else a temporary heap will be used (allocation of which
3179 * may cause this function to fail).
3180 */
3181 int cgroup_scan_tasks(struct cgroup_scanner *scan)
3182 {
3183 int retval, i;
3184 struct cgroup_iter it;
3185 struct task_struct *p, *dropped;
3186 /* Never dereference latest_task, since it's not refcounted */
3187 struct task_struct *latest_task = NULL;
3188 struct ptr_heap tmp_heap;
3189 struct ptr_heap *heap;
3190 struct timespec latest_time = { 0, 0 };
3192 if (scan->heap) {
3193 /* The caller supplied our heap and pre-allocated its memory */
3194 heap = scan->heap;
3195 heap->gt = &started_after;
3196 } else {
3197 /* We need to allocate our own heap memory */
3198 heap = &tmp_heap;
3199 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3200 if (retval)
3201 /* cannot allocate the heap */
3202 return retval;
3203 }
3205 again:
3206 /*
3207 * Scan tasks in the cgroup, using the scanner's "test_task" callback
3208 * to determine which are of interest, and using the scanner's
3209 * "process_task" callback to process any of them that need an update.
3210 * Since we don't want to hold any locks during the task updates,
3211 * gather tasks to be processed in a heap structure.
3212 * The heap is sorted by descending task start time.
3213 * If the statically-sized heap fills up, we overflow tasks that
3214 * started later, and in future iterations only consider tasks that
3215 * started after the latest task in the previous pass. This
3216 * guarantees forward progress and that we don't miss any tasks.
3217 */
3218 heap->size = 0;
3219 cgroup_iter_start(scan->cg, &it);
3220 while ((p = cgroup_iter_next(scan->cg, &it))) {
3221 /*
3222 * Only affect tasks that qualify per the caller's callback,
3223 * if he provided one
3224 */
3225 if (scan->test_task && !scan->test_task(p, scan))
3226 continue;
3227 /*
3228 * Only process tasks that started after the last task
3229 * we processed
3230 */
3231 if (!started_after_time(p, &latest_time, latest_task))
3232 continue;
3233 dropped = heap_insert(heap, p);
3234 if (dropped == NULL) {
3235 /*
3236 * The new task was inserted; the heap wasn't
3237 * previously full
3238 */
3239 get_task_struct(p);
3240 } else if (dropped != p) {
3241 /*
3242 * The new task was inserted, and pushed out a
3243 * different task
3244 */
3245 get_task_struct(p);
3246 put_task_struct(dropped);
3247 }
3248 /*
3249 * Else the new task was newer than anything already in
3250 * the heap and wasn't inserted
3251 */
3252 }
3253 cgroup_iter_end(scan->cg, &it);
3255 if (heap->size) {
3256 for (i = 0; i < heap->size; i++) {
3257 struct task_struct *q = heap->ptrs[i];
3258 if (i == 0) {
3259 latest_time = q->start_time;
3260 latest_task = q;
3261 }
3262 /* Process the task per the caller's callback */
3263 scan->process_task(q, scan);
3264 put_task_struct(q);
3265 }
3266 /*
3267 * If we had to process any tasks at all, scan again
3268 * in case some of them were in the middle of forking
3269 * children that didn't get processed.
3270 * Not the most efficient way to do it, but it avoids
3271 * having to take callback_mutex in the fork path
3272 */
3273 goto again;
3274 }
3275 if (heap == &tmp_heap)
3276 heap_free(&tmp_heap);
3277 return 0;
3278 }
3280 /*
3281 * Stuff for reading the 'tasks'/'procs' files.
3282 *
3283 * Reading this file can return large amounts of data if a cgroup has
3284 * *lots* of attached tasks. So it may need several calls to read(),
3285 * but we cannot guarantee that the information we produce is correct
3286 * unless we produce it entirely atomically.
3287 *
3288 */
3290 /* which pidlist file are we talking about? */
3291 enum cgroup_filetype {
3292 CGROUP_FILE_PROCS,
3293 CGROUP_FILE_TASKS,
3294 };
3296 /*
3297 * A pidlist is a list of pids that virtually represents the contents of one
3298 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3299 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3300 * to the cgroup.
3301 */
3302 struct cgroup_pidlist {
3303 /*
3304 * used to find which pidlist is wanted. doesn't change as long as
3305 * this particular list stays in the list.
3306 */
3307 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3308 /* array of xids */
3309 pid_t *list;
3310 /* how many elements the above list has */
3311 int length;
3312 /* how many files are using the current array */
3313 int use_count;
3314 /* each of these stored in a list by its cgroup */
3315 struct list_head links;
3316 /* pointer to the cgroup we belong to, for list removal purposes */
3317 struct cgro