Skip to content

mm: accept madvise(MADV_FREE) on private anonymous mappings - #15014

Open
hugelgupf wants to merge 1 commit into
gvisor:masterfrom
hugelgupf:pr/madv-free
Open

hugelgupf wants to merge 1 commit into
gvisor:masterfrom
hugelgupf:pr/madv-free

Conversation

@hugelgupf

@hugelgupf hugelgupf commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

madvise(MADV_FREE) returns EINVAL for every mapping. Allocators such as jemalloc and Ruby's fiber pool use it to tell the kernel that freed pages may be discarded, and on EINVAL they fall back to a slower purge path or keep the memory. This change accepts MADV_FREE on private anonymous mappings and frees the pages at the call, as MADV_DONTNEED does. That is within the MADV_FREE contract (the kernel may free the pages at any time), and Linux 4.5 to 4.11 did the same on systems without swap.

Linux Fidelity

  • mm/madvise.c:madvise_free_single_vma(): EINVAL unless vma_is_anonymous(), so file-backed and shared anonymous mappings return EINVAL.
  • mm/madvise.c:madvise_dontneed_free_valid_vma(): EINVAL for locked mappings (same check as MADV_DONTNEED).

Divergences:

  • Pages are freed at the call, not at memory-pressure reclaim: old contents read as zeros right away and RSS drops immediately.
  • No LazyFree accounting in /proc/[pid]/smaps.

Comment thread pkg/sentry/syscalls/linux/sys_mmap.go Outdated
Comment on lines +220 to +224
case linux.MADV_FREE:
// Linux accepts MADV_FREE on private anonymous mappings. Pages may
// remain until reclaim; gVisor has no lazy reclaim path, so Decommit
// frees them immediately, which MADV_FREE allows.
return 0, nil, t.MemoryManager().DecommitMadvFree(addr, length)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

MADV_FREE is supposed to be async and asks the kernel to lazily free the range, while MADV_DONTNEED is sync and asks the kernel to free pages immediately. I don't think we should symlink MADV_FREE into MADV_DONTNEED like this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's not an illegal change. In fact, Linux itself supported MADV_FREE like this on swapless systems (or systems where swap was full) between 4.5 and 4.11 (2016-2017):

The contract of MADV_FREE is that the kernel can lazily reclaim, but can reclaim at any time.

Bug-for-bug implementation would require a notion of memory pressure in gVisor, with memory.max set, and things that gVisor isn't tracking today. Meanwhile, this is kinda cheap and easy to implement the feature.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree that this is a valid implementation of MADV_FREE. I have an old implementation of MADV_FREE that used pgalloc evictable ranges to delay MADV_FREE, but it was measurably slower than synchronous MADV_FREE (what this commit does) or leaving it unimplemented.

Comment thread pkg/sentry/syscalls/linux/sys_mmap.go Outdated
case linux.MADV_FREE:
// Linux accepts MADV_FREE on private anonymous mappings. Pages may
// remain until reclaim; gVisor has no lazy reclaim path, so Decommit
// frees them immediately, which MADV_FREE allows.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing in this comment is relevant to the code here, it's just staleness bait. Delete it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, removed.

Comment thread pkg/sentry/mm/syscalls.go Outdated
if vma.mlockMode != memmap.MLockNone {
return linuxerr.EINVAL
}
if madvFree && (vma.mappable != nil || !vma.private) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shared anonymous mappings have a non-nil mappable, so I think only the vma.mappable != nil check is required.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, shared anon gets a tmpfs zero file as its mappable, so vma.mappable != nil covers it. Dropped the !vma.private check; RejectsSharedAnonMapping still passes with only the mappable check. Added the madvise_free_single_vma() / vma_is_anonymous() cite next to that EINVAL.

