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