521591dbab2fd1af86a03804da55e1104f9816a3
[safe/jmp/linux-2.6] / 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  *  Copyright notices from the original cpuset code:
8  *  --------------------------------------------------
9  *  Copyright (C) 2003 BULL SA.
10  *  Copyright (C) 2004-2006 Silicon Graphics, Inc.
11  *
12  *  Portions derived from Patrick Mochel's sysfs code.
13  *  sysfs is Copyright (c) 2001-3 Patrick Mochel
14  *
15  *  2003-10-10 Written by Simon Derr.
16  *  2003-10-22 Updates by Stephen Hemminger.
17  *  2004 May-July Rework by Paul Jackson.
18  *  ---------------------------------------------------
19  *
20  *  This file is subject to the terms and conditions of the GNU General Public
21  *  License.  See the file COPYING in the main directory of the Linux
22  *  distribution for more details.
23  */
24
25 #include <linux/cgroup.h>
26 #include <linux/module.h>
27 #include <linux/ctype.h>
28 #include <linux/errno.h>
29 #include <linux/fs.h>
30 #include <linux/kernel.h>
31 #include <linux/list.h>
32 #include <linux/mm.h>
33 #include <linux/mutex.h>
34 #include <linux/mount.h>
35 #include <linux/pagemap.h>
36 #include <linux/proc_fs.h>
37 #include <linux/rcupdate.h>
38 #include <linux/sched.h>
39 #include <linux/backing-dev.h>
40 #include <linux/seq_file.h>
41 #include <linux/slab.h>
42 #include <linux/magic.h>
43 #include <linux/spinlock.h>
44 #include <linux/string.h>
45 #include <linux/sort.h>
46 #include <linux/kmod.h>
47 #include <linux/module.h>
48 #include <linux/delayacct.h>
49 #include <linux/cgroupstats.h>
50 #include <linux/hash.h>
51 #include <linux/namei.h>
52 #include <linux/smp_lock.h>
53 #include <linux/pid_namespace.h>
54 #include <linux/idr.h>
55 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
56
57 #include <asm/atomic.h>
58
59 static DEFINE_MUTEX(cgroup_mutex);
60
61 /*
62  * Generate an array of cgroup subsystem pointers. At boot time, this is
63  * populated up to CGROUP_BUILTIN_SUBSYS_COUNT, and modular subsystems are
64  * registered after that. The mutable section of this array is protected by
65  * cgroup_mutex.
66  */
67 #define SUBSYS(_x) &_x ## _subsys,
68 static struct cgroup_subsys *subsys[CGROUP_SUBSYS_COUNT] = {
69 #include <linux/cgroup_subsys.h>
70 };
71
72 #define MAX_CGROUP_ROOT_NAMELEN 64
73
74 /*
75  * A cgroupfs_root represents the root of a cgroup hierarchy,
76  * and may be associated with a superblock to form an active
77  * hierarchy
78  */
79 struct cgroupfs_root {
80         struct super_block *sb;
81
82         /*
83          * The bitmask of subsystems intended to be attached to this
84          * hierarchy
85          */
86         unsigned long subsys_bits;
87
88         /* Unique id for this hierarchy. */
89         int hierarchy_id;
90
91         /* The bitmask of subsystems currently attached to this hierarchy */
92         unsigned long actual_subsys_bits;
93
94         /* A list running through the attached subsystems */
95         struct list_head subsys_list;
96
97         /* The root cgroup for this hierarchy */
98         struct cgroup top_cgroup;
99
100         /* Tracks how many cgroups are currently defined in hierarchy.*/
101         int number_of_cgroups;
102
103         /* A list running through the active hierarchies */
104         struct list_head root_list;
105
106         /* Hierarchy-specific flags */
107         unsigned long flags;
108
109         /* The path to use for release notifications. */
110         char release_agent_path[PATH_MAX];
111
112         /* The name for this hierarchy - may be empty */
113         char name[MAX_CGROUP_ROOT_NAMELEN];
114 };
115
116 /*
117  * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the
118  * subsystems that are otherwise unattached - it never has more than a
119  * single cgroup, and all tasks are part of that cgroup.
120  */
121 static struct cgroupfs_root rootnode;
122
123 /*
124  * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when
125  * cgroup_subsys->use_id != 0.
126  */
127 #define CSS_ID_MAX      (65535)
128 struct css_id {
129         /*
130          * The css to which this ID points. This pointer is set to valid value
131          * after cgroup is populated. If cgroup is removed, this will be NULL.
132          * This pointer is expected to be RCU-safe because destroy()
133          * is called after synchronize_rcu(). But for safe use, css_is_removed()
134          * css_tryget() should be used for avoiding race.
135          */
136         struct cgroup_subsys_state *css;
137         /*
138          * ID of this css.
139          */
140         unsigned short id;
141         /*
142          * Depth in hierarchy which this ID belongs to.
143          */
144         unsigned short depth;
145         /*
146          * ID is freed by RCU. (and lookup routine is RCU safe.)
147          */
148         struct rcu_head rcu_head;
149         /*
150          * Hierarchy of CSS ID belongs to.
151          */
152         unsigned short stack[0]; /* Array of Length (depth+1) */
153 };
154
155
156 /* The list of hierarchy roots */
157
158 static LIST_HEAD(roots);
159 static int root_count;
160
161 static DEFINE_IDA(hierarchy_ida);
162 static int next_hierarchy_id;
163 static DEFINE_SPINLOCK(hierarchy_id_lock);
164
165 /* dummytop is a shorthand for the dummy hierarchy's top cgroup */
166 #define dummytop (&rootnode.top_cgroup)
167
168 /* This flag indicates whether tasks in the fork and exit paths should
169  * check for fork/exit handlers to call. This avoids us having to do
170  * extra work in the fork/exit path if none of the subsystems need to
171  * be called.
172  */
173 static int need_forkexit_callback __read_mostly;
174
175 #ifdef CONFIG_PROVE_LOCKING
176 int cgroup_lock_is_held(void)
177 {
178         return lockdep_is_held(&cgroup_mutex);
179 }
180 #else /* #ifdef CONFIG_PROVE_LOCKING */
181 int cgroup_lock_is_held(void)
182 {
183         return mutex_is_locked(&cgroup_mutex);
184 }
185 #endif /* #else #ifdef CONFIG_PROVE_LOCKING */
186
187 EXPORT_SYMBOL_GPL(cgroup_lock_is_held);
188
189 /* convenient tests for these bits */
190 inline int cgroup_is_removed(const struct cgroup *cgrp)
191 {
192         return test_bit(CGRP_REMOVED, &cgrp->flags);
193 }
194
195 /* bits in struct cgroupfs_root flags field */
196 enum {
197         ROOT_NOPREFIX, /* mounted subsystems have no named prefix */
198 };
199
200 static int cgroup_is_releasable(const struct cgroup *cgrp)
201 {
202         const int bits =
203                 (1 << CGRP_RELEASABLE) |
204                 (1 << CGRP_NOTIFY_ON_RELEASE);
205         return (cgrp->flags & bits) == bits;
206 }
207
208 static int notify_on_release(const struct cgroup *cgrp)
209 {
210         return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
211 }
212
213 /*
214  * for_each_subsys() allows you to iterate on each subsystem attached to
215  * an active hierarchy
216  */
217 #define for_each_subsys(_root, _ss) \
218 list_for_each_entry(_ss, &_root->subsys_list, sibling)
219
220 /* for_each_active_root() allows you to iterate across the active hierarchies */
221 #define for_each_active_root(_root) \
222 list_for_each_entry(_root, &roots, root_list)
223
224 /* the list of cgroups eligible for automatic release. Protected by
225  * release_list_lock */
226 static LIST_HEAD(release_list);
227 static DEFINE_SPINLOCK(release_list_lock);
228 static void cgroup_release_agent(struct work_struct *work);
229 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
230 static void check_for_release(struct cgroup *cgrp);
231
232 /* Link structure for associating css_set objects with cgroups */
233 struct cg_cgroup_link {
234         /*
235          * List running through cg_cgroup_links associated with a
236          * cgroup, anchored on cgroup->css_sets
237          */
238         struct list_head cgrp_link_list;
239         struct cgroup *cgrp;
240         /*
241          * List running through cg_cgroup_links pointing at a
242          * single css_set object, anchored on css_set->cg_links
243          */
244         struct list_head cg_link_list;
245         struct css_set *cg;
246 };
247
248 /* The default css_set - used by init and its children prior to any
249  * hierarchies being mounted. It contains a pointer to the root state
250  * for each subsystem. Also used to anchor the list of css_sets. Not
251  * reference-counted, to improve performance when child cgroups
252  * haven't been created.
253  */
254
255 static struct css_set init_css_set;
256 static struct cg_cgroup_link init_css_set_link;
257
258 static int cgroup_init_idr(struct cgroup_subsys *ss,
259                            struct cgroup_subsys_state *css);
260
261 /* css_set_lock protects the list of css_set objects, and the
262  * chain of tasks off each css_set.  Nests outside task->alloc_lock
263  * due to cgroup_iter_start() */
264 static DEFINE_RWLOCK(css_set_lock);
265 static int css_set_count;
266
267 /*
268  * hash table for cgroup groups. This improves the performance to find
269  * an existing css_set. This hash doesn't (currently) take into
270  * account cgroups in empty hierarchies.
271  */
272 #define CSS_SET_HASH_BITS       7
273 #define CSS_SET_TABLE_SIZE      (1 << CSS_SET_HASH_BITS)
274 static struct hlist_head css_set_table[CSS_SET_TABLE_SIZE];
275
276 static struct hlist_head *css_set_hash(struct cgroup_subsys_state *css[])
277 {
278         int i;
279         int index;
280         unsigned long tmp = 0UL;
281
282         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++)
283                 tmp += (unsigned long)css[i];
284         tmp = (tmp >> 16) ^ tmp;
285
286         index = hash_long(tmp, CSS_SET_HASH_BITS);
287
288         return &css_set_table[index];
289 }
290
291 static void free_css_set_rcu(struct rcu_head *obj)
292 {
293         struct css_set *cg = container_of(obj, struct css_set, rcu_head);
294         kfree(cg);
295 }
296
297 /* We don't maintain the lists running through each css_set to its
298  * task until after the first call to cgroup_iter_start(). This
299  * reduces the fork()/exit() overhead for people who have cgroups
300  * compiled into their kernel but not actually in use */
301 static int use_task_css_set_links __read_mostly;
302
303 static void __put_css_set(struct css_set *cg, int taskexit)
304 {
305         struct cg_cgroup_link *link;
306         struct cg_cgroup_link *saved_link;
307         /*
308          * Ensure that the refcount doesn't hit zero while any readers
309          * can see it. Similar to atomic_dec_and_lock(), but for an
310          * rwlock
311          */
312         if (atomic_add_unless(&cg->refcount, -1, 1))
313                 return;
314         write_lock(&css_set_lock);
315         if (!atomic_dec_and_test(&cg->refcount)) {
316                 write_unlock(&css_set_lock);
317                 return;
318         }
319
320         /* This css_set is dead. unlink it and release cgroup refcounts */
321         hlist_del(&cg->hlist);
322         css_set_count--;
323
324         list_for_each_entry_safe(link, saved_link, &cg->cg_links,
325                                  cg_link_list) {
326                 struct cgroup *cgrp = link->cgrp;
327                 list_del(&link->cg_link_list);
328                 list_del(&link->cgrp_link_list);
329                 if (atomic_dec_and_test(&cgrp->count) &&
330                     notify_on_release(cgrp)) {
331                         if (taskexit)
332                                 set_bit(CGRP_RELEASABLE, &cgrp->flags);
333                         check_for_release(cgrp);
334                 }
335
336                 kfree(link);
337         }
338
339         write_unlock(&css_set_lock);
340         call_rcu(&cg->rcu_head, free_css_set_rcu);
341 }
342
343 /*
344  * refcounted get/put for css_set objects
345  */
346 static inline void get_css_set(struct css_set *cg)
347 {
348         atomic_inc(&cg->refcount);
349 }
350
351 static inline void put_css_set(struct css_set *cg)
352 {
353         __put_css_set(cg, 0);
354 }
355
356 static inline void put_css_set_taskexit(struct css_set *cg)
357 {
358         __put_css_set(cg, 1);
359 }
360
361 /*
362  * compare_css_sets - helper function for find_existing_css_set().
363  * @cg: candidate css_set being tested
364  * @old_cg: existing css_set for a task
365  * @new_cgrp: cgroup that's being entered by the task
366  * @template: desired set of css pointers in css_set (pre-calculated)
367  *
368  * Returns true if "cg" matches "old_cg" except for the hierarchy
369  * which "new_cgrp" belongs to, for which it should match "new_cgrp".
370  */
371 static bool compare_css_sets(struct css_set *cg,
372                              struct css_set *old_cg,
373                              struct cgroup *new_cgrp,
374                              struct cgroup_subsys_state *template[])
375 {
376         struct list_head *l1, *l2;
377
378         if (memcmp(template, cg->subsys, sizeof(cg->subsys))) {
379                 /* Not all subsystems matched */
380                 return false;
381         }
382
383         /*
384          * Compare cgroup pointers in order to distinguish between
385          * different cgroups in heirarchies with no subsystems. We
386          * could get by with just this check alone (and skip the
387          * memcmp above) but on most setups the memcmp check will
388          * avoid the need for this more expensive check on almost all
389          * candidates.
390          */
391
392         l1 = &cg->cg_links;
393         l2 = &old_cg->cg_links;
394         while (1) {
395                 struct cg_cgroup_link *cgl1, *cgl2;
396                 struct cgroup *cg1, *cg2;
397
398                 l1 = l1->next;
399                 l2 = l2->next;
400                 /* See if we reached the end - both lists are equal length. */
401                 if (l1 == &cg->cg_links) {
402                         BUG_ON(l2 != &old_cg->cg_links);
403                         break;
404                 } else {
405                         BUG_ON(l2 == &old_cg->cg_links);
406                 }
407                 /* Locate the cgroups associated with these links. */
408                 cgl1 = list_entry(l1, struct cg_cgroup_link, cg_link_list);
409                 cgl2 = list_entry(l2, struct cg_cgroup_link, cg_link_list);
410                 cg1 = cgl1->cgrp;
411                 cg2 = cgl2->cgrp;
412                 /* Hierarchies should be linked in the same order. */
413                 BUG_ON(cg1->root != cg2->root);
414
415                 /*
416                  * If this hierarchy is the hierarchy of the cgroup
417                  * that's changing, then we need to check that this
418                  * css_set points to the new cgroup; if it's any other
419                  * hierarchy, then this css_set should point to the
420                  * same cgroup as the old css_set.
421                  */
422                 if (cg1->root == new_cgrp->root) {
423                         if (cg1 != new_cgrp)
424                                 return false;
425                 } else {
426                         if (cg1 != cg2)
427                                 return false;
428                 }
429         }
430         return true;
431 }
432
433 /*
434  * find_existing_css_set() is a helper for
435  * find_css_set(), and checks to see whether an existing
436  * css_set is suitable.
437  *
438  * oldcg: the cgroup group that we're using before the cgroup
439  * transition
440  *
441  * cgrp: the cgroup that we're moving into
442  *
443  * template: location in which to build the desired set of subsystem
444  * state objects for the new cgroup group
445  */
446 static struct css_set *find_existing_css_set(
447         struct css_set *oldcg,
448         struct cgroup *cgrp,
449         struct cgroup_subsys_state *template[])
450 {
451         int i;
452         struct cgroupfs_root *root = cgrp->root;
453         struct hlist_head *hhead;
454         struct hlist_node *node;
455         struct css_set *cg;
456
457         /*
458          * Build the set of subsystem state objects that we want to see in the
459          * new css_set. while subsystems can change globally, the entries here
460          * won't change, so no need for locking.
461          */
462         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
463                 if (root->subsys_bits & (1UL << i)) {
464                         /* Subsystem is in this hierarchy. So we want
465                          * the subsystem state from the new
466                          * cgroup */
467                         template[i] = cgrp->subsys[i];
468                 } else {
469                         /* Subsystem is not in this hierarchy, so we
470                          * don't want to change the subsystem state */
471                         template[i] = oldcg->subsys[i];
472                 }
473         }
474
475         hhead = css_set_hash(template);
476         hlist_for_each_entry(cg, node, hhead, hlist) {
477                 if (!compare_css_sets(cg, oldcg, cgrp, template))
478                         continue;
479
480                 /* This css_set matches what we need */
481                 return cg;
482         }
483
484         /* No existing cgroup group matched */
485         return NULL;
486 }
487
488 static void free_cg_links(struct list_head *tmp)
489 {
490         struct cg_cgroup_link *link;
491         struct cg_cgroup_link *saved_link;
492
493         list_for_each_entry_safe(link, saved_link, tmp, cgrp_link_list) {
494                 list_del(&link->cgrp_link_list);
495                 kfree(link);
496         }
497 }
498
499 /*
500  * allocate_cg_links() allocates "count" cg_cgroup_link structures
501  * and chains them on tmp through their cgrp_link_list fields. Returns 0 on
502  * success or a negative error
503  */
504 static int allocate_cg_links(int count, struct list_head *tmp)
505 {
506         struct cg_cgroup_link *link;
507         int i;
508         INIT_LIST_HEAD(tmp);
509         for (i = 0; i < count; i++) {
510                 link = kmalloc(sizeof(*link), GFP_KERNEL);
511                 if (!link) {
512                         free_cg_links(tmp);
513                         return -ENOMEM;
514                 }
515                 list_add(&link->cgrp_link_list, tmp);
516         }
517         return 0;
518 }
519
520 /**
521  * link_css_set - a helper function to link a css_set to a cgroup
522  * @tmp_cg_links: cg_cgroup_link objects allocated by allocate_cg_links()
523  * @cg: the css_set to be linked
524  * @cgrp: the destination cgroup
525  */
526 static void link_css_set(struct list_head *tmp_cg_links,
527                          struct css_set *cg, struct cgroup *cgrp)
528 {
529         struct cg_cgroup_link *link;
530
531         BUG_ON(list_empty(tmp_cg_links));
532         link = list_first_entry(tmp_cg_links, struct cg_cgroup_link,
533                                 cgrp_link_list);
534         link->cg = cg;
535         link->cgrp = cgrp;
536         atomic_inc(&cgrp->count);
537         list_move(&link->cgrp_link_list, &cgrp->css_sets);
538         /*
539          * Always add links to the tail of the list so that the list
540          * is sorted by order of hierarchy creation
541          */
542         list_add_tail(&link->cg_link_list, &cg->cg_links);
543 }
544
545 /*
546  * find_css_set() takes an existing cgroup group and a
547  * cgroup object, and returns a css_set object that's
548  * equivalent to the old group, but with the given cgroup
549  * substituted into the appropriate hierarchy. Must be called with
550  * cgroup_mutex held
551  */
552 static struct css_set *find_css_set(
553         struct css_set *oldcg, struct cgroup *cgrp)
554 {
555         struct css_set *res;
556         struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT];
557
558         struct list_head tmp_cg_links;
559
560         struct hlist_head *hhead;
561         struct cg_cgroup_link *link;
562
563         /* First see if we already have a cgroup group that matches
564          * the desired set */
565         read_lock(&css_set_lock);
566         res = find_existing_css_set(oldcg, cgrp, template);
567         if (res)
568                 get_css_set(res);
569         read_unlock(&css_set_lock);
570
571         if (res)
572                 return res;
573
574         res = kmalloc(sizeof(*res), GFP_KERNEL);
575         if (!res)
576                 return NULL;
577
578         /* Allocate all the cg_cgroup_link objects that we'll need */
579         if (allocate_cg_links(root_count, &tmp_cg_links) < 0) {
580                 kfree(res);
581                 return NULL;
582         }
583
584         atomic_set(&res->refcount, 1);
585         INIT_LIST_HEAD(&res->cg_links);
586         INIT_LIST_HEAD(&res->tasks);
587         INIT_HLIST_NODE(&res->hlist);
588
589         /* Copy the set of subsystem state objects generated in
590          * find_existing_css_set() */
591         memcpy(res->subsys, template, sizeof(res->subsys));
592
593         write_lock(&css_set_lock);
594         /* Add reference counts and links from the new css_set. */
595         list_for_each_entry(link, &oldcg->cg_links, cg_link_list) {
596                 struct cgroup *c = link->cgrp;
597                 if (c->root == cgrp->root)
598                         c = cgrp;
599                 link_css_set(&tmp_cg_links, res, c);
600         }
601
602         BUG_ON(!list_empty(&tmp_cg_links));
603
604         css_set_count++;
605
606         /* Add this cgroup group to the hash table */
607         hhead = css_set_hash(res->subsys);
608         hlist_add_head(&res->hlist, hhead);
609
610         write_unlock(&css_set_lock);
611
612         return res;
613 }
614
615 /*
616  * Return the cgroup for "task" from the given hierarchy. Must be
617  * called with cgroup_mutex held.
618  */
619 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
620                                             struct cgroupfs_root *root)
621 {
622         struct css_set *css;
623         struct cgroup *res = NULL;
624
625         BUG_ON(!mutex_is_locked(&cgroup_mutex));
626         read_lock(&css_set_lock);
627         /*
628          * No need to lock the task - since we hold cgroup_mutex the
629          * task can't change groups, so the only thing that can happen
630          * is that it exits and its css is set back to init_css_set.
631          */
632         css = task->cgroups;
633         if (css == &init_css_set) {
634                 res = &root->top_cgroup;
635         } else {
636                 struct cg_cgroup_link *link;
637                 list_for_each_entry(link, &css->cg_links, cg_link_list) {
638                         struct cgroup *c = link->cgrp;
639                         if (c->root == root) {
640                                 res = c;
641                                 break;
642                         }
643                 }
644         }
645         read_unlock(&css_set_lock);
646         BUG_ON(!res);
647         return res;
648 }
649
650 /*
651  * There is one global cgroup mutex. We also require taking
652  * task_lock() when dereferencing a task's cgroup subsys pointers.
653  * See "The task_lock() exception", at the end of this comment.
654  *
655  * A task must hold cgroup_mutex to modify cgroups.
656  *
657  * Any task can increment and decrement the count field without lock.
658  * So in general, code holding cgroup_mutex can't rely on the count
659  * field not changing.  However, if the count goes to zero, then only
660  * cgroup_attach_task() can increment it again.  Because a count of zero
661  * means that no tasks are currently attached, therefore there is no
662  * way a task attached to that cgroup can fork (the other way to
663  * increment the count).  So code holding cgroup_mutex can safely
664  * assume that if the count is zero, it will stay zero. Similarly, if
665  * a task holds cgroup_mutex on a cgroup with zero count, it
666  * knows that the cgroup won't be removed, as cgroup_rmdir()
667  * needs that mutex.
668  *
669  * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
670  * (usually) take cgroup_mutex.  These are the two most performance
671  * critical pieces of code here.  The exception occurs on cgroup_exit(),
672  * when a task in a notify_on_release cgroup exits.  Then cgroup_mutex
673  * is taken, and if the cgroup count is zero, a usermode call made
674  * to the release agent with the name of the cgroup (path relative to
675  * the root of cgroup file system) as the argument.
676  *
677  * A cgroup can only be deleted if both its 'count' of using tasks
678  * is zero, and its list of 'children' cgroups is empty.  Since all
679  * tasks in the system use _some_ cgroup, and since there is always at
680  * least one task in the system (init, pid == 1), therefore, top_cgroup
681  * always has either children cgroups and/or using tasks.  So we don't
682  * need a special hack to ensure that top_cgroup cannot be deleted.
683  *
684  *      The task_lock() exception
685  *
686  * The need for this exception arises from the action of
687  * cgroup_attach_task(), which overwrites one tasks cgroup pointer with
688  * another.  It does so using cgroup_mutex, however there are
689  * several performance critical places that need to reference
690  * task->cgroup without the expense of grabbing a system global
691  * mutex.  Therefore except as noted below, when dereferencing or, as
692  * in cgroup_attach_task(), modifying a task'ss cgroup pointer we use
693  * task_lock(), which acts on a spinlock (task->alloc_lock) already in
694  * the task_struct routinely used for such matters.
695  *
696  * P.S.  One more locking exception.  RCU is used to guard the
697  * update of a tasks cgroup pointer by cgroup_attach_task()
698  */
699
700 /**
701  * cgroup_lock - lock out any changes to cgroup structures
702  *
703  */
704 void cgroup_lock(void)
705 {
706         mutex_lock(&cgroup_mutex);
707 }
708 EXPORT_SYMBOL_GPL(cgroup_lock);
709
710 /**
711  * cgroup_unlock - release lock on cgroup changes
712  *
713  * Undo the lock taken in a previous cgroup_lock() call.
714  */
715 void cgroup_unlock(void)
716 {
717         mutex_unlock(&cgroup_mutex);
718 }
719 EXPORT_SYMBOL_GPL(cgroup_unlock);
720
721 /*
722  * A couple of forward declarations required, due to cyclic reference loop:
723  * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
724  * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
725  * -> cgroup_mkdir.
726  */
727
728 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode);
729 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
730 static int cgroup_populate_dir(struct cgroup *cgrp);
731 static const struct inode_operations cgroup_dir_inode_operations;
732 static const struct file_operations proc_cgroupstats_operations;
733
734 static struct backing_dev_info cgroup_backing_dev_info = {
735         .name           = "cgroup",
736         .capabilities   = BDI_CAP_NO_ACCT_AND_WRITEBACK,
737 };
738
739 static int alloc_css_id(struct cgroup_subsys *ss,
740                         struct cgroup *parent, struct cgroup *child);
741
742 static struct inode *cgroup_new_inode(mode_t mode, struct super_block *sb)
743 {
744         struct inode *inode = new_inode(sb);
745
746         if (inode) {
747                 inode->i_mode = mode;
748                 inode->i_uid = current_fsuid();
749                 inode->i_gid = current_fsgid();
750                 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
751                 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
752         }
753         return inode;
754 }
755
756 /*
757  * Call subsys's pre_destroy handler.
758  * This is called before css refcnt check.
759  */
760 static int cgroup_call_pre_destroy(struct cgroup *cgrp)
761 {
762         struct cgroup_subsys *ss;
763         int ret = 0;
764
765         for_each_subsys(cgrp->root, ss)
766                 if (ss->pre_destroy) {
767                         ret = ss->pre_destroy(ss, cgrp);
768                         if (ret)
769                                 break;
770                 }
771         return ret;
772 }
773
774 static void free_cgroup_rcu(struct rcu_head *obj)
775 {
776         struct cgroup *cgrp = container_of(obj, struct cgroup, rcu_head);
777
778         kfree(cgrp);
779 }
780
781 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
782 {
783         /* is dentry a directory ? if so, kfree() associated cgroup */
784         if (S_ISDIR(inode->i_mode)) {
785                 struct cgroup *cgrp = dentry->d_fsdata;
786                 struct cgroup_subsys *ss;
787                 BUG_ON(!(cgroup_is_removed(cgrp)));
788                 /* It's possible for external users to be holding css
789                  * reference counts on a cgroup; css_put() needs to
790                  * be able to access the cgroup after decrementing
791                  * the reference count in order to know if it needs to
792                  * queue the cgroup to be handled by the release
793                  * agent */
794                 synchronize_rcu();
795
796                 mutex_lock(&cgroup_mutex);
797                 /*
798                  * Release the subsystem state objects.
799                  */
800                 for_each_subsys(cgrp->root, ss)
801                         ss->destroy(ss, cgrp);
802
803                 cgrp->root->number_of_cgroups--;
804                 mutex_unlock(&cgroup_mutex);
805
806                 /*
807                  * Drop the active superblock reference that we took when we
808                  * created the cgroup
809                  */
810                 deactivate_super(cgrp->root->sb);
811
812                 /*
813                  * if we're getting rid of the cgroup, refcount should ensure
814                  * that there are no pidlists left.
815                  */
816                 BUG_ON(!list_empty(&cgrp->pidlists));
817
818                 call_rcu(&cgrp->rcu_head, free_cgroup_rcu);
819         }
820         iput(inode);
821 }
822
823 static void remove_dir(struct dentry *d)
824 {
825         struct dentry *parent = dget(d->d_parent);
826
827         d_delete(d);
828         simple_rmdir(parent->d_inode, d);
829         dput(parent);
830 }
831
832 static void cgroup_clear_directory(struct dentry *dentry)
833 {
834         struct list_head *node;
835
836         BUG_ON(!mutex_is_locked(&dentry->d_inode->i_mutex));
837         spin_lock(&dcache_lock);
838         node = dentry->d_subdirs.next;
839         while (node != &dentry->d_subdirs) {
840                 struct dentry *d = list_entry(node, struct dentry, d_u.d_child);
841                 list_del_init(node);
842                 if (d->d_inode) {
843                         /* This should never be called on a cgroup
844                          * directory with child cgroups */
845                         BUG_ON(d->d_inode->i_mode & S_IFDIR);
846                         d = dget_locked(d);
847                         spin_unlock(&dcache_lock);
848                         d_delete(d);
849                         simple_unlink(dentry->d_inode, d);
850                         dput(d);
851                         spin_lock(&dcache_lock);
852                 }
853                 node = dentry->d_subdirs.next;
854         }
855         spin_unlock(&dcache_lock);
856 }
857
858 /*
859  * NOTE : the dentry must have been dget()'ed
860  */
861 static void cgroup_d_remove_dir(struct dentry *dentry)
862 {
863         cgroup_clear_directory(dentry);
864
865         spin_lock(&dcache_lock);
866         list_del_init(&dentry->d_u.d_child);
867         spin_unlock(&dcache_lock);
868         remove_dir(dentry);
869 }
870
871 /*
872  * A queue for waiters to do rmdir() cgroup. A tasks will sleep when
873  * cgroup->count == 0 && list_empty(&cgroup->children) && subsys has some
874  * reference to css->refcnt. In general, this refcnt is expected to goes down
875  * to zero, soon.
876  *
877  * CGRP_WAIT_ON_RMDIR flag is set under cgroup's inode->i_mutex;
878  */
879 DECLARE_WAIT_QUEUE_HEAD(cgroup_rmdir_waitq);
880
881 static void cgroup_wakeup_rmdir_waiter(struct cgroup *cgrp)
882 {
883         if (unlikely(test_and_clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags)))
884                 wake_up_all(&cgroup_rmdir_waitq);
885 }
886
887 void cgroup_exclude_rmdir(struct cgroup_subsys_state *css)
888 {
889         css_get(css);
890 }
891
892 void cgroup_release_and_wakeup_rmdir(struct cgroup_subsys_state *css)
893 {
894         cgroup_wakeup_rmdir_waiter(css->cgroup);
895         css_put(css);
896 }
897
898 /*
899  * Call with cgroup_mutex held. Drops reference counts on modules, including
900  * any duplicate ones that parse_cgroupfs_options took. If this function
901  * returns an error, no reference counts are touched.
902  */
903 static int rebind_subsystems(struct cgroupfs_root *root,
904                               unsigned long final_bits)
905 {
906         unsigned long added_bits, removed_bits;
907         struct cgroup *cgrp = &root->top_cgroup;
908         int i;
909
910         BUG_ON(!mutex_is_locked(&cgroup_mutex));
911
912         removed_bits = root->actual_subsys_bits & ~final_bits;
913         added_bits = final_bits & ~root->actual_subsys_bits;
914         /* Check that any added subsystems are currently free */
915         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
916                 unsigned long bit = 1UL << i;
917                 struct cgroup_subsys *ss = subsys[i];
918                 if (!(bit & added_bits))
919                         continue;
920                 /*
921                  * Nobody should tell us to do a subsys that doesn't exist:
922                  * parse_cgroupfs_options should catch that case and refcounts
923                  * ensure that subsystems won't disappear once selected.
924                  */
925                 BUG_ON(ss == NULL);
926                 if (ss->root != &rootnode) {
927                         /* Subsystem isn't free */
928                         return -EBUSY;
929                 }
930         }
931
932         /* Currently we don't handle adding/removing subsystems when
933          * any child cgroups exist. This is theoretically supportable
934          * but involves complex error handling, so it's being left until
935          * later */
936         if (root->number_of_cgroups > 1)
937                 return -EBUSY;
938
939         /* Process each subsystem */
940         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
941                 struct cgroup_subsys *ss = subsys[i];
942                 unsigned long bit = 1UL << i;
943                 if (bit & added_bits) {
944                         /* We're binding this subsystem to this hierarchy */
945                         BUG_ON(ss == NULL);
946                         BUG_ON(cgrp->subsys[i]);
947                         BUG_ON(!dummytop->subsys[i]);
948                         BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
949                         mutex_lock(&ss->hierarchy_mutex);
950                         cgrp->subsys[i] = dummytop->subsys[i];
951                         cgrp->subsys[i]->cgroup = cgrp;
952                         list_move(&ss->sibling, &root->subsys_list);
953                         ss->root = root;
954                         if (ss->bind)
955                                 ss->bind(ss, cgrp);
956                         mutex_unlock(&ss->hierarchy_mutex);
957                         /* refcount was already taken, and we're keeping it */
958                 } else if (bit & removed_bits) {
959                         /* We're removing this subsystem */
960                         BUG_ON(ss == NULL);
961                         BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
962                         BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
963                         mutex_lock(&ss->hierarchy_mutex);
964                         if (ss->bind)
965                                 ss->bind(ss, dummytop);
966                         dummytop->subsys[i]->cgroup = dummytop;
967                         cgrp->subsys[i] = NULL;
968                         subsys[i]->root = &rootnode;
969                         list_move(&ss->sibling, &rootnode.subsys_list);
970                         mutex_unlock(&ss->hierarchy_mutex);
971                         /* subsystem is now free - drop reference on module */
972                         module_put(ss->module);
973                 } else if (bit & final_bits) {
974                         /* Subsystem state should already exist */
975                         BUG_ON(ss == NULL);
976                         BUG_ON(!cgrp->subsys[i]);
977                         /*
978                          * a refcount was taken, but we already had one, so
979                          * drop the extra reference.
980                          */
981                         module_put(ss->module);
982 #ifdef CONFIG_MODULE_UNLOAD
983                         BUG_ON(ss->module && !module_refcount(ss->module));
984 #endif
985                 } else {
986                         /* Subsystem state shouldn't exist */
987                         BUG_ON(cgrp->subsys[i]);
988                 }
989         }
990         root->subsys_bits = root->actual_subsys_bits = final_bits;
991         synchronize_rcu();
992
993         return 0;
994 }
995
996 static int cgroup_show_options(struct seq_file *seq, struct vfsmount *vfs)
997 {
998         struct cgroupfs_root *root = vfs->mnt_sb->s_fs_info;
999         struct cgroup_subsys *ss;
1000
1001         mutex_lock(&cgroup_mutex);
1002         for_each_subsys(root, ss)
1003                 seq_printf(seq, ",%s", ss->name);
1004         if (test_bit(ROOT_NOPREFIX, &root->flags))
1005                 seq_puts(seq, ",noprefix");
1006         if (strlen(root->release_agent_path))
1007                 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1008         if (strlen(root->name))
1009                 seq_printf(seq, ",name=%s", root->name);
1010         mutex_unlock(&cgroup_mutex);
1011         return 0;
1012 }
1013
1014 struct cgroup_sb_opts {
1015         unsigned long subsys_bits;
1016         unsigned long flags;
1017         char *release_agent;
1018         char *name;
1019         /* User explicitly requested empty subsystem */
1020         bool none;
1021
1022         struct cgroupfs_root *new_root;
1023
1024 };
1025
1026 /*
1027  * Convert a hierarchy specifier into a bitmask of subsystems and flags. Call
1028  * with cgroup_mutex held to protect the subsys[] array. This function takes
1029  * refcounts on subsystems to be used, unless it returns error, in which case
1030  * no refcounts are taken.
1031  */
1032 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1033 {
1034         char *token, *o = data ?: "all";
1035         unsigned long mask = (unsigned long)-1;
1036         int i;
1037         bool module_pin_failed = false;
1038
1039         BUG_ON(!mutex_is_locked(&cgroup_mutex));
1040
1041 #ifdef CONFIG_CPUSETS
1042         mask = ~(1UL << cpuset_subsys_id);
1043 #endif
1044
1045         memset(opts, 0, sizeof(*opts));
1046
1047         while ((token = strsep(&o, ",")) != NULL) {
1048                 if (!*token)
1049                         return -EINVAL;
1050                 if (!strcmp(token, "all")) {
1051                         /* Add all non-disabled subsystems */
1052                         opts->subsys_bits = 0;
1053                         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1054                                 struct cgroup_subsys *ss = subsys[i];
1055                                 if (ss == NULL)
1056                                         continue;
1057                                 if (!ss->disabled)
1058                                         opts->subsys_bits |= 1ul << i;
1059                         }
1060                 } else if (!strcmp(token, "none")) {
1061                         /* Explicitly have no subsystems */
1062                         opts->none = true;
1063                 } else if (!strcmp(token, "noprefix")) {
1064                         set_bit(ROOT_NOPREFIX, &opts->flags);
1065                 } else if (!strncmp(token, "release_agent=", 14)) {
1066                         /* Specifying two release agents is forbidden */
1067                         if (opts->release_agent)
1068                                 return -EINVAL;
1069                         opts->release_agent =
1070                                 kstrndup(token + 14, PATH_MAX, GFP_KERNEL);
1071                         if (!opts->release_agent)
1072                                 return -ENOMEM;
1073                 } else if (!strncmp(token, "name=", 5)) {
1074                         const char *name = token + 5;
1075                         /* Can't specify an empty name */
1076                         if (!strlen(name))
1077                                 return -EINVAL;
1078                         /* Must match [\w.-]+ */
1079                         for (i = 0; i < strlen(name); i++) {
1080                                 char c = name[i];
1081                                 if (isalnum(c))
1082                                         continue;
1083                                 if ((c == '.') || (c == '-') || (c == '_'))
1084                                         continue;
1085                                 return -EINVAL;
1086                         }
1087                         /* Specifying two names is forbidden */
1088                         if (opts->name)
1089                                 return -EINVAL;
1090                         opts->name = kstrndup(name,
1091                                               MAX_CGROUP_ROOT_NAMELEN,
1092                                               GFP_KERNEL);
1093                         if (!opts->name)
1094                                 return -ENOMEM;
1095                 } else {
1096                         struct cgroup_subsys *ss;
1097                         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1098                                 ss = subsys[i];
1099                                 if (ss == NULL)
1100                                         continue;
1101                                 if (!strcmp(token, ss->name)) {
1102                                         if (!ss->disabled)
1103                                                 set_bit(i, &opts->subsys_bits);
1104                                         break;
1105                                 }
1106                         }
1107                         if (i == CGROUP_SUBSYS_COUNT)
1108                                 return -ENOENT;
1109                 }
1110         }
1111
1112         /* Consistency checks */
1113
1114         /*
1115          * Option noprefix was introduced just for backward compatibility
1116          * with the old cpuset, so we allow noprefix only if mounting just
1117          * the cpuset subsystem.
1118          */
1119         if (test_bit(ROOT_NOPREFIX, &opts->flags) &&
1120             (opts->subsys_bits & mask))
1121                 return -EINVAL;
1122
1123
1124         /* Can't specify "none" and some subsystems */
1125         if (opts->subsys_bits && opts->none)
1126                 return -EINVAL;
1127
1128         /*
1129          * We either have to specify by name or by subsystems. (So all
1130          * empty hierarchies must have a name).
1131          */
1132         if (!opts->subsys_bits && !opts->name)
1133                 return -EINVAL;
1134
1135         /*
1136          * Grab references on all the modules we'll need, so the subsystems
1137          * don't dance around before rebind_subsystems attaches them. This may
1138          * take duplicate reference counts on a subsystem that's already used,
1139          * but rebind_subsystems handles this case.
1140          */
1141         for (i = CGROUP_BUILTIN_SUBSYS_COUNT; i < CGROUP_SUBSYS_COUNT; i++) {
1142                 unsigned long bit = 1UL << i;
1143
1144                 if (!(bit & opts->subsys_bits))
1145                         continue;
1146                 if (!try_module_get(subsys[i]->module)) {
1147                         module_pin_failed = true;
1148                         break;
1149                 }
1150         }
1151         if (module_pin_failed) {
1152                 /*
1153                  * oops, one of the modules was going away. this means that we
1154                  * raced with a module_delete call, and to the user this is
1155                  * essentially a "subsystem doesn't exist" case.
1156                  */
1157                 for (i--; i >= CGROUP_BUILTIN_SUBSYS_COUNT; i--) {
1158                         /* drop refcounts only on the ones we took */
1159                         unsigned long bit = 1UL << i;
1160
1161                         if (!(bit & opts->subsys_bits))
1162                                 continue;
1163                         module_put(subsys[i]->module);
1164                 }
1165                 return -ENOENT;
1166         }
1167
1168         return 0;
1169 }
1170
1171 static void drop_parsed_module_refcounts(unsigned long subsys_bits)
1172 {
1173         int i;
1174         for (i = CGROUP_BUILTIN_SUBSYS_COUNT; i < CGROUP_SUBSYS_COUNT; i++) {
1175                 unsigned long bit = 1UL << i;
1176
1177                 if (!(bit & subsys_bits))
1178                         continue;
1179                 module_put(subsys[i]->module);
1180         }
1181 }
1182
1183 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1184 {
1185         int ret = 0;
1186         struct cgroupfs_root *root = sb->s_fs_info;
1187         struct cgroup *cgrp = &root->top_cgroup;
1188         struct cgroup_sb_opts opts;
1189
1190         lock_kernel();
1191         mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1192         mutex_lock(&cgroup_mutex);
1193
1194         /* See what subsystems are wanted */
1195         ret = parse_cgroupfs_options(data, &opts);
1196         if (ret)
1197                 goto out_unlock;
1198
1199         /* Don't allow flags or name to change at remount */
1200         if (opts.flags != root->flags ||
1201             (opts.name && strcmp(opts.name, root->name))) {
1202                 ret = -EINVAL;
1203                 drop_parsed_module_refcounts(opts.subsys_bits);
1204                 goto out_unlock;
1205         }
1206
1207         ret = rebind_subsystems(root, opts.subsys_bits);
1208         if (ret) {
1209                 drop_parsed_module_refcounts(opts.subsys_bits);
1210                 goto out_unlock;
1211         }
1212
1213         /* (re)populate subsystem files */
1214         cgroup_populate_dir(cgrp);
1215
1216         if (opts.release_agent)
1217                 strcpy(root->release_agent_path, opts.release_agent);
1218  out_unlock:
1219         kfree(opts.release_agent);
1220         kfree(opts.name);
1221         mutex_unlock(&cgroup_mutex);
1222         mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1223         unlock_kernel();
1224         return ret;
1225 }
1226
1227 static const struct super_operations cgroup_ops = {
1228         .statfs = simple_statfs,
1229         .drop_inode = generic_delete_inode,
1230         .show_options = cgroup_show_options,
1231         .remount_fs = cgroup_remount,
1232 };
1233
1234 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1235 {
1236         INIT_LIST_HEAD(&cgrp->sibling);
1237         INIT_LIST_HEAD(&cgrp->children);
1238         INIT_LIST_HEAD(&cgrp->css_sets);
1239         INIT_LIST_HEAD(&cgrp->release_list);
1240         INIT_LIST_HEAD(&cgrp->pidlists);
1241         mutex_init(&cgrp->pidlist_mutex);
1242 }
1243
1244 static void init_cgroup_root(struct cgroupfs_root *root)
1245 {
1246         struct cgroup *cgrp = &root->top_cgroup;
1247         INIT_LIST_HEAD(&root->subsys_list);
1248         INIT_LIST_HEAD(&root->root_list);
1249         root->number_of_cgroups = 1;
1250         cgrp->root = root;
1251         cgrp->top_cgroup = cgrp;
1252         init_cgroup_housekeeping(cgrp);
1253 }
1254
1255 static bool init_root_id(struct cgroupfs_root *root)
1256 {
1257         int ret = 0;
1258
1259         do {
1260                 if (!ida_pre_get(&hierarchy_ida, GFP_KERNEL))
1261                         return false;
1262                 spin_lock(&hierarchy_id_lock);
1263                 /* Try to allocate the next unused ID */
1264                 ret = ida_get_new_above(&hierarchy_ida, next_hierarchy_id,
1265                                         &root->hierarchy_id);
1266                 if (ret == -ENOSPC)
1267                         /* Try again starting from 0 */
1268                         ret = ida_get_new(&hierarchy_ida, &root->hierarchy_id);
1269                 if (!ret) {
1270                         next_hierarchy_id = root->hierarchy_id + 1;
1271                 } else if (ret != -EAGAIN) {
1272                         /* Can only get here if the 31-bit IDR is full ... */
1273                         BUG_ON(ret);
1274                 }
1275                 spin_unlock(&hierarchy_id_lock);
1276         } while (ret);
1277         return true;
1278 }
1279
1280 static int cgroup_test_super(struct super_block *sb, void *data)
1281 {
1282         struct cgroup_sb_opts *opts = data;
1283         struct cgroupfs_root *root = sb->s_fs_info;
1284
1285         /* If we asked for a name then it must match */
1286         if (opts->name && strcmp(opts->name, root->name))
1287                 return 0;
1288
1289         /*
1290          * If we asked for subsystems (or explicitly for no
1291          * subsystems) then they must match
1292          */
1293         if ((opts->subsys_bits || opts->none)
1294             && (opts->subsys_bits != root->subsys_bits))
1295                 return 0;
1296
1297         return 1;
1298 }
1299
1300 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1301 {
1302         struct cgroupfs_root *root;
1303
1304         if (!opts->subsys_bits && !opts->none)
1305                 return NULL;
1306
1307         root = kzalloc(sizeof(*root), GFP_KERNEL);
1308         if (!root)
1309                 return ERR_PTR(-ENOMEM);
1310
1311         if (!init_root_id(root)) {
1312                 kfree(root);
1313                 return ERR_PTR(-ENOMEM);
1314         }
1315         init_cgroup_root(root);
1316
1317         root->subsys_bits = opts->subsys_bits;
1318         root->flags = opts->flags;
1319         if (opts->release_agent)
1320                 strcpy(root->release_agent_path, opts->release_agent);
1321         if (opts->name)
1322                 strcpy(root->name, opts->name);
1323         return root;
1324 }
1325
1326 static void cgroup_drop_root(struct cgroupfs_root *root)
1327 {
1328         if (!root)
1329                 return;
1330
1331         BUG_ON(!root->hierarchy_id);
1332         spin_lock(&hierarchy_id_lock);
1333         ida_remove(&hierarchy_ida, root->hierarchy_id);
1334         spin_unlock(&hierarchy_id_lock);
1335         kfree(root);
1336 }
1337
1338 static int cgroup_set_super(struct super_block *sb, void *data)
1339 {
1340         int ret;
1341         struct cgroup_sb_opts *opts = data;
1342
1343         /* If we don't have a new root, we can't set up a new sb */
1344         if (!opts->new_root)
1345                 return -EINVAL;
1346
1347         BUG_ON(!opts->subsys_bits && !opts->none);
1348
1349         ret = set_anon_super(sb, NULL);
1350         if (ret)
1351                 return ret;
1352
1353         sb->s_fs_info = opts->new_root;
1354         opts->new_root->sb = sb;
1355
1356         sb->s_blocksize = PAGE_CACHE_SIZE;
1357         sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1358         sb->s_magic = CGROUP_SUPER_MAGIC;
1359         sb->s_op = &cgroup_ops;
1360
1361         return 0;
1362 }
1363
1364 static int cgroup_get_rootdir(struct super_block *sb)
1365 {
1366         struct inode *inode =
1367                 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1368         struct dentry *dentry;
1369
1370         if (!inode)
1371                 return -ENOMEM;
1372
1373         inode->i_fop = &simple_dir_operations;
1374         inode->i_op = &cgroup_dir_inode_operations;
1375         /* directories start off with i_nlink == 2 (for "." entry) */
1376         inc_nlink(inode);
1377         dentry = d_alloc_root(inode);
1378         if (!dentry) {
1379                 iput(inode);
1380                 return -ENOMEM;
1381         }
1382         sb->s_root = dentry;
1383         return 0;
1384 }
1385
1386 static int cgroup_get_sb(struct file_system_type *fs_type,
1387                          int flags, const char *unused_dev_name,
1388                          void *data, struct vfsmount *mnt)
1389 {
1390         struct cgroup_sb_opts opts;
1391         struct cgroupfs_root *root;
1392         int ret = 0;
1393         struct super_block *sb;
1394         struct cgroupfs_root *new_root;
1395
1396         /* First find the desired set of subsystems */
1397         mutex_lock(&cgroup_mutex);
1398         ret = parse_cgroupfs_options(data, &opts);
1399         mutex_unlock(&cgroup_mutex);
1400         if (ret)
1401                 goto out_err;
1402
1403         /*
1404          * Allocate a new cgroup root. We may not need it if we're
1405          * reusing an existing hierarchy.
1406          */
1407         new_root = cgroup_root_from_opts(&opts);
1408         if (IS_ERR(new_root)) {
1409                 ret = PTR_ERR(new_root);
1410                 goto drop_modules;
1411         }
1412         opts.new_root = new_root;
1413
1414         /* Locate an existing or new sb for this hierarchy */
1415         sb = sget(fs_type, cgroup_test_super, cgroup_set_super, &opts);
1416         if (IS_ERR(sb)) {
1417                 ret = PTR_ERR(sb);
1418                 cgroup_drop_root(opts.new_root);
1419                 goto drop_modules;
1420         }
1421
1422         root = sb->s_fs_info;
1423         BUG_ON(!root);
1424         if (root == opts.new_root) {
1425                 /* We used the new root structure, so this is a new hierarchy */
1426                 struct list_head tmp_cg_links;
1427                 struct cgroup *root_cgrp = &root->top_cgroup;
1428                 struct inode *inode;
1429                 struct cgroupfs_root *existing_root;
1430                 int i;
1431
1432                 BUG_ON(sb->s_root != NULL);
1433
1434                 ret = cgroup_get_rootdir(sb);
1435                 if (ret)
1436                         goto drop_new_super;
1437                 inode = sb->s_root->d_inode;
1438
1439                 mutex_lock(&inode->i_mutex);
1440                 mutex_lock(&cgroup_mutex);
1441
1442                 if (strlen(root->name)) {
1443                         /* Check for name clashes with existing mounts */
1444                         for_each_active_root(existing_root) {
1445                                 if (!strcmp(existing_root->name, root->name)) {
1446                                         ret = -EBUSY;
1447                                         mutex_unlock(&cgroup_mutex);
1448                                         mutex_unlock(&inode->i_mutex);
1449                                         goto drop_new_super;
1450                                 }
1451                         }
1452                 }
1453
1454                 /*
1455                  * We're accessing css_set_count without locking
1456                  * css_set_lock here, but that's OK - it can only be
1457                  * increased by someone holding cgroup_lock, and
1458                  * that's us. The worst that can happen is that we
1459                  * have some link structures left over
1460                  */
1461                 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
1462                 if (ret) {
1463                         mutex_unlock(&cgroup_mutex);
1464                         mutex_unlock(&inode->i_mutex);
1465                         goto drop_new_super;
1466                 }
1467
1468                 ret = rebind_subsystems(root, root->subsys_bits);
1469                 if (ret == -EBUSY) {
1470                         mutex_unlock(&cgroup_mutex);
1471                         mutex_unlock(&inode->i_mutex);
1472                         free_cg_links(&tmp_cg_links);
1473                         goto drop_new_super;
1474                 }
1475                 /*
1476                  * There must be no failure case after here, since rebinding
1477                  * takes care of subsystems' refcounts, which are explicitly
1478                  * dropped in the failure exit path.
1479                  */
1480
1481                 /* EBUSY should be the only error here */
1482                 BUG_ON(ret);
1483
1484                 list_add(&root->root_list, &roots);
1485                 root_count++;
1486
1487                 sb->s_root->d_fsdata = root_cgrp;
1488                 root->top_cgroup.dentry = sb->s_root;
1489
1490                 /* Link the top cgroup in this hierarchy into all
1491                  * the css_set objects */
1492                 write_lock(&css_set_lock);
1493                 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
1494                         struct hlist_head *hhead = &css_set_table[i];
1495                         struct hlist_node *node;
1496                         struct css_set *cg;
1497
1498                         hlist_for_each_entry(cg, node, hhead, hlist)
1499                                 link_css_set(&tmp_cg_links, cg, root_cgrp);
1500                 }
1501                 write_unlock(&css_set_lock);
1502
1503                 free_cg_links(&tmp_cg_links);
1504
1505                 BUG_ON(!list_empty(&root_cgrp->sibling));
1506                 BUG_ON(!list_empty(&root_cgrp->children));
1507                 BUG_ON(root->number_of_cgroups != 1);
1508
1509                 cgroup_populate_dir(root_cgrp);
1510                 mutex_unlock(&cgroup_mutex);
1511                 mutex_unlock(&inode->i_mutex);
1512         } else {
1513                 /*
1514                  * We re-used an existing hierarchy - the new root (if
1515                  * any) is not needed
1516                  */
1517                 cgroup_drop_root(opts.new_root);
1518                 /* no subsys rebinding, so refcounts don't change */
1519                 drop_parsed_module_refcounts(opts.subsys_bits);
1520         }
1521
1522         simple_set_mnt(mnt, sb);
1523         kfree(opts.release_agent);
1524         kfree(opts.name);
1525         return 0;
1526
1527  drop_new_super:
1528         deactivate_locked_super(sb);
1529  drop_modules:
1530         drop_parsed_module_refcounts(opts.subsys_bits);
1531  out_err:
1532         kfree(opts.release_agent);
1533         kfree(opts.name);
1534
1535         return ret;
1536 }
1537
1538 static void cgroup_kill_sb(struct super_block *sb) {
1539         struct cgroupfs_root *root = sb->s_fs_info;
1540         struct cgroup *cgrp = &root->top_cgroup;
1541         int ret;
1542         struct cg_cgroup_link *link;
1543         struct cg_cgroup_link *saved_link;
1544
1545         BUG_ON(!root);
1546
1547         BUG_ON(root->number_of_cgroups != 1);
1548         BUG_ON(!list_empty(&cgrp->children));
1549         BUG_ON(!list_empty(&cgrp->sibling));
1550
1551         mutex_lock(&cgroup_mutex);
1552
1553         /* Rebind all subsystems back to the default hierarchy */
1554         ret = rebind_subsystems(root, 0);
1555         /* Shouldn't be able to fail ... */
1556         BUG_ON(ret);
1557
1558         /*
1559          * Release all the links from css_sets to this hierarchy's
1560          * root cgroup
1561          */
1562         write_lock(&css_set_lock);
1563
1564         list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1565                                  cgrp_link_list) {
1566                 list_del(&link->cg_link_list);
1567                 list_del(&link->cgrp_link_list);
1568                 kfree(link);
1569         }
1570         write_unlock(&css_set_lock);
1571
1572         if (!list_empty(&root->root_list)) {
1573                 list_del(&root->root_list);
1574                 root_count--;
1575         }
1576
1577         mutex_unlock(&cgroup_mutex);
1578
1579         kill_litter_super(sb);
1580         cgroup_drop_root(root);
1581 }
1582
1583 static struct file_system_type cgroup_fs_type = {
1584         .name = "cgroup",
1585         .get_sb = cgroup_get_sb,
1586         .kill_sb = cgroup_kill_sb,
1587 };
1588
1589 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
1590 {
1591         return dentry->d_fsdata;
1592 }
1593
1594 static inline struct cftype *__d_cft(struct dentry *dentry)
1595 {
1596         return dentry->d_fsdata;
1597 }
1598
1599 /**
1600  * cgroup_path - generate the path of a cgroup
1601  * @cgrp: the cgroup in question
1602  * @buf: the buffer to write the path into
1603  * @buflen: the length of the buffer
1604  *
1605  * Called with cgroup_mutex held or else with an RCU-protected cgroup
1606  * reference.  Writes path of cgroup into buf.  Returns 0 on success,
1607  * -errno on error.
1608  */
1609 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1610 {
1611         char *start;
1612         struct dentry *dentry = rcu_dereference(cgrp->dentry);
1613
1614         if (!dentry || cgrp == dummytop) {
1615                 /*
1616                  * Inactive subsystems have no dentry for their root
1617                  * cgroup
1618                  */
1619                 strcpy(buf, "/");
1620                 return 0;
1621         }
1622
1623         start = buf + buflen;
1624
1625         *--start = '\0';
1626         for (;;) {
1627                 int len = dentry->d_name.len;
1628                 if ((start -= len) < buf)
1629                         return -ENAMETOOLONG;
1630                 memcpy(start, cgrp->dentry->d_name.name, len);
1631                 cgrp = cgrp->parent;
1632                 if (!cgrp)
1633                         break;
1634                 dentry = rcu_dereference(cgrp->dentry);
1635                 if (!cgrp->parent)
1636                         continue;
1637                 if (--start < buf)
1638                         return -ENAMETOOLONG;
1639                 *start = '/';
1640         }
1641         memmove(buf, start, buf + buflen - start);
1642         return 0;
1643 }
1644 EXPORT_SYMBOL_GPL(cgroup_path);
1645
1646 /**
1647  * cgroup_attach_task - attach task 'tsk' to cgroup 'cgrp'
1648  * @cgrp: the cgroup the task is attaching to
1649  * @tsk: the task to be attached
1650  *
1651  * Call holding cgroup_mutex. May take task_lock of
1652  * the task 'tsk' during call.
1653  */
1654 int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
1655 {
1656         int retval = 0;
1657         struct cgroup_subsys *ss, *failed_ss = NULL;
1658         struct cgroup *oldcgrp;
1659         struct css_set *cg;
1660         struct css_set *newcg;
1661         struct cgroupfs_root *root = cgrp->root;
1662
1663         /* Nothing to do if the task is already in that cgroup */
1664         oldcgrp = task_cgroup_from_root(tsk, root);
1665         if (cgrp == oldcgrp)
1666                 return 0;
1667
1668         for_each_subsys(root, ss) {
1669                 if (ss->can_attach) {
1670                         retval = ss->can_attach(ss, cgrp, tsk, false);
1671                         if (retval) {
1672                                 /*
1673                                  * Remember on which subsystem the can_attach()
1674                                  * failed, so that we only call cancel_attach()
1675                                  * against the subsystems whose can_attach()
1676                                  * succeeded. (See below)
1677                                  */
1678                                 failed_ss = ss;
1679                                 goto out;
1680                         }
1681                 }
1682         }
1683
1684         task_lock(tsk);
1685         cg = tsk->cgroups;
1686         get_css_set(cg);
1687         task_unlock(tsk);
1688         /*
1689          * Locate or allocate a new css_set for this task,
1690          * based on its final set of cgroups
1691          */
1692         newcg = find_css_set(cg, cgrp);
1693         put_css_set(cg);
1694         if (!newcg) {
1695                 retval = -ENOMEM;
1696                 goto out;
1697         }
1698
1699         task_lock(tsk);
1700         if (tsk->flags & PF_EXITING) {
1701                 task_unlock(tsk);
1702                 put_css_set(newcg);
1703                 retval = -ESRCH;
1704                 goto out;
1705         }
1706         rcu_assign_pointer(tsk->cgroups, newcg);
1707         task_unlock(tsk);
1708
1709         /* Update the css_set linked lists if we're using them */
1710         write_lock(&css_set_lock);
1711         if (!list_empty(&tsk->cg_list)) {
1712                 list_del(&tsk->cg_list);
1713                 list_add(&tsk->cg_list, &newcg->tasks);
1714         }
1715         write_unlock(&css_set_lock);
1716
1717         for_each_subsys(root, ss) {
1718                 if (ss->attach)
1719                         ss->attach(ss, cgrp, oldcgrp, tsk, false);
1720         }
1721         set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1722         synchronize_rcu();
1723         put_css_set(cg);
1724
1725         /*
1726          * wake up rmdir() waiter. the rmdir should fail since the cgroup
1727          * is no longer empty.
1728          */
1729         cgroup_wakeup_rmdir_waiter(cgrp);
1730 out:
1731         if (retval) {
1732                 for_each_subsys(root, ss) {
1733                         if (ss == failed_ss)
1734                                 /*
1735                                  * This subsystem was the one that failed the
1736                                  * can_attach() check earlier, so we don't need
1737                                  * to call cancel_attach() against it or any
1738                                  * remaining subsystems.
1739                                  */
1740                                 break;
1741                         if (ss->cancel_attach)
1742                                 ss->cancel_attach(ss, cgrp, tsk, false);
1743                 }
1744         }
1745         return retval;
1746 }
1747
1748 /*
1749  * Attach task with pid 'pid' to cgroup 'cgrp'. Call with cgroup_mutex
1750  * held. May take task_lock of task
1751  */
1752 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid)
1753 {
1754         struct task_struct *tsk;
1755         const struct cred *cred = current_cred(), *tcred;
1756         int ret;
1757
1758         if (pid) {
1759                 rcu_read_lock();
1760                 tsk = find_task_by_vpid(pid);
1761                 if (!tsk || tsk->flags & PF_EXITING) {
1762                         rcu_read_unlock();
1763                         return -ESRCH;
1764                 }
1765
1766                 tcred = __task_cred(tsk);
1767                 if (cred->euid &&
1768                     cred->euid != tcred->uid &&
1769                     cred->euid != tcred->suid) {
1770                         rcu_read_unlock();
1771                         return -EACCES;
1772                 }
1773                 get_task_struct(tsk);
1774                 rcu_read_unlock();
1775         } else {
1776                 tsk = current;
1777                 get_task_struct(tsk);
1778         }
1779
1780         ret = cgroup_attach_task(cgrp, tsk);
1781         put_task_struct(tsk);
1782         return ret;
1783 }
1784
1785 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
1786 {
1787         int ret;
1788         if (!cgroup_lock_live_group(cgrp))
1789                 return -ENODEV;
1790         ret = attach_task_by_pid(cgrp, pid);
1791         cgroup_unlock();
1792         return ret;
1793 }
1794
1795 /**
1796  * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
1797  * @cgrp: the cgroup to be checked for liveness
1798  *
1799  * On success, returns true; the lock should be later released with
1800  * cgroup_unlock(). On failure returns false with no lock held.
1801  */
1802 bool cgroup_lock_live_group(struct cgroup *cgrp)
1803 {
1804         mutex_lock(&cgroup_mutex);
1805         if (cgroup_is_removed(cgrp)) {
1806                 mutex_unlock(&cgroup_mutex);
1807                 return false;
1808         }
1809         return true;
1810 }
1811 EXPORT_SYMBOL_GPL(cgroup_lock_live_group);
1812
1813 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
1814                                       const char *buffer)
1815 {
1816         BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
1817         if (!cgroup_lock_live_group(cgrp))
1818                 return -ENODEV;
1819         strcpy(cgrp->root->release_agent_path, buffer);
1820         cgroup_unlock();
1821         return 0;
1822 }
1823
1824 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
1825                                      struct seq_file *seq)
1826 {
1827         if (!cgroup_lock_live_group(cgrp))
1828                 return -ENODEV;
1829         seq_puts(seq, cgrp->root->release_agent_path);
1830         seq_putc(seq, '\n');
1831         cgroup_unlock();
1832         return 0;
1833 }
1834
1835 /* A buffer size big enough for numbers or short strings */
1836 #define CGROUP_LOCAL_BUFFER_SIZE 64
1837
1838 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
1839                                 struct file *file,
1840                                 const char __user *userbuf,
1841                                 size_t nbytes, loff_t *unused_ppos)
1842 {
1843         char buffer[CGROUP_LOCAL_BUFFER_SIZE];
1844         int retval = 0;
1845         char *end;
1846
1847         if (!nbytes)
1848                 return -EINVAL;
1849         if (nbytes >= sizeof(buffer))
1850                 return -E2BIG;
1851         if (copy_from_user(buffer, userbuf, nbytes))
1852                 return -EFAULT;
1853
1854         buffer[nbytes] = 0;     /* nul-terminate */
1855         if (cft->write_u64) {
1856                 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
1857                 if (*end)
1858                         return -EINVAL;
1859                 retval = cft->write_u64(cgrp, cft, val);
1860         } else {
1861                 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
1862                 if (*end)
1863                         return -EINVAL;
1864                 retval = cft->write_s64(cgrp, cft, val);
1865         }
1866         if (!retval)
1867                 retval = nbytes;
1868         return retval;
1869 }
1870
1871 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
1872                                    struct file *file,
1873                                    const char __user *userbuf,
1874                                    size_t nbytes, loff_t *unused_ppos)
1875 {
1876         char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
1877         int retval = 0;
1878         size_t max_bytes = cft->max_write_len;
1879         char *buffer = local_buffer;
1880
1881         if (!max_bytes)
1882                 max_bytes = sizeof(local_buffer) - 1;
1883         if (nbytes >= max_bytes)
1884                 return -E2BIG;
1885         /* Allocate a dynamic buffer if we need one */
1886         if (nbytes >= sizeof(local_buffer)) {
1887                 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
1888                 if (buffer == NULL)
1889                         return -ENOMEM;
1890         }
1891         if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
1892                 retval = -EFAULT;
1893                 goto out;
1894         }
1895
1896         buffer[nbytes] = 0;     /* nul-terminate */
1897         retval = cft->write_string(cgrp, cft, strstrip(buffer));
1898         if (!retval)
1899                 retval = nbytes;
1900 out:
1901         if (buffer != local_buffer)
1902                 kfree(buffer);
1903         return retval;
1904 }
1905
1906 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
1907                                                 size_t nbytes, loff_t *ppos)
1908 {
1909         struct cftype *cft = __d_cft(file->f_dentry);
1910         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1911
1912         if (cgroup_is_removed(cgrp))
1913                 return -ENODEV;
1914         if (cft->write)
1915                 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
1916         if (cft->write_u64 || cft->write_s64)
1917                 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
1918         if (cft->write_string)
1919                 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
1920         if (cft->trigger) {
1921                 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
1922                 return ret ? ret : nbytes;
1923         }
1924         return -EINVAL;
1925 }
1926
1927 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
1928                                struct file *file,
1929                                char __user *buf, size_t nbytes,
1930                                loff_t *ppos)
1931 {
1932         char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1933         u64 val = cft->read_u64(cgrp, cft);
1934         int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
1935
1936         return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1937 }
1938
1939 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
1940                                struct file *file,
1941                                char __user *buf, size_t nbytes,
1942                                loff_t *ppos)
1943 {
1944         char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1945         s64 val = cft->read_s64(cgrp, cft);
1946         int len = sprintf(tmp, "%lld\n", (long long) val);
1947
1948         return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1949 }
1950
1951 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
1952                                    size_t nbytes, loff_t *ppos)
1953 {
1954         struct cftype *cft = __d_cft(file->f_dentry);
1955         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1956
1957         if (cgroup_is_removed(cgrp))
1958                 return -ENODEV;
1959
1960         if (cft->read)
1961                 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
1962         if (cft->read_u64)
1963                 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
1964         if (cft->read_s64)
1965                 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
1966         return -EINVAL;
1967 }
1968
1969 /*
1970  * seqfile ops/methods for returning structured data. Currently just
1971  * supports string->u64 maps, but can be extended in future.
1972  */
1973
1974 struct cgroup_seqfile_state {
1975         struct cftype *cft;
1976         struct cgroup *cgroup;
1977 };
1978
1979 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
1980 {
1981         struct seq_file *sf = cb->state;
1982         return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
1983 }
1984
1985 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
1986 {
1987         struct cgroup_seqfile_state *state = m->private;
1988         struct cftype *cft = state->cft;
1989         if (cft->read_map) {
1990                 struct cgroup_map_cb cb = {
1991                         .fill = cgroup_map_add,
1992                         .state = m,
1993                 };
1994                 return cft->read_map(state->cgroup, cft, &cb);
1995         }
1996         return cft->read_seq_string(state->cgroup, cft, m);
1997 }
1998
1999 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
2000 {
2001         struct seq_file *seq = file->private_data;
2002         kfree(seq->private);
2003         return single_release(inode, file);
2004 }
2005
2006 static const struct file_operations cgroup_seqfile_operations = {
2007         .read = seq_read,
2008         .write = cgroup_file_write,
2009         .llseek = seq_lseek,
2010         .release = cgroup_seqfile_release,
2011 };
2012
2013 static int cgroup_file_open(struct inode *inode, struct file *file)
2014 {
2015         int err;
2016         struct cftype *cft;
2017
2018         err = generic_file_open(inode, file);
2019         if (err)
2020                 return err;
2021         cft = __d_cft(file->f_dentry);
2022
2023         if (cft->read_map || cft->read_seq_string) {
2024                 struct cgroup_seqfile_state *state =
2025                         kzalloc(sizeof(*state), GFP_USER);
2026                 if (!state)
2027                         return -ENOMEM;
2028                 state->cft = cft;
2029                 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
2030                 file->f_op = &cgroup_seqfile_operations;
2031                 err = single_open(file, cgroup_seqfile_show, state);
2032                 if (err < 0)
2033                         kfree(state);
2034         } else if (cft->open)
2035                 err = cft->open(inode, file);
2036         else
2037                 err = 0;
2038
2039         return err;
2040 }
2041
2042 static int cgroup_file_release(struct inode *inode, struct file *file)
2043 {
2044         struct cftype *cft = __d_cft(file->f_dentry);
2045         if (cft->release)
2046                 return cft->release(inode, file);
2047         return 0;
2048 }
2049
2050 /*
2051  * cgroup_rename - Only allow simple rename of directories in place.
2052  */
2053 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2054                             struct inode *new_dir, struct dentry *new_dentry)
2055 {
2056         if (!S_ISDIR(old_dentry->d_inode->i_mode))
2057                 return -ENOTDIR;
2058         if (new_dentry->d_inode)
2059                 return -EEXIST;
2060         if (old_dir != new_dir)
2061                 return -EIO;
2062         return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2063 }
2064
2065 static const struct file_operations cgroup_file_operations = {
2066         .read = cgroup_file_read,
2067         .write = cgroup_file_write,
2068         .llseek = generic_file_llseek,
2069         .open = cgroup_file_open,
2070         .release = cgroup_file_release,
2071 };
2072
2073 static const struct inode_operations cgroup_dir_inode_operations = {
2074         .lookup = simple_lookup,
2075         .mkdir = cgroup_mkdir,
2076         .rmdir = cgroup_rmdir,
2077         .rename = cgroup_rename,
2078 };
2079
2080 static int cgroup_create_file(struct dentry *dentry, mode_t mode,
2081                                 struct super_block *sb)
2082 {
2083         static const struct dentry_operations cgroup_dops = {
2084                 .d_iput = cgroup_diput,
2085         };
2086
2087         struct inode *inode;
2088
2089         if (!dentry)
2090                 return -ENOENT;
2091         if (dentry->d_inode)
2092                 return -EEXIST;
2093
2094         inode = cgroup_new_inode(mode, sb);
2095         if (!inode)
2096                 return -ENOMEM;
2097
2098         if (S_ISDIR(mode)) {
2099                 inode->i_op = &cgroup_dir_inode_operations;
2100                 inode->i_fop = &simple_dir_operations;
2101
2102                 /* start off with i_nlink == 2 (for "." entry) */
2103                 inc_nlink(inode);
2104
2105                 /* start with the directory inode held, so that we can
2106                  * populate it without racing with another mkdir */
2107                 mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
2108         } else if (S_ISREG(mode)) {
2109                 inode->i_size = 0;
2110                 inode->i_fop = &cgroup_file_operations;
2111         }
2112         dentry->d_op = &cgroup_dops;
2113         d_instantiate(dentry, inode);
2114         dget(dentry);   /* Extra count - pin the dentry in core */
2115         return 0;
2116 }
2117
2118 /*
2119  * cgroup_create_dir - create a directory for an object.
2120  * @cgrp: the cgroup we create the directory for. It must have a valid
2121  *        ->parent field. And we are going to fill its ->dentry field.
2122  * @dentry: dentry of the new cgroup
2123  * @mode: mode to set on new directory.
2124  */
2125 static int cgroup_create_dir(struct cgroup *cgrp, struct dentry *dentry,
2126                                 mode_t mode)
2127 {
2128         struct dentry *parent;
2129         int error = 0;
2130
2131         parent = cgrp->parent->dentry;
2132         error = cgroup_create_file(dentry, S_IFDIR | mode, cgrp->root->sb);
2133         if (!error) {
2134                 dentry->d_fsdata = cgrp;
2135                 inc_nlink(parent->d_inode);
2136                 rcu_assign_pointer(cgrp->dentry, dentry);
2137                 dget(dentry);
2138         }
2139         dput(dentry);
2140
2141         return error;
2142 }
2143
2144 /**
2145  * cgroup_file_mode - deduce file mode of a control file
2146  * @cft: the control file in question
2147  *
2148  * returns cft->mode if ->mode is not 0
2149  * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2150  * returns S_IRUGO if it has only a read handler
2151  * returns S_IWUSR if it has only a write hander
2152  */
2153 static mode_t cgroup_file_mode(const struct cftype *cft)
2154 {
2155         mode_t mode = 0;
2156
2157         if (cft->mode)
2158                 return cft->mode;
2159
2160         if (cft->read || cft->read_u64 || cft->read_s64 ||
2161             cft->read_map || cft->read_seq_string)
2162                 mode |= S_IRUGO;
2163
2164         if (cft->write || cft->write_u64 || cft->write_s64 ||
2165             cft->write_string || cft->trigger)
2166                 mode |= S_IWUSR;
2167
2168         return mode;
2169 }
2170
2171 int cgroup_add_file(struct cgroup *cgrp,
2172                        struct cgroup_subsys *subsys,
2173                        const struct cftype *cft)
2174 {
2175         struct dentry *dir = cgrp->dentry;
2176         struct dentry *dentry;
2177         int error;
2178         mode_t mode;
2179
2180         char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2181         if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) {
2182                 strcpy(name, subsys->name);
2183                 strcat(name, ".");
2184         }
2185         strcat(name, cft->name);
2186         BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2187         dentry = lookup_one_len(name, dir, strlen(name));
2188         if (!IS_ERR(dentry)) {
2189                 mode = cgroup_file_mode(cft);
2190                 error = cgroup_create_file(dentry, mode | S_IFREG,
2191                                                 cgrp->root->sb);
2192                 if (!error)
2193                         dentry->d_fsdata = (void *)cft;
2194                 dput(dentry);
2195         } else
2196                 error = PTR_ERR(dentry);
2197         return error;
2198 }
2199 EXPORT_SYMBOL_GPL(cgroup_add_file);
2200
2201 int cgroup_add_files(struct cgroup *cgrp,
2202                         struct cgroup_subsys *subsys,
2203                         const struct cftype cft[],
2204                         int count)
2205 {
2206         int i, err;
2207         for (i = 0; i < count; i++) {
2208                 err = cgroup_add_file(cgrp, subsys, &cft[i]);
2209                 if (err)
2210                         return err;
2211         }
2212         return 0;
2213 }
2214 EXPORT_SYMBOL_GPL(cgroup_add_files);
2215
2216 /**
2217  * cgroup_task_count - count the number of tasks in a cgroup.
2218  * @cgrp: the cgroup in question
2219  *
2220  * Return the number of tasks in the cgroup.
2221  */
2222 int cgroup_task_count(const struct cgroup *cgrp)
2223 {
2224         int count = 0;
2225         struct cg_cgroup_link *link;
2226
2227         read_lock(&css_set_lock);
2228         list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
2229                 count += atomic_read(&link->cg->refcount);
2230         }
2231         read_unlock(&css_set_lock);
2232         return count;
2233 }
2234
2235 /*
2236  * Advance a list_head iterator.  The iterator should be positioned at
2237  * the start of a css_set
2238  */
2239 static void cgroup_advance_iter(struct cgroup *cgrp,
2240                                 struct cgroup_iter *it)
2241 {
2242         struct list_head *l = it->cg_link;
2243         struct cg_cgroup_link *link;
2244         struct css_set *cg;
2245
2246         /* Advance to the next non-empty css_set */
2247         do {
2248                 l = l->next;
2249                 if (l == &cgrp->css_sets) {
2250                         it->cg_link = NULL;
2251                         return;
2252                 }
2253                 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
2254                 cg = link->cg;
2255         } while (list_empty(&cg->tasks));
2256         it->cg_link = l;
2257         it->task = cg->tasks.next;
2258 }
2259
2260 /*
2261  * To reduce the fork() overhead for systems that are not actually
2262  * using their cgroups capability, we don't maintain the lists running
2263  * through each css_set to its tasks until we see the list actually
2264  * used - in other words after the first call to cgroup_iter_start().
2265  *
2266  * The tasklist_lock is not held here, as do_each_thread() and
2267  * while_each_thread() are protected by RCU.
2268  */
2269 static void cgroup_enable_task_cg_lists(void)
2270 {
2271         struct task_struct *p, *g;
2272         write_lock(&css_set_lock);
2273         use_task_css_set_links = 1;
2274         do_each_thread(g, p) {
2275                 task_lock(p);
2276                 /*
2277                  * We should check if the process is exiting, otherwise
2278                  * it will race with cgroup_exit() in that the list
2279                  * entry won't be deleted though the process has exited.
2280                  */
2281                 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2282                         list_add(&p->cg_list, &p->cgroups->tasks);
2283                 task_unlock(p);
2284         } while_each_thread(g, p);
2285         write_unlock(&css_set_lock);
2286 }
2287
2288 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
2289 {
2290         /*
2291          * The first time anyone tries to iterate across a cgroup,
2292          * we need to enable the list linking each css_set to its
2293          * tasks, and fix up all existing tasks.
2294          */
2295         if (!use_task_css_set_links)
2296                 cgroup_enable_task_cg_lists();
2297
2298         read_lock(&css_set_lock);
2299         it->cg_link = &cgrp->css_sets;
2300         cgroup_advance_iter(cgrp, it);
2301 }
2302
2303 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
2304                                         struct cgroup_iter *it)
2305 {
2306         struct task_struct *res;
2307         struct list_head *l = it->task;
2308         struct cg_cgroup_link *link;
2309
2310         /* If the iterator cg is NULL, we have no tasks */
2311         if (!it->cg_link)
2312                 return NULL;
2313         res = list_entry(l, struct task_struct, cg_list);
2314         /* Advance iterator to find next entry */
2315         l = l->next;
2316         link = list_entry(it->cg_link, struct cg_cgroup_link, cgrp_link_list);
2317         if (l == &link->cg->tasks) {
2318                 /* We reached the end of this task list - move on to
2319                  * the next cg_cgroup_link */
2320                 cgroup_advance_iter(cgrp, it);
2321         } else {
2322                 it->task = l;
2323         }
2324         return res;
2325 }
2326
2327 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
2328 {
2329         read_unlock(&css_set_lock);
2330 }
2331
2332 static inline int started_after_time(struct task_struct *t1,
2333                                      struct timespec *time,
2334                                      struct task_struct *t2)
2335 {
2336         int start_diff = timespec_compare(&t1->start_time, time);
2337         if (start_diff > 0) {
2338                 return 1;
2339         } else if (start_diff < 0) {
2340                 return 0;
2341         } else {
2342                 /*
2343                  * Arbitrarily, if two processes started at the same
2344                  * time, we'll say that the lower pointer value
2345                  * started first. Note that t2 may have exited by now
2346                  * so this may not be a valid pointer any longer, but
2347                  * that's fine - it still serves to distinguish
2348                  * between two tasks started (effectively) simultaneously.
2349                  */
2350                 return t1 > t2;
2351         }
2352 }
2353
2354 /*
2355  * This function is a callback from heap_insert() and is used to order
2356  * the heap.
2357  * In this case we order the heap in descending task start time.
2358  */
2359 static inline int started_after(void *p1, void *p2)
2360 {
2361         struct task_struct *t1 = p1;
2362         struct task_struct *t2 = p2;
2363         return started_after_time(t1, &t2->start_time, t2);
2364 }
2365
2366 /**
2367  * cgroup_scan_tasks - iterate though all the tasks in a cgroup
2368  * @scan: struct cgroup_scanner containing arguments for the scan
2369  *
2370  * Arguments include pointers to callback functions test_task() and
2371  * process_task().
2372  * Iterate through all the tasks in a cgroup, calling test_task() for each,
2373  * and if it returns true, call process_task() for it also.
2374  * The test_task pointer may be NULL, meaning always true (select all tasks).
2375  * Effectively duplicates cgroup_iter_{start,next,end}()
2376  * but does not lock css_set_lock for the call to process_task().
2377  * The struct cgroup_scanner may be embedded in any structure of the caller's
2378  * creation.
2379  * It is guaranteed that process_task() will act on every task that
2380  * is a member of the cgroup for the duration of this call. This
2381  * function may or may not call process_task() for tasks that exit
2382  * or move to a different cgroup during the call, or are forked or
2383  * move into the cgroup during the call.
2384  *
2385  * Note that test_task() may be called with locks held, and may in some
2386  * situations be called multiple times for the same task, so it should
2387  * be cheap.
2388  * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
2389  * pre-allocated and will be used for heap operations (and its "gt" member will
2390  * be overwritten), else a temporary heap will be used (allocation of which
2391  * may cause this function to fail).
2392  */
2393 int cgroup_scan_tasks(struct cgroup_scanner *scan)
2394 {
2395         int retval, i;
2396         struct cgroup_iter it;
2397         struct task_struct *p, *dropped;
2398         /* Never dereference latest_task, since it's not refcounted */
2399         struct task_struct *latest_task = NULL;
2400         struct ptr_heap tmp_heap;
2401         struct ptr_heap *heap;
2402         struct timespec latest_time = { 0, 0 };
2403
2404         if (scan->heap) {
2405                 /* The caller supplied our heap and pre-allocated its memory */
2406                 heap = scan->heap;
2407                 heap->gt = &started_after;
2408         } else {
2409                 /* We need to allocate our own heap memory */
2410                 heap = &tmp_heap;
2411                 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
2412                 if (retval)
2413                         /* cannot allocate the heap */
2414                         return retval;
2415         }
2416
2417  again:
2418         /*
2419          * Scan tasks in the cgroup, using the scanner's "test_task" callback
2420          * to determine which are of interest, and using the scanner's
2421          * "process_task" callback to process any of them that need an update.
2422          * Since we don't want to hold any locks during the task updates,
2423          * gather tasks to be processed in a heap structure.
2424          * The heap is sorted by descending task start time.
2425          * If the statically-sized heap fills up, we overflow tasks that
2426          * started later, and in future iterations only consider tasks that
2427          * started after the latest task in the previous pass. This
2428          * guarantees forward progress and that we don't miss any tasks.
2429          */
2430         heap->size = 0;
2431         cgroup_iter_start(scan->cg, &it);
2432         while ((p = cgroup_iter_next(scan->cg, &it))) {
2433                 /*
2434                  * Only affect tasks that qualify per the caller's callback,
2435                  * if he provided one
2436                  */
2437                 if (scan->test_task && !scan->test_task(p, scan))
2438                         continue;
2439                 /*
2440                  * Only process tasks that started after the last task
2441                  * we processed
2442                  */
2443                 if (!started_after_time(p, &latest_time, latest_task))
2444                         continue;
2445                 dropped = heap_insert(heap, p);
2446                 if (dropped == NULL) {
2447                         /*
2448                          * The new task was inserted; the heap wasn't
2449                          * previously full
2450                          */
2451                         get_task_struct(p);
2452                 } else if (dropped != p) {
2453                         /*
2454                          * The new task was inserted, and pushed out a
2455                          * different task
2456                          */
2457                         get_task_struct(p);
2458                         put_task_struct(dropped);
2459                 }
2460                 /*
2461                  * Else the new task was newer than anything already in
2462                  * the heap and wasn't inserted
2463                  */
2464         }
2465         cgroup_iter_end(scan->cg, &it);
2466
2467         if (heap->size) {
2468                 for (i = 0; i < heap->size; i++) {
2469                         struct task_struct *q = heap->ptrs[i];
2470                         if (i == 0) {
2471                                 latest_time = q->start_time;
2472                                 latest_task = q;
2473                         }
2474                         /* Process the task per the caller's callback */
2475                         scan->process_task(q, scan);
2476                         put_task_struct(q);
2477                 }
2478                 /*
2479                  * If we had to process any tasks at all, scan again
2480                  * in case some of them were in the middle of forking
2481                  * children that didn't get processed.
2482                  * Not the most efficient way to do it, but it avoids
2483                  * having to take callback_mutex in the fork path
2484                  */
2485                 goto again;
2486         }
2487         if (heap == &tmp_heap)
2488                 heap_free(&tmp_heap);
2489         return 0;
2490 }
2491
2492 /*
2493  * Stuff for reading the 'tasks'/'procs' files.
2494  *
2495  * Reading this file can return large amounts of data if a cgroup has
2496  * *lots* of attached tasks. So it may need several calls to read(),
2497  * but we cannot guarantee that the information we produce is correct
2498  * unless we produce it entirely atomically.
2499  *
2500  */
2501
2502 /*
2503  * The following two functions "fix" the issue where there are more pids
2504  * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
2505  * TODO: replace with a kernel-wide solution to this problem
2506  */
2507 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
2508 static void *pidlist_allocate(int count)
2509 {
2510         if (PIDLIST_TOO_LARGE(count))
2511                 return vmalloc(count * sizeof(pid_t));
2512         else
2513                 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
2514 }
2515 static void pidlist_free(void *p)
2516 {
2517         if (is_vmalloc_addr(p))
2518                 vfree(p);
2519         else
2520                 kfree(p);
2521 }
2522 static void *pidlist_resize(void *p, int newcount)
2523 {
2524         void *newlist;
2525         /* note: if new alloc fails, old p will still be valid either way */
2526         if (is_vmalloc_addr(p)) {
2527                 newlist = vmalloc(newcount * sizeof(pid_t));
2528                 if (!newlist)
2529                         return NULL;
2530                 memcpy(newlist, p, newcount * sizeof(pid_t));
2531                 vfree(p);
2532         } else {
2533                 newlist = krealloc(p, newcount * sizeof(pid_t), GFP_KERNEL);
2534         }
2535         return newlist;
2536 }
2537
2538 /*
2539  * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
2540  * If the new stripped list is sufficiently smaller and there's enough memory
2541  * to allocate a new buffer, will let go of the unneeded memory. Returns the
2542  * number of unique elements.
2543  */
2544 /* is the size difference enough that we should re-allocate the array? */
2545 #define PIDLIST_REALLOC_DIFFERENCE(old, new) ((old) - PAGE_SIZE >= (new))
2546 static int pidlist_uniq(pid_t **p, int length)
2547 {
2548         int src, dest = 1;
2549         pid_t *list = *p;
2550         pid_t *newlist;
2551
2552         /*
2553          * we presume the 0th element is unique, so i starts at 1. trivial
2554          * edge cases first; no work needs to be done for either
2555          */
2556         if (length == 0 || length == 1)
2557                 return length;
2558         /* src and dest walk down the list; dest counts unique elements */
2559         for (src = 1; src < length; src++) {
2560                 /* find next unique element */
2561                 while (list[src] == list[src-1]) {
2562                         src++;
2563                         if (src == length)
2564                                 goto after;
2565                 }
2566                 /* dest always points to where the next unique element goes */
2567                 list[dest] = list[src];
2568                 dest++;
2569         }
2570 after:
2571         /*
2572          * if the length difference is large enough, we want to allocate a
2573          * smaller buffer to save memory. if this fails due to out of memory,
2574          * we'll just stay with what we've got.
2575          */
2576         if (PIDLIST_REALLOC_DIFFERENCE(length, dest)) {
2577                 newlist = pidlist_resize(list, dest);
2578                 if (newlist)
2579                         *p = newlist;
2580         }
2581         return dest;
2582 }
2583
2584 static int cmppid(const void *a, const void *b)
2585 {
2586         return *(pid_t *)a - *(pid_t *)b;
2587 }
2588
2589 /*
2590  * find the appropriate pidlist for our purpose (given procs vs tasks)
2591  * returns with the lock on that pidlist already held, and takes care
2592  * of the use count, or returns NULL with no locks held if we're out of
2593  * memory.
2594  */
2595 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
2596                                                   enum cgroup_filetype type)
2597 {
2598         struct cgroup_pidlist *l;
2599         /* don't need task_nsproxy() if we're looking at ourself */
2600         struct pid_namespace *ns = get_pid_ns(current->nsproxy->pid_ns);
2601         /*
2602          * We can't drop the pidlist_mutex before taking the l->mutex in case
2603          * the last ref-holder is trying to remove l from the list at the same
2604          * time. Holding the pidlist_mutex precludes somebody taking whichever
2605          * list we find out from under us - compare release_pid_array().
2606          */
2607         mutex_lock(&cgrp->pidlist_mutex);
2608         list_for_each_entry(l, &cgrp->pidlists, links) {
2609                 if (l->key.type == type && l->key.ns == ns) {
2610                         /* found a matching list - drop the extra refcount */
2611                         put_pid_ns(ns);
2612                         /* make sure l doesn't vanish out from under us */
2613                         down_write(&l->mutex);
2614                         mutex_unlock(&cgrp->pidlist_mutex);
2615                         return l;
2616                 }
2617         }
2618         /* entry not found; create a new one */
2619         l = kmalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
2620         if (!l) {
2621                 mutex_unlock(&cgrp->pidlist_mutex);
2622                 put_pid_ns(ns);
2623                 return l;
2624         }
2625         init_rwsem(&l->mutex);
2626         down_write(&l->mutex);
2627         l->key.type = type;
2628         l->key.ns = ns;
2629         l->use_count = 0; /* don't increment here */
2630         l->list = NULL;
2631         l->owner = cgrp;
2632         list_add(&l->links, &cgrp->pidlists);
2633         mutex_unlock(&cgrp->pidlist_mutex);
2634         return l;
2635 }
2636
2637 /*
2638  * Load a cgroup's pidarray with either procs' tgids or tasks' pids
2639  */
2640 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
2641                               struct cgroup_pidlist **lp)
2642 {
2643         pid_t *array;
2644         int length;
2645         int pid, n = 0; /* used for populating the array */
2646         struct cgroup_iter it;
2647         struct task_struct *tsk;
2648         struct cgroup_pidlist *l;
2649
2650         /*
2651          * If cgroup gets more users after we read count, we won't have
2652          * enough space - tough.  This race is indistinguishable to the
2653          * caller from the case that the additional cgroup users didn't
2654          * show up until sometime later on.
2655          */
2656         length = cgroup_task_count(cgrp);
2657         array = pidlist_allocate(length);
2658         if (!array)
2659                 return -ENOMEM;
2660         /* now, populate the array */
2661         cgroup_iter_start(cgrp, &it);
2662         while ((tsk = cgroup_iter_next(cgrp, &it))) {
2663                 if (unlikely(n == length))
2664                         break;
2665                 /* get tgid or pid for procs or tasks file respectively */
2666                 if (type == CGROUP_FILE_PROCS)
2667                         pid = task_tgid_vnr(tsk);
2668                 else
2669                         pid = task_pid_vnr(tsk);
2670                 if (pid > 0) /* make sure to only use valid results */
2671                         array[n++] = pid;
2672         }
2673         cgroup_iter_end(cgrp, &it);
2674         length = n;
2675         /* now sort & (if procs) strip out duplicates */
2676         sort(array, length, sizeof(pid_t), cmppid, NULL);
2677         if (type == CGROUP_FILE_PROCS)
2678                 length = pidlist_uniq(&array, length);
2679         l = cgroup_pidlist_find(cgrp, type);
2680         if (!l) {
2681                 pidlist_free(array);
2682                 return -ENOMEM;
2683         }
2684         /* store array, freeing old if necessary - lock already held */
2685         pidlist_free(l->list);
2686         l->list = array;
2687         l->length = length;
2688         l->use_count++;
2689         up_write(&l->mutex);
2690         *lp = l;
2691         return 0;
2692 }
2693
2694 /**
2695  * cgroupstats_build - build and fill cgroupstats
2696  * @stats: cgroupstats to fill information into
2697  * @dentry: A dentry entry belonging to the cgroup for which stats have
2698  * been requested.
2699  *
2700  * Build and fill cgroupstats so that taskstats can export it to user
2701  * space.
2702  */
2703 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
2704 {
2705         int ret = -EINVAL;
2706         struct cgroup *cgrp;
2707         struct cgroup_iter it;
2708         struct task_struct *tsk;
2709
2710         /*
2711          * Validate dentry by checking the superblock operations,
2712          * and make sure it's a directory.
2713          */
2714         if (dentry->d_sb->s_op != &cgroup_ops ||
2715             !S_ISDIR(dentry->d_inode->i_mode))
2716                  goto err;
2717
2718         ret = 0;
2719         cgrp = dentry->d_fsdata;
2720
2721         cgroup_iter_start(cgrp, &it);
2722         while ((tsk = cgroup_iter_next(cgrp, &it))) {
2723                 switch (tsk->state) {
2724                 case TASK_RUNNING:
2725                         stats->nr_running++;
2726                         break;
2727                 case TASK_INTERRUPTIBLE:
2728                         stats->nr_sleeping++;
2729                         break;
2730                 case TASK_UNINTERRUPTIBLE:
2731                         stats->nr_uninterruptible++;
2732                         break;
2733                 case TASK_STOPPED:
2734                         stats->nr_stopped++;
2735                         break;
2736                 default:
2737                         if (delayacct_is_task_waiting_on_io(tsk))
2738                                 stats->nr_io_wait++;
2739                         break;
2740                 }
2741         }
2742         cgroup_iter_end(cgrp, &it);
2743
2744 err:
2745         return ret;
2746 }
2747
2748
2749 /*
2750  * seq_file methods for the tasks/procs files. The seq_file position is the
2751  * next pid to display; the seq_file iterator is a pointer to the pid
2752  * in the cgroup->l->list array.
2753  */
2754
2755 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
2756 {
2757         /*
2758          * Initially we receive a position value that corresponds to
2759          * one more than the last pid shown (or 0 on the first call or
2760          * after a seek to the start). Use a binary-search to find the
2761          * next pid to display, if any
2762          */
2763         struct cgroup_pidlist *l = s->private;
2764         int index = 0, pid = *pos;
2765         int *iter;
2766
2767         down_read(&l->mutex);
2768         if (pid) {
2769                 int end = l->length;
2770
2771                 while (index < end) {
2772                         int mid = (index + end) / 2;
2773                         if (l->list[mid] == pid) {
2774                                 index = mid;
2775                                 break;
2776                         } else if (l->list[mid] <= pid)
2777                                 index = mid + 1;
2778                         else
2779                                 end = mid;
2780                 }
2781         }
2782         /* If we're off the end of the array, we're done */
2783         if (index >= l->length)
2784                 return NULL;
2785         /* Update the abstract position to be the actual pid that we found */
2786         iter = l->list + index;
2787         *pos = *iter;
2788         return iter;
2789 }
2790
2791 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
2792 {
2793         struct cgroup_pidlist *l = s->private;
2794         up_read(&l->mutex);
2795 }
2796
2797 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
2798 {
2799         struct cgroup_pidlist *l = s->private;
2800         pid_t *p = v;
2801         pid_t *end = l->list + l->length;
2802         /*
2803          * Advance to the next pid in the array. If this goes off the
2804          * end, we're done
2805          */
2806         p++;
2807         if (p >= end) {
2808                 return NULL;
2809         } else {
2810                 *pos = *p;
2811                 return p;
2812         }
2813 }
2814
2815 static int cgroup_pidlist_show(struct seq_file *s, void *v)
2816 {
2817         return seq_printf(s, "%d\n", *(int *)v);
2818 }
2819
2820 /*
2821  * seq_operations functions for iterating on pidlists through seq_file -
2822  * independent of whether it's tasks or procs
2823  */
2824 static const struct seq_operations cgroup_pidlist_seq_operations = {
2825         .start = cgroup_pidlist_start,
2826         .stop = cgroup_pidlist_stop,
2827         .next = cgroup_pidlist_next,
2828         .show = cgroup_pidlist_show,
2829 };
2830
2831 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
2832 {
2833         /*
2834          * the case where we're the last user of this particular pidlist will
2835          * have us remove it from the cgroup's list, which entails taking the
2836          * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
2837          * pidlist_mutex, we have to take pidlist_mutex first.
2838          */
2839         mutex_lock(&l->owner->pidlist_mutex);
2840         down_write(&l->mutex);
2841         BUG_ON(!l->use_count);
2842         if (!--l->use_count) {
2843                 /* we're the last user if refcount is 0; remove and free */
2844                 list_del(&l->links);
2845                 mutex_unlock(&l->owner->pidlist_mutex);
2846                 pidlist_free(l->list);
2847                 put_pid_ns(l->key.ns);
2848                 up_write(&l->mutex);
2849                 kfree(l);
2850                 return;
2851         }
2852         mutex_unlock(&l->owner->pidlist_mutex);
2853         up_write(&l->mutex);
2854 }
2855
2856 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
2857 {
2858         struct cgroup_pidlist *l;
2859         if (!(file->f_mode & FMODE_READ))
2860                 return 0;
2861         /*
2862          * the seq_file will only be initialized if the file was opened for
2863          * reading; hence we check if it's not null only in that case.
2864          */
2865         l = ((struct seq_file *)file->private_data)->private;
2866         cgroup_release_pid_array(l);
2867         return seq_release(inode, file);
2868 }
2869
2870 static const struct file_operations cgroup_pidlist_operations = {
2871         .read = seq_read,
2872         .llseek = seq_lseek,
2873         .write = cgroup_file_write,
2874         .release = cgroup_pidlist_release,
2875 };
2876
2877 /*
2878  * The following functions handle opens on a file that displays a pidlist
2879  * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
2880  * in the cgroup.
2881  */
2882 /* helper function for the two below it */
2883 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
2884 {
2885         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2886         struct cgroup_pidlist *l;
2887         int retval;
2888
2889         /* Nothing to do for write-only files */
2890         if (!(file->f_mode & FMODE_READ))
2891                 return 0;
2892
2893         /* have the array populated */
2894         retval = pidlist_array_load(cgrp, type, &l);
2895         if (retval)
2896                 return retval;
2897         /* configure file information */
2898         file->f_op = &cgroup_pidlist_operations;
2899
2900         retval = seq_open(file, &cgroup_pidlist_seq_operations);
2901         if (retval) {
2902                 cgroup_release_pid_array(l);
2903                 return retval;
2904         }
2905         ((struct seq_file *)file->private_data)->private = l;
2906         return 0;
2907 }
2908 static int cgroup_tasks_open(struct inode *unused, struct file *file)
2909 {
2910         return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
2911 }
2912 static int cgroup_procs_open(struct inode *unused, struct file *file)
2913 {
2914         return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
2915 }
2916
2917 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
2918                                             struct cftype *cft)
2919 {
2920         return notify_on_release(cgrp);
2921 }
2922
2923 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
2924                                           struct cftype *cft,
2925                                           u64 val)
2926 {
2927         clear_bit(CGRP_RELEASABLE, &cgrp->flags);
2928         if (val)
2929                 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2930         else
2931                 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2932         return 0;
2933 }
2934
2935 /*
2936  * for the common functions, 'private' gives the type of file
2937  */
2938 /* for hysterical raisins, we can't put this on the older files */
2939 #define CGROUP_FILE_GENERIC_PREFIX "cgroup."
2940 static struct cftype files[] = {
2941         {
2942                 .name = "tasks",
2943                 .open = cgroup_tasks_open,
2944                 .write_u64 = cgroup_tasks_write,
2945                 .release = cgroup_pidlist_release,
2946                 .mode = S_IRUGO | S_IWUSR,
2947         },
2948         {
2949                 .name = CGROUP_FILE_GENERIC_PREFIX "procs",
2950                 .open = cgroup_procs_open,
2951                 /* .write_u64 = cgroup_procs_write, TODO */
2952                 .release = cgroup_pidlist_release,
2953                 .mode = S_IRUGO,
2954         },
2955         {
2956                 .name = "notify_on_release",
2957                 .read_u64 = cgroup_read_notify_on_release,
2958                 .write_u64 = cgroup_write_notify_on_release,
2959         },
2960 };
2961
2962 static struct cftype cft_release_agent = {
2963         .name = "release_agent",
2964         .read_seq_string = cgroup_release_agent_show,
2965         .write_string = cgroup_release_agent_write,
2966         .max_write_len = PATH_MAX,
2967 };
2968
2969 static int cgroup_populate_dir(struct cgroup *cgrp)
2970 {
2971         int err;
2972         struct cgroup_subsys *ss;
2973
2974         /* First clear out any existing files */
2975         cgroup_clear_directory(cgrp->dentry);
2976
2977         err = cgroup_add_files(cgrp, NULL, files, ARRAY_SIZE(files));
2978         if (err < 0)
2979                 return err;
2980
2981         if (cgrp == cgrp->top_cgroup) {
2982                 if ((err = cgroup_add_file(cgrp, NULL, &cft_release_agent)) < 0)
2983                         return err;
2984         }
2985
2986         for_each_subsys(cgrp->root, ss) {
2987                 if (ss->populate && (err = ss->populate(ss, cgrp)) < 0)
2988                         return err;
2989         }
2990         /* This cgroup is ready now */
2991         for_each_subsys(cgrp->root, ss) {
2992                 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
2993                 /*
2994                  * Update id->css pointer and make this css visible from
2995                  * CSS ID functions. This pointer will be dereferened
2996                  * from RCU-read-side without locks.
2997                  */
2998                 if (css->id)
2999                         rcu_assign_pointer(css->id->css, css);
3000         }
3001
3002         return 0;
3003 }
3004
3005 static void init_cgroup_css(struct cgroup_subsys_state *css,
3006                                struct cgroup_subsys *ss,
3007                                struct cgroup *cgrp)
3008 {
3009         css->cgroup = cgrp;
3010         atomic_set(&css->refcnt, 1);
3011         css->flags = 0;
3012         css->id = NULL;
3013         if (cgrp == dummytop)
3014                 set_bit(CSS_ROOT, &css->flags);
3015         BUG_ON(cgrp->subsys[ss->subsys_id]);
3016         cgrp->subsys[ss->subsys_id] = css;
3017 }
3018
3019 static void cgroup_lock_hierarchy(struct cgroupfs_root *root)
3020 {
3021         /* We need to take each hierarchy_mutex in a consistent order */
3022         int i;
3023
3024         /*
3025          * No worry about a race with rebind_subsystems that might mess up the
3026          * locking order, since both parties are under cgroup_mutex.
3027          */
3028         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3029                 struct cgroup_subsys *ss = subsys[i];
3030                 if (ss == NULL)
3031                         continue;
3032                 if (ss->root == root)
3033                         mutex_lock(&ss->hierarchy_mutex);
3034         }
3035 }
3036
3037 static void cgroup_unlock_hierarchy(struct cgroupfs_root *root)
3038 {
3039         int i;
3040
3041         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3042                 struct cgroup_subsys *ss = subsys[i];
3043                 if (ss == NULL)
3044                         continue;
3045                 if (ss->root == root)
3046                         mutex_unlock(&ss->hierarchy_mutex);
3047         }
3048 }
3049
3050 /*
3051  * cgroup_create - create a cgroup
3052  * @parent: cgroup that will be parent of the new cgroup
3053  * @dentry: dentry of the new cgroup
3054  * @mode: mode to set on new inode
3055  *
3056  * Must be called with the mutex on the parent inode held
3057  */
3058 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
3059                              mode_t mode)
3060 {
3061         struct cgroup *cgrp;
3062         struct cgroupfs_root *root = parent->root;
3063         int err = 0;
3064         struct cgroup_subsys *ss;
3065         struct super_block *sb = root->sb;
3066
3067         cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
3068         if (!cgrp)
3069                 return -ENOMEM;
3070
3071         /* Grab a reference on the superblock so the hierarchy doesn't
3072          * get deleted on unmount if there are child cgroups.  This
3073          * can be done outside cgroup_mutex, since the sb can't
3074          * disappear while someone has an open control file on the
3075          * fs */
3076         atomic_inc(&sb->s_active);
3077
3078         mutex_lock(&cgroup_mutex);
3079
3080         init_cgroup_housekeeping(cgrp);
3081
3082         cgrp->parent = parent;
3083         cgrp->root = parent->root;
3084         cgrp->top_cgroup = parent->top_cgroup;
3085
3086         if (notify_on_release(parent))
3087                 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3088
3089         for_each_subsys(root, ss) {
3090                 struct cgroup_subsys_state *css = ss->create(ss, cgrp);
3091
3092                 if (IS_ERR(css)) {
3093                         err = PTR_ERR(css);
3094                         goto err_destroy;
3095                 }
3096                 init_cgroup_css(css, ss, cgrp);
3097                 if (ss->use_id) {
3098                         err = alloc_css_id(ss, parent, cgrp);
3099                         if (err)
3100                                 goto err_destroy;
3101                 }
3102                 /* At error, ->destroy() callback has to free assigned ID. */
3103         }
3104
3105         cgroup_lock_hierarchy(root);
3106         list_add(&cgrp->sibling, &cgrp->parent->children);
3107         cgroup_unlock_hierarchy(root);
3108         root->number_of_cgroups++;
3109
3110         err = cgroup_create_dir(cgrp, dentry, mode);
3111         if (err < 0)
3112                 goto err_remove;
3113
3114         /* The cgroup directory was pre-locked for us */
3115         BUG_ON(!mutex_is_locked(&cgrp->dentry->d_inode->i_mutex));
3116
3117         err = cgroup_populate_dir(cgrp);
3118         /* If err < 0, we have a half-filled directory - oh well ;) */
3119
3120         mutex_unlock(&cgroup_mutex);
3121         mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
3122
3123         return 0;
3124
3125  err_remove:
3126
3127         cgroup_lock_hierarchy(root);
3128         list_del(&cgrp->sibling);
3129         cgroup_unlock_hierarchy(root);
3130         root->number_of_cgroups--;
3131
3132  err_destroy:
3133
3134         for_each_subsys(root, ss) {
3135                 if (cgrp->subsys[ss->subsys_id])
3136                         ss->destroy(ss, cgrp);
3137         }
3138
3139         mutex_unlock(&cgroup_mutex);
3140
3141         /* Release the reference count that we took on the superblock */
3142         deactivate_super(sb);
3143
3144         kfree(cgrp);
3145         return err;
3146 }
3147
3148 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode)
3149 {
3150         struct cgroup *c_parent = dentry->d_parent->d_fsdata;
3151
3152         /* the vfs holds inode->i_mutex already */
3153         return cgroup_create(c_parent, dentry, mode | S_IFDIR);
3154 }
3155
3156 static int cgroup_has_css_refs(struct cgroup *cgrp)
3157 {
3158         /* Check the reference count on each subsystem. Since we
3159          * already established that there are no tasks in the
3160          * cgroup, if the css refcount is also 1, then there should
3161          * be no outstanding references, so the subsystem is safe to
3162          * destroy. We scan across all subsystems rather than using
3163          * the per-hierarchy linked list of mounted subsystems since
3164          * we can be called via check_for_release() with no
3165          * synchronization other than RCU, and the subsystem linked
3166          * list isn't RCU-safe */
3167         int i;
3168         /*
3169          * We won't need to lock the subsys array, because the subsystems
3170          * we're concerned about aren't going anywhere since our cgroup root
3171          * has a reference on them.
3172          */
3173         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3174                 struct cgroup_subsys *ss = subsys[i];
3175                 struct cgroup_subsys_state *css;
3176                 /* Skip subsystems not present or not in this hierarchy */
3177                 if (ss == NULL || ss->root != cgrp->root)
3178                         continue;
3179                 css = cgrp->subsys[ss->subsys_id];
3180                 /* When called from check_for_release() it's possible
3181                  * that by this point the cgroup has been removed
3182                  * and the css deleted. But a false-positive doesn't
3183                  * matter, since it can only happen if the cgroup
3184                  * has been deleted and hence no longer needs the
3185                  * release agent to be called anyway. */
3186                 if (css && (atomic_read(&css->refcnt) > 1))
3187                         return 1;
3188         }
3189         return 0;
3190 }
3191
3192 /*
3193  * Atomically mark all (or else none) of the cgroup's CSS objects as
3194  * CSS_REMOVED. Return true on success, or false if the cgroup has
3195  * busy subsystems. Call with cgroup_mutex held
3196  */
3197
3198 static int cgroup_clear_css_refs(struct cgroup *cgrp)
3199 {
3200         struct cgroup_subsys *ss;
3201         unsigned long flags;
3202         bool failed = false;
3203         local_irq_save(flags);
3204         for_each_subsys(cgrp->root, ss) {
3205                 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
3206                 int refcnt;
3207                 while (1) {
3208                         /* We can only remove a CSS with a refcnt==1 */
3209                         refcnt = atomic_read(&css->refcnt);
3210                         if (refcnt > 1) {
3211                                 failed = true;
3212                                 goto done;
3213                         }
3214                         BUG_ON(!refcnt);
3215                         /*
3216                          * Drop the refcnt to 0 while we check other
3217                          * subsystems. This will cause any racing
3218                          * css_tryget() to spin until we set the
3219                          * CSS_REMOVED bits or abort
3220                          */
3221                         if (atomic_cmpxchg(&css->refcnt, refcnt, 0) == refcnt)
3222                                 break;
3223                         cpu_relax();
3224                 }
3225         }
3226  done:
3227         for_each_subsys(cgrp->root, ss) {
3228                 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
3229                 if (failed) {
3230                         /*
3231                          * Restore old refcnt if we previously managed
3232                          * to clear it from 1 to 0
3233                          */
3234                         if (!atomic_read(&css->refcnt))
3235                                 atomic_set(&css->refcnt, 1);
3236                 } else {
3237                         /* Commit the fact that the CSS is removed */
3238                         set_bit(CSS_REMOVED, &css->flags);
3239                 }
3240         }
3241         local_irq_restore(flags);
3242         return !failed;
3243 }
3244
3245 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
3246 {
3247         struct cgroup *cgrp = dentry->d_fsdata;
3248         struct dentry *d;
3249         struct cgroup *parent;
3250         DEFINE_WAIT(wait);
3251         int ret;
3252
3253         /* the vfs holds both inode->i_mutex already */
3254 again:
3255         mutex_lock(&cgroup_mutex);
3256         if (atomic_read(&cgrp->count) != 0) {
3257                 mutex_unlock(&cgroup_mutex);
3258                 return -EBUSY;
3259         }
3260         if (!list_empty(&cgrp->children)) {
3261                 mutex_unlock(&cgroup_mutex);
3262                 return -EBUSY;
3263         }
3264         mutex_unlock(&cgroup_mutex);
3265
3266         /*
3267          * In general, subsystem has no css->refcnt after pre_destroy(). But
3268          * in racy cases, subsystem may have to get css->refcnt after
3269          * pre_destroy() and it makes rmdir return with -EBUSY. This sometimes
3270          * make rmdir return -EBUSY too often. To avoid that, we use waitqueue
3271          * for cgroup's rmdir. CGRP_WAIT_ON_RMDIR is for synchronizing rmdir
3272          * and subsystem's reference count handling. Please see css_get/put
3273          * and css_tryget() and cgroup_wakeup_rmdir_waiter() implementation.
3274          */
3275         set_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3276
3277         /*
3278          * Call pre_destroy handlers of subsys. Notify subsystems
3279          * that rmdir() request comes.
3280          */
3281         ret = cgroup_call_pre_destroy(cgrp);
3282         if (ret) {
3283                 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3284                 return ret;
3285         }
3286
3287         mutex_lock(&cgroup_mutex);
3288         parent = cgrp->parent;
3289         if (atomic_read(&cgrp->count) || !list_empty(&cgrp->children)) {
3290                 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3291                 mutex_unlock(&cgroup_mutex);
3292                 return -EBUSY;
3293         }
3294         prepare_to_wait(&cgroup_rmdir_waitq, &wait, TASK_INTERRUPTIBLE);
3295         if (!cgroup_clear_css_refs(cgrp)) {
3296                 mutex_unlock(&cgroup_mutex);
3297                 /*
3298                  * Because someone may call cgroup_wakeup_rmdir_waiter() before
3299                  * prepare_to_wait(), we need to check this flag.
3300                  */
3301                 if (test_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags))
3302                         schedule();
3303                 finish_wait(&cgroup_rmdir_waitq, &wait);
3304                 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3305                 if (signal_pending(current))
3306                         return -EINTR;
3307                 goto again;
3308         }
3309         /* NO css_tryget() can success after here. */
3310         finish_wait(&cgroup_rmdir_waitq, &wait);
3311         clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3312
3313         spin_lock(&release_list_lock);
3314         set_bit(CGRP_REMOVED, &cgrp->flags);
3315         if (!list_empty(&cgrp->release_list))
3316                 list_del(&cgrp->release_list);
3317         spin_unlock(&release_list_lock);
3318
3319         cgroup_lock_hierarchy(cgrp->root);
3320         /* delete this cgroup from parent->children */
3321         list_del(&cgrp->sibling);
3322         cgroup_unlock_hierarchy(cgrp->root);
3323
3324         spin_lock(&cgrp->dentry->d_lock);
3325         d = dget(cgrp->dentry);
3326         spin_unlock(&d->d_lock);
3327
3328         cgroup_d_remove_dir(d);
3329         dput(d);
3330
3331         set_bit(CGRP_RELEASABLE, &parent->flags);
3332         check_for_release(parent);
3333
3334         mutex_unlock(&cgroup_mutex);
3335         return 0;
3336 }
3337
3338 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
3339 {
3340         struct cgroup_subsys_state *css;
3341
3342         printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
3343
3344         /* Create the top cgroup state for this subsystem */
3345         list_add(&ss->sibling, &rootnode.subsys_list);
3346         ss->root = &rootnode;
3347         css = ss->create(ss, dummytop);
3348         /* We don't handle early failures gracefully */
3349         BUG_ON(IS_ERR(css));
3350         init_cgroup_css(css, ss, dummytop);
3351
3352         /* Update the init_css_set to contain a subsys
3353          * pointer to this state - since the subsystem is
3354          * newly registered, all tasks and hence the
3355          * init_css_set is in the subsystem's top cgroup. */
3356         init_css_set.subsys[ss->subsys_id] = dummytop->subsys[ss->subsys_id];
3357
3358         need_forkexit_callback |= ss->fork || ss->exit;
3359
3360         /* At system boot, before all subsystems have been
3361          * registered, no tasks have been forked, so we don't
3362          * need to invoke fork callbacks here. */
3363         BUG_ON(!list_empty(&init_task.tasks));
3364
3365         mutex_init(&ss->hierarchy_mutex);
3366         lockdep_set_class(&ss->hierarchy_mutex, &ss->subsys_key);
3367         ss->active = 1;
3368
3369         /* this function shouldn't be used with modular subsystems, since they
3370          * need to register a subsys_id, among other things */
3371         BUG_ON(ss->module);
3372 }
3373
3374 /**
3375  * cgroup_load_subsys: load and register a modular subsystem at runtime
3376  * @ss: the subsystem to load
3377  *
3378  * This function should be called in a modular subsystem's initcall. If the
3379  * subsytem is built as a module, it will be assigned a new subsys_id and set
3380  * up for use. If the subsystem is built-in anyway, work is delegated to the
3381  * simpler cgroup_init_subsys.
3382  */
3383 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
3384 {
3385         int i;
3386         struct cgroup_subsys_state *css;
3387
3388         /* check name and function validity */
3389         if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
3390             ss->create == NULL || ss->destroy == NULL)
3391                 return -EINVAL;
3392
3393         /*
3394          * we don't support callbacks in modular subsystems. this check is
3395          * before the ss->module check for consistency; a subsystem that could
3396          * be a module should still have no callbacks even if the user isn't
3397          * compiling it as one.
3398          */
3399         if (ss->fork || ss->exit)
3400                 return -EINVAL;
3401
3402         /*
3403          * an optionally modular subsystem is built-in: we want to do nothing,
3404          * since cgroup_init_subsys will have already taken care of it.
3405          */
3406         if (ss->module == NULL) {
3407                 /* a few sanity checks */
3408                 BUG_ON(ss->subsys_id >= CGROUP_BUILTIN_SUBSYS_COUNT);
3409                 BUG_ON(subsys[ss->subsys_id] != ss);
3410                 return 0;
3411         }
3412
3413         /*
3414          * need to register a subsys id before anything else - for example,
3415          * init_cgroup_css needs it.
3416          */
3417         mutex_lock(&cgroup_mutex);
3418         /* find the first empty slot in the array */
3419         for (i = CGROUP_BUILTIN_SUBSYS_COUNT; i < CGROUP_SUBSYS_COUNT; i++) {
3420                 if (subsys[i] == NULL)
3421                         break;
3422         }
3423         if (i == CGROUP_SUBSYS_COUNT) {
3424                 /* maximum number of subsystems already registered! */
3425                 mutex_unlock(&cgroup_mutex);
3426                 return -EBUSY;
3427         }
3428         /* assign ourselves the subsys_id */
3429         ss->subsys_id = i;
3430         subsys[i] = ss;
3431
3432         /*
3433          * no ss->create seems to need anything important in the ss struct, so
3434          * this can happen first (i.e. before the rootnode attachment).
3435          */
3436         css = ss->create(ss, dummytop);
3437         if (IS_ERR(css)) {
3438                 /* failure case - need to deassign the subsys[] slot. */
3439                 subsys[i] = NULL;
3440                 mutex_unlock(&cgroup_mutex);
3441                 return PTR_ERR(css);
3442         }
3443
3444         list_add(&ss->sibling, &rootnode.subsys_list);
3445         ss->root = &rootnode;
3446
3447         /* our new subsystem will be attached to the dummy hierarchy. */
3448         init_cgroup_css(css, ss, dummytop);
3449         /* init_idr must be after init_cgroup_css because it sets css->id. */
3450         if (ss->use_id) {
3451                 int ret = cgroup_init_idr(ss, css);
3452                 if (ret) {
3453                         dummytop->subsys[ss->subsys_id] = NULL;
3454                         ss->destroy(ss, dummytop);
3455                         subsys[i] = NULL;
3456                         mutex_unlock(&cgroup_mutex);
3457                         return ret;
3458                 }
3459         }
3460
3461         /*
3462          * Now we need to entangle the css into the existing css_sets. unlike
3463          * in cgroup_init_subsys, there are now multiple css_sets, so each one
3464          * will need a new pointer to it; done by iterating the css_set_table.
3465          * furthermore, modifying the existing css_sets will corrupt the hash
3466          * table state, so each changed css_set will need its hash recomputed.
3467          * this is all done under the css_set_lock.
3468          */
3469         write_lock(&css_set_lock);
3470         for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
3471                 struct css_set *cg;
3472                 struct hlist_node *node, *tmp;
3473                 struct hlist_head *bucket = &css_set_table[i], *new_bucket;
3474
3475                 hlist_for_each_entry_safe(cg, node, tmp, bucket, hlist) {
3476                         /* skip entries that we already rehashed */
3477                         if (cg->subsys[ss->subsys_id])
3478                                 continue;
3479                         /* remove existing entry */
3480                         hlist_del(&cg->hlist);
3481                         /* set new value */
3482                         cg->subsys[ss->subsys_id] = css;
3483                         /* recompute hash and restore entry */
3484                         new_bucket = css_set_hash(cg->subsys);
3485                         hlist_add_head(&cg->hlist, new_bucket);
3486                 }
3487         }
3488         write_unlock(&css_set_lock);
3489
3490         mutex_init(&ss->hierarchy_mutex);
3491         lockdep_set_class(&ss->hierarchy_mutex, &ss->subsys_key);
3492         ss->active = 1;
3493
3494         /* success! */
3495         mutex_unlock(&cgroup_mutex);
3496         return 0;
3497 }
3498 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
3499
3500 /**
3501  * cgroup_unload_subsys: unload a modular subsystem
3502  * @ss: the subsystem to unload
3503  *
3504  * This function should be called in a modular subsystem's exitcall. When this
3505  * function is invoked, the refcount on the subsystem's module will be 0, so
3506  * the subsystem will not be attached to any hierarchy.
3507  */
3508 void cgroup_unload_subsys(struct cgroup_subsys *ss)
3509 {
3510         struct cg_cgroup_link *link;
3511         struct hlist_head *hhead;
3512
3513         BUG_ON(ss->module == NULL);
3514
3515         /*
3516          * we shouldn't be called if the subsystem is in use, and the use of
3517          * try_module_get in parse_cgroupfs_options should ensure that it
3518          * doesn't start being used while we're killing it off.
3519          */
3520         BUG_ON(ss->root != &rootnode);
3521
3522         mutex_lock(&cgroup_mutex);
3523         /* deassign the subsys_id */
3524         BUG_ON(ss->subsys_id < CGROUP_BUILTIN_SUBSYS_COUNT);
3525         subsys[ss->subsys_id] = NULL;
3526
3527         /* remove subsystem from rootnode's list of subsystems */
3528         list_del(&ss->sibling);
3529
3530         /*
3531          * disentangle the css from all css_sets attached to the dummytop. as
3532          * in loading, we need to pay our respects to the hashtable gods.
3533          */
3534         write_lock(&css_set_lock);
3535         list_for_each_entry(link, &dummytop->css_sets, cgrp_link_list) {
3536                 struct css_set *cg = link->cg;
3537
3538                 hlist_del(&cg->hlist);
3539                 BUG_ON(!cg->subsys[ss->subsys_id]);
3540                 cg->subsys[ss->subsys_id] = NULL;
3541                 hhead = css_set_hash(cg->subsys);
3542                 hlist_add_head(&cg->hlist, hhead);
3543         }
3544         write_unlock(&css_set_lock);
3545
3546         /*
3547          * remove subsystem's css from the dummytop and free it - need to free
3548          * before marking as null because ss->destroy needs the cgrp->subsys
3549          * pointer to find their state. note that this also takes care of
3550          * freeing the css_id.
3551          */
3552         ss->destroy(ss, dummytop);
3553         dummytop->subsys[ss->subsys_id] = NULL;
3554
3555         mutex_unlock(&cgroup_mutex);
3556 }
3557 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
3558
3559 /**
3560  * cgroup_init_early - cgroup initialization at system boot
3561  *
3562  * Initialize cgroups at system boot, and initialize any
3563  * subsystems that request early init.
3564  */
3565 int __init cgroup_init_early(void)
3566 {
3567         int i;
3568         atomic_set(&init_css_set.refcount, 1);
3569         INIT_LIST_HEAD(&init_css_set.cg_links);
3570         INIT_LIST_HEAD(&init_css_set.tasks);
3571         INIT_HLIST_NODE(&init_css_set.hlist);
3572         css_set_count = 1;
3573         init_cgroup_root(&rootnode);
3574         root_count = 1;
3575         init_task.cgroups = &init_css_set;
3576
3577         init_css_set_link.cg = &init_css_set;
3578         init_css_set_link.cgrp = dummytop;
3579         list_add(&init_css_set_link.cgrp_link_list,
3580                  &rootnode.top_cgroup.css_sets);
3581         list_add(&init_css_set_link.cg_link_list,
3582                  &init_css_set.cg_links);
3583
3584         for (i = 0; i < CSS_SET_TABLE_SIZE; i++)
3585                 INIT_HLIST_HEAD(&css_set_table[i]);
3586
3587         /* at bootup time, we don't worry about modular subsystems */
3588         for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
3589                 struct cgroup_subsys *ss = subsys[i];
3590
3591                 BUG_ON(!ss->name);
3592                 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
3593                 BUG_ON(!ss->create);
3594                 BUG_ON(!ss->destroy);
3595                 if (ss->subsys_id != i) {
3596                         printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
3597                                ss->name, ss->subsys_id);
3598                         BUG();
3599                 }
3600
3601                 if (ss->early_init)
3602                         cgroup_init_subsys(ss);
3603         }
3604         return 0;
3605 }
3606
3607 /**
3608  * cgroup_init - cgroup initialization
3609  *
3610  * Register cgroup filesystem and /proc file, and initialize
3611  * any subsystems that didn't request early init.
3612  */
3613 int __init cgroup_init(void)
3614 {
3615         int err;
3616         int i;
3617         struct hlist_head *hhead;
3618
3619         err = bdi_init(&cgroup_backing_dev_info);
3620         if (err)
3621                 return err;
3622
3623         /* at bootup time, we don't worry about modular subsystems */
3624         for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
3625                 struct cgroup_subsys *ss = subsys[i];
3626                 if (!ss->early_init)
3627                         cgroup_init_subsys(ss);
3628                 if (ss->use_id)
3629                         cgroup_init_idr(ss, init_css_set.subsys[ss->subsys_id]);
3630         }
3631
3632         /* Add init_css_set to the hash table */
3633         hhead = css_set_hash(init_css_set.subsys);
3634         hlist_add_head(&init_css_set.hlist, hhead);
3635         BUG_ON(!init_root_id(&rootnode));
3636         err = register_filesystem(&cgroup_fs_type);
3637         if (err < 0)
3638                 goto out;
3639
3640         proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
3641
3642 out:
3643         if (err)
3644                 bdi_destroy(&cgroup_backing_dev_info);
3645
3646         return err;
3647 }
3648
3649 /*
3650  * proc_cgroup_show()
3651  *  - Print task's cgroup paths into seq_file, one line for each hierarchy
3652  *  - Used for /proc/<pid>/cgroup.
3653  *  - No need to task_lock(tsk) on this tsk->cgroup reference, as it
3654  *    doesn't really matter if tsk->cgroup changes after we read it,
3655  *    and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
3656  *    anyway.  No need to check that tsk->cgroup != NULL, thanks to
3657  *    the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
3658  *    cgroup to top_cgroup.
3659  */
3660
3661 /* TODO: Use a proper seq_file iterator */
3662 static int proc_cgroup_show(struct seq_file *m, void *v)
3663 {
3664         struct pid *pid;
3665         struct task_struct *tsk;
3666         char *buf;
3667         int retval;
3668         struct cgroupfs_root *root;
3669
3670         retval = -ENOMEM;
3671         buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
3672         if (!buf)
3673                 goto out;
3674
3675         retval = -ESRCH;
3676         pid = m->private;
3677         tsk = get_pid_task(pid, PIDTYPE_PID);
3678         if (!tsk)
3679                 goto out_free;
3680
3681         retval = 0;
3682
3683         mutex_lock(&cgroup_mutex);
3684
3685         for_each_active_root(root) {
3686                 struct cgroup_subsys *ss;
3687                 struct cgroup *cgrp;
3688                 int count = 0;
3689
3690                 seq_printf(m, "%d:", root->hierarchy_id);
3691                 for_each_subsys(root, ss)
3692                         seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
3693                 if (strlen(root->name))
3694                         seq_printf(m, "%sname=%s", count ? "," : "",
3695                                    root->name);
3696                 seq_putc(m, ':');
3697                 cgrp = task_cgroup_from_root(tsk, root);
3698                 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
3699                 if (retval < 0)
3700                         goto out_unlock;
3701                 seq_puts(m, buf);
3702                 seq_putc(m, '\n');
3703         }
3704
3705 out_unlock:
3706         mutex_unlock(&cgroup_mutex);
3707         put_task_struct(tsk);
3708 out_free:
3709         kfree(buf);
3710 out:
3711         return retval;
3712 }
3713
3714 static int cgroup_open(struct inode *inode, struct file *file)
3715 {
3716         struct pid *pid = PROC_I(inode)->pid;
3717         return single_open(file, proc_cgroup_show, pid);
3718 }
3719
3720 const struct file_operations proc_cgroup_operations = {
3721         .open           = cgroup_open,
3722         .read           = seq_read,
3723         .llseek         = seq_lseek,
3724         .release        = single_release,
3725 };
3726
3727 /* Display information about each subsystem and each hierarchy */
3728 static int proc_cgroupstats_show(struct seq_file *m, void *v)
3729 {
3730         int i;
3731
3732         seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
3733         /*
3734          * ideally we don't want subsystems moving around while we do this.
3735          * cgroup_mutex is also necessary to guarantee an atomic snapshot of
3736          * subsys/hierarchy state.
3737          */
3738         mutex_lock(&cgroup_mutex);
3739         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3740                 struct cgroup_subsys *ss = subsys[i];
3741                 if (ss == NULL)
3742                         continue;
3743                 seq_printf(m, "%s\t%d\t%d\t%d\n",
3744                            ss->name, ss->root->hierarchy_id,
3745                            ss->root->number_of_cgroups, !ss->disabled);
3746         }
3747         mutex_unlock(&cgroup_mutex);
3748         return 0;
3749 }
3750
3751 static int cgroupstats_open(struct inode *inode, struct file *file)
3752 {
3753         return single_open(file, proc_cgroupstats_show, NULL);
3754 }
3755
3756 static const struct file_operations proc_cgroupstats_operations = {
3757         .open = cgroupstats_open,
3758         .read = seq_read,
3759         .llseek = seq_lseek,
3760         .release = single_release,
3761 };
3762
3763 /**
3764  * cgroup_fork - attach newly forked task to its parents cgroup.
3765  * @child: pointer to task_struct of forking parent process.
3766  *
3767  * Description: A task inherits its parent's cgroup at fork().
3768  *
3769  * A pointer to the shared css_set was automatically copied in
3770  * fork.c by dup_task_struct().  However, we ignore that copy, since
3771  * it was not made under the protection of RCU or cgroup_mutex, so
3772  * might no longer be a valid cgroup pointer.  cgroup_attach_task() might
3773  * have already changed current->cgroups, allowing the previously
3774  * referenced cgroup group to be removed and freed.
3775  *
3776  * At the point that cgroup_fork() is called, 'current' is the parent
3777  * task, and the passed argument 'child' points to the child task.
3778  */
3779 void cgroup_fork(struct task_struct *child)
3780 {
3781         task_lock(current);
3782         child->cgroups = current->cgroups;
3783         get_css_set(child->cgroups);
3784         task_unlock(current);
3785         INIT_LIST_HEAD(&child->cg_list);
3786 }
3787
3788 /**
3789  * cgroup_fork_callbacks - run fork callbacks
3790  * @child: the new task
3791  *
3792  * Called on a new task very soon before adding it to the
3793  * tasklist. No need to take any locks since no-one can
3794  * be operating on this task.
3795  */
3796 void cgroup_fork_callbacks(struct task_struct *child)
3797 {
3798         if (need_forkexit_callback) {
3799                 int i;
3800                 /*
3801                  * forkexit callbacks are only supported for builtin
3802                  * subsystems, and the builtin section of the subsys array is
3803                  * immutable, so we don't need to lock the subsys array here.
3804                  */
3805                 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
3806                         struct cgroup_subsys *ss = subsys[i];
3807                         if (ss->fork)
3808                                 ss->fork(ss, child);
3809                 }
3810         }
3811 }
3812
3813 /**
3814  * cgroup_post_fork - called on a new task after adding it to the task list
3815  * @child: the task in question
3816  *
3817  * Adds the task to the list running through its css_set if necessary.
3818  * Has to be after the task is visible on the task list in case we race
3819  * with the first call to cgroup_iter_start() - to guarantee that the
3820  * new task ends up on its list.
3821  */
3822 void cgroup_post_fork(struct task_struct *child)
3823 {
3824         if (use_task_css_set_links) {
3825                 write_lock(&css_set_lock);
3826                 task_lock(child);
3827                 if (list_empty(&child->cg_list))
3828                         list_add(&child->cg_list, &child->cgroups->tasks);
3829                 task_unlock(child);
3830                 write_unlock(&css_set_lock);
3831         }
3832 }
3833 /**
3834  * cgroup_exit - detach cgroup from exiting task
3835  * @tsk: pointer to task_struct of exiting process
3836  * @run_callback: run exit callbacks?
3837  *
3838  * Description: Detach cgroup from @tsk and release it.
3839  *
3840  * Note that cgroups marked notify_on_release force every task in
3841  * them to take the global cgroup_mutex mutex when exiting.
3842  * This could impact scaling on very large systems.  Be reluctant to
3843  * use notify_on_release cgroups where very high task exit scaling
3844  * is required on large systems.
3845  *
3846  * the_top_cgroup_hack:
3847  *
3848  *    Set the exiting tasks cgroup to the root cgroup (top_cgroup).
3849  *
3850  *    We call cgroup_exit() while the task is still competent to
3851  *    handle notify_on_release(), then leave the task attached to the
3852  *    root cgroup in each hierarchy for the remainder of its exit.
3853  *
3854  *    To do this properly, we would increment the reference count on
3855  *    top_cgroup, and near the very end of the kernel/exit.c do_exit()
3856  *    code we would add a second cgroup function call, to drop that
3857  *    reference.  This would just create an unnecessary hot spot on
3858  *    the top_cgroup reference count, to no avail.
3859  *
3860  *    Normally, holding a reference to a cgroup without bumping its
3861  *    count is unsafe.   The cgroup could go away, or someone could
3862  *    attach us to a different cgroup, decrementing the count on
3863  *    the first cgroup that we never incremented.  But in this case,
3864  *    top_cgroup isn't going away, and either task has PF_EXITING set,
3865  *    which wards off any cgroup_attach_task() attempts, or task is a failed
3866  *    fork, never visible to cgroup_attach_task.
3867  */
3868 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
3869 {
3870         int i;
3871         struct css_set *cg;
3872
3873         if (run_callbacks && need_forkexit_callback) {
3874                 /*
3875                  * modular subsystems can't use callbacks, so no need to lock
3876                  * the subsys array
3877                  */
3878                 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
3879                         struct cgroup_subsys *ss = subsys[i];
3880                         if (ss->exit)
3881                                 ss->exit(ss, tsk);
3882                 }
3883         }
3884
3885         /*
3886          * Unlink from the css_set task list if necessary.
3887          * Optimistically check cg_list before taking
3888          * css_set_lock
3889          */
3890         if (!list_empty(&tsk->cg_list)) {
3891                 write_lock(&css_set_lock);
3892                 if (!list_empty(&tsk->cg_list))
3893                         list_del(&tsk->cg_list);
3894                 write_unlock(&css_set_lock);
3895         }
3896
3897         /* Reassign the task to the init_css_set. */
3898         task_lock(tsk);
3899         cg = tsk->cgroups;
3900         tsk->cgroups = &init_css_set;
3901         task_unlock(tsk);
3902         if (cg)
3903                 put_css_set_taskexit(cg);
3904 }
3905
3906 /**
3907  * cgroup_clone - clone the cgroup the given subsystem is attached to
3908  * @tsk: the task to be moved
3909  * @subsys: the given subsystem
3910  * @nodename: the name for the new cgroup
3911  *
3912  * Duplicate the current cgroup in the hierarchy that the given
3913  * subsystem is attached to, and move this task into the new
3914  * child.
3915  */
3916 int cgroup_clone(struct task_struct *tsk, struct cgroup_subsys *subsys,
3917                                                         char *nodename)
3918 {
3919         struct dentry *dentry;
3920         int ret = 0;
3921         struct cgroup *parent, *child;
3922         struct inode *inode;
3923         struct css_set *cg;
3924         struct cgroupfs_root *root;
3925         struct cgroup_subsys *ss;
3926
3927         /* We shouldn't be called by an unregistered subsystem */
3928         BUG_ON(!subsys->active);
3929
3930         /* First figure out what hierarchy and cgroup we're dealing
3931          * with, and pin them so we can drop cgroup_mutex */
3932         mutex_lock(&cgroup_mutex);
3933  again:
3934         root = subsys->root;
3935         if (root == &rootnode) {
3936                 mutex_unlock(&cgroup_mutex);
3937                 return 0;
3938         }
3939
3940         /* Pin the hierarchy */
3941         if (!atomic_inc_not_zero(&root->sb->s_active)) {
3942                 /* We race with the final deactivate_super() */
3943                 mutex_unlock(&cgroup_mutex);
3944                 return 0;
3945         }
3946
3947         /* Keep the cgroup alive */
3948         task_lock(tsk);
3949         parent = task_cgroup(tsk, subsys->subsys_id);
3950         cg = tsk->cgroups;
3951         get_css_set(cg);
3952         task_unlock(tsk);
3953
3954         mutex_unlock(&cgroup_mutex);
3955
3956         /* Now do the VFS work to create a cgroup */
3957         inode = parent->dentry->d_inode;
3958
3959         /* Hold the parent directory mutex across this operation to
3960          * stop anyone else deleting the new cgroup */
3961         mutex_lock(&inode->i_mutex);
3962         dentry = lookup_one_len(nodename, parent->dentry, strlen(nodename));
3963         if (IS_ERR(dentry)) {
3964                 printk(KERN_INFO
3965                        "cgroup: Couldn't allocate dentry for %s: %ld\n", nodename,
3966                        PTR_ERR(dentry));
3967                 ret = PTR_ERR(dentry);
3968                 goto out_release;
3969         }
3970
3971         /* Create the cgroup directory, which also creates the cgroup */
3972         ret = vfs_mkdir(inode, dentry, 0755);
3973         child = __d_cgrp(dentry);
3974         dput(dentry);
3975         if (ret) {
3976                 printk(KERN_INFO
3977                        "Failed to create cgroup %s: %d\n", nodename,
3978                        ret);
3979                 goto out_release;
3980         }
3981
3982         /* The cgroup now exists. Retake cgroup_mutex and check
3983          * that we're still in the same state that we thought we
3984          * were. */
3985         mutex_lock(&cgroup_mutex);
3986         if ((root != subsys->root) ||
3987             (parent != task_cgroup(tsk, subsys->subsys_id))) {
3988                 /* Aargh, we raced ... */
3989                 mutex_unlock(&inode->i_mutex);
3990                 put_css_set(cg);
3991
3992                 deactivate_super(root->sb);
3993                 /* The cgroup is still accessible in the VFS, but
3994                  * we're not going to try to rmdir() it at this
3995                  * point. */
3996                 printk(KERN_INFO
3997                        "Race in cgroup_clone() - leaking cgroup %s\n",
3998                        nodename);
3999                 goto again;
4000         }
4001
4002         /* do any required auto-setup */
4003         for_each_subsys(root, ss) {
4004                 if (ss->post_clone)
4005                         ss->post_clone(ss, child);
4006         }
4007
4008         /* All seems fine. Finish by moving the task into the new cgroup */
4009         ret = cgroup_attach_task(child, tsk);
4010         mutex_unlock(&cgroup_mutex);
4011
4012  out_release:
4013         mutex_unlock(&inode->i_mutex);
4014
4015         mutex_lock(&cgroup_mutex);
4016         put_css_set(cg);
4017         mutex_unlock(&cgroup_mutex);
4018         deactivate_super(root->sb);
4019         return ret;
4020 }
4021
4022 /**
4023  * cgroup_is_descendant - see if @cgrp is a descendant of @task's cgrp
4024  * @cgrp: the cgroup in question
4025  * @task: the task in question
4026  *
4027  * See if @cgrp is a descendant of @task's cgroup in the appropriate
4028  * hierarchy.
4029  *
4030  * If we are sending in dummytop, then presumably we are creating
4031  * the top cgroup in the subsystem.
4032  *
4033  * Called only by the ns (nsproxy) cgroup.
4034  */
4035 int cgroup_is_descendant(const struct cgroup *cgrp, struct task_struct *task)
4036 {
4037         int ret;
4038         struct cgroup *target;
4039
4040         if (cgrp == dummytop)
4041                 return 1;
4042
4043         target = task_cgroup_from_root(task, cgrp->root);
4044         while (cgrp != target && cgrp!= cgrp->top_cgroup)
4045                 cgrp = cgrp->parent;
4046         ret = (cgrp == target);
4047         return ret;
4048 }
4049
4050 static void check_for_release(struct cgroup *cgrp)
4051 {
4052         /* All of these checks rely on RCU to keep the cgroup
4053          * structure alive */
4054         if (cgroup_is_releasable(cgrp) && !atomic_read(&cgrp->count)
4055             && list_empty(&cgrp->children) && !cgroup_has_css_refs(cgrp)) {
4056                 /* Control Group is currently removeable. If it's not
4057                  * already queued for a userspace notification, queue
4058                  * it now */
4059                 int need_schedule_work = 0;
4060                 spin_lock(&release_list_lock);
4061                 if (!cgroup_is_removed(cgrp) &&
4062                     list_empty(&cgrp->release_list)) {
4063                         list_add(&cgrp->release_list, &release_list);
4064                         need_schedule_work = 1;
4065                 }
4066                 spin_unlock(&release_list_lock);
4067                 if (need_schedule_work)
4068                         schedule_work(&release_agent_work);
4069         }
4070 }
4071
4072 /* Caller must verify that the css is not for root cgroup */
4073 void __css_put(struct cgroup_subsys_state *css, int count)
4074 {
4075         struct cgroup *cgrp = css->cgroup;
4076         int val;
4077         rcu_read_lock();
4078         val = atomic_sub_return(count, &css->refcnt);
4079         if (val == 1) {
4080                 if (notify_on_release(cgrp)) {
4081                         set_bit(CGRP_RELEASABLE, &cgrp->flags);
4082                         check_for_release(cgrp);
4083                 }
4084                 cgroup_wakeup_rmdir_waiter(cgrp);
4085         }
4086         rcu_read_unlock();
4087         WARN_ON_ONCE(val < 1);
4088 }
4089 EXPORT_SYMBOL_GPL(__css_put);
4090
4091 /*
4092  * Notify userspace when a cgroup is released, by running the
4093  * configured release agent with the name of the cgroup (path
4094  * relative to the root of cgroup file system) as the argument.
4095  *
4096  * Most likely, this user command will try to rmdir this cgroup.
4097  *
4098  * This races with the possibility that some other task will be
4099  * attached to this cgroup before it is removed, or that some other
4100  * user task will 'mkdir' a child cgroup of this cgroup.  That's ok.
4101  * The presumed 'rmdir' will fail quietly if this cgroup is no longer
4102  * unused, and this cgroup will be reprieved from its death sentence,
4103  * to continue to serve a useful existence.  Next time it's released,
4104  * we will get notified again, if it still has 'notify_on_release' set.
4105  *
4106  * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
4107  * means only wait until the task is successfully execve()'d.  The
4108  * separate release agent task is forked by call_usermodehelper(),
4109  * then control in this thread returns here, without waiting for the
4110  * release agent task.  We don't bother to wait because the caller of
4111  * this routine has no use for the exit status of the release agent
4112  * task, so no sense holding our caller up for that.
4113  */
4114 static void cgroup_release_agent(struct work_struct *work)
4115 {
4116         BUG_ON(work != &release_agent_work);
4117         mutex_lock(&cgroup_mutex);
4118         spin_lock(&release_list_lock);
4119         while (!list_empty(&release_list)) {
4120                 char *argv[3], *envp[3];
4121                 int i;
4122                 char *pathbuf = NULL, *agentbuf = NULL;
4123                 struct cgroup *cgrp = list_entry(release_list.next,
4124                                                     struct cgroup,
4125                                                     release_list);
4126                 list_del_init(&cgrp->release_list);
4127                 spin_unlock(&release_list_lock);
4128                 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4129                 if (!pathbuf)
4130                         goto continue_free;
4131                 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
4132                         goto continue_free;
4133                 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
4134                 if (!agentbuf)
4135                         goto continue_free;
4136
4137                 i = 0;
4138                 argv[i++] = agentbuf;
4139                 argv[i++] = pathbuf;
4140                 argv[i] = NULL;
4141
4142                 i = 0;
4143                 /* minimal command environment */
4144                 envp[i++] = "HOME=/";
4145                 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
4146                 envp[i] = NULL;
4147
4148                 /* Drop the lock while we invoke the usermode helper,
4149                  * since the exec could involve hitting disk and hence
4150                  * be a slow process */
4151                 mutex_unlock(&cgroup_mutex);
4152                 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
4153                 mutex_lock(&cgroup_mutex);
4154  continue_free:
4155                 kfree(pathbuf);
4156                 kfree(agentbuf);
4157                 spin_lock(&release_list_lock);
4158         }
4159         spin_unlock(&release_list_lock);
4160         mutex_unlock(&cgroup_mutex);
4161 }
4162
4163 static int __init cgroup_disable(char *str)
4164 {
4165         int i;
4166         char *token;
4167
4168         while ((token = strsep(&str, ",")) != NULL) {
4169                 if (!*token)
4170                         continue;
4171                 /*
4172                  * cgroup_disable, being at boot time, can't know about module
4173                  * subsystems, so we don't worry about them.
4174                  */
4175                 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
4176                         struct cgroup_subsys *ss = subsys[i];
4177
4178                         if (!strcmp(token, ss->name)) {
4179                                 ss->disabled = 1;
4180                                 printk(KERN_INFO "Disabling %s control group"
4181                                         " subsystem\n", ss->name);
4182                                 break;
4183                         }
4184                 }
4185         }
4186         return 1;
4187 }
4188 __setup("cgroup_disable=", cgroup_disable);
4189
4190 /*
4191  * Functons for CSS ID.
4192  */
4193
4194 /*
4195  *To get ID other than 0, this should be called when !cgroup_is_removed().
4196  */
4197 unsigned short css_id(struct cgroup_subsys_state *css)
4198 {
4199         struct css_id *cssid = rcu_dereference(css->id);
4200
4201         if (cssid)
4202                 return cssid->id;
4203         return 0;
4204 }
4205 EXPORT_SYMBOL_GPL(css_id);
4206
4207 unsigned short css_depth(struct cgroup_subsys_state *css)
4208 {
4209         struct css_id *cssid = rcu_dereference(css->id);
4210
4211         if (cssid)
4212                 return cssid->depth;
4213         return 0;
4214 }
4215 EXPORT_SYMBOL_GPL(css_depth);
4216
4217 bool css_is_ancestor(struct cgroup_subsys_state *child,
4218                     const struct cgroup_subsys_state *root)
4219 {
4220         struct css_id *child_id = rcu_dereference(child->id);
4221         struct css_id *root_id = rcu_dereference(root->id);
4222
4223         if (!child_id || !root_id || (child_id->depth < root_id->depth))
4224                 return false;
4225         return child_id->stack[root_id->depth] == root_id->id;
4226 }
4227
4228 static void __free_css_id_cb(struct rcu_head *head)
4229 {
4230         struct css_id *id;
4231
4232         id = container_of(head, struct css_id, rcu_head);
4233         kfree(id);
4234 }
4235
4236 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
4237 {
4238         struct css_id *id = css->id;
4239         /* When this is called before css_id initialization, id can be NULL */
4240         if (!id)
4241                 return;
4242
4243         BUG_ON(!ss->use_id);
4244
4245         rcu_assign_pointer(id->css, NULL);
4246         rcu_assign_pointer(css->id, NULL);
4247         spin_lock(&ss->id_lock);
4248         idr_remove(&ss->idr, id->id);
4249         spin_unlock(&ss->id_lock);
4250         call_rcu(&id->rcu_head, __free_css_id_cb);
4251 }
4252 EXPORT_SYMBOL_GPL(free_css_id);
4253
4254 /*
4255  * This is called by init or create(). Then, calls to this function are
4256  * always serialized (By cgroup_mutex() at create()).
4257  */
4258
4259 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
4260 {
4261         struct css_id *newid;
4262         int myid, error, size;
4263
4264         BUG_ON(!ss->use_id);
4265
4266         size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
4267         newid = kzalloc(size, GFP_KERNEL);
4268         if (!newid)
4269                 return ERR_PTR(-ENOMEM);
4270         /* get id */
4271         if (unlikely(!idr_pre_get(&ss->idr, GFP_KERNEL))) {
4272                 error = -ENOMEM;
4273                 goto err_out;
4274         }
4275         spin_lock(&ss->id_lock);
4276         /* Don't use 0. allocates an ID of 1-65535 */
4277         error = idr_get_new_above(&ss->idr, newid, 1, &myid);
4278         spin_unlock(&ss->id_lock);
4279
4280         /* Returns error when there are no free spaces for new ID.*/
4281         if (error) {
4282                 error = -ENOSPC;
4283                 goto err_out;
4284         }
4285         if (myid > CSS_ID_MAX)
4286                 goto remove_idr;
4287
4288         newid->id = myid;
4289         newid->depth = depth;
4290         return newid;
4291 remove_idr:
4292         error = -ENOSPC;
4293         spin_lock(&ss->id_lock);
4294         idr_remove(&ss->idr, myid);
4295         spin_unlock(&ss->id_lock);
4296 err_out:
4297         kfree(newid);
4298         return ERR_PTR(error);
4299
4300 }
4301
4302 static int __init_or_module cgroup_init_idr(struct cgroup_subsys *ss,
4303                                             struct cgroup_subsys_state *rootcss)
4304 {
4305         struct css_id *newid;
4306
4307         spin_lock_init(&ss->id_lock);
4308         idr_init(&ss->idr);
4309
4310         newid = get_new_cssid(ss, 0);
4311         if (IS_ERR(newid))
4312                 return PTR_ERR(newid);
4313
4314         newid->stack[0] = newid->id;
4315         newid->css = rootcss;
4316         rootcss->id = newid;
4317         return 0;
4318 }
4319
4320 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
4321                         struct cgroup *child)
4322 {
4323         int subsys_id, i, depth = 0;
4324         struct cgroup_subsys_state *parent_css, *child_css;
4325         struct css_id *child_id, *parent_id = NULL;
4326
4327         subsys_id = ss->subsys_id;
4328         parent_css = parent->subsys[subsys_id];
4329         child_css = child->subsys[subsys_id];
4330         depth = css_depth(parent_css) + 1;
4331         parent_id = parent_css->id;
4332
4333         child_id = get_new_cssid(ss, depth);
4334         if (IS_ERR(child_id))
4335                 return PTR_ERR(child_id);
4336
4337         for (i = 0; i < depth; i++)
4338                 child_id->stack[i] = parent_id->stack[i];
4339         child_id->stack[depth] = child_id->id;
4340         /*
4341          * child_id->css pointer will be set after this cgroup is available
4342          * see cgroup_populate_dir()
4343          */
4344         rcu_assign_pointer(child_css->id, child_id);
4345
4346         return 0;
4347 }
4348
4349 /**
4350  * css_lookup - lookup css by id
4351  * @ss: cgroup subsys to be looked into.
4352  * @id: the id
4353  *
4354  * Returns pointer to cgroup_subsys_state if there is valid one with id.
4355  * NULL if not. Should be called under rcu_read_lock()
4356  */
4357 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
4358 {
4359         struct css_id *cssid = NULL;
4360
4361         BUG_ON(!ss->use_id);
4362         cssid = idr_find(&ss->idr, id);
4363
4364         if (unlikely(!cssid))
4365                 return NULL;
4366
4367         return rcu_dereference(cssid->css);
4368 }
4369 EXPORT_SYMBOL_GPL(css_lookup);
4370
4371 /**
4372  * css_get_next - lookup next cgroup under specified hierarchy.
4373  * @ss: pointer to subsystem
4374  * @id: current position of iteration.
4375  * @root: pointer to css. search tree under this.
4376  * @foundid: position of found object.
4377  *
4378  * Search next css under the specified hierarchy of rootid. Calling under
4379  * rcu_read_lock() is necessary. Returns NULL if it reaches the end.
4380  */
4381 struct cgroup_subsys_state *
4382 css_get_next(struct cgroup_subsys *ss, int id,
4383              struct cgroup_subsys_state *root, int *foundid)
4384 {
4385         struct cgroup_subsys_state *ret = NULL;
4386         struct css_id *tmp;
4387         int tmpid;
4388         int rootid = css_id(root);
4389         int depth = css_depth(root);
4390
4391         if (!rootid)
4392                 return NULL;
4393
4394         BUG_ON(!ss->use_id);
4395         /* fill start point for scan */
4396         tmpid = id;
4397         while (1) {
4398                 /*
4399                  * scan next entry from bitmap(tree), tmpid is updated after
4400                  * idr_get_next().
4401                  */
4402                 spin_lock(&ss->id_lock);
4403                 tmp = idr_get_next(&ss->idr, &tmpid);
4404                 spin_unlock(&ss->id_lock);
4405
4406                 if (!tmp)
4407                         break;
4408                 if (tmp->depth >= depth && tmp->stack[depth] == rootid) {
4409                         ret = rcu_dereference(tmp->css);
4410                         if (ret) {
4411                                 *foundid = tmpid;
4412                                 break;
4413                         }
4414                 }
4415                 /* continue to scan from next id */
4416                 tmpid = tmpid + 1;
4417         }
4418         return ret;
4419 }
4420
4421 #ifdef CONFIG_CGROUP_DEBUG
4422 static struct cgroup_subsys_state *debug_create(struct cgroup_subsys *ss,
4423                                                    struct cgroup *cont)
4424 {
4425         struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
4426
4427         if (!css)
4428                 return ERR_PTR(-ENOMEM);
4429
4430         return css;
4431 }
4432
4433 static void debug_destroy(struct cgroup_subsys *ss, struct cgroup *cont)
4434 {
4435         kfree(cont->subsys[debug_subsys_id]);
4436 }
4437
4438 static u64 cgroup_refcount_read(struct cgroup *cont, struct cftype *cft)
4439 {
4440         return atomic_read(&cont->count);
4441 }
4442
4443 static u64 debug_taskcount_read(struct cgroup *cont, struct cftype *cft)
4444 {
4445         return cgroup_task_count(cont);
4446 }
4447
4448 static u64 current_css_set_read(struct cgroup *cont, struct cftype *cft)
4449 {
4450         return (u64)(unsigned long)current->cgroups;
4451 }
4452
4453 static u64 current_css_set_refcount_read(struct cgroup *cont,
4454                                            struct cftype *cft)
4455 {
4456         u64 count;
4457
4458         rcu_read_lock();
4459         count = atomic_read(&current->cgroups->refcount);
4460         rcu_read_unlock();
4461         return count;
4462 }
4463
4464 static int current_css_set_cg_links_read(struct cgroup *cont,
4465                                          struct cftype *cft,
4466                                          struct seq_file *seq)
4467 {
4468         struct cg_cgroup_link *link;
4469         struct css_set *cg;
4470
4471         read_lock(&css_set_lock);
4472         rcu_read_lock();
4473         cg = rcu_dereference(current->cgroups);
4474         list_for_each_entry(link, &cg->cg_links, cg_link_list) {
4475                 struct cgroup *c = link->cgrp;
4476                 const char *name;
4477
4478                 if (c->dentry)
4479                         name = c->dentry->d_name.name;
4480                 else
4481                         name = "?";
4482                 seq_printf(seq, "Root %d group %s\n",
4483                            c->root->hierarchy_id, name);
4484         }
4485         rcu_read_unlock();
4486         read_unlock(&css_set_lock);
4487         return 0;
4488 }
4489
4490 #define MAX_TASKS_SHOWN_PER_CSS 25
4491 static int cgroup_css_links_read(struct cgroup *cont,
4492                                  struct cftype *cft,
4493                                  struct seq_file *seq)
4494 {
4495         struct cg_cgroup_link *link;
4496
4497         read_lock(&css_set_lock);
4498         list_for_each_entry(link, &cont->css_sets, cgrp_link_list) {
4499                 struct css_set *cg = link->cg;
4500                 struct task_struct *task;
4501                 int count = 0;
4502                 seq_printf(seq, "css_set %p\n", cg);
4503                 list_for_each_entry(task, &cg->tasks, cg_list) {
4504                         if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
4505                                 seq_puts(seq, "  ...\n");
4506                                 break;
4507                         } else {
4508                                 seq_printf(seq, "  task %d\n",
4509                                            task_pid_vnr(task));
4510                         }
4511                 }
4512         }
4513         read_unlock(&css_set_lock);
4514         return 0;
4515 }
4516
4517 static u64 releasable_read(struct cgroup *cgrp, struct cftype *cft)
4518 {
4519         return test_bit(CGRP_RELEASABLE, &cgrp->flags);
4520 }
4521
4522 static struct cftype debug_files[] =  {
4523         {
4524                 .name = "cgroup_refcount",
4525                 .read_u64 = cgroup_refcount_read,
4526         },
4527         {
4528                 .name = "taskcount",
4529                 .read_u64 = debug_taskcount_read,
4530         },
4531
4532         {
4533                 .name = "current_css_set",
4534                 .read_u64 = current_css_set_read,
4535         },
4536
4537         {
4538                 .name = "current_css_set_refcount",
4539                 .read_u64 = current_css_set_refcount_read,
4540         },
4541
4542         {
4543                 .name = "current_css_set_cg_links",
4544                 .read_seq_string = current_css_set_cg_links_read,
4545         },
4546
4547         {
4548                 .name = "cgroup_css_links",
4549                 .read_seq_string = cgroup_css_links_read,
4550         },
4551
4552         {
4553                 .name = "releasable",
4554                 .read_u64 = releasable_read,
4555         },
4556 };
4557
4558 static int debug_populate(struct cgroup_subsys *ss, struct cgroup *cont)
4559 {
4560         return cgroup_add_files(cont, ss, debug_files,
4561                                 ARRAY_SIZE(debug_files));
4562 }
4563
4564 struct cgroup_subsys debug_subsys = {
4565         .name = "debug",
4566         .create = debug_create,
4567         .destroy = debug_destroy,
4568         .populate = debug_populate,
4569         .subsys_id = debug_subsys_id,
4570 };
4571 #endif /* CONFIG_CGROUP_DEBUG */