diff --git a/docs/experiments.md b/docs/experiments.md index f6ed2eb1da..f5c6dc0750 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -303,6 +303,16 @@ The source is a same-device desktop resource with no title shadow, a unique alia or an already covered range. Later overlapping copies invalidate earlier coverage. The recording discards this proof at Close, so another recording needs its own writer. +`X2W_TRANSLATED_TITLE_INPUT_SNAPSHOT=1` lets a translated compute Dispatch read an input that lies in a placed buffer which does +not alias title memory. That buffer's desktop copy is a committed default buffer that holds zeros, so the bytes the title wrote +exist only in title memory. The input resolves in this order: a validated GPU copy of the current recording (the proof above, +which needs `X2W_TRANSLATED_INDIRECT_COPY_RANGES=1`), else a snapshot of the range (at most 16 MiB) taken from title memory +into the snapshot pool when the Dispatch is recorded, else the refusal `an input is in a placed buffer that does not alias title +memory`. A guest write after the recording is not seen, and data a GPU pass wrote into such a buffer is not either. The first +use per pipeline key logs `x2w-draw compute input (...) comes from a GPU copy this list made|a snapshot of title +memory`, and the render totals line counts both paths. Off by default. To turn it on for a run, set `$env:X2W_TRANSLATED_TITLE_INPUT_SNAPSHOT = "1"` in the PowerShell session before +starting `tools/startup/run.ps1`, which passes the session's environment on to the run. The snapshots have a pool of their own (128 MiB, chunks of 16 MiB, built like the shared upload ring: a chunk is reused once no recording can submit its bytes and every queue that used it has finished), so draw and texture uploads cannot starve them and a long run is not stopped by a full pool; a reservation it cannot serve logs `x2w-draw snapshot pool reservation refused: no unused capacity`. `startup_compute_dispatch_input` covers it with the `dispatch-input-snapshot` case and, for the recycling, `dispatch-input-snapshot-long` (48 frames of an 8 MiB snapshot, 384 MiB in all). + The source-built fixture reproduces a 68-byte request shape with source offset `0xbfffa0`. Its compute writer fills the source with contrasting colours. The consumer reads red from the second DWORD in the destination while the title-side green sentinel stays diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index 7657512a45..e0cb2a5a3c 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -48,6 +48,7 @@ struct ComputeTranslation { const char* unmodelled = nullptr; // why a manifest that exists cannot be used u64 dispatches = 0, translated = 0; // census: Dispatch calls with this key bound, and those recorded const char* first_refusal = nullptr; // reason of the first refused call + bool input_path_logged = false; // the first time a placed input came from a GPU copy or a title snapshot std::uint32_t refusal_words[4] = {}; // the table descriptor that reason was about, if any; a view token's // last word is replaced by its view format | dimension << 16 ~ComputeTranslation() @@ -83,6 +84,7 @@ unsigned float_output_channels(DXGI_FORMAT format) } std::unordered_map& compute_translations() { static std::unordered_map m; return m; } LONG compute_dispatches_translated, compute_dispatches_refused, compute_dispatches_untranslated, compute_dispatches_unmodelled; +LONG compute_inputs_gpu_copied, compute_inputs_snapshot, compute_inputs_snapshot_kib; // inputs by path: this list's GPU copy, a title snapshot // The root signature and pipeline of a translation whose entry values and views are filled in. Returns why it is // unavailable, or null when it is ready. @@ -591,7 +593,17 @@ const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& } if (!output) { // Each condition of a complete GPU-backed buffer range has its own reason. - const IndirectBufferView view = indirect_table_buffer(self, words, false, &reason, 16u << 20); + const IndirectBufferView view = indirect_table_buffer(self, words, false, &reason, 16u << 20, true); + if (view.source == 1) InterlockedIncrement(&compute_inputs_gpu_copied); + if (view.source == 2) { + InterlockedIncrement(&compute_inputs_snapshot); + InterlockedExchangeAdd(&compute_inputs_snapshot_kib, static_cast((view.bytes + 1023) / 1024)); + } + if (view.source && !tr->input_path_logged) { + tr->input_path_logged = true; + log("x2w-draw compute %016llx input %zu (%s %d %d) comes from %s (%llu bytes)", key, i, slot.heap ? "heap" : "table", slot.a, slot.b, + view.source == 1 ? "a GPU copy this list made" : view.source == 3 ? "zeros for a null descriptor" : "a snapshot of title memory", view.bytes); + } if (view.resource && view.offset % D3D12_RAW_UAV_SRV_BYTE_ALIGNMENT) reason = "an input buffer range is not 16-byte aligned in its resource"; if (reason && !tr->first_refusal) // once per key: which input, and where its descriptor was read log("x2w-draw compute %016llx first refused input %zu (%s %d %d), descriptor at 0x%llx", key, i, diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 972e6d89b2..c7acc0352d 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -2284,14 +2284,24 @@ struct IndirectBufferView { u64 offset = 0, bytes = 0; UINT stride = 0; bool upload = false; + int source = 0; // 0 aliased or any other backing, 1 a GPU copy this list made (X2W_TRANSLATED_INDIRECT_COPY_RANGES), 2 a snapshot of title memory, 3 zeros for a null descriptor }; +// X2W_TRANSLATED_TITLE_INPUT_SNAPSHOT=1: a translated compute input in a placed buffer that does not alias title memory +// (a committed default buffer that holds zeros) is read from title memory, snapshotted into its own recycled pool. +bool title_input_snapshot_enabled() +{ + static const bool enabled = x2w_local::env_on("X2W_TRANSLATED_TITLE_INPUT_SNAPSHOT"); + return enabled; +} + // For indirect draws, bind the complete descriptor range on a known GPU backing. There is no // fallback to copying an unrelated or stale title allocation into the draw upload ring. // why, when given, receives the condition an empty result failed on. IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* words, bool allow_address_alias = false, const char** why = nullptr, - u64 limit = u64{4} << D3D12_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP) + u64 limit = u64{4} << D3D12_REQ_BUFFER_RESOURCE_TEXEL_COUNT_2_TO_EXP, + bool allow_title_snapshot = false) { const auto refuse = [why](const char* reason) { if (why) *why = reason; @@ -2349,12 +2359,23 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor stride = (words[1] >> 16) & 0x3fff; bytes = u64{stride ? stride : 1} * words[2]; } + // A compute input whose four descriptor words are all zero is an unbound (null) buffer: the hardware reads zeros from + // it, so the dispatch gets 16 bytes of zeros instead of being refused. Any other empty range is still refused. + if (!bytes && allow_title_snapshot && !words[0] && !words[1] && !words[2] && !words[3]) { + u64 zero_offset = 0; + ID3D12Resource* zero_ring = nullptr; + unsigned char* zero_bytes = reserve_upload_ring(self, 16, &zero_offset, &zero_ring, true); + if (!zero_bytes || !zero_ring) return refuse("a null input could not get its zero bytes"); + std::memset(zero_bytes, 0, 16); + return {zero_ring, zero_offset, 16, 0, true, 3}; + } if (!bytes) return refuse("an input buffer descriptor has zero records"); if (bytes > limit || bytes % 4) return refuse(limit == (16u << 20) ? "an input buffer range is over 16 MiB or not whole dwords" : "an input buffer range exceeds the D3D12 raw SRV limit or is not whole dwords"); ID3D12Resource* native = nullptr; bool upload = false; + int input_source = 0; Wrapper* device = self->own().list_device; if (address) { if (const auto allocation = list_upload_range(self, address, bytes); allocation.resource) { @@ -2375,8 +2396,24 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor owner = placed.owner; native = static_cast(owner->own().real); offset = address - reinterpret_cast(owner->own().title_memory); - if (!placed.alias && (!native || !list_copied_gpu_range(self, native, offset, bytes))) - return refuse("an input is in a placed buffer that does not alias title memory"); + if (!placed.alias) { + if (native && list_copied_gpu_range(self, native, offset, bytes)) { + input_source = 1; // a GPU copy of this list filled the range: the GPU buffer is the truth + } else if (allow_title_snapshot && title_input_snapshot_enabled() && bytes <= (u64{16} << 20)) { + // The buffer is a committed default buffer that holds zeros (it does not alias title memory), so the + // bytes the title wrote are only in title memory: snapshot the range into the snapshot pool now. A later + // guest write is not seen (as title_backed_source for copies); data a GPU pass wrote into this buffer is not either. + u64 ring_offset = 0; + ID3D12Resource* ring = nullptr; + if (readable_window(address, static_cast(bytes)) < bytes) + return refuse("an input range in title memory is not readable"); + if (!ring_copy(self, address, static_cast(bytes), &ring_offset, &ring, true) || !ring) + return refuse("an input range could not be copied from title memory"); + return {ring, ring_offset, bytes, stride, true, 2}; + } else { + return refuse("an input is in a placed buffer that does not alias title memory"); + } + } } else if (own_memory) { native = static_cast(owner->own().real); } else if (owner && !owner->own().title_memory) { @@ -2400,7 +2437,7 @@ IndirectBufferView indirect_table_buffer(Wrapper* self, const std::uint32_t* wor const auto desc = native->GetDesc(); if (desc.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER || (desc.Flags & D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE) || offset > desc.Width || bytes > desc.Width - offset) return refuse("an input range is outside its desktop buffer"); - return {native, offset, bytes, stride, upload}; + return {native, offset, bytes, stride, upload, input_source}; } struct FormattedBufferDescriptor { diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index e24f2acda5..523a561836 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -182,7 +182,7 @@ struct alignas(16) WrapperOwn { bool list_open; // CommandList (render mode): recording between reset and close x2w_upload::Arena* list_uploads; // Current recording's allocations, owned by its desktop allocator. ID3D12Resource* list_scratch; // Current recording's rectangle-list argument scratch, owned by its desktop allocator. - UploadChunkMask upload_chunks; // Ring chunks referenced by this recording, including while closed. + UploadChunkMask upload_chunks; // Ring and snapshot chunks referenced by this recording, including while closed. bool list_close_failed; // Desktop Reset repeats a failed Close result indefinitely. bool unplaced_srv_backing; // Resource: synthetic backing for an address-only buffer SRV. bool exact_copy; // Resource: synthetic backing that starts at the view address. @@ -1478,6 +1478,7 @@ std::unordered_map title_allocators; std::unordered_map list_recordings; // list -> allocator holding its recording std::unordered_map> queue_submits; std::vector upload_chunks; // allocator_lock also protects recording holds and queue fence values +std::vector snapshot_chunks; // the title input snapshot pool: same rules, its own chunks and budget // X2W_D3D12_RING_RELEASE_AT_SUBMIT=1 (allocator_lock): chunks each closed list released at a fenced submit, until its Reset. std::unordered_map released_upload_chunks; LONG upload_resubmits_refused; // closed lists submitted again after a released chunk was reused; not executed @@ -1487,7 +1488,7 @@ LONG allocator_swaps, allocator_creates; void release_upload_recording(Wrapper* list) { AcquireSRWLockExclusive(&allocator_lock); - discard_upload_chunks(list->own().upload_chunks, upload_chunks.data()); + discard_upload_chunks(list->own().upload_chunks, upload_chunks.data(), snapshot_chunks.data()); released_upload_chunks.erase(list); ReleaseSRWLockExclusive(&allocator_lock); } @@ -1717,13 +1718,13 @@ 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); + resubmitted_upload_chunks(released->second, upload_chunks.data(), recycled, snapshot_chunks.data()); 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(list), static_cast(recycled)); + log("x2w-draw upload ring: closed list %p submitted again after its released chunks 0x%llx were reused; " + "refused, it is not executed", static_cast(list), static_cast(recycled)); return true; } @@ -1749,7 +1750,7 @@ void note_submits(ID3D12CommandQueue* queue, const std::vector& lists) 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); + chunks |= resubmitted_upload_chunks(released->second, upload_chunks.data(), reused, snapshot_chunks.data()); } const bool signaled = fence && SUCCEEDED(queue->Signal(fence, value + 1)); if (signaled) ++value; @@ -1759,7 +1760,7 @@ void note_submits(ID3D12CommandQueue* queue, const std::vector& lists) if (!list->own().upload_chunks) continue; try { release_upload_chunks_at_submit(list->own().upload_chunks, upload_chunks.data(), - released_upload_chunks[list]); + released_upload_chunks[list], snapshot_chunks.data()); } catch (const std::bad_alloc&) { // Keep the holds: the list then pins its chunks until its Reset, as without the switch. } @@ -1898,7 +1899,7 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator) if (on) --on->lists; on = title.current; ++on->lists; - discard_upload_chunks(state.upload_chunks, upload_chunks.data()); + discard_upload_chunks(state.upload_chunks, upload_chunks.data(), snapshot_chunks.data()); released_upload_chunks.erase(self); state.list_uploads = nullptr; state.list_scratch = nullptr; @@ -1941,7 +1942,7 @@ HRESULT __stdcall list_close(Wrapper* self) state.list_ready = SUCCEEDED(hr); state.list_close_failed = FAILED(hr); if (FAILED(hr)) { - discard_upload_chunks(state.upload_chunks, upload_chunks.data()); + discard_upload_chunks(state.upload_chunks, upload_chunks.data(), snapshot_chunks.data()); if (const auto found = list_recordings.find(self); found != list_recordings.end() && found->second) found->second->close_failed = true; } @@ -2690,30 +2691,37 @@ 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. With -// X2W_D3D12_RING_RELEASE_AT_SUBMIT=1 every chunk is 16 MiB, up to 512 MiB, and a fenced submit releases its lists. +// X2W_D3D12_RING_RELEASE_AT_SUBMIT=1 the ring uses 16 MiB chunks (larger for oversized reservations), +// up to 512 MiB. A fenced submit releases the list's holds in both pools. volatile LONG64 upload_ring_reserved_bytes, upload_ring_capacity_bytes; volatile LONG upload_ring_reservations, upload_ring_refusals; -UploadReservation reserve_upload_ring(Wrapper* list, std::size_t bytes) +// snapshot = true takes the reservation from the title input snapshot pool (128 MiB, chunks numbered after the ring's). +UploadReservation reserve_upload_ring(Wrapper* list, std::size_t bytes, bool snapshot = false) { - constexpr u64 max_alloc_bytes = max_upload_ring_bytes / 4; + const u64 max_pool_bytes = snapshot ? max_snapshot_pool_bytes : max_upload_ring_bytes; + const unsigned base = snapshot ? snapshot_chunk_base : 0; + const u64 max_alloc_bytes = max_pool_bytes / 4; UploadReservation reservation; if (bytes == 0 || bytes > max_alloc_bytes) return reservation; const u64 rounded = (static_cast(bytes) + 511) & ~u64{511}; - const auto note_reserved = [](u64 reserved) { + const auto note_reserved = [snapshot](u64 reserved) { + if (snapshot) return; InterlockedAdd64(&upload_ring_reserved_bytes, static_cast(reserved)); InterlockedIncrement(&upload_ring_reservations); }; - auto& chunks = upload_chunks; - static unsigned active = 0; - static u64 total_bytes = 0; + auto& chunks = snapshot ? snapshot_chunks : upload_chunks; + static unsigned actives[2] = {0, 0}; + static u64 totals[2] = {0, 0}; + unsigned& active = actives[snapshot ? 1 : 0]; + u64& total_bytes = totals[snapshot ? 1 : 0]; AcquireSRWLockExclusive(&allocator_lock); const auto finish = [&](unsigned index) { active = index; - chunks[index].hold(list->own().upload_chunks, index); + chunks[index].hold(list->own().upload_chunks, base + index); ReleaseSRWLockExclusive(&allocator_lock); return reservation; }; @@ -2725,11 +2733,11 @@ UploadReservation reserve_upload_ring(Wrapper* list, std::size_t bytes) } } - 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; + const bool grow_released_ring = !snapshot && ring_release_at_submit(); + const u64 budget_bytes = grow_released_ring ? max_released_upload_ring_bytes : max_pool_bytes; + const u64 remaining = total_bytes < budget_bytes ? budget_bytes - total_bytes : 0; if (rounded <= remaining) { - u64 chunk_bytes = chunks.empty() || release_at_submit ? initial_upload_chunk_bytes : chunks.back().capacity * 2; + u64 chunk_bytes = chunks.empty() || grow_released_ring ? 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; @@ -2752,7 +2760,7 @@ UploadReservation reserve_upload_ring(Wrapper* list, std::size_t bytes) try { chunks.push_back(UploadRingChunk{created, static_cast(base), chunk_bytes, 0}); total_bytes += chunk_bytes; - InterlockedAdd64(&upload_ring_capacity_bytes, static_cast(chunk_bytes)); + if (!snapshot) InterlockedAdd64(&upload_ring_capacity_bytes, static_cast(chunk_bytes)); reservation = reserve_upload_chunk(chunks.back(), rounded); note_reserved(rounded); return finish(static_cast(chunks.size() - 1)); @@ -2778,7 +2786,7 @@ UploadReservation reserve_upload_ring(Wrapper* list, std::size_t bytes) } for (unsigned index = 0; index < chunks.size(); ++index) { - reservation = reuse_upload_chunk(chunks[index], index, rounded, queue_submits); + reservation = reuse_upload_chunk(chunks[index], base + index, rounded, queue_submits); if (reservation.mapped) { note_reserved(rounded); return finish(index); @@ -2786,27 +2794,28 @@ UploadReservation reserve_upload_ring(Wrapper* list, std::size_t bytes) } ReleaseSRWLockExclusive(&allocator_lock); - InterlockedIncrement(&upload_ring_refusals); - static LONG refused; - if (first_calls(refused, 8)) - log("x2w-draw upload ring reservation refused: no unused capacity"); + if (!snapshot) InterlockedIncrement(&upload_ring_refusals); + static LONG refused[2]; + if (first_calls(refused[snapshot ? 1 : 0], 8)) + log(snapshot ? "x2w-draw snapshot pool reservation refused: no unused capacity" + : "x2w-draw upload ring reservation refused: no unused capacity"); return reservation; } -unsigned char* reserve_upload_ring(Wrapper* list, std::size_t bytes, u64* offset, ID3D12Resource** resource) +unsigned char* reserve_upload_ring(Wrapper* list, std::size_t bytes, u64* offset, ID3D12Resource** resource, bool snapshot = false) { if (resource) *resource = nullptr; if (offset) *offset = 0; - const UploadReservation reservation = reserve_upload_ring(list, bytes); + const UploadReservation reservation = reserve_upload_ring(list, bytes, snapshot); if (!reservation.mapped) return nullptr; if (offset) *offset = reservation.offset; if (resource) *resource = reservation.resource; return reservation.mapped; } -bool ring_copy(Wrapper* list, u64 title_address, std::size_t bytes, u64* offset, ID3D12Resource** resource = nullptr) +bool ring_copy(Wrapper* list, u64 title_address, std::size_t bytes, u64* offset, ID3D12Resource** resource = nullptr, bool snapshot = false) { - auto* dest = reserve_upload_ring(list, bytes, offset, resource); + auto* dest = reserve_upload_ring(list, bytes, offset, resource, snapshot); if (!dest) return false; std::memcpy(dest, reinterpret_cast(title_address), bytes); return true; @@ -7437,9 +7446,9 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa log("x2w-render upload ring: reserved %llu MiB in %ld reservations, refusals %ld, capacity %llu MiB", static_cast(upload_ring_reserved_bytes) >> 20, upload_ring_reservations, upload_ring_refusals, static_cast(upload_ring_capacity_bytes) >> 20); - log("x2w-render compute dispatches: translated %ld, refused %ld, no translation %ld, not modelled %ld, builder gate refused %ld", + log("x2w-render compute dispatches: translated %ld, refused %ld, no translation %ld, not modelled %ld, builder gate refused %ld; placed inputs from a GPU copy %ld, from a title snapshot %ld (%ld KiB)", compute_dispatches_translated, compute_dispatches_refused, compute_dispatches_untranslated, compute_dispatches_unmodelled, - compute_builder_gate_refusals); + compute_builder_gate_refusals, compute_inputs_gpu_copied, compute_inputs_snapshot, compute_inputs_snapshot_kib); log_compute_census(); } if (render_mode() && frame % 300 == 0) { diff --git a/src/startup_stubs/upload_reservation.h b/src/startup_stubs/upload_reservation.h index eec33a9d33..121bbd6cf3 100644 --- a/src/startup_stubs/upload_reservation.h +++ b/src/startup_stubs/upload_reservation.h @@ -2,6 +2,7 @@ #include #include +#include struct ID3D12Resource; @@ -11,14 +12,21 @@ inline constexpr std::uint64_t max_upload_ring_bytes = 256ull << 20; inline constexpr std::uint64_t max_released_upload_ring_bytes = 512ull << 20; // Each allocation except possibly the final remainder is at least the initial size. inline constexpr unsigned max_upload_chunks = max_released_upload_ring_bytes / initial_upload_chunk_bytes; -using UploadChunkMask = std::uint32_t; -static_assert(max_upload_chunks <= 32); +// Title input snapshots have a pool of their own, built like the ring (chunks reused once no recording can submit them and every +// queue that used them has finished), so draw and texture uploads cannot starve them and they cannot starve the ring. Its chunks +// are numbered after the ring's in the same recording mask: bit snapshot_chunk_base + i is chunk i of the snapshot pool. +inline constexpr std::uint64_t max_snapshot_pool_bytes = 128ull << 20; +inline constexpr unsigned max_snapshot_chunks = max_snapshot_pool_bytes / initial_upload_chunk_bytes; +inline constexpr unsigned snapshot_chunk_base = max_upload_chunks; +inline constexpr unsigned upload_chunk_bits = max_upload_chunks + max_snapshot_chunks; +using UploadChunkMask = std::uint64_t; +static_assert(upload_chunk_bits <= std::numeric_limits::digits); template struct UploadQueue { Fence* fence = nullptr; std::uint64_t value = 0; - std::array last_use{}; + std::array last_use{}; void submitted(UploadChunkMask chunks, bool signaled) { @@ -56,28 +64,35 @@ struct UploadRingChunk { } }; -inline void discard_upload_chunks(UploadChunkMask& recording, UploadRingChunk* chunks) +// Indices below snapshot_chunk_base belong to the upload ring. +template +inline Chunk& upload_chunk_at(unsigned index, Chunk* chunks, Chunk* snapshot_chunks) +{ + return index < snapshot_chunk_base ? chunks[index] : snapshot_chunks[index - snapshot_chunk_base]; +} +inline void discard_upload_chunks(UploadChunkMask& recording, UploadRingChunk* chunks, UploadRingChunk* snapshot_chunks = nullptr) { for (unsigned i = 0; recording; ++i, recording >>= 1) - if (recording & 1) --chunks[i].recordings; + if (recording & 1) --upload_chunk_at(i, chunks, snapshot_chunks).recordings; } // X2W_D3D12_RING_RELEASE_AT_SUBMIT=1: the chunks a closed list stopped holding when its submit was fenced, and // each chunk's generation at that moment. The queue fence keeps those chunks from reuse until the GPU passes it. struct ReleasedUploadChunks { UploadChunkMask chunks = 0; - std::array generation{}; + std::array generation{}; }; // Caller holds the lock, after the queue recorded a signalled fence for the recording's chunks. inline void release_upload_chunks_at_submit(UploadChunkMask& recording, UploadRingChunk* chunks, - ReleasedUploadChunks& released) + ReleasedUploadChunks& released, UploadRingChunk* snapshot_chunks = nullptr) { for (unsigned i = 0; recording; ++i, recording >>= 1) { if (!(recording & 1)) continue; released.chunks |= UploadChunkMask{1} << i; - released.generation[i] = chunks[i].generation; - --chunks[i].recordings; + auto& chunk = upload_chunk_at(i, chunks, snapshot_chunks); + released.generation[i] = chunk.generation; + --chunk.recordings; } } @@ -85,14 +100,14 @@ inline void release_upload_chunks_at_submit(UploadChunkMask& recording, UploadRi // the released chunks that were not reused since, which the new submit must fence again, and sets `recycled` to // those that were. inline UploadChunkMask resubmitted_upload_chunks(const ReleasedUploadChunks& released, const UploadRingChunk* chunks, - UploadChunkMask& recycled) + UploadChunkMask& recycled, const UploadRingChunk* snapshot_chunks = nullptr) { UploadChunkMask intact = 0; recycled = 0; - for (unsigned i = 0; i < max_upload_chunks; ++i) { + for (unsigned i = 0; i < upload_chunk_bits; ++i) { const auto bit = UploadChunkMask{1} << i; if (!(released.chunks & bit)) continue; - (chunks[i].generation == released.generation[i] ? intact : recycled) |= bit; + (upload_chunk_at(i, chunks, snapshot_chunks).generation == released.generation[i] ? intact : recycled) |= bit; } return intact; } diff --git a/tests/startup_compute_dispatch_input_check.py b/tests/startup_compute_dispatch_input_check.py index 57b9e88392..66acb20d30 100644 --- a/tests/startup_compute_dispatch_input_check.py +++ b/tests/startup_compute_dispatch_input_check.py @@ -43,6 +43,8 @@ def main(consumer, dxc, adapter): with tempfile.TemporaryDirectory() as temporary: directory = Path(temporary) cache, env = prepare(directory) + env.pop('X2W_TRANSLATED_TITLE_INPUT_SNAPSHOT', None) # prepare() copies os.environ: every baseline run starts with the flag off + env.pop("X2W_D3D12_RING_RELEASE_AT_SUBMIT", None) env.update(X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') # guest lists; debug-layer messages go to the log if adapter == 'hardware': env['X2W_TEST_DISPATCH_HARDWARE'] = '1' @@ -85,6 +87,45 @@ def main(consumer, dxc, adapter): assert got == expected and len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused: '), result.stderr[-3000:] errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] assert not errors, errors[0] + # Opt-in X2W_TRANSLATED_TITLE_INPUT_SNAPSHOT: an input in a placed buffer that does not alias title memory holds + # its bytes only in title memory (the desktop copy is zeros). Off, it is refused; on, the bytes are snapshotted + # into the snapshot pool and all 320 words match; with title memory zero (dispatch-input-copied) the dispatch runs + # on zeros: not refused, not the expected words, not untouched. + snapshot_env = dict(env, X2W_TRANSLATED_TITLE_INPUT_SNAPSHOT='1') + got, result = dispatch(directory, consumer, env, 'dispatch-input-snapshot') + assert got == untouched and lines(result, 'refused: ')[0].endswith(CONTROLS[3][1]), result.stderr[-3000:] + got, result = dispatch(directory, consumer, snapshot_env, 'dispatch-input-snapshot') + assert got == expected and len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused: '), result.stderr[-3000:] + assert len(lines(result, 'comes from a snapshot of title memory (1280 bytes)')) == 1, result.stderr[-3000:] + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + got, result = dispatch(directory, consumer, snapshot_env, 'dispatch-input-copied') + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused: '), result.stderr[-3000:] + assert got != expected and got != untouched, 'a snapshot of zero title memory must not give the expected words' + # Long run: 48 frames of dispatches whose 8 MiB title-memory input is snapshotted each frame, the queue completed between + # frames: 384 MiB in all, three times the snapshot pool (128 MiB). The pool must be recycled: every frame translates, + # gives the first frame's words (the consumer exits 85 if one does not), the last frame matches the CPU reference + # and no reservation is refused. + # With release enabled, keep the submitted lists closed to exercise release without Reset. + for release, mode in ((False, 'dispatch-input-snapshot-long'), (True, 'dispatch-input-snapshot-long-keep')): + long_env = dict(snapshot_env) + if release: + long_env["X2W_D3D12_RING_RELEASE_AT_SUBMIT"] = "1" + got, result = dispatch(directory, consumer, long_env, mode) + assert got == expected and not lines(result, 'refused: '), result.stderr[-3000:] + assert not lines(result, 'reservation refused'), lines(result, 'reservation refused') + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) >= 1, result.stderr[-3000:] + # The input must really come from a snapshot (8 MiB), not be read in place: an empty long case would pass everything above. + assert len(lines(result, 'comes from a snapshot of title memory (8388608 bytes)')) == 1, result.stderr[-3000:] + errors = [line for line in lines(result, 'x2w-d3d12-debug ') if ' sev=0 ' in line or ' sev=1 ' in line] + assert not errors, errors[0] + # An all-zero descriptor is an unbound buffer: the dispatch runs on zeros instead of being refused (the empty + # control above has a nonzero base and stays refused). + got, result = dispatch(directory, consumer, env, 'dispatch-input-null') + assert len(lines(result, 'Dispatch(3, 2, 2) translated')) == 1 and not lines(result, 'refused: '), result.stderr[-3000:] + assert len(lines(result, 'comes from zeros for a null descriptor (16 bytes)')) == 1, result.stderr[-3000:] + assert got != expected and got != untouched, 'a null input must read zeros, not the expected words' + print(f'{adapter}: title-input snapshot: off refused, on all {C.WORDS} words match, zero title memory runs on zeros') print(f'startup_compute_dispatch_input: PASS on {adapter} (all {C.WORDS} words match, also with the input behind ' f'a memory view token; {len(CONTROLS)} inputs refused, each with its own reason and an untouched output)') diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index ccac33ac6b..9a89c3dfe1 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -219,6 +220,7 @@ static void* make_committed(void* device, D3D12_HEAP_TYPE type, const D3D12_RESO // Input descriptors the dispatch refuses, one reason each: dispatch-input-empty has zero records (a nonzero base, // word 3 zero), dispatch-input-past ends 16 bytes past the input buffer, dispatch-input-unplaced names memory between // the two buffers, dispatch-input-copied a third buffer placed there at an offset the desktop cannot alias, and +// dispatch-input-null (all four words zero, an unbound buffer) is not refused and reads zeros; // dispatch-input-token writes the token of a texture view where the input descriptor was. // Output descriptors the dispatch refuses, one reason each: dispatch-output-texture-token, -unplaced and -copied do // to the output what dispatch-input-token, -unplaced and -copied do to the input, dispatch-output-unaligned starts @@ -226,10 +228,19 @@ static void* make_committed(void* device, D3D12_HEAP_TYPE type, const D3D12_RESO // For any mode, X2W_TEST_DISPATCH_IN names 1280 bytes that replace the input words, and X2W_TEST_DISPATCH_FIELDS // names six words that replace, for the input and then the output descriptor, the stride (word 1 bits 16-31), the // record count (word 2) and word 3, which are otherwise 4, 320 and 0. +// (The long case puts its input at 0x28000, not at a 64 KiB multiple like 0x20000: there the placed buffer would alias title memory +// and the input would be read in place, never snapshotted, which is how an earlier version of this case passed without a snapshot.) +// dispatch-input-snapshot-long: dispatch-input-snapshot with an 8 MiB input range (the descriptor declares 2M records; the program +// reads the first 320 words) dispatched in 48 frames, 384 MiB of snapshots in all, with the queue completed between frames. The +// snapshot pool holds 128 MiB, so every frame after the sixteenth reuses chunks the GPU is done with; a pool that is not recycled +// refuses them. Every frame must translate and give the first frame's words. // Table controls bind away from the heap start or change the root/view heap after slot 35 without rebinding. static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::string& mode) { constexpr UINT words = 320; + const bool keep_closed = mode == "dispatch-input-snapshot-long-keep"; + const bool long_run = keep_closed || mode == "dispatch-input-snapshot-long"; + constexpr UINT long_records = 2u << 20, long_frames = 48; const bool shared_uav = mode == "dispatch-read-write-uav"; const bool indirect = mode.rfind("dispatch-indirect-", 0) == 0; const bool pixel = mode.rfind("dispatch-indirect-pixel-", 0) == 0; @@ -237,7 +248,8 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin const bool root_srv = mode.rfind("dispatch-root-srv", 0) == 0; const UINT groups = mode == "dispatch-indirect-zero" || write_zero || mode == "dispatch-indirect-pixel-omit" ? 0u : mode == "dispatch-indirect-2" || mode == "dispatch-indirect-pixel-2" ? 2u : 5u; - auto* memory = static_cast(VirtualAlloc(nullptr, (indirect || root_srv) ? 0x30000 : 0x20000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + auto* memory = static_cast(VirtualAlloc(nullptr, long_run ? 0x28000 + long_records * sizeof(UINT) : (indirect || root_srv) ? 0x30000 : 0x20000, + MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); if (!memory) return 70; UINT* const buffers[2] = {memory, memory + 0x10000 / sizeof(UINT)}; UINT* const buffer2 = memory + 0x20000 / sizeof(UINT); @@ -245,7 +257,7 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin buffers[0][i] = 0x8b02a7f1u + i * 0x413b1u; buffers[1][i] = 0xc5c5c5c5u; } - UINT fields[2][3] = {{4, words, 0}, {4, words, 0}}; + UINT fields[2][3] = {{4, long_run ? long_records : words, 0}, {4, words, 0}}; const auto from_file = [](const char* variable, void* data, std::streamsize bytes) { char path[MAX_PATH]; const DWORD n = GetEnvironmentVariableA(variable, path, MAX_PATH); @@ -269,7 +281,7 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin const UINT view[4] = {static_cast(address), static_cast(address >> 32) | fields[i][0] << 16, fields[i][1], fields[i][2]}; std::memcpy(descriptors[mode == "dispatch-swapped" ? 1 - i : i], view, sizeof(view)); } - const UINT64 between = reinterpret_cast(memory) + 0x8000; + const UINT64 between = reinterpret_cast(memory) + (long_run ? 0x28000 : 0x8000); void* placed2 = nullptr; if (root_srv) { for (UINT i = 0; i < words; ++i) buffer2[i] = 0x3c6ef372u + i * 0x19660du; @@ -282,8 +294,13 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin if (FAILED(static_cast(invoke(device, 133, word(buffer2), word(&desc), D3D12_RESOURCE_STATE_COMMON, 0, word(&__uuidof(ID3D12Resource)), word(&placed2))))) return 71; } - if (mode == "dispatch-input-copied" || mode == "dispatch-root-srv-copied" || mode == "dispatch-output-copied") { - const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, words * sizeof(UINT), 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, + // dispatch-input-snapshot: the input words are written into the memory the third buffer is placed over, so they + // exist only in title memory (the desktop copy of a buffer that does not alias holds zeros); dispatch-input-copied + // leaves that memory zero. + if (mode == "dispatch-input-snapshot" || long_run) std::memcpy(reinterpret_cast(between), input, sizeof(input)); + if (mode == "dispatch-input-copied" || mode == "dispatch-input-snapshot" || long_run || mode == "dispatch-root-srv-copied" || + mode == "dispatch-output-copied") { + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, long_run ? long_records * sizeof(UINT) : words * sizeof(UINT), 1, 1, 1, DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR}; void* copied = nullptr; if (FAILED(static_cast(invoke(device, 133, word(reinterpret_cast(between)), word(&desc), D3D12_RESOURCE_STATE_COMMON, 0, @@ -292,9 +309,11 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin if (mode == "dispatch-input-empty") { const UINT view[4] = {0x32c, 0, 0, 0}; std::memcpy(descriptors[0], view, sizeof(view)); + } else if (mode == "dispatch-input-null") { + std::memset(descriptors[0], 0, sizeof(descriptors[0])); // an unbound buffer: all four words zero } else if (mode == "dispatch-input-past") { descriptors[0][2] = words + 4; - } else if (mode == "dispatch-input-unplaced" || mode == "dispatch-input-copied") { + } else if (mode == "dispatch-input-unplaced" || mode == "dispatch-input-copied" || mode == "dispatch-input-snapshot" || long_run) { descriptors[0][0] = static_cast(between); descriptors[0][1] = static_cast(between >> 32) | 4u << 16; } else if (mode == "dispatch-output-unplaced" || mode == "dispatch-output-copied") { @@ -525,6 +544,34 @@ static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::strin if (indirect && !pixel && !record.check_record(groups)) return 80; for (UINT i = 0; i < words; ++i) if (buffers[0][i] != input[i]) return 79; // the input must stay as written + if (long_run) { + UINT first[words]; + std::memcpy(first, buffers[1], sizeof(first)); + for (UINT frame = 1; frame < long_frames; ++frame) { + std::fill_n(buffers[1], words, 0xc5c5c5c5u); + if (FAILED(static_cast(invoke(allocator, 8)))) return 84; + // Keep each submitted list alive and closed so only fenced submit can drop its snapshot hold. + if (keep_closed && FAILED(static_cast(invoke(device, 73, word(list_desc), word(allocator), 0, + word(&__uuidof(ID3D12GraphicsCommandList)), word(&list))))) return 72; + if (FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; + bind(); + invoke(list, 37, 0, constants[0], 0); + invoke(list, 40, 0, 2, word(graphics), 0); + invoke(list, 39, 0, 1, word(&constants[1]), 1); + invoke(list, 35, 1, gpu); + invoke(list, 14, 3, 2, 2); + if (FAILED(static_cast(invoke(list, 9)))) return 75; + invoke(queue, 10, 1, word(&list)); + if (FAILED(static_cast(invoke(queue, 14, word(fence), frame + 1)))) return 76; + for (const ULONGLONG deadline = GetTickCount64() + 10000; invoke(fence, 8) < frame + 1;) { + if (GetTickCount64() >= deadline) return 78; + Sleep(1); + } + if (std::memcmp(first, buffers[1], sizeof(first)) != 0) return 85; // a frame gave other words than the first + for (UINT i = 0; i < words; ++i) + if (buffers[0][i] != input[i]) return 79; + } + } x2w_d3d12_compute_census(); char path[MAX_PATH]; const DWORD n = GetEnvironmentVariableA("X2W_TEST_DISPATCH_OUT", path, MAX_PATH); diff --git a/tests/upload_reservation_check.cpp b/tests/upload_reservation_check.cpp index 075e38f685..0eaa3c6661 100644 --- a/tests/upload_reservation_check.cpp +++ b/tests/upload_reservation_check.cpp @@ -64,6 +64,33 @@ void check_ring_reuse() check(!reuse_upload_chunk(chunk, 0, bytes, queues).mapped, "untracked submit prevents reuse"); } +void check_snapshot_pool() +{ + // The snapshot pool's chunks are numbered after the ring's in the same recording mask and the same per-queue table. + check(snapshot_chunk_base == max_upload_chunks && max_snapshot_chunks == 8 && upload_chunk_bits == 40, "pool numbering"); + unsigned char storage[4 * kAlign]; + std::array ring{}; + std::array snap{}; + UploadRingChunk& chunk = snap[1]; + chunk = {nullptr, storage, sizeof(storage), sizeof(storage)}; + UploadChunkMask recording = 0; + ring[1].hold(recording, 1); + snap[0].hold(recording, snapshot_chunk_base + 0); + snap[1].hold(recording, snapshot_chunk_base + 1); + check(ring[1].recordings == 1 && snap[0].recordings == 1 && snap[1].recordings == 1 && ring[0].recordings == 0, "holds land in their pool"); + TestFence fence; + std::map> queues{{0, {&fence, 1}}}; + queues[0].submitted(recording, true); + check(!queues[0].completed(snapshot_chunk_base + 1), "a snapshot chunk in flight is not complete"); + fence.value = 1; + check(queues[0].completed(snapshot_chunk_base + 1) && queues[0].completed(snapshot_chunk_base + 7), "completed, or never used"); + check(!reuse_upload_chunk(chunk, snapshot_chunk_base + 1, kAlign, queues).mapped, "a held chunk is not reused"); + discard_upload_chunks(recording, ring.data(), snap.data()); + check(recording == 0 && ring[1].recordings == 0 && snap[0].recordings == 0 && snap[1].recordings == 0, "discard releases both pools"); + const auto again = reuse_upload_chunk(chunk, snapshot_chunk_base + 1, kAlign, queues); + check(again.mapped == storage && again.generation == 1, "a finished, unheld snapshot chunk is reused"); +} + // X2W_D3D12_RING_RELEASE_AT_SUBMIT=1 bookkeeping: a closed list stops holding its chunks once its submit is fenced, // the fence alone then guards the chunks, and a later submit of the same list before its Reset fences the intact // chunks again and reports the reused ones. @@ -95,7 +122,7 @@ void check_release_at_submit() const auto reused = reuse_upload_chunk(chunks[0], 0, bytes, queues); check(reused.mapped == storage[0] && reused.generation == 1, "release: chunk reused after the fence"); - UploadChunkMask recycled = UINT32_MAX; + UploadChunkMask recycled = UINT64_MAX; const auto intact = resubmitted_upload_chunks(released, chunks.data(), recycled); check(intact == 2 && recycled == 1, "release: a resubmit finds chunk 1 intact and chunk 0 reused"); @@ -109,6 +136,50 @@ void check_release_at_submit() "release: both chunks reported once reused"); } +void check_snapshot_release_at_submit() +{ + constexpr unsigned ring_index = max_upload_chunks - 1; + constexpr unsigned snapshot_index = upload_chunk_bits - 1; + constexpr auto ring_bit = UploadChunkMask{1} << ring_index; + constexpr auto snapshot_bit = UploadChunkMask{1} << snapshot_index; + constexpr auto both = ring_bit | snapshot_bit; + unsigned char storage[2][kAlign]; + std::array ring{}; + std::array snapshots{}; + auto& ring_chunk = ring.back(); + auto& snapshot = snapshots.back(); + ring_chunk = {nullptr, storage[0], kAlign, kAlign, 2}; + snapshot = {nullptr, storage[1], kAlign, kAlign, 3}; + UploadChunkMask recording = 0; + ring_chunk.hold(recording, ring_index); + snapshot.hold(recording, snapshot_index); + check(recording == both, "snapshot release: both boundary bits are recorded"); + + TestFence first, second; + std::map> queues{{0, {&first, 1}}, {1, {&second, 1}}}; + queues[0].submitted(recording, true); + ReleasedUploadChunks released; + release_upload_chunks_at_submit(recording, ring.data(), released, snapshots.data()); + check(!recording && !ring_chunk.recordings && !snapshot.recordings, "snapshot release: both holds dropped"); + check(released.chunks == both && released.generation[ring_index] == 2 && released.generation[snapshot_index] == 3, + "snapshot release: both generations saved"); + check(!reuse_upload_chunk(snapshot, snapshot_index, kAlign, queues).mapped, + "snapshot release: first fence guards the snapshot after release"); + + UploadChunkMask recycled = UINT64_MAX; + const auto intact = resubmitted_upload_chunks(released, ring.data(), recycled, snapshots.data()); + check(intact == both && !recycled, "snapshot release: intact resubmit includes both pools"); + queues[1].submitted(intact, true); + first.value = 1; + check(!reuse_upload_chunk(snapshot, snapshot_index, kAlign, queues).mapped, + "snapshot release: the other queue's resubmit fence still guards reuse"); + second.value = 1; + const auto reused = reuse_upload_chunk(snapshot, snapshot_index, kAlign, queues); + check(reused.mapped == storage[1] && reused.generation == 4, "snapshot release: reuse after both fences"); + check(resubmitted_upload_chunks(released, ring.data(), recycled, snapshots.data()) == ring_bit && + recycled == snapshot_bit, "snapshot release: a recycled snapshot alone invalidates the recording"); +} + } // namespace int main() @@ -156,7 +227,9 @@ int main() "existing reservations survive exhaustion"); check_ring_reuse(); + check_snapshot_pool(); check_release_at_submit(); + check_snapshot_release_at_submit(); std::puts("upload_reservation_check: all checks passed"); return 0; }