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