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