Skip to content

xmem: coalesce contiguous runs in XMemMapPhysicalPages - #742

Closed
madhyn wants to merge 2 commits into
ProjectLeonida:mainfrom
madhyn:perf/xmem-coalesce-map-physical-pages
Closed

madhyn wants to merge 2 commits into
ProjectLeonida:mainfrom
madhyn:perf/xmem-coalesce-map-physical-pages

Conversation

@madhyn

@madhyn madhyn commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

What and why

During retail startup (1.0.2.1), after CopyDescriptorsSimple, the title calls XMemMapPhysicalPages with 99,776 contiguous pages (6,236.0 MiB) in a single call. Mapping them one 64 KiB page at a time issues ~100k separate VirtualFree(MEM_PRESERVE_PLACEHOLDER) + MapViewOfFile3 calls, which under Wine 11.22 takes longer than 30 seconds and triggers the title's internal 30 s watchdog assert (0x142215c35).

This change coalesces contiguous runs of pages from the same Section and consecutive offsets into a single isolate_placeholder + MapViewOfFile3 call, while preserving per-page unmap/remap semantics:

  • MappedPage records view_base, view_pages, and view_protect.
  • unmap_page splits a multi-page view when a middle page is unmapped or overwritten, re-mapping the surviving prefix and suffix runs while keeping their backing data intact.
  • If a coalesced map_view_run fails (e.g. pre-split placeholders), XMemMapPhysicalPages falls back to mapping that run page-by-page.

