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