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