cgroup-v2.rst 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142
  1. ================
  2. Control Group v2
  3. ================
  4. :Date: October, 2015
  5. :Author: Tejun Heo <tj@kernel.org>
  6. This is the authoritative documentation on the design, interface and
  7. conventions of cgroup v2. It describes all userland-visible aspects
  8. of cgroup including core and specific controller behaviors. All
  9. future changes must be reflected in this document. Documentation for
  10. v1 is available under Documentation/cgroup-v1/.
  11. .. CONTENTS
  12. 1. Introduction
  13. 1-1. Terminology
  14. 1-2. What is cgroup?
  15. 2. Basic Operations
  16. 2-1. Mounting
  17. 2-2. Organizing Processes and Threads
  18. 2-2-1. Processes
  19. 2-2-2. Threads
  20. 2-3. [Un]populated Notification
  21. 2-4. Controlling Controllers
  22. 2-4-1. Enabling and Disabling
  23. 2-4-2. Top-down Constraint
  24. 2-4-3. No Internal Process Constraint
  25. 2-5. Delegation
  26. 2-5-1. Model of Delegation
  27. 2-5-2. Delegation Containment
  28. 2-6. Guidelines
  29. 2-6-1. Organize Once and Control
  30. 2-6-2. Avoid Name Collisions
  31. 3. Resource Distribution Models
  32. 3-1. Weights
  33. 3-2. Limits
  34. 3-3. Protections
  35. 3-4. Allocations
  36. 4. Interface Files
  37. 4-1. Format
  38. 4-2. Conventions
  39. 4-3. Core Interface Files
  40. 5. Controllers
  41. 5-1. CPU
  42. 5-1-1. CPU Interface Files
  43. 5-2. Memory
  44. 5-2-1. Memory Interface Files
  45. 5-2-2. Usage Guidelines
  46. 5-2-3. Memory Ownership
  47. 5-3. IO
  48. 5-3-1. IO Interface Files
  49. 5-3-2. Writeback
  50. 5-3-3. IO Latency
  51. 5-3-3-1. How IO Latency Throttling Works
  52. 5-3-3-2. IO Latency Interface Files
  53. 5-4. PID
  54. 5-4-1. PID Interface Files
  55. 5-5. Device
  56. 5-6. RDMA
  57. 5-6-1. RDMA Interface Files
  58. 5-7. Misc
  59. 5-7-1. perf_event
  60. 5-N. Non-normative information
  61. 5-N-1. CPU controller root cgroup process behaviour
  62. 5-N-2. IO controller root cgroup process behaviour
  63. 6. Namespace
  64. 6-1. Basics
  65. 6-2. The Root and Views
  66. 6-3. Migration and setns(2)
  67. 6-4. Interaction with Other Namespaces
  68. P. Information on Kernel Programming
  69. P-1. Filesystem Support for Writeback
  70. D. Deprecated v1 Core Features
  71. R. Issues with v1 and Rationales for v2
  72. R-1. Multiple Hierarchies
  73. R-2. Thread Granularity
  74. R-3. Competition Between Inner Nodes and Threads
  75. R-4. Other Interface Issues
  76. R-5. Controller Issues and Remedies
  77. R-5-1. Memory
  78. Introduction
  79. ============
  80. Terminology
  81. -----------
  82. "cgroup" stands for "control group" and is never capitalized. The
  83. singular form is used to designate the whole feature and also as a
  84. qualifier as in "cgroup controllers". When explicitly referring to
  85. multiple individual control groups, the plural form "cgroups" is used.
  86. What is cgroup?
  87. ---------------
  88. cgroup is a mechanism to organize processes hierarchically and
  89. distribute system resources along the hierarchy in a controlled and
  90. configurable manner.
  91. cgroup is largely composed of two parts - the core and controllers.
  92. cgroup core is primarily responsible for hierarchically organizing
  93. processes. A cgroup controller is usually responsible for
  94. distributing a specific type of system resource along the hierarchy
  95. although there are utility controllers which serve purposes other than
  96. resource distribution.
  97. cgroups form a tree structure and every process in the system belongs
  98. to one and only one cgroup. All threads of a process belong to the
  99. same cgroup. On creation, all processes are put in the cgroup that
  100. the parent process belongs to at the time. A process can be migrated
  101. to another cgroup. Migration of a process doesn't affect already
  102. existing descendant processes.
  103. Following certain structural constraints, controllers may be enabled or
  104. disabled selectively on a cgroup. All controller behaviors are
  105. hierarchical - if a controller is enabled on a cgroup, it affects all
  106. processes which belong to the cgroups consisting the inclusive
  107. sub-hierarchy of the cgroup. When a controller is enabled on a nested
  108. cgroup, it always restricts the resource distribution further. The
  109. restrictions set closer to the root in the hierarchy can not be
  110. overridden from further away.
  111. Basic Operations
  112. ================
  113. Mounting
  114. --------
  115. Unlike v1, cgroup v2 has only single hierarchy. The cgroup v2
  116. hierarchy can be mounted with the following mount command::
  117. # mount -t cgroup2 none $MOUNT_POINT
  118. cgroup2 filesystem has the magic number 0x63677270 ("cgrp"). All
  119. controllers which support v2 and are not bound to a v1 hierarchy are
  120. automatically bound to the v2 hierarchy and show up at the root.
  121. Controllers which are not in active use in the v2 hierarchy can be
  122. bound to other hierarchies. This allows mixing v2 hierarchy with the
  123. legacy v1 multiple hierarchies in a fully backward compatible way.
  124. A controller can be moved across hierarchies only after the controller
  125. is no longer referenced in its current hierarchy. Because per-cgroup
  126. controller states are destroyed asynchronously and controllers may
  127. have lingering references, a controller may not show up immediately on
  128. the v2 hierarchy after the final umount of the previous hierarchy.
  129. Similarly, a controller should be fully disabled to be moved out of
  130. the unified hierarchy and it may take some time for the disabled
  131. controller to become available for other hierarchies; furthermore, due
  132. to inter-controller dependencies, other controllers may need to be
  133. disabled too.
  134. While useful for development and manual configurations, moving
  135. controllers dynamically between the v2 and other hierarchies is
  136. strongly discouraged for production use. It is recommended to decide
  137. the hierarchies and controller associations before starting using the
  138. controllers after system boot.
  139. During transition to v2, system management software might still
  140. automount the v1 cgroup filesystem and so hijack all controllers
  141. during boot, before manual intervention is possible. To make testing
  142. and experimenting easier, the kernel parameter cgroup_no_v1= allows
  143. disabling controllers in v1 and make them always available in v2.
  144. cgroup v2 currently supports the following mount options.
  145. nsdelegate
  146. Consider cgroup namespaces as delegation boundaries. This
  147. option is system wide and can only be set on mount or modified
  148. through remount from the init namespace. The mount option is
  149. ignored on non-init namespace mounts. Please refer to the
  150. Delegation section for details.
  151. Organizing Processes and Threads
  152. --------------------------------
  153. Processes
  154. ~~~~~~~~~
  155. Initially, only the root cgroup exists to which all processes belong.
  156. A child cgroup can be created by creating a sub-directory::
  157. # mkdir $CGROUP_NAME
  158. A given cgroup may have multiple child cgroups forming a tree
  159. structure. Each cgroup has a read-writable interface file
  160. "cgroup.procs". When read, it lists the PIDs of all processes which
  161. belong to the cgroup one-per-line. The PIDs are not ordered and the
  162. same PID may show up more than once if the process got moved to
  163. another cgroup and then back or the PID got recycled while reading.
  164. A process can be migrated into a cgroup by writing its PID to the
  165. target cgroup's "cgroup.procs" file. Only one process can be migrated
  166. on a single write(2) call. If a process is composed of multiple
  167. threads, writing the PID of any thread migrates all threads of the
  168. process.
  169. When a process forks a child process, the new process is born into the
  170. cgroup that the forking process belongs to at the time of the
  171. operation. After exit, a process stays associated with the cgroup
  172. that it belonged to at the time of exit until it's reaped; however, a
  173. zombie process does not appear in "cgroup.procs" and thus can't be
  174. moved to another cgroup.
  175. A cgroup which doesn't have any children or live processes can be
  176. destroyed by removing the directory. Note that a cgroup which doesn't
  177. have any children and is associated only with zombie processes is
  178. considered empty and can be removed::
  179. # rmdir $CGROUP_NAME
  180. "/proc/$PID/cgroup" lists a process's cgroup membership. If legacy
  181. cgroup is in use in the system, this file may contain multiple lines,
  182. one for each hierarchy. The entry for cgroup v2 is always in the
  183. format "0::$PATH"::
  184. # cat /proc/842/cgroup
  185. ...
  186. 0::/test-cgroup/test-cgroup-nested
  187. If the process becomes a zombie and the cgroup it was associated with
  188. is removed subsequently, " (deleted)" is appended to the path::
  189. # cat /proc/842/cgroup
  190. ...
  191. 0::/test-cgroup/test-cgroup-nested (deleted)
  192. Threads
  193. ~~~~~~~
  194. cgroup v2 supports thread granularity for a subset of controllers to
  195. support use cases requiring hierarchical resource distribution across
  196. the threads of a group of processes. By default, all threads of a
  197. process belong to the same cgroup, which also serves as the resource
  198. domain to host resource consumptions which are not specific to a
  199. process or thread. The thread mode allows threads to be spread across
  200. a subtree while still maintaining the common resource domain for them.
  201. Controllers which support thread mode are called threaded controllers.
  202. The ones which don't are called domain controllers.
  203. Marking a cgroup threaded makes it join the resource domain of its
  204. parent as a threaded cgroup. The parent may be another threaded
  205. cgroup whose resource domain is further up in the hierarchy. The root
  206. of a threaded subtree, that is, the nearest ancestor which is not
  207. threaded, is called threaded domain or thread root interchangeably and
  208. serves as the resource domain for the entire subtree.
  209. Inside a threaded subtree, threads of a process can be put in
  210. different cgroups and are not subject to the no internal process
  211. constraint - threaded controllers can be enabled on non-leaf cgroups
  212. whether they have threads in them or not.
  213. As the threaded domain cgroup hosts all the domain resource
  214. consumptions of the subtree, it is considered to have internal
  215. resource consumptions whether there are processes in it or not and
  216. can't have populated child cgroups which aren't threaded. Because the
  217. root cgroup is not subject to no internal process constraint, it can
  218. serve both as a threaded domain and a parent to domain cgroups.
  219. The current operation mode or type of the cgroup is shown in the
  220. "cgroup.type" file which indicates whether the cgroup is a normal
  221. domain, a domain which is serving as the domain of a threaded subtree,
  222. or a threaded cgroup.
  223. On creation, a cgroup is always a domain cgroup and can be made
  224. threaded by writing "threaded" to the "cgroup.type" file. The
  225. operation is single direction::
  226. # echo threaded > cgroup.type
  227. Once threaded, the cgroup can't be made a domain again. To enable the
  228. thread mode, the following conditions must be met.
  229. - As the cgroup will join the parent's resource domain. The parent
  230. must either be a valid (threaded) domain or a threaded cgroup.
  231. - When the parent is an unthreaded domain, it must not have any domain
  232. controllers enabled or populated domain children. The root is
  233. exempt from this requirement.
  234. Topology-wise, a cgroup can be in an invalid state. Please consider
  235. the following topology::
  236. A (threaded domain) - B (threaded) - C (domain, just created)
  237. C is created as a domain but isn't connected to a parent which can
  238. host child domains. C can't be used until it is turned into a
  239. threaded cgroup. "cgroup.type" file will report "domain (invalid)" in
  240. these cases. Operations which fail due to invalid topology use
  241. EOPNOTSUPP as the errno.
  242. A domain cgroup is turned into a threaded domain when one of its child
  243. cgroup becomes threaded or threaded controllers are enabled in the
  244. "cgroup.subtree_control" file while there are processes in the cgroup.
  245. A threaded domain reverts to a normal domain when the conditions
  246. clear.
  247. When read, "cgroup.threads" contains the list of the thread IDs of all
  248. threads in the cgroup. Except that the operations are per-thread
  249. instead of per-process, "cgroup.threads" has the same format and
  250. behaves the same way as "cgroup.procs". While "cgroup.threads" can be
  251. written to in any cgroup, as it can only move threads inside the same
  252. threaded domain, its operations are confined inside each threaded
  253. subtree.
  254. The threaded domain cgroup serves as the resource domain for the whole
  255. subtree, and, while the threads can be scattered across the subtree,
  256. all the processes are considered to be in the threaded domain cgroup.
  257. "cgroup.procs" in a threaded domain cgroup contains the PIDs of all
  258. processes in the subtree and is not readable in the subtree proper.
  259. However, "cgroup.procs" can be written to from anywhere in the subtree
  260. to migrate all threads of the matching process to the cgroup.
  261. Only threaded controllers can be enabled in a threaded subtree. When
  262. a threaded controller is enabled inside a threaded subtree, it only
  263. accounts for and controls resource consumptions associated with the
  264. threads in the cgroup and its descendants. All consumptions which
  265. aren't tied to a specific thread belong to the threaded domain cgroup.
  266. Because a threaded subtree is exempt from no internal process
  267. constraint, a threaded controller must be able to handle competition
  268. between threads in a non-leaf cgroup and its child cgroups. Each
  269. threaded controller defines how such competitions are handled.
  270. [Un]populated Notification
  271. --------------------------
  272. Each non-root cgroup has a "cgroup.events" file which contains
  273. "populated" field indicating whether the cgroup's sub-hierarchy has
  274. live processes in it. Its value is 0 if there is no live process in
  275. the cgroup and its descendants; otherwise, 1. poll and [id]notify
  276. events are triggered when the value changes. This can be used, for
  277. example, to start a clean-up operation after all processes of a given
  278. sub-hierarchy have exited. The populated state updates and
  279. notifications are recursive. Consider the following sub-hierarchy
  280. where the numbers in the parentheses represent the numbers of processes
  281. in each cgroup::
  282. A(4) - B(0) - C(1)
  283. \ D(0)
  284. A, B and C's "populated" fields would be 1 while D's 0. After the one
  285. process in C exits, B and C's "populated" fields would flip to "0" and
  286. file modified events will be generated on the "cgroup.events" files of
  287. both cgroups.
  288. Controlling Controllers
  289. -----------------------
  290. Enabling and Disabling
  291. ~~~~~~~~~~~~~~~~~~~~~~
  292. Each cgroup has a "cgroup.controllers" file which lists all
  293. controllers available for the cgroup to enable::
  294. # cat cgroup.controllers
  295. cpu io memory
  296. No controller is enabled by default. Controllers can be enabled and
  297. disabled by writing to the "cgroup.subtree_control" file::
  298. # echo "+cpu +memory -io" > cgroup.subtree_control
  299. Only controllers which are listed in "cgroup.controllers" can be
  300. enabled. When multiple operations are specified as above, either they
  301. all succeed or fail. If multiple operations on the same controller
  302. are specified, the last one is effective.
  303. Enabling a controller in a cgroup indicates that the distribution of
  304. the target resource across its immediate children will be controlled.
  305. Consider the following sub-hierarchy. The enabled controllers are
  306. listed in parentheses::
  307. A(cpu,memory) - B(memory) - C()
  308. \ D()
  309. As A has "cpu" and "memory" enabled, A will control the distribution
  310. of CPU cycles and memory to its children, in this case, B. As B has
  311. "memory" enabled but not "CPU", C and D will compete freely on CPU
  312. cycles but their division of memory available to B will be controlled.
  313. As a controller regulates the distribution of the target resource to
  314. the cgroup's children, enabling it creates the controller's interface
  315. files in the child cgroups. In the above example, enabling "cpu" on B
  316. would create the "cpu." prefixed controller interface files in C and
  317. D. Likewise, disabling "memory" from B would remove the "memory."
  318. prefixed controller interface files from C and D. This means that the
  319. controller interface files - anything which doesn't start with
  320. "cgroup." are owned by the parent rather than the cgroup itself.
  321. Top-down Constraint
  322. ~~~~~~~~~~~~~~~~~~~
  323. Resources are distributed top-down and a cgroup can further distribute
  324. a resource only if the resource has been distributed to it from the
  325. parent. This means that all non-root "cgroup.subtree_control" files
  326. can only contain controllers which are enabled in the parent's
  327. "cgroup.subtree_control" file. A controller can be enabled only if
  328. the parent has the controller enabled and a controller can't be
  329. disabled if one or more children have it enabled.
  330. No Internal Process Constraint
  331. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  332. Non-root cgroups can distribute domain resources to their children
  333. only when they don't have any processes of their own. In other words,
  334. only domain cgroups which don't contain any processes can have domain
  335. controllers enabled in their "cgroup.subtree_control" files.
  336. This guarantees that, when a domain controller is looking at the part
  337. of the hierarchy which has it enabled, processes are always only on
  338. the leaves. This rules out situations where child cgroups compete
  339. against internal processes of the parent.
  340. The root cgroup is exempt from this restriction. Root contains
  341. processes and anonymous resource consumption which can't be associated
  342. with any other cgroups and requires special treatment from most
  343. controllers. How resource consumption in the root cgroup is governed
  344. is up to each controller (for more information on this topic please
  345. refer to the Non-normative information section in the Controllers
  346. chapter).
  347. Note that the restriction doesn't get in the way if there is no
  348. enabled controller in the cgroup's "cgroup.subtree_control". This is
  349. important as otherwise it wouldn't be possible to create children of a
  350. populated cgroup. To control resource distribution of a cgroup, the
  351. cgroup must create children and transfer all its processes to the
  352. children before enabling controllers in its "cgroup.subtree_control"
  353. file.
  354. Delegation
  355. ----------
  356. Model of Delegation
  357. ~~~~~~~~~~~~~~~~~~~
  358. A cgroup can be delegated in two ways. First, to a less privileged
  359. user by granting write access of the directory and its "cgroup.procs",
  360. "cgroup.threads" and "cgroup.subtree_control" files to the user.
  361. Second, if the "nsdelegate" mount option is set, automatically to a
  362. cgroup namespace on namespace creation.
  363. Because the resource control interface files in a given directory
  364. control the distribution of the parent's resources, the delegatee
  365. shouldn't be allowed to write to them. For the first method, this is
  366. achieved by not granting access to these files. For the second, the
  367. kernel rejects writes to all files other than "cgroup.procs" and
  368. "cgroup.subtree_control" on a namespace root from inside the
  369. namespace.
  370. The end results are equivalent for both delegation types. Once
  371. delegated, the user can build sub-hierarchy under the directory,
  372. organize processes inside it as it sees fit and further distribute the
  373. resources it received from the parent. The limits and other settings
  374. of all resource controllers are hierarchical and regardless of what
  375. happens in the delegated sub-hierarchy, nothing can escape the
  376. resource restrictions imposed by the parent.
  377. Currently, cgroup doesn't impose any restrictions on the number of
  378. cgroups in or nesting depth of a delegated sub-hierarchy; however,
  379. this may be limited explicitly in the future.
  380. Delegation Containment
  381. ~~~~~~~~~~~~~~~~~~~~~~
  382. A delegated sub-hierarchy is contained in the sense that processes
  383. can't be moved into or out of the sub-hierarchy by the delegatee.
  384. For delegations to a less privileged user, this is achieved by
  385. requiring the following conditions for a process with a non-root euid
  386. to migrate a target process into a cgroup by writing its PID to the
  387. "cgroup.procs" file.
  388. - The writer must have write access to the "cgroup.procs" file.
  389. - The writer must have write access to the "cgroup.procs" file of the
  390. common ancestor of the source and destination cgroups.
  391. The above two constraints ensure that while a delegatee may migrate
  392. processes around freely in the delegated sub-hierarchy it can't pull
  393. in from or push out to outside the sub-hierarchy.
  394. For an example, let's assume cgroups C0 and C1 have been delegated to
  395. user U0 who created C00, C01 under C0 and C10 under C1 as follows and
  396. all processes under C0 and C1 belong to U0::
  397. ~~~~~~~~~~~~~ - C0 - C00
  398. ~ cgroup ~ \ C01
  399. ~ hierarchy ~
  400. ~~~~~~~~~~~~~ - C1 - C10
  401. Let's also say U0 wants to write the PID of a process which is
  402. currently in C10 into "C00/cgroup.procs". U0 has write access to the
  403. file; however, the common ancestor of the source cgroup C10 and the
  404. destination cgroup C00 is above the points of delegation and U0 would
  405. not have write access to its "cgroup.procs" files and thus the write
  406. will be denied with -EACCES.
  407. For delegations to namespaces, containment is achieved by requiring
  408. that both the source and destination cgroups are reachable from the
  409. namespace of the process which is attempting the migration. If either
  410. is not reachable, the migration is rejected with -ENOENT.
  411. Guidelines
  412. ----------
  413. Organize Once and Control
  414. ~~~~~~~~~~~~~~~~~~~~~~~~~
  415. Migrating a process across cgroups is a relatively expensive operation
  416. and stateful resources such as memory are not moved together with the
  417. process. This is an explicit design decision as there often exist
  418. inherent trade-offs between migration and various hot paths in terms
  419. of synchronization cost.
  420. As such, migrating processes across cgroups frequently as a means to
  421. apply different resource restrictions is discouraged. A workload
  422. should be assigned to a cgroup according to the system's logical and
  423. resource structure once on start-up. Dynamic adjustments to resource
  424. distribution can be made by changing controller configuration through
  425. the interface files.
  426. Avoid Name Collisions
  427. ~~~~~~~~~~~~~~~~~~~~~
  428. Interface files for a cgroup and its children cgroups occupy the same
  429. directory and it is possible to create children cgroups which collide
  430. with interface files.
  431. All cgroup core interface files are prefixed with "cgroup." and each
  432. controller's interface files are prefixed with the controller name and
  433. a dot. A controller's name is composed of lower case alphabets and
  434. '_'s but never begins with an '_' so it can be used as the prefix
  435. character for collision avoidance. Also, interface file names won't
  436. start or end with terms which are often used in categorizing workloads
  437. such as job, service, slice, unit or workload.
  438. cgroup doesn't do anything to prevent name collisions and it's the
  439. user's responsibility to avoid them.
  440. Resource Distribution Models
  441. ============================
  442. cgroup controllers implement several resource distribution schemes
  443. depending on the resource type and expected use cases. This section
  444. describes major schemes in use along with their expected behaviors.
  445. Weights
  446. -------
  447. A parent's resource is distributed by adding up the weights of all
  448. active children and giving each the fraction matching the ratio of its
  449. weight against the sum. As only children which can make use of the
  450. resource at the moment participate in the distribution, this is
  451. work-conserving. Due to the dynamic nature, this model is usually
  452. used for stateless resources.
  453. All weights are in the range [1, 10000] with the default at 100. This
  454. allows symmetric multiplicative biases in both directions at fine
  455. enough granularity while staying in the intuitive range.
  456. As long as the weight is in range, all configuration combinations are
  457. valid and there is no reason to reject configuration changes or
  458. process migrations.
  459. "cpu.weight" proportionally distributes CPU cycles to active children
  460. and is an example of this type.
  461. Limits
  462. ------
  463. A child can only consume upto the configured amount of the resource.
  464. Limits can be over-committed - the sum of the limits of children can
  465. exceed the amount of resource available to the parent.
  466. Limits are in the range [0, max] and defaults to "max", which is noop.
  467. As limits can be over-committed, all configuration combinations are
  468. valid and there is no reason to reject configuration changes or
  469. process migrations.
  470. "io.max" limits the maximum BPS and/or IOPS that a cgroup can consume
  471. on an IO device and is an example of this type.
  472. Protections
  473. -----------
  474. A cgroup is protected to be allocated upto the configured amount of
  475. the resource if the usages of all its ancestors are under their
  476. protected levels. Protections can be hard guarantees or best effort
  477. soft boundaries. Protections can also be over-committed in which case
  478. only upto the amount available to the parent is protected among
  479. children.
  480. Protections are in the range [0, max] and defaults to 0, which is
  481. noop.
  482. As protections can be over-committed, all configuration combinations
  483. are valid and there is no reason to reject configuration changes or
  484. process migrations.
  485. "memory.low" implements best-effort memory protection and is an
  486. example of this type.
  487. Allocations
  488. -----------
  489. A cgroup is exclusively allocated a certain amount of a finite
  490. resource. Allocations can't be over-committed - the sum of the
  491. allocations of children can not exceed the amount of resource
  492. available to the parent.
  493. Allocations are in the range [0, max] and defaults to 0, which is no
  494. resource.
  495. As allocations can't be over-committed, some configuration
  496. combinations are invalid and should be rejected. Also, if the
  497. resource is mandatory for execution of processes, process migrations
  498. may be rejected.
  499. "cpu.rt.max" hard-allocates realtime slices and is an example of this
  500. type.
  501. Interface Files
  502. ===============
  503. Format
  504. ------
  505. All interface files should be in one of the following formats whenever
  506. possible::
  507. New-line separated values
  508. (when only one value can be written at once)
  509. VAL0\n
  510. VAL1\n
  511. ...
  512. Space separated values
  513. (when read-only or multiple values can be written at once)
  514. VAL0 VAL1 ...\n
  515. Flat keyed
  516. KEY0 VAL0\n
  517. KEY1 VAL1\n
  518. ...
  519. Nested keyed
  520. KEY0 SUB_KEY0=VAL00 SUB_KEY1=VAL01...
  521. KEY1 SUB_KEY0=VAL10 SUB_KEY1=VAL11...
  522. ...
  523. For a writable file, the format for writing should generally match
  524. reading; however, controllers may allow omitting later fields or
  525. implement restricted shortcuts for most common use cases.
  526. For both flat and nested keyed files, only the values for a single key
  527. can be written at a time. For nested keyed files, the sub key pairs
  528. may be specified in any order and not all pairs have to be specified.
  529. Conventions
  530. -----------
  531. - Settings for a single feature should be contained in a single file.
  532. - The root cgroup should be exempt from resource control and thus
  533. shouldn't have resource control interface files. Also,
  534. informational files on the root cgroup which end up showing global
  535. information available elsewhere shouldn't exist.
  536. - If a controller implements weight based resource distribution, its
  537. interface file should be named "weight" and have the range [1,
  538. 10000] with 100 as the default. The values are chosen to allow
  539. enough and symmetric bias in both directions while keeping it
  540. intuitive (the default is 100%).
  541. - If a controller implements an absolute resource guarantee and/or
  542. limit, the interface files should be named "min" and "max"
  543. respectively. If a controller implements best effort resource
  544. guarantee and/or limit, the interface files should be named "low"
  545. and "high" respectively.
  546. In the above four control files, the special token "max" should be
  547. used to represent upward infinity for both reading and writing.
  548. - If a setting has a configurable default value and keyed specific
  549. overrides, the default entry should be keyed with "default" and
  550. appear as the first entry in the file.
  551. The default value can be updated by writing either "default $VAL" or
  552. "$VAL".
  553. When writing to update a specific override, "default" can be used as
  554. the value to indicate removal of the override. Override entries
  555. with "default" as the value must not appear when read.
  556. For example, a setting which is keyed by major:minor device numbers
  557. with integer values may look like the following::
  558. # cat cgroup-example-interface-file
  559. default 150
  560. 8:0 300
  561. The default value can be updated by::
  562. # echo 125 > cgroup-example-interface-file
  563. or::
  564. # echo "default 125" > cgroup-example-interface-file
  565. An override can be set by::
  566. # echo "8:16 170" > cgroup-example-interface-file
  567. and cleared by::
  568. # echo "8:0 default" > cgroup-example-interface-file
  569. # cat cgroup-example-interface-file
  570. default 125
  571. 8:16 170
  572. - For events which are not very high frequency, an interface file
  573. "events" should be created which lists event key value pairs.
  574. Whenever a notifiable event happens, file modified event should be
  575. generated on the file.
  576. Core Interface Files
  577. --------------------
  578. All cgroup core files are prefixed with "cgroup."
  579. cgroup.type
  580. A read-write single value file which exists on non-root
  581. cgroups.
  582. When read, it indicates the current type of the cgroup, which
  583. can be one of the following values.
  584. - "domain" : A normal valid domain cgroup.
  585. - "domain threaded" : A threaded domain cgroup which is
  586. serving as the root of a threaded subtree.
  587. - "domain invalid" : A cgroup which is in an invalid state.
  588. It can't be populated or have controllers enabled. It may
  589. be allowed to become a threaded cgroup.
  590. - "threaded" : A threaded cgroup which is a member of a
  591. threaded subtree.
  592. A cgroup can be turned into a threaded cgroup by writing
  593. "threaded" to this file.
  594. cgroup.procs
  595. A read-write new-line separated values file which exists on
  596. all cgroups.
  597. When read, it lists the PIDs of all processes which belong to
  598. the cgroup one-per-line. The PIDs are not ordered and the
  599. same PID may show up more than once if the process got moved
  600. to another cgroup and then back or the PID got recycled while
  601. reading.
  602. A PID can be written to migrate the process associated with
  603. the PID to the cgroup. The writer should match all of the
  604. following conditions.
  605. - It must have write access to the "cgroup.procs" file.
  606. - It must have write access to the "cgroup.procs" file of the
  607. common ancestor of the source and destination cgroups.
  608. When delegating a sub-hierarchy, write access to this file
  609. should be granted along with the containing directory.
  610. In a threaded cgroup, reading this file fails with EOPNOTSUPP
  611. as all the processes belong to the thread root. Writing is
  612. supported and moves every thread of the process to the cgroup.
  613. cgroup.threads
  614. A read-write new-line separated values file which exists on
  615. all cgroups.
  616. When read, it lists the TIDs of all threads which belong to
  617. the cgroup one-per-line. The TIDs are not ordered and the
  618. same TID may show up more than once if the thread got moved to
  619. another cgroup and then back or the TID got recycled while
  620. reading.
  621. A TID can be written to migrate the thread associated with the
  622. TID to the cgroup. The writer should match all of the
  623. following conditions.
  624. - It must have write access to the "cgroup.threads" file.
  625. - The cgroup that the thread is currently in must be in the
  626. same resource domain as the destination cgroup.
  627. - It must have write access to the "cgroup.procs" file of the
  628. common ancestor of the source and destination cgroups.
  629. When delegating a sub-hierarchy, write access to this file
  630. should be granted along with the containing directory.
  631. cgroup.controllers
  632. A read-only space separated values file which exists on all
  633. cgroups.
  634. It shows space separated list of all controllers available to
  635. the cgroup. The controllers are not ordered.
  636. cgroup.subtree_control
  637. A read-write space separated values file which exists on all
  638. cgroups. Starts out empty.
  639. When read, it shows space separated list of the controllers
  640. which are enabled to control resource distribution from the
  641. cgroup to its children.
  642. Space separated list of controllers prefixed with '+' or '-'
  643. can be written to enable or disable controllers. A controller
  644. name prefixed with '+' enables the controller and '-'
  645. disables. If a controller appears more than once on the list,
  646. the last one is effective. When multiple enable and disable
  647. operations are specified, either all succeed or all fail.
  648. cgroup.events
  649. A read-only flat-keyed file which exists on non-root cgroups.
  650. The following entries are defined. Unless specified
  651. otherwise, a value change in this file generates a file
  652. modified event.
  653. populated
  654. 1 if the cgroup or its descendants contains any live
  655. processes; otherwise, 0.
  656. cgroup.max.descendants
  657. A read-write single value files. The default is "max".
  658. Maximum allowed number of descent cgroups.
  659. If the actual number of descendants is equal or larger,
  660. an attempt to create a new cgroup in the hierarchy will fail.
  661. cgroup.max.depth
  662. A read-write single value files. The default is "max".
  663. Maximum allowed descent depth below the current cgroup.
  664. If the actual descent depth is equal or larger,
  665. an attempt to create a new child cgroup will fail.
  666. cgroup.stat
  667. A read-only flat-keyed file with the following entries:
  668. nr_descendants
  669. Total number of visible descendant cgroups.
  670. nr_dying_descendants
  671. Total number of dying descendant cgroups. A cgroup becomes
  672. dying after being deleted by a user. The cgroup will remain
  673. in dying state for some time undefined time (which can depend
  674. on system load) before being completely destroyed.
  675. A process can't enter a dying cgroup under any circumstances,
  676. a dying cgroup can't revive.
  677. A dying cgroup can consume system resources not exceeding
  678. limits, which were active at the moment of cgroup deletion.
  679. Controllers
  680. ===========
  681. CPU
  682. ---
  683. The "cpu" controllers regulates distribution of CPU cycles. This
  684. controller implements weight and absolute bandwidth limit models for
  685. normal scheduling policy and absolute bandwidth allocation model for
  686. realtime scheduling policy.
  687. WARNING: cgroup2 doesn't yet support control of realtime processes and
  688. the cpu controller can only be enabled when all RT processes are in
  689. the root cgroup. Be aware that system management software may already
  690. have placed RT processes into nonroot cgroups during the system boot
  691. process, and these processes may need to be moved to the root cgroup
  692. before the cpu controller can be enabled.
  693. CPU Interface Files
  694. ~~~~~~~~~~~~~~~~~~~
  695. All time durations are in microseconds.
  696. cpu.stat
  697. A read-only flat-keyed file which exists on non-root cgroups.
  698. This file exists whether the controller is enabled or not.
  699. It always reports the following three stats:
  700. - usage_usec
  701. - user_usec
  702. - system_usec
  703. and the following three when the controller is enabled:
  704. - nr_periods
  705. - nr_throttled
  706. - throttled_usec
  707. cpu.weight
  708. A read-write single value file which exists on non-root
  709. cgroups. The default is "100".
  710. The weight in the range [1, 10000].
  711. cpu.weight.nice
  712. A read-write single value file which exists on non-root
  713. cgroups. The default is "0".
  714. The nice value is in the range [-20, 19].
  715. This interface file is an alternative interface for
  716. "cpu.weight" and allows reading and setting weight using the
  717. same values used by nice(2). Because the range is smaller and
  718. granularity is coarser for the nice values, the read value is
  719. the closest approximation of the current weight.
  720. cpu.max
  721. A read-write two value file which exists on non-root cgroups.
  722. The default is "max 100000".
  723. The maximum bandwidth limit. It's in the following format::
  724. $MAX $PERIOD
  725. which indicates that the group may consume upto $MAX in each
  726. $PERIOD duration. "max" for $MAX indicates no limit. If only
  727. one number is written, $MAX is updated.
  728. Memory
  729. ------
  730. The "memory" controller regulates distribution of memory. Memory is
  731. stateful and implements both limit and protection models. Due to the
  732. intertwining between memory usage and reclaim pressure and the
  733. stateful nature of memory, the distribution model is relatively
  734. complex.
  735. While not completely water-tight, all major memory usages by a given
  736. cgroup are tracked so that the total memory consumption can be
  737. accounted and controlled to a reasonable extent. Currently, the
  738. following types of memory usages are tracked.
  739. - Userland memory - page cache and anonymous memory.
  740. - Kernel data structures such as dentries and inodes.
  741. - TCP socket buffers.
  742. The above list may expand in the future for better coverage.
  743. Memory Interface Files
  744. ~~~~~~~~~~~~~~~~~~~~~~
  745. All memory amounts are in bytes. If a value which is not aligned to
  746. PAGE_SIZE is written, the value may be rounded up to the closest
  747. PAGE_SIZE multiple when read back.
  748. memory.current
  749. A read-only single value file which exists on non-root
  750. cgroups.
  751. The total amount of memory currently being used by the cgroup
  752. and its descendants.
  753. memory.min
  754. A read-write single value file which exists on non-root
  755. cgroups. The default is "0".
  756. Hard memory protection. If the memory usage of a cgroup
  757. is within its effective min boundary, the cgroup's memory
  758. won't be reclaimed under any conditions. If there is no
  759. unprotected reclaimable memory available, OOM killer
  760. is invoked.
  761. Effective min boundary is limited by memory.min values of
  762. all ancestor cgroups. If there is memory.min overcommitment
  763. (child cgroup or cgroups are requiring more protected memory
  764. than parent will allow), then each child cgroup will get
  765. the part of parent's protection proportional to its
  766. actual memory usage below memory.min.
  767. Putting more memory than generally available under this
  768. protection is discouraged and may lead to constant OOMs.
  769. If a memory cgroup is not populated with processes,
  770. its memory.min is ignored.
  771. memory.low
  772. A read-write single value file which exists on non-root
  773. cgroups. The default is "0".
  774. Best-effort memory protection. If the memory usage of a
  775. cgroup is within its effective low boundary, the cgroup's
  776. memory won't be reclaimed unless memory can be reclaimed
  777. from unprotected cgroups.
  778. Effective low boundary is limited by memory.low values of
  779. all ancestor cgroups. If there is memory.low overcommitment
  780. (child cgroup or cgroups are requiring more protected memory
  781. than parent will allow), then each child cgroup will get
  782. the part of parent's protection proportional to its
  783. actual memory usage below memory.low.
  784. Putting more memory than generally available under this
  785. protection is discouraged.
  786. memory.high
  787. A read-write single value file which exists on non-root
  788. cgroups. The default is "max".
  789. Memory usage throttle limit. This is the main mechanism to
  790. control memory usage of a cgroup. If a cgroup's usage goes
  791. over the high boundary, the processes of the cgroup are
  792. throttled and put under heavy reclaim pressure.
  793. Going over the high limit never invokes the OOM killer and
  794. under extreme conditions the limit may be breached.
  795. memory.max
  796. A read-write single value file which exists on non-root
  797. cgroups. The default is "max".
  798. Memory usage hard limit. This is the final protection
  799. mechanism. If a cgroup's memory usage reaches this limit and
  800. can't be reduced, the OOM killer is invoked in the cgroup.
  801. Under certain circumstances, the usage may go over the limit
  802. temporarily.
  803. This is the ultimate protection mechanism. As long as the
  804. high limit is used and monitored properly, this limit's
  805. utility is limited to providing the final safety net.
  806. memory.oom.group
  807. A read-write single value file which exists on non-root
  808. cgroups. The default value is "0".
  809. Determines whether the cgroup should be treated as
  810. an indivisible workload by the OOM killer. If set,
  811. all tasks belonging to the cgroup or to its descendants
  812. (if the memory cgroup is not a leaf cgroup) are killed
  813. together or not at all. This can be used to avoid
  814. partial kills to guarantee workload integrity.
  815. Tasks with the OOM protection (oom_score_adj set to -1000)
  816. are treated as an exception and are never killed.
  817. If the OOM killer is invoked in a cgroup, it's not going
  818. to kill any tasks outside of this cgroup, regardless
  819. memory.oom.group values of ancestor cgroups.
  820. memory.events
  821. A read-only flat-keyed file which exists on non-root cgroups.
  822. The following entries are defined. Unless specified
  823. otherwise, a value change in this file generates a file
  824. modified event.
  825. low
  826. The number of times the cgroup is reclaimed due to
  827. high memory pressure even though its usage is under
  828. the low boundary. This usually indicates that the low
  829. boundary is over-committed.
  830. high
  831. The number of times processes of the cgroup are
  832. throttled and routed to perform direct memory reclaim
  833. because the high memory boundary was exceeded. For a
  834. cgroup whose memory usage is capped by the high limit
  835. rather than global memory pressure, this event's
  836. occurrences are expected.
  837. max
  838. The number of times the cgroup's memory usage was
  839. about to go over the max boundary. If direct reclaim
  840. fails to bring it down, the cgroup goes to OOM state.
  841. oom
  842. The number of time the cgroup's memory usage was
  843. reached the limit and allocation was about to fail.
  844. Depending on context result could be invocation of OOM
  845. killer and retrying allocation or failing allocation.
  846. Failed allocation in its turn could be returned into
  847. userspace as -ENOMEM or silently ignored in cases like
  848. disk readahead. For now OOM in memory cgroup kills
  849. tasks iff shortage has happened inside page fault.
  850. oom_kill
  851. The number of processes belonging to this cgroup
  852. killed by any kind of OOM killer.
  853. memory.stat
  854. A read-only flat-keyed file which exists on non-root cgroups.
  855. This breaks down the cgroup's memory footprint into different
  856. types of memory, type-specific details, and other information
  857. on the state and past events of the memory management system.
  858. All memory amounts are in bytes.
  859. The entries are ordered to be human readable, and new entries
  860. can show up in the middle. Don't rely on items remaining in a
  861. fixed position; use the keys to look up specific values!
  862. anon
  863. Amount of memory used in anonymous mappings such as
  864. brk(), sbrk(), and mmap(MAP_ANONYMOUS)
  865. file
  866. Amount of memory used to cache filesystem data,
  867. including tmpfs and shared memory.
  868. kernel_stack
  869. Amount of memory allocated to kernel stacks.
  870. slab
  871. Amount of memory used for storing in-kernel data
  872. structures.
  873. sock
  874. Amount of memory used in network transmission buffers
  875. shmem
  876. Amount of cached filesystem data that is swap-backed,
  877. such as tmpfs, shm segments, shared anonymous mmap()s
  878. file_mapped
  879. Amount of cached filesystem data mapped with mmap()
  880. file_dirty
  881. Amount of cached filesystem data that was modified but
  882. not yet written back to disk
  883. file_writeback
  884. Amount of cached filesystem data that was modified and
  885. is currently being written back to disk
  886. inactive_anon, active_anon, inactive_file, active_file, unevictable
  887. Amount of memory, swap-backed and filesystem-backed,
  888. on the internal memory management lists used by the
  889. page reclaim algorithm
  890. slab_reclaimable
  891. Part of "slab" that might be reclaimed, such as
  892. dentries and inodes.
  893. slab_unreclaimable
  894. Part of "slab" that cannot be reclaimed on memory
  895. pressure.
  896. pgfault
  897. Total number of page faults incurred
  898. pgmajfault
  899. Number of major page faults incurred
  900. workingset_refault
  901. Number of refaults of previously evicted pages
  902. workingset_activate
  903. Number of refaulted pages that were immediately activated
  904. workingset_nodereclaim
  905. Number of times a shadow node has been reclaimed
  906. pgrefill
  907. Amount of scanned pages (in an active LRU list)
  908. pgscan
  909. Amount of scanned pages (in an inactive LRU list)
  910. pgsteal
  911. Amount of reclaimed pages
  912. pgactivate
  913. Amount of pages moved to the active LRU list
  914. pgdeactivate
  915. Amount of pages moved to the inactive LRU lis
  916. pglazyfree
  917. Amount of pages postponed to be freed under memory pressure
  918. pglazyfreed
  919. Amount of reclaimed lazyfree pages
  920. memory.swap.current
  921. A read-only single value file which exists on non-root
  922. cgroups.
  923. The total amount of swap currently being used by the cgroup
  924. and its descendants.
  925. memory.swap.max
  926. A read-write single value file which exists on non-root
  927. cgroups. The default is "max".
  928. Swap usage hard limit. If a cgroup's swap usage reaches this
  929. limit, anonymous memory of the cgroup will not be swapped out.
  930. memory.swap.events
  931. A read-only flat-keyed file which exists on non-root cgroups.
  932. The following entries are defined. Unless specified
  933. otherwise, a value change in this file generates a file
  934. modified event.
  935. max
  936. The number of times the cgroup's swap usage was about
  937. to go over the max boundary and swap allocation
  938. failed.
  939. fail
  940. The number of times swap allocation failed either
  941. because of running out of swap system-wide or max
  942. limit.
  943. When reduced under the current usage, the existing swap
  944. entries are reclaimed gradually and the swap usage may stay
  945. higher than the limit for an extended period of time. This
  946. reduces the impact on the workload and memory management.
  947. Usage Guidelines
  948. ~~~~~~~~~~~~~~~~
  949. "memory.high" is the main mechanism to control memory usage.
  950. Over-committing on high limit (sum of high limits > available memory)
  951. and letting global memory pressure to distribute memory according to
  952. usage is a viable strategy.
  953. Because breach of the high limit doesn't trigger the OOM killer but
  954. throttles the offending cgroup, a management agent has ample
  955. opportunities to monitor and take appropriate actions such as granting
  956. more memory or terminating the workload.
  957. Determining whether a cgroup has enough memory is not trivial as
  958. memory usage doesn't indicate whether the workload can benefit from
  959. more memory. For example, a workload which writes data received from
  960. network to a file can use all available memory but can also operate as
  961. performant with a small amount of memory. A measure of memory
  962. pressure - how much the workload is being impacted due to lack of
  963. memory - is necessary to determine whether a workload needs more
  964. memory; unfortunately, memory pressure monitoring mechanism isn't
  965. implemented yet.
  966. Memory Ownership
  967. ~~~~~~~~~~~~~~~~
  968. A memory area is charged to the cgroup which instantiated it and stays
  969. charged to the cgroup until the area is released. Migrating a process
  970. to a different cgroup doesn't move the memory usages that it
  971. instantiated while in the previous cgroup to the new cgroup.
  972. A memory area may be used by processes belonging to different cgroups.
  973. To which cgroup the area will be charged is in-deterministic; however,
  974. over time, the memory area is likely to end up in a cgroup which has
  975. enough memory allowance to avoid high reclaim pressure.
  976. If a cgroup sweeps a considerable amount of memory which is expected
  977. to be accessed repeatedly by other cgroups, it may make sense to use
  978. POSIX_FADV_DONTNEED to relinquish the ownership of memory areas
  979. belonging to the affected files to ensure correct memory ownership.
  980. IO
  981. --
  982. The "io" controller regulates the distribution of IO resources. This
  983. controller implements both weight based and absolute bandwidth or IOPS
  984. limit distribution; however, weight based distribution is available
  985. only if cfq-iosched is in use and neither scheme is available for
  986. blk-mq devices.
  987. IO Interface Files
  988. ~~~~~~~~~~~~~~~~~~
  989. io.stat
  990. A read-only nested-keyed file which exists on non-root
  991. cgroups.
  992. Lines are keyed by $MAJ:$MIN device numbers and not ordered.
  993. The following nested keys are defined.
  994. ====== =====================
  995. rbytes Bytes read
  996. wbytes Bytes written
  997. rios Number of read IOs
  998. wios Number of write IOs
  999. dbytes Bytes discarded
  1000. dios Number of discard IOs
  1001. ====== =====================
  1002. An example read output follows:
  1003. 8:16 rbytes=1459200 wbytes=314773504 rios=192 wios=353 dbytes=0 dios=0
  1004. 8:0 rbytes=90430464 wbytes=299008000 rios=8950 wios=1252 dbytes=50331648 dios=3021
  1005. io.weight
  1006. A read-write flat-keyed file which exists on non-root cgroups.
  1007. The default is "default 100".
  1008. The first line is the default weight applied to devices
  1009. without specific override. The rest are overrides keyed by
  1010. $MAJ:$MIN device numbers and not ordered. The weights are in
  1011. the range [1, 10000] and specifies the relative amount IO time
  1012. the cgroup can use in relation to its siblings.
  1013. The default weight can be updated by writing either "default
  1014. $WEIGHT" or simply "$WEIGHT". Overrides can be set by writing
  1015. "$MAJ:$MIN $WEIGHT" and unset by writing "$MAJ:$MIN default".
  1016. An example read output follows::
  1017. default 100
  1018. 8:16 200
  1019. 8:0 50
  1020. io.max
  1021. A read-write nested-keyed file which exists on non-root
  1022. cgroups.
  1023. BPS and IOPS based IO limit. Lines are keyed by $MAJ:$MIN
  1024. device numbers and not ordered. The following nested keys are
  1025. defined.
  1026. ===== ==================================
  1027. rbps Max read bytes per second
  1028. wbps Max write bytes per second
  1029. riops Max read IO operations per second
  1030. wiops Max write IO operations per second
  1031. ===== ==================================
  1032. When writing, any number of nested key-value pairs can be
  1033. specified in any order. "max" can be specified as the value
  1034. to remove a specific limit. If the same key is specified
  1035. multiple times, the outcome is undefined.
  1036. BPS and IOPS are measured in each IO direction and IOs are
  1037. delayed if limit is reached. Temporary bursts are allowed.
  1038. Setting read limit at 2M BPS and write at 120 IOPS for 8:16::
  1039. echo "8:16 rbps=2097152 wiops=120" > io.max
  1040. Reading returns the following::
  1041. 8:16 rbps=2097152 wbps=max riops=max wiops=120
  1042. Write IOPS limit can be removed by writing the following::
  1043. echo "8:16 wiops=max" > io.max
  1044. Reading now returns the following::
  1045. 8:16 rbps=2097152 wbps=max riops=max wiops=max
  1046. Writeback
  1047. ~~~~~~~~~
  1048. Page cache is dirtied through buffered writes and shared mmaps and
  1049. written asynchronously to the backing filesystem by the writeback
  1050. mechanism. Writeback sits between the memory and IO domains and
  1051. regulates the proportion of dirty memory by balancing dirtying and
  1052. write IOs.
  1053. The io controller, in conjunction with the memory controller,
  1054. implements control of page cache writeback IOs. The memory controller
  1055. defines the memory domain that dirty memory ratio is calculated and
  1056. maintained for and the io controller defines the io domain which
  1057. writes out dirty pages for the memory domain. Both system-wide and
  1058. per-cgroup dirty memory states are examined and the more restrictive
  1059. of the two is enforced.
  1060. cgroup writeback requires explicit support from the underlying
  1061. filesystem. Currently, cgroup writeback is implemented on ext2, ext4
  1062. and btrfs. On other filesystems, all writeback IOs are attributed to
  1063. the root cgroup.
  1064. There are inherent differences in memory and writeback management
  1065. which affects how cgroup ownership is tracked. Memory is tracked per
  1066. page while writeback per inode. For the purpose of writeback, an
  1067. inode is assigned to a cgroup and all IO requests to write dirty pages
  1068. from the inode are attributed to that cgroup.
  1069. As cgroup ownership for memory is tracked per page, there can be pages
  1070. which are associated with different cgroups than the one the inode is
  1071. associated with. These are called foreign pages. The writeback
  1072. constantly keeps track of foreign pages and, if a particular foreign
  1073. cgroup becomes the majority over a certain period of time, switches
  1074. the ownership of the inode to that cgroup.
  1075. While this model is enough for most use cases where a given inode is
  1076. mostly dirtied by a single cgroup even when the main writing cgroup
  1077. changes over time, use cases where multiple cgroups write to a single
  1078. inode simultaneously are not supported well. In such circumstances, a
  1079. significant portion of IOs are likely to be attributed incorrectly.
  1080. As memory controller assigns page ownership on the first use and
  1081. doesn't update it until the page is released, even if writeback
  1082. strictly follows page ownership, multiple cgroups dirtying overlapping
  1083. areas wouldn't work as expected. It's recommended to avoid such usage
  1084. patterns.
  1085. The sysctl knobs which affect writeback behavior are applied to cgroup
  1086. writeback as follows.
  1087. vm.dirty_background_ratio, vm.dirty_ratio
  1088. These ratios apply the same to cgroup writeback with the
  1089. amount of available memory capped by limits imposed by the
  1090. memory controller and system-wide clean memory.
  1091. vm.dirty_background_bytes, vm.dirty_bytes
  1092. For cgroup writeback, this is calculated into ratio against
  1093. total available memory and applied the same way as
  1094. vm.dirty[_background]_ratio.
  1095. IO Latency
  1096. ~~~~~~~~~~
  1097. This is a cgroup v2 controller for IO workload protection. You provide a group
  1098. with a latency target, and if the average latency exceeds that target the
  1099. controller will throttle any peers that have a lower latency target than the
  1100. protected workload.
  1101. The limits are only applied at the peer level in the hierarchy. This means that
  1102. in the diagram below, only groups A, B, and C will influence each other, and
  1103. groups D and F will influence each other. Group G will influence nobody.
  1104. [root]
  1105. / | \
  1106. A B C
  1107. / \ |
  1108. D F G
  1109. So the ideal way to configure this is to set io.latency in groups A, B, and C.
  1110. Generally you do not want to set a value lower than the latency your device
  1111. supports. Experiment to find the value that works best for your workload.
  1112. Start at higher than the expected latency for your device and watch the
  1113. avg_lat value in io.stat for your workload group to get an idea of the
  1114. latency you see during normal operation. Use the avg_lat value as a basis for
  1115. your real setting, setting at 10-15% higher than the value in io.stat.
  1116. How IO Latency Throttling Works
  1117. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1118. io.latency is work conserving; so as long as everybody is meeting their latency
  1119. target the controller doesn't do anything. Once a group starts missing its
  1120. target it begins throttling any peer group that has a higher target than itself.
  1121. This throttling takes 2 forms:
  1122. - Queue depth throttling. This is the number of outstanding IO's a group is
  1123. allowed to have. We will clamp down relatively quickly, starting at no limit
  1124. and going all the way down to 1 IO at a time.
  1125. - Artificial delay induction. There are certain types of IO that cannot be
  1126. throttled without possibly adversely affecting higher priority groups. This
  1127. includes swapping and metadata IO. These types of IO are allowed to occur
  1128. normally, however they are "charged" to the originating group. If the
  1129. originating group is being throttled you will see the use_delay and delay
  1130. fields in io.stat increase. The delay value is how many microseconds that are
  1131. being added to any process that runs in this group. Because this number can
  1132. grow quite large if there is a lot of swapping or metadata IO occurring we
  1133. limit the individual delay events to 1 second at a time.
  1134. Once the victimized group starts meeting its latency target again it will start
  1135. unthrottling any peer groups that were throttled previously. If the victimized
  1136. group simply stops doing IO the global counter will unthrottle appropriately.
  1137. IO Latency Interface Files
  1138. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  1139. io.latency
  1140. This takes a similar format as the other controllers.
  1141. "MAJOR:MINOR target=<target time in microseconds"
  1142. io.stat
  1143. If the controller is enabled you will see extra stats in io.stat in
  1144. addition to the normal ones.
  1145. depth
  1146. This is the current queue depth for the group.
  1147. avg_lat
  1148. This is an exponential moving average with a decay rate of 1/exp
  1149. bound by the sampling interval. The decay rate interval can be
  1150. calculated by multiplying the win value in io.stat by the
  1151. corresponding number of samples based on the win value.
  1152. win
  1153. The sampling window size in milliseconds. This is the minimum
  1154. duration of time between evaluation events. Windows only elapse
  1155. with IO activity. Idle periods extend the most recent window.
  1156. PID
  1157. ---
  1158. The process number controller is used to allow a cgroup to stop any
  1159. new tasks from being fork()'d or clone()'d after a specified limit is
  1160. reached.
  1161. The number of tasks in a cgroup can be exhausted in ways which other
  1162. controllers cannot prevent, thus warranting its own controller. For
  1163. example, a fork bomb is likely to exhaust the number of tasks before
  1164. hitting memory restrictions.
  1165. Note that PIDs used in this controller refer to TIDs, process IDs as
  1166. used by the kernel.
  1167. PID Interface Files
  1168. ~~~~~~~~~~~~~~~~~~~
  1169. pids.max
  1170. A read-write single value file which exists on non-root
  1171. cgroups. The default is "max".
  1172. Hard limit of number of processes.
  1173. pids.current
  1174. A read-only single value file which exists on all cgroups.
  1175. The number of processes currently in the cgroup and its
  1176. descendants.
  1177. Organisational operations are not blocked by cgroup policies, so it is
  1178. possible to have pids.current > pids.max. This can be done by either
  1179. setting the limit to be smaller than pids.current, or attaching enough
  1180. processes to the cgroup such that pids.current is larger than
  1181. pids.max. However, it is not possible to violate a cgroup PID policy
  1182. through fork() or clone(). These will return -EAGAIN if the creation
  1183. of a new process would cause a cgroup policy to be violated.
  1184. Device controller
  1185. -----------------
  1186. Device controller manages access to device files. It includes both
  1187. creation of new device files (using mknod), and access to the
  1188. existing device files.
  1189. Cgroup v2 device controller has no interface files and is implemented
  1190. on top of cgroup BPF. To control access to device files, a user may
  1191. create bpf programs of the BPF_CGROUP_DEVICE type and attach them
  1192. to cgroups. On an attempt to access a device file, corresponding
  1193. BPF programs will be executed, and depending on the return value
  1194. the attempt will succeed or fail with -EPERM.
  1195. A BPF_CGROUP_DEVICE program takes a pointer to the bpf_cgroup_dev_ctx
  1196. structure, which describes the device access attempt: access type
  1197. (mknod/read/write) and device (type, major and minor numbers).
  1198. If the program returns 0, the attempt fails with -EPERM, otherwise
  1199. it succeeds.
  1200. An example of BPF_CGROUP_DEVICE program may be found in the kernel
  1201. source tree in the tools/testing/selftests/bpf/dev_cgroup.c file.
  1202. RDMA
  1203. ----
  1204. The "rdma" controller regulates the distribution and accounting of
  1205. of RDMA resources.
  1206. RDMA Interface Files
  1207. ~~~~~~~~~~~~~~~~~~~~
  1208. rdma.max
  1209. A readwrite nested-keyed file that exists for all the cgroups
  1210. except root that describes current configured resource limit
  1211. for a RDMA/IB device.
  1212. Lines are keyed by device name and are not ordered.
  1213. Each line contains space separated resource name and its configured
  1214. limit that can be distributed.
  1215. The following nested keys are defined.
  1216. ========== =============================
  1217. hca_handle Maximum number of HCA Handles
  1218. hca_object Maximum number of HCA Objects
  1219. ========== =============================
  1220. An example for mlx4 and ocrdma device follows::
  1221. mlx4_0 hca_handle=2 hca_object=2000
  1222. ocrdma1 hca_handle=3 hca_object=max
  1223. rdma.current
  1224. A read-only file that describes current resource usage.
  1225. It exists for all the cgroup except root.
  1226. An example for mlx4 and ocrdma device follows::
  1227. mlx4_0 hca_handle=1 hca_object=20
  1228. ocrdma1 hca_handle=1 hca_object=23
  1229. Misc
  1230. ----
  1231. perf_event
  1232. ~~~~~~~~~~
  1233. perf_event controller, if not mounted on a legacy hierarchy, is
  1234. automatically enabled on the v2 hierarchy so that perf events can
  1235. always be filtered by cgroup v2 path. The controller can still be
  1236. moved to a legacy hierarchy after v2 hierarchy is populated.
  1237. Non-normative information
  1238. -------------------------
  1239. This section contains information that isn't considered to be a part of
  1240. the stable kernel API and so is subject to change.
  1241. CPU controller root cgroup process behaviour
  1242. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1243. When distributing CPU cycles in the root cgroup each thread in this
  1244. cgroup is treated as if it was hosted in a separate child cgroup of the
  1245. root cgroup. This child cgroup weight is dependent on its thread nice
  1246. level.
  1247. For details of this mapping see sched_prio_to_weight array in
  1248. kernel/sched/core.c file (values from this array should be scaled
  1249. appropriately so the neutral - nice 0 - value is 100 instead of 1024).
  1250. IO controller root cgroup process behaviour
  1251. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1252. Root cgroup processes are hosted in an implicit leaf child node.
  1253. When distributing IO resources this implicit child node is taken into
  1254. account as if it was a normal child cgroup of the root cgroup with a
  1255. weight value of 200.
  1256. Namespace
  1257. =========
  1258. Basics
  1259. ------
  1260. cgroup namespace provides a mechanism to virtualize the view of the
  1261. "/proc/$PID/cgroup" file and cgroup mounts. The CLONE_NEWCGROUP clone
  1262. flag can be used with clone(2) and unshare(2) to create a new cgroup
  1263. namespace. The process running inside the cgroup namespace will have
  1264. its "/proc/$PID/cgroup" output restricted to cgroupns root. The
  1265. cgroupns root is the cgroup of the process at the time of creation of
  1266. the cgroup namespace.
  1267. Without cgroup namespace, the "/proc/$PID/cgroup" file shows the
  1268. complete path of the cgroup of a process. In a container setup where
  1269. a set of cgroups and namespaces are intended to isolate processes the
  1270. "/proc/$PID/cgroup" file may leak potential system level information
  1271. to the isolated processes. For Example::
  1272. # cat /proc/self/cgroup
  1273. 0::/batchjobs/container_id1
  1274. The path '/batchjobs/container_id1' can be considered as system-data
  1275. and undesirable to expose to the isolated processes. cgroup namespace
  1276. can be used to restrict visibility of this path. For example, before
  1277. creating a cgroup namespace, one would see::
  1278. # ls -l /proc/self/ns/cgroup
  1279. lrwxrwxrwx 1 root root 0 2014-07-15 10:37 /proc/self/ns/cgroup -> cgroup:[4026531835]
  1280. # cat /proc/self/cgroup
  1281. 0::/batchjobs/container_id1
  1282. After unsharing a new namespace, the view changes::
  1283. # ls -l /proc/self/ns/cgroup
  1284. lrwxrwxrwx 1 root root 0 2014-07-15 10:35 /proc/self/ns/cgroup -> cgroup:[4026532183]
  1285. # cat /proc/self/cgroup
  1286. 0::/
  1287. When some thread from a multi-threaded process unshares its cgroup
  1288. namespace, the new cgroupns gets applied to the entire process (all
  1289. the threads). This is natural for the v2 hierarchy; however, for the
  1290. legacy hierarchies, this may be unexpected.
  1291. A cgroup namespace is alive as long as there are processes inside or
  1292. mounts pinning it. When the last usage goes away, the cgroup
  1293. namespace is destroyed. The cgroupns root and the actual cgroups
  1294. remain.
  1295. The Root and Views
  1296. ------------------
  1297. The 'cgroupns root' for a cgroup namespace is the cgroup in which the
  1298. process calling unshare(2) is running. For example, if a process in
  1299. /batchjobs/container_id1 cgroup calls unshare, cgroup
  1300. /batchjobs/container_id1 becomes the cgroupns root. For the
  1301. init_cgroup_ns, this is the real root ('/') cgroup.
  1302. The cgroupns root cgroup does not change even if the namespace creator
  1303. process later moves to a different cgroup::
  1304. # ~/unshare -c # unshare cgroupns in some cgroup
  1305. # cat /proc/self/cgroup
  1306. 0::/
  1307. # mkdir sub_cgrp_1
  1308. # echo 0 > sub_cgrp_1/cgroup.procs
  1309. # cat /proc/self/cgroup
  1310. 0::/sub_cgrp_1
  1311. Each process gets its namespace-specific view of "/proc/$PID/cgroup"
  1312. Processes running inside the cgroup namespace will be able to see
  1313. cgroup paths (in /proc/self/cgroup) only inside their root cgroup.
  1314. From within an unshared cgroupns::
  1315. # sleep 100000 &
  1316. [1] 7353
  1317. # echo 7353 > sub_cgrp_1/cgroup.procs
  1318. # cat /proc/7353/cgroup
  1319. 0::/sub_cgrp_1
  1320. From the initial cgroup namespace, the real cgroup path will be
  1321. visible::
  1322. $ cat /proc/7353/cgroup
  1323. 0::/batchjobs/container_id1/sub_cgrp_1
  1324. From a sibling cgroup namespace (that is, a namespace rooted at a
  1325. different cgroup), the cgroup path relative to its own cgroup
  1326. namespace root will be shown. For instance, if PID 7353's cgroup
  1327. namespace root is at '/batchjobs/container_id2', then it will see::
  1328. # cat /proc/7353/cgroup
  1329. 0::/../container_id2/sub_cgrp_1
  1330. Note that the relative path always starts with '/' to indicate that
  1331. its relative to the cgroup namespace root of the caller.
  1332. Migration and setns(2)
  1333. ----------------------
  1334. Processes inside a cgroup namespace can move into and out of the
  1335. namespace root if they have proper access to external cgroups. For
  1336. example, from inside a namespace with cgroupns root at
  1337. /batchjobs/container_id1, and assuming that the global hierarchy is
  1338. still accessible inside cgroupns::
  1339. # cat /proc/7353/cgroup
  1340. 0::/sub_cgrp_1
  1341. # echo 7353 > batchjobs/container_id2/cgroup.procs
  1342. # cat /proc/7353/cgroup
  1343. 0::/../container_id2
  1344. Note that this kind of setup is not encouraged. A task inside cgroup
  1345. namespace should only be exposed to its own cgroupns hierarchy.
  1346. setns(2) to another cgroup namespace is allowed when:
  1347. (a) the process has CAP_SYS_ADMIN against its current user namespace
  1348. (b) the process has CAP_SYS_ADMIN against the target cgroup
  1349. namespace's userns
  1350. No implicit cgroup changes happen with attaching to another cgroup
  1351. namespace. It is expected that the someone moves the attaching
  1352. process under the target cgroup namespace root.
  1353. Interaction with Other Namespaces
  1354. ---------------------------------
  1355. Namespace specific cgroup hierarchy can be mounted by a process
  1356. running inside a non-init cgroup namespace::
  1357. # mount -t cgroup2 none $MOUNT_POINT
  1358. This will mount the unified cgroup hierarchy with cgroupns root as the
  1359. filesystem root. The process needs CAP_SYS_ADMIN against its user and
  1360. mount namespaces.
  1361. The virtualization of /proc/self/cgroup file combined with restricting
  1362. the view of cgroup hierarchy by namespace-private cgroupfs mount
  1363. provides a properly isolated cgroup view inside the container.
  1364. Information on Kernel Programming
  1365. =================================
  1366. This section contains kernel programming information in the areas
  1367. where interacting with cgroup is necessary. cgroup core and
  1368. controllers are not covered.
  1369. Filesystem Support for Writeback
  1370. --------------------------------
  1371. A filesystem can support cgroup writeback by updating
  1372. address_space_operations->writepage[s]() to annotate bio's using the
  1373. following two functions.
  1374. wbc_init_bio(@wbc, @bio)
  1375. Should be called for each bio carrying writeback data and
  1376. associates the bio with the inode's owner cgroup. Can be
  1377. called anytime between bio allocation and submission.
  1378. wbc_account_io(@wbc, @page, @bytes)
  1379. Should be called for each data segment being written out.
  1380. While this function doesn't care exactly when it's called
  1381. during the writeback session, it's the easiest and most
  1382. natural to call it as data segments are added to a bio.
  1383. With writeback bio's annotated, cgroup support can be enabled per
  1384. super_block by setting SB_I_CGROUPWB in ->s_iflags. This allows for
  1385. selective disabling of cgroup writeback support which is helpful when
  1386. certain filesystem features, e.g. journaled data mode, are
  1387. incompatible.
  1388. wbc_init_bio() binds the specified bio to its cgroup. Depending on
  1389. the configuration, the bio may be executed at a lower priority and if
  1390. the writeback session is holding shared resources, e.g. a journal
  1391. entry, may lead to priority inversion. There is no one easy solution
  1392. for the problem. Filesystems can try to work around specific problem
  1393. cases by skipping wbc_init_bio() or using bio_associate_blkcg()
  1394. directly.
  1395. Deprecated v1 Core Features
  1396. ===========================
  1397. - Multiple hierarchies including named ones are not supported.
  1398. - All v1 mount options are not supported.
  1399. - The "tasks" file is removed and "cgroup.procs" is not sorted.
  1400. - "cgroup.clone_children" is removed.
  1401. - /proc/cgroups is meaningless for v2. Use "cgroup.controllers" file
  1402. at the root instead.
  1403. Issues with v1 and Rationales for v2
  1404. ====================================
  1405. Multiple Hierarchies
  1406. --------------------
  1407. cgroup v1 allowed an arbitrary number of hierarchies and each
  1408. hierarchy could host any number of controllers. While this seemed to
  1409. provide a high level of flexibility, it wasn't useful in practice.
  1410. For example, as there is only one instance of each controller, utility
  1411. type controllers such as freezer which can be useful in all
  1412. hierarchies could only be used in one. The issue is exacerbated by
  1413. the fact that controllers couldn't be moved to another hierarchy once
  1414. hierarchies were populated. Another issue was that all controllers
  1415. bound to a hierarchy were forced to have exactly the same view of the
  1416. hierarchy. It wasn't possible to vary the granularity depending on
  1417. the specific controller.
  1418. In practice, these issues heavily limited which controllers could be
  1419. put on the same hierarchy and most configurations resorted to putting
  1420. each controller on its own hierarchy. Only closely related ones, such
  1421. as the cpu and cpuacct controllers, made sense to be put on the same
  1422. hierarchy. This often meant that userland ended up managing multiple
  1423. similar hierarchies repeating the same steps on each hierarchy
  1424. whenever a hierarchy management operation was necessary.
  1425. Furthermore, support for multiple hierarchies came at a steep cost.
  1426. It greatly complicated cgroup core implementation but more importantly
  1427. the support for multiple hierarchies restricted how cgroup could be
  1428. used in general and what controllers was able to do.
  1429. There was no limit on how many hierarchies there might be, which meant
  1430. that a thread's cgroup membership couldn't be described in finite
  1431. length. The key might contain any number of entries and was unlimited
  1432. in length, which made it highly awkward to manipulate and led to
  1433. addition of controllers which existed only to identify membership,
  1434. which in turn exacerbated the original problem of proliferating number
  1435. of hierarchies.
  1436. Also, as a controller couldn't have any expectation regarding the
  1437. topologies of hierarchies other controllers might be on, each
  1438. controller had to assume that all other controllers were attached to
  1439. completely orthogonal hierarchies. This made it impossible, or at
  1440. least very cumbersome, for controllers to cooperate with each other.
  1441. In most use cases, putting controllers on hierarchies which are
  1442. completely orthogonal to each other isn't necessary. What usually is
  1443. called for is the ability to have differing levels of granularity
  1444. depending on the specific controller. In other words, hierarchy may
  1445. be collapsed from leaf towards root when viewed from specific
  1446. controllers. For example, a given configuration might not care about
  1447. how memory is distributed beyond a certain level while still wanting
  1448. to control how CPU cycles are distributed.
  1449. Thread Granularity
  1450. ------------------
  1451. cgroup v1 allowed threads of a process to belong to different cgroups.
  1452. This didn't make sense for some controllers and those controllers
  1453. ended up implementing different ways to ignore such situations but
  1454. much more importantly it blurred the line between API exposed to
  1455. individual applications and system management interface.
  1456. Generally, in-process knowledge is available only to the process
  1457. itself; thus, unlike service-level organization of processes,
  1458. categorizing threads of a process requires active participation from
  1459. the application which owns the target process.
  1460. cgroup v1 had an ambiguously defined delegation model which got abused
  1461. in combination with thread granularity. cgroups were delegated to
  1462. individual applications so that they can create and manage their own
  1463. sub-hierarchies and control resource distributions along them. This
  1464. effectively raised cgroup to the status of a syscall-like API exposed
  1465. to lay programs.
  1466. First of all, cgroup has a fundamentally inadequate interface to be
  1467. exposed this way. For a process to access its own knobs, it has to
  1468. extract the path on the target hierarchy from /proc/self/cgroup,
  1469. construct the path by appending the name of the knob to the path, open
  1470. and then read and/or write to it. This is not only extremely clunky
  1471. and unusual but also inherently racy. There is no conventional way to
  1472. define transaction across the required steps and nothing can guarantee
  1473. that the process would actually be operating on its own sub-hierarchy.
  1474. cgroup controllers implemented a number of knobs which would never be
  1475. accepted as public APIs because they were just adding control knobs to
  1476. system-management pseudo filesystem. cgroup ended up with interface
  1477. knobs which were not properly abstracted or refined and directly
  1478. revealed kernel internal details. These knobs got exposed to
  1479. individual applications through the ill-defined delegation mechanism
  1480. effectively abusing cgroup as a shortcut to implementing public APIs
  1481. without going through the required scrutiny.
  1482. This was painful for both userland and kernel. Userland ended up with
  1483. misbehaving and poorly abstracted interfaces and kernel exposing and
  1484. locked into constructs inadvertently.
  1485. Competition Between Inner Nodes and Threads
  1486. -------------------------------------------
  1487. cgroup v1 allowed threads to be in any cgroups which created an
  1488. interesting problem where threads belonging to a parent cgroup and its
  1489. children cgroups competed for resources. This was nasty as two
  1490. different types of entities competed and there was no obvious way to
  1491. settle it. Different controllers did different things.
  1492. The cpu controller considered threads and cgroups as equivalents and
  1493. mapped nice levels to cgroup weights. This worked for some cases but
  1494. fell flat when children wanted to be allocated specific ratios of CPU
  1495. cycles and the number of internal threads fluctuated - the ratios
  1496. constantly changed as the number of competing entities fluctuated.
  1497. There also were other issues. The mapping from nice level to weight
  1498. wasn't obvious or universal, and there were various other knobs which
  1499. simply weren't available for threads.
  1500. The io controller implicitly created a hidden leaf node for each
  1501. cgroup to host the threads. The hidden leaf had its own copies of all
  1502. the knobs with ``leaf_`` prefixed. While this allowed equivalent
  1503. control over internal threads, it was with serious drawbacks. It
  1504. always added an extra layer of nesting which wouldn't be necessary
  1505. otherwise, made the interface messy and significantly complicated the
  1506. implementation.
  1507. The memory controller didn't have a way to control what happened
  1508. between internal tasks and child cgroups and the behavior was not
  1509. clearly defined. There were attempts to add ad-hoc behaviors and
  1510. knobs to tailor the behavior to specific workloads which would have
  1511. led to problems extremely difficult to resolve in the long term.
  1512. Multiple controllers struggled with internal tasks and came up with
  1513. different ways to deal with it; unfortunately, all the approaches were
  1514. severely flawed and, furthermore, the widely different behaviors
  1515. made cgroup as a whole highly inconsistent.
  1516. This clearly is a problem which needs to be addressed from cgroup core
  1517. in a uniform way.
  1518. Other Interface Issues
  1519. ----------------------
  1520. cgroup v1 grew without oversight and developed a large number of
  1521. idiosyncrasies and inconsistencies. One issue on the cgroup core side
  1522. was how an empty cgroup was notified - a userland helper binary was
  1523. forked and executed for each event. The event delivery wasn't
  1524. recursive or delegatable. The limitations of the mechanism also led
  1525. to in-kernel event delivery filtering mechanism further complicating
  1526. the interface.
  1527. Controller interfaces were problematic too. An extreme example is
  1528. controllers completely ignoring hierarchical organization and treating
  1529. all cgroups as if they were all located directly under the root
  1530. cgroup. Some controllers exposed a large amount of inconsistent
  1531. implementation details to userland.
  1532. There also was no consistency across controllers. When a new cgroup
  1533. was created, some controllers defaulted to not imposing extra
  1534. restrictions while others disallowed any resource usage until
  1535. explicitly configured. Configuration knobs for the same type of
  1536. control used widely differing naming schemes and formats. Statistics
  1537. and information knobs were named arbitrarily and used different
  1538. formats and units even in the same controller.
  1539. cgroup v2 establishes common conventions where appropriate and updates
  1540. controllers so that they expose minimal and consistent interfaces.
  1541. Controller Issues and Remedies
  1542. ------------------------------
  1543. Memory
  1544. ~~~~~~
  1545. The original lower boundary, the soft limit, is defined as a limit
  1546. that is per default unset. As a result, the set of cgroups that
  1547. global reclaim prefers is opt-in, rather than opt-out. The costs for
  1548. optimizing these mostly negative lookups are so high that the
  1549. implementation, despite its enormous size, does not even provide the
  1550. basic desirable behavior. First off, the soft limit has no
  1551. hierarchical meaning. All configured groups are organized in a global
  1552. rbtree and treated like equal peers, regardless where they are located
  1553. in the hierarchy. This makes subtree delegation impossible. Second,
  1554. the soft limit reclaim pass is so aggressive that it not just
  1555. introduces high allocation latencies into the system, but also impacts
  1556. system performance due to overreclaim, to the point where the feature
  1557. becomes self-defeating.
  1558. The memory.low boundary on the other hand is a top-down allocated
  1559. reserve. A cgroup enjoys reclaim protection when it's within its low,
  1560. which makes delegation of subtrees possible.
  1561. The original high boundary, the hard limit, is defined as a strict
  1562. limit that can not budge, even if the OOM killer has to be called.
  1563. But this generally goes against the goal of making the most out of the
  1564. available memory. The memory consumption of workloads varies during
  1565. runtime, and that requires users to overcommit. But doing that with a
  1566. strict upper limit requires either a fairly accurate prediction of the
  1567. working set size or adding slack to the limit. Since working set size
  1568. estimation is hard and error prone, and getting it wrong results in
  1569. OOM kills, most users tend to err on the side of a looser limit and
  1570. end up wasting precious resources.
  1571. The memory.high boundary on the other hand can be set much more
  1572. conservatively. When hit, it throttles allocations by forcing them
  1573. into direct reclaim to work off the excess, but it never invokes the
  1574. OOM killer. As a result, a high boundary that is chosen too
  1575. aggressively will not terminate the processes, but instead it will
  1576. lead to gradual performance degradation. The user can monitor this
  1577. and make corrections until the minimal memory footprint that still
  1578. gives acceptable performance is found.
  1579. In extreme cases, with many concurrent allocations and a complete
  1580. breakdown of reclaim progress within the group, the high boundary can
  1581. be exceeded. But even then it's mostly better to satisfy the
  1582. allocation from the slack available in other groups or the rest of the
  1583. system than killing the group. Otherwise, memory.max is there to
  1584. limit this type of spillover and ultimately contain buggy or even
  1585. malicious applications.
  1586. Setting the original memory.limit_in_bytes below the current usage was
  1587. subject to a race condition, where concurrent charges could cause the
  1588. limit setting to fail. memory.max on the other hand will first set the
  1589. limit to prevent new charges, and then reclaim and OOM kill until the
  1590. new limit is met - or the task writing to memory.max is killed.
  1591. The combined memory+swap accounting and limiting is replaced by real
  1592. control over swap space.
  1593. The main argument for a combined memory+swap facility in the original
  1594. cgroup design was that global or parental pressure would always be
  1595. able to swap all anonymous memory of a child group, regardless of the
  1596. child's own (possibly untrusted) configuration. However, untrusted
  1597. groups can sabotage swapping by other means - such as referencing its
  1598. anonymous memory in a tight loop - and an admin can not assume full
  1599. swappability when overcommitting untrusted jobs.
  1600. For trusted jobs, on the other hand, a combined counter is not an
  1601. intuitive userspace interface, and it flies in the face of the idea
  1602. that cgroup controllers should account and limit specific physical
  1603. resources. Swap space is a resource like all others in the system,
  1604. and that's why unified hierarchy allows distributing it separately.