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