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