Comment thread pkg/sentry/mm/syscalls.go Outdated
// DecommitMadvFree implements madvise(MADV_FREE): same decommit as
// MADV_DONTNEED, but only for private anonymous mappings. Linux returns EINVAL
// for file-backed and shared mappings (mm/madvise.c:madvise_dontneed_free).
func (mm *MemoryManager) DecommitMadvFree(addr hostarch.Addr, length uint64) error {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Name this method MadviseFree and only describe it as implementing madvise(MADV_FREE). If you want to document that this currently decommits memory synchronously, do so in the function body rather than the function comment since it's not contractual (we could change this transparently in the future). If you want to document that the behavior on file-backed and shared mappings is consistent with Linux, it would be better to do so where EINVAL is actually returned in MM.decommit() (and the correct function to cite is mm/madvise.c:madvise_free_single_vma(), which actually checks vma_is_anonymous().)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: renamed to MadviseFree. The doc comment now just says it implements madvise(MADV_FREE), and the note that it currently decommits synchronously is in the body.

Comment thread pkg/sentry/syscalls/linux/sys_mmap.go Outdated
Comment on lines +220 to +224
case linux.MADV_FREE:
// Linux accepts MADV_FREE on private anonymous mappings. Pages may
// remain until reclaim; gVisor has no lazy reclaim path, so Decommit
// frees them immediately, which MADV_FREE allows.
return 0, nil, t.MemoryManager().DecommitMadvFree(addr, length)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree that this is a valid implementation of MADV_FREE. I have an old implementation of MADV_FREE that used pgalloc evictable ranges to delay MADV_FREE, but it was measurably slower than synchronous MADV_FREE (what this commit does) or leaving it unimplemented.

@EtiennePerot EtiennePerot added this to the Lightspeed milestone Oct 22, 2026
@EtiennePerot

Copy link
Copy Markdown
Member

Tried to look for regressions here, I'm manually going over pgalloc PRs that may have a perf impact since we don't have good benchmark tests. Claude found some regressions here, I rewrote and simplified the below.

Setup: PR rebased on fresh master, c4-standard-16 with COS 129 (Linux 6.12), systrap.

Who calls MADV_FREE

  • jemalloc 5.0/5.1 (muzzy_decay_ms = 10 s), e.g. Redis 6.0/6.2 (bundled jemalloc 5.1.0) and Debian buster's libjemalloc2. On EINVAL, decayed extents skip the muzzy cache and take the forced-purge/retained path (pac_decay_stashed()).
  • Ruby >= 2.7's fiber pool. cont.c:fiber_pool_stack_free() calls madvise(MADV_FREE) on every fiber stack release and ignores errors, with no DONTNEED fallback. On x86_64 the pool's stack allocations are never unmapped. So on master, fiber stack memory is never returned, and it is reused without faulting.
  • Go with GODEBUG=madvdontneed=0.

Three arms: master (EINVAL), this PR (synchronous decommit), and an "accept, keep pages" suggested variant (validate, then return 0)

workload metric master this PR keep-pages Linux (runc)
Ruby 3.0, 200k Fiber.new+resume fibers/s 219k 25.7k (0.117x [0.102, 0.123]) 241k (1.10x, p=0.07) 421k
host page faults 39k 530k (13.7x) 38k 21k
Ruby, 5000 live fibers, then all finished, idle memory when idle 235 MB 60 MB (0.255x) 235 MB 215 MB anon, of which 180 MB LazyFree
jemalloc 5.3, muzzy_decay_ms:5000, 8-thread malloc churn ops/s 1.42M 1.82M (1.275x [1.18, 1.34]) 1.81M (1.270x) 2.09M
host page faults 5.9M 3.5M (0.59x) 3.4M (0.58x) 3.9M
peak memory 1430 MB 1454 MB (+1.6%) 1468 MB (+2.6%) 1450 MB
Go, GODEBUG=madvdontneed=0, churn ops/s 103k 104k (1.00x) 127k (1.23x [1.17, 1.27]) 150k
memory after 10 s idle 169 MB 168 MB 272 MB (1.61x) 221-279 MB (lazyfree)

Additionally, fs:rubydev (in //test/benchmarks) regresses by 4.3-5.9% with this PR.

The "suggested" variant is a lazy middle-ground which would get both the speed and the reclaim:

  • On MADV_FREE, record the range as lazily freed and write-protect it in the AddressSpace.
  • A later write fault clears the mark: redirtying cancels the free.
  • Pages still marked get decommitted later: when the MemoryFile is under pressure (e.g. via pgalloc's eviction machinery), during an idle reclaim pass, or by skipping them at checkpoint.

The cost is one host mprotect per MADV_FREE, plus one sentry fault per redirtied page, instead of decommit + fault + zero-fill.

@hugelgupf

Copy link
Copy Markdown
Contributor Author

@EtiennePerot @nixprime I see Etienne's benchmark, but also Jamie's note that delayed free's were slower.

runsc appears to not consume host memory pressure signals (loader.go#L1240 (https://github.com/google/gvisor/blob/3fdb673dc0a300a9a975ce3f5d356f285687c1e9/runsc/boot/loader.go#L1240)), so DelayedEviction evicts as soon as the releaser goroutine is idle. A MarkEvictable-based MADV_FREE would probably usually evict before the app reuses the page, so it pays the same refault as synchronous decommit, plus the write-protect and mprotect overhead. That would fit Jamie's result that his lazy version was slower.

Thoughts?

@hugelgupf

Copy link
Copy Markdown
Contributor Author

I went with the synchronous for now still... but we can switch gears if y'all want.

@hugelgupf

Copy link
Copy Markdown
Contributor Author

ping @EtiennePerot and @nixprime

@hugelgupf

Copy link
Copy Markdown
Contributor Author

@nixprime @EtiennePerot friendly ping on this: v2 (synchronous MADV_FREE) has been up since 10-23, now signed off for DCO. Happy to change direction if you'd rather handle it differently.


🤖 Posted by an AI agent (Cursor · skill none) on behalf of @hugelgupf.

@hugelgupf
hugelgupf force-pushed the pr/madv-free branch 2 times, most recently from be23ab1 to d07036f Compare November 20, 2026 06:03
madvise(MADV_FREE) returns EINVAL for every mapping. Allocators such as
jemalloc and Ruby's fiber pool use MADV_FREE to tell the kernel that
freed pages may be discarded; on EINVAL they fall back to a slower purge
path or keep the memory.

Accept MADV_FREE on private anonymous mappings and decommit the range
synchronously, as for MADV_DONTNEED. MADV_FREE allows the kernel to free
the pages at any time, and Linux 4.5 to 4.11 did the same on systems
without swap. Data written after the call is kept: it lands on a fresh
zero-filled page.

Linux fidelity: mm/madvise.c:madvise_free_single_vma() returns EINVAL
for any vma that is not vma_is_anonymous(), so file-backed and shared
anonymous mappings return EINVAL; madvise_dontneed_free_valid_vma()
returns EINVAL for locked mappings, which the existing MADV_DONTNEED
check already covers. Divergence: pages are freed at the call instead of
at memory-pressure reclaim, so their old contents read as zeros right
away and RSS drops immediately; smaps has no LazyFree accounting.

Tests: MadviseFreeTest.AcceptsPrivateAnonPage fails with EINVAL without
the change and passes with it. RejectsPrivateFileMapping and
RejectsSharedAnonMapping fail if the anonymous-mapping check is removed.
madvise_test passes on native, runsc_ptrace and runsc_systrap_directfs,
each with _save and _save_resume; //pkg/sentry/mm:mm_test passes.

Assisted-by: Cortex Code
Signed-off-by: Chris Koch <[email protected]>

@shayonj shayonj left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

claude on behalf of shayon

I took a look but remain conflicted. Perhaps someone else with more exposure can chime in.

switch adv {
case linux.MADV_DONTNEED:
return 0, nil, t.MemoryManager().Decommit(addr, length)
case linux.MADV_FREE:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I took it for a spin and noticed fs:rubydev goes from 28.0s to 29.9s on systrap and from 32.3s to 40.8s on KVM, rebased on current master. I wonder if freeing at the call can be cheap enough here, since app memory is a host memfd and the host can’t free shmem lazily. I also tried keeping the pmas and only punching the memfd, so reuse is a host fault instead of a sentry fault, but rubydev still came in at +6% on systrap and +25% on KVM.

Comment thread pkg/sentry/mm/syscalls.go
// +checklocksexclude:mm.activeMu
func (mm *MemoryManager) MadviseFree(addr hostarch.Addr, length uint64) error {
// MADV_FREE permits the kernel to free the pages at any time, so this
// currently decommits them synchronously, as for MADV_DONTNEED.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking at the callers, I’m wondering if leaving the pages in place would be the better shape. Ruby’s fiber pool and musl’s mallocng ignore the result, so they already keep these pages on master, while Go with madvdontneed=0 and jemalloc’s boot probe act on it. With pages kept, rubydev was 28.4s on systrap and 32.2s on KVM, and jemalloc kept the same gain. The cost is that callers that fall back to MADV_DONTNEED today lose that reclaim under a memory limit.

Comment thread pkg/sentry/mm/syscalls.go
//
// +checklocksexclude:mm.mappingMu
// +checklocksexclude:mm.activeMu
func (mm *MemoryManager) MadviseFree(addr hostarch.Addr, length uint64) error {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I noticed that dropping the pma lets a pinned range, such as one from nvproxy or vfio, diverge from the app after MADV_FREE, because the app refaults onto a new page. Linux skips pages that have extra references, so they stay shared.

case linux.MADV_DONTNEED:
return 0, nil, t.MemoryManager().Decommit(addr, length)
case linux.MADV_FREE:
return 0, nil, t.MemoryManager().MadviseFree(addr, length)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Small one: the madvise entries in linux64.go don’t mention MADV_FREE yet.

@carzh
carzh removed their request for review November 23, 2026 23:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants