Repository navigation
perf(gpu,hle): optimize view-memory guards, xmem alias mapping, texture waits, and relay card copy-back - #824
powplusplus wants to merge 1 commit into
Conversation
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9dae0a74e8
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if !mapped && n > crate::watch::PAGE { | ||
| let mut written = 0; | ||
| let mut off = 0; | ||
| while off < n { | ||
| let chunk = (n - off).min(crate::watch::PAGE); |
There was a problem hiding this comment.
Split failed coalesced merges at title-page boundaries
When adjacent flagged pieces straddle mapped and unmapped title memory, trimming to the first and last differing bytes can leave n <= PAGE even though the span crosses the mapping boundary. For example, changes at offsets 65535 and 65536 produce a two-byte read that fails, bypassing this fallback. The subsequent merge advances held without writing the changed byte in the mapped page, permanently losing that GPU result; merging the pieces separately preserves it. Split failed coalesced reads at actual title-page boundaries even when the trimmed span is smaller than PAGE. Fixed-size chunks starting at the trimmed offset can also straddle those boundaries.
Useful? React with 👍 / 👎.
| Some(g) if std::sync::Arc::ptr_eq(&g[0].0, &item.0) => g.push(item), | ||
| _ => groups.push(vec![item]), |
There was a problem hiding this comment.
Serialize merges with overlapping title-memory destinations
When at least four dirty runs trigger parallel merging, different shadows backed by overlapping title memory can enter separate workers. Such shadows are supported: shadow::register and lookup retain separate copies for overlapping or nested buffers. Grouping only by Arc leaves their before mutexes independent, so both workers can read the same title snapshot, merge different GPU changes, and then overwrite each other's results when card_merge_relay writes its entire first-to-last-difference span. The previous relay loop serialized these read-modify-write operations. Keep overlapping destinations in the same serialized group rather than treating distinct shadows as necessarily disjoint.
Useful? React with 👍 / 👎.
| if info.State == MEM_FREE || info.Type != MEM_MAPPED { | ||
| g.holes.insert_range(block, until); | ||
| g.clean.insert_range(block, until); |
There was a problem hiding this comment.
Keep ordinary private reservations out of the clean-hole cache
When a guarded window spans a mapped view and an ordinary private reservation, Type != MEM_MAPPED puts the reservation into clean as though it were an immutable placeholder. XMemVirtualAlloc can subsequently commit those private pages without calling title_memory_remapped, so the clean-range fast paths continue reporting no changes and leave the GPU copy holding the previous zeros. The previous implementation kept these blocks in absent and detected the commit through uncommitted_end. Keep ordinary reservations subject to rechecking, or add commit notifications before caching them as clean holes.
Useful? React with 👍 / 👎.
|
Test report on real hardware: AMD RX 6950 XT (RDNA2), Windows 11, Rust 1.98.1, with a GPU present. I merged this PR's head AI-assisted (Claude Code); no game data. |
|
Fixes for the three review findings above, as three commits on top of this PR's head
Results on Windows 11, RTX 3070:
Not yet run in game on its own. Our in-game runs have this PR merged into a larger stack. (AI-assisted: drafted with Codex and reviewed with Claude Code. No game data.) |
|
Follow-up to my test report above: the AI-assisted (Claude Code); no game data. |
…re waits, and relay card copy-back
9dae0a7 to
02deab8
Compare
|
Tested #824 (
(Note: #824 and #827 were tested together on the same branch.) Next up on our side is testing @npanu420's 3 review-fix commits ( AI-assisted: benchmark analysis and write-up prepared with AI assistance. |
Repeated checks of clean view heaps collect one entry per 64 KiB block while holding the guard mutex. If most blocks are clean, that allocates and scans thousands of entries to find just a few dirty gaps. Track the same clean blocks as contiguous half-open runs. The fully clean path needs a single lookup and the mixed path visits only dirty gaps. Keep the existing mapping queries, alias protection, and dirty notifications. Compare the interval operations with the old per-block representation and retain the existing guard and mapping tests. Based-on: fxceless#824 Tested-on: RX 6800, Fedora Linux 45, Wine (14 guard and mapping tests) Assisted-by: gpt-6.2 sol xhigh
Repeated checks of clean view heaps collect one entry per 64 KiB block while holding the guard mutex. If most blocks are clean, that allocates and scans thousands of entries to find just a few dirty gaps. Track the same clean blocks as contiguous half-open runs. The fully clean path needs a single lookup and the mixed path visits only dirty gaps. Keep the existing mapping queries, alias protection, and dirty notifications. Compare the interval operations with the old per-block representation and retain the existing guard and mapping tests. Based-on: fxceless#824 Tested-on: RX 6800, Fedora Linux 45, Wine (14 guard and mapping tests) Assisted-by: gpt-6.2 sol xhigh (pull request fxceless#979, fitted to this tree: the asking whether a range is held, and the notes of writes through other views, use the runs as well) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Related native Windows reproduction, independent of the performance stack: map three adjacent 64 KiB pages separately, return them to placeholders, then remap the range to three consecutive pages of the same committed section. The larger replacement can fail because it spans three separate placeholders, even though the addresses and section offsets are contiguous. This is consistent with A candidate that respects the returned boundaries instead of coalescing them passed both a targeted Windows test and full GPU texture readbacks. It tries the whole view first and only partitions a proven split on a replacement failure; it does not retry a commit failure or suppress invalidation. Tested on Windows with an RTX 5070 Ti, no game files required. This confirms the failure mode #824 deals with, not its end-to-end performance numbers. Keeping GPU/CPU copy-back ordered relative to the remap is a separate issue. The standalone patch below applies to Source-only diff: respect existing placeholder boundaries (12 KB)diff --git a/crates/victory-hle/src/modules/xmem.rs b/crates/victory-hle/src/modules/xmem.rs
index e898459..c759cc1 100644
--- a/crates/victory-hle/src/modules/xmem.rs
+++ b/crates/victory-hle/src/modules/xmem.rs
@@ -769,9 +769,84 @@ pub fn map_alias(to: u64, from: u64, len: u64) -> bool {
true
}
-/// Maps `slice` and the slices after it over `[base, base + len)`, which
-/// must lie in one placeholder.
+/// Maps consecutive slices at `base`. A single backing run can span several
+/// destination placeholders left by earlier page-by-page mappings.
fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool {
+ match map_view(physical, base, len, slice) {
+ Ok(()) => true,
+ Err(MapError::Commit) => false,
+ Err(MapError::Replace(error, slice)) => {
+ // Keep the single-view fast path. Only partition a failed request
+ // if the first reserved region really ends within it. Do not
+ // coalesce placeholders or retry a commitment failure.
+ if len > PAGE
+ && let Some(first) = reserved_prefix(base)
+ && first < len
+ {
+ let mut offset = 0;
+ let mut size = first;
+ loop {
+ let at = base + offset;
+ let start = Slice {
+ index: slice.index + offset / PAGE,
+ section: slice.section.clone(),
+ };
+ // As with multiple backing runs, any installed prefix
+ // remains valid and tracked if a later replacement fails.
+ match map_view(physical, at, size, start) {
+ Ok(()) => (),
+ Err(MapError::Commit) => return false,
+ Err(MapError::Replace(error, _)) => return replace_failed(at, size, error),
+ }
+ offset += size;
+ if offset == len {
+ return true;
+ }
+ let Some(next) = reserved_prefix(base + offset) else {
+ return replace_failed(base, len, error);
+ };
+ size = next.min(len - offset);
+ }
+ }
+ replace_failed(base, len, error)
+ }
+ }
+}
+
+/// This is only an upper bound on a replaceable span: a reserved region need
+/// not be a placeholder. MapViewOfFile3 still validates each replacement.
+fn reserved_prefix(base: usize) -> Option<usize> {
+ let mut info = MEMORY_BASIC_INFORMATION::default();
+ // SAFETY: querying our process, with a live, correctly sized output buffer.
+ let queried = unsafe {
+ VirtualQueryEx(GetCurrentProcess(), base as *const c_void, &mut info, size_of_val(&info))
+ };
+ (queried != 0
+ && info.State == MEM_RESERVE
+ && info.BaseAddress as usize == base
+ && info.RegionSize >= PAGE
+ && info.RegionSize.is_multiple_of(PAGE))
+ .then_some(info.RegionSize)
+}
+
+enum MapError {
+ Replace(std::io::Error, Slice),
+ Commit,
+}
+
+fn replace_failed(base: usize, len: usize, error: std::io::Error) -> bool {
+ tracing::warn!(
+ address = format_args!("{base:#x}"),
+ len,
+ %error,
+ "mapping physical pages failed (not a placeholder?)"
+ );
+ false
+}
+
+/// Replaces part or all of one placeholder, and records only the view the
+/// host actually installed. Callers hold the page table and remapping guard.
+fn map_view(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> Result<(), MapError> {
// SAFETY: splits the placeholder around the range (failing harmlessly
// when the range is the whole placeholder), then maps the section
// there; both act only on placeholders.
@@ -793,19 +868,13 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool {
0,
)
};
- if view.Value as usize != base {
- tracing::warn!(
- address = format_args!("{base:#x}"),
- len,
- error = %std::io::Error::last_os_error(),
- "mapping physical pages failed (not a placeholder?)"
- );
- return false;
+ if view.Value.is_null() || view.Value as usize != base {
+ return Err(MapError::Replace(std::io::Error::last_os_error(), slice));
}
if !commit(base, len) {
// SAFETY: the view just mapped, back to a placeholder.
unsafe { UnmapViewOfFile2(GetCurrentProcess(), view, MEM_PRESERVE_PLACEHOLDER) };
- return false;
+ return Err(MapError::Commit);
}
// New contents, read-write: the GPU side's copies no longer guard it.
victory_gpu::title_memory_remapped(base, len);
@@ -815,7 +884,7 @@ fn map(physical: &mut Physical, base: usize, len: usize, slice: Slice) -> bool {
physical.shown.entry(slice.key(k)).or_default().push(base + k * PAGE);
}
physical.views.insert(base, (len, slice));
- true
+ Ok(())
}
/// Commits the section pages a view shows (once per page, whichever view).
@@ -1034,6 +1103,9 @@ pub(crate) fn module() -> HleModule {
mod tests {
use super::*;
+ #[cfg(feature = "diagnostics")]
+ mod gpu;
+
fn query(address: *const c_void) -> BasicInformation {
// SAFETY: plain data; zero is a valid value.
let mut info: BasicInformation = unsafe { std::mem::zeroed() };
@@ -1329,6 +1401,151 @@ mod tests {
pages
}
+ /// Owns a small reservation, possibly split into multiple placeholders.
+ struct AliasWindow {
+ base: usize,
+ pages: usize,
+ }
+
+ impl AliasWindow {
+ fn new(pages: usize) -> Self {
+ let base = XMemVirtualAlloc(
+ std::ptr::null_mut(),
+ pages * PAGE,
+ MEM_RESERVE | PAGES_64K,
+ 0,
+ PAGE_READWRITE,
+ );
+ assert!(!base.is_null());
+ Self { base: base as usize, pages }
+ }
+
+ fn at(&self, page: usize) -> *mut c_void {
+ assert!(page < self.pages);
+ (self.base + page * PAGE) as *mut c_void
+ }
+
+ fn assert_bytes(&self, page: usize, byte: u8) {
+ let at = self.at(page);
+ assert_eq!(query(at).host.State, MEM_COMMIT, "page {page} is not mapped");
+ // SAFETY: the fixture owns a committed page and does not remap it concurrently.
+ let bytes = unsafe { std::slice::from_raw_parts(at.cast::<u8>(), PAGE) };
+ assert!(bytes.iter().all(|&b| b == byte), "wrong bytes in page {page}");
+ }
+ }
+
+ impl Drop for AliasWindow {
+ fn drop(&mut self) {
+ XMemMapPhysicalPages(self.at(0), self.pages, std::ptr::null());
+ let end = self.base + self.pages * PAGE;
+ let mut at = self.base;
+ while at < end {
+ let mut info = MEMORY_BASIC_INFORMATION::default();
+ // SAFETY: query our window; the output is a live structure of the supplied size.
+ let queried = unsafe {
+ VirtualQueryEx(GetCurrentProcess(), at as *const c_void, &mut info, size_of_val(&info))
+ };
+ if queried == 0 || info.AllocationBase as usize != at || info.State != MEM_RESERVE
+ || info.RegionSize == 0 || info.RegionSize > end - at
+ {
+ break;
+ }
+ // SAFETY: this is the base of a remaining placeholder owned by the window.
+ unsafe { VirtualFree(at as *mut c_void, 0, MEM_RELEASE) };
+ at += info.RegionSize;
+ }
+ }
+ }
+
+ struct FixturePages(Vec<usize>);
+
+ impl Drop for FixturePages {
+ fn drop(&mut self) {
+ XMemFreePhysicalPages(self.0.len(), self.0.as_ptr());
+ }
+ }
+
+ #[test]
+ fn regrouped_pages_cross_old_placeholder_boundaries() {
+ let original = FixturePages(allocate(3));
+ let replacement = FixturePages(allocate(4));
+ let pool = AliasWindow::new(4);
+ let mapped = AliasWindow::new(3);
+ let other = AliasWindow::new(3);
+ for (set, first) in [(&original.0, 0x10), (&replacement.0, 0x20)] {
+ for (i, id) in set.iter().enumerate() {
+ assert!(write_physical(std::slice::from_ref(id), 0, &vec![first + i as u8; PAGE]));
+ }
+ }
+
+ assert_eq!(XMemMapPhysicalPages(pool.at(0), 4, replacement.0.as_ptr()), pool.at(0));
+ // Three distinct installed views, with distinct placeholders when unmapped.
+ for (i, id) in original.0.iter().enumerate() {
+ assert_eq!(XMemMapPhysicalPages(mapped.at(i), 1, id), mapped.at(i));
+ mapped.assert_bytes(i, 0x10 + i as u8);
+ }
+ assert_eq!(
+ XMemMapPhysicalPages(mapped.at(0), 3, replacement.0.as_ptr()),
+ mapped.at(0),
+ "a contiguous backing run must work across three old single-page views"
+ );
+ assert!(map_alias(other.base as u64, pool.base as u64, (3 * PAGE) as u64));
+ for i in 0..3 {
+ mapped.assert_bytes(i, 0x20 + i as u8);
+ other.assert_bytes(i, 0x20 + i as u8);
+ }
+
+ // Remap the middle pool page. Copied aliases must stay on its old backing.
+ assert_eq!(XMemMapPhysicalPages(pool.at(1), 1, &replacement.0[3]), pool.at(1));
+ pool.assert_bytes(1, 0x23);
+ // The mapped page is still writable through either other view.
+ // SAFETY: both fixture-owned views of this page are committed and writable.
+ unsafe { mapped.at(1).cast::<u8>().write_bytes(0x42, PAGE) };
+ other.assert_bytes(1, 0x42);
+ assert!(write_physical(&replacement.0[1..2], 0, &vec![0x65; PAGE]));
+ mapped.assert_bytes(1, 0x65);
+ other.assert_bytes(1, 0x65);
+ pool.assert_bytes(1, 0x23);
+ assert_eq!(XMemMapPhysicalPages(mapped.at(1), 1, std::ptr::null()), mapped.at(1));
+ assert_eq!(query(mapped.at(1)).host.State, MEM_RESERVE);
+ mapped.assert_bytes(0, 0x20);
+ mapped.assert_bytes(2, 0x22);
+ other.assert_bytes(1, 0x65);
+ }
+
+ #[test]
+ fn regrouped_pages_keep_larger_views_and_an_untouched_suffix() {
+ let original = FixturePages(allocate(5));
+ let replacement = FixturePages(allocate(4));
+ let placed = AliasWindow::new(5);
+ let alias = AliasWindow::new(1);
+ for (pages, start) in [(&original.0, 0x10), (&replacement.0, 0x20)] {
+ for (i, id) in pages.iter().enumerate() {
+ assert!(write_physical(std::slice::from_ref(id), 0, &vec![start + i as u8; PAGE]));
+ }
+ }
+ for (at, pages) in [(0, &original.0[..2]), (2, &original.0[2..])] {
+ assert_eq!(XMemMapPhysicalPages(placed.at(at), pages.len(), pages.as_ptr()), placed.at(at));
+ }
+ assert_eq!(XMemMapPhysicalPages(placed.at(0), 4, replacement.0.as_ptr()), placed.at(0));
+ // The four pages should fit in two views, not four single-page views.
+ let sizes: Vec<_> = physical()
+ .views
+ .range(placed.base..placed.base + 5 * PAGE)
+ .map(|(_, (len, _))| *len)
+ .collect();
+ assert_eq!(sizes, [2 * PAGE, 2 * PAGE, PAGE]);
+ // Installed views continue to own the backing after the page IDs are freed.
+ drop(replacement);
+ drop(original);
+ assert!(map_alias(alias.base as u64, placed.at(3) as u64, PAGE as u64));
+ alias.assert_bytes(0, 0x23);
+ for page in 0..4 {
+ placed.assert_bytes(page, 0x20 + page as u8);
+ }
+ placed.assert_bytes(4, 0x14);
+ }
+
/// The bytes of one page, through a view of our own.
fn page_bytes(page: usize) -> Vec<u8> {
let slice = physical().pages.get(&page).cloned().expect("known page"); |
|
I tried the readback-command coalescing idea on the RX 7900 XT with 16 KiB pieces. My local variant only joins consecutive CopyBufferRegion calls when the source resource, source offsets and destination offsets all continue. It keeps the CPU merge pieces and their original order. This tests one part of the proposal, on a different integration build. In the first room it removed 4,152 copy commands per frame. Median readback was 75.1 MB/frame at 16.5 ms on the copy queue. A preceding run with ordinary commands measured 77.2 MB/frame at 4.8 ms. The two sessions averaged 5.25 and 8.87 successful presents/s with 4,931 and 4,854 draws/frame respectively. The joined run also had substantially longer CPU preparation and GPU waits. One run each under shared system load; I can verify the command reduction, but can’t attribute the frame-time difference to coalescing. RADV 26.3.1, Wine 11.22, vkd3d-proton v3.1-83. |
Repeated checks of clean view heaps collect one entry per 64 KiB block while holding the guard mutex. If most blocks are clean, that allocates and scans thousands of entries to find just a few dirty gaps. Track the same clean blocks as contiguous half-open runs. The fully clean path needs a single lookup and the mixed path visits only dirty gaps. Keep the existing mapping queries, alias protection, and dirty notifications. Compare the interval operations with the old per-block representation and retain the existing guard and mapping tests. Based-on: fxceless/victory-fork#824 Tested-on: RX 6800, Fedora Linux 45, Wine (14 guard and mapping tests) Assisted-by: gpt-6.2 sol xhigh (cherry picked from commit ac6e475108f0e82ed6efb657e4f0b7552c0275f7)
Summary
Cuts CPU-side frame preparation, lock contention, and copy-back overhead in the 3D world from
0.1-0.2 fps(4,244-6,146 ms/frame, GPU 5-18% busy) to1.9-2.0 fps(498.7-536.7 ms/frame, GPU 71% busy) on RTX 3080 under GE-Proton11-14.Root Causes & Fixes
View-memory guards (
crates/victory-gpu/src/watch.rs,inplace.rs):BTreeSet<usize>tracking inGuards(protected,clean,absent,aliased) with a coalescing half-open intervalRangeSet(BTreeMap<usize, usize>), reducing 174 MiB heap checks to a single O(log intervals) lookup.Guards::holes) from reserved section views (MEM_MAPPED | MEM_RESERVE), adding placeholder holes tocleanuntiltitle_memory_remappedremoves them. Eliminates thousands ofVirtualQuerysyscalls per frame on sparse view buffers while preservingVirtualAlloc(MEM_COMMIT)detection on reserved section views.GUARDSfromMutextoRwLockwith read-first fast paths inwrites_since_kind,guard,ask_once,writing,title_memory_written, andtitle_memory_remapped.VirtualProtectcalls inprotect_hereandopen_here.GUARD_GENandJournal::ahead_guardedto cache guarded view-memory checks across a submission inask_once, plusJournal::last_writeandwrites_since_kindsotexture.rsavoids duplicatewatch::writescalls.inplace::pages_ofcalls insidewatch::protectwith single-lockinplace::aliased_pages_inthat checks view count bounds before allocating, eliminating thousands of temporaryVeccopies of filler-page view lists. Stored single-view mappings inline inPageSet(One(usize)/Many(BTreeSet<usize>)).Shadow refresh fast path (
crates/victory-gpu/src/shadow.rs,texture.rs):Shadow::all_copiedand zero-page tracking inShadow::copied, plusShadow::copy_stale_sparse, so unchanged refreshes skip per-page scans in O(1).VICTORY_TEXTURE_NO_WAITby default (VICTORY_TEXTURE_NO_WAIT=0to wait onMAPPING.read()), eliminating multi-second texture stalls whilexmemremaps streaming pages.Physical page alias mapping (
crates/victory-hle/src/modules/xmem.rs):Physical::shownwith inline single-viewShownPages(One(usize)/Many(HashSet<usize>)), replacing O(N)Vec::retainscans on the filler page while holdingMAPPING.write().map_aliasinto a single view mapping (withMEM_COALESCE_PLACEHOLDERSand page-by-page fallback across split placeholder boundaries).Card copy-back relay (
crates/victory-gpu/src/host.rs,shadow.rs):relay_card_backbeforeCopyBufferRegionandcard_merge_relay, with 64 KiB chunk fallback incard_merge_relaywhen a coalesced span crosses unmapped memory.VICTORY_WIDE_MERGEby default (VICTORY_WIDE_MERGE=0for single-threaded) and parallelizedrelay_card_backmerges across up to 8 workers grouped by shadow to avoidShadow::beforelock contention.Benchmarks (RTX 3080, GE-Proton11-14, live 3D world)
Measured against baseline (
8dd30ab+#737latch fix) on the same binary path and vkd3d-proton shader cache:0.1-0.2 fps(4,244-6,146 ms)1.9-2.0 fps(498.7-536.7 ms)5-18%(2,789-5,817 msidle)71%(47.1 msidle)copies1,324.7-2,545.7 ms37.6-63.6 mstextures(MAPPING.read()wait)1,382-4,566.9 ms(2,104-4,175.7 mswait)5.0-8.0 ms(0.0 mswait)411/frame, 1,170.4 ms(max127.9 ms)3.0/frame, 4.6 ms(max2.2 ms)534-846 ms(pre-coalesce relay3,280 ms)60.3 ms(61.0 MB, 956 pieces)Verification
origin/main(9376fd6), preservingVICTORY_VIEW_ASK,WatchKnownView/WatchFailed,Tracked, andVICTORY_CARD_FETCH_INFLIGHT.cargo clippy --target x86_64-pc-windows-gnu -p victory-gpu -p victory-hle --all-targets(default and--features diagnostics): zero warnings in touched files.watch::*:14/14passed (including newrange_set_merges_splits_and_queries_gapsandplaceholder_holes_join_clean_until_remapped)shadow::*:28/28passedinplace::*:6/6passedhost::*/descriptor::host::*/pipeline::host::*:34/34passed (1 ignored benchmark)xmem::*:13/13passed (including newmap_alias_coalesces_consecutive_pages_and_split_placeholders)