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