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