diff --git a/CMakeLists.txt b/CMakeLists.txt index 9c407cdd21..050d92ead4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1267,6 +1267,7 @@ target_sources(startup_stream_consumer PRIVATE tests/startup_frame_copy.cpp) target_sources(startup_stream_consumer PRIVATE tests/startup_root_reset.cpp) target_sources(startup_stream_consumer PRIVATE tests/startup_memory_srv_diag.cpp) target_sources(startup_stream_consumer PRIVATE tests/startup_pixel_uav.cpp) +target_sources(startup_stream_consumer PRIVATE tests/startup_slot67_indirect.cpp tests/desktop_gpu.cpp) add_executable(startup_stream_depth tests/startup_stream_depth.cpp $) target_compile_features(startup_stream_depth PRIVATE cxx_std_17) @@ -4534,6 +4535,10 @@ if(EXISTS "${INTAKE_PYTHON}") add_test(NAME startup_compute_dispatch_texture_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_texture_check.py" "$" "${DXC_EXECUTABLE}" ${adapter}) + add_test(NAME startup_slot67_indirect_dispatch_${adapter} COMMAND "${INTAKE_PYTHON}" -B + "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_slot67_indirect_dispatch_check.py" "$" + "${DXC_EXECUTABLE}" ${adapter}) + set_tests_properties(startup_slot67_indirect_dispatch_${adapter} PROPERTIES TIMEOUT 120 SKIP_RETURN_CODE 77) add_test(NAME startup_compute_dispatch_heap_${adapter} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_CURRENT_SOURCE_DIR}/tests/startup_compute_dispatch_heap_check.py" "$" "${DXC_EXECUTABLE}" ${adapter}) diff --git a/docs/experiments.md b/docs/experiments.md index 9f7676bc80..a45b95422b 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -16755,6 +16755,25 @@ cmake --build --preset dev --target startup_stream_consumer ctest --preset dev --no-tests=error -R "^startup_compute_dispatch_" -V ``` +### GPU-written indirect Dispatch + +For a translated slot 67 pipeline with fixed-table raw buffers, command-list slot 61 accepts one rootless +Dispatch record in a placed argument buffer. It binds the same translated pipeline and descriptors as direct +Dispatch, transitions the argument buffer and records desktop `ExecuteIndirect`. The GPU reads the group counts. + +The fixture records a compute producer, a copy of the argument record and the indirect consumer on one list. +After the queue fence it checks both guard words, all three argument words, the input and all 320 output words. +Counts of 2 and 5 write exactly that many words. Direct Dispatch with the same bindings and counts must produce +the same outputs. Omitting the producer leaves the zero record and the output sentinel intact. Omitting the +translation preserves the output and reports the refusal. Other controls exercise multiple commands, a count +buffer, an out-of-range record and an argument buffer also bound as shader output. + +```powershell +cmake --build --preset release --target startup_stream_consumer +ctest --preset release --no-tests=error -j 1 -R '^startup_slot67_indirect_dispatch_(warp|hardware)$' -V +python -B tests/startup_slot67_indirect_dispatch_check.py mutation +``` + ### Entry values from a buffer descriptor A formatted buffer load passes the input's stride and word 3 as entry values (`udsrc stride `, `udsrc descword3 `), and a formatted buffer store (`buffer_store_format_d16_x`, and `buffer_store_format_xyzw` of #2530) passes the output's word 3, the upper half of word 1 and the record count (`uav_descword3`, `uav_stride`, `uav_numrecords`). At Dispatch the stand-in takes each from the descriptor words the same call binds the view from: the stride as the draw path takes it (from the hardware descriptor, or from the title's buffer view for a token), word 3 through the draw path's formatted-buffer check (a token's word is built from its view; a FORMAT the program does not decode refuses the dispatch with `a formatted input has no word 3 the program decodes`), and the output words unmasked, since the store helper checks the swizzle bits itself. A descriptor that is not bound refuses the dispatch as before; an entry value naming a texture slot leaves the pipeline untranslated, and so does any other source. diff --git a/src/startup_stubs/d3d12_compute_dispatch.inl b/src/startup_stubs/d3d12_compute_dispatch.inl index c039ff5f64..3024222bd0 100644 --- a/src/startup_stubs/d3d12_compute_dispatch.inl +++ b/src/startup_stubs/d3d12_compute_dispatch.inl @@ -165,14 +165,13 @@ const char* load_compute_translation(ComputeTranslation& tr) return nullptr; } -// True when the bound pipeline is a slot 67 placeholder with a request key: the call is then settled here -// (dispatched, or refused and logged). False leaves it to the desktop-pipeline decision of list_dispatch. -bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) +// Both callers have an open list and a slot 67 request. The indirect caller has checked the signature and argument range. +const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& dispatch) { auto* list = recording(self); Pass& pass = pass_of(self); - const u64 key = list && pass.pipeline ? pass.pipeline->own().compute_request_key : 0; - if (!key) return false; + const u64 key = pass.pipeline->own().compute_request_key; + const auto [x, y, z] = dispatch.groups; const char* reason = nullptr; LONG* counter = &compute_dispatches_refused; struct View { @@ -216,6 +215,10 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) for (std::size_t i = 0; i < count && !reason; ++i) { const bool output = i >= inputs; const ComputeTranslation::Slot slot = output ? tr->uavs[i - inputs] : tr->srvs[i]; + if (dispatch.signature && (slot.heap || slot.texture)) { + reason = "translated indirect Dispatch requires fixed-table raw buffers"; + break; + } std::uint32_t index = slot.a < 0 || slot.b < 0 ? 0 : pass.compute_constants.word(slot.a, slot.b); std::memset(words, 0, sizeof(words)); if (slot.word_param >= 0) { @@ -339,6 +342,9 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) views[i] = {placed.alias, offset, bytes, true}; std::memcpy(views[i].words, words, sizeof(views[i].words)); } + if (dispatch.argument) + for (std::size_t i = 0; i < count && !reason; ++i) + if (views[i].resource == dispatch.argument) reason = "the indirect argument buffer is also a bound shader resource"; // An entry value from a descriptor comes from the words its view was bound from in the loop above. std::uint32_t values[32] = {}; for (std::size_t i = 0; !reason && i < tr->uds.size(); ++i) { @@ -377,8 +383,9 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) InterlockedIncrement(counter); // Dispatches that arrive before the offline translation must not use up the lines for bind refusals. static LONG untranslated, refusals; - if (first_calls(counter == &compute_dispatches_refused ? refusals : untranslated, 16)) log("x2w-draw compute %016llx Dispatch(%u, %u, %u) refused: %s", key, x, y, z, reason); - return true; + if (!dispatch.signature && first_calls(counter == &compute_dispatches_refused ? refusals : untranslated, 16)) + log("x2w-draw compute %016llx Dispatch(%u, %u, %u) refused: %s", key, x, y, z, reason); + return reason; } const UINT n = static_cast(count); UINT first = static_cast(InterlockedExchangeAdd(&draw_heap_cursor, static_cast(n))) % draw_heap_size; @@ -425,7 +432,12 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) list->SetComputeRootSignature(tr->root.Get()); if (!tr->uds.empty()) list->SetComputeRoot32BitConstants(0, static_cast(tr->uds.size()), values, 0); if (n) list->SetComputeRootDescriptorTable(1, D3D12_GPU_DESCRIPTOR_HANDLE{draw_heap->GetGPUDescriptorHandleForHeapStart().ptr + u64{first} * draw_heap_increment}); - list->Dispatch(x, y, z); + if (dispatch.signature) { + require_state(self, dispatch.argument, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); + list->ExecuteIndirect(dispatch.signature, 1, dispatch.argument, dispatch.offset, nullptr, 0); + } else { + list->Dispatch(x, y, z); + } for (std::size_t i = inputs; i < count; ++i) { // a later dispatch on this list reads what this one wrote D3D12_RESOURCE_BARRIER barrier{}; barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; @@ -441,13 +453,13 @@ bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z) ++tr->translated; ReleaseSRWLockExclusive(&draw_lock); static LONG checks; // as translated draws do: the queue's execute drains the rest - if ((InterlockedIncrement(&checks) & 63) == 1) check_device("translated dispatch", 14); + if ((InterlockedIncrement(&checks) & 63) == 1) check_device("translated dispatch", dispatch.signature ? 61 : 14); InterlockedIncrement(&compute_dispatches_translated); static LONG logged; - if (first_calls(logged, 8)) + if (!dispatch.signature && first_calls(logged, 8)) log("x2w-draw compute %016llx Dispatch(%u, %u, %u) translated: entry [%x %x %x %x], %zu inputs, %zu outputs", key, x, y, z, values[0], values[1], values[2], values[3], inputs, count - inputs); - return true; + return nullptr; } // With the periodic totals: refused dispatches by the first refusal reason of their key, then every key by diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 96ff66bf4f..a8146d032c 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -2951,6 +2951,13 @@ struct IndirectIndexView { }; const char* draw_translated_indirect(Wrapper* self, ID3D12CommandSignature* signature, ID3D12Resource* argument, u64 offset, const IndirectIndexView& indices); +struct TranslatedDispatch { + D3D12_DISPATCH_ARGUMENTS groups{}; + ID3D12CommandSignature* signature = nullptr; + ID3D12Resource* argument = nullptr; + u64 offset = 0; +}; +const char* record_translated_dispatch(Wrapper* self, const TranslatedDispatch& dispatch); u64 known_pipeline_key(Wrapper* pipeline); namespace indirect_other_refusal_code { @@ -3053,6 +3060,7 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, const bool graphics = indexed || mesh || command == IndirectCommand::draw; Pass& pass = pass_of(self); refusal_pipeline = pass.pipeline; + const bool translated_compute = command == IndirectCommand::dispatch && pass.pipeline && pass.pipeline->own().compute_request_key; const bool translated = (command == IndirectCommand::draw || indexed) && pass.pipeline && !pass.pipeline->own().real && (pass.graphics_root || pass.deferred_root) && x2w_local::env_on("X2W_TRANSLATED_INDIRECT_DRAW"); u64 bytes = sig->own().indirect_bytes; @@ -3132,6 +3140,9 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, if (samples.Count != 1 || samples.Quality) return refuse("draw requires a single-sample render target", indirect_other, indirect_other_refusal_code::multisample_target); } + } else if (translated_compute) { + if (count != 1 || count_buffer || sig->own().signature_root) + return refuse("translated Dispatch requires one rootless command and no count buffer", indirect_compute_pipeline); } else if (!pass.compute_pipeline || !pass.compute_root) { return refuse("requires a desktop compute pipeline and root", indirect_compute_pipeline); } else if (sig->own().signature_root && sig->own().signature_root != pass.compute_root) { @@ -3158,6 +3169,12 @@ void __stdcall list_execute_indirect(Wrapper* self, void* signature, UINT count, if (!info || info->initial_state != D3D12_RESOURCE_STATE_COMMON) return refuse("argument buffer does not use COMMON state tracking", indirect_other, indirect_other_refusal_code::argument_not_common_state); auto* resource = static_cast(buffer->own().real); + if (translated_compute) { + const TranslatedDispatch dispatch{{}, static_cast(sig->own().real), resource, offset}; + if (const char* failure = record_translated_dispatch(self, dispatch)) return refuse(failure, indirect_compute_pipeline); + InterlockedIncrement64(&indirect_calls[indirect_forwarded][static_cast(kind)]); + return; + } IndirectIndexView index_view; if (indexed) { auto view = pass.ib; @@ -3837,15 +3854,17 @@ void __stdcall list_root_cbv(Wrapper* self, UINT parameter, u64 address) pass.root_address[parameter] = (address && readable_window(address, 1)) ? address : 0; } // List slot 14, Dispatch. Forwarded only with a desktop compute pipeline and root bound and group counts within the limit. -bool dispatch_translated(Wrapper* self, UINT x, UINT y, UINT z); void __stdcall list_dispatch(Wrapper* self, UINT x, UINT y, UINT z) { - if (dispatch_translated(self, x, y, z)) return; // a slot 67 placeholder never reaches the desktop decision auto* list = recording(self); + const Pass& pass = pass_of(self); + if (list && pass.pipeline && pass.pipeline->own().compute_request_key) { + record_translated_dispatch(self, {{x, y, z}}); + return; + } x2w_startup::ListDispatch request; request.list_open = list != nullptr; if (list) request.type = list->GetType(); - const Pass& pass = pass_of(self); request.compute_pipeline = pass.compute_pipeline; request.compute_root = pass.compute_root != nullptr; request.compute_root_has_arguments = pass.compute_root_has_arguments; diff --git a/tests/startup_indirect_dispatch.cpp b/tests/startup_indirect_dispatch.cpp index 090b97a1de..aab481fd37 100644 --- a/tests/startup_indirect_dispatch.cpp +++ b/tests/startup_indirect_dispatch.cpp @@ -5,7 +5,7 @@ #include #include "adapter_name_filter.h" -#include "desktop_gpu.h" +#include "startup_indirect_writer.h" #include #include @@ -116,22 +116,6 @@ Method slot(IUnknown* object, unsigned index) return reinterpret_cast((*reinterpret_cast(object))[index]); } -template -ComPtr native_object(ID3D12Device* device, ID3D12Device* guest, IUnknown* object) -{ - // SetPrivateDataInterface unwraps a guest argument before the call reaches the shared desktop device. - constexpr GUID key{0x10a62244, 0x1615, 0x4953, {0xa2, 0x52, 0xbe, 0x42, 0x35, 0x27, 0xa0, 0x61}}; - check(guest->SetPrivateDataInterface(key, object), "publish underlying object"); - ComPtr stored; - UINT bytes = sizeof(IUnknown*); - const HRESULT read = device->GetPrivateData(key, &bytes, stored.GetAddressOf()); - check(guest->SetPrivateDataInterface(key, nullptr), "clear underlying object"); - check(read, "retrieve underlying object"); - ComPtr result; - check(stored.As(&result), "query underlying object"); - return result; -} - ComPtr guest_pipeline(ID3D12Device* guest, ID3D12RootSignature* root) { const auto code = compile(constants ? "consume_constant_args" : "consume_args"); @@ -187,7 +171,7 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* root, I check(slot(guest, 133)(guest, static_cast(memory_backing.get()) + 4, &argument_desc, D3D12_RESOURCE_STATE_COMMON, nullptr, __uuidof(ID3D12Resource), reinterpret_cast(guest_arguments.GetAddressOf())), "place guest argument buffer"); - const auto arguments = native_object(device, guest, guest_arguments.Get()); + const auto arguments = indirect_native_object(device, guest, guest_arguments.Get()); auto result = make_buffer(device, result_bytes, D3D12_HEAP_TYPE_DEFAULT, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); void* memory = nullptr; @@ -205,7 +189,7 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* root, I reinterpret_cast(guest_list.GetAddressOf())), "create guest command list"); using Reset = HRESULT (WINAPI*)(IUnknown*, IUnknown*, void*, void*); check(slot(guest_list.Get(), 139)(guest_list.Get(), allocator.Get(), nullptr, nullptr), "reset guest command list"); - const auto native_list = native_object(device, guest, guest_list.Get()); + const auto native_list = indirect_native_object(device, guest, guest_list.Get()); auto* list = native_list.Get(); transition(list, arguments.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); list->CopyBufferRegion(arguments.Get(), 0, upload.Get(), 0, argument_bytes); @@ -216,9 +200,7 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* root, I if (writer) { transition(list, arguments.Get(), argument_state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); argument_state = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; - list->SetPipelineState(writer); - list->SetComputeRootUnorderedAccessView(0, arguments->GetGPUVirtualAddress()); - list->Dispatch(1, 1, 1); + record_indirect_writer(list, writer, arguments.Get()); } transition(list, arguments.Get(), argument_state, D3D12_RESOURCE_STATE_COPY_SOURCE); list->CopyBufferRegion(readback.Get(), 0, arguments.Get(), 0, argument_bytes); @@ -271,7 +253,7 @@ bool run(ID3D12Device* device, ID3D12Device* guest, ID3D12RootSignature* root, I ComPtr guest_queue; check(guest->CreateCommandQueue(&queue_desc, __uuidof(ID3D12CommandQueue), reinterpret_cast(guest_queue.GetAddressOf())), "create guest queue"); - const auto queue = native_object(device, guest, guest_queue.Get()); + const auto queue = indirect_native_object(device, guest, guest_queue.Get()); ComPtr gate; check(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&gate)), "create gate fence"); check(queue->Wait(gate.Get(), 1), "hold the guest queue on the gate"); diff --git a/tests/startup_indirect_writer.h b/tests/startup_indirect_writer.h new file mode 100644 index 0000000000..b853427d37 --- /dev/null +++ b/tests/startup_indirect_writer.h @@ -0,0 +1,26 @@ +#pragma once +#include "desktop_gpu.h" + +template +Microsoft::WRL::ComPtr indirect_native_object(ID3D12Device* device, ID3D12Device* guest, IUnknown* object) +{ + // SetPrivateDataInterface unwraps a guest argument before the call reaches the shared desktop device. + constexpr GUID key{0x10a62244, 0x1615, 0x4953, {0xa2, 0x52, 0xbe, 0x42, 0x35, 0x27, 0xa0, 0x61}}; + check(guest->SetPrivateDataInterface(key, object), "publish underlying object"); + Microsoft::WRL::ComPtr stored; + UINT bytes = sizeof(IUnknown*); + const HRESULT read = device->GetPrivateData(key, &bytes, stored.GetAddressOf()); + check(guest->SetPrivateDataInterface(key, nullptr), "clear underlying object"); + check(read, "retrieve underlying object"); + Microsoft::WRL::ComPtr result; + check(stored.As(&result), "query underlying object"); + return result; +} + +inline void record_indirect_writer(ID3D12GraphicsCommandList* list, ID3D12PipelineState* writer, + ID3D12Resource* arguments) +{ + list->SetPipelineState(writer); + list->SetComputeRootUnorderedAccessView(0, arguments->GetGPUVirtualAddress()); + list->Dispatch(1, 1, 1); +} diff --git a/tests/startup_slot67_indirect.cpp b/tests/startup_slot67_indirect.cpp new file mode 100644 index 0000000000..f3389e2a13 --- /dev/null +++ b/tests/startup_slot67_indirect.cpp @@ -0,0 +1,93 @@ +#include "startup_slot67_indirect.h" +#include "startup_indirect_writer.h" +#include "startup_stream_setup.h" +#include +#include +#include +#include + +extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); +using Microsoft::WRL::ComPtr; + +namespace { +using Record = std::array; +constexpr Record initial{0xa5a5a5a5, 0, 0, 0, 0x5a5a5a5a}; +constexpr UINT offset = sizeof(UINT); // guards on either side of the three-DWORD record +constexpr char producer[] = R"( +RWByteAddressBuffer args : register(u0); +cbuffer Size : register(b0) { uint groups; }; +[numthreads(1, 1, 1)] +void main() { args.Store3(4, uint3(groups, 1, 1)); } +)"; +StreamWord word(const void* value) { return reinterpret_cast(value); } +} + +void Slot67Indirect::prepare(IDXGIAdapter* adapter, void* guest_device, void* guest_list, void* backing, UINT groups) +{ + auto* guest = static_cast(guest_device); + ComPtr device; + check(D3D12XboxCreateDevice(adapter, nullptr, IID_PPV_ARGS(&device)), "open producer's desktop device"); + auto list = indirect_native_object(device.Get(), guest, static_cast(guest_list)); + const D3D12_RESOURCE_DESC desc{D3D12_RESOURCE_DIMENSION_BUFFER, 0, sizeof(initial), 1, 1, 1, + DXGI_FORMAT_UNKNOWN, {1, 0}, D3D12_TEXTURE_LAYOUT_ROW_MAJOR, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS}; + check(static_cast(invoke(guest, 133, word(backing), word(&desc), D3D12_RESOURCE_STATE_COMMON, 0, + word(&__uuidof(ID3D12Resource)), word(placed.GetAddressOf()))), "place indirect arguments"); + auto args = indirect_native_object(device.Get(), guest, placed.Get()); + upload = make_buffer(device.Get(), sizeof(initial), D3D12_HEAP_TYPE_UPLOAD, D3D12_RESOURCE_STATE_GENERIC_READ); + readback = make_buffer(device.Get(), sizeof(initial), D3D12_HEAP_TYPE_READBACK, D3D12_RESOURCE_STATE_COPY_DEST); + const D3D12_RANGE empty{0, 0}; + void* mapped = nullptr; + check(upload->Map(0, &empty, &mapped), "map zero dispatch record"); + std::memcpy(mapped, initial.data(), sizeof(initial)); + upload->Unmap(0, nullptr); + transition(list.Get(), args.Get(), D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + list->CopyBufferRegion(args.Get(), 0, upload.Get(), 0, sizeof(initial)); + auto state = D3D12_RESOURCE_STATE_COPY_DEST; + if (groups) { + D3D12_ROOT_PARAMETER params[2]{}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[1].Constants = {0, 0, 1}; + const D3D12_ROOT_SIGNATURE_DESC root_desc{2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + ComPtr blob, code; + check(D3D12SerializeRootSignature(&root_desc, D3D_ROOT_SIGNATURE_VERSION_1, &blob, nullptr), "serialize producer root"); + check(device->CreateRootSignature(0, blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(&root)), "create producer root"); + check(D3DCompile(producer, sizeof(producer) - 1, nullptr, nullptr, nullptr, "main", "cs_5_0", 0, 0, + &code, nullptr), "compile indirect producer"); + D3D12_COMPUTE_PIPELINE_STATE_DESC pso{}; + pso.pRootSignature = root.Get(); + pso.CS = {code->GetBufferPointer(), code->GetBufferSize()}; + check(device->CreateComputePipelineState(&pso, IID_PPV_ARGS(&writer)), "create indirect producer"); + transition(list.Get(), args.Get(), state, D3D12_RESOURCE_STATE_UNORDERED_ACCESS); + state = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + list->SetComputeRootSignature(root.Get()); + list->SetComputeRoot32BitConstant(1, groups, 0); + record_indirect_writer(list.Get(), writer.Get(), args.Get()); + } + transition(list.Get(), args.Get(), state, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->CopyBufferRegion(readback.Get(), 0, args.Get(), 0, sizeof(initial)); + transition(list.Get(), args.Get(), D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + D3D12_INDIRECT_ARGUMENT_DESC command{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH}; + const D3D12_COMMAND_SIGNATURE_DESC sig{sizeof(D3D12_DISPATCH_ARGUMENTS), 1, &command, 0}; + check(guest->CreateCommandSignature(&sig, nullptr, IID_PPV_ARGS(&signature)), "create guest dispatch signature"); +} + +void Slot67Indirect::execute(void* list, UINT commands, bool count_buffer, bool outside) const +{ + invoke(list, 61, word(signature.Get()), commands, word(placed.Get()), outside ? sizeof(initial) - sizeof(UINT) : offset, + count_buffer ? word(placed.Get()) : 0, count_buffer ? offset : 0); +} + +bool Slot67Indirect::check_record(UINT groups) const +{ + const D3D12_RANGE range{0, sizeof(initial)}, empty{0, 0}; + void* mapped = nullptr; + check(readback->Map(0, &range, &mapped), "map GPU argument readback after consumer fence"); + Record actual{}; + std::memcpy(actual.data(), mapped, sizeof(actual)); + readback->Unmap(0, &empty); + const Record expected{initial.front(), groups, groups ? 1u : 0u, groups ? 1u : 0u, initial.back()}; + std::printf("GPU argument record: %08x [%u,%u,%u] %08x\n", actual[0], actual[1], actual[2], actual[3], actual[4]); + std::fflush(stdout); + return actual == expected; +} diff --git a/tests/startup_slot67_indirect.h b/tests/startup_slot67_indirect.h new file mode 100644 index 0000000000..7aaba4a6aa --- /dev/null +++ b/tests/startup_slot67_indirect.h @@ -0,0 +1,16 @@ +#pragma once +#include +#include +#include + +// Keeps the producer, argument resource and signature alive until the consumer's queue fence. +struct Slot67Indirect { + Microsoft::WRL::ComPtr root; + Microsoft::WRL::ComPtr writer; + Microsoft::WRL::ComPtr placed, upload, readback; + Microsoft::WRL::ComPtr signature; + + void prepare(IDXGIAdapter* adapter, void* guest_device, void* guest_list, void* backing, UINT groups); + void execute(void* guest_list, UINT commands, bool count_buffer, bool outside) const; + bool check_record(UINT groups) const; +}; diff --git a/tests/startup_slot67_indirect_dispatch_check.py b/tests/startup_slot67_indirect_dispatch_check.py new file mode 100644 index 0000000000..c6f1db0490 --- /dev/null +++ b/tests/startup_slot67_indirect_dispatch_check.py @@ -0,0 +1,167 @@ +"""GPU-written Dispatch arguments consumed by a translated slot 67 pipeline on the same queue (#2492). + +`mutation` runs the device-free half: it builds the same 320-word expectation as `check()`, verifies that the +prefilled sentinel readback matches zero written words, that one flipped consumer word and one flipped sentinel are +both caught, and that the 2-group and 5-group references differ only at indices 2, 3 and 4. +""" +import os +from pathlib import Path +import subprocess +import sys +import tempfile + +import startup_gfx2hlsl_compute_check as C +from startup_compute_dispatch_check import dispatch, lines +from startup_compute_request_check import DATA, prepare +from startup_compute_translate_check import state_a +from startup_flat_param_check import assemble + + +# One thread per group. s7 is GroupID.x, s4 is a root constant, s6 is the buffer table. +SOURCE = """s_mov_b32 s10, s6 +s_mov_b32 s11, 0 +s_load_dwordx8 s[12:19], s[10:11], 0 +s_waitcnt lgkmcnt(0) +v_mov_b32 v3, s7 +v_lshlrev_b32 v4, 2, v3 +buffer_load_dword v5, v4, s[12:15], 0 offen +s_waitcnt vmcnt(0) +v_xor_b32 v5, s4, v5 +buffer_store_dword v5, v4, s[16:19], 0 offen +s_endpgm +""" +PROGRAM = bytes.fromhex('06038abe80038bbe05030cf4000000fa7fc08cbf0702067e82060834001030e004050380' + '703f8cbf040a0a3a001070e004050480000081bf') + + +def expected_words(written): + return [(((0x8b02a7f1 + i * 0x413b1) & C.MASK) ^ C.KEY) if i < written else C.SENTINEL + for i in range(C.WORDS)] + + +def compare_words(actual, expected): + """Return the differing indices, or one length entry when the readback size is wrong.""" + if len(actual) != len(expected): + return [('length', len(actual), len(expected))] + return [i for i, (word, want) in enumerate(zip(actual, expected)) if word != want] + + +def setup(directory, adapter): + cache, env = prepare(directory) + env.update(X2W_TEST_COMPUTE_ROOT=str(directory / 'compute_root'), X2W_D3D12_LIST_NOOP='1', X2W_D3D12_DEBUG='1') + if adapter == 'hardware': + env['X2W_TEST_DISPATCH_HARDWARE'] = '1' + else: + env.pop('X2W_TEST_DISPATCH_HARDWARE', None) + (directory / 'compute_root').write_bytes(C.root_blob(table_range=True)) + (directory / 'program').write_bytes(PROGRAM) + (directory / 'data').write_bytes(DATA) + (directory / 'state').write_bytes(state_a((1, 1, 1), C.USER7 | C.TGID_X)) + return cache, env + + +def check(directory, consumer, env, mode, groups, written, direct=False): + actual, result = dispatch(directory, consumer, env, ('dispatch-reference-' if direct else 'dispatch-indirect-') + mode) + print(result.stdout, end='') + expected = expected_words(written) + if direct: + assert len(lines(result, f'Dispatch({groups}, 1, 1) translated')) == 1, result.stderr[-2500:] + else: + assert f'[{groups},{int(bool(groups))},{int(bool(groups))}]' in result.stdout, result.stdout + wrong = compare_words(actual, expected) + if wrong: + first = wrong[0] + if isinstance(first, tuple): + raise AssertionError(f'{mode}: readback has {first[1]} words, expected {first[2]}\n' + f'{result.stderr[-2500:]}') + raise AssertionError(f'{mode}: word {first} got {actual[first]:08x}, expected {expected[first]:08x}, ' + f'{len(wrong)} differences\n{result.stderr[-2500:]}') + for line in lines(result, 'x2w-d3d12-debug '): + assert ' sev=0 ' not in line and ' sev=1 ' not in line, line + label = 'direct' if direct else 'indirect' + print(f'{label} {mode}: all {C.WORDS} words match ({written} written, {C.WORDS-written} sentinel)') + return result + + +def check_mutation(): + sentinel = [C.SENTINEL] * C.WORDS + assert len(sentinel) == 320 and C.WORDS == 320, (len(sentinel), C.WORDS) + assert compare_words(sentinel, expected_words(0)) == [], 'a fully sentinel readback must match zero writes' + for groups in (2, 5): + reference = expected_words(groups) + assert compare_words(list(reference), reference) == [], f'{groups}: reference must match itself' + assert all(word != C.SENTINEL for word in reference[:groups]), f'{groups}: consumer words use the sentinel' + for label, index in (('first consumer', 0), ('last consumer', groups - 1), + ('first sentinel', groups), ('last sentinel', C.WORDS - 1)): + mutated = list(reference) + mutated[index] ^= 1 + assert compare_words(mutated, reference) == [index], f'{groups}: {label} mutation was not isolated' + assert compare_words(reference[:-1], reference), f'{groups}: a short readback passed' + assert compare_words(reference + [C.SENTINEL], reference), f'{groups}: a long readback passed' + two, five = expected_words(2), expected_words(5) + differing = [i for i in range(C.WORDS) if two[i] != five[i]] + assert differing == [2, 3, 4], f'2/5 group references differ at {differing}' + assert compare_words(two, five) == [2, 3, 4] + print(f'mutation oracle: {C.WORDS} words, sentinel 0x{C.SENTINEL:08x}; consumer and sentinel flips detected; ' + '2/5 references differ at [2, 3, 4]') + + +def run_mutation(): + try: + check_mutation() + except AssertionError as error: + print(f'FAIL: {error}', file=sys.stderr) + return 1 + print('slot67 indirect mutation oracle: PASS (device-free)') + return 0 + + +def main(consumer, dxc, adapter): + with tempfile.TemporaryDirectory() as tmp: + directory = Path(tmp) + cache, env = setup(directory, adapter) + missing = check(directory, consumer, env, '5', 5, 0) + refused = lines(missing, 'refused') + assert any('no translation' in line for line in refused), missing.stderr[-2500:] + print(next(line for line in refused if 'no translation' in line)) + req, = cache.glob('req_*.c67') + key = req.stem.removeprefix('req_') + translated = subprocess.run([sys.executable, '-B', C.G.__file__, '--pending', cache], check=True, + capture_output=True, text=True, env=dict(os.environ, X2W_DXC=dxc)) + assert f'{key}: ok' in translated.stdout, translated.stdout + for groups in (2, 5, 0): + run = check(directory, consumer, env, str(groups) if groups else 'zero', groups, groups) + assert not lines(run, 'refused:'), run.stderr[-2500:] + if groups: + check(directory, consumer, env, str(groups), groups, groups, direct=True) + for mode, reason in (('multi', 'one rootless command'), ('counted', 'no count buffer'), + ('outside', 'outside a unique placed buffer'), ('output-alias', 'also a bound shader resource')): + run = check(directory, consumer, env, mode, 5, 0) + refusals = lines(run, 'ExecuteIndirect refused') + assert len(refusals) == 1 and reason in refusals[0], run.stderr[-2500:] + print(refusals[0]) + manifest = cache / f'{key}.txt' + text = manifest.read_text() + buf = 'srv 0 buf table 1 0' + assert text.count(buf) == 1 + for other in ('srv 0 tex2d table 1 0', 'srv 0 buf heap rootconst 0 0'): + manifest.write_text(text.replace(buf, other)) + run = check(directory, consumer, env, '5', 5, 0) + refusals = lines(run, 'ExecuteIndirect refused') + assert len(refusals) == 1 and 'requires fixed-table raw buffers' in refusals[0], run.stderr[-2500:] + print(refusals[0]) + layer = lines(run, 'x2w-d3d12 debug layer: ') + print('debug layer:', 'enabled' if layer and '0x00000000' in layer[0] else 'unavailable') + + +if __name__ == '__main__': + if len(sys.argv) == 2 and sys.argv[1] == 'mutation': + sys.exit(run_mutation()) + elif len(sys.argv) == 3 and sys.argv[1] == 'binary': + assert assemble(sys.argv[2], SOURCE) == PROGRAM + print('slot 67 indirect consumer matches LLVM gfx1013 assembly') + elif len(sys.argv) == 4 and sys.argv[3] in ('hardware', 'warp'): + main(*sys.argv[1:]) + else: + sys.exit('usage: startup_slot67_indirect_dispatch_check.py | ' + 'binary | mutation') diff --git a/tests/startup_stream_consumer.cpp b/tests/startup_stream_consumer.cpp index 9bc46e8502..ee78b1d5e0 100644 --- a/tests/startup_stream_consumer.cpp +++ b/tests/startup_stream_consumer.cpp @@ -15,6 +15,7 @@ #include "startup_stream_draw.h" #include "startup_stream_setup.h" +#include "startup_slot67_indirect.h" using Microsoft::WRL::ComPtr; extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); @@ -212,10 +213,12 @@ 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. -static int dispatch_slot67(void* device, const std::string& mode) +static int dispatch_slot67(IDXGIAdapter* adapter, void* device, const std::string& mode) { constexpr UINT words = 320; - auto* memory = static_cast(VirtualAlloc(nullptr, 0x20000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + const bool indirect = mode.rfind("dispatch-indirect-", 0) == 0; + const UINT groups = mode == "dispatch-indirect-zero" ? 0u : mode == "dispatch-indirect-2" ? 2u : 5u; + auto* memory = static_cast(VirtualAlloc(nullptr, indirect ? 0x30000 : 0x20000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); if (!memory) return 70; UINT* const buffers[2] = {memory, memory + 0x10000 / sizeof(UINT)}; for (UINT i = 0; i < words; ++i) { @@ -277,6 +280,11 @@ static int dispatch_slot67(void* device, const std::string& mode) FAILED(static_cast(invoke(device, 36, 0, 0, word(&__uuidof(ID3D12Fence)), word(&fence))))) return 72; const StreamWord cpu = invoke(heap, 9), gpu = invoke(heap, 10); if (!cpu || !gpu) return 73; + if (mode == "dispatch-indirect-output-alias") { + const UINT64 address = reinterpret_cast(memory) + 0x20000; + const UINT alias[4] = {static_cast(address), static_cast(address >> 32) | (4u << 16), 5, 0}; + std::memcpy(descriptors[1], alias, sizeof(alias)); + } std::memcpy(reinterpret_cast(cpu), descriptors, sizeof(descriptors)); const bool heap_record = mode.rfind("dispatch-heap", 0) == 0; if (heap_record) @@ -291,6 +299,8 @@ static int dispatch_slot67(void* device, const std::string& mode) invoke(list, 33, word(mode == "dispatch-wrong-root" ? slot67_other_root : slot67_root)); }; if (FAILED(static_cast(invoke(list, 139, word(allocator))))) return 74; + Slot67Indirect record; + if (indirect) record.prepare(adapter, device, list, memory + 0x20000 / sizeof(UINT), groups); bind(); if (mode.rfind("dispatch-sampled", 0) == 0 || mode == "dispatch-input-token") { const UINT width = mode == "dispatch-sampled-2x1" ? 2 : 1; @@ -358,7 +368,11 @@ static int dispatch_slot67(void* device, const std::string& mode) std::memcpy(reinterpret_cast(cpu + 96), view, sizeof(view)); } invoke(list, 35, 1, gpu); - if (mode != "dispatch-none") invoke(list, 14, 3, 2, 2); + if (indirect) record.execute(list, mode == "dispatch-indirect-multi" ? 2 : 1, + mode == "dispatch-indirect-counted", mode == "dispatch-indirect-outside"); + else if (mode == "dispatch-reference-2" || mode == "dispatch-reference-5") + invoke(list, 14, mode == "dispatch-reference-2" ? 2 : 5, 1, 1); + else if (mode != "dispatch-none") 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), 1)))) return 76; @@ -366,6 +380,7 @@ static int dispatch_slot67(void* device, const std::string& mode) if (GetTickCount64() >= deadline) return 78; Sleep(1); } + if (indirect && !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 x2w_d3d12_compute_census(); @@ -587,12 +602,12 @@ int main(int argc, char** argv) if (argc == 9 && std::strcmp(argv[4], "slot67") == 0 && std::strncmp(argv[8], "dispatch", 8) == 0) { if (!create_slot67(device, argv[5], argv[6], argv[7], argv[8])) return 10; if (std::strcmp(argv[8], "dispatch-retry") == 0) { - if (int rc = dispatch_slot67(device, "dispatch")) return rc; + if (int rc = dispatch_slot67(adapter.Get(), device, "dispatch")) return rc; std::puts("first slot 67 Dispatch fenced"); std::fflush(stdout); if (std::getchar() != '\n') return 2; } - return dispatch_slot67(device, argv[8]); + return dispatch_slot67(adapter.Get(), device, argv[8]); } if (argc == 9 && std::strcmp(argv[4], "slot67") == 0 && std::strncmp(argv[8], "texture", 7) == 0) return create_slot67(device, argv[5], argv[6], argv[7], argv[8]) ? texture_slot67(device, argv[8]) : 10;