gpu: release stale clean buffers without memory pressure #1934

Open
github-bot wants to merge 5 commits from github-bot/gh-1934 into main AGit
Owner

@⁠MrBigBritches on GitHub · 2026-10-27 06:33 UTC · original
MrBigBritches:stale-buffer-release → main · +530 −5 · 9 files · 5 commits · open

A cached buffer keeps its guest pages write-protected. Once a game reuses that memory for other data, every CPU write there faults and is uploaded again into a buffer nothing reads. In Octopath Traveler II, about a third of all write faults landed in buffers no binding had used for over 300 frames.

This releases clean buffers that no binding has used for a while, even without memory pressure, and adds a safety net for buffers that shaders read only through BDA.

It is the third part of #1809, redesigned. #1809 released any buffer unbound for 300 ticks and pinned BDA-read buffers permanently. Here, ranges are protected only when a shader is seen reading one again, and protection is cleared on unmap. It is independent of #1932 and #1933.

Changes

  1. Debug counters BufferReleases and BufferReleaseRefaults, shown in the performance overlay's GPU memory section. A refault turns the row yellow.
  2. Mesh index buffers count as a use. Mesh shaders read the guest index buffer through BDA, and the draw only registered it with FindBuffer, which deliberately doesn't count as a use. BufferCache::FindBufferForShaderRead finds or creates the buffer and touches it. FindBuffer is unchanged.
  3. Stale release.
    • Every 60 garbage-collector ticks, release clean buffers that no binding has used for 300 ticks, at most 128 per pass.
    • It runs before the memory-pressure check and uses the same untrack-and-delete path as the memory-pressure collector.
    • Buffers holding GPU-written data are kept.
  4. Refault safety net.
    • Recently released ranges are remembered, up to 16,384.
    • If the BDA fault path recreates one, that's a refault: it is counted, logged, and the range is protected from stale release until it is unmapped.
    • Protection is kept by address, so it carries over when buffers merge.
  5. A comment at the BDA-write rejection in shader info collection. "Not GPU-written, so safe to drop" holds only because shaders can't write guest memory through an address. Whoever lifts that rejection has to track those writes first.

Why dropping a buffer without a download is safe

Shaders with FLAT/GLOBAL stores to guest memory are rejected at compile time (ShaderInfoCollection, "writable FLAT/GLOBAL addresses require GPU ownership tracking"), and there is no store-through-BDA emitter. Address atomics and scalar stores aren't decoded. So every shader write to guest memory goes through a bound buffer, which is tracked as GPU-written. The memory-pressure collector already relies on the same thing. MemoryTracker also stops the process ("cannot untrack GPU-dirty memory") if a GPU-written range is ever released.

Measurements

Octopath Traveler II, the same route on main and on an experiment build with the same release rule. The figures come from a temporary per-second log, which is not part of this PR.

Stretch FPS, main → release Faults per frame, main → release Re-uploads into buffers unused for 300+ ticks
Heavy scene 55.3 → 59.2 1,707 → 1,192 (−30%) 35% → 1%
Burst of BDA draws 54.3 → 58.7 3,037 → 1,710 (−44%) 39% → 1%
Late scene 59.8 → 59.8 1,707 → 882 (−48%) 48% → 1.7%
Whole run 56.9 → 58.6 1,631 → 1,099 (−33%) 33% → 1%
  • The experiment released 4,074 buffers (202 MB) in about 2 minutes, with zero refaults and no visible glitches.
  • With this branch, the same route showed no refaults, no BDA reads of missing memory, and no visual problems.
  • About 100% of write faults come from BDA synchronization re-uploads, so this is the main source.

Testing

  • Octopath Traveler II: a clean run on this branch, with no refaults and nothing missing or flickering.
  • New tests in shader_recompiler_compute_tests:
Test What it checks
BufferCacheShaderReadLookup A shader-read lookup keeps its buffer resident under garbage collection, while a plain FindBuffer lookup still doesn't.
BufferCacheStaleRelease A stale clean buffer is released at its first eligible pass and not before. A buffer in use is kept. A GPU-written buffer is kept, with no work submitted. Released pages are untracked, and a rebind uploads current data. Counters are correct. 129 stale buffers are released as 128, then 1.
BufferCacheReleaseRefault A refault is counted and protects its range through aging. A fault on a never-released range isn't counted. A buffer merged over a protected range is kept. Unmap and remap clear protection.
  • I checked that the tests can fail. Each of these mutations fails the matching check:
    • removing the touch in the shader-read lookup;
    • removing the per-pass cap;
    • removing the untrack;
    • ignoring protection;
    • not clearing protection on unmap.
  • No existing test changed. BufferCacheDirtyGarbageCollection passes unchanged.
  • ctest on Windows: 63 of 65 pass. The two failures also fail on main:
    • vdecsw doesn't build, because std::aligned_alloc isn't available in MSVC's C runtime.
    • kernel_file_system crashes with 0xc0000028.
  • Linux and macOS CI currently fail on main, and #1922 fixes them.

Behaviour change

A clean buffer that no binding uses no longer stays cached forever without memory pressure. BufferCacheStaleRelease makes that explicit.

Known limits

  • First refault per range: an engine that reads a buffer only through BDA still sees one read of zeros, for a frame or so, the first time a range is released. Protection prevents repeats, and the overlay and log show it.
  • Ticks are suspend points: an engine with several per frame shortens the 300-tick age in wall-clock time.
  • GPU barriers per release: each release clears the buffer's BDA page-table entries with a fill between two barriers, as the memory-pressure collector already does. No spikes were noticed. If one appears, the clears can be batched.
