本文是关于cgroup v2版本的设计、接口和协定方面的官方文档。描述了cgroup的核心和特定控制器行为在用户层面可见的方方面面。并且cgroup所有之后的改动都将在此文档中体现,v1版本的文档位于内核的Documentation/cgroup-v1/目录。

This is the authoritative documentation on the design, interface and conventions of cgroup v2. It describes all userland-visible aspects
of cgroup including core and specific controller behaviors. All future changes must be reflected in this document. Documentation for
v1 is available under Documentation/cgroup-v1/.

CONTENTS 内容

  1. Introduction 介绍
    1-1. Terminology 术语
    1-2. What is cgroup? cgroup是什么?
  2. Basic Operations 基础操作
    2-1. Mounting 挂载
    2-2. Organizing Processes and Threads 组织进程和线程
    2-2-1. Processes 进程
    2-2-2. Threads 线程
    2-3. [Un]populated Notification
    2-4. Controlling Controllers 可控控制器
    2-4-1. Enabling and Disabling 使能和禁止
    2-4-2. Top-down Constraint 自上而下的约束
    2-4-3. No Internal Process Constraint 无内部进程约束
    2-5. Delegation 委托
    2-5-1. Model of Delegation 委托模型
    2-5-2. Delegation Containment 委托抑制
    2-6. Guidelines 指南
    2-6-1. Organize Once and Control 组织一次和控制
    2-6-2. Avoid Name Collisions 名称冲突避免
  3. Resource Distribution Models 资源分布模型
    3-1. Weights 权重
    3-2. Limits 限度
    3-3. Protections 保护
    3-4. Allocations 分配
  4. Interface Files 接口文件
    4-1. Format 格式
    4-2. Conventions 约定
    4-3. Core Interface Files 核心接口文件
  5. Controllers 控制器
    5-1. CPU 中央处理器
    5-1-1. CPU Interface Files 处理器接口文件
    5-2. Memory 内存
    5-2-1. Memory Interface Files 内存接口文件
    5-2-2. Usage Guidelines 使用指南
    5-2-3. Memory Ownership 内存所有权
    5-3. IO 输入输出
    5-3-1. IO Interface Files 输入输出接口文件
    5-3-2. Writeback 回写
    5-4. PID 进程ID
    5-4-1. PID Interface Files 进程ID接口文件
    5-5. RDMA 远程DMA
    5-5-1. RDMA Interface Files 远程DMA接口文件
    5-6. Misc 杂项
    5-6-1. perf_event 性能事件
  6. Namespace 命名空间
    6-1. Basics 基础
    6-2. The Root and Views 根和视图
    6-3. Migration and setns(2) 迁移和setns(2)
    6-4. Interaction with Other Namespaces 与其它命名空间交互
    P. Information on Kernel Programming 内核编程相关信息
    P-1. Filesystem Support for Writeback 文件系统对回写的支持
    D. Deprecated v1 Core Features 废弃的v1版核心功能
    R. Issues with v1 and Rationales for v2 v1版问题及v2版原理
    R-1. Multiple Hierarchies 多层级体系
    R-2. Thread Granularity 线程粒度
    R-3. Competition Between Inner Nodes and Threads 内部节点与线程间的竞争
    R-4. Other Interface Issues 其它接口问题
    R-5. Controller Issues and Remedies 控制器问题及扑救措施
    R-5-1. Memory 内存

Introduction 介绍

Terminology 术语

“cgroup"代表"control group”,并且字母都是小写格式。此处的单数形式用于指代整个cgroup特性,也可作为"cgroup controllers"中的一个修饰词。当明确的引用多个不同的control groups时,使用复数形式"cgroups"。

“cgroup” stands for “control group” and is never capitalized. The singular form is used to designate the whole feature and also as a
qualifier as in “cgroup controllers”. When explicitly referring to multiple individual control groups, the plural form “cgroups” is used.

What is cgroup? cgroup是什么?

cgroup机制可实现按层级体系组织进程,并且将系统资源以一种可控和可配置的方式在此进程层级上分布。

cgroup is a mechanism to organize processes hierarchically and distribute system resources along the hierarchy in a controlled and
configurable manner.

cgroup大体由两部分组成 - 核心和控制器。cgroup核心主要负责按照层级组织进程。cgroup控制器通常负责在层级间分布特定类别的系统资源,不过工具类控制器除外。

cgroup is largely composed of two parts - the core and controllers. cgroup core is primarily responsible for hierarchically organizing
processes. A cgroup controller is usually responsible for distributing a specific type of system resource along the hierarchy
although there are utility controllers which serve purposes other than resource distribution.

cgroup生成一个树状结构,系统中的每个进程属于一个并且仅一个cgroup。进程的所有线程属于同一个cgroup。创建时,所有的进程归入和父进程当时相同的cgroup。进程可被迁移到另外的cgroup中。进程的迁移不影响已经存在的其子辈进程。

cgroups form a tree structure and every process in the system belongs to one and only one cgroup. All threads of a process belong to the
same cgroup. On creation, all processes are put in the cgroup that the parent process belongs to at the time. A process can be migrated
to another cgroup. Migration of a process doesn’t affect already existing descendant processes.

遵循特定结构化的约束,cgroup内的控制器可被选择性的使能或者禁止。所有的控制器行为都是层级化地 - 如果cgroup中的一个控制器被使能,那么这一层及其下层的所有进程都将受到影响。当一个控制器在嵌套结构的cgroup中被使能时,意味着更近一步的资源分布限制。层级中更低层次实行的限制不能循环覆盖较高层级。

Following certain structural constraints, controllers may be enabled or disabled selectively on a cgroup. All controller behaviors are
hierarchical - if a controller is enabled on a cgroup, it affects all processes which belong to the cgroups consisting the inclusive
sub-hierarchy of the cgroup. When a controller is enabled on a nested cgroup, it always restricts the resource distribution further. The
restrictions set closer to the root in the hierarchy can not be overridden from further away.

Basic Operations 基础操作

Mounting 挂载

不同于v1版本,cgroup v2仅有一个层级结构。cgroup v2层级机构可使用如下的mount命令挂载::

Unlike v1, cgroup v2 has only single hierarchy. The cgroup v2 hierarchy can be mounted with the following mount command::

  # mount -t cgroup2 none $MOUNT_POINT

cgroup2文件系统的魔数为0x63677270 (ASCII码"cgrp")。所有支持v2版的控制器,如果没有绑定到v1的层级结构中,都经自动绑定到v2层级结构中,显示在root下。v2层级下未使用的控制器可绑定到其它的层级体系中。这样可实现v2的单层级体系与传统的v1多层级体系的在完全向后兼容的形式下进行联合使用。

cgroup2 filesystem has the magic number 0x63677270 (“cgrp”). All controllers which support v2 and are not bound to a v1 hierarchy are
automatically bound to the v2 hierarchy and show up at the root. Controllers which are not in active use in the v2 hierarchy can be
bound to other hierarchies. This allows mixing v2 hierarchy with the legacy v1 multiple hierarchies in a fully backward compatible way.

~# mount -t cgroup2 none /root/cgroup/
~#
~# ls /root/cgroup/
cgroup.controllers  cgroup.max.descendants  cgroup.stat             cgroup.threads  system.slice
cgroup.max.depth    cgroup.procs            cgroup.subtree_control  init.scope      user.slice
~#

当控制器在当前层级体系中不再引用之后,可将其移动到其它层级体系。由于cgroup控制器的状态是异步销毁处理,导致控制器可能存在延迟释放的引用,这样控制器在前一个层级体系中卸载后并不会马上出现在v2层级体系中。相似的,控制器应当完全的禁止后才能移动出当前的层级体系,可能需要一些时间才能在另一个层级体系中变得可用状态;再者,由于控制器直接的依赖关系,其它的依赖控制器也需要禁止。

A controller can be moved across hierarchies only after the controller is no longer referenced in its current hierarchy. Because per-cgroup
controller states are destroyed asynchronously and controllers may have lingering references, a controller may not show up immediately on
the v2 hierarchy after the final umount of the previous hierarchy. Similarly, a controller should be fully disabled to be moved out of
the unified hierarchy and it may take some time for the disabled controller to become available for other hierarchies; furthermore, due
to inter-controller dependencies, other controllers may need to be disabled too.

虽然在开发和手动配置方面有益处,但是在产品级别不鼓励动态的将控制器在v2和其它层级体系中移动。推荐的做法是在系统启动之后使用控制器之前,确定下来层级体系与控制器之间的关联。

While useful for development and manual configurations, moving controllers dynamically between the v2 and other hierarchies is
strongly discouraged for production use. It is recommended to decide the hierarchies and controller associations before starting using the
controllers after system boot.

在向v2版本的过度过程中,系统管理软件可能在收到干预之前,仍然自动挂载v1版的cgroup文件系统,并且在启动过程中劫持所有的控制器。为了尽早的测试和进行实验,内核启动参数cgroup_no_v1=允许禁止v1版控制器,并且使其在v2可用。

During transition to v2, system management software might still automount the v1 cgroup filesystem and so hijack all controllers
during boot, before manual intervention is possible. To make testing and experimenting easier, the kernel parameter cgroup_no_v1= allows
disabling controllers in v1 and make them always available in v2.

cgroup v2版当前支持一下的挂载选项。
cgroup v2 currently supports the following mount options.

nsdelegate

考虑cgroup命名空间作为委托边界。此选项为系统级别,仅在init命名空间中执行挂载时设置或者通过重新挂载进行修改。在非init命名空间忽略此选项。详情参见委托delegation一节。
Consider cgroup namespaces as delegation boundaries. This option is system wide and can only be set on mount or modified
through remount from the init namespace. The mount option is ignored on non-init namespace mounts. Please refer to the
Delegation section for details.

Organizing Processes and Threads 组织进程和线程

Processes 进程

初始时,仅存在root cgroup,所有进程都属于此cgroup。可通过创建子目录来添加子cgroup::
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

一个cgroup可能包含多个子cgroups以构成一个树结构。每个cgroup有一个可读写的接口文件"cgroup.procs"。读的时候,列出属于此cgroup的所有进程的PID,每个一行。PID没有排序,并且相同的PID可能出现多次,原因是当读操作发生时,此PID进程移动到另一个cgroup,之后又移动回来;或者此PID被系统回收又在此被分配。

A given cgroup may have multiple child cgroups forming a tree structure. Each cgroup has a read-writable interface file
“cgroup.procs”. When read, it lists the PIDs of all processes which belong to the cgroup one-per-line. The PIDs are not ordered and the
same PID may show up more than once if the process got moved to another cgroup and then back or the PID got recycled while reading.

将进程的PID写入目标cgroup的"cgroup.procs"接口文件就意味着移动到此cgroup。单个write(2)系统调用仅可移动一个进程。如果进程有多个线程组成,写入任一线程的PID都可将此进程的所有线程移动到目标cgroup中。

A process can be migrated into a cgroup by writing its PID to the target cgroup’s “cgroup.procs” file. Only one process can be migrated
on a single write(2) call. If a process is composed of multiple threads, writing the PID of any thread migrates all threads of the
process.

当进程创建子进程时,新的子进程天生属于在创建那一刻父进程所属的cgroup。当退出时,进程仍关联与其所属的cgroup,直到被收割为止。尽管如此,僵尸进程的PID不会出现在"cgroup.procs"中,也不能被移动到其它的cgroup。

When a process forks a child process, the new process is born into the cgroup that the forking process belongs to at the time of the
operation. After exit, a process stays associated with the cgroup that it belonged to at the time of exit until it’s reaped; however, a
zombie process does not appear in “cgroup.procs” and thus can’t be moved to another cgroup.

当cgroup没有任何子cgroup或者存活的进程时,可通过删除目录将其销毁。注意没有任何子cgroup但是有关联的僵尸进程的cgroup,视为空,可以被销毁。

A cgroup which doesn’t have any children or live processes can be destroyed by removing the directory. Note that a cgroup which doesn’t
have any children and is associated only with zombie processes is considered empty and can be removed::

  # rmdir $CGROUP_NAME

文件"/proc/PID/cgroup"列出了PID进程的cgroup所属关系。如果系统使用的是传统的cgroup,此文件包含多行,每行表示一个层级体系。cgroupv2总是使用此格式"0::PID/cgroup"列出了PID进程的cgroup所属关系。如果系统使用的是传统的cgroup,此文件包含多行,每行表示一个层级体系。cgroup v2总是使用此格式"0::PID/cgroup"列出了PID进程的cgroup所属关系。如果系统使用的是传统的cgroup,此文件包含多行,每行表示一个层级体系。cgroupv2总是使用此格式"0::PATH"::

“/proc/PID/cgroup"listsaprocess′scgroupmembership.Iflegacycgroupisinuseinthesystem,thisfilemaycontainmultiplelines,oneforeachhierarchy.Theentryforcgroupv2isalwaysintheformat"0::PID/cgroup" lists a process's cgroup membership. If legacy cgroup is in use in the system, this file may contain multiple lines, one for each hierarchy. The entry for cgroup v2 is always in the format "0::PID/cgroup"listsaprocess′scgroupmembership.Iflegacycgroupisinuseinthesystem,thisfilemaycontainmultiplelines,oneforeachhierarchy.Theentryforcgroupv2isalwaysintheformat"0::PATH”::

  # cat /proc/842/cgroup...0::/test-cgroup/test-cgroup-nested

如果进程变为僵尸进程,并且其所属cgroup随后被移除," (deleted)"添加到路径之后::

If the process becomes a zombie and the cgroup it was associated with is removed subsequently, " (deleted)" is appended to the path::

  # cat /proc/842/cgroup...0::/test-cgroup/test-cgroup-nested (deleted)

Threads 线程

对于一些控制器,cgroup v2支持线程粒度的管控,以支持在一组进程的所有线程间分布资源的用法。默认情况下,进程的所有线程属于同一个cgroup,此cgroup也被当做承载资源配置的资源域,其中的资源配置并不特别针对某一进程或者线程。线程模式允许线程跨越cgroup子树,但是仍然维持通用的资源域。

