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