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