cgroup v2 supports thread granularity for a subset of controllers to support use cases requiring hierarchical resource distribution across
the threads of a group of processes. By default, all threads of a process belong to the same cgroup, which also serves as the resource
domain to host resource consumptions which are not specific to a process or thread. The thread mode allows threads to be spread across
a 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.

标记一个cgroup为线程模式,意味着将其作为线程cgroup加入到其父cgroup的资源域。父cgroup可能是另外一个线程模式的cgroup,其资源域位于层级体系的更高一层。线程子树的根,是距离最近的非线程模式的父辈cgroup,称其为线程域或者线程根,作为整个子树的资源域。

Marking a cgroup threaded makes it join the resource domain of its parent as a threaded cgroup. The parent may be another threaded
cgroup whose resource domain is further up in the hierarchy. The root of a threaded subtree, that is, the nearest ancestor which is not
threaded, is called threaded domain or thread root interchangeably and serves as the resource domain for the entire subtree.

线程模式的cgroup子树内部,某个进程的多个线程可分别归属于不同的cgroup,并且不受限于无内部进程的约束 - 即线程类控制器可在非叶子cgroup上启用,而不论此cgroup是否含有线程。

Inside a threaded subtree, threads of a process can be put in different cgroups and are not subject to the no internal process
constraint - threaded controllers can be enabled on non-leaf cgroups whether they have threads in them or not.

由于线程化的域cgroup承载着其所有子树的域资源配额,不管其是否包含有进程都认为其具有内部资源配额,并且不能迁移到非线程化的子cgroup中。因为根cgroup不受限于无内部进程的约束,可用作线程化的域或者域cgroup的父辈。

As the threaded domain cgroup hosts all the domain resource consumptions of the subtree, it is considered to have internal
resource consumptions whether there are processes in it or not and can’t have populated child cgroups which aren’t threaded. Because the
root cgroup is not subject to no internal process constraint, it can serve both as a threaded domain and a parent to domain cgroups.

cgroup当前的运行模式或者说类型显示在文件"cgroup.type"中,指明cgroup是否为一个普通的域cgroup,或者一个服务于线程化子树的域cgroup,或者为线程化cgroup。

The current operation mode or type of the cgroup is shown in the “cgroup.type” file which indicates whether the cgroup is a normal
domain, a domain which is serving as the domain of a threaded subtree, or a threaded cgroup.

创建时,cgroup总是域类型cgroup,可通过向文件"cgroup.type"写入“threaded”字符串变更为线程化cgroup。此操作为当方向的::
On creation, a cgroup is always a domain cgroup and can be made threaded by writing “threaded” to the “cgroup.type” file. The
operation is single direction::

  # echo threaded > cgroup.type

一旦线程化,此cgroup不能再转化回域cgroup类型。要使能线程模式,以下的条件必须满足。
Once threaded, the cgroup can’t be made a domain again. To enable the thread mode, the following conditions must be met.

  • 由于操作的cgroup将加入父辈的资源域。其父辈必须是有效的域cgroup,或者是线程化cgroup。

  • As the cgroup will join the parent’s resource domain. The parent must either be a valid (threaded) domain or a threaded cgroup.

  • 当父辈不是线程化域,要求其不能包含任何使能的域控制器,也不能有迁移的域子辈。树根不受此限制。

  • When the parent is an unthreaded domain, it must not have any domain controllers enabled or populated domain children. The root is
    exempt from this requirement.

拓扑结构,cgroup可处在无效的状态。考虑一下的拓扑::
Topology-wise, a cgroup can be in an invalid state. Please consider the following toplogy::

  A (threaded domain) - B (threaded) - C (domain, just created)

C作为一个域cgroup被创建,但是其没有连接到一个可接受域类型子cgroup的父辈。只有当C转化为一个线程化cgroup之后才会可用。在此之前,“cgroup.type” 文件显示"domain (invalid)"字样。由于无效的拓扑对C的操作将会失败,错误码为EOPNOTSUPP。

C is created as a domain but isn’t connected to a parent which can host child domains. C can’t be used until it is turned into a
threaded cgroup. “cgroup.type” file will report “domain (invalid)” in these cases. Operations which fail due to invalid topology use
EOPNOTSUPP as the errno.

当cgroup的任一子辈cgroup线程化,或者通过其"cgroup.subtree_control"文件使能线程化控制器,并且cgroup中含有进程时,cgroup由域类型转化为线程化域cgroup。当条件不满足时,cgroup转换会普通的域cgroup。

A domain cgroup is turned into a threaded domain when one of its child cgroup 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 conditions
clear.

读的时候,"cgroup.threads"文件包含cgroup中所有线程的线程ID号。除了相关操作是线程级别而非进程级别,"cgroup.threads"文件与"cgroup.procs"文件拥有相同的格式和行为表现。虽然任意的cgroup中的"cgroup.threads"都可被写入线程值,但是由于线程仅可在相同的线程化域中移动,写操作被限制在线程化的子树内。

When read, “cgroup.threads” contains the list of the thread IDs of all threads in the cgroup. Except that the operations are per-thread
instead of per-process, “cgroup.threads” has the same format and behaves the same way as “cgroup.procs”. While “cgroup.threads” can be
written to in any cgroup, as it can only move threads inside the same threaded domain, its operations are confined inside each threaded
subtree.

线程化的域cgroup充当整个子树的资源域,虽然线程可分散与子树内,但是所有的进程都被认为包含在线程化的域cgroup中。线程化的域cgroup文件"cgroup.procs"包含子树中所有进程的PID信息,并且在子树内不可读。尽管如此,“cgroup.procs” 文件在子树的任意位置都可被写入,以将进程的所有线程移入cgroup中。

The threaded domain cgroup serves as the resource domain for the whole subtree, 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 all
processes in the subtree and is not readable in the subtree proper. However, “cgroup.procs” can be written to from anywhere in the subtree
to migrate all threads of the matching process to the cgroup.

线程控制器仅可在线程化的子树中使能。使能之后,仅统计控制cgroup中与此线程及其子辈关联的资源配额。所有未关联到具体线程的配额都属于顶层的线程化域cgroup。
Only threaded controllers can be enabled in a threaded subtree. When a threaded controller is enabled inside a threaded subtree, it only
accounts for and controls resource consumptions associated with the threads in the cgroup and its descendants. All consumptions which
aren’t tied to a specific thread belong to the threaded domain cgroup.

由于线程化的子树不受限于无内部进程约束,线程化控制器必须能够处理非叶子cgroup与其子cgroup中线程间的竞争。每个线程化控制器定义了竞争如何被处理。
Because a threaded subtree is exempt from no internal process constraint, a threaded controller must be able to handle competition
between threads in a non-leaf cgroup and its child cgroups. Each threaded controller defines how such competitions are handled.

[Un]populated Notification [非]迁移通知

每个非根cgroup都有一个"cgroup.events"文件,其中包含有"populated"字段的值,用来标识此cgroup的子层次体系是否包含活动的进程。值为0表示在此cgroup及其子辈中没有活动进程;否则,值为1。值改变时触发poll 和 [id]notify事件。比如具此可在子层次体系中所有的进程退出后,执行清理工作。populated状态更新和通知时递归的。考虑以下的子层级结构,括号中的数字表示cgroup中进程的数量::

Each non-root cgroup has a “cgroup.events” file which contains “populated” field indicating whether the cgroup’s sub-hierarchy has
live processes in it. Its value is 0 if there is no live process in the cgroup and its descendants; otherwise, 1. poll and [id]notify
events are triggered when the value changes. This can be used, for example, to start a clean-up operation after all processes of a given
sub-hierarchy have exited. The populated state updates and notifications are recursive. Consider the following sub-hierarchy
where the numbers in the parentheses represent the numbers of processes
in each cgroup::

  A(4) - B(0) - C(1)\ D(0)

A、B和C的"populated"字段为1,而D的为0。当C中的唯一一个进程退出后,B和C的"populated"字段变为0,这两个cgroup中文件"cgroup.events"将产生修改事件。

A, B and C’s “populated” fields would be 1 while D’s 0. After the one process in C exits, B and C’s “populated” fields would flip to “0” and
file modified events will be generated on the “cgroup.events” files of both cgroups.

Controlling Controllers 可控控制器

Enabling and Disabling 使能和禁止

每个cgroup有一个"cgroup.controllers"文件,包含对此cgroup可使能/可用的控制器::
Each cgroup has a “cgroup.controllers” file which lists all controllers available for the cgroup to enable::

  # cat cgroup.controllerscpu io memory

默认控制器都是禁止状态。可通过写入"cgroup.subtree_control"文件使能和禁止控制器::
No controller is enabled by default. Controllers can be enabled and disabled by writing to the “cgroup.subtree_control” file::

  # echo "+cpu +memory -io" > cgroup.subtree_control

仅在文件"cgroup.controllers"中列出的控制器可被使能。如以上操作,当同时操作多个控制器时,他们或者都成功或者都失败。如果对于一个控制器同时进行多个操作,最后一个操作反应执行结果。

Only controllers which are listed in “cgroup.controllers” can be enabled. When multiple operations are specified as above, either they
all succeed or fail. If multiple operations on the same controller are specified, the last one is effective.

使能cgroup中的控制器表示其直接子辈的资源分布将受到控制。考虑以下的子层次体系。括号中列出的是使能的控制器::

Enabling a controller in a cgroup indicates that the distribution of the target resource across its immediate children will be controlled.
Consider the following sub-hierarchy. The enabled controllers are listed in parentheses::

  A(cpu,memory) - B(memory) - C()\ D()

A使能了"cpu" 和 "memory"两个控制器,A将控制CPU运行周期和memory内存在其直接子辈中的分别,这里是:B。由于B使能了"momory"控制器,未使能"CPU"控制器,其直接子辈C和D将不受限的使用CPU周期,但是他们由B中分配内存确是受限的。

As A has “cpu” and “memory” enabled, A will control the distribution of 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 CPU cycles but their division of memory available to B will be controlled.

由于控制器管理着目标资源在cgroup的子辈中的分配,使能控制器将在子辈cgroup目录下创建控制器的接口文件。在以上的示例中,在B上使能cpu控制器将在C和D中创建以"cpu."为前缀的控制器接口文件。同理,禁用B中的memory控制,将导致C和D中的以"memory."为前缀的控制器文件被删除。这意味着,控制器接口文件 - 非以"cgroup."开头的文件,都是由父辈cgroup所有,而不是子辈自身。

As a controller regulates the distribution of the target resource to the cgroup’s children, enabling it creates the controller’s interface
files in the child cgroups. In the above example, enabling “cpu” on B would create the “cpu.” prefixed controller interface files in C and
D. Likewise, disabling “memory” from B would remove the “memory.” prefixed controller interface files from C and D. This means that the
controller interface files - anything which doesn’t start with “cgroup.” are owned by the parent rather than the cgroup itself.

Top-down Constraint 自上而下的约束

资源以自上而下的方式分配,cgroup只有在其父cgroup赋予其资源之后,才能向下层分布资源。这就正意味着所有非根"cgroup.subtree_control"文件只能包含父cgroup的"cgroup.subtree_control"文件中使能的控制器。控制器可被使能的前提是其父cgroup使能了此控制器,并且如果cgroup的一个或者多个子cgroup使能了某一控制器,此cgroup的控制器不能被禁用。

Resources are distributed top-down and a cgroup can further distribute a resource only if the resource has been distributed to it from the
parent. This means that all non-root “cgroup.subtree_control” files can only contain controllers which are enabled in the parent’s
“cgroup.subtree_control” file. A controller can be enabled only if the parent has the controller enabled and a controller can’t be
disabled if one or more children have it enabled.

No Internal Process Constraint 无内部进程约束

非根cgroup只有在不包含任何进程时才可以分配域资源给子辈cgroup。换句话说,仅不包含任何进程的域cgroup能够在其"cgroup.subtree_control"文件中使能域控制器。

Non-root cgroups can distribute domain resources to their children only when they don’t have any processes of their own. In other words,
only domain cgroups which don’t contain any processes can have domain controllers enabled in their “cgroup.subtree_control” files.

这样保证了当域控制器看向使能它的那部分层级结构时,进程总是位于层级最底端的叶子cgroup。打破此规则的情形是当子cgroup与父cgroup中的内部进程存在竞争时。

This guarantees that, when a domain controller is looking at the part of the hierarchy which has it enabled, processes are always only on
the leaves. This rules out situations where child cgroups compete against internal processes of the parent.

根cgroup不受此限制。根cgroup包含进程和不可分配给其它任何cgroup的匿名资源额度,需要大多数的控制器做特殊对待。关于根cgroup中的资源额度如何处理取决于每个特定的控制器。

The root cgroup is exempt from this restriction. Root contains processes and anonymous resource consumption which can’t be associated
with any other cgroups and requires special treatment from most controllers. How resource consumption in the root cgroup is governed
is up to each controller.

注意如果cgroup的"cgroup.subtree_control"文件中没有任何使能的控制器,不受制于以上描述的约束。这一点非常重要,否则将不能创建一个populated cgroup的子辈cgroup。为了控制cgroup资源的分配,cgroup必须创建子cgroup,并且在通过"cgroup.subtree_control"文件使能控制器之前将其进程转移到子cgroup中。

Note that the restriction doesn’t get in the way if there is no enabled controller in the cgroup’s “cgroup.subtree_control”. This is
important as otherwise it wouldn’t be possible to create children of a populated cgroup. To control resource distribution of a cgroup, the
cgroup must create children and transfer all its processes to the children before enabling controllers in its “cgroup.subtree_control”
file.

Delegation 委托

Model of Delegation 委托模型

cgroup的委可分为两种方式。第一,对于非特权用户,给与其对目录和"cgroup.procs",
“cgroup.threads” 和 "cgroup.subtree_control"文件的写权限。第二,如果在挂载命令mount执行时,设置了"nsdelegate"选项,在命名空间创建时,自动委托给一个cgroup命名空间。

A cgroup can be delegated in two ways. First, to a less privileged user 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 a
cgroup namespace on namespace creation.

由于给定目录下的资源控制接口文件控制着父cgroup资源的分配,不应允许被委托者写入这些文件。对于第一种委托方法,可通过不授予这些文件的访问权限来实现。对于第二种委托方法,在命名空间根上,内核拒绝从命名空间内部写入除"cgroup.procs" 和 "cgroup.subtree_control"文件之外的其它文件。

