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