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