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