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