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