Because the resource control interface files in a given directory control the distribution of the parent’s resources, the delegatee
shouldn’t be allowed to write to them. For the first method, this is achieved by not granting access to these files. For the second, the
kernel rejects writes to all files other than “cgroup.procs” and “cgroup.subtree_control” on a namespace root from inside the namespace.

最终的结果对于两种委托方式是一样的。一旦进行委托,用户可在目录下建立子层级结构,在其中以合适的方式组织进程,并且更进一步分配由其父cgroup获得的资源。限制以及所有资源控制器的设置都是层级结构,不管被委托的子层级机构发生什么,一切都在父cgroup施加的资源约束内。

The end results are equivalent for both delegation types. Once delegated, the user can build sub-hierarchy under the directory,
organize processes inside it as it sees fit and further distribute the resources it received from the parent. The limits and other settings
of all resource controllers are hierarchical and regardless of what happens in the delegated sub-hierarchy, nothing can escape the
resource restrictions imposed by the parent.

目前,cgroup对委托子层次结构中的cgroup数量或嵌套深度没有任何限制;但是,这在将来可能会受到明确限制。

Currently, cgroup doesn’t impose any restrictions on the number of cgroups 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 processes can’t be moved into or out of the sub-hierarchy by the delegatee.

对于委托给低特权级用户的情况,要达到以上的限制,需要非root euid的进程满足以下的条件,才能允许其通过将进程PID写入cgroup的"cgroup.procs"文件,迁移进程到目标cgroup中。

For delegations to a less privileged user, this is achieved by requiring the following conditions for a process with a non-root euid
to migrate a target process into a cgroup by writing its PID to the “cgroup.procs” file.

  • 写入者必须具有"cgroup.procs"文件的写权限。

  • The writer must have write access to the “cgroup.procs” file.

  • 写入者必须具有迁移源和目的cgroup的父辈的"cgroup.procs"文件的写权限。

  • The writer must have write access to the “cgroup.procs” file of the common ancestor of the source and destination cgroups.

以上的两个约束保证了被委托者可以自由的在被委托的子层级机构内迁移进程,但是不能由子层级结构之外迁入,也不能迁移出子层级结构。

The above two constraints ensure that while a delegatee may migrate processes around freely in the delegated sub-hierarchy it can’t pull
in from or push out to outside the sub-hierarchy.

例如,假设将cgroup C0和C1委托给了用户U0,随后U0在C0之下创建了C00、C01,在C1之下创建了C10,如下所示,C0和C1之下的所有进程都属于用户U0::

For an example, let’s assume cgroups C0 and C1 have been delegated to user U0 who created C00, C01 under C0 and C10 under C1 as follows and
all processes under C0 and C1 belong to U0::

  ~~~~~~~~~~~~~ - C0 - C00~ cgroup    ~      \ C01~ hierarchy ~~~~~~~~~~~~~~ - C1 - C10

假设用户U0准备将一个C10内的进程的PIC写入到"C00/cgroup.procs"文件中。虽然用户U0具有此文件的写权限,但是源cgroup C10的父辈和目的cgroup C00的父辈都在委托节点之外,用户U0没有父辈"cgroup.procs"文件的写入权限,所以,之前的写操作将被拒绝,错误为:-EACCES。

Let’s also say U0 wants to write the PID of a process which is currently in C10 into “C00/cgroup.procs”. U0 has write access to the
file; however, the common ancestor of the source cgroup C10 and the destination cgroup C00 is above the points of delegation and U0 would
not have write access to its “cgroup.procs” files and thus the write will be denied with -EACCES.

对于委托给命名空间的情况,要达到限制目的需要的条件是,尝试进行迁移操作的进程所在的命名空间可访问到源cgroup和目的cgroup。如果其中任何一个不可访问,迁移操作将被拒绝,错误码:-ENOENT。

For delegations to namespaces, containment is achieved by requiring that both the source and destination cgroups are reachable from the
namespace of the process which is attempting the migration. If either is not reachable, the migration is rejected with -ENOENT.

Guidelines 指南

Organize Once and Control 组织一次和控制

跨cgroup迁移进程是相对高成本的操作,并且一些有状态的资源,比如内存不会随着进程一起迁移。这是一个明确的设计决策,因为通常在迁移和各种热路径的同步成本之间存在固有的权衡。

Migrating a process across cgroups is a relatively expensive operation and stateful resources such as memory are not moved together with the
process. This is an explicit design decision as there often exist inherent trade-offs between migration and various hot paths in terms
of synchronization cost.

因此,频繁地跨cgroups迁移进程来应用不同的资源限制的方法是不鼓励的。启动后应根据系统的逻辑和资源结构分配给cgroup一个工作负荷量。资源配置的动态调整可以通过接口文件来更改控制器配置实现。

As such, migrating processes across cgroups frequently as a means to apply different resource restrictions is discouraged. A workload
should be assigned to a cgroup according to the system’s logical and resource structure once on start-up. Dynamic adjustments to resource
distribution can be made by changing controller configuration through the interface files.

Avoid Name Collisions 名字冲突避免

cgroup及其子cgroup的接口文件使用同一目录,并且有可能创建与接口文件冲突的子辈cgroup。

Interface files for a cgroup and its children cgroups occupy the same directory and it is possible to create children cgroups which collide
with interface files.

所有cgroup核心接口文件都以"cgroup."作为前缀,每个控制器的接口文件都以控制器名称和一个点为前缀。控制器的名称由小写字母和’‘组成,但从不以’'开头,因此为避免冲突,它可以用作前缀。此外,接口文件名不会以工作负载分类中常用的术语开头或结尾,例如job、service, slice, unit or workload.

All cgroup core interface files are prefixed with “cgroup.” and each controller’s interface files are prefixed with the controller name and
a 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 prefix
character for collision avoidance. Also, interface file names won’t start or end with terms which are often used in categorizing workloads
such as job, service, slice, unit or workload.

cgroup不做任何事情来防止名称冲突,用户有责任避免这些冲突。

cgroup doesn’t do anything to prevent name collisions and it’s the user’s responsibility to avoid them.

Resource Distribution Models 资源分配模型

cgroup控制器根据资源类型和预期的用例实现了几个资源分配方案。本节描述正在使用的主要方案及其预期行为。

cgroup controllers implement several resource distribution schemes depending on the resource type and expected use cases. This section
describes major schemes in use along with their expected behaviors.

Weights 权重

父辈资源的分布方式是:将所有活动子辈的权重相加,之后每个活动子辈得到一个与其权重与总和之比率相匹配的资源量。由于子辈仅在参与分配的时刻才能使用资源,这中分配方式可做到任务节约。由于动态属性,此模型通常用于无状态资源。

A parent’s resource is distributed by adding up the weights of all active children and giving each the fraction matching the ratio of its
weight against the sum. As only children which can make use of the resource at the moment participate in the distribution, this is
work-conserving. Due to the dynamic nature, this model is usually used for stateless resources.

所有权重值都在[1, 10000]范围内,默认值为100。这使得在两个方向上可以足够的粒度,对称的增加偏差,而又不会超出合法的范围。

All weights are in the range [1, 10000] with the default at 100. This allows symmetric multiplicative biases in both directions at fine
enough granularity while staying in the intuitive range.

只要权重在范围内,所有配置组合都有效,没有理由拒绝配置更改或进程迁移。
As long as the weight is in range, all configuration combinations are valid and there is no reason to reject configuration changes or
process migrations.

"cpu.weight"按比例地将CPU周期分配给活动子辈,这就是这种类型的一个例子。
“cpu.weight” proportionally distributes CPU cycles to active children and is an example of this type.

Limits 限额

子辈只能使用配置的资源量。限额可以过度给与 - 即子辈限额的总和可以超出父辈可提供的资源总量。
A child can only consume upto the configured amount of the resource. Limits can be over-committed - the sum of the limits of children can
exceed the amount of resource available to the parent.

限额范围在[0,max]内,默认取"max"值,即noop。
Limits are in the range [0, max] and defaults to “max”, which is noop.

由于限额可能被过度给与,所有配置组合都是有效的,因此没有理由拒绝配置更改或进程迁移。
As limits can be over-committed, all configuration combinations are valid and there is no reason to reject configuration changes or
process migrations.

"io.max"限制了一个cgroup在IO设备上可以使用的最大BPS和/或IOPS,即为这种类型的一个例子。
“io.max” limits the maximum BPS and/or IOPS that a cgroup can consume on an IO device and is an example of this type.

Protections 保护

如果一个cgroup的所有祖先的使用率都在被保护级别,那么该cgroup将被保证分配到配置的资源量。保护可以是硬保证,也可以是尽最大努力的软边界。保护也可能过度承诺,在这种情况下,保护的边界是父辈的可用资源量。

A cgroup is protected to be allocated upto the configured amount of the resource if the usages of all its ancestors are under their
protected levels. Protections can be hard guarantees or best effort soft boundaries. Protections can also be over-committed in which case
only upto the amount available to the parent is protected among children.

保护在[0,max]范围内,默认为0,即noop。
Protections are in the range [0, max] and defaults to 0, which is noop.

由于保护可能被过度承诺,所有配置组合都是有效的,因此没有理由拒绝配置更改或进程迁移。

As protections can be over-committed, all configuration combinations are valid and there is no reason to reject configuration changes or
process migrations.

"memory.low"实现了最大努力的内存保护,是这种类型的一个例子。
“memory.low” implements best-effort memory protection and is an example of this type.

Allocations 分配

一个cgroup被专门分配一定量的有限资源。分配量不能过度承诺 - 所有子辈分配量的总和不能超过父辈可用的资源量。
A cgroup is exclusively allocated a certain amount of a finite resource. Allocations can’t be over-committed - the sum of the
allocations of children can not exceed the amount of resource available to the parent.

分配在[0,max]范围内,默认为0,即无资源。
Allocations are in the range [0, max] and defaults to 0, which is no resource.

由于分配不能过度承诺,某些配置组合无效,应被拒绝。此外,如果资源是执行进程所必需的,进程迁移可能被拒绝。

As allocations can’t be over-committed, some configuration combinations are invalid and should be rejected. Also, if the
resource is mandatory for execution of processes, process migrations may be rejected.

"cpu.rt.max"硬分配实时时间片,是这种类型的一个例子。
“cpu.rt.max” hard-allocates realtime slices and is an example of this type.

Interface Files 接口文件

Format 格式

所有接口文件应尽可能采用以下格式之一:
All interface files should be in one of the following formats whenever possible::

新行分隔的值
New-line separated values
(当一次只能写入一个值时)
(when only one value can be written at once)

    VAL0\nVAL1\n...

空格分隔的值
Space separated values
(当只读或多个值可以同时写入时)
(when read-only or multiple values can be written at once)

    VAL0 VAL1 ...\n

Flat键值
Flat keyed

    KEY0 VAL0\nKEY1 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 match reading; however, controllers may allow omitting later fields or
implement restricted shortcuts for most common use cases.

对于Flat和嵌套键值文件,一次只能写入单个键的值。对于嵌套键值文件,子键对可按任何顺序指定,但并不要求必须指定所有键值对。

For both flat and nested keyed files, only the values for a single key can be written at a time. For nested keyed files, the sub key pairs
may 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.

  • 根cgroup应不受资源控制,因此不应具有资源控制接口文件。同样的,根cgroup上的信息文件(最终显示其他地方可用的全局信息)不应该存在。

  • The root cgroup should be exempt from resource control and thus shouldn’t have resource control interface files. Also,
    informational files on the root cgroup which end up showing global information available elsewhere shouldn’t exist.

  • 如果控制器实现基于权重weight的资源分配,则其接口文件应命名为“weight”,并具有范围[1,10000]的要求,默认为100。这些值的选择允许在两个方向上有足够的和对称的偏差,同时保持指导性(默认为100%)。

  • If a controller implements weight based resource distribution, its interface file should be named “weight” and have the range [1,
    10000] with 100 as the default. The values are chosen to allow enough and symmetric bias in both directions while keeping it
    intuitive (the default is 100%).

  • 如果控制器实现了绝对资源保证和/或限额,则接口文件应分别命名为"min"和"max"。如果控制器实现了最大努力的资源保证和/或限制,则接口文件应分别命名为"low"。为"high"。

  • If a controller implements an absolute resource guarantee and/or limit, the interface files should be named “min” and “max”
    respectively. If a controller implements best effort resource guarantee and/or limit, the interface files should be named “low”
    and “high” respectively.

    在上述四个控制文件中,应使用特殊标记"max"表示读写的上限无穷大。
    In the above four control files, the special token “max” should be used to represent upward infinity for both reading and writing.

  • 如果设置具有可配置的默认值和键控的特定覆盖值,则默认条目使用"default"键值表示,并且显示为文件中的第一个条目。

  • If a setting has a configurable default value and keyed specific overrides, the default entry should be keyed with “default” and
    appear as the first entry in the file.

    可以通过写入"default VAL"或"VAL"或"VAL"或"VAL"来更新默认值。
    The default value can be updated by writing either “default VAL"or"VAL" or "VAL"or"VAL”.

    写入以更新特定的覆盖值时,"default"可用作指示移除覆盖的值。以"default"为值的覆盖条目,读取时不得出现。
    When writing to update a specific override, “default” can be used as the value to indicate removal of the override. Override entries
    with “default” as the value must not appear when read.

    例如,由major:minor设备号和整数值键控的设置可能如下所示:
    For example, a setting which is keyed by major:minor device numbers with 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-file
default 125
8:16 170
  • 对于频率不是很高的事件,应该创建一个接口文件"events",列出事件键值对。每当发生应通知事件时,应在文件上生成文件修改事件。
  • 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 be generated on the file.

Core Interface Files 核心接口文件

所有cgroup核心文件都以"cgroup."为前缀
All cgroup core files are prefixed with “cgroup.”

cgroup.type

存在于非根cgroups上的可读写的单值文件。
A read-write single value file which exists on non-root cgroups.

