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