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