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