josefguenther opened PR #14714 from josefguenther:feat/memory-discard to bytecodealliance:main:
Closes #9572.
This adds
Memory::discard(store, start, count), the host API fitzgen sketched in #9572. It zeroes Wasm pages of a non-shared memory and gives them back to the OS where Wasmtime owns the mapping. Likegrowandsize, it counts in Wasm pages, so a range is always page-aligned. The memory's size and base pointer don't change, and the pages read as zeros if they are touched again. Linear memory can't shrink, so this lets an embedder whose guest allocator frees large spans return that memory instead of holding the guest's high-water mark until the instance is dropped.The separate
memory.discardproposal takes bytes and rounds them to whole pages; taking pages means nothing is rounded and is consistent with grow/size, so that's the approach I took.How it works:
- On Linux it calls
madvise(MADV_DONTNEED)on the pages. Other Unix platforms map fresh zeroed memory over them, and Windows decommits and recommits them.- If the memory was initialized from a copy-on-write image,
madviseon Linux would bring back the image's data instead of zeros. So that part gets fresh zeroed memory, and the slot drops the image at its next reset, as resets already do on other platforms. The next instance maps the image again.- Memories that Wasmtime doesn't map itself, such as a custom LinearMemory, are zeroed by writing. They read the same afterwards, but no memory is released.
- Pages out of bounds, or a memory with a custom page size, return an error. Shared memories aren't supported.
- The C API gets
wasmtime_memory_discardand the C++ APIMemory::discard, consistent with the rest.The tests cover each of these cases, including the Linux image case, and a C++ test covers the new binding. I ran the Rust tests on macOS and on x86_64 and aarch64 Linux, and the C API tests on macOS.
This is my first contribution to wasmtime and it's a larger one, so let me know if you have changes or concerns.
josefguenther requested fitzgen for a review on PR #14714.
josefguenther requested wasmtime-core-reviewers for a review on PR #14714.
github-actions[bot] added the label wasmtime:c-api on PR #14714.
github-actions[bot] added the label wasmtime:api on PR #14714.
:memo: fitzgen submitted PR review:
Thanks! Overall looks good to me, but I have a few comments/questions below.
:speech_balloon: fitzgen created PR review comment:
I realize this is a pre-existing comment, but it should end with "or restore the original mapping" as per
decommit_behaviorjust below.
:speech_balloon: fitzgen created PR review comment:
We should document that this method will trap when given out-of-bounds regions to discard, and that callers should have already done their own bounds checks.
:speech_balloon: fitzgen created PR review comment:
Isn't it the opposite? When we restore the original mapping we get the CoW image, not zeros.
:speech_balloon: fitzgen created PR review comment:
As just mentioned, we should match the proposed instruction and use bytes-rounded-to-pages rather than pages.
:speech_balloon: fitzgen created PR review comment:
Doc comment mentions
lenandoffsetbut the parameters arecountandstart.Also, I think we should match the proposed
memory.discardinstruction's parameters, which last time I looked was bytes that get rounded to page multiples of the memory's page size. I personally think the instruction should take pages instead of bytes, but that is a spec conversation to have, and not matching it in the wasmtime API would be even worse. We can always change this API if the instruction changes its operands.
:speech_balloon: fitzgen created PR review comment:
Why do we only need to reapply the pkey for the overlap and not for the anonymous ranges? Especially since the
DecommitBehavior::Zerobranch reapplies it to the whole range.
:speech_balloon: fitzgen created PR review comment:
This makes it sound like a guarantee, which it is not. If the platform does not support virtual memory, then we will just write the zeroes.
And this may not be what the embedder wants, so it may make sense to also expose a method for testing whether
wasmtime::Memory::discardwill write zeroes or use virtual memory so they can decide what to do in that case. This doesn't need to be part of this PR though, fine as a follow up PR or a new issue so we don't forget about it.
:speech_balloon: fitzgen created PR review comment:
It looks like we are not quite complete on the different kinds of overlaps:
- [ ] before
- [x] overlapping start
- [x] inside
- [x] overlapping end
- [ ] overlapping both the start and the end (i.e. containing the image)
- [x] after
:speech_balloon: fitzgen created PR review comment:
Also, we should test each of these both when dirty and when not dirty.
:speech_balloon: fitzgen created PR review comment:
Unless the memory creator's memory overwrites the default
RuntimeLinearMemory::discardimplementation, right? That seems like an important disctinction and that we should link to that method's docs from here.
:speech_balloon: fitzgen created PR review comment:
The last one is not an empty range?
josefguenther updated PR #14714.
josefguenther edited PR #14714:
Closes #9572.
This adds
Memory::discard(store, offset, len), the host API fitzgen sketched in #9572. It zeroes the pages of a non-shared memory that a byte range touches, and gives them back to the OS where Wasmtime owns the mapping. Like the proposedmemory.discardinstruction, it takes a byte offset and length and rounds them out to whole pages: the start is rounded down and the end up, so every page the range touches is discarded. The memory's size and base pointer don't change, and the pages read as zeros if they are touched again. Linear memory can't shrink, so this lets an embedder whose guest allocator frees large spans return that memory instead of holding the guest's high-water mark until the instance is dropped.How it works:
LinearMemorygets adiscardmethod. Its default writes zeros, which custom memories and memories without virtual memory use. A custom memory can override it to release its own pages.MmapMemoryand the pooling allocator'sStaticMemoryoverride it. On Linux they callmadvise(MADV_DONTNEED)on the pages. Other Unix platforms map fresh zeroed memory over them, and Windows decommits and recommits them.- If the memory was initialized from a copy-on-write image,
madviseon Linux would bring back the image's data instead of zeros. So that part gets fresh zeroed memory. A pooling slot then drops the image at its next reset, as resets already do on other platforms, and the next instance maps the image again.- A range out of bounds, or a memory with a custom page size, returns an error. Shared memories aren't supported.
- The C API gets
wasmtime_memory_discardand the C++ APIMemory::discard, consistent with the rest.The tests cover each of these cases, including every way a range can overlap an image, with the pages written first and untouched, and a C++ test covers the new binding.
josefguenther commented on PR #14714:
Thanks for the review! I rebased onto main, since the memory layer changed under this PR (
discardis now a provided method onLinearMemory), and addressed your comments in separate commits on top. It now takes a byte range rounded out to whole pages, like the proposed instruction, so I've updated the description to match.
:memo: josefguenther submitted PR review.
:speech_balloon: josefguenther created PR review comment:
Done.
MmapMemory::discardand the pooling slot'sdiscardnow say that an out-of-bounds range panics and that callers check bounds first, asMemory::discarddoes.
:memo: josefguenther submitted PR review.
:speech_balloon: josefguenther created PR review comment:
The comment was about the reset after a discard, but I agree it read the wrong way round. Restoring the image mapping brings the image back, which is why
discardmaps anonymous memory over those pages. After that the reset has no image mapping left to restore. I've reworded it.
:memo: josefguenther submitted PR review.
:speech_balloon: josefguenther created PR review comment:
Done.
:memo: josefguenther submitted PR review.
:speech_balloon: josefguenther created PR review comment:
The anonymous ranges are decommitted with
madvise(MADV_DONTNEED), which keeps the existing mapping and its protection key. Only the overlap gets a freshmmap, so only it needs the key back. In theZerobranch the whole range is a fresh mapping. I added a comment saying so.
:memo: josefguenther submitted PR review.
:speech_balloon: josefguenther created PR review comment:
Fixed: the parameters are now
offsetandlen, in bytes like the instruction (see below).
:memo: josefguenther submitted PR review.
:speech_balloon: josefguenther created PR review comment:
Done, it takes
offsetandlenin bytes now. The proposal says the address and size are "aligned down and up respectively", which is ambiguous: rounding the size up on its own can miss the end of a range that crosses a page boundary, like 0xF000 + 0x2000. I read it as rounding the start down and the end (offset + len) up, so the whole requested range is covered. Out of bounds is checked on the range as given and once rounded, and a zero length does nothing. The docs say so, and the tests cover the edges. The C and C++ APIs takesize_tbytes to match.
:memo: josefguenther submitted PR review.
:speech_balloon: josefguenther created PR review comment:
Agreed. The docs now say that how the pages are zeroed depends on the memory, and that without virtual memory it writes zeros. I'll open an issue for a way to ask which one a memory does, so we don't forget it.
:memo: josefguenther submitted PR review.
:speech_balloon: josefguenther created PR review comment:
Right. After rebasing onto main, where the internal trait is gone,
discardis a provided method on the publicLinearMemorythat writes zeros. A custom memory can override it to release its own pages, and the docs onMemory::discardnow link it.
:memo: josefguenther submitted PR review.
:speech_balloon: josefguenther created PR review comment:
Added both. The image test now discards a range before the image, across its start, inside it, exactly over it, across its end, containing it, and after it. It runs with on-demand memories and with the pooling allocator, with a fresh store per case so the slot is reset and reused in between.
:memo: josefguenther submitted PR review.
:speech_balloon: josefguenther created PR review comment:
Each of those cases now runs dirty, with every page written first, and clean, with the pages untouched since instantiation.
:memo: josefguenther submitted PR review.
:speech_balloon: josefguenther created PR review comment:
Right, it wasn't. The empty cases now all have a zero length, including one at an unaligned offset and one at the end.
:speech_balloon: fitzgen created PR review comment:
const DEFAULT_WASM_PAGE: usize = 0x10000;
:speech_balloon: fitzgen created PR review comment:
/// offset and length are multiples of this memory's page size.
:memo: fitzgen submitted PR review:
Thanks! LGTM, just a last couple nitpicks before this lands.
:repeat: alexcrichton submitted PR review:
Reading over this a bit I'm personally pretty concerned about the partial failure aspect I document below. I think that this'll want to probably make
discardanunsafefunction, and clearly document that it's kind of UB if an error is returned.
:speech_balloon: alexcrichton created PR review comment:
This to me seems pretty dangerous where the naming "discard" of this function seems to indicate that it would map the range specified here to zero, but in reality this is not actually doing that on Linux and is restoring the mapping which the page ranges originally had. Could an alternative name be considered for this backend-style function which doesn't mention "discard" and more accurately reflects what it's doing?
Or, alternatively, why make a new function here as opposed to using the preexisting
decommit_pages?
:speech_balloon: alexcrichton created PR review comment:
This documentation does not match the implementation because if an error is returned then the memory is basically left in an undefined state. For example it could be unmapped and then fail to re-map. On Unix there are many code paths I see implemented here which just perform a sequence of operations using
?at the end, and failure in the middle doesn't do any cleanup.IIRC this is one of the main holdups on the native wasm
memory.discard, what to do on partial failure, and I don't think that's addressed in this PR. I don't know if that means that this implementation is suitable for use, but I think that the documentation should at least be clear here in indicating that on failure access to the memory is basically UB as it could fault, it could return zeros, it could return the original mapping, etc.The faulting behavior probably means that this function needs to be
unsafeas well.
Last updated: Nov 19 2026 at 20:05 UTC