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