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