]> git.karo-electronics.de Git - karo-tx-linux.git/blob - kernel/cgroup.c
shrinker: add node awareness
[karo-tx-linux.git] / kernel / cgroup.c
1 /*
2  *  Generic process-grouping system.
3  *
4  *  Based originally on the cpuset system, extracted by Paul Menage
5  *  Copyright (C) 2006 Google, Inc
6  *
7  *  Notifications support
8  *  Copyright (C) 2009 Nokia Corporation
9  *  Author: Kirill A. Shutemov
10  *
11  *  Copyright notices from the original cpuset code:
12  *  --------------------------------------------------
13  *  Copyright (C) 2003 BULL SA.
14  *  Copyright (C) 2004-2006 Silicon Graphics, Inc.
15  *
16  *  Portions derived from Patrick Mochel's sysfs code.
17  *  sysfs is Copyright (c) 2001-3 Patrick Mochel
18  *
19  *  2003-10-10 Written by Simon Derr.
20  *  2003-10-22 Updates by Stephen Hemminger.
21  *  2004 May-July Rework by Paul Jackson.
22  *  ---------------------------------------------------
23  *
24  *  This file is subject to the terms and conditions of the GNU General Public
25  *  License.  See the file COPYING in the main directory of the Linux
26  *  distribution for more details.
27  */
28
29 #include <linux/cgroup.h>
30 #include <linux/cred.h>
31 #include <linux/ctype.h>
32 #include <linux/errno.h>
33 #include <linux/init_task.h>
34 #include <linux/kernel.h>
35 #include <linux/list.h>
36 #include <linux/mm.h>
37 #include <linux/mutex.h>
38 #include <linux/mount.h>
39 #include <linux/pagemap.h>
40 #include <linux/proc_fs.h>
41 #include <linux/rcupdate.h>
42 #include <linux/sched.h>
43 #include <linux/backing-dev.h>
44 #include <linux/seq_file.h>
45 #include <linux/slab.h>
46 #include <linux/magic.h>
47 #include <linux/spinlock.h>
48 #include <linux/string.h>
49 #include <linux/sort.h>
50 #include <linux/kmod.h>
51 #include <linux/module.h>
52 #include <linux/delayacct.h>
53 #include <linux/cgroupstats.h>
54 #include <linux/hashtable.h>
55 #include <linux/namei.h>
56 #include <linux/pid_namespace.h>
57 #include <linux/idr.h>
58 #include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
59 #include <linux/eventfd.h>
60 #include <linux/poll.h>
61 #include <linux/flex_array.h> /* used in cgroup_attach_task */
62 #include <linux/kthread.h>
63
64 #include <linux/atomic.h>
65
66 /*
67  * cgroup_mutex is the master lock.  Any modification to cgroup or its
68  * hierarchy must be performed while holding it.
69  *
70  * cgroup_root_mutex nests inside cgroup_mutex and should be held to modify
71  * cgroupfs_root of any cgroup hierarchy - subsys list, flags,
72  * release_agent_path and so on.  Modifying requires both cgroup_mutex and
73  * cgroup_root_mutex.  Readers can acquire either of the two.  This is to
74  * break the following locking order cycle.
75  *
76  *  A. cgroup_mutex -> cred_guard_mutex -> s_type->i_mutex_key -> namespace_sem
77  *  B. namespace_sem -> cgroup_mutex
78  *
79  * B happens only through cgroup_show_options() and using cgroup_root_mutex
80  * breaks it.
81  */
82 #ifdef CONFIG_PROVE_RCU
83 DEFINE_MUTEX(cgroup_mutex);
84 EXPORT_SYMBOL_GPL(cgroup_mutex);        /* only for lockdep */
85 #else
86 static DEFINE_MUTEX(cgroup_mutex);
87 #endif
88
89 static DEFINE_MUTEX(cgroup_root_mutex);
90
91 /*
92  * Generate an array of cgroup subsystem pointers. At boot time, this is
93  * populated with the built in subsystems, and modular subsystems are
94  * registered after that. The mutable section of this array is protected by
95  * cgroup_mutex.
96  */
97 #define SUBSYS(_x) [_x ## _subsys_id] = &_x ## _subsys,
98 #define IS_SUBSYS_ENABLED(option) IS_BUILTIN(option)
99 static struct cgroup_subsys *cgroup_subsys[CGROUP_SUBSYS_COUNT] = {
100 #include <linux/cgroup_subsys.h>
101 };
102
103 /*
104  * The dummy hierarchy, reserved for the subsystems that are otherwise
105  * unattached - it never has more than a single cgroup, and all tasks are
106  * part of that cgroup.
107  */
108 static struct cgroupfs_root cgroup_dummy_root;
109
110 /* dummy_top is a shorthand for the dummy hierarchy's top cgroup */
111 static struct cgroup * const cgroup_dummy_top = &cgroup_dummy_root.top_cgroup;
112
113 /*
114  * cgroupfs file entry, pointed to from leaf dentry->d_fsdata.
115  */
116 struct cfent {
117         struct list_head                node;
118         struct dentry                   *dentry;
119         struct cftype                   *type;
120         struct cgroup_subsys_state      *css;
121
122         /* file xattrs */
123         struct simple_xattrs            xattrs;
124 };
125
126 /*
127  * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when
128  * cgroup_subsys->use_id != 0.
129  */
130 #define CSS_ID_MAX      (65535)
131 struct css_id {
132         /*
133          * The css to which this ID points. This pointer is set to valid value
134          * after cgroup is populated. If cgroup is removed, this will be NULL.
135          * This pointer is expected to be RCU-safe because destroy()
136          * is called after synchronize_rcu(). But for safe use, css_tryget()
137          * should be used for avoiding race.
138          */
139         struct cgroup_subsys_state __rcu *css;
140         /*
141          * ID of this css.
142          */
143         unsigned short id;
144         /*
145          * Depth in hierarchy which this ID belongs to.
146          */
147         unsigned short depth;
148         /*
149          * ID is freed by RCU. (and lookup routine is RCU safe.)
150          */
151         struct rcu_head rcu_head;
152         /*
153          * Hierarchy of CSS ID belongs to.
154          */
155         unsigned short stack[0]; /* Array of Length (depth+1) */
156 };
157
158 /*
159  * cgroup_event represents events which userspace want to receive.
160  */
161 struct cgroup_event {
162         /*
163          * css which the event belongs to.
164          */
165         struct cgroup_subsys_state *css;
166         /*
167          * Control file which the event associated.
168          */
169         struct cftype *cft;
170         /*
171          * eventfd to signal userspace about the event.
172          */
173         struct eventfd_ctx *eventfd;
174         /*
175          * Each of these stored in a list by the cgroup.
176          */
177         struct list_head list;
178         /*
179          * All fields below needed to unregister event when
180          * userspace closes eventfd.
181          */
182         poll_table pt;
183         wait_queue_head_t *wqh;
184         wait_queue_t wait;
185         struct work_struct remove;
186 };
187
188 /* The list of hierarchy roots */
189
190 static LIST_HEAD(cgroup_roots);
191 static int cgroup_root_count;
192
193 /*
194  * Hierarchy ID allocation and mapping.  It follows the same exclusion
195  * rules as other root ops - both cgroup_mutex and cgroup_root_mutex for
196  * writes, either for reads.
197  */
198 static DEFINE_IDR(cgroup_hierarchy_idr);
199
200 static struct cgroup_name root_cgroup_name = { .name = "/" };
201
202 /*
203  * Assign a monotonically increasing serial number to cgroups.  It
204  * guarantees cgroups with bigger numbers are newer than those with smaller
205  * numbers.  Also, as cgroups are always appended to the parent's
206  * ->children list, it guarantees that sibling cgroups are always sorted in
207  * the ascending serial number order on the list.  Protected by
208  * cgroup_mutex.
209  */
210 static u64 cgroup_serial_nr_next = 1;
211
212 /* This flag indicates whether tasks in the fork and exit paths should
213  * check for fork/exit handlers to call. This avoids us having to do
214  * extra work in the fork/exit path if none of the subsystems need to
215  * be called.
216  */
217 static int need_forkexit_callback __read_mostly;
218
219 static struct cftype cgroup_base_files[];
220
221 static void cgroup_destroy_css_killed(struct cgroup *cgrp);
222 static int cgroup_destroy_locked(struct cgroup *cgrp);
223 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
224                               bool is_add);
225
226 /**
227  * cgroup_css - obtain a cgroup's css for the specified subsystem
228  * @cgrp: the cgroup of interest
229  * @subsys_id: the subsystem of interest
230  *
231  * Return @cgrp's css (cgroup_subsys_state) associated with @subsys_id.
232  * This function must be called either under cgroup_mutex or
233  * rcu_read_lock() and the caller is responsible for pinning the returned
234  * css if it wants to keep accessing it outside the said locks.  This
235  * function may return %NULL if @cgrp doesn't have @subsys_id enabled.
236  */
237 static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
238                                               int subsys_id)
239 {
240         return rcu_dereference_check(cgrp->subsys[subsys_id],
241                                      lockdep_is_held(&cgroup_mutex));
242 }
243
244 /* convenient tests for these bits */
245 static inline bool cgroup_is_dead(const struct cgroup *cgrp)
246 {
247         return test_bit(CGRP_DEAD, &cgrp->flags);
248 }
249
250 /**
251  * cgroup_is_descendant - test ancestry
252  * @cgrp: the cgroup to be tested
253  * @ancestor: possible ancestor of @cgrp
254  *
255  * Test whether @cgrp is a descendant of @ancestor.  It also returns %true
256  * if @cgrp == @ancestor.  This function is safe to call as long as @cgrp
257  * and @ancestor are accessible.
258  */
259 bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
260 {
261         while (cgrp) {
262                 if (cgrp == ancestor)
263                         return true;
264                 cgrp = cgrp->parent;
265         }
266         return false;
267 }
268 EXPORT_SYMBOL_GPL(cgroup_is_descendant);
269
270 static int cgroup_is_releasable(const struct cgroup *cgrp)
271 {
272         const int bits =
273                 (1 << CGRP_RELEASABLE) |
274                 (1 << CGRP_NOTIFY_ON_RELEASE);
275         return (cgrp->flags & bits) == bits;
276 }
277
278 static int notify_on_release(const struct cgroup *cgrp)
279 {
280         return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
281 }
282
283 /**
284  * for_each_subsys - iterate all loaded cgroup subsystems
285  * @ss: the iteration cursor
286  * @i: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
287  *
288  * Should be called under cgroup_mutex.
289  */
290 #define for_each_subsys(ss, i)                                          \
291         for ((i) = 0; (i) < CGROUP_SUBSYS_COUNT; (i)++)                 \
292                 if (({ lockdep_assert_held(&cgroup_mutex);              \
293                        !((ss) = cgroup_subsys[i]); })) { }              \
294                 else
295
296 /**
297  * for_each_builtin_subsys - iterate all built-in cgroup subsystems
298  * @ss: the iteration cursor
299  * @i: the index of @ss, CGROUP_BUILTIN_SUBSYS_COUNT after reaching the end
300  *
301  * Bulit-in subsystems are always present and iteration itself doesn't
302  * require any synchronization.
303  */
304 #define for_each_builtin_subsys(ss, i)                                  \
305         for ((i) = 0; (i) < CGROUP_BUILTIN_SUBSYS_COUNT &&              \
306              (((ss) = cgroup_subsys[i]) || true); (i)++)
307
308 /* iterate each subsystem attached to a hierarchy */
309 #define for_each_root_subsys(root, ss)                                  \
310         list_for_each_entry((ss), &(root)->subsys_list, sibling)
311
312 /* iterate across the active hierarchies */
313 #define for_each_active_root(root)                                      \
314         list_for_each_entry((root), &cgroup_roots, root_list)
315
316 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
317 {
318         return dentry->d_fsdata;
319 }
320
321 static inline struct cfent *__d_cfe(struct dentry *dentry)
322 {
323         return dentry->d_fsdata;
324 }
325
326 static inline struct cftype *__d_cft(struct dentry *dentry)
327 {
328         return __d_cfe(dentry)->type;
329 }
330
331 /**
332  * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
333  * @cgrp: the cgroup to be checked for liveness
334  *
335  * On success, returns true; the mutex should be later unlocked.  On
336  * failure returns false with no lock held.
337  */
338 static bool cgroup_lock_live_group(struct cgroup *cgrp)
339 {
340         mutex_lock(&cgroup_mutex);
341         if (cgroup_is_dead(cgrp)) {
342                 mutex_unlock(&cgroup_mutex);
343                 return false;
344         }
345         return true;
346 }
347
348 /* the list of cgroups eligible for automatic release. Protected by
349  * release_list_lock */
350 static LIST_HEAD(release_list);
351 static DEFINE_RAW_SPINLOCK(release_list_lock);
352 static void cgroup_release_agent(struct work_struct *work);
353 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
354 static void check_for_release(struct cgroup *cgrp);
355
356 /*
357  * A cgroup can be associated with multiple css_sets as different tasks may
358  * belong to different cgroups on different hierarchies.  In the other
359  * direction, a css_set is naturally associated with multiple cgroups.
360  * This M:N relationship is represented by the following link structure
361  * which exists for each association and allows traversing the associations
362  * from both sides.
363  */
364 struct cgrp_cset_link {
365         /* the cgroup and css_set this link associates */
366         struct cgroup           *cgrp;
367         struct css_set          *cset;
368
369         /* list of cgrp_cset_links anchored at cgrp->cset_links */
370         struct list_head        cset_link;
371
372         /* list of cgrp_cset_links anchored at css_set->cgrp_links */
373         struct list_head        cgrp_link;
374 };
375
376 /* The default css_set - used by init and its children prior to any
377  * hierarchies being mounted. It contains a pointer to the root state
378  * for each subsystem. Also used to anchor the list of css_sets. Not
379  * reference-counted, to improve performance when child cgroups
380  * haven't been created.
381  */
382
383 static struct css_set init_css_set;
384 static struct cgrp_cset_link init_cgrp_cset_link;
385
386 static int cgroup_init_idr(struct cgroup_subsys *ss,
387                            struct cgroup_subsys_state *css);
388
389 /*
390  * css_set_lock protects the list of css_set objects, and the chain of
391  * tasks off each css_set.  Nests outside task->alloc_lock due to
392  * css_task_iter_start().
393  */
394 static DEFINE_RWLOCK(css_set_lock);
395 static int css_set_count;
396
397 /*
398  * hash table for cgroup groups. This improves the performance to find
399  * an existing css_set. This hash doesn't (currently) take into
400  * account cgroups in empty hierarchies.
401  */
402 #define CSS_SET_HASH_BITS       7
403 static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
404
405 static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
406 {
407         unsigned long key = 0UL;
408         struct cgroup_subsys *ss;
409         int i;
410
411         for_each_subsys(ss, i)
412                 key += (unsigned long)css[i];
413         key = (key >> 16) ^ key;
414
415         return key;
416 }
417
418 /*
419  * We don't maintain the lists running through each css_set to its task
420  * until after the first call to css_task_iter_start().  This reduces the
421  * fork()/exit() overhead for people who have cgroups compiled into their
422  * kernel but not actually in use.
423  */
424 static int use_task_css_set_links __read_mostly;
425
426 static void __put_css_set(struct css_set *cset, int taskexit)
427 {
428         struct cgrp_cset_link *link, *tmp_link;
429
430         /*
431          * Ensure that the refcount doesn't hit zero while any readers
432          * can see it. Similar to atomic_dec_and_lock(), but for an
433          * rwlock
434          */
435         if (atomic_add_unless(&cset->refcount, -1, 1))
436                 return;
437         write_lock(&css_set_lock);
438         if (!atomic_dec_and_test(&cset->refcount)) {
439                 write_unlock(&css_set_lock);
440                 return;
441         }
442
443         /* This css_set is dead. unlink it and release cgroup refcounts */
444         hash_del(&cset->hlist);
445         css_set_count--;
446
447         list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
448                 struct cgroup *cgrp = link->cgrp;
449
450                 list_del(&link->cset_link);
451                 list_del(&link->cgrp_link);
452
453                 /* @cgrp can't go away while we're holding css_set_lock */
454                 if (list_empty(&cgrp->cset_links) && notify_on_release(cgrp)) {
455                         if (taskexit)
456                                 set_bit(CGRP_RELEASABLE, &cgrp->flags);
457                         check_for_release(cgrp);
458                 }
459
460                 kfree(link);
461         }
462
463         write_unlock(&css_set_lock);
464         kfree_rcu(cset, rcu_head);
465 }
466
467 /*
468  * refcounted get/put for css_set objects
469  */
470 static inline void get_css_set(struct css_set *cset)
471 {
472         atomic_inc(&cset->refcount);
473 }
474
475 static inline void put_css_set(struct css_set *cset)
476 {
477         __put_css_set(cset, 0);
478 }
479
480 static inline void put_css_set_taskexit(struct css_set *cset)
481 {
482         __put_css_set(cset, 1);
483 }
484
485 /**
486  * compare_css_sets - helper function for find_existing_css_set().
487  * @cset: candidate css_set being tested
488  * @old_cset: existing css_set for a task
489  * @new_cgrp: cgroup that's being entered by the task
490  * @template: desired set of css pointers in css_set (pre-calculated)
491  *
492  * Returns true if "cset" matches "old_cset" except for the hierarchy
493  * which "new_cgrp" belongs to, for which it should match "new_cgrp".
494  */
495 static bool compare_css_sets(struct css_set *cset,
496                              struct css_set *old_cset,
497                              struct cgroup *new_cgrp,
498                              struct cgroup_subsys_state *template[])
499 {
500         struct list_head *l1, *l2;
501
502         if (memcmp(template, cset->subsys, sizeof(cset->subsys))) {
503                 /* Not all subsystems matched */
504                 return false;
505         }
506
507         /*
508          * Compare cgroup pointers in order to distinguish between
509          * different cgroups in heirarchies with no subsystems. We
510          * could get by with just this check alone (and skip the
511          * memcmp above) but on most setups the memcmp check will
512          * avoid the need for this more expensive check on almost all
513          * candidates.
514          */
515
516         l1 = &cset->cgrp_links;
517         l2 = &old_cset->cgrp_links;
518         while (1) {
519                 struct cgrp_cset_link *link1, *link2;
520                 struct cgroup *cgrp1, *cgrp2;
521
522                 l1 = l1->next;
523                 l2 = l2->next;
524                 /* See if we reached the end - both lists are equal length. */
525                 if (l1 == &cset->cgrp_links) {
526                         BUG_ON(l2 != &old_cset->cgrp_links);
527                         break;
528                 } else {
529                         BUG_ON(l2 == &old_cset->cgrp_links);
530                 }
531                 /* Locate the cgroups associated with these links. */
532                 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
533                 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
534                 cgrp1 = link1->cgrp;
535                 cgrp2 = link2->cgrp;
536                 /* Hierarchies should be linked in the same order. */
537                 BUG_ON(cgrp1->root != cgrp2->root);
538
539                 /*
540                  * If this hierarchy is the hierarchy of the cgroup
541                  * that's changing, then we need to check that this
542                  * css_set points to the new cgroup; if it's any other
543                  * hierarchy, then this css_set should point to the
544                  * same cgroup as the old css_set.
545                  */
546                 if (cgrp1->root == new_cgrp->root) {
547                         if (cgrp1 != new_cgrp)
548                                 return false;
549                 } else {
550                         if (cgrp1 != cgrp2)
551                                 return false;
552                 }
553         }
554         return true;
555 }
556
557 /**
558  * find_existing_css_set - init css array and find the matching css_set
559  * @old_cset: the css_set that we're using before the cgroup transition
560  * @cgrp: the cgroup that we're moving into
561  * @template: out param for the new set of csses, should be clear on entry
562  */
563 static struct css_set *find_existing_css_set(struct css_set *old_cset,
564                                         struct cgroup *cgrp,
565                                         struct cgroup_subsys_state *template[])
566 {
567         struct cgroupfs_root *root = cgrp->root;
568         struct cgroup_subsys *ss;
569         struct css_set *cset;
570         unsigned long key;
571         int i;
572
573         /*
574          * Build the set of subsystem state objects that we want to see in the
575          * new css_set. while subsystems can change globally, the entries here
576          * won't change, so no need for locking.
577          */
578         for_each_subsys(ss, i) {
579                 if (root->subsys_mask & (1UL << i)) {
580                         /* Subsystem is in this hierarchy. So we want
581                          * the subsystem state from the new
582                          * cgroup */
583                         template[i] = cgroup_css(cgrp, i);
584                 } else {
585                         /* Subsystem is not in this hierarchy, so we
586                          * don't want to change the subsystem state */
587                         template[i] = old_cset->subsys[i];
588                 }
589         }
590
591         key = css_set_hash(template);
592         hash_for_each_possible(css_set_table, cset, hlist, key) {
593                 if (!compare_css_sets(cset, old_cset, cgrp, template))
594                         continue;
595
596                 /* This css_set matches what we need */
597                 return cset;
598         }
599
600         /* No existing cgroup group matched */
601         return NULL;
602 }
603
604 static void free_cgrp_cset_links(struct list_head *links_to_free)
605 {
606         struct cgrp_cset_link *link, *tmp_link;
607
608         list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
609                 list_del(&link->cset_link);
610                 kfree(link);
611         }
612 }
613
614 /**
615  * allocate_cgrp_cset_links - allocate cgrp_cset_links
616  * @count: the number of links to allocate
617  * @tmp_links: list_head the allocated links are put on
618  *
619  * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
620  * through ->cset_link.  Returns 0 on success or -errno.
621  */
622 static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
623 {
624         struct cgrp_cset_link *link;
625         int i;
626
627         INIT_LIST_HEAD(tmp_links);
628
629         for (i = 0; i < count; i++) {
630                 link = kzalloc(sizeof(*link), GFP_KERNEL);
631                 if (!link) {
632                         free_cgrp_cset_links(tmp_links);
633                         return -ENOMEM;
634                 }
635                 list_add(&link->cset_link, tmp_links);
636         }
637         return 0;
638 }
639
640 /**
641  * link_css_set - a helper function to link a css_set to a cgroup
642  * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
643  * @cset: the css_set to be linked
644  * @cgrp: the destination cgroup
645  */
646 static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
647                          struct cgroup *cgrp)
648 {
649         struct cgrp_cset_link *link;
650
651         BUG_ON(list_empty(tmp_links));
652         link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
653         link->cset = cset;
654         link->cgrp = cgrp;
655         list_move(&link->cset_link, &cgrp->cset_links);
656         /*
657          * Always add links to the tail of the list so that the list
658          * is sorted by order of hierarchy creation
659          */
660         list_add_tail(&link->cgrp_link, &cset->cgrp_links);
661 }
662
663 /**
664  * find_css_set - return a new css_set with one cgroup updated
665  * @old_cset: the baseline css_set
666  * @cgrp: the cgroup to be updated
667  *
668  * Return a new css_set that's equivalent to @old_cset, but with @cgrp
669  * substituted into the appropriate hierarchy.
670  */
671 static struct css_set *find_css_set(struct css_set *old_cset,
672                                     struct cgroup *cgrp)
673 {
674         struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
675         struct css_set *cset;
676         struct list_head tmp_links;
677         struct cgrp_cset_link *link;
678         unsigned long key;
679
680         lockdep_assert_held(&cgroup_mutex);
681
682         /* First see if we already have a cgroup group that matches
683          * the desired set */
684         read_lock(&css_set_lock);
685         cset = find_existing_css_set(old_cset, cgrp, template);
686         if (cset)
687                 get_css_set(cset);
688         read_unlock(&css_set_lock);
689
690         if (cset)
691                 return cset;
692
693         cset = kzalloc(sizeof(*cset), GFP_KERNEL);
694         if (!cset)
695                 return NULL;
696
697         /* Allocate all the cgrp_cset_link objects that we'll need */
698         if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
699                 kfree(cset);
700                 return NULL;
701         }
702
703         atomic_set(&cset->refcount, 1);
704         INIT_LIST_HEAD(&cset->cgrp_links);
705         INIT_LIST_HEAD(&cset->tasks);
706         INIT_HLIST_NODE(&cset->hlist);
707
708         /* Copy the set of subsystem state objects generated in
709          * find_existing_css_set() */
710         memcpy(cset->subsys, template, sizeof(cset->subsys));
711
712         write_lock(&css_set_lock);
713         /* Add reference counts and links from the new css_set. */
714         list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
715                 struct cgroup *c = link->cgrp;
716
717                 if (c->root == cgrp->root)
718                         c = cgrp;
719                 link_css_set(&tmp_links, cset, c);
720         }
721
722         BUG_ON(!list_empty(&tmp_links));
723
724         css_set_count++;
725
726         /* Add this cgroup group to the hash table */
727         key = css_set_hash(cset->subsys);
728         hash_add(css_set_table, &cset->hlist, key);
729
730         write_unlock(&css_set_lock);
731
732         return cset;
733 }
734
735 /*
736  * Return the cgroup for "task" from the given hierarchy. Must be
737  * called with cgroup_mutex held.
738  */
739 static struct cgroup *task_cgroup_from_root(struct task_struct *task,
740                                             struct cgroupfs_root *root)
741 {
742         struct css_set *cset;
743         struct cgroup *res = NULL;
744
745         BUG_ON(!mutex_is_locked(&cgroup_mutex));
746         read_lock(&css_set_lock);
747         /*
748          * No need to lock the task - since we hold cgroup_mutex the
749          * task can't change groups, so the only thing that can happen
750          * is that it exits and its css is set back to init_css_set.
751          */
752         cset = task_css_set(task);
753         if (cset == &init_css_set) {
754                 res = &root->top_cgroup;
755         } else {
756                 struct cgrp_cset_link *link;
757
758                 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
759                         struct cgroup *c = link->cgrp;
760
761                         if (c->root == root) {
762                                 res = c;
763                                 break;
764                         }
765                 }
766         }
767         read_unlock(&css_set_lock);
768         BUG_ON(!res);
769         return res;
770 }
771
772 /*
773  * There is one global cgroup mutex. We also require taking
774  * task_lock() when dereferencing a task's cgroup subsys pointers.
775  * See "The task_lock() exception", at the end of this comment.
776  *
777  * A task must hold cgroup_mutex to modify cgroups.
778  *
779  * Any task can increment and decrement the count field without lock.
780  * So in general, code holding cgroup_mutex can't rely on the count
781  * field not changing.  However, if the count goes to zero, then only
782  * cgroup_attach_task() can increment it again.  Because a count of zero
783  * means that no tasks are currently attached, therefore there is no
784  * way a task attached to that cgroup can fork (the other way to
785  * increment the count).  So code holding cgroup_mutex can safely
786  * assume that if the count is zero, it will stay zero. Similarly, if
787  * a task holds cgroup_mutex on a cgroup with zero count, it
788  * knows that the cgroup won't be removed, as cgroup_rmdir()
789  * needs that mutex.
790  *
791  * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
792  * (usually) take cgroup_mutex.  These are the two most performance
793  * critical pieces of code here.  The exception occurs on cgroup_exit(),
794  * when a task in a notify_on_release cgroup exits.  Then cgroup_mutex
795  * is taken, and if the cgroup count is zero, a usermode call made
796  * to the release agent with the name of the cgroup (path relative to
797  * the root of cgroup file system) as the argument.
798  *
799  * A cgroup can only be deleted if both its 'count' of using tasks
800  * is zero, and its list of 'children' cgroups is empty.  Since all
801  * tasks in the system use _some_ cgroup, and since there is always at
802  * least one task in the system (init, pid == 1), therefore, top_cgroup
803  * always has either children cgroups and/or using tasks.  So we don't
804  * need a special hack to ensure that top_cgroup cannot be deleted.
805  *
806  *      The task_lock() exception
807  *
808  * The need for this exception arises from the action of
809  * cgroup_attach_task(), which overwrites one task's cgroup pointer with
810  * another.  It does so using cgroup_mutex, however there are
811  * several performance critical places that need to reference
812  * task->cgroup without the expense of grabbing a system global
813  * mutex.  Therefore except as noted below, when dereferencing or, as
814  * in cgroup_attach_task(), modifying a task's cgroup pointer we use
815  * task_lock(), which acts on a spinlock (task->alloc_lock) already in
816  * the task_struct routinely used for such matters.
817  *
818  * P.S.  One more locking exception.  RCU is used to guard the
819  * update of a tasks cgroup pointer by cgroup_attach_task()
820  */
821
822 /*
823  * A couple of forward declarations required, due to cyclic reference loop:
824  * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
825  * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
826  * -> cgroup_mkdir.
827  */
828
829 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode);
830 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
831 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask);
832 static const struct inode_operations cgroup_dir_inode_operations;
833 static const struct file_operations proc_cgroupstats_operations;
834
835 static struct backing_dev_info cgroup_backing_dev_info = {
836         .name           = "cgroup",
837         .capabilities   = BDI_CAP_NO_ACCT_AND_WRITEBACK,
838 };
839
840 static int alloc_css_id(struct cgroup_subsys_state *child_css);
841
842 static struct inode *cgroup_new_inode(umode_t mode, struct super_block *sb)
843 {
844         struct inode *inode = new_inode(sb);
845
846         if (inode) {
847                 inode->i_ino = get_next_ino();
848                 inode->i_mode = mode;
849                 inode->i_uid = current_fsuid();
850                 inode->i_gid = current_fsgid();
851                 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
852                 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
853         }
854         return inode;
855 }
856
857 static struct cgroup_name *cgroup_alloc_name(struct dentry *dentry)
858 {
859         struct cgroup_name *name;
860
861         name = kmalloc(sizeof(*name) + dentry->d_name.len + 1, GFP_KERNEL);
862         if (!name)
863                 return NULL;
864         strcpy(name->name, dentry->d_name.name);
865         return name;
866 }
867
868 static void cgroup_free_fn(struct work_struct *work)
869 {
870         struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
871
872         mutex_lock(&cgroup_mutex);
873         cgrp->root->number_of_cgroups--;
874         mutex_unlock(&cgroup_mutex);
875
876         /*
877          * We get a ref to the parent's dentry, and put the ref when
878          * this cgroup is being freed, so it's guaranteed that the
879          * parent won't be destroyed before its children.
880          */
881         dput(cgrp->parent->dentry);
882
883         /*
884          * Drop the active superblock reference that we took when we
885          * created the cgroup. This will free cgrp->root, if we are
886          * holding the last reference to @sb.
887          */
888         deactivate_super(cgrp->root->sb);
889
890         /*
891          * if we're getting rid of the cgroup, refcount should ensure
892          * that there are no pidlists left.
893          */
894         BUG_ON(!list_empty(&cgrp->pidlists));
895
896         simple_xattrs_free(&cgrp->xattrs);
897
898         kfree(rcu_dereference_raw(cgrp->name));
899         kfree(cgrp);
900 }
901
902 static void cgroup_free_rcu(struct rcu_head *head)
903 {
904         struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
905
906         INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
907         schedule_work(&cgrp->destroy_work);
908 }
909
910 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
911 {
912         /* is dentry a directory ? if so, kfree() associated cgroup */
913         if (S_ISDIR(inode->i_mode)) {
914                 struct cgroup *cgrp = dentry->d_fsdata;
915
916                 BUG_ON(!(cgroup_is_dead(cgrp)));
917                 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
918         } else {
919                 struct cfent *cfe = __d_cfe(dentry);
920                 struct cgroup *cgrp = dentry->d_parent->d_fsdata;
921
922                 WARN_ONCE(!list_empty(&cfe->node) &&
923                           cgrp != &cgrp->root->top_cgroup,
924                           "cfe still linked for %s\n", cfe->type->name);
925                 simple_xattrs_free(&cfe->xattrs);
926                 kfree(cfe);
927         }
928         iput(inode);
929 }
930
931 static int cgroup_delete(const struct dentry *d)
932 {
933         return 1;
934 }
935
936 static void remove_dir(struct dentry *d)
937 {
938         struct dentry *parent = dget(d->d_parent);
939
940         d_delete(d);
941         simple_rmdir(parent->d_inode, d);
942         dput(parent);
943 }
944
945 static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
946 {
947         struct cfent *cfe;
948
949         lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
950         lockdep_assert_held(&cgroup_mutex);
951
952         /*
953          * If we're doing cleanup due to failure of cgroup_create(),
954          * the corresponding @cfe may not exist.
955          */
956         list_for_each_entry(cfe, &cgrp->files, node) {
957                 struct dentry *d = cfe->dentry;
958
959                 if (cft && cfe->type != cft)
960                         continue;
961
962                 dget(d);
963                 d_delete(d);
964                 simple_unlink(cgrp->dentry->d_inode, d);
965                 list_del_init(&cfe->node);
966                 dput(d);
967
968                 break;
969         }
970 }
971
972 /**
973  * cgroup_clear_dir - remove subsys files in a cgroup directory
974  * @cgrp: target cgroup
975  * @subsys_mask: mask of the subsystem ids whose files should be removed
976  */
977 static void cgroup_clear_dir(struct cgroup *cgrp, unsigned long subsys_mask)
978 {
979         struct cgroup_subsys *ss;
980         int i;
981
982         for_each_subsys(ss, i) {
983                 struct cftype_set *set;
984
985                 if (!test_bit(i, &subsys_mask))
986                         continue;
987                 list_for_each_entry(set, &ss->cftsets, node)
988                         cgroup_addrm_files(cgrp, set->cfts, false);
989         }
990 }
991
992 /*
993  * NOTE : the dentry must have been dget()'ed
994  */
995 static void cgroup_d_remove_dir(struct dentry *dentry)
996 {
997         struct dentry *parent;
998
999         parent = dentry->d_parent;
1000         spin_lock(&parent->d_lock);
1001         spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
1002         list_del_init(&dentry->d_u.d_child);
1003         spin_unlock(&dentry->d_lock);
1004         spin_unlock(&parent->d_lock);
1005         remove_dir(dentry);
1006 }
1007
1008 /*
1009  * Call with cgroup_mutex held. Drops reference counts on modules, including
1010  * any duplicate ones that parse_cgroupfs_options took. If this function
1011  * returns an error, no reference counts are touched.
1012  */
1013 static int rebind_subsystems(struct cgroupfs_root *root,
1014                              unsigned long added_mask, unsigned removed_mask)
1015 {
1016         struct cgroup *cgrp = &root->top_cgroup;
1017         struct cgroup_subsys *ss;
1018         unsigned long pinned = 0;
1019         int i, ret;
1020
1021         BUG_ON(!mutex_is_locked(&cgroup_mutex));
1022         BUG_ON(!mutex_is_locked(&cgroup_root_mutex));
1023
1024         /* Check that any added subsystems are currently free */
1025         for_each_subsys(ss, i) {
1026                 if (!(added_mask & (1 << i)))
1027                         continue;
1028
1029                 /* is the subsystem mounted elsewhere? */
1030                 if (ss->root != &cgroup_dummy_root) {
1031                         ret = -EBUSY;
1032                         goto out_put;
1033                 }
1034
1035                 /* pin the module */
1036                 if (!try_module_get(ss->module)) {
1037                         ret = -ENOENT;
1038                         goto out_put;
1039                 }
1040                 pinned |= 1 << i;
1041         }
1042
1043         /* subsys could be missing if unloaded between parsing and here */
1044         if (added_mask != pinned) {
1045                 ret = -ENOENT;
1046                 goto out_put;
1047         }
1048
1049         ret = cgroup_populate_dir(cgrp, added_mask);
1050         if (ret)
1051                 goto out_put;
1052
1053         /*
1054          * Nothing can fail from this point on.  Remove files for the
1055          * removed subsystems and rebind each subsystem.
1056          */
1057         cgroup_clear_dir(cgrp, removed_mask);
1058
1059         for_each_subsys(ss, i) {
1060                 unsigned long bit = 1UL << i;
1061
1062                 if (bit & added_mask) {
1063                         /* We're binding this subsystem to this hierarchy */
1064                         BUG_ON(cgroup_css(cgrp, i));
1065                         BUG_ON(!cgroup_css(cgroup_dummy_top, i));
1066                         BUG_ON(cgroup_css(cgroup_dummy_top, i)->cgroup != cgroup_dummy_top);
1067
1068                         rcu_assign_pointer(cgrp->subsys[i],
1069                                            cgroup_css(cgroup_dummy_top, i));
1070                         cgroup_css(cgrp, i)->cgroup = cgrp;
1071
1072                         list_move(&ss->sibling, &root->subsys_list);
1073                         ss->root = root;
1074                         if (ss->bind)
1075                                 ss->bind(cgroup_css(cgrp, i));
1076
1077                         /* refcount was already taken, and we're keeping it */
1078                         root->subsys_mask |= bit;
1079                 } else if (bit & removed_mask) {
1080                         /* We're removing this subsystem */
1081                         BUG_ON(cgroup_css(cgrp, i) != cgroup_css(cgroup_dummy_top, i));
1082                         BUG_ON(cgroup_css(cgrp, i)->cgroup != cgrp);
1083
1084                         if (ss->bind)
1085                                 ss->bind(cgroup_css(cgroup_dummy_top, i));
1086
1087                         cgroup_css(cgroup_dummy_top, i)->cgroup = cgroup_dummy_top;
1088                         RCU_INIT_POINTER(cgrp->subsys[i], NULL);
1089
1090                         cgroup_subsys[i]->root = &cgroup_dummy_root;
1091                         list_move(&ss->sibling, &cgroup_dummy_root.subsys_list);
1092
1093                         /* subsystem is now free - drop reference on module */
1094                         module_put(ss->module);
1095                         root->subsys_mask &= ~bit;
1096                 }
1097         }
1098
1099         /*
1100          * Mark @root has finished binding subsystems.  @root->subsys_mask
1101          * now matches the bound subsystems.
1102          */
1103         root->flags |= CGRP_ROOT_SUBSYS_BOUND;
1104
1105         return 0;
1106
1107 out_put:
1108         for_each_subsys(ss, i)
1109                 if (pinned & (1 << i))
1110                         module_put(ss->module);
1111         return ret;
1112 }
1113
1114 static int cgroup_show_options(struct seq_file *seq, struct dentry *dentry)
1115 {
1116         struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
1117         struct cgroup_subsys *ss;
1118
1119         mutex_lock(&cgroup_root_mutex);
1120         for_each_root_subsys(root, ss)
1121                 seq_printf(seq, ",%s", ss->name);
1122         if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1123                 seq_puts(seq, ",sane_behavior");
1124         if (root->flags & CGRP_ROOT_NOPREFIX)
1125                 seq_puts(seq, ",noprefix");
1126         if (root->flags & CGRP_ROOT_XATTR)
1127                 seq_puts(seq, ",xattr");
1128         if (strlen(root->release_agent_path))
1129                 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
1130         if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
1131                 seq_puts(seq, ",clone_children");
1132         if (strlen(root->name))
1133                 seq_printf(seq, ",name=%s", root->name);
1134         mutex_unlock(&cgroup_root_mutex);
1135         return 0;
1136 }
1137
1138 struct cgroup_sb_opts {
1139         unsigned long subsys_mask;
1140         unsigned long flags;
1141         char *release_agent;
1142         bool cpuset_clone_children;
1143         char *name;
1144         /* User explicitly requested empty subsystem */
1145         bool none;
1146
1147         struct cgroupfs_root *new_root;
1148
1149 };
1150
1151 /*
1152  * Convert a hierarchy specifier into a bitmask of subsystems and
1153  * flags. Call with cgroup_mutex held to protect the cgroup_subsys[]
1154  * array. This function takes refcounts on subsystems to be used, unless it
1155  * returns error, in which case no refcounts are taken.
1156  */
1157 static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
1158 {
1159         char *token, *o = data;
1160         bool all_ss = false, one_ss = false;
1161         unsigned long mask = (unsigned long)-1;
1162         struct cgroup_subsys *ss;
1163         int i;
1164
1165         BUG_ON(!mutex_is_locked(&cgroup_mutex));
1166
1167 #ifdef CONFIG_CPUSETS
1168         mask = ~(1UL << cpuset_subsys_id);
1169 #endif
1170
1171         memset(opts, 0, sizeof(*opts));
1172
1173         while ((token = strsep(&o, ",")) != NULL) {
1174                 if (!*token)
1175                         return -EINVAL;
1176                 if (!strcmp(token, "none")) {
1177                         /* Explicitly have no subsystems */
1178                         opts->none = true;
1179                         continue;
1180                 }
1181                 if (!strcmp(token, "all")) {
1182                         /* Mutually exclusive option 'all' + subsystem name */
1183                         if (one_ss)
1184                                 return -EINVAL;
1185                         all_ss = true;
1186                         continue;
1187                 }
1188                 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1189                         opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1190                         continue;
1191                 }
1192                 if (!strcmp(token, "noprefix")) {
1193                         opts->flags |= CGRP_ROOT_NOPREFIX;
1194                         continue;
1195                 }
1196                 if (!strcmp(token, "clone_children")) {
1197                         opts->cpuset_clone_children = true;
1198                         continue;
1199                 }
1200                 if (!strcmp(token, "xattr")) {
1201                         opts->flags |= CGRP_ROOT_XATTR;
1202                         continue;
1203                 }
1204                 if (!strncmp(token, "release_agent=", 14)) {
1205                         /* Specifying two release agents is forbidden */
1206                         if (opts->release_agent)
1207                                 return -EINVAL;
1208                         opts->release_agent =
1209                                 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
1210                         if (!opts->release_agent)
1211                                 return -ENOMEM;
1212                         continue;
1213                 }
1214                 if (!strncmp(token, "name=", 5)) {
1215                         const char *name = token + 5;
1216                         /* Can't specify an empty name */
1217                         if (!strlen(name))
1218                                 return -EINVAL;
1219                         /* Must match [\w.-]+ */
1220                         for (i = 0; i < strlen(name); i++) {
1221                                 char c = name[i];
1222                                 if (isalnum(c))
1223                                         continue;
1224                                 if ((c == '.') || (c == '-') || (c == '_'))
1225                                         continue;
1226                                 return -EINVAL;
1227                         }
1228                         /* Specifying two names is forbidden */
1229                         if (opts->name)
1230                                 return -EINVAL;
1231                         opts->name = kstrndup(name,
1232                                               MAX_CGROUP_ROOT_NAMELEN - 1,
1233                                               GFP_KERNEL);
1234                         if (!opts->name)
1235                                 return -ENOMEM;
1236
1237                         continue;
1238                 }
1239
1240                 for_each_subsys(ss, i) {
1241                         if (strcmp(token, ss->name))
1242                                 continue;
1243                         if (ss->disabled)
1244                                 continue;
1245
1246                         /* Mutually exclusive option 'all' + subsystem name */
1247                         if (all_ss)
1248                                 return -EINVAL;
1249                         set_bit(i, &opts->subsys_mask);
1250                         one_ss = true;
1251
1252                         break;
1253                 }
1254                 if (i == CGROUP_SUBSYS_COUNT)
1255                         return -ENOENT;
1256         }
1257
1258         /*
1259          * If the 'all' option was specified select all the subsystems,
1260          * otherwise if 'none', 'name=' and a subsystem name options
1261          * were not specified, let's default to 'all'
1262          */
1263         if (all_ss || (!one_ss && !opts->none && !opts->name))
1264                 for_each_subsys(ss, i)
1265                         if (!ss->disabled)
1266                                 set_bit(i, &opts->subsys_mask);
1267
1268         /* Consistency checks */
1269
1270         if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1271                 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1272
1273                 if (opts->flags & CGRP_ROOT_NOPREFIX) {
1274                         pr_err("cgroup: sane_behavior: noprefix is not allowed\n");
1275                         return -EINVAL;
1276                 }
1277
1278                 if (opts->cpuset_clone_children) {
1279                         pr_err("cgroup: sane_behavior: clone_children is not allowed\n");
1280                         return -EINVAL;
1281                 }
1282         }
1283
1284         /*
1285          * Option noprefix was introduced just for backward compatibility
1286          * with the old cpuset, so we allow noprefix only if mounting just
1287          * the cpuset subsystem.
1288          */
1289         if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
1290                 return -EINVAL;
1291
1292
1293         /* Can't specify "none" and some subsystems */
1294         if (opts->subsys_mask && opts->none)
1295                 return -EINVAL;
1296
1297         /*
1298          * We either have to specify by name or by subsystems. (So all
1299          * empty hierarchies must have a name).
1300          */
1301         if (!opts->subsys_mask && !opts->name)
1302                 return -EINVAL;
1303
1304         return 0;
1305 }
1306
1307 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1308 {
1309         int ret = 0;
1310         struct cgroupfs_root *root = sb->s_fs_info;
1311         struct cgroup *cgrp = &root->top_cgroup;
1312         struct cgroup_sb_opts opts;
1313         unsigned long added_mask, removed_mask;
1314
1315         if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1316                 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1317                 return -EINVAL;
1318         }
1319
1320         mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1321         mutex_lock(&cgroup_mutex);
1322         mutex_lock(&cgroup_root_mutex);
1323
1324         /* See what subsystems are wanted */
1325         ret = parse_cgroupfs_options(data, &opts);
1326         if (ret)
1327                 goto out_unlock;
1328
1329         if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
1330                 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1331                            task_tgid_nr(current), current->comm);
1332
1333         added_mask = opts.subsys_mask & ~root->subsys_mask;
1334         removed_mask = root->subsys_mask & ~opts.subsys_mask;
1335
1336         /* Don't allow flags or name to change at remount */
1337         if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
1338             (opts.name && strcmp(opts.name, root->name))) {
1339                 pr_err("cgroup: option or name mismatch, new: 0x%lx \"%s\", old: 0x%lx \"%s\"\n",
1340                        opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1341                        root->flags & CGRP_ROOT_OPTION_MASK, root->name);
1342                 ret = -EINVAL;
1343                 goto out_unlock;
1344         }
1345
1346         /* remounting is not allowed for populated hierarchies */
1347         if (root->number_of_cgroups > 1) {
1348                 ret = -EBUSY;
1349                 goto out_unlock;
1350         }
1351
1352         ret = rebind_subsystems(root, added_mask, removed_mask);
1353         if (ret)
1354                 goto out_unlock;
1355
1356         if (opts.release_agent)
1357                 strcpy(root->release_agent_path, opts.release_agent);
1358  out_unlock:
1359         kfree(opts.release_agent);
1360         kfree(opts.name);
1361         mutex_unlock(&cgroup_root_mutex);
1362         mutex_unlock(&cgroup_mutex);
1363         mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1364         return ret;
1365 }
1366
1367 static const struct super_operations cgroup_ops = {
1368         .statfs = simple_statfs,
1369         .drop_inode = generic_delete_inode,
1370         .show_options = cgroup_show_options,
1371         .remount_fs = cgroup_remount,
1372 };
1373
1374 static void init_cgroup_housekeeping(struct cgroup *cgrp)
1375 {
1376         INIT_LIST_HEAD(&cgrp->sibling);
1377         INIT_LIST_HEAD(&cgrp->children);
1378         INIT_LIST_HEAD(&cgrp->files);
1379         INIT_LIST_HEAD(&cgrp->cset_links);
1380         INIT_LIST_HEAD(&cgrp->release_list);
1381         INIT_LIST_HEAD(&cgrp->pidlists);
1382         mutex_init(&cgrp->pidlist_mutex);
1383         cgrp->dummy_css.cgroup = cgrp;
1384         INIT_LIST_HEAD(&cgrp->event_list);
1385         spin_lock_init(&cgrp->event_list_lock);
1386         simple_xattrs_init(&cgrp->xattrs);
1387 }
1388
1389 static void init_cgroup_root(struct cgroupfs_root *root)
1390 {
1391         struct cgroup *cgrp = &root->top_cgroup;
1392
1393         INIT_LIST_HEAD(&root->subsys_list);
1394         INIT_LIST_HEAD(&root->root_list);
1395         root->number_of_cgroups = 1;
1396         cgrp->root = root;
1397         RCU_INIT_POINTER(cgrp->name, &root_cgroup_name);
1398         init_cgroup_housekeeping(cgrp);
1399         idr_init(&root->cgroup_idr);
1400 }
1401
1402 static int cgroup_init_root_id(struct cgroupfs_root *root, int start, int end)
1403 {
1404         int id;
1405
1406         lockdep_assert_held(&cgroup_mutex);
1407         lockdep_assert_held(&cgroup_root_mutex);
1408
1409         id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, start, end,
1410                               GFP_KERNEL);
1411         if (id < 0)
1412                 return id;
1413
1414         root->hierarchy_id = id;
1415         return 0;
1416 }
1417
1418 static void cgroup_exit_root_id(struct cgroupfs_root *root)
1419 {
1420         lockdep_assert_held(&cgroup_mutex);
1421         lockdep_assert_held(&cgroup_root_mutex);
1422
1423         if (root->hierarchy_id) {
1424                 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
1425                 root->hierarchy_id = 0;
1426         }
1427 }
1428
1429 static int cgroup_test_super(struct super_block *sb, void *data)
1430 {
1431         struct cgroup_sb_opts *opts = data;
1432         struct cgroupfs_root *root = sb->s_fs_info;
1433
1434         /* If we asked for a name then it must match */
1435         if (opts->name && strcmp(opts->name, root->name))
1436                 return 0;
1437
1438         /*
1439          * If we asked for subsystems (or explicitly for no
1440          * subsystems) then they must match
1441          */
1442         if ((opts->subsys_mask || opts->none)
1443             && (opts->subsys_mask != root->subsys_mask))
1444                 return 0;
1445
1446         return 1;
1447 }
1448
1449 static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1450 {
1451         struct cgroupfs_root *root;
1452
1453         if (!opts->subsys_mask && !opts->none)
1454                 return NULL;
1455
1456         root = kzalloc(sizeof(*root), GFP_KERNEL);
1457         if (!root)
1458                 return ERR_PTR(-ENOMEM);
1459
1460         init_cgroup_root(root);
1461
1462         /*
1463          * We need to set @root->subsys_mask now so that @root can be
1464          * matched by cgroup_test_super() before it finishes
1465          * initialization; otherwise, competing mounts with the same
1466          * options may try to bind the same subsystems instead of waiting
1467          * for the first one leading to unexpected mount errors.
1468          * SUBSYS_BOUND will be set once actual binding is complete.
1469          */
1470         root->subsys_mask = opts->subsys_mask;
1471         root->flags = opts->flags;
1472         if (opts->release_agent)
1473                 strcpy(root->release_agent_path, opts->release_agent);
1474         if (opts->name)
1475                 strcpy(root->name, opts->name);
1476         if (opts->cpuset_clone_children)
1477                 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
1478         return root;
1479 }
1480
1481 static void cgroup_free_root(struct cgroupfs_root *root)
1482 {
1483         if (root) {
1484                 /* hierarhcy ID shoulid already have been released */
1485                 WARN_ON_ONCE(root->hierarchy_id);
1486
1487                 idr_destroy(&root->cgroup_idr);
1488                 kfree(root);
1489         }
1490 }
1491
1492 static int cgroup_set_super(struct super_block *sb, void *data)
1493 {
1494         int ret;
1495         struct cgroup_sb_opts *opts = data;
1496
1497         /* If we don't have a new root, we can't set up a new sb */
1498         if (!opts->new_root)
1499                 return -EINVAL;
1500
1501         BUG_ON(!opts->subsys_mask && !opts->none);
1502
1503         ret = set_anon_super(sb, NULL);
1504         if (ret)
1505                 return ret;
1506
1507         sb->s_fs_info = opts->new_root;
1508         opts->new_root->sb = sb;
1509
1510         sb->s_blocksize = PAGE_CACHE_SIZE;
1511         sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1512         sb->s_magic = CGROUP_SUPER_MAGIC;
1513         sb->s_op = &cgroup_ops;
1514
1515         return 0;
1516 }
1517
1518 static int cgroup_get_rootdir(struct super_block *sb)
1519 {
1520         static const struct dentry_operations cgroup_dops = {
1521                 .d_iput = cgroup_diput,
1522                 .d_delete = cgroup_delete,
1523         };
1524
1525         struct inode *inode =
1526                 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
1527
1528         if (!inode)
1529                 return -ENOMEM;
1530
1531         inode->i_fop = &simple_dir_operations;
1532         inode->i_op = &cgroup_dir_inode_operations;
1533         /* directories start off with i_nlink == 2 (for "." entry) */
1534         inc_nlink(inode);
1535         sb->s_root = d_make_root(inode);
1536         if (!sb->s_root)
1537                 return -ENOMEM;
1538         /* for everything else we want ->d_op set */
1539         sb->s_d_op = &cgroup_dops;
1540         return 0;
1541 }
1542
1543 static struct dentry *cgroup_mount(struct file_system_type *fs_type,
1544                          int flags, const char *unused_dev_name,
1545                          void *data)
1546 {
1547         struct cgroup_sb_opts opts;
1548         struct cgroupfs_root *root;
1549         int ret = 0;
1550         struct super_block *sb;
1551         struct cgroupfs_root *new_root;
1552         struct list_head tmp_links;
1553         struct inode *inode;
1554         const struct cred *cred;
1555
1556         /* First find the desired set of subsystems */
1557         mutex_lock(&cgroup_mutex);
1558         ret = parse_cgroupfs_options(data, &opts);
1559         mutex_unlock(&cgroup_mutex);
1560         if (ret)
1561                 goto out_err;
1562
1563         /*
1564          * Allocate a new cgroup root. We may not need it if we're
1565          * reusing an existing hierarchy.
1566          */
1567         new_root = cgroup_root_from_opts(&opts);
1568         if (IS_ERR(new_root)) {
1569                 ret = PTR_ERR(new_root);
1570                 goto out_err;
1571         }
1572         opts.new_root = new_root;
1573
1574         /* Locate an existing or new sb for this hierarchy */
1575         sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
1576         if (IS_ERR(sb)) {
1577                 ret = PTR_ERR(sb);
1578                 cgroup_free_root(opts.new_root);
1579                 goto out_err;
1580         }
1581
1582         root = sb->s_fs_info;
1583         BUG_ON(!root);
1584         if (root == opts.new_root) {
1585                 /* We used the new root structure, so this is a new hierarchy */
1586                 struct cgroup *root_cgrp = &root->top_cgroup;
1587                 struct cgroupfs_root *existing_root;
1588                 int i;
1589                 struct css_set *cset;
1590
1591                 BUG_ON(sb->s_root != NULL);
1592
1593                 ret = cgroup_get_rootdir(sb);
1594                 if (ret)
1595                         goto drop_new_super;
1596                 inode = sb->s_root->d_inode;
1597
1598                 mutex_lock(&inode->i_mutex);
1599                 mutex_lock(&cgroup_mutex);
1600                 mutex_lock(&cgroup_root_mutex);
1601
1602                 root_cgrp->id = idr_alloc(&root->cgroup_idr, root_cgrp,
1603                                            0, 1, GFP_KERNEL);
1604                 if (root_cgrp->id < 0)
1605                         goto unlock_drop;
1606
1607                 /* Check for name clashes with existing mounts */
1608                 ret = -EBUSY;
1609                 if (strlen(root->name))
1610                         for_each_active_root(existing_root)
1611                                 if (!strcmp(existing_root->name, root->name))
1612                                         goto unlock_drop;
1613
1614                 /*
1615                  * We're accessing css_set_count without locking
1616                  * css_set_lock here, but that's OK - it can only be
1617                  * increased by someone holding cgroup_lock, and
1618                  * that's us. The worst that can happen is that we
1619                  * have some link structures left over
1620                  */
1621                 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1622                 if (ret)
1623                         goto unlock_drop;
1624
1625                 /* ID 0 is reserved for dummy root, 1 for unified hierarchy */
1626                 ret = cgroup_init_root_id(root, 2, 0);
1627                 if (ret)
1628                         goto unlock_drop;
1629
1630                 sb->s_root->d_fsdata = root_cgrp;
1631                 root_cgrp->dentry = sb->s_root;
1632
1633                 /*
1634                  * We're inside get_sb() and will call lookup_one_len() to
1635                  * create the root files, which doesn't work if SELinux is
1636                  * in use.  The following cred dancing somehow works around
1637                  * it.  See 2ce9738ba ("cgroupfs: use init_cred when
1638                  * populating new cgroupfs mount") for more details.
1639                  */
1640                 cred = override_creds(&init_cred);
1641
1642                 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1643                 if (ret)
1644                         goto rm_base_files;
1645
1646                 ret = rebind_subsystems(root, root->subsys_mask, 0);
1647                 if (ret)
1648                         goto rm_base_files;
1649
1650                 revert_creds(cred);
1651
1652                 /*
1653                  * There must be no failure case after here, since rebinding
1654                  * takes care of subsystems' refcounts, which are explicitly
1655                  * dropped in the failure exit path.
1656                  */
1657
1658                 list_add(&root->root_list, &cgroup_roots);
1659                 cgroup_root_count++;
1660
1661                 /* Link the top cgroup in this hierarchy into all
1662                  * the css_set objects */
1663                 write_lock(&css_set_lock);
1664                 hash_for_each(css_set_table, i, cset, hlist)
1665                         link_css_set(&tmp_links, cset, root_cgrp);
1666                 write_unlock(&css_set_lock);
1667
1668                 free_cgrp_cset_links(&tmp_links);
1669
1670                 BUG_ON(!list_empty(&root_cgrp->children));
1671                 BUG_ON(root->number_of_cgroups != 1);
1672
1673                 mutex_unlock(&cgroup_root_mutex);
1674                 mutex_unlock(&cgroup_mutex);
1675                 mutex_unlock(&inode->i_mutex);
1676         } else {
1677                 /*
1678                  * We re-used an existing hierarchy - the new root (if
1679                  * any) is not needed
1680                  */
1681                 cgroup_free_root(opts.new_root);
1682
1683                 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
1684                         if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1685                                 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1686                                 ret = -EINVAL;
1687                                 goto drop_new_super;
1688                         } else {
1689                                 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1690                         }
1691                 }
1692         }
1693
1694         kfree(opts.release_agent);
1695         kfree(opts.name);
1696         return dget(sb->s_root);
1697
1698  rm_base_files:
1699         free_cgrp_cset_links(&tmp_links);
1700         cgroup_addrm_files(&root->top_cgroup, cgroup_base_files, false);
1701         revert_creds(cred);
1702  unlock_drop:
1703         cgroup_exit_root_id(root);
1704         mutex_unlock(&cgroup_root_mutex);
1705         mutex_unlock(&cgroup_mutex);
1706         mutex_unlock(&inode->i_mutex);
1707  drop_new_super:
1708         deactivate_locked_super(sb);
1709  out_err:
1710         kfree(opts.release_agent);
1711         kfree(opts.name);
1712         return ERR_PTR(ret);
1713 }
1714
1715 static void cgroup_kill_sb(struct super_block *sb) {
1716         struct cgroupfs_root *root = sb->s_fs_info;
1717         struct cgroup *cgrp = &root->top_cgroup;
1718         struct cgrp_cset_link *link, *tmp_link;
1719         int ret;
1720
1721         BUG_ON(!root);
1722
1723         BUG_ON(root->number_of_cgroups != 1);
1724         BUG_ON(!list_empty(&cgrp->children));
1725
1726         mutex_lock(&cgrp->dentry->d_inode->i_mutex);
1727         mutex_lock(&cgroup_mutex);
1728         mutex_lock(&cgroup_root_mutex);
1729
1730         /* Rebind all subsystems back to the default hierarchy */
1731         if (root->flags & CGRP_ROOT_SUBSYS_BOUND) {
1732                 ret = rebind_subsystems(root, 0, root->subsys_mask);
1733                 /* Shouldn't be able to fail ... */
1734                 BUG_ON(ret);
1735         }
1736
1737         /*
1738          * Release all the links from cset_links to this hierarchy's
1739          * root cgroup
1740          */
1741         write_lock(&css_set_lock);
1742
1743         list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
1744                 list_del(&link->cset_link);
1745                 list_del(&link->cgrp_link);
1746                 kfree(link);
1747         }
1748         write_unlock(&css_set_lock);
1749
1750         if (!list_empty(&root->root_list)) {
1751                 list_del(&root->root_list);
1752                 cgroup_root_count--;
1753         }
1754
1755         cgroup_exit_root_id(root);
1756
1757         mutex_unlock(&cgroup_root_mutex);
1758         mutex_unlock(&cgroup_mutex);
1759         mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
1760
1761         simple_xattrs_free(&cgrp->xattrs);
1762
1763         kill_litter_super(sb);
1764         cgroup_free_root(root);
1765 }
1766
1767 static struct file_system_type cgroup_fs_type = {
1768         .name = "cgroup",
1769         .mount = cgroup_mount,
1770         .kill_sb = cgroup_kill_sb,
1771 };
1772
1773 static struct kobject *cgroup_kobj;
1774
1775 /**
1776  * cgroup_path - generate the path of a cgroup
1777  * @cgrp: the cgroup in question
1778  * @buf: the buffer to write the path into
1779  * @buflen: the length of the buffer
1780  *
1781  * Writes path of cgroup into buf.  Returns 0 on success, -errno on error.
1782  *
1783  * We can't generate cgroup path using dentry->d_name, as accessing
1784  * dentry->name must be protected by irq-unsafe dentry->d_lock or parent
1785  * inode's i_mutex, while on the other hand cgroup_path() can be called
1786  * with some irq-safe spinlocks held.
1787  */
1788 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1789 {
1790         int ret = -ENAMETOOLONG;
1791         char *start;
1792
1793         if (!cgrp->parent) {
1794                 if (strlcpy(buf, "/", buflen) >= buflen)
1795                         return -ENAMETOOLONG;
1796                 return 0;
1797         }
1798
1799         start = buf + buflen - 1;
1800         *start = '\0';
1801
1802         rcu_read_lock();
1803         do {
1804                 const char *name = cgroup_name(cgrp);
1805                 int len;
1806
1807                 len = strlen(name);
1808                 if ((start -= len) < buf)
1809                         goto out;
1810                 memcpy(start, name, len);
1811
1812                 if (--start < buf)
1813                         goto out;
1814                 *start = '/';
1815
1816                 cgrp = cgrp->parent;
1817         } while (cgrp->parent);
1818         ret = 0;
1819         memmove(buf, start, buf + buflen - start);
1820 out:
1821         rcu_read_unlock();
1822         return ret;
1823 }
1824 EXPORT_SYMBOL_GPL(cgroup_path);
1825
1826 /**
1827  * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
1828  * @task: target task
1829  * @buf: the buffer to write the path into
1830  * @buflen: the length of the buffer
1831  *
1832  * Determine @task's cgroup on the first (the one with the lowest non-zero
1833  * hierarchy_id) cgroup hierarchy and copy its path into @buf.  This
1834  * function grabs cgroup_mutex and shouldn't be used inside locks used by
1835  * cgroup controller callbacks.
1836  *
1837  * Returns 0 on success, fails with -%ENAMETOOLONG if @buflen is too short.
1838  */
1839 int task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
1840 {
1841         struct cgroupfs_root *root;
1842         struct cgroup *cgrp;
1843         int hierarchy_id = 1, ret = 0;
1844
1845         if (buflen < 2)
1846                 return -ENAMETOOLONG;
1847
1848         mutex_lock(&cgroup_mutex);
1849
1850         root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1851
1852         if (root) {
1853                 cgrp = task_cgroup_from_root(task, root);
1854                 ret = cgroup_path(cgrp, buf, buflen);
1855         } else {
1856                 /* if no hierarchy exists, everyone is in "/" */
1857                 memcpy(buf, "/", 2);
1858         }
1859
1860         mutex_unlock(&cgroup_mutex);
1861         return ret;
1862 }
1863 EXPORT_SYMBOL_GPL(task_cgroup_path);
1864
1865 /*
1866  * Control Group taskset
1867  */
1868 struct task_and_cgroup {
1869         struct task_struct      *task;
1870         struct cgroup           *cgrp;
1871         struct css_set          *cset;
1872 };
1873
1874 struct cgroup_taskset {
1875         struct task_and_cgroup  single;
1876         struct flex_array       *tc_array;
1877         int                     tc_array_len;
1878         int                     idx;
1879         struct cgroup           *cur_cgrp;
1880 };
1881
1882 /**
1883  * cgroup_taskset_first - reset taskset and return the first task
1884  * @tset: taskset of interest
1885  *
1886  * @tset iteration is initialized and the first task is returned.
1887  */
1888 struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1889 {
1890         if (tset->tc_array) {
1891                 tset->idx = 0;
1892                 return cgroup_taskset_next(tset);
1893         } else {
1894                 tset->cur_cgrp = tset->single.cgrp;
1895                 return tset->single.task;
1896         }
1897 }
1898 EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1899
1900 /**
1901  * cgroup_taskset_next - iterate to the next task in taskset
1902  * @tset: taskset of interest
1903  *
1904  * Return the next task in @tset.  Iteration must have been initialized
1905  * with cgroup_taskset_first().
1906  */
1907 struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1908 {
1909         struct task_and_cgroup *tc;
1910
1911         if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1912                 return NULL;
1913
1914         tc = flex_array_get(tset->tc_array, tset->idx++);
1915         tset->cur_cgrp = tc->cgrp;
1916         return tc->task;
1917 }
1918 EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1919
1920 /**
1921  * cgroup_taskset_cur_css - return the matching css for the current task
1922  * @tset: taskset of interest
1923  * @subsys_id: the ID of the target subsystem
1924  *
1925  * Return the css for the current (last returned) task of @tset for
1926  * subsystem specified by @subsys_id.  This function must be preceded by
1927  * either cgroup_taskset_first() or cgroup_taskset_next().
1928  */
1929 struct cgroup_subsys_state *cgroup_taskset_cur_css(struct cgroup_taskset *tset,
1930                                                    int subsys_id)
1931 {
1932         return cgroup_css(tset->cur_cgrp, subsys_id);
1933 }
1934 EXPORT_SYMBOL_GPL(cgroup_taskset_cur_css);
1935
1936 /**
1937  * cgroup_taskset_size - return the number of tasks in taskset
1938  * @tset: taskset of interest
1939  */
1940 int cgroup_taskset_size(struct cgroup_taskset *tset)
1941 {
1942         return tset->tc_array ? tset->tc_array_len : 1;
1943 }
1944 EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1945
1946
1947 /*
1948  * cgroup_task_migrate - move a task from one cgroup to another.
1949  *
1950  * Must be called with cgroup_mutex and threadgroup locked.
1951  */
1952 static void cgroup_task_migrate(struct cgroup *old_cgrp,
1953                                 struct task_struct *tsk,
1954                                 struct css_set *new_cset)
1955 {
1956         struct css_set *old_cset;
1957
1958         /*
1959          * We are synchronized through threadgroup_lock() against PF_EXITING
1960          * setting such that we can't race against cgroup_exit() changing the
1961          * css_set to init_css_set and dropping the old one.
1962          */
1963         WARN_ON_ONCE(tsk->flags & PF_EXITING);
1964         old_cset = task_css_set(tsk);
1965
1966         task_lock(tsk);
1967         rcu_assign_pointer(tsk->cgroups, new_cset);
1968         task_unlock(tsk);
1969
1970         /* Update the css_set linked lists if we're using them */
1971         write_lock(&css_set_lock);
1972         if (!list_empty(&tsk->cg_list))
1973                 list_move(&tsk->cg_list, &new_cset->tasks);
1974         write_unlock(&css_set_lock);
1975
1976         /*
1977          * We just gained a reference on old_cset by taking it from the
1978          * task. As trading it for new_cset is protected by cgroup_mutex,
1979          * we're safe to drop it here; it will be freed under RCU.
1980          */
1981         set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
1982         put_css_set(old_cset);
1983 }
1984
1985 /**
1986  * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1987  * @cgrp: the cgroup to attach to
1988  * @tsk: the task or the leader of the threadgroup to be attached
1989  * @threadgroup: attach the whole threadgroup?
1990  *
1991  * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
1992  * task_lock of @tsk or each thread in the threadgroup individually in turn.
1993  */
1994 static int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk,
1995                               bool threadgroup)
1996 {
1997         int retval, i, group_size;
1998         struct cgroup_subsys *ss, *failed_ss = NULL;
1999         struct cgroupfs_root *root = cgrp->root;
2000         /* threadgroup list cursor and array */
2001         struct task_struct *leader = tsk;
2002         struct task_and_cgroup *tc;
2003         struct flex_array *group;
2004         struct cgroup_taskset tset = { };
2005
2006         /*
2007          * step 0: in order to do expensive, possibly blocking operations for
2008          * every thread, we cannot iterate the thread group list, since it needs
2009          * rcu or tasklist locked. instead, build an array of all threads in the
2010          * group - group_rwsem prevents new threads from appearing, and if
2011          * threads exit, this will just be an over-estimate.
2012          */
2013         if (threadgroup)
2014                 group_size = get_nr_threads(tsk);
2015         else
2016                 group_size = 1;
2017         /* flex_array supports very large thread-groups better than kmalloc. */
2018         group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
2019         if (!group)
2020                 return -ENOMEM;
2021         /* pre-allocate to guarantee space while iterating in rcu read-side. */
2022         retval = flex_array_prealloc(group, 0, group_size, GFP_KERNEL);
2023         if (retval)
2024                 goto out_free_group_list;
2025
2026         i = 0;
2027         /*
2028          * Prevent freeing of tasks while we take a snapshot. Tasks that are
2029          * already PF_EXITING could be freed from underneath us unless we
2030          * take an rcu_read_lock.
2031          */
2032         rcu_read_lock();
2033         do {
2034                 struct task_and_cgroup ent;
2035
2036                 /* @tsk either already exited or can't exit until the end */
2037                 if (tsk->flags & PF_EXITING)
2038                         continue;
2039
2040                 /* as per above, nr_threads may decrease, but not increase. */
2041                 BUG_ON(i >= group_size);
2042                 ent.task = tsk;
2043                 ent.cgrp = task_cgroup_from_root(tsk, root);
2044                 /* nothing to do if this task is already in the cgroup */
2045                 if (ent.cgrp == cgrp)
2046                         continue;
2047                 /*
2048                  * saying GFP_ATOMIC has no effect here because we did prealloc
2049                  * earlier, but it's good form to communicate our expectations.
2050                  */
2051                 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
2052                 BUG_ON(retval != 0);
2053                 i++;
2054
2055                 if (!threadgroup)
2056                         break;
2057         } while_each_thread(leader, tsk);
2058         rcu_read_unlock();
2059         /* remember the number of threads in the array for later. */
2060         group_size = i;
2061         tset.tc_array = group;
2062         tset.tc_array_len = group_size;
2063
2064         /* methods shouldn't be called if no task is actually migrating */
2065         retval = 0;
2066         if (!group_size)
2067                 goto out_free_group_list;
2068
2069         /*
2070          * step 1: check that we can legitimately attach to the cgroup.
2071          */
2072         for_each_root_subsys(root, ss) {
2073                 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss->subsys_id);
2074
2075                 if (ss->can_attach) {
2076                         retval = ss->can_attach(css, &tset);
2077                         if (retval) {
2078                                 failed_ss = ss;
2079                                 goto out_cancel_attach;
2080                         }
2081                 }
2082         }
2083
2084         /*
2085          * step 2: make sure css_sets exist for all threads to be migrated.
2086          * we use find_css_set, which allocates a new one if necessary.
2087          */
2088         for (i = 0; i < group_size; i++) {
2089                 struct css_set *old_cset;
2090
2091                 tc = flex_array_get(group, i);
2092                 old_cset = task_css_set(tc->task);
2093                 tc->cset = find_css_set(old_cset, cgrp);
2094                 if (!tc->cset) {
2095                         retval = -ENOMEM;
2096                         goto out_put_css_set_refs;
2097                 }
2098         }
2099
2100         /*
2101          * step 3: now that we're guaranteed success wrt the css_sets,
2102          * proceed to move all tasks to the new cgroup.  There are no
2103          * failure cases after here, so this is the commit point.
2104          */
2105         for (i = 0; i < group_size; i++) {
2106                 tc = flex_array_get(group, i);
2107                 cgroup_task_migrate(tc->cgrp, tc->task, tc->cset);
2108         }
2109         /* nothing is sensitive to fork() after this point. */
2110
2111         /*
2112          * step 4: do subsystem attach callbacks.
2113          */
2114         for_each_root_subsys(root, ss) {
2115                 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss->subsys_id);
2116
2117                 if (ss->attach)
2118                         ss->attach(css, &tset);
2119         }
2120
2121         /*
2122          * step 5: success! and cleanup
2123          */
2124         retval = 0;
2125 out_put_css_set_refs:
2126         if (retval) {
2127                 for (i = 0; i < group_size; i++) {
2128                         tc = flex_array_get(group, i);
2129                         if (!tc->cset)
2130                                 break;
2131                         put_css_set(tc->cset);
2132                 }
2133         }
2134 out_cancel_attach:
2135         if (retval) {
2136                 for_each_root_subsys(root, ss) {
2137                         struct cgroup_subsys_state *css = cgroup_css(cgrp, ss->subsys_id);
2138
2139                         if (ss == failed_ss)
2140                                 break;
2141                         if (ss->cancel_attach)
2142                                 ss->cancel_attach(css, &tset);
2143                 }
2144         }
2145 out_free_group_list:
2146         flex_array_free(group);
2147         return retval;
2148 }
2149
2150 /*
2151  * Find the task_struct of the task to attach by vpid and pass it along to the
2152  * function to attach either it or all tasks in its threadgroup. Will lock
2153  * cgroup_mutex and threadgroup; may take task_lock of task.
2154  */
2155 static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
2156 {
2157         struct task_struct *tsk;
2158         const struct cred *cred = current_cred(), *tcred;
2159         int ret;
2160
2161         if (!cgroup_lock_live_group(cgrp))
2162                 return -ENODEV;
2163
2164 retry_find_task:
2165         rcu_read_lock();
2166         if (pid) {
2167                 tsk = find_task_by_vpid(pid);
2168                 if (!tsk) {
2169                         rcu_read_unlock();
2170                         ret= -ESRCH;
2171                         goto out_unlock_cgroup;
2172                 }
2173                 /*
2174                  * even if we're attaching all tasks in the thread group, we
2175                  * only need to check permissions on one of them.
2176                  */
2177                 tcred = __task_cred(tsk);
2178                 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2179                     !uid_eq(cred->euid, tcred->uid) &&
2180                     !uid_eq(cred->euid, tcred->suid)) {
2181                         rcu_read_unlock();
2182                         ret = -EACCES;
2183                         goto out_unlock_cgroup;
2184                 }
2185         } else
2186                 tsk = current;
2187
2188         if (threadgroup)
2189                 tsk = tsk->group_leader;
2190
2191         /*
2192          * Workqueue threads may acquire PF_NO_SETAFFINITY and become
2193          * trapped in a cpuset, or RT worker may be born in a cgroup
2194          * with no rt_runtime allocated.  Just say no.
2195          */
2196         if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
2197                 ret = -EINVAL;
2198                 rcu_read_unlock();
2199                 goto out_unlock_cgroup;
2200         }
2201
2202         get_task_struct(tsk);
2203         rcu_read_unlock();
2204
2205         threadgroup_lock(tsk);
2206         if (threadgroup) {
2207                 if (!thread_group_leader(tsk)) {
2208                         /*
2209                          * a race with de_thread from another thread's exec()
2210                          * may strip us of our leadership, if this happens,
2211                          * there is no choice but to throw this task away and
2212                          * try again; this is
2213                          * "double-double-toil-and-trouble-check locking".
2214                          */
2215                         threadgroup_unlock(tsk);
2216                         put_task_struct(tsk);
2217                         goto retry_find_task;
2218                 }
2219         }
2220
2221         ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2222
2223         threadgroup_unlock(tsk);
2224
2225         put_task_struct(tsk);
2226 out_unlock_cgroup:
2227         mutex_unlock(&cgroup_mutex);
2228         return ret;
2229 }
2230
2231 /**
2232  * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2233  * @from: attach to all cgroups of a given task
2234  * @tsk: the task to be attached
2235  */
2236 int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2237 {
2238         struct cgroupfs_root *root;
2239         int retval = 0;
2240
2241         mutex_lock(&cgroup_mutex);
2242         for_each_active_root(root) {
2243                 struct cgroup *from_cgrp = task_cgroup_from_root(from, root);
2244
2245                 retval = cgroup_attach_task(from_cgrp, tsk, false);
2246                 if (retval)
2247                         break;
2248         }
2249         mutex_unlock(&cgroup_mutex);
2250
2251         return retval;
2252 }
2253 EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2254
2255 static int cgroup_tasks_write(struct cgroup_subsys_state *css,
2256                               struct cftype *cft, u64 pid)
2257 {
2258         return attach_task_by_pid(css->cgroup, pid, false);
2259 }
2260
2261 static int cgroup_procs_write(struct cgroup_subsys_state *css,
2262                               struct cftype *cft, u64 tgid)
2263 {
2264         return attach_task_by_pid(css->cgroup, tgid, true);
2265 }
2266
2267 static int cgroup_release_agent_write(struct cgroup_subsys_state *css,
2268                                       struct cftype *cft, const char *buffer)
2269 {
2270         BUILD_BUG_ON(sizeof(css->cgroup->root->release_agent_path) < PATH_MAX);
2271         if (strlen(buffer) >= PATH_MAX)
2272                 return -EINVAL;
2273         if (!cgroup_lock_live_group(css->cgroup))
2274                 return -ENODEV;
2275         mutex_lock(&cgroup_root_mutex);
2276         strcpy(css->cgroup->root->release_agent_path, buffer);
2277         mutex_unlock(&cgroup_root_mutex);
2278         mutex_unlock(&cgroup_mutex);
2279         return 0;
2280 }
2281
2282 static int cgroup_release_agent_show(struct cgroup_subsys_state *css,
2283                                      struct cftype *cft, struct seq_file *seq)
2284 {
2285         struct cgroup *cgrp = css->cgroup;
2286
2287         if (!cgroup_lock_live_group(cgrp))
2288                 return -ENODEV;
2289         seq_puts(seq, cgrp->root->release_agent_path);
2290         seq_putc(seq, '\n');
2291         mutex_unlock(&cgroup_mutex);
2292         return 0;
2293 }
2294
2295 static int cgroup_sane_behavior_show(struct cgroup_subsys_state *css,
2296                                      struct cftype *cft, struct seq_file *seq)
2297 {
2298         seq_printf(seq, "%d\n", cgroup_sane_behavior(css->cgroup));
2299         return 0;
2300 }
2301
2302 /* A buffer size big enough for numbers or short strings */
2303 #define CGROUP_LOCAL_BUFFER_SIZE 64
2304
2305 static ssize_t cgroup_write_X64(struct cgroup_subsys_state *css,
2306                                 struct cftype *cft, struct file *file,
2307                                 const char __user *userbuf, size_t nbytes,
2308                                 loff_t *unused_ppos)
2309 {
2310         char buffer[CGROUP_LOCAL_BUFFER_SIZE];
2311         int retval = 0;
2312         char *end;
2313
2314         if (!nbytes)
2315                 return -EINVAL;
2316         if (nbytes >= sizeof(buffer))
2317                 return -E2BIG;
2318         if (copy_from_user(buffer, userbuf, nbytes))
2319                 return -EFAULT;
2320
2321         buffer[nbytes] = 0;     /* nul-terminate */
2322         if (cft->write_u64) {
2323                 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
2324                 if (*end)
2325                         return -EINVAL;
2326                 retval = cft->write_u64(css, cft, val);
2327         } else {
2328                 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
2329                 if (*end)
2330                         return -EINVAL;
2331                 retval = cft->write_s64(css, cft, val);
2332         }
2333         if (!retval)
2334                 retval = nbytes;
2335         return retval;
2336 }
2337
2338 static ssize_t cgroup_write_string(struct cgroup_subsys_state *css,
2339                                    struct cftype *cft, struct file *file,
2340                                    const char __user *userbuf, size_t nbytes,
2341                                    loff_t *unused_ppos)
2342 {
2343         char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
2344         int retval = 0;
2345         size_t max_bytes = cft->max_write_len;
2346         char *buffer = local_buffer;
2347
2348         if (!max_bytes)
2349                 max_bytes = sizeof(local_buffer) - 1;
2350         if (nbytes >= max_bytes)
2351                 return -E2BIG;
2352         /* Allocate a dynamic buffer if we need one */
2353         if (nbytes >= sizeof(local_buffer)) {
2354                 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2355                 if (buffer == NULL)
2356                         return -ENOMEM;
2357         }
2358         if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2359                 retval = -EFAULT;
2360                 goto out;
2361         }
2362
2363         buffer[nbytes] = 0;     /* nul-terminate */
2364         retval = cft->write_string(css, cft, strstrip(buffer));
2365         if (!retval)
2366                 retval = nbytes;
2367 out:
2368         if (buffer != local_buffer)
2369                 kfree(buffer);
2370         return retval;
2371 }
2372
2373 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2374                                  size_t nbytes, loff_t *ppos)
2375 {
2376         struct cfent *cfe = __d_cfe(file->f_dentry);
2377         struct cftype *cft = __d_cft(file->f_dentry);
2378         struct cgroup_subsys_state *css = cfe->css;
2379
2380         if (cft->write)
2381                 return cft->write(css, cft, file, buf, nbytes, ppos);
2382         if (cft->write_u64 || cft->write_s64)
2383                 return cgroup_write_X64(css, cft, file, buf, nbytes, ppos);
2384         if (cft->write_string)
2385                 return cgroup_write_string(css, cft, file, buf, nbytes, ppos);
2386         if (cft->trigger) {
2387                 int ret = cft->trigger(css, (unsigned int)cft->private);
2388                 return ret ? ret : nbytes;
2389         }
2390         return -EINVAL;
2391 }
2392
2393 static ssize_t cgroup_read_u64(struct cgroup_subsys_state *css,
2394                                struct cftype *cft, struct file *file,
2395                                char __user *buf, size_t nbytes, loff_t *ppos)
2396 {
2397         char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2398         u64 val = cft->read_u64(css, cft);
2399         int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2400
2401         return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2402 }
2403
2404 static ssize_t cgroup_read_s64(struct cgroup_subsys_state *css,
2405                                struct cftype *cft, struct file *file,
2406                                char __user *buf, size_t nbytes, loff_t *ppos)
2407 {
2408         char tmp[CGROUP_LOCAL_BUFFER_SIZE];
2409         s64 val = cft->read_s64(css, cft);
2410         int len = sprintf(tmp, "%lld\n", (long long) val);
2411
2412         return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2413 }
2414
2415 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2416                                 size_t nbytes, loff_t *ppos)
2417 {
2418         struct cfent *cfe = __d_cfe(file->f_dentry);
2419         struct cftype *cft = __d_cft(file->f_dentry);
2420         struct cgroup_subsys_state *css = cfe->css;
2421
2422         if (cft->read)
2423                 return cft->read(css, cft, file, buf, nbytes, ppos);
2424         if (cft->read_u64)
2425                 return cgroup_read_u64(css, cft, file, buf, nbytes, ppos);
2426         if (cft->read_s64)
2427                 return cgroup_read_s64(css, cft, file, buf, nbytes, ppos);
2428         return -EINVAL;
2429 }
2430
2431 /*
2432  * seqfile ops/methods for returning structured data. Currently just
2433  * supports string->u64 maps, but can be extended in future.
2434  */
2435
2436 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2437 {
2438         struct seq_file *sf = cb->state;
2439         return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2440 }
2441
2442 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2443 {
2444         struct cfent *cfe = m->private;
2445         struct cftype *cft = cfe->type;
2446         struct cgroup_subsys_state *css = cfe->css;
2447
2448         if (cft->read_map) {
2449                 struct cgroup_map_cb cb = {
2450                         .fill = cgroup_map_add,
2451                         .state = m,
2452                 };
2453                 return cft->read_map(css, cft, &cb);
2454         }
2455         return cft->read_seq_string(css, cft, m);
2456 }
2457
2458 static const struct file_operations cgroup_seqfile_operations = {
2459         .read = seq_read,
2460         .write = cgroup_file_write,
2461         .llseek = seq_lseek,
2462         .release = single_release,
2463 };
2464
2465 static int cgroup_file_open(struct inode *inode, struct file *file)
2466 {
2467         struct cfent *cfe = __d_cfe(file->f_dentry);
2468         struct cftype *cft = __d_cft(file->f_dentry);
2469         struct cgroup *cgrp = __d_cgrp(cfe->dentry->d_parent);
2470         struct cgroup_subsys_state *css;
2471         int err;
2472
2473         err = generic_file_open(inode, file);
2474         if (err)
2475                 return err;
2476
2477         /*
2478          * If the file belongs to a subsystem, pin the css.  Will be
2479          * unpinned either on open failure or release.  This ensures that
2480          * @css stays alive for all file operations.
2481          */
2482         rcu_read_lock();
2483         if (cft->ss) {
2484                 css = cgroup_css(cgrp, cft->ss->subsys_id);
2485                 if (!css_tryget(css))
2486                         css = NULL;
2487         } else {
2488                 css = &cgrp->dummy_css;
2489         }
2490         rcu_read_unlock();
2491
2492         if (!css)
2493                 return -ENODEV;
2494
2495         /*
2496          * @cfe->css is used by read/write/close to determine the
2497          * associated css.  @file->private_data would be a better place but
2498          * that's already used by seqfile.  Multiple accessors may use it
2499          * simultaneously which is okay as the association never changes.
2500          */
2501         WARN_ON_ONCE(cfe->css && cfe->css != css);
2502         cfe->css = css;
2503
2504         if (cft->read_map || cft->read_seq_string) {
2505                 file->f_op = &cgroup_seqfile_operations;
2506                 err = single_open(file, cgroup_seqfile_show, cfe);
2507         } else if (cft->open) {
2508                 err = cft->open(inode, file);
2509         }
2510
2511         if (css->ss && err)
2512                 css_put(css);
2513         return err;
2514 }
2515
2516 static int cgroup_file_release(struct inode *inode, struct file *file)
2517 {
2518         struct cfent *cfe = __d_cfe(file->f_dentry);
2519         struct cftype *cft = __d_cft(file->f_dentry);
2520         struct cgroup_subsys_state *css = cfe->css;
2521         int ret = 0;
2522
2523         if (cft->release)
2524                 ret = cft->release(inode, file);
2525         if (css->ss)
2526                 css_put(css);
2527         return ret;
2528 }
2529
2530 /*
2531  * cgroup_rename - Only allow simple rename of directories in place.
2532  */
2533 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2534                             struct inode *new_dir, struct dentry *new_dentry)
2535 {
2536         int ret;
2537         struct cgroup_name *name, *old_name;
2538         struct cgroup *cgrp;
2539
2540         /*
2541          * It's convinient to use parent dir's i_mutex to protected
2542          * cgrp->name.
2543          */
2544         lockdep_assert_held(&old_dir->i_mutex);
2545
2546         if (!S_ISDIR(old_dentry->d_inode->i_mode))
2547                 return -ENOTDIR;
2548         if (new_dentry->d_inode)
2549                 return -EEXIST;
2550         if (old_dir != new_dir)
2551                 return -EIO;
2552
2553         cgrp = __d_cgrp(old_dentry);
2554
2555         /*
2556          * This isn't a proper migration and its usefulness is very
2557          * limited.  Disallow if sane_behavior.
2558          */
2559         if (cgroup_sane_behavior(cgrp))
2560                 return -EPERM;
2561
2562         name = cgroup_alloc_name(new_dentry);
2563         if (!name)
2564                 return -ENOMEM;
2565
2566         ret = simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2567         if (ret) {
2568                 kfree(name);
2569                 return ret;
2570         }
2571
2572         old_name = rcu_dereference_protected(cgrp->name, true);
2573         rcu_assign_pointer(cgrp->name, name);
2574
2575         kfree_rcu(old_name, rcu_head);
2576         return 0;
2577 }
2578
2579 static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2580 {
2581         if (S_ISDIR(dentry->d_inode->i_mode))
2582                 return &__d_cgrp(dentry)->xattrs;
2583         else
2584                 return &__d_cfe(dentry)->xattrs;
2585 }
2586
2587 static inline int xattr_enabled(struct dentry *dentry)
2588 {
2589         struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2590         return root->flags & CGRP_ROOT_XATTR;
2591 }
2592
2593 static bool is_valid_xattr(const char *name)
2594 {
2595         if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2596             !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2597                 return true;
2598         return false;
2599 }
2600
2601 static int cgroup_setxattr(struct dentry *dentry, const char *name,
2602                            const void *val, size_t size, int flags)
2603 {
2604         if (!xattr_enabled(dentry))
2605                 return -EOPNOTSUPP;
2606         if (!is_valid_xattr(name))
2607                 return -EINVAL;
2608         return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2609 }
2610
2611 static int cgroup_removexattr(struct dentry *dentry, const char *name)
2612 {
2613         if (!xattr_enabled(dentry))
2614                 return -EOPNOTSUPP;
2615         if (!is_valid_xattr(name))
2616                 return -EINVAL;
2617         return simple_xattr_remove(__d_xattrs(dentry), name);
2618 }
2619
2620 static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2621                                void *buf, size_t size)
2622 {
2623         if (!xattr_enabled(dentry))
2624                 return -EOPNOTSUPP;
2625         if (!is_valid_xattr(name))
2626                 return -EINVAL;
2627         return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2628 }
2629
2630 static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2631 {
2632         if (!xattr_enabled(dentry))
2633                 return -EOPNOTSUPP;
2634         return simple_xattr_list(__d_xattrs(dentry), buf, size);
2635 }
2636
2637 static const struct file_operations cgroup_file_operations = {
2638         .read = cgroup_file_read,
2639         .write = cgroup_file_write,
2640         .llseek = generic_file_llseek,
2641         .open = cgroup_file_open,
2642         .release = cgroup_file_release,
2643 };
2644
2645 static const struct inode_operations cgroup_file_inode_operations = {
2646         .setxattr = cgroup_setxattr,
2647         .getxattr = cgroup_getxattr,
2648         .listxattr = cgroup_listxattr,
2649         .removexattr = cgroup_removexattr,
2650 };
2651
2652 static const struct inode_operations cgroup_dir_inode_operations = {
2653         .lookup = simple_lookup,
2654         .mkdir = cgroup_mkdir,
2655         .rmdir = cgroup_rmdir,
2656         .rename = cgroup_rename,
2657         .setxattr = cgroup_setxattr,
2658         .getxattr = cgroup_getxattr,
2659         .listxattr = cgroup_listxattr,
2660         .removexattr = cgroup_removexattr,
2661 };
2662
2663 /*
2664  * Check if a file is a control file
2665  */
2666 static inline struct cftype *__file_cft(struct file *file)
2667 {
2668         if (file_inode(file)->i_fop != &cgroup_file_operations)
2669                 return ERR_PTR(-EINVAL);
2670         return __d_cft(file->f_dentry);
2671 }
2672
2673 static int cgroup_create_file(struct dentry *dentry, umode_t mode,
2674                                 struct super_block *sb)
2675 {
2676         struct inode *inode;
2677
2678         if (!dentry)
2679                 return -ENOENT;
2680         if (dentry->d_inode)
2681                 return -EEXIST;
2682
2683         inode = cgroup_new_inode(mode, sb);
2684         if (!inode)
2685                 return -ENOMEM;
2686
2687         if (S_ISDIR(mode)) {
2688                 inode->i_op = &cgroup_dir_inode_operations;
2689                 inode->i_fop = &simple_dir_operations;
2690
2691                 /* start off with i_nlink == 2 (for "." entry) */
2692                 inc_nlink(inode);
2693                 inc_nlink(dentry->d_parent->d_inode);
2694
2695                 /*
2696                  * Control reaches here with cgroup_mutex held.
2697                  * @inode->i_mutex should nest outside cgroup_mutex but we
2698                  * want to populate it immediately without releasing
2699                  * cgroup_mutex.  As @inode isn't visible to anyone else
2700                  * yet, trylock will always succeed without affecting
2701                  * lockdep checks.
2702                  */
2703                 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
2704         } else if (S_ISREG(mode)) {
2705                 inode->i_size = 0;
2706                 inode->i_fop = &cgroup_file_operations;
2707                 inode->i_op = &cgroup_file_inode_operations;
2708         }
2709         d_instantiate(dentry, inode);
2710         dget(dentry);   /* Extra count - pin the dentry in core */
2711         return 0;
2712 }
2713
2714 /**
2715  * cgroup_file_mode - deduce file mode of a control file
2716  * @cft: the control file in question
2717  *
2718  * returns cft->mode if ->mode is not 0
2719  * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2720  * returns S_IRUGO if it has only a read handler
2721  * returns S_IWUSR if it has only a write hander
2722  */
2723 static umode_t cgroup_file_mode(const struct cftype *cft)
2724 {
2725         umode_t mode = 0;
2726
2727         if (cft->mode)
2728                 return cft->mode;
2729
2730         if (cft->read || cft->read_u64 || cft->read_s64 ||
2731             cft->read_map || cft->read_seq_string)
2732                 mode |= S_IRUGO;
2733
2734         if (cft->write || cft->write_u64 || cft->write_s64 ||
2735             cft->write_string || cft->trigger)
2736                 mode |= S_IWUSR;
2737
2738         return mode;
2739 }
2740
2741 static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
2742 {
2743         struct dentry *dir = cgrp->dentry;
2744         struct cgroup *parent = __d_cgrp(dir);
2745         struct dentry *dentry;
2746         struct cfent *cfe;
2747         int error;
2748         umode_t mode;
2749         char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
2750
2751         if (cft->ss && !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
2752                 strcpy(name, cft->ss->name);
2753                 strcat(name, ".");
2754         }
2755         strcat(name, cft->name);
2756
2757         BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
2758
2759         cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2760         if (!cfe)
2761                 return -ENOMEM;
2762
2763         dentry = lookup_one_len(name, dir, strlen(name));
2764         if (IS_ERR(dentry)) {
2765                 error = PTR_ERR(dentry);
2766                 goto out;
2767         }
2768
2769         cfe->type = (void *)cft;
2770         cfe->dentry = dentry;
2771         dentry->d_fsdata = cfe;
2772         simple_xattrs_init(&cfe->xattrs);
2773
2774         mode = cgroup_file_mode(cft);
2775         error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2776         if (!error) {
2777                 list_add_tail(&cfe->node, &parent->files);
2778                 cfe = NULL;
2779         }
2780         dput(dentry);
2781 out:
2782         kfree(cfe);
2783         return error;
2784 }
2785
2786 /**
2787  * cgroup_addrm_files - add or remove files to a cgroup directory
2788  * @cgrp: the target cgroup
2789  * @cfts: array of cftypes to be added
2790  * @is_add: whether to add or remove
2791  *
2792  * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2793  * For removals, this function never fails.  If addition fails, this
2794  * function doesn't remove files already added.  The caller is responsible
2795  * for cleaning up.
2796  */
2797 static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2798                               bool is_add)
2799 {
2800         struct cftype *cft;
2801         int ret;
2802
2803         lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
2804         lockdep_assert_held(&cgroup_mutex);
2805
2806         for (cft = cfts; cft->name[0] != '\0'; cft++) {
2807                 /* does cft->flags tell us to skip this file on @cgrp? */
2808                 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2809                         continue;
2810                 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2811                         continue;
2812                 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2813                         continue;
2814
2815                 if (is_add) {
2816                         ret = cgroup_add_file(cgrp, cft);
2817                         if (ret) {
2818                                 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2819                                         cft->name, ret);
2820                                 return ret;
2821                         }
2822                 } else {
2823                         cgroup_rm_file(cgrp, cft);
2824                 }
2825         }
2826         return 0;
2827 }
2828
2829 static void cgroup_cfts_prepare(void)
2830         __acquires(&cgroup_mutex)
2831 {
2832         /*
2833          * Thanks to the entanglement with vfs inode locking, we can't walk
2834          * the existing cgroups under cgroup_mutex and create files.
2835          * Instead, we use css_for_each_descendant_pre() and drop RCU read
2836          * lock before calling cgroup_addrm_files().
2837          */
2838         mutex_lock(&cgroup_mutex);
2839 }
2840
2841 static int cgroup_cfts_commit(struct cftype *cfts, bool is_add)
2842         __releases(&cgroup_mutex)
2843 {
2844         LIST_HEAD(pending);
2845         struct cgroup_subsys *ss = cfts[0].ss;
2846         struct cgroup *root = &ss->root->top_cgroup;
2847         struct super_block *sb = ss->root->sb;
2848         struct dentry *prev = NULL;
2849         struct inode *inode;
2850         struct cgroup_subsys_state *css;
2851         u64 update_before;
2852         int ret = 0;
2853
2854         /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2855         if (!cfts || ss->root == &cgroup_dummy_root ||
2856             !atomic_inc_not_zero(&sb->s_active)) {
2857                 mutex_unlock(&cgroup_mutex);
2858                 return 0;
2859         }
2860
2861         /*
2862          * All cgroups which are created after we drop cgroup_mutex will
2863          * have the updated set of files, so we only need to update the
2864          * cgroups created before the current @cgroup_serial_nr_next.
2865          */
2866         update_before = cgroup_serial_nr_next;
2867
2868         mutex_unlock(&cgroup_mutex);
2869
2870         /* add/rm files for all cgroups created before */
2871         rcu_read_lock();
2872         css_for_each_descendant_pre(css, cgroup_css(root, ss->subsys_id)) {
2873                 struct cgroup *cgrp = css->cgroup;
2874
2875                 if (cgroup_is_dead(cgrp))
2876                         continue;
2877
2878                 inode = cgrp->dentry->d_inode;
2879                 dget(cgrp->dentry);
2880                 rcu_read_unlock();
2881
2882                 dput(prev);
2883                 prev = cgrp->dentry;
2884
2885                 mutex_lock(&inode->i_mutex);
2886                 mutex_lock(&cgroup_mutex);
2887                 if (cgrp->serial_nr < update_before && !cgroup_is_dead(cgrp))
2888                         ret = cgroup_addrm_files(cgrp, cfts, is_add);
2889                 mutex_unlock(&cgroup_mutex);
2890                 mutex_unlock(&inode->i_mutex);
2891
2892                 rcu_read_lock();
2893                 if (ret)
2894                         break;
2895         }
2896         rcu_read_unlock();
2897         dput(prev);
2898         deactivate_super(sb);
2899         return ret;
2900 }
2901
2902 /**
2903  * cgroup_add_cftypes - add an array of cftypes to a subsystem
2904  * @ss: target cgroup subsystem
2905  * @cfts: zero-length name terminated array of cftypes
2906  *
2907  * Register @cfts to @ss.  Files described by @cfts are created for all
2908  * existing cgroups to which @ss is attached and all future cgroups will
2909  * have them too.  This function can be called anytime whether @ss is
2910  * attached or not.
2911  *
2912  * Returns 0 on successful registration, -errno on failure.  Note that this
2913  * function currently returns 0 as long as @cfts registration is successful
2914  * even if some file creation attempts on existing cgroups fail.
2915  */
2916 int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2917 {
2918         struct cftype_set *set;
2919         struct cftype *cft;
2920         int ret;
2921
2922         set = kzalloc(sizeof(*set), GFP_KERNEL);
2923         if (!set)
2924                 return -ENOMEM;
2925
2926         for (cft = cfts; cft->name[0] != '\0'; cft++)
2927                 cft->ss = ss;
2928
2929         cgroup_cfts_prepare();
2930         set->cfts = cfts;
2931         list_add_tail(&set->node, &ss->cftsets);
2932         ret = cgroup_cfts_commit(cfts, true);
2933         if (ret)
2934                 cgroup_rm_cftypes(cfts);
2935         return ret;
2936 }
2937 EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2938
2939 /**
2940  * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2941  * @cfts: zero-length name terminated array of cftypes
2942  *
2943  * Unregister @cfts.  Files described by @cfts are removed from all
2944  * existing cgroups and all future cgroups won't have them either.  This
2945  * function can be called anytime whether @cfts' subsys is attached or not.
2946  *
2947  * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2948  * registered.
2949  */
2950 int cgroup_rm_cftypes(struct cftype *cfts)
2951 {
2952         struct cftype_set *set;
2953
2954         if (!cfts || !cfts[0].ss)
2955                 return -ENOENT;
2956
2957         cgroup_cfts_prepare();
2958
2959         list_for_each_entry(set, &cfts[0].ss->cftsets, node) {
2960                 if (set->cfts == cfts) {
2961                         list_del(&set->node);
2962                         kfree(set);
2963                         cgroup_cfts_commit(cfts, false);
2964                         return 0;
2965                 }
2966         }
2967
2968         cgroup_cfts_commit(NULL, false);
2969         return -ENOENT;
2970 }
2971
2972 /**
2973  * cgroup_task_count - count the number of tasks in a cgroup.
2974  * @cgrp: the cgroup in question
2975  *
2976  * Return the number of tasks in the cgroup.
2977  */
2978 int cgroup_task_count(const struct cgroup *cgrp)
2979 {
2980         int count = 0;
2981         struct cgrp_cset_link *link;
2982
2983         read_lock(&css_set_lock);
2984         list_for_each_entry(link, &cgrp->cset_links, cset_link)
2985                 count += atomic_read(&link->cset->refcount);
2986         read_unlock(&css_set_lock);
2987         return count;
2988 }
2989
2990 /*
2991  * To reduce the fork() overhead for systems that are not actually using
2992  * their cgroups capability, we don't maintain the lists running through
2993  * each css_set to its tasks until we see the list actually used - in other
2994  * words after the first call to css_task_iter_start().
2995  */
2996 static void cgroup_enable_task_cg_lists(void)
2997 {
2998         struct task_struct *p, *g;
2999         write_lock(&css_set_lock);
3000         use_task_css_set_links = 1;
3001         /*
3002          * We need tasklist_lock because RCU is not safe against
3003          * while_each_thread(). Besides, a forking task that has passed
3004          * cgroup_post_fork() without seeing use_task_css_set_links = 1
3005          * is not guaranteed to have its child immediately visible in the
3006          * tasklist if we walk through it with RCU.
3007          */
3008         read_lock(&tasklist_lock);
3009         do_each_thread(g, p) {
3010                 task_lock(p);
3011                 /*
3012                  * We should check if the process is exiting, otherwise
3013                  * it will race with cgroup_exit() in that the list
3014                  * entry won't be deleted though the process has exited.
3015                  */
3016                 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
3017                         list_add(&p->cg_list, &task_css_set(p)->tasks);
3018                 task_unlock(p);
3019         } while_each_thread(g, p);
3020         read_unlock(&tasklist_lock);
3021         write_unlock(&css_set_lock);
3022 }
3023
3024 /**
3025  * css_next_child - find the next child of a given css
3026  * @pos_css: the current position (%NULL to initiate traversal)
3027  * @parent_css: css whose children to walk
3028  *
3029  * This function returns the next child of @parent_css and should be called
3030  * under RCU read lock.  The only requirement is that @parent_css and
3031  * @pos_css are accessible.  The next sibling is guaranteed to be returned
3032  * regardless of their states.
3033  */
3034 struct cgroup_subsys_state *
3035 css_next_child(struct cgroup_subsys_state *pos_css,
3036                struct cgroup_subsys_state *parent_css)
3037 {
3038         struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
3039         struct cgroup *cgrp = parent_css->cgroup;
3040         struct cgroup *next;
3041
3042         WARN_ON_ONCE(!rcu_read_lock_held());
3043
3044         /*
3045          * @pos could already have been removed.  Once a cgroup is removed,
3046          * its ->sibling.next is no longer updated when its next sibling
3047          * changes.  As CGRP_DEAD assertion is serialized and happens
3048          * before the cgroup is taken off the ->sibling list, if we see it
3049          * unasserted, it's guaranteed that the next sibling hasn't
3050          * finished its grace period even if it's already removed, and thus
3051          * safe to dereference from this RCU critical section.  If
3052          * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
3053          * to be visible as %true here.
3054          *
3055          * If @pos is dead, its next pointer can't be dereferenced;
3056          * however, as each cgroup is given a monotonically increasing
3057          * unique serial number and always appended to the sibling list,
3058          * the next one can be found by walking the parent's children until
3059          * we see a cgroup with higher serial number than @pos's.  While
3060          * this path can be slower, it's taken only when either the current
3061          * cgroup is removed or iteration and removal race.
3062          */
3063         if (!pos) {
3064                 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
3065         } else if (likely(!cgroup_is_dead(pos))) {
3066                 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3067         } else {
3068                 list_for_each_entry_rcu(next, &cgrp->children, sibling)
3069                         if (next->serial_nr > pos->serial_nr)
3070                                 break;
3071         }
3072
3073         if (&next->sibling == &cgrp->children)
3074                 return NULL;
3075
3076         if (parent_css->ss)
3077                 return cgroup_css(next, parent_css->ss->subsys_id);
3078         else
3079                 return &next->dummy_css;
3080 }
3081 EXPORT_SYMBOL_GPL(css_next_child);
3082
3083 /**
3084  * css_next_descendant_pre - find the next descendant for pre-order walk
3085  * @pos: the current position (%NULL to initiate traversal)
3086  * @root: css whose descendants to walk
3087  *
3088  * To be used by css_for_each_descendant_pre().  Find the next descendant
3089  * to visit for pre-order traversal of @root's descendants.  @root is
3090  * included in the iteration and the first node to be visited.
3091  *
3092  * While this function requires RCU read locking, it doesn't require the
3093  * whole traversal to be contained in a single RCU critical section.  This
3094  * function will return the correct next descendant as long as both @pos
3095  * and @root are accessible and @pos is a descendant of @root.
3096  */
3097 struct cgroup_subsys_state *
3098 css_next_descendant_pre(struct cgroup_subsys_state *pos,
3099                         struct cgroup_subsys_state *root)
3100 {
3101         struct cgroup_subsys_state *next;
3102
3103         WARN_ON_ONCE(!rcu_read_lock_held());
3104
3105         /* if first iteration, visit @root */
3106         if (!pos)
3107                 return root;
3108
3109         /* visit the first child if exists */
3110         next = css_next_child(NULL, pos);
3111         if (next)
3112                 return next;
3113
3114         /* no child, visit my or the closest ancestor's next sibling */
3115         while (pos != root) {
3116                 next = css_next_child(pos, css_parent(pos));
3117                 if (next)
3118                         return next;
3119                 pos = css_parent(pos);
3120         }
3121
3122         return NULL;
3123 }
3124 EXPORT_SYMBOL_GPL(css_next_descendant_pre);
3125
3126 /**
3127  * css_rightmost_descendant - return the rightmost descendant of a css
3128  * @pos: css of interest
3129  *
3130  * Return the rightmost descendant of @pos.  If there's no descendant, @pos
3131  * is returned.  This can be used during pre-order traversal to skip
3132  * subtree of @pos.
3133  *
3134  * While this function requires RCU read locking, it doesn't require the
3135  * whole traversal to be contained in a single RCU critical section.  This
3136  * function will return the correct rightmost descendant as long as @pos is
3137  * accessible.
3138  */
3139 struct cgroup_subsys_state *
3140 css_rightmost_descendant(struct cgroup_subsys_state *pos)
3141 {
3142         struct cgroup_subsys_state *last, *tmp;
3143
3144         WARN_ON_ONCE(!rcu_read_lock_held());
3145
3146         do {
3147                 last = pos;
3148                 /* ->prev isn't RCU safe, walk ->next till the end */
3149                 pos = NULL;
3150                 css_for_each_child(tmp, last)
3151                         pos = tmp;
3152         } while (pos);
3153
3154         return last;
3155 }
3156 EXPORT_SYMBOL_GPL(css_rightmost_descendant);
3157
3158 static struct cgroup_subsys_state *
3159 css_leftmost_descendant(struct cgroup_subsys_state *pos)
3160 {
3161         struct cgroup_subsys_state *last;
3162
3163         do {
3164                 last = pos;
3165                 pos = css_next_child(NULL, pos);
3166         } while (pos);
3167
3168         return last;
3169 }
3170
3171 /**
3172  * css_next_descendant_post - find the next descendant for post-order walk
3173  * @pos: the current position (%NULL to initiate traversal)
3174  * @root: css whose descendants to walk
3175  *
3176  * To be used by css_for_each_descendant_post().  Find the next descendant
3177  * to visit for post-order traversal of @root's descendants.  @root is
3178  * included in the iteration and the last node to be visited.
3179  *
3180  * While this function requires RCU read locking, it doesn't require the
3181  * whole traversal to be contained in a single RCU critical section.  This
3182  * function will return the correct next descendant as long as both @pos
3183  * and @cgroup are accessible and @pos is a descendant of @cgroup.
3184  */
3185 struct cgroup_subsys_state *
3186 css_next_descendant_post(struct cgroup_subsys_state *pos,
3187                          struct cgroup_subsys_state *root)
3188 {
3189         struct cgroup_subsys_state *next;
3190
3191         WARN_ON_ONCE(!rcu_read_lock_held());
3192
3193         /* if first iteration, visit the leftmost descendant */
3194         if (!pos) {
3195                 next = css_leftmost_descendant(root);
3196                 return next != root ? next : NULL;
3197         }
3198
3199         /* if we visited @root, we're done */
3200         if (pos == root)
3201                 return NULL;
3202
3203         /* if there's an unvisited sibling, visit its leftmost descendant */
3204         next = css_next_child(pos, css_parent(pos));
3205         if (next)
3206                 return css_leftmost_descendant(next);
3207
3208         /* no sibling left, visit parent */
3209         return css_parent(pos);
3210 }
3211 EXPORT_SYMBOL_GPL(css_next_descendant_post);
3212
3213 /**
3214  * css_advance_task_iter - advance a task itererator to the next css_set
3215  * @it: the iterator to advance
3216  *
3217  * Advance @it to the next css_set to walk.
3218  */
3219 static void css_advance_task_iter(struct css_task_iter *it)
3220 {
3221         struct list_head *l = it->cset_link;
3222         struct cgrp_cset_link *link;
3223         struct css_set *cset;
3224
3225         /* Advance to the next non-empty css_set */
3226         do {
3227                 l = l->next;
3228                 if (l == &it->origin_css->cgroup->cset_links) {
3229                         it->cset_link = NULL;
3230                         return;
3231                 }
3232                 link = list_entry(l, struct cgrp_cset_link, cset_link);
3233                 cset = link->cset;
3234         } while (list_empty(&cset->tasks));
3235         it->cset_link = l;
3236         it->task = cset->tasks.next;
3237 }
3238
3239 /**
3240  * css_task_iter_start - initiate task iteration
3241  * @css: the css to walk tasks of
3242  * @it: the task iterator to use
3243  *
3244  * Initiate iteration through the tasks of @css.  The caller can call
3245  * css_task_iter_next() to walk through the tasks until the function
3246  * returns NULL.  On completion of iteration, css_task_iter_end() must be
3247  * called.
3248  *
3249  * Note that this function acquires a lock which is released when the
3250  * iteration finishes.  The caller can't sleep while iteration is in
3251  * progress.
3252  */
3253 void css_task_iter_start(struct cgroup_subsys_state *css,
3254                          struct css_task_iter *it)
3255         __acquires(css_set_lock)
3256 {
3257         /*
3258          * The first time anyone tries to iterate across a css, we need to
3259          * enable the list linking each css_set to its tasks, and fix up
3260          * all existing tasks.
3261          */
3262         if (!use_task_css_set_links)
3263                 cgroup_enable_task_cg_lists();
3264
3265         read_lock(&css_set_lock);
3266
3267         it->origin_css = css;
3268         it->cset_link = &css->cgroup->cset_links;
3269
3270         css_advance_task_iter(it);
3271 }
3272
3273 /**
3274  * css_task_iter_next - return the next task for the iterator
3275  * @it: the task iterator being iterated
3276  *
3277  * The "next" function for task iteration.  @it should have been
3278  * initialized via css_task_iter_start().  Returns NULL when the iteration
3279  * reaches the end.
3280  */
3281 struct task_struct *css_task_iter_next(struct css_task_iter *it)
3282 {
3283         struct task_struct *res;
3284         struct list_head *l = it->task;
3285         struct cgrp_cset_link *link;
3286
3287         /* If the iterator cg is NULL, we have no tasks */
3288         if (!it->cset_link)
3289                 return NULL;
3290         res = list_entry(l, struct task_struct, cg_list);
3291         /* Advance iterator to find next entry */
3292         l = l->next;
3293         link = list_entry(it->cset_link, struct cgrp_cset_link, cset_link);
3294         if (l == &link->cset->tasks) {
3295                 /*
3296                  * We reached the end of this task list - move on to the
3297                  * next cgrp_cset_link.
3298                  */
3299                 css_advance_task_iter(it);
3300         } else {
3301                 it->task = l;
3302         }
3303         return res;
3304 }
3305
3306 /**
3307  * css_task_iter_end - finish task iteration
3308  * @it: the task iterator to finish
3309  *
3310  * Finish task iteration started by css_task_iter_start().
3311  */
3312 void css_task_iter_end(struct css_task_iter *it)
3313         __releases(css_set_lock)
3314 {
3315         read_unlock(&css_set_lock);
3316 }
3317
3318 static inline int started_after_time(struct task_struct *t1,
3319                                      struct timespec *time,
3320                                      struct task_struct *t2)
3321 {
3322         int start_diff = timespec_compare(&t1->start_time, time);
3323         if (start_diff > 0) {
3324                 return 1;
3325         } else if (start_diff < 0) {
3326                 return 0;
3327         } else {
3328                 /*
3329                  * Arbitrarily, if two processes started at the same
3330                  * time, we'll say that the lower pointer value
3331                  * started first. Note that t2 may have exited by now
3332                  * so this may not be a valid pointer any longer, but
3333                  * that's fine - it still serves to distinguish
3334                  * between two tasks started (effectively) simultaneously.
3335                  */
3336                 return t1 > t2;
3337         }
3338 }
3339
3340 /*
3341  * This function is a callback from heap_insert() and is used to order
3342  * the heap.
3343  * In this case we order the heap in descending task start time.
3344  */
3345 static inline int started_after(void *p1, void *p2)
3346 {
3347         struct task_struct *t1 = p1;
3348         struct task_struct *t2 = p2;
3349         return started_after_time(t1, &t2->start_time, t2);
3350 }
3351
3352 /**
3353  * css_scan_tasks - iterate though all the tasks in a css
3354  * @css: the css to iterate tasks of
3355  * @test: optional test callback
3356  * @process: process callback
3357  * @data: data passed to @test and @process
3358  * @heap: optional pre-allocated heap used for task iteration
3359  *
3360  * Iterate through all the tasks in @css, calling @test for each, and if it
3361  * returns %true, call @process for it also.
3362  *
3363  * @test may be NULL, meaning always true (select all tasks), which
3364  * effectively duplicates css_task_iter_{start,next,end}() but does not
3365  * lock css_set_lock for the call to @process.
3366  *
3367  * It is guaranteed that @process will act on every task that is a member
3368  * of @css for the duration of this call.  This function may or may not
3369  * call @process for tasks that exit or move to a different css during the
3370  * call, or are forked or move into the css during the call.
3371  *
3372  * Note that @test may be called with locks held, and may in some
3373  * situations be called multiple times for the same task, so it should be
3374  * cheap.
3375  *
3376  * If @heap is non-NULL, a heap has been pre-allocated and will be used for
3377  * heap operations (and its "gt" member will be overwritten), else a
3378  * temporary heap will be used (allocation of which may cause this function
3379  * to fail).
3380  */
3381 int css_scan_tasks(struct cgroup_subsys_state *css,
3382                    bool (*test)(struct task_struct *, void *),
3383                    void (*process)(struct task_struct *, void *),
3384                    void *data, struct ptr_heap *heap)
3385 {
3386         int retval, i;
3387         struct css_task_iter it;
3388         struct task_struct *p, *dropped;
3389         /* Never dereference latest_task, since it's not refcounted */
3390         struct task_struct *latest_task = NULL;
3391         struct ptr_heap tmp_heap;
3392         struct timespec latest_time = { 0, 0 };
3393
3394         if (heap) {
3395                 /* The caller supplied our heap and pre-allocated its memory */
3396                 heap->gt = &started_after;
3397         } else {
3398                 /* We need to allocate our own heap memory */
3399                 heap = &tmp_heap;
3400                 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3401                 if (retval)
3402                         /* cannot allocate the heap */
3403                         return retval;
3404         }
3405
3406  again:
3407         /*
3408          * Scan tasks in the css, using the @test callback to determine
3409          * which are of interest, and invoking @process callback on the
3410          * ones which need an update.  Since we don't want to hold any
3411          * locks during the task updates, gather tasks to be processed in a
3412          * heap structure.  The heap is sorted by descending task start
3413          * time.  If the statically-sized heap fills up, we overflow tasks
3414          * that started later, and in future iterations only consider tasks
3415          * that started after the latest task in the previous pass. This
3416          * guarantees forward progress and that we don't miss any tasks.
3417          */
3418         heap->size = 0;
3419         css_task_iter_start(css, &it);
3420         while ((p = css_task_iter_next(&it))) {
3421                 /*
3422                  * Only affect tasks that qualify per the caller's callback,
3423                  * if he provided one
3424                  */
3425                 if (test && !test(p, data))
3426                         continue;
3427                 /*
3428                  * Only process tasks that started after the last task
3429                  * we processed
3430                  */
3431                 if (!started_after_time(p, &latest_time, latest_task))
3432                         continue;
3433                 dropped = heap_insert(heap, p);
3434                 if (dropped == NULL) {
3435                         /*
3436                          * The new task was inserted; the heap wasn't
3437                          * previously full
3438                          */
3439                         get_task_struct(p);
3440                 } else if (dropped != p) {
3441                         /*
3442                          * The new task was inserted, and pushed out a
3443                          * different task
3444                          */
3445                         get_task_struct(p);
3446                         put_task_struct(dropped);
3447                 }
3448                 /*
3449                  * Else the new task was newer than anything already in
3450                  * the heap and wasn't inserted
3451                  */
3452         }
3453         css_task_iter_end(&it);
3454
3455         if (heap->size) {
3456                 for (i = 0; i < heap->size; i++) {
3457                         struct task_struct *q = heap->ptrs[i];
3458                         if (i == 0) {
3459                                 latest_time = q->start_time;
3460                                 latest_task = q;
3461                         }
3462                         /* Process the task per the caller's callback */
3463                         process(q, data);
3464                         put_task_struct(q);
3465                 }
3466                 /*
3467                  * If we had to process any tasks at all, scan again
3468                  * in case some of them were in the middle of forking
3469                  * children that didn't get processed.
3470                  * Not the most efficient way to do it, but it avoids
3471                  * having to take callback_mutex in the fork path
3472                  */
3473                 goto again;
3474         }
3475         if (heap == &tmp_heap)
3476                 heap_free(&tmp_heap);
3477         return 0;
3478 }
3479
3480 static void cgroup_transfer_one_task(struct task_struct *task, void *data)
3481 {
3482         struct cgroup *new_cgroup = data;
3483
3484         mutex_lock(&cgroup_mutex);
3485         cgroup_attach_task(new_cgroup, task, false);
3486         mutex_unlock(&cgroup_mutex);
3487 }
3488
3489 /**
3490  * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3491  * @to: cgroup to which the tasks will be moved
3492  * @from: cgroup in which the tasks currently reside
3493  */
3494 int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3495 {
3496         return css_scan_tasks(&from->dummy_css, NULL, cgroup_transfer_one_task,
3497                               to, NULL);
3498 }
3499
3500 /*
3501  * Stuff for reading the 'tasks'/'procs' files.
3502  *
3503  * Reading this file can return large amounts of data if a cgroup has
3504  * *lots* of attached tasks. So it may need several calls to read(),
3505  * but we cannot guarantee that the information we produce is correct
3506  * unless we produce it entirely atomically.
3507  *
3508  */
3509
3510 /* which pidlist file are we talking about? */
3511 enum cgroup_filetype {
3512         CGROUP_FILE_PROCS,
3513         CGROUP_FILE_TASKS,
3514 };
3515
3516 /*
3517  * A pidlist is a list of pids that virtually represents the contents of one
3518  * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3519  * a pair (one each for procs, tasks) for each pid namespace that's relevant
3520  * to the cgroup.
3521  */
3522 struct cgroup_pidlist {
3523         /*
3524          * used to find which pidlist is wanted. doesn't change as long as
3525          * this particular list stays in the list.
3526         */
3527         struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3528         /* array of xids */
3529         pid_t *list;
3530         /* how many elements the above list has */
3531         int length;
3532         /* how many files are using the current array */
3533         int use_count;
3534         /* each of these stored in a list by its cgroup */
3535         struct list_head links;
3536         /* pointer to the cgroup we belong to, for list removal purposes */
3537         struct cgroup *owner;
3538         /* protects the other fields */
3539         struct rw_semaphore rwsem;
3540 };
3541
3542 /*
3543  * The following two functions "fix" the issue where there are more pids
3544  * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3545  * TODO: replace with a kernel-wide solution to this problem
3546  */
3547 #define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3548 static void *pidlist_allocate(int count)
3549 {
3550         if (PIDLIST_TOO_LARGE(count))
3551                 return vmalloc(count * sizeof(pid_t));
3552         else
3553                 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3554 }
3555 static void pidlist_free(void *p)
3556 {
3557         if (is_vmalloc_addr(p))
3558                 vfree(p);
3559         else
3560                 kfree(p);
3561 }
3562
3563 /*
3564  * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
3565  * Returns the number of unique elements.
3566  */
3567 static int pidlist_uniq(pid_t *list, int length)
3568 {
3569         int src, dest = 1;
3570
3571         /*
3572          * we presume the 0th element is unique, so i starts at 1. trivial
3573          * edge cases first; no work needs to be done for either
3574          */
3575         if (length == 0 || length == 1)
3576                 return length;
3577         /* src and dest walk down the list; dest counts unique elements */
3578         for (src = 1; src < length; src++) {
3579                 /* find next unique element */
3580                 while (list[src] == list[src-1]) {
3581                         src++;
3582                         if (src == length)
3583                                 goto after;
3584                 }
3585                 /* dest always points to where the next unique element goes */
3586                 list[dest] = list[src];
3587                 dest++;
3588         }
3589 after:
3590         return dest;
3591 }
3592
3593 static int cmppid(const void *a, const void *b)
3594 {
3595         return *(pid_t *)a - *(pid_t *)b;
3596 }
3597
3598 /*
3599  * find the appropriate pidlist for our purpose (given procs vs tasks)
3600  * returns with the lock on that pidlist already held, and takes care
3601  * of the use count, or returns NULL with no locks held if we're out of
3602  * memory.
3603  */
3604 static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3605                                                   enum cgroup_filetype type)
3606 {
3607         struct cgroup_pidlist *l;
3608         /* don't need task_nsproxy() if we're looking at ourself */
3609         struct pid_namespace *ns = task_active_pid_ns(current);
3610
3611         /*
3612          * We can't drop the pidlist_mutex before taking the l->rwsem in case
3613          * the last ref-holder is trying to remove l from the list at the same
3614          * time. Holding the pidlist_mutex precludes somebody taking whichever
3615          * list we find out from under us - compare release_pid_array().
3616          */
3617         mutex_lock(&cgrp->pidlist_mutex);
3618         list_for_each_entry(l, &cgrp->pidlists, links) {
3619                 if (l->key.type == type && l->key.ns == ns) {
3620                         /* make sure l doesn't vanish out from under us */
3621                         down_write(&l->rwsem);
3622                         mutex_unlock(&cgrp->pidlist_mutex);
3623                         return l;
3624                 }
3625         }
3626         /* entry not found; create a new one */
3627         l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3628         if (!l) {
3629                 mutex_unlock(&cgrp->pidlist_mutex);
3630                 return l;
3631         }
3632         init_rwsem(&l->rwsem);
3633         down_write(&l->rwsem);
3634         l->key.type = type;
3635         l->key.ns = get_pid_ns(ns);
3636         l->owner = cgrp;
3637         list_add(&l->links, &cgrp->pidlists);
3638         mutex_unlock(&cgrp->pidlist_mutex);
3639         return l;
3640 }
3641
3642 /*
3643  * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3644  */
3645 static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3646                               struct cgroup_pidlist **lp)
3647 {
3648         pid_t *array;
3649         int length;
3650         int pid, n = 0; /* used for populating the array */
3651         struct css_task_iter it;
3652         struct task_struct *tsk;
3653         struct cgroup_pidlist *l;
3654
3655         /*
3656          * If cgroup gets more users after we read count, we won't have
3657          * enough space - tough.  This race is indistinguishable to the
3658          * caller from the case that the additional cgroup users didn't
3659          * show up until sometime later on.
3660          */
3661         length = cgroup_task_count(cgrp);
3662         array = pidlist_allocate(length);
3663         if (!array)
3664                 return -ENOMEM;
3665         /* now, populate the array */
3666         css_task_iter_start(&cgrp->dummy_css, &it);
3667         while ((tsk = css_task_iter_next(&it))) {
3668                 if (unlikely(n == length))
3669                         break;
3670                 /* get tgid or pid for procs or tasks file respectively */
3671                 if (type == CGROUP_FILE_PROCS)
3672                         pid = task_tgid_vnr(tsk);
3673                 else
3674                         pid = task_pid_vnr(tsk);
3675                 if (pid > 0) /* make sure to only use valid results */
3676                         array[n++] = pid;
3677         }
3678         css_task_iter_end(&it);
3679         length = n;
3680         /* now sort & (if procs) strip out duplicates */
3681         sort(array, length, sizeof(pid_t), cmppid, NULL);
3682         if (type == CGROUP_FILE_PROCS)
3683                 length = pidlist_uniq(array, length);
3684         l = cgroup_pidlist_find(cgrp, type);
3685         if (!l) {
3686                 pidlist_free(array);
3687                 return -ENOMEM;
3688         }
3689         /* store array, freeing old if necessary - lock already held */
3690         pidlist_free(l->list);
3691         l->list = array;
3692         l->length = length;
3693         l->use_count++;
3694         up_write(&l->rwsem);
3695         *lp = l;
3696         return 0;
3697 }
3698
3699 /**
3700  * cgroupstats_build - build and fill cgroupstats
3701  * @stats: cgroupstats to fill information into
3702  * @dentry: A dentry entry belonging to the cgroup for which stats have
3703  * been requested.
3704  *
3705  * Build and fill cgroupstats so that taskstats can export it to user
3706  * space.
3707  */
3708 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3709 {
3710         int ret = -EINVAL;
3711         struct cgroup *cgrp;
3712         struct css_task_iter it;
3713         struct task_struct *tsk;
3714
3715         /*
3716          * Validate dentry by checking the superblock operations,
3717          * and make sure it's a directory.
3718          */
3719         if (dentry->d_sb->s_op != &cgroup_ops ||
3720             !S_ISDIR(dentry->d_inode->i_mode))
3721                  goto err;
3722
3723         ret = 0;
3724         cgrp = dentry->d_fsdata;
3725
3726         css_task_iter_start(&cgrp->dummy_css, &it);
3727         while ((tsk = css_task_iter_next(&it))) {
3728                 switch (tsk->state) {
3729                 case TASK_RUNNING:
3730                         stats->nr_running++;
3731                         break;
3732                 case TASK_INTERRUPTIBLE:
3733                         stats->nr_sleeping++;
3734                         break;
3735                 case TASK_UNINTERRUPTIBLE:
3736                         stats->nr_uninterruptible++;
3737                         break;
3738                 case TASK_STOPPED:
3739                         stats->nr_stopped++;
3740                         break;
3741                 default:
3742                         if (delayacct_is_task_waiting_on_io(tsk))
3743                                 stats->nr_io_wait++;
3744                         break;
3745                 }
3746         }
3747         css_task_iter_end(&it);
3748
3749 err:
3750         return ret;
3751 }
3752
3753
3754 /*
3755  * seq_file methods for the tasks/procs files. The seq_file position is the
3756  * next pid to display; the seq_file iterator is a pointer to the pid
3757  * in the cgroup->l->list array.
3758  */
3759
3760 static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
3761 {
3762         /*
3763          * Initially we receive a position value that corresponds to
3764          * one more than the last pid shown (or 0 on the first call or
3765          * after a seek to the start). Use a binary-search to find the
3766          * next pid to display, if any
3767          */
3768         struct cgroup_pidlist *l = s->private;
3769         int index = 0, pid = *pos;
3770         int *iter;
3771
3772         down_read(&l->rwsem);
3773         if (pid) {
3774                 int end = l->length;
3775
3776                 while (index < end) {
3777                         int mid = (index + end) / 2;
3778                         if (l->list[mid] == pid) {
3779                                 index = mid;
3780                                 break;
3781                         } else if (l->list[mid] <= pid)
3782                                 index = mid + 1;
3783                         else
3784                                 end = mid;
3785                 }
3786         }
3787         /* If we're off the end of the array, we're done */
3788         if (index >= l->length)
3789                 return NULL;
3790         /* Update the abstract position to be the actual pid that we found */
3791         iter = l->list + index;
3792         *pos = *iter;
3793         return iter;
3794 }
3795
3796 static void cgroup_pidlist_stop(struct seq_file *s, void *v)
3797 {
3798         struct cgroup_pidlist *l = s->private;
3799         up_read(&l->rwsem);
3800 }
3801
3802 static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
3803 {
3804         struct cgroup_pidlist *l = s->private;
3805         pid_t *p = v;
3806         pid_t *end = l->list + l->length;
3807         /*
3808          * Advance to the next pid in the array. If this goes off the
3809          * end, we're done
3810          */
3811         p++;
3812         if (p >= end) {
3813                 return NULL;
3814         } else {
3815                 *pos = *p;
3816                 return p;
3817         }
3818 }
3819
3820 static int cgroup_pidlist_show(struct seq_file *s, void *v)
3821 {
3822         return seq_printf(s, "%d\n", *(int *)v);
3823 }
3824
3825 /*
3826  * seq_operations functions for iterating on pidlists through seq_file -
3827  * independent of whether it's tasks or procs
3828  */
3829 static const struct seq_operations cgroup_pidlist_seq_operations = {
3830         .start = cgroup_pidlist_start,
3831         .stop = cgroup_pidlist_stop,
3832         .next = cgroup_pidlist_next,
3833         .show = cgroup_pidlist_show,
3834 };
3835
3836 static void cgroup_release_pid_array(struct cgroup_pidlist *l)
3837 {
3838         /*
3839          * the case where we're the last user of this particular pidlist will
3840          * have us remove it from the cgroup's list, which entails taking the
3841          * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3842          * pidlist_mutex, we have to take pidlist_mutex first.
3843          */
3844         mutex_lock(&l->owner->pidlist_mutex);
3845         down_write(&l->rwsem);
3846         BUG_ON(!l->use_count);
3847         if (!--l->use_count) {
3848                 /* we're the last user if refcount is 0; remove and free */
3849                 list_del(&l->links);
3850                 mutex_unlock(&l->owner->pidlist_mutex);
3851                 pidlist_free(l->list);
3852                 put_pid_ns(l->key.ns);
3853                 up_write(&l->rwsem);
3854                 kfree(l);
3855                 return;
3856         }
3857         mutex_unlock(&l->owner->pidlist_mutex);
3858         up_write(&l->rwsem);
3859 }
3860
3861 static int cgroup_pidlist_release(struct inode *inode, struct file *file)
3862 {
3863         struct cgroup_pidlist *l;
3864         if (!(file->f_mode & FMODE_READ))
3865                 return 0;
3866         /*
3867          * the seq_file will only be initialized if the file was opened for
3868          * reading; hence we check if it's not null only in that case.
3869          */
3870         l = ((struct seq_file *)file->private_data)->private;
3871         cgroup_release_pid_array(l);
3872         return seq_release(inode, file);
3873 }
3874
3875 static const struct file_operations cgroup_pidlist_operations = {
3876         .read = seq_read,
3877         .llseek = seq_lseek,
3878         .write = cgroup_file_write,
3879         .release = cgroup_pidlist_release,
3880 };
3881
3882 /*
3883  * The following functions handle opens on a file that displays a pidlist
3884  * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3885  * in the cgroup.
3886  */
3887 /* helper function for the two below it */
3888 static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
3889 {
3890         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
3891         struct cgroup_pidlist *l;
3892         int retval;
3893
3894         /* Nothing to do for write-only files */
3895         if (!(file->f_mode & FMODE_READ))
3896                 return 0;
3897
3898         /* have the array populated */
3899         retval = pidlist_array_load(cgrp, type, &l);
3900         if (retval)
3901                 return retval;
3902         /* configure file information */
3903         file->f_op = &cgroup_pidlist_operations;
3904
3905         retval = seq_open(file, &cgroup_pidlist_seq_operations);
3906         if (retval) {
3907                 cgroup_release_pid_array(l);
3908                 return retval;
3909         }
3910         ((struct seq_file *)file->private_data)->private = l;
3911         return 0;
3912 }
3913 static int cgroup_tasks_open(struct inode *unused, struct file *file)
3914 {
3915         return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
3916 }
3917 static int cgroup_procs_open(struct inode *unused, struct file *file)
3918 {
3919         return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
3920 }
3921
3922 static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3923                                          struct cftype *cft)
3924 {
3925         return notify_on_release(css->cgroup);
3926 }
3927
3928 static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3929                                           struct cftype *cft, u64 val)
3930 {
3931         clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
3932         if (val)
3933                 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3934         else
3935                 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
3936         return 0;
3937 }
3938
3939 /*
3940  * When dput() is called asynchronously, if umount has been done and
3941  * then deactivate_super() in cgroup_free_fn() kills the superblock,
3942  * there's a small window that vfs will see the root dentry with non-zero
3943  * refcnt and trigger BUG().
3944  *
3945  * That's why we hold a reference before dput() and drop it right after.
3946  */
3947 static void cgroup_dput(struct cgroup *cgrp)
3948 {
3949         struct super_block *sb = cgrp->root->sb;
3950
3951         atomic_inc(&sb->s_active);
3952         dput(cgrp->dentry);
3953         deactivate_super(sb);
3954 }
3955
3956 /*
3957  * Unregister event and free resources.
3958  *
3959  * Gets called from workqueue.
3960  */
3961 static void cgroup_event_remove(struct work_struct *work)
3962 {
3963         struct cgroup_event *event = container_of(work, struct cgroup_event,
3964                         remove);
3965         struct cgroup_subsys_state *css = event->css;
3966         struct cgroup *cgrp = css->cgroup;
3967
3968         remove_wait_queue(event->wqh, &event->wait);
3969
3970         event->cft->unregister_event(css, event->cft, event->eventfd);
3971
3972         /* Notify userspace the event is going away. */
3973         eventfd_signal(event->eventfd, 1);
3974
3975         eventfd_ctx_put(event->eventfd);
3976         kfree(event);
3977         cgroup_dput(cgrp);
3978 }
3979
3980 /*
3981  * Gets called on POLLHUP on eventfd when user closes it.
3982  *
3983  * Called with wqh->lock held and interrupts disabled.
3984  */
3985 static int cgroup_event_wake(wait_queue_t *wait, unsigned mode,
3986                 int sync, void *key)
3987 {
3988         struct cgroup_event *event = container_of(wait,
3989                         struct cgroup_event, wait);
3990         struct cgroup *cgrp = event->css->cgroup;
3991         unsigned long flags = (unsigned long)key;
3992
3993         if (flags & POLLHUP) {
3994                 /*
3995                  * If the event has been detached at cgroup removal, we
3996                  * can simply return knowing the other side will cleanup
3997                  * for us.
3998                  *
3999                  * We can't race against event freeing since the other
4000                  * side will require wqh->lock via remove_wait_queue(),
4001                  * which we hold.
4002                  */
4003                 spin_lock(&cgrp->event_list_lock);
4004                 if (!list_empty(&event->list)) {
4005                         list_del_init(&event->list);
4006                         /*
4007                          * We are in atomic context, but cgroup_event_remove()
4008                          * may sleep, so we have to call it in workqueue.
4009                          */
4010                         schedule_work(&event->remove);
4011                 }
4012                 spin_unlock(&cgrp->event_list_lock);
4013         }
4014
4015         return 0;
4016 }
4017
4018 static void cgroup_event_ptable_queue_proc(struct file *file,
4019                 wait_queue_head_t *wqh, poll_table *pt)
4020 {
4021         struct cgroup_event *event = container_of(pt,
4022                         struct cgroup_event, pt);
4023
4024         event->wqh = wqh;
4025         add_wait_queue(wqh, &event->wait);
4026 }
4027
4028 /*
4029  * Parse input and register new cgroup event handler.
4030  *
4031  * Input must be in format '<event_fd> <control_fd> <args>'.
4032  * Interpretation of args is defined by control file implementation.
4033  */
4034 static int cgroup_write_event_control(struct cgroup_subsys_state *dummy_css,
4035                                       struct cftype *cft, const char *buffer)
4036 {
4037         struct cgroup *cgrp = dummy_css->cgroup;
4038         struct cgroup_event *event;
4039         struct cgroup *cgrp_cfile;
4040         unsigned int efd, cfd;
4041         struct file *efile;
4042         struct file *cfile;
4043         char *endp;
4044         int ret;
4045
4046         efd = simple_strtoul(buffer, &endp, 10);
4047         if (*endp != ' ')
4048                 return -EINVAL;
4049         buffer = endp + 1;
4050
4051         cfd = simple_strtoul(buffer, &endp, 10);
4052         if ((*endp != ' ') && (*endp != '\0'))
4053                 return -EINVAL;
4054         buffer = endp + 1;
4055
4056         event = kzalloc(sizeof(*event), GFP_KERNEL);
4057         if (!event)
4058                 return -ENOMEM;
4059
4060         INIT_LIST_HEAD(&event->list);
4061         init_poll_funcptr(&event->pt, cgroup_event_ptable_queue_proc);
4062         init_waitqueue_func_entry(&event->wait, cgroup_event_wake);
4063         INIT_WORK(&event->remove, cgroup_event_remove);
4064
4065         efile = eventfd_fget(efd);
4066         if (IS_ERR(efile)) {
4067                 ret = PTR_ERR(efile);
4068                 goto out_kfree;
4069         }
4070
4071         event->eventfd = eventfd_ctx_fileget(efile);
4072         if (IS_ERR(event->eventfd)) {
4073                 ret = PTR_ERR(event->eventfd);
4074                 goto out_put_efile;
4075         }
4076
4077         cfile = fget(cfd);
4078         if (!cfile) {
4079                 ret = -EBADF;
4080                 goto out_put_eventfd;
4081         }
4082
4083         /* the process need read permission on control file */
4084         /* AV: shouldn't we check that it's been opened for read instead? */
4085         ret = inode_permission(file_inode(cfile), MAY_READ);
4086         if (ret < 0)
4087                 goto out_put_cfile;
4088
4089         event->cft = __file_cft(cfile);
4090         if (IS_ERR(event->cft)) {
4091                 ret = PTR_ERR(event->cft);
4092                 goto out_put_cfile;
4093         }
4094
4095         if (!event->cft->ss) {
4096                 ret = -EBADF;
4097                 goto out_put_cfile;
4098         }
4099
4100         /* determine the css of @cfile and associate @event with it */
4101         rcu_read_lock();
4102
4103         ret = -EINVAL;
4104         event->css = cgroup_css(cgrp, event->cft->ss->subsys_id);
4105         if (event->css)
4106                 ret = 0;
4107
4108         rcu_read_unlock();
4109         if (ret)
4110                 goto out_put_cfile;
4111
4112         /*
4113          * The file to be monitored must be in the same cgroup as
4114          * cgroup.event_control is.
4115          */
4116         cgrp_cfile = __d_cgrp(cfile->f_dentry->d_parent);
4117         if (cgrp_cfile != cgrp) {
4118                 ret = -EINVAL;
4119                 goto out_put_cfile;
4120         }
4121
4122         if (!event->cft->register_event || !event->cft->unregister_event) {
4123                 ret = -EINVAL;
4124                 goto out_put_cfile;
4125         }
4126
4127         ret = event->cft->register_event(event->css, event->cft,
4128                         event->eventfd, buffer);
4129         if (ret)
4130                 goto out_put_cfile;
4131
4132         efile->f_op->poll(efile, &event->pt);
4133
4134         /*
4135          * Events should be removed after rmdir of cgroup directory, but before
4136          * destroying subsystem state objects. Let's take reference to cgroup
4137          * directory dentry to do that.
4138          */
4139         dget(cgrp->dentry);
4140
4141         spin_lock(&cgrp->event_list_lock);
4142         list_add(&event->list, &cgrp->event_list);
4143         spin_unlock(&cgrp->event_list_lock);
4144
4145         fput(cfile);
4146         fput(efile);
4147
4148         return 0;
4149
4150 out_put_cfile:
4151         fput(cfile);
4152 out_put_eventfd:
4153         eventfd_ctx_put(event->eventfd);
4154 out_put_efile:
4155         fput(efile);
4156 out_kfree:
4157         kfree(event);
4158
4159         return ret;
4160 }
4161
4162 static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
4163                                       struct cftype *cft)
4164 {
4165         return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4166 }
4167
4168 static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
4169                                        struct cftype *cft, u64 val)
4170 {
4171         if (val)
4172                 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4173         else
4174                 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
4175         return 0;
4176 }
4177
4178 static struct cftype cgroup_base_files[] = {
4179         {
4180                 .name = "cgroup.procs",
4181                 .open = cgroup_procs_open,
4182                 .write_u64 = cgroup_procs_write,
4183                 .release = cgroup_pidlist_release,
4184                 .mode = S_IRUGO | S_IWUSR,
4185         },
4186         {
4187                 .name = "cgroup.event_control",
4188                 .write_string = cgroup_write_event_control,
4189                 .mode = S_IWUGO,
4190         },
4191         {
4192                 .name = "cgroup.clone_children",
4193                 .flags = CFTYPE_INSANE,
4194                 .read_u64 = cgroup_clone_children_read,
4195                 .write_u64 = cgroup_clone_children_write,
4196         },
4197         {
4198                 .name = "cgroup.sane_behavior",
4199                 .flags = CFTYPE_ONLY_ON_ROOT,
4200                 .read_seq_string = cgroup_sane_behavior_show,
4201         },
4202
4203         /*
4204          * Historical crazy stuff.  These don't have "cgroup."  prefix and
4205          * don't exist if sane_behavior.  If you're depending on these, be
4206          * prepared to be burned.
4207          */
4208         {
4209                 .name = "tasks",
4210                 .flags = CFTYPE_INSANE,         /* use "procs" instead */
4211                 .open = cgroup_tasks_open,
4212                 .write_u64 = cgroup_tasks_write,
4213                 .release = cgroup_pidlist_release,
4214                 .mode = S_IRUGO | S_IWUSR,
4215         },
4216         {
4217                 .name = "notify_on_release",
4218                 .flags = CFTYPE_INSANE,
4219                 .read_u64 = cgroup_read_notify_on_release,
4220                 .write_u64 = cgroup_write_notify_on_release,
4221         },
4222         {
4223                 .name = "release_agent",
4224                 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
4225                 .read_seq_string = cgroup_release_agent_show,
4226                 .write_string = cgroup_release_agent_write,
4227                 .max_write_len = PATH_MAX,
4228         },
4229         { }     /* terminate */
4230 };
4231
4232 /**
4233  * cgroup_populate_dir - create subsys files in a cgroup directory
4234  * @cgrp: target cgroup
4235  * @subsys_mask: mask of the subsystem ids whose files should be added
4236  *
4237  * On failure, no file is added.
4238  */
4239 static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
4240 {
4241         struct cgroup_subsys *ss;
4242         int i, ret = 0;
4243
4244         /* process cftsets of each subsystem */
4245         for_each_subsys(ss, i) {
4246                 struct cftype_set *set;
4247
4248                 if (!test_bit(i, &subsys_mask))
4249                         continue;
4250
4251                 list_for_each_entry(set, &ss->cftsets, node) {
4252                         ret = cgroup_addrm_files(cgrp, set->cfts, true);
4253                         if (ret < 0)
4254                                 goto err;
4255                 }
4256         }
4257
4258         /* This cgroup is ready now */
4259         for_each_root_subsys(cgrp->root, ss) {
4260                 struct cgroup_subsys_state *css = cgroup_css(cgrp, ss->subsys_id);
4261                 struct css_id *id = rcu_dereference_protected(css->id, true);
4262
4263                 /*
4264                  * Update id->css pointer and make this css visible from
4265                  * CSS ID functions. This pointer will be dereferened
4266                  * from RCU-read-side without locks.
4267                  */
4268                 if (id)
4269                         rcu_assign_pointer(id->css, css);
4270         }
4271
4272         return 0;
4273 err:
4274         cgroup_clear_dir(cgrp, subsys_mask);
4275         return ret;
4276 }
4277
4278 /*
4279  * css destruction is four-stage process.
4280  *
4281  * 1. Destruction starts.  Killing of the percpu_ref is initiated.
4282  *    Implemented in kill_css().
4283  *
4284  * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
4285  *    and thus css_tryget() is guaranteed to fail, the css can be offlined
4286  *    by invoking offline_css().  After offlining, the base ref is put.
4287  *    Implemented in css_killed_work_fn().
4288  *
4289  * 3. When the percpu_ref reaches zero, the only possible remaining
4290  *    accessors are inside RCU read sections.  css_release() schedules the
4291  *    RCU callback.
4292  *
4293  * 4. After the grace period, the css can be freed.  Implemented in
4294  *    css_free_work_fn().
4295  *
4296  * It is actually hairier because both step 2 and 4 require process context
4297  * and thus involve punting to css->destroy_work adding two additional
4298  * steps to the already complex sequence.
4299  */
4300 static void css_free_work_fn(struct work_struct *work)
4301 {
4302         struct cgroup_subsys_state *css =
4303                 container_of(work, struct cgroup_subsys_state, destroy_work);
4304         struct cgroup *cgrp = css->cgroup;
4305
4306         if (css->parent)
4307                 css_put(css->parent);
4308
4309         css->ss->css_free(css);
4310         cgroup_dput(cgrp);
4311 }
4312
4313 static void css_free_rcu_fn(struct rcu_head *rcu_head)
4314 {
4315         struct cgroup_subsys_state *css =
4316                 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
4317
4318         /*
4319          * css holds an extra ref to @cgrp->dentry which is put on the last
4320          * css_put().  dput() requires process context which we don't have.
4321          */
4322         INIT_WORK(&css->destroy_work, css_free_work_fn);
4323         schedule_work(&css->destroy_work);
4324 }
4325
4326 static void css_release(struct percpu_ref *ref)
4327 {
4328         struct cgroup_subsys_state *css =
4329                 container_of(ref, struct cgroup_subsys_state, refcnt);
4330
4331         call_rcu(&css->rcu_head, css_free_rcu_fn);
4332 }
4333
4334 static void init_css(struct cgroup_subsys_state *css, struct cgroup_subsys *ss,
4335                      struct cgroup *cgrp)
4336 {
4337         css->cgroup = cgrp;
4338         css->ss = ss;
4339         css->flags = 0;
4340         css->id = NULL;
4341
4342         if (cgrp->parent)
4343                 css->parent = cgroup_css(cgrp->parent, ss->subsys_id);
4344         else
4345                 css->flags |= CSS_ROOT;
4346
4347         BUG_ON(cgroup_css(cgrp, ss->subsys_id));
4348 }
4349
4350 /* invoke ->css_online() on a new CSS and mark it online if successful */
4351 static int online_css(struct cgroup_subsys_state *css)
4352 {
4353         struct cgroup_subsys *ss = css->ss;
4354         int ret = 0;
4355
4356         lockdep_assert_held(&cgroup_mutex);
4357
4358         if (ss->css_online)
4359                 ret = ss->css_online(css);
4360         if (!ret) {
4361                 css->flags |= CSS_ONLINE;
4362                 css->cgroup->nr_css++;
4363                 rcu_assign_pointer(css->cgroup->subsys[ss->subsys_id], css);
4364         }
4365         return ret;
4366 }
4367
4368 /* if the CSS is online, invoke ->css_offline() on it and mark it offline */
4369 static void offline_css(struct cgroup_subsys_state *css)
4370 {
4371         struct cgroup_subsys *ss = css->ss;
4372
4373         lockdep_assert_held(&cgroup_mutex);
4374
4375         if (!(css->flags & CSS_ONLINE))
4376                 return;
4377
4378         if (ss->css_offline)
4379                 ss->css_offline(css);
4380
4381         css->flags &= ~CSS_ONLINE;
4382         css->cgroup->nr_css--;
4383         RCU_INIT_POINTER(css->cgroup->subsys[ss->subsys_id], css);
4384 }
4385
4386 /*
4387  * cgroup_create - create a cgroup
4388  * @parent: cgroup that will be parent of the new cgroup
4389  * @dentry: dentry of the new cgroup
4390  * @mode: mode to set on new inode
4391  *
4392  * Must be called with the mutex on the parent inode held
4393  */
4394 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
4395                              umode_t mode)
4396 {
4397         struct cgroup_subsys_state *css_ar[CGROUP_SUBSYS_COUNT] = { };
4398         struct cgroup *cgrp;
4399         struct cgroup_name *name;
4400         struct cgroupfs_root *root = parent->root;
4401         int err = 0;
4402         struct cgroup_subsys *ss;
4403         struct super_block *sb = root->sb;
4404
4405         /* allocate the cgroup and its ID, 0 is reserved for the root */
4406         cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4407         if (!cgrp)
4408                 return -ENOMEM;
4409
4410         name = cgroup_alloc_name(dentry);
4411         if (!name)
4412                 goto err_free_cgrp;
4413         rcu_assign_pointer(cgrp->name, name);
4414
4415         /*
4416          * Temporarily set the pointer to NULL, so idr_find() won't return
4417          * a half-baked cgroup.
4418          */
4419         cgrp->id = idr_alloc(&root->cgroup_idr, NULL, 1, 0, GFP_KERNEL);
4420         if (cgrp->id < 0)
4421                 goto err_free_name;
4422
4423         /*
4424          * Only live parents can have children.  Note that the liveliness
4425          * check isn't strictly necessary because cgroup_mkdir() and
4426          * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4427          * anyway so that locking is contained inside cgroup proper and we
4428          * don't get nasty surprises if we ever grow another caller.
4429          */
4430         if (!cgroup_lock_live_group(parent)) {
4431                 err = -ENODEV;
4432                 goto err_free_id;
4433         }
4434
4435         /* Grab a reference on the superblock so the hierarchy doesn't
4436          * get deleted on unmount if there are child cgroups.  This
4437          * can be done outside cgroup_mutex, since the sb can't
4438          * disappear while someone has an open control file on the
4439          * fs */
4440         atomic_inc(&sb->s_active);
4441
4442         init_cgroup_housekeeping(cgrp);
4443
4444         dentry->d_fsdata = cgrp;
4445         cgrp->dentry = dentry;
4446
4447         cgrp->parent = parent;
4448         cgrp->dummy_css.parent = &parent->dummy_css;
4449         cgrp->root = parent->root;
4450
4451         if (notify_on_release(parent))
4452                 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4453
4454         if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4455                 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
4456
4457         for_each_root_subsys(root, ss) {
4458                 struct cgroup_subsys_state *css;
4459
4460                 css = ss->css_alloc(cgroup_css(parent, ss->subsys_id));
4461                 if (IS_ERR(css)) {
4462                         err = PTR_ERR(css);
4463                         goto err_free_all;
4464                 }
4465                 css_ar[ss->subsys_id] = css;
4466
4467                 err = percpu_ref_init(&css->refcnt, css_release);
4468                 if (err)
4469                         goto err_free_all;
4470
4471                 init_css(css, ss, cgrp);
4472
4473                 if (ss->use_id) {
4474                         err = alloc_css_id(css);
4475                         if (err)
4476                                 goto err_free_all;
4477                 }
4478         }
4479
4480         /*
4481          * Create directory.  cgroup_create_file() returns with the new
4482          * directory locked on success so that it can be populated without
4483          * dropping cgroup_mutex.
4484          */
4485         err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
4486         if (err < 0)
4487                 goto err_free_all;
4488         lockdep_assert_held(&dentry->d_inode->i_mutex);
4489
4490         cgrp->serial_nr = cgroup_serial_nr_next++;
4491
4492         /* allocation complete, commit to creation */
4493         list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4494         root->number_of_cgroups++;
4495
4496         /* each css holds a ref to the cgroup's dentry and the parent css */
4497         for_each_root_subsys(root, ss) {
4498                 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4499
4500                 dget(dentry);
4501                 css_get(css->parent);
4502         }
4503
4504         /* hold a ref to the parent's dentry */
4505         dget(parent->dentry);
4506
4507         /* creation succeeded, notify subsystems */
4508         for_each_root_subsys(root, ss) {
4509                 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4510
4511                 err = online_css(css);
4512                 if (err)
4513                         goto err_destroy;
4514
4515                 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4516                     parent->parent) {
4517                         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",
4518                                    current->comm, current->pid, ss->name);
4519                         if (!strcmp(ss->name, "memory"))
4520                                 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4521                         ss->warned_broken_hierarchy = true;
4522                 }
4523         }
4524
4525         idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
4526
4527         err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
4528         if (err)
4529                 goto err_destroy;
4530
4531         err = cgroup_populate_dir(cgrp, root->subsys_mask);
4532         if (err)
4533                 goto err_destroy;
4534
4535         mutex_unlock(&cgroup_mutex);
4536         mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
4537
4538         return 0;
4539
4540 err_free_all:
4541         for_each_root_subsys(root, ss) {
4542                 struct cgroup_subsys_state *css = css_ar[ss->subsys_id];
4543
4544                 if (css) {
4545                         percpu_ref_cancel_init(&css->refcnt);
4546                         ss->css_free(css);
4547                 }
4548         }
4549         mutex_unlock(&cgroup_mutex);
4550         /* Release the reference count that we took on the superblock */
4551         deactivate_super(sb);
4552 err_free_id:
4553         idr_remove(&root->cgroup_idr, cgrp->id);
4554 err_free_name:
4555         kfree(rcu_dereference_raw(cgrp->name));
4556 err_free_cgrp:
4557         kfree(cgrp);
4558         return err;
4559
4560 err_destroy:
4561         cgroup_destroy_locked(cgrp);
4562         mutex_unlock(&cgroup_mutex);
4563         mutex_unlock(&dentry->d_inode->i_mutex);
4564         return err;
4565 }
4566
4567 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
4568 {
4569         struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4570
4571         /* the vfs holds inode->i_mutex already */
4572         return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4573 }
4574
4575 /*
4576  * This is called when the refcnt of a css is confirmed to be killed.
4577  * css_tryget() is now guaranteed to fail.
4578  */
4579 static void css_killed_work_fn(struct work_struct *work)
4580 {
4581         struct cgroup_subsys_state *css =
4582                 container_of(work, struct cgroup_subsys_state, destroy_work);
4583         struct cgroup *cgrp = css->cgroup;
4584
4585         mutex_lock(&cgroup_mutex);
4586
4587         /*
4588          * css_tryget() is guaranteed to fail now.  Tell subsystems to
4589          * initate destruction.
4590          */
4591         offline_css(css);
4592
4593         /*
4594          * If @cgrp is marked dead, it's waiting for refs of all css's to
4595          * be disabled before proceeding to the second phase of cgroup
4596          * destruction.  If we are the last one, kick it off.
4597          */
4598         if (!cgrp->nr_css && cgroup_is_dead(cgrp))
4599                 cgroup_destroy_css_killed(cgrp);
4600
4601         mutex_unlock(&cgroup_mutex);
4602
4603         /*
4604          * Put the css refs from kill_css().  Each css holds an extra
4605          * reference to the cgroup's dentry and cgroup removal proceeds
4606          * regardless of css refs.  On the last put of each css, whenever
4607          * that may be, the extra dentry ref is put so that dentry
4608          * destruction happens only after all css's are released.
4609          */
4610         css_put(css);
4611 }
4612
4613 /* css kill confirmation processing requires process context, bounce */
4614 static void css_killed_ref_fn(struct percpu_ref *ref)
4615 {
4616         struct cgroup_subsys_state *css =
4617                 container_of(ref, struct cgroup_subsys_state, refcnt);
4618
4619         INIT_WORK(&css->destroy_work, css_killed_work_fn);
4620         schedule_work(&css->destroy_work);
4621 }
4622
4623 /**
4624  * kill_css - destroy a css
4625  * @css: css to destroy
4626  *
4627  * This function initiates destruction of @css by removing cgroup interface
4628  * files and putting its base reference.  ->css_offline() will be invoked
4629  * asynchronously once css_tryget() is guaranteed to fail and when the
4630  * reference count reaches zero, @css will be released.
4631  */
4632 static void kill_css(struct cgroup_subsys_state *css)
4633 {
4634         cgroup_clear_dir(css->cgroup, 1 << css->ss->subsys_id);
4635
4636         /*
4637          * Killing would put the base ref, but we need to keep it alive
4638          * until after ->css_offline().
4639          */
4640         css_get(css);
4641
4642         /*
4643          * cgroup core guarantees that, by the time ->css_offline() is
4644          * invoked, no new css reference will be given out via
4645          * css_tryget().  We can't simply call percpu_ref_kill() and
4646          * proceed to offlining css's because percpu_ref_kill() doesn't
4647          * guarantee that the ref is seen as killed on all CPUs on return.
4648          *
4649          * Use percpu_ref_kill_and_confirm() to get notifications as each
4650          * css is confirmed to be seen as killed on all CPUs.
4651          */
4652         percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
4653 }
4654
4655 /**
4656  * cgroup_destroy_locked - the first stage of cgroup destruction
4657  * @cgrp: cgroup to be destroyed
4658  *
4659  * css's make use of percpu refcnts whose killing latency shouldn't be
4660  * exposed to userland and are RCU protected.  Also, cgroup core needs to
4661  * guarantee that css_tryget() won't succeed by the time ->css_offline() is
4662  * invoked.  To satisfy all the requirements, destruction is implemented in
4663  * the following two steps.
4664  *
4665  * s1. Verify @cgrp can be destroyed and mark it dying.  Remove all
4666  *     userland visible parts and start killing the percpu refcnts of
4667  *     css's.  Set up so that the next stage will be kicked off once all
4668  *     the percpu refcnts are confirmed to be killed.
4669  *
4670  * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
4671  *     rest of destruction.  Once all cgroup references are gone, the
4672  *     cgroup is RCU-freed.
4673  *
4674  * This function implements s1.  After this step, @cgrp is gone as far as
4675  * the userland is concerned and a new cgroup with the same name may be
4676  * created.  As cgroup doesn't care about the names internally, this
4677  * doesn't cause any problem.
4678  */
4679 static int cgroup_destroy_locked(struct cgroup *cgrp)
4680         __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4681 {
4682         struct dentry *d = cgrp->dentry;
4683         struct cgroup_event *event, *tmp;
4684         struct cgroup_subsys *ss;
4685         bool empty;
4686
4687         lockdep_assert_held(&d->d_inode->i_mutex);
4688         lockdep_assert_held(&cgroup_mutex);
4689
4690         /*
4691          * css_set_lock synchronizes access to ->cset_links and prevents
4692          * @cgrp from being removed while __put_css_set() is in progress.
4693          */
4694         read_lock(&css_set_lock);
4695         empty = list_empty(&cgrp->cset_links) && list_empty(&cgrp->children);
4696         read_unlock(&css_set_lock);
4697         if (!empty)
4698                 return -EBUSY;
4699
4700         /*
4701          * Initiate massacre of all css's.  cgroup_destroy_css_killed()
4702          * will be invoked to perform the rest of destruction once the
4703          * percpu refs of all css's are confirmed to be killed.
4704          */
4705         for_each_root_subsys(cgrp->root, ss)
4706                 kill_css(cgroup_css(cgrp, ss->subsys_id));
4707
4708         /*
4709          * Mark @cgrp dead.  This prevents further task migration and child
4710          * creation by disabling cgroup_lock_live_group().  Note that
4711          * CGRP_DEAD assertion is depended upon by css_next_child() to
4712          * resume iteration after dropping RCU read lock.  See
4713          * css_next_child() for details.
4714          */
4715         set_bit(CGRP_DEAD, &cgrp->flags);
4716
4717         /* CGRP_DEAD is set, remove from ->release_list for the last time */
4718         raw_spin_lock(&release_list_lock);
4719         if (!list_empty(&cgrp->release_list))
4720                 list_del_init(&cgrp->release_list);
4721         raw_spin_unlock(&release_list_lock);
4722
4723         /*
4724          * If @cgrp has css's attached, the second stage of cgroup
4725          * destruction is kicked off from css_killed_work_fn() after the
4726          * refs of all attached css's are killed.  If @cgrp doesn't have
4727          * any css, we kick it off here.
4728          */
4729         if (!cgrp->nr_css)
4730                 cgroup_destroy_css_killed(cgrp);
4731
4732         /*
4733          * Clear the base files and remove @cgrp directory.  The removal
4734          * puts the base ref but we aren't quite done with @cgrp yet, so
4735          * hold onto it.
4736          */
4737         cgroup_addrm_files(cgrp, cgroup_base_files, false);
4738         dget(d);
4739         cgroup_d_remove_dir(d);
4740
4741         /*
4742          * Unregister events and notify userspace.
4743          * Notify userspace about cgroup removing only after rmdir of cgroup
4744          * directory to avoid race between userspace and kernelspace.
4745          */
4746         spin_lock(&cgrp->event_list_lock);
4747         list_for_each_entry_safe(event, tmp, &cgrp->event_list, list) {
4748                 list_del_init(&event->list);
4749                 schedule_work(&event->remove);
4750         }
4751         spin_unlock(&cgrp->event_list_lock);
4752
4753         return 0;
4754 };
4755
4756 /**
4757  * cgroup_destroy_css_killed - the second step of cgroup destruction
4758  * @work: cgroup->destroy_free_work
4759  *
4760  * This function is invoked from a work item for a cgroup which is being
4761  * destroyed after all css's are offlined and performs the rest of
4762  * destruction.  This is the second step of destruction described in the
4763  * comment above cgroup_destroy_locked().
4764  */
4765 static void cgroup_destroy_css_killed(struct cgroup *cgrp)
4766 {
4767         struct cgroup *parent = cgrp->parent;
4768         struct dentry *d = cgrp->dentry;
4769
4770         lockdep_assert_held(&cgroup_mutex);
4771
4772         /* delete this cgroup from parent->children */
4773         list_del_rcu(&cgrp->sibling);
4774
4775         /*
4776          * We should remove the cgroup object from idr before its grace
4777          * period starts, so we won't be looking up a cgroup while the
4778          * cgroup is being freed.
4779          */
4780         idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
4781         cgrp->id = -1;
4782
4783         dput(d);
4784
4785         set_bit(CGRP_RELEASABLE, &parent->flags);
4786         check_for_release(parent);
4787 }
4788
4789 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4790 {
4791         int ret;
4792
4793         mutex_lock(&cgroup_mutex);
4794         ret = cgroup_destroy_locked(dentry->d_fsdata);
4795         mutex_unlock(&cgroup_mutex);
4796
4797         return ret;
4798 }
4799
4800 static void __init_or_module cgroup_init_cftsets(struct cgroup_subsys *ss)
4801 {
4802         INIT_LIST_HEAD(&ss->cftsets);
4803
4804         /*
4805          * base_cftset is embedded in subsys itself, no need to worry about
4806          * deregistration.
4807          */
4808         if (ss->base_cftypes) {
4809                 struct cftype *cft;
4810
4811                 for (cft = ss->base_cftypes; cft->name[0] != '\0'; cft++)
4812                         cft->ss = ss;
4813
4814                 ss->base_cftset.cfts = ss->base_cftypes;
4815                 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4816         }
4817 }
4818
4819 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
4820 {
4821         struct cgroup_subsys_state *css;
4822
4823         printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
4824
4825         mutex_lock(&cgroup_mutex);
4826
4827         /* init base cftset */
4828         cgroup_init_cftsets(ss);
4829
4830         /* Create the top cgroup state for this subsystem */
4831         list_add(&ss->sibling, &cgroup_dummy_root.subsys_list);
4832         ss->root = &cgroup_dummy_root;
4833         css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss->subsys_id));
4834         /* We don't handle early failures gracefully */
4835         BUG_ON(IS_ERR(css));
4836         init_css(css, ss, cgroup_dummy_top);
4837
4838         /* Update the init_css_set to contain a subsys
4839          * pointer to this state - since the subsystem is
4840          * newly registered, all tasks and hence the
4841          * init_css_set is in the subsystem's top cgroup. */
4842         init_css_set.subsys[ss->subsys_id] = css;
4843
4844         need_forkexit_callback |= ss->fork || ss->exit;
4845
4846         /* At system boot, before all subsystems have been
4847          * registered, no tasks have been forked, so we don't
4848          * need to invoke fork callbacks here. */
4849         BUG_ON(!list_empty(&init_task.tasks));
4850
4851         BUG_ON(online_css(css));
4852
4853         mutex_unlock(&cgroup_mutex);
4854
4855         /* this function shouldn't be used with modular subsystems, since they
4856          * need to register a subsys_id, among other things */
4857         BUG_ON(ss->module);
4858 }
4859
4860 /**
4861  * cgroup_load_subsys: load and register a modular subsystem at runtime
4862  * @ss: the subsystem to load
4863  *
4864  * This function should be called in a modular subsystem's initcall. If the
4865  * subsystem is built as a module, it will be assigned a new subsys_id and set
4866  * up for use. If the subsystem is built-in anyway, work is delegated to the
4867  * simpler cgroup_init_subsys.
4868  */
4869 int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
4870 {
4871         struct cgroup_subsys_state *css;
4872         int i, ret;
4873         struct hlist_node *tmp;
4874         struct css_set *cset;
4875         unsigned long key;
4876
4877         /* check name and function validity */
4878         if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
4879             ss->css_alloc == NULL || ss->css_free == NULL)
4880                 return -EINVAL;
4881
4882         /*
4883          * we don't support callbacks in modular subsystems. this check is
4884          * before the ss->module check for consistency; a subsystem that could
4885          * be a module should still have no callbacks even if the user isn't
4886          * compiling it as one.
4887          */
4888         if (ss->fork || ss->exit)
4889                 return -EINVAL;
4890
4891         /*
4892          * an optionally modular subsystem is built-in: we want to do nothing,
4893          * since cgroup_init_subsys will have already taken care of it.
4894          */
4895         if (ss->module == NULL) {
4896                 /* a sanity check */
4897                 BUG_ON(cgroup_subsys[ss->subsys_id] != ss);
4898                 return 0;
4899         }
4900
4901         /* init base cftset */
4902         cgroup_init_cftsets(ss);
4903
4904         mutex_lock(&cgroup_mutex);
4905         cgroup_subsys[ss->subsys_id] = ss;
4906
4907         /*
4908          * no ss->css_alloc seems to need anything important in the ss
4909          * struct, so this can happen first (i.e. before the dummy root
4910          * attachment).
4911          */
4912         css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss->subsys_id));
4913         if (IS_ERR(css)) {
4914                 /* failure case - need to deassign the cgroup_subsys[] slot. */
4915                 cgroup_subsys[ss->subsys_id] = NULL;
4916                 mutex_unlock(&cgroup_mutex);
4917                 return PTR_ERR(css);
4918         }
4919
4920         list_add(&ss->sibling, &cgroup_dummy_root.subsys_list);
4921         ss->root = &cgroup_dummy_root;
4922
4923         /* our new subsystem will be attached to the dummy hierarchy. */
4924         init_css(css, ss, cgroup_dummy_top);
4925         /* init_idr must be after init_css() because it sets css->id. */
4926         if (ss->use_id) {
4927                 ret = cgroup_init_idr(ss, css);
4928                 if (ret)
4929                         goto err_unload;
4930         }
4931
4932         /*
4933          * Now we need to entangle the css into the existing css_sets. unlike
4934          * in cgroup_init_subsys, there are now multiple css_sets, so each one
4935          * will need a new pointer to it; done by iterating the css_set_table.
4936          * furthermore, modifying the existing css_sets will corrupt the hash
4937          * table state, so each changed css_set will need its hash recomputed.
4938          * this is all done under the css_set_lock.
4939          */
4940         write_lock(&css_set_lock);
4941         hash_for_each_safe(css_set_table, i, tmp, cset, hlist) {
4942                 /* skip entries that we already rehashed */
4943                 if (cset->subsys[ss->subsys_id])
4944                         continue;
4945                 /* remove existing entry */
4946                 hash_del(&cset->hlist);
4947                 /* set new value */
4948                 cset->subsys[ss->subsys_id] = css;
4949                 /* recompute hash and restore entry */
4950                 key = css_set_hash(cset->subsys);
4951                 hash_add(css_set_table, &cset->hlist, key);
4952         }
4953         write_unlock(&css_set_lock);
4954
4955         ret = online_css(css);
4956         if (ret)
4957                 goto err_unload;
4958
4959         /* success! */
4960         mutex_unlock(&cgroup_mutex);
4961         return 0;
4962
4963 err_unload:
4964         mutex_unlock(&cgroup_mutex);
4965         /* @ss can't be mounted here as try_module_get() would fail */
4966         cgroup_unload_subsys(ss);
4967         return ret;
4968 }
4969 EXPORT_SYMBOL_GPL(cgroup_load_subsys);
4970
4971 /**
4972  * cgroup_unload_subsys: unload a modular subsystem
4973  * @ss: the subsystem to unload
4974  *
4975  * This function should be called in a modular subsystem's exitcall. When this
4976  * function is invoked, the refcount on the subsystem's module will be 0, so
4977  * the subsystem will not be attached to any hierarchy.
4978  */
4979 void cgroup_unload_subsys(struct cgroup_subsys *ss)
4980 {
4981         struct cgrp_cset_link *link;
4982
4983         BUG_ON(ss->module == NULL);
4984
4985         /*
4986          * we shouldn't be called if the subsystem is in use, and the use of
4987          * try_module_get() in rebind_subsystems() should ensure that it
4988          * doesn't start being used while we're killing it off.
4989          */
4990         BUG_ON(ss->root != &cgroup_dummy_root);
4991
4992         mutex_lock(&cgroup_mutex);
4993
4994         offline_css(cgroup_css(cgroup_dummy_top, ss->subsys_id));
4995
4996         if (ss->use_id)
4997                 idr_destroy(&ss->idr);
4998
4999         /* deassign the subsys_id */
5000         cgroup_subsys[ss->subsys_id] = NULL;
5001
5002         /* remove subsystem from the dummy root's list of subsystems */
5003         list_del_init(&ss->sibling);
5004
5005         /*
5006          * disentangle the css from all css_sets attached to the dummy
5007          * top. as in loading, we need to pay our respects to the hashtable
5008          * gods.
5009          */
5010         write_lock(&css_set_lock);
5011         list_for_each_entry(link, &cgroup_dummy_top->cset_links, cset_link) {
5012                 struct css_set *cset = link->cset;
5013                 unsigned long key;
5014
5015                 hash_del(&cset->hlist);
5016                 cset->subsys[ss->subsys_id] = NULL;
5017                 key = css_set_hash(cset->subsys);
5018                 hash_add(css_set_table, &cset->hlist, key);
5019         }
5020         write_unlock(&css_set_lock);
5021
5022         /*
5023          * remove subsystem's css from the cgroup_dummy_top and free it -
5024          * need to free before marking as null because ss->css_free needs
5025          * the cgrp->subsys pointer to find their state. note that this
5026          * also takes care of freeing the css_id.
5027          */
5028         ss->css_free(cgroup_css(cgroup_dummy_top, ss->subsys_id));
5029         RCU_INIT_POINTER(cgroup_dummy_top->subsys[ss->subsys_id], NULL);
5030
5031         mutex_unlock(&cgroup_mutex);
5032 }
5033 EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
5034
5035 /**
5036  * cgroup_init_early - cgroup initialization at system boot
5037  *
5038  * Initialize cgroups at system boot, and initialize any
5039  * subsystems that request early init.
5040  */
5041 int __init cgroup_init_early(void)
5042 {
5043         struct cgroup_subsys *ss;
5044         int i;
5045
5046         atomic_set(&init_css_set.refcount, 1);
5047         INIT_LIST_HEAD(&init_css_set.cgrp_links);
5048         INIT_LIST_HEAD(&init_css_set.tasks);
5049         INIT_HLIST_NODE(&init_css_set.hlist);
5050         css_set_count = 1;
5051         init_cgroup_root(&cgroup_dummy_root);
5052         cgroup_root_count = 1;
5053         RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
5054
5055         init_cgrp_cset_link.cset = &init_css_set;
5056         init_cgrp_cset_link.cgrp = cgroup_dummy_top;
5057         list_add(&init_cgrp_cset_link.cset_link, &cgroup_dummy_top->cset_links);
5058         list_add(&init_cgrp_cset_link.cgrp_link, &init_css_set.cgrp_links);
5059
5060         /* at bootup time, we don't worry about modular subsystems */
5061         for_each_builtin_subsys(ss, i) {
5062                 BUG_ON(!ss->name);
5063                 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
5064                 BUG_ON(!ss->css_alloc);
5065                 BUG_ON(!ss->css_free);
5066                 if (ss->subsys_id != i) {
5067                         printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
5068                                ss->name, ss->subsys_id);
5069                         BUG();
5070                 }
5071
5072                 if (ss->early_init)
5073                         cgroup_init_subsys(ss);
5074         }
5075         return 0;
5076 }
5077
5078 /**
5079  * cgroup_init - cgroup initialization
5080  *
5081  * Register cgroup filesystem and /proc file, and initialize
5082  * any subsystems that didn't request early init.
5083  */
5084 int __init cgroup_init(void)
5085 {
5086         struct cgroup_subsys *ss;
5087         unsigned long key;
5088         int i, err;
5089
5090         err = bdi_init(&cgroup_backing_dev_info);
5091         if (err)
5092                 return err;
5093
5094         for_each_builtin_subsys(ss, i) {
5095                 if (!ss->early_init)
5096                         cgroup_init_subsys(ss);
5097                 if (ss->use_id)
5098                         cgroup_init_idr(ss, init_css_set.subsys[ss->subsys_id]);
5099         }
5100
5101         /* allocate id for the dummy hierarchy */
5102         mutex_lock(&cgroup_mutex);
5103         mutex_lock(&cgroup_root_mutex);
5104
5105         /* Add init_css_set to the hash table */
5106         key = css_set_hash(init_css_set.subsys);
5107         hash_add(css_set_table, &init_css_set.hlist, key);
5108
5109         BUG_ON(cgroup_init_root_id(&cgroup_dummy_root, 0, 1));
5110
5111         err = idr_alloc(&cgroup_dummy_root.cgroup_idr, cgroup_dummy_top,
5112                         0, 1, GFP_KERNEL);
5113         BUG_ON(err < 0);
5114
5115         mutex_unlock(&cgroup_root_mutex);
5116         mutex_unlock(&cgroup_mutex);
5117
5118         cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
5119         if (!cgroup_kobj) {
5120                 err = -ENOMEM;
5121                 goto out;
5122         }
5123
5124         err = register_filesystem(&cgroup_fs_type);
5125         if (err < 0) {
5126                 kobject_put(cgroup_kobj);
5127                 goto out;
5128         }
5129
5130         proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
5131
5132 out:
5133         if (err)
5134                 bdi_destroy(&cgroup_backing_dev_info);
5135
5136         return err;
5137 }
5138
5139 /*
5140  * proc_cgroup_show()
5141  *  - Print task's cgroup paths into seq_file, one line for each hierarchy
5142  *  - Used for /proc/<pid>/cgroup.
5143  *  - No need to task_lock(tsk) on this tsk->cgroup reference, as it
5144  *    doesn't really matter if tsk->cgroup changes after we read it,
5145  *    and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
5146  *    anyway.  No need to check that tsk->cgroup != NULL, thanks to
5147  *    the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
5148  *    cgroup to top_cgroup.
5149  */
5150
5151 /* TODO: Use a proper seq_file iterator */
5152 int proc_cgroup_show(struct seq_file *m, void *v)
5153 {
5154         struct pid *pid;
5155         struct task_struct *tsk;
5156         char *buf;
5157         int retval;
5158         struct cgroupfs_root *root;
5159
5160         retval = -ENOMEM;
5161         buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5162         if (!buf)
5163                 goto out;
5164
5165         retval = -ESRCH;
5166         pid = m->private;
5167         tsk = get_pid_task(pid, PIDTYPE_PID);
5168         if (!tsk)
5169                 goto out_free;
5170
5171         retval = 0;
5172
5173         mutex_lock(&cgroup_mutex);
5174
5175         for_each_active_root(root) {
5176                 struct cgroup_subsys *ss;
5177                 struct cgroup *cgrp;
5178                 int count = 0;
5179
5180                 seq_printf(m, "%d:", root->hierarchy_id);
5181                 for_each_root_subsys(root, ss)
5182                         seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
5183                 if (strlen(root->name))
5184                         seq_printf(m, "%sname=%s", count ? "," : "",
5185                                    root->name);
5186                 seq_putc(m, ':');
5187                 cgrp = task_cgroup_from_root(tsk, root);
5188                 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
5189                 if (retval < 0)
5190                         goto out_unlock;
5191                 seq_puts(m, buf);
5192                 seq_putc(m, '\n');
5193         }
5194
5195 out_unlock:
5196         mutex_unlock(&cgroup_mutex);
5197         put_task_struct(tsk);
5198 out_free:
5199         kfree(buf);
5200 out:
5201         return retval;
5202 }
5203
5204 /* Display information about each subsystem and each hierarchy */
5205 static int proc_cgroupstats_show(struct seq_file *m, void *v)
5206 {
5207         struct cgroup_subsys *ss;
5208         int i;
5209
5210         seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
5211         /*
5212          * ideally we don't want subsystems moving around while we do this.
5213          * cgroup_mutex is also necessary to guarantee an atomic snapshot of
5214          * subsys/hierarchy state.
5215          */
5216         mutex_lock(&cgroup_mutex);
5217
5218         for_each_subsys(ss, i)
5219                 seq_printf(m, "%s\t%d\t%d\t%d\n",
5220                            ss->name, ss->root->hierarchy_id,
5221                            ss->root->number_of_cgroups, !ss->disabled);
5222
5223         mutex_unlock(&cgroup_mutex);
5224         return 0;
5225 }
5226
5227 static int cgroupstats_open(struct inode *inode, struct file *file)
5228 {
5229         return single_open(file, proc_cgroupstats_show, NULL);
5230 }
5231
5232 static const struct file_operations proc_cgroupstats_operations = {
5233         .open = cgroupstats_open,
5234         .read = seq_read,
5235         .llseek = seq_lseek,
5236         .release = single_release,
5237 };
5238
5239 /**
5240  * cgroup_fork - attach newly forked task to its parents cgroup.
5241  * @child: pointer to task_struct of forking parent process.
5242  *
5243  * Description: A task inherits its parent's cgroup at fork().
5244  *
5245  * A pointer to the shared css_set was automatically copied in
5246  * fork.c by dup_task_struct().  However, we ignore that copy, since
5247  * it was not made under the protection of RCU or cgroup_mutex, so
5248  * might no longer be a valid cgroup pointer.  cgroup_attach_task() might
5249  * have already changed current->cgroups, allowing the previously
5250  * referenced cgroup group to be removed and freed.
5251  *
5252  * At the point that cgroup_fork() is called, 'current' is the parent
5253  * task, and the passed argument 'child' points to the child task.
5254  */
5255 void cgroup_fork(struct task_struct *child)
5256 {
5257         task_lock(current);
5258         get_css_set(task_css_set(current));
5259         child->cgroups = current->cgroups;
5260         task_unlock(current);
5261         INIT_LIST_HEAD(&child->cg_list);
5262 }
5263
5264 /**
5265  * cgroup_post_fork - called on a new task after adding it to the task list
5266  * @child: the task in question
5267  *
5268  * Adds the task to the list running through its css_set if necessary and
5269  * call the subsystem fork() callbacks.  Has to be after the task is
5270  * visible on the task list in case we race with the first call to
5271  * cgroup_task_iter_start() - to guarantee that the new task ends up on its
5272  * list.
5273  */
5274 void cgroup_post_fork(struct task_struct *child)
5275 {
5276         struct cgroup_subsys *ss;
5277         int i;
5278
5279         /*
5280          * use_task_css_set_links is set to 1 before we walk the tasklist
5281          * under the tasklist_lock and we read it here after we added the child
5282          * to the tasklist under the tasklist_lock as well. If the child wasn't
5283          * yet in the tasklist when we walked through it from
5284          * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
5285          * should be visible now due to the paired locking and barriers implied
5286          * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
5287          * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
5288          * lock on fork.
5289          */
5290         if (use_task_css_set_links) {
5291                 write_lock(&css_set_lock);
5292                 task_lock(child);
5293                 if (list_empty(&child->cg_list))
5294                         list_add(&child->cg_list, &task_css_set(child)->tasks);
5295                 task_unlock(child);
5296                 write_unlock(&css_set_lock);
5297         }
5298
5299         /*
5300          * Call ss->fork().  This must happen after @child is linked on
5301          * css_set; otherwise, @child might change state between ->fork()
5302          * and addition to css_set.
5303          */
5304         if (need_forkexit_callback) {
5305                 /*
5306                  * fork/exit callbacks are supported only for builtin
5307                  * subsystems, and the builtin section of the subsys
5308                  * array is immutable, so we don't need to lock the
5309                  * subsys array here. On the other hand, modular section
5310                  * of the array can be freed at module unload, so we
5311                  * can't touch that.
5312                  */
5313                 for_each_builtin_subsys(ss, i)
5314                         if (ss->fork)
5315                                 ss->fork(child);
5316         }
5317 }
5318
5319 /**
5320  * cgroup_exit - detach cgroup from exiting task
5321  * @tsk: pointer to task_struct of exiting process
5322  * @run_callback: run exit callbacks?
5323  *
5324  * Description: Detach cgroup from @tsk and release it.
5325  *
5326  * Note that cgroups marked notify_on_release force every task in
5327  * them to take the global cgroup_mutex mutex when exiting.
5328  * This could impact scaling on very large systems.  Be reluctant to
5329  * use notify_on_release cgroups where very high task exit scaling
5330  * is required on large systems.
5331  *
5332  * the_top_cgroup_hack:
5333  *
5334  *    Set the exiting tasks cgroup to the root cgroup (top_cgroup).
5335  *
5336  *    We call cgroup_exit() while the task is still competent to
5337  *    handle notify_on_release(), then leave the task attached to the
5338  *    root cgroup in each hierarchy for the remainder of its exit.
5339  *
5340  *    To do this properly, we would increment the reference count on
5341  *    top_cgroup, and near the very end of the kernel/exit.c do_exit()
5342  *    code we would add a second cgroup function call, to drop that
5343  *    reference.  This would just create an unnecessary hot spot on
5344  *    the top_cgroup reference count, to no avail.
5345  *
5346  *    Normally, holding a reference to a cgroup without bumping its
5347  *    count is unsafe.   The cgroup could go away, or someone could
5348  *    attach us to a different cgroup, decrementing the count on
5349  *    the first cgroup that we never incremented.  But in this case,
5350  *    top_cgroup isn't going away, and either task has PF_EXITING set,
5351  *    which wards off any cgroup_attach_task() attempts, or task is a failed
5352  *    fork, never visible to cgroup_attach_task.
5353  */
5354 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
5355 {
5356         struct cgroup_subsys *ss;
5357         struct css_set *cset;
5358         int i;
5359
5360         /*
5361          * Unlink from the css_set task list if necessary.
5362          * Optimistically check cg_list before taking
5363          * css_set_lock
5364          */
5365         if (!list_empty(&tsk->cg_list)) {
5366                 write_lock(&css_set_lock);
5367                 if (!list_empty(&tsk->cg_list))
5368                         list_del_init(&tsk->cg_list);
5369                 write_unlock(&css_set_lock);
5370         }
5371
5372         /* Reassign the task to the init_css_set. */
5373         task_lock(tsk);
5374         cset = task_css_set(tsk);
5375         RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
5376
5377         if (run_callbacks && need_forkexit_callback) {
5378                 /*
5379                  * fork/exit callbacks are supported only for builtin
5380                  * subsystems, see cgroup_post_fork() for details.
5381                  */
5382                 for_each_builtin_subsys(ss, i) {
5383                         if (ss->exit) {
5384                                 struct cgroup_subsys_state *old_css = cset->subsys[i];
5385                                 struct cgroup_subsys_state *css = task_css(tsk, i);
5386
5387                                 ss->exit(css, old_css, tsk);
5388                         }
5389                 }
5390         }
5391         task_unlock(tsk);
5392
5393         put_css_set_taskexit(cset);
5394 }
5395
5396 static void check_for_release(struct cgroup *cgrp)
5397 {
5398         if (cgroup_is_releasable(cgrp) &&
5399             list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
5400                 /*
5401                  * Control Group is currently removeable. If it's not
5402                  * already queued for a userspace notification, queue
5403                  * it now
5404                  */
5405                 int need_schedule_work = 0;
5406
5407                 raw_spin_lock(&release_list_lock);
5408                 if (!cgroup_is_dead(cgrp) &&
5409                     list_empty(&cgrp->release_list)) {
5410                         list_add(&cgrp->release_list, &release_list);
5411                         need_schedule_work = 1;
5412                 }
5413                 raw_spin_unlock(&release_list_lock);
5414                 if (need_schedule_work)
5415                         schedule_work(&release_agent_work);
5416         }
5417 }
5418
5419 /*
5420  * Notify userspace when a cgroup is released, by running the
5421  * configured release agent with the name of the cgroup (path
5422  * relative to the root of cgroup file system) as the argument.
5423  *
5424  * Most likely, this user command will try to rmdir this cgroup.
5425  *
5426  * This races with the possibility that some other task will be
5427  * attached to this cgroup before it is removed, or that some other
5428  * user task will 'mkdir' a child cgroup of this cgroup.  That's ok.
5429  * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5430  * unused, and this cgroup will be reprieved from its death sentence,
5431  * to continue to serve a useful existence.  Next time it's released,
5432  * we will get notified again, if it still has 'notify_on_release' set.
5433  *
5434  * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5435  * means only wait until the task is successfully execve()'d.  The
5436  * separate release agent task is forked by call_usermodehelper(),
5437  * then control in this thread returns here, without waiting for the
5438  * release agent task.  We don't bother to wait because the caller of
5439  * this routine has no use for the exit status of the release agent
5440  * task, so no sense holding our caller up for that.
5441  */
5442 static void cgroup_release_agent(struct work_struct *work)
5443 {
5444         BUG_ON(work != &release_agent_work);
5445         mutex_lock(&cgroup_mutex);
5446         raw_spin_lock(&release_list_lock);
5447         while (!list_empty(&release_list)) {
5448                 char *argv[3], *envp[3];
5449                 int i;
5450                 char *pathbuf = NULL, *agentbuf = NULL;
5451                 struct cgroup *cgrp = list_entry(release_list.next,
5452                                                     struct cgroup,
5453                                                     release_list);
5454                 list_del_init(&cgrp->release_list);
5455                 raw_spin_unlock(&release_list_lock);
5456                 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
5457                 if (!pathbuf)
5458                         goto continue_free;
5459                 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
5460                         goto continue_free;
5461                 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5462                 if (!agentbuf)
5463                         goto continue_free;
5464
5465                 i = 0;
5466                 argv[i++] = agentbuf;
5467                 argv[i++] = pathbuf;
5468                 argv[i] = NULL;
5469
5470                 i = 0;
5471                 /* minimal command environment */
5472                 envp[i++] = "HOME=/";
5473                 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5474                 envp[i] = NULL;
5475
5476                 /* Drop the lock while we invoke the usermode helper,
5477                  * since the exec could involve hitting disk and hence
5478                  * be a slow process */
5479                 mutex_unlock(&cgroup_mutex);
5480                 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
5481                 mutex_lock(&cgroup_mutex);
5482  continue_free:
5483                 kfree(pathbuf);
5484                 kfree(agentbuf);
5485                 raw_spin_lock(&release_list_lock);
5486         }
5487         raw_spin_unlock(&release_list_lock);
5488         mutex_unlock(&cgroup_mutex);
5489 }
5490
5491 static int __init cgroup_disable(char *str)
5492 {
5493         struct cgroup_subsys *ss;
5494         char *token;
5495         int i;
5496
5497         while ((token = strsep(&str, ",")) != NULL) {
5498                 if (!*token)
5499                         continue;
5500
5501                 /*
5502                  * cgroup_disable, being at boot time, can't know about
5503                  * module subsystems, so we don't worry about them.
5504                  */
5505                 for_each_builtin_subsys(ss, i) {
5506                         if (!strcmp(token, ss->name)) {
5507                                 ss->disabled = 1;
5508                                 printk(KERN_INFO "Disabling %s control group"
5509                                         " subsystem\n", ss->name);
5510                                 break;
5511                         }
5512                 }
5513         }
5514         return 1;
5515 }
5516 __setup("cgroup_disable=", cgroup_disable);
5517
5518 /*
5519  * Functons for CSS ID.
5520  */
5521
5522 /* to get ID other than 0, this should be called when !cgroup_is_dead() */
5523 unsigned short css_id(struct cgroup_subsys_state *css)
5524 {
5525         struct css_id *cssid;
5526
5527         /*
5528          * This css_id() can return correct value when somone has refcnt
5529          * on this or this is under rcu_read_lock(). Once css->id is allocated,
5530          * it's unchanged until freed.
5531          */
5532         cssid = rcu_dereference_raw(css->id);
5533
5534         if (cssid)
5535                 return cssid->id;
5536         return 0;
5537 }
5538 EXPORT_SYMBOL_GPL(css_id);
5539
5540 /**
5541  *  css_is_ancestor - test "root" css is an ancestor of "child"
5542  * @child: the css to be tested.
5543  * @root: the css supporsed to be an ancestor of the child.
5544  *
5545  * Returns true if "root" is an ancestor of "child" in its hierarchy. Because
5546  * this function reads css->id, the caller must hold rcu_read_lock().
5547  * But, considering usual usage, the csses should be valid objects after test.
5548  * Assuming that the caller will do some action to the child if this returns
5549  * returns true, the caller must take "child";s reference count.
5550  * If "child" is valid object and this returns true, "root" is valid, too.
5551  */
5552
5553 bool css_is_ancestor(struct cgroup_subsys_state *child,
5554                     const struct cgroup_subsys_state *root)
5555 {
5556         struct css_id *child_id;
5557         struct css_id *root_id;
5558
5559         child_id  = rcu_dereference(child->id);
5560         if (!child_id)
5561                 return false;
5562         root_id = rcu_dereference(root->id);
5563         if (!root_id)
5564                 return false;
5565         if (child_id->depth < root_id->depth)
5566                 return false;
5567         if (child_id->stack[root_id->depth] != root_id->id)
5568                 return false;
5569         return true;
5570 }
5571
5572 void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
5573 {
5574         struct css_id *id = rcu_dereference_protected(css->id, true);
5575
5576         /* When this is called before css_id initialization, id can be NULL */
5577         if (!id)
5578                 return;
5579
5580         BUG_ON(!ss->use_id);
5581
5582         rcu_assign_pointer(id->css, NULL);
5583         rcu_assign_pointer(css->id, NULL);
5584         spin_lock(&ss->id_lock);
5585         idr_remove(&ss->idr, id->id);
5586         spin_unlock(&ss->id_lock);
5587         kfree_rcu(id, rcu_head);
5588 }
5589 EXPORT_SYMBOL_GPL(free_css_id);
5590
5591 /*
5592  * This is called by init or create(). Then, calls to this function are
5593  * always serialized (By cgroup_mutex() at create()).
5594  */
5595
5596 static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
5597 {
5598         struct css_id *newid;
5599         int ret, size;
5600
5601         BUG_ON(!ss->use_id);
5602
5603         size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
5604         newid = kzalloc(size, GFP_KERNEL);
5605         if (!newid)
5606                 return ERR_PTR(-ENOMEM);
5607
5608         idr_preload(GFP_KERNEL);
5609         spin_lock(&ss->id_lock);
5610         /* Don't use 0. allocates an ID of 1-65535 */
5611         ret = idr_alloc(&ss->idr, newid, 1, CSS_ID_MAX + 1, GFP_NOWAIT);
5612         spin_unlock(&ss->id_lock);
5613         idr_preload_end();
5614
5615         /* Returns error when there are no free spaces for new ID.*/
5616         if (ret < 0)
5617                 goto err_out;
5618
5619         newid->id = ret;
5620         newid->depth = depth;
5621         return newid;
5622 err_out:
5623         kfree(newid);
5624         return ERR_PTR(ret);
5625
5626 }
5627
5628 static int __init_or_module cgroup_init_idr(struct cgroup_subsys *ss,
5629                                             struct cgroup_subsys_state *rootcss)
5630 {
5631         struct css_id *newid;
5632
5633         spin_lock_init(&ss->id_lock);
5634         idr_init(&ss->idr);
5635
5636         newid = get_new_cssid(ss, 0);
5637         if (IS_ERR(newid))
5638                 return PTR_ERR(newid);
5639
5640         newid->stack[0] = newid->id;
5641         RCU_INIT_POINTER(newid->css, rootcss);
5642         RCU_INIT_POINTER(rootcss->id, newid);
5643         return 0;
5644 }
5645
5646 static int alloc_css_id(struct cgroup_subsys_state *child_css)
5647 {
5648         struct cgroup_subsys_state *parent_css = css_parent(child_css);
5649         struct css_id *child_id, *parent_id;
5650         int i, depth;
5651
5652         parent_id = rcu_dereference_protected(parent_css->id, true);
5653         depth = parent_id->depth + 1;
5654
5655         child_id = get_new_cssid(child_css->ss, depth);
5656         if (IS_ERR(child_id))
5657                 return PTR_ERR(child_id);
5658
5659         for (i = 0; i < depth; i++)
5660                 child_id->stack[i] = parent_id->stack[i];
5661         child_id->stack[depth] = child_id->id;
5662         /*
5663          * child_id->css pointer will be set after this cgroup is available
5664          * see cgroup_populate_dir()
5665          */
5666         rcu_assign_pointer(child_css->id, child_id);
5667
5668         return 0;
5669 }
5670
5671 /**
5672  * css_lookup - lookup css by id
5673  * @ss: cgroup subsys to be looked into.
5674  * @id: the id
5675  *
5676  * Returns pointer to cgroup_subsys_state if there is valid one with id.
5677  * NULL if not. Should be called under rcu_read_lock()
5678  */
5679 struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
5680 {
5681         struct css_id *cssid = NULL;
5682
5683         BUG_ON(!ss->use_id);
5684         cssid = idr_find(&ss->idr, id);
5685
5686         if (unlikely(!cssid))
5687                 return NULL;
5688
5689         return rcu_dereference(cssid->css);
5690 }
5691 EXPORT_SYMBOL_GPL(css_lookup);
5692
5693 /**
5694  * cgroup_css_from_dir - get corresponding css from file open on cgroup dir
5695  * @f: directory file of interest
5696  * @id: subsystem id of interest
5697  *
5698  * Must be called under RCU read lock.  The caller is responsible for
5699  * pinning the returned css if it needs to be accessed outside the RCU
5700  * critical section.
5701  */
5702 struct cgroup_subsys_state *cgroup_css_from_dir(struct file *f, int id)
5703 {
5704         struct cgroup *cgrp;
5705         struct inode *inode;
5706         struct cgroup_subsys_state *css;
5707
5708         WARN_ON_ONCE(!rcu_read_lock_held());
5709
5710         inode = file_inode(f);
5711         /* check in cgroup filesystem dir */
5712         if (inode->i_op != &cgroup_dir_inode_operations)
5713                 return ERR_PTR(-EBADF);
5714
5715         if (id < 0 || id >= CGROUP_SUBSYS_COUNT)
5716                 return ERR_PTR(-EINVAL);
5717
5718         /* get cgroup */
5719         cgrp = __d_cgrp(f->f_dentry);
5720         css = cgroup_css(cgrp, id);
5721         return css ? css : ERR_PTR(-ENOENT);
5722 }
5723
5724 /**
5725  * css_from_id - lookup css by id
5726  * @id: the cgroup id
5727  * @ss: cgroup subsys to be looked into
5728  *
5729  * Returns the css if there's valid one with @id, otherwise returns NULL.
5730  * Should be called under rcu_read_lock().
5731  */
5732 struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
5733 {
5734         struct cgroup *cgrp;
5735
5736         rcu_lockdep_assert(rcu_read_lock_held() ||
5737                            lockdep_is_held(&cgroup_mutex),
5738                            "css_from_id() needs proper protection");
5739
5740         cgrp = idr_find(&ss->root->cgroup_idr, id);
5741         if (cgrp)
5742                 return cgroup_css(cgrp, ss->subsys_id);
5743         return NULL;
5744 }
5745
5746 #ifdef CONFIG_CGROUP_DEBUG
5747 static struct cgroup_subsys_state *
5748 debug_css_alloc(struct cgroup_subsys_state *parent_css)
5749 {
5750         struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5751
5752         if (!css)
5753                 return ERR_PTR(-ENOMEM);
5754
5755         return css;
5756 }
5757
5758 static void debug_css_free(struct cgroup_subsys_state *css)
5759 {
5760         kfree(css);
5761 }
5762
5763 static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
5764                                 struct cftype *cft)
5765 {
5766         return cgroup_task_count(css->cgroup);
5767 }
5768
5769 static u64 current_css_set_read(struct cgroup_subsys_state *css,
5770                                 struct cftype *cft)
5771 {
5772         return (u64)(unsigned long)current->cgroups;
5773 }
5774
5775 static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
5776                                          struct cftype *cft)
5777 {
5778         u64 count;
5779
5780         rcu_read_lock();
5781         count = atomic_read(&task_css_set(current)->refcount);
5782         rcu_read_unlock();
5783         return count;
5784 }
5785
5786 static int current_css_set_cg_links_read(struct cgroup_subsys_state *css,
5787                                          struct cftype *cft,
5788                                          struct seq_file *seq)
5789 {
5790         struct cgrp_cset_link *link;
5791         struct css_set *cset;
5792
5793         read_lock(&css_set_lock);
5794         rcu_read_lock();
5795         cset = rcu_dereference(current->cgroups);
5796         list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
5797                 struct cgroup *c = link->cgrp;
5798                 const char *name;
5799
5800                 if (c->dentry)
5801                         name = c->dentry->d_name.name;
5802                 else
5803                         name = "?";
5804                 seq_printf(seq, "Root %d group %s\n",
5805                            c->root->hierarchy_id, name);
5806         }
5807         rcu_read_unlock();
5808         read_unlock(&css_set_lock);
5809         return 0;
5810 }
5811
5812 #define MAX_TASKS_SHOWN_PER_CSS 25
5813 static int cgroup_css_links_read(struct cgroup_subsys_state *css,
5814                                  struct cftype *cft, struct seq_file *seq)
5815 {
5816         struct cgrp_cset_link *link;
5817
5818         read_lock(&css_set_lock);
5819         list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
5820                 struct css_set *cset = link->cset;
5821                 struct task_struct *task;
5822                 int count = 0;
5823                 seq_printf(seq, "css_set %p\n", cset);
5824                 list_for_each_entry(task, &cset->tasks, cg_list) {
5825                         if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5826                                 seq_puts(seq, "  ...\n");
5827                                 break;
5828                         } else {
5829                                 seq_printf(seq, "  task %d\n",
5830                                            task_pid_vnr(task));
5831                         }
5832                 }
5833         }
5834         read_unlock(&css_set_lock);
5835         return 0;
5836 }
5837
5838 static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
5839 {
5840         return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
5841 }
5842
5843 static struct cftype debug_files[] =  {
5844         {
5845                 .name = "taskcount",
5846                 .read_u64 = debug_taskcount_read,
5847         },
5848
5849         {
5850                 .name = "current_css_set",
5851                 .read_u64 = current_css_set_read,
5852         },
5853
5854         {
5855                 .name = "current_css_set_refcount",
5856                 .read_u64 = current_css_set_refcount_read,
5857         },
5858
5859         {
5860                 .name = "current_css_set_cg_links",
5861                 .read_seq_string = current_css_set_cg_links_read,
5862         },
5863
5864         {
5865                 .name = "cgroup_css_links",
5866                 .read_seq_string = cgroup_css_links_read,
5867         },
5868
5869         {
5870                 .name = "releasable",
5871                 .read_u64 = releasable_read,
5872         },
5873
5874         { }     /* terminate */
5875 };
5876
5877 struct cgroup_subsys debug_subsys = {
5878         .name = "debug",
5879         .css_alloc = debug_css_alloc,
5880         .css_free = debug_css_free,
5881         .subsys_id = debug_subsys_id,
5882         .base_cftypes = debug_files,
5883 };
5884 #endif /* CONFIG_CGROUP_DEBUG */