Testing

  • Added test_coalesced_run_partial_unmap in runtime/test/xmem_test.cpp (maps 4 contiguous pages, unmaps a middle page, verifies prefix/suffix data survival, remaps the middle page back, unmaps and frees).
  • ctest -R xmem under Wine 11.22 (Arch Linux):
    • d3d12_xmem_placed: passed.
    • xmem: 223/228 checks passed, including all 11 checks of test_coalesced_run_partial_unmap (the 5 existing failures are Wine 11.22 VirtualQuery / PAGE_READONLY / commit-charge checks that also fail on main).
  • Retail gta6rt.sh --run (with d3d12_xs: device slot 74 returns S_OK instead of reaching ShaderCacheControl, again (RT-SLOT74) #385 + d3d12_xs: accept Xbox ID3D12GraphicsCommandListX IID in CreateCommandListX #445 stack): the 99,776-page (6,236 MiB) XMemMapPhysicalPages call dropped from >30,000 ms (watchdog hang) to 14 ms, advancing boot through device slot 74, dstorage (CreateStatusArray, CreateQueue1, CPU zlib inflate), and reaching device slot 108.

AI-assisted: yes

@abnalstlll-byte abnalstlll-byte left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Audited and verified. Clean-room compliant.

  • Coalesces contiguous physical page mappings into single virtual memory placeholder view mappings via map_view_run in runtime/shims/xmem.cpp.
  • Handles partial unmapping inside coalesced views by splitting into prefix/suffix views.
  • Test coverage in test_coalesced_run_partial_unmap (xmem_test.cpp) verifies preservation of unmapped/remapped physical backing.

@moffington

Copy link
Copy Markdown
Contributor

Independently tested 6ed318f2e against 2d73c242f under Wine 11.20 with clang-cl 23.1.3 and xwin.

All 11 new XMem checks pass, d3d12_xmem_placed passes, and additional partial-unmap/remap probes behaved correctly. The same five pre-existing Wine metadata failures remain.

The mapping improvement is substantial (4,096 pages: 150.65 ms → 0.60 ms), but I found a significant bulk-unmap regression:

Pages Base PR
1,024 12.22 ms 97.76 ms
2,048 23.20 ms 357.69 ms
4,096 49.91 ms 1,207.14 ms

The remap race test also increased from 249 ms to 2,404 ms.

The apparent cause is page-by-page unmap_page calls repeatedly unmapping and reconstructing the remaining coalesced view, producing quadratic scaling. This could be particularly expensive for the large mappings motivating this PR.

Could we introduce a range-aware unmap helper that unmaps each intersecting view once and reconstructs only surviving prefixes and suffixes? That should preserve the mapping speedup without introducing the bulk-unmap regression.

@madhyn

madhyn commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Implemented unmap_range in f6cfa2f25 to address the O(N²) bulk-unmap regression:

  • Added unmap_range(start, count) in runtime/shims/xmem.cpp so each intersecting coalesced view is unmapped once, with at most one prefix and/or suffix map_view_run reconstruction for surviving pages outside the unmapped range. unmap_page now delegates to unmap_range(address, 1).
  • Updated XMemMapPhysicalPages to determine contiguous zero/non-zero runs first and call unmap_range once per run instead of calling unmap_page page-by-page.
  • Extended test_coalesced_run_partial_unmap in runtime/test/xmem_test.cpp to cover multi-page middle sub-range unmaps.
  • ctest -R xmem (Wine 11.22): d3d12_xmem_placed passed; xmem 227/232 checks passed (all 15 checks in test_coalesced_run_partial_unmap pass; same 5 pre-existing Wine metadata/protection failures), and the 4,096-page remap race test dropped to 6 ms.

AI-assisted: yes

@milk4sale

Copy link
Copy Markdown
Contributor

Tested f6cfa2f25 with the retail 1.0.2.1 package on an RTX 4070 Ti (NVIDIA 620.70.06), wine-staging 11.21, Linux (CachyOS): the two commits cherry-picked onto #939's head eb6a08cd3 (they apply cleanly), gta6rt --first-run-ui, network off, clang-cl 23.1.4 + xwin build. Counts only.

#939 alone (4 runs) #939 + this pull request (2 runs)
End of the run the title's watchdog (the write to 0 at +0x2215c35) at 32.0 to 32.4 s, 30 s after the 99,776-page request still running at my 240 s limit, no exception
D3D12 calls 1,657 to 1,662 676,947 and 738,683
PresentX ok 0 10,946 and 12,110

The wineserver's side of the stall, which I have not seen posted: sampled once a second from outside the sandbox (/proc/<pid>/task/*/stat and status), after XMemAllocatePhysicalPages of 99,776 pages the title's main thread makes about 7,300 voluntary context switches a second for 27 s or more, about 190,000 in all, which is two server round trips a page. Its own CPU use falls from 0.8 to 0.05 s per second while the wineserver's rises from 0.2 to 0.9 s per second, so each map costs the server more than the one before. With this change the wineserver gains under 0.2 s of CPU in the 5 s after the request.

One of the four runs had #939's file-backed section switched off (LEONIDA_XMEM_BACKING_DIR set to a non-absolute value) and stalled the same way, so it is the number of views and not the kind of section.

Not checked here: xmem_test, a partial unmap inside the 99,776-page view, and Windows. The frames the #939 stack presents under Wine are black in both runs (every captured frame up to frame 5,851); I have not looked into why, and it is not this pull request's subject. AI-assisted (Claude Code).

@milk4sale

Copy link
Copy Markdown
Contributor

Correction to my comment above: the two runs with this pull request presented 5,473 and 6,055 frames, not 10,946 and 12,110. Each present writes two trace lines that contain PresentX ok (the queue method and the presentation core), and I counted lines. The call counts, the timings and the wineserver numbers stand; so does the result (no stall, 240 s without an exception).

@madhyn

madhyn commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Closing as superseded — coalesced physical page views and range-based unmap_range landed on main via #984. Huge thanks to @moffington for catching the O(N²) bulk-unmap regression and to @milk4sale for the Wine/wineserver benchmarks.

@madhyn madhyn closed this Nov 25, 2026
clquwu pushed a commit to clquwu/leonida-ultimate that referenced this pull request Nov 25, 2026
…nt 2D mip loads, Win11 timer opt-out

Translator (tools/rdna2spirv.py)
- ubiquitarianism/leonida#1585 (whoalin1, GPL-3.0): the low-16 mask of every
  int-derived value merged into a preserved 16-bit half is OpBitFieldUExtract
  (base 0, count 16), not OpBitwiseAnd & 0xFFFF, which NVIDIA's compiler
  miscompiles (the kept high half corrupted). Six sites: VOP3 16-bit integer
  results, mad_i16/u16, min/max/med3, signed cvt_i16_f16 / cvt_norm_i16_f16,
  signed saturate_int16. Two tests that pinned the old shape updated; new
  tests/semantic/test_nv_and16_extract.py (shape census + interpreter values,
  negative control; fails on the previous translator).
- ubiquitarianism/leonida#1572 (tedin7, GPL-3.0), refined: 2D image_load_mip
  with glc reads the coherent storage view for mip 0; any other mip takes the
  sampled fetch at that level instead of upstream's zero-fill, which is only
  right for a single-level T#. Other dims and tfe/lwe stay Unsupported.
  CoherentMipLoad tests + spirv-val on four forms; design.md row updated.

Decoder (tools/rdna2_decode.py + native port)
- ubiquitarianism/leonida#1525 / #1524 (GPL-3.0): inline constants 240..248 on
  16-bit integer operands decode to their binary16 patterns (LLVM
  printImmediateInt16), so the translator no longer reads f32 bits there;
  ds_condxchg32 keeps one offset; ds_swizzle omits offset 0 and prints
  ROTATE/FFT as LLVM does. Ported to tools/rdna2_decode_native (tables passed
  through the blob, _src_is_int16 added to the fingerprint).

Runtime (runtime/src/main.cpp)
- FVF-07, after ThatRecompDev/five-star-recomp@344f05b (GPL-3.0):
  ScopedTimerResolution also opts out of Windows 11 timer-resolution
  throttling (PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION) and hands it
  back to the system with timeEndPeriod.

Guard only: Marvisak/VIctory#2091's Wave32 scalar-mask fix is already how this
translator works (EXEC is a per-lane flag, scalar ops unmasked, wave-uniform
branches); tests/semantic/test_wave32_scalar_mask_branches.py pins it.

Skipped: ubiquitarianism/leonida#742 (XMem view coalescing). Natively it saves
about 230 ms once at startup (99,776 per-page views 233 ms vs 4 MiB views
4 ms), but every partial unmap would then tear down up to 63 neighbouring
pages, including GPU host-pointer imports and pages under in-flight I/O.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
clquwu added a commit to clquwu/leonida-ultimate that referenced this pull request Nov 25, 2026
…h commit (#1707), MSVC SEH helpers (#1499)

Wave 9A (GPL-3.0 direct adaptations from ubiquitarianism/leonida):
- ProjectLeonida/mandy#742 (madhyn): coalesce contiguous physical-page runs into single MapViewOfFile3 views in XMemMapPhysicalPages and copy_page_mappings, splitting multi-page views on partial unmap/remap, coalescing split placeholders on remap, and avoiding O(N^2) splits during TitleVirtualFree window teardown. Preserves GPU-only <-> CPU-view pair mirroring, PageTrack write tracking, and pre/post unmap remap_epoch bumps.
- ProjectLeonida/mandy#1707 (Tortoche): 64-page-aligned (4 MiB) fault-ahead batch commit in commit_mapped_page with view-end clamping, single-page VirtualAlloc fallback, PageTrack committed/change propagation across every newly committed page in the batch, and PAGE_READONLY/PAGE_GUARD preservation (keeping tiny 1..3-page views demand-committed per page so sparse shadow/stamp tests do not over-commit neighbors).
- ProjectLeonida/mandy#1499 (huangzhuoyue): replace per-#UD VirtualQuery kernel transitions in rt::cpu_emulation::handler and apply(Op::clzero) with MSVC SEH helpers (read_code_seh / zero_line_seh) while retaining writable()/readable() for try_clzero_loop and non-MSVC/clang-cl builds.
- Tests: added test_coalesced_run_partial_unmap, test_fault_batch_commit, and test_page_edge_faults. Verified xmem (500 checks), cpu_emulation, d3d12_xmem_placed, and d3d12_xmem_shadow (4/4 CTest passed) + gta6rt build + check_no_game_data.py.
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.

4 participants