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