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