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