**@⁠MrBigBritches** on GitHub · 2026-10-27 06:33 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1934) `MrBigBritches:stale-buffer-release` → `main` · +530 −5 · 9 files · 5 commits · open A cached buffer keeps its guest pages write-protected. Once a game reuses that memory for other data, every CPU write there faults and is uploaded again into a buffer nothing reads. In Octopath Traveler II, about a third of all write faults landed in buffers no binding had used for over 300 frames. This releases clean buffers that no binding has used for a while, even without memory pressure, and adds a safety net for buffers that shaders read only through BDA. It is the third part of #1809, redesigned. #1809 released any buffer unbound for 300 ticks and pinned BDA-read buffers permanently. Here, ranges are protected only when a shader is seen reading one again, and protection is cleared on unmap. It is independent of #1932 and #1933. ## Changes 1. **Debug counters** `BufferReleases` and `BufferReleaseRefaults`, shown in the performance overlay's GPU memory section. A refault turns the row yellow. 2. **Mesh index buffers count as a use.** Mesh shaders read the guest index buffer through BDA, and the draw only registered it with `FindBuffer`, which deliberately doesn't count as a use. `BufferCache::FindBufferForShaderRead` finds or creates the buffer and touches it. `FindBuffer` is unchanged. 3. **Stale release.** - Every 60 garbage-collector ticks, release clean buffers that no binding has used for 300 ticks, at most 128 per pass. - It runs before the memory-pressure check and uses the same untrack-and-delete path as the memory-pressure collector. - Buffers holding GPU-written data are kept. 4. **Refault safety net.** - Recently released ranges are remembered, up to 16,384. - If the BDA fault path recreates one, that's a refault: it is counted, logged, and the range is protected from stale release until it is unmapped. - Protection is kept by address, so it carries over when buffers merge. 5. **A comment at the BDA-write rejection** in shader info collection. "Not GPU-written, so safe to drop" holds only because shaders can't write guest memory through an address. Whoever lifts that rejection has to track those writes first. ## Why dropping a buffer without a download is safe Shaders with FLAT/GLOBAL stores to guest memory are rejected at compile time (`ShaderInfoCollection`, "writable FLAT/GLOBAL addresses require GPU ownership tracking"), and there is no store-through-BDA emitter. Address atomics and scalar stores aren't decoded. So every shader write to guest memory goes through a bound buffer, which is tracked as GPU-written. The memory-pressure collector already relies on the same thing. `MemoryTracker` also stops the process ("cannot untrack GPU-dirty memory") if a GPU-written range is ever released. ## Measurements Octopath Traveler II, the same route on `main` and on an experiment build with the same release rule. The figures come from a temporary per-second log, which is not part of this PR. | Stretch | FPS, `main` → release | Faults per frame, `main` → release | Re-uploads into buffers unused for 300+ ticks | |---|---|---|---| | Heavy scene | 55.3 → 59.2 | 1,707 → 1,192 (−30%) | 35% → 1% | | Burst of BDA draws | 54.3 → 58.7 | 3,037 → 1,710 (−44%) | 39% → 1% | | Late scene | 59.8 → 59.8 | 1,707 → 882 (−48%) | 48% → 1.7% | | Whole run | 56.9 → 58.6 | 1,631 → 1,099 (−33%) | 33% → 1% | - The experiment released 4,074 buffers (202 MB) in about 2 minutes, with **zero refaults** and no visible glitches. - With this branch, the same route showed no refaults, no BDA reads of missing memory, and no visual problems. - About 100% of write faults come from BDA synchronization re-uploads, so this is the main source. ## Testing - **Octopath Traveler II:** a clean run on this branch, with no refaults and nothing missing or flickering. - **New tests** in `shader_recompiler_compute_tests`: | Test | What it checks | |---|---| | `BufferCacheShaderReadLookup` | A shader-read lookup keeps its buffer resident under garbage collection, while a plain `FindBuffer` lookup still doesn't. | | `BufferCacheStaleRelease` | A stale clean buffer is released at its first eligible pass and not before. A buffer in use is kept. A GPU-written buffer is kept, with no work submitted. Released pages are untracked, and a rebind uploads current data. Counters are correct. 129 stale buffers are released as 128, then 1. | | `BufferCacheReleaseRefault` | A refault is counted and protects its range through aging. A fault on a never-released range isn't counted. A buffer merged over a protected range is kept. Unmap and remap clear protection. | - I checked that the tests can fail. Each of these mutations fails the matching check: - removing the touch in the shader-read lookup; - removing the per-pass cap; - removing the untrack; - ignoring protection; - not clearing protection on unmap. - **No existing test changed.** `BufferCacheDirtyGarbageCollection` passes unchanged. - **ctest on Windows:** 63 of 65 pass. The two failures also fail on `main`: - `vdecsw` doesn't build, because `std::aligned_alloc` isn't available in MSVC's C runtime. - `kernel_file_system` crashes with `0xc0000028`. - **Linux and macOS CI** currently fail on `main`, and #1922 fixes them. ## Behaviour change A clean buffer that no binding uses no longer stays cached forever without memory pressure. `BufferCacheStaleRelease` makes that explicit. ## Known limits - **First refault per range:** an engine that reads a buffer only through BDA still sees one read of zeros, for a frame or so, the first time a range is released. Protection prevents repeats, and the overlay and log show it. - **Ticks are suspend points:** an engine with several per frame shortens the 300-tick age in wall-clock time. - **GPU barriers per release:** each release clears the buffer's BDA page-table entries with a fill between two barriers, as the memory-pressure collector already does. No spikes were noticed. If one appears, the clears can be batched.
Count clean buffers released after going unbound, and released ranges
a shader then read again through BDA. Show both in the performance
overlay's GPU memory section, flagging any refaults.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Mesh shaders read the guest index buffer through BDA, and the draw only
registers it with FindBuffer, which deliberately doesn't count as a use.
So the garbage collector saw the buffer as unused while shaders kept
reading it. Add BufferCache::FindBufferForShaderRead, which finds or
creates the buffer and touches it, and use it for the mesh index buffer.
FindBuffer itself is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A cached buffer keeps its pages write-protected. Once a game reuses that
memory for other data, every CPU write there faults and is uploaded
again into a buffer nothing reads. In Octopath Traveler II about a third
of all write faults landed in buffers no binding had used for over 300
frames.

