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