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