Every 60 garbage-collector ticks, release clean buffers that no binding
has used for 300 ticks, at most 128 per pass, through the same untrack
and delete path the memory-pressure collector uses. Buffers holding
GPU-written data are kept. That check is complete only because shaders
cannot write guest memory through BDA.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A buffer that shaders read only through BDA never counts as bound, so
stale release can drop it while it is still in use. The next read then
finds no buffer, reads zeros for a frame or so, and the fault path
creates it again.

Remember recently released ranges. When the fault path recreates one,
count a refault, log it, and protect that range from stale release
until it is unmapped. Protection is kept by address, so it carries over
when buffers merge. In Octopath Traveler II there were no refaults, so
this only guards engines that read buffers through BDA alone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Stale release and the memory-pressure garbage collector drop buffers the
GPU did not write without downloading them. That is safe only because
shaders cannot write guest memory through an address, which shader info
collection rejects, so only writes through bound buffers need tracking.
Say so where the rejection is, so whoever lifts it tracks those writes
first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 10:09:26 +00:00
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-27 06:40 UTC · original

Review in Change Stack →

Walkthrough

BufferCache now tracks shader-read use and releases eligible stale buffers during garbage collection. It records released ranges and protects them when a later fault overlaps them. Unmapping clears release history for the affected range. The change also adds release and refault counters, a performance overlay row, and tests for use tracking, release eligibility, release limits, refault handling, and unmapping.

Suggested reviewers: shadowbeat070, nmzik

Priority: Normal

Change: Feature

Merge Risk: Low · up to 1ca8e

Partial unmapping can permit repeated zero reads on a narrow shader-read path. Preserve the remaining release history and strengthen the remap test; these bounded issues warrant follow-up before or alongside merge.

Pre-merge checks: Passed 4 · Inconclusive 1

Failed Failed checks: 1 inconclusive

