kernel: zero freshly allocated direct memory #820
No reviewers
Labels
No labels
bug
documentation
duplicate
enhancement
GPU
GUI
help wanted
question
Shaders
Video
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
github/KytyPS5--KytyPS5!820
Loading…
Reference in a new issue
No description provided.
Delete branch "gh-pr/820/head"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
@6d4m on GitHub · 2026-09-25 03:04 UTC · original
6d4m:fix/direct-memory-zeroing→main· +151 −0 · 2 files · 2 commits · closed without mergingSummary
sceKernelAllocateDirectMemoryandsceKernelMemoryPoolExpandreturn physical ranges whose backing store still holds the previous owner's bytes. This clears the range at allocation, which is the only point where that can be done without breaking the documented unmap/remap contents contract.The diagnosis and the original evidence come from #147 and #156 (credit to @StefanosCosta) - this is the zeroing part of that work, split out as a small PR with a regression test, plus the pool-expansion path.
Problem
UnmapBackingdeliberately never clears: that is what lets a remap of a still-allocated range see its previous contents. The consequence is that the free list hands out ranges whose backing still contains the last owner's data, and a fresh allocation can read it back. Whether the console hands back a fresh allocation already cleared is not something a guest can rely on, and some middleware reads its buffers before writing them, so a fresh allocation must not expose another allocation's bytes.The backing store is one object indexed by physical address (
KernelMapDirectMemorydocuments the requirement that contents survive unmap/remap), so allocation is the only place a range can be cleared.FlexibleMemoryalready callsZeroBackingon this path; direct memory and pool expansion did not.Change
KernelAllocateDirectMemory: zero the allocated range, and release the allocation again if the clear failsKernelMemoryPoolExpand: same, for the expansion rangeBoth clear at allocation rather than at map time, so map/unmap/remap of an already-allocated range still preserves its contents.
Testing
DirectMemoryReuseIsZeroFilledinvirtual_memory_allocation_tests: poisons a range with0xa5, releases it, then allocates again withsearch_startset to the released address so the reuse is deterministic, and asserts the remapped range reads back as zeros.reused direct backing exposed stale bytes; with it applied it passes.audio_out2_port,ime_dialog,virtual_memory_allocation,page_manager,memory_tracker(5/5).DirectMemoryContentPersistsAcrossRemapand the other remap/aliasing tests still pass, so the contents contract is intact.Scope and what this does not do
This is a memory-correctness fix, and it is not a fix for the corrupted FMOD audio in #805 / #819. That symptom survives this change: with the fix applied, 3D Mini Golf's guest-side AudioOut output was measured at exactly realtime (audio/host ratio 0.998) with a steady 37 ms queue cushion and no starvation, yet the music itself is generated at the wrong rate. Those two issues are tracked separately.
AI use disclosure
I used AI (OpenCode) to investigate the symptom, read the audio path, capture and measure the PCM, and prepare the change and this description. I reviewed the diff and the test results before submitting.
@coderabbitai[bot] on GitHub · 2026-09-25 03:09 UTC · original · edited 2026-09-27 01:15 UTC
Navigate logical layers of code changes, visualize relationships, and explore their blast radius.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
Review profile: CHILL
Plan: Advanced
Run ID:
09b86d3e-bce7-42ed-a00f-f93ec9838f05📥 Commits
Reviewing files that changed from the base of the PR and between
680c744ccdand7c3fd5e7e5.📒 Files selected for processing (1)
tests/VirtualMemoryAllocationTests.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.
📝 Walkthrough
Walkthrough
Direct-memory allocations and memory-pool expansions now clear physical backing before making it available. If clearing fails, each path releases the allocation and returns an error. New tests verify that reused direct memory and memory added through pool expansion contain zeroes.
Suggested reviewers:
nmzikPriority: ➖ Normal
Change: Bug fix
Merge Risk: ⚪ Minimal · up to
7c3fdThe allocation changes and reuse tests present no identified merge-blocking issue; merge after normal checks.
Security Architecture Review
Security architecture risk: 🔵 Low · up to
7c3fdThe new clearing step reduces the chance that a fresh allocation exposes a previous allocation’s data. No introduced security weakness was established, but failure and caller-boundary coverage is incomplete.
Retained concerns
No architecture-level concerns identified.
Security review details
Security Blast Radius
Security Findings and Attack Paths
Trust Boundaries and Controls
Resilience and Maintainability Implications
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Comment
@coderabbitai helpto get the list of available commands.@Nmzik on GitHub · 2026-09-26 22:49 UTC · original
@6d4m What is the reason for this fix? Does it actually fix any bug? Does a real PS5 zero this out? Audio fix is fine but is it correlated somehow with this fix?
@6d4m on GitHub · 2026-09-27 00:36 UTC · original
Fair question, and the claim was too strong. I've pulled it out of the code, the commit message and the description: we don't know what the console does here, we only know the guest can't be expected to cope either way.
The fix itself: our backing store is one object indexed by physical address, and Unmap deliberately keeps contents so a remap of a still-allocated range still sees them. A range going back to the free list therefore still holds the last owner's bytes, and the next allocation hands it straight back. The guest heap path already clears every new block, direct memory and pool expansion were the two that didn't, so this just makes them consistent.
Does it fix a real bug: yes, but the evidence isn't mine. It's from @StefanosCosta in #156. FMOD reads a buffer before writing it, and stale bytes, NaN patterns included, travel through FMA chains without raising an FP exception, so the DSP stays poisoned for the rest of the process. Same binary one env var apart: 248 s clean against NaN at 61.3 s, on two titles. I haven't reproduced that end to end myself. The test in the PR pins the behaviour and fails against the old code.
On the console: I don't know and I can't test it. There's no documentation for sceKernelAllocateDirectMemory that promises cleared pages. Our reuse is structural, we recycle a single backing store so stale bytes are guaranteed here, while the console takes pages from the OS allocator and may or may not get recycled ones back. And the guest won't tolerate garbage: if the console handed back arbitrary bytes, every Unity/FMOD title would break non-deterministically, and they don't. So this is deliberately conservative, one memset per allocation rather than per map, instead of a claim that it copies documented kernel behaviour.
The alternative I weighed was giving each direct allocation its own fresh host mapping, so the OS hands over zero pages. That's closer to what "new physical memory" should mean, but the backing store is a single object indexed by physical address and remap-has-to-see-the-old-contents is a tested contract, so per-allocation mappings turn into a much bigger change to the physical memory model. Say the word if you'd rather have that instead.
AI assistance (OpenCode) was used for the investigation and this change; I read the diff and the test results before posting.
@coderabbitai[bot] on GitHub · 2026-09-27 00:41 UTC · original · reviewed
🧹 Nitpick comments (1)
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository: KytyPS5/KytyPS5/.coderabbit.yaml
Review profile: CHILL
Plan: Advanced
Run ID:
73a03062-900b-46dd-96ff-74bb79ac0884📥 Commits
Reviewing files that changed from the base of the PR and between d3371dd0455fb1f645f914625ac3ebacf91db186 and
680c744ccd.📒 Files selected for processing (1)
src/kernel/memory.cppIncluded review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.
@6d4m on GitHub · 2026-09-27 00:57 UTC · original
Short answer: no shared cause, but they hide each other.
What I hit was the pacing bug, not this one. The two titles I reported in #805/#819 produced clean PCM at the right rate, and their audio became correct with the pacing change in #822 alone - this fix was not in the build I tested. Measured on 3D Mini Golf: zero non-finite samples in 21000 buffers, correct format, production at 0.998 of realtime, only the write cadence wrong.
What this fix is for is a different signature, and the evidence is @StefanosCosta's from #156: FMOD reads a buffer before writing it, stale NaN bytes move through FMA chains without raising an FP exception, and the DSP stays poisoned for the rest of the process. So audio is fine for a while and then goes bad at a fixed elapsed time and never recovers - 248 s clean against NaN at 61.3 s on the same binary, one env var apart, across two titles with different audible symptoms. That is not what a pacing problem looks like.
The correlation is one of occlusion. #156 puts it plainly: without the signal and audio fixes, titles do not reach the in-game state where the stale allocation gets read, so this may not reproduce in isolation. The pacing bug keeps the game from getting far enough for the zeroing bug to matter, and once pacing is fixed the stale-memory bug becomes reachable. Both still need fixing, and each was confirmed on its own.
I have not reproduced the NaN case end to end myself, so treat that half as reported rather than verified by me. The two titles I did test show no trace of it, which is consistent with them simply never reaching the state that triggers it.
On the test gap CodeRabbit found - correct, the pool-expansion path is changed but untested. Adding a sibling test for it.
@6d4m on GitHub · 2026-09-27 01:10 UTC · original
Good catch, that was a real gap -
KernelMemoryPoolExpandwas changed without a test, so a regression there would have exposed stale backing with every case still green.Added
PoolExpansionReuseIsZeroFilled: poison a pool-aligned direct range, release it, expand the pool with the search range starting at that address so the reuse is deterministic, commit, and assert zeros. It fails with "reused pool expansion exposed stale bytes" against the previous production code and passes with the fix, so it does pin the behaviour rather than just passing.One note on running it locally:
PrtBackingReadPreservesSparseResidencyfails on this machine on unmodifiedbec67b7too, and the runner stops at the first failure, so the new case never gets reached in a full local run. I verified the new test on its own, both with and without the production change. Not caused by this PR, but worth knowing if you see the same locally.@Nmzik on GitHub · 2026-09-28 15:48 UTC · original
I'll close this. No real evidence
Pull request closed