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