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