cgroup: refactor hierarchy_id handling
[platform/adaptation/renesas_rcar/renesas_kernel.git] / kernel / cgroup.c
1 /*
2  *  Generic process-grouping system.
3  *
4  *  Based originally on the cpuset system, extracted by Paul Menage
5  *  Copyright (C) 2006 Google, Inc
6  *
7  *  Notifications support
8  *  Copyright (C) 2009 Nokia Corporation
9  *  Author: Kirill A. Shutemov
10  *
11  *  Copyright notices from the original cpuset code:
12  *  --------------------------------------------------
13  *  Copyright (C) 2003 BULL SA.
14  *  Copyright (C) 2004-2006 Silicon Graphics, Inc.
15  *
16  *  Portions derived from Patrick Mochel's sysfs code.
17  *  sysfs is Copyright (c) 2001-3 Patrick Mochel
18  *
19  *  2003-10-10 Written by Simon Derr.
20  *  2003-10-22 Updates by Stephen Hemminger.
21  *  2004 May-July Rework by Paul Jackson.
22  *  ---------------------------------------------------
23  *
24  *  This file is subject to the terms and conditions of the GNU General Public
25  *  License.  See the file COPYING in the main directory of the Linux
26  *  distribution for more details.
27  */
28
29 #include <linux/cgroup.h>
30 #include <linux/cred.h>
31 #include <linux/ctype.h>
32 #include <linux/errno.h>
33 #include <linux/init_task.h>
34 #include <linux/kernel.h>
35 #include <linux/list.h>
36 #include <linux/mm.h>
37 #include <linux/mutex.h>
38 #include <linux/mount.h>
39 #include <linux/pagemap.h>
40 #include <linux/proc_fs.h>
41 #include <linux/rcupdate.h>
42 #include <linux/sched.h>
43 #include <linux/backing-dev.h>
44 #include <linux/seq_file.h>
45 #include <linux/slab.h>
46 #include <linux/magic.h>
47 #include <linux/spinlock.h>
48 #include <linux/string.h>
49 #include <linux/sort.h>
50 #include <linux/kmod.h>
51 #include <linux/module.h>
52 #include <linux/delayacct.h>
53 #include <linux/cgroupstats.h>
54 #include <linux/hashtable.h>
55 #include <linux/namei.h>
56 #include <linux/pid_namespace.h>
57 #include <linux/idr.h>
58 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
59 #include <linux/eventfd.h>
60 #include <linux/poll.h>
61 #include <linux/flex_array.h> /* used in cgroup_attach_task */
62 #include <linux/kthread.h>
63
64 #include <linux/atomic.h>
65
66 /* 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 int cgroup_init_root_id(struct cgroupfs_root *root)
1430 {
1431         int ret;
1432
1433         do {
1434                 if (!ida_pre_get(&hierarchy_ida, GFP_KERNEL))
1435                         return -ENOMEM;
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 0;
1452 }
1453
1454 static void cgroup_exit_root_id(struct cgroupfs_root *root)
1455 {
1456         if (root->hierarchy_id) {
1457                 spin_lock(&hierarchy_id_lock);
1458                 ida_remove(&hierarchy_ida, root->hierarchy_id);
1459                 spin_unlock(&hierarchy_id_lock);
1460
1461                 root->hierarchy_id = 0;
1462         }
1463 }
1464
1465 static int cgroup_test_super(struct super_block *sb, void *data)
1466 {
1467         struct cgroup_sb_opts *opts = data;
1468         struct cgroupfs_root *root = sb->s_fs_info;
1469
1470         /* If we asked for a name then it must match */
1471         if (opts->name && strcmp(opts->name, root->name))
1472                 return 0;
1473
1474         /*
1475          * If we asked for subsystems (or explicitly for no
1476          * subsystems) then they must match
1477          */
1478         if ((opts->subsys_mask || opts->none)
1479             && (opts->subsys_mask != root->subsys_mask))
1480                 return 0;
1481
1482         return 1;
1483 }
1484
1485 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1486 {
1487         struct cgroupfs_root *root;
1488
1489         if (!opts->subsys_mask && !opts->none)
1490                 return NULL;
1491
1492         root = kzalloc(sizeof(*root), GFP_KERNEL);
1493         if (!root)
1494                 return ERR_PTR(-ENOMEM);
1495
1496         init_cgroup_root(root);
1497
1498         root->subsys_mask = opts->subsys_mask;
1499         root->flags = opts->flags;
1500         ida_init(&root->cgroup_ida);
1501         if (opts->release_agent)
1502                 strcpy(root->release_agent_path, opts->release_agent);
1503         if (opts->name)
1504                 strcpy(root->name, opts->name);
1505         if (opts->cpuset_clone_children)
1506                 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1507         return root;
1508 }
1509
1510 static void cgroup_free_root(struct cgroupfs_root *root)
1511 {
1512         if (root) {
1513                 /* hierarhcy ID shoulid already have been released */
1514                 WARN_ON_ONCE(root->hierarchy_id);
1515
1516                 ida_destroy(&root->cgroup_ida);
1517                 kfree(root);
1518         }
1519 }
1520
1521 static int cgroup_set_super(struct super_block *sb, void *data)
1522 {
1523         int ret;
1524         struct cgroup_sb_opts *opts = data;
1525
1526         /* If we don't have a new root, we can't set up a new sb */
1527         if (!opts->new_root)
1528                 return -EINVAL;
1529
1530         BUG_ON(!opts->subsys_mask && !opts->none);
1531
1532         ret = set_anon_super(sb, NULL);
1533         if (ret)
1534                 return ret;
1535
1536         sb->s_fs_info = opts->new_root;
1537         opts->new_root->sb = sb;
1538
1539         sb->s_blocksize = PAGE_CACHE_SIZE;
1540         sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1541         sb->s_magic = CGROUP_SUPER_MAGIC;
1542         sb->s_op = &cgroup_ops;
1543
1544         return 0;
1545 }
1546
1547 static int cgroup_get_rootdir(struct super_block *sb)
1548 {
1549         static const struct dentry_operations cgroup_dops = {
1550                 .d_iput = cgroup_diput,
1551                 .d_delete = cgroup_delete,
1552         };
1553
1554         struct inode *inode =
1555                 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1556
1557         if (!inode)
1558                 return -ENOMEM;
1559
1560         inode->i_fop = &simple_dir_operations;
1561         inode->i_op = &cgroup_dir_inode_operations;
1562         /* directories start off with i_nlink == 2 (for "." entry) */
1563         inc_nlink(inode);
1564         sb->s_root = d_make_root(inode);
1565         if (!sb->s_root)
1566                 return -ENOMEM;
1567         /* for everything else we want ->d_op set */
1568         sb->s_d_op = &cgroup_dops;
1569         return 0;
1570 }
1571
1572 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1573                          int flags, const char *unused_dev_name,
1574                          void *data)
1575 {
1576         struct cgroup_sb_opts opts;
1577         struct cgroupfs_root *root;
1578         int ret = 0;
1579         struct super_block *sb;
1580         struct cgroupfs_root *new_root;
1581         struct inode *inode;
1582
1583         /* First find the desired set of subsystems */
1584         mutex_lock(&cgroup_mutex);
1585         ret = parse_cgroupfs_options(data, &opts);
1586         mutex_unlock(&cgroup_mutex);
1587         if (ret)
1588                 goto out_err;
1589
1590         /*
1591          * Allocate a new cgroup root. We may not need it if we're
1592          * reusing an existing hierarchy.
1593          */
1594         new_root = cgroup_root_from_opts(&opts);
1595         if (IS_ERR(new_root)) {
1596                 ret = PTR_ERR(new_root);
1597                 goto drop_modules;
1598         }
1599         opts.new_root = new_root;
1600
1601         /* Locate an existing or new sb for this hierarchy */
1602         sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1603         if (IS_ERR(sb)) {
1604                 ret = PTR_ERR(sb);
1605                 cgroup_free_root(opts.new_root);
1606                 goto drop_modules;
1607         }
1608
1609         root = sb->s_fs_info;
1610         BUG_ON(!root);
1611         if (root == opts.new_root) {
1612                 /* We used the new root structure, so this is a new hierarchy */
1613                 struct list_head tmp_cg_links;
1614                 struct cgroup *root_cgrp = &root->top_cgroup;
1615                 struct cgroupfs_root *existing_root;
1616                 const struct cred *cred;
1617                 int i;
1618                 struct css_set *cg;
1619
1620                 BUG_ON(sb->s_root != NULL);
1621
1622                 ret = cgroup_get_rootdir(sb);
1623                 if (ret)
1624                         goto drop_new_super;
1625                 inode = sb->s_root->d_inode;
1626
1627                 mutex_lock(&inode->i_mutex);
1628                 mutex_lock(&cgroup_mutex);
1629                 mutex_lock(&cgroup_root_mutex);
1630
1631                 /* Check for name clashes with existing mounts */
1632                 ret = -EBUSY;
1633                 if (strlen(root->name))
1634                         for_each_active_root(existing_root)
1635                                 if (!strcmp(existing_root->name, root->name))
1636                                         goto unlock_drop;
1637
1638                 /*
1639                  * We're accessing css_set_count without locking
1640                  * css_set_lock here, but that's OK - it can only be
1641                  * increased by someone holding cgroup_lock, and
1642                  * that's us. The worst that can happen is that we
1643                  * have some link structures left over
1644                  */
1645                 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
1646                 if (ret)
1647                         goto unlock_drop;
1648
1649                 ret = cgroup_init_root_id(root);
1650                 if (ret)
1651                         goto unlock_drop;
1652
1653                 ret = rebind_subsystems(root, root->subsys_mask);
1654                 if (ret == -EBUSY) {
1655                         free_cg_links(&tmp_cg_links);
1656                         goto unlock_drop;
1657                 }
1658                 /*
1659                  * There must be no failure case after here, since rebinding
1660                  * takes care of subsystems' refcounts, which are explicitly
1661                  * dropped in the failure exit path.
1662                  */
1663
1664                 /* EBUSY should be the only error here */
1665                 BUG_ON(ret);
1666
1667                 list_add(&root->root_list, &roots);
1668                 root_count++;
1669
1670                 sb->s_root->d_fsdata = root_cgrp;
1671                 root->top_cgroup.dentry = sb->s_root;
1672
1673                 /* Link the top cgroup in this hierarchy into all
1674                  * the css_set objects */
1675                 write_lock(&css_set_lock);
1676                 hash_for_each(css_set_table, i, cg, hlist)
1677                         link_css_set(&tmp_cg_links, cg, root_cgrp);
1678                 write_unlock(&css_set_lock);
1679
1680                 free_cg_links(&tmp_cg_links);
1681
1682                 BUG_ON(!list_empty(&root_cgrp->children));
1683                 BUG_ON(root->number_of_cgroups != 1);
1684
1685                 cred = override_creds(&init_cred);
1686                 cgroup_populate_dir(root_cgrp, true, root->subsys_mask);
1687                 revert_creds(cred);
1688                 mutex_unlock(&cgroup_root_mutex);
1689                 mutex_unlock(&cgroup_mutex);
1690                 mutex_unlock(&inode->i_mutex);
1691         } else {
1692                 /*
1693                  * We re-used an existing hierarchy - the new root (if
1694                  * any) is not needed
1695                  */
1696                 cgroup_free_root(opts.new_root);
1697
1698                 if (((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) &&
1699                     root->flags != opts.flags) {
1700                         pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1701                         ret = -EINVAL;
1702                         goto drop_new_super;
1703                 }
1704
1705                 /* no subsys rebinding, so refcounts don't change */
1706                 drop_parsed_module_refcounts(opts.subsys_mask);
1707         }
1708
1709         kfree(opts.release_agent);
1710         kfree(opts.name);
1711         return dget(sb->s_root);
1712
1713  unlock_drop:
1714         cgroup_exit_root_id(root);
1715         mutex_unlock(&cgroup_root_mutex);
1716         mutex_unlock(&cgroup_mutex);
1717         mutex_unlock(&inode->i_mutex);
1718  drop_new_super:
1719         deactivate_locked_super(sb);
1720  drop_modules:
1721         drop_parsed_module_refcounts(opts.subsys_mask);
1722  out_err:
1723         kfree(opts.release_agent);
1724         kfree(opts.name);
1725         return ERR_PTR(ret);
1726 }
1727
1728 static void cgroup_kill_sb(struct super_block *sb) {
1729         struct cgroupfs_root *root = sb->s_fs_info;
1730         struct cgroup *cgrp = &root->top_cgroup;
1731         int ret;
1732         struct cg_cgroup_link *link;
1733         struct cg_cgroup_link *saved_link;
1734
1735         BUG_ON(!root);
1736
1737         BUG_ON(root->number_of_cgroups != 1);
1738         BUG_ON(!list_empty(&cgrp->children));
1739
1740         mutex_lock(&cgroup_mutex);
1741         mutex_lock(&cgroup_root_mutex);
1742
1743         /* Rebind all subsystems back to the default hierarchy */
1744         ret = rebind_subsystems(root, 0);
1745         /* Shouldn't be able to fail ... */
1746         BUG_ON(ret);
1747
1748         /*
1749          * Release all the links from css_sets to this hierarchy's
1750          * root cgroup
1751          */
1752         write_lock(&css_set_lock);
1753
1754         list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1755                                  cgrp_link_list) {
1756                 list_del(&link->cg_link_list);
1757                 list_del(&link->cgrp_link_list);
1758                 kfree(link);
1759         }
1760         write_unlock(&css_set_lock);
1761
1762         if (!list_empty(&root->root_list)) {
1763                 list_del(&root->root_list);
1764                 root_count--;
1765         }
1766
1767         cgroup_exit_root_id(root);
1768
1769         mutex_unlock(&cgroup_root_mutex);
1770         mutex_unlock(&cgroup_mutex);
1771
1772         simple_xattrs_free(&cgrp->xattrs);
1773
1774         kill_litter_super(sb);
1775         cgroup_free_root(root);
1776 }
1777
1778 static struct file_system_type cgroup_fs_type = {
1779         .name = "cgroup",
1780         .mount = cgroup_mount,
1781         .kill_sb = cgroup_kill_sb,
1782 };
1783
1784 static struct kobject *cgroup_kobj;
1785
1786 /**
1787  * cgroup_path - generate the path of a cgroup
1788  * @cgrp: the cgroup in question
1789  * @buf: the buffer to write the path into
1790  * @buflen: the length of the buffer
1791  *
1792  * Writes path of cgroup into buf.  Returns 0 on success, -errno on error.
1793  *
1794  * We can't generate cgroup path using dentry->d_name, as accessing
1795  * dentry->name must be protected by irq-unsafe dentry->d_lock or parent
1796  * inode's i_mutex, while on the other hand cgroup_path() can be called
1797  * with some irq-safe spinlocks held.
1798  */
1799 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1800 {
1801         int ret = -ENAMETOOLONG;
1802         char *start;
1803
1804         if (!cgrp->parent) {
1805                 if (strlcpy(buf, "/", buflen) >= buflen)
1806                         return -ENAMETOOLONG;
1807                 return 0;
1808         }
1809
1810         start = buf + buflen - 1;
1811         *start = '\0';
1812
1813         rcu_read_lock();
1814         do {
1815                 const char *name = cgroup_name(cgrp);
1816                 int len;
1817
1818                 len = strlen(name);
1819                 if ((start -= len) < buf)
1820                         goto out;
1821                 memcpy(start, name, len);
1822
1823                 if (--start < buf)
1824                         goto out;
1825                 *start = '/';
1826
1827                 cgrp = cgrp->parent;
1828         } while (cgrp->parent);
1829         ret = 0;
1830         memmove(buf, start, buf + buflen - start);
1831 out:
1832         rcu_read_unlock();
1833         return ret;
1834 }
1835 EXPORT_SYMBOL_GPL(cgroup_path);
1836
1837 /*
1838  * Control Group taskset
1839  */
1840 struct task_and_cgroup {
1841         struct task_struct      *task;
1842         struct cgroup           *cgrp;
1843         struct css_set          *cg;
1844 };
1845
1846 struct cgroup_taskset {
1847         struct task_and_cgroup  single;
1848         struct flex_array       *tc_array;
1849         int                     tc_array_len;
1850         int                     idx;
1851         struct cgroup           *cur_cgrp;
1852 };
1853
1854 /**
1855  * cgroup_taskset_first - reset taskset and return the first task
1856  * @tset: taskset of interest
1857  *
1858  * @tset iteration is initialized and the first task is returned.
1859  */
1860 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1861 {
1862         if (tset->tc_array) {
1863                 tset->idx = 0;
1864                 return cgroup_taskset_next(tset);
1865         } else {
1866                 tset->cur_cgrp = tset->single.cgrp;
1867                 return tset->single.task;
1868         }
1869 }
1870 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1871
1872 /**
1873  * cgroup_taskset_next - iterate to the next task in taskset
1874  * @tset: taskset of interest
1875  *
1876  * Return the next task in @tset.  Iteration must have been initialized
1877  * with cgroup_taskset_first().
1878  */
1879 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1880 {
1881         struct task_and_cgroup *tc;
1882
1883         if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1884                 return NULL;
1885
1886         tc = flex_array_get(tset->tc_array, tset->idx++);
1887         tset->cur_cgrp = tc->cgrp;
1888         return tc->task;
1889 }
1890 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1891
1892 /**
1893  * cgroup_taskset_cur_cgroup - return the matching cgroup for the current task
1894  * @tset: taskset of interest
1895  *
1896  * Return the cgroup for the current (last returned) task of @tset.  This
1897  * function must be preceded by either cgroup_taskset_first() or
1898  * cgroup_taskset_next().
1899  */
1900 struct cgroup *cgroup_taskset_cur_cgroup(struct cgroup_taskset *tset)
1901 {
1902         return tset->cur_cgrp;
1903 }
1904 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_cgroup);
1905
1906 /**
1907  * cgroup_taskset_size - return the number of tasks in taskset
1908  * @tset: taskset of interest
1909  */
1910 int cgroup_taskset_size(struct cgroup_taskset *tset)
1911 {
1912         return tset->tc_array ? tset->tc_array_len : 1;
1913 }
1914 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1915
1916
1917 /*
1918  * cgroup_task_migrate - move a task from one cgroup to another.
1919  *
1920  * Must be called with cgroup_mutex and threadgroup locked.
1921  */
1922 static void cgroup_task_migrate(struct cgroup *oldcgrp,
1923                                 struct task_struct *tsk, struct css_set *newcg)
1924 {
1925         struct css_set *oldcg;
1926
1927         /*
1928          * We are synchronized through threadgroup_lock() against PF_EXITING
1929          * setting such that we can't race against cgroup_exit() changing the
1930          * css_set to init_css_set and dropping the old one.
1931          */
1932         WARN_ON_ONCE(tsk->flags & PF_EXITING);
1933         oldcg = tsk->cgroups;
1934
1935         task_lock(tsk);
1936         rcu_assign_pointer(tsk->cgroups, newcg);
1937         task_unlock(tsk);
1938
1939         /* Update the css_set linked lists if we're using them */
1940         write_lock(&css_set_lock);
1941         if (!list_empty(&tsk->cg_list))
1942                 list_move(&tsk->cg_list, &newcg->tasks);
1943         write_unlock(&css_set_lock);
1944
1945         /*
1946          * We just gained a reference on oldcg by taking it from the task. As
1947          * trading it for newcg is protected by cgroup_mutex, we're safe to drop
1948          * it here; it will be freed under RCU.
1949          */
1950         set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1951         put_css_set(oldcg);
1952 }
1953
1954 /**
1955  * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1956  * @cgrp: the cgroup to attach to
1957  * @tsk: the task or the leader of the threadgroup to be attached
1958  * @threadgroup: attach the whole threadgroup?
1959  *
1960  * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
1961  * task_lock of @tsk or each thread in the threadgroup individually in turn.
1962  */
1963 static int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk,
1964                               bool threadgroup)
1965 {
1966         int retval, i, group_size;
1967         struct cgroup_subsys *ss, *failed_ss = NULL;
1968         struct cgroupfs_root *root = cgrp->root;
1969         /* threadgroup list cursor and array */
1970         struct task_struct *leader = tsk;
1971         struct task_and_cgroup *tc;
1972         struct flex_array *group;
1973         struct cgroup_taskset tset = { };
1974
1975         /*
1976          * step 0: in order to do expensive, possibly blocking operations for
1977          * every thread, we cannot iterate the thread group list, since it needs
1978          * rcu or tasklist locked. instead, build an array of all threads in the
1979          * group - group_rwsem prevents new threads from appearing, and if
1980          * threads exit, this will just be an over-estimate.
1981          */
1982         if (threadgroup)
1983                 group_size = get_nr_threads(tsk);
1984         else
1985                 group_size = 1;
1986         /* flex_array supports very large thread-groups better than kmalloc. */
1987         group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
1988         if (!group)
1989                 return -ENOMEM;
1990         /* pre-allocate to guarantee space while iterating in rcu read-side. */
1991         retval = flex_array_prealloc(group, 0, group_size, GFP_KERNEL);
1992         if (retval)
1993                 goto out_free_group_list;
1994
1995         i = 0;
1996         /*
1997          * Prevent freeing of tasks while we take a snapshot. Tasks that are
1998          * already PF_EXITING could be freed from underneath us unless we
1999          * take an rcu_read_lock.
2000          */
2001         rcu_read_lock();
2002         do {
2003                 struct task_and_cgroup ent;
2004
2005                 /* @tsk either already exited or can't exit until the end */
2006                 if (tsk->flags & PF_EXITING)
2007                         continue;
2008
2009                 /* as per above, nr_threads may decrease, but not increase. */
2010                 BUG_ON(i >= group_size);
2011                 ent.task = tsk;
2012                 ent.cgrp = task_cgroup_from_root(tsk, root);
2013                 /* nothing to do if this task is already in the cgroup */
2014                 if (ent.cgrp == cgrp)
2015                         continue;
2016                 /*
2017                  * saying GFP_ATOMIC has no effect here because we did prealloc
2018                  * earlier, but it's good form to communicate our expectations.
2019                  */
2020                 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
2021                 BUG_ON(retval != 0);
2022                 i++;
2023
2024                 if (!threadgroup)
2025                         break;
2026         } while_each_thread(leader, tsk);
2027         rcu_read_unlock();
2028         /* remember the number of threads in the array for later. */
2029         group_size = i;
2030         tset.tc_array = group;
2031         tset.tc_array_len = group_size;
2032
2033         /* methods shouldn't be called if no task is actually migrating */
2034         retval = 0;
2035         if (!group_size)
2036                 goto out_free_group_list;
2037
2038         /*
2039          * step 1: check that we can legitimately attach to the cgroup.
2040          */
2041         for_each_subsys(root, ss) {
2042                 if (ss->can_attach) {
2043                         retval = ss->can_attach(cgrp, &tset);
2044                         if (retval) {
2045                                 failed_ss = ss;
2046                                 goto out_cancel_attach;
2047                         }
2048                 }
2049         }
2050
2051         /*
2052          * step 2: make sure css_sets exist for all threads to be migrated.
2053          * we use find_css_set, which allocates a new one if necessary.
2054          */
2055         for (i = 0; i < group_size; i++) {
2056                 tc = flex_array_get(group, i);
2057                 tc->cg = find_css_set(tc->task->cgroups, cgrp);
2058                 if (!tc->cg) {
2059                         retval = -ENOMEM;
2060                         goto out_put_css_set_refs;
2061                 }
2062         }
2063
2064         /*
2065          * step 3: now that we're guaranteed success wrt the css_sets,
2066          * proceed to move all tasks to the new cgroup.  There are no
2067          * failure cases after here, so this is the commit point.
2068          */
2069         for (i = 0; i < group_size; i++) {
2070                 tc = flex_array_get(group, i);
2071                 cgroup_task_migrate(tc->cgrp, tc->task, tc->cg);
2072         }
2073         /* nothing is sensitive to fork() after this point. */
2074
2075         /*
2076          * step 4: do subsystem attach callbacks.
2077          */
2078         for_each_subsys(root, ss) {
2079                 if (ss->attach)
2080                         ss->attach(cgrp, &tset);
2081         }
2082
2083         /*
2084          * step 5: success! and cleanup
2085          */
2086         retval = 0;
2087 out_put_css_set_refs:
2088         if (retval) {
2089                 for (i = 0; i < group_size; i++) {
2090                         tc = flex_array_get(group, i);
2091                         if (!tc->cg)
2092                                 break;
2093                         put_css_set(tc->cg);
2094                 }
2095         }
2096 out_cancel_attach:
2097         if (retval) {
2098                 for_each_subsys(root, ss) {
2099                         if (ss == failed_ss)
2100                                 break;
2101                         if (ss->cancel_attach)
2102                                 ss->cancel_attach(cgrp, &tset);
2103                 }
2104         }
2105 out_free_group_list:
2106         flex_array_free(group);
2107         return retval;
2108 }
2109
2110 /*
2111  * Find the task_struct of the task to attach by vpid and pass it along to the
2112  * function to attach either it or all tasks in its threadgroup. Will lock
2113  * cgroup_mutex and threadgroup; may take task_lock of task.
2114  */
2115 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2116 {
2117         struct task_struct *tsk;
2118         const struct cred *cred = current_cred(), *tcred;
2119         int ret;
2120
2121         if (!cgroup_lock_live_group(cgrp))
2122                 return -ENODEV;
2123
2124 retry_find_task:
2125         rcu_read_lock();
2126         if (pid) {
2127                 tsk = find_task_by_vpid(pid);
2128                 if (!tsk) {
2129                         rcu_read_unlock();
2130                         ret= -ESRCH;
2131                         goto out_unlock_cgroup;
2132                 }
2133                 /*
2134                  * even if we're attaching all tasks in the thread group, we
2135                  * only need to check permissions on one of them.
2136                  */
2137                 tcred = __task_cred(tsk);
2138                 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2139                     !uid_eq(cred->euid, tcred->uid) &&
2140                     !uid_eq(cred->euid, tcred->suid)) {
2141                         rcu_read_unlock();
2142                         ret = -EACCES;
2143                         goto out_unlock_cgroup;
2144                 }
2145         } else
2146                 tsk = current;
2147
2148         if (threadgroup)
2149                 tsk = tsk->group_leader;
2150
2151         /*
2152          * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2153          * trapped in a cpuset, or RT worker may be born in a cgroup
2154          * with no rt_runtime allocated.  Just say no.
2155          */
2156         if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2157                 ret = -EINVAL;
2158                 rcu_read_unlock();
2159                 goto out_unlock_cgroup;
2160         }
2161
2162         get_task_struct(tsk);
2163         rcu_read_unlock();
2164
2165         threadgroup_lock(tsk);
2166         if (threadgroup) {
2167                 if (!thread_group_leader(tsk)) {
2168                         /*
2169                          * a race with de_thread from another thread's exec()
2170                          * may strip us of our leadership, if this happens,
2171                          * there is no choice but to throw this task away and
2172                          * try again; this is
2173                          * "double-double-toil-and-trouble-check locking".
2174                          */
2175                         threadgroup_unlock(tsk);
2176                         put_task_struct(tsk);
2177                         goto retry_find_task;
2178                 }
2179         }
2180
2181         ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2182
2183         threadgroup_unlock(tsk);
2184
2185         put_task_struct(tsk);
2186 out_unlock_cgroup:
2187         mutex_unlock(&cgroup_mutex);
2188         return ret;
2189 }
2190
2191 /**
2192  * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2193  * @from: attach to all cgroups of a given task
2194  * @tsk: the task to be attached
2195  */
2196 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2197 {
2198         struct cgroupfs_root *root;
2199         int retval = 0;
2200
2201         mutex_lock(&cgroup_mutex);
2202         for_each_active_root(root) {
2203                 struct cgroup *from_cg = task_cgroup_from_root(from, root);
2204
2205                 retval = cgroup_attach_task(from_cg, tsk, false);
2206                 if (retval)
2207                         break;
2208         }
2209         mutex_unlock(&cgroup_mutex);
2210
2211         return retval;
2212 }
2213 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2214
2215 static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
2216 {
2217         return attach_task_by_pid(cgrp, pid, false);
2218 }
2219
2220 static int cgroup_procs_write(struct cgroup *cgrp, struct cftype *cft, u64 tgid)
2221 {
2222         return attach_task_by_pid(cgrp, tgid, true);
2223 }
2224
2225 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
2226                                       const char *buffer)
2227 {
2228         BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
2229         if (strlen(buffer) >= PATH_MAX)
2230                 return -EINVAL;
2231         if (!cgroup_lock_live_group(cgrp))
2232                 return -ENODEV;
2233         mutex_lock(&cgroup_root_mutex);
2234         strcpy(cgrp->root->release_agent_path, buffer);
2235         mutex_unlock(&cgroup_root_mutex);
2236         mutex_unlock(&cgroup_mutex);
2237         return 0;
2238 }
2239
2240 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
2241                                      struct seq_file *seq)
2242 {
2243         if (!cgroup_lock_live_group(cgrp))
2244                 return -ENODEV;
2245         seq_puts(seq, cgrp->root->release_agent_path);
2246         seq_putc(seq, '\n');
2247         mutex_unlock(&cgroup_mutex);
2248         return 0;
2249 }
2250
2251 static int cgroup_sane_behavior_show(struct cgroup *cgrp, struct cftype *cft,
2252                                      struct seq_file *seq)
2253 {
2254         seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
2255         return 0;
2256 }
2257
2258 /* A buffer size big enough for numbers or short strings */
2259 #define CGROUP_LOCAL_BUFFER_SIZE 64
2260
2261 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
2262                                 struct file *file,
2263                                 const char __user *userbuf,
2264                                 size_t nbytes, loff_t *unused_ppos)
2265 {
2266         char buffer[CGROUP_LOCAL_BUFFER_SIZE];
2267         int retval = 0;
2268         char *end;
2269
2270         if (!nbytes)
2271                 return -EINVAL;
2272         if (nbytes >= sizeof(buffer))
2273                 return -E2BIG;
2274         if (copy_from_user(buffer, userbuf, nbytes))
2275                 return -EFAULT;
2276
2277         buffer[nbytes] = 0;     /* nul-terminate */
2278         if (cft->write_u64) {
2279                 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
2280                 if (*end)
2281                         return -EINVAL;
2282                 retval = cft->write_u64(cgrp, cft, val);
2283         } else {
2284                 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
2285                 if (*end)
2286                         return -EINVAL;
2287                 retval = cft->write_s64(cgrp, cft, val);
2288         }
2289         if (!retval)
2290                 retval = nbytes;
2291         return retval;
2292 }
2293
2294 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
2295                                    struct file *file,
2296                                    const char __user *userbuf,
2297                                    size_t nbytes, loff_t *unused_ppos)
2298 {
2299         char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
2300         int retval = 0;
2301         size_t max_bytes = cft->max_write_len;
2302         char *buffer = local_buffer;
2303
2304         if (!max_bytes)
2305                 max_bytes = sizeof(local_buffer) - 1;
2306         if (nbytes >= max_bytes)
2307                 return -E2BIG;
2308         /* Allocate a dynamic buffer if we need one */
2309         if (nbytes >= sizeof(local_buffer)) {
2310                 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2311                 if (buffer == NULL)
2312                         return -ENOMEM;
2313         }
2314         if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2315                 retval = -EFAULT;
2316                 goto out;
2317         }
2318
2319         buffer[nbytes] = 0;     /* nul-terminate */
2320         retval = cft->write_string(cgrp, cft, strstrip(buffer));
2321         if (!retval)
2322                 retval = nbytes;
2323 out:
2324         if (buffer != local_buffer)
2325                 kfree(buffer);
2326         return retval;
2327 }
2328
2329 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2330                                                 size_t nbytes, loff_t *ppos)
2331 {
2332         struct cftype *cft = __d_cft(file->f_dentry);
2333         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2334
2335         if (cgroup_is_removed(cgrp))
2336                 return -ENODEV;
2337         if (cft->write)
2338                 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
2339         if (cft->write_u64 || cft->write_s64)
2340                 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
2341         if (cft->write_string)
2342                 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
2343         if (cft->trigger) {
2344                 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
2345                 return ret ? ret : nbytes;
2346         }
2347         return -EINVAL;
2348 }
2349
2350 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
2351                                struct file *file,
2352                                char __user *buf, size_t nbytes,
2353                                loff_t *ppos)
2354 {
2355         char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2356         u64 val = cft->read_u64(cgrp, cft);
2357         int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2358
2359         return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2360 }
2361
2362 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
2363                                struct file *file,
2364                                char __user *buf, size_t nbytes,
2365                                loff_t *ppos)
2366 {
2367         char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2368         s64 val = cft->read_s64(cgrp, cft);
2369         int len = sprintf(tmp, "%lld\n", (long long) val);
2370
2371         return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2372 }
2373
2374 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2375                                    size_t nbytes, loff_t *ppos)
2376 {
2377         struct cftype *cft = __d_cft(file->f_dentry);
2378         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2379
2380         if (cgroup_is_removed(cgrp))
2381                 return -ENODEV;
2382
2383         if (cft->read)
2384                 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
2385         if (cft->read_u64)
2386                 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
2387         if (cft->read_s64)
2388                 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
2389         return -EINVAL;
2390 }
2391
2392 /*
2393  * seqfile ops/methods for returning structured data. Currently just
2394  * supports string->u64 maps, but can be extended in future.
2395  */
2396
2397 struct cgroup_seqfile_state {
2398         struct cftype *cft;
2399         struct cgroup *cgroup;
2400 };
2401
2402 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2403 {
2404         struct seq_file *sf = cb->state;
2405         return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2406 }
2407
2408 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2409 {
2410         struct cgroup_seqfile_state *state = m->private;
2411         struct cftype *cft = state->cft;
2412         if (cft->read_map) {
2413                 struct cgroup_map_cb cb = {
2414                         .fill = cgroup_map_add,
2415                         .state = m,
2416                 };
2417                 return cft->read_map(state->cgroup, cft, &cb);
2418         }
2419         return cft->read_seq_string(state->cgroup, cft, m);
2420 }
2421
2422 static int cgroup_seqfile_release(struct inode *inode, struct file *file)
2423 {
2424         struct seq_file *seq = file->private_data;
2425         kfree(seq->private);
2426         return single_release(inode, file);
2427 }
2428
2429 static const struct file_operations cgroup_seqfile_operations = {
2430         .read = seq_read,
2431         .write = cgroup_file_write,
2432         .llseek = seq_lseek,
2433         .release = cgroup_seqfile_release,
2434 };
2435
2436 static int cgroup_file_open(struct inode *inode, struct file *file)
2437 {
2438         int err;
2439         struct cftype *cft;
2440
2441         err = generic_file_open(inode, file);
2442         if (err)
2443                 return err;
2444         cft = __d_cft(file->f_dentry);
2445
2446         if (cft->read_map || cft->read_seq_string) {
2447                 struct cgroup_seqfile_state *state =
2448                         kzalloc(sizeof(*state), GFP_USER);
2449                 if (!state)
2450                         return -ENOMEM;
2451                 state->cft = cft;
2452                 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
2453                 file->f_op = &cgroup_seqfile_operations;
2454                 err = single_open(file, cgroup_seqfile_show, state);
2455                 if (err < 0)
2456                         kfree(state);
2457         } else if (cft->open)
2458                 err = cft->open(inode, file);
2459         else
2460                 err = 0;
2461
2462         return err;
2463 }
2464
2465 static int cgroup_file_release(struct inode *inode, struct file *file)
2466 {
2467         struct cftype *cft = __d_cft(file->f_dentry);
2468         if (cft->release)
2469                 return cft->release(inode, file);
2470         return 0;
2471 }
2472
2473 /*
2474  * cgroup_rename - Only allow simple rename of directories in place.
2475  */
2476 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2477                             struct inode *new_dir, struct dentry *new_dentry)
2478 {
2479         int ret;
2480         struct cgroup_name *name, *old_name;
2481         struct cgroup *cgrp;
2482
2483         /*
2484          * It's convinient to use parent dir's i_mutex to protected
2485          * cgrp->name.
2486          */
2487         lockdep_assert_held(&old_dir->i_mutex);
2488
2489         if (!S_ISDIR(old_dentry->d_inode->i_mode))
2490                 return -ENOTDIR;
2491         if (new_dentry->d_inode)
2492                 return -EEXIST;
2493         if (old_dir != new_dir)
2494                 return -EIO;
2495
2496         cgrp = __d_cgrp(old_dentry);
2497
2498         name = cgroup_alloc_name(new_dentry);
2499         if (!name)
2500                 return -ENOMEM;
2501
2502         ret = simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2503         if (ret) {
2504                 kfree(name);
2505                 return ret;
2506         }
2507
2508         old_name = cgrp->name;
2509         rcu_assign_pointer(cgrp->name, name);
2510
2511         kfree_rcu(old_name, rcu_head);
2512         return 0;
2513 }
2514
2515 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2516 {
2517         if (S_ISDIR(dentry->d_inode->i_mode))
2518                 return &__d_cgrp(dentry)->xattrs;
2519         else
2520                 return &__d_cfe(dentry)->xattrs;
2521 }
2522
2523 static inline int xattr_enabled(struct dentry *dentry)
2524 {
2525         struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2526         return root->flags & CGRP_ROOT_XATTR;
2527 }
2528
2529 static bool is_valid_xattr(const char *name)
2530 {
2531         if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2532             !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2533                 return true;
2534         return false;
2535 }
2536
2537 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2538                            const void *val, size_t size, int flags)
2539 {
2540         if (!xattr_enabled(dentry))
2541                 return -EOPNOTSUPP;
2542         if (!is_valid_xattr(name))
2543                 return -EINVAL;
2544         return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2545 }
2546
2547 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2548 {
2549         if (!xattr_enabled(dentry))
2550                 return -EOPNOTSUPP;
2551         if (!is_valid_xattr(name))
2552                 return -EINVAL;
2553         return simple_xattr_remove(__d_xattrs(dentry), name);
2554 }
2555
2556 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2557                                void *buf, size_t size)
2558 {
2559         if (!xattr_enabled(dentry))
2560                 return -EOPNOTSUPP;
2561         if (!is_valid_xattr(name))
2562                 return -EINVAL;
2563         return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2564 }
2565
2566 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2567 {
2568         if (!xattr_enabled(dentry))
2569                 return -EOPNOTSUPP;
2570         return simple_xattr_list(__d_xattrs(dentry), buf, size);
2571 }
2572
2573 static const struct file_operations cgroup_file_operations = {
2574         .read = cgroup_file_read,
2575         .write = cgroup_file_write,
2576         .llseek = generic_file_llseek,
2577         .open = cgroup_file_open,
2578         .release = cgroup_file_release,
2579 };
2580
2581 static const struct inode_operations cgroup_file_inode_operations = {
2582         .setxattr = cgroup_setxattr,
2583         .getxattr = cgroup_getxattr,
2584         .listxattr = cgroup_listxattr,
2585         .removexattr = cgroup_removexattr,
2586 };
2587
2588 static const struct inode_operations cgroup_dir_inode_operations = {
2589         .lookup = cgroup_lookup,
2590         .mkdir = cgroup_mkdir,
2591         .rmdir = cgroup_rmdir,
2592         .rename = cgroup_rename,
2593         .setxattr = cgroup_setxattr,
2594         .getxattr = cgroup_getxattr,
2595         .listxattr = cgroup_listxattr,
2596         .removexattr = cgroup_removexattr,
2597 };
2598
2599 static struct dentry *cgroup_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
2600 {
2601         if (dentry->d_name.len > NAME_MAX)
2602                 return ERR_PTR(-ENAMETOOLONG);
2603         d_add(dentry, NULL);
2604         return NULL;
2605 }
2606
2607 /*
2608  * Check if a file is a control file
2609  */
2610 static inline struct cftype *__file_cft(struct file *file)
2611 {
2612         if (file_inode(file)->i_fop != &cgroup_file_operations)
2613                 return ERR_PTR(-EINVAL);
2614         return __d_cft(file->f_dentry);
2615 }
2616
2617 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2618                                 struct super_block *sb)
2619 {
2620         struct inode *inode;
2621
2622         if (!dentry)
2623                 return -ENOENT;
2624         if (dentry->d_inode)
2625                 return -EEXIST;
2626
2627         inode = cgroup_new_inode(mode, sb);
2628         if (!inode)
2629                 return -ENOMEM;
2630
2631         if (S_ISDIR(mode)) {
2632                 inode->i_op = &cgroup_dir_inode_operations;
2633                 inode->i_fop = &simple_dir_operations;
2634
2635                 /* start off with i_nlink == 2 (for "." entry) */
2636                 inc_nlink(inode);
2637                 inc_nlink(dentry->d_parent->d_inode);
2638
2639                 /*
2640                  * Control reaches here with cgroup_mutex held.
2641                  * @inode->i_mutex should nest outside cgroup_mutex but we
2642                  * want to populate it immediately without releasing
2643                  * cgroup_mutex.  As @inode isn't visible to anyone else
2644                  * yet, trylock will always succeed without affecting
2645                  * lockdep checks.
2646                  */
2647                 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2648         } else if (S_ISREG(mode)) {
2649                 inode->i_size = 0;
2650                 inode->i_fop = &cgroup_file_operations;
2651                 inode->i_op = &cgroup_file_inode_operations;
2652         }
2653         d_instantiate(dentry, inode);
2654         dget(dentry);   /* Extra count - pin the dentry in core */
2655         return 0;
2656 }
2657
2658 /**
2659  * cgroup_file_mode - deduce file mode of a control file
2660  * @cft: the control file in question
2661  *
2662  * returns cft->mode if ->mode is not 0
2663  * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2664  * returns S_IRUGO if it has only a read handler
2665  * returns S_IWUSR if it has only a write hander
2666  */
2667 static umode_t cgroup_file_mode(const struct cftype *cft)
2668 {
2669         umode_t mode = 0;
2670
2671         if (cft->mode)
2672                 return cft->mode;
2673
2674         if (cft->read || cft->read_u64 || cft->read_s64 ||
2675             cft->read_map || cft->read_seq_string)
2676                 mode |= S_IRUGO;
2677
2678         if (cft->write || cft->write_u64 || cft->write_s64 ||
2679             cft->write_string || cft->trigger)
2680                 mode |= S_IWUSR;
2681
2682         return mode;
2683 }
2684
2685 static int cgroup_add_file(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2686                            struct cftype *cft)
2687 {
2688         struct dentry *dir = cgrp->dentry;
2689         struct cgroup *parent = __d_cgrp(dir);
2690         struct dentry *dentry;
2691         struct cfent *cfe;
2692         int error;
2693         umode_t mode;
2694         char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2695
2696         if (subsys && !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
2697                 strcpy(name, subsys->name);
2698                 strcat(name, ".");
2699         }
2700         strcat(name, cft->name);
2701
2702         BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2703
2704         cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2705         if (!cfe)
2706                 return -ENOMEM;
2707
2708         dentry = lookup_one_len(name, dir, strlen(name));
2709         if (IS_ERR(dentry)) {
2710                 error = PTR_ERR(dentry);
2711                 goto out;
2712         }
2713
2714         mode = cgroup_file_mode(cft);
2715         error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2716         if (!error) {
2717                 cfe->type = (void *)cft;
2718                 cfe->dentry = dentry;
2719                 dentry->d_fsdata = cfe;
2720                 simple_xattrs_init(&cfe->xattrs);
2721                 list_add_tail(&cfe->node, &parent->files);
2722                 cfe = NULL;
2723         }
2724         dput(dentry);
2725 out:
2726         kfree(cfe);
2727         return error;
2728 }
2729
2730 static int cgroup_addrm_files(struct cgroup *cgrp, struct cgroup_subsys *subsys,
2731                               struct cftype cfts[], bool is_add)
2732 {
2733         struct cftype *cft;
2734         int err, ret = 0;
2735
2736         for (cft = cfts; cft->name[0] != '\0'; cft++) {
2737                 /* does cft->flags tell us to skip this file on @cgrp? */
2738                 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2739                         continue;
2740                 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2741                         continue;
2742                 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2743                         continue;
2744
2745                 if (is_add) {
2746                         err = cgroup_add_file(cgrp, subsys, cft);
2747                         if (err)
2748                                 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2749                                         cft->name, err);
2750                         ret = err;
2751                 } else {
2752                         cgroup_rm_file(cgrp, cft);
2753                 }
2754         }
2755         return ret;
2756 }
2757
2758 static DEFINE_MUTEX(cgroup_cft_mutex);
2759
2760 static void cgroup_cfts_prepare(void)
2761         __acquires(&cgroup_cft_mutex) __acquires(&cgroup_mutex)
2762 {
2763         /*
2764          * Thanks to the entanglement with vfs inode locking, we can't walk
2765          * the existing cgroups under cgroup_mutex and create files.
2766          * Instead, we increment reference on all cgroups and build list of
2767          * them using @cgrp->cft_q_node.  Grab cgroup_cft_mutex to ensure
2768          * exclusive access to the field.
2769          */
2770         mutex_lock(&cgroup_cft_mutex);
2771         mutex_lock(&cgroup_mutex);
2772 }
2773
2774 static void cgroup_cfts_commit(struct cgroup_subsys *ss,
2775                                struct cftype *cfts, bool is_add)
2776         __releases(&cgroup_mutex) __releases(&cgroup_cft_mutex)
2777 {
2778         LIST_HEAD(pending);
2779         struct cgroup *cgrp, *n;
2780
2781         /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2782         if (cfts && ss->root != &rootnode) {
2783                 list_for_each_entry(cgrp, &ss->root->allcg_list, allcg_node) {
2784                         dget(cgrp->dentry);
2785                         list_add_tail(&cgrp->cft_q_node, &pending);
2786                 }
2787         }
2788
2789         mutex_unlock(&cgroup_mutex);
2790
2791         /*
2792          * All new cgroups will see @cfts update on @ss->cftsets.  Add/rm
2793          * files for all cgroups which were created before.
2794          */
2795         list_for_each_entry_safe(cgrp, n, &pending, cft_q_node) {
2796                 struct inode *inode = cgrp->dentry->d_inode;
2797
2798                 mutex_lock(&inode->i_mutex);
2799                 mutex_lock(&cgroup_mutex);
2800                 if (!cgroup_is_removed(cgrp))
2801                         cgroup_addrm_files(cgrp, ss, cfts, is_add);
2802                 mutex_unlock(&cgroup_mutex);
2803                 mutex_unlock(&inode->i_mutex);
2804
2805                 list_del_init(&cgrp->cft_q_node);
2806                 dput(cgrp->dentry);
2807         }
2808
2809         mutex_unlock(&cgroup_cft_mutex);
2810 }
2811
2812 /**
2813  * cgroup_add_cftypes - add an array of cftypes to a subsystem
2814  * @ss: target cgroup subsystem
2815  * @cfts: zero-length name terminated array of cftypes
2816  *
2817  * Register @cfts to @ss.  Files described by @cfts are created for all
2818  * existing cgroups to which @ss is attached and all future cgroups will
2819  * have them too.  This function can be called anytime whether @ss is
2820  * attached or not.
2821  *
2822  * Returns 0 on successful registration, -errno on failure.  Note that this
2823  * function currently returns 0 as long as @cfts registration is successful
2824  * even if some file creation attempts on existing cgroups fail.
2825  */
2826 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2827 {
2828         struct cftype_set *set;
2829
2830         set = kzalloc(sizeof(*set), GFP_KERNEL);
2831         if (!set)
2832                 return -ENOMEM;
2833
2834         cgroup_cfts_prepare();
2835         set->cfts = cfts;
2836         list_add_tail(&set->node, &ss->cftsets);
2837         cgroup_cfts_commit(ss, cfts, true);
2838
2839         return 0;
2840 }
2841 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2842
2843 /**
2844  * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2845  * @ss: target cgroup subsystem
2846  * @cfts: zero-length name terminated array of cftypes
2847  *
2848  * Unregister @cfts from @ss.  Files described by @cfts are removed from
2849  * all existing cgroups to which @ss is attached and all future cgroups
2850  * won't have them either.  This function can be called anytime whether @ss
2851  * is attached or not.
2852  *
2853  * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2854  * registered with @ss.
2855  */
2856 int cgroup_rm_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2857 {
2858         struct cftype_set *set;
2859
2860         cgroup_cfts_prepare();
2861
2862         list_for_each_entry(set, &ss->cftsets, node) {
2863                 if (set->cfts == cfts) {
2864                         list_del_init(&set->node);
2865                         cgroup_cfts_commit(ss, cfts, false);
2866                         return 0;
2867                 }
2868         }
2869
2870         cgroup_cfts_commit(ss, NULL, false);
2871         return -ENOENT;
2872 }
2873
2874 /**
2875  * cgroup_task_count - count the number of tasks in a cgroup.
2876  * @cgrp: the cgroup in question
2877  *
2878  * Return the number of tasks in the cgroup.
2879  */
2880 int cgroup_task_count(const struct cgroup *cgrp)
2881 {
2882         int count = 0;
2883         struct cg_cgroup_link *link;
2884
2885         read_lock(&css_set_lock);
2886         list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
2887                 count += atomic_read(&link->cg->refcount);
2888         }
2889         read_unlock(&css_set_lock);
2890         return count;
2891 }
2892
2893 /*
2894  * Advance a list_head iterator.  The iterator should be positioned at
2895  * the start of a css_set
2896  */
2897 static void cgroup_advance_iter(struct cgroup *cgrp,
2898                                 struct cgroup_iter *it)
2899 {
2900         struct list_head *l = it->cg_link;
2901         struct cg_cgroup_link *link;
2902         struct css_set *cg;
2903
2904         /* Advance to the next non-empty css_set */
2905         do {
2906                 l = l->next;
2907                 if (l == &cgrp->css_sets) {
2908                         it->cg_link = NULL;
2909                         return;
2910                 }
2911                 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
2912                 cg = link->cg;
2913         } while (list_empty(&cg->tasks));
2914         it->cg_link = l;
2915         it->task = cg->tasks.next;
2916 }
2917
2918 /*
2919  * To reduce the fork() overhead for systems that are not actually
2920  * using their cgroups capability, we don't maintain the lists running
2921  * through each css_set to its tasks until we see the list actually
2922  * used - in other words after the first call to cgroup_iter_start().
2923  */
2924 static void cgroup_enable_task_cg_lists(void)
2925 {
2926         struct task_struct *p, *g;
2927         write_lock(&css_set_lock);
2928         use_task_css_set_links = 1;
2929         /*
2930          * We need tasklist_lock because RCU is not safe against
2931          * while_each_thread(). Besides, a forking task that has passed
2932          * cgroup_post_fork() without seeing use_task_css_set_links = 1
2933          * is not guaranteed to have its child immediately visible in the
2934          * tasklist if we walk through it with RCU.
2935          */
2936         read_lock(&tasklist_lock);
2937         do_each_thread(g, p) {
2938                 task_lock(p);
2939                 /*
2940                  * We should check if the process is exiting, otherwise
2941                  * it will race with cgroup_exit() in that the list
2942                  * entry won't be deleted though the process has exited.
2943                  */
2944                 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2945                         list_add(&p->cg_list, &p->cgroups->tasks);
2946                 task_unlock(p);
2947         } while_each_thread(g, p);
2948         read_unlock(&tasklist_lock);
2949         write_unlock(&css_set_lock);
2950 }
2951
2952 /**
2953  * cgroup_next_descendant_pre - find the next descendant for pre-order walk
2954  * @pos: the current position (%NULL to initiate traversal)
2955  * @cgroup: cgroup whose descendants to walk
2956  *
2957  * To be used by cgroup_for_each_descendant_pre().  Find the next
2958  * descendant to visit for pre-order traversal of @cgroup's descendants.
2959  */
2960 struct cgroup *cgroup_next_descendant_pre(struct cgroup *pos,
2961                                           struct cgroup *cgroup)
2962 {
2963         struct cgroup *next;
2964
2965         WARN_ON_ONCE(!rcu_read_lock_held());
2966
2967         /* if first iteration, pretend we just visited @cgroup */
2968         if (!pos) {
2969                 if (list_empty(&cgroup->children))
2970                         return NULL;
2971                 pos = cgroup;
2972         }
2973
2974         /* visit the first child if exists */
2975         next = list_first_or_null_rcu(&pos->children, struct cgroup, sibling);
2976         if (next)
2977                 return next;
2978
2979         /* no child, visit my or the closest ancestor's next sibling */
2980         do {
2981                 next = list_entry_rcu(pos->sibling.next, struct cgroup,
2982                                       sibling);
2983                 if (&next->sibling != &pos->parent->children)
2984                         return next;
2985
2986                 pos = pos->parent;
2987         } while (pos != cgroup);
2988
2989         return NULL;
2990 }
2991 EXPORT_SYMBOL_GPL(cgroup_next_descendant_pre);
2992
2993 /**
2994  * cgroup_rightmost_descendant - return the rightmost descendant of a cgroup
2995  * @pos: cgroup of interest
2996  *
2997  * Return the rightmost descendant of @pos.  If there's no descendant,
2998  * @pos is returned.  This can be used during pre-order traversal to skip
2999  * subtree of @pos.
3000  */
3001 struct cgroup *cgroup_rightmost_descendant(struct cgroup *pos)
3002 {
3003         struct cgroup *last, *tmp;
3004
3005         WARN_ON_ONCE(!rcu_read_lock_held());
3006
3007         do {
3008                 last = pos;
3009                 /* ->prev isn't RCU safe, walk ->next till the end */
3010                 pos = NULL;
3011                 list_for_each_entry_rcu(tmp, &last->children, sibling)
3012                         pos = tmp;
3013         } while (pos);
3014
3015         return last;
3016 }
3017 EXPORT_SYMBOL_GPL(cgroup_rightmost_descendant);
3018
3019 static struct cgroup *cgroup_leftmost_descendant(struct cgroup *pos)
3020 {
3021         struct cgroup *last;
3022
3023         do {
3024                 last = pos;
3025                 pos = list_first_or_null_rcu(&pos->children, struct cgroup,
3026                                              sibling);
3027         } while (pos);
3028
3029         return last;
3030 }
3031
3032 /**
3033  * cgroup_next_descendant_post - find the next descendant for post-order walk
3034  * @pos: the current position (%NULL to initiate traversal)
3035  * @cgroup: cgroup whose descendants to walk
3036  *
3037  * To be used by cgroup_for_each_descendant_post().  Find the next
3038  * descendant to visit for post-order traversal of @cgroup's descendants.
3039  */
3040 struct cgroup *cgroup_next_descendant_post(struct cgroup *pos,
3041                                            struct cgroup *cgroup)
3042 {
3043         struct cgroup *next;
3044
3045         WARN_ON_ONCE(!rcu_read_lock_held());
3046
3047         /* if first iteration, visit the leftmost descendant */
3048         if (!pos) {
3049                 next = cgroup_leftmost_descendant(cgroup);
3050                 return next != cgroup ? next : NULL;
3051         }
3052
3053         /* if there's an unvisited sibling, visit its leftmost descendant */
3054         next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3055         if (&next->sibling != &pos->parent->children)
3056                 return cgroup_leftmost_descendant(next);
3057
3058         /* no sibling left, visit parent */
3059         next = pos->parent;
3060         return next != cgroup ? next : NULL;
3061 }
3062 EXPORT_SYMBOL_GPL(cgroup_next_descendant_post);
3063
3064 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
3065         __acquires(css_set_lock)
3066 {
3067         /*
3068          * The first time anyone tries to iterate across a cgroup,
3069          * we need to enable the list linking each css_set to its
3070          * tasks, and fix up all existing tasks.
3071          */
3072         if (!use_task_css_set_links)
3073                 cgroup_enable_task_cg_lists();
3074
3075         read_lock(&css_set_lock);
3076         it->cg_link = &cgrp->css_sets;
3077         cgroup_advance_iter(cgrp, it);
3078 }
3079
3080 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
3081                                         struct cgroup_iter *it)
3082 {
3083         struct task_struct *res;
3084         struct list_head *l = it->task;
3085         struct cg_cgroup_link *link;
3086
3087         /* If the iterator cg is NULL, we have no tasks */
3088         if (!it->cg_link)
3089                 return NULL;
3090         res = list_entry(l, struct task_struct, cg_list);
3091         /* Advance iterator to find next entry */
3092         l = l->next;
3093         link = list_entry(it->cg_link, struct cg_cgroup_link, cgrp_link_list);
3094         if (l == &link->cg->tasks) {
3095                 /* We reached the end of this task list - move on to
3096                  * the next cg_cgroup_link */
3097                 cgroup_advance_iter(cgrp, it);
3098         } else {
3099                 it->task = l;
3100         }
3101         return res;
3102 }
3103
3104 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
3105         __releases(css_set_lock)
3106 {
3107         read_unlock(&css_set_lock);
3108 }
3109
3110 static inline int started_after_time(struct task_struct *t1,
3111                                      struct timespec *time,
3112                                      struct task_struct *t2)
3113 {
3114         int start_diff = timespec_compare(&t1->start_time, time);
3115         if (start_diff > 0) {
3116                 return 1;
3117         } else if (start_diff < 0) {
3118                 return 0;
3119         } else {
3120                 /*
3121                  * Arbitrarily, if two processes started at the same
3122                  * time, we'll say that the lower pointer value
3123                  * started first. Note that t2 may have exited by now
3124                  * so this may not be a valid pointer any longer, but
3125                  * that's fine - it still serves to distinguish
3126                  * between two tasks started (effectively) simultaneously.
3127                  */
3128                 return t1 > t2;
3129         }
3130 }
3131
3132 /*
3133  * This function is a callback from heap_insert() and is used to order
3134  * the heap.
3135  * In this case we order the heap in descending task start time.
3136  */
3137 static inline int started_after(void *p1, void *p2)
3138 {
3139         struct task_struct *t1 = p1;
3140         struct task_struct *t2 = p2;
3141         return started_after_time(t1, &t2->start_time, t2);
3142 }
3143
3144 /**
3145  * cgroup_scan_tasks - iterate though all the tasks in a cgroup
3146  * @scan: struct cgroup_scanner containing arguments for the scan
3147  *
3148  * Arguments include pointers to callback functions test_task() and
3149  * process_task().
3150  * Iterate through all the tasks in a cgroup, calling test_task() for each,
3151  * and if it returns true, call process_task() for it also.
3152  * The test_task pointer may be NULL, meaning always true (select all tasks).
3153  * Effectively duplicates cgroup_iter_{start,next,end}()
3154  * but does not lock css_set_lock for the call to process_task().
3155  * The struct cgroup_scanner may be embedded in any structure of the caller's
3156  * creation.
3157  * It is guaranteed that process_task() will act on every task that
3158  * is a member of the cgroup for the duration of this call. This
3159  * function may or may not call process_task() for tasks that exit
3160  * or move to a different cgroup during the call, or are forked or
3161  * move into the cgroup during the call.
3162  *
3163  * Note that test_task() may be called with locks held, and may in some
3164  * situations be called multiple times for the same task, so it should
3165  * be cheap.
3166  * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
3167  * pre-allocated and will be used for heap operations (and its "gt" member will
3168  * be overwritten), else a temporary heap will be used (allocation of which
3169  * may cause this function to fail).
3170  */
3171 int cgroup_scan_tasks(struct cgroup_scanner *scan)
3172 {
3173         int retval, i;
3174         struct cgroup_iter it;
3175         struct task_struct *p, *dropped;
3176         /* Never dereference latest_task, since it's not refcounted */
3177         struct task_struct *latest_task = NULL;
3178         struct ptr_heap tmp_heap;
3179         struct ptr_heap *heap;
3180         struct timespec latest_time = { 0, 0 };
3181
3182         if (scan->heap) {
3183                 /* The caller supplied our heap and pre-allocated its memory */
3184                 heap = scan->heap;
3185                 heap->gt = &started_after;
3186         } else {
3187                 /* We need to allocate our own heap memory */
3188                 heap = &tmp_heap;
3189                 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3190                 if (retval)
3191                         /* cannot allocate the heap */
3192                         return retval;
3193         }
3194
3195  again:
3196         /*
3197          * Scan tasks in the cgroup, using the scanner's "test_task" callback
3198          * to determine which are of interest, and using the scanner's
3199          * "process_task" callback to process any of them that need an update.
3200          * Since we don't want to hold any locks during the task updates,
3201          * gather tasks to be processed in a heap structure.
3202          * The heap is sorted by descending task start time.
3203          * If the statically-sized heap fills up, we overflow tasks that
3204          * started later, and in future iterations only consider tasks that
3205          * started after the latest task in the previous pass. This
3206          * guarantees forward progress and that we don't miss any tasks.
3207          */
3208         heap->size = 0;
3209         cgroup_iter_start(scan->cg, &it);
3210         while ((p = cgroup_iter_next(scan->cg, &it))) {
3211                 /*
3212                  * Only affect tasks that qualify per the caller's callback,
3213                  * if he provided one
3214                  */
3215                 if (scan->test_task && !scan->test_task(p, scan))
3216                         continue;
3217                 /*
3218                  * Only process tasks that started after the last task
3219                  * we processed
3220                  */
3221                 if (!started_after_time(p, &latest_time, latest_task))
3222                         continue;
3223                 dropped = heap_insert(heap, p);
3224                 if (dropped == NULL) {
3225                         /*
3226                          * The new task was inserted; the heap wasn't
3227                          * previously full
3228                          */
3229                         get_task_struct(p);
3230                 } else if (dropped != p) {
3231                         /*
3232                          * The new task was inserted, and pushed out a
3233                          * different task
3234                          */
3235                         get_task_struct(p);
3236                         put_task_struct(dropped);
3237                 }
3238                 /*
3239                  * Else the new task was newer than anything already in
3240                  * the heap and wasn't inserted
3241                  */
3242         }
3243         cgroup_iter_end(scan->cg, &it);
3244
3245         if (heap->size) {
3246                 for (i = 0; i < heap->size; i++) {
3247                         struct task_struct *q = heap->ptrs[i];
3248                         if (i == 0) {
3249                                 latest_time = q->start_time;
3250                                 latest_task = q;
3251                         }
3252                         /* Process the task per the caller's callback */
3253                         scan->process_task(q, scan);
3254                         put_task_struct(q);
3255                 }
3256                 /*
3257                  * If we had to process any tasks at all, scan again
3258                  * in case some of them were in the middle of forking
3259                  * children that didn't get processed.
3260                  * Not the most efficient way to do it, but it avoids
3261                  * having to take callback_mutex in the fork path
3262                  */
3263                 goto again;
3264         }
3265         if (heap == &tmp_heap)
3266                 heap_free(&tmp_heap);
3267         return 0;
3268 }
3269
3270 static void cgroup_transfer_one_task(struct task_struct *task,
3271                                      struct cgroup_scanner *scan)
3272 {
3273         struct cgroup *new_cgroup = scan->data;
3274
3275         mutex_lock(&cgroup_mutex);
3276         cgroup_attach_task(new_cgroup, task, false);
3277         mutex_unlock(&cgroup_mutex);
3278 }
3279
3280 /**
3281  * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3282  * @to: cgroup to which the tasks will be moved
3283  * @from: cgroup in which the tasks currently reside
3284  */
3285 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3286 {
3287         struct cgroup_scanner scan;
3288
3289         scan.cg = from;
3290         scan.test_task = NULL; /* select all tasks in cgroup */
3291         scan.process_task = cgroup_transfer_one_task;
3292         scan.heap = NULL;
3293         scan.data = to;
3294
3295         return cgroup_scan_tasks(&scan);
3296 }
3297
3298 /*
3299  * Stuff for reading the 'tasks'/'procs' files.
3300  *
3301  * Reading this file can return large amounts of data if a cgroup has
3302  * *lots* of attached tasks. So it may need several calls to read(),
3303  * but we cannot guarantee that the information we produce is correct
3304  * unless we produce it entirely atomically.
3305  *
3306  */
3307
3308 /* which pidlist file are we talking about? */
3309 enum cgroup_filetype {
3310         CGROUP_FILE_PROCS,
3311         CGROUP_FILE_TASKS,
3312 };
3313
3314 /*
3315  * A pidlist is a list of pids that virtually represents the contents of one
3316  * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3317  * a pair (one each for procs, tasks) for each pid namespace that's relevant
3318  * to the cgroup.
3319  */
3320 struct cgroup_pidlist {
3321         /*
3322          * used to find which pidlist is wanted. doesn't change as long as
3323          * this particular list stays in the list.
3324         */
3325         struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3326         /* array of xids */
3327         pid_t *list;
3328         /* how many elements the above list has */
3329         int length;
3330         /* how many files are using the current array */
3331         int use_count;
3332         /* each of these stored in a list by its cgroup */
3333         struct list_head links;
3334         /* pointer to the cgroup we belong to, for list removal purposes */
3335         struct cgroup *owner;
3336         /* protects the other fields */
3337         struct rw_semaphore mutex;
3338 };
3339
3340 /*
3341  * The following two functions "fix" the issue where there are more pids
3342  * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3343  * TODO: replace with a kernel-wide solution to this problem
3344  */
3345 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3346 static void *pidlist_allocate(int count)
3347 {
3348         if (PIDLIST_TOO_LARGE(count))
3349                 return vmalloc(count * sizeof(pid_t));
3350         else
3351                 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3352 }
3353 static void pidlist_free(void *p)
3354 {
3355         if (is_vmalloc_addr(p))
3356                 vfree(p);
3357         else
3358                 kfree(p);
3359 }
3360
3361 /*
3362  * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3363  * Returns the number of unique elements.
3364  */
3365 static int pidlist_uniq(pid_t *list, int length)
3366 {
3367         int src, dest = 1;
3368
3369         /*
3370          * we presume the 0th element is unique, so i starts at 1. trivial
3371          * edge cases first; no work needs to be done for either
3372          */
3373         if (length == 0 || length == 1)
3374                 return length;
3375         /* src and dest walk down the list; dest counts unique elements */
3376         for (src = 1; src < length; src++) {
3377                 /* find next unique element */
3378                 while (list[src] == list[src-1]) {
3379                         src++;
3380                         if (src == length)
3381                                 goto after;
3382                 }
3383                 /* dest always points to where the next unique element goes */
3384                 list[dest] = list[src];
3385                 dest++;
3386         }
3387 after:
3388         return dest;
3389 }
3390
3391 static int cmppid(const void *a, const void *b)
3392 {
3393         return *(pid_t *)a - *(pid_t *)b;
3394 }
3395
3396 /*
3397  * find the appropriate pidlist for our purpose (given procs vs tasks)
3398  * returns with the lock on that pidlist already held, and takes care
3399  * of the use count, or returns NULL with no locks held if we're out of
3400  * memory.
3401  */
3402 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3403                                                   enum cgroup_filetype type)
3404 {
3405         struct cgroup_pidlist *l;
3406         /* don't need task_nsproxy() if we're looking at ourself */
3407         struct pid_namespace *ns = task_active_pid_ns(current);
3408
3409         /*
3410          * We can't drop the pidlist_mutex before taking the l->mutex in case
3411          * the last ref-holder is trying to remove l from the list at the same
3412          * time. Holding the pidlist_mutex precludes somebody taking whichever
3413          * list we find out from under us - compare release_pid_array().
3414          */
3415         mutex_lock(&cgrp->pidlist_mutex);
3416         list_for_each_entry(l, &cgrp->pidlists, links) {
3417                 if (l->key.type == type && l->key.ns == ns) {
3418                         /* make sure l doesn't vanish out from under us */
3419                         down_write(&l->mutex);
3420                         mutex_unlock(&cgrp->pidlist_mutex);
3421                         return l;
3422                 }
3423         }
3424         /* entry not found; create a new one */
3425         l = kmalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3426         if (!l) {
3427                 mutex_unlock(&cgrp->pidlist_mutex);
3428                 return l;
3429         }
3430         init_rwsem(&l->mutex);
3431         down_write(&l->mutex);
3432         l->key.type = type;
3433         l->key.ns = get_pid_ns(ns);
3434         l->use_count = 0; /* don't increment here */
3435         l->list = NULL;
3436         l->owner = cgrp;
3437         list_add(&l->links, &cgrp->pidlists);
3438         mutex_unlock(&cgrp->pidlist_mutex);
3439         return l;
3440 }
3441
3442 /*
3443  * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3444  */
3445 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3446                               struct cgroup_pidlist **lp)
3447 {
3448         pid_t *array;
3449         int length;
3450         int pid, n = 0; /* used for populating the array */
3451         struct cgroup_iter it;
3452         struct task_struct *tsk;
3453         struct cgroup_pidlist *l;
3454
3455         /*
3456          * If cgroup gets more users after we read count, we won't have
3457          * enough space - tough.  This race is indistinguishable to the
3458          * caller from the case that the additional cgroup users didn't
3459          * show up until sometime later on.
3460          */
3461         length = cgroup_task_count(cgrp);
3462         array = pidlist_allocate(length);
3463         if (!array)
3464                 return -ENOMEM;
3465         /* now, populate the array */
3466         cgroup_iter_start(cgrp, &it);
3467         while ((tsk = cgroup_iter_next(cgrp, &it))) {
3468                 if (unlikely(n == length))
3469                         break;
3470                 /* get tgid or pid for procs or tasks file respectively */
3471                 if (type == CGROUP_FILE_PROCS)
3472                         pid = task_tgid_vnr(tsk);
3473                 else
3474                         pid = task_pid_vnr(tsk);
3475                 if (pid > 0) /* make sure to only use valid results */
3476                         array[n++] = pid;
3477         }
3478         cgroup_iter_end(cgrp, &it);
3479         length = n;
3480         /* now sort & (if procs) strip out duplicates */
3481         sort(array, length, sizeof(pid_t), cmppid, NULL);
3482         if (type == CGROUP_FILE_PROCS)
3483                 length = pidlist_uniq(array, length);
3484         l = cgroup_pidlist_find(cgrp, type);
3485         if (!l) {
3486                 pidlist_free(array);
3487                 return -ENOMEM;
3488         }
3489         /* store array, freeing old if necessary - lock already held */
3490         pidlist_free(l->list);
3491         l->list = array;
3492         l->length = length;
3493         l->use_count++;
3494         up_write(&l->mutex);
3495         *lp = l;
3496         return 0;
3497 }
3498
3499 /**
3500  * cgroupstats_build - build and fill cgroupstats
3501  * @stats: cgroupstats to fill information into
3502  * @dentry: A dentry entry belonging to the cgroup for which stats have
3503  * been requested.
3504  *
3505  * Build and fill cgroupstats so that taskstats can export it to user
3506  * space.
3507  */
3508 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3509 {
3510         int ret = -EINVAL;
3511         struct cgroup *cgrp;
3512         struct cgroup_iter it;
3513         struct task_struct *tsk;
3514
3515         /*
3516          * Validate dentry by checking the superblock operations,
3517          * and make sure it's a directory.
3518          */
3519         if (dentry->d_sb->s_op != &cgroup_ops ||
3520             !S_ISDIR(dentry->d_inode->i_mode))
3521                  goto err;
3522
3523         ret = 0;
3524         cgrp = dentry->d_fsdata;
3525
3526         cgroup_iter_start(cgrp, &it);
3527         while ((tsk = cgroup_iter_next(cgrp, &it))) {
3528                 switch (tsk->state) {
3529                 case TASK_RUNNING:
3530                         stats->nr_running++;
3531                         break;
3532                 case TASK_INTERRUPTIBLE:
3533                         stats->nr_sleeping++;
3534                         break;
3535                 case TASK_UNINTERRUPTIBLE:
3536                         stats->nr_uninterruptible++;
3537                         break;
3538                 case TASK_STOPPED:
3539                         stats->nr_stopped++;
3540                         break;
3541                 default:
3542                         if (delayacct_is_task_waiting_on_io(tsk))
3543                                 stats->nr_io_wait++;
3544                         break;
3545                 }
3546         }
3547         cgroup_iter_end(cgrp, &it);
3548
3549 err:
3550         return ret;
3551 }
3552
3553
3554 /*
3555  * seq_file methods for the tasks/procs files. The seq_file position is the
3556  * next pid to display; the seq_file iterator is a pointer to the pid
3557  * in the cgroup->l->list array.
3558  */
3559
3560 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3561 {
3562         /*
3563          * Initially we receive a position value that corresponds to
3564          * one more than the last pid shown (or 0 on the first call or
3565          * after a seek to the start). Use a binary-search to find the
3566          * next pid to display, if any
3567          */
3568         struct cgroup_pidlist *l = s->private;
3569         int index = 0, pid = *pos;
3570         int *iter;
3571
3572         down_read(&l->mutex);
3573         if (pid) {
3574                 int end = l->length;
3575
3576                 while (index < end) {
3577                         int mid = (index + end) / 2;
3578                         if (l->list[mid] == pid) {
3579                                 index = mid;
3580                                 break;
3581                         } else if (l->list[mid] <= pid)
3582                                 index = mid + 1;
3583                         else
3584                                 end = mid;
3585                 }
3586         }
3587         /* If we're off the end of the array, we're done */
3588         if (index >= l->length)
3589                 return NULL;
3590         /* Update the abstract position to be the actual pid that we found */
3591         iter = l->list + index;
3592         *pos = *iter;
3593         return iter;
3594 }
3595
3596 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3597 {
3598         struct cgroup_pidlist *l = s->private;
3599         up_read(&l->mutex);
3600 }
3601
3602 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3603 {
3604         struct cgroup_pidlist *l = s->private;
3605         pid_t *p = v;
3606         pid_t *end = l->list + l->length;
3607         /*
3608          * Advance to the next pid in the array. If this goes off the
3609          * end, we're done
3610          */
3611         p++;
3612         if (p >= end) {
3613                 return NULL;
3614         } else {
3615                 *pos = *p;
3616                 return p;
3617         }
3618 }
3619
3620 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3621 {
3622         return seq_printf(s, "%d\n", *(int *)v);
3623 }
3624
3625 /*
3626  * seq_operations functions for iterating on pidlists through seq_file -
3627  * independent of whether it's tasks or procs
3628  */
3629 static const struct seq_operations cgroup_pidlist_seq_operations = {
3630         .start = cgroup_pidlist_start,
3631         .stop = cgroup_pidlist_stop,
3632         .next = cgroup_pidlist_next,
3633         .show = cgroup_pidlist_show,
3634 };
3635
3636 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
3637 {
3638         /*
3639          * the case where we're the last user of this particular pidlist will
3640          * have us remove it from the cgroup's list, which entails taking the
3641          * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3642          * pidlist_mutex, we have to take pidlist_mutex first.
3643          */
3644         mutex_lock(&l->owner->pidlist_mutex);
3645         down_write(&l->mutex);
3646         BUG_ON(!l->use_count);
3647         if (!--l->use_count) {
3648                 /* we're the last user if refcount is 0; remove and free */
3649                 list_del(&l->links);
3650                 mutex_unlock(&l->owner->pidlist_mutex);
3651                 pidlist_free(l->list);
3652                 put_pid_ns(l->key.ns);
3653                 up_write(&l->mutex);
3654                 kfree(l);
3655                 return;
3656         }
3657         mutex_unlock(&l->owner->pidlist_mutex);
3658         up_write(&l->mutex);
3659 }
3660
3661 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
3662 {
3663         struct cgroup_pidlist *l;
3664         if (!(file->f_mode & FMODE_READ))
3665                 return 0;
3666         /*
3667          * the seq_file will only be initialized if the file was opened for
3668          * reading; hence we check if it's not null only in that case.
3669          */
3670         l = ((struct seq_file *)file->private_data)->private;
3671         cgroup_release_pid_array(l);
3672         return seq_release(inode, file);
3673 }
3674
3675 static const struct file_operations cgroup_pidlist_operations = {
3676         .read = seq_read,
3677         .llseek = seq_lseek,
3678         .write = cgroup_file_write,
3679         .release = cgroup_pidlist_release,
3680 };
3681
3682 /*
3683  * The following functions handle opens on a file that displays a pidlist
3684  * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3685  * in the cgroup.
3686  */
3687 /* helper function for the two below it */
3688 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
3689 {
3690         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
3691         struct cgroup_pidlist *l;
3692         int retval;
3693
3694         /* Nothing to do for write-only files */
3695         if (!(file->f_mode & FMODE_READ))
3696                 return 0;
3697
3698         /* have the array populated */
3699         retval = pidlist_array_load(cgrp, type, &l);
3700         if (retval)
3701                 return retval;
3702         /* configure file information */
3703         file->f_op = &cgroup_pidlist_operations;
3704
3705         retval = seq_open(file, &cgroup_pidlist_seq_operations);
3706         if (retval) {
3707                 cgroup_release_pid_array(l);
3708                 return retval;
3709         }
3710         ((struct seq_file *)file->private_data)->private = l;
3711         return 0;
3712 }
3713 static int cgroup_tasks_open(struct inode *unused, struct file *file)
3714 {
3715         return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
3716 }
3717 static int cgroup_procs_open(struct inode *unused, struct file *file)
3718 {
3719         return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
3720 }
3721
3722 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
3723                                             struct cftype *cft)
3724 {
3725         return notify_on_release(cgrp);
3726 }
3727
3728 static int cgroup_write_notify_on_release(struct cgroup *cgrp,
3729                                           struct cftype *cft,
3730                                           u64 val)
3731 {
3732         clear_bit(CGRP_RELEASABLE, &cgrp->flags);
3733         if (val)
3734                 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3735         else
3736                 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3737         return 0;
3738 }
3739
3740 /*
3741  * Unregister event and free resources.
3742  *
3743  * Gets called from workqueue.
3744  */
3745 static void cgroup_event_remove(struct work_struct *work)
3746 {
3747         struct cgroup_event *event = container_of(work, struct cgroup_event,
3748                         remove);
3749         struct cgroup *cgrp = event->cgrp;
3750
3751         remove_wait_queue(event->wqh, &event->wait);
3752
3753         event->cft->unregister_event(cgrp, event->cft, event->eventfd);
3754
3755         /* Notify userspace the event is going away. */
3756         eventfd_signal(event->eventfd, 1);
3757
3758         eventfd_ctx_put(event->eventfd);
3759         kfree(event);
3760         dput(cgrp->dentry);
3761 }
3762
3763 /*
3764  * Gets called on POLLHUP on eventfd when user closes it.
3765  *
3766  * Called with wqh->lock held and interrupts disabled.
3767  */
3768 static int cgroup_event_wake(wait_queue_t *wait, unsigned mode,
3769                 int sync, void *key)
3770 {
3771         struct cgroup_event *event = container_of(wait,
3772                         struct cgroup_event, wait);
3773         struct cgroup *cgrp = event->cgrp;
3774         unsigned long flags = (unsigned long)key;
3775
3776         if (flags & POLLHUP) {
3777                 /*
3778                  * If the event has been detached at cgroup removal, we
3779                  * can simply return knowing the other side will cleanup
3780                  * for us.
3781                  *
3782                  * We can't race against event freeing since the other
3783                  * side will require wqh->lock via remove_wait_queue(),
3784                  * which we hold.
3785                  */
3786                 spin_lock(&cgrp->event_list_lock);
3787                 if (!list_empty(&event->list)) {
3788                         list_del_init(&event->list);
3789                         /*
3790                          * We are in atomic context, but cgroup_event_remove()
3791                          * may sleep, so we have to call it in workqueue.
3792                          */
3793                         schedule_work(&event->remove);
3794                 }
3795                 spin_unlock(&cgrp->event_list_lock);
3796         }
3797
3798         return 0;
3799 }
3800
3801 static void cgroup_event_ptable_queue_proc(struct file *file,
3802                 wait_queue_head_t *wqh, poll_table *pt)
3803 {
3804         struct cgroup_event *event = container_of(pt,
3805                         struct cgroup_event, pt);
3806
3807         event->wqh = wqh;
3808         add_wait_queue(wqh, &event->wait);
3809 }
3810
3811 /*
3812  * Parse input and register new cgroup event handler.
3813  *
3814  * Input must be in format '<event_fd> <control_fd> <args>'.
3815  * Interpretation of args is defined by control file implementation.
3816  */
3817 static int cgroup_write_event_control(struct cgroup *cgrp, struct cftype *cft,
3818                                       const char *buffer)
3819 {
3820         struct cgroup_event *event = NULL;
3821         struct cgroup *cgrp_cfile;
3822         unsigned int efd, cfd;
3823         struct file *efile = NULL;
3824         struct file *cfile = NULL;
3825         char *endp;
3826         int ret;
3827
3828         efd = simple_strtoul(buffer, &endp, 10);
3829         if (*endp != ' ')
3830                 return -EINVAL;
3831         buffer = endp + 1;
3832
3833         cfd = simple_strtoul(buffer, &endp, 10);
3834         if ((*endp != ' ') && (*endp != '\0'))
3835                 return -EINVAL;
3836         buffer = endp + 1;
3837
3838         event = kzalloc(sizeof(*event), GFP_KERNEL);
3839         if (!event)
3840                 return -ENOMEM;
3841         event->cgrp = cgrp;
3842         INIT_LIST_HEAD(&event->list);
3843         init_poll_funcptr(&event->pt, cgroup_event_ptable_queue_proc);
3844         init_waitqueue_func_entry(&event->wait, cgroup_event_wake);
3845         INIT_WORK(&event->remove, cgroup_event_remove);
3846
3847         efile = eventfd_fget(efd);
3848         if (IS_ERR(efile)) {
3849                 ret = PTR_ERR(efile);
3850                 goto fail;
3851         }
3852
3853         event->eventfd = eventfd_ctx_fileget(efile);
3854         if (IS_ERR(event->eventfd)) {
3855                 ret = PTR_ERR(event->eventfd);
3856                 goto fail;
3857         }
3858
3859         cfile = fget(cfd);
3860         if (!cfile) {
3861                 ret = -EBADF;
3862                 goto fail;
3863         }
3864
3865         /* the process need read permission on control file */
3866         /* AV: shouldn't we check that it's been opened for read instead? */
3867         ret = inode_permission(file_inode(cfile), MAY_READ);
3868         if (ret < 0)
3869                 goto fail;
3870
3871         event->cft = __file_cft(cfile);
3872         if (IS_ERR(event->cft)) {
3873                 ret = PTR_ERR(event->cft);
3874                 goto fail;
3875         }
3876
3877         /*
3878          * The file to be monitored must be in the same cgroup as
3879          * cgroup.event_control is.
3880          */
3881         cgrp_cfile = __d_cgrp(cfile->f_dentry->d_parent);
3882         if (cgrp_cfile != cgrp) {
3883                 ret = -EINVAL;
3884                 goto fail;
3885         }
3886
3887         if (!event->cft->register_event || !event->cft->unregister_event) {
3888                 ret = -EINVAL;
3889                 goto fail;
3890         }
3891
3892         ret = event->cft->register_event(cgrp, event->cft,
3893                         event->eventfd, buffer);
3894         if (ret)
3895                 goto fail;
3896
3897         efile->f_op->poll(efile, &event->pt);
3898
3899         /*
3900          * Events should be removed after rmdir of cgroup directory, but before
3901          * destroying subsystem state objects. Let's take reference to cgroup
3902          * directory dentry to do that.
3903          */
3904         dget(cgrp->dentry);
3905
3906         spin_lock(&cgrp->event_list_lock);
3907         list_add(&event->list, &cgrp->event_list);
3908         spin_unlock(&cgrp->event_list_lock);
3909
3910         fput(cfile);
3911         fput(efile);
3912
3913         return 0;
3914
3915 fail:
3916         if (cfile)
3917                 fput(cfile);
3918
3919         if (event && event->eventfd && !IS_ERR(event->eventfd))
3920                 eventfd_ctx_put(event->eventfd);
3921
3922         if (!IS_ERR_OR_NULL(efile))
3923                 fput(efile);
3924
3925         kfree(event);
3926
3927         return ret;
3928 }
3929
3930 static u64 cgroup_clone_children_read(struct cgroup *cgrp,
3931                                     struct cftype *cft)
3932 {
3933         return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3934 }
3935
3936 static int cgroup_clone_children_write(struct cgroup *cgrp,
3937                                      struct cftype *cft,
3938                                      u64 val)
3939 {
3940         if (val)
3941                 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3942         else
3943                 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
3944         return 0;
3945 }
3946
3947 /*
3948  * for the common functions, 'private' gives the type of file
3949  */
3950 /* for hysterical raisins, we can't put this on the older files */
3951 #define CGROUP_FILE_GENERIC_PREFIX "cgroup."
3952 static struct cftype files[] = {
3953         {
3954                 .name = "tasks",
3955                 .open = cgroup_tasks_open,
3956                 .write_u64 = cgroup_tasks_write,
3957                 .release = cgroup_pidlist_release,
3958                 .mode = S_IRUGO | S_IWUSR,
3959         },
3960         {
3961                 .name = CGROUP_FILE_GENERIC_PREFIX "procs",
3962                 .open = cgroup_procs_open,
3963                 .write_u64 = cgroup_procs_write,
3964                 .release = cgroup_pidlist_release,
3965                 .mode = S_IRUGO | S_IWUSR,
3966         },
3967         {
3968                 .name = "notify_on_release",
3969                 .read_u64 = cgroup_read_notify_on_release,
3970                 .write_u64 = cgroup_write_notify_on_release,
3971         },
3972         {
3973                 .name = CGROUP_FILE_GENERIC_PREFIX "event_control",
3974                 .write_string = cgroup_write_event_control,
3975                 .mode = S_IWUGO,
3976         },
3977         {
3978                 .name = "cgroup.clone_children",
3979                 .flags = CFTYPE_INSANE,
3980                 .read_u64 = cgroup_clone_children_read,
3981                 .write_u64 = cgroup_clone_children_write,
3982         },
3983         {
3984                 .name = "cgroup.sane_behavior",
3985                 .flags = CFTYPE_ONLY_ON_ROOT,
3986                 .read_seq_string = cgroup_sane_behavior_show,
3987         },
3988         {
3989                 .name = "release_agent",
3990                 .flags = CFTYPE_ONLY_ON_ROOT,
3991                 .read_seq_string = cgroup_release_agent_show,
3992                 .write_string = cgroup_release_agent_write,
3993                 .max_write_len = PATH_MAX,
3994         },
3995         { }     /* terminate */
3996 };
3997
3998 /**
3999  * cgroup_populate_dir - selectively creation of files in a directory
4000  * @cgrp: target cgroup
4001  * @base_files: true if the base files should be added
4002  * @subsys_mask: mask of the subsystem ids whose files should be added
4003  */
4004 static int cgroup_populate_dir(struct cgroup *cgrp, bool base_files,
4005                                unsigned long subsys_mask)
4006 {
4007         int err;
4008         struct cgroup_subsys *ss;
4009
4010         if (base_files) {
4011                 err = cgroup_addrm_files(cgrp, NULL, files, true);
4012                 if (err < 0)
4013                         return err;
4014         }
4015
4016         /* process cftsets of each subsystem */
4017         for_each_subsys(cgrp->root, ss) {
4018                 struct cftype_set *set;
4019                 if (!test_bit(ss->subsys_id, &subsys_mask))
4020                         continue;
4021
4022                 list_for_each_entry(set, &ss->cftsets, node)
4023                         cgroup_addrm_files(cgrp, ss, set->cfts, true);
4024         }
4025
4026         /* This cgroup is ready now */
4027         for_each_subsys(cgrp->root, ss) {
4028                 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4029                 /*
4030                  * Update id->css pointer and make this css visible from
4031                  * CSS ID functions. This pointer will be dereferened
4032                  * from RCU-read-side without locks.
4033                  */
4034                 if (css->id)
4035                         rcu_assign_pointer(css->id->css, css);
4036         }
4037
4038         return 0;
4039 }
4040
4041 static void css_dput_fn(struct work_struct *work)
4042 {
4043         struct cgroup_subsys_state *css =
4044                 container_of(work, struct cgroup_subsys_state, dput_work);
4045         struct dentry *dentry = css->cgroup->dentry;
4046         struct super_block *sb = dentry->d_sb;
4047
4048         atomic_inc(&sb->s_active);
4049         dput(dentry);
4050         deactivate_super(sb);
4051 }
4052
4053 static void init_cgroup_css(struct cgroup_subsys_state *css,
4054                                struct cgroup_subsys *ss,
4055                                struct cgroup *cgrp)
4056 {
4057         css->cgroup = cgrp;
4058         atomic_set(&css->refcnt, 1);
4059         css->flags = 0;
4060         css->id = NULL;
4061         if (cgrp == dummytop)
4062                 css->flags |= CSS_ROOT;
4063         BUG_ON(cgrp->subsys[ss->subsys_id]);
4064         cgrp->subsys[ss->subsys_id] = css;
4065
4066         /*
4067          * css holds an extra ref to @cgrp->dentry which is put on the last
4068          * css_put().  dput() requires process context, which css_put() may
4069          * be called without.  @css->dput_work will be used to invoke
4070          * dput() asynchronously from css_put().
4071          */
4072         INIT_WORK(&css->dput_work, css_dput_fn);
4073 }
4074
4075 /* invoke ->post_create() on a new CSS and mark it online if successful */
4076 static int online_css(struct cgroup_subsys *ss, struct cgroup *cgrp)
4077 {
4078         int ret = 0;
4079
4080         lockdep_assert_held(&cgroup_mutex);
4081
4082         if (ss->css_online)
4083                 ret = ss->css_online(cgrp);
4084         if (!ret)
4085                 cgrp->subsys[ss->subsys_id]->flags |= CSS_ONLINE;
4086         return ret;
4087 }
4088
4089 /* if the CSS is online, invoke ->pre_destory() on it and mark it offline */
4090 static void offline_css(struct cgroup_subsys *ss, struct cgroup *cgrp)
4091         __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4092 {
4093         struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4094
4095         lockdep_assert_held(&cgroup_mutex);
4096
4097         if (!(css->flags & CSS_ONLINE))
4098                 return;
4099
4100         if (ss->css_offline)
4101                 ss->css_offline(cgrp);
4102
4103         cgrp->subsys[ss->subsys_id]->flags &= ~CSS_ONLINE;
4104 }
4105
4106 /*
4107  * cgroup_create - create a cgroup
4108  * @parent: cgroup that will be parent of the new cgroup
4109  * @dentry: dentry of the new cgroup
4110  * @mode: mode to set on new inode
4111  *
4112  * Must be called with the mutex on the parent inode held
4113  */
4114 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4115                              umode_t mode)
4116 {
4117         struct cgroup *cgrp;
4118         struct cgroup_name *name;
4119         struct cgroupfs_root *root = parent->root;
4120         int err = 0;
4121         struct cgroup_subsys *ss;
4122         struct super_block *sb = root->sb;
4123
4124         /* allocate the cgroup and its ID, 0 is reserved for the root */
4125         cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4126         if (!cgrp)
4127                 return -ENOMEM;
4128
4129         name = cgroup_alloc_name(dentry);
4130         if (!name)
4131                 goto err_free_cgrp;
4132         rcu_assign_pointer(cgrp->name, name);
4133
4134         cgrp->id = ida_simple_get(&root->cgroup_ida, 1, 0, GFP_KERNEL);
4135         if (cgrp->id < 0)
4136                 goto err_free_name;
4137
4138         /*
4139          * Only live parents can have children.  Note that the liveliness
4140          * check isn't strictly necessary because cgroup_mkdir() and
4141          * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4142          * anyway so that locking is contained inside cgroup proper and we
4143          * don't get nasty surprises if we ever grow another caller.
4144          */
4145         if (!cgroup_lock_live_group(parent)) {
4146                 err = -ENODEV;
4147                 goto err_free_id;
4148         }
4149
4150         /* Grab a reference on the superblock so the hierarchy doesn't
4151          * get deleted on unmount if there are child cgroups.  This
4152          * can be done outside cgroup_mutex, since the sb can't
4153          * disappear while someone has an open control file on the
4154          * fs */
4155         atomic_inc(&sb->s_active);
4156
4157         init_cgroup_housekeeping(cgrp);
4158
4159         dentry->d_fsdata = cgrp;
4160         cgrp->dentry = dentry;
4161
4162         cgrp->parent = parent;
4163         cgrp->root = parent->root;
4164
4165         if (notify_on_release(parent))
4166                 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4167
4168         if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4169                 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4170
4171         for_each_subsys(root, ss) {
4172                 struct cgroup_subsys_state *css;
4173
4174                 css = ss->css_alloc(cgrp);
4175                 if (IS_ERR(css)) {
4176                         err = PTR_ERR(css);
4177                         goto err_free_all;
4178                 }
4179                 init_cgroup_css(css, ss, cgrp);
4180                 if (ss->use_id) {
4181                         err = alloc_css_id(ss, parent, cgrp);
4182                         if (err)
4183                                 goto err_free_all;
4184                 }
4185         }
4186
4187         /*
4188          * Create directory.  cgroup_create_file() returns with the new
4189          * directory locked on success so that it can be populated without
4190          * dropping cgroup_mutex.
4191          */
4192         err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4193         if (err < 0)
4194                 goto err_free_all;
4195         lockdep_assert_held(&dentry->d_inode->i_mutex);
4196
4197         /* allocation complete, commit to creation */
4198         list_add_tail(&cgrp->allcg_node, &root->allcg_list);
4199         list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4200         root->number_of_cgroups++;
4201
4202         /* each css holds a ref to the cgroup's dentry */
4203         for_each_subsys(root, ss)
4204                 dget(dentry);
4205
4206         /* hold a ref to the parent's dentry */
4207         dget(parent->dentry);
4208
4209         /* creation succeeded, notify subsystems */
4210         for_each_subsys(root, ss) {
4211                 err = online_css(ss, cgrp);
4212                 if (err)
4213                         goto err_destroy;
4214
4215                 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4216                     parent->parent) {
4217                         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",
4218                                    current->comm, current->pid, ss->name);
4219                         if (!strcmp(ss->name, "memory"))
4220                                 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4221                         ss->warned_broken_hierarchy = true;
4222                 }
4223         }
4224
4225         err = cgroup_populate_dir(cgrp, true, root->subsys_mask);
4226         if (err)
4227                 goto err_destroy;
4228
4229         mutex_unlock(&cgroup_mutex);
4230         mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4231
4232         return 0;
4233
4234 err_free_all:
4235         for_each_subsys(root, ss) {
4236                 if (cgrp->subsys[ss->subsys_id])
4237                         ss->css_free(cgrp);
4238         }
4239         mutex_unlock(&cgroup_mutex);
4240         /* Release the reference count that we took on the superblock */
4241         deactivate_super(sb);
4242 err_free_id:
4243         ida_simple_remove(&root->cgroup_ida, cgrp->id);
4244 err_free_name:
4245         kfree(rcu_dereference_raw(cgrp->name));
4246 err_free_cgrp:
4247         kfree(cgrp);
4248         return err;
4249
4250 err_destroy:
4251         cgroup_destroy_locked(cgrp);
4252         mutex_unlock(&cgroup_mutex);
4253         mutex_unlock(&dentry->d_inode->i_mutex);
4254         return err;
4255 }
4256
4257 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4258 {
4259         struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4260
4261         /* the vfs holds inode->i_mutex already */
4262         return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4263 }
4264
4265 static int cgroup_destroy_locked(struct cgroup *cgrp)
4266         __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4267 {
4268         struct dentry *d = cgrp->dentry;
4269         struct cgroup *parent = cgrp->parent;
4270         struct cgroup_event *event, *tmp;
4271         struct cgroup_subsys *ss;
4272
4273         lockdep_assert_held(&d->d_inode->i_mutex);
4274         lockdep_assert_held(&cgroup_mutex);
4275
4276         if (atomic_read(&cgrp->count) || !list_empty(&cgrp->children))
4277                 return -EBUSY;
4278
4279         /*
4280          * Block new css_tryget() by deactivating refcnt and mark @cgrp
4281          * removed.  This makes future css_tryget() and child creation
4282          * attempts fail thus maintaining the removal conditions verified
4283          * above.
4284          */
4285         for_each_subsys(cgrp->root, ss) {
4286                 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4287
4288                 WARN_ON(atomic_read(&css->refcnt) < 0);
4289                 atomic_add(CSS_DEACT_BIAS, &css->refcnt);
4290         }
4291         set_bit(CGRP_REMOVED, &cgrp->flags);
4292
4293         /* tell subsystems to initate destruction */
4294         for_each_subsys(cgrp->root, ss)
4295                 offline_css(ss, cgrp);
4296
4297         /*
4298          * Put all the base refs.  Each css holds an extra reference to the
4299          * cgroup's dentry and cgroup removal proceeds regardless of css
4300          * refs.  On the last put of each css, whenever that may be, the
4301          * extra dentry ref is put so that dentry destruction happens only
4302          * after all css's are released.
4303          */
4304         for_each_subsys(cgrp->root, ss)
4305                 css_put(cgrp->subsys[ss->subsys_id]);
4306
4307         raw_spin_lock(&release_list_lock);
4308         if (!list_empty(&cgrp->release_list))
4309                 list_del_init(&cgrp->release_list);
4310         raw_spin_unlock(&release_list_lock);
4311
4312         /* delete this cgroup from parent->children */
4313         list_del_rcu(&cgrp->sibling);
4314         list_del_init(&cgrp->allcg_node);
4315
4316         dget(d);
4317         cgroup_d_remove_dir(d);
4318         dput(d);
4319
4320         set_bit(CGRP_RELEASABLE, &parent->flags);
4321         check_for_release(parent);
4322
4323         /*
4324          * Unregister events and notify userspace.
4325          * Notify userspace about cgroup removing only after rmdir of cgroup
4326          * directory to avoid race between userspace and kernelspace.
4327          */
4328         spin_lock(&cgrp->event_list_lock);
4329         list_for_each_entry_safe(event, tmp, &cgrp->event_list, list) {
4330                 list_del_init(&event->list);
4331                 schedule_work(&event->remove);
4332         }
4333         spin_unlock(&cgrp->event_list_lock);
4334
4335         return 0;
4336 }
4337
4338 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4339 {
4340         int ret;
4341
4342         mutex_lock(&cgroup_mutex);
4343         ret = cgroup_destroy_locked(dentry->d_fsdata);
4344         mutex_unlock(&cgroup_mutex);
4345
4346         return ret;
4347 }
4348
4349 static void __init_or_module cgroup_init_cftsets(struct cgroup_subsys *ss)
4350 {
4351         INIT_LIST_HEAD(&ss->cftsets);
4352
4353         /*
4354          * base_cftset is embedded in subsys itself, no need to worry about
4355          * deregistration.
4356          */
4357         if (ss->base_cftypes) {
4358                 ss->base_cftset.cfts = ss->base_cftypes;
4359                 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4360         }
4361 }
4362
4363 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4364 {
4365         struct cgroup_subsys_state *css;
4366
4367         printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4368
4369         mutex_lock(&cgroup_mutex);
4370
4371         /* init base cftset */
4372         cgroup_init_cftsets(ss);
4373
4374         /* Create the top cgroup state for this subsystem */
4375         list_add(&ss->sibling, &rootnode.subsys_list);
4376         ss->root = &rootnode;
4377         css = ss->css_alloc(dummytop);
4378         /* We don't handle early failures gracefully */
4379         BUG_ON(IS_ERR(css));
4380         init_cgroup_css(css, ss, dummytop);
4381
4382         /* Update the init_css_set to contain a subsys
4383          * pointer to this state - since the subsystem is
4384          * newly registered, all tasks and hence the
4385          * init_css_set is in the subsystem's top cgroup. */
4386         init_css_set.subsys[ss->subsys_id] = css;
4387
4388         need_forkexit_callback |= ss->fork || ss->exit;
4389
4390         /* At system boot, before all subsystems have been
4391          * registered, no tasks have been forked, so we don't
4392          * need to invoke fork callbacks here. */
4393         BUG_ON(!list_empty(&init_task.tasks));
4394
4395         BUG_ON(online_css(ss, dummytop));
4396
4397         mutex_unlock(&cgroup_mutex);
4398
4399         /* this function shouldn't be used with modular subsystems, since they
4400          * need to register a subsys_id, among other things */
4401         BUG_ON(ss->module);
4402 }
4403
4404 /**
4405  * cgroup_load_subsys: load and register a modular subsystem at runtime
4406  * @ss: the subsystem to load
4407  *
4408  * This function should be called in a modular subsystem's initcall. If the
4409  * subsystem is built as a module, it will be assigned a new subsys_id and set
4410  * up for use. If the subsystem is built-in anyway, work is delegated to the
4411  * simpler cgroup_init_subsys.
4412  */
4413 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
4414 {
4415         struct cgroup_subsys_state *css;
4416         int i, ret;
4417         struct hlist_node *tmp;
4418         struct css_set *cg;
4419         unsigned long key;
4420
4421         /* check name and function validity */
4422         if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
4423             ss->css_alloc == NULL || ss->css_free == NULL)
4424                 return -EINVAL;
4425
4426         /*
4427          * we don't support callbacks in modular subsystems. this check is
4428          * before the ss->module check for consistency; a subsystem that could
4429          * be a module should still have no callbacks even if the user isn't
4430          * compiling it as one.
4431          */
4432         if (ss->fork || ss->exit)
4433                 return -EINVAL;
4434
4435         /*
4436          * an optionally modular subsystem is built-in: we want to do nothing,
4437          * since cgroup_init_subsys will have already taken care of it.
4438          */
4439         if (ss->module == NULL) {
4440                 /* a sanity check */
4441                 BUG_ON(subsys[ss->subsys_id] != ss);
4442                 return 0;
4443         }
4444
4445         /* init base cftset */
4446         cgroup_init_cftsets(ss);
4447
4448         mutex_lock(&cgroup_mutex);
4449         subsys[ss->subsys_id] = ss;
4450
4451         /*
4452          * no ss->css_alloc seems to need anything important in the ss
4453          * struct, so this can happen first (i.e. before the rootnode
4454          * attachment).
4455          */
4456         css = ss->css_alloc(dummytop);
4457         if (IS_ERR(css)) {
4458                 /* failure case - need to deassign the subsys[] slot. */
4459                 subsys[ss->subsys_id] = NULL;
4460                 mutex_unlock(&cgroup_mutex);
4461                 return PTR_ERR(css);
4462         }
4463
4464         list_add(&ss->sibling, &rootnode.subsys_list);
4465         ss->root = &rootnode;
4466
4467         /* our new subsystem will be attached to the dummy hierarchy. */
4468         init_cgroup_css(css, ss, dummytop);
4469         /* init_idr must be after init_cgroup_css because it sets css->id. */
4470         if (ss->use_id) {
4471                 ret = cgroup_init_idr(ss, css);
4472                 if (ret)
4473                         goto err_unload;
4474         }
4475
4476         /*
4477          * Now we need to entangle the css into the existing css_sets. unlike
4478          * in cgroup_init_subsys, there are now multiple css_sets, so each one
4479          * will need a new pointer to it; done by iterating the css_set_table.
4480          * furthermore, modifying the existing css_sets will corrupt the hash
4481          * table state, so each changed css_set will need its hash recomputed.
4482          * this is all done under the css_set_lock.
4483          */
4484         write_lock(&css_set_lock);
4485         hash_for_each_safe(css_set_table, i, tmp, cg, hlist) {
4486                 /* skip entries that we already rehashed */
4487                 if (cg->subsys[ss->subsys_id])
4488                         continue;
4489                 /* remove existing entry */
4490                 hash_del(&cg->hlist);
4491                 /* set new value */
4492                 cg->subsys[ss->subsys_id] = css;
4493                 /* recompute hash and restore entry */
4494                 key = css_set_hash(cg->subsys);
4495                 hash_add(css_set_table, &cg->hlist, key);
4496         }
4497         write_unlock(&css_set_lock);
4498
4499         ret = online_css(ss, dummytop);
4500         if (ret)
4501                 goto err_unload;
4502
4503         /* success! */
4504         mutex_unlock(&cgroup_mutex);
4505         return 0;
4506
4507 err_unload:
4508         mutex_unlock(&cgroup_mutex);
4509         /* @ss can't be mounted here as try_module_get() would fail */
4510         cgroup_unload_subsys(ss);
4511         return ret;
4512 }
4513 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
4514
4515 /**
4516  * cgroup_unload_subsys: unload a modular subsystem
4517  * @ss: the subsystem to unload
4518  *
4519  * This function should be called in a modular subsystem's exitcall. When this
4520  * function is invoked, the refcount on the subsystem's module will be 0, so
4521  * the subsystem will not be attached to any hierarchy.
4522  */
4523 void cgroup_unload_subsys(struct cgroup_subsys *ss)
4524 {
4525         struct cg_cgroup_link *link;
4526
4527         BUG_ON(ss->module == NULL);
4528
4529         /*
4530          * we shouldn't be called if the subsystem is in use, and the use of
4531          * try_module_get in parse_cgroupfs_options should ensure that it
4532          * doesn't start being used while we're killing it off.
4533          */
4534         BUG_ON(ss->root != &rootnode);
4535
4536         mutex_lock(&cgroup_mutex);
4537
4538         offline_css(ss, dummytop);
4539
4540         if (ss->use_id)
4541                 idr_destroy(&ss->idr);
4542
4543         /* deassign the subsys_id */
4544         subsys[ss->subsys_id] = NULL;
4545
4546         /* remove subsystem from rootnode's list of subsystems */
4547         list_del_init(&ss->sibling);
4548
4549         /*
4550          * disentangle the css from all css_sets attached to the dummytop. as
4551          * in loading, we need to pay our respects to the hashtable gods.
4552          */
4553         write_lock(&css_set_lock);
4554         list_for_each_entry(link, &dummytop->css_sets, cgrp_link_list) {
4555                 struct css_set *cg = link->cg;
4556                 unsigned long key;
4557
4558                 hash_del(&cg->hlist);
4559                 cg->subsys[ss->subsys_id] = NULL;
4560                 key = css_set_hash(cg->subsys);
4561                 hash_add(css_set_table, &cg->hlist, key);
4562         }
4563         write_unlock(&css_set_lock);
4564
4565         /*
4566          * remove subsystem's css from the dummytop and free it - need to
4567          * free before marking as null because ss->css_free needs the
4568          * cgrp->subsys pointer to find their state. note that this also
4569          * takes care of freeing the css_id.
4570          */
4571         ss->css_free(dummytop);
4572         dummytop->subsys[ss->subsys_id] = NULL;
4573
4574         mutex_unlock(&cgroup_mutex);
4575 }
4576 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
4577
4578 /**
4579  * cgroup_init_early - cgroup initialization at system boot
4580  *
4581  * Initialize cgroups at system boot, and initialize any
4582  * subsystems that request early init.
4583  */
4584 int __init cgroup_init_early(void)
4585 {
4586         int i;
4587         atomic_set(&init_css_set.refcount, 1);
4588         INIT_LIST_HEAD(&init_css_set.cg_links);
4589         INIT_LIST_HEAD(&init_css_set.tasks);
4590         INIT_HLIST_NODE(&init_css_set.hlist);
4591         css_set_count = 1;
4592         init_cgroup_root(&rootnode);
4593         root_count = 1;
4594         init_task.cgroups = &init_css_set;
4595
4596         init_css_set_link.cg = &init_css_set;
4597         init_css_set_link.cgrp = dummytop;
4598         list_add(&init_css_set_link.cgrp_link_list,
4599                  &rootnode.top_cgroup.css_sets);
4600         list_add(&init_css_set_link.cg_link_list,
4601                  &init_css_set.cg_links);
4602
4603         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4604                 struct cgroup_subsys *ss = subsys[i];
4605
4606                 /* at bootup time, we don't worry about modular subsystems */
4607                 if (!ss || ss->module)
4608                         continue;
4609
4610                 BUG_ON(!ss->name);
4611                 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
4612                 BUG_ON(!ss->css_alloc);
4613                 BUG_ON(!ss->css_free);
4614                 if (ss->subsys_id != i) {
4615                         printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
4616                                ss->name, ss->subsys_id);
4617                         BUG();
4618                 }
4619
4620                 if (ss->early_init)
4621                         cgroup_init_subsys(ss);
4622         }
4623         return 0;
4624 }
4625
4626 /**
4627  * cgroup_init - cgroup initialization
4628  *
4629  * Register cgroup filesystem and /proc file, and initialize
4630  * any subsystems that didn't request early init.
4631  */
4632 int __init cgroup_init(void)
4633 {
4634         int err;
4635         int i;
4636         unsigned long key;
4637
4638         err = bdi_init(&cgroup_backing_dev_info);
4639         if (err)
4640                 return err;
4641
4642         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4643                 struct cgroup_subsys *ss = subsys[i];
4644
4645                 /* at bootup time, we don't worry about modular subsystems */
4646                 if (!ss || ss->module)
4647                         continue;
4648                 if (!ss->early_init)
4649                         cgroup_init_subsys(ss);
4650                 if (ss->use_id)
4651                         cgroup_init_idr(ss, init_css_set.subsys[ss->subsys_id]);
4652         }
4653
4654         /* Add init_css_set to the hash table */
4655         key = css_set_hash(init_css_set.subsys);
4656         hash_add(css_set_table, &init_css_set.hlist, key);
4657
4658         /* allocate id for the dummy hierarchy */
4659         BUG_ON(cgroup_init_root_id(&rootnode));
4660
4661         cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4662         if (!cgroup_kobj) {
4663                 err = -ENOMEM;
4664                 goto out;
4665         }
4666
4667         err = register_filesystem(&cgroup_fs_type);
4668         if (err < 0) {
4669                 kobject_put(cgroup_kobj);
4670                 goto out;
4671         }
4672
4673         proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4674
4675 out:
4676         if (err)
4677                 bdi_destroy(&cgroup_backing_dev_info);
4678
4679         return err;
4680 }
4681
4682 /*
4683  * proc_cgroup_show()
4684  *  - Print task's cgroup paths into seq_file, one line for each hierarchy
4685  *  - Used for /proc/<pid>/cgroup.
4686  *  - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4687  *    doesn't really matter if tsk->cgroup changes after we read it,
4688  *    and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4689  *    anyway.  No need to check that tsk->cgroup != NULL, thanks to
4690  *    the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4691  *    cgroup to top_cgroup.
4692  */
4693
4694 /* TODO: Use a proper seq_file iterator */
4695 int proc_cgroup_show(struct seq_file *m, void *v)
4696 {
4697         struct pid *pid;
4698         struct task_struct *tsk;
4699         char *buf;
4700         int retval;
4701         struct cgroupfs_root *root;
4702
4703         retval = -ENOMEM;
4704         buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4705         if (!buf)
4706                 goto out;
4707
4708         retval = -ESRCH;
4709         pid = m->private;
4710         tsk = get_pid_task(pid, PIDTYPE_PID);
4711         if (!tsk)
4712                 goto out_free;
4713
4714         retval = 0;
4715
4716         mutex_lock(&cgroup_mutex);
4717
4718         for_each_active_root(root) {
4719                 struct cgroup_subsys *ss;
4720                 struct cgroup *cgrp;
4721                 int count = 0;
4722
4723                 seq_printf(m, "%d:", root->hierarchy_id);
4724                 for_each_subsys(root, ss)
4725                         seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4726                 if (strlen(root->name))
4727                         seq_printf(m, "%sname=%s", count ? "," : "",
4728                                    root->name);
4729                 seq_putc(m, ':');
4730                 cgrp = task_cgroup_from_root(tsk, root);
4731                 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
4732                 if (retval < 0)
4733                         goto out_unlock;
4734                 seq_puts(m, buf);
4735                 seq_putc(m, '\n');
4736         }
4737
4738 out_unlock:
4739         mutex_unlock(&cgroup_mutex);
4740         put_task_struct(tsk);
4741 out_free:
4742         kfree(buf);
4743 out:
4744         return retval;
4745 }
4746
4747 /* Display information about each subsystem and each hierarchy */
4748 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4749 {
4750         int i;
4751
4752         seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4753         /*
4754          * ideally we don't want subsystems moving around while we do this.
4755          * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4756          * subsys/hierarchy state.
4757          */
4758         mutex_lock(&cgroup_mutex);
4759         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4760                 struct cgroup_subsys *ss = subsys[i];
4761                 if (ss == NULL)
4762                         continue;
4763                 seq_printf(m, "%s\t%d\t%d\t%d\n",
4764                            ss->name, ss->root->hierarchy_id,
4765                            ss->root->number_of_cgroups, !ss->disabled);
4766         }
4767         mutex_unlock(&cgroup_mutex);
4768         return 0;
4769 }
4770
4771 static int cgroupstats_open(struct inode *inode, struct file *file)
4772 {
4773         return single_open(file, proc_cgroupstats_show, NULL);
4774 }
4775
4776 static const struct file_operations proc_cgroupstats_operations = {
4777         .open = cgroupstats_open,
4778         .read = seq_read,
4779         .llseek = seq_lseek,
4780         .release = single_release,
4781 };
4782
4783 /**
4784  * cgroup_fork - attach newly forked task to its parents cgroup.
4785  * @child: pointer to task_struct of forking parent process.
4786  *
4787  * Description: A task inherits its parent's cgroup at fork().
4788  *
4789  * A pointer to the shared css_set was automatically copied in
4790  * fork.c by dup_task_struct().  However, we ignore that copy, since
4791  * it was not made under the protection of RCU or cgroup_mutex, so
4792  * might no longer be a valid cgroup pointer.  cgroup_attach_task() might
4793  * have already changed current->cgroups, allowing the previously
4794  * referenced cgroup group to be removed and freed.
4795  *
4796  * At the point that cgroup_fork() is called, 'current' is the parent
4797  * task, and the passed argument 'child' points to the child task.
4798  */
4799 void cgroup_fork(struct task_struct *child)
4800 {
4801         task_lock(current);
4802         child->cgroups = current->cgroups;
4803         get_css_set(child->cgroups);
4804         task_unlock(current);
4805         INIT_LIST_HEAD(&child->cg_list);
4806 }
4807
4808 /**
4809  * cgroup_post_fork - called on a new task after adding it to the task list
4810  * @child: the task in question
4811  *
4812  * Adds the task to the list running through its css_set if necessary and
4813  * call the subsystem fork() callbacks.  Has to be after the task is
4814  * visible on the task list in case we race with the first call to
4815  * cgroup_iter_start() - to guarantee that the new task ends up on its
4816  * list.
4817  */
4818 void cgroup_post_fork(struct task_struct *child)
4819 {
4820         int i;
4821
4822         /*
4823          * use_task_css_set_links is set to 1 before we walk the tasklist
4824          * under the tasklist_lock and we read it here after we added the child
4825          * to the tasklist under the tasklist_lock as well. If the child wasn't
4826          * yet in the tasklist when we walked through it from
4827          * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4828          * should be visible now due to the paired locking and barriers implied
4829          * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4830          * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4831          * lock on fork.
4832          */
4833         if (use_task_css_set_links) {
4834                 write_lock(&css_set_lock);
4835                 task_lock(child);
4836                 if (list_empty(&child->cg_list))
4837                         list_add(&child->cg_list, &child->cgroups->tasks);
4838                 task_unlock(child);
4839                 write_unlock(&css_set_lock);
4840         }
4841
4842         /*
4843          * Call ss->fork().  This must happen after @child is linked on
4844          * css_set; otherwise, @child might change state between ->fork()
4845          * and addition to css_set.
4846          */
4847         if (need_forkexit_callback) {
4848                 /*
4849                  * fork/exit callbacks are supported only for builtin
4850                  * subsystems, and the builtin section of the subsys
4851                  * array is immutable, so we don't need to lock the
4852                  * subsys array here. On the other hand, modular section
4853                  * of the array can be freed at module unload, so we
4854                  * can't touch that.
4855                  */
4856                 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
4857                         struct cgroup_subsys *ss = subsys[i];
4858
4859                         if (ss->fork)
4860                                 ss->fork(child);
4861                 }
4862         }
4863 }
4864
4865 /**
4866  * cgroup_exit - detach cgroup from exiting task
4867  * @tsk: pointer to task_struct of exiting process
4868  * @run_callback: run exit callbacks?
4869  *
4870  * Description: Detach cgroup from @tsk and release it.
4871  *
4872  * Note that cgroups marked notify_on_release force every task in
4873  * them to take the global cgroup_mutex mutex when exiting.
4874  * This could impact scaling on very large systems.  Be reluctant to
4875  * use notify_on_release cgroups where very high task exit scaling
4876  * is required on large systems.
4877  *
4878  * the_top_cgroup_hack:
4879  *
4880  *    Set the exiting tasks cgroup to the root cgroup (top_cgroup).
4881  *
4882  *    We call cgroup_exit() while the task is still competent to
4883  *    handle notify_on_release(), then leave the task attached to the
4884  *    root cgroup in each hierarchy for the remainder of its exit.
4885  *
4886  *    To do this properly, we would increment the reference count on
4887  *    top_cgroup, and near the very end of the kernel/exit.c do_exit()
4888  *    code we would add a second cgroup function call, to drop that
4889  *    reference.  This would just create an unnecessary hot spot on
4890  *    the top_cgroup reference count, to no avail.
4891  *
4892  *    Normally, holding a reference to a cgroup without bumping its
4893  *    count is unsafe.   The cgroup could go away, or someone could
4894  *    attach us to a different cgroup, decrementing the count on
4895  *    the first cgroup that we never incremented.  But in this case,
4896  *    top_cgroup isn't going away, and either task has PF_EXITING set,
4897  *    which wards off any cgroup_attach_task() attempts, or task is a failed
4898  *    fork, never visible to cgroup_attach_task.
4899  */
4900 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
4901 {
4902         struct css_set *cg;
4903         int i;
4904
4905         /*
4906          * Unlink from the css_set task list if necessary.
4907          * Optimistically check cg_list before taking
4908          * css_set_lock
4909          */
4910         if (!list_empty(&tsk->cg_list)) {
4911                 write_lock(&css_set_lock);
4912                 if (!list_empty(&tsk->cg_list))
4913                         list_del_init(&tsk->cg_list);
4914                 write_unlock(&css_set_lock);
4915         }
4916
4917         /* Reassign the task to the init_css_set. */
4918         task_lock(tsk);
4919         cg = tsk->cgroups;
4920         tsk->cgroups = &init_css_set;
4921
4922         if (run_callbacks && need_forkexit_callback) {
4923                 /*
4924                  * fork/exit callbacks are supported only for builtin
4925                  * subsystems, see cgroup_post_fork() for details.
4926                  */
4927                 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
4928                         struct cgroup_subsys *ss = subsys[i];
4929
4930                         if (ss->exit) {
4931                                 struct cgroup *old_cgrp =
4932                                         rcu_dereference_raw(cg->subsys[i])->cgroup;
4933                                 struct cgroup *cgrp = task_cgroup(tsk, i);
4934                                 ss->exit(cgrp, old_cgrp, tsk);
4935                         }
4936                 }
4937         }
4938         task_unlock(tsk);
4939
4940         put_css_set_taskexit(cg);
4941 }
4942
4943 static void check_for_release(struct cgroup *cgrp)
4944 {
4945         /* All of these checks rely on RCU to keep the cgroup
4946          * structure alive */
4947         if (cgroup_is_releasable(cgrp) &&
4948             !atomic_read(&cgrp->count) && list_empty(&cgrp->children)) {
4949                 /*
4950                  * Control Group is currently removeable. If it's not
4951                  * already queued for a userspace notification, queue
4952                  * it now
4953                  */
4954                 int need_schedule_work = 0;
4955
4956                 raw_spin_lock(&release_list_lock);
4957                 if (!cgroup_is_removed(cgrp) &&
4958                     list_empty(&cgrp->release_list)) {
4959                         list_add(&cgrp->release_list, &release_list);
4960                         need_schedule_work = 1;
4961                 }
4962                 raw_spin_unlock(&release_list_lock);
4963                 if (need_schedule_work)
4964                         schedule_work(&release_agent_work);
4965         }
4966 }
4967
4968 /* Caller must verify that the css is not for root cgroup */
4969 bool __css_tryget(struct cgroup_subsys_state *css)
4970 {
4971         while (true) {
4972                 int t, v;
4973
4974                 v = css_refcnt(css);
4975                 t = atomic_cmpxchg(&css->refcnt, v, v + 1);
4976                 if (likely(t == v))
4977                         return true;
4978                 else if (t < 0)
4979                         return false;
4980                 cpu_relax();
4981         }
4982 }
4983 EXPORT_SYMBOL_GPL(__css_tryget);
4984
4985 /* Caller must verify that the css is not for root cgroup */
4986 void __css_put(struct cgroup_subsys_state *css)
4987 {
4988         int v;
4989
4990         v = css_unbias_refcnt(atomic_dec_return(&css->refcnt));
4991         if (v == 0)
4992                 schedule_work(&css->dput_work);
4993 }
4994 EXPORT_SYMBOL_GPL(__css_put);
4995
4996 /*
4997  * Notify userspace when a cgroup is released, by running the
4998  * configured release agent with the name of the cgroup (path
4999  * relative to the root of cgroup file system) as the argument.
5000  *
5001  * Most likely, this user command will try to rmdir this cgroup.
5002  *
5003  * This races with the possibility that some other task will be
5004  * attached to this cgroup before it is removed, or that some other
5005  * user task will 'mkdir' a child cgroup of this cgroup.  That's ok.
5006  * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5007  * unused, and this cgroup will be reprieved from its death sentence,
5008  * to continue to serve a useful existence.  Next time it's released,
5009  * we will get notified again, if it still has 'notify_on_release' set.
5010  *
5011  * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5012  * means only wait until the task is successfully execve()'d.  The
5013  * separate release agent task is forked by call_usermodehelper(),
5014  * then control in this thread returns here, without waiting for the
5015  * release agent task.  We don't bother to wait because the caller of
5016  * this routine has no use for the exit status of the release agent
5017  * task, so no sense holding our caller up for that.
5018  */
5019 static void cgroup_release_agent(struct work_struct *work)
5020 {
5021         BUG_ON(work != &release_agent_work);
5022         mutex_lock(&cgroup_mutex);
5023         raw_spin_lock(&release_list_lock);
5024         while (!list_empty(&release_list)) {
5025                 char *argv[3], *envp[3];
5026                 int i;
5027                 char *pathbuf = NULL, *agentbuf = NULL;
5028                 struct cgroup *cgrp = list_entry(release_list.next,
5029                                                     struct cgroup,
5030                                                     release_list);
5031                 list_del_init(&cgrp->release_list);
5032                 raw_spin_unlock(&release_list_lock);
5033                 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5034                 if (!pathbuf)
5035                         goto continue_free;
5036                 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
5037                         goto continue_free;
5038                 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5039                 if (!agentbuf)
5040                         goto continue_free;
5041
5042                 i = 0;
5043                 argv[i++] = agentbuf;
5044                 argv[i++] = pathbuf;
5045                 argv[i] = NULL;
5046
5047                 i = 0;
5048                 /* minimal command environment */
5049                 envp[i++] = "HOME=/";
5050                 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5051                 envp[i] = NULL;
5052
5053                 /* Drop the lock while we invoke the usermode helper,
5054                  * since the exec could involve hitting disk and hence
5055                  * be a slow process */
5056                 mutex_unlock(&cgroup_mutex);
5057                 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5058                 mutex_lock(&cgroup_mutex);
5059  continue_free:
5060                 kfree(pathbuf);
5061                 kfree(agentbuf);
5062                 raw_spin_lock(&release_list_lock);
5063         }
5064         raw_spin_unlock(&release_list_lock);
5065         mutex_unlock(&cgroup_mutex);
5066 }
5067
5068 static int __init cgroup_disable(char *str)
5069 {
5070         int i;
5071         char *token;
5072
5073         while ((token = strsep(&str, ",")) != NULL) {
5074                 if (!*token)
5075                         continue;
5076                 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
5077                         struct cgroup_subsys *ss = subsys[i];
5078
5079                         /*
5080                          * cgroup_disable, being at boot time, can't
5081                          * know about module subsystems, so we don't
5082                          * worry about them.
5083                          */
5084                         if (!ss || ss->module)
5085                                 continue;
5086
5087                         if (!strcmp(token, ss->name)) {
5088                                 ss->disabled = 1;
5089                                 printk(KERN_INFO "Disabling %s control group"
5090                                         " subsystem\n", ss->name);
5091                                 break;
5092                         }
5093                 }
5094         }
5095         return 1;
5096 }
5097 __setup("cgroup_disable=", cgroup_disable);
5098
5099 /*
5100  * Functons for CSS ID.
5101  */
5102
5103 /*
5104  *To get ID other than 0, this should be called when !cgroup_is_removed().
5105  */
5106 unsigned short css_id(struct cgroup_subsys_state *css)
5107 {
5108         struct css_id *cssid;
5109
5110         /*
5111          * This css_id() can return correct value when somone has refcnt
5112          * on this or this is under rcu_read_lock(). Once css->id is allocated,
5113          * it's unchanged until freed.
5114          */
5115         cssid = rcu_dereference_check(css->id, css_refcnt(css));
5116
5117         if (cssid)
5118                 return cssid->id;
5119         return 0;
5120 }
5121 EXPORT_SYMBOL_GPL(css_id);
5122
5123 unsigned short css_depth(struct cgroup_subsys_state *css)
5124 {
5125         struct css_id *cssid;
5126
5127         cssid = rcu_dereference_check(css->id, css_refcnt(css));
5128
5129         if (cssid)
5130                 return cssid->depth;
5131         return 0;
5132 }
5133 EXPORT_SYMBOL_GPL(css_depth);
5134
5135 /**
5136  *  css_is_ancestor - test "root" css is an ancestor of "child"
5137  * @child: the css to be tested.
5138  * @root: the css supporsed to be an ancestor of the child.
5139  *
5140  * Returns true if "root" is an ancestor of "child" in its hierarchy. Because
5141  * this function reads css->id, the caller must hold rcu_read_lock().
5142  * But, considering usual usage, the csses should be valid objects after test.
5143  * Assuming that the caller will do some action to the child if this returns
5144  * returns true, the caller must take "child";s reference count.
5145  * If "child" is valid object and this returns true, "root" is valid, too.
5146  */
5147
5148 bool css_is_ancestor(struct cgroup_subsys_state *child,
5149                     const struct cgroup_subsys_state *root)
5150 {
5151         struct css_id *child_id;
5152         struct css_id *root_id;
5153
5154         child_id  = rcu_dereference(child->id);
5155         if (!child_id)
5156                 return false;
5157         root_id = rcu_dereference(root->id);
5158         if (!root_id)
5159                 return false;
5160         if (child_id->depth < root_id->depth)
5161                 return false;
5162         if (child_id->stack[root_id->depth] != root_id->id)
5163                 return false;
5164         return true;
5165 }
5166
5167 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
5168 {
5169         struct css_id *id = css->id;
5170         /* When this is called before css_id initialization, id can be NULL */
5171         if (!id)
5172                 return;
5173
5174         BUG_ON(!ss->use_id);
5175
5176         rcu_assign_pointer(id->css, NULL);
5177         rcu_assign_pointer(css->id, NULL);
5178         spin_lock(&ss->id_lock);
5179         idr_remove(&ss->idr, id->id);
5180         spin_unlock(&ss->id_lock);
5181         kfree_rcu(id, rcu_head);
5182 }
5183 EXPORT_SYMBOL_GPL(free_css_id);
5184
5185 /*
5186  * This is called by init or create(). Then, calls to this function are
5187  * always serialized (By cgroup_mutex() at create()).
5188  */
5189
5190 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
5191 {
5192         struct css_id *newid;
5193         int ret, size;
5194
5195         BUG_ON(!ss->use_id);
5196
5197         size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
5198         newid = kzalloc(size, GFP_KERNEL);
5199         if (!newid)
5200                 return ERR_PTR(-ENOMEM);
5201
5202         idr_preload(GFP_KERNEL);
5203         spin_lock(&ss->id_lock);
5204         /* Don't use 0. allocates an ID of 1-65535 */
5205         ret = idr_alloc(&ss->idr, newid, 1, CSS_ID_MAX + 1, GFP_NOWAIT);
5206         spin_unlock(&ss->id_lock);
5207         idr_preload_end();
5208
5209         /* Returns error when there are no free spaces for new ID.*/
5210         if (ret < 0)
5211                 goto err_out;
5212
5213         newid->id = ret;
5214         newid->depth = depth;
5215         return newid;
5216 err_out:
5217         kfree(newid);
5218         return ERR_PTR(ret);
5219
5220 }
5221
5222 static int __init_or_module cgroup_init_idr(struct cgroup_subsys *ss,
5223                                             struct cgroup_subsys_state *rootcss)
5224 {
5225         struct css_id *newid;
5226
5227         spin_lock_init(&ss->id_lock);
5228         idr_init(&ss->idr);
5229
5230         newid = get_new_cssid(ss, 0);
5231         if (IS_ERR(newid))
5232                 return PTR_ERR(newid);
5233
5234         newid->stack[0] = newid->id;
5235         newid->css = rootcss;
5236         rootcss->id = newid;
5237         return 0;
5238 }
5239
5240 static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
5241                         struct cgroup *child)
5242 {
5243         int subsys_id, i, depth = 0;
5244         struct cgroup_subsys_state *parent_css, *child_css;
5245         struct css_id *child_id, *parent_id;
5246
5247         subsys_id = ss->subsys_id;
5248         parent_css = parent->subsys[subsys_id];
5249         child_css = child->subsys[subsys_id];
5250         parent_id = parent_css->id;
5251         depth = parent_id->depth + 1;
5252
5253         child_id = get_new_cssid(ss, depth);
5254         if (IS_ERR(child_id))
5255                 return PTR_ERR(child_id);
5256
5257         for (i = 0; i < depth; i++)
5258                 child_id->stack[i] = parent_id->stack[i];
5259         child_id->stack[depth] = child_id->id;
5260         /*
5261          * child_id->css pointer will be set after this cgroup is available
5262          * see cgroup_populate_dir()
5263          */
5264         rcu_assign_pointer(child_css->id, child_id);
5265
5266         return 0;
5267 }
5268
5269 /**
5270  * css_lookup - lookup css by id
5271  * @ss: cgroup subsys to be looked into.
5272  * @id: the id
5273  *
5274  * Returns pointer to cgroup_subsys_state if there is valid one with id.
5275  * NULL if not. Should be called under rcu_read_lock()
5276  */
5277 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
5278 {
5279         struct css_id *cssid = NULL;
5280
5281         BUG_ON(!ss->use_id);
5282         cssid = idr_find(&ss->idr, id);
5283
5284         if (unlikely(!cssid))
5285                 return NULL;
5286
5287         return rcu_dereference(cssid->css);
5288 }
5289 EXPORT_SYMBOL_GPL(css_lookup);
5290
5291 /*
5292  * get corresponding css from file open on cgroupfs directory
5293  */
5294 struct cgroup_subsys_state *cgroup_css_from_dir(struct file *f, int id)
5295 {
5296         struct cgroup *cgrp;
5297         struct inode *inode;
5298         struct cgroup_subsys_state *css;
5299
5300         inode = file_inode(f);
5301         /* check in cgroup filesystem dir */
5302         if (inode->i_op != &cgroup_dir_inode_operations)
5303                 return ERR_PTR(-EBADF);
5304
5305         if (id < 0 || id >= CGROUP_SUBSYS_COUNT)
5306                 return ERR_PTR(-EINVAL);
5307
5308         /* get cgroup */
5309         cgrp = __d_cgrp(f->f_dentry);
5310         css = cgrp->subsys[id];
5311         return css ? css : ERR_PTR(-ENOENT);
5312 }
5313
5314 #ifdef CONFIG_CGROUP_DEBUG
5315 static struct cgroup_subsys_state *debug_css_alloc(struct cgroup *cont)
5316 {
5317         struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5318
5319         if (!css)
5320                 return ERR_PTR(-ENOMEM);
5321
5322         return css;
5323 }
5324
5325 static void debug_css_free(struct cgroup *cont)
5326 {
5327         kfree(cont->subsys[debug_subsys_id]);
5328 }
5329
5330 static u64 cgroup_refcount_read(struct cgroup *cont, struct cftype *cft)
5331 {
5332         return atomic_read(&cont->count);
5333 }
5334
5335 static u64 debug_taskcount_read(struct cgroup *cont, struct cftype *cft)
5336 {
5337         return cgroup_task_count(cont);
5338 }
5339
5340 static u64 current_css_set_read(struct cgroup *cont, struct cftype *cft)
5341 {
5342         return (u64)(unsigned long)current->cgroups;
5343 }
5344
5345 static u64 current_css_set_refcount_read(struct cgroup *cont,
5346                                            struct cftype *cft)
5347 {
5348         u64 count;
5349
5350         rcu_read_lock();
5351         count = atomic_read(&current->cgroups->refcount);
5352         rcu_read_unlock();
5353         return count;
5354 }
5355
5356 static int current_css_set_cg_links_read(struct cgroup *cont,
5357                                          struct cftype *cft,
5358                                          struct seq_file *seq)
5359 {
5360         struct cg_cgroup_link *link;
5361         struct css_set *cg;
5362
5363         read_lock(&css_set_lock);
5364         rcu_read_lock();
5365         cg = rcu_dereference(current->cgroups);
5366         list_for_each_entry(link, &cg->cg_links, cg_link_list) {
5367                 struct cgroup *c = link->cgrp;
5368                 const char *name;
5369
5370                 if (c->dentry)
5371                         name = c->dentry->d_name.name;
5372                 else
5373                         name = "?";
5374                 seq_printf(seq, "Root %d group %s\n",
5375                            c->root->hierarchy_id, name);
5376         }
5377         rcu_read_unlock();
5378         read_unlock(&css_set_lock);
5379         return 0;
5380 }
5381
5382 #define MAX_TASKS_SHOWN_PER_CSS 25
5383 static int cgroup_css_links_read(struct cgroup *cont,
5384                                  struct cftype *cft,
5385                                  struct seq_file *seq)
5386 {
5387         struct cg_cgroup_link *link;
5388
5389         read_lock(&css_set_lock);
5390         list_for_each_entry(link, &cont->css_sets, cgrp_link_list) {
5391                 struct css_set *cg = link->cg;
5392                 struct task_struct *task;
5393                 int count = 0;
5394                 seq_printf(seq, "css_set %p\n", cg);
5395                 list_for_each_entry(task, &cg->tasks, cg_list) {
5396                         if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5397                                 seq_puts(seq, "  ...\n");
5398                                 break;
5399                         } else {
5400                                 seq_printf(seq, "  task %d\n",
5401                                            task_pid_vnr(task));
5402                         }
5403                 }
5404         }
5405         read_unlock(&css_set_lock);
5406         return 0;
5407 }
5408
5409 static u64 releasable_read(struct cgroup *cgrp, struct cftype *cft)
5410 {
5411         return test_bit(CGRP_RELEASABLE, &cgrp->flags);
5412 }
5413
5414 static struct cftype debug_files[] =  {
5415         {
5416                 .name = "cgroup_refcount",
5417                 .read_u64 = cgroup_refcount_read,
5418         },
5419         {
5420                 .name = "taskcount",
5421                 .read_u64 = debug_taskcount_read,
5422         },
5423
5424         {
5425                 .name = "current_css_set",
5426                 .read_u64 = current_css_set_read,
5427         },
5428
5429         {
5430                 .name = "current_css_set_refcount",
5431                 .read_u64 = current_css_set_refcount_read,
5432         },
5433
5434         {
5435                 .name = "current_css_set_cg_links",
5436                 .read_seq_string = current_css_set_cg_links_read,
5437         },
5438
5439         {
5440                 .name = "cgroup_css_links",
5441                 .read_seq_string = cgroup_css_links_read,
5442         },
5443
5444         {
5445                 .name = "releasable",
5446                 .read_u64 = releasable_read,
5447         },
5448
5449         { }     /* terminate */
5450 };
5451
5452 struct cgroup_subsys debug_subsys = {
5453         .name = "debug",
5454         .css_alloc = debug_css_alloc,
5455         .css_free = debug_css_free,
5456         .subsys_id = debug_subsys_id,
5457         .base_cftypes = debug_files,
5458 };
5459 #endif /* CONFIG_CGROUP_DEBUG */