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