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