cgroup: relocate setting of CGRP_DEAD
[linux-2.6-block.git] / kernel / cgroup.c
CommitLineData
ddbcc7e8 1/*
ddbcc7e8
PM
2 * Generic process-grouping system.
3 *
4 * Based originally on the cpuset system, extracted by Paul Menage
5 * Copyright (C) 2006 Google, Inc
6 *
0dea1168
KS
7 * Notifications support
8 * Copyright (C) 2009 Nokia Corporation
9 * Author: Kirill A. Shutemov
10 *
ddbcc7e8
PM
11 * Copyright notices from the original cpuset code:
12 * --------------------------------------------------
13 * Copyright (C) 2003 BULL SA.
14 * Copyright (C) 2004-2006 Silicon Graphics, Inc.
15 *
16 * Portions derived from Patrick Mochel's sysfs code.
17 * sysfs is Copyright (c) 2001-3 Patrick Mochel
18 *
19 * 2003-10-10 Written by Simon Derr.
20 * 2003-10-22 Updates by Stephen Hemminger.
21 * 2004 May-July Rework by Paul Jackson.
22 * ---------------------------------------------------
23 *
24 * This file is subject to the terms and conditions of the GNU General Public
25 * License. See the file COPYING in the main directory of the Linux
26 * distribution for more details.
27 */
28
29#include <linux/cgroup.h>
2ce9738b 30#include <linux/cred.h>
c6d57f33 31#include <linux/ctype.h>
ddbcc7e8 32#include <linux/errno.h>
2ce9738b 33#include <linux/init_task.h>
ddbcc7e8
PM
34#include <linux/kernel.h>
35#include <linux/list.h>
36#include <linux/mm.h>
37#include <linux/mutex.h>
38#include <linux/mount.h>
39#include <linux/pagemap.h>
a424316c 40#include <linux/proc_fs.h>
ddbcc7e8
PM
41#include <linux/rcupdate.h>
42#include <linux/sched.h>
ddbcc7e8 43#include <linux/slab.h>
ddbcc7e8 44#include <linux/spinlock.h>
96d365e0 45#include <linux/rwsem.h>
ddbcc7e8 46#include <linux/string.h>
bbcb81d0 47#include <linux/sort.h>
81a6a5cd 48#include <linux/kmod.h>
846c7bb0
BS
49#include <linux/delayacct.h>
50#include <linux/cgroupstats.h>
0ac801fe 51#include <linux/hashtable.h>
096b7fe0 52#include <linux/pid_namespace.h>
2c6ab6d2 53#include <linux/idr.h>
d1d9fd33 54#include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
c4c27fbd 55#include <linux/kthread.h>
776f02fa 56#include <linux/delay.h>
846c7bb0 57
60063497 58#include <linux/atomic.h>
ddbcc7e8 59
b1a21367
TH
60/*
61 * pidlists linger the following amount before being destroyed. The goal
62 * is avoiding frequent destruction in the middle of consecutive read calls
63 * Expiring in the middle is a performance problem not a correctness one.
64 * 1 sec should be enough.
65 */
66#define CGROUP_PIDLIST_DESTROY_DELAY HZ
67
8d7e6fb0
TH
68#define CGROUP_FILE_NAME_MAX (MAX_CGROUP_TYPE_NAMELEN + \
69 MAX_CFTYPE_NAME + 2)
70
ace2bee8
TH
71/*
72 * cgroup_tree_mutex nests above cgroup_mutex and protects cftypes, file
73 * creation/removal and hierarchy changing operations including cgroup
74 * creation, removal, css association and controller rebinding. This outer
75 * lock is needed mainly to resolve the circular dependency between kernfs
76 * active ref and cgroup_mutex. cgroup_tree_mutex nests above both.
77 */
78static DEFINE_MUTEX(cgroup_tree_mutex);
79
e25e2cbb
TH
80/*
81 * cgroup_mutex is the master lock. Any modification to cgroup or its
82 * hierarchy must be performed while holding it.
0e1d768f
TH
83 *
84 * css_set_rwsem protects task->cgroups pointer, the list of css_set
85 * objects, and the chain of tasks off each css_set.
86 *
87 * These locks are exported if CONFIG_PROVE_RCU so that accessors in
88 * cgroup.h can use them for lockdep annotations.
e25e2cbb 89 */
2219449a
TH
90#ifdef CONFIG_PROVE_RCU
91DEFINE_MUTEX(cgroup_mutex);
0e1d768f
TH
92DECLARE_RWSEM(css_set_rwsem);
93EXPORT_SYMBOL_GPL(cgroup_mutex);
94EXPORT_SYMBOL_GPL(css_set_rwsem);
2219449a 95#else
81a6a5cd 96static DEFINE_MUTEX(cgroup_mutex);
0e1d768f 97static DECLARE_RWSEM(css_set_rwsem);
2219449a
TH
98#endif
99
69e943b7
TH
100/*
101 * Protects cgroup_subsys->release_agent_path. Modifying it also requires
102 * cgroup_mutex. Reading requires either cgroup_mutex or this spinlock.
103 */
104static DEFINE_SPINLOCK(release_agent_path_lock);
105
ace2bee8 106#define cgroup_assert_mutexes_or_rcu_locked() \
87fb54f1 107 rcu_lockdep_assert(rcu_read_lock_held() || \
ace2bee8 108 lockdep_is_held(&cgroup_tree_mutex) || \
87fb54f1 109 lockdep_is_held(&cgroup_mutex), \
ace2bee8 110 "cgroup_[tree_]mutex or RCU read lock required");
87fb54f1 111
e5fca243
TH
112/*
113 * cgroup destruction makes heavy use of work items and there can be a lot
114 * of concurrent destructions. Use a separate workqueue so that cgroup
115 * destruction work items don't end up filling up max_active of system_wq
116 * which may lead to deadlock.
117 */
118static struct workqueue_struct *cgroup_destroy_wq;
119
b1a21367
TH
120/*
121 * pidlist destructions need to be flushed on cgroup destruction. Use a
122 * separate workqueue as flush domain.
123 */
124static struct workqueue_struct *cgroup_pidlist_destroy_wq;
125
3ed80a62 126/* generate an array of cgroup subsystem pointers */
073219e9 127#define SUBSYS(_x) [_x ## _cgrp_id] = &_x ## _cgrp_subsys,
3ed80a62 128static struct cgroup_subsys *cgroup_subsys[] = {
ddbcc7e8
PM
129#include <linux/cgroup_subsys.h>
130};
073219e9
TH
131#undef SUBSYS
132
133/* array of cgroup subsystem names */
134#define SUBSYS(_x) [_x ## _cgrp_id] = #_x,
135static const char *cgroup_subsys_name[] = {
136#include <linux/cgroup_subsys.h>
137};
138#undef SUBSYS
ddbcc7e8 139
ddbcc7e8 140/*
9871bf95
TH
141 * The dummy hierarchy, reserved for the subsystems that are otherwise
142 * unattached - it never has more than a single cgroup, and all tasks are
143 * part of that cgroup.
ddbcc7e8 144 */
9871bf95
TH
145static struct cgroupfs_root cgroup_dummy_root;
146
147/* dummy_top is a shorthand for the dummy hierarchy's top cgroup */
148static struct cgroup * const cgroup_dummy_top = &cgroup_dummy_root.top_cgroup;
ddbcc7e8
PM
149
150/* The list of hierarchy roots */
151
9871bf95
TH
152static LIST_HEAD(cgroup_roots);
153static int cgroup_root_count;
ddbcc7e8 154
3417ae1f 155/* hierarchy ID allocation and mapping, protected by cgroup_mutex */
1a574231 156static DEFINE_IDR(cgroup_hierarchy_idr);
2c6ab6d2 157
794611a1
LZ
158/*
159 * Assign a monotonically increasing serial number to cgroups. It
160 * guarantees cgroups with bigger numbers are newer than those with smaller
161 * numbers. Also, as cgroups are always appended to the parent's
162 * ->children list, it guarantees that sibling cgroups are always sorted in
00356bd5
TH
163 * the ascending serial number order on the list. Protected by
164 * cgroup_mutex.
794611a1 165 */
00356bd5 166static u64 cgroup_serial_nr_next = 1;
794611a1 167
ddbcc7e8 168/* This flag indicates whether tasks in the fork and exit paths should
a043e3b2
LZ
169 * check for fork/exit handlers to call. This avoids us having to do
170 * extra work in the fork/exit path if none of the subsystems need to
171 * be called.
ddbcc7e8 172 */
8947f9d5 173static int need_forkexit_callback __read_mostly;
ddbcc7e8 174
628f7cd4
TH
175static struct cftype cgroup_base_files[];
176
59f5296b 177static void cgroup_put(struct cgroup *cgrp);
f2e85d57
TH
178static int rebind_subsystems(struct cgroupfs_root *root,
179 unsigned long added_mask, unsigned removed_mask);
f20104de 180static void cgroup_destroy_css_killed(struct cgroup *cgrp);
42809dd4 181static int cgroup_destroy_locked(struct cgroup *cgrp);
2bb566cb
TH
182static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
183 bool is_add);
b1a21367 184static void cgroup_pidlist_destroy_all(struct cgroup *cgrp);
42809dd4 185
95109b62
TH
186/**
187 * cgroup_css - obtain a cgroup's css for the specified subsystem
188 * @cgrp: the cgroup of interest
ca8bdcaf 189 * @ss: the subsystem of interest (%NULL returns the dummy_css)
95109b62 190 *
ca8bdcaf
TH
191 * Return @cgrp's css (cgroup_subsys_state) associated with @ss. This
192 * function must be called either under cgroup_mutex or rcu_read_lock() and
193 * the caller is responsible for pinning the returned css if it wants to
194 * keep accessing it outside the said locks. This function may return
195 * %NULL if @cgrp doesn't have @subsys_id enabled.
95109b62
TH
196 */
197static struct cgroup_subsys_state *cgroup_css(struct cgroup *cgrp,
ca8bdcaf 198 struct cgroup_subsys *ss)
95109b62 199{
ca8bdcaf 200 if (ss)
aec25020 201 return rcu_dereference_check(cgrp->subsys[ss->id],
ace2bee8
TH
202 lockdep_is_held(&cgroup_tree_mutex) ||
203 lockdep_is_held(&cgroup_mutex));
ca8bdcaf
TH
204 else
205 return &cgrp->dummy_css;
95109b62 206}
42809dd4 207
ddbcc7e8 208/* convenient tests for these bits */
54766d4a 209static inline bool cgroup_is_dead(const struct cgroup *cgrp)
ddbcc7e8 210{
54766d4a 211 return test_bit(CGRP_DEAD, &cgrp->flags);
ddbcc7e8
PM
212}
213
59f5296b
TH
214struct cgroup_subsys_state *seq_css(struct seq_file *seq)
215{
2bd59d48
TH
216 struct kernfs_open_file *of = seq->private;
217 struct cgroup *cgrp = of->kn->parent->priv;
218 struct cftype *cft = seq_cft(seq);
219
220 /*
221 * This is open and unprotected implementation of cgroup_css().
222 * seq_css() is only called from a kernfs file operation which has
223 * an active reference on the file. Because all the subsystem
224 * files are drained before a css is disassociated with a cgroup,
225 * the matching css from the cgroup's subsys table is guaranteed to
226 * be and stay valid until the enclosing operation is complete.
227 */
228 if (cft->ss)
229 return rcu_dereference_raw(cgrp->subsys[cft->ss->id]);
230 else
231 return &cgrp->dummy_css;
59f5296b
TH
232}
233EXPORT_SYMBOL_GPL(seq_css);
234
78574cf9
LZ
235/**
236 * cgroup_is_descendant - test ancestry
237 * @cgrp: the cgroup to be tested
238 * @ancestor: possible ancestor of @cgrp
239 *
240 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
241 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
242 * and @ancestor are accessible.
243 */
244bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
245{
246 while (cgrp) {
247 if (cgrp == ancestor)
248 return true;
249 cgrp = cgrp->parent;
250 }
251 return false;
252}
ddbcc7e8 253
e9685a03 254static int cgroup_is_releasable(const struct cgroup *cgrp)
81a6a5cd
PM
255{
256 const int bits =
bd89aabc
PM
257 (1 << CGRP_RELEASABLE) |
258 (1 << CGRP_NOTIFY_ON_RELEASE);
259 return (cgrp->flags & bits) == bits;
81a6a5cd
PM
260}
261
e9685a03 262static int notify_on_release(const struct cgroup *cgrp)
81a6a5cd 263{
bd89aabc 264 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
81a6a5cd
PM
265}
266
1c6727af
TH
267/**
268 * for_each_css - iterate all css's of a cgroup
269 * @css: the iteration cursor
270 * @ssid: the index of the subsystem, CGROUP_SUBSYS_COUNT after reaching the end
271 * @cgrp: the target cgroup to iterate css's of
272 *
273 * Should be called under cgroup_mutex.
274 */
275#define for_each_css(css, ssid, cgrp) \
276 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT; (ssid)++) \
277 if (!((css) = rcu_dereference_check( \
278 (cgrp)->subsys[(ssid)], \
ace2bee8 279 lockdep_is_held(&cgroup_tree_mutex) || \
1c6727af
TH
280 lockdep_is_held(&cgroup_mutex)))) { } \
281 else
282
30159ec7 283/**
3ed80a62 284 * for_each_subsys - iterate all enabled cgroup subsystems
30159ec7 285 * @ss: the iteration cursor
780cd8b3 286 * @ssid: the index of @ss, CGROUP_SUBSYS_COUNT after reaching the end
30159ec7 287 */
780cd8b3 288#define for_each_subsys(ss, ssid) \
3ed80a62
TH
289 for ((ssid) = 0; (ssid) < CGROUP_SUBSYS_COUNT && \
290 (((ss) = cgroup_subsys[ssid]) || true); (ssid)++)
30159ec7 291
5549c497
TH
292/* iterate across the active hierarchies */
293#define for_each_active_root(root) \
294 list_for_each_entry((root), &cgroup_roots, root_list)
ddbcc7e8 295
7ae1bad9
TH
296/**
297 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
298 * @cgrp: the cgroup to be checked for liveness
299 *
47cfcd09
TH
300 * On success, returns true; the mutex should be later unlocked. On
301 * failure returns false with no lock held.
7ae1bad9 302 */
b9777cf8 303static bool cgroup_lock_live_group(struct cgroup *cgrp)
7ae1bad9
TH
304{
305 mutex_lock(&cgroup_mutex);
54766d4a 306 if (cgroup_is_dead(cgrp)) {
7ae1bad9
TH
307 mutex_unlock(&cgroup_mutex);
308 return false;
309 }
310 return true;
311}
7ae1bad9 312
81a6a5cd
PM
313/* the list of cgroups eligible for automatic release. Protected by
314 * release_list_lock */
315static LIST_HEAD(release_list);
cdcc136f 316static DEFINE_RAW_SPINLOCK(release_list_lock);
81a6a5cd
PM
317static void cgroup_release_agent(struct work_struct *work);
318static DECLARE_WORK(release_agent_work, cgroup_release_agent);
bd89aabc 319static void check_for_release(struct cgroup *cgrp);
81a6a5cd 320
69d0206c
TH
321/*
322 * A cgroup can be associated with multiple css_sets as different tasks may
323 * belong to different cgroups on different hierarchies. In the other
324 * direction, a css_set is naturally associated with multiple cgroups.
325 * This M:N relationship is represented by the following link structure
326 * which exists for each association and allows traversing the associations
327 * from both sides.
328 */
329struct cgrp_cset_link {
330 /* the cgroup and css_set this link associates */
331 struct cgroup *cgrp;
332 struct css_set *cset;
333
334 /* list of cgrp_cset_links anchored at cgrp->cset_links */
335 struct list_head cset_link;
336
337 /* list of cgrp_cset_links anchored at css_set->cgrp_links */
338 struct list_head cgrp_link;
817929ec
PM
339};
340
341/* The default css_set - used by init and its children prior to any
342 * hierarchies being mounted. It contains a pointer to the root state
343 * for each subsystem. Also used to anchor the list of css_sets. Not
344 * reference-counted, to improve performance when child cgroups
345 * haven't been created.
346 */
347
348static struct css_set init_css_set;
69d0206c 349static struct cgrp_cset_link init_cgrp_cset_link;
817929ec
PM
350static int css_set_count;
351
7717f7ba
PM
352/*
353 * hash table for cgroup groups. This improves the performance to find
354 * an existing css_set. This hash doesn't (currently) take into
355 * account cgroups in empty hierarchies.
356 */
472b1053 357#define CSS_SET_HASH_BITS 7
0ac801fe 358static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
472b1053 359
0ac801fe 360static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
472b1053 361{
0ac801fe 362 unsigned long key = 0UL;
30159ec7
TH
363 struct cgroup_subsys *ss;
364 int i;
472b1053 365
30159ec7 366 for_each_subsys(ss, i)
0ac801fe
LZ
367 key += (unsigned long)css[i];
368 key = (key >> 16) ^ key;
472b1053 369
0ac801fe 370 return key;
472b1053
LZ
371}
372
89c5509b 373static void put_css_set_locked(struct css_set *cset, bool taskexit)
b4f48b63 374{
69d0206c 375 struct cgrp_cset_link *link, *tmp_link;
5abb8855 376
89c5509b
TH
377 lockdep_assert_held(&css_set_rwsem);
378
379 if (!atomic_dec_and_test(&cset->refcount))
146aa1bd 380 return;
81a6a5cd 381
2c6ab6d2 382 /* This css_set is dead. unlink it and release cgroup refcounts */
5abb8855 383 hash_del(&cset->hlist);
2c6ab6d2
PM
384 css_set_count--;
385
69d0206c 386 list_for_each_entry_safe(link, tmp_link, &cset->cgrp_links, cgrp_link) {
2c6ab6d2 387 struct cgroup *cgrp = link->cgrp;
5abb8855 388
69d0206c
TH
389 list_del(&link->cset_link);
390 list_del(&link->cgrp_link);
71b5707e 391
96d365e0 392 /* @cgrp can't go away while we're holding css_set_rwsem */
6f3d828f 393 if (list_empty(&cgrp->cset_links) && notify_on_release(cgrp)) {
81a6a5cd 394 if (taskexit)
bd89aabc
PM
395 set_bit(CGRP_RELEASABLE, &cgrp->flags);
396 check_for_release(cgrp);
81a6a5cd 397 }
2c6ab6d2
PM
398
399 kfree(link);
81a6a5cd 400 }
2c6ab6d2 401
5abb8855 402 kfree_rcu(cset, rcu_head);
b4f48b63
PM
403}
404
89c5509b
TH
405static void put_css_set(struct css_set *cset, bool taskexit)
406{
407 /*
408 * Ensure that the refcount doesn't hit zero while any readers
409 * can see it. Similar to atomic_dec_and_lock(), but for an
410 * rwlock
411 */
412 if (atomic_add_unless(&cset->refcount, -1, 1))
413 return;
414
415 down_write(&css_set_rwsem);
416 put_css_set_locked(cset, taskexit);
417 up_write(&css_set_rwsem);
418}
419
817929ec
PM
420/*
421 * refcounted get/put for css_set objects
422 */
5abb8855 423static inline void get_css_set(struct css_set *cset)
817929ec 424{
5abb8855 425 atomic_inc(&cset->refcount);
817929ec
PM
426}
427
b326f9d0 428/**
7717f7ba 429 * compare_css_sets - helper function for find_existing_css_set().
5abb8855
TH
430 * @cset: candidate css_set being tested
431 * @old_cset: existing css_set for a task
7717f7ba
PM
432 * @new_cgrp: cgroup that's being entered by the task
433 * @template: desired set of css pointers in css_set (pre-calculated)
434 *
6f4b7e63 435 * Returns true if "cset" matches "old_cset" except for the hierarchy
7717f7ba
PM
436 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
437 */
5abb8855
TH
438static bool compare_css_sets(struct css_set *cset,
439 struct css_set *old_cset,
7717f7ba
PM
440 struct cgroup *new_cgrp,
441 struct cgroup_subsys_state *template[])
442{
443 struct list_head *l1, *l2;
444
5abb8855 445 if (memcmp(template, cset->subsys, sizeof(cset->subsys))) {
7717f7ba
PM
446 /* Not all subsystems matched */
447 return false;
448 }
449
450 /*
451 * Compare cgroup pointers in order to distinguish between
452 * different cgroups in heirarchies with no subsystems. We
453 * could get by with just this check alone (and skip the
454 * memcmp above) but on most setups the memcmp check will
455 * avoid the need for this more expensive check on almost all
456 * candidates.
457 */
458
69d0206c
TH
459 l1 = &cset->cgrp_links;
460 l2 = &old_cset->cgrp_links;
7717f7ba 461 while (1) {
69d0206c 462 struct cgrp_cset_link *link1, *link2;
5abb8855 463 struct cgroup *cgrp1, *cgrp2;
7717f7ba
PM
464
465 l1 = l1->next;
466 l2 = l2->next;
467 /* See if we reached the end - both lists are equal length. */
69d0206c
TH
468 if (l1 == &cset->cgrp_links) {
469 BUG_ON(l2 != &old_cset->cgrp_links);
7717f7ba
PM
470 break;
471 } else {
69d0206c 472 BUG_ON(l2 == &old_cset->cgrp_links);
7717f7ba
PM
473 }
474 /* Locate the cgroups associated with these links. */
69d0206c
TH
475 link1 = list_entry(l1, struct cgrp_cset_link, cgrp_link);
476 link2 = list_entry(l2, struct cgrp_cset_link, cgrp_link);
477 cgrp1 = link1->cgrp;
478 cgrp2 = link2->cgrp;
7717f7ba 479 /* Hierarchies should be linked in the same order. */
5abb8855 480 BUG_ON(cgrp1->root != cgrp2->root);
7717f7ba
PM
481
482 /*
483 * If this hierarchy is the hierarchy of the cgroup
484 * that's changing, then we need to check that this
485 * css_set points to the new cgroup; if it's any other
486 * hierarchy, then this css_set should point to the
487 * same cgroup as the old css_set.
488 */
5abb8855
TH
489 if (cgrp1->root == new_cgrp->root) {
490 if (cgrp1 != new_cgrp)
7717f7ba
PM
491 return false;
492 } else {
5abb8855 493 if (cgrp1 != cgrp2)
7717f7ba
PM
494 return false;
495 }
496 }
497 return true;
498}
499
b326f9d0
TH
500/**
501 * find_existing_css_set - init css array and find the matching css_set
502 * @old_cset: the css_set that we're using before the cgroup transition
503 * @cgrp: the cgroup that we're moving into
504 * @template: out param for the new set of csses, should be clear on entry
817929ec 505 */
5abb8855
TH
506static struct css_set *find_existing_css_set(struct css_set *old_cset,
507 struct cgroup *cgrp,
508 struct cgroup_subsys_state *template[])
b4f48b63 509{
bd89aabc 510 struct cgroupfs_root *root = cgrp->root;
30159ec7 511 struct cgroup_subsys *ss;
5abb8855 512 struct css_set *cset;
0ac801fe 513 unsigned long key;
b326f9d0 514 int i;
817929ec 515
aae8aab4
BB
516 /*
517 * Build the set of subsystem state objects that we want to see in the
518 * new css_set. while subsystems can change globally, the entries here
519 * won't change, so no need for locking.
520 */
30159ec7 521 for_each_subsys(ss, i) {
a1a71b45 522 if (root->subsys_mask & (1UL << i)) {
817929ec
PM
523 /* Subsystem is in this hierarchy. So we want
524 * the subsystem state from the new
525 * cgroup */
ca8bdcaf 526 template[i] = cgroup_css(cgrp, ss);
817929ec
PM
527 } else {
528 /* Subsystem is not in this hierarchy, so we
529 * don't want to change the subsystem state */
5abb8855 530 template[i] = old_cset->subsys[i];
817929ec
PM
531 }
532 }
533
0ac801fe 534 key = css_set_hash(template);
5abb8855
TH
535 hash_for_each_possible(css_set_table, cset, hlist, key) {
536 if (!compare_css_sets(cset, old_cset, cgrp, template))
7717f7ba
PM
537 continue;
538
539 /* This css_set matches what we need */
5abb8855 540 return cset;
472b1053 541 }
817929ec
PM
542
543 /* No existing cgroup group matched */
544 return NULL;
545}
546
69d0206c 547static void free_cgrp_cset_links(struct list_head *links_to_free)
36553434 548{
69d0206c 549 struct cgrp_cset_link *link, *tmp_link;
36553434 550
69d0206c
TH
551 list_for_each_entry_safe(link, tmp_link, links_to_free, cset_link) {
552 list_del(&link->cset_link);
36553434
LZ
553 kfree(link);
554 }
555}
556
69d0206c
TH
557/**
558 * allocate_cgrp_cset_links - allocate cgrp_cset_links
559 * @count: the number of links to allocate
560 * @tmp_links: list_head the allocated links are put on
561 *
562 * Allocate @count cgrp_cset_link structures and chain them on @tmp_links
563 * through ->cset_link. Returns 0 on success or -errno.
817929ec 564 */
69d0206c 565static int allocate_cgrp_cset_links(int count, struct list_head *tmp_links)
817929ec 566{
69d0206c 567 struct cgrp_cset_link *link;
817929ec 568 int i;
69d0206c
TH
569
570 INIT_LIST_HEAD(tmp_links);
571
817929ec 572 for (i = 0; i < count; i++) {
f4f4be2b 573 link = kzalloc(sizeof(*link), GFP_KERNEL);
817929ec 574 if (!link) {
69d0206c 575 free_cgrp_cset_links(tmp_links);
817929ec
PM
576 return -ENOMEM;
577 }
69d0206c 578 list_add(&link->cset_link, tmp_links);
817929ec
PM
579 }
580 return 0;
581}
582
c12f65d4
LZ
583/**
584 * link_css_set - a helper function to link a css_set to a cgroup
69d0206c 585 * @tmp_links: cgrp_cset_link objects allocated by allocate_cgrp_cset_links()
5abb8855 586 * @cset: the css_set to be linked
c12f65d4
LZ
587 * @cgrp: the destination cgroup
588 */
69d0206c
TH
589static void link_css_set(struct list_head *tmp_links, struct css_set *cset,
590 struct cgroup *cgrp)
c12f65d4 591{
69d0206c 592 struct cgrp_cset_link *link;
c12f65d4 593
69d0206c
TH
594 BUG_ON(list_empty(tmp_links));
595 link = list_first_entry(tmp_links, struct cgrp_cset_link, cset_link);
596 link->cset = cset;
7717f7ba 597 link->cgrp = cgrp;
69d0206c 598 list_move(&link->cset_link, &cgrp->cset_links);
7717f7ba
PM
599 /*
600 * Always add links to the tail of the list so that the list
601 * is sorted by order of hierarchy creation
602 */
69d0206c 603 list_add_tail(&link->cgrp_link, &cset->cgrp_links);
c12f65d4
LZ
604}
605
b326f9d0
TH
606/**
607 * find_css_set - return a new css_set with one cgroup updated
608 * @old_cset: the baseline css_set
609 * @cgrp: the cgroup to be updated
610 *
611 * Return a new css_set that's equivalent to @old_cset, but with @cgrp
612 * substituted into the appropriate hierarchy.
817929ec 613 */
5abb8855
TH
614static struct css_set *find_css_set(struct css_set *old_cset,
615 struct cgroup *cgrp)
817929ec 616{
b326f9d0 617 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT] = { };
5abb8855 618 struct css_set *cset;
69d0206c
TH
619 struct list_head tmp_links;
620 struct cgrp_cset_link *link;
0ac801fe 621 unsigned long key;
472b1053 622
b326f9d0
TH
623 lockdep_assert_held(&cgroup_mutex);
624
817929ec
PM
625 /* First see if we already have a cgroup group that matches
626 * the desired set */
96d365e0 627 down_read(&css_set_rwsem);
5abb8855
TH
628 cset = find_existing_css_set(old_cset, cgrp, template);
629 if (cset)
630 get_css_set(cset);
96d365e0 631 up_read(&css_set_rwsem);
817929ec 632
5abb8855
TH
633 if (cset)
634 return cset;
817929ec 635
f4f4be2b 636 cset = kzalloc(sizeof(*cset), GFP_KERNEL);
5abb8855 637 if (!cset)
817929ec
PM
638 return NULL;
639
69d0206c 640 /* Allocate all the cgrp_cset_link objects that we'll need */
9871bf95 641 if (allocate_cgrp_cset_links(cgroup_root_count, &tmp_links) < 0) {
5abb8855 642 kfree(cset);
817929ec
PM
643 return NULL;
644 }
645
5abb8855 646 atomic_set(&cset->refcount, 1);
69d0206c 647 INIT_LIST_HEAD(&cset->cgrp_links);
5abb8855 648 INIT_LIST_HEAD(&cset->tasks);
c7561128 649 INIT_LIST_HEAD(&cset->mg_tasks);
1958d2d5 650 INIT_LIST_HEAD(&cset->mg_preload_node);
b3dc094e 651 INIT_LIST_HEAD(&cset->mg_node);
5abb8855 652 INIT_HLIST_NODE(&cset->hlist);
817929ec
PM
653
654 /* Copy the set of subsystem state objects generated in
655 * find_existing_css_set() */
5abb8855 656 memcpy(cset->subsys, template, sizeof(cset->subsys));
817929ec 657
96d365e0 658 down_write(&css_set_rwsem);
817929ec 659 /* Add reference counts and links from the new css_set. */
69d0206c 660 list_for_each_entry(link, &old_cset->cgrp_links, cgrp_link) {
7717f7ba 661 struct cgroup *c = link->cgrp;
69d0206c 662
7717f7ba
PM
663 if (c->root == cgrp->root)
664 c = cgrp;
69d0206c 665 link_css_set(&tmp_links, cset, c);
7717f7ba 666 }
817929ec 667
69d0206c 668 BUG_ON(!list_empty(&tmp_links));
817929ec 669
817929ec 670 css_set_count++;
472b1053
LZ
671
672 /* Add this cgroup group to the hash table */
5abb8855
TH
673 key = css_set_hash(cset->subsys);
674 hash_add(css_set_table, &cset->hlist, key);
472b1053 675
96d365e0 676 up_write(&css_set_rwsem);
817929ec 677
5abb8855 678 return cset;
b4f48b63
PM
679}
680
2bd59d48
TH
681static struct cgroupfs_root *cgroup_root_from_kf(struct kernfs_root *kf_root)
682{
683 struct cgroup *top_cgrp = kf_root->kn->priv;
684
685 return top_cgrp->root;
686}
687
f2e85d57
TH
688static int cgroup_init_root_id(struct cgroupfs_root *root, int start, int end)
689{
690 int id;
691
692 lockdep_assert_held(&cgroup_mutex);
693
694 id = idr_alloc_cyclic(&cgroup_hierarchy_idr, root, start, end,
695 GFP_KERNEL);
696 if (id < 0)
697 return id;
698
699 root->hierarchy_id = id;
700 return 0;
701}
702
703static void cgroup_exit_root_id(struct cgroupfs_root *root)
704{
705 lockdep_assert_held(&cgroup_mutex);
706
707 if (root->hierarchy_id) {
708 idr_remove(&cgroup_hierarchy_idr, root->hierarchy_id);
709 root->hierarchy_id = 0;
710 }
711}
712
713static void cgroup_free_root(struct cgroupfs_root *root)
714{
715 if (root) {
716 /* hierarhcy ID shoulid already have been released */
717 WARN_ON_ONCE(root->hierarchy_id);
718
719 idr_destroy(&root->cgroup_idr);
720 kfree(root);
721 }
722}
723
776f02fa 724static void cgroup_destroy_root(struct cgroupfs_root *root)
59f5296b 725{
f2e85d57
TH
726 struct cgroup *cgrp = &root->top_cgroup;
727 struct cgrp_cset_link *link, *tmp_link;
f2e85d57 728
2bd59d48 729 mutex_lock(&cgroup_tree_mutex);
2bd59d48 730 mutex_lock(&cgroup_mutex);
f2e85d57 731
776f02fa 732 BUG_ON(atomic_read(&root->nr_cgrps));
f2e85d57
TH
733 BUG_ON(!list_empty(&cgrp->children));
734
f2e85d57 735 /* Rebind all subsystems back to the default hierarchy */
35585573 736 WARN_ON(rebind_subsystems(root, 0, root->subsys_mask));
f2e85d57
TH
737
738 /*
739 * Release all the links from cset_links to this hierarchy's
740 * root cgroup
741 */
96d365e0 742 down_write(&css_set_rwsem);
f2e85d57
TH
743
744 list_for_each_entry_safe(link, tmp_link, &cgrp->cset_links, cset_link) {
745 list_del(&link->cset_link);
746 list_del(&link->cgrp_link);
747 kfree(link);
748 }
96d365e0 749 up_write(&css_set_rwsem);
f2e85d57
TH
750
751 if (!list_empty(&root->root_list)) {
752 list_del(&root->root_list);
753 cgroup_root_count--;
754 }
755
756 cgroup_exit_root_id(root);
757
758 mutex_unlock(&cgroup_mutex);
759 mutex_unlock(&cgroup_tree_mutex);
f2e85d57 760
2bd59d48 761 kernfs_destroy_root(root->kf_root);
f2e85d57
TH
762 cgroup_free_root(root);
763}
764
ceb6a081
TH
765/* look up cgroup associated with given css_set on the specified hierarchy */
766static struct cgroup *cset_cgroup_from_root(struct css_set *cset,
7717f7ba
PM
767 struct cgroupfs_root *root)
768{
7717f7ba
PM
769 struct cgroup *res = NULL;
770
96d365e0
TH
771 lockdep_assert_held(&cgroup_mutex);
772 lockdep_assert_held(&css_set_rwsem);
773
5abb8855 774 if (cset == &init_css_set) {
7717f7ba
PM
775 res = &root->top_cgroup;
776 } else {
69d0206c
TH
777 struct cgrp_cset_link *link;
778
779 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
7717f7ba 780 struct cgroup *c = link->cgrp;
69d0206c 781
7717f7ba
PM
782 if (c->root == root) {
783 res = c;
784 break;
785 }
786 }
787 }
96d365e0 788
7717f7ba
PM
789 BUG_ON(!res);
790 return res;
791}
792
ceb6a081
TH
793/*
794 * Return the cgroup for "task" from the given hierarchy. Must be
795 * called with cgroup_mutex and css_set_rwsem held.
796 */
797static struct cgroup *task_cgroup_from_root(struct task_struct *task,
798 struct cgroupfs_root *root)
799{
800 /*
801 * No need to lock the task - since we hold cgroup_mutex the
802 * task can't change groups, so the only thing that can happen
803 * is that it exits and its css is set back to init_css_set.
804 */
805 return cset_cgroup_from_root(task_css_set(task), root);
806}
807
ddbcc7e8 808/*
ddbcc7e8
PM
809 * A task must hold cgroup_mutex to modify cgroups.
810 *
811 * Any task can increment and decrement the count field without lock.
812 * So in general, code holding cgroup_mutex can't rely on the count
813 * field not changing. However, if the count goes to zero, then only
956db3ca 814 * cgroup_attach_task() can increment it again. Because a count of zero
ddbcc7e8
PM
815 * means that no tasks are currently attached, therefore there is no
816 * way a task attached to that cgroup can fork (the other way to
817 * increment the count). So code holding cgroup_mutex can safely
818 * assume that if the count is zero, it will stay zero. Similarly, if
819 * a task holds cgroup_mutex on a cgroup with zero count, it
820 * knows that the cgroup won't be removed, as cgroup_rmdir()
821 * needs that mutex.
822 *
ddbcc7e8
PM
823 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
824 * (usually) take cgroup_mutex. These are the two most performance
825 * critical pieces of code here. The exception occurs on cgroup_exit(),
826 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
827 * is taken, and if the cgroup count is zero, a usermode call made
a043e3b2
LZ
828 * to the release agent with the name of the cgroup (path relative to
829 * the root of cgroup file system) as the argument.
ddbcc7e8
PM
830 *
831 * A cgroup can only be deleted if both its 'count' of using tasks
832 * is zero, and its list of 'children' cgroups is empty. Since all
833 * tasks in the system use _some_ cgroup, and since there is always at
834 * least one task in the system (init, pid == 1), therefore, top_cgroup
835 * always has either children cgroups and/or using tasks. So we don't
836 * need a special hack to ensure that top_cgroup cannot be deleted.
837 *
ddbcc7e8 838 * P.S. One more locking exception. RCU is used to guard the
956db3ca 839 * update of a tasks cgroup pointer by cgroup_attach_task()
ddbcc7e8
PM
840 */
841
628f7cd4 842static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask);
2bd59d48 843static struct kernfs_syscall_ops cgroup_kf_syscall_ops;
828c0950 844static const struct file_operations proc_cgroupstats_operations;
a424316c 845
8d7e6fb0
TH
846static char *cgroup_file_name(struct cgroup *cgrp, const struct cftype *cft,
847 char *buf)
848{
849 if (cft->ss && !(cft->flags & CFTYPE_NO_PREFIX) &&
850 !(cgrp->root->flags & CGRP_ROOT_NOPREFIX))
851 snprintf(buf, CGROUP_FILE_NAME_MAX, "%s.%s",
852 cft->ss->name, cft->name);
853 else
854 strncpy(buf, cft->name, CGROUP_FILE_NAME_MAX);
855 return buf;
856}
857
f2e85d57
TH
858/**
859 * cgroup_file_mode - deduce file mode of a control file
860 * @cft: the control file in question
861 *
862 * returns cft->mode if ->mode is not 0
863 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
864 * returns S_IRUGO if it has only a read handler
865 * returns S_IWUSR if it has only a write hander
866 */
867static umode_t cgroup_file_mode(const struct cftype *cft)
868{
869 umode_t mode = 0;
870
871 if (cft->mode)
872 return cft->mode;
873
874 if (cft->read_u64 || cft->read_s64 || cft->seq_show)
875 mode |= S_IRUGO;
876
877 if (cft->write_u64 || cft->write_s64 || cft->write_string ||
878 cft->trigger)
879 mode |= S_IWUSR;
880
881 return mode;
882}
883
be445626
LZ
884static void cgroup_free_fn(struct work_struct *work)
885{
ea15f8cc 886 struct cgroup *cgrp = container_of(work, struct cgroup, destroy_work);
be445626 887
3c9c825b 888 atomic_dec(&cgrp->root->nr_cgrps);
b1a21367 889 cgroup_pidlist_destroy_all(cgrp);
be445626 890
776f02fa
TH
891 if (cgrp->parent) {
892 /*
893 * We get a ref to the parent, and put the ref when this
894 * cgroup is being freed, so it's guaranteed that the
895 * parent won't be destroyed before its children.
896 */
897 cgroup_put(cgrp->parent);
898 kernfs_put(cgrp->kn);
899 kfree(cgrp);
900 } else {
901 /*
902 * This is top cgroup's refcnt reaching zero, which
903 * indicates that the root should be released.
904 */
905 cgroup_destroy_root(cgrp->root);
906 }
be445626
LZ
907}
908
909static void cgroup_free_rcu(struct rcu_head *head)
910{
911 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
912
ea15f8cc 913 INIT_WORK(&cgrp->destroy_work, cgroup_free_fn);
e5fca243 914 queue_work(cgroup_destroy_wq, &cgrp->destroy_work);
be445626
LZ
915}
916
59f5296b
TH
917static void cgroup_get(struct cgroup *cgrp)
918{
2bd59d48
TH
919 WARN_ON_ONCE(cgroup_is_dead(cgrp));
920 WARN_ON_ONCE(atomic_read(&cgrp->refcnt) <= 0);
921 atomic_inc(&cgrp->refcnt);
ddbcc7e8
PM
922}
923
59f5296b
TH
924static void cgroup_put(struct cgroup *cgrp)
925{
2bd59d48
TH
926 if (!atomic_dec_and_test(&cgrp->refcnt))
927 return;
776f02fa 928 if (WARN_ON_ONCE(cgrp->parent && !cgroup_is_dead(cgrp)))
2bd59d48 929 return;
59f5296b 930
2bd59d48
TH
931 /*
932 * XXX: cgrp->id is only used to look up css's. As cgroup and
933 * css's lifetimes will be decoupled, it should be made
934 * per-subsystem and moved to css->id so that lookups are
935 * successful until the target css is released.
936 */
937 mutex_lock(&cgroup_mutex);
938 idr_remove(&cgrp->root->cgroup_idr, cgrp->id);
939 mutex_unlock(&cgroup_mutex);
940 cgrp->id = -1;
ddbcc7e8 941
2bd59d48 942 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
ddbcc7e8
PM
943}
944
2739d3cc 945static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
05ef1d7c 946{
2bd59d48 947 char name[CGROUP_FILE_NAME_MAX];
05ef1d7c 948
ace2bee8 949 lockdep_assert_held(&cgroup_tree_mutex);
2bd59d48 950 kernfs_remove_by_name(cgrp->kn, cgroup_file_name(cgrp, cft, name));
05ef1d7c
TH
951}
952
13af07df 953/**
628f7cd4 954 * cgroup_clear_dir - remove subsys files in a cgroup directory
8f89140a 955 * @cgrp: target cgroup
13af07df
AR
956 * @subsys_mask: mask of the subsystem ids whose files should be removed
957 */
628f7cd4 958static void cgroup_clear_dir(struct cgroup *cgrp, unsigned long subsys_mask)
05ef1d7c 959{
13af07df 960 struct cgroup_subsys *ss;
b420ba7d 961 int i;
05ef1d7c 962
b420ba7d 963 for_each_subsys(ss, i) {
0adb0704 964 struct cftype *cfts;
b420ba7d
TH
965
966 if (!test_bit(i, &subsys_mask))
13af07df 967 continue;
0adb0704
TH
968 list_for_each_entry(cfts, &ss->cfts, node)
969 cgroup_addrm_files(cgrp, cfts, false);
13af07df 970 }
ddbcc7e8
PM
971}
972
ddbcc7e8 973static int rebind_subsystems(struct cgroupfs_root *root,
a8a648c4 974 unsigned long added_mask, unsigned removed_mask)
ddbcc7e8 975{
bd89aabc 976 struct cgroup *cgrp = &root->top_cgroup;
30159ec7 977 struct cgroup_subsys *ss;
3126121f 978 int i, ret;
ddbcc7e8 979
ace2bee8
TH
980 lockdep_assert_held(&cgroup_tree_mutex);
981 lockdep_assert_held(&cgroup_mutex);
aae8aab4 982
ddbcc7e8 983 /* Check that any added subsystems are currently free */
3ed80a62
TH
984 for_each_subsys(ss, i)
985 if ((added_mask & (1 << i)) && ss->root != &cgroup_dummy_root)
986 return -EBUSY;
ddbcc7e8 987
3126121f
TH
988 ret = cgroup_populate_dir(cgrp, added_mask);
989 if (ret)
3ed80a62 990 return ret;
3126121f
TH
991
992 /*
993 * Nothing can fail from this point on. Remove files for the
994 * removed subsystems and rebind each subsystem.
995 */
4ac06017 996 mutex_unlock(&cgroup_mutex);
3126121f 997 cgroup_clear_dir(cgrp, removed_mask);
4ac06017 998 mutex_lock(&cgroup_mutex);
ddbcc7e8 999
30159ec7 1000 for_each_subsys(ss, i) {
ddbcc7e8 1001 unsigned long bit = 1UL << i;
30159ec7 1002
a1a71b45 1003 if (bit & added_mask) {
ddbcc7e8 1004 /* We're binding this subsystem to this hierarchy */
ca8bdcaf
TH
1005 BUG_ON(cgroup_css(cgrp, ss));
1006 BUG_ON(!cgroup_css(cgroup_dummy_top, ss));
1007 BUG_ON(cgroup_css(cgroup_dummy_top, ss)->cgroup != cgroup_dummy_top);
a8a648c4 1008
73e80ed8 1009 rcu_assign_pointer(cgrp->subsys[i],
ca8bdcaf
TH
1010 cgroup_css(cgroup_dummy_top, ss));
1011 cgroup_css(cgrp, ss)->cgroup = cgrp;
a8a648c4 1012
b2aa30f7 1013 ss->root = root;
ddbcc7e8 1014 if (ss->bind)
ca8bdcaf 1015 ss->bind(cgroup_css(cgrp, ss));
a8a648c4 1016
cf5d5941 1017 /* refcount was already taken, and we're keeping it */
a8a648c4 1018 root->subsys_mask |= bit;
a1a71b45 1019 } else if (bit & removed_mask) {
ddbcc7e8 1020 /* We're removing this subsystem */
ca8bdcaf
TH
1021 BUG_ON(cgroup_css(cgrp, ss) != cgroup_css(cgroup_dummy_top, ss));
1022 BUG_ON(cgroup_css(cgrp, ss)->cgroup != cgrp);
a8a648c4 1023
ddbcc7e8 1024 if (ss->bind)
ca8bdcaf 1025 ss->bind(cgroup_css(cgroup_dummy_top, ss));
73e80ed8 1026
ca8bdcaf 1027 cgroup_css(cgroup_dummy_top, ss)->cgroup = cgroup_dummy_top;
73e80ed8
TH
1028 RCU_INIT_POINTER(cgrp->subsys[i], NULL);
1029
9871bf95 1030 cgroup_subsys[i]->root = &cgroup_dummy_root;
a8a648c4 1031 root->subsys_mask &= ~bit;
ddbcc7e8
PM
1032 }
1033 }
ddbcc7e8 1034
2bd59d48 1035 kernfs_activate(cgrp->kn);
ddbcc7e8
PM
1036 return 0;
1037}
1038
2bd59d48
TH
1039static int cgroup_show_options(struct seq_file *seq,
1040 struct kernfs_root *kf_root)
ddbcc7e8 1041{
2bd59d48 1042 struct cgroupfs_root *root = cgroup_root_from_kf(kf_root);
ddbcc7e8 1043 struct cgroup_subsys *ss;
b85d2040 1044 int ssid;
ddbcc7e8 1045
b85d2040
TH
1046 for_each_subsys(ss, ssid)
1047 if (root->subsys_mask & (1 << ssid))
1048 seq_printf(seq, ",%s", ss->name);
873fe09e
TH
1049 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1050 seq_puts(seq, ",sane_behavior");
93438629 1051 if (root->flags & CGRP_ROOT_NOPREFIX)
ddbcc7e8 1052 seq_puts(seq, ",noprefix");
93438629 1053 if (root->flags & CGRP_ROOT_XATTR)
03b1cde6 1054 seq_puts(seq, ",xattr");
69e943b7
TH
1055
1056 spin_lock(&release_agent_path_lock);
81a6a5cd
PM
1057 if (strlen(root->release_agent_path))
1058 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
69e943b7
TH
1059 spin_unlock(&release_agent_path_lock);
1060
2260e7fc 1061 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
97978e6d 1062 seq_puts(seq, ",clone_children");
c6d57f33
PM
1063 if (strlen(root->name))
1064 seq_printf(seq, ",name=%s", root->name);
ddbcc7e8
PM
1065 return 0;
1066}
1067
1068struct cgroup_sb_opts {
a1a71b45 1069 unsigned long subsys_mask;
ddbcc7e8 1070 unsigned long flags;
81a6a5cd 1071 char *release_agent;
2260e7fc 1072 bool cpuset_clone_children;
c6d57f33 1073 char *name;
2c6ab6d2
PM
1074 /* User explicitly requested empty subsystem */
1075 bool none;
ddbcc7e8
PM
1076};
1077
aae8aab4 1078/*
9871bf95
TH
1079 * Convert a hierarchy specifier into a bitmask of subsystems and
1080 * flags. Call with cgroup_mutex held to protect the cgroup_subsys[]
1081 * array. This function takes refcounts on subsystems to be used, unless it
1082 * returns error, in which case no refcounts are taken.
aae8aab4 1083 */
cf5d5941 1084static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
ddbcc7e8 1085{
32a8cf23
DL
1086 char *token, *o = data;
1087 bool all_ss = false, one_ss = false;
f9ab5b5b 1088 unsigned long mask = (unsigned long)-1;
30159ec7
TH
1089 struct cgroup_subsys *ss;
1090 int i;
f9ab5b5b 1091
aae8aab4
BB
1092 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1093
f9ab5b5b 1094#ifdef CONFIG_CPUSETS
073219e9 1095 mask = ~(1UL << cpuset_cgrp_id);
f9ab5b5b 1096#endif
ddbcc7e8 1097
c6d57f33 1098 memset(opts, 0, sizeof(*opts));
ddbcc7e8
PM
1099
1100 while ((token = strsep(&o, ",")) != NULL) {
1101 if (!*token)
1102 return -EINVAL;
32a8cf23 1103 if (!strcmp(token, "none")) {
2c6ab6d2
PM
1104 /* Explicitly have no subsystems */
1105 opts->none = true;
32a8cf23
DL
1106 continue;
1107 }
1108 if (!strcmp(token, "all")) {
1109 /* Mutually exclusive option 'all' + subsystem name */
1110 if (one_ss)
1111 return -EINVAL;
1112 all_ss = true;
1113 continue;
1114 }
873fe09e
TH
1115 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1116 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1117 continue;
1118 }
32a8cf23 1119 if (!strcmp(token, "noprefix")) {
93438629 1120 opts->flags |= CGRP_ROOT_NOPREFIX;
32a8cf23
DL
1121 continue;
1122 }
1123 if (!strcmp(token, "clone_children")) {
2260e7fc 1124 opts->cpuset_clone_children = true;
32a8cf23
DL
1125 continue;
1126 }
03b1cde6 1127 if (!strcmp(token, "xattr")) {
93438629 1128 opts->flags |= CGRP_ROOT_XATTR;
03b1cde6
AR
1129 continue;
1130 }
32a8cf23 1131 if (!strncmp(token, "release_agent=", 14)) {
81a6a5cd
PM
1132 /* Specifying two release agents is forbidden */
1133 if (opts->release_agent)
1134 return -EINVAL;
c6d57f33 1135 opts->release_agent =
e400c285 1136 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
81a6a5cd
PM
1137 if (!opts->release_agent)
1138 return -ENOMEM;
32a8cf23
DL
1139 continue;
1140 }
1141 if (!strncmp(token, "name=", 5)) {
c6d57f33
PM
1142 const char *name = token + 5;
1143 /* Can't specify an empty name */
1144 if (!strlen(name))
1145 return -EINVAL;
1146 /* Must match [\w.-]+ */
1147 for (i = 0; i < strlen(name); i++) {
1148 char c = name[i];
1149 if (isalnum(c))
1150 continue;
1151 if ((c == '.') || (c == '-') || (c == '_'))
1152 continue;
1153 return -EINVAL;
1154 }
1155 /* Specifying two names is forbidden */
1156 if (opts->name)
1157 return -EINVAL;
1158 opts->name = kstrndup(name,
e400c285 1159 MAX_CGROUP_ROOT_NAMELEN - 1,
c6d57f33
PM
1160 GFP_KERNEL);
1161 if (!opts->name)
1162 return -ENOMEM;
32a8cf23
DL
1163
1164 continue;
1165 }
1166
30159ec7 1167 for_each_subsys(ss, i) {
32a8cf23
DL
1168 if (strcmp(token, ss->name))
1169 continue;
1170 if (ss->disabled)
1171 continue;
1172
1173 /* Mutually exclusive option 'all' + subsystem name */
1174 if (all_ss)
1175 return -EINVAL;
a1a71b45 1176 set_bit(i, &opts->subsys_mask);
32a8cf23
DL
1177 one_ss = true;
1178
1179 break;
1180 }
1181 if (i == CGROUP_SUBSYS_COUNT)
1182 return -ENOENT;
1183 }
1184
1185 /*
1186 * If the 'all' option was specified select all the subsystems,
0d19ea86
LZ
1187 * otherwise if 'none', 'name=' and a subsystem name options
1188 * were not specified, let's default to 'all'
32a8cf23 1189 */
30159ec7
TH
1190 if (all_ss || (!one_ss && !opts->none && !opts->name))
1191 for_each_subsys(ss, i)
1192 if (!ss->disabled)
1193 set_bit(i, &opts->subsys_mask);
ddbcc7e8 1194
2c6ab6d2
PM
1195 /* Consistency checks */
1196
873fe09e
TH
1197 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1198 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1199
d3ba07c3
TH
1200 if ((opts->flags & (CGRP_ROOT_NOPREFIX | CGRP_ROOT_XATTR)) ||
1201 opts->cpuset_clone_children || opts->release_agent ||
1202 opts->name) {
1203 pr_err("cgroup: sane_behavior: noprefix, xattr, clone_children, release_agent and name are not allowed\n");
873fe09e
TH
1204 return -EINVAL;
1205 }
873fe09e
TH
1206 }
1207
f9ab5b5b
LZ
1208 /*
1209 * Option noprefix was introduced just for backward compatibility
1210 * with the old cpuset, so we allow noprefix only if mounting just
1211 * the cpuset subsystem.
1212 */
93438629 1213 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
f9ab5b5b
LZ
1214 return -EINVAL;
1215
2c6ab6d2
PM
1216
1217 /* Can't specify "none" and some subsystems */
a1a71b45 1218 if (opts->subsys_mask && opts->none)
2c6ab6d2
PM
1219 return -EINVAL;
1220
1221 /*
1222 * We either have to specify by name or by subsystems. (So all
1223 * empty hierarchies must have a name).
1224 */
a1a71b45 1225 if (!opts->subsys_mask && !opts->name)
ddbcc7e8
PM
1226 return -EINVAL;
1227
1228 return 0;
1229}
1230
2bd59d48 1231static int cgroup_remount(struct kernfs_root *kf_root, int *flags, char *data)
ddbcc7e8
PM
1232{
1233 int ret = 0;
2bd59d48 1234 struct cgroupfs_root *root = cgroup_root_from_kf(kf_root);
ddbcc7e8 1235 struct cgroup_sb_opts opts;
a1a71b45 1236 unsigned long added_mask, removed_mask;
ddbcc7e8 1237
873fe09e
TH
1238 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1239 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1240 return -EINVAL;
1241 }
1242
ace2bee8 1243 mutex_lock(&cgroup_tree_mutex);
ddbcc7e8
PM
1244 mutex_lock(&cgroup_mutex);
1245
1246 /* See what subsystems are wanted */
1247 ret = parse_cgroupfs_options(data, &opts);
1248 if (ret)
1249 goto out_unlock;
1250
a8a648c4 1251 if (opts.subsys_mask != root->subsys_mask || opts.release_agent)
8b5a5a9d
TH
1252 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1253 task_tgid_nr(current), current->comm);
1254
a1a71b45
AR
1255 added_mask = opts.subsys_mask & ~root->subsys_mask;
1256 removed_mask = root->subsys_mask & ~opts.subsys_mask;
13af07df 1257
cf5d5941 1258 /* Don't allow flags or name to change at remount */
0ce6cba3 1259 if (((opts.flags ^ root->flags) & CGRP_ROOT_OPTION_MASK) ||
cf5d5941 1260 (opts.name && strcmp(opts.name, root->name))) {
0ce6cba3
TH
1261 pr_err("cgroup: option or name mismatch, new: 0x%lx \"%s\", old: 0x%lx \"%s\"\n",
1262 opts.flags & CGRP_ROOT_OPTION_MASK, opts.name ?: "",
1263 root->flags & CGRP_ROOT_OPTION_MASK, root->name);
c6d57f33
PM
1264 ret = -EINVAL;
1265 goto out_unlock;
1266 }
1267
f172e67c 1268 /* remounting is not allowed for populated hierarchies */
3c9c825b 1269 if (!list_empty(&root->top_cgroup.children)) {
f172e67c 1270 ret = -EBUSY;
0670e08b 1271 goto out_unlock;
cf5d5941 1272 }
ddbcc7e8 1273
a8a648c4 1274 ret = rebind_subsystems(root, added_mask, removed_mask);
3126121f 1275 if (ret)
0670e08b 1276 goto out_unlock;
ddbcc7e8 1277
69e943b7
TH
1278 if (opts.release_agent) {
1279 spin_lock(&release_agent_path_lock);
81a6a5cd 1280 strcpy(root->release_agent_path, opts.release_agent);
69e943b7
TH
1281 spin_unlock(&release_agent_path_lock);
1282 }
ddbcc7e8 1283 out_unlock:
66bdc9cf 1284 kfree(opts.release_agent);
c6d57f33 1285 kfree(opts.name);
ddbcc7e8 1286 mutex_unlock(&cgroup_mutex);
ace2bee8 1287 mutex_unlock(&cgroup_tree_mutex);
ddbcc7e8
PM
1288 return ret;
1289}
1290
afeb0f9f
TH
1291/*
1292 * To reduce the fork() overhead for systems that are not actually using
1293 * their cgroups capability, we don't maintain the lists running through
1294 * each css_set to its tasks until we see the list actually used - in other
1295 * words after the first mount.
1296 */
1297static bool use_task_css_set_links __read_mostly;
1298
1299static void cgroup_enable_task_cg_lists(void)
1300{
1301 struct task_struct *p, *g;
1302
96d365e0 1303 down_write(&css_set_rwsem);
afeb0f9f
TH
1304
1305 if (use_task_css_set_links)
1306 goto out_unlock;
1307
1308 use_task_css_set_links = true;
1309
1310 /*
1311 * We need tasklist_lock because RCU is not safe against
1312 * while_each_thread(). Besides, a forking task that has passed
1313 * cgroup_post_fork() without seeing use_task_css_set_links = 1
1314 * is not guaranteed to have its child immediately visible in the
1315 * tasklist if we walk through it with RCU.
1316 */
1317 read_lock(&tasklist_lock);
1318 do_each_thread(g, p) {
afeb0f9f
TH
1319 WARN_ON_ONCE(!list_empty(&p->cg_list) ||
1320 task_css_set(p) != &init_css_set);
1321
1322 /*
1323 * We should check if the process is exiting, otherwise
1324 * it will race with cgroup_exit() in that the list
1325 * entry won't be deleted though the process has exited.
f153ad11
TH
1326 * Do it while holding siglock so that we don't end up
1327 * racing against cgroup_exit().
afeb0f9f 1328 */
f153ad11 1329 spin_lock_irq(&p->sighand->siglock);
eaf797ab
TH
1330 if (!(p->flags & PF_EXITING)) {
1331 struct css_set *cset = task_css_set(p);
1332
1333 list_add(&p->cg_list, &cset->tasks);
1334 get_css_set(cset);
1335 }
f153ad11 1336 spin_unlock_irq(&p->sighand->siglock);
afeb0f9f
TH
1337 } while_each_thread(g, p);
1338 read_unlock(&tasklist_lock);
1339out_unlock:
96d365e0 1340 up_write(&css_set_rwsem);
afeb0f9f
TH
1341}
1342
cc31edce
PM
1343static void init_cgroup_housekeeping(struct cgroup *cgrp)
1344{
2bd59d48 1345 atomic_set(&cgrp->refcnt, 1);
cc31edce
PM
1346 INIT_LIST_HEAD(&cgrp->sibling);
1347 INIT_LIST_HEAD(&cgrp->children);
69d0206c 1348 INIT_LIST_HEAD(&cgrp->cset_links);
cc31edce 1349 INIT_LIST_HEAD(&cgrp->release_list);
72a8cb30
BB
1350 INIT_LIST_HEAD(&cgrp->pidlists);
1351 mutex_init(&cgrp->pidlist_mutex);
67f4c36f 1352 cgrp->dummy_css.cgroup = cgrp;
cc31edce 1353}
c6d57f33 1354
ddbcc7e8
PM
1355static void init_cgroup_root(struct cgroupfs_root *root)
1356{
bd89aabc 1357 struct cgroup *cgrp = &root->top_cgroup;
b0ca5a84 1358
ddbcc7e8 1359 INIT_LIST_HEAD(&root->root_list);
3c9c825b 1360 atomic_set(&root->nr_cgrps, 1);
bd89aabc 1361 cgrp->root = root;
cc31edce 1362 init_cgroup_housekeeping(cgrp);
4e96ee8e 1363 idr_init(&root->cgroup_idr);
ddbcc7e8
PM
1364}
1365
c6d57f33
PM
1366static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1367{
1368 struct cgroupfs_root *root;
1369
a1a71b45 1370 if (!opts->subsys_mask && !opts->none)
2bd59d48 1371 return ERR_PTR(-EINVAL);
c6d57f33
PM
1372
1373 root = kzalloc(sizeof(*root), GFP_KERNEL);
1374 if (!root)
1375 return ERR_PTR(-ENOMEM);
1376
1377 init_cgroup_root(root);
2c6ab6d2 1378
c6d57f33
PM
1379 root->flags = opts->flags;
1380 if (opts->release_agent)
1381 strcpy(root->release_agent_path, opts->release_agent);
1382 if (opts->name)
1383 strcpy(root->name, opts->name);
2260e7fc
TH
1384 if (opts->cpuset_clone_children)
1385 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
c6d57f33
PM
1386 return root;
1387}
1388
35585573 1389static int cgroup_setup_root(struct cgroupfs_root *root, unsigned long ss_mask)
d427dfeb
TH
1390{
1391 LIST_HEAD(tmp_links);
d427dfeb 1392 struct cgroup *root_cgrp = &root->top_cgroup;
d427dfeb 1393 struct css_set *cset;
d427dfeb
TH
1394 int i, ret;
1395
1396 lockdep_assert_held(&cgroup_tree_mutex);
1397 lockdep_assert_held(&cgroup_mutex);
d427dfeb
TH
1398
1399 ret = idr_alloc(&root->cgroup_idr, root_cgrp, 0, 1, GFP_KERNEL);
1400 if (ret < 0)
2bd59d48 1401 goto out;
d427dfeb
TH
1402 root_cgrp->id = ret;
1403
d427dfeb 1404 /*
96d365e0 1405 * We're accessing css_set_count without locking css_set_rwsem here,
d427dfeb
TH
1406 * but that's OK - it can only be increased by someone holding
1407 * cgroup_lock, and that's us. The worst that can happen is that we
1408 * have some link structures left over
1409 */
1410 ret = allocate_cgrp_cset_links(css_set_count, &tmp_links);
1411 if (ret)
2bd59d48 1412 goto out;
d427dfeb
TH
1413
1414 /* ID 0 is reserved for dummy root, 1 for unified hierarchy */
1415 ret = cgroup_init_root_id(root, 2, 0);
1416 if (ret)
2bd59d48 1417 goto out;
d427dfeb 1418
2bd59d48
TH
1419 root->kf_root = kernfs_create_root(&cgroup_kf_syscall_ops,
1420 KERNFS_ROOT_CREATE_DEACTIVATED,
1421 root_cgrp);
1422 if (IS_ERR(root->kf_root)) {
1423 ret = PTR_ERR(root->kf_root);
1424 goto exit_root_id;
1425 }
1426 root_cgrp->kn = root->kf_root->kn;
d427dfeb
TH
1427
1428 ret = cgroup_addrm_files(root_cgrp, cgroup_base_files, true);
1429 if (ret)
2bd59d48 1430 goto destroy_root;
d427dfeb 1431
35585573 1432 ret = rebind_subsystems(root, ss_mask, 0);
d427dfeb 1433 if (ret)
2bd59d48 1434 goto destroy_root;
d427dfeb
TH
1435
1436 /*
1437 * There must be no failure case after here, since rebinding takes
1438 * care of subsystems' refcounts, which are explicitly dropped in
1439 * the failure exit path.
1440 */
1441 list_add(&root->root_list, &cgroup_roots);
1442 cgroup_root_count++;
1443
1444 /*
1445 * Link the top cgroup in this hierarchy into all the css_set
1446 * objects.
1447 */
96d365e0 1448 down_write(&css_set_rwsem);
d427dfeb
TH
1449 hash_for_each(css_set_table, i, cset, hlist)
1450 link_css_set(&tmp_links, cset, root_cgrp);
96d365e0 1451 up_write(&css_set_rwsem);
d427dfeb
TH
1452
1453 BUG_ON(!list_empty(&root_cgrp->children));
3c9c825b 1454 BUG_ON(atomic_read(&root->nr_cgrps) != 1);
d427dfeb 1455
2bd59d48 1456 kernfs_activate(root_cgrp->kn);
d427dfeb 1457 ret = 0;
2bd59d48 1458 goto out;
d427dfeb 1459
2bd59d48
TH
1460destroy_root:
1461 kernfs_destroy_root(root->kf_root);
1462 root->kf_root = NULL;
1463exit_root_id:
d427dfeb 1464 cgroup_exit_root_id(root);
2bd59d48 1465out:
d427dfeb
TH
1466 free_cgrp_cset_links(&tmp_links);
1467 return ret;
1468}
1469
f7e83571 1470static struct dentry *cgroup_mount(struct file_system_type *fs_type,
ddbcc7e8 1471 int flags, const char *unused_dev_name,
f7e83571 1472 void *data)
ddbcc7e8 1473{
2bd59d48 1474 struct cgroupfs_root *root;
ddbcc7e8 1475 struct cgroup_sb_opts opts;
2bd59d48 1476 struct dentry *dentry;
8e30e2b8 1477 int ret;
56fde9e0
TH
1478
1479 /*
1480 * The first time anyone tries to mount a cgroup, enable the list
1481 * linking each css_set to its tasks and fix up all existing tasks.
1482 */
1483 if (!use_task_css_set_links)
1484 cgroup_enable_task_cg_lists();
776f02fa 1485retry:
8e30e2b8 1486 mutex_lock(&cgroup_tree_mutex);
aae8aab4 1487 mutex_lock(&cgroup_mutex);
8e30e2b8
TH
1488
1489 /* First find the desired set of subsystems */
ddbcc7e8 1490 ret = parse_cgroupfs_options(data, &opts);
c6d57f33 1491 if (ret)
8e30e2b8 1492 goto out_unlock;
ddbcc7e8 1493
2bd59d48
TH
1494 /* look for a matching existing root */
1495 for_each_active_root(root) {
1496 bool name_match = false;
ddbcc7e8 1497
2bd59d48
TH
1498 /*
1499 * If we asked for a name then it must match. Also, if
1500 * name matches but sybsys_mask doesn't, we should fail.
1501 * Remember whether name matched.
1502 */
1503 if (opts.name) {
1504 if (strcmp(opts.name, root->name))
1505 continue;
1506 name_match = true;
1507 }
ddbcc7e8 1508
c6d57f33 1509 /*
2bd59d48
TH
1510 * If we asked for subsystems (or explicitly for no
1511 * subsystems) then they must match.
c6d57f33 1512 */
2bd59d48
TH
1513 if ((opts.subsys_mask || opts.none) &&
1514 (opts.subsys_mask != root->subsys_mask)) {
1515 if (!name_match)
1516 continue;
1517 ret = -EBUSY;
1518 goto out_unlock;
1519 }
873fe09e 1520
c7ba8287 1521 if ((root->flags ^ opts.flags) & CGRP_ROOT_OPTION_MASK) {
2a0ff3fb
JL
1522 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1523 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1524 ret = -EINVAL;
8e30e2b8 1525 goto out_unlock;
2a0ff3fb
JL
1526 } else {
1527 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1528 }
873fe09e 1529 }
2bd59d48 1530
776f02fa
TH
1531 /*
1532 * A root's lifetime is governed by its top cgroup. Zero
1533 * ref indicate that the root is being destroyed. Wait for
1534 * destruction to complete so that the subsystems are free.
1535 * We can use wait_queue for the wait but this path is
1536 * super cold. Let's just sleep for a bit and retry.
1537 */
1538 if (!atomic_inc_not_zero(&root->top_cgroup.refcnt)) {
1539 mutex_unlock(&cgroup_mutex);
1540 mutex_unlock(&cgroup_tree_mutex);
6534fd6c
LZ
1541 kfree(opts.release_agent);
1542 kfree(opts.name);
776f02fa
TH
1543 msleep(10);
1544 goto retry;
1545 }
1546
1547 ret = 0;
2bd59d48 1548 goto out_unlock;
ddbcc7e8
PM
1549 }
1550
2bd59d48
TH
1551 /* no such thing, create a new one */
1552 root = cgroup_root_from_opts(&opts);
1553 if (IS_ERR(root)) {
1554 ret = PTR_ERR(root);
1555 goto out_unlock;
1556 }
1557
35585573 1558 ret = cgroup_setup_root(root, opts.subsys_mask);
2bd59d48
TH
1559 if (ret)
1560 cgroup_free_root(root);
1561
8e30e2b8 1562out_unlock:
e25e2cbb 1563 mutex_unlock(&cgroup_mutex);
ace2bee8 1564 mutex_unlock(&cgroup_tree_mutex);
8e30e2b8 1565
c6d57f33
PM
1566 kfree(opts.release_agent);
1567 kfree(opts.name);
8e30e2b8 1568
2bd59d48 1569 if (ret)
8e30e2b8 1570 return ERR_PTR(ret);
2bd59d48
TH
1571
1572 dentry = kernfs_mount(fs_type, flags, root->kf_root);
1573 if (IS_ERR(dentry))
776f02fa 1574 cgroup_put(&root->top_cgroup);
2bd59d48
TH
1575 return dentry;
1576}
1577
1578static void cgroup_kill_sb(struct super_block *sb)
1579{
1580 struct kernfs_root *kf_root = kernfs_root_from_sb(sb);
1581 struct cgroupfs_root *root = cgroup_root_from_kf(kf_root);
1582
776f02fa 1583 cgroup_put(&root->top_cgroup);
2bd59d48 1584 kernfs_kill_sb(sb);
ddbcc7e8
PM
1585}
1586
ddbcc7e8
PM
1587static struct file_system_type cgroup_fs_type = {
1588 .name = "cgroup",
f7e83571 1589 .mount = cgroup_mount,
ddbcc7e8
PM
1590 .kill_sb = cgroup_kill_sb,
1591};
1592
676db4af
GK
1593static struct kobject *cgroup_kobj;
1594
857a2beb 1595/**
913ffdb5 1596 * task_cgroup_path - cgroup path of a task in the first cgroup hierarchy
857a2beb 1597 * @task: target task
857a2beb
TH
1598 * @buf: the buffer to write the path into
1599 * @buflen: the length of the buffer
1600 *
913ffdb5
TH
1601 * Determine @task's cgroup on the first (the one with the lowest non-zero
1602 * hierarchy_id) cgroup hierarchy and copy its path into @buf. This
1603 * function grabs cgroup_mutex and shouldn't be used inside locks used by
1604 * cgroup controller callbacks.
1605 *
e61734c5 1606 * Return value is the same as kernfs_path().
857a2beb 1607 */
e61734c5 1608char *task_cgroup_path(struct task_struct *task, char *buf, size_t buflen)
857a2beb
TH
1609{
1610 struct cgroupfs_root *root;
913ffdb5 1611 struct cgroup *cgrp;
e61734c5
TH
1612 int hierarchy_id = 1;
1613 char *path = NULL;
857a2beb
TH
1614
1615 mutex_lock(&cgroup_mutex);
96d365e0 1616 down_read(&css_set_rwsem);
857a2beb 1617
913ffdb5
TH
1618 root = idr_get_next(&cgroup_hierarchy_idr, &hierarchy_id);
1619
857a2beb
TH
1620 if (root) {
1621 cgrp = task_cgroup_from_root(task, root);
e61734c5 1622 path = cgroup_path(cgrp, buf, buflen);
913ffdb5
TH
1623 } else {
1624 /* if no hierarchy exists, everyone is in "/" */
e61734c5
TH
1625 if (strlcpy(buf, "/", buflen) < buflen)
1626 path = buf;
857a2beb
TH
1627 }
1628
96d365e0 1629 up_read(&css_set_rwsem);
857a2beb 1630 mutex_unlock(&cgroup_mutex);
e61734c5 1631 return path;
857a2beb 1632}
913ffdb5 1633EXPORT_SYMBOL_GPL(task_cgroup_path);
857a2beb 1634
b3dc094e 1635/* used to track tasks and other necessary states during migration */
2f7ee569 1636struct cgroup_taskset {
b3dc094e
TH
1637 /* the src and dst cset list running through cset->mg_node */
1638 struct list_head src_csets;
1639 struct list_head dst_csets;
1640
1641 /*
1642 * Fields for cgroup_taskset_*() iteration.
1643 *
1644 * Before migration is committed, the target migration tasks are on
1645 * ->mg_tasks of the csets on ->src_csets. After, on ->mg_tasks of
1646 * the csets on ->dst_csets. ->csets point to either ->src_csets
1647 * or ->dst_csets depending on whether migration is committed.
1648 *
1649 * ->cur_csets and ->cur_task point to the current task position
1650 * during iteration.
1651 */
1652 struct list_head *csets;
1653 struct css_set *cur_cset;
1654 struct task_struct *cur_task;
2f7ee569
TH
1655};
1656
1657/**
1658 * cgroup_taskset_first - reset taskset and return the first task
1659 * @tset: taskset of interest
1660 *
1661 * @tset iteration is initialized and the first task is returned.
1662 */
1663struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1664{
b3dc094e
TH
1665 tset->cur_cset = list_first_entry(tset->csets, struct css_set, mg_node);
1666 tset->cur_task = NULL;
1667
1668 return cgroup_taskset_next(tset);
2f7ee569 1669}
2f7ee569
TH
1670
1671/**
1672 * cgroup_taskset_next - iterate to the next task in taskset
1673 * @tset: taskset of interest
1674 *
1675 * Return the next task in @tset. Iteration must have been initialized
1676 * with cgroup_taskset_first().
1677 */
1678struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1679{
b3dc094e
TH
1680 struct css_set *cset = tset->cur_cset;
1681 struct task_struct *task = tset->cur_task;
2f7ee569 1682
b3dc094e
TH
1683 while (&cset->mg_node != tset->csets) {
1684 if (!task)
1685 task = list_first_entry(&cset->mg_tasks,
1686 struct task_struct, cg_list);
1687 else
1688 task = list_next_entry(task, cg_list);
2f7ee569 1689
b3dc094e
TH
1690 if (&task->cg_list != &cset->mg_tasks) {
1691 tset->cur_cset = cset;
1692 tset->cur_task = task;
1693 return task;
1694 }
1695
1696 cset = list_next_entry(cset, mg_node);
1697 task = NULL;
1698 }
1699
1700 return NULL;
2f7ee569 1701}
2f7ee569 1702
cb0f1fe9 1703/**
74a1166d 1704 * cgroup_task_migrate - move a task from one cgroup to another.
cb0f1fe9
TH
1705 * @old_cgrp; the cgroup @tsk is being migrated from
1706 * @tsk: the task being migrated
1707 * @new_cset: the new css_set @tsk is being attached to
74a1166d 1708 *
cb0f1fe9 1709 * Must be called with cgroup_mutex, threadgroup and css_set_rwsem locked.
74a1166d 1710 */
5abb8855
TH
1711static void cgroup_task_migrate(struct cgroup *old_cgrp,
1712 struct task_struct *tsk,
1713 struct css_set *new_cset)
74a1166d 1714{
5abb8855 1715 struct css_set *old_cset;
74a1166d 1716
cb0f1fe9
TH
1717 lockdep_assert_held(&cgroup_mutex);
1718 lockdep_assert_held(&css_set_rwsem);
1719
74a1166d 1720 /*
026085ef
MSB
1721 * We are synchronized through threadgroup_lock() against PF_EXITING
1722 * setting such that we can't race against cgroup_exit() changing the
1723 * css_set to init_css_set and dropping the old one.
74a1166d 1724 */
c84cdf75 1725 WARN_ON_ONCE(tsk->flags & PF_EXITING);
a8ad805c 1726 old_cset = task_css_set(tsk);
74a1166d 1727
b3dc094e 1728 get_css_set(new_cset);
5abb8855 1729 rcu_assign_pointer(tsk->cgroups, new_cset);
b3dc094e 1730 list_move(&tsk->cg_list, &new_cset->mg_tasks);
74a1166d
BB
1731
1732 /*
5abb8855
TH
1733 * We just gained a reference on old_cset by taking it from the
1734 * task. As trading it for new_cset is protected by cgroup_mutex,
1735 * we're safe to drop it here; it will be freed under RCU.
74a1166d 1736 */
5abb8855 1737 set_bit(CGRP_RELEASABLE, &old_cgrp->flags);
cb0f1fe9 1738 put_css_set_locked(old_cset, false);
74a1166d
BB
1739}
1740
a043e3b2 1741/**
1958d2d5
TH
1742 * cgroup_migrate_finish - cleanup after attach
1743 * @preloaded_csets: list of preloaded css_sets
74a1166d 1744 *
1958d2d5
TH
1745 * Undo cgroup_migrate_add_src() and cgroup_migrate_prepare_dst(). See
1746 * those functions for details.
74a1166d 1747 */
1958d2d5
TH
1748static void cgroup_migrate_finish(struct list_head *preloaded_csets)
1749{
1750 struct css_set *cset, *tmp_cset;
1751
1752 lockdep_assert_held(&cgroup_mutex);
1753
1754 down_write(&css_set_rwsem);
1755 list_for_each_entry_safe(cset, tmp_cset, preloaded_csets, mg_preload_node) {
1756 cset->mg_src_cgrp = NULL;
1757 cset->mg_dst_cset = NULL;
1758 list_del_init(&cset->mg_preload_node);
1759 put_css_set_locked(cset, false);
1760 }
1761 up_write(&css_set_rwsem);
1762}
1763
1764/**
1765 * cgroup_migrate_add_src - add a migration source css_set
1766 * @src_cset: the source css_set to add
1767 * @dst_cgrp: the destination cgroup
1768 * @preloaded_csets: list of preloaded css_sets
1769 *
1770 * Tasks belonging to @src_cset are about to be migrated to @dst_cgrp. Pin
1771 * @src_cset and add it to @preloaded_csets, which should later be cleaned
1772 * up by cgroup_migrate_finish().
1773 *
1774 * This function may be called without holding threadgroup_lock even if the
1775 * target is a process. Threads may be created and destroyed but as long
1776 * as cgroup_mutex is not dropped, no new css_set can be put into play and
1777 * the preloaded css_sets are guaranteed to cover all migrations.
1778 */
1779static void cgroup_migrate_add_src(struct css_set *src_cset,
1780 struct cgroup *dst_cgrp,
1781 struct list_head *preloaded_csets)
1782{
1783 struct cgroup *src_cgrp;
1784
1785 lockdep_assert_held(&cgroup_mutex);
1786 lockdep_assert_held(&css_set_rwsem);
1787
1788 src_cgrp = cset_cgroup_from_root(src_cset, dst_cgrp->root);
1789
1790 /* nothing to do if this cset already belongs to the cgroup */
1791 if (src_cgrp == dst_cgrp)
1792 return;
1793
1794 if (!list_empty(&src_cset->mg_preload_node))
1795 return;
1796
1797 WARN_ON(src_cset->mg_src_cgrp);
1798 WARN_ON(!list_empty(&src_cset->mg_tasks));
1799 WARN_ON(!list_empty(&src_cset->mg_node));
1800
1801 src_cset->mg_src_cgrp = src_cgrp;
1802 get_css_set(src_cset);
1803 list_add(&src_cset->mg_preload_node, preloaded_csets);
1804}
1805
1806/**
1807 * cgroup_migrate_prepare_dst - prepare destination css_sets for migration
1808 * @dst_cgrp: the destination cgroup
1809 * @preloaded_csets: list of preloaded source css_sets
1810 *
1811 * Tasks are about to be moved to @dst_cgrp and all the source css_sets
1812 * have been preloaded to @preloaded_csets. This function looks up and
1813 * pins all destination css_sets, links each to its source, and put them on
1814 * @preloaded_csets.
1815 *
1816 * This function must be called after cgroup_migrate_add_src() has been
1817 * called on each migration source css_set. After migration is performed
1818 * using cgroup_migrate(), cgroup_migrate_finish() must be called on
1819 * @preloaded_csets.
1820 */
1821static int cgroup_migrate_prepare_dst(struct cgroup *dst_cgrp,
1822 struct list_head *preloaded_csets)
1823{
1824 LIST_HEAD(csets);
1825 struct css_set *src_cset;
1826
1827 lockdep_assert_held(&cgroup_mutex);
1828
1829 /* look up the dst cset for each src cset and link it to src */
1830 list_for_each_entry(src_cset, preloaded_csets, mg_preload_node) {
1831 struct css_set *dst_cset;
1832
1833 dst_cset = find_css_set(src_cset, dst_cgrp);
1834 if (!dst_cset)
1835 goto err;
1836
1837 WARN_ON_ONCE(src_cset->mg_dst_cset || dst_cset->mg_dst_cset);
1838 src_cset->mg_dst_cset = dst_cset;
1839
1840 if (list_empty(&dst_cset->mg_preload_node))
1841 list_add(&dst_cset->mg_preload_node, &csets);
1842 else
1843 put_css_set(dst_cset, false);
1844 }
1845
1846 list_splice(&csets, preloaded_csets);
1847 return 0;
1848err:
1849 cgroup_migrate_finish(&csets);
1850 return -ENOMEM;
1851}
1852
1853/**
1854 * cgroup_migrate - migrate a process or task to a cgroup
1855 * @cgrp: the destination cgroup
1856 * @leader: the leader of the process or the task to migrate
1857 * @threadgroup: whether @leader points to the whole process or a single task
1858 *
1859 * Migrate a process or task denoted by @leader to @cgrp. If migrating a
1860 * process, the caller must be holding threadgroup_lock of @leader. The
1861 * caller is also responsible for invoking cgroup_migrate_add_src() and
1862 * cgroup_migrate_prepare_dst() on the targets before invoking this
1863 * function and following up with cgroup_migrate_finish().
1864 *
1865 * As long as a controller's ->can_attach() doesn't fail, this function is
1866 * guaranteed to succeed. This means that, excluding ->can_attach()
1867 * failure, when migrating multiple targets, the success or failure can be
1868 * decided for all targets by invoking group_migrate_prepare_dst() before
1869 * actually starting migrating.
1870 */
1871static int cgroup_migrate(struct cgroup *cgrp, struct task_struct *leader,
1872 bool threadgroup)
74a1166d 1873{
b3dc094e
TH
1874 struct cgroup_taskset tset = {
1875 .src_csets = LIST_HEAD_INIT(tset.src_csets),
1876 .dst_csets = LIST_HEAD_INIT(tset.dst_csets),
1877 .csets = &tset.src_csets,
1878 };
1c6727af 1879 struct cgroup_subsys_state *css, *failed_css = NULL;
b3dc094e
TH
1880 struct css_set *cset, *tmp_cset;
1881 struct task_struct *task, *tmp_task;
1882 int i, ret;
74a1166d 1883
fb5d2b4c
MSB
1884 /*
1885 * Prevent freeing of tasks while we take a snapshot. Tasks that are
1886 * already PF_EXITING could be freed from underneath us unless we
1887 * take an rcu_read_lock.
1888 */
b3dc094e 1889 down_write(&css_set_rwsem);
fb5d2b4c 1890 rcu_read_lock();
9db8de37 1891 task = leader;
74a1166d 1892 do {
9db8de37
TH
1893 /* @task either already exited or can't exit until the end */
1894 if (task->flags & PF_EXITING)
ea84753c 1895 goto next;
cd3d0952 1896
eaf797ab
TH
1897 /* leave @task alone if post_fork() hasn't linked it yet */
1898 if (list_empty(&task->cg_list))
1899 goto next;
1900
b3dc094e 1901 cset = task_css_set(task);
1958d2d5 1902 if (!cset->mg_src_cgrp)
ea84753c 1903 goto next;
b3dc094e 1904
b3dc094e 1905 list_move(&task->cg_list, &cset->mg_tasks);
1958d2d5
TH
1906 list_move(&cset->mg_node, &tset.src_csets);
1907 list_move(&cset->mg_dst_cset->mg_node, &tset.dst_csets);
ea84753c 1908 next:
081aa458
LZ
1909 if (!threadgroup)
1910 break;
9db8de37 1911 } while_each_thread(leader, task);
fb5d2b4c 1912 rcu_read_unlock();
b3dc094e 1913 up_write(&css_set_rwsem);
74a1166d 1914
134d3373 1915 /* methods shouldn't be called if no task is actually migrating */
b3dc094e
TH
1916 if (list_empty(&tset.src_csets))
1917 return 0;
134d3373 1918
1958d2d5 1919 /* check that we can legitimately attach to the cgroup */
1c6727af
TH
1920 for_each_css(css, i, cgrp) {
1921 if (css->ss->can_attach) {
9db8de37
TH
1922 ret = css->ss->can_attach(css, &tset);
1923 if (ret) {
1c6727af 1924 failed_css = css;
74a1166d
BB
1925 goto out_cancel_attach;
1926 }
1927 }
74a1166d
BB
1928 }
1929
1930 /*
1958d2d5
TH
1931 * Now that we're guaranteed success, proceed to move all tasks to
1932 * the new cgroup. There are no failure cases after here, so this
1933 * is the commit point.
74a1166d 1934 */
cb0f1fe9 1935 down_write(&css_set_rwsem);
b3dc094e
TH
1936 list_for_each_entry(cset, &tset.src_csets, mg_node) {
1937 list_for_each_entry_safe(task, tmp_task, &cset->mg_tasks, cg_list)
1938 cgroup_task_migrate(cset->mg_src_cgrp, task,
1939 cset->mg_dst_cset);
74a1166d 1940 }
cb0f1fe9 1941 up_write(&css_set_rwsem);
b3dc094e 1942
74a1166d 1943 /*
1958d2d5
TH
1944 * Migration is committed, all target tasks are now on dst_csets.
1945 * Nothing is sensitive to fork() after this point. Notify
1946 * controllers that migration is complete.
74a1166d 1947 */
1958d2d5
TH
1948 tset.csets = &tset.dst_csets;
1949
1c6727af
TH
1950 for_each_css(css, i, cgrp)
1951 if (css->ss->attach)
1952 css->ss->attach(css, &tset);
74a1166d 1953
9db8de37 1954 ret = 0;
b3dc094e
TH
1955 goto out_release_tset;
1956
74a1166d 1957out_cancel_attach:
b3dc094e
TH
1958 for_each_css(css, i, cgrp) {
1959 if (css == failed_css)
1960 break;
1961 if (css->ss->cancel_attach)
1962 css->ss->cancel_attach(css, &tset);
74a1166d 1963 }
b3dc094e
TH
1964out_release_tset:
1965 down_write(&css_set_rwsem);
1966 list_splice_init(&tset.dst_csets, &tset.src_csets);
1967 list_for_each_entry_safe(cset, tmp_cset, &tset.src_csets, mg_node) {
1968 list_splice_init(&cset->mg_tasks, &cset->tasks);
b3dc094e 1969 list_del_init(&cset->mg_node);
b3dc094e
TH
1970 }
1971 up_write(&css_set_rwsem);
9db8de37 1972 return ret;
74a1166d
BB
1973}
1974
1958d2d5
TH
1975/**
1976 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
1977 * @dst_cgrp: the cgroup to attach to
1978 * @leader: the task or the leader of the threadgroup to be attached
1979 * @threadgroup: attach the whole threadgroup?
1980 *
0e1d768f 1981 * Call holding cgroup_mutex and threadgroup_lock of @leader.
1958d2d5
TH
1982 */
1983static int cgroup_attach_task(struct cgroup *dst_cgrp,
1984 struct task_struct *leader, bool threadgroup)
1985{
1986 LIST_HEAD(preloaded_csets);
1987 struct task_struct *task;
1988 int ret;
1989
1990 /* look up all src csets */
1991 down_read(&css_set_rwsem);
1992 rcu_read_lock();
1993 task = leader;
1994 do {
1995 cgroup_migrate_add_src(task_css_set(task), dst_cgrp,
1996 &preloaded_csets);
1997 if (!threadgroup)
1998 break;
1999 } while_each_thread(leader, task);
2000 rcu_read_unlock();
2001 up_read(&css_set_rwsem);
2002
2003 /* prepare dst csets and commit */
2004 ret = cgroup_migrate_prepare_dst(dst_cgrp, &preloaded_csets);
2005 if (!ret)
2006 ret = cgroup_migrate(dst_cgrp, leader, threadgroup);
2007
2008 cgroup_migrate_finish(&preloaded_csets);
2009 return ret;
2010}
2011
74a1166d
BB
2012/*
2013 * Find the task_struct of the task to attach by vpid and pass it along to the
cd3d0952 2014 * function to attach either it or all tasks in its threadgroup. Will lock
0e1d768f 2015 * cgroup_mutex and threadgroup.
bbcb81d0 2016 */
74a1166d 2017static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
bbcb81d0 2018{
bbcb81d0 2019 struct task_struct *tsk;
c69e8d9c 2020 const struct cred *cred = current_cred(), *tcred;
bbcb81d0
PM
2021 int ret;
2022
74a1166d
BB
2023 if (!cgroup_lock_live_group(cgrp))
2024 return -ENODEV;
2025
b78949eb
MSB
2026retry_find_task:
2027 rcu_read_lock();
bbcb81d0 2028 if (pid) {
73507f33 2029 tsk = find_task_by_vpid(pid);
74a1166d
BB
2030 if (!tsk) {
2031 rcu_read_unlock();
dd4b0a46 2032 ret = -ESRCH;
b78949eb 2033 goto out_unlock_cgroup;
bbcb81d0 2034 }
74a1166d
BB
2035 /*
2036 * even if we're attaching all tasks in the thread group, we
2037 * only need to check permissions on one of them.
2038 */
c69e8d9c 2039 tcred = __task_cred(tsk);
14a590c3
EB
2040 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2041 !uid_eq(cred->euid, tcred->uid) &&
2042 !uid_eq(cred->euid, tcred->suid)) {
c69e8d9c 2043 rcu_read_unlock();
b78949eb
MSB
2044 ret = -EACCES;
2045 goto out_unlock_cgroup;
bbcb81d0 2046 }
b78949eb
MSB
2047 } else
2048 tsk = current;
cd3d0952
TH
2049
2050 if (threadgroup)
b78949eb 2051 tsk = tsk->group_leader;
c4c27fbd
MG
2052
2053 /*
14a40ffc 2054 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
c4c27fbd
MG
2055 * trapped in a cpuset, or RT worker may be born in a cgroup
2056 * with no rt_runtime allocated. Just say no.
2057 */
14a40ffc 2058 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
c4c27fbd
MG
2059 ret = -EINVAL;
2060 rcu_read_unlock();
2061 goto out_unlock_cgroup;
2062 }
2063
b78949eb
MSB
2064 get_task_struct(tsk);
2065 rcu_read_unlock();
2066
2067 threadgroup_lock(tsk);
2068 if (threadgroup) {
2069 if (!thread_group_leader(tsk)) {
2070 /*
2071 * a race with de_thread from another thread's exec()
2072 * may strip us of our leadership, if this happens,
2073 * there is no choice but to throw this task away and
2074 * try again; this is
2075 * "double-double-toil-and-trouble-check locking".
2076 */
2077 threadgroup_unlock(tsk);
2078 put_task_struct(tsk);
2079 goto retry_find_task;
2080 }
081aa458
LZ
2081 }
2082
2083 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2084
cd3d0952
TH
2085 threadgroup_unlock(tsk);
2086
bbcb81d0 2087 put_task_struct(tsk);
b78949eb 2088out_unlock_cgroup:
47cfcd09 2089 mutex_unlock(&cgroup_mutex);
bbcb81d0
PM
2090 return ret;
2091}
2092
7ae1bad9
TH
2093/**
2094 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2095 * @from: attach to all cgroups of a given task
2096 * @tsk: the task to be attached
2097 */
2098int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2099{
2100 struct cgroupfs_root *root;
2101 int retval = 0;
2102
47cfcd09 2103 mutex_lock(&cgroup_mutex);
7ae1bad9 2104 for_each_active_root(root) {
96d365e0
TH
2105 struct cgroup *from_cgrp;
2106
2107 down_read(&css_set_rwsem);
2108 from_cgrp = task_cgroup_from_root(from, root);
2109 up_read(&css_set_rwsem);
7ae1bad9 2110
6f4b7e63 2111 retval = cgroup_attach_task(from_cgrp, tsk, false);
7ae1bad9
TH
2112 if (retval)
2113 break;
2114 }
47cfcd09 2115 mutex_unlock(&cgroup_mutex);
7ae1bad9
TH
2116
2117 return retval;
2118}
2119EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2120
182446d0
TH
2121static int cgroup_tasks_write(struct cgroup_subsys_state *css,
2122 struct cftype *cft, u64 pid)
74a1166d 2123{
182446d0 2124 return attach_task_by_pid(css->cgroup, pid, false);
74a1166d
BB
2125}
2126
182446d0
TH
2127static int cgroup_procs_write(struct cgroup_subsys_state *css,
2128 struct cftype *cft, u64 tgid)
af351026 2129{
182446d0 2130 return attach_task_by_pid(css->cgroup, tgid, true);
af351026
PM
2131}
2132
182446d0
TH
2133static int cgroup_release_agent_write(struct cgroup_subsys_state *css,
2134 struct cftype *cft, const char *buffer)
e788e066 2135{
5f469907
TH
2136 struct cgroupfs_root *root = css->cgroup->root;
2137
2138 BUILD_BUG_ON(sizeof(root->release_agent_path) < PATH_MAX);
182446d0 2139 if (!cgroup_lock_live_group(css->cgroup))
e788e066 2140 return -ENODEV;
69e943b7 2141 spin_lock(&release_agent_path_lock);
5f469907
TH
2142 strlcpy(root->release_agent_path, buffer,
2143 sizeof(root->release_agent_path));
69e943b7 2144 spin_unlock(&release_agent_path_lock);
47cfcd09 2145 mutex_unlock(&cgroup_mutex);
e788e066
PM
2146 return 0;
2147}
2148
2da8ca82 2149static int cgroup_release_agent_show(struct seq_file *seq, void *v)
e788e066 2150{
2da8ca82 2151 struct cgroup *cgrp = seq_css(seq)->cgroup;
182446d0 2152
e788e066
PM
2153 if (!cgroup_lock_live_group(cgrp))
2154 return -ENODEV;
2155 seq_puts(seq, cgrp->root->release_agent_path);
2156 seq_putc(seq, '\n');
47cfcd09 2157 mutex_unlock(&cgroup_mutex);
e788e066
PM
2158 return 0;
2159}
2160
2da8ca82 2161static int cgroup_sane_behavior_show(struct seq_file *seq, void *v)
873fe09e 2162{
2da8ca82
TH
2163 struct cgroup *cgrp = seq_css(seq)->cgroup;
2164
2165 seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
e788e066
PM
2166 return 0;
2167}
2168
2bd59d48
TH
2169static ssize_t cgroup_file_write(struct kernfs_open_file *of, char *buf,
2170 size_t nbytes, loff_t off)
355e0c48 2171{
2bd59d48
TH
2172 struct cgroup *cgrp = of->kn->parent->priv;
2173 struct cftype *cft = of->kn->priv;
2174 struct cgroup_subsys_state *css;
a742c59d 2175 int ret;
355e0c48 2176
2bd59d48
TH
2177 /*
2178 * kernfs guarantees that a file isn't deleted with operations in
2179 * flight, which means that the matching css is and stays alive and
2180 * doesn't need to be pinned. The RCU locking is not necessary
2181 * either. It's just for the convenience of using cgroup_css().
2182 */
2183 rcu_read_lock();
2184 css = cgroup_css(cgrp, cft->ss);
2185 rcu_read_unlock();
a742c59d
TH
2186
2187 if (cft->write_string) {
2188 ret = cft->write_string(css, cft, strstrip(buf));
2189 } else if (cft->write_u64) {
2190 unsigned long long v;
2191 ret = kstrtoull(buf, 0, &v);
2192 if (!ret)
2193 ret = cft->write_u64(css, cft, v);
2194 } else if (cft->write_s64) {
2195 long long v;
2196 ret = kstrtoll(buf, 0, &v);
2197 if (!ret)
2198 ret = cft->write_s64(css, cft, v);
2199 } else if (cft->trigger) {
2200 ret = cft->trigger(css, (unsigned int)cft->private);
e73d2c61 2201 } else {
a742c59d 2202 ret = -EINVAL;
e73d2c61 2203 }
2bd59d48 2204
a742c59d 2205 return ret ?: nbytes;
355e0c48
PM
2206}
2207
6612f05b 2208static void *cgroup_seqfile_start(struct seq_file *seq, loff_t *ppos)
db3b1497 2209{
2bd59d48 2210 return seq_cft(seq)->seq_start(seq, ppos);
db3b1497
PM
2211}
2212
6612f05b 2213static void *cgroup_seqfile_next(struct seq_file *seq, void *v, loff_t *ppos)
ddbcc7e8 2214{
2bd59d48 2215 return seq_cft(seq)->seq_next(seq, v, ppos);
ddbcc7e8
PM
2216}
2217
6612f05b 2218static void cgroup_seqfile_stop(struct seq_file *seq, void *v)
ddbcc7e8 2219{
2bd59d48 2220 seq_cft(seq)->seq_stop(seq, v);
ddbcc7e8
PM
2221}
2222
91796569 2223static int cgroup_seqfile_show(struct seq_file *m, void *arg)
e73d2c61 2224{
7da11279
TH
2225 struct cftype *cft = seq_cft(m);
2226 struct cgroup_subsys_state *css = seq_css(m);
e73d2c61 2227
2da8ca82
TH
2228 if (cft->seq_show)
2229 return cft->seq_show(m, arg);
e73d2c61 2230
f4c753b7 2231 if (cft->read_u64)
896f5199
TH
2232 seq_printf(m, "%llu\n", cft->read_u64(css, cft));
2233 else if (cft->read_s64)
2234 seq_printf(m, "%lld\n", cft->read_s64(css, cft));
2235 else
2236 return -EINVAL;
2237 return 0;
91796569
PM
2238}
2239
2bd59d48
TH
2240static struct kernfs_ops cgroup_kf_single_ops = {
2241 .atomic_write_len = PAGE_SIZE,
2242 .write = cgroup_file_write,
2243 .seq_show = cgroup_seqfile_show,
91796569
PM
2244};
2245
2bd59d48
TH
2246static struct kernfs_ops cgroup_kf_ops = {
2247 .atomic_write_len = PAGE_SIZE,
2248 .write = cgroup_file_write,
2249 .seq_start = cgroup_seqfile_start,
2250 .seq_next = cgroup_seqfile_next,
2251 .seq_stop = cgroup_seqfile_stop,
2252 .seq_show = cgroup_seqfile_show,
2253};
ddbcc7e8
PM
2254
2255/*
2256 * cgroup_rename - Only allow simple rename of directories in place.
2257 */
2bd59d48
TH
2258static int cgroup_rename(struct kernfs_node *kn, struct kernfs_node *new_parent,
2259 const char *new_name_str)
ddbcc7e8 2260{
2bd59d48 2261 struct cgroup *cgrp = kn->priv;
2bd59d48 2262 int ret;
65dff759 2263
2bd59d48 2264 if (kernfs_type(kn) != KERNFS_DIR)
ddbcc7e8 2265 return -ENOTDIR;
2bd59d48 2266 if (kn->parent != new_parent)
ddbcc7e8 2267 return -EIO;
65dff759 2268
6db8e85c
TH
2269 /*
2270 * This isn't a proper migration and its usefulness is very
2271 * limited. Disallow if sane_behavior.
2272 */
2273 if (cgroup_sane_behavior(cgrp))
2274 return -EPERM;
2275
2bd59d48
TH
2276 mutex_lock(&cgroup_tree_mutex);
2277 mutex_lock(&cgroup_mutex);
2278
2279 ret = kernfs_rename(kn, new_parent, new_name_str);
65dff759 2280
2bd59d48
TH
2281 mutex_unlock(&cgroup_mutex);
2282 mutex_unlock(&cgroup_tree_mutex);
2bd59d48 2283 return ret;
ddbcc7e8
PM
2284}
2285
2bb566cb 2286static int cgroup_add_file(struct cgroup *cgrp, struct cftype *cft)
ddbcc7e8 2287{
8d7e6fb0 2288 char name[CGROUP_FILE_NAME_MAX];
2bd59d48
TH
2289 struct kernfs_node *kn;
2290 struct lock_class_key *key = NULL;
05ef1d7c 2291
2bd59d48
TH
2292#ifdef CONFIG_DEBUG_LOCK_ALLOC
2293 key = &cft->lockdep_key;
2294#endif
2295 kn = __kernfs_create_file(cgrp->kn, cgroup_file_name(cgrp, cft, name),
2296 cgroup_file_mode(cft), 0, cft->kf_ops, cft,
2297 NULL, false, key);
430af8ad 2298 return PTR_ERR_OR_ZERO(kn);
ddbcc7e8
PM
2299}
2300
b1f28d31
TH
2301/**
2302 * cgroup_addrm_files - add or remove files to a cgroup directory
2303 * @cgrp: the target cgroup
b1f28d31
TH
2304 * @cfts: array of cftypes to be added
2305 * @is_add: whether to add or remove
2306 *
2307 * Depending on @is_add, add or remove files defined by @cfts on @cgrp.
2bb566cb
TH
2308 * For removals, this function never fails. If addition fails, this
2309 * function doesn't remove files already added. The caller is responsible
2310 * for cleaning up.
b1f28d31 2311 */
2bb566cb
TH
2312static int cgroup_addrm_files(struct cgroup *cgrp, struct cftype cfts[],
2313 bool is_add)
ddbcc7e8 2314{
03b1cde6 2315 struct cftype *cft;
b1f28d31
TH
2316 int ret;
2317
ace2bee8 2318 lockdep_assert_held(&cgroup_tree_mutex);
db0416b6
TH
2319
2320 for (cft = cfts; cft->name[0] != '\0'; cft++) {
f33fddc2 2321 /* does cft->flags tell us to skip this file on @cgrp? */
873fe09e
TH
2322 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2323 continue;
f33fddc2
G
2324 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2325 continue;
2326 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2327 continue;
2328
2739d3cc 2329 if (is_add) {
2bb566cb 2330 ret = cgroup_add_file(cgrp, cft);
b1f28d31 2331 if (ret) {
2739d3cc 2332 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
b1f28d31
TH
2333 cft->name, ret);
2334 return ret;
2335 }
2739d3cc
LZ
2336 } else {
2337 cgroup_rm_file(cgrp, cft);
db0416b6 2338 }
ddbcc7e8 2339 }
b1f28d31 2340 return 0;
ddbcc7e8
PM
2341}
2342
21a2d343 2343static int cgroup_apply_cftypes(struct cftype *cfts, bool is_add)
8e3f6541
TH
2344{
2345 LIST_HEAD(pending);
2bb566cb 2346 struct cgroup_subsys *ss = cfts[0].ss;
492eb21b 2347 struct cgroup *root = &ss->root->top_cgroup;
492eb21b 2348 struct cgroup_subsys_state *css;
9ccece80 2349 int ret = 0;
8e3f6541 2350
21a2d343 2351 lockdep_assert_held(&cgroup_tree_mutex);
4ac06017 2352
21a2d343
TH
2353 /* don't bother if @ss isn't attached */
2354 if (ss->root == &cgroup_dummy_root)
9ccece80 2355 return 0;
e8c82d20 2356
e8c82d20 2357 /* add/rm files for all cgroups created before */
ca8bdcaf 2358 css_for_each_descendant_pre(css, cgroup_css(root, ss)) {
492eb21b
TH
2359 struct cgroup *cgrp = css->cgroup;
2360
e8c82d20
LZ
2361 if (cgroup_is_dead(cgrp))
2362 continue;
2363
21a2d343 2364 ret = cgroup_addrm_files(cgrp, cfts, is_add);
9ccece80
TH
2365 if (ret)
2366 break;
8e3f6541 2367 }
21a2d343
TH
2368
2369 if (is_add && !ret)
2370 kernfs_activate(root->kn);
9ccece80 2371 return ret;
8e3f6541
TH
2372}
2373
2da440a2
TH
2374static void cgroup_exit_cftypes(struct cftype *cfts)
2375{
2376 struct cftype *cft;
2377
2bd59d48
TH
2378 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2379 /* free copy for custom atomic_write_len, see init_cftypes() */
2380 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE)
2381 kfree(cft->kf_ops);
2382 cft->kf_ops = NULL;
2da440a2 2383 cft->ss = NULL;
2bd59d48 2384 }
2da440a2
TH
2385}
2386
2bd59d48 2387static int cgroup_init_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
2da440a2
TH
2388{
2389 struct cftype *cft;
2390
2bd59d48
TH
2391 for (cft = cfts; cft->name[0] != '\0'; cft++) {
2392 struct kernfs_ops *kf_ops;
2393
0adb0704
TH
2394 WARN_ON(cft->ss || cft->kf_ops);
2395
2bd59d48
TH
2396 if (cft->seq_start)
2397 kf_ops = &cgroup_kf_ops;
2398 else
2399 kf_ops = &cgroup_kf_single_ops;
2400
2401 /*
2402 * Ugh... if @cft wants a custom max_write_len, we need to
2403 * make a copy of kf_ops to set its atomic_write_len.
2404 */
2405 if (cft->max_write_len && cft->max_write_len != PAGE_SIZE) {
2406 kf_ops = kmemdup(kf_ops, sizeof(*kf_ops), GFP_KERNEL);
2407 if (!kf_ops) {
2408 cgroup_exit_cftypes(cfts);
2409 return -ENOMEM;
2410 }
2411 kf_ops->atomic_write_len = cft->max_write_len;
2412 }
2413
2414 cft->kf_ops = kf_ops;
2da440a2 2415 cft->ss = ss;
2bd59d48
TH
2416 }
2417
2418 return 0;
2da440a2
TH
2419}
2420
21a2d343
TH
2421static int cgroup_rm_cftypes_locked(struct cftype *cfts)
2422{
2423 lockdep_assert_held(&cgroup_tree_mutex);
2424
2425 if (!cfts || !cfts[0].ss)
2426 return -ENOENT;
2427
2428 list_del(&cfts->node);
2429 cgroup_apply_cftypes(cfts, false);
2430 cgroup_exit_cftypes(cfts);
2431 return 0;
2432}
2433
80b13586
TH
2434/**
2435 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2436 * @cfts: zero-length name terminated array of cftypes
2437 *
2438 * Unregister @cfts. Files described by @cfts are removed from all
2439 * existing cgroups and all future cgroups won't have them either. This
2440 * function can be called anytime whether @cfts' subsys is attached or not.
2441 *
2442 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2443 * registered.
2444 */
2445int cgroup_rm_cftypes(struct cftype *cfts)
2446{
21a2d343 2447 int ret;
80b13586 2448
21a2d343
TH
2449 mutex_lock(&cgroup_tree_mutex);
2450 ret = cgroup_rm_cftypes_locked(cfts);
2451 mutex_unlock(&cgroup_tree_mutex);
2452 return ret;
80b13586
TH
2453}
2454
8e3f6541
TH
2455/**
2456 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2457 * @ss: target cgroup subsystem
2458 * @cfts: zero-length name terminated array of cftypes
2459 *
2460 * Register @cfts to @ss. Files described by @cfts are created for all
2461 * existing cgroups to which @ss is attached and all future cgroups will
2462 * have them too. This function can be called anytime whether @ss is
2463 * attached or not.
2464 *
2465 * Returns 0 on successful registration, -errno on failure. Note that this
2466 * function currently returns 0 as long as @cfts registration is successful
2467 * even if some file creation attempts on existing cgroups fail.
2468 */
03b1cde6 2469int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
8e3f6541 2470{
9ccece80 2471 int ret;
8e3f6541 2472
dc5736ed
LZ
2473 if (!cfts || cfts[0].name[0] == '\0')
2474 return 0;
2475
2bd59d48
TH
2476 ret = cgroup_init_cftypes(ss, cfts);
2477 if (ret)
2478 return ret;
2bb566cb 2479
21a2d343
TH
2480 mutex_lock(&cgroup_tree_mutex);
2481
0adb0704 2482 list_add_tail(&cfts->node, &ss->cfts);
21a2d343 2483 ret = cgroup_apply_cftypes(cfts, true);
9ccece80 2484 if (ret)
21a2d343
TH
2485 cgroup_rm_cftypes_locked(cfts);
2486
2487 mutex_unlock(&cgroup_tree_mutex);
9ccece80 2488 return ret;
8e3f6541 2489}
8e3f6541 2490
a043e3b2
LZ
2491/**
2492 * cgroup_task_count - count the number of tasks in a cgroup.
2493 * @cgrp: the cgroup in question
2494 *
2495 * Return the number of tasks in the cgroup.
2496 */
07bc356e 2497static int cgroup_task_count(const struct cgroup *cgrp)
bbcb81d0
PM
2498{
2499 int count = 0;
69d0206c 2500 struct cgrp_cset_link *link;
817929ec 2501
96d365e0 2502 down_read(&css_set_rwsem);
69d0206c
TH
2503 list_for_each_entry(link, &cgrp->cset_links, cset_link)
2504 count += atomic_read(&link->cset->refcount);
96d365e0 2505 up_read(&css_set_rwsem);
bbcb81d0
PM
2506 return count;
2507}
2508
53fa5261 2509/**
492eb21b
TH
2510 * css_next_child - find the next child of a given css
2511 * @pos_css: the current position (%NULL to initiate traversal)
2512 * @parent_css: css whose children to walk
53fa5261 2513 *
492eb21b 2514 * This function returns the next child of @parent_css and should be called
87fb54f1
TH
2515 * under either cgroup_mutex or RCU read lock. The only requirement is
2516 * that @parent_css and @pos_css are accessible. The next sibling is
2517 * guaranteed to be returned regardless of their states.
53fa5261 2518 */
492eb21b
TH
2519struct cgroup_subsys_state *
2520css_next_child(struct cgroup_subsys_state *pos_css,
2521 struct cgroup_subsys_state *parent_css)
53fa5261 2522{
492eb21b
TH
2523 struct cgroup *pos = pos_css ? pos_css->cgroup : NULL;
2524 struct cgroup *cgrp = parent_css->cgroup;
53fa5261
TH
2525 struct cgroup *next;
2526
ace2bee8 2527 cgroup_assert_mutexes_or_rcu_locked();
53fa5261
TH
2528
2529 /*
2530 * @pos could already have been removed. Once a cgroup is removed,
2531 * its ->sibling.next is no longer updated when its next sibling
ea15f8cc
TH
2532 * changes. As CGRP_DEAD assertion is serialized and happens
2533 * before the cgroup is taken off the ->sibling list, if we see it
2534 * unasserted, it's guaranteed that the next sibling hasn't
2535 * finished its grace period even if it's already removed, and thus
2536 * safe to dereference from this RCU critical section. If
2537 * ->sibling.next is inaccessible, cgroup_is_dead() is guaranteed
2538 * to be visible as %true here.
3b287a50
TH
2539 *
2540 * If @pos is dead, its next pointer can't be dereferenced;
2541 * however, as each cgroup is given a monotonically increasing
2542 * unique serial number and always appended to the sibling list,
2543 * the next one can be found by walking the parent's children until
2544 * we see a cgroup with higher serial number than @pos's. While
2545 * this path can be slower, it's taken only when either the current
2546 * cgroup is removed or iteration and removal race.
53fa5261 2547 */
3b287a50
TH
2548 if (!pos) {
2549 next = list_entry_rcu(cgrp->children.next, struct cgroup, sibling);
2550 } else if (likely(!cgroup_is_dead(pos))) {
53fa5261 2551 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3b287a50
TH
2552 } else {
2553 list_for_each_entry_rcu(next, &cgrp->children, sibling)
2554 if (next->serial_nr > pos->serial_nr)
2555 break;
53fa5261
TH
2556 }
2557
492eb21b
TH
2558 if (&next->sibling == &cgrp->children)
2559 return NULL;
2560
ca8bdcaf 2561 return cgroup_css(next, parent_css->ss);
53fa5261 2562}
53fa5261 2563
574bd9f7 2564/**
492eb21b 2565 * css_next_descendant_pre - find the next descendant for pre-order walk
574bd9f7 2566 * @pos: the current position (%NULL to initiate traversal)
492eb21b 2567 * @root: css whose descendants to walk
574bd9f7 2568 *
492eb21b 2569 * To be used by css_for_each_descendant_pre(). Find the next descendant
bd8815a6
TH
2570 * to visit for pre-order traversal of @root's descendants. @root is
2571 * included in the iteration and the first node to be visited.
75501a6d 2572 *
87fb54f1
TH
2573 * While this function requires cgroup_mutex or RCU read locking, it
2574 * doesn't require the whole traversal to be contained in a single critical
2575 * section. This function will return the correct next descendant as long
2576 * as both @pos and @root are accessible and @pos is a descendant of @root.
574bd9f7 2577 */
492eb21b
TH
2578struct cgroup_subsys_state *
2579css_next_descendant_pre(struct cgroup_subsys_state *pos,
2580 struct cgroup_subsys_state *root)
574bd9f7 2581{
492eb21b 2582 struct cgroup_subsys_state *next;
574bd9f7 2583
ace2bee8 2584 cgroup_assert_mutexes_or_rcu_locked();
574bd9f7 2585
bd8815a6 2586 /* if first iteration, visit @root */
7805d000 2587 if (!pos)
bd8815a6 2588 return root;
574bd9f7
TH
2589
2590 /* visit the first child if exists */
492eb21b 2591 next = css_next_child(NULL, pos);
574bd9f7
TH
2592 if (next)
2593 return next;
2594
2595 /* no child, visit my or the closest ancestor's next sibling */
492eb21b
TH
2596 while (pos != root) {
2597 next = css_next_child(pos, css_parent(pos));
75501a6d 2598 if (next)
574bd9f7 2599 return next;
492eb21b 2600 pos = css_parent(pos);
7805d000 2601 }
574bd9f7
TH
2602
2603 return NULL;
2604}
574bd9f7 2605
12a9d2fe 2606/**
492eb21b
TH
2607 * css_rightmost_descendant - return the rightmost descendant of a css
2608 * @pos: css of interest
12a9d2fe 2609 *
492eb21b
TH
2610 * Return the rightmost descendant of @pos. If there's no descendant, @pos
2611 * is returned. This can be used during pre-order traversal to skip
12a9d2fe 2612 * subtree of @pos.
75501a6d 2613 *
87fb54f1
TH
2614 * While this function requires cgroup_mutex or RCU read locking, it
2615 * doesn't require the whole traversal to be contained in a single critical
2616 * section. This function will return the correct rightmost descendant as
2617 * long as @pos is accessible.
12a9d2fe 2618 */
492eb21b
TH
2619struct cgroup_subsys_state *
2620css_rightmost_descendant(struct cgroup_subsys_state *pos)
12a9d2fe 2621{
492eb21b 2622 struct cgroup_subsys_state *last, *tmp;
12a9d2fe 2623
ace2bee8 2624 cgroup_assert_mutexes_or_rcu_locked();
12a9d2fe
TH
2625
2626 do {
2627 last = pos;
2628 /* ->prev isn't RCU safe, walk ->next till the end */
2629 pos = NULL;
492eb21b 2630 css_for_each_child(tmp, last)
12a9d2fe
TH
2631 pos = tmp;
2632 } while (pos);
2633
2634 return last;
2635}
12a9d2fe 2636
492eb21b
TH
2637static struct cgroup_subsys_state *
2638css_leftmost_descendant(struct cgroup_subsys_state *pos)
574bd9f7 2639{
492eb21b 2640 struct cgroup_subsys_state *last;
574bd9f7
TH
2641
2642 do {
2643 last = pos;
492eb21b 2644 pos = css_next_child(NULL, pos);
574bd9f7
TH
2645 } while (pos);
2646
2647 return last;
2648}
2649
2650/**
492eb21b 2651 * css_next_descendant_post - find the next descendant for post-order walk
574bd9f7 2652 * @pos: the current position (%NULL to initiate traversal)
492eb21b 2653 * @root: css whose descendants to walk
574bd9f7 2654 *
492eb21b 2655 * To be used by css_for_each_descendant_post(). Find the next descendant
bd8815a6
TH
2656 * to visit for post-order traversal of @root's descendants. @root is
2657 * included in the iteration and the last node to be visited.
75501a6d 2658 *
87fb54f1
TH
2659 * While this function requires cgroup_mutex or RCU read locking, it
2660 * doesn't require the whole traversal to be contained in a single critical
2661 * section. This function will return the correct next descendant as long
2662 * as both @pos and @cgroup are accessible and @pos is a descendant of
2663 * @cgroup.
574bd9f7 2664 */
492eb21b
TH
2665struct cgroup_subsys_state *
2666css_next_descendant_post(struct cgroup_subsys_state *pos,
2667 struct cgroup_subsys_state *root)
574bd9f7 2668{
492eb21b 2669 struct cgroup_subsys_state *next;
574bd9f7 2670
ace2bee8 2671 cgroup_assert_mutexes_or_rcu_locked();
574bd9f7 2672
58b79a91
TH
2673 /* if first iteration, visit leftmost descendant which may be @root */
2674 if (!pos)
2675 return css_leftmost_descendant(root);
574bd9f7 2676
bd8815a6
TH
2677 /* if we visited @root, we're done */
2678 if (pos == root)
2679 return NULL;
2680
574bd9f7 2681 /* if there's an unvisited sibling, visit its leftmost descendant */
492eb21b 2682 next = css_next_child(pos, css_parent(pos));
75501a6d 2683 if (next)
492eb21b 2684 return css_leftmost_descendant(next);
574bd9f7
TH
2685
2686 /* no sibling left, visit parent */
bd8815a6 2687 return css_parent(pos);
574bd9f7 2688}
574bd9f7 2689
0942eeee 2690/**
72ec7029 2691 * css_advance_task_iter - advance a task itererator to the next css_set
0942eeee
TH
2692 * @it: the iterator to advance
2693 *
2694 * Advance @it to the next css_set to walk.
d515876e 2695 */
72ec7029 2696static void css_advance_task_iter(struct css_task_iter *it)
d515876e
TH
2697{
2698 struct list_head *l = it->cset_link;
2699 struct cgrp_cset_link *link;
2700 struct css_set *cset;
2701
2702 /* Advance to the next non-empty css_set */
2703 do {
2704 l = l->next;
72ec7029 2705 if (l == &it->origin_css->cgroup->cset_links) {
d515876e
TH
2706 it->cset_link = NULL;
2707 return;
2708 }
2709 link = list_entry(l, struct cgrp_cset_link, cset_link);
2710 cset = link->cset;
c7561128
TH
2711 } while (list_empty(&cset->tasks) && list_empty(&cset->mg_tasks));
2712
d515876e 2713 it->cset_link = l;
c7561128
TH
2714
2715 if (!list_empty(&cset->tasks))
2716 it->task = cset->tasks.next;
2717 else
2718 it->task = cset->mg_tasks.next;
d515876e
TH
2719}
2720
0942eeee 2721/**
72ec7029
TH
2722 * css_task_iter_start - initiate task iteration
2723 * @css: the css to walk tasks of
0942eeee
TH
2724 * @it: the task iterator to use
2725 *
72ec7029
TH
2726 * Initiate iteration through the tasks of @css. The caller can call
2727 * css_task_iter_next() to walk through the tasks until the function
2728 * returns NULL. On completion of iteration, css_task_iter_end() must be
2729 * called.
0942eeee
TH
2730 *
2731 * Note that this function acquires a lock which is released when the
2732 * iteration finishes. The caller can't sleep while iteration is in
2733 * progress.
2734 */
72ec7029
TH
2735void css_task_iter_start(struct cgroup_subsys_state *css,
2736 struct css_task_iter *it)
96d365e0 2737 __acquires(css_set_rwsem)
817929ec 2738{
56fde9e0
TH
2739 /* no one should try to iterate before mounting cgroups */
2740 WARN_ON_ONCE(!use_task_css_set_links);
31a7df01 2741
96d365e0 2742 down_read(&css_set_rwsem);
c59cd3d8 2743
72ec7029
TH
2744 it->origin_css = css;
2745 it->cset_link = &css->cgroup->cset_links;
c59cd3d8 2746
72ec7029 2747 css_advance_task_iter(it);
817929ec
PM
2748}
2749
0942eeee 2750/**
72ec7029 2751 * css_task_iter_next - return the next task for the iterator
0942eeee
TH
2752 * @it: the task iterator being iterated
2753 *
2754 * The "next" function for task iteration. @it should have been
72ec7029
TH
2755 * initialized via css_task_iter_start(). Returns NULL when the iteration
2756 * reaches the end.
0942eeee 2757 */
72ec7029 2758struct task_struct *css_task_iter_next(struct css_task_iter *it)
817929ec
PM
2759{
2760 struct task_struct *res;
2761 struct list_head *l = it->task;
c7561128
TH
2762 struct cgrp_cset_link *link = list_entry(it->cset_link,
2763 struct cgrp_cset_link, cset_link);
817929ec
PM
2764
2765 /* If the iterator cg is NULL, we have no tasks */
69d0206c 2766 if (!it->cset_link)
817929ec
PM
2767 return NULL;
2768 res = list_entry(l, struct task_struct, cg_list);
c7561128
TH
2769
2770 /*
2771 * Advance iterator to find next entry. cset->tasks is consumed
2772 * first and then ->mg_tasks. After ->mg_tasks, we move onto the
2773 * next cset.
2774 */
817929ec 2775 l = l->next;
c7561128
TH
2776
2777 if (l == &link->cset->tasks)
2778 l = link->cset->mg_tasks.next;
2779
2780 if (l == &link->cset->mg_tasks)
72ec7029 2781 css_advance_task_iter(it);
c7561128 2782 else
817929ec 2783 it->task = l;
c7561128 2784
817929ec
PM
2785 return res;
2786}
2787
0942eeee 2788/**
72ec7029 2789 * css_task_iter_end - finish task iteration
0942eeee
TH
2790 * @it: the task iterator to finish
2791 *
72ec7029 2792 * Finish task iteration started by css_task_iter_start().
0942eeee 2793 */
72ec7029 2794void css_task_iter_end(struct css_task_iter *it)
96d365e0 2795 __releases(css_set_rwsem)
817929ec 2796{
96d365e0 2797 up_read(&css_set_rwsem);
817929ec
PM
2798}
2799
8cc99345
TH
2800/**
2801 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
2802 * @to: cgroup to which the tasks will be moved
2803 * @from: cgroup in which the tasks currently reside
eaf797ab
TH
2804 *
2805 * Locking rules between cgroup_post_fork() and the migration path
2806 * guarantee that, if a task is forking while being migrated, the new child
2807 * is guaranteed to be either visible in the source cgroup after the
2808 * parent's migration is complete or put into the target cgroup. No task
2809 * can slip out of migration through forking.
8cc99345
TH
2810 */
2811int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
2812{
952aaa12
TH
2813 LIST_HEAD(preloaded_csets);
2814 struct cgrp_cset_link *link;
e406d1cf
TH
2815 struct css_task_iter it;
2816 struct task_struct *task;
952aaa12
TH
2817 int ret;
2818
2819 mutex_lock(&cgroup_mutex);
2820
2821 /* all tasks in @from are being moved, all csets are source */
2822 down_read(&css_set_rwsem);
2823 list_for_each_entry(link, &from->cset_links, cset_link)
2824 cgroup_migrate_add_src(link->cset, to, &preloaded_csets);
2825 up_read(&css_set_rwsem);
e406d1cf 2826
952aaa12
TH
2827 ret = cgroup_migrate_prepare_dst(to, &preloaded_csets);
2828 if (ret)
2829 goto out_err;
2830
2831 /*
2832 * Migrate tasks one-by-one until @form is empty. This fails iff
2833 * ->can_attach() fails.
2834 */
e406d1cf
TH
2835 do {
2836 css_task_iter_start(&from->dummy_css, &it);
2837 task = css_task_iter_next(&it);
2838 if (task)
2839 get_task_struct(task);
2840 css_task_iter_end(&it);
2841
2842 if (task) {
952aaa12 2843 ret = cgroup_migrate(to, task, false);
e406d1cf
TH
2844 put_task_struct(task);
2845 }
2846 } while (task && !ret);
952aaa12
TH
2847out_err:
2848 cgroup_migrate_finish(&preloaded_csets);
2849 mutex_unlock(&cgroup_mutex);
e406d1cf 2850 return ret;
8cc99345
TH
2851}
2852
bbcb81d0 2853/*
102a775e 2854 * Stuff for reading the 'tasks'/'procs' files.
bbcb81d0
PM
2855 *
2856 * Reading this file can return large amounts of data if a cgroup has
2857 * *lots* of attached tasks. So it may need several calls to read(),
2858 * but we cannot guarantee that the information we produce is correct
2859 * unless we produce it entirely atomically.
2860 *
bbcb81d0 2861 */
bbcb81d0 2862
24528255
LZ
2863/* which pidlist file are we talking about? */
2864enum cgroup_filetype {
2865 CGROUP_FILE_PROCS,
2866 CGROUP_FILE_TASKS,
2867};
2868
2869/*
2870 * A pidlist is a list of pids that virtually represents the contents of one
2871 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
2872 * a pair (one each for procs, tasks) for each pid namespace that's relevant
2873 * to the cgroup.
2874 */
2875struct cgroup_pidlist {
2876 /*
2877 * used to find which pidlist is wanted. doesn't change as long as
2878 * this particular list stays in the list.
2879 */
2880 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
2881 /* array of xids */
2882 pid_t *list;
2883 /* how many elements the above list has */
2884 int length;
24528255
LZ
2885 /* each of these stored in a list by its cgroup */
2886 struct list_head links;
2887 /* pointer to the cgroup we belong to, for list removal purposes */
2888 struct cgroup *owner;
b1a21367
TH
2889 /* for delayed destruction */
2890 struct delayed_work destroy_dwork;
24528255
LZ
2891};
2892
d1d9fd33
BB
2893/*
2894 * The following two functions "fix" the issue where there are more pids
2895 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
2896 * TODO: replace with a kernel-wide solution to this problem
2897 */
2898#define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
2899static void *pidlist_allocate(int count)
2900{
2901 if (PIDLIST_TOO_LARGE(count))
2902 return vmalloc(count * sizeof(pid_t));
2903 else
2904 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
2905}
b1a21367 2906
d1d9fd33
BB
2907static void pidlist_free(void *p)
2908{
2909 if (is_vmalloc_addr(p))
2910 vfree(p);
2911 else
2912 kfree(p);
2913}
d1d9fd33 2914
b1a21367
TH
2915/*
2916 * Used to destroy all pidlists lingering waiting for destroy timer. None
2917 * should be left afterwards.
2918 */
2919static void cgroup_pidlist_destroy_all(struct cgroup *cgrp)
2920{
2921 struct cgroup_pidlist *l, *tmp_l;
2922
2923 mutex_lock(&cgrp->pidlist_mutex);
2924 list_for_each_entry_safe(l, tmp_l, &cgrp->pidlists, links)
2925 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork, 0);
2926 mutex_unlock(&cgrp->pidlist_mutex);
2927
2928 flush_workqueue(cgroup_pidlist_destroy_wq);
2929 BUG_ON(!list_empty(&cgrp->pidlists));
2930}
2931
2932static void cgroup_pidlist_destroy_work_fn(struct work_struct *work)
2933{
2934 struct delayed_work *dwork = to_delayed_work(work);
2935 struct cgroup_pidlist *l = container_of(dwork, struct cgroup_pidlist,
2936 destroy_dwork);
2937 struct cgroup_pidlist *tofree = NULL;
2938
2939 mutex_lock(&l->owner->pidlist_mutex);
b1a21367
TH
2940
2941 /*
04502365
TH
2942 * Destroy iff we didn't get queued again. The state won't change
2943 * as destroy_dwork can only be queued while locked.
b1a21367 2944 */
04502365 2945 if (!delayed_work_pending(dwork)) {
b1a21367
TH
2946 list_del(&l->links);
2947 pidlist_free(l->list);
2948 put_pid_ns(l->key.ns);
2949 tofree = l;
2950 }
2951
b1a21367
TH
2952 mutex_unlock(&l->owner->pidlist_mutex);
2953 kfree(tofree);
2954}
2955
bbcb81d0 2956/*
102a775e 2957 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
6ee211ad 2958 * Returns the number of unique elements.
bbcb81d0 2959 */
6ee211ad 2960static int pidlist_uniq(pid_t *list, int length)
bbcb81d0 2961{
102a775e 2962 int src, dest = 1;
102a775e
BB
2963
2964 /*
2965 * we presume the 0th element is unique, so i starts at 1. trivial
2966 * edge cases first; no work needs to be done for either
2967 */
2968 if (length == 0 || length == 1)
2969 return length;
2970 /* src and dest walk down the list; dest counts unique elements */
2971 for (src = 1; src < length; src++) {
2972 /* find next unique element */
2973 while (list[src] == list[src-1]) {
2974 src++;
2975 if (src == length)
2976 goto after;
2977 }
2978 /* dest always points to where the next unique element goes */
2979 list[dest] = list[src];
2980 dest++;
2981 }
2982after:
102a775e
BB
2983 return dest;
2984}
2985
afb2bc14
TH
2986/*
2987 * The two pid files - task and cgroup.procs - guaranteed that the result
2988 * is sorted, which forced this whole pidlist fiasco. As pid order is
2989 * different per namespace, each namespace needs differently sorted list,
2990 * making it impossible to use, for example, single rbtree of member tasks
2991 * sorted by task pointer. As pidlists can be fairly large, allocating one
2992 * per open file is dangerous, so cgroup had to implement shared pool of
2993 * pidlists keyed by cgroup and namespace.
2994 *
2995 * All this extra complexity was caused by the original implementation
2996 * committing to an entirely unnecessary property. In the long term, we
2997 * want to do away with it. Explicitly scramble sort order if
2998 * sane_behavior so that no such expectation exists in the new interface.
2999 *
3000 * Scrambling is done by swapping every two consecutive bits, which is
3001 * non-identity one-to-one mapping which disturbs sort order sufficiently.
3002 */
3003static pid_t pid_fry(pid_t pid)
3004{
3005 unsigned a = pid & 0x55555555;
3006 unsigned b = pid & 0xAAAAAAAA;
3007
3008 return (a << 1) | (b >> 1);
3009}
3010
3011static pid_t cgroup_pid_fry(struct cgroup *cgrp, pid_t pid)
3012{
3013 if (cgroup_sane_behavior(cgrp))
3014 return pid_fry(pid);
3015 else
3016 return pid;
3017}
3018
102a775e
BB
3019static int cmppid(const void *a, const void *b)
3020{
3021 return *(pid_t *)a - *(pid_t *)b;
3022}
3023
afb2bc14
TH
3024static int fried_cmppid(const void *a, const void *b)
3025{
3026 return pid_fry(*(pid_t *)a) - pid_fry(*(pid_t *)b);
3027}
3028
e6b81710
TH
3029static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3030 enum cgroup_filetype type)
3031{
3032 struct cgroup_pidlist *l;
3033 /* don't need task_nsproxy() if we're looking at ourself */
3034 struct pid_namespace *ns = task_active_pid_ns(current);
3035
3036 lockdep_assert_held(&cgrp->pidlist_mutex);
3037
3038 list_for_each_entry(l, &cgrp->pidlists, links)
3039 if (l->key.type == type && l->key.ns == ns)
3040 return l;
3041 return NULL;
3042}
3043
72a8cb30
BB
3044/*
3045 * find the appropriate pidlist for our purpose (given procs vs tasks)
3046 * returns with the lock on that pidlist already held, and takes care
3047 * of the use count, or returns NULL with no locks held if we're out of
3048 * memory.
3049 */
e6b81710
TH
3050static struct cgroup_pidlist *cgroup_pidlist_find_create(struct cgroup *cgrp,
3051 enum cgroup_filetype type)
72a8cb30
BB
3052{
3053 struct cgroup_pidlist *l;
b70cc5fd 3054
e6b81710
TH
3055 lockdep_assert_held(&cgrp->pidlist_mutex);
3056
3057 l = cgroup_pidlist_find(cgrp, type);
3058 if (l)
3059 return l;
3060
72a8cb30 3061 /* entry not found; create a new one */
f4f4be2b 3062 l = kzalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
e6b81710 3063 if (!l)
72a8cb30 3064 return l;
e6b81710 3065
b1a21367 3066 INIT_DELAYED_WORK(&l->destroy_dwork, cgroup_pidlist_destroy_work_fn);
72a8cb30 3067 l->key.type = type;
e6b81710
TH
3068 /* don't need task_nsproxy() if we're looking at ourself */
3069 l->key.ns = get_pid_ns(task_active_pid_ns(current));
72a8cb30
BB
3070 l->owner = cgrp;
3071 list_add(&l->links, &cgrp->pidlists);
72a8cb30
BB
3072 return l;
3073}
3074
102a775e
BB
3075/*
3076 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3077 */
72a8cb30
BB
3078static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3079 struct cgroup_pidlist **lp)
102a775e
BB
3080{
3081 pid_t *array;
3082 int length;
3083 int pid, n = 0; /* used for populating the array */
72ec7029 3084 struct css_task_iter it;
817929ec 3085 struct task_struct *tsk;
102a775e
BB
3086 struct cgroup_pidlist *l;
3087
4bac00d1
TH
3088 lockdep_assert_held(&cgrp->pidlist_mutex);
3089
102a775e
BB
3090 /*
3091 * If cgroup gets more users after we read count, we won't have
3092 * enough space - tough. This race is indistinguishable to the
3093 * caller from the case that the additional cgroup users didn't
3094 * show up until sometime later on.
3095 */
3096 length = cgroup_task_count(cgrp);
d1d9fd33 3097 array = pidlist_allocate(length);
102a775e
BB
3098 if (!array)
3099 return -ENOMEM;
3100 /* now, populate the array */
72ec7029
TH
3101 css_task_iter_start(&cgrp->dummy_css, &it);
3102 while ((tsk = css_task_iter_next(&it))) {
102a775e 3103 if (unlikely(n == length))
817929ec 3104 break;
102a775e 3105 /* get tgid or pid for procs or tasks file respectively */
72a8cb30
BB
3106 if (type == CGROUP_FILE_PROCS)
3107 pid = task_tgid_vnr(tsk);
3108 else
3109 pid = task_pid_vnr(tsk);
102a775e
BB
3110 if (pid > 0) /* make sure to only use valid results */
3111 array[n++] = pid;
817929ec 3112 }
72ec7029 3113 css_task_iter_end(&it);
102a775e
BB
3114 length = n;
3115 /* now sort & (if procs) strip out duplicates */
afb2bc14
TH
3116 if (cgroup_sane_behavior(cgrp))
3117 sort(array, length, sizeof(pid_t), fried_cmppid, NULL);
3118 else
3119 sort(array, length, sizeof(pid_t), cmppid, NULL);
72a8cb30 3120 if (type == CGROUP_FILE_PROCS)
6ee211ad 3121 length = pidlist_uniq(array, length);
e6b81710 3122
e6b81710 3123 l = cgroup_pidlist_find_create(cgrp, type);
72a8cb30 3124 if (!l) {
e6b81710 3125 mutex_unlock(&cgrp->pidlist_mutex);
d1d9fd33 3126 pidlist_free(array);
72a8cb30 3127 return -ENOMEM;
102a775e 3128 }
e6b81710
TH
3129
3130 /* store array, freeing old if necessary */
d1d9fd33 3131 pidlist_free(l->list);
102a775e
BB
3132 l->list = array;
3133 l->length = length;
72a8cb30 3134 *lp = l;
102a775e 3135 return 0;
bbcb81d0
PM
3136}
3137
846c7bb0 3138/**
a043e3b2 3139 * cgroupstats_build - build and fill cgroupstats
846c7bb0
BS
3140 * @stats: cgroupstats to fill information into
3141 * @dentry: A dentry entry belonging to the cgroup for which stats have
3142 * been requested.
a043e3b2
LZ
3143 *
3144 * Build and fill cgroupstats so that taskstats can export it to user
3145 * space.
846c7bb0
BS
3146 */
3147int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3148{
2bd59d48 3149 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
bd89aabc 3150 struct cgroup *cgrp;
72ec7029 3151 struct css_task_iter it;
846c7bb0 3152 struct task_struct *tsk;
33d283be 3153
2bd59d48
TH
3154 /* it should be kernfs_node belonging to cgroupfs and is a directory */
3155 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
3156 kernfs_type(kn) != KERNFS_DIR)
3157 return -EINVAL;
3158
bad34660
LZ
3159 mutex_lock(&cgroup_mutex);
3160
846c7bb0 3161 /*
2bd59d48
TH
3162 * We aren't being called from kernfs and there's no guarantee on
3163 * @kn->priv's validity. For this and css_tryget_from_dir(),
3164 * @kn->priv is RCU safe. Let's do the RCU dancing.
846c7bb0 3165 */
2bd59d48
TH
3166 rcu_read_lock();
3167 cgrp = rcu_dereference(kn->priv);
bad34660 3168 if (!cgrp || cgroup_is_dead(cgrp)) {
2bd59d48 3169 rcu_read_unlock();
bad34660 3170 mutex_unlock(&cgroup_mutex);
2bd59d48
TH
3171 return -ENOENT;
3172 }
bad34660 3173 rcu_read_unlock();
846c7bb0 3174
72ec7029
TH
3175 css_task_iter_start(&cgrp->dummy_css, &it);
3176 while ((tsk = css_task_iter_next(&it))) {
846c7bb0
BS
3177 switch (tsk->state) {
3178 case TASK_RUNNING:
3179 stats->nr_running++;
3180 break;
3181 case TASK_INTERRUPTIBLE:
3182 stats->nr_sleeping++;
3183 break;
3184 case TASK_UNINTERRUPTIBLE:
3185 stats->nr_uninterruptible++;
3186 break;
3187 case TASK_STOPPED:
3188 stats->nr_stopped++;
3189 break;
3190 default:
3191 if (delayacct_is_task_waiting_on_io(tsk))
3192 stats->nr_io_wait++;
3193 break;
3194 }
3195 }
72ec7029 3196 css_task_iter_end(&it);
846c7bb0 3197
bad34660 3198 mutex_unlock(&cgroup_mutex);
2bd59d48 3199 return 0;
846c7bb0
BS
3200}
3201
8f3ff208 3202
bbcb81d0 3203/*
102a775e 3204 * seq_file methods for the tasks/procs files. The seq_file position is the
cc31edce 3205 * next pid to display; the seq_file iterator is a pointer to the pid
102a775e 3206 * in the cgroup->l->list array.
bbcb81d0 3207 */
cc31edce 3208
102a775e 3209static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
bbcb81d0 3210{
cc31edce
PM
3211 /*
3212 * Initially we receive a position value that corresponds to
3213 * one more than the last pid shown (or 0 on the first call or
3214 * after a seek to the start). Use a binary-search to find the
3215 * next pid to display, if any
3216 */
2bd59d48 3217 struct kernfs_open_file *of = s->private;
7da11279 3218 struct cgroup *cgrp = seq_css(s)->cgroup;
4bac00d1 3219 struct cgroup_pidlist *l;
7da11279 3220 enum cgroup_filetype type = seq_cft(s)->private;
cc31edce 3221 int index = 0, pid = *pos;
4bac00d1
TH
3222 int *iter, ret;
3223
3224 mutex_lock(&cgrp->pidlist_mutex);
3225
3226 /*
5d22444f 3227 * !NULL @of->priv indicates that this isn't the first start()
4bac00d1 3228 * after open. If the matching pidlist is around, we can use that.
5d22444f 3229 * Look for it. Note that @of->priv can't be used directly. It
4bac00d1
TH
3230 * could already have been destroyed.
3231 */
5d22444f
TH
3232 if (of->priv)
3233 of->priv = cgroup_pidlist_find(cgrp, type);
4bac00d1
TH
3234
3235 /*
3236 * Either this is the first start() after open or the matching
3237 * pidlist has been destroyed inbetween. Create a new one.
3238 */
5d22444f
TH
3239 if (!of->priv) {
3240 ret = pidlist_array_load(cgrp, type,
3241 (struct cgroup_pidlist **)&of->priv);
4bac00d1
TH
3242 if (ret)
3243 return ERR_PTR(ret);
3244 }
5d22444f 3245 l = of->priv;
cc31edce 3246
cc31edce 3247 if (pid) {
102a775e 3248 int end = l->length;
20777766 3249
cc31edce
PM
3250 while (index < end) {
3251 int mid = (index + end) / 2;
afb2bc14 3252 if (cgroup_pid_fry(cgrp, l->list[mid]) == pid) {
cc31edce
PM
3253 index = mid;
3254 break;
afb2bc14 3255 } else if (cgroup_pid_fry(cgrp, l->list[mid]) <= pid)
cc31edce
PM
3256 index = mid + 1;
3257 else
3258 end = mid;
3259 }
3260 }
3261 /* If we're off the end of the array, we're done */
102a775e 3262 if (index >= l->length)
cc31edce
PM
3263 return NULL;
3264 /* Update the abstract position to be the actual pid that we found */
102a775e 3265 iter = l->list + index;
afb2bc14 3266 *pos = cgroup_pid_fry(cgrp, *iter);
cc31edce
PM
3267 return iter;
3268}
3269
102a775e 3270static void cgroup_pidlist_stop(struct seq_file *s, void *v)
cc31edce 3271{
2bd59d48 3272 struct kernfs_open_file *of = s->private;
5d22444f 3273 struct cgroup_pidlist *l = of->priv;
62236858 3274
5d22444f
TH
3275 if (l)
3276 mod_delayed_work(cgroup_pidlist_destroy_wq, &l->destroy_dwork,
04502365 3277 CGROUP_PIDLIST_DESTROY_DELAY);
7da11279 3278 mutex_unlock(&seq_css(s)->cgroup->pidlist_mutex);
cc31edce
PM
3279}
3280
102a775e 3281static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
cc31edce 3282{
2bd59d48 3283 struct kernfs_open_file *of = s->private;
5d22444f 3284 struct cgroup_pidlist *l = of->priv;
102a775e
BB
3285 pid_t *p = v;
3286 pid_t *end = l->list + l->length;
cc31edce
PM
3287 /*
3288 * Advance to the next pid in the array. If this goes off the
3289 * end, we're done
3290 */
3291 p++;
3292 if (p >= end) {
3293 return NULL;
3294 } else {
7da11279 3295 *pos = cgroup_pid_fry(seq_css(s)->cgroup, *p);
cc31edce
PM
3296 return p;
3297 }
3298}
3299
102a775e 3300static int cgroup_pidlist_show(struct seq_file *s, void *v)
cc31edce
PM
3301{
3302 return seq_printf(s, "%d\n", *(int *)v);
3303}
bbcb81d0 3304
102a775e
BB
3305/*
3306 * seq_operations functions for iterating on pidlists through seq_file -
3307 * independent of whether it's tasks or procs
3308 */
3309static const struct seq_operations cgroup_pidlist_seq_operations = {
3310 .start = cgroup_pidlist_start,
3311 .stop = cgroup_pidlist_stop,
3312 .next = cgroup_pidlist_next,
3313 .show = cgroup_pidlist_show,
cc31edce
PM
3314};
3315
182446d0
TH
3316static u64 cgroup_read_notify_on_release(struct cgroup_subsys_state *css,
3317 struct cftype *cft)
81a6a5cd 3318{
182446d0 3319 return notify_on_release(css->cgroup);
81a6a5cd
PM
3320}
3321
182446d0
TH
3322static int cgroup_write_notify_on_release(struct cgroup_subsys_state *css,
3323 struct cftype *cft, u64 val)
6379c106 3324{
182446d0 3325 clear_bit(CGRP_RELEASABLE, &css->cgroup->flags);
6379c106 3326 if (val)
182446d0 3327 set_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
6379c106 3328 else
182446d0 3329 clear_bit(CGRP_NOTIFY_ON_RELEASE, &css->cgroup->flags);
6379c106
PM
3330 return 0;
3331}
3332
182446d0
TH
3333static u64 cgroup_clone_children_read(struct cgroup_subsys_state *css,
3334 struct cftype *cft)
97978e6d 3335{
182446d0 3336 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
97978e6d
DL
3337}
3338
182446d0
TH
3339static int cgroup_clone_children_write(struct cgroup_subsys_state *css,
3340 struct cftype *cft, u64 val)
97978e6d
DL
3341{
3342 if (val)
182446d0 3343 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
97978e6d 3344 else
182446d0 3345 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &css->cgroup->flags);
97978e6d
DL
3346 return 0;
3347}
3348
d5c56ced 3349static struct cftype cgroup_base_files[] = {
81a6a5cd 3350 {
d5c56ced 3351 .name = "cgroup.procs",
6612f05b
TH
3352 .seq_start = cgroup_pidlist_start,
3353 .seq_next = cgroup_pidlist_next,
3354 .seq_stop = cgroup_pidlist_stop,
3355 .seq_show = cgroup_pidlist_show,
5d22444f 3356 .private = CGROUP_FILE_PROCS,
74a1166d 3357 .write_u64 = cgroup_procs_write,
74a1166d 3358 .mode = S_IRUGO | S_IWUSR,
102a775e 3359 },
97978e6d
DL
3360 {
3361 .name = "cgroup.clone_children",
873fe09e 3362 .flags = CFTYPE_INSANE,
97978e6d
DL
3363 .read_u64 = cgroup_clone_children_read,
3364 .write_u64 = cgroup_clone_children_write,
3365 },
873fe09e
TH
3366 {
3367 .name = "cgroup.sane_behavior",
3368 .flags = CFTYPE_ONLY_ON_ROOT,
2da8ca82 3369 .seq_show = cgroup_sane_behavior_show,
873fe09e 3370 },
d5c56ced
TH
3371
3372 /*
3373 * Historical crazy stuff. These don't have "cgroup." prefix and
3374 * don't exist if sane_behavior. If you're depending on these, be
3375 * prepared to be burned.
3376 */
3377 {
3378 .name = "tasks",
3379 .flags = CFTYPE_INSANE, /* use "procs" instead */
6612f05b
TH
3380 .seq_start = cgroup_pidlist_start,
3381 .seq_next = cgroup_pidlist_next,
3382 .seq_stop = cgroup_pidlist_stop,
3383 .seq_show = cgroup_pidlist_show,
5d22444f 3384 .private = CGROUP_FILE_TASKS,
d5c56ced 3385 .write_u64 = cgroup_tasks_write,
d5c56ced
TH
3386 .mode = S_IRUGO | S_IWUSR,
3387 },
3388 {
3389 .name = "notify_on_release",
3390 .flags = CFTYPE_INSANE,
3391 .read_u64 = cgroup_read_notify_on_release,
3392 .write_u64 = cgroup_write_notify_on_release,
3393 },
6e6ff25b
TH
3394 {
3395 .name = "release_agent",
cc5943a7 3396 .flags = CFTYPE_INSANE | CFTYPE_ONLY_ON_ROOT,
2da8ca82 3397 .seq_show = cgroup_release_agent_show,
6e6ff25b 3398 .write_string = cgroup_release_agent_write,
5f469907 3399 .max_write_len = PATH_MAX - 1,
6e6ff25b 3400 },
db0416b6 3401 { } /* terminate */
bbcb81d0
PM
3402};
3403
13af07df 3404/**
628f7cd4 3405 * cgroup_populate_dir - create subsys files in a cgroup directory
13af07df 3406 * @cgrp: target cgroup
13af07df 3407 * @subsys_mask: mask of the subsystem ids whose files should be added
bee55099
TH
3408 *
3409 * On failure, no file is added.
13af07df 3410 */
628f7cd4 3411static int cgroup_populate_dir(struct cgroup *cgrp, unsigned long subsys_mask)
ddbcc7e8 3412{
ddbcc7e8 3413 struct cgroup_subsys *ss;
b420ba7d 3414 int i, ret = 0;
bbcb81d0 3415
8e3f6541 3416 /* process cftsets of each subsystem */
b420ba7d 3417 for_each_subsys(ss, i) {
0adb0704 3418 struct cftype *cfts;
b420ba7d
TH
3419
3420 if (!test_bit(i, &subsys_mask))
13af07df 3421 continue;
8e3f6541 3422
0adb0704
TH
3423 list_for_each_entry(cfts, &ss->cfts, node) {
3424 ret = cgroup_addrm_files(cgrp, cfts, true);
bee55099
TH
3425 if (ret < 0)
3426 goto err;
3427 }
ddbcc7e8 3428 }
ddbcc7e8 3429 return 0;
bee55099
TH
3430err:
3431 cgroup_clear_dir(cgrp, subsys_mask);
3432 return ret;
ddbcc7e8
PM
3433}
3434
0c21ead1
TH
3435/*
3436 * css destruction is four-stage process.
3437 *
3438 * 1. Destruction starts. Killing of the percpu_ref is initiated.
3439 * Implemented in kill_css().
3440 *
3441 * 2. When the percpu_ref is confirmed to be visible as killed on all CPUs
3442 * and thus css_tryget() is guaranteed to fail, the css can be offlined
3443 * by invoking offline_css(). After offlining, the base ref is put.
3444 * Implemented in css_killed_work_fn().
3445 *
3446 * 3. When the percpu_ref reaches zero, the only possible remaining
3447 * accessors are inside RCU read sections. css_release() schedules the
3448 * RCU callback.
3449 *
3450 * 4. After the grace period, the css can be freed. Implemented in
3451 * css_free_work_fn().
3452 *
3453 * It is actually hairier because both step 2 and 4 require process context
3454 * and thus involve punting to css->destroy_work adding two additional
3455 * steps to the already complex sequence.
3456 */
35ef10da 3457static void css_free_work_fn(struct work_struct *work)
48ddbe19
TH
3458{
3459 struct cgroup_subsys_state *css =
35ef10da 3460 container_of(work, struct cgroup_subsys_state, destroy_work);
0c21ead1 3461 struct cgroup *cgrp = css->cgroup;
48ddbe19 3462
0ae78e0b
TH
3463 if (css->parent)
3464 css_put(css->parent);
3465
0c21ead1 3466 css->ss->css_free(css);
2bd59d48 3467 cgroup_put(cgrp);
48ddbe19
TH
3468}
3469
0c21ead1 3470static void css_free_rcu_fn(struct rcu_head *rcu_head)
d3daf28d
TH
3471{
3472 struct cgroup_subsys_state *css =
0c21ead1 3473 container_of(rcu_head, struct cgroup_subsys_state, rcu_head);
d3daf28d 3474
35ef10da 3475 INIT_WORK(&css->destroy_work, css_free_work_fn);
e5fca243 3476 queue_work(cgroup_destroy_wq, &css->destroy_work);
48ddbe19
TH
3477}
3478
d3daf28d
TH
3479static void css_release(struct percpu_ref *ref)
3480{
3481 struct cgroup_subsys_state *css =
3482 container_of(ref, struct cgroup_subsys_state, refcnt);
3483
aec25020 3484 rcu_assign_pointer(css->cgroup->subsys[css->ss->id], NULL);
0c21ead1 3485 call_rcu(&css->rcu_head, css_free_rcu_fn);
d3daf28d
TH
3486}
3487
623f926b
TH
3488static void init_css(struct cgroup_subsys_state *css, struct cgroup_subsys *ss,
3489 struct cgroup *cgrp)
ddbcc7e8 3490{
bd89aabc 3491 css->cgroup = cgrp;
72c97e54 3492 css->ss = ss;
ddbcc7e8 3493 css->flags = 0;
0ae78e0b
TH
3494
3495 if (cgrp->parent)
ca8bdcaf 3496 css->parent = cgroup_css(cgrp->parent, ss);
0ae78e0b 3497 else
38b53aba 3498 css->flags |= CSS_ROOT;
48ddbe19 3499
ca8bdcaf 3500 BUG_ON(cgroup_css(cgrp, ss));
ddbcc7e8
PM
3501}
3502
2a4ac633 3503/* invoke ->css_online() on a new CSS and mark it online if successful */
623f926b 3504static int online_css(struct cgroup_subsys_state *css)
a31f2d3f 3505{
623f926b 3506 struct cgroup_subsys *ss = css->ss;
b1929db4
TH
3507 int ret = 0;
3508
ace2bee8 3509 lockdep_assert_held(&cgroup_tree_mutex);
a31f2d3f
TH
3510 lockdep_assert_held(&cgroup_mutex);
3511
92fb9748 3512 if (ss->css_online)
eb95419b 3513 ret = ss->css_online(css);
ae7f164a 3514 if (!ret) {
eb95419b 3515 css->flags |= CSS_ONLINE;
f20104de 3516 css->cgroup->nr_css++;
aec25020 3517 rcu_assign_pointer(css->cgroup->subsys[ss->id], css);
ae7f164a 3518 }
b1929db4 3519 return ret;
a31f2d3f
TH
3520}
3521
2a4ac633 3522/* if the CSS is online, invoke ->css_offline() on it and mark it offline */
623f926b 3523static void offline_css(struct cgroup_subsys_state *css)
a31f2d3f 3524{
623f926b 3525 struct cgroup_subsys *ss = css->ss;
a31f2d3f 3526
ace2bee8 3527 lockdep_assert_held(&cgroup_tree_mutex);
a31f2d3f
TH
3528 lockdep_assert_held(&cgroup_mutex);
3529
3530 if (!(css->flags & CSS_ONLINE))
3531 return;
3532
d7eeac19 3533 if (ss->css_offline)
eb95419b 3534 ss->css_offline(css);
a31f2d3f 3535
eb95419b 3536 css->flags &= ~CSS_ONLINE;
09a503ea 3537 css->cgroup->nr_css--;
aec25020 3538 RCU_INIT_POINTER(css->cgroup->subsys[ss->id], css);
a31f2d3f
TH
3539}
3540
c81c925a
TH
3541/**
3542 * create_css - create a cgroup_subsys_state
3543 * @cgrp: the cgroup new css will be associated with
3544 * @ss: the subsys of new css
3545 *
3546 * Create a new css associated with @cgrp - @ss pair. On success, the new
3547 * css is online and installed in @cgrp with all interface files created.
3548 * Returns 0 on success, -errno on failure.
3549 */
3550static int create_css(struct cgroup *cgrp, struct cgroup_subsys *ss)
3551{
3552 struct cgroup *parent = cgrp->parent;
3553 struct cgroup_subsys_state *css;
3554 int err;
3555
c81c925a
TH
3556 lockdep_assert_held(&cgroup_mutex);
3557
3558 css = ss->css_alloc(cgroup_css(parent, ss));
3559 if (IS_ERR(css))
3560 return PTR_ERR(css);
3561
3562 err = percpu_ref_init(&css->refcnt, css_release);
3563 if (err)
3564 goto err_free;
3565
3566 init_css(css, ss, cgrp);
3567
aec25020 3568 err = cgroup_populate_dir(cgrp, 1 << ss->id);
c81c925a
TH
3569 if (err)
3570 goto err_free;
3571
3572 err = online_css(css);
3573 if (err)
3574 goto err_free;
3575
59f5296b 3576 cgroup_get(cgrp);
c81c925a
TH
3577 css_get(css->parent);
3578
3579 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
3580 parent->parent) {
3581 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",
3582 current->comm, current->pid, ss->name);
3583 if (!strcmp(ss->name, "memory"))
3584 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
3585 ss->warned_broken_hierarchy = true;
3586 }
3587
3588 return 0;
3589
3590err_free:
3591 percpu_ref_cancel_init(&css->refcnt);
3592 ss->css_free(css);
3593 return err;
3594}
3595
2bd59d48 3596/**
a043e3b2
LZ
3597 * cgroup_create - create a cgroup
3598 * @parent: cgroup that will be parent of the new cgroup
e61734c5 3599 * @name: name of the new cgroup
2bd59d48 3600 * @mode: mode to set on new cgroup
ddbcc7e8 3601 */
e61734c5 3602static long cgroup_create(struct cgroup *parent, const char *name,
2bd59d48 3603 umode_t mode)
ddbcc7e8 3604{
bd89aabc 3605 struct cgroup *cgrp;
ddbcc7e8 3606 struct cgroupfs_root *root = parent->root;
b58c8998 3607 int ssid, err;
ddbcc7e8 3608 struct cgroup_subsys *ss;
2bd59d48 3609 struct kernfs_node *kn;
ddbcc7e8 3610
0a950f65 3611 /* allocate the cgroup and its ID, 0 is reserved for the root */
bd89aabc
PM
3612 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
3613 if (!cgrp)
ddbcc7e8
PM
3614 return -ENOMEM;
3615
ace2bee8
TH
3616 mutex_lock(&cgroup_tree_mutex);
3617
976c06bc
TH
3618 /*
3619 * Only live parents can have children. Note that the liveliness
3620 * check isn't strictly necessary because cgroup_mkdir() and
3621 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
3622 * anyway so that locking is contained inside cgroup proper and we
3623 * don't get nasty surprises if we ever grow another caller.
3624 */
3625 if (!cgroup_lock_live_group(parent)) {
3626 err = -ENODEV;
ace2bee8 3627 goto err_unlock_tree;
0ab02ca8
LZ
3628 }
3629
3630 /*
3631 * Temporarily set the pointer to NULL, so idr_find() won't return
3632 * a half-baked cgroup.
3633 */
3634 cgrp->id = idr_alloc(&root->cgroup_idr, NULL, 1, 0, GFP_KERNEL);
3635 if (cgrp->id < 0) {
3636 err = -ENOMEM;
3637 goto err_unlock;
976c06bc
TH
3638 }
3639
cc31edce 3640 init_cgroup_housekeeping(cgrp);
ddbcc7e8 3641
bd89aabc 3642 cgrp->parent = parent;
0ae78e0b 3643 cgrp->dummy_css.parent = &parent->dummy_css;
bd89aabc 3644 cgrp->root = parent->root;
ddbcc7e8 3645
b6abdb0e
LZ
3646 if (notify_on_release(parent))
3647 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3648
2260e7fc
TH
3649 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
3650 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
97978e6d 3651
2bd59d48 3652 /* create the directory */
e61734c5 3653 kn = kernfs_create_dir(parent->kn, name, mode, cgrp);
2bd59d48
TH
3654 if (IS_ERR(kn)) {
3655 err = PTR_ERR(kn);
0ab02ca8 3656 goto err_free_id;
2bd59d48
TH
3657 }
3658 cgrp->kn = kn;
ddbcc7e8 3659
6f30558f
TH
3660 /*
3661 * This extra ref will be put in cgroup_free_fn() and guarantees
3662 * that @cgrp->kn is always accessible.
3663 */
3664 kernfs_get(kn);
3665
00356bd5 3666 cgrp->serial_nr = cgroup_serial_nr_next++;
53fa5261 3667
4e139afc 3668 /* allocation complete, commit to creation */
4e139afc 3669 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
3c9c825b 3670 atomic_inc(&root->nr_cgrps);
59f5296b 3671 cgroup_get(parent);
415cf07a 3672
0d80255e
TH
3673 /*
3674 * @cgrp is now fully operational. If something fails after this
3675 * point, it'll be released via the normal destruction path.
3676 */
4e96ee8e
LZ
3677 idr_replace(&root->cgroup_idr, cgrp, cgrp->id);
3678
2bb566cb 3679 err = cgroup_addrm_files(cgrp, cgroup_base_files, true);
628f7cd4
TH
3680 if (err)
3681 goto err_destroy;
3682
9d403e99 3683 /* let's create and online css's */
b85d2040
TH
3684 for_each_subsys(ss, ssid) {
3685 if (root->subsys_mask & (1 << ssid)) {
3686 err = create_css(cgrp, ss);
3687 if (err)
3688 goto err_destroy;
3689 }
a8638030 3690 }
ddbcc7e8 3691
2bd59d48
TH
3692 kernfs_activate(kn);
3693
ddbcc7e8 3694 mutex_unlock(&cgroup_mutex);
ace2bee8 3695 mutex_unlock(&cgroup_tree_mutex);
ddbcc7e8
PM
3696
3697 return 0;
3698
0a950f65 3699err_free_id:
4e96ee8e 3700 idr_remove(&root->cgroup_idr, cgrp->id);
0ab02ca8
LZ
3701err_unlock:
3702 mutex_unlock(&cgroup_mutex);
ace2bee8
TH
3703err_unlock_tree:
3704 mutex_unlock(&cgroup_tree_mutex);
bd89aabc 3705 kfree(cgrp);
ddbcc7e8 3706 return err;
4b8b47eb
TH
3707
3708err_destroy:
3709 cgroup_destroy_locked(cgrp);
3710 mutex_unlock(&cgroup_mutex);
ace2bee8 3711 mutex_unlock(&cgroup_tree_mutex);
4b8b47eb 3712 return err;
ddbcc7e8
PM
3713}
3714
2bd59d48
TH
3715static int cgroup_mkdir(struct kernfs_node *parent_kn, const char *name,
3716 umode_t mode)
ddbcc7e8 3717{
2bd59d48 3718 struct cgroup *parent = parent_kn->priv;
ddbcc7e8 3719
2bd59d48 3720 return cgroup_create(parent, name, mode);
ddbcc7e8
PM
3721}
3722
223dbc38
TH
3723/*
3724 * This is called when the refcnt of a css is confirmed to be killed.
3725 * css_tryget() is now guaranteed to fail.
3726 */
3727static void css_killed_work_fn(struct work_struct *work)
d3daf28d 3728{
223dbc38
TH
3729 struct cgroup_subsys_state *css =
3730 container_of(work, struct cgroup_subsys_state, destroy_work);
3731 struct cgroup *cgrp = css->cgroup;
d3daf28d 3732
ace2bee8 3733 mutex_lock(&cgroup_tree_mutex);
f20104de
TH
3734 mutex_lock(&cgroup_mutex);
3735
09a503ea
TH
3736 /*
3737 * css_tryget() is guaranteed to fail now. Tell subsystems to
3738 * initate destruction.
3739 */
3740 offline_css(css);
3741
f20104de
TH
3742 /*
3743 * If @cgrp is marked dead, it's waiting for refs of all css's to
3744 * be disabled before proceeding to the second phase of cgroup
3745 * destruction. If we are the last one, kick it off.
3746 */
09a503ea 3747 if (!cgrp->nr_css && cgroup_is_dead(cgrp))
f20104de
TH
3748 cgroup_destroy_css_killed(cgrp);
3749
3750 mutex_unlock(&cgroup_mutex);
ace2bee8 3751 mutex_unlock(&cgroup_tree_mutex);
09a503ea
TH
3752
3753 /*
3754 * Put the css refs from kill_css(). Each css holds an extra
3755 * reference to the cgroup's dentry and cgroup removal proceeds
3756 * regardless of css refs. On the last put of each css, whenever
3757 * that may be, the extra dentry ref is put so that dentry
3758 * destruction happens only after all css's are released.
3759 */
3760 css_put(css);
d3daf28d
TH
3761}
3762
223dbc38
TH
3763/* css kill confirmation processing requires process context, bounce */
3764static void css_killed_ref_fn(struct percpu_ref *ref)
d3daf28d
TH
3765{
3766 struct cgroup_subsys_state *css =
3767 container_of(ref, struct cgroup_subsys_state, refcnt);
3768
223dbc38 3769 INIT_WORK(&css->destroy_work, css_killed_work_fn);
e5fca243 3770 queue_work(cgroup_destroy_wq, &css->destroy_work);
d3daf28d
TH
3771}
3772
edae0c33
TH
3773/**
3774 * kill_css - destroy a css
3775 * @css: css to destroy
3776 *
3c14f8b4
TH
3777 * This function initiates destruction of @css by removing cgroup interface
3778 * files and putting its base reference. ->css_offline() will be invoked
3779 * asynchronously once css_tryget() is guaranteed to fail and when the
3780 * reference count reaches zero, @css will be released.
edae0c33
TH
3781 */
3782static void kill_css(struct cgroup_subsys_state *css)
3783{
2bd59d48
TH
3784 /*
3785 * This must happen before css is disassociated with its cgroup.
3786 * See seq_css() for details.
3787 */
aec25020 3788 cgroup_clear_dir(css->cgroup, 1 << css->ss->id);
3c14f8b4 3789
edae0c33
TH
3790 /*
3791 * Killing would put the base ref, but we need to keep it alive
3792 * until after ->css_offline().
3793 */
3794 css_get(css);
3795
3796 /*
3797 * cgroup core guarantees that, by the time ->css_offline() is
3798 * invoked, no new css reference will be given out via
3799 * css_tryget(). We can't simply call percpu_ref_kill() and
3800 * proceed to offlining css's because percpu_ref_kill() doesn't
3801 * guarantee that the ref is seen as killed on all CPUs on return.
3802 *
3803 * Use percpu_ref_kill_and_confirm() to get notifications as each
3804 * css is confirmed to be seen as killed on all CPUs.
3805 */
3806 percpu_ref_kill_and_confirm(&css->refcnt, css_killed_ref_fn);
d3daf28d
TH
3807}
3808
3809/**
3810 * cgroup_destroy_locked - the first stage of cgroup destruction
3811 * @cgrp: cgroup to be destroyed
3812 *
3813 * css's make use of percpu refcnts whose killing latency shouldn't be
3814 * exposed to userland and are RCU protected. Also, cgroup core needs to
3815 * guarantee that css_tryget() won't succeed by the time ->css_offline() is
3816 * invoked. To satisfy all the requirements, destruction is implemented in
3817 * the following two steps.
3818 *
3819 * s1. Verify @cgrp can be destroyed and mark it dying. Remove all
3820 * userland visible parts and start killing the percpu refcnts of
3821 * css's. Set up so that the next stage will be kicked off once all
3822 * the percpu refcnts are confirmed to be killed.
3823 *
3824 * s2. Invoke ->css_offline(), mark the cgroup dead and proceed with the
3825 * rest of destruction. Once all cgroup references are gone, the
3826 * cgroup is RCU-freed.
3827 *
3828 * This function implements s1. After this step, @cgrp is gone as far as
3829 * the userland is concerned and a new cgroup with the same name may be
3830 * created. As cgroup doesn't care about the names internally, this
3831 * doesn't cause any problem.
3832 */
42809dd4
TH
3833static int cgroup_destroy_locked(struct cgroup *cgrp)
3834 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
ddbcc7e8 3835{
bb78a92f 3836 struct cgroup *child;
2bd59d48 3837 struct cgroup_subsys_state *css;
ddd69148 3838 bool empty;
1c6727af 3839 int ssid;
ddbcc7e8 3840
ace2bee8 3841 lockdep_assert_held(&cgroup_tree_mutex);
42809dd4
TH
3842 lockdep_assert_held(&cgroup_mutex);
3843
ddd69148 3844 /*
96d365e0 3845 * css_set_rwsem synchronizes access to ->cset_links and prevents
89c5509b 3846 * @cgrp from being removed while put_css_set() is in progress.
ddd69148 3847 */
96d365e0 3848 down_read(&css_set_rwsem);
bb78a92f 3849 empty = list_empty(&cgrp->cset_links);
96d365e0 3850 up_read(&css_set_rwsem);
ddd69148 3851 if (!empty)
ddbcc7e8 3852 return -EBUSY;
a043e3b2 3853
bb78a92f
HD
3854 /*
3855 * Make sure there's no live children. We can't test ->children
3856 * emptiness as dead children linger on it while being destroyed;
3857 * otherwise, "rmdir parent/child parent" may fail with -EBUSY.
3858 */
3859 empty = true;
3860 rcu_read_lock();
3861 list_for_each_entry_rcu(child, &cgrp->children, sibling) {
3862 empty = cgroup_is_dead(child);
3863 if (!empty)
3864 break;
3865 }
3866 rcu_read_unlock();
3867 if (!empty)
3868 return -EBUSY;
3869
5d77381f
TH
3870 /*
3871 * Mark @cgrp dead. This prevents further task migration and child
3872 * creation by disabling cgroup_lock_live_group(). Note that
3873 * CGRP_DEAD assertion is depended upon by css_next_child() to
3874 * resume iteration after dropping RCU read lock. See
3875 * css_next_child() for details.
3876 */
3877 set_bit(CGRP_DEAD, &cgrp->flags);
3878
88703267 3879 /*
edae0c33
TH
3880 * Initiate massacre of all css's. cgroup_destroy_css_killed()
3881 * will be invoked to perform the rest of destruction once the
4ac06017
TH
3882 * percpu refs of all css's are confirmed to be killed. This
3883 * involves removing the subsystem's files, drop cgroup_mutex.
88703267 3884 */
4ac06017 3885 mutex_unlock(&cgroup_mutex);
1c6727af
TH
3886 for_each_css(css, ssid, cgrp)
3887 kill_css(css);
4ac06017 3888 mutex_lock(&cgroup_mutex);
455050d2 3889
455050d2
TH
3890 /* CGRP_DEAD is set, remove from ->release_list for the last time */
3891 raw_spin_lock(&release_list_lock);
3892 if (!list_empty(&cgrp->release_list))
3893 list_del_init(&cgrp->release_list);
3894 raw_spin_unlock(&release_list_lock);
3895
3896 /*
f20104de
TH
3897 * If @cgrp has css's attached, the second stage of cgroup
3898 * destruction is kicked off from css_killed_work_fn() after the
3899 * refs of all attached css's are killed. If @cgrp doesn't have
3900 * any css, we kick it off here.
3901 */
3902 if (!cgrp->nr_css)
3903 cgroup_destroy_css_killed(cgrp);
3904
2bd59d48
TH
3905 /* remove @cgrp directory along with the base files */
3906 mutex_unlock(&cgroup_mutex);
3907
455050d2 3908 /*
2bd59d48
TH
3909 * There are two control paths which try to determine cgroup from
3910 * dentry without going through kernfs - cgroupstats_build() and
3911 * css_tryget_from_dir(). Those are supported by RCU protecting
3912 * clearing of cgrp->kn->priv backpointer, which should happen
3913 * after all files under it have been removed.
455050d2 3914 */
6f30558f 3915 kernfs_remove(cgrp->kn); /* @cgrp has an extra ref on its kn */
2bd59d48 3916 RCU_INIT_POINTER(*(void __rcu __force **)&cgrp->kn->priv, NULL);
2bd59d48 3917
4ac06017 3918 mutex_lock(&cgroup_mutex);
455050d2 3919
ea15f8cc
TH
3920 return 0;
3921};
3922
d3daf28d 3923/**
f20104de 3924 * cgroup_destroy_css_killed - the second step of cgroup destruction
d3daf28d
TH
3925 * @work: cgroup->destroy_free_work
3926 *
3927 * This function is invoked from a work item for a cgroup which is being
09a503ea
TH
3928 * destroyed after all css's are offlined and performs the rest of
3929 * destruction. This is the second step of destruction described in the
3930 * comment above cgroup_destroy_locked().
d3daf28d 3931 */
f20104de 3932static void cgroup_destroy_css_killed(struct cgroup *cgrp)
ea15f8cc 3933{
ea15f8cc 3934 struct cgroup *parent = cgrp->parent;
ea15f8cc 3935
ace2bee8 3936 lockdep_assert_held(&cgroup_tree_mutex);
f20104de 3937 lockdep_assert_held(&cgroup_mutex);
ea15f8cc 3938
999cd8a4 3939 /* delete this cgroup from parent->children */
eb6fd504 3940 list_del_rcu(&cgrp->sibling);
ed957793 3941
59f5296b 3942 cgroup_put(cgrp);
ddbcc7e8 3943
bd89aabc 3944 set_bit(CGRP_RELEASABLE, &parent->flags);
81a6a5cd 3945 check_for_release(parent);
ddbcc7e8
PM
3946}
3947
2bd59d48 3948static int cgroup_rmdir(struct kernfs_node *kn)
42809dd4 3949{
2bd59d48
TH
3950 struct cgroup *cgrp = kn->priv;
3951 int ret = 0;
3952
3953 /*
3954 * This is self-destruction but @kn can't be removed while this
3955 * callback is in progress. Let's break active protection. Once
3956 * the protection is broken, @cgrp can be destroyed at any point.
3957 * Pin it so that it stays accessible.
3958 */
3959 cgroup_get(cgrp);
3960 kernfs_break_active_protection(kn);
42809dd4 3961
ace2bee8 3962 mutex_lock(&cgroup_tree_mutex);
42809dd4 3963 mutex_lock(&cgroup_mutex);
2bd59d48
TH
3964
3965 /*
3966 * @cgrp might already have been destroyed while we're trying to
3967 * grab the mutexes.
3968 */
3969 if (!cgroup_is_dead(cgrp))
3970 ret = cgroup_destroy_locked(cgrp);
3971
42809dd4 3972 mutex_unlock(&cgroup_mutex);
ace2bee8 3973 mutex_unlock(&cgroup_tree_mutex);
42809dd4 3974
2bd59d48
TH
3975 kernfs_unbreak_active_protection(kn);
3976 cgroup_put(cgrp);
42809dd4
TH
3977 return ret;
3978}
3979
2bd59d48
TH
3980static struct kernfs_syscall_ops cgroup_kf_syscall_ops = {
3981 .remount_fs = cgroup_remount,
3982 .show_options = cgroup_show_options,
3983 .mkdir = cgroup_mkdir,
3984 .rmdir = cgroup_rmdir,
3985 .rename = cgroup_rename,
3986};
3987
06a11920 3988static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
ddbcc7e8 3989{
ddbcc7e8 3990 struct cgroup_subsys_state *css;
cfe36bde
DC
3991
3992 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
ddbcc7e8 3993
ace2bee8 3994 mutex_lock(&cgroup_tree_mutex);
648bb56d
TH
3995 mutex_lock(&cgroup_mutex);
3996
0adb0704 3997 INIT_LIST_HEAD(&ss->cfts);
8e3f6541 3998
ddbcc7e8 3999 /* Create the top cgroup state for this subsystem */
9871bf95 4000 ss->root = &cgroup_dummy_root;
ca8bdcaf 4001 css = ss->css_alloc(cgroup_css(cgroup_dummy_top, ss));
ddbcc7e8
PM
4002 /* We don't handle early failures gracefully */
4003 BUG_ON(IS_ERR(css));
623f926b 4004 init_css(css, ss, cgroup_dummy_top);
ddbcc7e8 4005
e8d55fde 4006 /* Update the init_css_set to contain a subsys
817929ec 4007 * pointer to this state - since the subsystem is
e8d55fde
LZ
4008 * newly registered, all tasks and hence the
4009 * init_css_set is in the subsystem's top cgroup. */
aec25020 4010 init_css_set.subsys[ss->id] = css;
ddbcc7e8
PM
4011
4012 need_forkexit_callback |= ss->fork || ss->exit;
4013
e8d55fde
LZ
4014 /* At system boot, before all subsystems have been
4015 * registered, no tasks have been forked, so we don't
4016 * need to invoke fork callbacks here. */
4017 BUG_ON(!list_empty(&init_task.tasks));
4018
ae7f164a 4019 BUG_ON(online_css(css));
a8638030 4020
648bb56d 4021 mutex_unlock(&cgroup_mutex);
ace2bee8 4022 mutex_unlock(&cgroup_tree_mutex);
e6a1105b
BB
4023}
4024
ddbcc7e8 4025/**
a043e3b2
LZ
4026 * cgroup_init_early - cgroup initialization at system boot
4027 *
4028 * Initialize cgroups at system boot, and initialize any
4029 * subsystems that request early init.
ddbcc7e8
PM
4030 */
4031int __init cgroup_init_early(void)
4032{
30159ec7 4033 struct cgroup_subsys *ss;
ddbcc7e8 4034 int i;
30159ec7 4035
146aa1bd 4036 atomic_set(&init_css_set.refcount, 1);
69d0206c 4037 INIT_LIST_HEAD(&init_css_set.cgrp_links);
817929ec 4038 INIT_LIST_HEAD(&init_css_set.tasks);
b3dc094e 4039 INIT_LIST_HEAD(&init_css_set.mg_tasks);
1958d2d5 4040 INIT_LIST_HEAD(&init_css_set.mg_preload_node);
b3dc094e 4041 INIT_LIST_HEAD(&init_css_set.mg_node);
472b1053 4042 INIT_HLIST_NODE(&init_css_set.hlist);
817929ec 4043 css_set_count = 1;
9871bf95
TH
4044 init_cgroup_root(&cgroup_dummy_root);
4045 cgroup_root_count = 1;
a4ea1cc9 4046 RCU_INIT_POINTER(init_task.cgroups, &init_css_set);
817929ec 4047
69d0206c 4048 init_cgrp_cset_link.cset = &init_css_set;
9871bf95
TH
4049 init_cgrp_cset_link.cgrp = cgroup_dummy_top;
4050 list_add(&init_cgrp_cset_link.cset_link, &cgroup_dummy_top->cset_links);
69d0206c 4051 list_add(&init_cgrp_cset_link.cgrp_link, &init_css_set.cgrp_links);
ddbcc7e8 4052
3ed80a62 4053 for_each_subsys(ss, i) {
aec25020 4054 WARN(!ss->css_alloc || !ss->css_free || ss->name || ss->id,
073219e9
TH
4055 "invalid cgroup_subsys %d:%s css_alloc=%p css_free=%p name:id=%d:%s\n",
4056 i, cgroup_subsys_name[i], ss->css_alloc, ss->css_free,
aec25020 4057 ss->id, ss->name);
073219e9
TH
4058 WARN(strlen(cgroup_subsys_name[i]) > MAX_CGROUP_TYPE_NAMELEN,
4059 "cgroup_subsys_name %s too long\n", cgroup_subsys_name[i]);
4060
aec25020 4061 ss->id = i;
073219e9 4062 ss->name = cgroup_subsys_name[i];
ddbcc7e8
PM
4063
4064 if (ss->early_init)
4065 cgroup_init_subsys(ss);
4066 }
4067 return 0;
4068}
4069
4070/**
a043e3b2
LZ
4071 * cgroup_init - cgroup initialization
4072 *
4073 * Register cgroup filesystem and /proc file, and initialize
4074 * any subsystems that didn't request early init.
ddbcc7e8
PM
4075 */
4076int __init cgroup_init(void)
4077{
30159ec7 4078 struct cgroup_subsys *ss;
0ac801fe 4079 unsigned long key;
30159ec7 4080 int i, err;
a424316c 4081
2bd59d48 4082 BUG_ON(cgroup_init_cftypes(NULL, cgroup_base_files));
2da440a2 4083
3ed80a62 4084 for_each_subsys(ss, i) {
ddbcc7e8
PM
4085 if (!ss->early_init)
4086 cgroup_init_subsys(ss);
de00ffa5
TH
4087
4088 /*
4089 * cftype registration needs kmalloc and can't be done
4090 * during early_init. Register base cftypes separately.
4091 */
4092 if (ss->base_cftypes)
4093 WARN_ON(cgroup_add_cftypes(ss, ss->base_cftypes));
ddbcc7e8
PM
4094 }
4095
fa3ca07e 4096 /* allocate id for the dummy hierarchy */
54e7b4eb 4097 mutex_lock(&cgroup_mutex);
54e7b4eb 4098
82fe9b0d
TH
4099 /* Add init_css_set to the hash table */
4100 key = css_set_hash(init_css_set.subsys);
4101 hash_add(css_set_table, &init_css_set.hlist, key);
4102
fc76df70 4103 BUG_ON(cgroup_init_root_id(&cgroup_dummy_root, 0, 1));
676db4af 4104
4e96ee8e
LZ
4105 err = idr_alloc(&cgroup_dummy_root.cgroup_idr, cgroup_dummy_top,
4106 0, 1, GFP_KERNEL);
4107 BUG_ON(err < 0);
4108
54e7b4eb
TH
4109 mutex_unlock(&cgroup_mutex);
4110
676db4af 4111 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
2bd59d48
TH
4112 if (!cgroup_kobj)
4113 return -ENOMEM;
676db4af 4114
ddbcc7e8 4115 err = register_filesystem(&cgroup_fs_type);
676db4af
GK
4116 if (err < 0) {
4117 kobject_put(cgroup_kobj);
2bd59d48 4118 return err;
676db4af 4119 }
ddbcc7e8 4120
46ae220b 4121 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
2bd59d48 4122 return 0;
ddbcc7e8 4123}
b4f48b63 4124
e5fca243
TH
4125static int __init cgroup_wq_init(void)
4126{
4127 /*
4128 * There isn't much point in executing destruction path in
4129 * parallel. Good chunk is serialized with cgroup_mutex anyway.
1a11533f 4130 * Use 1 for @max_active.
e5fca243
TH
4131 *
4132 * We would prefer to do this in cgroup_init() above, but that
4133 * is called before init_workqueues(): so leave this until after.
4134 */
1a11533f 4135 cgroup_destroy_wq = alloc_workqueue("cgroup_destroy", 0, 1);
e5fca243 4136 BUG_ON(!cgroup_destroy_wq);
b1a21367
TH
4137
4138 /*
4139 * Used to destroy pidlists and separate to serve as flush domain.
4140 * Cap @max_active to 1 too.
4141 */
4142 cgroup_pidlist_destroy_wq = alloc_workqueue("cgroup_pidlist_destroy",
4143 0, 1);
4144 BUG_ON(!cgroup_pidlist_destroy_wq);
4145
e5fca243
TH
4146 return 0;
4147}
4148core_initcall(cgroup_wq_init);
4149
a424316c
PM
4150/*
4151 * proc_cgroup_show()
4152 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4153 * - Used for /proc/<pid>/cgroup.
a424316c
PM
4154 */
4155
4156/* TODO: Use a proper seq_file iterator */
8d8b97ba 4157int proc_cgroup_show(struct seq_file *m, void *v)
a424316c
PM
4158{
4159 struct pid *pid;
4160 struct task_struct *tsk;
e61734c5 4161 char *buf, *path;
a424316c
PM
4162 int retval;
4163 struct cgroupfs_root *root;
4164
4165 retval = -ENOMEM;
e61734c5 4166 buf = kmalloc(PATH_MAX, GFP_KERNEL);
a424316c
PM
4167 if (!buf)
4168 goto out;
4169
4170 retval = -ESRCH;
4171 pid = m->private;
4172 tsk = get_pid_task(pid, PIDTYPE_PID);
4173 if (!tsk)
4174 goto out_free;
4175
4176 retval = 0;
4177
4178 mutex_lock(&cgroup_mutex);
96d365e0 4179 down_read(&css_set_rwsem);
a424316c 4180
e5f6a860 4181 for_each_active_root(root) {
a424316c 4182 struct cgroup_subsys *ss;
bd89aabc 4183 struct cgroup *cgrp;
b85d2040 4184 int ssid, count = 0;
a424316c 4185
2c6ab6d2 4186 seq_printf(m, "%d:", root->hierarchy_id);
b85d2040
TH
4187 for_each_subsys(ss, ssid)
4188 if (root->subsys_mask & (1 << ssid))
4189 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
c6d57f33
PM
4190 if (strlen(root->name))
4191 seq_printf(m, "%sname=%s", count ? "," : "",
4192 root->name);
a424316c 4193 seq_putc(m, ':');
7717f7ba 4194 cgrp = task_cgroup_from_root(tsk, root);
e61734c5
TH
4195 path = cgroup_path(cgrp, buf, PATH_MAX);
4196 if (!path) {
4197 retval = -ENAMETOOLONG;
a424316c 4198 goto out_unlock;
e61734c5
TH
4199 }
4200 seq_puts(m, path);
a424316c
PM
4201 seq_putc(m, '\n');
4202 }
4203
4204out_unlock:
96d365e0 4205 up_read(&css_set_rwsem);
a424316c
PM
4206 mutex_unlock(&cgroup_mutex);
4207 put_task_struct(tsk);
4208out_free:
4209 kfree(buf);
4210out:
4211 return retval;
4212}
4213
a424316c
PM
4214/* Display information about each subsystem and each hierarchy */
4215static int proc_cgroupstats_show(struct seq_file *m, void *v)
4216{
30159ec7 4217 struct cgroup_subsys *ss;
a424316c 4218 int i;
a424316c 4219
8bab8dde 4220 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
aae8aab4
BB
4221 /*
4222 * ideally we don't want subsystems moving around while we do this.
4223 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4224 * subsys/hierarchy state.
4225 */
a424316c 4226 mutex_lock(&cgroup_mutex);
30159ec7
TH
4227
4228 for_each_subsys(ss, i)
2c6ab6d2
PM
4229 seq_printf(m, "%s\t%d\t%d\t%d\n",
4230 ss->name, ss->root->hierarchy_id,
3c9c825b 4231 atomic_read(&ss->root->nr_cgrps), !ss->disabled);
30159ec7 4232
a424316c
PM
4233 mutex_unlock(&cgroup_mutex);
4234 return 0;
4235}
4236
4237static int cgroupstats_open(struct inode *inode, struct file *file)
4238{
9dce07f1 4239 return single_open(file, proc_cgroupstats_show, NULL);
a424316c
PM
4240}
4241
828c0950 4242static const struct file_operations proc_cgroupstats_operations = {
a424316c
PM
4243 .open = cgroupstats_open,
4244 .read = seq_read,
4245 .llseek = seq_lseek,
4246 .release = single_release,
4247};
4248
b4f48b63 4249/**
eaf797ab 4250 * cgroup_fork - initialize cgroup related fields during copy_process()
a043e3b2 4251 * @child: pointer to task_struct of forking parent process.
b4f48b63 4252 *
eaf797ab
TH
4253 * A task is associated with the init_css_set until cgroup_post_fork()
4254 * attaches it to the parent's css_set. Empty cg_list indicates that
4255 * @child isn't holding reference to its css_set.
b4f48b63
PM
4256 */
4257void cgroup_fork(struct task_struct *child)
4258{
eaf797ab 4259 RCU_INIT_POINTER(child->cgroups, &init_css_set);
817929ec 4260 INIT_LIST_HEAD(&child->cg_list);
b4f48b63
PM
4261}
4262
817929ec 4263/**
a043e3b2
LZ
4264 * cgroup_post_fork - called on a new task after adding it to the task list
4265 * @child: the task in question
4266 *
5edee61e
TH
4267 * Adds the task to the list running through its css_set if necessary and
4268 * call the subsystem fork() callbacks. Has to be after the task is
4269 * visible on the task list in case we race with the first call to
0942eeee 4270 * cgroup_task_iter_start() - to guarantee that the new task ends up on its
5edee61e 4271 * list.
a043e3b2 4272 */
817929ec
PM
4273void cgroup_post_fork(struct task_struct *child)
4274{
30159ec7 4275 struct cgroup_subsys *ss;
5edee61e
TH
4276 int i;
4277
3ce3230a 4278 /*
eaf797ab
TH
4279 * This may race against cgroup_enable_task_cg_links(). As that
4280 * function sets use_task_css_set_links before grabbing
4281 * tasklist_lock and we just went through tasklist_lock to add
4282 * @child, it's guaranteed that either we see the set
4283 * use_task_css_set_links or cgroup_enable_task_cg_lists() sees
4284 * @child during its iteration.
4285 *
4286 * If we won the race, @child is associated with %current's
4287 * css_set. Grabbing css_set_rwsem guarantees both that the
4288 * association is stable, and, on completion of the parent's
4289 * migration, @child is visible in the source of migration or
4290 * already in the destination cgroup. This guarantee is necessary
4291 * when implementing operations which need to migrate all tasks of
4292 * a cgroup to another.
4293 *
4294 * Note that if we lose to cgroup_enable_task_cg_links(), @child
4295 * will remain in init_css_set. This is safe because all tasks are
4296 * in the init_css_set before cg_links is enabled and there's no
4297 * operation which transfers all tasks out of init_css_set.
3ce3230a 4298 */
817929ec 4299 if (use_task_css_set_links) {
eaf797ab
TH
4300 struct css_set *cset;
4301
96d365e0 4302 down_write(&css_set_rwsem);
0e1d768f 4303 cset = task_css_set(current);
eaf797ab
TH
4304 if (list_empty(&child->cg_list)) {
4305 rcu_assign_pointer(child->cgroups, cset);
4306 list_add(&child->cg_list, &cset->tasks);
4307 get_css_set(cset);
4308 }
96d365e0 4309 up_write(&css_set_rwsem);
817929ec 4310 }
5edee61e
TH
4311
4312 /*
4313 * Call ss->fork(). This must happen after @child is linked on
4314 * css_set; otherwise, @child might change state between ->fork()
4315 * and addition to css_set.
4316 */
4317 if (need_forkexit_callback) {
3ed80a62 4318 for_each_subsys(ss, i)
5edee61e
TH
4319 if (ss->fork)
4320 ss->fork(child);
5edee61e 4321 }
817929ec 4322}
5edee61e 4323
b4f48b63
PM
4324/**
4325 * cgroup_exit - detach cgroup from exiting task
4326 * @tsk: pointer to task_struct of exiting process
a043e3b2 4327 * @run_callback: run exit callbacks?
b4f48b63
PM
4328 *
4329 * Description: Detach cgroup from @tsk and release it.
4330 *
4331 * Note that cgroups marked notify_on_release force every task in
4332 * them to take the global cgroup_mutex mutex when exiting.
4333 * This could impact scaling on very large systems. Be reluctant to
4334 * use notify_on_release cgroups where very high task exit scaling
4335 * is required on large systems.
4336 *
0e1d768f
TH
4337 * We set the exiting tasks cgroup to the root cgroup (top_cgroup). We
4338 * call cgroup_exit() while the task is still competent to handle
4339 * notify_on_release(), then leave the task attached to the root cgroup in
4340 * each hierarchy for the remainder of its exit. No need to bother with
4341 * init_css_set refcnting. init_css_set never goes away and we can't race
4342 * with migration path - either PF_EXITING is visible to migration path or
4343 * @tsk never got on the tasklist.
b4f48b63
PM
4344 */
4345void cgroup_exit(struct task_struct *tsk, int run_callbacks)
4346{
30159ec7 4347 struct cgroup_subsys *ss;
5abb8855 4348 struct css_set *cset;
eaf797ab 4349 bool put_cset = false;
d41d5a01 4350 int i;
817929ec
PM
4351
4352 /*
0e1d768f
TH
4353 * Unlink from @tsk from its css_set. As migration path can't race
4354 * with us, we can check cg_list without grabbing css_set_rwsem.
817929ec
PM
4355 */
4356 if (!list_empty(&tsk->cg_list)) {
96d365e0 4357 down_write(&css_set_rwsem);
0e1d768f 4358 list_del_init(&tsk->cg_list);
96d365e0 4359 up_write(&css_set_rwsem);
0e1d768f 4360 put_cset = true;
817929ec
PM
4361 }
4362
b4f48b63 4363 /* Reassign the task to the init_css_set. */
a8ad805c
TH
4364 cset = task_css_set(tsk);
4365 RCU_INIT_POINTER(tsk->cgroups, &init_css_set);
d41d5a01
PZ
4366
4367 if (run_callbacks && need_forkexit_callback) {
3ed80a62
TH
4368 /* see cgroup_post_fork() for details */
4369 for_each_subsys(ss, i) {
d41d5a01 4370 if (ss->exit) {
eb95419b
TH
4371 struct cgroup_subsys_state *old_css = cset->subsys[i];
4372 struct cgroup_subsys_state *css = task_css(tsk, i);
30159ec7 4373
eb95419b 4374 ss->exit(css, old_css, tsk);
d41d5a01
PZ
4375 }
4376 }
4377 }
d41d5a01 4378
eaf797ab
TH
4379 if (put_cset)
4380 put_css_set(cset, true);
b4f48b63 4381}
697f4161 4382
bd89aabc 4383static void check_for_release(struct cgroup *cgrp)
81a6a5cd 4384{
f50daa70 4385 if (cgroup_is_releasable(cgrp) &&
6f3d828f 4386 list_empty(&cgrp->cset_links) && list_empty(&cgrp->children)) {
f50daa70
LZ
4387 /*
4388 * Control Group is currently removeable. If it's not
81a6a5cd 4389 * already queued for a userspace notification, queue
f50daa70
LZ
4390 * it now
4391 */
81a6a5cd 4392 int need_schedule_work = 0;
f50daa70 4393
cdcc136f 4394 raw_spin_lock(&release_list_lock);
54766d4a 4395 if (!cgroup_is_dead(cgrp) &&
bd89aabc
PM
4396 list_empty(&cgrp->release_list)) {
4397 list_add(&cgrp->release_list, &release_list);
81a6a5cd
PM
4398 need_schedule_work = 1;
4399 }
cdcc136f 4400 raw_spin_unlock(&release_list_lock);
81a6a5cd
PM
4401 if (need_schedule_work)
4402 schedule_work(&release_agent_work);
4403 }
4404}
4405
81a6a5cd
PM
4406/*
4407 * Notify userspace when a cgroup is released, by running the
4408 * configured release agent with the name of the cgroup (path
4409 * relative to the root of cgroup file system) as the argument.
4410 *
4411 * Most likely, this user command will try to rmdir this cgroup.
4412 *
4413 * This races with the possibility that some other task will be
4414 * attached to this cgroup before it is removed, or that some other
4415 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
4416 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
4417 * unused, and this cgroup will be reprieved from its death sentence,
4418 * to continue to serve a useful existence. Next time it's released,
4419 * we will get notified again, if it still has 'notify_on_release' set.
4420 *
4421 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
4422 * means only wait until the task is successfully execve()'d. The
4423 * separate release agent task is forked by call_usermodehelper(),
4424 * then control in this thread returns here, without waiting for the
4425 * release agent task. We don't bother to wait because the caller of
4426 * this routine has no use for the exit status of the release agent
4427 * task, so no sense holding our caller up for that.
81a6a5cd 4428 */
81a6a5cd
PM
4429static void cgroup_release_agent(struct work_struct *work)
4430{
4431 BUG_ON(work != &release_agent_work);
4432 mutex_lock(&cgroup_mutex);
cdcc136f 4433 raw_spin_lock(&release_list_lock);
81a6a5cd
PM
4434 while (!list_empty(&release_list)) {
4435 char *argv[3], *envp[3];
4436 int i;
e61734c5 4437 char *pathbuf = NULL, *agentbuf = NULL, *path;
bd89aabc 4438 struct cgroup *cgrp = list_entry(release_list.next,
81a6a5cd
PM
4439 struct cgroup,
4440 release_list);
bd89aabc 4441 list_del_init(&cgrp->release_list);
cdcc136f 4442 raw_spin_unlock(&release_list_lock);
e61734c5 4443 pathbuf = kmalloc(PATH_MAX, GFP_KERNEL);
e788e066
PM
4444 if (!pathbuf)
4445 goto continue_free;
e61734c5
TH
4446 path = cgroup_path(cgrp, pathbuf, PATH_MAX);
4447 if (!path)
e788e066
PM
4448 goto continue_free;
4449 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
4450 if (!agentbuf)
4451 goto continue_free;
81a6a5cd
PM
4452
4453 i = 0;
e788e066 4454 argv[i++] = agentbuf;
e61734c5 4455 argv[i++] = path;
81a6a5cd
PM
4456 argv[i] = NULL;
4457
4458 i = 0;
4459 /* minimal command environment */
4460 envp[i++] = "HOME=/";
4461 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
4462 envp[i] = NULL;
4463
4464 /* Drop the lock while we invoke the usermode helper,
4465 * since the exec could involve hitting disk and hence
4466 * be a slow process */
4467 mutex_unlock(&cgroup_mutex);
4468 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
81a6a5cd 4469 mutex_lock(&cgroup_mutex);
e788e066
PM
4470 continue_free:
4471 kfree(pathbuf);
4472 kfree(agentbuf);
cdcc136f 4473 raw_spin_lock(&release_list_lock);
81a6a5cd 4474 }
cdcc136f 4475 raw_spin_unlock(&release_list_lock);
81a6a5cd
PM
4476 mutex_unlock(&cgroup_mutex);
4477}
8bab8dde
PM
4478
4479static int __init cgroup_disable(char *str)
4480{
30159ec7 4481 struct cgroup_subsys *ss;
8bab8dde 4482 char *token;
30159ec7 4483 int i;
8bab8dde
PM
4484
4485 while ((token = strsep(&str, ",")) != NULL) {
4486 if (!*token)
4487 continue;
be45c900 4488
3ed80a62 4489 for_each_subsys(ss, i) {
8bab8dde
PM
4490 if (!strcmp(token, ss->name)) {
4491 ss->disabled = 1;
4492 printk(KERN_INFO "Disabling %s control group"
4493 " subsystem\n", ss->name);
4494 break;
4495 }
4496 }
4497 }
4498 return 1;
4499}
4500__setup("cgroup_disable=", cgroup_disable);
38460b48 4501
b77d7b60 4502/**
5a17f543 4503 * css_tryget_from_dir - get corresponding css from the dentry of a cgroup dir
35cf0836
TH
4504 * @dentry: directory dentry of interest
4505 * @ss: subsystem of interest
b77d7b60 4506 *
5a17f543
TH
4507 * If @dentry is a directory for a cgroup which has @ss enabled on it, try
4508 * to get the corresponding css and return it. If such css doesn't exist
4509 * or can't be pinned, an ERR_PTR value is returned.
e5d1367f 4510 */
5a17f543
TH
4511struct cgroup_subsys_state *css_tryget_from_dir(struct dentry *dentry,
4512 struct cgroup_subsys *ss)
e5d1367f 4513{
2bd59d48
TH
4514 struct kernfs_node *kn = kernfs_node_from_dentry(dentry);
4515 struct cgroup_subsys_state *css = NULL;
e5d1367f 4516 struct cgroup *cgrp;
b77d7b60 4517
35cf0836 4518 /* is @dentry a cgroup dir? */
2bd59d48
TH
4519 if (dentry->d_sb->s_type != &cgroup_fs_type || !kn ||
4520 kernfs_type(kn) != KERNFS_DIR)
e5d1367f
SE
4521 return ERR_PTR(-EBADF);
4522
5a17f543
TH
4523 rcu_read_lock();
4524
2bd59d48
TH
4525 /*
4526 * This path doesn't originate from kernfs and @kn could already
4527 * have been or be removed at any point. @kn->priv is RCU
4528 * protected for this access. See destroy_locked() for details.
4529 */
4530 cgrp = rcu_dereference(kn->priv);
4531 if (cgrp)
4532 css = cgroup_css(cgrp, ss);
5a17f543
TH
4533
4534 if (!css || !css_tryget(css))
4535 css = ERR_PTR(-ENOENT);
4536
4537 rcu_read_unlock();
4538 return css;
e5d1367f 4539}
e5d1367f 4540
1cb650b9
LZ
4541/**
4542 * css_from_id - lookup css by id
4543 * @id: the cgroup id
4544 * @ss: cgroup subsys to be looked into
4545 *
4546 * Returns the css if there's valid one with @id, otherwise returns NULL.
4547 * Should be called under rcu_read_lock().
4548 */
4549struct cgroup_subsys_state *css_from_id(int id, struct cgroup_subsys *ss)
4550{
4551 struct cgroup *cgrp;
4552
ace2bee8 4553 cgroup_assert_mutexes_or_rcu_locked();
1cb650b9
LZ
4554
4555 cgrp = idr_find(&ss->root->cgroup_idr, id);
4556 if (cgrp)
d1625964 4557 return cgroup_css(cgrp, ss);
1cb650b9 4558 return NULL;
e5d1367f
SE
4559}
4560
fe693435 4561#ifdef CONFIG_CGROUP_DEBUG
eb95419b
TH
4562static struct cgroup_subsys_state *
4563debug_css_alloc(struct cgroup_subsys_state *parent_css)
fe693435
PM
4564{
4565 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
4566
4567 if (!css)
4568 return ERR_PTR(-ENOMEM);
4569
4570 return css;
4571}
4572
eb95419b 4573static void debug_css_free(struct cgroup_subsys_state *css)
fe693435 4574{
eb95419b 4575 kfree(css);
fe693435
PM
4576}
4577
182446d0
TH
4578static u64 debug_taskcount_read(struct cgroup_subsys_state *css,
4579 struct cftype *cft)
fe693435 4580{
182446d0 4581 return cgroup_task_count(css->cgroup);
fe693435
PM
4582}
4583
182446d0
TH
4584static u64 current_css_set_read(struct cgroup_subsys_state *css,
4585 struct cftype *cft)
fe693435
PM
4586{
4587 return (u64)(unsigned long)current->cgroups;
4588}
4589
182446d0 4590static u64 current_css_set_refcount_read(struct cgroup_subsys_state *css,
03c78cbe 4591 struct cftype *cft)
fe693435
PM
4592{
4593 u64 count;
4594
4595 rcu_read_lock();
a8ad805c 4596 count = atomic_read(&task_css_set(current)->refcount);
fe693435
PM
4597 rcu_read_unlock();
4598 return count;
4599}
4600
2da8ca82 4601static int current_css_set_cg_links_read(struct seq_file *seq, void *v)
7717f7ba 4602{
69d0206c 4603 struct cgrp_cset_link *link;
5abb8855 4604 struct css_set *cset;
e61734c5
TH
4605 char *name_buf;
4606
4607 name_buf = kmalloc(NAME_MAX + 1, GFP_KERNEL);
4608 if (!name_buf)
4609 return -ENOMEM;
7717f7ba 4610
96d365e0 4611 down_read(&css_set_rwsem);
7717f7ba 4612 rcu_read_lock();
5abb8855 4613 cset = rcu_dereference(current->cgroups);
69d0206c 4614 list_for_each_entry(link, &cset->cgrp_links, cgrp_link) {
7717f7ba 4615 struct cgroup *c = link->cgrp;
59f5296b
TH
4616 const char *name = "?";
4617
e61734c5
TH
4618 if (c != cgroup_dummy_top) {
4619 cgroup_name(c, name_buf, NAME_MAX + 1);
4620 name = name_buf;
4621 }
7717f7ba 4622
2c6ab6d2
PM
4623 seq_printf(seq, "Root %d group %s\n",
4624 c->root->hierarchy_id, name);
7717f7ba
PM
4625 }
4626 rcu_read_unlock();
96d365e0 4627 up_read(&css_set_rwsem);
e61734c5 4628 kfree(name_buf);
7717f7ba
PM
4629 return 0;
4630}
4631
4632#define MAX_TASKS_SHOWN_PER_CSS 25
2da8ca82 4633static int cgroup_css_links_read(struct seq_file *seq, void *v)
7717f7ba 4634{
2da8ca82 4635 struct cgroup_subsys_state *css = seq_css(seq);
69d0206c 4636 struct cgrp_cset_link *link;
7717f7ba 4637
96d365e0 4638 down_read(&css_set_rwsem);
182446d0 4639 list_for_each_entry(link, &css->cgroup->cset_links, cset_link) {
69d0206c 4640 struct css_set *cset = link->cset;
7717f7ba
PM
4641 struct task_struct *task;
4642 int count = 0;
c7561128 4643
5abb8855 4644 seq_printf(seq, "css_set %p\n", cset);
c7561128 4645
5abb8855 4646 list_for_each_entry(task, &cset->tasks, cg_list) {
c7561128
TH
4647 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
4648 goto overflow;
4649 seq_printf(seq, " task %d\n", task_pid_vnr(task));
4650 }
4651
4652 list_for_each_entry(task, &cset->mg_tasks, cg_list) {
4653 if (count++ > MAX_TASKS_SHOWN_PER_CSS)
4654 goto overflow;
4655 seq_printf(seq, " task %d\n", task_pid_vnr(task));
7717f7ba 4656 }
c7561128
TH
4657 continue;
4658 overflow:
4659 seq_puts(seq, " ...\n");
7717f7ba 4660 }
96d365e0 4661 up_read(&css_set_rwsem);
7717f7ba
PM
4662 return 0;
4663}
4664
182446d0 4665static u64 releasable_read(struct cgroup_subsys_state *css, struct cftype *cft)
fe693435 4666{
182446d0 4667 return test_bit(CGRP_RELEASABLE, &css->cgroup->flags);
fe693435
PM
4668}
4669
4670static struct cftype debug_files[] = {
fe693435
PM
4671 {
4672 .name = "taskcount",
4673 .read_u64 = debug_taskcount_read,
4674 },
4675
4676 {
4677 .name = "current_css_set",
4678 .read_u64 = current_css_set_read,
4679 },
4680
4681 {
4682 .name = "current_css_set_refcount",
4683 .read_u64 = current_css_set_refcount_read,
4684 },
4685
7717f7ba
PM
4686 {
4687 .name = "current_css_set_cg_links",
2da8ca82 4688 .seq_show = current_css_set_cg_links_read,
7717f7ba
PM
4689 },
4690
4691 {
4692 .name = "cgroup_css_links",
2da8ca82 4693 .seq_show = cgroup_css_links_read,
7717f7ba
PM
4694 },
4695
fe693435
PM
4696 {
4697 .name = "releasable",
4698 .read_u64 = releasable_read,
4699 },
fe693435 4700
4baf6e33
TH
4701 { } /* terminate */
4702};
fe693435 4703
073219e9 4704struct cgroup_subsys debug_cgrp_subsys = {
92fb9748
TH
4705 .css_alloc = debug_css_alloc,
4706 .css_free = debug_css_free,
4baf6e33 4707 .base_cftypes = debug_files,
fe693435
PM
4708};
4709#endif /* CONFIG_CGROUP_DEBUG */