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