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