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.
- favordynmods
Reduce the latencies of dynamic cgroup modifications such astask migrations and controller on/offs at the cost of makinghot path operations such as forks and exits more expensive.The static usage pattern of creating a cgroup, enablingcontrollers, and then seeding it with CLONE_INTO_CGROUP isnot affected by this option.
- 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).
- memory_hugetlb_accounting
Count HugeTLB memory usage towards the cgroup’s overallmemory usage for the memory controller (for the purpose ofstatistics reporting and memory protetion). This is a newbehavior that could regress existing setups, so it must beexplicitly opted in with this mount option.
A few caveats to keep in mind:
There is no HugeTLB pool management involved in the memorycontroller. The pre-allocated pool does not belong to anyone.Specifically, when a new HugeTLB folio is allocated tothe pool, it is not accounted for from the perspective of thememory controller. It is only charged to a cgroup when it isactually used (for e.g at page fault time). Host memoryovercommit management has to consider this when configuringhard limits. In general, HugeTLB pool management should bedone via other mechanisms (such as the HugeTLB controller).
Failure to charge a HugeTLB folio to the memory controllerresults in SIGBUS. This could happen even if the HugeTLB poolstill has pages available (but the cgroup limit is hit andreclaim attempt fails).
Charging HugeTLB memory towards the memory controller affectsmemory protection and reclaim dynamics. Any userspace tuning(of low, min limits for e.g) needs to take this into account.
HugeTLB pages utilized while this option is not selectedwill not be tracked by the memory controller (even if cgroupv2 is remounted later on).
- pids_localevents
The option restores v1-like behavior of pids.events:max, that is onlylocal (inside cgroup proper) fork failures are counted. Without thisoption pids.events.max represents any pids.max enforcemnt acrosscgroup’s subtree.
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.
Currently, the following controllers are threaded and can be enabledin a threaded cgroup:
- cpu- cpuset- perf_event- pids
[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¶
Availability¶
A controller is available in a cgroup when it is supported by the kernel (i.e.,compiled in, not disabled and not attached to a v1 hierarchy) and listed in the“cgroup.controllers” file. Availability means the controller’s interface filesare exposed in the cgroup’s directory, allowing the distribution of the targetresource to be observed or controlled within that cgroup.
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, filesoutside the namespace should be hidden from the delegatee by the meansof at least mount namespacing, and the kernel rejects writes to allfiles on a namespace root from inside the cgroup namespace, except forthose files listed in “/sys/kernel/cgroup/delegate” (including“cgroup.procs”, “cgroup.threads”, “cgroup.subtree_control”, etc.).
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 up to 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 up to 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 up to 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.
- nr_subsys_<cgroup_subsys>
Total number of live cgroup subsystems (e.g memorycgroup) at and beneath the current cgroup.
- nr_dying_subsys_<cgroup_subsys>
Total number of dying cgroup subsystems (e.g. memorycgroup) at and beneath the current cgroup.
- cgroup.stat.local
A read-only flat-keyed file which exists in non-root cgroups.The following entry is defined:
- frozen_usec
Cumulative time that this cgroup has spent between freezing andthawing, regardless of whether by self or ancestor groups.NB: (not) reaching “frozen” state is not accounted here.
Using the following ASCII representation of a cgroup’s freezerstate,
1 _____frozen 0 __/ \__ ab cdthe duration being measured is the span between a and c.
- 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.
- cgroup.kill
A write-only single value file which exists in non-root cgroups.The only allowed value is “1”.
Writing “1” to the file causes the cgroup and all descendant cgroups tobe killed. This means that all processes located in the affected cgrouptree will be killed via SIGKILL.
Killing a cgroup tree will deal with concurrent forks appropriately andis protected against migrations.
In a threaded cgroup, writing this file fails with EOPNOTSUPP askilling cgroups is a process directed operation, i.e. it affectsthe whole thread-group.
- cgroup.pressure
A read-write single value file that allowed values are “0” and “1”.The default is “1”.
Writing “0” to the file will disable the cgroup PSI accounting.Writing “1” to the file will re-enable the cgroup PSI accounting.
This control attribute is not hierarchical, so disable or enable PSIaccounting in a cgroup does not affect PSI accounting in descendantsand doesn’t need pass enablement via ancestors from root.
The reason this control attribute exists is that PSI accounts stalls foreach cgroup separately and aggregates it at each level of the hierarchy.This may cause non-negligible overhead for some workloads when underdeep level of the hierarchy, in which case this control attribute canbe used to disable PSI accounting in the non-leaf cgroups.
- irq.pressure
A read-write nested-keyed file.
Shows pressure stall information for IRQ/SOFTIRQ. SeeDocumentation/accounting/psi.rst for details.
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 cpu controller doesn’t yet support the (bandwidth) control ofrealtime processes. For a kernel built with the CONFIG_RT_GROUP_SCHED optionenabled for group scheduling of realtime processes, the cpu controller can onlybe enabled when all RT processes are in the root cgroup. Be aware that systemmanagement software may already have placed RT processes into non-root cgroupsduring the system boot process, and these processes may need to be moved to theroot cgroup before the cpu controller can be enabled with aCONFIG_RT_GROUP_SCHED enabled kernel.
With CONFIG_RT_GROUP_SCHED disabled, this limitation does not apply and some ofthe interface files either affect realtime processes or account for them. Seethe following section for details. Only the cpu controller is affected byCONFIG_RT_GROUP_SCHED. Other controllers can be used for the resource control ofrealtime processes irrespective of CONFIG_RT_GROUP_SCHED.
CPU Interface Files¶
The interaction of a process with the cpu controller depends on its schedulingpolicy and the underlying scheduler. From the point of view of the cpu controller,processes can be categorized as follows:
Processes under the fair-class scheduler
Processes under a BPF scheduler with the
cgroup_set_weightcallbackEverything else:
SCHED_{FIFO,RR,DEADLINE}and processes under a BPF schedulerwithout thecgroup_set_weightcallback
For details on when a process is under the fair-class scheduler or a BPF scheduler,check outDocumentation/scheduler/sched-ext.rst.
For each of the following interface files, the above categorieswill be referred to. 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, which account for all theprocesses in the cgroup:
usage_usec
user_usec
system_usec
and the following five when the controller is enabled, which account foronly the processes under the fair-class scheduler:
nr_periods
nr_throttled
throttled_usec
nr_bursts
burst_usec
- cpu.weight
A read-write single value file which exists on non-rootcgroups. The default is “100”.
For non idle groups (cpu.idle = 0), the weight is in therange [1, 10000].
If the cgroup has been configured to be SCHED_IDLE (cpu.idle = 1),then the weight will show as a 0.
This file affects only processes under the fair-class scheduler and a BPFscheduler with the
cgroup_set_weightcallback depending on what thecallback actually does.- 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.
This file affects only processes under the fair-class scheduler and a BPFscheduler with the
cgroup_set_weightcallback depending on what thecallback actually does.- 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 up to $MAX in each$PERIOD duration. “max” for $MAX indicates no limit. If onlyone number is written, $MAX is updated.
This file affects only processes under the fair-class scheduler.
- cpu.max.burst
A read-write single value file which exists on non-rootcgroups. The default is “0”.
The burst in the range [0, $MAX].
This file affects only processes under the fair-class scheduler.
- cpu.pressure
A read-write nested-keyed file.
Shows pressure stall information for CPU. SeeDocumentation/accounting/psi.rst for details.
This file accounts for all the processes in the cgroup.
- 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,including those of realtime processes.
The requested minimum utilization (protection) is always capped bythe current value for the maximum utilization (limit), i.e.cpu.uclamp.max.
This file affects all the processes in the cgroup.
- 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,including those of realtime processes.
This file affects all the processes in the cgroup.
- cpu.idle
A read-write single value file which exists on non-root cgroups.The default is 0.
This is the cgroup analog of the per-task SCHED_IDLE sched policy.Setting this value to a 1 will make the scheduling policy of thecgroup SCHED_IDLE. The threads inside the cgroup will retain theirown relative priorities, but the cgroup itself will be treated asvery low priority relative to its peers.
This file affects only processes under the fair-class scheduler.
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. 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. The highlimit should be used in scenarios where an external processmonitors the limited cgroup to alleviate heavy reclaimpressure.
If memory.high is opened with O_NONBLOCK then the synchronousreclaim is bypassed. This is useful for admin processes thatneed to dynamically adjust the job’s memory limits withoutexpending their own CPU resources on memory reclamation. Thejob will trigger the reclaim and/or get throttled on itsnext charge request.
Please note that with O_NONBLOCK, there is a chance that thetarget memory cgroup may take indefinite amount of time toreduce usage below the limit due to delayed charge request orbusy-hitting its memory to slow down reclaim.
- memory.max
A read-write single value file which exists on non-rootcgroups. The default is “max”.
Memory usage hard limit. This is the main mechanism to limitmemory usage of a cgroup. If a cgroup’s memory usage reachesthis limit and can’t be reduced, the OOM killer is invoked inthe cgroup. Under certain circumstances, the usage may goover the limit temporarily.
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.
If memory.max is opened with O_NONBLOCK, then the synchronousreclaim and oom-kill are bypassed. This is useful for adminprocesses that need to dynamically adjust the job’s memory limitswithout expending their own CPU resources on memory reclamation.The job will trigger the reclaim and/or oom-kill on its nextcharge request.
Please note that with O_NONBLOCK, there is a chance that thetarget memory cgroup may take indefinite amount of time toreduce usage below the limit due to delayed charge request orbusy-hitting its memory to slow down reclaim.
- memory.reclaim
A write-only nested-keyed file which exists for all cgroups.
This is a simple interface to trigger memory reclaim in thetarget cgroup.
Example:
echo "1G" > memory.reclaimPlease note that the kernel can over or under reclaim fromthe target cgroup. If less bytes are reclaimed than thespecified amount, -EAGAIN is returned.
Please note that the proactive reclaim (triggered by thisinterface) is not meant to indicate memory pressure on thememory cgroup. Therefore socket memory balancing triggered bythe memory reclaim normally is not exercised in this case.This means that the networking layer will not adapt based onreclaim induced by memory.reclaim.
The following nested keys are defined.
swappiness
Swappiness value to reclaim with
Specifying a swappiness value instructs the kernel to performthe reclaim with that swappiness value. Note that this has thesame semantics as vm.swappiness applied to memcg reclaim withall the existing limitations and potential future extensions.
The valid range for swappiness is [0-200, max], settingswappiness=max exclusively reclaims anonymous memory.
- memory.peak
A read-write single value file which exists on non-root cgroups.
The max memory usage recorded for the cgroup and its descendants sinceeither the creation of the cgroup or the most recent reset for that FD.
A write of any non-empty string to this file resets it to thecurrent memory usage for subsequent reads through the samefile descriptor.
- 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 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.
- oom_group_kill
The number of times a group OOM has occurred.
- 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!
If the entry has no per-node counter (or not show in thememory.numa_stat). We use ‘npn’ (non-per-node) as the tagto indicate that it will not show in the memory.numa_stat.
- anon
Amount of memory used in anonymous mappings such as
brk(),sbrk(), and mmap(MAP_ANONYMOUS). Note thatsome kernel configurations might account complete largerallocations (e.g., THP) if only some, but not all thememory of such an allocation is mapped anymore.- file
Amount of memory used to cache filesystem data,including tmpfs and shared memory.
- kernel (npn)
Amount of total kernel memory, including(kernel_stack, pagetables, percpu, vmalloc, slab) inaddition to other kernel memory use cases.
- kernel_stack
Amount of memory allocated to kernel stacks.
- pagetables
Amount of memory allocated for page tables.
- sec_pagetables
Amount of memory allocated for secondary page tables,this currently includes KVM mmu allocations on x86and arm64 and IOMMU page tables.
- percpu (npn)
Amount of memory used for storing per-cpu kerneldata structures.
- sock (npn)
Amount of memory used in network transmission buffers
- vmalloc (npn)
Amount of memory used for vmap backed memory.
- shmem
Amount of cached filesystem data that is swap-backed,such as tmpfs, shm segments, shared anonymous mmap()s
- zswap
Amount of memory consumed by the zswap compression backend.
- zswapped
Amount of application memory swapped out to zswap.
- file_mapped
Amount of cached filesystem data mapped with mmap(). Notethat some kernel configurations might account completelarger allocations (e.g., THP) if only some, but notnot all the memory of such an allocation is mapped.
- 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
- swapcached
Amount of swap cached in memory. The swapcache is accountedagainst both memory and swap usage.
- anon_thp
Amount of memory used in anonymous mappings backed bytransparent hugepages
- file_thp
Amount of cached filesystem data backed by transparenthugepages
- shmem_thp
Amount of shm, tmpfs, shared anonymous mmap()s 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.
- slab (npn)
Amount of memory used for storing in-kernel datastructures.
- 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
- pswpin (npn)
Number of pages swapped into memory
- pswpout (npn)
Number of pages swapped out of memory
- pgscan (npn)
Amount of scanned pages (in an inactive LRU list)
- pgsteal (npn)
Amount of reclaimed pages
- pgscan_kswapd (npn)
Amount of scanned pages by kswapd (in an inactive LRU list)
- pgscan_direct (npn)
Amount of scanned pages directly (in an inactive LRU list)
- pgscan_khugepaged (npn)
Amount of scanned pages by khugepaged (in an inactive LRU list)
- pgscan_proactive (npn)
Amount of scanned pages proactively (in an inactive LRU list)
- pgsteal_kswapd (npn)
Amount of reclaimed pages by kswapd
- pgsteal_direct (npn)
Amount of reclaimed pages directly
- pgsteal_khugepaged (npn)
Amount of reclaimed pages by khugepaged
- pgsteal_proactive (npn)
Amount of reclaimed pages proactively
- pgfault (npn)
Total number of page faults incurred
- pgmajfault (npn)
Number of major page faults incurred
- pgrefill (npn)
Amount of scanned pages (in an active LRU list)
- pgactivate (npn)
Amount of pages moved to the active LRU list
- pgdeactivate (npn)
Amount of pages moved to the inactive LRU list
- pglazyfree (npn)
Amount of pages postponed to be freed under memory pressure
- pglazyfreed (npn)
Amount of reclaimed lazyfree pages
- swpin_zero
Number of pages swapped into memory and filled with zero, where I/Owas optimized out because the page content was detected to be zeroduring swapout.
- swpout_zero
Number of zero-filled pages swapped out with I/O skipped due to thecontent being detected as zero.
- zswpin
Number of pages moved in to memory from zswap.
- zswpout
Number of pages moved out of memory to zswap.
- zswpwb
Number of pages written from zswap to swap.
- thp_fault_alloc (npn)
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 (npn)
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.
- thp_swpout (npn)
Number of transparent hugepages which are swapout in one piecewithout splitting.
- thp_swpout_fallback (npn)
Number of transparent hugepages which were split before swapout.Usually because failed to allocate some continuous swap spacefor the huge page.
- numa_pages_migrated (npn)
Number of pages migrated by NUMA balancing.
- numa_pte_updates (npn)
Number of pages whose page table entries are modified byNUMA balancing to produce NUMA hinting faults on access.
- numa_hint_faults (npn)
Number of NUMA hinting faults.
- pgdemote_kswapd
Number of pages demoted by kswapd.
- pgdemote_direct
Number of pages demoted directly.
- pgdemote_khugepaged
Number of pages demoted by khugepaged.
- pgdemote_proactive
Number of pages demoted by proactively.
- hugetlb
Amount of memory used by hugetlb pages. This metric only showsup if hugetlb usage is accounted for in memory.current (i.e.cgroup is mounted with the memory_hugetlb_accounting option).
- memory.numa_stat
A read-only nested-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 informationper node on the state of the memory management system.
This is useful for providing visibility into the NUMA localityinformation within an memcg since the pages are allowed to beallocated from any physical node. One of the use case is evaluatingapplication performance by combining this information with theapplication’s CPU allocation.
All memory amounts are in bytes.
The output format of memory.numa_stat is:
type N0=<bytes in node 0> N1=<bytes in node 1> ...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!
The entries can refer to the memory.stat.
- 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.peak
A read-write single value file which exists on non-root cgroups.
The max swap usage recorded for the cgroup and its descendants sincethe creation of the cgroup or the most recent reset for that FD.
A write of any non-empty string to this file resets it to thecurrent memory usage for subsequent reads through the samefile descriptor.
- 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.zswap.current
A read-only single value file which exists on non-rootcgroups.
The total amount of memory consumed by the zswap compressionbackend.
- memory.zswap.max
A read-write single value file which exists on non-rootcgroups. The default is “max”.
Zswap usage hard limit. If a cgroup’s zswap pool reaches thislimit, it will refuse to take any more stores before existingentries fault back in or are written out to disk.
- memory.zswap.writeback
A read-write single value file. The default value is “1”.Note that this setting is hierarchical, i.e. the writeback would beimplicitly disabled for child cgroups if the upper hierarchydoes so.
When this is set to 0, all swapping attempts to swapping devicesare disabled. This included both zswap writebacks, and swapping dueto zswap store failures. If the zswap store failures are recurring(for e.g if the pages are incompressible), users can observereclaim inefficiency after disabling writeback (because the samepages might be rejected again and again).
Note that this is subtly different from setting memory.swap.max to0, as it still allows for pages to be written to the zswap pool.This setting has no effect if zswap is disabled, and swappingis allowed unless memory.swap.max is set to 0.
- memory.pressure
A read-only nested-keyed file.
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 which 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 which 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-keyed file.
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.
IO Priority¶
A single attribute controls the behavior of the I/O priority cgroup policy,namely the io.prio.class attribute. The following values are accepted forthat attribute:
- no-change
Do not modify the I/O priority class.
- promote-to-rt
For requests that have a non-RT I/O priority class, change it into RT.Also change the priority level of these requests to 4. Do not modifythe I/O priority of requests that have priority class RT.
- restrict-to-be
For requests that do not have an I/O priority class or that have I/Opriority class RT, change it into BE. Also change the priority levelof these requests to 0. Do not modify the I/O priority class ofrequests that have priority class IDLE.
- idle
Change the I/O priority class of all requests into IDLE, the lowestI/O priority class.
- none-to-rt
Deprecated. Just an alias for promote-to-rt.
The following numerical values are associated with the I/O priority policies:
no-change | 0 |
promote-to-rt | 1 |
restrict-to-be | 2 |
idle | 3 |
The numerical value that corresponds to each I/O priority class is as follows:
IOPRIO_CLASS_NONE | 0 |
IOPRIO_CLASS_RT (real-time) | 1 |
IOPRIO_CLASS_BE (best effort) | 2 |
IOPRIO_CLASS_IDLE | 3 |
The algorithm to set the I/O priority class for a request is as follows:
If I/O priority class policy is promote-to-rt, change the request I/Opriority class to IOPRIO_CLASS_RT and change the request I/O prioritylevel to 4.
If I/O priority class policy is not promote-to-rt, translate the I/O priorityclass policy into a number, then change the request I/O priority classinto the maximum of the I/O priority class policy number and the numericalI/O priority class.
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 non-root cgroups.
The number of processes currently in the cgroup and itsdescendants.
- pids.peak
A read-only single value file which exists on non-root cgroups.
The maximum value that the number of processes in the cgroup and itsdescendants has ever reached.
- pids.events
A read-only flat-keyed file which exists on non-root cgroups. Unlessspecified otherwise, a value change in this file generates a filemodified event. The following entries are defined.
- max
The number of times the cgroup’s total number of processes hit the pids.maxlimit (see also pids_localevents).
- pids.events.local
Similar to pids.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.
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.
Setting a non-empty value to “cpuset.mems” causes memory oftasks within the cgroup to be migrated to the designated nodes ifthey are currently using memory outside of the designated nodes.
There is a cost for this memory migration. The migrationmay not be complete and some memory pages may be left behind.So it is recommended that “cpuset.mems” should be set properlybefore spawning new tasks into the cpuset. Even if there isa need to change “cpuset.mems” with active tasks, it shouldn’tbe done frequently.
- 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.exclusive
A read-write multiple values file which exists on non-rootcpuset-enabled cgroups.
It lists all the exclusive CPUs that are allowed to be usedto create a new cpuset partition. Its value is not usedunless the cgroup becomes a valid partition root. See the“cpuset.cpus.partition” section below for a description of whata cpuset partition is.
When the cgroup becomes a partition root, the actual exclusiveCPUs that are allocated to that partition are listed in“cpuset.cpus.exclusive.effective” which may be differentfrom “cpuset.cpus.exclusive”. If “cpuset.cpus.exclusive”has previously been set, “cpuset.cpus.exclusive.effective”is always a subset of it.
Users can manually set it to a value that is different from“cpuset.cpus”. One constraint in setting it is that the list ofCPUs must be exclusive with respect to “cpuset.cpus.exclusive”of its sibling. If “cpuset.cpus.exclusive” of a sibling cgroupisn’t set, its “cpuset.cpus” value, if set, cannot be a subsetof it to leave at least one CPU available when the exclusiveCPUs are taken away.
For a parent cgroup, any one of its exclusive CPUs can onlybe distributed to at most one of its child cgroups. Having anexclusive CPU appearing in two or more of its child cgroups isnot allowed (the exclusivity rule). A value that violates theexclusivity rule will be rejected with a write error.
The root cgroup is a partition root and all its available CPUsare in its exclusive CPU set.
- cpuset.cpus.exclusive.effective
A read-only multiple values file which exists on all non-rootcpuset-enabled cgroups.
This file shows the effective set of exclusive CPUs thatcan be used to create a partition root. The contentof this file will always be a subset of its parent’s“cpuset.cpus.exclusive.effective” if its parent is not the rootcgroup. It will also be a subset of “cpuset.cpus.exclusive”if it is set. If “cpuset.cpus.exclusive” is not set, it istreated to have an implicit value of “cpuset.cpus” in theformation of local partition.
- cpuset.cpus.isolated
A read-only and root cgroup only multiple values file.
This file shows the set of all isolated CPUs used in existingisolated partitions. It will be empty if no isolated partitionis created.
- 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.
“member”
Non-root member of a partition
“root”
Partition root
“isolated”
Partition root without load balancing
A cpuset partition is a collection of cpuset-enabled cgroups witha partition root at the top of the hierarchy and its descendantsexcept those that are separate partition roots themselves andtheir descendants. A partition has exclusive access to theset of exclusive CPUs allocated to it. Other cgroups outsideof that partition cannot use any CPUs in that set.
There are two types of partitions - local and remote. A localpartition is one whose parent cgroup is also a valid partitionroot. A remote partition is one whose parent cgroup is not avalid partition root itself. Writing to “cpuset.cpus.exclusive”is optional for the creation of a local partition as its“cpuset.cpus.exclusive” file will assume an implicit value thatis the same as “cpuset.cpus” if it is not set. Writing theproper “cpuset.cpus.exclusive” values down the cgroup hierarchybefore the target partition root is mandatory for the creationof a remote partition.
Currently, a remote partition cannot be created under a localpartition. All the ancestors of a remote partition root exceptthe root cgroup cannot be a partition root.
The root cgroup is always a partition root and its state cannotbe changed. All other non-root cgroups start out as “member”.
When set to “root”, the current cgroup is the root of a newpartition or scheduling domain. The set of exclusive CPUs isdetermined by the value of its “cpuset.cpus.exclusive.effective”.
When set to “isolated”, the CPUs in that partition will be inan isolated state without any load balancing from the schedulerand excluded from the unbound workqueues. Tasks placed in sucha partition with multiple CPUs should be carefully distributedand bound to each of the individual CPUs for optimal performance.
A partition root (“root” or “isolated”) can be in one of thetwo possible states - valid or invalid. An invalid partitionroot is in a degraded state where some state information maybe retained, but behaves more like a “member”.
All possible state transitions among “member”, “root” and“isolated” are allowed.
On read, the “cpuset.cpus.partition” file can show the followingvalues.
“member”
Non-root member of a partition
“root”
Partition root
“isolated”
Partition root without load balancing
“root invalid (<reason>)”
Invalid partition root
“isolated invalid (<reason>)”
Invalid isolated partition root
In the case of an invalid partition root, a descriptive string onwhy the partition is invalid is included within parentheses.
For a local partition root to be valid, the following conditionsmust be met.
The parent cgroup is a valid partition root.
The “cpuset.cpus.exclusive.effective” file cannot be empty,though it may contain offline CPUs.
The “cpuset.cpus.effective” cannot be empty unless there isno task associated with this partition.
For a remote partition root to be valid, all the above conditionsexcept the first one must be met.
External events like hotplug or changes to “cpuset.cpus” or“cpuset.cpus.exclusive” can cause a valid partition root tobecome invalid and vice versa. Note that a task cannot bemoved to a cgroup with empty “cpuset.cpus.effective”.
A valid non-root parent partition may distribute out all its CPUsto its child local partitions when there is no task associatedwith it.
Care must be taken to change a valid partition root to “member”as all its child local partitions, if present, will becomeinvalid causing disruption to tasks running in those childpartitions. These inactivated partitions could be recovered iftheir parent is switched back to a partition root with a propervalue in “cpuset.cpus” or “cpuset.cpus.exclusive”.
Poll and inotify events are triggered whenever the state of“cpuset.cpus.partition” changes. That includes changes causedby write to “cpuset.cpus.partition”, cpu hotplug or otherchanges that modify the validity status of the partition.This will allow user space agents to monitor unexpected changesto “cpuset.cpus.partition” without the need to do continuouspolling.
A user can pre-configure certain CPUs to an isolated statewith load balancing disabled at boot time with the “isolcpus”kernel boot command line option. If those CPUs are to be putinto a partition, they have to be used in an isolated partition.
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 type BPF_PROG_TYPE_CGROUP_DEVICE and attachthem to cgroups with BPF_CGROUP_DEVICE flag. On an attempt to access adevice file, corresponding BPF programs will be executed, and dependingon the return value the attempt will succeed or fail with -EPERM.
A BPF_PROG_TYPE_CGROUP_DEVICE program takes a pointer to thebpf_cgroup_dev_ctx structure, 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, otherwise itsucceeds.
An example of BPF_PROG_TYPE_CGROUP_DEVICE program may be found intools/testing/selftests/bpf/progs/dev_cgroup.c in the kernel source tree.
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
DMEM¶
The “dmem” controller regulates the distribution and accounting ofdevice memory regions. Because each memory region may have its own page size,which does not have to be equal to the system page size, the units are always bytes.
DMEM Interface Files¶
- dmem.max, dmem.min, dmem.low
A readwrite nested-keyed file that exists for all the cgroupsexcept root that describes current configured resource limitfor a region.
An example for xe follows:
drm/0000:03:00.0/vram0 1073741824drm/0000:03:00.0/stolen maxThe semantics are the same as for the memory cgroup controller, and arecalculated in the same way.
- dmem.capacity
A read-only file that describes maximum region capacity.It only exists on the root cgroup. Not all memory can beallocated by cgroups, as the kernel reserves some forinternal use.
An example for xe follows:
drm/0000:03:00.0/vram0 8514437120drm/0000:03:00.0/stolen 67108864- dmem.current
A read-only file that describes current resource usage.It exists for all the cgroup except root.
An example for xe follows:
drm/0000:03:00.0/vram0 12550144drm/0000:03:00.0/stolen 8650752
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.
- hugetlb.<hugepagesize>.numa_stat
Similar to memory.numa_stat, it shows the numa information of thehugetlb pages of <hugepagesize> in this cgroup. Only active inuse hugetlb pages are included. The per-node values are in bytes.
Misc¶
The Miscellaneous cgroup provides the resource limiting and trackingmechanism for the scalar resources which cannot be abstracted like the othercgroup resources. Controller is enabled by the CONFIG_CGROUP_MISC configoption.
A resource can be added to the controller viaenummisc_res_type{} in theinclude/linux/misc_cgroup.h file and the corresponding name via misc_res_name[]in the kernel/cgroup/misc.c file. Provider of the resource must set itscapacity prior to using the resource by callingmisc_cg_set_capacity().
Once a capacity is set then the resource usage can be updated using charge anduncharge APIs. All of the APIs to interact with misc controller are ininclude/linux/misc_cgroup.h.
Misc Interface Files¶
Miscellaneous controller provides 3 interface files. If two misc resources (res_a and res_b) are registered then:
- misc.capacity
A read-only flat-keyed file shown only in the root cgroup. It showsmiscellaneous scalar resources available on the platform along withtheir quantities:
$ cat misc.capacityres_a 50res_b 10- misc.current
A read-only flat-keyed file shown in the all cgroups. It showsthe current usage of the resources in the cgroup and its children.:
$ cat misc.currentres_a 3res_b 0- misc.peak
A read-only flat-keyed file shown in all cgroups. It shows thehistorical maximum usage of the resources in the cgroup and itschildren.:
$ cat misc.peakres_a 10res_b 8- misc.max
A read-write flat-keyed file shown in the non root cgroups. Allowedmaximum usage of the resources in the cgroup and its children.:
$ cat misc.maxres_a maxres_b 4Limit can be set by:
# echo res_a 1 > misc.maxLimit can be set to max by:
# echo res_a max > misc.maxLimits can be set higher than the capacity value in the misc.capacityfile.
- misc.events
A read-only flat-keyed file which exists on non-root cgroups. Thefollowing entries are defined. Unless specified otherwise, a valuechange in this file generates a file modified event. All fields inthis file are hierarchical.
- max
The number of times the cgroup’s resource usage wasabout to go over the max boundary.
- misc.events.local
Similar to misc.events but the fields in the file are local to thecgroup i.e. not hierarchical. The file modified event generated onthis file reflects only the local events.
Migration and Ownership¶
A miscellaneous scalar resource is charged to the cgroup in which it is usedfirst, and stays charged to that cgroup until that resource is freed. Migratinga process to a different cgroup does not move the charge to the destinationcgroup where the process has moved.
Others¶
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->writepages() 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, @folio, @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 skippingwbc_init_bio() and usingbio_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” or“cgroup.stat” files at 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.