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