Check name Status Explanation Resolution
Docstring Coverage Inconclusive Docstring coverage is 15.38% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Documentation-only edits and deletions within surv… Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title names the primary change: periodic release of stale clean GPU buffers that no binding has used, even without memory pressure. It matches the raw summary (ReleaseStaleBuffers in the garbage c…
Description check Passed The description states the problem (write faults into unused buffers) and the fix (releasing clean buffers unused for a period, plus a BDA refault safety net). It lists the changes, the rationale for …
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the primary change: periodic release of stale clean GPU buffers that no binding has used, even without memory pressure. It matches the raw summary (ReleaseStaleBuffers in the garbage collector, with the release and refault counters) and the objectives, which describe the same release rule. It does not mention the refault safety net or the BDA mesh index-buffer use, but those are supporting parts of the same change.

Full details: Description check

Explanation

The description states the problem (write faults into unused buffers) and the fix (releasing clean buffers unused for a period, plus a BDA refault safety net). It lists the changes, the rationale for dropping buffers without download, measurements, tests, behaviour change, and known limits. These match the raw summary and the objectives.

Full details: Docstring Coverage

Explanation

Docstring coverage is 15.38% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 13 functions across 8 files. (1 skipped: 1 too large.)

Resolution

Write docstrings for the functions missing them to satisfy the coverage threshold.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-27 06:40 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1934#issuecomment-6435537567) <!-- coderabbit-ai-generated:v1 --> <!-- This is an auto-generated comment: summarize by coderabbit.ai --> <!-- review_stack_entry_start --> <a href="https://app.coderabbit.ai/change-stack/KytyPS5/KytyPS5/pull/1934?scope=ghh_OusAJGA4HG8ljoOV0wJvVx8NmnZIjc2DdjmxOu0xZWA&amp;cs_source=review_comment"><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui-dark.svg?v=3"><source media="(prefers-color-scheme: light)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg?v=3" alt="Review in Change Stack →" height="32"></picture></a> <!-- review_stack_entry_end --> <!-- walkthrough_start --> <details> <summary><strong>Walkthrough</strong></summary> <dl> <dd> BufferCache now tracks shader-read use and releases eligible stale buffers during garbage collection. It records released ranges and protects them when a later fault overlaps them. Unmapping clears release history for the affected range. The change also adds release and refault counters, a performance overlay row, and tests for use tracking, release eligibility, release limits, refault handling, and unmapping. **Suggested reviewers:** `shadowbeat070`, `nmzik` </dd> </dl> </details> <!-- walkthrough_end --> <!-- change_assessment_start --> <strong>Priority: <picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/priority-normal-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Normal</strong> <!-- change_assessment_commit:"1ca8e2ce000a0644651af1ada35ad7723a2268aa" --> **Change:** Feature <!-- change_assessment_end --> <details> <summary><strong>Merge Risk:</strong> <strong><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/risk-low-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Low</strong> · up to <code>1ca8e</code></summary> <dl> <dd> <!-- final_review_risk_start --> <!-- final_review_risk_label **Merge Risk:** **🔵 Low** · up to `1ca8e` --> <!-- final_review_risk_coverage:{"sourceCommitId":"1ca8e2ce000a0644651af1ada35ad7723a2268aa","coveredCommitId":"1ca8e2ce000a0644651af1ada35ad7723a2268aa","kind":"reviewed"} --> Partial unmapping can permit repeated zero reads on a narrow shader-read path. Preserve the remaining release history and strengthen the remap test; these bounded issues warrant follow-up before or alongside merge. <!-- final_review_risk_end --> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_start --> <details> <summary><strong>Pre-merge checks: <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> 4 · <sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-inconclusive-14-v2.svg" width="14" height="14" align="middle" alt="Inconclusive" title="Inconclusive"></picture></sup> 1</strong></summary> <dl> <dd> <strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-failed-14-v2.svg" width="14" height="14" align="middle" alt="Failed" title="Failed"></picture></sup> Failed checks: 1 inconclusive</strong> | Check name | Status | Explanation | Resolution | | :---------------- | :--------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | :--------------------------------------------------------------------------------- | | Docstring Coverage | ![Inconclusive](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-inconclusive.svg) | Docstring coverage is 15.38% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Documentation-only edits and deletions within surv… | Write docstrings for the functions missing them to satisfy the coverage threshold. | <details> <summary><strong><sup><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-counter-passed-14-v2.svg" width="14" height="14" align="middle" alt="Passed" title="Passed"></picture></sup> Passed checks: 4 passed</strong></summary> <dl> <dd> | Check name | Status | Explanation | | :------------------------ | :--------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Title check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The title names the primary change: periodic release of stale clean GPU buffers that no binding has used, even without memory pressure. It matches the raw summary (ReleaseStaleBuffers in the garbage c… | | Description check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | The description states the problem (write faults into unused buffers) and the fix (releasing clean buffers unused for a period, plus a BDA refault safety net). It lists the changes, the rationale for … | | Linked Issues check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | | Out of Scope Changes check | ![Passed](https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-passed.svg) | Check skipped because no linked issues were found for this pull request. | <details> <summary><strong>Full details: Title check</strong></summary> <dl> <dd> **Explanation** The title names the primary change: periodic release of stale clean GPU buffers that no binding has used, even without memory pressure. It matches the raw summary (ReleaseStaleBuffers in the garbage collector, with the release and refault counters) and the objectives, which describe the same release rule. It does not mention the refault safety net or the BDA mesh index-buffer use, but those are supporting parts of the same change. </dd> </dl> </details> <details> <summary><strong>Full details: Description check</strong></summary> <dl> <dd> **Explanation** The description states the problem (write faults into unused buffers) and the fix (releasing clean buffers unused for a period, plus a BDA refault safety net). It lists the changes, the rationale for dropping buffers without download, measurements, tests, behaviour change, and known limits. These match the raw summary and the objectives. </dd> </dl> </details> </dd> </dl> </details> <details> <summary><strong>Full details: Docstring Coverage</strong></summary> <dl> <dd> **Explanation** Docstring coverage is 15.38% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 13 functions across 8 files. (1 skipped: 1 too large.) **Resolution** Write docstrings for the functions missing them to satisfy the coverage threshold. </dd> </dl> </details> </dd> </dl> </details> <!-- pre_merge_checks_walkthrough_end --> <!-- autopilot:start --> - [ ] <!-- {"checkboxId":"2708ad07-9f24-4260-9c11-7dc76a49f2e3"} --> <strong title="Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts">Autofix</strong> · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts <!-- autopilot:end --> <!-- tips_start --> Thanks for using [CodeRabbit](https://coderabbit.ai?utm_source=oss&utm_medium=github&utm_campaign=KytyPS5/KytyPS5&utm_content=1934)! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. <details> <summary><strong>❤️ Share</strong></summary> <dl> <dd> - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code) </dd> </dl> </details> <sub>Comment `@coderabbitai help` to get the list of available commands.</sub> <!-- tips_end -->
@ -665,0 +717,4 @@
m_release_protected.Subtract(begin, end - begin);
std::erase_if(m_recent_releases, [&](const ReleasedRange& range) {
return range.begin < end && range.end > begin;
});
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-27 06:40 UTC · original · edited 2026-10-27 06:45 UTC

Minor · Functional Correctness · Quick win

Supported by static analysis

Script executed:

sed -n '665,755p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
sed -n '100,128p' src/graphics/host_gpu/renderer/renderContext.cpp
sed -n '125,155p' src/graphics/host_gpu/renderer/cache/faultManager.cpp

Repository: KytyPS5/KytyPS5

Length of output: 6294


Script executed:

set -o pipefail
printf '%s\n' '--- declarations and references ---'
rg -n -F --glob '*.cpp' --glob '*.h' -e 'void BufferCache::InvalidateMemory' -e 'InvalidateMemory(uint64_t' -e 'ForgetReleasedRanges' -e 'RecreateFaultedRange' -e 'UnmapMemory(' -e 'FindBuffer(' src/graphics/host_gpu/renderer src/graphics/host_gpu | head -240
printf '%s\n' '--- buffer cache invalidation and related definitions ---'
sed -n '1,180p' src/graphics/host_gpu/renderer/cache/bufferCache.h
rg -n -F --glob 'bufferCache.cpp' -e 'BufferCache::InvalidateMemory' -e 'BufferCache::FindBuffer' -e 'BufferCache::DeleteBuffer' -e 'BufferCache::CreateBuffer' src/graphics/host_gpu/renderer/cache
printf '%s\n' '--- render-context unmap callers and implementation ---'
rg -n -F --glob '*.cpp' --glob '*.h' -e 'RenderContext::UnmapMemory' -e 'UnmapMemory(' src/graphics/host_gpu src | head -180
sed -n '60,145p' src/graphics/host_gpu/renderer/renderContext.cpp
printf '%s\n' '--- fault manager complete callback path ---'
sed -n '1,210p' src/graphics/host_gpu/renderer/cache/faultManager.cpp

Repository: KytyPS5/KytyPS5

Length of output: 29823


Script executed:

set -o pipefail
printf '%s\n' '--- BufferCache invalidation, lookup, creation, and deletion ---'
sed -n '135,175p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
sed -n '280,365p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
sed -n '400,455p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp
printf '%s\n' '--- guest unmap entrypoints and range handling ---'
sed -n '2515,2570p' src/kernel/memory.cpp
sed -n '3180,3220p' src/kernel/memory.cpp
sed -n '3965,4005p' src/kernel/memory.cpp
printf '%s\n' '--- mapping range implementation references ---'
rg -n -F --glob '*.cpp' --glob '*.h' -e 'class GuestRange' -e 'struct GuestRange' -e 'm_mapped_ranges.Add' -e 'm_mapped_ranges.Subtract' -e 'UnmapMemory(vaddr, size)' src/kernel src/graphics | head -120

Repository: KytyPS5/KytyPS5

Length of output: 12285


Script executed:

set -o pipefail
printf '%s\n' '--- VirtualRanges span query and map alignment ---'
rg -n -F --glob '*.cpp' --glob '*.h' -e 'QuerySpan' -e 'class VirtualRanges' -e 'struct VirtualRanges' -e 'MapDirectMemory' -e 'IsAmmMemoryRange' src/kernel src | head -180
rg -n -F --glob '*.cpp' --glob '*.h' -e 'class VirtualRanges' -e 'struct VirtualRanges' -e 'QuerySpan' src | head -120

Repository: KytyPS5/KytyPS5

Length of output: 5797


Script executed:

set -o pipefail
sed -n '218,420p' src/kernel/memory.cpp
sed -n '2944,2995p' src/kernel/memory.cpp
sed -n '2560,2580p' src/kernel/memory.cpp

Repository: KytyPS5/KytyPS5

Length of output: 9471


Retain surviving release ranges after a partial unmap.

When an unmap overlaps only part of a released multi-page buffer, the current predicate removes the complete release record. A later BDA fault in the still-mapped portion then has no record to restore protection. The recreated buffer may be released again and return zero data on a later BDA read.

Split each overlapping ReleasedRange around the aligned unmapped range.

Suggested fix
--- "a/src/graphics/host_gpu/renderer/cache/bufferCache.cpp"
+++ "b/src/graphics/host_gpu/renderer/cache/bufferCache.cpp"
@@ -715,9 +715,22 @@
 	const auto begin = Common::AlignDown(vaddr, CACHING_PAGESIZE);
 	const auto end   = Common::AlignUp(vaddr + size, CACHING_PAGESIZE);
 	m_release_protected.Subtract(begin, end - begin);
-	std::erase_if(m_recent_releases, [&](const ReleasedRange& range) {
-		return range.begin < end && range.end > begin;
-	});
+	for (auto it = m_recent_releases.begin(); it != m_recent_releases.end();) {
+		const auto range = *it;
+		if (range.end <= begin || range.begin >= end) {
+			++it;
+			continue;
+		}
+		it = m_recent_releases.erase(it);
+		if (range.begin < begin) {
+			it = m_recent_releases.insert(it, ReleasedRange {range.begin, begin});
+			++it;
+		}
+		if (end < range.end) {
+			it = m_recent_releases.insert(it, ReleasedRange {end, range.end});
+			++it;
+		}
+	}
 }
 
 // A cached buffer keeps its pages write-protected. Once the game reuses that memory for other
