diff --git a/CMakeLists.txt b/CMakeLists.txt index 29e7a60036..3843db6122 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4831,7 +4831,8 @@ if(EXISTS "${INTAKE_PYTHON}") set_tests_properties(startup_address_console_${backend} PROPERTIES TIMEOUT 180 SKIP_RETURN_CODE 77) # Uploads of by-address textures recorded while the queue waits on a fence keep their bytes until the # queue has run them. The ring control fills them from the shared upload ring and must lose the first. - foreach(gate IN ITEMS gate gate-ring) + # gate-ring-reuse: once those submits have completed, the ring must accept new uploads again. + foreach(gate IN ITEMS gate gate-ring gate-ring-reuse) 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" diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index dcad1222ea..4fa9920c90 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -3358,9 +3358,9 @@ uncovered prefix, and right before `OpenExistingHeapFromAddress` opens the heap). Anything else gets a committed default buffer that does not alias the title memory, holds zeros and is reported as success (`not aliased` in the log). `reserve_upload_ring` grows in demand -chunks from 16 MiB up to the 256 MiB total cap. A reservation owns its mapped -bytes for the process; the allocator may use an older unused tail but -refuses exhaustion or allocation failure rather than resetting live storage. +chunks from 16 MiB up to the 256 MiB total cap. Completed chunks whose queue +submissions have finished on the GPU are reused; storage still in flight is +never reused, and exhaustion refuses new reservations. `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`. diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index a67724e605..2ca8e3e8e0 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -1226,13 +1226,14 @@ struct FrameCopy { u64 address = 0; u64 offset = 0; ID3D12Resource* resource = nullptr; + u64 generation = 0; std::vector content; }; std::unordered_map& frame_copies() { static std::unordered_map m; return m; } LONG frame_copies_frame = -1; // Callers have just probed that [address, address + bytes) is readable (readable_window), and draw_lock is held. -bool frame_copy(u64 address, std::size_t bytes, u64* offset, ID3D12Resource** resource) +bool frame_copy(u64 address, std::size_t bytes, u64* offset, ID3D12Resource** resource, ID3D12CommandList* list = nullptr) { if (frame_copies_frame != frame_number) { frame_copies().clear(); @@ -1243,25 +1244,27 @@ bool frame_copy(u64 address, std::size_t bytes, u64* offset, ID3D12Resource** re const auto found = frame_copies().find(key); const bool known = found != frame_copies().end() && found->second.address == address && found->second.content.size() == bytes; if (known && std::memcmp(found->second.content.data(), title, bytes) == 0) { - *offset = found->second.offset; - if (resource) *resource = found->second.resource; - return true; + if (validate_and_note_upload_ring_use(found->second.resource, found->second.generation, list)) { + *offset = found->second.offset; + if (resource) *resource = found->second.resource; + return true; + } } - u64 fresh = 0; - ID3D12Resource* chunk = nullptr; - auto* ring = reserve_upload_ring(bytes, &fresh, &chunk); - if (!ring || !chunk) return false; + const auto reservation = reserve_upload_ring(bytes, list); + if (!reservation.mapped || !reservation.resource) return false; + const u64 fresh = reservation.offset; + auto* chunk = reservation.resource; // Cache insertion and snapshot allocation are optional. Fill the ring directly if they fail. const unsigned char* source = title; try { std::vector content(title, title + bytes); // Use the stored snapshot to fill the ring so the GPU bytes and subsequent comparisons agree. - auto entry = frame_copies().insert_or_assign(key, FrameCopy{address, fresh, chunk, std::move(content)}); + auto entry = frame_copies().insert_or_assign(key, FrameCopy{address, fresh, chunk, reservation.generation, std::move(content)}); source = entry.first->second.content.data(); } catch (const std::bad_alloc&) { // The ring slice is already reserved. The draw can proceed without another CPU allocation. } - std::memcpy(ring, source, bytes); + std::memcpy(reservation.mapped, source, bytes); if (known) { static LONG refreshed; if (first_calls(refreshed, 4)) @@ -1436,7 +1439,7 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) if (owned.cpu) { owned.cursor += (bytes + placement - 1) & ~(placement - 1); } else { - rows = reserve_upload_ring(static_cast(bytes), &offset, &chunk); + rows = reserve_upload_ring(static_cast(bytes), &offset, &chunk, list); if (!rows || !chunk) { state.done = false; return false; @@ -1458,7 +1461,7 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) const u64 bytes = plan.bytes(i); u64 offset = 0; ID3D12Resource* chunk = nullptr; - auto* rows = reserve_upload_ring(static_cast(bytes), &offset, &chunk); + auto* rows = reserve_upload_ring(static_cast(bytes), &offset, &chunk, list); if (!rows || !chunk) { state.done = false; return true; @@ -1472,7 +1475,7 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) u64 offset = 0; const auto bytes = plan.bytes(0); ID3D12Resource* chunk = nullptr; - auto* rows = reserve_upload_ring(static_cast(bytes), &offset, &chunk); + auto* rows = reserve_upload_ring(static_cast(bytes), &offset, &chunk, list); if (!rows || !chunk) { state.done = false; return true; @@ -1488,7 +1491,7 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) u64 offset = 0; ID3D12Resource* chunk = nullptr; if (is_compact) { - auto* const rows = reserve_upload_ring(static_cast(bytes), &offset, &chunk); + auto* const rows = reserve_upload_ring(static_cast(bytes), &offset, &chunk, list); if (!rows || !chunk) { state.done = false; return true; @@ -1497,7 +1500,7 @@ bool upload_texture(Wrapper* self, Wrapper* resource, ID3D12Resource* texture) for (u64 y = 0; y < level.rows; ++y) std::memcpy(rows + y * fp.Footprint.RowPitch, memory + level.offset + y * level.row_bytes, static_cast(level.row_bytes)); - } else if (!ring_copy(reinterpret_cast(memory) + stride * s + fp.Offset, static_cast(bytes), &offset, &chunk) || !chunk) { + } else if (!ring_copy(reinterpret_cast(memory) + stride * s + fp.Offset, static_cast(bytes), &offset, &chunk, list) || !chunk) { state.done = false; return true; } @@ -2585,7 +2588,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI // to a DWORD, so initialise its final padding without reading the guest. const auto padded = (bytes + 3) & ~std::size_t{3}; ID3D12Resource* chunk = nullptr; - auto* target = readable_window(address, bytes) >= bytes ? reserve_upload_ring(padded, &offset, &chunk) : nullptr; + auto* target = readable_window(address, bytes) >= bytes ? reserve_upload_ring(padded, &offset, &chunk, list) : nullptr; if (target) { std::memcpy(target, reinterpret_cast(address), bytes); std::memset(target + bytes, 0, padded - bytes); @@ -2600,7 +2603,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI continue; } ID3D12Resource* chunk = nullptr; - bool have = address && bytes && readable_window(address, bytes) >= bytes && frame_copy(address, bytes, &offset, &chunk); + bool have = address && bytes && readable_window(address, bytes) >= bytes && frame_copy(address, bytes, &offset, &chunk, list); // Experiment (X2W_DRAW_NULL_IDENTITY=1): an empty buffer slot reads as repeated identity // matrices instead of zeros. The start-up screen's last pass takes its world matrix from a // slot the title leaves empty here; why is not known yet. @@ -2618,7 +2621,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI for (int k = 0; k < 64; ++k) identity[k] = (k % 16) % 5 == 0 ? 1.0f : 0.0f; address = reinterpret_cast(identity); bytes = sizeof(identity); - have = frame_copy(address, bytes, &offset, &chunk); + have = frame_copy(address, bytes, &offset, &chunk, list); } buffer_view(dest, have ? chunk : nullptr, offset, bytes); count_buffer(have); @@ -2723,7 +2726,7 @@ bool draw_translated(Wrapper* self, bool indexed, UINT count, UINT instances, UI auto view = live_indices; if (live_index_resource) { require_state(self, live_index_resource, D3D12_RESOURCE_STATE_INDEX_BUFFER); - } else if (indices_ok && frame_copy(index_address, index_total, &offset, &index_chunk) && index_chunk) { + } else if (indices_ok && frame_copy(index_address, index_total, &offset, &index_chunk, list) && index_chunk) { view = {index_chunk->GetGPUVirtualAddress() + offset, static_cast(index_total), index_bytes == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT}; } diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 57c89ef8ed..07ac0c9bf7 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -1030,6 +1030,7 @@ bool retire_reasons_enabled(); void retire_diag_note_release(Wrapper* w); void drop_mesh_lease_owner(Wrapper* w); void discard_mesh_lease_recording(ID3D12CommandList* list); +void discard_upload_ring(ID3D12CommandList* list); void clear_unplaced_buffers(Wrapper* device); ULONG __stdcall release(Wrapper* self) { @@ -1046,7 +1047,9 @@ ULONG __stdcall release(Wrapper* self) linear_buffers().retire(static_cast(self->own().real)); } if (self->own().kind == list_kind && self->own().real) { - discard_mesh_lease_recording(static_cast(self->own().real)); + auto* list = static_cast(self->own().real); + discard_mesh_lease_recording(list); + discard_upload_ring(list); retire_drop_recording(self); } if (self->own().kind == resource_kind && retire_reasons_enabled()) retire_diag_note_release(self); @@ -1648,7 +1651,11 @@ bool submit_fence_fails() // 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. -void note_submits(ID3D12CommandQueue* queue, const std::vector& lists) +void note_upload_ring_submits(ID3D12Fence* fence, UINT64 value, const std::vector& lists); +void mark_upload_ring_untracked(const std::vector& lists); +void discard_upload_ring(ID3D12CommandList* list); + +void note_submits(ID3D12CommandQueue* queue, const std::vector& lists, const std::vector& native_lists) { auto& [fence, value] = queue_submits[queue]; if (!fence && !submit_fence_fails()) { @@ -1660,6 +1667,7 @@ void note_submits(ID3D12CommandQueue* queue, const std::vector& lists) } if (fence && SUCCEEDED(queue->Signal(fence, value + 1))) { ++value; + note_upload_ring_submits(fence, value, native_lists); for (Wrapper* list : lists) { const auto found = list_recordings.find(list); if (found == list_recordings.end()) continue; @@ -1669,6 +1677,7 @@ void note_submits(ID3D12CommandQueue* queue, const std::vector& lists) else same->second = value; } } else { + mark_upload_ring_untracked(native_lists); for (Wrapper* list : lists) if (const auto found = list_recordings.find(list); found != list_recordings.end()) found->second->untracked = true; static LONG failures; @@ -1804,6 +1813,7 @@ HRESULT __stdcall list_reset(Wrapper* self, void* allocator) discard_list_gpu_writes(self); discard_draw_sampler_heaps(previous); discard_address_uploads(previous); + discard_upload_ring(previous); discard_mesh_lease_recording(previous); retire_drop_recording(self); if (draw_dump_frame()) draw_dumps().discard(previous); @@ -1842,6 +1852,7 @@ HRESULT __stdcall list_close(Wrapper* self) discard_list_gpu_writes(self); discard_draw_sampler_heaps(list); discard_address_uploads(list); + discard_upload_ring(list); discard_mesh_lease_recording(list); retire_drop_recording(self); if (draw_dump_frame()) draw_dumps().discard(list); @@ -2414,10 +2425,126 @@ 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. Exhaustion -// refuses new reservations rather than reusing storage without completion. +// 16 MiB up to 256 MiB in total and stay alive for the process. Completed chunks +// whose queue submissions have finished on the GPU are reused; storage still in +// flight is never reused, and exhaustion refuses new reservations. + +static SRWLOCK upload_ring_lock = SRWLOCK_INIT; +static std::vector upload_ring_chunks; +static std::size_t upload_ring_active = 0; +static u64 upload_ring_total_bytes = 0; +static std::unordered_map> recorded_upload_chunks; + +void note_upload_ring_submits(ID3D12Fence* fence, UINT64 value, const std::vector& lists) +{ + if (!fence) return; + AcquireSRWLockExclusive(&upload_ring_lock); + for (auto* list : lists) { + const auto it = recorded_upload_chunks.find(list); + if (it == recorded_upload_chunks.end()) continue; + for (std::size_t chunk_idx : it->second) { + if (chunk_idx < upload_ring_chunks.size()) { + auto& chunk = upload_ring_chunks[chunk_idx]; + const auto sub = std::find_if(chunk.submits.begin(), chunk.submits.end(), + [fence](const auto& s) { return s.first == fence; }); + if (sub != chunk.submits.end()) { + sub->second = value; + } else { + chunk.submits.emplace_back(fence, value); + } + } + } + } + ReleaseSRWLockExclusive(&upload_ring_lock); +} + +void discard_upload_ring(ID3D12CommandList* list) +{ + if (!list) return; + AcquireSRWLockExclusive(&upload_ring_lock); + const auto it = recorded_upload_chunks.find(list); + if (it != recorded_upload_chunks.end()) { + for (std::size_t chunk_idx : it->second) { + if (chunk_idx < upload_ring_chunks.size()) { + auto& chunk = upload_ring_chunks[chunk_idx]; + if (chunk.recordings > 0) --chunk.recordings; + } + } + recorded_upload_chunks.erase(it); + } + ReleaseSRWLockExclusive(&upload_ring_lock); +} -UploadReservation reserve_upload_ring(std::size_t bytes) +void mark_upload_ring_untracked(const std::vector& lists) +{ + AcquireSRWLockExclusive(&upload_ring_lock); + for (ID3D12CommandList* list : lists) { + const auto it = recorded_upload_chunks.find(list); + if (it == recorded_upload_chunks.end()) continue; + for (std::size_t chunk_idx : it->second) { + if (chunk_idx < upload_ring_chunks.size()) { + upload_ring_chunks[chunk_idx].untracked = true; + } + } + } + ReleaseSRWLockExclusive(&upload_ring_lock); +} + +bool validate_and_note_upload_ring_use(ID3D12Resource* resource, u64 generation, ID3D12CommandList* list) +{ + if (!resource) return false; + AcquireSRWLockExclusive(&upload_ring_lock); + for (std::size_t i = 0; i < upload_ring_chunks.size(); ++i) { + if (upload_ring_chunks[i].resource == resource) { + if (upload_ring_chunks[i].generation != generation) { + ReleaseSRWLockExclusive(&upload_ring_lock); + return false; + } + if (list) { + auto& chunks = recorded_upload_chunks[list]; + if (std::find(chunks.begin(), chunks.end(), i) == chunks.end()) { + chunks.push_back(i); + ++upload_ring_chunks[i].recordings; + } + } + ReleaseSRWLockExclusive(&upload_ring_lock); + return true; + } + } + ReleaseSRWLockExclusive(&upload_ring_lock); + return false; +} + +void note_upload_ring_use(ID3D12Resource* resource, ID3D12CommandList* list) +{ + if (!resource || !list) return; + AcquireSRWLockExclusive(&upload_ring_lock); + for (std::size_t i = 0; i < upload_ring_chunks.size(); ++i) { + if (upload_ring_chunks[i].resource == resource) { + auto& chunks = recorded_upload_chunks[list]; + if (std::find(chunks.begin(), chunks.end(), i) == chunks.end()) { + chunks.push_back(i); + ++upload_ring_chunks[i].recordings; + } + break; + } + } + ReleaseSRWLockExclusive(&upload_ring_lock); +} + +bool is_upload_chunk_generation_valid(ID3D12Resource* resource, u64 generation) +{ + return validate_and_note_upload_ring_use(resource, generation, nullptr); +} + +static bool is_upload_chunk_idle(const UploadRingChunk& chunk) +{ + return is_upload_chunk_idle(chunk, [](ID3D12Fence* fence) { + return fence->GetCompletedValue(); + }); +} + +UploadReservation reserve_upload_ring(std::size_t bytes, ID3D12CommandList* list = nullptr) { constexpr u64 initial_chunk_bytes = u64{16} << 20; constexpr u64 max_total_bytes = u64{256} << 20; @@ -2426,23 +2553,28 @@ UploadReservation reserve_upload_ring(std::size_t bytes) if (bytes == 0 || bytes > max_alloc_bytes) return reservation; const u64 rounded = (static_cast(bytes) + 511) & ~u64{511}; - static SRWLOCK lock = SRWLOCK_INIT; - static std::vector chunks; - static std::size_t active = 0; - static u64 total_bytes = 0; + AcquireSRWLockExclusive(&upload_ring_lock); + const auto note_list = [&](std::size_t index) { + if (!list) return; + auto& chunks = recorded_upload_chunks[list]; + if (std::find(chunks.begin(), chunks.end(), index) == chunks.end()) { + chunks.push_back(index); + ++upload_ring_chunks[index].recordings; + } + }; - AcquireSRWLockExclusive(&lock); - if (!chunks.empty()) { - reservation = reserve_upload_chunk(chunks[active], rounded); + if (!upload_ring_chunks.empty()) { + reservation = reserve_upload_chunk(upload_ring_chunks[upload_ring_active], rounded); if (reservation.mapped) { - ReleaseSRWLockExclusive(&lock); + note_list(upload_ring_active); + ReleaseSRWLockExclusive(&upload_ring_lock); return reservation; } } - const u64 remaining = total_bytes < max_total_bytes ? max_total_bytes - total_bytes : 0; + const u64 remaining = upload_ring_total_bytes < max_total_bytes ? max_total_bytes - upload_ring_total_bytes : 0; if (rounded <= remaining) { - u64 chunk_bytes = chunks.empty() ? initial_chunk_bytes : chunks.back().capacity * 2; + u64 chunk_bytes = upload_ring_chunks.empty() ? initial_chunk_bytes : upload_ring_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; @@ -2463,11 +2595,12 @@ UploadReservation reserve_upload_ring(std::size_t bytes) auto* budget = x2w_budget::committed(device, created, D3D12_HEAP_TYPE_UPLOAD); if (SUCCEEDED(created->Map(0, nullptr, &base))) { try { - chunks.push_back(UploadRingChunk{created, static_cast(base), chunk_bytes, 0}); - total_bytes += chunk_bytes; - active = chunks.size() - 1; - reservation = reserve_upload_chunk(chunks.back(), rounded); - ReleaseSRWLockExclusive(&lock); + upload_ring_chunks.push_back(UploadRingChunk{created, static_cast(base), chunk_bytes, 0}); + upload_ring_total_bytes += chunk_bytes; + upload_ring_active = upload_ring_chunks.size() - 1; + reservation = reserve_upload_chunk(upload_ring_chunks.back(), rounded); + note_list(upload_ring_active); + ReleaseSRWLockExclusive(&upload_ring_lock); return reservation; } catch (const std::bad_alloc&) { created->Unmap(0, nullptr); @@ -2482,46 +2615,63 @@ UploadReservation reserve_upload_ring(std::size_t bytes) } } // Allocation failed or the cap was reached. Older unused tails are still safe. - for (std::size_t index = 0; index < chunks.size(); ++index) { - reservation = reserve_upload_chunk(chunks[index], rounded); + for (std::size_t index = 0; index < upload_ring_chunks.size(); ++index) { + reservation = reserve_upload_chunk(upload_ring_chunks[index], rounded); if (reservation.mapped) { - active = index; - ReleaseSRWLockExclusive(&lock); + upload_ring_active = index; + note_list(upload_ring_active); + ReleaseSRWLockExclusive(&upload_ring_lock); return reservation; } } - ReleaseSRWLockExclusive(&lock); + // Check if any chunk whose GPU work has completed can be reset. + for (std::size_t step = 0; step < upload_ring_chunks.size(); ++step) { + const std::size_t index = (upload_ring_active + 1 + step) % upload_ring_chunks.size(); + auto& chunk = upload_ring_chunks[index]; + if (chunk.capacity >= rounded && is_upload_chunk_idle(chunk)) { + reset_upload_chunk(chunk); + reservation = reserve_upload_chunk(chunk, rounded); + if (reservation.mapped) { + upload_ring_active = index; + note_list(upload_ring_active); + ReleaseSRWLockExclusive(&upload_ring_lock); + return reservation; + } + } + } + + ReleaseSRWLockExclusive(&upload_ring_lock); static LONG refused; if (first_calls(refused, 8)) log("x2w-draw upload ring reservation refused: no unused capacity"); return reservation; } -unsigned char* reserve_upload_ring(std::size_t bytes, u64* offset, ID3D12Resource** resource) +unsigned char* reserve_upload_ring(std::size_t bytes, u64* offset, ID3D12Resource** resource, ID3D12CommandList* list = nullptr) { if (resource) *resource = nullptr; if (offset) *offset = 0; - const UploadReservation reservation = reserve_upload_ring(bytes); + const UploadReservation reservation = reserve_upload_ring(bytes, list); if (!reservation.mapped) return nullptr; if (offset) *offset = reservation.offset; if (resource) *resource = reservation.resource; return reservation.mapped; } -bool ring_copy(u64 title_address, std::size_t bytes, u64* offset, ID3D12Resource** resource = nullptr) +bool ring_copy(u64 title_address, std::size_t bytes, u64* offset, ID3D12Resource** resource = nullptr, ID3D12CommandList* list = nullptr) { - auto* dest = reserve_upload_ring(bytes, offset, resource); + auto* dest = reserve_upload_ring(bytes, offset, resource, list); if (!dest) return false; std::memcpy(dest, reinterpret_cast(title_address), bytes); return true; } -D3D12_GPU_VIRTUAL_ADDRESS upload_from_title(u64 title_address, std::size_t bytes) +D3D12_GPU_VIRTUAL_ADDRESS upload_from_title(u64 title_address, std::size_t bytes, ID3D12CommandList* list = nullptr) { u64 offset = 0; ID3D12Resource* resource = nullptr; - return ring_copy(title_address, bytes, &offset, &resource) && resource ? resource->GetGPUVirtualAddress() + offset : 0; + return ring_copy(title_address, bytes, &offset, &resource, list) && resource ? resource->GetGPUVirtualAddress() + offset : 0; } // Number of contiguous readable bytes at address, up to wanted. @@ -3877,7 +4027,7 @@ void __stdcall list_root_srv(Wrapper* self, UINT parameter, u64 address) return; } const std::size_t bytes = readable_window(address, 0x10000); - const D3D12_GPU_VIRTUAL_ADDRESS desktop = bytes ? upload_from_title(address, bytes) : 0; + const D3D12_GPU_VIRTUAL_ADDRESS desktop = bytes ? upload_from_title(address, bytes, list) : 0; static LONG logged; if (first_calls(logged, 4)) { char head[3 * 32 + 1]; @@ -4059,7 +4209,7 @@ void __stdcall queue_execute(Wrapper* self, UINT count, void* const* lists) }); retire_address_uploads(queue, native_lists); retire_draw_sampler_heaps(queue, native_lists); - note_submits(queue, wrappers); + note_submits(queue, wrappers, native_lists); retire_note_submission(queue, wrappers); for (Wrapper* w : wrappers) commit_list_gpu_writes(w); InterlockedIncrement(&render_executes); diff --git a/src/startup_stubs/upload_reservation.h b/src/startup_stubs/upload_reservation.h index 991beab79b..8a272b23b0 100644 --- a/src/startup_stubs/upload_reservation.h +++ b/src/startup_stubs/upload_reservation.h @@ -1,20 +1,28 @@ #pragma once #include +#include +#include struct ID3D12Resource; +struct ID3D12Fence; struct UploadRingChunk { ID3D12Resource* resource = nullptr; unsigned char* mapped = nullptr; std::uint64_t capacity = 0; std::uint64_t used = 0; + std::size_t recordings = 0; + std::uint64_t generation = 0; + bool untracked = false; + std::vector> submits{}; }; struct UploadReservation { unsigned char* mapped = nullptr; std::uint64_t offset = 0; ID3D12Resource* resource = nullptr; + std::uint64_t generation = 0; }; // Caller holds the lock. A successful reservation owns previously unused bytes. @@ -23,5 +31,30 @@ inline UploadReservation reserve_upload_chunk(UploadRingChunk& chunk, std::uint6 if (chunk.used > chunk.capacity || rounded > chunk.capacity - chunk.used) return {}; const auto start = chunk.used; chunk.used += rounded; - return {chunk.mapped + start, start, chunk.resource}; + return {chunk.mapped + start, start, chunk.resource, chunk.generation}; +} + +template +inline bool is_upload_chunk_idle(const UploadRingChunk& chunk, FenceQuery&& query) +{ + if (chunk.untracked || chunk.recordings != 0) return false; + for (const auto& submit : chunk.submits) { + if (!submit.first) return false; + const auto completed = query(submit.first); + if (completed == UINT64_MAX || completed < submit.second) return false; + } + return true; +} + +inline bool is_upload_chunk_generation_valid(const UploadRingChunk& chunk, std::uint64_t generation) +{ + return chunk.generation == generation; +} + +inline void reset_upload_chunk(UploadRingChunk& chunk) +{ + chunk.used = 0; + ++chunk.generation; + chunk.submits.clear(); + chunk.recordings = 0; } diff --git a/tests/startup_address_console_check.py b/tests/startup_address_console_check.py index d36db04448..aef58b108a 100644 --- a/tests/startup_address_console_check.py +++ b/tests/startup_address_console_check.py @@ -8,6 +8,8 @@ gate-ring the same draws with X2W_TEST_ADDRESS_UPLOAD_RING=1: the 256 MiB ring refuses the uploads past its cap, the refused draws read the null view and the left half keeps payload 0 + gate-ring-reuse gate-ring, then once every submit has completed one more payload from + the ring, which must not be refused The backing bytes are built here, independently of src/startup_stubs/gfx10_layout.h, from the address equations of AMD addrlib's GFX10 pattern tables, written out below. Reference: addrlib as Mesa carries it @@ -217,6 +219,48 @@ def gate_colour(payload): return bytes(((17 * payload + 3) & 255, (255 - 9 * payload) & 255, payload ^ 0x5a, 255)) +def check_gate_ring_reuse(directory, consumer, backend): + """After the gate-ring sequence has completed, one more payload must find ring capacity again. + + The fixture runs the gate-ring draws. While the queue is still held behind the gate, a negative + control draw attempts a reservation from the exhausted ring; because submissions are still in flight, + the reservation must be refused and payload 0 on the left half preserved. Once every submit has + completed, a final draw uploads payload 18 over the right half from the recycled ring. The left half + must hold payload 0 and the right half payload 18. + """ + hlsl = ("Texture2D t : register(t0);\n" + "float4 main(float4 p : SV_Position) : SV_Target {\n" + " return t.Load(int3(uint(p.x) % 2048, uint(p.y) % 2048, 0));\n}\n") + trap_log = directory / "trap.log" + modes = {"X2W_TEST_CONSOLE_GATE": "1", "X2W_TRAP_LOG": str(trap_log), + "X2W_TEST_ADDRESS_UPLOAD_RING": "1", "X2W_TEST_ADDRESS_UPLOAD_RING_REUSE": "1"} + actual = draw_texture(directory, consumer, backend, hlsl, modes) + if actual is None: + return 77 + if len(actual) != TARGET_W * TARGET_H * 4: + raise AssertionError(f"gate-ring-reuse: readback length {len(actual)}") + first, last = gate_colour(0), gate_colour(GATE_PAYLOADS) + wrong = {"left": 0, "right": 0} + seen = set() + for y in range(TARGET_H): + for x in range(TARGET_W): + pixel = actual[4 * (y * TARGET_W + x):4 * (y * TARGET_W + x) + 4] + side = "left" if x < TARGET_W // 2 else "right" + if pixel != (first if side == "left" else last): + wrong[side] += 1 + seen.add(pixel.hex()) + if wrong["left"] or wrong["right"]: + raise AssertionError(f"gate-ring-reuse: {wrong} wrong pixels, found {sorted(seen)[:4]}; expected " + f"{first.hex()} left, {last.hex()} right (payload {GATE_PAYLOADS} after completion)") + log = trap_log.read_text(errors="replace") + if "x2w-draw upload ring reservation refused: no unused capacity" not in log: + raise AssertionError("gate-ring-reuse: expected upload reservation refusal while queue was held") + half = TARGET_W * TARGET_H // 2 + print(f"{backend} gate-ring-reuse: after all submits completed, payload {GATE_PAYLOADS} was uploaded from the ring; " + f"{half} left pixels hold payload 0 and {half} right pixels payload {GATE_PAYLOADS}") + return 0 + + def check_gate(directory, consumer, backend, ring): """Uploads recorded while the queue cannot run must still hold their bytes when it does. @@ -282,9 +326,12 @@ def check_gate(directory, consumer, backend, ring): if __name__ == "__main__": - if len(sys.argv) not in (3, 4) or (len(sys.argv) == 4 and sys.argv[3] not in ("gate", "gate-ring")): - usage = "usage: startup_address_console_check.py [gate | gate-ring]\n" + if len(sys.argv) not in (3, 4) or (len(sys.argv) == 4 and sys.argv[3] not in ("gate", "gate-ring", "gate-ring-reuse")): + usage = "usage: startup_address_console_check.py [gate | gate-ring | gate-ring-reuse]\n" sys.exit(usage + "\n\n".join(__doc__.split("\n\n")[:2])) + if len(sys.argv) == 4 and sys.argv[3] == "gate-ring-reuse": + with tempfile.TemporaryDirectory() as temporary: + sys.exit(check_gate_ring_reuse(Path(temporary), sys.argv[1], sys.argv[2])) if len(sys.argv) == 4: with tempfile.TemporaryDirectory() as temporary: sys.exit(check_gate(Path(temporary), sys.argv[1], sys.argv[2], sys.argv[3] == "gate-ring")) diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index 633dd69406..5e11878653 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -601,6 +601,16 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* } Sleep(250); if (invoke(fence, 8) != 0) return 46; // a submit completed although the queue was held + // Negative control: while the queue is held behind the gate, any new reservation must be + // refused because storage is in-flight. If early reuse wrongly recycled chunks before + // completion, this draw would overwrite chunk 0 while payload 0 is still in flight. + if (GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_UPLOAD_RING_REUSE", nullptr, 0)) { + if (!next_recording()) return 35; + if (const int result = draw_gated_console_payload(guest, list, 99, false)) return result; + invoke(list, 9); + invoke(queue, 10, 1, arg(&list)); + if (FAILED(static_cast(invoke(queue, 14, arg(fence), payloads + 1)))) return 24; + } if (FAILED(static_cast(invoke(gate, 10, 1)))) return 47; // One more recording without a draw: its submit is where the stand-in visits the completed ones. const auto reached = [&](UINT64 value) { @@ -608,11 +618,22 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* while (invoke(fence, 8) < value && GetTickCount64() < deadline) Sleep(1); return invoke(fence, 8) == value; }; - if (!reached(payloads)) return 25; + const UINT64 gate_fence = GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_UPLOAD_RING_REUSE", nullptr, 0) + ? payloads + 1 : payloads; + if (!reached(gate_fence)) return 25; if (!next_recording()) return 35; invoke(list, 9); invoke(queue, 10, 1, arg(&list)); - if (FAILED(static_cast(invoke(queue, 14, arg(fence), payloads + 1))) || !reached(payloads + 1)) return 25; + if (FAILED(static_cast(invoke(queue, 14, arg(fence), gate_fence + 1))) || !reached(gate_fence + 1)) return 25; + // X2W_TEST_ADDRESS_UPLOAD_RING_REUSE: every earlier upload has now completed, so one more payload over + // the right half must find ring capacity again (refs #2823). + if (GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_UPLOAD_RING_REUSE", nullptr, 0)) { + if (!next_recording()) return 35; + if (const int result = draw_gated_console_payload(guest, list, payloads, false)) return result; + invoke(list, 9); + invoke(queue, 10, 1, arg(&list)); + if (FAILED(static_cast(invoke(queue, 14, arg(fence), gate_fence + 2))) || !reached(gate_fence + 2)) return 25; + } return read_stream_target(desktop.Get(), frame, pixels); } else if (bc) { extern int draw_bc_address_srvs(void*, void*); diff --git a/tests/upload_reservation_check.cpp b/tests/upload_reservation_check.cpp index 8a20ad4367..161e1652a4 100644 --- a/tests/upload_reservation_check.cpp +++ b/tests/upload_reservation_check.cpp @@ -63,6 +63,56 @@ int main() storage_a[2 * kAlign - 1] == 0x5a && storage_a[2 * kAlign] == 0x7d, "existing reservations survive exhaustion"); + reset_upload_chunk(chunks[0]); + check(chunks[0].used == 0 && chunks[0].recordings == 0 && chunks[0].submits.empty(), + "reset clears cursor, recordings and submits"); + const auto recycled = reserve_upload_chunk(chunks[0], kAlign); + check(recycled.mapped == storage_a && recycled.offset == 0 && recycled.generation == 1, + "recycled chunk reserves from start with incremented generation"); + check(is_upload_chunk_generation_valid(chunks[0], 1), "generation validation matches incremented generation"); + check(!is_upload_chunk_generation_valid(chunks[0], 0), "generation validation rejects stale generation"); + + // Guard fence logic, recording holds and device removal: + struct MockFence { + std::uint64_t completed = 0; + }; + MockFence fence_a; + MockFence fence_b; + const auto fence_query = [](const ID3D12Fence* f) { + return reinterpret_cast(f)->completed; + }; + + check(is_upload_chunk_idle(chunks[0], fence_query), "chunk without recordings or submits is idle"); + + chunks[0].recordings = 1; + check(!is_upload_chunk_idle(chunks[0], fence_query), "closed list still held cannot be recycled"); + + chunks[0].recordings = 0; + chunks[0].untracked = true; + check(!is_upload_chunk_idle(chunks[0], fence_query), "untracked chunk after failed submit fence cannot be recycled"); + chunks[0].untracked = false; + chunks[0].submits.emplace_back(reinterpret_cast(&fence_a), 10); + fence_a.completed = 9; + check(!is_upload_chunk_idle(chunks[0], fence_query), "chunk with in-flight submit is not idle"); + + fence_a.completed = 10; + check(is_upload_chunk_idle(chunks[0], fence_query), "chunk with completed submit is idle"); + + // Multi-queue submits: + chunks[0].submits.emplace_back(reinterpret_cast(&fence_b), 5); + fence_b.completed = 4; + check(!is_upload_chunk_idle(chunks[0], fence_query), "chunk with second pending queue submit is not idle"); + + fence_b.completed = UINT64_MAX; + check(!is_upload_chunk_idle(chunks[0], fence_query), "device removal is not completion"); + + fence_b.completed = 5; + check(is_upload_chunk_idle(chunks[0], fence_query), "chunk with all queue submits completed is idle"); + + reset_upload_chunk(chunks[0]); + check(chunks[0].used == 0 && chunks[0].recordings == 0 && chunks[0].submits.empty() && chunks[0].generation == 2, + "final reset clears submits and increments generation"); + std::puts("upload_reservation_check: all checks passed"); return 0; }