diff --git a/CMakeLists.txt b/CMakeLists.txt index 29e7a6003..8d9886fdf 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -4830,8 +4830,10 @@ if(EXISTS "${INTAKE_PYTHON}") "$" "${backend}") 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) + # 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) 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/experiments.md b/docs/experiments.md index 1fe79025e..f9fb98d4e 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16335,6 +16335,12 @@ instead. It requires a reservation refusal after exhaustion, payload 0 preserved on the left, the null view on the right, and no retained-upload release line. The ring no longer reuses live storage. The revised Windows readback control remains unmeasured on macOS. +`startup_address_console_gate_ring_reuse_{warp,hardware}` runs the same +sequence, opens the gate, waits until every submit has completed and then +draws payload 18 from the ring over the right half. That reservation must not +be refused ([#2837](https://github.com/R0Y00/Xbox2Windows/issues/2837)). With +chunk reuse disabled, as before the fix, it fails while `gate_ring` still +passes. The equations are checked against addrlib and against the three existing layout headers, not against console memory. Which layouts a given console build writes for which textures is not established by diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 6f47b668c..9825ee587 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -3353,8 +3353,15 @@ uncovered prefix, and right before 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. +bytes until its chunk is recycled. The allocator tries the active chunk, the +remaining capacity and older unused tails first. Only then does it recycle a +chunk, and only one that no command-list recording holds (a closed list keeps +its hold until Reset, Release or a failed Close, because it can be submitted +again) and whose last submit on every queue has completed. A failed fence +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. `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 a67724e60..e1107e281 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -1071,8 +1071,7 @@ std::unordered_map& texture_uploads() { static s u64 address_upload_revision; // A texture published in a newly supported console layout is not filled through the shared upload ring. -// The ring is reused without waiting for any queue, and a queue held behind a fence can execute a -// recorded copy long after later uploads have passed over its source bytes. Each such upload owns +// The bounded ring can fill while a queue waits on a fence. Each such upload owns // its upload buffer instead. The buffer and the texture it fills stay referenced by the recording, // and by every submit of that recording until the queue it went to has completed the submit, as // for the sampler heaps above. @@ -1224,15 +1223,14 @@ bool prepare_draw_sampler_heap(Pass& pass, ID3D12GraphicsCommandList* list, bool // upload ring is write-combined memory that is slow to read, so the comparison is against this copy, not the ring. struct FrameCopy { u64 address = 0; - u64 offset = 0; - ID3D12Resource* resource = nullptr; + UploadReservation slice; 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(Wrapper* self, u64 address, std::size_t bytes, u64* offset, ID3D12Resource** resource) { if (frame_copies_frame != frame_number) { frame_copies().clear(); @@ -1243,32 +1241,40 @@ 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; + const auto& slice = found->second.slice; + AcquireSRWLockExclusive(&allocator_lock); + for (unsigned i = 0; i < upload_chunks.size(); ++i) { + auto& chunk = upload_chunks[i]; + if (chunk.resource == slice.resource && chunk.generation == slice.generation) { + chunk.hold(self->own().upload_chunks, i); + ReleaseSRWLockExclusive(&allocator_lock); + *offset = slice.offset; + if (resource) *resource = slice.resource; + return true; + } + } + ReleaseSRWLockExclusive(&allocator_lock); } - u64 fresh = 0; - ID3D12Resource* chunk = nullptr; - auto* ring = reserve_upload_ring(bytes, &fresh, &chunk); - if (!ring || !chunk) return false; + const auto slice = reserve_upload_ring(self, bytes); + if (!slice.mapped) return false; // 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, slice, 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(slice.mapped, source, bytes); if (known) { static LONG refreshed; if (first_calls(refreshed, 4)) log("x2w-draw frame copy of 0x%llx (%zu bytes) refreshed: the title changed it since an earlier draw of this frame", address, bytes); } - *offset = fresh; - if (resource) *resource = chunk; + *offset = slice.offset; + if (resource) *resource = slice.resource; return true; } @@ -1436,7 +1442,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(self, static_cast(bytes), &offset, &chunk); if (!rows || !chunk) { state.done = false; return false; @@ -1458,7 +1464,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(self, static_cast(bytes), &offset, &chunk); if (!rows || !chunk) { state.done = false; return true; @@ -1472,7 +1478,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(self, static_cast(bytes), &offset, &chunk); if (!rows || !chunk) { state.done = false; return true; @@ -1488,7 +1494,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(self, static_cast(bytes), &offset, &chunk); if (!rows || !chunk) { state.done = false; return true; @@ -1497,7 +1503,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(self, reinterpret_cast(memory) + stride * s + fp.Offset, static_cast(bytes), &offset, &chunk) || !chunk) { state.done = false; return true; } @@ -2585,7 +2591,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(self, padded, &offset, &chunk) : nullptr; if (target) { std::memcpy(target, reinterpret_cast(address), bytes); std::memset(target + bytes, 0, padded - bytes); @@ -2600,7 +2606,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(self, address, bytes, &offset, &chunk); // 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 +2624,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(self, address, bytes, &offset, &chunk); } buffer_view(dest, have ? chunk : nullptr, offset, bytes); count_buffer(have); @@ -2723,7 +2729,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(self, index_address, index_total, &offset, &index_chunk) && 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 57c89ef8e..56d453557 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -171,6 +171,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. bool list_close_failed; // Desktop Reset repeats a failed Close result indefinitely. bool tiled_address_srv; // Resource backed by 4 KiB tiled guest memory for translated draws. bool retire_when_idle; // Resource: in the retire class (X2W_D3D12_RELEASE_RETIRED); cleared by any other use. Plain @@ -1023,6 +1024,7 @@ void retire_drop_heap_views(Wrapper* heap); void retire_note_title_release(Wrapper* w); void retire_hold(Wrapper* list, Wrapper* resource); void retire_drop_recording(Wrapper* list); +void release_upload_recording(Wrapper* list); void retire_discard_holds(Wrapper* list); void retire_note_submission(ID3D12CommandQueue* queue, const std::vector& lists); void drain_retired_resources(); @@ -1046,6 +1048,7 @@ ULONG __stdcall release(Wrapper* self) linear_buffers().retire(static_cast(self->own().real)); } if (self->own().kind == list_kind && self->own().real) { + release_upload_recording(self); discard_mesh_lease_recording(static_cast(self->own().real)); retire_drop_recording(self); } @@ -1454,9 +1457,18 @@ struct TitleAllocator { SRWLOCK allocator_lock = SRWLOCK_INIT; std::unordered_map title_allocators; std::unordered_map list_recordings; // list -> allocator holding its recording -std::unordered_map> queue_submits; +std::unordered_map> queue_submits; +std::vector upload_chunks; // allocator_lock also protects recording holds and queue fence values + LONG allocator_swaps, allocator_creates; +void release_upload_recording(Wrapper* list) +{ + AcquireSRWLockExclusive(&allocator_lock); + discard_upload_chunks(list->own().upload_chunks, upload_chunks.data()); + ReleaseSRWLockExclusive(&allocator_lock); +} + // allocator_lock held. TitleAllocator& title_allocator(Wrapper* allocator) { @@ -1650,7 +1662,9 @@ bool submit_fence_fails() // 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) { - auto& [fence, value] = queue_submits[queue]; + auto& submit = queue_submits[queue]; + auto& fence = submit.fence; + auto& value = submit.value; if (!fence && !submit_fence_fails()) { ID3D12Device* device = nullptr; if (SUCCEEDED(queue->GetDevice(IID_PPV_ARGS(&device)))) { @@ -1658,8 +1672,12 @@ void note_submits(ID3D12CommandQueue* queue, const std::vector& lists) device->Release(); } } - if (fence && SUCCEEDED(queue->Signal(fence, value + 1))) { - ++value; + UploadChunkMask chunks = 0; + for (auto* list : lists) chunks |= list->own().upload_chunks; + const bool signaled = fence && SUCCEEDED(queue->Signal(fence, value + 1)); + if (signaled) ++value; + submit.submitted(chunks, signaled); + if (signaled) { for (Wrapper* list : lists) { const auto found = list_recordings.find(list); if (found == list_recordings.end()) continue; @@ -1792,6 +1810,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()); state.list_uploads = nullptr; state.list_scratch = nullptr; state.list_ready = false; @@ -1833,6 +1852,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()); if (const auto found = list_recordings.find(self); found != list_recordings.end() && found->second) found->second->close_failed = true; } @@ -2414,35 +2434,35 @@ 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. A full chunk can be reused once +// no recording can submit its bytes and every queue that used it has finished. -UploadReservation reserve_upload_ring(std::size_t bytes) +UploadReservation reserve_upload_ring(Wrapper* list, std::size_t bytes) { - constexpr u64 initial_chunk_bytes = u64{16} << 20; - constexpr u64 max_total_bytes = u64{256} << 20; - constexpr u64 max_alloc_bytes = max_total_bytes / 4; + constexpr u64 max_alloc_bytes = max_upload_ring_bytes / 4; UploadReservation reservation; 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; + auto& chunks = upload_chunks; + static unsigned active = 0; static u64 total_bytes = 0; - AcquireSRWLockExclusive(&lock); + AcquireSRWLockExclusive(&allocator_lock); + const auto finish = [&](unsigned index) { + active = index; + chunks[index].hold(list->own().upload_chunks, index); + ReleaseSRWLockExclusive(&allocator_lock); + return reservation; + }; if (!chunks.empty()) { reservation = reserve_upload_chunk(chunks[active], rounded); - if (reservation.mapped) { - ReleaseSRWLockExclusive(&lock); - return reservation; - } + if (reservation.mapped) return finish(active); } - const u64 remaining = total_bytes < max_total_bytes ? max_total_bytes - total_bytes : 0; + const u64 remaining = total_bytes < max_upload_ring_bytes ? max_upload_ring_bytes - total_bytes : 0; if (rounded <= remaining) { - u64 chunk_bytes = chunks.empty() ? initial_chunk_bytes : chunks.back().capacity * 2; + u64 chunk_bytes = chunks.empty() ? 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; @@ -2465,10 +2485,8 @@ UploadReservation reserve_upload_ring(std::size_t bytes) 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); - return reservation; + return finish(static_cast(chunks.size() - 1)); } catch (const std::bad_alloc&) { created->Unmap(0, nullptr); if (budget) budget->end_use(); @@ -2482,46 +2500,47 @@ 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) { + for (unsigned index = 0; index < chunks.size(); ++index) { reservation = reserve_upload_chunk(chunks[index], rounded); - if (reservation.mapped) { - active = index; - ReleaseSRWLockExclusive(&lock); - return reservation; - } + if (reservation.mapped) return finish(index); } - ReleaseSRWLockExclusive(&lock); + for (unsigned index = 0; index < chunks.size(); ++index) { + reservation = reuse_upload_chunk(chunks[index], index, rounded, queue_submits); + if (reservation.mapped) return finish(index); + } + + ReleaseSRWLockExclusive(&allocator_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(Wrapper* list, std::size_t bytes, u64* offset, ID3D12Resource** resource) { if (resource) *resource = nullptr; if (offset) *offset = 0; - const UploadReservation reservation = reserve_upload_ring(bytes); + const UploadReservation reservation = reserve_upload_ring(list, bytes); 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(Wrapper* list, u64 title_address, std::size_t bytes, u64* offset, ID3D12Resource** resource = nullptr) { - auto* dest = reserve_upload_ring(bytes, offset, resource); + auto* dest = reserve_upload_ring(list, bytes, offset, resource); 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(Wrapper* list, u64 title_address, std::size_t bytes) { u64 offset = 0; ID3D12Resource* resource = nullptr; - return ring_copy(title_address, bytes, &offset, &resource) && resource ? resource->GetGPUVirtualAddress() + offset : 0; + return ring_copy(list, title_address, bytes, &offset, &resource) && resource ? resource->GetGPUVirtualAddress() + offset : 0; } // Number of contiguous readable bytes at address, up to wanted. @@ -3877,7 +3896,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(self, address, bytes) : 0; static LONG logged; if (first_calls(logged, 4)) { char head[3 * 32 + 1]; diff --git a/src/startup_stubs/upload_reservation.h b/src/startup_stubs/upload_reservation.h index 991beab79..57bf321a5 100644 --- a/src/startup_stubs/upload_reservation.h +++ b/src/startup_stubs/upload_reservation.h @@ -1,20 +1,70 @@ #pragma once +#include #include struct ID3D12Resource; +inline constexpr std::uint64_t initial_upload_chunk_bytes = 16ull << 20; +inline constexpr std::uint64_t max_upload_ring_bytes = 256ull << 20; +// Each allocation except possibly the final remainder is at least the initial size. +inline constexpr unsigned max_upload_chunks = max_upload_ring_bytes / initial_upload_chunk_bytes; +using UploadChunkMask = std::uint32_t; +static_assert(max_upload_chunks <= 32); + +template +struct UploadQueue { + Fence* fence = nullptr; + std::uint64_t value = 0; + std::array last_use{}; + + void submitted(UploadChunkMask chunks, bool signaled) + { + for (unsigned i = 0; chunks; ++i, chunks >>= 1) { + if ((chunks & 1) && last_use[i] != UINT64_MAX) + last_use[i] = signaled ? value : UINT64_MAX; + } + } + + bool completed(unsigned index) const + { + const auto target = last_use[index]; + if (!target) return true; + if (target == UINT64_MAX) return false; + const auto completed = fence->GetCompletedValue(); + return completed != UINT64_MAX && completed >= target; + } +}; + struct UploadRingChunk { ID3D12Resource* resource = nullptr; unsigned char* mapped = nullptr; std::uint64_t capacity = 0; std::uint64_t used = 0; + std::uint64_t generation = 0; + unsigned recordings = 0; + + void hold(UploadChunkMask& recording, unsigned index) + { + const auto bit = UploadChunkMask{1} << index; + if (!(recording & bit)) { + recording |= bit; + ++recordings; + } + } }; +inline void discard_upload_chunks(UploadChunkMask& recording, UploadRingChunk* chunks) +{ + for (unsigned i = 0; recording; ++i, recording >>= 1) + if (recording & 1) --chunks[i].recordings; +} + 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 +73,17 @@ 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}; +} + +// Called only after the unused tails and the capacity budget have been tried. +template +UploadReservation reuse_upload_chunk(UploadRingChunk& chunk, unsigned index, std::uint64_t rounded, const Queues& queues) +{ + if (rounded > chunk.capacity || chunk.recordings) return {}; + for (const auto& queue : queues) + if (!queue.second.completed(index)) return {}; + chunk.used = 0; + ++chunk.generation; + return reserve_upload_chunk(chunk, rounded); } diff --git a/tests/startup_address_console_check.py b/tests/startup_address_console_check.py index d36db0444..41ba62e26 100644 --- a/tests/startup_address_console_check.py +++ b/tests/startup_address_console_check.py @@ -8,6 +8,7 @@ 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 after completion, a new ring upload draws payload 18 over the right half 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,7 +218,7 @@ def gate_colour(payload): return bytes(((17 * payload + 3) & 255, (255 - 9 * payload) & 255, payload ^ 0x5a, 255)) -def check_gate(directory, consumer, backend, ring): +def check_gate(directory, consumer, backend, mode): """Uploads recorded while the queue cannot run must still hold their bytes when it does. The normal fixture records and discards a draw using payload 0 before the first submit retries that @@ -237,6 +238,12 @@ def check_gate(directory, consumer, backend, ring): " 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)} + ring = mode != "gate" + reuse = mode == "gate-ring-reuse" + if reuse: + modes["X2W_TEST_ADDRESS_UPLOAD_RING_REUSE"] = "1" + else: + os.environ.pop("X2W_TEST_ADDRESS_UPLOAD_RING_REUSE", None) if ring: modes["X2W_TEST_ADDRESS_UPLOAD_RING"] = "1" else: @@ -249,6 +256,8 @@ def check_gate(directory, consumer, backend, ring): raise AssertionError(f"gate: readback length {len(actual)}") first = gate_colour(0) last = bytes(4) if ring else gate_colour(GATE_PAYLOADS - 1) + if reuse: + last = gate_colour(GATE_PAYLOADS) wrong = {"left": 0, "right": 0} seen = set() for y in range(TARGET_H): @@ -263,13 +272,13 @@ def check_gate(directory, consumer, backend, ring): half = TARGET_W * TARGET_H // 2 if ring: if wrong["left"] or wrong["right"]: - raise AssertionError(f"gate-ring: {wrong} wrong pixels; expected payload 0 left and null view right") + raise AssertionError(f"{mode}: {wrong} wrong pixels, found {sorted(seen)[:4]}; expected {first.hex()} left, {last.hex()} right") if "x2w-draw upload ring reservation refused: no unused capacity" not in log: raise AssertionError("gate-ring: no upload reservation refusal") if "x2w-draw by-address uploads:" in log: raise AssertionError("gate-ring: the ring control retained upload buffers") print(f"{backend} gate, uploads from the shared ring: exhaustion refused; " - f"{half} left pixels hold payload 0 and {half} right pixels read the null view") + f"{half} left pixels hold payload 0 and {half} right pixels hold {last.hex()}") return 0 if wrong["left"] or wrong["right"]: raise AssertionError(f"gate: {wrong} wrong pixels, found {sorted(seen)[:4]}; expected {first.hex()} left, {last.hex()} right") @@ -282,12 +291,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: with tempfile.TemporaryDirectory() as temporary: - sys.exit(check_gate(Path(temporary), sys.argv[1], sys.argv[2], sys.argv[3] == "gate-ring")) + sys.exit(check_gate(Path(temporary), sys.argv[1], sys.argv[2], sys.argv[3])) for case in CASES: with tempfile.TemporaryDirectory() as temporary: result = check(Path(temporary), *sys.argv[1:3], case) diff --git a/tests/startup_stream_draw.cpp b/tests/startup_stream_draw.cpp index 633dd6940..26b37f639 100644 --- a/tests/startup_stream_draw.cpp +++ b/tests/startup_stream_draw.cpp @@ -602,7 +602,7 @@ 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 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. + // The last submit visits the completed uploads. In the ring-reuse case it also draws a new payload. const auto reached = [&](UINT64 value) { const auto deadline = GetTickCount64() + 60000; while (invoke(fence, 8) < value && GetTickCount64() < deadline) Sleep(1); @@ -610,6 +610,9 @@ int check_stream_draw(IDXGIAdapter* adapter, void* guest, void* pso, const char* }; if (!reached(payloads)) return 25; if (!next_recording()) return 35; + if (GetEnvironmentVariableW(L"X2W_TEST_ADDRESS_UPLOAD_RING_REUSE", nullptr, 0)) { + 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), payloads + 1))) || !reached(payloads + 1)) return 25; diff --git a/tests/upload_reservation_check.cpp b/tests/upload_reservation_check.cpp index 8a20ad436..9b84a3b4d 100644 --- a/tests/upload_reservation_check.cpp +++ b/tests/upload_reservation_check.cpp @@ -3,6 +3,8 @@ #include #include #include +#include +#include #include namespace { @@ -17,6 +19,51 @@ void check(bool ok, const char* what) constexpr std::uint64_t kAlign = 512; +struct TestFence { + std::uint64_t value = 0; + std::uint64_t GetCompletedValue() const { return value; } +}; + +void check_ring_reuse() +{ + // Four 64 MiB reservations fill the 256 MiB budget. The queues run independently. + constexpr auto bytes = max_upload_ring_bytes / 4; + std::unique_ptr storage(new unsigned char[max_upload_ring_bytes]); + std::array chunks{}; + UploadChunkMask recording = 0; + for (unsigned i = 0; i < chunks.size(); ++i) { + chunks[i] = {nullptr, storage.get() + i * bytes, bytes}; + const auto slice = reserve_upload_chunk(chunks[i], bytes); + check(slice.mapped != nullptr, "fill ring"); + chunks[i].hold(recording, i); + chunks[i].hold(recording, i); + check(chunks[i].recordings == 1, "one hold per recording and chunk"); + } + + TestFence a, b; + std::map> queues{{0, {&a, 1}}, {1, {&b, 1}}}; + for (auto& queue : queues) queue.second.submitted(recording, true); + a.value = b.value = 1; + auto& chunk = chunks[0]; + check(!reuse_upload_chunk(chunk, 0, bytes, queues).mapped, "closed list can be resubmitted"); + + ++queues[1].value; + queues[1].submitted(recording, true); + const auto submitted = recording; + discard_upload_chunks(recording, chunks.data()); // reset after the second submit on queue b + check(!reuse_upload_chunk(chunk, 0, bytes, queues).mapped, "latest submit on every queue must complete"); + b.value = UINT64_MAX; + check(!reuse_upload_chunk(chunk, 0, bytes, queues).mapped, "device removal is not completion"); + b.value = 2; + const auto next = reuse_upload_chunk(chunk, 0, bytes, queues); + check(next.mapped == storage.get() && next.offset == 0 && next.generation == 1, + "320 MiB cumulative reservations reuse completed storage"); + + queues[0].submitted(submitted, false); + queues[0].submitted(submitted, true); + check(!reuse_upload_chunk(chunk, 0, bytes, queues).mapped, "untracked submit prevents reuse"); +} + } // namespace int main() @@ -63,6 +110,7 @@ int main() storage_a[2 * kAlign - 1] == 0x5a && storage_a[2 * kAlign] == 0x7d, "existing reservations survive exhaustion"); + check_ring_reuse(); std::puts("upload_reservation_check: all checks passed"); return 0; }