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