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