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