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