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