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