Committable suggestion

IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	for (auto it = m_recent_releases.begin(); it != m_recent_releases.end();) {
		const auto range = *it;
		if (range.end <= begin || range.begin >= end) {
			++it;
			continue;
		}
		it = m_recent_releases.erase(it);
		if (range.begin < begin) {
			it = m_recent_releases.insert(it, ReleasedRange {range.begin, begin});
			++it;
		}
		if (end < range.end) {
			it = m_recent_releases.insert(it, ReleasedRange {end, range.end});
			++it;
		}
	}
**@⁠coderabbitai[bot]** on GitHub · 2026-10-27 06:40 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1934#discussion_r4385802814) · edited 2026-10-27 06:45 UTC <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/review-details.svg" width="16" height="16" align="absmiddle" alt=""></picture> Supported by static analysis</summary> <dl> <dd> Script executed: ```bash sed -n '665,755p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp sed -n '100,128p' src/graphics/host_gpu/renderer/renderContext.cpp sed -n '125,155p' src/graphics/host_gpu/renderer/cache/faultManager.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 6294 --- Script executed: ```bash set -o pipefail printf '%s\n' '--- declarations and references ---' rg -n -F --glob '*.cpp' --glob '*.h' -e 'void BufferCache::InvalidateMemory' -e 'InvalidateMemory(uint64_t' -e 'ForgetReleasedRanges' -e 'RecreateFaultedRange' -e 'UnmapMemory(' -e 'FindBuffer(' src/graphics/host_gpu/renderer src/graphics/host_gpu | head -240 printf '%s\n' '--- buffer cache invalidation and related definitions ---' sed -n '1,180p' src/graphics/host_gpu/renderer/cache/bufferCache.h rg -n -F --glob 'bufferCache.cpp' -e 'BufferCache::InvalidateMemory' -e 'BufferCache::FindBuffer' -e 'BufferCache::DeleteBuffer' -e 'BufferCache::CreateBuffer' src/graphics/host_gpu/renderer/cache printf '%s\n' '--- render-context unmap callers and implementation ---' rg -n -F --glob '*.cpp' --glob '*.h' -e 'RenderContext::UnmapMemory' -e 'UnmapMemory(' src/graphics/host_gpu src | head -180 sed -n '60,145p' src/graphics/host_gpu/renderer/renderContext.cpp printf '%s\n' '--- fault manager complete callback path ---' sed -n '1,210p' src/graphics/host_gpu/renderer/cache/faultManager.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 29823 --- Script executed: ```bash set -o pipefail printf '%s\n' '--- BufferCache invalidation, lookup, creation, and deletion ---' sed -n '135,175p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp sed -n '280,365p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp sed -n '400,455p' src/graphics/host_gpu/renderer/cache/bufferCache.cpp printf '%s\n' '--- guest unmap entrypoints and range handling ---' sed -n '2515,2570p' src/kernel/memory.cpp sed -n '3180,3220p' src/kernel/memory.cpp sed -n '3965,4005p' src/kernel/memory.cpp printf '%s\n' '--- mapping range implementation references ---' rg -n -F --glob '*.cpp' --glob '*.h' -e 'class GuestRange' -e 'struct GuestRange' -e 'm_mapped_ranges.Add' -e 'm_mapped_ranges.Subtract' -e 'UnmapMemory(vaddr, size)' src/kernel src/graphics | head -120 ``` Repository: KytyPS5/KytyPS5 Length of output: 12285 --- Script executed: ```bash set -o pipefail printf '%s\n' '--- VirtualRanges span query and map alignment ---' rg -n -F --glob '*.cpp' --glob '*.h' -e 'QuerySpan' -e 'class VirtualRanges' -e 'struct VirtualRanges' -e 'MapDirectMemory' -e 'IsAmmMemoryRange' src/kernel src | head -180 rg -n -F --glob '*.cpp' --glob '*.h' -e 'class VirtualRanges' -e 'struct VirtualRanges' -e 'QuerySpan' src | head -120 ``` Repository: KytyPS5/KytyPS5 Length of output: 5797 --- Script executed: ```bash set -o pipefail sed -n '218,420p' src/kernel/memory.cpp sed -n '2944,2995p' src/kernel/memory.cpp sed -n '2560,2580p' src/kernel/memory.cpp ``` Repository: KytyPS5/KytyPS5 Length of output: 9471 --- </dd> </dl> </details> **Retain surviving release ranges after a partial unmap.** When an unmap overlaps only part of a released multi-page buffer, the current predicate removes the complete release record. A later BDA fault in the still-mapped portion then has no record to restore protection. The recreated buffer may be released again and return zero data on a later BDA read. Split each overlapping `ReleasedRange` around the aligned unmapped range. <details> <summary>Suggested fix</summary> <dl> <dd> ```diff --- "a/src/graphics/host_gpu/renderer/cache/bufferCache.cpp" +++ "b/src/graphics/host_gpu/renderer/cache/bufferCache.cpp" @@ -715,9 +715,22 @@ const auto begin = Common::AlignDown(vaddr, CACHING_PAGESIZE); const auto end = Common::AlignUp(vaddr + size, CACHING_PAGESIZE); m_release_protected.Subtract(begin, end - begin); - std::erase_if(m_recent_releases, [&](const ReleasedRange& range) { - return range.begin < end && range.end > begin; - }); + for (auto it = m_recent_releases.begin(); it != m_recent_releases.end();) { + const auto range = *it; + if (range.end <= begin || range.begin >= end) { + ++it; + continue; + } + it = m_recent_releases.erase(it); + if (range.begin < begin) { + it = m_recent_releases.insert(it, ReleasedRange {range.begin, begin}); + ++it; + } + if (end < range.end) { + it = m_recent_releases.insert(it, ReleasedRange {end, range.end}); + ++it; + } + } } // A cached buffer keeps its pages write-protected. Once the game reuses that memory for other ``` </dd> </dl> </details> <!-- suggestion_start --> <details> <summary>Committable suggestion</summary> <dl> <dd> > <picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-warning.svg" width="20" height="20" align="absmiddle" alt=""></picture> **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion for (auto it = m_recent_releases.begin(); it != m_recent_releases.end();) { const auto range = *it; if (range.end <= begin || range.begin >= end) { ++it; continue; } it = m_recent_releases.erase(it); if (range.begin < begin) { it = m_recent_releases.insert(it, ReleasedRange {range.begin, begin}); ++it; } if (end < range.end) { it = m_recent_releases.insert(it, ReleasedRange {end, range.end}); ++it; } } ``` </dd> </dl> </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:wombat --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:f1fa09e700a79d9ff915c62d --> <!-- This is an auto-generated reply by CodeRabbit -->
@ -4208,0 +4570,4 @@
"an unmap kept the protection of its range");
age_out();
Require(name, "released after remap", !registered(refault_offset, page),
"a remapped range stayed protected from stale release");
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-27 06:40 UTC · original · edited 2026-10-27 06:45 UTC

