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