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