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