From b7ae3bd9672e7e1a3fc8e75d90b5bcbe75e6febf Mon Sep 17 00:00:00 2001 From: Benedikt Peetz Date: Mon, 19 May 2025 21:29:54 +0200 Subject: [PATCH 3/3] memory: Avoid estimating available memory, use kernel estimate instead `free`, `btop` and other tools (like the `sysinfo` rust library) use `mem_total - mem_avail` to calculate the used memory. As explained in the already linked [kernel commit][1], `mem_avail` is an estimate of the available memory based on the current way the kernel handles memory. The previous logic for calculating used memory tried to estimate this based on `mem_free`, `buffers`, `pagecache` and `reclaimable`. Unfortunately, as the kernel commit message predicts, this user space estimate bitrots, as the kernel memory usage patterns change. Thus, we now simply use the kernel estimate `mem_avail` as we know that that is in-sync with the relevant kernel internals. [1]: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773 --- src/blocks/memory.rs | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/src/blocks/memory.rs b/src/blocks/memory.rs index 8cf32f9ba..94d8a5fe3 100644 --- a/src/blocks/memory.rs +++ b/src/blocks/memory.rs @@ -145,13 +145,9 @@ pub async fn run(config: &Config, api: &CommonApi) -> Result<()> { let buffers = mem_state.buffers as f64; - // same logic as htop - let used_diff = mem_free + buffers + pagecache + reclaimable; - let mem_used = if mem_total >= used_diff { - mem_total - used_diff - } else { - mem_total - mem_free - }; + // Userspace should use `mem_avail` for estimating the memory that is available. + // See: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=34e431b0ae398fc54ea69ff85ec700722c9da773 + let mem_used = mem_total - mem_avail; // account for ZFS ARC cache let mem_used = mem_used - zfs_shrinkable_size; -- 2.49.0