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