Minor · Functional Correctness · Quick win

The "released after remap" check can pass without testing stale release.

Step (j) unmaps and remaps merged_size bytes. Nothing then creates a buffer on that range. When age_out() runs, there is no buffer to release. !registered(refault_offset, page) is true whether or not the protection was cleared.

If a regression kept the protection after unmap, this check would still pass. The earlier IsReleaseProtected check covers only the protection record. It does not cover the release behavior that the comment on step (j) claims.

Create a buffer on the remapped range before age_out(). Check that the buffer exists first, so the later check cannot pass vacuously.

🧪 Proposed fix
+      const auto [remapped, remapped_offset] =
+          cache.ObtainBuffer(base + refault_offset, range_size, false, false);
+      Require(name, "remap allocation", remapped != nullptr && remapped_offset == 0 &&
+                                            registered(refault_offset, range_size),
+              "the remapped range was not cached on its own");
       age_out();
       Require(name, "released after remap", !registered(refault_offset, page),
               "a remapped range stayed protected from stale release");
Committable suggestion

IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

      const auto [remapped, remapped_offset] =
          cache.ObtainBuffer(base + refault_offset, range_size, false, false);
      Require(name, "remap allocation", remapped != nullptr && remapped_offset == 0 &&
                                            registered(refault_offset, range_size),
              "the remapped range was not cached on its own");
      age_out();
      Require(name, "released after remap", !registered(refault_offset, page),
              "a remapped range stayed protected from stale release");
**@⁠coderabbitai[bot]** on GitHub · 2026-10-27 06:40 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1934#discussion_r4385802833) · edited 2026-10-27 06:45 UTC <!-- coderabbit-ai-generated:v1 --> **<picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/amber-16.svg" width="16" height="16" align="absmiddle" alt=""></picture> Minor** · **Functional Correctness** · **Quick win** **The "released after remap" check can pass without testing stale release.** Step (j) unmaps and remaps `merged_size` bytes. Nothing then creates a buffer on that range. When `age_out()` runs, there is no buffer to release. `!registered(refault_offset, page)` is true whether or not the protection was cleared. If a regression kept the protection after unmap, this check would still pass. The earlier `IsReleaseProtected` check covers only the protection record. It does not cover the release behavior that the comment on step (j) claims. Create a buffer on the remapped range before `age_out()`. Check that the buffer exists first, so the later check cannot pass vacuously. <details> <summary>🧪 Proposed fix</summary> <dl> <dd> ```diff + const auto [remapped, remapped_offset] = + cache.ObtainBuffer(base + refault_offset, range_size, false, false); + Require(name, "remap allocation", remapped != nullptr && remapped_offset == 0 && + registered(refault_offset, range_size), + "the remapped range was not cached on its own"); age_out(); Require(name, "released after remap", !registered(refault_offset, page), "a remapped range stayed protected from stale release"); ``` </dd> </dl> </details> <!-- suggestion_start --> <details> <summary>Committable suggestion</summary> <dl> <dd> > <picture><img src="https://storage.googleapis.com/coderabbit_public_assets/pre-merge-checks-warning.svg" width="20" height="20" align="absmiddle" alt=""></picture> **IMPORTANT** > Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements. ```suggestion const auto [remapped, remapped_offset] = cache.ObtainBuffer(base + refault_offset, range_size, false, false); Require(name, "remap allocation", remapped != nullptr && remapped_offset == 0 && registered(refault_offset, range_size), "the remapped range was not cached on its own"); age_out(); Require(name, "released after remap", !registered(refault_offset, page), "a remapped range stayed protected from stale release"); ``` </dd> </dl> </details> <!-- suggestion_end --> <!-- fingerprinting:phantom:medusa:beignet55 --> <!-- cr-indicator-types:potential_issue --> <!-- cr-comment:v1:7b39d9095cc9e4f499a2e9d2 --> <!-- This is an auto-generated reply by CodeRabbit -->
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-27 06:40 UTC · original · reviewed

