Skip to content

d3d12: evict geometry views on range release and retry refused ranges - #2094

Merged
aslan2142 merged 9 commits into
ProjectLeonida:mainfrom
qhukz13:cont/geometry-view-eviction
Nov 26, 2026
Merged

aslan2142 merged 9 commits into
ProjectLeonida:mainfrom
qhukz13:cont/geometry-view-eviction

Conversation

@qhukz13

@qhukz13 qhukz13 commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Item: RT-GEOMETRY-VIEW-EVICTION

Problem

runtime/shims/d3d12_geometry_views.h: once LEONIDA_GEOMETRY_MB is used up, resolve() marks a range refused for good, and no view is freed before teardown, even after the title releases the memory it copies.

Change

  • Release events. xmem reports title ranges that go away: XMemFree/XMemFreeDefault, VirtualFree MEM_RELEASE/MEM_DECOMMIT, the XMemMapPhysicalPages unmap and the CopyPageMappingsBatchX unmap range. They go to a small queue in title_geometry_watch.h (note_released/take_released). Ranges outside every watched tile are not queued; a GPU-only range counts through its CPU view, where the views are keyed. When the queue is full it collapses into one covering range: retiring a few views too many is harmless (they are made again on the next resolve), dropping a release is not.
  • Retire, then reap. On the submit thread (before_execute_, before the geometry refresh) a released range retires every view over it at once: it leaves keys_, the address map, the fast lookup, the tile watches and the title VA aliases. Its storage is freed only once completed_retire_ticket() passes the submitted_retire_ticket() taken at retirement, so in-flight work keeps reading valid memory. The recording threads never drain, so they do not wait on GeometryViews::mutex_ while a refresh holds it (speed-26).
  • Retry. A refused key remembers the free generation it was refused in. resolve() answers it from the fast map without a lock while nothing was freed, and tries again once a reap has returned budget.
  • Storage. TitleBufferWindows keeps coalesced free ranges per block, destroys a block when its last range comes back, and keeps one empty 4 MiB block as a spare (dropped when a larger request needs the cap), so a title that frees and reallocates each frame does not allocate Vulkan memory each frame. The 2 s backoff after a driver refusal is kept.
  • refresh() walks the tiles by key (lower_bound) instead of holding a std::map iterator and raw Tile* across its periodic unlock, because a retirement can now erase a tile in that window.

Nothing changes while under the cap, and with LEONIDA_GEOMETRY_MB=0 (default) note_released returns on one atomic load.

Testing

Windows 10 Pro 19045, GeForce GTX 1050 Ti (Pascal, 4 GB, no Resizable BAR), NVIDIA 582.66, MSVC (VS 18 Build Tools), RelWithDebInfo, base 9f9a7c5f3.

AI-assisted (Claude Code, Opus 5.5, with Antigravity / Gemini 4 Neon for the first draft of the code; every change reviewed and the GPU-only filter case fixed by hand).

🤖 Generated with Claude Code

qhukz13 and others added 2 commits November 25, 2026 20:46
RT-GEOMETRY-VIEW-EVICTION: free GeometryViews entries when their backing
title range is released or unmapped, deferring Vulkan storage reclamation
until in-flight GPU work completes, and retry cap-refused ranges once
budget is freed.

- Queue released title ranges from xmem (XMemFree/Default, VirtualFree
  MEM_RELEASE/MEM_DECOMMIT, XMemMapPhysicalPages unmap, CopyPageMappingsBatchX
  unmap range) via leonida::geometry_writes::note_released.
- Add coalesced sub-range freeing and empty-block Vulkan destruction to
  TitleBufferWindows.
- Retire overlapping views immediately from lookup/find/refresh/watch and
  title_va_aliases, and reap their backing storage once
  completed_retire_ticket() reaches the view's retire ticket.
- Track free_generation_ per refused key so resolve() short-circuits while
  nothing changed and retries once budget is reclaimed.
- Extend geometry_views_test.cpp with small-cap eviction, deferred GPU
  retirement, retry, and full block reclamation checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ueue, keep one empty block

- Drain released geometry ranges only in the submit-thread before_execute callback, removing recording-thread drain calls and GeometryViews::should_reclaim().
- Filter geometry_writes::note_released() against monotonic watched_lo/watched_hi bounds and collapse the queue on 65536-entry overflow instead of dropping ranges.
- Bound GeometryViews::retire_range() walks using max_view_bytes_ and an ordered refused_ map with max_refused_bytes_.
- Keep one empty 4 MiB spare block in TitleBufferWindows (dropping it when needed under a cap), remove failed_ reset in free(), and cover all four points in geometry_views_test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

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

