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