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