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