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