Control Group v2¶
| Date: | October, 2015 |
|---|---|
| Author: | Tejun Heo <tj@kernel.org> |
This is the authoritative documentation on the design, interface andconventions of cgroup v2. It describes all userland-visible aspectsof cgroup including core and specific controller behaviors. Allfuture changes must be reflected in this document. Documentation forv1 is available underDocumentation/admin-guide/cgroup-v1/index.rst.
Introduction¶
Terminology¶
“cgroup” stands for “control group” and is never capitalized. Thesingular form is used to designate the whole feature and also as aqualifier as in “cgroup controllers”. When explicitly referring tomultiple individual control groups, the plural form “cgroups” is used.
What is cgroup?¶
cgroup is a mechanism to organize processes hierarchically anddistribute system resources along the hierarchy in a controlled andconfigurable manner.
cgroup is largely composed of two parts - the core and controllers.cgroup core is primarily responsible for hierarchically organizingprocesses. A cgroup controller is usually responsible fordistributing a specific type of system resource along the hierarchyalthough there are utility controllers which serve purposes other thanresource distribution.
cgroups form a tree structure and every process in the system belongsto one and only one cgroup. All threads of a process belong to thesame cgroup. On creation, all processes are put in the cgroup thatthe parent process belongs to at the time. A process can be migratedto another cgroup. Migration of a process doesn’t affect alreadyexisting descendant processes.
Following certain structural constraints, controllers may be enabled ordisabled selectively on a cgroup. All controller behaviors arehierarchical - if a controller is enabled on a cgroup, it affects allprocesses which belong to the cgroups consisting the inclusivesub-hierarchy of the cgroup. When a controller is enabled on a nestedcgroup, it always restricts the resource distribution further. Therestrictions set closer to the root in the hierarchy can not beoverridden from further away.
Basic Operations¶
Mounting¶
Unlike v1, cgroup v2 has only single hierarchy. The cgroup v2hierarchy can be mounted with the following mount command:
# mount -t cgroup2 none $MOUNT_POINT
cgroup2 filesystem has the magic number 0x63677270 (“cgrp”). Allcontrollers which support v2 and are not bound to a v1 hierarchy areautomatically bound to the v2 hierarchy and show up at the root.Controllers which are not in active use in the v2 hierarchy can bebound to other hierarchies. This allows mixing v2 hierarchy with thelegacy v1 multiple hierarchies in a fully backward compatible way.
A controller can be moved across hierarchies only after the controlleris no longer referenced in its current hierarchy. Because per-cgroupcontroller states are destroyed asynchronously and controllers mayhave lingering references, a controller may not show up immediately onthe v2 hierarchy after the final umount of the previous hierarchy.Similarly, a controller should be fully disabled to be moved out ofthe unified hierarchy and it may take some time for the disabledcontroller to become available for other hierarchies; furthermore, dueto inter-controller dependencies, other controllers may need to bedisabled too.
While useful for development and manual configurations, movingcontrollers dynamically between the v2 and other hierarchies isstrongly discouraged for production use. It is recommended to decidethe hierarchies and controller associations before starting using thecontrollers after system boot.
During transition to v2, system management software might stillautomount the v1 cgroup filesystem and so hijack all controllersduring boot, before manual intervention is possible. To make testingand experimenting easier, the kernel parameter cgroup_no_v1= allowsdisabling controllers in v1 and make them always available in v2.
cgroup v2 currently supports the following mount options.
nsdelegate
Consider cgroup namespaces as delegation boundaries. Thisoption is system wide and can only be set on mount or modifiedthrough remount from the init namespace. The mount option isignored on non-init namespace mounts. Please refer to theDelegation section for details.memory_localevents
Only populate memory.events with data for the current cgroup,and not any subtrees. This is legacy behaviour, the defaultbehaviour without this option is to include subtree counts.This option is system wide and can only be set on mount ormodified through remount from the init namespace. The mountoption is ignored on non-init namespace mounts.memory_recursiveprot
Recursively apply memory.min and memory.low protection toentire subtrees, without requiring explicit downwardpropagation into leaf cgroups. This allows protecting entiresubtrees from one another, while retaining free competitionwithin those subtrees. This should have been the defaultbehavior but is a mount-option to avoid regressing setupsrelying on the original semantics (e.g. specifying boguslyhigh ‘bypass’ protection values at higher tree levels).
Organizing Processes and Threads¶
Processes¶
Initially, only the root cgroup exists to which all processes belong.A child cgroup can be created by creating a sub-directory:
# mkdir $CGROUP_NAME
A given cgroup may have multiple child cgroups forming a treestructure. Each cgroup has a read-writable interface file“cgroup.procs”. When read, it lists the PIDs of all processes whichbelong to the cgroup one-per-line. The PIDs are not ordered and thesame PID may show up more than once if the process got moved toanother cgroup and then back or the PID got recycled while reading.
A process can be migrated into a cgroup by writing its PID to thetarget cgroup’s “cgroup.procs” file. Only one process can be migratedon a single write(2) call. If a process is composed of multiplethreads, writing the PID of any thread migrates all threads of theprocess.
When a process forks a child process, the new process is born into thecgroup that the forking process belongs to at the time of theoperation. After exit, a process stays associated with the cgroupthat it belonged to at the time of exit until it’s reaped; however, azombie process does not appear in “cgroup.procs” and thus can’t bemoved to another cgroup.
A cgroup which doesn’t have any children or live processes can bedestroyed by removing the directory. Note that a cgroup which doesn’thave any children and is associated only with zombie processes isconsidered empty and can be removed:
# rmdir $CGROUP_NAME
“/proc/$PID/cgroup” lists a process’s cgroup membership. If legacycgroup is in use in the system, this file may contain multiple lines,one for each hierarchy. The entry for cgroup v2 is always in theformat “0::$PATH”:
# cat /proc/842/cgroup...0::/test-cgroup/test-cgroup-nested
If the process becomes a zombie and the cgroup it was associated withis removed subsequently, ” (deleted)” is appended to the path:
# cat /proc/842/cgroup...0::/test-cgroup/test-cgroup-nested (deleted)
Threads¶
cgroup v2 supports thread granularity for a subset of controllers tosupport use cases requiring hierarchical resource distribution acrossthe threads of a group of processes. By default, all threads of aprocess belong to the same cgroup, which also serves as the resourcedomain to host resource consumptions which are not specific to aprocess or thread. The thread mode allows threads to be spread acrossa subtree while still maintaining the common resource domain for them.
Controllers which support thread mode are called threaded controllers.The ones which don’t are called domain controllers.
Marking a cgroup threaded makes it join the resource domain of itsparent as a threaded cgroup. The parent may be another threadedcgroup whose resource domain is further up in the hierarchy. The rootof a threaded subtree, that is, the nearest ancestor which is notthreaded, is called threaded domain or thread root interchangeably andserves as the resource domain for the entire subtree.
Inside a threaded subtree, threads of a process can be put indifferent cgroups and are not subject to the no internal processconstraint - threaded controllers can be enabled on non-leaf cgroupswhether they have threads in them or not.
As the threaded domain cgroup hosts all the domain resourceconsumptions of the subtree, it is considered to have internalresource consumptions whether there are processes in it or not andcan’t have populated child cgroups which aren’t threaded. Because theroot cgroup is not subject to no internal process constraint, it canserve both as a threaded domain and a parent to domain cgroups.
The current operation mode or type of the cgroup is shown in the“cgroup.type” file which indicates whether the cgroup is a normaldomain, a domain which is serving as the domain of a threaded subtree,or a threaded cgroup.
On creation, a cgroup is always a domain cgroup and can be madethreaded by writing “threaded” to the “cgroup.type” file. Theoperation is single direction:
# echo threaded > cgroup.type
Once threaded, the cgroup can’t be made a domain again. To enable thethread mode, the following conditions must be met.
- As the cgroup will join the parent’s resource domain. The parentmust either be a valid (threaded) domain or a threaded cgroup.
- When the parent is an unthreaded domain, it must not have any domaincontrollers enabled or populated domain children. The root isexempt from this requirement.
Topology-wise, a cgroup can be in an invalid state. Please considerthe following topology:
A (threaded domain) - B (threaded) - C (domain, just created)
C is created as a domain but isn’t connected to a parent which canhost child domains. C can’t be used until it is turned into athreaded cgroup. “cgroup.type” file will report “domain (invalid)” inthese cases. Operations which fail due to invalid topology useEOPNOTSUPP as the errno.
A domain cgroup is turned into a threaded domain when one of its childcgroup becomes threaded or threaded controllers are enabled in the“cgroup.subtree_control” file while there are processes in the cgroup.A threaded domain reverts to a normal domain when the conditionsclear.
When read, “cgroup.threads” contains the list of the thread IDs of allthreads in the cgroup. Except that the operations are per-threadinstead of per-process, “cgroup.threads” has the same format andbehaves the same way as “cgroup.procs”. While “cgroup.threads” can bewritten to in any cgroup, as it can only move threads inside the samethreaded domain, its operations are confined inside each threadedsubtree.
The threaded domain cgroup serves as the resource domain for the wholesubtree, and, while the threads can be scattered across the subtree,all the processes are considered to be in the threaded domain cgroup.“cgroup.procs” in a threaded domain cgroup contains the PIDs of allprocesses in the subtree and is not readable in the subtree proper.However, “cgroup.procs” can be written to from anywhere in the subtreeto migrate all threads of the matching process to the cgroup.
Only threaded controllers can be enabled in a threaded subtree. Whena threaded controller is enabled inside a threaded subtree, it onlyaccounts for and controls resource consumptions associated with thethreads in the cgroup and its descendants. All consumptions whicharen’t tied to a specific thread belong to the threaded domain cgroup.
Because a threaded subtree is exempt from no internal processconstraint, a threaded controller must be able to handle competitionbetween threads in a non-leaf cgroup and its child cgroups. Eachthreaded controller defines how such competitions are handled.
[Un]populated Notification¶
Each non-root cgroup has a “cgroup.events” file which contains“populated” field indicating whether the cgroup’s sub-hierarchy haslive processes in it. Its value is 0 if there is no live process inthe cgroup and its descendants; otherwise, 1. poll and [id]notifyevents are triggered when the value changes. This can be used, forexample, to start a clean-up operation after all processes of a givensub-hierarchy have exited. The populated state updates andnotifications are recursive. Consider the following sub-hierarchywhere the numbers in the parentheses represent the numbers of processesin each cgroup:
A(4) - B(0) - C(1) \ D(0)
A, B and C’s “populated” fields would be 1 while D’s 0. After the oneprocess in C exits, B and C’s “populated” fields would flip to “0” andfile modified events will be generated on the “cgroup.events” files ofboth cgroups.
Controlling Controllers¶
Enabling and Disabling¶
Each cgroup has a “cgroup.controllers” file which lists allcontrollers available for the cgroup to enable:
# cat cgroup.controllerscpu io memory
No controller is enabled by default. Controllers can be enabled anddisabled by writing to the “cgroup.subtree_control” file:
# echo "+cpu +memory -io" > cgroup.subtree_control
Only controllers which are listed in “cgroup.controllers” can beenabled. When multiple operations are specified as above, either theyall succeed or fail. If multiple operations on the same controllerare specified, the last one is effective.
Enabling a controller in a cgroup indicates that the distribution ofthe target resource across its immediate children will be controlled.Consider the following sub-hierarchy. The enabled controllers arelisted in parentheses:
A(cpu,memory) - B(memory) - C() \ D()
As A has “cpu” and “memory” enabled, A will control the distributionof CPU cycles and memory to its children, in this case, B. As B has“memory” enabled but not “CPU”, C and D will compete freely on CPUcycles but their division of memory available to B will be controlled.
As a controller regulates the distribution of the target resource tothe cgroup’s children, enabling it creates the controller’s interfacefiles in the child cgroups. In the above example, enabling “cpu” on Bwould create the “cpu.” prefixed controller interface files in C andD. Likewise, disabling “memory” from B would remove the “memory.”prefixed controller interface files from C and D. This means that thecontroller interface files - anything which doesn’t start with“cgroup.” are owned by the parent rather than the cgroup itself.
Top-down Constraint¶
Resources are distributed top-down and a cgroup can further distributea resource only if the resource has been distributed to it from theparent. This means that all non-root “cgroup.subtree_control” filescan only contain controllers which are enabled in the parent’s“cgroup.subtree_control” file. A controller can be enabled only ifthe parent has the controller enabled and a controller can’t bedisabled if one or more children have it enabled.
No Internal Process Constraint¶
Non-root cgroups can distribute domain resources to their childrenonly when they don’t have any processes of their own. In other words,only domain cgroups which don’t contain any processes can have domaincontrollers enabled in their “cgroup.subtree_control” files.
This guarantees that, when a domain controller is looking at the partof the hierarchy which has it enabled, processes are always only onthe leaves. This rules out situations where child cgroups competeagainst internal processes of the parent.
The root cgroup is exempt from this restriction. Root containsprocesses and anonymous resource consumption which can’t be associatedwith any other cgroups and requires special treatment from mostcontrollers. How resource consumption in the root cgroup is governedis up to each controller (for more information on this topic pleaserefer to the Non-normative information section in the Controllerschapter).
Note that the restriction doesn’t get in the way if there is noenabled controller in the cgroup’s “cgroup.subtree_control”. This isimportant as otherwise it wouldn’t be possible to create children of apopulated cgroup. To control resource distribution of a cgroup, thecgroup must create children and transfer all its processes to thechildren before enabling controllers in its “cgroup.subtree_control”file.
Delegation¶
Model of Delegation¶
A cgroup can be delegated in two ways. First, to a less privilegeduser by granting write access of the directory and its “cgroup.procs”,“cgroup.threads” and “cgroup.subtree_control” files to the user.Second, if the “nsdelegate” mount option is set, automatically to acgroup namespace on namespace creation.
Because the resource control interface files in a given directorycontrol the distribution of the parent’s resources, the delegateeshouldn’t be allowed to write to them. For the first method, this isachieved by not granting access to these files. For the second, thekernel rejects writes to all files other than “cgroup.procs” and“cgroup.subtree_control” on a namespace root from inside thenamespace.
The end results are equivalent for both delegation types. Oncedelegated, the user can build sub-hierarchy under the directory,organize processes inside it as it sees fit and further distribute theresources it received from the parent. The limits and other settingsof all resource controllers are hierarchical and regardless of whathappens in the delegated sub-hierarchy, nothing can escape theresource restrictions imposed by the parent.
Currently, cgroup doesn’t impose any restrictions on the number ofcgroups in or nesting depth of a delegated sub-hierarchy; however,this may be limited explicitly in the future.
Delegation Containment¶
A delegated sub-hierarchy is contained in the sense that processescan’t be moved into or out of the sub-hierarchy by the delegatee.
For delegations to a less privileged user, this is achieved byrequiring the following conditions for a process with a non-root euidto migrate a target process into a cgroup by writing its PID to the“cgroup.procs” file.
- The writer must have write access to the “cgroup.procs” file.
- The writer must have write access to the “cgroup.procs” file of thecommon ancestor of the source and destination cgroups.
The above two constraints ensure that while a delegatee may migrateprocesses around freely in the delegated sub-hierarchy it can’t pullin from or push out to outside the sub-hierarchy.
For an example, let’s assume cgroups C0 and C1 have been delegated touser U0 who created C00, C01 under C0 and C10 under C1 as follows andall processes under C0 and C1 belong to U0:
~~~~~~~~~~~~~ - C0 - C00~ cgroup ~ \ C01~ hierarchy ~~~~~~~~~~~~~~ - C1 - C10
Let’s also say U0 wants to write the PID of a process which iscurrently in C10 into “C00/cgroup.procs”. U0 has write access to thefile; however, the common ancestor of the source cgroup C10 and thedestination cgroup C00 is above the points of delegation and U0 wouldnot have write access to its “cgroup.procs” files and thus the writewill be denied with -EACCES.
For delegations to namespaces, containment is achieved by requiringthat both the source and destination cgroups are reachable from thenamespace of the process which is attempting the migration. If eitheris not reachable, the migration is rejected with -ENOENT.
Guidelines¶
Organize Once and Control¶
Migrating a process across cgroups is a relatively expensive operationand stateful resources such as memory are not moved together with theprocess. This is an explicit design decision as there often existinherent trade-offs between migration and various hot paths in termsof synchronization cost.
As such, migrating processes across cgroups frequently as a means toapply different resource restrictions is discouraged. A workloadshould be assigned to a cgroup according to the system’s logical andresource structure once on start-up. Dynamic adjustments to resourcedistribution can be made by changing controller configuration throughthe interface files.
Avoid Name Collisions¶
Interface files for a cgroup and its children cgroups occupy the samedirectory and it is possible to create children cgroups which collidewith interface files.
All cgroup core interface files are prefixed with “cgroup.” and eachcontroller’s interface files are prefixed with the controller name anda dot. A controller’s name is composed of lower case alphabets and‘_’s but never begins with an ‘_’ so it can be used as the prefixcharacter for collision avoidance. Also, interface file names won’tstart or end with terms which are often used in categorizing workloadssuch as job, service, slice, unit or workload.
cgroup doesn’t do anything to prevent name collisions and it’s theuser’s responsibility to avoid them.
Resource Distribution Models¶
cgroup controllers implement several resource distribution schemesdepending on the resource type and expected use cases. This sectiondescribes major schemes in use along with their expected behaviors.
Weights¶
A parent’s resource is distributed by adding up the weights of allactive children and giving each the fraction matching the ratio of itsweight against the sum. As only children which can make use of theresource at the moment participate in the distribution, this iswork-conserving. Due to the dynamic nature, this model is usuallyused for stateless resources.
All weights are in the range [1, 10000] with the default at 100. Thisallows symmetric multiplicative biases in both directions at fineenough granularity while staying in the intuitive range.
As long as the weight is in range, all configuration combinations arevalid and there is no reason to reject configuration changes orprocess migrations.
“cpu.weight” proportionally distributes CPU cycles to active childrenand is an example of this type.
Limits¶
A child can only consume upto the configured amount of the resource.Limits can be over-committed - the sum of the limits of children canexceed the amount of resource available to the parent.
Limits are in the range [0, max] and defaults to “max”, which is noop.
As limits can be over-committed, all configuration combinations arevalid and there is no reason to reject configuration changes orprocess migrations.
“io.max” limits the maximum BPS and/or IOPS that a cgroup can consumeon an IO device and is an example of this type.
Protections¶
A cgroup is protected upto the configured amount of the resourceas long as the usages of all its ancestors are under theirprotected levels. Protections can be hard guarantees or best effortsoft boundaries. Protections can also be over-committed in which caseonly upto the amount available to the parent is protected amongchildren.
Protections are in the range [0, max] and defaults to 0, which isnoop.
As protections can be over-committed, all configuration combinationsare valid and there is no reason to reject configuration changes orprocess migrations.
“memory.low” implements best-effort memory protection and is anexample of this type.
Allocations¶
A cgroup is exclusively allocated a certain amount of a finiteresource. Allocations can’t be over-committed - the sum of theallocations of children can not exceed the amount of resourceavailable to the parent.
Allocations are in the range [0, max] and defaults to 0, which is noresource.
As allocations can’t be over-committed, some configurationcombinations are invalid and should be rejected. Also, if theresource is mandatory for execution of processes, process migrationsmay be rejected.
“cpu.rt.max” hard-allocates realtime slices and is an example of thistype.
Interface Files¶
Format¶
All interface files should be in one of the following formats wheneverpossible:
New-line separated values(when only one value can be written at once) VAL0\n VAL1\n ...Space separated values(when read-only or multiple values can be written at once) VAL0 VAL1 ...\nFlat keyed KEY0 VAL0\n KEY1 VAL1\n ...Nested keyed KEY0 SUB_KEY0=VAL00 SUB_KEY1=VAL01... KEY1 SUB_KEY0=VAL10 SUB_KEY1=VAL11... ...
For a writable file, the format for writing should generally matchreading; however, controllers may allow omitting later fields orimplement restricted shortcuts for most common use cases.
For both flat and nested keyed files, only the values for a single keycan be written at a time. For nested keyed files, the sub key pairsmay be specified in any order and not all pairs have to be specified.
Conventions¶
Settings for a single feature should be contained in a single file.
The root cgroup should be exempt from resource control and thusshouldn’t have resource control interface files.
The default time unit is microseconds. If a different unit is everused, an explicit unit suffix must be present.
A parts-per quantity should use a percentage decimal with at leasttwo digit fractional part - e.g. 13.40.
If a controller implements weight based resource distribution, itsinterface file should be named “weight” and have the range [1,10000] with 100 as the default. The values are chosen to allowenough and symmetric bias in both directions while keeping itintuitive (the default is 100%).
If a controller implements an absolute resource guarantee and/orlimit, the interface files should be named “min” and “max”respectively. If a controller implements best effort resourceguarantee and/or limit, the interface files should be named “low”and “high” respectively.
In the above four control files, the special token “max” should beused to represent upward infinity for both reading and writing.
If a setting has a configurable default value and keyed specificoverrides, the default entry should be keyed with “default” andappear as the first entry in the file.
The default value can be updated by writing either “default $VAL” or“$VAL”.
When writing to update a specific override, “default” can be used asthe value to indicate removal of the override. Override entrieswith “default” as the value must not appear when read.
For example, a setting which is keyed by major:minor device numberswith integer values may look like the following:
# cat cgroup-example-interface-filedefault 1508:0 300
The default value can be updated by:
# echo 125 > cgroup-example-interface-file
or:
# echo "default 125" > cgroup-example-interface-file
An override can be set by:
# echo "8:16 170" > cgroup-example-interface-file
and cleared by:
# echo "8:0 default" > cgroup-example-interface-file# cat cgroup-example-interface-filedefault 1258:16 170
For events which are not very high frequency, an interface file“events” should be created which lists event key value pairs.Whenever a notifiable event happens, file modified event should begenerated on the file.
Core Interface Files¶
All cgroup core files are prefixed with “cgroup.”
cgroup.type
A read-write single value file which exists on non-rootcgroups.
When read, it indicates the current type of the cgroup, whichcan be one of the following values.
- “domain” : A normal valid domain cgroup.
- “domain threaded” : A threaded domain cgroup which isserving as the root of a threaded subtree.
- “domain invalid” : A cgroup which is in an invalid state.It can’t be populated or have controllers enabled. It maybe allowed to become a threaded cgroup.
- “threaded” : A threaded cgroup which is a member of athreaded subtree.
A cgroup can be turned into a threaded cgroup by writing“threaded” to this file.
- cgroup.procs
A read-write new-line separated values file which exists onall cgroups.
When read, it lists the PIDs of all processes which belong tothe cgroup one-per-line. The PIDs are not ordered and thesame PID may show up more than once if the process got movedto another cgroup and then back or the PID got recycled whilereading.
A PID can be written to migrate the process associated withthe PID to the cgroup. The writer should match all of thefollowing conditions.
- It must have write access to the “cgroup.procs” file.
- It must have write access to the “cgroup.procs” file of thecommon ancestor of the source and destination cgroups.
When delegating a sub-hierarchy, write access to this fileshould be granted along with the containing directory.
In a threaded cgroup, reading this file fails with EOPNOTSUPPas all the processes belong to the thread root. Writing issupported and moves every thread of the process to the cgroup.
- cgroup.threads
A read-write new-line separated values file which exists onall cgroups.
When read, it lists the TIDs of all threads which belong tothe cgroup one-per-line. The TIDs are not ordered and thesame TID may show up more than once if the thread got moved toanother cgroup and then back or the TID got recycled whilereading.
A TID can be written to migrate the thread associated with theTID to the cgroup. The writer should match all of thefollowing conditions.
- It must have write access to the “cgroup.threads” file.
- The cgroup that the thread is currently in must be in thesame resource domain as the destination cgroup.
- It must have write access to the “cgroup.procs” file of thecommon ancestor of the source and destination cgroups.
When delegating a sub-hierarchy, write access to this fileshould be granted along with the containing directory.
- cgroup.controllers
A read-only space separated values file which exists on allcgroups.
It shows space separated list of all controllers available tothe cgroup. The controllers are not ordered.
- cgroup.subtree_control
A read-write space separated values file which exists on allcgroups. Starts out empty.
When read, it shows space separated list of the controllerswhich are enabled to control resource distribution from thecgroup to its children.
Space separated list of controllers prefixed with ‘+’ or ‘-‘can be written to enable or disable controllers. A controllername prefixed with ‘+’ enables the controller and ‘-‘disables. If a controller appears more than once on the list,the last one is effective. When multiple enable and disableoperations are specified, either all succeed or all fail.
- cgroup.events
A read-only flat-keyed file which exists on non-root cgroups.The following entries are defined. Unless specifiedotherwise, a value change in this file generates a filemodified event.
- populated
- 1 if the cgroup or its descendants contains any liveprocesses; otherwise, 0.
- frozen
- 1 if the cgroup is frozen; otherwise, 0.
- cgroup.max.descendants
A read-write single value files. The default is “max”.
Maximum allowed number of descent cgroups.If the actual number of descendants is equal or larger,an attempt to create a new cgroup in the hierarchy will fail.
- cgroup.max.depth
A read-write single value files. The default is “max”.
Maximum allowed descent depth below the current cgroup.If the actual descent depth is equal or larger,an attempt to create a new child cgroup will fail.
- cgroup.stat
A read-only flat-keyed file with the following entries:
- nr_descendants
- Total number of visible descendant cgroups.
- nr_dying_descendants
Total number of dying descendant cgroups. A cgroup becomesdying after being deleted by a user. The cgroup will remainin dying state for some time undefined time (which can dependon system load) before being completely destroyed.
A process can’t enter a dying cgroup under any circumstances,a dying cgroup can’t revive.
A dying cgroup can consume system resources not exceedinglimits, which were active at the moment of cgroup deletion.
- cgroup.freeze
A read-write single value file which exists on non-root cgroups.Allowed values are “0” and “1”. The default is “0”.
Writing “1” to the file causes freezing of the cgroup and alldescendant cgroups. This means that all belonging processes willbe stopped and will not run until the cgroup will be explicitlyunfrozen. Freezing of the cgroup may take some time; when this actionis completed, the “frozen” value in the cgroup.events control filewill be updated to “1” and the corresponding notification will beissued.
A cgroup can be frozen either by its own settings, or by settingsof any ancestor cgroups. If any of ancestor cgroups is frozen, thecgroup will remain frozen.
Processes in the frozen cgroup can be killed by a fatal signal.They also can enter and leave a frozen cgroup: either by an explicitmove by a user, or if freezing of the cgroup races with fork().If a process is moved to a frozen cgroup, it stops. If a process ismoved out of a frozen cgroup, it becomes running.
Frozen status of a cgroup doesn’t affect any cgroup tree operations:it’s possible to delete a frozen (and empty) cgroup, as well ascreate new sub-cgroups.
Controllers¶
CPU¶
The “cpu” controllers regulates distribution of CPU cycles. Thiscontroller implements weight and absolute bandwidth limit models fornormal scheduling policy and absolute bandwidth allocation model forrealtime scheduling policy.
In all the above models, cycles distribution is defined only on a temporalbase and it does not account for the frequency at which tasks are executed.The (optional) utilization clamping support allows to hint the schedutilcpufreq governor about the minimum desired frequency which should always beprovided by a CPU, as well as the maximum desired frequency, which should notbe exceeded by a CPU.
WARNING: cgroup2 doesn’t yet support control of realtime processes andthe cpu controller can only be enabled when all RT processes are inthe root cgroup. Be aware that system management software may alreadyhave placed RT processes into nonroot cgroups during the system bootprocess, and these processes may need to be moved to the root cgroupbefore the cpu controller can be enabled.
CPU Interface Files¶
All time durations are in microseconds.
- cpu.stat
A read-only flat-keyed file.This file exists whether the controller is enabled or not.
It always reports the following three stats:
- usage_usec
- user_usec
- system_usec
and the following three when the controller is enabled:
- nr_periods
- nr_throttled
- throttled_usec
- cpu.weight
A read-write single value file which exists on non-rootcgroups. The default is “100”.
The weight in the range [1, 10000].
- cpu.weight.nice
A read-write single value file which exists on non-rootcgroups. The default is “0”.
The nice value is in the range [-20, 19].
This interface file is an alternative interface for“cpu.weight” and allows reading and setting weight using thesame values used by nice(2). Because the range is smaller andgranularity is coarser for the nice values, the read value isthe closest approximation of the current weight.
- cpu.max
A read-write two value file which exists on non-root cgroups.The default is “max 100000”.
The maximum bandwidth limit. It’s in the following format:
$MAX $PERIODwhich indicates that the group may consume upto $MAX in each$PERIOD duration. “max” for $MAX indicates no limit. If onlyone number is written, $MAX is updated.
- cpu.pressure
A read-only nested-key file which exists on non-root cgroups.
Shows pressure stall information for CPU. SeeDocumentation/accounting/psi.rst for details.
- cpu.uclamp.min
A read-write single value file which exists on non-root cgroups.The default is “0”, i.e. no utilization boosting.
The requested minimum utilization (protection) as a percentagerational number, e.g. 12.34 for 12.34%.
This interface allows reading and setting minimum utilization clampvalues similar to the sched_setattr(2). This minimum utilizationvalue is used to clamp the task specific minimum utilization clamp.
The requested minimum utilization (protection) is always capped bythe current value for the maximum utilization (limit), i.e.cpu.uclamp.max.
- cpu.uclamp.max
A read-write single value file which exists on non-root cgroups.The default is “max”. i.e. no utilization capping
The requested maximum utilization (limit) as a percentage rationalnumber, e.g. 98.76 for 98.76%.
This interface allows reading and setting maximum utilization clampvalues similar to the sched_setattr(2). This maximum utilizationvalue is used to clamp the task specific maximum utilization clamp.
Memory¶
The “memory” controller regulates distribution of memory. Memory isstateful and implements both limit and protection models. Due to theintertwining between memory usage and reclaim pressure and thestateful nature of memory, the distribution model is relativelycomplex.
While not completely water-tight, all major memory usages by a givencgroup are tracked so that the total memory consumption can beaccounted and controlled to a reasonable extent. Currently, thefollowing types of memory usages are tracked.
- Userland memory - page cache and anonymous memory.
- Kernel data structures such as dentries and inodes.
- TCP socket buffers.
The above list may expand in the future for better coverage.
Memory Interface Files¶
All memory amounts are in bytes. If a value which is not aligned toPAGE_SIZE is written, the value may be rounded up to the closestPAGE_SIZE multiple when read back.
- memory.current
A read-only single value file which exists on non-rootcgroups.
The total amount of memory currently being used by the cgroupand its descendants.
- memory.min
A read-write single value file which exists on non-rootcgroups. The default is “0”.
Hard memory protection. If the memory usage of a cgroupis within its effective min boundary, the cgroup’s memorywon’t be reclaimed under any conditions. If there is nounprotected reclaimable memory available, OOM killeris invoked. Above the effective min boundary (oreffective low boundary if it is higher), pages are reclaimedproportionally to the overage, reducing reclaim pressure forsmaller overages.
Effective min boundary is limited by memory.min values ofall ancestor cgroups. If there is memory.min overcommitment(child cgroup or cgroups are requiring more protected memorythan parent will allow), then each child cgroup will getthe part of parent’s protection proportional to itsactual memory usage below memory.min.
Putting more memory than generally available under thisprotection is discouraged and may lead to constant OOMs.
If a memory cgroup is not populated with processes,its memory.min is ignored.
- memory.low
A read-write single value file which exists on non-rootcgroups. The default is “0”.
Best-effort memory protection. If the memory usage of acgroup is within its effective low boundary, the cgroup’smemory won’t be reclaimed unless there is no reclaimablememory available in unprotected cgroups.Above the effective low boundary (oreffective min boundary if it is higher), pages are reclaimedproportionally to the overage, reducing reclaim pressure forsmaller overages.
Effective low boundary is limited by memory.low values ofall ancestor cgroups. If there is memory.low overcommitment(child cgroup or cgroups are requiring more protected memorythan parent will allow), then each child cgroup will getthe part of parent’s protection proportional to itsactual memory usage below memory.low.
Putting more memory than generally available under thisprotection is discouraged.
- memory.high
A read-write single value file which exists on non-rootcgroups. The default is “max”.
Memory usage throttle limit. This is the main mechanism tocontrol memory usage of a cgroup. If a cgroup’s usage goesover the high boundary, the processes of the cgroup arethrottled and put under heavy reclaim pressure.
Going over the high limit never invokes the OOM killer andunder extreme conditions the limit may be breached.
- memory.max
A read-write single value file which exists on non-rootcgroups. The default is “max”.
Memory usage hard limit. This is the final protectionmechanism. If a cgroup’s memory usage reaches this limit andcan’t be reduced, the OOM killer is invoked in the cgroup.Under certain circumstances, the usage may go over the limittemporarily.
In default configuration regular 0-order allocations alwayssucceed unless OOM killer chooses current task as a victim.
Some kinds of allocations don’t invoke the OOM killer.Caller could retry them differently, return into userspaceas -ENOMEM or silently ignore in cases like disk readahead.
This is the ultimate protection mechanism. As long as thehigh limit is used and monitored properly, this limit’sutility is limited to providing the final safety net.
- memory.oom.group
A read-write single value file which exists on non-rootcgroups. The default value is “0”.
Determines whether the cgroup should be treated asan indivisible workload by the OOM killer. If set,all tasks belonging to the cgroup or to its descendants(if the memory cgroup is not a leaf cgroup) are killedtogether or not at all. This can be used to avoidpartial kills to guarantee workload integrity.
Tasks with the OOM protection (oom_score_adj set to -1000)are treated as an exception and are never killed.
If the OOM killer is invoked in a cgroup, it’s not goingto kill any tasks outside of this cgroup, regardlessmemory.oom.group values of ancestor cgroups.
- memory.events
A read-only flat-keyed file which exists on non-root cgroups.The following entries are defined. Unless specifiedotherwise, a value change in this file generates a filemodified event.
Note that all fields in this file are hierarchical and thefile modified event can be generated due to an event down thehierarchy. For for the local events at the cgroup level seememory.events.local.
- low
- The number of times the cgroup is reclaimed due tohigh memory pressure even though its usage is underthe low boundary. This usually indicates that the lowboundary is over-committed.
- high
- The number of times processes of the cgroup arethrottled and routed to perform direct memory reclaimbecause the high memory boundary was exceeded. For acgroup whose memory usage is capped by the high limitrather than global memory pressure, this event’soccurrences are expected.
- max
- The number of times the cgroup’s memory usage wasabout to go over the max boundary. If direct reclaimfails to bring it down, the cgroup goes to OOM state.
- oom
The number of time the cgroup’s memory usage wasreached the limit and allocation was about to fail.
This event is not raised if the OOM killer is notconsidered as an option, e.g. for failed high-orderallocations or if caller asked to not retry attempts.
- oom_kill
- The number of processes belonging to this cgroupkilled by any kind of OOM killer.
- memory.events.local
- Similar to memory.events but the fields in the file are localto the cgroup i.e. not hierarchical. The file modified eventgenerated on this file reflects only the local events.
- memory.stat
A read-only flat-keyed file which exists on non-root cgroups.
This breaks down the cgroup’s memory footprint into differenttypes of memory, type-specific details, and other informationon the state and past events of the memory management system.
All memory amounts are in bytes.
The entries are ordered to be human readable, and new entriescan show up in the middle. Don’t rely on items remaining in afixed position; use the keys to look up specific values!
- anon
- Amount of memory used in anonymous mappings such asbrk(), sbrk(), and mmap(MAP_ANONYMOUS)
- file
- Amount of memory used to cache filesystem data,including tmpfs and shared memory.
- kernel_stack
- Amount of memory allocated to kernel stacks.
- slab
- Amount of memory used for storing in-kernel datastructures.
- percpu
- Amount of memory used for storing per-cpu kerneldata structures.
- sock
- Amount of memory used in network transmission buffers
- shmem
- Amount of cached filesystem data that is swap-backed,such as tmpfs, shm segments, shared anonymous mmap()s
- file_mapped
- Amount of cached filesystem data mapped with mmap()
- file_dirty
- Amount of cached filesystem data that was modified butnot yet written back to disk
- file_writeback
- Amount of cached filesystem data that was modified andis currently being written back to disk
- anon_thp
- Amount of memory used in anonymous mappings backed bytransparent hugepages
- inactive_anon, active_anon, inactive_file, active_file, unevictable
Amount of memory, swap-backed and filesystem-backed,on the internal memory management lists used by thepage reclaim algorithm.
As these represent internal list state (eg. shmem pages are on anonmemory management lists), inactive_foo + active_foo may not be equal tothe value for the foo counter, since the foo counter is type-based, notlist-based.
- slab_reclaimable
- Part of “slab” that might be reclaimed, such asdentries and inodes.
- slab_unreclaimable
- Part of “slab” that cannot be reclaimed on memorypressure.
- pgfault
- Total number of page faults incurred
- pgmajfault
- Number of major page faults incurred
- workingset_refault_anon
- Number of refaults of previously evicted anonymous pages.
- workingset_refault_file
- Number of refaults of previously evicted file pages.
- workingset_activate_anon
- Number of refaulted anonymous pages that were immediatelyactivated.
- workingset_activate_file
- Number of refaulted file pages that were immediately activated.
- workingset_restore_anon
- Number of restored anonymous pages which have been detected asan active workingset before they got reclaimed.
- workingset_restore_file
- Number of restored file pages which have been detected as anactive workingset before they got reclaimed.
- workingset_nodereclaim
- Number of times a shadow node has been reclaimed
- pgrefill
- Amount of scanned pages (in an active LRU list)
- pgscan
- Amount of scanned pages (in an inactive LRU list)
- pgsteal
- Amount of reclaimed pages
- pgactivate
- Amount of pages moved to the active LRU list
- pgdeactivate
- Amount of pages moved to the inactive LRU list
- pglazyfree
- Amount of pages postponed to be freed under memory pressure
- pglazyfreed
- Amount of reclaimed lazyfree pages
- thp_fault_alloc
- Number of transparent hugepages which were allocated to satisfya page fault. This counter is not present when CONFIG_TRANSPARENT_HUGEPAGEis not set.
- thp_collapse_alloc
- Number of transparent hugepages which were allocated to allowcollapsing an existing range of pages. This counter is notpresent when CONFIG_TRANSPARENT_HUGEPAGE is not set.
- memory.swap.current
A read-only single value file which exists on non-rootcgroups.
The total amount of swap currently being used by the cgroupand its descendants.
- memory.swap.high
A read-write single value file which exists on non-rootcgroups. The default is “max”.
Swap usage throttle limit. If a cgroup’s swap usage exceedsthis limit, all its further allocations will be throttled toallow userspace to implement custom out-of-memory procedures.
This limit marks a point of no return for the cgroup. It is NOTdesigned to manage the amount of swapping a workload doesduring regular operation. Compare to memory.swap.max, whichprohibits swapping past a set amount, but lets the cgroupcontinue unimpeded as long as other memory can be reclaimed.
Healthy workloads are not expected to reach this limit.
- memory.swap.max
A read-write single value file which exists on non-rootcgroups. The default is “max”.
Swap usage hard limit. If a cgroup’s swap usage reaches thislimit, anonymous memory of the cgroup will not be swapped out.
- memory.swap.events
A read-only flat-keyed file which exists on non-root cgroups.The following entries are defined. Unless specifiedotherwise, a value change in this file generates a filemodified event.
- high
- The number of times the cgroup’s swap usage was overthe high threshold.
- max
- The number of times the cgroup’s swap usage was aboutto go over the max boundary and swap allocationfailed.
- fail
- The number of times swap allocation failed eitherbecause of running out of swap system-wide or maxlimit.
When reduced under the current usage, the existing swapentries are reclaimed gradually and the swap usage may stayhigher than the limit for an extended period of time. Thisreduces the impact on the workload and memory management.
- memory.pressure
A read-only nested-key file which exists on non-root cgroups.
Shows pressure stall information for memory. SeeDocumentation/accounting/psi.rst for details.
Usage Guidelines¶
“memory.high” is the main mechanism to control memory usage.Over-committing on high limit (sum of high limits > available memory)and letting global memory pressure to distribute memory according tousage is a viable strategy.
Because breach of the high limit doesn’t trigger the OOM killer butthrottles the offending cgroup, a management agent has ampleopportunities to monitor and take appropriate actions such as grantingmore memory or terminating the workload.
Determining whether a cgroup has enough memory is not trivial asmemory usage doesn’t indicate whether the workload can benefit frommore memory. For example, a workload which writes data received fromnetwork to a file can use all available memory but can also operate asperformant with a small amount of memory. A measure of memorypressure - how much the workload is being impacted due to lack ofmemory - is necessary to determine whether a workload needs morememory; unfortunately, memory pressure monitoring mechanism isn’timplemented yet.
Memory Ownership¶
A memory area is charged to the cgroup which instantiated it and stayscharged to the cgroup until the area is released. Migrating a processto a different cgroup doesn’t move the memory usages that itinstantiated while in the previous cgroup to the new cgroup.
A memory area may be used by processes belonging to different cgroups.To which cgroup the area will be charged is in-deterministic; however,over time, the memory area is likely to end up in a cgroup which hasenough memory allowance to avoid high reclaim pressure.
If a cgroup sweeps a considerable amount of memory which is expectedto be accessed repeatedly by other cgroups, it may make sense to usePOSIX_FADV_DONTNEED to relinquish the ownership of memory areasbelonging to the affected files to ensure correct memory ownership.
IO¶
The “io” controller regulates the distribution of IO resources. Thiscontroller implements both weight based and absolute bandwidth or IOPSlimit distribution; however, weight based distribution is availableonly if cfq-iosched is in use and neither scheme is available forblk-mq devices.
IO Interface Files¶
- io.stat
A read-only nested-keyed file.
Lines are keyed by $MAJ:$MIN device numbers and not ordered.The following nested keys are defined.
rbytes Bytes read wbytes Bytes written rios Number of read IOs wios Number of write IOs dbytes Bytes discarded dios Number of discard IOs An example read output follows:
8:16 rbytes=1459200 wbytes=314773504 rios=192 wios=353 dbytes=0 dios=08:0 rbytes=90430464 wbytes=299008000 rios=8950 wios=1252 dbytes=50331648 dios=3021- io.cost.qos
A read-write nested-keyed file with exists only on the rootcgroup.
This file configures the Quality of Service of the IO costmodel based controller (CONFIG_BLK_CGROUP_IOCOST) whichcurrently implements “io.weight” proportional control. Linesare keyed by $MAJ:$MIN device numbers and not ordered. Theline for a given device is populated on the first write forthe device on “io.cost.qos” or “io.cost.model”. The followingnested keys are defined.
enable Weight-based control enable ctrl “auto” or “user” rpct Read latency percentile [0, 100] rlat Read latency threshold wpct Write latency percentile [0, 100] wlat Write latency threshold min Minimum scaling percentage [1, 10000] max Maximum scaling percentage [1, 10000] The controller is disabled by default and can be enabled bysetting “enable” to 1. “rpct” and “wpct” parameters defaultto zero and the controller uses internal device saturationstate to adjust the overall IO rate between “min” and “max”.
When a better control quality is needed, latency QoSparameters can be configured. For example:
8:16 enable=1 ctrl=auto rpct=95.00 rlat=75000 wpct=95.00 wlat=150000 min=50.00 max=150.0shows that on sdb, the controller is enabled, will considerthe device saturated if the 95th percentile of read completionlatencies is above 75ms or write 150ms, and adjust the overallIO issue rate between 50% and 150% accordingly.
The lower the saturation point, the better the latency QoS atthe cost of aggregate bandwidth. The narrower the allowedadjustment range between “min” and “max”, the more conformantto the cost model the IO behavior. Note that the IO issuebase rate may be far off from 100% and setting “min” and “max”blindly can lead to a significant loss of device capacity orcontrol quality. “min” and “max” are useful for regulatingdevices which show wide temporary behavior changes - e.g. assd which accepts writes at the line speed for a while andthen completely stalls for multiple seconds.
When “ctrl” is “auto”, the parameters are controlled by thekernel and may change automatically. Setting “ctrl” to “user”or setting any of the percentile and latency parameters putsit into “user” mode and disables the automatic changes. Theautomatic mode can be restored by setting “ctrl” to “auto”.
- io.cost.model
A read-write nested-keyed file with exists only on the rootcgroup.
This file configures the cost model of the IO cost model basedcontroller (CONFIG_BLK_CGROUP_IOCOST) which currentlyimplements “io.weight” proportional control. Lines are keyedby $MAJ:$MIN device numbers and not ordered. The line for agiven device is populated on the first write for the device on“io.cost.qos” or “io.cost.model”. The following nested keysare defined.
ctrl “auto” or “user” model The cost model in use - “linear” When “ctrl” is “auto”, the kernel may change all parametersdynamically. When “ctrl” is set to “user” or any otherparameters are written to, “ctrl” become “user” and theautomatic changes are disabled.
When “model” is “linear”, the following model parameters aredefined.
[r|w]bps The maximum sequential IO throughput [r|w]seqiops The maximum 4k sequential IOs per second [r|w]randiops The maximum 4k random IOs per second From the above, the builtin linear model determines the basecosts of a sequential and random IO and the cost coefficientfor the IO size. While simple, this model can cover mostcommon device classes acceptably.
The IO cost model isn’t expected to be accurate in absolutesense and is scaled to the device behavior dynamically.
If needed, tools/cgroup/iocost_coef_gen.py can be used togenerate device-specific coefficients.
- io.weight
A read-write flat-keyed file which exists on non-root cgroups.The default is “default 100”.
The first line is the default weight applied to deviceswithout specific override. The rest are overrides keyed by$MAJ:$MIN device numbers and not ordered. The weights are inthe range [1, 10000] and specifies the relative amount IO timethe cgroup can use in relation to its siblings.
The default weight can be updated by writing either “default$WEIGHT” or simply “$WEIGHT”. Overrides can be set by writing“$MAJ:$MIN $WEIGHT” and unset by writing “$MAJ:$MIN default”.
An example read output follows:
default 1008:16 2008:0 50- io.max
A read-write nested-keyed file which exists on non-rootcgroups.
BPS and IOPS based IO limit. Lines are keyed by $MAJ:$MINdevice numbers and not ordered. The following nested keys aredefined.
rbps Max read bytes per second wbps Max write bytes per second riops Max read IO operations per second wiops Max write IO operations per second When writing, any number of nested key-value pairs can bespecified in any order. “max” can be specified as the valueto remove a specific limit. If the same key is specifiedmultiple times, the outcome is undefined.
BPS and IOPS are measured in each IO direction and IOs aredelayed if limit is reached. Temporary bursts are allowed.
Setting read limit at 2M BPS and write at 120 IOPS for 8:16:
echo "8:16 rbps=2097152 wiops=120" > io.maxReading returns the following:
8:16 rbps=2097152 wbps=max riops=max wiops=120Write IOPS limit can be removed by writing the following:
echo "8:16 wiops=max" > io.maxReading now returns the following:
8:16 rbps=2097152 wbps=max riops=max wiops=max- io.pressure
A read-only nested-key file which exists on non-root cgroups.
Shows pressure stall information for IO. SeeDocumentation/accounting/psi.rst for details.
Writeback¶
Page cache is dirtied through buffered writes and shared mmaps andwritten asynchronously to the backing filesystem by the writebackmechanism. Writeback sits between the memory and IO domains andregulates the proportion of dirty memory by balancing dirtying andwrite IOs.
The io controller, in conjunction with the memory controller,implements control of page cache writeback IOs. The memory controllerdefines the memory domain that dirty memory ratio is calculated andmaintained for and the io controller defines the io domain whichwrites out dirty pages for the memory domain. Both system-wide andper-cgroup dirty memory states are examined and the more restrictiveof the two is enforced.
cgroup writeback requires explicit support from the underlyingfilesystem. Currently, cgroup writeback is implemented on ext2, ext4,btrfs, f2fs, and xfs. On other filesystems, all writeback IOs areattributed to the root cgroup.
There are inherent differences in memory and writeback managementwhich affects how cgroup ownership is tracked. Memory is tracked perpage while writeback per inode. For the purpose of writeback, aninode is assigned to a cgroup and all IO requests to write dirty pagesfrom the inode are attributed to that cgroup.
As cgroup ownership for memory is tracked per page, there can be pageswhich are associated with different cgroups than the one the inode isassociated with. These are called foreign pages. The writebackconstantly keeps track of foreign pages and, if a particular foreigncgroup becomes the majority over a certain period of time, switchesthe ownership of the inode to that cgroup.
While this model is enough for most use cases where a given inode ismostly dirtied by a single cgroup even when the main writing cgroupchanges over time, use cases where multiple cgroups write to a singleinode simultaneously are not supported well. In such circumstances, asignificant portion of IOs are likely to be attributed incorrectly.As memory controller assigns page ownership on the first use anddoesn’t update it until the page is released, even if writebackstrictly follows page ownership, multiple cgroups dirtying overlappingareas wouldn’t work as expected. It’s recommended to avoid such usagepatterns.
The sysctl knobs which affect writeback behavior are applied to cgroupwriteback as follows.
- vm.dirty_background_ratio, vm.dirty_ratio
- These ratios apply the same to cgroup writeback with theamount of available memory capped by limits imposed by thememory controller and system-wide clean memory.
- vm.dirty_background_bytes, vm.dirty_bytes
- For cgroup writeback, this is calculated into ratio againsttotal available memory and applied the same way asvm.dirty[_background]_ratio.
IO Latency¶
This is a cgroup v2 controller for IO workload protection. You provide a groupwith a latency target, and if the average latency exceeds that target thecontroller will throttle any peers that have a lower latency target than theprotected workload.
The limits are only applied at the peer level in the hierarchy. This means thatin the diagram below, only groups A, B, and C will influence each other, andgroups D and F will influence each other. Group G will influence nobody:
[root] / | \ A B C / \ |D F G
So the ideal way to configure this is to set io.latency in groups A, B, and C.Generally you do not want to set a value lower than the latency your devicesupports. Experiment to find the value that works best for your workload.Start at higher than the expected latency for your device and watch theavg_lat value in io.stat for your workload group to get an idea of thelatency you see during normal operation. Use the avg_lat value as a basis foryour real setting, setting at 10-15% higher than the value in io.stat.
How IO Latency Throttling Works¶
io.latency is work conserving; so as long as everybody is meeting their latencytarget the controller doesn’t do anything. Once a group starts missing itstarget it begins throttling any peer group that has a higher target than itself.This throttling takes 2 forms:
- Queue depth throttling. This is the number of outstanding IO’s a group isallowed to have. We will clamp down relatively quickly, starting at no limitand going all the way down to 1 IO at a time.
- Artificial delay induction. There are certain types of IO that cannot bethrottled without possibly adversely affecting higher priority groups. Thisincludes swapping and metadata IO. These types of IO are allowed to occurnormally, however they are “charged” to the originating group. If theoriginating group is being throttled you will see the use_delay and delayfields in io.stat increase. The delay value is how many microseconds that arebeing added to any process that runs in this group. Because this number cangrow quite large if there is a lot of swapping or metadata IO occurring welimit the individual delay events to 1 second at a time.
Once the victimized group starts meeting its latency target again it will startunthrottling any peer groups that were throttled previously. If the victimizedgroup simply stops doing IO the global counter will unthrottle appropriately.
IO Latency Interface Files¶
- io.latency
This takes a similar format as the other controllers.
“MAJOR:MINOR target=<target time in microseconds”- io.stat
If the controller is enabled you will see extra stats in io.stat inaddition to the normal ones.
- depth
- This is the current queue depth for the group.
- avg_lat
- This is an exponential moving average with a decay rate of 1/expbound by the sampling interval. The decay rate interval can becalculated by multiplying the win value in io.stat by thecorresponding number of samples based on the win value.
- win
- The sampling window size in milliseconds. This is the minimumduration of time between evaluation events. Windows only elapsewith IO activity. Idle periods extend the most recent window.
PID¶
The process number controller is used to allow a cgroup to stop anynew tasks from being fork()’d or clone()’d after a specified limit isreached.
The number of tasks in a cgroup can be exhausted in ways which othercontrollers cannot prevent, thus warranting its own controller. Forexample, a fork bomb is likely to exhaust the number of tasks beforehitting memory restrictions.
Note that PIDs used in this controller refer to TIDs, process IDs asused by the kernel.
PID Interface Files¶
- pids.max
A read-write single value file which exists on non-rootcgroups. The default is “max”.
Hard limit of number of processes.
- pids.current
A read-only single value file which exists on all cgroups.
The number of processes currently in the cgroup and itsdescendants.
Organisational operations are not blocked by cgroup policies, so it ispossible to have pids.current > pids.max. This can be done by eithersetting the limit to be smaller than pids.current, or attaching enoughprocesses to the cgroup such that pids.current is larger thanpids.max. However, it is not possible to violate a cgroup PID policythrough fork() or clone(). These will return -EAGAIN if the creationof a new process would cause a cgroup policy to be violated.
Cpuset¶
The “cpuset” controller provides a mechanism for constrainingthe CPU and memory node placement of tasks to only the resourcesspecified in the cpuset interface files in a task’s current cgroup.This is especially valuable on large NUMA systems where placing jobson properly sized subsets of the systems with careful processor andmemory placement to reduce cross-node memory access and contentioncan improve overall system performance.
The “cpuset” controller is hierarchical. That means the controllercannot use CPUs or memory nodes not allowed in its parent.
Cpuset Interface Files¶
- cpuset.cpus
A read-write multiple values file which exists on non-rootcpuset-enabled cgroups.
It lists the requested CPUs to be used by tasks within thiscgroup. The actual list of CPUs to be granted, however, issubjected to constraints imposed by its parent and can differfrom the requested CPUs.
The CPU numbers are comma-separated numbers or ranges.For example:
# cat cpuset.cpus0-4,6,8-10An empty value indicates that the cgroup is using the samesetting as the nearest cgroup ancestor with a non-empty“cpuset.cpus” or all the available CPUs if none is found.
The value of “cpuset.cpus” stays constant until the next updateand won’t be affected by any CPU hotplug events.
- cpuset.cpus.effective
A read-only multiple values file which exists on allcpuset-enabled cgroups.
It lists the onlined CPUs that are actually granted to thiscgroup by its parent. These CPUs are allowed to be used bytasks within the current cgroup.
If “cpuset.cpus” is empty, the “cpuset.cpus.effective” file showsall the CPUs from the parent cgroup that can be available tobe used by this cgroup. Otherwise, it should be a subset of“cpuset.cpus” unless none of the CPUs listed in “cpuset.cpus”can be granted. In this case, it will be treated just like anempty “cpuset.cpus”.
Its value will be affected by CPU hotplug events.
- cpuset.mems
A read-write multiple values file which exists on non-rootcpuset-enabled cgroups.
It lists the requested memory nodes to be used by tasks withinthis cgroup. The actual list of memory nodes granted, however,is subjected to constraints imposed by its parent and can differfrom the requested memory nodes.
The memory node numbers are comma-separated numbers or ranges.For example:
# cat cpuset.mems0-1,3An empty value indicates that the cgroup is using the samesetting as the nearest cgroup ancestor with a non-empty“cpuset.mems” or all the available memory nodes if noneis found.
The value of “cpuset.mems” stays constant until the next updateand won’t be affected by any memory nodes hotplug events.
- cpuset.mems.effective
A read-only multiple values file which exists on allcpuset-enabled cgroups.
It lists the onlined memory nodes that are actually granted tothis cgroup by its parent. These memory nodes are allowed tobe used by tasks within the current cgroup.
If “cpuset.mems” is empty, it shows all the memory nodes from theparent cgroup that will be available to be used by this cgroup.Otherwise, it should be a subset of “cpuset.mems” unless none ofthe memory nodes listed in “cpuset.mems” can be granted. In thiscase, it will be treated just like an empty “cpuset.mems”.
Its value will be affected by memory nodes hotplug events.
- cpuset.cpus.partition
A read-write single value file which exists on non-rootcpuset-enabled cgroups. This flag is owned by the parent cgroupand is not delegatable.
It accepts only the following input values when written to.
“root” - a partition root“member” - a non-root member of a partition
When set to be a partition root, the current cgroup is theroot of a new partition or scheduling domain that comprisesitself and all its descendants except those that are separatepartition roots themselves and their descendants. The rootcgroup is always a partition root.
There are constraints on where a partition root can be set.It can only be set in a cgroup if all the following conditionsare true.
- The “cpuset.cpus” is not empty and the list of CPUs areexclusive, i.e. they are not shared by any of its siblings.
- The parent cgroup is a partition root.
- The “cpuset.cpus” is also a proper subset of the parent’s“cpuset.cpus.effective”.
- There is no child cgroups with cpuset enabled. This is foreliminating corner cases that have to be handled if such acondition is allowed.
Setting it to partition root will take the CPUs away from theeffective CPUs of the parent cgroup. Once it is set, thisfile cannot be reverted back to “member” if there are any childcgroups with cpuset enabled.
A parent partition cannot distribute all its CPUs to itschild partitions. There must be at least one cpu left in theparent partition.
Once becoming a partition root, changes to “cpuset.cpus” isgenerally allowed as long as the first condition above is true,the change will not take away all the CPUs from the parentpartition and the new “cpuset.cpus” value is a superset of itschildren’s “cpuset.cpus” values.
Sometimes, external factors like changes to ancestors’“cpuset.cpus” or cpu hotplug can cause the state of the partitionroot to change. On read, the “cpuset.sched.partition” filecan show the following values.
“member” Non-root member of a partition“root” Partition root“root invalid” Invalid partition root
It is a partition root if the first 2 partition root conditionsabove are true and at least one CPU from “cpuset.cpus” isgranted by the parent cgroup.
A partition root can become invalid if none of CPUs requestedin “cpuset.cpus” can be granted by the parent cgroup or theparent cgroup is no longer a partition root itself. In thiscase, it is not a real partition even though the restrictionof the first partition root condition above will still apply.The cpu affinity of all the tasks in the cgroup will then beassociated with CPUs in the nearest ancestor partition.
An invalid partition root can be transitioned back to areal partition root if at least one of the requested CPUscan now be granted by its parent. In this case, the cpuaffinity of all the tasks in the formerly invalid partitionwill be associated to the CPUs of the newly formed partition.Changing the partition state of an invalid partition root to“member” is always allowed even if child cpusets are present.
Device controller¶
Device controller manages access to device files. It includes bothcreation of new device files (using mknod), and access to theexisting device files.
Cgroup v2 device controller has no interface files and is implementedon top of cgroup BPF. To control access to device files, a user maycreate bpf programs of the BPF_CGROUP_DEVICE type and attach themto cgroups. On an attempt to access a device file, correspondingBPF programs will be executed, and depending on the return valuethe attempt will succeed or fail with -EPERM.
A BPF_CGROUP_DEVICE program takes a pointer to the bpf_cgroup_dev_ctxstructure, which describes the device access attempt: access type(mknod/read/write) and device (type, major and minor numbers).If the program returns 0, the attempt fails with -EPERM, otherwiseit succeeds.
An example of BPF_CGROUP_DEVICE program may be found in the kernelsource tree in the tools/testing/selftests/bpf/dev_cgroup.c file.
RDMA¶
The “rdma” controller regulates the distribution and accounting ofRDMA resources.
RDMA Interface Files¶
- rdma.max
A readwrite nested-keyed file that exists for all the cgroupsexcept root that describes current configured resource limitfor a RDMA/IB device.
Lines are keyed by device name and are not ordered.Each line contains space separated resource name and its configuredlimit that can be distributed.
The following nested keys are defined.
hca_handle Maximum number of HCA Handles hca_object Maximum number of HCA Objects An example for mlx4 and ocrdma device follows:
mlx4_0 hca_handle=2 hca_object=2000ocrdma1 hca_handle=3 hca_object=max- rdma.current
A read-only file that describes current resource usage.It exists for all the cgroup except root.
An example for mlx4 and ocrdma device follows:
mlx4_0 hca_handle=1 hca_object=20ocrdma1 hca_handle=1 hca_object=23
HugeTLB¶
The HugeTLB controller allows to limit the HugeTLB usage per control group andenforces the controller limit during page fault.
HugeTLB Interface Files¶
- hugetlb.<hugepagesize>.current
- Show current usage for “hugepagesize” hugetlb. It exists for allthe cgroup except root.
- hugetlb.<hugepagesize>.max
- Set/show the hard limit of “hugepagesize” hugetlb usage.The default value is “max”. It exists for all the cgroup except root.
- hugetlb.<hugepagesize>.events
A read-only flat-keyed file which exists on non-root cgroups.
- max
- The number of allocation failure due to HugeTLB limit
- hugetlb.<hugepagesize>.events.local
- Similar to hugetlb.<hugepagesize>.events but the fields in the fileare local to the cgroup i.e. not hierarchical. The file modified eventgenerated on this file reflects only the local events.
Misc¶
perf_event¶
perf_event controller, if not mounted on a legacy hierarchy, isautomatically enabled on the v2 hierarchy so that perf events canalways be filtered by cgroup v2 path. The controller can still bemoved to a legacy hierarchy after v2 hierarchy is populated.
Non-normative information¶
This section contains information that isn’t considered to be a part ofthe stable kernel API and so is subject to change.
CPU controller root cgroup process behaviour¶
When distributing CPU cycles in the root cgroup each thread in thiscgroup is treated as if it was hosted in a separate child cgroup of theroot cgroup. This child cgroup weight is dependent on its thread nicelevel.
For details of this mapping see sched_prio_to_weight array inkernel/sched/core.c file (values from this array should be scaledappropriately so the neutral - nice 0 - value is 100 instead of 1024).
IO controller root cgroup process behaviour¶
Root cgroup processes are hosted in an implicit leaf child node.When distributing IO resources this implicit child node is taken intoaccount as if it was a normal child cgroup of the root cgroup with aweight value of 200.
Namespace¶
Basics¶
cgroup namespace provides a mechanism to virtualize the view of the“/proc/$PID/cgroup” file and cgroup mounts. The CLONE_NEWCGROUP cloneflag can be used with clone(2) and unshare(2) to create a new cgroupnamespace. The process running inside the cgroup namespace will haveits “/proc/$PID/cgroup” output restricted to cgroupns root. Thecgroupns root is the cgroup of the process at the time of creation ofthe cgroup namespace.
Without cgroup namespace, the “/proc/$PID/cgroup” file shows thecomplete path of the cgroup of a process. In a container setup wherea set of cgroups and namespaces are intended to isolate processes the“/proc/$PID/cgroup” file may leak potential system level informationto the isolated processes. For Example:
# cat /proc/self/cgroup0::/batchjobs/container_id1
The path ‘/batchjobs/container_id1’ can be considered as system-dataand undesirable to expose to the isolated processes. cgroup namespacecan be used to restrict visibility of this path. For example, beforecreating a cgroup namespace, one would see:
# ls -l /proc/self/ns/cgrouplrwxrwxrwx 1 root root 0 2014-07-15 10:37 /proc/self/ns/cgroup -> cgroup:[4026531835]# cat /proc/self/cgroup0::/batchjobs/container_id1
After unsharing a new namespace, the view changes:
# ls -l /proc/self/ns/cgrouplrwxrwxrwx 1 root root 0 2014-07-15 10:35 /proc/self/ns/cgroup -> cgroup:[4026532183]# cat /proc/self/cgroup0::/
When some thread from a multi-threaded process unshares its cgroupnamespace, the new cgroupns gets applied to the entire process (allthe threads). This is natural for the v2 hierarchy; however, for thelegacy hierarchies, this may be unexpected.
A cgroup namespace is alive as long as there are processes inside ormounts pinning it. When the last usage goes away, the cgroupnamespace is destroyed. The cgroupns root and the actual cgroupsremain.
The Root and Views¶
The ‘cgroupns root’ for a cgroup namespace is the cgroup in which theprocess calling unshare(2) is running. For example, if a process in/batchjobs/container_id1 cgroup calls unshare, cgroup/batchjobs/container_id1 becomes the cgroupns root. For theinit_cgroup_ns, this is the real root (‘/’) cgroup.
The cgroupns root cgroup does not change even if the namespace creatorprocess later moves to a different cgroup:
# ~/unshare -c # unshare cgroupns in some cgroup# cat /proc/self/cgroup0::/# mkdir sub_cgrp_1# echo 0 > sub_cgrp_1/cgroup.procs# cat /proc/self/cgroup0::/sub_cgrp_1
Each process gets its namespace-specific view of “/proc/$PID/cgroup”
Processes running inside the cgroup namespace will be able to seecgroup paths (in /proc/self/cgroup) only inside their root cgroup.From within an unshared cgroupns:
# sleep 100000 &[1] 7353# echo 7353 > sub_cgrp_1/cgroup.procs# cat /proc/7353/cgroup0::/sub_cgrp_1
From the initial cgroup namespace, the real cgroup path will bevisible:
$ cat /proc/7353/cgroup0::/batchjobs/container_id1/sub_cgrp_1
From a sibling cgroup namespace (that is, a namespace rooted at adifferent cgroup), the cgroup path relative to its own cgroupnamespace root will be shown. For instance, if PID 7353’s cgroupnamespace root is at ‘/batchjobs/container_id2’, then it will see:
# cat /proc/7353/cgroup0::/../container_id2/sub_cgrp_1
Note that the relative path always starts with ‘/’ to indicate thatits relative to the cgroup namespace root of the caller.
Migration and setns(2)¶
Processes inside a cgroup namespace can move into and out of thenamespace root if they have proper access to external cgroups. Forexample, from inside a namespace with cgroupns root at/batchjobs/container_id1, and assuming that the global hierarchy isstill accessible inside cgroupns:
# cat /proc/7353/cgroup0::/sub_cgrp_1# echo 7353 > batchjobs/container_id2/cgroup.procs# cat /proc/7353/cgroup0::/../container_id2
Note that this kind of setup is not encouraged. A task inside cgroupnamespace should only be exposed to its own cgroupns hierarchy.
setns(2) to another cgroup namespace is allowed when:
- the process has CAP_SYS_ADMIN against its current user namespace
- the process has CAP_SYS_ADMIN against the target cgroupnamespace’s userns
No implicit cgroup changes happen with attaching to another cgroupnamespace. It is expected that the someone moves the attachingprocess under the target cgroup namespace root.
Interaction with Other Namespaces¶
Namespace specific cgroup hierarchy can be mounted by a processrunning inside a non-init cgroup namespace:
# mount -t cgroup2 none $MOUNT_POINT
This will mount the unified cgroup hierarchy with cgroupns root as thefilesystem root. The process needs CAP_SYS_ADMIN against its user andmount namespaces.
The virtualization of /proc/self/cgroup file combined with restrictingthe view of cgroup hierarchy by namespace-private cgroupfs mountprovides a properly isolated cgroup view inside the container.
Information on Kernel Programming¶
This section contains kernel programming information in the areaswhere interacting with cgroup is necessary. cgroup core andcontrollers are not covered.
Filesystem Support for Writeback¶
A filesystem can support cgroup writeback by updatingaddress_space_operations->writepage[s]() to annotate bio’s using thefollowing two functions.
- wbc_init_bio(@wbc, @bio)
- Should be called for each bio carrying writeback data andassociates the bio with the inode’s owner cgroup and thecorresponding request queue. This must be called aftera queue (device) has been associated with the bio andbefore submission.
- wbc_account_cgroup_owner(@wbc, @page, @bytes)
- Should be called for each data segment being written out.While this function doesn’t care exactly when it’s calledduring the writeback session, it’s the easiest and mostnatural to call it as data segments are added to a bio.
With writeback bio’s annotated, cgroup support can be enabled persuper_block by setting SB_I_CGROUPWB in ->s_iflags. This allows forselective disabling of cgroup writeback support which is helpful whencertain filesystem features, e.g. journaled data mode, areincompatible.
wbc_init_bio() binds the specified bio to its cgroup. Depending onthe configuration, the bio may be executed at a lower priority and ifthe writeback session is holding shared resources, e.g. a journalentry, may lead to priority inversion. There is no one easy solutionfor the problem. Filesystems can try to work around specific problemcases by skipping wbc_init_bio() and using bio_associate_blkg()directly.
Deprecated v1 Core Features¶
- Multiple hierarchies including named ones are not supported.
- All v1 mount options are not supported.
- The “tasks” file is removed and “cgroup.procs” is not sorted.
- “cgroup.clone_children” is removed.
- /proc/cgroups is meaningless for v2. Use “cgroup.controllers” fileat the root instead.
Issues with v1 and Rationales for v2¶
Multiple Hierarchies¶
cgroup v1 allowed an arbitrary number of hierarchies and eachhierarchy could host any number of controllers. While this seemed toprovide a high level of flexibility, it wasn’t useful in practice.
For example, as there is only one instance of each controller, utilitytype controllers such as freezer which can be useful in allhierarchies could only be used in one. The issue is exacerbated bythe fact that controllers couldn’t be moved to another hierarchy oncehierarchies were populated. Another issue was that all controllersbound to a hierarchy were forced to have exactly the same view of thehierarchy. It wasn’t possible to vary the granularity depending onthe specific controller.
In practice, these issues heavily limited which controllers could beput on the same hierarchy and most configurations resorted to puttingeach controller on its own hierarchy. Only closely related ones, suchas the cpu and cpuacct controllers, made sense to be put on the samehierarchy. This often meant that userland ended up managing multiplesimilar hierarchies repeating the same steps on each hierarchywhenever a hierarchy management operation was necessary.
Furthermore, support for multiple hierarchies came at a steep cost.It greatly complicated cgroup core implementation but more importantlythe support for multiple hierarchies restricted how cgroup could beused in general and what controllers was able to do.
There was no limit on how many hierarchies there might be, which meantthat a thread’s cgroup membership couldn’t be described in finitelength. The key might contain any number of entries and was unlimitedin length, which made it highly awkward to manipulate and led toaddition of controllers which existed only to identify membership,which in turn exacerbated the original problem of proliferating numberof hierarchies.
Also, as a controller couldn’t have any expectation regarding thetopologies of hierarchies other controllers might be on, eachcontroller had to assume that all other controllers were attached tocompletely orthogonal hierarchies. This made it impossible, or atleast very cumbersome, for controllers to cooperate with each other.
In most use cases, putting controllers on hierarchies which arecompletely orthogonal to each other isn’t necessary. What usually iscalled for is the ability to have differing levels of granularitydepending on the specific controller. In other words, hierarchy maybe collapsed from leaf towards root when viewed from specificcontrollers. For example, a given configuration might not care abouthow memory is distributed beyond a certain level while still wantingto control how CPU cycles are distributed.
Thread Granularity¶
cgroup v1 allowed threads of a process to belong to different cgroups.This didn’t make sense for some controllers and those controllersended up implementing different ways to ignore such situations butmuch more importantly it blurred the line between API exposed toindividual applications and system management interface.
Generally, in-process knowledge is available only to the processitself; thus, unlike service-level organization of processes,categorizing threads of a process requires active participation fromthe application which owns the target process.
cgroup v1 had an ambiguously defined delegation model which got abusedin combination with thread granularity. cgroups were delegated toindividual applications so that they can create and manage their ownsub-hierarchies and control resource distributions along them. Thiseffectively raised cgroup to the status of a syscall-like API exposedto lay programs.
First of all, cgroup has a fundamentally inadequate interface to beexposed this way. For a process to access its own knobs, it has toextract the path on the target hierarchy from /proc/self/cgroup,construct the path by appending the name of the knob to the path, openand then read and/or write to it. This is not only extremely clunkyand unusual but also inherently racy. There is no conventional way todefine transaction across the required steps and nothing can guaranteethat the process would actually be operating on its own sub-hierarchy.
cgroup controllers implemented a number of knobs which would never beaccepted as public APIs because they were just adding control knobs tosystem-management pseudo filesystem. cgroup ended up with interfaceknobs which were not properly abstracted or refined and directlyrevealed kernel internal details. These knobs got exposed toindividual applications through the ill-defined delegation mechanismeffectively abusing cgroup as a shortcut to implementing public APIswithout going through the required scrutiny.
This was painful for both userland and kernel. Userland ended up withmisbehaving and poorly abstracted interfaces and kernel exposing andlocked into constructs inadvertently.
Competition Between Inner Nodes and Threads¶
cgroup v1 allowed threads to be in any cgroups which created aninteresting problem where threads belonging to a parent cgroup and itschildren cgroups competed for resources. This was nasty as twodifferent types of entities competed and there was no obvious way tosettle it. Different controllers did different things.
The cpu controller considered threads and cgroups as equivalents andmapped nice levels to cgroup weights. This worked for some cases butfell flat when children wanted to be allocated specific ratios of CPUcycles and the number of internal threads fluctuated - the ratiosconstantly changed as the number of competing entities fluctuated.There also were other issues. The mapping from nice level to weightwasn’t obvious or universal, and there were various other knobs whichsimply weren’t available for threads.
The io controller implicitly created a hidden leaf node for eachcgroup to host the threads. The hidden leaf had its own copies of allthe knobs withleaf_ prefixed. While this allowed equivalentcontrol over internal threads, it was with serious drawbacks. Italways added an extra layer of nesting which wouldn’t be necessaryotherwise, made the interface messy and significantly complicated theimplementation.
The memory controller didn’t have a way to control what happenedbetween internal tasks and child cgroups and the behavior was notclearly defined. There were attempts to add ad-hoc behaviors andknobs to tailor the behavior to specific workloads which would haveled to problems extremely difficult to resolve in the long term.
Multiple controllers struggled with internal tasks and came up withdifferent ways to deal with it; unfortunately, all the approaches wereseverely flawed and, furthermore, the widely different behaviorsmade cgroup as a whole highly inconsistent.
This clearly is a problem which needs to be addressed from cgroup corein a uniform way.
Other Interface Issues¶
cgroup v1 grew without oversight and developed a large number ofidiosyncrasies and inconsistencies. One issue on the cgroup core sidewas how an empty cgroup was notified - a userland helper binary wasforked and executed for each event. The event delivery wasn’trecursive or delegatable. The limitations of the mechanism also ledto in-kernel event delivery filtering mechanism further complicatingthe interface.
Controller interfaces were problematic too. An extreme example iscontrollers completely ignoring hierarchical organization and treatingall cgroups as if they were all located directly under the rootcgroup. Some controllers exposed a large amount of inconsistentimplementation details to userland.
There also was no consistency across controllers. When a new cgroupwas created, some controllers defaulted to not imposing extrarestrictions while others disallowed any resource usage untilexplicitly configured. Configuration knobs for the same type ofcontrol used widely differing naming schemes and formats. Statisticsand information knobs were named arbitrarily and used differentformats and units even in the same controller.
cgroup v2 establishes common conventions where appropriate and updatescontrollers so that they expose minimal and consistent interfaces.
Controller Issues and Remedies¶
Memory¶
The original lower boundary, the soft limit, is defined as a limitthat is per default unset. As a result, the set of cgroups thatglobal reclaim prefers is opt-in, rather than opt-out. The costs foroptimizing these mostly negative lookups are so high that theimplementation, despite its enormous size, does not even provide thebasic desirable behavior. First off, the soft limit has nohierarchical meaning. All configured groups are organized in a globalrbtree and treated like equal peers, regardless where they are locatedin the hierarchy. This makes subtree delegation impossible. Second,the soft limit reclaim pass is so aggressive that it not justintroduces high allocation latencies into the system, but also impactssystem performance due to overreclaim, to the point where the featurebecomes self-defeating.
The memory.low boundary on the other hand is a top-down allocatedreserve. A cgroup enjoys reclaim protection when it’s within itseffective low, which makes delegation of subtrees possible. It alsoenjoys having reclaim pressure proportional to its overage whenabove its effective low.
The original high boundary, the hard limit, is defined as a strictlimit that can not budge, even if the OOM killer has to be called.But this generally goes against the goal of making the most out of theavailable memory. The memory consumption of workloads varies duringruntime, and that requires users to overcommit. But doing that with astrict upper limit requires either a fairly accurate prediction of theworking set size or adding slack to the limit. Since working set sizeestimation is hard and error prone, and getting it wrong results inOOM kills, most users tend to err on the side of a looser limit andend up wasting precious resources.
The memory.high boundary on the other hand can be set much moreconservatively. When hit, it throttles allocations by forcing theminto direct reclaim to work off the excess, but it never invokes theOOM killer. As a result, a high boundary that is chosen tooaggressively will not terminate the processes, but instead it willlead to gradual performance degradation. The user can monitor thisand make corrections until the minimal memory footprint that stillgives acceptable performance is found.
In extreme cases, with many concurrent allocations and a completebreakdown of reclaim progress within the group, the high boundary canbe exceeded. But even then it’s mostly better to satisfy theallocation from the slack available in other groups or the rest of thesystem than killing the group. Otherwise, memory.max is there tolimit this type of spillover and ultimately contain buggy or evenmalicious applications.
Setting the original memory.limit_in_bytes below the current usage wassubject to a race condition, where concurrent charges could cause thelimit setting to fail. memory.max on the other hand will first set thelimit to prevent new charges, and then reclaim and OOM kill until thenew limit is met - or the task writing to memory.max is killed.
The combined memory+swap accounting and limiting is replaced by realcontrol over swap space.
The main argument for a combined memory+swap facility in the originalcgroup design was that global or parental pressure would always beable to swap all anonymous memory of a child group, regardless of thechild’s own (possibly untrusted) configuration. However, untrustedgroups can sabotage swapping by other means - such as referencing itsanonymous memory in a tight loop - and an admin can not assume fullswappability when overcommitting untrusted jobs.
For trusted jobs, on the other hand, a combined counter is not anintuitive userspace interface, and it flies in the face of the ideathat cgroup controllers should account and limit specific physicalresources. Swap space is a resource like all others in the system,and that’s why unified hierarchy allows distributing it separately.