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