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