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