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