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