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