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