Merge branch 'for-3.14-fixes' into for-3.15
[pandora-kernel.git] / kernel / cgroup.c
1 /*
2  *  Generic process-grouping system.
3  *
4  *  Based originally on the cpuset system, extracted by Paul Menage
5  *  Copyright (C) 2006 Google, Inc
6  *
7  *  Notifications support
8  *  Copyright (C) 2009 Nokia Corporation
9  *  Author: Kirill A. Shutemov
10  *
11  *  Copyright notices from the original cpuset code:
12  *  --------------------------------------------------
13  *  Copyright (C) 2003 BULL SA.
14  *  Copyright (C) 2004-2006 Silicon Graphics, Inc.
15  *
16  *  Portions derived from Patrick Mochel's sysfs code.
17  *  sysfs is Copyright (c) 2001-3 Patrick Mochel
18  *
19  *  2003-10-10 Written by Simon Derr.
20  *  2003-10-22 Updates by Stephen Hemminger.
21  *  2004 May-July Rework by Paul Jackson.
22  *  ---------------------------------------------------
23  *
24  *  This file is subject to the terms and conditions of the GNU General Public
25  *  License.  See the file COPYING in the main directory of the Linux
26  *  distribution for more details.
27  */
28
29 #include <linux/cgroup.h>
30 #include <linux/cred.h>
31 #include <linux/ctype.h>
32 #include <linux/errno.h>
33 #include <linux/init_task.h>
34 #include <linux/kernel.h>
35 #include <linux/list.h>
36 #include <linux/mm.h>
37 #include <linux/mutex.h>
38 #include <linux/mount.h>
39 #include <linux/pagemap.h>
40 #include <linux/proc_fs.h>
41 #include <linux/rcupdate.h>
42 #include <linux/sched.h>
43 #include <linux/backing-dev.h>
44 #include <linux/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                 ret = idr_alloc(&root->cgroup_idr, root_cgrp, 0, 1, GFP_KERNEL);
1498                 if (ret < 0)
1499                         goto unlock_drop;
1500                 root_cgrp->id = ret;
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         /* add/rm files for all cgroups created before */
2691         css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
2692                 struct cgroup *cgrp = css->cgroup;
2693
2694                 if (cgroup_is_dead(cgrp))
2695                         continue;
2696
2697                 inode = cgrp->dentry->d_inode;
2698                 dget(cgrp->dentry);
2699                 dput(prev);
2700                 prev = cgrp->dentry;
2701
2702                 mutex_unlock(&cgroup_mutex);
2703                 mutex_lock(&inode->i_mutex);
2704                 mutex_lock(&cgroup_mutex);
2705                 if (cgrp->serial_nr < update_before && !cgroup_is_dead(cgrp))
2706                         ret = cgroup_addrm_files(cgrp, cfts, is_add);
2707                 mutex_unlock(&inode->i_mutex);
2708                 if (ret)
2709                         break;
2710         }
2711         mutex_unlock(&cgroup_mutex);
2712         dput(prev);
2713         deactivate_super(sb);
2714         return ret;
2715 }
2716
2717 /**
2718  * cgroup_add_cftypes - add an array of cftypes to a subsystem
2719  * @ss: target cgroup subsystem
2720  * @cfts: zero-length name terminated array of cftypes
2721  *
2722  * Register @cfts to @ss.  Files described by @cfts are created for all
2723  * existing cgroups to which @ss is attached and all future cgroups will
2724  * have them too.  This function can be called anytime whether @ss is
2725  * attached or not.
2726  *
2727  * Returns 0 on successful registration, -errno on failure.  Note that this
2728  * function currently returns 0 as long as @cfts registration is successful
2729  * even if some file creation attempts on existing cgroups fail.
2730  */
2731 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2732 {
2733         struct cftype_set *set;
2734         struct cftype *cft;
2735         int ret;
2736
2737         set = kzalloc(sizeof(*set), GFP_KERNEL);
2738         if (!set)
2739                 return -ENOMEM;
2740
2741         for (cft = cfts; cft->name[0] != '\0'; cft++)
2742                 cft->ss = ss;
2743
2744         cgroup_cfts_prepare();
2745         set->cfts = cfts;
2746         list_add_tail(&set->node, &ss->cftsets);
2747         ret = cgroup_cfts_commit(cfts, true);
2748         if (ret)
2749                 cgroup_rm_cftypes(cfts);
2750         return ret;
2751 }
2752 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2753
2754 /**
2755  * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2756  * @cfts: zero-length name terminated array of cftypes
2757  *
2758  * Unregister @cfts.  Files described by @cfts are removed from all
2759  * existing cgroups and all future cgroups won't have them either.  This
2760  * function can be called anytime whether @cfts' subsys is attached or not.
2761  *
2762  * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2763  * registered.
2764  */
2765 int cgroup_rm_cftypes(struct cftype *cfts)
2766 {
2767         struct cftype_set *set;
2768
2769         if (!cfts || !cfts[0].ss)
2770                 return -ENOENT;
2771
2772         cgroup_cfts_prepare();
2773
2774         list_for_each_entry(set, &cfts[0].ss->cftsets, node) {
2775                 if (set->cfts == cfts) {
2776                         list_del(&set->node);
2777                         kfree(set);
2778                         cgroup_cfts_commit(cfts, false);
2779                         return 0;
2780                 }
2781         }
2782
2783         cgroup_cfts_commit(NULL, false);
2784         return -ENOENT;
2785 }
2786
2787 /**
2788  * cgroup_task_count - count the number of tasks in a cgroup.
2789  * @cgrp: the cgroup in question
2790  *
2791  * Return the number of tasks in the cgroup.
2792  */
2793 int cgroup_task_count(const struct cgroup *cgrp)
2794 {
2795         int count = 0;
2796         struct cgrp_cset_link *link;
2797
2798         read_lock(&css_set_lock);
2799         list_for_each_entry(link, &cgrp->cset_links, cset_link)
2800                 count += atomic_read(&link->cset->refcount);
2801         read_unlock(&css_set_lock);
2802         return count;
2803 }
2804
2805 /*
2806  * To reduce the fork() overhead for systems that are not actually using
2807  * their cgroups capability, we don't maintain the lists running through
2808  * each css_set to its tasks until we see the list actually used - in other
2809  * words after the first call to css_task_iter_start().
2810  */
2811 static void cgroup_enable_task_cg_lists(void)
2812 {
2813         struct task_struct *p, *g;
2814         write_lock(&css_set_lock);
2815         use_task_css_set_links = 1;
2816         /*
2817          * We need tasklist_lock because RCU is not safe against
2818          * while_each_thread(). Besides, a forking task that has passed
2819          * cgroup_post_fork() without seeing use_task_css_set_links = 1
2820          * is not guaranteed to have its child immediately visible in the
2821          * tasklist if we walk through it with RCU.
2822          */
2823         read_lock(&tasklist_lock);
2824         do_each_thread(g, p) {
2825                 task_lock(p);
2826                 /*
2827                  * We should check if the process is exiting, otherwise
2828                  * it will race with cgroup_exit() in that the list
2829                  * entry won't be deleted though the process has exited.
2830                  */
2831                 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
2832                         list_add(&p->cg_list, &task_css_set(p)->tasks);
2833                 task_unlock(p);
2834         } while_each_thread(g, p);
2835         read_unlock(&tasklist_lock);
2836         write_unlock(&css_set_lock);
2837 }
2838
2839 /**
2840  * css_next_child - find the next child of a given css
2841  * @pos_css: the current position (%NULL to initiate traversal)
2842  * @parent_css: css whose children to walk
2843  *
2844  * This function returns the next child of @parent_css and should be called
2845  * under either cgroup_mutex or RCU read lock.  The only requirement is
2846  * that @parent_css and @pos_css are accessible.  The next sibling is
2847  * guaranteed to be returned regardless of their states.
2848  */
2849 struct cgroup_subsys_state *
2850 css_next_child(struct cgroup_subsys_state *pos_css,
2851                struct cgroup_subsys_state *parent_css)
2852 {
2853         struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
2854         struct cgroup *cgrp = parent_css->cgroup;
2855         struct cgroup *next;
2856
2857         cgroup_assert_mutex_or_rcu_locked();
2858
2859         /*
2860          * @pos could already have been removed.  Once a cgroup is removed,
2861          * its ->sibling.next is no longer updated when its next sibling
2862          * changes.  As CGRP_DEAD assertion is serialized and happens
2863          * before the cgroup is taken off the ->sibling list, if we see it
2864          * unasserted, it's guaranteed that the next sibling hasn't
2865          * finished its grace period even if it's already removed, and thus
2866          * safe to dereference from this RCU critical section.  If
2867          * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
2868          * to be visible as %true here.
2869          *
2870          * If @pos is dead, its next pointer can't be dereferenced;
2871          * however, as each cgroup is given a monotonically increasing
2872          * unique serial number and always appended to the sibling list,
2873          * the next one can be found by walking the parent's children until
2874          * we see a cgroup with higher serial number than @pos's.  While
2875          * this path can be slower, it's taken only when either the current
2876          * cgroup is removed or iteration and removal race.
2877          */
2878         if (!pos) {
2879                 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
2880         } else if (likely(!cgroup_is_dead(pos))) {
2881                 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
2882         } else {
2883                 list_for_each_entry_rcu(next, &cgrp->children, sibling)
2884                         if (next->serial_nr > pos->serial_nr)
2885                                 break;
2886         }
2887
2888         if (&next->sibling == &cgrp->children)
2889                 return NULL;
2890
2891         return cgroup_css(next, parent_css->ss);
2892 }
2893 EXPORT_SYMBOL_GPL(css_next_child);
2894
2895 /**
2896  * css_next_descendant_pre - find the next descendant for pre-order walk
2897  * @pos: the current position (%NULL to initiate traversal)
2898  * @root: css whose descendants to walk
2899  *
2900  * To be used by css_for_each_descendant_pre().  Find the next descendant
2901  * to visit for pre-order traversal of @root's descendants.  @root is
2902  * included in the iteration and the first node to be visited.
2903  *
2904  * While this function requires cgroup_mutex or RCU read locking, it
2905  * doesn't require the whole traversal to be contained in a single critical
2906  * section.  This function will return the correct next descendant as long
2907  * as both @pos and @root are accessible and @pos is a descendant of @root.
2908  */
2909 struct cgroup_subsys_state *
2910 css_next_descendant_pre(struct cgroup_subsys_state *pos,
2911                         struct cgroup_subsys_state *root)
2912 {
2913         struct cgroup_subsys_state *next;
2914
2915         cgroup_assert_mutex_or_rcu_locked();
2916
2917         /* if first iteration, visit @root */
2918         if (!pos)
2919                 return root;
2920
2921         /* visit the first child if exists */
2922         next = css_next_child(NULL, pos);
2923         if (next)
2924                 return next;
2925
2926         /* no child, visit my or the closest ancestor's next sibling */
2927         while (pos != root) {
2928                 next = css_next_child(pos, css_parent(pos));
2929                 if (next)
2930                         return next;
2931                 pos = css_parent(pos);
2932         }
2933
2934         return NULL;
2935 }
2936 EXPORT_SYMBOL_GPL(css_next_descendant_pre);
2937
2938 /**
2939  * css_rightmost_descendant - return the rightmost descendant of a css
2940  * @pos: css of interest
2941  *
2942  * Return the rightmost descendant of @pos.  If there's no descendant, @pos
2943  * is returned.  This can be used during pre-order traversal to skip
2944  * subtree of @pos.
2945  *
2946  * While this function requires cgroup_mutex or RCU read locking, it
2947  * doesn't require the whole traversal to be contained in a single critical
2948  * section.  This function will return the correct rightmost descendant as
2949  * long as @pos is accessible.
2950  */
2951 struct cgroup_subsys_state *
2952 css_rightmost_descendant(struct cgroup_subsys_state *pos)
2953 {
2954         struct cgroup_subsys_state *last, *tmp;
2955
2956         cgroup_assert_mutex_or_rcu_locked();
2957
2958         do {
2959                 last = pos;
2960                 /* ->prev isn't RCU safe, walk ->next till the end */
2961                 pos = NULL;
2962                 css_for_each_child(tmp, last)
2963                         pos = tmp;
2964         } while (pos);
2965
2966         return last;
2967 }
2968 EXPORT_SYMBOL_GPL(css_rightmost_descendant);
2969
2970 static struct cgroup_subsys_state *
2971 css_leftmost_descendant(struct cgroup_subsys_state *pos)
2972 {
2973         struct cgroup_subsys_state *last;
2974
2975         do {
2976                 last = pos;
2977                 pos = css_next_child(NULL, pos);
2978         } while (pos);
2979
2980         return last;
2981 }
2982
2983 /**
2984  * css_next_descendant_post - find the next descendant for post-order walk
2985  * @pos: the current position (%NULL to initiate traversal)
2986  * @root: css whose descendants to walk
2987  *
2988  * To be used by css_for_each_descendant_post().  Find the next descendant
2989  * to visit for post-order traversal of @root's descendants.  @root is
2990  * included in the iteration and the last node to be visited.
2991  *
2992  * While this function requires cgroup_mutex or RCU read locking, it
2993  * doesn't require the whole traversal to be contained in a single critical
2994  * section.  This function will return the correct next descendant as long
2995  * as both @pos and @cgroup are accessible and @pos is a descendant of
2996  * @cgroup.
2997  */
2998 struct cgroup_subsys_state *
2999 css_next_descendant_post(struct cgroup_subsys_state *pos,
3000                          struct cgroup_subsys_state *root)
3001 {
3002         struct cgroup_subsys_state *next;
3003
3004         cgroup_assert_mutex_or_rcu_locked();
3005
3006         /* if first iteration, visit leftmost descendant which may be @root */
3007         if (!pos)
3008                 return css_leftmost_descendant(root);
3009
3010         /* if we visited @root, we're done */
3011         if (pos == root)
3012                 return NULL;
3013
3014         /* if there's an unvisited sibling, visit its leftmost descendant */
3015         next = css_next_child(pos, css_parent(pos));
3016         if (next)
3017                 return css_leftmost_descendant(next);
3018
3019         /* no sibling left, visit parent */
3020         return css_parent(pos);
3021 }
3022 EXPORT_SYMBOL_GPL(css_next_descendant_post);
3023
3024 /**
3025  * css_advance_task_iter - advance a task itererator to the next css_set
3026  * @it: the iterator to advance
3027  *
3028  * Advance @it to the next css_set to walk.
3029  */
3030 static void css_advance_task_iter(struct css_task_iter *it)
3031 {
3032         struct list_head *l = it->cset_link;
3033         struct cgrp_cset_link *link;
3034         struct css_set *cset;
3035
3036         /* Advance to the next non-empty css_set */
3037         do {
3038                 l = l->next;
3039                 if (l == &it->origin_css->cgroup->cset_links) {
3040                         it->cset_link = NULL;
3041                         return;
3042                 }
3043                 link = list_entry(l, struct cgrp_cset_link, cset_link);
3044                 cset = link->cset;
3045         } while (list_empty(&cset->tasks));
3046         it->cset_link = l;
3047         it->task = cset->tasks.next;
3048 }
3049
3050 /**
3051  * css_task_iter_start - initiate task iteration
3052  * @css: the css to walk tasks of
3053  * @it: the task iterator to use
3054  *
3055  * Initiate iteration through the tasks of @css.  The caller can call
3056  * css_task_iter_next() to walk through the tasks until the function
3057  * returns NULL.  On completion of iteration, css_task_iter_end() must be
3058  * called.
3059  *
3060  * Note that this function acquires a lock which is released when the
3061  * iteration finishes.  The caller can't sleep while iteration is in
3062  * progress.
3063  */
3064 void css_task_iter_start(struct cgroup_subsys_state *css,
3065                          struct css_task_iter *it)
3066         __acquires(css_set_lock)
3067 {
3068         /*
3069          * The first time anyone tries to iterate across a css, we need to
3070          * enable the list linking each css_set to its tasks, and fix up
3071          * all existing tasks.
3072          */
3073         if (!use_task_css_set_links)
3074                 cgroup_enable_task_cg_lists();
3075
3076         read_lock(&css_set_lock);
3077
3078         it->origin_css = css;
3079         it->cset_link = &css->cgroup->cset_links;
3080
3081         css_advance_task_iter(it);
3082 }
3083
3084 /**
3085  * css_task_iter_next - return the next task for the iterator
3086  * @it: the task iterator being iterated
3087  *
3088  * The "next" function for task iteration.  @it should have been
3089  * initialized via css_task_iter_start().  Returns NULL when the iteration
3090  * reaches the end.
3091  */
3092 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3093 {
3094         struct task_struct *res;
3095         struct list_head *l = it->task;
3096         struct cgrp_cset_link *link;
3097
3098         /* If the iterator cg is NULL, we have no tasks */
3099         if (!it->cset_link)
3100                 return NULL;
3101         res = list_entry(l, struct task_struct, cg_list);
3102         /* Advance iterator to find next entry */
3103         l = l->next;
3104         link = list_entry(it->cset_link, struct cgrp_cset_link, cset_link);
3105         if (l == &link->cset->tasks) {
3106                 /*
3107                  * We reached the end of this task list - move on to the
3108                  * next cgrp_cset_link.
3109                  */
3110                 css_advance_task_iter(it);
3111         } else {
3112                 it->task = l;
3113         }
3114         return res;
3115 }
3116
3117 /**
3118  * css_task_iter_end - finish task iteration
3119  * @it: the task iterator to finish
3120  *
3121  * Finish task iteration started by css_task_iter_start().
3122  */
3123 void css_task_iter_end(struct css_task_iter *it)
3124         __releases(css_set_lock)
3125 {
3126         read_unlock(&css_set_lock);
3127 }
3128
3129 static inline int started_after_time(struct task_struct *t1,
3130                                      struct timespec *time,
3131                                      struct task_struct *t2)
3132 {
3133         int start_diff = timespec_compare(&t1->start_time, time);
3134         if (start_diff > 0) {
3135                 return 1;
3136         } else if (start_diff < 0) {
3137                 return 0;
3138         } else {
3139                 /*
3140                  * Arbitrarily, if two processes started at the same
3141                  * time, we'll say that the lower pointer value
3142                  * started first. Note that t2 may have exited by now
3143                  * so this may not be a valid pointer any longer, but
3144                  * that's fine - it still serves to distinguish
3145                  * between two tasks started (effectively) simultaneously.
3146                  */
3147                 return t1 > t2;
3148         }
3149 }
3150
3151 /*
3152  * This function is a callback from heap_insert() and is used to order
3153  * the heap.
3154  * In this case we order the heap in descending task start time.
3155  */
3156 static inline int started_after(void *p1, void *p2)
3157 {
3158         struct task_struct *t1 = p1;
3159         struct task_struct *t2 = p2;
3160         return started_after_time(t1, &t2->start_time, t2);
3161 }
3162
3163 /**
3164  * css_scan_tasks - iterate though all the tasks in a css
3165  * @css: the css to iterate tasks of
3166  * @test: optional test callback
3167  * @process: process callback
3168  * @data: data passed to @test and @process
3169  * @heap: optional pre-allocated heap used for task iteration
3170  *
3171  * Iterate through all the tasks in @css, calling @test for each, and if it
3172  * returns %true, call @process for it also.
3173  *
3174  * @test may be NULL, meaning always true (select all tasks), which
3175  * effectively duplicates css_task_iter_{start,next,end}() but does not
3176  * lock css_set_lock for the call to @process.
3177  *
3178  * It is guaranteed that @process will act on every task that is a member
3179  * of @css for the duration of this call.  This function may or may not
3180  * call @process for tasks that exit or move to a different css during the
3181  * call, or are forked or move into the css during the call.
3182  *
3183  * Note that @test may be called with locks held, and may in some
3184  * situations be called multiple times for the same task, so it should be
3185  * cheap.
3186  *
3187  * If @heap is non-NULL, a heap has been pre-allocated and will be used for
3188  * heap operations (and its "gt" member will be overwritten), else a
3189  * temporary heap will be used (allocation of which may cause this function
3190  * to fail).
3191  */
3192 int css_scan_tasks(struct cgroup_subsys_state *css,
3193                    bool (*test)(struct task_struct *, void *),
3194                    void (*process)(struct task_struct *, void *),
3195                    void *data, struct ptr_heap *heap)
3196 {
3197         int retval, i;
3198         struct css_task_iter it;
3199         struct task_struct *p, *dropped;
3200         /* Never dereference latest_task, since it's not refcounted */
3201         struct task_struct *latest_task = NULL;
3202         struct ptr_heap tmp_heap;
3203         struct timespec latest_time = { 0, 0 };
3204
3205         if (heap) {
3206                 /* The caller supplied our heap and pre-allocated its memory */
3207                 heap->gt = &started_after;
3208         } else {
3209                 /* We need to allocate our own heap memory */
3210                 heap = &tmp_heap;
3211                 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3212                 if (retval)
3213                         /* cannot allocate the heap */
3214                         return retval;
3215         }
3216
3217  again:
3218         /*
3219          * Scan tasks in the css, using the @test callback to determine
3220          * which are of interest, and invoking @process callback on the
3221          * ones which need an update.  Since we don't want to hold any
3222          * locks during the task updates, gather tasks to be processed in a
3223          * heap structure.  The heap is sorted by descending task start
3224          * time.  If the statically-sized heap fills up, we overflow tasks
3225          * that started later, and in future iterations only consider tasks
3226          * that started after the latest task in the previous pass. This
3227          * guarantees forward progress and that we don't miss any tasks.
3228          */
3229         heap->size = 0;
3230         css_task_iter_start(css, &it);
3231         while ((p = css_task_iter_next(&it))) {
3232                 /*
3233                  * Only affect tasks that qualify per the caller's callback,
3234                  * if he provided one
3235                  */
3236                 if (test && !test(p, data))
3237                         continue;
3238                 /*
3239                  * Only process tasks that started after the last task
3240                  * we processed
3241                  */
3242                 if (!started_after_time(p, &latest_time, latest_task))
3243                         continue;
3244                 dropped = heap_insert(heap, p);
3245                 if (dropped == NULL) {
3246                         /*
3247                          * The new task was inserted; the heap wasn't
3248                          * previously full
3249                          */
3250                         get_task_struct(p);
3251                 } else if (dropped != p) {
3252                         /*
3253                          * The new task was inserted, and pushed out a
3254                          * different task
3255                          */
3256                         get_task_struct(p);
3257                         put_task_struct(dropped);
3258                 }
3259                 /*
3260                  * Else the new task was newer than anything already in
3261                  * the heap and wasn't inserted
3262                  */
3263         }
3264         css_task_iter_end(&it);
3265
3266         if (heap->size) {
3267                 for (i = 0; i < heap->size; i++) {
3268                         struct task_struct *q = heap->ptrs[i];
3269                         if (i == 0) {
3270                                 latest_time = q->start_time;
3271                                 latest_task = q;
3272                         }
3273                         /* Process the task per the caller's callback */
3274                         process(q, data);
3275                         put_task_struct(q);
3276                 }
3277                 /*
3278                  * If we had to process any tasks at all, scan again
3279                  * in case some of them were in the middle of forking
3280                  * children that didn't get processed.
3281                  * Not the most efficient way to do it, but it avoids
3282                  * having to take callback_mutex in the fork path
3283                  */
3284                 goto again;
3285         }
3286         if (heap == &tmp_heap)
3287                 heap_free(&tmp_heap);
3288         return 0;
3289 }
3290
3291 static void cgroup_transfer_one_task(struct task_struct *task, void *data)
3292 {
3293         struct cgroup *new_cgroup = data;
3294
3295         mutex_lock(&cgroup_mutex);
3296         cgroup_attach_task(new_cgroup, task, false);
3297         mutex_unlock(&cgroup_mutex);
3298 }
3299
3300 /**
3301  * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3302  * @to: cgroup to which the tasks will be moved
3303  * @from: cgroup in which the tasks currently reside
3304  */
3305 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3306 {
3307         return css_scan_tasks(&from->dummy_css, NULL, cgroup_transfer_one_task,
3308                               to, NULL);
3309 }
3310
3311 /*
3312  * Stuff for reading the 'tasks'/'procs' files.
3313  *
3314  * Reading this file can return large amounts of data if a cgroup has
3315  * *lots* of attached tasks. So it may need several calls to read(),
3316  * but we cannot guarantee that the information we produce is correct
3317  * unless we produce it entirely atomically.
3318  *
3319  */
3320
3321 /* which pidlist file are we talking about? */
3322 enum cgroup_filetype {
3323         CGROUP_FILE_PROCS,
3324         CGROUP_FILE_TASKS,
3325 };
3326
3327 /*
3328  * A pidlist is a list of pids that virtually represents the contents of one
3329  * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3330  * a pair (one each for procs, tasks) for each pid namespace that's relevant
3331  * to the cgroup.
3332  */
3333 struct cgroup_pidlist {
3334         /*
3335          * used to find which pidlist is wanted. doesn't change as long as
3336          * this particular list stays in the list.
3337         */
3338         struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3339         /* array of xids */
3340         pid_t *list;
3341         /* how many elements the above list has */
3342         int length;
3343         /* each of these stored in a list by its cgroup */
3344         struct list_head links;
3345         /* pointer to the cgroup we belong to, for list removal purposes */
3346         struct cgroup *owner;
3347         /* for delayed destruction */
3348         struct delayed_work destroy_dwork;
3349 };
3350
3351 /*
3352  * The following two functions "fix" the issue where there are more pids
3353  * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3354  * TODO: replace with a kernel-wide solution to this problem
3355  */
3356 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3357 static void *pidlist_allocate(int count)
3358 {
3359         if (PIDLIST_TOO_LARGE(count))
3360                 return vmalloc(count * sizeof(pid_t));
3361         else
3362                 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3363 }
3364
3365 static void pidlist_free(void *p)
3366 {
3367         if (is_vmalloc_addr(p))
3368                 vfree(p);
3369         else
3370                 kfree(p);
3371 }
3372
3373 /*
3374  * Used to destroy all pidlists lingering waiting for destroy timer.  None
3375  * should be left afterwards.
3376  */
3377 static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
3378 {
3379         struct cgroup_pidlist *l, *tmp_l;
3380
3381         mutex_lock(&cgrp->pidlist_mutex);
3382         list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
3383                 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
3384         mutex_unlock(&cgrp->pidlist_mutex);
3385
3386         flush_workqueue(cgroup_pidlist_destroy_wq);
3387         BUG_ON(!list_empty(&cgrp->pidlists));
3388 }
3389
3390 static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
3391 {
3392         struct delayed_work *dwork = to_delayed_work(work);
3393         struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
3394                                                 destroy_dwork);
3395         struct cgroup_pidlist *tofree = NULL;
3396
3397         mutex_lock(&l->owner->pidlist_mutex);
3398
3399         /*
3400          * Destroy iff we didn't get queued again.  The state won't change
3401          * as destroy_dwork can only be queued while locked.
3402          */
3403         if (!delayed_work_pending(dwork)) {
3404                 list_del(&l->links);
3405                 pidlist_free(l->list);
3406                 put_pid_ns(l->key.ns);
3407                 tofree = l;
3408         }
3409
3410         mutex_unlock(&l->owner->pidlist_mutex);
3411         kfree(tofree);
3412 }
3413
3414 /*
3415  * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3416  * Returns the number of unique elements.
3417  */
3418 static int pidlist_uniq(pid_t *list, int length)
3419 {
3420         int src, dest = 1;
3421
3422         /*
3423          * we presume the 0th element is unique, so i starts at 1. trivial
3424          * edge cases first; no work needs to be done for either
3425          */
3426         if (length == 0 || length == 1)
3427                 return length;
3428         /* src and dest walk down the list; dest counts unique elements */
3429         for (src = 1; src < length; src++) {
3430                 /* find next unique element */
3431                 while (list[src] == list[src-1]) {
3432                         src++;
3433                         if (src == length)
3434                                 goto after;
3435                 }
3436                 /* dest always points to where the next unique element goes */
3437                 list[dest] = list[src];
3438                 dest++;
3439         }
3440 after:
3441         return dest;
3442 }
3443
3444 /*
3445  * The two pid files - task and cgroup.procs - guaranteed that the result
3446  * is sorted, which forced this whole pidlist fiasco.  As pid order is
3447  * different per namespace, each namespace needs differently sorted list,
3448  * making it impossible to use, for example, single rbtree of member tasks
3449  * sorted by task pointer.  As pidlists can be fairly large, allocating one
3450  * per open file is dangerous, so cgroup had to implement shared pool of
3451  * pidlists keyed by cgroup and namespace.
3452  *
3453  * All this extra complexity was caused by the original implementation
3454  * committing to an entirely unnecessary property.  In the long term, we
3455  * want to do away with it.  Explicitly scramble sort order if
3456  * sane_behavior so that no such expectation exists in the new interface.
3457  *
3458  * Scrambling is done by swapping every two consecutive bits, which is
3459  * non-identity one-to-one mapping which disturbs sort order sufficiently.
3460  */
3461 static pid_t pid_fry(pid_t pid)
3462 {
3463         unsigned a = pid & 0x55555555;
3464         unsigned b = pid & 0xAAAAAAAA;
3465
3466         return (a << 1) | (b >> 1);
3467 }
3468
3469 static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
3470 {
3471         if (cgroup_sane_behavior(cgrp))
3472                 return pid_fry(pid);
3473         else
3474                 return pid;
3475 }
3476
3477 static int cmppid(const void *a, const void *b)
3478 {
3479         return *(pid_t *)a - *(pid_t *)b;
3480 }
3481
3482 static int fried_cmppid(const void *a, const void *b)
3483 {
3484         return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
3485 }
3486
3487 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3488                                                   enum cgroup_filetype type)
3489 {
3490         struct cgroup_pidlist *l;
3491         /* don't need task_nsproxy() if we're looking at ourself */
3492         struct pid_namespace *ns = task_active_pid_ns(current);
3493
3494         lockdep_assert_held(&cgrp->pidlist_mutex);
3495
3496         list_for_each_entry(l, &cgrp->pidlists, links)
3497                 if (l->key.type == type && l->key.ns == ns)
3498                         return l;
3499         return NULL;
3500 }
3501
3502 /*
3503  * find the appropriate pidlist for our purpose (given procs vs tasks)
3504  * returns with the lock on that pidlist already held, and takes care
3505  * of the use count, or returns NULL with no locks held if we're out of
3506  * memory.
3507  */
3508 static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
3509                                                 enum cgroup_filetype type)
3510 {
3511         struct cgroup_pidlist *l;
3512
3513         lockdep_assert_held(&cgrp->pidlist_mutex);
3514
3515         l = cgroup_pidlist_find(cgrp, type);
3516         if (l)
3517                 return l;
3518
3519         /* entry not found; create a new one */
3520         l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3521         if (!l)
3522                 return l;
3523
3524         INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
3525         l->key.type = type;
3526         /* don't need task_nsproxy() if we're looking at ourself */
3527         l->key.ns = get_pid_ns(task_active_pid_ns(current));
3528         l->owner = cgrp;
3529         list_add(&l->links, &cgrp->pidlists);
3530         return l;
3531 }
3532
3533 /*
3534  * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3535  */
3536 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3537                               struct cgroup_pidlist **lp)
3538 {
3539         pid_t *array;
3540         int length;
3541         int pid, n = 0; /* used for populating the array */
3542         struct css_task_iter it;
3543         struct task_struct *tsk;
3544         struct cgroup_pidlist *l;
3545
3546         lockdep_assert_held(&cgrp->pidlist_mutex);
3547
3548         /*
3549          * If cgroup gets more users after we read count, we won't have
3550          * enough space - tough.  This race is indistinguishable to the
3551          * caller from the case that the additional cgroup users didn't
3552          * show up until sometime later on.
3553          */
3554         length = cgroup_task_count(cgrp);
3555         array = pidlist_allocate(length);
3556         if (!array)
3557                 return -ENOMEM;
3558         /* now, populate the array */
3559         css_task_iter_start(&cgrp->dummy_css, &it);
3560         while ((tsk = css_task_iter_next(&it))) {
3561                 if (unlikely(n == length))
3562                         break;
3563                 /* get tgid or pid for procs or tasks file respectively */
3564                 if (type == CGROUP_FILE_PROCS)
3565                         pid = task_tgid_vnr(tsk);
3566                 else
3567                         pid = task_pid_vnr(tsk);
3568                 if (pid > 0) /* make sure to only use valid results */
3569                         array[n++] = pid;
3570         }
3571         css_task_iter_end(&it);
3572         length = n;
3573         /* now sort & (if procs) strip out duplicates */
3574         if (cgroup_sane_behavior(cgrp))
3575                 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
3576         else
3577                 sort(array, length, sizeof(pid_t), cmppid, NULL);
3578         if (type == CGROUP_FILE_PROCS)
3579                 length = pidlist_uniq(array, length);
3580
3581         l = cgroup_pidlist_find_create(cgrp, type);
3582         if (!l) {
3583                 mutex_unlock(&cgrp->pidlist_mutex);
3584                 pidlist_free(array);
3585                 return -ENOMEM;
3586         }
3587
3588         /* store array, freeing old if necessary */
3589         pidlist_free(l->list);
3590         l->list = array;
3591         l->length = length;
3592         *lp = l;
3593         return 0;
3594 }
3595
3596 /**
3597  * cgroupstats_build - build and fill cgroupstats
3598  * @stats: cgroupstats to fill information into
3599  * @dentry: A dentry entry belonging to the cgroup for which stats have
3600  * been requested.
3601  *
3602  * Build and fill cgroupstats so that taskstats can export it to user
3603  * space.
3604  */
3605 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3606 {
3607         int ret = -EINVAL;
3608         struct cgroup *cgrp;
3609         struct css_task_iter it;
3610         struct task_struct *tsk;
3611
3612         /*
3613          * Validate dentry by checking the superblock operations,
3614          * and make sure it's a directory.
3615          */
3616         if (dentry->d_sb->s_op != &cgroup_ops ||
3617             !S_ISDIR(dentry->d_inode->i_mode))
3618                  goto err;
3619
3620         ret = 0;
3621         cgrp = dentry->d_fsdata;
3622
3623         css_task_iter_start(&cgrp->dummy_css, &it);
3624         while ((tsk = css_task_iter_next(&it))) {
3625                 switch (tsk->state) {
3626                 case TASK_RUNNING:
3627                         stats->nr_running++;
3628                         break;
3629                 case TASK_INTERRUPTIBLE:
3630                         stats->nr_sleeping++;
3631                         break;
3632                 case TASK_UNINTERRUPTIBLE:
3633                         stats->nr_uninterruptible++;
3634                         break;
3635                 case TASK_STOPPED:
3636                         stats->nr_stopped++;
3637                         break;
3638                 default:
3639                         if (delayacct_is_task_waiting_on_io(tsk))
3640                                 stats->nr_io_wait++;
3641                         break;
3642                 }
3643         }
3644         css_task_iter_end(&it);
3645
3646 err:
3647         return ret;
3648 }
3649
3650
3651 /*
3652  * seq_file methods for the tasks/procs files. The seq_file position is the
3653  * next pid to display; the seq_file iterator is a pointer to the pid
3654  * in the cgroup->l->list array.
3655  */
3656
3657 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3658 {
3659         /*
3660          * Initially we receive a position value that corresponds to
3661          * one more than the last pid shown (or 0 on the first call or
3662          * after a seek to the start). Use a binary-search to find the
3663          * next pid to display, if any
3664          */
3665         struct cgroup_open_file *of = s->private;
3666         struct cgroup *cgrp = seq_css(s)->cgroup;
3667         struct cgroup_pidlist *l;
3668         enum cgroup_filetype type = seq_cft(s)->private;
3669         int index = 0, pid = *pos;
3670         int *iter, ret;
3671
3672         mutex_lock(&cgrp->pidlist_mutex);
3673
3674         /*
3675          * !NULL @of->priv indicates that this isn't the first start()
3676          * after open.  If the matching pidlist is around, we can use that.
3677          * Look for it.  Note that @of->priv can't be used directly.  It
3678          * could already have been destroyed.
3679          */
3680         if (of->priv)
3681                 of->priv = cgroup_pidlist_find(cgrp, type);
3682
3683         /*
3684          * Either this is the first start() after open or the matching
3685          * pidlist has been destroyed inbetween.  Create a new one.
3686          */
3687         if (!of->priv) {
3688                 ret = pidlist_array_load(cgrp, type,
3689                                          (struct cgroup_pidlist **)&of->priv);
3690                 if (ret)
3691                         return ERR_PTR(ret);
3692         }
3693         l = of->priv;
3694
3695         if (pid) {
3696                 int end = l->length;
3697
3698                 while (index < end) {
3699                         int mid = (index + end) / 2;
3700                         if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
3701                                 index = mid;
3702                                 break;
3703                         } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
3704                                 index = mid + 1;
3705                         else
3706                                 end = mid;
3707                 }
3708         }
3709         /* If we're off the end of the array, we're done */
3710         if (index >= l->length)
3711                 return NULL;
3712         /* Update the abstract position to be the actual pid that we found */
3713         iter = l->list + index;
3714         *pos = cgroup_pid_fry(cgrp, *iter);
3715         return iter;
3716 }
3717
3718 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3719 {
3720         struct cgroup_open_file *of = s->private;
3721         struct cgroup_pidlist *l = of->priv;
3722
3723         if (l)
3724                 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
3725                                  CGROUP_PIDLIST_DESTROY_DELAY);
3726         mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
3727 }
3728
3729 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3730 {
3731         struct cgroup_open_file *of = s->private;
3732         struct cgroup_pidlist *l = of->priv;
3733         pid_t *p = v;
3734         pid_t *end = l->list + l->length;
3735         /*
3736          * Advance to the next pid in the array. If this goes off the
3737          * end, we're done
3738          */
3739         p++;
3740         if (p >= end) {
3741                 return NULL;
3742         } else {
3743                 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
3744                 return p;
3745         }
3746 }
3747
3748 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3749 {
3750         return seq_printf(s, "%d\n", *(int *)v);
3751 }
3752
3753 /*
3754  * seq_operations functions for iterating on pidlists through seq_file -
3755  * independent of whether it's tasks or procs
3756  */
3757 static const struct seq_operations cgroup_pidlist_seq_operations = {
3758         .start = cgroup_pidlist_start,
3759         .stop = cgroup_pidlist_stop,
3760         .next = cgroup_pidlist_next,
3761         .show = cgroup_pidlist_show,
3762 };
3763
3764 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3765                                          struct cftype *cft)
3766 {
3767         return notify_on_release(css->cgroup);
3768 }
3769
3770 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3771                                           struct cftype *cft, u64 val)
3772 {
3773         clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3774         if (val)
3775                 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3776         else
3777                 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3778         return 0;
3779 }
3780
3781 /*
3782  * When dput() is called asynchronously, if umount has been done and
3783  * then deactivate_super() in cgroup_free_fn() kills the superblock,
3784  * there's a small window that vfs will see the root dentry with non-zero
3785  * refcnt and trigger BUG().
3786  *
3787  * That's why we hold a reference before dput() and drop it right after.
3788  */
3789 static void cgroup_dput(struct cgroup *cgrp)
3790 {
3791         struct super_block *sb = cgrp->root->sb;
3792
3793         atomic_inc(&sb->s_active);
3794         dput(cgrp->dentry);
3795         deactivate_super(sb);
3796 }
3797
3798 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3799                                       struct cftype *cft)
3800 {
3801         return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3802 }
3803
3804 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3805                                        struct cftype *cft, u64 val)
3806 {
3807         if (val)
3808                 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3809         else
3810                 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
3811         return 0;
3812 }
3813
3814 static struct cftype cgroup_base_files[] = {
3815         {
3816                 .name = "cgroup.procs",
3817                 .seq_start = cgroup_pidlist_start,
3818                 .seq_next = cgroup_pidlist_next,
3819                 .seq_stop = cgroup_pidlist_stop,
3820                 .seq_show = cgroup_pidlist_show,
3821                 .private = CGROUP_FILE_PROCS,
3822                 .write_u64 = cgroup_procs_write,
3823                 .mode = S_IRUGO | S_IWUSR,
3824         },
3825         {
3826                 .name = "cgroup.clone_children",
3827                 .flags = CFTYPE_INSANE,
3828                 .read_u64 = cgroup_clone_children_read,
3829                 .write_u64 = cgroup_clone_children_write,
3830         },
3831         {
3832                 .name = "cgroup.sane_behavior",
3833                 .flags = CFTYPE_ONLY_ON_ROOT,
3834                 .seq_show = cgroup_sane_behavior_show,
3835         },
3836
3837         /*
3838          * Historical crazy stuff.  These don't have "cgroup."  prefix and
3839          * don't exist if sane_behavior.  If you're depending on these, be
3840          * prepared to be burned.
3841          */
3842         {
3843                 .name = "tasks",
3844                 .flags = CFTYPE_INSANE,         /* use "procs" instead */
3845                 .seq_start = cgroup_pidlist_start,
3846                 .seq_next = cgroup_pidlist_next,
3847                 .seq_stop = cgroup_pidlist_stop,
3848                 .seq_show = cgroup_pidlist_show,
3849                 .private = CGROUP_FILE_TASKS,
3850                 .write_u64 = cgroup_tasks_write,
3851                 .mode = S_IRUGO | S_IWUSR,
3852         },
3853         {
3854                 .name = "notify_on_release",
3855                 .flags = CFTYPE_INSANE,
3856                 .read_u64 = cgroup_read_notify_on_release,
3857                 .write_u64 = cgroup_write_notify_on_release,
3858         },
3859         {
3860                 .name = "release_agent",
3861                 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
3862                 .seq_show = cgroup_release_agent_show,
3863                 .write_string = cgroup_release_agent_write,
3864                 .max_write_len = PATH_MAX,
3865         },
3866         { }     /* terminate */
3867 };
3868
3869 /**
3870  * cgroup_populate_dir - create subsys files in a cgroup directory
3871  * @cgrp: target cgroup
3872  * @subsys_mask: mask of the subsystem ids whose files should be added
3873  *
3874  * On failure, no file is added.
3875  */
3876 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
3877 {
3878         struct cgroup_subsys *ss;
3879         int i, ret = 0;
3880
3881         /* process cftsets of each subsystem */
3882         for_each_subsys(ss, i) {
3883                 struct cftype_set *set;
3884
3885                 if (!test_bit(i, &subsys_mask))
3886                         continue;
3887
3888                 list_for_each_entry(set, &ss->cftsets, node) {
3889                         ret = cgroup_addrm_files(cgrp, set->cfts, true);
3890                         if (ret < 0)
3891                                 goto err;
3892                 }
3893         }
3894         return 0;
3895 err:
3896         cgroup_clear_dir(cgrp, subsys_mask);
3897         return ret;
3898 }
3899
3900 /*
3901  * css destruction is four-stage process.
3902  *
3903  * 1. Destruction starts.  Killing of the percpu_ref is initiated.
3904  *    Implemented in kill_css().
3905  *
3906  * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
3907  *    and thus css_tryget() is guaranteed to fail, the css can be offlined
3908  *    by invoking offline_css().  After offlining, the base ref is put.
3909  *    Implemented in css_killed_work_fn().
3910  *
3911  * 3. When the percpu_ref reaches zero, the only possible remaining
3912  *    accessors are inside RCU read sections.  css_release() schedules the
3913  *    RCU callback.
3914  *
3915  * 4. After the grace period, the css can be freed.  Implemented in
3916  *    css_free_work_fn().
3917  *
3918  * It is actually hairier because both step 2 and 4 require process context
3919  * and thus involve punting to css->destroy_work adding two additional
3920  * steps to the already complex sequence.
3921  */
3922 static void css_free_work_fn(struct work_struct *work)
3923 {
3924         struct cgroup_subsys_state *css =
3925                 container_of(work, struct cgroup_subsys_state, destroy_work);
3926         struct cgroup *cgrp = css->cgroup;
3927
3928         if (css->parent)
3929                 css_put(css->parent);
3930
3931         css->ss->css_free(css);
3932         cgroup_dput(cgrp);
3933 }
3934
3935 static void css_free_rcu_fn(struct rcu_head *rcu_head)
3936 {
3937         struct cgroup_subsys_state *css =
3938                 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
3939
3940         /*
3941          * css holds an extra ref to @cgrp->dentry which is put on the last
3942          * css_put().  dput() requires process context which we don't have.
3943          */
3944         INIT_WORK(&css->destroy_work, css_free_work_fn);
3945         queue_work(cgroup_destroy_wq, &css->destroy_work);
3946 }
3947
3948 static void css_release(struct percpu_ref *ref)
3949 {
3950         struct cgroup_subsys_state *css =
3951                 container_of(ref, struct cgroup_subsys_state, refcnt);
3952
3953         rcu_assign_pointer(css->cgroup->subsys[css->ss->id], NULL);
3954         call_rcu(&css->rcu_head, css_free_rcu_fn);
3955 }
3956
3957 static void init_css(struct cgroup_subsys_state *css, struct cgroup_subsys *ss,
3958                      struct cgroup *cgrp)
3959 {
3960         css->cgroup = cgrp;
3961         css->ss = ss;
3962         css->flags = 0;
3963
3964         if (cgrp->parent)
3965                 css->parent = cgroup_css(cgrp->parent, ss);
3966         else
3967                 css->flags |= CSS_ROOT;
3968
3969         BUG_ON(cgroup_css(cgrp, ss));
3970 }
3971
3972 /* invoke ->css_online() on a new CSS and mark it online if successful */
3973 static int online_css(struct cgroup_subsys_state *css)
3974 {
3975         struct cgroup_subsys *ss = css->ss;
3976         int ret = 0;
3977
3978         lockdep_assert_held(&cgroup_mutex);
3979
3980         if (ss->css_online)
3981                 ret = ss->css_online(css);
3982         if (!ret) {
3983                 css->flags |= CSS_ONLINE;
3984                 css->cgroup->nr_css++;
3985                 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
3986         }
3987         return ret;
3988 }
3989
3990 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
3991 static void offline_css(struct cgroup_subsys_state *css)
3992 {
3993         struct cgroup_subsys *ss = css->ss;
3994
3995         lockdep_assert_held(&cgroup_mutex);
3996
3997         if (!(css->flags & CSS_ONLINE))
3998                 return;
3999
4000         if (ss->css_offline)
4001                 ss->css_offline(css);
4002
4003         css->flags &= ~CSS_ONLINE;
4004         css->cgroup->nr_css--;
4005         RCU_INIT_POINTER(css->cgroup->subsys[ss->id], css);
4006 }
4007
4008 /**
4009  * create_css - create a cgroup_subsys_state
4010  * @cgrp: the cgroup new css will be associated with
4011  * @ss: the subsys of new css
4012  *
4013  * Create a new css associated with @cgrp - @ss pair.  On success, the new
4014  * css is online and installed in @cgrp with all interface files created.
4015  * Returns 0 on success, -errno on failure.
4016  */
4017 static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss)
4018 {
4019         struct cgroup *parent = cgrp->parent;
4020         struct cgroup_subsys_state *css;
4021         int err;
4022
4023         lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
4024         lockdep_assert_held(&cgroup_mutex);
4025
4026         css = ss->css_alloc(cgroup_css(parent, ss));
4027         if (IS_ERR(css))
4028                 return PTR_ERR(css);
4029
4030         err = percpu_ref_init(&css->refcnt, css_release);
4031         if (err)
4032                 goto err_free;
4033
4034         init_css(css, ss, cgrp);
4035
4036         err = cgroup_populate_dir(cgrp, 1 << ss->id);
4037         if (err)
4038                 goto err_free;
4039
4040         err = online_css(css);
4041         if (err)
4042                 goto err_free;
4043
4044         dget(cgrp->dentry);
4045         css_get(css->parent);
4046
4047         if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4048             parent->parent) {
4049                 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",
4050                            current->comm, current->pid, ss->name);
4051                 if (!strcmp(ss->name, "memory"))
4052                         pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4053                 ss->warned_broken_hierarchy = true;
4054         }
4055
4056         return 0;
4057
4058 err_free:
4059         percpu_ref_cancel_init(&css->refcnt);
4060         ss->css_free(css);
4061         return err;
4062 }
4063
4064 /*
4065  * cgroup_create - create a cgroup
4066  * @parent: cgroup that will be parent of the new cgroup
4067  * @dentry: dentry of the new cgroup
4068  * @mode: mode to set on new inode
4069  *
4070  * Must be called with the mutex on the parent inode held
4071  */
4072 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4073                              umode_t mode)
4074 {
4075         struct cgroup *cgrp;
4076         struct cgroup_name *name;
4077         struct cgroupfs_root *root = parent->root;
4078         int ssid, err;
4079         struct cgroup_subsys *ss;
4080         struct super_block *sb = root->sb;
4081
4082         /* allocate the cgroup and its ID, 0 is reserved for the root */
4083         cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4084         if (!cgrp)
4085                 return -ENOMEM;
4086
4087         name = cgroup_alloc_name(dentry);
4088         if (!name) {
4089                 err = -ENOMEM;
4090                 goto err_free_cgrp;
4091         }
4092         rcu_assign_pointer(cgrp->name, name);
4093
4094         /*
4095          * Temporarily set the pointer to NULL, so idr_find() won't return
4096          * a half-baked cgroup.
4097          */
4098         cgrp->id = idr_alloc(&root->cgroup_idr, NULL, 1, 0, GFP_KERNEL);
4099         if (cgrp->id < 0) {
4100                 err = -ENOMEM;
4101                 goto err_free_name;
4102         }
4103
4104         /*
4105          * Only live parents can have children.  Note that the liveliness
4106          * check isn't strictly necessary because cgroup_mkdir() and
4107          * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4108          * anyway so that locking is contained inside cgroup proper and we
4109          * don't get nasty surprises if we ever grow another caller.
4110          */
4111         if (!cgroup_lock_live_group(parent)) {
4112                 err = -ENODEV;
4113                 goto err_free_id;
4114         }
4115
4116         /* Grab a reference on the superblock so the hierarchy doesn't
4117          * get deleted on unmount if there are child cgroups.  This
4118          * can be done outside cgroup_mutex, since the sb can't
4119          * disappear while someone has an open control file on the
4120          * fs */
4121         atomic_inc(&sb->s_active);
4122
4123         init_cgroup_housekeeping(cgrp);
4124
4125         dentry->d_fsdata = cgrp;
4126         cgrp->dentry = dentry;
4127
4128         cgrp->parent = parent;
4129         cgrp->dummy_css.parent = &parent->dummy_css;
4130         cgrp->root = parent->root;
4131
4132         if (notify_on_release(parent))
4133                 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4134
4135         if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4136                 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4137
4138         /*
4139          * Create directory.  cgroup_create_file() returns with the new
4140          * directory locked on success so that it can be populated without
4141          * dropping cgroup_mutex.
4142          */
4143         err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4144         if (err < 0)
4145                 goto err_unlock;
4146         lockdep_assert_held(&dentry->d_inode->i_mutex);
4147
4148         cgrp->serial_nr = cgroup_serial_nr_next++;
4149
4150         /* allocation complete, commit to creation */
4151         list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4152         root->number_of_cgroups++;
4153
4154         /* hold a ref to the parent's dentry */
4155         dget(parent->dentry);
4156
4157         /*
4158          * @cgrp is now fully operational.  If something fails after this
4159          * point, it'll be released via the normal destruction path.
4160          */
4161         idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4162
4163         err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
4164         if (err)
4165                 goto err_destroy;
4166
4167         /* let's create and online css's */
4168         for_each_subsys(ss, ssid) {
4169                 if (root->subsys_mask & (1 << ssid)) {
4170                         err = create_css(cgrp, ss);
4171                         if (err)
4172                                 goto err_destroy;
4173                 }
4174         }
4175
4176         mutex_unlock(&cgroup_mutex);
4177         mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4178
4179         return 0;
4180
4181 err_unlock:
4182         mutex_unlock(&cgroup_mutex);
4183         /* Release the reference count that we took on the superblock */
4184         deactivate_super(sb);
4185 err_free_id:
4186         idr_remove(&root->cgroup_idr, cgrp->id);
4187 err_free_name:
4188         kfree(rcu_dereference_raw(cgrp->name));
4189 err_free_cgrp:
4190         kfree(cgrp);
4191         return err;
4192
4193 err_destroy:
4194         cgroup_destroy_locked(cgrp);
4195         mutex_unlock(&cgroup_mutex);
4196         mutex_unlock(&dentry->d_inode->i_mutex);
4197         return err;
4198 }
4199
4200 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4201 {
4202         struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4203
4204         /* the vfs holds inode->i_mutex already */
4205         return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4206 }
4207
4208 /*
4209  * This is called when the refcnt of a css is confirmed to be killed.
4210  * css_tryget() is now guaranteed to fail.
4211  */
4212 static void css_killed_work_fn(struct work_struct *work)
4213 {
4214         struct cgroup_subsys_state *css =
4215                 container_of(work, struct cgroup_subsys_state, destroy_work);
4216         struct cgroup *cgrp = css->cgroup;
4217
4218         mutex_lock(&cgroup_mutex);
4219
4220         /*
4221          * css_tryget() is guaranteed to fail now.  Tell subsystems to
4222          * initate destruction.
4223          */
4224         offline_css(css);
4225
4226         /*
4227          * If @cgrp is marked dead, it's waiting for refs of all css's to
4228          * be disabled before proceeding to the second phase of cgroup
4229          * destruction.  If we are the last one, kick it off.
4230          */
4231         if (!cgrp->nr_css && cgroup_is_dead(cgrp))
4232                 cgroup_destroy_css_killed(cgrp);
4233
4234         mutex_unlock(&cgroup_mutex);
4235
4236         /*
4237          * Put the css refs from kill_css().  Each css holds an extra
4238          * reference to the cgroup's dentry and cgroup removal proceeds
4239          * regardless of css refs.  On the last put of each css, whenever
4240          * that may be, the extra dentry ref is put so that dentry
4241          * destruction happens only after all css's are released.
4242          */
4243         css_put(css);
4244 }
4245
4246 /* css kill confirmation processing requires process context, bounce */
4247 static void css_killed_ref_fn(struct percpu_ref *ref)
4248 {
4249         struct cgroup_subsys_state *css =
4250                 container_of(ref, struct cgroup_subsys_state, refcnt);
4251
4252         INIT_WORK(&css->destroy_work, css_killed_work_fn);
4253         queue_work(cgroup_destroy_wq, &css->destroy_work);
4254 }
4255
4256 /**
4257  * kill_css - destroy a css
4258  * @css: css to destroy
4259  *
4260  * This function initiates destruction of @css by removing cgroup interface
4261  * files and putting its base reference.  ->css_offline() will be invoked
4262  * asynchronously once css_tryget() is guaranteed to fail and when the
4263  * reference count reaches zero, @css will be released.
4264  */
4265 static void kill_css(struct cgroup_subsys_state *css)
4266 {
4267         cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
4268
4269         /*
4270          * Killing would put the base ref, but we need to keep it alive
4271          * until after ->css_offline().
4272          */
4273         css_get(css);
4274
4275         /*
4276          * cgroup core guarantees that, by the time ->css_offline() is
4277          * invoked, no new css reference will be given out via
4278          * css_tryget().  We can't simply call percpu_ref_kill() and
4279          * proceed to offlining css's because percpu_ref_kill() doesn't
4280          * guarantee that the ref is seen as killed on all CPUs on return.
4281          *
4282          * Use percpu_ref_kill_and_confirm() to get notifications as each
4283          * css is confirmed to be seen as killed on all CPUs.
4284          */
4285         percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4286 }
4287
4288 /**
4289  * cgroup_destroy_locked - the first stage of cgroup destruction
4290  * @cgrp: cgroup to be destroyed
4291  *
4292  * css's make use of percpu refcnts whose killing latency shouldn't be
4293  * exposed to userland and are RCU protected.  Also, cgroup core needs to
4294  * guarantee that css_tryget() won't succeed by the time ->css_offline() is
4295  * invoked.  To satisfy all the requirements, destruction is implemented in
4296  * the following two steps.
4297  *
4298  * s1. Verify @cgrp can be destroyed and mark it dying.  Remove all
4299  *     userland visible parts and start killing the percpu refcnts of
4300  *     css's.  Set up so that the next stage will be kicked off once all
4301  *     the percpu refcnts are confirmed to be killed.
4302  *
4303  * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4304  *     rest of destruction.  Once all cgroup references are gone, the
4305  *     cgroup is RCU-freed.
4306  *
4307  * This function implements s1.  After this step, @cgrp is gone as far as
4308  * the userland is concerned and a new cgroup with the same name may be
4309  * created.  As cgroup doesn't care about the names internally, this
4310  * doesn't cause any problem.
4311  */
4312 static int cgroup_destroy_locked(struct cgroup *cgrp)
4313         __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4314 {
4315         struct dentry *d = cgrp->dentry;
4316         struct cgroup_subsys_state *css;
4317         struct cgroup *child;
4318         bool empty;
4319         int ssid;
4320
4321         lockdep_assert_held(&d->d_inode->i_mutex);
4322         lockdep_assert_held(&cgroup_mutex);
4323
4324         /*
4325          * css_set_lock synchronizes access to ->cset_links and prevents
4326          * @cgrp from being removed while __put_css_set() is in progress.
4327          */
4328         read_lock(&css_set_lock);
4329         empty = list_empty(&cgrp->cset_links);
4330         read_unlock(&css_set_lock);
4331         if (!empty)
4332                 return -EBUSY;
4333
4334         /*
4335          * Make sure there's no live children.  We can't test ->children
4336          * emptiness as dead children linger on it while being destroyed;
4337          * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
4338          */
4339         empty = true;
4340         rcu_read_lock();
4341         list_for_each_entry_rcu(child, &cgrp->children, sibling) {
4342                 empty = cgroup_is_dead(child);
4343                 if (!empty)
4344                         break;
4345         }
4346         rcu_read_unlock();
4347         if (!empty)
4348                 return -EBUSY;
4349
4350         /*
4351          * Initiate massacre of all css's.  cgroup_destroy_css_killed()
4352          * will be invoked to perform the rest of destruction once the
4353          * percpu refs of all css's are confirmed to be killed.
4354          */
4355         for_each_css(css, ssid, cgrp)
4356                 kill_css(css);
4357
4358         /*
4359          * Mark @cgrp dead.  This prevents further task migration and child
4360          * creation by disabling cgroup_lock_live_group().  Note that
4361          * CGRP_DEAD assertion is depended upon by css_next_child() to
4362          * resume iteration after dropping RCU read lock.  See
4363          * css_next_child() for details.
4364          */
4365         set_bit(CGRP_DEAD, &cgrp->flags);
4366
4367         /* CGRP_DEAD is set, remove from ->release_list for the last time */
4368         raw_spin_lock(&release_list_lock);
4369         if (!list_empty(&cgrp->release_list))
4370                 list_del_init(&cgrp->release_list);
4371         raw_spin_unlock(&release_list_lock);
4372
4373         /*
4374          * If @cgrp has css's attached, the second stage of cgroup
4375          * destruction is kicked off from css_killed_work_fn() after the
4376          * refs of all attached css's are killed.  If @cgrp doesn't have
4377          * any css, we kick it off here.
4378          */
4379         if (!cgrp->nr_css)
4380                 cgroup_destroy_css_killed(cgrp);
4381
4382         /*
4383          * Clear the base files and remove @cgrp directory.  The removal
4384          * puts the base ref but we aren't quite done with @cgrp yet, so
4385          * hold onto it.
4386          */
4387         cgroup_addrm_files(cgrp, cgroup_base_files, false);
4388         dget(d);
4389         cgroup_d_remove_dir(d);
4390
4391         return 0;
4392 };
4393
4394 /**
4395  * cgroup_destroy_css_killed - the second step of cgroup destruction
4396  * @work: cgroup->destroy_free_work
4397  *
4398  * This function is invoked from a work item for a cgroup which is being
4399  * destroyed after all css's are offlined and performs the rest of
4400  * destruction.  This is the second step of destruction described in the
4401  * comment above cgroup_destroy_locked().
4402  */
4403 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
4404 {
4405         struct cgroup *parent = cgrp->parent;
4406         struct dentry *d = cgrp->dentry;
4407
4408         lockdep_assert_held(&cgroup_mutex);
4409
4410         /* delete this cgroup from parent->children */
4411         list_del_rcu(&cgrp->sibling);
4412
4413         dput(d);
4414
4415         set_bit(CGRP_RELEASABLE, &parent->flags);
4416         check_for_release(parent);
4417 }
4418
4419 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4420 {
4421         int ret;
4422
4423         mutex_lock(&cgroup_mutex);
4424         ret = cgroup_destroy_locked(dentry->d_fsdata);
4425         mutex_unlock(&cgroup_mutex);
4426
4427         return ret;
4428 }
4429
4430 static void __init cgroup_init_cftsets(struct cgroup_subsys *ss)
4431 {
4432         INIT_LIST_HEAD(&ss->cftsets);
4433
4434         /*
4435          * base_cftset is embedded in subsys itself, no need to worry about
4436          * deregistration.
4437          */
4438         if (ss->base_cftypes) {
4439                 struct cftype *cft;
4440
4441                 for (cft = ss->base_cftypes; cft->name[0] != '\0'; cft++)
4442                         cft->ss = ss;
4443
4444                 ss->base_cftset.cfts = ss->base_cftypes;
4445                 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4446         }
4447 }
4448
4449 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4450 {
4451         struct cgroup_subsys_state *css;
4452
4453         printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4454
4455         mutex_lock(&cgroup_mutex);
4456
4457         /* init base cftset */
4458         cgroup_init_cftsets(ss);
4459
4460         /* Create the top cgroup state for this subsystem */
4461         ss->root = &cgroup_dummy_root;
4462         css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
4463         /* We don't handle early failures gracefully */
4464         BUG_ON(IS_ERR(css));
4465         init_css(css, ss, cgroup_dummy_top);
4466
4467         /* Update the init_css_set to contain a subsys
4468          * pointer to this state - since the subsystem is
4469          * newly registered, all tasks and hence the
4470          * init_css_set is in the subsystem's top cgroup. */
4471         init_css_set.subsys[ss->id] = css;
4472
4473         need_forkexit_callback |= ss->fork || ss->exit;
4474
4475         /* At system boot, before all subsystems have been
4476          * registered, no tasks have been forked, so we don't
4477          * need to invoke fork callbacks here. */
4478         BUG_ON(!list_empty(&init_task.tasks));
4479
4480         BUG_ON(online_css(css));
4481
4482         mutex_unlock(&cgroup_mutex);
4483 }
4484
4485 /**
4486  * cgroup_init_early - cgroup initialization at system boot
4487  *
4488  * Initialize cgroups at system boot, and initialize any
4489  * subsystems that request early init.
4490  */
4491 int __init cgroup_init_early(void)
4492 {
4493         struct cgroup_subsys *ss;
4494         int i;
4495
4496         atomic_set(&init_css_set.refcount, 1);
4497         INIT_LIST_HEAD(&init_css_set.cgrp_links);
4498         INIT_LIST_HEAD(&init_css_set.tasks);
4499         INIT_HLIST_NODE(&init_css_set.hlist);
4500         css_set_count = 1;
4501         init_cgroup_root(&cgroup_dummy_root);
4502         cgroup_root_count = 1;
4503         RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
4504
4505         init_cgrp_cset_link.cset = &init_css_set;
4506         init_cgrp_cset_link.cgrp = cgroup_dummy_top;
4507         list_add(&init_cgrp_cset_link.cset_link, &cgroup_dummy_top->cset_links);
4508         list_add(&init_cgrp_cset_link.cgrp_link, &init_css_set.cgrp_links);
4509
4510         for_each_subsys(ss, i) {
4511                 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
4512                      "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
4513                      i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
4514                      ss->id, ss->name);
4515                 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
4516                      "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
4517
4518                 ss->id = i;
4519                 ss->name = cgroup_subsys_name[i];
4520
4521                 if (ss->early_init)
4522                         cgroup_init_subsys(ss);
4523         }
4524         return 0;
4525 }
4526
4527 /**
4528  * cgroup_init - cgroup initialization
4529  *
4530  * Register cgroup filesystem and /proc file, and initialize
4531  * any subsystems that didn't request early init.
4532  */
4533 int __init cgroup_init(void)
4534 {
4535         struct cgroup_subsys *ss;
4536         unsigned long key;
4537         int i, err;
4538
4539         err = bdi_init(&cgroup_backing_dev_info);
4540         if (err)
4541                 return err;
4542
4543         for_each_subsys(ss, i) {
4544                 if (!ss->early_init)
4545                         cgroup_init_subsys(ss);
4546         }
4547
4548         /* allocate id for the dummy hierarchy */
4549         mutex_lock(&cgroup_mutex);
4550
4551         /* Add init_css_set to the hash table */
4552         key = css_set_hash(init_css_set.subsys);
4553         hash_add(css_set_table, &init_css_set.hlist, key);
4554
4555         BUG_ON(cgroup_init_root_id(&cgroup_dummy_root, 0, 1));
4556
4557         err = idr_alloc(&cgroup_dummy_root.cgroup_idr, cgroup_dummy_top,
4558                         0, 1, GFP_KERNEL);
4559         BUG_ON(err < 0);
4560
4561         mutex_unlock(&cgroup_mutex);
4562
4563         cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4564         if (!cgroup_kobj) {
4565                 err = -ENOMEM;
4566                 goto out;
4567         }
4568
4569         err = register_filesystem(&cgroup_fs_type);
4570         if (err < 0) {
4571                 kobject_put(cgroup_kobj);
4572                 goto out;
4573         }
4574
4575         proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
4576
4577 out:
4578         if (err)
4579                 bdi_destroy(&cgroup_backing_dev_info);
4580
4581         return err;
4582 }
4583
4584 static int __init cgroup_wq_init(void)
4585 {
4586         /*
4587          * There isn't much point in executing destruction path in
4588          * parallel.  Good chunk is serialized with cgroup_mutex anyway.
4589          *
4590          * XXX: Must be ordered to make sure parent is offlined after
4591          * children.  The ordering requirement is for memcg where a
4592          * parent's offline may wait for a child's leading to deadlock.  In
4593          * the long term, this should be fixed from memcg side.
4594          *
4595          * We would prefer to do this in cgroup_init() above, but that
4596          * is called before init_workqueues(): so leave this until after.
4597          */
4598         cgroup_destroy_wq = alloc_ordered_workqueue("cgroup_destroy", 0);
4599         BUG_ON(!cgroup_destroy_wq);
4600
4601         /*
4602          * Used to destroy pidlists and separate to serve as flush domain.
4603          * Cap @max_active to 1 too.
4604          */
4605         cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
4606                                                     0, 1);
4607         BUG_ON(!cgroup_pidlist_destroy_wq);
4608
4609         return 0;
4610 }
4611 core_initcall(cgroup_wq_init);
4612
4613 /*
4614  * proc_cgroup_show()
4615  *  - Print task's cgroup paths into seq_file, one line for each hierarchy
4616  *  - Used for /proc/<pid>/cgroup.
4617  *  - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4618  *    doesn't really matter if tsk->cgroup changes after we read it,
4619  *    and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
4620  *    anyway.  No need to check that tsk->cgroup != NULL, thanks to
4621  *    the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4622  *    cgroup to top_cgroup.
4623  */
4624
4625 /* TODO: Use a proper seq_file iterator */
4626 int proc_cgroup_show(struct seq_file *m, void *v)
4627 {
4628         struct pid *pid;
4629         struct task_struct *tsk;
4630         char *buf;
4631         int retval;
4632         struct cgroupfs_root *root;
4633
4634         retval = -ENOMEM;
4635         buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4636         if (!buf)
4637                 goto out;
4638
4639         retval = -ESRCH;
4640         pid = m->private;
4641         tsk = get_pid_task(pid, PIDTYPE_PID);
4642         if (!tsk)
4643                 goto out_free;
4644
4645         retval = 0;
4646
4647         mutex_lock(&cgroup_mutex);
4648
4649         for_each_active_root(root) {
4650                 struct cgroup_subsys *ss;
4651                 struct cgroup *cgrp;
4652                 int ssid, count = 0;
4653
4654                 seq_printf(m, "%d:", root->hierarchy_id);
4655                 for_each_subsys(ss, ssid)
4656                         if (root->subsys_mask & (1 << ssid))
4657                                 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
4658                 if (strlen(root->name))
4659                         seq_printf(m, "%sname=%s", count ? "," : "",
4660                                    root->name);
4661                 seq_putc(m, ':');
4662                 cgrp = task_cgroup_from_root(tsk, root);
4663                 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
4664                 if (retval < 0)
4665                         goto out_unlock;
4666                 seq_puts(m, buf);
4667                 seq_putc(m, '\n');
4668         }
4669
4670 out_unlock:
4671         mutex_unlock(&cgroup_mutex);
4672         put_task_struct(tsk);
4673 out_free:
4674         kfree(buf);
4675 out:
4676         return retval;
4677 }
4678
4679 /* Display information about each subsystem and each hierarchy */
4680 static int proc_cgroupstats_show(struct seq_file *m, void *v)
4681 {
4682         struct cgroup_subsys *ss;
4683         int i;
4684
4685         seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
4686         /*
4687          * ideally we don't want subsystems moving around while we do this.
4688          * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4689          * subsys/hierarchy state.
4690          */
4691         mutex_lock(&cgroup_mutex);
4692
4693         for_each_subsys(ss, i)
4694                 seq_printf(m, "%s\t%d\t%d\t%d\n",
4695                            ss->name, ss->root->hierarchy_id,
4696                            ss->root->number_of_cgroups, !ss->disabled);
4697
4698         mutex_unlock(&cgroup_mutex);
4699         return 0;
4700 }
4701
4702 static int cgroupstats_open(struct inode *inode, struct file *file)
4703 {
4704         return single_open(file, proc_cgroupstats_show, NULL);
4705 }
4706
4707 static const struct file_operations proc_cgroupstats_operations = {
4708         .open = cgroupstats_open,
4709         .read = seq_read,
4710         .llseek = seq_lseek,
4711         .release = single_release,
4712 };
4713
4714 /**
4715  * cgroup_fork - attach newly forked task to its parents cgroup.
4716  * @child: pointer to task_struct of forking parent process.
4717  *
4718  * Description: A task inherits its parent's cgroup at fork().
4719  *
4720  * A pointer to the shared css_set was automatically copied in
4721  * fork.c by dup_task_struct().  However, we ignore that copy, since
4722  * it was not made under the protection of RCU or cgroup_mutex, so
4723  * might no longer be a valid cgroup pointer.  cgroup_attach_task() might
4724  * have already changed current->cgroups, allowing the previously
4725  * referenced cgroup group to be removed and freed.
4726  *
4727  * At the point that cgroup_fork() is called, 'current' is the parent
4728  * task, and the passed argument 'child' points to the child task.
4729  */
4730 void cgroup_fork(struct task_struct *child)
4731 {
4732         task_lock(current);
4733         get_css_set(task_css_set(current));
4734         child->cgroups = current->cgroups;
4735         task_unlock(current);
4736         INIT_LIST_HEAD(&child->cg_list);
4737 }
4738
4739 /**
4740  * cgroup_post_fork - called on a new task after adding it to the task list
4741  * @child: the task in question
4742  *
4743  * Adds the task to the list running through its css_set if necessary and
4744  * call the subsystem fork() callbacks.  Has to be after the task is
4745  * visible on the task list in case we race with the first call to
4746  * cgroup_task_iter_start() - to guarantee that the new task ends up on its
4747  * list.
4748  */
4749 void cgroup_post_fork(struct task_struct *child)
4750 {
4751         struct cgroup_subsys *ss;
4752         int i;
4753
4754         /*
4755          * use_task_css_set_links is set to 1 before we walk the tasklist
4756          * under the tasklist_lock and we read it here after we added the child
4757          * to the tasklist under the tasklist_lock as well. If the child wasn't
4758          * yet in the tasklist when we walked through it from
4759          * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4760          * should be visible now due to the paired locking and barriers implied
4761          * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4762          * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4763          * lock on fork.
4764          */
4765         if (use_task_css_set_links) {
4766                 write_lock(&css_set_lock);
4767                 task_lock(child);
4768                 if (list_empty(&child->cg_list))
4769                         list_add(&child->cg_list, &task_css_set(child)->tasks);
4770                 task_unlock(child);
4771                 write_unlock(&css_set_lock);
4772         }
4773
4774         /*
4775          * Call ss->fork().  This must happen after @child is linked on
4776          * css_set; otherwise, @child might change state between ->fork()
4777          * and addition to css_set.
4778          */
4779         if (need_forkexit_callback) {
4780                 for_each_subsys(ss, i)
4781                         if (ss->fork)
4782                                 ss->fork(child);
4783         }
4784 }
4785
4786 /**
4787  * cgroup_exit - detach cgroup from exiting task
4788  * @tsk: pointer to task_struct of exiting process
4789  * @run_callback: run exit callbacks?
4790  *
4791  * Description: Detach cgroup from @tsk and release it.
4792  *
4793  * Note that cgroups marked notify_on_release force every task in
4794  * them to take the global cgroup_mutex mutex when exiting.
4795  * This could impact scaling on very large systems.  Be reluctant to
4796  * use notify_on_release cgroups where very high task exit scaling
4797  * is required on large systems.
4798  *
4799  * the_top_cgroup_hack:
4800  *
4801  *    Set the exiting tasks cgroup to the root cgroup (top_cgroup).
4802  *
4803  *    We call cgroup_exit() while the task is still competent to
4804  *    handle notify_on_release(), then leave the task attached to the
4805  *    root cgroup in each hierarchy for the remainder of its exit.
4806  *
4807  *    To do this properly, we would increment the reference count on
4808  *    top_cgroup, and near the very end of the kernel/exit.c do_exit()
4809  *    code we would add a second cgroup function call, to drop that
4810  *    reference.  This would just create an unnecessary hot spot on
4811  *    the top_cgroup reference count, to no avail.
4812  *
4813  *    Normally, holding a reference to a cgroup without bumping its
4814  *    count is unsafe.   The cgroup could go away, or someone could
4815  *    attach us to a different cgroup, decrementing the count on
4816  *    the first cgroup that we never incremented.  But in this case,
4817  *    top_cgroup isn't going away, and either task has PF_EXITING set,
4818  *    which wards off any cgroup_attach_task() attempts, or task is a failed
4819  *    fork, never visible to cgroup_attach_task.
4820  */
4821 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
4822 {
4823         struct cgroup_subsys *ss;
4824         struct css_set *cset;
4825         int i;
4826
4827         /*
4828          * Unlink from the css_set task list if necessary.
4829          * Optimistically check cg_list before taking
4830          * css_set_lock
4831          */
4832         if (!list_empty(&tsk->cg_list)) {
4833                 write_lock(&css_set_lock);
4834                 if (!list_empty(&tsk->cg_list))
4835                         list_del_init(&tsk->cg_list);
4836                 write_unlock(&css_set_lock);
4837         }
4838
4839         /* Reassign the task to the init_css_set. */
4840         task_lock(tsk);
4841         cset = task_css_set(tsk);
4842         RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
4843
4844         if (run_callbacks && need_forkexit_callback) {
4845                 /* see cgroup_post_fork() for details */
4846                 for_each_subsys(ss, i) {
4847                         if (ss->exit) {
4848                                 struct cgroup_subsys_state *old_css = cset->subsys[i];
4849                                 struct cgroup_subsys_state *css = task_css(tsk, i);
4850
4851                                 ss->exit(css, old_css, tsk);
4852                         }
4853                 }
4854         }
4855         task_unlock(tsk);
4856
4857         put_css_set_taskexit(cset);
4858 }
4859
4860 static void check_for_release(struct cgroup *cgrp)
4861 {
4862         if (cgroup_is_releasable(cgrp) &&
4863             list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
4864                 /*
4865                  * Control Group is currently removeable. If it's not
4866                  * already queued for a userspace notification, queue
4867                  * it now
4868                  */
4869                 int need_schedule_work = 0;
4870
4871                 raw_spin_lock(&release_list_lock);
4872                 if (!cgroup_is_dead(cgrp) &&
4873                     list_empty(&cgrp->release_list)) {
4874                         list_add(&cgrp->release_list, &release_list);
4875                         need_schedule_work = 1;
4876                 }
4877                 raw_spin_unlock(&release_list_lock);
4878                 if (need_schedule_work)
4879                         schedule_work(&release_agent_work);
4880         }
4881 }
4882
4883 /*
4884  * Notify userspace when a cgroup is released, by running the
4885  * configured release agent with the name of the cgroup (path
4886  * relative to the root of cgroup file system) as the argument.
4887  *
4888  * Most likely, this user command will try to rmdir this cgroup.
4889  *
4890  * This races with the possibility that some other task will be
4891  * attached to this cgroup before it is removed, or that some other
4892  * user task will 'mkdir' a child cgroup of this cgroup.  That's ok.
4893  * The presumed 'rmdir' will fail quietly if this cgroup is no longer
4894  * unused, and this cgroup will be reprieved from its death sentence,
4895  * to continue to serve a useful existence.  Next time it's released,
4896  * we will get notified again, if it still has 'notify_on_release' set.
4897  *
4898  * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
4899  * means only wait until the task is successfully execve()'d.  The
4900  * separate release agent task is forked by call_usermodehelper(),
4901  * then control in this thread returns here, without waiting for the
4902  * release agent task.  We don't bother to wait because the caller of
4903  * this routine has no use for the exit status of the release agent
4904  * task, so no sense holding our caller up for that.
4905  */
4906 static void cgroup_release_agent(struct work_struct *work)
4907 {
4908         BUG_ON(work != &release_agent_work);
4909         mutex_lock(&cgroup_mutex);
4910         raw_spin_lock(&release_list_lock);
4911         while (!list_empty(&release_list)) {
4912                 char *argv[3], *envp[3];
4913                 int i;
4914                 char *pathbuf = NULL, *agentbuf = NULL;
4915                 struct cgroup *cgrp = list_entry(release_list.next,
4916                                                     struct cgroup,
4917                                                     release_list);
4918                 list_del_init(&cgrp->release_list);
4919                 raw_spin_unlock(&release_list_lock);
4920                 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4921                 if (!pathbuf)
4922                         goto continue_free;
4923                 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
4924                         goto continue_free;
4925                 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
4926                 if (!agentbuf)
4927                         goto continue_free;
4928
4929                 i = 0;
4930                 argv[i++] = agentbuf;
4931                 argv[i++] = pathbuf;
4932                 argv[i] = NULL;
4933
4934                 i = 0;
4935                 /* minimal command environment */
4936                 envp[i++] = "HOME=/";
4937                 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
4938                 envp[i] = NULL;
4939
4940                 /* Drop the lock while we invoke the usermode helper,
4941                  * since the exec could involve hitting disk and hence
4942                  * be a slow process */
4943                 mutex_unlock(&cgroup_mutex);
4944                 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
4945                 mutex_lock(&cgroup_mutex);
4946  continue_free:
4947                 kfree(pathbuf);
4948                 kfree(agentbuf);
4949                 raw_spin_lock(&release_list_lock);
4950         }
4951         raw_spin_unlock(&release_list_lock);
4952         mutex_unlock(&cgroup_mutex);
4953 }
4954
4955 static int __init cgroup_disable(char *str)
4956 {
4957         struct cgroup_subsys *ss;
4958         char *token;
4959         int i;
4960
4961         while ((token = strsep(&str, ",")) != NULL) {
4962                 if (!*token)
4963                         continue;
4964
4965                 for_each_subsys(ss, i) {
4966                         if (!strcmp(token, ss->name)) {
4967                                 ss->disabled = 1;
4968                                 printk(KERN_INFO "Disabling %s control group"
4969                                         " subsystem\n", ss->name);
4970                                 break;
4971                         }
4972                 }
4973         }
4974         return 1;
4975 }
4976 __setup("cgroup_disable=", cgroup_disable);
4977
4978 /**
4979  * css_from_dir - get corresponding css from the dentry of a cgroup dir
4980  * @dentry: directory dentry of interest
4981  * @ss: subsystem of interest
4982  *
4983  * Must be called under cgroup_mutex or RCU read lock.  The caller is
4984  * responsible for pinning the returned css if it needs to be accessed
4985  * outside the critical section.
4986  */
4987 struct cgroup_subsys_state *css_from_dir(struct dentry *dentry,
4988                                          struct cgroup_subsys *ss)
4989 {
4990         struct cgroup *cgrp;
4991
4992         cgroup_assert_mutex_or_rcu_locked();
4993
4994         /* is @dentry a cgroup dir? */
4995         if (!dentry->d_inode ||
4996             dentry->d_inode->i_op != &cgroup_dir_inode_operations)
4997                 return ERR_PTR(-EBADF);
4998
4999         cgrp = __d_cgrp(dentry);
5000         return cgroup_css(cgrp, ss) ?: ERR_PTR(-ENOENT);
5001 }
5002
5003 /**
5004  * css_from_id - lookup css by id
5005  * @id: the cgroup id
5006  * @ss: cgroup subsys to be looked into
5007  *
5008  * Returns the css if there's valid one with @id, otherwise returns NULL.
5009  * Should be called under rcu_read_lock().
5010  */
5011 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5012 {
5013         struct cgroup *cgrp;
5014
5015         cgroup_assert_mutex_or_rcu_locked();
5016
5017         cgrp = idr_find(&ss->root->cgroup_idr, id);
5018         if (cgrp)
5019                 return cgroup_css(cgrp, ss);
5020         return NULL;
5021 }
5022
5023 #ifdef CONFIG_CGROUP_DEBUG
5024 static struct cgroup_subsys_state *
5025 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5026 {
5027         struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5028
5029         if (!css)
5030                 return ERR_PTR(-ENOMEM);
5031
5032         return css;
5033 }
5034
5035 static void debug_css_free(struct cgroup_subsys_state *css)
5036 {
5037         kfree(css);
5038 }
5039
5040 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5041                                 struct cftype *cft)
5042 {
5043         return cgroup_task_count(css->cgroup);
5044 }
5045
5046 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5047                                 struct cftype *cft)
5048 {
5049         return (u64)(unsigned long)current->cgroups;
5050 }
5051
5052 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5053                                          struct cftype *cft)
5054 {
5055         u64 count;
5056
5057         rcu_read_lock();
5058         count = atomic_read(&task_css_set(current)->refcount);
5059         rcu_read_unlock();
5060         return count;
5061 }
5062
5063 static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
5064 {
5065         struct cgrp_cset_link *link;
5066         struct css_set *cset;
5067
5068         read_lock(&css_set_lock);
5069         rcu_read_lock();
5070         cset = rcu_dereference(current->cgroups);
5071         list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5072                 struct cgroup *c = link->cgrp;
5073                 const char *name;
5074
5075                 if (c->dentry)
5076                         name = c->dentry->d_name.name;
5077                 else
5078                         name = "?";
5079                 seq_printf(seq, "Root %d group %s\n",
5080                            c->root->hierarchy_id, name);
5081         }
5082         rcu_read_unlock();
5083         read_unlock(&css_set_lock);
5084         return 0;
5085 }
5086
5087 #define MAX_TASKS_SHOWN_PER_CSS 25
5088 static int cgroup_css_links_read(struct seq_file *seq, void *v)
5089 {
5090         struct cgroup_subsys_state *css = seq_css(seq);
5091         struct cgrp_cset_link *link;
5092
5093         read_lock(&css_set_lock);
5094         list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5095                 struct css_set *cset = link->cset;
5096                 struct task_struct *task;
5097                 int count = 0;
5098                 seq_printf(seq, "css_set %p\n", cset);
5099                 list_for_each_entry(task, &cset->tasks, cg_list) {
5100                         if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5101                                 seq_puts(seq, "  ...\n");
5102                                 break;
5103                         } else {
5104                                 seq_printf(seq, "  task %d\n",
5105                                            task_pid_vnr(task));
5106                         }
5107                 }
5108         }
5109         read_unlock(&css_set_lock);
5110         return 0;
5111 }
5112
5113 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5114 {
5115         return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
5116 }
5117
5118 static struct cftype debug_files[] =  {
5119         {
5120                 .name = "taskcount",
5121                 .read_u64 = debug_taskcount_read,
5122         },
5123
5124         {
5125                 .name = "current_css_set",
5126                 .read_u64 = current_css_set_read,
5127         },
5128
5129         {
5130                 .name = "current_css_set_refcount",
5131                 .read_u64 = current_css_set_refcount_read,
5132         },
5133
5134         {
5135                 .name = "current_css_set_cg_links",
5136                 .seq_show = current_css_set_cg_links_read,
5137         },
5138
5139         {
5140                 .name = "cgroup_css_links",
5141                 .seq_show = cgroup_css_links_read,
5142         },
5143
5144         {
5145                 .name = "releasable",
5146                 .read_u64 = releasable_read,
5147         },
5148
5149         { }     /* terminate */
5150 };
5151
5152 struct cgroup_subsys debug_cgrp_subsys = {
5153         .css_alloc = debug_css_alloc,
5154         .css_free = debug_css_free,
5155         .base_cftypes = debug_files,
5156 };
5157 #endif /* CONFIG_CGROUP_DEBUG */