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