Module 2 · Lesson 110 of 131

cgroups v2 limits

Create a cgroup v2, set memory.max, cpu.max and pids.max, run a process inside it, and observe the OOM kill.

  • Beginner to advanced
  • 9 min read
  • 45 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM with systemd; gcc; sudo (root) access to create cgroups under /sys/fs/cgroup.

Your place in the module
By the end you can 4 objectives
  • Create a cgroup on the unified hierarchy and move a process into it
  • Set and read the memory.max, cpu.max and pids.max limit files
  • Explain how reclaim and the OOM killer enforce memory.max
  • Describe how cgroup v2 differs from v1 and how systemd delegates a subtree
Video coming sooncgroups v2 limits
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from The network namespace
  • Every network namespace starts with only a loopback device, which is down until you bring it up.
  • ip netns add persists the namespace as a bind mount under /run/netns, and exec runs a command inside it.
  • A veth pair links two namespaces: each end lives in one namespace, and frames written to one end arrive at the other.
01

The unified hierarchy and its controllers

3 min read

Namespaces control what a process can see. This lesson adds cgroups v2, which control what a process can use, through the unified hierarchy and its limit files.

A control group (cgroup) is a kernel object that groups processes so the kernel can measure, limit and account for the resources they use together. In cgroup v2 every resource controller lives on one hierarchy, mounted at /sys/fs/cgroup with the type cgroup2:

bash
findmnt -t cgroup2

The output shows /sys/fs/cgroup as the target and cgroup2 as the source and filesystem type. A The kernel ships several: cpu, cpuset, memory, pids and io, plus rdma, hugetlb and misc. The five this lesson uses are:

  • cpu: CPU time, as a hard quota (cpu.max) or a weight for sharing (cpu.weight)
  • memory: memory usage, hard limits (memory.max) and soft throttling (memory.high)
  • pids: the number of processes and threads a cgroup may hold (pids.max)
  • io: block I/O bandwidth and latency (io.max, io.weight)
  • cpuset: which CPUs and NUMA memory nodes a cgroup may use (cpuset.cpus, cpuset.mems)

Which controllers the running kernel supports is listed in the root cgroup's cgroup.controllers file:

bash
cat /sys/fs/cgroup/cgroup.controllers

Being available is not the same as being enabled for children. A controller applies to child cgroups only after a parent enables it by writing its name, with a leading plus, to cgroup.subtree_control:

bash
sudo sh -c 'echo "+memory +pids +cpu" > /sys/fs/cgroup/cgroup.subtree_control'

The plus adds a controller; a minus removes it. This per-subtree enablement is what the "v2" design means by a unified hierarchy: there is one tree, and each branch decides which controllers are active below it.

Creating a cgroup is a directory operation. mkdir on the hierarchy makes a cgroup, and the kernel populates it with interface files:

bash
sudo mkdir /sys/fs/cgroup/demo
ls /sys/fs/cgroup/demo

The new directory now holds files such as memory.max, memory.current, cpu.max, pids.max, cgroup.procs and cgroup.events. To place a process inside, write its PID to cgroup.procs; reading cgroup.procs lists the member PIDs. All of a process's threads move together, and a child process starts in the same cgroup as its parent. Removing a cgroup is rmdir, which succeeds only when the cgroup is empty and holds no processes.

This file-and-directory interface is the whole control surface, called cgroupfs: mkdir and rmdir create and delete, an ordinary write() sets a limit, and cgroup.procs moves processes. No special system call is required.

The unified hierarchy/sys/fs/cgroupunified hierarchy (cgroup2)cgroup.controllerscpu memory pids io cpusetcgroup.subtree_controlenable controllers for childrendemomemory.maxhard memory limitcpu.maxquota per periodpids.maxprocess and thread capcgroup.procsmember PIDs/sys/fs/cgroupunified hierarchy (cgroup2)cgroup.controllerscpu memory pids io cpusetcgroup.subtree_controlenable controllers forchildrendemomemory.maxhard memory limitcpu.maxquota per periodpids.maxprocess and thread capcgroup.procsmember PIDs
One tree holds the controllers and every cgroup, with the limit files inside each cgroup.
02

Writing limits: memory.max, cpu.max and pids.max

4 min read

memory.max is the hard limit. Write a byte count, a value with a suffix, or the word max for no limit:

bash
echo 64M | sudo tee /sys/fs/cgroup/demo/memory.max
cat /sys/fs/cgroup/demo/memory.max

As usage approaches the limit, the kernel reclaims memory: it drops clean page cache and shrinks other reclaimable memory where it can. Anonymous pages that a process has written cannot be reclaimed without either swapping or killing. When the cgroup's usage cannot be brought back under the limit, the OOM killer selects a process inside that cgroup (or a descendant) and sends it SIGKILL. The limit is per cgroup, not per process: 64M is shared by every process in the subtree.