读取时,它指示cgroup的当前类型,可以是以下值之一。
When read, it indicates the current type of the cgroup, which can be one of the following values.

  • “domain” : 一个正常有效的 domain cgroup.

  • “domain” : A normal valid domain cgroup.

  • “domain threaded” : 一个线程化的 domain cgroup,其作为一个线程化子树的根root.

  • “domain threaded” : A threaded domain cgroup which is serving as the root of a threaded subtree.

  • “domain invalid” : 一个处于无效状态的 cgroup. 其不能被populated或者在其上启用控制器。其可允许变为线程化的cgroup。

  • “domain invalid” : A cgroup which is in an invalid state.
    It can’t be populated or have controllers enabled. It may be allowed to become a threaded cgroup.

  • “threaded” : 一个线程化的 cgroup,其为一个线程化子树的成员.

  • “threaded” : A threaded cgroup which is a member of a threaded subtree.

    通过向此文件中写入"threaded",可将一个cgroup转变为线程化cgroup。
    A cgroup can be turned into a threaded cgroup by writing “threaded” to this file.

cgroup.procs

一个可读写的由新行分隔值的文件,存在于所有cgroup中。
A read-write new-line separated values file which exists on all cgroups.
读取时,它列出属于此cgroup的所有进程的PID,每行一个。PID没有次序之分,并且相同的PID可能会出现多次,原因是进程被迁移到另一个cgroup,然后又被移回,或者在读取文件时,PID被回收。
When read, it lists the PIDs of all processes which belong to the cgroup one-per-line. The PIDs are not ordered and the
same PID may show up more than once if the process got moved to another cgroup and then back or the PID got recycled while reading.

可以向此文件写入一个PID,来将与PID关联的进程迁移到此cgroup中。写入者应匹配所有以下条件。
A PID can be written to migrate the process associated with the PID to the cgroup. The writer should match all of the
following conditions.

  • 它必须要具有对"cgroup.procs"文件的写入权限。

  • It must have write access to the “cgroup.procs” file.

  • 它必须要具有对迁移的源和目标cgroup的一般父辈的"cgroup.procs"文件的写入权限。

  • It must have write access to the “cgroup.procs” file of the common ancestor of the source and destination cgroups.

委托子层次结构时,此文件的写入权限应授予包含此文件的目录。
When delegating a sub-hierarchy, write access to this file should be granted along with the containing directory.

在线程化cgroup中,由于所有进程都属于线程根,因此读取此文件将失败,错误码EOPNOTSUPP。写操作是支持的,将进程的每个线程迁移到此cgroup中。
In a threaded cgroup, reading this file fails with EOPNOTSUPP as all the processes belong to the thread root. Writing is
supported and moves every thread of the process to the cgroup.

cgroup.threads
一个可读写的由新行分隔数值的文件,存在于所有cgroup中。
A read-write new-line separated values file which exists on all cgroups.

读取时,它列出属于此cgroup的所有线程的TID,每行一个。TID没有次序之分,并且相同的TID可能会出现多次,原因是线程被迁移到另一个cgroup,然后又被移回,或者在读取文件时,TID被回收。
When read, it lists the TIDs of all threads which belong to the cgroup one-per-line. The TIDs are not ordered and the
same TID may show up more than once if the thread got moved to another cgroup and then back or the TID got recycled while reading.

可以向此文件写入一个TID,来将与TID关联的线程迁移到此cgroup中。写入者应匹配所有以下条件。
A TID can be written to migrate the thread associated with the TID to the cgroup. The writer should match all of the
following conditions.

  • 它必须要具有对"cgroup.threads"文件的写入权限。

  • It must have write access to the “cgroup.threads” file.

  • 线程当前所在的cgroup必须与目标cgroup位于相同的资源domain中。

  • The cgroup that the thread is currently in must be in the same resource domain as the destination cgroup.

  • 它必须要具有对迁移的源和目标cgroup的一般父辈的"cgroup.procs"(不知道这里是不是写错了,应为cgroup.threads?)文件的写入权限。

  • It must have write access to the “cgroup.procs” file of the common ancestor of the source and destination cgroups.

委托子层次结构时,此文件的写入权限应授予包含此文件的目录。
When delegating a sub-hierarchy, write access to this file should be granted along with the containing directory.

cgroup.controllers
一个只读的由空格分隔数值的文件,存在于所有cgroup中。
A read-only space separated values file which exists on all cgroups.

它显示了此cgroup可用的以空格分隔的所有控制器列表。控制器不分顺序。
It shows space separated list of all controllers available to the cgroup. The controllers are not ordered.

cgroup.subtree_control
一个可读写的由空格分隔数值的文件,存在于所有cgroup中。开始时为空。
A read-write space separated values file which exists on all cgroups. Starts out empty.

读取时,它会显示以空格分隔的已使能的控制器列表,这些控制器管理着从此cgroup到其子辈的资源分布。
When read, it shows space separated list of the controllers which are enabled to control resource distribution from the
cgroup to its children.

以空格分隔的控制器列表中,为控制器的名称加入前缀’+’ 或 '-‘达到使能和禁用控制器的目的。控制器名称前缀为’+‘使能控制器,为’-'禁用控制器。如果某个控制器在列表中出现多次,最后一次有效。当指定多个启用和禁用操作时,都成功或者都失败。
Space separated list of controllers prefixed with ‘+’ or ‘-’ can be written to enable or disable controllers. A controller
name 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 disable operations are specified, either all succeed or all fail.

cgroup.events
一个只读的flat-keyed文件,存在于非root cgroup中。定义了以下的项。如果没有特别指定,此文件中值的变化将产生一个文件修改事件。
A read-only flat-keyed file which exists on non-root cgroups. The following entries are defined. Unless specified
otherwise, a value change in this file generates a file modified event.

populated
如果cgroup或其后代包含任何活动进程,值为1;否则为0。
1 if the cgroup or its descendants contains any live processes; otherwise, 0.

cgroup.max.descendants
一个可读写的单一值文件,默认为"max"。
A read-write single value files. The default is “max”.

允许的最大子辈cgroups数量。如果子辈的实际数目等于或大于此值,尝试在层次结构中创建新的cgroup将失败。
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
一个可读写的单一值文件,默认为"max"。
A read-write single value files. The default is “max”.

当前cgroup下允许的最大子辈深度。如果实际的子辈深度等于或大于此值,尝试创建新的子cgroup将失败。
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
一个只读的flat-keyed文件,包含以下项。
A read-only flat-keyed file with the following entries:

nr_descendants
可见的子辈cgroup的总数量.
Total number of visible descendant cgroups.

nr_dying_descendants
消亡的子辈cgroups总数。一个cgroup在被用户删除后会消亡。cgroup将继续在消亡状态下一段时间,不确定的时间(取决于系统负载)才被完全销毁。
Total number of dying descendant cgroups. A cgroup becomes dying after being deleted by a user. The cgroup will remain
in dying state for some time undefined time (which can depend on system load) before being completely destroyed.

一个进程在任何情况下都不能进入一个消亡的cgroup,一个消亡的cgroup不能复活。
A process can’t enter a dying cgroup under any circumstances, a dying cgroup can’t revive.

一个消亡的cgroup可以消耗不超过限制的系统资源,这些限制是在cgroup删除时刻有效的限制。
A dying cgroup can consume system resources not exceeding limits, which were active at the moment of cgroup deletion.

Controllers 控制器

CPU

"cpu"控制器控制CPU周期的分配。此控制器为正常调度策略实现了权重和绝对带宽限制模型,为实时调度策略实现了绝对带宽分配模型。

The “cpu” controllers regulates distribution of CPU cycles. This controller implements weight and absolute bandwidth limit models for
normal scheduling policy and absolute bandwidth allocation model for realtime scheduling policy.

警告:cgroup2尚不支持实时进程的控制,只有当所有RT进程都在根cgroup中时,才能启用CPU控制器。请注意,系统管理软件可能已经在系统引导期间将RT进程放入非根cgroups中,在启用CPU控制器之前,这些进程可能需要移动到根cgroup。

WARNING: cgroup2 doesn’t yet support control of realtime processes and the cpu controller can only be enabled when all RT processes are in
the root cgroup. Be aware that system management software may already have placed RT processes into nonroot cgroups during the system boot
process, and these processes may need to be moved to the root cgroup before the cpu controller can be enabled.

CPU Interface Files CPU接口文件

所有持续长度都以微秒为单位。
All time durations are in microseconds.

cpu.stat
存在于非根cgroups中的只读flat-keyed文件。无论控制器是否启用,此文件都存在。
A read-only flat-keyed file which exists on non-root cgroups. This file exists whether the controller is enabled or not.

它总是报告以下三个状态:
It always reports the following three stats:

  • usage_usec
  • user_usec
  • system_usec

以及以下三个文件,当控制器启用时:
and the following three when the controller is enabled:

  • nr_periods
  • nr_throttled
  • throttled_usec

cpu.weight
存在于非根cgroups上的可读写单值文件。默认值为"100"。
A read-write single value file which exists on non-root cgroups. The default is “100”.

 权重值的范围为[1, 10000].The weight in the range [1, 10000].

cpu.weight.nice
存在于非根cgroups上的可读写单值文件。默认值为"0"。
A read-write single value file which exists on non-root cgroups. The default is “0”.

nice值的范围为[-20, 19].
The nice value is in the range [-20, 19].
此接口文件是"cpu.weight"的可选接口,允许读取,以及使用与系统调用nice(2)相同的值进行写入。因为范围较小,nice值粒度更粗糙,所以读取值为当前权重的最接近近似值。
This interface file is an alternative interface for “cpu.weight” and allows reading and setting weight using the
same values used by nice(2). Because the range is smaller and granularity is coarser for the nice values, the read value is
the closest approximation of the current weight.

cpu.max
存在于非根cgroups上的可读写双值文件。
A read-write two value file which exists on non-root cgroups.
默认值为"max 100000".
The default is “max 100000”.

最大带宽限制。格式如下:
The maximum bandwidth limit. It’s in the following format::

          $MAX $PERIOD
 这表示该组在每个$PERIOD持续时间内最多可消耗$MAX。$MAX值为"max"时表示没有限制。只要写了一个数字,更新$MAX值。which indicates that the group may consume upto $MAX in each $PERIOD duration.  "max" for $MAX indicates no limit.  If onlyone number is written, $MAX is updated.

Memory 内存

"memory"控制器控制内存的分配。内存是有状态的,实现了限制和保护模型model。由于内存使用和回收压力以及内存的状态属性之间的交织,分布模型相对复杂。

The “memory” controller regulates distribution of memory. Memory is stateful and implements both limit and protection models. Due to the intertwining between memory usage and reclaim pressure and the stateful nature of memory, the distribution model is relatively complex.

虽然不是完全无懈可击,但是跟踪给定cgroup的所有主要内存使用情况,以便将总的内存消耗核算和控制在合理范围内。目前,跟踪了以下类型的内存使用情况。

While not completely water-tight, all major memory usages by a given cgroup are tracked so that the total memory consumption can be accounted and controlled to a reasonable extent. Currently, the following types of memory usages are tracked.

  • 用户空间内存 - 页面缓存和匿名内存.

  • Userland memory - page cache and anonymous memory.

  • Kernel数据结构,如:dentries 和 inodes.

  • Kernel data structures such as dentries and inodes.

  • TCP 套接口缓存.

  • TCP socket buffers.

为了更好的覆盖,以上的列表将来可能扩展。
The above list may expand in the future for better coverage.

Memory Interface Files 内存接口文件

所有的内存量以字节为单位。如果写入的值没有对齐到PAGE_SIZE,在读回时可能取整到了最接近的PAGE_SIZE的倍数。

All memory amounts are in bytes. If a value which is not aligned to PAGE_SIZE is written, the value may be rounded up to the closest
PAGE_SIZE multiple when read back.

memory.current
non-root cgroup中的只读单值文件。
A read-only single value file which exists on non-root cgroups.

cgroup及其子辈当前使用的内存总量。
The total amount of memory currently being used by the cgroup and its descendants.

memory.low
non-root cgroup中的可读写单值文件。默认值为"0"。
A read-write single value file which exists on non-root cgroups. The default is “0”.

尽力而为的内存保护。如果cgroup及其所有子辈使用的内存量低于他们的低边界,cgroup的内存将不会回收,但是可从非保护的cgroup中回收内存。
Best-effort memory protection. If the memory usages of a cgroup and all its ancestors are below their low boundaries,
the cgroup’s memory won’t be reclaimed unless memory can be reclaimed from unprotected cgroups.

不鼓励在此保护下放入超出通常可用的内存。
Putting more memory than generally available under this protection is discouraged.

memory.high
non-root cgroup中的可读写的单值文件。默认值为"max"。
A read-write single value file which exists on non-root cgroups. The default is “max”.

内存使用钳制限制值。这是控制cgroup内存使用的主要机制。如果一个cgroup的使用量超过了此上限,那么这个cgroup中的进程就会受到限制,并承受巨大的回收压力。
Memory usage throttle limit. This is the main mechanism to control memory usage of a cgroup. If a cgroup’s usage goes
over the high boundary, the processes of the cgroup are throttled and put under heavy reclaim pressure.

超过上限永远不会调用OOM killer,在极端情况下,该限制可能会被突破。
Going over the high limit never invokes the OOM killer and under extreme conditions the limit may be breached.

memory.max
non-root cgroup中的可读写单值文件。默认值为"max"。
A read-write single value file which exists on non-root cgroups. The default is “max”.

内存使用硬限制。这是最终的保护机制。如果一个cgroup的内存使用量达到这个限制,并且不能减少,那么会在cgroup中调用OOM killer。在某些情况下,使用量可能会暂时超过此限制。
Memory usage hard limit. This is the final protection mechanism. If a cgroup’s memory usage reaches this limit and
can’t be reduced, the OOM killer is invoked in the cgroup. Under certain circumstances, the usage may go over the limit temporarily.

这是最终的保护机制。只要正确使用和监测上限,此限值的效用仅限于提供最终安全网。
This is the ultimate protection mechanism. As long as the high limit is used and monitored properly, this limit’s
utility is limited to providing the final safety net.

