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