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