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