memory.events
non-root cgroup中的只读flat-keyed文件。定义了以下的条目。如果没有特别指定,此文件中值的改变产生文件修改事件。
A read-only flat-keyed file which exists on non-root cgroups. The following entries are defined. Unless specified
otherwise, a value change in this file generates a file modified event.

      low由于内存过高压力cgroup执行回收的次数,即使其使用量处于低边界之下。这通常表示低边界被过度提交。The number of times the cgroup is reclaimed due to high memory pressure even though its usage is underthe low boundary.  This usually indicates that the low boundary is over-committed.high由于超出了高内存边界,cgroup内的进程被限制并路由到执行直接的内存回收的次数。对于内存使用受到上限而不是全局内存压力限制的cgroup,预期会出现此事件。The number of times processes of the cgroup are throttled and routed to perform direct memory reclaimbecause the high memory boundary was exceeded.  For a cgroup whose memory usage is capped by the high limitrather than global memory pressure, this event's occurrences are expected.maxcgroup的内存使用将要超过max边界的次数。如果直接回收失败未能降低内存使用量,cgroup将进入OOM状态。The number of times the cgroup's memory usage was about to go over the max boundary.  If direct reclaimfails to bring it down, the cgroup goes to OOM state.oomcgroup的内存使用达到限制并且分配即将失败的次数。The number of time the cgroup's memory usage was reached the limit and allocation was about to fail.根据上下文的不同,结果可能是调用OOM killer并重新尝试分配或分配失败。Depending on context result could be invocation of OOM killer and retrying allocation or failing alloction.如果分配失败,则可以将-ENOMEM错误码返回到用户空间,或者在磁盘预读等情况下静默的忽略分配失败。目前,如果内存短缺发送在缺页内部,内存cgroup中的OOM killer将终止任务。Failed allocation in its turn could be returned into userspace as -ENOMEM or siletly ignored in cases likedisk readahead.  For now OOM in memory cgroup kills tasks iff shortage has happened inside page fault.oom_kill任何OOM killer杀死的属于此cgroup的进程数量。The number of processes belonging to this cgroup killed by any kind of OOM killer.

memory.stat
non-root cgroup中的只读flat-keyed文件。
A read-only flat-keyed file which exists on non-root cgroups.

这将cgroup的内存占用分解为不同类型的内存、特定类型的详细信息以及有关内存管理系统的状态和过去事件的其他信息。所有内存量均以字节为单位。
This breaks down the cgroup’s memory footprint into different types of memory, type-specific details, and other information
on 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 entries can show up in the middle. Don’t rely on items remaining in a
fixed position; use the keys to look up specific values!

      anon匿名映射中使用的内存量,如brk(), sbrk()和 mmap(MAP_ANONYMOUS)Amount of memory used in anonymous mappings such as brk(), sbrk(), and mmap(MAP_ANONYMOUS)file用于缓存文件系统数据的内存量,包括tmpfs和共享内存。Amount of memory used to cache filesystem data, including tmpfs and shared memory.kernel_stack分配给内核堆栈的内存量。Amount of memory allocated to kernel stacks.slab用于存储内核中数据结构的内存量。Amount of memory used for storing in-kernel datastructures.sock网络传输缓冲区中使用的内存量Amount of memory used in network transmission buffersshmem交换支持的缓存的文件系统数据量,如tmpfs、shm段、共享匿名mmap()sAmount of cached filesystem data that is swap-backed, such as tmpfs, shm segments, shared anonymous mmap()sfile_mapped用mmap()映射的缓存文件系统数据量Amount of cached filesystem data mapped with mmap()file_dirty已修改但尚未写回磁盘的缓存文件系统数据量Amount of cached filesystem data that was modified but not yet written back to diskfile_writeback已修改且当前正在写回磁盘的缓存文件系统数据量Amount of cached filesystem data that was modified and is currently being written back to diskinactive_anon, active_anon, inactive_file, active_file, unevictable Amount of memory, swap-backed and filesystem-backed,页面回收算法使用的内存管理列表on the internal memory management lists used by the page reclaim algorithmslab_reclaimable可能被回收的"slab"的一部分,如dentries 和 inodes。Part of "slab" that might be reclaimed, such as dentries and inodes.slab_unreclaimable在内存压力下无法回收的"slab"部分。Part of "slab" that cannot be reclaimed on memory pressure.pgfault发生的页面错误总数Total number of page faults incurredpgmajfault发生的主要页面错误数Number of major page faults incurredworkingset_refault之前回收的页面的重新失败次数Number of refaults of previously evicted pagesworkingset_activate立即激活的重新出错页数Number of refaulted pages that were immediately activatedworkingset_nodereclaim影子节点的回收次数Number of times a shadow node has been reclaimedpgrefill扫描页面数量(在活动的LRU列表中)Amount of scanned pages (in an active LRU list)pgscan扫描页面数量(在非活动的LRU列表中)Amount of scanned pages (in an inactive LRU list)pgsteal回收页面数量Amount of reclaimed pagespgactivate移动到活动LRU列表的页面数量Amount of pages moved to the active LRU listpgdeactivate移动到非活动LRU列表的页面数量Amount of pages moved to the inactive LRU lispglazyfree内存压力下延迟释放的页面数量Amount of pages postponed to be freed under memory pressurepglazyfreed回收的lazyfree页面数量Amount of reclaimed lazyfree pages

memory.swap.current
non-root cgroup中的只读单值文件。
A read-only single value file which exists on non-root cgroups.

cgroup及其后代当前使用的交换内存总量。
The total amount of swap currently being used by the cgroup and its descendants.

memory.swap.max
non-root cgroup中的可读写单值文件。默认值为"max"。
A read-write single value file which exists on non-root cgroups. The default is “max”.

交换空间使用量硬限制。如果一个cgroup的交换空间使用达到这个限制,则不会交换该cgroup的匿名内存。
Swap usage hard limit. If a cgroup’s swap usage reaches this limit, anonymous meomry of the cgroup will not be swapped out.

Usage Guidelines 使用指南

"memory.high"是控制内存使用的主要机制。过度提交上限(上限总和>可用内存)并且让全局内存压力根据使用情况分配内存是一个可行的策略。

“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 to usage is a viable strategy.

由于违反上限不会触发OOM killer,但会扼杀触犯的cgroup,管理代理有足够的监控和采取适当行动的机会,例如授予更多内存或终止工作负载。

Because breach of the high limit doesn’t trigger the OOM killer but throttles the offending cgroup, a management agent has ample
opportunities to monitor and take appropriate actions such as granting more memory or terminating the workload.

确定一个cgroup是否有足够的内存并不容易,因为内存使用并不指示工作负载是否可从更多可用内存中受益。例如,将从网络接收的数据写入文件的工作负载可以使用所有可用内存,但也可以使用少量内存运行。内存压力的度量 - 由于缺少内存工作负载受到影响 - 是确定工作负载是否需要更多内存所必需的;不幸的是,内存压力监控机制尚未实施。

Determining whether a cgroup has enough memory is not trivial as memory usage doesn’t indicate whether the workload can benefit from
more memory. For example, a workload which writes data received from network to a file can use all available memory but can also operate as
performant with a small amount of memory. A measure of memory pressure - how much the workload is being impacted due to lack of
memory - is necessary to determine whether a workload needs more memory; unfortunately, memory pressure monitoring mechanism isn’t
implemented yet.

Memory Ownership 内存所有权

一个内存区域被填充到实例化它的cgroup,并保持到在cgroup中,直到该内存区域的释放为止。迁移进程到不同的cgroup,不会将它在前一个cgroup中实例化的内存使用量移动到新的cgroup。

A memory area is charged to the cgroup which instantiated it and stays charged to the cgroup until the area is released. Migrating a process
to a different cgroup doesn’t move the memory usages that it instantiated while in the previous cgroup to the new cgroup.

属于不同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 has enough memory allowance to avoid high reclaim pressure.

如果一个cgroup清理了大量的内存,而其他cgroup预期会重复访问这些内存,那么使用POSIX_FADV_DONTNEED可能是有意义的。放弃属于受影响文件的内存区域的所有权,以确保正确的内存所有权。

If a cgroup sweeps a considerable amount of memory which is expected to be accessed repeatedly by other cgroups, it may make sense to use
POSIX_FADV_DONTNEED to relinquish the ownership of memory areas belonging to the affected files to ensure correct memory ownership.

IO 输入输出

"io"控制器控制IO资源的分配。此控制器实现基于权重和绝对带宽或IOPS限制的资源分配;但是,只有cfq-iosched在使用中且其它两种方案都不适用blk-mq设备的情况下,基于权重的分配才可用。

The “io” controller regulates the distribution of IO resources. This controller implements both weight based and absolute bandwidth or IOPS
limit distribution; however, weight based distribution is available only if cfq-iosched is in use and neither scheme is available for
blk-mq devices.

IO Interface Files 输入输出接口文件

io.stat
non-root cgroup中的只读nested-keyed文件。
A read-only nested-keyed file which exists on non-root cgroups.

 每一行由$MAJ:$MIN设备编号做键值,未排序。定义了以下的嵌套键值。Lines are keyed by $MAJ:$MIN device numbers and not ordered. The following nested keys are defined.======        ===================rbytes        Bytes readwbytes        Bytes writtenrios          Number of read IOswios          Number of write IOs======        ===================以下示例是一个读操作的输出:An example read output follows:8:16 rbytes=1459200 wbytes=314773504 rios=192 wios=3538:0 rbytes=90430464 wbytes=299008000 rios=8950 wios=1252

io.weight

    non-root cgroup中的可读写flat-keyed文件。默认值为"default 100"。A read-write flat-keyed file which exists on non-root cgroups. The default is "default 100".第一行是应用于没有特定覆盖的设备的默认权重。其余的是以$MAJ:$MIN设备编号为键值的覆盖,没有排序。权重在[1,10000]范围内,并指定cgroup相对于其同级cgroup可以使用的相对IO时间量。The first line is the default weight applied to devices without specific override.  The rest are overrides keyed by$MAJ:$MIN device numbers and not ordered.  The weights are in the range [1, 10000] and specifies the relative amount IO timethe cgroup can use in relation to its siblings.默认权重可以通过写入"default $WEIGHT"或简单地写入"$WEIGHT"来更新。可以通过写入"$MAJ:$MIN $WEIGHT"来设置覆盖,并通过写入"$MAJ:$MIN default"来取消设置覆盖。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

    non-root cgroup中的可读写nested-keyed文件。A read-write nested-keyed file which exists on non-root cgroups.基于BPS和IOPS的IO限制。每一行以$MAJ:$MIN设备号为键值,未排序。定义了以下的嵌套键值。BPS and IOPS based IO limit.  Lines are keyed by $MAJ:$MIN device numbers and not ordered.  The following nested keys are defined.=====         ==================================rbps          Max read bytes per secondwbps          Max write bytes per secondriops         Max read IO operations per secondwiops         Max write IO operations per second=====         ==================================写入时,可以按任意顺序指定任意数量的嵌套键值对。可以指定"max"以移除特定的限制值。如果多次指定同一个键,则结果未定义。When writing, any number of nested key-value pairs can be specified in any order.  "max" can be specified as the valueto remove a specific limit.  If the same key is specified multiple times, the outcome is undefined.在每个IO方向测量BPS和IOPS,如果达到限制,IOs将延迟。但允许临时的突发。BPS and IOPS are measured in each IO direction and IOs are delayed if limit is reached.  Temporary bursts are allowed.将设备号为8:16的设备的读操作限制设置为2M BPS,写操作限制为120 IOPS:Setting read limit at 2M BPS and write at 120 IOPS for 8:16::echo "8:16 rbps=2097152 wiops=120" > io.max读返回以下值:Reading returns the following::8:16 rbps=2097152 wbps=max riops=max wiops=120写入以下值可移除写操作的IOPS限制值:Write IOPS limit can be removed by writing the following::echo "8:16 wiops=max" > io.max限制读返回以下值:Reading now returns the following::8:16 rbps=2097152 wbps=max riops=max wiops=max

Writeback 回写

页面缓存通过缓存写入和共享mmap实现dirty化,并通过回写机制异步的写入支持文件系统。回写位于内存和IO域之间,通过dirty化和写IO来调节dirty内存的比例。

Page cache is dirtied through buffered writes and shared mmaps and written asynchronously to the backing filesystem by the writeback
mechanism. Writeback sits between the memory and IO domains and regulates the proportion of dirty memory by balancing dirtying and write IOs.

IO控制器与内存控制器一起实现对页面缓存回写IO的控制。内存控制器定义了计算和维护dirty内存比率的内存域,IO控制器定义了为内存域回写dirty页面的IO域。系统范围和每个cgroup范围的dirty内存状态都会被检查,并且这两种状态的限制性更强。

The io controller, in conjunction with the memory controller, implements control of page cache writeback IOs. The memory controller
defines the memory domain that dirty memory ratio is calculated and maintained for and the io controller defines the io domain which
writes out dirty pages for the memory domain. Both system-wide and per-cgroup dirty memory states are examined and the more restrictive
of the two is enforced.

cgroup回写需要底层文件系统的显式支持。目前,cgroup回写是在ext2、ext4和btrf上实现的。在其他文件系统上,所有回写IO都属于root cgroup。

cgroup writeback requires explicit support from the underlying filesystem. Currently, cgroup writeback is implemented on ext2, ext4
and btrfs. On other filesystems, all writeback IOs are attributed to the root cgroup.

内存和回写管理间存在固有的差异,这会影响对cgroup所有权的跟踪方式。内存按照页面跟踪,而回写按照每个inode进行跟踪。为了回写,一个inode被分配给一个cgroup,所有从inode写入dirty页的IO请求都被分配给该cgroup。

There are inherent differences in memory and writeback management which affects how cgroup ownership is tracked. Memory is tracked per
page while writeback per inode. For the purpose of writeback, an inode is assigned to a cgroup and all IO requests to write dirty pages
from the inode are attributed to that cgroup.

由于cgroup对内存的所有权由每个页面跟踪,因此可能存在与inode关联的不同cgroup的页面。这些页面称为外部页面。回写将持续跟踪外部页面,如果某个特定的外部cgroup在某段时间内占多数,则会将inode的所有权切换到该cgroup。