Actionable comments posted: 2


Review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between fd6b28c4b2 and 1ca8e2ce00.

Files selected for processing: 9
  • src/common/debugCounters.h
  • src/graphics/host_gpu/renderer/cache/bufferCache.cpp
  • src/graphics/host_gpu/renderer/cache/bufferCache.h
  • src/graphics/host_gpu/renderer/cache/faultManager.cpp
  • src/graphics/host_gpu/renderer/renderContext.cpp
  • src/graphics/host_gpu/renderer/renderDraw.cpp
  • src/graphics/presentation/performanceOverlay.cpp
  • src/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp
  • tests/ShaderRecompilerComputeTests.cpp

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-27 06:40 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1934#pullrequestreview-5663170260) · **reviewed** <!-- coderabbit-ai-generated:v1 --> **Actionable comments posted: 2** --- <details> <summary><picture><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/info.svg" width="16" height="16" align="absmiddle" alt=""></picture> Review info</summary> <dl> <dd> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/cog.svg" width="16" height="16" align="absmiddle" alt=""></picture> Run configuration</summary> <dl> <dd> - **Source mode**: Auto - **Repository**: [KytyPS5/KytyPS5](<https://github.com/KytyPS5/KytyPS5>) - **Branch**: [main](<https://github.com/KytyPS5/KytyPS5/tree/main>) - **File**: [.coderabbit.yaml](<https://github.com/KytyPS5/KytyPS5/blob/fd6b28c4b261a59b35f8f6a225a8fbe87b41f993/.coderabbit.yaml>) - **Commit**: [fd6b28c](<https://github.com/KytyPS5/KytyPS5/commit/fd6b28c4b261a59b35f8f6a225a8fbe87b41f993>) - **Layers**: Repository YAML - **Review profile**: CHILL - **Plan**: Advanced - **Run ID**: `f9698afe-dca8-42e1-917e-a7f382530532` </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/git-commit-horizontal.svg" width="16" height="16" align="absmiddle" alt=""></picture> Commits</summary> <dl> <dd> Reviewing files that changed from the base of the PR and between fd6b28c4b261a59b35f8f6a225a8fbe87b41f993 and 1ca8e2ce000a0644651af1ada35ad7723a2268aa. </dd> </dl> </details> <details> <summary><picture><source media="(prefers-color-scheme: dark)" srcset="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner-dark.svg"><img src="https://storage.googleapis.com/coderabbit_public_assets/review-comment-icons-v1/file-plus-corner.svg" width="16" height="16" align="absmiddle" alt=""></picture> Files selected for processing: 9</summary> <dl> <dd> * `src/common/debugCounters.h` * `src/graphics/host_gpu/renderer/cache/bufferCache.cpp` * `src/graphics/host_gpu/renderer/cache/bufferCache.h` * `src/graphics/host_gpu/renderer/cache/faultManager.cpp` * `src/graphics/host_gpu/renderer/renderContext.cpp` * `src/graphics/host_gpu/renderer/renderDraw.cpp` * `src/graphics/presentation/performanceOverlay.cpp` * `src/graphics/shader/recompiler/ir/passes/ShaderInfoCollection.cpp` * `tests/ShaderRecompilerComputeTests.cpp` </dd> </dl> </details> **Included review availability:** This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review. </dd> </dl> </details> <!-- This is an auto-generated comment by CodeRabbit for review status --> <!-- coderabbit-review-publication v1 publication=71b15efb-8db7-4dde-b669-28b96abb856b attempt=9fa32e0c-d966-4e00-b9b5-8b26bb38bd1a batch=1/1 -->
@ -665,0 +717,4 @@
m_release_protected.Subtract(begin, end - begin);
std::erase_if(m_recent_releases, [&](const ReleasedRange& range) {
return range.begin < end && range.end > begin;
});
Author
Owner

@⁠MrBigBritches on GitHub · 2026-10-27 06:45 UTC · original

Correct in principle, but the impact is bounded. Protection is already split by Subtract; the only loss is the history record of an unrefaulted range. The worst case is one extra refault cycle before the range is protected, the same documented outcome as a record ageing out of the FIFO. The partial-unmap-then-BDA-only-read pattern is rare, and the suggested in-place splitting is O(N²) on the deque and breaks the capacity cap.

**@⁠MrBigBritches** on GitHub · 2026-10-27 06:45 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1934#discussion_r4385834372) Correct in principle, but the impact is bounded. Protection is already split by Subtract; the only loss is the history record of an unrefaulted range. The worst case is one extra refault cycle before the range is protected, the same documented outcome as a record ageing out of the FIFO. The partial-unmap-then-BDA-only-read pattern is rare, and the suggested in-place splitting is O(N²) on the deque and breaks the capacity cap.
@ -4208,0 +4570,4 @@
"an unmap kept the protection of its range");
age_out();
Require(name, "released after remap", !registered(refault_offset, page),
"a remapped range stayed protected from stale release");
Author
Owner

@⁠MrBigBritches on GitHub · 2026-10-27 06:45 UTC · original

The buffer is not removed by unmap. BufferCache::InvalidateMemory only invalidates tracker state (MemoryTracker::InvalidateRegion) and queues a BDA sync; buffers are only deleted by JoinOverlap, stale release and the pressure GC. So the merged buffer from (i) is still registered when age_out() runs, and the release check is not vacuous.

