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