As cgroup ownership for memory is tracked per page, there can be pages which are associated with different cgroups than the one the inode is
associated with. These are called foreign pages. The writeback constantly keeps track of foreign pages and, if a particular foreign
cgroup becomes the majority over a certain period of time, switches the ownership of the inode to that cgroup.

虽然这个模型对于大多数用例来说已经足够了,在这些用例中,一个给定的inode大部分情况下被单个cgroup所标记为dirty,即使主要的写操作cgroup随着时间的推移而改变,但是不支持多个cgroup同时写入一个inode的用例。在这种情况下,很大一部分的IOs可能会被错误地做归属。由于内存控制器在第一次使用时分配页面所有权,直到释放页面后才会更新,即使回写严格遵循页面所有权,多个cgroups脏化重叠区域也无法按预期工作。建议避免这种使用模式。

While this model is enough for most use cases where a given inode is mostly dirtied by a single cgroup even when the main writing cgroup
changes over time, use cases where multiple cgroups write to a single inode simultaneously are not supported well. In such circumstances, a
significant portion of IOs are likely to be attributed incorrectly. As memory controller assigns page ownership on the first use and
doesn’t update it until the page is released, even if writeback strictly follows page ownership, multiple cgroups dirtying overlapping
areas wouldn’t work as expected. It’s recommended to avoid such usage patterns.

影响回写行为的sysctl开关如下所示应用于cgroup回写。
The sysctl knobs which affect writeback behavior are applied to cgroup writeback as follows.

vm.dirty_background_ratio, vm.dirty_ratio
这些比率同样适用于cgroup回写,可用内存量受内存控制器和系统范围的干净内存所施加的限制所限制。
These ratios apply the same to cgroup writeback with the amount of available memory capped by limits imposed by the
memory controller and system-wide clean memory.

vm.dirty_background_bytes, vm.dirty_bytes
对于cgroup回写,将其计算为总可用内存的比率,并采用与vm.dirty[_background]_ratio相同的应用方式。
For cgroup writeback, this is calculated into ratio against total available memory and applied the same way as
vm.dirty[_background]_ratio.

PID 进程ID

进程号控制器用于允许cgroup在达到指定限制后停止任何新任务的fork()或clone()。
The process number controller is used to allow a cgroup to stop any new tasks from being fork()'d or clone()'d after a specified limit is
reached.

一个cgroup中的任务数量可以以其他控制器无法阻止的方式耗尽,从而保证自己的控制器。例如,一个fork炸弹可能会在达到内存限制之前耗尽任务的数量。

The number of tasks in a cgroup can be exhausted in ways which other controllers cannot prevent, thus warranting its own controller. For
example, a fork bomb is likely to exhaust the number of tasks before hitting memory restrictions.

请注意,此控制器中使用的PIDs指的是TIDs,内核使用的为进程ID。
Note that PIDs used in this controller refer to TIDs, process IDs as used by the kernel.

PID Interface Files 进程ID接口文件

pids.max
non-root cgroup中的可读写的单值文件。默认值为"max"。
A read-write single value file which exists on non-root cgroups. The default is “max”.

进程数的硬限制。
Hard limit of number of processes.

pids.current
所有cgroup上都存在的只读单值文件。
A read-only single value file which exists on all cgroups.

当前在cgroup及其子代中的进程数。
The number of processes currently in the cgroup and its descendants.

cgroup策略不会阻止组织化的操作,因此很可能出现情况:pids.current > pids.max。这可通过将限制值设置为小于pids.current,或者将足够多的进程附加到cgroup以使pids.current大于pids.max。但是,它是不可能通过fork()或clone()违反cgroup的PID策略的。如果创建新进程会导致违反cgroup策略,则返回-EAGAIN。

Organisational operations are not blocked by cgroup policies, so it is possible to have pids.current > pids.max. This can be done by either
setting the limit to be smaller than pids.current, or attaching enough processes to the cgroup such that pids.current is larger than
pids.max. However, it is not possible to violate a cgroup PID policy through fork() or clone(). These will return -EAGAIN if the creation
of a new process would cause a cgroup policy to be violated.

RDMA 远程DMA

"rdma"控制器管理RDMA资源的分配和记账。
The “rdma” controller regulates the distribution and accounting of of RDMA resources.

RDMA Interface Files 远程DMA接口文件

rdma.max
存在于除root外的所有cgroup种的可读写nested-keyed文件,由于描述RDMA/IB设备当前配置的资源限制。
A readwrite nested-keyed file that exists for all the cgroups except root that describes current configured resource limit
for a RDMA/IB device.

每一行以设备名称为键值,不排序。每一行包含以空格分开的资源名称及其配置的可分配的限制。
Lines are keyed by device name and are not ordered. Each line contains space separated resource name and its configured
limit that can be distributed.

定义了以下的嵌套键值。
The following nested keys are defined.

      ==========    =============================hca_handle    Maximum number of HCA Handleshca_object    Maximum number of HCA Objects==========    =============================

以下为mlx4 和 ocrdma设备的示例。
An example for mlx4 and ocrdma device follows::

      mlx4_0 hca_handle=2 hca_object=2000ocrdma1 hca_handle=3 hca_object=max

rdma.current
描述当前资源使用情况的只读文件。存在于除root之外的所有cgroup中。
A read-only file that describes current resource usage. It exists for all the cgroup except root.

以下为mlx4 和 ocrdma设备的示例。
An example for mlx4 and ocrdma device follows::

      mlx4_0 hca_handle=1 hca_object=20ocrdma1 hca_handle=1 hca_object=23

Misc 杂项

perf_event

perf_event控制器,如果没有挂载在传统的体系结构上,将自动在v2体系中使能,以便cgroup v2路径总能过滤性能事件。控制器仍然可在v2体系populated之后移动到传统体系内。

perf_event controller, if not mounted on a legacy hierarchy, is automatically enabled on the v2 hierarchy so that perf events can
always be filtered by cgroup v2 path. The controller can still be moved to a legacy hierarchy after v2 hierarchy is populated.

Namespace 命名空间

Basics

cgroup命名空间提供将"/proc/PID/cgroup"文件和cgroup挂载虚拟化的机制。CLONENEWCGROUP克隆clone标志可传递与clone(2)和unshare(2)系统调用以创建新的cgroup命名空间。运行在cgroup命名空间内部的进程的"/proc/PID/cgroup"文件和cgroup挂载虚拟化的机制。CLONE_NEWCGROUP克隆clone标志可传递与clone(2) 和 unshare(2) 系统调用以创建新的cgroup命名空间。运行在cgroup命名空间内部的进程的"/proc/PID/cgroup"文件和cgroup挂载虚拟化的机制。CLONEN​EWCGROUP克隆clone标志可传递与clone(2)和unshare(2)系统调用以创建新的cgroup命名空间。运行在cgroup命名空间内部的进程的"/proc/PID/cgroup"文件输出限制在cgroupns根。cgroupns根是在创建cgroup命名空间之时进程所在的cgroup。

cgroup namespace provides a mechanism to virtualize the view of the “/proc/PID/cgroup"fileandcgroupmounts.TheCLONENEWCGROUPcloneflagcanbeusedwithclone(2)andunshare(2)tocreateanewcgroupnamespace.Theprocessrunninginsidethecgroupnamespacewillhaveits"/proc/PID/cgroup" file and cgroup mounts. The CLONE_NEWCGROUP clone flag can be used with clone(2) and unshare(2) to create a new cgroup namespace. The process running inside the cgroup namespace will have its "/proc/PID/cgroup"fileandcgroupmounts.TheCLONEN​EWCGROUPcloneflagcanbeusedwithclone(2)andunshare(2)tocreateanewcgroupnamespace.Theprocessrunninginsidethecgroupnamespacewillhaveits"/proc/PID/cgroup” output restricted to cgroupns root. The cgroupns root is the cgroup of the process at the time of creation of
the cgroup namespace.

没有cgroup命名空间的话,"/proc/PID/cgroup"文件显示的是进程所属cgroup的完整路径。在容器环境下,一组cgroups和命名空间试图隔离进程的"/proc/PID/cgroup"文件显示的是进程所属cgroup的完整路径。在容器环境下,一组cgroups和命名空间试图隔离进程的"/proc/PID/cgroup"文件显示的是进程所属cgroup的完整路径。在容器环境下,一组cgroups和命名空间试图隔离进程的"/proc/PID/cgroup"文件,可能泄露潜在的系统级别的信息到隔离的进程。如示例:

Without cgroup namespace, the “/proc/PID/cgroup"fileshowsthecompletepathofthecgroupofaprocess.Inacontainersetupwhereasetofcgroupsandnamespacesareintendedtoisolateprocessesthe"/proc/PID/cgroup" file shows the complete path of the cgroup of a process. In a container setup where a set of cgroups and namespaces are intended to isolate processes the "/proc/PID/cgroup"fileshowsthecompletepathofthecgroupofaprocess.Inacontainersetupwhereasetofcgroupsandnamespacesareintendedtoisolateprocessesthe"/proc/PID/cgroup” file may leak potential system level information
to the isolated processes. For Example::

  # cat /proc/self/cgroup0::/batchjobs/container_id1

路径’/batchjobs/container_id1’可认为是system-data,并且不想泄露到隔离的进程。cgroup命名空间可由于限制此路径的可视性。例如,在创建cgroup命名空间之前,可见如下信息:

The path ‘/batchjobs/container_id1’ can be considered as system-data and undesirable to expose to the isolated processes. cgroup namespace
can be used to restrict visibility of this path. For example, before creating 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

unsharing新的命名空间之后,信息变为如下:
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::/

当一个多线程的进程的某些线程unshare它们的cgroup命名空间,新的cgroupns应用到整个进程(所有的线程)。对于v2体系这是自然的,但是对于传统体系,这将时不可预测的。

When some thread from a multi-threaded process unshares its cgroup namespace, the new cgroupns gets applied to the entire process (all
the threads). This is natural for the v2 hierarchy; however, for the legacy hierarchies, this may be unexpected.

只要有进程在内部或挂载绑定它,cgroup名称空间就处于活动状态。当最后一个用法消失时,cgroup名称空间将被销毁。cgroupns根和实际的cgroups保持不变。

A cgroup namespace is alive as long as there are processes inside or mounts pinning it. When the last usage goes away, the cgroup
namespace is destroyed. The cgroupns root and the actual cgroups remain.

The Root and Views 根和视图

cgroup命名空间的’cgroupns root’是调用unshare(2)时正在运行的进程的cgroup。例如,/batchjobs/container_id1 cgroup中的进程调用unshare,cgroup /batchjobs/container_id1变成为cgroupns root。对于init_cgroup_ns,其是真正的根(’/’)cgroup。

The ‘cgroupns root’ for a cgroup namespace is the cgroup in which the process 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 the
init_cgroup_ns, this is the real root (’/’) cgroup.

cgroupns root cgroup不会改变,即使之后创建命名空间的进程移动到了一个不同的cgroup:
The cgroupns root cgroup does not change even if the namespace creator process 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

每个进程有其命名空间特定的"/proc/PID/cgroup"视图。Eachprocessgetsitsnamespace−specificviewof"/proc/PID/cgroup"视图。 Each process gets its namespace-specific view of "/proc/PID/cgroup"视图。Eachprocessgetsitsnamespace−specificviewof"/proc/PID/cgroup"

运行在cgroup命名空间中的进程将仅可看到它们在root cgroup中的cgroup路径(在文件/proc/self/cgroup中),
Processes running inside the cgroup namespace will be able to see cgroup paths (in /proc/self/cgroup) only inside their root cgroup.

从unshared cgroupns内开始:
From within an unshared cgroupns::

  # sleep 100000 &[1] 7353# echo 7353 > sub_cgrp_1/cgroup.procs# cat /proc/7353/cgroup0::/sub_cgrp_1

从最初的cgroup命名空间,可见真实的cgroup路径:
From the initial cgroup namespace, the real cgroup path will be visible::

  $ cat /proc/7353/cgroup0::/batchjobs/container_id1/sub_cgrp_1

从兄弟cgroup命名空间(即,根植在不同cgroup的命名空间),相对于其自身cgroup命名空间的cgroup路径将显示。例如,如果PID 7353的cgroup命名空间root是’/batchjobs/container_id2’,其显示如下:

From a sibling cgroup namespace (that is, a namespace rooted at a different cgroup), the cgroup path relative to its own cgroup
namespace root will be shown. For instance, if PID 7353’s cgroup namespace root is at ‘/batchjobs/container_id2’, then it will see::

  # cat /proc/7353/cgroup0::/../container_id2/sub_cgrp_1

注意相对路径总是以’/'开头,表明其是相对于调用者的cgroup命名空间root。
Note that the relative path always starts with ‘/’ to indicate that its relative to the cgroup namespace root of the caller.

Migration and setns(2) 迁移和setns(2)

cgroup命名空间中的进程可移动到或移除命名空间根root,前提是其具有外部cgroup的合适访问权限。例如,在一个cgroupns根为/batchjobs/container_id1的命名空间内,假设全局体系结构在cgroupns内部仍然可访问:

Processes inside a cgroup namespace can move into and out of the namespace root if they have proper access to external cgroups. For
example, from inside a namespace with cgroupns root at /batchjobs/container_id1, and assuming that the global hierarchy is
still accessible inside cgroupns::

  # cat /proc/7353/cgroup0::/sub_cgrp_1# echo 7353 > batchjobs/container_id2/cgroup.procs# cat /proc/7353/cgroup0::/../container_id2

注意不鼓励这种配置。cgroup命名空间内部的进程仅应开放给其自身cgroupns体系。
Note that this kind of setup is not encouraged. A task inside cgroup namespace should only be exposed to its own cgroupns hierarchy.

setns(2)到另外的cgroup命名空间在以下情况是允许的:
setns(2) to another cgroup namespace is allowed when:

(a) 相对于其当前的用户命名空间,进程具有CAP_SYS_ADMIN权限
(a) the process has CAP_SYS_ADMIN against its current user namespace

(b) 相对于目标cgroup命名空间的userns,进程具有CAP_SYS_ADMIN权限。
(b) the process has CAP_SYS_ADMIN against the target cgroup namespace’s userns

