cgroup, cpuset: remove cgroup_subsys->post_clone()
[linux-2.6-block.git] / kernel / cgroup.c
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  */
28
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>
64
65 #include <linux/atomic.h>
66
67 /* css deactivation bias, makes css->refcnt negative to deny new trygets */
68 #define CSS_DEACT_BIAS          INT_MIN
69
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);
88
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 };
100
101 #define MAX_CGROUP_ROOT_NAMELEN 64
102
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;
110
111         /*
112          * The bitmask of subsystems intended to be attached to this
113          * hierarchy
114          */
115         unsigned long subsys_mask;
116
117         /* Unique id for this hierarchy. */
118         int hierarchy_id;
119
120         /* The bitmask of subsystems currently attached to this hierarchy */
121         unsigned long actual_subsys_mask;
122
123         /* A list running through the attached subsystems */
124         struct list_head subsys_list;
125
126         /* The root cgroup for this hierarchy */
127         struct cgroup top_cgroup;
128
129         /* Tracks how many cgroups are currently defined in hierarchy.*/
130         int number_of_cgroups;
131
132         /* A list running through the active hierarchies */
133         struct list_head root_list;
134
135         /* All cgroups on this root, cgroup_mutex protected */
136         struct list_head allcg_list;
137
138         /* Hierarchy-specific flags */
139         unsigned long flags;
140
141         /* The path to use for release notifications. */
142         char release_agent_path[PATH_MAX];
143
144         /* The name for this hierarchy - may be empty */
145         char name[MAX_CGROUP_ROOT_NAMELEN];
146 };
147
148 /*
149  * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the
150  * subsystems that are otherwise unattached - it never has more than a
151  * single cgroup, and all tasks are part of that cgroup.
152  */
153 static struct cgroupfs_root rootnode;
154
155 /*
156  * cgroupfs file entry, pointed to from leaf dentry->d_fsdata.
157  */
158 struct cfent {
159         struct list_head                node;
160         struct dentry                   *dentry;
161         struct cftype                   *type;
162 };
163
164 /*
165  * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when
166  * cgroup_subsys->use_id != 0.
167  */
168 #define CSS_ID_MAX      (65535)
169 struct css_id {
170         /*
171          * The css to which this ID points. This pointer is set to valid value
172          * after cgroup is populated. If cgroup is removed, this will be NULL.
173          * This pointer is expected to be RCU-safe because destroy()
174          * is called after synchronize_rcu(). But for safe use, css_tryget()
175          * should be used for avoiding race.
176          */
177         struct cgroup_subsys_state __rcu *css;
178         /*
179          * ID of this css.
180          */
181         unsigned short id;
182         /*
183          * Depth in hierarchy which this ID belongs to.
184          */
185         unsigned short depth;
186         /*
187          * ID is freed by RCU. (and lookup routine is RCU safe.)
188          */
189         struct rcu_head rcu_head;
190         /*
191          * Hierarchy of CSS ID belongs to.
192          */
193         unsigned short stack[0]; /* Array of Length (depth+1) */
194 };
195
196 /*
197  * cgroup_event represents events which userspace want to receive.
198  */
199 struct cgroup_event {
200         /*
201          * Cgroup which the event belongs to.
202          */
203         struct cgroup *cgrp;
204         /*
205          * Control file which the event associated.
206          */
207         struct cftype *cft;
208         /*
209          * eventfd to signal userspace about the event.
210          */
211         struct eventfd_ctx *eventfd;
212         /*
213          * Each of these stored in a list by the cgroup.
214          */
215         struct list_head list;
216         /*
217          * All fields below needed to unregister event when
218          * userspace closes eventfd.
219          */
220         poll_table pt;
221         wait_queue_head_t *wqh;
222         wait_queue_t wait;
223         struct work_struct remove;
224 };
225
226 /* The list of hierarchy roots */
227
228 static LIST_HEAD(roots);
229 static int root_count;
230
231 static DEFINE_IDA(hierarchy_ida);
232 static int next_hierarchy_id;
233 static DEFINE_SPINLOCK(hierarchy_id_lock);
234
235 /* dummytop is a shorthand for the dummy hierarchy's top cgroup */
236 #define dummytop (&rootnode.top_cgroup)
237
238 /* This flag indicates whether tasks in the fork and exit paths should
239  * check for fork/exit handlers to call. This avoids us having to do
240  * extra work in the fork/exit path if none of the subsystems need to
241  * be called.
242  */
243 static int need_forkexit_callback __read_mostly;
244
245 static int cgroup_destroy_locked(struct cgroup *cgrp);
246
247 #ifdef CONFIG_PROVE_LOCKING
248 int cgroup_lock_is_held(void)
249 {
250         return lockdep_is_held(&cgroup_mutex);
251 }
252 #else /* #ifdef CONFIG_PROVE_LOCKING */
253 int cgroup_lock_is_held(void)
254 {
255         return mutex_is_locked(&cgroup_mutex);
256 }
257 #endif /* #else #ifdef CONFIG_PROVE_LOCKING */
258
259 EXPORT_SYMBOL_GPL(cgroup_lock_is_held);
260
261 static int css_unbias_refcnt(int refcnt)
262 {
263         return refcnt >= 0 ? refcnt : refcnt - CSS_DEACT_BIAS;
264 }
265
266 /* the current nr of refs, always >= 0 whether @css is deactivated or not */
267 static int css_refcnt(struct cgroup_subsys_state *css)
268 {
269         int v = atomic_read(&css->refcnt);
270
271         return css_unbias_refcnt(v);
272 }
273
274 /* convenient tests for these bits */
275 inline int cgroup_is_removed(const struct cgroup *cgrp)
276 {
277         return test_bit(CGRP_REMOVED, &cgrp->flags);
278 }
279
280 /* bits in struct cgroupfs_root flags field */
281 enum {
282         ROOT_NOPREFIX,  /* mounted subsystems have no named prefix */
283         ROOT_XATTR,     /* supports extended attributes */
284 };
285
286 static int cgroup_is_releasable(const struct cgroup *cgrp)
287 {
288         const int bits =
289                 (1 << CGRP_RELEASABLE) |
290                 (1 << CGRP_NOTIFY_ON_RELEASE);
291         return (cgrp->flags & bits) == bits;
292 }
293
294 static int notify_on_release(const struct cgroup *cgrp)
295 {
296         return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
297 }
298
299 /*
300  * for_each_subsys() allows you to iterate on each subsystem attached to
301  * an active hierarchy
302  */
303 #define for_each_subsys(_root, _ss) \
304 list_for_each_entry(_ss, &_root->subsys_list, sibling)
305
306 /* for_each_active_root() allows you to iterate across the active hierarchies */
307 #define for_each_active_root(_root) \
308 list_for_each_entry(_root, &roots, root_list)
309
310 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
311 {
312         return dentry->d_fsdata;
313 }
314
315 static inline struct cfent *__d_cfe(struct dentry *dentry)
316 {
317         return dentry->d_fsdata;
318 }
319
320 static inline struct cftype *__d_cft(struct dentry *dentry)
321 {
322         return __d_cfe(dentry)->type;
323 }
324
325 /* the list of cgroups eligible for automatic release. Protected by
326  * release_list_lock */
327 static LIST_HEAD(release_list);
328 static DEFINE_RAW_SPINLOCK(release_list_lock);
329 static void cgroup_release_agent(struct work_struct *work);
330 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
331 static void check_for_release(struct cgroup *cgrp);
332
333 /* Link structure for associating css_set objects with cgroups */
334 struct cg_cgroup_link {
335         /*
336          * List running through cg_cgroup_links associated with a
337          * cgroup, anchored on cgroup->css_sets
338          */
339         struct list_head cgrp_link_list;
340         struct cgroup *cgrp;
341         /*
342          * List running through cg_cgroup_links pointing at a
343          * single css_set object, anchored on css_set->cg_links
344          */
345         struct list_head cg_link_list;
346         struct css_set *cg;
347 };
348
349 /* The default css_set - used by init and its children prior to any
350  * hierarchies being mounted. It contains a pointer to the root state
351  * for each subsystem. Also used to anchor the list of css_sets. Not
352  * reference-counted, to improve performance when child cgroups
353  * haven't been created.
354  */
355
356 static struct css_set init_css_set;
357 static struct cg_cgroup_link init_css_set_link;
358
359 static int cgroup_init_idr(struct cgroup_subsys *ss,
360                            struct cgroup_subsys_state *css);
361
362 /* css_set_lock protects the list of css_set objects, and the
363  * chain of tasks off each css_set.  Nests outside task->alloc_lock
364  * due to cgroup_iter_start() */
365 static DEFINE_RWLOCK(css_set_lock);
366 static int css_set_count;
367
368 /*
369  * hash table for cgroup groups. This improves the performance to find
370  * an existing css_set. This hash doesn't (currently) take into
371  * account cgroups in empty hierarchies.
372  */
373 #define CSS_SET_HASH_BITS       7
374 #define CSS_SET_TABLE_SIZE      (1 << CSS_SET_HASH_BITS)
375 static struct hlist_head css_set_table[CSS_SET_TABLE_SIZE];
376
377 static struct hlist_head *css_set_hash(struct cgroup_subsys_state *css[])
378 {
379         int i;
380         int index;
381         unsigned long tmp = 0UL;
382
383         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++)
384                 tmp += (unsigned long)css[i];
385         tmp = (tmp >> 16) ^ tmp;
386
387         index = hash_long(tmp, CSS_SET_HASH_BITS);
388
389         return &css_set_table[index];
390 }
391
392 /* We don't maintain the lists running through each css_set to its
393  * task until after the first call to cgroup_iter_start(). This
394  * reduces the fork()/exit() overhead for people who have cgroups
395  * compiled into their kernel but not actually in use */
396 static int use_task_css_set_links __read_mostly;
397
398 static void __put_css_set(struct css_set *cg, int taskexit)
399 {
400         struct cg_cgroup_link *link;
401         struct cg_cgroup_link *saved_link;
402         /*
403          * Ensure that the refcount doesn't hit zero while any readers
404          * can see it. Similar to atomic_dec_and_lock(), but for an
405          * rwlock
406          */
407         if (atomic_add_unless(&cg->refcount, -1, 1))
408                 return;
409         write_lock(&css_set_lock);
410         if (!atomic_dec_and_test(&cg->refcount)) {
411                 write_unlock(&css_set_lock);
412                 return;
413         }
414
415         /* This css_set is dead. unlink it and release cgroup refcounts */
416         hlist_del(&cg->hlist);
417         css_set_count--;
418
419         list_for_each_entry_safe(link, saved_link, &cg->cg_links,
420                                  cg_link_list) {
421                 struct cgroup *cgrp = link->cgrp;
422                 list_del(&link->cg_link_list);
423                 list_del(&link->cgrp_link_list);
424                 if (atomic_dec_and_test(&cgrp->count) &&
425                     notify_on_release(cgrp)) {
426                         if (taskexit)
427                                 set_bit(CGRP_RELEASABLE, &cgrp->flags);
428                         check_for_release(cgrp);
429                 }
430
431                 kfree(link);
432         }
433
434         write_unlock(&css_set_lock);
435         kfree_rcu(cg, rcu_head);
436 }
437
438 /*
439  * refcounted get/put for css_set objects
440  */
441 static inline void get_css_set(struct css_set *cg)
442 {
443         atomic_inc(&cg->refcount);
444 }
445
446 static inline void put_css_set(struct css_set *cg)
447 {
448         __put_css_set(cg, 0);
449 }
450
451 static inline void put_css_set_taskexit(struct css_set *cg)
452 {
453         __put_css_set(cg, 1);
454 }
455
456 /*
457  * compare_css_sets - helper function for find_existing_css_set().
458  * @cg: candidate css_set being tested
459  * @old_cg: existing css_set for a task
460  * @new_cgrp: cgroup that's being entered by the task
461  * @template: desired set of css pointers in css_set (pre-calculated)
462  *
463  * Returns true if "cg" matches "old_cg" except for the hierarchy
464  * which "new_cgrp" belongs to, for which it should match "new_cgrp".
465  */
466 static bool compare_css_sets(struct css_set *cg,
467                              struct css_set *old_cg,
468                              struct cgroup *new_cgrp,
469                              struct cgroup_subsys_state *template[])
470 {
471         struct list_head *l1, *l2;
472
473         if (memcmp(template, cg->subsys, sizeof(cg->subsys))) {
474                 /* Not all subsystems matched */
475                 return false;
476         }
477
478         /*
479          * Compare cgroup pointers in order to distinguish between
480          * different cgroups in heirarchies with no subsystems. We
481          * could get by with just this check alone (and skip the
482          * memcmp above) but on most setups the memcmp check will
483          * avoid the need for this more expensive check on almost all
484          * candidates.
485          */
486
487         l1 = &cg->cg_links;
488         l2 = &old_cg->cg_links;
489         while (1) {
490                 struct cg_cgroup_link *cgl1, *cgl2;
491                 struct cgroup *cg1, *cg2;
492
493                 l1 = l1->next;
494                 l2 = l2->next;
495                 /* See if we reached the end - both lists are equal length. */
496                 if (l1 == &cg->cg_links) {
497                         BUG_ON(l2 != &old_cg->cg_links);
498                         break;
499                 } else {
500                         BUG_ON(l2 == &old_cg->cg_links);
501                 }
502                 /* Locate the cgroups associated with these links. */
503                 cgl1 = list_entry(l1, struct cg_cgroup_link, cg_link_list);
504                 cgl2 = list_entry(l2, struct cg_cgroup_link, cg_link_list);
505                 cg1 = cgl1->cgrp;
506                 cg2 = cgl2->cgrp;
507                 /* Hierarchies should be linked in the same order. */
508                 BUG_ON(cg1->root != cg2->root);
509
510                 /*
511                  * If this hierarchy is the hierarchy of the cgroup
512                  * that's changing, then we need to check that this
513                  * css_set points to the new cgroup; if it's any other
514                  * hierarchy, then this css_set should point to the
515                  * same cgroup as the old css_set.
516                  */
517                 if (cg1->root == new_cgrp->root) {
518                         if (cg1 != new_cgrp)
519                                 return false;
520                 } else {
521                         if (cg1 != cg2)
522                                 return false;
523                 }
524         }
525         return true;
526 }
527
528 /*
529  * find_existing_css_set() is a helper for
530  * find_css_set(), and checks to see whether an existing
531  * css_set is suitable.
532  *
533  * oldcg: the cgroup group that we're using before the cgroup
534  * transition
535  *
536  * cgrp: the cgroup that we're moving into
537  *
538  * template: location in which to build the desired set of subsystem
539  * state objects for the new cgroup group
540  */
541 static struct css_set *find_existing_css_set(
542         struct css_set *oldcg,
543         struct cgroup *cgrp,
544         struct cgroup_subsys_state *template[])
545 {
546         int i;
547         struct cgroupfs_root *root = cgrp->root;
548         struct hlist_head *hhead;
549         struct hlist_node *node;
550         struct css_set *cg;
551
552         /*
553          * Build the set of subsystem state objects that we want to see in the
554          * new css_set. while subsystems can change globally, the entries here
555          * won't change, so no need for locking.
556          */
557         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
558                 if (root->subsys_mask & (1UL << i)) {
559                         /* Subsystem is in this hierarchy. So we want
560                          * the subsystem state from the new
561                          * cgroup */
562                         template[i] = cgrp->subsys[i];
563                 } else {
564                         /* Subsystem is not in this hierarchy, so we
565                          * don't want to change the subsystem state */
566                         template[i] = oldcg->subsys[i];
567                 }
568         }
569
570         hhead = css_set_hash(template);
571         hlist_for_each_entry(cg, node, hhead, hlist) {
572                 if (!compare_css_sets(cg, oldcg, cgrp, template))
573                         continue;
574
575                 /* This css_set matches what we need */
576                 return cg;
577         }
578
579         /* No existing cgroup group matched */
580         return NULL;
581 }
582
583 static void free_cg_links(struct list_head *tmp)
584 {
585         struct cg_cgroup_link *link;
586         struct cg_cgroup_link *saved_link;
587
588         list_for_each_entry_safe(link, saved_link, tmp, cgrp_link_list) {
589                 list_del(&link->cgrp_link_list);
590                 kfree(link);
591         }
592 }
593
594 /*
595  * allocate_cg_links() allocates "count" cg_cgroup_link structures
596  * and chains them on tmp through their cgrp_link_list fields. Returns 0 on
597  * success or a negative error
598  */
599 static int allocate_cg_links(int count, struct list_head *tmp)
600 {
601         struct cg_cgroup_link *link;
602         int i;
603         INIT_LIST_HEAD(tmp);
604         for (i = 0; i < count; i++) {
605                 link = kmalloc(sizeof(*link), GFP_KERNEL);
606                 if (!link) {
607                         free_cg_links(tmp);
608                         return -ENOMEM;
609                 }
610                 list_add(&link->cgrp_link_list, tmp);
611         }
612         return 0;
613 }
614
615 /**
616  * link_css_set - a helper function to link a css_set to a cgroup
617  * @tmp_cg_links: cg_cgroup_link objects allocated by allocate_cg_links()
618  * @cg: the css_set to be linked
619  * @cgrp: the destination cgroup
620  */
621 static void link_css_set(struct list_head *tmp_cg_links,
622                          struct css_set *cg, struct cgroup *cgrp)
623 {
624         struct cg_cgroup_link *link;
625
626         BUG_ON(list_empty(tmp_cg_links));
627         link = list_first_entry(tmp_cg_links, struct cg_cgroup_link,
628                                 cgrp_link_list);
629         link->cg = cg;
630         link->cgrp = cgrp;
631         atomic_inc(&cgrp->count);
632         list_move(&link->cgrp_link_list, &cgrp->css_sets);
633         /*
634          * Always add links to the tail of the list so that the list
635          * is sorted by order of hierarchy creation
636          */
637         list_add_tail(&link->cg_link_list, &cg->cg_links);
638 }
639
640 /*
641  * find_css_set() takes an existing cgroup group and a
642  * cgroup object, and returns a css_set object that's
643  * equivalent to the old group, but with the given cgroup
644  * substituted into the appropriate hierarchy. Must be called with
645  * cgroup_mutex held
646  */
647 static struct css_set *find_css_set(
648         struct css_set *oldcg, struct cgroup *cgrp)
649 {
650         struct css_set *res;
651         struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT];
652
653         struct list_head tmp_cg_links;
654
655         struct hlist_head *hhead;
656         struct cg_cgroup_link *link;
657
658         /* First see if we already have a cgroup group that matches
659          * the desired set */
660         read_lock(&css_set_lock);
661         res = find_existing_css_set(oldcg, cgrp, template);
662         if (res)
663                 get_css_set(res);
664         read_unlock(&css_set_lock);
665
666         if (res)
667                 return res;
668
669         res = kmalloc(sizeof(*res), GFP_KERNEL);
670         if (!res)
671                 return NULL;
672
673         /* Allocate all the cg_cgroup_link objects that we'll need */
674         if (allocate_cg_links(root_count, &tmp_cg_links) < 0) {
675                 kfree(res);
676                 return NULL;
677         }
678
679         atomic_set(&res->refcount, 1);
680         INIT_LIST_HEAD(&res->cg_links);
681         INIT_LIST_HEAD(&res->tasks);
682         INIT_HLIST_NODE(&res->hlist);
683
684         /* Copy the set of subsystem state objects generated in
685          * find_existing_css_set() */
686         memcpy(res->subsys, template, sizeof(res->subsys));
687
688         write_lock(&css_set_lock);
689         /* Add reference counts and links from the new css_set. */
690         list_for_each_entry(link, &oldcg->cg_links, cg_link_list) {
691                 struct cgroup *c = link->cgrp;
692                 if (c->root == cgrp->root)
693                         c = cgrp;
694                 link_css_set(&tmp_cg_links, res, c);
695         }
696
697         BUG_ON(!list_empty(&tmp_cg_links));
698
699         css_set_count++;
700
701         /* Add this cgroup group to the hash table */
702         hhead = css_set_hash(res->subsys);
703         hlist_add_head(&res->hlist, hhead);
704
705         write_unlock(&css_set_lock);
706
707         return res;
708 }
709
710 /*
711  * Return the cgroup for "task" from the given hierarchy. Must be
712  * called with cgroup_mutex held.
713  */
714 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
715                                             struct cgroupfs_root *root)
716 {
717         struct css_set *css;
718         struct cgroup *res = NULL;
719
720         BUG_ON(!mutex_is_locked(&cgroup_mutex));
721         read_lock(&css_set_lock);
722         /*
723          * No need to lock the task - since we hold cgroup_mutex the
724          * task can't change groups, so the only thing that can happen
725          * is that it exits and its css is set back to init_css_set.
726          */
727         css = task->cgroups;
728         if (css == &init_css_set) {
729                 res = &root->top_cgroup;
730         } else {
731                 struct cg_cgroup_link *link;
732                 list_for_each_entry(link, &css->cg_links, cg_link_list) {
733                         struct cgroup *c = link->cgrp;
734                         if (c->root == root) {
735                                 res = c;
736                                 break;
737                         }
738                 }
739         }
740         read_unlock(&css_set_lock);
741         BUG_ON(!res);
742         return res;
743 }
744
745 /*
746  * There is one global cgroup mutex. We also require taking
747  * task_lock() when dereferencing a task's cgroup subsys pointers.
748  * See "The task_lock() exception", at the end of this comment.
749  *
750  * A task must hold cgroup_mutex to modify cgroups.
751  *
752  * Any task can increment and decrement the count field without lock.
753  * So in general, code holding cgroup_mutex can't rely on the count
754  * field not changing.  However, if the count goes to zero, then only
755  * cgroup_attach_task() can increment it again.  Because a count of zero
756  * means that no tasks are currently attached, therefore there is no
757  * way a task attached to that cgroup can fork (the other way to
758  * increment the count).  So code holding cgroup_mutex can safely
759  * assume that if the count is zero, it will stay zero. Similarly, if
760  * a task holds cgroup_mutex on a cgroup with zero count, it
761  * knows that the cgroup won't be removed, as cgroup_rmdir()
762  * needs that mutex.
763  *
764  * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
765  * (usually) take cgroup_mutex.  These are the two most performance
766  * critical pieces of code here.  The exception occurs on cgroup_exit(),
767  * when a task in a notify_on_release cgroup exits.  Then cgroup_mutex
768  * is taken, and if the cgroup count is zero, a usermode call made
769  * to the release agent with the name of the cgroup (path relative to
770  * the root of cgroup file system) as the argument.
771  *
772  * A cgroup can only be deleted if both its 'count' of using tasks
773  * is zero, and its list of 'children' cgroups is empty.  Since all
774  * tasks in the system use _some_ cgroup, and since there is always at
775  * least one task in the system (init, pid == 1), therefore, top_cgroup
776  * always has either children cgroups and/or using tasks.  So we don't
777  * need a special hack to ensure that top_cgroup cannot be deleted.
778  *
779  *      The task_lock() exception
780  *
781  * The need for this exception arises from the action of
782  * cgroup_attach_task(), which overwrites one tasks cgroup pointer with
783  * another.  It does so using cgroup_mutex, however there are
784  * several performance critical places that need to reference
785  * task->cgroup without the expense of grabbing a system global
786  * mutex.  Therefore except as noted below, when dereferencing or, as
787  * in cgroup_attach_task(), modifying a task'ss cgroup pointer we use
788  * task_lock(), which acts on a spinlock (task->alloc_lock) already in
789  * the task_struct routinely used for such matters.
790  *
791  * P.S.  One more locking exception.  RCU is used to guard the
792  * update of a tasks cgroup pointer by cgroup_attach_task()
793  */
794
795 /**
796  * cgroup_lock - lock out any changes to cgroup structures
797  *
798  */
799 void cgroup_lock(void)
800 {
801         mutex_lock(&cgroup_mutex);
802 }
803 EXPORT_SYMBOL_GPL(cgroup_lock);
804
805 /**
806  * cgroup_unlock - release lock on cgroup changes
807  *
808  * Undo the lock taken in a previous cgroup_lock() call.
809  */
810 void cgroup_unlock(void)
811 {
812         mutex_unlock(&cgroup_mutex);
813 }
814 EXPORT_SYMBOL_GPL(cgroup_unlock);
815
816 /*
817  * A couple of forward declarations required, due to cyclic reference loop:
818  * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
819  * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
820  * -> cgroup_mkdir.
821  */
822
823 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode);
824 static struct dentry *cgroup_lookup(struct inode *, struct dentry *, unsigned int);
825 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
826 static int cgroup_populate_dir(struct cgroup *cgrp, bool base_files,
827                                unsigned long subsys_mask);
828 static const struct inode_operations cgroup_dir_inode_operations;
829 static const struct file_operations proc_cgroupstats_operations;
830
831 static struct backing_dev_info cgroup_backing_dev_info = {
832         .name           = "cgroup",
833         .capabilities   = BDI_CAP_NO_ACCT_AND_WRITEBACK,
834 };
835
836 static int alloc_css_id(struct cgroup_subsys *ss,
837                         struct cgroup *parent, struct cgroup *child);
838
839 static struct inode *cgroup_new_inode(umode_t mode, struct super_block *sb)
840 {
841         struct inode *inode = new_inode(sb);
842
843         if (inode) {
844                 inode->i_ino = get_next_ino();
845                 inode->i_mode = mode;
846                 inode->i_uid = current_fsuid();
847                 inode->i_gid = current_fsgid();
848                 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
849                 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
850         }
851         return inode;
852 }
853
854 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
855 {
856         /* is dentry a directory ? if so, kfree() associated cgroup */
857         if (S_ISDIR(inode->i_mode)) {
858                 struct cgroup *cgrp = dentry->d_fsdata;
859                 struct cgroup_subsys *ss;
860                 BUG_ON(!(cgroup_is_removed(cgrp)));
861                 /* It's possible for external users to be holding css
862                  * reference counts on a cgroup; css_put() needs to
863                  * be able to access the cgroup after decrementing
864                  * the reference count in order to know if it needs to
865                  * queue the cgroup to be handled by the release
866                  * agent */
867                 synchronize_rcu();
868
869                 mutex_lock(&cgroup_mutex);
870                 /*
871                  * Release the subsystem state objects.
872                  */
873                 for_each_subsys(cgrp->root, ss)
874                         ss->css_free(cgrp);
875
876                 cgrp->root->number_of_cgroups--;
877                 mutex_unlock(&cgroup_mutex);
878
879                 /*
880                  * Drop the active superblock reference that we took when we
881                  * created the cgroup
882                  */
883                 deactivate_super(cgrp->root->sb);
884
885                 /*
886                  * if we're getting rid of the cgroup, refcount should ensure
887                  * that there are no pidlists left.
888                  */
889                 BUG_ON(!list_empty(&cgrp->pidlists));
890
891                 simple_xattrs_free(&cgrp->xattrs);
892
893                 kfree_rcu(cgrp, rcu_head);
894         } else {
895                 struct cfent *cfe = __d_cfe(dentry);
896                 struct cgroup *cgrp = dentry->d_parent->d_fsdata;
897                 struct cftype *cft = cfe->type;
898
899                 WARN_ONCE(!list_empty(&cfe->node) &&
900                           cgrp != &cgrp->root->top_cgroup,
901                           "cfe still linked for %s\n", cfe->type->name);
902                 kfree(cfe);
903                 simple_xattrs_free(&cft->xattrs);
904         }
905         iput(inode);
906 }
907
908 static int cgroup_delete(const struct dentry *d)
909 {
910         return 1;
911 }
912
913 static void remove_dir(struct dentry *d)
914 {
915         struct dentry *parent = dget(d->d_parent);
916
917         d_delete(d);
918         simple_rmdir(parent->d_inode, d);
919         dput(parent);
920 }
921
922 static int cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
923 {
924         struct cfent *cfe;
925
926         lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
927         lockdep_assert_held(&cgroup_mutex);
928
929         list_for_each_entry(cfe, &cgrp->files, node) {
930                 struct dentry *d = cfe->dentry;
931
932                 if (cft && cfe->type != cft)
933                         continue;
934
935                 dget(d);
936                 d_delete(d);
937                 simple_unlink(cgrp->dentry->d_inode, d);
938                 list_del_init(&cfe->node);
939                 dput(d);
940
941                 return 0;
942         }
943         return -ENOENT;
944 }
945
946 /**
947  * cgroup_clear_directory - selective removal of base and subsystem files
948  * @dir: directory containing the files
949  * @base_files: true if the base files should be removed
950  * @subsys_mask: mask of the subsystem ids whose files should be removed
951  */
952 static void cgroup_clear_directory(struct dentry *dir, bool base_files,
953                                    unsigned long subsys_mask)
954 {
955         struct cgroup *cgrp = __d_cgrp(dir);
956         struct cgroup_subsys *ss;
957
958         for_each_subsys(cgrp->root, ss) {
959                 struct cftype_set *set;
960                 if (!test_bit(ss->subsys_id, &subsys_mask))
961                         continue;
962                 list_for_each_entry(set, &ss->cftsets, node)
963                         cgroup_rm_file(cgrp, set->cfts);
964         }
965         if (base_files) {
966                 while (!list_empty(&cgrp->files))
967                         cgroup_rm_file(cgrp, NULL);
968         }
969 }
970
971 /*
972  * NOTE : the dentry must have been dget()'ed
973  */
974 static void cgroup_d_remove_dir(struct dentry *dentry)
975 {
976         struct dentry *parent;
977         struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
978
979         cgroup_clear_directory(dentry, true, root->subsys_mask);
980
981         parent = dentry->d_parent;
982         spin_lock(&parent->d_lock);
983         spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
984         list_del_init(&dentry->d_u.d_child);
985         spin_unlock(&dentry->d_lock);
986         spin_unlock(&parent->d_lock);
987         remove_dir(dentry);
988 }
989
990 /*
991  * Call with cgroup_mutex held. Drops reference counts on modules, including
992  * any duplicate ones that parse_cgroupfs_options took. If this function
993  * returns an error, no reference counts are touched.
994  */
995 static int rebind_subsystems(struct cgroupfs_root *root,
996                               unsigned long final_subsys_mask)
997 {
998         unsigned long added_mask, removed_mask;
999         struct cgroup *cgrp = &root->top_cgroup;
1000         int i;
1001
1002         BUG_ON(!mutex_is_locked(&cgroup_mutex));
1003         BUG_ON(!mutex_is_locked(&cgroup_root_mutex));
1004
1005         removed_mask = root->actual_subsys_mask & ~final_subsys_mask;
1006         added_mask = final_subsys_mask & ~root->actual_subsys_mask;
1007         /* Check that any added subsystems are currently free */
1008         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1009                 unsigned long bit = 1UL << i;
1010                 struct cgroup_subsys *ss = subsys[i];
1011                 if (!(bit & added_mask))
1012                         continue;
1013                 /*
1014                  * Nobody should tell us to do a subsys that doesn't exist:
1015                  * parse_cgroupfs_options should catch that case and refcounts
1016                  * ensure that subsystems won't disappear once selected.
1017                  */
1018                 BUG_ON(ss == NULL);
1019                 if (ss->root != &rootnode) {
1020                         /* Subsystem isn't free */
1021                         return -EBUSY;
1022                 }
1023         }
1024
1025         /* Currently we don't handle adding/removing subsystems when
1026          * any child cgroups exist. This is theoretically supportable
1027          * but involves complex error handling, so it's being left until
1028          * later */
1029         if (root->number_of_cgroups > 1)
1030                 return -EBUSY;
1031
1032         /* Process each subsystem */
1033         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1034                 struct cgroup_subsys *ss = subsys[i];
1035                 unsigned long bit = 1UL << i;
1036                 if (bit & added_mask) {
1037                         /* We're binding this subsystem to this hierarchy */
1038                         BUG_ON(ss == NULL);
1039                         BUG_ON(cgrp->subsys[i]);
1040                         BUG_ON(!dummytop->subsys[i]);
1041                         BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
1042                         cgrp->subsys[i] = dummytop->subsys[i];
1043                         cgrp->subsys[i]->cgroup = cgrp;
1044                         list_move(&ss->sibling, &root->subsys_list);
1045                         ss->root = root;
1046                         if (ss->bind)
1047                                 ss->bind(cgrp);
1048                         /* refcount was already taken, and we're keeping it */
1049                 } else if (bit & removed_mask) {
1050                         /* We're removing this subsystem */
1051                         BUG_ON(ss == NULL);
1052                         BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
1053                         BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
1054                         if (ss->bind)
1055                                 ss->bind(dummytop);
1056                         dummytop->subsys[i]->cgroup = dummytop;
1057                         cgrp->subsys[i] = NULL;
1058                         subsys[i]->root = &rootnode;
1059                         list_move(&ss->sibling, &rootnode.subsys_list);
1060                         /* subsystem is now free - drop reference on module */
1061                         module_put(ss->module);
1062                 } else if (bit & final_subsys_mask) {
1063                         /* Subsystem state should already exist */
1064                         BUG_ON(ss == NULL);
1065                         BUG_ON(!cgrp->subsys[i]);
1066                         /*
1067                          * a refcount was taken, but we already had one, so
1068                          * drop the extra reference.
1069                          */
1070                         module_put(ss->module);
1071 #ifdef CONFIG_MODULE_UNLOAD
1072                         BUG_ON(ss->module && !module_refcount(ss->module));
1073 #endif
1074                 } else {
1075                         /* Subsystem state shouldn't exist */
1076                         BUG_ON(cgrp->subsys[i]);
1077                 }
1078         }
1079         root->subsys_mask = root->actual_subsys_mask = final_subsys_mask;
1080         synchronize_rcu();
1081
1082         return 0;
1083 }
1084
1085 static int cgroup_show_options(struct seq_file *seq, struct dentry *dentry)
1086 {
1087         struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
1088         struct cgroup_subsys *ss;
1089
1090         mutex_lock(&cgroup_root_mutex);
1091         for_each_subsys(root, ss)
1092                 seq_printf(seq, ",%s", ss->name);
1093         if (test_bit(ROOT_NOPREFIX, &root->flags))
1094                 seq_puts(seq, ",noprefix");
1095         if (test_bit(ROOT_XATTR, &root->flags))
1096                 seq_puts(seq, ",xattr");
1097         if (strlen(root->release_agent_path))
1098                 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1099         if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1100                 seq_puts(seq, ",clone_children");
1101         if (strlen(root->name))
1102                 seq_printf(seq, ",name=%s", root->name);
1103         mutex_unlock(&cgroup_root_mutex);
1104         return 0;
1105 }
1106
1107 struct cgroup_sb_opts {
1108         unsigned long subsys_mask;
1109         unsigned long flags;
1110         char *release_agent;
1111         bool cpuset_clone_children;
1112         char *name;
1113         /* User explicitly requested empty subsystem */
1114         bool none;
1115
1116         struct cgroupfs_root *new_root;
1117
1118 };
1119
1120 /*
1121  * Convert a hierarchy specifier into a bitmask of subsystems and flags. Call
1122  * with cgroup_mutex held to protect the subsys[] array. This function takes
1123  * refcounts on subsystems to be used, unless it returns error, in which case
1124  * no refcounts are taken.
1125  */
1126 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1127 {
1128         char *token, *o = data;
1129         bool all_ss = false, one_ss = false;
1130         unsigned long mask = (unsigned long)-1;
1131         int i;
1132         bool module_pin_failed = false;
1133
1134         BUG_ON(!mutex_is_locked(&cgroup_mutex));
1135
1136 #ifdef CONFIG_CPUSETS
1137         mask = ~(1UL << cpuset_subsys_id);
1138 #endif
1139
1140         memset(opts, 0, sizeof(*opts));
1141
1142         while ((token = strsep(&o, ",")) != NULL) {
1143                 if (!*token)
1144                         return -EINVAL;
1145                 if (!strcmp(token, "none")) {
1146                         /* Explicitly have no subsystems */
1147                         opts->none = true;
1148                         continue;
1149                 }
1150                 if (!strcmp(token, "all")) {
1151                         /* Mutually exclusive option 'all' + subsystem name */
1152                         if (one_ss)
1153                                 return -EINVAL;
1154                         all_ss = true;
1155                         continue;
1156                 }
1157                 if (!strcmp(token, "noprefix")) {
1158                         set_bit(ROOT_NOPREFIX, &opts->flags);
1159                         continue;
1160                 }
1161                 if (!strcmp(token, "clone_children")) {
1162                         opts->cpuset_clone_children = true;
1163                         continue;
1164                 }
1165                 if (!strcmp(token, "xattr")) {
1166                         set_bit(ROOT_XATTR, &opts->flags);
1167                         continue;
1168                 }
1169                 if (!strncmp(token, "release_agent=", 14)) {
1170                         /* Specifying two release agents is forbidden */
1171                         if (opts->release_agent)
1172                                 return -EINVAL;
1173                         opts->release_agent =
1174                                 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1175                         if (!opts->release_agent)
1176                                 return -ENOMEM;
1177                         continue;
1178                 }
1179                 if (!strncmp(token, "name=", 5)) {
1180                         const char *name = token + 5;
1181                         /* Can't specify an empty name */
1182                         if (!strlen(name))
1183                                 return -EINVAL;
1184                         /* Must match [\w.-]+ */
1185                         for (i = 0; i < strlen(name); i++) {
1186                                 char c = name[i];
1187                                 if (isalnum(c))
1188                                         continue;
1189                                 if ((c == '.') || (c == '-') || (c == '_'))
1190                                         continue;
1191                                 return -EINVAL;
1192                         }
1193                         /* Specifying two names is forbidden */
1194                         if (opts->name)
1195                                 return -EINVAL;
1196                         opts->name = kstrndup(name,
1197                                               MAX_CGROUP_ROOT_NAMELEN - 1,
1198                                               GFP_KERNEL);
1199                         if (!opts->name)
1200                                 return -ENOMEM;
1201
1202                         continue;
1203                 }
1204
1205                 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1206                         struct cgroup_subsys *ss = subsys[i];
1207                         if (ss == NULL)
1208                                 continue;
1209                         if (strcmp(token, ss->name))
1210                                 continue;
1211                         if (ss->disabled)
1212                                 continue;
1213
1214                         /* Mutually exclusive option 'all' + subsystem name */
1215                         if (all_ss)
1216                                 return -EINVAL;
1217                         set_bit(i, &opts->subsys_mask);
1218                         one_ss = true;
1219
1220                         break;
1221                 }
1222                 if (i == CGROUP_SUBSYS_COUNT)
1223                         return -ENOENT;
1224         }
1225
1226         /*
1227          * If the 'all' option was specified select all the subsystems,
1228          * otherwise if 'none', 'name=' and a subsystem name options
1229          * were not specified, let's default to 'all'
1230          */
1231         if (all_ss || (!one_ss && !opts->none && !opts->name)) {
1232                 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1233                         struct cgroup_subsys *ss = subsys[i];
1234                         if (ss == NULL)
1235                                 continue;
1236                         if (ss->disabled)
1237                                 continue;
1238                         set_bit(i, &opts->subsys_mask);
1239                 }
1240         }
1241
1242         /* Consistency checks */
1243
1244         /*
1245          * Option noprefix was introduced just for backward compatibility
1246          * with the old cpuset, so we allow noprefix only if mounting just
1247          * the cpuset subsystem.
1248          */
1249         if (test_bit(ROOT_NOPREFIX, &opts->flags) &&
1250             (opts->subsys_mask & mask))
1251                 return -EINVAL;
1252
1253
1254         /* Can't specify "none" and some subsystems */
1255         if (opts->subsys_mask && opts->none)
1256                 return -EINVAL;
1257
1258         /*
1259          * We either have to specify by name or by subsystems. (So all
1260          * empty hierarchies must have a name).
1261          */
1262         if (!opts->subsys_mask && !opts->name)
1263                 return -EINVAL;
1264
1265         /*
1266          * Grab references on all the modules we'll need, so the subsystems
1267          * don't dance around before rebind_subsystems attaches them. This may
1268          * take duplicate reference counts on a subsystem that's already used,
1269          * but rebind_subsystems handles this case.
1270          */
1271         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1272                 unsigned long bit = 1UL << i;
1273
1274                 if (!(bit & opts->subsys_mask))
1275                         continue;
1276                 if (!try_module_get(subsys[i]->module)) {
1277                         module_pin_failed = true;
1278                         break;
1279                 }
1280         }
1281         if (module_pin_failed) {
1282                 /*
1283                  * oops, one of the modules was going away. this means that we
1284                  * raced with a module_delete call, and to the user this is
1285                  * essentially a "subsystem doesn't exist" case.
1286                  */
1287                 for (i--; i >= 0; i--) {
1288                         /* drop refcounts only on the ones we took */
1289                         unsigned long bit = 1UL << i;
1290
1291                         if (!(bit & opts->subsys_mask))
1292                                 continue;
1293                         module_put(subsys[i]->module);
1294                 }
1295                 return -ENOENT;
1296         }
1297
1298         return 0;
1299 }
1300
1301 static void drop_parsed_module_refcounts(unsigned long subsys_mask)
1302 {
1303         int i;
1304         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1305                 unsigned long bit = 1UL << i;
1306
1307                 if (!(bit & subsys_mask))
1308                         continue;
1309                 module_put(subsys[i]->module);
1310         }
1311 }
1312
1313 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1314 {
1315         int ret = 0;
1316         struct cgroupfs_root *root = sb->s_fs_info;
1317         struct cgroup *cgrp = &root->top_cgroup;
1318         struct cgroup_sb_opts opts;
1319         unsigned long added_mask, removed_mask;
1320
1321         mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1322         mutex_lock(&cgroup_mutex);
1323         mutex_lock(&cgroup_root_mutex);
1324
1325         /* See what subsystems are wanted */
1326         ret = parse_cgroupfs_options(data, &opts);
1327         if (ret)
1328                 goto out_unlock;
1329
1330         /* See feature-removal-schedule.txt */
1331         if (opts.subsys_mask != root->actual_subsys_mask || opts.release_agent)
1332                 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1333                            task_tgid_nr(current), current->comm);
1334
1335         added_mask = opts.subsys_mask & ~root->subsys_mask;
1336         removed_mask = root->subsys_mask & ~opts.subsys_mask;
1337
1338         /* Don't allow flags or name to change at remount */
1339         if (opts.flags != root->flags ||
1340             (opts.name && strcmp(opts.name, root->name))) {
1341                 ret = -EINVAL;
1342                 drop_parsed_module_refcounts(opts.subsys_mask);
1343                 goto out_unlock;
1344         }
1345
1346         ret = rebind_subsystems(root, opts.subsys_mask);
1347         if (ret) {
1348                 drop_parsed_module_refcounts(opts.subsys_mask);
1349                 goto out_unlock;
1350         }
1351
1352         /* clear out any existing files and repopulate subsystem files */
1353         cgroup_clear_directory(cgrp->dentry, false, removed_mask);
1354         /* re-populate subsystem files */
1355         cgroup_populate_dir(cgrp, false, added_mask);
1356
1357         if (opts.release_agent)
1358                 strcpy(root->release_agent_path, opts.release_agent);
1359  out_unlock:
1360         kfree(opts.release_agent);
1361         kfree(opts.name);
1362         mutex_unlock(&cgroup_root_mutex);
1363         mutex_unlock(&cgroup_mutex);
1364         mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1365         return ret;
1366 }
1367
1368 static const struct super_operations cgroup_ops = {
1369         .statfs = simple_statfs,
1370         .drop_inode = generic_delete_inode,
1371         .show_options = cgroup_show_options,
1372         .remount_fs = cgroup_remount,
1373 };
1374
1375 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1376 {
1377         INIT_LIST_HEAD(&cgrp->sibling);
1378         INIT_LIST_HEAD(&cgrp->children);
1379         INIT_LIST_HEAD(&cgrp->files);
1380         INIT_LIST_HEAD(&cgrp->css_sets);
1381         INIT_LIST_HEAD(&cgrp->allcg_node);
1382         INIT_LIST_HEAD(&cgrp->release_list);
1383         INIT_LIST_HEAD(&cgrp->pidlists);
1384         mutex_init(&cgrp->pidlist_mutex);
1385         INIT_LIST_HEAD(&cgrp->event_list);
1386         spin_lock_init(&cgrp->event_list_lock);
1387         simple_xattrs_init(&cgrp->xattrs);
1388 }
1389
1390 static void init_cgroup_root(struct cgroupfs_root *root)
1391 {
1392         struct cgroup *cgrp = &root->top_cgroup;
1393
1394         INIT_LIST_HEAD(&root->subsys_list);
1395         INIT_LIST_HEAD(&root->root_list);
1396         INIT_LIST_HEAD(&root->allcg_list);
1397         root->number_of_cgroups = 1;
1398         cgrp->root = root;
1399         cgrp->top_cgroup = cgrp;
1400         list_add_tail(&cgrp->allcg_node, &root->allcg_list);
1401         init_cgroup_housekeeping(cgrp);
1402 }
1403
1404 static bool init_root_id(struct cgroupfs_root *root)
1405 {
1406         int ret = 0;
1407
1408         do {
1409                 if (!ida_pre_get(&hierarchy_ida, GFP_KERNEL))
1410                         return false;
1411                 spin_lock(&hierarchy_id_lock);
1412                 /* Try to allocate the next unused ID */
1413                 ret = ida_get_new_above(&hierarchy_ida, next_hierarchy_id,
1414                                         &root->hierarchy_id);
1415                 if (ret == -ENOSPC)
1416                         /* Try again starting from 0 */
1417                         ret = ida_get_new(&hierarchy_ida, &root->hierarchy_id);
1418                 if (!ret) {
1419                         next_hierarchy_id = root->hierarchy_id + 1;
1420                 } else if (ret != -EAGAIN) {
1421                         /* Can only get here if the 31-bit IDR is full ... */
1422                         BUG_ON(ret);
1423                 }
1424                 spin_unlock(&hierarchy_id_lock);
1425         } while (ret);
1426         return true;
1427 }
1428
1429 static int cgroup_test_super(struct super_block *sb, void *data)
1430 {
1431         struct cgroup_sb_opts *opts = data;
1432         struct cgroupfs_root *root = sb->s_fs_info;
1433
1434         /* If we asked for a name then it must match */
1435         if (opts->name && strcmp(opts->name, root->name))
1436                 return 0;
1437
1438         /*
1439          * If we asked for subsystems (or explicitly for no
1440          * subsystems) then they must match
1441          */
1442         if ((opts->subsys_mask || opts->none)
1443             && (opts->subsys_mask != root->subsys_mask))
1444                 return 0;
1445
1446         return 1;
1447 }
1448
1449 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1450 {
1451         struct cgroupfs_root *root;
1452
1453         if (!opts->subsys_mask && !opts->none)
1454                 return NULL;
1455
1456         root = kzalloc(sizeof(*root), GFP_KERNEL);
1457         if (!root)
1458                 return ERR_PTR(-ENOMEM);
1459
1460         if (!init_root_id(root)) {
1461                 kfree(root);
1462                 return ERR_PTR(-ENOMEM);
1463         }
1464         init_cgroup_root(root);
1465
1466         root->subsys_mask = opts->subsys_mask;
1467         root->flags = opts->flags;
1468         if (opts->release_agent)
1469                 strcpy(root->release_agent_path, opts->release_agent);
1470         if (opts->name)
1471                 strcpy(root->name, opts->name);
1472         if (opts->cpuset_clone_children)
1473                 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1474         return root;
1475 }
1476
1477 static void cgroup_drop_root(struct cgroupfs_root *root)
1478 {
1479         if (!root)
1480                 return;
1481
1482         BUG_ON(!root->hierarchy_id);
1483         spin_lock(&hierarchy_id_lock);
1484         ida_remove(&hierarchy_ida, root->hierarchy_id);
1485         spin_unlock(&hierarchy_id_lock);
1486         kfree(root);
1487 }
1488
1489 static int cgroup_set_super(struct super_block *sb, void *data)
1490 {
1491         int ret;
1492         struct cgroup_sb_opts *opts = data;
1493
1494         /* If we don't have a new root, we can't set up a new sb */
1495         if (!opts->new_root)
1496                 return -EINVAL;
1497
1498         BUG_ON(!opts->subsys_mask && !opts->none);
1499
1500         ret = set_anon_super(sb, NULL);
1501         if (ret)
1502                 return ret;
1503
1504         sb->s_fs_info = opts->new_root;
1505         opts->new_root->sb = sb;
1506
1507         sb->s_blocksize = PAGE_CACHE_SIZE;
1508         sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1509         sb->s_magic = CGROUP_SUPER_MAGIC;
1510         sb->s_op = &cgroup_ops;
1511
1512         return 0;
1513 }
1514
1515 static int cgroup_get_rootdir(struct super_block *sb)
1516 {
1517         static const struct dentry_operations cgroup_dops = {
1518                 .d_iput = cgroup_diput,
1519                 .d_delete = cgroup_delete,
1520         };
1521
1522         struct inode *inode =
1523                 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1524
1525         if (!inode)
1526                 return -ENOMEM;
1527
1528         inode->i_fop = &simple_dir_operations;
1529         inode->i_op = &cgroup_dir_inode_operations;
1530         /* directories start off with i_nlink == 2 (for "." entry) */
1531         inc_nlink(inode);
1532         sb->s_root = d_make_root(inode);
1533         if (!sb->s_root)
1534                 return -ENOMEM;
1535         /* for everything else we want ->d_op set */
1536         sb->s_d_op = &cgroup_dops;
1537         return 0;
1538 }
1539
1540 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1541                          int flags, const char *unused_dev_name,
1542                          void *data)
1543 {
1544         struct cgroup_sb_opts opts;
1545         struct cgroupfs_root *root;
1546         int ret = 0;
1547         struct super_block *sb;
1548         struct cgroupfs_root *new_root;
1549         struct inode *inode;
1550
1551         /* First find the desired set of subsystems */
1552         mutex_lock(&cgroup_mutex);
1553         ret = parse_cgroupfs_options(data, &opts);
1554         mutex_unlock(&cgroup_mutex);
1555         if (ret)
1556                 goto out_err;
1557
1558         /*
1559          * Allocate a new cgroup root. We may not need it if we're
1560          * reusing an existing hierarchy.
1561          */
1562         new_root = cgroup_root_from_opts(&opts);
1563         if (IS_ERR(new_root)) {
1564                 ret = PTR_ERR(new_root);
1565                 goto drop_modules;
1566         }
1567         opts.new_root = new_root;
1568
1569         /* Locate an existing or new sb for this hierarchy */
1570         sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1571         if (IS_ERR(sb)) {
1572                 ret = PTR_ERR(sb);
1573                 cgroup_drop_root(opts.new_root);
1574                 goto drop_modules;
1575         }
1576
1577         root = sb->s_fs_info;
1578         BUG_ON(!root);
1579         if (root == opts.new_root) {
1580                 /* We used the new root structure, so this is a new hierarchy */
1581                 struct list_head tmp_cg_links;
1582                 struct cgroup *root_cgrp = &root->top_cgroup;
1583                 struct cgroupfs_root *existing_root;
1584                 const struct cred *cred;
1585                 int i;
1586
1587                 BUG_ON(sb->s_root != NULL);
1588
1589                 ret = cgroup_get_rootdir(sb);
1590                 if (ret)
1591                         goto drop_new_super;
1592                 inode = sb->s_root->d_inode;
1593
1594                 mutex_lock(&inode->i_mutex);
1595                 mutex_lock(&cgroup_mutex);
1596                 mutex_lock(&cgroup_root_mutex);
1597
1598                 /* Check for name clashes with existing mounts */
1599                 ret = -EBUSY;
1600                 if (strlen(root->name))
1601                         for_each_active_root(existing_root)
1602                                 if (!strcmp(existing_root->name, root->name))
1603                                         goto unlock_drop;
1604
1605                 /*
1606                  * We're accessing css_set_count without locking
1607                  * css_set_lock here, but that's OK - it can only be
1608                  * increased by someone holding cgroup_lock, and
1609                  * that's us. The worst that can happen is that we
1610                  * have some link structures left over
1611                  */
1612                 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
1613                 if (ret)
1614                         goto unlock_drop;
1615
1616                 ret = rebind_subsystems(root, root->subsys_mask);
1617                 if (ret == -EBUSY) {
1618                         free_cg_links(&tmp_cg_links);
1619                         goto unlock_drop;
1620                 }
1621                 /*
1622                  * There must be no failure case after here, since rebinding
1623                  * takes care of subsystems' refcounts, which are explicitly
1624                  * dropped in the failure exit path.
1625                  */
1626
1627                 /* EBUSY should be the only error here */
1628                 BUG_ON(ret);
1629
1630                 list_add(&root->root_list, &roots);
1631                 root_count++;
1632
1633                 sb->s_root->d_fsdata = root_cgrp;
1634                 root->top_cgroup.dentry = sb->s_root;
1635
1636                 /* Link the top cgroup in this hierarchy into all
1637                  * the css_set objects */
1638                 write_lock(&css_set_lock);
1639                 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
1640                         struct hlist_head *hhead = &css_set_table[i];
1641                         struct hlist_node *node;
1642                         struct css_set *cg;
1643
1644                         hlist_for_each_entry(cg, node, hhead, hlist)
1645                                 link_css_set(&tmp_cg_links, cg, root_cgrp);
1646                 }
1647                 write_unlock(&css_set_lock);
1648
1649                 free_cg_links(&tmp_cg_links);
1650
1651                 BUG_ON(!list_empty(&root_cgrp->children));
1652                 BUG_ON(root->number_of_cgroups != 1);
1653
1654                 cred = override_creds(&init_cred);
1655                 cgroup_populate_dir(root_cgrp, true, root->subsys_mask);
1656                 revert_creds(cred);
1657                 mutex_unlock(&cgroup_root_mutex);
1658                 mutex_unlock(&cgroup_mutex);
1659                 mutex_unlock(&inode->i_mutex);
1660         } else {
1661                 /*
1662                  * We re-used an existing hierarchy - the new root (if
1663                  * any) is not needed
1664                  */
1665                 cgroup_drop_root(opts.new_root);
1666                 /* no subsys rebinding, so refcounts don't change */
1667                 drop_parsed_module_refcounts(opts.subsys_mask);
1668         }
1669
1670         kfree(opts.release_agent);
1671         kfree(opts.name);
1672         return dget(sb->s_root);
1673
1674  unlock_drop:
1675         mutex_unlock(&cgroup_root_mutex);
1676         mutex_unlock(&cgroup_mutex);
1677         mutex_unlock(&inode->i_mutex);
1678  drop_new_super:
1679         deactivate_locked_super(sb);
1680  drop_modules:
1681         drop_parsed_module_refcounts(opts.subsys_mask);
1682  out_err:
1683         kfree(opts.release_agent);
1684         kfree(opts.name);
1685         return ERR_PTR(ret);
1686 }
1687
1688 static void cgroup_kill_sb(struct super_block *sb) {
1689         struct cgroupfs_root *root = sb->s_fs_info;
1690         struct cgroup *cgrp = &root->top_cgroup;
1691         int ret;
1692         struct cg_cgroup_link *link;
1693         struct cg_cgroup_link *saved_link;
1694
1695         BUG_ON(!root);
1696
1697         BUG_ON(root->number_of_cgroups != 1);
1698         BUG_ON(!list_empty(&cgrp->children));
1699
1700         mutex_lock(&cgroup_mutex);
1701         mutex_lock(&cgroup_root_mutex);
1702
1703         /* Rebind all subsystems back to the default hierarchy */
1704         ret = rebind_subsystems(root, 0);
1705         /* Shouldn't be able to fail ... */
1706         BUG_ON(ret);
1707
1708         /*
1709          * Release all the links from css_sets to this hierarchy's
1710          * root cgroup
1711          */
1712         write_lock(&css_set_lock);
1713
1714         list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1715                                  cgrp_link_list) {
1716                 list_del(&link->cg_link_list);
1717                 list_del(&link->cgrp_link_list);
1718                 kfree(link);
1719         }
1720         write_unlock(&css_set_lock);
1721
1722         if (!list_empty(&root->root_list)) {
1723                 list_del(&root->root_list);
1724                 root_count--;
1725         }
1726
1727         mutex_unlock(&cgroup_root_mutex);
1728         mutex_unlock(&cgroup_mutex);
1729
1730         simple_xattrs_free(&cgrp->xattrs);
1731
1732         kill_litter_super(sb);
1733         cgroup_drop_root(root);
1734 }
1735
1736 static struct file_system_type cgroup_fs_type = {
1737         .name = "cgroup",
1738         .mount = cgroup_mount,
1739         .kill_sb = cgroup_kill_sb,
1740 };
1741
1742 static struct kobject *cgroup_kobj;
1743
1744 /**
1745  * cgroup_path - generate the path of a cgroup
1746  * @cgrp: the cgroup in question
1747  * @buf: the buffer to write the path into
1748  * @buflen: the length of the buffer
1749  *
1750  * Called with cgroup_mutex held or else with an RCU-protected cgroup
1751  * reference.  Writes path of cgroup into buf.  Returns 0 on success,
1752  * -errno on error.
1753  */
1754 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1755 {
1756         struct dentry *dentry = cgrp->dentry;
1757         char *start;
1758
1759         rcu_lockdep_assert(rcu_read_lock_held() || cgroup_lock_is_held(),
1760                            "cgroup_path() called without proper locking");
1761
1762         if (!dentry || cgrp == dummytop) {
1763                 /*
1764                  * Inactive subsystems have no dentry for their root
1765                  * cgroup
1766                  */
1767                 strcpy(buf, "/");
1768                 return 0;
1769         }
1770
1771         start = buf + buflen - 1;
1772
1773         *start = '\0';
1774         for (;;) {
1775                 int len = dentry->d_name.len;
1776
1777                 if ((start -= len) < buf)
1778                         return -ENAMETOOLONG;
1779                 memcpy(start, dentry->d_name.name, len);
1780                 cgrp = cgrp->parent;
1781                 if (!cgrp)
1782                         break;
1783
1784                 dentry = cgrp->dentry;
1785                 if (!cgrp->parent)
1786                         continue;
1787                 if (--start < buf)
1788                         return -ENAMETOOLONG;
1789                 *start = '/';
1790         }
1791         memmove(buf, start, buf + buflen - start);
1792         return 0;
1793 }
1794 EXPORT_SYMBOL_GPL(cgroup_path);
1795
1796 /*
1797  * Control Group taskset
1798  */
1799 struct task_and_cgroup {
1800         struct task_struct      *task;
1801         struct cgroup           *cgrp;
1802         struct css_set          *cg;
1803 };
1804
1805 struct cgroup_taskset {
1806         struct task_and_cgroup  single;
1807         struct flex_array       *tc_array;
1808         int                     tc_array_len;
1809         int                     idx;
1810         struct cgroup           *cur_cgrp;
1811 };
1812
1813 /**
1814  * cgroup_taskset_first - reset taskset and return the first task
1815  * @tset: taskset of interest
1816  *
1817  * @tset iteration is initialized and the first task is returned.
1818  */
1819 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1820 {
1821         if (tset->tc_array) {
1822                 tset->idx = 0;
1823                 return cgroup_taskset_next(tset);
1824         } else {
1825                 tset->cur_cgrp = tset->single.cgrp;
1826                 return tset->single.task;
1827         }
1828 }
1829 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1830
1831 /**
1832  * cgroup_taskset_next - iterate to the next task in taskset
1833  * @tset: taskset of interest
1834  *
1835  * Return the next task in @tset.  Iteration must have been initialized
1836  * with cgroup_taskset_first().
1837  */
1838 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1839 {
1840         struct task_and_cgroup *tc;
1841
1842         if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1843                 return NULL;
1844
1845         tc = flex_array_get(tset->tc_array, tset->idx++);
1846         tset->cur_cgrp = tc->cgrp;
1847         return tc->task;
1848 }
1849 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1850
1851 /**
1852  * cgroup_taskset_cur_cgroup - return the matching cgroup for the current task
1853  * @tset: taskset of interest
1854  *
1855  * Return the cgroup for the current (last returned) task of @tset.  This
1856  * function must be preceded by either cgroup_taskset_first() or
1857  * cgroup_taskset_next().
1858  */
1859 struct cgroup *cgroup_taskset_cur_cgroup(struct cgroup_taskset *tset)
1860 {
1861         return tset->cur_cgrp;
1862 }
1863 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_cgroup);
1864
1865 /**
1866  * cgroup_taskset_size - return the number of tasks in taskset
1867  * @tset: taskset of interest
1868  */
1869 int cgroup_taskset_size(struct cgroup_taskset *tset)
1870 {
1871         return tset->tc_array ? tset->tc_array_len : 1;
1872 }
1873 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1874
1875
1876 /*
1877  * cgroup_task_migrate - move a task from one cgroup to another.
1878  *
1879  * 'guarantee' is set if the caller promises that a new css_set for the task
1880  * will already exist. If not set, this function might sleep, and can fail with
1881  * -ENOMEM. Must be called with cgroup_mutex and threadgroup locked.
1882  */
1883 static void cgroup_task_migrate(struct cgroup *cgrp, struct cgroup *oldcgrp,
1884                                 struct task_struct *tsk, struct css_set *newcg)
1885 {
1886         struct css_set *oldcg;
1887
1888         /*
1889          * We are synchronized through threadgroup_lock() against PF_EXITING
1890          * setting such that we can't race against cgroup_exit() changing the
1891          * css_set to init_css_set and dropping the old one.
1892          */
1893         WARN_ON_ONCE(tsk->flags & PF_EXITING);
1894         oldcg = tsk->cgroups;
1895
1896         task_lock(tsk);
1897         rcu_assign_pointer(tsk->cgroups, newcg);
1898         task_unlock(tsk);
1899
1900         /* Update the css_set linked lists if we're using them */
1901         write_lock(&css_set_lock);
1902         if (!list_empty(&tsk->cg_list))
1903                 list_move(&tsk->cg_list, &newcg->tasks);
1904         write_unlock(&css_set_lock);
1905
1906         /*
1907          * We just gained a reference on oldcg by taking it from the task. As
1908          * trading it for newcg is protected by cgroup_mutex, we're safe to drop
1909          * it here; it will be freed under RCU.
1910          */
1911         set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1912         put_css_set(oldcg);
1913 }
1914
1915 /**
1916  * cgroup_attach_task - attach task 'tsk' to cgroup 'cgrp'
1917  * @cgrp: the cgroup the task is attaching to
1918  * @tsk: the task to be attached
1919  *
1920  * Call with cgroup_mutex and threadgroup locked. May take task_lock of
1921  * @tsk during call.
1922  */
1923 int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
1924 {
1925         int retval = 0;
1926         struct cgroup_subsys *ss, *failed_ss = NULL;
1927         struct cgroup *oldcgrp;
1928         struct cgroupfs_root *root = cgrp->root;
1929         struct cgroup_taskset tset = { };
1930         struct css_set *newcg;
1931
1932         /* @tsk either already exited or can't exit until the end */
1933         if (tsk->flags & PF_EXITING)
1934                 return -ESRCH;
1935
1936         /* Nothing to do if the task is already in that cgroup */
1937         oldcgrp = task_cgroup_from_root(tsk, root);
1938         if (cgrp == oldcgrp)
1939                 return 0;
1940
1941         tset.single.task = tsk;
1942         tset.single.cgrp = oldcgrp;
1943
1944         for_each_subsys(root, ss) {
1945                 if (ss->can_attach) {
1946                         retval = ss->can_attach(cgrp, &tset);
1947                         if (retval) {
1948                                 /*
1949                                  * Remember on which subsystem the can_attach()
1950                                  * failed, so that we only call cancel_attach()
1951                                  * against the subsystems whose can_attach()
1952                                  * succeeded. (See below)
1953                                  */
1954                                 failed_ss = ss;
1955                                 goto out;
1956                         }
1957                 }
1958         }
1959
1960         newcg = find_css_set(tsk->cgroups, cgrp);
1961         if (!newcg) {
1962                 retval = -ENOMEM;
1963                 goto out;
1964         }
1965
1966         cgroup_task_migrate(cgrp, oldcgrp, tsk, newcg);
1967
1968         for_each_subsys(root, ss) {
1969                 if (ss->attach)
1970                         ss->attach(cgrp, &tset);
1971         }
1972
1973         synchronize_rcu();
1974 out:
1975         if (retval) {
1976                 for_each_subsys(root, ss) {
1977                         if (ss == failed_ss)
1978                                 /*
1979                                  * This subsystem was the one that failed the
1980                                  * can_attach() check earlier, so we don't need
1981                                  * to call cancel_attach() against it or any
1982                                  * remaining subsystems.
1983                                  */
1984                                 break;
1985                         if (ss->cancel_attach)
1986                                 ss->cancel_attach(cgrp, &tset);
1987                 }
1988         }
1989         return retval;
1990 }
1991
1992 /**
1993  * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
1994  * @from: attach to all cgroups of a given task
1995  * @tsk: the task to be attached
1996  */
1997 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
1998 {
1999         struct cgroupfs_root *root;
2000         int retval = 0;
2001
2002         cgroup_lock();
2003         for_each_active_root(root) {
2004                 struct cgroup *from_cg = task_cgroup_from_root(from, root);
2005
2006                 retval = cgroup_attach_task(from_cg, tsk);
2007                 if (retval)
2008                         break;
2009         }
2010         cgroup_unlock();
2011
2012         return retval;
2013 }
2014 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2015
2016 /**
2017  * cgroup_attach_proc - attach all threads in a threadgroup to a cgroup
2018  * @cgrp: the cgroup to attach to
2019  * @leader: the threadgroup leader task_struct of the group to be attached
2020  *
2021  * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
2022  * task_lock of each thread in leader's threadgroup individually in turn.
2023  */
2024 static int cgroup_attach_proc(struct cgroup *cgrp, struct task_struct *leader)
2025 {
2026         int retval, i, group_size;
2027         struct cgroup_subsys *ss, *failed_ss = NULL;
2028         /* guaranteed to be initialized later, but the compiler needs this */
2029         struct cgroupfs_root *root = cgrp->root;
2030         /* threadgroup list cursor and array */
2031         struct task_struct *tsk;
2032         struct task_and_cgroup *tc;
2033         struct flex_array *group;
2034         struct cgroup_taskset tset = { };
2035
2036         /*
2037          * step 0: in order to do expensive, possibly blocking operations for
2038          * every thread, we cannot iterate the thread group list, since it needs
2039          * rcu or tasklist locked. instead, build an array of all threads in the
2040          * group - group_rwsem prevents new threads from appearing, and if
2041          * threads exit, this will just be an over-estimate.
2042          */
2043         group_size = get_nr_threads(leader);
2044         /* flex_array supports very large thread-groups better than kmalloc. */
2045         group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
2046         if (!group)
2047                 return -ENOMEM;
2048         /* pre-allocate to guarantee space while iterating in rcu read-side. */
2049         retval = flex_array_prealloc(group, 0, group_size - 1, GFP_KERNEL);
2050         if (retval)
2051                 goto out_free_group_list;
2052
2053         tsk = leader;
2054         i = 0;
2055         /*
2056          * Prevent freeing of tasks while we take a snapshot. Tasks that are
2057          * already PF_EXITING could be freed from underneath us unless we
2058          * take an rcu_read_lock.
2059          */
2060         rcu_read_lock();
2061         do {
2062                 struct task_and_cgroup ent;
2063
2064                 /* @tsk either already exited or can't exit until the end */
2065                 if (tsk->flags & PF_EXITING)
2066                         continue;
2067
2068                 /* as per above, nr_threads may decrease, but not increase. */
2069                 BUG_ON(i >= group_size);
2070                 ent.task = tsk;
2071                 ent.cgrp = task_cgroup_from_root(tsk, root);
2072                 /* nothing to do if this task is already in the cgroup */
2073                 if (ent.cgrp == cgrp)
2074                         continue;
2075                 /*
2076                  * saying GFP_ATOMIC has no effect here because we did prealloc
2077                  * earlier, but it's good form to communicate our expectations.
2078                  */
2079                 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
2080                 BUG_ON(retval != 0);
2081                 i++;
2082         } while_each_thread(leader, tsk);
2083         rcu_read_unlock();
2084         /* remember the number of threads in the array for later. */
2085         group_size = i;
2086         tset.tc_array = group;
2087         tset.tc_array_len = group_size;
2088
2089         /* methods shouldn't be called if no task is actually migrating */
2090         retval = 0;
2091         if (!group_size)
2092                 goto out_free_group_list;
2093
2094         /*
2095          * step 1: check that we can legitimately attach to the cgroup.
2096          */
2097         for_each_subsys(root, ss) {
2098                 if (ss->can_attach) {
2099                         retval = ss->can_attach(cgrp, &tset);
2100                         if (retval) {
2101                                 failed_ss = ss;
2102                                 goto out_cancel_attach;
2103                         }
2104                 }
2105         }
2106
2107         /*
2108          * step 2: make sure css_sets exist for all threads to be migrated.
2109          * we use find_css_set, which allocates a new one if necessary.
2110          */
2111         for (i = 0; i < group_size; i++) {
2112                 tc = flex_array_get(group, i);
2113                 tc->cg = find_css_set(tc->task->cgroups, cgrp);
2114                 if (!tc->cg) {
2115                         retval = -ENOMEM;
2116                         goto out_put_css_set_refs;
2117                 }
2118         }
2119
2120         /*
2121          * step 3: now that we're guaranteed success wrt the css_sets,
2122          * proceed to move all tasks to the new cgroup.  There are no
2123          * failure cases after here, so this is the commit point.
2124          */
2125         for (i = 0; i < group_size; i++) {
2126                 tc = flex_array_get(group, i);
2127                 cgroup_task_migrate(cgrp, tc->cgrp, tc->task, tc->cg);
2128         }
2129         /* nothing is sensitive to fork() after this point. */
2130
2131         /*
2132          * step 4: do subsystem attach callbacks.
2133          */
2134         for_each_subsys(root, ss) {
2135                 if (ss->attach)
2136                         ss->attach(cgrp, &tset);
2137         }
2138
2139         /*
2140          * step 5: success! and cleanup
2141          */
2142         synchronize_rcu();
2143         retval = 0;
2144 out_put_css_set_refs:
2145         if (retval) {
2146                 for (i = 0; i < group_size; i++) {
2147                         tc = flex_array_get(group, i);
2148                         if (!tc->cg)
2149                                 break;
2150                         put_css_set(tc->cg);
2151                 }
2152         }
2153 out_cancel_attach:
2154         if (retval) {
2155                 for_each_subsys(root, ss) {
2156                         if (ss == failed_ss)
2157                                 break;
2158                         if (ss->cancel_attach)
2159                                 ss->cancel_attach(cgrp, &tset);
2160                 }
2161         }
2162 out_free_group_list:
2163         flex_array_free(group);
2164         return retval;
2165 }
2166
2167 /*
2168  * Find the task_struct of the task to attach by vpid and pass it along to the
2169  * function to attach either it or all tasks in its threadgroup. Will lock
2170  * cgroup_mutex and threadgroup; may take task_lock of task.
2171  */
2172 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2173 {
2174         struct task_struct *tsk;
2175         const struct cred *cred = current_cred(), *tcred;
2176         int ret;
2177
2178         if (!cgroup_lock_live_group(cgrp))
2179                 return -ENODEV;
2180
2181 retry_find_task:
2182         rcu_read_lock();
2183         if (pid) {
2184                 tsk = find_task_by_vpid(pid);
2185                 if (!tsk) {
2186                         rcu_read_unlock();
2187                         ret= -ESRCH;
2188                         goto out_unlock_cgroup;
2189                 }
2190                 /*
2191                  * even if we're attaching all tasks in the thread group, we
2192                  * only need to check permissions on one of them.
2193                  */
2194                 tcred = __task_cred(tsk);
2195                 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2196                     !uid_eq(cred->euid, tcred->uid) &&
2197                     !uid_eq(cred->euid, tcred->suid)) {
2198                         rcu_read_unlock();
2199                         ret = -EACCES;
2200                         goto out_unlock_cgroup;
2201                 }
2202         } else
2203                 tsk = current;
2204
2205         if (threadgroup)
2206                 tsk = tsk->group_leader;
2207
2208         /*
2209          * Workqueue threads may acquire PF_THREAD_BOUND and become
2210          * trapped in a cpuset, or RT worker may be born in a cgroup
2211          * with no rt_runtime allocated.  Just say no.
2212          */
2213         if (tsk == kthreadd_task || (tsk->flags & PF_THREAD_BOUND)) {
2214                 ret = -EINVAL;
2215                 rcu_read_unlock();
2216                 goto out_unlock_cgroup;
2217         }
2218
2219         get_task_struct(tsk);
2220         rcu_read_unlock();
2221
2222         threadgroup_lock(tsk);
2223         if (threadgroup) {
2224                 if (!thread_group_leader(tsk)) {
2225                         /*
2226                          * a race with de_thread from another thread's exec()
2227                          * may strip us of our leadership, if this happens,
2228                          * there is no choice but to throw this task away and
2229                          * try again; this is
2230                          * "double-double-toil-and-trouble-check locking".
2231                          */
2232                         threadgroup_unlock(tsk);
2233                         put_task_struct(tsk);
2234                         goto retry_find_task;
2235                 }
2236                 ret = cgroup_attach_proc(cgrp, tsk);
2237         } else
2238                 ret = cgroup_attach_task(cgrp, tsk);
2239         threadgroup_unlock(tsk);
2240
2241         put_task_struct(tsk);
2242 out_unlock_cgroup:
2243         cgroup_unlock();
2244         return ret;
2245 }
2246
2247 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
2248 {
2249         return attach_task_by_pid(cgrp, pid, false);
2250 }
2251
2252 static int cgroup_procs_write(struct cgroup *cgrp, struct cftype *cft, u64 tgid)
2253 {
2254         return attach_task_by_pid(cgrp, tgid, true);
2255 }
2256
2257 /**
2258  * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
2259  * @cgrp: the cgroup to be checked for liveness
2260  *
2261  * On success, returns true; the lock should be later released with
2262  * cgroup_unlock(). On failure returns false with no lock held.
2263  */
2264 bool cgroup_lock_live_group(struct cgroup *cgrp)
2265 {
2266         mutex_lock(&cgroup_mutex);
2267         if (cgroup_is_removed(cgrp)) {
2268                 mutex_unlock(&cgroup_mutex);
2269                 return false;
2270         }
2271         return true;
2272 }
2273 EXPORT_SYMBOL_GPL(cgroup_lock_live_group);
2274
2275 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
2276                                       const char *buffer)
2277 {
2278         BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
2279         if (strlen(buffer) >= PATH_MAX)
2280                 return -EINVAL;
2281         if (!cgroup_lock_live_group(cgrp))
2282                 return -ENODEV;
2283         mutex_lock(&cgroup_root_mutex);
2284         strcpy(cgrp->root->release_agent_path, buffer);
2285         mutex_unlock(&cgroup_root_mutex);
2286         cgroup_unlock();
2287         return 0;
2288 }
2289
2290 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
2291                                      struct seq_file *seq)
2292 {
2293         if (!cgroup_lock_live_group(cgrp))
2294                 return -ENODEV;
2295         seq_puts(seq, cgrp->root->release_agent_path);
2296         seq_putc(seq, '\n');
2297         cgroup_unlock();
2298         return 0;
2299 }
2300
2301 /* A buffer size big enough for numbers or short strings */
2302 #define CGROUP_LOCAL_BUFFER_SIZE 64
2303
2304 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
2305                                 struct file *file,
2306                                 const char __user *userbuf,
2307                                 size_t nbytes, loff_t *unused_ppos)
2308 {
2309         char buffer[CGROUP_LOCAL_BUFFER_SIZE];
2310         int retval = 0;
2311         char *end;
2312
2313         if (!nbytes)
2314                 return -EINVAL;
2315         if (nbytes >= sizeof(buffer))
2316                 return -E2BIG;
2317         if (copy_from_user(buffer, userbuf, nbytes))
2318                 return -EFAULT;
2319
2320         buffer[nbytes] = 0;     /* nul-terminate */
2321         if (cft->write_u64) {
2322                 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
2323                 if (*end)
2324                         return -EINVAL;
2325                 retval = cft->write_u64(cgrp, cft, val);
2326         } else {
2327                 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
2328                 if (*end)
2329                         return -EINVAL;
2330                 retval = cft->write_s64(cgrp, cft, val);
2331         }
2332         if (!retval)
2333                 retval = nbytes;
2334         return retval;
2335 }
2336
2337 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
2338                                    struct file *file,
2339                                    const char __user *userbuf,
2340                                    size_t nbytes, loff_t *unused_ppos)
2341 {
2342         char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
2343         int retval = 0;
2344         size_t max_bytes = cft->max_write_len;
2345         char *buffer = local_buffer;
2346
2347         if (!max_bytes)
2348                 max_bytes = sizeof(local_buffer) - 1;
2349         if (nbytes >= max_bytes)
2350                 return -E2BIG;
2351         /* Allocate a dynamic buffer if we need one */
2352         if (nbytes >= sizeof(local_buffer)) {
2353                 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2354                 if (buffer == NULL)
2355                         return -ENOMEM;
2356         }
2357         if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2358                 retval = -EFAULT;
2359                 goto out;
2360         }
2361
2362         buffer[nbytes] = 0;     /* nul-terminate */
2363         retval = cft->write_string(cgrp, cft, strstrip(buffer));
2364         if (!retval)
2365                 retval = nbytes;
2366 out:
2367         if (buffer != local_buffer)
2368                 kfree(buffer);
2369         return retval;
2370 }
2371
2372 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2373                                                 size_t nbytes, loff_t *ppos)
2374 {
2375         struct cftype *cft = __d_cft(file->f_dentry);
2376         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2377
2378         if (cgroup_is_removed(cgrp))
2379                 return -ENODEV;
2380         if (cft->write)
2381                 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
2382         if (cft->write_u64 || cft->write_s64)
2383                 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
2384         if (cft->write_string)
2385                 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
2386         if (cft->trigger) {
2387                 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
2388                 return ret ? ret : nbytes;
2389         }
2390         return -EINVAL;
2391 }
2392
2393 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
2394                                struct file *file,
2395                                char __user *buf, size_t nbytes,
2396                                loff_t *ppos)
2397 {
2398         char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2399         u64 val = cft->read_u64(cgrp, cft);
2400         int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2401
2402         return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2403 }
2404
2405 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
2406                                struct file *file,
2407                                char __user *buf, size_t nbytes,
2408                                loff_t *ppos)
2409 {
2410         char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2411         s64 val = cft->read_s64(cgrp, cft);
2412         int len = sprintf(tmp, "%lld\n", (long long) val);
2413
2414         return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2415 }
2416
2417 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2418                                    size_t nbytes, loff_t *ppos)
2419 {
2420         struct cftype *cft = __d_cft(file->f_dentry);
2421         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2422
2423         if (cgroup_is_removed(cgrp))
2424                 return -ENODEV;
2425
2426         if (cft->read)
2427                 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
2428         if (cft->read_u64)
2429                 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
2430         if (cft->read_s64)
2431                 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
2432         return -EINVAL;
2433 }
2434
2435 /*
2436  * seqfile ops/methods for returning structured data. Currently just
2437  * supports string->u64 maps, but can be extended in future.
2438  */
2439
2440 struct cgroup_seqfile_state {
2441         struct cftype *cft;
2442         struct cgroup *cgroup;
2443 };
2444
2445 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2446 {
2447         struct seq_file *sf = cb->state;
2448         return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2449 }
2450
2451 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2452 {
2453         struct cgroup_seqfile_state *state = m->private;
2454         struct cftype *cft = state->cft;
2455         if (cft->read_map) {
2456                 struct cgroup_map_cb cb = {
2457                         .fill = cgroup_map_add,
2458                         .state = m,
2459                 };
2460                 return cft->read_map(state->cgroup, cft, &cb);
2461         }
2462         return cft->read_seq_string(state->cgroup, cft, m);
2463 }
2464
2465 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
2466 {
2467         struct seq_file *seq = file->private_data;
2468         kfree(seq->private);
2469         return single_release(inode, file);
2470 }
2471
2472 static const struct file_operations cgroup_seqfile_operations = {
2473         .read = seq_read,
2474         .write = cgroup_file_write,
2475         .llseek = seq_lseek,
2476         .release = cgroup_seqfile_release,
2477 };
2478
2479 static int cgroup_file_open(struct inode *inode, struct file *file)
2480 {
2481         int err;
2482         struct cftype *cft;
2483
2484         err = generic_file_open(inode, file);
2485         if (err)
2486                 return err;
2487         cft = __d_cft(file->f_dentry);
2488
2489         if (cft->read_map || cft->read_seq_string) {
2490                 struct cgroup_seqfile_state *state =
2491                         kzalloc(sizeof(*state), GFP_USER);
2492                 if (!state)
2493                         return -ENOMEM;
2494                 state->cft = cft;
2495                 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
2496                 file->f_op = &cgroup_seqfile_operations;
2497                 err = single_open(file, cgroup_seqfile_show, state);
2498                 if (err < 0)
2499                         kfree(state);
2500         } else if (cft->open)
2501                 err = cft->open(inode, file);
2502         else
2503                 err = 0;
2504
2505         return err;
2506 }
2507
2508 static int cgroup_file_release(struct inode *inode, struct file *file)
2509 {
2510         struct cftype *cft = __d_cft(file->f_dentry);
2511         if (cft->release)
2512                 return cft->release(inode, file);
2513         return 0;
2514 }
2515
2516 /*
2517  * cgroup_rename - Only allow simple rename of directories in place.
2518  */
2519 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2520                             struct inode *new_dir, struct dentry *new_dentry)
2521 {
2522         if (!S_ISDIR(old_dentry->d_inode->i_mode))
2523                 return -ENOTDIR;
2524         if (new_dentry->d_inode)
2525                 return -EEXIST;
2526         if (old_dir != new_dir)
2527                 return -EIO;
2528         return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2529 }
2530
2531 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2532 {
2533         if (S_ISDIR(dentry->d_inode->i_mode))
2534                 return &__d_cgrp(dentry)->xattrs;
2535         else
2536                 return &__d_cft(dentry)->xattrs;
2537 }
2538
2539 static inline int xattr_enabled(struct dentry *dentry)
2540 {
2541         struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2542         return test_bit(ROOT_XATTR, &root->flags);
2543 }
2544
2545 static bool is_valid_xattr(const char *name)
2546 {
2547         if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2548             !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2549                 return true;
2550         return false;
2551 }
2552
2553 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2554                            const void *val, size_t size, int flags)
2555 {
2556         if (!xattr_enabled(dentry))
2557                 return -EOPNOTSUPP;
2558         if (!is_valid_xattr(name))
2559                 return -EINVAL;
2560         return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2561 }
2562
2563 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2564 {
2565         if (!xattr_enabled(dentry))
2566                 return -EOPNOTSUPP;
2567         if (!is_valid_xattr(name))
2568                 return -EINVAL;
2569         return simple_xattr_remove(__d_xattrs(dentry), name);
2570 }
2571
2572 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2573                                void *buf, size_t size)
2574 {
2575         if (!xattr_enabled(dentry))
2576                 return -EOPNOTSUPP;
2577         if (!is_valid_xattr(name))
2578                 return -EINVAL;
2579         return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2580 }
2581
2582 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2583 {
2584         if (!xattr_enabled(dentry))
2585                 return -EOPNOTSUPP;
2586         return simple_xattr_list(__d_xattrs(dentry), buf, size);
2587 }
2588
2589 static const struct file_operations cgroup_file_operations = {
2590         .read = cgroup_file_read,
2591         .write = cgroup_file_write,
2592         .llseek = generic_file_llseek,
2593         .open = cgroup_file_open,
2594         .release = cgroup_file_release,
2595 };
2596
2597 static const struct inode_operations cgroup_file_inode_operations = {
2598         .setxattr = cgroup_setxattr,
2599         .getxattr = cgroup_getxattr,
2600         .listxattr = cgroup_listxattr,
2601         .removexattr = cgroup_removexattr,
2602 };
2603
2604 static const struct inode_operations cgroup_dir_inode_operations = {
2605         .lookup = cgroup_lookup,
2606         .mkdir = cgroup_mkdir,
2607         .rmdir = cgroup_rmdir,
2608         .rename = cgroup_rename,
2609         .setxattr = cgroup_setxattr,
2610         .getxattr = cgroup_getxattr,
2611         .listxattr = cgroup_listxattr,
2612         .removexattr = cgroup_removexattr,
2613 };
2614
2615 static struct dentry *cgroup_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
2616 {
2617         if (dentry->d_name.len > NAME_MAX)
2618                 return ERR_PTR(-ENAMETOOLONG);
2619         d_add(dentry, NULL);
2620         return NULL;
2621 }
2622
2623 /*
2624  * Check if a file is a control file
2625  */
2626 static inline struct cftype *__file_cft(struct file *file)
2627 {
2628         if (file->f_dentry->d_inode->i_fop != &cgroup_file_operations)
2629                 return ERR_PTR(-EINVAL);
2630         return __d_cft(file->f_dentry);
2631 }
2632
2633 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2634                                 struct super_block *sb)
2635 {
2636         struct inode *inode;
2637
2638         if (!dentry)
2639                 return -ENOENT;
2640         if (dentry->d_inode)
2641                 return -EEXIST;
2642
2643         inode = cgroup_new_inode(mode, sb);
2644         if (!inode)
2645                 return -ENOMEM;
2646
2647         if (S_ISDIR(mode)) {
2648                 inode->i_op = &cgroup_dir_inode_operations;
2649                 inode->i_fop = &simple_dir_operations;
2650
2651                 /* start off with i_nlink == 2 (for "." entry) */
2652                 inc_nlink(inode);
2653                 inc_nlink(dentry->d_parent->d_inode);
2654
2655                 /*
2656                  * Control reaches here with cgroup_mutex held.
2657                  * @inode->i_mutex should nest outside cgroup_mutex but we
2658                  * want to populate it immediately without releasing
2659                  * cgroup_mutex.  As @inode isn't visible to anyone else
2660                  * yet, trylock will always succeed without affecting
2661                  * lockdep checks.
2662                  */
2663                 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2664         } else if (S_ISREG(mode)) {
2665                 inode->i_size = 0;
2666                 inode->i_fop = &cgroup_file_operations;
2667                 inode->i_op = &cgroup_file_inode_operations;
2668         }
2669         d_instantiate(dentry, inode);
2670         dget(dentry);   /* Extra count - pin the dentry in core */
2671         return 0;
2672 }
2673
2674 /**
2675  * cgroup_file_mode - deduce file mode of a control file
2676  * @cft: the control file in question
2677  *
2678  * returns cft->mode if ->mode is not 0
2679  * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2680  * returns S_IRUGO if it has only a read handler
2681  * returns S_IWUSR if it has only a write hander
2682  */
2683 static umode_t cgroup_file_mode(const struct cftype *cft)
2684 {
2685         umode_t mode = 0;
2686
2687         if (cft->mode)
2688                 return cft->mode;
2689
2690         if (cft->read || cft->read_u64 || cft->read_s64 ||
2691             cft->read_map || cft->read_seq_string)
2692                 mode |= S_IRUGO;
2693
2694         if (cft->write || cft->write_u64 || cft->write_s64 ||
2695             cft->write_string || cft->trigger)
2696                 mode |= S_IWUSR;
2697
2698         return mode;
2699 }
2700
2701 static int cgroup_add_file(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2702                            struct cftype *cft)
2703 {
2704         struct dentry *dir = cgrp->dentry;
2705         struct cgroup *parent = __d_cgrp(dir);
2706         struct dentry *dentry;
2707         struct cfent *cfe;
2708         int error;
2709         umode_t mode;
2710         char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2711
2712         simple_xattrs_init(&cft->xattrs);
2713
2714         /* does @cft->flags tell us to skip creation on @cgrp? */
2715         if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2716                 return 0;
2717         if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2718                 return 0;
2719
2720         if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) {
2721                 strcpy(name, subsys->name);
2722                 strcat(name, ".");
2723         }
2724         strcat(name, cft->name);
2725
2726         BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2727
2728         cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2729         if (!cfe)
2730                 return -ENOMEM;
2731
2732         dentry = lookup_one_len(name, dir, strlen(name));
2733         if (IS_ERR(dentry)) {
2734                 error = PTR_ERR(dentry);
2735                 goto out;
2736         }
2737
2738         mode = cgroup_file_mode(cft);
2739         error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2740         if (!error) {
2741                 cfe->type = (void *)cft;
2742                 cfe->dentry = dentry;
2743                 dentry->d_fsdata = cfe;
2744                 list_add_tail(&cfe->node, &parent->files);
2745                 cfe = NULL;
2746         }
2747         dput(dentry);
2748 out:
2749         kfree(cfe);
2750         return error;
2751 }
2752
2753 static int cgroup_addrm_files(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2754                               struct cftype cfts[], bool is_add)
2755 {
2756         struct cftype *cft;
2757         int err, ret = 0;
2758
2759         for (cft = cfts; cft->name[0] != '\0'; cft++) {
2760                 if (is_add)
2761                         err = cgroup_add_file(cgrp, subsys, cft);
2762                 else
2763                         err = cgroup_rm_file(cgrp, cft);
2764                 if (err) {
2765                         pr_warning("cgroup_addrm_files: failed to %s %s, err=%d\n",
2766                                    is_add ? "add" : "remove", cft->name, err);
2767                         ret = err;
2768                 }
2769         }
2770         return ret;
2771 }
2772
2773 static DEFINE_MUTEX(cgroup_cft_mutex);
2774
2775 static void cgroup_cfts_prepare(void)
2776         __acquires(&cgroup_cft_mutex) __acquires(&cgroup_mutex)
2777 {
2778         /*
2779          * Thanks to the entanglement with vfs inode locking, we can't walk
2780          * the existing cgroups under cgroup_mutex and create files.
2781          * Instead, we increment reference on all cgroups and build list of
2782          * them using @cgrp->cft_q_node.  Grab cgroup_cft_mutex to ensure
2783          * exclusive access to the field.
2784          */
2785         mutex_lock(&cgroup_cft_mutex);
2786         mutex_lock(&cgroup_mutex);
2787 }
2788
2789 static void cgroup_cfts_commit(struct cgroup_subsys *ss,
2790                                struct cftype *cfts, bool is_add)
2791         __releases(&cgroup_mutex) __releases(&cgroup_cft_mutex)
2792 {
2793         LIST_HEAD(pending);
2794         struct cgroup *cgrp, *n;
2795
2796         /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2797         if (cfts && ss->root != &rootnode) {
2798                 list_for_each_entry(cgrp, &ss->root->allcg_list, allcg_node) {
2799                         dget(cgrp->dentry);
2800                         list_add_tail(&cgrp->cft_q_node, &pending);
2801                 }
2802         }
2803
2804         mutex_unlock(&cgroup_mutex);
2805
2806         /*
2807          * All new cgroups will see @cfts update on @ss->cftsets.  Add/rm
2808          * files for all cgroups which were created before.
2809          */
2810         list_for_each_entry_safe(cgrp, n, &pending, cft_q_node) {
2811                 struct inode *inode = cgrp->dentry->d_inode;
2812
2813                 mutex_lock(&inode->i_mutex);
2814                 mutex_lock(&cgroup_mutex);
2815                 if (!cgroup_is_removed(cgrp))
2816                         cgroup_addrm_files(cgrp, ss, cfts, is_add);
2817                 mutex_unlock(&cgroup_mutex);
2818                 mutex_unlock(&inode->i_mutex);
2819
2820                 list_del_init(&cgrp->cft_q_node);
2821                 dput(cgrp->dentry);
2822         }
2823
2824         mutex_unlock(&cgroup_cft_mutex);
2825 }
2826
2827 /**
2828  * cgroup_add_cftypes - add an array of cftypes to a subsystem
2829  * @ss: target cgroup subsystem
2830  * @cfts: zero-length name terminated array of cftypes
2831  *
2832  * Register @cfts to @ss.  Files described by @cfts are created for all
2833  * existing cgroups to which @ss is attached and all future cgroups will
2834  * have them too.  This function can be called anytime whether @ss is
2835  * attached or not.
2836  *
2837  * Returns 0 on successful registration, -errno on failure.  Note that this
2838  * function currently returns 0 as long as @cfts registration is successful
2839  * even if some file creation attempts on existing cgroups fail.
2840  */
2841 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2842 {
2843         struct cftype_set *set;
2844
2845         set = kzalloc(sizeof(*set), GFP_KERNEL);
2846         if (!set)
2847                 return -ENOMEM;
2848
2849         cgroup_cfts_prepare();
2850         set->cfts = cfts;
2851         list_add_tail(&set->node, &ss->cftsets);
2852         cgroup_cfts_commit(ss, cfts, true);
2853
2854         return 0;
2855 }
2856 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2857
2858 /**
2859  * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2860  * @ss: target cgroup subsystem
2861  * @cfts: zero-length name terminated array of cftypes
2862  *
2863  * Unregister @cfts from @ss.  Files described by @cfts are removed from
2864  * all existing cgroups to which @ss is attached and all future cgroups
2865  * won't have them either.  This function can be called anytime whether @ss
2866  * is attached or not.
2867  *
2868  * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2869  * registered with @ss.
2870  */
2871 int cgroup_rm_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2872 {
2873         struct cftype_set *set;
2874
2875         cgroup_cfts_prepare();
2876
2877         list_for_each_entry(set, &ss->cftsets, node) {
2878                 if (set->cfts == cfts) {
2879                         list_del_init(&set->node);
2880                         cgroup_cfts_commit(ss, cfts, false);
2881                         return 0;
2882                 }
2883         }
2884
2885         cgroup_cfts_commit(ss, NULL, false);
2886         return -ENOENT;
2887 }
2888
2889 /**
2890  * cgroup_task_count - count the number of tasks in a cgroup.
2891  * @cgrp: the cgroup in question
2892  *
2893  * Return the number of tasks in the cgroup.
2894  */
2895 int cgroup_task_count(const struct cgroup *cgrp)
2896 {
2897         int count = 0;
2898         struct cg_cgroup_link *link;
2899
2900         read_lock(&css_set_lock);
2901         list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
2902                 count += atomic_read(&link->cg->refcount);
2903         }
2904         read_unlock(&css_set_lock);
2905         return count;
2906 }
2907
2908 /*
2909  * Advance a list_head iterator.  The iterator should be positioned at
2910  * the start of a css_set
2911  */
2912 static void cgroup_advance_iter(struct cgroup *cgrp,
2913                                 struct cgroup_iter *it)
2914 {
2915         struct list_head *l = it->cg_link;
2916         struct cg_cgroup_link *link;
2917         struct css_set *cg;
2918
2919         /* Advance to the next non-empty css_set */
2920         do {
2921                 l = l->next;
2922                 if (l == &cgrp->css_sets) {
2923                         it->cg_link = NULL;
2924                         return;
2925                 }
2926                 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
2927                 cg = link->cg;
2928         } while (list_empty(&cg->tasks));
2929         it->cg_link = l;
2930         it->task = cg->tasks.next;
2931 }
2932
2933 /*
2934  * To reduce the fork() overhead for systems that are not actually
2935  * using their cgroups capability, we don't maintain the lists running
2936  * through each css_set to its tasks until we see the list actually
2937  * used - in other words after the first call to cgroup_iter_start().
2938  */
2939 static void cgroup_enable_task_cg_lists(void)
2940 {
2941         struct task_struct *p, *g;
2942         write_lock(&css_set_lock);
2943         use_task_css_set_links = 1;
2944         /*
2945          * We need tasklist_lock because RCU is not safe against
2946          * while_each_thread(). Besides, a forking task that has passed
2947          * cgroup_post_fork() without seeing use_task_css_set_links = 1
2948          * is not guaranteed to have its child immediately visible in the
2949          * tasklist if we walk through it with RCU.
2950          */
2951         read_lock(&tasklist_lock);
2952         do_each_thread(g, p) {
2953                 task_lock(p);
2954                 /*
2955                  * We should check if the process is exiting, otherwise
2956                  * it will race with cgroup_exit() in that the list
2957                  * entry won't be deleted though the process has exited.
2958                  */
2959                 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2960                         list_add(&p->cg_list, &p->cgroups->tasks);
2961                 task_unlock(p);
2962         } while_each_thread(g, p);
2963         read_unlock(&tasklist_lock);
2964         write_unlock(&css_set_lock);
2965 }
2966
2967 /**
2968  * cgroup_next_descendant_pre - find the next descendant for pre-order walk
2969  * @pos: the current position (%NULL to initiate traversal)
2970  * @cgroup: cgroup whose descendants to walk
2971  *
2972  * To be used by cgroup_for_each_descendant_pre().  Find the next
2973  * descendant to visit for pre-order traversal of @cgroup's descendants.
2974  */
2975 struct cgroup *cgroup_next_descendant_pre(struct cgroup *pos,
2976                                           struct cgroup *cgroup)
2977 {
2978         struct cgroup *next;
2979
2980         WARN_ON_ONCE(!rcu_read_lock_held());
2981
2982         /* if first iteration, pretend we just visited @cgroup */
2983         if (!pos) {
2984                 if (list_empty(&cgroup->children))
2985                         return NULL;
2986                 pos = cgroup;
2987         }
2988
2989         /* visit the first child if exists */
2990         next = list_first_or_null_rcu(&pos->children, struct cgroup, sibling);
2991         if (next)
2992                 return next;
2993
2994         /* no child, visit my or the closest ancestor's next sibling */
2995         do {
2996                 next = list_entry_rcu(pos->sibling.next, struct cgroup,
2997                                       sibling);
2998                 if (&next->sibling != &pos->parent->children)
2999                         return next;
3000
3001                 pos = pos->parent;
3002         } while (pos != cgroup);
3003
3004         return NULL;
3005 }
3006 EXPORT_SYMBOL_GPL(cgroup_next_descendant_pre);
3007
3008 static struct cgroup *cgroup_leftmost_descendant(struct cgroup *pos)
3009 {
3010         struct cgroup *last;
3011
3012         do {
3013                 last = pos;
3014                 pos = list_first_or_null_rcu(&pos->children, struct cgroup,
3015                                              sibling);
3016         } while (pos);
3017
3018         return last;
3019 }
3020
3021 /**
3022  * cgroup_next_descendant_post - find the next descendant for post-order walk
3023  * @pos: the current position (%NULL to initiate traversal)
3024  * @cgroup: cgroup whose descendants to walk
3025  *
3026  * To be used by cgroup_for_each_descendant_post().  Find the next
3027  * descendant to visit for post-order traversal of @cgroup's descendants.
3028  */
3029 struct cgroup *cgroup_next_descendant_post(struct cgroup *pos,
3030                                            struct cgroup *cgroup)
3031 {
3032         struct cgroup *next;
3033
3034         WARN_ON_ONCE(!rcu_read_lock_held());
3035
3036         /* if first iteration, visit the leftmost descendant */
3037         if (!pos) {
3038                 next = cgroup_leftmost_descendant(cgroup);
3039                 return next != cgroup ? next : NULL;
3040         }
3041
3042         /* if there's an unvisited sibling, visit its leftmost descendant */
3043         next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3044         if (&next->sibling != &pos->parent->children)
3045                 return cgroup_leftmost_descendant(next);
3046
3047         /* no sibling left, visit parent */
3048         next = pos->parent;
3049         return next != cgroup ? next : NULL;
3050 }
3051 EXPORT_SYMBOL_GPL(cgroup_next_descendant_post);
3052
3053 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
3054         __acquires(css_set_lock)
3055 {
3056         /*
3057          * The first time anyone tries to iterate across a cgroup,
3058          * we need to enable the list linking each css_set to its
3059          * tasks, and fix up all existing tasks.
3060          */
3061         if (!use_task_css_set_links)
3062                 cgroup_enable_task_cg_lists();
3063
3064         read_lock(&css_set_lock);
3065         it->cg_link = &cgrp->css_sets;
3066         cgroup_advance_iter(cgrp, it);
3067 }
3068
3069 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
3070                                         struct cgroup_iter *it)
3071 {
3072         struct task_struct *res;
3073         struct list_head *l = it->task;
3074         struct cg_cgroup_link *link;
3075
3076         /* If the iterator cg is NULL, we have no tasks */
3077         if (!it->cg_link)
3078                 return NULL;
3079         res = list_entry(l, struct task_struct, cg_list);
3080         /* Advance iterator to find next entry */
3081         l = l->next;
3082         link = list_entry(it->cg_link, struct cg_cgroup_link, cgrp_link_list);
3083         if (l == &link->cg->tasks) {
3084                 /* We reached the end of this task list - move on to
3085                  * the next cg_cgroup_link */
3086                 cgroup_advance_iter(cgrp, it);
3087         } else {
3088                 it->task = l;
3089         }
3090         return res;
3091 }
3092
3093 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
3094         __releases(css_set_lock)
3095 {
3096         read_unlock(&css_set_lock);
3097 }
3098
3099 static inline int started_after_time(struct task_struct *t1,
3100                                      struct timespec *time,
3101                                      struct task_struct *t2)
3102 {
3103         int start_diff = timespec_compare(&t1->start_time, time);
3104         if (start_diff > 0) {
3105                 return 1;
3106         } else if (start_diff < 0) {
3107                 return 0;
3108         } else {
3109                 /*
3110                  * Arbitrarily, if two processes started at the same
3111                  * time, we'll say that the lower pointer value
3112                  * started first. Note that t2 may have exited by now
3113                  * so this may not be a valid pointer any longer, but
3114                  * that's fine - it still serves to distinguish
3115                  * between two tasks started (effectively) simultaneously.
3116                  */
3117                 return t1 > t2;
3118         }
3119 }
3120
3121 /*
3122  * This function is a callback from heap_insert() and is used to order
3123  * the heap.
3124  * In this case we order the heap in descending task start time.
3125  */
3126 static inline int started_after(void *p1, void *p2)
3127 {
3128         struct task_struct *t1 = p1;
3129         struct task_struct *t2 = p2;
3130         return started_after_time(t1, &t2->start_time, t2);
3131 }
3132
3133 /**
3134  * cgroup_scan_tasks - iterate though all the tasks in a cgroup
3135  * @scan: struct cgroup_scanner containing arguments for the scan
3136  *
3137  * Arguments include pointers to callback functions test_task() and
3138  * process_task().
3139  * Iterate through all the tasks in a cgroup, calling test_task() for each,
3140  * and if it returns true, call process_task() for it also.
3141  * The test_task pointer may be NULL, meaning always true (select all tasks).
3142  * Effectively duplicates cgroup_iter_{start,next,end}()
3143  * but does not lock css_set_lock for the call to process_task().
3144  * The struct cgroup_scanner may be embedded in any structure of the caller's
3145  * creation.
3146  * It is guaranteed that process_task() will act on every task that
3147  * is a member of the cgroup for the duration of this call. This
3148  * function may or may not call process_task() for tasks that exit
3149  * or move to a different cgroup during the call, or are forked or
3150  * move into the cgroup during the call.
3151  *
3152  * Note that test_task() may be called with locks held, and may in some
3153  * situations be called multiple times for the same task, so it should
3154  * be cheap.
3155  * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
3156  * pre-allocated and will be used for heap operations (and its "gt" member will
3157  * be overwritten), else a temporary heap will be used (allocation of which
3158  * may cause this function to fail).
3159  */
3160 int cgroup_scan_tasks(struct cgroup_scanner *scan)
3161 {
3162         int retval, i;
3163         struct cgroup_iter it;
3164         struct task_struct *p, *dropped;
3165         /* Never dereference latest_task, since it's not refcounted */
3166         struct task_struct *latest_task = NULL;
3167         struct ptr_heap tmp_heap;
3168         struct ptr_heap *heap;
3169         struct timespec latest_time = { 0, 0 };
3170
3171         if (scan->heap) {
3172                 /* The caller supplied our heap and pre-allocated its memory */
3173                 heap = scan->heap;
3174                 heap->gt = &started_after;
3175         } else {
3176                 /* We need to allocate our own heap memory */
3177                 heap = &tmp_heap;
3178                 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3179                 if (retval)
3180                         /* cannot allocate the heap */
3181                         return retval;
3182         }
3183
3184  again:
3185         /*
3186          * Scan tasks in the cgroup, using the scanner's "test_task" callback
3187          * to determine which are of interest, and using the scanner's
3188          * "process_task" callback to process any of them that need an update.
3189          * Since we don't want to hold any locks during the task updates,
3190          * gather tasks to be processed in a heap structure.
3191          * The heap is sorted by descending task start time.
3192          * If the statically-sized heap fills up, we overflow tasks that
3193          * started later, and in future iterations only consider tasks that
3194          * started after the latest task in the previous pass. This
3195          * guarantees forward progress and that we don't miss any tasks.
3196          */
3197         heap->size = 0;
3198         cgroup_iter_start(scan->cg, &it);
3199         while ((p = cgroup_iter_next(scan->cg, &it))) {
3200                 /*
3201                  * Only affect tasks that qualify per the caller's callback,
3202                  * if he provided one
3203                  */
3204                 if (scan->test_task && !scan->test_task(p, scan))
3205                         continue;
3206                 /*
3207                  * Only process tasks that started after the last task
3208                  * we processed
3209                  */
3210                 if (!started_after_time(p, &latest_time, latest_task))
3211                         continue;
3212                 dropped = heap_insert(heap, p);
3213                 if (dropped == NULL) {
3214                         /*
3215                          * The new task was inserted; the heap wasn't
3216                          * previously full
3217                          */
3218                         get_task_struct(p);
3219                 } else if (dropped != p) {
3220                         /*
3221                          * The new task was inserted, and pushed out a
3222                          * different task
3223                          */
3224                         get_task_struct(p);
3225                         put_task_struct(dropped);
3226                 }
3227                 /*
3228                  * Else the new task was newer than anything already in
3229                  * the heap and wasn't inserted
3230                  */
3231         }
3232         cgroup_iter_end(scan->cg, &it);
3233
3234         if (heap->size) {
3235                 for (i = 0; i < heap->size; i++) {
3236                         struct task_struct *q = heap->ptrs[i];
3237                         if (i == 0) {
3238                                 latest_time = q->start_time;
3239                                 latest_task = q;
3240                         }
3241                         /* Process the task per the caller's callback */
3242                         scan->process_task(q, scan);
3243                         put_task_struct(q);
3244                 }
3245                 /*
3246                  * If we had to process any tasks at all, scan again
3247                  * in case some of them were in the middle of forking
3248                  * children that didn't get processed.
3249                  * Not the most efficient way to do it, but it avoids
3250                  * having to take callback_mutex in the fork path
3251                  */
3252                 goto again;
3253         }
3254         if (heap == &tmp_heap)
3255                 heap_free(&tmp_heap);
3256         return 0;
3257 }
3258
3259 /*
3260  * Stuff for reading the 'tasks'/'procs' files.
3261  *
3262  * Reading this file can return large amounts of data if a cgroup has
3263  * *lots* of attached tasks. So it may need several calls to read(),
3264  * but we cannot guarantee that the information we produce is correct
3265  * unless we produce it entirely atomically.
3266  *
3267  */
3268
3269 /* which pidlist file are we talking about? */
3270 enum cgroup_filetype {
3271         CGROUP_FILE_PROCS,
3272         CGROUP_FILE_TASKS,
3273 };
3274
3275 /*
3276  * A pidlist is a list of pids that virtually represents the contents of one
3277  * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3278  * a pair (one each for procs, tasks) for each pid namespace that's relevant
3279  * to the cgroup.
3280  */
3281 struct cgroup_pidlist {
3282         /*
3283          * used to find which pidlist is wanted. doesn't change as long as
3284          * this particular list stays in the list.
3285         */
3286         struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3287         /* array of xids */
3288         pid_t *list;
3289         /* how many elements the above list has */
3290         int length;
3291         /* how many files are using the current array */
3292         int use_count;
3293         /* each of these stored in a list by its cgroup */
3294         struct list_head links;
3295         /* pointer to the cgroup we belong to, for list removal purposes */
3296         struct cgroup *owner;
3297         /* protects the other fields */
3298         struct rw_semaphore mutex;
3299 };
3300
3301 /*
3302  * The following two functions "fix" the issue where there are more pids
3303  * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3304  * TODO: replace with a kernel-wide solution to this problem
3305  */
3306 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3307 static void *pidlist_allocate(int count)
3308 {
3309         if (PIDLIST_TOO_LARGE(count))
3310                 return vmalloc(count * sizeof(pid_t));
3311         else
3312                 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3313 }
3314 static void pidlist_free(void *p)
3315 {
3316         if (is_vmalloc_addr(p))
3317                 vfree(p);
3318         else
3319                 kfree(p);
3320 }
3321 static void *pidlist_resize(void *p, int newcount)
3322 {
3323         void *newlist;
3324         /* note: if new alloc fails, old p will still be valid either way */
3325         if (is_vmalloc_addr(p)) {
3326                 newlist = vmalloc(newcount * sizeof(pid_t));
3327                 if (!newlist)
3328                         return NULL;
3329                 memcpy(newlist, p, newcount * sizeof(pid_t));
3330                 vfree(p);
3331         } else {
3332                 newlist = krealloc(p, newcount * sizeof(pid_t), GFP_KERNEL);
3333         }
3334         return newlist;
3335 }
3336
3337 /*
3338  * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3339  * If the new stripped list is sufficiently smaller and there's enough memory
3340  * to allocate a new buffer, will let go of the unneeded memory. Returns the
3341  * number of unique elements.
3342  */
3343 /* is the size difference enough that we should re-allocate the array? */
3344 #define PIDLIST_REALLOC_DIFFERENCE(old, new) ((old) - PAGE_SIZE >= (new))
3345 static int pidlist_uniq(pid_t **p, int length)
3346 {
3347         int src, dest = 1;
3348         pid_t *list = *p;
3349         pid_t *newlist;
3350
3351         /*
3352          * we presume the 0th element is unique, so i starts at 1. trivial
3353          * edge cases first; no work needs to be done for either
3354          */
3355         if (length == 0 || length == 1)
3356                 return length;
3357         /* src and dest walk down the list; dest counts unique elements */
3358         for (src = 1; src < length; src++) {
3359                 /* find next unique element */
3360                 while (list[src] == list[src-1]) {
3361                         src++;
3362                         if (src == length)
3363                                 goto after;
3364                 }
3365                 /* dest always points to where the next unique element goes */
3366                 list[dest] = list[src];
3367                 dest++;
3368         }
3369 after:
3370         /*
3371          * if the length difference is large enough, we want to allocate a
3372          * smaller buffer to save memory. if this fails due to out of memory,
3373          * we'll just stay with what we've got.
3374          */
3375         if (PIDLIST_REALLOC_DIFFERENCE(length, dest)) {
3376                 newlist = pidlist_resize(list, dest);
3377                 if (newlist)
3378                         *p = newlist;
3379         }
3380         return dest;
3381 }
3382
3383 static int cmppid(const void *a, const void *b)
3384 {
3385         return *(pid_t *)a - *(pid_t *)b;
3386 }
3387
3388 /*
3389  * find the appropriate pidlist for our purpose (given procs vs tasks)
3390  * returns with the lock on that pidlist already held, and takes care
3391  * of the use count, or returns NULL with no locks held if we're out of
3392  * memory.
3393  */
3394 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3395                                                   enum cgroup_filetype type)
3396 {
3397         struct cgroup_pidlist *l;
3398         /* don't need task_nsproxy() if we're looking at ourself */
3399         struct pid_namespace *ns = current->nsproxy->pid_ns;
3400
3401         /*
3402          * We can't drop the pidlist_mutex before taking the l->mutex in case
3403          * the last ref-holder is trying to remove l from the list at the same
3404          * time. Holding the pidlist_mutex precludes somebody taking whichever
3405          * list we find out from under us - compare release_pid_array().
3406          */
3407         mutex_lock(&cgrp->pidlist_mutex);
3408         list_for_each_entry(l, &cgrp->pidlists, links) {
3409                 if (l->key.type == type && l->key.ns == ns) {
3410                         /* make sure l doesn't vanish out from under us */
3411                         down_write(&l->mutex);
3412                         mutex_unlock(&cgrp->pidlist_mutex);
3413                         return l;
3414                 }
3415         }
3416         /* entry not found; create a new one */
3417         l = kmalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3418         if (!l) {
3419                 mutex_unlock(&cgrp->pidlist_mutex);
3420                 return l;
3421         }
3422         init_rwsem(&l->mutex);
3423         down_write(&l->mutex);
3424         l->key.type = type;
3425         l->key.ns = get_pid_ns(ns);
3426         l->use_count = 0; /* don't increment here */
3427         l->list = NULL;
3428         l->owner = cgrp;
3429         list_add(&l->links, &cgrp->pidlists);
3430         mutex_unlock(&cgrp->pidlist_mutex);
3431         return l;
3432 }
3433
3434 /*
3435  * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3436  */
3437 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3438                               struct cgroup_pidlist **lp)
3439 {
3440         pid_t *array;
3441         int length;
3442         int pid, n = 0; /* used for populating the array */
3443         struct cgroup_iter it;
3444         struct task_struct *tsk;
3445         struct cgroup_pidlist *l;
3446
3447         /*
3448          * If cgroup gets more users after we read count, we won't have
3449          * enough space - tough.  This race is indistinguishable to the
3450          * caller from the case that the additional cgroup users didn't
3451          * show up until sometime later on.
3452          */
3453         length = cgroup_task_count(cgrp);
3454         array = pidlist_allocate(length);
3455         if (!array)
3456                 return -ENOMEM;
3457         /* now, populate the array */
3458         cgroup_iter_start(cgrp, &it);
3459         while ((tsk = cgroup_iter_next(cgrp, &it))) {
3460                 if (unlikely(n == length))
3461                         break;
3462                 /* get tgid or pid for procs or tasks file respectively */
3463                 if (type == CGROUP_FILE_PROCS)
3464                         pid = task_tgid_vnr(tsk);
3465                 else
3466                         pid = task_pid_vnr(tsk);
3467                 if (pid > 0) /* make sure to only use valid results */
3468                         array[n++] = pid;
3469         }
3470         cgroup_iter_end(cgrp, &it);
3471         length = n;
3472         /* now sort & (if procs) strip out duplicates */
3473         sort(array, length, sizeof(pid_t), cmppid, NULL);
3474         if (type == CGROUP_FILE_PROCS)
3475                 length = pidlist_uniq(&array, length);
3476         l = cgroup_pidlist_find(cgrp, type);
3477         if (!l) {
3478                 pidlist_free(array);
3479                 return -ENOMEM;
3480         }
3481         /* store array, freeing old if necessary - lock already held */
3482         pidlist_free(l->list);
3483         l->list = array;
3484         l->length = length;
3485         l->use_count++;
3486         up_write(&l->mutex);
3487         *lp = l;
3488         return 0;
3489 }
3490
3491 /**
3492  * cgroupstats_build - build and fill cgroupstats
3493  * @stats: cgroupstats to fill information into
3494  * @dentry: A dentry entry belonging to the cgroup for which stats have
3495  * been requested.
3496  *
3497  * Build and fill cgroupstats so that taskstats can export it to user
3498  * space.
3499  */
3500 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3501 {
3502         int ret = -EINVAL;
3503         struct cgroup *cgrp;
3504         struct cgroup_iter it;
3505         struct task_struct *tsk;
3506
3507         /*
3508          * Validate dentry by checking the superblock operations,
3509          * and make sure it's a directory.
3510          */
3511         if (dentry->d_sb->s_op != &cgroup_ops ||
3512             !S_ISDIR(dentry->d_inode->i_mode))
3513                  goto err;
3514
3515         ret = 0;
3516         cgrp = dentry->d_fsdata;
3517
3518         cgroup_iter_start(cgrp, &it);
3519         while ((tsk = cgroup_iter_next(cgrp, &it))) {
3520                 switch (tsk->state) {
3521                 case TASK_RUNNING:
3522                         stats->nr_running++;
3523                         break;
3524                 case TASK_INTERRUPTIBLE:
3525                         stats->nr_sleeping++;
3526                         break;
3527                 case TASK_UNINTERRUPTIBLE:
3528                         stats->nr_uninterruptible++;
3529                         break;
3530                 case TASK_STOPPED:
3531                         stats->nr_stopped++;
3532                         break;
3533                 default:
3534                         if (delayacct_is_task_waiting_on_io(tsk))
3535                                 stats->nr_io_wait++;
3536                         break;
3537                 }
3538         }
3539         cgroup_iter_end(cgrp, &it);
3540
3541 err:
3542         return ret;
3543 }
3544
3545
3546 /*
3547  * seq_file methods for the tasks/procs files. The seq_file position is the
3548  * next pid to display; the seq_file iterator is a pointer to the pid
3549  * in the cgroup->l->list array.
3550  */
3551
3552 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3553 {
3554         /*
3555          * Initially we receive a position value that corresponds to
3556          * one more than the last pid shown (or 0 on the first call or
3557          * after a seek to the start). Use a binary-search to find the
3558          * next pid to display, if any
3559          */
3560         struct cgroup_pidlist *l = s->private;
3561         int index = 0, pid = *pos;
3562         int *iter;
3563
3564         down_read(&l->mutex);
3565         if (pid) {
3566                 int end = l->length;
3567
3568                 while (index < end) {
3569                         int mid = (index + end) / 2;
3570                         if (l->list[mid] == pid) {
3571                                 index = mid;
3572                                 break;
3573                         } else if (l->list[mid] <= pid)
3574                                 index = mid + 1;
3575                         else
3576                                 end = mid;
3577                 }
3578         }
3579         /* If we're off the end of the array, we're done */
3580         if (index >= l->length)
3581                 return NULL;
3582         /* Update the abstract position to be the actual pid that we found */
3583         iter = l->list + index;
3584         *pos = *iter;
3585         return iter;
3586 }
3587
3588 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3589 {
3590         struct cgroup_pidlist *l = s->private;
3591         up_read(&l->mutex);
3592 }
3593
3594 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3595 {
3596         struct cgroup_pidlist *l = s->private;
3597         pid_t *p = v;
3598         pid_t *end = l->list + l->length;
3599         /*
3600          * Advance to the next pid in the array. If this goes off the
3601          * end, we're done
3602          */
3603         p++;
3604         if (p >= end) {
3605                 return NULL;
3606         } else {
3607                 *pos = *p;
3608                 return p;
3609         }
3610 }
3611
3612 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3613 {
3614         return seq_printf(s, "%d\n", *(int *)v);
3615 }
3616
3617 /*
3618  * seq_operations functions for iterating on pidlists through seq_file -
3619  * independent of whether it's tasks or procs
3620  */
3621 static const struct seq_operations cgroup_pidlist_seq_operations = {
3622         .start = cgroup_pidlist_start,
3623         .stop = cgroup_pidlist_stop,
3624         .next = cgroup_pidlist_next,
3625         .show = cgroup_pidlist_show,
3626 };
3627
3628 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
3629 {
3630         /*
3631          * the case where we're the last user of this particular pidlist will
3632          * have us remove it from the cgroup's list, which entails taking the
3633          * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3634          * pidlist_mutex, we have to take pidlist_mutex first.
3635          */
3636         mutex_lock(&l->owner->pidlist_mutex);
3637         down_write(&l->mutex);
3638         BUG_ON(!l->use_count);
3639         if (!--l->use_count) {
3640                 /* we're the last user if refcount is 0; remove and free */
3641                 list_del(&l->links);
3642                 mutex_unlock(&l->owner->pidlist_mutex);
3643                 pidlist_free(l->list);
3644                 put_pid_ns(l->key.ns);
3645                 up_write(&l->mutex);
3646                 kfree(l);
3647                 return;
3648         }
3649         mutex_unlock(&l->owner->pidlist_mutex);
3650         up_write(&l->mutex);
3651 }
3652
3653 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
3654 {
3655         struct cgroup_pidlist *l;
3656         if (!(file->f_mode & FMODE_READ))
3657                 return 0;
3658         /*
3659          * the seq_file will only be initialized if the file was opened for
3660          * reading; hence we check if it's not null only in that case.
3661          */
3662         l = ((struct seq_file *)file->private_data)->private;
3663         cgroup_release_pid_array(l);
3664         return seq_release(inode, file);
3665 }
3666
3667 static const struct file_operations cgroup_pidlist_operations = {
3668         .read = seq_read,
3669         .llseek = seq_lseek,
3670         .write = cgroup_file_write,
3671         .release = cgroup_pidlist_release,
3672 };
3673
3674 /*
3675  * The following functions handle opens on a file that displays a pidlist
3676  * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3677  * in the cgroup.
3678  */
3679 /* helper function for the two below it */
3680 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
3681 {
3682         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
3683         struct cgroup_pidlist *l;
3684         int retval;
3685
3686         /* Nothing to do for write-only files */
3687         if (!(file->f_mode & FMODE_READ))
3688                 return 0;
3689
3690         /* have the array populated */
3691         retval = pidlist_array_load(cgrp, type, &l);
3692         if (retval)
3693                 return retval;
3694         /* configure file information */
3695         file->f_op = &cgroup_pidlist_operations;
3696
3697         retval = seq_open(file, &cgroup_pidlist_seq_operations);
3698         if (retval) {
3699                 cgroup_release_pid_array(l);
3700                 return retval;
3701         }
3702         ((struct seq_file *)file->private_data)->private = l;
3703         return 0;
3704 }
3705 static int cgroup_tasks_open(struct inode *unused, struct file *file)
3706 {
3707         return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
3708 }
3709 static int cgroup_procs_open(struct inode *unused, struct file *file)
3710 {
3711         return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
3712 }
3713
3714 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
3715                                             struct cftype *cft)
3716 {
3717         return notify_on_release(cgrp);
3718 }
3719
3720 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
3721                                           struct cftype *cft,
3722                                           u64 val)
3723 {
3724         clear_bit(CGRP_RELEASABLE, &cgrp->flags);
3725         if (val)
3726                 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3727         else
3728                 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3729         return 0;
3730 }
3731
3732 /*
3733  * Unregister event and free resources.
3734  *
3735  * Gets called from workqueue.
3736  */
3737 static void cgroup_event_remove(struct work_struct *work)
3738 {
3739         struct cgroup_event *event = container_of(work, struct cgroup_event,
3740                         remove);
3741         struct cgroup *cgrp = event->cgrp;
3742
3743         event->cft->unregister_event(cgrp, event->cft, event->eventfd);
3744
3745         eventfd_ctx_put(event->eventfd);
3746         kfree(event);
3747         dput(cgrp->dentry);
3748 }
3749
3750 /*
3751  * Gets called on POLLHUP on eventfd when user closes it.
3752  *
3753  * Called with wqh->lock held and interrupts disabled.
3754  */
3755 static int cgroup_event_wake(wait_queue_t *wait, unsigned mode,
3756                 int sync, void *key)
3757 {
3758         struct cgroup_event *event = container_of(wait,
3759                         struct cgroup_event, wait);
3760         struct cgroup *cgrp = event->cgrp;
3761         unsigned long flags = (unsigned long)key;
3762
3763         if (flags & POLLHUP) {
3764                 __remove_wait_queue(event->wqh, &event->wait);
3765                 spin_lock(&cgrp->event_list_lock);
3766                 list_del(&event->list);
3767                 spin_unlock(&cgrp->event_list_lock);
3768                 /*
3769                  * We are in atomic context, but cgroup_event_remove() may
3770                  * sleep, so we have to call it in workqueue.
3771                  */
3772                 schedule_work(&event->remove);
3773         }
3774
3775         return 0;
3776 }
3777
3778 static void cgroup_event_ptable_queue_proc(struct file *file,
3779                 wait_queue_head_t *wqh, poll_table *pt)
3780 {
3781         struct cgroup_event *event = container_of(pt,
3782                         struct cgroup_event, pt);
3783
3784         event->wqh = wqh;
3785         add_wait_queue(wqh, &event->wait);
3786 }
3787
3788 /*
3789  * Parse input and register new cgroup event handler.
3790  *
3791  * Input must be in format '<event_fd> <control_fd> <args>'.
3792  * Interpretation of args is defined by control file implementation.
3793  */
3794 static int cgroup_write_event_control(struct cgroup *cgrp, struct cftype *cft,
3795                                       const char *buffer)
3796 {
3797         struct cgroup_event *event = NULL;
3798         unsigned int efd, cfd;
3799         struct file *efile = NULL;
3800         struct file *cfile = NULL;
3801         char *endp;
3802         int ret;
3803
3804         efd = simple_strtoul(buffer, &endp, 10);
3805         if (*endp != ' ')
3806                 return -EINVAL;
3807         buffer = endp + 1;
3808
3809         cfd = simple_strtoul(buffer, &endp, 10);
3810         if ((*endp != ' ') && (*endp != '\0'))
3811                 return -EINVAL;
3812         buffer = endp + 1;
3813
3814         event = kzalloc(sizeof(*event), GFP_KERNEL);
3815         if (!event)
3816                 return -ENOMEM;
3817         event->cgrp = cgrp;
3818         INIT_LIST_HEAD(&event->list);
3819         init_poll_funcptr(&event->pt, cgroup_event_ptable_queue_proc);
3820         init_waitqueue_func_entry(&event->wait, cgroup_event_wake);
3821         INIT_WORK(&event->remove, cgroup_event_remove);
3822
3823         efile = eventfd_fget(efd);
3824         if (IS_ERR(efile)) {
3825                 ret = PTR_ERR(efile);
3826                 goto fail;
3827         }
3828
3829         event->eventfd = eventfd_ctx_fileget(efile);
3830         if (IS_ERR(event->eventfd)) {
3831                 ret = PTR_ERR(event->eventfd);
3832                 goto fail;
3833         }
3834
3835         cfile = fget(cfd);
3836         if (!cfile) {
3837                 ret = -EBADF;
3838                 goto fail;
3839         }
3840
3841         /* the process need read permission on control file */
3842         /* AV: shouldn't we check that it's been opened for read instead? */
3843         ret = inode_permission(cfile->f_path.dentry->d_inode, MAY_READ);
3844         if (ret < 0)
3845                 goto fail;
3846
3847         event->cft = __file_cft(cfile);
3848         if (IS_ERR(event->cft)) {
3849                 ret = PTR_ERR(event->cft);
3850                 goto fail;
3851         }
3852
3853         if (!event->cft->register_event || !event->cft->unregister_event) {
3854                 ret = -EINVAL;
3855                 goto fail;
3856         }
3857
3858         ret = event->cft->register_event(cgrp, event->cft,
3859                         event->eventfd, buffer);
3860         if (ret)
3861                 goto fail;
3862
3863         if (efile->f_op->poll(efile, &event->pt) & POLLHUP) {
3864                 event->cft->unregister_event(cgrp, event->cft, event->eventfd);
3865                 ret = 0;
3866                 goto fail;
3867         }
3868
3869         /*
3870          * Events should be removed after rmdir of cgroup directory, but before
3871          * destroying subsystem state objects. Let's take reference to cgroup
3872          * directory dentry to do that.
3873          */
3874         dget(cgrp->dentry);
3875
3876         spin_lock(&cgrp->event_list_lock);
3877         list_add(&event->list, &cgrp->event_list);
3878         spin_unlock(&cgrp->event_list_lock);
3879
3880         fput(cfile);
3881         fput(efile);
3882
3883         return 0;
3884
3885 fail:
3886         if (cfile)
3887                 fput(cfile);
3888
3889         if (event && event->eventfd && !IS_ERR(event->eventfd))
3890                 eventfd_ctx_put(event->eventfd);
3891
3892         if (!IS_ERR_OR_NULL(efile))
3893                 fput(efile);
3894
3895         kfree(event);
3896
3897         return ret;
3898 }
3899
3900 static u64 cgroup_clone_children_read(struct cgroup *cgrp,
3901                                     struct cftype *cft)
3902 {
3903         return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3904 }
3905
3906 static int cgroup_clone_children_write(struct cgroup *cgrp,
3907                                      struct cftype *cft,
3908                                      u64 val)
3909 {
3910         if (val)
3911                 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3912         else
3913                 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3914         return 0;
3915 }
3916
3917 /*
3918  * for the common functions, 'private' gives the type of file
3919  */
3920 /* for hysterical raisins, we can't put this on the older files */
3921 #define CGROUP_FILE_GENERIC_PREFIX "cgroup."
3922 static struct cftype files[] = {
3923         {
3924                 .name = "tasks",
3925                 .open = cgroup_tasks_open,
3926                 .write_u64 = cgroup_tasks_write,
3927                 .release = cgroup_pidlist_release,
3928                 .mode = S_IRUGO | S_IWUSR,
3929         },
3930         {
3931                 .name = CGROUP_FILE_GENERIC_PREFIX "procs",
3932                 .open = cgroup_procs_open,
3933                 .write_u64 = cgroup_procs_write,
3934                 .release = cgroup_pidlist_release,
3935                 .mode = S_IRUGO | S_IWUSR,
3936         },
3937         {
3938                 .name = "notify_on_release",
3939                 .read_u64 = cgroup_read_notify_on_release,
3940                 .write_u64 = cgroup_write_notify_on_release,
3941         },
3942         {
3943                 .name = CGROUP_FILE_GENERIC_PREFIX "event_control",
3944                 .write_string = cgroup_write_event_control,
3945                 .mode = S_IWUGO,
3946         },
3947         {
3948                 .name = "cgroup.clone_children",
3949                 .read_u64 = cgroup_clone_children_read,
3950                 .write_u64 = cgroup_clone_children_write,
3951         },
3952         {
3953                 .name = "release_agent",
3954                 .flags = CFTYPE_ONLY_ON_ROOT,
3955                 .read_seq_string = cgroup_release_agent_show,
3956                 .write_string = cgroup_release_agent_write,
3957                 .max_write_len = PATH_MAX,
3958         },
3959         { }     /* terminate */
3960 };
3961
3962 /**
3963  * cgroup_populate_dir - selectively creation of files in a directory
3964  * @cgrp: target cgroup
3965  * @base_files: true if the base files should be added
3966  * @subsys_mask: mask of the subsystem ids whose files should be added
3967  */
3968 static int cgroup_populate_dir(struct cgroup *cgrp, bool base_files,
3969                                unsigned long subsys_mask)
3970 {
3971         int err;
3972         struct cgroup_subsys *ss;
3973
3974         if (base_files) {
3975                 err = cgroup_addrm_files(cgrp, NULL, files, true);
3976                 if (err < 0)
3977                         return err;
3978         }
3979
3980         /* process cftsets of each subsystem */
3981         for_each_subsys(cgrp->root, ss) {
3982                 struct cftype_set *set;
3983                 if (!test_bit(ss->subsys_id, &subsys_mask))
3984                         continue;
3985
3986                 list_for_each_entry(set, &ss->cftsets, node)
3987                         cgroup_addrm_files(cgrp, ss, set->cfts, true);
3988         }
3989
3990         /* This cgroup is ready now */
3991         for_each_subsys(cgrp->root, ss) {
3992                 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
3993                 /*
3994                  * Update id->css pointer and make this css visible from
3995                  * CSS ID functions. This pointer will be dereferened
3996                  * from RCU-read-side without locks.
3997                  */
3998                 if (css->id)
3999                         rcu_assign_pointer(css->id->css, css);
4000         }
4001
4002         return 0;
4003 }
4004
4005 static void css_dput_fn(struct work_struct *work)
4006 {
4007         struct cgroup_subsys_state *css =
4008                 container_of(work, struct cgroup_subsys_state, dput_work);
4009         struct dentry *dentry = css->cgroup->dentry;
4010         struct super_block *sb = dentry->d_sb;
4011
4012         atomic_inc(&sb->s_active);
4013         dput(dentry);
4014         deactivate_super(sb);
4015 }
4016
4017 static void init_cgroup_css(struct cgroup_subsys_state *css,
4018                                struct cgroup_subsys *ss,
4019                                struct cgroup *cgrp)
4020 {
4021         css->cgroup = cgrp;
4022         atomic_set(&css->refcnt, 1);
4023         css->flags = 0;
4024         css->id = NULL;
4025         if (cgrp == dummytop)
4026                 css->flags |= CSS_ROOT;
4027         BUG_ON(cgrp->subsys[ss->subsys_id]);
4028         cgrp->subsys[ss->subsys_id] = css;
4029
4030         /*
4031          * css holds an extra ref to @cgrp->dentry which is put on the last
4032          * css_put().  dput() requires process context, which css_put() may
4033          * be called without.  @css->dput_work will be used to invoke
4034          * dput() asynchronously from css_put().
4035          */
4036         INIT_WORK(&css->dput_work, css_dput_fn);
4037 }
4038
4039 /* invoke ->post_create() on a new CSS and mark it online if successful */
4040 static int online_css(struct cgroup_subsys *ss, struct cgroup *cgrp)
4041 {
4042         int ret = 0;
4043
4044         lockdep_assert_held(&cgroup_mutex);
4045
4046         if (ss->css_online)
4047                 ret = ss->css_online(cgrp);
4048         if (!ret)
4049                 cgrp->subsys[ss->subsys_id]->flags |= CSS_ONLINE;
4050         return ret;
4051 }
4052
4053 /* if the CSS is online, invoke ->pre_destory() on it and mark it offline */
4054 static void offline_css(struct cgroup_subsys *ss, struct cgroup *cgrp)
4055         __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4056 {
4057         struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4058
4059         lockdep_assert_held(&cgroup_mutex);
4060
4061         if (!(css->flags & CSS_ONLINE))
4062                 return;
4063
4064         /*
4065          * css_offline() should be called with cgroup_mutex unlocked.  See
4066          * 3fa59dfbc3 ("cgroup: fix potential deadlock in pre_destroy") for
4067          * details.  This temporary unlocking should go away once
4068          * cgroup_mutex is unexported from controllers.
4069          */
4070         if (ss->css_offline) {
4071                 mutex_unlock(&cgroup_mutex);
4072                 ss->css_offline(cgrp);
4073                 mutex_lock(&cgroup_mutex);
4074         }
4075
4076         cgrp->subsys[ss->subsys_id]->flags &= ~CSS_ONLINE;
4077 }
4078
4079 /*
4080  * cgroup_create - create a cgroup
4081  * @parent: cgroup that will be parent of the new cgroup
4082  * @dentry: dentry of the new cgroup
4083  * @mode: mode to set on new inode
4084  *
4085  * Must be called with the mutex on the parent inode held
4086  */
4087 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4088                              umode_t mode)
4089 {
4090         struct cgroup *cgrp;
4091         struct cgroupfs_root *root = parent->root;
4092         int err = 0;
4093         struct cgroup_subsys *ss;
4094         struct super_block *sb = root->sb;
4095
4096         cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4097         if (!cgrp)
4098                 return -ENOMEM;
4099
4100         /*
4101          * Only live parents can have children.  Note that the liveliness
4102          * check isn't strictly necessary because cgroup_mkdir() and
4103          * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4104          * anyway so that locking is contained inside cgroup proper and we
4105          * don't get nasty surprises if we ever grow another caller.
4106          */
4107         if (!cgroup_lock_live_group(parent)) {
4108                 err = -ENODEV;
4109                 goto err_free_cgrp;
4110         }
4111
4112         /* Grab a reference on the superblock so the hierarchy doesn't
4113          * get deleted on unmount if there are child cgroups.  This
4114          * can be done outside cgroup_mutex, since the sb can't
4115          * disappear while someone has an open control file on the
4116          * fs */
4117         atomic_inc(&sb->s_active);
4118
4119         init_cgroup_housekeeping(cgrp);
4120
4121         cgrp->parent = parent;
4122         cgrp->root = parent->root;
4123         cgrp->top_cgroup = parent->top_cgroup;
4124
4125         if (notify_on_release(parent))
4126                 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4127
4128         if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4129                 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4130
4131         for_each_subsys(root, ss) {
4132                 struct cgroup_subsys_state *css;
4133
4134                 css = ss->css_alloc(cgrp);
4135                 if (IS_ERR(css)) {
4136                         err = PTR_ERR(css);
4137                         goto err_free_all;
4138                 }
4139                 init_cgroup_css(css, ss, cgrp);
4140                 if (ss->use_id) {
4141                         err = alloc_css_id(ss, parent, cgrp);
4142                         if (err)
4143                                 goto err_free_all;
4144                 }
4145
4146                 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4147                     parent->parent) {
4148                         pr_warning("cgroup: %s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4149                                    current->comm, current->pid, ss->name);
4150                         if (!strcmp(ss->name, "memory"))
4151                                 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4152                         ss->warned_broken_hierarchy = true;
4153                 }
4154         }
4155
4156         /*
4157          * Create directory.  cgroup_create_file() returns with the new
4158          * directory locked on success so that it can be populated without
4159          * dropping cgroup_mutex.
4160          */
4161         err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4162         if (err < 0)
4163                 goto err_free_all;
4164         lockdep_assert_held(&dentry->d_inode->i_mutex);
4165
4166         /* allocation complete, commit to creation */
4167         dentry->d_fsdata = cgrp;
4168         cgrp->dentry = dentry;
4169         list_add_tail(&cgrp->allcg_node, &root->allcg_list);
4170         list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4171         root->number_of_cgroups++;
4172
4173         /* each css holds a ref to the cgroup's dentry */
4174         for_each_subsys(root, ss)
4175                 dget(dentry);
4176
4177         /* creation succeeded, notify subsystems */
4178         for_each_subsys(root, ss) {
4179                 err = online_css(ss, cgrp);
4180                 if (err)
4181                         goto err_destroy;
4182         }
4183
4184         err = cgroup_populate_dir(cgrp, true, root->subsys_mask);
4185         if (err)
4186                 goto err_destroy;
4187
4188         mutex_unlock(&cgroup_mutex);
4189         mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4190
4191         return 0;
4192
4193 err_free_all:
4194         for_each_subsys(root, ss) {
4195                 if (cgrp->subsys[ss->subsys_id])
4196                         ss->css_free(cgrp);
4197         }
4198         mutex_unlock(&cgroup_mutex);
4199         /* Release the reference count that we took on the superblock */
4200         deactivate_super(sb);
4201 err_free_cgrp:
4202         kfree(cgrp);
4203         return err;
4204
4205 err_destroy:
4206         cgroup_destroy_locked(cgrp);
4207         mutex_unlock(&cgroup_mutex);
4208         mutex_unlock(&dentry->d_inode->i_mutex);
4209         return err;
4210 }
4211
4212 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4213 {
4214         struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4215
4216         /* the vfs holds inode->i_mutex already */
4217         return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4218 }
4219
4220 /*
4221  * Check the reference count on each subsystem. Since we already
4222  * established that there are no tasks in the cgroup, if the css refcount
4223  * is also 1, then there should be no outstanding references, so the
4224  * subsystem is safe to destroy. We scan across all subsystems rather than
4225  * using the per-hierarchy linked list of mounted subsystems since we can
4226  * be called via check_for_release() with no synchronization other than
4227  * RCU, and the subsystem linked list isn't RCU-safe.
4228  */
4229 static int cgroup_has_css_refs(struct cgroup *cgrp)
4230 {
4231         int i;
4232
4233         /*
4234          * We won't need to lock the subsys array, because the subsystems
4235          * we're concerned about aren't going anywhere since our cgroup root
4236          * has a reference on them.
4237          */
4238         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4239                 struct cgroup_subsys *ss = subsys[i];
4240                 struct cgroup_subsys_state *css;
4241
4242                 /* Skip subsystems not present or not in this hierarchy */
4243                 if (ss == NULL || ss->root != cgrp->root)
4244                         continue;
4245
4246                 css = cgrp->subsys[ss->subsys_id];
4247                 /*
4248                  * When called from check_for_release() it's possible
4249                  * that by this point the cgroup has been removed
4250                  * and the css deleted. But a false-positive doesn't
4251                  * matter, since it can only happen if the cgroup
4252                  * has been deleted and hence no longer needs the
4253                  * release agent to be called anyway.
4254                  */
4255                 if (css && css_refcnt(css) > 1)
4256                         return 1;
4257         }
4258         return 0;
4259 }
4260
4261 static int cgroup_destroy_locked(struct cgroup *cgrp)
4262         __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4263 {
4264         struct dentry *d = cgrp->dentry;
4265         struct cgroup *parent = cgrp->parent;
4266         DEFINE_WAIT(wait);
4267         struct cgroup_event *event, *tmp;
4268         struct cgroup_subsys *ss;
4269
4270         lockdep_assert_held(&d->d_inode->i_mutex);
4271         lockdep_assert_held(&cgroup_mutex);
4272
4273         if (atomic_read(&cgrp->count) || !list_empty(&cgrp->children))
4274                 return -EBUSY;
4275
4276         /*
4277          * Block new css_tryget() by deactivating refcnt and mark @cgrp
4278          * removed.  This makes future css_tryget() and child creation
4279          * attempts fail thus maintaining the removal conditions verified
4280          * above.
4281          */
4282         for_each_subsys(cgrp->root, ss) {
4283                 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4284
4285                 WARN_ON(atomic_read(&css->refcnt) < 0);
4286                 atomic_add(CSS_DEACT_BIAS, &css->refcnt);
4287         }
4288         set_bit(CGRP_REMOVED, &cgrp->flags);
4289
4290         /* tell subsystems to initate destruction */
4291         for_each_subsys(cgrp->root, ss)
4292                 offline_css(ss, cgrp);
4293
4294         /*
4295          * Put all the base refs.  Each css holds an extra reference to the
4296          * cgroup's dentry and cgroup removal proceeds regardless of css
4297          * refs.  On the last put of each css, whenever that may be, the
4298          * extra dentry ref is put so that dentry destruction happens only
4299          * after all css's are released.
4300          */
4301         for_each_subsys(cgrp->root, ss)
4302                 css_put(cgrp->subsys[ss->subsys_id]);
4303
4304         raw_spin_lock(&release_list_lock);
4305         if (!list_empty(&cgrp->release_list))
4306                 list_del_init(&cgrp->release_list);
4307         raw_spin_unlock(&release_list_lock);
4308
4309         /* delete this cgroup from parent->children */
4310         list_del_rcu(&cgrp->sibling);
4311         list_del_init(&cgrp->allcg_node);
4312
4313         dget(d);
4314         cgroup_d_remove_dir(d);
4315         dput(d);
4316
4317         set_bit(CGRP_RELEASABLE, &parent->flags);
4318         check_for_release(parent);
4319
4320         /*
4321          * Unregister events and notify userspace.
4322          * Notify userspace about cgroup removing only after rmdir of cgroup
4323          * directory to avoid race between userspace and kernelspace
4324          */
4325         spin_lock(&cgrp->event_list_lock);
4326         list_for_each_entry_safe(event, tmp, &cgrp->event_list, list) {
4327                 list_del(&event->list);
4328                 remove_wait_queue(event->wqh, &event->wait);
4329                 eventfd_signal(event->eventfd, 1);
4330                 schedule_work(&event->remove);
4331         }
4332         spin_unlock(&cgrp->event_list_lock);
4333
4334         return 0;
4335 }
4336
4337 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4338 {
4339         int ret;
4340
4341         mutex_lock(&cgroup_mutex);
4342         ret = cgroup_destroy_locked(dentry->d_fsdata);
4343         mutex_unlock(&cgroup_mutex);
4344
4345         return ret;
4346 }
4347
4348 static void __init_or_module cgroup_init_cftsets(struct cgroup_subsys *ss)
4349 {
4350         INIT_LIST_HEAD(&ss->cftsets);
4351
4352         /*
4353          * base_cftset is embedded in subsys itself, no need to worry about
4354          * deregistration.
4355          */
4356         if (ss->base_cftypes) {
4357                 ss->base_cftset.cfts = ss->base_cftypes;
4358                 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4359         }
4360 }
4361
4362 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4363 {
4364         struct cgroup_subsys_state *css;
4365
4366         printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4367
4368         mutex_lock(&cgroup_mutex);
4369
4370         /* init base cftset */
4371         cgroup_init_cftsets(ss);
4372
4373         /* Create the top cgroup state for this subsystem */
4374         list_add(&ss->sibling, &rootnode.subsys_list);
4375         ss->root = &rootnode;
4376         css = ss->css_alloc(dummytop);
4377         /* We don't handle early failures gracefully */
4378         BUG_ON(IS_ERR(css));
4379         init_cgroup_css(css, ss, dummytop);
4380
4381         /* Update the init_css_set to contain a subsys
4382          * pointer to this state - since the subsystem is
4383          * newly registered, all tasks and hence the
4384          * init_css_set is in the subsystem's top cgroup. */
4385         init_css_set.subsys[ss->subsys_id] = css;
4386
4387         need_forkexit_callback |= ss->fork || ss->exit;
4388
4389         /* At system boot, before all subsystems have been
4390          * registered, no tasks have been forked, so we don't
4391          * need to invoke fork callbacks here. */
4392         BUG_ON(!list_empty(&init_task.tasks));
4393
4394         ss->active = 1;
4395         BUG_ON(online_css(ss, dummytop));
4396
4397         mutex_unlock(&cgroup_mutex);
4398
4399         /* this function shouldn't be used with modular subsystems, since they
4400          * need to register a subsys_id, among other things */
4401         BUG_ON(ss->module);
4402 }
4403
4404 /**
4405  * cgroup_load_subsys: load and register a modular subsystem at runtime
4406  * @ss: the subsystem to load
4407  *
4408  * This function should be called in a modular subsystem's initcall. If the
4409  * subsystem is built as a module, it will be assigned a new subsys_id and set
4410  * up for use. If the subsystem is built-in anyway, work is delegated to the
4411  * simpler cgroup_init_subsys.
4412  */
4413 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
4414 {
4415         struct cgroup_subsys_state *css;
4416         int i, ret;
4417
4418         /* check name and function validity */
4419         if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
4420             ss->css_alloc == NULL || ss->css_free == NULL)
4421                 return -EINVAL;
4422
4423         /*
4424          * we don't support callbacks in modular subsystems. this check is
4425          * before the ss->module check for consistency; a subsystem that could
4426          * be a module should still have no callbacks even if the user isn't
4427          * compiling it as one.
4428          */
4429         if (ss->fork || ss->exit)
4430                 return -EINVAL;
4431
4432         /*
4433          * an optionally modular subsystem is built-in: we want to do nothing,
4434          * since cgroup_init_subsys will have already taken care of it.
4435          */
4436         if (ss->module == NULL) {
4437                 /* a sanity check */
4438                 BUG_ON(subsys[ss->subsys_id] != ss);
4439                 return 0;
4440         }
4441
4442         /* init base cftset */
4443         cgroup_init_cftsets(ss);
4444
4445         mutex_lock(&cgroup_mutex);
4446         subsys[ss->subsys_id] = ss;
4447
4448         /*
4449          * no ss->css_alloc seems to need anything important in the ss
4450          * struct, so this can happen first (i.e. before the rootnode
4451          * attachment).
4452          */
4453         css = ss->css_alloc(dummytop);
4454         if (IS_ERR(css)) {
4455                 /* failure case - need to deassign the subsys[] slot. */
4456                 subsys[ss->subsys_id] = NULL;
4457                 mutex_unlock(&cgroup_mutex);
4458                 return PTR_ERR(css);
4459         }
4460
4461         list_add(&ss->sibling, &rootnode.subsys_list);
4462         ss->root = &rootnode;
4463
4464         /* our new subsystem will be attached to the dummy hierarchy. */
4465         init_cgroup_css(css, ss, dummytop);
4466         /* init_idr must be after init_cgroup_css because it sets css->id. */
4467         if (ss->use_id) {
4468                 ret = cgroup_init_idr(ss, css);
4469                 if (ret)
4470                         goto err_unload;
4471         }
4472
4473         /*
4474          * Now we need to entangle the css into the existing css_sets. unlike
4475          * in cgroup_init_subsys, there are now multiple css_sets, so each one
4476          * will need a new pointer to it; done by iterating the css_set_table.
4477          * furthermore, modifying the existing css_sets will corrupt the hash
4478          * table state, so each changed css_set will need its hash recomputed.
4479          * this is all done under the css_set_lock.
4480          */
4481         write_lock(&css_set_lock);
4482         for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
4483                 struct css_set *cg;
4484                 struct hlist_node *node, *tmp;
4485                 struct hlist_head *bucket = &css_set_table[i], *new_bucket;
4486
4487                 hlist_for_each_entry_safe(cg, node, tmp, bucket, hlist) {
4488                         /* skip entries that we already rehashed */
4489                         if (cg->subsys[ss->subsys_id])
4490                                 continue;
4491                         /* remove existing entry */
4492                         hlist_del(&cg->hlist);
4493                         /* set new value */
4494                         cg->subsys[ss->subsys_id] = css;
4495                         /* recompute hash and restore entry */
4496                         new_bucket = css_set_hash(cg->subsys);
4497                         hlist_add_head(&cg->hlist, new_bucket);
4498                 }
4499         }
4500         write_unlock(&css_set_lock);
4501
4502         ss->active = 1;
4503         ret = online_css(ss, dummytop);
4504         if (ret)
4505                 goto err_unload;
4506
4507         /* success! */
4508         mutex_unlock(&cgroup_mutex);
4509         return 0;
4510
4511 err_unload:
4512         mutex_unlock(&cgroup_mutex);
4513         /* @ss can't be mounted here as try_module_get() would fail */
4514         cgroup_unload_subsys(ss);
4515         return ret;
4516 }
4517 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
4518
4519 /**
4520  * cgroup_unload_subsys: unload a modular subsystem
4521  * @ss: the subsystem to unload
4522  *
4523  * This function should be called in a modular subsystem's exitcall. When this
4524  * function is invoked, the refcount on the subsystem's module will be 0, so
4525  * the subsystem will not be attached to any hierarchy.
4526  */
4527 void cgroup_unload_subsys(struct cgroup_subsys *ss)
4528 {
4529         struct cg_cgroup_link *link;
4530         struct hlist_head *hhead;
4531
4532         BUG_ON(ss->module == NULL);
4533
4534         /*
4535          * we shouldn't be called if the subsystem is in use, and the use of
4536          * try_module_get in parse_cgroupfs_options should ensure that it
4537          * doesn't start being used while we're killing it off.
4538          */
4539         BUG_ON(ss->root != &rootnode);
4540
4541         mutex_lock(&cgroup_mutex);
4542
4543         offline_css(ss, dummytop);
4544         ss->active = 0;
4545
4546         if (ss->use_id) {
4547                 idr_remove_all(&ss->idr);
4548                 idr_destroy(&ss->idr);
4549         }
4550
4551         /* deassign the subsys_id */
4552         subsys[ss->subsys_id] = NULL;
4553
4554         /* remove subsystem from rootnode's list of subsystems */
4555         list_del_init(&ss->sibling);
4556
4557         /*
4558          * disentangle the css from all css_sets attached to the dummytop. as
4559          * in loading, we need to pay our respects to the hashtable gods.
4560          */
4561         write_lock(&css_set_lock);
4562         list_for_each_entry(link, &dummytop->css_sets, cgrp_link_list) {
4563                 struct css_set *cg = link->cg;
4564
4565                 hlist_del(&cg->hlist);
4566                 cg->subsys[ss->subsys_id] = NULL;
4567                 hhead = css_set_hash(cg->subsys);
4568                 hlist_add_head(&cg->hlist, hhead);
4569         }
4570         write_unlock(&css_set_lock);
4571
4572         /*
4573          * remove subsystem's css from the dummytop and free it - need to
4574          * free before marking as null because ss->css_free needs the
4575          * cgrp->subsys pointer to find their state. note that this also
4576          * takes care of freeing the css_id.
4577          */
4578         ss->css_free(dummytop);
4579         dummytop->subsys[ss->subsys_id] = NULL;
4580
4581         mutex_unlock(&cgroup_mutex);
4582 }
4583 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
4584
4585 /**
4586  * cgroup_init_early - cgroup initialization at system boot
4587  *
4588  * Initialize cgroups at system boot, and initialize any
4589  * subsystems that request early init.
4590  */
4591 int __init cgroup_init_early(void)
4592 {
4593         int i;
4594         atomic_set(&init_css_set.refcount, 1);
4595         INIT_LIST_HEAD(&init_css_set.cg_links);
4596         INIT_LIST_HEAD(&init_css_set.tasks);
4597         INIT_HLIST_NODE(&init_css_set.hlist);
4598         css_set_count = 1;
4599         init_cgroup_root(&rootnode);
4600         root_count = 1;
4601         init_task.cgroups = &init_css_set;
4602
4603         init_css_set_link.cg = &init_css_set;
4604         init_css_set_link.cgrp = dummytop;
4605         list_add(&init_css_set_link.cgrp_link_list,
4606                  &rootnode.top_cgroup.css_sets);
4607         list_add(&init_css_set_link.cg_link_list,
4608                  &init_css_set.cg_links);
4609
4610         for (i = 0; i < CSS_SET_TABLE_SIZE; i++)
4611                 INIT_HLIST_HEAD(&css_set_table[i]);
4612
4613         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4614                 struct cgroup_subsys *ss = subsys[i];
4615
4616                 /* at bootup time, we don't worry about modular subsystems */
4617                 if (!ss || ss->module)
4618                         continue;
4619
4620                 BUG_ON(!ss->name);
4621                 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
4622                 BUG_ON(!ss->css_alloc);
4623                 BUG_ON(!ss->css_free);
4624                 if (ss->subsys_id != i) {
4625                         printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
4626                                ss->name, ss->subsys_id);
4627                         BUG();
4628                 }
4629
4630                 if (ss->early_init)
4631                         cgroup_init_subsys(ss);
4632         }
4633         return 0;
4634 }
4635
4636 /**
4637  * cgroup_init - cgroup initialization
4638  *
4639  * Register cgroup filesystem and /proc file, and initialize
4640  * any subsystems that didn't request early init.
4641  */
4642 int __init cgroup_init(void)
4643 {
4644         int err;
4645         int i;
4646         struct hlist_head *hhead;
4647
4648         err = bdi_init(&cgroup_backing_dev_info);
4649         if (err)
4650                 return err;
4651
4652         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4653                 struct cgroup_subsys *ss = subsys[i];
4654
4655                 /* at bootup time, we don't worry about modular subsystems */
4656                 if (!ss || ss->module)
4657                         continue;
4658                 if (!ss->early_init)
4659                         cgroup_init_subsys(ss);
4660                 if (ss->use_id)
4661                         cgroup_init_idr(ss, init_css_set.subsys[ss->subsys_id]);
4662         }
4663
4664         /* Add init_css_set to the hash table */
4665         hhead = css_set_hash(init_css_set.subsys);
4666         hlist_add_head(&init_css_set.hlist, hhead);
4667         BUG_ON(!init_root_id(&rootnode));
4668
4669         cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4670         if (!cgroup_kobj) {
4671                 err = -ENOMEM;
4672                 goto out;
4673         }
4674
4675         err = register_filesystem(&cgroup_fs_type);
4676         if (err < 0) {
4677                 kobject_put(cgroup_kobj);
4678                 goto out;
4679         }
4680
4681         proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4682
4683 out:
4684         if (err)
4685                 bdi_destroy(&cgroup_backing_dev_info);
4686
4687         return err;
4688 }
4689
4690 /*
4691  * proc_cgroup_show()
4692  *  - Print task's cgroup paths into seq_file, one line for each hierarchy
4693  *  - Used for /proc/<pid>/cgroup.
4694  *  - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4695  *    doesn't really matter if tsk->cgroup changes after we read it,
4696  *    and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4697  *    anyway.  No need to check that tsk->cgroup != NULL, thanks to
4698  *    the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4699  *    cgroup to top_cgroup.
4700  */
4701
4702 /* TODO: Use a proper seq_file iterator */
4703 static int proc_cgroup_show(struct seq_file *m, void *v)
4704 {
4705         struct pid *pid;
4706         struct task_struct *tsk;
4707         char *buf;
4708         int retval;
4709         struct cgroupfs_root *root;
4710
4711         retval = -ENOMEM;
4712         buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4713         if (!buf)
4714                 goto out;
4715
4716         retval = -ESRCH;
4717         pid = m->private;
4718         tsk = get_pid_task(pid, PIDTYPE_PID);
4719         if (!tsk)
4720                 goto out_free;
4721
4722         retval = 0;
4723
4724         mutex_lock(&cgroup_mutex);
4725
4726         for_each_active_root(root) {
4727                 struct cgroup_subsys *ss;
4728                 struct cgroup *cgrp;
4729                 int count = 0;
4730
4731                 seq_printf(m, "%d:", root->hierarchy_id);
4732                 for_each_subsys(root, ss)
4733                         seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4734                 if (strlen(root->name))
4735                         seq_printf(m, "%sname=%s", count ? "," : "",
4736                                    root->name);
4737                 seq_putc(m, ':');
4738                 cgrp = task_cgroup_from_root(tsk, root);
4739                 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
4740                 if (retval < 0)
4741                         goto out_unlock;
4742                 seq_puts(m, buf);
4743                 seq_putc(m, '\n');
4744         }
4745
4746 out_unlock:
4747         mutex_unlock(&cgroup_mutex);
4748         put_task_struct(tsk);
4749 out_free:
4750         kfree(buf);
4751 out:
4752         return retval;
4753 }
4754
4755 static int cgroup_open(struct inode *inode, struct file *file)
4756 {
4757         struct pid *pid = PROC_I(inode)->pid;
4758         return single_open(file, proc_cgroup_show, pid);
4759 }
4760
4761 const struct file_operations proc_cgroup_operations = {
4762         .open           = cgroup_open,
4763         .read           = seq_read,
4764         .llseek         = seq_lseek,
4765         .release        = single_release,
4766 };
4767
4768 /* Display information about each subsystem and each hierarchy */
4769 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4770 {
4771         int i;
4772
4773         seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4774         /*
4775          * ideally we don't want subsystems moving around while we do this.
4776          * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4777          * subsys/hierarchy state.
4778          */
4779         mutex_lock(&cgroup_mutex);
4780         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4781                 struct cgroup_subsys *ss = subsys[i];
4782                 if (ss == NULL)
4783                         continue;
4784                 seq_printf(m, "%s\t%d\t%d\t%d\n",
4785                            ss->name, ss->root->hierarchy_id,
4786                            ss->root->number_of_cgroups, !ss->disabled);
4787         }
4788         mutex_unlock(&cgroup_mutex);
4789         return 0;
4790 }
4791
4792 static int cgroupstats_open(struct inode *inode, struct file *file)
4793 {
4794         return single_open(file, proc_cgroupstats_show, NULL);
4795 }
4796
4797 static const struct file_operations proc_cgroupstats_operations = {
4798         .open = cgroupstats_open,
4799         .read = seq_read,
4800         .llseek = seq_lseek,
4801         .release = single_release,
4802 };
4803
4804 /**
4805  * cgroup_fork - attach newly forked task to its parents cgroup.
4806  * @child: pointer to task_struct of forking parent process.
4807  *
4808  * Description: A task inherits its parent's cgroup at fork().
4809  *
4810  * A pointer to the shared css_set was automatically copied in
4811  * fork.c by dup_task_struct().  However, we ignore that copy, since
4812  * it was not made under the protection of RCU or cgroup_mutex, so
4813  * might no longer be a valid cgroup pointer.  cgroup_attach_task() might
4814  * have already changed current->cgroups, allowing the previously
4815  * referenced cgroup group to be removed and freed.
4816  *
4817  * At the point that cgroup_fork() is called, 'current' is the parent
4818  * task, and the passed argument 'child' points to the child task.
4819  */
4820 void cgroup_fork(struct task_struct *child)
4821 {
4822         task_lock(current);
4823         child->cgroups = current->cgroups;
4824         get_css_set(child->cgroups);
4825         task_unlock(current);
4826         INIT_LIST_HEAD(&child->cg_list);
4827 }
4828
4829 /**
4830  * cgroup_post_fork - called on a new task after adding it to the task list
4831  * @child: the task in question
4832  *
4833  * Adds the task to the list running through its css_set if necessary and
4834  * call the subsystem fork() callbacks.  Has to be after the task is
4835  * visible on the task list in case we race with the first call to
4836  * cgroup_iter_start() - to guarantee that the new task ends up on its
4837  * list.
4838  */
4839 void cgroup_post_fork(struct task_struct *child)
4840 {
4841         int i;
4842
4843         /*
4844          * use_task_css_set_links is set to 1 before we walk the tasklist
4845          * under the tasklist_lock and we read it here after we added the child
4846          * to the tasklist under the tasklist_lock as well. If the child wasn't
4847          * yet in the tasklist when we walked through it from
4848          * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4849          * should be visible now due to the paired locking and barriers implied
4850          * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4851          * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4852          * lock on fork.
4853          */
4854         if (use_task_css_set_links) {
4855                 write_lock(&css_set_lock);
4856                 task_lock(child);
4857                 if (list_empty(&child->cg_list))
4858                         list_add(&child->cg_list, &child->cgroups->tasks);
4859                 task_unlock(child);
4860                 write_unlock(&css_set_lock);
4861         }
4862
4863         /*
4864          * Call ss->fork().  This must happen after @child is linked on
4865          * css_set; otherwise, @child might change state between ->fork()
4866          * and addition to css_set.
4867          */
4868         if (need_forkexit_callback) {
4869                 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4870                         struct cgroup_subsys *ss = subsys[i];
4871
4872                         /*
4873                          * fork/exit callbacks are supported only for
4874                          * builtin subsystems and we don't need further
4875                          * synchronization as they never go away.
4876                          */
4877                         if (!ss || ss->module)
4878                                 continue;
4879
4880                         if (ss->fork)
4881                                 ss->fork(child);
4882                 }
4883         }
4884 }
4885
4886 /**
4887  * cgroup_exit - detach cgroup from exiting task
4888  * @tsk: pointer to task_struct of exiting process
4889  * @run_callback: run exit callbacks?
4890  *
4891  * Description: Detach cgroup from @tsk and release it.
4892  *
4893  * Note that cgroups marked notify_on_release force every task in
4894  * them to take the global cgroup_mutex mutex when exiting.
4895  * This could impact scaling on very large systems.  Be reluctant to
4896  * use notify_on_release cgroups where very high task exit scaling
4897  * is required on large systems.
4898  *
4899  * the_top_cgroup_hack:
4900  *
4901  *    Set the exiting tasks cgroup to the root cgroup (top_cgroup).
4902  *
4903  *    We call cgroup_exit() while the task is still competent to
4904  *    handle notify_on_release(), then leave the task attached to the
4905  *    root cgroup in each hierarchy for the remainder of its exit.
4906  *
4907  *    To do this properly, we would increment the reference count on
4908  *    top_cgroup, and near the very end of the kernel/exit.c do_exit()
4909  *    code we would add a second cgroup function call, to drop that
4910  *    reference.  This would just create an unnecessary hot spot on
4911  *    the top_cgroup reference count, to no avail.
4912  *
4913  *    Normally, holding a reference to a cgroup without bumping its
4914  *    count is unsafe.   The cgroup could go away, or someone could
4915  *    attach us to a different cgroup, decrementing the count on
4916  *    the first cgroup that we never incremented.  But in this case,
4917  *    top_cgroup isn't going away, and either task has PF_EXITING set,
4918  *    which wards off any cgroup_attach_task() attempts, or task is a failed
4919  *    fork, never visible to cgroup_attach_task.
4920  */
4921 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
4922 {
4923         struct css_set *cg;
4924         int i;
4925
4926         /*
4927          * Unlink from the css_set task list if necessary.
4928          * Optimistically check cg_list before taking
4929          * css_set_lock
4930          */
4931         if (!list_empty(&tsk->cg_list)) {
4932                 write_lock(&css_set_lock);
4933                 if (!list_empty(&tsk->cg_list))
4934                         list_del_init(&tsk->cg_list);
4935                 write_unlock(&css_set_lock);
4936         }
4937
4938         /* Reassign the task to the init_css_set. */
4939         task_lock(tsk);
4940         cg = tsk->cgroups;
4941         tsk->cgroups = &init_css_set;
4942
4943         if (run_callbacks && need_forkexit_callback) {
4944                 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4945                         struct cgroup_subsys *ss = subsys[i];
4946
4947                         /* modular subsystems can't use callbacks */
4948                         if (!ss || ss->module)
4949                                 continue;
4950
4951                         if (ss->exit) {
4952                                 struct cgroup *old_cgrp =
4953                                         rcu_dereference_raw(cg->subsys[i])->cgroup;
4954                                 struct cgroup *cgrp = task_cgroup(tsk, i);
4955                                 ss->exit(cgrp, old_cgrp, tsk);
4956                         }
4957                 }
4958         }
4959         task_unlock(tsk);
4960
4961         if (cg)
4962                 put_css_set_taskexit(cg);
4963 }
4964
4965 /**
4966  * cgroup_is_descendant - see if @cgrp is a descendant of @task's cgrp
4967  * @cgrp: the cgroup in question
4968  * @task: the task in question
4969  *
4970  * See if @cgrp is a descendant of @task's cgroup in the appropriate
4971  * hierarchy.
4972  *
4973  * If we are sending in dummytop, then presumably we are creating
4974  * the top cgroup in the subsystem.
4975  *
4976  * Called only by the ns (nsproxy) cgroup.
4977  */
4978 int cgroup_is_descendant(const struct cgroup *cgrp, struct task_struct *task)
4979 {
4980         int ret;
4981         struct cgroup *target;
4982
4983         if (cgrp == dummytop)
4984                 return 1;
4985
4986         target = task_cgroup_from_root(task, cgrp->root);
4987         while (cgrp != target && cgrp!= cgrp->top_cgroup)
4988                 cgrp = cgrp->parent;
4989         ret = (cgrp == target);
4990         return ret;
4991 }
4992
4993 static void check_for_release(struct cgroup *cgrp)
4994 {
4995         /* All of these checks rely on RCU to keep the cgroup
4996          * structure alive */
4997         if (cgroup_is_releasable(cgrp) && !atomic_read(&cgrp->count)
4998             && list_empty(&cgrp->children) && !cgroup_has_css_refs(cgrp)) {
4999                 /* Control Group is currently removeable. If it's not
5000                  * already queued for a userspace notification, queue
5001                  * it now */
5002                 int need_schedule_work = 0;
5003                 raw_spin_lock(&release_list_lock);
5004                 if (!cgroup_is_removed(cgrp) &&
5005                     list_empty(&cgrp->release_list)) {
5006                         list_add(&cgrp->release_list, &release_list);
5007                         need_schedule_work = 1;
5008                 }
5009                 raw_spin_unlock(&release_list_lock);
5010                 if (need_schedule_work)
5011                         schedule_work(&release_agent_work);
5012         }
5013 }
5014
5015 /* Caller must verify that the css is not for root cgroup */
5016 bool __css_tryget(struct cgroup_subsys_state *css)
5017 {
5018         while (true) {
5019                 int t, v;
5020
5021                 v = css_refcnt(css);
5022                 t = atomic_cmpxchg(&css->refcnt, v, v + 1);
5023                 if (likely(t == v))
5024                         return true;
5025                 else if (t < 0)
5026                         return false;
5027                 cpu_relax();
5028         }
5029 }
5030 EXPORT_SYMBOL_GPL(__css_tryget);
5031
5032 /* Caller must verify that the css is not for root cgroup */
5033 void __css_put(struct cgroup_subsys_state *css)
5034 {
5035         struct cgroup *cgrp = css->cgroup;
5036         int v;
5037
5038         rcu_read_lock();
5039         v = css_unbias_refcnt(atomic_dec_return(&css->refcnt));
5040
5041         switch (v) {
5042         case 1:
5043                 if (notify_on_release(cgrp)) {
5044                         set_bit(CGRP_RELEASABLE, &cgrp->flags);
5045                         check_for_release(cgrp);
5046                 }
5047                 break;
5048         case 0:
5049                 schedule_work(&css->dput_work);
5050                 break;
5051         }
5052         rcu_read_unlock();
5053 }
5054 EXPORT_SYMBOL_GPL(__css_put);
5055
5056 /*
5057  * Notify userspace when a cgroup is released, by running the
5058  * configured release agent with the name of the cgroup (path
5059  * relative to the root of cgroup file system) as the argument.
5060  *
5061  * Most likely, this user command will try to rmdir this cgroup.
5062  *
5063  * This races with the possibility that some other task will be
5064  * attached to this cgroup before it is removed, or that some other
5065  * user task will 'mkdir' a child cgroup of this cgroup.  That's ok.
5066  * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5067  * unused, and this cgroup will be reprieved from its death sentence,
5068  * to continue to serve a useful existence.  Next time it's released,
5069  * we will get notified again, if it still has 'notify_on_release' set.
5070  *
5071  * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5072  * means only wait until the task is successfully execve()'d.  The
5073  * separate release agent task is forked by call_usermodehelper(),
5074  * then control in this thread returns here, without waiting for the
5075  * release agent task.  We don't bother to wait because the caller of
5076  * this routine has no use for the exit status of the release agent
5077  * task, so no sense holding our caller up for that.
5078  */
5079 static void cgroup_release_agent(struct work_struct *work)
5080 {
5081         BUG_ON(work != &release_agent_work);
5082         mutex_lock(&cgroup_mutex);
5083         raw_spin_lock(&release_list_lock);
5084         while (!list_empty(&release_list)) {
5085                 char *argv[3], *envp[3];
5086                 int i;
5087                 char *pathbuf = NULL, *agentbuf = NULL;
5088                 struct cgroup *cgrp = list_entry(release_list.next,
5089                                                     struct cgroup,
5090                                                     release_list);
5091                 list_del_init(&cgrp->release_list);
5092                 raw_spin_unlock(&release_list_lock);
5093                 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5094                 if (!pathbuf)
5095                         goto continue_free;
5096                 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
5097                         goto continue_free;
5098                 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5099                 if (!agentbuf)
5100                         goto continue_free;
5101
5102                 i = 0;
5103                 argv[i++] = agentbuf;
5104                 argv[i++] = pathbuf;
5105                 argv[i] = NULL;
5106
5107                 i = 0;
5108                 /* minimal command environment */
5109                 envp[i++] = "HOME=/";
5110                 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5111                 envp[i] = NULL;
5112
5113                 /* Drop the lock while we invoke the usermode helper,
5114                  * since the exec could involve hitting disk and hence
5115                  * be a slow process */
5116                 mutex_unlock(&cgroup_mutex);
5117                 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5118                 mutex_lock(&cgroup_mutex);
5119  continue_free:
5120                 kfree(pathbuf);
5121                 kfree(agentbuf);
5122                 raw_spin_lock(&release_list_lock);
5123         }
5124         raw_spin_unlock(&release_list_lock);
5125         mutex_unlock(&cgroup_mutex);
5126 }
5127
5128 static int __init cgroup_disable(char *str)
5129 {
5130         int i;
5131         char *token;
5132
5133         while ((token = strsep(&str, ",")) != NULL) {
5134                 if (!*token)
5135                         continue;
5136                 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
5137                         struct cgroup_subsys *ss = subsys[i];
5138
5139                         /*
5140                          * cgroup_disable, being at boot time, can't
5141                          * know about module subsystems, so we don't
5142                          * worry about them.
5143                          */
5144                         if (!ss || ss->module)
5145                                 continue;
5146
5147                         if (!strcmp(token, ss->name)) {
5148                                 ss->disabled = 1;
5149                                 printk(KERN_INFO "Disabling %s control group"
5150                                         " subsystem\n", ss->name);
5151                                 break;
5152                         }
5153                 }
5154         }
5155         return 1;
5156 }
5157 __setup("cgroup_disable=", cgroup_disable);
5158
5159 /*
5160  * Functons for CSS ID.
5161  */
5162
5163 /*
5164  *To get ID other than 0, this should be called when !cgroup_is_removed().
5165  */
5166 unsigned short css_id(struct cgroup_subsys_state *css)
5167 {
5168         struct css_id *cssid;
5169
5170         /*
5171          * This css_id() can return correct value when somone has refcnt
5172          * on this or this is under rcu_read_lock(). Once css->id is allocated,
5173          * it's unchanged until freed.
5174          */
5175         cssid = rcu_dereference_check(css->id, css_refcnt(css));
5176
5177         if (cssid)
5178                 return cssid->id;
5179         return 0;
5180 }
5181 EXPORT_SYMBOL_GPL(css_id);
5182
5183 unsigned short css_depth(struct cgroup_subsys_state *css)
5184 {
5185         struct css_id *cssid;
5186
5187         cssid = rcu_dereference_check(css->id, css_refcnt(css));
5188
5189         if (cssid)
5190                 return cssid->depth;
5191         return 0;
5192 }
5193 EXPORT_SYMBOL_GPL(css_depth);
5194
5195 /**
5196  *  css_is_ancestor - test "root" css is an ancestor of "child"
5197  * @child: the css to be tested.
5198  * @root: the css supporsed to be an ancestor of the child.
5199  *
5200  * Returns true if "root" is an ancestor of "child" in its hierarchy. Because
5201  * this function reads css->id, the caller must hold rcu_read_lock().
5202  * But, considering usual usage, the csses should be valid objects after test.
5203  * Assuming that the caller will do some action to the child if this returns
5204  * returns true, the caller must take "child";s reference count.
5205  * If "child" is valid object and this returns true, "root" is valid, too.
5206  */
5207
5208 bool css_is_ancestor(struct cgroup_subsys_state *child,
5209                     const struct cgroup_subsys_state *root)
5210 {
5211         struct css_id *child_id;
5212         struct css_id *root_id;
5213
5214         child_id  = rcu_dereference(child->id);
5215         if (!child_id)
5216                 return false;
5217         root_id = rcu_dereference(root->id);
5218         if (!root_id)
5219                 return false;
5220         if (child_id->depth < root_id->depth)
5221                 return false;
5222         if (child_id->stack[root_id->depth] != root_id->id)
5223                 return false;
5224         return true;
5225 }
5226
5227 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
5228 {
5229         struct css_id *id = css->id;
5230         /* When this is called before css_id initialization, id can be NULL */
5231         if (!id)
5232                 return;
5233
5234         BUG_ON(!ss->use_id);
5235
5236         rcu_assign_pointer(id->css, NULL);
5237         rcu_assign_pointer(css->id, NULL);
5238         spin_lock(&ss->id_lock);
5239         idr_remove(&ss->idr, id->id);
5240         spin_unlock(&ss->id_lock);
5241         kfree_rcu(id, rcu_head);
5242 }
5243 EXPORT_SYMBOL_GPL(free_css_id);
5244
5245 /*
5246  * This is called by init or create(). Then, calls to this function are
5247  * always serialized (By cgroup_mutex() at create()).
5248  */
5249
5250 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
5251 {
5252         struct css_id *newid;
5253         int myid, error, size;
5254
5255         BUG_ON(!ss->use_id);
5256
5257         size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
5258         newid = kzalloc(size, GFP_KERNEL);
5259         if (!newid)
5260                 return ERR_PTR(-ENOMEM);
5261         /* get id */
5262         if (unlikely(!idr_pre_get(&ss->idr, GFP_KERNEL))) {
5263                 error = -ENOMEM;
5264                 goto err_out;
5265         }
5266         spin_lock(&ss->id_lock);
5267         /* Don't use 0. allocates an ID of 1-65535 */
5268         error = idr_get_new_above(&ss->idr, newid, 1, &myid);
5269         spin_unlock(&ss->id_lock);
5270
5271         /* Returns error when there are no free spaces for new ID.*/
5272         if (error) {
5273                 error = -ENOSPC;
5274                 goto err_out;
5275         }
5276         if (myid > CSS_ID_MAX)
5277                 goto remove_idr;
5278
5279         newid->id = myid;
5280         newid->depth = depth;
5281         return newid;
5282 remove_idr:
5283         error = -ENOSPC;
5284         spin_lock(&ss->id_lock);
5285         idr_remove(&ss->idr, myid);
5286         spin_unlock(&ss->id_lock);
5287 err_out:
5288         kfree(newid);
5289         return ERR_PTR(error);
5290
5291 }
5292
5293 static int __init_or_module cgroup_init_idr(struct cgroup_subsys *ss,
5294                                             struct cgroup_subsys_state *rootcss)
5295 {
5296         struct css_id *newid;
5297
5298         spin_lock_init(&ss->id_lock);
5299         idr_init(&ss->idr);
5300
5301         newid = get_new_cssid(ss, 0);
5302         if (IS_ERR(newid))
5303                 return PTR_ERR(newid);
5304
5305         newid->stack[0] = newid->id;
5306         newid->css = rootcss;
5307         rootcss->id = newid;
5308         return 0;
5309 }
5310
5311 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
5312                         struct cgroup *child)
5313 {
5314         int subsys_id, i, depth = 0;
5315         struct cgroup_subsys_state *parent_css, *child_css;
5316         struct css_id *child_id, *parent_id;
5317
5318         subsys_id = ss->subsys_id;
5319         parent_css = parent->subsys[subsys_id];
5320         child_css = child->subsys[subsys_id];
5321         parent_id = parent_css->id;
5322         depth = parent_id->depth + 1;
5323
5324         child_id = get_new_cssid(ss, depth);
5325         if (IS_ERR(child_id))
5326                 return PTR_ERR(child_id);
5327
5328         for (i = 0; i < depth; i++)
5329                 child_id->stack[i] = parent_id->stack[i];
5330         child_id->stack[depth] = child_id->id;
5331         /*
5332          * child_id->css pointer will be set after this cgroup is available
5333          * see cgroup_populate_dir()
5334          */
5335         rcu_assign_pointer(child_css->id, child_id);
5336
5337         return 0;
5338 }
5339
5340 /**
5341  * css_lookup - lookup css by id
5342  * @ss: cgroup subsys to be looked into.
5343  * @id: the id
5344  *
5345  * Returns pointer to cgroup_subsys_state if there is valid one with id.
5346  * NULL if not. Should be called under rcu_read_lock()
5347  */
5348 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
5349 {
5350         struct css_id *cssid = NULL;
5351
5352         BUG_ON(!ss->use_id);
5353         cssid = idr_find(&ss->idr, id);
5354
5355         if (unlikely(!cssid))
5356                 return NULL;
5357
5358         return rcu_dereference(cssid->css);
5359 }
5360 EXPORT_SYMBOL_GPL(css_lookup);
5361
5362 /**
5363  * css_get_next - lookup next cgroup under specified hierarchy.
5364  * @ss: pointer to subsystem
5365  * @id: current position of iteration.
5366  * @root: pointer to css. search tree under this.
5367  * @foundid: position of found object.
5368  *
5369  * Search next css under the specified hierarchy of rootid. Calling under
5370  * rcu_read_lock() is necessary. Returns NULL if it reaches the end.
5371  */
5372 struct cgroup_subsys_state *
5373 css_get_next(struct cgroup_subsys *ss, int id,
5374              struct cgroup_subsys_state *root, int *foundid)
5375 {
5376         struct cgroup_subsys_state *ret = NULL;
5377         struct css_id *tmp;
5378         int tmpid;
5379         int rootid = css_id(root);
5380         int depth = css_depth(root);
5381
5382         if (!rootid)
5383                 return NULL;
5384
5385         BUG_ON(!ss->use_id);
5386         WARN_ON_ONCE(!rcu_read_lock_held());
5387
5388         /* fill start point for scan */
5389         tmpid = id;
5390         while (1) {
5391                 /*
5392                  * scan next entry from bitmap(tree), tmpid is updated after
5393                  * idr_get_next().
5394                  */
5395                 tmp = idr_get_next(&ss->idr, &tmpid);
5396                 if (!tmp)
5397                         break;
5398                 if (tmp->depth >= depth && tmp->stack[depth] == rootid) {
5399                         ret = rcu_dereference(tmp->css);
5400                         if (ret) {
5401                                 *foundid = tmpid;
5402                                 break;
5403                         }
5404                 }
5405                 /* continue to scan from next id */
5406                 tmpid = tmpid + 1;
5407         }
5408         return ret;
5409 }
5410
5411 /*
5412  * get corresponding css from file open on cgroupfs directory
5413  */
5414 struct cgroup_subsys_state *cgroup_css_from_dir(struct file *f, int id)
5415 {
5416         struct cgroup *cgrp;
5417         struct inode *inode;
5418         struct cgroup_subsys_state *css;
5419
5420         inode = f->f_dentry->d_inode;
5421         /* check in cgroup filesystem dir */
5422         if (inode->i_op != &cgroup_dir_inode_operations)
5423                 return ERR_PTR(-EBADF);
5424
5425         if (id < 0 || id >= CGROUP_SUBSYS_COUNT)
5426                 return ERR_PTR(-EINVAL);
5427
5428         /* get cgroup */
5429         cgrp = __d_cgrp(f->f_dentry);
5430         css = cgrp->subsys[id];
5431         return css ? css : ERR_PTR(-ENOENT);
5432 }
5433
5434 #ifdef CONFIG_CGROUP_DEBUG
5435 static struct cgroup_subsys_state *debug_css_alloc(struct cgroup *cont)
5436 {
5437         struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5438
5439         if (!css)
5440                 return ERR_PTR(-ENOMEM);
5441
5442         return css;
5443 }
5444
5445 static void debug_css_free(struct cgroup *cont)
5446 {
5447         kfree(cont->subsys[debug_subsys_id]);
5448 }
5449
5450 static u64 cgroup_refcount_read(struct cgroup *cont, struct cftype *cft)
5451 {
5452         return atomic_read(&cont->count);
5453 }
5454
5455 static u64 debug_taskcount_read(struct cgroup *cont, struct cftype *cft)
5456 {
5457         return cgroup_task_count(cont);
5458 }
5459
5460 static u64 current_css_set_read(struct cgroup *cont, struct cftype *cft)
5461 {
5462         return (u64)(unsigned long)current->cgroups;
5463 }
5464
5465 static u64 current_css_set_refcount_read(struct cgroup *cont,
5466                                            struct cftype *cft)
5467 {
5468         u64 count;
5469
5470         rcu_read_lock();
5471         count = atomic_read(&current->cgroups->refcount);
5472         rcu_read_unlock();
5473         return count;
5474 }
5475
5476 static int current_css_set_cg_links_read(struct cgroup *cont,
5477                                          struct cftype *cft,
5478                                          struct seq_file *seq)
5479 {
5480         struct cg_cgroup_link *link;
5481         struct css_set *cg;
5482
5483         read_lock(&css_set_lock);
5484         rcu_read_lock();
5485         cg = rcu_dereference(current->cgroups);
5486         list_for_each_entry(link, &cg->cg_links, cg_link_list) {
5487                 struct cgroup *c = link->cgrp;
5488                 const char *name;
5489
5490                 if (c->dentry)
5491                         name = c->dentry->d_name.name;
5492                 else
5493                         name = "?";
5494                 seq_printf(seq, "Root %d group %s\n",
5495                            c->root->hierarchy_id, name);
5496         }
5497         rcu_read_unlock();
5498         read_unlock(&css_set_lock);
5499         return 0;
5500 }
5501
5502 #define MAX_TASKS_SHOWN_PER_CSS 25
5503 static int cgroup_css_links_read(struct cgroup *cont,
5504                                  struct cftype *cft,
5505                                  struct seq_file *seq)
5506 {
5507         struct cg_cgroup_link *link;
5508
5509         read_lock(&css_set_lock);
5510         list_for_each_entry(link, &cont->css_sets, cgrp_link_list) {
5511                 struct css_set *cg = link->cg;
5512                 struct task_struct *task;
5513                 int count = 0;
5514                 seq_printf(seq, "css_set %p\n", cg);
5515                 list_for_each_entry(task, &cg->tasks, cg_list) {
5516                         if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5517                                 seq_puts(seq, "  ...\n");
5518                                 break;
5519                         } else {
5520                                 seq_printf(seq, "  task %d\n",
5521                                            task_pid_vnr(task));
5522                         }
5523                 }
5524         }
5525         read_unlock(&css_set_lock);
5526         return 0;
5527 }
5528
5529 static u64 releasable_read(struct cgroup *cgrp, struct cftype *cft)
5530 {
5531         return test_bit(CGRP_RELEASABLE, &cgrp->flags);
5532 }
5533
5534 static struct cftype debug_files[] =  {
5535         {
5536                 .name = "cgroup_refcount",
5537                 .read_u64 = cgroup_refcount_read,
5538         },
5539         {
5540                 .name = "taskcount",
5541                 .read_u64 = debug_taskcount_read,
5542         },
5543
5544         {
5545                 .name = "current_css_set",
5546                 .read_u64 = current_css_set_read,
5547         },
5548
5549         {
5550                 .name = "current_css_set_refcount",
5551                 .read_u64 = current_css_set_refcount_read,
5552         },
5553
5554         {
5555                 .name = "current_css_set_cg_links",
5556                 .read_seq_string = current_css_set_cg_links_read,
5557         },
5558
5559         {
5560                 .name = "cgroup_css_links",
5561                 .read_seq_string = cgroup_css_links_read,
5562         },
5563
5564         {
5565                 .name = "releasable",
5566                 .read_u64 = releasable_read,
5567         },
5568
5569         { }     /* terminate */
5570 };
5571
5572 struct cgroup_subsys debug_subsys = {
5573         .name = "debug",
5574         .css_alloc = debug_css_alloc,
5575         .css_free = debug_css_free,
5576         .subsys_id = debug_subsys_id,
5577         .base_cftypes = debug_files,
5578 };
5579 #endif /* CONFIG_CGROUP_DEBUG */