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