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