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