Path: blob/master/Documentation/cgroups/cgroups.txt
10821 views
CGROUPS1-------23Written by Paul Menage <[email protected]> based on4Documentation/cgroups/cpusets.txt56Original copyright statements from cpusets.txt:7Portions Copyright (C) 2004 BULL SA.8Portions Copyright (c) 2004-2006 Silicon Graphics, Inc.9Modified by Paul Jackson <[email protected]>10Modified by Christoph Lameter <[email protected]>1112CONTENTS:13=========14151. Control Groups161.1 What are cgroups ?171.2 Why are cgroups needed ?181.3 How are cgroups implemented ?191.4 What does notify_on_release do ?201.5 What does clone_children do ?211.6 How do I use cgroups ?222. Usage Examples and Syntax232.1 Basic Usage242.2 Attaching processes252.3 Mounting hierarchies by name262.4 Notification API273. Kernel API283.1 Overview293.2 Synchronization303.3 Subsystem API314. Questions32331. Control Groups34=================35361.1 What are cgroups ?37----------------------3839Control Groups provide a mechanism for aggregating/partitioning sets of40tasks, and all their future children, into hierarchical groups with41specialized behaviour.4243Definitions:4445A *cgroup* associates a set of tasks with a set of parameters for one46or more subsystems.4748A *subsystem* is a module that makes use of the task grouping49facilities provided by cgroups to treat groups of tasks in50particular ways. A subsystem is typically a "resource controller" that51schedules a resource or applies per-cgroup limits, but it may be52anything that wants to act on a group of processes, e.g. a53virtualization subsystem.5455A *hierarchy* is a set of cgroups arranged in a tree, such that56every task in the system is in exactly one of the cgroups in the57hierarchy, and a set of subsystems; each subsystem has system-specific58state attached to each cgroup in the hierarchy. Each hierarchy has59an instance of the cgroup virtual filesystem associated with it.6061At any one time there may be multiple active hierarchies of task62cgroups. Each hierarchy is a partition of all tasks in the system.6364User level code may create and destroy cgroups by name in an65instance of the cgroup virtual file system, specify and query to66which cgroup a task is assigned, and list the task pids assigned to67a cgroup. Those creations and assignments only affect the hierarchy68associated with that instance of the cgroup file system.6970On their own, the only use for cgroups is for simple job71tracking. The intention is that other subsystems hook into the generic72cgroup support to provide new attributes for cgroups, such as73accounting/limiting the resources which processes in a cgroup can74access. For example, cpusets (see Documentation/cgroups/cpusets.txt) allows75you to associate a set of CPUs and a set of memory nodes with the76tasks in each cgroup.77781.2 Why are cgroups needed ?79----------------------------8081There are multiple efforts to provide process aggregations in the82Linux kernel, mainly for resource tracking purposes. Such efforts83include cpusets, CKRM/ResGroups, UserBeanCounters, and virtual server84namespaces. These all require the basic notion of a85grouping/partitioning of processes, with newly forked processes ending86in the same group (cgroup) as their parent process.8788The kernel cgroup patch provides the minimum essential kernel89mechanisms required to efficiently implement such groups. It has90minimal impact on the system fast paths, and provides hooks for91specific subsystems such as cpusets to provide additional behaviour as92desired.9394Multiple hierarchy support is provided to allow for situations where95the division of tasks into cgroups is distinctly different for96different subsystems - having parallel hierarchies allows each97hierarchy to be a natural division of tasks, without having to handle98complex combinations of tasks that would be present if several99unrelated subsystems needed to be forced into the same tree of100cgroups.101102At one extreme, each resource controller or subsystem could be in a103separate hierarchy; at the other extreme, all subsystems104would be attached to the same hierarchy.105106As an example of a scenario (originally proposed by [email protected])107that can benefit from multiple hierarchies, consider a large108university server with various users - students, professors, system109tasks etc. The resource planning for this server could be along the110following lines:111112CPU : "Top cpuset"113/ \114CPUSet1 CPUSet2115| |116(Professors) (Students)117118In addition (system tasks) are attached to topcpuset (so119that they can run anywhere) with a limit of 20%120121Memory : Professors (50%), Students (30%), system (20%)122123Disk : Professors (50%), Students (30%), system (20%)124125Network : WWW browsing (20%), Network File System (60%), others (20%)126/ \127Professors (15%) students (5%)128129Browsers like Firefox/Lynx go into the WWW network class, while (k)nfsd go130into NFS network class.131132At the same time Firefox/Lynx will share an appropriate CPU/Memory class133depending on who launched it (prof/student).134135With the ability to classify tasks differently for different resources136(by putting those resource subsystems in different hierarchies) then137the admin can easily set up a script which receives exec notifications138and depending on who is launching the browser he can139140# echo browser_pid > /sys/fs/cgroup/<restype>/<userclass>/tasks141142With only a single hierarchy, he now would potentially have to create143a separate cgroup for every browser launched and associate it with144appropriate network and other resource class. This may lead to145proliferation of such cgroups.146147Also lets say that the administrator would like to give enhanced network148access temporarily to a student's browser (since it is night and the user149wants to do online gaming :)) OR give one of the students simulation150apps enhanced CPU power,151152With ability to write pids directly to resource classes, it's just a153matter of :154155# echo pid > /sys/fs/cgroup/network/<new_class>/tasks156(after some time)157# echo pid > /sys/fs/cgroup/network/<orig_class>/tasks158159Without this ability, he would have to split the cgroup into160multiple separate ones and then associate the new cgroups with the161new resource classes.1621631641651.3 How are cgroups implemented ?166---------------------------------167168Control Groups extends the kernel as follows:169170- Each task in the system has a reference-counted pointer to a171css_set.172173- A css_set contains a set of reference-counted pointers to174cgroup_subsys_state objects, one for each cgroup subsystem175registered in the system. There is no direct link from a task to176the cgroup of which it's a member in each hierarchy, but this177can be determined by following pointers through the178cgroup_subsys_state objects. This is because accessing the179subsystem state is something that's expected to happen frequently180and in performance-critical code, whereas operations that require a181task's actual cgroup assignments (in particular, moving between182cgroups) are less common. A linked list runs through the cg_list183field of each task_struct using the css_set, anchored at184css_set->tasks.185186- A cgroup hierarchy filesystem can be mounted for browsing and187manipulation from user space.188189- You can list all the tasks (by pid) attached to any cgroup.190191The implementation of cgroups requires a few, simple hooks192into the rest of the kernel, none in performance critical paths:193194- in init/main.c, to initialize the root cgroups and initial195css_set at system boot.196197- in fork and exit, to attach and detach a task from its css_set.198199In addition a new file system, of type "cgroup" may be mounted, to200enable browsing and modifying the cgroups presently known to the201kernel. When mounting a cgroup hierarchy, you may specify a202comma-separated list of subsystems to mount as the filesystem mount203options. By default, mounting the cgroup filesystem attempts to204mount a hierarchy containing all registered subsystems.205206If an active hierarchy with exactly the same set of subsystems already207exists, it will be reused for the new mount. If no existing hierarchy208matches, and any of the requested subsystems are in use in an existing209hierarchy, the mount will fail with -EBUSY. Otherwise, a new hierarchy210is activated, associated with the requested subsystems.211212It's not currently possible to bind a new subsystem to an active213cgroup hierarchy, or to unbind a subsystem from an active cgroup214hierarchy. This may be possible in future, but is fraught with nasty215error-recovery issues.216217When a cgroup filesystem is unmounted, if there are any218child cgroups created below the top-level cgroup, that hierarchy219will remain active even though unmounted; if there are no220child cgroups then the hierarchy will be deactivated.221222No new system calls are added for cgroups - all support for223querying and modifying cgroups is via this cgroup file system.224225Each task under /proc has an added file named 'cgroup' displaying,226for each active hierarchy, the subsystem names and the cgroup name227as the path relative to the root of the cgroup file system.228229Each cgroup is represented by a directory in the cgroup file system230containing the following files describing that cgroup:231232- tasks: list of tasks (by pid) attached to that cgroup. This list233is not guaranteed to be sorted. Writing a thread id into this file234moves the thread into this cgroup.235- cgroup.procs: list of tgids in the cgroup. This list is not236guaranteed to be sorted or free of duplicate tgids, and userspace237should sort/uniquify the list if this property is required.238Writing a thread group id into this file moves all threads in that239group into this cgroup.240- notify_on_release flag: run the release agent on exit?241- release_agent: the path to use for release notifications (this file242exists in the top cgroup only)243244Other subsystems such as cpusets may add additional files in each245cgroup dir.246247New cgroups are created using the mkdir system call or shell248command. The properties of a cgroup, such as its flags, are249modified by writing to the appropriate file in that cgroups250directory, as listed above.251252The named hierarchical structure of nested cgroups allows partitioning253a large system into nested, dynamically changeable, "soft-partitions".254255The attachment of each task, automatically inherited at fork by any256children of that task, to a cgroup allows organizing the work load257on a system into related sets of tasks. A task may be re-attached to258any other cgroup, if allowed by the permissions on the necessary259cgroup file system directories.260261When a task is moved from one cgroup to another, it gets a new262css_set pointer - if there's an already existing css_set with the263desired collection of cgroups then that group is reused, else a new264css_set is allocated. The appropriate existing css_set is located by265looking into a hash table.266267To allow access from a cgroup to the css_sets (and hence tasks)268that comprise it, a set of cg_cgroup_link objects form a lattice;269each cg_cgroup_link is linked into a list of cg_cgroup_links for270a single cgroup on its cgrp_link_list field, and a list of271cg_cgroup_links for a single css_set on its cg_link_list.272273Thus the set of tasks in a cgroup can be listed by iterating over274each css_set that references the cgroup, and sub-iterating over275each css_set's task set.276277The use of a Linux virtual file system (vfs) to represent the278cgroup hierarchy provides for a familiar permission and name space279for cgroups, with a minimum of additional kernel code.2802811.4 What does notify_on_release do ?282------------------------------------283284If the notify_on_release flag is enabled (1) in a cgroup, then285whenever the last task in the cgroup leaves (exits or attaches to286some other cgroup) and the last child cgroup of that cgroup287is removed, then the kernel runs the command specified by the contents288of the "release_agent" file in that hierarchy's root directory,289supplying the pathname (relative to the mount point of the cgroup290file system) of the abandoned cgroup. This enables automatic291removal of abandoned cgroups. The default value of292notify_on_release in the root cgroup at system boot is disabled293(0). The default value of other cgroups at creation is the current294value of their parents notify_on_release setting. The default value of295a cgroup hierarchy's release_agent path is empty.2962971.5 What does clone_children do ?298---------------------------------299300If the clone_children flag is enabled (1) in a cgroup, then all301cgroups created beneath will call the post_clone callbacks for each302subsystem of the newly created cgroup. Usually when this callback is303implemented for a subsystem, it copies the values of the parent304subsystem, this is the case for the cpuset.3053061.6 How do I use cgroups ?307--------------------------308309To start a new job that is to be contained within a cgroup, using310the "cpuset" cgroup subsystem, the steps are something like:3113121) mount -t tmpfs cgroup_root /sys/fs/cgroup3132) mkdir /sys/fs/cgroup/cpuset3143) mount -t cgroup -ocpuset cpuset /sys/fs/cgroup/cpuset3154) Create the new cgroup by doing mkdir's and write's (or echo's) in316the /sys/fs/cgroup virtual file system.3175) Start a task that will be the "founding father" of the new job.3186) Attach that task to the new cgroup by writing its pid to the319/sys/fs/cgroup/cpuset/tasks file for that cgroup.3207) fork, exec or clone the job tasks from this founding father task.321322For example, the following sequence of commands will setup a cgroup323named "Charlie", containing just CPUs 2 and 3, and Memory Node 1,324and then start a subshell 'sh' in that cgroup:325326mount -t tmpfs cgroup_root /sys/fs/cgroup327mkdir /sys/fs/cgroup/cpuset328mount -t cgroup cpuset -ocpuset /sys/fs/cgroup/cpuset329cd /sys/fs/cgroup/cpuset330mkdir Charlie331cd Charlie332/bin/echo 2-3 > cpuset.cpus333/bin/echo 1 > cpuset.mems334/bin/echo $$ > tasks335sh336# The subshell 'sh' is now running in cgroup Charlie337# The next line should display '/Charlie'338cat /proc/self/cgroup3393402. Usage Examples and Syntax341============================3423432.1 Basic Usage344---------------345346Creating, modifying, using the cgroups can be done through the cgroup347virtual filesystem.348349To mount a cgroup hierarchy with all available subsystems, type:350# mount -t cgroup xxx /sys/fs/cgroup351352The "xxx" is not interpreted by the cgroup code, but will appear in353/proc/mounts so may be any useful identifying string that you like.354355Note: Some subsystems do not work without some user input first. For instance,356if cpusets are enabled the user will have to populate the cpus and mems files357for each new cgroup created before that group can be used.358359As explained in section `1.2 Why are cgroups needed?' you should create360different hierarchies of cgroups for each single resource or group of361resources you want to control. Therefore, you should mount a tmpfs on362/sys/fs/cgroup and create directories for each cgroup resource or resource363group.364365# mount -t tmpfs cgroup_root /sys/fs/cgroup366# mkdir /sys/fs/cgroup/rg1367368To mount a cgroup hierarchy with just the cpuset and memory369subsystems, type:370# mount -t cgroup -o cpuset,memory hier1 /sys/fs/cgroup/rg1371372To change the set of subsystems bound to a mounted hierarchy, just373remount with different options:374# mount -o remount,cpuset,blkio hier1 /sys/fs/cgroup/rg1375376Now memory is removed from the hierarchy and blkio is added.377378Note this will add blkio to the hierarchy but won't remove memory or379cpuset, because the new options are appended to the old ones:380# mount -o remount,blkio /sys/fs/cgroup/rg1381382To Specify a hierarchy's release_agent:383# mount -t cgroup -o cpuset,release_agent="/sbin/cpuset_release_agent" \384xxx /sys/fs/cgroup/rg1385386Note that specifying 'release_agent' more than once will return failure.387388Note that changing the set of subsystems is currently only supported389when the hierarchy consists of a single (root) cgroup. Supporting390the ability to arbitrarily bind/unbind subsystems from an existing391cgroup hierarchy is intended to be implemented in the future.392393Then under /sys/fs/cgroup/rg1 you can find a tree that corresponds to the394tree of the cgroups in the system. For instance, /sys/fs/cgroup/rg1395is the cgroup that holds the whole system.396397If you want to change the value of release_agent:398# echo "/sbin/new_release_agent" > /sys/fs/cgroup/rg1/release_agent399400It can also be changed via remount.401402If you want to create a new cgroup under /sys/fs/cgroup/rg1:403# cd /sys/fs/cgroup/rg1404# mkdir my_cgroup405406Now you want to do something with this cgroup.407# cd my_cgroup408409In this directory you can find several files:410# ls411cgroup.procs notify_on_release tasks412(plus whatever files added by the attached subsystems)413414Now attach your shell to this cgroup:415# /bin/echo $$ > tasks416417You can also create cgroups inside your cgroup by using mkdir in this418directory.419# mkdir my_sub_cs420421To remove a cgroup, just use rmdir:422# rmdir my_sub_cs423424This will fail if the cgroup is in use (has cgroups inside, or425has processes attached, or is held alive by other subsystem-specific426reference).4274282.2 Attaching processes429-----------------------430431# /bin/echo PID > tasks432433Note that it is PID, not PIDs. You can only attach ONE task at a time.434If you have several tasks to attach, you have to do it one after another:435436# /bin/echo PID1 > tasks437# /bin/echo PID2 > tasks438...439# /bin/echo PIDn > tasks440441You can attach the current shell task by echoing 0:442443# echo 0 > tasks444445You can use the cgroup.procs file instead of the tasks file to move all446threads in a threadgroup at once. Echoing the pid of any task in a447threadgroup to cgroup.procs causes all tasks in that threadgroup to be448be attached to the cgroup. Writing 0 to cgroup.procs moves all tasks449in the writing task's threadgroup.450451Note: Since every task is always a member of exactly one cgroup in each452mounted hierarchy, to remove a task from its current cgroup you must453move it into a new cgroup (possibly the root cgroup) by writing to the454new cgroup's tasks file.455456Note: If the ns cgroup is active, moving a process to another cgroup can457fail.4584592.3 Mounting hierarchies by name460--------------------------------461462Passing the name=<x> option when mounting a cgroups hierarchy463associates the given name with the hierarchy. This can be used when464mounting a pre-existing hierarchy, in order to refer to it by name465rather than by its set of active subsystems. Each hierarchy is either466nameless, or has a unique name.467468The name should match [\w.-]+469470When passing a name=<x> option for a new hierarchy, you need to471specify subsystems manually; the legacy behaviour of mounting all472subsystems when none are explicitly specified is not supported when473you give a subsystem a name.474475The name of the subsystem appears as part of the hierarchy description476in /proc/mounts and /proc/<pid>/cgroups.4774782.4 Notification API479--------------------480481There is mechanism which allows to get notifications about changing482status of a cgroup.483484To register new notification handler you need:485- create a file descriptor for event notification using eventfd(2);486- open a control file to be monitored (e.g. memory.usage_in_bytes);487- write "<event_fd> <control_fd> <args>" to cgroup.event_control.488Interpretation of args is defined by control file implementation;489490eventfd will be woken up by control file implementation or when the491cgroup is removed.492493To unregister notification handler just close eventfd.494495NOTE: Support of notifications should be implemented for the control496file. See documentation for the subsystem.4974983. Kernel API499=============5005013.1 Overview502------------503504Each kernel subsystem that wants to hook into the generic cgroup505system needs to create a cgroup_subsys object. This contains506various methods, which are callbacks from the cgroup system, along507with a subsystem id which will be assigned by the cgroup system.508509Other fields in the cgroup_subsys object include:510511- subsys_id: a unique array index for the subsystem, indicating which512entry in cgroup->subsys[] this subsystem should be managing.513514- name: should be initialized to a unique subsystem name. Should be515no longer than MAX_CGROUP_TYPE_NAMELEN.516517- early_init: indicate if the subsystem needs early initialization518at system boot.519520Each cgroup object created by the system has an array of pointers,521indexed by subsystem id; this pointer is entirely managed by the522subsystem; the generic cgroup code will never touch this pointer.5235243.2 Synchronization525-------------------526527There is a global mutex, cgroup_mutex, used by the cgroup528system. This should be taken by anything that wants to modify a529cgroup. It may also be taken to prevent cgroups from being530modified, but more specific locks may be more appropriate in that531situation.532533See kernel/cgroup.c for more details.534535Subsystems can take/release the cgroup_mutex via the functions536cgroup_lock()/cgroup_unlock().537538Accessing a task's cgroup pointer may be done in the following ways:539- while holding cgroup_mutex540- while holding the task's alloc_lock (via task_lock())541- inside an rcu_read_lock() section via rcu_dereference()5425433.3 Subsystem API544-----------------545546Each subsystem should:547548- add an entry in linux/cgroup_subsys.h549- define a cgroup_subsys object called <name>_subsys550551If a subsystem can be compiled as a module, it should also have in its552module initcall a call to cgroup_load_subsys(), and in its exitcall a553call to cgroup_unload_subsys(). It should also set its_subsys.module =554THIS_MODULE in its .c file.555556Each subsystem may export the following methods. The only mandatory557methods are create/destroy. Any others that are null are presumed to558be successful no-ops.559560struct cgroup_subsys_state *create(struct cgroup_subsys *ss,561struct cgroup *cgrp)562(cgroup_mutex held by caller)563564Called to create a subsystem state object for a cgroup. The565subsystem should allocate its subsystem state object for the passed566cgroup, returning a pointer to the new object on success or a567negative error code. On success, the subsystem pointer should point to568a structure of type cgroup_subsys_state (typically embedded in a569larger subsystem-specific object), which will be initialized by the570cgroup system. Note that this will be called at initialization to571create the root subsystem state for this subsystem; this case can be572identified by the passed cgroup object having a NULL parent (since573it's the root of the hierarchy) and may be an appropriate place for574initialization code.575576void destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)577(cgroup_mutex held by caller)578579The cgroup system is about to destroy the passed cgroup; the subsystem580should do any necessary cleanup and free its subsystem state581object. By the time this method is called, the cgroup has already been582unlinked from the file system and from the child list of its parent;583cgroup->parent is still valid. (Note - can also be called for a584newly-created cgroup if an error occurs after this subsystem's585create() method has been called for the new cgroup).586587int pre_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp);588589Called before checking the reference count on each subsystem. This may590be useful for subsystems which have some extra references even if591there are not tasks in the cgroup. If pre_destroy() returns error code,592rmdir() will fail with it. From this behavior, pre_destroy() can be593called multiple times against a cgroup.594595int can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,596struct task_struct *task)597(cgroup_mutex held by caller)598599Called prior to moving a task into a cgroup; if the subsystem600returns an error, this will abort the attach operation. If a NULL601task is passed, then a successful result indicates that *any*602unspecified task can be moved into the cgroup. Note that this isn't603called on a fork. If this method returns 0 (success) then this should604remain valid while the caller holds cgroup_mutex and it is ensured that either605attach() or cancel_attach() will be called in future.606607int can_attach_task(struct cgroup *cgrp, struct task_struct *tsk);608(cgroup_mutex held by caller)609610As can_attach, but for operations that must be run once per task to be611attached (possibly many when using cgroup_attach_proc). Called after612can_attach.613614void cancel_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,615struct task_struct *task, bool threadgroup)616(cgroup_mutex held by caller)617618Called when a task attach operation has failed after can_attach() has succeeded.619A subsystem whose can_attach() has some side-effects should provide this620function, so that the subsystem can implement a rollback. If not, not necessary.621This will be called only about subsystems whose can_attach() operation have622succeeded.623624void pre_attach(struct cgroup *cgrp);625(cgroup_mutex held by caller)626627For any non-per-thread attachment work that needs to happen before628attach_task. Needed by cpuset.629630void attach(struct cgroup_subsys *ss, struct cgroup *cgrp,631struct cgroup *old_cgrp, struct task_struct *task)632(cgroup_mutex held by caller)633634Called after the task has been attached to the cgroup, to allow any635post-attachment activity that requires memory allocations or blocking.636637void attach_task(struct cgroup *cgrp, struct task_struct *tsk);638(cgroup_mutex held by caller)639640As attach, but for operations that must be run once per task to be attached,641like can_attach_task. Called before attach. Currently does not support any642subsystem that might need the old_cgrp for every thread in the group.643644void fork(struct cgroup_subsy *ss, struct task_struct *task)645646Called when a task is forked into a cgroup.647648void exit(struct cgroup_subsys *ss, struct task_struct *task)649650Called during task exit.651652int populate(struct cgroup_subsys *ss, struct cgroup *cgrp)653(cgroup_mutex held by caller)654655Called after creation of a cgroup to allow a subsystem to populate656the cgroup directory with file entries. The subsystem should make657calls to cgroup_add_file() with objects of type cftype (see658include/linux/cgroup.h for details). Note that although this659method can return an error code, the error code is currently not660always handled well.661662void post_clone(struct cgroup_subsys *ss, struct cgroup *cgrp)663(cgroup_mutex held by caller)664665Called during cgroup_create() to do any parameter666initialization which might be required before a task could attach. For667example in cpusets, no task may attach before 'cpus' and 'mems' are set668up.669670void bind(struct cgroup_subsys *ss, struct cgroup *root)671(cgroup_mutex and ss->hierarchy_mutex held by caller)672673Called when a cgroup subsystem is rebound to a different hierarchy674and root cgroup. Currently this will only involve movement between675the default hierarchy (which never has sub-cgroups) and a hierarchy676that is being created/destroyed (and hence has no sub-cgroups).6776784. Questions679============680681Q: what's up with this '/bin/echo' ?682A: bash's builtin 'echo' command does not check calls to write() against683errors. If you use it in the cgroup file system, you won't be684able to tell whether a command succeeded or failed.685686Q: When I attach processes, only the first of the line gets really attached !687A: We can only return one error code per call to write(). So you should also688put only ONE pid.689690691692