Skip to content

Fix decommit racing with asynchronous checkpoint reads - #15722

Open
jingyugao wants to merge 2 commits into
gvisor:masterfrom
jingyugao:fix/decommit-async-restore
Open

jingyugao wants to merge 2 commits into
gvisor:masterfrom
jingyugao:fix/decommit-async-restore

Conversation

@jingyugao

@jingyugao jingyugao commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

During background restore, MADV_DONTNEED on part of a huge page backing private anonymous memory can expose checkpointed contents instead of zeroes. MemoryManager.Decommit may keep the huge page and call MemoryFile.Decommit to zero the range in place, while the asynchronous page loader still has checkpoint reads outstanding for the same backing. This affects hosts where application huge pages are enabled (shmem_enabled=advise). Other MADV_DONTNEED calls drop page references instead, and cancelWasteLoad already handles them.

runsc restore defaults to --background (#16399), so this is reachable with default restore flags.

COMPATIBILITY:REGRESSION-GVISOR: Go programs restored in the background on such hosts can get stale data in newly allocated objects. The Go runtime returns memory with MADV_DONTNEED and assumes that the memory is zero when it reuses it.

Fix

The fix distinguishes reads already in flight from reads that have not started:

  • In-flight reads: MemoryFile.Decommit returns false without changing the range. MemoryManager.Decommit invalidates the affected PMAs and drops their references. Existing read waiters and background reads retain independent references until the old reads finish; later faults allocate new backing and read as zero. This avoids holding MemoryManager.activeMu while waiting for checkpoint I/O. The loader only performs I/O and never hole-punches the range.
  • Unstarted reads: cancellation has a begin/complete pair. beginDecommit marks the range aplDecommitting but leaves it in unloaded, so new MapInternal/DataFD calls still wait and the read queues skip it. Physical zeroing and memory accounting happen outside the loader lock. completeDecommit then removes the range, settles waiters, advances minUnloaded, and finishes the MemoryFile if appropriate. Thus completion cannot be published before the pages are zero.
  • An overlapping in-place decommit or an in-flight read conflict uses the same PMA fallback. MemoryManager.Decommit's interface is unchanged, and no new checkpoint-read error path is added.
  • If asynchronous loading has failed, unloaded pages remain inaccessible. The first commit factors out asyncMemoryFileLoad.finishLocked for this completion path.

The cancellation approach and the first pgalloc implementation come from Etienne Perot's patch (master...EtiennePerot:gvisor:autoresearch/decommit-cancels-unloaded).

Tests

decommit_test.go covers cancelled loads, in-flight read conflicts, waiters whose pages are cancelled alone or together with pages being read, completion after the last cancellation, read failures, memory accounting, saving during loading, and a randomized stress test.

The mixed-waiter regression uses synctest and explicit read/zeroing gates: page 0's read completes while page 1 is marked for decommit but not yet zeroed. The test checks that the shared waiter still has page 1 pending, a new DataFD remains blocked, an overlapping decommit is declined, and the loader does not report success. After zeroing is released, both MapInternal and DataFD return and page 1 reads as zero. The same test also checks that a failed assertion does not consume the fixture's only completion result.

mm_test.go verifies PMA invalidation, allocation of replacement backing, and zero contents after the old read completes. It also contains BenchmarkAsyncDecommit.

Performance

BenchmarkAsyncDecommit measures the incremental cost of the two-phase completion barrier relative to the PMA-fallback implementation without that barrier. The same benchmark source runs against both production implementations; checkpoint setup and fixture teardown are excluded.

Measured on an i7-12700KF with Go 1.27.3, fixed CPUs, GOMAXPROCS=2, interleaved before/after runs, and 24 independent samples per side:

Scenario Before After Difference
In-place cancellation 616.5 ns 681.4 ns +10.54% (p=0.000)
Decommit with concurrent read completions 909.5 ns 996.9 ns +9.61% (p=0.001)
Time holding activeMu in that scenario 824.5 ns 904.7 ns +9.71% (p=0.000)
Last cancellation plus loader completion 49.73 µs 48.99 µs no significant difference (p=0.830)

The absolute increments are 64.9 ns per in-place cancellation and 80.2 ns of activeMu hold time. The benchmark does not isolate application fault time spent waiting for activeMu, the read-queue cost of skipping marked ranges, or the tail latency when the last zeroing fully overlaps loader completion.

Earlier revisions were also exercised with C and Go end-to-end probes. Those results described an older implementation and are not claimed as results for the current head.

Validation

  • Both commits build independently.
  • //pkg/sentry/pgalloc:pgalloc_test and //pkg/sentry/mm:mm_test pass, as do the affected nogo targets.
  • pgalloc_test passes with --config=race; the three new benchmark scenarios also pass race-enabled smoke runs.
  • make lint and make lint-cc pass.
  • mm_test with --config=race does not complete in this environment: TestDataASUpdates, and then TestMRemapCopyOntoSource when the former is skipped, fail in the existing ptrace subprocess setup before reaching the Decommit cases.
  • The full repository test suite and the earlier end-to-end probes have not been rerun on the current head.

This bug fix is separate from background prefetch throttling in #15721.

Assisted-by: OpenAI Codex
Assisted-by: Claude Code

🤖 Generated with Claude Code

@gemini-code-assist

Copy link
Copy Markdown

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@jingyugao
jingyugao marked this pull request as ready for review October 13, 2026 05:27
@gemini-code-assist

Copy link
Copy Markdown

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@EtiennePerot

Copy link
Copy Markdown
Member

I found a similar finding with autoresearch, but it found that the version in this PR causes a regression for madvise during restore:

One concern is that awaiting the load of every decommitted range ties madvise latency to restore I/O. In a probe that MADV_DONTNEEDs 64 partial huge pages right after runsc restore --background of a 512 MiB app, the 64 MADV_DONTNEEDs takes 153 ms on a fast disk and 5.4 s with the disk throttled to 64 MB/s, vs 1.4 ms on current master.

You can cancel the loads instead of awaiting them. Decommit removes unloaded ranges that haven't been read and have no waiters (since they will read as zero anyway). For ranges whose read is in flight or awaited, it sets a flag so that the loader re-decommits them when the read completes. Every access to an unloaded page already waits for that point, so nothing sees stale data, and writes made after the wait are kept.

Here's the vibecoded patch it came up with: master...EtiennePerot:gvisor:autoresearch/decommit-cancels-unloaded

@jingyugao

jingyugao commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @EtiennePerot, I agree with the cancel-instead-of-await approach. I replaced my implementation with your two commits (finishLocked factoring and cancelLoadForDecommit) and force-pushed this branch; it also contains the mm-side error propagation and regression tests. The PR description is updated to match.

I checked it in two ways:

  • In-package: with checkpoint reads blocked, Decommit returns immediately, the page reads as zero afterwards, a write made after the Decommit survives the late re-decommit, and neighboring pages are unchanged.
  • End-to-end on WSL (ptrace, shmem_enabled=advise, defrag=defer, io.max 64 MB/s, 256 MiB app, 64 partial-huge-page discards right after restore --background --direct, 5 runs per build):
Build 64 madvise calls Pages with old data (of 64)
master 2.7-3.6 ms 40-60
previous version of this PR (await) 1.25-1.75 s 0
this PR (cancel) 2.4-2.8 ms 0

This matches your numbers: no stale pages, and madvise latency no longer depends on restore I/O. I did not run //test/benchmarks/base; I am relying on your results in #16151 for that.

Comment thread pkg/sentry/pgalloc/save_restore.go Resolved
@jingyugao
jingyugao marked this pull request as draft October 27, 2026 09:02
@jingyugao
jingyugao marked this pull request as ready for review October 27, 2026 15:49
@jingyugao
jingyugao requested a review from nixprime October 29, 2026 06:05
@jingyugao
jingyugao force-pushed the fix/decommit-async-restore branch from 02881d1 to 77bd7bf Compare October 30, 2026 16:12
jingyugao added a commit to jingyugao/gvisor that referenced this pull request Oct 31, 2026

@manninglucas manninglucas 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.

Thanks, the production change looks correct. Cancelling unstarted loads under apfl.mu, waiting only for reads already in flight, and waking cancelled waiters after the zeroing all hold up under tracing (lock order, waiter split/wake accounting, finishLocked preconditions, error paths). The new tests fail without the fix for the right reasons: 9 of 11 tests, and 18 of 20 stress seeds.

  1. Commit history: the merge bot applies every commit (CONTRIBUTING.md, "does not yet support squash merging"). This branch would land merge commit 05dd0c3, where pgalloc_test doesn't compile (3-arg StartAsyncPagesFileLoad), and 52fe47f's EIO-from-madvise mm change, which 77bd7bf reverts. Please rebase onto master as two commits that each build, the finishLocked refactor and then the fix with its tests. Sign off each one (git commit -s, now required by CONTRIBUTING.md), and describe the final behavior in the commit message without referring to earlier versions ("no longer returns an error", "same as on master").
  2. Rebase breakage: pkg/sentry/pgalloc/BUILD conflicts with master. After the rebase, decommit_test.go won't compile, because newSaveTestMemoryFile now takes dir and arm64 hostarch.PageSize is a uintptr var (see inline).
  3. Test robustness: the in-flight Decommit tests don't synchronize on Decommit actually waiting, and the TotalUsage assertions depend on the host's shmem THP setting (see inline).

Security: This fixes an in-sandbox Integrity bug: after madvise(MADV_DONTNEED) during background restore, the application could read stale checkpoint data instead of zeroes. The change adds no host syscalls, FDs or paths and can't cross the sandbox boundary. It introduces no new panic, deadlock or unbounded allocation reachable from SandboxUser. Decommit now blocks only on reads already in flight, the same way page faults already do.

Requesting changes before approval.


[🤖] This review is part of an experimental auto-review process to help speed up gVisor review velocity. It is a work in progress. Assisted-By: Gemini Carbon

Comment thread pkg/sentry/pgalloc/decommit_test.go Outdated
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build !pagesize_64k

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.

After the rebase this PR needs, the file doesn't compile. newSaveTestMemoryFile now takes a dir argument (pass "" at lines 127, 177, 305 and 625), and on arm64 hostarch.PageSize is a uintptr var, so expressions like int64(page) * hostarch.PageSize and off / hostarch.PageSize fail. Drop this now-dead pagesize_64k tag and convert explicitly, e.g. a local pageSize := uint64(hostarch.PageSize) plus int64(...) where offsets are compared, as master's save_restore_test.go does.

Comment thread pkg/sentry/pgalloc/BUILD Outdated
Comment on lines +217 to +220
"//pkg/errors/linuxerr",
"//pkg/hostarch",
"//pkg/memutil",
"//pkg/safemem",

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.

No test in this target imports //pkg/safemem (or, at this head, //pkg/errors/linuxerr); they're left over from the deleted decommit_restore_test.go. When you resolve the BUILD conflict, keep master's srcs/deps and add only decommit_test.go and //pkg/sync.

Comment thread pkg/sentry/pgalloc/decommit_test.go Outdated
Comment on lines +586 to +590
inflight := startDecommit(f, decommitTestPage(fr, 0))
awaitDecommit(t, startDecommit(f, decommitTestPages(fr, 4, 8)))
l.releaseReads()
awaitDecommit(t, inflight)
if err := l.wait(t); err != nil {

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.

Nothing checks that this Decommit reached awaitLoad before releaseReads(). If it runs after the read completes, the test still passes without covering the in-flight case. Call awaitLoadWaiter(t, f) before releaseReads() here, and before expectBlocked at lines 414 and 549, so the wait is confirmed deterministically.

Comment thread pkg/sentry/pgalloc/decommit_test.go Outdated
if err := l.wait(t); err != nil {
t.Fatalf("async page loading failed: %v", err)
}
checkCommitted(t, f, 11)

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.

TotalUsage() is the memfd's st_blocks. With shmem_enabled set to always or within_size, the first fault into this 1 GiB memfd can allocate a 512-page shmem folio, so this check and the stress bound at line 709 fail on such hosts. Skip only the TotalUsage comparisons unless /sys/kernel/mm/transparent_hugepage/shmem_enabled is missing or [never]/[deny]/[advise], and keep the content and knownCommittedBytes checks.

Comment thread pkg/sentry/pgalloc/save_restore.go Outdated
Comment on lines +2156 to +2159
// Async page loading failed. Unloaded pages in fr will never be
// loaded, but reads of them may still be in flight, and are no
// longer marked started. Leave them unloaded so that accesses to
// them fail, consistently with other unloaded pages.

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.

The defer in main() calls ar.Close(), which stops in-flight reads, before it clears started, so in-flight reads are never "no longer marked started". The real window is between the errVal store and Close() returning, and it's harmless because those pages stay unloaded. Please say that here, and add a one-line comment above amfl.awaitLoad(fr) (line 2193) explaining why its error is ignored.

Comment thread pkg/sentry/pgalloc/save_restore.go Outdated
Comment on lines +2179 to +2181
// If this emptied amfl.unloaded, no read completion may follow to finish
// amfl. (If we didn't cancel anything, amfl.unloaded was empty already and
// amfl may already be finished.)

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.

!cancelled doesn't imply that unloaded was empty. Suggest: "Finish amfl only if this call emptied amfl.unloaded; otherwise the read completion or LoadFrom() that emptied it has already called finishLocked()."

Comment thread pkg/sentry/pgalloc/decommit_test.go Outdated
t.Helper()
select {
case <-done:
t.Fatalf("%s returned before the read of decommitted pages completed", what)

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.

This message is wrong for the MapInternal caller (page 0 isn't decommitted) and the SaveTo caller. Use a neutral message such as "%s returned while reads were still blocked".

@jingyugao
jingyugao force-pushed the fix/decommit-async-restore branch from 77bd7bf to 7b90775 Compare November 18, 2026 08:05
jingyugao and others added 2 commits December 2, 2026 14:50
Share MemoryFile load completion between LoadFrom and the async page loader. Callers hold the loader locks and have finished adding and loading pages for the file.

Co-authored-by: Etienne Perot <[email protected]>
Signed-off-by: gaojingyu <[email protected]>
During background restore, MADV_DONTNEED on part of a huge page backing
private anonymous memory must leave the pages zeroed. Otherwise the async
page loader can write checkpoint data into the decommitted pages, and the
application reads stale data instead of zeroes.

MemoryFile.Decommit cancels unstarted reads of the range and zeroes the
pages in place. If a read of the range is already in flight, Decommit
returns false without changing the range, and MemoryManager.Decommit
invalidates the PMA and drops its references instead. Background reads
hold temporary references, so the old backing is not recycled during I/O
and a refault allocates fresh zeroed pages. Awaited reads are excluded by
activeMu or by save-side quiescence. Decommit does not wait for checkpoint
I/O.

Keep cancelled pages pending until the backing is zeroed and memory
accounting is updated. If async page loading failed, unloaded pages remain
inaccessible. Finish loading only after the last pending pages complete.

Cover cancellation, in-flight reads, the PMA-invalidation fallback, waiter
accounting, save and restore, and load failures. Check page contents
independently of the host's shmem huge page policy.

Co-authored-by: Etienne Perot <[email protected]>
Signed-off-by: gaojingyu <[email protected]>
@jingyugao
jingyugao force-pushed the fix/decommit-async-restore branch from 7b90775 to d09c845 Compare December 2, 2026 06:50
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