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