当连接到另外的cgroup命名空间时,没有隐含的cgroup改变发生。期待某人移动连接的进程到目标cgroup命名空间root之下。
No implicit cgroup changes happen with attaching to another cgroup namespace. It is expected that the someone moves the attaching
process under the target cgroup namespace root.

Interaction with Other Namespaces 与其它命名空间交互

命名空间特定的cgroup层次结构可以由在non-init cgroup命名空间内运行的进程挂载。
Namespace specific cgroup hierarchy can be mounted by a process running inside a non-init cgroup namespace::

# mount -t cgroup2 none $MOUNT_POINT

这将安装统一的cgroup体系结构,其以cgroupns根作为文件系统根。该进程需要对其用户和挂载命名空间具有CAP_SYS_ADMIN权限。
This will mount the unified cgroup hierarchy with cgroupns root as the filesystem root. The process needs CAP_SYS_ADMIN against its user and
mount namespaces.

/proc/self/cgroup文件的虚拟化与通过命名空间私有 cgroupfs 挂载实现的cgroup体系结构限制视图相结合,在容器内提供了一个适当隔离的cgroup视图。

The virtualization of /proc/self/cgroup file combined with restricting the view of cgroup hierarchy by namespace-private cgroupfs mount
provides a properly isolated cgroup view inside the container.

Information on Kernel Programming 内核编程相关信息

本节包含了在需要与cgroup交互的领域中的内核编程信息。不包括cgroup核心和控制器。
This section contains kernel programming information in the areas where interacting with cgroup is necessary. cgroup core and
controllers are not covered.

Filesystem Support for Writeback 文件系统对回写的支持

文件系统可以通过更新address_space_operations->writepages来支持cgroup回写,以使用以下两个函数对bio进行注释。
A filesystem can support cgroup writeback by updating address_space_operations->writepages to annotate bio’s using the
following two functions.

wbc_init_bio(@wbc, @bio)
应该为每个携带回写数据的bio进行调用,并将该bio与inode的所有者cgroup关联起来。可以在bio分配和提交之间的任意时间调用。
Should be called for each bio carrying writeback data and associates the bio with the inode’s owner cgroup. Can be
called anytime between bio allocation and submission.

wbc_account_io(@wbc, @page, @bytes)
应为正在写出的每个数据段调用。虽然这个函数并不关心在回写会话中何时调用它,但是在将数据段添加到bio中时调用它是最简单和最自然的。
Should be called for each data segment being written out. While this function doesn’t care exactly when it’s called
during the writeback session, it’s the easiest and most natural to call it as data segments are added to a bio.

通过回写bio的注释,可以通过在->s_iflags中设置SB_I_CGROUPWB标志来启用基于每个super_block的cgroup支持。这允许选择性地禁用cgroup回写支持,当某些文件系统功能(例如日志数据模式)不兼容时,这种支持非常有用。

With writeback bio’s annotated, cgroup support can be enabled per super_block by setting SB_I_CGROUPWB in ->s_iflags. This allows for
selective disabling of cgroup writeback support which is helpful when certain filesystem features, e.g. journaled data mode, are
incompatible.

wbc_init_bio()将指定的bio绑定到其cgroup。根据配置的不同,可以低优先级执行BIO,如果回写会话持有共享资源(例如日志条目),则可能导致优先级反转。这个问题没有一个简单的解决办法。文件系统可以尝试通过跳过wbc_init_bio()或直接使用bio_associate_blkcg()来解决特定的问题。

wbc_init_bio() binds the specified bio to its cgroup. Depending on the configuration, the bio may be executed at a lower priority and if
the writeback session is holding shared resources, e.g. a journal entry, may lead to priority inversion. There is no one easy solution
for the problem. Filesystems can try to work around specific problem cases by skipping wbc_init_bio() or using bio_associate_blkcg()
directly.

Deprecated v1 Core Features 废弃的v1版核心功能

  • 不支持多层级结构,包括命名层级结构。

  • Multiple hierarchies including named ones are not supported.

  • 不支持所有v1挂载选项。

  • All v1 mount options are not supported.

  • 移除了"tasks"文件,不对"cgroup.procs"排序。

  • The “tasks” file is removed and “cgroup.procs” is not sorted.

  • 移除了"cgroup.clone_children"

  • “cgroup.clone_children” is removed.

  • /proc/cgroups 对v2版无意义。相反使用root中的"cgroup.controllers"文件。

  • /proc/cgroups is meaningless for v2. Use “cgroup.controllers” file at the root instead.

Issues with v1 and Rationales for v2 v1版问题及v2版原理

Multiple Hierarchies 多层级体系

cgroup v1允许任意数量的层级结构,每个层级结构可以承载任意数量的控制器。虽然这似乎提供了很高的灵活性,但在实践中并没有用。
cgroup v1 allowed an arbitrary number of hierarchies and each hierarchy could host any number of controllers. While this seemed to
provide a high level of flexibility, it wasn’t useful in practice.

例如,由于每个控制器只有一个实例,因此即使在所有层次结构中都可用的实用类型控制器(如freezer)也只能在一个层级机构中使用。一旦填充了层级结构,控制器就不能移动到另一个层级结构,这一事实加剧了这个问题。另一个问题是,绑定到层级结构的所有控制器都被强制具有完全相同的层级结构视图。不可能依据特定的控制器改变粒度。

For example, as there is only one instance of each controller, utility type controllers such as freezer which can be useful in all
hierarchies could only be used in one. The issue is exacerbated by the fact that controllers couldn’t be moved to another hierarchy once
hierarchies were populated. Another issue was that all controllers bound to a hierarchy were forced to have exactly the same view of the
hierarchy. It wasn’t possible to vary the granularity depending on the specific controller.

在实践中,这些问题严重限制了哪些控制器可以放在同一层级上,大多数配置都是将每个控制器放在自己的层级上。只有密切相关的控制器(如cpu和cpuacct控制器)置于同一层级结构中才有意义。这通常意味着,当需要层级管理操作时,用户空间最终会管理多个类似的层级结构,并在每个层级结构上重复相同的步骤。

In practice, these issues heavily limited which controllers could be put on the same hierarchy and most configurations resorted to putting
each controller on its own hierarchy. Only closely related ones, such as the cpu and cpuacct controllers, made sense to be put on the same
hierarchy. This often meant that userland ended up managing multiple similar hierarchies repeating the same steps on each hierarchy
whenever a hierarchy management operation was necessary.

此外,对多层级结构的支持付出了巨大的代价。它极大地复杂化了cgroup的核心实现,但更重要的是,对多层级结构的支持限制了cgroup在通常情况下的使用方式和控制器的功能。

Furthermore, support for multiple hierarchies came at a steep cost. It greatly complicated cgroup core implementation but more importantly
the support for multiple hierarchies restricted how cgroup could be used in general and what controllers was able to do.

对可能存在的层级结构数量没有限制,这意味着线程的cgroup成员身份不能用有限的长度描述。键可能包含任意数量的条目,并且长度不受限制,这使得操作非常困难,并导致添加仅用于标识成员身份的控制器,从而又加剧了原始层级结构数量激增的问题。

There was no limit on how many hierarchies there might be, which meant that a thread’s cgroup membership couldn’t be described in finite
length. The key might contain any number of entries and was unlimited in length, which made it highly awkward to manipulate and led to
addition of controllers which existed only to identify membership, which in turn exacerbated the original problem of proliferating number
of hierarchies.

此外,由于控制器不能对其他控制器所在的层级结构的拓扑有任何期望,因此每个控制器必须假定所有其他控制器都连接到完全正交的层级结构。这使得控制器之间无法合作,或者至少非常麻烦。

Also, as a controller couldn’t have any expectation regarding the topologies of hierarchies other controllers might be on, each
controller had to assume that all other controllers were attached to completely orthogonal hierarchies. This made it impossible, or at
least very cumbersome, for controllers to cooperate with each other.

在大多数用例中,不需要将控制器放在相互完全正交的层级结构上。通常需要的是根据特定的控制器具有不同粒度级别的能力。换句话说,当从特定控制器查看时,层级结构可能从叶子向根折叠。例如,一个给定的配置可能不关心内存如何在超过某个级别外的分配,而仍然希望控制CPU周期的分配。

In most use cases, putting controllers on hierarchies which are completely orthogonal to each other isn’t necessary. What usually is
called for is the ability to have differing levels of granularity depending on the specific controller. In other words, hierarchy may
be collapsed from leaf towards root when viewed from specific controllers. For example, a given configuration might not care about
how memory is distributed beyond a certain level while still wanting to control how CPU cycles are distributed.

Thread Granularity 线程粒度

cgroup v1允许进程的线程属于不同的cgroup。这对某些控制器来说没有意义,而这些控制器最终实现了不同的方法来忽略这些情况,但更重要的是,它模糊了开放给单个应用程序和系统管理接口之间的API的界限。

cgroup v1 allowed threads of a process to belong to different cgroups. This didn’t make sense for some controllers and those controllers
ended up implementing different ways to ignore such situations but much more importantly it blurred the line between API exposed to
individual applications and system management interface.

通常,进程内内容只对进程本身可用;因此,与进程的服务级别组织不同,对进程的线程进行分类需要目标进程的应用程序的积极参与。

Generally, in-process knowledge is available only to the process itself; thus, unlike service-level organization of processes,
categorizing threads of a process requires active participation from the application which owns the target process.

cgroup v1有一个模糊定义的委托模型,它与线程粒度的结合被滥用。cgroups被委托给单个应用程序,这样它们就可以创建和管理自己的子层级结构,并控制沿着它们的资源分配。这有效地将cgroup提升到了一个类似系统调用API的状态,此API开放给lay programs。

cgroup v1 had an ambiguously defined delegation model which got abused in combination with thread granularity. cgroups were delegated to
individual applications so that they can create and manage their own sub-hierarchies and control resource distributions along them. This
effectively raised cgroup to the status of a syscall-like API exposed to lay programs.

首先,cgroup以这种方式开放了一个基本上不充分的接口。要让进程访问自己的开关,它必须从/proc/self/cgroup中提取目标层级结构上的路径,通过将开关的名称附加到路径来构造路径,打开然后读取和/或写入。这不仅是极其笨拙和不寻常的,而且存在固有的竞争。没有常规的方法来定义跨所需步骤的事务,也没有任何方法可以保证进程实际上是在自己的子层级结构上运行的。

First of all, cgroup has a fundamentally inadequate interface to be exposed this way. For a process to access its own knobs, it has to
extract the path on the target hierarchy from /proc/self/cgroup, construct the path by appending the name of the knob to the path, open
and then read and/or write to it. This is not only extremely clunky and unusual but also inherently racy. There is no conventional way to
define transaction across the required steps and nothing can guarantee that the process would actually be operating on its own sub-hierarchy.

cgroup控制器实现了许多开关,这些开关永远不会被接受为公开的API,因为它们只是将控制开关添加到系统管理伪文件系统中。cgroup最后以接口开关结束,这些开关没有被正确地抽象或提炼,并且直接显示内核内部细节。这些开关通过定义不清的委托机制暴露在单个应用程序中,实际上滥用cgroup作为实现公共API的快捷方式,而无需经过必要的审查。

cgroup controllers implemented a number of knobs which would never be accepted as public APIs because they were just adding control knobs to
system-management pseudo filesystem. cgroup ended up with interface knobs which were not properly abstracted or refined and directly
revealed kernel internal details. These knobs got exposed to individual applications through the ill-defined delegation mechanism
effectively abusing cgroup as a shortcut to implementing public APIs without going through the required scrutiny.

这对用户和内核都是痛苦的。最终,用户层面出现了行为不当、抽象性差的接口,并且内核意外地暴露并锁定到构造中。

This was painful for both userland and kernel. Userland ended up with misbehaving and poorly abstracted interfaces and kernel exposing and
locked into constructs inadvertently.

Competition Between Inner Nodes and Threads 内部节点与线程间的竞争

cgroup v1允许线程位于任何cgroup中,这就产生了一个有趣的问题:属于父cgroup的线程及其子cgroup竞争资源。这是令人讨厌的,因为两种不同类型的实体竞争,没有明显的解决办法。不同的控制器做了不同的事情。

cgroup v1 allowed threads to be in any cgroups which created an interesting problem where threads belonging to a parent cgroup and its
children cgroups competed for resources. This was nasty as two different types of entities competed and there was no obvious way to
settle it. Different controllers did different things.

CPU控制器将线程和cgroups视为等价物,并将nice级别映射到cgroup权重。这在某些情况下是有效的,但是当子辈想要被分配特定比率的CPU周期,而内部线程的数量在波动时 — 这比率将随着竞争实体(线程)的数量的波动而不断变化。还有其他问题。从nice等级到权重的映射并不明显,也不通用,还有各种各样的开关,它们根本无法用于线程。

The cpu controller considered threads and cgroups as equivalents and mapped nice levels to cgroup weights. This worked for some cases but
fell flat when children wanted to be allocated specific ratios of CPU cycles and the number of internal threads fluctuated - the ratios
constantly changed as the number of competing entities fluctuated. There also were other issues. The mapping from nice level to weight
wasn’t obvious or universal, and there were various other knobs which simply weren’t available for threads.

IO控制器隐含地为每个cgroup创建了一个隐藏的叶节点来承载线程。隐藏的叶子有它自己的所有开关的副本,前缀是leaf_。虽然这允许对内部线程进行等效的控制,但它有严重的缺点。它总是添加一个额外的不应需要的嵌套层,这会使接口变得混乱,并使实现变得非常复杂。

The io controller implicitly created a hidden leaf node for each cgroup to host the threads. The hidden leaf had its own copies of all
the knobs with leaf_ prefixed. While this allowed equivalent control over internal threads, it was with serious drawbacks. It
always added an extra layer of nesting which wouldn’t be necessary otherwise, made the interface messy and significantly complicated the
implementation.

Memory控制器无法控制内部任务和子cgroups之间发生的事情,并且行为没有明确定义。试图添加一些ad-hoc的行为和开关,以根据特定的工作负载来调整行为,这将导致长期难以解决的问题。

