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