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