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