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