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