genirq: Fix can_request_irq() for IRQs without an action
[GitHub/mt8127/android_kernel_alcatel_ttab.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>
817929ec 43#include <linux/backing-dev.h>
ddbcc7e8
PM
44#include <linux/seq_file.h>
45#include <linux/slab.h>
46#include <linux/magic.h>
47#include <linux/spinlock.h>
48#include <linux/string.h>
bbcb81d0 49#include <linux/sort.h>
81a6a5cd 50#include <linux/kmod.h>
e6a1105b 51#include <linux/module.h>
846c7bb0
BS
52#include <linux/delayacct.h>
53#include <linux/cgroupstats.h>
0ac801fe 54#include <linux/hashtable.h>
3f8206d4 55#include <linux/namei.h>
096b7fe0 56#include <linux/pid_namespace.h>
2c6ab6d2 57#include <linux/idr.h>
d1d9fd33 58#include <linux/vmalloc.h> /* TODO: replace with more sophisticated array */
0dea1168
KS
59#include <linux/eventfd.h>
60#include <linux/poll.h>
081aa458 61#include <linux/flex_array.h> /* used in cgroup_attach_task */
c4c27fbd 62#include <linux/kthread.h>
846c7bb0 63
60063497 64#include <linux/atomic.h>
ddbcc7e8 65
28b4c27b
TH
66/* css deactivation bias, makes css->refcnt negative to deny new trygets */
67#define CSS_DEACT_BIAS INT_MIN
68
e25e2cbb
TH
69/*
70 * cgroup_mutex is the master lock. Any modification to cgroup or its
71 * hierarchy must be performed while holding it.
72 *
73 * cgroup_root_mutex nests inside cgroup_mutex and should be held to modify
74 * cgroupfs_root of any cgroup hierarchy - subsys list, flags,
75 * release_agent_path and so on. Modifying requires both cgroup_mutex and
76 * cgroup_root_mutex. Readers can acquire either of the two. This is to
77 * break the following locking order cycle.
78 *
79 * A. cgroup_mutex -> cred_guard_mutex -> s_type->i_mutex_key -> namespace_sem
80 * B. namespace_sem -> cgroup_mutex
81 *
82 * B happens only through cgroup_show_options() and using cgroup_root_mutex
83 * breaks it.
84 */
2219449a
TH
85#ifdef CONFIG_PROVE_RCU
86DEFINE_MUTEX(cgroup_mutex);
87EXPORT_SYMBOL_GPL(cgroup_mutex); /* only for task_subsys_state_check() */
88#else
81a6a5cd 89static DEFINE_MUTEX(cgroup_mutex);
2219449a
TH
90#endif
91
e25e2cbb 92static DEFINE_MUTEX(cgroup_root_mutex);
81a6a5cd 93
aae8aab4
BB
94/*
95 * Generate an array of cgroup subsystem pointers. At boot time, this is
be45c900 96 * populated with the built in subsystems, and modular subsystems are
aae8aab4
BB
97 * registered after that. The mutable section of this array is protected by
98 * cgroup_mutex.
99 */
80f4c877 100#define SUBSYS(_x) [_x ## _subsys_id] = &_x ## _subsys,
5fc0b025 101#define IS_SUBSYS_ENABLED(option) IS_BUILTIN(option)
aae8aab4 102static struct cgroup_subsys *subsys[CGROUP_SUBSYS_COUNT] = {
ddbcc7e8
PM
103#include <linux/cgroup_subsys.h>
104};
105
ddbcc7e8
PM
106/*
107 * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the
108 * subsystems that are otherwise unattached - it never has more than a
109 * single cgroup, and all tasks are part of that cgroup.
110 */
111static struct cgroupfs_root rootnode;
112
05ef1d7c
TH
113/*
114 * cgroupfs file entry, pointed to from leaf dentry->d_fsdata.
115 */
116struct cfent {
117 struct list_head node;
118 struct dentry *dentry;
119 struct cftype *type;
712317ad
LZ
120
121 /* file xattrs */
122 struct simple_xattrs xattrs;
05ef1d7c
TH
123};
124
38460b48
KH
125/*
126 * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when
127 * cgroup_subsys->use_id != 0.
128 */
129#define CSS_ID_MAX (65535)
130struct css_id {
131 /*
132 * The css to which this ID points. This pointer is set to valid value
133 * after cgroup is populated. If cgroup is removed, this will be NULL.
134 * This pointer is expected to be RCU-safe because destroy()
e9316080
TH
135 * is called after synchronize_rcu(). But for safe use, css_tryget()
136 * should be used for avoiding race.
38460b48 137 */
2c392b8c 138 struct cgroup_subsys_state __rcu *css;
38460b48
KH
139 /*
140 * ID of this css.
141 */
142 unsigned short id;
143 /*
144 * Depth in hierarchy which this ID belongs to.
145 */
146 unsigned short depth;
147 /*
148 * ID is freed by RCU. (and lookup routine is RCU safe.)
149 */
150 struct rcu_head rcu_head;
151 /*
152 * Hierarchy of CSS ID belongs to.
153 */
154 unsigned short stack[0]; /* Array of Length (depth+1) */
155};
156
0dea1168 157/*
25985edc 158 * cgroup_event represents events which userspace want to receive.
0dea1168
KS
159 */
160struct cgroup_event {
161 /*
162 * Cgroup which the event belongs to.
163 */
164 struct cgroup *cgrp;
165 /*
166 * Control file which the event associated.
167 */
168 struct cftype *cft;
169 /*
170 * eventfd to signal userspace about the event.
171 */
172 struct eventfd_ctx *eventfd;
173 /*
174 * Each of these stored in a list by the cgroup.
175 */
176 struct list_head list;
177 /*
178 * All fields below needed to unregister event when
179 * userspace closes eventfd.
180 */
181 poll_table pt;
182 wait_queue_head_t *wqh;
183 wait_queue_t wait;
184 struct work_struct remove;
185};
38460b48 186
ddbcc7e8
PM
187/* The list of hierarchy roots */
188
189static LIST_HEAD(roots);
817929ec 190static int root_count;
ddbcc7e8 191
2c6ab6d2
PM
192static DEFINE_IDA(hierarchy_ida);
193static int next_hierarchy_id;
194static DEFINE_SPINLOCK(hierarchy_id_lock);
195
ddbcc7e8
PM
196/* dummytop is a shorthand for the dummy hierarchy's top cgroup */
197#define dummytop (&rootnode.top_cgroup)
198
65dff759
LZ
199static struct cgroup_name root_cgroup_name = { .name = "/" };
200
ddbcc7e8 201/* This flag indicates whether tasks in the fork and exit paths should
a043e3b2
LZ
202 * check for fork/exit handlers to call. This avoids us having to do
203 * extra work in the fork/exit path if none of the subsystems need to
204 * be called.
ddbcc7e8 205 */
8947f9d5 206static int need_forkexit_callback __read_mostly;
ddbcc7e8 207
42809dd4 208static int cgroup_destroy_locked(struct cgroup *cgrp);
879a3d9d
G
209static int cgroup_addrm_files(struct cgroup *cgrp, struct cgroup_subsys *subsys,
210 struct cftype cfts[], bool is_add);
42809dd4 211
8e3bbf42
SQ
212static int css_unbias_refcnt(int refcnt)
213{
214 return refcnt >= 0 ? refcnt : refcnt - CSS_DEACT_BIAS;
215}
216
28b4c27b
TH
217/* the current nr of refs, always >= 0 whether @css is deactivated or not */
218static int css_refcnt(struct cgroup_subsys_state *css)
219{
220 int v = atomic_read(&css->refcnt);
221
8e3bbf42 222 return css_unbias_refcnt(v);
28b4c27b
TH
223}
224
ddbcc7e8 225/* convenient tests for these bits */
bd89aabc 226inline int cgroup_is_removed(const struct cgroup *cgrp)
ddbcc7e8 227{
bd89aabc 228 return test_bit(CGRP_REMOVED, &cgrp->flags);
ddbcc7e8
PM
229}
230
78574cf9
LZ
231/**
232 * cgroup_is_descendant - test ancestry
233 * @cgrp: the cgroup to be tested
234 * @ancestor: possible ancestor of @cgrp
235 *
236 * Test whether @cgrp is a descendant of @ancestor. It also returns %true
237 * if @cgrp == @ancestor. This function is safe to call as long as @cgrp
238 * and @ancestor are accessible.
239 */
240bool cgroup_is_descendant(struct cgroup *cgrp, struct cgroup *ancestor)
241{
242 while (cgrp) {
243 if (cgrp == ancestor)
244 return true;
245 cgrp = cgrp->parent;
246 }
247 return false;
248}
249EXPORT_SYMBOL_GPL(cgroup_is_descendant);
ddbcc7e8 250
e9685a03 251static int cgroup_is_releasable(const struct cgroup *cgrp)
81a6a5cd
PM
252{
253 const int bits =
bd89aabc
PM
254 (1 << CGRP_RELEASABLE) |
255 (1 << CGRP_NOTIFY_ON_RELEASE);
256 return (cgrp->flags & bits) == bits;
81a6a5cd
PM
257}
258
e9685a03 259static int notify_on_release(const struct cgroup *cgrp)
81a6a5cd 260{
bd89aabc 261 return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
81a6a5cd
PM
262}
263
ddbcc7e8
PM
264/*
265 * for_each_subsys() allows you to iterate on each subsystem attached to
266 * an active hierarchy
267 */
268#define for_each_subsys(_root, _ss) \
269list_for_each_entry(_ss, &_root->subsys_list, sibling)
270
e5f6a860
LZ
271/* for_each_active_root() allows you to iterate across the active hierarchies */
272#define for_each_active_root(_root) \
ddbcc7e8
PM
273list_for_each_entry(_root, &roots, root_list)
274
f6ea9372
TH
275static inline struct cgroup *__d_cgrp(struct dentry *dentry)
276{
277 return dentry->d_fsdata;
278}
279
05ef1d7c 280static inline struct cfent *__d_cfe(struct dentry *dentry)
f6ea9372
TH
281{
282 return dentry->d_fsdata;
283}
284
05ef1d7c
TH
285static inline struct cftype *__d_cft(struct dentry *dentry)
286{
287 return __d_cfe(dentry)->type;
288}
289
7ae1bad9
TH
290/**
291 * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
292 * @cgrp: the cgroup to be checked for liveness
293 *
47cfcd09
TH
294 * On success, returns true; the mutex should be later unlocked. On
295 * failure returns false with no lock held.
7ae1bad9 296 */
b9777cf8 297static bool cgroup_lock_live_group(struct cgroup *cgrp)
7ae1bad9
TH
298{
299 mutex_lock(&cgroup_mutex);
300 if (cgroup_is_removed(cgrp)) {
301 mutex_unlock(&cgroup_mutex);
302 return false;
303 }
304 return true;
305}
7ae1bad9 306
81a6a5cd
PM
307/* the list of cgroups eligible for automatic release. Protected by
308 * release_list_lock */
309static LIST_HEAD(release_list);
cdcc136f 310static DEFINE_RAW_SPINLOCK(release_list_lock);
81a6a5cd
PM
311static void cgroup_release_agent(struct work_struct *work);
312static DECLARE_WORK(release_agent_work, cgroup_release_agent);
bd89aabc 313static void check_for_release(struct cgroup *cgrp);
81a6a5cd 314
817929ec
PM
315/* Link structure for associating css_set objects with cgroups */
316struct cg_cgroup_link {
317 /*
318 * List running through cg_cgroup_links associated with a
319 * cgroup, anchored on cgroup->css_sets
320 */
bd89aabc 321 struct list_head cgrp_link_list;
7717f7ba 322 struct cgroup *cgrp;
817929ec
PM
323 /*
324 * List running through cg_cgroup_links pointing at a
325 * single css_set object, anchored on css_set->cg_links
326 */
327 struct list_head cg_link_list;
328 struct css_set *cg;
329};
330
331/* The default css_set - used by init and its children prior to any
332 * hierarchies being mounted. It contains a pointer to the root state
333 * for each subsystem. Also used to anchor the list of css_sets. Not
334 * reference-counted, to improve performance when child cgroups
335 * haven't been created.
336 */
337
338static struct css_set init_css_set;
339static struct cg_cgroup_link init_css_set_link;
340
e6a1105b
BB
341static int cgroup_init_idr(struct cgroup_subsys *ss,
342 struct cgroup_subsys_state *css);
38460b48 343
817929ec
PM
344/* css_set_lock protects the list of css_set objects, and the
345 * chain of tasks off each css_set. Nests outside task->alloc_lock
346 * due to cgroup_iter_start() */
347static DEFINE_RWLOCK(css_set_lock);
348static int css_set_count;
349
7717f7ba
PM
350/*
351 * hash table for cgroup groups. This improves the performance to find
352 * an existing css_set. This hash doesn't (currently) take into
353 * account cgroups in empty hierarchies.
354 */
472b1053 355#define CSS_SET_HASH_BITS 7
0ac801fe 356static DEFINE_HASHTABLE(css_set_table, CSS_SET_HASH_BITS);
472b1053 357
0ac801fe 358static unsigned long css_set_hash(struct cgroup_subsys_state *css[])
472b1053
LZ
359{
360 int i;
0ac801fe 361 unsigned long key = 0UL;
472b1053
LZ
362
363 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++)
0ac801fe
LZ
364 key += (unsigned long)css[i];
365 key = (key >> 16) ^ key;
472b1053 366
0ac801fe 367 return key;
472b1053
LZ
368}
369
817929ec
PM
370/* We don't maintain the lists running through each css_set to its
371 * task until after the first call to cgroup_iter_start(). This
372 * reduces the fork()/exit() overhead for people who have cgroups
373 * compiled into their kernel but not actually in use */
8947f9d5 374static int use_task_css_set_links __read_mostly;
817929ec 375
2c6ab6d2 376static void __put_css_set(struct css_set *cg, int taskexit)
b4f48b63 377{
71cbb949
KM
378 struct cg_cgroup_link *link;
379 struct cg_cgroup_link *saved_link;
146aa1bd
LJ
380 /*
381 * Ensure that the refcount doesn't hit zero while any readers
382 * can see it. Similar to atomic_dec_and_lock(), but for an
383 * rwlock
384 */
385 if (atomic_add_unless(&cg->refcount, -1, 1))
386 return;
387 write_lock(&css_set_lock);
388 if (!atomic_dec_and_test(&cg->refcount)) {
389 write_unlock(&css_set_lock);
390 return;
391 }
81a6a5cd 392
2c6ab6d2 393 /* This css_set is dead. unlink it and release cgroup refcounts */
0ac801fe 394 hash_del(&cg->hlist);
2c6ab6d2
PM
395 css_set_count--;
396
397 list_for_each_entry_safe(link, saved_link, &cg->cg_links,
398 cg_link_list) {
399 struct cgroup *cgrp = link->cgrp;
400 list_del(&link->cg_link_list);
401 list_del(&link->cgrp_link_list);
71b5707e
LZ
402
403 /*
404 * We may not be holding cgroup_mutex, and if cgrp->count is
405 * dropped to 0 the cgroup can be destroyed at any time, hence
406 * rcu_read_lock is used to keep it alive.
407 */
408 rcu_read_lock();
bd89aabc
PM
409 if (atomic_dec_and_test(&cgrp->count) &&
410 notify_on_release(cgrp)) {
81a6a5cd 411 if (taskexit)
bd89aabc
PM
412 set_bit(CGRP_RELEASABLE, &cgrp->flags);
413 check_for_release(cgrp);
81a6a5cd 414 }
71b5707e 415 rcu_read_unlock();
2c6ab6d2
PM
416
417 kfree(link);
81a6a5cd 418 }
2c6ab6d2
PM
419
420 write_unlock(&css_set_lock);
30088ad8 421 kfree_rcu(cg, rcu_head);
b4f48b63
PM
422}
423
817929ec
PM
424/*
425 * refcounted get/put for css_set objects
426 */
427static inline void get_css_set(struct css_set *cg)
428{
146aa1bd 429 atomic_inc(&cg->refcount);
817929ec
PM
430}
431
432static inline void put_css_set(struct css_set *cg)
433{
146aa1bd 434 __put_css_set(cg, 0);
817929ec
PM
435}
436
81a6a5cd
PM
437static inline void put_css_set_taskexit(struct css_set *cg)
438{
146aa1bd 439 __put_css_set(cg, 1);
81a6a5cd
PM
440}
441
7717f7ba
PM
442/*
443 * compare_css_sets - helper function for find_existing_css_set().
444 * @cg: candidate css_set being tested
445 * @old_cg: existing css_set for a task
446 * @new_cgrp: cgroup that's being entered by the task
447 * @template: desired set of css pointers in css_set (pre-calculated)
448 *
449 * Returns true if "cg" matches "old_cg" except for the hierarchy
450 * which "new_cgrp" belongs to, for which it should match "new_cgrp".
451 */
452static bool compare_css_sets(struct css_set *cg,
453 struct css_set *old_cg,
454 struct cgroup *new_cgrp,
455 struct cgroup_subsys_state *template[])
456{
457 struct list_head *l1, *l2;
458
459 if (memcmp(template, cg->subsys, sizeof(cg->subsys))) {
460 /* Not all subsystems matched */
461 return false;
462 }
463
464 /*
465 * Compare cgroup pointers in order to distinguish between
466 * different cgroups in heirarchies with no subsystems. We
467 * could get by with just this check alone (and skip the
468 * memcmp above) but on most setups the memcmp check will
469 * avoid the need for this more expensive check on almost all
470 * candidates.
471 */
472
473 l1 = &cg->cg_links;
474 l2 = &old_cg->cg_links;
475 while (1) {
476 struct cg_cgroup_link *cgl1, *cgl2;
477 struct cgroup *cg1, *cg2;
478
479 l1 = l1->next;
480 l2 = l2->next;
481 /* See if we reached the end - both lists are equal length. */
482 if (l1 == &cg->cg_links) {
483 BUG_ON(l2 != &old_cg->cg_links);
484 break;
485 } else {
486 BUG_ON(l2 == &old_cg->cg_links);
487 }
488 /* Locate the cgroups associated with these links. */
489 cgl1 = list_entry(l1, struct cg_cgroup_link, cg_link_list);
490 cgl2 = list_entry(l2, struct cg_cgroup_link, cg_link_list);
491 cg1 = cgl1->cgrp;
492 cg2 = cgl2->cgrp;
493 /* Hierarchies should be linked in the same order. */
494 BUG_ON(cg1->root != cg2->root);
495
496 /*
497 * If this hierarchy is the hierarchy of the cgroup
498 * that's changing, then we need to check that this
499 * css_set points to the new cgroup; if it's any other
500 * hierarchy, then this css_set should point to the
501 * same cgroup as the old css_set.
502 */
503 if (cg1->root == new_cgrp->root) {
504 if (cg1 != new_cgrp)
505 return false;
506 } else {
507 if (cg1 != cg2)
508 return false;
509 }
510 }
511 return true;
512}
513
817929ec
PM
514/*
515 * find_existing_css_set() is a helper for
516 * find_css_set(), and checks to see whether an existing
472b1053 517 * css_set is suitable.
817929ec
PM
518 *
519 * oldcg: the cgroup group that we're using before the cgroup
520 * transition
521 *
bd89aabc 522 * cgrp: the cgroup that we're moving into
817929ec
PM
523 *
524 * template: location in which to build the desired set of subsystem
525 * state objects for the new cgroup group
526 */
817929ec
PM
527static struct css_set *find_existing_css_set(
528 struct css_set *oldcg,
bd89aabc 529 struct cgroup *cgrp,
817929ec 530 struct cgroup_subsys_state *template[])
b4f48b63
PM
531{
532 int i;
bd89aabc 533 struct cgroupfs_root *root = cgrp->root;
472b1053 534 struct css_set *cg;
0ac801fe 535 unsigned long key;
817929ec 536
aae8aab4
BB
537 /*
538 * Build the set of subsystem state objects that we want to see in the
539 * new css_set. while subsystems can change globally, the entries here
540 * won't change, so no need for locking.
541 */
817929ec 542 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
a1a71b45 543 if (root->subsys_mask & (1UL << i)) {
817929ec
PM
544 /* Subsystem is in this hierarchy. So we want
545 * the subsystem state from the new
546 * cgroup */
bd89aabc 547 template[i] = cgrp->subsys[i];
817929ec
PM
548 } else {
549 /* Subsystem is not in this hierarchy, so we
550 * don't want to change the subsystem state */
551 template[i] = oldcg->subsys[i];
552 }
553 }
554
0ac801fe 555 key = css_set_hash(template);
b67bfe0d 556 hash_for_each_possible(css_set_table, cg, hlist, key) {
7717f7ba
PM
557 if (!compare_css_sets(cg, oldcg, cgrp, template))
558 continue;
559
560 /* This css_set matches what we need */
561 return cg;
472b1053 562 }
817929ec
PM
563
564 /* No existing cgroup group matched */
565 return NULL;
566}
567
36553434
LZ
568static void free_cg_links(struct list_head *tmp)
569{
570 struct cg_cgroup_link *link;
571 struct cg_cgroup_link *saved_link;
572
573 list_for_each_entry_safe(link, saved_link, tmp, cgrp_link_list) {
574 list_del(&link->cgrp_link_list);
575 kfree(link);
576 }
577}
578
817929ec
PM
579/*
580 * allocate_cg_links() allocates "count" cg_cgroup_link structures
bd89aabc 581 * and chains them on tmp through their cgrp_link_list fields. Returns 0 on
817929ec
PM
582 * success or a negative error
583 */
817929ec
PM
584static int allocate_cg_links(int count, struct list_head *tmp)
585{
586 struct cg_cgroup_link *link;
587 int i;
588 INIT_LIST_HEAD(tmp);
589 for (i = 0; i < count; i++) {
590 link = kmalloc(sizeof(*link), GFP_KERNEL);
591 if (!link) {
36553434 592 free_cg_links(tmp);
817929ec
PM
593 return -ENOMEM;
594 }
bd89aabc 595 list_add(&link->cgrp_link_list, tmp);
817929ec
PM
596 }
597 return 0;
598}
599
c12f65d4
LZ
600/**
601 * link_css_set - a helper function to link a css_set to a cgroup
602 * @tmp_cg_links: cg_cgroup_link objects allocated by allocate_cg_links()
603 * @cg: the css_set to be linked
604 * @cgrp: the destination cgroup
605 */
606static void link_css_set(struct list_head *tmp_cg_links,
607 struct css_set *cg, struct cgroup *cgrp)
608{
609 struct cg_cgroup_link *link;
610
611 BUG_ON(list_empty(tmp_cg_links));
612 link = list_first_entry(tmp_cg_links, struct cg_cgroup_link,
613 cgrp_link_list);
614 link->cg = cg;
7717f7ba 615 link->cgrp = cgrp;
2c6ab6d2 616 atomic_inc(&cgrp->count);
c12f65d4 617 list_move(&link->cgrp_link_list, &cgrp->css_sets);
7717f7ba
PM
618 /*
619 * Always add links to the tail of the list so that the list
620 * is sorted by order of hierarchy creation
621 */
622 list_add_tail(&link->cg_link_list, &cg->cg_links);
c12f65d4
LZ
623}
624
817929ec
PM
625/*
626 * find_css_set() takes an existing cgroup group and a
627 * cgroup object, and returns a css_set object that's
628 * equivalent to the old group, but with the given cgroup
629 * substituted into the appropriate hierarchy. Must be called with
630 * cgroup_mutex held
631 */
817929ec 632static struct css_set *find_css_set(
bd89aabc 633 struct css_set *oldcg, struct cgroup *cgrp)
817929ec
PM
634{
635 struct css_set *res;
636 struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT];
817929ec
PM
637
638 struct list_head tmp_cg_links;
817929ec 639
7717f7ba 640 struct cg_cgroup_link *link;
0ac801fe 641 unsigned long key;
472b1053 642
817929ec
PM
643 /* First see if we already have a cgroup group that matches
644 * the desired set */
7e9abd89 645 read_lock(&css_set_lock);
bd89aabc 646 res = find_existing_css_set(oldcg, cgrp, template);
817929ec
PM
647 if (res)
648 get_css_set(res);
7e9abd89 649 read_unlock(&css_set_lock);
817929ec
PM
650
651 if (res)
652 return res;
653
654 res = kmalloc(sizeof(*res), GFP_KERNEL);
655 if (!res)
656 return NULL;
657
658 /* Allocate all the cg_cgroup_link objects that we'll need */
659 if (allocate_cg_links(root_count, &tmp_cg_links) < 0) {
660 kfree(res);
661 return NULL;
662 }
663
146aa1bd 664 atomic_set(&res->refcount, 1);
817929ec
PM
665 INIT_LIST_HEAD(&res->cg_links);
666 INIT_LIST_HEAD(&res->tasks);
472b1053 667 INIT_HLIST_NODE(&res->hlist);
817929ec
PM
668
669 /* Copy the set of subsystem state objects generated in
670 * find_existing_css_set() */
671 memcpy(res->subsys, template, sizeof(res->subsys));
672
673 write_lock(&css_set_lock);
674 /* Add reference counts and links from the new css_set. */
7717f7ba
PM
675 list_for_each_entry(link, &oldcg->cg_links, cg_link_list) {
676 struct cgroup *c = link->cgrp;
677 if (c->root == cgrp->root)
678 c = cgrp;
679 link_css_set(&tmp_cg_links, res, c);
680 }
817929ec
PM
681
682 BUG_ON(!list_empty(&tmp_cg_links));
683
817929ec 684 css_set_count++;
472b1053
LZ
685
686 /* Add this cgroup group to the hash table */
0ac801fe
LZ
687 key = css_set_hash(res->subsys);
688 hash_add(css_set_table, &res->hlist, key);
472b1053 689
817929ec
PM
690 write_unlock(&css_set_lock);
691
692 return res;
b4f48b63
PM
693}
694
7717f7ba
PM
695/*
696 * Return the cgroup for "task" from the given hierarchy. Must be
697 * called with cgroup_mutex held.
698 */
699static struct cgroup *task_cgroup_from_root(struct task_struct *task,
700 struct cgroupfs_root *root)
701{
702 struct css_set *css;
703 struct cgroup *res = NULL;
704
705 BUG_ON(!mutex_is_locked(&cgroup_mutex));
706 read_lock(&css_set_lock);
707 /*
708 * No need to lock the task - since we hold cgroup_mutex the
709 * task can't change groups, so the only thing that can happen
710 * is that it exits and its css is set back to init_css_set.
711 */
712 css = task->cgroups;
713 if (css == &init_css_set) {
714 res = &root->top_cgroup;
715 } else {
716 struct cg_cgroup_link *link;
717 list_for_each_entry(link, &css->cg_links, cg_link_list) {
718 struct cgroup *c = link->cgrp;
719 if (c->root == root) {
720 res = c;
721 break;
722 }
723 }
724 }
725 read_unlock(&css_set_lock);
726 BUG_ON(!res);
727 return res;
728}
729
ddbcc7e8
PM
730/*
731 * There is one global cgroup mutex. We also require taking
732 * task_lock() when dereferencing a task's cgroup subsys pointers.
733 * See "The task_lock() exception", at the end of this comment.
734 *
735 * A task must hold cgroup_mutex to modify cgroups.
736 *
737 * Any task can increment and decrement the count field without lock.
738 * So in general, code holding cgroup_mutex can't rely on the count
739 * field not changing. However, if the count goes to zero, then only
956db3ca 740 * cgroup_attach_task() can increment it again. Because a count of zero
ddbcc7e8
PM
741 * means that no tasks are currently attached, therefore there is no
742 * way a task attached to that cgroup can fork (the other way to
743 * increment the count). So code holding cgroup_mutex can safely
744 * assume that if the count is zero, it will stay zero. Similarly, if
745 * a task holds cgroup_mutex on a cgroup with zero count, it
746 * knows that the cgroup won't be removed, as cgroup_rmdir()
747 * needs that mutex.
748 *
ddbcc7e8
PM
749 * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
750 * (usually) take cgroup_mutex. These are the two most performance
751 * critical pieces of code here. The exception occurs on cgroup_exit(),
752 * when a task in a notify_on_release cgroup exits. Then cgroup_mutex
753 * is taken, and if the cgroup count is zero, a usermode call made
a043e3b2
LZ
754 * to the release agent with the name of the cgroup (path relative to
755 * the root of cgroup file system) as the argument.
ddbcc7e8
PM
756 *
757 * A cgroup can only be deleted if both its 'count' of using tasks
758 * is zero, and its list of 'children' cgroups is empty. Since all
759 * tasks in the system use _some_ cgroup, and since there is always at
760 * least one task in the system (init, pid == 1), therefore, top_cgroup
761 * always has either children cgroups and/or using tasks. So we don't
762 * need a special hack to ensure that top_cgroup cannot be deleted.
763 *
764 * The task_lock() exception
765 *
766 * The need for this exception arises from the action of
d0b2fdd2 767 * cgroup_attach_task(), which overwrites one task's cgroup pointer with
a043e3b2 768 * another. It does so using cgroup_mutex, however there are
ddbcc7e8
PM
769 * several performance critical places that need to reference
770 * task->cgroup without the expense of grabbing a system global
771 * mutex. Therefore except as noted below, when dereferencing or, as
d0b2fdd2 772 * in cgroup_attach_task(), modifying a task's cgroup pointer we use
ddbcc7e8
PM
773 * task_lock(), which acts on a spinlock (task->alloc_lock) already in
774 * the task_struct routinely used for such matters.
775 *
776 * P.S. One more locking exception. RCU is used to guard the
956db3ca 777 * update of a tasks cgroup pointer by cgroup_attach_task()
ddbcc7e8
PM
778 */
779
ddbcc7e8
PM
780/*
781 * A couple of forward declarations required, due to cyclic reference loop:
782 * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
783 * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
784 * -> cgroup_mkdir.
785 */
786
18bb1db3 787static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode);
00cd8dd3 788static struct dentry *cgroup_lookup(struct inode *, struct dentry *, unsigned int);
ddbcc7e8 789static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
13af07df
AR
790static int cgroup_populate_dir(struct cgroup *cgrp, bool base_files,
791 unsigned long subsys_mask);
6e1d5dcc 792static const struct inode_operations cgroup_dir_inode_operations;
828c0950 793static const struct file_operations proc_cgroupstats_operations;
a424316c
PM
794
795static struct backing_dev_info cgroup_backing_dev_info = {
d993831f 796 .name = "cgroup",
e4ad08fe 797 .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK,
a424316c 798};
ddbcc7e8 799
38460b48
KH
800static int alloc_css_id(struct cgroup_subsys *ss,
801 struct cgroup *parent, struct cgroup *child);
802
a5e7ed32 803static struct inode *cgroup_new_inode(umode_t mode, struct super_block *sb)
ddbcc7e8
PM
804{
805 struct inode *inode = new_inode(sb);
ddbcc7e8
PM
806
807 if (inode) {
85fe4025 808 inode->i_ino = get_next_ino();
ddbcc7e8 809 inode->i_mode = mode;
76aac0e9
DH
810 inode->i_uid = current_fsuid();
811 inode->i_gid = current_fsgid();
ddbcc7e8
PM
812 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
813 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
814 }
815 return inode;
816}
817
65dff759
LZ
818static struct cgroup_name *cgroup_alloc_name(struct dentry *dentry)
819{
820 struct cgroup_name *name;
821
822 name = kmalloc(sizeof(*name) + dentry->d_name.len + 1, GFP_KERNEL);
823 if (!name)
824 return NULL;
825 strcpy(name->name, dentry->d_name.name);
826 return name;
827}
828
be445626
LZ
829static void cgroup_free_fn(struct work_struct *work)
830{
831 struct cgroup *cgrp = container_of(work, struct cgroup, free_work);
832 struct cgroup_subsys *ss;
833
834 mutex_lock(&cgroup_mutex);
835 /*
836 * Release the subsystem state objects.
837 */
838 for_each_subsys(cgrp->root, ss)
839 ss->css_free(cgrp);
840
841 cgrp->root->number_of_cgroups--;
842 mutex_unlock(&cgroup_mutex);
843
415cf07a
LZ
844 /*
845 * We get a ref to the parent's dentry, and put the ref when
846 * this cgroup is being freed, so it's guaranteed that the
847 * parent won't be destroyed before its children.
848 */
849 dput(cgrp->parent->dentry);
850
cc20e01c
LZ
851 ida_simple_remove(&cgrp->root->cgroup_ida, cgrp->id);
852
be445626
LZ
853 /*
854 * Drop the active superblock reference that we took when we
cc20e01c
LZ
855 * created the cgroup. This will free cgrp->root, if we are
856 * holding the last reference to @sb.
be445626
LZ
857 */
858 deactivate_super(cgrp->root->sb);
859
860 /*
861 * if we're getting rid of the cgroup, refcount should ensure
862 * that there are no pidlists left.
863 */
864 BUG_ON(!list_empty(&cgrp->pidlists));
865
866 simple_xattrs_free(&cgrp->xattrs);
867
65dff759 868 kfree(rcu_dereference_raw(cgrp->name));
be445626
LZ
869 kfree(cgrp);
870}
871
872static void cgroup_free_rcu(struct rcu_head *head)
873{
874 struct cgroup *cgrp = container_of(head, struct cgroup, rcu_head);
875
876 schedule_work(&cgrp->free_work);
877}
878
ddbcc7e8
PM
879static void cgroup_diput(struct dentry *dentry, struct inode *inode)
880{
881 /* is dentry a directory ? if so, kfree() associated cgroup */
882 if (S_ISDIR(inode->i_mode)) {
bd89aabc 883 struct cgroup *cgrp = dentry->d_fsdata;
be445626 884
bd89aabc 885 BUG_ON(!(cgroup_is_removed(cgrp)));
be445626 886 call_rcu(&cgrp->rcu_head, cgroup_free_rcu);
05ef1d7c
TH
887 } else {
888 struct cfent *cfe = __d_cfe(dentry);
889 struct cgroup *cgrp = dentry->d_parent->d_fsdata;
890
891 WARN_ONCE(!list_empty(&cfe->node) &&
892 cgrp != &cgrp->root->top_cgroup,
893 "cfe still linked for %s\n", cfe->type->name);
712317ad 894 simple_xattrs_free(&cfe->xattrs);
05ef1d7c 895 kfree(cfe);
ddbcc7e8
PM
896 }
897 iput(inode);
898}
899
c72a04e3
AV
900static int cgroup_delete(const struct dentry *d)
901{
902 return 1;
903}
904
ddbcc7e8
PM
905static void remove_dir(struct dentry *d)
906{
907 struct dentry *parent = dget(d->d_parent);
908
909 d_delete(d);
910 simple_rmdir(parent->d_inode, d);
911 dput(parent);
912}
913
2739d3cc 914static void cgroup_rm_file(struct cgroup *cgrp, const struct cftype *cft)
05ef1d7c
TH
915{
916 struct cfent *cfe;
917
918 lockdep_assert_held(&cgrp->dentry->d_inode->i_mutex);
919 lockdep_assert_held(&cgroup_mutex);
920
2739d3cc
LZ
921 /*
922 * If we're doing cleanup due to failure of cgroup_create(),
923 * the corresponding @cfe may not exist.
924 */
05ef1d7c
TH
925 list_for_each_entry(cfe, &cgrp->files, node) {
926 struct dentry *d = cfe->dentry;
927
928 if (cft && cfe->type != cft)
929 continue;
930
931 dget(d);
932 d_delete(d);
ce27e317 933 simple_unlink(cgrp->dentry->d_inode, d);
05ef1d7c
TH
934 list_del_init(&cfe->node);
935 dput(d);
936
2739d3cc 937 break;
ddbcc7e8 938 }
05ef1d7c
TH
939}
940
13af07df
AR
941/**
942 * cgroup_clear_directory - selective removal of base and subsystem files
943 * @dir: directory containing the files
944 * @base_files: true if the base files should be removed
945 * @subsys_mask: mask of the subsystem ids whose files should be removed
946 */
947static void cgroup_clear_directory(struct dentry *dir, bool base_files,
948 unsigned long subsys_mask)
05ef1d7c
TH
949{
950 struct cgroup *cgrp = __d_cgrp(dir);
13af07df 951 struct cgroup_subsys *ss;
05ef1d7c 952
13af07df
AR
953 for_each_subsys(cgrp->root, ss) {
954 struct cftype_set *set;
955 if (!test_bit(ss->subsys_id, &subsys_mask))
956 continue;
957 list_for_each_entry(set, &ss->cftsets, node)
879a3d9d 958 cgroup_addrm_files(cgrp, NULL, set->cfts, false);
13af07df
AR
959 }
960 if (base_files) {
961 while (!list_empty(&cgrp->files))
962 cgroup_rm_file(cgrp, NULL);
963 }
ddbcc7e8
PM
964}
965
966/*
967 * NOTE : the dentry must have been dget()'ed
968 */
969static void cgroup_d_remove_dir(struct dentry *dentry)
970{
2fd6b7f5 971 struct dentry *parent;
13af07df 972 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
2fd6b7f5 973
a1a71b45 974 cgroup_clear_directory(dentry, true, root->subsys_mask);
ddbcc7e8 975
2fd6b7f5
NP
976 parent = dentry->d_parent;
977 spin_lock(&parent->d_lock);
3ec762ad 978 spin_lock_nested(&dentry->d_lock, DENTRY_D_LOCK_NESTED);
ddbcc7e8 979 list_del_init(&dentry->d_u.d_child);
2fd6b7f5
NP
980 spin_unlock(&dentry->d_lock);
981 spin_unlock(&parent->d_lock);
ddbcc7e8
PM
982 remove_dir(dentry);
983}
984
aae8aab4 985/*
cf5d5941
BB
986 * Call with cgroup_mutex held. Drops reference counts on modules, including
987 * any duplicate ones that parse_cgroupfs_options took. If this function
988 * returns an error, no reference counts are touched.
aae8aab4 989 */
ddbcc7e8 990static int rebind_subsystems(struct cgroupfs_root *root,
a1a71b45 991 unsigned long final_subsys_mask)
ddbcc7e8 992{
a1a71b45 993 unsigned long added_mask, removed_mask;
bd89aabc 994 struct cgroup *cgrp = &root->top_cgroup;
ddbcc7e8
PM
995 int i;
996
aae8aab4 997 BUG_ON(!mutex_is_locked(&cgroup_mutex));
e25e2cbb 998 BUG_ON(!mutex_is_locked(&cgroup_root_mutex));
aae8aab4 999
a1a71b45
AR
1000 removed_mask = root->actual_subsys_mask & ~final_subsys_mask;
1001 added_mask = final_subsys_mask & ~root->actual_subsys_mask;
ddbcc7e8
PM
1002 /* Check that any added subsystems are currently free */
1003 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
8d53d55d 1004 unsigned long bit = 1UL << i;
ddbcc7e8 1005 struct cgroup_subsys *ss = subsys[i];
a1a71b45 1006 if (!(bit & added_mask))
ddbcc7e8 1007 continue;
aae8aab4
BB
1008 /*
1009 * Nobody should tell us to do a subsys that doesn't exist:
1010 * parse_cgroupfs_options should catch that case and refcounts
1011 * ensure that subsystems won't disappear once selected.
1012 */
1013 BUG_ON(ss == NULL);
ddbcc7e8
PM
1014 if (ss->root != &rootnode) {
1015 /* Subsystem isn't free */
1016 return -EBUSY;
1017 }
1018 }
1019
1020 /* Currently we don't handle adding/removing subsystems when
1021 * any child cgroups exist. This is theoretically supportable
1022 * but involves complex error handling, so it's being left until
1023 * later */
307257cf 1024 if (root->number_of_cgroups > 1)
ddbcc7e8
PM
1025 return -EBUSY;
1026
1027 /* Process each subsystem */
1028 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1029 struct cgroup_subsys *ss = subsys[i];
1030 unsigned long bit = 1UL << i;
a1a71b45 1031 if (bit & added_mask) {
ddbcc7e8 1032 /* We're binding this subsystem to this hierarchy */
aae8aab4 1033 BUG_ON(ss == NULL);
bd89aabc 1034 BUG_ON(cgrp->subsys[i]);
ddbcc7e8
PM
1035 BUG_ON(!dummytop->subsys[i]);
1036 BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
bd89aabc
PM
1037 cgrp->subsys[i] = dummytop->subsys[i];
1038 cgrp->subsys[i]->cgroup = cgrp;
33a68ac1 1039 list_move(&ss->sibling, &root->subsys_list);
b2aa30f7 1040 ss->root = root;
ddbcc7e8 1041 if (ss->bind)
761b3ef5 1042 ss->bind(cgrp);
cf5d5941 1043 /* refcount was already taken, and we're keeping it */
a1a71b45 1044 } else if (bit & removed_mask) {
ddbcc7e8 1045 /* We're removing this subsystem */
aae8aab4 1046 BUG_ON(ss == NULL);
bd89aabc
PM
1047 BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
1048 BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
ddbcc7e8 1049 if (ss->bind)
761b3ef5 1050 ss->bind(dummytop);
ddbcc7e8 1051 dummytop->subsys[i]->cgroup = dummytop;
bd89aabc 1052 cgrp->subsys[i] = NULL;
b2aa30f7 1053 subsys[i]->root = &rootnode;
33a68ac1 1054 list_move(&ss->sibling, &rootnode.subsys_list);
cf5d5941
BB
1055 /* subsystem is now free - drop reference on module */
1056 module_put(ss->module);
a1a71b45 1057 } else if (bit & final_subsys_mask) {
ddbcc7e8 1058 /* Subsystem state should already exist */
aae8aab4 1059 BUG_ON(ss == NULL);
bd89aabc 1060 BUG_ON(!cgrp->subsys[i]);
cf5d5941
BB
1061 /*
1062 * a refcount was taken, but we already had one, so
1063 * drop the extra reference.
1064 */
1065 module_put(ss->module);
1066#ifdef CONFIG_MODULE_UNLOAD
1067 BUG_ON(ss->module && !module_refcount(ss->module));
1068#endif
ddbcc7e8
PM
1069 } else {
1070 /* Subsystem state shouldn't exist */
bd89aabc 1071 BUG_ON(cgrp->subsys[i]);
ddbcc7e8
PM
1072 }
1073 }
a1a71b45 1074 root->subsys_mask = root->actual_subsys_mask = final_subsys_mask;
ddbcc7e8
PM
1075
1076 return 0;
1077}
1078
34c80b1d 1079static int cgroup_show_options(struct seq_file *seq, struct dentry *dentry)
ddbcc7e8 1080{
34c80b1d 1081 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
ddbcc7e8
PM
1082 struct cgroup_subsys *ss;
1083
e25e2cbb 1084 mutex_lock(&cgroup_root_mutex);
ddbcc7e8
PM
1085 for_each_subsys(root, ss)
1086 seq_printf(seq, ",%s", ss->name);
873fe09e
TH
1087 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR)
1088 seq_puts(seq, ",sane_behavior");
93438629 1089 if (root->flags & CGRP_ROOT_NOPREFIX)
ddbcc7e8 1090 seq_puts(seq, ",noprefix");
93438629 1091 if (root->flags & CGRP_ROOT_XATTR)
03b1cde6 1092 seq_puts(seq, ",xattr");
81a6a5cd
PM
1093 if (strlen(root->release_agent_path))
1094 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
2260e7fc 1095 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags))
97978e6d 1096 seq_puts(seq, ",clone_children");
c6d57f33
PM
1097 if (strlen(root->name))
1098 seq_printf(seq, ",name=%s", root->name);
e25e2cbb 1099 mutex_unlock(&cgroup_root_mutex);
ddbcc7e8
PM
1100 return 0;
1101}
1102
1103struct cgroup_sb_opts {
a1a71b45 1104 unsigned long subsys_mask;
ddbcc7e8 1105 unsigned long flags;
81a6a5cd 1106 char *release_agent;
2260e7fc 1107 bool cpuset_clone_children;
c6d57f33 1108 char *name;
2c6ab6d2
PM
1109 /* User explicitly requested empty subsystem */
1110 bool none;
c6d57f33
PM
1111
1112 struct cgroupfs_root *new_root;
2c6ab6d2 1113
ddbcc7e8
PM
1114};
1115
aae8aab4
BB
1116/*
1117 * Convert a hierarchy specifier into a bitmask of subsystems and flags. Call
cf5d5941
BB
1118 * with cgroup_mutex held to protect the subsys[] array. This function takes
1119 * refcounts on subsystems to be used, unless it returns error, in which case
1120 * no refcounts are taken.
aae8aab4 1121 */
cf5d5941 1122static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts)
ddbcc7e8 1123{
32a8cf23
DL
1124 char *token, *o = data;
1125 bool all_ss = false, one_ss = false;
f9ab5b5b 1126 unsigned long mask = (unsigned long)-1;
cf5d5941
BB
1127 int i;
1128 bool module_pin_failed = false;
f9ab5b5b 1129
aae8aab4
BB
1130 BUG_ON(!mutex_is_locked(&cgroup_mutex));
1131
f9ab5b5b
LZ
1132#ifdef CONFIG_CPUSETS
1133 mask = ~(1UL << cpuset_subsys_id);
1134#endif
ddbcc7e8 1135
c6d57f33 1136 memset(opts, 0, sizeof(*opts));
ddbcc7e8
PM
1137
1138 while ((token = strsep(&o, ",")) != NULL) {
1139 if (!*token)
1140 return -EINVAL;
32a8cf23 1141 if (!strcmp(token, "none")) {
2c6ab6d2
PM
1142 /* Explicitly have no subsystems */
1143 opts->none = true;
32a8cf23
DL
1144 continue;
1145 }
1146 if (!strcmp(token, "all")) {
1147 /* Mutually exclusive option 'all' + subsystem name */
1148 if (one_ss)
1149 return -EINVAL;
1150 all_ss = true;
1151 continue;
1152 }
873fe09e
TH
1153 if (!strcmp(token, "__DEVEL__sane_behavior")) {
1154 opts->flags |= CGRP_ROOT_SANE_BEHAVIOR;
1155 continue;
1156 }
32a8cf23 1157 if (!strcmp(token, "noprefix")) {
93438629 1158 opts->flags |= CGRP_ROOT_NOPREFIX;
32a8cf23
DL
1159 continue;
1160 }
1161 if (!strcmp(token, "clone_children")) {
2260e7fc 1162 opts->cpuset_clone_children = true;
32a8cf23
DL
1163 continue;
1164 }
03b1cde6 1165 if (!strcmp(token, "xattr")) {
93438629 1166 opts->flags |= CGRP_ROOT_XATTR;
03b1cde6
AR
1167 continue;
1168 }
32a8cf23 1169 if (!strncmp(token, "release_agent=", 14)) {
81a6a5cd
PM
1170 /* Specifying two release agents is forbidden */
1171 if (opts->release_agent)
1172 return -EINVAL;
c6d57f33 1173 opts->release_agent =
e400c285 1174 kstrndup(token + 14, PATH_MAX - 1, GFP_KERNEL);
81a6a5cd
PM
1175 if (!opts->release_agent)
1176 return -ENOMEM;
32a8cf23
DL
1177 continue;
1178 }
1179 if (!strncmp(token, "name=", 5)) {
c6d57f33
PM
1180 const char *name = token + 5;
1181 /* Can't specify an empty name */
1182 if (!strlen(name))
1183 return -EINVAL;
1184 /* Must match [\w.-]+ */
1185 for (i = 0; i < strlen(name); i++) {
1186 char c = name[i];
1187 if (isalnum(c))
1188 continue;
1189 if ((c == '.') || (c == '-') || (c == '_'))
1190 continue;
1191 return -EINVAL;
1192 }
1193 /* Specifying two names is forbidden */
1194 if (opts->name)
1195 return -EINVAL;
1196 opts->name = kstrndup(name,
e400c285 1197 MAX_CGROUP_ROOT_NAMELEN - 1,
c6d57f33
PM
1198 GFP_KERNEL);
1199 if (!opts->name)
1200 return -ENOMEM;
32a8cf23
DL
1201
1202 continue;
1203 }
1204
1205 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1206 struct cgroup_subsys *ss = subsys[i];
1207 if (ss == NULL)
1208 continue;
1209 if (strcmp(token, ss->name))
1210 continue;
1211 if (ss->disabled)
1212 continue;
1213
1214 /* Mutually exclusive option 'all' + subsystem name */
1215 if (all_ss)
1216 return -EINVAL;
a1a71b45 1217 set_bit(i, &opts->subsys_mask);
32a8cf23
DL
1218 one_ss = true;
1219
1220 break;
1221 }
1222 if (i == CGROUP_SUBSYS_COUNT)
1223 return -ENOENT;
1224 }
1225
1226 /*
1227 * If the 'all' option was specified select all the subsystems,
0d19ea86
LZ
1228 * otherwise if 'none', 'name=' and a subsystem name options
1229 * were not specified, let's default to 'all'
32a8cf23 1230 */
0d19ea86 1231 if (all_ss || (!one_ss && !opts->none && !opts->name)) {
32a8cf23
DL
1232 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
1233 struct cgroup_subsys *ss = subsys[i];
1234 if (ss == NULL)
1235 continue;
1236 if (ss->disabled)
1237 continue;
a1a71b45 1238 set_bit(i, &opts->subsys_mask);
ddbcc7e8
PM
1239 }
1240 }
1241
2c6ab6d2
PM
1242 /* Consistency checks */
1243
873fe09e
TH
1244 if (opts->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1245 pr_warning("cgroup: sane_behavior: this is still under development and its behaviors will change, proceed at your own risk\n");
1246
1247 if (opts->flags & CGRP_ROOT_NOPREFIX) {
1248 pr_err("cgroup: sane_behavior: noprefix is not allowed\n");
1249 return -EINVAL;
1250 }
1251
1252 if (opts->cpuset_clone_children) {
1253 pr_err("cgroup: sane_behavior: clone_children is not allowed\n");
1254 return -EINVAL;
1255 }
1256 }
1257
f9ab5b5b
LZ
1258 /*
1259 * Option noprefix was introduced just for backward compatibility
1260 * with the old cpuset, so we allow noprefix only if mounting just
1261 * the cpuset subsystem.
1262 */
93438629 1263 if ((opts->flags & CGRP_ROOT_NOPREFIX) && (opts->subsys_mask & mask))
f9ab5b5b
LZ
1264 return -EINVAL;
1265
2c6ab6d2
PM
1266
1267 /* Can't specify "none" and some subsystems */
a1a71b45 1268 if (opts->subsys_mask && opts->none)
2c6ab6d2
PM
1269 return -EINVAL;
1270
1271 /*
1272 * We either have to specify by name or by subsystems. (So all
1273 * empty hierarchies must have a name).
1274 */
a1a71b45 1275 if (!opts->subsys_mask && !opts->name)
ddbcc7e8
PM
1276 return -EINVAL;
1277
cf5d5941
BB
1278 /*
1279 * Grab references on all the modules we'll need, so the subsystems
1280 * don't dance around before rebind_subsystems attaches them. This may
1281 * take duplicate reference counts on a subsystem that's already used,
1282 * but rebind_subsystems handles this case.
1283 */
be45c900 1284 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
cf5d5941
BB
1285 unsigned long bit = 1UL << i;
1286
a1a71b45 1287 if (!(bit & opts->subsys_mask))
cf5d5941
BB
1288 continue;
1289 if (!try_module_get(subsys[i]->module)) {
1290 module_pin_failed = true;
1291 break;
1292 }
1293 }
1294 if (module_pin_failed) {
1295 /*
1296 * oops, one of the modules was going away. this means that we
1297 * raced with a module_delete call, and to the user this is
1298 * essentially a "subsystem doesn't exist" case.
1299 */
be45c900 1300 for (i--; i >= 0; i--) {
cf5d5941
BB
1301 /* drop refcounts only on the ones we took */
1302 unsigned long bit = 1UL << i;
1303
a1a71b45 1304 if (!(bit & opts->subsys_mask))
cf5d5941
BB
1305 continue;
1306 module_put(subsys[i]->module);
1307 }
1308 return -ENOENT;
1309 }
1310
ddbcc7e8
PM
1311 return 0;
1312}
1313
a1a71b45 1314static void drop_parsed_module_refcounts(unsigned long subsys_mask)
cf5d5941
BB
1315{
1316 int i;
be45c900 1317 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
cf5d5941
BB
1318 unsigned long bit = 1UL << i;
1319
a1a71b45 1320 if (!(bit & subsys_mask))
cf5d5941
BB
1321 continue;
1322 module_put(subsys[i]->module);
1323 }
1324}
1325
ddbcc7e8
PM
1326static int cgroup_remount(struct super_block *sb, int *flags, char *data)
1327{
1328 int ret = 0;
1329 struct cgroupfs_root *root = sb->s_fs_info;
bd89aabc 1330 struct cgroup *cgrp = &root->top_cgroup;
ddbcc7e8 1331 struct cgroup_sb_opts opts;
a1a71b45 1332 unsigned long added_mask, removed_mask;
ddbcc7e8 1333
873fe09e
TH
1334 if (root->flags & CGRP_ROOT_SANE_BEHAVIOR) {
1335 pr_err("cgroup: sane_behavior: remount is not allowed\n");
1336 return -EINVAL;
1337 }
1338
bd89aabc 1339 mutex_lock(&cgrp->dentry->d_inode->i_mutex);
ddbcc7e8 1340 mutex_lock(&cgroup_mutex);
e25e2cbb 1341 mutex_lock(&cgroup_root_mutex);
ddbcc7e8
PM
1342
1343 /* See what subsystems are wanted */
1344 ret = parse_cgroupfs_options(data, &opts);
1345 if (ret)
1346 goto out_unlock;
1347
a1a71b45 1348 if (opts.subsys_mask != root->actual_subsys_mask || opts.release_agent)
8b5a5a9d
TH
1349 pr_warning("cgroup: option changes via remount are deprecated (pid=%d comm=%s)\n",
1350 task_tgid_nr(current), current->comm);
1351
a1a71b45
AR
1352 added_mask = opts.subsys_mask & ~root->subsys_mask;
1353 removed_mask = root->subsys_mask & ~opts.subsys_mask;
13af07df 1354
cf5d5941
BB
1355 /* Don't allow flags or name to change at remount */
1356 if (opts.flags != root->flags ||
1357 (opts.name && strcmp(opts.name, root->name))) {
c6d57f33 1358 ret = -EINVAL;
a1a71b45 1359 drop_parsed_module_refcounts(opts.subsys_mask);
c6d57f33
PM
1360 goto out_unlock;
1361 }
1362
7083d037
G
1363 /*
1364 * Clear out the files of subsystems that should be removed, do
1365 * this before rebind_subsystems, since rebind_subsystems may
1366 * change this hierarchy's subsys_list.
1367 */
1368 cgroup_clear_directory(cgrp->dentry, false, removed_mask);
1369
a1a71b45 1370 ret = rebind_subsystems(root, opts.subsys_mask);
cf5d5941 1371 if (ret) {
7083d037
G
1372 /* rebind_subsystems failed, re-populate the removed files */
1373 cgroup_populate_dir(cgrp, false, removed_mask);
a1a71b45 1374 drop_parsed_module_refcounts(opts.subsys_mask);
0670e08b 1375 goto out_unlock;
cf5d5941 1376 }
ddbcc7e8 1377
13af07df 1378 /* re-populate subsystem files */
a1a71b45 1379 cgroup_populate_dir(cgrp, false, added_mask);
ddbcc7e8 1380
81a6a5cd
PM
1381 if (opts.release_agent)
1382 strcpy(root->release_agent_path, opts.release_agent);
ddbcc7e8 1383 out_unlock:
66bdc9cf 1384 kfree(opts.release_agent);
c6d57f33 1385 kfree(opts.name);
e25e2cbb 1386 mutex_unlock(&cgroup_root_mutex);
ddbcc7e8 1387 mutex_unlock(&cgroup_mutex);
bd89aabc 1388 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
ddbcc7e8
PM
1389 return ret;
1390}
1391
b87221de 1392static const struct super_operations cgroup_ops = {
ddbcc7e8
PM
1393 .statfs = simple_statfs,
1394 .drop_inode = generic_delete_inode,
1395 .show_options = cgroup_show_options,
1396 .remount_fs = cgroup_remount,
1397};
1398
cc31edce
PM
1399static void init_cgroup_housekeeping(struct cgroup *cgrp)
1400{
1401 INIT_LIST_HEAD(&cgrp->sibling);
1402 INIT_LIST_HEAD(&cgrp->children);
05ef1d7c 1403 INIT_LIST_HEAD(&cgrp->files);
cc31edce 1404 INIT_LIST_HEAD(&cgrp->css_sets);
2243076a 1405 INIT_LIST_HEAD(&cgrp->allcg_node);
cc31edce 1406 INIT_LIST_HEAD(&cgrp->release_list);
72a8cb30 1407 INIT_LIST_HEAD(&cgrp->pidlists);
be445626 1408 INIT_WORK(&cgrp->free_work, cgroup_free_fn);
72a8cb30 1409 mutex_init(&cgrp->pidlist_mutex);
0dea1168
KS
1410 INIT_LIST_HEAD(&cgrp->event_list);
1411 spin_lock_init(&cgrp->event_list_lock);
03b1cde6 1412 simple_xattrs_init(&cgrp->xattrs);
cc31edce 1413}
c6d57f33 1414
ddbcc7e8
PM
1415static void init_cgroup_root(struct cgroupfs_root *root)
1416{
bd89aabc 1417 struct cgroup *cgrp = &root->top_cgroup;
b0ca5a84 1418
ddbcc7e8
PM
1419 INIT_LIST_HEAD(&root->subsys_list);
1420 INIT_LIST_HEAD(&root->root_list);
b0ca5a84 1421 INIT_LIST_HEAD(&root->allcg_list);
ddbcc7e8 1422 root->number_of_cgroups = 1;
bd89aabc 1423 cgrp->root = root;
65dff759 1424 cgrp->name = &root_cgroup_name;
cc31edce 1425 init_cgroup_housekeeping(cgrp);
fddfb02a 1426 list_add_tail(&cgrp->allcg_node, &root->allcg_list);
ddbcc7e8
PM
1427}
1428
2c6ab6d2
PM
1429static bool init_root_id(struct cgroupfs_root *root)
1430{
1431 int ret = 0;
1432
1433 do {
1434 if (!ida_pre_get(&hierarchy_ida, GFP_KERNEL))
1435 return false;
1436 spin_lock(&hierarchy_id_lock);
1437 /* Try to allocate the next unused ID */
1438 ret = ida_get_new_above(&hierarchy_ida, next_hierarchy_id,
1439 &root->hierarchy_id);
1440 if (ret == -ENOSPC)
1441 /* Try again starting from 0 */
1442 ret = ida_get_new(&hierarchy_ida, &root->hierarchy_id);
1443 if (!ret) {
1444 next_hierarchy_id = root->hierarchy_id + 1;
1445 } else if (ret != -EAGAIN) {
1446 /* Can only get here if the 31-bit IDR is full ... */
1447 BUG_ON(ret);
1448 }
1449 spin_unlock(&hierarchy_id_lock);
1450 } while (ret);
1451 return true;
1452}
1453
ddbcc7e8
PM
1454static int cgroup_test_super(struct super_block *sb, void *data)
1455{
c6d57f33 1456 struct cgroup_sb_opts *opts = data;
ddbcc7e8
PM
1457 struct cgroupfs_root *root = sb->s_fs_info;
1458
c6d57f33
PM
1459 /* If we asked for a name then it must match */
1460 if (opts->name && strcmp(opts->name, root->name))
1461 return 0;
ddbcc7e8 1462
2c6ab6d2
PM
1463 /*
1464 * If we asked for subsystems (or explicitly for no
1465 * subsystems) then they must match
1466 */
a1a71b45
AR
1467 if ((opts->subsys_mask || opts->none)
1468 && (opts->subsys_mask != root->subsys_mask))
ddbcc7e8
PM
1469 return 0;
1470
1471 return 1;
1472}
1473
c6d57f33
PM
1474static struct cgroupfs_root *cgroup_root_from_opts(struct cgroup_sb_opts *opts)
1475{
1476 struct cgroupfs_root *root;
1477
a1a71b45 1478 if (!opts->subsys_mask && !opts->none)
c6d57f33
PM
1479 return NULL;
1480
1481 root = kzalloc(sizeof(*root), GFP_KERNEL);
1482 if (!root)
1483 return ERR_PTR(-ENOMEM);
1484
2c6ab6d2
PM
1485 if (!init_root_id(root)) {
1486 kfree(root);
1487 return ERR_PTR(-ENOMEM);
1488 }
c6d57f33 1489 init_cgroup_root(root);
2c6ab6d2 1490
a1a71b45 1491 root->subsys_mask = opts->subsys_mask;
c6d57f33 1492 root->flags = opts->flags;
0a950f65 1493 ida_init(&root->cgroup_ida);
c6d57f33
PM
1494 if (opts->release_agent)
1495 strcpy(root->release_agent_path, opts->release_agent);
1496 if (opts->name)
1497 strcpy(root->name, opts->name);
2260e7fc
TH
1498 if (opts->cpuset_clone_children)
1499 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &root->top_cgroup.flags);
c6d57f33
PM
1500 return root;
1501}
1502
2c6ab6d2
PM
1503static void cgroup_drop_root(struct cgroupfs_root *root)
1504{
1505 if (!root)
1506 return;
1507
1508 BUG_ON(!root->hierarchy_id);
1509 spin_lock(&hierarchy_id_lock);
1510 ida_remove(&hierarchy_ida, root->hierarchy_id);
1511 spin_unlock(&hierarchy_id_lock);
0a950f65 1512 ida_destroy(&root->cgroup_ida);
2c6ab6d2
PM
1513 kfree(root);
1514}
1515
ddbcc7e8
PM
1516static int cgroup_set_super(struct super_block *sb, void *data)
1517{
1518 int ret;
c6d57f33
PM
1519 struct cgroup_sb_opts *opts = data;
1520
1521 /* If we don't have a new root, we can't set up a new sb */
1522 if (!opts->new_root)
1523 return -EINVAL;
1524
a1a71b45 1525 BUG_ON(!opts->subsys_mask && !opts->none);
ddbcc7e8
PM
1526
1527 ret = set_anon_super(sb, NULL);
1528 if (ret)
1529 return ret;
1530
c6d57f33
PM
1531 sb->s_fs_info = opts->new_root;
1532 opts->new_root->sb = sb;
ddbcc7e8
PM
1533
1534 sb->s_blocksize = PAGE_CACHE_SIZE;
1535 sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
1536 sb->s_magic = CGROUP_SUPER_MAGIC;
1537 sb->s_op = &cgroup_ops;
1538
1539 return 0;
1540}
1541
1542static int cgroup_get_rootdir(struct super_block *sb)
1543{
0df6a63f
AV
1544 static const struct dentry_operations cgroup_dops = {
1545 .d_iput = cgroup_diput,
c72a04e3 1546 .d_delete = cgroup_delete,
0df6a63f
AV
1547 };
1548
ddbcc7e8
PM
1549 struct inode *inode =
1550 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
ddbcc7e8
PM
1551
1552 if (!inode)
1553 return -ENOMEM;
1554
ddbcc7e8
PM
1555 inode->i_fop = &simple_dir_operations;
1556 inode->i_op = &cgroup_dir_inode_operations;
1557 /* directories start off with i_nlink == 2 (for "." entry) */
1558 inc_nlink(inode);
48fde701
AV
1559 sb->s_root = d_make_root(inode);
1560 if (!sb->s_root)
ddbcc7e8 1561 return -ENOMEM;
0df6a63f
AV
1562 /* for everything else we want ->d_op set */
1563 sb->s_d_op = &cgroup_dops;
ddbcc7e8
PM
1564 return 0;
1565}
1566
f7e83571 1567static struct dentry *cgroup_mount(struct file_system_type *fs_type,
ddbcc7e8 1568 int flags, const char *unused_dev_name,
f7e83571 1569 void *data)
ddbcc7e8
PM
1570{
1571 struct cgroup_sb_opts opts;
c6d57f33 1572 struct cgroupfs_root *root;
ddbcc7e8
PM
1573 int ret = 0;
1574 struct super_block *sb;
c6d57f33 1575 struct cgroupfs_root *new_root;
e25e2cbb 1576 struct inode *inode;
ddbcc7e8
PM
1577
1578 /* First find the desired set of subsystems */
aae8aab4 1579 mutex_lock(&cgroup_mutex);
ddbcc7e8 1580 ret = parse_cgroupfs_options(data, &opts);
aae8aab4 1581 mutex_unlock(&cgroup_mutex);
c6d57f33
PM
1582 if (ret)
1583 goto out_err;
ddbcc7e8 1584
c6d57f33
PM
1585 /*
1586 * Allocate a new cgroup root. We may not need it if we're
1587 * reusing an existing hierarchy.
1588 */
1589 new_root = cgroup_root_from_opts(&opts);
1590 if (IS_ERR(new_root)) {
1591 ret = PTR_ERR(new_root);
cf5d5941 1592 goto drop_modules;
81a6a5cd 1593 }
c6d57f33 1594 opts.new_root = new_root;
ddbcc7e8 1595
c6d57f33 1596 /* Locate an existing or new sb for this hierarchy */
9249e17f 1597 sb = sget(fs_type, cgroup_test_super, cgroup_set_super, 0, &opts);
ddbcc7e8 1598 if (IS_ERR(sb)) {
c6d57f33 1599 ret = PTR_ERR(sb);
2c6ab6d2 1600 cgroup_drop_root(opts.new_root);
cf5d5941 1601 goto drop_modules;
ddbcc7e8
PM
1602 }
1603
c6d57f33
PM
1604 root = sb->s_fs_info;
1605 BUG_ON(!root);
1606 if (root == opts.new_root) {
1607 /* We used the new root structure, so this is a new hierarchy */
1608 struct list_head tmp_cg_links;
c12f65d4 1609 struct cgroup *root_cgrp = &root->top_cgroup;
c6d57f33 1610 struct cgroupfs_root *existing_root;
2ce9738b 1611 const struct cred *cred;
28fd5dfc 1612 int i;
0ac801fe 1613 struct css_set *cg;
ddbcc7e8
PM
1614
1615 BUG_ON(sb->s_root != NULL);
1616
1617 ret = cgroup_get_rootdir(sb);
1618 if (ret)
1619 goto drop_new_super;
817929ec 1620 inode = sb->s_root->d_inode;
ddbcc7e8 1621
817929ec 1622 mutex_lock(&inode->i_mutex);
ddbcc7e8 1623 mutex_lock(&cgroup_mutex);
e25e2cbb 1624 mutex_lock(&cgroup_root_mutex);
ddbcc7e8 1625
e25e2cbb
TH
1626 /* Check for name clashes with existing mounts */
1627 ret = -EBUSY;
1628 if (strlen(root->name))
1629 for_each_active_root(existing_root)
1630 if (!strcmp(existing_root->name, root->name))
1631 goto unlock_drop;
c6d57f33 1632
817929ec
PM
1633 /*
1634 * We're accessing css_set_count without locking
1635 * css_set_lock here, but that's OK - it can only be
1636 * increased by someone holding cgroup_lock, and
1637 * that's us. The worst that can happen is that we
1638 * have some link structures left over
1639 */
1640 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
e25e2cbb
TH
1641 if (ret)
1642 goto unlock_drop;
817929ec 1643
a1a71b45 1644 ret = rebind_subsystems(root, root->subsys_mask);
ddbcc7e8 1645 if (ret == -EBUSY) {
c6d57f33 1646 free_cg_links(&tmp_cg_links);
e25e2cbb 1647 goto unlock_drop;
ddbcc7e8 1648 }
cf5d5941
BB
1649 /*
1650 * There must be no failure case after here, since rebinding
1651 * takes care of subsystems' refcounts, which are explicitly
1652 * dropped in the failure exit path.
1653 */
ddbcc7e8
PM
1654
1655 /* EBUSY should be the only error here */
1656 BUG_ON(ret);
1657
1658 list_add(&root->root_list, &roots);
817929ec 1659 root_count++;
ddbcc7e8 1660
c12f65d4 1661 sb->s_root->d_fsdata = root_cgrp;
ddbcc7e8
PM
1662 root->top_cgroup.dentry = sb->s_root;
1663
817929ec
PM
1664 /* Link the top cgroup in this hierarchy into all
1665 * the css_set objects */
1666 write_lock(&css_set_lock);
b67bfe0d 1667 hash_for_each(css_set_table, i, cg, hlist)
0ac801fe 1668 link_css_set(&tmp_cg_links, cg, root_cgrp);
817929ec
PM
1669 write_unlock(&css_set_lock);
1670
1671 free_cg_links(&tmp_cg_links);
1672
c12f65d4 1673 BUG_ON(!list_empty(&root_cgrp->children));
ddbcc7e8
PM
1674 BUG_ON(root->number_of_cgroups != 1);
1675
2ce9738b 1676 cred = override_creds(&init_cred);
a1a71b45 1677 cgroup_populate_dir(root_cgrp, true, root->subsys_mask);
2ce9738b 1678 revert_creds(cred);
e25e2cbb 1679 mutex_unlock(&cgroup_root_mutex);
ddbcc7e8 1680 mutex_unlock(&cgroup_mutex);
34f77a90 1681 mutex_unlock(&inode->i_mutex);
c6d57f33
PM
1682 } else {
1683 /*
1684 * We re-used an existing hierarchy - the new root (if
1685 * any) is not needed
1686 */
2c6ab6d2 1687 cgroup_drop_root(opts.new_root);
873fe09e 1688
2a0ff3fb
JL
1689 if (root->flags != opts.flags) {
1690 if ((root->flags | opts.flags) & CGRP_ROOT_SANE_BEHAVIOR) {
1691 pr_err("cgroup: sane_behavior: new mount options should match the existing superblock\n");
1692 ret = -EINVAL;
1693 goto drop_new_super;
1694 } else {
1695 pr_warning("cgroup: new mount options do not match the existing superblock, will be ignored\n");
1696 }
873fe09e
TH
1697 }
1698
cf5d5941 1699 /* no subsys rebinding, so refcounts don't change */
a1a71b45 1700 drop_parsed_module_refcounts(opts.subsys_mask);
ddbcc7e8
PM
1701 }
1702
c6d57f33
PM
1703 kfree(opts.release_agent);
1704 kfree(opts.name);
f7e83571 1705 return dget(sb->s_root);
ddbcc7e8 1706
e25e2cbb
TH
1707 unlock_drop:
1708 mutex_unlock(&cgroup_root_mutex);
1709 mutex_unlock(&cgroup_mutex);
1710 mutex_unlock(&inode->i_mutex);
ddbcc7e8 1711 drop_new_super:
6f5bbff9 1712 deactivate_locked_super(sb);
cf5d5941 1713 drop_modules:
a1a71b45 1714 drop_parsed_module_refcounts(opts.subsys_mask);
c6d57f33
PM
1715 out_err:
1716 kfree(opts.release_agent);
1717 kfree(opts.name);
f7e83571 1718 return ERR_PTR(ret);
ddbcc7e8
PM
1719}
1720
1721static void cgroup_kill_sb(struct super_block *sb) {
1722 struct cgroupfs_root *root = sb->s_fs_info;
bd89aabc 1723 struct cgroup *cgrp = &root->top_cgroup;
ddbcc7e8 1724 int ret;
71cbb949
KM
1725 struct cg_cgroup_link *link;
1726 struct cg_cgroup_link *saved_link;
ddbcc7e8
PM
1727
1728 BUG_ON(!root);
1729
1730 BUG_ON(root->number_of_cgroups != 1);
bd89aabc 1731 BUG_ON(!list_empty(&cgrp->children));
ddbcc7e8
PM
1732
1733 mutex_lock(&cgroup_mutex);
e25e2cbb 1734 mutex_lock(&cgroup_root_mutex);
ddbcc7e8
PM
1735
1736 /* Rebind all subsystems back to the default hierarchy */
1737 ret = rebind_subsystems(root, 0);
1738 /* Shouldn't be able to fail ... */
1739 BUG_ON(ret);
1740
817929ec
PM
1741 /*
1742 * Release all the links from css_sets to this hierarchy's
1743 * root cgroup
1744 */
1745 write_lock(&css_set_lock);
71cbb949
KM
1746
1747 list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1748 cgrp_link_list) {
817929ec 1749 list_del(&link->cg_link_list);
bd89aabc 1750 list_del(&link->cgrp_link_list);
817929ec
PM
1751 kfree(link);
1752 }
1753 write_unlock(&css_set_lock);
1754
839ec545
PM
1755 if (!list_empty(&root->root_list)) {
1756 list_del(&root->root_list);
1757 root_count--;
1758 }
e5f6a860 1759
e25e2cbb 1760 mutex_unlock(&cgroup_root_mutex);
ddbcc7e8
PM
1761 mutex_unlock(&cgroup_mutex);
1762
03b1cde6
AR
1763 simple_xattrs_free(&cgrp->xattrs);
1764
ddbcc7e8 1765 kill_litter_super(sb);
2c6ab6d2 1766 cgroup_drop_root(root);
ddbcc7e8
PM
1767}
1768
1769static struct file_system_type cgroup_fs_type = {
1770 .name = "cgroup",
f7e83571 1771 .mount = cgroup_mount,
ddbcc7e8
PM
1772 .kill_sb = cgroup_kill_sb,
1773};
1774
676db4af
GKH
1775static struct kobject *cgroup_kobj;
1776
a043e3b2
LZ
1777/**
1778 * cgroup_path - generate the path of a cgroup
1779 * @cgrp: the cgroup in question
1780 * @buf: the buffer to write the path into
1781 * @buflen: the length of the buffer
1782 *
65dff759
LZ
1783 * Writes path of cgroup into buf. Returns 0 on success, -errno on error.
1784 *
1785 * We can't generate cgroup path using dentry->d_name, as accessing
1786 * dentry->name must be protected by irq-unsafe dentry->d_lock or parent
1787 * inode's i_mutex, while on the other hand cgroup_path() can be called
1788 * with some irq-safe spinlocks held.
ddbcc7e8 1789 */
bd89aabc 1790int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
ddbcc7e8 1791{
65dff759 1792 int ret = -ENAMETOOLONG;
ddbcc7e8 1793 char *start;
febfcef6 1794
da1f296f
TH
1795 if (!cgrp->parent) {
1796 if (strlcpy(buf, "/", buflen) >= buflen)
1797 return -ENAMETOOLONG;
ddbcc7e8
PM
1798 return 0;
1799 }
1800
316eb661 1801 start = buf + buflen - 1;
316eb661 1802 *start = '\0';
9a9686b6 1803
65dff759 1804 rcu_read_lock();
da1f296f 1805 do {
65dff759
LZ
1806 const char *name = cgroup_name(cgrp);
1807 int len;
1808
1809 len = strlen(name);
ddbcc7e8 1810 if ((start -= len) < buf)
65dff759
LZ
1811 goto out;
1812 memcpy(start, name, len);
9a9686b6 1813
ddbcc7e8 1814 if (--start < buf)
65dff759 1815 goto out;
ddbcc7e8 1816 *start = '/';
65dff759
LZ
1817
1818 cgrp = cgrp->parent;
da1f296f 1819 } while (cgrp->parent);
65dff759 1820 ret = 0;
ddbcc7e8 1821 memmove(buf, start, buf + buflen - start);
65dff759
LZ
1822out:
1823 rcu_read_unlock();
1824 return ret;
ddbcc7e8 1825}
67523c48 1826EXPORT_SYMBOL_GPL(cgroup_path);
ddbcc7e8 1827
2f7ee569
TH
1828/*
1829 * Control Group taskset
1830 */
134d3373
TH
1831struct task_and_cgroup {
1832 struct task_struct *task;
1833 struct cgroup *cgrp;
61d1d219 1834 struct css_set *cg;
134d3373
TH
1835};
1836
2f7ee569
TH
1837struct cgroup_taskset {
1838 struct task_and_cgroup single;
1839 struct flex_array *tc_array;
1840 int tc_array_len;
1841 int idx;
1842 struct cgroup *cur_cgrp;
1843};
1844
1845/**
1846 * cgroup_taskset_first - reset taskset and return the first task
1847 * @tset: taskset of interest
1848 *
1849 * @tset iteration is initialized and the first task is returned.
1850 */
1851struct task_struct *cgroup_taskset_first(struct cgroup_taskset *tset)
1852{
1853 if (tset->tc_array) {
1854 tset->idx = 0;
1855 return cgroup_taskset_next(tset);
1856 } else {
1857 tset->cur_cgrp = tset->single.cgrp;
1858 return tset->single.task;
1859 }
1860}
1861EXPORT_SYMBOL_GPL(cgroup_taskset_first);
1862
1863/**
1864 * cgroup_taskset_next - iterate to the next task in taskset
1865 * @tset: taskset of interest
1866 *
1867 * Return the next task in @tset. Iteration must have been initialized
1868 * with cgroup_taskset_first().
1869 */
1870struct task_struct *cgroup_taskset_next(struct cgroup_taskset *tset)
1871{
1872 struct task_and_cgroup *tc;
1873
1874 if (!tset->tc_array || tset->idx >= tset->tc_array_len)
1875 return NULL;
1876
1877 tc = flex_array_get(tset->tc_array, tset->idx++);
1878 tset->cur_cgrp = tc->cgrp;
1879 return tc->task;
1880}
1881EXPORT_SYMBOL_GPL(cgroup_taskset_next);
1882
1883/**
1884 * cgroup_taskset_cur_cgroup - return the matching cgroup for the current task
1885 * @tset: taskset of interest
1886 *
1887 * Return the cgroup for the current (last returned) task of @tset. This
1888 * function must be preceded by either cgroup_taskset_first() or
1889 * cgroup_taskset_next().
1890 */
1891struct cgroup *cgroup_taskset_cur_cgroup(struct cgroup_taskset *tset)
1892{
1893 return tset->cur_cgrp;
1894}
1895EXPORT_SYMBOL_GPL(cgroup_taskset_cur_cgroup);
1896
1897/**
1898 * cgroup_taskset_size - return the number of tasks in taskset
1899 * @tset: taskset of interest
1900 */
1901int cgroup_taskset_size(struct cgroup_taskset *tset)
1902{
1903 return tset->tc_array ? tset->tc_array_len : 1;
1904}
1905EXPORT_SYMBOL_GPL(cgroup_taskset_size);
1906
1907
74a1166d
BB
1908/*
1909 * cgroup_task_migrate - move a task from one cgroup to another.
1910 *
d0b2fdd2 1911 * Must be called with cgroup_mutex and threadgroup locked.
74a1166d 1912 */
1e2ccd1c 1913static void cgroup_task_migrate(struct cgroup *oldcgrp,
61d1d219 1914 struct task_struct *tsk, struct css_set *newcg)
74a1166d
BB
1915{
1916 struct css_set *oldcg;
74a1166d
BB
1917
1918 /*
026085ef
MSB
1919 * We are synchronized through threadgroup_lock() against PF_EXITING
1920 * setting such that we can't race against cgroup_exit() changing the
1921 * css_set to init_css_set and dropping the old one.
74a1166d 1922 */
c84cdf75 1923 WARN_ON_ONCE(tsk->flags & PF_EXITING);
74a1166d 1924 oldcg = tsk->cgroups;
74a1166d 1925
74a1166d 1926 task_lock(tsk);
74a1166d
BB
1927 rcu_assign_pointer(tsk->cgroups, newcg);
1928 task_unlock(tsk);
1929
1930 /* Update the css_set linked lists if we're using them */
1931 write_lock(&css_set_lock);
1932 if (!list_empty(&tsk->cg_list))
1933 list_move(&tsk->cg_list, &newcg->tasks);
1934 write_unlock(&css_set_lock);
1935
1936 /*
1937 * We just gained a reference on oldcg by taking it from the task. As
1938 * trading it for newcg is protected by cgroup_mutex, we're safe to drop
1939 * it here; it will be freed under RCU.
1940 */
74a1166d 1941 set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1f5320d5 1942 put_css_set(oldcg);
74a1166d
BB
1943}
1944
a043e3b2 1945/**
081aa458 1946 * cgroup_attach_task - attach a task or a whole threadgroup to a cgroup
74a1166d 1947 * @cgrp: the cgroup to attach to
081aa458
LZ
1948 * @tsk: the task or the leader of the threadgroup to be attached
1949 * @threadgroup: attach the whole threadgroup?
74a1166d 1950 *
257058ae 1951 * Call holding cgroup_mutex and the group_rwsem of the leader. Will take
081aa458 1952 * task_lock of @tsk or each thread in the threadgroup individually in turn.
74a1166d 1953 */
47cfcd09
TH
1954static int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk,
1955 bool threadgroup)
74a1166d
BB
1956{
1957 int retval, i, group_size;
1958 struct cgroup_subsys *ss, *failed_ss = NULL;
74a1166d
BB
1959 struct cgroupfs_root *root = cgrp->root;
1960 /* threadgroup list cursor and array */
081aa458 1961 struct task_struct *leader = tsk;
134d3373 1962 struct task_and_cgroup *tc;
d846687d 1963 struct flex_array *group;
2f7ee569 1964 struct cgroup_taskset tset = { };
74a1166d
BB
1965
1966 /*
1967 * step 0: in order to do expensive, possibly blocking operations for
1968 * every thread, we cannot iterate the thread group list, since it needs
1969 * rcu or tasklist locked. instead, build an array of all threads in the
257058ae
TH
1970 * group - group_rwsem prevents new threads from appearing, and if
1971 * threads exit, this will just be an over-estimate.
74a1166d 1972 */
081aa458
LZ
1973 if (threadgroup)
1974 group_size = get_nr_threads(tsk);
1975 else
1976 group_size = 1;
d846687d 1977 /* flex_array supports very large thread-groups better than kmalloc. */
134d3373 1978 group = flex_array_alloc(sizeof(*tc), group_size, GFP_KERNEL);
74a1166d
BB
1979 if (!group)
1980 return -ENOMEM;
d846687d 1981 /* pre-allocate to guarantee space while iterating in rcu read-side. */
3ac1707a 1982 retval = flex_array_prealloc(group, 0, group_size, GFP_KERNEL);
d846687d
BB
1983 if (retval)
1984 goto out_free_group_list;
74a1166d 1985
74a1166d 1986 i = 0;
fb5d2b4c
MSB
1987 /*
1988 * Prevent freeing of tasks while we take a snapshot. Tasks that are
1989 * already PF_EXITING could be freed from underneath us unless we
1990 * take an rcu_read_lock.
1991 */
1992 rcu_read_lock();
74a1166d 1993 do {
134d3373
TH
1994 struct task_and_cgroup ent;
1995
cd3d0952
TH
1996 /* @tsk either already exited or can't exit until the end */
1997 if (tsk->flags & PF_EXITING)
1998 continue;
1999
74a1166d
BB
2000 /* as per above, nr_threads may decrease, but not increase. */
2001 BUG_ON(i >= group_size);
134d3373
TH
2002 ent.task = tsk;
2003 ent.cgrp = task_cgroup_from_root(tsk, root);
892a2b90
MSB
2004 /* nothing to do if this task is already in the cgroup */
2005 if (ent.cgrp == cgrp)
2006 continue;
61d1d219
MSB
2007 /*
2008 * saying GFP_ATOMIC has no effect here because we did prealloc
2009 * earlier, but it's good form to communicate our expectations.
2010 */
134d3373 2011 retval = flex_array_put(group, i, &ent, GFP_ATOMIC);
d846687d 2012 BUG_ON(retval != 0);
74a1166d 2013 i++;
081aa458
LZ
2014
2015 if (!threadgroup)
2016 break;
74a1166d 2017 } while_each_thread(leader, tsk);
fb5d2b4c 2018 rcu_read_unlock();
74a1166d
BB
2019 /* remember the number of threads in the array for later. */
2020 group_size = i;
2f7ee569
TH
2021 tset.tc_array = group;
2022 tset.tc_array_len = group_size;
74a1166d 2023
134d3373
TH
2024 /* methods shouldn't be called if no task is actually migrating */
2025 retval = 0;
892a2b90 2026 if (!group_size)
b07ef774 2027 goto out_free_group_list;
134d3373 2028
74a1166d
BB
2029 /*
2030 * step 1: check that we can legitimately attach to the cgroup.
2031 */
2032 for_each_subsys(root, ss) {
2033 if (ss->can_attach) {
761b3ef5 2034 retval = ss->can_attach(cgrp, &tset);
74a1166d
BB
2035 if (retval) {
2036 failed_ss = ss;
2037 goto out_cancel_attach;
2038 }
2039 }
74a1166d
BB
2040 }
2041
2042 /*
2043 * step 2: make sure css_sets exist for all threads to be migrated.
2044 * we use find_css_set, which allocates a new one if necessary.
2045 */
74a1166d 2046 for (i = 0; i < group_size; i++) {
134d3373 2047 tc = flex_array_get(group, i);
61d1d219
MSB
2048 tc->cg = find_css_set(tc->task->cgroups, cgrp);
2049 if (!tc->cg) {
2050 retval = -ENOMEM;
2051 goto out_put_css_set_refs;
74a1166d
BB
2052 }
2053 }
2054
2055 /*
494c167c
TH
2056 * step 3: now that we're guaranteed success wrt the css_sets,
2057 * proceed to move all tasks to the new cgroup. There are no
2058 * failure cases after here, so this is the commit point.
74a1166d 2059 */
74a1166d 2060 for (i = 0; i < group_size; i++) {
134d3373 2061 tc = flex_array_get(group, i);
1e2ccd1c 2062 cgroup_task_migrate(tc->cgrp, tc->task, tc->cg);
74a1166d
BB
2063 }
2064 /* nothing is sensitive to fork() after this point. */
2065
2066 /*
494c167c 2067 * step 4: do subsystem attach callbacks.
74a1166d
BB
2068 */
2069 for_each_subsys(root, ss) {
2070 if (ss->attach)
761b3ef5 2071 ss->attach(cgrp, &tset);
74a1166d
BB
2072 }
2073
2074 /*
2075 * step 5: success! and cleanup
2076 */
74a1166d 2077 retval = 0;
61d1d219
MSB
2078out_put_css_set_refs:
2079 if (retval) {
2080 for (i = 0; i < group_size; i++) {
2081 tc = flex_array_get(group, i);
2082 if (!tc->cg)
2083 break;
2084 put_css_set(tc->cg);
2085 }
74a1166d
BB
2086 }
2087out_cancel_attach:
74a1166d
BB
2088 if (retval) {
2089 for_each_subsys(root, ss) {
494c167c 2090 if (ss == failed_ss)
74a1166d 2091 break;
74a1166d 2092 if (ss->cancel_attach)
761b3ef5 2093 ss->cancel_attach(cgrp, &tset);
74a1166d
BB
2094 }
2095 }
74a1166d 2096out_free_group_list:
d846687d 2097 flex_array_free(group);
74a1166d
BB
2098 return retval;
2099}
2100
2101/*
2102 * Find the task_struct of the task to attach by vpid and pass it along to the
cd3d0952
TH
2103 * function to attach either it or all tasks in its threadgroup. Will lock
2104 * cgroup_mutex and threadgroup; may take task_lock of task.
bbcb81d0 2105 */
74a1166d 2106static int attach_task_by_pid(struct cgroup *cgrp, u64 pid, bool threadgroup)
bbcb81d0 2107{
bbcb81d0 2108 struct task_struct *tsk;
c69e8d9c 2109 const struct cred *cred = current_cred(), *tcred;
bbcb81d0
PM
2110 int ret;
2111
74a1166d
BB
2112 if (!cgroup_lock_live_group(cgrp))
2113 return -ENODEV;
2114
b78949eb
MSB
2115retry_find_task:
2116 rcu_read_lock();
bbcb81d0 2117 if (pid) {
73507f33 2118 tsk = find_task_by_vpid(pid);
74a1166d
BB
2119 if (!tsk) {
2120 rcu_read_unlock();
b78949eb
MSB
2121 ret= -ESRCH;
2122 goto out_unlock_cgroup;
bbcb81d0 2123 }
74a1166d
BB
2124 /*
2125 * even if we're attaching all tasks in the thread group, we
2126 * only need to check permissions on one of them.
2127 */
c69e8d9c 2128 tcred = __task_cred(tsk);
14a590c3
EB
2129 if (!uid_eq(cred->euid, GLOBAL_ROOT_UID) &&
2130 !uid_eq(cred->euid, tcred->uid) &&
2131 !uid_eq(cred->euid, tcred->suid)) {
c69e8d9c 2132 rcu_read_unlock();
b78949eb
MSB
2133 ret = -EACCES;
2134 goto out_unlock_cgroup;
bbcb81d0 2135 }
b78949eb
MSB
2136 } else
2137 tsk = current;
cd3d0952
TH
2138
2139 if (threadgroup)
b78949eb 2140 tsk = tsk->group_leader;
c4c27fbd
MG
2141
2142 /*
14a40ffc 2143 * Workqueue threads may acquire PF_NO_SETAFFINITY and become
c4c27fbd
MG
2144 * trapped in a cpuset, or RT worker may be born in a cgroup
2145 * with no rt_runtime allocated. Just say no.
2146 */
14a40ffc 2147 if (tsk == kthreadd_task || (tsk->flags & PF_NO_SETAFFINITY)) {
c4c27fbd
MG
2148 ret = -EINVAL;
2149 rcu_read_unlock();
2150 goto out_unlock_cgroup;
2151 }
2152
b78949eb
MSB
2153 get_task_struct(tsk);
2154 rcu_read_unlock();
2155
2156 threadgroup_lock(tsk);
2157 if (threadgroup) {
2158 if (!thread_group_leader(tsk)) {
2159 /*
2160 * a race with de_thread from another thread's exec()
2161 * may strip us of our leadership, if this happens,
2162 * there is no choice but to throw this task away and
2163 * try again; this is
2164 * "double-double-toil-and-trouble-check locking".
2165 */
2166 threadgroup_unlock(tsk);
2167 put_task_struct(tsk);
2168 goto retry_find_task;
2169 }
081aa458
LZ
2170 }
2171
2172 ret = cgroup_attach_task(cgrp, tsk, threadgroup);
2173
cd3d0952
TH
2174 threadgroup_unlock(tsk);
2175
bbcb81d0 2176 put_task_struct(tsk);
b78949eb 2177out_unlock_cgroup:
47cfcd09 2178 mutex_unlock(&cgroup_mutex);
bbcb81d0
PM
2179 return ret;
2180}
2181
7ae1bad9
TH
2182/**
2183 * cgroup_attach_task_all - attach task 'tsk' to all cgroups of task 'from'
2184 * @from: attach to all cgroups of a given task
2185 * @tsk: the task to be attached
2186 */
2187int cgroup_attach_task_all(struct task_struct *from, struct task_struct *tsk)
2188{
2189 struct cgroupfs_root *root;
2190 int retval = 0;
2191
47cfcd09 2192 mutex_lock(&cgroup_mutex);
7ae1bad9
TH
2193 for_each_active_root(root) {
2194 struct cgroup *from_cg = task_cgroup_from_root(from, root);
2195
2196 retval = cgroup_attach_task(from_cg, tsk, false);
2197 if (retval)
2198 break;
2199 }
47cfcd09 2200 mutex_unlock(&cgroup_mutex);
7ae1bad9
TH
2201
2202 return retval;
2203}
2204EXPORT_SYMBOL_GPL(cgroup_attach_task_all);
2205
af351026 2206static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid)
74a1166d
BB
2207{
2208 return attach_task_by_pid(cgrp, pid, false);
2209}
2210
2211static int cgroup_procs_write(struct cgroup *cgrp, struct cftype *cft, u64 tgid)
af351026 2212{
b78949eb 2213 return attach_task_by_pid(cgrp, tgid, true);
af351026
PM
2214}
2215
e788e066
PM
2216static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
2217 const char *buffer)
2218{
2219 BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
f4a2589f
EK
2220 if (strlen(buffer) >= PATH_MAX)
2221 return -EINVAL;
e788e066
PM
2222 if (!cgroup_lock_live_group(cgrp))
2223 return -ENODEV;
e25e2cbb 2224 mutex_lock(&cgroup_root_mutex);
e788e066 2225 strcpy(cgrp->root->release_agent_path, buffer);
e25e2cbb 2226 mutex_unlock(&cgroup_root_mutex);
47cfcd09 2227 mutex_unlock(&cgroup_mutex);
e788e066
PM
2228 return 0;
2229}
2230
2231static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
2232 struct seq_file *seq)
2233{
2234 if (!cgroup_lock_live_group(cgrp))
2235 return -ENODEV;
2236 seq_puts(seq, cgrp->root->release_agent_path);
2237 seq_putc(seq, '\n');
47cfcd09 2238 mutex_unlock(&cgroup_mutex);
e788e066
PM
2239 return 0;
2240}
2241
873fe09e
TH
2242static int cgroup_sane_behavior_show(struct cgroup *cgrp, struct cftype *cft,
2243 struct seq_file *seq)
2244{
2245 seq_printf(seq, "%d\n", cgroup_sane_behavior(cgrp));
e788e066
PM
2246 return 0;
2247}
2248
84eea842
PM
2249/* A buffer size big enough for numbers or short strings */
2250#define CGROUP_LOCAL_BUFFER_SIZE 64
2251
e73d2c61 2252static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
f4c753b7
PM
2253 struct file *file,
2254 const char __user *userbuf,
2255 size_t nbytes, loff_t *unused_ppos)
355e0c48 2256{
84eea842 2257 char buffer[CGROUP_LOCAL_BUFFER_SIZE];
355e0c48 2258 int retval = 0;
355e0c48
PM
2259 char *end;
2260
2261 if (!nbytes)
2262 return -EINVAL;
2263 if (nbytes >= sizeof(buffer))
2264 return -E2BIG;
2265 if (copy_from_user(buffer, userbuf, nbytes))
2266 return -EFAULT;
2267
2268 buffer[nbytes] = 0; /* nul-terminate */
e73d2c61 2269 if (cft->write_u64) {
478988d3 2270 u64 val = simple_strtoull(strstrip(buffer), &end, 0);
e73d2c61
PM
2271 if (*end)
2272 return -EINVAL;
2273 retval = cft->write_u64(cgrp, cft, val);
2274 } else {
478988d3 2275 s64 val = simple_strtoll(strstrip(buffer), &end, 0);
e73d2c61
PM
2276 if (*end)
2277 return -EINVAL;
2278 retval = cft->write_s64(cgrp, cft, val);
2279 }
355e0c48
PM
2280 if (!retval)
2281 retval = nbytes;
2282 return retval;
2283}
2284
db3b1497
PM
2285static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
2286 struct file *file,
2287 const char __user *userbuf,
2288 size_t nbytes, loff_t *unused_ppos)
2289{
84eea842 2290 char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
db3b1497
PM
2291 int retval = 0;
2292 size_t max_bytes = cft->max_write_len;
2293 char *buffer = local_buffer;
2294
2295 if (!max_bytes)
2296 max_bytes = sizeof(local_buffer) - 1;
2297 if (nbytes >= max_bytes)
2298 return -E2BIG;
2299 /* Allocate a dynamic buffer if we need one */
2300 if (nbytes >= sizeof(local_buffer)) {
2301 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
2302 if (buffer == NULL)
2303 return -ENOMEM;
2304 }
5a3eb9f6
LZ
2305 if (nbytes && copy_from_user(buffer, userbuf, nbytes)) {
2306 retval = -EFAULT;
2307 goto out;
2308 }
db3b1497
PM
2309
2310 buffer[nbytes] = 0; /* nul-terminate */
478988d3 2311 retval = cft->write_string(cgrp, cft, strstrip(buffer));
db3b1497
PM
2312 if (!retval)
2313 retval = nbytes;
5a3eb9f6 2314out:
db3b1497
PM
2315 if (buffer != local_buffer)
2316 kfree(buffer);
2317 return retval;
2318}
2319
ddbcc7e8
PM
2320static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
2321 size_t nbytes, loff_t *ppos)
2322{
2323 struct cftype *cft = __d_cft(file->f_dentry);
bd89aabc 2324 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
ddbcc7e8 2325
75139b82 2326 if (cgroup_is_removed(cgrp))
ddbcc7e8 2327 return -ENODEV;
355e0c48 2328 if (cft->write)
bd89aabc 2329 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
e73d2c61
PM
2330 if (cft->write_u64 || cft->write_s64)
2331 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
db3b1497
PM
2332 if (cft->write_string)
2333 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
d447ea2f
PE
2334 if (cft->trigger) {
2335 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
2336 return ret ? ret : nbytes;
2337 }
355e0c48 2338 return -EINVAL;
ddbcc7e8
PM
2339}
2340
f4c753b7
PM
2341static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
2342 struct file *file,
2343 char __user *buf, size_t nbytes,
2344 loff_t *ppos)
ddbcc7e8 2345{
84eea842 2346 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
f4c753b7 2347 u64 val = cft->read_u64(cgrp, cft);
ddbcc7e8
PM
2348 int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
2349
2350 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2351}
2352
e73d2c61
PM
2353static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
2354 struct file *file,
2355 char __user *buf, size_t nbytes,
2356 loff_t *ppos)
2357{
84eea842 2358 char tmp[CGROUP_LOCAL_BUFFER_SIZE];
e73d2c61
PM
2359 s64 val = cft->read_s64(cgrp, cft);
2360 int len = sprintf(tmp, "%lld\n", (long long) val);
2361
2362 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
2363}
2364
ddbcc7e8
PM
2365static ssize_t cgroup_file_read(struct file *file, char __user *buf,
2366 size_t nbytes, loff_t *ppos)
2367{
2368 struct cftype *cft = __d_cft(file->f_dentry);
bd89aabc 2369 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
ddbcc7e8 2370
75139b82 2371 if (cgroup_is_removed(cgrp))
ddbcc7e8
PM
2372 return -ENODEV;
2373
2374 if (cft->read)
bd89aabc 2375 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
f4c753b7
PM
2376 if (cft->read_u64)
2377 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
e73d2c61
PM
2378 if (cft->read_s64)
2379 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
ddbcc7e8
PM
2380 return -EINVAL;
2381}
2382
91796569
PM
2383/*
2384 * seqfile ops/methods for returning structured data. Currently just
2385 * supports string->u64 maps, but can be extended in future.
2386 */
2387
2388struct cgroup_seqfile_state {
2389 struct cftype *cft;
2390 struct cgroup *cgroup;
2391};
2392
2393static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
2394{
2395 struct seq_file *sf = cb->state;
2396 return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
2397}
2398
2399static int cgroup_seqfile_show(struct seq_file *m, void *arg)
2400{
2401 struct cgroup_seqfile_state *state = m->private;
2402 struct cftype *cft = state->cft;
29486df3
SH
2403 if (cft->read_map) {
2404 struct cgroup_map_cb cb = {
2405 .fill = cgroup_map_add,
2406 .state = m,
2407 };
2408 return cft->read_map(state->cgroup, cft, &cb);
2409 }
2410 return cft->read_seq_string(state->cgroup, cft, m);
91796569
PM
2411}
2412
96930a63 2413static int cgroup_seqfile_release(struct inode *inode, struct file *file)
91796569
PM
2414{
2415 struct seq_file *seq = file->private_data;
2416 kfree(seq->private);
2417 return single_release(inode, file);
2418}
2419
828c0950 2420static const struct file_operations cgroup_seqfile_operations = {
91796569 2421 .read = seq_read,
e788e066 2422 .write = cgroup_file_write,
91796569
PM
2423 .llseek = seq_lseek,
2424 .release = cgroup_seqfile_release,
2425};
2426
ddbcc7e8
PM
2427static int cgroup_file_open(struct inode *inode, struct file *file)
2428{
2429 int err;
2430 struct cftype *cft;
2431
2432 err = generic_file_open(inode, file);
2433 if (err)
2434 return err;
ddbcc7e8 2435 cft = __d_cft(file->f_dentry);
75139b82 2436
29486df3 2437 if (cft->read_map || cft->read_seq_string) {
91796569
PM
2438 struct cgroup_seqfile_state *state =
2439 kzalloc(sizeof(*state), GFP_USER);
2440 if (!state)
2441 return -ENOMEM;
2442 state->cft = cft;
2443 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
2444 file->f_op = &cgroup_seqfile_operations;
2445 err = single_open(file, cgroup_seqfile_show, state);
2446 if (err < 0)
2447 kfree(state);
2448 } else if (cft->open)
ddbcc7e8
PM
2449 err = cft->open(inode, file);
2450 else
2451 err = 0;
2452
2453 return err;
2454}
2455
2456static int cgroup_file_release(struct inode *inode, struct file *file)
2457{
2458 struct cftype *cft = __d_cft(file->f_dentry);
2459 if (cft->release)
2460 return cft->release(inode, file);
2461 return 0;
2462}
2463
2464/*
2465 * cgroup_rename - Only allow simple rename of directories in place.
2466 */
2467static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
2468 struct inode *new_dir, struct dentry *new_dentry)
2469{
65dff759
LZ
2470 int ret;
2471 struct cgroup_name *name, *old_name;
2472 struct cgroup *cgrp;
2473
2474 /*
2475 * It's convinient to use parent dir's i_mutex to protected
2476 * cgrp->name.
2477 */
2478 lockdep_assert_held(&old_dir->i_mutex);
2479
ddbcc7e8
PM
2480 if (!S_ISDIR(old_dentry->d_inode->i_mode))
2481 return -ENOTDIR;
2482 if (new_dentry->d_inode)
2483 return -EEXIST;
2484 if (old_dir != new_dir)
2485 return -EIO;
65dff759
LZ
2486
2487 cgrp = __d_cgrp(old_dentry);
2488
2489 name = cgroup_alloc_name(new_dentry);
2490 if (!name)
2491 return -ENOMEM;
2492
2493 ret = simple_rename(old_dir, old_dentry, new_dir, new_dentry);
2494 if (ret) {
2495 kfree(name);
2496 return ret;
2497 }
2498
2499 old_name = cgrp->name;
2500 rcu_assign_pointer(cgrp->name, name);
2501
2502 kfree_rcu(old_name, rcu_head);
2503 return 0;
ddbcc7e8
PM
2504}
2505
03b1cde6
AR
2506static struct simple_xattrs *__d_xattrs(struct dentry *dentry)
2507{
2508 if (S_ISDIR(dentry->d_inode->i_mode))
2509 return &__d_cgrp(dentry)->xattrs;
2510 else
712317ad 2511 return &__d_cfe(dentry)->xattrs;
03b1cde6
AR
2512}
2513
2514static inline int xattr_enabled(struct dentry *dentry)
2515{
2516 struct cgroupfs_root *root = dentry->d_sb->s_fs_info;
93438629 2517 return root->flags & CGRP_ROOT_XATTR;
03b1cde6
AR
2518}
2519
2520static bool is_valid_xattr(const char *name)
2521{
2522 if (!strncmp(name, XATTR_TRUSTED_PREFIX, XATTR_TRUSTED_PREFIX_LEN) ||
2523 !strncmp(name, XATTR_SECURITY_PREFIX, XATTR_SECURITY_PREFIX_LEN))
2524 return true;
2525 return false;
2526}
2527
2528static int cgroup_setxattr(struct dentry *dentry, const char *name,
2529 const void *val, size_t size, int flags)
2530{
2531 if (!xattr_enabled(dentry))
2532 return -EOPNOTSUPP;
2533 if (!is_valid_xattr(name))
2534 return -EINVAL;
2535 return simple_xattr_set(__d_xattrs(dentry), name, val, size, flags);
2536}
2537
2538static int cgroup_removexattr(struct dentry *dentry, const char *name)
2539{
2540 if (!xattr_enabled(dentry))
2541 return -EOPNOTSUPP;
2542 if (!is_valid_xattr(name))
2543 return -EINVAL;
2544 return simple_xattr_remove(__d_xattrs(dentry), name);
2545}
2546
2547static ssize_t cgroup_getxattr(struct dentry *dentry, const char *name,
2548 void *buf, size_t size)
2549{
2550 if (!xattr_enabled(dentry))
2551 return -EOPNOTSUPP;
2552 if (!is_valid_xattr(name))
2553 return -EINVAL;
2554 return simple_xattr_get(__d_xattrs(dentry), name, buf, size);
2555}
2556
2557static ssize_t cgroup_listxattr(struct dentry *dentry, char *buf, size_t size)
2558{
2559 if (!xattr_enabled(dentry))
2560 return -EOPNOTSUPP;
2561 return simple_xattr_list(__d_xattrs(dentry), buf, size);
2562}
2563
828c0950 2564static const struct file_operations cgroup_file_operations = {
ddbcc7e8
PM
2565 .read = cgroup_file_read,
2566 .write = cgroup_file_write,
2567 .llseek = generic_file_llseek,
2568 .open = cgroup_file_open,
2569 .release = cgroup_file_release,
2570};
2571
03b1cde6
AR
2572static const struct inode_operations cgroup_file_inode_operations = {
2573 .setxattr = cgroup_setxattr,
2574 .getxattr = cgroup_getxattr,
2575 .listxattr = cgroup_listxattr,
2576 .removexattr = cgroup_removexattr,
2577};
2578
6e1d5dcc 2579static const struct inode_operations cgroup_dir_inode_operations = {
c72a04e3 2580 .lookup = cgroup_lookup,
ddbcc7e8
PM
2581 .mkdir = cgroup_mkdir,
2582 .rmdir = cgroup_rmdir,
2583 .rename = cgroup_rename,
03b1cde6
AR
2584 .setxattr = cgroup_setxattr,
2585 .getxattr = cgroup_getxattr,
2586 .listxattr = cgroup_listxattr,
2587 .removexattr = cgroup_removexattr,
ddbcc7e8
PM
2588};
2589
00cd8dd3 2590static struct dentry *cgroup_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags)
c72a04e3
AV
2591{
2592 if (dentry->d_name.len > NAME_MAX)
2593 return ERR_PTR(-ENAMETOOLONG);
2594 d_add(dentry, NULL);
2595 return NULL;
2596}
2597
0dea1168
KS
2598/*
2599 * Check if a file is a control file
2600 */
2601static inline struct cftype *__file_cft(struct file *file)
2602{
496ad9aa 2603 if (file_inode(file)->i_fop != &cgroup_file_operations)
0dea1168
KS
2604 return ERR_PTR(-EINVAL);
2605 return __d_cft(file->f_dentry);
2606}
2607
a5e7ed32 2608static int cgroup_create_file(struct dentry *dentry, umode_t mode,
5adcee1d
NP
2609 struct super_block *sb)
2610{
ddbcc7e8
PM
2611 struct inode *inode;
2612
2613 if (!dentry)
2614 return -ENOENT;
2615 if (dentry->d_inode)
2616 return -EEXIST;
2617
2618 inode = cgroup_new_inode(mode, sb);
2619 if (!inode)
2620 return -ENOMEM;
2621
2622 if (S_ISDIR(mode)) {
2623 inode->i_op = &cgroup_dir_inode_operations;
2624 inode->i_fop = &simple_dir_operations;
2625
2626 /* start off with i_nlink == 2 (for "." entry) */
2627 inc_nlink(inode);
28fd6f30 2628 inc_nlink(dentry->d_parent->d_inode);
ddbcc7e8 2629
b8a2df6a
TH
2630 /*
2631 * Control reaches here with cgroup_mutex held.
2632 * @inode->i_mutex should nest outside cgroup_mutex but we
2633 * want to populate it immediately without releasing
2634 * cgroup_mutex. As @inode isn't visible to anyone else
2635 * yet, trylock will always succeed without affecting
2636 * lockdep checks.
2637 */
2638 WARN_ON_ONCE(!mutex_trylock(&inode->i_mutex));
ddbcc7e8
PM
2639 } else if (S_ISREG(mode)) {
2640 inode->i_size = 0;
2641 inode->i_fop = &cgroup_file_operations;
03b1cde6 2642 inode->i_op = &cgroup_file_inode_operations;
ddbcc7e8 2643 }
ddbcc7e8
PM
2644 d_instantiate(dentry, inode);
2645 dget(dentry); /* Extra count - pin the dentry in core */
2646 return 0;
2647}
2648
099fca32
LZ
2649/**
2650 * cgroup_file_mode - deduce file mode of a control file
2651 * @cft: the control file in question
2652 *
2653 * returns cft->mode if ->mode is not 0
2654 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler
2655 * returns S_IRUGO if it has only a read handler
2656 * returns S_IWUSR if it has only a write hander
2657 */
a5e7ed32 2658static umode_t cgroup_file_mode(const struct cftype *cft)
099fca32 2659{
a5e7ed32 2660 umode_t mode = 0;
099fca32
LZ
2661
2662 if (cft->mode)
2663 return cft->mode;
2664
2665 if (cft->read || cft->read_u64 || cft->read_s64 ||
2666 cft->read_map || cft->read_seq_string)
2667 mode |= S_IRUGO;
2668
2669 if (cft->write || cft->write_u64 || cft->write_s64 ||
2670 cft->write_string || cft->trigger)
2671 mode |= S_IWUSR;
2672
2673 return mode;
2674}
2675
db0416b6 2676static int cgroup_add_file(struct cgroup *cgrp, struct cgroup_subsys *subsys,
03b1cde6 2677 struct cftype *cft)
ddbcc7e8 2678{
bd89aabc 2679 struct dentry *dir = cgrp->dentry;
05ef1d7c 2680 struct cgroup *parent = __d_cgrp(dir);
ddbcc7e8 2681 struct dentry *dentry;
05ef1d7c 2682 struct cfent *cfe;
ddbcc7e8 2683 int error;
a5e7ed32 2684 umode_t mode;
ddbcc7e8 2685 char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
8e3f6541 2686
93438629 2687 if (subsys && !(cgrp->root->flags & CGRP_ROOT_NOPREFIX)) {
ddbcc7e8
PM
2688 strcpy(name, subsys->name);
2689 strcat(name, ".");
2690 }
2691 strcat(name, cft->name);
05ef1d7c 2692
ddbcc7e8 2693 BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
05ef1d7c
TH
2694
2695 cfe = kzalloc(sizeof(*cfe), GFP_KERNEL);
2696 if (!cfe)
2697 return -ENOMEM;
2698
ddbcc7e8 2699 dentry = lookup_one_len(name, dir, strlen(name));
05ef1d7c 2700 if (IS_ERR(dentry)) {
ddbcc7e8 2701 error = PTR_ERR(dentry);
05ef1d7c
TH
2702 goto out;
2703 }
2704
d6cbf35d
LZ
2705 cfe->type = (void *)cft;
2706 cfe->dentry = dentry;
2707 dentry->d_fsdata = cfe;
2708 simple_xattrs_init(&cfe->xattrs);
2709
05ef1d7c
TH
2710 mode = cgroup_file_mode(cft);
2711 error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb);
2712 if (!error) {
05ef1d7c
TH
2713 list_add_tail(&cfe->node, &parent->files);
2714 cfe = NULL;
2715 }
2716 dput(dentry);
2717out:
2718 kfree(cfe);
ddbcc7e8
PM
2719 return error;
2720}
2721
79578621 2722static int cgroup_addrm_files(struct cgroup *cgrp, struct cgroup_subsys *subsys,
03b1cde6 2723 struct cftype cfts[], bool is_add)
ddbcc7e8 2724{
03b1cde6 2725 struct cftype *cft;
db0416b6
TH
2726 int err, ret = 0;
2727
2728 for (cft = cfts; cft->name[0] != '\0'; cft++) {
f33fddc2 2729 /* does cft->flags tell us to skip this file on @cgrp? */
873fe09e
TH
2730 if ((cft->flags & CFTYPE_INSANE) && cgroup_sane_behavior(cgrp))
2731 continue;
f33fddc2
G
2732 if ((cft->flags & CFTYPE_NOT_ON_ROOT) && !cgrp->parent)
2733 continue;
2734 if ((cft->flags & CFTYPE_ONLY_ON_ROOT) && cgrp->parent)
2735 continue;
2736
2739d3cc 2737 if (is_add) {
79578621 2738 err = cgroup_add_file(cgrp, subsys, cft);
2739d3cc
LZ
2739 if (err)
2740 pr_warn("cgroup_addrm_files: failed to add %s, err=%d\n",
2741 cft->name, err);
db0416b6 2742 ret = err;
2739d3cc
LZ
2743 } else {
2744 cgroup_rm_file(cgrp, cft);
db0416b6 2745 }
ddbcc7e8 2746 }
db0416b6 2747 return ret;
ddbcc7e8
PM
2748}
2749
8e3f6541
TH
2750static DEFINE_MUTEX(cgroup_cft_mutex);
2751
2752static void cgroup_cfts_prepare(void)
2753 __acquires(&cgroup_cft_mutex) __acquires(&cgroup_mutex)
2754{
2755 /*
2756 * Thanks to the entanglement with vfs inode locking, we can't walk
2757 * the existing cgroups under cgroup_mutex and create files.
2758 * Instead, we increment reference on all cgroups and build list of
2759 * them using @cgrp->cft_q_node. Grab cgroup_cft_mutex to ensure
2760 * exclusive access to the field.
2761 */
2762 mutex_lock(&cgroup_cft_mutex);
2763 mutex_lock(&cgroup_mutex);
2764}
2765
2766static void cgroup_cfts_commit(struct cgroup_subsys *ss,
03b1cde6 2767 struct cftype *cfts, bool is_add)
8e3f6541
TH
2768 __releases(&cgroup_mutex) __releases(&cgroup_cft_mutex)
2769{
2770 LIST_HEAD(pending);
2771 struct cgroup *cgrp, *n;
8e3f6541
TH
2772
2773 /* %NULL @cfts indicates abort and don't bother if @ss isn't attached */
2774 if (cfts && ss->root != &rootnode) {
2775 list_for_each_entry(cgrp, &ss->root->allcg_list, allcg_node) {
2776 dget(cgrp->dentry);
2777 list_add_tail(&cgrp->cft_q_node, &pending);
2778 }
2779 }
2780
2781 mutex_unlock(&cgroup_mutex);
2782
2783 /*
2784 * All new cgroups will see @cfts update on @ss->cftsets. Add/rm
2785 * files for all cgroups which were created before.
2786 */
2787 list_for_each_entry_safe(cgrp, n, &pending, cft_q_node) {
2788 struct inode *inode = cgrp->dentry->d_inode;
2789
2790 mutex_lock(&inode->i_mutex);
2791 mutex_lock(&cgroup_mutex);
2792 if (!cgroup_is_removed(cgrp))
79578621 2793 cgroup_addrm_files(cgrp, ss, cfts, is_add);
8e3f6541
TH
2794 mutex_unlock(&cgroup_mutex);
2795 mutex_unlock(&inode->i_mutex);
2796
2797 list_del_init(&cgrp->cft_q_node);
2798 dput(cgrp->dentry);
2799 }
2800
2801 mutex_unlock(&cgroup_cft_mutex);
2802}
2803
2804/**
2805 * cgroup_add_cftypes - add an array of cftypes to a subsystem
2806 * @ss: target cgroup subsystem
2807 * @cfts: zero-length name terminated array of cftypes
2808 *
2809 * Register @cfts to @ss. Files described by @cfts are created for all
2810 * existing cgroups to which @ss is attached and all future cgroups will
2811 * have them too. This function can be called anytime whether @ss is
2812 * attached or not.
2813 *
2814 * Returns 0 on successful registration, -errno on failure. Note that this
2815 * function currently returns 0 as long as @cfts registration is successful
2816 * even if some file creation attempts on existing cgroups fail.
2817 */
03b1cde6 2818int cgroup_add_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
8e3f6541
TH
2819{
2820 struct cftype_set *set;
2821
2822 set = kzalloc(sizeof(*set), GFP_KERNEL);
2823 if (!set)
2824 return -ENOMEM;
2825
2826 cgroup_cfts_prepare();
2827 set->cfts = cfts;
2828 list_add_tail(&set->node, &ss->cftsets);
79578621 2829 cgroup_cfts_commit(ss, cfts, true);
8e3f6541
TH
2830
2831 return 0;
2832}
2833EXPORT_SYMBOL_GPL(cgroup_add_cftypes);
2834
79578621
TH
2835/**
2836 * cgroup_rm_cftypes - remove an array of cftypes from a subsystem
2837 * @ss: target cgroup subsystem
2838 * @cfts: zero-length name terminated array of cftypes
2839 *
2840 * Unregister @cfts from @ss. Files described by @cfts are removed from
2841 * all existing cgroups to which @ss is attached and all future cgroups
2842 * won't have them either. This function can be called anytime whether @ss
2843 * is attached or not.
2844 *
2845 * Returns 0 on successful unregistration, -ENOENT if @cfts is not
2846 * registered with @ss.
2847 */
03b1cde6 2848int cgroup_rm_cftypes(struct cgroup_subsys *ss, struct cftype *cfts)
79578621
TH
2849{
2850 struct cftype_set *set;
2851
2852 cgroup_cfts_prepare();
2853
2854 list_for_each_entry(set, &ss->cftsets, node) {
2855 if (set->cfts == cfts) {
2856 list_del_init(&set->node);
2857 cgroup_cfts_commit(ss, cfts, false);
2858 return 0;
2859 }
2860 }
2861
2862 cgroup_cfts_commit(ss, NULL, false);
2863 return -ENOENT;
2864}
2865
a043e3b2
LZ
2866/**
2867 * cgroup_task_count - count the number of tasks in a cgroup.
2868 * @cgrp: the cgroup in question
2869 *
2870 * Return the number of tasks in the cgroup.
2871 */
bd89aabc 2872int cgroup_task_count(const struct cgroup *cgrp)
bbcb81d0
PM
2873{
2874 int count = 0;
71cbb949 2875 struct cg_cgroup_link *link;
817929ec
PM
2876
2877 read_lock(&css_set_lock);
71cbb949 2878 list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
146aa1bd 2879 count += atomic_read(&link->cg->refcount);
817929ec
PM
2880 }
2881 read_unlock(&css_set_lock);
bbcb81d0
PM
2882 return count;
2883}
2884
817929ec
PM
2885/*
2886 * Advance a list_head iterator. The iterator should be positioned at
2887 * the start of a css_set
2888 */
bd89aabc 2889static void cgroup_advance_iter(struct cgroup *cgrp,
7717f7ba 2890 struct cgroup_iter *it)
817929ec
PM
2891{
2892 struct list_head *l = it->cg_link;
2893 struct cg_cgroup_link *link;
2894 struct css_set *cg;
2895
2896 /* Advance to the next non-empty css_set */
2897 do {
2898 l = l->next;
bd89aabc 2899 if (l == &cgrp->css_sets) {
817929ec
PM
2900 it->cg_link = NULL;
2901 return;
2902 }
bd89aabc 2903 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
817929ec
PM
2904 cg = link->cg;
2905 } while (list_empty(&cg->tasks));
2906 it->cg_link = l;
2907 it->task = cg->tasks.next;
2908}
2909
31a7df01
CW
2910/*
2911 * To reduce the fork() overhead for systems that are not actually
2912 * using their cgroups capability, we don't maintain the lists running
2913 * through each css_set to its tasks until we see the list actually
2914 * used - in other words after the first call to cgroup_iter_start().
31a7df01 2915 */
3df91fe3 2916static void cgroup_enable_task_cg_lists(void)
31a7df01
CW
2917{
2918 struct task_struct *p, *g;
2919 write_lock(&css_set_lock);
2920 use_task_css_set_links = 1;
3ce3230a
FW
2921 /*
2922 * We need tasklist_lock because RCU is not safe against
2923 * while_each_thread(). Besides, a forking task that has passed
2924 * cgroup_post_fork() without seeing use_task_css_set_links = 1
2925 * is not guaranteed to have its child immediately visible in the
2926 * tasklist if we walk through it with RCU.
2927 */
2928 read_lock(&tasklist_lock);
31a7df01
CW
2929 do_each_thread(g, p) {
2930 task_lock(p);
0e04388f
LZ
2931 /*
2932 * We should check if the process is exiting, otherwise
2933 * it will race with cgroup_exit() in that the list
2934 * entry won't be deleted though the process has exited.
2935 */
2936 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
31a7df01
CW
2937 list_add(&p->cg_list, &p->cgroups->tasks);
2938 task_unlock(p);
2939 } while_each_thread(g, p);
3ce3230a 2940 read_unlock(&tasklist_lock);
31a7df01
CW
2941 write_unlock(&css_set_lock);
2942}
2943
574bd9f7
TH
2944/**
2945 * cgroup_next_descendant_pre - find the next descendant for pre-order walk
2946 * @pos: the current position (%NULL to initiate traversal)
2947 * @cgroup: cgroup whose descendants to walk
2948 *
2949 * To be used by cgroup_for_each_descendant_pre(). Find the next
2950 * descendant to visit for pre-order traversal of @cgroup's descendants.
2951 */
2952struct cgroup *cgroup_next_descendant_pre(struct cgroup *pos,
2953 struct cgroup *cgroup)
2954{
2955 struct cgroup *next;
2956
2957 WARN_ON_ONCE(!rcu_read_lock_held());
2958
2959 /* if first iteration, pretend we just visited @cgroup */
7805d000 2960 if (!pos)
574bd9f7 2961 pos = cgroup;
574bd9f7
TH
2962
2963 /* visit the first child if exists */
2964 next = list_first_or_null_rcu(&pos->children, struct cgroup, sibling);
2965 if (next)
2966 return next;
2967
2968 /* no child, visit my or the closest ancestor's next sibling */
7805d000 2969 while (pos != cgroup) {
574bd9f7
TH
2970 next = list_entry_rcu(pos->sibling.next, struct cgroup,
2971 sibling);
2972 if (&next->sibling != &pos->parent->children)
2973 return next;
2974
2975 pos = pos->parent;
7805d000 2976 }
574bd9f7
TH
2977
2978 return NULL;
2979}
2980EXPORT_SYMBOL_GPL(cgroup_next_descendant_pre);
2981
12a9d2fe
TH
2982/**
2983 * cgroup_rightmost_descendant - return the rightmost descendant of a cgroup
2984 * @pos: cgroup of interest
2985 *
2986 * Return the rightmost descendant of @pos. If there's no descendant,
2987 * @pos is returned. This can be used during pre-order traversal to skip
2988 * subtree of @pos.
2989 */
2990struct cgroup *cgroup_rightmost_descendant(struct cgroup *pos)
2991{
2992 struct cgroup *last, *tmp;
2993
2994 WARN_ON_ONCE(!rcu_read_lock_held());
2995
2996 do {
2997 last = pos;
2998 /* ->prev isn't RCU safe, walk ->next till the end */
2999 pos = NULL;
3000 list_for_each_entry_rcu(tmp, &last->children, sibling)
3001 pos = tmp;
3002 } while (pos);
3003
3004 return last;
3005}
3006EXPORT_SYMBOL_GPL(cgroup_rightmost_descendant);
3007
574bd9f7
TH
3008static struct cgroup *cgroup_leftmost_descendant(struct cgroup *pos)
3009{
3010 struct cgroup *last;
3011
3012 do {
3013 last = pos;
3014 pos = list_first_or_null_rcu(&pos->children, struct cgroup,
3015 sibling);
3016 } while (pos);
3017
3018 return last;
3019}
3020
3021/**
3022 * cgroup_next_descendant_post - find the next descendant for post-order walk
3023 * @pos: the current position (%NULL to initiate traversal)
3024 * @cgroup: cgroup whose descendants to walk
3025 *
3026 * To be used by cgroup_for_each_descendant_post(). Find the next
3027 * descendant to visit for post-order traversal of @cgroup's descendants.
3028 */
3029struct cgroup *cgroup_next_descendant_post(struct cgroup *pos,
3030 struct cgroup *cgroup)
3031{
3032 struct cgroup *next;
3033
3034 WARN_ON_ONCE(!rcu_read_lock_held());
3035
3036 /* if first iteration, visit the leftmost descendant */
3037 if (!pos) {
3038 next = cgroup_leftmost_descendant(cgroup);
3039 return next != cgroup ? next : NULL;
3040 }
3041
3042 /* if there's an unvisited sibling, visit its leftmost descendant */
3043 next = list_entry_rcu(pos->sibling.next, struct cgroup, sibling);
3044 if (&next->sibling != &pos->parent->children)
3045 return cgroup_leftmost_descendant(next);
3046
3047 /* no sibling left, visit parent */
3048 next = pos->parent;
3049 return next != cgroup ? next : NULL;
3050}
3051EXPORT_SYMBOL_GPL(cgroup_next_descendant_post);
3052
bd89aabc 3053void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
c6ca5750 3054 __acquires(css_set_lock)
817929ec
PM
3055{
3056 /*
3057 * The first time anyone tries to iterate across a cgroup,
3058 * we need to enable the list linking each css_set to its
3059 * tasks, and fix up all existing tasks.
3060 */
31a7df01
CW
3061 if (!use_task_css_set_links)
3062 cgroup_enable_task_cg_lists();
3063
817929ec 3064 read_lock(&css_set_lock);
bd89aabc
PM
3065 it->cg_link = &cgrp->css_sets;
3066 cgroup_advance_iter(cgrp, it);
817929ec
PM
3067}
3068
bd89aabc 3069struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
817929ec
PM
3070 struct cgroup_iter *it)
3071{
3072 struct task_struct *res;
3073 struct list_head *l = it->task;
2019f634 3074 struct cg_cgroup_link *link;
817929ec
PM
3075
3076 /* If the iterator cg is NULL, we have no tasks */
3077 if (!it->cg_link)
3078 return NULL;
3079 res = list_entry(l, struct task_struct, cg_list);
3080 /* Advance iterator to find next entry */
3081 l = l->next;
2019f634
LJ
3082 link = list_entry(it->cg_link, struct cg_cgroup_link, cgrp_link_list);
3083 if (l == &link->cg->tasks) {
817929ec
PM
3084 /* We reached the end of this task list - move on to
3085 * the next cg_cgroup_link */
bd89aabc 3086 cgroup_advance_iter(cgrp, it);
817929ec
PM
3087 } else {
3088 it->task = l;
3089 }
3090 return res;
3091}
3092
bd89aabc 3093void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
c6ca5750 3094 __releases(css_set_lock)
817929ec
PM
3095{
3096 read_unlock(&css_set_lock);
3097}
3098
31a7df01
CW
3099static inline int started_after_time(struct task_struct *t1,
3100 struct timespec *time,
3101 struct task_struct *t2)
3102{
3103 int start_diff = timespec_compare(&t1->start_time, time);
3104 if (start_diff > 0) {
3105 return 1;
3106 } else if (start_diff < 0) {
3107 return 0;
3108 } else {
3109 /*
3110 * Arbitrarily, if two processes started at the same
3111 * time, we'll say that the lower pointer value
3112 * started first. Note that t2 may have exited by now
3113 * so this may not be a valid pointer any longer, but
3114 * that's fine - it still serves to distinguish
3115 * between two tasks started (effectively) simultaneously.
3116 */
3117 return t1 > t2;
3118 }
3119}
3120
3121/*
3122 * This function is a callback from heap_insert() and is used to order
3123 * the heap.
3124 * In this case we order the heap in descending task start time.
3125 */
3126static inline int started_after(void *p1, void *p2)
3127{
3128 struct task_struct *t1 = p1;
3129 struct task_struct *t2 = p2;
3130 return started_after_time(t1, &t2->start_time, t2);
3131}
3132
3133/**
3134 * cgroup_scan_tasks - iterate though all the tasks in a cgroup
3135 * @scan: struct cgroup_scanner containing arguments for the scan
3136 *
3137 * Arguments include pointers to callback functions test_task() and
3138 * process_task().
3139 * Iterate through all the tasks in a cgroup, calling test_task() for each,
3140 * and if it returns true, call process_task() for it also.
3141 * The test_task pointer may be NULL, meaning always true (select all tasks).
3142 * Effectively duplicates cgroup_iter_{start,next,end}()
3143 * but does not lock css_set_lock for the call to process_task().
3144 * The struct cgroup_scanner may be embedded in any structure of the caller's
3145 * creation.
3146 * It is guaranteed that process_task() will act on every task that
3147 * is a member of the cgroup for the duration of this call. This
3148 * function may or may not call process_task() for tasks that exit
3149 * or move to a different cgroup during the call, or are forked or
3150 * move into the cgroup during the call.
3151 *
3152 * Note that test_task() may be called with locks held, and may in some
3153 * situations be called multiple times for the same task, so it should
3154 * be cheap.
3155 * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
3156 * pre-allocated and will be used for heap operations (and its "gt" member will
3157 * be overwritten), else a temporary heap will be used (allocation of which
3158 * may cause this function to fail).
3159 */
3160int cgroup_scan_tasks(struct cgroup_scanner *scan)
3161{
3162 int retval, i;
3163 struct cgroup_iter it;
3164 struct task_struct *p, *dropped;
3165 /* Never dereference latest_task, since it's not refcounted */
3166 struct task_struct *latest_task = NULL;
3167 struct ptr_heap tmp_heap;
3168 struct ptr_heap *heap;
3169 struct timespec latest_time = { 0, 0 };
3170
3171 if (scan->heap) {
3172 /* The caller supplied our heap and pre-allocated its memory */
3173 heap = scan->heap;
3174 heap->gt = &started_after;
3175 } else {
3176 /* We need to allocate our own heap memory */
3177 heap = &tmp_heap;
3178 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
3179 if (retval)
3180 /* cannot allocate the heap */
3181 return retval;
3182 }
3183
3184 again:
3185 /*
3186 * Scan tasks in the cgroup, using the scanner's "test_task" callback
3187 * to determine which are of interest, and using the scanner's
3188 * "process_task" callback to process any of them that need an update.
3189 * Since we don't want to hold any locks during the task updates,
3190 * gather tasks to be processed in a heap structure.
3191 * The heap is sorted by descending task start time.
3192 * If the statically-sized heap fills up, we overflow tasks that
3193 * started later, and in future iterations only consider tasks that
3194 * started after the latest task in the previous pass. This
3195 * guarantees forward progress and that we don't miss any tasks.
3196 */
3197 heap->size = 0;
3198 cgroup_iter_start(scan->cg, &it);
3199 while ((p = cgroup_iter_next(scan->cg, &it))) {
3200 /*
3201 * Only affect tasks that qualify per the caller's callback,
3202 * if he provided one
3203 */
3204 if (scan->test_task && !scan->test_task(p, scan))
3205 continue;
3206 /*
3207 * Only process tasks that started after the last task
3208 * we processed
3209 */
3210 if (!started_after_time(p, &latest_time, latest_task))
3211 continue;
3212 dropped = heap_insert(heap, p);
3213 if (dropped == NULL) {
3214 /*
3215 * The new task was inserted; the heap wasn't
3216 * previously full
3217 */
3218 get_task_struct(p);
3219 } else if (dropped != p) {
3220 /*
3221 * The new task was inserted, and pushed out a
3222 * different task
3223 */
3224 get_task_struct(p);
3225 put_task_struct(dropped);
3226 }
3227 /*
3228 * Else the new task was newer than anything already in
3229 * the heap and wasn't inserted
3230 */
3231 }
3232 cgroup_iter_end(scan->cg, &it);
3233
3234 if (heap->size) {
3235 for (i = 0; i < heap->size; i++) {
4fe91d51 3236 struct task_struct *q = heap->ptrs[i];
31a7df01 3237 if (i == 0) {
4fe91d51
PJ
3238 latest_time = q->start_time;
3239 latest_task = q;
31a7df01
CW
3240 }
3241 /* Process the task per the caller's callback */
4fe91d51
PJ
3242 scan->process_task(q, scan);
3243 put_task_struct(q);
31a7df01
CW
3244 }
3245 /*
3246 * If we had to process any tasks at all, scan again
3247 * in case some of them were in the middle of forking
3248 * children that didn't get processed.
3249 * Not the most efficient way to do it, but it avoids
3250 * having to take callback_mutex in the fork path
3251 */
3252 goto again;
3253 }
3254 if (heap == &tmp_heap)
3255 heap_free(&tmp_heap);
3256 return 0;
3257}
3258
8cc99345
TH
3259static void cgroup_transfer_one_task(struct task_struct *task,
3260 struct cgroup_scanner *scan)
3261{
3262 struct cgroup *new_cgroup = scan->data;
3263
47cfcd09 3264 mutex_lock(&cgroup_mutex);
8cc99345 3265 cgroup_attach_task(new_cgroup, task, false);
47cfcd09 3266 mutex_unlock(&cgroup_mutex);
8cc99345
TH
3267}
3268
3269/**
3270 * cgroup_trasnsfer_tasks - move tasks from one cgroup to another
3271 * @to: cgroup to which the tasks will be moved
3272 * @from: cgroup in which the tasks currently reside
3273 */
3274int cgroup_transfer_tasks(struct cgroup *to, struct cgroup *from)
3275{
3276 struct cgroup_scanner scan;
3277
3278 scan.cg = from;
3279 scan.test_task = NULL; /* select all tasks in cgroup */
3280 scan.process_task = cgroup_transfer_one_task;
3281 scan.heap = NULL;
3282 scan.data = to;
3283
3284 return cgroup_scan_tasks(&scan);
3285}
3286
bbcb81d0 3287/*
102a775e 3288 * Stuff for reading the 'tasks'/'procs' files.
bbcb81d0
PM
3289 *
3290 * Reading this file can return large amounts of data if a cgroup has
3291 * *lots* of attached tasks. So it may need several calls to read(),
3292 * but we cannot guarantee that the information we produce is correct
3293 * unless we produce it entirely atomically.
3294 *
bbcb81d0 3295 */
bbcb81d0 3296
24528255
LZ
3297/* which pidlist file are we talking about? */
3298enum cgroup_filetype {
3299 CGROUP_FILE_PROCS,
3300 CGROUP_FILE_TASKS,
3301};
3302
3303/*
3304 * A pidlist is a list of pids that virtually represents the contents of one
3305 * of the cgroup files ("procs" or "tasks"). We keep a list of such pidlists,
3306 * a pair (one each for procs, tasks) for each pid namespace that's relevant
3307 * to the cgroup.
3308 */
3309struct cgroup_pidlist {
3310 /*
3311 * used to find which pidlist is wanted. doesn't change as long as
3312 * this particular list stays in the list.
3313 */
3314 struct { enum cgroup_filetype type; struct pid_namespace *ns; } key;
3315 /* array of xids */
3316 pid_t *list;
3317 /* how many elements the above list has */
3318 int length;
3319 /* how many files are using the current array */
3320 int use_count;
3321 /* each of these stored in a list by its cgroup */
3322 struct list_head links;
3323 /* pointer to the cgroup we belong to, for list removal purposes */
3324 struct cgroup *owner;
3325 /* protects the other fields */
3326 struct rw_semaphore mutex;
3327};
3328
d1d9fd33
BB
3329/*
3330 * The following two functions "fix" the issue where there are more pids
3331 * than kmalloc will give memory for; in such cases, we use vmalloc/vfree.
3332 * TODO: replace with a kernel-wide solution to this problem
3333 */
3334#define PIDLIST_TOO_LARGE(c) ((c) * sizeof(pid_t) > (PAGE_SIZE * 2))
3335static void *pidlist_allocate(int count)
3336{
3337 if (PIDLIST_TOO_LARGE(count))
3338 return vmalloc(count * sizeof(pid_t));
3339 else
3340 return kmalloc(count * sizeof(pid_t), GFP_KERNEL);
3341}
3342static void pidlist_free(void *p)
3343{
3344 if (is_vmalloc_addr(p))
3345 vfree(p);
3346 else
3347 kfree(p);
3348}
d1d9fd33 3349
bbcb81d0 3350/*
102a775e 3351 * pidlist_uniq - given a kmalloc()ed list, strip out all duplicate entries
6ee211ad 3352 * Returns the number of unique elements.
bbcb81d0 3353 */
6ee211ad 3354static int pidlist_uniq(pid_t *list, int length)
bbcb81d0 3355{
102a775e 3356 int src, dest = 1;
102a775e
BB
3357
3358 /*
3359 * we presume the 0th element is unique, so i starts at 1. trivial
3360 * edge cases first; no work needs to be done for either
3361 */
3362 if (length == 0 || length == 1)
3363 return length;
3364 /* src and dest walk down the list; dest counts unique elements */
3365 for (src = 1; src < length; src++) {
3366 /* find next unique element */
3367 while (list[src] == list[src-1]) {
3368 src++;
3369 if (src == length)
3370 goto after;
3371 }
3372 /* dest always points to where the next unique element goes */
3373 list[dest] = list[src];
3374 dest++;
3375 }
3376after:
102a775e
BB
3377 return dest;
3378}
3379
3380static int cmppid(const void *a, const void *b)
3381{
3382 return *(pid_t *)a - *(pid_t *)b;
3383}
3384
72a8cb30
BB
3385/*
3386 * find the appropriate pidlist for our purpose (given procs vs tasks)
3387 * returns with the lock on that pidlist already held, and takes care
3388 * of the use count, or returns NULL with no locks held if we're out of
3389 * memory.
3390 */
3391static struct cgroup_pidlist *cgroup_pidlist_find(struct cgroup *cgrp,
3392 enum cgroup_filetype type)
3393{
3394 struct cgroup_pidlist *l;
3395 /* don't need task_nsproxy() if we're looking at ourself */
17cf22c3 3396 struct pid_namespace *ns = task_active_pid_ns(current);
b70cc5fd 3397
72a8cb30
BB
3398 /*
3399 * We can't drop the pidlist_mutex before taking the l->mutex in case
3400 * the last ref-holder is trying to remove l from the list at the same
3401 * time. Holding the pidlist_mutex precludes somebody taking whichever
3402 * list we find out from under us - compare release_pid_array().
3403 */
3404 mutex_lock(&cgrp->pidlist_mutex);
3405 list_for_each_entry(l, &cgrp->pidlists, links) {
3406 if (l->key.type == type && l->key.ns == ns) {
72a8cb30
BB
3407 /* make sure l doesn't vanish out from under us */
3408 down_write(&l->mutex);
3409 mutex_unlock(&cgrp->pidlist_mutex);
72a8cb30
BB
3410 return l;
3411 }
3412 }
3413 /* entry not found; create a new one */
3414 l = kmalloc(sizeof(struct cgroup_pidlist), GFP_KERNEL);
3415 if (!l) {
3416 mutex_unlock(&cgrp->pidlist_mutex);
72a8cb30
BB
3417 return l;
3418 }
3419 init_rwsem(&l->mutex);
3420 down_write(&l->mutex);
3421 l->key.type = type;
b70cc5fd 3422 l->key.ns = get_pid_ns(ns);
72a8cb30
BB
3423 l->use_count = 0; /* don't increment here */
3424 l->list = NULL;
3425 l->owner = cgrp;
3426 list_add(&l->links, &cgrp->pidlists);
3427 mutex_unlock(&cgrp->pidlist_mutex);
3428 return l;
3429}
3430
102a775e
BB
3431/*
3432 * Load a cgroup's pidarray with either procs' tgids or tasks' pids
3433 */
72a8cb30
BB
3434static int pidlist_array_load(struct cgroup *cgrp, enum cgroup_filetype type,
3435 struct cgroup_pidlist **lp)
102a775e
BB
3436{
3437 pid_t *array;
3438 int length;
3439 int pid, n = 0; /* used for populating the array */
817929ec
PM
3440 struct cgroup_iter it;
3441 struct task_struct *tsk;
102a775e
BB
3442 struct cgroup_pidlist *l;
3443
3444 /*
3445 * If cgroup gets more users after we read count, we won't have
3446 * enough space - tough. This race is indistinguishable to the
3447 * caller from the case that the additional cgroup users didn't
3448 * show up until sometime later on.
3449 */
3450 length = cgroup_task_count(cgrp);
d1d9fd33 3451 array = pidlist_allocate(length);
102a775e
BB
3452 if (!array)
3453 return -ENOMEM;
3454 /* now, populate the array */
bd89aabc
PM
3455 cgroup_iter_start(cgrp, &it);
3456 while ((tsk = cgroup_iter_next(cgrp, &it))) {
102a775e 3457 if (unlikely(n == length))
817929ec 3458 break;
102a775e 3459 /* get tgid or pid for procs or tasks file respectively */
72a8cb30
BB
3460 if (type == CGROUP_FILE_PROCS)
3461 pid = task_tgid_vnr(tsk);
3462 else
3463 pid = task_pid_vnr(tsk);
102a775e
BB
3464 if (pid > 0) /* make sure to only use valid results */
3465 array[n++] = pid;
817929ec 3466 }
bd89aabc 3467 cgroup_iter_end(cgrp, &it);
102a775e
BB
3468 length = n;
3469 /* now sort & (if procs) strip out duplicates */
3470 sort(array, length, sizeof(pid_t), cmppid, NULL);
72a8cb30 3471 if (type == CGROUP_FILE_PROCS)
6ee211ad 3472 length = pidlist_uniq(array, length);
72a8cb30
BB
3473 l = cgroup_pidlist_find(cgrp, type);
3474 if (!l) {
d1d9fd33 3475 pidlist_free(array);
72a8cb30 3476 return -ENOMEM;
102a775e 3477 }
72a8cb30 3478 /* store array, freeing old if necessary - lock already held */
d1d9fd33 3479 pidlist_free(l->list);
102a775e
BB
3480 l->list = array;
3481 l->length = length;
3482 l->use_count++;
3483 up_write(&l->mutex);
72a8cb30 3484 *lp = l;
102a775e 3485 return 0;
bbcb81d0
PM
3486}
3487
846c7bb0 3488/**
a043e3b2 3489 * cgroupstats_build - build and fill cgroupstats
846c7bb0
BS
3490 * @stats: cgroupstats to fill information into
3491 * @dentry: A dentry entry belonging to the cgroup for which stats have
3492 * been requested.
a043e3b2
LZ
3493 *
3494 * Build and fill cgroupstats so that taskstats can export it to user
3495 * space.
846c7bb0
BS
3496 */
3497int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
3498{
3499 int ret = -EINVAL;
bd89aabc 3500 struct cgroup *cgrp;
846c7bb0
BS
3501 struct cgroup_iter it;
3502 struct task_struct *tsk;
33d283be 3503
846c7bb0 3504 /*
33d283be
LZ
3505 * Validate dentry by checking the superblock operations,
3506 * and make sure it's a directory.
846c7bb0 3507 */
33d283be
LZ
3508 if (dentry->d_sb->s_op != &cgroup_ops ||
3509 !S_ISDIR(dentry->d_inode->i_mode))
846c7bb0
BS
3510 goto err;
3511
3512 ret = 0;
bd89aabc 3513 cgrp = dentry->d_fsdata;
846c7bb0 3514
bd89aabc
PM
3515 cgroup_iter_start(cgrp, &it);
3516 while ((tsk = cgroup_iter_next(cgrp, &it))) {
846c7bb0
BS
3517 switch (tsk->state) {
3518 case TASK_RUNNING:
3519 stats->nr_running++;
3520 break;
3521 case TASK_INTERRUPTIBLE:
3522 stats->nr_sleeping++;
3523 break;
3524 case TASK_UNINTERRUPTIBLE:
3525 stats->nr_uninterruptible++;
3526 break;
3527 case TASK_STOPPED:
3528 stats->nr_stopped++;
3529 break;
3530 default:
3531 if (delayacct_is_task_waiting_on_io(tsk))
3532 stats->nr_io_wait++;
3533 break;
3534 }
3535 }
bd89aabc 3536 cgroup_iter_end(cgrp, &it);
846c7bb0 3537
846c7bb0
BS
3538err:
3539 return ret;
3540}
3541
8f3ff208 3542
bbcb81d0 3543/*
102a775e 3544 * seq_file methods for the tasks/procs files. The seq_file position is the
cc31edce 3545 * next pid to display; the seq_file iterator is a pointer to the pid
102a775e 3546 * in the cgroup->l->list array.
bbcb81d0 3547 */
cc31edce 3548
102a775e 3549static void *cgroup_pidlist_start(struct seq_file *s, loff_t *pos)
bbcb81d0 3550{
cc31edce
PM
3551 /*
3552 * Initially we receive a position value that corresponds to
3553 * one more than the last pid shown (or 0 on the first call or
3554 * after a seek to the start). Use a binary-search to find the
3555 * next pid to display, if any
3556 */
102a775e 3557 struct cgroup_pidlist *l = s->private;
cc31edce
PM
3558 int index = 0, pid = *pos;
3559 int *iter;
3560
102a775e 3561 down_read(&l->mutex);
cc31edce 3562 if (pid) {
102a775e 3563 int end = l->length;
20777766 3564
cc31edce
PM
3565 while (index < end) {
3566 int mid = (index + end) / 2;
102a775e 3567 if (l->list[mid] == pid) {
cc31edce
PM
3568 index = mid;
3569 break;
102a775e 3570 } else if (l->list[mid] <= pid)
cc31edce
PM
3571 index = mid + 1;
3572 else
3573 end = mid;
3574 }
3575 }
3576 /* If we're off the end of the array, we're done */
102a775e 3577 if (index >= l->length)
cc31edce
PM
3578 return NULL;
3579 /* Update the abstract position to be the actual pid that we found */
102a775e 3580 iter = l->list + index;
cc31edce
PM
3581 *pos = *iter;
3582 return iter;
3583}
3584
102a775e 3585static void cgroup_pidlist_stop(struct seq_file *s, void *v)
cc31edce 3586{
102a775e
BB
3587 struct cgroup_pidlist *l = s->private;
3588 up_read(&l->mutex);
cc31edce
PM
3589}
3590
102a775e 3591static void *cgroup_pidlist_next(struct seq_file *s, void *v, loff_t *pos)
cc31edce 3592{
102a775e
BB
3593 struct cgroup_pidlist *l = s->private;
3594 pid_t *p = v;
3595 pid_t *end = l->list + l->length;
cc31edce
PM
3596 /*
3597 * Advance to the next pid in the array. If this goes off the
3598 * end, we're done
3599 */
3600 p++;
3601 if (p >= end) {
3602 return NULL;
3603 } else {
3604 *pos = *p;
3605 return p;
3606 }
3607}
3608
102a775e 3609static int cgroup_pidlist_show(struct seq_file *s, void *v)
cc31edce
PM
3610{
3611 return seq_printf(s, "%d\n", *(int *)v);
3612}
bbcb81d0 3613
102a775e
BB
3614/*
3615 * seq_operations functions for iterating on pidlists through seq_file -
3616 * independent of whether it's tasks or procs
3617 */
3618static const struct seq_operations cgroup_pidlist_seq_operations = {
3619 .start = cgroup_pidlist_start,
3620 .stop = cgroup_pidlist_stop,
3621 .next = cgroup_pidlist_next,
3622 .show = cgroup_pidlist_show,
cc31edce
PM
3623};
3624
102a775e 3625static void cgroup_release_pid_array(struct cgroup_pidlist *l)
cc31edce 3626{
72a8cb30
BB
3627 /*
3628 * the case where we're the last user of this particular pidlist will
3629 * have us remove it from the cgroup's list, which entails taking the
3630 * mutex. since in pidlist_find the pidlist->lock depends on cgroup->
3631 * pidlist_mutex, we have to take pidlist_mutex first.
3632 */
3633 mutex_lock(&l->owner->pidlist_mutex);
102a775e
BB
3634 down_write(&l->mutex);
3635 BUG_ON(!l->use_count);
3636 if (!--l->use_count) {
72a8cb30
BB
3637 /* we're the last user if refcount is 0; remove and free */
3638 list_del(&l->links);
3639 mutex_unlock(&l->owner->pidlist_mutex);
d1d9fd33 3640 pidlist_free(l->list);
72a8cb30
BB
3641 put_pid_ns(l->key.ns);
3642 up_write(&l->mutex);
3643 kfree(l);
3644 return;
cc31edce 3645 }
72a8cb30 3646 mutex_unlock(&l->owner->pidlist_mutex);
102a775e 3647 up_write(&l->mutex);
bbcb81d0
PM
3648}
3649
102a775e 3650static int cgroup_pidlist_release(struct inode *inode, struct file *file)
cc31edce 3651{
102a775e 3652 struct cgroup_pidlist *l;
cc31edce
PM
3653 if (!(file->f_mode & FMODE_READ))
3654 return 0;
102a775e
BB
3655 /*
3656 * the seq_file will only be initialized if the file was opened for
3657 * reading; hence we check if it's not null only in that case.
3658 */
3659 l = ((struct seq_file *)file->private_data)->private;
3660 cgroup_release_pid_array(l);
cc31edce
PM
3661 return seq_release(inode, file);
3662}
3663
102a775e 3664static const struct file_operations cgroup_pidlist_operations = {
cc31edce
PM
3665 .read = seq_read,
3666 .llseek = seq_lseek,
3667 .write = cgroup_file_write,
102a775e 3668 .release = cgroup_pidlist_release,
cc31edce
PM
3669};
3670
bbcb81d0 3671/*
102a775e
BB
3672 * The following functions handle opens on a file that displays a pidlist
3673 * (tasks or procs). Prepare an array of the process/thread IDs of whoever's
3674 * in the cgroup.
bbcb81d0 3675 */
102a775e 3676/* helper function for the two below it */
72a8cb30 3677static int cgroup_pidlist_open(struct file *file, enum cgroup_filetype type)
bbcb81d0 3678{
bd89aabc 3679 struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
72a8cb30 3680 struct cgroup_pidlist *l;
cc31edce 3681 int retval;
bbcb81d0 3682
cc31edce 3683 /* Nothing to do for write-only files */
bbcb81d0
PM
3684 if (!(file->f_mode & FMODE_READ))
3685 return 0;
3686
102a775e 3687 /* have the array populated */
72a8cb30 3688 retval = pidlist_array_load(cgrp, type, &l);
102a775e
BB
3689 if (retval)
3690 return retval;
3691 /* configure file information */
3692 file->f_op = &cgroup_pidlist_operations;
cc31edce 3693
102a775e 3694 retval = seq_open(file, &cgroup_pidlist_seq_operations);
cc31edce 3695 if (retval) {
102a775e 3696 cgroup_release_pid_array(l);
cc31edce 3697 return retval;
bbcb81d0 3698 }
102a775e 3699 ((struct seq_file *)file->private_data)->private = l;
bbcb81d0
PM
3700 return 0;
3701}
102a775e
BB
3702static int cgroup_tasks_open(struct inode *unused, struct file *file)
3703{
72a8cb30 3704 return cgroup_pidlist_open(file, CGROUP_FILE_TASKS);
102a775e
BB
3705}
3706static int cgroup_procs_open(struct inode *unused, struct file *file)
3707{
72a8cb30 3708 return cgroup_pidlist_open(file, CGROUP_FILE_PROCS);
102a775e 3709}
bbcb81d0 3710
bd89aabc 3711static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
81a6a5cd
PM
3712 struct cftype *cft)
3713{
bd89aabc 3714 return notify_on_release(cgrp);
81a6a5cd
PM
3715}
3716
6379c106
PM
3717static int cgroup_write_notify_on_release(struct cgroup *cgrp,
3718 struct cftype *cft,
3719 u64 val)
3720{
3721 clear_bit(CGRP_RELEASABLE, &cgrp->flags);
3722 if (val)
3723 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3724 else
3725 clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
3726 return 0;
3727}
3728
83d0eb79
LZ
3729/*
3730 * When dput() is called asynchronously, if umount has been done and
3731 * then deactivate_super() in cgroup_free_fn() kills the superblock,
3732 * there's a small window that vfs will see the root dentry with non-zero
3733 * refcnt and trigger BUG().
3734 *
3735 * That's why we hold a reference before dput() and drop it right after.
3736 */
3737static void cgroup_dput(struct cgroup *cgrp)
3738{
3739 struct super_block *sb = cgrp->root->sb;
3740
3741 atomic_inc(&sb->s_active);
3742 dput(cgrp->dentry);
3743 deactivate_super(sb);
3744}
3745
0dea1168
KS
3746/*
3747 * Unregister event and free resources.
3748 *
3749 * Gets called from workqueue.
3750 */
3751static void cgroup_event_remove(struct work_struct *work)
3752{
3753 struct cgroup_event *event = container_of(work, struct cgroup_event,
3754 remove);
3755 struct cgroup *cgrp = event->cgrp;
3756
810cbee4
LZ
3757 remove_wait_queue(event->wqh, &event->wait);
3758
0dea1168
KS
3759 event->cft->unregister_event(cgrp, event->cft, event->eventfd);
3760
810cbee4
LZ
3761 /* Notify userspace the event is going away. */
3762 eventfd_signal(event->eventfd, 1);
3763
0dea1168 3764 eventfd_ctx_put(event->eventfd);
0dea1168 3765 kfree(event);
83d0eb79 3766 cgroup_dput(cgrp);
0dea1168
KS
3767}
3768
3769/*
3770 * Gets called on POLLHUP on eventfd when user closes it.
3771 *
3772 * Called with wqh->lock held and interrupts disabled.
3773 */
3774static int cgroup_event_wake(wait_queue_t *wait, unsigned mode,
3775 int sync, void *key)
3776{
3777 struct cgroup_event *event = container_of(wait,
3778 struct cgroup_event, wait);
3779 struct cgroup *cgrp = event->cgrp;
3780 unsigned long flags = (unsigned long)key;
3781
3782 if (flags & POLLHUP) {
0dea1168 3783 /*
810cbee4
LZ
3784 * If the event has been detached at cgroup removal, we
3785 * can simply return knowing the other side will cleanup
3786 * for us.
3787 *
3788 * We can't race against event freeing since the other
3789 * side will require wqh->lock via remove_wait_queue(),
3790 * which we hold.
0dea1168 3791 */
810cbee4
LZ
3792 spin_lock(&cgrp->event_list_lock);
3793 if (!list_empty(&event->list)) {
3794 list_del_init(&event->list);
3795 /*
3796 * We are in atomic context, but cgroup_event_remove()
3797 * may sleep, so we have to call it in workqueue.
3798 */
3799 schedule_work(&event->remove);
3800 }
3801 spin_unlock(&cgrp->event_list_lock);
0dea1168
KS
3802 }
3803
3804 return 0;
3805}
3806
3807static void cgroup_event_ptable_queue_proc(struct file *file,
3808 wait_queue_head_t *wqh, poll_table *pt)
3809{
3810 struct cgroup_event *event = container_of(pt,
3811 struct cgroup_event, pt);
3812
3813 event->wqh = wqh;
3814 add_wait_queue(wqh, &event->wait);
3815}
3816
3817/*
3818 * Parse input and register new cgroup event handler.
3819 *
3820 * Input must be in format '<event_fd> <control_fd> <args>'.
3821 * Interpretation of args is defined by control file implementation.
3822 */
3823static int cgroup_write_event_control(struct cgroup *cgrp, struct cftype *cft,
3824 const char *buffer)
3825{
3826 struct cgroup_event *event = NULL;
f169007b 3827 struct cgroup *cgrp_cfile;
0dea1168
KS
3828 unsigned int efd, cfd;
3829 struct file *efile = NULL;
3830 struct file *cfile = NULL;
3831 char *endp;
3832 int ret;
3833
3834 efd = simple_strtoul(buffer, &endp, 10);
3835 if (*endp != ' ')
3836 return -EINVAL;
3837 buffer = endp + 1;
3838
3839 cfd = simple_strtoul(buffer, &endp, 10);
3840 if ((*endp != ' ') && (*endp != '\0'))
3841 return -EINVAL;
3842 buffer = endp + 1;
3843
3844 event = kzalloc(sizeof(*event), GFP_KERNEL);
3845 if (!event)
3846 return -ENOMEM;
3847 event->cgrp = cgrp;
3848 INIT_LIST_HEAD(&event->list);
3849 init_poll_funcptr(&event->pt, cgroup_event_ptable_queue_proc);
3850 init_waitqueue_func_entry(&event->wait, cgroup_event_wake);
3851 INIT_WORK(&event->remove, cgroup_event_remove);
3852
3853 efile = eventfd_fget(efd);
3854 if (IS_ERR(efile)) {
3855 ret = PTR_ERR(efile);
3856 goto fail;
3857 }
3858
3859 event->eventfd = eventfd_ctx_fileget(efile);
3860 if (IS_ERR(event->eventfd)) {
3861 ret = PTR_ERR(event->eventfd);
3862 goto fail;
3863 }
3864
3865 cfile = fget(cfd);
3866 if (!cfile) {
3867 ret = -EBADF;
3868 goto fail;
3869 }
3870
3871 /* the process need read permission on control file */
3bfa784a 3872 /* AV: shouldn't we check that it's been opened for read instead? */
496ad9aa 3873 ret = inode_permission(file_inode(cfile), MAY_READ);
0dea1168
KS
3874 if (ret < 0)
3875 goto fail;
3876
3877 event->cft = __file_cft(cfile);
3878 if (IS_ERR(event->cft)) {
3879 ret = PTR_ERR(event->cft);
3880 goto fail;
3881 }
3882
f169007b
LZ
3883 /*
3884 * The file to be monitored must be in the same cgroup as
3885 * cgroup.event_control is.
3886 */
3887 cgrp_cfile = __d_cgrp(cfile->f_dentry->d_parent);
3888 if (cgrp_cfile != cgrp) {
3889 ret = -EINVAL;
3890 goto fail;
3891 }
3892
0dea1168
KS
3893 if (!event->cft->register_event || !event->cft->unregister_event) {
3894 ret = -EINVAL;
3895 goto fail;
3896 }
3897
3898 ret = event->cft->register_event(cgrp, event->cft,
3899 event->eventfd, buffer);
3900 if (ret)
3901 goto fail;
3902
7ef70e48 3903 efile->f_op->poll(efile, &event->pt);
0dea1168 3904
a0a4db54
KS
3905 /*
3906 * Events should be removed after rmdir of cgroup directory, but before
3907 * destroying subsystem state objects. Let's take reference to cgroup
3908 * directory dentry to do that.
3909 */
3910 dget(cgrp->dentry);
3911
0dea1168
KS
3912 spin_lock(&cgrp->event_list_lock);
3913 list_add(&event->list, &cgrp->event_list);
3914 spin_unlock(&cgrp->event_list_lock);
3915
3916 fput(cfile);
3917 fput(efile);
3918
3919 return 0;
3920
3921fail:
3922 if (cfile)
3923 fput(cfile);
3924
3925 if (event && event->eventfd && !IS_ERR(event->eventfd))
3926 eventfd_ctx_put(event->eventfd);
3927
3928 if (!IS_ERR_OR_NULL(efile))
3929 fput(efile);
3930
3931 kfree(event);
3932
3933 return ret;
3934}
3935
97978e6d
DL
3936static u64 cgroup_clone_children_read(struct cgroup *cgrp,
3937 struct cftype *cft)
3938{
2260e7fc 3939 return test_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
97978e6d
DL
3940}
3941
3942static int cgroup_clone_children_write(struct cgroup *cgrp,
3943 struct cftype *cft,
3944 u64 val)
3945{
3946 if (val)
2260e7fc 3947 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
97978e6d 3948 else
2260e7fc 3949 clear_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
97978e6d
DL
3950 return 0;
3951}
3952
bbcb81d0
PM
3953/*
3954 * for the common functions, 'private' gives the type of file
3955 */
102a775e
BB
3956/* for hysterical raisins, we can't put this on the older files */
3957#define CGROUP_FILE_GENERIC_PREFIX "cgroup."
81a6a5cd
PM
3958static struct cftype files[] = {
3959 {
3960 .name = "tasks",
3961 .open = cgroup_tasks_open,
af351026 3962 .write_u64 = cgroup_tasks_write,
102a775e 3963 .release = cgroup_pidlist_release,
099fca32 3964 .mode = S_IRUGO | S_IWUSR,
81a6a5cd 3965 },
102a775e
BB
3966 {
3967 .name = CGROUP_FILE_GENERIC_PREFIX "procs",
3968 .open = cgroup_procs_open,
74a1166d 3969 .write_u64 = cgroup_procs_write,
102a775e 3970 .release = cgroup_pidlist_release,
74a1166d 3971 .mode = S_IRUGO | S_IWUSR,
102a775e 3972 },
81a6a5cd
PM
3973 {
3974 .name = "notify_on_release",
f4c753b7 3975 .read_u64 = cgroup_read_notify_on_release,
6379c106 3976 .write_u64 = cgroup_write_notify_on_release,
81a6a5cd 3977 },
0dea1168
KS
3978 {
3979 .name = CGROUP_FILE_GENERIC_PREFIX "event_control",
3980 .write_string = cgroup_write_event_control,
3981 .mode = S_IWUGO,
3982 },
97978e6d
DL
3983 {
3984 .name = "cgroup.clone_children",
873fe09e 3985 .flags = CFTYPE_INSANE,
97978e6d
DL
3986 .read_u64 = cgroup_clone_children_read,
3987 .write_u64 = cgroup_clone_children_write,
3988 },
873fe09e
TH
3989 {
3990 .name = "cgroup.sane_behavior",
3991 .flags = CFTYPE_ONLY_ON_ROOT,
3992 .read_seq_string = cgroup_sane_behavior_show,
3993 },
6e6ff25b
TH
3994 {
3995 .name = "release_agent",
3996 .flags = CFTYPE_ONLY_ON_ROOT,
3997 .read_seq_string = cgroup_release_agent_show,
3998 .write_string = cgroup_release_agent_write,
3999 .max_write_len = PATH_MAX,
4000 },
db0416b6 4001 { } /* terminate */
bbcb81d0
PM
4002};
4003
13af07df
AR
4004/**
4005 * cgroup_populate_dir - selectively creation of files in a directory
4006 * @cgrp: target cgroup
4007 * @base_files: true if the base files should be added
4008 * @subsys_mask: mask of the subsystem ids whose files should be added
4009 */
4010static int cgroup_populate_dir(struct cgroup *cgrp, bool base_files,
4011 unsigned long subsys_mask)
ddbcc7e8
PM
4012{
4013 int err;
4014 struct cgroup_subsys *ss;
4015
13af07df
AR
4016 if (base_files) {
4017 err = cgroup_addrm_files(cgrp, NULL, files, true);
4018 if (err < 0)
4019 return err;
4020 }
bbcb81d0 4021
8e3f6541 4022 /* process cftsets of each subsystem */
bd89aabc 4023 for_each_subsys(cgrp->root, ss) {
8e3f6541 4024 struct cftype_set *set;
13af07df
AR
4025 if (!test_bit(ss->subsys_id, &subsys_mask))
4026 continue;
8e3f6541 4027
db0416b6 4028 list_for_each_entry(set, &ss->cftsets, node)
79578621 4029 cgroup_addrm_files(cgrp, ss, set->cfts, true);
ddbcc7e8 4030 }
8e3f6541 4031
38460b48
KH
4032 /* This cgroup is ready now */
4033 for_each_subsys(cgrp->root, ss) {
4034 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4035 /*
4036 * Update id->css pointer and make this css visible from
4037 * CSS ID functions. This pointer will be dereferened
4038 * from RCU-read-side without locks.
4039 */
4040 if (css->id)
4041 rcu_assign_pointer(css->id->css, css);
4042 }
ddbcc7e8
PM
4043
4044 return 0;
4045}
4046
48ddbe19
TH
4047static void css_dput_fn(struct work_struct *work)
4048{
4049 struct cgroup_subsys_state *css =
4050 container_of(work, struct cgroup_subsys_state, dput_work);
4051
83d0eb79 4052 cgroup_dput(css->cgroup);
48ddbe19
TH
4053}
4054
ddbcc7e8
PM
4055static void init_cgroup_css(struct cgroup_subsys_state *css,
4056 struct cgroup_subsys *ss,
bd89aabc 4057 struct cgroup *cgrp)
ddbcc7e8 4058{
bd89aabc 4059 css->cgroup = cgrp;
e7c5ec91 4060 atomic_set(&css->refcnt, 1);
ddbcc7e8 4061 css->flags = 0;
38460b48 4062 css->id = NULL;
bd89aabc 4063 if (cgrp == dummytop)
38b53aba 4064 css->flags |= CSS_ROOT;
bd89aabc
PM
4065 BUG_ON(cgrp->subsys[ss->subsys_id]);
4066 cgrp->subsys[ss->subsys_id] = css;
48ddbe19
TH
4067
4068 /*
ed957793
TH
4069 * css holds an extra ref to @cgrp->dentry which is put on the last
4070 * css_put(). dput() requires process context, which css_put() may
4071 * be called without. @css->dput_work will be used to invoke
4072 * dput() asynchronously from css_put().
48ddbe19
TH
4073 */
4074 INIT_WORK(&css->dput_work, css_dput_fn);
ddbcc7e8
PM
4075}
4076
b1929db4
TH
4077/* invoke ->post_create() on a new CSS and mark it online if successful */
4078static int online_css(struct cgroup_subsys *ss, struct cgroup *cgrp)
a31f2d3f 4079{
b1929db4
TH
4080 int ret = 0;
4081
a31f2d3f
TH
4082 lockdep_assert_held(&cgroup_mutex);
4083
92fb9748
TH
4084 if (ss->css_online)
4085 ret = ss->css_online(cgrp);
b1929db4
TH
4086 if (!ret)
4087 cgrp->subsys[ss->subsys_id]->flags |= CSS_ONLINE;
4088 return ret;
a31f2d3f
TH
4089}
4090
4091/* if the CSS is online, invoke ->pre_destory() on it and mark it offline */
4092static void offline_css(struct cgroup_subsys *ss, struct cgroup *cgrp)
4093 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
4094{
4095 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
4096
4097 lockdep_assert_held(&cgroup_mutex);
4098
4099 if (!(css->flags & CSS_ONLINE))
4100 return;
4101
d7eeac19 4102 if (ss->css_offline)
92fb9748 4103 ss->css_offline(cgrp);
a31f2d3f
TH
4104
4105 cgrp->subsys[ss->subsys_id]->flags &= ~CSS_ONLINE;
4106}
4107
ddbcc7e8 4108/*
a043e3b2
LZ
4109 * cgroup_create - create a cgroup
4110 * @parent: cgroup that will be parent of the new cgroup
4111 * @dentry: dentry of the new cgroup
4112 * @mode: mode to set on new inode
ddbcc7e8 4113 *
a043e3b2 4114 * Must be called with the mutex on the parent inode held
ddbcc7e8 4115 */
ddbcc7e8 4116static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
a5e7ed32 4117 umode_t mode)
ddbcc7e8 4118{
bd89aabc 4119 struct cgroup *cgrp;
65dff759 4120 struct cgroup_name *name;
ddbcc7e8
PM
4121 struct cgroupfs_root *root = parent->root;
4122 int err = 0;
4123 struct cgroup_subsys *ss;
4124 struct super_block *sb = root->sb;
4125
0a950f65 4126 /* allocate the cgroup and its ID, 0 is reserved for the root */
bd89aabc
PM
4127 cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
4128 if (!cgrp)
ddbcc7e8
PM
4129 return -ENOMEM;
4130
65dff759
LZ
4131 name = cgroup_alloc_name(dentry);
4132 if (!name)
4133 goto err_free_cgrp;
4134 rcu_assign_pointer(cgrp->name, name);
4135
0a950f65
TH
4136 cgrp->id = ida_simple_get(&root->cgroup_ida, 1, 0, GFP_KERNEL);
4137 if (cgrp->id < 0)
65dff759 4138 goto err_free_name;
0a950f65 4139
976c06bc
TH
4140 /*
4141 * Only live parents can have children. Note that the liveliness
4142 * check isn't strictly necessary because cgroup_mkdir() and
4143 * cgroup_rmdir() are fully synchronized by i_mutex; however, do it
4144 * anyway so that locking is contained inside cgroup proper and we
4145 * don't get nasty surprises if we ever grow another caller.
4146 */
4147 if (!cgroup_lock_live_group(parent)) {
4148 err = -ENODEV;
0a950f65 4149 goto err_free_id;
976c06bc
TH
4150 }
4151
ddbcc7e8
PM
4152 /* Grab a reference on the superblock so the hierarchy doesn't
4153 * get deleted on unmount if there are child cgroups. This
4154 * can be done outside cgroup_mutex, since the sb can't
4155 * disappear while someone has an open control file on the
4156 * fs */
4157 atomic_inc(&sb->s_active);
4158
cc31edce 4159 init_cgroup_housekeeping(cgrp);
ddbcc7e8 4160
fe1c06ca
LZ
4161 dentry->d_fsdata = cgrp;
4162 cgrp->dentry = dentry;
4163
bd89aabc
PM
4164 cgrp->parent = parent;
4165 cgrp->root = parent->root;
ddbcc7e8 4166
b6abdb0e
LZ
4167 if (notify_on_release(parent))
4168 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
4169
2260e7fc
TH
4170 if (test_bit(CGRP_CPUSET_CLONE_CHILDREN, &parent->flags))
4171 set_bit(CGRP_CPUSET_CLONE_CHILDREN, &cgrp->flags);
97978e6d 4172
ddbcc7e8 4173 for_each_subsys(root, ss) {
8c7f6edb 4174 struct cgroup_subsys_state *css;
4528fd05 4175
92fb9748 4176 css = ss->css_alloc(cgrp);
ddbcc7e8
PM
4177 if (IS_ERR(css)) {
4178 err = PTR_ERR(css);
4b8b47eb 4179 goto err_free_all;
ddbcc7e8 4180 }
bd89aabc 4181 init_cgroup_css(css, ss, cgrp);
4528fd05
LZ
4182 if (ss->use_id) {
4183 err = alloc_css_id(ss, parent, cgrp);
4184 if (err)
4b8b47eb 4185 goto err_free_all;
4528fd05 4186 }
ddbcc7e8
PM
4187 }
4188
4e139afc
TH
4189 /*
4190 * Create directory. cgroup_create_file() returns with the new
4191 * directory locked on success so that it can be populated without
4192 * dropping cgroup_mutex.
4193 */
28fd6f30 4194 err = cgroup_create_file(dentry, S_IFDIR | mode, sb);
ddbcc7e8 4195 if (err < 0)
4b8b47eb 4196 goto err_free_all;
4e139afc 4197 lockdep_assert_held(&dentry->d_inode->i_mutex);
ddbcc7e8 4198
4e139afc 4199 /* allocation complete, commit to creation */
4e139afc
TH
4200 list_add_tail(&cgrp->allcg_node, &root->allcg_list);
4201 list_add_tail_rcu(&cgrp->sibling, &cgrp->parent->children);
4202 root->number_of_cgroups++;
28fd6f30 4203
b1929db4
TH
4204 /* each css holds a ref to the cgroup's dentry */
4205 for_each_subsys(root, ss)
ed957793 4206 dget(dentry);
48ddbe19 4207
415cf07a
LZ
4208 /* hold a ref to the parent's dentry */
4209 dget(parent->dentry);
4210
b1929db4
TH
4211 /* creation succeeded, notify subsystems */
4212 for_each_subsys(root, ss) {
4213 err = online_css(ss, cgrp);
4214 if (err)
4215 goto err_destroy;
1f869e87
GC
4216
4217 if (ss->broken_hierarchy && !ss->warned_broken_hierarchy &&
4218 parent->parent) {
4219 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",
4220 current->comm, current->pid, ss->name);
4221 if (!strcmp(ss->name, "memory"))
4222 pr_warning("cgroup: \"memory\" requires setting use_hierarchy to 1 on the root.\n");
4223 ss->warned_broken_hierarchy = true;
4224 }
a8638030
TH
4225 }
4226
a1a71b45 4227 err = cgroup_populate_dir(cgrp, true, root->subsys_mask);
4b8b47eb
TH
4228 if (err)
4229 goto err_destroy;
ddbcc7e8
PM
4230
4231 mutex_unlock(&cgroup_mutex);
bd89aabc 4232 mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
ddbcc7e8
PM
4233
4234 return 0;
4235
4b8b47eb 4236err_free_all:
ddbcc7e8 4237 for_each_subsys(root, ss) {
bd89aabc 4238 if (cgrp->subsys[ss->subsys_id])
92fb9748 4239 ss->css_free(cgrp);
ddbcc7e8 4240 }
ddbcc7e8 4241 mutex_unlock(&cgroup_mutex);
ddbcc7e8
PM
4242 /* Release the reference count that we took on the superblock */
4243 deactivate_super(sb);
0a950f65
TH
4244err_free_id:
4245 ida_simple_remove(&root->cgroup_ida, cgrp->id);
65dff759
LZ
4246err_free_name:
4247 kfree(rcu_dereference_raw(cgrp->name));
4b8b47eb 4248err_free_cgrp:
bd89aabc 4249 kfree(cgrp);
ddbcc7e8 4250 return err;
4b8b47eb
TH
4251
4252err_destroy:
4253 cgroup_destroy_locked(cgrp);
4254 mutex_unlock(&cgroup_mutex);
4255 mutex_unlock(&dentry->d_inode->i_mutex);
4256 return err;
ddbcc7e8
PM
4257}
4258
18bb1db3 4259static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode)
ddbcc7e8
PM
4260{
4261 struct cgroup *c_parent = dentry->d_parent->d_fsdata;
4262
4263 /* the vfs holds inode->i_mutex already */
4264 return cgroup_create(c_parent, dentry, mode | S_IFDIR);
4265}
4266
42809dd4
TH
4267static int cgroup_destroy_locked(struct cgroup *cgrp)
4268 __releases(&cgroup_mutex) __acquires(&cgroup_mutex)
ddbcc7e8 4269{
42809dd4
TH
4270 struct dentry *d = cgrp->dentry;
4271 struct cgroup *parent = cgrp->parent;
4ab78683 4272 struct cgroup_event *event, *tmp;
ed957793 4273 struct cgroup_subsys *ss;
ddbcc7e8 4274
42809dd4
TH
4275 lockdep_assert_held(&d->d_inode->i_mutex);
4276 lockdep_assert_held(&cgroup_mutex);
4277
4278 if (atomic_read(&cgrp->count) || !list_empty(&cgrp->children))
ddbcc7e8 4279 return -EBUSY;
a043e3b2 4280
88703267 4281 /*
1a90dd50
TH
4282 * Block new css_tryget() by deactivating refcnt and mark @cgrp
4283 * removed. This makes future css_tryget() and child creation
4284 * attempts fail thus maintaining the removal conditions verified
4285 * above.
88703267 4286 */
ed957793
TH
4287 for_each_subsys(cgrp->root, ss) {
4288 struct cgroup_subsys_state *css = cgrp->subsys[ss->subsys_id];
88703267 4289
ed957793
TH
4290 WARN_ON(atomic_read(&css->refcnt) < 0);
4291 atomic_add(CSS_DEACT_BIAS, &css->refcnt);
88703267 4292 }
1a90dd50 4293 set_bit(CGRP_REMOVED, &cgrp->flags);
ddbcc7e8 4294
a31f2d3f 4295 /* tell subsystems to initate destruction */
1a90dd50 4296 for_each_subsys(cgrp->root, ss)
a31f2d3f 4297 offline_css(ss, cgrp);
ed957793
TH
4298
4299 /*
ed957793
TH
4300 * Put all the base refs. Each css holds an extra reference to the
4301 * cgroup's dentry and cgroup removal proceeds regardless of css
4302 * refs. On the last put of each css, whenever that may be, the
4303 * extra dentry ref is put so that dentry destruction happens only
4304 * after all css's are released.
4305 */
e9316080
TH
4306 for_each_subsys(cgrp->root, ss)
4307 css_put(cgrp->subsys[ss->subsys_id]);
ddbcc7e8 4308
cdcc136f 4309 raw_spin_lock(&release_list_lock);
bd89aabc 4310 if (!list_empty(&cgrp->release_list))
8d258797 4311 list_del_init(&cgrp->release_list);
cdcc136f 4312 raw_spin_unlock(&release_list_lock);
999cd8a4 4313
999cd8a4 4314 /* delete this cgroup from parent->children */
eb6fd504 4315 list_del_rcu(&cgrp->sibling);
b0ca5a84
TH
4316 list_del_init(&cgrp->allcg_node);
4317
42809dd4 4318 dget(d);
ddbcc7e8
PM
4319 cgroup_d_remove_dir(d);
4320 dput(d);
ddbcc7e8 4321
bd89aabc 4322 set_bit(CGRP_RELEASABLE, &parent->flags);
81a6a5cd
PM
4323 check_for_release(parent);
4324
4ab78683
KS
4325 /*
4326 * Unregister events and notify userspace.
4327 * Notify userspace about cgroup removing only after rmdir of cgroup
810cbee4 4328 * directory to avoid race between userspace and kernelspace.
4ab78683
KS
4329 */
4330 spin_lock(&cgrp->event_list_lock);
810cbee4 4331 list_for_each_entry_safe(event, tmp, &cgrp->event_list, list) {
9718ceb3 4332 list_del_init(&event->list);
4ab78683
KS
4333 schedule_work(&event->remove);
4334 }
810cbee4 4335 spin_unlock(&cgrp->event_list_lock);
4ab78683 4336
ddbcc7e8
PM
4337 return 0;
4338}
4339
42809dd4
TH
4340static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
4341{
4342 int ret;
4343
4344 mutex_lock(&cgroup_mutex);
4345 ret = cgroup_destroy_locked(dentry->d_fsdata);
4346 mutex_unlock(&cgroup_mutex);
4347
4348 return ret;
4349}
4350
8e3f6541
TH
4351static void __init_or_module cgroup_init_cftsets(struct cgroup_subsys *ss)
4352{
4353 INIT_LIST_HEAD(&ss->cftsets);
4354
4355 /*
4356 * base_cftset is embedded in subsys itself, no need to worry about
4357 * deregistration.
4358 */
4359 if (ss->base_cftypes) {
4360 ss->base_cftset.cfts = ss->base_cftypes;
4361 list_add_tail(&ss->base_cftset.node, &ss->cftsets);
4362 }
4363}
4364
06a11920 4365static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
ddbcc7e8 4366{
ddbcc7e8 4367 struct cgroup_subsys_state *css;
cfe36bde
DC
4368
4369 printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
ddbcc7e8 4370
648bb56d
TH
4371 mutex_lock(&cgroup_mutex);
4372
8e3f6541
TH
4373 /* init base cftset */
4374 cgroup_init_cftsets(ss);
4375
ddbcc7e8 4376 /* Create the top cgroup state for this subsystem */
33a68ac1 4377 list_add(&ss->sibling, &rootnode.subsys_list);
ddbcc7e8 4378 ss->root = &rootnode;
92fb9748 4379 css = ss->css_alloc(dummytop);
ddbcc7e8
PM
4380 /* We don't handle early failures gracefully */
4381 BUG_ON(IS_ERR(css));
4382 init_cgroup_css(css, ss, dummytop);
4383
e8d55fde 4384 /* Update the init_css_set to contain a subsys
817929ec 4385 * pointer to this state - since the subsystem is
e8d55fde
LZ
4386 * newly registered, all tasks and hence the
4387 * init_css_set is in the subsystem's top cgroup. */
b48c6a80 4388 init_css_set.subsys[ss->subsys_id] = css;
ddbcc7e8
PM
4389
4390 need_forkexit_callback |= ss->fork || ss->exit;
4391
e8d55fde
LZ
4392 /* At system boot, before all subsystems have been
4393 * registered, no tasks have been forked, so we don't
4394 * need to invoke fork callbacks here. */
4395 BUG_ON(!list_empty(&init_task.tasks));
4396
b1929db4 4397 BUG_ON(online_css(ss, dummytop));
a8638030 4398
648bb56d
TH
4399 mutex_unlock(&cgroup_mutex);
4400
e6a1105b
BB
4401 /* this function shouldn't be used with modular subsystems, since they
4402 * need to register a subsys_id, among other things */
4403 BUG_ON(ss->module);
4404}
4405
4406/**
4407 * cgroup_load_subsys: load and register a modular subsystem at runtime
4408 * @ss: the subsystem to load
4409 *
4410 * This function should be called in a modular subsystem's initcall. If the
88393161 4411 * subsystem is built as a module, it will be assigned a new subsys_id and set
e6a1105b
BB
4412 * up for use. If the subsystem is built-in anyway, work is delegated to the
4413 * simpler cgroup_init_subsys.
4414 */
4415int __init_or_module cgroup_load_subsys(struct cgroup_subsys *ss)
4416{
e6a1105b 4417 struct cgroup_subsys_state *css;
d19e19de 4418 int i, ret;
b67bfe0d 4419 struct hlist_node *tmp;
0ac801fe
LZ
4420 struct css_set *cg;
4421 unsigned long key;
e6a1105b
BB
4422
4423 /* check name and function validity */
4424 if (ss->name == NULL || strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN ||
92fb9748 4425 ss->css_alloc == NULL || ss->css_free == NULL)
e6a1105b
BB
4426 return -EINVAL;
4427
4428 /*
4429 * we don't support callbacks in modular subsystems. this check is
4430 * before the ss->module check for consistency; a subsystem that could
4431 * be a module should still have no callbacks even if the user isn't
4432 * compiling it as one.
4433 */
4434 if (ss->fork || ss->exit)
4435 return -EINVAL;
4436
4437 /*
4438 * an optionally modular subsystem is built-in: we want to do nothing,
4439 * since cgroup_init_subsys will have already taken care of it.
4440 */
4441 if (ss->module == NULL) {
be45c900 4442 /* a sanity check */
e6a1105b
BB
4443 BUG_ON(subsys[ss->subsys_id] != ss);
4444 return 0;
4445 }
4446
8e3f6541
TH
4447 /* init base cftset */
4448 cgroup_init_cftsets(ss);
4449
e6a1105b 4450 mutex_lock(&cgroup_mutex);
8a8e04df 4451 subsys[ss->subsys_id] = ss;
e6a1105b
BB
4452
4453 /*
92fb9748
TH
4454 * no ss->css_alloc seems to need anything important in the ss
4455 * struct, so this can happen first (i.e. before the rootnode
4456 * attachment).
e6a1105b 4457 */
92fb9748 4458 css = ss->css_alloc(dummytop);
e6a1105b
BB
4459 if (IS_ERR(css)) {
4460 /* failure case - need to deassign the subsys[] slot. */
8a8e04df 4461 subsys[ss->subsys_id] = NULL;
e6a1105b
BB
4462 mutex_unlock(&cgroup_mutex);
4463 return PTR_ERR(css);
4464 }
4465
4466 list_add(&ss->sibling, &rootnode.subsys_list);
4467 ss->root = &rootnode;
4468
4469 /* our new subsystem will be attached to the dummy hierarchy. */
4470 init_cgroup_css(css, ss, dummytop);
4471 /* init_idr must be after init_cgroup_css because it sets css->id. */
4472 if (ss->use_id) {
d19e19de
TH
4473 ret = cgroup_init_idr(ss, css);
4474 if (ret)
4475 goto err_unload;
e6a1105b
BB
4476 }
4477
4478 /*
4479 * Now we need to entangle the css into the existing css_sets. unlike
4480 * in cgroup_init_subsys, there are now multiple css_sets, so each one
4481 * will need a new pointer to it; done by iterating the css_set_table.
4482 * furthermore, modifying the existing css_sets will corrupt the hash
4483 * table state, so each changed css_set will need its hash recomputed.
4484 * this is all done under the css_set_lock.
4485 */
4486 write_lock(&css_set_lock);
b67bfe0d 4487 hash_for_each_safe(css_set_table, i, tmp, cg, hlist) {
0ac801fe
LZ
4488 /* skip entries that we already rehashed */
4489 if (cg->subsys[ss->subsys_id])
4490 continue;
4491 /* remove existing entry */
4492 hash_del(&cg->hlist);
4493 /* set new value */
4494 cg->subsys[ss->subsys_id] = css;
4495 /* recompute hash and restore entry */
4496 key = css_set_hash(cg->subsys);
b67bfe0d 4497 hash_add(css_set_table, &cg->hlist, key);
e6a1105b
BB
4498 }
4499 write_unlock(&css_set_lock);
4500
b1929db4
TH
4501 ret = online_css(ss, dummytop);
4502 if (ret)
4503 goto err_unload;
a8638030 4504
e6a1105b
BB
4505 /* success! */
4506 mutex_unlock(&cgroup_mutex);
4507 return 0;
d19e19de
TH
4508
4509err_unload:
4510 mutex_unlock(&cgroup_mutex);
4511 /* @ss can't be mounted here as try_module_get() would fail */
4512 cgroup_unload_subsys(ss);
4513 return ret;
ddbcc7e8 4514}
e6a1105b 4515EXPORT_SYMBOL_GPL(cgroup_load_subsys);
ddbcc7e8 4516
cf5d5941
BB
4517/**
4518 * cgroup_unload_subsys: unload a modular subsystem
4519 * @ss: the subsystem to unload
4520 *
4521 * This function should be called in a modular subsystem's exitcall. When this
4522 * function is invoked, the refcount on the subsystem's module will be 0, so
4523 * the subsystem will not be attached to any hierarchy.
4524 */
4525void cgroup_unload_subsys(struct cgroup_subsys *ss)
4526{
4527 struct cg_cgroup_link *link;
cf5d5941
BB
4528
4529 BUG_ON(ss->module == NULL);
4530
4531 /*
4532 * we shouldn't be called if the subsystem is in use, and the use of
4533 * try_module_get in parse_cgroupfs_options should ensure that it
4534 * doesn't start being used while we're killing it off.
4535 */
4536 BUG_ON(ss->root != &rootnode);
4537
4538 mutex_lock(&cgroup_mutex);
02ae7486 4539
a31f2d3f 4540 offline_css(ss, dummytop);
02ae7486 4541
c897ff68 4542 if (ss->use_id)
02ae7486 4543 idr_destroy(&ss->idr);
02ae7486 4544
cf5d5941 4545 /* deassign the subsys_id */
cf5d5941
BB
4546 subsys[ss->subsys_id] = NULL;
4547
4548 /* remove subsystem from rootnode's list of subsystems */
8d258797 4549 list_del_init(&ss->sibling);
cf5d5941
BB
4550
4551 /*
4552 * disentangle the css from all css_sets attached to the dummytop. as
4553 * in loading, we need to pay our respects to the hashtable gods.
4554 */
4555 write_lock(&css_set_lock);
4556 list_for_each_entry(link, &dummytop->css_sets, cgrp_link_list) {
4557 struct css_set *cg = link->cg;
0ac801fe 4558 unsigned long key;
cf5d5941 4559
0ac801fe 4560 hash_del(&cg->hlist);
cf5d5941 4561 cg->subsys[ss->subsys_id] = NULL;
0ac801fe
LZ
4562 key = css_set_hash(cg->subsys);
4563 hash_add(css_set_table, &cg->hlist, key);
cf5d5941
BB
4564 }
4565 write_unlock(&css_set_lock);
4566
4567 /*
92fb9748
TH
4568 * remove subsystem's css from the dummytop and free it - need to
4569 * free before marking as null because ss->css_free needs the
4570 * cgrp->subsys pointer to find their state. note that this also
4571 * takes care of freeing the css_id.
cf5d5941 4572 */
92fb9748 4573 ss->css_free(dummytop);
cf5d5941
BB
4574 dummytop->subsys[ss->subsys_id] = NULL;
4575
4576 mutex_unlock(&cgroup_mutex);
4577}
4578EXPORT_SYMBOL_GPL(cgroup_unload_subsys);
4579
ddbcc7e8 4580/**
a043e3b2
LZ
4581 * cgroup_init_early - cgroup initialization at system boot
4582 *
4583 * Initialize cgroups at system boot, and initialize any
4584 * subsystems that request early init.
ddbcc7e8
PM
4585 */
4586int __init cgroup_init_early(void)
4587{
4588 int i;
146aa1bd 4589 atomic_set(&init_css_set.refcount, 1);
817929ec
PM
4590 INIT_LIST_HEAD(&init_css_set.cg_links);
4591 INIT_LIST_HEAD(&init_css_set.tasks);
472b1053 4592 INIT_HLIST_NODE(&init_css_set.hlist);
817929ec 4593 css_set_count = 1;
ddbcc7e8 4594 init_cgroup_root(&rootnode);
817929ec
PM
4595 root_count = 1;
4596 init_task.cgroups = &init_css_set;
4597
4598 init_css_set_link.cg = &init_css_set;
7717f7ba 4599 init_css_set_link.cgrp = dummytop;
bd89aabc 4600 list_add(&init_css_set_link.cgrp_link_list,
817929ec
PM
4601 &rootnode.top_cgroup.css_sets);
4602 list_add(&init_css_set_link.cg_link_list,
4603 &init_css_set.cg_links);
ddbcc7e8 4604
be45c900 4605 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
ddbcc7e8
PM
4606 struct cgroup_subsys *ss = subsys[i];
4607
be45c900
DW
4608 /* at bootup time, we don't worry about modular subsystems */
4609 if (!ss || ss->module)
4610 continue;
4611
ddbcc7e8
PM
4612 BUG_ON(!ss->name);
4613 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
92fb9748
TH
4614 BUG_ON(!ss->css_alloc);
4615 BUG_ON(!ss->css_free);
ddbcc7e8 4616 if (ss->subsys_id != i) {
cfe36bde 4617 printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
ddbcc7e8
PM
4618 ss->name, ss->subsys_id);
4619 BUG();
4620 }
4621
4622 if (ss->early_init)
4623 cgroup_init_subsys(ss);
4624 }
4625 return 0;
4626}
4627
4628/**
a043e3b2
LZ
4629 * cgroup_init - cgroup initialization
4630 *
4631 * Register cgroup filesystem and /proc file, and initialize
4632 * any subsystems that didn't request early init.
ddbcc7e8
PM
4633 */
4634int __init cgroup_init(void)
4635{
4636 int err;
4637 int i;
0ac801fe 4638 unsigned long key;
a424316c
PM
4639
4640 err = bdi_init(&cgroup_backing_dev_info);
4641 if (err)
4642 return err;
ddbcc7e8 4643
be45c900 4644 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
ddbcc7e8 4645 struct cgroup_subsys *ss = subsys[i];
be45c900
DW
4646
4647 /* at bootup time, we don't worry about modular subsystems */
4648 if (!ss || ss->module)
4649 continue;
ddbcc7e8
PM
4650 if (!ss->early_init)
4651 cgroup_init_subsys(ss);
38460b48 4652 if (ss->use_id)
e6a1105b 4653 cgroup_init_idr(ss, init_css_set.subsys[ss->subsys_id]);
ddbcc7e8
PM
4654 }
4655
472b1053 4656 /* Add init_css_set to the hash table */
0ac801fe
LZ
4657 key = css_set_hash(init_css_set.subsys);
4658 hash_add(css_set_table, &init_css_set.hlist, key);
2c6ab6d2 4659 BUG_ON(!init_root_id(&rootnode));
676db4af
GKH
4660
4661 cgroup_kobj = kobject_create_and_add("cgroup", fs_kobj);
4662 if (!cgroup_kobj) {
4663 err = -ENOMEM;
4664 goto out;
4665 }
4666
ddbcc7e8 4667 err = register_filesystem(&cgroup_fs_type);
676db4af
GKH
4668 if (err < 0) {
4669 kobject_put(cgroup_kobj);
ddbcc7e8 4670 goto out;
676db4af 4671 }
ddbcc7e8 4672
46ae220b 4673 proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
a424316c 4674
ddbcc7e8 4675out:
a424316c
PM
4676 if (err)
4677 bdi_destroy(&cgroup_backing_dev_info);
4678
ddbcc7e8
PM
4679 return err;
4680}
b4f48b63 4681
a424316c
PM
4682/*
4683 * proc_cgroup_show()
4684 * - Print task's cgroup paths into seq_file, one line for each hierarchy
4685 * - Used for /proc/<pid>/cgroup.
4686 * - No need to task_lock(tsk) on this tsk->cgroup reference, as it
4687 * doesn't really matter if tsk->cgroup changes after we read it,
956db3ca 4688 * and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
a424316c
PM
4689 * anyway. No need to check that tsk->cgroup != NULL, thanks to
4690 * the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
4691 * cgroup to top_cgroup.
4692 */
4693
4694/* TODO: Use a proper seq_file iterator */
8d8b97ba 4695int proc_cgroup_show(struct seq_file *m, void *v)
a424316c
PM
4696{
4697 struct pid *pid;
4698 struct task_struct *tsk;
4699 char *buf;
4700 int retval;
4701 struct cgroupfs_root *root;
4702
4703 retval = -ENOMEM;
4704 buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
4705 if (!buf)
4706 goto out;
4707
4708 retval = -ESRCH;
4709 pid = m->private;
4710 tsk = get_pid_task(pid, PIDTYPE_PID);
4711 if (!tsk)
4712 goto out_free;
4713
4714 retval = 0;
4715
4716 mutex_lock(&cgroup_mutex);
4717
e5f6a860 4718 for_each_active_root(root) {
a424316c 4719 struct cgroup_subsys *ss;
bd89aabc 4720 struct cgroup *cgrp;
a424316c
PM
4721 int count = 0;
4722
2c6ab6d2 4723 seq_printf(m, "%d:", root->hierarchy_id);
a424316c
PM
4724 for_each_subsys(root, ss)
4725 seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
c6d57f33
PM
4726 if (strlen(root->name))
4727 seq_printf(m, "%sname=%s", count ? "," : "",
4728 root->name);
a424316c 4729 seq_putc(m, ':');
7717f7ba 4730 cgrp = task_cgroup_from_root(tsk, root);
bd89aabc 4731 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
a424316c
PM
4732 if (retval < 0)
4733 goto out_unlock;
4734 seq_puts(m, buf);
4735 seq_putc(m, '\n');
4736 }
4737
4738out_unlock:
4739 mutex_unlock(&cgroup_mutex);
4740 put_task_struct(tsk);
4741out_free:
4742 kfree(buf);
4743out:
4744 return retval;
4745}
4746
a424316c
PM
4747/* Display information about each subsystem and each hierarchy */
4748static int proc_cgroupstats_show(struct seq_file *m, void *v)
4749{
4750 int i;
a424316c 4751
8bab8dde 4752 seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
aae8aab4
BB
4753 /*
4754 * ideally we don't want subsystems moving around while we do this.
4755 * cgroup_mutex is also necessary to guarantee an atomic snapshot of
4756 * subsys/hierarchy state.
4757 */
a424316c 4758 mutex_lock(&cgroup_mutex);
a424316c
PM
4759 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
4760 struct cgroup_subsys *ss = subsys[i];
aae8aab4
BB
4761 if (ss == NULL)
4762 continue;
2c6ab6d2
PM
4763 seq_printf(m, "%s\t%d\t%d\t%d\n",
4764 ss->name, ss->root->hierarchy_id,
8bab8dde 4765 ss->root->number_of_cgroups, !ss->disabled);
a424316c
PM
4766 }
4767 mutex_unlock(&cgroup_mutex);
4768 return 0;
4769}
4770
4771static int cgroupstats_open(struct inode *inode, struct file *file)
4772{
9dce07f1 4773 return single_open(file, proc_cgroupstats_show, NULL);
a424316c
PM
4774}
4775
828c0950 4776static const struct file_operations proc_cgroupstats_operations = {
a424316c
PM
4777 .open = cgroupstats_open,
4778 .read = seq_read,
4779 .llseek = seq_lseek,
4780 .release = single_release,
4781};
4782
b4f48b63
PM
4783/**
4784 * cgroup_fork - attach newly forked task to its parents cgroup.
a043e3b2 4785 * @child: pointer to task_struct of forking parent process.
b4f48b63
PM
4786 *
4787 * Description: A task inherits its parent's cgroup at fork().
4788 *
4789 * A pointer to the shared css_set was automatically copied in
4790 * fork.c by dup_task_struct(). However, we ignore that copy, since
9bb71308
TH
4791 * it was not made under the protection of RCU or cgroup_mutex, so
4792 * might no longer be a valid cgroup pointer. cgroup_attach_task() might
4793 * have already changed current->cgroups, allowing the previously
4794 * referenced cgroup group to be removed and freed.
b4f48b63
PM
4795 *
4796 * At the point that cgroup_fork() is called, 'current' is the parent
4797 * task, and the passed argument 'child' points to the child task.
4798 */
4799void cgroup_fork(struct task_struct *child)
4800{
9bb71308 4801 task_lock(current);
817929ec
PM
4802 child->cgroups = current->cgroups;
4803 get_css_set(child->cgroups);
9bb71308 4804 task_unlock(current);
817929ec 4805 INIT_LIST_HEAD(&child->cg_list);
b4f48b63
PM
4806}
4807
817929ec 4808/**
a043e3b2
LZ
4809 * cgroup_post_fork - called on a new task after adding it to the task list
4810 * @child: the task in question
4811 *
5edee61e
TH
4812 * Adds the task to the list running through its css_set if necessary and
4813 * call the subsystem fork() callbacks. Has to be after the task is
4814 * visible on the task list in case we race with the first call to
4815 * cgroup_iter_start() - to guarantee that the new task ends up on its
4816 * list.
a043e3b2 4817 */
817929ec
PM
4818void cgroup_post_fork(struct task_struct *child)
4819{
5edee61e
TH
4820 int i;
4821
3ce3230a
FW
4822 /*
4823 * use_task_css_set_links is set to 1 before we walk the tasklist
4824 * under the tasklist_lock and we read it here after we added the child
4825 * to the tasklist under the tasklist_lock as well. If the child wasn't
4826 * yet in the tasklist when we walked through it from
4827 * cgroup_enable_task_cg_lists(), then use_task_css_set_links value
4828 * should be visible now due to the paired locking and barriers implied
4829 * by LOCK/UNLOCK: it is written before the tasklist_lock unlock
4830 * in cgroup_enable_task_cg_lists() and read here after the tasklist_lock
4831 * lock on fork.
4832 */
817929ec
PM
4833 if (use_task_css_set_links) {
4834 write_lock(&css_set_lock);
d8783832
TH
4835 task_lock(child);
4836 if (list_empty(&child->cg_list))
817929ec 4837 list_add(&child->cg_list, &child->cgroups->tasks);
d8783832 4838 task_unlock(child);
817929ec
PM
4839 write_unlock(&css_set_lock);
4840 }
5edee61e
TH
4841
4842 /*
4843 * Call ss->fork(). This must happen after @child is linked on
4844 * css_set; otherwise, @child might change state between ->fork()
4845 * and addition to css_set.
4846 */
4847 if (need_forkexit_callback) {
7d8e0bf5
LZ
4848 /*
4849 * fork/exit callbacks are supported only for builtin
4850 * subsystems, and the builtin section of the subsys
4851 * array is immutable, so we don't need to lock the
4852 * subsys array here. On the other hand, modular section
4853 * of the array can be freed at module unload, so we
4854 * can't touch that.
4855 */
4856 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
5edee61e
TH
4857 struct cgroup_subsys *ss = subsys[i];
4858
5edee61e
TH
4859 if (ss->fork)
4860 ss->fork(child);
4861 }
4862 }
817929ec 4863}
5edee61e 4864
b4f48b63
PM
4865/**
4866 * cgroup_exit - detach cgroup from exiting task
4867 * @tsk: pointer to task_struct of exiting process
a043e3b2 4868 * @run_callback: run exit callbacks?
b4f48b63
PM
4869 *
4870 * Description: Detach cgroup from @tsk and release it.
4871 *
4872 * Note that cgroups marked notify_on_release force every task in
4873 * them to take the global cgroup_mutex mutex when exiting.
4874 * This could impact scaling on very large systems. Be reluctant to
4875 * use notify_on_release cgroups where very high task exit scaling
4876 * is required on large systems.
4877 *
4878 * the_top_cgroup_hack:
4879 *
4880 * Set the exiting tasks cgroup to the root cgroup (top_cgroup).
4881 *
4882 * We call cgroup_exit() while the task is still competent to
4883 * handle notify_on_release(), then leave the task attached to the
4884 * root cgroup in each hierarchy for the remainder of its exit.
4885 *
4886 * To do this properly, we would increment the reference count on
4887 * top_cgroup, and near the very end of the kernel/exit.c do_exit()
4888 * code we would add a second cgroup function call, to drop that
4889 * reference. This would just create an unnecessary hot spot on
4890 * the top_cgroup reference count, to no avail.
4891 *
4892 * Normally, holding a reference to a cgroup without bumping its
4893 * count is unsafe. The cgroup could go away, or someone could
4894 * attach us to a different cgroup, decrementing the count on
4895 * the first cgroup that we never incremented. But in this case,
4896 * top_cgroup isn't going away, and either task has PF_EXITING set,
956db3ca
CW
4897 * which wards off any cgroup_attach_task() attempts, or task is a failed
4898 * fork, never visible to cgroup_attach_task.
b4f48b63
PM
4899 */
4900void cgroup_exit(struct task_struct *tsk, int run_callbacks)
4901{
817929ec 4902 struct css_set *cg;
d41d5a01 4903 int i;
817929ec
PM
4904
4905 /*
4906 * Unlink from the css_set task list if necessary.
4907 * Optimistically check cg_list before taking
4908 * css_set_lock
4909 */
4910 if (!list_empty(&tsk->cg_list)) {
4911 write_lock(&css_set_lock);
4912 if (!list_empty(&tsk->cg_list))
8d258797 4913 list_del_init(&tsk->cg_list);
817929ec
PM
4914 write_unlock(&css_set_lock);
4915 }
4916
b4f48b63
PM
4917 /* Reassign the task to the init_css_set. */
4918 task_lock(tsk);
817929ec
PM
4919 cg = tsk->cgroups;
4920 tsk->cgroups = &init_css_set;
d41d5a01
PZ
4921
4922 if (run_callbacks && need_forkexit_callback) {
7d8e0bf5
LZ
4923 /*
4924 * fork/exit callbacks are supported only for builtin
4925 * subsystems, see cgroup_post_fork() for details.
4926 */
4927 for (i = 0; i < CGROUP_BUILTIN_SUBSYS_COUNT; i++) {
d41d5a01 4928 struct cgroup_subsys *ss = subsys[i];
be45c900 4929
d41d5a01
PZ
4930 if (ss->exit) {
4931 struct cgroup *old_cgrp =
4932 rcu_dereference_raw(cg->subsys[i])->cgroup;
4933 struct cgroup *cgrp = task_cgroup(tsk, i);
761b3ef5 4934 ss->exit(cgrp, old_cgrp, tsk);
d41d5a01
PZ
4935 }
4936 }
4937 }
b4f48b63 4938 task_unlock(tsk);
d41d5a01 4939
b5d646f5 4940 put_css_set_taskexit(cg);
b4f48b63 4941}
697f4161 4942
bd89aabc 4943static void check_for_release(struct cgroup *cgrp)
81a6a5cd
PM
4944{
4945 /* All of these checks rely on RCU to keep the cgroup
4946 * structure alive */
f50daa70
LZ
4947 if (cgroup_is_releasable(cgrp) &&
4948 !atomic_read(&cgrp->count) && list_empty(&cgrp->children)) {
4949 /*
4950 * Control Group is currently removeable. If it's not
81a6a5cd 4951 * already queued for a userspace notification, queue
f50daa70
LZ
4952 * it now
4953 */
81a6a5cd 4954 int need_schedule_work = 0;
f50daa70 4955
cdcc136f 4956 raw_spin_lock(&release_list_lock);
bd89aabc
PM
4957 if (!cgroup_is_removed(cgrp) &&
4958 list_empty(&cgrp->release_list)) {
4959 list_add(&cgrp->release_list, &release_list);
81a6a5cd
PM
4960 need_schedule_work = 1;
4961 }
cdcc136f 4962 raw_spin_unlock(&release_list_lock);
81a6a5cd
PM
4963 if (need_schedule_work)
4964 schedule_work(&release_agent_work);
4965 }
4966}
4967
d7b9fff7 4968/* Caller must verify that the css is not for root cgroup */
28b4c27b
TH
4969bool __css_tryget(struct cgroup_subsys_state *css)
4970{
e9316080
TH
4971 while (true) {
4972 int t, v;
28b4c27b 4973
e9316080
TH
4974 v = css_refcnt(css);
4975 t = atomic_cmpxchg(&css->refcnt, v, v + 1);
4976 if (likely(t == v))
28b4c27b 4977 return true;
e9316080
TH
4978 else if (t < 0)
4979 return false;
28b4c27b 4980 cpu_relax();
e9316080 4981 }
28b4c27b
TH
4982}
4983EXPORT_SYMBOL_GPL(__css_tryget);
4984
4985/* Caller must verify that the css is not for root cgroup */
4986void __css_put(struct cgroup_subsys_state *css)
81a6a5cd 4987{
8e3bbf42 4988 int v;
28b4c27b 4989
8e3bbf42 4990 v = css_unbias_refcnt(atomic_dec_return(&css->refcnt));
f50daa70 4991 if (v == 0)
ed957793 4992 schedule_work(&css->dput_work);
81a6a5cd 4993}
67523c48 4994EXPORT_SYMBOL_GPL(__css_put);
81a6a5cd
PM
4995
4996/*
4997 * Notify userspace when a cgroup is released, by running the
4998 * configured release agent with the name of the cgroup (path
4999 * relative to the root of cgroup file system) as the argument.
5000 *
5001 * Most likely, this user command will try to rmdir this cgroup.
5002 *
5003 * This races with the possibility that some other task will be
5004 * attached to this cgroup before it is removed, or that some other
5005 * user task will 'mkdir' a child cgroup of this cgroup. That's ok.
5006 * The presumed 'rmdir' will fail quietly if this cgroup is no longer
5007 * unused, and this cgroup will be reprieved from its death sentence,
5008 * to continue to serve a useful existence. Next time it's released,
5009 * we will get notified again, if it still has 'notify_on_release' set.
5010 *
5011 * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
5012 * means only wait until the task is successfully execve()'d. The
5013 * separate release agent task is forked by call_usermodehelper(),
5014 * then control in this thread returns here, without waiting for the
5015 * release agent task. We don't bother to wait because the caller of
5016 * this routine has no use for the exit status of the release agent
5017 * task, so no sense holding our caller up for that.
81a6a5cd 5018 */
81a6a5cd
PM
5019static void cgroup_release_agent(struct work_struct *work)
5020{
5021 BUG_ON(work != &release_agent_work);
5022 mutex_lock(&cgroup_mutex);
cdcc136f 5023 raw_spin_lock(&release_list_lock);
81a6a5cd
PM
5024 while (!list_empty(&release_list)) {
5025 char *argv[3], *envp[3];
5026 int i;
e788e066 5027 char *pathbuf = NULL, *agentbuf = NULL;
bd89aabc 5028 struct cgroup *cgrp = list_entry(release_list.next,
81a6a5cd
PM
5029 struct cgroup,
5030 release_list);
bd89aabc 5031 list_del_init(&cgrp->release_list);
cdcc136f 5032 raw_spin_unlock(&release_list_lock);
81a6a5cd 5033 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
e788e066
PM
5034 if (!pathbuf)
5035 goto continue_free;
5036 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
5037 goto continue_free;
5038 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
5039 if (!agentbuf)
5040 goto continue_free;
81a6a5cd
PM
5041
5042 i = 0;
e788e066
PM
5043 argv[i++] = agentbuf;
5044 argv[i++] = pathbuf;
81a6a5cd
PM
5045 argv[i] = NULL;
5046
5047 i = 0;
5048 /* minimal command environment */
5049 envp[i++] = "HOME=/";
5050 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
5051 envp[i] = NULL;
5052
5053 /* Drop the lock while we invoke the usermode helper,
5054 * since the exec could involve hitting disk and hence
5055 * be a slow process */
5056 mutex_unlock(&cgroup_mutex);
5057 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
81a6a5cd 5058 mutex_lock(&cgroup_mutex);
e788e066
PM
5059 continue_free:
5060 kfree(pathbuf);
5061 kfree(agentbuf);
cdcc136f 5062 raw_spin_lock(&release_list_lock);
81a6a5cd 5063 }
cdcc136f 5064 raw_spin_unlock(&release_list_lock);
81a6a5cd
PM
5065 mutex_unlock(&cgroup_mutex);
5066}
8bab8dde
PM
5067
5068static int __init cgroup_disable(char *str)
5069{
5070 int i;
5071 char *token;
5072
5073 while ((token = strsep(&str, ",")) != NULL) {
5074 if (!*token)
5075 continue;
be45c900 5076 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
8bab8dde
PM
5077 struct cgroup_subsys *ss = subsys[i];
5078
be45c900
DW
5079 /*
5080 * cgroup_disable, being at boot time, can't
5081 * know about module subsystems, so we don't
5082 * worry about them.
5083 */
5084 if (!ss || ss->module)
5085 continue;
5086
8bab8dde
PM
5087 if (!strcmp(token, ss->name)) {
5088 ss->disabled = 1;
5089 printk(KERN_INFO "Disabling %s control group"
5090 " subsystem\n", ss->name);
5091 break;
5092 }
5093 }
5094 }
5095 return 1;
5096}
5097__setup("cgroup_disable=", cgroup_disable);
38460b48
KH
5098
5099/*
5100 * Functons for CSS ID.
5101 */
5102
5103/*
5104 *To get ID other than 0, this should be called when !cgroup_is_removed().
5105 */
5106unsigned short css_id(struct cgroup_subsys_state *css)
5107{
7f0f1546
KH
5108 struct css_id *cssid;
5109
5110 /*
5111 * This css_id() can return correct value when somone has refcnt
5112 * on this or this is under rcu_read_lock(). Once css->id is allocated,
5113 * it's unchanged until freed.
5114 */
28b4c27b 5115 cssid = rcu_dereference_check(css->id, css_refcnt(css));
38460b48
KH
5116
5117 if (cssid)
5118 return cssid->id;
5119 return 0;
5120}
67523c48 5121EXPORT_SYMBOL_GPL(css_id);
38460b48
KH
5122
5123unsigned short css_depth(struct cgroup_subsys_state *css)
5124{
7f0f1546
KH
5125 struct css_id *cssid;
5126
28b4c27b 5127 cssid = rcu_dereference_check(css->id, css_refcnt(css));
38460b48
KH
5128
5129 if (cssid)
5130 return cssid->depth;
5131 return 0;
5132}
67523c48 5133EXPORT_SYMBOL_GPL(css_depth);
38460b48 5134
747388d7
KH
5135/**
5136 * css_is_ancestor - test "root" css is an ancestor of "child"
5137 * @child: the css to be tested.
5138 * @root: the css supporsed to be an ancestor of the child.
5139 *
5140 * Returns true if "root" is an ancestor of "child" in its hierarchy. Because
91c63734 5141 * this function reads css->id, the caller must hold rcu_read_lock().
747388d7
KH
5142 * But, considering usual usage, the csses should be valid objects after test.
5143 * Assuming that the caller will do some action to the child if this returns
5144 * returns true, the caller must take "child";s reference count.
5145 * If "child" is valid object and this returns true, "root" is valid, too.
5146 */
5147
38460b48 5148bool css_is_ancestor(struct cgroup_subsys_state *child,
0b7f569e 5149 const struct cgroup_subsys_state *root)
38460b48 5150{
747388d7
KH
5151 struct css_id *child_id;
5152 struct css_id *root_id;
38460b48 5153
747388d7 5154 child_id = rcu_dereference(child->id);
91c63734
JW
5155 if (!child_id)
5156 return false;
747388d7 5157 root_id = rcu_dereference(root->id);
91c63734
JW
5158 if (!root_id)
5159 return false;
5160 if (child_id->depth < root_id->depth)
5161 return false;
5162 if (child_id->stack[root_id->depth] != root_id->id)
5163 return false;
5164 return true;
38460b48
KH
5165}
5166
38460b48
KH
5167void free_css_id(struct cgroup_subsys *ss, struct cgroup_subsys_state *css)
5168{
5169 struct css_id *id = css->id;
5170 /* When this is called before css_id initialization, id can be NULL */
5171 if (!id)
5172 return;
5173
5174 BUG_ON(!ss->use_id);
5175
5176 rcu_assign_pointer(id->css, NULL);
5177 rcu_assign_pointer(css->id, NULL);
42aee6c4 5178 spin_lock(&ss->id_lock);
38460b48 5179 idr_remove(&ss->idr, id->id);
42aee6c4 5180 spin_unlock(&ss->id_lock);
025cea99 5181 kfree_rcu(id, rcu_head);
38460b48 5182}
67523c48 5183EXPORT_SYMBOL_GPL(free_css_id);
38460b48
KH
5184
5185/*
5186 * This is called by init or create(). Then, calls to this function are
5187 * always serialized (By cgroup_mutex() at create()).
5188 */
5189
5190static struct css_id *get_new_cssid(struct cgroup_subsys *ss, int depth)
5191{
5192 struct css_id *newid;
d228d9ec 5193 int ret, size;
38460b48
KH
5194
5195 BUG_ON(!ss->use_id);
5196
5197 size = sizeof(*newid) + sizeof(unsigned short) * (depth + 1);
5198 newid = kzalloc(size, GFP_KERNEL);
5199 if (!newid)
5200 return ERR_PTR(-ENOMEM);
d228d9ec
TH
5201
5202 idr_preload(GFP_KERNEL);
42aee6c4 5203 spin_lock(&ss->id_lock);
38460b48 5204 /* Don't use 0. allocates an ID of 1-65535 */
d228d9ec 5205 ret = idr_alloc(&ss->idr, newid, 1, CSS_ID_MAX + 1, GFP_NOWAIT);
42aee6c4 5206 spin_unlock(&ss->id_lock);
d228d9ec 5207 idr_preload_end();
38460b48
KH
5208
5209 /* Returns error when there are no free spaces for new ID.*/
d228d9ec 5210 if (ret < 0)
38460b48 5211 goto err_out;
38460b48 5212
d228d9ec 5213 newid->id = ret;
38460b48
KH
5214 newid->depth = depth;
5215 return newid;
38460b48
KH
5216err_out:
5217 kfree(newid);
d228d9ec 5218 return ERR_PTR(ret);
38460b48
KH
5219
5220}
5221
e6a1105b
BB
5222static int __init_or_module cgroup_init_idr(struct cgroup_subsys *ss,
5223 struct cgroup_subsys_state *rootcss)
38460b48
KH
5224{
5225 struct css_id *newid;
38460b48 5226
42aee6c4 5227 spin_lock_init(&ss->id_lock);
38460b48
KH
5228 idr_init(&ss->idr);
5229
38460b48
KH
5230 newid = get_new_cssid(ss, 0);
5231 if (IS_ERR(newid))
5232 return PTR_ERR(newid);
5233
5234 newid->stack[0] = newid->id;
5235 newid->css = rootcss;
5236 rootcss->id = newid;
5237 return 0;
5238}
5239
5240static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent,
5241 struct cgroup *child)
5242{
5243 int subsys_id, i, depth = 0;
5244 struct cgroup_subsys_state *parent_css, *child_css;
fae9c791 5245 struct css_id *child_id, *parent_id;
38460b48
KH
5246
5247 subsys_id = ss->subsys_id;
5248 parent_css = parent->subsys[subsys_id];
5249 child_css = child->subsys[subsys_id];
38460b48 5250 parent_id = parent_css->id;
94b3dd0f 5251 depth = parent_id->depth + 1;
38460b48
KH
5252
5253 child_id = get_new_cssid(ss, depth);
5254 if (IS_ERR(child_id))
5255 return PTR_ERR(child_id);
5256
5257 for (i = 0; i < depth; i++)
5258 child_id->stack[i] = parent_id->stack[i];
5259 child_id->stack[depth] = child_id->id;
5260 /*
5261 * child_id->css pointer will be set after this cgroup is available
5262 * see cgroup_populate_dir()
5263 */
5264 rcu_assign_pointer(child_css->id, child_id);
5265
5266 return 0;
5267}
5268
5269/**
5270 * css_lookup - lookup css by id
5271 * @ss: cgroup subsys to be looked into.
5272 * @id: the id
5273 *
5274 * Returns pointer to cgroup_subsys_state if there is valid one with id.
5275 * NULL if not. Should be called under rcu_read_lock()
5276 */
5277struct cgroup_subsys_state *css_lookup(struct cgroup_subsys *ss, int id)
5278{
5279 struct css_id *cssid = NULL;
5280
5281 BUG_ON(!ss->use_id);
5282 cssid = idr_find(&ss->idr, id);
5283
5284 if (unlikely(!cssid))
5285 return NULL;
5286
5287 return rcu_dereference(cssid->css);
5288}
67523c48 5289EXPORT_SYMBOL_GPL(css_lookup);
38460b48 5290
e5d1367f
SE
5291/*
5292 * get corresponding css from file open on cgroupfs directory
5293 */
5294struct cgroup_subsys_state *cgroup_css_from_dir(struct file *f, int id)
5295{
5296 struct cgroup *cgrp;
5297 struct inode *inode;
5298 struct cgroup_subsys_state *css;
5299
496ad9aa 5300 inode = file_inode(f);
e5d1367f
SE
5301 /* check in cgroup filesystem dir */
5302 if (inode->i_op != &cgroup_dir_inode_operations)
5303 return ERR_PTR(-EBADF);
5304
5305 if (id < 0 || id >= CGROUP_SUBSYS_COUNT)
5306 return ERR_PTR(-EINVAL);
5307
5308 /* get cgroup */
5309 cgrp = __d_cgrp(f->f_dentry);
5310 css = cgrp->subsys[id];
5311 return css ? css : ERR_PTR(-ENOENT);
5312}
5313
fe693435 5314#ifdef CONFIG_CGROUP_DEBUG
92fb9748 5315static struct cgroup_subsys_state *debug_css_alloc(struct cgroup *cont)
fe693435
PM
5316{
5317 struct cgroup_subsys_state *css = kzalloc(sizeof(*css), GFP_KERNEL);
5318
5319 if (!css)
5320 return ERR_PTR(-ENOMEM);
5321
5322 return css;
5323}
5324
92fb9748 5325static void debug_css_free(struct cgroup *cont)
fe693435
PM
5326{
5327 kfree(cont->subsys[debug_subsys_id]);
5328}
5329
5330static u64 cgroup_refcount_read(struct cgroup *cont, struct cftype *cft)
5331{
5332 return atomic_read(&cont->count);
5333}
5334
5335static u64 debug_taskcount_read(struct cgroup *cont, struct cftype *cft)
5336{
5337 return cgroup_task_count(cont);
5338}
5339
5340static u64 current_css_set_read(struct cgroup *cont, struct cftype *cft)
5341{
5342 return (u64)(unsigned long)current->cgroups;
5343}
5344
5345static u64 current_css_set_refcount_read(struct cgroup *cont,
5346 struct cftype *cft)
5347{
5348 u64 count;
5349
5350 rcu_read_lock();
5351 count = atomic_read(&current->cgroups->refcount);
5352 rcu_read_unlock();
5353 return count;
5354}
5355
7717f7ba
PM
5356static int current_css_set_cg_links_read(struct cgroup *cont,
5357 struct cftype *cft,
5358 struct seq_file *seq)
5359{
5360 struct cg_cgroup_link *link;
5361 struct css_set *cg;
5362
5363 read_lock(&css_set_lock);
5364 rcu_read_lock();
5365 cg = rcu_dereference(current->cgroups);
5366 list_for_each_entry(link, &cg->cg_links, cg_link_list) {
5367 struct cgroup *c = link->cgrp;
5368 const char *name;
5369
5370 if (c->dentry)
5371 name = c->dentry->d_name.name;
5372 else
5373 name = "?";
2c6ab6d2
PM
5374 seq_printf(seq, "Root %d group %s\n",
5375 c->root->hierarchy_id, name);
7717f7ba
PM
5376 }
5377 rcu_read_unlock();
5378 read_unlock(&css_set_lock);
5379 return 0;
5380}
5381
5382#define MAX_TASKS_SHOWN_PER_CSS 25
5383static int cgroup_css_links_read(struct cgroup *cont,
5384 struct cftype *cft,
5385 struct seq_file *seq)
5386{
5387 struct cg_cgroup_link *link;
5388
5389 read_lock(&css_set_lock);
5390 list_for_each_entry(link, &cont->css_sets, cgrp_link_list) {
5391 struct css_set *cg = link->cg;
5392 struct task_struct *task;
5393 int count = 0;
5394 seq_printf(seq, "css_set %p\n", cg);
5395 list_for_each_entry(task, &cg->tasks, cg_list) {
5396 if (count++ > MAX_TASKS_SHOWN_PER_CSS) {
5397 seq_puts(seq, " ...\n");
5398 break;
5399 } else {
5400 seq_printf(seq, " task %d\n",
5401 task_pid_vnr(task));
5402 }
5403 }
5404 }
5405 read_unlock(&css_set_lock);
5406 return 0;
5407}
5408
fe693435
PM
5409static u64 releasable_read(struct cgroup *cgrp, struct cftype *cft)
5410{
5411 return test_bit(CGRP_RELEASABLE, &cgrp->flags);
5412}
5413
5414static struct cftype debug_files[] = {
5415 {
5416 .name = "cgroup_refcount",
5417 .read_u64 = cgroup_refcount_read,
5418 },
5419 {
5420 .name = "taskcount",
5421 .read_u64 = debug_taskcount_read,
5422 },
5423
5424 {
5425 .name = "current_css_set",
5426 .read_u64 = current_css_set_read,
5427 },
5428
5429 {
5430 .name = "current_css_set_refcount",
5431 .read_u64 = current_css_set_refcount_read,
5432 },
5433
7717f7ba
PM
5434 {
5435 .name = "current_css_set_cg_links",
5436 .read_seq_string = current_css_set_cg_links_read,
5437 },
5438
5439 {
5440 .name = "cgroup_css_links",
5441 .read_seq_string = cgroup_css_links_read,
5442 },
5443
fe693435
PM
5444 {
5445 .name = "releasable",
5446 .read_u64 = releasable_read,
5447 },
fe693435 5448
4baf6e33
TH
5449 { } /* terminate */
5450};
fe693435
PM
5451
5452struct cgroup_subsys debug_subsys = {
5453 .name = "debug",
92fb9748
TH
5454 .css_alloc = debug_css_alloc,
5455 .css_free = debug_css_free,
fe693435 5456 .subsys_id = debug_subsys_id,
4baf6e33 5457 .base_cftypes = debug_files,
fe693435
PM
5458};
5459#endif /* CONFIG_CGROUP_DEBUG */