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