Skip to content
Merged
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,15 @@ This file records each release. The format follows [Keep a Changelog](https://ke
### Fixed

- nf_tables: the batch and the programs of the base chains share the elements of the sets. A batch copies a set only at its first change, and a commit makes the program data of a set again only when the set changed. Before, each batch begin copied each element of each table, and each commit copied each set that a base chain used into each program (#542).
- A thread of a cgroup over `memory.high` now takes back at the return to user mode only the pages that its cgroup charged over the limit since the last wait, as `reclaim_high` of Linux takes back `memcg_nr_pages_over_high`. Before, it took at least 64 pages also after a fault of one page. A write to swap keeps the CPU busy until the disk completes, so the workers of `stress-ng --vm` in TEST-55-OOMD of systemd kept both CPUs busy, and the workers that systemd-oomd killed took up to 38 seconds to exit. (#752)
- The reclaim of anonymous memory now looks at the address space in steps of 2 MiB and stops when it has enough pages, as `walk_page_range` of Linux. Before, each reclaim first collected each mapped page from its start to the end of the space. For the 10 workers of `stress-ng --vm 10 --vm-bytes 200M` in a cgroup over `memory.high`, this kept each CPU in the kernel, and PID1 did not answer `systemctl` for 25 seconds in TEST-55-OOMD of systemd. (#752)
- The reclaim of anonymous memory now goes on from the page after the last page that it took, as `swap_address` of Linux 2.4. Before, each reclaim looked at the address space again from address 0, so it looked at the same pages that cannot go each time. A cgroup over `memory.high` then used minutes of CPU in the reclaim, and because the kernel is not preemptive, PID1 did not get the CPU and `systemctl` timed out. (#752)
- The reclaim of a thread for `memory.high`, for `memory.max` and for a system that is short of memory now counts as a memory stall in the pressure (PSI) of its cgroup, as `psi_memstall_enter` of Linux around a reclaim. Before, only the wait after the reclaim counted, so the pressure stayed low while a cgroup did a lot of reclaim, and systemd-oomd did not kill it. TEST-55-OOMD of systemd needs this. (#752)
- A cgroup over `memory.high` now takes back pages and makes its threads wait once for each batch of 64 pages that it charged over the limit, as Linux charges in batches of `MEMCG_CHARGE_BATCH`. Before, a thread did a reclaim after each fault of one page, and the wait for a part of a batch was shorter than 10 ms, so no thread waited. The workers of `stress-ng --vm` in TEST-55-OOMD of systemd then kept the CPUs busy and the pressure "full" of the cgroup stayed near 0. (#752)
- The reclaim of anonymous memory now skips for up to 1 second an address space that had no page to give at the last look and has the same number of pages. Before, each reclaim of a cgroup looked at each page of each sleeping process of the cgroup again. In TEST-55-OOMD of systemd the reclaim looked at 9000 pages for each page that it took. (#752)
- The read of a page back from swap at a fault now counts as a memory stall in the pressure (PSI) of the cgroup of the thread, as `swap_read_folio` of Linux counts the read of a page of the working set. Before, a thread that waited for swap counted as a thread that ran, and the pressure "full" stayed low while all threads of a cgroup waited for swap. (#752)
- One read or write of the swap areas now runs at a time, and the other tasks that want to do swap I/O sleep until their turn, as a task of Linux sleeps in `submit_bio_wait`. Before, they spun on the lock of the disk driver. When the workers of `stress-ng --vm` in TEST-55-OOMD of systemd thrashed, both CPUs then spun for the disk, and `systemctl` and the killed workers did not get a CPU. (#752)
- A thread with a kill now does not take back pages for `memory.high` at its return to user mode, and a fault of a thread with a kill does not reclaim and does not call the OOM killer, as Linux delivers the fatal signal before `mem_cgroup_handle_over_high` and `out_of_memory` gives true for a task in `task_will_free_mem`. Before, the killed workers of `stress-ng` in TEST-55-OOMD of systemd wrote pages to swap before they ended. (#752)

## [0.5.39] - 2026-11-22

Expand Down
54 changes: 42 additions & 12 deletions core/rk-cgroup/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1641,7 +1641,10 @@ impl Hierarchy {
/// The time in nanoseconds that a thread of `id` must wait because its cgroup or a cgroup
/// above it uses more than `memory.high`, as `mem_cgroup_handle_over_high` of Linux. The
/// wait grows with the square of the part of the use over the limit and with the pages that
/// the cgroup charged while over it. Sets the count of these pages to 0.
/// the cgroup charged while over it. A cgroup gives a wait only when these pages are a full
/// batch of `HIGH_BATCH` pages, as Linux charges and handles the pages in batches of
/// `MEMCG_CHARGE_BATCH`. Then the count of the pages goes to 0. The count also goes to 0
/// when the use is not over the limit.
pub fn high_delay(&mut self, id: CgId) -> u64 {
if !self.shared.any_over_high.load(Ordering::SeqCst) {
return 0;
Expand All @@ -1651,12 +1654,16 @@ impl Hierarchy {
let on = self.on(a, MEMORY);
let Some(n) = self.nodes.get(&a) else { continue };
let m = &n.c.mem;
let charged = m.over_high.swap(0, Ordering::SeqCst);
let (current, high) =
(m.current.load(Ordering::Relaxed), m.high.load(Ordering::Relaxed));
if !on || high == MAX || current <= high || high == 0 {
m.over_high.store(0, Ordering::SeqCst);
continue;
}
if m.over_high.load(Ordering::SeqCst) < HIGH_BATCH * PAGE_SIZE {
continue;
}
let charged = m.over_high.swap(0, Ordering::SeqCst);
// The part over the limit in units of 2^-20, `calculate_overage` of Linux.
let over = ((current - high) << 20) / high;
overage = overage.max(over);
Expand All @@ -1668,10 +1675,8 @@ impl Hierarchy {
if self.nodes.values().any(|n| n.c.mem.over_high.load(Ordering::SeqCst) > 0) {
self.shared.any_over_high.store(true, Ordering::SeqCst);
}
// `calculate_high_delay` of Linux, in nanoseconds instead of jiffies. Linux handles the
// pages in batches of `HIGH_BATCH`, and the limit is for one batch. Here a thread can
// come back after each page, so the limit is for a batch and the wait is for the part of
// a batch.
// `calculate_high_delay` of Linux, in nanoseconds instead of jiffies. The limit is for
// one batch of `HIGH_BATCH` pages.
let delay = (u128::from(overage) * u128::from(overage) * 1_000_000_000) >> 34;
let delay = delay.min(u128::from(HIGH_DELAY_MAX)) * u128::from(pages);
let delay = u64::try_from(delay / u128::from(HIGH_BATCH)).unwrap_or(HIGH_DELAY_MAX);
Expand Down Expand Up @@ -2611,9 +2616,14 @@ pub fn count_reclaim(id: CgId, who: Reclaimer, anon: bool, scanned: u64, stolen:

/// Takes back memory from `id` and each cgroup above it whose use is over `memory.high`, as
/// `reclaim_high` of Linux. Each of these cgroups gives the bytes that the subtree charged over
/// the limit, and at least `RECLAIM_BATCH`. The return to user mode calls this before
/// [`high_delay`], so the wait is for the use that the reclaim leaves.
pub fn reclaim_high(id: CgId) {
/// the limit since the last wait, as Linux takes back the `memcg_nr_pages_over_high` pages of
/// the task. A cgroup gives nothing until these bytes are a batch of `HIGH_BATCH` pages, as Linux
/// charges in batches of `MEMCG_CHARGE_BATCH` pages. One reclaim of a batch costs much less than
/// a reclaim for each page. The return to user mode calls this
/// before [`high_delay`], so the wait is for the use that the reclaim leaves. The reclaim counts
/// as a memory stall of the cgroup `stall` of the thread in the pressure, as `psi_memstall_enter`
/// of Linux around the reclaim.
pub fn reclaim_high(id: CgId, stall: CgId) {
if id == 0 || !shared().any_over_high.load(Ordering::Relaxed) {
return;
}
Expand All @@ -2624,15 +2634,21 @@ pub fn reclaim_high(id: CgId) {
let high = a.mem.high.load(Ordering::Relaxed);
let current = a.mem.current.load(Ordering::Relaxed);
let charged = a.mem.over_high.load(Ordering::Relaxed);
(a.on(MEMORY) && high != MAX && current > high)
.then(|| (a.id, charged.max(RECLAIM_BATCH)))
(a.on(MEMORY) && high != MAX && current > high && charged >= HIGH_BATCH * PAGE_SIZE)
.then_some((a.id, charged))
})
.collect();
(over, Changed::default())
});
for (cg, bytes) in over.unwrap_or_default() {
let over = over.unwrap_or_default();
if over.is_empty() {
return;
}
psi_change(stall, |c| c.memstall += 1);
for (cg, bytes) in over {
reclaim_swap(cg, bytes);
}
psi_change(stall, |c| c.memstall = c.memstall.saturating_sub(1));
}

/// Charges a page of memory to `id`. A charge past a `memory.max` first takes back page cache
Expand Down Expand Up @@ -2732,6 +2748,20 @@ pub fn high_delay(id: CgId) -> u64 {
if id == 0 || !shared().any_over_high.load(Ordering::Relaxed) {
return 0;
}
// Most returns to user mode come before a full batch. They do not take the lock of the
// hierarchy.
let due = with_counters(id, |c, _| {
let due = c.path().any(|a| {
let charged = a.mem.over_high.load(Ordering::Relaxed);
let high = a.mem.high.load(Ordering::Relaxed);
charged >= HIGH_BATCH * PAGE_SIZE
|| (charged > 0 && a.mem.current.load(Ordering::Relaxed) <= high)
});
(due, Changed::default())
});
if due != Some(true) {
return 0;
}
with(|h| h.high_delay(id))
}

Expand Down
44 changes: 42 additions & 2 deletions core/rk-cgroup/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -477,14 +477,54 @@ fn memory_high_makes_a_delay_that_grows_with_the_use() {
// Twice the limit gives the longest wait.
h.charge_memory(a, (1 << 20) - PAGE_SIZE).unwrap();
assert_eq!(h.high_delay(a), HIGH_DELAY_MAX);
// The wait is for the pages that the cgroup charged since the last wait.
// The wait is for the pages that the cgroup charged since the last wait, in batches of
// `HIGH_BATCH` pages.
assert_eq!(h.high_delay(a), 0);
h.charge_memory(a, PAGE_SIZE).unwrap();
assert_eq!(h.high_delay(a), HIGH_DELAY_MAX / HIGH_BATCH);
assert_eq!(h.high_delay(a), 0);
h.charge_memory(a, (HIGH_BATCH - 1) * PAGE_SIZE).unwrap();
assert_eq!(h.high_delay(a), HIGH_DELAY_MAX);
assert_eq!(h.high_delay(a), 0);
let events = h.read(a, "memory.events", 0).unwrap();
assert!(events.starts_with("low 0\nhigh "), "{events}");
}

#[test]
fn memory_high_counts_the_pages_over_the_limit_only_while_the_use_is_over_it() {
let mut h = Hierarchy::new(0, 1);
h.write(ROOT, "cgroup.subtree_control", b"+memory", 0).unwrap();
let a = h.mkdir(ROOT, b"a", 0).unwrap();
h.write(a, "memory.high", b"1M", 0).unwrap();
h.charge_memory(a, 1 << 20).unwrap();
h.charge_memory(a, (HIGH_BATCH - 1) * PAGE_SIZE).unwrap();
assert_eq!(h.high_delay(a), 0);
// The use goes under the limit, and the pages over it do not count after that.
h.uncharge_memory(a, HIGH_BATCH * PAGE_SIZE);
assert_eq!(h.high_delay(a), 0);
h.charge_memory(a, 2 * PAGE_SIZE).unwrap();
h.write(a, "memory.high", b"512K", 0).unwrap();
assert_eq!(h.high_delay(a), 0);
// A full batch at twice the limit gives the longest wait.
h.charge_memory(a, (HIGH_BATCH - 2) * PAGE_SIZE).unwrap();
assert_eq!(h.high_delay(a), HIGH_DELAY_MAX);
}

#[test]
fn memory_high_wait_of_a_batch_grows_with_the_square_of_the_use_over_the_limit() {
let mut h = Hierarchy::new(0, 1);
h.write(ROOT, "cgroup.subtree_control", b"+memory", 0).unwrap();
let a = h.mkdir(ROOT, b"a", 0).unwrap();
h.write(a, "memory.high", b"64M", 0).unwrap();
h.charge_memory(a, 64 << 20).unwrap();
// A batch at 1/256 over the limit gives 1/1024 s, less than the shortest wait.
h.charge_memory(a, HIGH_BATCH * PAGE_SIZE).unwrap();
assert_eq!(h.high_delay(a), 0);
// At 1/64 over the limit a batch gives 1/64 s, as `calculate_high_delay` of Linux gives
// HZ / 64. The wait is for the 3 batches since the last wait.
h.charge_memory(a, 3 * HIGH_BATCH * PAGE_SIZE).unwrap();
assert_eq!(h.high_delay(a), 3 * 1_000_000_000 / 64);
}

#[test]
fn memory_oom_group_gives_the_highest_group() {
let mut h = Hierarchy::new(0, 1);
Expand Down
75 changes: 75 additions & 0 deletions core/rk-mm/src/idle.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
//! The mark of an address space that the reclaim of anonymous memory found with no page to take.
//!
//! The reclaim of a memory cgroup looks at each process of the cgroup in turn. A process that
//! only sleeps, or whose pages `fork` shares with its children, has no page that can go. Linux
//! takes pages from the LRU lists of the cgroup and does not look at such a process again and
//! again. Here the reclaim looks at the page tables, so it skips a space that had no page to give
//! at the last look and that has the same number of pages now. The mark is good for
//! [`IDLE_NS`] only, because a page can become a page of only one space without a fault of
//! this space, for example when a child exits.

use core::sync::atomic::{AtomicU64, AtomicUsize, Ordering};

/// The time in nanoseconds for which a mark stays good.
pub const IDLE_NS: u64 = 1_000_000_000;

/// The mark. The pages are one more than the number of pages of the space at the look, and 0
/// when the space has no mark.
#[derive(Default)]
pub struct Idle {
pages: AtomicUsize,
at: AtomicU64,
}

impl Idle {
/// Marks the space, which has `pages` pages at the time `now` and no page to give.
pub fn mark(&self, pages: usize, now: u64) {
self.at.store(now, Ordering::Relaxed);
self.pages.store(pages.saturating_add(1), Ordering::Relaxed);
}

/// Removes the mark.
pub fn clear(&self) {
self.pages.store(0, Ordering::Relaxed);
}

/// Tells if the reclaim can skip the space, which has `pages` pages at the time `now`.
pub fn skip(&self, pages: usize, now: u64) -> bool {
self.pages.load(Ordering::Relaxed) == pages.saturating_add(1)
&& now.saturating_sub(self.at.load(Ordering::Relaxed)) < IDLE_NS
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn a_space_with_no_mark_is_not_skipped() {
let idle = Idle::default();
assert!(!idle.skip(0, 0));
assert!(!idle.skip(5, 100));
}

#[test]
fn a_marked_space_is_skipped_while_its_pages_stay_the_same() {
let idle = Idle::default();
idle.mark(10, 1000);
assert!(idle.skip(10, 1000));
assert!(idle.skip(10, 1000 + IDLE_NS - 1));
// A fault or an unmap changes the pages, and the reclaim looks again.
assert!(!idle.skip(11, 1000));
assert!(!idle.skip(9, 1000));
}

#[test]
fn a_mark_ends_after_its_time_or_a_clear() {
let idle = Idle::default();
idle.mark(0, 1000);
assert!(idle.skip(0, 1000));
assert!(!idle.skip(0, 1000 + IDLE_NS));
idle.mark(3, 5);
idle.clear();
assert!(!idle.skip(3, 5));
}
}
3 changes: 2 additions & 1 deletion core/rk-mm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
extern crate alloc;

pub mod hugetlb;
pub mod idle;
pub mod ksm;
pub mod pttree;
pub mod rangelog;
Expand All @@ -27,7 +28,7 @@ mod space;
#[cfg(all(target_os = "none", any(target_arch = "x86_64", target_arch = "aarch64")))]
pub use space::{
Access, AddressSpace, FileRef, MMAP_MIN_ADDR, MMAP_TOP, MmFile, MmapRequest, Remap, STACK_SIZE,
STACK_TOP, WriteMap, set_populate_hook,
STACK_TOP, WriteMap, set_memstall_hook, set_populate_hook,
};
pub use vma::{Backing, HugeAdvice, PAGE_SIZE, Prot, STACK_GUARD_GAP, Vma, VmaKind, VmaSet};

Expand Down
Loading
Loading