GNU Linux-libre 4.14.328-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, 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, *cset_pos;
1648                 struct css_task_iter *it;
1649
1650                 WARN_ON(!css || cgroup_css(dcgrp, ss));
1651
1652                 if (src_root != &cgrp_dfl_root) {
1653                         /* disable from the source */
1654                         src_root->subsys_mask &= ~(1 << ssid);
1655                         WARN_ON(cgroup_apply_control(scgrp));
1656                         cgroup_finalize_control(scgrp, 0);
1657                 }
1658
1659                 /* rebind */
1660                 RCU_INIT_POINTER(scgrp->subsys[ssid], NULL);
1661                 rcu_assign_pointer(dcgrp->subsys[ssid], css);
1662                 ss->root = dst_root;
1663                 css->cgroup = dcgrp;
1664
1665                 spin_lock_irq(&css_set_lock);
1666                 WARN_ON(!list_empty(&dcgrp->e_csets[ss->id]));
1667                 list_for_each_entry_safe(cset, cset_pos, &scgrp->e_csets[ss->id],
1668                                          e_cset_node[ss->id]) {
1669                         list_move_tail(&cset->e_cset_node[ss->id],
1670                                        &dcgrp->e_csets[ss->id]);
1671                         /*
1672                          * all css_sets of scgrp together in same order to dcgrp,
1673                          * patch in-flight iterators to preserve correct iteration.
1674                          * since the iterator is always advanced right away and
1675                          * finished when it->cset_pos meets it->cset_head, so only
1676                          * update it->cset_head is enough here.
1677                          */
1678                         list_for_each_entry(it, &cset->task_iters, iters_node)
1679                                 if (it->cset_head == &scgrp->e_csets[ss->id])
1680                                         it->cset_head = &dcgrp->e_csets[ss->id];
1681                 }
1682                 spin_unlock_irq(&css_set_lock);
1683
1684                 /* default hierarchy doesn't enable controllers by default */
1685                 dst_root->subsys_mask |= 1 << ssid;
1686                 if (dst_root == &cgrp_dfl_root) {
1687                         static_branch_enable(cgroup_subsys_on_dfl_key[ssid]);
1688                 } else {
1689                         dcgrp->subtree_control |= 1 << ssid;
1690                         static_branch_disable(cgroup_subsys_on_dfl_key[ssid]);
1691                 }
1692
1693                 ret = cgroup_apply_control(dcgrp);
1694                 if (ret)
1695                         pr_warn("partial failure to rebind %s controller (err=%d)\n",
1696                                 ss->name, ret);
1697
1698                 if (ss->bind)
1699                         ss->bind(css);
1700         } while_each_subsys_mask();
1701
1702         kernfs_activate(dcgrp->kn);
1703         return 0;
1704 }
1705
1706 int cgroup_show_path(struct seq_file *sf, struct kernfs_node *kf_node,
1707                      struct kernfs_root *kf_root)
1708 {
1709         int len = 0;
1710         char *buf = NULL;
1711         struct cgroup_root *kf_cgroot = cgroup_root_from_kf(kf_root);
1712         struct cgroup *ns_cgroup;
1713
1714         buf = kmalloc(PATH_MAX, GFP_KERNEL);
1715         if (!buf)
1716                 return -ENOMEM;
1717
1718         spin_lock_irq(&css_set_lock);
1719         ns_cgroup = current_cgns_cgroup_from_root(kf_cgroot);
1720         len = kernfs_path_from_node(kf_node, ns_cgroup->kn, buf, PATH_MAX);
1721         spin_unlock_irq(&css_set_lock);
1722
1723         if (len >= PATH_MAX)
1724                 len = -ERANGE;
1725         else if (len > 0) {
1726                 seq_escape(sf, buf, " \t\n\\");
1727                 len = 0;
1728         }
1729         kfree(buf);
1730         return len;
1731 }
1732
1733 static int parse_cgroup_root_flags(char *data, unsigned int *root_flags)
1734 {
1735         char *token;
1736
1737         *root_flags = 0;
1738
1739         if (!data || *data == '\0')
1740                 return 0;
1741
1742         while ((token = strsep(&data, ",")) != NULL) {
1743                 if (!strcmp(token, "nsdelegate")) {
1744                         *root_flags |= CGRP_ROOT_NS_DELEGATE;
1745                         continue;
1746                 }
1747
1748                 pr_err("cgroup2: unknown option \"%s\"\n", token);
1749                 return -EINVAL;
1750         }
1751
1752         return 0;
1753 }
1754
1755 static void apply_cgroup_root_flags(unsigned int root_flags)
1756 {
1757         if (current->nsproxy->cgroup_ns == &init_cgroup_ns) {
1758                 if (root_flags & CGRP_ROOT_NS_DELEGATE)
1759                         cgrp_dfl_root.flags |= CGRP_ROOT_NS_DELEGATE;
1760                 else
1761                         cgrp_dfl_root.flags &= ~CGRP_ROOT_NS_DELEGATE;
1762         }
1763 }
1764
1765 static int cgroup_show_options(struct seq_file *seq, struct kernfs_root *kf_root)
1766 {
1767         if (cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE)
1768                 seq_puts(seq, ",nsdelegate");
1769         return 0;
1770 }
1771
1772 static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
1773 {
1774         unsigned int root_flags;
1775         int ret;
1776
1777         ret = parse_cgroup_root_flags(data, &root_flags);
1778         if (ret)
1779                 return ret;
1780
1781         apply_cgroup_root_flags(root_flags);
1782         return 0;
1783 }
1784
1785 /*
1786  * To reduce the fork() overhead for systems that are not actually using
1787  * their cgroups capability, we don't maintain the lists running through
1788  * each css_set to its tasks until we see the list actually used - in other
1789  * words after the first mount.
1790  */
1791 static bool use_task_css_set_links __read_mostly;
1792
1793 static void cgroup_enable_task_cg_lists(void)
1794 {
1795         struct task_struct *p, *g;
1796
1797         spin_lock_irq(&css_set_lock);
1798
1799         if (use_task_css_set_links)
1800                 goto out_unlock;
1801
1802         use_task_css_set_links = true;
1803
1804         /*
1805          * We need tasklist_lock because RCU is not safe against
1806          * while_each_thread(). Besides, a forking task that has passed
1807          * cgroup_post_fork() without seeing use_task_css_set_links = 1
1808          * is not guaranteed to have its child immediately visible in the
1809          * tasklist if we walk through it with RCU.
1810          */
1811         read_lock(&tasklist_lock);
1812         do_each_thread(g, p) {
1813                 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1814                              task_css_set(p) != &init_css_set);
1815
1816                 /*
1817                  * We should check if the process is exiting, otherwise
1818                  * it will race with cgroup_exit() in that the list
1819                  * entry won't be deleted though the process has exited.
1820                  * Do it while holding siglock so that we don't end up
1821                  * racing against cgroup_exit().
1822                  *
1823                  * Interrupts were already disabled while acquiring
1824                  * the css_set_lock, so we do not need to disable it
1825                  * again when acquiring the sighand->siglock here.
1826                  */
1827                 spin_lock(&p->sighand->siglock);
1828                 if (!(p->flags & PF_EXITING)) {
1829                         struct css_set *cset = task_css_set(p);
1830
1831                         if (!css_set_populated(cset))
1832                                 css_set_update_populated(cset, true);
1833                         list_add_tail(&p->cg_list, &cset->tasks);
1834                         get_css_set(cset);
1835                         cset->nr_tasks++;
1836                 }
1837                 spin_unlock(&p->sighand->siglock);
1838         } while_each_thread(g, p);
1839         read_unlock(&tasklist_lock);
1840 out_unlock:
1841         spin_unlock_irq(&css_set_lock);
1842 }
1843
1844 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1845 {
1846         struct cgroup_subsys *ss;
1847         int ssid;
1848
1849         INIT_LIST_HEAD(&cgrp->self.sibling);
1850         INIT_LIST_HEAD(&cgrp->self.children);
1851         INIT_LIST_HEAD(&cgrp->cset_links);
1852         INIT_LIST_HEAD(&cgrp->pidlists);
1853         mutex_init(&cgrp->pidlist_mutex);
1854         cgrp->self.cgroup = cgrp;
1855         cgrp->self.flags |= CSS_ONLINE;
1856         cgrp->dom_cgrp = cgrp;
1857         cgrp->max_descendants = INT_MAX;
1858         cgrp->max_depth = INT_MAX;
1859
1860         for_each_subsys(ss, ssid)
1861                 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
1862
1863         init_waitqueue_head(&cgrp->offline_waitq);
1864         INIT_WORK(&cgrp->release_agent_work, cgroup1_release_agent);
1865 }
1866
1867 void init_cgroup_root(struct cgroup_root *root, struct cgroup_sb_opts *opts)
1868 {
1869         struct cgroup *cgrp = &root->cgrp;
1870
1871         INIT_LIST_HEAD(&root->root_list);
1872         atomic_set(&root->nr_cgrps, 1);
1873         cgrp->root = root;
1874         init_cgroup_housekeeping(cgrp);
1875         idr_init(&root->cgroup_idr);
1876
1877         root->flags = opts->flags;
1878         if (opts->release_agent)
1879                 strcpy(root->release_agent_path, opts->release_agent);
1880         if (opts->name)
1881                 strcpy(root->name, opts->name);
1882         if (opts->cpuset_clone_children)
1883                 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
1884 }
1885
1886 int cgroup_setup_root(struct cgroup_root *root, u16 ss_mask, int ref_flags)
1887 {
1888         LIST_HEAD(tmp_links);
1889         struct cgroup *root_cgrp = &root->cgrp;
1890         struct kernfs_syscall_ops *kf_sops;
1891         struct css_set *cset;
1892         int i, ret;
1893
1894         lockdep_assert_held(&cgroup_mutex);
1895
1896         ret = cgroup_idr_alloc(&root->cgroup_idr, root_cgrp, 1, 2, GFP_KERNEL);
1897         if (ret < 0)
1898                 goto out;
1899         root_cgrp->id = ret;
1900         root_cgrp->ancestor_ids[0] = ret;
1901
1902         ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release,
1903                               ref_flags, GFP_KERNEL);
1904         if (ret)
1905                 goto out;
1906
1907         /*
1908          * We're accessing css_set_count without locking css_set_lock here,
1909          * but that's OK - it can only be increased by someone holding
1910          * cgroup_lock, and that's us.  Later rebinding may disable
1911          * controllers on the default hierarchy and thus create new csets,
1912          * which can't be more than the existing ones.  Allocate 2x.
1913          */
1914         ret = allocate_cgrp_cset_links(2 * css_set_count, &tmp_links);
1915         if (ret)
1916                 goto cancel_ref;
1917
1918         ret = cgroup_init_root_id(root);
1919         if (ret)
1920                 goto cancel_ref;
1921
1922         kf_sops = root == &cgrp_dfl_root ?
1923                 &cgroup_kf_syscall_ops : &cgroup1_kf_syscall_ops;
1924
1925         root->kf_root = kernfs_create_root(kf_sops,
1926                                            KERNFS_ROOT_CREATE_DEACTIVATED |
1927                                            KERNFS_ROOT_SUPPORT_EXPORTOP,
1928                                            root_cgrp);
1929         if (IS_ERR(root->kf_root)) {
1930                 ret = PTR_ERR(root->kf_root);
1931                 goto exit_root_id;
1932         }
1933         root_cgrp->kn = root->kf_root->kn;
1934
1935         ret = css_populate_dir(&root_cgrp->self);
1936         if (ret)
1937                 goto destroy_root;
1938
1939         ret = rebind_subsystems(root, ss_mask);
1940         if (ret)
1941                 goto destroy_root;
1942
1943         trace_cgroup_setup_root(root);
1944
1945         /*
1946          * There must be no failure case after here, since rebinding takes
1947          * care of subsystems' refcounts, which are explicitly dropped in
1948          * the failure exit path.
1949          */
1950         list_add(&root->root_list, &cgroup_roots);
1951         cgroup_root_count++;
1952
1953         /*
1954          * Link the root cgroup in this hierarchy into all the css_set
1955          * objects.
1956          */
1957         spin_lock_irq(&css_set_lock);
1958         hash_for_each(css_set_table, i, cset, hlist) {
1959                 link_css_set(&tmp_links, cset, root_cgrp);
1960                 if (css_set_populated(cset))
1961                         cgroup_update_populated(root_cgrp, true);
1962         }
1963         spin_unlock_irq(&css_set_lock);
1964
1965         BUG_ON(!list_empty(&root_cgrp->self.children));
1966         BUG_ON(atomic_read(&root->nr_cgrps) != 1);
1967
1968         kernfs_activate(root_cgrp->kn);
1969         ret = 0;
1970         goto out;
1971
1972 destroy_root:
1973         kernfs_destroy_root(root->kf_root);
1974         root->kf_root = NULL;
1975 exit_root_id:
1976         cgroup_exit_root_id(root);
1977 cancel_ref:
1978         percpu_ref_exit(&root_cgrp->self.refcnt);
1979 out:
1980         free_cgrp_cset_links(&tmp_links);
1981         return ret;
1982 }
1983
1984 struct dentry *cgroup_do_mount(struct file_system_type *fs_type, int flags,
1985                                struct cgroup_root *root, unsigned long magic,
1986                                struct cgroup_namespace *ns)
1987 {
1988         struct dentry *dentry;
1989         bool new_sb = false;
1990
1991         dentry = kernfs_mount(fs_type, flags, root->kf_root, magic, &new_sb);
1992
1993         /*
1994          * In non-init cgroup namespace, instead of root cgroup's dentry,
1995          * we return the dentry corresponding to the cgroupns->root_cgrp.
1996          */
1997         if (!IS_ERR(dentry) && ns != &init_cgroup_ns) {
1998                 struct dentry *nsdentry;
1999                 struct super_block *sb = dentry->d_sb;
2000                 struct cgroup *cgrp;
2001
2002                 mutex_lock(&cgroup_mutex);
2003                 spin_lock_irq(&css_set_lock);
2004
2005                 cgrp = cset_cgroup_from_root(ns->root_cset, root);
2006
2007                 spin_unlock_irq(&css_set_lock);
2008                 mutex_unlock(&cgroup_mutex);
2009
2010                 nsdentry = kernfs_node_dentry(cgrp->kn, sb);
2011                 dput(dentry);
2012                 if (IS_ERR(nsdentry))
2013                         deactivate_locked_super(sb);
2014                 dentry = nsdentry;
2015         }
2016
2017         if (!new_sb)
2018                 cgroup_put(&root->cgrp);
2019
2020         return dentry;
2021 }
2022
2023 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
2024                          int flags, const char *unused_dev_name,
2025                          void *data)
2026 {
2027         struct cgroup_namespace *ns = current->nsproxy->cgroup_ns;
2028         struct dentry *dentry;
2029         int ret;
2030
2031         get_cgroup_ns(ns);
2032
2033         /* Check if the caller has permission to mount. */
2034         if (!ns_capable(ns->user_ns, CAP_SYS_ADMIN)) {
2035                 put_cgroup_ns(ns);
2036                 return ERR_PTR(-EPERM);
2037         }
2038
2039         /*
2040          * The first time anyone tries to mount a cgroup, enable the list
2041          * linking each css_set to its tasks and fix up all existing tasks.
2042          */
2043         if (!use_task_css_set_links)
2044                 cgroup_enable_task_cg_lists();
2045
2046         if (fs_type == &cgroup2_fs_type) {
2047                 unsigned int root_flags;
2048
2049                 ret = parse_cgroup_root_flags(data, &root_flags);
2050                 if (ret) {
2051                         put_cgroup_ns(ns);
2052                         return ERR_PTR(ret);
2053                 }
2054
2055                 cgrp_dfl_visible = true;
2056                 cgroup_get_live(&cgrp_dfl_root.cgrp);
2057
2058                 dentry = cgroup_do_mount(&cgroup2_fs_type, flags, &cgrp_dfl_root,
2059                                          CGROUP2_SUPER_MAGIC, ns);
2060                 if (!IS_ERR(dentry))
2061                         apply_cgroup_root_flags(root_flags);
2062         } else {
2063                 dentry = cgroup1_mount(&cgroup_fs_type, flags, data,
2064                                        CGROUP_SUPER_MAGIC, ns);
2065         }
2066
2067         put_cgroup_ns(ns);
2068         return dentry;
2069 }
2070
2071 static void cgroup_kill_sb(struct super_block *sb)
2072 {
2073         struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
2074         struct cgroup_root *root = cgroup_root_from_kf(kf_root);
2075
2076         /*
2077          * If @root doesn't have any mounts or children, start killing it.
2078          * This prevents new mounts by disabling percpu_ref_tryget_live().
2079          * cgroup_mount() may wait for @root's release.
2080          *
2081          * And don't kill the default root.
2082          */
2083         if (!list_empty(&root->cgrp.self.children) ||
2084             root == &cgrp_dfl_root)
2085                 cgroup_put(&root->cgrp);
2086         else
2087                 percpu_ref_kill(&root->cgrp.self.refcnt);
2088
2089         kernfs_kill_sb(sb);
2090 }
2091
2092 struct file_system_type cgroup_fs_type = {
2093         .name = "cgroup",
2094         .mount = cgroup_mount,
2095         .kill_sb = cgroup_kill_sb,
2096         .fs_flags = FS_USERNS_MOUNT,
2097 };
2098
2099 static struct file_system_type cgroup2_fs_type = {
2100         .name = "cgroup2",
2101         .mount = cgroup_mount,
2102         .kill_sb = cgroup_kill_sb,
2103         .fs_flags = FS_USERNS_MOUNT,
2104 };
2105
2106 int cgroup_path_ns_locked(struct cgroup *cgrp, char *buf, size_t buflen,
2107                           struct cgroup_namespace *ns)
2108 {
2109         struct cgroup *root = cset_cgroup_from_root(ns->root_cset, cgrp->root);
2110
2111         return kernfs_path_from_node(cgrp->kn, root->kn, buf, buflen);
2112 }
2113
2114 int cgroup_path_ns(struct cgroup *cgrp, char *buf, size_t buflen,
2115                    struct cgroup_namespace *ns)
2116 {
2117         int ret;
2118
2119         mutex_lock(&cgroup_mutex);
2120         spin_lock_irq(&css_set_lock);
2121
2122         ret = cgroup_path_ns_locked(cgrp, buf, buflen, ns);
2123
2124         spin_unlock_irq(&css_set_lock);
2125         mutex_unlock(&cgroup_mutex);
2126
2127         return ret;
2128 }
2129 EXPORT_SYMBOL_GPL(cgroup_path_ns);
2130
2131 /**
2132  * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
2133  * @task: target task
2134  * @buf: the buffer to write the path into
2135  * @buflen: the length of the buffer
2136  *
2137  * Determine @task's cgroup on the first (the one with the lowest non-zero
2138  * hierarchy_id) cgroup hierarchy and copy its path into @buf.  This
2139  * function grabs cgroup_mutex and shouldn't be used inside locks used by
2140  * cgroup controller callbacks.
2141  *
2142  * Return value is the same as kernfs_path().
2143  */
2144 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
2145 {
2146         struct cgroup_root *root;
2147         struct cgroup *cgrp;
2148         int hierarchy_id = 1;
2149         int ret;
2150
2151         mutex_lock(&cgroup_mutex);
2152         spin_lock_irq(&css_set_lock);
2153
2154         root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
2155
2156         if (root) {
2157                 cgrp = task_cgroup_from_root(task, root);
2158                 ret = cgroup_path_ns_locked(cgrp, buf, buflen, &init_cgroup_ns);
2159         } else {
2160                 /* if no hierarchy exists, everyone is in "/" */
2161                 ret = strlcpy(buf, "/", buflen);
2162         }
2163
2164         spin_unlock_irq(&css_set_lock);
2165         mutex_unlock(&cgroup_mutex);
2166         return ret;
2167 }
2168 EXPORT_SYMBOL_GPL(task_cgroup_path);
2169
2170 /**
2171  * cgroup_migrate_add_task - add a migration target task to a migration context
2172  * @task: target task
2173  * @mgctx: target migration context
2174  *
2175  * Add @task, which is a migration target, to @mgctx->tset.  This function
2176  * becomes noop if @task doesn't need to be migrated.  @task's css_set
2177  * should have been added as a migration source and @task->cg_list will be
2178  * moved from the css_set's tasks list to mg_tasks one.
2179  */
2180 static void cgroup_migrate_add_task(struct task_struct *task,
2181                                     struct cgroup_mgctx *mgctx)
2182 {
2183         struct css_set *cset;
2184
2185         lockdep_assert_held(&css_set_lock);
2186
2187         /* @task either already exited or can't exit until the end */
2188         if (task->flags & PF_EXITING)
2189                 return;
2190
2191         /* leave @task alone if post_fork() hasn't linked it yet */
2192         if (list_empty(&task->cg_list))
2193                 return;
2194
2195         cset = task_css_set(task);
2196         if (!cset->mg_src_cgrp)
2197                 return;
2198
2199         mgctx->tset.nr_tasks++;
2200
2201         list_move_tail(&task->cg_list, &cset->mg_tasks);
2202         if (list_empty(&cset->mg_node))
2203                 list_add_tail(&cset->mg_node,
2204                               &mgctx->tset.src_csets);
2205         if (list_empty(&cset->mg_dst_cset->mg_node))
2206                 list_add_tail(&cset->mg_dst_cset->mg_node,
2207                               &mgctx->tset.dst_csets);
2208 }
2209
2210 /**
2211  * cgroup_taskset_first - reset taskset and return the first task
2212  * @tset: taskset of interest
2213  * @dst_cssp: output variable for the destination css
2214  *
2215  * @tset iteration is initialized and the first task is returned.
2216  */
2217 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset,
2218                                          struct cgroup_subsys_state **dst_cssp)
2219 {
2220         tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
2221         tset->cur_task = NULL;
2222
2223         return cgroup_taskset_next(tset, dst_cssp);
2224 }
2225
2226 /**
2227  * cgroup_taskset_next - iterate to the next task in taskset
2228  * @tset: taskset of interest
2229  * @dst_cssp: output variable for the destination css
2230  *
2231  * Return the next task in @tset.  Iteration must have been initialized
2232  * with cgroup_taskset_first().
2233  */
2234 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset,
2235                                         struct cgroup_subsys_state **dst_cssp)
2236 {
2237         struct css_set *cset = tset->cur_cset;
2238         struct task_struct *task = tset->cur_task;
2239
2240         while (&cset->mg_node != tset->csets) {
2241                 if (!task)
2242                         task = list_first_entry(&cset->mg_tasks,
2243                                                 struct task_struct, cg_list);
2244                 else
2245                         task = list_next_entry(task, cg_list);
2246
2247                 if (&task->cg_list != &cset->mg_tasks) {
2248                         tset->cur_cset = cset;
2249                         tset->cur_task = task;
2250
2251                         /*
2252                          * This function may be called both before and
2253                          * after cgroup_taskset_migrate().  The two cases
2254                          * can be distinguished by looking at whether @cset
2255                          * has its ->mg_dst_cset set.
2256                          */
2257                         if (cset->mg_dst_cset)
2258                                 *dst_cssp = cset->mg_dst_cset->subsys[tset->ssid];
2259                         else
2260                                 *dst_cssp = cset->subsys[tset->ssid];
2261
2262                         return task;
2263                 }
2264
2265                 cset = list_next_entry(cset, mg_node);
2266                 task = NULL;
2267         }
2268
2269         return NULL;
2270 }
2271
2272 /**
2273  * cgroup_taskset_migrate - migrate a taskset
2274  * @mgctx: migration context
2275  *
2276  * Migrate tasks in @mgctx as setup by migration preparation functions.
2277  * This function fails iff one of the ->can_attach callbacks fails and
2278  * guarantees that either all or none of the tasks in @mgctx are migrated.
2279  * @mgctx is consumed regardless of success.
2280  */
2281 static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx)
2282 {
2283         struct cgroup_taskset *tset = &mgctx->tset;
2284         struct cgroup_subsys *ss;
2285         struct task_struct *task, *tmp_task;
2286         struct css_set *cset, *tmp_cset;
2287         int ssid, failed_ssid, ret;
2288
2289         /* check that we can legitimately attach to the cgroup */
2290         if (tset->nr_tasks) {
2291                 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2292                         if (ss->can_attach) {
2293                                 tset->ssid = ssid;
2294                                 ret = ss->can_attach(tset);
2295                                 if (ret) {
2296                                         failed_ssid = ssid;
2297                                         goto out_cancel_attach;
2298                                 }
2299                         }
2300                 } while_each_subsys_mask();
2301         }
2302
2303         /*
2304          * Now that we're guaranteed success, proceed to move all tasks to
2305          * the new cgroup.  There are no failure cases after here, so this
2306          * is the commit point.
2307          */
2308         spin_lock_irq(&css_set_lock);
2309         list_for_each_entry(cset, &tset->src_csets, mg_node) {
2310                 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list) {
2311                         struct css_set *from_cset = task_css_set(task);
2312                         struct css_set *to_cset = cset->mg_dst_cset;
2313
2314                         get_css_set(to_cset);
2315                         to_cset->nr_tasks++;
2316                         css_set_move_task(task, from_cset, to_cset, true);
2317                         put_css_set_locked(from_cset);
2318                         from_cset->nr_tasks--;
2319                 }
2320         }
2321         spin_unlock_irq(&css_set_lock);
2322
2323         /*
2324          * Migration is committed, all target tasks are now on dst_csets.
2325          * Nothing is sensitive to fork() after this point.  Notify
2326          * controllers that migration is complete.
2327          */
2328         tset->csets = &tset->dst_csets;
2329
2330         if (tset->nr_tasks) {
2331                 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2332                         if (ss->attach) {
2333                                 tset->ssid = ssid;
2334                                 ss->attach(tset);
2335                         }
2336                 } while_each_subsys_mask();
2337         }
2338
2339         ret = 0;
2340         goto out_release_tset;
2341
2342 out_cancel_attach:
2343         if (tset->nr_tasks) {
2344                 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2345                         if (ssid == failed_ssid)
2346                                 break;
2347                         if (ss->cancel_attach) {
2348                                 tset->ssid = ssid;
2349                                 ss->cancel_attach(tset);
2350                         }
2351                 } while_each_subsys_mask();
2352         }
2353 out_release_tset:
2354         spin_lock_irq(&css_set_lock);
2355         list_splice_init(&tset->dst_csets, &tset->src_csets);
2356         list_for_each_entry_safe(cset, tmp_cset, &tset->src_csets, mg_node) {
2357                 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2358                 list_del_init(&cset->mg_node);
2359         }
2360         spin_unlock_irq(&css_set_lock);
2361
2362         /*
2363          * Re-initialize the cgroup_taskset structure in case it is reused
2364          * again in another cgroup_migrate_add_task()/cgroup_migrate_execute()
2365          * iteration.
2366          */
2367         tset->nr_tasks = 0;
2368         tset->csets    = &tset->src_csets;
2369         return ret;
2370 }
2371
2372 /**
2373  * cgroup_migrate_vet_dst - verify whether a cgroup can be migration destination
2374  * @dst_cgrp: destination cgroup to test
2375  *
2376  * On the default hierarchy, except for the mixable, (possible) thread root
2377  * and threaded cgroups, subtree_control must be zero for migration
2378  * destination cgroups with tasks so that child cgroups don't compete
2379  * against tasks.
2380  */
2381 int cgroup_migrate_vet_dst(struct cgroup *dst_cgrp)
2382 {
2383         /* v1 doesn't have any restriction */
2384         if (!cgroup_on_dfl(dst_cgrp))
2385                 return 0;
2386
2387         /* verify @dst_cgrp can host resources */
2388         if (!cgroup_is_valid_domain(dst_cgrp->dom_cgrp))
2389                 return -EOPNOTSUPP;
2390
2391         /* mixables don't care */
2392         if (cgroup_is_mixable(dst_cgrp))
2393                 return 0;
2394
2395         /*
2396          * If @dst_cgrp is already or can become a thread root or is
2397          * threaded, it doesn't matter.
2398          */
2399         if (cgroup_can_be_thread_root(dst_cgrp) || cgroup_is_threaded(dst_cgrp))
2400                 return 0;
2401
2402         /* apply no-internal-process constraint */
2403         if (dst_cgrp->subtree_control)
2404                 return -EBUSY;
2405
2406         return 0;
2407 }
2408
2409 /**
2410  * cgroup_migrate_finish - cleanup after attach
2411  * @mgctx: migration context
2412  *
2413  * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst().  See
2414  * those functions for details.
2415  */
2416 void cgroup_migrate_finish(struct cgroup_mgctx *mgctx)
2417 {
2418         struct css_set *cset, *tmp_cset;
2419
2420         lockdep_assert_held(&cgroup_mutex);
2421
2422         spin_lock_irq(&css_set_lock);
2423
2424         list_for_each_entry_safe(cset, tmp_cset, &mgctx->preloaded_src_csets,
2425                                  mg_src_preload_node) {
2426                 cset->mg_src_cgrp = NULL;
2427                 cset->mg_dst_cgrp = NULL;
2428                 cset->mg_dst_cset = NULL;
2429                 list_del_init(&cset->mg_src_preload_node);
2430                 put_css_set_locked(cset);
2431         }
2432
2433         list_for_each_entry_safe(cset, tmp_cset, &mgctx->preloaded_dst_csets,
2434                                  mg_dst_preload_node) {
2435                 cset->mg_src_cgrp = NULL;
2436                 cset->mg_dst_cgrp = NULL;
2437                 cset->mg_dst_cset = NULL;
2438                 list_del_init(&cset->mg_dst_preload_node);
2439                 put_css_set_locked(cset);
2440         }
2441
2442         spin_unlock_irq(&css_set_lock);
2443 }
2444
2445 /**
2446  * cgroup_migrate_add_src - add a migration source css_set
2447  * @src_cset: the source css_set to add
2448  * @dst_cgrp: the destination cgroup
2449  * @mgctx: migration context
2450  *
2451  * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp.  Pin
2452  * @src_cset and add it to @mgctx->src_csets, which should later be cleaned
2453  * up by cgroup_migrate_finish().
2454  *
2455  * This function may be called without holding cgroup_threadgroup_rwsem
2456  * even if the target is a process.  Threads may be created and destroyed
2457  * but as long as cgroup_mutex is not dropped, no new css_set can be put
2458  * into play and the preloaded css_sets are guaranteed to cover all
2459  * migrations.
2460  */
2461 void cgroup_migrate_add_src(struct css_set *src_cset,
2462                             struct cgroup *dst_cgrp,
2463                             struct cgroup_mgctx *mgctx)
2464 {
2465         struct cgroup *src_cgrp;
2466
2467         lockdep_assert_held(&cgroup_mutex);
2468         lockdep_assert_held(&css_set_lock);
2469
2470         /*
2471          * If ->dead, @src_set is associated with one or more dead cgroups
2472          * and doesn't contain any migratable tasks.  Ignore it early so
2473          * that the rest of migration path doesn't get confused by it.
2474          */
2475         if (src_cset->dead)
2476                 return;
2477
2478         src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2479
2480         if (!list_empty(&src_cset->mg_src_preload_node))
2481                 return;
2482
2483         WARN_ON(src_cset->mg_src_cgrp);
2484         WARN_ON(src_cset->mg_dst_cgrp);
2485         WARN_ON(!list_empty(&src_cset->mg_tasks));
2486         WARN_ON(!list_empty(&src_cset->mg_node));
2487
2488         src_cset->mg_src_cgrp = src_cgrp;
2489         src_cset->mg_dst_cgrp = dst_cgrp;
2490         get_css_set(src_cset);
2491         list_add_tail(&src_cset->mg_src_preload_node, &mgctx->preloaded_src_csets);
2492 }
2493
2494 /**
2495  * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2496  * @mgctx: migration context
2497  *
2498  * Tasks are about to be moved and all the source css_sets have been
2499  * preloaded to @mgctx->preloaded_src_csets.  This function looks up and
2500  * pins all destination css_sets, links each to its source, and append them
2501  * to @mgctx->preloaded_dst_csets.
2502  *
2503  * This function must be called after cgroup_migrate_add_src() has been
2504  * called on each migration source css_set.  After migration is performed
2505  * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2506  * @mgctx.
2507  */
2508 int cgroup_migrate_prepare_dst(struct cgroup_mgctx *mgctx)
2509 {
2510         struct css_set *src_cset, *tmp_cset;
2511
2512         lockdep_assert_held(&cgroup_mutex);
2513
2514         /* look up the dst cset for each src cset and link it to src */
2515         list_for_each_entry_safe(src_cset, tmp_cset, &mgctx->preloaded_src_csets,
2516                                  mg_src_preload_node) {
2517                 struct css_set *dst_cset;
2518                 struct cgroup_subsys *ss;
2519                 int ssid;
2520
2521                 dst_cset = find_css_set(src_cset, src_cset->mg_dst_cgrp);
2522                 if (!dst_cset)
2523                         goto err;
2524
2525                 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2526
2527                 /*
2528                  * If src cset equals dst, it's noop.  Drop the src.
2529                  * cgroup_migrate() will skip the cset too.  Note that we
2530                  * can't handle src == dst as some nodes are used by both.
2531                  */
2532                 if (src_cset == dst_cset) {
2533                         src_cset->mg_src_cgrp = NULL;
2534                         src_cset->mg_dst_cgrp = NULL;
2535                         list_del_init(&src_cset->mg_src_preload_node);
2536                         put_css_set(src_cset);
2537                         put_css_set(dst_cset);
2538                         continue;
2539                 }
2540
2541                 src_cset->mg_dst_cset = dst_cset;
2542
2543                 if (list_empty(&dst_cset->mg_dst_preload_node))
2544                         list_add_tail(&dst_cset->mg_dst_preload_node,
2545                                       &mgctx->preloaded_dst_csets);
2546                 else
2547                         put_css_set(dst_cset);
2548
2549                 for_each_subsys(ss, ssid)
2550                         if (src_cset->subsys[ssid] != dst_cset->subsys[ssid])
2551                                 mgctx->ss_mask |= 1 << ssid;
2552         }
2553
2554         return 0;
2555 err:
2556         cgroup_migrate_finish(mgctx);
2557         return -ENOMEM;
2558 }
2559
2560 /**
2561  * cgroup_migrate - migrate a process or task to a cgroup
2562  * @leader: the leader of the process or the task to migrate
2563  * @threadgroup: whether @leader points to the whole process or a single task
2564  * @mgctx: migration context
2565  *
2566  * Migrate a process or task denoted by @leader.  If migrating a process,
2567  * the caller must be holding cgroup_threadgroup_rwsem.  The caller is also
2568  * responsible for invoking cgroup_migrate_add_src() and
2569  * cgroup_migrate_prepare_dst() on the targets before invoking this
2570  * function and following up with cgroup_migrate_finish().
2571  *
2572  * As long as a controller's ->can_attach() doesn't fail, this function is
2573  * guaranteed to succeed.  This means that, excluding ->can_attach()
2574  * failure, when migrating multiple targets, the success or failure can be
2575  * decided for all targets by invoking group_migrate_prepare_dst() before
2576  * actually starting migrating.
2577  */
2578 int cgroup_migrate(struct task_struct *leader, bool threadgroup,
2579                    struct cgroup_mgctx *mgctx)
2580 {
2581         struct task_struct *task;
2582
2583         /*
2584          * Prevent freeing of tasks while we take a snapshot. Tasks that are
2585          * already PF_EXITING could be freed from underneath us unless we
2586          * take an rcu_read_lock.
2587          */
2588         spin_lock_irq(&css_set_lock);
2589         rcu_read_lock();
2590         task = leader;
2591         do {
2592                 cgroup_migrate_add_task(task, mgctx);
2593                 if (!threadgroup)
2594                         break;
2595         } while_each_thread(leader, task);
2596         rcu_read_unlock();
2597         spin_unlock_irq(&css_set_lock);
2598
2599         return cgroup_migrate_execute(mgctx);
2600 }
2601
2602 /**
2603  * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2604  * @dst_cgrp: the cgroup to attach to
2605  * @leader: the task or the leader of the threadgroup to be attached
2606  * @threadgroup: attach the whole threadgroup?
2607  *
2608  * Call holding cgroup_mutex and cgroup_threadgroup_rwsem.
2609  */
2610 int cgroup_attach_task(struct cgroup *dst_cgrp, struct task_struct *leader,
2611                        bool threadgroup)
2612 {
2613         DEFINE_CGROUP_MGCTX(mgctx);
2614         struct task_struct *task;
2615         int ret;
2616
2617         ret = cgroup_migrate_vet_dst(dst_cgrp);
2618         if (ret)
2619                 return ret;
2620
2621         /* look up all src csets */
2622         spin_lock_irq(&css_set_lock);
2623         rcu_read_lock();
2624         task = leader;
2625         do {
2626                 cgroup_migrate_add_src(task_css_set(task), dst_cgrp, &mgctx);
2627                 if (!threadgroup)
2628                         break;
2629         } while_each_thread(leader, task);
2630         rcu_read_unlock();
2631         spin_unlock_irq(&css_set_lock);
2632
2633         /* prepare dst csets and commit */
2634         ret = cgroup_migrate_prepare_dst(&mgctx);
2635         if (!ret)
2636                 ret = cgroup_migrate(leader, threadgroup, &mgctx);
2637
2638         cgroup_migrate_finish(&mgctx);
2639
2640         if (!ret)
2641                 trace_cgroup_attach_task(dst_cgrp, leader, threadgroup);
2642
2643         return ret;
2644 }
2645
2646 struct task_struct *cgroup_procs_write_start(char *buf, bool threadgroup)
2647         __acquires(&cgroup_threadgroup_rwsem)
2648 {
2649         struct task_struct *tsk;
2650         pid_t pid;
2651
2652         if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2653                 return ERR_PTR(-EINVAL);
2654
2655         percpu_down_write(&cgroup_threadgroup_rwsem);
2656
2657         rcu_read_lock();
2658         if (pid) {
2659                 tsk = find_task_by_vpid(pid);
2660                 if (!tsk) {
2661                         tsk = ERR_PTR(-ESRCH);
2662                         goto out_unlock_threadgroup;
2663                 }
2664         } else {
2665                 tsk = current;
2666         }
2667
2668         if (threadgroup)
2669                 tsk = tsk->group_leader;
2670
2671         /*
2672          * kthreads may acquire PF_NO_SETAFFINITY during initialization.
2673          * If userland migrates such a kthread to a non-root cgroup, it can
2674          * become trapped in a cpuset, or RT kthread may be born in a
2675          * cgroup with no rt_runtime allocated.  Just say no.
2676          */
2677         if (tsk->no_cgroup_migration || (tsk->flags & PF_NO_SETAFFINITY)) {
2678                 tsk = ERR_PTR(-EINVAL);
2679                 goto out_unlock_threadgroup;
2680         }
2681
2682         get_task_struct(tsk);
2683         goto out_unlock_rcu;
2684
2685 out_unlock_threadgroup:
2686         percpu_up_write(&cgroup_threadgroup_rwsem);
2687 out_unlock_rcu:
2688         rcu_read_unlock();
2689         return tsk;
2690 }
2691
2692 void cgroup_procs_write_finish(struct task_struct *task)
2693         __releases(&cgroup_threadgroup_rwsem)
2694 {
2695         struct cgroup_subsys *ss;
2696         int ssid;
2697
2698         /* release reference from cgroup_procs_write_start() */
2699         put_task_struct(task);
2700
2701         percpu_up_write(&cgroup_threadgroup_rwsem);
2702         for_each_subsys(ss, ssid)
2703                 if (ss->post_attach)
2704                         ss->post_attach();
2705 }
2706
2707 static void cgroup_print_ss_mask(struct seq_file *seq, u16 ss_mask)
2708 {
2709         struct cgroup_subsys *ss;
2710         bool printed = false;
2711         int ssid;
2712
2713         do_each_subsys_mask(ss, ssid, ss_mask) {
2714                 if (printed)
2715                         seq_putc(seq, ' ');
2716                 seq_printf(seq, "%s", ss->name);
2717                 printed = true;
2718         } while_each_subsys_mask();
2719         if (printed)
2720                 seq_putc(seq, '\n');
2721 }
2722
2723 /* show controllers which are enabled from the parent */
2724 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2725 {
2726         struct cgroup *cgrp = seq_css(seq)->cgroup;
2727
2728         cgroup_print_ss_mask(seq, cgroup_control(cgrp));
2729         return 0;
2730 }
2731
2732 /* show controllers which are enabled for a given cgroup's children */
2733 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
2734 {
2735         struct cgroup *cgrp = seq_css(seq)->cgroup;
2736
2737         cgroup_print_ss_mask(seq, cgrp->subtree_control);
2738         return 0;
2739 }
2740
2741 /**
2742  * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
2743  * @cgrp: root of the subtree to update csses for
2744  *
2745  * @cgrp's control masks have changed and its subtree's css associations
2746  * need to be updated accordingly.  This function looks up all css_sets
2747  * which are attached to the subtree, creates the matching updated css_sets
2748  * and migrates the tasks to the new ones.
2749  */
2750 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
2751 {
2752         DEFINE_CGROUP_MGCTX(mgctx);
2753         struct cgroup_subsys_state *d_css;
2754         struct cgroup *dsct;
2755         struct css_set *src_cset;
2756         int ret;
2757
2758         lockdep_assert_held(&cgroup_mutex);
2759
2760         percpu_down_write(&cgroup_threadgroup_rwsem);
2761
2762         /* look up all csses currently attached to @cgrp's subtree */
2763         spin_lock_irq(&css_set_lock);
2764         cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2765                 struct cgrp_cset_link *link;
2766
2767                 list_for_each_entry(link, &dsct->cset_links, cset_link)
2768                         cgroup_migrate_add_src(link->cset, dsct, &mgctx);
2769         }
2770         spin_unlock_irq(&css_set_lock);
2771
2772         /* NULL dst indicates self on default hierarchy */
2773         ret = cgroup_migrate_prepare_dst(&mgctx);
2774         if (ret)
2775                 goto out_finish;
2776
2777         spin_lock_irq(&css_set_lock);
2778         list_for_each_entry(src_cset, &mgctx.preloaded_src_csets,
2779                             mg_src_preload_node) {
2780                 struct task_struct *task, *ntask;
2781
2782                 /* all tasks in src_csets need to be migrated */
2783                 list_for_each_entry_safe(task, ntask, &src_cset->tasks, cg_list)
2784                         cgroup_migrate_add_task(task, &mgctx);
2785         }
2786         spin_unlock_irq(&css_set_lock);
2787
2788         ret = cgroup_migrate_execute(&mgctx);
2789 out_finish:
2790         cgroup_migrate_finish(&mgctx);
2791         percpu_up_write(&cgroup_threadgroup_rwsem);
2792         return ret;
2793 }
2794
2795 /**
2796  * cgroup_lock_and_drain_offline - lock cgroup_mutex and drain offlined csses
2797  * @cgrp: root of the target subtree
2798  *
2799  * Because css offlining is asynchronous, userland may try to re-enable a
2800  * controller while the previous css is still around.  This function grabs
2801  * cgroup_mutex and drains the previous css instances of @cgrp's subtree.
2802  */
2803 void cgroup_lock_and_drain_offline(struct cgroup *cgrp)
2804         __acquires(&cgroup_mutex)
2805 {
2806         struct cgroup *dsct;
2807         struct cgroup_subsys_state *d_css;
2808         struct cgroup_subsys *ss;
2809         int ssid;
2810
2811 restart:
2812         mutex_lock(&cgroup_mutex);
2813
2814         cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2815                 for_each_subsys(ss, ssid) {
2816                         struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2817                         DEFINE_WAIT(wait);
2818
2819                         if (!css || !percpu_ref_is_dying(&css->refcnt))
2820                                 continue;
2821
2822                         cgroup_get_live(dsct);
2823                         prepare_to_wait(&dsct->offline_waitq, &wait,
2824                                         TASK_UNINTERRUPTIBLE);
2825
2826                         mutex_unlock(&cgroup_mutex);
2827                         schedule();
2828                         finish_wait(&dsct->offline_waitq, &wait);
2829
2830                         cgroup_put(dsct);
2831                         goto restart;
2832                 }
2833         }
2834 }
2835
2836 /**
2837  * cgroup_save_control - save control masks and dom_cgrp of a subtree
2838  * @cgrp: root of the target subtree
2839  *
2840  * Save ->subtree_control, ->subtree_ss_mask and ->dom_cgrp to the
2841  * respective old_ prefixed fields for @cgrp's subtree including @cgrp
2842  * itself.
2843  */
2844 static void cgroup_save_control(struct cgroup *cgrp)
2845 {
2846         struct cgroup *dsct;
2847         struct cgroup_subsys_state *d_css;
2848
2849         cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2850                 dsct->old_subtree_control = dsct->subtree_control;
2851                 dsct->old_subtree_ss_mask = dsct->subtree_ss_mask;
2852                 dsct->old_dom_cgrp = dsct->dom_cgrp;
2853         }
2854 }
2855
2856 /**
2857  * cgroup_propagate_control - refresh control masks of a subtree
2858  * @cgrp: root of the target subtree
2859  *
2860  * For @cgrp and its subtree, ensure ->subtree_ss_mask matches
2861  * ->subtree_control and propagate controller availability through the
2862  * subtree so that descendants don't have unavailable controllers enabled.
2863  */
2864 static void cgroup_propagate_control(struct cgroup *cgrp)
2865 {
2866         struct cgroup *dsct;
2867         struct cgroup_subsys_state *d_css;
2868
2869         cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2870                 dsct->subtree_control &= cgroup_control(dsct);
2871                 dsct->subtree_ss_mask =
2872                         cgroup_calc_subtree_ss_mask(dsct->subtree_control,
2873                                                     cgroup_ss_mask(dsct));
2874         }
2875 }
2876
2877 /**
2878  * cgroup_restore_control - restore control masks and dom_cgrp of a subtree
2879  * @cgrp: root of the target subtree
2880  *
2881  * Restore ->subtree_control, ->subtree_ss_mask and ->dom_cgrp from the
2882  * respective old_ prefixed fields for @cgrp's subtree including @cgrp
2883  * itself.
2884  */
2885 static void cgroup_restore_control(struct cgroup *cgrp)
2886 {
2887         struct cgroup *dsct;
2888         struct cgroup_subsys_state *d_css;
2889
2890         cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2891                 dsct->subtree_control = dsct->old_subtree_control;
2892                 dsct->subtree_ss_mask = dsct->old_subtree_ss_mask;
2893                 dsct->dom_cgrp = dsct->old_dom_cgrp;
2894         }
2895 }
2896
2897 static bool css_visible(struct cgroup_subsys_state *css)
2898 {
2899         struct cgroup_subsys *ss = css->ss;
2900         struct cgroup *cgrp = css->cgroup;
2901
2902         if (cgroup_control(cgrp) & (1 << ss->id))
2903                 return true;
2904         if (!(cgroup_ss_mask(cgrp) & (1 << ss->id)))
2905                 return false;
2906         return cgroup_on_dfl(cgrp) && ss->implicit_on_dfl;
2907 }
2908
2909 /**
2910  * cgroup_apply_control_enable - enable or show csses according to control
2911  * @cgrp: root of the target subtree
2912  *
2913  * Walk @cgrp's subtree and create new csses or make the existing ones
2914  * visible.  A css is created invisible if it's being implicitly enabled
2915  * through dependency.  An invisible css is made visible when the userland
2916  * explicitly enables it.
2917  *
2918  * Returns 0 on success, -errno on failure.  On failure, csses which have
2919  * been processed already aren't cleaned up.  The caller is responsible for
2920  * cleaning up with cgroup_apply_control_disable().
2921  */
2922 static int cgroup_apply_control_enable(struct cgroup *cgrp)
2923 {
2924         struct cgroup *dsct;
2925         struct cgroup_subsys_state *d_css;
2926         struct cgroup_subsys *ss;
2927         int ssid, ret;
2928
2929         cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
2930                 for_each_subsys(ss, ssid) {
2931                         struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2932
2933                         if (!(cgroup_ss_mask(dsct) & (1 << ss->id)))
2934                                 continue;
2935
2936                         if (!css) {
2937                                 css = css_create(dsct, ss);
2938                                 if (IS_ERR(css))
2939                                         return PTR_ERR(css);
2940                         }
2941
2942                         WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
2943
2944                         if (css_visible(css)) {
2945                                 ret = css_populate_dir(css);
2946                                 if (ret)
2947                                         return ret;
2948                         }
2949                 }
2950         }
2951
2952         return 0;
2953 }
2954
2955 /**
2956  * cgroup_apply_control_disable - kill or hide csses according to control
2957  * @cgrp: root of the target subtree
2958  *
2959  * Walk @cgrp's subtree and kill and hide csses so that they match
2960  * cgroup_ss_mask() and cgroup_visible_mask().
2961  *
2962  * A css is hidden when the userland requests it to be disabled while other
2963  * subsystems are still depending on it.  The css must not actively control
2964  * resources and be in the vanilla state if it's made visible again later.
2965  * Controllers which may be depended upon should provide ->css_reset() for
2966  * this purpose.
2967  */
2968 static void cgroup_apply_control_disable(struct cgroup *cgrp)
2969 {
2970         struct cgroup *dsct;
2971         struct cgroup_subsys_state *d_css;
2972         struct cgroup_subsys *ss;
2973         int ssid;
2974
2975         cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
2976                 for_each_subsys(ss, ssid) {
2977                         struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
2978
2979                         if (!css)
2980                                 continue;
2981
2982                         WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
2983
2984                         if (css->parent &&
2985                             !(cgroup_ss_mask(dsct) & (1 << ss->id))) {
2986                                 kill_css(css);
2987                         } else if (!css_visible(css)) {
2988                                 css_clear_dir(css);
2989                                 if (ss->css_reset)
2990                                         ss->css_reset(css);
2991                         }
2992                 }
2993         }
2994 }
2995
2996 /**
2997  * cgroup_apply_control - apply control mask updates to the subtree
2998  * @cgrp: root of the target subtree
2999  *
3000  * subsystems can be enabled and disabled in a subtree using the following
3001  * steps.
3002  *
3003  * 1. Call cgroup_save_control() to stash the current state.
3004  * 2. Update ->subtree_control masks in the subtree as desired.
3005  * 3. Call cgroup_apply_control() to apply the changes.
3006  * 4. Optionally perform other related operations.
3007  * 5. Call cgroup_finalize_control() to finish up.
3008  *
3009  * This function implements step 3 and propagates the mask changes
3010  * throughout @cgrp's subtree, updates csses accordingly and perform
3011  * process migrations.
3012  */
3013 static int cgroup_apply_control(struct cgroup *cgrp)
3014 {
3015         int ret;
3016
3017         cgroup_propagate_control(cgrp);
3018
3019         ret = cgroup_apply_control_enable(cgrp);
3020         if (ret)
3021                 return ret;
3022
3023         /*
3024          * At this point, cgroup_e_css() results reflect the new csses
3025          * making the following cgroup_update_dfl_csses() properly update
3026          * css associations of all tasks in the subtree.
3027          */
3028         ret = cgroup_update_dfl_csses(cgrp);
3029         if (ret)
3030                 return ret;
3031
3032         return 0;
3033 }
3034
3035 /**
3036  * cgroup_finalize_control - finalize control mask update
3037  * @cgrp: root of the target subtree
3038  * @ret: the result of the update
3039  *
3040  * Finalize control mask update.  See cgroup_apply_control() for more info.
3041  */
3042 static void cgroup_finalize_control(struct cgroup *cgrp, int ret)
3043 {
3044         if (ret) {
3045                 cgroup_restore_control(cgrp);
3046                 cgroup_propagate_control(cgrp);
3047         }
3048
3049         cgroup_apply_control_disable(cgrp);
3050 }
3051
3052 static int cgroup_vet_subtree_control_enable(struct cgroup *cgrp, u16 enable)
3053 {
3054         u16 domain_enable = enable & ~cgrp_dfl_threaded_ss_mask;
3055
3056         /* if nothing is getting enabled, nothing to worry about */
3057         if (!enable)
3058                 return 0;
3059
3060         /* can @cgrp host any resources? */
3061         if (!cgroup_is_valid_domain(cgrp->dom_cgrp))
3062                 return -EOPNOTSUPP;
3063
3064         /* mixables don't care */
3065         if (cgroup_is_mixable(cgrp))
3066                 return 0;
3067
3068         if (domain_enable) {
3069                 /* can't enable domain controllers inside a thread subtree */
3070                 if (cgroup_is_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3071                         return -EOPNOTSUPP;
3072         } else {
3073                 /*
3074                  * Threaded controllers can handle internal competitions
3075                  * and are always allowed inside a (prospective) thread
3076                  * subtree.
3077                  */
3078                 if (cgroup_can_be_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3079                         return 0;
3080         }
3081
3082         /*
3083          * Controllers can't be enabled for a cgroup with tasks to avoid
3084          * child cgroups competing against tasks.
3085          */
3086         if (cgroup_has_tasks(cgrp))
3087                 return -EBUSY;
3088
3089         return 0;
3090 }
3091
3092 /* change the enabled child controllers for a cgroup in the default hierarchy */
3093 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
3094                                             char *buf, size_t nbytes,
3095                                             loff_t off)
3096 {
3097         u16 enable = 0, disable = 0;
3098         struct cgroup *cgrp, *child;
3099         struct cgroup_subsys *ss;
3100         char *tok;
3101         int ssid, ret;
3102
3103         /*
3104          * Parse input - space separated list of subsystem names prefixed
3105          * with either + or -.
3106          */
3107         buf = strstrip(buf);
3108         while ((tok = strsep(&buf, " "))) {
3109                 if (tok[0] == '\0')
3110                         continue;
3111                 do_each_subsys_mask(ss, ssid, ~cgrp_dfl_inhibit_ss_mask) {
3112                         if (!cgroup_ssid_enabled(ssid) ||
3113                             strcmp(tok + 1, ss->name))
3114                                 continue;
3115
3116                         if (*tok == '+') {
3117                                 enable |= 1 << ssid;
3118                                 disable &= ~(1 << ssid);
3119                         } else if (*tok == '-') {
3120                                 disable |= 1 << ssid;
3121                                 enable &= ~(1 << ssid);
3122                         } else {
3123                                 return -EINVAL;
3124                         }
3125                         break;
3126                 } while_each_subsys_mask();
3127                 if (ssid == CGROUP_SUBSYS_COUNT)
3128                         return -EINVAL;
3129         }
3130
3131         cgrp = cgroup_kn_lock_live(of->kn, true);
3132         if (!cgrp)
3133                 return -ENODEV;
3134
3135         for_each_subsys(ss, ssid) {
3136                 if (enable & (1 << ssid)) {
3137                         if (cgrp->subtree_control & (1 << ssid)) {
3138                                 enable &= ~(1 << ssid);
3139                                 continue;
3140                         }
3141
3142                         if (!(cgroup_control(cgrp) & (1 << ssid))) {
3143                                 ret = -ENOENT;
3144                                 goto out_unlock;
3145                         }
3146                 } else if (disable & (1 << ssid)) {
3147                         if (!(cgrp->subtree_control & (1 << ssid))) {
3148                                 disable &= ~(1 << ssid);
3149                                 continue;
3150                         }
3151
3152                         /* a child has it enabled? */
3153                         cgroup_for_each_live_child(child, cgrp) {
3154                                 if (child->subtree_control & (1 << ssid)) {
3155                                         ret = -EBUSY;
3156                                         goto out_unlock;
3157                                 }
3158                         }
3159                 }
3160         }
3161
3162         if (!enable && !disable) {
3163                 ret = 0;
3164                 goto out_unlock;
3165         }
3166
3167         ret = cgroup_vet_subtree_control_enable(cgrp, enable);
3168         if (ret)
3169                 goto out_unlock;
3170
3171         /* save and update control masks and prepare csses */
3172         cgroup_save_control(cgrp);
3173
3174         cgrp->subtree_control |= enable;
3175         cgrp->subtree_control &= ~disable;
3176
3177         ret = cgroup_apply_control(cgrp);
3178         cgroup_finalize_control(cgrp, ret);
3179         if (ret)
3180                 goto out_unlock;
3181
3182         kernfs_activate(cgrp->kn);
3183 out_unlock:
3184         cgroup_kn_unlock(of->kn);
3185         return ret ?: nbytes;
3186 }
3187
3188 /**
3189  * cgroup_enable_threaded - make @cgrp threaded
3190  * @cgrp: the target cgroup
3191  *
3192  * Called when "threaded" is written to the cgroup.type interface file and
3193  * tries to make @cgrp threaded and join the parent's resource domain.
3194  * This function is never called on the root cgroup as cgroup.type doesn't
3195  * exist on it.
3196  */
3197 static int cgroup_enable_threaded(struct cgroup *cgrp)
3198 {
3199         struct cgroup *parent = cgroup_parent(cgrp);
3200         struct cgroup *dom_cgrp = parent->dom_cgrp;
3201         struct cgroup *dsct;
3202         struct cgroup_subsys_state *d_css;
3203         int ret;
3204
3205         lockdep_assert_held(&cgroup_mutex);
3206
3207         /* noop if already threaded */
3208         if (cgroup_is_threaded(cgrp))
3209                 return 0;
3210
3211         /*
3212          * If @cgroup is populated or has domain controllers enabled, it
3213          * can't be switched.  While the below cgroup_can_be_thread_root()
3214          * test can catch the same conditions, that's only when @parent is
3215          * not mixable, so let's check it explicitly.
3216          */
3217         if (cgroup_is_populated(cgrp) ||
3218             cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
3219                 return -EOPNOTSUPP;
3220
3221         /* we're joining the parent's domain, ensure its validity */
3222         if (!cgroup_is_valid_domain(dom_cgrp) ||
3223             !cgroup_can_be_thread_root(dom_cgrp))
3224                 return -EOPNOTSUPP;
3225
3226         /*
3227          * The following shouldn't cause actual migrations and should
3228          * always succeed.
3229          */
3230         cgroup_save_control(cgrp);
3231
3232         cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp)
3233                 if (dsct == cgrp || cgroup_is_threaded(dsct))
3234                         dsct->dom_cgrp = dom_cgrp;
3235
3236         ret = cgroup_apply_control(cgrp);
3237         if (!ret)
3238                 parent->nr_threaded_children++;
3239
3240         cgroup_finalize_control(cgrp, ret);
3241         return ret;
3242 }
3243
3244 static int cgroup_type_show(struct seq_file *seq, void *v)
3245 {
3246         struct cgroup *cgrp = seq_css(seq)->cgroup;
3247
3248         if (cgroup_is_threaded(cgrp))
3249                 seq_puts(seq, "threaded\n");
3250         else if (!cgroup_is_valid_domain(cgrp))
3251                 seq_puts(seq, "domain invalid\n");
3252         else if (cgroup_is_thread_root(cgrp))
3253                 seq_puts(seq, "domain threaded\n");
3254         else
3255                 seq_puts(seq, "domain\n");
3256
3257         return 0;
3258 }
3259
3260 static ssize_t cgroup_type_write(struct kernfs_open_file *of, char *buf,
3261                                  size_t nbytes, loff_t off)
3262 {
3263         struct cgroup *cgrp;
3264         int ret;
3265
3266         /* only switching to threaded mode is supported */
3267         if (strcmp(strstrip(buf), "threaded"))
3268                 return -EINVAL;
3269
3270         /* drain dying csses before we re-apply (threaded) subtree control */
3271         cgrp = cgroup_kn_lock_live(of->kn, true);
3272         if (!cgrp)
3273                 return -ENOENT;
3274
3275         /* threaded can only be enabled */
3276         ret = cgroup_enable_threaded(cgrp);
3277
3278         cgroup_kn_unlock(of->kn);
3279         return ret ?: nbytes;
3280 }
3281
3282 static int cgroup_max_descendants_show(struct seq_file *seq, void *v)
3283 {
3284         struct cgroup *cgrp = seq_css(seq)->cgroup;
3285         int descendants = READ_ONCE(cgrp->max_descendants);
3286
3287         if (descendants == INT_MAX)
3288                 seq_puts(seq, "max\n");
3289         else
3290                 seq_printf(seq, "%d\n", descendants);
3291
3292         return 0;
3293 }
3294
3295 static ssize_t cgroup_max_descendants_write(struct kernfs_open_file *of,
3296                                            char *buf, size_t nbytes, loff_t off)
3297 {
3298         struct cgroup *cgrp;
3299         int descendants;
3300         ssize_t ret;
3301
3302         buf = strstrip(buf);
3303         if (!strcmp(buf, "max")) {
3304                 descendants = INT_MAX;
3305         } else {
3306                 ret = kstrtoint(buf, 0, &descendants);
3307                 if (ret)
3308                         return ret;
3309         }
3310
3311         if (descendants < 0)
3312                 return -ERANGE;
3313
3314         cgrp = cgroup_kn_lock_live(of->kn, false);
3315         if (!cgrp)
3316                 return -ENOENT;
3317
3318         cgrp->max_descendants = descendants;
3319
3320         cgroup_kn_unlock(of->kn);
3321
3322         return nbytes;
3323 }
3324
3325 static int cgroup_max_depth_show(struct seq_file *seq, void *v)
3326 {
3327         struct cgroup *cgrp = seq_css(seq)->cgroup;
3328         int depth = READ_ONCE(cgrp->max_depth);
3329
3330         if (depth == INT_MAX)
3331                 seq_puts(seq, "max\n");
3332         else
3333                 seq_printf(seq, "%d\n", depth);
3334
3335         return 0;
3336 }
3337
3338 static ssize_t cgroup_max_depth_write(struct kernfs_open_file *of,
3339                                       char *buf, size_t nbytes, loff_t off)
3340 {
3341         struct cgroup *cgrp;
3342         ssize_t ret;
3343         int depth;
3344
3345         buf = strstrip(buf);
3346         if (!strcmp(buf, "max")) {
3347                 depth = INT_MAX;
3348         } else {
3349                 ret = kstrtoint(buf, 0, &depth);
3350                 if (ret)
3351                         return ret;
3352         }
3353
3354         if (depth < 0)
3355                 return -ERANGE;
3356
3357         cgrp = cgroup_kn_lock_live(of->kn, false);
3358         if (!cgrp)
3359                 return -ENOENT;
3360
3361         cgrp->max_depth = depth;
3362
3363         cgroup_kn_unlock(of->kn);
3364
3365         return nbytes;
3366 }
3367
3368 static int cgroup_events_show(struct seq_file *seq, void *v)
3369 {
3370         seq_printf(seq, "populated %d\n",
3371                    cgroup_is_populated(seq_css(seq)->cgroup));
3372         return 0;
3373 }
3374
3375 static int cgroup_stat_show(struct seq_file *seq, void *v)
3376 {
3377         struct cgroup *cgroup = seq_css(seq)->cgroup;
3378
3379         seq_printf(seq, "nr_descendants %d\n",
3380                    cgroup->nr_descendants);
3381         seq_printf(seq, "nr_dying_descendants %d\n",
3382                    cgroup->nr_dying_descendants);
3383
3384         return 0;
3385 }
3386
3387 static int cgroup_file_open(struct kernfs_open_file *of)
3388 {
3389         struct cftype *cft = of->kn->priv;
3390         struct cgroup_file_ctx *ctx;
3391         int ret;
3392
3393         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
3394         if (!ctx)
3395                 return -ENOMEM;
3396
3397         ctx->ns = current->nsproxy->cgroup_ns;
3398         get_cgroup_ns(ctx->ns);
3399         of->priv = ctx;
3400
3401         if (!cft->open)
3402                 return 0;
3403
3404         ret = cft->open(of);
3405         if (ret) {
3406                 put_cgroup_ns(ctx->ns);
3407                 kfree(ctx);
3408         }
3409         return ret;
3410 }
3411
3412 static void cgroup_file_release(struct kernfs_open_file *of)
3413 {
3414         struct cftype *cft = of->kn->priv;
3415         struct cgroup_file_ctx *ctx = of->priv;
3416
3417         if (cft->release)
3418                 cft->release(of);
3419         put_cgroup_ns(ctx->ns);
3420         kfree(ctx);
3421 }
3422
3423 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
3424                                  size_t nbytes, loff_t off)
3425 {
3426         struct cgroup_file_ctx *ctx = of->priv;
3427         struct cgroup *cgrp = of->kn->parent->priv;
3428         struct cftype *cft = of->kn->priv;
3429         struct cgroup_subsys_state *css;
3430         int ret;
3431
3432         /*
3433          * If namespaces are delegation boundaries, disallow writes to
3434          * files in an non-init namespace root from inside the namespace
3435          * except for the files explicitly marked delegatable -
3436          * cgroup.procs and cgroup.subtree_control.
3437          */
3438         if ((cgrp->root->flags & CGRP_ROOT_NS_DELEGATE) &&
3439             !(cft->flags & CFTYPE_NS_DELEGATABLE) &&
3440             ctx->ns != &init_cgroup_ns && ctx->ns->root_cset->dfl_cgrp == cgrp)
3441                 return -EPERM;
3442
3443         if (cft->write)
3444                 return cft->write(of, buf, nbytes, off);
3445
3446         /*
3447          * kernfs guarantees that a file isn't deleted with operations in
3448          * flight, which means that the matching css is and stays alive and
3449          * doesn't need to be pinned.  The RCU locking is not necessary
3450          * either.  It's just for the convenience of using cgroup_css().
3451          */
3452         rcu_read_lock();
3453         css = cgroup_css(cgrp, cft->ss);
3454         rcu_read_unlock();
3455
3456         if (cft->write_u64) {
3457                 unsigned long long v;
3458                 ret = kstrtoull(buf, 0, &v);
3459                 if (!ret)
3460                         ret = cft->write_u64(css, cft, v);
3461         } else if (cft->write_s64) {
3462                 long long v;
3463                 ret = kstrtoll(buf, 0, &v);
3464                 if (!ret)
3465                         ret = cft->write_s64(css, cft, v);
3466         } else {
3467                 ret = -EINVAL;
3468         }
3469
3470         return ret ?: nbytes;
3471 }
3472
3473 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
3474 {
3475         return seq_cft(seq)->seq_start(seq, ppos);
3476 }
3477
3478 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
3479 {
3480         return seq_cft(seq)->seq_next(seq, v, ppos);
3481 }
3482
3483 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
3484 {
3485         if (seq_cft(seq)->seq_stop)
3486                 seq_cft(seq)->seq_stop(seq, v);
3487 }
3488
3489 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
3490 {
3491         struct cftype *cft = seq_cft(m);
3492         struct cgroup_subsys_state *css = seq_css(m);
3493
3494         if (cft->seq_show)
3495                 return cft->seq_show(m, arg);
3496
3497         if (cft->read_u64)
3498                 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
3499         else if (cft->read_s64)
3500                 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
3501         else
3502                 return -EINVAL;
3503         return 0;
3504 }
3505
3506 static struct kernfs_ops cgroup_kf_single_ops = {
3507         .atomic_write_len       = PAGE_SIZE,
3508         .open                   = cgroup_file_open,
3509         .release                = cgroup_file_release,
3510         .write                  = cgroup_file_write,
3511         .seq_show               = cgroup_seqfile_show,
3512 };
3513
3514 static struct kernfs_ops cgroup_kf_ops = {
3515         .atomic_write_len       = PAGE_SIZE,
3516         .open                   = cgroup_file_open,
3517         .release                = cgroup_file_release,
3518         .write                  = cgroup_file_write,
3519         .seq_start              = cgroup_seqfile_start,
3520         .seq_next               = cgroup_seqfile_next,
3521         .seq_stop               = cgroup_seqfile_stop,
3522         .seq_show               = cgroup_seqfile_show,
3523 };
3524
3525 /* set uid and gid of cgroup dirs and files to that of the creator */
3526 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
3527 {
3528         struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
3529                                .ia_uid = current_fsuid(),
3530                                .ia_gid = current_fsgid(), };
3531
3532         if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
3533             gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
3534                 return 0;
3535
3536         return kernfs_setattr(kn, &iattr);
3537 }
3538
3539 static int cgroup_add_file(struct cgroup_subsys_state *css, struct cgroup *cgrp,
3540                            struct cftype *cft)
3541 {
3542         char name[CGROUP_FILE_NAME_MAX];
3543         struct kernfs_node *kn;
3544         struct lock_class_key *key = NULL;
3545         int ret;
3546
3547 #ifdef CONFIG_DEBUG_LOCK_ALLOC
3548         key = &cft->lockdep_key;
3549 #endif
3550         kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
3551                                   cgroup_file_mode(cft), 0, cft->kf_ops, cft,
3552                                   NULL, key);
3553         if (IS_ERR(kn))
3554                 return PTR_ERR(kn);
3555
3556         ret = cgroup_kn_set_ugid(kn);
3557         if (ret) {
3558                 kernfs_remove(kn);
3559                 return ret;
3560         }
3561
3562         if (cft->file_offset) {
3563                 struct cgroup_file *cfile = (void *)css + cft->file_offset;
3564
3565                 spin_lock_irq(&cgroup_file_kn_lock);
3566                 cfile->kn = kn;
3567                 spin_unlock_irq(&cgroup_file_kn_lock);
3568         }
3569
3570         return 0;
3571 }
3572
3573 /**
3574  * cgroup_addrm_files - add or remove files to a cgroup directory
3575  * @css: the target css
3576  * @cgrp: the target cgroup (usually css->cgroup)
3577  * @cfts: array of cftypes to be added
3578  * @is_add: whether to add or remove
3579  *
3580  * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
3581  * For removals, this function never fails.
3582  */
3583 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
3584                               struct cgroup *cgrp, struct cftype cfts[],
3585                               bool is_add)
3586 {
3587         struct cftype *cft, *cft_end = NULL;
3588         int ret = 0;
3589
3590         lockdep_assert_held(&cgroup_mutex);
3591
3592 restart:
3593         for (cft = cfts; cft != cft_end && cft->name[0] != '\0'; cft++) {
3594                 /* does cft->flags tell us to skip this file on @cgrp? */
3595                 if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
3596                         continue;
3597                 if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
3598                         continue;
3599                 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
3600                         continue;
3601                 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
3602                         continue;
3603
3604                 if (is_add) {
3605                         ret = cgroup_add_file(css, cgrp, cft);
3606                         if (ret) {
3607                                 pr_warn("%s: failed to add %s, err=%d\n",
3608                                         __func__, cft->name, ret);
3609                                 cft_end = cft;
3610                                 is_add = false;
3611                                 goto restart;
3612                         }
3613                 } else {
3614                         cgroup_rm_file(cgrp, cft);
3615                 }
3616         }
3617         return ret;
3618 }
3619
3620 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
3621 {
3622         struct cgroup_subsys *ss = cfts[0].ss;
3623         struct cgroup *root = &ss->root->cgrp;
3624         struct cgroup_subsys_state *css;
3625         int ret = 0;
3626
3627         lockdep_assert_held(&cgroup_mutex);
3628
3629         /* add/rm files for all cgroups created before */
3630         css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
3631                 struct cgroup *cgrp = css->cgroup;
3632
3633                 if (!(css->flags & CSS_VISIBLE))
3634                         continue;
3635
3636                 ret = cgroup_addrm_files(css, cgrp, cfts, is_add);
3637                 if (ret)
3638                         break;
3639         }
3640
3641         if (is_add && !ret)
3642                 kernfs_activate(root->kn);
3643         return ret;
3644 }
3645
3646 static void cgroup_exit_cftypes(struct cftype *cfts)
3647 {
3648         struct cftype *cft;
3649
3650         for (cft = cfts; cft->name[0] != '\0'; cft++) {
3651                 /* free copy for custom atomic_write_len, see init_cftypes() */
3652                 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
3653                         kfree(cft->kf_ops);
3654                 cft->kf_ops = NULL;
3655                 cft->ss = NULL;
3656
3657                 /* revert flags set by cgroup core while adding @cfts */
3658                 cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL);
3659         }
3660 }
3661
3662 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3663 {
3664         struct cftype *cft;
3665
3666         for (cft = cfts; cft->name[0] != '\0'; cft++) {
3667                 struct kernfs_ops *kf_ops;
3668
3669                 WARN_ON(cft->ss || cft->kf_ops);
3670
3671                 if (cft->seq_start)
3672                         kf_ops = &cgroup_kf_ops;
3673                 else
3674                         kf_ops = &cgroup_kf_single_ops;
3675
3676                 /*
3677                  * Ugh... if @cft wants a custom max_write_len, we need to
3678                  * make a copy of kf_ops to set its atomic_write_len.
3679                  */
3680                 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
3681                         kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
3682                         if (!kf_ops) {
3683                                 cgroup_exit_cftypes(cfts);
3684                                 return -ENOMEM;
3685                         }
3686                         kf_ops->atomic_write_len = cft->max_write_len;
3687                 }
3688
3689                 cft->kf_ops = kf_ops;
3690                 cft->ss = ss;
3691         }
3692
3693         return 0;
3694 }
3695
3696 static int cgroup_rm_cftypes_locked(struct cftype *cfts)
3697 {
3698         lockdep_assert_held(&cgroup_mutex);
3699
3700         if (!cfts || !cfts[0].ss)
3701                 return -ENOENT;
3702
3703         list_del(&cfts->node);
3704         cgroup_apply_cftypes(cfts, false);
3705         cgroup_exit_cftypes(cfts);
3706         return 0;
3707 }
3708
3709 /**
3710  * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
3711  * @cfts: zero-length name terminated array of cftypes
3712  *
3713  * Unregister @cfts.  Files described by @cfts are removed from all
3714  * existing cgroups and all future cgroups won't have them either.  This
3715  * function can be called anytime whether @cfts' subsys is attached or not.
3716  *
3717  * Returns 0 on successful unregistration, -ENOENT if @cfts is not
3718  * registered.
3719  */
3720 int cgroup_rm_cftypes(struct cftype *cfts)
3721 {
3722         int ret;
3723
3724         mutex_lock(&cgroup_mutex);
3725         ret = cgroup_rm_cftypes_locked(cfts);
3726         mutex_unlock(&cgroup_mutex);
3727         return ret;
3728 }
3729
3730 /**
3731  * cgroup_add_cftypes - add an array of cftypes to a subsystem
3732  * @ss: target cgroup subsystem
3733  * @cfts: zero-length name terminated array of cftypes
3734  *
3735  * Register @cfts to @ss.  Files described by @cfts are created for all
3736  * existing cgroups to which @ss is attached and all future cgroups will
3737  * have them too.  This function can be called anytime whether @ss is
3738  * attached or not.
3739  *
3740  * Returns 0 on successful registration, -errno on failure.  Note that this
3741  * function currently returns 0 as long as @cfts registration is successful
3742  * even if some file creation attempts on existing cgroups fail.
3743  */
3744 static int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3745 {
3746         int ret;
3747
3748         if (!cgroup_ssid_enabled(ss->id))
3749                 return 0;
3750
3751         if (!cfts || cfts[0].name[0] == '\0')
3752                 return 0;
3753
3754         ret = cgroup_init_cftypes(ss, cfts);
3755         if (ret)
3756                 return ret;
3757
3758         mutex_lock(&cgroup_mutex);
3759
3760         list_add_tail(&cfts->node, &ss->cfts);
3761         ret = cgroup_apply_cftypes(cfts, true);
3762         if (ret)
3763                 cgroup_rm_cftypes_locked(cfts);
3764
3765         mutex_unlock(&cgroup_mutex);
3766         return ret;
3767 }
3768
3769 /**
3770  * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
3771  * @ss: target cgroup subsystem
3772  * @cfts: zero-length name terminated array of cftypes
3773  *
3774  * Similar to cgroup_add_cftypes() but the added files are only used for
3775  * the default hierarchy.
3776  */
3777 int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3778 {
3779         struct cftype *cft;
3780
3781         for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3782                 cft->flags |= __CFTYPE_ONLY_ON_DFL;
3783         return cgroup_add_cftypes(ss, cfts);
3784 }
3785
3786 /**
3787  * cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies
3788  * @ss: target cgroup subsystem
3789  * @cfts: zero-length name terminated array of cftypes
3790  *
3791  * Similar to cgroup_add_cftypes() but the added files are only used for
3792  * the legacy hierarchies.
3793  */
3794 int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
3795 {
3796         struct cftype *cft;
3797
3798         for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
3799                 cft->flags |= __CFTYPE_NOT_ON_DFL;
3800         return cgroup_add_cftypes(ss, cfts);
3801 }
3802
3803 /**
3804  * cgroup_file_notify - generate a file modified event for a cgroup_file
3805  * @cfile: target cgroup_file
3806  *
3807  * @cfile must have been obtained by setting cftype->file_offset.
3808  */
3809 void cgroup_file_notify(struct cgroup_file *cfile)
3810 {
3811         unsigned long flags;
3812
3813         spin_lock_irqsave(&cgroup_file_kn_lock, flags);
3814         if (cfile->kn)
3815                 kernfs_notify(cfile->kn);
3816         spin_unlock_irqrestore(&cgroup_file_kn_lock, flags);
3817 }
3818
3819 /**
3820  * css_next_child - find the next child of a given css
3821  * @pos: the current position (%NULL to initiate traversal)
3822  * @parent: css whose children to walk
3823  *
3824  * This function returns the next child of @parent and should be called
3825  * under either cgroup_mutex or RCU read lock.  The only requirement is
3826  * that @parent and @pos are accessible.  The next sibling is guaranteed to
3827  * be returned regardless of their states.
3828  *
3829  * If a subsystem synchronizes ->css_online() and the start of iteration, a
3830  * css which finished ->css_online() is guaranteed to be visible in the
3831  * future iterations and will stay visible until the last reference is put.
3832  * A css which hasn't finished ->css_online() or already finished
3833  * ->css_offline() may show up during traversal.  It's each subsystem's
3834  * responsibility to synchronize against on/offlining.
3835  */
3836 struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
3837                                            struct cgroup_subsys_state *parent)
3838 {
3839         struct cgroup_subsys_state *next;
3840
3841         cgroup_assert_mutex_or_rcu_locked();
3842
3843         /*
3844          * @pos could already have been unlinked from the sibling list.
3845          * Once a cgroup is removed, its ->sibling.next is no longer
3846          * updated when its next sibling changes.  CSS_RELEASED is set when
3847          * @pos is taken off list, at which time its next pointer is valid,
3848          * and, as releases are serialized, the one pointed to by the next
3849          * pointer is guaranteed to not have started release yet.  This
3850          * implies that if we observe !CSS_RELEASED on @pos in this RCU
3851          * critical section, the one pointed to by its next pointer is
3852          * guaranteed to not have finished its RCU grace period even if we
3853          * have dropped rcu_read_lock() inbetween iterations.
3854          *
3855          * If @pos has CSS_RELEASED set, its next pointer can't be
3856          * dereferenced; however, as each css is given a monotonically
3857          * increasing unique serial number and always appended to the
3858          * sibling list, the next one can be found by walking the parent's
3859          * children until the first css with higher serial number than
3860          * @pos's.  While this path can be slower, it happens iff iteration
3861          * races against release and the race window is very small.
3862          */
3863         if (!pos) {
3864                 next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
3865         } else if (likely(!(pos->flags & CSS_RELEASED))) {
3866                 next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
3867         } else {
3868                 list_for_each_entry_rcu(next, &parent->children, sibling)
3869                         if (next->serial_nr > pos->serial_nr)
3870                                 break;
3871         }
3872
3873         /*
3874          * @next, if not pointing to the head, can be dereferenced and is
3875          * the next sibling.
3876          */
3877         if (&next->sibling != &parent->children)
3878                 return next;
3879         return NULL;
3880 }
3881
3882 /**
3883  * css_next_descendant_pre - find the next descendant for pre-order walk
3884  * @pos: the current position (%NULL to initiate traversal)
3885  * @root: css whose descendants to walk
3886  *
3887  * To be used by css_for_each_descendant_pre().  Find the next descendant
3888  * to visit for pre-order traversal of @root's descendants.  @root is
3889  * included in the iteration and the first node to be visited.
3890  *
3891  * While this function requires cgroup_mutex or RCU read locking, it
3892  * doesn't require the whole traversal to be contained in a single critical
3893  * section.  This function will return the correct next descendant as long
3894  * as both @pos and @root are accessible and @pos is a descendant of @root.
3895  *
3896  * If a subsystem synchronizes ->css_online() and the start of iteration, a
3897  * css which finished ->css_online() is guaranteed to be visible in the
3898  * future iterations and will stay visible until the last reference is put.
3899  * A css which hasn't finished ->css_online() or already finished
3900  * ->css_offline() may show up during traversal.  It's each subsystem's
3901  * responsibility to synchronize against on/offlining.
3902  */
3903 struct cgroup_subsys_state *
3904 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3905                         struct cgroup_subsys_state *root)
3906 {
3907         struct cgroup_subsys_state *next;
3908
3909         cgroup_assert_mutex_or_rcu_locked();
3910
3911         /* if first iteration, visit @root */
3912         if (!pos)
3913                 return root;
3914
3915         /* visit the first child if exists */
3916         next = css_next_child(NULL, pos);
3917         if (next)
3918                 return next;
3919
3920         /* no child, visit my or the closest ancestor's next sibling */
3921         while (pos != root) {
3922                 next = css_next_child(pos, pos->parent);
3923                 if (next)
3924                         return next;
3925                 pos = pos->parent;
3926         }
3927
3928         return NULL;
3929 }
3930
3931 /**
3932  * css_rightmost_descendant - return the rightmost descendant of a css
3933  * @pos: css of interest
3934  *
3935  * Return the rightmost descendant of @pos.  If there's no descendant, @pos
3936  * is returned.  This can be used during pre-order traversal to skip
3937  * subtree of @pos.
3938  *
3939  * While this function requires cgroup_mutex or RCU read locking, it
3940  * doesn't require the whole traversal to be contained in a single critical
3941  * section.  This function will return the correct rightmost descendant as
3942  * long as @pos is accessible.
3943  */
3944 struct cgroup_subsys_state *
3945 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3946 {
3947         struct cgroup_subsys_state *last, *tmp;
3948
3949         cgroup_assert_mutex_or_rcu_locked();
3950
3951         do {
3952                 last = pos;
3953                 /* ->prev isn't RCU safe, walk ->next till the end */
3954                 pos = NULL;
3955                 css_for_each_child(tmp, last)
3956                         pos = tmp;
3957         } while (pos);
3958
3959         return last;
3960 }
3961
3962 static struct cgroup_subsys_state *
3963 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3964 {
3965         struct cgroup_subsys_state *last;
3966
3967         do {
3968                 last = pos;
3969                 pos = css_next_child(NULL, pos);
3970         } while (pos);
3971
3972         return last;
3973 }
3974
3975 /**
3976  * css_next_descendant_post - find the next descendant for post-order walk
3977  * @pos: the current position (%NULL to initiate traversal)
3978  * @root: css whose descendants to walk
3979  *
3980  * To be used by css_for_each_descendant_post().  Find the next descendant
3981  * to visit for post-order traversal of @root's descendants.  @root is
3982  * included in the iteration and the last node to be visited.
3983  *
3984  * While this function requires cgroup_mutex or RCU read locking, it
3985  * doesn't require the whole traversal to be contained in a single critical
3986  * section.  This function will return the correct next descendant as long
3987  * as both @pos and @cgroup are accessible and @pos is a descendant of
3988  * @cgroup.
3989  *
3990  * If a subsystem synchronizes ->css_online() and the start of iteration, a
3991  * css which finished ->css_online() is guaranteed to be visible in the
3992  * future iterations and will stay visible until the last reference is put.
3993  * A css which hasn't finished ->css_online() or already finished
3994  * ->css_offline() may show up during traversal.  It's each subsystem's
3995  * responsibility to synchronize against on/offlining.
3996  */
3997 struct cgroup_subsys_state *
3998 css_next_descendant_post(struct cgroup_subsys_state *pos,
3999                          struct cgroup_subsys_state *root)
4000 {
4001         struct cgroup_subsys_state *next;
4002
4003         cgroup_assert_mutex_or_rcu_locked();
4004
4005         /* if first iteration, visit leftmost descendant which may be @root */
4006         if (!pos)
4007                 return css_leftmost_descendant(root);
4008
4009         /* if we visited @root, we're done */
4010         if (pos == root)
4011                 return NULL;
4012
4013         /* if there's an unvisited sibling, visit its leftmost descendant */
4014         next = css_next_child(pos, pos->parent);
4015         if (next)
4016                 return css_leftmost_descendant(next);
4017
4018         /* no sibling left, visit parent */
4019         return pos->parent;
4020 }
4021
4022 /**
4023  * css_has_online_children - does a css have online children
4024  * @css: the target css
4025  *
4026  * Returns %true if @css has any online children; otherwise, %false.  This
4027  * function can be called from any context but the caller is responsible
4028  * for synchronizing against on/offlining as necessary.
4029  */
4030 bool css_has_online_children(struct cgroup_subsys_state *css)
4031 {
4032         struct cgroup_subsys_state *child;
4033         bool ret = false;
4034
4035         rcu_read_lock();
4036         css_for_each_child(child, css) {
4037                 if (child->flags & CSS_ONLINE) {
4038                         ret = true;
4039                         break;
4040                 }
4041         }
4042         rcu_read_unlock();
4043         return ret;
4044 }
4045
4046 static struct css_set *css_task_iter_next_css_set(struct css_task_iter *it)
4047 {
4048         struct list_head *l;
4049         struct cgrp_cset_link *link;
4050         struct css_set *cset;
4051
4052         lockdep_assert_held(&css_set_lock);
4053
4054         /* find the next threaded cset */
4055         if (it->tcset_pos) {
4056                 l = it->tcset_pos->next;
4057
4058                 if (l != it->tcset_head) {
4059                         it->tcset_pos = l;
4060                         return container_of(l, struct css_set,
4061                                             threaded_csets_node);
4062                 }
4063
4064                 it->tcset_pos = NULL;
4065         }
4066
4067         /* find the next cset */
4068         l = it->cset_pos;
4069         l = l->next;
4070         if (l == it->cset_head) {
4071                 it->cset_pos = NULL;
4072                 return NULL;
4073         }
4074
4075         if (it->ss) {
4076                 cset = container_of(l, struct css_set, e_cset_node[it->ss->id]);
4077         } else {
4078                 link = list_entry(l, struct cgrp_cset_link, cset_link);
4079                 cset = link->cset;
4080         }
4081
4082         it->cset_pos = l;
4083
4084         /* initialize threaded css_set walking */
4085         if (it->flags & CSS_TASK_ITER_THREADED) {
4086                 if (it->cur_dcset)
4087                         put_css_set_locked(it->cur_dcset);
4088                 it->cur_dcset = cset;
4089                 get_css_set(cset);
4090
4091                 it->tcset_head = &cset->threaded_csets;
4092                 it->tcset_pos = &cset->threaded_csets;
4093         }
4094
4095         return cset;
4096 }
4097
4098 /**
4099  * css_task_iter_advance_css_set - advance a task itererator to the next css_set
4100  * @it: the iterator to advance
4101  *
4102  * Advance @it to the next css_set to walk.
4103  */
4104 static void css_task_iter_advance_css_set(struct css_task_iter *it)
4105 {
4106         struct css_set *cset;
4107
4108         lockdep_assert_held(&css_set_lock);
4109
4110         /* Advance to the next non-empty css_set */
4111         do {
4112                 cset = css_task_iter_next_css_set(it);
4113                 if (!cset) {
4114                         it->task_pos = NULL;
4115                         return;
4116                 }
4117         } while (!css_set_populated(cset) && list_empty(&cset->dying_tasks));
4118
4119         if (!list_empty(&cset->tasks)) {
4120                 it->task_pos = cset->tasks.next;
4121                 it->cur_tasks_head = &cset->tasks;
4122         } else if (!list_empty(&cset->mg_tasks)) {
4123                 it->task_pos = cset->mg_tasks.next;
4124                 it->cur_tasks_head = &cset->mg_tasks;
4125         } else {
4126                 it->task_pos = cset->dying_tasks.next;
4127                 it->cur_tasks_head = &cset->dying_tasks;
4128         }
4129
4130         it->tasks_head = &cset->tasks;
4131         it->mg_tasks_head = &cset->mg_tasks;
4132         it->dying_tasks_head = &cset->dying_tasks;
4133
4134         /*
4135          * We don't keep css_sets locked across iteration steps and thus
4136          * need to take steps to ensure that iteration can be resumed after
4137          * the lock is re-acquired.  Iteration is performed at two levels -
4138          * css_sets and tasks in them.
4139          *
4140          * Once created, a css_set never leaves its cgroup lists, so a
4141          * pinned css_set is guaranteed to stay put and we can resume
4142          * iteration afterwards.
4143          *
4144          * Tasks may leave @cset across iteration steps.  This is resolved
4145          * by registering each iterator with the css_set currently being
4146          * walked and making css_set_move_task() advance iterators whose
4147          * next task is leaving.
4148          */
4149         if (it->cur_cset) {
4150                 list_del(&it->iters_node);
4151                 put_css_set_locked(it->cur_cset);
4152         }
4153         get_css_set(cset);
4154         it->cur_cset = cset;
4155         list_add(&it->iters_node, &cset->task_iters);
4156 }
4157
4158 static void css_task_iter_skip(struct css_task_iter *it,
4159                                struct task_struct *task)
4160 {
4161         lockdep_assert_held(&css_set_lock);
4162
4163         if (it->task_pos == &task->cg_list) {
4164                 it->task_pos = it->task_pos->next;
4165                 it->flags |= CSS_TASK_ITER_SKIPPED;
4166         }
4167 }
4168
4169 static void css_task_iter_advance(struct css_task_iter *it)
4170 {
4171         struct task_struct *task;
4172
4173         lockdep_assert_held(&css_set_lock);
4174 repeat:
4175         if (it->task_pos) {
4176                 /*
4177                  * Advance iterator to find next entry.  cset->tasks is
4178                  * consumed first and then ->mg_tasks.  After ->mg_tasks,
4179                  * we move onto the next cset.
4180                  */
4181                 if (it->flags & CSS_TASK_ITER_SKIPPED)
4182                         it->flags &= ~CSS_TASK_ITER_SKIPPED;
4183                 else
4184                         it->task_pos = it->task_pos->next;
4185
4186                 if (it->task_pos == it->tasks_head) {
4187                         it->task_pos = it->mg_tasks_head->next;
4188                         it->cur_tasks_head = it->mg_tasks_head;
4189                 }
4190                 if (it->task_pos == it->mg_tasks_head) {
4191                         it->task_pos = it->dying_tasks_head->next;
4192                         it->cur_tasks_head = it->dying_tasks_head;
4193                 }
4194                 if (it->task_pos == it->dying_tasks_head)
4195                         css_task_iter_advance_css_set(it);
4196         } else {
4197                 /* called from start, proceed to the first cset */
4198                 css_task_iter_advance_css_set(it);
4199         }
4200
4201         if (!it->task_pos)
4202                 return;
4203
4204         task = list_entry(it->task_pos, struct task_struct, cg_list);
4205
4206         if (it->flags & CSS_TASK_ITER_PROCS) {
4207                 /* if PROCS, skip over tasks which aren't group leaders */
4208                 if (!thread_group_leader(task))
4209                         goto repeat;
4210
4211                 /* and dying leaders w/o live member threads */
4212                 if (it->cur_tasks_head == it->dying_tasks_head &&
4213                     !atomic_read(&task->signal->live))
4214                         goto repeat;
4215         } else {
4216                 /* skip all dying ones */
4217                 if (it->cur_tasks_head == it->dying_tasks_head)
4218                         goto repeat;
4219         }
4220 }
4221
4222 /**
4223  * css_task_iter_start - initiate task iteration
4224  * @css: the css to walk tasks of
4225  * @flags: CSS_TASK_ITER_* flags
4226  * @it: the task iterator to use
4227  *
4228  * Initiate iteration through the tasks of @css.  The caller can call
4229  * css_task_iter_next() to walk through the tasks until the function
4230  * returns NULL.  On completion of iteration, css_task_iter_end() must be
4231  * called.
4232  */
4233 void css_task_iter_start(struct cgroup_subsys_state *css, unsigned int flags,
4234                          struct css_task_iter *it)
4235 {
4236         /* no one should try to iterate before mounting cgroups */
4237         WARN_ON_ONCE(!use_task_css_set_links);
4238
4239         memset(it, 0, sizeof(*it));
4240
4241         spin_lock_irq(&css_set_lock);
4242
4243         it->ss = css->ss;
4244         it->flags = flags;
4245
4246         if (it->ss)
4247                 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
4248         else
4249                 it->cset_pos = &css->cgroup->cset_links;
4250
4251         it->cset_head = it->cset_pos;
4252
4253         css_task_iter_advance(it);
4254
4255         spin_unlock_irq(&css_set_lock);
4256 }
4257
4258 /**
4259  * css_task_iter_next - return the next task for the iterator
4260  * @it: the task iterator being iterated
4261  *
4262  * The "next" function for task iteration.  @it should have been
4263  * initialized via css_task_iter_start().  Returns NULL when the iteration
4264  * reaches the end.
4265  */
4266 struct task_struct *css_task_iter_next(struct css_task_iter *it)
4267 {
4268         if (it->cur_task) {
4269                 put_task_struct(it->cur_task);
4270                 it->cur_task = NULL;
4271         }
4272
4273         spin_lock_irq(&css_set_lock);
4274
4275         /* @it may be half-advanced by skips, finish advancing */
4276         if (it->flags & CSS_TASK_ITER_SKIPPED)
4277                 css_task_iter_advance(it);
4278
4279         if (it->task_pos) {
4280                 it->cur_task = list_entry(it->task_pos, struct task_struct,
4281                                           cg_list);
4282                 get_task_struct(it->cur_task);
4283                 css_task_iter_advance(it);
4284         }
4285
4286         spin_unlock_irq(&css_set_lock);
4287
4288         return it->cur_task;
4289 }
4290
4291 /**
4292  * css_task_iter_end - finish task iteration
4293  * @it: the task iterator to finish
4294  *
4295  * Finish task iteration started by css_task_iter_start().
4296  */
4297 void css_task_iter_end(struct css_task_iter *it)
4298 {
4299         if (it->cur_cset) {
4300                 spin_lock_irq(&css_set_lock);
4301                 list_del(&it->iters_node);
4302                 put_css_set_locked(it->cur_cset);
4303                 spin_unlock_irq(&css_set_lock);
4304         }
4305
4306         if (it->cur_dcset)
4307                 put_css_set(it->cur_dcset);
4308
4309         if (it->cur_task)
4310                 put_task_struct(it->cur_task);
4311 }
4312
4313 static void cgroup_procs_release(struct kernfs_open_file *of)
4314 {
4315         struct cgroup_file_ctx *ctx = of->priv;
4316
4317         if (ctx->procs.started)
4318                 css_task_iter_end(&ctx->procs.iter);
4319 }
4320
4321 static void *cgroup_procs_next(struct seq_file *s, void *v, loff_t *pos)
4322 {
4323         struct kernfs_open_file *of = s->private;
4324         struct cgroup_file_ctx *ctx = of->priv;
4325
4326         if (pos)
4327                 (*pos)++;
4328
4329         return css_task_iter_next(&ctx->procs.iter);
4330 }
4331
4332 static void *__cgroup_procs_start(struct seq_file *s, loff_t *pos,
4333                                   unsigned int iter_flags)
4334 {
4335         struct kernfs_open_file *of = s->private;
4336         struct cgroup *cgrp = seq_css(s)->cgroup;
4337         struct cgroup_file_ctx *ctx = of->priv;
4338         struct css_task_iter *it = &ctx->procs.iter;
4339
4340         /*
4341          * When a seq_file is seeked, it's always traversed sequentially
4342          * from position 0, so we can simply keep iterating on !0 *pos.
4343          */
4344         if (!ctx->procs.started) {
4345                 if (WARN_ON_ONCE((*pos)))
4346                         return ERR_PTR(-EINVAL);
4347                 css_task_iter_start(&cgrp->self, iter_flags, it);
4348                 ctx->procs.started = true;
4349         } else if (!(*pos)) {
4350                 css_task_iter_end(it);
4351                 css_task_iter_start(&cgrp->self, iter_flags, it);
4352         } else
4353                 return it->cur_task;
4354
4355         return cgroup_procs_next(s, NULL, NULL);
4356 }
4357
4358 static void *cgroup_procs_start(struct seq_file *s, loff_t *pos)
4359 {
4360         struct cgroup *cgrp = seq_css(s)->cgroup;
4361
4362         /*
4363          * All processes of a threaded subtree belong to the domain cgroup
4364          * of the subtree.  Only threads can be distributed across the
4365          * subtree.  Reject reads on cgroup.procs in the subtree proper.
4366          * They're always empty anyway.
4367          */
4368         if (cgroup_is_threaded(cgrp))
4369                 return ERR_PTR(-EOPNOTSUPP);
4370
4371         return __cgroup_procs_start(s, pos, CSS_TASK_ITER_PROCS |
4372                                             CSS_TASK_ITER_THREADED);
4373 }
4374
4375 static int cgroup_procs_show(struct seq_file *s, void *v)
4376 {
4377         seq_printf(s, "%d\n", task_pid_vnr(v));
4378         return 0;
4379 }
4380
4381 static int cgroup_procs_write_permission(struct cgroup *src_cgrp,
4382                                          struct cgroup *dst_cgrp,
4383                                          struct super_block *sb,
4384                                          struct cgroup_namespace *ns)
4385 {
4386         struct cgroup *com_cgrp = src_cgrp;
4387         struct inode *inode;
4388         int ret;
4389
4390         lockdep_assert_held(&cgroup_mutex);
4391
4392         /* find the common ancestor */
4393         while (!cgroup_is_descendant(dst_cgrp, com_cgrp))
4394                 com_cgrp = cgroup_parent(com_cgrp);
4395
4396         /* %current should be authorized to migrate to the common ancestor */
4397         inode = kernfs_get_inode(sb, com_cgrp->procs_file.kn);
4398         if (!inode)
4399                 return -ENOMEM;
4400
4401         ret = inode_permission(inode, MAY_WRITE);
4402         iput(inode);
4403         if (ret)
4404                 return ret;
4405
4406         /*
4407          * If namespaces are delegation boundaries, %current must be able
4408          * to see both source and destination cgroups from its namespace.
4409          */
4410         if ((cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE) &&
4411             (!cgroup_is_descendant(src_cgrp, ns->root_cset->dfl_cgrp) ||
4412              !cgroup_is_descendant(dst_cgrp, ns->root_cset->dfl_cgrp)))
4413                 return -ENOENT;
4414
4415         return 0;
4416 }
4417
4418 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
4419                                   char *buf, size_t nbytes, loff_t off)
4420 {
4421         struct cgroup_file_ctx *ctx = of->priv;
4422         struct cgroup *src_cgrp, *dst_cgrp;
4423         struct task_struct *task;
4424         const struct cred *saved_cred;
4425         ssize_t ret;
4426
4427         dst_cgrp = cgroup_kn_lock_live(of->kn, false);
4428         if (!dst_cgrp)
4429                 return -ENODEV;
4430
4431         task = cgroup_procs_write_start(buf, true);
4432         ret = PTR_ERR_OR_ZERO(task);
4433         if (ret)
4434                 goto out_unlock;
4435
4436         /* find the source cgroup */
4437         spin_lock_irq(&css_set_lock);
4438         src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
4439         spin_unlock_irq(&css_set_lock);
4440
4441         /*
4442          * Process and thread migrations follow same delegation rule. Check
4443          * permissions using the credentials from file open to protect against
4444          * inherited fd attacks.
4445          */
4446         saved_cred = override_creds(of->file->f_cred);
4447         ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp,
4448                                             of->file->f_path.dentry->d_sb,
4449                                             ctx->ns);
4450         revert_creds(saved_cred);
4451         if (ret)
4452                 goto out_finish;
4453
4454         ret = cgroup_attach_task(dst_cgrp, task, true);
4455
4456 out_finish:
4457         cgroup_procs_write_finish(task);
4458 out_unlock:
4459         cgroup_kn_unlock(of->kn);
4460
4461         return ret ?: nbytes;
4462 }
4463
4464 static void *cgroup_threads_start(struct seq_file *s, loff_t *pos)
4465 {
4466         return __cgroup_procs_start(s, pos, 0);
4467 }
4468
4469 static ssize_t cgroup_threads_write(struct kernfs_open_file *of,
4470                                     char *buf, size_t nbytes, loff_t off)
4471 {
4472         struct cgroup_file_ctx *ctx = of->priv;
4473         struct cgroup *src_cgrp, *dst_cgrp;
4474         struct task_struct *task;
4475         const struct cred *saved_cred;
4476         ssize_t ret;
4477
4478         buf = strstrip(buf);
4479
4480         dst_cgrp = cgroup_kn_lock_live(of->kn, false);
4481         if (!dst_cgrp)
4482                 return -ENODEV;
4483
4484         task = cgroup_procs_write_start(buf, false);
4485         ret = PTR_ERR_OR_ZERO(task);
4486         if (ret)
4487                 goto out_unlock;
4488
4489         /* find the source cgroup */
4490         spin_lock_irq(&css_set_lock);
4491         src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
4492         spin_unlock_irq(&css_set_lock);
4493
4494         /*
4495          * Process and thread migrations follow same delegation rule. Check
4496          * permissions using the credentials from file open to protect against
4497          * inherited fd attacks.
4498          */
4499         saved_cred = override_creds(of->file->f_cred);
4500         ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp,
4501                                             of->file->f_path.dentry->d_sb,
4502                                             ctx->ns);
4503         revert_creds(saved_cred);
4504         if (ret)
4505                 goto out_finish;
4506
4507         /* and must be contained in the same domain */
4508         ret = -EOPNOTSUPP;
4509         if (src_cgrp->dom_cgrp != dst_cgrp->dom_cgrp)
4510                 goto out_finish;
4511
4512         ret = cgroup_attach_task(dst_cgrp, task, false);
4513
4514 out_finish:
4515         cgroup_procs_write_finish(task);
4516 out_unlock:
4517         cgroup_kn_unlock(of->kn);
4518
4519         return ret ?: nbytes;
4520 }
4521
4522 /* cgroup core interface files for the default hierarchy */
4523 static struct cftype cgroup_base_files[] = {
4524         {
4525                 .name = "cgroup.type",
4526                 .flags = CFTYPE_NOT_ON_ROOT,
4527                 .seq_show = cgroup_type_show,
4528                 .write = cgroup_type_write,
4529         },
4530         {
4531                 .name = "cgroup.procs",
4532                 .flags = CFTYPE_NS_DELEGATABLE,
4533                 .file_offset = offsetof(struct cgroup, procs_file),
4534                 .release = cgroup_procs_release,
4535                 .seq_start = cgroup_procs_start,
4536                 .seq_next = cgroup_procs_next,
4537                 .seq_show = cgroup_procs_show,
4538                 .write = cgroup_procs_write,
4539         },
4540         {
4541                 .name = "cgroup.threads",
4542                 .release = cgroup_procs_release,
4543                 .seq_start = cgroup_threads_start,
4544                 .seq_next = cgroup_procs_next,
4545                 .seq_show = cgroup_procs_show,
4546                 .write = cgroup_threads_write,
4547         },
4548         {
4549                 .name = "cgroup.controllers",
4550                 .seq_show = cgroup_controllers_show,
4551         },
4552         {
4553                 .name = "cgroup.subtree_control",
4554                 .flags = CFTYPE_NS_DELEGATABLE,
4555                 .seq_show = cgroup_subtree_control_show,
4556                 .write = cgroup_subtree_control_write,
4557         },
4558         {
4559                 .name = "cgroup.events",
4560                 .flags = CFTYPE_NOT_ON_ROOT,
4561                 .file_offset = offsetof(struct cgroup, events_file),
4562                 .seq_show = cgroup_events_show,
4563         },
4564         {
4565                 .name = "cgroup.max.descendants",
4566                 .seq_show = cgroup_max_descendants_show,
4567                 .write = cgroup_max_descendants_write,
4568         },
4569         {
4570                 .name = "cgroup.max.depth",
4571                 .seq_show = cgroup_max_depth_show,
4572                 .write = cgroup_max_depth_write,
4573         },
4574         {
4575                 .name = "cgroup.stat",
4576                 .seq_show = cgroup_stat_show,
4577         },
4578         { }     /* terminate */
4579 };
4580
4581 /*
4582  * css destruction is four-stage process.
4583  *
4584  * 1. Destruction starts.  Killing of the percpu_ref is initiated.
4585  *    Implemented in kill_css().
4586  *
4587  * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4588  *    and thus css_tryget_online() is guaranteed to fail, the css can be
4589  *    offlined by invoking offline_css().  After offlining, the base ref is
4590  *    put.  Implemented in css_killed_work_fn().
4591  *
4592  * 3. When the percpu_ref reaches zero, the only possible remaining
4593  *    accessors are inside RCU read sections.  css_release() schedules the
4594  *    RCU callback.
4595  *
4596  * 4. After the grace period, the css can be freed.  Implemented in
4597  *    css_free_work_fn().
4598  *
4599  * It is actually hairier because both step 2 and 4 require process context
4600  * and thus involve punting to css->destroy_work adding two additional
4601  * steps to the already complex sequence.
4602  */
4603 static void css_free_work_fn(struct work_struct *work)
4604 {
4605         struct cgroup_subsys_state *css =
4606                 container_of(work, struct cgroup_subsys_state, destroy_work);
4607         struct cgroup_subsys *ss = css->ss;
4608         struct cgroup *cgrp = css->cgroup;
4609
4610         percpu_ref_exit(&css->refcnt);
4611
4612         if (ss) {
4613                 /* css free path */
4614                 struct cgroup_subsys_state *parent = css->parent;
4615                 int id = css->id;
4616
4617                 ss->css_free(css);
4618                 cgroup_idr_remove(&ss->css_idr, id);
4619                 cgroup_put(cgrp);
4620
4621                 if (parent)
4622                         css_put(parent);
4623         } else {
4624                 /* cgroup free path */
4625                 atomic_dec(&cgrp->root->nr_cgrps);
4626                 cgroup1_pidlist_destroy_all(cgrp);
4627                 cancel_work_sync(&cgrp->release_agent_work);
4628
4629                 if (cgroup_parent(cgrp)) {
4630                         /*
4631                          * We get a ref to the parent, and put the ref when
4632                          * this cgroup is being freed, so it's guaranteed
4633                          * that the parent won't be destroyed before its
4634                          * children.
4635                          */
4636                         cgroup_put(cgroup_parent(cgrp));
4637                         kernfs_put(cgrp->kn);
4638                         kfree(cgrp);
4639                 } else {
4640                         /*
4641                          * This is root cgroup's refcnt reaching zero,
4642                          * which indicates that the root should be
4643                          * released.
4644                          */
4645                         cgroup_destroy_root(cgrp->root);
4646                 }
4647         }
4648 }
4649
4650 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4651 {
4652         struct cgroup_subsys_state *css =
4653                 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4654
4655         INIT_WORK(&css->destroy_work, css_free_work_fn);
4656         queue_work(cgroup_destroy_wq, &css->destroy_work);
4657 }
4658
4659 static void css_release_work_fn(struct work_struct *work)
4660 {
4661         struct cgroup_subsys_state *css =
4662                 container_of(work, struct cgroup_subsys_state, destroy_work);
4663         struct cgroup_subsys *ss = css->ss;
4664         struct cgroup *cgrp = css->cgroup;
4665
4666         mutex_lock(&cgroup_mutex);
4667
4668         css->flags |= CSS_RELEASED;
4669         list_del_rcu(&css->sibling);
4670
4671         if (ss) {
4672                 /* css release path */
4673                 cgroup_idr_replace(&ss->css_idr, NULL, css->id);
4674                 if (ss->css_released)
4675                         ss->css_released(css);
4676         } else {
4677                 struct cgroup *tcgrp;
4678
4679                 /* cgroup release path */
4680                 trace_cgroup_release(cgrp);
4681
4682                 spin_lock_irq(&css_set_lock);
4683                 for (tcgrp = cgroup_parent(cgrp); tcgrp;
4684                      tcgrp = cgroup_parent(tcgrp))
4685                         tcgrp->nr_dying_descendants--;
4686                 spin_unlock_irq(&css_set_lock);
4687
4688                 cgroup_idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4689                 cgrp->id = -1;
4690
4691                 /*
4692                  * There are two control paths which try to determine
4693                  * cgroup from dentry without going through kernfs -
4694                  * cgroupstats_build() and css_tryget_online_from_dir().
4695                  * Those are supported by RCU protecting clearing of
4696                  * cgrp->kn->priv backpointer.
4697                  */
4698                 if (cgrp->kn)
4699                         RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv,
4700                                          NULL);
4701
4702                 cgroup_bpf_put(cgrp);
4703         }
4704
4705         mutex_unlock(&cgroup_mutex);
4706
4707         call_rcu(&css->rcu_head, css_free_rcu_fn);
4708 }
4709
4710 static void css_release(struct percpu_ref *ref)
4711 {
4712         struct cgroup_subsys_state *css =
4713                 container_of(ref, struct cgroup_subsys_state, refcnt);
4714
4715         INIT_WORK(&css->destroy_work, css_release_work_fn);
4716         queue_work(cgroup_destroy_wq, &css->destroy_work);
4717 }
4718
4719 static void init_and_link_css(struct cgroup_subsys_state *css,
4720                               struct cgroup_subsys *ss, struct cgroup *cgrp)
4721 {
4722         lockdep_assert_held(&cgroup_mutex);
4723
4724         cgroup_get_live(cgrp);
4725
4726         memset(css, 0, sizeof(*css));
4727         css->cgroup = cgrp;
4728         css->ss = ss;
4729         css->id = -1;
4730         INIT_LIST_HEAD(&css->sibling);
4731         INIT_LIST_HEAD(&css->children);
4732         css->serial_nr = css_serial_nr_next++;
4733         atomic_set(&css->online_cnt, 0);
4734
4735         if (cgroup_parent(cgrp)) {
4736                 css->parent = cgroup_css(cgroup_parent(cgrp), ss);
4737                 css_get(css->parent);
4738         }
4739
4740         BUG_ON(cgroup_css(cgrp, ss));
4741 }
4742
4743 /* invoke ->css_online() on a new CSS and mark it online if successful */
4744 static int online_css(struct cgroup_subsys_state *css)
4745 {
4746         struct cgroup_subsys *ss = css->ss;
4747         int ret = 0;
4748
4749         lockdep_assert_held(&cgroup_mutex);
4750
4751         if (ss->css_online)
4752                 ret = ss->css_online(css);
4753         if (!ret) {
4754                 css->flags |= CSS_ONLINE;
4755                 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
4756
4757                 atomic_inc(&css->online_cnt);
4758                 if (css->parent)
4759                         atomic_inc(&css->parent->online_cnt);
4760         }
4761         return ret;
4762 }
4763
4764 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4765 static void offline_css(struct cgroup_subsys_state *css)
4766 {
4767         struct cgroup_subsys *ss = css->ss;
4768
4769         lockdep_assert_held(&cgroup_mutex);
4770
4771         if (!(css->flags & CSS_ONLINE))
4772                 return;
4773
4774         if (ss->css_offline)
4775                 ss->css_offline(css);
4776
4777         css->flags &= ~CSS_ONLINE;
4778         RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
4779
4780         wake_up_all(&css->cgroup->offline_waitq);
4781 }
4782
4783 /**
4784  * css_create - create a cgroup_subsys_state
4785  * @cgrp: the cgroup new css will be associated with
4786  * @ss: the subsys of new css
4787  *
4788  * Create a new css associated with @cgrp - @ss pair.  On success, the new
4789  * css is online and installed in @cgrp.  This function doesn't create the
4790  * interface files.  Returns 0 on success, -errno on failure.
4791  */
4792 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
4793                                               struct cgroup_subsys *ss)
4794 {
4795         struct cgroup *parent = cgroup_parent(cgrp);
4796         struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
4797         struct cgroup_subsys_state *css;
4798         int err;
4799
4800         lockdep_assert_held(&cgroup_mutex);
4801
4802         css = ss->css_alloc(parent_css);
4803         if (!css)
4804                 css = ERR_PTR(-ENOMEM);
4805         if (IS_ERR(css))
4806                 return css;
4807
4808         init_and_link_css(css, ss, cgrp);
4809
4810         err = percpu_ref_init(&css->refcnt, css_release, 0, GFP_KERNEL);
4811         if (err)
4812                 goto err_free_css;
4813
4814         err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_KERNEL);
4815         if (err < 0)
4816                 goto err_free_css;
4817         css->id = err;
4818
4819         /* @css is ready to be brought online now, make it visible */
4820         list_add_tail_rcu(&css->sibling, &parent_css->children);
4821         cgroup_idr_replace(&ss->css_idr, css, css->id);
4822
4823         err = online_css(css);
4824         if (err)
4825                 goto err_list_del;
4826
4827         if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4828             cgroup_parent(parent)) {
4829                 pr_warn("%s (%d) created nested cgroup for controller \"%s\" which has incomplete hierarchy support. Nested cgroups may change behavior in the future.\n",
4830                         current->comm, current->pid, ss->name);
4831                 if (!strcmp(ss->name, "memory"))
4832                         pr_warn("\"memory\" requires setting use_hierarchy to 1 on the root\n");
4833                 ss->warned_broken_hierarchy = true;
4834         }
4835
4836         return css;
4837
4838 err_list_del:
4839         list_del_rcu(&css->sibling);
4840 err_free_css:
4841         call_rcu(&css->rcu_head, css_free_rcu_fn);
4842         return ERR_PTR(err);
4843 }
4844
4845 /*
4846  * The returned cgroup is fully initialized including its control mask, but
4847  * it isn't associated with its kernfs_node and doesn't have the control
4848  * mask applied.
4849  */
4850 static struct cgroup *cgroup_create(struct cgroup *parent)
4851 {
4852         struct cgroup_root *root = parent->root;
4853         struct cgroup *cgrp, *tcgrp;
4854         int level = parent->level + 1;
4855         int ret;
4856
4857         /* allocate the cgroup and its ID, 0 is reserved for the root */
4858         cgrp = kzalloc(sizeof(*cgrp) +
4859                        sizeof(cgrp->ancestor_ids[0]) * (level + 1), GFP_KERNEL);
4860         if (!cgrp)
4861                 return ERR_PTR(-ENOMEM);
4862
4863         ret = percpu_ref_init(&cgrp->self.refcnt, css_release, 0, GFP_KERNEL);
4864         if (ret)
4865                 goto out_free_cgrp;
4866
4867         /*
4868          * Temporarily set the pointer to NULL, so idr_find() won't return
4869          * a half-baked cgroup.
4870          */
4871         cgrp->id = cgroup_idr_alloc(&root->cgroup_idr, NULL, 2, 0, GFP_KERNEL);
4872         if (cgrp->id < 0) {
4873                 ret = -ENOMEM;
4874                 goto out_cancel_ref;
4875         }
4876
4877         init_cgroup_housekeeping(cgrp);
4878
4879         cgrp->self.parent = &parent->self;
4880         cgrp->root = root;
4881         cgrp->level = level;
4882
4883         spin_lock_irq(&css_set_lock);
4884         for (tcgrp = cgrp; tcgrp; tcgrp = cgroup_parent(tcgrp)) {
4885                 cgrp->ancestor_ids[tcgrp->level] = tcgrp->id;
4886
4887                 if (tcgrp != cgrp)
4888                         tcgrp->nr_descendants++;
4889         }
4890         spin_unlock_irq(&css_set_lock);
4891
4892         if (notify_on_release(parent))
4893                 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4894
4895         if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4896                 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4897
4898         cgrp->self.serial_nr = css_serial_nr_next++;
4899
4900         /* allocation complete, commit to creation */
4901         list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
4902         atomic_inc(&root->nr_cgrps);
4903         cgroup_get_live(parent);
4904
4905         /*
4906          * @cgrp is now fully operational.  If something fails after this
4907          * point, it'll be released via the normal destruction path.
4908          */
4909         cgroup_idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4910
4911         /*
4912          * On the default hierarchy, a child doesn't automatically inherit
4913          * subtree_control from the parent.  Each is configured manually.
4914          */
4915         if (!cgroup_on_dfl(cgrp))
4916                 cgrp->subtree_control = cgroup_control(cgrp);
4917
4918         if (parent)
4919                 cgroup_bpf_inherit(cgrp, parent);
4920
4921         cgroup_propagate_control(cgrp);
4922
4923         return cgrp;
4924
4925 out_cancel_ref:
4926         percpu_ref_exit(&cgrp->self.refcnt);
4927 out_free_cgrp:
4928         kfree(cgrp);
4929         return ERR_PTR(ret);
4930 }
4931
4932 static bool cgroup_check_hierarchy_limits(struct cgroup *parent)
4933 {
4934         struct cgroup *cgroup;
4935         int ret = false;
4936         int level = 1;
4937
4938         lockdep_assert_held(&cgroup_mutex);
4939
4940         for (cgroup = parent; cgroup; cgroup = cgroup_parent(cgroup)) {
4941                 if (cgroup->nr_descendants >= cgroup->max_descendants)
4942                         goto fail;
4943
4944                 if (level > cgroup->max_depth)
4945                         goto fail;
4946
4947                 level++;
4948         }
4949
4950         ret = true;
4951 fail:
4952         return ret;
4953 }
4954
4955 int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name, umode_t mode)
4956 {
4957         struct cgroup *parent, *cgrp;
4958         struct kernfs_node *kn;
4959         int ret;
4960
4961         /* do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable */
4962         if (strchr(name, '\n'))
4963                 return -EINVAL;
4964
4965         parent = cgroup_kn_lock_live(parent_kn, false);
4966         if (!parent)
4967                 return -ENODEV;
4968
4969         if (!cgroup_check_hierarchy_limits(parent)) {
4970                 ret = -EAGAIN;
4971                 goto out_unlock;
4972         }
4973
4974         cgrp = cgroup_create(parent);
4975         if (IS_ERR(cgrp)) {
4976                 ret = PTR_ERR(cgrp);
4977                 goto out_unlock;
4978         }
4979
4980         /* create the directory */
4981         kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
4982         if (IS_ERR(kn)) {
4983                 ret = PTR_ERR(kn);
4984                 goto out_destroy;
4985         }
4986         cgrp->kn = kn;
4987
4988         /*
4989          * This extra ref will be put in cgroup_free_fn() and guarantees
4990          * that @cgrp->kn is always accessible.
4991          */
4992         kernfs_get(kn);
4993
4994         ret = cgroup_kn_set_ugid(kn);
4995         if (ret)
4996                 goto out_destroy;
4997
4998         ret = css_populate_dir(&cgrp->self);
4999         if (ret)
5000                 goto out_destroy;
5001
5002         ret = cgroup_apply_control_enable(cgrp);
5003         if (ret)
5004                 goto out_destroy;
5005
5006         trace_cgroup_mkdir(cgrp);
5007
5008         /* let's create and online css's */
5009         kernfs_activate(kn);
5010
5011         ret = 0;
5012         goto out_unlock;
5013
5014 out_destroy:
5015         cgroup_destroy_locked(cgrp);
5016 out_unlock:
5017         cgroup_kn_unlock(parent_kn);
5018         return ret;
5019 }
5020
5021 /*
5022  * This is called when the refcnt of a css is confirmed to be killed.
5023  * css_tryget_online() is now guaranteed to fail.  Tell the subsystem to
5024  * initate destruction and put the css ref from kill_css().
5025  */
5026 static void css_killed_work_fn(struct work_struct *work)
5027 {
5028         struct cgroup_subsys_state *css =
5029                 container_of(work, struct cgroup_subsys_state, destroy_work);
5030
5031         mutex_lock(&cgroup_mutex);
5032
5033         do {
5034                 offline_css(css);
5035                 css_put(css);
5036                 /* @css can't go away while we're holding cgroup_mutex */
5037                 css = css->parent;
5038         } while (css && atomic_dec_and_test(&css->online_cnt));
5039
5040         mutex_unlock(&cgroup_mutex);
5041 }
5042
5043 /* css kill confirmation processing requires process context, bounce */
5044 static void css_killed_ref_fn(struct percpu_ref *ref)
5045 {
5046         struct cgroup_subsys_state *css =
5047                 container_of(ref, struct cgroup_subsys_state, refcnt);
5048
5049         if (atomic_dec_and_test(&css->online_cnt)) {
5050                 INIT_WORK(&css->destroy_work, css_killed_work_fn);
5051                 queue_work(cgroup_destroy_wq, &css->destroy_work);
5052         }
5053 }
5054
5055 /**
5056  * kill_css - destroy a css
5057  * @css: css to destroy
5058  *
5059  * This function initiates destruction of @css by removing cgroup interface
5060  * files and putting its base reference.  ->css_offline() will be invoked
5061  * asynchronously once css_tryget_online() is guaranteed to fail and when
5062  * the reference count reaches zero, @css will be released.
5063  */
5064 static void kill_css(struct cgroup_subsys_state *css)
5065 {
5066         lockdep_assert_held(&cgroup_mutex);
5067
5068         if (css->flags & CSS_DYING)
5069                 return;
5070
5071         css->flags |= CSS_DYING;
5072
5073         /*
5074          * This must happen before css is disassociated with its cgroup.
5075          * See seq_css() for details.
5076          */
5077         css_clear_dir(css);
5078
5079         /*
5080          * Killing would put the base ref, but we need to keep it alive
5081          * until after ->css_offline().
5082          */
5083         css_get(css);
5084
5085         /*
5086          * cgroup core guarantees that, by the time ->css_offline() is
5087          * invoked, no new css reference will be given out via
5088          * css_tryget_online().  We can't simply call percpu_ref_kill() and
5089          * proceed to offlining css's because percpu_ref_kill() doesn't
5090          * guarantee that the ref is seen as killed on all CPUs on return.
5091          *
5092          * Use percpu_ref_kill_and_confirm() to get notifications as each
5093          * css is confirmed to be seen as killed on all CPUs.
5094          */
5095         percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
5096 }
5097
5098 /**
5099  * cgroup_destroy_locked - the first stage of cgroup destruction
5100  * @cgrp: cgroup to be destroyed
5101  *
5102  * css's make use of percpu refcnts whose killing latency shouldn't be
5103  * exposed to userland and are RCU protected.  Also, cgroup core needs to
5104  * guarantee that css_tryget_online() won't succeed by the time
5105  * ->css_offline() is invoked.  To satisfy all the requirements,
5106  * destruction is implemented in the following two steps.
5107  *
5108  * s1. Verify @cgrp can be destroyed and mark it dying.  Remove all
5109  *     userland visible parts and start killing the percpu refcnts of
5110  *     css's.  Set up so that the next stage will be kicked off once all
5111  *     the percpu refcnts are confirmed to be killed.
5112  *
5113  * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
5114  *     rest of destruction.  Once all cgroup references are gone, the
5115  *     cgroup is RCU-freed.
5116  *
5117  * This function implements s1.  After this step, @cgrp is gone as far as
5118  * the userland is concerned and a new cgroup with the same name may be
5119  * created.  As cgroup doesn't care about the names internally, this
5120  * doesn't cause any problem.
5121  */
5122 static int cgroup_destroy_locked(struct cgroup *cgrp)
5123         __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
5124 {
5125         struct cgroup *tcgrp, *parent = cgroup_parent(cgrp);
5126         struct cgroup_subsys_state *css;
5127         struct cgrp_cset_link *link;
5128         int ssid;
5129
5130         lockdep_assert_held(&cgroup_mutex);
5131
5132         /*
5133          * Only migration can raise populated from zero and we're already
5134          * holding cgroup_mutex.
5135          */
5136         if (cgroup_is_populated(cgrp))
5137                 return -EBUSY;
5138
5139         /*
5140          * Make sure there's no live children.  We can't test emptiness of
5141          * ->self.children as dead children linger on it while being
5142          * drained; otherwise, "rmdir parent/child parent" may fail.
5143          */
5144         if (css_has_online_children(&cgrp->self))
5145                 return -EBUSY;
5146
5147         /*
5148          * Mark @cgrp and the associated csets dead.  The former prevents
5149          * further task migration and child creation by disabling
5150          * cgroup_lock_live_group().  The latter makes the csets ignored by
5151          * the migration path.
5152          */
5153         cgrp->self.flags &= ~CSS_ONLINE;
5154
5155         spin_lock_irq(&css_set_lock);
5156         list_for_each_entry(link, &cgrp->cset_links, cset_link)
5157                 link->cset->dead = true;
5158         spin_unlock_irq(&css_set_lock);
5159
5160         /* initiate massacre of all css's */
5161         for_each_css(css, ssid, cgrp)
5162                 kill_css(css);
5163
5164         /*
5165          * Remove @cgrp directory along with the base files.  @cgrp has an
5166          * extra ref on its kn.
5167          */
5168         kernfs_remove(cgrp->kn);
5169
5170         if (parent && cgroup_is_threaded(cgrp))
5171                 parent->nr_threaded_children--;
5172
5173         spin_lock_irq(&css_set_lock);
5174         for (tcgrp = cgroup_parent(cgrp); tcgrp; tcgrp = cgroup_parent(tcgrp)) {
5175                 tcgrp->nr_descendants--;
5176                 tcgrp->nr_dying_descendants++;
5177         }
5178         spin_unlock_irq(&css_set_lock);
5179
5180         cgroup1_check_for_release(parent);
5181
5182         /* put the base reference */
5183         percpu_ref_kill(&cgrp->self.refcnt);
5184
5185         return 0;
5186 };
5187
5188 int cgroup_rmdir(struct kernfs_node *kn)
5189 {
5190         struct cgroup *cgrp;
5191         int ret = 0;
5192
5193         cgrp = cgroup_kn_lock_live(kn, false);
5194         if (!cgrp)
5195                 return 0;
5196
5197         ret = cgroup_destroy_locked(cgrp);
5198
5199         if (!ret)
5200                 trace_cgroup_rmdir(cgrp);
5201
5202         cgroup_kn_unlock(kn);
5203         return ret;
5204 }
5205
5206 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
5207         .show_options           = cgroup_show_options,
5208         .remount_fs             = cgroup_remount,
5209         .mkdir                  = cgroup_mkdir,
5210         .rmdir                  = cgroup_rmdir,
5211         .show_path              = cgroup_show_path,
5212 };
5213
5214 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
5215 {
5216         struct cgroup_subsys_state *css;
5217
5218         pr_debug("Initializing cgroup subsys %s\n", ss->name);
5219
5220         mutex_lock(&cgroup_mutex);
5221
5222         idr_init(&ss->css_idr);
5223         INIT_LIST_HEAD(&ss->cfts);
5224
5225         /* Create the root cgroup state for this subsystem */
5226         ss->root = &cgrp_dfl_root;
5227         css = ss->css_alloc(cgroup_css(&cgrp_dfl_root.cgrp, ss));
5228         /* We don't handle early failures gracefully */
5229         BUG_ON(IS_ERR(css));
5230         init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
5231
5232         /*
5233          * Root csses are never destroyed and we can't initialize
5234          * percpu_ref during early init.  Disable refcnting.
5235          */
5236         css->flags |= CSS_NO_REF;
5237
5238         if (early) {
5239                 /* allocation can't be done safely during early init */
5240                 css->id = 1;
5241         } else {
5242                 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
5243                 BUG_ON(css->id < 0);
5244         }
5245
5246         /* Update the init_css_set to contain a subsys
5247          * pointer to this state - since the subsystem is
5248          * newly registered, all tasks and hence the
5249          * init_css_set is in the subsystem's root cgroup. */
5250         init_css_set.subsys[ss->id] = css;
5251
5252         have_fork_callback |= (bool)ss->fork << ss->id;
5253         have_exit_callback |= (bool)ss->exit << ss->id;
5254         have_release_callback |= (bool)ss->release << ss->id;
5255         have_canfork_callback |= (bool)ss->can_fork << ss->id;
5256
5257         /* At system boot, before all subsystems have been
5258          * registered, no tasks have been forked, so we don't
5259          * need to invoke fork callbacks here. */
5260         BUG_ON(!list_empty(&init_task.tasks));
5261
5262         BUG_ON(online_css(css));
5263
5264         mutex_unlock(&cgroup_mutex);
5265 }
5266
5267 /**
5268  * cgroup_init_early - cgroup initialization at system boot
5269  *
5270  * Initialize cgroups at system boot, and initialize any
5271  * subsystems that request early init.
5272  */
5273 int __init cgroup_init_early(void)
5274 {
5275         static struct cgroup_sb_opts __initdata opts;
5276         struct cgroup_subsys *ss;
5277         int i;
5278
5279         init_cgroup_root(&cgrp_dfl_root, &opts);
5280         cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
5281
5282         RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
5283
5284         for_each_subsys(ss, i) {
5285                 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
5286                      "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p id:name=%d:%s\n",
5287                      i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
5288                      ss->id, ss->name);
5289                 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
5290                      "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
5291
5292                 ss->id = i;
5293                 ss->name = cgroup_subsys_name[i];
5294                 if (!ss->legacy_name)
5295                         ss->legacy_name = cgroup_subsys_name[i];
5296
5297                 if (ss->early_init)
5298                         cgroup_init_subsys(ss, true);
5299         }
5300         return 0;
5301 }
5302
5303 /**
5304  * cgroup_init - cgroup initialization
5305  *
5306  * Register cgroup filesystem and /proc file, and initialize
5307  * any subsystems that didn't request early init.
5308  */
5309 int __init cgroup_init(void)
5310 {
5311         struct cgroup_subsys *ss;
5312         int ssid;
5313
5314         BUILD_BUG_ON(CGROUP_SUBSYS_COUNT > 16);
5315         BUG_ON(percpu_init_rwsem(&cgroup_threadgroup_rwsem));
5316         BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
5317         BUG_ON(cgroup_init_cftypes(NULL, cgroup1_base_files));
5318
5319         /*
5320          * The latency of the synchronize_sched() is too high for cgroups,
5321          * avoid it at the cost of forcing all readers into the slow path.
5322          */
5323         rcu_sync_enter_start(&cgroup_threadgroup_rwsem.rss);
5324
5325         get_user_ns(init_cgroup_ns.user_ns);
5326
5327         mutex_lock(&cgroup_mutex);
5328
5329         /*
5330          * Add init_css_set to the hash table so that dfl_root can link to
5331          * it during init.
5332          */
5333         hash_add(css_set_table, &init_css_set.hlist,
5334                  css_set_hash(init_css_set.subsys));
5335
5336         BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0, 0));
5337
5338         mutex_unlock(&cgroup_mutex);
5339
5340         for_each_subsys(ss, ssid) {
5341                 if (ss->early_init) {
5342                         struct cgroup_subsys_state *css =
5343                                 init_css_set.subsys[ss->id];
5344
5345                         css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
5346                                                    GFP_KERNEL);
5347                         BUG_ON(css->id < 0);
5348                 } else {
5349                         cgroup_init_subsys(ss, false);
5350                 }
5351
5352                 list_add_tail(&init_css_set.e_cset_node[ssid],
5353                               &cgrp_dfl_root.cgrp.e_csets[ssid]);
5354
5355                 /*
5356                  * Setting dfl_root subsys_mask needs to consider the
5357                  * disabled flag and cftype registration needs kmalloc,
5358                  * both of which aren't available during early_init.
5359                  */
5360                 if (!cgroup_ssid_enabled(ssid))
5361                         continue;
5362
5363                 if (cgroup1_ssid_disabled(ssid))
5364                         printk(KERN_INFO "Disabling %s control group subsystem in v1 mounts\n",
5365                                ss->name);
5366
5367                 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
5368
5369                 /* implicit controllers must be threaded too */
5370                 WARN_ON(ss->implicit_on_dfl && !ss->threaded);
5371
5372                 if (ss->implicit_on_dfl)
5373                         cgrp_dfl_implicit_ss_mask |= 1 << ss->id;
5374                 else if (!ss->dfl_cftypes)
5375                         cgrp_dfl_inhibit_ss_mask |= 1 << ss->id;
5376
5377                 if (ss->threaded)
5378                         cgrp_dfl_threaded_ss_mask |= 1 << ss->id;
5379
5380                 if (ss->dfl_cftypes == ss->legacy_cftypes) {
5381                         WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes));
5382                 } else {
5383                         WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes));
5384                         WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes));
5385                 }
5386
5387                 if (ss->bind)
5388                         ss->bind(init_css_set.subsys[ssid]);
5389
5390                 mutex_lock(&cgroup_mutex);
5391                 css_populate_dir(init_css_set.subsys[ssid]);
5392                 mutex_unlock(&cgroup_mutex);
5393         }
5394
5395         /* init_css_set.subsys[] has been updated, re-hash */
5396         hash_del(&init_css_set.hlist);
5397         hash_add(css_set_table, &init_css_set.hlist,
5398                  css_set_hash(init_css_set.subsys));
5399
5400         WARN_ON(sysfs_create_mount_point(fs_kobj, "cgroup"));
5401         WARN_ON(register_filesystem(&cgroup_fs_type));
5402         WARN_ON(register_filesystem(&cgroup2_fs_type));
5403         WARN_ON(!proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations));
5404
5405         return 0;
5406 }
5407
5408 static int __init cgroup_wq_init(void)
5409 {
5410         /*
5411          * There isn't much point in executing destruction path in
5412          * parallel.  Good chunk is serialized with cgroup_mutex anyway.
5413          * Use 1 for @max_active.
5414          *
5415          * We would prefer to do this in cgroup_init() above, but that
5416          * is called before init_workqueues(): so leave this until after.
5417          */
5418         cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
5419         BUG_ON(!cgroup_destroy_wq);
5420         return 0;
5421 }
5422 core_initcall(cgroup_wq_init);
5423
5424 void cgroup_path_from_kernfs_id(const union kernfs_node_id *id,
5425                                         char *buf, size_t buflen)
5426 {
5427         struct kernfs_node *kn;
5428
5429         kn = kernfs_get_node_by_id(cgrp_dfl_root.kf_root, id);
5430         if (!kn)
5431                 return;
5432         kernfs_path(kn, buf, buflen);
5433         kernfs_put(kn);
5434 }
5435
5436 /*
5437  * proc_cgroup_show()
5438  *  - Print task's cgroup paths into seq_file, one line for each hierarchy
5439  *  - Used for /proc/<pid>/cgroup.
5440  */
5441 int proc_cgroup_show(struct seq_file *m, struct pid_namespace *ns,
5442                      struct pid *pid, struct task_struct *tsk)
5443 {
5444         char *buf;
5445         int retval;
5446         struct cgroup_root *root;
5447
5448         retval = -ENOMEM;
5449         buf = kmalloc(PATH_MAX, GFP_KERNEL);
5450         if (!buf)
5451                 goto out;
5452
5453         mutex_lock(&cgroup_mutex);
5454         spin_lock_irq(&css_set_lock);
5455
5456         for_each_root(root) {
5457                 struct cgroup_subsys *ss;
5458                 struct cgroup *cgrp;
5459                 int ssid, count = 0;
5460
5461                 if (root == &cgrp_dfl_root && !cgrp_dfl_visible)
5462                         continue;
5463
5464                 seq_printf(m, "%d:", root->hierarchy_id);
5465                 if (root != &cgrp_dfl_root)
5466                         for_each_subsys(ss, ssid)
5467                                 if (root->subsys_mask & (1 << ssid))
5468                                         seq_printf(m, "%s%s", count++ ? "," : "",
5469                                                    ss->legacy_name);
5470                 if (strlen(root->name))
5471                         seq_printf(m, "%sname=%s", count ? "," : "",
5472                                    root->name);
5473                 seq_putc(m, ':');
5474
5475                 cgrp = task_cgroup_from_root(tsk, root);
5476
5477                 /*
5478                  * On traditional hierarchies, all zombie tasks show up as
5479                  * belonging to the root cgroup.  On the default hierarchy,
5480                  * while a zombie doesn't show up in "cgroup.procs" and
5481                  * thus can't be migrated, its /proc/PID/cgroup keeps
5482                  * reporting the cgroup it belonged to before exiting.  If
5483                  * the cgroup is removed before the zombie is reaped,
5484                  * " (deleted)" is appended to the cgroup path.
5485                  */
5486                 if (cgroup_on_dfl(cgrp) || !(tsk->flags & PF_EXITING)) {
5487                         retval = cgroup_path_ns_locked(cgrp, buf, PATH_MAX,
5488                                                 current->nsproxy->cgroup_ns);
5489                         if (retval >= PATH_MAX)
5490                                 retval = -ENAMETOOLONG;
5491                         if (retval < 0)
5492                                 goto out_unlock;
5493
5494                         seq_puts(m, buf);
5495                 } else {
5496                         seq_puts(m, "/");
5497                 }
5498
5499                 if (cgroup_on_dfl(cgrp) && cgroup_is_dead(cgrp))
5500                         seq_puts(m, " (deleted)\n");
5501                 else
5502                         seq_putc(m, '\n');
5503         }
5504
5505         retval = 0;
5506 out_unlock:
5507         spin_unlock_irq(&css_set_lock);
5508         mutex_unlock(&cgroup_mutex);
5509         kfree(buf);
5510 out:
5511         return retval;
5512 }
5513
5514 /**
5515  * cgroup_fork - initialize cgroup related fields during copy_process()
5516  * @child: pointer to task_struct of forking parent process.
5517  *
5518  * A task is associated with the init_css_set until cgroup_post_fork()
5519  * attaches it to the parent's css_set.  Empty cg_list indicates that
5520  * @child isn't holding reference to its css_set.
5521  */
5522 void cgroup_fork(struct task_struct *child)
5523 {
5524         RCU_INIT_POINTER(child->cgroups, &init_css_set);
5525         INIT_LIST_HEAD(&child->cg_list);
5526 }
5527
5528 /**
5529  * cgroup_can_fork - called on a new task before the process is exposed
5530  * @child: the task in question.
5531  *
5532  * This calls the subsystem can_fork() callbacks. If the can_fork() callback
5533  * returns an error, the fork aborts with that error code. This allows for
5534  * a cgroup subsystem to conditionally allow or deny new forks.
5535  */
5536 int cgroup_can_fork(struct task_struct *child)
5537 {
5538         struct cgroup_subsys *ss;
5539         int i, j, ret;
5540
5541         do_each_subsys_mask(ss, i, have_canfork_callback) {
5542                 ret = ss->can_fork(child);
5543                 if (ret)
5544                         goto out_revert;
5545         } while_each_subsys_mask();
5546
5547         return 0;
5548
5549 out_revert:
5550         for_each_subsys(ss, j) {
5551                 if (j >= i)
5552                         break;
5553                 if (ss->cancel_fork)
5554                         ss->cancel_fork(child);
5555         }
5556
5557         return ret;
5558 }
5559
5560 /**
5561  * cgroup_cancel_fork - called if a fork failed after cgroup_can_fork()
5562  * @child: the task in question
5563  *
5564  * This calls the cancel_fork() callbacks if a fork failed *after*
5565  * cgroup_can_fork() succeded.
5566  */
5567 void cgroup_cancel_fork(struct task_struct *child)
5568 {
5569         struct cgroup_subsys *ss;
5570         int i;
5571
5572         for_each_subsys(ss, i)
5573                 if (ss->cancel_fork)
5574                         ss->cancel_fork(child);
5575 }
5576
5577 /**
5578  * cgroup_post_fork - called on a new task after adding it to the task list
5579  * @child: the task in question
5580  *
5581  * Adds the task to the list running through its css_set if necessary and
5582  * call the subsystem fork() callbacks.  Has to be after the task is
5583  * visible on the task list in case we race with the first call to
5584  * cgroup_task_iter_start() - to guarantee that the new task ends up on its
5585  * list.
5586  */
5587 void cgroup_post_fork(struct task_struct *child)
5588 {
5589         struct cgroup_subsys *ss;
5590         int i;
5591
5592         /*
5593          * This may race against cgroup_enable_task_cg_lists().  As that
5594          * function sets use_task_css_set_links before grabbing
5595          * tasklist_lock and we just went through tasklist_lock to add
5596          * @child, it's guaranteed that either we see the set
5597          * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
5598          * @child during its iteration.
5599          *
5600          * If we won the race, @child is associated with %current's
5601          * css_set.  Grabbing css_set_lock guarantees both that the
5602          * association is stable, and, on completion of the parent's
5603          * migration, @child is visible in the source of migration or
5604          * already in the destination cgroup.  This guarantee is necessary
5605          * when implementing operations which need to migrate all tasks of
5606          * a cgroup to another.
5607          *
5608          * Note that if we lose to cgroup_enable_task_cg_lists(), @child
5609          * will remain in init_css_set.  This is safe because all tasks are
5610          * in the init_css_set before cg_links is enabled and there's no
5611          * operation which transfers all tasks out of init_css_set.
5612          */
5613         if (use_task_css_set_links) {
5614                 struct css_set *cset;
5615
5616                 spin_lock_irq(&css_set_lock);
5617                 cset = task_css_set(current);
5618                 if (list_empty(&child->cg_list)) {
5619                         get_css_set(cset);
5620                         cset->nr_tasks++;
5621                         css_set_move_task(child, NULL, cset, false);
5622                 }
5623                 spin_unlock_irq(&css_set_lock);
5624         }
5625
5626         /*
5627          * Call ss->fork().  This must happen after @child is linked on
5628          * css_set; otherwise, @child might change state between ->fork()
5629          * and addition to css_set.
5630          */
5631         do_each_subsys_mask(ss, i, have_fork_callback) {
5632                 ss->fork(child);
5633         } while_each_subsys_mask();
5634 }
5635
5636 /**
5637  * cgroup_exit - detach cgroup from exiting task
5638  * @tsk: pointer to task_struct of exiting process
5639  *
5640  * Description: Detach cgroup from @tsk and release it.
5641  *
5642  * Note that cgroups marked notify_on_release force every task in
5643  * them to take the global cgroup_mutex mutex when exiting.
5644  * This could impact scaling on very large systems.  Be reluctant to
5645  * use notify_on_release cgroups where very high task exit scaling
5646  * is required on large systems.
5647  *
5648  * We set the exiting tasks cgroup to the root cgroup (top_cgroup).  We
5649  * call cgroup_exit() while the task is still competent to handle
5650  * notify_on_release(), then leave the task attached to the root cgroup in
5651  * each hierarchy for the remainder of its exit.  No need to bother with
5652  * init_css_set refcnting.  init_css_set never goes away and we can't race
5653  * with migration path - PF_EXITING is visible to migration path.
5654  */
5655 void cgroup_exit(struct task_struct *tsk)
5656 {
5657         struct cgroup_subsys *ss;
5658         struct css_set *cset;
5659         int i;
5660
5661         /*
5662          * Unlink from @tsk from its css_set.  As migration path can't race
5663          * with us, we can check css_set and cg_list without synchronization.
5664          */
5665         cset = task_css_set(tsk);
5666
5667         if (!list_empty(&tsk->cg_list)) {
5668                 spin_lock_irq(&css_set_lock);
5669                 css_set_move_task(tsk, cset, NULL, false);
5670                 list_add_tail(&tsk->cg_list, &cset->dying_tasks);
5671                 cset->nr_tasks--;
5672                 spin_unlock_irq(&css_set_lock);
5673         } else {
5674                 get_css_set(cset);
5675         }
5676
5677         /* see cgroup_post_fork() for details */
5678         do_each_subsys_mask(ss, i, have_exit_callback) {
5679                 ss->exit(tsk);
5680         } while_each_subsys_mask();
5681 }
5682
5683 void cgroup_release(struct task_struct *task)
5684 {
5685         struct cgroup_subsys *ss;
5686         int ssid;
5687
5688         do_each_subsys_mask(ss, ssid, have_release_callback) {
5689                 ss->release(task);
5690         } while_each_subsys_mask();
5691
5692         if (use_task_css_set_links) {
5693                 spin_lock_irq(&css_set_lock);
5694                 css_set_skip_task_iters(task_css_set(task), task);
5695                 list_del_init(&task->cg_list);
5696                 spin_unlock_irq(&css_set_lock);
5697         }
5698 }
5699
5700 void cgroup_free(struct task_struct *task)
5701 {
5702         struct css_set *cset = task_css_set(task);
5703         put_css_set(cset);
5704 }
5705
5706 static int __init cgroup_disable(char *str)
5707 {
5708         struct cgroup_subsys *ss;
5709         char *token;
5710         int i;
5711
5712         while ((token = strsep(&str, ",")) != NULL) {
5713                 if (!*token)
5714                         continue;
5715
5716                 for_each_subsys(ss, i) {
5717                         if (strcmp(token, ss->name) &&
5718                             strcmp(token, ss->legacy_name))
5719                                 continue;
5720
5721                         static_branch_disable(cgroup_subsys_enabled_key[i]);
5722                         pr_info("Disabling %s control group subsystem\n",
5723                                 ss->name);
5724                 }
5725         }
5726         return 1;
5727 }
5728 __setup("cgroup_disable=", cgroup_disable);
5729
5730 /**
5731  * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
5732  * @dentry: directory dentry of interest
5733  * @ss: subsystem of interest
5734  *
5735  * If @dentry is a directory for a cgroup which has @ss enabled on it, try
5736  * to get the corresponding css and return it.  If such css doesn't exist
5737  * or can't be pinned, an ERR_PTR value is returned.
5738  */
5739 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
5740                                                        struct cgroup_subsys *ss)
5741 {
5742         struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
5743         struct file_system_type *s_type = dentry->d_sb->s_type;
5744         struct cgroup_subsys_state *css = NULL;
5745         struct cgroup *cgrp;
5746
5747         /* is @dentry a cgroup dir? */
5748         if ((s_type != &cgroup_fs_type && s_type != &cgroup2_fs_type) ||
5749             !kn || kernfs_type(kn) != KERNFS_DIR)
5750                 return ERR_PTR(-EBADF);
5751
5752         rcu_read_lock();
5753
5754         /*
5755          * This path doesn't originate from kernfs and @kn could already
5756          * have been or be removed at any point.  @kn->priv is RCU
5757          * protected for this access.  See css_release_work_fn() for details.
5758          */
5759         cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
5760         if (cgrp)
5761                 css = cgroup_css(cgrp, ss);
5762
5763         if (!css || !css_tryget_online(css))
5764                 css = ERR_PTR(-ENOENT);
5765
5766         rcu_read_unlock();
5767         return css;
5768 }
5769
5770 /**
5771  * css_from_id - lookup css by id
5772  * @id: the cgroup id
5773  * @ss: cgroup subsys to be looked into
5774  *
5775  * Returns the css if there's valid one with @id, otherwise returns NULL.
5776  * Should be called under rcu_read_lock().
5777  */
5778 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5779 {
5780         WARN_ON_ONCE(!rcu_read_lock_held());
5781         return idr_find(&ss->css_idr, id);
5782 }
5783
5784 /**
5785  * cgroup_get_from_path - lookup and get a cgroup from its default hierarchy path
5786  * @path: path on the default hierarchy
5787  *
5788  * Find the cgroup at @path on the default hierarchy, increment its
5789  * reference count and return it.  Returns pointer to the found cgroup on
5790  * success, ERR_PTR(-ENOENT) if @path doens't exist and ERR_PTR(-ENOTDIR)
5791  * if @path points to a non-directory.
5792  */
5793 struct cgroup *cgroup_get_from_path(const char *path)
5794 {
5795         struct kernfs_node *kn;
5796         struct cgroup *cgrp;
5797
5798         mutex_lock(&cgroup_mutex);
5799
5800         kn = kernfs_walk_and_get(cgrp_dfl_root.cgrp.kn, path);
5801         if (kn) {
5802                 if (kernfs_type(kn) == KERNFS_DIR) {
5803                         cgrp = kn->priv;
5804                         cgroup_get_live(cgrp);
5805                 } else {
5806                         cgrp = ERR_PTR(-ENOTDIR);
5807                 }
5808                 kernfs_put(kn);
5809         } else {
5810                 cgrp = ERR_PTR(-ENOENT);
5811         }
5812
5813         mutex_unlock(&cgroup_mutex);
5814         return cgrp;
5815 }
5816 EXPORT_SYMBOL_GPL(cgroup_get_from_path);
5817
5818 /**
5819  * cgroup_get_from_fd - get a cgroup pointer from a fd
5820  * @fd: fd obtained by open(cgroup2_dir)
5821  *
5822  * Find the cgroup from a fd which should be obtained
5823  * by opening a cgroup directory.  Returns a pointer to the
5824  * cgroup on success. ERR_PTR is returned if the cgroup
5825  * cannot be found.
5826  */
5827 struct cgroup *cgroup_get_from_fd(int fd)
5828 {
5829         struct cgroup_subsys_state *css;
5830         struct cgroup *cgrp;
5831         struct file *f;
5832
5833         f = fget_raw(fd);
5834         if (!f)
5835                 return ERR_PTR(-EBADF);
5836
5837         css = css_tryget_online_from_dir(f->f_path.dentry, NULL);
5838         fput(f);
5839         if (IS_ERR(css))
5840                 return ERR_CAST(css);
5841
5842         cgrp = css->cgroup;
5843         if (!cgroup_on_dfl(cgrp)) {
5844                 cgroup_put(cgrp);
5845                 return ERR_PTR(-EBADF);
5846         }
5847
5848         return cgrp;
5849 }
5850 EXPORT_SYMBOL_GPL(cgroup_get_from_fd);
5851
5852 /*
5853  * sock->sk_cgrp_data handling.  For more info, see sock_cgroup_data
5854  * definition in cgroup-defs.h.
5855  */
5856 #ifdef CONFIG_SOCK_CGROUP_DATA
5857
5858 #if defined(CONFIG_CGROUP_NET_PRIO) || defined(CONFIG_CGROUP_NET_CLASSID)
5859
5860 DEFINE_SPINLOCK(cgroup_sk_update_lock);
5861 static bool cgroup_sk_alloc_disabled __read_mostly;
5862
5863 void cgroup_sk_alloc_disable(void)
5864 {
5865         if (cgroup_sk_alloc_disabled)
5866                 return;
5867         pr_info("cgroup: disabling cgroup2 socket matching due to net_prio or net_cls activation\n");
5868         cgroup_sk_alloc_disabled = true;
5869 }
5870
5871 #else
5872
5873 #define cgroup_sk_alloc_disabled        false
5874
5875 #endif
5876
5877 void cgroup_sk_alloc(struct sock_cgroup_data *skcd)
5878 {
5879         if (cgroup_sk_alloc_disabled) {
5880                 skcd->no_refcnt = 1;
5881                 return;
5882         }
5883
5884         /* Don't associate the sock with unrelated interrupted task's cgroup. */
5885         if (in_interrupt())
5886                 return;
5887
5888         rcu_read_lock();
5889
5890         while (true) {
5891                 struct css_set *cset;
5892
5893                 cset = task_css_set(current);
5894                 if (likely(cgroup_tryget(cset->dfl_cgrp))) {
5895                         skcd->val = (unsigned long)cset->dfl_cgrp;
5896                         break;
5897                 }
5898                 cpu_relax();
5899         }
5900
5901         rcu_read_unlock();
5902 }
5903
5904 void cgroup_sk_clone(struct sock_cgroup_data *skcd)
5905 {
5906         /* Socket clone path */
5907         if (skcd->val) {
5908                 if (skcd->no_refcnt)
5909                         return;
5910                 /*
5911                  * We might be cloning a socket which is left in an empty
5912                  * cgroup and the cgroup might have already been rmdir'd.
5913                  * Don't use cgroup_get_live().
5914                  */
5915                 cgroup_get(sock_cgroup_ptr(skcd));
5916         }
5917 }
5918
5919 void cgroup_sk_free(struct sock_cgroup_data *skcd)
5920 {
5921         if (skcd->no_refcnt)
5922                 return;
5923
5924         cgroup_put(sock_cgroup_ptr(skcd));
5925 }
5926
5927 #endif  /* CONFIG_SOCK_CGROUP_DATA */
5928
5929 #ifdef CONFIG_CGROUP_BPF
5930 int cgroup_bpf_update(struct cgroup *cgrp, struct bpf_prog *prog,
5931                       enum bpf_attach_type type, bool overridable)
5932 {
5933         struct cgroup *parent = cgroup_parent(cgrp);
5934         int ret;
5935
5936         mutex_lock(&cgroup_mutex);
5937         ret = __cgroup_bpf_update(cgrp, parent, prog, type, overridable);
5938         mutex_unlock(&cgroup_mutex);
5939         return ret;
5940 }
5941 #endif /* CONFIG_CGROUP_BPF */