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