/* * Generic process-grouping system. * * Based originally on the cpuset system, extracted by Paul Menage * Copyright (C) 2006 Google, Inc * * Copyright notices from the original cpuset code: * -------------------------------------------------- * Copyright (C) 2003 BULL SA. * Copyright (C) 2004-2006 Silicon Graphics, Inc. * * Portions derived from Patrick Mochel's sysfs code. * sysfs is Copyright (c) 2001-3 Patrick Mochel * * 2003-10-10 Written by Simon Derr. * 2003-10-22 Updates by Stephen Hemminger. * 2004 May-July Rework by Paul Jackson. * --------------------------------------------------- * * This file is subject to the terms and conditions of the GNU General Public * License. See the file COPYING in the main directory of the Linux * distribution for more details. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static DEFINE_MUTEX(cgroup_mutex); /* Generate an array of cgroup subsystem pointers */ #define SUBSYS(_x) &_x ## _subsys, static struct cgroup_subsys *subsys[] = { #include }; /* * A cgroupfs_root represents the root of a cgroup hierarchy, * and may be associated with a superblock to form an active * hierarchy */ struct cgroupfs_root { struct super_block *sb; /* * The bitmask of subsystems intended to be attached to this * hierarchy */ unsigned long subsys_bits; /* The bitmask of subsystems currently attached to this hierarchy */ unsigned long actual_subsys_bits; /* A list running through the attached subsystems */ struct list_head subsys_list; /* The root cgroup for this hierarchy */ struct cgroup top_cgroup; /* Tracks how many cgroups are currently defined in hierarchy.*/ int number_of_cgroups; /* A list running through the active hierarchies */ struct list_head root_list; /* Hierarchy-specific flags */ unsigned long flags; /* The path to use for release notifications. */ char release_agent_path[PATH_MAX]; }; /* * The "rootnode" hierarchy is the "dummy hierarchy", reserved for the * subsystems that are otherwise unattached - it never has more than a * single cgroup, and all tasks are part of that cgroup. */ static struct cgroupfs_root rootnode; /* * CSS ID -- ID per subsys's Cgroup Subsys State(CSS). used only when * cgroup_subsys->use_id != 0. */ #define CSS_ID_MAX (65535) struct css_id { /* * The css to which this ID points. This pointer is set to valid value * after cgroup is populated. If cgroup is removed, this will be NULL. * This pointer is expected to be RCU-safe because destroy() * is called after synchronize_rcu(). But for safe use, css_is_removed() * css_tryget() should be used for avoiding race. */ struct cgroup_subsys_state *css; /* * ID of this css. */ unsigned short id; /* * Depth in hierarchy which this ID belongs to. */ unsigned short depth; /* * ID is freed by RCU. (and lookup routine is RCU safe.) */ struct rcu_head rcu_head; /* * Hierarchy of CSS ID belongs to. */ unsigned short stack[0]; /* Array of Length (depth+1) */ }; /* The list of hierarchy roots */ static LIST_HEAD(roots); static int root_count; /* dummytop is a shorthand for the dummy hierarchy's top cgroup */ #define dummytop (&rootnode.top_cgroup) /* This flag indicates whether tasks in the fork and exit paths should * check for fork/exit handlers to call. This avoids us having to do * extra work in the fork/exit path if none of the subsystems need to * be called. */ static int need_forkexit_callback __read_mostly; /* convenient tests for these bits */ inline int cgroup_is_removed(const struct cgroup *cgrp) { return test_bit(CGRP_REMOVED, &cgrp->flags); } /* bits in struct cgroupfs_root flags field */ enum { ROOT_NOPREFIX, /* mounted subsystems have no named prefix */ }; static int cgroup_is_releasable(const struct cgroup *cgrp) { const int bits = (1 << CGRP_RELEASABLE) | (1 << CGRP_NOTIFY_ON_RELEASE); return (cgrp->flags & bits) == bits; } static int notify_on_release(const struct cgroup *cgrp) { return test_bit(CGRP_NOTIFY_ON_RELEASE, &cgrp->flags); } /* * for_each_subsys() allows you to iterate on each subsystem attached to * an active hierarchy */ #define for_each_subsys(_root, _ss) \ list_for_each_entry(_ss, &_root->subsys_list, sibling) /* for_each_active_root() allows you to iterate across the active hierarchies */ #define for_each_active_root(_root) \ list_for_each_entry(_root, &roots, root_list) /* the list of cgroups eligible for automatic release. Protected by * release_list_lock */ static LIST_HEAD(release_list); static DEFINE_SPINLOCK(release_list_lock); static void cgroup_release_agent(struct work_struct *work); static DECLARE_WORK(release_agent_work, cgroup_release_agent); static void check_for_release(struct cgroup *cgrp); /* Link structure for associating css_set objects with cgroups */ struct cg_cgroup_link { /* * List running through cg_cgroup_links associated with a * cgroup, anchored on cgroup->css_sets */ struct list_head cgrp_link_list; /* * List running through cg_cgroup_links pointing at a * single css_set object, anchored on css_set->cg_links */ struct list_head cg_link_list; struct css_set *cg; }; /* The default css_set - used by init and its children prior to any * hierarchies being mounted. It contains a pointer to the root state * for each subsystem. Also used to anchor the list of css_sets. Not * reference-counted, to improve performance when child cgroups * haven't been created. */ static struct css_set init_css_set; static struct cg_cgroup_link init_css_set_link; static int cgroup_subsys_init_idr(struct cgroup_subsys *ss); /* css_set_lock protects the list of css_set objects, and the * chain of tasks off each css_set. Nests outside task->alloc_lock * due to cgroup_iter_start() */ static DEFINE_RWLOCK(css_set_lock); static int css_set_count; /* hash table for cgroup groups. This improves the performance to * find an existing css_set */ #define CSS_SET_HASH_BITS 7 #define CSS_SET_TABLE_SIZE (1 << CSS_SET_HASH_BITS) static struct hlist_head css_set_table[CSS_SET_TABLE_SIZE]; static struct hlist_head *css_set_hash(struct cgroup_subsys_state *css[]) { int i; int index; unsigned long tmp = 0UL; for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) tmp += (unsigned long)css[i]; tmp = (tmp >> 16) ^ tmp; index = hash_long(tmp, CSS_SET_HASH_BITS); return &css_set_table[index]; } /* We don't maintain the lists running through each css_set to its * task until after the first call to cgroup_iter_start(). This * reduces the fork()/exit() overhead for people who have cgroups * compiled into their kernel but not actually in use */ static int use_task_css_set_links __read_mostly; /* When we create or destroy a css_set, the operation simply * takes/releases a reference count on all the cgroups referenced * by subsystems in this css_set. This can end up multiple-counting * some cgroups, but that's OK - the ref-count is just a * busy/not-busy indicator; ensuring that we only count each cgroup * once would require taking a global lock to ensure that no * subsystems moved between hierarchies while we were doing so. * * Possible TODO: decide at boot time based on the number of * registered subsystems and the number of CPUs or NUMA nodes whether * it's better for performance to ref-count every subsystem, or to * take a global lock and only add one ref count to each hierarchy. */ /* * unlink a css_set from the list and free it */ static void unlink_css_set(struct css_set *cg) { struct cg_cgroup_link *link; struct cg_cgroup_link *saved_link; hlist_del(&cg->hlist); css_set_count--; list_for_each_entry_safe(link, saved_link, &cg->cg_links, cg_link_list) { list_del(&link->cg_link_list); list_del(&link->cgrp_link_list); kfree(link); } } static void __put_css_set(struct css_set *cg, int taskexit) { int i; /* * Ensure that the refcount doesn't hit zero while any readers * can see it. Similar to atomic_dec_and_lock(), but for an * rwlock */ if (atomic_add_unless(&cg->refcount, -1, 1)) return; write_lock(&css_set_lock); if (!atomic_dec_and_test(&cg->refcount)) { write_unlock(&css_set_lock); return; } unlink_css_set(cg); write_unlock(&css_set_lock); rcu_read_lock(); for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) { struct cgroup *cgrp = rcu_dereference(cg->subsys[i]->cgroup); if (atomic_dec_and_test(&cgrp->count) && notify_on_release(cgrp)) { if (taskexit) set_bit(CGRP_RELEASABLE, &cgrp->flags); check_for_release(cgrp); } } rcu_read_unlock(); kfree(cg); } /* * refcounted get/put for css_set objects */ static inline void get_css_set(struct css_set *cg) { atomic_inc(&cg->refcount); } static inline void put_css_set(struct css_set *cg) { __put_css_set(cg, 0); } static inline void put_css_set_taskexit(struct css_set *cg) { __put_css_set(cg, 1); } /* * find_existing_css_set() is a helper for * find_css_set(), and checks to see whether an existing * css_set is suitable. * * oldcg: the cgroup group that we're using before the cgroup * transition * * cgrp: the cgroup that we're moving into * * template: location in which to build the desired set of subsystem * state objects for the new cgroup group */ static struct css_set *find_existing_css_set( struct css_set *oldcg, struct cgroup *cgrp, struct cgroup_subsys_state *template[]) { int i; struct cgroupfs_root *root = cgrp->root; struct hlist_head *hhead; struct hlist_node *node; struct css_set *cg; /* Built the set of subsystem state objects that we want to * see in the new css_set */ for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) { if (root->subsys_bits & (1UL << i)) { /* Subsystem is in this hierarchy. So we want * the subsystem state from the new * cgroup */ template[i] = cgrp->subsys[i]; } else { /* Subsystem is not in this hierarchy, so we * don't want to change the subsystem state */ template[i] = oldcg->subsys[i]; } } hhead = css_set_hash(template); hlist_for_each_entry(cg, node, hhead, hlist) { if (!memcmp(template, cg->subsys, sizeof(cg->subsys))) { /* All subsystems matched */ return cg; } } /* No existing cgroup group matched */ return NULL; } static void free_cg_links(struct list_head *tmp) { struct cg_cgroup_link *link; struct cg_cgroup_link *saved_link; list_for_each_entry_safe(link, saved_link, tmp, cgrp_link_list) { list_del(&link->cgrp_link_list); kfree(link); } } /* * allocate_cg_links() allocates "count" cg_cgroup_link structures * and chains them on tmp through their cgrp_link_list fields. Returns 0 on * success or a negative error */ static int allocate_cg_links(int count, struct list_head *tmp) { struct cg_cgroup_link *link; int i; INIT_LIST_HEAD(tmp); for (i = 0; i < count; i++) { link = kmalloc(sizeof(*link), GFP_KERNEL); if (!link) { free_cg_links(tmp); return -ENOMEM; } list_add(&link->cgrp_link_list, tmp); } return 0; } /** * link_css_set - a helper function to link a css_set to a cgroup * @tmp_cg_links: cg_cgroup_link objects allocated by allocate_cg_links() * @cg: the css_set to be linked * @cgrp: the destination cgroup */ static void link_css_set(struct list_head *tmp_cg_links, struct css_set *cg, struct cgroup *cgrp) { struct cg_cgroup_link *link; BUG_ON(list_empty(tmp_cg_links)); link = list_first_entry(tmp_cg_links, struct cg_cgroup_link, cgrp_link_list); link->cg = cg; list_move(&link->cgrp_link_list, &cgrp->css_sets); list_add(&link->cg_link_list, &cg->cg_links); } /* * find_css_set() takes an existing cgroup group and a * cgroup object, and returns a css_set object that's * equivalent to the old group, but with the given cgroup * substituted into the appropriate hierarchy. Must be called with * cgroup_mutex held */ static struct css_set *find_css_set( struct css_set *oldcg, struct cgroup *cgrp) { struct css_set *res; struct cgroup_subsys_state *template[CGROUP_SUBSYS_COUNT]; int i; struct list_head tmp_cg_links; struct hlist_head *hhead; /* First see if we already have a cgroup group that matches * the desired set */ read_lock(&css_set_lock); res = find_existing_css_set(oldcg, cgrp, template); if (res) get_css_set(res); read_unlock(&css_set_lock); if (res) return res; res = kmalloc(sizeof(*res), GFP_KERNEL); if (!res) return NULL; /* Allocate all the cg_cgroup_link objects that we'll need */ if (allocate_cg_links(root_count, &tmp_cg_links) < 0) { kfree(res); return NULL; } atomic_set(&res->refcount, 1); INIT_LIST_HEAD(&res->cg_links); INIT_LIST_HEAD(&res->tasks); INIT_HLIST_NODE(&res->hlist); /* Copy the set of subsystem state objects generated in * find_existing_css_set() */ memcpy(res->subsys, template, sizeof(res->subsys)); write_lock(&css_set_lock); /* Add reference counts and links from the new css_set. */ for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) { struct cgroup *cgrp = res->subsys[i]->cgroup; struct cgroup_subsys *ss = subsys[i]; atomic_inc(&cgrp->count); /* * We want to add a link once per cgroup, so we * only do it for the first subsystem in each * hierarchy */ if (ss->root->subsys_list.next == &ss->sibling) link_css_set(&tmp_cg_links, res, cgrp); } if (list_empty(&rootnode.subsys_list)) link_css_set(&tmp_cg_links, res, dummytop); BUG_ON(!list_empty(&tmp_cg_links)); css_set_count++; /* Add this cgroup group to the hash table */ hhead = css_set_hash(res->subsys); hlist_add_head(&res->hlist, hhead); write_unlock(&css_set_lock); return res; } /* * There is one global cgroup mutex. We also require taking * task_lock() when dereferencing a task's cgroup subsys pointers. * See "The task_lock() exception", at the end of this comment. * * A task must hold cgroup_mutex to modify cgroups. * * Any task can increment and decrement the count field without lock. * So in general, code holding cgroup_mutex can't rely on the count * field not changing. However, if the count goes to zero, then only * cgroup_attach_task() can increment it again. Because a count of zero * means that no tasks are currently attached, therefore there is no * way a task attached to that cgroup can fork (the other way to * increment the count). So code holding cgroup_mutex can safely * assume that if the count is zero, it will stay zero. Similarly, if * a task holds cgroup_mutex on a cgroup with zero count, it * knows that the cgroup won't be removed, as cgroup_rmdir() * needs that mutex. * * The fork and exit callbacks cgroup_fork() and cgroup_exit(), don't * (usually) take cgroup_mutex. These are the two most performance * critical pieces of code here. The exception occurs on cgroup_exit(), * when a task in a notify_on_release cgroup exits. Then cgroup_mutex * is taken, and if the cgroup count is zero, a usermode call made * to the release agent with the name of the cgroup (path relative to * the root of cgroup file system) as the argument. * * A cgroup can only be deleted if both its 'count' of using tasks * is zero, and its list of 'children' cgroups is empty. Since all * tasks in the system use _some_ cgroup, and since there is always at * least one task in the system (init, pid == 1), therefore, top_cgroup * always has either children cgroups and/or using tasks. So we don't * need a special hack to ensure that top_cgroup cannot be deleted. * * The task_lock() exception * * The need for this exception arises from the action of * cgroup_attach_task(), which overwrites one tasks cgroup pointer with * another. It does so using cgroup_mutex, however there are * several performance critical places that need to reference * task->cgroup without the expense of grabbing a system global * mutex. Therefore except as noted below, when dereferencing or, as * in cgroup_attach_task(), modifying a task'ss cgroup pointer we use * task_lock(), which acts on a spinlock (task->alloc_lock) already in * the task_struct routinely used for such matters. * * P.S. One more locking exception. RCU is used to guard the * update of a tasks cgroup pointer by cgroup_attach_task() */ /** * cgroup_lock - lock out any changes to cgroup structures * */ void cgroup_lock(void) { mutex_lock(&cgroup_mutex); } /** * cgroup_unlock - release lock on cgroup changes * * Undo the lock taken in a previous cgroup_lock() call. */ void cgroup_unlock(void) { mutex_unlock(&cgroup_mutex); } /* * A couple of forward declarations required, due to cyclic reference loop: * cgroup_mkdir -> cgroup_create -> cgroup_populate_dir -> * cgroup_add_file -> cgroup_create_file -> cgroup_dir_inode_operations * -> cgroup_mkdir. */ static int cgroup_mkdir(struct inode *dir, struct dentry *dentry, int mode); static int cgroup_rmdir(struct inode *unused_dir, struct dentry *dentry); static int cgroup_populate_dir(struct cgroup *cgrp); static struct inode_operations cgroup_dir_inode_operations; static struct file_operations proc_cgroupstats_operations; static struct backing_dev_info cgroup_backing_dev_info = { .capabilities = BDI_CAP_NO_ACCT_AND_WRITEBACK, }; static int alloc_css_id(struct cgroup_subsys *ss, struct cgroup *parent, struct cgroup *child); static struct inode *cgroup_new_inode(mode_t mode, struct super_block *sb) { struct inode *inode = new_inode(sb); if (inode) { inode->i_mode = mode; inode->i_uid = current_fsuid(); inode->i_gid = current_fsgid(); inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME; inode->i_mapping->backing_dev_info = &cgroup_backing_dev_info; } return inode; } /* * Call subsys's pre_destroy handler. * This is called before css refcnt check. */ static int cgroup_call_pre_destroy(struct cgroup *cgrp) { struct cgroup_subsys *ss; int ret = 0; for_each_subsys(cgrp->root, ss) if (ss->pre_destroy) { ret = ss->pre_destroy(ss, cgrp); if (ret) break; } return ret; } static void free_cgroup_rcu(struct rcu_head *obj) { struct cgroup *cgrp = container_of(obj, struct cgroup, rcu_head); kfree(cgrp); } static void cgroup_diput(struct dentry *dentry, struct inode *inode) { /* is dentry a directory ? if so, kfree() associated cgroup */ if (S_ISDIR(inode->i_mode)) { struct cgroup *cgrp = dentry->d_fsdata; struct cgroup_subsys *ss; BUG_ON(!(cgroup_is_removed(cgrp))); /* It's possible for external users to be holding css * reference counts on a cgroup; css_put() needs to * be able to access the cgroup after decrementing * the reference count in order to know if it needs to * queue the cgroup to be handled by the release * agent */ synchronize_rcu(); mutex_lock(&cgroup_mutex); /* * Release the subsystem state objects. */ for_each_subsys(cgrp->root, ss) ss->destroy(ss, cgrp); cgrp->root->number_of_cgroups--; mutex_unlock(&cgroup_mutex); /* * Drop the active superblock reference that we took when we * created the cgroup */ deactivate_super(cgrp->root->sb); call_rcu(&cgrp->rcu_head, free_cgroup_rcu); } iput(inode); } static void remove_dir(struct dentry *d) { struct dentry *parent = dget(d->d_parent); d_delete(d); simple_rmdir(parent->d_inode, d); dput(parent); } static void cgroup_clear_directory(struct dentry *dentry) { struct list_head *node; BUG_ON(!mutex_is_locked(&dentry->d_inode->i_mutex)); spin_lock(&dcache_lock); node = dentry->d_subdirs.next; while (node != &dentry->d_subdirs) { struct dentry *d = list_entry(node, struct dentry, d_u.d_child); list_del_init(node); if (d->d_inode) { /* This should never be called on a cgroup * directory with child cgroups */ BUG_ON(d->d_inode->i_mode & S_IFDIR); d = dget_locked(d); spin_unlock(&dcache_lock); d_delete(d); simple_unlink(dentry->d_inode, d); dput(d); spin_lock(&dcache_lock); } node = dentry->d_subdirs.next; } spin_unlock(&dcache_lock); } /* * NOTE : the dentry must have been dget()'ed */ static void cgroup_d_remove_dir(struct dentry *dentry) { cgroup_clear_directory(dentry); spin_lock(&dcache_lock); list_del_init(&dentry->d_u.d_child); spin_unlock(&dcache_lock); remove_dir(dentry); } /* * A queue for waiters to do rmdir() cgroup. A tasks will sleep when * cgroup->count == 0 && list_empty(&cgroup->children) && subsys has some * reference to css->refcnt. In general, this refcnt is expected to goes down * to zero, soon. * * CGRP_WAIT_ON_RMDIR flag is modified under cgroup's inode->i_mutex; */ DECLARE_WAIT_QUEUE_HEAD(cgroup_rmdir_waitq); static void cgroup_wakeup_rmdir_waiters(const struct cgroup *cgrp) { if (unlikely(test_bit(CGRP_WAIT_ON_RMDIR, &cgrp->flags))) wake_up_all(&cgroup_rmdir_waitq); } static int rebind_subsystems(struct cgroupfs_root *root, unsigned long final_bits) { unsigned long added_bits, removed_bits; struct cgroup *cgrp = &root->top_cgroup; int i; removed_bits = root->actual_subsys_bits & ~final_bits; added_bits = final_bits & ~root->actual_subsys_bits; /* Check that any added subsystems are currently free */ for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) { unsigned long bit = 1UL << i; struct cgroup_subsys *ss = subsys[i]; if (!(bit & added_bits)) continue; if (ss->root != &rootnode) { /* Subsystem isn't free */ return -EBUSY; } } /* Currently we don't handle adding/removing subsystems when * any child cgroups exist. This is theoretically supportable * but involves complex error handling, so it's being left until * later */ if (root->number_of_cgroups > 1) return -EBUSY; /* Process each subsystem */ for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) { struct cgroup_subsys *ss = subsys[i]; unsigned long bit = 1UL << i; if (bit & added_bits) { /* We're binding this subsystem to this hierarchy */ BUG_ON(cgrp->subsys[i]); BUG_ON(!dummytop->subsys[i]); BUG_ON(dummytop->subsys[i]->cgroup != dummytop); mutex_lock(&ss->hierarchy_mutex); cgrp->subsys[i] = dummytop->subsys[i]; cgrp->subsys[i]->cgroup = cgrp; list_move(&ss->sibling, &root->subsys_list); ss->root = root; if (ss->bind) ss->bind(ss, cgrp); mutex_unlock(&ss->hierarchy_mutex); } else if (bit & removed_bits) { /* We're removing this subsystem */ BUG_ON(cgrp->subsys[i] != dummytop->subsys[i]); BUG_ON(cgrp->subsys[i]->cgroup != cgrp); mutex_lock(&ss->hierarchy_mutex); if (ss->bind) ss->bind(ss, dummytop); dummytop->subsys[i]->cgroup = dummytop; cgrp->subsys[i] = NULL; subsys[i]->root = &rootnode; list_move(&ss->sibling, &rootnode.subsys_list); mutex_unlock(&ss->hierarchy_mutex); } else if (bit & final_bits) { /* Subsystem state should already exist */ BUG_ON(!cgrp->subsys[i]); } else { /* Subsystem state shouldn't exist */ BUG_ON(cgrp->subsys[i]); } } root->subsys_bits = root->actual_subsys_bits = final_bits; synchronize_rcu(); return 0; } static int cgroup_show_options(struct seq_file *seq, struct vfsmount *vfs) { struct cgroupfs_root *root = vfs->mnt_sb->s_fs_info; struct cgroup_subsys *ss; mutex_lock(&cgroup_mutex); for_each_subsys(root, ss) seq_printf(seq, ",%s", ss->name); if (test_bit(ROOT_NOPREFIX, &root->flags)) seq_puts(seq, ",noprefix"); if (strlen(root->release_agent_path)) seq_printf(seq, ",release_agent=%s", root->release_agent_path); mutex_unlock(&cgroup_mutex); return 0; } struct cgroup_sb_opts { unsigned long subsys_bits; unsigned long flags; char *release_agent; }; /* Convert a hierarchy specifier into a bitmask of subsystems and * flags. */ static int parse_cgroupfs_options(char *data, struct cgroup_sb_opts *opts) { char *token, *o = data ?: "all"; opts->subsys_bits = 0; opts->flags = 0; opts->release_agent = NULL; while ((token = strsep(&o, ",")) != NULL) { if (!*token) return -EINVAL; if (!strcmp(token, "all")) { /* Add all non-disabled subsystems */ int i; opts->subsys_bits = 0; for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) { struct cgroup_subsys *ss = subsys[i]; if (!ss->disabled) opts->subsys_bits |= 1ul << i; } } else if (!strcmp(token, "noprefix")) { set_bit(ROOT_NOPREFIX, &opts->flags); } else if (!strncmp(token, "release_agent=", 14)) { /* Specifying two release agents is forbidden */ if (opts->release_agent) return -EINVAL; opts->release_agent = kzalloc(PATH_MAX, GFP_KERNEL); if (!opts->release_agent) return -ENOMEM; strncpy(opts->release_agent, token + 14, PATH_MAX - 1); opts->release_agent[PATH_MAX - 1] = 0; } else { struct cgroup_subsys *ss; int i; for (i = 0; i < CGROUP_SUBSYS_COUNT; i++) { ss = subsys[i]; if (!strcmp(token, ss->name)) { if (!ss->disabled) set_bit(i, &opts->subsys_bits); break; } } if (i == CGROUP_SUBSYS_COUNT) return -ENOENT; } } /* We can't have an empty hierarchy */ if (!opts->subsys_bits) return -EINVAL; return 0; } static int cgroup_remount(struct super_block *sb, int *flags, char *data) { int ret = 0; struct cgroupfs_root *root = sb->s_fs_info; struct cgroup *cgrp = &root->top_cgroup; struct cgroup_sb_opts opts; mutex_lock(&cgrp->dentry->d_inode->i_mutex); mutex_lock(&cgroup_mutex); /* See what subsystems are wanted */ ret = parse_cgroupfs_options(data, &opts); if (ret) goto out_unlock; /* Don't allow flags to change at remount */ if (opts.flags != root->flags) { ret = -EINVAL; goto out_unlock; } ret = rebind_subsystems(root, opts.subsys_bits); if (ret) goto out_unlock; /* (re)populate subsystem files */ cgroup_populate_dir(cgrp); if (opts.release_agent) strcpy(root->release_agent_path, opts.release_agent); out_unlock: kfree(opts.release_agent); mutex_unlock(&cgroup_mutex); mutex_unlock(&cgrp->dentry->d_inode->i_mutex); return ret; } static struct super_operations cgroup_ops = { .statfs = simple_statfs, .drop_inode = generic_delete_inode, .show_options = cgroup_show_options, .remount_fs = cgroup_remount, }; static void init_cgroup_housekeeping(struct cgroup *cgrp) { INIT_LIST_HEAD(&cgrp->sibling); INIT_LIST_HEAD(&cgrp->children); INIT_LIST_HEAD(&cgrp->css_sets); INIT_LIST_HEAD(&cgrp->release_list); init_rwsem(&cgrp->pids_mutex); } static void init_cgroup_root(struct cgroupfs_root *root) { struct cgroup *cgrp = &root->top_cgroup; INIT_LIST_HEAD(&root->subsys_list); INIT_LIST_HEAD(&root->root_list); root->number_of_cgroups = 1; cgrp->root = root; cgrp->top_cgroup = cgrp; init_cgroup_housekeeping(cgrp); } static int cgroup_test_super(struct super_block *sb, void *data) { struct cgroupfs_root *new = data; struct cgroupfs_root *root = sb->s_fs_info; /* First check subsystems */ if (new->subsys_bits != root->subsys_bits) return 0; /* Next check flags */ if (new->flags != root->flags) return 0; return 1; } static int cgroup_set_super(struct super_block *sb, void *data) { int ret; struct cgroupfs_root *root = data; ret = set_anon_super(sb, NULL); if (ret) return ret; sb->s_fs_info = root; root->sb = sb; sb->s_blocksize = PAGE_CACHE_SIZE; sb->s_blocksize_bits = PAGE_CACHE_SHIFT; sb->s_magic = CGROUP_SUPER_MAGIC; sb->s_op = &cgroup_ops; return 0; } static int cgroup_get_rootdir(struct super_block *sb) { struct inode *inode = cgroup_new_inode(S_IFDIR | S_IRUGO | S_IXUGO | S_IWUSR, sb); struct dentry *dentry; if (!inode) return -ENOMEM; inode->i_fop = &simple_dir_operations; inode->i_op = &cgroup_dir_inode_operations; /* directories start off with i_nlink == 2 (for "." entry) */ inc_nlink(inode); dentry = d_alloc_root(inode); if (!dentry) { iput(inode); return -ENOMEM; } sb->s_root = dentry; return 0; } static int cgroup_get_sb(struct file_system_type *fs_type, int flags, const char *unused_dev_name, void *data, struct vfsmount *mnt) { struct cgroup_sb_opts opts; int ret = 0; struct super_block *sb; struct cgroupfs_root *root; struct list_head tmp_cg_links; /* First find the desired set of subsystems */ ret = parse_cgroupfs_options(data, &opts); if (ret) { kfree(opts.release_agent); return ret; } root = kzalloc(sizeof(*root), GFP_KERNEL); if (!root) { kfree(opts.release_agent); return -ENOMEM; } init_cgroup_root(root); root->subsys_bits = opts.subsys_bits; root->flags = opts.flags; if (opts.release_agent) { strcpy(root->release_agent_path, opts.release_agent); kfree(opts.release_agent); } sb = sget(fs_type, cgroup_test_super, cgroup_set_super, root); if (IS_ERR(sb)) { kfree(root); return PTR_ERR(sb); } if (sb->s_fs_info != root) { /* Reusing an existing superblock */ BUG_ON(sb->s_root == NULL); kfree(root); root = NULL; } else { /* New superblock */ struct cgroup *root_cgrp = &root->top_cgroup; struct inode *inode; int i; BUG_ON(sb->s_root != NULL); ret = cgroup_get_rootdir(sb); if (ret) goto drop_new_super; inode = sb->s_root->d_inode; mutex_lock(&inode->i_mutex); mutex_lock(&cgroup_mutex); /* * We're accessing css_set_count without locking * css_set_lock here, but that's OK - it can only be * increased by someone holding cgroup_lock, and * that's us. The worst that can happen is that we * have some link structures left over */ ret = allocate_cg_links(css_set_count, &tmp_cg_links); if (ret) { mutex_unlock(&cgroup_mutex); mutex_unlock(&inode->i_mutex); goto drop_new_super; } ret = rebind_subsystems(root, root->subsys_bits); if (ret == -EBUSY) { mutex_unlock(&cgroup_mutex); mutex_unlock(&inode->i_mutex); goto free_cg_links; } /* EBUSY should be the only error here */ BUG_ON(ret); list_add(&root->root_list, &roots); root_count++; sb->s_root->d_fsdata = root_cgrp; root->top_cgroup.dentry = sb->s_root; /* Link the top cgroup in this hierarchy into all * the css_set objects */ write_lock(&css_set_lock); for (i = 0; i < CSS_SET_TABLE_SIZE; i++) { struct hlist_head *hhead = &css_set_table[i]; struct hlist_node *node; struct css_set *cg; hlist_for_each_entry(cg, node, hhead, hlist) link_css_set(&tmp_cg_links, cg, root_cgrp); } write_unlock(&css_set_lock); free_cg_links(&tmp_cg_links); BUG_ON(!list_empty(&root_cgrp->sibling)); BUG_ON(!list_empty(&root_cgrp->children)); BUG_ON(root->number_of_cgroups != 1); cgroup_populate_dir(root_cgrp); mutex_unlock(&inode->i_mutex); mutex_unlock(&cgroup_mutex); } simple_set_mnt(mnt, sb); return 0; free_cg_links: free_cg_links(&tmp_cg_links); drop_new_super: deactivate_locked_super(sb); return ret; } static void cgroup_kill_sb(struct super_block *sb) { struct cgroupfs_root *root = sb->s_fs_info; struct cgroup *cgrp = &root->top_cgroup; int ret; struct cg_cgroup_link *link; struct cg_cgroup_link *saved_link; BUG_ON(!root); BUG_ON(root->number_of_cgroups != 1); BUG_ON(!list_empty(&cgrp->children)); BUG_ON(!list_empty(&cgrp->sibling)); mutex_lock(&cgroup_mutex); /* Rebind all subsystems back to the default hierarchy */ ret = rebind_subsystems(root, 0); /* Shouldn't be able to fail ... */ BUG_ON(ret); /* * Release all the links from css_sets to this hierarchy's * root cgroup */ write_lock(&css_set_lock); list_for_each_entry_safe(link, saved_link, &cgrp->css_sets, cgrp_link_list) { list_del(&link->cg_link_list); list_del(&link->cgrp_link_list); kfree(link); } write_unlock(&css_set_lock); if (!list_empty(&root->root_list)) { list_del(&root->root_list); root_count--; } mutex_unlock(&cgroup_mutex); kill_litter_super(sb); kfree(root); } static struct file_system_type cgroup_fs_type = { .name = "cgroup", .get_sb = cgroup_get_sb, .kill_sb = cgroup_kill_sb, }; static inline struct cgroup *__d_cgrp(struct dentry *dentry) { return dentry->d_fsdata; } static inline struct cftype *__d_cft(struct dentry *dentry) { return dentry->d_fsdata; } /** * cgroup_path - generate the path of a cgroup * @cgrp: the cgroup in question * @buf: the buffer to write the path into * @buflen: the length of the buffer * * Called with cgroup_mutex held or else with an RCU-protected cgroup * reference. Writes path of cgroup into buf. Returns 0 on success, * -errno on error. */ int cgroup_path(const struct cgroup *cgrp, char *buf, int buflen) { char *start; struct dentry *dentry = rcu_dereference(cgrp->dentry); if (!dentry || cgrp == dummytop) { /* * Inactive subsystems have no dentry for their root * cgroup */ strcpy(buf, "/"); return 0; } start = buf + buflen; *--start = '\0'; for (;;) { int len = dentry->d_name.len; if ((start -= len) < buf) return -ENAMETOOLONG; memcpy(start, cgrp->dentry->d_name.name, len); cgrp = cgrp->parent; if (!cgrp) break; dentry = rcu_dereference(cgrp->dentry); if (!cgrp->parent) continue; if (--start < buf) return -ENAMETOOLONG; *start = '/'; } memmove(buf, start, buf + buflen - start); return 0; } /* * Return the first subsystem attached to a cgroup's hierarchy, and * its subsystem id. */ static void get_first_subsys(const struct cgroup *cgrp, struct cgroup_subsys_state **css, int *subsys_id) { const struct cgroupfs_root *root = cgrp->root; const struct cgroup_subsys *test_ss; BUG_ON(list_empty(&root->subsys_list)); test_ss = list_entry(root->subsys_list.next, struct cgroup_subsys, sibling); if (css) { *css = cgrp->subsys[test_ss->subsys_id]; BUG_ON(!*css); } if (subsys_id) *subsys_id = test_ss->subsys_id; } /** * cgroup_attach_task - attach task 'tsk' to cgroup 'cgrp' * @cgrp: the cgroup the task is attaching to * @tsk: the task to be attached * * Call holding cgroup_mutex. May take task_lock of * the task 'tsk' during call. */ int cgroup_attach_task(struct cgroup *cgrp, struct task_struct *tsk) { int retval = 0; struct cgroup_subsys *ss; struct cgroup *oldcgrp; struct css_set *cg; struct css_set *newcg; struct cgroupfs_root *root = cgrp->root; int subsys_id; get_first_subsys(cgrp, NULL, &subsys_id); /* Nothing to do if the task is already in that cgroup */ oldcgrp = task_cgroup(tsk, subsys_id); if (cgrp == oldcgrp) return 0; for_each_subsys(root, ss) { if (ss->can_attach) { retval = ss->can_attach(ss, cgrp, tsk); if (retval) return retval; } } task_lock(tsk); cg = tsk->cgroups; get_css_set(cg); task_unlock(tsk); /* * Locate or allocate a new css_set for this task, * based on its final set of cgroups */ newcg = find_css_set(cg, cgrp); put_css_set(cg); if (!newcg) return -ENOMEM; task_lock(tsk); if (tsk->flags & PF_EXITING) { task_unlock(tsk); put_css_set(newcg); return -ESRCH; } rcu_assign_pointer(tsk->cgroups, newcg); task_unlock(tsk); /* Update the css_set linked lists if we're using them */ write_lock(&css_set_lock); if (!list_empty(&tsk->cg_list)) { list_del(&tsk->cg_list); list_add(&tsk->cg_list, &newcg->tasks); } write_unlock(&css_set_lock); for_each_subsys(root, ss) { if (ss->attach) ss->attach(ss, cgrp, oldcgrp, tsk); } set_bit(CGRP_RELEASABLE, &oldcgrp->flags); synchronize_rcu(); put_css_set(cg); /* * wake up rmdir() waiter. the rmdir should fail since the cgroup * is no longer empty. */ cgroup_wakeup_rmdir_waiters(cgrp); return 0; } /* * Attach task with pid 'pid' to cgroup 'cgrp'. Call with cgroup_mutex * held. May take task_lock of task */ static int attach_task_by_pid(struct cgroup *cgrp, u64 pid) { struct task_struct *tsk; const struct cred *cred = current_cred(), *tcred; int ret; if (pid) { rcu_read_lock(); tsk = find_task_by_vpid(pid); if (!tsk || tsk->flags & PF_EXITING) { rcu_read_unlock(); return -ESRCH; } tcred = __task_cred(tsk); if (cred->euid && cred->euid != tcred->uid && cred->euid != tcred->suid) { rcu_read_unlock(); return -EACCES; } get_task_struct(tsk); rcu_read_unlock(); } else { tsk = current; get_task_struct(tsk); } ret = cgroup_attach_task(cgrp, tsk); put_task_struct(tsk); return ret; } static int cgroup_tasks_write(struct cgroup *cgrp, struct cftype *cft, u64 pid) { int ret; if (!cgroup_lock_live_group(cgrp)) return -ENODEV; ret = attach_task_by_pid(cgrp, pid); cgroup_unlock(); return ret; } /* The various types of files and directories in a cgroup file system */ enum cgroup_filetype { FILE_ROOT, FILE_DIR, FILE_TASKLIST, FILE_NOTIFY_ON_RELEASE, FILE_RELEASE_AGENT, }; /** * cgroup_lock_live_group - take cgroup_mutex and check that cgrp is alive. * @cgrp: the cgroup to be checked for liveness * * On success, returns true; the lock should be later released with * cgroup_unlock(). On failure returns false with no lock held. */ bool cgroup_lock_live_group(struct cgroup *cgrp) { mutex_lock(&cgroup_mutex); if (cgroup_is_removed(cgrp)) { mutex_unlock(&cgroup_mutex); return false; } return true; } static int cgroup_release_agent_write(struct cgroup *cgrp, struct cftype *cft, const char *buffer) { BUILD_BUG_ON(sizeof(cgrp->root->release_agent_path) < PATH_MAX); if (!cgroup_lock_live_group(cgrp)) return -ENODEV; strcpy(cgrp->root->release_agent_path, buffer); cgroup_unlock(); return 0; } static int cgroup_release_agent_show(struct cgroup *cgrp, struct cftype *cft, struct seq_file *seq) { if (!cgroup_lock_live_group(cgrp)) return -ENODEV; seq_puts(seq, cgrp->root->release_agent_path); seq_putc(seq, '\n'); cgroup_unlock(); return 0; } /* A buffer size big enough for numbers or short strings */ #define CGROUP_LOCAL_BUFFER_SIZE 64 static ssize_t cgroup_write_X64(struct cgroup *cgrp, struct cftype *cft, struct file *file, const char __user *userbuf, size_t nbytes, loff_t *unused_ppos) { char buffer[CGROUP_LOCAL_BUFFER_SIZE]; int retval = 0; char *end; if (!nbytes) return -EINVAL; if (nbytes >= sizeof(buffer)) return -E2BIG; if (copy_from_user(buffer, userbuf, nbytes)) return -EFAULT; buffer[nbytes] = 0; /* nul-terminate */ strstrip(buffer); if (cft->write_u64) { u64 val = simple_strtoull(buffer, &end, 0); if (*end) return -EINVAL; retval = cft->write_u64(cgrp, cft, val); } else { s64 val = simple_strtoll(buffer, &end, 0); if (*end) return -EINVAL; retval = cft->write_s64(cgrp, cft, val); } if (!retval) retval = nbytes; return retval; } static ssize_t cgroup_write_string(struct cgroup *cgrp, struct cftype *cft, struct file *file, const char __user *userbuf, size_t nbytes, loff_t *unused_ppos) { char local_buffer[CGROUP_LOCAL_BUFFER_SIZE]; int retval = 0; size_t max_bytes = cft->max_write_len; char *buffer = local_buffer; if (!max_bytes) max_bytes = sizeof(local_buffer) - 1; if (nbytes >= max_bytes) return -E2BIG; /* Allocate a dynamic buffer if we need one */ if (nbytes >= sizeof(local_buffer)) { buffer = kmalloc(nbytes + 1, GFP_KERNEL); if (buffer == NULL) return -ENOMEM; } if (nbytes && copy_from_user(buffer, userbuf, nbytes)) { retval = -EFAULT; goto out; } buffer[nbytes] = 0; /* nul-terminate */ strstrip(buffer); retval = cft->write_string(cgrp, cft, buffer); if (!retval) retval = nbytes; out: if (buffer != local_buffer) kfree(buffer); return retval; } static ssize_t cgroup_file_write(struct file *file, const char __user *buf, size_t nbytes, loff_t *ppos) { struct cftype *cft = __d_cft(file->f_dentry); struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent); if (cgroup_is_removed(cgrp)) return -ENODEV; if (cft->write) return cft->write(cgrp, cft, file, buf, nbytes, ppos); if (cft->write_u64 || cft->write_s64) return cgroup_write_X64(cgrp, cft, file, buf, nbytes, ppos); if (cft->write_string) return cgroup_write_string(cgrp, cft, file, buf, nbytes, ppos); if (cft->trigger) { int ret = cft->trigger(cgrp, (unsigned int)cft->private); return ret ? ret : nbytes; } return -EINVAL; } static ssize_t cgroup_read_u64(struct cgroup *cgrp, struct cftype *cft, struct file *file, char __user *buf, size_t nbytes, loff_t *ppos) { char tmp[CGROUP_LOCAL_BUFFER_SIZE]; u64 val = cft->read_u64(cgrp, cft); int len = sprintf(tmp, "%llu\n", (unsigned long long) val); return simple_read_from_buffer(buf, nbytes, ppos, tmp, len); } static ssize_t cgroup_read_s64(struct cgroup *cgrp, struct cftype *cft, struct file *file, char __user *buf, size_t nbytes, loff_t *ppos) { char tmp[CGROUP_LOCAL_BUFFER_SIZE]; s64 val = cft->read_s64(cgrp, cft); int len = sprintf(tmp, "%lld\n", (long long) val); return simple_read_from_buffer(buf, nbytes, ppos, tmp, len); } static ssize_t cgroup_file_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos) { struct cftype *cft = __d_cft(file->f_dentry); struct cgroup *cgrp = __d_cgrp(file->f_dentry->d_parent); if (cgroup_is_removed(cgrp)) return -ENODEV; if (cft->read) return cft->read(cgrp, cft, file, buf, nbytes, ppos); if (cft->read_u64) return cgroup_read_u64(cgrp, cft, file, buf, nbytes, ppos); if (cft->read_s64) return cgroup_read_s64(cgrp, cft, file, buf, nbytes, ppos); return -EINVAL; } /* * seqfile ops/methods for returning structured data. Currently just * supports string->u64 maps, but can be extended in future. */ struct cgroup_seqfile_state { struct cftype *cft; struct cgroup *cgroup; }; static int cgroup_map_add(struct cgroup_map_cb *cb, const char *key, u64 value) { struct seq_file *sf = cb->state; return seq_printf(sf, "%s %llu\n", key, (unsigned long long)value); } static int cgroup_seqfile_show(struct seq_file *m, void *arg) { struct cgroup_seqfile_state *state = m->private; struct cftype *cft = state->cft; if (cft->read_map) { struct cgroup_map_cb cb = { .fill = cgroup_map_add, .state = m, }; return cft->read_map(state->cgroup, cft, &cb); } return cft->read_seq_string(state->cgroup, cft, m); } static int cgroup_seqfile_release(struct inode *inode, struct file *file) { struct seq_file *seq = file->private_data; kfree(seq->private); return single_release(inode, file); } static struct file_operations cgroup_seqfile_operations = { .read = seq_read, .write = cgroup_file_write, .llseek = seq_lseek, .release = cgroup_seqfile_release, }; static int cgroup_file_open(struct inode *inode, struct file *file) { int err; struct cftype *cft; err = generic_file_open(inode, file); if (err) return err; cft = __d_cft(file->f_dentry); if (cft->read_map || cft->read_seq_string) { struct cgroup_seqfile_state *state = kzalloc(sizeof(*state), GFP_USER); if (!state) return -ENOMEM; state->cft = cft; state->cgroup = __d_cgrp(file->f_dentry->d_parent); file->f_op = &cgroup_seqfile_operations; err = single_open(file, cgroup_seqfile_show, state); if (err < 0) kfree(state); } else if (cft->open) err = cft->open(inode, file); else err = 0; return err; } static int cgroup_file_release(struct inode *inode, struct file *file) { struct cftype *cft = __d_cft(file->f_dentry); if (cft->release) return cft->release(inode, file); return 0; } /* * cgroup_rename - Only allow simple rename of directories in place. */ static int cgroup_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry) { if (!S_ISDIR(old_dentry->d_inode->i_mode)) return -ENOTDIR; if (new_dentry->d_inode) return -EEXIST; if (old_dir != new_dir) return -EIO; return simple_rename(old_dir, old_dentry, new_dir, new_dentry); } static struct file_operations cgroup_file_operations = { .read = cgroup_file_read, .write = cgroup_file_write, .llseek = generic_file_llseek, .open = cgroup_file_open, .release = cgroup_file_release, }; static struct inode_operations cgroup_dir_inode_operations = { .lookup = simple_lookup, .mkdir = cgroup_mkdir, .rmdir = cgroup_rmdir, .rename = cgroup_rename, }; static int cgroup_create_file(struct dentry *dentry, mode_t mode, struct super_block *sb) { static const struct dentry_operations cgroup_dops = { .d_iput = cgroup_diput, }; struct inode *inode; if (!dentry) return -ENOENT; if (dentry->d_inode) return -EEXIST; inode = cgroup_new_inode(mode, sb); if (!inode) return -ENOMEM; if (S_ISDIR(mode)) { inode->i_op = &cgroup_dir_inode_operations; inode->i_fop = &simple_dir_operations; /* start off with i_nlink == 2 (for "." entry) */ inc_nlink(inode); /* start with the directory inode held, so that we can * populate it without racing with another mkdir */ mutex_lock_nested(&inode->i_mutex, I_MUTEX_CHILD); } else if (S_ISREG(mode)) { inode->i_size = 0; inode->i_fop = &cgroup_file_operations; } dentry->d_op = &cgroup_dops; d_instantiate(dentry, inode); dget(dentry); /* Extra count - pin the dentry in core */ return 0; } /* * cgroup_create_dir - create a directory for an object. * @cgrp: the cgroup we create the directory for. It must have a valid * ->parent field. And we are going to fill its ->dentry field. * @dentry: dentry of the new cgroup * @mode: mode to set on new directory. */ static int cgroup_create_dir(struct cgroup *cgrp, struct dentry *dentry, mode_t mode) { struct dentry *parent; int error = 0; parent = cgrp->parent->dentry; error = cgroup_create_file(dentry, S_IFDIR | mode, cgrp->root->sb); if (!error) { dentry->d_fsdata = cgrp; inc_nlink(parent->d_inode); rcu_assign_pointer(cgrp->dentry, dentry); dget(dentry); } dput(dentry); return error; } /** * cgroup_file_mode - deduce file mode of a control file * @cft: the control file in question * * returns cft->mode if ->mode is not 0 * returns S_IRUGO|S_IWUSR if it has both a read and a write handler * returns S_IRUGO if it has only a read handler * returns S_IWUSR if it has only a write hander */ static mode_t cgroup_file_mode(const struct cftype *cft) { mode_t mode = 0; if (cft->mode) return cft->mode; if (cft->read || cft->read_u64 || cft->read_s64 || cft->read_map || cft->read_seq_string) mode |= S_IRUGO; if (cft->write || cft->write_u64 || cft->write_s64 || cft->write_string || cft->trigger) mode |= S_IWUSR; return mode; } int cgroup_add_file(struct cgroup *cgrp, struct cgroup_subsys *subsys, const struct cftype *cft) { struct dentry *dir = cgrp->dentry; struct dentry *dentry; int error; mode_t mode; char name[MAX_CGROUP_TYPE_NAMELEN + MAX_CFTYPE_NAME + 2] = { 0 }; if (subsys && !test_bit(ROOT_NOPREFIX, &cgrp->root->flags)) { strcpy(name, subsys->name); strcat(name, "."); } strcat(name, cft->name); BUG_ON(!mutex_is_locked(&dir->d_inode->i_mutex)); dentry = lookup_one_len(name, dir, strlen(name)); if (!IS_ERR(dentry)) { mode = cgroup_file_mode(cft); error = cgroup_create_file(dentry, mode | S_IFREG, cgrp->root->sb); if (!error) dentry->d_fsdata = (void *)cft; dput(dentry); } else error = PTR_ERR(dentry); return error; } int cgroup_add_files(struct cgroup *cgrp, struct cgroup_subsys *subsys, const struct cftype cft[], int count) { int i, err; for (i = 0; i < count; i++) { err = cgroup_add_file(cgrp, subsys, &cft[i]); if (err) return err; } return 0; } /** * cgroup_task_count - count the number of tasks in a cgroup. * @cgrp: the cgroup in question * * Return the number of tasks in the cgroup. */ int cgroup_task_count(const struct cgroup *cgrp) { int count = 0; struct cg_cgroup_link *link; read_lock(&css_set_lock); list_for_each_entry(link, &cgrp->css_sets, cgrp_link_list) { count += atomic_read(&link->cg->refcount); } read_unlock(&css_set_lock); return count; } /* * Advance a list_head iterator. The iterator should be positioned at * the start of a css_set */ static void cgroup_advance_iter(struct cgroup *cgrp, struct cgroup_iter *it) { struct list_head *l = it->cg_link; struct cg_cgroup_link *link; struct css_set *cg; /* Advance to the next non-empty css_set */ do { l = l->next; if (l == &cgrp->css_sets) { it->cg_link = NULL; return; } link = list_entry(l, struct cg_cgroup_link, cgrp_link_list); cg = link->cg; } while (list_empty(&cg->tasks)); it->cg_link = l; it->task = cg->tasks.next; } /* * To reduce the fork() overhead for systems that are not actually * using their cgroups capability, we don't maintain the lists running * through each css_set to its tasks until we see the list actually * used - in other words after the first call to cgroup_iter_start(). * * The tasklist_lock is not held here, as do_each_thread() and * while_each_thread() are protected by RCU. */ static void cgroup_enable_task_cg_lists(void) { struct task_struct *p, *g; write_lock(&css_set_lock); use_task_css_set_links = 1; do_each_thread(g, p) { task_lock(p); /* * We should check if the process is exiting, otherwise * it will race with cgroup_exit() in that the list * entry won't be deleted though the process has exited. */ if (!(p->flags & PF_EXITING) && list_empty(&p->cg_list)) list_add(&p->cg_list, &p->cgroups->tasks); task_unlock(p); } while_each_thread(g, p); write_unlock(&css_set_lock); } void cgroup_iter_start(struct cgroup *cgrp, struct cgroup_iter *it) { /* * The first time anyone tries to iterate across a cgroup, * we need to enable the list linking each css_set to its * tasks, and fix up all existing tasks. */ if (!use_task_css_set_links) cgroup_enable_task_cg_lists(); read_lock(&css_set_lock); it->cg_link = &cgrp->css_sets; cgroup_advance_iter(cgrp, it); } struct task_struct *cgroup_iter_next(struct cgroup *cgrp, struct cgroup_iter *it) { struct task_struct *res; struct list_head *l = it->task; struct cg_cgroup_link *link; /* If the iterator cg is NULL, we have no tasks */ if (!it->cg_link) return NULL; res = list_entry(l, struct task_struct, cg_list); /* Advance iterator to find next entry */ l = l->next; link = list_entry(it->cg_link, struct cg_cgroup_link, cgrp_link_list); if (l == &link->cg->tasks) { /* We reached the end of this task list - move on to * the next cg_cgroup_link */ cgroup_advance_iter(cgrp, it); } else { it->task = l; } return res; } void cgroup_iter_end(struct cgroup *cgrp, struct cgroup_iter *it) { read_unlock(&css_set_lock); } static inline int started_after_time(struct task_struct *t1, struct timespec *time, struct task_struct *t2) { int start_diff = timespec_compare(&t1->start_time, time); if (start_diff > 0) { return 1; } else if (start_diff < 0) { return 0; } else { /* * Arbitrarily, if two processes started at the same * time, we'll say that the lower pointer value * started first. Note that t2 may have exited by now * so this may not be a valid pointer any longer, but * that's fine - it still serves to distinguish * between two tasks started (effectively) simultaneously. */ return t1 > t2; } } /* * This function is a callback from heap_insert() and is used to order * the heap. * In this case we order the heap in descending task start time. */ static inline int started_after(void *p1, void *p2) { struct task_struct *t1 = p1; struct task_struct *t2 = p2; return started_after_time(t1, &t2->start_time, t2); } /** * cgroup_scan_tasks - iterate though all the tasks in a cgroup * @scan: struct cgroup_scanner containing arguments for the scan * * Arguments include pointers to callback functions test_task() and * process_task(). * Iterate through all the tasks in a cgroup, calling test_task() for each, * and if it returns true, call process_task() for it also. * The test_task pointer may be NULL, meaning always true (select all tasks). * Effectively duplicates cgroup_iter_{start,next,end}() * but does not lock css_set_lock for the call to process_task(). * The struct cgroup_scanner may be embedded in any structure of the caller's * creation. * It is guaranteed that process_task() will act on every task that * is a member of the cgroup for the duration of this call. This * function may or may not call process_task() for tasks that exit * or move to a different cgroup during the call, or are forked or * move into the cgroup during the call. * * Note that test_task() may be called with locks held, and may in some * situations be called multiple times for the same task, so it should * be cheap. * If the heap pointer in the struct cgroup_scanner is non-NULL, a heap has been * pre-allocated and will be used for heap operations (and its "gt" member will * be overwritten), else a temporary heap will be used (allocation of which * may cause this function to fail). */ int cgroup_scan_tasks(struct cgroup_scanner *scan) { int retval, i; struct cgroup_iter it; struct task_struct *p, *dropped; /* Never dereference latest_task, since it's not refcounted */ struct task_struct *latest_task = NULL; struct ptr_heap tmp_heap; struct ptr_heap *heap; struct timespec latest_time = { 0, 0 }; if (scan->heap) { /* The caller supplied our heap and pre-allocated its memory */ heap = scan->heap; heap->gt = &started_after; } else { /* We need to allocate our own heap memory */ heap = &tmp_heap; retval = heap_init(heap, PAGE_SIZE, GFP_KERNEL, &started_after); if (retval) /* cannot allocate the heap */ return retval; } again: /* * Scan tasks in the cgroup, using the scanner's "test_task" callback * to determine which are of interest, and using the scanner's * "process_task" callback __u8 s_users[16*48]; /* ids of all fs'es sharing the log */ /* 0x0400 */ } journal_superblock_t; #define JFS_HAS_COMPAT_FEATURE(j,mask) \ ((j)->j_format_version >= 2 && \ ((j)->j_superblock->s_feature_compat & cpu_to_be32((mask)))) #define JFS_HAS_RO_COMPAT_FEATURE(j,mask) \ ((j)->j_format_version >= 2 && \ ((j)->j_superblock->s_feature_ro_compat & cpu_to_be32((mask)))) #define JFS_HAS_INCOMPAT_FEATURE(j,mask) \ ((j)->j_format_version >= 2 && \ ((j)->j_superblock->s_feature_incompat & cpu_to_be32((mask)))) #define JFS_FEATURE_INCOMPAT_REVOKE 0x00000001 /* Features known to this kernel version: */ #define JFS_KNOWN_COMPAT_FEATURES 0 #define JFS_KNOWN_ROCOMPAT_FEATURES 0 #define JFS_KNOWN_INCOMPAT_FEATURES JFS_FEATURE_INCOMPAT_REVOKE #ifdef __KERNEL__ #include <linux/fs.h> #include <linux/sched.h> #define J_ASSERT(assert) BUG_ON(!(assert)) #if defined(CONFIG_BUFFER_DEBUG) void buffer_assertion_failure(struct buffer_head *bh); #define J_ASSERT_BH(bh, expr) \ do { \ if (!(expr)) \ buffer_assertion_failure(bh); \ J_ASSERT(expr); \ } while (0) #define J_ASSERT_JH(jh, expr) J_ASSERT_BH(jh2bh(jh), expr) #else #define J_ASSERT_BH(bh, expr) J_ASSERT(expr) #define J_ASSERT_JH(jh, expr) J_ASSERT(expr) #endif #if defined(JBD_PARANOID_IOFAIL) #define J_EXPECT(expr, why...) J_ASSERT(expr) #define J_EXPECT_BH(bh, expr, why...) J_ASSERT_BH(bh, expr) #define J_EXPECT_JH(jh, expr, why...) J_ASSERT_JH(jh, expr) #else #define __journal_expect(expr, why...) \ ({ \ int val = (expr); \ if (!val) { \ printk(KERN_ERR \ "EXT3-fs unexpected failure: %s;\n",# expr); \ printk(KERN_ERR why "\n"); \ } \ val; \ }) #define J_EXPECT(expr, why...) __journal_expect(expr, ## why) #define J_EXPECT_BH(bh, expr, why...) __journal_expect(expr, ## why) #define J_EXPECT_JH(jh, expr, why...) __journal_expect(expr, ## why) #endif enum jbd_state_bits { BH_JBD /* Has an attached ext3 journal_head */ = BH_PrivateStart, BH_JWrite, /* Being written to log (@@@ DEBUGGING) */ BH_Freed, /* Has been freed (truncated) */ BH_Revoked, /* Has been revoked from the log */ BH_RevokeValid, /* Revoked flag is valid */ BH_JBDDirty, /* Is dirty but journaled */ BH_State, /* Pins most journal_head state */ BH_JournalHead, /* Pins bh->b_private and jh->b_bh */ BH_Unshadow, /* Dummy bit, for BJ_Shadow wakeup filtering */ }; BUFFER_FNS(JBD, jbd) BUFFER_FNS(JWrite, jwrite) BUFFER_FNS(JBDDirty, jbddirty) TAS_BUFFER_FNS(JBDDirty, jbddirty) BUFFER_FNS(Revoked, revoked) TAS_BUFFER_FNS(Revoked, revoked) BUFFER_FNS(RevokeValid, revokevalid) TAS_BUFFER_FNS(RevokeValid, revokevalid) BUFFER_FNS(Freed, freed) static inline struct buffer_head *jh2bh(struct journal_head *jh) { return jh->b_bh; } static inline struct journal_head *bh2jh(struct buffer_head *bh) { return bh->b_private; } static inline void jbd_lock_bh_state(struct buffer_head *bh) { bit_spin_lock(BH_State, &bh->b_state); } static inline int jbd_trylock_bh_state(struct buffer_head *bh) { return bit_spin_trylock(BH_State, &bh->b_state); } static inline int jbd_is_locked_bh_state(struct buffer_head *bh) { return bit_spin_is_locked(BH_State, &bh->b_state); } static inline void jbd_unlock_bh_state(struct buffer_head *bh) { bit_spin_unlock(BH_State, &bh->b_state); } static inline void jbd_lock_bh_journal_head(struct buffer_head *bh) { bit_spin_lock(BH_JournalHead, &bh->b_state); } static inline void jbd_unlock_bh_journal_head(struct buffer_head *bh) { bit_spin_unlock(BH_JournalHead, &bh->b_state); } struct jbd_revoke_table_s; /** * struct handle_s - this is the concrete type associated with handle_t. * @h_transaction: Which compound transaction is this update a part of? * @h_buffer_credits: Number of remaining buffers we are allowed to dirty. * @h_ref: Reference count on this handle * @h_err: Field for caller's use to track errors through large fs operations * @h_sync: flag for sync-on-close * @h_jdata: flag to force data journaling * @h_aborted: flag indicating fatal error on handle * @h_lockdep_map: lockdep info for debugging lock problems */ struct handle_s { /* Which compound transaction is this update a part of? */ transaction_t *h_transaction; /* Number of remaining buffers we are allowed to dirty: */ int h_buffer_credits; /* Reference count on this handle */ int h_ref; /* Field for caller's use to track errors through large fs */ /* operations */ int h_err; /* Flags [no locking] */ unsigned int h_sync: 1; /* sync-on-close */ unsigned int h_jdata: 1; /* force data journaling */ unsigned int h_aborted: 1; /* fatal error on handle */ #ifdef CONFIG_DEBUG_LOCK_ALLOC struct lockdep_map h_lockdep_map; #endif }; /* The transaction_t type is the guts of the journaling mechanism. It * tracks a compound transaction through its various states: * * RUNNING: accepting new updates * LOCKED: Updates still running but we don't accept new ones * RUNDOWN: Updates are tidying up but have finished requesting * new buffers to modify (state not used for now) * FLUSH: All updates complete, but we are still writing to disk * COMMIT: All data on disk, writing commit record * FINISHED: We still have to keep the transaction for checkpointing. * * The transaction keeps track of all of the buffers modified by a * running transaction, and all of the buffers committed but not yet * flushed to home for finished transactions. */ /* * Lock ranking: * * j_list_lock * ->jbd_lock_bh_journal_head() (This is "innermost") * * j_state_lock * ->jbd_lock_bh_state() * * jbd_lock_bh_state() * ->j_list_lock * * j_state_lock * ->t_handle_lock * * j_state_lock * ->j_list_lock (journal_unmap_buffer) * */ struct transaction_s { /* Pointer to the journal for this transaction. [no locking] */ journal_t *t_journal; /* Sequence number for this transaction [no locking] */ tid_t t_tid; /* * Transaction's current state * [no locking - only kjournald alters this] * [j_list_lock] guards transition of a transaction into T_FINISHED * state and subsequent call of __journal_drop_transaction() * FIXME: needs barriers * KLUDGE: [use j_state_lock] */ enum { T_RUNNING, T_LOCKED, T_RUNDOWN, T_FLUSH, T_COMMIT, T_FINISHED } t_state; /* * Where in the log does this transaction's commit start? [no locking] */ unsigned long t_log_start; /* Number of buffers on the t_buffers list [j_list_lock] */ int t_nr_buffers; /* * Doubly-linked circular list of all buffers reserved but not yet * modified by this transaction [j_list_lock] */ struct journal_head *t_reserved_list; /* * Doubly-linked circular list of all buffers under writeout during * commit [j_list_lock] */ struct journal_head *t_locked_list; /* * Doubly-linked circular list of all metadata buffers owned by this * transaction [j_list_lock] */ struct journal_head *t_buffers; /* * Doubly-linked circular list of all data buffers still to be * flushed before this transaction can be committed [j_list_lock] */ struct journal_head *t_sync_datalist; /* * Doubly-linked circular list of all forget buffers (superseded * buffers which we can un-checkpoint once this transaction commits) * [j_list_lock] */ struct journal_head *t_forget; /* * Doubly-linked circular list of all buffers still to be flushed before * this transaction can be checkpointed. [j_list_lock] */ struct journal_head *t_checkpoint_list; /* * Doubly-linked circular list of all buffers submitted for IO while * checkpointing. [j_list_lock] */ struct journal_head *t_checkpoint_io_list; /* * Doubly-linked circular list of temporary buffers currently undergoing * IO in the log [j_list_lock] */ struct journal_head *t_iobuf_list; /* * Doubly-linked circular list of metadata buffers being shadowed by log * IO. The IO buffers on the iobuf list and the shadow buffers on this * list match each other one for one at all times. [j_list_lock] */ struct journal_head *t_shadow_list; /* * Doubly-linked circular list of control buffers being written to the * log. [j_list_lock] */ struct journal_head *t_log_list; /* * Protects info related to handles */ spinlock_t t_handle_lock; /* * Number of outstanding updates running on this transaction * [t_handle_lock] */ int t_updates; /* * Number of buffers reserved for use by all handles in this transaction * handle but not yet modified. [t_handle_lock] */ int t_outstanding_credits; /* * Forward and backward links for the circular list of all transactions * awaiting checkpoint. [j_list_lock] */ transaction_t *t_cpnext, *t_cpprev; /* * When will the transaction expire (become due for commit), in jiffies? * [no locking] */ unsigned long t_expires; /* * How many handles used this transaction? [t_handle_lock] */ int t_handle_count; }; /** * struct journal_s - this is the concrete type associated with journal_t. * @j_flags: General journaling state flags * @j_errno: Is there an outstanding uncleared error on the journal (from a * prior abort)? * @j_sb_buffer: First part of superblock buffer * @j_superblock: Second part of superblock buffer * @j_format_version: Version of the superblock format * @j_state_lock: Protect the various scalars in the journal * @j_barrier_count: Number of processes waiting to create a barrier lock * @j_barrier: The barrier lock itself * @j_running_transaction: The current running transaction.. * @j_committing_transaction: the transaction we are pushing to disk * @j_checkpoint_transactions: a linked circular list of all transactions * waiting for checkpointing * @j_wait_transaction_locked: Wait queue for waiting for a locked transaction * to start committing, or for a barrier lock to be released * @j_wait_logspace: Wait queue for waiting for checkpointing to complete * @j_wait_done_commit: Wait queue for waiting for commit to complete * @j_wait_checkpoint: Wait queue to trigger checkpointing * @j_wait_commit: Wait queue to trigger commit * @j_wait_updates: Wait queue to wait for updates to complete * @j_checkpoint_mutex: Mutex for locking against concurrent checkpoints * @j_head: Journal head - identifies the first unused block in the journal * @j_tail: Journal tail - identifies the oldest still-used block in the * journal. * @j_free: Journal free - how many free blocks are there in the journal? * @j_first: The block number of the first usable block * @j_last: The block number one beyond the last usable block * @j_dev: Device where we store the journal * @j_blocksize: blocksize for the location where we store the journal. * @j_blk_offset: starting block offset for into the device where we store the * journal * @j_fs_dev: Device which holds the client fs. For internal journal this will * be equal to j_dev * @j_maxlen: Total maximum capacity of the journal region on disk. * @j_list_lock: Protects the buffer lists and internal buffer state. * @j_inode: Optional inode where we store the journal. If present, all journal * block numbers are mapped into this inode via bmap(). * @j_tail_sequence: Sequence number of the oldest transaction in the log * @j_transaction_sequence: Sequence number of the next transaction to grant * @j_commit_sequence: Sequence number of the most recently committed * transaction * @j_commit_request: Sequence number of the most recent transaction wanting * commit * @j_uuid: Uuid of client object. * @j_task: Pointer to the current commit thread for this journal * @j_max_transaction_buffers: Maximum number of metadata buffers to allow in a * single compound commit transaction * @j_commit_interval: What is the maximum transaction lifetime before we begin * a commit? * @j_commit_timer: The timer used to wakeup the commit thread * @j_revoke_lock: Protect the revoke table * @j_revoke: The revoke table - maintains the list of revoked blocks in the * current transaction. * @j_revoke_table: alternate revoke tables for j_revoke * @j_wbuf: array of buffer_heads for journal_commit_transaction * @j_wbufsize: maximum number of buffer_heads allowed in j_wbuf, the * number that will fit in j_blocksize * @j_last_sync_writer: most recent pid which did a synchronous write * @j_private: An opaque pointer to fs-private information. */ struct journal_s { /* General journaling state flags [j_state_lock] */ unsigned long j_flags; /* * Is there an outstanding uncleared error on the journal (from a prior * abort)? [j_state_lock] */ int j_errno; /* The superblock buffer */ struct buffer_head *j_sb_buffer; journal_superblock_t *j_superblock; /* Version of the superblock format */ int j_format_version; /* * Protect the various scalars in the journal */ spinlock_t j_state_lock; /* * Number of processes waiting to create a barrier lock [j_state_lock] */ int j_barrier_count; /* The barrier lock itself */ struct mutex j_barrier; /* * Transactions: The current running transaction... * [j_state_lock] [caller holding open handle] */ transaction_t *j_running_transaction; /* * the transaction we are pushing to disk * [j_state_lock] [caller holding open handle] */ transaction_t *j_committing_transaction; /* * ... and a linked circular list of all transactions waiting for * checkpointing. [j_list_lock] */ transaction_t *j_checkpoint_transactions; /* * Wait queue for waiting for a locked transaction to start committing, * or for a barrier lock to be released */ wait_queue_head_t j_wait_transaction_locked; /* Wait queue for waiting for checkpointing to complete */ wait_queue_head_t j_wait_logspace; /* Wait queue for waiting for commit to complete */ wait_queue_head_t j_wait_done_commit; /* Wait queue to trigger checkpointing */ wait_queue_head_t j_wait_checkpoint; /* Wait queue to trigger commit */ wait_queue_head_t j_wait_commit; /* Wait queue to wait for updates to complete */ wait_queue_head_t j_wait_updates; /* Semaphore for locking against concurrent checkpoints */ struct mutex j_checkpoint_mutex; /* * Journal head: identifies the first unused block in the journal. * [j_state_lock] */ unsigned long j_head; /* * Journal tail: identifies the oldest still-used block in the journal. * [j_state_lock] */ unsigned long j_tail; /* * Journal free: how many free blocks are there in the journal? * [j_state_lock] */ unsigned long j_free; /* * Journal start and end: the block numbers of the first usable block * and one beyond the last usable block in the journal. [j_state_lock] */ unsigned long j_first; unsigned long j_last; /* * Device, blocksize and starting block offset for the location where we * store the journal. */ struct block_device *j_dev; int j_blocksize; unsigned long j_blk_offset; /* * Device which holds the client fs. For internal journal this will be * equal to j_dev. */ struct block_device *j_fs_dev; /* Total maximum capacity of the journal region on disk. */ unsigned int j_maxlen; /* * Protects the buffer lists and internal buffer state. */ spinlock_t j_list_lock; /* Optional inode where we store the journal. If present, all */ /* journal block numbers are mapped into this inode via */ /* bmap(). */ struct inode *j_inode; /* * Sequence number of the oldest transaction in the log [j_state_lock] */ tid_t j_tail_sequence; /* * Sequence number of the next transaction to grant [j_state_lock] */ tid_t j_transaction_sequence; /* * Sequence number of the most recently committed transaction * [j_state_lock]. */ tid_t j_commit_sequence; /* * Sequence number of the most recent transaction wanting commit * [j_state_lock] */ tid_t j_commit_request; /* * Journal uuid: identifies the object (filesystem, LVM volume etc) * backed by this journal. This will eventually be replaced by an array * of uuids, allowing us to index multiple devices within a single * journal and to perform atomic updates across them. */ __u8 j_uuid[16]; /* Pointer to the current commit thread for this journal */ struct task_struct *j_task; /* * Maximum number of metadata buffers to allow in a single compound * commit transaction */ int j_max_transaction_buffers; /* * What is the maximum transaction lifetime before we begin a commit? */ unsigned long j_commit_interval; /* The timer used to wakeup the commit thread: */ struct timer_list j_commit_timer; /* * The revoke table: maintains the list of revoked blocks in the * current transaction. [j_revoke_lock] */ spinlock_t j_revoke_lock; struct jbd_revoke_table_s *j_revoke; struct jbd_revoke_table_s *j_revoke_table[2]; /* * array of bhs for journal_commit_transaction */ struct buffer_head **j_wbuf; int j_wbufsize; pid_t j_last_sync_writer; /* * An opaque pointer to fs-private information. ext3 puts its * superblock pointer here */ void *j_private; }; /* * Journal flag definitions */ #define JFS_UNMOUNT 0x001 /* Journal thread is being destroyed */ #define JFS_ABORT 0x002 /* Journaling has been aborted for errors. */ #define JFS_ACK_ERR 0x004 /* The errno in the sb has been acked */ #define JFS_FLUSHED 0x008 /* The journal superblock has been flushed */ #define JFS_LOADED 0x010 /* The journal superblock has been loaded */ #define JFS_BARRIER 0x020 /* Use IDE barriers */ /* * Function declarations for the journaling transaction and buffer * management */ /* Filing buffers */ extern void journal_unfile_buffer(journal_t *, struct journal_head *); extern void __journal_unfile_buffer(struct journal_head *); extern void __journal_refile_buffer(struct journal_head *); extern void journal_refile_buffer(journal_t *, struct journal_head *); extern void __journal_file_buffer(struct journal_head *, transaction_t *, int); extern void __journal_free_buffer(struct journal_head *bh); extern void journal_file_buffer(struct journal_head *, transaction_t *, int); extern v