kdbus: Revert "cgroup: remove unused task_cgroup_path()"
[platform/kernel/linux-rpi.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/bpf-cgroup.h>
34 #include <linux/cred.h>
35 #include <linux/errno.h>
36 #include <linux/init_task.h>
37 #include <linux/kernel.h>
38 #include <linux/magic.h>
39 #include <linux/mutex.h>
40 #include <linux/mount.h>
41 #include <linux/pagemap.h>
42 #include <linux/proc_fs.h>
43 #include <linux/rcupdate.h>
44 #include <linux/sched.h>
45 #include <linux/sched/task.h>
46 #include <linux/slab.h>
47 #include <linux/spinlock.h>
48 #include <linux/percpu-rwsem.h>
49 #include <linux/string.h>
50 #include <linux/hashtable.h>
51 #include <linux/idr.h>
52 #include <linux/kthread.h>
53 #include <linux/atomic.h>
54 #include <linux/cpuset.h>
55 #include <linux/proc_ns.h>
56 #include <linux/nsproxy.h>
57 #include <linux/file.h>
58 #include <linux/fs_parser.h>
59 #include <linux/sched/cputime.h>
60 #include <linux/sched/deadline.h>
61 #include <linux/psi.h>
62 #include <net/sock.h>
63
64 #define CREATE_TRACE_POINTS
65 #include <trace/events/cgroup.h>
66
67 #define CGROUP_FILE_NAME_MAX            (MAX_CGROUP_TYPE_NAMELEN +      \
68                                          MAX_CFTYPE_NAME + 2)
69 /* let's not notify more than 100 times per second */
70 #define CGROUP_FILE_NOTIFY_MIN_INTV     DIV_ROUND_UP(HZ, 100)
71
72 /*
73  * To avoid confusing the compiler (and generating warnings) with code
74  * that attempts to access what would be a 0-element array (i.e. sized
75  * to a potentially empty array when CGROUP_SUBSYS_COUNT == 0), this
76  * constant expression can be added.
77  */
78 #define CGROUP_HAS_SUBSYS_CONFIG        (CGROUP_SUBSYS_COUNT > 0)
79
80 /*
81  * cgroup_mutex is the master lock.  Any modification to cgroup or its
82  * hierarchy must be performed while holding it.
83  *
84  * css_set_lock protects task->cgroups pointer, the list of css_set
85  * objects, and the chain of tasks off each css_set.
86  *
87  * These locks are exported if CONFIG_PROVE_RCU so that accessors in
88  * cgroup.h can use them for lockdep annotations.
89  */
90 DEFINE_MUTEX(cgroup_mutex);
91 DEFINE_SPINLOCK(css_set_lock);
92
93 #ifdef CONFIG_PROVE_RCU
94 EXPORT_SYMBOL_GPL(cgroup_mutex);
95 EXPORT_SYMBOL_GPL(css_set_lock);
96 #endif
97
98 DEFINE_SPINLOCK(trace_cgroup_path_lock);
99 char trace_cgroup_path[TRACE_CGROUP_PATH_LEN];
100 static bool cgroup_debug __read_mostly;
101
102 /*
103  * Protects cgroup_idr and css_idr so that IDs can be released without
104  * grabbing cgroup_mutex.
105  */
106 static DEFINE_SPINLOCK(cgroup_idr_lock);
107
108 /*
109  * Protects cgroup_file->kn for !self csses.  It synchronizes notifications
110  * against file removal/re-creation across css hiding.
111  */
112 static DEFINE_SPINLOCK(cgroup_file_kn_lock);
113
114 DEFINE_PERCPU_RWSEM(cgroup_threadgroup_rwsem);
115
116 #define cgroup_assert_mutex_or_rcu_locked()                             \
117         RCU_LOCKDEP_WARN(!rcu_read_lock_held() &&                       \
118                            !lockdep_is_held(&cgroup_mutex),             \
119                            "cgroup_mutex or RCU read lock required");
120
121 /*
122  * cgroup destruction makes heavy use of work items and there can be a lot
123  * of concurrent destructions.  Use a separate workqueue so that cgroup
124  * destruction work items don't end up filling up max_active of system_wq
125  * which may lead to deadlock.
126  */
127 static struct workqueue_struct *cgroup_destroy_wq;
128
129 /* generate an array of cgroup subsystem pointers */
130 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
131 struct cgroup_subsys *cgroup_subsys[] = {
132 #include <linux/cgroup_subsys.h>
133 };
134 #undef SUBSYS
135
136 /* array of cgroup subsystem names */
137 #define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
138 static const char *cgroup_subsys_name[] = {
139 #include <linux/cgroup_subsys.h>
140 };
141 #undef SUBSYS
142
143 /* array of static_keys for cgroup_subsys_enabled() and cgroup_subsys_on_dfl() */
144 #define SUBSYS(_x)                                                              \
145         DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_enabled_key);                 \
146         DEFINE_STATIC_KEY_TRUE(_x ## _cgrp_subsys_on_dfl_key);                  \
147         EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_enabled_key);                      \
148         EXPORT_SYMBOL_GPL(_x ## _cgrp_subsys_on_dfl_key);
149 #include <linux/cgroup_subsys.h>
150 #undef SUBSYS
151
152 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_enabled_key,
153 static struct static_key_true *cgroup_subsys_enabled_key[] = {
154 #include <linux/cgroup_subsys.h>
155 };
156 #undef SUBSYS
157
158 #define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys_on_dfl_key,
159 static struct static_key_true *cgroup_subsys_on_dfl_key[] = {
160 #include <linux/cgroup_subsys.h>
161 };
162 #undef SUBSYS
163
164 static DEFINE_PER_CPU(struct cgroup_rstat_cpu, cgrp_dfl_root_rstat_cpu);
165
166 /* the default hierarchy */
167 struct cgroup_root cgrp_dfl_root = { .cgrp.rstat_cpu = &cgrp_dfl_root_rstat_cpu };
168 EXPORT_SYMBOL_GPL(cgrp_dfl_root);
169
170 /*
171  * The default hierarchy always exists but is hidden until mounted for the
172  * first time.  This is for backward compatibility.
173  */
174 static bool cgrp_dfl_visible;
175
176 /* some controllers are not supported in the default hierarchy */
177 static u16 cgrp_dfl_inhibit_ss_mask;
178
179 /* some controllers are implicitly enabled on the default hierarchy */
180 static u16 cgrp_dfl_implicit_ss_mask;
181
182 /* some controllers can be threaded on the default hierarchy */
183 static u16 cgrp_dfl_threaded_ss_mask;
184
185 /* The list of hierarchy roots */
186 LIST_HEAD(cgroup_roots);
187 static int cgroup_root_count;
188
189 /* hierarchy ID allocation and mapping, protected by cgroup_mutex */
190 static DEFINE_IDR(cgroup_hierarchy_idr);
191
192 /*
193  * Assign a monotonically increasing serial number to csses.  It guarantees
194  * cgroups with bigger numbers are newer than those with smaller numbers.
195  * Also, as csses are always appended to the parent's ->children list, it
196  * guarantees that sibling csses are always sorted in the ascending serial
197  * number order on the list.  Protected by cgroup_mutex.
198  */
199 static u64 css_serial_nr_next = 1;
200
201 /*
202  * These bitmasks identify subsystems with specific features to avoid
203  * having to do iterative checks repeatedly.
204  */
205 static u16 have_fork_callback __read_mostly;
206 static u16 have_exit_callback __read_mostly;
207 static u16 have_release_callback __read_mostly;
208 static u16 have_canfork_callback __read_mostly;
209
210 /* cgroup namespace for init task */
211 struct cgroup_namespace init_cgroup_ns = {
212         .ns.count       = REFCOUNT_INIT(2),
213         .user_ns        = &init_user_ns,
214         .ns.ops         = &cgroupns_operations,
215         .ns.inum        = PROC_CGROUP_INIT_INO,
216         .root_cset      = &init_css_set,
217 };
218
219 static struct file_system_type cgroup2_fs_type;
220 static struct cftype cgroup_base_files[];
221 static struct cftype cgroup_psi_files[];
222
223 /* cgroup optional features */
224 enum cgroup_opt_features {
225 #ifdef CONFIG_PSI
226         OPT_FEATURE_PRESSURE,
227 #endif
228         OPT_FEATURE_COUNT
229 };
230
231 static const char *cgroup_opt_feature_names[OPT_FEATURE_COUNT] = {
232 #ifdef CONFIG_PSI
233         "pressure",
234 #endif
235 };
236
237 static u16 cgroup_feature_disable_mask __read_mostly;
238
239 static int cgroup_apply_control(struct cgroup *cgrp);
240 static void cgroup_finalize_control(struct cgroup *cgrp, int ret);
241 static void css_task_iter_skip(struct css_task_iter *it,
242                                struct task_struct *task);
243 static int cgroup_destroy_locked(struct cgroup *cgrp);
244 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
245                                               struct cgroup_subsys *ss);
246 static void css_release(struct percpu_ref *ref);
247 static void kill_css(struct cgroup_subsys_state *css);
248 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
249                               struct cgroup *cgrp, struct cftype cfts[],
250                               bool is_add);
251
252 #ifdef CONFIG_DEBUG_CGROUP_REF
253 #define CGROUP_REF_FN_ATTRS     noinline
254 #define CGROUP_REF_EXPORT(fn)   EXPORT_SYMBOL_GPL(fn);
255 #include <linux/cgroup_refcnt.h>
256 #endif
257
258 /**
259  * cgroup_ssid_enabled - cgroup subsys enabled test by subsys ID
260  * @ssid: subsys ID of interest
261  *
262  * cgroup_subsys_enabled() can only be used with literal subsys names which
263  * is fine for individual subsystems but unsuitable for cgroup core.  This
264  * is slower static_key_enabled() based test indexed by @ssid.
265  */
266 bool cgroup_ssid_enabled(int ssid)
267 {
268         if (!CGROUP_HAS_SUBSYS_CONFIG)
269                 return false;
270
271         return static_key_enabled(cgroup_subsys_enabled_key[ssid]);
272 }
273
274 /**
275  * cgroup_on_dfl - test whether a cgroup is on the default hierarchy
276  * @cgrp: the cgroup of interest
277  *
278  * The default hierarchy is the v2 interface of cgroup and this function
279  * can be used to test whether a cgroup is on the default hierarchy for
280  * cases where a subsystem should behave differently depending on the
281  * interface version.
282  *
283  * List of changed behaviors:
284  *
285  * - Mount options "noprefix", "xattr", "clone_children", "release_agent"
286  *   and "name" are disallowed.
287  *
288  * - When mounting an existing superblock, mount options should match.
289  *
290  * - rename(2) is disallowed.
291  *
292  * - "tasks" is removed.  Everything should be at process granularity.  Use
293  *   "cgroup.procs" instead.
294  *
295  * - "cgroup.procs" is not sorted.  pids will be unique unless they got
296  *   recycled in-between reads.
297  *
298  * - "release_agent" and "notify_on_release" are removed.  Replacement
299  *   notification mechanism will be implemented.
300  *
301  * - "cgroup.clone_children" is removed.
302  *
303  * - "cgroup.subtree_populated" is available.  Its value is 0 if the cgroup
304  *   and its descendants contain no task; otherwise, 1.  The file also
305  *   generates kernfs notification which can be monitored through poll and
306  *   [di]notify when the value of the file changes.
307  *
308  * - cpuset: tasks will be kept in empty cpusets when hotplug happens and
309  *   take masks of ancestors with non-empty cpus/mems, instead of being
310  *   moved to an ancestor.
311  *
312  * - cpuset: a task can be moved into an empty cpuset, and again it takes
313  *   masks of ancestors.
314  *
315  * - blkcg: blk-throttle becomes properly hierarchical.
316  */
317 bool cgroup_on_dfl(const struct cgroup *cgrp)
318 {
319         return cgrp->root == &cgrp_dfl_root;
320 }
321
322 /* IDR wrappers which synchronize using cgroup_idr_lock */
323 static int cgroup_idr_alloc(struct idr *idr, void *ptr, int start, int end,
324                             gfp_t gfp_mask)
325 {
326         int ret;
327
328         idr_preload(gfp_mask);
329         spin_lock_bh(&cgroup_idr_lock);
330         ret = idr_alloc(idr, ptr, start, end, gfp_mask & ~__GFP_DIRECT_RECLAIM);
331         spin_unlock_bh(&cgroup_idr_lock);
332         idr_preload_end();
333         return ret;
334 }
335
336 static void *cgroup_idr_replace(struct idr *idr, void *ptr, int id)
337 {
338         void *ret;
339
340         spin_lock_bh(&cgroup_idr_lock);
341         ret = idr_replace(idr, ptr, id);
342         spin_unlock_bh(&cgroup_idr_lock);
343         return ret;
344 }
345
346 static void cgroup_idr_remove(struct idr *idr, int id)
347 {
348         spin_lock_bh(&cgroup_idr_lock);
349         idr_remove(idr, id);
350         spin_unlock_bh(&cgroup_idr_lock);
351 }
352
353 static bool cgroup_has_tasks(struct cgroup *cgrp)
354 {
355         return cgrp->nr_populated_csets;
356 }
357
358 static bool cgroup_is_threaded(struct cgroup *cgrp)
359 {
360         return cgrp->dom_cgrp != cgrp;
361 }
362
363 /* can @cgrp host both domain and threaded children? */
364 static bool cgroup_is_mixable(struct cgroup *cgrp)
365 {
366         /*
367          * Root isn't under domain level resource control exempting it from
368          * the no-internal-process constraint, so it can serve as a thread
369          * root and a parent of resource domains at the same time.
370          */
371         return !cgroup_parent(cgrp);
372 }
373
374 /* can @cgrp become a thread root? Should always be true for a thread root */
375 static bool cgroup_can_be_thread_root(struct cgroup *cgrp)
376 {
377         /* mixables don't care */
378         if (cgroup_is_mixable(cgrp))
379                 return true;
380
381         /* domain roots can't be nested under threaded */
382         if (cgroup_is_threaded(cgrp))
383                 return false;
384
385         /* can only have either domain or threaded children */
386         if (cgrp->nr_populated_domain_children)
387                 return false;
388
389         /* and no domain controllers can be enabled */
390         if (cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
391                 return false;
392
393         return true;
394 }
395
396 /* is @cgrp root of a threaded subtree? */
397 static bool cgroup_is_thread_root(struct cgroup *cgrp)
398 {
399         /* thread root should be a domain */
400         if (cgroup_is_threaded(cgrp))
401                 return false;
402
403         /* a domain w/ threaded children is a thread root */
404         if (cgrp->nr_threaded_children)
405                 return true;
406
407         /*
408          * A domain which has tasks and explicit threaded controllers
409          * enabled is a thread root.
410          */
411         if (cgroup_has_tasks(cgrp) &&
412             (cgrp->subtree_control & cgrp_dfl_threaded_ss_mask))
413                 return true;
414
415         return false;
416 }
417
418 /* a domain which isn't connected to the root w/o brekage can't be used */
419 static bool cgroup_is_valid_domain(struct cgroup *cgrp)
420 {
421         /* the cgroup itself can be a thread root */
422         if (cgroup_is_threaded(cgrp))
423                 return false;
424
425         /* but the ancestors can't be unless mixable */
426         while ((cgrp = cgroup_parent(cgrp))) {
427                 if (!cgroup_is_mixable(cgrp) && cgroup_is_thread_root(cgrp))
428                         return false;
429                 if (cgroup_is_threaded(cgrp))
430                         return false;
431         }
432
433         return true;
434 }
435
436 /* subsystems visibly enabled on a cgroup */
437 static u16 cgroup_control(struct cgroup *cgrp)
438 {
439         struct cgroup *parent = cgroup_parent(cgrp);
440         u16 root_ss_mask = cgrp->root->subsys_mask;
441
442         if (parent) {
443                 u16 ss_mask = parent->subtree_control;
444
445                 /* threaded cgroups can only have threaded controllers */
446                 if (cgroup_is_threaded(cgrp))
447                         ss_mask &= cgrp_dfl_threaded_ss_mask;
448                 return ss_mask;
449         }
450
451         if (cgroup_on_dfl(cgrp))
452                 root_ss_mask &= ~(cgrp_dfl_inhibit_ss_mask |
453                                   cgrp_dfl_implicit_ss_mask);
454         return root_ss_mask;
455 }
456
457 /* subsystems enabled on a cgroup */
458 static u16 cgroup_ss_mask(struct cgroup *cgrp)
459 {
460         struct cgroup *parent = cgroup_parent(cgrp);
461
462         if (parent) {
463                 u16 ss_mask = parent->subtree_ss_mask;
464
465                 /* threaded cgroups can only have threaded controllers */
466                 if (cgroup_is_threaded(cgrp))
467                         ss_mask &= cgrp_dfl_threaded_ss_mask;
468                 return ss_mask;
469         }
470
471         return cgrp->root->subsys_mask;
472 }
473
474 /**
475  * cgroup_css - obtain a cgroup's css for the specified subsystem
476  * @cgrp: the cgroup of interest
477  * @ss: the subsystem of interest (%NULL returns @cgrp->self)
478  *
479  * Return @cgrp's css (cgroup_subsys_state) associated with @ss.  This
480  * function must be called either under cgroup_mutex or rcu_read_lock() and
481  * the caller is responsible for pinning the returned css if it wants to
482  * keep accessing it outside the said locks.  This function may return
483  * %NULL if @cgrp doesn't have @subsys_id enabled.
484  */
485 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
486                                               struct cgroup_subsys *ss)
487 {
488         if (CGROUP_HAS_SUBSYS_CONFIG && ss)
489                 return rcu_dereference_check(cgrp->subsys[ss->id],
490                                         lockdep_is_held(&cgroup_mutex));
491         else
492                 return &cgrp->self;
493 }
494
495 /**
496  * cgroup_e_css_by_mask - obtain a cgroup's effective css for the specified ss
497  * @cgrp: the cgroup of interest
498  * @ss: the subsystem of interest (%NULL returns @cgrp->self)
499  *
500  * Similar to cgroup_css() but returns the effective css, which is defined
501  * as the matching css of the nearest ancestor including self which has @ss
502  * enabled.  If @ss is associated with the hierarchy @cgrp is on, this
503  * function is guaranteed to return non-NULL css.
504  */
505 static struct cgroup_subsys_state *cgroup_e_css_by_mask(struct cgroup *cgrp,
506                                                         struct cgroup_subsys *ss)
507 {
508         lockdep_assert_held(&cgroup_mutex);
509
510         if (!ss)
511                 return &cgrp->self;
512
513         /*
514          * This function is used while updating css associations and thus
515          * can't test the csses directly.  Test ss_mask.
516          */
517         while (!(cgroup_ss_mask(cgrp) & (1 << ss->id))) {
518                 cgrp = cgroup_parent(cgrp);
519                 if (!cgrp)
520                         return NULL;
521         }
522
523         return cgroup_css(cgrp, ss);
524 }
525
526 /**
527  * cgroup_e_css - obtain a cgroup's effective css for the specified subsystem
528  * @cgrp: the cgroup of interest
529  * @ss: the subsystem of interest
530  *
531  * Find and get the effective css of @cgrp for @ss.  The effective css is
532  * defined as the matching css of the nearest ancestor including self which
533  * has @ss enabled.  If @ss is not mounted on the hierarchy @cgrp is on,
534  * the root css is returned, so this function always returns a valid css.
535  *
536  * The returned css is not guaranteed to be online, and therefore it is the
537  * callers responsibility to try get a reference for it.
538  */
539 struct cgroup_subsys_state *cgroup_e_css(struct cgroup *cgrp,
540                                          struct cgroup_subsys *ss)
541 {
542         struct cgroup_subsys_state *css;
543
544         if (!CGROUP_HAS_SUBSYS_CONFIG)
545                 return NULL;
546
547         do {
548                 css = cgroup_css(cgrp, ss);
549
550                 if (css)
551                         return css;
552                 cgrp = cgroup_parent(cgrp);
553         } while (cgrp);
554
555         return init_css_set.subsys[ss->id];
556 }
557
558 /**
559  * cgroup_get_e_css - get a cgroup's effective css for the specified subsystem
560  * @cgrp: the cgroup of interest
561  * @ss: the subsystem of interest
562  *
563  * Find and get the effective css of @cgrp for @ss.  The effective css is
564  * defined as the matching css of the nearest ancestor including self which
565  * has @ss enabled.  If @ss is not mounted on the hierarchy @cgrp is on,
566  * the root css is returned, so this function always returns a valid css.
567  * The returned css must be put using css_put().
568  */
569 struct cgroup_subsys_state *cgroup_get_e_css(struct cgroup *cgrp,
570                                              struct cgroup_subsys *ss)
571 {
572         struct cgroup_subsys_state *css;
573
574         if (!CGROUP_HAS_SUBSYS_CONFIG)
575                 return NULL;
576
577         rcu_read_lock();
578
579         do {
580                 css = cgroup_css(cgrp, ss);
581
582                 if (css && css_tryget_online(css))
583                         goto out_unlock;
584                 cgrp = cgroup_parent(cgrp);
585         } while (cgrp);
586
587         css = init_css_set.subsys[ss->id];
588         css_get(css);
589 out_unlock:
590         rcu_read_unlock();
591         return css;
592 }
593 EXPORT_SYMBOL_GPL(cgroup_get_e_css);
594
595 static void cgroup_get_live(struct cgroup *cgrp)
596 {
597         WARN_ON_ONCE(cgroup_is_dead(cgrp));
598         cgroup_get(cgrp);
599 }
600
601 /**
602  * __cgroup_task_count - count the number of tasks in a cgroup. The caller
603  * is responsible for taking the css_set_lock.
604  * @cgrp: the cgroup in question
605  */
606 int __cgroup_task_count(const struct cgroup *cgrp)
607 {
608         int count = 0;
609         struct cgrp_cset_link *link;
610
611         lockdep_assert_held(&css_set_lock);
612
613         list_for_each_entry(link, &cgrp->cset_links, cset_link)
614                 count += link->cset->nr_tasks;
615
616         return count;
617 }
618
619 /**
620  * cgroup_task_count - count the number of tasks in a cgroup.
621  * @cgrp: the cgroup in question
622  */
623 int cgroup_task_count(const struct cgroup *cgrp)
624 {
625         int count;
626
627         spin_lock_irq(&css_set_lock);
628         count = __cgroup_task_count(cgrp);
629         spin_unlock_irq(&css_set_lock);
630
631         return count;
632 }
633
634 struct cgroup_subsys_state *of_css(struct kernfs_open_file *of)
635 {
636         struct cgroup *cgrp = of->kn->parent->priv;
637         struct cftype *cft = of_cft(of);
638
639         /*
640          * This is open and unprotected implementation of cgroup_css().
641          * seq_css() is only called from a kernfs file operation which has
642          * an active reference on the file.  Because all the subsystem
643          * files are drained before a css is disassociated with a cgroup,
644          * the matching css from the cgroup's subsys table is guaranteed to
645          * be and stay valid until the enclosing operation is complete.
646          */
647         if (CGROUP_HAS_SUBSYS_CONFIG && cft->ss)
648                 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
649         else
650                 return &cgrp->self;
651 }
652 EXPORT_SYMBOL_GPL(of_css);
653
654 /**
655  * for_each_css - iterate all css's of a cgroup
656  * @css: the iteration cursor
657  * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
658  * @cgrp: the target cgroup to iterate css's of
659  *
660  * Should be called under cgroup_mutex.
661  */
662 #define for_each_css(css, ssid, cgrp)                                   \
663         for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++)        \
664                 if (!((css) = rcu_dereference_check(                    \
665                                 (cgrp)->subsys[(ssid)],                 \
666                                 lockdep_is_held(&cgroup_mutex)))) { }   \
667                 else
668
669 /**
670  * do_each_subsys_mask - filter for_each_subsys with a bitmask
671  * @ss: the iteration cursor
672  * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
673  * @ss_mask: the bitmask
674  *
675  * The block will only run for cases where the ssid-th bit (1 << ssid) of
676  * @ss_mask is set.
677  */
678 #define do_each_subsys_mask(ss, ssid, ss_mask) do {                     \
679         unsigned long __ss_mask = (ss_mask);                            \
680         if (!CGROUP_HAS_SUBSYS_CONFIG) {                                \
681                 (ssid) = 0;                                             \
682                 break;                                                  \
683         }                                                               \
684         for_each_set_bit(ssid, &__ss_mask, CGROUP_SUBSYS_COUNT) {       \
685                 (ss) = cgroup_subsys[ssid];                             \
686                 {
687
688 #define while_each_subsys_mask()                                        \
689                 }                                                       \
690         }                                                               \
691 } while (false)
692
693 /* iterate over child cgrps, lock should be held throughout iteration */
694 #define cgroup_for_each_live_child(child, cgrp)                         \
695         list_for_each_entry((child), &(cgrp)->self.children, self.sibling) \
696                 if (({ lockdep_assert_held(&cgroup_mutex);              \
697                        cgroup_is_dead(child); }))                       \
698                         ;                                               \
699                 else
700
701 /* walk live descendants in pre order */
702 #define cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp)          \
703         css_for_each_descendant_pre((d_css), cgroup_css((cgrp), NULL))  \
704                 if (({ lockdep_assert_held(&cgroup_mutex);              \
705                        (dsct) = (d_css)->cgroup;                        \
706                        cgroup_is_dead(dsct); }))                        \
707                         ;                                               \
708                 else
709
710 /* walk live descendants in postorder */
711 #define cgroup_for_each_live_descendant_post(dsct, d_css, cgrp)         \
712         css_for_each_descendant_post((d_css), cgroup_css((cgrp), NULL)) \
713                 if (({ lockdep_assert_held(&cgroup_mutex);              \
714                        (dsct) = (d_css)->cgroup;                        \
715                        cgroup_is_dead(dsct); }))                        \
716                         ;                                               \
717                 else
718
719 /*
720  * The default css_set - used by init and its children prior to any
721  * hierarchies being mounted. It contains a pointer to the root state
722  * for each subsystem. Also used to anchor the list of css_sets. Not
723  * reference-counted, to improve performance when child cgroups
724  * haven't been created.
725  */
726 struct css_set init_css_set = {
727         .refcount               = REFCOUNT_INIT(1),
728         .dom_cset               = &init_css_set,
729         .tasks                  = LIST_HEAD_INIT(init_css_set.tasks),
730         .mg_tasks               = LIST_HEAD_INIT(init_css_set.mg_tasks),
731         .dying_tasks            = LIST_HEAD_INIT(init_css_set.dying_tasks),
732         .task_iters             = LIST_HEAD_INIT(init_css_set.task_iters),
733         .threaded_csets         = LIST_HEAD_INIT(init_css_set.threaded_csets),
734         .cgrp_links             = LIST_HEAD_INIT(init_css_set.cgrp_links),
735         .mg_src_preload_node    = LIST_HEAD_INIT(init_css_set.mg_src_preload_node),
736         .mg_dst_preload_node    = LIST_HEAD_INIT(init_css_set.mg_dst_preload_node),
737         .mg_node                = LIST_HEAD_INIT(init_css_set.mg_node),
738
739         /*
740          * The following field is re-initialized when this cset gets linked
741          * in cgroup_init().  However, let's initialize the field
742          * statically too so that the default cgroup can be accessed safely
743          * early during boot.
744          */
745         .dfl_cgrp               = &cgrp_dfl_root.cgrp,
746 };
747
748 static int css_set_count        = 1;    /* 1 for init_css_set */
749
750 static bool css_set_threaded(struct css_set *cset)
751 {
752         return cset->dom_cset != cset;
753 }
754
755 /**
756  * css_set_populated - does a css_set contain any tasks?
757  * @cset: target css_set
758  *
759  * css_set_populated() should be the same as !!cset->nr_tasks at steady
760  * state. However, css_set_populated() can be called while a task is being
761  * added to or removed from the linked list before the nr_tasks is
762  * properly updated. Hence, we can't just look at ->nr_tasks here.
763  */
764 static bool css_set_populated(struct css_set *cset)
765 {
766         lockdep_assert_held(&css_set_lock);
767
768         return !list_empty(&cset->tasks) || !list_empty(&cset->mg_tasks);
769 }
770
771 /**
772  * cgroup_update_populated - update the populated count of a cgroup
773  * @cgrp: the target cgroup
774  * @populated: inc or dec populated count
775  *
776  * One of the css_sets associated with @cgrp is either getting its first
777  * task or losing the last.  Update @cgrp->nr_populated_* accordingly.  The
778  * count is propagated towards root so that a given cgroup's
779  * nr_populated_children is zero iff none of its descendants contain any
780  * tasks.
781  *
782  * @cgrp's interface file "cgroup.populated" is zero if both
783  * @cgrp->nr_populated_csets and @cgrp->nr_populated_children are zero and
784  * 1 otherwise.  When the sum changes from or to zero, userland is notified
785  * that the content of the interface file has changed.  This can be used to
786  * detect when @cgrp and its descendants become populated or empty.
787  */
788 static void cgroup_update_populated(struct cgroup *cgrp, bool populated)
789 {
790         struct cgroup *child = NULL;
791         int adj = populated ? 1 : -1;
792
793         lockdep_assert_held(&css_set_lock);
794
795         do {
796                 bool was_populated = cgroup_is_populated(cgrp);
797
798                 if (!child) {
799                         cgrp->nr_populated_csets += adj;
800                 } else {
801                         if (cgroup_is_threaded(child))
802                                 cgrp->nr_populated_threaded_children += adj;
803                         else
804                                 cgrp->nr_populated_domain_children += adj;
805                 }
806
807                 if (was_populated == cgroup_is_populated(cgrp))
808                         break;
809
810                 cgroup1_check_for_release(cgrp);
811                 TRACE_CGROUP_PATH(notify_populated, cgrp,
812                                   cgroup_is_populated(cgrp));
813                 cgroup_file_notify(&cgrp->events_file);
814
815                 child = cgrp;
816                 cgrp = cgroup_parent(cgrp);
817         } while (cgrp);
818 }
819
820 /**
821  * css_set_update_populated - update populated state of a css_set
822  * @cset: target css_set
823  * @populated: whether @cset is populated or depopulated
824  *
825  * @cset is either getting the first task or losing the last.  Update the
826  * populated counters of all associated cgroups accordingly.
827  */
828 static void css_set_update_populated(struct css_set *cset, bool populated)
829 {
830         struct cgrp_cset_link *link;
831
832         lockdep_assert_held(&css_set_lock);
833
834         list_for_each_entry(link, &cset->cgrp_links, cgrp_link)
835                 cgroup_update_populated(link->cgrp, populated);
836 }
837
838 /*
839  * @task is leaving, advance task iterators which are pointing to it so
840  * that they can resume at the next position.  Advancing an iterator might
841  * remove it from the list, use safe walk.  See css_task_iter_skip() for
842  * details.
843  */
844 static void css_set_skip_task_iters(struct css_set *cset,
845                                     struct task_struct *task)
846 {
847         struct css_task_iter *it, *pos;
848
849         list_for_each_entry_safe(it, pos, &cset->task_iters, iters_node)
850                 css_task_iter_skip(it, task);
851 }
852
853 /**
854  * css_set_move_task - move a task from one css_set to another
855  * @task: task being moved
856  * @from_cset: css_set @task currently belongs to (may be NULL)
857  * @to_cset: new css_set @task is being moved to (may be NULL)
858  * @use_mg_tasks: move to @to_cset->mg_tasks instead of ->tasks
859  *
860  * Move @task from @from_cset to @to_cset.  If @task didn't belong to any
861  * css_set, @from_cset can be NULL.  If @task is being disassociated
862  * instead of moved, @to_cset can be NULL.
863  *
864  * This function automatically handles populated counter updates and
865  * css_task_iter adjustments but the caller is responsible for managing
866  * @from_cset and @to_cset's reference counts.
867  */
868 static void css_set_move_task(struct task_struct *task,
869                               struct css_set *from_cset, struct css_set *to_cset,
870                               bool use_mg_tasks)
871 {
872         lockdep_assert_held(&css_set_lock);
873
874         if (to_cset && !css_set_populated(to_cset))
875                 css_set_update_populated(to_cset, true);
876
877         if (from_cset) {
878                 WARN_ON_ONCE(list_empty(&task->cg_list));
879
880                 css_set_skip_task_iters(from_cset, task);
881                 list_del_init(&task->cg_list);
882                 if (!css_set_populated(from_cset))
883                         css_set_update_populated(from_cset, false);
884         } else {
885                 WARN_ON_ONCE(!list_empty(&task->cg_list));
886         }
887
888         if (to_cset) {
889                 /*
890                  * We are synchronized through cgroup_threadgroup_rwsem
891                  * against PF_EXITING setting such that we can't race
892                  * against cgroup_exit()/cgroup_free() dropping the css_set.
893                  */
894                 WARN_ON_ONCE(task->flags & PF_EXITING);
895
896                 cgroup_move_task(task, to_cset);
897                 list_add_tail(&task->cg_list, use_mg_tasks ? &to_cset->mg_tasks :
898                                                              &to_cset->tasks);
899         }
900 }
901
902 /*
903  * hash table for cgroup groups. This improves the performance to find
904  * an existing css_set. This hash doesn't (currently) take into
905  * account cgroups in empty hierarchies.
906  */
907 #define CSS_SET_HASH_BITS       7
908 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
909
910 static unsigned long css_set_hash(struct cgroup_subsys_state **css)
911 {
912         unsigned long key = 0UL;
913         struct cgroup_subsys *ss;
914         int i;
915
916         for_each_subsys(ss, i)
917                 key += (unsigned long)css[i];
918         key = (key >> 16) ^ key;
919
920         return key;
921 }
922
923 void put_css_set_locked(struct css_set *cset)
924 {
925         struct cgrp_cset_link *link, *tmp_link;
926         struct cgroup_subsys *ss;
927         int ssid;
928
929         lockdep_assert_held(&css_set_lock);
930
931         if (!refcount_dec_and_test(&cset->refcount))
932                 return;
933
934         WARN_ON_ONCE(!list_empty(&cset->threaded_csets));
935
936         /* This css_set is dead. Unlink it and release cgroup and css refs */
937         for_each_subsys(ss, ssid) {
938                 list_del(&cset->e_cset_node[ssid]);
939                 css_put(cset->subsys[ssid]);
940         }
941         hash_del(&cset->hlist);
942         css_set_count--;
943
944         list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
945                 list_del(&link->cset_link);
946                 list_del(&link->cgrp_link);
947                 if (cgroup_parent(link->cgrp))
948                         cgroup_put(link->cgrp);
949                 kfree(link);
950         }
951
952         if (css_set_threaded(cset)) {
953                 list_del(&cset->threaded_csets_node);
954                 put_css_set_locked(cset->dom_cset);
955         }
956
957         kfree_rcu(cset, rcu_head);
958 }
959
960 /**
961  * compare_css_sets - helper function for find_existing_css_set().
962  * @cset: candidate css_set being tested
963  * @old_cset: existing css_set for a task
964  * @new_cgrp: cgroup that's being entered by the task
965  * @template: desired set of css pointers in css_set (pre-calculated)
966  *
967  * Returns true if "cset" matches "old_cset" except for the hierarchy
968  * which "new_cgrp" belongs to, for which it should match "new_cgrp".
969  */
970 static bool compare_css_sets(struct css_set *cset,
971                              struct css_set *old_cset,
972                              struct cgroup *new_cgrp,
973                              struct cgroup_subsys_state *template[])
974 {
975         struct cgroup *new_dfl_cgrp;
976         struct list_head *l1, *l2;
977
978         /*
979          * On the default hierarchy, there can be csets which are
980          * associated with the same set of cgroups but different csses.
981          * Let's first ensure that csses match.
982          */
983         if (memcmp(template, cset->subsys, sizeof(cset->subsys)))
984                 return false;
985
986
987         /* @cset's domain should match the default cgroup's */
988         if (cgroup_on_dfl(new_cgrp))
989                 new_dfl_cgrp = new_cgrp;
990         else
991                 new_dfl_cgrp = old_cset->dfl_cgrp;
992
993         if (new_dfl_cgrp->dom_cgrp != cset->dom_cset->dfl_cgrp)
994                 return false;
995
996         /*
997          * Compare cgroup pointers in order to distinguish between
998          * different cgroups in hierarchies.  As different cgroups may
999          * share the same effective css, this comparison is always
1000          * necessary.
1001          */
1002         l1 = &cset->cgrp_links;
1003         l2 = &old_cset->cgrp_links;
1004         while (1) {
1005                 struct cgrp_cset_link *link1, *link2;
1006                 struct cgroup *cgrp1, *cgrp2;
1007
1008                 l1 = l1->next;
1009                 l2 = l2->next;
1010                 /* See if we reached the end - both lists are equal length. */
1011                 if (l1 == &cset->cgrp_links) {
1012                         BUG_ON(l2 != &old_cset->cgrp_links);
1013                         break;
1014                 } else {
1015                         BUG_ON(l2 == &old_cset->cgrp_links);
1016                 }
1017                 /* Locate the cgroups associated with these links. */
1018                 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
1019                 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
1020                 cgrp1 = link1->cgrp;
1021                 cgrp2 = link2->cgrp;
1022                 /* Hierarchies should be linked in the same order. */
1023                 BUG_ON(cgrp1->root != cgrp2->root);
1024
1025                 /*
1026                  * If this hierarchy is the hierarchy of the cgroup
1027                  * that's changing, then we need to check that this
1028                  * css_set points to the new cgroup; if it's any other
1029                  * hierarchy, then this css_set should point to the
1030                  * same cgroup as the old css_set.
1031                  */
1032                 if (cgrp1->root == new_cgrp->root) {
1033                         if (cgrp1 != new_cgrp)
1034                                 return false;
1035                 } else {
1036                         if (cgrp1 != cgrp2)
1037                                 return false;
1038                 }
1039         }
1040         return true;
1041 }
1042
1043 /**
1044  * find_existing_css_set - init css array and find the matching css_set
1045  * @old_cset: the css_set that we're using before the cgroup transition
1046  * @cgrp: the cgroup that we're moving into
1047  * @template: out param for the new set of csses, should be clear on entry
1048  */
1049 static struct css_set *find_existing_css_set(struct css_set *old_cset,
1050                                         struct cgroup *cgrp,
1051                                         struct cgroup_subsys_state **template)
1052 {
1053         struct cgroup_root *root = cgrp->root;
1054         struct cgroup_subsys *ss;
1055         struct css_set *cset;
1056         unsigned long key;
1057         int i;
1058
1059         /*
1060          * Build the set of subsystem state objects that we want to see in the
1061          * new css_set. While subsystems can change globally, the entries here
1062          * won't change, so no need for locking.
1063          */
1064         for_each_subsys(ss, i) {
1065                 if (root->subsys_mask & (1UL << i)) {
1066                         /*
1067                          * @ss is in this hierarchy, so we want the
1068                          * effective css from @cgrp.
1069                          */
1070                         template[i] = cgroup_e_css_by_mask(cgrp, ss);
1071                 } else {
1072                         /*
1073                          * @ss is not in this hierarchy, so we don't want
1074                          * to change the css.
1075                          */
1076                         template[i] = old_cset->subsys[i];
1077                 }
1078         }
1079
1080         key = css_set_hash(template);
1081         hash_for_each_possible(css_set_table, cset, hlist, key) {
1082                 if (!compare_css_sets(cset, old_cset, cgrp, template))
1083                         continue;
1084
1085                 /* This css_set matches what we need */
1086                 return cset;
1087         }
1088
1089         /* No existing cgroup group matched */
1090         return NULL;
1091 }
1092
1093 static void free_cgrp_cset_links(struct list_head *links_to_free)
1094 {
1095         struct cgrp_cset_link *link, *tmp_link;
1096
1097         list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
1098                 list_del(&link->cset_link);
1099                 kfree(link);
1100         }
1101 }
1102
1103 /**
1104  * allocate_cgrp_cset_links - allocate cgrp_cset_links
1105  * @count: the number of links to allocate
1106  * @tmp_links: list_head the allocated links are put on
1107  *
1108  * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
1109  * through ->cset_link.  Returns 0 on success or -errno.
1110  */
1111 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
1112 {
1113         struct cgrp_cset_link *link;
1114         int i;
1115
1116         INIT_LIST_HEAD(tmp_links);
1117
1118         for (i = 0; i < count; i++) {
1119                 link = kzalloc(sizeof(*link), GFP_KERNEL);
1120                 if (!link) {
1121                         free_cgrp_cset_links(tmp_links);
1122                         return -ENOMEM;
1123                 }
1124                 list_add(&link->cset_link, tmp_links);
1125         }
1126         return 0;
1127 }
1128
1129 /**
1130  * link_css_set - a helper function to link a css_set to a cgroup
1131  * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
1132  * @cset: the css_set to be linked
1133  * @cgrp: the destination cgroup
1134  */
1135 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
1136                          struct cgroup *cgrp)
1137 {
1138         struct cgrp_cset_link *link;
1139
1140         BUG_ON(list_empty(tmp_links));
1141
1142         if (cgroup_on_dfl(cgrp))
1143                 cset->dfl_cgrp = cgrp;
1144
1145         link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
1146         link->cset = cset;
1147         link->cgrp = cgrp;
1148
1149         /*
1150          * Always add links to the tail of the lists so that the lists are
1151          * in chronological order.
1152          */
1153         list_move_tail(&link->cset_link, &cgrp->cset_links);
1154         list_add_tail(&link->cgrp_link, &cset->cgrp_links);
1155
1156         if (cgroup_parent(cgrp))
1157                 cgroup_get_live(cgrp);
1158 }
1159
1160 /**
1161  * find_css_set - return a new css_set with one cgroup updated
1162  * @old_cset: the baseline css_set
1163  * @cgrp: the cgroup to be updated
1164  *
1165  * Return a new css_set that's equivalent to @old_cset, but with @cgrp
1166  * substituted into the appropriate hierarchy.
1167  */
1168 static struct css_set *find_css_set(struct css_set *old_cset,
1169                                     struct cgroup *cgrp)
1170 {
1171         struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
1172         struct css_set *cset;
1173         struct list_head tmp_links;
1174         struct cgrp_cset_link *link;
1175         struct cgroup_subsys *ss;
1176         unsigned long key;
1177         int ssid;
1178
1179         lockdep_assert_held(&cgroup_mutex);
1180
1181         /* First see if we already have a cgroup group that matches
1182          * the desired set */
1183         spin_lock_irq(&css_set_lock);
1184         cset = find_existing_css_set(old_cset, cgrp, template);
1185         if (cset)
1186                 get_css_set(cset);
1187         spin_unlock_irq(&css_set_lock);
1188
1189         if (cset)
1190                 return cset;
1191
1192         cset = kzalloc(sizeof(*cset), GFP_KERNEL);
1193         if (!cset)
1194                 return NULL;
1195
1196         /* Allocate all the cgrp_cset_link objects that we'll need */
1197         if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
1198                 kfree(cset);
1199                 return NULL;
1200         }
1201
1202         refcount_set(&cset->refcount, 1);
1203         cset->dom_cset = cset;
1204         INIT_LIST_HEAD(&cset->tasks);
1205         INIT_LIST_HEAD(&cset->mg_tasks);
1206         INIT_LIST_HEAD(&cset->dying_tasks);
1207         INIT_LIST_HEAD(&cset->task_iters);
1208         INIT_LIST_HEAD(&cset->threaded_csets);
1209         INIT_HLIST_NODE(&cset->hlist);
1210         INIT_LIST_HEAD(&cset->cgrp_links);
1211         INIT_LIST_HEAD(&cset->mg_src_preload_node);
1212         INIT_LIST_HEAD(&cset->mg_dst_preload_node);
1213         INIT_LIST_HEAD(&cset->mg_node);
1214
1215         /* Copy the set of subsystem state objects generated in
1216          * find_existing_css_set() */
1217         memcpy(cset->subsys, template, sizeof(cset->subsys));
1218
1219         spin_lock_irq(&css_set_lock);
1220         /* Add reference counts and links from the new css_set. */
1221         list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
1222                 struct cgroup *c = link->cgrp;
1223
1224                 if (c->root == cgrp->root)
1225                         c = cgrp;
1226                 link_css_set(&tmp_links, cset, c);
1227         }
1228
1229         BUG_ON(!list_empty(&tmp_links));
1230
1231         css_set_count++;
1232
1233         /* Add @cset to the hash table */
1234         key = css_set_hash(cset->subsys);
1235         hash_add(css_set_table, &cset->hlist, key);
1236
1237         for_each_subsys(ss, ssid) {
1238                 struct cgroup_subsys_state *css = cset->subsys[ssid];
1239
1240                 list_add_tail(&cset->e_cset_node[ssid],
1241                               &css->cgroup->e_csets[ssid]);
1242                 css_get(css);
1243         }
1244
1245         spin_unlock_irq(&css_set_lock);
1246
1247         /*
1248          * If @cset should be threaded, look up the matching dom_cset and
1249          * link them up.  We first fully initialize @cset then look for the
1250          * dom_cset.  It's simpler this way and safe as @cset is guaranteed
1251          * to stay empty until we return.
1252          */
1253         if (cgroup_is_threaded(cset->dfl_cgrp)) {
1254                 struct css_set *dcset;
1255
1256                 dcset = find_css_set(cset, cset->dfl_cgrp->dom_cgrp);
1257                 if (!dcset) {
1258                         put_css_set(cset);
1259                         return NULL;
1260                 }
1261
1262                 spin_lock_irq(&css_set_lock);
1263                 cset->dom_cset = dcset;
1264                 list_add_tail(&cset->threaded_csets_node,
1265                               &dcset->threaded_csets);
1266                 spin_unlock_irq(&css_set_lock);
1267         }
1268
1269         return cset;
1270 }
1271
1272 struct cgroup_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
1273 {
1274         struct cgroup *root_cgrp = kernfs_root_to_node(kf_root)->priv;
1275
1276         return root_cgrp->root;
1277 }
1278
1279 void cgroup_favor_dynmods(struct cgroup_root *root, bool favor)
1280 {
1281         bool favoring = root->flags & CGRP_ROOT_FAVOR_DYNMODS;
1282
1283         /* see the comment above CGRP_ROOT_FAVOR_DYNMODS definition */
1284         if (favor && !favoring) {
1285                 rcu_sync_enter(&cgroup_threadgroup_rwsem.rss);
1286                 root->flags |= CGRP_ROOT_FAVOR_DYNMODS;
1287         } else if (!favor && favoring) {
1288                 rcu_sync_exit(&cgroup_threadgroup_rwsem.rss);
1289                 root->flags &= ~CGRP_ROOT_FAVOR_DYNMODS;
1290         }
1291 }
1292
1293 static int cgroup_init_root_id(struct cgroup_root *root)
1294 {
1295         int id;
1296
1297         lockdep_assert_held(&cgroup_mutex);
1298
1299         id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, 0, 0, GFP_KERNEL);
1300         if (id < 0)
1301                 return id;
1302
1303         root->hierarchy_id = id;
1304         return 0;
1305 }
1306
1307 static void cgroup_exit_root_id(struct cgroup_root *root)
1308 {
1309         lockdep_assert_held(&cgroup_mutex);
1310
1311         idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1312 }
1313
1314 void cgroup_free_root(struct cgroup_root *root)
1315 {
1316         kfree(root);
1317 }
1318
1319 static void cgroup_destroy_root(struct cgroup_root *root)
1320 {
1321         struct cgroup *cgrp = &root->cgrp;
1322         struct cgrp_cset_link *link, *tmp_link;
1323
1324         trace_cgroup_destroy_root(root);
1325
1326         cgroup_lock_and_drain_offline(&cgrp_dfl_root.cgrp);
1327
1328         BUG_ON(atomic_read(&root->nr_cgrps));
1329         BUG_ON(!list_empty(&cgrp->self.children));
1330
1331         /* Rebind all subsystems back to the default hierarchy */
1332         WARN_ON(rebind_subsystems(&cgrp_dfl_root, root->subsys_mask));
1333
1334         /*
1335          * Release all the links from cset_links to this hierarchy's
1336          * root cgroup
1337          */
1338         spin_lock_irq(&css_set_lock);
1339
1340         list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1341                 list_del(&link->cset_link);
1342                 list_del(&link->cgrp_link);
1343                 kfree(link);
1344         }
1345
1346         spin_unlock_irq(&css_set_lock);
1347
1348         if (!list_empty(&root->root_list)) {
1349                 list_del(&root->root_list);
1350                 cgroup_root_count--;
1351         }
1352
1353         cgroup_favor_dynmods(root, false);
1354         cgroup_exit_root_id(root);
1355
1356         cgroup_unlock();
1357
1358         cgroup_rstat_exit(cgrp);
1359         kernfs_destroy_root(root->kf_root);
1360         cgroup_free_root(root);
1361 }
1362
1363 /*
1364  * Returned cgroup is without refcount but it's valid as long as cset pins it.
1365  */
1366 static inline struct cgroup *__cset_cgroup_from_root(struct css_set *cset,
1367                                             struct cgroup_root *root)
1368 {
1369         struct cgroup *res_cgroup = NULL;
1370
1371         if (cset == &init_css_set) {
1372                 res_cgroup = &root->cgrp;
1373         } else if (root == &cgrp_dfl_root) {
1374                 res_cgroup = cset->dfl_cgrp;
1375         } else {
1376                 struct cgrp_cset_link *link;
1377                 lockdep_assert_held(&css_set_lock);
1378
1379                 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
1380                         struct cgroup *c = link->cgrp;
1381
1382                         if (c->root == root) {
1383                                 res_cgroup = c;
1384                                 break;
1385                         }
1386                 }
1387         }
1388
1389         BUG_ON(!res_cgroup);
1390         return res_cgroup;
1391 }
1392
1393 /*
1394  * look up cgroup associated with current task's cgroup namespace on the
1395  * specified hierarchy
1396  */
1397 static struct cgroup *
1398 current_cgns_cgroup_from_root(struct cgroup_root *root)
1399 {
1400         struct cgroup *res = NULL;
1401         struct css_set *cset;
1402
1403         lockdep_assert_held(&css_set_lock);
1404
1405         rcu_read_lock();
1406
1407         cset = current->nsproxy->cgroup_ns->root_cset;
1408         res = __cset_cgroup_from_root(cset, root);
1409
1410         rcu_read_unlock();
1411
1412         return res;
1413 }
1414
1415 /*
1416  * Look up cgroup associated with current task's cgroup namespace on the default
1417  * hierarchy.
1418  *
1419  * Unlike current_cgns_cgroup_from_root(), this doesn't need locks:
1420  * - Internal rcu_read_lock is unnecessary because we don't dereference any rcu
1421  *   pointers.
1422  * - css_set_lock is not needed because we just read cset->dfl_cgrp.
1423  * - As a bonus returned cgrp is pinned with the current because it cannot
1424  *   switch cgroup_ns asynchronously.
1425  */
1426 static struct cgroup *current_cgns_cgroup_dfl(void)
1427 {
1428         struct css_set *cset;
1429
1430         if (current->nsproxy) {
1431                 cset = current->nsproxy->cgroup_ns->root_cset;
1432                 return __cset_cgroup_from_root(cset, &cgrp_dfl_root);
1433         } else {
1434                 /*
1435                  * NOTE: This function may be called from bpf_cgroup_from_id()
1436                  * on a task which has already passed exit_task_namespaces() and
1437                  * nsproxy == NULL. Fall back to cgrp_dfl_root which will make all
1438                  * cgroups visible for lookups.
1439                  */
1440                 return &cgrp_dfl_root.cgrp;
1441         }
1442 }
1443
1444 /* look up cgroup associated with given css_set on the specified hierarchy */
1445 static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
1446                                             struct cgroup_root *root)
1447 {
1448         lockdep_assert_held(&cgroup_mutex);
1449         lockdep_assert_held(&css_set_lock);
1450
1451         return __cset_cgroup_from_root(cset, root);
1452 }
1453
1454 /*
1455  * Return the cgroup for "task" from the given hierarchy. Must be
1456  * called with cgroup_mutex and css_set_lock held.
1457  */
1458 struct cgroup *task_cgroup_from_root(struct task_struct *task,
1459                                      struct cgroup_root *root)
1460 {
1461         /*
1462          * No need to lock the task - since we hold css_set_lock the
1463          * task can't change groups.
1464          */
1465         return cset_cgroup_from_root(task_css_set(task), root);
1466 }
1467
1468 /*
1469  * A task must hold cgroup_mutex to modify cgroups.
1470  *
1471  * Any task can increment and decrement the count field without lock.
1472  * So in general, code holding cgroup_mutex can't rely on the count
1473  * field not changing.  However, if the count goes to zero, then only
1474  * cgroup_attach_task() can increment it again.  Because a count of zero
1475  * means that no tasks are currently attached, therefore there is no
1476  * way a task attached to that cgroup can fork (the other way to
1477  * increment the count).  So code holding cgroup_mutex can safely
1478  * assume that if the count is zero, it will stay zero. Similarly, if
1479  * a task holds cgroup_mutex on a cgroup with zero count, it
1480  * knows that the cgroup won't be removed, as cgroup_rmdir()
1481  * needs that mutex.
1482  *
1483  * A cgroup can only be deleted if both its 'count' of using tasks
1484  * is zero, and its list of 'children' cgroups is empty.  Since all
1485  * tasks in the system use _some_ cgroup, and since there is always at
1486  * least one task in the system (init, pid == 1), therefore, root cgroup
1487  * always has either children cgroups and/or using tasks.  So we don't
1488  * need a special hack to ensure that root cgroup cannot be deleted.
1489  *
1490  * P.S.  One more locking exception.  RCU is used to guard the
1491  * update of a tasks cgroup pointer by cgroup_attach_task()
1492  */
1493
1494 static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
1495
1496 static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
1497                               char *buf)
1498 {
1499         struct cgroup_subsys *ss = cft->ss;
1500
1501         if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
1502             !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
1503                 const char *dbg = (cft->flags & CFTYPE_DEBUG) ? ".__DEBUG__." : "";
1504
1505                 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s%s.%s",
1506                          dbg, cgroup_on_dfl(cgrp) ? ss->name : ss->legacy_name,
1507                          cft->name);
1508         } else {
1509                 strscpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
1510         }
1511         return buf;
1512 }
1513
1514 /**
1515  * cgroup_file_mode - deduce file mode of a control file
1516  * @cft: the control file in question
1517  *
1518  * S_IRUGO for read, S_IWUSR for write.
1519  */
1520 static umode_t cgroup_file_mode(const struct cftype *cft)
1521 {
1522         umode_t mode = 0;
1523
1524         if (cft->read_u64 || cft->read_s64 || cft->seq_show)
1525                 mode |= S_IRUGO;
1526
1527         if (cft->write_u64 || cft->write_s64 || cft->write) {
1528                 if (cft->flags & CFTYPE_WORLD_WRITABLE)
1529                         mode |= S_IWUGO;
1530                 else
1531                         mode |= S_IWUSR;
1532         }
1533
1534         return mode;
1535 }
1536
1537 /**
1538  * cgroup_calc_subtree_ss_mask - calculate subtree_ss_mask
1539  * @subtree_control: the new subtree_control mask to consider
1540  * @this_ss_mask: available subsystems
1541  *
1542  * On the default hierarchy, a subsystem may request other subsystems to be
1543  * enabled together through its ->depends_on mask.  In such cases, more
1544  * subsystems than specified in "cgroup.subtree_control" may be enabled.
1545  *
1546  * This function calculates which subsystems need to be enabled if
1547  * @subtree_control is to be applied while restricted to @this_ss_mask.
1548  */
1549 static u16 cgroup_calc_subtree_ss_mask(u16 subtree_control, u16 this_ss_mask)
1550 {
1551         u16 cur_ss_mask = subtree_control;
1552         struct cgroup_subsys *ss;
1553         int ssid;
1554
1555         lockdep_assert_held(&cgroup_mutex);
1556
1557         cur_ss_mask |= cgrp_dfl_implicit_ss_mask;
1558
1559         while (true) {
1560                 u16 new_ss_mask = cur_ss_mask;
1561
1562                 do_each_subsys_mask(ss, ssid, cur_ss_mask) {
1563                         new_ss_mask |= ss->depends_on;
1564                 } while_each_subsys_mask();
1565
1566                 /*
1567                  * Mask out subsystems which aren't available.  This can
1568                  * happen only if some depended-upon subsystems were bound
1569                  * to non-default hierarchies.
1570                  */
1571                 new_ss_mask &= this_ss_mask;
1572
1573                 if (new_ss_mask == cur_ss_mask)
1574                         break;
1575                 cur_ss_mask = new_ss_mask;
1576         }
1577
1578         return cur_ss_mask;
1579 }
1580
1581 /**
1582  * cgroup_kn_unlock - unlocking helper for cgroup kernfs methods
1583  * @kn: the kernfs_node being serviced
1584  *
1585  * This helper undoes cgroup_kn_lock_live() and should be invoked before
1586  * the method finishes if locking succeeded.  Note that once this function
1587  * returns the cgroup returned by cgroup_kn_lock_live() may become
1588  * inaccessible any time.  If the caller intends to continue to access the
1589  * cgroup, it should pin it before invoking this function.
1590  */
1591 void cgroup_kn_unlock(struct kernfs_node *kn)
1592 {
1593         struct cgroup *cgrp;
1594
1595         if (kernfs_type(kn) == KERNFS_DIR)
1596                 cgrp = kn->priv;
1597         else
1598                 cgrp = kn->parent->priv;
1599
1600         cgroup_unlock();
1601
1602         kernfs_unbreak_active_protection(kn);
1603         cgroup_put(cgrp);
1604 }
1605
1606 /**
1607  * cgroup_kn_lock_live - locking helper for cgroup kernfs methods
1608  * @kn: the kernfs_node being serviced
1609  * @drain_offline: perform offline draining on the cgroup
1610  *
1611  * This helper is to be used by a cgroup kernfs method currently servicing
1612  * @kn.  It breaks the active protection, performs cgroup locking and
1613  * verifies that the associated cgroup is alive.  Returns the cgroup if
1614  * alive; otherwise, %NULL.  A successful return should be undone by a
1615  * matching cgroup_kn_unlock() invocation.  If @drain_offline is %true, the
1616  * cgroup is drained of offlining csses before return.
1617  *
1618  * Any cgroup kernfs method implementation which requires locking the
1619  * associated cgroup should use this helper.  It avoids nesting cgroup
1620  * locking under kernfs active protection and allows all kernfs operations
1621  * including self-removal.
1622  */
1623 struct cgroup *cgroup_kn_lock_live(struct kernfs_node *kn, bool drain_offline)
1624 {
1625         struct cgroup *cgrp;
1626
1627         if (kernfs_type(kn) == KERNFS_DIR)
1628                 cgrp = kn->priv;
1629         else
1630                 cgrp = kn->parent->priv;
1631
1632         /*
1633          * We're gonna grab cgroup_mutex which nests outside kernfs
1634          * active_ref.  cgroup liveliness check alone provides enough
1635          * protection against removal.  Ensure @cgrp stays accessible and
1636          * break the active_ref protection.
1637          */
1638         if (!cgroup_tryget(cgrp))
1639                 return NULL;
1640         kernfs_break_active_protection(kn);
1641
1642         if (drain_offline)
1643                 cgroup_lock_and_drain_offline(cgrp);
1644         else
1645                 cgroup_lock();
1646
1647         if (!cgroup_is_dead(cgrp))
1648                 return cgrp;
1649
1650         cgroup_kn_unlock(kn);
1651         return NULL;
1652 }
1653
1654 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
1655 {
1656         char name[CGROUP_FILE_NAME_MAX];
1657
1658         lockdep_assert_held(&cgroup_mutex);
1659
1660         if (cft->file_offset) {
1661                 struct cgroup_subsys_state *css = cgroup_css(cgrp, cft->ss);
1662                 struct cgroup_file *cfile = (void *)css + cft->file_offset;
1663
1664                 spin_lock_irq(&cgroup_file_kn_lock);
1665                 cfile->kn = NULL;
1666                 spin_unlock_irq(&cgroup_file_kn_lock);
1667
1668                 del_timer_sync(&cfile->notify_timer);
1669         }
1670
1671         kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
1672 }
1673
1674 /**
1675  * css_clear_dir - remove subsys files in a cgroup directory
1676  * @css: target css
1677  */
1678 static void css_clear_dir(struct cgroup_subsys_state *css)
1679 {
1680         struct cgroup *cgrp = css->cgroup;
1681         struct cftype *cfts;
1682
1683         if (!(css->flags & CSS_VISIBLE))
1684                 return;
1685
1686         css->flags &= ~CSS_VISIBLE;
1687
1688         if (!css->ss) {
1689                 if (cgroup_on_dfl(cgrp)) {
1690                         cgroup_addrm_files(css, cgrp,
1691                                            cgroup_base_files, false);
1692                         if (cgroup_psi_enabled())
1693                                 cgroup_addrm_files(css, cgrp,
1694                                                    cgroup_psi_files, false);
1695                 } else {
1696                         cgroup_addrm_files(css, cgrp,
1697                                            cgroup1_base_files, false);
1698                 }
1699         } else {
1700                 list_for_each_entry(cfts, &css->ss->cfts, node)
1701                         cgroup_addrm_files(css, cgrp, cfts, false);
1702         }
1703 }
1704
1705 /**
1706  * css_populate_dir - create subsys files in a cgroup directory
1707  * @css: target css
1708  *
1709  * On failure, no file is added.
1710  */
1711 static int css_populate_dir(struct cgroup_subsys_state *css)
1712 {
1713         struct cgroup *cgrp = css->cgroup;
1714         struct cftype *cfts, *failed_cfts;
1715         int ret;
1716
1717         if (css->flags & CSS_VISIBLE)
1718                 return 0;
1719
1720         if (!css->ss) {
1721                 if (cgroup_on_dfl(cgrp)) {
1722                         ret = cgroup_addrm_files(&cgrp->self, cgrp,
1723                                                  cgroup_base_files, true);
1724                         if (ret < 0)
1725                                 return ret;
1726
1727                         if (cgroup_psi_enabled()) {
1728                                 ret = cgroup_addrm_files(&cgrp->self, cgrp,
1729                                                          cgroup_psi_files, true);
1730                                 if (ret < 0)
1731                                         return ret;
1732                         }
1733                 } else {
1734                         cgroup_addrm_files(css, cgrp,
1735                                            cgroup1_base_files, true);
1736                 }
1737         } else {
1738                 list_for_each_entry(cfts, &css->ss->cfts, node) {
1739                         ret = cgroup_addrm_files(css, cgrp, cfts, true);
1740                         if (ret < 0) {
1741                                 failed_cfts = cfts;
1742                                 goto err;
1743                         }
1744                 }
1745         }
1746
1747         css->flags |= CSS_VISIBLE;
1748
1749         return 0;
1750 err:
1751         list_for_each_entry(cfts, &css->ss->cfts, node) {
1752                 if (cfts == failed_cfts)
1753                         break;
1754                 cgroup_addrm_files(css, cgrp, cfts, false);
1755         }
1756         return ret;
1757 }
1758
1759 int rebind_subsystems(struct cgroup_root *dst_root, u16 ss_mask)
1760 {
1761         struct cgroup *dcgrp = &dst_root->cgrp;
1762         struct cgroup_subsys *ss;
1763         int ssid, ret;
1764         u16 dfl_disable_ss_mask = 0;
1765
1766         lockdep_assert_held(&cgroup_mutex);
1767
1768         do_each_subsys_mask(ss, ssid, ss_mask) {
1769                 /*
1770                  * If @ss has non-root csses attached to it, can't move.
1771                  * If @ss is an implicit controller, it is exempt from this
1772                  * rule and can be stolen.
1773                  */
1774                 if (css_next_child(NULL, cgroup_css(&ss->root->cgrp, ss)) &&
1775                     !ss->implicit_on_dfl)
1776                         return -EBUSY;
1777
1778                 /* can't move between two non-dummy roots either */
1779                 if (ss->root != &cgrp_dfl_root && dst_root != &cgrp_dfl_root)
1780                         return -EBUSY;
1781
1782                 /*
1783                  * Collect ssid's that need to be disabled from default
1784                  * hierarchy.
1785                  */
1786                 if (ss->root == &cgrp_dfl_root)
1787                         dfl_disable_ss_mask |= 1 << ssid;
1788
1789         } while_each_subsys_mask();
1790
1791         if (dfl_disable_ss_mask) {
1792                 struct cgroup *scgrp = &cgrp_dfl_root.cgrp;
1793
1794                 /*
1795                  * Controllers from default hierarchy that need to be rebound
1796                  * are all disabled together in one go.
1797                  */
1798                 cgrp_dfl_root.subsys_mask &= ~dfl_disable_ss_mask;
1799                 WARN_ON(cgroup_apply_control(scgrp));
1800                 cgroup_finalize_control(scgrp, 0);
1801         }
1802
1803         do_each_subsys_mask(ss, ssid, ss_mask) {
1804                 struct cgroup_root *src_root = ss->root;
1805                 struct cgroup *scgrp = &src_root->cgrp;
1806                 struct cgroup_subsys_state *css = cgroup_css(scgrp, ss);
1807                 struct css_set *cset, *cset_pos;
1808                 struct css_task_iter *it;
1809
1810                 WARN_ON(!css || cgroup_css(dcgrp, ss));
1811
1812                 if (src_root != &cgrp_dfl_root) {
1813                         /* disable from the source */
1814                         src_root->subsys_mask &= ~(1 << ssid);
1815                         WARN_ON(cgroup_apply_control(scgrp));
1816                         cgroup_finalize_control(scgrp, 0);
1817                 }
1818
1819                 /* rebind */
1820                 RCU_INIT_POINTER(scgrp->subsys[ssid], NULL);
1821                 rcu_assign_pointer(dcgrp->subsys[ssid], css);
1822                 ss->root = dst_root;
1823                 css->cgroup = dcgrp;
1824
1825                 spin_lock_irq(&css_set_lock);
1826                 WARN_ON(!list_empty(&dcgrp->e_csets[ss->id]));
1827                 list_for_each_entry_safe(cset, cset_pos, &scgrp->e_csets[ss->id],
1828                                          e_cset_node[ss->id]) {
1829                         list_move_tail(&cset->e_cset_node[ss->id],
1830                                        &dcgrp->e_csets[ss->id]);
1831                         /*
1832                          * all css_sets of scgrp together in same order to dcgrp,
1833                          * patch in-flight iterators to preserve correct iteration.
1834                          * since the iterator is always advanced right away and
1835                          * finished when it->cset_pos meets it->cset_head, so only
1836                          * update it->cset_head is enough here.
1837                          */
1838                         list_for_each_entry(it, &cset->task_iters, iters_node)
1839                                 if (it->cset_head == &scgrp->e_csets[ss->id])
1840                                         it->cset_head = &dcgrp->e_csets[ss->id];
1841                 }
1842                 spin_unlock_irq(&css_set_lock);
1843
1844                 if (ss->css_rstat_flush) {
1845                         list_del_rcu(&css->rstat_css_node);
1846                         synchronize_rcu();
1847                         list_add_rcu(&css->rstat_css_node,
1848                                      &dcgrp->rstat_css_list);
1849                 }
1850
1851                 /* default hierarchy doesn't enable controllers by default */
1852                 dst_root->subsys_mask |= 1 << ssid;
1853                 if (dst_root == &cgrp_dfl_root) {
1854                         static_branch_enable(cgroup_subsys_on_dfl_key[ssid]);
1855                 } else {
1856                         dcgrp->subtree_control |= 1 << ssid;
1857                         static_branch_disable(cgroup_subsys_on_dfl_key[ssid]);
1858                 }
1859
1860                 ret = cgroup_apply_control(dcgrp);
1861                 if (ret)
1862                         pr_warn("partial failure to rebind %s controller (err=%d)\n",
1863                                 ss->name, ret);
1864
1865                 if (ss->bind)
1866                         ss->bind(css);
1867         } while_each_subsys_mask();
1868
1869         kernfs_activate(dcgrp->kn);
1870         return 0;
1871 }
1872
1873 int cgroup_show_path(struct seq_file *sf, struct kernfs_node *kf_node,
1874                      struct kernfs_root *kf_root)
1875 {
1876         int len = 0;
1877         char *buf = NULL;
1878         struct cgroup_root *kf_cgroot = cgroup_root_from_kf(kf_root);
1879         struct cgroup *ns_cgroup;
1880
1881         buf = kmalloc(PATH_MAX, GFP_KERNEL);
1882         if (!buf)
1883                 return -ENOMEM;
1884
1885         spin_lock_irq(&css_set_lock);
1886         ns_cgroup = current_cgns_cgroup_from_root(kf_cgroot);
1887         len = kernfs_path_from_node(kf_node, ns_cgroup->kn, buf, PATH_MAX);
1888         spin_unlock_irq(&css_set_lock);
1889
1890         if (len >= PATH_MAX)
1891                 len = -ERANGE;
1892         else if (len > 0) {
1893                 seq_escape(sf, buf, " \t\n\\");
1894                 len = 0;
1895         }
1896         kfree(buf);
1897         return len;
1898 }
1899
1900 enum cgroup2_param {
1901         Opt_nsdelegate,
1902         Opt_favordynmods,
1903         Opt_memory_localevents,
1904         Opt_memory_recursiveprot,
1905         nr__cgroup2_params
1906 };
1907
1908 static const struct fs_parameter_spec cgroup2_fs_parameters[] = {
1909         fsparam_flag("nsdelegate",              Opt_nsdelegate),
1910         fsparam_flag("favordynmods",            Opt_favordynmods),
1911         fsparam_flag("memory_localevents",      Opt_memory_localevents),
1912         fsparam_flag("memory_recursiveprot",    Opt_memory_recursiveprot),
1913         {}
1914 };
1915
1916 static int cgroup2_parse_param(struct fs_context *fc, struct fs_parameter *param)
1917 {
1918         struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
1919         struct fs_parse_result result;
1920         int opt;
1921
1922         opt = fs_parse(fc, cgroup2_fs_parameters, param, &result);
1923         if (opt < 0)
1924                 return opt;
1925
1926         switch (opt) {
1927         case Opt_nsdelegate:
1928                 ctx->flags |= CGRP_ROOT_NS_DELEGATE;
1929                 return 0;
1930         case Opt_favordynmods:
1931                 ctx->flags |= CGRP_ROOT_FAVOR_DYNMODS;
1932                 return 0;
1933         case Opt_memory_localevents:
1934                 ctx->flags |= CGRP_ROOT_MEMORY_LOCAL_EVENTS;
1935                 return 0;
1936         case Opt_memory_recursiveprot:
1937                 ctx->flags |= CGRP_ROOT_MEMORY_RECURSIVE_PROT;
1938                 return 0;
1939         }
1940         return -EINVAL;
1941 }
1942
1943 static void apply_cgroup_root_flags(unsigned int root_flags)
1944 {
1945         if (current->nsproxy->cgroup_ns == &init_cgroup_ns) {
1946                 if (root_flags & CGRP_ROOT_NS_DELEGATE)
1947                         cgrp_dfl_root.flags |= CGRP_ROOT_NS_DELEGATE;
1948                 else
1949                         cgrp_dfl_root.flags &= ~CGRP_ROOT_NS_DELEGATE;
1950
1951                 cgroup_favor_dynmods(&cgrp_dfl_root,
1952                                      root_flags & CGRP_ROOT_FAVOR_DYNMODS);
1953
1954                 if (root_flags & CGRP_ROOT_MEMORY_LOCAL_EVENTS)
1955                         cgrp_dfl_root.flags |= CGRP_ROOT_MEMORY_LOCAL_EVENTS;
1956                 else
1957                         cgrp_dfl_root.flags &= ~CGRP_ROOT_MEMORY_LOCAL_EVENTS;
1958
1959                 if (root_flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT)
1960                         cgrp_dfl_root.flags |= CGRP_ROOT_MEMORY_RECURSIVE_PROT;
1961                 else
1962                         cgrp_dfl_root.flags &= ~CGRP_ROOT_MEMORY_RECURSIVE_PROT;
1963         }
1964 }
1965
1966 static int cgroup_show_options(struct seq_file *seq, struct kernfs_root *kf_root)
1967 {
1968         if (cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE)
1969                 seq_puts(seq, ",nsdelegate");
1970         if (cgrp_dfl_root.flags & CGRP_ROOT_FAVOR_DYNMODS)
1971                 seq_puts(seq, ",favordynmods");
1972         if (cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_LOCAL_EVENTS)
1973                 seq_puts(seq, ",memory_localevents");
1974         if (cgrp_dfl_root.flags & CGRP_ROOT_MEMORY_RECURSIVE_PROT)
1975                 seq_puts(seq, ",memory_recursiveprot");
1976         return 0;
1977 }
1978
1979 static int cgroup_reconfigure(struct fs_context *fc)
1980 {
1981         struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
1982
1983         apply_cgroup_root_flags(ctx->flags);
1984         return 0;
1985 }
1986
1987 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1988 {
1989         struct cgroup_subsys *ss;
1990         int ssid;
1991
1992         INIT_LIST_HEAD(&cgrp->self.sibling);
1993         INIT_LIST_HEAD(&cgrp->self.children);
1994         INIT_LIST_HEAD(&cgrp->cset_links);
1995         INIT_LIST_HEAD(&cgrp->pidlists);
1996         mutex_init(&cgrp->pidlist_mutex);
1997         cgrp->self.cgroup = cgrp;
1998         cgrp->self.flags |= CSS_ONLINE;
1999         cgrp->dom_cgrp = cgrp;
2000         cgrp->max_descendants = INT_MAX;
2001         cgrp->max_depth = INT_MAX;
2002         INIT_LIST_HEAD(&cgrp->rstat_css_list);
2003         prev_cputime_init(&cgrp->prev_cputime);
2004
2005         for_each_subsys(ss, ssid)
2006                 INIT_LIST_HEAD(&cgrp->e_csets[ssid]);
2007
2008         init_waitqueue_head(&cgrp->offline_waitq);
2009         INIT_WORK(&cgrp->release_agent_work, cgroup1_release_agent);
2010 }
2011
2012 void init_cgroup_root(struct cgroup_fs_context *ctx)
2013 {
2014         struct cgroup_root *root = ctx->root;
2015         struct cgroup *cgrp = &root->cgrp;
2016
2017         INIT_LIST_HEAD(&root->root_list);
2018         atomic_set(&root->nr_cgrps, 1);
2019         cgrp->root = root;
2020         init_cgroup_housekeeping(cgrp);
2021
2022         /* DYNMODS must be modified through cgroup_favor_dynmods() */
2023         root->flags = ctx->flags & ~CGRP_ROOT_FAVOR_DYNMODS;
2024         if (ctx->release_agent)
2025                 strscpy(root->release_agent_path, ctx->release_agent, PATH_MAX);
2026         if (ctx->name)
2027                 strscpy(root->name, ctx->name, MAX_CGROUP_ROOT_NAMELEN);
2028         if (ctx->cpuset_clone_children)
2029                 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->cgrp.flags);
2030 }
2031
2032 int cgroup_setup_root(struct cgroup_root *root, u16 ss_mask)
2033 {
2034         LIST_HEAD(tmp_links);
2035         struct cgroup *root_cgrp = &root->cgrp;
2036         struct kernfs_syscall_ops *kf_sops;
2037         struct css_set *cset;
2038         int i, ret;
2039
2040         lockdep_assert_held(&cgroup_mutex);
2041
2042         ret = percpu_ref_init(&root_cgrp->self.refcnt, css_release,
2043                               0, GFP_KERNEL);
2044         if (ret)
2045                 goto out;
2046
2047         /*
2048          * We're accessing css_set_count without locking css_set_lock here,
2049          * but that's OK - it can only be increased by someone holding
2050          * cgroup_lock, and that's us.  Later rebinding may disable
2051          * controllers on the default hierarchy and thus create new csets,
2052          * which can't be more than the existing ones.  Allocate 2x.
2053          */
2054         ret = allocate_cgrp_cset_links(2 * css_set_count, &tmp_links);
2055         if (ret)
2056                 goto cancel_ref;
2057
2058         ret = cgroup_init_root_id(root);
2059         if (ret)
2060                 goto cancel_ref;
2061
2062         kf_sops = root == &cgrp_dfl_root ?
2063                 &cgroup_kf_syscall_ops : &cgroup1_kf_syscall_ops;
2064
2065         root->kf_root = kernfs_create_root(kf_sops,
2066                                            KERNFS_ROOT_CREATE_DEACTIVATED |
2067                                            KERNFS_ROOT_SUPPORT_EXPORTOP |
2068                                            KERNFS_ROOT_SUPPORT_USER_XATTR,
2069                                            root_cgrp);
2070         if (IS_ERR(root->kf_root)) {
2071                 ret = PTR_ERR(root->kf_root);
2072                 goto exit_root_id;
2073         }
2074         root_cgrp->kn = kernfs_root_to_node(root->kf_root);
2075         WARN_ON_ONCE(cgroup_ino(root_cgrp) != 1);
2076         root_cgrp->ancestors[0] = root_cgrp;
2077
2078         ret = css_populate_dir(&root_cgrp->self);
2079         if (ret)
2080                 goto destroy_root;
2081
2082         ret = cgroup_rstat_init(root_cgrp);
2083         if (ret)
2084                 goto destroy_root;
2085
2086         ret = rebind_subsystems(root, ss_mask);
2087         if (ret)
2088                 goto exit_stats;
2089
2090         ret = cgroup_bpf_inherit(root_cgrp);
2091         WARN_ON_ONCE(ret);
2092
2093         trace_cgroup_setup_root(root);
2094
2095         /*
2096          * There must be no failure case after here, since rebinding takes
2097          * care of subsystems' refcounts, which are explicitly dropped in
2098          * the failure exit path.
2099          */
2100         list_add(&root->root_list, &cgroup_roots);
2101         cgroup_root_count++;
2102
2103         /*
2104          * Link the root cgroup in this hierarchy into all the css_set
2105          * objects.
2106          */
2107         spin_lock_irq(&css_set_lock);
2108         hash_for_each(css_set_table, i, cset, hlist) {
2109                 link_css_set(&tmp_links, cset, root_cgrp);
2110                 if (css_set_populated(cset))
2111                         cgroup_update_populated(root_cgrp, true);
2112         }
2113         spin_unlock_irq(&css_set_lock);
2114
2115         BUG_ON(!list_empty(&root_cgrp->self.children));
2116         BUG_ON(atomic_read(&root->nr_cgrps) != 1);
2117
2118         ret = 0;
2119         goto out;
2120
2121 exit_stats:
2122         cgroup_rstat_exit(root_cgrp);
2123 destroy_root:
2124         kernfs_destroy_root(root->kf_root);
2125         root->kf_root = NULL;
2126 exit_root_id:
2127         cgroup_exit_root_id(root);
2128 cancel_ref:
2129         percpu_ref_exit(&root_cgrp->self.refcnt);
2130 out:
2131         free_cgrp_cset_links(&tmp_links);
2132         return ret;
2133 }
2134
2135 int cgroup_do_get_tree(struct fs_context *fc)
2136 {
2137         struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2138         int ret;
2139
2140         ctx->kfc.root = ctx->root->kf_root;
2141         if (fc->fs_type == &cgroup2_fs_type)
2142                 ctx->kfc.magic = CGROUP2_SUPER_MAGIC;
2143         else
2144                 ctx->kfc.magic = CGROUP_SUPER_MAGIC;
2145         ret = kernfs_get_tree(fc);
2146
2147         /*
2148          * In non-init cgroup namespace, instead of root cgroup's dentry,
2149          * we return the dentry corresponding to the cgroupns->root_cgrp.
2150          */
2151         if (!ret && ctx->ns != &init_cgroup_ns) {
2152                 struct dentry *nsdentry;
2153                 struct super_block *sb = fc->root->d_sb;
2154                 struct cgroup *cgrp;
2155
2156                 cgroup_lock();
2157                 spin_lock_irq(&css_set_lock);
2158
2159                 cgrp = cset_cgroup_from_root(ctx->ns->root_cset, ctx->root);
2160
2161                 spin_unlock_irq(&css_set_lock);
2162                 cgroup_unlock();
2163
2164                 nsdentry = kernfs_node_dentry(cgrp->kn, sb);
2165                 dput(fc->root);
2166                 if (IS_ERR(nsdentry)) {
2167                         deactivate_locked_super(sb);
2168                         ret = PTR_ERR(nsdentry);
2169                         nsdentry = NULL;
2170                 }
2171                 fc->root = nsdentry;
2172         }
2173
2174         if (!ctx->kfc.new_sb_created)
2175                 cgroup_put(&ctx->root->cgrp);
2176
2177         return ret;
2178 }
2179
2180 /*
2181  * Destroy a cgroup filesystem context.
2182  */
2183 static void cgroup_fs_context_free(struct fs_context *fc)
2184 {
2185         struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2186
2187         kfree(ctx->name);
2188         kfree(ctx->release_agent);
2189         put_cgroup_ns(ctx->ns);
2190         kernfs_free_fs_context(fc);
2191         kfree(ctx);
2192 }
2193
2194 static int cgroup_get_tree(struct fs_context *fc)
2195 {
2196         struct cgroup_fs_context *ctx = cgroup_fc2context(fc);
2197         int ret;
2198
2199         WRITE_ONCE(cgrp_dfl_visible, true);
2200         cgroup_get_live(&cgrp_dfl_root.cgrp);
2201         ctx->root = &cgrp_dfl_root;
2202
2203         ret = cgroup_do_get_tree(fc);
2204         if (!ret)
2205                 apply_cgroup_root_flags(ctx->flags);
2206         return ret;
2207 }
2208
2209 static const struct fs_context_operations cgroup_fs_context_ops = {
2210         .free           = cgroup_fs_context_free,
2211         .parse_param    = cgroup2_parse_param,
2212         .get_tree       = cgroup_get_tree,
2213         .reconfigure    = cgroup_reconfigure,
2214 };
2215
2216 static const struct fs_context_operations cgroup1_fs_context_ops = {
2217         .free           = cgroup_fs_context_free,
2218         .parse_param    = cgroup1_parse_param,
2219         .get_tree       = cgroup1_get_tree,
2220         .reconfigure    = cgroup1_reconfigure,
2221 };
2222
2223 /*
2224  * Initialise the cgroup filesystem creation/reconfiguration context.  Notably,
2225  * we select the namespace we're going to use.
2226  */
2227 static int cgroup_init_fs_context(struct fs_context *fc)
2228 {
2229         struct cgroup_fs_context *ctx;
2230
2231         ctx = kzalloc(sizeof(struct cgroup_fs_context), GFP_KERNEL);
2232         if (!ctx)
2233                 return -ENOMEM;
2234
2235         ctx->ns = current->nsproxy->cgroup_ns;
2236         get_cgroup_ns(ctx->ns);
2237         fc->fs_private = &ctx->kfc;
2238         if (fc->fs_type == &cgroup2_fs_type)
2239                 fc->ops = &cgroup_fs_context_ops;
2240         else
2241                 fc->ops = &cgroup1_fs_context_ops;
2242         put_user_ns(fc->user_ns);
2243         fc->user_ns = get_user_ns(ctx->ns->user_ns);
2244         fc->global = true;
2245
2246 #ifdef CONFIG_CGROUP_FAVOR_DYNMODS
2247         ctx->flags |= CGRP_ROOT_FAVOR_DYNMODS;
2248 #endif
2249         return 0;
2250 }
2251
2252 static void cgroup_kill_sb(struct super_block *sb)
2253 {
2254         struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
2255         struct cgroup_root *root = cgroup_root_from_kf(kf_root);
2256
2257         /*
2258          * If @root doesn't have any children, start killing it.
2259          * This prevents new mounts by disabling percpu_ref_tryget_live().
2260          *
2261          * And don't kill the default root.
2262          */
2263         if (list_empty(&root->cgrp.self.children) && root != &cgrp_dfl_root &&
2264             !percpu_ref_is_dying(&root->cgrp.self.refcnt)) {
2265                 cgroup_bpf_offline(&root->cgrp);
2266                 percpu_ref_kill(&root->cgrp.self.refcnt);
2267         }
2268         cgroup_put(&root->cgrp);
2269         kernfs_kill_sb(sb);
2270 }
2271
2272 struct file_system_type cgroup_fs_type = {
2273         .name                   = "cgroup",
2274         .init_fs_context        = cgroup_init_fs_context,
2275         .parameters             = cgroup1_fs_parameters,
2276         .kill_sb                = cgroup_kill_sb,
2277         .fs_flags               = FS_USERNS_MOUNT,
2278 };
2279
2280 static struct file_system_type cgroup2_fs_type = {
2281         .name                   = "cgroup2",
2282         .init_fs_context        = cgroup_init_fs_context,
2283         .parameters             = cgroup2_fs_parameters,
2284         .kill_sb                = cgroup_kill_sb,
2285         .fs_flags               = FS_USERNS_MOUNT,
2286 };
2287
2288 #ifdef CONFIG_CPUSETS
2289 static const struct fs_context_operations cpuset_fs_context_ops = {
2290         .get_tree       = cgroup1_get_tree,
2291         .free           = cgroup_fs_context_free,
2292 };
2293
2294 /*
2295  * This is ugly, but preserves the userspace API for existing cpuset
2296  * users. If someone tries to mount the "cpuset" filesystem, we
2297  * silently switch it to mount "cgroup" instead
2298  */
2299 static int cpuset_init_fs_context(struct fs_context *fc)
2300 {
2301         char *agent = kstrdup("/sbin/cpuset_release_agent", GFP_USER);
2302         struct cgroup_fs_context *ctx;
2303         int err;
2304
2305         err = cgroup_init_fs_context(fc);
2306         if (err) {
2307                 kfree(agent);
2308                 return err;
2309         }
2310
2311         fc->ops = &cpuset_fs_context_ops;
2312
2313         ctx = cgroup_fc2context(fc);
2314         ctx->subsys_mask = 1 << cpuset_cgrp_id;
2315         ctx->flags |= CGRP_ROOT_NOPREFIX;
2316         ctx->release_agent = agent;
2317
2318         get_filesystem(&cgroup_fs_type);
2319         put_filesystem(fc->fs_type);
2320         fc->fs_type = &cgroup_fs_type;
2321
2322         return 0;
2323 }
2324
2325 static struct file_system_type cpuset_fs_type = {
2326         .name                   = "cpuset",
2327         .init_fs_context        = cpuset_init_fs_context,
2328         .fs_flags               = FS_USERNS_MOUNT,
2329 };
2330 #endif
2331
2332 int cgroup_path_ns_locked(struct cgroup *cgrp, char *buf, size_t buflen,
2333                           struct cgroup_namespace *ns)
2334 {
2335         struct cgroup *root = cset_cgroup_from_root(ns->root_cset, cgrp->root);
2336
2337         return kernfs_path_from_node(cgrp->kn, root->kn, buf, buflen);
2338 }
2339
2340 int cgroup_path_ns(struct cgroup *cgrp, char *buf, size_t buflen,
2341                    struct cgroup_namespace *ns)
2342 {
2343         int ret;
2344
2345         cgroup_lock();
2346         spin_lock_irq(&css_set_lock);
2347
2348         ret = cgroup_path_ns_locked(cgrp, buf, buflen, ns);
2349
2350         spin_unlock_irq(&css_set_lock);
2351         cgroup_unlock();
2352
2353         return ret;
2354 }
2355 EXPORT_SYMBOL_GPL(cgroup_path_ns);
2356
2357 /**
2358  * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
2359  * @task: target task
2360  * @buf: the buffer to write the path into
2361  * @buflen: the length of the buffer
2362  *
2363  * Determine @task's cgroup on the first (the one with the lowest non-zero
2364  * hierarchy_id) cgroup hierarchy and copy its path into @buf.  This
2365  * function grabs cgroup_mutex and shouldn't be used inside locks used by
2366  * cgroup controller callbacks.
2367  *
2368  * Return value is the same as kernfs_path().
2369  */
2370 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
2371 {
2372         struct cgroup_root *root;
2373         struct cgroup *cgrp;
2374         int hierarchy_id = 1;
2375         int ret;
2376
2377         cgroup_lock();
2378         spin_lock_irq(&css_set_lock);
2379
2380         root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
2381
2382         if (root) {
2383                 cgrp = task_cgroup_from_root(task, root);
2384                 ret = cgroup_path_ns_locked(cgrp, buf, buflen, &init_cgroup_ns);
2385         } else {
2386                 /* if no hierarchy exists, everyone is in "/" */
2387                 ret = strscpy(buf, "/", buflen);
2388         }
2389
2390         spin_unlock_irq(&css_set_lock);
2391         cgroup_unlock();
2392         return ret;
2393 }
2394 EXPORT_SYMBOL_GPL(task_cgroup_path);
2395
2396 /**
2397  * cgroup_attach_lock - Lock for ->attach()
2398  * @lock_threadgroup: whether to down_write cgroup_threadgroup_rwsem
2399  *
2400  * cgroup migration sometimes needs to stabilize threadgroups against forks and
2401  * exits by write-locking cgroup_threadgroup_rwsem. However, some ->attach()
2402  * implementations (e.g. cpuset), also need to disable CPU hotplug.
2403  * Unfortunately, letting ->attach() operations acquire cpus_read_lock() can
2404  * lead to deadlocks.
2405  *
2406  * Bringing up a CPU may involve creating and destroying tasks which requires
2407  * read-locking threadgroup_rwsem, so threadgroup_rwsem nests inside
2408  * cpus_read_lock(). If we call an ->attach() which acquires the cpus lock while
2409  * write-locking threadgroup_rwsem, the locking order is reversed and we end up
2410  * waiting for an on-going CPU hotplug operation which in turn is waiting for
2411  * the threadgroup_rwsem to be released to create new tasks. For more details:
2412  *
2413  *   http://lkml.kernel.org/r/20220711174629.uehfmqegcwn2lqzu@wubuntu
2414  *
2415  * Resolve the situation by always acquiring cpus_read_lock() before optionally
2416  * write-locking cgroup_threadgroup_rwsem. This allows ->attach() to assume that
2417  * CPU hotplug is disabled on entry.
2418  */
2419 void cgroup_attach_lock(bool lock_threadgroup)
2420 {
2421         cpus_read_lock();
2422         if (lock_threadgroup)
2423                 percpu_down_write(&cgroup_threadgroup_rwsem);
2424 }
2425
2426 /**
2427  * cgroup_attach_unlock - Undo cgroup_attach_lock()
2428  * @lock_threadgroup: whether to up_write cgroup_threadgroup_rwsem
2429  */
2430 void cgroup_attach_unlock(bool lock_threadgroup)
2431 {
2432         if (lock_threadgroup)
2433                 percpu_up_write(&cgroup_threadgroup_rwsem);
2434         cpus_read_unlock();
2435 }
2436
2437 /**
2438  * cgroup_migrate_add_task - add a migration target task to a migration context
2439  * @task: target task
2440  * @mgctx: target migration context
2441  *
2442  * Add @task, which is a migration target, to @mgctx->tset.  This function
2443  * becomes noop if @task doesn't need to be migrated.  @task's css_set
2444  * should have been added as a migration source and @task->cg_list will be
2445  * moved from the css_set's tasks list to mg_tasks one.
2446  */
2447 static void cgroup_migrate_add_task(struct task_struct *task,
2448                                     struct cgroup_mgctx *mgctx)
2449 {
2450         struct css_set *cset;
2451
2452         lockdep_assert_held(&css_set_lock);
2453
2454         /* @task either already exited or can't exit until the end */
2455         if (task->flags & PF_EXITING)
2456                 return;
2457
2458         /* cgroup_threadgroup_rwsem protects racing against forks */
2459         WARN_ON_ONCE(list_empty(&task->cg_list));
2460
2461         cset = task_css_set(task);
2462         if (!cset->mg_src_cgrp)
2463                 return;
2464
2465         mgctx->tset.nr_tasks++;
2466
2467         list_move_tail(&task->cg_list, &cset->mg_tasks);
2468         if (list_empty(&cset->mg_node))
2469                 list_add_tail(&cset->mg_node,
2470                               &mgctx->tset.src_csets);
2471         if (list_empty(&cset->mg_dst_cset->mg_node))
2472                 list_add_tail(&cset->mg_dst_cset->mg_node,
2473                               &mgctx->tset.dst_csets);
2474 }
2475
2476 /**
2477  * cgroup_taskset_first - reset taskset and return the first task
2478  * @tset: taskset of interest
2479  * @dst_cssp: output variable for the destination css
2480  *
2481  * @tset iteration is initialized and the first task is returned.
2482  */
2483 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset,
2484                                          struct cgroup_subsys_state **dst_cssp)
2485 {
2486         tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
2487         tset->cur_task = NULL;
2488
2489         return cgroup_taskset_next(tset, dst_cssp);
2490 }
2491
2492 /**
2493  * cgroup_taskset_next - iterate to the next task in taskset
2494  * @tset: taskset of interest
2495  * @dst_cssp: output variable for the destination css
2496  *
2497  * Return the next task in @tset.  Iteration must have been initialized
2498  * with cgroup_taskset_first().
2499  */
2500 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset,
2501                                         struct cgroup_subsys_state **dst_cssp)
2502 {
2503         struct css_set *cset = tset->cur_cset;
2504         struct task_struct *task = tset->cur_task;
2505
2506         while (CGROUP_HAS_SUBSYS_CONFIG && &cset->mg_node != tset->csets) {
2507                 if (!task)
2508                         task = list_first_entry(&cset->mg_tasks,
2509                                                 struct task_struct, cg_list);
2510                 else
2511                         task = list_next_entry(task, cg_list);
2512
2513                 if (&task->cg_list != &cset->mg_tasks) {
2514                         tset->cur_cset = cset;
2515                         tset->cur_task = task;
2516
2517                         /*
2518                          * This function may be called both before and
2519                          * after cgroup_migrate_execute().  The two cases
2520                          * can be distinguished by looking at whether @cset
2521                          * has its ->mg_dst_cset set.
2522                          */
2523                         if (cset->mg_dst_cset)
2524                                 *dst_cssp = cset->mg_dst_cset->subsys[tset->ssid];
2525                         else
2526                                 *dst_cssp = cset->subsys[tset->ssid];
2527
2528                         return task;
2529                 }
2530
2531                 cset = list_next_entry(cset, mg_node);
2532                 task = NULL;
2533         }
2534
2535         return NULL;
2536 }
2537
2538 /**
2539  * cgroup_migrate_execute - migrate a taskset
2540  * @mgctx: migration context
2541  *
2542  * Migrate tasks in @mgctx as setup by migration preparation functions.
2543  * This function fails iff one of the ->can_attach callbacks fails and
2544  * guarantees that either all or none of the tasks in @mgctx are migrated.
2545  * @mgctx is consumed regardless of success.
2546  */
2547 static int cgroup_migrate_execute(struct cgroup_mgctx *mgctx)
2548 {
2549         struct cgroup_taskset *tset = &mgctx->tset;
2550         struct cgroup_subsys *ss;
2551         struct task_struct *task, *tmp_task;
2552         struct css_set *cset, *tmp_cset;
2553         int ssid, failed_ssid, ret;
2554
2555         /* check that we can legitimately attach to the cgroup */
2556         if (tset->nr_tasks) {
2557                 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2558                         if (ss->can_attach) {
2559                                 tset->ssid = ssid;
2560                                 ret = ss->can_attach(tset);
2561                                 if (ret) {
2562                                         failed_ssid = ssid;
2563                                         goto out_cancel_attach;
2564                                 }
2565                         }
2566                 } while_each_subsys_mask();
2567         }
2568
2569         /*
2570          * Now that we're guaranteed success, proceed to move all tasks to
2571          * the new cgroup.  There are no failure cases after here, so this
2572          * is the commit point.
2573          */
2574         spin_lock_irq(&css_set_lock);
2575         list_for_each_entry(cset, &tset->src_csets, mg_node) {
2576                 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list) {
2577                         struct css_set *from_cset = task_css_set(task);
2578                         struct css_set *to_cset = cset->mg_dst_cset;
2579
2580                         get_css_set(to_cset);
2581                         to_cset->nr_tasks++;
2582                         css_set_move_task(task, from_cset, to_cset, true);
2583                         from_cset->nr_tasks--;
2584                         /*
2585                          * If the source or destination cgroup is frozen,
2586                          * the task might require to change its state.
2587                          */
2588                         cgroup_freezer_migrate_task(task, from_cset->dfl_cgrp,
2589                                                     to_cset->dfl_cgrp);
2590                         put_css_set_locked(from_cset);
2591
2592                 }
2593         }
2594         spin_unlock_irq(&css_set_lock);
2595
2596         /*
2597          * Migration is committed, all target tasks are now on dst_csets.
2598          * Nothing is sensitive to fork() after this point.  Notify
2599          * controllers that migration is complete.
2600          */
2601         tset->csets = &tset->dst_csets;
2602
2603         if (tset->nr_tasks) {
2604                 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2605                         if (ss->attach) {
2606                                 tset->ssid = ssid;
2607                                 ss->attach(tset);
2608                         }
2609                 } while_each_subsys_mask();
2610         }
2611
2612         ret = 0;
2613         goto out_release_tset;
2614
2615 out_cancel_attach:
2616         if (tset->nr_tasks) {
2617                 do_each_subsys_mask(ss, ssid, mgctx->ss_mask) {
2618                         if (ssid == failed_ssid)
2619                                 break;
2620                         if (ss->cancel_attach) {
2621                                 tset->ssid = ssid;
2622                                 ss->cancel_attach(tset);
2623                         }
2624                 } while_each_subsys_mask();
2625         }
2626 out_release_tset:
2627         spin_lock_irq(&css_set_lock);
2628         list_splice_init(&tset->dst_csets, &tset->src_csets);
2629         list_for_each_entry_safe(cset, tmp_cset, &tset->src_csets, mg_node) {
2630                 list_splice_tail_init(&cset->mg_tasks, &cset->tasks);
2631                 list_del_init(&cset->mg_node);
2632         }
2633         spin_unlock_irq(&css_set_lock);
2634
2635         /*
2636          * Re-initialize the cgroup_taskset structure in case it is reused
2637          * again in another cgroup_migrate_add_task()/cgroup_migrate_execute()
2638          * iteration.
2639          */
2640         tset->nr_tasks = 0;
2641         tset->csets    = &tset->src_csets;
2642         return ret;
2643 }
2644
2645 /**
2646  * cgroup_migrate_vet_dst - verify whether a cgroup can be migration destination
2647  * @dst_cgrp: destination cgroup to test
2648  *
2649  * On the default hierarchy, except for the mixable, (possible) thread root
2650  * and threaded cgroups, subtree_control must be zero for migration
2651  * destination cgroups with tasks so that child cgroups don't compete
2652  * against tasks.
2653  */
2654 int cgroup_migrate_vet_dst(struct cgroup *dst_cgrp)
2655 {
2656         /* v1 doesn't have any restriction */
2657         if (!cgroup_on_dfl(dst_cgrp))
2658                 return 0;
2659
2660         /* verify @dst_cgrp can host resources */
2661         if (!cgroup_is_valid_domain(dst_cgrp->dom_cgrp))
2662                 return -EOPNOTSUPP;
2663
2664         /*
2665          * If @dst_cgrp is already or can become a thread root or is
2666          * threaded, it doesn't matter.
2667          */
2668         if (cgroup_can_be_thread_root(dst_cgrp) || cgroup_is_threaded(dst_cgrp))
2669                 return 0;
2670
2671         /* apply no-internal-process constraint */
2672         if (dst_cgrp->subtree_control)
2673                 return -EBUSY;
2674
2675         return 0;
2676 }
2677
2678 /**
2679  * cgroup_migrate_finish - cleanup after attach
2680  * @mgctx: migration context
2681  *
2682  * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst().  See
2683  * those functions for details.
2684  */
2685 void cgroup_migrate_finish(struct cgroup_mgctx *mgctx)
2686 {
2687         struct css_set *cset, *tmp_cset;
2688
2689         lockdep_assert_held(&cgroup_mutex);
2690
2691         spin_lock_irq(&css_set_lock);
2692
2693         list_for_each_entry_safe(cset, tmp_cset, &mgctx->preloaded_src_csets,
2694                                  mg_src_preload_node) {
2695                 cset->mg_src_cgrp = NULL;
2696                 cset->mg_dst_cgrp = NULL;
2697                 cset->mg_dst_cset = NULL;
2698                 list_del_init(&cset->mg_src_preload_node);
2699                 put_css_set_locked(cset);
2700         }
2701
2702         list_for_each_entry_safe(cset, tmp_cset, &mgctx->preloaded_dst_csets,
2703                                  mg_dst_preload_node) {
2704                 cset->mg_src_cgrp = NULL;
2705                 cset->mg_dst_cgrp = NULL;
2706                 cset->mg_dst_cset = NULL;
2707                 list_del_init(&cset->mg_dst_preload_node);
2708                 put_css_set_locked(cset);
2709         }
2710
2711         spin_unlock_irq(&css_set_lock);
2712 }
2713
2714 /**
2715  * cgroup_migrate_add_src - add a migration source css_set
2716  * @src_cset: the source css_set to add
2717  * @dst_cgrp: the destination cgroup
2718  * @mgctx: migration context
2719  *
2720  * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp.  Pin
2721  * @src_cset and add it to @mgctx->src_csets, which should later be cleaned
2722  * up by cgroup_migrate_finish().
2723  *
2724  * This function may be called without holding cgroup_threadgroup_rwsem
2725  * even if the target is a process.  Threads may be created and destroyed
2726  * but as long as cgroup_mutex is not dropped, no new css_set can be put
2727  * into play and the preloaded css_sets are guaranteed to cover all
2728  * migrations.
2729  */
2730 void cgroup_migrate_add_src(struct css_set *src_cset,
2731                             struct cgroup *dst_cgrp,
2732                             struct cgroup_mgctx *mgctx)
2733 {
2734         struct cgroup *src_cgrp;
2735
2736         lockdep_assert_held(&cgroup_mutex);
2737         lockdep_assert_held(&css_set_lock);
2738
2739         /*
2740          * If ->dead, @src_set is associated with one or more dead cgroups
2741          * and doesn't contain any migratable tasks.  Ignore it early so
2742          * that the rest of migration path doesn't get confused by it.
2743          */
2744         if (src_cset->dead)
2745                 return;
2746
2747         if (!list_empty(&src_cset->mg_src_preload_node))
2748                 return;
2749
2750         src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
2751
2752         WARN_ON(src_cset->mg_src_cgrp);
2753         WARN_ON(src_cset->mg_dst_cgrp);
2754         WARN_ON(!list_empty(&src_cset->mg_tasks));
2755         WARN_ON(!list_empty(&src_cset->mg_node));
2756
2757         src_cset->mg_src_cgrp = src_cgrp;
2758         src_cset->mg_dst_cgrp = dst_cgrp;
2759         get_css_set(src_cset);
2760         list_add_tail(&src_cset->mg_src_preload_node, &mgctx->preloaded_src_csets);
2761 }
2762
2763 /**
2764  * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
2765  * @mgctx: migration context
2766  *
2767  * Tasks are about to be moved and all the source css_sets have been
2768  * preloaded to @mgctx->preloaded_src_csets.  This function looks up and
2769  * pins all destination css_sets, links each to its source, and append them
2770  * to @mgctx->preloaded_dst_csets.
2771  *
2772  * This function must be called after cgroup_migrate_add_src() has been
2773  * called on each migration source css_set.  After migration is performed
2774  * using cgroup_migrate(), cgroup_migrate_finish() must be called on
2775  * @mgctx.
2776  */
2777 int cgroup_migrate_prepare_dst(struct cgroup_mgctx *mgctx)
2778 {
2779         struct css_set *src_cset, *tmp_cset;
2780
2781         lockdep_assert_held(&cgroup_mutex);
2782
2783         /* look up the dst cset for each src cset and link it to src */
2784         list_for_each_entry_safe(src_cset, tmp_cset, &mgctx->preloaded_src_csets,
2785                                  mg_src_preload_node) {
2786                 struct css_set *dst_cset;
2787                 struct cgroup_subsys *ss;
2788                 int ssid;
2789
2790                 dst_cset = find_css_set(src_cset, src_cset->mg_dst_cgrp);
2791                 if (!dst_cset)
2792                         return -ENOMEM;
2793
2794                 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
2795
2796                 /*
2797                  * If src cset equals dst, it's noop.  Drop the src.
2798                  * cgroup_migrate() will skip the cset too.  Note that we
2799                  * can't handle src == dst as some nodes are used by both.
2800                  */
2801                 if (src_cset == dst_cset) {
2802                         src_cset->mg_src_cgrp = NULL;
2803                         src_cset->mg_dst_cgrp = NULL;
2804                         list_del_init(&src_cset->mg_src_preload_node);
2805                         put_css_set(src_cset);
2806                         put_css_set(dst_cset);
2807                         continue;
2808                 }
2809
2810                 src_cset->mg_dst_cset = dst_cset;
2811
2812                 if (list_empty(&dst_cset->mg_dst_preload_node))
2813                         list_add_tail(&dst_cset->mg_dst_preload_node,
2814                                       &mgctx->preloaded_dst_csets);
2815                 else
2816                         put_css_set(dst_cset);
2817
2818                 for_each_subsys(ss, ssid)
2819                         if (src_cset->subsys[ssid] != dst_cset->subsys[ssid])
2820                                 mgctx->ss_mask |= 1 << ssid;
2821         }
2822
2823         return 0;
2824 }
2825
2826 /**
2827  * cgroup_migrate - migrate a process or task to a cgroup
2828  * @leader: the leader of the process or the task to migrate
2829  * @threadgroup: whether @leader points to the whole process or a single task
2830  * @mgctx: migration context
2831  *
2832  * Migrate a process or task denoted by @leader.  If migrating a process,
2833  * the caller must be holding cgroup_threadgroup_rwsem.  The caller is also
2834  * responsible for invoking cgroup_migrate_add_src() and
2835  * cgroup_migrate_prepare_dst() on the targets before invoking this
2836  * function and following up with cgroup_migrate_finish().
2837  *
2838  * As long as a controller's ->can_attach() doesn't fail, this function is
2839  * guaranteed to succeed.  This means that, excluding ->can_attach()
2840  * failure, when migrating multiple targets, the success or failure can be
2841  * decided for all targets by invoking group_migrate_prepare_dst() before
2842  * actually starting migrating.
2843  */
2844 int cgroup_migrate(struct task_struct *leader, bool threadgroup,
2845                    struct cgroup_mgctx *mgctx)
2846 {
2847         struct task_struct *task;
2848
2849         /*
2850          * The following thread iteration should be inside an RCU critical
2851          * section to prevent tasks from being freed while taking the snapshot.
2852          * spin_lock_irq() implies RCU critical section here.
2853          */
2854         spin_lock_irq(&css_set_lock);
2855         task = leader;
2856         do {
2857                 cgroup_migrate_add_task(task, mgctx);
2858                 if (!threadgroup)
2859                         break;
2860         } while_each_thread(leader, task);
2861         spin_unlock_irq(&css_set_lock);
2862
2863         return cgroup_migrate_execute(mgctx);
2864 }
2865
2866 /**
2867  * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
2868  * @dst_cgrp: the cgroup to attach to
2869  * @leader: the task or the leader of the threadgroup to be attached
2870  * @threadgroup: attach the whole threadgroup?
2871  *
2872  * Call holding cgroup_mutex and cgroup_threadgroup_rwsem.
2873  */
2874 int cgroup_attach_task(struct cgroup *dst_cgrp, struct task_struct *leader,
2875                        bool threadgroup)
2876 {
2877         DEFINE_CGROUP_MGCTX(mgctx);
2878         struct task_struct *task;
2879         int ret = 0;
2880
2881         /* look up all src csets */
2882         spin_lock_irq(&css_set_lock);
2883         rcu_read_lock();
2884         task = leader;
2885         do {
2886                 cgroup_migrate_add_src(task_css_set(task), dst_cgrp, &mgctx);
2887                 if (!threadgroup)
2888                         break;
2889         } while_each_thread(leader, task);
2890         rcu_read_unlock();
2891         spin_unlock_irq(&css_set_lock);
2892
2893         /* prepare dst csets and commit */
2894         ret = cgroup_migrate_prepare_dst(&mgctx);
2895         if (!ret)
2896                 ret = cgroup_migrate(leader, threadgroup, &mgctx);
2897
2898         cgroup_migrate_finish(&mgctx);
2899
2900         if (!ret)
2901                 TRACE_CGROUP_PATH(attach_task, dst_cgrp, leader, threadgroup);
2902
2903         return ret;
2904 }
2905
2906 struct task_struct *cgroup_procs_write_start(char *buf, bool threadgroup,
2907                                              bool *threadgroup_locked)
2908 {
2909         struct task_struct *tsk;
2910         pid_t pid;
2911
2912         if (kstrtoint(strstrip(buf), 0, &pid) || pid < 0)
2913                 return ERR_PTR(-EINVAL);
2914
2915         /*
2916          * If we migrate a single thread, we don't care about threadgroup
2917          * stability. If the thread is `current`, it won't exit(2) under our
2918          * hands or change PID through exec(2). We exclude
2919          * cgroup_update_dfl_csses and other cgroup_{proc,thread}s_write
2920          * callers by cgroup_mutex.
2921          * Therefore, we can skip the global lock.
2922          */
2923         lockdep_assert_held(&cgroup_mutex);
2924         *threadgroup_locked = pid || threadgroup;
2925         cgroup_attach_lock(*threadgroup_locked);
2926
2927         rcu_read_lock();
2928         if (pid) {
2929                 tsk = find_task_by_vpid(pid);
2930                 if (!tsk) {
2931                         tsk = ERR_PTR(-ESRCH);
2932                         goto out_unlock_threadgroup;
2933                 }
2934         } else {
2935                 tsk = current;
2936         }
2937
2938         if (threadgroup)
2939                 tsk = tsk->group_leader;
2940
2941         /*
2942          * kthreads may acquire PF_NO_SETAFFINITY during initialization.
2943          * If userland migrates such a kthread to a non-root cgroup, it can
2944          * become trapped in a cpuset, or RT kthread may be born in a
2945          * cgroup with no rt_runtime allocated.  Just say no.
2946          */
2947         if (tsk->no_cgroup_migration || (tsk->flags & PF_NO_SETAFFINITY)) {
2948                 tsk = ERR_PTR(-EINVAL);
2949                 goto out_unlock_threadgroup;
2950         }
2951
2952         get_task_struct(tsk);
2953         goto out_unlock_rcu;
2954
2955 out_unlock_threadgroup:
2956         cgroup_attach_unlock(*threadgroup_locked);
2957         *threadgroup_locked = false;
2958 out_unlock_rcu:
2959         rcu_read_unlock();
2960         return tsk;
2961 }
2962
2963 void cgroup_procs_write_finish(struct task_struct *task, bool threadgroup_locked)
2964 {
2965         struct cgroup_subsys *ss;
2966         int ssid;
2967
2968         /* release reference from cgroup_procs_write_start() */
2969         put_task_struct(task);
2970
2971         cgroup_attach_unlock(threadgroup_locked);
2972
2973         for_each_subsys(ss, ssid)
2974                 if (ss->post_attach)
2975                         ss->post_attach();
2976 }
2977
2978 static void cgroup_print_ss_mask(struct seq_file *seq, u16 ss_mask)
2979 {
2980         struct cgroup_subsys *ss;
2981         bool printed = false;
2982         int ssid;
2983
2984         do_each_subsys_mask(ss, ssid, ss_mask) {
2985                 if (printed)
2986                         seq_putc(seq, ' ');
2987                 seq_puts(seq, ss->name);
2988                 printed = true;
2989         } while_each_subsys_mask();
2990         if (printed)
2991                 seq_putc(seq, '\n');
2992 }
2993
2994 /* show controllers which are enabled from the parent */
2995 static int cgroup_controllers_show(struct seq_file *seq, void *v)
2996 {
2997         struct cgroup *cgrp = seq_css(seq)->cgroup;
2998
2999         cgroup_print_ss_mask(seq, cgroup_control(cgrp));
3000         return 0;
3001 }
3002
3003 /* show controllers which are enabled for a given cgroup's children */
3004 static int cgroup_subtree_control_show(struct seq_file *seq, void *v)
3005 {
3006         struct cgroup *cgrp = seq_css(seq)->cgroup;
3007
3008         cgroup_print_ss_mask(seq, cgrp->subtree_control);
3009         return 0;
3010 }
3011
3012 /**
3013  * cgroup_update_dfl_csses - update css assoc of a subtree in default hierarchy
3014  * @cgrp: root of the subtree to update csses for
3015  *
3016  * @cgrp's control masks have changed and its subtree's css associations
3017  * need to be updated accordingly.  This function looks up all css_sets
3018  * which are attached to the subtree, creates the matching updated css_sets
3019  * and migrates the tasks to the new ones.
3020  */
3021 static int cgroup_update_dfl_csses(struct cgroup *cgrp)
3022 {
3023         DEFINE_CGROUP_MGCTX(mgctx);
3024         struct cgroup_subsys_state *d_css;
3025         struct cgroup *dsct;
3026         struct css_set *src_cset;
3027         bool has_tasks;
3028         int ret;
3029
3030         lockdep_assert_held(&cgroup_mutex);
3031
3032         /* look up all csses currently attached to @cgrp's subtree */
3033         spin_lock_irq(&css_set_lock);
3034         cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3035                 struct cgrp_cset_link *link;
3036
3037                 /*
3038                  * As cgroup_update_dfl_csses() is only called by
3039                  * cgroup_apply_control(). The csses associated with the
3040                  * given cgrp will not be affected by changes made to
3041                  * its subtree_control file. We can skip them.
3042                  */
3043                 if (dsct == cgrp)
3044                         continue;
3045
3046                 list_for_each_entry(link, &dsct->cset_links, cset_link)
3047                         cgroup_migrate_add_src(link->cset, dsct, &mgctx);
3048         }
3049         spin_unlock_irq(&css_set_lock);
3050
3051         /*
3052          * We need to write-lock threadgroup_rwsem while migrating tasks.
3053          * However, if there are no source csets for @cgrp, changing its
3054          * controllers isn't gonna produce any task migrations and the
3055          * write-locking can be skipped safely.
3056          */
3057         has_tasks = !list_empty(&mgctx.preloaded_src_csets);
3058         cgroup_attach_lock(has_tasks);
3059
3060         /* NULL dst indicates self on default hierarchy */
3061         ret = cgroup_migrate_prepare_dst(&mgctx);
3062         if (ret)
3063                 goto out_finish;
3064
3065         spin_lock_irq(&css_set_lock);
3066         list_for_each_entry(src_cset, &mgctx.preloaded_src_csets,
3067                             mg_src_preload_node) {
3068                 struct task_struct *task, *ntask;
3069
3070                 /* all tasks in src_csets need to be migrated */
3071                 list_for_each_entry_safe(task, ntask, &src_cset->tasks, cg_list)
3072                         cgroup_migrate_add_task(task, &mgctx);
3073         }
3074         spin_unlock_irq(&css_set_lock);
3075
3076         ret = cgroup_migrate_execute(&mgctx);
3077 out_finish:
3078         cgroup_migrate_finish(&mgctx);
3079         cgroup_attach_unlock(has_tasks);
3080         return ret;
3081 }
3082
3083 /**
3084  * cgroup_lock_and_drain_offline - lock cgroup_mutex and drain offlined csses
3085  * @cgrp: root of the target subtree
3086  *
3087  * Because css offlining is asynchronous, userland may try to re-enable a
3088  * controller while the previous css is still around.  This function grabs
3089  * cgroup_mutex and drains the previous css instances of @cgrp's subtree.
3090  */
3091 void cgroup_lock_and_drain_offline(struct cgroup *cgrp)
3092         __acquires(&cgroup_mutex)
3093 {
3094         struct cgroup *dsct;
3095         struct cgroup_subsys_state *d_css;
3096         struct cgroup_subsys *ss;
3097         int ssid;
3098
3099 restart:
3100         cgroup_lock();
3101
3102         cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3103                 for_each_subsys(ss, ssid) {
3104                         struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3105                         DEFINE_WAIT(wait);
3106
3107                         if (!css || !percpu_ref_is_dying(&css->refcnt))
3108                                 continue;
3109
3110                         cgroup_get_live(dsct);
3111                         prepare_to_wait(&dsct->offline_waitq, &wait,
3112                                         TASK_UNINTERRUPTIBLE);
3113
3114                         cgroup_unlock();
3115                         schedule();
3116                         finish_wait(&dsct->offline_waitq, &wait);
3117
3118                         cgroup_put(dsct);
3119                         goto restart;
3120                 }
3121         }
3122 }
3123
3124 /**
3125  * cgroup_save_control - save control masks and dom_cgrp of a subtree
3126  * @cgrp: root of the target subtree
3127  *
3128  * Save ->subtree_control, ->subtree_ss_mask and ->dom_cgrp to the
3129  * respective old_ prefixed fields for @cgrp's subtree including @cgrp
3130  * itself.
3131  */
3132 static void cgroup_save_control(struct cgroup *cgrp)
3133 {
3134         struct cgroup *dsct;
3135         struct cgroup_subsys_state *d_css;
3136
3137         cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3138                 dsct->old_subtree_control = dsct->subtree_control;
3139                 dsct->old_subtree_ss_mask = dsct->subtree_ss_mask;
3140                 dsct->old_dom_cgrp = dsct->dom_cgrp;
3141         }
3142 }
3143
3144 /**
3145  * cgroup_propagate_control - refresh control masks of a subtree
3146  * @cgrp: root of the target subtree
3147  *
3148  * For @cgrp and its subtree, ensure ->subtree_ss_mask matches
3149  * ->subtree_control and propagate controller availability through the
3150  * subtree so that descendants don't have unavailable controllers enabled.
3151  */
3152 static void cgroup_propagate_control(struct cgroup *cgrp)
3153 {
3154         struct cgroup *dsct;
3155         struct cgroup_subsys_state *d_css;
3156
3157         cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3158                 dsct->subtree_control &= cgroup_control(dsct);
3159                 dsct->subtree_ss_mask =
3160                         cgroup_calc_subtree_ss_mask(dsct->subtree_control,
3161                                                     cgroup_ss_mask(dsct));
3162         }
3163 }
3164
3165 /**
3166  * cgroup_restore_control - restore control masks and dom_cgrp of a subtree
3167  * @cgrp: root of the target subtree
3168  *
3169  * Restore ->subtree_control, ->subtree_ss_mask and ->dom_cgrp from the
3170  * respective old_ prefixed fields for @cgrp's subtree including @cgrp
3171  * itself.
3172  */
3173 static void cgroup_restore_control(struct cgroup *cgrp)
3174 {
3175         struct cgroup *dsct;
3176         struct cgroup_subsys_state *d_css;
3177
3178         cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3179                 dsct->subtree_control = dsct->old_subtree_control;
3180                 dsct->subtree_ss_mask = dsct->old_subtree_ss_mask;
3181                 dsct->dom_cgrp = dsct->old_dom_cgrp;
3182         }
3183 }
3184
3185 static bool css_visible(struct cgroup_subsys_state *css)
3186 {
3187         struct cgroup_subsys *ss = css->ss;
3188         struct cgroup *cgrp = css->cgroup;
3189
3190         if (cgroup_control(cgrp) & (1 << ss->id))
3191                 return true;
3192         if (!(cgroup_ss_mask(cgrp) & (1 << ss->id)))
3193                 return false;
3194         return cgroup_on_dfl(cgrp) && ss->implicit_on_dfl;
3195 }
3196
3197 /**
3198  * cgroup_apply_control_enable - enable or show csses according to control
3199  * @cgrp: root of the target subtree
3200  *
3201  * Walk @cgrp's subtree and create new csses or make the existing ones
3202  * visible.  A css is created invisible if it's being implicitly enabled
3203  * through dependency.  An invisible css is made visible when the userland
3204  * explicitly enables it.
3205  *
3206  * Returns 0 on success, -errno on failure.  On failure, csses which have
3207  * been processed already aren't cleaned up.  The caller is responsible for
3208  * cleaning up with cgroup_apply_control_disable().
3209  */
3210 static int cgroup_apply_control_enable(struct cgroup *cgrp)
3211 {
3212         struct cgroup *dsct;
3213         struct cgroup_subsys_state *d_css;
3214         struct cgroup_subsys *ss;
3215         int ssid, ret;
3216
3217         cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp) {
3218                 for_each_subsys(ss, ssid) {
3219                         struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3220
3221                         if (!(cgroup_ss_mask(dsct) & (1 << ss->id)))
3222                                 continue;
3223
3224                         if (!css) {
3225                                 css = css_create(dsct, ss);
3226                                 if (IS_ERR(css))
3227                                         return PTR_ERR(css);
3228                         }
3229
3230                         WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
3231
3232                         if (css_visible(css)) {
3233                                 ret = css_populate_dir(css);
3234                                 if (ret)
3235                                         return ret;
3236                         }
3237                 }
3238         }
3239
3240         return 0;
3241 }
3242
3243 /**
3244  * cgroup_apply_control_disable - kill or hide csses according to control
3245  * @cgrp: root of the target subtree
3246  *
3247  * Walk @cgrp's subtree and kill and hide csses so that they match
3248  * cgroup_ss_mask() and cgroup_visible_mask().
3249  *
3250  * A css is hidden when the userland requests it to be disabled while other
3251  * subsystems are still depending on it.  The css must not actively control
3252  * resources and be in the vanilla state if it's made visible again later.
3253  * Controllers which may be depended upon should provide ->css_reset() for
3254  * this purpose.
3255  */
3256 static void cgroup_apply_control_disable(struct cgroup *cgrp)
3257 {
3258         struct cgroup *dsct;
3259         struct cgroup_subsys_state *d_css;
3260         struct cgroup_subsys *ss;
3261         int ssid;
3262
3263         cgroup_for_each_live_descendant_post(dsct, d_css, cgrp) {
3264                 for_each_subsys(ss, ssid) {
3265                         struct cgroup_subsys_state *css = cgroup_css(dsct, ss);
3266
3267                         if (!css)
3268                                 continue;
3269
3270                         WARN_ON_ONCE(percpu_ref_is_dying(&css->refcnt));
3271
3272                         if (css->parent &&
3273                             !(cgroup_ss_mask(dsct) & (1 << ss->id))) {
3274                                 kill_css(css);
3275                         } else if (!css_visible(css)) {
3276                                 css_clear_dir(css);
3277                                 if (ss->css_reset)
3278                                         ss->css_reset(css);
3279                         }
3280                 }
3281         }
3282 }
3283
3284 /**
3285  * cgroup_apply_control - apply control mask updates to the subtree
3286  * @cgrp: root of the target subtree
3287  *
3288  * subsystems can be enabled and disabled in a subtree using the following
3289  * steps.
3290  *
3291  * 1. Call cgroup_save_control() to stash the current state.
3292  * 2. Update ->subtree_control masks in the subtree as desired.
3293  * 3. Call cgroup_apply_control() to apply the changes.
3294  * 4. Optionally perform other related operations.
3295  * 5. Call cgroup_finalize_control() to finish up.
3296  *
3297  * This function implements step 3 and propagates the mask changes
3298  * throughout @cgrp's subtree, updates csses accordingly and perform
3299  * process migrations.
3300  */
3301 static int cgroup_apply_control(struct cgroup *cgrp)
3302 {
3303         int ret;
3304
3305         cgroup_propagate_control(cgrp);
3306
3307         ret = cgroup_apply_control_enable(cgrp);
3308         if (ret)
3309                 return ret;
3310
3311         /*
3312          * At this point, cgroup_e_css_by_mask() results reflect the new csses
3313          * making the following cgroup_update_dfl_csses() properly update
3314          * css associations of all tasks in the subtree.
3315          */
3316         return cgroup_update_dfl_csses(cgrp);
3317 }
3318
3319 /**
3320  * cgroup_finalize_control - finalize control mask update
3321  * @cgrp: root of the target subtree
3322  * @ret: the result of the update
3323  *
3324  * Finalize control mask update.  See cgroup_apply_control() for more info.
3325  */
3326 static void cgroup_finalize_control(struct cgroup *cgrp, int ret)
3327 {
3328         if (ret) {
3329                 cgroup_restore_control(cgrp);
3330                 cgroup_propagate_control(cgrp);
3331         }
3332
3333         cgroup_apply_control_disable(cgrp);
3334 }
3335
3336 static int cgroup_vet_subtree_control_enable(struct cgroup *cgrp, u16 enable)
3337 {
3338         u16 domain_enable = enable & ~cgrp_dfl_threaded_ss_mask;
3339
3340         /* if nothing is getting enabled, nothing to worry about */
3341         if (!enable)
3342                 return 0;
3343
3344         /* can @cgrp host any resources? */
3345         if (!cgroup_is_valid_domain(cgrp->dom_cgrp))
3346                 return -EOPNOTSUPP;
3347
3348         /* mixables don't care */
3349         if (cgroup_is_mixable(cgrp))
3350                 return 0;
3351
3352         if (domain_enable) {
3353                 /* can't enable domain controllers inside a thread subtree */
3354                 if (cgroup_is_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3355                         return -EOPNOTSUPP;
3356         } else {
3357                 /*
3358                  * Threaded controllers can handle internal competitions
3359                  * and are always allowed inside a (prospective) thread
3360                  * subtree.
3361                  */
3362                 if (cgroup_can_be_thread_root(cgrp) || cgroup_is_threaded(cgrp))
3363                         return 0;
3364         }
3365
3366         /*
3367          * Controllers can't be enabled for a cgroup with tasks to avoid
3368          * child cgroups competing against tasks.
3369          */
3370         if (cgroup_has_tasks(cgrp))
3371                 return -EBUSY;
3372
3373         return 0;
3374 }
3375
3376 /* change the enabled child controllers for a cgroup in the default hierarchy */
3377 static ssize_t cgroup_subtree_control_write(struct kernfs_open_file *of,
3378                                             char *buf, size_t nbytes,
3379                                             loff_t off)
3380 {
3381         u16 enable = 0, disable = 0;
3382         struct cgroup *cgrp, *child;
3383         struct cgroup_subsys *ss;
3384         char *tok;
3385         int ssid, ret;
3386
3387         /*
3388          * Parse input - space separated list of subsystem names prefixed
3389          * with either + or -.
3390          */
3391         buf = strstrip(buf);
3392         while ((tok = strsep(&buf, " "))) {
3393                 if (tok[0] == '\0')
3394                         continue;
3395                 do_each_subsys_mask(ss, ssid, ~cgrp_dfl_inhibit_ss_mask) {
3396                         if (!cgroup_ssid_enabled(ssid) ||
3397                             strcmp(tok + 1, ss->name))
3398                                 continue;
3399
3400                         if (*tok == '+') {
3401                                 enable |= 1 << ssid;
3402                                 disable &= ~(1 << ssid);
3403                         } else if (*tok == '-') {
3404                                 disable |= 1 << ssid;
3405                                 enable &= ~(1 << ssid);
3406                         } else {
3407                                 return -EINVAL;
3408                         }
3409                         break;
3410                 } while_each_subsys_mask();
3411                 if (ssid == CGROUP_SUBSYS_COUNT)
3412                         return -EINVAL;
3413         }
3414
3415         cgrp = cgroup_kn_lock_live(of->kn, true);
3416         if (!cgrp)
3417                 return -ENODEV;
3418
3419         for_each_subsys(ss, ssid) {
3420                 if (enable & (1 << ssid)) {
3421                         if (cgrp->subtree_control & (1 << ssid)) {
3422                                 enable &= ~(1 << ssid);
3423                                 continue;
3424                         }
3425
3426                         if (!(cgroup_control(cgrp) & (1 << ssid))) {
3427                                 ret = -ENOENT;
3428                                 goto out_unlock;
3429                         }
3430                 } else if (disable & (1 << ssid)) {
3431                         if (!(cgrp->subtree_control & (1 << ssid))) {
3432                                 disable &= ~(1 << ssid);
3433                                 continue;
3434                         }
3435
3436                         /* a child has it enabled? */
3437                         cgroup_for_each_live_child(child, cgrp) {
3438                                 if (child->subtree_control & (1 << ssid)) {
3439                                         ret = -EBUSY;
3440                                         goto out_unlock;
3441                                 }
3442                         }
3443                 }
3444         }
3445
3446         if (!enable && !disable) {
3447                 ret = 0;
3448                 goto out_unlock;
3449         }
3450
3451         ret = cgroup_vet_subtree_control_enable(cgrp, enable);
3452         if (ret)
3453                 goto out_unlock;
3454
3455         /* save and update control masks and prepare csses */
3456         cgroup_save_control(cgrp);
3457
3458         cgrp->subtree_control |= enable;
3459         cgrp->subtree_control &= ~disable;
3460
3461         ret = cgroup_apply_control(cgrp);
3462         cgroup_finalize_control(cgrp, ret);
3463         if (ret)
3464                 goto out_unlock;
3465
3466         kernfs_activate(cgrp->kn);
3467 out_unlock:
3468         cgroup_kn_unlock(of->kn);
3469         return ret ?: nbytes;
3470 }
3471
3472 /**
3473  * cgroup_enable_threaded - make @cgrp threaded
3474  * @cgrp: the target cgroup
3475  *
3476  * Called when "threaded" is written to the cgroup.type interface file and
3477  * tries to make @cgrp threaded and join the parent's resource domain.
3478  * This function is never called on the root cgroup as cgroup.type doesn't
3479  * exist on it.
3480  */
3481 static int cgroup_enable_threaded(struct cgroup *cgrp)
3482 {
3483         struct cgroup *parent = cgroup_parent(cgrp);
3484         struct cgroup *dom_cgrp = parent->dom_cgrp;
3485         struct cgroup *dsct;
3486         struct cgroup_subsys_state *d_css;
3487         int ret;
3488
3489         lockdep_assert_held(&cgroup_mutex);
3490
3491         /* noop if already threaded */
3492         if (cgroup_is_threaded(cgrp))
3493                 return 0;
3494
3495         /*
3496          * If @cgroup is populated or has domain controllers enabled, it
3497          * can't be switched.  While the below cgroup_can_be_thread_root()
3498          * test can catch the same conditions, that's only when @parent is
3499          * not mixable, so let's check it explicitly.
3500          */
3501         if (cgroup_is_populated(cgrp) ||
3502             cgrp->subtree_control & ~cgrp_dfl_threaded_ss_mask)
3503                 return -EOPNOTSUPP;
3504
3505         /* we're joining the parent's domain, ensure its validity */
3506         if (!cgroup_is_valid_domain(dom_cgrp) ||
3507             !cgroup_can_be_thread_root(dom_cgrp))
3508                 return -EOPNOTSUPP;
3509
3510         /*
3511          * The following shouldn't cause actual migrations and should
3512          * always succeed.
3513          */
3514         cgroup_save_control(cgrp);
3515
3516         cgroup_for_each_live_descendant_pre(dsct, d_css, cgrp)
3517                 if (dsct == cgrp || cgroup_is_threaded(dsct))
3518                         dsct->dom_cgrp = dom_cgrp;
3519
3520         ret = cgroup_apply_control(cgrp);
3521         if (!ret)
3522                 parent->nr_threaded_children++;
3523
3524         cgroup_finalize_control(cgrp, ret);
3525         return ret;
3526 }
3527
3528 static int cgroup_type_show(struct seq_file *seq, void *v)
3529 {
3530         struct cgroup *cgrp = seq_css(seq)->cgroup;
3531
3532         if (cgroup_is_threaded(cgrp))
3533                 seq_puts(seq, "threaded\n");
3534         else if (!cgroup_is_valid_domain(cgrp))
3535                 seq_puts(seq, "domain invalid\n");
3536         else if (cgroup_is_thread_root(cgrp))
3537                 seq_puts(seq, "domain threaded\n");
3538         else
3539                 seq_puts(seq, "domain\n");
3540
3541         return 0;
3542 }
3543
3544 static ssize_t cgroup_type_write(struct kernfs_open_file *of, char *buf,
3545                                  size_t nbytes, loff_t off)
3546 {
3547         struct cgroup *cgrp;
3548         int ret;
3549
3550         /* only switching to threaded mode is supported */
3551         if (strcmp(strstrip(buf), "threaded"))
3552                 return -EINVAL;
3553
3554         /* drain dying csses before we re-apply (threaded) subtree control */
3555         cgrp = cgroup_kn_lock_live(of->kn, true);
3556         if (!cgrp)
3557                 return -ENOENT;
3558
3559         /* threaded can only be enabled */
3560         ret = cgroup_enable_threaded(cgrp);
3561
3562         cgroup_kn_unlock(of->kn);
3563         return ret ?: nbytes;
3564 }
3565
3566 static int cgroup_max_descendants_show(struct seq_file *seq, void *v)
3567 {
3568         struct cgroup *cgrp = seq_css(seq)->cgroup;
3569         int descendants = READ_ONCE(cgrp->max_descendants);
3570
3571         if (descendants == INT_MAX)
3572                 seq_puts(seq, "max\n");
3573         else
3574                 seq_printf(seq, "%d\n", descendants);
3575
3576         return 0;
3577 }
3578
3579 static ssize_t cgroup_max_descendants_write(struct kernfs_open_file *of,
3580                                            char *buf, size_t nbytes, loff_t off)
3581 {
3582         struct cgroup *cgrp;
3583         int descendants;
3584         ssize_t ret;
3585
3586         buf = strstrip(buf);
3587         if (!strcmp(buf, "max")) {
3588                 descendants = INT_MAX;
3589         } else {
3590                 ret = kstrtoint(buf, 0, &descendants);
3591                 if (ret)
3592                         return ret;
3593         }
3594
3595         if (descendants < 0)
3596                 return -ERANGE;
3597
3598         cgrp = cgroup_kn_lock_live(of->kn, false);
3599         if (!cgrp)
3600                 return -ENOENT;
3601
3602         cgrp->max_descendants = descendants;
3603
3604         cgroup_kn_unlock(of->kn);
3605
3606         return nbytes;
3607 }
3608
3609 static int cgroup_max_depth_show(struct seq_file *seq, void *v)
3610 {
3611         struct cgroup *cgrp = seq_css(seq)->cgroup;
3612         int depth = READ_ONCE(cgrp->max_depth);
3613
3614         if (depth == INT_MAX)
3615                 seq_puts(seq, "max\n");
3616         else
3617                 seq_printf(seq, "%d\n", depth);
3618
3619         return 0;
3620 }
3621
3622 static ssize_t cgroup_max_depth_write(struct kernfs_open_file *of,
3623                                       char *buf, size_t nbytes, loff_t off)
3624 {
3625         struct cgroup *cgrp;
3626         ssize_t ret;
3627         int depth;
3628
3629         buf = strstrip(buf);
3630         if (!strcmp(buf, "max")) {
3631                 depth = INT_MAX;
3632         } else {
3633                 ret = kstrtoint(buf, 0, &depth);
3634                 if (ret)
3635                         return ret;
3636         }
3637
3638         if (depth < 0)
3639                 return -ERANGE;
3640
3641         cgrp = cgroup_kn_lock_live(of->kn, false);
3642         if (!cgrp)
3643                 return -ENOENT;
3644
3645         cgrp->max_depth = depth;
3646
3647         cgroup_kn_unlock(of->kn);
3648
3649         return nbytes;
3650 }
3651
3652 static int cgroup_events_show(struct seq_file *seq, void *v)
3653 {
3654         struct cgroup *cgrp = seq_css(seq)->cgroup;
3655
3656         seq_printf(seq, "populated %d\n", cgroup_is_populated(cgrp));
3657         seq_printf(seq, "frozen %d\n", test_bit(CGRP_FROZEN, &cgrp->flags));
3658
3659         return 0;
3660 }
3661
3662 static int cgroup_stat_show(struct seq_file *seq, void *v)
3663 {
3664         struct cgroup *cgroup = seq_css(seq)->cgroup;
3665
3666         seq_printf(seq, "nr_descendants %d\n",
3667                    cgroup->nr_descendants);
3668         seq_printf(seq, "nr_dying_descendants %d\n",
3669                    cgroup->nr_dying_descendants);
3670
3671         return 0;
3672 }
3673
3674 #ifdef CONFIG_CGROUP_SCHED
3675 /**
3676  * cgroup_tryget_css - try to get a cgroup's css for the specified subsystem
3677  * @cgrp: the cgroup of interest
3678  * @ss: the subsystem of interest
3679  *
3680  * Find and get @cgrp's css associated with @ss.  If the css doesn't exist
3681  * or is offline, %NULL is returned.
3682  */
3683 static struct cgroup_subsys_state *cgroup_tryget_css(struct cgroup *cgrp,
3684                                                      struct cgroup_subsys *ss)
3685 {
3686         struct cgroup_subsys_state *css;
3687
3688         rcu_read_lock();
3689         css = cgroup_css(cgrp, ss);
3690         if (css && !css_tryget_online(css))
3691                 css = NULL;
3692         rcu_read_unlock();
3693
3694         return css;
3695 }
3696
3697 static int cgroup_extra_stat_show(struct seq_file *seq, int ssid)
3698 {
3699         struct cgroup *cgrp = seq_css(seq)->cgroup;
3700         struct cgroup_subsys *ss = cgroup_subsys[ssid];
3701         struct cgroup_subsys_state *css;
3702         int ret;
3703
3704         if (!ss->css_extra_stat_show)
3705                 return 0;
3706
3707         css = cgroup_tryget_css(cgrp, ss);
3708         if (!css)
3709                 return 0;
3710
3711         ret = ss->css_extra_stat_show(seq, css);
3712         css_put(css);
3713         return ret;
3714 }
3715
3716 static int cgroup_local_stat_show(struct seq_file *seq,
3717                                   struct cgroup *cgrp, int ssid)
3718 {
3719         struct cgroup_subsys *ss = cgroup_subsys[ssid];
3720         struct cgroup_subsys_state *css;
3721         int ret;
3722
3723         if (!ss->css_local_stat_show)
3724                 return 0;
3725
3726         css = cgroup_tryget_css(cgrp, ss);
3727         if (!css)
3728                 return 0;
3729
3730         ret = ss->css_local_stat_show(seq, css);
3731         css_put(css);
3732         return ret;
3733 }
3734 #endif
3735
3736 static int cpu_stat_show(struct seq_file *seq, void *v)
3737 {
3738         int ret = 0;
3739
3740         cgroup_base_stat_cputime_show(seq);
3741 #ifdef CONFIG_CGROUP_SCHED
3742         ret = cgroup_extra_stat_show(seq, cpu_cgrp_id);
3743 #endif
3744         return ret;
3745 }
3746
3747 static int cpu_local_stat_show(struct seq_file *seq, void *v)
3748 {
3749         struct cgroup __maybe_unused *cgrp = seq_css(seq)->cgroup;
3750         int ret = 0;
3751
3752 #ifdef CONFIG_CGROUP_SCHED
3753         ret = cgroup_local_stat_show(seq, cgrp, cpu_cgrp_id);
3754 #endif
3755         return ret;
3756 }
3757
3758 #ifdef CONFIG_PSI
3759 static int cgroup_io_pressure_show(struct seq_file *seq, void *v)
3760 {
3761         struct cgroup *cgrp = seq_css(seq)->cgroup;
3762         struct psi_group *psi = cgroup_psi(cgrp);
3763
3764         return psi_show(seq, psi, PSI_IO);
3765 }
3766 static int cgroup_memory_pressure_show(struct seq_file *seq, void *v)
3767 {
3768         struct cgroup *cgrp = seq_css(seq)->cgroup;
3769         struct psi_group *psi = cgroup_psi(cgrp);
3770
3771         return psi_show(seq, psi, PSI_MEM);
3772 }
3773 static int cgroup_cpu_pressure_show(struct seq_file *seq, void *v)
3774 {
3775         struct cgroup *cgrp = seq_css(seq)->cgroup;
3776         struct psi_group *psi = cgroup_psi(cgrp);
3777
3778         return psi_show(seq, psi, PSI_CPU);
3779 }
3780
3781 static ssize_t pressure_write(struct kernfs_open_file *of, char *buf,
3782                               size_t nbytes, enum psi_res res)
3783 {
3784         struct cgroup_file_ctx *ctx = of->priv;
3785         struct psi_trigger *new;
3786         struct cgroup *cgrp;
3787         struct psi_group *psi;
3788
3789         cgrp = cgroup_kn_lock_live(of->kn, false);
3790         if (!cgrp)
3791                 return -ENODEV;
3792
3793         cgroup_get(cgrp);
3794         cgroup_kn_unlock(of->kn);
3795
3796         /* Allow only one trigger per file descriptor */
3797         if (ctx->psi.trigger) {
3798                 cgroup_put(cgrp);
3799                 return -EBUSY;
3800         }
3801
3802         psi = cgroup_psi(cgrp);
3803         new = psi_trigger_create(psi, buf, res, of->file, of);
3804         if (IS_ERR(new)) {
3805                 cgroup_put(cgrp);
3806                 return PTR_ERR(new);
3807         }
3808
3809         smp_store_release(&ctx->psi.trigger, new);
3810         cgroup_put(cgrp);
3811
3812         return nbytes;
3813 }
3814
3815 static ssize_t cgroup_io_pressure_write(struct kernfs_open_file *of,
3816                                           char *buf, size_t nbytes,
3817                                           loff_t off)
3818 {
3819         return pressure_write(of, buf, nbytes, PSI_IO);
3820 }
3821
3822 static ssize_t cgroup_memory_pressure_write(struct kernfs_open_file *of,
3823                                           char *buf, size_t nbytes,
3824                                           loff_t off)
3825 {
3826         return pressure_write(of, buf, nbytes, PSI_MEM);
3827 }
3828
3829 static ssize_t cgroup_cpu_pressure_write(struct kernfs_open_file *of,
3830                                           char *buf, size_t nbytes,
3831                                           loff_t off)
3832 {
3833         return pressure_write(of, buf, nbytes, PSI_CPU);
3834 }
3835
3836 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
3837 static int cgroup_irq_pressure_show(struct seq_file *seq, void *v)
3838 {
3839         struct cgroup *cgrp = seq_css(seq)->cgroup;
3840         struct psi_group *psi = cgroup_psi(cgrp);
3841
3842         return psi_show(seq, psi, PSI_IRQ);
3843 }
3844
3845 static ssize_t cgroup_irq_pressure_write(struct kernfs_open_file *of,
3846                                          char *buf, size_t nbytes,
3847                                          loff_t off)
3848 {
3849         return pressure_write(of, buf, nbytes, PSI_IRQ);
3850 }
3851 #endif
3852
3853 static int cgroup_pressure_show(struct seq_file *seq, void *v)
3854 {
3855         struct cgroup *cgrp = seq_css(seq)->cgroup;
3856         struct psi_group *psi = cgroup_psi(cgrp);
3857
3858         seq_printf(seq, "%d\n", psi->enabled);
3859
3860         return 0;
3861 }
3862
3863 static ssize_t cgroup_pressure_write(struct kernfs_open_file *of,
3864                                      char *buf, size_t nbytes,
3865                                      loff_t off)
3866 {
3867         ssize_t ret;
3868         int enable;
3869         struct cgroup *cgrp;
3870         struct psi_group *psi;
3871
3872         ret = kstrtoint(strstrip(buf), 0, &enable);
3873         if (ret)
3874                 return ret;
3875
3876         if (enable < 0 || enable > 1)
3877                 return -ERANGE;
3878
3879         cgrp = cgroup_kn_lock_live(of->kn, false);
3880         if (!cgrp)
3881                 return -ENOENT;
3882
3883         psi = cgroup_psi(cgrp);
3884         if (psi->enabled != enable) {
3885                 int i;
3886
3887                 /* show or hide {cpu,memory,io,irq}.pressure files */
3888                 for (i = 0; i < NR_PSI_RESOURCES; i++)
3889                         cgroup_file_show(&cgrp->psi_files[i], enable);
3890
3891                 psi->enabled = enable;
3892                 if (enable)
3893                         psi_cgroup_restart(psi);
3894         }
3895
3896         cgroup_kn_unlock(of->kn);
3897
3898         return nbytes;
3899 }
3900
3901 static __poll_t cgroup_pressure_poll(struct kernfs_open_file *of,
3902                                           poll_table *pt)
3903 {
3904         struct cgroup_file_ctx *ctx = of->priv;
3905
3906         return psi_trigger_poll(&ctx->psi.trigger, of->file, pt);
3907 }
3908
3909 static void cgroup_pressure_release(struct kernfs_open_file *of)
3910 {
3911         struct cgroup_file_ctx *ctx = of->priv;
3912
3913         psi_trigger_destroy(ctx->psi.trigger);
3914 }
3915
3916 bool cgroup_psi_enabled(void)
3917 {
3918         if (static_branch_likely(&psi_disabled))
3919                 return false;
3920
3921         return (cgroup_feature_disable_mask & (1 << OPT_FEATURE_PRESSURE)) == 0;
3922 }
3923
3924 #else /* CONFIG_PSI */
3925 bool cgroup_psi_enabled(void)
3926 {
3927         return false;
3928 }
3929
3930 #endif /* CONFIG_PSI */
3931
3932 static int cgroup_freeze_show(struct seq_file *seq, void *v)
3933 {
3934         struct cgroup *cgrp = seq_css(seq)->cgroup;
3935
3936         seq_printf(seq, "%d\n", cgrp->freezer.freeze);
3937
3938         return 0;
3939 }
3940
3941 static ssize_t cgroup_freeze_write(struct kernfs_open_file *of,
3942                                    char *buf, size_t nbytes, loff_t off)
3943 {
3944         struct cgroup *cgrp;
3945         ssize_t ret;
3946         int freeze;
3947
3948         ret = kstrtoint(strstrip(buf), 0, &freeze);
3949         if (ret)
3950                 return ret;
3951
3952         if (freeze < 0 || freeze > 1)
3953                 return -ERANGE;
3954
3955         cgrp = cgroup_kn_lock_live(of->kn, false);
3956         if (!cgrp)
3957                 return -ENOENT;
3958
3959         cgroup_freeze(cgrp, freeze);
3960
3961         cgroup_kn_unlock(of->kn);
3962
3963         return nbytes;
3964 }
3965
3966 static void __cgroup_kill(struct cgroup *cgrp)
3967 {
3968         struct css_task_iter it;
3969         struct task_struct *task;
3970
3971         lockdep_assert_held(&cgroup_mutex);
3972
3973         spin_lock_irq(&css_set_lock);
3974         set_bit(CGRP_KILL, &cgrp->flags);
3975         spin_unlock_irq(&css_set_lock);
3976
3977         css_task_iter_start(&cgrp->self, CSS_TASK_ITER_PROCS | CSS_TASK_ITER_THREADED, &it);
3978         while ((task = css_task_iter_next(&it))) {
3979                 /* Ignore kernel threads here. */
3980                 if (task->flags & PF_KTHREAD)
3981                         continue;
3982
3983                 /* Skip tasks that are already dying. */
3984                 if (__fatal_signal_pending(task))
3985                         continue;
3986
3987                 send_sig(SIGKILL, task, 0);
3988         }
3989         css_task_iter_end(&it);
3990
3991         spin_lock_irq(&css_set_lock);
3992         clear_bit(CGRP_KILL, &cgrp->flags);
3993         spin_unlock_irq(&css_set_lock);
3994 }
3995
3996 static void cgroup_kill(struct cgroup *cgrp)
3997 {
3998         struct cgroup_subsys_state *css;
3999         struct cgroup *dsct;
4000
4001         lockdep_assert_held(&cgroup_mutex);
4002
4003         cgroup_for_each_live_descendant_pre(dsct, css, cgrp)
4004                 __cgroup_kill(dsct);
4005 }
4006
4007 static ssize_t cgroup_kill_write(struct kernfs_open_file *of, char *buf,
4008                                  size_t nbytes, loff_t off)
4009 {
4010         ssize_t ret = 0;
4011         int kill;
4012         struct cgroup *cgrp;
4013
4014         ret = kstrtoint(strstrip(buf), 0, &kill);
4015         if (ret)
4016                 return ret;
4017
4018         if (kill != 1)
4019                 return -ERANGE;
4020
4021         cgrp = cgroup_kn_lock_live(of->kn, false);
4022         if (!cgrp)
4023                 return -ENOENT;
4024
4025         /*
4026          * Killing is a process directed operation, i.e. the whole thread-group
4027          * is taken down so act like we do for cgroup.procs and only make this
4028          * writable in non-threaded cgroups.
4029          */
4030         if (cgroup_is_threaded(cgrp))
4031                 ret = -EOPNOTSUPP;
4032         else
4033                 cgroup_kill(cgrp);
4034
4035         cgroup_kn_unlock(of->kn);
4036
4037         return ret ?: nbytes;
4038 }
4039
4040 static int cgroup_file_open(struct kernfs_open_file *of)
4041 {
4042         struct cftype *cft = of_cft(of);
4043         struct cgroup_file_ctx *ctx;
4044         int ret;
4045
4046         ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
4047         if (!ctx)
4048                 return -ENOMEM;
4049
4050         ctx->ns = current->nsproxy->cgroup_ns;
4051         get_cgroup_ns(ctx->ns);
4052         of->priv = ctx;
4053
4054         if (!cft->open)
4055                 return 0;
4056
4057         ret = cft->open(of);
4058         if (ret) {
4059                 put_cgroup_ns(ctx->ns);
4060                 kfree(ctx);
4061         }
4062         return ret;
4063 }
4064
4065 static void cgroup_file_release(struct kernfs_open_file *of)
4066 {
4067         struct cftype *cft = of_cft(of);
4068         struct cgroup_file_ctx *ctx = of->priv;
4069
4070         if (cft->release)
4071                 cft->release(of);
4072         put_cgroup_ns(ctx->ns);
4073         kfree(ctx);
4074 }
4075
4076 static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
4077                                  size_t nbytes, loff_t off)
4078 {
4079         struct cgroup_file_ctx *ctx = of->priv;
4080         struct cgroup *cgrp = of->kn->parent->priv;
4081         struct cftype *cft = of_cft(of);
4082         struct cgroup_subsys_state *css;
4083         int ret;
4084
4085         if (!nbytes)
4086                 return 0;
4087
4088         /*
4089          * If namespaces are delegation boundaries, disallow writes to
4090          * files in an non-init namespace root from inside the namespace
4091          * except for the files explicitly marked delegatable -
4092          * cgroup.procs and cgroup.subtree_control.
4093          */
4094         if ((cgrp->root->flags & CGRP_ROOT_NS_DELEGATE) &&
4095             !(cft->flags & CFTYPE_NS_DELEGATABLE) &&
4096             ctx->ns != &init_cgroup_ns && ctx->ns->root_cset->dfl_cgrp == cgrp)
4097                 return -EPERM;
4098
4099         if (cft->write)
4100                 return cft->write(of, buf, nbytes, off);
4101
4102         /*
4103          * kernfs guarantees that a file isn't deleted with operations in
4104          * flight, which means that the matching css is and stays alive and
4105          * doesn't need to be pinned.  The RCU locking is not necessary
4106          * either.  It's just for the convenience of using cgroup_css().
4107          */
4108         rcu_read_lock();
4109         css = cgroup_css(cgrp, cft->ss);
4110         rcu_read_unlock();
4111
4112         if (cft->write_u64) {
4113                 unsigned long long v;
4114                 ret = kstrtoull(buf, 0, &v);
4115                 if (!ret)
4116                         ret = cft->write_u64(css, cft, v);
4117         } else if (cft->write_s64) {
4118                 long long v;
4119                 ret = kstrtoll(buf, 0, &v);
4120                 if (!ret)
4121                         ret = cft->write_s64(css, cft, v);
4122         } else {
4123                 ret = -EINVAL;
4124         }
4125
4126         return ret ?: nbytes;
4127 }
4128
4129 static __poll_t cgroup_file_poll(struct kernfs_open_file *of, poll_table *pt)
4130 {
4131         struct cftype *cft = of_cft(of);
4132
4133         if (cft->poll)
4134                 return cft->poll(of, pt);
4135
4136         return kernfs_generic_poll(of, pt);
4137 }
4138
4139 static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
4140 {
4141         return seq_cft(seq)->seq_start(seq, ppos);
4142 }
4143
4144 static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
4145 {
4146         return seq_cft(seq)->seq_next(seq, v, ppos);
4147 }
4148
4149 static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
4150 {
4151         if (seq_cft(seq)->seq_stop)
4152                 seq_cft(seq)->seq_stop(seq, v);
4153 }
4154
4155 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
4156 {
4157         struct cftype *cft = seq_cft(m);
4158         struct cgroup_subsys_state *css = seq_css(m);
4159
4160         if (cft->seq_show)
4161                 return cft->seq_show(m, arg);
4162
4163         if (cft->read_u64)
4164                 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
4165         else if (cft->read_s64)
4166                 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
4167         else
4168                 return -EINVAL;
4169         return 0;
4170 }
4171
4172 static struct kernfs_ops cgroup_kf_single_ops = {
4173         .atomic_write_len       = PAGE_SIZE,
4174         .open                   = cgroup_file_open,
4175         .release                = cgroup_file_release,
4176         .write                  = cgroup_file_write,
4177         .poll                   = cgroup_file_poll,
4178         .seq_show               = cgroup_seqfile_show,
4179 };
4180
4181 static struct kernfs_ops cgroup_kf_ops = {
4182         .atomic_write_len       = PAGE_SIZE,
4183         .open                   = cgroup_file_open,
4184         .release                = cgroup_file_release,
4185         .write                  = cgroup_file_write,
4186         .poll                   = cgroup_file_poll,
4187         .seq_start              = cgroup_seqfile_start,
4188         .seq_next               = cgroup_seqfile_next,
4189         .seq_stop               = cgroup_seqfile_stop,
4190         .seq_show               = cgroup_seqfile_show,
4191 };
4192
4193 /* set uid and gid of cgroup dirs and files to that of the creator */
4194 static int cgroup_kn_set_ugid(struct kernfs_node *kn)
4195 {
4196         struct iattr iattr = { .ia_valid = ATTR_UID | ATTR_GID,
4197                                .ia_uid = current_fsuid(),
4198                                .ia_gid = current_fsgid(), };
4199
4200         if (uid_eq(iattr.ia_uid, GLOBAL_ROOT_UID) &&
4201             gid_eq(iattr.ia_gid, GLOBAL_ROOT_GID))
4202                 return 0;
4203
4204         return kernfs_setattr(kn, &iattr);
4205 }
4206
4207 static void cgroup_file_notify_timer(struct timer_list *timer)
4208 {
4209         cgroup_file_notify(container_of(timer, struct cgroup_file,
4210                                         notify_timer));
4211 }
4212
4213 static int cgroup_add_file(struct cgroup_subsys_state *css, struct cgroup *cgrp,
4214                            struct cftype *cft)
4215 {
4216         char name[CGROUP_FILE_NAME_MAX];
4217         struct kernfs_node *kn;
4218         struct lock_class_key *key = NULL;
4219         int ret;
4220
4221 #ifdef CONFIG_DEBUG_LOCK_ALLOC
4222         key = &cft->lockdep_key;
4223 #endif
4224         kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
4225                                   cgroup_file_mode(cft),
4226                                   GLOBAL_ROOT_UID, GLOBAL_ROOT_GID,
4227                                   0, cft->kf_ops, cft,
4228                                   NULL, key);
4229         if (IS_ERR(kn))
4230                 return PTR_ERR(kn);
4231
4232         ret = cgroup_kn_set_ugid(kn);
4233         if (ret) {
4234                 kernfs_remove(kn);
4235                 return ret;
4236         }
4237
4238         if (cft->file_offset) {
4239                 struct cgroup_file *cfile = (void *)css + cft->file_offset;
4240
4241                 timer_setup(&cfile->notify_timer, cgroup_file_notify_timer, 0);
4242
4243                 spin_lock_irq(&cgroup_file_kn_lock);
4244                 cfile->kn = kn;
4245                 spin_unlock_irq(&cgroup_file_kn_lock);
4246         }
4247
4248         return 0;
4249 }
4250
4251 /**
4252  * cgroup_addrm_files - add or remove files to a cgroup directory
4253  * @css: the target css
4254  * @cgrp: the target cgroup (usually css->cgroup)
4255  * @cfts: array of cftypes to be added
4256  * @is_add: whether to add or remove
4257  *
4258  * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
4259  * For removals, this function never fails.
4260  */
4261 static int cgroup_addrm_files(struct cgroup_subsys_state *css,
4262                               struct cgroup *cgrp, struct cftype cfts[],
4263                               bool is_add)
4264 {
4265         struct cftype *cft, *cft_end = NULL;
4266         int ret = 0;
4267
4268         lockdep_assert_held(&cgroup_mutex);
4269
4270 restart:
4271         for (cft = cfts; cft != cft_end && cft->name[0] != '\0'; cft++) {
4272                 /* does cft->flags tell us to skip this file on @cgrp? */
4273                 if ((cft->flags & __CFTYPE_ONLY_ON_DFL) && !cgroup_on_dfl(cgrp))
4274                         continue;
4275                 if ((cft->flags & __CFTYPE_NOT_ON_DFL) && cgroup_on_dfl(cgrp))
4276                         continue;
4277                 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgroup_parent(cgrp))
4278                         continue;
4279                 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgroup_parent(cgrp))
4280                         continue;
4281                 if ((cft->flags & CFTYPE_DEBUG) && !cgroup_debug)
4282                         continue;
4283                 if (is_add) {
4284                         ret = cgroup_add_file(css, cgrp, cft);
4285                         if (ret) {
4286                                 pr_warn("%s: failed to add %s, err=%d\n",
4287                                         __func__, cft->name, ret);
4288                                 cft_end = cft;
4289                                 is_add = false;
4290                                 goto restart;
4291                         }
4292                 } else {
4293                         cgroup_rm_file(cgrp, cft);
4294                 }
4295         }
4296         return ret;
4297 }
4298
4299 static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
4300 {
4301         struct cgroup_subsys *ss = cfts[0].ss;
4302         struct cgroup *root = &ss->root->cgrp;
4303         struct cgroup_subsys_state *css;
4304         int ret = 0;
4305
4306         lockdep_assert_held(&cgroup_mutex);
4307
4308         /* add/rm files for all cgroups created before */
4309         css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
4310                 struct cgroup *cgrp = css->cgroup;
4311
4312                 if (!(css->flags & CSS_VISIBLE))
4313                         continue;
4314
4315                 ret = cgroup_addrm_files(css, cgrp, cfts, is_add);
4316                 if (ret)
4317                         break;
4318         }
4319
4320         if (is_add && !ret)
4321                 kernfs_activate(root->kn);
4322         return ret;
4323 }
4324
4325 static void cgroup_exit_cftypes(struct cftype *cfts)
4326 {
4327         struct cftype *cft;
4328
4329         for (cft = cfts; cft->name[0] != '\0'; cft++) {
4330                 /* free copy for custom atomic_write_len, see init_cftypes() */
4331                 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
4332                         kfree(cft->kf_ops);
4333                 cft->kf_ops = NULL;
4334                 cft->ss = NULL;
4335
4336                 /* revert flags set by cgroup core while adding @cfts */
4337                 cft->flags &= ~(__CFTYPE_ONLY_ON_DFL | __CFTYPE_NOT_ON_DFL |
4338                                 __CFTYPE_ADDED);
4339         }
4340 }
4341
4342 static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4343 {
4344         struct cftype *cft;
4345         int ret = 0;
4346
4347         for (cft = cfts; cft->name[0] != '\0'; cft++) {
4348                 struct kernfs_ops *kf_ops;
4349
4350                 WARN_ON(cft->ss || cft->kf_ops);
4351
4352                 if (cft->flags & __CFTYPE_ADDED) {
4353                         ret = -EBUSY;
4354                         break;
4355                 }
4356
4357                 if (cft->seq_start)
4358                         kf_ops = &cgroup_kf_ops;
4359                 else
4360                         kf_ops = &cgroup_kf_single_ops;
4361
4362                 /*
4363                  * Ugh... if @cft wants a custom max_write_len, we need to
4364                  * make a copy of kf_ops to set its atomic_write_len.
4365                  */
4366                 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
4367                         kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
4368                         if (!kf_ops) {
4369                                 ret = -ENOMEM;
4370                                 break;
4371                         }
4372                         kf_ops->atomic_write_len = cft->max_write_len;
4373                 }
4374
4375                 cft->kf_ops = kf_ops;
4376                 cft->ss = ss;
4377                 cft->flags |= __CFTYPE_ADDED;
4378         }
4379
4380         if (ret)
4381                 cgroup_exit_cftypes(cfts);
4382         return ret;
4383 }
4384
4385 static void cgroup_rm_cftypes_locked(struct cftype *cfts)
4386 {
4387         lockdep_assert_held(&cgroup_mutex);
4388
4389         list_del(&cfts->node);
4390         cgroup_apply_cftypes(cfts, false);
4391         cgroup_exit_cftypes(cfts);
4392 }
4393
4394 /**
4395  * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
4396  * @cfts: zero-length name terminated array of cftypes
4397  *
4398  * Unregister @cfts.  Files described by @cfts are removed from all
4399  * existing cgroups and all future cgroups won't have them either.  This
4400  * function can be called anytime whether @cfts' subsys is attached or not.
4401  *
4402  * Returns 0 on successful unregistration, -ENOENT if @cfts is not
4403  * registered.
4404  */
4405 int cgroup_rm_cftypes(struct cftype *cfts)
4406 {
4407         if (!cfts || cfts[0].name[0] == '\0')
4408                 return 0;
4409
4410         if (!(cfts[0].flags & __CFTYPE_ADDED))
4411                 return -ENOENT;
4412
4413         cgroup_lock();
4414         cgroup_rm_cftypes_locked(cfts);
4415         cgroup_unlock();
4416         return 0;
4417 }
4418
4419 /**
4420  * cgroup_add_cftypes - add an array of cftypes to a subsystem
4421  * @ss: target cgroup subsystem
4422  * @cfts: zero-length name terminated array of cftypes
4423  *
4424  * Register @cfts to @ss.  Files described by @cfts are created for all
4425  * existing cgroups to which @ss is attached and all future cgroups will
4426  * have them too.  This function can be called anytime whether @ss is
4427  * attached or not.
4428  *
4429  * Returns 0 on successful registration, -errno on failure.  Note that this
4430  * function currently returns 0 as long as @cfts registration is successful
4431  * even if some file creation attempts on existing cgroups fail.
4432  */
4433 static int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4434 {
4435         int ret;
4436
4437         if (!cgroup_ssid_enabled(ss->id))
4438                 return 0;
4439
4440         if (!cfts || cfts[0].name[0] == '\0')
4441                 return 0;
4442
4443         ret = cgroup_init_cftypes(ss, cfts);
4444         if (ret)
4445                 return ret;
4446
4447         cgroup_lock();
4448
4449         list_add_tail(&cfts->node, &ss->cfts);
4450         ret = cgroup_apply_cftypes(cfts, true);
4451         if (ret)
4452                 cgroup_rm_cftypes_locked(cfts);
4453
4454         cgroup_unlock();
4455         return ret;
4456 }
4457
4458 /**
4459  * cgroup_add_dfl_cftypes - add an array of cftypes for default hierarchy
4460  * @ss: target cgroup subsystem
4461  * @cfts: zero-length name terminated array of cftypes
4462  *
4463  * Similar to cgroup_add_cftypes() but the added files are only used for
4464  * the default hierarchy.
4465  */
4466 int cgroup_add_dfl_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4467 {
4468         struct cftype *cft;
4469
4470         for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
4471                 cft->flags |= __CFTYPE_ONLY_ON_DFL;
4472         return cgroup_add_cftypes(ss, cfts);
4473 }
4474
4475 /**
4476  * cgroup_add_legacy_cftypes - add an array of cftypes for legacy hierarchies
4477  * @ss: target cgroup subsystem
4478  * @cfts: zero-length name terminated array of cftypes
4479  *
4480  * Similar to cgroup_add_cftypes() but the added files are only used for
4481  * the legacy hierarchies.
4482  */
4483 int cgroup_add_legacy_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
4484 {
4485         struct cftype *cft;
4486
4487         for (cft = cfts; cft && cft->name[0] != '\0'; cft++)
4488                 cft->flags |= __CFTYPE_NOT_ON_DFL;
4489         return cgroup_add_cftypes(ss, cfts);
4490 }
4491
4492 /**
4493  * cgroup_file_notify - generate a file modified event for a cgroup_file
4494  * @cfile: target cgroup_file
4495  *
4496  * @cfile must have been obtained by setting cftype->file_offset.
4497  */
4498 void cgroup_file_notify(struct cgroup_file *cfile)
4499 {
4500         unsigned long flags;
4501
4502         spin_lock_irqsave(&cgroup_file_kn_lock, flags);
4503         if (cfile->kn) {
4504                 unsigned long last = cfile->notified_at;
4505                 unsigned long next = last + CGROUP_FILE_NOTIFY_MIN_INTV;
4506
4507                 if (time_in_range(jiffies, last, next)) {
4508                         timer_reduce(&cfile->notify_timer, next);
4509                 } else {
4510                         kernfs_notify(cfile->kn);
4511                         cfile->notified_at = jiffies;
4512                 }
4513         }
4514         spin_unlock_irqrestore(&cgroup_file_kn_lock, flags);
4515 }
4516
4517 /**
4518  * cgroup_file_show - show or hide a hidden cgroup file
4519  * @cfile: target cgroup_file obtained by setting cftype->file_offset
4520  * @show: whether to show or hide
4521  */
4522 void cgroup_file_show(struct cgroup_file *cfile, bool show)
4523 {
4524         struct kernfs_node *kn;
4525
4526         spin_lock_irq(&cgroup_file_kn_lock);
4527         kn = cfile->kn;
4528         kernfs_get(kn);
4529         spin_unlock_irq(&cgroup_file_kn_lock);
4530
4531         if (kn)
4532                 kernfs_show(kn, show);
4533
4534         kernfs_put(kn);
4535 }
4536
4537 /**
4538  * css_next_child - find the next child of a given css
4539  * @pos: the current position (%NULL to initiate traversal)
4540  * @parent: css whose children to walk
4541  *
4542  * This function returns the next child of @parent and should be called
4543  * under either cgroup_mutex or RCU read lock.  The only requirement is
4544  * that @parent and @pos are accessible.  The next sibling is guaranteed to
4545  * be returned regardless of their states.
4546  *
4547  * If a subsystem synchronizes ->css_online() and the start of iteration, a
4548  * css which finished ->css_online() is guaranteed to be visible in the
4549  * future iterations and will stay visible until the last reference is put.
4550  * A css which hasn't finished ->css_online() or already finished
4551  * ->css_offline() may show up during traversal.  It's each subsystem's
4552  * responsibility to synchronize against on/offlining.
4553  */
4554 struct cgroup_subsys_state *css_next_child(struct cgroup_subsys_state *pos,
4555                                            struct cgroup_subsys_state *parent)
4556 {
4557         struct cgroup_subsys_state *next;
4558
4559         cgroup_assert_mutex_or_rcu_locked();
4560
4561         /*
4562          * @pos could already have been unlinked from the sibling list.
4563          * Once a cgroup is removed, its ->sibling.next is no longer
4564          * updated when its next sibling changes.  CSS_RELEASED is set when
4565          * @pos is taken off list, at which time its next pointer is valid,
4566          * and, as releases are serialized, the one pointed to by the next
4567          * pointer is guaranteed to not have started release yet.  This
4568          * implies that if we observe !CSS_RELEASED on @pos in this RCU
4569          * critical section, the one pointed to by its next pointer is
4570          * guaranteed to not have finished its RCU grace period even if we
4571          * have dropped rcu_read_lock() in-between iterations.
4572          *
4573          * If @pos has CSS_RELEASED set, its next pointer can't be
4574          * dereferenced; however, as each css is given a monotonically
4575          * increasing unique serial number and always appended to the
4576          * sibling list, the next one can be found by walking the parent's
4577          * children until the first css with higher serial number than
4578          * @pos's.  While this path can be slower, it happens iff iteration
4579          * races against release and the race window is very small.
4580          */
4581         if (!pos) {
4582                 next = list_entry_rcu(parent->children.next, struct cgroup_subsys_state, sibling);
4583         } else if (likely(!(pos->flags & CSS_RELEASED))) {
4584                 next = list_entry_rcu(pos->sibling.next, struct cgroup_subsys_state, sibling);
4585         } else {
4586                 list_for_each_entry_rcu(next, &parent->children, sibling,
4587                                         lockdep_is_held(&cgroup_mutex))
4588                         if (next->serial_nr > pos->serial_nr)
4589                                 break;
4590         }
4591
4592         /*
4593          * @next, if not pointing to the head, can be dereferenced and is
4594          * the next sibling.
4595          */
4596         if (&next->sibling != &parent->children)
4597                 return next;
4598         return NULL;
4599 }
4600
4601 /**
4602  * css_next_descendant_pre - find the next descendant for pre-order walk
4603  * @pos: the current position (%NULL to initiate traversal)
4604  * @root: css whose descendants to walk
4605  *
4606  * To be used by css_for_each_descendant_pre().  Find the next descendant
4607  * to visit for pre-order traversal of @root's descendants.  @root is
4608  * included in the iteration and the first node to be visited.
4609  *
4610  * While this function requires cgroup_mutex or RCU read locking, it
4611  * doesn't require the whole traversal to be contained in a single critical
4612  * section.  This function will return the correct next descendant as long
4613  * as both @pos and @root are accessible and @pos is a descendant of @root.
4614  *
4615  * If a subsystem synchronizes ->css_online() and the start of iteration, a
4616  * css which finished ->css_online() is guaranteed to be visible in the
4617  * future iterations and will stay visible until the last reference is put.
4618  * A css which hasn't finished ->css_online() or already finished
4619  * ->css_offline() may show up during traversal.  It's each subsystem's
4620  * responsibility to synchronize against on/offlining.
4621  */
4622 struct cgroup_subsys_state *
4623 css_next_descendant_pre(struct cgroup_subsys_state *pos,
4624                         struct cgroup_subsys_state *root)
4625 {
4626         struct cgroup_subsys_state *next;
4627
4628         cgroup_assert_mutex_or_rcu_locked();
4629
4630         /* if first iteration, visit @root */
4631         if (!pos)
4632                 return root;
4633
4634         /* visit the first child if exists */
4635         next = css_next_child(NULL, pos);
4636         if (next)
4637                 return next;
4638
4639         /* no child, visit my or the closest ancestor's next sibling */
4640         while (pos != root) {
4641                 next = css_next_child(pos, pos->parent);
4642                 if (next)
4643                         return next;
4644                 pos = pos->parent;
4645         }
4646
4647         return NULL;
4648 }
4649 EXPORT_SYMBOL_GPL(css_next_descendant_pre);
4650
4651 /**
4652  * css_rightmost_descendant - return the rightmost descendant of a css
4653  * @pos: css of interest
4654  *
4655  * Return the rightmost descendant of @pos.  If there's no descendant, @pos
4656  * is returned.  This can be used during pre-order traversal to skip
4657  * subtree of @pos.
4658  *
4659  * While this function requires cgroup_mutex or RCU read locking, it
4660  * doesn't require the whole traversal to be contained in a single critical
4661  * section.  This function will return the correct rightmost descendant as
4662  * long as @pos is accessible.
4663  */
4664 struct cgroup_subsys_state *
4665 css_rightmost_descendant(struct cgroup_subsys_state *pos)
4666 {
4667         struct cgroup_subsys_state *last, *tmp;
4668
4669         cgroup_assert_mutex_or_rcu_locked();
4670
4671         do {
4672                 last = pos;
4673                 /* ->prev isn't RCU safe, walk ->next till the end */
4674                 pos = NULL;
4675                 css_for_each_child(tmp, last)
4676                         pos = tmp;
4677         } while (pos);
4678
4679         return last;
4680 }
4681
4682 static struct cgroup_subsys_state *
4683 css_leftmost_descendant(struct cgroup_subsys_state *pos)
4684 {
4685         struct cgroup_subsys_state *last;
4686
4687         do {
4688                 last = pos;
4689                 pos = css_next_child(NULL, pos);
4690         } while (pos);
4691
4692         return last;
4693 }
4694
4695 /**
4696  * css_next_descendant_post - find the next descendant for post-order walk
4697  * @pos: the current position (%NULL to initiate traversal)
4698  * @root: css whose descendants to walk
4699  *
4700  * To be used by css_for_each_descendant_post().  Find the next descendant
4701  * to visit for post-order traversal of @root's descendants.  @root is
4702  * included in the iteration and the last node to be visited.
4703  *
4704  * While this function requires cgroup_mutex or RCU read locking, it
4705  * doesn't require the whole traversal to be contained in a single critical
4706  * section.  This function will return the correct next descendant as long
4707  * as both @pos and @cgroup are accessible and @pos is a descendant of
4708  * @cgroup.
4709  *
4710  * If a subsystem synchronizes ->css_online() and the start of iteration, a
4711  * css which finished ->css_online() is guaranteed to be visible in the
4712  * future iterations and will stay visible until the last reference is put.
4713  * A css which hasn't finished ->css_online() or already finished
4714  * ->css_offline() may show up during traversal.  It's each subsystem's
4715  * responsibility to synchronize against on/offlining.
4716  */
4717 struct cgroup_subsys_state *
4718 css_next_descendant_post(struct cgroup_subsys_state *pos,
4719                          struct cgroup_subsys_state *root)
4720 {
4721         struct cgroup_subsys_state *next;
4722
4723         cgroup_assert_mutex_or_rcu_locked();
4724
4725         /* if first iteration, visit leftmost descendant which may be @root */
4726         if (!pos)
4727                 return css_leftmost_descendant(root);
4728
4729         /* if we visited @root, we're done */
4730         if (pos == root)
4731                 return NULL;
4732
4733         /* if there's an unvisited sibling, visit its leftmost descendant */
4734         next = css_next_child(pos, pos->parent);
4735         if (next)
4736                 return css_leftmost_descendant(next);
4737
4738         /* no sibling left, visit parent */
4739         return pos->parent;
4740 }
4741
4742 /**
4743  * css_has_online_children - does a css have online children
4744  * @css: the target css
4745  *
4746  * Returns %true if @css has any online children; otherwise, %false.  This
4747  * function can be called from any context but the caller is responsible
4748  * for synchronizing against on/offlining as necessary.
4749  */
4750 bool css_has_online_children(struct cgroup_subsys_state *css)
4751 {
4752         struct cgroup_subsys_state *child;
4753         bool ret = false;
4754
4755         rcu_read_lock();
4756         css_for_each_child(child, css) {
4757                 if (child->flags & CSS_ONLINE) {
4758                         ret = true;
4759                         break;
4760                 }
4761         }
4762         rcu_read_unlock();
4763         return ret;
4764 }
4765
4766 static struct css_set *css_task_iter_next_css_set(struct css_task_iter *it)
4767 {
4768         struct list_head *l;
4769         struct cgrp_cset_link *link;
4770         struct css_set *cset;
4771
4772         lockdep_assert_held(&css_set_lock);
4773
4774         /* find the next threaded cset */
4775         if (it->tcset_pos) {
4776                 l = it->tcset_pos->next;
4777
4778                 if (l != it->tcset_head) {
4779                         it->tcset_pos = l;
4780                         return container_of(l, struct css_set,
4781                                             threaded_csets_node);
4782                 }
4783
4784                 it->tcset_pos = NULL;
4785         }
4786
4787         /* find the next cset */
4788         l = it->cset_pos;
4789         l = l->next;
4790         if (l == it->cset_head) {
4791                 it->cset_pos = NULL;
4792                 return NULL;
4793         }
4794
4795         if (it->ss) {
4796                 cset = container_of(l, struct css_set, e_cset_node[it->ss->id]);
4797         } else {
4798                 link = list_entry(l, struct cgrp_cset_link, cset_link);
4799                 cset = link->cset;
4800         }
4801
4802         it->cset_pos = l;
4803
4804         /* initialize threaded css_set walking */
4805         if (it->flags & CSS_TASK_ITER_THREADED) {
4806                 if (it->cur_dcset)
4807                         put_css_set_locked(it->cur_dcset);
4808                 it->cur_dcset = cset;
4809                 get_css_set(cset);
4810
4811                 it->tcset_head = &cset->threaded_csets;
4812                 it->tcset_pos = &cset->threaded_csets;
4813         }
4814
4815         return cset;
4816 }
4817
4818 /**
4819  * css_task_iter_advance_css_set - advance a task iterator to the next css_set
4820  * @it: the iterator to advance
4821  *
4822  * Advance @it to the next css_set to walk.
4823  */
4824 static void css_task_iter_advance_css_set(struct css_task_iter *it)
4825 {
4826         struct css_set *cset;
4827
4828         lockdep_assert_held(&css_set_lock);
4829
4830         /* Advance to the next non-empty css_set and find first non-empty tasks list*/
4831         while ((cset = css_task_iter_next_css_set(it))) {
4832                 if (!list_empty(&cset->tasks)) {
4833                         it->cur_tasks_head = &cset->tasks;
4834                         break;
4835                 } else if (!list_empty(&cset->mg_tasks)) {
4836                         it->cur_tasks_head = &cset->mg_tasks;
4837                         break;
4838                 } else if (!list_empty(&cset->dying_tasks)) {
4839                         it->cur_tasks_head = &cset->dying_tasks;
4840                         break;
4841                 }
4842         }
4843         if (!cset) {
4844                 it->task_pos = NULL;
4845                 return;
4846         }
4847         it->task_pos = it->cur_tasks_head->next;
4848
4849         /*
4850          * We don't keep css_sets locked across iteration steps and thus
4851          * need to take steps to ensure that iteration can be resumed after
4852          * the lock is re-acquired.  Iteration is performed at two levels -
4853          * css_sets and tasks in them.
4854          *
4855          * Once created, a css_set never leaves its cgroup lists, so a
4856          * pinned css_set is guaranteed to stay put and we can resume
4857          * iteration afterwards.
4858          *
4859          * Tasks may leave @cset across iteration steps.  This is resolved
4860          * by registering each iterator with the css_set currently being
4861          * walked and making css_set_move_task() advance iterators whose
4862          * next task is leaving.
4863          */
4864         if (it->cur_cset) {
4865                 list_del(&it->iters_node);
4866                 put_css_set_locked(it->cur_cset);
4867         }
4868         get_css_set(cset);
4869         it->cur_cset = cset;
4870         list_add(&it->iters_node, &cset->task_iters);
4871 }
4872
4873 static void css_task_iter_skip(struct css_task_iter *it,
4874                                struct task_struct *task)
4875 {
4876         lockdep_assert_held(&css_set_lock);
4877
4878         if (it->task_pos == &task->cg_list) {
4879                 it->task_pos = it->task_pos->next;
4880                 it->flags |= CSS_TASK_ITER_SKIPPED;
4881         }
4882 }
4883
4884 static void css_task_iter_advance(struct css_task_iter *it)
4885 {
4886         struct task_struct *task;
4887
4888         lockdep_assert_held(&css_set_lock);
4889 repeat:
4890         if (it->task_pos) {
4891                 /*
4892                  * Advance iterator to find next entry. We go through cset
4893                  * tasks, mg_tasks and dying_tasks, when consumed we move onto
4894                  * the next cset.
4895                  */
4896                 if (it->flags & CSS_TASK_ITER_SKIPPED)
4897                         it->flags &= ~CSS_TASK_ITER_SKIPPED;
4898                 else
4899                         it->task_pos = it->task_pos->next;
4900
4901                 if (it->task_pos == &it->cur_cset->tasks) {
4902                         it->cur_tasks_head = &it->cur_cset->mg_tasks;
4903                         it->task_pos = it->cur_tasks_head->next;
4904                 }
4905                 if (it->task_pos == &it->cur_cset->mg_tasks) {
4906                         it->cur_tasks_head = &it->cur_cset->dying_tasks;
4907                         it->task_pos = it->cur_tasks_head->next;
4908                 }
4909                 if (it->task_pos == &it->cur_cset->dying_tasks)
4910                         css_task_iter_advance_css_set(it);
4911         } else {
4912                 /* called from start, proceed to the first cset */
4913                 css_task_iter_advance_css_set(it);
4914         }
4915
4916         if (!it->task_pos)
4917                 return;
4918
4919         task = list_entry(it->task_pos, struct task_struct, cg_list);
4920
4921         if (it->flags & CSS_TASK_ITER_PROCS) {
4922                 /* if PROCS, skip over tasks which aren't group leaders */
4923                 if (!thread_group_leader(task))
4924                         goto repeat;
4925
4926                 /* and dying leaders w/o live member threads */
4927                 if (it->cur_tasks_head == &it->cur_cset->dying_tasks &&
4928                     !atomic_read(&task->signal->live))
4929                         goto repeat;
4930         } else {
4931                 /* skip all dying ones */
4932                 if (it->cur_tasks_head == &it->cur_cset->dying_tasks)
4933                         goto repeat;
4934         }
4935 }
4936
4937 /**
4938  * css_task_iter_start - initiate task iteration
4939  * @css: the css to walk tasks of
4940  * @flags: CSS_TASK_ITER_* flags
4941  * @it: the task iterator to use
4942  *
4943  * Initiate iteration through the tasks of @css.  The caller can call
4944  * css_task_iter_next() to walk through the tasks until the function
4945  * returns NULL.  On completion of iteration, css_task_iter_end() must be
4946  * called.
4947  */
4948 void css_task_iter_start(struct cgroup_subsys_state *css, unsigned int flags,
4949                          struct css_task_iter *it)
4950 {
4951         memset(it, 0, sizeof(*it));
4952
4953         spin_lock_irq(&css_set_lock);
4954
4955         it->ss = css->ss;
4956         it->flags = flags;
4957
4958         if (CGROUP_HAS_SUBSYS_CONFIG && it->ss)
4959                 it->cset_pos = &css->cgroup->e_csets[css->ss->id];
4960         else
4961                 it->cset_pos = &css->cgroup->cset_links;
4962
4963         it->cset_head = it->cset_pos;
4964
4965         css_task_iter_advance(it);
4966
4967         spin_unlock_irq(&css_set_lock);
4968 }
4969
4970 /**
4971  * css_task_iter_next - return the next task for the iterator
4972  * @it: the task iterator being iterated
4973  *
4974  * The "next" function for task iteration.  @it should have been
4975  * initialized via css_task_iter_start().  Returns NULL when the iteration
4976  * reaches the end.
4977  */
4978 struct task_struct *css_task_iter_next(struct css_task_iter *it)
4979 {
4980         if (it->cur_task) {
4981                 put_task_struct(it->cur_task);
4982                 it->cur_task = NULL;
4983         }
4984
4985         spin_lock_irq(&css_set_lock);
4986
4987         /* @it may be half-advanced by skips, finish advancing */
4988         if (it->flags & CSS_TASK_ITER_SKIPPED)
4989                 css_task_iter_advance(it);
4990
4991         if (it->task_pos) {
4992                 it->cur_task = list_entry(it->task_pos, struct task_struct,
4993                                           cg_list);
4994                 get_task_struct(it->cur_task);
4995                 css_task_iter_advance(it);
4996         }
4997
4998         spin_unlock_irq(&css_set_lock);
4999
5000         return it->cur_task;
5001 }
5002
5003 /**
5004  * css_task_iter_end - finish task iteration
5005  * @it: the task iterator to finish
5006  *
5007  * Finish task iteration started by css_task_iter_start().
5008  */
5009 void css_task_iter_end(struct css_task_iter *it)
5010 {
5011         if (it->cur_cset) {
5012                 spin_lock_irq(&css_set_lock);
5013                 list_del(&it->iters_node);
5014                 put_css_set_locked(it->cur_cset);
5015                 spin_unlock_irq(&css_set_lock);
5016         }
5017
5018         if (it->cur_dcset)
5019                 put_css_set(it->cur_dcset);
5020
5021         if (it->cur_task)
5022                 put_task_struct(it->cur_task);
5023 }
5024
5025 static void cgroup_procs_release(struct kernfs_open_file *of)
5026 {
5027         struct cgroup_file_ctx *ctx = of->priv;
5028
5029         if (ctx->procs.started)
5030                 css_task_iter_end(&ctx->procs.iter);
5031 }
5032
5033 static void *cgroup_procs_next(struct seq_file *s, void *v, loff_t *pos)
5034 {
5035         struct kernfs_open_file *of = s->private;
5036         struct cgroup_file_ctx *ctx = of->priv;
5037
5038         if (pos)
5039                 (*pos)++;
5040
5041         return css_task_iter_next(&ctx->procs.iter);
5042 }
5043
5044 static void *__cgroup_procs_start(struct seq_file *s, loff_t *pos,
5045                                   unsigned int iter_flags)
5046 {
5047         struct kernfs_open_file *of = s->private;
5048         struct cgroup *cgrp = seq_css(s)->cgroup;
5049         struct cgroup_file_ctx *ctx = of->priv;
5050         struct css_task_iter *it = &ctx->procs.iter;
5051
5052         /*
5053          * When a seq_file is seeked, it's always traversed sequentially
5054          * from position 0, so we can simply keep iterating on !0 *pos.
5055          */
5056         if (!ctx->procs.started) {
5057                 if (WARN_ON_ONCE((*pos)))
5058                         return ERR_PTR(-EINVAL);
5059                 css_task_iter_start(&cgrp->self, iter_flags, it);
5060                 ctx->procs.started = true;
5061         } else if (!(*pos)) {
5062                 css_task_iter_end(it);
5063                 css_task_iter_start(&cgrp->self, iter_flags, it);
5064         } else
5065                 return it->cur_task;
5066
5067         return cgroup_procs_next(s, NULL, NULL);
5068 }
5069
5070 static void *cgroup_procs_start(struct seq_file *s, loff_t *pos)
5071 {
5072         struct cgroup *cgrp = seq_css(s)->cgroup;
5073
5074         /*
5075          * All processes of a threaded subtree belong to the domain cgroup
5076          * of the subtree.  Only threads can be distributed across the
5077          * subtree.  Reject reads on cgroup.procs in the subtree proper.
5078          * They're always empty anyway.
5079          */
5080         if (cgroup_is_threaded(cgrp))
5081                 return ERR_PTR(-EOPNOTSUPP);
5082
5083         return __cgroup_procs_start(s, pos, CSS_TASK_ITER_PROCS |
5084                                             CSS_TASK_ITER_THREADED);
5085 }
5086
5087 static int cgroup_procs_show(struct seq_file *s, void *v)
5088 {
5089         seq_printf(s, "%d\n", task_pid_vnr(v));
5090         return 0;
5091 }
5092
5093 static int cgroup_may_write(const struct cgroup *cgrp, struct super_block *sb)
5094 {
5095         int ret;
5096         struct inode *inode;
5097
5098         lockdep_assert_held(&cgroup_mutex);
5099
5100         inode = kernfs_get_inode(sb, cgrp->procs_file.kn);
5101         if (!inode)
5102                 return -ENOMEM;
5103
5104         ret = inode_permission(&nop_mnt_idmap, inode, MAY_WRITE);
5105         iput(inode);
5106         return ret;
5107 }
5108
5109 static int cgroup_procs_write_permission(struct cgroup *src_cgrp,
5110                                          struct cgroup *dst_cgrp,
5111                                          struct super_block *sb,
5112                                          struct cgroup_namespace *ns)
5113 {
5114         struct cgroup *com_cgrp = src_cgrp;
5115         int ret;
5116
5117         lockdep_assert_held(&cgroup_mutex);
5118
5119         /* find the common ancestor */
5120         while (!cgroup_is_descendant(dst_cgrp, com_cgrp))
5121                 com_cgrp = cgroup_parent(com_cgrp);
5122
5123         /* %current should be authorized to migrate to the common ancestor */
5124         ret = cgroup_may_write(com_cgrp, sb);
5125         if (ret)
5126                 return ret;
5127
5128         /*
5129          * If namespaces are delegation boundaries, %current must be able
5130          * to see both source and destination cgroups from its namespace.
5131          */
5132         if ((cgrp_dfl_root.flags & CGRP_ROOT_NS_DELEGATE) &&
5133             (!cgroup_is_descendant(src_cgrp, ns->root_cset->dfl_cgrp) ||
5134              !cgroup_is_descendant(dst_cgrp, ns->root_cset->dfl_cgrp)))
5135                 return -ENOENT;
5136
5137         return 0;
5138 }
5139
5140 static int cgroup_attach_permissions(struct cgroup *src_cgrp,
5141                                      struct cgroup *dst_cgrp,
5142                                      struct super_block *sb, bool threadgroup,
5143                                      struct cgroup_namespace *ns)
5144 {
5145         int ret = 0;
5146
5147         ret = cgroup_procs_write_permission(src_cgrp, dst_cgrp, sb, ns);
5148         if (ret)
5149                 return ret;
5150
5151         ret = cgroup_migrate_vet_dst(dst_cgrp);
5152         if (ret)
5153                 return ret;
5154
5155         if (!threadgroup && (src_cgrp->dom_cgrp != dst_cgrp->dom_cgrp))
5156                 ret = -EOPNOTSUPP;
5157
5158         return ret;
5159 }
5160
5161 static ssize_t __cgroup_procs_write(struct kernfs_open_file *of, char *buf,
5162                                     bool threadgroup)
5163 {
5164         struct cgroup_file_ctx *ctx = of->priv;
5165         struct cgroup *src_cgrp, *dst_cgrp;
5166         struct task_struct *task;
5167         const struct cred *saved_cred;
5168         ssize_t ret;
5169         bool threadgroup_locked;
5170
5171         dst_cgrp = cgroup_kn_lock_live(of->kn, false);
5172         if (!dst_cgrp)
5173                 return -ENODEV;
5174
5175         task = cgroup_procs_write_start(buf, threadgroup, &threadgroup_locked);
5176         ret = PTR_ERR_OR_ZERO(task);
5177         if (ret)
5178                 goto out_unlock;
5179
5180         /* find the source cgroup */
5181         spin_lock_irq(&css_set_lock);
5182         src_cgrp = task_cgroup_from_root(task, &cgrp_dfl_root);
5183         spin_unlock_irq(&css_set_lock);
5184
5185         /*
5186          * Process and thread migrations follow same delegation rule. Check
5187          * permissions using the credentials from file open to protect against
5188          * inherited fd attacks.
5189          */
5190         saved_cred = override_creds(of->file->f_cred);
5191         ret = cgroup_attach_permissions(src_cgrp, dst_cgrp,
5192                                         of->file->f_path.dentry->d_sb,
5193                                         threadgroup, ctx->ns);
5194         revert_creds(saved_cred);
5195         if (ret)
5196                 goto out_finish;
5197
5198         ret = cgroup_attach_task(dst_cgrp, task, threadgroup);
5199
5200 out_finish:
5201         cgroup_procs_write_finish(task, threadgroup_locked);
5202 out_unlock:
5203         cgroup_kn_unlock(of->kn);
5204
5205         return ret;
5206 }
5207
5208 static ssize_t cgroup_procs_write(struct kernfs_open_file *of,
5209                                   char *buf, size_t nbytes, loff_t off)
5210 {
5211         return __cgroup_procs_write(of, buf, true) ?: nbytes;
5212 }
5213
5214 static void *cgroup_threads_start(struct seq_file *s, loff_t *pos)
5215 {
5216         return __cgroup_procs_start(s, pos, 0);
5217 }
5218
5219 static ssize_t cgroup_threads_write(struct kernfs_open_file *of,
5220                                     char *buf, size_t nbytes, loff_t off)
5221 {
5222         return __cgroup_procs_write(of, buf, false) ?: nbytes;
5223 }
5224
5225 /* cgroup core interface files for the default hierarchy */
5226 static struct cftype cgroup_base_files[] = {
5227         {
5228                 .name = "cgroup.type",
5229                 .flags = CFTYPE_NOT_ON_ROOT,
5230                 .seq_show = cgroup_type_show,
5231                 .write = cgroup_type_write,
5232         },
5233         {
5234                 .name = "cgroup.procs",
5235                 .flags = CFTYPE_NS_DELEGATABLE,
5236                 .file_offset = offsetof(struct cgroup, procs_file),
5237                 .release = cgroup_procs_release,
5238                 .seq_start = cgroup_procs_start,
5239                 .seq_next = cgroup_procs_next,
5240                 .seq_show = cgroup_procs_show,
5241                 .write = cgroup_procs_write,
5242         },
5243         {
5244                 .name = "cgroup.threads",
5245                 .flags = CFTYPE_NS_DELEGATABLE,
5246                 .release = cgroup_procs_release,
5247                 .seq_start = cgroup_threads_start,
5248                 .seq_next = cgroup_procs_next,
5249                 .seq_show = cgroup_procs_show,
5250                 .write = cgroup_threads_write,
5251         },
5252         {
5253                 .name = "cgroup.controllers",
5254                 .seq_show = cgroup_controllers_show,
5255         },
5256         {
5257                 .name = "cgroup.subtree_control",
5258                 .flags = CFTYPE_NS_DELEGATABLE,
5259                 .seq_show = cgroup_subtree_control_show,
5260                 .write = cgroup_subtree_control_write,
5261         },
5262         {
5263                 .name = "cgroup.events",
5264                 .flags = CFTYPE_NOT_ON_ROOT,
5265                 .file_offset = offsetof(struct cgroup, events_file),
5266                 .seq_show = cgroup_events_show,
5267         },
5268         {
5269                 .name = "cgroup.max.descendants",
5270                 .seq_show = cgroup_max_descendants_show,
5271                 .write = cgroup_max_descendants_write,
5272         },
5273         {
5274                 .name = "cgroup.max.depth",
5275                 .seq_show = cgroup_max_depth_show,
5276                 .write = cgroup_max_depth_write,
5277         },
5278         {
5279                 .name = "cgroup.stat",
5280                 .seq_show = cgroup_stat_show,
5281         },
5282         {
5283                 .name = "cgroup.freeze",
5284                 .flags = CFTYPE_NOT_ON_ROOT,
5285                 .seq_show = cgroup_freeze_show,
5286                 .write = cgroup_freeze_write,
5287         },
5288         {
5289                 .name = "cgroup.kill",
5290                 .flags = CFTYPE_NOT_ON_ROOT,
5291                 .write = cgroup_kill_write,
5292         },
5293         {
5294                 .name = "cpu.stat",
5295                 .seq_show = cpu_stat_show,
5296         },
5297         {
5298                 .name = "cpu.stat.local",
5299                 .seq_show = cpu_local_stat_show,
5300         },
5301         { }     /* terminate */
5302 };
5303
5304 static struct cftype cgroup_psi_files[] = {
5305 #ifdef CONFIG_PSI
5306         {
5307                 .name = "io.pressure",
5308                 .file_offset = offsetof(struct cgroup, psi_files[PSI_IO]),
5309                 .seq_show = cgroup_io_pressure_show,
5310                 .write = cgroup_io_pressure_write,
5311                 .poll = cgroup_pressure_poll,
5312                 .release = cgroup_pressure_release,
5313         },
5314         {
5315                 .name = "memory.pressure",
5316                 .file_offset = offsetof(struct cgroup, psi_files[PSI_MEM]),
5317                 .seq_show = cgroup_memory_pressure_show,
5318                 .write = cgroup_memory_pressure_write,
5319                 .poll = cgroup_pressure_poll,
5320                 .release = cgroup_pressure_release,
5321         },
5322         {
5323                 .name = "cpu.pressure",
5324                 .file_offset = offsetof(struct cgroup, psi_files[PSI_CPU]),
5325                 .seq_show = cgroup_cpu_pressure_show,
5326                 .write = cgroup_cpu_pressure_write,
5327                 .poll = cgroup_pressure_poll,
5328                 .release = cgroup_pressure_release,
5329         },
5330 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
5331         {
5332                 .name = "irq.pressure",
5333                 .file_offset = offsetof(struct cgroup, psi_files[PSI_IRQ]),
5334                 .seq_show = cgroup_irq_pressure_show,
5335                 .write = cgroup_irq_pressure_write,
5336                 .poll = cgroup_pressure_poll,
5337                 .release = cgroup_pressure_release,
5338         },
5339 #endif
5340         {
5341                 .name = "cgroup.pressure",
5342                 .seq_show = cgroup_pressure_show,
5343                 .write = cgroup_pressure_write,
5344         },
5345 #endif /* CONFIG_PSI */
5346         { }     /* terminate */
5347 };
5348
5349 /*
5350  * css destruction is four-stage process.
5351  *
5352  * 1. Destruction starts.  Killing of the percpu_ref is initiated.
5353  *    Implemented in kill_css().
5354  *
5355  * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
5356  *    and thus css_tryget_online() is guaranteed to fail, the css can be
5357  *    offlined by invoking offline_css().  After offlining, the base ref is
5358  *    put.  Implemented in css_killed_work_fn().
5359  *
5360  * 3. When the percpu_ref reaches zero, the only possible remaining
5361  *    accessors are inside RCU read sections.  css_release() schedules the
5362  *    RCU callback.
5363  *
5364  * 4. After the grace period, the css can be freed.  Implemented in
5365  *    css_free_rwork_fn().
5366  *
5367  * It is actually hairier because both step 2 and 4 require process context
5368  * and thus involve punting to css->destroy_work adding two additional
5369  * steps to the already complex sequence.
5370  */
5371 static void css_free_rwork_fn(struct work_struct *work)
5372 {
5373         struct cgroup_subsys_state *css = container_of(to_rcu_work(work),
5374                                 struct cgroup_subsys_state, destroy_rwork);
5375         struct cgroup_subsys *ss = css->ss;
5376         struct cgroup *cgrp = css->cgroup;
5377
5378         percpu_ref_exit(&css->refcnt);
5379
5380         if (ss) {
5381                 /* css free path */
5382                 struct cgroup_subsys_state *parent = css->parent;
5383                 int id = css->id;
5384
5385                 ss->css_free(css);
5386                 cgroup_idr_remove(&ss->css_idr, id);
5387                 cgroup_put(cgrp);
5388
5389                 if (parent)
5390                         css_put(parent);
5391         } else {
5392                 /* cgroup free path */
5393                 atomic_dec(&cgrp->root->nr_cgrps);
5394                 cgroup1_pidlist_destroy_all(cgrp);
5395                 cancel_work_sync(&cgrp->release_agent_work);
5396                 bpf_cgrp_storage_free(cgrp);
5397
5398                 if (cgroup_parent(cgrp)) {
5399                         /*
5400                          * We get a ref to the parent, and put the ref when
5401                          * this cgroup is being freed, so it's guaranteed
5402                          * that the parent won't be destroyed before its
5403                          * children.
5404                          */
5405                         cgroup_put(cgroup_parent(cgrp));
5406                         kernfs_put(cgrp->kn);
5407                         psi_cgroup_free(cgrp);
5408                         cgroup_rstat_exit(cgrp);
5409                         kfree(cgrp);
5410                 } else {
5411                         /*
5412                          * This is root cgroup's refcnt reaching zero,
5413                          * which indicates that the root should be
5414                          * released.
5415                          */
5416                         cgroup_destroy_root(cgrp->root);
5417                 }
5418         }
5419 }
5420
5421 static void css_release_work_fn(struct work_struct *work)
5422 {
5423         struct cgroup_subsys_state *css =
5424                 container_of(work, struct cgroup_subsys_state, destroy_work);
5425         struct cgroup_subsys *ss = css->ss;
5426         struct cgroup *cgrp = css->cgroup;
5427
5428         cgroup_lock();
5429
5430         css->flags |= CSS_RELEASED;
5431         list_del_rcu(&css->sibling);
5432
5433         if (ss) {
5434                 /* css release path */
5435                 if (!list_empty(&css->rstat_css_node)) {
5436                         cgroup_rstat_flush(cgrp);
5437                         list_del_rcu(&css->rstat_css_node);
5438                 }
5439
5440                 cgroup_idr_replace(&ss->css_idr, NULL, css->id);
5441                 if (ss->css_released)
5442                         ss->css_released(css);
5443         } else {
5444                 struct cgroup *tcgrp;
5445
5446                 /* cgroup release path */
5447                 TRACE_CGROUP_PATH(release, cgrp);
5448
5449                 cgroup_rstat_flush(cgrp);
5450
5451                 spin_lock_irq(&css_set_lock);
5452                 for (tcgrp = cgroup_parent(cgrp); tcgrp;
5453                      tcgrp = cgroup_parent(tcgrp))
5454                         tcgrp->nr_dying_descendants--;
5455                 spin_unlock_irq(&css_set_lock);
5456
5457                 /*
5458                  * There are two control paths which try to determine
5459                  * cgroup from dentry without going through kernfs -
5460                  * cgroupstats_build() and css_tryget_online_from_dir().
5461                  * Those are supported by RCU protecting clearing of
5462                  * cgrp->kn->priv backpointer.
5463                  */
5464                 if (cgrp->kn)
5465                         RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv,
5466                                          NULL);
5467         }
5468
5469         cgroup_unlock();
5470
5471         INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
5472         queue_rcu_work(cgroup_destroy_wq, &css->destroy_rwork);
5473 }
5474
5475 static void css_release(struct percpu_ref *ref)
5476 {
5477         struct cgroup_subsys_state *css =
5478                 container_of(ref, struct cgroup_subsys_state, refcnt);
5479
5480         INIT_WORK(&css->destroy_work, css_release_work_fn);
5481         queue_work(cgroup_destroy_wq, &css->destroy_work);
5482 }
5483
5484 static void init_and_link_css(struct cgroup_subsys_state *css,
5485                               struct cgroup_subsys *ss, struct cgroup *cgrp)
5486 {
5487         lockdep_assert_held(&cgroup_mutex);
5488
5489         cgroup_get_live(cgrp);
5490
5491         memset(css, 0, sizeof(*css));
5492         css->cgroup = cgrp;
5493         css->ss = ss;
5494         css->id = -1;
5495         INIT_LIST_HEAD(&css->sibling);
5496         INIT_LIST_HEAD(&css->children);
5497         INIT_LIST_HEAD(&css->rstat_css_node);
5498         css->serial_nr = css_serial_nr_next++;
5499         atomic_set(&css->online_cnt, 0);
5500
5501         if (cgroup_parent(cgrp)) {
5502                 css->parent = cgroup_css(cgroup_parent(cgrp), ss);
5503                 css_get(css->parent);
5504         }
5505
5506         if (ss->css_rstat_flush)
5507                 list_add_rcu(&css->rstat_css_node, &cgrp->rstat_css_list);
5508
5509         BUG_ON(cgroup_css(cgrp, ss));
5510 }
5511
5512 /* invoke ->css_online() on a new CSS and mark it online if successful */
5513 static int online_css(struct cgroup_subsys_state *css)
5514 {
5515         struct cgroup_subsys *ss = css->ss;
5516         int ret = 0;
5517
5518         lockdep_assert_held(&cgroup_mutex);
5519
5520         if (ss->css_online)
5521                 ret = ss->css_online(css);
5522         if (!ret) {
5523                 css->flags |= CSS_ONLINE;
5524                 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
5525
5526                 atomic_inc(&css->online_cnt);
5527                 if (css->parent)
5528                         atomic_inc(&css->parent->online_cnt);
5529         }
5530         return ret;
5531 }
5532
5533 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
5534 static void offline_css(struct cgroup_subsys_state *css)
5535 {
5536         struct cgroup_subsys *ss = css->ss;
5537
5538         lockdep_assert_held(&cgroup_mutex);
5539
5540         if (!(css->flags & CSS_ONLINE))
5541                 return;
5542
5543         if (ss->css_offline)
5544                 ss->css_offline(css);
5545
5546         css->flags &= ~CSS_ONLINE;
5547         RCU_INIT_POINTER(css->cgroup->subsys[ss->id], NULL);
5548
5549         wake_up_all(&css->cgroup->offline_waitq);
5550 }
5551
5552 /**
5553  * css_create - create a cgroup_subsys_state
5554  * @cgrp: the cgroup new css will be associated with
5555  * @ss: the subsys of new css
5556  *
5557  * Create a new css associated with @cgrp - @ss pair.  On success, the new
5558  * css is online and installed in @cgrp.  This function doesn't create the
5559  * interface files.  Returns 0 on success, -errno on failure.
5560  */
5561 static struct cgroup_subsys_state *css_create(struct cgroup *cgrp,
5562                                               struct cgroup_subsys *ss)
5563 {
5564         struct cgroup *parent = cgroup_parent(cgrp);
5565         struct cgroup_subsys_state *parent_css = cgroup_css(parent, ss);
5566         struct cgroup_subsys_state *css;
5567         int err;
5568
5569         lockdep_assert_held(&cgroup_mutex);
5570
5571         css = ss->css_alloc(parent_css);
5572         if (!css)
5573                 css = ERR_PTR(-ENOMEM);
5574         if (IS_ERR(css))
5575                 return css;
5576
5577         init_and_link_css(css, ss, cgrp);
5578
5579         err = percpu_ref_init(&css->refcnt, css_release, 0, GFP_KERNEL);
5580         if (err)
5581                 goto err_free_css;
5582
5583         err = cgroup_idr_alloc(&ss->css_idr, NULL, 2, 0, GFP_KERNEL);
5584         if (err < 0)
5585                 goto err_free_css;
5586         css->id = err;
5587
5588         /* @css is ready to be brought online now, make it visible */
5589         list_add_tail_rcu(&css->sibling, &parent_css->children);
5590         cgroup_idr_replace(&ss->css_idr, css, css->id);
5591
5592         err = online_css(css);
5593         if (err)
5594                 goto err_list_del;
5595
5596         return css;
5597
5598 err_list_del:
5599         list_del_rcu(&css->sibling);
5600 err_free_css:
5601         list_del_rcu(&css->rstat_css_node);
5602         INIT_RCU_WORK(&css->destroy_rwork, css_free_rwork_fn);
5603         queue_rcu_work(cgroup_destroy_wq, &css->destroy_rwork);
5604         return ERR_PTR(err);
5605 }
5606
5607 /*
5608  * The returned cgroup is fully initialized including its control mask, but
5609  * it doesn't have the control mask applied.
5610  */
5611 static struct cgroup *cgroup_create(struct cgroup *parent, const char *name,
5612                                     umode_t mode)
5613 {
5614         struct cgroup_root *root = parent->root;
5615         struct cgroup *cgrp, *tcgrp;
5616         struct kernfs_node *kn;
5617         int level = parent->level + 1;
5618         int ret;
5619
5620         /* allocate the cgroup and its ID, 0 is reserved for the root */
5621         cgrp = kzalloc(struct_size(cgrp, ancestors, (level + 1)), GFP_KERNEL);
5622         if (!cgrp)
5623                 return ERR_PTR(-ENOMEM);
5624
5625         ret = percpu_ref_init(&cgrp->self.refcnt, css_release, 0, GFP_KERNEL);
5626         if (ret)
5627                 goto out_free_cgrp;
5628
5629         ret = cgroup_rstat_init(cgrp);
5630         if (ret)
5631                 goto out_cancel_ref;
5632
5633         /* create the directory */
5634         kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
5635         if (IS_ERR(kn)) {
5636                 ret = PTR_ERR(kn);
5637                 goto out_stat_exit;
5638         }
5639         cgrp->kn = kn;
5640
5641         init_cgroup_housekeeping(cgrp);
5642
5643         cgrp->self.parent = &parent->self;
5644         cgrp->root = root;
5645         cgrp->level = level;
5646
5647         ret = psi_cgroup_alloc(cgrp);
5648         if (ret)
5649                 goto out_kernfs_remove;
5650
5651         ret = cgroup_bpf_inherit(cgrp);
5652         if (ret)
5653                 goto out_psi_free;
5654
5655         /*
5656          * New cgroup inherits effective freeze counter, and
5657          * if the parent has to be frozen, the child has too.
5658          */
5659         cgrp->freezer.e_freeze = parent->freezer.e_freeze;
5660         if (cgrp->freezer.e_freeze) {
5661                 /*
5662                  * Set the CGRP_FREEZE flag, so when a process will be
5663                  * attached to the child cgroup, it will become frozen.
5664                  * At this point the new cgroup is unpopulated, so we can
5665                  * consider it frozen immediately.
5666                  */
5667                 set_bit(CGRP_FREEZE, &cgrp->flags);
5668                 set_bit(CGRP_FROZEN, &cgrp->flags);
5669         }
5670
5671         spin_lock_irq(&css_set_lock);
5672         for (tcgrp = cgrp; tcgrp; tcgrp = cgroup_parent(tcgrp)) {
5673                 cgrp->ancestors[tcgrp->level] = tcgrp;
5674
5675                 if (tcgrp != cgrp) {
5676                         tcgrp->nr_descendants++;
5677
5678                         /*
5679                          * If the new cgroup is frozen, all ancestor cgroups
5680                          * get a new frozen descendant, but their state can't
5681                          * change because of this.
5682                          */
5683                         if (cgrp->freezer.e_freeze)
5684                                 tcgrp->freezer.nr_frozen_descendants++;
5685                 }
5686         }
5687         spin_unlock_irq(&css_set_lock);
5688
5689         if (notify_on_release(parent))
5690                 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
5691
5692         if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
5693                 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
5694
5695         cgrp->self.serial_nr = css_serial_nr_next++;
5696
5697         /* allocation complete, commit to creation */
5698         list_add_tail_rcu(&cgrp->self.sibling, &cgroup_parent(cgrp)->self.children);
5699         atomic_inc(&root->nr_cgrps);
5700         cgroup_get_live(parent);
5701
5702         /*
5703          * On the default hierarchy, a child doesn't automatically inherit
5704          * subtree_control from the parent.  Each is configured manually.
5705          */
5706         if (!cgroup_on_dfl(cgrp))
5707                 cgrp->subtree_control = cgroup_control(cgrp);
5708
5709         cgroup_propagate_control(cgrp);
5710
5711         return cgrp;
5712
5713 out_psi_free:
5714         psi_cgroup_free(cgrp);
5715 out_kernfs_remove:
5716         kernfs_remove(cgrp->kn);
5717 out_stat_exit:
5718         cgroup_rstat_exit(cgrp);
5719 out_cancel_ref:
5720         percpu_ref_exit(&cgrp->self.refcnt);
5721 out_free_cgrp:
5722         kfree(cgrp);
5723         return ERR_PTR(ret);
5724 }
5725
5726 static bool cgroup_check_hierarchy_limits(struct cgroup *parent)
5727 {
5728         struct cgroup *cgroup;
5729         int ret = false;
5730         int level = 1;
5731
5732         lockdep_assert_held(&cgroup_mutex);
5733
5734         for (cgroup = parent; cgroup; cgroup = cgroup_parent(cgroup)) {
5735                 if (cgroup->nr_descendants >= cgroup->max_descendants)
5736                         goto fail;
5737
5738                 if (level > cgroup->max_depth)
5739                         goto fail;
5740
5741                 level++;
5742         }
5743
5744         ret = true;
5745 fail:
5746         return ret;
5747 }
5748
5749 int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name, umode_t mode)
5750 {
5751         struct cgroup *parent, *cgrp;
5752         int ret;
5753
5754         /* do not accept '\n' to prevent making /proc/<pid>/cgroup unparsable */
5755         if (strchr(name, '\n'))
5756                 return -EINVAL;
5757
5758         parent = cgroup_kn_lock_live(parent_kn, false);
5759         if (!parent)
5760                 return -ENODEV;
5761
5762         if (!cgroup_check_hierarchy_limits(parent)) {
5763                 ret = -EAGAIN;
5764                 goto out_unlock;
5765         }
5766
5767         cgrp = cgroup_create(parent, name, mode);
5768         if (IS_ERR(cgrp)) {
5769                 ret = PTR_ERR(cgrp);
5770                 goto out_unlock;
5771         }
5772
5773         /*
5774          * This extra ref will be put in cgroup_free_fn() and guarantees
5775          * that @cgrp->kn is always accessible.
5776          */
5777         kernfs_get(cgrp->kn);
5778
5779         ret = cgroup_kn_set_ugid(cgrp->kn);
5780         if (ret)
5781                 goto out_destroy;
5782
5783         ret = css_populate_dir(&cgrp->self);
5784         if (ret)
5785                 goto out_destroy;
5786
5787         ret = cgroup_apply_control_enable(cgrp);
5788         if (ret)
5789                 goto out_destroy;
5790
5791         TRACE_CGROUP_PATH(mkdir, cgrp);
5792
5793         /* let's create and online css's */
5794         kernfs_activate(cgrp->kn);
5795
5796         ret = 0;
5797         goto out_unlock;
5798
5799 out_destroy:
5800         cgroup_destroy_locked(cgrp);
5801 out_unlock:
5802         cgroup_kn_unlock(parent_kn);
5803         return ret;
5804 }
5805
5806 /*
5807  * This is called when the refcnt of a css is confirmed to be killed.
5808  * css_tryget_online() is now guaranteed to fail.  Tell the subsystem to
5809  * initiate destruction and put the css ref from kill_css().
5810  */
5811 static void css_killed_work_fn(struct work_struct *work)
5812 {
5813         struct cgroup_subsys_state *css =
5814                 container_of(work, struct cgroup_subsys_state, destroy_work);
5815
5816         cgroup_lock();
5817
5818         do {
5819                 offline_css(css);
5820                 css_put(css);
5821                 /* @css can't go away while we're holding cgroup_mutex */
5822                 css = css->parent;
5823         } while (css && atomic_dec_and_test(&css->online_cnt));
5824
5825         cgroup_unlock();
5826 }
5827
5828 /* css kill confirmation processing requires process context, bounce */
5829 static void css_killed_ref_fn(struct percpu_ref *ref)
5830 {
5831         struct cgroup_subsys_state *css =
5832                 container_of(ref, struct cgroup_subsys_state, refcnt);
5833
5834         if (atomic_dec_and_test(&css->online_cnt)) {
5835                 INIT_WORK(&css->destroy_work, css_killed_work_fn);
5836                 queue_work(cgroup_destroy_wq, &css->destroy_work);
5837         }
5838 }
5839
5840 /**
5841  * kill_css - destroy a css
5842  * @css: css to destroy
5843  *
5844  * This function initiates destruction of @css by removing cgroup interface
5845  * files and putting its base reference.  ->css_offline() will be invoked
5846  * asynchronously once css_tryget_online() is guaranteed to fail and when
5847  * the reference count reaches zero, @css will be released.
5848  */
5849 static void kill_css(struct cgroup_subsys_state *css)
5850 {
5851         lockdep_assert_held(&cgroup_mutex);
5852
5853         if (css->flags & CSS_DYING)
5854                 return;
5855
5856         css->flags |= CSS_DYING;
5857
5858         /*
5859          * This must happen before css is disassociated with its cgroup.
5860          * See seq_css() for details.
5861          */
5862         css_clear_dir(css);
5863
5864         /*
5865          * Killing would put the base ref, but we need to keep it alive
5866          * until after ->css_offline().
5867          */
5868         css_get(css);
5869
5870         /*
5871          * cgroup core guarantees that, by the time ->css_offline() is
5872          * invoked, no new css reference will be given out via
5873          * css_tryget_online().  We can't simply call percpu_ref_kill() and
5874          * proceed to offlining css's because percpu_ref_kill() doesn't
5875          * guarantee that the ref is seen as killed on all CPUs on return.
5876          *
5877          * Use percpu_ref_kill_and_confirm() to get notifications as each
5878          * css is confirmed to be seen as killed on all CPUs.
5879          */
5880         percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
5881 }
5882
5883 /**
5884  * cgroup_destroy_locked - the first stage of cgroup destruction
5885  * @cgrp: cgroup to be destroyed
5886  *
5887  * css's make use of percpu refcnts whose killing latency shouldn't be
5888  * exposed to userland and are RCU protected.  Also, cgroup core needs to
5889  * guarantee that css_tryget_online() won't succeed by the time
5890  * ->css_offline() is invoked.  To satisfy all the requirements,
5891  * destruction is implemented in the following two steps.
5892  *
5893  * s1. Verify @cgrp can be destroyed and mark it dying.  Remove all
5894  *     userland visible parts and start killing the percpu refcnts of
5895  *     css's.  Set up so that the next stage will be kicked off once all
5896  *     the percpu refcnts are confirmed to be killed.
5897  *
5898  * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
5899  *     rest of destruction.  Once all cgroup references are gone, the
5900  *     cgroup is RCU-freed.
5901  *
5902  * This function implements s1.  After this step, @cgrp is gone as far as
5903  * the userland is concerned and a new cgroup with the same name may be
5904  * created.  As cgroup doesn't care about the names internally, this
5905  * doesn't cause any problem.
5906  */
5907 static int cgroup_destroy_locked(struct cgroup *cgrp)
5908         __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
5909 {
5910         struct cgroup *tcgrp, *parent = cgroup_parent(cgrp);
5911         struct cgroup_subsys_state *css;
5912         struct cgrp_cset_link *link;
5913         int ssid;
5914
5915         lockdep_assert_held(&cgroup_mutex);
5916
5917         /*
5918          * Only migration can raise populated from zero and we're already
5919          * holding cgroup_mutex.
5920          */
5921         if (cgroup_is_populated(cgrp))
5922                 return -EBUSY;
5923
5924         /*
5925          * Make sure there's no live children.  We can't test emptiness of
5926          * ->self.children as dead children linger on it while being
5927          * drained; otherwise, "rmdir parent/child parent" may fail.
5928          */
5929         if (css_has_online_children(&cgrp->self))
5930                 return -EBUSY;
5931
5932         /*
5933          * Mark @cgrp and the associated csets dead.  The former prevents
5934          * further task migration and child creation by disabling
5935          * cgroup_kn_lock_live().  The latter makes the csets ignored by
5936          * the migration path.
5937          */
5938         cgrp->self.flags &= ~CSS_ONLINE;
5939
5940         spin_lock_irq(&css_set_lock);
5941         list_for_each_entry(link, &cgrp->cset_links, cset_link)
5942                 link->cset->dead = true;
5943         spin_unlock_irq(&css_set_lock);
5944
5945         /* initiate massacre of all css's */
5946         for_each_css(css, ssid, cgrp)
5947                 kill_css(css);
5948
5949         /* clear and remove @cgrp dir, @cgrp has an extra ref on its kn */
5950         css_clear_dir(&cgrp->self);
5951         kernfs_remove(cgrp->kn);
5952
5953         if (cgroup_is_threaded(cgrp))
5954                 parent->nr_threaded_children--;
5955
5956         spin_lock_irq(&css_set_lock);
5957         for (tcgrp = parent; tcgrp; tcgrp = cgroup_parent(tcgrp)) {
5958                 tcgrp->nr_descendants--;
5959                 tcgrp->nr_dying_descendants++;
5960                 /*
5961                  * If the dying cgroup is frozen, decrease frozen descendants
5962                  * counters of ancestor cgroups.
5963                  */
5964                 if (test_bit(CGRP_FROZEN, &cgrp->flags))
5965                         tcgrp->freezer.nr_frozen_descendants--;
5966         }
5967         spin_unlock_irq(&css_set_lock);
5968
5969         cgroup1_check_for_release(parent);
5970
5971         cgroup_bpf_offline(cgrp);
5972
5973         /* put the base reference */
5974         percpu_ref_kill(&cgrp->self.refcnt);
5975
5976         return 0;
5977 };
5978
5979 int cgroup_rmdir(struct kernfs_node *kn)
5980 {
5981         struct cgroup *cgrp;
5982         int ret = 0;
5983
5984         cgrp = cgroup_kn_lock_live(kn, false);
5985         if (!cgrp)
5986                 return 0;
5987
5988         ret = cgroup_destroy_locked(cgrp);
5989         if (!ret)
5990                 TRACE_CGROUP_PATH(rmdir, cgrp);
5991
5992         cgroup_kn_unlock(kn);
5993         return ret;
5994 }
5995
5996 static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
5997         .show_options           = cgroup_show_options,
5998         .mkdir                  = cgroup_mkdir,
5999         .rmdir                  = cgroup_rmdir,
6000         .show_path              = cgroup_show_path,
6001 };
6002
6003 static void __init cgroup_init_subsys(struct cgroup_subsys *ss, bool early)
6004 {
6005         struct cgroup_subsys_state *css;
6006
6007         pr_debug("Initializing cgroup subsys %s\n", ss->name);
6008
6009         cgroup_lock();
6010
6011         idr_init(&ss->css_idr);
6012         INIT_LIST_HEAD(&ss->cfts);
6013
6014         /* Create the root cgroup state for this subsystem */
6015         ss->root = &cgrp_dfl_root;
6016         css = ss->css_alloc(NULL);
6017         /* We don't handle early failures gracefully */
6018         BUG_ON(IS_ERR(css));
6019         init_and_link_css(css, ss, &cgrp_dfl_root.cgrp);
6020
6021         /*
6022          * Root csses are never destroyed and we can't initialize
6023          * percpu_ref during early init.  Disable refcnting.
6024          */
6025         css->flags |= CSS_NO_REF;
6026
6027         if (early) {
6028                 /* allocation can't be done safely during early init */
6029                 css->id = 1;
6030         } else {
6031                 css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2, GFP_KERNEL);
6032                 BUG_ON(css->id < 0);
6033         }
6034
6035         /* Update the init_css_set to contain a subsys
6036          * pointer to this state - since the subsystem is
6037          * newly registered, all tasks and hence the
6038          * init_css_set is in the subsystem's root cgroup. */
6039         init_css_set.subsys[ss->id] = css;
6040
6041         have_fork_callback |= (bool)ss->fork << ss->id;
6042         have_exit_callback |= (bool)ss->exit << ss->id;
6043         have_release_callback |= (bool)ss->release << ss->id;
6044         have_canfork_callback |= (bool)ss->can_fork << ss->id;
6045
6046         /* At system boot, before all subsystems have been
6047          * registered, no tasks have been forked, so we don't
6048          * need to invoke fork callbacks here. */
6049         BUG_ON(!list_empty(&init_task.tasks));
6050
6051         BUG_ON(online_css(css));
6052
6053         cgroup_unlock();
6054 }
6055
6056 /**
6057  * cgroup_init_early - cgroup initialization at system boot
6058  *
6059  * Initialize cgroups at system boot, and initialize any
6060  * subsystems that request early init.
6061  */
6062 int __init cgroup_init_early(void)
6063 {
6064         static struct cgroup_fs_context __initdata ctx;
6065         struct cgroup_subsys *ss;
6066         int i;
6067
6068         ctx.root = &cgrp_dfl_root;
6069         init_cgroup_root(&ctx);
6070         cgrp_dfl_root.cgrp.self.flags |= CSS_NO_REF;
6071
6072         RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
6073
6074         for_each_subsys(ss, i) {
6075                 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
6076                      "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p id:name=%d:%s\n",
6077                      i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
6078                      ss->id, ss->name);
6079                 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
6080                      "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
6081
6082                 ss->id = i;
6083                 ss->name = cgroup_subsys_name[i];
6084                 if (!ss->legacy_name)
6085                         ss->legacy_name = cgroup_subsys_name[i];
6086
6087                 if (ss->early_init)
6088                         cgroup_init_subsys(ss, true);
6089         }
6090         return 0;
6091 }
6092
6093 static u16 cgroup_enable_mask __initdata;
6094 static int __init cgroup_disable(char *str);
6095
6096 /**
6097  * cgroup_init - cgroup initialization
6098  *
6099  * Register cgroup filesystem and /proc file, and initialize
6100  * any subsystems that didn't request early init.
6101  */
6102 int __init cgroup_init(void)
6103 {
6104         struct cgroup_subsys *ss;
6105         int ssid;
6106
6107         BUILD_BUG_ON(CGROUP_SUBSYS_COUNT > 16);
6108         BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
6109         BUG_ON(cgroup_init_cftypes(NULL, cgroup_psi_files));
6110         BUG_ON(cgroup_init_cftypes(NULL, cgroup1_base_files));
6111
6112         cgroup_rstat_boot();
6113
6114         get_user_ns(init_cgroup_ns.user_ns);
6115
6116         cgroup_lock();
6117
6118         /*
6119          * Add init_css_set to the hash table so that dfl_root can link to
6120          * it during init.
6121          */
6122         hash_add(css_set_table, &init_css_set.hlist,
6123                  css_set_hash(init_css_set.subsys));
6124
6125         BUG_ON(cgroup_setup_root(&cgrp_dfl_root, 0));
6126
6127         cgroup_unlock();
6128
6129         /*
6130          * Apply an implicit disable, knowing that an explicit enable will
6131          * prevent if from doing anything.
6132          */
6133         cgroup_disable("memory");
6134
6135         for_each_subsys(ss, ssid) {
6136                 if (ss->early_init) {
6137                         struct cgroup_subsys_state *css =
6138                                 init_css_set.subsys[ss->id];
6139
6140                         css->id = cgroup_idr_alloc(&ss->css_idr, css, 1, 2,
6141                                                    GFP_KERNEL);
6142                         BUG_ON(css->id < 0);
6143                 } else {
6144                         cgroup_init_subsys(ss, false);
6145                 }
6146
6147                 list_add_tail(&init_css_set.e_cset_node[ssid],
6148                               &cgrp_dfl_root.cgrp.e_csets[ssid]);
6149
6150                 /*
6151                  * Setting dfl_root subsys_mask needs to consider the
6152                  * disabled flag and cftype registration needs kmalloc,
6153                  * both of which aren't available during early_init.
6154                  */
6155                 if (!cgroup_ssid_enabled(ssid))
6156                         continue;
6157
6158                 if (cgroup1_ssid_disabled(ssid))
6159                         pr_info("Disabling %s control group subsystem in v1 mounts\n",
6160                                 ss->name);
6161
6162                 cgrp_dfl_root.subsys_mask |= 1 << ss->id;
6163
6164                 /* implicit controllers must be threaded too */
6165                 WARN_ON(ss->implicit_on_dfl && !ss->threaded);
6166
6167                 if (ss->implicit_on_dfl)
6168                         cgrp_dfl_implicit_ss_mask |= 1 << ss->id;
6169                 else if (!ss->dfl_cftypes)
6170                         cgrp_dfl_inhibit_ss_mask |= 1 << ss->id;
6171
6172                 if (ss->threaded)
6173                         cgrp_dfl_threaded_ss_mask |= 1 << ss->id;
6174
6175                 if (ss->dfl_cftypes == ss->legacy_cftypes) {
6176                         WARN_ON(cgroup_add_cftypes(ss, ss->dfl_cftypes));
6177                 } else {
6178                         WARN_ON(cgroup_add_dfl_cftypes(ss, ss->dfl_cftypes));
6179                         WARN_ON(cgroup_add_legacy_cftypes(ss, ss->legacy_cftypes));
6180                 }
6181
6182                 if (ss->bind)
6183                         ss->bind(init_css_set.subsys[ssid]);
6184
6185                 cgroup_lock();
6186                 css_populate_dir(init_css_set.subsys[ssid]);
6187                 cgroup_unlock();
6188         }
6189
6190         /* init_css_set.subsys[] has been updated, re-hash */
6191         hash_del(&init_css_set.hlist);
6192         hash_add(css_set_table, &init_css_set.hlist,
6193                  css_set_hash(init_css_set.subsys));
6194
6195         WARN_ON(sysfs_create_mount_point(fs_kobj, "cgroup"));
6196         WARN_ON(register_filesystem(&cgroup_fs_type));
6197         WARN_ON(register_filesystem(&cgroup2_fs_type));
6198         WARN_ON(!proc_create_single("cgroups", 0, NULL, proc_cgroupstats_show));
6199 #ifdef CONFIG_CPUSETS
6200         WARN_ON(register_filesystem(&cpuset_fs_type));
6201 #endif
6202
6203         return 0;
6204 }
6205
6206 static int __init cgroup_wq_init(void)
6207 {
6208         /*
6209          * There isn't much point in executing destruction path in
6210          * parallel.  Good chunk is serialized with cgroup_mutex anyway.
6211          * Use 1 for @max_active.
6212          *
6213          * We would prefer to do this in cgroup_init() above, but that
6214          * is called before init_workqueues(): so leave this until after.
6215          */
6216         cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
6217         BUG_ON(!cgroup_destroy_wq);
6218         return 0;
6219 }
6220 core_initcall(cgroup_wq_init);
6221
6222 void cgroup_path_from_kernfs_id(u64 id, char *buf, size_t buflen)
6223 {
6224         struct kernfs_node *kn;
6225
6226         kn = kernfs_find_and_get_node_by_id(cgrp_dfl_root.kf_root, id);
6227         if (!kn)
6228                 return;
6229         kernfs_path(kn, buf, buflen);
6230         kernfs_put(kn);
6231 }
6232
6233 /*
6234  * cgroup_get_from_id : get the cgroup associated with cgroup id
6235  * @id: cgroup id
6236  * On success return the cgrp or ERR_PTR on failure
6237  * Only cgroups within current task's cgroup NS are valid.
6238  */
6239 struct cgroup *cgroup_get_from_id(u64 id)
6240 {
6241         struct kernfs_node *kn;
6242         struct cgroup *cgrp, *root_cgrp;
6243
6244         kn = kernfs_find_and_get_node_by_id(cgrp_dfl_root.kf_root, id);
6245         if (!kn)
6246                 return ERR_PTR(-ENOENT);
6247
6248         if (kernfs_type(kn) != KERNFS_DIR) {
6249                 kernfs_put(kn);
6250                 return ERR_PTR(-ENOENT);
6251         }
6252
6253         rcu_read_lock();
6254
6255         cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
6256         if (cgrp && !cgroup_tryget(cgrp))
6257                 cgrp = NULL;
6258
6259         rcu_read_unlock();
6260         kernfs_put(kn);
6261
6262         if (!cgrp)
6263                 return ERR_PTR(-ENOENT);
6264
6265         root_cgrp = current_cgns_cgroup_dfl();
6266         if (!cgroup_is_descendant(cgrp, root_cgrp)) {
6267                 cgroup_put(cgrp);
6268                 return ERR_PTR(-ENOENT);
6269         }
6270
6271         return cgrp;
6272 }
6273 EXPORT_SYMBOL_GPL(cgroup_get_from_id);
6274
6275 /*
6276  * proc_cgroup_show()
6277  *  - Print task's cgroup paths into seq_file, one line for each hierarchy
6278  *  - Used for /proc/<pid>/cgroup.
6279  */
6280 int proc_cgroup_show(struct seq_file *m, struct pid_namespace *ns,
6281                      struct pid *pid, struct task_struct *tsk)
6282 {
6283         char *buf;
6284         int retval;
6285         struct cgroup_root *root;
6286
6287         retval = -ENOMEM;
6288         buf = kmalloc(PATH_MAX, GFP_KERNEL);
6289         if (!buf)
6290                 goto out;
6291
6292         cgroup_lock();
6293         spin_lock_irq(&css_set_lock);
6294
6295         for_each_root(root) {
6296                 struct cgroup_subsys *ss;
6297                 struct cgroup *cgrp;
6298                 int ssid, count = 0;
6299
6300                 if (root == &cgrp_dfl_root && !READ_ONCE(cgrp_dfl_visible))
6301                         continue;
6302
6303                 seq_printf(m, "%d:", root->hierarchy_id);
6304                 if (root != &cgrp_dfl_root)
6305                         for_each_subsys(ss, ssid)
6306                                 if (root->subsys_mask & (1 << ssid))
6307                                         seq_printf(m, "%s%s", count++ ? "," : "",
6308                                                    ss->legacy_name);
6309                 if (strlen(root->name))
6310                         seq_printf(m, "%sname=%s", count ? "," : "",
6311                                    root->name);
6312                 seq_putc(m, ':');
6313
6314                 cgrp = task_cgroup_from_root(tsk, root);
6315
6316                 /*
6317                  * On traditional hierarchies, all zombie tasks show up as
6318                  * belonging to the root cgroup.  On the default hierarchy,
6319                  * while a zombie doesn't show up in "cgroup.procs" and
6320                  * thus can't be migrated, its /proc/PID/cgroup keeps
6321                  * reporting the cgroup it belonged to before exiting.  If
6322                  * the cgroup is removed before the zombie is reaped,
6323                  * " (deleted)" is appended to the cgroup path.
6324                  */
6325                 if (cgroup_on_dfl(cgrp) || !(tsk->flags & PF_EXITING)) {
6326                         retval = cgroup_path_ns_locked(cgrp, buf, PATH_MAX,
6327                                                 current->nsproxy->cgroup_ns);
6328                         if (retval >= PATH_MAX)
6329                                 retval = -ENAMETOOLONG;
6330                         if (retval < 0)
6331                                 goto out_unlock;
6332
6333                         seq_puts(m, buf);
6334                 } else {
6335                         seq_puts(m, "/");
6336                 }
6337
6338                 if (cgroup_on_dfl(cgrp) && cgroup_is_dead(cgrp))
6339                         seq_puts(m, " (deleted)\n");
6340                 else
6341                         seq_putc(m, '\n');
6342         }
6343
6344         retval = 0;
6345 out_unlock:
6346         spin_unlock_irq(&css_set_lock);
6347         cgroup_unlock();
6348         kfree(buf);
6349 out:
6350         return retval;
6351 }
6352
6353 /**
6354  * cgroup_fork - initialize cgroup related fields during copy_process()
6355  * @child: pointer to task_struct of forking parent process.
6356  *
6357  * A task is associated with the init_css_set until cgroup_post_fork()
6358  * attaches it to the target css_set.
6359  */
6360 void cgroup_fork(struct task_struct *child)
6361 {
6362         RCU_INIT_POINTER(child->cgroups, &init_css_set);
6363         INIT_LIST_HEAD(&child->cg_list);
6364 }
6365
6366 /**
6367  * cgroup_v1v2_get_from_file - get a cgroup pointer from a file pointer
6368  * @f: file corresponding to cgroup_dir
6369  *
6370  * Find the cgroup from a file pointer associated with a cgroup directory.
6371  * Returns a pointer to the cgroup on success. ERR_PTR is returned if the
6372  * cgroup cannot be found.
6373  */
6374 static struct cgroup *cgroup_v1v2_get_from_file(struct file *f)
6375 {
6376         struct cgroup_subsys_state *css;
6377
6378         css = css_tryget_online_from_dir(f->f_path.dentry, NULL);
6379         if (IS_ERR(css))
6380                 return ERR_CAST(css);
6381
6382         return css->cgroup;
6383 }
6384
6385 /**
6386  * cgroup_get_from_file - same as cgroup_v1v2_get_from_file, but only supports
6387  * cgroup2.
6388  * @f: file corresponding to cgroup2_dir
6389  */
6390 static struct cgroup *cgroup_get_from_file(struct file *f)
6391 {
6392         struct cgroup *cgrp = cgroup_v1v2_get_from_file(f);
6393
6394         if (IS_ERR(cgrp))
6395                 return ERR_CAST(cgrp);
6396
6397         if (!cgroup_on_dfl(cgrp)) {
6398                 cgroup_put(cgrp);
6399                 return ERR_PTR(-EBADF);
6400         }
6401
6402         return cgrp;
6403 }
6404
6405 /**
6406  * cgroup_css_set_fork - find or create a css_set for a child process
6407  * @kargs: the arguments passed to create the child process
6408  *
6409  * This functions finds or creates a new css_set which the child
6410  * process will be attached to in cgroup_post_fork(). By default,
6411  * the child process will be given the same css_set as its parent.
6412  *
6413  * If CLONE_INTO_CGROUP is specified this function will try to find an
6414  * existing css_set which includes the requested cgroup and if not create
6415  * a new css_set that the child will be attached to later. If this function
6416  * succeeds it will hold cgroup_threadgroup_rwsem on return. If
6417  * CLONE_INTO_CGROUP is requested this function will grab cgroup mutex
6418  * before grabbing cgroup_threadgroup_rwsem and will hold a reference
6419  * to the target cgroup.
6420  */
6421 static int cgroup_css_set_fork(struct kernel_clone_args *kargs)
6422         __acquires(&cgroup_mutex) __acquires(&cgroup_threadgroup_rwsem)
6423 {
6424         int ret;
6425         struct cgroup *dst_cgrp = NULL;
6426         struct css_set *cset;
6427         struct super_block *sb;
6428         struct file *f;
6429
6430         if (kargs->flags & CLONE_INTO_CGROUP)
6431                 cgroup_lock();
6432
6433         cgroup_threadgroup_change_begin(current);
6434
6435         spin_lock_irq(&css_set_lock);
6436         cset = task_css_set(current);
6437         get_css_set(cset);
6438         spin_unlock_irq(&css_set_lock);
6439
6440         if (!(kargs->flags & CLONE_INTO_CGROUP)) {
6441                 kargs->cset = cset;
6442                 return 0;
6443         }
6444
6445         f = fget_raw(kargs->cgroup);
6446         if (!f) {
6447                 ret = -EBADF;
6448                 goto err;
6449         }
6450         sb = f->f_path.dentry->d_sb;
6451
6452         dst_cgrp = cgroup_get_from_file(f);
6453         if (IS_ERR(dst_cgrp)) {
6454                 ret = PTR_ERR(dst_cgrp);
6455                 dst_cgrp = NULL;
6456                 goto err;
6457         }
6458
6459         if (cgroup_is_dead(dst_cgrp)) {
6460                 ret = -ENODEV;
6461                 goto err;
6462         }
6463
6464         /*
6465          * Verify that we the target cgroup is writable for us. This is
6466          * usually done by the vfs layer but since we're not going through
6467          * the vfs layer here we need to do it "manually".
6468          */
6469         ret = cgroup_may_write(dst_cgrp, sb);
6470         if (ret)
6471                 goto err;
6472
6473         /*
6474          * Spawning a task directly into a cgroup works by passing a file
6475          * descriptor to the target cgroup directory. This can even be an O_PATH
6476          * file descriptor. But it can never be a cgroup.procs file descriptor.
6477          * This was done on purpose so spawning into a cgroup could be
6478          * conceptualized as an atomic
6479          *
6480          *   fd = openat(dfd_cgroup, "cgroup.procs", ...);
6481          *   write(fd, <child-pid>, ...);
6482          *
6483          * sequence, i.e. it's a shorthand for the caller opening and writing
6484          * cgroup.procs of the cgroup indicated by @dfd_cgroup. This allows us
6485          * to always use the caller's credentials.
6486          */
6487         ret = cgroup_attach_permissions(cset->dfl_cgrp, dst_cgrp, sb,
6488                                         !(kargs->flags & CLONE_THREAD),
6489                                         current->nsproxy->cgroup_ns);
6490         if (ret)
6491                 goto err;
6492
6493         kargs->cset = find_css_set(cset, dst_cgrp);
6494         if (!kargs->cset) {
6495                 ret = -ENOMEM;
6496                 goto err;
6497         }
6498
6499         put_css_set(cset);
6500         fput(f);
6501         kargs->cgrp = dst_cgrp;
6502         return ret;
6503
6504 err:
6505         cgroup_threadgroup_change_end(current);
6506         cgroup_unlock();
6507         if (f)
6508                 fput(f);
6509         if (dst_cgrp)
6510                 cgroup_put(dst_cgrp);
6511         put_css_set(cset);
6512         if (kargs->cset)
6513                 put_css_set(kargs->cset);
6514         return ret;
6515 }
6516
6517 /**
6518  * cgroup_css_set_put_fork - drop references we took during fork
6519  * @kargs: the arguments passed to create the child process
6520  *
6521  * Drop references to the prepared css_set and target cgroup if
6522  * CLONE_INTO_CGROUP was requested.
6523  */
6524 static void cgroup_css_set_put_fork(struct kernel_clone_args *kargs)
6525         __releases(&cgroup_threadgroup_rwsem) __releases(&cgroup_mutex)
6526 {
6527         struct cgroup *cgrp = kargs->cgrp;
6528         struct css_set *cset = kargs->cset;
6529
6530         cgroup_threadgroup_change_end(current);
6531
6532         if (cset) {
6533                 put_css_set(cset);
6534                 kargs->cset = NULL;
6535         }
6536
6537         if (kargs->flags & CLONE_INTO_CGROUP) {
6538                 cgroup_unlock();
6539                 if (cgrp) {
6540                         cgroup_put(cgrp);
6541                         kargs->cgrp = NULL;
6542                 }
6543         }
6544 }
6545
6546 /**
6547  * cgroup_can_fork - called on a new task before the process is exposed
6548  * @child: the child process
6549  * @kargs: the arguments passed to create the child process
6550  *
6551  * This prepares a new css_set for the child process which the child will
6552  * be attached to in cgroup_post_fork().
6553  * This calls the subsystem can_fork() callbacks. If the cgroup_can_fork()
6554  * callback returns an error, the fork aborts with that error code. This
6555  * allows for a cgroup subsystem to conditionally allow or deny new forks.
6556  */
6557 int cgroup_can_fork(struct task_struct *child, struct kernel_clone_args *kargs)
6558 {
6559         struct cgroup_subsys *ss;
6560         int i, j, ret;
6561
6562         ret = cgroup_css_set_fork(kargs);
6563         if (ret)
6564                 return ret;
6565
6566         do_each_subsys_mask(ss, i, have_canfork_callback) {
6567                 ret = ss->can_fork(child, kargs->cset);
6568                 if (ret)
6569                         goto out_revert;
6570         } while_each_subsys_mask();
6571
6572         return 0;
6573
6574 out_revert:
6575         for_each_subsys(ss, j) {
6576                 if (j >= i)
6577                         break;
6578                 if (ss->cancel_fork)
6579                         ss->cancel_fork(child, kargs->cset);
6580         }
6581
6582         cgroup_css_set_put_fork(kargs);
6583
6584         return ret;
6585 }
6586
6587 /**
6588  * cgroup_cancel_fork - called if a fork failed after cgroup_can_fork()
6589  * @child: the child process
6590  * @kargs: the arguments passed to create the child process
6591  *
6592  * This calls the cancel_fork() callbacks if a fork failed *after*
6593  * cgroup_can_fork() succeeded and cleans up references we took to
6594  * prepare a new css_set for the child process in cgroup_can_fork().
6595  */
6596 void cgroup_cancel_fork(struct task_struct *child,
6597                         struct kernel_clone_args *kargs)
6598 {
6599         struct cgroup_subsys *ss;
6600         int i;
6601
6602         for_each_subsys(ss, i)
6603                 if (ss->cancel_fork)
6604                         ss->cancel_fork(child, kargs->cset);
6605
6606         cgroup_css_set_put_fork(kargs);
6607 }
6608
6609 /**
6610  * cgroup_post_fork - finalize cgroup setup for the child process
6611  * @child: the child process
6612  * @kargs: the arguments passed to create the child process
6613  *
6614  * Attach the child process to its css_set calling the subsystem fork()
6615  * callbacks.
6616  */
6617 void cgroup_post_fork(struct task_struct *child,
6618                       struct kernel_clone_args *kargs)
6619         __releases(&cgroup_threadgroup_rwsem) __releases(&cgroup_mutex)
6620 {
6621         unsigned long cgrp_flags = 0;
6622         bool kill = false;
6623         struct cgroup_subsys *ss;
6624         struct css_set *cset;
6625         int i;
6626
6627         cset = kargs->cset;
6628         kargs->cset = NULL;
6629
6630         spin_lock_irq(&css_set_lock);
6631
6632         /* init tasks are special, only link regular threads */
6633         if (likely(child->pid)) {
6634                 if (kargs->cgrp)
6635                         cgrp_flags = kargs->cgrp->flags;
6636                 else
6637                         cgrp_flags = cset->dfl_cgrp->flags;
6638
6639                 WARN_ON_ONCE(!list_empty(&child->cg_list));
6640                 cset->nr_tasks++;
6641                 css_set_move_task(child, NULL, cset, false);
6642         } else {
6643                 put_css_set(cset);
6644                 cset = NULL;
6645         }
6646
6647         if (!(child->flags & PF_KTHREAD)) {
6648                 if (unlikely(test_bit(CGRP_FREEZE, &cgrp_flags))) {
6649                         /*
6650                          * If the cgroup has to be frozen, the new task has
6651                          * too. Let's set the JOBCTL_TRAP_FREEZE jobctl bit to
6652                          * get the task into the frozen state.
6653                          */
6654                         spin_lock(&child->sighand->siglock);
6655                         WARN_ON_ONCE(child->frozen);
6656                         child->jobctl |= JOBCTL_TRAP_FREEZE;
6657                         spin_unlock(&child->sighand->siglock);
6658
6659                         /*
6660                          * Calling cgroup_update_frozen() isn't required here,
6661                          * because it will be called anyway a bit later from
6662                          * do_freezer_trap(). So we avoid cgroup's transient
6663                          * switch from the frozen state and back.
6664                          */
6665                 }
6666
6667                 /*
6668                  * If the cgroup is to be killed notice it now and take the
6669                  * child down right after we finished preparing it for
6670                  * userspace.
6671                  */
6672                 kill = test_bit(CGRP_KILL, &cgrp_flags);
6673         }
6674
6675         spin_unlock_irq(&css_set_lock);
6676
6677         /*
6678          * Call ss->fork().  This must happen after @child is linked on
6679          * css_set; otherwise, @child might change state between ->fork()
6680          * and addition to css_set.
6681          */
6682         do_each_subsys_mask(ss, i, have_fork_callback) {
6683                 ss->fork(child);
6684         } while_each_subsys_mask();
6685
6686         /* Make the new cset the root_cset of the new cgroup namespace. */
6687         if (kargs->flags & CLONE_NEWCGROUP) {
6688                 struct css_set *rcset = child->nsproxy->cgroup_ns->root_cset;
6689
6690                 get_css_set(cset);
6691                 child->nsproxy->cgroup_ns->root_cset = cset;
6692                 put_css_set(rcset);
6693         }
6694
6695         /* Cgroup has to be killed so take down child immediately. */
6696         if (unlikely(kill))
6697                 do_send_sig_info(SIGKILL, SEND_SIG_NOINFO, child, PIDTYPE_TGID);
6698
6699         cgroup_css_set_put_fork(kargs);
6700 }
6701
6702 /**
6703  * cgroup_exit - detach cgroup from exiting task
6704  * @tsk: pointer to task_struct of exiting process
6705  *
6706  * Description: Detach cgroup from @tsk.
6707  *
6708  */
6709 void cgroup_exit(struct task_struct *tsk)
6710 {
6711         struct cgroup_subsys *ss;
6712         struct css_set *cset;
6713         int i;
6714
6715         spin_lock_irq(&css_set_lock);
6716
6717         WARN_ON_ONCE(list_empty(&tsk->cg_list));
6718         cset = task_css_set(tsk);
6719         css_set_move_task(tsk, cset, NULL, false);
6720         list_add_tail(&tsk->cg_list, &cset->dying_tasks);
6721         cset->nr_tasks--;
6722
6723         if (dl_task(tsk))
6724                 dec_dl_tasks_cs(tsk);
6725
6726         WARN_ON_ONCE(cgroup_task_frozen(tsk));
6727         if (unlikely(!(tsk->flags & PF_KTHREAD) &&
6728                      test_bit(CGRP_FREEZE, &task_dfl_cgroup(tsk)->flags)))
6729                 cgroup_update_frozen(task_dfl_cgroup(tsk));
6730
6731         spin_unlock_irq(&css_set_lock);
6732
6733         /* see cgroup_post_fork() for details */
6734         do_each_subsys_mask(ss, i, have_exit_callback) {
6735                 ss->exit(tsk);
6736         } while_each_subsys_mask();
6737 }
6738
6739 void cgroup_release(struct task_struct *task)
6740 {
6741         struct cgroup_subsys *ss;
6742         int ssid;
6743
6744         do_each_subsys_mask(ss, ssid, have_release_callback) {
6745                 ss->release(task);
6746         } while_each_subsys_mask();
6747
6748         spin_lock_irq(&css_set_lock);
6749         css_set_skip_task_iters(task_css_set(task), task);
6750         list_del_init(&task->cg_list);
6751         spin_unlock_irq(&css_set_lock);
6752 }
6753
6754 void cgroup_free(struct task_struct *task)
6755 {
6756         struct css_set *cset = task_css_set(task);
6757         put_css_set(cset);
6758 }
6759
6760 static int __init cgroup_disable(char *str)
6761 {
6762         struct cgroup_subsys *ss;
6763         char *token;
6764         int i;
6765
6766         while ((token = strsep(&str, ",")) != NULL) {
6767                 if (!*token)
6768                         continue;
6769
6770                 for_each_subsys(ss, i) {
6771                         if (strcmp(token, ss->name) &&
6772                             strcmp(token, ss->legacy_name))
6773                                 continue;
6774
6775                         /* An explicit cgroup_enable overrides a disable */
6776                         if (cgroup_enable_mask & (1 << i))
6777                                 continue;
6778
6779                         static_branch_disable(cgroup_subsys_enabled_key[i]);
6780                         pr_info("Disabling %s control group subsystem\n",
6781                                 ss->name);
6782                 }
6783
6784                 for (i = 0; i < OPT_FEATURE_COUNT; i++) {
6785                         if (strcmp(token, cgroup_opt_feature_names[i]))
6786                                 continue;
6787                         cgroup_feature_disable_mask |= 1 << i;
6788                         pr_info("Disabling %s control group feature\n",
6789                                 cgroup_opt_feature_names[i]);
6790                         break;
6791                 }
6792         }
6793         return 1;
6794 }
6795 __setup("cgroup_disable=", cgroup_disable);
6796
6797 static int __init cgroup_enable(char *str)
6798 {
6799         struct cgroup_subsys *ss;
6800         char *token;
6801         int i;
6802
6803         while ((token = strsep(&str, ",")) != NULL) {
6804                 if (!*token)
6805                         continue;
6806
6807                 for_each_subsys(ss, i) {
6808                         if (strcmp(token, ss->name) &&
6809                             strcmp(token, ss->legacy_name))
6810                                 continue;
6811
6812                         cgroup_enable_mask |= 1 << i;
6813                         static_branch_enable(cgroup_subsys_enabled_key[i]);
6814                         pr_info("Enabling %s control group subsystem\n",
6815                                 ss->name);
6816                 }
6817         }
6818         return 1;
6819 }
6820 __setup("cgroup_enable=", cgroup_enable);
6821
6822 void __init __weak enable_debug_cgroup(void) { }
6823
6824 static int __init enable_cgroup_debug(char *str)
6825 {
6826         cgroup_debug = true;
6827         enable_debug_cgroup();
6828         return 1;
6829 }
6830 __setup("cgroup_debug", enable_cgroup_debug);
6831
6832 /**
6833  * css_tryget_online_from_dir - get corresponding css from a cgroup dentry
6834  * @dentry: directory dentry of interest
6835  * @ss: subsystem of interest
6836  *
6837  * If @dentry is a directory for a cgroup which has @ss enabled on it, try
6838  * to get the corresponding css and return it.  If such css doesn't exist
6839  * or can't be pinned, an ERR_PTR value is returned.
6840  */
6841 struct cgroup_subsys_state *css_tryget_online_from_dir(struct dentry *dentry,
6842                                                        struct cgroup_subsys *ss)
6843 {
6844         struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
6845         struct file_system_type *s_type = dentry->d_sb->s_type;
6846         struct cgroup_subsys_state *css = NULL;
6847         struct cgroup *cgrp;
6848
6849         /* is @dentry a cgroup dir? */
6850         if ((s_type != &cgroup_fs_type && s_type != &cgroup2_fs_type) ||
6851             !kn || kernfs_type(kn) != KERNFS_DIR)
6852                 return ERR_PTR(-EBADF);
6853
6854         rcu_read_lock();
6855
6856         /*
6857          * This path doesn't originate from kernfs and @kn could already
6858          * have been or be removed at any point.  @kn->priv is RCU
6859          * protected for this access.  See css_release_work_fn() for details.
6860          */
6861         cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
6862         if (cgrp)
6863                 css = cgroup_css(cgrp, ss);
6864
6865         if (!css || !css_tryget_online(css))
6866                 css = ERR_PTR(-ENOENT);
6867
6868         rcu_read_unlock();
6869         return css;
6870 }
6871
6872 /**
6873  * css_from_id - lookup css by id
6874  * @id: the cgroup id
6875  * @ss: cgroup subsys to be looked into
6876  *
6877  * Returns the css if there's valid one with @id, otherwise returns NULL.
6878  * Should be called under rcu_read_lock().
6879  */
6880 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
6881 {
6882         WARN_ON_ONCE(!rcu_read_lock_held());
6883         return idr_find(&ss->css_idr, id);
6884 }
6885
6886 /**
6887  * cgroup_get_from_path - lookup and get a cgroup from its default hierarchy path
6888  * @path: path on the default hierarchy
6889  *
6890  * Find the cgroup at @path on the default hierarchy, increment its
6891  * reference count and return it.  Returns pointer to the found cgroup on
6892  * success, ERR_PTR(-ENOENT) if @path doesn't exist or if the cgroup has already
6893  * been released and ERR_PTR(-ENOTDIR) if @path points to a non-directory.
6894  */
6895 struct cgroup *cgroup_get_from_path(const char *path)
6896 {
6897         struct kernfs_node *kn;
6898         struct cgroup *cgrp = ERR_PTR(-ENOENT);
6899         struct cgroup *root_cgrp;
6900
6901         root_cgrp = current_cgns_cgroup_dfl();
6902         kn = kernfs_walk_and_get(root_cgrp->kn, path);
6903         if (!kn)
6904                 goto out;
6905
6906         if (kernfs_type(kn) != KERNFS_DIR) {
6907                 cgrp = ERR_PTR(-ENOTDIR);
6908                 goto out_kernfs;
6909         }
6910
6911         rcu_read_lock();
6912
6913         cgrp = rcu_dereference(*(void __rcu __force **)&kn->priv);
6914         if (!cgrp || !cgroup_tryget(cgrp))
6915                 cgrp = ERR_PTR(-ENOENT);
6916
6917         rcu_read_unlock();
6918
6919 out_kernfs:
6920         kernfs_put(kn);
6921 out:
6922         return cgrp;
6923 }
6924 EXPORT_SYMBOL_GPL(cgroup_get_from_path);
6925
6926 /**
6927  * cgroup_v1v2_get_from_fd - get a cgroup pointer from a fd
6928  * @fd: fd obtained by open(cgroup_dir)
6929  *
6930  * Find the cgroup from a fd which should be obtained
6931  * by opening a cgroup directory.  Returns a pointer to the
6932  * cgroup on success. ERR_PTR is returned if the cgroup
6933  * cannot be found.
6934  */
6935 struct cgroup *cgroup_v1v2_get_from_fd(int fd)
6936 {
6937         struct cgroup *cgrp;
6938         struct fd f = fdget_raw(fd);
6939         if (!f.file)
6940                 return ERR_PTR(-EBADF);
6941
6942         cgrp = cgroup_v1v2_get_from_file(f.file);
6943         fdput(f);
6944         return cgrp;
6945 }
6946
6947 /**
6948  * cgroup_get_from_fd - same as cgroup_v1v2_get_from_fd, but only supports
6949  * cgroup2.
6950  * @fd: fd obtained by open(cgroup2_dir)
6951  */
6952 struct cgroup *cgroup_get_from_fd(int fd)
6953 {
6954         struct cgroup *cgrp = cgroup_v1v2_get_from_fd(fd);
6955
6956         if (IS_ERR(cgrp))
6957                 return ERR_CAST(cgrp);
6958
6959         if (!cgroup_on_dfl(cgrp)) {
6960                 cgroup_put(cgrp);
6961                 return ERR_PTR(-EBADF);
6962         }
6963         return cgrp;
6964 }
6965 EXPORT_SYMBOL_GPL(cgroup_get_from_fd);
6966
6967 static u64 power_of_ten(int power)
6968 {
6969         u64 v = 1;
6970         while (power--)
6971                 v *= 10;
6972         return v;
6973 }
6974
6975 /**
6976  * cgroup_parse_float - parse a floating number
6977  * @input: input string
6978  * @dec_shift: number of decimal digits to shift
6979  * @v: output
6980  *
6981  * Parse a decimal floating point number in @input and store the result in
6982  * @v with decimal point right shifted @dec_shift times.  For example, if
6983  * @input is "12.3456" and @dec_shift is 3, *@v will be set to 12345.
6984  * Returns 0 on success, -errno otherwise.
6985  *
6986  * There's nothing cgroup specific about this function except that it's
6987  * currently the only user.
6988  */
6989 int cgroup_parse_float(const char *input, unsigned dec_shift, s64 *v)
6990 {
6991         s64 whole, frac = 0;
6992         int fstart = 0, fend = 0, flen;
6993
6994         if (!sscanf(input, "%lld.%n%lld%n", &whole, &fstart, &frac, &fend))
6995                 return -EINVAL;
6996         if (frac < 0)
6997                 return -EINVAL;
6998
6999         flen = fend > fstart ? fend - fstart : 0;
7000         if (flen < dec_shift)
7001                 frac *= power_of_ten(dec_shift - flen);
7002         else
7003                 frac = DIV_ROUND_CLOSEST_ULL(frac, power_of_ten(flen - dec_shift));
7004
7005         *v = whole * power_of_ten(dec_shift) + frac;
7006         return 0;
7007 }
7008
7009 /*
7010  * sock->sk_cgrp_data handling.  For more info, see sock_cgroup_data
7011  * definition in cgroup-defs.h.
7012  */
7013 #ifdef CONFIG_SOCK_CGROUP_DATA
7014
7015 void cgroup_sk_alloc(struct sock_cgroup_data *skcd)
7016 {
7017         struct cgroup *cgroup;
7018
7019         rcu_read_lock();
7020         /* Don't associate the sock with unrelated interrupted task's cgroup. */
7021         if (in_interrupt()) {
7022                 cgroup = &cgrp_dfl_root.cgrp;
7023                 cgroup_get(cgroup);
7024                 goto out;
7025         }
7026
7027         while (true) {
7028                 struct css_set *cset;
7029
7030                 cset = task_css_set(current);
7031                 if (likely(cgroup_tryget(cset->dfl_cgrp))) {
7032                         cgroup = cset->dfl_cgrp;
7033                         break;
7034                 }
7035                 cpu_relax();
7036         }
7037 out:
7038         skcd->cgroup = cgroup;
7039         cgroup_bpf_get(cgroup);
7040         rcu_read_unlock();
7041 }
7042
7043 void cgroup_sk_clone(struct sock_cgroup_data *skcd)
7044 {
7045         struct cgroup *cgrp = sock_cgroup_ptr(skcd);
7046
7047         /*
7048          * We might be cloning a socket which is left in an empty
7049          * cgroup and the cgroup might have already been rmdir'd.
7050          * Don't use cgroup_get_live().
7051          */
7052         cgroup_get(cgrp);
7053         cgroup_bpf_get(cgrp);
7054 }
7055
7056 void cgroup_sk_free(struct sock_cgroup_data *skcd)
7057 {
7058         struct cgroup *cgrp = sock_cgroup_ptr(skcd);
7059
7060         cgroup_bpf_put(cgrp);
7061         cgroup_put(cgrp);
7062 }
7063
7064 #endif  /* CONFIG_SOCK_CGROUP_DATA */
7065
7066 #ifdef CONFIG_SYSFS
7067 static ssize_t show_delegatable_files(struct cftype *files, char *buf,
7068                                       ssize_t size, const char *prefix)
7069 {
7070         struct cftype *cft;
7071         ssize_t ret = 0;
7072
7073         for (cft = files; cft && cft->name[0] != '\0'; cft++) {
7074                 if (!(cft->flags & CFTYPE_NS_DELEGATABLE))
7075                         continue;
7076
7077                 if (prefix)
7078                         ret += snprintf(buf + ret, size - ret, "%s.", prefix);
7079
7080                 ret += snprintf(buf + ret, size - ret, "%s\n", cft->name);
7081
7082                 if (WARN_ON(ret >= size))
7083                         break;
7084         }
7085
7086         return ret;
7087 }
7088
7089 static ssize_t delegate_show(struct kobject *kobj, struct kobj_attribute *attr,
7090                               char *buf)
7091 {
7092         struct cgroup_subsys *ss;
7093         int ssid;
7094         ssize_t ret = 0;
7095
7096         ret = show_delegatable_files(cgroup_base_files, buf + ret,
7097                                      PAGE_SIZE - ret, NULL);
7098         if (cgroup_psi_enabled())
7099                 ret += show_delegatable_files(cgroup_psi_files, buf + ret,
7100                                               PAGE_SIZE - ret, NULL);
7101
7102         for_each_subsys(ss, ssid)
7103                 ret += show_delegatable_files(ss->dfl_cftypes, buf + ret,
7104                                               PAGE_SIZE - ret,
7105                                               cgroup_subsys_name[ssid]);
7106
7107         return ret;
7108 }
7109 static struct kobj_attribute cgroup_delegate_attr = __ATTR_RO(delegate);
7110
7111 static ssize_t features_show(struct kobject *kobj, struct kobj_attribute *attr,
7112                              char *buf)
7113 {
7114         return snprintf(buf, PAGE_SIZE,
7115                         "nsdelegate\n"
7116                         "favordynmods\n"
7117                         "memory_localevents\n"
7118                         "memory_recursiveprot\n");
7119 }
7120 static struct kobj_attribute cgroup_features_attr = __ATTR_RO(features);
7121
7122 static struct attribute *cgroup_sysfs_attrs[] = {
7123         &cgroup_delegate_attr.attr,
7124         &cgroup_features_attr.attr,
7125         NULL,
7126 };
7127
7128 static const struct attribute_group cgroup_sysfs_attr_group = {
7129         .attrs = cgroup_sysfs_attrs,
7130         .name = "cgroup",
7131 };
7132
7133 static int __init cgroup_sysfs_init(void)
7134 {
7135         return sysfs_create_group(kernel_kobj, &cgroup_sysfs_attr_group);
7136 }
7137 subsys_initcall(cgroup_sysfs_init);
7138
7139 #endif /* CONFIG_SYSFS */