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