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