Native Windows review of this head. geometry_views passed its existing 51 checks and xmem passed on retry. The additional two-device case below failed. AI-assisted.

Comment thread runtime/shims/d3d12_geometry_views.h Outdated
void drain_released(Device& device, std::uint64_t retire_ticket, std::uint64_t completed_ticket,
OnRetire&& on_retire = {}) {
std::vector<std::pair<Address, Address>> ranges;
leonida::geometry_writes::take_released(ranges);

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.

[P2] Deliver a release to every device that owns a view of the range. take_released() removes the notification from a process-wide queue, but this call only retires views in the current DeviceState. I reproduced this with two GeometryViews instances over the same synthetic title extent: resolve it in both, queue one note_released, then drain both with completed tickets. The first drops the view and frees its charged bytes. The second retains the old view and its charged bytes indefinitely because its drain sees an empty queue. Could the queue route releases to the affected owners, with each owner retiring against its own submission tickets?

leonida::geometry_writes previously kept one process-wide release queue, so when two devices held GeometryViews over the same title range, the first device to call drain_released() emptied the queue and the second kept its view and charged bytes forever.

Give each GeometryViews its own ReleaseQueue subscribed to leonida::geometry_writes on construction and unsubscribed on destruction. note_released() delivers each released range to every subscriber's queue under subscribers_mutex -> queue.mutex (keeping the 65536-entry collapse per queue), and take_released() drains only the caller's queue under queue.mutex.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@qhukz13

qhukz13 commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Thanks, confirmed and fixed in 6fd430e. The release queue was process-wide while every DeviceState owns its own GeometryViews, so the first device to drain took every release.

  • title_geometry_watch.h: each GeometryViews now owns a ReleaseQueue and subscribes it on construction (unsubscribes in its destructor). note_released keeps the same filters (watched bounds, GPU-only twin) and then appends the range to every subscribed queue, each with the 65536-entry collapse on its own. Lock order is subscribers -> queue; take_released takes only its own queue.
  • Each owner drains its own queue in its before_execute_ and retires against its own submitted_retire_ticket() / completed_retire_ticket(), as you suggested.
  • geometry_views_test case 12 is your scenario: two instances over the same synthetic extent, one note_released, both drained -> both retire and reap the view and return to bytes() == 0. It also checks that an instance destroyed in a scope stops receiving releases while the survivor still does.

GTX 1050 Ti, Windows 10 19045, NVIDIA 582.66, MSVC RelWithDebInfo: geometry_views_test 60 checks, 3/3 passes. Full ctest with #2059 applied (for d3d12_geometry_views on Windows 10): 449 tests, the same 13 failures as before this commit, all of which fail on plain 9f9a7c5f3 too; geometry_views, xmem*, d3d12_title_va*, d3d12_geometry_views, d3d12_compute and the other title-VA cases pass 3x plain and 3x with LEONIDA_VK_VALIDATION=1, no validation messages.

AI-assisted (Claude Code).

@moffington

Copy link
Copy Markdown
Contributor

Checked 6fd430ebc on Linux/Wine (clang++ --target=x86_64-w64-windows-gnu): geometry_views_test passes all 60 checks (0 failures), confirming the per-GeometryViews ReleaseQueue subscription fix for multi-device release delivery.

Three findings still remain on 6fd430ebc:

  1. Confirmed in local probe (RetireTickets/GeometryViews) + code inspection — Cross-queue retirement ticket race (DeviceState::drain_geometry_releases): retire_ticket = context->submitted_retire_ticket() is sampled before unlinking outside the replay/submit critical section. Another queue that already captured a geometry VA during replay and publishes its submission afterward can get a higher ticket than the retirement cutoff; if the prior ticket is already complete, reap reclaims the backing while the newer submission is still pending (FAIL backing still holds queue A's data while ticket 6 is incomplete).
  2. Code inspection — before_execute_ ordering (refresh_shadows before drain_geometry_releases): fix_console_slot can resolve a title V# into a live geometry view, and drain_geometry_releases in the same before_execute_ can immediately unlink and reap it before the batch executes (and without an alias entry, TitleVaAliases::remove will not bump the generation).
  3. Code inspection — 65,537-entry overflow collapse in raw address space: When a subscriber's ReleaseQueue overflows, note_released collapses [min_begin, max_end) in the original address space, and drain_released only translates the collapsed range if its start is a GPU address. An unrelated CPU release below a GPU twin can mask the GPU-only event's CPU twin if the CPU twin lies outside [min_begin, max_end).

AI-assisted.

aslan2142 and others added 6 commits November 25, 2026 21:22
Conflict in runtime/shims/d3d12_title_buffer_windows.h: main (ProjectLeonida#2098) added the
lock-free published_ block list (for_each_block, find_mapped); this branch
destroys empty blocks. Both are kept; a destroyed block's published_ entry is
cleared here, and the follow-up commits make that safe for the lock-free readers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ame it

drain_geometry_releases retired released views at submitted_retire_ticket(),
read in before_execute_. The submission about to run records its own ticket
only after that, so it was not covered, and with an idle GPU
(completed == submitted) drain_released reaped the view in the same call,
before the lists recorded against it ran. A sparse bind in the same replay or
another queue's replay can take tickets in between, so submitted + 1 is not
enough either.

- VulkanContext::set_after_execute: called at the end of every replay that
  called before_execute_, however it returns, once its submissions are recorded.
- GeometryViews::execute_begin/execute_end track the replays in progress. A view
  retired at kAfterExecutes takes the serial of the last replay begun once it
  is unreachable, and gets its ticket (submitted_retire_ticket(), read under
  the views' lock) only when every replay up to that serial has ended.
- before_execute_ drains before refresh_shadows(), so this submission's console
  heap slots are never translated to a view retired in the same call.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t an alias

forget_geometry_alias only removed the view's alias ranges. vsharp_address and
placed views take geometry_va() answers straight from GeometryViews, with no
alias entry, so a retirement left the console heap slots translated through
them, and the GPU key table's entries, pointing at the view after its reap.

TitleVaAliases::forget_copy records the retired view as a removal: its title
range (CPU address and GPU twin) goes into changed_ranges with an invalidations
bump, so the console heaps translate those slots again, and its shader VA into
take_removed, so the GPU key table drops answers into it. That is what remove()
does for a range that has an alias; recording the answers instead would cost a
table entry per answer on the hot path, while this costs one entry per
retirement. The retirement runs before refresh_shadows() (previous commit), so
the submission about to run already translates without the view.

pool_spans keeps a retired view's shader_va, but only for its statistics line;
nothing answers from it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ProjectLeonida#2098's TitleBufferWindows::published_ and update_gpu_backed assumed blocks are
never destroyed: for_each_block fed every block made so far into the console
heap pass's backed table, and the table was rebuilt only when the published
count grew. With empty blocks now destroyed, a freed block stayed in the table,
and its "never of memory that is not there" contract broke.

- A destroyed block's published_ slot keeps its other fields; only its address
  (now atomic) goes to 0, and for_each_block and find_mapped skip it. A slot is
  never reused before release(), so a lock-free reader never sees one half
  rewritten.
- layout_generation() changes whenever a block is made or destroyed;
  update_gpu_backed uses it instead of the block count to see a change.
- destroy_block tells the device (DeviceState::title_block_gone): the block's
  span goes into released_ranges, as a released backing's does, so the backed
  table cuts it at once and the key entries and heap slots answering into it go
  at the next refresh. A block is destroyed only once its last range was freed,
  after the GPU work that used it completed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Since ProjectLeonida#2098 every TitleBufferWindows carries a 128 KiB published_ array, so the
eight GeometryViews this test puts on the stack pass the 1 MiB Windows default
and the test died at startup with a stack overflow. They are heap-allocated now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…block removal

geometry_views_test case 13 runs DeviceState's order for one submission with
an idle GPU (completed == submitted): execute_begin, the drain at
kAfterExecutes in before_execute_, the replay records its ticket, execute_end.
Another queue's replay began before the release and one more begins after
the retirement. It checks that
- the drain retires the view but does not reap it (a ticket read in the drain
  reaped it in the same call),
- the view waits until every replay begun before the retirement recorded its
  submission, then for the last of their tickets, and not for the later replay,
- the retirement invalidates answers made without an alias (forget_copy:
  changed_ranges, invalidations, take_removed),
- the destroyed block leaves for_each_block, changes layout_generation and is
  reported to the device (title_block_gone).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@aslan2142
aslan2142 merged commit 7f3d009 into ProjectLeonida:main Nov 26, 2026
2 of 5 checks passed
@aslan2142

Copy link
Copy Markdown
Collaborator

Merged, thanks @qhukz13! Freeing geometry views when the title releases their range is a real gain under a cap. We merged main in and fixed what the review found:

  • Reap race: a retired view is freed only after every replay that may name it has recorded and completed its submissions (a new after-execute hook), and the drain runs before the console heaps are translated.
  • Answers without an alias: retirement now invalidates them too (TitleVaAliases::forget_copy), so heap slots and the GPU key table drop a reaped view.
  • Destroyed blocks: a destroyed block leaves Improve post-load GPU memory and pipeline handling (RT-POST-LOAD-GPU-MEMORY) #2098's published_ and the backed table (layout_generation, title_block_gone).
  • Tests: geometry_views_test keeps its views off the stack; its new case 13 covers the race, the invalidation and the block removal, and fails without these fixes.
  • Tested: the full Windows suite under Wine on the gfx1036 iGPU (RADV), merged onto main 3abb99cad: area tests 28/28, and nothing failing that doesn't fail on main too.
  • Left for later: a DeviceState-level test, and command lists executed again keep the root VAs resolved when they were recorded.
  • Checked on main 86dc3d86e + bbc8ef17c: it merges cleanly; the semantic suite passes (496 files, 6,336 tests, 0 files failed); the 15 docs and writer tests pass; check_no_game_data.py is clean on the 8 changed files.

AI-assisted (Claude Code, Claude Opus 5.5).

Kokonotcu added a commit to Kokonotcu/leonida that referenced this pull request Nov 26, 2026
37 upstream commits after 86dc3d8: ProjectLeonida#2138 (integration/boot-combined), ProjectLeonida#2094 (geometry-view eviction on range
release, reaped after the replays that may name them), ProjectLeonida#998/ProjectLeonida#1317/ProjectLeonida#1281/ProjectLeonida#583 heads (pipeline-library compute
programs by code hash, shader_disasm prints the dot4 op_sel words llvm-mc rejects, FSPX short prologue with the
literal-form check), null-resource texture barriers and null-view RTV clears on the console list, and the removal
of the title's executable addresses from code (read from the environment).

Conflicts, on merit:
- d3d12_xs_device.cpp: both. Our title heap sync (LEONIDA_TITLE_HEAP_SYNC) and upstream's null-RTV marks sit side
  by side; heap_release unregisters the sync or the range as before and also drops the heap's null-RTV marks;
  CreateDescriptorHeap keeps our desc argument and takes upstream's RTV real range. Our value-op/upload-ring
  slots and upstream's slot 146 barrier conversion both stay.
- startup_trace.h: our thread and watchdog-table logging stays, and follows upstream's rule: the watchdog table's
  store and table RVAs come from LEONIDA_WATCHDOG_TABLE (off when unset, documented in runtime/README.md);
  upstream's environment-driven pool diagnostic replaces the fixed address.
- fspx_unpack.py: ours (the code end is found from one rdna2_decode pass, not an llvm-mc run per s_endpgm: the
  OOM and 15-minute fix). Its test takes upstream's short-prologue case, which checks the literal form our code
  also requires.
- rdna2spirv.py: ours (s_bitreplicate_b64_b32 into VCC in wave32 stays translated: 6 pipeline-library programs),
  plus the point behind upstream's refusal: in wave32 VCC's high word is data, so it is now written to vcc_hi as
  source bits 16..31 replicated (replicate_bits16, shared with the scalar form). Tests: ours kept, one added for
  the vcc_hi word; test_salu_flbit_64 keeps ours (this tree translates i64 of a lane mask).
- xs_proxy_mock_test.cpp: upstream's empty Barrier call, our chained-submission reference count.

Every line the merge removes from our side is upstream's own or one of the resolutions above (checked against the
merge base, D:\GTA6\analysis\lostlines.sh). The touched Python suites pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
aslan2142 added a commit that referenced this pull request Nov 26, 2026
…emaps their pages

Geometry copies held 4.4-6 GB of VRAM in world runs and were never evicted: a view retired only when its range was
freed, decommitted or unmapped, and the title streams by remapping the frames of its pools.

- LEONIDA_GEOMETRY_HOST (unset by default): 1 puts the copies in system memory outside VRAM, write-back where the
  device offers a cached host type; 2 write-combined. The memory type is picked among the host-visible types that are
  not device-local (memory_type_order alone would give the BAR first); a device with none keeps its types. Logged once
  and in the geometry buffers line.
- LEONIDA_GEOMETRY_REMAP_RELEASE (on by default, 0 off): XMemMapPhysicalPages with pages, the scatter call and
  CopyPageMappingsBatchX report the pages whose frame changed (or went) as released (xmem's RemapReleases, collected
  under the fault lock, reported after it), so GeometryViews retires the copies over them through #2094's
  drain_released and kAfterExecutes reaping. A page mapped again to its own frame is no change.
- A retired view is copied once more from its pages when they are readable: a list recorded before a remap that took
  the view's address reads the new bytes, as the refresh this replaces would have given it.
- A stream-pool extent backed by a retired copy leaves pool_spans (it was kept for the device's life).
- A full release queue joins touching ranges before it collapses into one covering range.

Tests: geometry_views_test cases 14-16, xmem_test test_remap_releases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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