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