cgroups: misc cleanups to write_string patchset
[safe/jmp/linux-2.6] / kernel / cgroup.c
1 /*
2  *  Generic process-grouping system.
3  *
4  *  Based originally on the cpuset system, extracted by Paul Menage
5  *  Copyright (C) 2006 Google, Inc
6  *
7  *  Copyright notices from the original cpuset code:
8  *  --------------------------------------------------
9  *  Copyright (C) 2003 BULL SA.
10  *  Copyright (C) 2004-2006 Silicon Graphics, Inc.
11  *
12  *  Portions derived from Patrick Mochel's sysfs code.
13  *  sysfs is Copyright (c) 2001-3 Patrick Mochel
14  *
15  *  2003-10-10 Written by Simon Derr.
16  *  2003-10-22 Updates by Stephen Hemminger.
17  *  2004 May-July Rework by Paul Jackson.
18  *  ---------------------------------------------------
19  *
20  *  This file is subject to the terms and conditions of the GNU General Public
21  *  License.  See the file COPYING in the main directory of the Linux
22  *  distribution for more details.
23  */
24
25 #include <linux/cgroup.h>
26 #include <linux/errno.h>
27 #include <linux/fs.h>
28 #include <linux/kernel.h>
29 #include <linux/list.h>
30 #include <linux/mm.h>
31 #include <linux/mutex.h>
32 #include <linux/mount.h>
33 #include <linux/pagemap.h>
34 #include <linux/proc_fs.h>
35 #include <linux/rcupdate.h>
36 #include <linux/sched.h>
37 #include <linux/backing-dev.h>
38 #include <linux/seq_file.h>
39 #include <linux/slab.h>
40 #include <linux/magic.h>
41 #include <linux/spinlock.h>
42 #include <linux/string.h>
43 #include <linux/sort.h>
44 #include <linux/kmod.h>
45 #include <linux/delayacct.h>
46 #include <linux/cgroupstats.h>
47 #include <linux/hash.h>
48
49 #include <asm/atomic.h>
50
51 static DEFINE_MUTEX(cgroup_mutex);
52
53 /* Generate an array of cgroup subsystem pointers */
54 #define SUBSYS(_x) &_x ## _subsys,
55
56 static struct cgroup_subsys *subsys[] = {
57 #include <linux/cgroup_subsys.h>
58 };
59
60 /*
61  * A cgroupfs_root represents the root of a cgroup hierarchy,
62  * and may be associated with a superblock to form an active
63  * hierarchy
64  */
65 struct cgroupfs_root {
66         struct super_block *sb;
67
68         /*
69          * The bitmask of subsystems intended to be attached to this
70          * hierarchy
71          */
72         unsigned long subsys_bits;
73
74         /* The bitmask of subsystems currently attached to this hierarchy */
75         unsigned long actual_subsys_bits;
76
77         /* A list running through the attached subsystems */
78         struct list_head subsys_list;
79
80         /* The root cgroup for this hierarchy */
81         struct cgroup top_cgroup;
82
83         /* Tracks how many cgroups are currently defined in hierarchy.*/
84         int number_of_cgroups;
85
86         /* A list running through the mounted hierarchies */
87         struct list_head root_list;
88
89         /* Hierarchy-specific flags */
90         unsigned long flags;
91
92         /* The path to use for release notifications. */
93         char release_agent_path[PATH_MAX];
94 };
95
96
97 /*
98  * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the
99  * subsystems that are otherwise unattached - it never has more than a
100  * single cgroup, and all tasks are part of that cgroup.
101  */
102 static struct cgroupfs_root rootnode;
103
104 /* The list of hierarchy roots */
105
106 static LIST_HEAD(roots);
107 static int root_count;
108
109 /* dummytop is a shorthand for the dummy hierarchy's top cgroup */
110 #define dummytop (&rootnode.top_cgroup)
111
112 /* This flag indicates whether tasks in the fork and exit paths should
113  * check for fork/exit handlers to call. This avoids us having to do
114  * extra work in the fork/exit path if none of the subsystems need to
115  * be called.
116  */
117 static int need_forkexit_callback __read_mostly;
118 static int need_mm_owner_callback __read_mostly;
119
120 /* convenient tests for these bits */
121 inline int cgroup_is_removed(const struct cgroup *cgrp)
122 {
123         return test_bit(CGRP_REMOVED, &cgrp->flags);
124 }
125
126 /* bits in struct cgroupfs_root flags field */
127 enum {
128         ROOT_NOPREFIX, /* mounted subsystems have no named prefix */
129 };
130
131 static int cgroup_is_releasable(const struct cgroup *cgrp)
132 {
133         const int bits =
134                 (1 << CGRP_RELEASABLE) |
135                 (1 << CGRP_NOTIFY_ON_RELEASE);
136         return (cgrp->flags & bits) == bits;
137 }
138
139 static int notify_on_release(const struct cgroup *cgrp)
140 {
141         return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
142 }
143
144 /*
145  * for_each_subsys() allows you to iterate on each subsystem attached to
146  * an active hierarchy
147  */
148 #define for_each_subsys(_root, _ss) \
149 list_for_each_entry(_ss, &_root->subsys_list, sibling)
150
151 /* for_each_root() allows you to iterate across the active hierarchies */
152 #define for_each_root(_root) \
153 list_for_each_entry(_root, &roots, root_list)
154
155 /* the list of cgroups eligible for automatic release. Protected by
156  * release_list_lock */
157 static LIST_HEAD(release_list);
158 static DEFINE_SPINLOCK(release_list_lock);
159 static void cgroup_release_agent(struct work_struct *work);
160 static DECLARE_WORK(release_agent_work, cgroup_release_agent);
161 static void check_for_release(struct cgroup *cgrp);
162
163 /* Link structure for associating css_set objects with cgroups */
164 struct cg_cgroup_link {
165         /*
166          * List running through cg_cgroup_links associated with a
167          * cgroup, anchored on cgroup->css_sets
168          */
169         struct list_head cgrp_link_list;
170         /*
171          * List running through cg_cgroup_links pointing at a
172          * single css_set object, anchored on css_set->cg_links
173          */
174         struct list_head cg_link_list;
175         struct css_set *cg;
176 };
177
178 /* The default css_set - used by init and its children prior to any
179  * hierarchies being mounted. It contains a pointer to the root state
180  * for each subsystem. Also used to anchor the list of css_sets. Not
181  * reference-counted, to improve performance when child cgroups
182  * haven't been created.
183  */
184
185 static struct css_set init_css_set;
186 static struct cg_cgroup_link init_css_set_link;
187
188 /* css_set_lock protects the list of css_set objects, and the
189  * chain of tasks off each css_set.  Nests outside task->alloc_lock
190  * due to cgroup_iter_start() */
191 static DEFINE_RWLOCK(css_set_lock);
192 static int css_set_count;
193
194 /* hash table for cgroup groups. This improves the performance to
195  * find an existing css_set */
196 #define CSS_SET_HASH_BITS       7
197 #define CSS_SET_TABLE_SIZE      (1 << CSS_SET_HASH_BITS)
198 static struct hlist_head css_set_table[CSS_SET_TABLE_SIZE];
199
200 static struct hlist_head *css_set_hash(struct cgroup_subsys_state *css[])
201 {
202         int i;
203         int index;
204         unsigned long tmp = 0UL;
205
206         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++)
207                 tmp += (unsigned long)css[i];
208         tmp = (tmp >> 16) ^ tmp;
209
210         index = hash_long(tmp, CSS_SET_HASH_BITS);
211
212         return &css_set_table[index];
213 }
214
215 /* We don't maintain the lists running through each css_set to its
216  * task until after the first call to cgroup_iter_start(). This
217  * reduces the fork()/exit() overhead for people who have cgroups
218  * compiled into their kernel but not actually in use */
219 static int use_task_css_set_links __read_mostly;
220
221 /* When we create or destroy a css_set, the operation simply
222  * takes/releases a reference count on all the cgroups referenced
223  * by subsystems in this css_set. This can end up multiple-counting
224  * some cgroups, but that's OK - the ref-count is just a
225  * busy/not-busy indicator; ensuring that we only count each cgroup
226  * once would require taking a global lock to ensure that no
227  * subsystems moved between hierarchies while we were doing so.
228  *
229  * Possible TODO: decide at boot time based on the number of
230  * registered subsystems and the number of CPUs or NUMA nodes whether
231  * it's better for performance to ref-count every subsystem, or to
232  * take a global lock and only add one ref count to each hierarchy.
233  */
234
235 /*
236  * unlink a css_set from the list and free it
237  */
238 static void unlink_css_set(struct css_set *cg)
239 {
240         struct cg_cgroup_link *link;
241         struct cg_cgroup_link *saved_link;
242
243         write_lock(&css_set_lock);
244         hlist_del(&cg->hlist);
245         css_set_count--;
246
247         list_for_each_entry_safe(link, saved_link, &cg->cg_links,
248                                  cg_link_list) {
249                 list_del(&link->cg_link_list);
250                 list_del(&link->cgrp_link_list);
251                 kfree(link);
252         }
253
254         write_unlock(&css_set_lock);
255 }
256
257 static void __release_css_set(struct kref *k, int taskexit)
258 {
259         int i;
260         struct css_set *cg = container_of(k, struct css_set, ref);
261
262         unlink_css_set(cg);
263
264         rcu_read_lock();
265         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
266                 struct cgroup *cgrp = cg->subsys[i]->cgroup;
267                 if (atomic_dec_and_test(&cgrp->count) &&
268                     notify_on_release(cgrp)) {
269                         if (taskexit)
270                                 set_bit(CGRP_RELEASABLE, &cgrp->flags);
271                         check_for_release(cgrp);
272                 }
273         }
274         rcu_read_unlock();
275         kfree(cg);
276 }
277
278 static void release_css_set(struct kref *k)
279 {
280         __release_css_set(k, 0);
281 }
282
283 static void release_css_set_taskexit(struct kref *k)
284 {
285         __release_css_set(k, 1);
286 }
287
288 /*
289  * refcounted get/put for css_set objects
290  */
291 static inline void get_css_set(struct css_set *cg)
292 {
293         kref_get(&cg->ref);
294 }
295
296 static inline void put_css_set(struct css_set *cg)
297 {
298         kref_put(&cg->ref, release_css_set);
299 }
300
301 static inline void put_css_set_taskexit(struct css_set *cg)
302 {
303         kref_put(&cg->ref, release_css_set_taskexit);
304 }
305
306 /*
307  * find_existing_css_set() is a helper for
308  * find_css_set(), and checks to see whether an existing
309  * css_set is suitable.
310  *
311  * oldcg: the cgroup group that we're using before the cgroup
312  * transition
313  *
314  * cgrp: the cgroup that we're moving into
315  *
316  * template: location in which to build the desired set of subsystem
317  * state objects for the new cgroup group
318  */
319 static struct css_set *find_existing_css_set(
320         struct css_set *oldcg,
321         struct cgroup *cgrp,
322         struct cgroup_subsys_state *template[])
323 {
324         int i;
325         struct cgroupfs_root *root = cgrp->root;
326         struct hlist_head *hhead;
327         struct hlist_node *node;
328         struct css_set *cg;
329
330         /* Built the set of subsystem state objects that we want to
331          * see in the new css_set */
332         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
333                 if (root->subsys_bits & (1UL << i)) {
334                         /* Subsystem is in this hierarchy. So we want
335                          * the subsystem state from the new
336                          * cgroup */
337                         template[i] = cgrp->subsys[i];
338                 } else {
339                         /* Subsystem is not in this hierarchy, so we
340                          * don't want to change the subsystem state */
341                         template[i] = oldcg->subsys[i];
342                 }
343         }
344
345         hhead = css_set_hash(template);
346         hlist_for_each_entry(cg, node, hhead, hlist) {
347                 if (!memcmp(template, cg->subsys, sizeof(cg->subsys))) {
348                         /* All subsystems matched */
349                         return cg;
350                 }
351         }
352
353         /* No existing cgroup group matched */
354         return NULL;
355 }
356
357 /*
358  * allocate_cg_links() allocates "count" cg_cgroup_link structures
359  * and chains them on tmp through their cgrp_link_list fields. Returns 0 on
360  * success or a negative error
361  */
362 static int allocate_cg_links(int count, struct list_head *tmp)
363 {
364         struct cg_cgroup_link *link;
365         struct cg_cgroup_link *saved_link;
366         int i;
367         INIT_LIST_HEAD(tmp);
368         for (i = 0; i < count; i++) {
369                 link = kmalloc(sizeof(*link), GFP_KERNEL);
370                 if (!link) {
371                         list_for_each_entry_safe(link, saved_link, tmp,
372                                                  cgrp_link_list) {
373                                 list_del(&link->cgrp_link_list);
374                                 kfree(link);
375                         }
376                         return -ENOMEM;
377                 }
378                 list_add(&link->cgrp_link_list, tmp);
379         }
380         return 0;
381 }
382
383 static void free_cg_links(struct list_head *tmp)
384 {
385         struct cg_cgroup_link *link;
386         struct cg_cgroup_link *saved_link;
387
388         list_for_each_entry_safe(link, saved_link, tmp, cgrp_link_list) {
389                 list_del(&link->cgrp_link_list);
390                 kfree(link);
391         }
392 }
393
394 /*
395  * find_css_set() takes an existing cgroup group and a
396  * cgroup object, and returns a css_set object that's
397  * equivalent to the old group, but with the given cgroup
398  * substituted into the appropriate hierarchy. Must be called with
399  * cgroup_mutex held
400  */
401 static struct css_set *find_css_set(
402         struct css_set *oldcg, struct cgroup *cgrp)
403 {
404         struct css_set *res;
405         struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT];
406         int i;
407
408         struct list_head tmp_cg_links;
409         struct cg_cgroup_link *link;
410
411         struct hlist_head *hhead;
412
413         /* First see if we already have a cgroup group that matches
414          * the desired set */
415         read_lock(&css_set_lock);
416         res = find_existing_css_set(oldcg, cgrp, template);
417         if (res)
418                 get_css_set(res);
419         read_unlock(&css_set_lock);
420
421         if (res)
422                 return res;
423
424         res = kmalloc(sizeof(*res), GFP_KERNEL);
425         if (!res)
426                 return NULL;
427
428         /* Allocate all the cg_cgroup_link objects that we'll need */
429         if (allocate_cg_links(root_count, &tmp_cg_links) < 0) {
430                 kfree(res);
431                 return NULL;
432         }
433
434         kref_init(&res->ref);
435         INIT_LIST_HEAD(&res->cg_links);
436         INIT_LIST_HEAD(&res->tasks);
437         INIT_HLIST_NODE(&res->hlist);
438
439         /* Copy the set of subsystem state objects generated in
440          * find_existing_css_set() */
441         memcpy(res->subsys, template, sizeof(res->subsys));
442
443         write_lock(&css_set_lock);
444         /* Add reference counts and links from the new css_set. */
445         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
446                 struct cgroup *cgrp = res->subsys[i]->cgroup;
447                 struct cgroup_subsys *ss = subsys[i];
448                 atomic_inc(&cgrp->count);
449                 /*
450                  * We want to add a link once per cgroup, so we
451                  * only do it for the first subsystem in each
452                  * hierarchy
453                  */
454                 if (ss->root->subsys_list.next == &ss->sibling) {
455                         BUG_ON(list_empty(&tmp_cg_links));
456                         link = list_entry(tmp_cg_links.next,
457                                           struct cg_cgroup_link,
458                                           cgrp_link_list);
459                         list_del(&link->cgrp_link_list);
460                         list_add(&link->cgrp_link_list, &cgrp->css_sets);
461                         link->cg = res;
462                         list_add(&link->cg_link_list, &res->cg_links);
463                 }
464         }
465         if (list_empty(&rootnode.subsys_list)) {
466                 link = list_entry(tmp_cg_links.next,
467                                   struct cg_cgroup_link,
468                                   cgrp_link_list);
469                 list_del(&link->cgrp_link_list);
470                 list_add(&link->cgrp_link_list, &dummytop->css_sets);
471                 link->cg = res;
472                 list_add(&link->cg_link_list, &res->cg_links);
473         }
474
475         BUG_ON(!list_empty(&tmp_cg_links));
476
477         css_set_count++;
478
479         /* Add this cgroup group to the hash table */
480         hhead = css_set_hash(res->subsys);
481         hlist_add_head(&res->hlist, hhead);
482
483         write_unlock(&css_set_lock);
484
485         return res;
486 }
487
488 /*
489  * There is one global cgroup mutex. We also require taking
490  * task_lock() when dereferencing a task's cgroup subsys pointers.
491  * See "The task_lock() exception", at the end of this comment.
492  *
493  * A task must hold cgroup_mutex to modify cgroups.
494  *
495  * Any task can increment and decrement the count field without lock.
496  * So in general, code holding cgroup_mutex can't rely on the count
497  * field not changing.  However, if the count goes to zero, then only
498  * cgroup_attach_task() can increment it again.  Because a count of zero
499  * means that no tasks are currently attached, therefore there is no
500  * way a task attached to that cgroup can fork (the other way to
501  * increment the count).  So code holding cgroup_mutex can safely
502  * assume that if the count is zero, it will stay zero. Similarly, if
503  * a task holds cgroup_mutex on a cgroup with zero count, it
504  * knows that the cgroup won't be removed, as cgroup_rmdir()
505  * needs that mutex.
506  *
507  * The cgroup_common_file_write handler for operations that modify
508  * the cgroup hierarchy holds cgroup_mutex across the entire operation,
509  * single threading all such cgroup modifications across the system.
510  *
511  * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't
512  * (usually) take cgroup_mutex.  These are the two most performance
513  * critical pieces of code here.  The exception occurs on cgroup_exit(),
514  * when a task in a notify_on_release cgroup exits.  Then cgroup_mutex
515  * is taken, and if the cgroup count is zero, a usermode call made
516  * to the release agent with the name of the cgroup (path relative to
517  * the root of cgroup file system) as the argument.
518  *
519  * A cgroup can only be deleted if both its 'count' of using tasks
520  * is zero, and its list of 'children' cgroups is empty.  Since all
521  * tasks in the system use _some_ cgroup, and since there is always at
522  * least one task in the system (init, pid == 1), therefore, top_cgroup
523  * always has either children cgroups and/or using tasks.  So we don't
524  * need a special hack to ensure that top_cgroup cannot be deleted.
525  *
526  *      The task_lock() exception
527  *
528  * The need for this exception arises from the action of
529  * cgroup_attach_task(), which overwrites one tasks cgroup pointer with
530  * another.  It does so using cgroup_mutex, however there are
531  * several performance critical places that need to reference
532  * task->cgroup without the expense of grabbing a system global
533  * mutex.  Therefore except as noted below, when dereferencing or, as
534  * in cgroup_attach_task(), modifying a task'ss cgroup pointer we use
535  * task_lock(), which acts on a spinlock (task->alloc_lock) already in
536  * the task_struct routinely used for such matters.
537  *
538  * P.S.  One more locking exception.  RCU is used to guard the
539  * update of a tasks cgroup pointer by cgroup_attach_task()
540  */
541
542 /**
543  * cgroup_lock - lock out any changes to cgroup structures
544  *
545  */
546 void cgroup_lock(void)
547 {
548         mutex_lock(&cgroup_mutex);
549 }
550
551 /**
552  * cgroup_unlock - release lock on cgroup changes
553  *
554  * Undo the lock taken in a previous cgroup_lock() call.
555  */
556 void cgroup_unlock(void)
557 {
558         mutex_unlock(&cgroup_mutex);
559 }
560
561 /*
562  * A couple of forward declarations required, due to cyclic reference loop:
563  * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir ->
564  * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations
565  * -> cgroup_mkdir.
566  */
567
568 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode);
569 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry);
570 static int cgroup_populate_dir(struct cgroup *cgrp);
571 static struct inode_operations cgroup_dir_inode_operations;
572 static struct file_operations proc_cgroupstats_operations;
573
574 static struct backing_dev_info cgroup_backing_dev_info = {
575         .capabilities   = BDI_CAP_NO_ACCT_AND_WRITEBACK,
576 };
577
578 static struct inode *cgroup_new_inode(mode_t mode, struct super_block *sb)
579 {
580         struct inode *inode = new_inode(sb);
581
582         if (inode) {
583                 inode->i_mode = mode;
584                 inode->i_uid = current->fsuid;
585                 inode->i_gid = current->fsgid;
586                 inode->i_blocks = 0;
587                 inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
588                 inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info;
589         }
590         return inode;
591 }
592
593 /*
594  * Call subsys's pre_destroy handler.
595  * This is called before css refcnt check.
596  */
597 static void cgroup_call_pre_destroy(struct cgroup *cgrp)
598 {
599         struct cgroup_subsys *ss;
600         for_each_subsys(cgrp->root, ss)
601                 if (ss->pre_destroy && cgrp->subsys[ss->subsys_id])
602                         ss->pre_destroy(ss, cgrp);
603         return;
604 }
605
606 static void cgroup_diput(struct dentry *dentry, struct inode *inode)
607 {
608         /* is dentry a directory ? if so, kfree() associated cgroup */
609         if (S_ISDIR(inode->i_mode)) {
610                 struct cgroup *cgrp = dentry->d_fsdata;
611                 struct cgroup_subsys *ss;
612                 BUG_ON(!(cgroup_is_removed(cgrp)));
613                 /* It's possible for external users to be holding css
614                  * reference counts on a cgroup; css_put() needs to
615                  * be able to access the cgroup after decrementing
616                  * the reference count in order to know if it needs to
617                  * queue the cgroup to be handled by the release
618                  * agent */
619                 synchronize_rcu();
620
621                 mutex_lock(&cgroup_mutex);
622                 /*
623                  * Release the subsystem state objects.
624                  */
625                 for_each_subsys(cgrp->root, ss) {
626                         if (cgrp->subsys[ss->subsys_id])
627                                 ss->destroy(ss, cgrp);
628                 }
629
630                 cgrp->root->number_of_cgroups--;
631                 mutex_unlock(&cgroup_mutex);
632
633                 /* Drop the active superblock reference that we took when we
634                  * created the cgroup */
635                 deactivate_super(cgrp->root->sb);
636
637                 kfree(cgrp);
638         }
639         iput(inode);
640 }
641
642 static void remove_dir(struct dentry *d)
643 {
644         struct dentry *parent = dget(d->d_parent);
645
646         d_delete(d);
647         simple_rmdir(parent->d_inode, d);
648         dput(parent);
649 }
650
651 static void cgroup_clear_directory(struct dentry *dentry)
652 {
653         struct list_head *node;
654
655         BUG_ON(!mutex_is_locked(&dentry->d_inode->i_mutex));
656         spin_lock(&dcache_lock);
657         node = dentry->d_subdirs.next;
658         while (node != &dentry->d_subdirs) {
659                 struct dentry *d = list_entry(node, struct dentry, d_u.d_child);
660                 list_del_init(node);
661                 if (d->d_inode) {
662                         /* This should never be called on a cgroup
663                          * directory with child cgroups */
664                         BUG_ON(d->d_inode->i_mode & S_IFDIR);
665                         d = dget_locked(d);
666                         spin_unlock(&dcache_lock);
667                         d_delete(d);
668                         simple_unlink(dentry->d_inode, d);
669                         dput(d);
670                         spin_lock(&dcache_lock);
671                 }
672                 node = dentry->d_subdirs.next;
673         }
674         spin_unlock(&dcache_lock);
675 }
676
677 /*
678  * NOTE : the dentry must have been dget()'ed
679  */
680 static void cgroup_d_remove_dir(struct dentry *dentry)
681 {
682         cgroup_clear_directory(dentry);
683
684         spin_lock(&dcache_lock);
685         list_del_init(&dentry->d_u.d_child);
686         spin_unlock(&dcache_lock);
687         remove_dir(dentry);
688 }
689
690 static int rebind_subsystems(struct cgroupfs_root *root,
691                               unsigned long final_bits)
692 {
693         unsigned long added_bits, removed_bits;
694         struct cgroup *cgrp = &root->top_cgroup;
695         int i;
696
697         removed_bits = root->actual_subsys_bits & ~final_bits;
698         added_bits = final_bits & ~root->actual_subsys_bits;
699         /* Check that any added subsystems are currently free */
700         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
701                 unsigned long bit = 1UL << i;
702                 struct cgroup_subsys *ss = subsys[i];
703                 if (!(bit & added_bits))
704                         continue;
705                 if (ss->root != &rootnode) {
706                         /* Subsystem isn't free */
707                         return -EBUSY;
708                 }
709         }
710
711         /* Currently we don't handle adding/removing subsystems when
712          * any child cgroups exist. This is theoretically supportable
713          * but involves complex error handling, so it's being left until
714          * later */
715         if (!list_empty(&cgrp->children))
716                 return -EBUSY;
717
718         /* Process each subsystem */
719         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
720                 struct cgroup_subsys *ss = subsys[i];
721                 unsigned long bit = 1UL << i;
722                 if (bit & added_bits) {
723                         /* We're binding this subsystem to this hierarchy */
724                         BUG_ON(cgrp->subsys[i]);
725                         BUG_ON(!dummytop->subsys[i]);
726                         BUG_ON(dummytop->subsys[i]->cgroup != dummytop);
727                         cgrp->subsys[i] = dummytop->subsys[i];
728                         cgrp->subsys[i]->cgroup = cgrp;
729                         list_add(&ss->sibling, &root->subsys_list);
730                         rcu_assign_pointer(ss->root, root);
731                         if (ss->bind)
732                                 ss->bind(ss, cgrp);
733
734                 } else if (bit & removed_bits) {
735                         /* We're removing this subsystem */
736                         BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]);
737                         BUG_ON(cgrp->subsys[i]->cgroup != cgrp);
738                         if (ss->bind)
739                                 ss->bind(ss, dummytop);
740                         dummytop->subsys[i]->cgroup = dummytop;
741                         cgrp->subsys[i] = NULL;
742                         rcu_assign_pointer(subsys[i]->root, &rootnode);
743                         list_del(&ss->sibling);
744                 } else if (bit & final_bits) {
745                         /* Subsystem state should already exist */
746                         BUG_ON(!cgrp->subsys[i]);
747                 } else {
748                         /* Subsystem state shouldn't exist */
749                         BUG_ON(cgrp->subsys[i]);
750                 }
751         }
752         root->subsys_bits = root->actual_subsys_bits = final_bits;
753         synchronize_rcu();
754
755         return 0;
756 }
757
758 static int cgroup_show_options(struct seq_file *seq, struct vfsmount *vfs)
759 {
760         struct cgroupfs_root *root = vfs->mnt_sb->s_fs_info;
761         struct cgroup_subsys *ss;
762
763         mutex_lock(&cgroup_mutex);
764         for_each_subsys(root, ss)
765                 seq_printf(seq, ",%s", ss->name);
766         if (test_bit(ROOT_NOPREFIX, &root->flags))
767                 seq_puts(seq, ",noprefix");
768         if (strlen(root->release_agent_path))
769                 seq_printf(seq, ",release_agent=%s", root->release_agent_path);
770         mutex_unlock(&cgroup_mutex);
771         return 0;
772 }
773
774 struct cgroup_sb_opts {
775         unsigned long subsys_bits;
776         unsigned long flags;
777         char *release_agent;
778 };
779
780 /* Convert a hierarchy specifier into a bitmask of subsystems and
781  * flags. */
782 static int parse_cgroupfs_options(char *data,
783                                      struct cgroup_sb_opts *opts)
784 {
785         char *token, *o = data ?: "all";
786
787         opts->subsys_bits = 0;
788         opts->flags = 0;
789         opts->release_agent = NULL;
790
791         while ((token = strsep(&o, ",")) != NULL) {
792                 if (!*token)
793                         return -EINVAL;
794                 if (!strcmp(token, "all")) {
795                         /* Add all non-disabled subsystems */
796                         int i;
797                         opts->subsys_bits = 0;
798                         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
799                                 struct cgroup_subsys *ss = subsys[i];
800                                 if (!ss->disabled)
801                                         opts->subsys_bits |= 1ul << i;
802                         }
803                 } else if (!strcmp(token, "noprefix")) {
804                         set_bit(ROOT_NOPREFIX, &opts->flags);
805                 } else if (!strncmp(token, "release_agent=", 14)) {
806                         /* Specifying two release agents is forbidden */
807                         if (opts->release_agent)
808                                 return -EINVAL;
809                         opts->release_agent = kzalloc(PATH_MAX, GFP_KERNEL);
810                         if (!opts->release_agent)
811                                 return -ENOMEM;
812                         strncpy(opts->release_agent, token + 14, PATH_MAX - 1);
813                         opts->release_agent[PATH_MAX - 1] = 0;
814                 } else {
815                         struct cgroup_subsys *ss;
816                         int i;
817                         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
818                                 ss = subsys[i];
819                                 if (!strcmp(token, ss->name)) {
820                                         if (!ss->disabled)
821                                                 set_bit(i, &opts->subsys_bits);
822                                         break;
823                                 }
824                         }
825                         if (i == CGROUP_SUBSYS_COUNT)
826                                 return -ENOENT;
827                 }
828         }
829
830         /* We can't have an empty hierarchy */
831         if (!opts->subsys_bits)
832                 return -EINVAL;
833
834         return 0;
835 }
836
837 static int cgroup_remount(struct super_block *sb, int *flags, char *data)
838 {
839         int ret = 0;
840         struct cgroupfs_root *root = sb->s_fs_info;
841         struct cgroup *cgrp = &root->top_cgroup;
842         struct cgroup_sb_opts opts;
843
844         mutex_lock(&cgrp->dentry->d_inode->i_mutex);
845         mutex_lock(&cgroup_mutex);
846
847         /* See what subsystems are wanted */
848         ret = parse_cgroupfs_options(data, &opts);
849         if (ret)
850                 goto out_unlock;
851
852         /* Don't allow flags to change at remount */
853         if (opts.flags != root->flags) {
854                 ret = -EINVAL;
855                 goto out_unlock;
856         }
857
858         ret = rebind_subsystems(root, opts.subsys_bits);
859
860         /* (re)populate subsystem files */
861         if (!ret)
862                 cgroup_populate_dir(cgrp);
863
864         if (opts.release_agent)
865                 strcpy(root->release_agent_path, opts.release_agent);
866  out_unlock:
867         if (opts.release_agent)
868                 kfree(opts.release_agent);
869         mutex_unlock(&cgroup_mutex);
870         mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
871         return ret;
872 }
873
874 static struct super_operations cgroup_ops = {
875         .statfs = simple_statfs,
876         .drop_inode = generic_delete_inode,
877         .show_options = cgroup_show_options,
878         .remount_fs = cgroup_remount,
879 };
880
881 static void init_cgroup_root(struct cgroupfs_root *root)
882 {
883         struct cgroup *cgrp = &root->top_cgroup;
884         INIT_LIST_HEAD(&root->subsys_list);
885         INIT_LIST_HEAD(&root->root_list);
886         root->number_of_cgroups = 1;
887         cgrp->root = root;
888         cgrp->top_cgroup = cgrp;
889         INIT_LIST_HEAD(&cgrp->sibling);
890         INIT_LIST_HEAD(&cgrp->children);
891         INIT_LIST_HEAD(&cgrp->css_sets);
892         INIT_LIST_HEAD(&cgrp->release_list);
893 }
894
895 static int cgroup_test_super(struct super_block *sb, void *data)
896 {
897         struct cgroupfs_root *new = data;
898         struct cgroupfs_root *root = sb->s_fs_info;
899
900         /* First check subsystems */
901         if (new->subsys_bits != root->subsys_bits)
902             return 0;
903
904         /* Next check flags */
905         if (new->flags != root->flags)
906                 return 0;
907
908         return 1;
909 }
910
911 static int cgroup_set_super(struct super_block *sb, void *data)
912 {
913         int ret;
914         struct cgroupfs_root *root = data;
915
916         ret = set_anon_super(sb, NULL);
917         if (ret)
918                 return ret;
919
920         sb->s_fs_info = root;
921         root->sb = sb;
922
923         sb->s_blocksize = PAGE_CACHE_SIZE;
924         sb->s_blocksize_bits = PAGE_CACHE_SHIFT;
925         sb->s_magic = CGROUP_SUPER_MAGIC;
926         sb->s_op = &cgroup_ops;
927
928         return 0;
929 }
930
931 static int cgroup_get_rootdir(struct super_block *sb)
932 {
933         struct inode *inode =
934                 cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb);
935         struct dentry *dentry;
936
937         if (!inode)
938                 return -ENOMEM;
939
940         inode->i_fop = &simple_dir_operations;
941         inode->i_op = &cgroup_dir_inode_operations;
942         /* directories start off with i_nlink == 2 (for "." entry) */
943         inc_nlink(inode);
944         dentry = d_alloc_root(inode);
945         if (!dentry) {
946                 iput(inode);
947                 return -ENOMEM;
948         }
949         sb->s_root = dentry;
950         return 0;
951 }
952
953 static int cgroup_get_sb(struct file_system_type *fs_type,
954                          int flags, const char *unused_dev_name,
955                          void *data, struct vfsmount *mnt)
956 {
957         struct cgroup_sb_opts opts;
958         int ret = 0;
959         struct super_block *sb;
960         struct cgroupfs_root *root;
961         struct list_head tmp_cg_links;
962         INIT_LIST_HEAD(&tmp_cg_links);
963
964         /* First find the desired set of subsystems */
965         ret = parse_cgroupfs_options(data, &opts);
966         if (ret) {
967                 if (opts.release_agent)
968                         kfree(opts.release_agent);
969                 return ret;
970         }
971
972         root = kzalloc(sizeof(*root), GFP_KERNEL);
973         if (!root) {
974                 if (opts.release_agent)
975                         kfree(opts.release_agent);
976                 return -ENOMEM;
977         }
978
979         init_cgroup_root(root);
980         root->subsys_bits = opts.subsys_bits;
981         root->flags = opts.flags;
982         if (opts.release_agent) {
983                 strcpy(root->release_agent_path, opts.release_agent);
984                 kfree(opts.release_agent);
985         }
986
987         sb = sget(fs_type, cgroup_test_super, cgroup_set_super, root);
988
989         if (IS_ERR(sb)) {
990                 kfree(root);
991                 return PTR_ERR(sb);
992         }
993
994         if (sb->s_fs_info != root) {
995                 /* Reusing an existing superblock */
996                 BUG_ON(sb->s_root == NULL);
997                 kfree(root);
998                 root = NULL;
999         } else {
1000                 /* New superblock */
1001                 struct cgroup *cgrp = &root->top_cgroup;
1002                 struct inode *inode;
1003                 int i;
1004
1005                 BUG_ON(sb->s_root != NULL);
1006
1007                 ret = cgroup_get_rootdir(sb);
1008                 if (ret)
1009                         goto drop_new_super;
1010                 inode = sb->s_root->d_inode;
1011
1012                 mutex_lock(&inode->i_mutex);
1013                 mutex_lock(&cgroup_mutex);
1014
1015                 /*
1016                  * We're accessing css_set_count without locking
1017                  * css_set_lock here, but that's OK - it can only be
1018                  * increased by someone holding cgroup_lock, and
1019                  * that's us. The worst that can happen is that we
1020                  * have some link structures left over
1021                  */
1022                 ret = allocate_cg_links(css_set_count, &tmp_cg_links);
1023                 if (ret) {
1024                         mutex_unlock(&cgroup_mutex);
1025                         mutex_unlock(&inode->i_mutex);
1026                         goto drop_new_super;
1027                 }
1028
1029                 ret = rebind_subsystems(root, root->subsys_bits);
1030                 if (ret == -EBUSY) {
1031                         mutex_unlock(&cgroup_mutex);
1032                         mutex_unlock(&inode->i_mutex);
1033                         goto drop_new_super;
1034                 }
1035
1036                 /* EBUSY should be the only error here */
1037                 BUG_ON(ret);
1038
1039                 list_add(&root->root_list, &roots);
1040                 root_count++;
1041
1042                 sb->s_root->d_fsdata = &root->top_cgroup;
1043                 root->top_cgroup.dentry = sb->s_root;
1044
1045                 /* Link the top cgroup in this hierarchy into all
1046                  * the css_set objects */
1047                 write_lock(&css_set_lock);
1048                 for (i = 0; i < CSS_SET_TABLE_SIZE; i++) {
1049                         struct hlist_head *hhead = &css_set_table[i];
1050                         struct hlist_node *node;
1051                         struct css_set *cg;
1052
1053                         hlist_for_each_entry(cg, node, hhead, hlist) {
1054                                 struct cg_cgroup_link *link;
1055
1056                                 BUG_ON(list_empty(&tmp_cg_links));
1057                                 link = list_entry(tmp_cg_links.next,
1058                                                   struct cg_cgroup_link,
1059                                                   cgrp_link_list);
1060                                 list_del(&link->cgrp_link_list);
1061                                 link->cg = cg;
1062                                 list_add(&link->cgrp_link_list,
1063                                          &root->top_cgroup.css_sets);
1064                                 list_add(&link->cg_link_list, &cg->cg_links);
1065                         }
1066                 }
1067                 write_unlock(&css_set_lock);
1068
1069                 free_cg_links(&tmp_cg_links);
1070
1071                 BUG_ON(!list_empty(&cgrp->sibling));
1072                 BUG_ON(!list_empty(&cgrp->children));
1073                 BUG_ON(root->number_of_cgroups != 1);
1074
1075                 cgroup_populate_dir(cgrp);
1076                 mutex_unlock(&inode->i_mutex);
1077                 mutex_unlock(&cgroup_mutex);
1078         }
1079
1080         return simple_set_mnt(mnt, sb);
1081
1082  drop_new_super:
1083         up_write(&sb->s_umount);
1084         deactivate_super(sb);
1085         free_cg_links(&tmp_cg_links);
1086         return ret;
1087 }
1088
1089 static void cgroup_kill_sb(struct super_block *sb) {
1090         struct cgroupfs_root *root = sb->s_fs_info;
1091         struct cgroup *cgrp = &root->top_cgroup;
1092         int ret;
1093         struct cg_cgroup_link *link;
1094         struct cg_cgroup_link *saved_link;
1095
1096         BUG_ON(!root);
1097
1098         BUG_ON(root->number_of_cgroups != 1);
1099         BUG_ON(!list_empty(&cgrp->children));
1100         BUG_ON(!list_empty(&cgrp->sibling));
1101
1102         mutex_lock(&cgroup_mutex);
1103
1104         /* Rebind all subsystems back to the default hierarchy */
1105         ret = rebind_subsystems(root, 0);
1106         /* Shouldn't be able to fail ... */
1107         BUG_ON(ret);
1108
1109         /*
1110          * Release all the links from css_sets to this hierarchy's
1111          * root cgroup
1112          */
1113         write_lock(&css_set_lock);
1114
1115         list_for_each_entry_safe(link, saved_link, &cgrp->css_sets,
1116                                  cgrp_link_list) {
1117                 list_del(&link->cg_link_list);
1118                 list_del(&link->cgrp_link_list);
1119                 kfree(link);
1120         }
1121         write_unlock(&css_set_lock);
1122
1123         if (!list_empty(&root->root_list)) {
1124                 list_del(&root->root_list);
1125                 root_count--;
1126         }
1127         mutex_unlock(&cgroup_mutex);
1128
1129         kfree(root);
1130         kill_litter_super(sb);
1131 }
1132
1133 static struct file_system_type cgroup_fs_type = {
1134         .name = "cgroup",
1135         .get_sb = cgroup_get_sb,
1136         .kill_sb = cgroup_kill_sb,
1137 };
1138
1139 static inline struct cgroup *__d_cgrp(struct dentry *dentry)
1140 {
1141         return dentry->d_fsdata;
1142 }
1143
1144 static inline struct cftype *__d_cft(struct dentry *dentry)
1145 {
1146         return dentry->d_fsdata;
1147 }
1148
1149 /**
1150  * cgroup_path - generate the path of a cgroup
1151  * @cgrp: the cgroup in question
1152  * @buf: the buffer to write the path into
1153  * @buflen: the length of the buffer
1154  *
1155  * Called with cgroup_mutex held. Writes path of cgroup into buf.
1156  * Returns 0 on success, -errno on error.
1157  */
1158 int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen)
1159 {
1160         char *start;
1161
1162         if (cgrp == dummytop) {
1163                 /*
1164                  * Inactive subsystems have no dentry for their root
1165                  * cgroup
1166                  */
1167                 strcpy(buf, "/");
1168                 return 0;
1169         }
1170
1171         start = buf + buflen;
1172
1173         *--start = '\0';
1174         for (;;) {
1175                 int len = cgrp->dentry->d_name.len;
1176                 if ((start -= len) < buf)
1177                         return -ENAMETOOLONG;
1178                 memcpy(start, cgrp->dentry->d_name.name, len);
1179                 cgrp = cgrp->parent;
1180                 if (!cgrp)
1181                         break;
1182                 if (!cgrp->parent)
1183                         continue;
1184                 if (--start < buf)
1185                         return -ENAMETOOLONG;
1186                 *start = '/';
1187         }
1188         memmove(buf, start, buf + buflen - start);
1189         return 0;
1190 }
1191
1192 /*
1193  * Return the first subsystem attached to a cgroup's hierarchy, and
1194  * its subsystem id.
1195  */
1196
1197 static void get_first_subsys(const struct cgroup *cgrp,
1198                         struct cgroup_subsys_state **css, int *subsys_id)
1199 {
1200         const struct cgroupfs_root *root = cgrp->root;
1201         const struct cgroup_subsys *test_ss;
1202         BUG_ON(list_empty(&root->subsys_list));
1203         test_ss = list_entry(root->subsys_list.next,
1204                              struct cgroup_subsys, sibling);
1205         if (css) {
1206                 *css = cgrp->subsys[test_ss->subsys_id];
1207                 BUG_ON(!*css);
1208         }
1209         if (subsys_id)
1210                 *subsys_id = test_ss->subsys_id;
1211 }
1212
1213 /**
1214  * cgroup_attach_task - attach task 'tsk' to cgroup 'cgrp'
1215  * @cgrp: the cgroup the task is attaching to
1216  * @tsk: the task to be attached
1217  *
1218  * Call holding cgroup_mutex. May take task_lock of
1219  * the task 'tsk' during call.
1220  */
1221 int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
1222 {
1223         int retval = 0;
1224         struct cgroup_subsys *ss;
1225         struct cgroup *oldcgrp;
1226         struct css_set *cg = tsk->cgroups;
1227         struct css_set *newcg;
1228         struct cgroupfs_root *root = cgrp->root;
1229         int subsys_id;
1230
1231         get_first_subsys(cgrp, NULL, &subsys_id);
1232
1233         /* Nothing to do if the task is already in that cgroup */
1234         oldcgrp = task_cgroup(tsk, subsys_id);
1235         if (cgrp == oldcgrp)
1236                 return 0;
1237
1238         for_each_subsys(root, ss) {
1239                 if (ss->can_attach) {
1240                         retval = ss->can_attach(ss, cgrp, tsk);
1241                         if (retval)
1242                                 return retval;
1243                 }
1244         }
1245
1246         /*
1247          * Locate or allocate a new css_set for this task,
1248          * based on its final set of cgroups
1249          */
1250         newcg = find_css_set(cg, cgrp);
1251         if (!newcg)
1252                 return -ENOMEM;
1253
1254         task_lock(tsk);
1255         if (tsk->flags & PF_EXITING) {
1256                 task_unlock(tsk);
1257                 put_css_set(newcg);
1258                 return -ESRCH;
1259         }
1260         rcu_assign_pointer(tsk->cgroups, newcg);
1261         task_unlock(tsk);
1262
1263         /* Update the css_set linked lists if we're using them */
1264         write_lock(&css_set_lock);
1265         if (!list_empty(&tsk->cg_list)) {
1266                 list_del(&tsk->cg_list);
1267                 list_add(&tsk->cg_list, &newcg->tasks);
1268         }
1269         write_unlock(&css_set_lock);
1270
1271         for_each_subsys(root, ss) {
1272                 if (ss->attach)
1273                         ss->attach(ss, cgrp, oldcgrp, tsk);
1274         }
1275         set_bit(CGRP_RELEASABLE, &oldcgrp->flags);
1276         synchronize_rcu();
1277         put_css_set(cg);
1278         return 0;
1279 }
1280
1281 /*
1282  * Attach task with pid 'pid' to cgroup 'cgrp'. Call with
1283  * cgroup_mutex, may take task_lock of task
1284  */
1285 static int attach_task_by_pid(struct cgroup *cgrp, char *pidbuf)
1286 {
1287         pid_t pid;
1288         struct task_struct *tsk;
1289         int ret;
1290
1291         if (sscanf(pidbuf, "%d", &pid) != 1)
1292                 return -EIO;
1293
1294         if (pid) {
1295                 rcu_read_lock();
1296                 tsk = find_task_by_vpid(pid);
1297                 if (!tsk || tsk->flags & PF_EXITING) {
1298                         rcu_read_unlock();
1299                         return -ESRCH;
1300                 }
1301                 get_task_struct(tsk);
1302                 rcu_read_unlock();
1303
1304                 if ((current->euid) && (current->euid != tsk->uid)
1305                     && (current->euid != tsk->suid)) {
1306                         put_task_struct(tsk);
1307                         return -EACCES;
1308                 }
1309         } else {
1310                 tsk = current;
1311                 get_task_struct(tsk);
1312         }
1313
1314         ret = cgroup_attach_task(cgrp, tsk);
1315         put_task_struct(tsk);
1316         return ret;
1317 }
1318
1319 /* The various types of files and directories in a cgroup file system */
1320 enum cgroup_filetype {
1321         FILE_ROOT,
1322         FILE_DIR,
1323         FILE_TASKLIST,
1324         FILE_NOTIFY_ON_RELEASE,
1325         FILE_RELEASE_AGENT,
1326 };
1327
1328 /**
1329  * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive.
1330  * @cgrp: the cgroup to be checked for liveness
1331  *
1332  * On success, returns true; the lock should be later released with
1333  * cgroup_unlock(). On failure returns false with no lock held.
1334  */
1335 bool cgroup_lock_live_group(struct cgroup *cgrp)
1336 {
1337         mutex_lock(&cgroup_mutex);
1338         if (cgroup_is_removed(cgrp)) {
1339                 mutex_unlock(&cgroup_mutex);
1340                 return false;
1341         }
1342         return true;
1343 }
1344
1345 static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft,
1346                                       const char *buffer)
1347 {
1348         BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX);
1349         if (!cgroup_lock_live_group(cgrp))
1350                 return -ENODEV;
1351         strcpy(cgrp->root->release_agent_path, buffer);
1352         cgroup_unlock();
1353         return 0;
1354 }
1355
1356 static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft,
1357                                      struct seq_file *seq)
1358 {
1359         if (!cgroup_lock_live_group(cgrp))
1360                 return -ENODEV;
1361         seq_puts(seq, cgrp->root->release_agent_path);
1362         seq_putc(seq, '\n');
1363         cgroup_unlock();
1364         return 0;
1365 }
1366
1367 /* A buffer size big enough for numbers or short strings */
1368 #define CGROUP_LOCAL_BUFFER_SIZE 64
1369
1370 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft,
1371                                 struct file *file,
1372                                 const char __user *userbuf,
1373                                 size_t nbytes, loff_t *unused_ppos)
1374 {
1375         char buffer[CGROUP_LOCAL_BUFFER_SIZE];
1376         int retval = 0;
1377         char *end;
1378
1379         if (!nbytes)
1380                 return -EINVAL;
1381         if (nbytes >= sizeof(buffer))
1382                 return -E2BIG;
1383         if (copy_from_user(buffer, userbuf, nbytes))
1384                 return -EFAULT;
1385
1386         buffer[nbytes] = 0;     /* nul-terminate */
1387         strstrip(buffer);
1388         if (cft->write_u64) {
1389                 u64 val = simple_strtoull(buffer, &end, 0);
1390                 if (*end)
1391                         return -EINVAL;
1392                 retval = cft->write_u64(cgrp, cft, val);
1393         } else {
1394                 s64 val = simple_strtoll(buffer, &end, 0);
1395                 if (*end)
1396                         return -EINVAL;
1397                 retval = cft->write_s64(cgrp, cft, val);
1398         }
1399         if (!retval)
1400                 retval = nbytes;
1401         return retval;
1402 }
1403
1404 static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft,
1405                                    struct file *file,
1406                                    const char __user *userbuf,
1407                                    size_t nbytes, loff_t *unused_ppos)
1408 {
1409         char local_buffer[CGROUP_LOCAL_BUFFER_SIZE];
1410         int retval = 0;
1411         size_t max_bytes = cft->max_write_len;
1412         char *buffer = local_buffer;
1413
1414         if (!max_bytes)
1415                 max_bytes = sizeof(local_buffer) - 1;
1416         if (nbytes >= max_bytes)
1417                 return -E2BIG;
1418         /* Allocate a dynamic buffer if we need one */
1419         if (nbytes >= sizeof(local_buffer)) {
1420                 buffer = kmalloc(nbytes + 1, GFP_KERNEL);
1421                 if (buffer == NULL)
1422                         return -ENOMEM;
1423         }
1424         if (nbytes && copy_from_user(buffer, userbuf, nbytes))
1425                 return -EFAULT;
1426
1427         buffer[nbytes] = 0;     /* nul-terminate */
1428         strstrip(buffer);
1429         retval = cft->write_string(cgrp, cft, buffer);
1430         if (!retval)
1431                 retval = nbytes;
1432         if (buffer != local_buffer)
1433                 kfree(buffer);
1434         return retval;
1435 }
1436
1437 static ssize_t cgroup_common_file_write(struct cgroup *cgrp,
1438                                            struct cftype *cft,
1439                                            struct file *file,
1440                                            const char __user *userbuf,
1441                                            size_t nbytes, loff_t *unused_ppos)
1442 {
1443         enum cgroup_filetype type = cft->private;
1444         char *buffer;
1445         int retval = 0;
1446
1447         if (nbytes >= PATH_MAX)
1448                 return -E2BIG;
1449
1450         /* +1 for nul-terminator */
1451         buffer = kmalloc(nbytes + 1, GFP_KERNEL);
1452         if (buffer == NULL)
1453                 return -ENOMEM;
1454
1455         if (copy_from_user(buffer, userbuf, nbytes)) {
1456                 retval = -EFAULT;
1457                 goto out1;
1458         }
1459         buffer[nbytes] = 0;     /* nul-terminate */
1460         strstrip(buffer);       /* strip -just- trailing whitespace */
1461
1462         mutex_lock(&cgroup_mutex);
1463
1464         /*
1465          * This was already checked for in cgroup_file_write(), but
1466          * check again now we're holding cgroup_mutex.
1467          */
1468         if (cgroup_is_removed(cgrp)) {
1469                 retval = -ENODEV;
1470                 goto out2;
1471         }
1472
1473         switch (type) {
1474         case FILE_TASKLIST:
1475                 retval = attach_task_by_pid(cgrp, buffer);
1476                 break;
1477         case FILE_NOTIFY_ON_RELEASE:
1478                 clear_bit(CGRP_RELEASABLE, &cgrp->flags);
1479                 if (simple_strtoul(buffer, NULL, 10) != 0)
1480                         set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
1481                 else
1482                         clear_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
1483                 break;
1484         default:
1485                 retval = -EINVAL;
1486                 goto out2;
1487         }
1488
1489         if (retval == 0)
1490                 retval = nbytes;
1491 out2:
1492         mutex_unlock(&cgroup_mutex);
1493 out1:
1494         kfree(buffer);
1495         return retval;
1496 }
1497
1498 static ssize_t cgroup_file_write(struct file *file, const char __user *buf,
1499                                                 size_t nbytes, loff_t *ppos)
1500 {
1501         struct cftype *cft = __d_cft(file->f_dentry);
1502         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1503
1504         if (!cft || cgroup_is_removed(cgrp))
1505                 return -ENODEV;
1506         if (cft->write)
1507                 return cft->write(cgrp, cft, file, buf, nbytes, ppos);
1508         if (cft->write_u64 || cft->write_s64)
1509                 return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos);
1510         if (cft->write_string)
1511                 return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos);
1512         if (cft->trigger) {
1513                 int ret = cft->trigger(cgrp, (unsigned int)cft->private);
1514                 return ret ? ret : nbytes;
1515         }
1516         return -EINVAL;
1517 }
1518
1519 static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft,
1520                                struct file *file,
1521                                char __user *buf, size_t nbytes,
1522                                loff_t *ppos)
1523 {
1524         char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1525         u64 val = cft->read_u64(cgrp, cft);
1526         int len = sprintf(tmp, "%llu\n", (unsigned long long) val);
1527
1528         return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1529 }
1530
1531 static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft,
1532                                struct file *file,
1533                                char __user *buf, size_t nbytes,
1534                                loff_t *ppos)
1535 {
1536         char tmp[CGROUP_LOCAL_BUFFER_SIZE];
1537         s64 val = cft->read_s64(cgrp, cft);
1538         int len = sprintf(tmp, "%lld\n", (long long) val);
1539
1540         return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
1541 }
1542
1543 static ssize_t cgroup_file_read(struct file *file, char __user *buf,
1544                                    size_t nbytes, loff_t *ppos)
1545 {
1546         struct cftype *cft = __d_cft(file->f_dentry);
1547         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
1548
1549         if (!cft || cgroup_is_removed(cgrp))
1550                 return -ENODEV;
1551
1552         if (cft->read)
1553                 return cft->read(cgrp, cft, file, buf, nbytes, ppos);
1554         if (cft->read_u64)
1555                 return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos);
1556         if (cft->read_s64)
1557                 return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos);
1558         return -EINVAL;
1559 }
1560
1561 /*
1562  * seqfile ops/methods for returning structured data. Currently just
1563  * supports string->u64 maps, but can be extended in future.
1564  */
1565
1566 struct cgroup_seqfile_state {
1567         struct cftype *cft;
1568         struct cgroup *cgroup;
1569 };
1570
1571 static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value)
1572 {
1573         struct seq_file *sf = cb->state;
1574         return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value);
1575 }
1576
1577 static int cgroup_seqfile_show(struct seq_file *m, void *arg)
1578 {
1579         struct cgroup_seqfile_state *state = m->private;
1580         struct cftype *cft = state->cft;
1581         if (cft->read_map) {
1582                 struct cgroup_map_cb cb = {
1583                         .fill = cgroup_map_add,
1584                         .state = m,
1585                 };
1586                 return cft->read_map(state->cgroup, cft, &cb);
1587         }
1588         return cft->read_seq_string(state->cgroup, cft, m);
1589 }
1590
1591 int cgroup_seqfile_release(struct inode *inode, struct file *file)
1592 {
1593         struct seq_file *seq = file->private_data;
1594         kfree(seq->private);
1595         return single_release(inode, file);
1596 }
1597
1598 static struct file_operations cgroup_seqfile_operations = {
1599         .read = seq_read,
1600         .write = cgroup_file_write,
1601         .llseek = seq_lseek,
1602         .release = cgroup_seqfile_release,
1603 };
1604
1605 static int cgroup_file_open(struct inode *inode, struct file *file)
1606 {
1607         int err;
1608         struct cftype *cft;
1609
1610         err = generic_file_open(inode, file);
1611         if (err)
1612                 return err;
1613
1614         cft = __d_cft(file->f_dentry);
1615         if (!cft)
1616                 return -ENODEV;
1617         if (cft->read_map || cft->read_seq_string) {
1618                 struct cgroup_seqfile_state *state =
1619                         kzalloc(sizeof(*state), GFP_USER);
1620                 if (!state)
1621                         return -ENOMEM;
1622                 state->cft = cft;
1623                 state->cgroup = __d_cgrp(file->f_dentry->d_parent);
1624                 file->f_op = &cgroup_seqfile_operations;
1625                 err = single_open(file, cgroup_seqfile_show, state);
1626                 if (err < 0)
1627                         kfree(state);
1628         } else if (cft->open)
1629                 err = cft->open(inode, file);
1630         else
1631                 err = 0;
1632
1633         return err;
1634 }
1635
1636 static int cgroup_file_release(struct inode *inode, struct file *file)
1637 {
1638         struct cftype *cft = __d_cft(file->f_dentry);
1639         if (cft->release)
1640                 return cft->release(inode, file);
1641         return 0;
1642 }
1643
1644 /*
1645  * cgroup_rename - Only allow simple rename of directories in place.
1646  */
1647 static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry,
1648                             struct inode *new_dir, struct dentry *new_dentry)
1649 {
1650         if (!S_ISDIR(old_dentry->d_inode->i_mode))
1651                 return -ENOTDIR;
1652         if (new_dentry->d_inode)
1653                 return -EEXIST;
1654         if (old_dir != new_dir)
1655                 return -EIO;
1656         return simple_rename(old_dir, old_dentry, new_dir, new_dentry);
1657 }
1658
1659 static struct file_operations cgroup_file_operations = {
1660         .read = cgroup_file_read,
1661         .write = cgroup_file_write,
1662         .llseek = generic_file_llseek,
1663         .open = cgroup_file_open,
1664         .release = cgroup_file_release,
1665 };
1666
1667 static struct inode_operations cgroup_dir_inode_operations = {
1668         .lookup = simple_lookup,
1669         .mkdir = cgroup_mkdir,
1670         .rmdir = cgroup_rmdir,
1671         .rename = cgroup_rename,
1672 };
1673
1674 static int cgroup_create_file(struct dentry *dentry, int mode,
1675                                 struct super_block *sb)
1676 {
1677         static struct dentry_operations cgroup_dops = {
1678                 .d_iput = cgroup_diput,
1679         };
1680
1681         struct inode *inode;
1682
1683         if (!dentry)
1684                 return -ENOENT;
1685         if (dentry->d_inode)
1686                 return -EEXIST;
1687
1688         inode = cgroup_new_inode(mode, sb);
1689         if (!inode)
1690                 return -ENOMEM;
1691
1692         if (S_ISDIR(mode)) {
1693                 inode->i_op = &cgroup_dir_inode_operations;
1694                 inode->i_fop = &simple_dir_operations;
1695
1696                 /* start off with i_nlink == 2 (for "." entry) */
1697                 inc_nlink(inode);
1698
1699                 /* start with the directory inode held, so that we can
1700                  * populate it without racing with another mkdir */
1701                 mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD);
1702         } else if (S_ISREG(mode)) {
1703                 inode->i_size = 0;
1704                 inode->i_fop = &cgroup_file_operations;
1705         }
1706         dentry->d_op = &cgroup_dops;
1707         d_instantiate(dentry, inode);
1708         dget(dentry);   /* Extra count - pin the dentry in core */
1709         return 0;
1710 }
1711
1712 /*
1713  * cgroup_create_dir - create a directory for an object.
1714  * @cgrp: the cgroup we create the directory for. It must have a valid
1715  *        ->parent field. And we are going to fill its ->dentry field.
1716  * @dentry: dentry of the new cgroup
1717  * @mode: mode to set on new directory.
1718  */
1719 static int cgroup_create_dir(struct cgroup *cgrp, struct dentry *dentry,
1720                                 int mode)
1721 {
1722         struct dentry *parent;
1723         int error = 0;
1724
1725         parent = cgrp->parent->dentry;
1726         error = cgroup_create_file(dentry, S_IFDIR | mode, cgrp->root->sb);
1727         if (!error) {
1728                 dentry->d_fsdata = cgrp;
1729                 inc_nlink(parent->d_inode);
1730                 cgrp->dentry = dentry;
1731                 dget(dentry);
1732         }
1733         dput(dentry);
1734
1735         return error;
1736 }
1737
1738 int cgroup_add_file(struct cgroup *cgrp,
1739                        struct cgroup_subsys *subsys,
1740                        const struct cftype *cft)
1741 {
1742         struct dentry *dir = cgrp->dentry;
1743         struct dentry *dentry;
1744         int error;
1745
1746         char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 };
1747         if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) {
1748                 strcpy(name, subsys->name);
1749                 strcat(name, ".");
1750         }
1751         strcat(name, cft->name);
1752         BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex));
1753         dentry = lookup_one_len(name, dir, strlen(name));
1754         if (!IS_ERR(dentry)) {
1755                 error = cgroup_create_file(dentry, 0644 | S_IFREG,
1756                                                 cgrp->root->sb);
1757                 if (!error)
1758                         dentry->d_fsdata = (void *)cft;
1759                 dput(dentry);
1760         } else
1761                 error = PTR_ERR(dentry);
1762         return error;
1763 }
1764
1765 int cgroup_add_files(struct cgroup *cgrp,
1766                         struct cgroup_subsys *subsys,
1767                         const struct cftype cft[],
1768                         int count)
1769 {
1770         int i, err;
1771         for (i = 0; i < count; i++) {
1772                 err = cgroup_add_file(cgrp, subsys, &cft[i]);
1773                 if (err)
1774                         return err;
1775         }
1776         return 0;
1777 }
1778
1779 /**
1780  * cgroup_task_count - count the number of tasks in a cgroup.
1781  * @cgrp: the cgroup in question
1782  *
1783  * Return the number of tasks in the cgroup.
1784  */
1785 int cgroup_task_count(const struct cgroup *cgrp)
1786 {
1787         int count = 0;
1788         struct cg_cgroup_link *link;
1789
1790         read_lock(&css_set_lock);
1791         list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) {
1792                 count += atomic_read(&link->cg->ref.refcount);
1793         }
1794         read_unlock(&css_set_lock);
1795         return count;
1796 }
1797
1798 /*
1799  * Advance a list_head iterator.  The iterator should be positioned at
1800  * the start of a css_set
1801  */
1802 static void cgroup_advance_iter(struct cgroup *cgrp,
1803                                           struct cgroup_iter *it)
1804 {
1805         struct list_head *l = it->cg_link;
1806         struct cg_cgroup_link *link;
1807         struct css_set *cg;
1808
1809         /* Advance to the next non-empty css_set */
1810         do {
1811                 l = l->next;
1812                 if (l == &cgrp->css_sets) {
1813                         it->cg_link = NULL;
1814                         return;
1815                 }
1816                 link = list_entry(l, struct cg_cgroup_link, cgrp_link_list);
1817                 cg = link->cg;
1818         } while (list_empty(&cg->tasks));
1819         it->cg_link = l;
1820         it->task = cg->tasks.next;
1821 }
1822
1823 /*
1824  * To reduce the fork() overhead for systems that are not actually
1825  * using their cgroups capability, we don't maintain the lists running
1826  * through each css_set to its tasks until we see the list actually
1827  * used - in other words after the first call to cgroup_iter_start().
1828  *
1829  * The tasklist_lock is not held here, as do_each_thread() and
1830  * while_each_thread() are protected by RCU.
1831  */
1832 static void cgroup_enable_task_cg_lists(void)
1833 {
1834         struct task_struct *p, *g;
1835         write_lock(&css_set_lock);
1836         use_task_css_set_links = 1;
1837         do_each_thread(g, p) {
1838                 task_lock(p);
1839                 /*
1840                  * We should check if the process is exiting, otherwise
1841                  * it will race with cgroup_exit() in that the list
1842                  * entry won't be deleted though the process has exited.
1843                  */
1844                 if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list))
1845                         list_add(&p->cg_list, &p->cgroups->tasks);
1846                 task_unlock(p);
1847         } while_each_thread(g, p);
1848         write_unlock(&css_set_lock);
1849 }
1850
1851 void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it)
1852 {
1853         /*
1854          * The first time anyone tries to iterate across a cgroup,
1855          * we need to enable the list linking each css_set to its
1856          * tasks, and fix up all existing tasks.
1857          */
1858         if (!use_task_css_set_links)
1859                 cgroup_enable_task_cg_lists();
1860
1861         read_lock(&css_set_lock);
1862         it->cg_link = &cgrp->css_sets;
1863         cgroup_advance_iter(cgrp, it);
1864 }
1865
1866 struct task_struct *cgroup_iter_next(struct cgroup *cgrp,
1867                                         struct cgroup_iter *it)
1868 {
1869         struct task_struct *res;
1870         struct list_head *l = it->task;
1871
1872         /* If the iterator cg is NULL, we have no tasks */
1873         if (!it->cg_link)
1874                 return NULL;
1875         res = list_entry(l, struct task_struct, cg_list);
1876         /* Advance iterator to find next entry */
1877         l = l->next;
1878         if (l == &res->cgroups->tasks) {
1879                 /* We reached the end of this task list - move on to
1880                  * the next cg_cgroup_link */
1881                 cgroup_advance_iter(cgrp, it);
1882         } else {
1883                 it->task = l;
1884         }
1885         return res;
1886 }
1887
1888 void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it)
1889 {
1890         read_unlock(&css_set_lock);
1891 }
1892
1893 static inline int started_after_time(struct task_struct *t1,
1894                                      struct timespec *time,
1895                                      struct task_struct *t2)
1896 {
1897         int start_diff = timespec_compare(&t1->start_time, time);
1898         if (start_diff > 0) {
1899                 return 1;
1900         } else if (start_diff < 0) {
1901                 return 0;
1902         } else {
1903                 /*
1904                  * Arbitrarily, if two processes started at the same
1905                  * time, we'll say that the lower pointer value
1906                  * started first. Note that t2 may have exited by now
1907                  * so this may not be a valid pointer any longer, but
1908                  * that's fine - it still serves to distinguish
1909                  * between two tasks started (effectively) simultaneously.
1910                  */
1911                 return t1 > t2;
1912         }
1913 }
1914
1915 /*
1916  * This function is a callback from heap_insert() and is used to order
1917  * the heap.
1918  * In this case we order the heap in descending task start time.
1919  */
1920 static inline int started_after(void *p1, void *p2)
1921 {
1922         struct task_struct *t1 = p1;
1923         struct task_struct *t2 = p2;
1924         return started_after_time(t1, &t2->start_time, t2);
1925 }
1926
1927 /**
1928  * cgroup_scan_tasks - iterate though all the tasks in a cgroup
1929  * @scan: struct cgroup_scanner containing arguments for the scan
1930  *
1931  * Arguments include pointers to callback functions test_task() and
1932  * process_task().
1933  * Iterate through all the tasks in a cgroup, calling test_task() for each,
1934  * and if it returns true, call process_task() for it also.
1935  * The test_task pointer may be NULL, meaning always true (select all tasks).
1936  * Effectively duplicates cgroup_iter_{start,next,end}()
1937  * but does not lock css_set_lock for the call to process_task().
1938  * The struct cgroup_scanner may be embedded in any structure of the caller's
1939  * creation.
1940  * It is guaranteed that process_task() will act on every task that
1941  * is a member of the cgroup for the duration of this call. This
1942  * function may or may not call process_task() for tasks that exit
1943  * or move to a different cgroup during the call, or are forked or
1944  * move into the cgroup during the call.
1945  *
1946  * Note that test_task() may be called with locks held, and may in some
1947  * situations be called multiple times for the same task, so it should
1948  * be cheap.
1949  * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been
1950  * pre-allocated and will be used for heap operations (and its "gt" member will
1951  * be overwritten), else a temporary heap will be used (allocation of which
1952  * may cause this function to fail).
1953  */
1954 int cgroup_scan_tasks(struct cgroup_scanner *scan)
1955 {
1956         int retval, i;
1957         struct cgroup_iter it;
1958         struct task_struct *p, *dropped;
1959         /* Never dereference latest_task, since it's not refcounted */
1960         struct task_struct *latest_task = NULL;
1961         struct ptr_heap tmp_heap;
1962         struct ptr_heap *heap;
1963         struct timespec latest_time = { 0, 0 };
1964
1965         if (scan->heap) {
1966                 /* The caller supplied our heap and pre-allocated its memory */
1967                 heap = scan->heap;
1968                 heap->gt = &started_after;
1969         } else {
1970                 /* We need to allocate our own heap memory */
1971                 heap = &tmp_heap;
1972                 retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after);
1973                 if (retval)
1974                         /* cannot allocate the heap */
1975                         return retval;
1976         }
1977
1978  again:
1979         /*
1980          * Scan tasks in the cgroup, using the scanner's "test_task" callback
1981          * to determine which are of interest, and using the scanner's
1982          * "process_task" callback to process any of them that need an update.
1983          * Since we don't want to hold any locks during the task updates,
1984          * gather tasks to be processed in a heap structure.
1985          * The heap is sorted by descending task start time.
1986          * If the statically-sized heap fills up, we overflow tasks that
1987          * started later, and in future iterations only consider tasks that
1988          * started after the latest task in the previous pass. This
1989          * guarantees forward progress and that we don't miss any tasks.
1990          */
1991         heap->size = 0;
1992         cgroup_iter_start(scan->cg, &it);
1993         while ((p = cgroup_iter_next(scan->cg, &it))) {
1994                 /*
1995                  * Only affect tasks that qualify per the caller's callback,
1996                  * if he provided one
1997                  */
1998                 if (scan->test_task && !scan->test_task(p, scan))
1999                         continue;
2000                 /*
2001                  * Only process tasks that started after the last task
2002                  * we processed
2003                  */
2004                 if (!started_after_time(p, &latest_time, latest_task))
2005                         continue;
2006                 dropped = heap_insert(heap, p);
2007                 if (dropped == NULL) {
2008                         /*
2009                          * The new task was inserted; the heap wasn't
2010                          * previously full
2011                          */
2012                         get_task_struct(p);
2013                 } else if (dropped != p) {
2014                         /*
2015                          * The new task was inserted, and pushed out a
2016                          * different task
2017                          */
2018                         get_task_struct(p);
2019                         put_task_struct(dropped);
2020                 }
2021                 /*
2022                  * Else the new task was newer than anything already in
2023                  * the heap and wasn't inserted
2024                  */
2025         }
2026         cgroup_iter_end(scan->cg, &it);
2027
2028         if (heap->size) {
2029                 for (i = 0; i < heap->size; i++) {
2030                         struct task_struct *q = heap->ptrs[i];
2031                         if (i == 0) {
2032                                 latest_time = q->start_time;
2033                                 latest_task = q;
2034                         }
2035                         /* Process the task per the caller's callback */
2036                         scan->process_task(q, scan);
2037                         put_task_struct(q);
2038                 }
2039                 /*
2040                  * If we had to process any tasks at all, scan again
2041                  * in case some of them were in the middle of forking
2042                  * children that didn't get processed.
2043                  * Not the most efficient way to do it, but it avoids
2044                  * having to take callback_mutex in the fork path
2045                  */
2046                 goto again;
2047         }
2048         if (heap == &tmp_heap)
2049                 heap_free(&tmp_heap);
2050         return 0;
2051 }
2052
2053 /*
2054  * Stuff for reading the 'tasks' file.
2055  *
2056  * Reading this file can return large amounts of data if a cgroup has
2057  * *lots* of attached tasks. So it may need several calls to read(),
2058  * but we cannot guarantee that the information we produce is correct
2059  * unless we produce it entirely atomically.
2060  *
2061  * Upon tasks file open(), a struct ctr_struct is allocated, that
2062  * will have a pointer to an array (also allocated here).  The struct
2063  * ctr_struct * is stored in file->private_data.  Its resources will
2064  * be freed by release() when the file is closed.  The array is used
2065  * to sprintf the PIDs and then used by read().
2066  */
2067 struct ctr_struct {
2068         char *buf;
2069         int bufsz;
2070 };
2071
2072 /*
2073  * Load into 'pidarray' up to 'npids' of the tasks using cgroup
2074  * 'cgrp'.  Return actual number of pids loaded.  No need to
2075  * task_lock(p) when reading out p->cgroup, since we're in an RCU
2076  * read section, so the css_set can't go away, and is
2077  * immutable after creation.
2078  */
2079 static int pid_array_load(pid_t *pidarray, int npids, struct cgroup *cgrp)
2080 {
2081         int n = 0;
2082         struct cgroup_iter it;
2083         struct task_struct *tsk;
2084         cgroup_iter_start(cgrp, &it);
2085         while ((tsk = cgroup_iter_next(cgrp, &it))) {
2086                 if (unlikely(n == npids))
2087                         break;
2088                 pidarray[n++] = task_pid_vnr(tsk);
2089         }
2090         cgroup_iter_end(cgrp, &it);
2091         return n;
2092 }
2093
2094 /**
2095  * cgroupstats_build - build and fill cgroupstats
2096  * @stats: cgroupstats to fill information into
2097  * @dentry: A dentry entry belonging to the cgroup for which stats have
2098  * been requested.
2099  *
2100  * Build and fill cgroupstats so that taskstats can export it to user
2101  * space.
2102  */
2103 int cgroupstats_build(struct cgroupstats *stats, struct dentry *dentry)
2104 {
2105         int ret = -EINVAL;
2106         struct cgroup *cgrp;
2107         struct cgroup_iter it;
2108         struct task_struct *tsk;
2109         /*
2110          * Validate dentry by checking the superblock operations
2111          */
2112         if (dentry->d_sb->s_op != &cgroup_ops)
2113                  goto err;
2114
2115         ret = 0;
2116         cgrp = dentry->d_fsdata;
2117         rcu_read_lock();
2118
2119         cgroup_iter_start(cgrp, &it);
2120         while ((tsk = cgroup_iter_next(cgrp, &it))) {
2121                 switch (tsk->state) {
2122                 case TASK_RUNNING:
2123                         stats->nr_running++;
2124                         break;
2125                 case TASK_INTERRUPTIBLE:
2126                         stats->nr_sleeping++;
2127                         break;
2128                 case TASK_UNINTERRUPTIBLE:
2129                         stats->nr_uninterruptible++;
2130                         break;
2131                 case TASK_STOPPED:
2132                         stats->nr_stopped++;
2133                         break;
2134                 default:
2135                         if (delayacct_is_task_waiting_on_io(tsk))
2136                                 stats->nr_io_wait++;
2137                         break;
2138                 }
2139         }
2140         cgroup_iter_end(cgrp, &it);
2141
2142         rcu_read_unlock();
2143 err:
2144         return ret;
2145 }
2146
2147 static int cmppid(const void *a, const void *b)
2148 {
2149         return *(pid_t *)a - *(pid_t *)b;
2150 }
2151
2152 /*
2153  * Convert array 'a' of 'npids' pid_t's to a string of newline separated
2154  * decimal pids in 'buf'.  Don't write more than 'sz' chars, but return
2155  * count 'cnt' of how many chars would be written if buf were large enough.
2156  */
2157 static int pid_array_to_buf(char *buf, int sz, pid_t *a, int npids)
2158 {
2159         int cnt = 0;
2160         int i;
2161
2162         for (i = 0; i < npids; i++)
2163                 cnt += snprintf(buf + cnt, max(sz - cnt, 0), "%d\n", a[i]);
2164         return cnt;
2165 }
2166
2167 /*
2168  * Handle an open on 'tasks' file.  Prepare a buffer listing the
2169  * process id's of tasks currently attached to the cgroup being opened.
2170  *
2171  * Does not require any specific cgroup mutexes, and does not take any.
2172  */
2173 static int cgroup_tasks_open(struct inode *unused, struct file *file)
2174 {
2175         struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent);
2176         struct ctr_struct *ctr;
2177         pid_t *pidarray;
2178         int npids;
2179         char c;
2180
2181         if (!(file->f_mode & FMODE_READ))
2182                 return 0;
2183
2184         ctr = kmalloc(sizeof(*ctr), GFP_KERNEL);
2185         if (!ctr)
2186                 goto err0;
2187
2188         /*
2189          * If cgroup gets more users after we read count, we won't have
2190          * enough space - tough.  This race is indistinguishable to the
2191          * caller from the case that the additional cgroup users didn't
2192          * show up until sometime later on.
2193          */
2194         npids = cgroup_task_count(cgrp);
2195         if (npids) {
2196                 pidarray = kmalloc(npids * sizeof(pid_t), GFP_KERNEL);
2197                 if (!pidarray)
2198                         goto err1;
2199
2200                 npids = pid_array_load(pidarray, npids, cgrp);
2201                 sort(pidarray, npids, sizeof(pid_t), cmppid, NULL);
2202
2203                 /* Call pid_array_to_buf() twice, first just to get bufsz */
2204                 ctr->bufsz = pid_array_to_buf(&c, sizeof(c), pidarray, npids) + 1;
2205                 ctr->buf = kmalloc(ctr->bufsz, GFP_KERNEL);
2206                 if (!ctr->buf)
2207                         goto err2;
2208                 ctr->bufsz = pid_array_to_buf(ctr->buf, ctr->bufsz, pidarray, npids);
2209
2210                 kfree(pidarray);
2211         } else {
2212                 ctr->buf = NULL;
2213                 ctr->bufsz = 0;
2214         }
2215         file->private_data = ctr;
2216         return 0;
2217
2218 err2:
2219         kfree(pidarray);
2220 err1:
2221         kfree(ctr);
2222 err0:
2223         return -ENOMEM;
2224 }
2225
2226 static ssize_t cgroup_tasks_read(struct cgroup *cgrp,
2227                                     struct cftype *cft,
2228                                     struct file *file, char __user *buf,
2229                                     size_t nbytes, loff_t *ppos)
2230 {
2231         struct ctr_struct *ctr = file->private_data;
2232
2233         return simple_read_from_buffer(buf, nbytes, ppos, ctr->buf, ctr->bufsz);
2234 }
2235
2236 static int cgroup_tasks_release(struct inode *unused_inode,
2237                                         struct file *file)
2238 {
2239         struct ctr_struct *ctr;
2240
2241         if (file->f_mode & FMODE_READ) {
2242                 ctr = file->private_data;
2243                 kfree(ctr->buf);
2244                 kfree(ctr);
2245         }
2246         return 0;
2247 }
2248
2249 static u64 cgroup_read_notify_on_release(struct cgroup *cgrp,
2250                                             struct cftype *cft)
2251 {
2252         return notify_on_release(cgrp);
2253 }
2254
2255 /*
2256  * for the common functions, 'private' gives the type of file
2257  */
2258 static struct cftype files[] = {
2259         {
2260                 .name = "tasks",
2261                 .open = cgroup_tasks_open,
2262                 .read = cgroup_tasks_read,
2263                 .write = cgroup_common_file_write,
2264                 .release = cgroup_tasks_release,
2265                 .private = FILE_TASKLIST,
2266         },
2267
2268         {
2269                 .name = "notify_on_release",
2270                 .read_u64 = cgroup_read_notify_on_release,
2271                 .write = cgroup_common_file_write,
2272                 .private = FILE_NOTIFY_ON_RELEASE,
2273         },
2274 };
2275
2276 static struct cftype cft_release_agent = {
2277         .name = "release_agent",
2278         .read_seq_string = cgroup_release_agent_show,
2279         .write_string = cgroup_release_agent_write,
2280         .max_write_len = PATH_MAX,
2281         .private = FILE_RELEASE_AGENT,
2282 };
2283
2284 static int cgroup_populate_dir(struct cgroup *cgrp)
2285 {
2286         int err;
2287         struct cgroup_subsys *ss;
2288
2289         /* First clear out any existing files */
2290         cgroup_clear_directory(cgrp->dentry);
2291
2292         err = cgroup_add_files(cgrp, NULL, files, ARRAY_SIZE(files));
2293         if (err < 0)
2294                 return err;
2295
2296         if (cgrp == cgrp->top_cgroup) {
2297                 if ((err = cgroup_add_file(cgrp, NULL, &cft_release_agent)) < 0)
2298                         return err;
2299         }
2300
2301         for_each_subsys(cgrp->root, ss) {
2302                 if (ss->populate && (err = ss->populate(ss, cgrp)) < 0)
2303                         return err;
2304         }
2305
2306         return 0;
2307 }
2308
2309 static void init_cgroup_css(struct cgroup_subsys_state *css,
2310                                struct cgroup_subsys *ss,
2311                                struct cgroup *cgrp)
2312 {
2313         css->cgroup = cgrp;
2314         atomic_set(&css->refcnt, 0);
2315         css->flags = 0;
2316         if (cgrp == dummytop)
2317                 set_bit(CSS_ROOT, &css->flags);
2318         BUG_ON(cgrp->subsys[ss->subsys_id]);
2319         cgrp->subsys[ss->subsys_id] = css;
2320 }
2321
2322 /*
2323  * cgroup_create - create a cgroup
2324  * @parent: cgroup that will be parent of the new cgroup
2325  * @dentry: dentry of the new cgroup
2326  * @mode: mode to set on new inode
2327  *
2328  * Must be called with the mutex on the parent inode held
2329  */
2330 static long cgroup_create(struct cgroup *parent, struct dentry *dentry,
2331                              int mode)
2332 {
2333         struct cgroup *cgrp;
2334         struct cgroupfs_root *root = parent->root;
2335         int err = 0;
2336         struct cgroup_subsys *ss;
2337         struct super_block *sb = root->sb;
2338
2339         cgrp = kzalloc(sizeof(*cgrp), GFP_KERNEL);
2340         if (!cgrp)
2341                 return -ENOMEM;
2342
2343         /* Grab a reference on the superblock so the hierarchy doesn't
2344          * get deleted on unmount if there are child cgroups.  This
2345          * can be done outside cgroup_mutex, since the sb can't
2346          * disappear while someone has an open control file on the
2347          * fs */
2348         atomic_inc(&sb->s_active);
2349
2350         mutex_lock(&cgroup_mutex);
2351
2352         INIT_LIST_HEAD(&cgrp->sibling);
2353         INIT_LIST_HEAD(&cgrp->children);
2354         INIT_LIST_HEAD(&cgrp->css_sets);
2355         INIT_LIST_HEAD(&cgrp->release_list);
2356
2357         cgrp->parent = parent;
2358         cgrp->root = parent->root;
2359         cgrp->top_cgroup = parent->top_cgroup;
2360
2361         if (notify_on_release(parent))
2362                 set_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags);
2363
2364         for_each_subsys(root, ss) {
2365                 struct cgroup_subsys_state *css = ss->create(ss, cgrp);
2366                 if (IS_ERR(css)) {
2367                         err = PTR_ERR(css);
2368                         goto err_destroy;
2369                 }
2370                 init_cgroup_css(css, ss, cgrp);
2371         }
2372
2373         list_add(&cgrp->sibling, &cgrp->parent->children);
2374         root->number_of_cgroups++;
2375
2376         err = cgroup_create_dir(cgrp, dentry, mode);
2377         if (err < 0)
2378                 goto err_remove;
2379
2380         /* The cgroup directory was pre-locked for us */
2381         BUG_ON(!mutex_is_locked(&cgrp->dentry->d_inode->i_mutex));
2382
2383         err = cgroup_populate_dir(cgrp);
2384         /* If err < 0, we have a half-filled directory - oh well ;) */
2385
2386         mutex_unlock(&cgroup_mutex);
2387         mutex_unlock(&cgrp->dentry->d_inode->i_mutex);
2388
2389         return 0;
2390
2391  err_remove:
2392
2393         list_del(&cgrp->sibling);
2394         root->number_of_cgroups--;
2395
2396  err_destroy:
2397
2398         for_each_subsys(root, ss) {
2399                 if (cgrp->subsys[ss->subsys_id])
2400                         ss->destroy(ss, cgrp);
2401         }
2402
2403         mutex_unlock(&cgroup_mutex);
2404
2405         /* Release the reference count that we took on the superblock */
2406         deactivate_super(sb);
2407
2408         kfree(cgrp);
2409         return err;
2410 }
2411
2412 static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode)
2413 {
2414         struct cgroup *c_parent = dentry->d_parent->d_fsdata;
2415
2416         /* the vfs holds inode->i_mutex already */
2417         return cgroup_create(c_parent, dentry, mode | S_IFDIR);
2418 }
2419
2420 static inline int cgroup_has_css_refs(struct cgroup *cgrp)
2421 {
2422         /* Check the reference count on each subsystem. Since we
2423          * already established that there are no tasks in the
2424          * cgroup, if the css refcount is also 0, then there should
2425          * be no outstanding references, so the subsystem is safe to
2426          * destroy. We scan across all subsystems rather than using
2427          * the per-hierarchy linked list of mounted subsystems since
2428          * we can be called via check_for_release() with no
2429          * synchronization other than RCU, and the subsystem linked
2430          * list isn't RCU-safe */
2431         int i;
2432         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2433                 struct cgroup_subsys *ss = subsys[i];
2434                 struct cgroup_subsys_state *css;
2435                 /* Skip subsystems not in this hierarchy */
2436                 if (ss->root != cgrp->root)
2437                         continue;
2438                 css = cgrp->subsys[ss->subsys_id];
2439                 /* When called from check_for_release() it's possible
2440                  * that by this point the cgroup has been removed
2441                  * and the css deleted. But a false-positive doesn't
2442                  * matter, since it can only happen if the cgroup
2443                  * has been deleted and hence no longer needs the
2444                  * release agent to be called anyway. */
2445                 if (css && atomic_read(&css->refcnt))
2446                         return 1;
2447         }
2448         return 0;
2449 }
2450
2451 static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry)
2452 {
2453         struct cgroup *cgrp = dentry->d_fsdata;
2454         struct dentry *d;
2455         struct cgroup *parent;
2456         struct super_block *sb;
2457         struct cgroupfs_root *root;
2458
2459         /* the vfs holds both inode->i_mutex already */
2460
2461         mutex_lock(&cgroup_mutex);
2462         if (atomic_read(&cgrp->count) != 0) {
2463                 mutex_unlock(&cgroup_mutex);
2464                 return -EBUSY;
2465         }
2466         if (!list_empty(&cgrp->children)) {
2467                 mutex_unlock(&cgroup_mutex);
2468                 return -EBUSY;
2469         }
2470
2471         parent = cgrp->parent;
2472         root = cgrp->root;
2473         sb = root->sb;
2474
2475         /*
2476          * Call pre_destroy handlers of subsys. Notify subsystems
2477          * that rmdir() request comes.
2478          */
2479         cgroup_call_pre_destroy(cgrp);
2480
2481         if (cgroup_has_css_refs(cgrp)) {
2482                 mutex_unlock(&cgroup_mutex);
2483                 return -EBUSY;
2484         }
2485
2486         spin_lock(&release_list_lock);
2487         set_bit(CGRP_REMOVED, &cgrp->flags);
2488         if (!list_empty(&cgrp->release_list))
2489                 list_del(&cgrp->release_list);
2490         spin_unlock(&release_list_lock);
2491         /* delete my sibling from parent->children */
2492         list_del(&cgrp->sibling);
2493         spin_lock(&cgrp->dentry->d_lock);
2494         d = dget(cgrp->dentry);
2495         cgrp->dentry = NULL;
2496         spin_unlock(&d->d_lock);
2497
2498         cgroup_d_remove_dir(d);
2499         dput(d);
2500
2501         set_bit(CGRP_RELEASABLE, &parent->flags);
2502         check_for_release(parent);
2503
2504         mutex_unlock(&cgroup_mutex);
2505         return 0;
2506 }
2507
2508 static void __init cgroup_init_subsys(struct cgroup_subsys *ss)
2509 {
2510         struct cgroup_subsys_state *css;
2511
2512         printk(KERN_INFO "Initializing cgroup subsys %s\n", ss->name);
2513
2514         /* Create the top cgroup state for this subsystem */
2515         ss->root = &rootnode;
2516         css = ss->create(ss, dummytop);
2517         /* We don't handle early failures gracefully */
2518         BUG_ON(IS_ERR(css));
2519         init_cgroup_css(css, ss, dummytop);
2520
2521         /* Update the init_css_set to contain a subsys
2522          * pointer to this state - since the subsystem is
2523          * newly registered, all tasks and hence the
2524          * init_css_set is in the subsystem's top cgroup. */
2525         init_css_set.subsys[ss->subsys_id] = dummytop->subsys[ss->subsys_id];
2526
2527         need_forkexit_callback |= ss->fork || ss->exit;
2528         need_mm_owner_callback |= !!ss->mm_owner_changed;
2529
2530         /* At system boot, before all subsystems have been
2531          * registered, no tasks have been forked, so we don't
2532          * need to invoke fork callbacks here. */
2533         BUG_ON(!list_empty(&init_task.tasks));
2534
2535         ss->active = 1;
2536 }
2537
2538 /**
2539  * cgroup_init_early - cgroup initialization at system boot
2540  *
2541  * Initialize cgroups at system boot, and initialize any
2542  * subsystems that request early init.
2543  */
2544 int __init cgroup_init_early(void)
2545 {
2546         int i;
2547         kref_init(&init_css_set.ref);
2548         kref_get(&init_css_set.ref);
2549         INIT_LIST_HEAD(&init_css_set.cg_links);
2550         INIT_LIST_HEAD(&init_css_set.tasks);
2551         INIT_HLIST_NODE(&init_css_set.hlist);
2552         css_set_count = 1;
2553         init_cgroup_root(&rootnode);
2554         list_add(&rootnode.root_list, &roots);
2555         root_count = 1;
2556         init_task.cgroups = &init_css_set;
2557
2558         init_css_set_link.cg = &init_css_set;
2559         list_add(&init_css_set_link.cgrp_link_list,
2560                  &rootnode.top_cgroup.css_sets);
2561         list_add(&init_css_set_link.cg_link_list,
2562                  &init_css_set.cg_links);
2563
2564         for (i = 0; i < CSS_SET_TABLE_SIZE; i++)
2565                 INIT_HLIST_HEAD(&css_set_table[i]);
2566
2567         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2568                 struct cgroup_subsys *ss = subsys[i];
2569
2570                 BUG_ON(!ss->name);
2571                 BUG_ON(strlen(ss->name) > MAX_CGROUP_TYPE_NAMELEN);
2572                 BUG_ON(!ss->create);
2573                 BUG_ON(!ss->destroy);
2574                 if (ss->subsys_id != i) {
2575                         printk(KERN_ERR "cgroup: Subsys %s id == %d\n",
2576                                ss->name, ss->subsys_id);
2577                         BUG();
2578                 }
2579
2580                 if (ss->early_init)
2581                         cgroup_init_subsys(ss);
2582         }
2583         return 0;
2584 }
2585
2586 /**
2587  * cgroup_init - cgroup initialization
2588  *
2589  * Register cgroup filesystem and /proc file, and initialize
2590  * any subsystems that didn't request early init.
2591  */
2592 int __init cgroup_init(void)
2593 {
2594         int err;
2595         int i;
2596         struct hlist_head *hhead;
2597
2598         err = bdi_init(&cgroup_backing_dev_info);
2599         if (err)
2600                 return err;
2601
2602         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2603                 struct cgroup_subsys *ss = subsys[i];
2604                 if (!ss->early_init)
2605                         cgroup_init_subsys(ss);
2606         }
2607
2608         /* Add init_css_set to the hash table */
2609         hhead = css_set_hash(init_css_set.subsys);
2610         hlist_add_head(&init_css_set.hlist, hhead);
2611
2612         err = register_filesystem(&cgroup_fs_type);
2613         if (err < 0)
2614                 goto out;
2615
2616         proc_create("cgroups", 0, NULL, &proc_cgroupstats_operations);
2617
2618 out:
2619         if (err)
2620                 bdi_destroy(&cgroup_backing_dev_info);
2621
2622         return err;
2623 }
2624
2625 /*
2626  * proc_cgroup_show()
2627  *  - Print task's cgroup paths into seq_file, one line for each hierarchy
2628  *  - Used for /proc/<pid>/cgroup.
2629  *  - No need to task_lock(tsk) on this tsk->cgroup reference, as it
2630  *    doesn't really matter if tsk->cgroup changes after we read it,
2631  *    and we take cgroup_mutex, keeping cgroup_attach_task() from changing it
2632  *    anyway.  No need to check that tsk->cgroup != NULL, thanks to
2633  *    the_top_cgroup_hack in cgroup_exit(), which sets an exiting tasks
2634  *    cgroup to top_cgroup.
2635  */
2636
2637 /* TODO: Use a proper seq_file iterator */
2638 static int proc_cgroup_show(struct seq_file *m, void *v)
2639 {
2640         struct pid *pid;
2641         struct task_struct *tsk;
2642         char *buf;
2643         int retval;
2644         struct cgroupfs_root *root;
2645
2646         retval = -ENOMEM;
2647         buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
2648         if (!buf)
2649                 goto out;
2650
2651         retval = -ESRCH;
2652         pid = m->private;
2653         tsk = get_pid_task(pid, PIDTYPE_PID);
2654         if (!tsk)
2655                 goto out_free;
2656
2657         retval = 0;
2658
2659         mutex_lock(&cgroup_mutex);
2660
2661         for_each_root(root) {
2662                 struct cgroup_subsys *ss;
2663                 struct cgroup *cgrp;
2664                 int subsys_id;
2665                 int count = 0;
2666
2667                 /* Skip this hierarchy if it has no active subsystems */
2668                 if (!root->actual_subsys_bits)
2669                         continue;
2670                 seq_printf(m, "%lu:", root->subsys_bits);
2671                 for_each_subsys(root, ss)
2672                         seq_printf(m, "%s%s", count++ ? "," : "", ss->name);
2673                 seq_putc(m, ':');
2674                 get_first_subsys(&root->top_cgroup, NULL, &subsys_id);
2675                 cgrp = task_cgroup(tsk, subsys_id);
2676                 retval = cgroup_path(cgrp, buf, PAGE_SIZE);
2677                 if (retval < 0)
2678                         goto out_unlock;
2679                 seq_puts(m, buf);
2680                 seq_putc(m, '\n');
2681         }
2682
2683 out_unlock:
2684         mutex_unlock(&cgroup_mutex);
2685         put_task_struct(tsk);
2686 out_free:
2687         kfree(buf);
2688 out:
2689         return retval;
2690 }
2691
2692 static int cgroup_open(struct inode *inode, struct file *file)
2693 {
2694         struct pid *pid = PROC_I(inode)->pid;
2695         return single_open(file, proc_cgroup_show, pid);
2696 }
2697
2698 struct file_operations proc_cgroup_operations = {
2699         .open           = cgroup_open,
2700         .read           = seq_read,
2701         .llseek         = seq_lseek,
2702         .release        = single_release,
2703 };
2704
2705 /* Display information about each subsystem and each hierarchy */
2706 static int proc_cgroupstats_show(struct seq_file *m, void *v)
2707 {
2708         int i;
2709
2710         seq_puts(m, "#subsys_name\thierarchy\tnum_cgroups\tenabled\n");
2711         mutex_lock(&cgroup_mutex);
2712         for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2713                 struct cgroup_subsys *ss = subsys[i];
2714                 seq_printf(m, "%s\t%lu\t%d\t%d\n",
2715                            ss->name, ss->root->subsys_bits,
2716                            ss->root->number_of_cgroups, !ss->disabled);
2717         }
2718         mutex_unlock(&cgroup_mutex);
2719         return 0;
2720 }
2721
2722 static int cgroupstats_open(struct inode *inode, struct file *file)
2723 {
2724         return single_open(file, proc_cgroupstats_show, NULL);
2725 }
2726
2727 static struct file_operations proc_cgroupstats_operations = {
2728         .open = cgroupstats_open,
2729         .read = seq_read,
2730         .llseek = seq_lseek,
2731         .release = single_release,
2732 };
2733
2734 /**
2735  * cgroup_fork - attach newly forked task to its parents cgroup.
2736  * @child: pointer to task_struct of forking parent process.
2737  *
2738  * Description: A task inherits its parent's cgroup at fork().
2739  *
2740  * A pointer to the shared css_set was automatically copied in
2741  * fork.c by dup_task_struct().  However, we ignore that copy, since
2742  * it was not made under the protection of RCU or cgroup_mutex, so
2743  * might no longer be a valid cgroup pointer.  cgroup_attach_task() might
2744  * have already changed current->cgroups, allowing the previously
2745  * referenced cgroup group to be removed and freed.
2746  *
2747  * At the point that cgroup_fork() is called, 'current' is the parent
2748  * task, and the passed argument 'child' points to the child task.
2749  */
2750 void cgroup_fork(struct task_struct *child)
2751 {
2752         task_lock(current);
2753         child->cgroups = current->cgroups;
2754         get_css_set(child->cgroups);
2755         task_unlock(current);
2756         INIT_LIST_HEAD(&child->cg_list);
2757 }
2758
2759 /**
2760  * cgroup_fork_callbacks - run fork callbacks
2761  * @child: the new task
2762  *
2763  * Called on a new task very soon before adding it to the
2764  * tasklist. No need to take any locks since no-one can
2765  * be operating on this task.
2766  */
2767 void cgroup_fork_callbacks(struct task_struct *child)
2768 {
2769         if (need_forkexit_callback) {
2770                 int i;
2771                 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2772                         struct cgroup_subsys *ss = subsys[i];
2773                         if (ss->fork)
2774                                 ss->fork(ss, child);
2775                 }
2776         }
2777 }
2778
2779 #ifdef CONFIG_MM_OWNER
2780 /**
2781  * cgroup_mm_owner_callbacks - run callbacks when the mm->owner changes
2782  * @p: the new owner
2783  *
2784  * Called on every change to mm->owner. mm_init_owner() does not
2785  * invoke this routine, since it assigns the mm->owner the first time
2786  * and does not change it.
2787  */
2788 void cgroup_mm_owner_callbacks(struct task_struct *old, struct task_struct *new)
2789 {
2790         struct cgroup *oldcgrp, *newcgrp;
2791
2792         if (need_mm_owner_callback) {
2793                 int i;
2794                 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2795                         struct cgroup_subsys *ss = subsys[i];
2796                         oldcgrp = task_cgroup(old, ss->subsys_id);
2797                         newcgrp = task_cgroup(new, ss->subsys_id);
2798                         if (oldcgrp == newcgrp)
2799                                 continue;
2800                         if (ss->mm_owner_changed)
2801                                 ss->mm_owner_changed(ss, oldcgrp, newcgrp);
2802                 }
2803         }
2804 }
2805 #endif /* CONFIG_MM_OWNER */
2806
2807 /**
2808  * cgroup_post_fork - called on a new task after adding it to the task list
2809  * @child: the task in question
2810  *
2811  * Adds the task to the list running through its css_set if necessary.
2812  * Has to be after the task is visible on the task list in case we race
2813  * with the first call to cgroup_iter_start() - to guarantee that the
2814  * new task ends up on its list.
2815  */
2816 void cgroup_post_fork(struct task_struct *child)
2817 {
2818         if (use_task_css_set_links) {
2819                 write_lock(&css_set_lock);
2820                 if (list_empty(&child->cg_list))
2821                         list_add(&child->cg_list, &child->cgroups->tasks);
2822                 write_unlock(&css_set_lock);
2823         }
2824 }
2825 /**
2826  * cgroup_exit - detach cgroup from exiting task
2827  * @tsk: pointer to task_struct of exiting process
2828  * @run_callback: run exit callbacks?
2829  *
2830  * Description: Detach cgroup from @tsk and release it.
2831  *
2832  * Note that cgroups marked notify_on_release force every task in
2833  * them to take the global cgroup_mutex mutex when exiting.
2834  * This could impact scaling on very large systems.  Be reluctant to
2835  * use notify_on_release cgroups where very high task exit scaling
2836  * is required on large systems.
2837  *
2838  * the_top_cgroup_hack:
2839  *
2840  *    Set the exiting tasks cgroup to the root cgroup (top_cgroup).
2841  *
2842  *    We call cgroup_exit() while the task is still competent to
2843  *    handle notify_on_release(), then leave the task attached to the
2844  *    root cgroup in each hierarchy for the remainder of its exit.
2845  *
2846  *    To do this properly, we would increment the reference count on
2847  *    top_cgroup, and near the very end of the kernel/exit.c do_exit()
2848  *    code we would add a second cgroup function call, to drop that
2849  *    reference.  This would just create an unnecessary hot spot on
2850  *    the top_cgroup reference count, to no avail.
2851  *
2852  *    Normally, holding a reference to a cgroup without bumping its
2853  *    count is unsafe.   The cgroup could go away, or someone could
2854  *    attach us to a different cgroup, decrementing the count on
2855  *    the first cgroup that we never incremented.  But in this case,
2856  *    top_cgroup isn't going away, and either task has PF_EXITING set,
2857  *    which wards off any cgroup_attach_task() attempts, or task is a failed
2858  *    fork, never visible to cgroup_attach_task.
2859  */
2860 void cgroup_exit(struct task_struct *tsk, int run_callbacks)
2861 {
2862         int i;
2863         struct css_set *cg;
2864
2865         if (run_callbacks && need_forkexit_callback) {
2866                 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
2867                         struct cgroup_subsys *ss = subsys[i];
2868                         if (ss->exit)
2869                                 ss->exit(ss, tsk);
2870                 }
2871         }
2872
2873         /*
2874          * Unlink from the css_set task list if necessary.
2875          * Optimistically check cg_list before taking
2876          * css_set_lock
2877          */
2878         if (!list_empty(&tsk->cg_list)) {
2879                 write_lock(&css_set_lock);
2880                 if (!list_empty(&tsk->cg_list))
2881                         list_del(&tsk->cg_list);
2882                 write_unlock(&css_set_lock);
2883         }
2884
2885         /* Reassign the task to the init_css_set. */
2886         task_lock(tsk);
2887         cg = tsk->cgroups;
2888         tsk->cgroups = &init_css_set;
2889         task_unlock(tsk);
2890         if (cg)
2891                 put_css_set_taskexit(cg);
2892 }
2893
2894 /**
2895  * cgroup_clone - clone the cgroup the given subsystem is attached to
2896  * @tsk: the task to be moved
2897  * @subsys: the given subsystem
2898  *
2899  * Duplicate the current cgroup in the hierarchy that the given
2900  * subsystem is attached to, and move this task into the new
2901  * child.
2902  */
2903 int cgroup_clone(struct task_struct *tsk, struct cgroup_subsys *subsys)
2904 {
2905         struct dentry *dentry;
2906         int ret = 0;
2907         char nodename[MAX_CGROUP_TYPE_NAMELEN];
2908         struct cgroup *parent, *child;
2909         struct inode *inode;
2910         struct css_set *cg;
2911         struct cgroupfs_root *root;
2912         struct cgroup_subsys *ss;
2913
2914         /* We shouldn't be called by an unregistered subsystem */
2915         BUG_ON(!subsys->active);
2916
2917         /* First figure out what hierarchy and cgroup we're dealing
2918          * with, and pin them so we can drop cgroup_mutex */
2919         mutex_lock(&cgroup_mutex);
2920  again:
2921         root = subsys->root;
2922         if (root == &rootnode) {
2923                 printk(KERN_INFO
2924                        "Not cloning cgroup for unused subsystem %s\n",
2925                        subsys->name);
2926                 mutex_unlock(&cgroup_mutex);
2927                 return 0;
2928         }
2929         cg = tsk->cgroups;
2930         parent = task_cgroup(tsk, subsys->subsys_id);
2931
2932         snprintf(nodename, MAX_CGROUP_TYPE_NAMELEN, "%d", tsk->pid);
2933
2934         /* Pin the hierarchy */
2935         atomic_inc(&parent->root->sb->s_active);
2936
2937         /* Keep the cgroup alive */
2938         get_css_set(cg);
2939         mutex_unlock(&cgroup_mutex);
2940
2941         /* Now do the VFS work to create a cgroup */
2942         inode = parent->dentry->d_inode;
2943
2944         /* Hold the parent directory mutex across this operation to
2945          * stop anyone else deleting the new cgroup */
2946         mutex_lock(&inode->i_mutex);
2947         dentry = lookup_one_len(nodename, parent->dentry, strlen(nodename));
2948         if (IS_ERR(dentry)) {
2949                 printk(KERN_INFO
2950                        "cgroup: Couldn't allocate dentry for %s: %ld\n", nodename,
2951                        PTR_ERR(dentry));
2952                 ret = PTR_ERR(dentry);
2953                 goto out_release;
2954         }
2955
2956         /* Create the cgroup directory, which also creates the cgroup */
2957         ret = vfs_mkdir(inode, dentry, S_IFDIR | 0755);
2958         child = __d_cgrp(dentry);
2959         dput(dentry);
2960         if (ret) {
2961                 printk(KERN_INFO
2962                        "Failed to create cgroup %s: %d\n", nodename,
2963                        ret);
2964                 goto out_release;
2965         }
2966
2967         if (!child) {
2968                 printk(KERN_INFO
2969                        "Couldn't find new cgroup %s\n", nodename);
2970                 ret = -ENOMEM;
2971                 goto out_release;
2972         }
2973
2974         /* The cgroup now exists. Retake cgroup_mutex and check
2975          * that we're still in the same state that we thought we
2976          * were. */
2977         mutex_lock(&cgroup_mutex);
2978         if ((root != subsys->root) ||
2979             (parent != task_cgroup(tsk, subsys->subsys_id))) {
2980                 /* Aargh, we raced ... */
2981                 mutex_unlock(&inode->i_mutex);
2982                 put_css_set(cg);
2983
2984                 deactivate_super(parent->root->sb);
2985                 /* The cgroup is still accessible in the VFS, but
2986                  * we're not going to try to rmdir() it at this
2987                  * point. */
2988                 printk(KERN_INFO
2989                        "Race in cgroup_clone() - leaking cgroup %s\n",
2990                        nodename);
2991                 goto again;
2992         }
2993
2994         /* do any required auto-setup */
2995         for_each_subsys(root, ss) {
2996                 if (ss->post_clone)
2997                         ss->post_clone(ss, child);
2998         }
2999
3000         /* All seems fine. Finish by moving the task into the new cgroup */
3001         ret = cgroup_attach_task(child, tsk);
3002         mutex_unlock(&cgroup_mutex);
3003
3004  out_release:
3005         mutex_unlock(&inode->i_mutex);
3006
3007         mutex_lock(&cgroup_mutex);
3008         put_css_set(cg);
3009         mutex_unlock(&cgroup_mutex);
3010         deactivate_super(parent->root->sb);
3011         return ret;
3012 }
3013
3014 /**
3015  * cgroup_is_descendant - see if @cgrp is a descendant of current task's cgrp
3016  * @cgrp: the cgroup in question
3017  *
3018  * See if @cgrp is a descendant of the current task's cgroup in
3019  * the appropriate hierarchy.
3020  *
3021  * If we are sending in dummytop, then presumably we are creating
3022  * the top cgroup in the subsystem.
3023  *
3024  * Called only by the ns (nsproxy) cgroup.
3025  */
3026 int cgroup_is_descendant(const struct cgroup *cgrp)
3027 {
3028         int ret;
3029         struct cgroup *target;
3030         int subsys_id;
3031
3032         if (cgrp == dummytop)
3033                 return 1;
3034
3035         get_first_subsys(cgrp, NULL, &subsys_id);
3036         target = task_cgroup(current, subsys_id);
3037         while (cgrp != target && cgrp!= cgrp->top_cgroup)
3038                 cgrp = cgrp->parent;
3039         ret = (cgrp == target);
3040         return ret;
3041 }
3042
3043 static void check_for_release(struct cgroup *cgrp)
3044 {
3045         /* All of these checks rely on RCU to keep the cgroup
3046          * structure alive */
3047         if (cgroup_is_releasable(cgrp) && !atomic_read(&cgrp->count)
3048             && list_empty(&cgrp->children) && !cgroup_has_css_refs(cgrp)) {
3049                 /* Control Group is currently removeable. If it's not
3050                  * already queued for a userspace notification, queue
3051                  * it now */
3052                 int need_schedule_work = 0;
3053                 spin_lock(&release_list_lock);
3054                 if (!cgroup_is_removed(cgrp) &&
3055                     list_empty(&cgrp->release_list)) {
3056                         list_add(&cgrp->release_list, &release_list);
3057                         need_schedule_work = 1;
3058                 }
3059                 spin_unlock(&release_list_lock);
3060                 if (need_schedule_work)
3061                         schedule_work(&release_agent_work);
3062         }
3063 }
3064
3065 void __css_put(struct cgroup_subsys_state *css)
3066 {
3067         struct cgroup *cgrp = css->cgroup;
3068         rcu_read_lock();
3069         if (atomic_dec_and_test(&css->refcnt) && notify_on_release(cgrp)) {
3070                 set_bit(CGRP_RELEASABLE, &cgrp->flags);
3071                 check_for_release(cgrp);
3072         }
3073         rcu_read_unlock();
3074 }
3075
3076 /*
3077  * Notify userspace when a cgroup is released, by running the
3078  * configured release agent with the name of the cgroup (path
3079  * relative to the root of cgroup file system) as the argument.
3080  *
3081  * Most likely, this user command will try to rmdir this cgroup.
3082  *
3083  * This races with the possibility that some other task will be
3084  * attached to this cgroup before it is removed, or that some other
3085  * user task will 'mkdir' a child cgroup of this cgroup.  That's ok.
3086  * The presumed 'rmdir' will fail quietly if this cgroup is no longer
3087  * unused, and this cgroup will be reprieved from its death sentence,
3088  * to continue to serve a useful existence.  Next time it's released,
3089  * we will get notified again, if it still has 'notify_on_release' set.
3090  *
3091  * The final arg to call_usermodehelper() is UMH_WAIT_EXEC, which
3092  * means only wait until the task is successfully execve()'d.  The
3093  * separate release agent task is forked by call_usermodehelper(),
3094  * then control in this thread returns here, without waiting for the
3095  * release agent task.  We don't bother to wait because the caller of
3096  * this routine has no use for the exit status of the release agent
3097  * task, so no sense holding our caller up for that.
3098  */
3099 static void cgroup_release_agent(struct work_struct *work)
3100 {
3101         BUG_ON(work != &release_agent_work);
3102         mutex_lock(&cgroup_mutex);
3103         spin_lock(&release_list_lock);
3104         while (!list_empty(&release_list)) {
3105                 char *argv[3], *envp[3];
3106                 int i;
3107                 char *pathbuf = NULL, *agentbuf = NULL;
3108                 struct cgroup *cgrp = list_entry(release_list.next,
3109                                                     struct cgroup,
3110                                                     release_list);
3111                 list_del_init(&cgrp->release_list);
3112                 spin_unlock(&release_list_lock);
3113                 pathbuf = kmalloc(PAGE_SIZE, GFP_KERNEL);
3114                 if (!pathbuf)
3115                         goto continue_free;
3116                 if (cgroup_path(cgrp, pathbuf, PAGE_SIZE) < 0)
3117                         goto continue_free;
3118                 agentbuf = kstrdup(cgrp->root->release_agent_path, GFP_KERNEL);
3119                 if (!agentbuf)
3120                         goto continue_free;
3121
3122                 i = 0;
3123                 argv[i++] = agentbuf;
3124                 argv[i++] = pathbuf;
3125                 argv[i] = NULL;
3126
3127                 i = 0;
3128                 /* minimal command environment */
3129                 envp[i++] = "HOME=/";
3130                 envp[i++] = "PATH=/sbin:/bin:/usr/sbin:/usr/bin";
3131                 envp[i] = NULL;
3132
3133                 /* Drop the lock while we invoke the usermode helper,
3134                  * since the exec could involve hitting disk and hence
3135                  * be a slow process */
3136                 mutex_unlock(&cgroup_mutex);
3137                 call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
3138                 mutex_lock(&cgroup_mutex);
3139  continue_free:
3140                 kfree(pathbuf);
3141                 kfree(agentbuf);
3142                 spin_lock(&release_list_lock);
3143         }
3144         spin_unlock(&release_list_lock);
3145         mutex_unlock(&cgroup_mutex);
3146 }
3147
3148 static int __init cgroup_disable(char *str)
3149 {
3150         int i;
3151         char *token;
3152
3153         while ((token = strsep(&str, ",")) != NULL) {
3154                 if (!*token)
3155                         continue;
3156
3157                 for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) {
3158                         struct cgroup_subsys *ss = subsys[i];
3159
3160                         if (!strcmp(token, ss->name)) {
3161                                 ss->disabled = 1;
3162                                 printk(KERN_INFO "Disabling %s control group"
3163                                         " subsystem\n", ss->name);
3164                                 break;
3165                         }
3166                 }
3167         }
3168         return 1;
3169 }
3170 __setup("cgroup_disable=", cgroup_disable);