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