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