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