cgroup: document cgroup_no_v1=
[linux-2.6/btrfs-unstable.git] / Documentation / cgroup-v2.txt
blob3922ae1654fd40b297d045f1b7f6fcae0a8e6924
2 Control Group v2
4 October, 2015           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/.
12 CONTENTS
14 1. Introduction
15   1-1. Terminology
16   1-2. What is cgroup?
17 2. Basic Operations
18   2-1. Mounting
19   2-2. Organizing Processes
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 P. Information on Kernel Programming
51   P-1. Filesystem Support for Writeback
52 D. Deprecated v1 Core Features
53 R. Issues with v1 and Rationales for v2
54   R-1. Multiple Hierarchies
55   R-2. Thread Granularity
56   R-3. Competition Between Inner Nodes and Threads
57   R-4. Other Interface Issues
58   R-5. Controller Issues and Remedies
59     R-5-1. Memory
62 1. Introduction
64 1-1. Terminology
66 "cgroup" stands for "control group" and is never capitalized.  The
67 singular form is used to designate the whole feature and also as a
68 qualifier as in "cgroup controllers".  When explicitly referring to
69 multiple individual control groups, the plural form "cgroups" is used.
72 1-2. What is cgroup?
74 cgroup is a mechanism to organize processes hierarchically and
75 distribute system resources along the hierarchy in a controlled and
76 configurable manner.
78 cgroup is largely composed of two parts - the core and controllers.
79 cgroup core is primarily responsible for hierarchically organizing
80 processes.  A cgroup controller is usually responsible for
81 distributing a specific type of system resource along the hierarchy
82 although there are utility controllers which serve purposes other than
83 resource distribution.
85 cgroups form a tree structure and every process in the system belongs
86 to one and only one cgroup.  All threads of a process belong to the
87 same cgroup.  On creation, all processes are put in the cgroup that
88 the parent process belongs to at the time.  A process can be migrated
89 to another cgroup.  Migration of a process doesn't affect already
90 existing descendant processes.
92 Following certain structural constraints, controllers may be enabled or
93 disabled selectively on a cgroup.  All controller behaviors are
94 hierarchical - if a controller is enabled on a cgroup, it affects all
95 processes which belong to the cgroups consisting the inclusive
96 sub-hierarchy of the cgroup.  When a controller is enabled on a nested
97 cgroup, it always restricts the resource distribution further.  The
98 restrictions set closer to the root in the hierarchy can not be
99 overridden from further away.
102 2. Basic Operations
104 2-1. Mounting
106 Unlike v1, cgroup v2 has only single hierarchy.  The cgroup v2
107 hierarchy can be mounted with the following mount command.
109   # mount -t cgroup2 none $MOUNT_POINT
111 cgroup2 filesystem has the magic number 0x63677270 ("cgrp").  All
112 controllers which support v2 and are not bound to a v1 hierarchy are
113 automatically bound to the v2 hierarchy and show up at the root.
114 Controllers which are not in active use in the v2 hierarchy can be
115 bound to other hierarchies.  This allows mixing v2 hierarchy with the
116 legacy v1 multiple hierarchies in a fully backward compatible way.
118 A controller can be moved across hierarchies only after the controller
119 is no longer referenced in its current hierarchy.  Because per-cgroup
120 controller states are destroyed asynchronously and controllers may
121 have lingering references, a controller may not show up immediately on
122 the v2 hierarchy after the final umount of the previous hierarchy.
123 Similarly, a controller should be fully disabled to be moved out of
124 the unified hierarchy and it may take some time for the disabled
125 controller to become available for other hierarchies; furthermore, due
126 to inter-controller dependencies, other controllers may need to be
127 disabled too.
129 While useful for development and manual configurations, moving
130 controllers dynamically between the v2 and other hierarchies is
131 strongly discouraged for production use.  It is recommended to decide
132 the hierarchies and controller associations before starting using the
133 controllers after system boot.
135 During transition to v2, system management software might still
136 automount the v1 cgroup filesystem and so hijack all controllers
137 during boot, before manual intervention is possible. To make testing
138 and experimenting easier, the kernel parameter cgroup_no_v1= allows
139 disabling controllers in v1 and make them always available in v2.
142 2-2. Organizing Processes
144 Initially, only the root cgroup exists to which all processes belong.
145 A child cgroup can be created by creating a sub-directory.
147   # mkdir $CGROUP_NAME
149 A given cgroup may have multiple child cgroups forming a tree
150 structure.  Each cgroup has a read-writable interface file
151 "cgroup.procs".  When read, it lists the PIDs of all processes which
152 belong to the cgroup one-per-line.  The PIDs are not ordered and the
153 same PID may show up more than once if the process got moved to
154 another cgroup and then back or the PID got recycled while reading.
156 A process can be migrated into a cgroup by writing its PID to the
157 target cgroup's "cgroup.procs" file.  Only one process can be migrated
158 on a single write(2) call.  If a process is composed of multiple
159 threads, writing the PID of any thread migrates all threads of the
160 process.
162 When a process forks a child process, the new process is born into the
163 cgroup that the forking process belongs to at the time of the
164 operation.  After exit, a process stays associated with the cgroup
165 that it belonged to at the time of exit until it's reaped; however, a
166 zombie process does not appear in "cgroup.procs" and thus can't be
167 moved to another cgroup.
169 A cgroup which doesn't have any children or live processes can be
170 destroyed by removing the directory.  Note that a cgroup which doesn't
171 have any children and is associated only with zombie processes is
172 considered empty and can be removed.
174   # rmdir $CGROUP_NAME
176 "/proc/$PID/cgroup" lists a process's cgroup membership.  If legacy
177 cgroup is in use in the system, this file may contain multiple lines,
178 one for each hierarchy.  The entry for cgroup v2 is always in the
179 format "0::$PATH".
181   # cat /proc/842/cgroup
182   ...
183   0::/test-cgroup/test-cgroup-nested
185 If the process becomes a zombie and the cgroup it was associated with
186 is removed subsequently, " (deleted)" is appended to the path.
188   # cat /proc/842/cgroup
189   ...
190   0::/test-cgroup/test-cgroup-nested (deleted)
193 2-3. [Un]populated Notification
195 Each non-root cgroup has a "cgroup.events" file which contains
196 "populated" field indicating whether the cgroup's sub-hierarchy has
197 live processes in it.  Its value is 0 if there is no live process in
198 the cgroup and its descendants; otherwise, 1.  poll and [id]notify
199 events are triggered when the value changes.  This can be used, for
200 example, to start a clean-up operation after all processes of a given
201 sub-hierarchy have exited.  The populated state updates and
202 notifications are recursive.  Consider the following sub-hierarchy
203 where the numbers in the parentheses represent the numbers of processes
204 in each cgroup.
206   A(4) - B(0) - C(1)
207               \ D(0)
209 A, B and C's "populated" fields would be 1 while D's 0.  After the one
210 process in C exits, B and C's "populated" fields would flip to "0" and
211 file modified events will be generated on the "cgroup.events" files of
212 both cgroups.
215 2-4. Controlling Controllers
217 2-4-1. Enabling and Disabling
219 Each cgroup has a "cgroup.controllers" file which lists all
220 controllers available for the cgroup to enable.
222   # cat cgroup.controllers
223   cpu io memory
225 No controller is enabled by default.  Controllers can be enabled and
226 disabled by writing to the "cgroup.subtree_control" file.
228   # echo "+cpu +memory -io" > cgroup.subtree_control
230 Only controllers which are listed in "cgroup.controllers" can be
231 enabled.  When multiple operations are specified as above, either they
232 all succeed or fail.  If multiple operations on the same controller
233 are specified, the last one is effective.
235 Enabling a controller in a cgroup indicates that the distribution of
236 the target resource across its immediate children will be controlled.
237 Consider the following sub-hierarchy.  The enabled controllers are
238 listed in parentheses.
240   A(cpu,memory) - B(memory) - C()
241                             \ D()
243 As A has "cpu" and "memory" enabled, A will control the distribution
244 of CPU cycles and memory to its children, in this case, B.  As B has
245 "memory" enabled but not "CPU", C and D will compete freely on CPU
246 cycles but their division of memory available to B will be controlled.
248 As a controller regulates the distribution of the target resource to
249 the cgroup's children, enabling it creates the controller's interface
250 files in the child cgroups.  In the above example, enabling "cpu" on B
251 would create the "cpu." prefixed controller interface files in C and
252 D.  Likewise, disabling "memory" from B would remove the "memory."
253 prefixed controller interface files from C and D.  This means that the
254 controller interface files - anything which doesn't start with
255 "cgroup." are owned by the parent rather than the cgroup itself.
258 2-4-2. Top-down Constraint
260 Resources are distributed top-down and a cgroup can further distribute
261 a resource only if the resource has been distributed to it from the
262 parent.  This means that all non-root "cgroup.subtree_control" files
263 can only contain controllers which are enabled in the parent's
264 "cgroup.subtree_control" file.  A controller can be enabled only if
265 the parent has the controller enabled and a controller can't be
266 disabled if one or more children have it enabled.
269 2-4-3. No Internal Process Constraint
271 Non-root cgroups can only distribute resources to their children when
272 they don't have any processes of their own.  In other words, only
273 cgroups which don't contain any processes can have controllers enabled
274 in their "cgroup.subtree_control" files.
276 This guarantees that, when a controller is looking at the part of the
277 hierarchy which has it enabled, processes are always only on the
278 leaves.  This rules out situations where child cgroups compete against
279 internal processes of the parent.
281 The root cgroup is exempt from this restriction.  Root contains
282 processes and anonymous resource consumption which can't be associated
283 with any other cgroups and requires special treatment from most
284 controllers.  How resource consumption in the root cgroup is governed
285 is up to each controller.
287 Note that the restriction doesn't get in the way if there is no
288 enabled controller in the cgroup's "cgroup.subtree_control".  This is
289 important as otherwise it wouldn't be possible to create children of a
290 populated cgroup.  To control resource distribution of a cgroup, the
291 cgroup must create children and transfer all its processes to the
292 children before enabling controllers in its "cgroup.subtree_control"
293 file.
296 2-5. Delegation
298 2-5-1. Model of Delegation
300 A cgroup can be delegated to a less privileged user by granting write
301 access of the directory and its "cgroup.procs" file to the user.  Note
302 that resource control interface files in a given directory control the
303 distribution of the parent's resources and thus must not be delegated
304 along with the directory.
306 Once delegated, the user can build sub-hierarchy under the directory,
307 organize processes as it sees fit and further distribute the resources
308 it received from the parent.  The limits and other settings of all
309 resource controllers are hierarchical and regardless of what happens
310 in the delegated sub-hierarchy, nothing can escape the resource
311 restrictions imposed by the parent.
313 Currently, cgroup doesn't impose any restrictions on the number of
314 cgroups in or nesting depth of a delegated sub-hierarchy; however,
315 this may be limited explicitly in the future.
318 2-5-2. Delegation Containment
320 A delegated sub-hierarchy is contained in the sense that processes
321 can't be moved into or out of the sub-hierarchy by the delegatee.  For
322 a process with a non-root euid to migrate a target process into a
323 cgroup by writing its PID to the "cgroup.procs" file, the following
324 conditions must be met.
326 - The writer's euid must match either uid or suid of the target process.
328 - The writer must have write access to the "cgroup.procs" file.
330 - The writer must have write access to the "cgroup.procs" file of the
331   common ancestor of the source and destination cgroups.
333 The above three constraints ensure that while a delegatee may migrate
334 processes around freely in the delegated sub-hierarchy it can't pull
335 in from or push out to outside the sub-hierarchy.
337 For an example, let's assume cgroups C0 and C1 have been delegated to
338 user U0 who created C00, C01 under C0 and C10 under C1 as follows and
339 all processes under C0 and C1 belong to U0.
341   ~~~~~~~~~~~~~ - C0 - C00
342   ~ cgroup    ~      \ C01
343   ~ hierarchy ~
344   ~~~~~~~~~~~~~ - C1 - C10
346 Let's also say U0 wants to write the PID of a process which is
347 currently in C10 into "C00/cgroup.procs".  U0 has write access to the
348 file and uid match on the process; however, the common ancestor of the
349 source cgroup C10 and the destination cgroup C00 is above the points
350 of delegation and U0 would not have write access to its "cgroup.procs"
351 files and thus the write will be denied with -EACCES.
354 2-6. Guidelines
356 2-6-1. Organize Once and Control
358 Migrating a process across cgroups is a relatively expensive operation
359 and stateful resources such as memory are not moved together with the
360 process.  This is an explicit design decision as there often exist
361 inherent trade-offs between migration and various hot paths in terms
362 of synchronization cost.
364 As such, migrating processes across cgroups frequently as a means to
365 apply different resource restrictions is discouraged.  A workload
366 should be assigned to a cgroup according to the system's logical and
367 resource structure once on start-up.  Dynamic adjustments to resource
368 distribution can be made by changing controller configuration through
369 the interface files.
372 2-6-2. Avoid Name Collisions
374 Interface files for a cgroup and its children cgroups occupy the same
375 directory and it is possible to create children cgroups which collide
376 with interface files.
378 All cgroup core interface files are prefixed with "cgroup." and each
379 controller's interface files are prefixed with the controller name and
380 a dot.  A controller's name is composed of lower case alphabets and
381 '_'s but never begins with an '_' so it can be used as the prefix
382 character for collision avoidance.  Also, interface file names won't
383 start or end with terms which are often used in categorizing workloads
384 such as job, service, slice, unit or workload.
386 cgroup doesn't do anything to prevent name collisions and it's the
387 user's responsibility to avoid them.
390 3. Resource Distribution Models
392 cgroup controllers implement several resource distribution schemes
393 depending on the resource type and expected use cases.  This section
394 describes major schemes in use along with their expected behaviors.
397 3-1. Weights
399 A parent's resource is distributed by adding up the weights of all
400 active children and giving each the fraction matching the ratio of its
401 weight against the sum.  As only children which can make use of the
402 resource at the moment participate in the distribution, this is
403 work-conserving.  Due to the dynamic nature, this model is usually
404 used for stateless resources.
406 All weights are in the range [1, 10000] with the default at 100.  This
407 allows symmetric multiplicative biases in both directions at fine
408 enough granularity while staying in the intuitive range.
410 As long as the weight is in range, all configuration combinations are
411 valid and there is no reason to reject configuration changes or
412 process migrations.
414 "cpu.weight" proportionally distributes CPU cycles to active children
415 and is an example of this type.
418 3-2. Limits
420 A child can only consume upto the configured amount of the resource.
421 Limits can be over-committed - the sum of the limits of children can
422 exceed the amount of resource available to the parent.
424 Limits are in the range [0, max] and defaults to "max", which is noop.
426 As limits can be over-committed, all configuration combinations are
427 valid and there is no reason to reject configuration changes or
428 process migrations.
430 "io.max" limits the maximum BPS and/or IOPS that a cgroup can consume
431 on an IO device and is an example of this type.
434 3-3. Protections
436 A cgroup is protected to be allocated upto the configured amount of
437 the resource if the usages of all its ancestors are under their
438 protected levels.  Protections can be hard guarantees or best effort
439 soft boundaries.  Protections can also be over-committed in which case
440 only upto the amount available to the parent is protected among
441 children.
443 Protections are in the range [0, max] and defaults to 0, which is
444 noop.
446 As protections can be over-committed, all configuration combinations
447 are valid and there is no reason to reject configuration changes or
448 process migrations.
450 "memory.low" implements best-effort memory protection and is an
451 example of this type.
454 3-4. Allocations
456 A cgroup is exclusively allocated a certain amount of a finite
457 resource.  Allocations can't be over-committed - the sum of the
458 allocations of children can not exceed the amount of resource
459 available to the parent.
461 Allocations are in the range [0, max] and defaults to 0, which is no
462 resource.
464 As allocations can't be over-committed, some configuration
465 combinations are invalid and should be rejected.  Also, if the
466 resource is mandatory for execution of processes, process migrations
467 may be rejected.
469 "cpu.rt.max" hard-allocates realtime slices and is an example of this
470 type.
473 4. Interface Files
475 4-1. Format
477 All interface files should be in one of the following formats whenever
478 possible.
480   New-line separated values
481   (when only one value can be written at once)
483         VAL0\n
484         VAL1\n
485         ...
487   Space separated values
488   (when read-only or multiple values can be written at once)
490         VAL0 VAL1 ...\n
492   Flat keyed
494         KEY0 VAL0\n
495         KEY1 VAL1\n
496         ...
498   Nested keyed
500         KEY0 SUB_KEY0=VAL00 SUB_KEY1=VAL01...
501         KEY1 SUB_KEY0=VAL10 SUB_KEY1=VAL11...
502         ...
504 For a writable file, the format for writing should generally match
505 reading; however, controllers may allow omitting later fields or
506 implement restricted shortcuts for most common use cases.
508 For both flat and nested keyed files, only the values for a single key
509 can be written at a time.  For nested keyed files, the sub key pairs
510 may be specified in any order and not all pairs have to be specified.
513 4-2. Conventions
515 - Settings for a single feature should be contained in a single file.
517 - The root cgroup should be exempt from resource control and thus
518   shouldn't have resource control interface files.  Also,
519   informational files on the root cgroup which end up showing global
520   information available elsewhere shouldn't exist.
522 - If a controller implements weight based resource distribution, its
523   interface file should be named "weight" and have the range [1,
524   10000] with 100 as the default.  The values are chosen to allow
525   enough and symmetric bias in both directions while keeping it
526   intuitive (the default is 100%).
528 - If a controller implements an absolute resource guarantee and/or
529   limit, the interface files should be named "min" and "max"
530   respectively.  If a controller implements best effort resource
531   guarantee and/or limit, the interface files should be named "low"
532   and "high" respectively.
534   In the above four control files, the special token "max" should be
535   used to represent upward infinity for both reading and writing.
537 - If a setting has a configurable default value and keyed specific
538   overrides, the default entry should be keyed with "default" and
539   appear as the first entry in the file.
541   The default value can be updated by writing either "default $VAL" or
542   "$VAL".
544   When writing to update a specific override, "default" can be used as
545   the value to indicate removal of the override.  Override entries
546   with "default" as the value must not appear when read.
548   For example, a setting which is keyed by major:minor device numbers
549   with integer values may look like the following.
551     # cat cgroup-example-interface-file
552     default 150
553     8:0 300
555   The default value can be updated by
557     # echo 125 > cgroup-example-interface-file
559   or
561     # echo "default 125" > cgroup-example-interface-file
563   An override can be set by
565     # echo "8:16 170" > cgroup-example-interface-file
567   and cleared by
569     # echo "8:0 default" > cgroup-example-interface-file
570     # cat cgroup-example-interface-file
571     default 125
572     8:16 170
574 - For events which are not very high frequency, an interface file
575   "events" should be created which lists event key value pairs.
576   Whenever a notifiable event happens, file modified event should be
577   generated on the file.
580 4-3. Core Interface Files
582 All cgroup core files are prefixed with "cgroup."
584   cgroup.procs
586         A read-write new-line separated values file which exists on
587         all cgroups.
589         When read, it lists the PIDs of all processes which belong to
590         the cgroup one-per-line.  The PIDs are not ordered and the
591         same PID may show up more than once if the process got moved
592         to another cgroup and then back or the PID got recycled while
593         reading.
595         A PID can be written to migrate the process associated with
596         the PID to the cgroup.  The writer should match all of the
597         following conditions.
599         - Its euid is either root or must match either uid or suid of
600           the target process.
602         - It must have write access to the "cgroup.procs" file.
604         - It must have write access to the "cgroup.procs" file of the
605           common ancestor of the source and destination cgroups.
607         When delegating a sub-hierarchy, write access to this file
608         should be granted along with the containing directory.
610   cgroup.controllers
612         A read-only space separated values file which exists on all
613         cgroups.
615         It shows space separated list of all controllers available to
616         the cgroup.  The controllers are not ordered.
618   cgroup.subtree_control
620         A read-write space separated values file which exists on all
621         cgroups.  Starts out empty.
623         When read, it shows space separated list of the controllers
624         which are enabled to control resource distribution from the
625         cgroup to its children.
627         Space separated list of controllers prefixed with '+' or '-'
628         can be written to enable or disable controllers.  A controller
629         name prefixed with '+' enables the controller and '-'
630         disables.  If a controller appears more than once on the list,
631         the last one is effective.  When multiple enable and disable
632         operations are specified, either all succeed or all fail.
634   cgroup.events
636         A read-only flat-keyed file which exists on non-root cgroups.
637         The following entries are defined.  Unless specified
638         otherwise, a value change in this file generates a file
639         modified event.
641           populated
643                 1 if the cgroup or its descendants contains any live
644                 processes; otherwise, 0.
647 5. Controllers
649 5-1. CPU
651 [NOTE: The interface for the cpu controller hasn't been merged yet]
653 The "cpu" controllers regulates distribution of CPU cycles.  This
654 controller implements weight and absolute bandwidth limit models for
655 normal scheduling policy and absolute bandwidth allocation model for
656 realtime scheduling policy.
659 5-1-1. CPU Interface Files
661 All time durations are in microseconds.
663   cpu.stat
665         A read-only flat-keyed file which exists on non-root cgroups.
667         It reports the following six stats.
669           usage_usec
670           user_usec
671           system_usec
672           nr_periods
673           nr_throttled
674           throttled_usec
676   cpu.weight
678         A read-write single value file which exists on non-root
679         cgroups.  The default is "100".
681         The weight in the range [1, 10000].
683   cpu.max
685         A read-write two value file which exists on non-root cgroups.
686         The default is "max 100000".
688         The maximum bandwidth limit.  It's in the following format.
690           $MAX $PERIOD
692         which indicates that the group may consume upto $MAX in each
693         $PERIOD duration.  "max" for $MAX indicates no limit.  If only
694         one number is written, $MAX is updated.
696   cpu.rt.max
698   [NOTE: The semantics of this file is still under discussion and the
699    interface hasn't been merged yet]
701         A read-write two value file which exists on all cgroups.
702         The default is "0 100000".
704         The maximum realtime runtime allocation.  Over-committing
705         configurations are disallowed and process migrations are
706         rejected if not enough bandwidth is available.  It's in the
707         following format.
709           $MAX $PERIOD
711         which indicates that the group may consume upto $MAX in each
712         $PERIOD duration.  If only one number is written, $MAX is
713         updated.
716 5-2. Memory
718 The "memory" controller regulates distribution of memory.  Memory is
719 stateful and implements both limit and protection models.  Due to the
720 intertwining between memory usage and reclaim pressure and the
721 stateful nature of memory, the distribution model is relatively
722 complex.
724 While not completely water-tight, all major memory usages by a given
725 cgroup are tracked so that the total memory consumption can be
726 accounted and controlled to a reasonable extent.  Currently, the
727 following types of memory usages are tracked.
729 - Userland memory - page cache and anonymous memory.
731 - Kernel data structures such as dentries and inodes.
733 - TCP socket buffers.
735 The above list may expand in the future for better coverage.
738 5-2-1. Memory Interface Files
740 All memory amounts are in bytes.  If a value which is not aligned to
741 PAGE_SIZE is written, the value may be rounded up to the closest
742 PAGE_SIZE multiple when read back.
744   memory.current
746         A read-only single value file which exists on non-root
747         cgroups.
749         The total amount of memory currently being used by the cgroup
750         and its descendants.
752   memory.low
754         A read-write single value file which exists on non-root
755         cgroups.  The default is "0".
757         Best-effort memory protection.  If the memory usages of a
758         cgroup and all its ancestors are below their low boundaries,
759         the cgroup's memory won't be reclaimed unless memory can be
760         reclaimed from unprotected cgroups.
762         Putting more memory than generally available under this
763         protection is discouraged.
765   memory.high
767         A read-write single value file which exists on non-root
768         cgroups.  The default is "max".
770         Memory usage throttle limit.  This is the main mechanism to
771         control memory usage of a cgroup.  If a cgroup's usage goes
772         over the high boundary, the processes of the cgroup are
773         throttled and put under heavy reclaim pressure.
775         Going over the high limit never invokes the OOM killer and
776         under extreme conditions the limit may be breached.
778   memory.max
780         A read-write single value file which exists on non-root
781         cgroups.  The default is "max".
783         Memory usage hard limit.  This is the final protection
784         mechanism.  If a cgroup's memory usage reaches this limit and
785         can't be reduced, the OOM killer is invoked in the cgroup.
786         Under certain circumstances, the usage may go over the limit
787         temporarily.
789         This is the ultimate protection mechanism.  As long as the
790         high limit is used and monitored properly, this limit's
791         utility is limited to providing the final safety net.
793   memory.events
795         A read-only flat-keyed file which exists on non-root cgroups.
796         The following entries are defined.  Unless specified
797         otherwise, a value change in this file generates a file
798         modified event.
800           low
802                 The number of times the cgroup is reclaimed due to
803                 high memory pressure even though its usage is under
804                 the low boundary.  This usually indicates that the low
805                 boundary is over-committed.
807           high
809                 The number of times processes of the cgroup are
810                 throttled and routed to perform direct memory reclaim
811                 because the high memory boundary was exceeded.  For a
812                 cgroup whose memory usage is capped by the high limit
813                 rather than global memory pressure, this event's
814                 occurrences are expected.
816           max
818                 The number of times the cgroup's memory usage was
819                 about to go over the max boundary.  If direct reclaim
820                 fails to bring it down, the OOM killer is invoked.
822           oom
824                 The number of times the OOM killer has been invoked in
825                 the cgroup.  This may not exactly match the number of
826                 processes killed but should generally be close.
828   memory.stat
830         A read-only flat-keyed file which exists on non-root cgroups.
832         This breaks down the cgroup's memory footprint into different
833         types of memory, type-specific details, and other information
834         on the state and past events of the memory management system.
836         All memory amounts are in bytes.
838         The entries are ordered to be human readable, and new entries
839         can show up in the middle. Don't rely on items remaining in a
840         fixed position; use the keys to look up specific values!
842           anon
844                 Amount of memory used in anonymous mappings such as
845                 brk(), sbrk(), and mmap(MAP_ANONYMOUS)
847           file
849                 Amount of memory used to cache filesystem data,
850                 including tmpfs and shared memory.
852           file_mapped
854                 Amount of cached filesystem data mapped with mmap()
856           file_dirty
858                 Amount of cached filesystem data that was modified but
859                 not yet written back to disk
861           file_writeback
863                 Amount of cached filesystem data that was modified and
864                 is currently being written back to disk
866           inactive_anon
867           active_anon
868           inactive_file
869           active_file
870           unevictable
872                 Amount of memory, swap-backed and filesystem-backed,
873                 on the internal memory management lists used by the
874                 page reclaim algorithm
876           pgfault
878                 Total number of page faults incurred
880           pgmajfault
882                 Number of major page faults incurred
884   memory.swap.current
886         A read-only single value file which exists on non-root
887         cgroups.
889         The total amount of swap currently being used by the cgroup
890         and its descendants.
892   memory.swap.max
894         A read-write single value file which exists on non-root
895         cgroups.  The default is "max".
897         Swap usage hard limit.  If a cgroup's swap usage reaches this
898         limit, anonymous meomry of the cgroup will not be swapped out.
901 5-2-2. General Usage
903 "memory.high" is the main mechanism to control memory usage.
904 Over-committing on high limit (sum of high limits > available memory)
905 and letting global memory pressure to distribute memory according to
906 usage is a viable strategy.
908 Because breach of the high limit doesn't trigger the OOM killer but
909 throttles the offending cgroup, a management agent has ample
910 opportunities to monitor and take appropriate actions such as granting
911 more memory or terminating the workload.
913 Determining whether a cgroup has enough memory is not trivial as
914 memory usage doesn't indicate whether the workload can benefit from
915 more memory.  For example, a workload which writes data received from
916 network to a file can use all available memory but can also operate as
917 performant with a small amount of memory.  A measure of memory
918 pressure - how much the workload is being impacted due to lack of
919 memory - is necessary to determine whether a workload needs more
920 memory; unfortunately, memory pressure monitoring mechanism isn't
921 implemented yet.
924 5-2-3. Memory Ownership
926 A memory area is charged to the cgroup which instantiated it and stays
927 charged to the cgroup until the area is released.  Migrating a process
928 to a different cgroup doesn't move the memory usages that it
929 instantiated while in the previous cgroup to the new cgroup.
931 A memory area may be used by processes belonging to different cgroups.
932 To which cgroup the area will be charged is in-deterministic; however,
933 over time, the memory area is likely to end up in a cgroup which has
934 enough memory allowance to avoid high reclaim pressure.
936 If a cgroup sweeps a considerable amount of memory which is expected
937 to be accessed repeatedly by other cgroups, it may make sense to use
938 POSIX_FADV_DONTNEED to relinquish the ownership of memory areas
939 belonging to the affected files to ensure correct memory ownership.
942 5-3. IO
944 The "io" controller regulates the distribution of IO resources.  This
945 controller implements both weight based and absolute bandwidth or IOPS
946 limit distribution; however, weight based distribution is available
947 only if cfq-iosched is in use and neither scheme is available for
948 blk-mq devices.
951 5-3-1. IO Interface Files
953   io.stat
955         A read-only nested-keyed file which exists on non-root
956         cgroups.
958         Lines are keyed by $MAJ:$MIN device numbers and not ordered.
959         The following nested keys are defined.
961           rbytes        Bytes read
962           wbytes        Bytes written
963           rios          Number of read IOs
964           wios          Number of write IOs
966         An example read output follows.
968           8:16 rbytes=1459200 wbytes=314773504 rios=192 wios=353
969           8:0 rbytes=90430464 wbytes=299008000 rios=8950 wios=1252
971   io.weight
973         A read-write flat-keyed file which exists on non-root cgroups.
974         The default is "default 100".
976         The first line is the default weight applied to devices
977         without specific override.  The rest are overrides keyed by
978         $MAJ:$MIN device numbers and not ordered.  The weights are in
979         the range [1, 10000] and specifies the relative amount IO time
980         the cgroup can use in relation to its siblings.
982         The default weight can be updated by writing either "default
983         $WEIGHT" or simply "$WEIGHT".  Overrides can be set by writing
984         "$MAJ:$MIN $WEIGHT" and unset by writing "$MAJ:$MIN default".
986         An example read output follows.
988           default 100
989           8:16 200
990           8:0 50
992   io.max
994         A read-write nested-keyed file which exists on non-root
995         cgroups.
997         BPS and IOPS based IO limit.  Lines are keyed by $MAJ:$MIN
998         device numbers and not ordered.  The following nested keys are
999         defined.
1001           rbps          Max read bytes per second
1002           wbps          Max write bytes per second
1003           riops         Max read IO operations per second
1004           wiops         Max write IO operations per second
1006         When writing, any number of nested key-value pairs can be
1007         specified in any order.  "max" can be specified as the value
1008         to remove a specific limit.  If the same key is specified
1009         multiple times, the outcome is undefined.
1011         BPS and IOPS are measured in each IO direction and IOs are
1012         delayed if limit is reached.  Temporary bursts are allowed.
1014         Setting read limit at 2M BPS and write at 120 IOPS for 8:16.
1016           echo "8:16 rbps=2097152 wiops=120" > io.max
1018         Reading returns the following.
1020           8:16 rbps=2097152 wbps=max riops=max wiops=120
1022         Write IOPS limit can be removed by writing the following.
1024           echo "8:16 wiops=max" > io.max
1026         Reading now returns the following.
1028           8:16 rbps=2097152 wbps=max riops=max wiops=max
1031 5-3-2. Writeback
1033 Page cache is dirtied through buffered writes and shared mmaps and
1034 written asynchronously to the backing filesystem by the writeback
1035 mechanism.  Writeback sits between the memory and IO domains and
1036 regulates the proportion of dirty memory by balancing dirtying and
1037 write IOs.
1039 The io controller, in conjunction with the memory controller,
1040 implements control of page cache writeback IOs.  The memory controller
1041 defines the memory domain that dirty memory ratio is calculated and
1042 maintained for and the io controller defines the io domain which
1043 writes out dirty pages for the memory domain.  Both system-wide and
1044 per-cgroup dirty memory states are examined and the more restrictive
1045 of the two is enforced.
1047 cgroup writeback requires explicit support from the underlying
1048 filesystem.  Currently, cgroup writeback is implemented on ext2, ext4
1049 and btrfs.  On other filesystems, all writeback IOs are attributed to
1050 the root cgroup.
1052 There are inherent differences in memory and writeback management
1053 which affects how cgroup ownership is tracked.  Memory is tracked per
1054 page while writeback per inode.  For the purpose of writeback, an
1055 inode is assigned to a cgroup and all IO requests to write dirty pages
1056 from the inode are attributed to that cgroup.
1058 As cgroup ownership for memory is tracked per page, there can be pages
1059 which are associated with different cgroups than the one the inode is
1060 associated with.  These are called foreign pages.  The writeback
1061 constantly keeps track of foreign pages and, if a particular foreign
1062 cgroup becomes the majority over a certain period of time, switches
1063 the ownership of the inode to that cgroup.
1065 While this model is enough for most use cases where a given inode is
1066 mostly dirtied by a single cgroup even when the main writing cgroup
1067 changes over time, use cases where multiple cgroups write to a single
1068 inode simultaneously are not supported well.  In such circumstances, a
1069 significant portion of IOs are likely to be attributed incorrectly.
1070 As memory controller assigns page ownership on the first use and
1071 doesn't update it until the page is released, even if writeback
1072 strictly follows page ownership, multiple cgroups dirtying overlapping
1073 areas wouldn't work as expected.  It's recommended to avoid such usage
1074 patterns.
1076 The sysctl knobs which affect writeback behavior are applied to cgroup
1077 writeback as follows.
1079   vm.dirty_background_ratio
1080   vm.dirty_ratio
1082         These ratios apply the same to cgroup writeback with the
1083         amount of available memory capped by limits imposed by the
1084         memory controller and system-wide clean memory.
1086   vm.dirty_background_bytes
1087   vm.dirty_bytes
1089         For cgroup writeback, this is calculated into ratio against
1090         total available memory and applied the same way as
1091         vm.dirty[_background]_ratio.
1094 P. Information on Kernel Programming
1096 This section contains kernel programming information in the areas
1097 where interacting with cgroup is necessary.  cgroup core and
1098 controllers are not covered.
1101 P-1. Filesystem Support for Writeback
1103 A filesystem can support cgroup writeback by updating
1104 address_space_operations->writepage[s]() to annotate bio's using the
1105 following two functions.
1107   wbc_init_bio(@wbc, @bio)
1109         Should be called for each bio carrying writeback data and
1110         associates the bio with the inode's owner cgroup.  Can be
1111         called anytime between bio allocation and submission.
1113   wbc_account_io(@wbc, @page, @bytes)
1115         Should be called for each data segment being written out.
1116         While this function doesn't care exactly when it's called
1117         during the writeback session, it's the easiest and most
1118         natural to call it as data segments are added to a bio.
1120 With writeback bio's annotated, cgroup support can be enabled per
1121 super_block by setting SB_I_CGROUPWB in ->s_iflags.  This allows for
1122 selective disabling of cgroup writeback support which is helpful when
1123 certain filesystem features, e.g. journaled data mode, are
1124 incompatible.
1126 wbc_init_bio() binds the specified bio to its cgroup.  Depending on
1127 the configuration, the bio may be executed at a lower priority and if
1128 the writeback session is holding shared resources, e.g. a journal
1129 entry, may lead to priority inversion.  There is no one easy solution
1130 for the problem.  Filesystems can try to work around specific problem
1131 cases by skipping wbc_init_bio() or using bio_associate_blkcg()
1132 directly.
1135 D. Deprecated v1 Core Features
1137 - Multiple hierarchies including named ones are not supported.
1139 - All mount options and remounting are not supported.
1141 - The "tasks" file is removed and "cgroup.procs" is not sorted.
1143 - "cgroup.clone_children" is removed.
1145 - /proc/cgroups is meaningless for v2.  Use "cgroup.controllers" file
1146   at the root instead.
1149 R. Issues with v1 and Rationales for v2
1151 R-1. Multiple Hierarchies
1153 cgroup v1 allowed an arbitrary number of hierarchies and each
1154 hierarchy could host any number of controllers.  While this seemed to
1155 provide a high level of flexibility, it wasn't useful in practice.
1157 For example, as there is only one instance of each controller, utility
1158 type controllers such as freezer which can be useful in all
1159 hierarchies could only be used in one.  The issue is exacerbated by
1160 the fact that controllers couldn't be moved to another hierarchy once
1161 hierarchies were populated.  Another issue was that all controllers
1162 bound to a hierarchy were forced to have exactly the same view of the
1163 hierarchy.  It wasn't possible to vary the granularity depending on
1164 the specific controller.
1166 In practice, these issues heavily limited which controllers could be
1167 put on the same hierarchy and most configurations resorted to putting
1168 each controller on its own hierarchy.  Only closely related ones, such
1169 as the cpu and cpuacct controllers, made sense to be put on the same
1170 hierarchy.  This often meant that userland ended up managing multiple
1171 similar hierarchies repeating the same steps on each hierarchy
1172 whenever a hierarchy management operation was necessary.
1174 Furthermore, support for multiple hierarchies came at a steep cost.
1175 It greatly complicated cgroup core implementation but more importantly
1176 the support for multiple hierarchies restricted how cgroup could be
1177 used in general and what controllers was able to do.
1179 There was no limit on how many hierarchies there might be, which meant
1180 that a thread's cgroup membership couldn't be described in finite
1181 length.  The key might contain any number of entries and was unlimited
1182 in length, which made it highly awkward to manipulate and led to
1183 addition of controllers which existed only to identify membership,
1184 which in turn exacerbated the original problem of proliferating number
1185 of hierarchies.
1187 Also, as a controller couldn't have any expectation regarding the
1188 topologies of hierarchies other controllers might be on, each
1189 controller had to assume that all other controllers were attached to
1190 completely orthogonal hierarchies.  This made it impossible, or at
1191 least very cumbersome, for controllers to cooperate with each other.
1193 In most use cases, putting controllers on hierarchies which are
1194 completely orthogonal to each other isn't necessary.  What usually is
1195 called for is the ability to have differing levels of granularity
1196 depending on the specific controller.  In other words, hierarchy may
1197 be collapsed from leaf towards root when viewed from specific
1198 controllers.  For example, a given configuration might not care about
1199 how memory is distributed beyond a certain level while still wanting
1200 to control how CPU cycles are distributed.
1203 R-2. Thread Granularity
1205 cgroup v1 allowed threads of a process to belong to different cgroups.
1206 This didn't make sense for some controllers and those controllers
1207 ended up implementing different ways to ignore such situations but
1208 much more importantly it blurred the line between API exposed to
1209 individual applications and system management interface.
1211 Generally, in-process knowledge is available only to the process
1212 itself; thus, unlike service-level organization of processes,
1213 categorizing threads of a process requires active participation from
1214 the application which owns the target process.
1216 cgroup v1 had an ambiguously defined delegation model which got abused
1217 in combination with thread granularity.  cgroups were delegated to
1218 individual applications so that they can create and manage their own
1219 sub-hierarchies and control resource distributions along them.  This
1220 effectively raised cgroup to the status of a syscall-like API exposed
1221 to lay programs.
1223 First of all, cgroup has a fundamentally inadequate interface to be
1224 exposed this way.  For a process to access its own knobs, it has to
1225 extract the path on the target hierarchy from /proc/self/cgroup,
1226 construct the path by appending the name of the knob to the path, open
1227 and then read and/or write to it.  This is not only extremely clunky
1228 and unusual but also inherently racy.  There is no conventional way to
1229 define transaction across the required steps and nothing can guarantee
1230 that the process would actually be operating on its own sub-hierarchy.
1232 cgroup controllers implemented a number of knobs which would never be
1233 accepted as public APIs because they were just adding control knobs to
1234 system-management pseudo filesystem.  cgroup ended up with interface
1235 knobs which were not properly abstracted or refined and directly
1236 revealed kernel internal details.  These knobs got exposed to
1237 individual applications through the ill-defined delegation mechanism
1238 effectively abusing cgroup as a shortcut to implementing public APIs
1239 without going through the required scrutiny.
1241 This was painful for both userland and kernel.  Userland ended up with
1242 misbehaving and poorly abstracted interfaces and kernel exposing and
1243 locked into constructs inadvertently.
1246 R-3. Competition Between Inner Nodes and Threads
1248 cgroup v1 allowed threads to be in any cgroups which created an
1249 interesting problem where threads belonging to a parent cgroup and its
1250 children cgroups competed for resources.  This was nasty as two
1251 different types of entities competed and there was no obvious way to
1252 settle it.  Different controllers did different things.
1254 The cpu controller considered threads and cgroups as equivalents and
1255 mapped nice levels to cgroup weights.  This worked for some cases but
1256 fell flat when children wanted to be allocated specific ratios of CPU
1257 cycles and the number of internal threads fluctuated - the ratios
1258 constantly changed as the number of competing entities fluctuated.
1259 There also were other issues.  The mapping from nice level to weight
1260 wasn't obvious or universal, and there were various other knobs which
1261 simply weren't available for threads.
1263 The io controller implicitly created a hidden leaf node for each
1264 cgroup to host the threads.  The hidden leaf had its own copies of all
1265 the knobs with "leaf_" prefixed.  While this allowed equivalent
1266 control over internal threads, it was with serious drawbacks.  It
1267 always added an extra layer of nesting which wouldn't be necessary
1268 otherwise, made the interface messy and significantly complicated the
1269 implementation.
1271 The memory controller didn't have a way to control what happened
1272 between internal tasks and child cgroups and the behavior was not
1273 clearly defined.  There were attempts to add ad-hoc behaviors and
1274 knobs to tailor the behavior to specific workloads which would have
1275 led to problems extremely difficult to resolve in the long term.
1277 Multiple controllers struggled with internal tasks and came up with
1278 different ways to deal with it; unfortunately, all the approaches were
1279 severely flawed and, furthermore, the widely different behaviors
1280 made cgroup as a whole highly inconsistent.
1282 This clearly is a problem which needs to be addressed from cgroup core
1283 in a uniform way.
1286 R-4. Other Interface Issues
1288 cgroup v1 grew without oversight and developed a large number of
1289 idiosyncrasies and inconsistencies.  One issue on the cgroup core side
1290 was how an empty cgroup was notified - a userland helper binary was
1291 forked and executed for each event.  The event delivery wasn't
1292 recursive or delegatable.  The limitations of the mechanism also led
1293 to in-kernel event delivery filtering mechanism further complicating
1294 the interface.
1296 Controller interfaces were problematic too.  An extreme example is
1297 controllers completely ignoring hierarchical organization and treating
1298 all cgroups as if they were all located directly under the root
1299 cgroup.  Some controllers exposed a large amount of inconsistent
1300 implementation details to userland.
1302 There also was no consistency across controllers.  When a new cgroup
1303 was created, some controllers defaulted to not imposing extra
1304 restrictions while others disallowed any resource usage until
1305 explicitly configured.  Configuration knobs for the same type of
1306 control used widely differing naming schemes and formats.  Statistics
1307 and information knobs were named arbitrarily and used different
1308 formats and units even in the same controller.
1310 cgroup v2 establishes common conventions where appropriate and updates
1311 controllers so that they expose minimal and consistent interfaces.
1314 R-5. Controller Issues and Remedies
1316 R-5-1. Memory
1318 The original lower boundary, the soft limit, is defined as a limit
1319 that is per default unset.  As a result, the set of cgroups that
1320 global reclaim prefers is opt-in, rather than opt-out.  The costs for
1321 optimizing these mostly negative lookups are so high that the
1322 implementation, despite its enormous size, does not even provide the
1323 basic desirable behavior.  First off, the soft limit has no
1324 hierarchical meaning.  All configured groups are organized in a global
1325 rbtree and treated like equal peers, regardless where they are located
1326 in the hierarchy.  This makes subtree delegation impossible.  Second,
1327 the soft limit reclaim pass is so aggressive that it not just
1328 introduces high allocation latencies into the system, but also impacts
1329 system performance due to overreclaim, to the point where the feature
1330 becomes self-defeating.
1332 The memory.low boundary on the other hand is a top-down allocated
1333 reserve.  A cgroup enjoys reclaim protection when it and all its
1334 ancestors are below their low boundaries, which makes delegation of
1335 subtrees possible.  Secondly, new cgroups have no reserve per default
1336 and in the common case most cgroups are eligible for the preferred
1337 reclaim pass.  This allows the new low boundary to be efficiently
1338 implemented with just a minor addition to the generic reclaim code,
1339 without the need for out-of-band data structures and reclaim passes.
1340 Because the generic reclaim code considers all cgroups except for the
1341 ones running low in the preferred first reclaim pass, overreclaim of
1342 individual groups is eliminated as well, resulting in much better
1343 overall workload performance.
1345 The original high boundary, the hard limit, is defined as a strict
1346 limit that can not budge, even if the OOM killer has to be called.
1347 But this generally goes against the goal of making the most out of the
1348 available memory.  The memory consumption of workloads varies during
1349 runtime, and that requires users to overcommit.  But doing that with a
1350 strict upper limit requires either a fairly accurate prediction of the
1351 working set size or adding slack to the limit.  Since working set size
1352 estimation is hard and error prone, and getting it wrong results in
1353 OOM kills, most users tend to err on the side of a looser limit and
1354 end up wasting precious resources.
1356 The memory.high boundary on the other hand can be set much more
1357 conservatively.  When hit, it throttles allocations by forcing them
1358 into direct reclaim to work off the excess, but it never invokes the
1359 OOM killer.  As a result, a high boundary that is chosen too
1360 aggressively will not terminate the processes, but instead it will
1361 lead to gradual performance degradation.  The user can monitor this
1362 and make corrections until the minimal memory footprint that still
1363 gives acceptable performance is found.
1365 In extreme cases, with many concurrent allocations and a complete
1366 breakdown of reclaim progress within the group, the high boundary can
1367 be exceeded.  But even then it's mostly better to satisfy the
1368 allocation from the slack available in other groups or the rest of the
1369 system than killing the group.  Otherwise, memory.max is there to
1370 limit this type of spillover and ultimately contain buggy or even
1371 malicious applications.
1373 The combined memory+swap accounting and limiting is replaced by real
1374 control over swap space.
1376 The main argument for a combined memory+swap facility in the original
1377 cgroup design was that global or parental pressure would always be
1378 able to swap all anonymous memory of a child group, regardless of the
1379 child's own (possibly untrusted) configuration.  However, untrusted
1380 groups can sabotage swapping by other means - such as referencing its
1381 anonymous memory in a tight loop - and an admin can not assume full
1382 swappability when overcommitting untrusted jobs.
1384 For trusted jobs, on the other hand, a combined counter is not an
1385 intuitive userspace interface, and it flies in the face of the idea
1386 that cgroup controllers should account and limit specific physical
1387 resources.  Swap space is a resource like all others in the system,
1388 and that's why unified hierarchy allows distributing it separately.