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