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