cgroup-v2.txt 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582
  1. Control Group v2
  2. October, 2015 Tejun Heo <[email protected]>
  3. This is the authoritative documentation on the design, interface and
  4. conventions of cgroup v2. It describes all userland-visible aspects
  5. of cgroup including core and specific controller behaviors. All
  6. future changes must be reflected in this document. Documentation for
  7. v1 is available under Documentation/cgroup-v1/.
  8. CONTENTS
  9. 1. Introduction
  10. 1-1. Terminology
  11. 1-2. What is cgroup?
  12. 2. Basic Operations
  13. 2-1. Mounting
  14. 2-2. Organizing Processes
  15. 2-3. [Un]populated Notification
  16. 2-4. Controlling Controllers
  17. 2-4-1. Enabling and Disabling
  18. 2-4-2. Top-down Constraint
  19. 2-4-3. No Internal Process Constraint
  20. 2-5. Delegation
  21. 2-5-1. Model of Delegation
  22. 2-5-2. Delegation Containment
  23. 2-6. Guidelines
  24. 2-6-1. Organize Once and Control
  25. 2-6-2. Avoid Name Collisions
  26. 3. Resource Distribution Models
  27. 3-1. Weights
  28. 3-2. Limits
  29. 3-3. Protections
  30. 3-4. Allocations
  31. 4. Interface Files
  32. 4-1. Format
  33. 4-2. Conventions
  34. 4-3. Core Interface Files
  35. 5. Controllers
  36. 5-1. CPU
  37. 5-1-1. CPU Interface Files
  38. 5-2. Memory
  39. 5-2-1. Memory Interface Files
  40. 5-2-2. Usage Guidelines
  41. 5-2-3. Memory Ownership
  42. 5-3. IO
  43. 5-3-1. IO Interface Files
  44. 5-3-2. Writeback
  45. 6. Namespace
  46. 6-1. Basics
  47. 6-2. The Root and Views
  48. 6-3. Migration and setns(2)
  49. 6-4. Interaction with Other Namespaces
  50. P. Information on Kernel Programming
  51. P-1. Filesystem Support for Writeback
  52. D. Deprecated v1 Core Features
  53. R. Issues with v1 and Rationales for v2
  54. R-1. Multiple Hierarchies
  55. R-2. Thread Granularity
  56. R-3. Competition Between Inner Nodes and Threads
  57. R-4. Other Interface Issues
  58. R-5. Controller Issues and Remedies
  59. R-5-1. Memory
  60. 1. Introduction
  61. 1-1. Terminology
  62. "cgroup" stands for "control group" and is never capitalized. The
  63. singular form is used to designate the whole feature and also as a
  64. qualifier as in "cgroup controllers". When explicitly referring to
  65. multiple individual control groups, the plural form "cgroups" is used.
  66. 1-2. What is cgroup?
  67. cgroup is a mechanism to organize processes hierarchically and
  68. distribute system resources along the hierarchy in a controlled and
  69. configurable manner.
  70. cgroup is largely composed of two parts - the core and controllers.
  71. cgroup core is primarily responsible for hierarchically organizing
  72. processes. A cgroup controller is usually responsible for
  73. distributing a specific type of system resource along the hierarchy
  74. although there are utility controllers which serve purposes other than
  75. resource distribution.
  76. cgroups form a tree structure and every process in the system belongs
  77. to one and only one cgroup. All threads of a process belong to the
  78. same cgroup. On creation, all processes are put in the cgroup that
  79. the parent process belongs to at the time. A process can be migrated
  80. to another cgroup. Migration of a process doesn't affect already
  81. existing descendant processes.
  82. Following certain structural constraints, controllers may be enabled or
  83. disabled selectively on a cgroup. All controller behaviors are
  84. hierarchical - if a controller is enabled on a cgroup, it affects all
  85. processes which belong to the cgroups consisting the inclusive
  86. sub-hierarchy of the cgroup. When a controller is enabled on a nested
  87. cgroup, it always restricts the resource distribution further. The
  88. restrictions set closer to the root in the hierarchy can not be
  89. overridden from further away.
  90. 2. Basic Operations
  91. 2-1. Mounting
  92. Unlike v1, cgroup v2 has only single hierarchy. The cgroup v2
  93. hierarchy can be mounted with the following mount command.
  94. # mount -t cgroup2 none $MOUNT_POINT
  95. cgroup2 filesystem has the magic number 0x63677270 ("cgrp"). All
  96. controllers which support v2 and are not bound to a v1 hierarchy are
  97. automatically bound to the v2 hierarchy and show up at the root.
  98. Controllers which are not in active use in the v2 hierarchy can be
  99. bound to other hierarchies. This allows mixing v2 hierarchy with the
  100. legacy v1 multiple hierarchies in a fully backward compatible way.
  101. A controller can be moved across hierarchies only after the controller
  102. is no longer referenced in its current hierarchy. Because per-cgroup
  103. controller states are destroyed asynchronously and controllers may
  104. have lingering references, a controller may not show up immediately on
  105. the v2 hierarchy after the final umount of the previous hierarchy.
  106. Similarly, a controller should be fully disabled to be moved out of
  107. the unified hierarchy and it may take some time for the disabled
  108. controller to become available for other hierarchies; furthermore, due
  109. to inter-controller dependencies, other controllers may need to be
  110. disabled too.
  111. While useful for development and manual configurations, moving
  112. controllers dynamically between the v2 and other hierarchies is
  113. strongly discouraged for production use. It is recommended to decide
  114. the hierarchies and controller associations before starting using the
  115. controllers after system boot.
  116. During transition to v2, system management software might still
  117. automount the v1 cgroup filesystem and so hijack all controllers
  118. during boot, before manual intervention is possible. To make testing
  119. and experimenting easier, the kernel parameter cgroup_no_v1= allows
  120. disabling controllers in v1 and make them always available in v2.
  121. 2-2. Organizing Processes
  122. Initially, only the root cgroup exists to which all processes belong.
  123. A child cgroup can be created by creating a sub-directory.
  124. # mkdir $CGROUP_NAME
  125. A given cgroup may have multiple child cgroups forming a tree
  126. structure. Each cgroup has a read-writable interface file
  127. "cgroup.procs". When read, it lists the PIDs of all processes which
  128. belong to the cgroup one-per-line. The PIDs are not ordered and the
  129. same PID may show up more than once if the process got moved to
  130. another cgroup and then back or the PID got recycled while reading.
  131. A process can be migrated into a cgroup by writing its PID to the
  132. target cgroup's "cgroup.procs" file. Only one process can be migrated
  133. on a single write(2) call. If a process is composed of multiple
  134. threads, writing the PID of any thread migrates all threads of the
  135. process.
  136. When a process forks a child process, the new process is born into the
  137. cgroup that the forking process belongs to at the time of the
  138. operation. After exit, a process stays associated with the cgroup
  139. that it belonged to at the time of exit until it's reaped; however, a
  140. zombie process does not appear in "cgroup.procs" and thus can't be
  141. moved to another cgroup.
  142. A cgroup which doesn't have any children or live processes can be
  143. destroyed by removing the directory. Note that a cgroup which doesn't
  144. have any children and is associated only with zombie processes is
  145. considered empty and can be removed.
  146. # rmdir $CGROUP_NAME
  147. "/proc/$PID/cgroup" lists a process's cgroup membership. If legacy
  148. cgroup is in use in the system, this file may contain multiple lines,
  149. one for each hierarchy. The entry for cgroup v2 is always in the
  150. format "0::$PATH".
  151. # cat /proc/842/cgroup
  152. ...
  153. 0::/test-cgroup/test-cgroup-nested
  154. If the process becomes a zombie and the cgroup it was associated with
  155. is removed subsequently, " (deleted)" is appended to the path.
  156. # cat /proc/842/cgroup
  157. ...
  158. 0::/test-cgroup/test-cgroup-nested (deleted)
  159. 2-3. [Un]populated Notification
  160. Each non-root cgroup has a "cgroup.events" file which contains
  161. "populated" field indicating whether the cgroup's sub-hierarchy has
  162. live processes in it. Its value is 0 if there is no live process in
  163. the cgroup and its descendants; otherwise, 1. poll and [id]notify
  164. events are triggered when the value changes. This can be used, for
  165. example, to start a clean-up operation after all processes of a given
  166. sub-hierarchy have exited. The populated state updates and
  167. notifications are recursive. Consider the following sub-hierarchy
  168. where the numbers in the parentheses represent the numbers of processes
  169. in each cgroup.
  170. A(4) - B(0) - C(1)
  171. \ D(0)
  172. A, B and C's "populated" fields would be 1 while D's 0. After the one
  173. process in C exits, B and C's "populated" fields would flip to "0" and
  174. file modified events will be generated on the "cgroup.events" files of
  175. both cgroups.
  176. 2-4. Controlling Controllers
  177. 2-4-1. Enabling and Disabling
  178. Each cgroup has a "cgroup.controllers" file which lists all
  179. controllers available for the cgroup to enable.
  180. # cat cgroup.controllers
  181. cpu io memory
  182. No controller is enabled by default. Controllers can be enabled and
  183. disabled by writing to the "cgroup.subtree_control" file.
  184. # echo "+cpu +memory -io" > cgroup.subtree_control
  185. Only controllers which are listed in "cgroup.controllers" can be
  186. enabled. When multiple operations are specified as above, either they
  187. all succeed or fail. If multiple operations on the same controller
  188. are specified, the last one is effective.
  189. Enabling a controller in a cgroup indicates that the distribution of
  190. the target resource across its immediate children will be controlled.
  191. Consider the following sub-hierarchy. The enabled controllers are
  192. listed in parentheses.
  193. A(cpu,memory) - B(memory) - C()
  194. \ D()
  195. As A has "cpu" and "memory" enabled, A will control the distribution
  196. of CPU cycles and memory to its children, in this case, B. As B has
  197. "memory" enabled but not "CPU", C and D will compete freely on CPU
  198. cycles but their division of memory available to B will be controlled.
  199. As a controller regulates the distribution of the target resource to
  200. the cgroup's children, enabling it creates the controller's interface
  201. files in the child cgroups. In the above example, enabling "cpu" on B
  202. would create the "cpu." prefixed controller interface files in C and
  203. D. Likewise, disabling "memory" from B would remove the "memory."
  204. prefixed controller interface files from C and D. This means that the
  205. controller interface files - anything which doesn't start with
  206. "cgroup." are owned by the parent rather than the cgroup itself.
  207. 2-4-2. Top-down Constraint
  208. Resources are distributed top-down and a cgroup can further distribute
  209. a resource only if the resource has been distributed to it from the
  210. parent. This means that all non-root "cgroup.subtree_control" files
  211. can only contain controllers which are enabled in the parent's
  212. "cgroup.subtree_control" file. A controller can be enabled only if
  213. the parent has the controller enabled and a controller can't be
  214. disabled if one or more children have it enabled.
  215. 2-4-3. No Internal Process Constraint
  216. Non-root cgroups can only distribute resources to their children when
  217. they don't have any processes of their own. In other words, only
  218. cgroups which don't contain any processes can have controllers enabled
  219. in their "cgroup.subtree_control" files.
  220. This guarantees that, when a controller is looking at the part of the
  221. hierarchy which has it enabled, processes are always only on the
  222. leaves. This rules out situations where child cgroups compete against
  223. internal processes of the parent.
  224. The root cgroup is exempt from this restriction. Root contains
  225. processes and anonymous resource consumption which can't be associated
  226. with any other cgroups and requires special treatment from most
  227. controllers. How resource consumption in the root cgroup is governed
  228. is up to each controller.
  229. Note that the restriction doesn't get in the way if there is no
  230. enabled controller in the cgroup's "cgroup.subtree_control". This is
  231. important as otherwise it wouldn't be possible to create children of a
  232. populated cgroup. To control resource distribution of a cgroup, the
  233. cgroup must create children and transfer all its processes to the
  234. children before enabling controllers in its "cgroup.subtree_control"
  235. file.
  236. 2-5. Delegation
  237. 2-5-1. Model of Delegation
  238. A cgroup can be delegated to a less privileged user by granting write
  239. access of the directory and its "cgroup.procs" file to the user. Note
  240. that resource control interface files in a given directory control the
  241. distribution of the parent's resources and thus must not be delegated
  242. along with the directory.
  243. Once delegated, the user can build sub-hierarchy under the directory,
  244. organize processes as it sees fit and further distribute the resources
  245. it received from the parent. The limits and other settings of all
  246. resource controllers are hierarchical and regardless of what happens
  247. in the delegated sub-hierarchy, nothing can escape the resource
  248. restrictions imposed by the parent.
  249. Currently, cgroup doesn't impose any restrictions on the number of
  250. cgroups in or nesting depth of a delegated sub-hierarchy; however,
  251. this may be limited explicitly in the future.
  252. 2-5-2. Delegation Containment
  253. A delegated sub-hierarchy is contained in the sense that processes
  254. can't be moved into or out of the sub-hierarchy by the delegatee. For
  255. a process with a non-root euid to migrate a target process into a
  256. cgroup by writing its PID to the "cgroup.procs" file, the following
  257. conditions must be met.
  258. - The writer's euid must match either uid or suid of the target process.
  259. - The writer must have write access to the "cgroup.procs" file.
  260. - The writer must have write access to the "cgroup.procs" file of the
  261. common ancestor of the source and destination cgroups.
  262. The above three constraints ensure that while a delegatee may migrate
  263. processes around freely in the delegated sub-hierarchy it can't pull
  264. in from or push out to outside the sub-hierarchy.
  265. For an example, let's assume cgroups C0 and C1 have been delegated to
  266. user U0 who created C00, C01 under C0 and C10 under C1 as follows and
  267. all processes under C0 and C1 belong to U0.
  268. ~~~~~~~~~~~~~ - C0 - C00
  269. ~ cgroup ~ \ C01
  270. ~ hierarchy ~
  271. ~~~~~~~~~~~~~ - C1 - C10
  272. Let's also say U0 wants to write the PID of a process which is
  273. currently in C10 into "C00/cgroup.procs". U0 has write access to the
  274. file and uid match on the process; however, the common ancestor of the
  275. source cgroup C10 and the destination cgroup C00 is above the points
  276. of delegation and U0 would not have write access to its "cgroup.procs"
  277. files and thus the write will be denied with -EACCES.
  278. 2-6. Guidelines
  279. 2-6-1. Organize Once and Control
  280. Migrating a process across cgroups is a relatively expensive operation
  281. and stateful resources such as memory are not moved together with the
  282. process. This is an explicit design decision as there often exist
  283. inherent trade-offs between migration and various hot paths in terms
  284. of synchronization cost.
  285. As such, migrating processes across cgroups frequently as a means to
  286. apply different resource restrictions is discouraged. A workload
  287. should be assigned to a cgroup according to the system's logical and
  288. resource structure once on start-up. Dynamic adjustments to resource
  289. distribution can be made by changing controller configuration through
  290. the interface files.
  291. 2-6-2. Avoid Name Collisions
  292. Interface files for a cgroup and its children cgroups occupy the same
  293. directory and it is possible to create children cgroups which collide
  294. with interface files.
  295. All cgroup core interface files are prefixed with "cgroup." and each
  296. controller's interface files are prefixed with the controller name and
  297. a dot. A controller's name is composed of lower case alphabets and
  298. '_'s but never begins with an '_' so it can be used as the prefix
  299. character for collision avoidance. Also, interface file names won't
  300. start or end with terms which are often used in categorizing workloads
  301. such as job, service, slice, unit or workload.
  302. cgroup doesn't do anything to prevent name collisions and it's the
  303. user's responsibility to avoid them.
  304. 3. Resource Distribution Models
  305. cgroup controllers implement several resource distribution schemes
  306. depending on the resource type and expected use cases. This section
  307. describes major schemes in use along with their expected behaviors.
  308. 3-1. Weights
  309. A parent's resource is distributed by adding up the weights of all
  310. active children and giving each the fraction matching the ratio of its
  311. weight against the sum. As only children which can make use of the
  312. resource at the moment participate in the distribution, this is
  313. work-conserving. Due to the dynamic nature, this model is usually
  314. used for stateless resources.
  315. All weights are in the range [1, 10000] with the default at 100. This
  316. allows symmetric multiplicative biases in both directions at fine
  317. enough granularity while staying in the intuitive range.
  318. As long as the weight is in range, all configuration combinations are
  319. valid and there is no reason to reject configuration changes or
  320. process migrations.
  321. "cpu.weight" proportionally distributes CPU cycles to active children
  322. and is an example of this type.
  323. 3-2. Limits
  324. A child can only consume upto the configured amount of the resource.
  325. Limits can be over-committed - the sum of the limits of children can
  326. exceed the amount of resource available to the parent.
  327. Limits are in the range [0, max] and defaults to "max", which is noop.
  328. As limits can be over-committed, all configuration combinations are
  329. valid and there is no reason to reject configuration changes or
  330. process migrations.
  331. "io.max" limits the maximum BPS and/or IOPS that a cgroup can consume
  332. on an IO device and is an example of this type.
  333. 3-3. Protections
  334. A cgroup is protected to be allocated upto the configured amount of
  335. the resource if the usages of all its ancestors are under their
  336. protected levels. Protections can be hard guarantees or best effort
  337. soft boundaries. Protections can also be over-committed in which case
  338. only upto the amount available to the parent is protected among
  339. children.
  340. Protections are in the range [0, max] and defaults to 0, which is
  341. noop.
  342. As protections can be over-committed, all configuration combinations
  343. are valid and there is no reason to reject configuration changes or
  344. process migrations.
  345. "memory.low" implements best-effort memory protection and is an
  346. example of this type.
  347. 3-4. Allocations
  348. A cgroup is exclusively allocated a certain amount of a finite
  349. resource. Allocations can't be over-committed - the sum of the
  350. allocations of children can not exceed the amount of resource
  351. available to the parent.
  352. Allocations are in the range [0, max] and defaults to 0, which is no
  353. resource.
  354. As allocations can't be over-committed, some configuration
  355. combinations are invalid and should be rejected. Also, if the
  356. resource is mandatory for execution of processes, process migrations
  357. may be rejected.
  358. "cpu.rt.max" hard-allocates realtime slices and is an example of this
  359. type.
  360. 4. Interface Files
  361. 4-1. Format
  362. All interface files should be in one of the following formats whenever
  363. possible.
  364. New-line separated values
  365. (when only one value can be written at once)
  366. VAL0\n
  367. VAL1\n
  368. ...
  369. Space separated values
  370. (when read-only or multiple values can be written at once)
  371. VAL0 VAL1 ...\n
  372. Flat keyed
  373. KEY0 VAL0\n
  374. KEY1 VAL1\n
  375. ...
  376. Nested keyed
  377. KEY0 SUB_KEY0=VAL00 SUB_KEY1=VAL01...
  378. KEY1 SUB_KEY0=VAL10 SUB_KEY1=VAL11...
  379. ...
  380. For a writable file, the format for writing should generally match
  381. reading; however, controllers may allow omitting later fields or
  382. implement restricted shortcuts for most common use cases.
  383. For both flat and nested keyed files, only the values for a single key
  384. can be written at a time. For nested keyed files, the sub key pairs
  385. may be specified in any order and not all pairs have to be specified.
  386. 4-2. Conventions
  387. - Settings for a single feature should be contained in a single file.
  388. - The root cgroup should be exempt from resource control and thus
  389. shouldn't have resource control interface files. Also,
  390. informational files on the root cgroup which end up showing global
  391. information available elsewhere shouldn't exist.
  392. - If a controller implements weight based resource distribution, its
  393. interface file should be named "weight" and have the range [1,
  394. 10000] with 100 as the default. The values are chosen to allow
  395. enough and symmetric bias in both directions while keeping it
  396. intuitive (the default is 100%).
  397. - If a controller implements an absolute resource guarantee and/or
  398. limit, the interface files should be named "min" and "max"
  399. respectively. If a controller implements best effort resource
  400. guarantee and/or limit, the interface files should be named "low"
  401. and "high" respectively.
  402. In the above four control files, the special token "max" should be
  403. used to represent upward infinity for both reading and writing.
  404. - If a setting has a configurable default value and keyed specific
  405. overrides, the default entry should be keyed with "default" and
  406. appear as the first entry in the file.
  407. The default value can be updated by writing either "default $VAL" or
  408. "$VAL".
  409. When writing to update a specific override, "default" can be used as
  410. the value to indicate removal of the override. Override entries
  411. with "default" as the value must not appear when read.
  412. For example, a setting which is keyed by major:minor device numbers
  413. with integer values may look like the following.
  414. # cat cgroup-example-interface-file
  415. default 150
  416. 8:0 300
  417. The default value can be updated by
  418. # echo 125 > cgroup-example-interface-file
  419. or
  420. # echo "default 125" > cgroup-example-interface-file
  421. An override can be set by
  422. # echo "8:16 170" > cgroup-example-interface-file
  423. and cleared by
  424. # echo "8:0 default" > cgroup-example-interface-file
  425. # cat cgroup-example-interface-file
  426. default 125
  427. 8:16 170
  428. - For events which are not very high frequency, an interface file
  429. "events" should be created which lists event key value pairs.
  430. Whenever a notifiable event happens, file modified event should be
  431. generated on the file.
  432. 4-3. Core Interface Files
  433. All cgroup core files are prefixed with "cgroup."
  434. cgroup.procs
  435. A read-write new-line separated values file which exists on
  436. all cgroups.
  437. When read, it lists the PIDs of all processes which belong to
  438. the cgroup one-per-line. The PIDs are not ordered and the
  439. same PID may show up more than once if the process got moved
  440. to another cgroup and then back or the PID got recycled while
  441. reading.
  442. A PID can be written to migrate the process associated with
  443. the PID to the cgroup. The writer should match all of the
  444. following conditions.
  445. - Its euid is either root or must match either uid or suid of
  446. the target process.
  447. - It must have write access to the "cgroup.procs" file.
  448. - It must have write access to the "cgroup.procs" file of the
  449. common ancestor of the source and destination cgroups.
  450. When delegating a sub-hierarchy, write access to this file
  451. should be granted along with the containing directory.
  452. cgroup.controllers
  453. A read-only space separated values file which exists on all
  454. cgroups.
  455. It shows space separated list of all controllers available to
  456. the cgroup. The controllers are not ordered.
  457. cgroup.subtree_control
  458. A read-write space separated values file which exists on all
  459. cgroups. Starts out empty.
  460. When read, it shows space separated list of the controllers
  461. which are enabled to control resource distribution from the
  462. cgroup to its children.
  463. Space separated list of controllers prefixed with '+' or '-'
  464. can be written to enable or disable controllers. A controller
  465. name prefixed with '+' enables the controller and '-'
  466. disables. If a controller appears more than once on the list,
  467. the last one is effective. When multiple enable and disable
  468. operations are specified, either all succeed or all fail.
  469. cgroup.events
  470. A read-only flat-keyed file which exists on non-root cgroups.
  471. The following entries are defined. Unless specified
  472. otherwise, a value change in this file generates a file
  473. modified event.
  474. populated
  475. 1 if the cgroup or its descendants contains any live
  476. processes; otherwise, 0.
  477. 5. Controllers
  478. 5-1. CPU
  479. [NOTE: The interface for the cpu controller hasn't been merged yet]
  480. The "cpu" controllers regulates distribution of CPU cycles. This
  481. controller implements weight and absolute bandwidth limit models for
  482. normal scheduling policy and absolute bandwidth allocation model for
  483. realtime scheduling policy.
  484. 5-1-1. CPU Interface Files
  485. All time durations are in microseconds.
  486. cpu.stat
  487. A read-only flat-keyed file which exists on non-root cgroups.
  488. It reports the following six stats.
  489. usage_usec
  490. user_usec
  491. system_usec
  492. nr_periods
  493. nr_throttled
  494. throttled_usec
  495. cpu.weight
  496. A read-write single value file which exists on non-root
  497. cgroups. The default is "100".
  498. The weight in the range [1, 10000].
  499. cpu.max
  500. A read-write two value file which exists on non-root cgroups.
  501. The default is "max 100000".
  502. The maximum bandwidth limit. It's in the following format.
  503. $MAX $PERIOD
  504. which indicates that the group may consume upto $MAX in each
  505. $PERIOD duration. "max" for $MAX indicates no limit. If only
  506. one number is written, $MAX is updated.
  507. cpu.rt.max
  508. [NOTE: The semantics of this file is still under discussion and the
  509. interface hasn't been merged yet]
  510. A read-write two value file which exists on all cgroups.
  511. The default is "0 100000".
  512. The maximum realtime runtime allocation. Over-committing
  513. configurations are disallowed and process migrations are
  514. rejected if not enough bandwidth is available. It's in the
  515. following format.
  516. $MAX $PERIOD
  517. which indicates that the group may consume upto $MAX in each
  518. $PERIOD duration. If only one number is written, $MAX is
  519. updated.
  520. cpu.pressure
  521. A read-only nested-key file which exists on non-root cgroups.
  522. Shows pressure stall information for CPU. See
  523. Documentation/accounting/psi.txt for details.
  524. 5-2. Memory
  525. The "memory" controller regulates distribution of memory. Memory is
  526. stateful and implements both limit and protection models. Due to the
  527. intertwining between memory usage and reclaim pressure and the
  528. stateful nature of memory, the distribution model is relatively
  529. complex.
  530. While not completely water-tight, all major memory usages by a given
  531. cgroup are tracked so that the total memory consumption can be
  532. accounted and controlled to a reasonable extent. Currently, the
  533. following types of memory usages are tracked.
  534. - Userland memory - page cache and anonymous memory.
  535. - Kernel data structures such as dentries and inodes.
  536. - TCP socket buffers.
  537. The above list may expand in the future for better coverage.
  538. 5-2-1. Memory Interface Files
  539. All memory amounts are in bytes. If a value which is not aligned to
  540. PAGE_SIZE is written, the value may be rounded up to the closest
  541. PAGE_SIZE multiple when read back.
  542. memory.current
  543. A read-only single value file which exists on non-root
  544. cgroups.
  545. The total amount of memory currently being used by the cgroup
  546. and its descendants.
  547. memory.low
  548. A read-write single value file which exists on non-root
  549. cgroups. The default is "0".
  550. Best-effort memory protection. If the memory usages of a
  551. cgroup and all its ancestors are below their low boundaries,
  552. the cgroup's memory won't be reclaimed unless memory can be
  553. reclaimed from unprotected cgroups.
  554. Putting more memory than generally available under this
  555. protection is discouraged.
  556. memory.high
  557. A read-write single value file which exists on non-root
  558. cgroups. The default is "max".
  559. Memory usage throttle limit. This is the main mechanism to
  560. control memory usage of a cgroup. If a cgroup's usage goes
  561. over the high boundary, the processes of the cgroup are
  562. throttled and put under heavy reclaim pressure.
  563. Going over the high limit never invokes the OOM killer and
  564. under extreme conditions the limit may be breached.
  565. memory.max
  566. A read-write single value file which exists on non-root
  567. cgroups. The default is "max".
  568. Memory usage hard limit. This is the final protection
  569. mechanism. If a cgroup's memory usage reaches this limit and
  570. can't be reduced, the OOM killer is invoked in the cgroup.
  571. Under certain circumstances, the usage may go over the limit
  572. temporarily.
  573. This is the ultimate protection mechanism. As long as the
  574. high limit is used and monitored properly, this limit's
  575. utility is limited to providing the final safety net.
  576. memory.events
  577. A read-only flat-keyed file which exists on non-root cgroups.
  578. The following entries are defined. Unless specified
  579. otherwise, a value change in this file generates a file
  580. modified event.
  581. low
  582. The number of times the cgroup is reclaimed due to
  583. high memory pressure even though its usage is under
  584. the low boundary. This usually indicates that the low
  585. boundary is over-committed.
  586. high
  587. The number of times processes of the cgroup are
  588. throttled and routed to perform direct memory reclaim
  589. because the high memory boundary was exceeded. For a
  590. cgroup whose memory usage is capped by the high limit
  591. rather than global memory pressure, this event's
  592. occurrences are expected.
  593. max
  594. The number of times the cgroup's memory usage was
  595. about to go over the max boundary. If direct reclaim
  596. fails to bring it down, the OOM killer is invoked.
  597. oom
  598. The number of times the OOM killer has been invoked in
  599. the cgroup. This may not exactly match the number of
  600. processes killed but should generally be close.
  601. memory.stat
  602. A read-only flat-keyed file which exists on non-root cgroups.
  603. This breaks down the cgroup's memory footprint into different
  604. types of memory, type-specific details, and other information
  605. on the state and past events of the memory management system.
  606. All memory amounts are in bytes.
  607. The entries are ordered to be human readable, and new entries
  608. can show up in the middle. Don't rely on items remaining in a
  609. fixed position; use the keys to look up specific values!
  610. anon
  611. Amount of memory used in anonymous mappings such as
  612. brk(), sbrk(), and mmap(MAP_ANONYMOUS)
  613. file
  614. Amount of memory used to cache filesystem data,
  615. including tmpfs and shared memory.
  616. kernel_stack
  617. Amount of memory allocated to kernel stacks.
  618. slab
  619. Amount of memory used for storing in-kernel data
  620. structures.
  621. sock
  622. Amount of memory used in network transmission buffers
  623. file_mapped
  624. Amount of cached filesystem data mapped with mmap()
  625. file_dirty
  626. Amount of cached filesystem data that was modified but
  627. not yet written back to disk
  628. file_writeback
  629. Amount of cached filesystem data that was modified and
  630. is currently being written back to disk
  631. inactive_anon
  632. active_anon
  633. inactive_file
  634. active_file
  635. unevictable
  636. Amount of memory, swap-backed and filesystem-backed,
  637. on the internal memory management lists used by the
  638. page reclaim algorithm
  639. slab_reclaimable
  640. Part of "slab" that might be reclaimed, such as
  641. dentries and inodes.
  642. slab_unreclaimable
  643. Part of "slab" that cannot be reclaimed on memory
  644. pressure.
  645. pgfault
  646. Total number of page faults incurred
  647. pgmajfault
  648. Number of major page faults incurred
  649. memory.swap.current
  650. A read-only single value file which exists on non-root
  651. cgroups.
  652. The total amount of swap currently being used by the cgroup
  653. and its descendants.
  654. memory.swap.max
  655. A read-write single value file which exists on non-root
  656. cgroups. The default is "max".
  657. Swap usage hard limit. If a cgroup's swap usage reaches this
  658. limit, anonymous meomry of the cgroup will not be swapped out.
  659. memory.pressure
  660. A read-only nested-key file which exists on non-root cgroups.
  661. Shows pressure stall information for memory. See
  662. Documentation/accounting/psi.txt for details.
  663. 5-2-2. Usage Guidelines
  664. "memory.high" is the main mechanism to control memory usage.
  665. Over-committing on high limit (sum of high limits > available memory)
  666. and letting global memory pressure to distribute memory according to
  667. usage is a viable strategy.
  668. Because breach of the high limit doesn't trigger the OOM killer but
  669. throttles the offending cgroup, a management agent has ample
  670. opportunities to monitor and take appropriate actions such as granting
  671. more memory or terminating the workload.
  672. Determining whether a cgroup has enough memory is not trivial as
  673. memory usage doesn't indicate whether the workload can benefit from
  674. more memory. For example, a workload which writes data received from
  675. network to a file can use all available memory but can also operate as
  676. performant with a small amount of memory. A measure of memory
  677. pressure - how much the workload is being impacted due to lack of
  678. memory - is necessary to determine whether a workload needs more
  679. memory; unfortunately, memory pressure monitoring mechanism isn't
  680. implemented yet.
  681. 5-2-3. Memory Ownership
  682. A memory area is charged to the cgroup which instantiated it and stays
  683. charged to the cgroup until the area is released. Migrating a process
  684. to a different cgroup doesn't move the memory usages that it
  685. instantiated while in the previous cgroup to the new cgroup.
  686. A memory area may be used by processes belonging to different cgroups.
  687. To which cgroup the area will be charged is in-deterministic; however,
  688. over time, the memory area is likely to end up in a cgroup which has
  689. enough memory allowance to avoid high reclaim pressure.
  690. If a cgroup sweeps a considerable amount of memory which is expected
  691. to be accessed repeatedly by other cgroups, it may make sense to use
  692. POSIX_FADV_DONTNEED to relinquish the ownership of memory areas
  693. belonging to the affected files to ensure correct memory ownership.
  694. 5-3. IO
  695. The "io" controller regulates the distribution of IO resources. This
  696. controller implements both weight based and absolute bandwidth or IOPS
  697. limit distribution; however, weight based distribution is available
  698. only if cfq-iosched is in use and neither scheme is available for
  699. blk-mq devices.
  700. 5-3-1. IO Interface Files
  701. io.stat
  702. A read-only nested-keyed file which exists on non-root
  703. cgroups.
  704. Lines are keyed by $MAJ:$MIN device numbers and not ordered.
  705. The following nested keys are defined.
  706. rbytes Bytes read
  707. wbytes Bytes written
  708. rios Number of read IOs
  709. wios Number of write IOs
  710. An example read output follows.
  711. 8:16 rbytes=1459200 wbytes=314773504 rios=192 wios=353
  712. 8:0 rbytes=90430464 wbytes=299008000 rios=8950 wios=1252
  713. io.weight
  714. A read-write flat-keyed file which exists on non-root cgroups.
  715. The default is "default 100".
  716. The first line is the default weight applied to devices
  717. without specific override. The rest are overrides keyed by
  718. $MAJ:$MIN device numbers and not ordered. The weights are in
  719. the range [1, 10000] and specifies the relative amount IO time
  720. the cgroup can use in relation to its siblings.
  721. The default weight can be updated by writing either "default
  722. $WEIGHT" or simply "$WEIGHT". Overrides can be set by writing
  723. "$MAJ:$MIN $WEIGHT" and unset by writing "$MAJ:$MIN default".
  724. An example read output follows.
  725. default 100
  726. 8:16 200
  727. 8:0 50
  728. io.max
  729. A read-write nested-keyed file which exists on non-root
  730. cgroups.
  731. BPS and IOPS based IO limit. Lines are keyed by $MAJ:$MIN
  732. device numbers and not ordered. The following nested keys are
  733. defined.
  734. rbps Max read bytes per second
  735. wbps Max write bytes per second
  736. riops Max read IO operations per second
  737. wiops Max write IO operations per second
  738. When writing, any number of nested key-value pairs can be
  739. specified in any order. "max" can be specified as the value
  740. to remove a specific limit. If the same key is specified
  741. multiple times, the outcome is undefined.
  742. BPS and IOPS are measured in each IO direction and IOs are
  743. delayed if limit is reached. Temporary bursts are allowed.
  744. Setting read limit at 2M BPS and write at 120 IOPS for 8:16.
  745. echo "8:16 rbps=2097152 wiops=120" > io.max
  746. Reading returns the following.
  747. 8:16 rbps=2097152 wbps=max riops=max wiops=120
  748. Write IOPS limit can be removed by writing the following.
  749. echo "8:16 wiops=max" > io.max
  750. Reading now returns the following.
  751. 8:16 rbps=2097152 wbps=max riops=max wiops=max
  752. io.pressure
  753. A read-only nested-key file which exists on non-root cgroups.
  754. Shows pressure stall information for IO. See
  755. Documentation/accounting/psi.txt for details.
  756. 5-3-2. Writeback
  757. Page cache is dirtied through buffered writes and shared mmaps and
  758. written asynchronously to the backing filesystem by the writeback
  759. mechanism. Writeback sits between the memory and IO domains and
  760. regulates the proportion of dirty memory by balancing dirtying and
  761. write IOs.
  762. The io controller, in conjunction with the memory controller,
  763. implements control of page cache writeback IOs. The memory controller
  764. defines the memory domain that dirty memory ratio is calculated and
  765. maintained for and the io controller defines the io domain which
  766. writes out dirty pages for the memory domain. Both system-wide and
  767. per-cgroup dirty memory states are examined and the more restrictive
  768. of the two is enforced.
  769. cgroup writeback requires explicit support from the underlying
  770. filesystem. Currently, cgroup writeback is implemented on ext2, ext4
  771. and btrfs. On other filesystems, all writeback IOs are attributed to
  772. the root cgroup.
  773. There are inherent differences in memory and writeback management
  774. which affects how cgroup ownership is tracked. Memory is tracked per
  775. page while writeback per inode. For the purpose of writeback, an
  776. inode is assigned to a cgroup and all IO requests to write dirty pages
  777. from the inode are attributed to that cgroup.
  778. As cgroup ownership for memory is tracked per page, there can be pages
  779. which are associated with different cgroups than the one the inode is
  780. associated with. These are called foreign pages. The writeback
  781. constantly keeps track of foreign pages and, if a particular foreign
  782. cgroup becomes the majority over a certain period of time, switches
  783. the ownership of the inode to that cgroup.
  784. While this model is enough for most use cases where a given inode is
  785. mostly dirtied by a single cgroup even when the main writing cgroup
  786. changes over time, use cases where multiple cgroups write to a single
  787. inode simultaneously are not supported well. In such circumstances, a
  788. significant portion of IOs are likely to be attributed incorrectly.
  789. As memory controller assigns page ownership on the first use and
  790. doesn't update it until the page is released, even if writeback
  791. strictly follows page ownership, multiple cgroups dirtying overlapping
  792. areas wouldn't work as expected. It's recommended to avoid such usage
  793. patterns.
  794. The sysctl knobs which affect writeback behavior are applied to cgroup
  795. writeback as follows.
  796. vm.dirty_background_ratio
  797. vm.dirty_ratio
  798. These ratios apply the same to cgroup writeback with the
  799. amount of available memory capped by limits imposed by the
  800. memory controller and system-wide clean memory.
  801. vm.dirty_background_bytes
  802. vm.dirty_bytes
  803. For cgroup writeback, this is calculated into ratio against
  804. total available memory and applied the same way as
  805. vm.dirty[_background]_ratio.
  806. 6. Namespace
  807. 6-1. Basics
  808. cgroup namespace provides a mechanism to virtualize the view of the
  809. "/proc/$PID/cgroup" file and cgroup mounts. The CLONE_NEWCGROUP clone
  810. flag can be used with clone(2) and unshare(2) to create a new cgroup
  811. namespace. The process running inside the cgroup namespace will have
  812. its "/proc/$PID/cgroup" output restricted to cgroupns root. The
  813. cgroupns root is the cgroup of the process at the time of creation of
  814. the cgroup namespace.
  815. Without cgroup namespace, the "/proc/$PID/cgroup" file shows the
  816. complete path of the cgroup of a process. In a container setup where
  817. a set of cgroups and namespaces are intended to isolate processes the
  818. "/proc/$PID/cgroup" file may leak potential system level information
  819. to the isolated processes. For Example:
  820. # cat /proc/self/cgroup
  821. 0::/batchjobs/container_id1
  822. The path '/batchjobs/container_id1' can be considered as system-data
  823. and undesirable to expose to the isolated processes. cgroup namespace
  824. can be used to restrict visibility of this path. For example, before
  825. creating a cgroup namespace, one would see:
  826. # ls -l /proc/self/ns/cgroup
  827. lrwxrwxrwx 1 root root 0 2014-07-15 10:37 /proc/self/ns/cgroup -> cgroup:[4026531835]
  828. # cat /proc/self/cgroup
  829. 0::/batchjobs/container_id1
  830. After unsharing a new namespace, the view changes.
  831. # ls -l /proc/self/ns/cgroup
  832. lrwxrwxrwx 1 root root 0 2014-07-15 10:35 /proc/self/ns/cgroup -> cgroup:[4026532183]
  833. # cat /proc/self/cgroup
  834. 0::/
  835. When some thread from a multi-threaded process unshares its cgroup
  836. namespace, the new cgroupns gets applied to the entire process (all
  837. the threads). This is natural for the v2 hierarchy; however, for the
  838. legacy hierarchies, this may be unexpected.
  839. A cgroup namespace is alive as long as there are processes inside or
  840. mounts pinning it. When the last usage goes away, the cgroup
  841. namespace is destroyed. The cgroupns root and the actual cgroups
  842. remain.
  843. 6-2. The Root and Views
  844. The 'cgroupns root' for a cgroup namespace is the cgroup in which the
  845. process calling unshare(2) is running. For example, if a process in
  846. /batchjobs/container_id1 cgroup calls unshare, cgroup
  847. /batchjobs/container_id1 becomes the cgroupns root. For the
  848. init_cgroup_ns, this is the real root ('/') cgroup.
  849. The cgroupns root cgroup does not change even if the namespace creator
  850. process later moves to a different cgroup.
  851. # ~/unshare -c # unshare cgroupns in some cgroup
  852. # cat /proc/self/cgroup
  853. 0::/
  854. # mkdir sub_cgrp_1
  855. # echo 0 > sub_cgrp_1/cgroup.procs
  856. # cat /proc/self/cgroup
  857. 0::/sub_cgrp_1
  858. Each process gets its namespace-specific view of "/proc/$PID/cgroup"
  859. Processes running inside the cgroup namespace will be able to see
  860. cgroup paths (in /proc/self/cgroup) only inside their root cgroup.
  861. From within an unshared cgroupns:
  862. # sleep 100000 &
  863. [1] 7353
  864. # echo 7353 > sub_cgrp_1/cgroup.procs
  865. # cat /proc/7353/cgroup
  866. 0::/sub_cgrp_1
  867. From the initial cgroup namespace, the real cgroup path will be
  868. visible:
  869. $ cat /proc/7353/cgroup
  870. 0::/batchjobs/container_id1/sub_cgrp_1
  871. From a sibling cgroup namespace (that is, a namespace rooted at a
  872. different cgroup), the cgroup path relative to its own cgroup
  873. namespace root will be shown. For instance, if PID 7353's cgroup
  874. namespace root is at '/batchjobs/container_id2', then it will see
  875. # cat /proc/7353/cgroup
  876. 0::/../container_id2/sub_cgrp_1
  877. Note that the relative path always starts with '/' to indicate that
  878. its relative to the cgroup namespace root of the caller.
  879. 6-3. Migration and setns(2)
  880. Processes inside a cgroup namespace can move into and out of the
  881. namespace root if they have proper access to external cgroups. For
  882. example, from inside a namespace with cgroupns root at
  883. /batchjobs/container_id1, and assuming that the global hierarchy is
  884. still accessible inside cgroupns:
  885. # cat /proc/7353/cgroup
  886. 0::/sub_cgrp_1
  887. # echo 7353 > batchjobs/container_id2/cgroup.procs
  888. # cat /proc/7353/cgroup
  889. 0::/../container_id2
  890. Note that this kind of setup is not encouraged. A task inside cgroup
  891. namespace should only be exposed to its own cgroupns hierarchy.
  892. setns(2) to another cgroup namespace is allowed when:
  893. (a) the process has CAP_SYS_ADMIN against its current user namespace
  894. (b) the process has CAP_SYS_ADMIN against the target cgroup
  895. namespace's userns
  896. No implicit cgroup changes happen with attaching to another cgroup
  897. namespace. It is expected that the someone moves the attaching
  898. process under the target cgroup namespace root.
  899. 6-4. Interaction with Other Namespaces
  900. Namespace specific cgroup hierarchy can be mounted by a process
  901. running inside a non-init cgroup namespace.
  902. # mount -t cgroup2 none $MOUNT_POINT
  903. This will mount the unified cgroup hierarchy with cgroupns root as the
  904. filesystem root. The process needs CAP_SYS_ADMIN against its user and
  905. mount namespaces.
  906. The virtualization of /proc/self/cgroup file combined with restricting
  907. the view of cgroup hierarchy by namespace-private cgroupfs mount
  908. provides a properly isolated cgroup view inside the container.
  909. P. Information on Kernel Programming
  910. This section contains kernel programming information in the areas
  911. where interacting with cgroup is necessary. cgroup core and
  912. controllers are not covered.
  913. P-1. Filesystem Support for Writeback
  914. A filesystem can support cgroup writeback by updating
  915. address_space_operations->writepage[s]() to annotate bio's using the
  916. following two functions.
  917. wbc_init_bio(@wbc, @bio)
  918. Should be called for each bio carrying writeback data and
  919. associates the bio with the inode's owner cgroup. Can be
  920. called anytime between bio allocation and submission.
  921. wbc_account_io(@wbc, @page, @bytes)
  922. Should be called for each data segment being written out.
  923. While this function doesn't care exactly when it's called
  924. during the writeback session, it's the easiest and most
  925. natural to call it as data segments are added to a bio.
  926. With writeback bio's annotated, cgroup support can be enabled per
  927. super_block by setting SB_I_CGROUPWB in ->s_iflags. This allows for
  928. selective disabling of cgroup writeback support which is helpful when
  929. certain filesystem features, e.g. journaled data mode, are
  930. incompatible.
  931. wbc_init_bio() binds the specified bio to its cgroup. Depending on
  932. the configuration, the bio may be executed at a lower priority and if
  933. the writeback session is holding shared resources, e.g. a journal
  934. entry, may lead to priority inversion. There is no one easy solution
  935. for the problem. Filesystems can try to work around specific problem
  936. cases by skipping wbc_init_bio() or using bio_associate_blkcg()
  937. directly.
  938. D. Deprecated v1 Core Features
  939. - Multiple hierarchies including named ones are not supported.
  940. - All mount options and remounting are not supported.
  941. - The "tasks" file is removed and "cgroup.procs" is not sorted.
  942. - "cgroup.clone_children" is removed.
  943. - /proc/cgroups is meaningless for v2. Use "cgroup.controllers" file
  944. at the root instead.
  945. R. Issues with v1 and Rationales for v2
  946. R-1. Multiple Hierarchies
  947. cgroup v1 allowed an arbitrary number of hierarchies and each
  948. hierarchy could host any number of controllers. While this seemed to
  949. provide a high level of flexibility, it wasn't useful in practice.
  950. For example, as there is only one instance of each controller, utility
  951. type controllers such as freezer which can be useful in all
  952. hierarchies could only be used in one. The issue is exacerbated by
  953. the fact that controllers couldn't be moved to another hierarchy once
  954. hierarchies were populated. Another issue was that all controllers
  955. bound to a hierarchy were forced to have exactly the same view of the
  956. hierarchy. It wasn't possible to vary the granularity depending on
  957. the specific controller.
  958. In practice, these issues heavily limited which controllers could be
  959. put on the same hierarchy and most configurations resorted to putting
  960. each controller on its own hierarchy. Only closely related ones, such
  961. as the cpu and cpuacct controllers, made sense to be put on the same
  962. hierarchy. This often meant that userland ended up managing multiple
  963. similar hierarchies repeating the same steps on each hierarchy
  964. whenever a hierarchy management operation was necessary.
  965. Furthermore, support for multiple hierarchies came at a steep cost.
  966. It greatly complicated cgroup core implementation but more importantly
  967. the support for multiple hierarchies restricted how cgroup could be
  968. used in general and what controllers was able to do.
  969. There was no limit on how many hierarchies there might be, which meant
  970. that a thread's cgroup membership couldn't be described in finite
  971. length. The key might contain any number of entries and was unlimited
  972. in length, which made it highly awkward to manipulate and led to
  973. addition of controllers which existed only to identify membership,
  974. which in turn exacerbated the original problem of proliferating number
  975. of hierarchies.
  976. Also, as a controller couldn't have any expectation regarding the
  977. topologies of hierarchies other controllers might be on, each
  978. controller had to assume that all other controllers were attached to
  979. completely orthogonal hierarchies. This made it impossible, or at
  980. least very cumbersome, for controllers to cooperate with each other.
  981. In most use cases, putting controllers on hierarchies which are
  982. completely orthogonal to each other isn't necessary. What usually is
  983. called for is the ability to have differing levels of granularity
  984. depending on the specific controller. In other words, hierarchy may
  985. be collapsed from leaf towards root when viewed from specific
  986. controllers. For example, a given configuration might not care about
  987. how memory is distributed beyond a certain level while still wanting
  988. to control how CPU cycles are distributed.
  989. R-2. Thread Granularity
  990. cgroup v1 allowed threads of a process to belong to different cgroups.
  991. This didn't make sense for some controllers and those controllers
  992. ended up implementing different ways to ignore such situations but
  993. much more importantly it blurred the line between API exposed to
  994. individual applications and system management interface.
  995. Generally, in-process knowledge is available only to the process
  996. itself; thus, unlike service-level organization of processes,
  997. categorizing threads of a process requires active participation from
  998. the application which owns the target process.
  999. cgroup v1 had an ambiguously defined delegation model which got abused
  1000. in combination with thread granularity. cgroups were delegated to
  1001. individual applications so that they can create and manage their own
  1002. sub-hierarchies and control resource distributions along them. This
  1003. effectively raised cgroup to the status of a syscall-like API exposed
  1004. to lay programs.
  1005. First of all, cgroup has a fundamentally inadequate interface to be
  1006. exposed this way. For a process to access its own knobs, it has to
  1007. extract the path on the target hierarchy from /proc/self/cgroup,
  1008. construct the path by appending the name of the knob to the path, open
  1009. and then read and/or write to it. This is not only extremely clunky
  1010. and unusual but also inherently racy. There is no conventional way to
  1011. define transaction across the required steps and nothing can guarantee
  1012. that the process would actually be operating on its own sub-hierarchy.
  1013. cgroup controllers implemented a number of knobs which would never be
  1014. accepted as public APIs because they were just adding control knobs to
  1015. system-management pseudo filesystem. cgroup ended up with interface
  1016. knobs which were not properly abstracted or refined and directly
  1017. revealed kernel internal details. These knobs got exposed to
  1018. individual applications through the ill-defined delegation mechanism
  1019. effectively abusing cgroup as a shortcut to implementing public APIs
  1020. without going through the required scrutiny.
  1021. This was painful for both userland and kernel. Userland ended up with
  1022. misbehaving and poorly abstracted interfaces and kernel exposing and
  1023. locked into constructs inadvertently.
  1024. R-3. Competition Between Inner Nodes and Threads
  1025. cgroup v1 allowed threads to be in any cgroups which created an
  1026. interesting problem where threads belonging to a parent cgroup and its
  1027. children cgroups competed for resources. This was nasty as two
  1028. different types of entities competed and there was no obvious way to
  1029. settle it. Different controllers did different things.
  1030. The cpu controller considered threads and cgroups as equivalents and
  1031. mapped nice levels to cgroup weights. This worked for some cases but
  1032. fell flat when children wanted to be allocated specific ratios of CPU
  1033. cycles and the number of internal threads fluctuated - the ratios
  1034. constantly changed as the number of competing entities fluctuated.
  1035. There also were other issues. The mapping from nice level to weight
  1036. wasn't obvious or universal, and there were various other knobs which
  1037. simply weren't available for threads.
  1038. The io controller implicitly created a hidden leaf node for each
  1039. cgroup to host the threads. The hidden leaf had its own copies of all
  1040. the knobs with "leaf_" prefixed. While this allowed equivalent
  1041. control over internal threads, it was with serious drawbacks. It
  1042. always added an extra layer of nesting which wouldn't be necessary
  1043. otherwise, made the interface messy and significantly complicated the
  1044. implementation.
  1045. The memory controller didn't have a way to control what happened
  1046. between internal tasks and child cgroups and the behavior was not
  1047. clearly defined. There were attempts to add ad-hoc behaviors and
  1048. knobs to tailor the behavior to specific workloads which would have
  1049. led to problems extremely difficult to resolve in the long term.
  1050. Multiple controllers struggled with internal tasks and came up with
  1051. different ways to deal with it; unfortunately, all the approaches were
  1052. severely flawed and, furthermore, the widely different behaviors
  1053. made cgroup as a whole highly inconsistent.
  1054. This clearly is a problem which needs to be addressed from cgroup core
  1055. in a uniform way.
  1056. R-4. Other Interface Issues
  1057. cgroup v1 grew without oversight and developed a large number of
  1058. idiosyncrasies and inconsistencies. One issue on the cgroup core side
  1059. was how an empty cgroup was notified - a userland helper binary was
  1060. forked and executed for each event. The event delivery wasn't
  1061. recursive or delegatable. The limitations of the mechanism also led
  1062. to in-kernel event delivery filtering mechanism further complicating
  1063. the interface.
  1064. Controller interfaces were problematic too. An extreme example is
  1065. controllers completely ignoring hierarchical organization and treating
  1066. all cgroups as if they were all located directly under the root
  1067. cgroup. Some controllers exposed a large amount of inconsistent
  1068. implementation details to userland.
  1069. There also was no consistency across controllers. When a new cgroup
  1070. was created, some controllers defaulted to not imposing extra
  1071. restrictions while others disallowed any resource usage until
  1072. explicitly configured. Configuration knobs for the same type of
  1073. control used widely differing naming schemes and formats. Statistics
  1074. and information knobs were named arbitrarily and used different
  1075. formats and units even in the same controller.
  1076. cgroup v2 establishes common conventions where appropriate and updates
  1077. controllers so that they expose minimal and consistent interfaces.
  1078. R-5. Controller Issues and Remedies
  1079. R-5-1. Memory
  1080. The original lower boundary, the soft limit, is defined as a limit
  1081. that is per default unset. As a result, the set of cgroups that
  1082. global reclaim prefers is opt-in, rather than opt-out. The costs for
  1083. optimizing these mostly negative lookups are so high that the
  1084. implementation, despite its enormous size, does not even provide the
  1085. basic desirable behavior. First off, the soft limit has no
  1086. hierarchical meaning. All configured groups are organized in a global
  1087. rbtree and treated like equal peers, regardless where they are located
  1088. in the hierarchy. This makes subtree delegation impossible. Second,
  1089. the soft limit reclaim pass is so aggressive that it not just
  1090. introduces high allocation latencies into the system, but also impacts
  1091. system performance due to overreclaim, to the point where the feature
  1092. becomes self-defeating.
  1093. The memory.low boundary on the other hand is a top-down allocated
  1094. reserve. A cgroup enjoys reclaim protection when it and all its
  1095. ancestors are below their low boundaries, which makes delegation of
  1096. subtrees possible. Secondly, new cgroups have no reserve per default
  1097. and in the common case most cgroups are eligible for the preferred
  1098. reclaim pass. This allows the new low boundary to be efficiently
  1099. implemented with just a minor addition to the generic reclaim code,
  1100. without the need for out-of-band data structures and reclaim passes.
  1101. Because the generic reclaim code considers all cgroups except for the
  1102. ones running low in the preferred first reclaim pass, overreclaim of
  1103. individual groups is eliminated as well, resulting in much better
  1104. overall workload performance.
  1105. The original high boundary, the hard limit, is defined as a strict
  1106. limit that can not budge, even if the OOM killer has to be called.
  1107. But this generally goes against the goal of making the most out of the
  1108. available memory. The memory consumption of workloads varies during
  1109. runtime, and that requires users to overcommit. But doing that with a
  1110. strict upper limit requires either a fairly accurate prediction of the
  1111. working set size or adding slack to the limit. Since working set size
  1112. estimation is hard and error prone, and getting it wrong results in
  1113. OOM kills, most users tend to err on the side of a looser limit and
  1114. end up wasting precious resources.
  1115. The memory.high boundary on the other hand can be set much more
  1116. conservatively. When hit, it throttles allocations by forcing them
  1117. into direct reclaim to work off the excess, but it never invokes the
  1118. OOM killer. As a result, a high boundary that is chosen too
  1119. aggressively will not terminate the processes, but instead it will
  1120. lead to gradual performance degradation. The user can monitor this
  1121. and make corrections until the minimal memory footprint that still
  1122. gives acceptable performance is found.
  1123. In extreme cases, with many concurrent allocations and a complete
  1124. breakdown of reclaim progress within the group, the high boundary can
  1125. be exceeded. But even then it's mostly better to satisfy the
  1126. allocation from the slack available in other groups or the rest of the
  1127. system than killing the group. Otherwise, memory.max is there to
  1128. limit this type of spillover and ultimately contain buggy or even
  1129. malicious applications.
  1130. Setting the original memory.limit_in_bytes below the current usage was
  1131. subject to a race condition, where concurrent charges could cause the
  1132. limit setting to fail. memory.max on the other hand will first set the
  1133. limit to prevent new charges, and then reclaim and OOM kill until the
  1134. new limit is met - or the task writing to memory.max is killed.
  1135. The combined memory+swap accounting and limiting is replaced by real
  1136. control over swap space.
  1137. The main argument for a combined memory+swap facility in the original
  1138. cgroup design was that global or parental pressure would always be
  1139. able to swap all anonymous memory of a child group, regardless of the
  1140. child's own (possibly untrusted) configuration. However, untrusted
  1141. groups can sabotage swapping by other means - such as referencing its
  1142. anonymous memory in a tight loop - and an admin can not assume full
  1143. swappability when overcommitting untrusted jobs.
  1144. For trusted jobs, on the other hand, a combined counter is not an
  1145. intuitive userspace interface, and it flies in the face of the idea
  1146. that cgroup controllers should account and limit specific physical
  1147. resources. Swap space is a resource like all others in the system,
  1148. and that's why unified hierarchy allows distributing it separately.