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