Skip to main content

sim_platform_linux/
cgroup_limits.rs

1// SPDX-License-Identifier: MPL-2.0
2// This Source Code Form is subject to the terms of the Mozilla Public
3// License, v. 2.0. If a copy of the MPL was not distributed with this
4// file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
6//! Finite cgroup v2 accounting values and the protected-tree ceiling.
7//!
8//! These types record a selected limit. They do not open a cgroup, write a
9//! controller file, or start a process.
10
11use std::io;
12
13/// Hard maximum of directories plus files in one pinned read-only tree.
14pub const MAXIMUM_PINNED_BOOT_TREE_ENTRIES: usize = 4096;
15
16/// Hard maximum of logical file bytes in one pinned read-only tree.
17pub const MAXIMUM_PINNED_BOOT_TREE_BYTES: usize = 256 * 1024 * 1024;
18
19/// `LONG_MAX`. A 64-bit page counter uses `LONG_MAX / PAGE_SIZE`, and that
20/// page count is the unlimited `max` setting.
21const SIGNED_LONG_MAX: u64 = (1_u64 << 63) - 1;
22
23/// Base pages a 64-bit Linux kernel can select: 4 KiB, 16 KiB, and 64 KiB.
24const SUPPORTED_BASE_PAGES: [u64; 3] = [4 * 1024, 16 * 1024, 64 * 1024];
25
26const fn finite_page_bytes(page: u64) -> u64 {
27    (SIGNED_LONG_MAX / page) * page - 1
28}
29
30/// Largest memory or swap byte count that stays finite on every supported page.
31const MAXIMUM_FINITE_MEMORY_BYTES: u64 = {
32    let mut ceiling = finite_page_bytes(SUPPORTED_BASE_PAGES[0]);
33    let mut index = 1;
34    while index < SUPPORTED_BASE_PAGES.len() {
35        let finite = finite_page_bytes(SUPPORTED_BASE_PAGES[index]);
36        if finite < ceiling {
37            ceiling = finite;
38        }
39        index += 1;
40    }
41    ceiling
42};
43
44/// `min_bw_quota_period_us` and `max_bw_quota_period_us`, in microseconds.
45const MINIMUM_CPU_USEC: u64 = 1_000;
46const MAXIMUM_CPU_PERIOD_US: u64 = 1_000_000;
47
48/// `MAX_BW` at `BW_SHIFT` 20. A quota above this is rejected by the scheduler.
49const MAXIMUM_CPU_QUOTA_US: u64 = (1_u64 << (64 - 20)) - 1;
50
51/// Standard 64-bit `PID_MAX_LIMIT`. Numeric `pids.max` must be below
52/// `PID_MAX_LIMIT + 1`.
53const MAXIMUM_FINITE_TASKS: u64 = 4 * 1024 * 1024;
54
55/// Exact Linux controller values, in kernel accounting units.
56#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub struct CgroupV2Limits {
58    /// Aggregate CPU microseconds available per scheduling period.
59    pub cpu_quota_us: u64,
60    /// Scheduling period in microseconds, not a total CPU-time budget.
61    pub cpu_period_us: u64,
62    /// Extra CPU burst allowance in microseconds.
63    pub cpu_burst_us: u64,
64    /// Charged-memory hard-limit setting, with kernel reclaim semantics.
65    pub memory_bytes: u64,
66    /// Separate swap hard-limit setting; zero prohibits swap.
67    pub swap_bytes: u64,
68    /// Descendant task hard-limit setting; threads count separately.
69    pub tasks: u64,
70    /// Whether the kernel treats the group as an indivisible workload.
71    pub group_oom_kill: bool,
72}
73
74impl CgroupV2Limits {
75    /// Checks one named child selection against its parent without native I/O.
76    ///
77    /// # Errors
78    /// Refuses an empty or non-lowercase name, a non-finite limit, burst, a
79    /// disabled group workload, or a child that exceeds its parent.
80    pub fn admit_child(name: &str, child: Self, parent: Self) -> io::Result<()> {
81        finite(name, child)?;
82        finite("parent", parent)?;
83        if child.memory_bytes > parent.memory_bytes
84            || child.swap_bytes > parent.swap_bytes
85            || child.tasks > parent.tasks
86            || u128::from(child.cpu_quota_us) * u128::from(parent.cpu_period_us)
87                > u128::from(parent.cpu_quota_us) * u128::from(child.cpu_period_us)
88        {
89            return Err(invalid("child limits exceed the parent selection"));
90        }
91        Ok(())
92    }
93}
94
95fn finite(name: &str, limits: CgroupV2Limits) -> io::Result<()> {
96    if name.is_empty()
97        || name.len() > 64
98        || !name
99            .bytes()
100            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
101        || !(MINIMUM_CPU_USEC..=MAXIMUM_CPU_QUOTA_US).contains(&limits.cpu_quota_us)
102        || !(MINIMUM_CPU_USEC..=MAXIMUM_CPU_PERIOD_US).contains(&limits.cpu_period_us)
103        || limits.cpu_burst_us != 0
104        || limits.memory_bytes == 0
105        || limits.memory_bytes > MAXIMUM_FINITE_MEMORY_BYTES
106        || limits.swap_bytes > MAXIMUM_FINITE_MEMORY_BYTES
107        || limits.tasks == 0
108        || limits.tasks > MAXIMUM_FINITE_TASKS
109        || !limits.group_oom_kill
110    {
111        return Err(invalid("cgroup selection is not finite"));
112    }
113    Ok(())
114}
115
116fn invalid(message: &str) -> io::Error {
117    io::Error::new(io::ErrorKind::InvalidInput, message)
118}
119
120#[cfg(test)]
121mod tests {
122    use super::{CgroupV2Limits, MAXIMUM_PINNED_BOOT_TREE_BYTES, MAXIMUM_PINNED_BOOT_TREE_ENTRIES};
123
124    fn limits() -> CgroupV2Limits {
125        CgroupV2Limits {
126            cpu_quota_us: 100_000,
127            cpu_period_us: 100_000,
128            cpu_burst_us: 0,
129            memory_bytes: 268_435_456,
130            swap_bytes: 0,
131            tasks: 32,
132            group_oom_kill: true,
133        }
134    }
135
136    #[test]
137    fn child_selection_refuses_nonfinite_limits_and_a_child_over_its_parent() {
138        CgroupV2Limits::admit_child("query-1", limits(), limits()).unwrap();
139        let mut burst = limits();
140        burst.cpu_burst_us = 1;
141        assert!(CgroupV2Limits::admit_child("query-1", burst, limits()).is_err());
142        let mut child = limits();
143        child.memory_bytes = limits().memory_bytes + 1;
144        assert!(CgroupV2Limits::admit_child("query-1", child, limits()).is_err());
145        assert!(CgroupV2Limits::admit_child("Query", limits(), limits()).is_err());
146
147        let mut unlimited = limits();
148        unlimited.memory_bytes = u64::MAX;
149        assert!(CgroupV2Limits::admit_child("query-1", unlimited, unlimited).is_err());
150        unlimited = limits();
151        unlimited.swap_bytes = u64::MAX;
152        assert!(CgroupV2Limits::admit_child("query-1", unlimited, unlimited).is_err());
153
154        let finite_max = ((1_u64 << 63) - 1) / 65_536 * 65_536 - 1;
155        assert_eq!(finite_max, 9_223_372_036_854_710_271);
156        let mut edge = limits();
157        edge.memory_bytes = finite_max;
158        edge.swap_bytes = finite_max;
159        CgroupV2Limits::admit_child("query-1", edge, edge).unwrap();
160        edge.memory_bytes = finite_max + 1;
161        assert!(CgroupV2Limits::admit_child("query-1", edge, edge).is_err());
162        edge.memory_bytes = finite_max;
163        edge.swap_bytes = finite_max + 1;
164        assert!(CgroupV2Limits::admit_child("query-1", edge, edge).is_err());
165        let four_kib_only = ((1_u64 << 63) - 1) / 4096 * 4096 - 1;
166        assert_eq!(four_kib_only, 9_223_372_036_854_771_711);
167        edge.swap_bytes = finite_max;
168        edge.memory_bytes = four_kib_only;
169        assert!(CgroupV2Limits::admit_child("query-1", edge, edge).is_err());
170
171        let mut quota = limits();
172        quota.cpu_quota_us = 1;
173        assert!(CgroupV2Limits::admit_child("query-1", quota, quota).is_err());
174        quota.cpu_quota_us = 1_000;
175        CgroupV2Limits::admit_child("query-1", quota, quota).unwrap();
176        quota.cpu_quota_us = (1_u64 << 44) - 1;
177        CgroupV2Limits::admit_child("query-1", quota, quota).unwrap();
178        quota.cpu_quota_us = 1_u64 << 44;
179        assert!(CgroupV2Limits::admit_child("query-1", quota, quota).is_err());
180
181        let mut tasks = limits();
182        tasks.tasks = 4 * 1024 * 1024;
183        CgroupV2Limits::admit_child("query-1", tasks, tasks).unwrap();
184        tasks.tasks = 4 * 1024 * 1024 + 1;
185        assert!(CgroupV2Limits::admit_child("query-1", tasks, tasks).is_err());
186        tasks.tasks = u64::MAX;
187        assert!(CgroupV2Limits::admit_child("query-1", tasks, tasks).is_err());
188    }
189
190    #[test]
191    fn protected_tree_ceiling_is_the_shared_bound() {
192        assert_eq!(MAXIMUM_PINNED_BOOT_TREE_ENTRIES, 4096);
193        assert_eq!(MAXIMUM_PINNED_BOOT_TREE_BYTES, 256 * 1024 * 1024);
194    }
195}