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