memory.current is the read-only current usage, memory.peak the high-water mark, and memory.events the counters. After an OOM kill, the oom_kill counter in memory.events increases:

bash
cat /sys/fs/cgroup/demo/memory.events

memory.high is a soft throttle: when usage passes it, the kernel applies reclaim pressure to slow the cgroup down without killing, useful as a warning band below memory.max.

To make a memory limit deterministic in the lab, also disable swap for the cgroup by writing 0 to memory.swap.max. Otherwise the 64M memory.max can be partly satisfied by paging anonymous memory to swap, and the process survives much longer. With swap at 0, the limit applies to RAM alone and the OOM kill arrives promptly.

cpu.max takes two numbers, a quota and a period, both in microseconds, in the form "$MAX $PERIOD". The cgroup may use at most quota microseconds of CPU time in each period. The default period is 100000 (100 ms), and the default value is max (no quota):

bash
echo "50000 100000" | sudo tee /sys/fs/cgroup/demo/cpu.max

50000 microseconds per 100000 microsecond period is 50 percent of one CPU. The quota is per period and does not pin the cgroup to a particular core; a multi-threaded process still shares the single quota across all its threads. For sharing idle CPU without a hard cap, cpu.weight (1 to 10000, default 100) sets a relative weight used only while CPUs are contended.

pids.max caps the number of processes and threads that may exist in the cgroup at once. When a fork or clone would exceed it, the call returns -1 with errno EAGAIN (Resource temporarily unavailable):

bash
echo 32 | sudo tee /sys/fs/cgroup/demo/pids.max

The cpuset controller binds a cgroup to specific CPUs and memory nodes with cpuset.cpus and cpuset.mems (for example "0-3"); the io controller limits block I/O with io.max.

The program the lab will run allocates and touches memory in a loop:

c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
    const size_t chunk = 16 * 1024 * 1024; /* 16 MiB per round */
    size_t total = 0;

    for (;;) {
        char *p = malloc(chunk);
        if (!p) {
            fprintf(stderr, "malloc failed after %zu MiB\n", total >> 20);
            return 1;
        }
        memset(p, 0xab, chunk);   /* touch every page so it becomes resident */
        total += chunk;
        printf("resident %zu MiB\n", total >> 20);
        fflush(stdout);
    }
}

Compile it and run it inside a constrained cgroup:

bash
gcc -Wall -Wextra -std=c17 -o hog hog.c
sudo mkdir /sys/fs/cgroup/demo
echo 64M | sudo tee /sys/fs/cgroup/demo/memory.max
echo 0 | sudo tee /sys/fs/cgroup/demo/memory.swap.max
echo "50000 100000" | sudo tee /sys/fs/cgroup/demo/cpu.max
echo 32 | sudo tee /sys/fs/cgroup/demo/pids.max
sudo sh -c 'echo $$ > /sys/fs/cgroup/demo/cgroup.procs && exec ./hog'

The shell writes its own PID into cgroup.procs, then exec replaces it with hog, which inherits the cgroup. As hog touches pages, memory.current climbs toward 64M. Reclaim fails because the pages are anonymous and swap is disabled, so the OOM killer fires, hog dies, and memory.events records the kill:

bash
cat /sys/fs/cgroup/demo/memory.events
cat /sys/fs/cgroup/demo/memory.peak
sudo dmesg | tail

memory.peak shows the highest usage reached. dmesg shows a line whose form is "Memory cgroup out of memory: Killed process PID (hog) ..." (the PID and sizes differ on each machine and each run). Clean up with sudo rmdir /sys/fs/cgroup/demo once the cgroup holds no processes.

Enforcing memory.maxSetmemory.maxProcesstouchespagesUsage nearslimitKernelreclaimsExit from step 4: reclaim succeedsruns onOOM killeroom_killrecordedSetmemory.maxProcesstouchespagesUsage nearslimitKernelreclaimsExit from step 4: reclaimsucceedsruns onOOM killeroom_killrecorded
A hard memory limit is enforced by reclaim first, then by the OOM killer when reclaim cannot bring usage back down.
03

v1 vs v2, systemd delegation and the internals

5 min read

cgroup v1 mounted each controller as its own hierarchy, so a system could have several cgroup mounts with different shapes, and the same processes could sit at different places on each. Its limit files had per-controller names: memory.limit_in_bytes for memory, cpu.cfs_quota_us and cpu.cfs_period_us for the CPU quota, cpu.shares for CPU weight. v2 collapses this into one tree with uniform names (memory.max, cpu.max, cpu.weight) and makes the process the unit: all threads of a process live in the same cgroup, which v1 could not guarantee. Ubuntu 24.04 uses v2 by default, and the v1 mounts no longer appear.

