cgroups: clean up cgroup_pidlist_find() a bit
[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 = current->nsproxy->pid_ns;
2601
2602         /*
2603          * We can't drop the pidlist_mutex before taking the l->mutex in case
2604          * the last ref-holder is trying to remove l from the list at the same
2605          * time. Holding the pidlist_mutex precludes somebody taking whichever
2606          * list we find out from under us - compare release_pid_array().
2607          */
2608         mutex_lock(&cgrp->pidlist_mutex);
2609         list_for_each_entry(l, &cgrp->pidlists, links) {
2610                 if (l->key.type == type && l->key.ns == ns) {
2611                         /* make sure l doesn't vanish out from under us */
2612                         down_write(&l->mutex);
2613                         mutex_unlock(&cgrp->pidlist_mutex);
2614                         return l;
2615                 }
2616         }
2617         /* entry not found; create a new one */
2618         l = kmalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
2619         if (!l) {
2620                 mutex_unlock(&cgrp->pidlist_mutex);
2621                 return l;
2622         }
2623         init_rwsem(&l->mutex);
2624         down_write(&l->mutex);
2625         l->key.type = type;
2626         l->key.ns = get_pid_ns(ns);
2627         l->use_count = 0; /* don't increment here */
2628         l->list = NULL;
2629         l->owner = cgrp;
2630         list_add(&l->links, &cgrp->pidlists);
2631         mutex_unlock(&cgrp->pidlist_mutex);
2632         return l;
2633 }
2634
2635 /*
2636  * Load a cgroup's pidarray with either procs' tgids or tasks' pids
2637  */
2638 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
2639                               struct cgroup_pidlist **lp)
2640 {
2641         pid_t *array;
2642         int length;
2643         int pid, n = 0; /* used for populating the array */
2644         struct cgroup_iter it;
2645         struct task_struct *tsk;
2646         struct cgroup_pidlist *l;
2647
2648         /*
2649          * If cgroup gets more users after we read count, we won't have
2650          * enough space - tough.  This race is indistinguishable to the
2651          * caller from the case that the additional cgroup users didn't
2652          * show up until sometime later on.
2653          */
2654         length = cgroup_task_count(cgrp);
2655         array = pidlist_allocate(length);
2656         if (!array)
2657                 return -ENOMEM;
2658         /* now, populate the array */
2659         cgroup_iter_start(cgrp, &it);
2660         while ((tsk = cgroup_iter_next(cgrp, &it))) {
2661                 if (unlikely(n == length))
2662                         break;
2663                 /* get tgid or pid for procs or tasks file respectively */
2664                 if (type == CGROUP_FILE_PROCS)
2665                         pid = task_tgid_vnr(tsk);
2666                 else
2667                         pid = task_pid_vnr(tsk);
2668                 if (pid > 0) /* make sure to only use valid results */
2669                         array[n++] = pid;
2670         }
2671         cgroup_iter_end(cgrp, &it);
2672         length = n;
2673         /* now sort & (if procs) strip out duplicates */
2674         sort(array, length, sizeof(pid_t), cmppid, NULL);
2675         if (type == CGROUP_FILE_PROCS)
2676                 length = pidlist_uniq(&array, length);
2677         l = cgroup_pidlist_find(cgrp, type);
2678         if (!l) {
2679                 pidlist_free(array);
2680                 return -ENOMEM;
2681         }
2682         /* store array, freeing old if necessary - lock already held */
2683         pidlist_free(l->list);
2684         l->list = array;
2685         l->length = length;
2686         l->use_count++;
2687         up_write(&l->mutex);
2688         *lp = l;
2689         return 0;
2690 }
2691
2692 /**
2693  * cgroupstats_build - build and fill cgroupstats
2694  * @stats: cgroupstats to fill information into
2695  * @dentry: A dentry entry belonging to the cgroup for which stats have
2696  * been requested.
2697  *
2698  * Build and fill cgroupstats so that taskstats can export it to user
2699  * space.
2700  */
2701 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
2702 {
2703         int ret = -EINVAL;
2704         struct cgroup *cgrp;
2705         struct cgroup_iter it;
2706         struct task_struct *tsk;
2707
2708         /*
2709          * Validate dentry by checking the superblock operations,
2710          * and make sure it's a directory.
2711          */
2712         if (dentry->d_sb->s_op != &cgroup_ops ||
2713             !S_ISDIR(dentry->d_inode->i_mode))
2714                  goto err;
2715
2716         ret = 0;
2717         cgrp = dentry->d_fsdata;
2718
2719         cgroup_iter_start(cgrp, &it);
2720         while ((tsk = cgroup_iter_next(cgrp, &it))) {
2721                 switch (tsk->state) {
2722                 case TASK_RUNNING:
2723                         stats->nr_running++;
2724                         break;
2725                 case TASK_INTERRUPTIBLE:
2726                         stats->nr_sleeping++;
2727                         break;
2728                 case TASK_UNINTERRUPTIBLE:
2729                         stats->nr_uninterruptible++;
2730                         break;
2731                 case TASK_STOPPED:
2732                         stats->nr_stopped++;
2733                         break;
2734                 default:
2735                         if (delayacct_is_task_waiting_on_io(tsk))
2736                                 stats->nr_io_wait++;
2737                         break;
2738                 }
2739         }
2740         cgroup_iter_end(cgrp, &it);
2741
2742 err:
2743         return ret;
2744 }
2745
2746
2747 /*
2748  * seq_file methods for the tasks/procs files. The seq_file position is the
2749  * next pid to display; the seq_file iterator is a pointer to the pid
2750  * in the cgroup->l->list array.
2751  */
2752
2753 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
2754 {
2755         /*
2756          * Initially we receive a position value that corresponds to
2757          * one more than the last pid shown (or 0 on the first call or
2758          * after a seek to the start). Use a binary-search to find the
2759          * next pid to display, if any
2760          */
2761         struct cgroup_pidlist *l = s->private;
2762         int index = 0, pid = *pos;
2763         int *iter;
2764
2765         down_read(&l->mutex);
2766         if (pid) {
2767                 int end = l->length;
2768
2769                 while (index < end) {
2770                         int mid = (index + end) / 2;
2771                         if (l->list[mid] == pid) {
2772                                 index = mid;
2773                                 break;
2774                         } else if (l->list[mid] <= pid)
2775                                 index = mid + 1;
2776                         else
2777                                 end = mid;
2778                 }
2779         }
2780         /* If we're off the end of the array, we're done */
2781         if (index >= l->length)
2782                 return NULL;
2783         /* Update the abstract position to be the actual pid that we found */
2784         iter = l->list + index;
2785         *pos = *iter;
2786         return iter;
2787 }
2788
2789 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
2790 {
2791         struct cgroup_pidlist *l = s->private;
2792         up_read(&l->mutex);
2793 }
2794
2795 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
2796 {
2797         struct cgroup_pidlist *l = s->private;
2798         pid_t *p = v;
2799         pid_t *end = l->list + l->length;
2800         /*
2801          * Advance to the next pid in the array. If this goes off the
2802          * end, we're done
2803          */
2804         p++;
2805         if (p >= end) {
2806                 return NULL;
2807         } else {
2808                 *pos = *p;
2809                 return p;
2810         }
2811 }
2812
2813 static int cgroup_pidlist_show(struct seq_file *s, void *v)
2814 {
2815         return seq_printf(s, "%d\n", *(int *)v);
2816 }
2817
2818 /*
2819  * seq_operations functions for iterating on pidlists through seq_file -
2820  * independent of whether it's tasks or procs
2821  */
2822 static const struct seq_operations cgroup_pidlist_seq_operations = {
2823         .start = cgroup_pidlist_start,
2824         .stop = cgroup_pidlist_stop,
2825         .next = cgroup_pidlist_next,
2826         .show = cgroup_pidlist_show,
2827 };
2828
2829 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
2830 {
2831         /*
2832          * the case where we're the last user of this particular pidlist will
2833          * have us remove it from the cgroup's list, which entails taking the
2834          * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
2835          * pidlist_mutex, we have to take pidlist_mutex first.
2836          */
2837         mutex_lock(&l->owner->pidlist_mutex);
2838         down_write(&l->mutex);
2839         BUG_ON(!l->use_count);
2840         if (!--l->use_count) {
2841                 /* we're the last user if refcount is 0; remove and free */
2842                 list_del(&l->links);
2843                 mutex_unlock(&l->owner->pidlist_mutex);
2844                 pidlist_free(l->list);
2845                 put_pid_ns(l->key.ns);
2846                 up_write(&l->mutex);
2847                 kfree(l);
2848                 return;
2849         }
2850         mutex_unlock(&l->owner->pidlist_mutex);
2851         up_write(&l->mutex);
2852 }
2853
2854 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
2855 {
2856         struct cgroup_pidlist *l;
2857         if (!(file->f_mode & FMODE_READ))
2858                 return 0;
2859         /*
2860          * the seq_file will only be initialized if the file was opened for
2861          * reading; hence we check if it's not null only in that case.
2862          */
2863         l = ((struct seq_file *)file->private_data)->private;
2864         cgroup_release_pid_array(l);
2865         return seq_release(inode, file);
2866 }
2867
2868 static const struct file_operations cgroup_pidlist_operations = {
2869         .read = seq_read,
2870         .llseek = seq_lseek,
2871         .write = cgroup_file_write,
2872         .release = cgroup_pidlist_release,
2873 };
2874
2875 /*
2876  * The following functions handle opens on a file that displays a pidlist
2877  * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
2878  * in the cgroup.
2879  */
2880 /* helper function for the two below it */
2881 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
2882 {
2883         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2884         struct cgroup_pidlist *l;
2885         int retval;
2886
2887         /* Nothing to do for write-only files */
2888         if (!(file->f_mode & FMODE_READ))
2889                 return 0;
2890
2891         /* have the array populated */
2892         retval = pidlist_array_load(cgrp, type, &l);
2893         if (retval)
2894                 return retval;
2895         /* configure file information */
2896         file->f_op = &cgroup_pidlist_operations;
2897
2898         retval = seq_open(file, &cgroup_pidlist_seq_operations);
2899         if (retval) {
2900                 cgroup_release_pid_array(l);
2901                 return retval;
2902         }
2903         ((struct seq_file *)file->private_data)->private = l;
2904         return 0;
2905 }
2906 static int cgroup_tasks_open(struct inode *unused, struct file *file)
2907 {
2908         return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
2909 }
2910 static int cgroup_procs_open(struct inode *unused, struct file *file)
2911 {
2912         return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
2913 }
2914
2915 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
2916                                             struct cftype *cft)
2917 {
2918         return notify_on_release(cgrp);
2919 }
2920
2921 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
2922                                           struct cftype *cft,
2923                                           u64 val)
2924 {
2925         clear_bit(CGRP_RELEASABLE, &cgrp->flags);
2926         if (val)
2927                 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2928         else
2929                 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2930         return 0;
2931 }
2932
2933 /*
2934  * for the common functions, 'private' gives the type of file
2935  */
2936 /* for hysterical raisins, we can't put this on the older files */
2937 #define CGROUP_FILE_GENERIC_PREFIX "cgroup."
2938 static struct cftype files[] = {
2939         {
2940                 .name = "tasks",
2941                 .open = cgroup_tasks_open,
2942                 .write_u64 = cgroup_tasks_write,
2943                 .release = cgroup_pidlist_release,
2944                 .mode = S_IRUGO | S_IWUSR,
2945         },
2946         {
2947                 .name = CGROUP_FILE_GENERIC_PREFIX "procs",
2948                 .open = cgroup_procs_open,
2949                 /* .write_u64 = cgroup_procs_write, TODO */
2950                 .release = cgroup_pidlist_release,
2951                 .mode = S_IRUGO,
2952         },
2953         {
2954                 .name = "notify_on_release",
2955                 .read_u64 = cgroup_read_notify_on_release,
2956                 .write_u64 = cgroup_write_notify_on_release,
2957         },
2958 };
2959
2960 static struct cftype cft_release_agent = {
2961         .name = "release_agent",
2962         .read_seq_string = cgroup_release_agent_show,
2963         .write_string = cgroup_release_agent_write,
2964         .max_write_len = PATH_MAX,
2965 };
2966
2967 static int cgroup_populate_dir(struct cgroup *cgrp)
2968 {
2969         int err;
2970         struct cgroup_subsys *ss;
2971
2972         /* First clear out any existing files */
2973         cgroup_clear_directory(cgrp->dentry);
2974
2975         err = cgroup_add_files(cgrp, NULL, files, ARRAY_SIZE(files));
2976         if (err < 0)
2977                 return err;
2978
2979         if (cgrp == cgrp->top_cgroup) {
2980                 if ((err = cgroup_add_file(cgrp, NULL, &cft_release_agent)) < 0)
2981                         return err;
2982         }
2983
2984         for_each_subsys(cgrp->root, ss) {
2985                 if (ss->populate && (err = ss->populate(ss, cgrp)) < 0)
2986                         return err;
2987         }
2988         /* This cgroup is ready now */
2989         for_each_subsys(cgrp->root, ss) {
2990                 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
2991                 /*
2992                  * Update id->css pointer and make this css visible from
2993                  * CSS ID functions. This pointer will be dereferened
2994                  * from RCU-read-side without locks.
2995                  */
2996                 if (css->id)
2997                         rcu_assign_pointer(css->id->css, css);
2998         }
2999
3000         return 0;
3001 }
3002
3003 static void init_cgroup_css(struct cgroup_subsys_state *css,
3004                                struct cgroup_subsys *ss,
3005                                struct cgroup *cgrp)
3006 {
3007         css->cgroup = cgrp;
3008         atomic_set(&css->refcnt, 1);
3009         css->flags = 0;
3010         css->id = NULL;
3011         if (cgrp == dummytop)
3012                 set_bit(CSS_ROOT, &css->flags);
3013         BUG_ON(cgrp->subsys[ss->subsys_id]);
3014         cgrp->subsys[ss->subsys_id] = css;
3015 }
3016
3017 static void cgroup_lock_hierarchy(struct cgroupfs_root *root)
3018 {
3019         /* We need to take each hierarchy_mutex in a consistent order */
3020         int i;
3021
3022         /*
3023          * No worry about a race with rebind_subsystems that might mess up the
3024          * locking order, since both parties are under cgroup_mutex.
3025          */
3026         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3027                 struct cgroup_subsys *ss = subsys[i];
3028                 if (ss == NULL)
3029                         continue;
3030                 if (ss->root == root)
3031                         mutex_lock(&ss->hierarchy_mutex);
3032         }
3033 }
3034
3035 static void cgroup_unlock_hierarchy(struct cgroupfs_root *root)
3036 {
3037         int i;
3038
3039         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3040                 struct cgroup_subsys *ss = subsys[i];
3041                 if (ss == NULL)
3042                         continue;
3043                 if (ss->root == root)
3044                         mutex_unlock(&ss->hierarchy_mutex);
3045         }
3046 }
3047
3048 /*
3049  * cgroup_create - create a cgroup
3050  * @parent: cgroup that will be parent of the new cgroup
3051  * @dentry: dentry of the new cgroup
3052  * @mode: mode to set on new inode
3053  *
3054  * Must be called with the mutex on the parent inode held
3055  */
3056 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
3057                              mode_t mode)
3058 {
3059         struct cgroup *cgrp;
3060         struct cgroupfs_root *root = parent->root;
3061         int err = 0;
3062         struct cgroup_subsys *ss;
3063         struct super_block *sb = root->sb;
3064
3065         cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
3066         if (!cgrp)
3067                 return -ENOMEM;
3068
3069         /* Grab a reference on the superblock so the hierarchy doesn't
3070          * get deleted on unmount if there are child cgroups.  This
3071          * can be done outside cgroup_mutex, since the sb can't
3072          * disappear while someone has an open control file on the
3073          * fs */
3074         atomic_inc(&sb->s_active);
3075
3076         mutex_lock(&cgroup_mutex);
3077
3078         init_cgroup_housekeeping(cgrp);
3079
3080         cgrp->parent = parent;
3081         cgrp->root = parent->root;
3082         cgrp->top_cgroup = parent->top_cgroup;
3083
3084         if (notify_on_release(parent))
3085                 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3086
3087         for_each_subsys(root, ss) {
3088                 struct cgroup_subsys_state *css = ss->create(ss, cgrp);
3089
3090                 if (IS_ERR(css)) {
3091                         err = PTR_ERR(css);
3092                         goto err_destroy;
3093                 }
3094                 init_cgroup_css(css, ss, cgrp);
3095                 if (ss->use_id) {
3096                         err = alloc_css_id(ss, parent, cgrp);
3097                         if (err)
3098                                 goto err_destroy;
3099                 }
3100                 /* At error, ->destroy() callback has to free assigned ID. */
3101         }
3102
3103         cgroup_lock_hierarchy(root);
3104         list_add(&cgrp->sibling, &cgrp->parent->children);
3105         cgroup_unlock_hierarchy(root);
3106         root->number_of_cgroups++;
3107
3108         err = cgroup_create_dir(cgrp, dentry, mode);
3109         if (err < 0)
3110                 goto err_remove;
3111
3112         /* The cgroup directory was pre-locked for us */
3113         BUG_ON(!mutex_is_locked(&cgrp->dentry->d_inode->i_mutex));
3114
3115         err = cgroup_populate_dir(cgrp);
3116         /* If err < 0, we have a half-filled directory - oh well ;) */
3117
3118         mutex_unlock(&cgroup_mutex);
3119         mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
3120
3121         return 0;
3122
3123  err_remove:
3124
3125         cgroup_lock_hierarchy(root);
3126         list_del(&cgrp->sibling);
3127         cgroup_unlock_hierarchy(root);
3128         root->number_of_cgroups--;
3129
3130  err_destroy:
3131
3132         for_each_subsys(root, ss) {
3133                 if (cgrp->subsys[ss->subsys_id])
3134                         ss->destroy(ss, cgrp);
3135         }
3136
3137         mutex_unlock(&cgroup_mutex);
3138
3139         /* Release the reference count that we took on the superblock */
3140         deactivate_super(sb);
3141
3142         kfree(cgrp);
3143         return err;
3144 }
3145
3146 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode)
3147 {
3148         struct cgroup *c_parent = dentry->d_parent->d_fsdata;
3149
3150         /* the vfs holds inode->i_mutex already */
3151         return cgroup_create(c_parent, dentry, mode | S_IFDIR);
3152 }
3153
3154 static int cgroup_has_css_refs(struct cgroup *cgrp)
3155 {
3156         /* Check the reference count on each subsystem. Since we
3157          * already established that there are no tasks in the
3158          * cgroup, if the css refcount is also 1, then there should
3159          * be no outstanding references, so the subsystem is safe to
3160          * destroy. We scan across all subsystems rather than using
3161          * the per-hierarchy linked list of mounted subsystems since
3162          * we can be called via check_for_release() with no
3163          * synchronization other than RCU, and the subsystem linked
3164          * list isn't RCU-safe */
3165         int i;
3166         /*
3167          * We won't need to lock the subsys array, because the subsystems
3168          * we're concerned about aren't going anywhere since our cgroup root
3169          * has a reference on them.
3170          */
3171         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3172                 struct cgroup_subsys *ss = subsys[i];
3173                 struct cgroup_subsys_state *css;
3174                 /* Skip subsystems not present or not in this hierarchy */
3175                 if (ss == NULL || ss->root != cgrp->root)
3176                         continue;
3177                 css = cgrp->subsys[ss->subsys_id];
3178                 /* When called from check_for_release() it's possible
3179                  * that by this point the cgroup has been removed
3180                  * and the css deleted. But a false-positive doesn't
3181                  * matter, since it can only happen if the cgroup
3182                  * has been deleted and hence no longer needs the
3183                  * release agent to be called anyway. */
3184                 if (css && (atomic_read(&css->refcnt) > 1))
3185                         return 1;
3186         }
3187         return 0;
3188 }
3189
3190 /*
3191  * Atomically mark all (or else none) of the cgroup's CSS objects as
3192  * CSS_REMOVED. Return true on success, or false if the cgroup has
3193  * busy subsystems. Call with cgroup_mutex held
3194  */
3195
3196 static int cgroup_clear_css_refs(struct cgroup *cgrp)
3197 {
3198         struct cgroup_subsys *ss;
3199         unsigned long flags;
3200         bool failed = false;
3201         local_irq_save(flags);
3202         for_each_subsys(cgrp->root, ss) {
3203                 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
3204                 int refcnt;
3205                 while (1) {
3206                         /* We can only remove a CSS with a refcnt==1 */
3207                         refcnt = atomic_read(&css->refcnt);
3208                         if (refcnt > 1) {
3209                                 failed = true;
3210                                 goto done;
3211                         }
3212                         BUG_ON(!refcnt);
3213                         /*
3214                          * Drop the refcnt to 0 while we check other
3215                          * subsystems. This will cause any racing
3216                          * css_tryget() to spin until we set the
3217                          * CSS_REMOVED bits or abort
3218                          */
3219                         if (atomic_cmpxchg(&css->refcnt, refcnt, 0) == refcnt)
3220                                 break;
3221                         cpu_relax();
3222                 }
3223         }
3224  done:
3225         for_each_subsys(cgrp->root, ss) {
3226                 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
3227                 if (failed) {
3228                         /*
3229                          * Restore old refcnt if we previously managed
3230                          * to clear it from 1 to 0
3231                          */
3232                         if (!atomic_read(&css->refcnt))
3233                                 atomic_set(&css->refcnt, 1);
3234                 } else {
3235                         /* Commit the fact that the CSS is removed */
3236                         set_bit(CSS_REMOVED, &css->flags);
3237                 }
3238         }
3239         local_irq_restore(flags);
3240         return !failed;
3241 }
3242
3243 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
3244 {
3245         struct cgroup *cgrp = dentry->d_fsdata;
3246         struct dentry *d;
3247         struct cgroup *parent;
3248         DEFINE_WAIT(wait);
3249         int ret;
3250
3251         /* the vfs holds both inode->i_mutex already */
3252 again:
3253         mutex_lock(&cgroup_mutex);
3254         if (atomic_read(&cgrp->count) != 0) {
3255                 mutex_unlock(&cgroup_mutex);
3256                 return -EBUSY;
3257         }
3258         if (!list_empty(&cgrp->children)) {
3259                 mutex_unlock(&cgroup_mutex);
3260                 return -EBUSY;
3261         }
3262         mutex_unlock(&cgroup_mutex);
3263
3264         /*
3265          * In general, subsystem has no css->refcnt after pre_destroy(). But
3266          * in racy cases, subsystem may have to get css->refcnt after
3267          * pre_destroy() and it makes rmdir return with -EBUSY. This sometimes
3268          * make rmdir return -EBUSY too often. To avoid that, we use waitqueue
3269          * for cgroup's rmdir. CGRP_WAIT_ON_RMDIR is for synchronizing rmdir
3270          * and subsystem's reference count handling. Please see css_get/put
3271          * and css_tryget() and cgroup_wakeup_rmdir_waiter() implementation.
3272          */
3273         set_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3274
3275         /*
3276          * Call pre_destroy handlers of subsys. Notify subsystems
3277          * that rmdir() request comes.
3278          */
3279         ret = cgroup_call_pre_destroy(cgrp);
3280         if (ret) {
3281                 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3282                 return ret;
3283         }
3284
3285         mutex_lock(&cgroup_mutex);
3286         parent = cgrp->parent;
3287         if (atomic_read(&cgrp->count) || !list_empty(&cgrp->children)) {
3288                 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3289                 mutex_unlock(&cgroup_mutex);
3290                 return -EBUSY;
3291         }
3292         prepare_to_wait(&cgroup_rmdir_waitq, &wait, TASK_INTERRUPTIBLE);
3293         if (!cgroup_clear_css_refs(cgrp)) {
3294                 mutex_unlock(&cgroup_mutex);
3295                 /*
3296                  * Because someone may call cgroup_wakeup_rmdir_waiter() before
3297                  * prepare_to_wait(), we need to check this flag.
3298                  */
3299                 if (test_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags))
3300                         schedule();
3301                 finish_wait(&cgroup_rmdir_waitq, &wait);
3302                 clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3303                 if (signal_pending(current))
3304                         return -EINTR;
3305                 goto again;
3306         }
3307         /* NO css_tryget() can success after here. */
3308         finish_wait(&cgroup_rmdir_waitq, &wait);
3309         clear_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags);
3310
3311         spin_lock(&release_list_lock);
3312         set_bit(CGRP_REMOVED, &cgrp->flags);
3313         if (!list_empty(&cgrp->release_list))
3314                 list_del(&cgrp->release_list);
3315         spin_unlock(&release_list_lock);
3316
3317         cgroup_lock_hierarchy(cgrp->root);
3318         /* delete this cgroup from parent->children */
3319         list_del(&cgrp->sibling);
3320         cgroup_unlock_hierarchy(cgrp->root);
3321
3322         spin_lock(&cgrp->dentry->d_lock);
3323         d = dget(cgrp->dentry);
3324         spin_unlock(&d->d_lock);
3325
3326         cgroup_d_remove_dir(d);
3327         dput(d);
3328
3329         set_bit(CGRP_RELEASABLE, &parent->flags);
3330         check_for_release(parent);
3331
3332         mutex_unlock(&cgroup_mutex);
3333         return 0;
3334 }
3335
3336 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
3337 {
3338         struct cgroup_subsys_state *css;
3339
3340         printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
3341
3342         /* Create the top cgroup state for this subsystem */
3343         list_add(&ss->sibling, &rootnode.subsys_list);
3344         ss->root = &rootnode;
3345         css = ss->create(ss, dummytop);
3346         /* We don't handle early failures gracefully */
3347         BUG_ON(IS_ERR(css));
3348         init_cgroup_css(css, ss, dummytop);
3349
3350         /* Update the init_css_set to contain a subsys
3351          * pointer to this state - since the subsystem is
3352          * newly registered, all tasks and hence the
3353          * init_css_set is in the subsystem's top cgroup. */
3354         init_css_set.subsys[ss->subsys_id] = dummytop->subsys[ss->subsys_id];
3355
3356         need_forkexit_callback |= ss->fork || ss->exit;
3357
3358         /* At system boot, before all subsystems have been
3359          * registered, no tasks have been forked, so we don't
3360          * need to invoke fork callbacks here. */
3361         BUG_ON(!list_empty(&init_task.tasks));
3362
3363         mutex_init(&ss->hierarchy_mutex);
3364         lockdep_set_class(&ss->hierarchy_mutex, &ss->subsys_key);
3365         ss->active = 1;
3366
3367         /* this function shouldn't be used with modular subsystems, since they
3368          * need to register a subsys_id, among other things */
3369         BUG_ON(ss->module);
3370 }
3371
3372 /**
3373  * cgroup_load_subsys: load and register a modular subsystem at runtime
3374  * @ss: the subsystem to load
3375  *
3376  * This function should be called in a modular subsystem's initcall. If the
3377  * subsytem is built as a module, it will be assigned a new subsys_id and set
3378  * up for use. If the subsystem is built-in anyway, work is delegated to the
3379  * simpler cgroup_init_subsys.
3380  */
3381 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
3382 {
3383         int i;
3384         struct cgroup_subsys_state *css;
3385
3386         /* check name and function validity */
3387         if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
3388             ss->create == NULL || ss->destroy == NULL)
3389                 return -EINVAL;
3390
3391         /*
3392          * we don't support callbacks in modular subsystems. this check is
3393          * before the ss->module check for consistency; a subsystem that could
3394          * be a module should still have no callbacks even if the user isn't
3395          * compiling it as one.
3396          */
3397         if (ss->fork || ss->exit)
3398                 return -EINVAL;
3399
3400         /*
3401          * an optionally modular subsystem is built-in: we want to do nothing,
3402          * since cgroup_init_subsys will have already taken care of it.
3403          */
3404         if (ss->module == NULL) {
3405                 /* a few sanity checks */
3406                 BUG_ON(ss->subsys_id >= CGROUP_BUILTIN_SUBSYS_COUNT);
3407                 BUG_ON(subsys[ss->subsys_id] != ss);
3408                 return 0;
3409         }
3410
3411         /*
3412          * need to register a subsys id before anything else - for example,
3413          * init_cgroup_css needs it.
3414          */
3415         mutex_lock(&cgroup_mutex);
3416         /* find the first empty slot in the array */
3417         for (i = CGROUP_BUILTIN_SUBSYS_COUNT; i < CGROUP_SUBSYS_COUNT; i++) {
3418                 if (subsys[i] == NULL)
3419                         break;
3420         }
3421         if (i == CGROUP_SUBSYS_COUNT) {
3422                 /* maximum number of subsystems already registered! */
3423                 mutex_unlock(&cgroup_mutex);
3424                 return -EBUSY;
3425         }
3426         /* assign ourselves the subsys_id */
3427         ss->subsys_id = i;
3428         subsys[i] = ss;
3429
3430         /*
3431          * no ss->create seems to need anything important in the ss struct, so
3432          * this can happen first (i.e. before the rootnode attachment).
3433          */
3434         css = ss->create(ss, dummytop);
3435         if (IS_ERR(css)) {
3436                 /* failure case - need to deassign the subsys[] slot. */
3437                 subsys[i] = NULL;
3438                 mutex_unlock(&cgroup_mutex);
3439                 return PTR_ERR(css);
3440         }
3441
3442         list_add(&ss->sibling, &rootnode.subsys_list);
3443         ss->root = &rootnode;
3444
3445         /* our new subsystem will be attached to the dummy hierarchy. */
3446         init_cgroup_css(css, ss, dummytop);
3447         /* init_idr must be after init_cgroup_css because it sets css->id. */
3448         if (ss->use_id) {
3449                 int ret = cgroup_init_idr(ss, css);
3450                 if (ret) {
3451                         dummytop->subsys[ss->subsys_id] = NULL;
3452                         ss->destroy(ss, dummytop);
3453                         subsys[i] = NULL;
3454                         mutex_unlock(&cgroup_mutex);
3455                         return ret;
3456                 }
3457         }
3458
3459         /*
3460          * Now we need to entangle the css into the existing css_sets. unlike
3461          * in cgroup_init_subsys, there are now multiple css_sets, so each one
3462          * will need a new pointer to it; done by iterating the css_set_table.
3463          * furthermore, modifying the existing css_sets will corrupt the hash
3464          * table state, so each changed css_set will need its hash recomputed.
3465          * this is all done under the css_set_lock.
3466          */
3467         write_lock(&css_set_lock);
3468         for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
3469                 struct css_set *cg;
3470                 struct hlist_node *node, *tmp;
3471                 struct hlist_head *bucket = &css_set_table[i], *new_bucket;
3472
3473                 hlist_for_each_entry_safe(cg, node, tmp, bucket, hlist) {
3474                         /* skip entries that we already rehashed */
3475                         if (cg->subsys[ss->subsys_id])
3476                                 continue;
3477                         /* remove existing entry */
3478                         hlist_del(&cg->hlist);
3479                         /* set new value */
3480                         cg->subsys[ss->subsys_id] = css;
3481                         /* recompute hash and restore entry */
3482                         new_bucket = css_set_hash(cg->subsys);
3483                         hlist_add_head(&cg->hlist, new_bucket);
3484                 }
3485         }
3486         write_unlock(&css_set_lock);
3487
3488         mutex_init(&ss->hierarchy_mutex);
3489         lockdep_set_class(&ss->hierarchy_mutex, &ss->subsys_key);
3490         ss->active = 1;
3491
3492         /* success! */
3493         mutex_unlock(&cgroup_mutex);
3494         return 0;
3495 }
3496 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
3497
3498 /**
3499  * cgroup_unload_subsys: unload a modular subsystem
3500  * @ss: the subsystem to unload
3501  *
3502  * This function should be called in a modular subsystem's exitcall. When this
3503  * function is invoked, the refcount on the subsystem's module will be 0, so
3504  * the subsystem will not be attached to any hierarchy.
3505  */
3506 void cgroup_unload_subsys(struct cgroup_subsys *ss)
3507 {
3508         struct cg_cgroup_link *link;
3509         struct hlist_head *hhead;
3510
3511         BUG_ON(ss->module == NULL);
3512
3513         /*
3514          * we shouldn't be called if the subsystem is in use, and the use of
3515          * try_module_get in parse_cgroupfs_options should ensure that it
3516          * doesn't start being used while we're killing it off.
3517          */
3518         BUG_ON(ss->root != &rootnode);
3519
3520         mutex_lock(&cgroup_mutex);
3521         /* deassign the subsys_id */
3522         BUG_ON(ss->subsys_id < CGROUP_BUILTIN_SUBSYS_COUNT);
3523         subsys[ss->subsys_id] = NULL;
3524
3525         /* remove subsystem from rootnode's list of subsystems */
3526         list_del(&ss->sibling);
3527
3528         /*
3529          * disentangle the css from all css_sets attached to the dummytop. as
3530          * in loading, we need to pay our respects to the hashtable gods.
3531          */
3532         write_lock(&css_set_lock);
3533         list_for_each_entry(link, &dummytop->css_sets, cgrp_link_list) {
3534                 struct css_set *cg = link->cg;
3535
3536                 hlist_del(&cg->hlist);
3537                 BUG_ON(!cg->subsys[ss->subsys_id]);
3538                 cg->subsys[ss->subsys_id] = NULL;
3539                 hhead = css_set_hash(cg->subsys);
3540                 hlist_add_head(&cg->hlist, hhead);
3541         }
3542         write_unlock(&css_set_lock);
3543
3544         /*
3545          * remove subsystem's css from the dummytop and free it - need to free
3546          * before marking as null because ss->destroy needs the cgrp->subsys
3547          * pointer to find their state. note that this also takes care of
3548          * freeing the css_id.
3549          */
3550         ss->destroy(ss, dummytop);
3551         dummytop->subsys[ss->subsys_id] = NULL;
3552
3553         mutex_unlock(&cgroup_mutex);
3554 }
3555 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
3556
3557 /**
3558  * cgroup_init_early - cgroup initialization at system boot
3559  *
3560  * Initialize cgroups at system boot, and initialize any
3561  * subsystems that request early init.
3562  */
3563 int __init cgroup_init_early(void)
3564 {
3565         int i;
3566         atomic_set(&init_css_set.refcount, 1);
3567         INIT_LIST_HEAD(&init_css_set.cg_links);
3568         INIT_LIST_HEAD(&init_css_set.tasks);
3569         INIT_HLIST_NODE(&init_css_set.hlist);
3570         css_set_count = 1;
3571         init_cgroup_root(&rootnode);
3572         root_count = 1;
3573         init_task.cgroups = &init_css_set;
3574
3575         init_css_set_link.cg = &init_css_set;
3576         init_css_set_link.cgrp = dummytop;
3577         list_add(&init_css_set_link.cgrp_link_list,
3578                  &rootnode.top_cgroup.css_sets);
3579         list_add(&init_css_set_link.cg_link_list,
3580                  &init_css_set.cg_links);
3581
3582         for (i = 0; i < CSS_SET_TABLE_SIZE; i++)
3583                 INIT_HLIST_HEAD(&css_set_table[i]);
3584
3585         /* at bootup time, we don't worry about modular subsystems */
3586         for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
3587                 struct cgroup_subsys *ss = subsys[i];
3588
3589                 BUG_ON(!ss->name);
3590                 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
3591                 BUG_ON(!ss->create);
3592                 BUG_ON(!ss->destroy);
3593                 if (ss->subsys_id != i) {
3594                         printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
3595                                ss->name, ss->subsys_id);
3596                         BUG();
3597                 }
3598
3599                 if (ss->early_init)
3600                         cgroup_init_subsys(ss);
3601         }
3602         return 0;
3603 }
3604
3605 /**
3606  * cgroup_init - cgroup initialization
3607  *
3608  * Register cgroup filesystem and /proc file, and initialize
3609  * any subsystems that didn't request early init.
3610  */
3611 int __init cgroup_init(void)
3612 {
3613         int err;
3614         int i;
3615         struct hlist_head *hhead;
3616
3617         err = bdi_init(&cgroup_backing_dev_info);
3618         if (err)
3619                 return err;
3620
3621         /* at bootup time, we don't worry about modular subsystems */
3622         for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
3623                 struct cgroup_subsys *ss = subsys[i];
3624                 if (!ss->early_init)
3625                         cgroup_init_subsys(ss);
3626                 if (ss->use_id)
3627                         cgroup_init_idr(ss, init_css_set.subsys[ss->subsys_id]);
3628         }
3629
3630         /* Add init_css_set to the hash table */
3631         hhead = css_set_hash(init_css_set.subsys);
3632         hlist_add_head(&init_css_set.hlist, hhead);
3633         BUG_ON(!init_root_id(&rootnode));
3634         err = register_filesystem(&cgroup_fs_type);
3635         if (err < 0)
3636                 goto out;
3637
3638         proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
3639
3640 out:
3641         if (err)
3642                 bdi_destroy(&cgroup_backing_dev_info);
3643
3644         return err;
3645 }
3646
3647 /*
3648  * proc_cgroup_show()
3649  *  - Print task's cgroup paths into seq_file, one line for each hierarchy
3650  *  - Used for /proc/<pid>/cgroup.
3651  *  - No need to task_lock(tsk) on this tsk->cgroup reference, as it
3652  *    doesn't really matter if tsk->cgroup changes after we read it,
3653  *    and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
3654  *    anyway.  No need to check that tsk->cgroup != NULL, thanks to
3655  *    the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
3656  *    cgroup to top_cgroup.
3657  */
3658
3659 /* TODO: Use a proper seq_file iterator */
3660 static int proc_cgroup_show(struct seq_file *m, void *v)
3661 {
3662         struct pid *pid;
3663         struct task_struct *tsk;
3664         char *buf;
3665         int retval;
3666         struct cgroupfs_root *root;
3667
3668         retval = -ENOMEM;
3669         buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
3670         if (!buf)
3671                 goto out;
3672
3673         retval = -ESRCH;
3674         pid = m->private;
3675         tsk = get_pid_task(pid, PIDTYPE_PID);
3676         if (!tsk)
3677                 goto out_free;
3678
3679         retval = 0;
3680
3681         mutex_lock(&cgroup_mutex);
3682
3683         for_each_active_root(root) {
3684                 struct cgroup_subsys *ss;
3685                 struct cgroup *cgrp;
3686                 int count = 0;
3687
3688                 seq_printf(m, "%d:", root->hierarchy_id);
3689                 for_each_subsys(root, ss)
3690                         seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
3691                 if (strlen(root->name))
3692                         seq_printf(m, "%sname=%s", count ? "," : "",
3693                                    root->name);
3694                 seq_putc(m, ':');
3695                 cgrp = task_cgroup_from_root(tsk, root);
3696                 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
3697                 if (retval < 0)
3698                         goto out_unlock;
3699                 seq_puts(m, buf);
3700                 seq_putc(m, '\n');
3701         }
3702
3703 out_unlock:
3704         mutex_unlock(&cgroup_mutex);
3705         put_task_struct(tsk);
3706 out_free:
3707         kfree(buf);
3708 out:
3709         return retval;
3710 }
3711
3712 static int cgroup_open(struct inode *inode, struct file *file)
3713 {
3714         struct pid *pid = PROC_I(inode)->pid;
3715         return single_open(file, proc_cgroup_show, pid);
3716 }
3717
3718 const struct file_operations proc_cgroup_operations = {
3719         .open           = cgroup_open,
3720         .read           = seq_read,
3721         .llseek         = seq_lseek,
3722         .release        = single_release,
3723 };
3724
3725 /* Display information about each subsystem and each hierarchy */
3726 static int proc_cgroupstats_show(struct seq_file *m, void *v)
3727 {
3728         int i;
3729
3730         seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
3731         /*
3732          * ideally we don't want subsystems moving around while we do this.
3733          * cgroup_mutex is also necessary to guarantee an atomic snapshot of
3734          * subsys/hierarchy state.
3735          */
3736         mutex_lock(&cgroup_mutex);
3737         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3738                 struct cgroup_subsys *ss = subsys[i];
3739                 if (ss == NULL)
3740                         continue;
3741                 seq_printf(m, "%s\t%d\t%d\t%d\n",
3742                            ss->name, ss->root->hierarchy_id,
3743                            ss->root->number_of_cgroups, !ss->disabled);
3744         }
3745         mutex_unlock(&cgroup_mutex);
3746         return 0;
3747 }
3748
3749 static int cgroupstats_open(struct inode *inode, struct file *file)
3750 {
3751         return single_open(file, proc_cgroupstats_show, NULL);
3752 }
3753
3754 static const struct file_operations proc_cgroupstats_operations = {
3755         .open = cgroupstats_open,
3756         .read = seq_read,
3757         .llseek = seq_lseek,
3758         .release = single_release,
3759 };
3760
3761 /**
3762  * cgroup_fork - attach newly forked task to its parents cgroup.
3763  * @child: pointer to task_struct of forking parent process.
3764  *
3765  * Description: A task inherits its parent's cgroup at fork().
3766  *
3767  * A pointer to the shared css_set was automatically copied in
3768  * fork.c by dup_task_struct().  However, we ignore that copy, since
3769  * it was not made under the protection of RCU or cgroup_mutex, so
3770  * might no longer be a valid cgroup pointer.  cgroup_attach_task() might
3771  * have already changed current->cgroups, allowing the previously
3772  * referenced cgroup group to be removed and freed.
3773  *
3774  * At the point that cgroup_fork() is called, 'current' is the parent
3775  * task, and the passed argument 'child' points to the child task.
3776  */
3777 void cgroup_fork(struct task_struct *child)
3778 {
3779         task_lock(current);
3780         child->cgroups = current->cgroups;
3781         get_css_set(child->cgroups);
3782         task_unlock(current);
3783         INIT_LIST_HEAD(&child->cg_list);
3784 }
3785
3786 /**
3787  * cgroup_fork_callbacks - run fork callbacks
3788  * @child: the new task
3789  *
3790  * Called on a new task very soon before adding it to the
3791  * tasklist. No need to take any locks since no-one can
3792  * be operating on this task.
3793  */
3794 void cgroup_fork_callbacks(struct task_struct *child)
3795 {
3796         if (need_forkexit_callback) {
3797                 int i;
3798                 /*
3799                  * forkexit callbacks are only supported for builtin
3800                  * subsystems, and the builtin section of the subsys array is
3801                  * immutable, so we don't need to lock the subsys array here.
3802                  */
3803                 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
3804                         struct cgroup_subsys *ss = subsys[i];
3805                         if (ss->fork)
3806                                 ss->fork(ss, child);
3807                 }
3808         }
3809 }
3810
3811 /**
3812  * cgroup_post_fork - called on a new task after adding it to the task list
3813  * @child: the task in question
3814  *
3815  * Adds the task to the list running through its css_set if necessary.
3816  * Has to be after the task is visible on the task list in case we race
3817  * with the first call to cgroup_iter_start() - to guarantee that the
3818  * new task ends up on its list.
3819  */
3820 void cgroup_post_fork(struct task_struct *child)
3821 {
3822         if (use_task_css_set_links) {
3823                 write_lock(&css_set_lock);
3824                 task_lock(child);
3825                 if (list_empty(&child->cg_list))
3826                         list_add(&child->cg_list, &child->cgroups->tasks);
3827                 task_unlock(child);
3828                 write_unlock(&css_set_lock);
3829         }
3830 }
3831 /**
3832  * cgroup_exit - detach cgroup from exiting task
3833  * @tsk: pointer to task_struct of exiting process
3834  * @run_callback: run exit callbacks?
3835  *
3836  * Description: Detach cgroup from @tsk and release it.
3837  *
3838  * Note that cgroups marked notify_on_release force every task in
3839  * them to take the global cgroup_mutex mutex when exiting.
3840  * This could impact scaling on very large systems.  Be reluctant to
3841  * use notify_on_release cgroups where very high task exit scaling
3842  * is required on large systems.
3843  *
3844  * the_top_cgroup_hack:
3845  *
3846  *    Set the exiting tasks cgroup to the root cgroup (top_cgroup).
3847  *
3848  *    We call cgroup_exit() while the task is still competent to
3849  *    handle notify_on_release(), then leave the task attached to the
3850  *    root cgroup in each hierarchy for the remainder of its exit.
3851  *
3852  *    To do this properly, we would increment the reference count on
3853  *    top_cgroup, and near the very end of the kernel/exit.c do_exit()
3854  *    code we would add a second cgroup function call, to drop that
3855  *    reference.  This would just create an unnecessary hot spot on
3856  *    the top_cgroup reference count, to no avail.
3857  *
3858  *    Normally, holding a reference to a cgroup without bumping its
3859  *    count is unsafe.   The cgroup could go away, or someone could
3860  *    attach us to a different cgroup, decrementing the count on
3861  *    the first cgroup that we never incremented.  But in this case,
3862  *    top_cgroup isn't going away, and either task has PF_EXITING set,
3863  *    which wards off any cgroup_attach_task() attempts, or task is a failed
3864  *    fork, never visible to cgroup_attach_task.
3865  */
3866 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
3867 {
3868         int i;
3869         struct css_set *cg;
3870
3871         if (run_callbacks && need_forkexit_callback) {
3872                 /*
3873                  * modular subsystems can't use callbacks, so no need to lock
3874                  * the subsys array
3875                  */
3876                 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
3877                         struct cgroup_subsys *ss = subsys[i];
3878                         if (ss->exit)
3879                                 ss->exit(ss, tsk);
3880                 }
3881         }
3882
3883         /*
3884          * Unlink from the css_set task list if necessary.
3885          * Optimistically check cg_list before taking
3886          * css_set_lock
3887          */
3888         if (!list_empty(&tsk->cg_list)) {
3889                 write_lock(&css_set_lock);
3890                 if (!list_empty(&tsk->cg_list))
3891                         list_del(&tsk->cg_list);
3892                 write_unlock(&css_set_lock);
3893         }
3894
3895         /* Reassign the task to the init_css_set. */
3896         task_lock(tsk);
3897         cg = tsk->cgroups;
3898         tsk->cgroups = &init_css_set;
3899         task_unlock(tsk);
3900         if (cg)
3901                 put_css_set_taskexit(cg);
3902 }
3903
3904 /**
3905  * cgroup_clone - clone the cgroup the given subsystem is attached to
3906  * @tsk: the task to be moved
3907  * @subsys: the given subsystem
3908  * @nodename: the name for the new cgroup
3909  *
3910  * Duplicate the current cgroup in the hierarchy that the given
3911  * subsystem is attached to, and move this task into the new
3912  * child.
3913  */
3914 int cgroup_clone(struct task_struct *tsk, struct cgroup_subsys *subsys,
3915                                                         char *nodename)
3916 {
3917         struct dentry *dentry;
3918         int ret = 0;
3919         struct cgroup *parent, *child;
3920         struct inode *inode;
3921         struct css_set *cg;
3922         struct cgroupfs_root *root;
3923         struct cgroup_subsys *ss;
3924
3925         /* We shouldn't be called by an unregistered subsystem */
3926         BUG_ON(!subsys->active);
3927
3928         /* First figure out what hierarchy and cgroup we're dealing
3929          * with, and pin them so we can drop cgroup_mutex */
3930         mutex_lock(&cgroup_mutex);
3931  again:
3932         root = subsys->root;
3933         if (root == &rootnode) {
3934                 mutex_unlock(&cgroup_mutex);
3935                 return 0;
3936         }
3937
3938         /* Pin the hierarchy */
3939         if (!atomic_inc_not_zero(&root->sb->s_active)) {
3940                 /* We race with the final deactivate_super() */
3941                 mutex_unlock(&cgroup_mutex);
3942                 return 0;
3943         }
3944
3945         /* Keep the cgroup alive */
3946         task_lock(tsk);
3947         parent = task_cgroup(tsk, subsys->subsys_id);
3948         cg = tsk->cgroups;
3949         get_css_set(cg);
3950         task_unlock(tsk);
3951
3952         mutex_unlock(&cgroup_mutex);
3953
3954         /* Now do the VFS work to create a cgroup */
3955         inode = parent->dentry->d_inode;
3956
3957         /* Hold the parent directory mutex across this operation to
3958          * stop anyone else deleting the new cgroup */
3959         mutex_lock(&inode->i_mutex);
3960         dentry = lookup_one_len(nodename, parent->dentry, strlen(nodename));
3961         if (IS_ERR(dentry)) {
3962                 printk(KERN_INFO
3963                        "cgroup: Couldn't allocate dentry for %s: %ld\n", nodename,
3964                        PTR_ERR(dentry));
3965                 ret = PTR_ERR(dentry);
3966                 goto out_release;
3967         }
3968
3969         /* Create the cgroup directory, which also creates the cgroup */
3970         ret = vfs_mkdir(inode, dentry, 0755);
3971         child = __d_cgrp(dentry);
3972         dput(dentry);
3973         if (ret) {
3974                 printk(KERN_INFO
3975                        "Failed to create cgroup %s: %d\n", nodename,
3976                        ret);
3977                 goto out_release;
3978         }
3979
3980         /* The cgroup now exists. Retake cgroup_mutex and check
3981          * that we're still in the same state that we thought we
3982          * were. */
3983         mutex_lock(&cgroup_mutex);
3984         if ((root != subsys->root) ||
3985             (parent != task_cgroup(tsk, subsys->subsys_id))) {
3986                 /* Aargh, we raced ... */
3987                 mutex_unlock(&inode->i_mutex);
3988                 put_css_set(cg);
3989
3990                 deactivate_super(root->sb);
3991                 /* The cgroup is still accessible in the VFS, but
3992                  * we're not going to try to rmdir() it at this
3993                  * point. */
3994                 printk(KERN_INFO
3995                        "Race in cgroup_clone() - leaking cgroup %s\n",
3996                        nodename);
3997                 goto again;
3998         }
3999
4000         /* do any required auto-setup */
4001         for_each_subsys(root, ss) {
4002                 if (ss->post_clone)
4003                         ss->post_clone(ss, child);
4004         }
4005
4006         /* All seems fine. Finish by moving the task into the new cgroup */
4007         ret = cgroup_attach_task(child, tsk);
4008         mutex_unlock(&cgroup_mutex);
4009
4010  out_release:
4011         mutex_unlock(&inode->i_mutex);
4012
4013         mutex_lock(&cgroup_mutex);
4014         put_css_set(cg);
4015         mutex_unlock(&cgroup_mutex);
4016         deactivate_super(root->sb);
4017         return ret;
4018 }
4019
4020 /**
4021  * cgroup_is_descendant - see if @cgrp is a descendant of @task's cgrp
4022  * @cgrp: the cgroup in question
4023  * @task: the task in question
4024  *
4025  * See if @cgrp is a descendant of @task's cgroup in the appropriate
4026  * hierarchy.
4027  *
4028  * If we are sending in dummytop, then presumably we are creating
4029  * the top cgroup in the subsystem.
4030  *
4031  * Called only by the ns (nsproxy) cgroup.
4032  */
4033 int cgroup_is_descendant(const struct cgroup *cgrp, struct task_struct *task)
4034 {
4035         int ret;
4036         struct cgroup *target;
4037
4038         if (cgrp == dummytop)
4039                 return 1;
4040
4041         target = task_cgroup_from_root(task, cgrp->root);
4042         while (cgrp != target && cgrp!= cgrp->top_cgroup)
4043                 cgrp = cgrp->parent;
4044         ret = (cgrp == target);
4045         return ret;
4046 }
4047
4048 static void check_for_release(struct cgroup *cgrp)
4049 {
4050         /* All of these checks rely on RCU to keep the cgroup
4051          * structure alive */
4052         if (cgroup_is_releasable(cgrp) && !atomic_read(&cgrp->count)
4053             && list_empty(&cgrp->children) && !cgroup_has_css_refs(cgrp)) {
4054                 /* Control Group is currently removeable. If it's not
4055                  * already queued for a userspace notification, queue
4056                  * it now */
4057                 int need_schedule_work = 0;
4058                 spin_lock(&release_list_lock);
4059                 if (!cgroup_is_removed(cgrp) &&
4060                     list_empty(&cgrp->release_list)) {
4061                         list_add(&cgrp->release_list, &release_list);
4062                         need_schedule_work = 1;
4063                 }
4064                 spin_unlock(&release_list_lock);
4065                 if (need_schedule_work)
4066                         schedule_work(&release_agent_work);
4067         }
4068 }
4069
4070 /* Caller must verify that the css is not for root cgroup */
4071 void __css_put(struct cgroup_subsys_state *css, int count)
4072 {
4073         struct cgroup *cgrp = css->cgroup;
4074         int val;
4075         rcu_read_lock();
4076         val = atomic_sub_return(count, &css->refcnt);
4077         if (val == 1) {
4078                 if (notify_on_release(cgrp)) {
4079                         set_bit(CGRP_RELEASABLE, &cgrp->flags);
4080                         check_for_release(cgrp);
4081                 }
4082                 cgroup_wakeup_rmdir_waiter(cgrp);
4083         }
4084         rcu_read_unlock();
4085         WARN_ON_ONCE(val < 1);
4086 }
4087 EXPORT_SYMBOL_GPL(__css_put);
4088
4089 /*
4090  * Notify userspace when a cgroup is released, by running the
4091  * configured release agent with the name of the cgroup (path
4092  * relative to the root of cgroup file system) as the argument.
4093  *
4094  * Most likely, this user command will try to rmdir this cgroup.
4095  *
4096  * This races with the possibility that some other task will be
4097  * attached to this cgroup before it is removed, or that some other
4098  * user task will 'mkdir' a child cgroup of this cgroup.  That's ok.
4099  * The presumed 'rmdir' will fail quietly if this cgroup is no longer
4100  * unused, and this cgroup will be reprieved from its death sentence,
4101  * to continue to serve a useful existence.  Next time it's released,
4102  * we will get notified again, if it still has 'notify_on_release' set.
4103  *
4104  * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
4105  * means only wait until the task is successfully execve()'d.  The
4106  * separate release agent task is forked by call_usermodehelper(),
4107  * then control in this thread returns here, without waiting for the
4108  * release agent task.  We don't bother to wait because the caller of
4109  * this routine has no use for the exit status of the release agent
4110  * task, so no sense holding our caller up for that.
4111  */
4112 static void cgroup_release_agent(struct work_struct *work)
4113 {
4114         BUG_ON(work != &release_agent_work);
4115         mutex_lock(&cgroup_mutex);
4116         spin_lock(&release_list_lock);
4117         while (!list_empty(&release_list)) {
4118                 char *argv[3], *envp[3];
4119                 int i;
4120                 char *pathbuf = NULL, *agentbuf = NULL;
4121                 struct cgroup *cgrp = list_entry(release_list.next,
4122                                                     struct cgroup,
4123                                                     release_list);
4124                 list_del_init(&cgrp->release_list);
4125                 spin_unlock(&release_list_lock);
4126                 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4127                 if (!pathbuf)
4128                         goto continue_free;
4129                 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
4130                         goto continue_free;
4131                 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
4132                 if (!agentbuf)
4133                         goto continue_free;
4134
4135                 i = 0;
4136                 argv[i++] = agentbuf;
4137                 argv[i++] = pathbuf;
4138                 argv[i] = NULL;
4139
4140                 i = 0;
4141                 /* minimal command environment */
4142                 envp[i++] = "HOME=/";
4143                 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
4144                 envp[i] = NULL;
4145
4146                 /* Drop the lock while we invoke the usermode helper,
4147                  * since the exec could involve hitting disk and hence
4148                  * be a slow process */
4149                 mutex_unlock(&cgroup_mutex);
4150                 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
4151                 mutex_lock(&cgroup_mutex);
4152  continue_free:
4153                 kfree(pathbuf);
4154                 kfree(agentbuf);
4155                 spin_lock(&release_list_lock);
4156         }
4157         spin_unlock(&release_list_lock);
4158         mutex_unlock(&cgroup_mutex);
4159 }
4160
4161 static int __init cgroup_disable(char *str)
4162 {
4163         int i;
4164         char *token;
4165
4166         while ((token = strsep(&str, ",")) != NULL) {
4167                 if (!*token)
4168                         continue;
4169                 /*
4170                  * cgroup_disable, being at boot time, can't know about module
4171                  * subsystems, so we don't worry about them.
4172                  */
4173                 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
4174                         struct cgroup_subsys *ss = subsys[i];
4175
4176                         if (!strcmp(token, ss->name)) {
4177                                 ss->disabled = 1;
4178                                 printk(KERN_INFO "Disabling %s control group"
4179                                         " subsystem\n", ss->name);
4180                                 break;
4181                         }
4182                 }
4183         }
4184         return 1;
4185 }
4186 __setup("cgroup_disable=", cgroup_disable);
4187
4188 /*
4189  * Functons for CSS ID.
4190  */
4191
4192 /*
4193  *To get ID other than 0, this should be called when !cgroup_is_removed().
4194  */
4195 unsigned short css_id(struct cgroup_subsys_state *css)
4196 {
4197         struct css_id *cssid = rcu_dereference(css->id);
4198
4199         if (cssid)
4200                 return cssid->id;
4201         return 0;
4202 }
4203 EXPORT_SYMBOL_GPL(css_id);
4204
4205 unsigned short css_depth(struct cgroup_subsys_state *css)
4206 {
4207         struct css_id *cssid = rcu_dereference(css->id);
4208
4209         if (cssid)
4210                 return cssid->depth;
4211         return 0;
4212 }
4213 EXPORT_SYMBOL_GPL(css_depth);
4214
4215 bool css_is_ancestor(struct cgroup_subsys_state *child,
4216                     const struct cgroup_subsys_state *root)
4217 {
4218         struct css_id *child_id = rcu_dereference(child->id);
4219         struct css_id *root_id = rcu_dereference(root->id);
4220
4221         if (!child_id || !root_id || (child_id->depth < root_id->depth))
4222                 return false;
4223         return child_id->stack[root_id->depth] == root_id->id;
4224 }
4225
4226 static void __free_css_id_cb(struct rcu_head *head)
4227 {
4228         struct css_id *id;
4229
4230         id = container_of(head, struct css_id, rcu_head);
4231         kfree(id);
4232 }
4233
4234 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
4235 {
4236         struct css_id *id = css->id;
4237         /* When this is called before css_id initialization, id can be NULL */
4238         if (!id)
4239                 return;
4240
4241         BUG_ON(!ss->use_id);
4242
4243         rcu_assign_pointer(id->css, NULL);
4244         rcu_assign_pointer(css->id, NULL);
4245         spin_lock(&ss->id_lock);
4246         idr_remove(&ss->idr, id->id);
4247         spin_unlock(&ss->id_lock);
4248         call_rcu(&id->rcu_head, __free_css_id_cb);
4249 }
4250 EXPORT_SYMBOL_GPL(free_css_id);
4251
4252 /*
4253  * This is called by init or create(). Then, calls to this function are
4254  * always serialized (By cgroup_mutex() at create()).
4255  */
4256
4257 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
4258 {
4259         struct css_id *newid;
4260         int myid, error, size;
4261
4262         BUG_ON(!ss->use_id);
4263
4264         size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
4265         newid = kzalloc(size, GFP_KERNEL);
4266         if (!newid)
4267                 return ERR_PTR(-ENOMEM);
4268         /* get id */
4269         if (unlikely(!idr_pre_get(&ss->idr, GFP_KERNEL))) {
4270                 error = -ENOMEM;
4271                 goto err_out;
4272         }
4273         spin_lock(&ss->id_lock);
4274         /* Don't use 0. allocates an ID of 1-65535 */
4275         error = idr_get_new_above(&ss->idr, newid, 1, &myid);
4276         spin_unlock(&ss->id_lock);
4277
4278         /* Returns error when there are no free spaces for new ID.*/
4279         if (error) {
4280                 error = -ENOSPC;
4281                 goto err_out;
4282         }
4283         if (myid > CSS_ID_MAX)
4284                 goto remove_idr;
4285
4286         newid->id = myid;
4287         newid->depth = depth;
4288         return newid;
4289 remove_idr:
4290         error = -ENOSPC;
4291         spin_lock(&ss->id_lock);
4292         idr_remove(&ss->idr, myid);
4293         spin_unlock(&ss->id_lock);
4294 err_out:
4295         kfree(newid);
4296         return ERR_PTR(error);
4297
4298 }
4299
4300 static int __init_or_module cgroup_init_idr(struct cgroup_subsys *ss,
4301                                             struct cgroup_subsys_state *rootcss)
4302 {
4303         struct css_id *newid;
4304
4305         spin_lock_init(&ss->id_lock);
4306         idr_init(&ss->idr);
4307
4308         newid = get_new_cssid(ss, 0);
4309         if (IS_ERR(newid))
4310                 return PTR_ERR(newid);
4311
4312         newid->stack[0] = newid->id;
4313         newid->css = rootcss;
4314         rootcss->id = newid;
4315         return 0;
4316 }
4317
4318 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
4319                         struct cgroup *child)
4320 {
4321         int subsys_id, i, depth = 0;
4322         struct cgroup_subsys_state *parent_css, *child_css;
4323         struct css_id *child_id, *parent_id = NULL;
4324
4325         subsys_id = ss->subsys_id;
4326         parent_css = parent->subsys[subsys_id];
4327         child_css = child->subsys[subsys_id];
4328         depth = css_depth(parent_css) + 1;
4329         parent_id = parent_css->id;
4330
4331         child_id = get_new_cssid(ss, depth);
4332         if (IS_ERR(child_id))
4333                 return PTR_ERR(child_id);
4334
4335         for (i = 0; i < depth; i++)
4336                 child_id->stack[i] = parent_id->stack[i];
4337         child_id->stack[depth] = child_id->id;
4338         /*
4339          * child_id->css pointer will be set after this cgroup is available
4340          * see cgroup_populate_dir()
4341          */
4342         rcu_assign_pointer(child_css->id, child_id);
4343
4344         return 0;
4345 }
4346
4347 /**
4348  * css_lookup - lookup css by id
4349  * @ss: cgroup subsys to be looked into.
4350  * @id: the id
4351  *
4352  * Returns pointer to cgroup_subsys_state if there is valid one with id.
4353  * NULL if not. Should be called under rcu_read_lock()
4354  */
4355 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
4356 {
4357         struct css_id *cssid = NULL;
4358
4359         BUG_ON(!ss->use_id);
4360         cssid = idr_find(&ss->idr, id);
4361
4362         if (unlikely(!cssid))
4363                 return NULL;
4364
4365         return rcu_dereference(cssid->css);
4366 }
4367 EXPORT_SYMBOL_GPL(css_lookup);
4368
4369 /**
4370  * css_get_next - lookup next cgroup under specified hierarchy.
4371  * @ss: pointer to subsystem
4372  * @id: current position of iteration.
4373  * @root: pointer to css. search tree under this.
4374  * @foundid: position of found object.
4375  *
4376  * Search next css under the specified hierarchy of rootid. Calling under
4377  * rcu_read_lock() is necessary. Returns NULL if it reaches the end.
4378  */
4379 struct cgroup_subsys_state *
4380 css_get_next(struct cgroup_subsys *ss, int id,
4381              struct cgroup_subsys_state *root, int *foundid)
4382 {
4383         struct cgroup_subsys_state *ret = NULL;
4384         struct css_id *tmp;
4385         int tmpid;
4386         int rootid = css_id(root);
4387         int depth = css_depth(root);
4388
4389         if (!rootid)
4390                 return NULL;
4391
4392         BUG_ON(!ss->use_id);
4393         /* fill start point for scan */
4394         tmpid = id;
4395         while (1) {
4396                 /*
4397                  * scan next entry from bitmap(tree), tmpid is updated after
4398                  * idr_get_next().
4399                  */
4400                 spin_lock(&ss->id_lock);
4401                 tmp = idr_get_next(&ss->idr, &tmpid);
4402                 spin_unlock(&ss->id_lock);
4403
4404                 if (!tmp)
4405                         break;
4406                 if (tmp->depth >= depth && tmp->stack[depth] == rootid) {
4407                         ret = rcu_dereference(tmp->css);
4408                         if (ret) {
4409                                 *foundid = tmpid;
4410                                 break;
4411                         }
4412                 }
4413                 /* continue to scan from next id */
4414                 tmpid = tmpid + 1;
4415         }
4416         return ret;
4417 }
4418
4419 #ifdef CONFIG_CGROUP_DEBUG
4420 static struct cgroup_subsys_state *debug_create(struct cgroup_subsys *ss,
4421                                                    struct cgroup *cont)
4422 {
4423         struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
4424
4425         if (!css)
4426                 return ERR_PTR(-ENOMEM);
4427
4428         return css;
4429 }
4430
4431 static void debug_destroy(struct cgroup_subsys *ss, struct cgroup *cont)
4432 {
4433         kfree(cont->subsys[debug_subsys_id]);
4434 }
4435
4436 static u64 cgroup_refcount_read(struct cgroup *cont, struct cftype *cft)
4437 {
4438         return atomic_read(&cont->count);
4439 }
4440
4441 static u64 debug_taskcount_read(struct cgroup *cont, struct cftype *cft)
4442 {
4443         return cgroup_task_count(cont);
4444 }
4445
4446 static u64 current_css_set_read(struct cgroup *cont, struct cftype *cft)
4447 {
4448         return (u64)(unsigned long)current->cgroups;
4449 }
4450
4451 static u64 current_css_set_refcount_read(struct cgroup *cont,
4452                                            struct cftype *cft)
4453 {
4454         u64 count;
4455
4456         rcu_read_lock();
4457         count = atomic_read(&current->cgroups->refcount);
4458         rcu_read_unlock();
4459         return count;
4460 }
4461
4462 static int current_css_set_cg_links_read(struct cgroup *cont,
4463                                          struct cftype *cft,
4464                                          struct seq_file *seq)
4465 {
4466         struct cg_cgroup_link *link;
4467         struct css_set *cg;
4468
4469         read_lock(&css_set_lock);
4470         rcu_read_lock();
4471         cg = rcu_dereference(current->cgroups);
4472         list_for_each_entry(link, &cg->cg_links, cg_link_list) {
4473                 struct cgroup *c = link->cgrp;
4474                 const char *name;
4475
4476                 if (c->dentry)
4477                         name = c->dentry->d_name.name;
4478                 else
4479                         name = "?";
4480                 seq_printf(seq, "Root %d group %s\n",
4481                            c->root->hierarchy_id, name);
4482         }
4483         rcu_read_unlock();
4484         read_unlock(&css_set_lock);
4485         return 0;
4486 }
4487
4488 #define MAX_TASKS_SHOWN_PER_CSS 25
4489 static int cgroup_css_links_read(struct cgroup *cont,
4490                                  struct cftype *cft,
4491                                  struct seq_file *seq)
4492 {
4493         struct cg_cgroup_link *link;
4494
4495         read_lock(&css_set_lock);
4496         list_for_each_entry(link, &cont->css_sets, cgrp_link_list) {
4497                 struct css_set *cg = link->cg;
4498                 struct task_struct *task;
4499                 int count = 0;
4500                 seq_printf(seq, "css_set %p\n", cg);
4501                 list_for_each_entry(task, &cg->tasks, cg_list) {
4502                         if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
4503                                 seq_puts(seq, "  ...\n");
4504                                 break;
4505                         } else {
4506                                 seq_printf(seq, "  task %d\n",
4507                                            task_pid_vnr(task));
4508                         }
4509                 }
4510         }
4511         read_unlock(&css_set_lock);
4512         return 0;
4513 }
4514
4515 static u64 releasable_read(struct cgroup *cgrp, struct cftype *cft)
4516 {
4517         return test_bit(CGRP_RELEASABLE, &cgrp->flags);
4518 }
4519
4520 static struct cftype debug_files[] =  {
4521         {
4522                 .name = "cgroup_refcount",
4523                 .read_u64 = cgroup_refcount_read,
4524         },
4525         {
4526                 .name = "taskcount",
4527                 .read_u64 = debug_taskcount_read,
4528         },
4529
4530         {
4531                 .name = "current_css_set",
4532                 .read_u64 = current_css_set_read,
4533         },
4534
4535         {
4536                 .name = "current_css_set_refcount",
4537                 .read_u64 = current_css_set_refcount_read,
4538         },
4539
4540         {
4541                 .name = "current_css_set_cg_links",
4542                 .read_seq_string = current_css_set_cg_links_read,
4543         },
4544
4545         {
4546                 .name = "cgroup_css_links",
4547                 .read_seq_string = cgroup_css_links_read,
4548         },
4549
4550         {
4551                 .name = "releasable",
4552                 .read_u64 = releasable_read,
4553         },
4554 };
4555
4556 static int debug_populate(struct cgroup_subsys *ss, struct cgroup *cont)
4557 {
4558         return cgroup_add_files(cont, ss, debug_files,
4559                                 ARRAY_SIZE(debug_files));
4560 }
4561
4562 struct cgroup_subsys debug_subsys = {
4563         .name = "debug",
4564         .create = debug_create,
4565         .destroy = debug_destroy,
4566         .populate = debug_populate,
4567         .subsys_id = debug_subsys_id,
4568 };
4569 #endif /* CONFIG_CGROUP_DEBUG */