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