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