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