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