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