The memory controller didn’t have a way to control what happened between internal tasks and child cgroups and the behavior was not
clearly defined. There were attempts to add ad-hoc behaviors and knobs to tailor the behavior to specific workloads which would have
led to problems extremely difficult to resolve in the long term.

多个控制器在处理内部任务时遇到了困难,并提出了不同的处理方法;不幸的是,所有的方法都存在严重的缺陷,而且,广泛的不同行为使得整个cgroup系统高度不一致。

Multiple controllers struggled with internal tasks and came up with different ways to deal with it; unfortunately, all the approaches were
severely flawed and, furthermore, the widely different behaviors made cgroup as a whole highly inconsistent.

这显然是一个需要从cgroup核心统一解决的问题。
This clearly is a problem which needs to be addressed from cgroup core in a uniform way.

Other Interface Issues 其它接口问题

cgroup v1在没有监督的情况下增长,并发展出大量的特性和不一致。cgroup核心方面的一个问题是如何通知空cgroup - 为每个事件分配和执行一个userland helper可执行程序。事件传递不是递归的或可委托的。该机制的局限性还导致内核内事件传递过滤机制进一步使接口复杂化。

cgroup v1 grew without oversight and developed a large number of idiosyncrasies and inconsistencies. One issue on the cgroup core side
was how an empty cgroup was notified - a userland helper binary was forked and executed for each event. The event delivery wasn’t
recursive or delegatable. The limitations of the mechanism also led to in-kernel event delivery filtering mechanism further complicating
the interface.

控制器接口也有问题。一个极端的例子是,控制器完全忽略层级组织,将所有cgroup视为直接位于根cgroup之下。一些控制器向用户空间开放了大量不一致的实现细节。

Controller interfaces were problematic too. An extreme example is controllers completely ignoring hierarchical organization and treating
all cgroups as if they were all located directly under the root cgroup. Some controllers exposed a large amount of inconsistent
implementation details to userland.

控制器之间也没有一致性。创建新的cgroup时,一些控制器默认不施加额外的限制,而其他控制器则不允许任何资源的使用,直到显式配置完成。相同类型控件的配置开关使用了广泛不同的命名方案和格式。统计和信息开关是任意命名的,即使在同一个控制器中也使用不同的格式和单位。

There also was no consistency across controllers. When a new cgroup was created, some controllers defaulted to not imposing extra
restrictions while others disallowed any resource usage until explicitly configured. Configuration knobs for the same type of
control used widely differing naming schemes and formats. Statistics and information knobs were named arbitrarily and used different
formats and units even in the same controller.

cgroup v2在适当的地方建立了公共约定,并更新控制器,以便它们开放最小且一致的接口。

cgroup v2 establishes common conventions where appropriate and updates controllers so that they expose minimal and consistent interfaces.

Controller Issues and Remedies 控制器问题及扑救措施

Memory 内存

原始下限(软限制)定义为默认未设置的限制。因此,全局回收首选的cgroups集是opt-in,而不是opt-out。优化这些主要的反向查找的成本是如此之高,以至于尽管实现的规模巨大,但它甚至不能提供基本的期望行为。首先,软极限没有层级意义。所有配置的组都组织在全局rbtree中,并被视为对等的个体,不管它们位于层级结构中的什么位置。这使得子树委托成为不可能。第二,软限制回收许可非常激进,它不仅在系统中引入了很高的分配延迟,而且还会由于过度回收而影响系统性能,直至特性自我失效。

The original lower boundary, the soft limit, is defined as a limit that is per default unset. As a result, the set of cgroups that
global reclaim prefers is opt-in, rather than opt-out. The costs for optimizing these mostly negative lookups are so high that the
implementation, despite its enormous size, does not even provide the basic desirable behavior. First off, the soft limit has no
hierarchical meaning. All configured groups are organized in a global rbtree and treated like equal peers, regardless where they are located
in the hierarchy. This makes subtree delegation impossible. Second, the soft limit reclaim pass is so aggressive that it not just
introduces high allocation latencies into the system, but also impacts system performance due to overreclaim, to the point where the feature
becomes self-defeating.

另一方面,memory.low边界是自上而下分配的预留。当一个cgroup及其所有祖先都处于其低边界之下时,它就可以重新获得回收保护,这使得子树的委托成为可能。第二,新的cgroup没有默认的预留,在通常情况下,大多数cgroup都有资格获得首选的回收许可。这使得新的低边界只需在通用回收代码中添加一小部分就可以有效地实现,而不需要带外数据结构和回收许可。由于通用回收代码考虑所有cgroup,除了在首选的第一次回收许可中运行得较低的cgroup,因此也消除了单个组的过度回收,从而获得更好的总体工作负载性能。

The memory.low boundary on the other hand is a top-down allocated reserve. A cgroup enjoys reclaim protection when it and all its
ancestors are below their low boundaries, which makes delegation of subtrees possible. Secondly, new cgroups have no reserve per default
and in the common case most cgroups are eligible for the preferred reclaim pass. This allows the new low boundary to be efficiently
implemented with just a minor addition to the generic reclaim code, without the need for out-of-band data structures and reclaim passes.
Because the generic reclaim code considers all cgroups except for the ones running low in the preferred first reclaim pass, overreclaim of
individual groups is eliminated as well, resulting in much better overall workload performance.

最初的高上限,硬限制,被定义为一个不能改变的严格界限,即使OOM killer 必须被唤起。但这通常违背了充分利用可用内存的目标。工作负载的内存消耗在运行时会有所不同,这需要用户的过度提交。但是,使用严格的上限来实现这一点需要对工作集大小进行相当准确的预测,或者增加工作集的松弛度。由于工作集大小估计很难并且容易出错,并且出错会导致唤起OOM killer,因此大多数用户倾向于错误地执行更宽松的限制,最终浪费宝贵的资源。

The original high boundary, the hard limit, is defined as a strict limit 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 the available memory. The memory consumption of workloads varies during
runtime, and that requires users to overcommit. But doing that with a strict upper limit requires either a fairly accurate prediction of the
working set size or adding slack to the limit. Since working set size estimation is hard and error prone, and getting it wrong results in
OOM kills, most users tend to err on the side of a looser limit and end up wasting precious resources.

另一方面,可以更保守地设置memory.high边界。当触达边界时,它通过强制它们直接回收来减少分配,但它从不调用OOM killer。因此,过度选择的高边界不会终止进程,而是会导致性能逐渐下降。用户可以监视这一点并进行更正,直到找到仍能提供可接受性能的最小内存占用。

The memory.high boundary on the other hand can be set much more conservatively. When hit, it throttles allocations by forcing them
into direct reclaim to work off the excess, but it never invokes the OOM killer. As a result, a high boundary that is chosen too
aggressively will not terminate the processes, but instead it will lead to gradual performance degradation. The user can monitor this
and make corrections until the minimal memory footprint that still gives acceptable performance is found.

在极端情况下,由于许多并发分配和组内回收进度的完全故障,可能会超出上限。但即使这样,从其他组或系统的其他部分的可用空闲时间中满足分配也比杀死该组要好。否则,memory.max将限制这种类型的溢出,并最终包含错误的甚至恶意的应用程序。

In extreme cases, with many concurrent allocations and a complete breakdown of reclaim progress within the group, the high boundary can
be exceeded. But even then it’s mostly better to satisfy the allocation from the slack available in other groups or the rest of the
system than killing the group. Otherwise, memory.max is there to limit this type of spillover and ultimately contain buggy or even
malicious applications.

将原始的memory.limit_in_bytes设置为低于当前使用情况会受到竞争条件的影响,在竞争条件下,并发分配可能会导致限制设置失败。另一方面,memory.max将首先设置限制以防止新的分配,然后回收和OOM kill,直到达到新的限制-或者终止写入引发memory.max的任务。

Setting the original memory.limit_in_bytes below the current usage was subject to a race condition, where concurrent charges could cause the
limit setting to fail. memory.max on the other hand will first set the limit to prevent new charges, and then reclaim and OOM kill until the
new limit is met - or the task writing to memory.max is killed.

memory+swap计算和限制的组合被对交换空间的实际控制所取代。

The combined memory+swap accounting and limiting is replaced by real control over swap space.

在最初的cgroup设计中,组合memory+swap功能的主要论点是,全局或父辈压力总是能够交换子组的所有匿名内存,而不管子组自己的(可能不受信任)配置如何。但是,不受信任的组可以通过其他方式破坏交换,例如在一个紧密的循环中引用其匿名内存,并且当过度委托不受信任的作业时,管理员不能假定完全可交换性。

The main argument for a combined memory+swap facility in the original cgroup design was that global or parental pressure would always be
able to swap all anonymous memory of a child group, regardless of the child’s own (possibly untrusted) configuration. However, untrusted
groups can sabotage swapping by other means - such as referencing its anonymous memory in a tight loop - and an admin can not assume full
swappability when overcommitting untrusted jobs.

另一方面,对于受信任的作业,组合计数器不是直观的用户空间接口,它违背了cgroup控制器应考虑并限制特定物理资源的想法。交换空间和系统中的其他资源一样,是一种资源,因此统一的层次结构允许将其单独分布。

For trusted jobs, on the other hand, a combined counter is not an intuitive userspace interface, and it flies in the face of the idea
that cgroup controllers should account and limit specific physical resources. Swap space is a resource like all others in the system,
and that’s why unified hierarchy allows distributing it separately.

Control Group v2版本相关推荐

  1. 关于Google Map API V2 版本的定位与导航

    近来,在关注安卓手机上的GoogleMap应用的开发,但是目前官方API版本网页版已经升级到V3版,而对于Android的支持也已经升级到V2版本,虽然Google说继续对V1版提供服务,但是不再提供 ...

  2. 每日一皮:虽然我们交付了V2版本,但用户仍然使用V1版本...

    虽然我们交付了V2版本 但用户仍然使用V1版本 这个需求谁提的? 我保证不打死你! 往期推荐 每日一皮:进来说说昨天你是怎么过的? 每日一皮:没有经过测试就运行,自信的表情不言而喻! 每日一皮:当你要 ...

  3. CTS(20)---CTS测试框架 -- V2版本

    CTS测试框架 -- V2版本 目录 概述 组织case  入口CompatibilityConsole ModuleRepo 组件CompatibilityTest 执行测试 总结 1 概述 在An ...

  4. MEME将于4月12日推出V2版本

    据官方消息,MEME 宣布将于 2021 年 4 月 12 日推出 V2 版本.MEME 版本 2 更新包括:1. 更精简的 NFT 挖矿体验:2. 改进了 UX 的用户体验:3. 平台的灵活性让艺术 ...

  5. Gnosis发起提案就是否推出Gnosis协议v2版本展开讨论

    1月8日,预测市场协议Gnosis官方宣布,社区已发起提议,激励社区成员讨论Gnosis是否应该推出Gnosis协议v2版本.根据提议,截至2021年1月5日,当前Gnosis协议状态为"第 ...

  6. 补充轻量级持久层V2版本的测试页面模板与实体类模板

    前天做完忘记备份,所以昨天没有发上来,文件下载请到<轻量级持久层框架V2版本代码与模板> 需要说明下,测试页面的代码模板不是直接生成就可以用的,需要在我注释掉代码的部分添加自己的测试数据, ...

  7. 微信小程序开发笔记 支付篇③——微信支付JSAPI下单和微信小程序调起支付(V2版本)

    文章目录 一.前文 二.流程图 三.SpringBoot接口实现 2.1 微信调起支付所需数据 2.2 下单接口 2.3 支付回调接口 三.微信小程序实现 3.1 JSAP统一下单 3.2 小程序调起 ...

  8. pyqt5实现一个简易音乐播放器(升级到v2版本)

    前言 假期最后一天,看到一篇文章使用pyqt实现了一个音乐播放器,刚好前段时间学完pyqt,来撸一个玩一玩,最终的效果如下: 后来又萌生想法,升级了一下UI: 本代码开源仓库:https://gith ...

  9. 基于原生PHP完成小程序支付对接踩坑(V2版本)

    这个是我,2021年写的代码了,最近参加比赛,涉及到支付,于是又拿来用,幸好代码健全,但是去微信平台看,已经出v3支付了,再次,这个教程以及代码部分,仅仅用于V2版本,请勿踩空! 文章目录 前言 一. ...

最新文章

  1. loader调用过程
  2. 改变TPageControl的活动标签颜色
  3. 《税的真相》—— 读后总结
  4. zap安装提示java_使用API调用进行ZAP身份验证
  5. 作者:宋杰(1980-),男,博士,东北大学软件学院副教授
  6. Spark Streaming的工作机制
  7. 量子计算机 计算混沌,深入了解量子混沌可能是量子计算机的关键
  8. python 数据结构 树 dev get items_python数据结构之树(二叉树的遍历)
  9. 不戴眼镜听不清?Google用视觉信号分离语音 | 附论文
  10. 从零开始--系统深入学习IOS(使用Swift---带链接)
  11. mysql 5.6一主两从_Centos7 下配置mysql5.6主从复制实例(一主两从)
  12. PHP cookie和session的分析
  13. 视觉SLAM笔记(51) 非线性系统和 EKF
  14. 智能语音翻译APP——腾讯翻译君
  15. SP324099: 无法完成操作--VS2015社区版无法登陆
  16. Maya用样条线制作面片头发
  17. NOD32杀毒软件升级ID
  18. Win10添加ssh公钥
  19. GitLab上传文件教程
  20. linux添加163邮箱,centos 7 mailx配置163邮箱发送邮件

热门文章

  1. 服务器w7系统,w7系统的云服务器
  2. java 蓝桥杯 天干地支
  3. 《物理学之美》读书摘记
  4. UltraISO制作的系统U盘详细教程
  5. win10pe命令打开计算机,hp电脑win10如何进pe_惠普电脑怎么进去u盘pe系统
  6. dell进入u盘启动模式_台式戴尔电脑U盘装系统按F几是u盘启动
  7. CSS文字大小单位px、em、pt
  8. 计算机保研夏令营准备流程建议
  9. 还在为写调查问卷发愁的你赶快来看看这个自动填写问卷(问卷星版)
  10. JAVA潜心修炼五天——第4天