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