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