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