cgroup v1 versus v2cgroup v1cgroup v2Hierarchyone mount percontrollerone unifiedhierarchyMemory limitmemory.limit_in_bytesmemory.maxCPU limitcpu.cfs_quota_us / cpu.cfs_period_uscpu.maxCPU sharecpu.sharescpu.weightThreadscould splitacrosscgroupsprocess isthe unit
The same limits have different names and a different tree shape in v1 and v2.

systemd is the default manager of the cgroup v2 tree on this system. It builds the hierarchy under /sys/fs/cgroup from slices, scopes and service units: system.slice holds system services, user.slice holds user sessions, and each service or scope is a cgroup. systemctl status shows the path, for example CGroup: /system.slice/ssh.service. Because PID 1 owns the tree, a normal user cannot create cgroups at the root; the raw-file lab above uses sudo. systemd writes the same limit files when you give a unit resource settings, and systemd-run applies them to one command without writing a unit file:

bash
sudo systemd-run --unit=m2s13b4-hog --property=MemoryMax=64M \
  --property=MemorySwapMax=0 --property=CPUQuota=50% "$PWD/hog"

MemoryMax and CPUQuota become memory.max and cpu.max in the unit's cgroup. This unit runs under the system manager, so systemd-run needs sudo, and the program's output goes to the journal (journalctl -u m2s13b4-hog). An unprivileged user can do the same in the subtree systemd delegates to each user's manager, for example systemd-run --user --scope -p MemoryMax=64M ./hog. A unit with Delegate=yes hands its subtree's controllers to the service, so the service may create child cgroups itself; container runtimes rely on exactly this. Both paths end at the same files: raw cgroupfs is the low-level interface, and systemd is the manager layered on top.

{{< callout type="note" >}}On a stock Ubuntu 24.04 the whole /sys/fs/cgroup tree belongs to systemd, so manual creation needs root or a delegated subtree. The raw cgroupfs exercises in this lesson use sudo; systemd-run --user is the unprivileged alternative, working in the subtree systemd delegates to your user manager.{{< /callout >}}

Going deeperExplore the mechanism

The no-internal-processes rule. A non-root cgroup that has domain controllers enabled in its cgroup.subtree_control may not hold member processes of its own: writing a PID to its cgroup.procs is refused (EBUSY), and enabling such a controller fails while the cgroup still holds processes. Child cgroups alone do not trigger the rule; enabled controllers do, and the root cgroup is exempt. In a controlled subtree, processes therefore live in the leaves. To apply a two-level limit, create a parent cgroup, enable the controllers there, and put the processes in a child cgroup; the parent's limit files then bound the whole subtree. This rule prevents one cgroup from being both limited directly and having limited children.

Going deeperExplore the mechanism

Threaded controllers. By default a cgroup is a domain cgroup and holds whole processes. Writing threaded to cgroup.type makes it part of a threaded subtree, where individual threads of one process may be spread across cgroups so a threaded controller (cpu, cpuset, perf_event or pids) can account per thread. Constraints: the nearest domain cgroup above becomes the threaded domain, which carries the domain resources of the whole subtree; only threaded controllers can be enabled inside the threaded subtree; and the threaded domain cannot also have populated child cgroups that are not threaded.

Going deeperExplore the mechanism

Memory pressure (PSI). /proc/pressure/cpu, /proc/pressure/memory and /proc/pressure/io report the share of time tasks were stalled waiting for a resource, as some and full averages over 10s, 60s and 300s windows. Each cgroup exposes the same data in its cpu.pressure, memory.pressure and io.pressure files. A rising memory.pressure while memory.current is still below memory.max means the cgroup is already stalling, which is the signal an autoscaler should read before the OOM killer fires.

Going deeperExplore the mechanism

cgroup eBPF. BPF programs can attach directly to a cgroup with the BPF_CGROUP_* attach types (for example cgroup_skb for socket traffic, cgroup_device for device access) to observe or deny per-cgroup behaviour. A program can learn the current task's cgroup with bpf_get_current_cgroup_id() and iterate a cgroup's tasks. Container runtimes and security policies use this to enforce per-cgroup rules without parsing the cgroupfs files.

The next lesson, "Seccomp, capabilities and the mini container", combines these limits with syscall filtering and the privileges covered earlier to assemble a working container.

Key takeaways

  • cgroup v2 uses one hierarchy at /sys/fs/cgroup; controllers are enabled per subtree through cgroup.subtree_control
  • memory.max, cpu.max and pids.max are limit files; writing a value applies it to every process in the cgroup
  • memory.max is enforced by reclaim first and the OOM killer second; memory.swap.max=0 makes the limit deterministic
  • systemd manages the default cgroup v2 tree; Delegate=yes or systemd-run hands limits and a subtree to another manager
Reflect
  1. Explain to a colleague, in two sentences: create a cgroup on the unified hierarchy and move a process into it
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close