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