dc39e1774542ecf63a29fc123d9f5e84d11b2d5e
[firefly-linux-kernel-4.4.55.git] / kernel / cgroup.c
1 /*
2  *  Generic process-grouping system.
3  *
4  *  Based originally on the cpuset system, extracted by Paul Menage
5  *  Copyright (C) 2006 Google, Inc
6  *
7  *  Notifications support
8  *  Copyright (C) 2009 Nokia Corporation
9  *  Author: Kirill A. Shutemov
10  *
11  *  Copyright notices from the original cpuset code:
12  *  --------------------------------------------------
13  *  Copyright (C) 2003 BULL SA.
14  *  Copyright (C) 2004-2006 Silicon Graphics, Inc.
15  *
16  *  Portions derived from Patrick Mochel's sysfs code.
17  *  sysfs is Copyright (c) 2001-3 Patrick Mochel
18  *
19  *  2003-10-10 Written by Simon Derr.
20  *  2003-10-22 Updates by Stephen Hemminger.
21  *  2004 May-July Rework by Paul Jackson.
22  *  ---------------------------------------------------
23  *
24  *  This file is subject to the terms and conditions of the GNU General Public
25  *  License.  See the file COPYING in the main directory of the Linux
26  *  distribution for more details.
27  */
28
29 #include <linux/cgroup.h>
30 #include <linux/cred.h>
31 #include <linux/ctype.h>
32 #include <linux/errno.h>
33 #include <linux/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)
2328                 return cft->write(css, cft, file, buf, nbytes, ppos);
2329         if (cft->write_u64 || cft->write_s64)
2330                 return cgroup_write_X64(css, cft, file, buf, nbytes, ppos);
2331         if (cft->write_string)
2332                 return cgroup_write_string(css, cft, file, buf, nbytes, ppos);
2333         if (cft->trigger) {
2334                 int ret = cft->trigger(css, (unsigned int)cft->private);
2335                 return ret ? ret : nbytes;
2336         }
2337         return -EINVAL;
2338 }
2339
2340 static ssize_t cgroup_read_u64(struct cgroup_subsys_state *css,
2341                                struct cftype *cft, struct file *file,
2342                                char __user *buf, size_t nbytes, loff_t *ppos)
2343 {
2344         char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2345         u64 val = cft->read_u64(css, cft);
2346         int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2347
2348         return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2349 }
2350
2351 static ssize_t cgroup_read_s64(struct cgroup_subsys_state *css,
2352                                struct cftype *cft, struct file *file,
2353                                char __user *buf, size_t nbytes, loff_t *ppos)
2354 {
2355         char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2356         s64 val = cft->read_s64(css, cft);
2357         int len = sprintf(tmp, "%lld\n", (long long) val);
2358
2359         return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2360 }
2361
2362 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2363                                 size_t nbytes, loff_t *ppos)
2364 {
2365         struct cfent *cfe = __d_cfe(file->f_dentry);
2366         struct cftype *cft = __d_cft(file->f_dentry);
2367         struct cgroup_subsys_state *css = cfe->css;
2368
2369         if (cft->read)
2370                 return cft->read(css, cft, file, buf, nbytes, ppos);
2371         if (cft->read_u64)
2372                 return cgroup_read_u64(css, cft, file, buf, nbytes, ppos);
2373         if (cft->read_s64)
2374                 return cgroup_read_s64(css, cft, file, buf, nbytes, ppos);
2375         return -EINVAL;
2376 }
2377
2378 /*
2379  * seqfile ops/methods for returning structured data. Currently just
2380  * supports string->u64 maps, but can be extended in future.
2381  */
2382
2383 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2384 {
2385         struct seq_file *sf = cb->state;
2386         return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2387 }
2388
2389 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2390 {
2391         struct cfent *cfe = m->private;
2392         struct cftype *cft = cfe->type;
2393         struct cgroup_subsys_state *css = cfe->css;
2394
2395         if (cft->read_map) {
2396                 struct cgroup_map_cb cb = {
2397                         .fill = cgroup_map_add,
2398                         .state = m,
2399                 };
2400                 return cft->read_map(css, cft, &cb);
2401         }
2402         return cft->read_seq_string(css, cft, m);
2403 }
2404
2405 static const struct file_operations cgroup_seqfile_operations = {
2406         .read = seq_read,
2407         .write = cgroup_file_write,
2408         .llseek = seq_lseek,
2409         .release = cgroup_file_release,
2410 };
2411
2412 static int cgroup_file_open(struct inode *inode, struct file *file)
2413 {
2414         struct cfent *cfe = __d_cfe(file->f_dentry);
2415         struct cftype *cft = __d_cft(file->f_dentry);
2416         struct cgroup *cgrp = __d_cgrp(cfe->dentry->d_parent);
2417         struct cgroup_subsys_state *css;
2418         int err;
2419
2420         err = generic_file_open(inode, file);
2421         if (err)
2422                 return err;
2423
2424         /*
2425          * If the file belongs to a subsystem, pin the css.  Will be
2426          * unpinned either on open failure or release.  This ensures that
2427          * @css stays alive for all file operations.
2428          */
2429         rcu_read_lock();
2430         css = cgroup_css(cgrp, cft->ss);
2431         if (cft->ss && !css_tryget(css))
2432                 css = NULL;
2433         rcu_read_unlock();
2434
2435         if (!css)
2436                 return -ENODEV;
2437
2438         /*
2439          * @cfe->css is used by read/write/close to determine the
2440          * associated css.  @file->private_data would be a better place but
2441          * that's already used by seqfile.  Multiple accessors may use it
2442          * simultaneously which is okay as the association never changes.
2443          */
2444         WARN_ON_ONCE(cfe->css && cfe->css != css);
2445         cfe->css = css;
2446
2447         if (cft->read_map || cft->read_seq_string) {
2448                 file->f_op = &cgroup_seqfile_operations;
2449                 err = single_open(file, cgroup_seqfile_show, cfe);
2450         } else if (cft->open) {
2451                 err = cft->open(inode, file);
2452         }
2453
2454         if (css->ss && err)
2455                 css_put(css);
2456         return err;
2457 }
2458
2459 static int cgroup_file_release(struct inode *inode, struct file *file)
2460 {
2461         struct cfent *cfe = __d_cfe(file->f_dentry);
2462         struct cgroup_subsys_state *css = cfe->css;
2463
2464         if (css->ss)
2465                 css_put(css);
2466         if (file->f_op == &cgroup_seqfile_operations)
2467                 single_release(inode, file);
2468         return 0;
2469 }
2470
2471 /*
2472  * cgroup_rename - Only allow simple rename of directories in place.
2473  */
2474 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2475                             struct inode *new_dir, struct dentry *new_dentry)
2476 {
2477         int ret;
2478         struct cgroup_name *name, *old_name;
2479         struct cgroup *cgrp;
2480
2481         /*
2482          * It's convinient to use parent dir's i_mutex to protected
2483          * cgrp->name.
2484          */
2485         lockdep_assert_held(&old_dir->i_mutex);
2486
2487         if (!S_ISDIR(old_dentry->d_inode->i_mode))
2488                 return -ENOTDIR;
2489         if (new_dentry->d_inode)
2490                 return -EEXIST;
2491         if (old_dir != new_dir)
2492                 return -EIO;
2493
2494         cgrp = __d_cgrp(old_dentry);
2495
2496         /*
2497          * This isn't a proper migration and its usefulness is very
2498          * limited.  Disallow if sane_behavior.
2499          */
2500         if (cgroup_sane_behavior(cgrp))
2501                 return -EPERM;
2502
2503         name = cgroup_alloc_name(new_dentry);
2504         if (!name)
2505                 return -ENOMEM;
2506
2507         ret = simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2508         if (ret) {
2509                 kfree(name);
2510                 return ret;
2511         }
2512
2513         old_name = rcu_dereference_protected(cgrp->name, true);
2514         rcu_assign_pointer(cgrp->name, name);
2515
2516         kfree_rcu(old_name, rcu_head);
2517         return 0;
2518 }
2519
2520 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2521 {
2522         if (S_ISDIR(dentry->d_inode->i_mode))
2523                 return &__d_cgrp(dentry)->xattrs;
2524         else
2525                 return &__d_cfe(dentry)->xattrs;
2526 }
2527
2528 static inline int xattr_enabled(struct dentry *dentry)
2529 {
2530         struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2531         return root->flags & CGRP_ROOT_XATTR;
2532 }
2533
2534 static bool is_valid_xattr(const char *name)
2535 {
2536         if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2537             !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2538                 return true;
2539         return false;
2540 }
2541
2542 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2543                            const void *val, size_t size, int flags)
2544 {
2545         if (!xattr_enabled(dentry))
2546                 return -EOPNOTSUPP;
2547         if (!is_valid_xattr(name))
2548                 return -EINVAL;
2549         return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2550 }
2551
2552 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2553 {
2554         if (!xattr_enabled(dentry))
2555                 return -EOPNOTSUPP;
2556         if (!is_valid_xattr(name))
2557                 return -EINVAL;
2558         return simple_xattr_remove(__d_xattrs(dentry), name);
2559 }
2560
2561 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2562                                void *buf, size_t size)
2563 {
2564         if (!xattr_enabled(dentry))
2565                 return -EOPNOTSUPP;
2566         if (!is_valid_xattr(name))
2567                 return -EINVAL;
2568         return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2569 }
2570
2571 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2572 {
2573         if (!xattr_enabled(dentry))
2574                 return -EOPNOTSUPP;
2575         return simple_xattr_list(__d_xattrs(dentry), buf, size);
2576 }
2577
2578 static const struct file_operations cgroup_file_operations = {
2579         .read = cgroup_file_read,
2580         .write = cgroup_file_write,
2581         .llseek = generic_file_llseek,
2582         .open = cgroup_file_open,
2583         .release = cgroup_file_release,
2584 };
2585
2586 static const struct inode_operations cgroup_file_inode_operations = {
2587         .setxattr = cgroup_setxattr,
2588         .getxattr = cgroup_getxattr,
2589         .listxattr = cgroup_listxattr,
2590         .removexattr = cgroup_removexattr,
2591 };
2592
2593 static const struct inode_operations cgroup_dir_inode_operations = {
2594         .lookup = simple_lookup,
2595         .mkdir = cgroup_mkdir,
2596         .rmdir = cgroup_rmdir,
2597         .rename = cgroup_rename,
2598         .setxattr = cgroup_setxattr,
2599         .getxattr = cgroup_getxattr,
2600         .listxattr = cgroup_listxattr,
2601         .removexattr = cgroup_removexattr,
2602 };
2603
2604 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2605                                 struct super_block *sb)
2606 {
2607         struct inode *inode;
2608
2609         if (!dentry)
2610                 return -ENOENT;
2611         if (dentry->d_inode)
2612                 return -EEXIST;
2613
2614         inode = cgroup_new_inode(mode, sb);
2615         if (!inode)
2616                 return -ENOMEM;
2617
2618         if (S_ISDIR(mode)) {
2619                 inode->i_op = &cgroup_dir_inode_operations;
2620                 inode->i_fop = &simple_dir_operations;
2621
2622                 /* start off with i_nlink == 2 (for "." entry) */
2623                 inc_nlink(inode);
2624                 inc_nlink(dentry->d_parent->d_inode);
2625
2626                 /*
2627                  * Control reaches here with cgroup_mutex held.
2628                  * @inode->i_mutex should nest outside cgroup_mutex but we
2629                  * want to populate it immediately without releasing
2630                  * cgroup_mutex.  As @inode isn't visible to anyone else
2631                  * yet, trylock will always succeed without affecting
2632                  * lockdep checks.
2633                  */
2634                 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2635         } else if (S_ISREG(mode)) {
2636                 inode->i_size = 0;
2637                 inode->i_fop = &cgroup_file_operations;
2638                 inode->i_op = &cgroup_file_inode_operations;
2639         }
2640         d_instantiate(dentry, inode);
2641         dget(dentry);   /* Extra count - pin the dentry in core */
2642         return 0;
2643 }
2644
2645 /**
2646  * cgroup_file_mode - deduce file mode of a control file
2647  * @cft: the control file in question
2648  *
2649  * returns cft->mode if ->mode is not 0
2650  * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2651  * returns S_IRUGO if it has only a read handler
2652  * returns S_IWUSR if it has only a write hander
2653  */
2654 static umode_t cgroup_file_mode(const struct cftype *cft)
2655 {
2656         umode_t mode = 0;
2657
2658         if (cft->mode)
2659                 return cft->mode;
2660
2661         if (cft->read || cft->read_u64 || cft->read_s64 ||
2662             cft->read_map || cft->read_seq_string)
2663                 mode |= S_IRUGO;
2664
2665         if (cft->write || cft->write_u64 || cft->write_s64 ||
2666             cft->write_string || cft->trigger)
2667                 mode |= S_IWUSR;
2668
2669         return mode;
2670 }
2671
2672 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2673 {
2674         struct dentry *dir = cgrp->dentry;
2675         struct cgroup *parent = __d_cgrp(dir);
2676         struct dentry *dentry;
2677         struct cfent *cfe;
2678         int error;
2679         umode_t mode;
2680         char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2681
2682         if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
2683             !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
2684                 strcpy(name, cft->ss->name);
2685                 strcat(name, ".");
2686         }
2687         strcat(name, cft->name);
2688
2689         BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2690
2691         cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2692         if (!cfe)
2693                 return -ENOMEM;
2694
2695         dentry = lookup_one_len(name, dir, strlen(name));
2696         if (IS_ERR(dentry)) {
2697                 error = PTR_ERR(dentry);
2698                 goto out;
2699         }
2700
2701         cfe->type = (void *)cft;
2702         cfe->dentry = dentry;
2703         dentry->d_fsdata = cfe;
2704         simple_xattrs_init(&cfe->xattrs);
2705
2706         mode = cgroup_file_mode(cft);
2707         error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2708         if (!error) {
2709                 list_add_tail(&cfe->node, &parent->files);
2710                 cfe = NULL;
2711         }
2712         dput(dentry);
2713 out:
2714         kfree(cfe);
2715         return error;
2716 }
2717
2718 /**
2719  * cgroup_addrm_files - add or remove files to a cgroup directory
2720  * @cgrp: the target cgroup
2721  * @cfts: array of cftypes to be added
2722  * @is_add: whether to add or remove
2723  *
2724  * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2725  * For removals, this function never fails.  If addition fails, this
2726  * function doesn't remove files already added.  The caller is responsible
2727  * for cleaning up.
2728  */
2729 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2730                               bool is_add)
2731 {
2732         struct cftype *cft;
2733         int ret;
2734
2735         lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
2736         lockdep_assert_held(&cgroup_mutex);
2737
2738         for (cft = cfts; cft->name[0] != '\0'; cft++) {
2739                 /* does cft->flags tell us to skip this file on @cgrp? */
2740                 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2741                         continue;
2742                 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2743                         continue;
2744                 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2745                         continue;
2746
2747                 if (is_add) {
2748                         ret = cgroup_add_file(cgrp, cft);
2749                         if (ret) {
2750                                 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2751                                         cft->name, ret);
2752                                 return ret;
2753                         }
2754                 } else {
2755                         cgroup_rm_file(cgrp, cft);
2756                 }
2757         }
2758         return 0;
2759 }
2760
2761 static void cgroup_cfts_prepare(void)
2762         __acquires(&cgroup_mutex)
2763 {
2764         /*
2765          * Thanks to the entanglement with vfs inode locking, we can't walk
2766          * the existing cgroups under cgroup_mutex and create files.
2767          * Instead, we use css_for_each_descendant_pre() and drop RCU read
2768          * lock before calling cgroup_addrm_files().
2769          */
2770         mutex_lock(&cgroup_mutex);
2771 }
2772
2773 static int cgroup_cfts_commit(struct cftype *cfts, bool is_add)
2774         __releases(&cgroup_mutex)
2775 {
2776         LIST_HEAD(pending);
2777         struct cgroup_subsys *ss = cfts[0].ss;
2778         struct cgroup *root = &ss->root->top_cgroup;
2779         struct super_block *sb = ss->root->sb;
2780         struct dentry *prev = NULL;
2781         struct inode *inode;
2782         struct cgroup_subsys_state *css;
2783         u64 update_before;
2784         int ret = 0;
2785
2786         /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2787         if (!cfts || ss->root == &cgroup_dummy_root ||
2788             !atomic_inc_not_zero(&sb->s_active)) {
2789                 mutex_unlock(&cgroup_mutex);
2790                 return 0;
2791         }
2792
2793         /*
2794          * All cgroups which are created after we drop cgroup_mutex will
2795          * have the updated set of files, so we only need to update the
2796          * cgroups created before the current @cgroup_serial_nr_next.
2797          */
2798         update_before = cgroup_serial_nr_next;
2799
2800         mutex_unlock(&cgroup_mutex);
2801
2802         /* add/rm files for all cgroups created before */
2803         rcu_read_lock();
2804         css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2805                 struct cgroup *cgrp = css->cgroup;
2806
2807                 if (cgroup_is_dead(cgrp))
2808                         continue;
2809
2810                 inode = cgrp->dentry->d_inode;
2811                 dget(cgrp->dentry);
2812                 rcu_read_unlock();
2813
2814                 dput(prev);
2815                 prev = cgrp->dentry;
2816
2817                 mutex_lock(&inode->i_mutex);
2818                 mutex_lock(&cgroup_mutex);
2819                 if (cgrp->serial_nr < update_before && !cgroup_is_dead(cgrp))
2820                         ret = cgroup_addrm_files(cgrp, cfts, is_add);
2821                 mutex_unlock(&cgroup_mutex);
2822                 mutex_unlock(&inode->i_mutex);
2823
2824                 rcu_read_lock();
2825                 if (ret)
2826                         break;
2827         }
2828         rcu_read_unlock();
2829         dput(prev);
2830         deactivate_super(sb);
2831         return ret;
2832 }
2833
2834 /**
2835  * cgroup_add_cftypes - add an array of cftypes to a subsystem
2836  * @ss: target cgroup subsystem
2837  * @cfts: zero-length name terminated array of cftypes
2838  *
2839  * Register @cfts to @ss.  Files described by @cfts are created for all
2840  * existing cgroups to which @ss is attached and all future cgroups will
2841  * have them too.  This function can be called anytime whether @ss is
2842  * attached or not.
2843  *
2844  * Returns 0 on successful registration, -errno on failure.  Note that this
2845  * function currently returns 0 as long as @cfts registration is successful
2846  * even if some file creation attempts on existing cgroups fail.
2847  */
2848 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2849 {
2850         struct cftype_set *set;
2851         struct cftype *cft;
2852         int ret;
2853
2854         set = kzalloc(sizeof(*set), GFP_KERNEL);
2855         if (!set)
2856                 return -ENOMEM;
2857
2858         for (cft = cfts; cft->name[0] != '\0'; cft++)
2859                 cft->ss = ss;
2860
2861         cgroup_cfts_prepare();
2862         set->cfts = cfts;
2863         list_add_tail(&set->node, &ss->cftsets);
2864         ret = cgroup_cfts_commit(cfts, true);
2865         if (ret)
2866                 cgroup_rm_cftypes(cfts);
2867         return ret;
2868 }
2869 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2870
2871 /**
2872  * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2873  * @cfts: zero-length name terminated array of cftypes
2874  *
2875  * Unregister @cfts.  Files described by @cfts are removed from all
2876  * existing cgroups and all future cgroups won't have them either.  This
2877  * function can be called anytime whether @cfts' subsys is attached or not.
2878  *
2879  * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2880  * registered.
2881  */
2882 int cgroup_rm_cftypes(struct cftype *cfts)
2883 {
2884         struct cftype_set *set;
2885
2886         if (!cfts || !cfts[0].ss)
2887                 return -ENOENT;
2888
2889         cgroup_cfts_prepare();
2890
2891         list_for_each_entry(set, &cfts[0].ss->cftsets, node) {
2892                 if (set->cfts == cfts) {
2893                         list_del(&set->node);
2894                         kfree(set);
2895                         cgroup_cfts_commit(cfts, false);
2896                         return 0;
2897                 }
2898         }
2899
2900         cgroup_cfts_commit(NULL, false);
2901         return -ENOENT;
2902 }
2903
2904 /**
2905  * cgroup_task_count - count the number of tasks in a cgroup.
2906  * @cgrp: the cgroup in question
2907  *
2908  * Return the number of tasks in the cgroup.
2909  */
2910 int cgroup_task_count(const struct cgroup *cgrp)
2911 {
2912         int count = 0;
2913         struct cgrp_cset_link *link;
2914
2915         read_lock(&css_set_lock);
2916         list_for_each_entry(link, &cgrp->cset_links, cset_link)
2917                 count += atomic_read(&link->cset->refcount);
2918         read_unlock(&css_set_lock);
2919         return count;
2920 }
2921
2922 /*
2923  * To reduce the fork() overhead for systems that are not actually using
2924  * their cgroups capability, we don't maintain the lists running through
2925  * each css_set to its tasks until we see the list actually used - in other
2926  * words after the first call to css_task_iter_start().
2927  */
2928 static void cgroup_enable_task_cg_lists(void)
2929 {
2930         struct task_struct *p, *g;
2931         write_lock(&css_set_lock);
2932         use_task_css_set_links = 1;
2933         /*
2934          * We need tasklist_lock because RCU is not safe against
2935          * while_each_thread(). Besides, a forking task that has passed
2936          * cgroup_post_fork() without seeing use_task_css_set_links = 1
2937          * is not guaranteed to have its child immediately visible in the
2938          * tasklist if we walk through it with RCU.
2939          */
2940         read_lock(&tasklist_lock);
2941         do_each_thread(g, p) {
2942                 task_lock(p);
2943                 /*
2944                  * We should check if the process is exiting, otherwise
2945                  * it will race with cgroup_exit() in that the list
2946                  * entry won't be deleted though the process has exited.
2947                  */
2948                 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2949                         list_add(&p->cg_list, &task_css_set(p)->tasks);
2950                 task_unlock(p);
2951         } while_each_thread(g, p);
2952         read_unlock(&tasklist_lock);
2953         write_unlock(&css_set_lock);
2954 }
2955
2956 /**
2957  * css_next_child - find the next child of a given css
2958  * @pos_css: the current position (%NULL to initiate traversal)
2959  * @parent_css: css whose children to walk
2960  *
2961  * This function returns the next child of @parent_css and should be called
2962  * under RCU read lock.  The only requirement is that @parent_css and
2963  * @pos_css are accessible.  The next sibling is guaranteed to be returned
2964  * regardless of their states.
2965  */
2966 struct cgroup_subsys_state *
2967 css_next_child(struct cgroup_subsys_state *pos_css,
2968                struct cgroup_subsys_state *parent_css)
2969 {
2970         struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
2971         struct cgroup *cgrp = parent_css->cgroup;
2972         struct cgroup *next;
2973
2974         WARN_ON_ONCE(!rcu_read_lock_held());
2975
2976         /*
2977          * @pos could already have been removed.  Once a cgroup is removed,
2978          * its ->sibling.next is no longer updated when its next sibling
2979          * changes.  As CGRP_DEAD assertion is serialized and happens
2980          * before the cgroup is taken off the ->sibling list, if we see it
2981          * unasserted, it's guaranteed that the next sibling hasn't
2982          * finished its grace period even if it's already removed, and thus
2983          * safe to dereference from this RCU critical section.  If
2984          * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
2985          * to be visible as %true here.
2986          *
2987          * If @pos is dead, its next pointer can't be dereferenced;
2988          * however, as each cgroup is given a monotonically increasing
2989          * unique serial number and always appended to the sibling list,
2990          * the next one can be found by walking the parent's children until
2991          * we see a cgroup with higher serial number than @pos's.  While
2992          * this path can be slower, it's taken only when either the current
2993          * cgroup is removed or iteration and removal race.
2994          */
2995         if (!pos) {
2996                 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
2997         } else if (likely(!cgroup_is_dead(pos))) {
2998                 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
2999         } else {
3000                 list_for_each_entry_rcu(next, &cgrp->children, sibling)
3001                         if (next->serial_nr > pos->serial_nr)
3002                                 break;
3003         }
3004
3005         if (&next->sibling == &cgrp->children)
3006                 return NULL;
3007
3008         return cgroup_css(next, parent_css->ss);
3009 }
3010 EXPORT_SYMBOL_GPL(css_next_child);
3011
3012 /**
3013  * css_next_descendant_pre - find the next descendant for pre-order walk
3014  * @pos: the current position (%NULL to initiate traversal)
3015  * @root: css whose descendants to walk
3016  *
3017  * To be used by css_for_each_descendant_pre().  Find the next descendant
3018  * to visit for pre-order traversal of @root's descendants.  @root is
3019  * included in the iteration and the first node to be visited.
3020  *
3021  * While this function requires RCU read locking, it doesn't require the
3022  * whole traversal to be contained in a single RCU critical section.  This
3023  * function will return the correct next descendant as long as both @pos
3024  * and @root are accessible and @pos is a descendant of @root.
3025  */
3026 struct cgroup_subsys_state *
3027 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3028                         struct cgroup_subsys_state *root)
3029 {
3030         struct cgroup_subsys_state *next;
3031
3032         WARN_ON_ONCE(!rcu_read_lock_held());
3033
3034         /* if first iteration, visit @root */
3035         if (!pos)
3036                 return root;
3037
3038         /* visit the first child if exists */
3039         next = css_next_child(NULL, pos);
3040         if (next)
3041                 return next;
3042
3043         /* no child, visit my or the closest ancestor's next sibling */
3044         while (pos != root) {
3045                 next = css_next_child(pos, css_parent(pos));
3046                 if (next)
3047                         return next;
3048                 pos = css_parent(pos);
3049         }
3050
3051         return NULL;
3052 }
3053 EXPORT_SYMBOL_GPL(css_next_descendant_pre);
3054
3055 /**
3056  * css_rightmost_descendant - return the rightmost descendant of a css
3057  * @pos: css of interest
3058  *
3059  * Return the rightmost descendant of @pos.  If there's no descendant, @pos
3060  * is returned.  This can be used during pre-order traversal to skip
3061  * subtree of @pos.
3062  *
3063  * While this function requires RCU read locking, it doesn't require the
3064  * whole traversal to be contained in a single RCU critical section.  This
3065  * function will return the correct rightmost descendant as long as @pos is
3066  * accessible.
3067  */
3068 struct cgroup_subsys_state *
3069 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3070 {
3071         struct cgroup_subsys_state *last, *tmp;
3072
3073         WARN_ON_ONCE(!rcu_read_lock_held());
3074
3075         do {
3076                 last = pos;
3077                 /* ->prev isn't RCU safe, walk ->next till the end */
3078                 pos = NULL;
3079                 css_for_each_child(tmp, last)
3080                         pos = tmp;
3081         } while (pos);
3082
3083         return last;
3084 }
3085 EXPORT_SYMBOL_GPL(css_rightmost_descendant);
3086
3087 static struct cgroup_subsys_state *
3088 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3089 {
3090         struct cgroup_subsys_state *last;
3091
3092         do {
3093                 last = pos;
3094                 pos = css_next_child(NULL, pos);
3095         } while (pos);
3096
3097         return last;
3098 }
3099
3100 /**
3101  * css_next_descendant_post - find the next descendant for post-order walk
3102  * @pos: the current position (%NULL to initiate traversal)
3103  * @root: css whose descendants to walk
3104  *
3105  * To be used by css_for_each_descendant_post().  Find the next descendant
3106  * to visit for post-order traversal of @root's descendants.  @root is
3107  * included in the iteration and the last node to be visited.
3108  *
3109  * While this function requires RCU read locking, it doesn't require the
3110  * whole traversal to be contained in a single RCU critical section.  This
3111  * function will return the correct next descendant as long as both @pos
3112  * and @cgroup are accessible and @pos is a descendant of @cgroup.
3113  */
3114 struct cgroup_subsys_state *
3115 css_next_descendant_post(struct cgroup_subsys_state *pos,
3116                          struct cgroup_subsys_state *root)
3117 {
3118         struct cgroup_subsys_state *next;
3119
3120         WARN_ON_ONCE(!rcu_read_lock_held());
3121
3122         /* if first iteration, visit leftmost descendant which may be @root */
3123         if (!pos)
3124                 return css_leftmost_descendant(root);
3125
3126         /* if we visited @root, we're done */
3127         if (pos == root)
3128                 return NULL;
3129
3130         /* if there's an unvisited sibling, visit its leftmost descendant */
3131         next = css_next_child(pos, css_parent(pos));
3132         if (next)
3133                 return css_leftmost_descendant(next);
3134
3135         /* no sibling left, visit parent */
3136         return css_parent(pos);
3137 }
3138 EXPORT_SYMBOL_GPL(css_next_descendant_post);
3139
3140 /**
3141  * css_advance_task_iter - advance a task itererator to the next css_set
3142  * @it: the iterator to advance
3143  *
3144  * Advance @it to the next css_set to walk.
3145  */
3146 static void css_advance_task_iter(struct css_task_iter *it)
3147 {
3148         struct list_head *l = it->cset_link;
3149         struct cgrp_cset_link *link;
3150         struct css_set *cset;
3151
3152         /* Advance to the next non-empty css_set */
3153         do {
3154                 l = l->next;
3155                 if (l == &it->origin_css->cgroup->cset_links) {
3156                         it->cset_link = NULL;
3157                         return;
3158                 }
3159                 link = list_entry(l, struct cgrp_cset_link, cset_link);
3160                 cset = link->cset;
3161         } while (list_empty(&cset->tasks));
3162         it->cset_link = l;
3163         it->task = cset->tasks.next;
3164 }
3165
3166 /**
3167  * css_task_iter_start - initiate task iteration
3168  * @css: the css to walk tasks of
3169  * @it: the task iterator to use
3170  *
3171  * Initiate iteration through the tasks of @css.  The caller can call
3172  * css_task_iter_next() to walk through the tasks until the function
3173  * returns NULL.  On completion of iteration, css_task_iter_end() must be
3174  * called.
3175  *
3176  * Note that this function acquires a lock which is released when the
3177  * iteration finishes.  The caller can't sleep while iteration is in
3178  * progress.
3179  */
3180 void css_task_iter_start(struct cgroup_subsys_state *css,
3181                          struct css_task_iter *it)
3182         __acquires(css_set_lock)
3183 {
3184         /*
3185          * The first time anyone tries to iterate across a css, we need to
3186          * enable the list linking each css_set to its tasks, and fix up
3187          * all existing tasks.
3188          */
3189         if (!use_task_css_set_links)
3190                 cgroup_enable_task_cg_lists();
3191
3192         read_lock(&css_set_lock);
3193
3194         it->origin_css = css;
3195         it->cset_link = &css->cgroup->cset_links;
3196
3197         css_advance_task_iter(it);
3198 }
3199
3200 /**
3201  * css_task_iter_next - return the next task for the iterator
3202  * @it: the task iterator being iterated
3203  *
3204  * The "next" function for task iteration.  @it should have been
3205  * initialized via css_task_iter_start().  Returns NULL when the iteration
3206  * reaches the end.
3207  */
3208 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3209 {
3210         struct task_struct *res;
3211         struct list_head *l = it->task;
3212         struct cgrp_cset_link *link;
3213
3214         /* If the iterator cg is NULL, we have no tasks */
3215         if (!it->cset_link)
3216                 return NULL;
3217         res = list_entry(l, struct task_struct, cg_list);
3218         /* Advance iterator to find next entry */
3219         l = l->next;
3220         link = list_entry(it->cset_link, struct cgrp_cset_link, cset_link);
3221         if (l == &link->cset->tasks) {
3222                 /*
3223                  * We reached the end of this task list - move on to the
3224                  * next cgrp_cset_link.
3225                  */
3226                 css_advance_task_iter(it);
3227         } else {
3228                 it->task = l;
3229         }
3230         return res;
3231 }
3232
3233 /**
3234  * css_task_iter_end - finish task iteration
3235  * @it: the task iterator to finish
3236  *
3237  * Finish task iteration started by css_task_iter_start().
3238  */
3239 void css_task_iter_end(struct css_task_iter *it)
3240         __releases(css_set_lock)
3241 {
3242         read_unlock(&css_set_lock);
3243 }
3244
3245 static inline int started_after_time(struct task_struct *t1,
3246                                      struct timespec *time,
3247                                      struct task_struct *t2)
3248 {
3249         int start_diff = timespec_compare(&t1->start_time, time);
3250         if (start_diff > 0) {
3251                 return 1;
3252         } else if (start_diff < 0) {
3253                 return 0;
3254         } else {
3255                 /*
3256                  * Arbitrarily, if two processes started at the same
3257                  * time, we'll say that the lower pointer value
3258                  * started first. Note that t2 may have exited by now
3259                  * so this may not be a valid pointer any longer, but
3260                  * that's fine - it still serves to distinguish
3261                  * between two tasks started (effectively) simultaneously.
3262                  */
3263                 return t1 > t2;
3264         }
3265 }
3266
3267 /*
3268  * This function is a callback from heap_insert() and is used to order
3269  * the heap.
3270  * In this case we order the heap in descending task start time.
3271  */
3272 static inline int started_after(void *p1, void *p2)
3273 {
3274         struct task_struct *t1 = p1;
3275         struct task_struct *t2 = p2;
3276         return started_after_time(t1, &t2->start_time, t2);
3277 }
3278
3279 /**
3280  * css_scan_tasks - iterate though all the tasks in a css
3281  * @css: the css to iterate tasks of
3282  * @test: optional test callback
3283  * @process: process callback
3284  * @data: data passed to @test and @process
3285  * @heap: optional pre-allocated heap used for task iteration
3286  *
3287  * Iterate through all the tasks in @css, calling @test for each, and if it
3288  * returns %true, call @process for it also.
3289  *
3290  * @test may be NULL, meaning always true (select all tasks), which
3291  * effectively duplicates css_task_iter_{start,next,end}() but does not
3292  * lock css_set_lock for the call to @process.
3293  *
3294  * It is guaranteed that @process will act on every task that is a member
3295  * of @css for the duration of this call.  This function may or may not
3296  * call @process for tasks that exit or move to a different css during the
3297  * call, or are forked or move into the css during the call.
3298  *
3299  * Note that @test may be called with locks held, and may in some
3300  * situations be called multiple times for the same task, so it should be
3301  * cheap.
3302  *
3303  * If @heap is non-NULL, a heap has been pre-allocated and will be used for
3304  * heap operations (and its "gt" member will be overwritten), else a
3305  * temporary heap will be used (allocation of which may cause this function
3306  * to fail).
3307  */
3308 int css_scan_tasks(struct cgroup_subsys_state *css,
3309                    bool (*test)(struct task_struct *, void *),
3310                    void (*process)(struct task_struct *, void *),
3311                    void *data, struct ptr_heap *heap)
3312 {
3313         int retval, i;
3314         struct css_task_iter it;
3315         struct task_struct *p, *dropped;
3316         /* Never dereference latest_task, since it's not refcounted */
3317         struct task_struct *latest_task = NULL;
3318         struct ptr_heap tmp_heap;
3319         struct timespec latest_time = { 0, 0 };
3320
3321         if (heap) {
3322                 /* The caller supplied our heap and pre-allocated its memory */
3323                 heap->gt = &started_after;
3324         } else {
3325                 /* We need to allocate our own heap memory */
3326                 heap = &tmp_heap;
3327                 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3328                 if (retval)
3329                         /* cannot allocate the heap */
3330                         return retval;
3331         }
3332
3333  again:
3334         /*
3335          * Scan tasks in the css, using the @test callback to determine
3336          * which are of interest, and invoking @process callback on the
3337          * ones which need an update.  Since we don't want to hold any
3338          * locks during the task updates, gather tasks to be processed in a
3339          * heap structure.  The heap is sorted by descending task start
3340          * time.  If the statically-sized heap fills up, we overflow tasks
3341          * that started later, and in future iterations only consider tasks
3342          * that started after the latest task in the previous pass. This
3343          * guarantees forward progress and that we don't miss any tasks.
3344          */
3345         heap->size = 0;
3346         css_task_iter_start(css, &it);
3347         while ((p = css_task_iter_next(&it))) {
3348                 /*
3349                  * Only affect tasks that qualify per the caller's callback,
3350                  * if he provided one
3351                  */
3352                 if (test && !test(p, data))
3353                         continue;
3354                 /*
3355                  * Only process tasks that started after the last task
3356                  * we processed
3357                  */
3358                 if (!started_after_time(p, &latest_time, latest_task))
3359                         continue;
3360                 dropped = heap_insert(heap, p);
3361                 if (dropped == NULL) {
3362                         /*
3363                          * The new task was inserted; the heap wasn't
3364                          * previously full
3365                          */
3366                         get_task_struct(p);
3367                 } else if (dropped != p) {
3368                         /*
3369                          * The new task was inserted, and pushed out a
3370                          * different task
3371                          */
3372                         get_task_struct(p);
3373                         put_task_struct(dropped);
3374                 }
3375                 /*
3376                  * Else the new task was newer than anything already in
3377                  * the heap and wasn't inserted
3378                  */
3379         }
3380         css_task_iter_end(&it);
3381
3382         if (heap->size) {
3383                 for (i = 0; i < heap->size; i++) {
3384                         struct task_struct *q = heap->ptrs[i];
3385                         if (i == 0) {
3386                                 latest_time = q->start_time;
3387                                 latest_task = q;
3388                         }
3389                         /* Process the task per the caller's callback */
3390                         process(q, data);
3391                         put_task_struct(q);
3392                 }
3393                 /*
3394                  * If we had to process any tasks at all, scan again
3395                  * in case some of them were in the middle of forking
3396                  * children that didn't get processed.
3397                  * Not the most efficient way to do it, but it avoids
3398                  * having to take callback_mutex in the fork path
3399                  */
3400                 goto again;
3401         }
3402         if (heap == &tmp_heap)
3403                 heap_free(&tmp_heap);
3404         return 0;
3405 }
3406
3407 static void cgroup_transfer_one_task(struct task_struct *task, void *data)
3408 {
3409         struct cgroup *new_cgroup = data;
3410
3411         mutex_lock(&cgroup_mutex);
3412         cgroup_attach_task(new_cgroup, task, false);
3413         mutex_unlock(&cgroup_mutex);
3414 }
3415
3416 /**
3417  * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3418  * @to: cgroup to which the tasks will be moved
3419  * @from: cgroup in which the tasks currently reside
3420  */
3421 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3422 {
3423         return css_scan_tasks(&from->dummy_css, NULL, cgroup_transfer_one_task,
3424                               to, NULL);
3425 }
3426
3427 /*
3428  * Stuff for reading the 'tasks'/'procs' files.
3429  *
3430  * Reading this file can return large amounts of data if a cgroup has
3431  * *lots* of attached tasks. So it may need several calls to read(),
3432  * but we cannot guarantee that the information we produce is correct
3433  * unless we produce it entirely atomically.
3434  *
3435  */
3436
3437 /* which pidlist file are we talking about? */
3438 enum cgroup_filetype {
3439         CGROUP_FILE_PROCS,
3440         CGROUP_FILE_TASKS,
3441 };
3442
3443 /*
3444  * A pidlist is a list of pids that virtually represents the contents of one
3445  * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3446  * a pair (one each for procs, tasks) for each pid namespace that's relevant
3447  * to the cgroup.
3448  */
3449 struct cgroup_pidlist {
3450         /*
3451          * used to find which pidlist is wanted. doesn't change as long as
3452          * this particular list stays in the list.
3453         */
3454         struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3455         /* array of xids */
3456         pid_t *list;
3457         /* how many elements the above list has */
3458         int length;
3459         /* how many files are using the current array */
3460         int use_count;
3461         /* each of these stored in a list by its cgroup */
3462         struct list_head links;
3463         /* pointer to the cgroup we belong to, for list removal purposes */
3464         struct cgroup *owner;
3465         /* for delayed destruction */
3466         struct delayed_work destroy_dwork;
3467 };
3468
3469 /* seq_file->private points to the following */
3470 struct cgroup_pidlist_open_file {
3471         enum cgroup_filetype            type;
3472         struct cgroup                   *cgrp;
3473         struct cgroup_pidlist           *pidlist;
3474 };
3475
3476 /*
3477  * The following two functions "fix" the issue where there are more pids
3478  * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3479  * TODO: replace with a kernel-wide solution to this problem
3480  */
3481 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3482 static void *pidlist_allocate(int count)
3483 {
3484         if (PIDLIST_TOO_LARGE(count))
3485                 return vmalloc(count * sizeof(pid_t));
3486         else
3487                 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3488 }
3489
3490 static void pidlist_free(void *p)
3491 {
3492         if (is_vmalloc_addr(p))
3493                 vfree(p);
3494         else
3495                 kfree(p);
3496 }
3497
3498 /*
3499  * Used to destroy all pidlists lingering waiting for destroy timer.  None
3500  * should be left afterwards.
3501  */
3502 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
3503 {
3504         struct cgroup_pidlist *l, *tmp_l;
3505
3506         mutex_lock(&cgrp->pidlist_mutex);
3507         list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
3508                 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
3509         mutex_unlock(&cgrp->pidlist_mutex);
3510
3511         flush_workqueue(cgroup_pidlist_destroy_wq);
3512         BUG_ON(!list_empty(&cgrp->pidlists));
3513 }
3514
3515 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
3516 {
3517         struct delayed_work *dwork = to_delayed_work(work);
3518         struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
3519                                                 destroy_dwork);
3520         struct cgroup_pidlist *tofree = NULL;
3521
3522         mutex_lock(&l->owner->pidlist_mutex);
3523
3524         /*
3525          * Destroy iff we didn't race with a new user or get queued again.
3526          * Queued state won't change as it can only be queued while locked.
3527          */
3528         if (!l->use_count && !delayed_work_pending(dwork)) {
3529                 list_del(&l->links);
3530                 pidlist_free(l->list);
3531                 put_pid_ns(l->key.ns);
3532                 tofree = l;
3533         }
3534
3535         mutex_unlock(&l->owner->pidlist_mutex);
3536         kfree(tofree);
3537 }
3538
3539 /*
3540  * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3541  * Returns the number of unique elements.
3542  */
3543 static int pidlist_uniq(pid_t *list, int length)
3544 {
3545         int src, dest = 1;
3546
3547         /*
3548          * we presume the 0th element is unique, so i starts at 1. trivial
3549          * edge cases first; no work needs to be done for either
3550          */
3551         if (length == 0 || length == 1)
3552                 return length;
3553         /* src and dest walk down the list; dest counts unique elements */
3554         for (src = 1; src < length; src++) {
3555                 /* find next unique element */
3556                 while (list[src] == list[src-1]) {
3557                         src++;
3558                         if (src == length)
3559                                 goto after;
3560                 }
3561                 /* dest always points to where the next unique element goes */
3562                 list[dest] = list[src];
3563                 dest++;
3564         }
3565 after:
3566         return dest;
3567 }
3568
3569 static int cmppid(const void *a, const void *b)
3570 {
3571         return *(pid_t *)a - *(pid_t *)b;
3572 }
3573
3574 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3575                                                   enum cgroup_filetype type)
3576 {
3577         struct cgroup_pidlist *l;
3578         /* don't need task_nsproxy() if we're looking at ourself */
3579         struct pid_namespace *ns = task_active_pid_ns(current);
3580
3581         lockdep_assert_held(&cgrp->pidlist_mutex);
3582
3583         list_for_each_entry(l, &cgrp->pidlists, links)
3584                 if (l->key.type == type && l->key.ns == ns)
3585                         return l;
3586         return NULL;
3587 }
3588
3589 /*
3590  * find the appropriate pidlist for our purpose (given procs vs tasks)
3591  * returns with the lock on that pidlist already held, and takes care
3592  * of the use count, or returns NULL with no locks held if we're out of
3593  * memory.
3594  */
3595 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
3596                                                 enum cgroup_filetype type)
3597 {
3598         struct cgroup_pidlist *l;
3599
3600         lockdep_assert_held(&cgrp->pidlist_mutex);
3601
3602         l = cgroup_pidlist_find(cgrp, type);
3603         if (l)
3604                 return l;
3605
3606         /* entry not found; create a new one */
3607         l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3608         if (!l)
3609                 return l;
3610
3611         INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
3612         l->key.type = type;
3613         /* don't need task_nsproxy() if we're looking at ourself */
3614         l->key.ns = get_pid_ns(task_active_pid_ns(current));
3615         l->owner = cgrp;
3616         list_add(&l->links, &cgrp->pidlists);
3617         return l;
3618 }
3619
3620 /*
3621  * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3622  */
3623 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3624                               struct cgroup_pidlist **lp)
3625 {
3626         pid_t *array;
3627         int length;
3628         int pid, n = 0; /* used for populating the array */
3629         struct css_task_iter it;
3630         struct task_struct *tsk;
3631         struct cgroup_pidlist *l;
3632
3633         /*
3634          * If cgroup gets more users after we read count, we won't have
3635          * enough space - tough.  This race is indistinguishable to the
3636          * caller from the case that the additional cgroup users didn't
3637          * show up until sometime later on.
3638          */
3639         length = cgroup_task_count(cgrp);
3640         array = pidlist_allocate(length);
3641         if (!array)
3642                 return -ENOMEM;
3643         /* now, populate the array */
3644         css_task_iter_start(&cgrp->dummy_css, &it);
3645         while ((tsk = css_task_iter_next(&it))) {
3646                 if (unlikely(n == length))
3647                         break;
3648                 /* get tgid or pid for procs or tasks file respectively */
3649                 if (type == CGROUP_FILE_PROCS)
3650                         pid = task_tgid_vnr(tsk);
3651                 else
3652                         pid = task_pid_vnr(tsk);
3653                 if (pid > 0) /* make sure to only use valid results */
3654                         array[n++] = pid;
3655         }
3656         css_task_iter_end(&it);
3657         length = n;
3658         /* now sort & (if procs) strip out duplicates */
3659         sort(array, length, sizeof(pid_t), cmppid, NULL);
3660         if (type == CGROUP_FILE_PROCS)
3661                 length = pidlist_uniq(array, length);
3662
3663         mutex_lock(&cgrp->pidlist_mutex);
3664
3665         l = cgroup_pidlist_find_create(cgrp, type);
3666         if (!l) {
3667                 mutex_unlock(&cgrp->pidlist_mutex);
3668                 pidlist_free(array);
3669                 return -ENOMEM;
3670         }
3671
3672         /* store array, freeing old if necessary */
3673         pidlist_free(l->list);
3674         l->list = array;
3675         l->length = length;
3676         l->use_count++;
3677
3678         mutex_unlock(&cgrp->pidlist_mutex);
3679
3680         *lp = l;
3681         return 0;
3682 }
3683
3684 /**
3685  * cgroupstats_build - build and fill cgroupstats
3686  * @stats: cgroupstats to fill information into
3687  * @dentry: A dentry entry belonging to the cgroup for which stats have
3688  * been requested.
3689  *
3690  * Build and fill cgroupstats so that taskstats can export it to user
3691  * space.
3692  */
3693 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3694 {
3695         int ret = -EINVAL;
3696         struct cgroup *cgrp;
3697         struct css_task_iter it;
3698         struct task_struct *tsk;
3699
3700         /*
3701          * Validate dentry by checking the superblock operations,
3702          * and make sure it's a directory.
3703          */
3704         if (dentry->d_sb->s_op != &cgroup_ops ||
3705             !S_ISDIR(dentry->d_inode->i_mode))
3706                  goto err;
3707
3708         ret = 0;
3709         cgrp = dentry->d_fsdata;
3710
3711         css_task_iter_start(&cgrp->dummy_css, &it);
3712         while ((tsk = css_task_iter_next(&it))) {
3713                 switch (tsk->state) {
3714                 case TASK_RUNNING:
3715                         stats->nr_running++;
3716                         break;
3717                 case TASK_INTERRUPTIBLE:
3718                         stats->nr_sleeping++;
3719                         break;
3720                 case TASK_UNINTERRUPTIBLE:
3721                         stats->nr_uninterruptible++;
3722                         break;
3723                 case TASK_STOPPED:
3724                         stats->nr_stopped++;
3725                         break;
3726                 default:
3727                         if (delayacct_is_task_waiting_on_io(tsk))
3728                                 stats->nr_io_wait++;
3729                         break;
3730                 }
3731         }
3732         css_task_iter_end(&it);
3733
3734 err:
3735         return ret;
3736 }
3737
3738
3739 /*
3740  * seq_file methods for the tasks/procs files. The seq_file position is the
3741  * next pid to display; the seq_file iterator is a pointer to the pid
3742  * in the cgroup->l->list array.
3743  */
3744
3745 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3746 {
3747         /*
3748          * Initially we receive a position value that corresponds to
3749          * one more than the last pid shown (or 0 on the first call or
3750          * after a seek to the start). Use a binary-search to find the
3751          * next pid to display, if any
3752          */
3753         struct cgroup_pidlist_open_file *of = s->private;
3754         struct cgroup_pidlist *l = of->pidlist;
3755         int index = 0, pid = *pos;
3756         int *iter;
3757
3758         mutex_lock(&of->cgrp->pidlist_mutex);
3759         if (pid) {
3760                 int end = l->length;
3761
3762                 while (index < end) {
3763                         int mid = (index + end) / 2;
3764                         if (l->list[mid] == pid) {
3765                                 index = mid;
3766                                 break;
3767                         } else if (l->list[mid] <= pid)
3768                                 index = mid + 1;
3769                         else
3770                                 end = mid;
3771                 }
3772         }
3773         /* If we're off the end of the array, we're done */
3774         if (index >= l->length)
3775                 return NULL;
3776         /* Update the abstract position to be the actual pid that we found */
3777         iter = l->list + index;
3778         *pos = *iter;
3779         return iter;
3780 }
3781
3782 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3783 {
3784         struct cgroup_pidlist_open_file *of = s->private;
3785
3786         mutex_unlock(&of->cgrp->pidlist_mutex);
3787 }
3788
3789 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3790 {
3791         struct cgroup_pidlist_open_file *of = s->private;
3792         struct cgroup_pidlist *l = of->pidlist;
3793         pid_t *p = v;
3794         pid_t *end = l->list + l->length;
3795         /*
3796          * Advance to the next pid in the array. If this goes off the
3797          * end, we're done
3798          */
3799         p++;
3800         if (p >= end) {
3801                 return NULL;
3802         } else {
3803                 *pos = *p;
3804                 return p;
3805         }
3806 }
3807
3808 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3809 {
3810         return seq_printf(s, "%d\n", *(int *)v);
3811 }
3812
3813 /*
3814  * seq_operations functions for iterating on pidlists through seq_file -
3815  * independent of whether it's tasks or procs
3816  */
3817 static const struct seq_operations cgroup_pidlist_seq_operations = {
3818         .start = cgroup_pidlist_start,
3819         .stop = cgroup_pidlist_stop,
3820         .next = cgroup_pidlist_next,
3821         .show = cgroup_pidlist_show,
3822 };
3823
3824 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
3825 {
3826         mutex_lock(&l->owner->pidlist_mutex);
3827         BUG_ON(!l->use_count);
3828         /* if the last user, arm the destroy work */
3829         if (!--l->use_count)
3830                 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
3831                                  CGROUP_PIDLIST_DESTROY_DELAY);
3832         mutex_unlock(&l->owner->pidlist_mutex);
3833 }
3834
3835 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
3836 {
3837         struct cgroup_pidlist_open_file *of;
3838
3839         of = ((struct seq_file *)file->private_data)->private;
3840         cgroup_release_pid_array(of->pidlist);
3841         return seq_release_private(inode, file);
3842 }
3843
3844 static const struct file_operations cgroup_pidlist_operations = {
3845         .read = seq_read,
3846         .llseek = seq_lseek,
3847         .write = cgroup_file_write,
3848         .release = cgroup_pidlist_release,
3849 };
3850
3851 /*
3852  * The following functions handle opens on a file that displays a pidlist
3853  * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3854  * in the cgroup.
3855  */
3856 /* helper function for the two below it */
3857 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
3858 {
3859         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
3860         struct cgroup_pidlist_open_file *of;
3861         struct cgroup_pidlist *l;
3862         int retval;
3863
3864         /* have the array populated */
3865         retval = pidlist_array_load(cgrp, type, &l);
3866         if (retval)
3867                 return retval;
3868         /* configure file information */
3869         file->f_op = &cgroup_pidlist_operations;
3870
3871         of = __seq_open_private(file, &cgroup_pidlist_seq_operations,
3872                                 sizeof(*of));
3873         if (!of) {
3874                 cgroup_release_pid_array(l);
3875                 return -ENOMEM;
3876         }
3877
3878         of->type = type;
3879         of->cgrp = cgrp;
3880         of->pidlist = l;
3881         return 0;
3882 }
3883 static int cgroup_tasks_open(struct inode *unused, struct file *file)
3884 {
3885         return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
3886 }
3887 static int cgroup_procs_open(struct inode *unused, struct file *file)
3888 {
3889         return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
3890 }
3891
3892 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3893                                          struct cftype *cft)
3894 {
3895         return notify_on_release(css->cgroup);
3896 }
3897
3898 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3899                                           struct cftype *cft, u64 val)
3900 {
3901         clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3902         if (val)
3903                 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3904         else
3905                 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3906         return 0;
3907 }
3908
3909 /*
3910  * When dput() is called asynchronously, if umount has been done and
3911  * then deactivate_super() in cgroup_free_fn() kills the superblock,
3912  * there's a small window that vfs will see the root dentry with non-zero
3913  * refcnt and trigger BUG().
3914  *
3915  * That's why we hold a reference before dput() and drop it right after.
3916  */
3917 static void cgroup_dput(struct cgroup *cgrp)
3918 {
3919         struct super_block *sb = cgrp->root->sb;
3920
3921         atomic_inc(&sb->s_active);
3922         dput(cgrp->dentry);
3923         deactivate_super(sb);
3924 }
3925
3926 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3927                                       struct cftype *cft)
3928 {
3929         return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3930 }
3931
3932 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3933                                        struct cftype *cft, u64 val)
3934 {
3935         if (val)
3936                 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3937         else
3938                 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3939         return 0;
3940 }
3941
3942 static struct cftype cgroup_base_files[] = {
3943         {
3944                 .name = "cgroup.procs",
3945                 .open = cgroup_procs_open,
3946                 .write_u64 = cgroup_procs_write,
3947                 .mode = S_IRUGO | S_IWUSR,
3948         },
3949         {
3950                 .name = "cgroup.clone_children",
3951                 .flags = CFTYPE_INSANE,
3952                 .read_u64 = cgroup_clone_children_read,
3953                 .write_u64 = cgroup_clone_children_write,
3954         },
3955         {
3956                 .name = "cgroup.sane_behavior",
3957                 .flags = CFTYPE_ONLY_ON_ROOT,
3958                 .read_seq_string = cgroup_sane_behavior_show,
3959         },
3960
3961         /*
3962          * Historical crazy stuff.  These don't have "cgroup."  prefix and
3963          * don't exist if sane_behavior.  If you're depending on these, be
3964          * prepared to be burned.
3965          */
3966         {
3967                 .name = "tasks",
3968                 .flags = CFTYPE_INSANE,         /* use "procs" instead */
3969                 .open = cgroup_tasks_open,
3970                 .write_u64 = cgroup_tasks_write,
3971                 .mode = S_IRUGO | S_IWUSR,
3972         },
3973         {
3974                 .name = "notify_on_release",
3975                 .flags = CFTYPE_INSANE,
3976                 .read_u64 = cgroup_read_notify_on_release,
3977                 .write_u64 = cgroup_write_notify_on_release,
3978         },
3979         {
3980                 .name = "release_agent",
3981                 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
3982                 .read_seq_string = cgroup_release_agent_show,
3983                 .write_string = cgroup_release_agent_write,
3984                 .max_write_len = PATH_MAX,
3985         },
3986         { }     /* terminate */
3987 };
3988
3989 /**
3990  * cgroup_populate_dir - create subsys files in a cgroup directory
3991  * @cgrp: target cgroup
3992  * @subsys_mask: mask of the subsystem ids whose files should be added
3993  *
3994  * On failure, no file is added.
3995  */
3996 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
3997 {
3998         struct cgroup_subsys *ss;
3999         int i, ret = 0;
4000
4001         /* process cftsets of each subsystem */
4002         for_each_subsys(ss, i) {
4003                 struct cftype_set *set;
4004
4005                 if (!test_bit(i, &subsys_mask))
4006                         continue;
4007
4008                 list_for_each_entry(set, &ss->cftsets, node) {
4009                         ret = cgroup_addrm_files(cgrp, set->cfts, true);
4010                         if (ret < 0)
4011                                 goto err;
4012                 }
4013         }
4014         return 0;
4015 err:
4016         cgroup_clear_dir(cgrp, subsys_mask);
4017         return ret;
4018 }
4019
4020 /*
4021  * css destruction is four-stage process.
4022  *
4023  * 1. Destruction starts.  Killing of the percpu_ref is initiated.
4024  *    Implemented in kill_css().
4025  *
4026  * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4027  *    and thus css_tryget() is guaranteed to fail, the css can be offlined
4028  *    by invoking offline_css().  After offlining, the base ref is put.
4029  *    Implemented in css_killed_work_fn().
4030  *
4031  * 3. When the percpu_ref reaches zero, the only possible remaining
4032  *    accessors are inside RCU read sections.  css_release() schedules the
4033  *    RCU callback.
4034  *
4035  * 4. After the grace period, the css can be freed.  Implemented in
4036  *    css_free_work_fn().
4037  *
4038  * It is actually hairier because both step 2 and 4 require process context
4039  * and thus involve punting to css->destroy_work adding two additional
4040  * steps to the already complex sequence.
4041  */
4042 static void css_free_work_fn(struct work_struct *work)
4043 {
4044         struct cgroup_subsys_state *css =
4045                 container_of(work, struct cgroup_subsys_state, destroy_work);
4046         struct cgroup *cgrp = css->cgroup;
4047
4048         if (css->parent)
4049                 css_put(css->parent);
4050
4051         css->ss->css_free(css);
4052         cgroup_dput(cgrp);
4053 }
4054
4055 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4056 {
4057         struct cgroup_subsys_state *css =
4058                 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4059
4060         /*
4061          * css holds an extra ref to @cgrp->dentry which is put on the last
4062          * css_put().  dput() requires process context which we don't have.
4063          */
4064         INIT_WORK(&css->destroy_work, css_free_work_fn);
4065         queue_work(cgroup_destroy_wq, &css->destroy_work);
4066 }
4067
4068 static void css_release(struct percpu_ref *ref)
4069 {
4070         struct cgroup_subsys_state *css =
4071                 container_of(ref, struct cgroup_subsys_state, refcnt);
4072
4073         call_rcu(&css->rcu_head, css_free_rcu_fn);
4074 }
4075
4076 static void init_css(struct cgroup_subsys_state *css, struct cgroup_subsys *ss,
4077                      struct cgroup *cgrp)
4078 {
4079         css->cgroup = cgrp;
4080         css->ss = ss;
4081         css->flags = 0;
4082
4083         if (cgrp->parent)
4084                 css->parent = cgroup_css(cgrp->parent, ss);
4085         else
4086                 css->flags |= CSS_ROOT;
4087
4088         BUG_ON(cgroup_css(cgrp, ss));
4089 }
4090
4091 /* invoke ->css_online() on a new CSS and mark it online if successful */
4092 static int online_css(struct cgroup_subsys_state *css)
4093 {
4094         struct cgroup_subsys *ss = css->ss;
4095         int ret = 0;
4096
4097         lockdep_assert_held(&cgroup_mutex);
4098
4099         if (ss->css_online)
4100                 ret = ss->css_online(css);
4101         if (!ret) {
4102                 css->flags |= CSS_ONLINE;
4103                 css->cgroup->nr_css++;
4104                 rcu_assign_pointer(css->cgroup->subsys[ss->subsys_id], css);
4105         }
4106         return ret;
4107 }
4108
4109 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4110 static void offline_css(struct cgroup_subsys_state *css)
4111 {
4112         struct cgroup_subsys *ss = css->ss;
4113
4114         lockdep_assert_held(&cgroup_mutex);
4115
4116         if (!(css->flags & CSS_ONLINE))
4117                 return;
4118
4119         if (ss->css_offline)
4120                 ss->css_offline(css);
4121
4122         css->flags &= ~CSS_ONLINE;
4123         css->cgroup->nr_css--;
4124         RCU_INIT_POINTER(css->cgroup->subsys[ss->subsys_id], css);
4125 }
4126
4127 /*
4128  * cgroup_create - create a cgroup
4129  * @parent: cgroup that will be parent of the new cgroup
4130  * @dentry: dentry of the new cgroup
4131  * @mode: mode to set on new inode
4132  *
4133  * Must be called with the mutex on the parent inode held
4134  */
4135 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4136                              umode_t mode)
4137 {
4138         struct cgroup_subsys_state *css_ar[CGROUP_SUBSYS_COUNT] = { };
4139         struct cgroup *cgrp;
4140         struct cgroup_name *name;
4141         struct cgroupfs_root *root = parent->root;
4142         int err = 0;
4143         struct cgroup_subsys *ss;
4144         struct super_block *sb = root->sb;
4145
4146         /* allocate the cgroup and its ID, 0 is reserved for the root */
4147         cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4148         if (!cgrp)
4149                 return -ENOMEM;
4150
4151         name = cgroup_alloc_name(dentry);
4152         if (!name)
4153                 goto err_free_cgrp;
4154         rcu_assign_pointer(cgrp->name, name);
4155
4156         /*
4157          * Temporarily set the pointer to NULL, so idr_find() won't return
4158          * a half-baked cgroup.
4159          */
4160         cgrp->id = idr_alloc(&root->cgroup_idr, NULL, 1, 0, GFP_KERNEL);
4161         if (cgrp->id < 0)
4162                 goto err_free_name;
4163
4164         /*
4165          * Only live parents can have children.  Note that the liveliness
4166          * check isn't strictly necessary because cgroup_mkdir() and
4167          * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4168          * anyway so that locking is contained inside cgroup proper and we
4169          * don't get nasty surprises if we ever grow another caller.
4170          */
4171         if (!cgroup_lock_live_group(parent)) {
4172                 err = -ENODEV;
4173                 goto err_free_id;
4174         }
4175
4176         /* Grab a reference on the superblock so the hierarchy doesn't
4177          * get deleted on unmount if there are child cgroups.  This
4178          * can be done outside cgroup_mutex, since the sb can't
4179          * disappear while someone has an open control file on the
4180          * fs */
4181         atomic_inc(&sb->s_active);
4182
4183         init_cgroup_housekeeping(cgrp);
4184
4185         dentry->d_fsdata = cgrp;
4186         cgrp->dentry = dentry;
4187
4188         cgrp->parent = parent;
4189         cgrp->dummy_css.parent = &parent->dummy_css;
4190         cgrp->root = parent->root;
4191
4192         if (notify_on_release(parent))
4193                 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4194
4195         if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4196                 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4197
4198         for_each_root_subsys(root, ss) {
4199                 struct cgroup_subsys_state *css;
4200
4201                 css = ss->css_alloc(cgroup_css(parent, ss));
4202                 if (IS_ERR(css)) {
4203                         err = PTR_ERR(css);
4204                         goto err_free_all;
4205                 }
4206                 css_ar[ss->subsys_id] = css;
4207
4208                 err = percpu_ref_init(&css->refcnt, css_release);
4209                 if (err)
4210                         goto err_free_all;
4211
4212                 init_css(css, ss, cgrp);
4213         }
4214
4215         /*
4216          * Create directory.  cgroup_create_file() returns with the new
4217          * directory locked on success so that it can be populated without
4218          * dropping cgroup_mutex.
4219          */
4220         err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4221         if (err < 0)
4222                 goto err_free_all;
4223         lockdep_assert_held(&dentry->d_inode->i_mutex);
4224
4225         cgrp->serial_nr = cgroup_serial_nr_next++;
4226
4227         /* allocation complete, commit to creation */
4228         list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4229         root->number_of_cgroups++;
4230
4231         /* each css holds a ref to the cgroup's dentry and the parent css */
4232         for_each_root_subsys(root, ss) {
4233                 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4234
4235                 dget(dentry);
4236                 css_get(css->parent);
4237         }
4238
4239         /* hold a ref to the parent's dentry */
4240         dget(parent->dentry);
4241
4242         /* creation succeeded, notify subsystems */
4243         for_each_root_subsys(root, ss) {
4244                 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4245
4246                 err = online_css(css);
4247                 if (err)
4248                         goto err_destroy;
4249
4250                 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4251                     parent->parent) {
4252                         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",
4253                                    current->comm, current->pid, ss->name);
4254                         if (!strcmp(ss->name, "memory"))
4255                                 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4256                         ss->warned_broken_hierarchy = true;
4257                 }
4258         }
4259
4260         idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4261
4262         err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
4263         if (err)
4264                 goto err_destroy;
4265
4266         err = cgroup_populate_dir(cgrp, root->subsys_mask);
4267         if (err)
4268                 goto err_destroy;
4269
4270         mutex_unlock(&cgroup_mutex);
4271         mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4272
4273         return 0;
4274
4275 err_free_all:
4276         for_each_root_subsys(root, ss) {
4277                 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4278
4279                 if (css) {
4280                         percpu_ref_cancel_init(&css->refcnt);
4281                         ss->css_free(css);
4282                 }
4283         }
4284         mutex_unlock(&cgroup_mutex);
4285         /* Release the reference count that we took on the superblock */
4286         deactivate_super(sb);
4287 err_free_id:
4288         idr_remove(&root->cgroup_idr, cgrp->id);
4289 err_free_name:
4290         kfree(rcu_dereference_raw(cgrp->name));
4291 err_free_cgrp:
4292         kfree(cgrp);
4293         return err;
4294
4295 err_destroy:
4296         cgroup_destroy_locked(cgrp);
4297         mutex_unlock(&cgroup_mutex);
4298         mutex_unlock(&dentry->d_inode->i_mutex);
4299         return err;
4300 }
4301
4302 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4303 {
4304         struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4305
4306         /* the vfs holds inode->i_mutex already */
4307         return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4308 }
4309
4310 /*
4311  * This is called when the refcnt of a css is confirmed to be killed.
4312  * css_tryget() is now guaranteed to fail.
4313  */
4314 static void css_killed_work_fn(struct work_struct *work)
4315 {
4316         struct cgroup_subsys_state *css =
4317                 container_of(work, struct cgroup_subsys_state, destroy_work);
4318         struct cgroup *cgrp = css->cgroup;
4319
4320         mutex_lock(&cgroup_mutex);
4321
4322         /*
4323          * css_tryget() is guaranteed to fail now.  Tell subsystems to
4324          * initate destruction.
4325          */
4326         offline_css(css);
4327
4328         /*
4329          * If @cgrp is marked dead, it's waiting for refs of all css's to
4330          * be disabled before proceeding to the second phase of cgroup
4331          * destruction.  If we are the last one, kick it off.
4332          */
4333         if (!cgrp->nr_css && cgroup_is_dead(cgrp))
4334                 cgroup_destroy_css_killed(cgrp);
4335
4336         mutex_unlock(&cgroup_mutex);
4337
4338         /*
4339          * Put the css refs from kill_css().  Each css holds an extra
4340          * reference to the cgroup's dentry and cgroup removal proceeds
4341          * regardless of css refs.  On the last put of each css, whenever
4342          * that may be, the extra dentry ref is put so that dentry
4343          * destruction happens only after all css's are released.
4344          */
4345         css_put(css);
4346 }
4347
4348 /* css kill confirmation processing requires process context, bounce */
4349 static void css_killed_ref_fn(struct percpu_ref *ref)
4350 {
4351         struct cgroup_subsys_state *css =
4352                 container_of(ref, struct cgroup_subsys_state, refcnt);
4353
4354         INIT_WORK(&css->destroy_work, css_killed_work_fn);
4355         queue_work(cgroup_destroy_wq, &css->destroy_work);
4356 }
4357
4358 /**
4359  * kill_css - destroy a css
4360  * @css: css to destroy
4361  *
4362  * This function initiates destruction of @css by removing cgroup interface
4363  * files and putting its base reference.  ->css_offline() will be invoked
4364  * asynchronously once css_tryget() is guaranteed to fail and when the
4365  * reference count reaches zero, @css will be released.
4366  */
4367 static void kill_css(struct cgroup_subsys_state *css)
4368 {
4369         cgroup_clear_dir(css->cgroup, 1 << css->ss->subsys_id);
4370
4371         /*
4372          * Killing would put the base ref, but we need to keep it alive
4373          * until after ->css_offline().
4374          */
4375         css_get(css);
4376
4377         /*
4378          * cgroup core guarantees that, by the time ->css_offline() is
4379          * invoked, no new css reference will be given out via
4380          * css_tryget().  We can't simply call percpu_ref_kill() and
4381          * proceed to offlining css's because percpu_ref_kill() doesn't
4382          * guarantee that the ref is seen as killed on all CPUs on return.
4383          *
4384          * Use percpu_ref_kill_and_confirm() to get notifications as each
4385          * css is confirmed to be seen as killed on all CPUs.
4386          */
4387         percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4388 }
4389
4390 /**
4391  * cgroup_destroy_locked - the first stage of cgroup destruction
4392  * @cgrp: cgroup to be destroyed
4393  *
4394  * css's make use of percpu refcnts whose killing latency shouldn't be
4395  * exposed to userland and are RCU protected.  Also, cgroup core needs to
4396  * guarantee that css_tryget() won't succeed by the time ->css_offline() is
4397  * invoked.  To satisfy all the requirements, destruction is implemented in
4398  * the following two steps.
4399  *
4400  * s1. Verify @cgrp can be destroyed and mark it dying.  Remove all
4401  *     userland visible parts and start killing the percpu refcnts of
4402  *     css's.  Set up so that the next stage will be kicked off once all
4403  *     the percpu refcnts are confirmed to be killed.
4404  *
4405  * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4406  *     rest of destruction.  Once all cgroup references are gone, the
4407  *     cgroup is RCU-freed.
4408  *
4409  * This function implements s1.  After this step, @cgrp is gone as far as
4410  * the userland is concerned and a new cgroup with the same name may be
4411  * created.  As cgroup doesn't care about the names internally, this
4412  * doesn't cause any problem.
4413  */
4414 static int cgroup_destroy_locked(struct cgroup *cgrp)
4415         __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4416 {
4417         struct dentry *d = cgrp->dentry;
4418         struct cgroup_subsys *ss;
4419         struct cgroup *child;
4420         bool empty;
4421
4422         lockdep_assert_held(&d->d_inode->i_mutex);
4423         lockdep_assert_held(&cgroup_mutex);
4424
4425         /*
4426          * css_set_lock synchronizes access to ->cset_links and prevents
4427          * @cgrp from being removed while __put_css_set() is in progress.
4428          */
4429         read_lock(&css_set_lock);
4430         empty = list_empty(&cgrp->cset_links);
4431         read_unlock(&css_set_lock);
4432         if (!empty)
4433                 return -EBUSY;
4434
4435         /*
4436          * Make sure there's no live children.  We can't test ->children
4437          * emptiness as dead children linger on it while being destroyed;
4438          * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
4439          */
4440         empty = true;
4441         rcu_read_lock();
4442         list_for_each_entry_rcu(child, &cgrp->children, sibling) {
4443                 empty = cgroup_is_dead(child);
4444                 if (!empty)
4445                         break;
4446         }
4447         rcu_read_unlock();
4448         if (!empty)
4449                 return -EBUSY;
4450
4451         /*
4452          * Initiate massacre of all css's.  cgroup_destroy_css_killed()
4453          * will be invoked to perform the rest of destruction once the
4454          * percpu refs of all css's are confirmed to be killed.
4455          */
4456         for_each_root_subsys(cgrp->root, ss)
4457                 kill_css(cgroup_css(cgrp, ss));
4458
4459         /*
4460          * Mark @cgrp dead.  This prevents further task migration and child
4461          * creation by disabling cgroup_lock_live_group().  Note that
4462          * CGRP_DEAD assertion is depended upon by css_next_child() to
4463          * resume iteration after dropping RCU read lock.  See
4464          * css_next_child() for details.
4465          */
4466         set_bit(CGRP_DEAD, &cgrp->flags);
4467
4468         /* CGRP_DEAD is set, remove from ->release_list for the last time */
4469         raw_spin_lock(&release_list_lock);
4470         if (!list_empty(&cgrp->release_list))
4471                 list_del_init(&cgrp->release_list);
4472         raw_spin_unlock(&release_list_lock);
4473
4474         /*
4475          * If @cgrp has css's attached, the second stage of cgroup
4476          * destruction is kicked off from css_killed_work_fn() after the
4477          * refs of all attached css's are killed.  If @cgrp doesn't have
4478          * any css, we kick it off here.
4479          */
4480         if (!cgrp->nr_css)
4481                 cgroup_destroy_css_killed(cgrp);
4482
4483         /*
4484          * Clear the base files and remove @cgrp directory.  The removal
4485          * puts the base ref but we aren't quite done with @cgrp yet, so
4486          * hold onto it.
4487          */
4488         cgroup_addrm_files(cgrp, cgroup_base_files, false);
4489         dget(d);
4490         cgroup_d_remove_dir(d);
4491
4492         return 0;
4493 };
4494
4495 /**
4496  * cgroup_destroy_css_killed - the second step of cgroup destruction
4497  * @work: cgroup->destroy_free_work
4498  *
4499  * This function is invoked from a work item for a cgroup which is being
4500  * destroyed after all css's are offlined and performs the rest of
4501  * destruction.  This is the second step of destruction described in the
4502  * comment above cgroup_destroy_locked().
4503  */
4504 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
4505 {
4506         struct cgroup *parent = cgrp->parent;
4507         struct dentry *d = cgrp->dentry;
4508
4509         lockdep_assert_held(&cgroup_mutex);
4510
4511         /* delete this cgroup from parent->children */
4512         list_del_rcu(&cgrp->sibling);
4513
4514         /*
4515          * We should remove the cgroup object from idr before its grace
4516          * period starts, so we won't be looking up a cgroup while the
4517          * cgroup is being freed.
4518          */
4519         idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4520         cgrp->id = -1;
4521
4522         dput(d);
4523
4524         set_bit(CGRP_RELEASABLE, &parent->flags);
4525         check_for_release(parent);
4526 }
4527
4528 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4529 {
4530         int ret;
4531
4532         mutex_lock(&cgroup_mutex);
4533         ret = cgroup_destroy_locked(dentry->d_fsdata);
4534         mutex_unlock(&cgroup_mutex);
4535
4536         return ret;
4537 }
4538
4539 static void __init_or_module cgroup_init_cftsets(struct cgroup_subsys *ss)
4540 {
4541         INIT_LIST_HEAD(&ss->cftsets);
4542
4543         /*
4544          * base_cftset is embedded in subsys itself, no need to worry about
4545          * deregistration.
4546          */
4547         if (ss->base_cftypes) {
4548                 struct cftype *cft;
4549
4550                 for (cft = ss->base_cftypes; cft->name[0] != '\0'; cft++)
4551                         cft->ss = ss;
4552
4553                 ss->base_cftset.cfts = ss->base_cftypes;
4554                 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4555         }
4556 }
4557
4558 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4559 {
4560         struct cgroup_subsys_state *css;
4561
4562         printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4563
4564         mutex_lock(&cgroup_mutex);
4565
4566         /* init base cftset */
4567         cgroup_init_cftsets(ss);
4568
4569         /* Create the top cgroup state for this subsystem */
4570         list_add(&ss->sibling, &cgroup_dummy_root.subsys_list);
4571         ss->root = &cgroup_dummy_root;
4572         css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
4573         /* We don't handle early failures gracefully */
4574         BUG_ON(IS_ERR(css));
4575         init_css(css, ss, cgroup_dummy_top);
4576
4577         /* Update the init_css_set to contain a subsys
4578          * pointer to this state - since the subsystem is
4579          * newly registered, all tasks and hence the
4580          * init_css_set is in the subsystem's top cgroup. */
4581         init_css_set.subsys[ss->subsys_id] = css;
4582
4583         need_forkexit_callback |= ss->fork || ss->exit;
4584
4585         /* At system boot, before all subsystems have been
4586          * registered, no tasks have been forked, so we don't
4587          * need to invoke fork callbacks here. */
4588         BUG_ON(!list_empty(&init_task.tasks));
4589
4590         BUG_ON(online_css(css));
4591
4592         mutex_unlock(&cgroup_mutex);
4593
4594         /* this function shouldn't be used with modular subsystems, since they
4595          * need to register a subsys_id, among other things */
4596         BUG_ON(ss->module);
4597 }
4598
4599 /**
4600  * cgroup_load_subsys: load and register a modular subsystem at runtime
4601  * @ss: the subsystem to load
4602  *
4603  * This function should be called in a modular subsystem's initcall. If the
4604  * subsystem is built as a module, it will be assigned a new subsys_id and set
4605  * up for use. If the subsystem is built-in anyway, work is delegated to the
4606  * simpler cgroup_init_subsys.
4607  */
4608 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
4609 {
4610         struct cgroup_subsys_state *css;
4611         int i, ret;
4612         struct hlist_node *tmp;
4613         struct css_set *cset;
4614         unsigned long key;
4615
4616         /* check name and function validity */
4617         if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
4618             ss->css_alloc == NULL || ss->css_free == NULL)
4619                 return -EINVAL;
4620
4621         /*
4622          * we don't support callbacks in modular subsystems. this check is
4623          * before the ss->module check for consistency; a subsystem that could
4624          * be a module should still have no callbacks even if the user isn't
4625          * compiling it as one.
4626          */
4627         if (ss->fork || ss->exit)
4628                 return -EINVAL;
4629
4630         /*
4631          * an optionally modular subsystem is built-in: we want to do nothing,
4632          * since cgroup_init_subsys will have already taken care of it.
4633          */
4634         if (ss->module == NULL) {
4635                 /* a sanity check */
4636                 BUG_ON(cgroup_subsys[ss->subsys_id] != ss);
4637                 return 0;
4638         }
4639
4640         /* init base cftset */
4641         cgroup_init_cftsets(ss);
4642
4643         mutex_lock(&cgroup_mutex);
4644         cgroup_subsys[ss->subsys_id] = ss;
4645
4646         /*
4647          * no ss->css_alloc seems to need anything important in the ss
4648          * struct, so this can happen first (i.e. before the dummy root
4649          * attachment).
4650          */
4651         css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
4652         if (IS_ERR(css)) {
4653                 /* failure case - need to deassign the cgroup_subsys[] slot. */
4654                 cgroup_subsys[ss->subsys_id] = NULL;
4655                 mutex_unlock(&cgroup_mutex);
4656                 return PTR_ERR(css);
4657         }
4658
4659         list_add(&ss->sibling, &cgroup_dummy_root.subsys_list);
4660         ss->root = &cgroup_dummy_root;
4661
4662         /* our new subsystem will be attached to the dummy hierarchy. */
4663         init_css(css, ss, cgroup_dummy_top);
4664
4665         /*
4666          * Now we need to entangle the css into the existing css_sets. unlike
4667          * in cgroup_init_subsys, there are now multiple css_sets, so each one
4668          * will need a new pointer to it; done by iterating the css_set_table.
4669          * furthermore, modifying the existing css_sets will corrupt the hash
4670          * table state, so each changed css_set will need its hash recomputed.
4671          * this is all done under the css_set_lock.
4672          */
4673         write_lock(&css_set_lock);
4674         hash_for_each_safe(css_set_table, i, tmp, cset, hlist) {
4675                 /* skip entries that we already rehashed */
4676                 if (cset->subsys[ss->subsys_id])
4677                         continue;
4678                 /* remove existing entry */
4679                 hash_del(&cset->hlist);
4680                 /* set new value */
4681                 cset->subsys[ss->subsys_id] = css;
4682                 /* recompute hash and restore entry */
4683                 key = css_set_hash(cset->subsys);
4684                 hash_add(css_set_table, &cset->hlist, key);
4685         }
4686         write_unlock(&css_set_lock);
4687
4688         ret = online_css(css);
4689         if (ret)
4690                 goto err_unload;
4691
4692         /* success! */
4693         mutex_unlock(&cgroup_mutex);
4694         return 0;
4695
4696 err_unload:
4697         mutex_unlock(&cgroup_mutex);
4698         /* @ss can't be mounted here as try_module_get() would fail */
4699         cgroup_unload_subsys(ss);
4700         return ret;
4701 }
4702 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
4703
4704 /**
4705  * cgroup_unload_subsys: unload a modular subsystem
4706  * @ss: the subsystem to unload
4707  *
4708  * This function should be called in a modular subsystem's exitcall. When this
4709  * function is invoked, the refcount on the subsystem's module will be 0, so
4710  * the subsystem will not be attached to any hierarchy.
4711  */
4712 void cgroup_unload_subsys(struct cgroup_subsys *ss)
4713 {
4714         struct cgrp_cset_link *link;
4715
4716         BUG_ON(ss->module == NULL);
4717
4718         /*
4719          * we shouldn't be called if the subsystem is in use, and the use of
4720          * try_module_get() in rebind_subsystems() should ensure that it
4721          * doesn't start being used while we're killing it off.
4722          */
4723         BUG_ON(ss->root != &cgroup_dummy_root);
4724
4725         mutex_lock(&cgroup_mutex);
4726
4727         offline_css(cgroup_css(cgroup_dummy_top, ss));
4728
4729         /* deassign the subsys_id */
4730         cgroup_subsys[ss->subsys_id] = NULL;
4731
4732         /* remove subsystem from the dummy root's list of subsystems */
4733         list_del_init(&ss->sibling);
4734
4735         /*
4736          * disentangle the css from all css_sets attached to the dummy
4737          * top. as in loading, we need to pay our respects to the hashtable
4738          * gods.
4739          */
4740         write_lock(&css_set_lock);
4741         list_for_each_entry(link, &cgroup_dummy_top->cset_links, cset_link) {
4742                 struct css_set *cset = link->cset;
4743                 unsigned long key;
4744
4745                 hash_del(&cset->hlist);
4746                 cset->subsys[ss->subsys_id] = NULL;
4747                 key = css_set_hash(cset->subsys);
4748                 hash_add(css_set_table, &cset->hlist, key);
4749         }
4750         write_unlock(&css_set_lock);
4751
4752         /*
4753          * remove subsystem's css from the cgroup_dummy_top and free it -
4754          * need to free before marking as null because ss->css_free needs
4755          * the cgrp->subsys pointer to find their state.
4756          */
4757         ss->css_free(cgroup_css(cgroup_dummy_top, ss));
4758         RCU_INIT_POINTER(cgroup_dummy_top->subsys[ss->subsys_id], NULL);
4759
4760         mutex_unlock(&cgroup_mutex);
4761 }
4762 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
4763
4764 /**
4765  * cgroup_init_early - cgroup initialization at system boot
4766  *
4767  * Initialize cgroups at system boot, and initialize any
4768  * subsystems that request early init.
4769  */
4770 int __init cgroup_init_early(void)
4771 {
4772         struct cgroup_subsys *ss;
4773         int i;
4774
4775         atomic_set(&init_css_set.refcount, 1);
4776         INIT_LIST_HEAD(&init_css_set.cgrp_links);
4777         INIT_LIST_HEAD(&init_css_set.tasks);
4778         INIT_HLIST_NODE(&init_css_set.hlist);
4779         css_set_count = 1;
4780         init_cgroup_root(&cgroup_dummy_root);
4781         cgroup_root_count = 1;
4782         RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4783
4784         init_cgrp_cset_link.cset = &init_css_set;
4785         init_cgrp_cset_link.cgrp = cgroup_dummy_top;
4786         list_add(&init_cgrp_cset_link.cset_link, &cgroup_dummy_top->cset_links);
4787         list_add(&init_cgrp_cset_link.cgrp_link, &init_css_set.cgrp_links);
4788
4789         /* at bootup time, we don't worry about modular subsystems */
4790         for_each_builtin_subsys(ss, i) {
4791                 BUG_ON(!ss->name);
4792                 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
4793                 BUG_ON(!ss->css_alloc);
4794                 BUG_ON(!ss->css_free);
4795                 if (ss->subsys_id != i) {
4796                         printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
4797                                ss->name, ss->subsys_id);
4798                         BUG();
4799                 }
4800
4801                 if (ss->early_init)
4802                         cgroup_init_subsys(ss);
4803         }
4804         return 0;
4805 }
4806
4807 /**
4808  * cgroup_init - cgroup initialization
4809  *
4810  * Register cgroup filesystem and /proc file, and initialize
4811  * any subsystems that didn't request early init.
4812  */
4813 int __init cgroup_init(void)
4814 {
4815         struct cgroup_subsys *ss;
4816         unsigned long key;
4817         int i, err;
4818
4819         err = bdi_init(&cgroup_backing_dev_info);
4820         if (err)
4821                 return err;
4822
4823         for_each_builtin_subsys(ss, i) {
4824                 if (!ss->early_init)
4825                         cgroup_init_subsys(ss);
4826         }
4827
4828         /* allocate id for the dummy hierarchy */
4829         mutex_lock(&cgroup_mutex);
4830         mutex_lock(&cgroup_root_mutex);
4831
4832         /* Add init_css_set to the hash table */
4833         key = css_set_hash(init_css_set.subsys);
4834         hash_add(css_set_table, &init_css_set.hlist, key);
4835
4836         BUG_ON(cgroup_init_root_id(&cgroup_dummy_root, 0, 1));
4837
4838         err = idr_alloc(&cgroup_dummy_root.cgroup_idr, cgroup_dummy_top,
4839                         0, 1, GFP_KERNEL);
4840         BUG_ON(err < 0);
4841
4842         mutex_unlock(&cgroup_root_mutex);
4843         mutex_unlock(&cgroup_mutex);
4844
4845         cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4846         if (!cgroup_kobj) {
4847                 err = -ENOMEM;
4848                 goto out;
4849         }
4850
4851         err = register_filesystem(&cgroup_fs_type);
4852         if (err < 0) {
4853                 kobject_put(cgroup_kobj);
4854                 goto out;
4855         }
4856
4857         proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4858
4859 out:
4860         if (err)
4861                 bdi_destroy(&cgroup_backing_dev_info);
4862
4863         return err;
4864 }
4865
4866 static int __init cgroup_wq_init(void)
4867 {
4868         /*
4869          * There isn't much point in executing destruction path in
4870          * parallel.  Good chunk is serialized with cgroup_mutex anyway.
4871          * Use 1 for @max_active.
4872          *
4873          * We would prefer to do this in cgroup_init() above, but that
4874          * is called before init_workqueues(): so leave this until after.
4875          */
4876         cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
4877         BUG_ON(!cgroup_destroy_wq);
4878
4879         /*
4880          * Used to destroy pidlists and separate to serve as flush domain.
4881          * Cap @max_active to 1 too.
4882          */
4883         cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
4884                                                     0, 1);
4885         BUG_ON(!cgroup_pidlist_destroy_wq);
4886
4887         return 0;
4888 }
4889 core_initcall(cgroup_wq_init);
4890
4891 /*
4892  * proc_cgroup_show()
4893  *  - Print task's cgroup paths into seq_file, one line for each hierarchy
4894  *  - Used for /proc/<pid>/cgroup.
4895  *  - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4896  *    doesn't really matter if tsk->cgroup changes after we read it,
4897  *    and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4898  *    anyway.  No need to check that tsk->cgroup != NULL, thanks to
4899  *    the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4900  *    cgroup to top_cgroup.
4901  */
4902
4903 /* TODO: Use a proper seq_file iterator */
4904 int proc_cgroup_show(struct seq_file *m, void *v)
4905 {
4906         struct pid *pid;
4907         struct task_struct *tsk;
4908         char *buf;
4909         int retval;
4910         struct cgroupfs_root *root;
4911
4912         retval = -ENOMEM;
4913         buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4914         if (!buf)
4915                 goto out;
4916
4917         retval = -ESRCH;
4918         pid = m->private;
4919         tsk = get_pid_task(pid, PIDTYPE_PID);
4920         if (!tsk)
4921                 goto out_free;
4922
4923         retval = 0;
4924
4925         mutex_lock(&cgroup_mutex);
4926
4927         for_each_active_root(root) {
4928                 struct cgroup_subsys *ss;
4929                 struct cgroup *cgrp;
4930                 int count = 0;
4931
4932                 seq_printf(m, "%d:", root->hierarchy_id);
4933                 for_each_root_subsys(root, ss)
4934                         seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4935                 if (strlen(root->name))
4936                         seq_printf(m, "%sname=%s", count ? "," : "",
4937                                    root->name);
4938                 seq_putc(m, ':');
4939                 cgrp = task_cgroup_from_root(tsk, root);
4940                 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
4941                 if (retval < 0)
4942                         goto out_unlock;
4943                 seq_puts(m, buf);
4944                 seq_putc(m, '\n');
4945         }
4946
4947 out_unlock:
4948         mutex_unlock(&cgroup_mutex);
4949         put_task_struct(tsk);
4950 out_free:
4951         kfree(buf);
4952 out:
4953         return retval;
4954 }
4955
4956 /* Display information about each subsystem and each hierarchy */
4957 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4958 {
4959         struct cgroup_subsys *ss;
4960         int i;
4961
4962         seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4963         /*
4964          * ideally we don't want subsystems moving around while we do this.
4965          * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4966          * subsys/hierarchy state.
4967          */
4968         mutex_lock(&cgroup_mutex);
4969
4970         for_each_subsys(ss, i)
4971                 seq_printf(m, "%s\t%d\t%d\t%d\n",
4972                            ss->name, ss->root->hierarchy_id,
4973                            ss->root->number_of_cgroups, !ss->disabled);
4974
4975         mutex_unlock(&cgroup_mutex);
4976         return 0;
4977 }
4978
4979 static int cgroupstats_open(struct inode *inode, struct file *file)
4980 {
4981         return single_open(file, proc_cgroupstats_show, NULL);
4982 }
4983
4984 static const struct file_operations proc_cgroupstats_operations = {
4985         .open = cgroupstats_open,
4986         .read = seq_read,
4987         .llseek = seq_lseek,
4988         .release = single_release,
4989 };
4990
4991 /**
4992  * cgroup_fork - attach newly forked task to its parents cgroup.
4993  * @child: pointer to task_struct of forking parent process.
4994  *
4995  * Description: A task inherits its parent's cgroup at fork().
4996  *
4997  * A pointer to the shared css_set was automatically copied in
4998  * fork.c by dup_task_struct().  However, we ignore that copy, since
4999  * it was not made under the protection of RCU or cgroup_mutex, so
5000  * might no longer be a valid cgroup pointer.  cgroup_attach_task() might
5001  * have already changed current->cgroups, allowing the previously
5002  * referenced cgroup group to be removed and freed.
5003  *
5004  * At the point that cgroup_fork() is called, 'current' is the parent
5005  * task, and the passed argument 'child' points to the child task.
5006  */
5007 void cgroup_fork(struct task_struct *child)
5008 {
5009         task_lock(current);
5010         get_css_set(task_css_set(current));
5011         child->cgroups = current->cgroups;
5012         task_unlock(current);
5013         INIT_LIST_HEAD(&child->cg_list);
5014 }
5015
5016 /**
5017  * cgroup_post_fork - called on a new task after adding it to the task list
5018  * @child: the task in question
5019  *
5020  * Adds the task to the list running through its css_set if necessary and
5021  * call the subsystem fork() callbacks.  Has to be after the task is
5022  * visible on the task list in case we race with the first call to
5023  * cgroup_task_iter_start() - to guarantee that the new task ends up on its
5024  * list.
5025  */
5026 void cgroup_post_fork(struct task_struct *child)
5027 {
5028         struct cgroup_subsys *ss;
5029         int i;
5030
5031         /*
5032          * use_task_css_set_links is set to 1 before we walk the tasklist
5033          * under the tasklist_lock and we read it here after we added the child
5034          * to the tasklist under the tasklist_lock as well. If the child wasn't
5035          * yet in the tasklist when we walked through it from
5036          * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
5037          * should be visible now due to the paired locking and barriers implied
5038          * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
5039          * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
5040          * lock on fork.
5041          */
5042         if (use_task_css_set_links) {
5043                 write_lock(&css_set_lock);
5044                 task_lock(child);
5045                 if (list_empty(&child->cg_list))
5046                         list_add(&child->cg_list, &task_css_set(child)->tasks);
5047                 task_unlock(child);
5048                 write_unlock(&css_set_lock);
5049         }
5050
5051         /*
5052          * Call ss->fork().  This must happen after @child is linked on
5053          * css_set; otherwise, @child might change state between ->fork()
5054          * and addition to css_set.
5055          */
5056         if (need_forkexit_callback) {
5057                 /*
5058                  * fork/exit callbacks are supported only for builtin
5059                  * subsystems, and the builtin section of the subsys
5060                  * array is immutable, so we don't need to lock the
5061                  * subsys array here. On the other hand, modular section
5062                  * of the array can be freed at module unload, so we
5063                  * can't touch that.
5064                  */
5065                 for_each_builtin_subsys(ss, i)
5066                         if (ss->fork)
5067                                 ss->fork(child);
5068         }
5069 }
5070
5071 /**
5072  * cgroup_exit - detach cgroup from exiting task
5073  * @tsk: pointer to task_struct of exiting process
5074  * @run_callback: run exit callbacks?
5075  *
5076  * Description: Detach cgroup from @tsk and release it.
5077  *
5078  * Note that cgroups marked notify_on_release force every task in
5079  * them to take the global cgroup_mutex mutex when exiting.
5080  * This could impact scaling on very large systems.  Be reluctant to
5081  * use notify_on_release cgroups where very high task exit scaling
5082  * is required on large systems.
5083  *
5084  * the_top_cgroup_hack:
5085  *
5086  *    Set the exiting tasks cgroup to the root cgroup (top_cgroup).
5087  *
5088  *    We call cgroup_exit() while the task is still competent to
5089  *    handle notify_on_release(), then leave the task attached to the
5090  *    root cgroup in each hierarchy for the remainder of its exit.
5091  *
5092  *    To do this properly, we would increment the reference count on
5093  *    top_cgroup, and near the very end of the kernel/exit.c do_exit()
5094  *    code we would add a second cgroup function call, to drop that
5095  *    reference.  This would just create an unnecessary hot spot on
5096  *    the top_cgroup reference count, to no avail.
5097  *
5098  *    Normally, holding a reference to a cgroup without bumping its
5099  *    count is unsafe.   The cgroup could go away, or someone could
5100  *    attach us to a different cgroup, decrementing the count on
5101  *    the first cgroup that we never incremented.  But in this case,
5102  *    top_cgroup isn't going away, and either task has PF_EXITING set,
5103  *    which wards off any cgroup_attach_task() attempts, or task is a failed
5104  *    fork, never visible to cgroup_attach_task.
5105  */
5106 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
5107 {
5108         struct cgroup_subsys *ss;
5109         struct css_set *cset;
5110         int i;
5111
5112         /*
5113          * Unlink from the css_set task list if necessary.
5114          * Optimistically check cg_list before taking
5115          * css_set_lock
5116          */
5117         if (!list_empty(&tsk->cg_list)) {
5118                 write_lock(&css_set_lock);
5119                 if (!list_empty(&tsk->cg_list))
5120                         list_del_init(&tsk->cg_list);
5121                 write_unlock(&css_set_lock);
5122         }
5123
5124         /* Reassign the task to the init_css_set. */
5125         task_lock(tsk);
5126         cset = task_css_set(tsk);
5127         RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
5128
5129         if (run_callbacks && need_forkexit_callback) {
5130                 /*
5131                  * fork/exit callbacks are supported only for builtin
5132                  * subsystems, see cgroup_post_fork() for details.
5133                  */
5134                 for_each_builtin_subsys(ss, i) {
5135                         if (ss->exit) {
5136                                 struct cgroup_subsys_state *old_css = cset->subsys[i];
5137                                 struct cgroup_subsys_state *css = task_css(tsk, i);
5138
5139                                 ss->exit(css, old_css, tsk);
5140                         }
5141                 }
5142         }
5143         task_unlock(tsk);
5144
5145         put_css_set_taskexit(cset);
5146 }
5147
5148 static void check_for_release(struct cgroup *cgrp)
5149 {
5150         if (cgroup_is_releasable(cgrp) &&
5151             list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
5152                 /*
5153                  * Control Group is currently removeable. If it's not
5154                  * already queued for a userspace notification, queue
5155                  * it now
5156                  */
5157                 int need_schedule_work = 0;
5158
5159                 raw_spin_lock(&release_list_lock);
5160                 if (!cgroup_is_dead(cgrp) &&
5161                     list_empty(&cgrp->release_list)) {
5162                         list_add(&cgrp->release_list, &release_list);
5163                         need_schedule_work = 1;
5164                 }
5165                 raw_spin_unlock(&release_list_lock);
5166                 if (need_schedule_work)
5167                         schedule_work(&release_agent_work);
5168         }
5169 }
5170
5171 /*
5172  * Notify userspace when a cgroup is released, by running the
5173  * configured release agent with the name of the cgroup (path
5174  * relative to the root of cgroup file system) as the argument.
5175  *
5176  * Most likely, this user command will try to rmdir this cgroup.
5177  *
5178  * This races with the possibility that some other task will be
5179  * attached to this cgroup before it is removed, or that some other
5180  * user task will 'mkdir' a child cgroup of this cgroup.  That's ok.
5181  * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5182  * unused, and this cgroup will be reprieved from its death sentence,
5183  * to continue to serve a useful existence.  Next time it's released,
5184  * we will get notified again, if it still has 'notify_on_release' set.
5185  *
5186  * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5187  * means only wait until the task is successfully execve()'d.  The
5188  * separate release agent task is forked by call_usermodehelper(),
5189  * then control in this thread returns here, without waiting for the
5190  * release agent task.  We don't bother to wait because the caller of
5191  * this routine has no use for the exit status of the release agent
5192  * task, so no sense holding our caller up for that.
5193  */
5194 static void cgroup_release_agent(struct work_struct *work)
5195 {
5196         BUG_ON(work != &release_agent_work);
5197         mutex_lock(&cgroup_mutex);
5198         raw_spin_lock(&release_list_lock);
5199         while (!list_empty(&release_list)) {
5200                 char *argv[3], *envp[3];
5201                 int i;
5202                 char *pathbuf = NULL, *agentbuf = NULL;
5203                 struct cgroup *cgrp = list_entry(release_list.next,
5204                                                     struct cgroup,
5205                                                     release_list);
5206                 list_del_init(&cgrp->release_list);
5207                 raw_spin_unlock(&release_list_lock);
5208                 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5209                 if (!pathbuf)
5210                         goto continue_free;
5211                 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
5212                         goto continue_free;
5213                 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5214                 if (!agentbuf)
5215                         goto continue_free;
5216
5217                 i = 0;
5218                 argv[i++] = agentbuf;
5219                 argv[i++] = pathbuf;
5220                 argv[i] = NULL;
5221
5222                 i = 0;
5223                 /* minimal command environment */
5224                 envp[i++] = "HOME=/";
5225                 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5226                 envp[i] = NULL;
5227
5228                 /* Drop the lock while we invoke the usermode helper,
5229                  * since the exec could involve hitting disk and hence
5230                  * be a slow process */
5231                 mutex_unlock(&cgroup_mutex);
5232                 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5233                 mutex_lock(&cgroup_mutex);
5234  continue_free:
5235                 kfree(pathbuf);
5236                 kfree(agentbuf);
5237                 raw_spin_lock(&release_list_lock);
5238         }
5239         raw_spin_unlock(&release_list_lock);
5240         mutex_unlock(&cgroup_mutex);
5241 }
5242
5243 static int __init cgroup_disable(char *str)
5244 {
5245         struct cgroup_subsys *ss;
5246         char *token;
5247         int i;
5248
5249         while ((token = strsep(&str, ",")) != NULL) {
5250                 if (!*token)
5251                         continue;
5252
5253                 /*
5254                  * cgroup_disable, being at boot time, can't know about
5255                  * module subsystems, so we don't worry about them.
5256                  */
5257                 for_each_builtin_subsys(ss, i) {
5258                         if (!strcmp(token, ss->name)) {
5259                                 ss->disabled = 1;
5260                                 printk(KERN_INFO "Disabling %s control group"
5261                                         " subsystem\n", ss->name);
5262                                 break;
5263                         }
5264                 }
5265         }
5266         return 1;
5267 }
5268 __setup("cgroup_disable=", cgroup_disable);
5269
5270 /**
5271  * css_from_dir - get corresponding css from the dentry of a cgroup dir
5272  * @dentry: directory dentry of interest
5273  * @ss: subsystem of interest
5274  *
5275  * Must be called under RCU read lock.  The caller is responsible for
5276  * pinning the returned css if it needs to be accessed outside the RCU
5277  * critical section.
5278  */
5279 struct cgroup_subsys_state *css_from_dir(struct dentry *dentry,
5280                                          struct cgroup_subsys *ss)
5281 {
5282         struct cgroup *cgrp;
5283
5284         WARN_ON_ONCE(!rcu_read_lock_held());
5285
5286         /* is @dentry a cgroup dir? */
5287         if (!dentry->d_inode ||
5288             dentry->d_inode->i_op != &cgroup_dir_inode_operations)
5289                 return ERR_PTR(-EBADF);
5290
5291         cgrp = __d_cgrp(dentry);
5292         return cgroup_css(cgrp, ss) ?: ERR_PTR(-ENOENT);
5293 }
5294
5295 /**
5296  * css_from_id - lookup css by id
5297  * @id: the cgroup id
5298  * @ss: cgroup subsys to be looked into
5299  *
5300  * Returns the css if there's valid one with @id, otherwise returns NULL.
5301  * Should be called under rcu_read_lock().
5302  */
5303 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5304 {
5305         struct cgroup *cgrp;
5306
5307         rcu_lockdep_assert(rcu_read_lock_held() ||
5308                            lockdep_is_held(&cgroup_mutex),
5309                            "css_from_id() needs proper protection");
5310
5311         cgrp = idr_find(&ss->root->cgroup_idr, id);
5312         if (cgrp)
5313                 return cgroup_css(cgrp, ss);
5314         return NULL;
5315 }
5316
5317 #ifdef CONFIG_CGROUP_DEBUG
5318 static struct cgroup_subsys_state *
5319 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5320 {
5321         struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5322
5323         if (!css)
5324                 return ERR_PTR(-ENOMEM);
5325
5326         return css;
5327 }
5328
5329 static void debug_css_free(struct cgroup_subsys_state *css)
5330 {
5331         kfree(css);
5332 }
5333
5334 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5335                                 struct cftype *cft)
5336 {
5337         return cgroup_task_count(css->cgroup);
5338 }
5339
5340 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5341                                 struct cftype *cft)
5342 {
5343         return (u64)(unsigned long)current->cgroups;
5344 }
5345
5346 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5347                                          struct cftype *cft)
5348 {
5349         u64 count;
5350
5351         rcu_read_lock();
5352         count = atomic_read(&task_css_set(current)->refcount);
5353         rcu_read_unlock();
5354         return count;
5355 }
5356
5357 static int current_css_set_cg_links_read(struct cgroup_subsys_state *css,
5358                                          struct cftype *cft,
5359                                          struct seq_file *seq)
5360 {
5361         struct cgrp_cset_link *link;
5362         struct css_set *cset;
5363
5364         read_lock(&css_set_lock);
5365         rcu_read_lock();
5366         cset = rcu_dereference(current->cgroups);
5367         list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5368                 struct cgroup *c = link->cgrp;
5369                 const char *name;
5370
5371                 if (c->dentry)
5372                         name = c->dentry->d_name.name;
5373                 else
5374                         name = "?";
5375                 seq_printf(seq, "Root %d group %s\n",
5376                            c->root->hierarchy_id, name);
5377         }
5378         rcu_read_unlock();
5379         read_unlock(&css_set_lock);
5380         return 0;
5381 }
5382
5383 #define MAX_TASKS_SHOWN_PER_CSS 25
5384 static int cgroup_css_links_read(struct cgroup_subsys_state *css,
5385                                  struct cftype *cft, struct seq_file *seq)
5386 {
5387         struct cgrp_cset_link *link;
5388
5389         read_lock(&css_set_lock);
5390         list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5391                 struct css_set *cset = link->cset;
5392                 struct task_struct *task;
5393                 int count = 0;
5394                 seq_printf(seq, "css_set %p\n", cset);
5395                 list_for_each_entry(task, &cset->tasks, cg_list) {
5396                         if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5397                                 seq_puts(seq, "  ...\n");
5398                                 break;
5399                         } else {
5400                                 seq_printf(seq, "  task %d\n",
5401                                            task_pid_vnr(task));
5402                         }
5403                 }
5404         }
5405         read_unlock(&css_set_lock);
5406         return 0;
5407 }
5408
5409 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5410 {
5411         return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
5412 }
5413
5414 static struct cftype debug_files[] =  {
5415         {
5416                 .name = "taskcount",
5417                 .read_u64 = debug_taskcount_read,
5418         },
5419
5420         {
5421                 .name = "current_css_set",
5422                 .read_u64 = current_css_set_read,
5423         },
5424
5425         {
5426                 .name = "current_css_set_refcount",
5427                 .read_u64 = current_css_set_refcount_read,
5428         },
5429
5430         {
5431                 .name = "current_css_set_cg_links",
5432                 .read_seq_string = current_css_set_cg_links_read,
5433         },
5434
5435         {
5436                 .name = "cgroup_css_links",
5437                 .read_seq_string = cgroup_css_links_read,
5438         },
5439
5440         {
5441                 .name = "releasable",
5442                 .read_u64 = releasable_read,
5443         },
5444
5445         { }     /* terminate */
5446 };
5447
5448 struct cgroup_subsys debug_subsys = {
5449         .name = "debug",
5450         .css_alloc = debug_css_alloc,
5451         .css_free = debug_css_free,
5452         .subsys_id = debug_subsys_id,
5453         .base_cftypes = debug_files,
5454 };
5455 #endif /* CONFIG_CGROUP_DEBUG */