1                                CGROUPS
   2                                -------
   4Written by Paul Menage <> based on
   7Original copyright statements from cpusets.txt:
   8Portions Copyright (C) 2004 BULL SA.
   9Portions Copyright (c) 2004-2006 Silicon Graphics, Inc.
  10Modified by Paul Jackson <>
  11Modified by Christoph Lameter <>
  161. Control Groups
  17  1.1 What are cgroups ?
  18  1.2 Why are cgroups needed ?
  19  1.3 How are cgroups implemented ?
  20  1.4 What does notify_on_release do ?
  21  1.5 How do I use cgroups ?
  222. Usage Examples and Syntax
  23  2.1 Basic Usage
  24  2.2 Attaching processes
  253. Kernel API
  26  3.1 Overview
  27  3.2 Synchronization
  28  3.3 Subsystem API
  294. Questions
  311. Control Groups
  341.1 What are cgroups ?
  37Control Groups provide a mechanism for aggregating/partitioning sets of
  38tasks, and all their future children, into hierarchical groups with
  39specialized behaviour.
  43A *cgroup* associates a set of tasks with a set of parameters for one
  44or more subsystems.
  46A *subsystem* is a module that makes use of the task grouping
  47facilities provided by cgroups to treat groups of tasks in
  48particular ways. A subsystem is typically a "resource controller" that
  49schedules a resource or applies per-cgroup limits, but it may be
  50anything that wants to act on a group of processes, e.g. a
  51virtualization subsystem.
  53A *hierarchy* is a set of cgroups arranged in a tree, such that
  54every task in the system is in exactly one of the cgroups in the
  55hierarchy, and a set of subsystems; each subsystem has system-specific
  56state attached to each cgroup in the hierarchy.  Each hierarchy has
  57an instance of the cgroup virtual filesystem associated with it.
  59At any one time there may be multiple active hierachies of task
  60cgroups. Each hierarchy is a partition of all tasks in the system.
  62User level code may create and destroy cgroups by name in an
  63instance of the cgroup virtual file system, specify and query to
  64which cgroup a task is assigned, and list the task pids assigned to
  65a cgroup. Those creations and assignments only affect the hierarchy
  66associated with that instance of the cgroup file system.
  68On their own, the only use for cgroups is for simple job
  69tracking. The intention is that other subsystems hook into the generic
  70cgroup support to provide new attributes for cgroups, such as
  71accounting/limiting the resources which processes in a cgroup can
  72access. For example, cpusets (see Documentation/cgroups/cpusets.txt) allows
  73you to associate a set of CPUs and a set of memory nodes with the
  74tasks in each cgroup.
  761.2 Why are cgroups needed ?
  79There are multiple efforts to provide process aggregations in the
  80Linux kernel, mainly for resource tracking purposes. Such efforts
  81include cpusets, CKRM/ResGroups, UserBeanCounters, and virtual server
  82namespaces. These all require the basic notion of a
  83grouping/partitioning of processes, with newly forked processes ending
  84in the same group (cgroup) as their parent process.
  86The kernel cgroup patch provides the minimum essential kernel
  87mechanisms required to efficiently implement such groups. It has
  88minimal impact on the system fast paths, and provides hooks for
  89specific subsystems such as cpusets to provide additional behaviour as
  92Multiple hierarchy support is provided to allow for situations where
  93the division of tasks into cgroups is distinctly different for
  94different subsystems - having parallel hierarchies allows each
  95hierarchy to be a natural division of tasks, without having to handle
  96complex combinations of tasks that would be present if several
  97unrelated subsystems needed to be forced into the same tree of
 100At one extreme, each resource controller or subsystem could be in a
 101separate hierarchy; at the other extreme, all subsystems
 102would be attached to the same hierarchy.
 104As an example of a scenario (originally proposed by
 105that can benefit from multiple hierarchies, consider a large
 106university server with various users - students, professors, system
 107tasks etc. The resource planning for this server could be along the
 108following lines:
 110       CPU :           Top cpuset
 111                       /       \
 112               CPUSet1         CPUSet2
 113                  |              |
 114               (Profs)         (Students)
 116               In addition (system tasks) are attached to topcpuset (so
 117               that they can run anywhere) with a limit of 20%
 119       Memory : Professors (50%), students (30%), system (20%)
 121       Disk : Prof (50%), students (30%), system (20%)
 123       Network : WWW browsing (20%), Network File System (60%), others (20%)
 124                               / \
 125                       Prof (15%) students (5%)
 127Browsers like firefox/lynx go into the WWW network class, while (k)nfsd go
 128into NFS network class.
 130At the same time firefox/lynx will share an appropriate CPU/Memory class
 131depending on who launched it (prof/student).
 133With the ability to classify tasks differently for different resources
 134(by putting those resource subsystems in different hierarchies) then
 135the admin can easily set up a script which receives exec notifications
 136and depending on who is launching the browser he can
 138       # echo browser_pid > /mnt/<restype>/<userclass>/tasks
 140With only a single hierarchy, he now would potentially have to create
 141a separate cgroup for every browser launched and associate it with
 142approp network and other resource class.  This may lead to
 143proliferation of such cgroups.
 145Also lets say that the administrator would like to give enhanced network
 146access temporarily to a student's browser (since it is night and the user
 147wants to do online gaming :))  OR give one of the students simulation
 148apps enhanced CPU power,
 150With ability to write pids directly to resource classes, it's just a
 151matter of :
 153       # echo pid > /mnt/network/<new_class>/tasks
 154       (after some time)
 155       # echo pid > /mnt/network/<orig_class>/tasks
 157Without this ability, he would have to split the cgroup into
 158multiple separate ones and then associate the new cgroups with the
 159new resource classes.
 1631.3 How are cgroups implemented ?
 166Control Groups extends the kernel as follows:
 168 - Each task in the system has a reference-counted pointer to a
 169   css_set.
 171 - A css_set contains a set of reference-counted pointers to
 172   cgroup_subsys_state objects, one for each cgroup subsystem
 173   registered in the system. There is no direct link from a task to
 174   the cgroup of which it's a member in each hierarchy, but this
 175   can be determined by following pointers through the
 176   cgroup_subsys_state objects. This is because accessing the
 177   subsystem state is something that's expected to happen frequently
 178   and in performance-critical code, whereas operations that require a
 179   task's actual cgroup assignments (in particular, moving between
 180   cgroups) are less common. A linked list runs through the cg_list
 181   field of each task_struct using the css_set, anchored at
 182   css_set->tasks.
 184 - A cgroup hierarchy filesystem can be mounted  for browsing and
 185   manipulation from user space.
 187 - You can list all the tasks (by pid) attached to any cgroup.
 189The implementation of cgroups requires a few, simple hooks
 190into the rest of the kernel, none in performance critical paths:
 192 - in init/main.c, to initialize the root cgroups and initial
 193   css_set at system boot.
 195 - in fork and exit, to attach and detach a task from its css_set.
 197In addition a new file system, of type "cgroup" may be mounted, to
 198enable browsing and modifying the cgroups presently known to the
 199kernel.  When mounting a cgroup hierarchy, you may specify a
 200comma-separated list of subsystems to mount as the filesystem mount
 201options.  By default, mounting the cgroup filesystem attempts to
 202mount a hierarchy containing all registered subsystems.
 204If an active hierarchy with exactly the same set of subsystems already
 205exists, it will be reused for the new mount. If no existing hierarchy
 206matches, and any of the requested subsystems are in use in an existing
 207hierarchy, the mount will fail with -EBUSY. Otherwise, a new hierarchy
 208is activated, associated with the requested subsystems.
 210It's not currently possible to bind a new subsystem to an active
 211cgroup hierarchy, or to unbind a subsystem from an active cgroup
 212hierarchy. This may be possible in future, but is fraught with nasty
 213error-recovery issues.
 215When a cgroup filesystem is unmounted, if there are any
 216child cgroups created below the top-level cgroup, that hierarchy
 217will remain active even though unmounted; if there are no
 218child cgroups then the hierarchy will be deactivated.
 220No new system calls are added for cgroups - all support for
 221querying and modifying cgroups is via this cgroup file system.
 223Each task under /proc has an added file named 'cgroup' displaying,
 224for each active hierarchy, the subsystem names and the cgroup name
 225as the path relative to the root of the cgroup file system.
 227Each cgroup is represented by a directory in the cgroup file system
 228containing the following files describing that cgroup:
 230 - tasks: list of tasks (by pid) attached to that cgroup
 231 - notify_on_release flag: run the release agent on exit?
 232 - release_agent: the path to use for release notifications (this file
 233   exists in the top cgroup only)
 235Other subsystems such as cpusets may add additional files in each
 236cgroup dir.
 238New cgroups are created using the mkdir system call or shell
 239command.  The properties of a cgroup, such as its flags, are
 240modified by writing to the appropriate file in that cgroups
 241directory, as listed above.
 243The named hierarchical structure of nested cgroups allows partitioning
 244a large system into nested, dynamically changeable, "soft-partitions".
 246The attachment of each task, automatically inherited at fork by any
 247children of that task, to a cgroup allows organizing the work load
 248on a system into related sets of tasks.  A task may be re-attached to
 249any other cgroup, if allowed by the permissions on the necessary
 250cgroup file system directories.
 252When a task is moved from one cgroup to another, it gets a new
 253css_set pointer - if there's an already existing css_set with the
 254desired collection of cgroups then that group is reused, else a new
 255css_set is allocated. The appropriate existing css_set is located by
 256looking into a hash table.
 258To allow access from a cgroup to the css_sets (and hence tasks)
 259that comprise it, a set of cg_cgroup_link objects form a lattice;
 260each cg_cgroup_link is linked into a list of cg_cgroup_links for
 261a single cgroup on its cgrp_link_list field, and a list of
 262cg_cgroup_links for a single css_set on its cg_link_list.
 264Thus the set of tasks in a cgroup can be listed by iterating over
 265each css_set that references the cgroup, and sub-iterating over
 266each css_set's task set.
 268The use of a Linux virtual file system (vfs) to represent the
 269cgroup hierarchy provides for a familiar permission and name space
 270for cgroups, with a minimum of additional kernel code.
 2721.4 What does notify_on_release do ?
 275If the notify_on_release flag is enabled (1) in a cgroup, then
 276whenever the last task in the cgroup leaves (exits or attaches to
 277some other cgroup) and the last child cgroup of that cgroup
 278is removed, then the kernel runs the command specified by the contents
 279of the "release_agent" file in that hierarchy's root directory,
 280supplying the pathname (relative to the mount point of the cgroup
 281file system) of the abandoned cgroup.  This enables automatic
 282removal of abandoned cgroups.  The default value of
 283notify_on_release in the root cgroup at system boot is disabled
 284(0).  The default value of other cgroups at creation is the current
 285value of their parents notify_on_release setting. The default value of
 286a cgroup hierarchy's release_agent path is empty.
 2881.5 How do I use cgroups ?
 291To start a new job that is to be contained within a cgroup, using
 292the "cpuset" cgroup subsystem, the steps are something like:
 294 1) mkdir /dev/cgroup
 295 2) mount -t cgroup -ocpuset cpuset /dev/cgroup
 296 3) Create the new cgroup by doing mkdir's and write's (or echo's) in
 297    the /dev/cgroup virtual file system.
 298 4) Start a task that will be the "founding father" of the new job.
 299 5) Attach that task to the new cgroup by writing its pid to the
 300    /dev/cgroup tasks file for that cgroup.
 301 6) fork, exec or clone the job tasks from this founding father task.
 303For example, the following sequence of commands will setup a cgroup
 304named "Charlie", containing just CPUs 2 and 3, and Memory Node 1,
 305and then start a subshell 'sh' in that cgroup:
 307  mount -t cgroup cpuset -ocpuset /dev/cgroup
 308  cd /dev/cgroup
 309  mkdir Charlie
 310  cd Charlie
 311  /bin/echo 2-3 > cpuset.cpus
 312  /bin/echo 1 > cpuset.mems
 313  /bin/echo $$ > tasks
 314  sh
 315  # The subshell 'sh' is now running in cgroup Charlie
 316  # The next line should display '/Charlie'
 317  cat /proc/self/cgroup
 3192. Usage Examples and Syntax
 3222.1 Basic Usage
 325Creating, modifying, using the cgroups can be done through the cgroup
 326virtual filesystem.
 328To mount a cgroup hierarchy will all available subsystems, type:
 329# mount -t cgroup xxx /dev/cgroup
 331The "xxx" is not interpreted by the cgroup code, but will appear in
 332/proc/mounts so may be any useful identifying string that you like.
 334To mount a cgroup hierarchy with just the cpuset and numtasks
 335subsystems, type:
 336# mount -t cgroup -o cpuset,numtasks hier1 /dev/cgroup
 338To change the set of subsystems bound to a mounted hierarchy, just
 339remount with different options:
 341# mount -o remount,cpuset,ns  /dev/cgroup
 343Note that changing the set of subsystems is currently only supported
 344when the hierarchy consists of a single (root) cgroup. Supporting
 345the ability to arbitrarily bind/unbind subsystems from an existing
 346cgroup hierarchy is intended to be implemented in the future.
 348Then under /dev/cgroup you can find a tree that corresponds to the
 349tree of the cgroups in the system. For instance, /dev/cgroup
 350is the cgroup that holds the whole system.
 352If you want to create a new cgroup under /dev/cgroup:
 353# cd /dev/cgroup
 354# mkdir my_cgroup
 356Now you want to do something with this cgroup.
 357# cd my_cgroup
 359In this directory you can find several files:
 360# ls
 361notify_on_release tasks
 362(plus whatever files added by the attached subsystems)
 364Now attach your shell to this cgroup:
 365# /bin/echo $$ > tasks
 367You can also create cgroups inside your cgroup by using mkdir in this
 369# mkdir my_sub_cs
 371To remove a cgroup, just use rmdir:
 372# rmdir my_sub_cs
 374This will fail if the cgroup is in use (has cgroups inside, or
 375has processes attached, or is held alive by other subsystem-specific
 3782.2 Attaching processes
 381# /bin/echo PID > tasks
 383Note that it is PID, not PIDs. You can only attach ONE task at a time.
 384If you have several tasks to attach, you have to do it one after another:
 386# /bin/echo PID1 > tasks
 387# /bin/echo PID2 > tasks
 388        ...
 389# /bin/echo PIDn > tasks
 391You can attach the current shell task by echoing 0:
 393# echo 0 > tasks
 3953. Kernel API
 3983.1 Overview
 401Each kernel subsystem that wants to hook into the generic cgroup
 402system needs to create a cgroup_subsys object. This contains
 403various methods, which are callbacks from the cgroup system, along
 404with a subsystem id which will be assigned by the cgroup system.
 406Other fields in the cgroup_subsys object include:
 408- subsys_id: a unique array index for the subsystem, indicating which
 409  entry in cgroup->subsys[] this subsystem should be managing.
 411- name: should be initialized to a unique subsystem name. Should be
 412  no longer than MAX_CGROUP_TYPE_NAMELEN.
 414- early_init: indicate if the subsystem needs early initialization
 415  at system boot.
 417Each cgroup object created by the system has an array of pointers,
 418indexed by subsystem id; this pointer is entirely managed by the
 419subsystem; the generic cgroup code will never touch this pointer.
 4213.2 Synchronization
 424There is a global mutex, cgroup_mutex, used by the cgroup
 425system. This should be taken by anything that wants to modify a
 426cgroup. It may also be taken to prevent cgroups from being
 427modified, but more specific locks may be more appropriate in that
 430See kernel/cgroup.c for more details.
 432Subsystems can take/release the cgroup_mutex via the functions
 435Accessing a task's cgroup pointer may be done in the following ways:
 436- while holding cgroup_mutex
 437- while holding the task's alloc_lock (via task_lock())
 438- inside an rcu_read_lock() section via rcu_dereference()
 4403.3 Subsystem API
 443Each subsystem should:
 445- add an entry in linux/cgroup_subsys.h
 446- define a cgroup_subsys object called <name>_subsys
 448Each subsystem may export the following methods. The only mandatory
 449methods are create/destroy. Any others that are null are presumed to
 450be successful no-ops.
 452struct cgroup_subsys_state *create(struct cgroup_subsys *ss,
 453                                   struct cgroup *cgrp)
 454(cgroup_mutex held by caller)
 456Called to create a subsystem state object for a cgroup. The
 457subsystem should allocate its subsystem state object for the passed
 458cgroup, returning a pointer to the new object on success or a
 459negative error code. On success, the subsystem pointer should point to
 460a structure of type cgroup_subsys_state (typically embedded in a
 461larger subsystem-specific object), which will be initialized by the
 462cgroup system. Note that this will be called at initialization to
 463create the root subsystem state for this subsystem; this case can be
 464identified by the passed cgroup object having a NULL parent (since
 465it's the root of the hierarchy) and may be an appropriate place for
 466initialization code.
 468void destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
 469(cgroup_mutex held by caller)
 471The cgroup system is about to destroy the passed cgroup; the subsystem
 472should do any necessary cleanup and free its subsystem state
 473object. By the time this method is called, the cgroup has already been
 474unlinked from the file system and from the child list of its parent;
 475cgroup->parent is still valid. (Note - can also be called for a
 476newly-created cgroup if an error occurs after this subsystem's
 477create() method has been called for the new cgroup).
 479void pre_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp);
 481Called before checking the reference count on each subsystem. This may
 482be useful for subsystems which have some extra references even if
 483there are not tasks in the cgroup.
 485int can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
 486               struct task_struct *task)
 487(cgroup_mutex held by caller)
 489Called prior to moving a task into a cgroup; if the subsystem
 490returns an error, this will abort the attach operation.  If a NULL
 491task is passed, then a successful result indicates that *any*
 492unspecified task can be moved into the cgroup. Note that this isn't
 493called on a fork. If this method returns 0 (success) then this should
 494remain valid while the caller holds cgroup_mutex.
 496void attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
 497            struct cgroup *old_cgrp, struct task_struct *task)
 498(cgroup_mutex held by caller)
 500Called after the task has been attached to the cgroup, to allow any
 501post-attachment activity that requires memory allocations or blocking.
 503void fork(struct cgroup_subsy *ss, struct task_struct *task)
 505Called when a task is forked into a cgroup.
 507void exit(struct cgroup_subsys *ss, struct task_struct *task)
 509Called during task exit.
 511int populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
 512(cgroup_mutex held by caller)
 514Called after creation of a cgroup to allow a subsystem to populate
 515the cgroup directory with file entries.  The subsystem should make
 516calls to cgroup_add_file() with objects of type cftype (see
 517include/linux/cgroup.h for details).  Note that although this
 518method can return an error code, the error code is currently not
 519always handled well.
 521void post_clone(struct cgroup_subsys *ss, struct cgroup *cgrp)
 522(cgroup_mutex held by caller)
 524Called at the end of cgroup_clone() to do any paramater
 525initialization which might be required before a task could attach.  For
 526example in cpusets, no task may attach before 'cpus' and 'mems' are set
 529void bind(struct cgroup_subsys *ss, struct cgroup *root)
 530(cgroup_mutex and ss->hierarchy_mutex held by caller)
 532Called when a cgroup subsystem is rebound to a different hierarchy
 533and root cgroup. Currently this will only involve movement between
 534the default hierarchy (which never has sub-cgroups) and a hierarchy
 535that is being created/destroyed (and hence has no sub-cgroups).
 5374. Questions
 540Q: what's up with this '/bin/echo' ?
 541A: bash's builtin 'echo' command does not check calls to write() against
 542   errors. If you use it in the cgroup file system, you won't be
 543   able to tell whether a command succeeded or failed.
 545Q: When I attach processes, only the first of the line gets really attached !
 546A: We can only return one error code per call to write(). So you should also
 547   put only ONE pid.