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