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