**@⁠MrBigBritches** on GitHub · 2026-10-27 06:45 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1934#discussion_r4385836007) The buffer is not removed by unmap. BufferCache::InvalidateMemory only invalidates tracker state (MemoryTracker::InvalidateRegion) and queues a BDA sync; buffers are only deleted by JoinOverlap, stale release and the pressure GC. So the merged buffer from (i) is still registered when age_out() runs, and the release check is not vacuous.
@ -665,0 +717,4 @@
m_release_protected.Subtract(begin, end - begin);
std::erase_if(m_recent_releases, [&](const ReleasedRange& range) {
return range.begin < end && range.end > begin;
});
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-27 06:46 UTC · original

@⁠MrBigBritches Agreed. Subtract preserves protection outside the unmapped range. The loss affects only the recent-release history, which the bounded FIFO can also discard.

My suggested split was not a suitable fix. Repeated middle erases and inserts can make the deque traversal O(N²), and the suggestion does not enforce RECENT_RELEASE_CAPACITY.

I withdraw the requested change under this best-effort history design. One qualification: protection after an extra refault cycle depends on the new release record surviving until the next fault. The code does not guarantee that bound if further unmaps or FIFO eviction remove the record.

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-27 06:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1934#discussion_r4385836904) <!-- coderabbit-ai-generated:v1 --> @⁠MrBigBritches Agreed. `Subtract` preserves protection outside the unmapped range. The loss affects only the recent-release history, which the bounded FIFO can also discard. My suggested split was not a suitable fix. Repeated middle erases and inserts can make the deque traversal O(N²), and the suggestion does not enforce `RECENT_RELEASE_CAPACITY`. I withdraw the requested change under this best-effort history design. One qualification: protection after an extra refault cycle depends on the new release record surviving until the next fault. The code does not guarantee that bound if further unmaps or FIFO eviction remove the record. <!-- <review_comment_withdrawn> --> ✅ Review thread resolved. <sub><i>You are interacting with an AI system.</i></sub> <!-- This is an auto-generated reply by CodeRabbit -->
@ -4208,0 +4570,4 @@
"an unmap kept the protection of its range");
age_out();
Require(name, "released after remap", !registered(refault_offset, page),
"a remapped range stayed protected from stale release");
Author
Owner

@⁠coderabbitai[bot] on GitHub · 2026-10-27 06:46 UTC · original

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
ast-grep outline src/graphics/host_gpu/renderer/renderContext.cpp --match 'MapMemory|UnmapMemory'
ast-grep outline src/graphics/host_gpu/renderer/cache/bufferCache.cpp --match 'InvalidateMemory|ReleaseStaleBuffers|ForgetReleasedRanges|IsRegionRegistered'
rg -n -A45 -B3 'void RenderContext::(UnmapMemory|MapMemory)\(' src/graphics/host_gpu/renderer/renderContext.cpp
rg -n -A65 -B3 'BufferCache::(InvalidateMemory|ReleaseStaleBuffers|ForgetReleasedRanges|IsRegionRegistered)\(' src/graphics/host_gpu/renderer/cache/bufferCache.cpp

Length of output: 12556


@MrBigBritches You are correct. I checked RenderContext::UnmapMemory and BufferCache::InvalidateMemory. They invalidate tracker state and clear release protection, but they do not remove the cached buffer.

The merged buffer from step (i) remains registered when age_out() runs in step (j). The final check therefore tests stale release and is not vacuous.

My finding was incorrect. I withdraw it; the proposed allocation is unnecessary.

✅ Review thread resolved.

You are interacting with an AI system.

**@⁠coderabbitai[bot]** on GitHub · 2026-10-27 06:46 UTC · [original](https://github.com/KytyPS5/KytyPS5/pull/1934#discussion_r4385838995) <!-- coderabbit-ai-generated:v1 --> <details> <summary>🧩 Analysis chain</summary> <dl> <dd> 🏁 Script executed: ```shell #!/bin/bash ast-grep outline src/graphics/host_gpu/renderer/renderContext.cpp --match 'MapMemory|UnmapMemory' ast-grep outline src/graphics/host_gpu/renderer/cache/bufferCache.cpp --match 'InvalidateMemory|ReleaseStaleBuffers|ForgetReleasedRanges|IsRegionRegistered' rg -n -A45 -B3 'void RenderContext::(UnmapMemory|MapMemory)\(' src/graphics/host_gpu/renderer/renderContext.cpp rg -n -A65 -B3 'BufferCache::(InvalidateMemory|ReleaseStaleBuffers|ForgetReleasedRanges|IsRegionRegistered)\(' src/graphics/host_gpu/renderer/cache/bufferCache.cpp ``` Length of output: 12556 --- </dd> </dl> </details> `@MrBigBritches` You are correct. I checked `RenderContext::UnmapMemory` and `BufferCache::InvalidateMemory`. They invalidate tracker state and clear release protection, but they do not remove the cached buffer. The merged buffer from step (i) remains registered when `age_out()` runs in step (j). The final check therefore tests stale release and is not vacuous. My finding was incorrect. I withdraw it; the proposed allocation is unnecessary. <!-- <review_comment_withdrawn> --> ✅ Review thread resolved. <sub><i>You are interacting with an AI system.</i></sub> <!-- This is an auto-generated reply by CodeRabbit -->
This pull request has changes conflicting with the target branch.
  • src/graphics/host_gpu/renderer/cache/bufferCache.h
  • src/graphics/host_gpu/renderer/renderDraw.cpp
View command line instructions

Manual merge helper

Use this merge commit message when completing the merge manually.

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/1934/head:github-bot/gh-1934'
git switch 'github-bot/gh-1934'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-1934'
git switch 'github-bot/gh-1934'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-1934'
git switch 'github-bot/gh-1934'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-1934'
git switch 'main'
git merge --squash 'github-bot/gh-1934'
git switch 'main'
git merge --ff-only 'github-bot/gh-1934'
git switch 'main'
git merge 'github-bot/gh-1934'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.