Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4837,7 +4837,8 @@ if(EXISTS "${INTAKE_PYTHON}")
# queue has run them. The ring control fills them from the shared upload ring, which must refuse the uploads
# past its 256 MiB cap while the queue is held. gate-ring-reuse: once those submits have completed, the ring
# must accept a new upload again.
foreach(gate IN ITEMS gate gate-ring gate-ring-reuse)
# gate-ring-keep(-release): a closed list that is never Reset, without and with X2W_D3D12_RING_RELEASE_AT_SUBMIT.
foreach(gate IN ITEMS gate gate-ring gate-ring-reuse gate-ring-keep gate-ring-keep-release)
string(REPLACE "-" "_" gate_name "${gate}")
add_test(NAME startup_address_console_${gate_name}_${backend} COMMAND "${CMAKE_COMMAND}" -E env "X2W_FXC=${STARTUP_FXC}"
"${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_address_console_check.py"
Expand Down
78 changes: 78 additions & 0 deletions docs/experiments/startup-upload-ring-release-at-submit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
# Upload ring: release a closed list's chunks at its fenced submit (opt-in)

Refs [#2837](https://github.com/R0Y00/Xbox2Windows/issues/2837),
[#2849](https://github.com/R0Y00/Xbox2Windows/pull/2849).

Since #2823 a reservation in the shared upload ring keeps its bytes until its chunk is recycled, and #2849
recycles a chunk only when no command-list recording holds it and every queue that used it has passed its
fence. A closed list keeps its hold until Reset, Release or a failed Close, because D3D12 lets it be submitted
again. `X2W_D3D12_RING_RELEASE_AT_SUBMIT=1` moves that release to the list's fenced submit and sizes the ring
in 16 MiB chunks up to 512 MiB.

## What the switch changes

- After a submit whose queue fence was signalled, each submitted list stops holding its chunks
(`release_upload_chunks_at_submit`). The queue fence still keeps those chunks from reuse until the GPU has
passed it. Without a signalled fence nothing changes: the chunk stays busy, as without the switch.
- The list records the generation of each chunk it released. If the same list is submitted again before its
Reset, chunks with an unchanged generation are fenced again by that submit
(`resubmitted_upload_chunks`). If a chunk was recycled in between, the list would read replaced bytes: the
queue leaves it out of `ExecuteCommandLists` (`released_chunks_recycled`, checked with `draw_lock` and
`allocator_lock` held, the same locks the submit bookkeeping holds), counts it and logs the first eight
(`... were reused; refused, it is not executed`). The other lists of that call still run, as a list that is not
closed is left out today. It stays refused until its Reset, which records it afresh.
- The ring grows in 16 MiB chunks up to 512 MiB, so one list that is still recording or waiting to be submitted
pins 16 MiB instead of a chunk of up to 128 MiB.
- Unset, the ring behaves exactly as before: doubling chunks up to 256 MiB, holds until Reset.

## Fixtures

```powershell
cmake --build --preset release --target startup_stream_consumer upload_reservation_check d3d12_xs_shim
ctest --preset release --no-tests=error -j 1 -R '^(upload_reservation|startup_address_console_gate_ring_keep(_release)?_(warp|hardware))$' -V
```

- `upload_reservation`: `check_release_at_submit` releases two chunks after a fenced submit, keeps them from
reuse until the fence passes, reuses one, then finds the other intact and the reused one recycled on a
resubmit, and fences the intact one again. Mutants: keeping the holds fails "release: holds dropped";
ignoring generations fails "a resubmit finds chunk 1 intact and chunk 0 reused".
- `startup_address_console_gate_ring_keep_*` (`X2W_TEST_CONSOLE_KEEP`): a second list A uploads 32 by-address
payloads of 16 MiB each from the ring (512 MiB), is submitted, completes and is never Reset. The fixture's own
list then draws payload 32 over the right half of the target, A is submitted again, and the target is read back
after that submit.
- Without the switch, A keeps every chunk: the ring refuses past 256 MiB and the right half reads the null
view.
- `..._keep_release_*` sets the switch: the right half holds payload 32 from a chunk A released. A's second
submit would read a reused chunk, so it is refused and not executed: the right half still holds payload 32,
not A's payload 31.
- Mutants: disabling the release leaves the right half on the null view; executing the stale resubmit (the
check before the execute removed) puts A's draws back over the right half and fails on wrong pixels.
- Fixtures that describe the default ring clear the switch for their own process, so they keep testing the
default mode when it is set in the environment: the #2849 `startup_address_console_gate_ring{,_reuse}_*`
(a refusal at the 256 MiB cap) and `startup_slot133_heap_cap_capped_*` (doubling growth to 48 MiB).

## Startup run of the main executable

Local diagnostic runs, Windows 10 22H2 (19045), RTX 3080 Ti, NVIDIA driver 32.0.16.1047, i7-4790K, 16 GB,
release build of this change, warm shader cache, `run.ps1 -Render` without `-Translate`, scripted input, 250 s.
One build; only the switch differs. Aggregates only; logs stay local.

| | switch unset | switch set |
|---|---|---|
| null bindings with cause `buffer` | 33,632 | 0 |
| `upload ring reservation refused` logged | yes | no |
| resubmits after a reuse (now refused) | n/a | 0 |
| process commit peak | 16.7 GiB | 18.1 GiB |
| visible | single full black frames in the post-load animation | none seen |

- Without the switch, a census at each refusal showed every chunk held by closed lists not yet Reset, while
every queue had passed the chunk's fence. Most refused requests were 64 KiB: the window
`upload_from_title` copies for a graphics root SRV without an existing upload mapping.
- The title never submitted a closed list again without a Reset: 0 of more than 500,000 submits over five runs.
A title that does resubmit after a reuse gets the refusal described above: that list does not run.
- The larger ring cost about 1 GiB of process commit at peak in this run.
- Repeated after the stale-resubmit refusal, on a later `main`, same settings: buffer null bindings 50,665 →
0, reservation refusals logged → none, stale resubmits refused 0 → 0, commit peak 17.9 → 18.0 GiB, black
frames → none seen.

Not established: other titles' resubmit behaviour, and whether 512 MiB is enough on other workloads.
13 changes: 13 additions & 0 deletions docs/startup-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -1495,6 +1495,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr
| `X2W_SHADER_CACHE=<dir>` | translation cache: the runtime writes source requests `req_<key>.{a,b,root}`, when needed RTV variants `req_<key>.rtv`, and for device slot 67 compute pipelines `req_<key>.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_<key>.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending <dir>` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\<version>\x64`, else `PATH`. When none exists it writes `<key>.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. |
| `X2W_D3D12_LINEAR_BUFFERS=1` or `=copy` | opt-in backing for linear buffers placed at a title address (device slot 133, initial state `COMMON`): shared where the adapter, extent and memory allow it (private allocations larger than 256 MiB are skipped only with `X2W_D3D12_CAP_EXISTING_HEAP=1`), otherwise copied from title memory at each submission, otherwise the default backing is kept and the refusal recorded; `copy` never shares. Unset or `0`, slot 133 keeps its default backing. See [Linear buffer backing (device slot 133, opt-in)](#linear-buffer-backing-device-slot-133-opt-in) |
| `X2W_D3D12_CAP_EXISTING_HEAP=1` | opt-in 256 MiB (`unplaced_existing_heap_allowed`) allocation-size cap on `OpenExistingHeapFromAddress` in device slot 133 (`startup_slot133_heap_cap_*`). Unset (default), private allocations larger than 256 MiB keep the formerly aliased path: a capped copied placement is refused by `CopyBufferRegion` (list slot 15) as `title_backed_source`, losing a late guest write made after recording and before submit. Set, allocations larger than 256 MiB skip `OpenExistingHeapFromAddress` so multi-GiB startup blocks are not pinned in `WorkingSetSize` and `NonLocal` GPU memory |
| `X2W_D3D12_RING_RELEASE_AT_SUBMIT=1` | opt-in, render mode: a closed command list releases its upload ring chunks once its submit is fenced instead of holding them until Reset, and the ring grows in 16 MiB chunks up to 512 MiB (default: doubling chunks up to 256 MiB, holds until Reset). The larger ring can add up to about 1 GiB of process commit at peak (startup runs in the experiment note). A later submit of the same list before its Reset fences its unchanged chunks again; if one was reused in between, that list is refused before the execute and logged (`startup_address_console_gate_ring_keep_*`, `upload_reservation`). See [the experiment note](experiments/startup-upload-ring-release-at-submit.md) |
| `X2W_D3D12_QUERY_SLOTS=1` | diagnostic, in render mode: binds command-list slots 28 to 30 to the hypothesised occlusion query methods (see [Occlusion queries](#occlusion-queries)). Unset, the three slots stay no-ops |
| `X2W_D3D12_BUDGET=1` | adds [video memory budget and allocation counts](#d3d12-resource-budget) to the D3D12 heartbeat |
| `X2W_D3D12_RELEASE_RETIRED=1` | opt-in, effective with `X2W_D3D12_RENDER=1` only (the list handlers that record holds exist only there): frees the desktop object of a released committed 2D texture of one narrow class once no recorded list, submission or release-time fence refers to it ([details](#d3d12-resource-budget)). Unset, nothing changes |
Expand Down Expand Up @@ -3392,6 +3393,18 @@ signal or a removed device keeps the chunk busy. When no chunk qualifies, the
reservation is refused; live storage is never reset. Recycling bumps the
chunk's generation, and a cached frame copy from an older generation is not
reused.
With the opt-in `X2W_D3D12_RING_RELEASE_AT_SUBMIT=1`, a closed list stops
holding its chunks as soon as its submit is fenced: the queue fence alone then
keeps the chunks from reuse until the GPU has passed it. The ring grows in
16 MiB chunks up to 512 MiB in this mode. If the same list is submitted again
before its Reset, the submit fences its chunks again when their generation is
unchanged. If a chunk was recycled in between, the list would read replaced
bytes: it is left out of `ExecuteCommandLists` before the execute, counted and
logged (`closed list ... submitted again after its released chunks ... were
reused; refused, it is not executed`) until its Reset. The mode therefore suits
titles that Reset a list before submitting it again. `startup_address_console_gate_ring_keep_*` keeps one list
closed and never Reset while a second list needs ring space, without and with
the switch. See [the experiment note](experiments/startup-upload-ring-release-at-submit.md).
`upload_reservation` exercises the shared cursor and returned-pointer contract
without D3D12; on non-Windows hosts run
`c++ -std=c++17 -Isrc tests/upload_reservation_check.cpp -o out/upload_reservation_check && out/upload_reservation_check`.
Expand Down
63 changes: 59 additions & 4 deletions src/startup_stubs/d3d12_xs_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1460,13 +1460,17 @@ std::unordered_map<Wrapper*, TitleAllocator> title_allocators;
std::unordered_map<Wrapper*, DesktopAllocator*> list_recordings; // list -> allocator holding its recording
std::unordered_map<ID3D12CommandQueue*, UploadQueue<ID3D12Fence>> queue_submits;
std::vector<UploadRingChunk> upload_chunks; // allocator_lock also protects recording holds and queue fence values
// X2W_D3D12_RING_RELEASE_AT_SUBMIT=1 (allocator_lock): chunks each closed list released at a fenced submit, until its Reset.
std::unordered_map<Wrapper*, ReleasedUploadChunks> released_upload_chunks;
LONG upload_resubmits_refused; // closed lists submitted again after a released chunk was reused; not executed

LONG allocator_swaps, allocator_creates;

void release_upload_recording(Wrapper* list)
{
AcquireSRWLockExclusive(&allocator_lock);
discard_upload_chunks(list->own().upload_chunks, upload_chunks.data());
released_upload_chunks.erase(list);
ReleaseSRWLockExclusive(&allocator_lock);
}

Expand Down Expand Up @@ -1658,6 +1662,34 @@ bool submit_fence_fails()
return on;
}

// X2W_D3D12_RING_RELEASE_AT_SUBMIT=1 (opt-in): a closed list stops holding its upload ring chunks once its submit is
// fenced, so the queue fence alone guards them; the ring then grows in 16 MiB chunks up to 512 MiB. A later submit
// of the same list before its Reset fences its chunks again. One whose chunk was reused meanwhile is refused before
// ExecuteCommandLists (released_chunks_recycled), so it never reads replaced bytes.
bool ring_release_at_submit()
{
static const bool on = GetEnvironmentVariableW(L"X2W_D3D12_RING_RELEASE_AT_SUBMIT", nullptr, 0) != 0;
return on;
}

// draw_lock and allocator_lock held, before the queue executes `list`. True when the closed list released its chunks
// at an earlier fenced submit and one of them was reused since: the submit leaves it out, and it stays refused until
// its Reset. Counted and logged.
bool released_chunks_recycled(Wrapper* list)
{
const auto released = released_upload_chunks.find(list);
if (released == released_upload_chunks.end()) return false;
UploadChunkMask recycled = 0;
resubmitted_upload_chunks(released->second, upload_chunks.data(), recycled);
if (!recycled) return false;
InterlockedIncrement(&upload_resubmits_refused);
static LONG logged;
if (first_calls(logged, 8))
log("x2w-draw upload ring: closed list %p submitted again after its released chunks 0x%x were reused; "
"refused, it is not executed", static_cast<void*>(list), static_cast<unsigned>(recycled));
return true;
}

// draw_lock and allocator_lock held, after the lists were executed on queue. Each list's allocator holds a fence value
// the queue must pass before the allocator can be reset. If that fence cannot be created or
// signalled, the work is on the GPU all the same: the allocators are marked untracked instead.
Expand All @@ -1674,10 +1706,28 @@ void note_submits(ID3D12CommandQueue* queue, const std::vector<Wrapper*>& lists)
}
}
UploadChunkMask chunks = 0;
for (auto* list : lists) chunks |= list->own().upload_chunks;
for (auto* list : lists) {
chunks |= list->own().upload_chunks;
const auto released = released_upload_chunks.find(list);
if (released == released_upload_chunks.end()) continue;
// A list with a reused chunk was refused before the execute, under the same locks: all of them are intact.
UploadChunkMask reused = 0;
chunks |= resubmitted_upload_chunks(released->second, upload_chunks.data(), reused);
}
const bool signaled = fence && SUCCEEDED(queue->Signal(fence, value + 1));
if (signaled) ++value;
submit.submitted(chunks, signaled);
if (signaled && ring_release_at_submit()) {
for (Wrapper* list : lists) {
if (!list->own().upload_chunks) continue;
try {
release_upload_chunks_at_submit(list->own().upload_chunks, upload_chunks.data(),
released_upload_chunks[list]);
} catch (const std::bad_alloc&) {
// Keep the holds: the list then pins its chunks until its Reset, as without the switch.
}
}
}
if (signaled) {
for (Wrapper* list : lists) {
const auto found = list_recordings.find(list);
Expand Down Expand Up @@ -1812,6 +1862,7 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator)
on = title.current;
++on->lists;
discard_upload_chunks(state.upload_chunks, upload_chunks.data());
released_upload_chunks.erase(self);
state.list_uploads = nullptr;
state.list_scratch = nullptr;
state.list_ready = false;
Expand Down Expand Up @@ -2601,7 +2652,8 @@ ID3D12PipelineState* build_stream_pipeline(const D3D12_PIPELINE_STATE_STREAM_DES

// Transient guest data is copied into mapped upload chunks. Chunks grow from
// 16 MiB up to 256 MiB in total and stay alive for the process. A full chunk can be reused once
// no recording can submit its bytes and every queue that used it has finished.
// no recording can submit its bytes and every queue that used it has finished. With
// X2W_D3D12_RING_RELEASE_AT_SUBMIT=1 every chunk is 16 MiB, up to 512 MiB, and a fenced submit releases its lists.

UploadReservation reserve_upload_ring(Wrapper* list, std::size_t bytes)
{
Expand All @@ -2626,9 +2678,11 @@ UploadReservation reserve_upload_ring(Wrapper* list, std::size_t bytes)
if (reservation.mapped) return finish(active);
}

const u64 remaining = total_bytes < max_upload_ring_bytes ? max_upload_ring_bytes - total_bytes : 0;
const bool release_at_submit = ring_release_at_submit();
const u64 ring_bytes = release_at_submit ? max_released_upload_ring_bytes : max_upload_ring_bytes;
const u64 remaining = total_bytes < ring_bytes ? ring_bytes - total_bytes : 0;
if (rounded <= remaining) {
u64 chunk_bytes = chunks.empty() ? initial_upload_chunk_bytes : chunks.back().capacity * 2;
u64 chunk_bytes = chunks.empty() || release_at_submit ? initial_upload_chunk_bytes : chunks.back().capacity * 2;
if (chunk_bytes < rounded) chunk_bytes = rounded;
if (chunk_bytes > remaining) chunk_bytes = remaining;
auto* device = the_device ? device_of(the_device) : nullptr;
Expand Down Expand Up @@ -4227,6 +4281,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists)
for (UINT i = 0; i < count; ++i) {
Wrapper* w = as_wrapper(lists[i]);
if (w && w->own().kind == list_kind && w->own().list_ready) {
if (released_chunks_recycled(w)) continue; // its upload bytes were replaced: it is not executed
ready.push_back(static_cast<ID3D12CommandList*>(w->own().real));
submitted.push_back(w);
}
Expand Down
Loading
Loading