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 static int cgroup_allow_attach(struct cgroup *cgrp, struct cgroup_taskset *tset)
2190 {
2191 struct cgroup_subsys *ss;
2192 int ret;
2194 for_each_subsys(cgrp->root, ss) {
2195 if (ss->allow_attach) {
2196 ret = ss->allow_attach(cgrp, tset);
2197 if (ret)
2198 return ret;
2199 } else {
2200 return -EACCES;
2201 }
2202 }
2204 return 0;
2205 }
2207 /*
2208 * Find the task_struct of the task to attach by vpid and pass it along to the
2209 * function to attach either it or all tasks in its threadgroup. Will lock
2210 * cgroup_mutex and threadgroup; may take task_lock of task.
2211 */
2212 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2213 {
2214 struct task_struct *tsk;
2215 const struct cred *cred = current_cred(), *tcred;
2216 int ret;
2218 if (!cgroup_lock_live_group(cgrp))
2219 return -ENODEV;
2221 retry_find_task:
2222 rcu_read_lock();
2223 if (pid) {
2224 tsk = find_task_by_vpid(pid);
2225 if (!tsk) {
2226 rcu_read_unlock();
2227 ret= -ESRCH;
2228 goto out_unlock_cgroup;
2229 }
2230 /*
2231 * even if we're attaching all tasks in the thread group, we
2232 * only need to check permissions on one of them.
2233 */
2234 tcred = __task_cred(tsk);
2235 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2236 !uid_eq(cred->euid, tcred->uid) &&
2237 !uid_eq(cred->euid, tcred->suid)) {
2238 /*
2239 * if the default permission check fails, give each
2240 * cgroup a chance to extend the permission check
2241 */
2242 struct cgroup_taskset tset = { };
2243 tset.single.task = tsk;
2244 tset.single.cgrp = cgrp;
2245 ret = cgroup_allow_attach(cgrp, &tset);
2246 if (ret) {
2247 rcu_read_unlock();
2248 goto out_unlock_cgroup;
2249 }
2250 }
2251 } else
2252 tsk = current;
2254 if (threadgroup)
2255 tsk = tsk->group_leader;
2257 /*
2258 * Workqueue threads may acquire PF_THREAD_BOUND and become
2259 * trapped in a cpuset, or RT worker may be born in a cgroup
2260 * with no rt_runtime allocated. Just say no.
2261 */
2262 if (tsk == kthreadd_task || (tsk->flags & PF_THREAD_BOUND)) {
2263 ret = -EINVAL;
2264 rcu_read_unlock();
2265 goto out_unlock_cgroup;
2266 }
2268 get_task_struct(tsk);
2269 rcu_read_unlock();
2271 threadgroup_lock(tsk);
2272 if (threadgroup) {
2273 if (!thread_group_leader(tsk)) {
2274 /*
2275 * a race with de_thread from another thread's exec()
2276 * may strip us of our leadership, if this happens,
2277 * there is no choice but to throw this task away and
2278 * try again; this is
2279 * "double-double-toil-and-trouble-check locking".
2280 */
2281 threadgroup_unlock(tsk);
2282 put_task_struct(tsk);
2283 goto retry_find_task;
2284 }
2285 ret = cgroup_attach_proc(cgrp, tsk);
2286 } else
2287 ret = cgroup_attach_task(cgrp, tsk);
2288 threadgroup_unlock(tsk);
2290 put_task_struct(tsk);
2291 out_unlock_cgroup:
2292 cgroup_unlock();
2293 return ret;
2294 }
2296 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
2297 {
2298 return attach_task_by_pid(cgrp, pid, false);
2299 }
2301 static int cgroup_procs_write(struct cgroup *cgrp, struct cftype *cft, u64 tgid)
2302 {
2303 return attach_task_by_pid(cgrp, tgid, true);
2304 }
2306 /**
2307 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
2308 * @cgrp: the cgroup to be checked for liveness
2309 *
2310 * On success, returns true; the lock should be later released with
2311 * cgroup_unlock(). On failure returns false with no lock held.
2312 */
2313 bool cgroup_lock_live_group(struct cgroup *cgrp)
2314 {
2315 mutex_lock(&cgroup_mutex);
2316 if (cgroup_is_removed(cgrp)) {
2317 mutex_unlock(&cgroup_mutex);
2318 return false;
2319 }
2320 return true;
2321 }
2322 EXPORT_SYMBOL_GPL(cgroup_lock_live_group);
2324 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
2325 const char *buffer)
2326 {
2327 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
2328 if (strlen(buffer) >= PATH_MAX)
2329 return -EINVAL;
2330 if (!cgroup_lock_live_group(cgrp))
2331 return -ENODEV;
2332 mutex_lock(&cgroup_root_mutex);
2333 strcpy(cgrp->root->release_agent_path, buffer);
2334 mutex_unlock(&cgroup_root_mutex);
2335 cgroup_unlock();
2336 return 0;
2337 }
2339 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
2340 struct seq_file *seq)
2341 {
2342 if (!cgroup_lock_live_group(cgrp))
2343 return -ENODEV;
2344 seq_puts(seq, cgrp->root->release_agent_path);
2345 seq_putc(seq, '\n');
2346 cgroup_unlock();
2347 return 0;
2348 }
2350 /* A buffer size big enough for numbers or short strings */
2351 #define CGROUP_LOCAL_BUFFER_SIZE 64
2353 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
2354 struct file *file,
2355 const char __user *userbuf,
2356 size_t nbytes, loff_t *unused_ppos)
2357 {
2358 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
2359 int retval = 0;
2360 char *end;
2362 if (!nbytes)
2363 return -EINVAL;
2364 if (nbytes >= sizeof(buffer))
2365 return -E2BIG;
2366 if (copy_from_user(buffer, userbuf, nbytes))
2367 return -EFAULT;
2369 buffer[nbytes] = 0; /* nul-terminate */
2370 if (cft->write_u64) {
2371 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
2372 if (*end)
2373 return -EINVAL;
2374 retval = cft->write_u64(cgrp, cft, val);
2375 } else {
2376 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
2377 if (*end)
2378 return -EINVAL;
2379 retval = cft->write_s64(cgrp, cft, val);
2380 }
2381 if (!retval)
2382 retval = nbytes;
2383 return retval;
2384 }
2386 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
2387 struct file *file,
2388 const char __user *userbuf,
2389 size_t nbytes, loff_t *unused_ppos)
2390 {
2391 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
2392 int retval = 0;
2393 size_t max_bytes = cft->max_write_len;
2394 char *buffer = local_buffer;
2396 if (!max_bytes)
2397 max_bytes = sizeof(local_buffer) - 1;
2398 if (nbytes >= max_bytes)
2399 return -E2BIG;
2400 /* Allocate a dynamic buffer if we need one */
2401 if (nbytes >= sizeof(local_buffer)) {
2402 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2403 if (buffer == NULL)
2404 return -ENOMEM;
2405 }
2406 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2407 retval = -EFAULT;
2408 goto out;
2409 }
2411 buffer[nbytes] = 0; /* nul-terminate */
2412 retval = cft->write_string(cgrp, cft, strstrip(buffer));
2413 if (!retval)
2414 retval = nbytes;
2415 out:
2416 if (buffer != local_buffer)
2417 kfree(buffer);
2418 return retval;
2419 }
2421 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2422 size_t nbytes, loff_t *ppos)
2423 {
2424 struct cftype *cft = __d_cft(file->f_dentry);
2425 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2427 if (cgroup_is_removed(cgrp))
2428 return -ENODEV;
2429 if (cft->write)
2430 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
2431 if (cft->write_u64 || cft->write_s64)
2432 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
2433 if (cft->write_string)
2434 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
2435 if (cft->trigger) {
2436 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
2437 return ret ? ret : nbytes;
2438 }
2439 return -EINVAL;
2440 }
2442 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
2443 struct file *file,
2444 char __user *buf, size_t nbytes,
2445 loff_t *ppos)
2446 {
2447 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2448 u64 val = cft->read_u64(cgrp, cft);
2449 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2451 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2452 }
2454 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
2455 struct file *file,
2456 char __user *buf, size_t nbytes,
2457 loff_t *ppos)
2458 {
2459 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2460 s64 val = cft->read_s64(cgrp, cft);
2461 int len = sprintf(tmp, "%lld\n", (long long) val);
2463 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2464 }
2466 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2467 size_t nbytes, loff_t *ppos)
2468 {
2469 struct cftype *cft = __d_cft(file->f_dentry);
2470 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2472 if (cgroup_is_removed(cgrp))
2473 return -ENODEV;
2475 if (cft->read)
2476 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
2477 if (cft->read_u64)
2478 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
2479 if (cft->read_s64)
2480 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
2481 return -EINVAL;
2482 }
2484 /*
2485 * seqfile ops/methods for returning structured data. Currently just
2486 * supports string->u64 maps, but can be extended in future.
2487 */
2489 struct cgroup_seqfile_state {
2490 struct cftype *cft;
2491 struct cgroup *cgroup;
2492 };
2494 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2495 {
2496 struct seq_file *sf = cb->state;
2497 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2498 }
2500 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2501 {
2502 struct cgroup_seqfile_state *state = m->private;
2503 struct cftype *cft = state->cft;
2504 if (cft->read_map) {
2505 struct cgroup_map_cb cb = {
2506 .fill = cgroup_map_add,
2507 .state = m,
2508 };
2509 return cft->read_map(state->cgroup, cft, &cb);
2510 }
2511 return cft->read_seq_string(state->cgroup, cft, m);
2512 }
2514 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
2515 {
2516 struct seq_file *seq = file->private_data;
2517 kfree(seq->private);
2518 return single_release(inode, file);
2519 }
2521 static const struct file_operations cgroup_seqfile_operations = {
2522 .read = seq_read,
2523 .write = cgroup_file_write,
2524 .llseek = seq_lseek,
2525 .release = cgroup_seqfile_release,
2526 };
2528 static int cgroup_file_open(struct inode *inode, struct file *file)
2529 {
2530 int err;
2531 struct cftype *cft;
2533 err = generic_file_open(inode, file);
2534 if (err)
2535 return err;
2536 cft = __d_cft(file->f_dentry);
2538 if (cft->read_map || cft->read_seq_string) {
2539 struct cgroup_seqfile_state *state =
2540 kzalloc(sizeof(*state), GFP_USER);
2541 if (!state)
2542 return -ENOMEM;
2543 state->cft = cft;
2544 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
2545 file->f_op = &cgroup_seqfile_operations;
2546 err = single_open(file, cgroup_seqfile_show, state);
2547 if (err < 0)
2548 kfree(state);
2549 } else if (cft->open)
2550 err = cft->open(inode, file);
2551 else
2552 err = 0;
2554 return err;
2555 }
2557 static int cgroup_file_release(struct inode *inode, struct file *file)
2558 {
2559 struct cftype *cft = __d_cft(file->f_dentry);
2560 if (cft->release)
2561 return cft->release(inode, file);
2562 return 0;
2563 }
2565 /*
2566 * cgroup_rename - Only allow simple rename of directories in place.
2567 */
2568 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2569 struct inode *new_dir, struct dentry *new_dentry)
2570 {
2571 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2572 return -ENOTDIR;
2573 if (new_dentry->d_inode)
2574 return -EEXIST;
2575 if (old_dir != new_dir)
2576 return -EIO;
2577 return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2578 }
2580 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2581 {
2582 if (S_ISDIR(dentry->d_inode->i_mode))
2583 return &__d_cgrp(dentry)->xattrs;
2584 else
2585 return &__d_cfe(dentry)->xattrs;
2586 }
2588 static inline int xattr_enabled(struct dentry *dentry)
2589 {
2590 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2591 return test_bit(ROOT_XATTR, &root->flags);
2592 }
2594 static bool is_valid_xattr(const char *name)
2595 {
2596 if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2597 !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2598 return true;
2599 return false;
2600 }
2602 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2603 const void *val, size_t size, int flags)
2604 {
2605 if (!xattr_enabled(dentry))
2606 return -EOPNOTSUPP;
2607 if (!is_valid_xattr(name))
2608 return -EINVAL;
2609 return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2610 }
2612 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2613 {
2614 if (!xattr_enabled(dentry))
2615 return -EOPNOTSUPP;
2616 if (!is_valid_xattr(name))
2617 return -EINVAL;
2618 return simple_xattr_remove(__d_xattrs(dentry), name);
2619 }
2621 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2622 void *buf, size_t size)
2623 {
2624 if (!xattr_enabled(dentry))
2625 return -EOPNOTSUPP;
2626 if (!is_valid_xattr(name))
2627 return -EINVAL;
2628 return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2629 }
2631 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2632 {
2633 if (!xattr_enabled(dentry))
2634 return -EOPNOTSUPP;
2635 return simple_xattr_list(__d_xattrs(dentry), buf, size);
2636 }
2638 static const struct file_operations cgroup_file_operations = {
2639 .read = cgroup_file_read,
2640 .write = cgroup_file_write,
2641 .llseek = generic_file_llseek,
2642 .open = cgroup_file_open,
2643 .release = cgroup_file_release,
2644 };
2646 static const struct inode_operations cgroup_file_inode_operations = {
2647 .setxattr = cgroup_setxattr,
2648 .getxattr = cgroup_getxattr,
2649 .listxattr = cgroup_listxattr,
2650 .removexattr = cgroup_removexattr,
2651 };
2653 static const struct inode_operations cgroup_dir_inode_operations = {
2654 .lookup = cgroup_lookup,
2655 .mkdir = cgroup_mkdir,
2656 .rmdir = cgroup_rmdir,
2657 .rename = cgroup_rename,
2658 .setxattr = cgroup_setxattr,
2659 .getxattr = cgroup_getxattr,
2660 .listxattr = cgroup_listxattr,
2661 .removexattr = cgroup_removexattr,
2662 };
2664 static struct dentry *cgroup_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
2665 {
2666 if (dentry->d_name.len > NAME_MAX)
2667 return ERR_PTR(-ENAMETOOLONG);
2668 d_add(dentry, NULL);
2669 return NULL;
2670 }
2672 /*
2673 * Check if a file is a control file
2674 */
2675 static inline struct cftype *__file_cft(struct file *file)
2676 {
2677 if (file->f_dentry->d_inode->i_fop != &cgroup_file_operations)
2678 return ERR_PTR(-EINVAL);
2679 return __d_cft(file->f_dentry);
2680 }
2682 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2683 struct super_block *sb)
2684 {
2685 struct inode *inode;
2687 if (!dentry)
2688 return -ENOENT;
2689 if (dentry->d_inode)
2690 return -EEXIST;
2692 inode = cgroup_new_inode(mode, sb);
2693 if (!inode)
2694 return -ENOMEM;
2696 if (S_ISDIR(mode)) {
2697 inode->i_op = &cgroup_dir_inode_operations;
2698 inode->i_fop = &simple_dir_operations;
2700 /* start off with i_nlink == 2 (for "." entry) */
2701 inc_nlink(inode);
2702 inc_nlink(dentry->d_parent->d_inode);
2704 /*
2705 * Control reaches here with cgroup_mutex held.
2706 * @inode->i_mutex should nest outside cgroup_mutex but we
2707 * want to populate it immediately without releasing
2708 * cgroup_mutex. As @inode isn't visible to anyone else
2709 * yet, trylock will always succeed without affecting
2710 * lockdep checks.
2711 */
2712 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2713 } else if (S_ISREG(mode)) {
2714 inode->i_size = 0;
2715 inode->i_fop = &cgroup_file_operations;
2716 inode->i_op = &cgroup_file_inode_operations;
2717 }
2718 d_instantiate(dentry, inode);
2719 dget(dentry); /* Extra count - pin the dentry in core */
2720 return 0;
2721 }
2723 /**
2724 * cgroup_file_mode - deduce file mode of a control file
2725 * @cft: the control file in question
2726 *
2727 * returns cft->mode if ->mode is not 0
2728 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2729 * returns S_IRUGO if it has only a read handler
2730 * returns S_IWUSR if it has only a write hander
2731 */
2732 static umode_t cgroup_file_mode(const struct cftype *cft)
2733 {
2734 umode_t mode = 0;
2736 if (cft->mode)
2737 return cft->mode;
2739 if (cft->read || cft->read_u64 || cft->read_s64 ||
2740 cft->read_map || cft->read_seq_string)
2741 mode |= S_IRUGO;
2743 if (cft->write || cft->write_u64 || cft->write_s64 ||
2744 cft->write_string || cft->trigger)
2745 mode |= S_IWUSR;
2747 return mode;
2748 }
2750 static int cgroup_add_file(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2751 struct cftype *cft)
2752 {
2753 struct dentry *dir = cgrp->dentry;
2754 struct cgroup *parent = __d_cgrp(dir);
2755 struct dentry *dentry;
2756 struct cfent *cfe;
2757 int error;
2758 umode_t mode;
2759 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2761 if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) {
2762 strcpy(name, subsys->name);
2763 strcat(name, ".");
2764 }
2765 strcat(name, cft->name);
2767 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2769 cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2770 if (!cfe)
2771 return -ENOMEM;
2773 dentry = lookup_one_len(name, dir, strlen(name));
2774 if (IS_ERR(dentry)) {
2775 error = PTR_ERR(dentry);
2776 goto out;
2777 }
2779 mode = cgroup_file_mode(cft);
2780 error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2781 if (!error) {
2782 cfe->type = (void *)cft;
2783 cfe->dentry = dentry;
2784 dentry->d_fsdata = cfe;
2785 simple_xattrs_init(&cfe->xattrs);
2786 list_add_tail(&cfe->node, &parent->files);
2787 cfe = NULL;
2788 }
2789 dput(dentry);
2790 out:
2791 kfree(cfe);
2792 return error;
2793 }
2795 static int cgroup_addrm_files(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2796 struct cftype cfts[], bool is_add)
2797 {
2798 struct cftype *cft;
2799 int err, ret = 0;
2801 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2802 /* does cft->flags tell us to skip this file on @cgrp? */
2803 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2804 continue;
2805 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2806 continue;
2808 if (is_add)
2809 err = cgroup_add_file(cgrp, subsys, cft);
2810 else
2811 err = cgroup_rm_file(cgrp, cft);
2812 if (err) {
2813 pr_warning("cgroup_addrm_files: failed to %s %s, err=%d\n",
2814 is_add ? "add" : "remove", cft->name, err);
2815 ret = err;
2816 }
2817 }
2818 return ret;
2819 }
2821 static DEFINE_MUTEX(cgroup_cft_mutex);
2823 static void cgroup_cfts_prepare(void)
2824 __acquires(&cgroup_cft_mutex) __acquires(&cgroup_mutex)
2825 {
2826 /*
2827 * Thanks to the entanglement with vfs inode locking, we can't walk
2828 * the existing cgroups under cgroup_mutex and create files.
2829 * Instead, we increment reference on all cgroups and build list of
2830 * them using @cgrp->cft_q_node. Grab cgroup_cft_mutex to ensure
2831 * exclusive access to the field.
2832 */
2833 mutex_lock(&cgroup_cft_mutex);
2834 mutex_lock(&cgroup_mutex);
2835 }
2837 static void cgroup_cfts_commit(struct cgroup_subsys *ss,
2838 struct cftype *cfts, bool is_add)
2839 __releases(&cgroup_mutex) __releases(&cgroup_cft_mutex)
2840 {
2841 LIST_HEAD(pending);
2842 struct cgroup *cgrp, *n;
2844 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2845 if (cfts && ss->root != &rootnode) {
2846 list_for_each_entry(cgrp, &ss->root->allcg_list, allcg_node) {
2847 dget(cgrp->dentry);
2848 list_add_tail(&cgrp->cft_q_node, &pending);
2849 }
2850 }
2852 mutex_unlock(&cgroup_mutex);
2854 /*
2855 * All new cgroups will see @cfts update on @ss->cftsets. Add/rm
2856 * files for all cgroups which were created before.
2857 */
2858 list_for_each_entry_safe(cgrp, n, &pending, cft_q_node) {
2859 struct inode *inode = cgrp->dentry->d_inode;
2861 mutex_lock(&inode->i_mutex);
2862 mutex_lock(&cgroup_mutex);
2863 if (!cgroup_is_removed(cgrp))
2864 cgroup_addrm_files(cgrp, ss, cfts, is_add);
2865 mutex_unlock(&cgroup_mutex);
2866 mutex_unlock(&inode->i_mutex);
2868 list_del_init(&cgrp->cft_q_node);
2869 dput(cgrp->dentry);
2870 }
2872 mutex_unlock(&cgroup_cft_mutex);
2873 }
2875 /**
2876 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2877 * @ss: target cgroup subsystem
2878 * @cfts: zero-length name terminated array of cftypes
2879 *
2880 * Register @cfts to @ss. Files described by @cfts are created for all
2881 * existing cgroups to which @ss is attached and all future cgroups will
2882 * have them too. This function can be called anytime whether @ss is
2883 * attached or not.
2884 *
2885 * Returns 0 on successful registration, -errno on failure. Note that this
2886 * function currently returns 0 as long as @cfts registration is successful
2887 * even if some file creation attempts on existing cgroups fail.
2888 */
2889 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2890 {
2891 struct cftype_set *set;
2893 set = kzalloc(sizeof(*set), GFP_KERNEL);
2894 if (!set)
2895 return -ENOMEM;
2897 cgroup_cfts_prepare();
2898 set->cfts = cfts;
2899 list_add_tail(&set->node, &ss->cftsets);
2900 cgroup_cfts_commit(ss, cfts, true);
2902 return 0;
2903 }
2904 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2906 /**
2907 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2908 * @ss: target cgroup subsystem
2909 * @cfts: zero-length name terminated array of cftypes
2910 *
2911 * Unregister @cfts from @ss. Files described by @cfts are removed from
2912 * all existing cgroups to which @ss is attached and all future cgroups
2913 * won't have them either. This function can be called anytime whether @ss
2914 * is attached or not.
2915 *
2916 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2917 * registered with @ss.
2918 */
2919 int cgroup_rm_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2920 {
2921 struct cftype_set *set;
2923 cgroup_cfts_prepare();
2925 list_for_each_entry(set, &ss->cftsets, node) {
2926 if (set->cfts == cfts) {
2927 list_del_init(&set->node);
2928 cgroup_cfts_commit(ss, cfts, false);
2929 return 0;
2930 }
2931 }
2933 cgroup_cfts_commit(ss, NULL, false);
2934 return -ENOENT;
2935 }
2937 /**
2938 * cgroup_task_count - count the number of tasks in a cgroup.
2939 * @cgrp: the cgroup in question
2940 *
2941 * Return the number of tasks in the cgroup.
2942 */
2943 int cgroup_task_count(const struct cgroup *cgrp)
2944 {
2945 int count = 0;
2946 struct cg_cgroup_link *link;
2948 read_lock(&css_set_lock);
2949 list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
2950 count += atomic_read(&link->cg->refcount);
2951 }
2952 read_unlock(&css_set_lock);
2953 return count;
2954 }
2956 /*
2957 * Advance a list_head iterator. The iterator should be positioned at
2958 * the start of a css_set
2959 */
2960 static void cgroup_advance_iter(struct cgroup *cgrp,
2961 struct cgroup_iter *it)
2962 {
2963 struct list_head *l = it->cg_link;
2964 struct cg_cgroup_link *link;
2965 struct css_set *cg;
2967 /* Advance to the next non-empty css_set */
2968 do {
2969 l = l->next;
2970 if (l == &cgrp->css_sets) {
2971 it->cg_link = NULL;
2972 return;
2973 }
2974 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
2975 cg = link->cg;
2976 } while (list_empty(&cg->tasks));
2977 it->cg_link = l;
2978 it->task = cg->tasks.next;
2979 }
2981 /*
2982 * To reduce the fork() overhead for systems that are not actually
2983 * using their cgroups capability, we don't maintain the lists running
2984 * through each css_set to its tasks until we see the list actually
2985 * used - in other words after the first call to cgroup_iter_start().
2986 */
2987 static void cgroup_enable_task_cg_lists(void)
2988 {
2989 struct task_struct *p, *g;
2990 write_lock(&css_set_lock);
2991 use_task_css_set_links = 1;
2992 /*
2993 * We need tasklist_lock because RCU is not safe against
2994 * while_each_thread(). Besides, a forking task that has passed
2995 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2996 * is not guaranteed to have its child immediately visible in the
2997 * tasklist if we walk through it with RCU.
2998 */
2999 read_lock(&tasklist_lock);
3000 do_each_thread(g, p) {
3001 task_lock(p);
3002 /*
3003 * We should check if the process is exiting, otherwise
3004 * it will race with cgroup_exit() in that the list
3005 * entry won't be deleted though the process has exited.
3006 */
3007 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
3008 list_add(&p->cg_list, &p->cgroups->tasks);
3009 task_unlock(p);
3010 } while_each_thread(g, p);
3011 read_unlock(&tasklist_lock);
3012 write_unlock(&css_set_lock);
3013 }
3015 /**
3016 * cgroup_next_descendant_pre - find the next descendant for pre-order walk
3017 * @pos: the current position (%NULL to initiate traversal)
3018 * @cgroup: cgroup whose descendants to walk
3019 *
3020 * To be used by cgroup_for_each_descendant_pre(). Find the next
3021 * descendant to visit for pre-order traversal of @cgroup's descendants.
3022 */
3023 struct cgroup *cgroup_next_descendant_pre(struct cgroup *pos,
3024 struct cgroup *cgroup)
3025 {
3026 struct cgroup *next;
3028 WARN_ON_ONCE(!rcu_read_lock_held());
3030 /* if first iteration, pretend we just visited @cgroup */
3031 if (!pos) {
3032 if (list_empty(&cgroup->children))
3033 return NULL;
3034 pos = cgroup;
3035 }
3037 /* visit the first child if exists */
3038 next = list_first_or_null_rcu(&pos->children, struct cgroup, sibling);
3039 if (next)
3040 return next;
3042 /* no child, visit my or the closest ancestor's next sibling */
3043 do {
3044 next = list_entry_rcu(pos->sibling.next, struct cgroup,
3045 sibling);
3046 if (&next->sibling != &pos->parent->children)
3047 return next;
3049 pos = pos->parent;
3050 } while (pos != cgroup);
3052 return NULL;
3053 }
3054 EXPORT_SYMBOL_GPL(cgroup_next_descendant_pre);
3056 static struct cgroup *cgroup_leftmost_descendant(struct cgroup *pos)
3057 {
3058 struct cgroup *last;
3060 do {
3061 last = pos;
3062 pos = list_first_or_null_rcu(&pos->children, struct cgroup,
3063 sibling);
3064 } while (pos);
3066 return last;
3067 }
3069 /**
3070 * cgroup_next_descendant_post - find the next descendant for post-order walk
3071 * @pos: the current position (%NULL to initiate traversal)
3072 * @cgroup: cgroup whose descendants to walk
3073 *
3074 * To be used by cgroup_for_each_descendant_post(). Find the next
3075 * descendant to visit for post-order traversal of @cgroup's descendants.
3076 */
3077 struct cgroup *cgroup_next_descendant_post(struct cgroup *pos,
3078 struct cgroup *cgroup)
3079 {
3080 struct cgroup *next;
3082 WARN_ON_ONCE(!rcu_read_lock_held());
3084 /* if first iteration, visit the leftmost descendant */
3085 if (!pos) {
3086 next = cgroup_leftmost_descendant(cgroup);
3087 return next != cgroup ? next : NULL;
3088 }
3090 /* if there's an unvisited sibling, visit its leftmost descendant */
3091 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3092 if (&next->sibling != &pos->parent->children)
3093 return cgroup_leftmost_descendant(next);
3095 /* no sibling left, visit parent */
3096 next = pos->parent;
3097 return next != cgroup ? next : NULL;
3098 }
3099 EXPORT_SYMBOL_GPL(cgroup_next_descendant_post);
3101 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
3102 __acquires(css_set_lock)
3103 {
3104 /*
3105 * The first time anyone tries to iterate across a cgroup,
3106 * we need to enable the list linking each css_set to its
3107 * tasks, and fix up all existing tasks.
3108 */
3109 if (!use_task_css_set_links)
3110 cgroup_enable_task_cg_lists();
3112 read_lock(&css_set_lock);
3113 it->cg_link = &cgrp->css_sets;
3114 cgroup_advance_iter(cgrp, it);
3115 }
3117 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
3118 struct cgroup_iter *it)
3119 {
3120 struct task_struct *res;
3121 struct list_head *l = it->task;
3122 struct cg_cgroup_link *link;
3124 /* If the iterator cg is NULL, we have no tasks */
3125 if (!it->cg_link)
3126 return NULL;
3127 res = list_entry(l, struct task_struct, cg_list);
3128 /* Advance iterator to find next entry */
3129 l = l->next;
3130 link = list_entry(it->cg_link, struct cg_cgroup_link, cgrp_link_list);
3131 if (l == &link->cg->tasks) {
3132 /* We reached the end of this task list - move on to
3133 * the next cg_cgroup_link */
3134 cgroup_advance_iter(cgrp, it);
3135 } else {
3136 it->task = l;
3137 }
3138 return res;
3139 }
3141 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
3142 __releases(css_set_lock)
3143 {
3144 read_unlock(&css_set_lock);
3145 }
3147 static inline int started_after_time(struct task_struct *t1,
3148 struct timespec *time,
3149 struct task_struct *t2)
3150 {
3151 int start_diff = timespec_compare(&t1->start_time, time);
3152 if (start_diff > 0) {
3153 return 1;
3154 } else if (start_diff < 0) {
3155 return 0;
3156 } else {
3157 /*
3158 * Arbitrarily, if two processes started at the same
3159 * time, we'll say that the lower pointer value
3160 * started first. Note that t2 may have exited by now
3161 * so this may not be a valid pointer any longer, but
3162 * that's fine - it still serves to distinguish
3163 * between two tasks started (effectively) simultaneously.
3164 */
3165 return t1 > t2;
3166 }
3167 }
3169 /*
3170 * This function is a callback from heap_insert() and is used to order
3171 * the heap.
3172 * In this case we order the heap in descending task start time.
3173 */
3174 static inline int started_after(void *p1, void *p2)
3175 {
3176 struct task_struct *t1 = p1;
3177 struct task_struct *t2 = p2;
3178 return started_after_time(t1, &t2->start_time, t2);
3179 }
3181 /**
3182 * cgroup_scan_tasks - iterate though all the tasks in a cgroup
3183 * @scan: struct cgroup_scanner containing arguments for the scan
3184 *
3185 * Arguments include pointers to callback functions test_task() and
3186 * process_task().
3187 * Iterate through all the tasks in a cgroup, calling test_task() for each,
3188 * and if it returns true, call process_task() for it also.
3189 * The test_task pointer may be NULL, meaning always true (select all tasks).
3190 * Effectively duplicates cgroup_iter_{start,next,end}()
3191 * but does not lock css_set_lock for the call to process_task().
3192 * The struct cgroup_scanner may be embedded in any structure of the caller's
3193 * creation.
3194 * It is guaranteed that process_task() will act on every task that
3195 * is a member of the cgroup for the duration of this call. This
3196 * function may or may not call process_task() for tasks that exit
3197 * or move to a different cgroup during the call, or are forked or
3198 * move into the cgroup during the call.
3199 *
3200 * Note that test_task() may be called with locks held, and may in some
3201 * situations be called multiple times for the same task, so it should
3202 * be cheap.
3203 * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
3204 * pre-allocated and will be used for heap operations (and its "gt" member will
3205 * be overwritten), else a temporary heap will be used (allocation of which
3206 * may cause this function to fail).
3207 */
3208 int cgroup_scan_tasks(struct cgroup_scanner *scan)
3209 {
3210 int retval, i;
3211 struct cgroup_iter it;
3212 struct task_struct *p, *dropped;
3213 /* Never dereference latest_task, since it's not refcounted */
3214 struct task_struct *latest_task = NULL;
3215 struct ptr_heap tmp_heap;
3216 struct ptr_heap *heap;
3217 struct timespec latest_time = { 0, 0 };
3219 if (scan->heap) {
3220 /* The caller supplied our heap and pre-allocated its memory */
3221 heap = scan->heap;
3222 heap->gt = &started_after;
3223 } else {
3224 /* We need to allocate our own heap memory */
3225 heap = &tmp_heap;
3226 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3227 if (retval)
3228 /* cannot allocate the heap */
3229 return retval;
3230 }
3232 again:
3233 /*
3234 * Scan tasks in the cgroup, using the scanner's "test_task" callback
3235 * to determine which are of interest, and using the scanner's
3236 * "process_task" callback to process any of them that need an update.
3237 * Since we don't want to hold any locks during the task updates,
3238 * gather tasks to be processed in a heap structure.
3239 * The heap is sorted by descending task start time.
3240 * If the statically-sized heap fills up, we overflow tasks that
3241 * started later, and in future iterations only consider tasks that
3242 * started after the latest task in the previous pass. This
3243 * guarantees forward progress and that we don't miss any tasks.
3244 */
3245 heap->size = 0;
3246 cgroup_iter_start(scan->cg, &it);
3247 while ((p = cgroup_iter_next(scan->cg, &it))) {
3248 /*
3249 * Only affect tasks that qualify per the caller's callback,
3250 * if he provided one
3251 */
3252 if (scan->test_task && !scan->test_task(p, scan))
3253 continue;
3254 /*
3255 * Only process tasks that started after the last task
3256 * we processed
3257 */
3258 if (!started_after_time(p, &latest_time, latest_task))
3259 continue;
3260 dropped = heap_insert(heap, p);
3261 if (dropped == NULL) {
3262 /*
3263 * The new task was inserted; the heap wasn't
3264 * previously full
3265 */
3266 get_task_struct(p);
3267 } else if (dropped != p) {
3268 /*
3269 * The new task was inserted, and pushed out a
3270 * different task
3271 */
3272 get_task_struct(p);
3273 put_task_struct(dropped);
3274 }
3275 /*
3276 * Else the new task was newer than anything already in
3277 * the heap and wasn't inserted
3278 */
3279 }
3280 cgroup_iter_end(scan->cg, &it);
3282 if (heap->size) {
3283 for (i = 0; i < heap->size; i++) {
3284 struct task_struct *q = heap->ptrs[i];
3285 if (i == 0) {
3286 latest_time = q->start_time;
3287 latest_task = q;
3288 }
3289 /* Process the task per the caller's callback */
3290 scan->process_task(q, scan);
3291 put_task_struct(q);
3292 }
3293 /*
3294 * If we had to process any tasks at all, scan again
3295 * in case some of them were in the middle of forking
3296 * children that didn't get processed.
3297 * Not the most efficient way to do it, but it avoids
3298 * having to take callback_mutex in the fork path
3299 */
3300 goto again;
3301 }
3302 if (heap == &tmp_heap)
3303 heap_free(&tmp_heap);
3304 return 0;
3305 }
3307 /*
3308 * Stuff for reading the 'tasks'/'procs' files.
3309 *