diff --git a/core/libs/prx/libSceAgcDriver/CMakeLists.txt b/core/libs/prx/libSceAgcDriver/CMakeLists.txt index 168a820c5af1..048471d10b38 100644 --- a/core/libs/prx/libSceAgcDriver/CMakeLists.txt +++ b/core/libs/prx/libSceAgcDriver/CMakeLists.txt @@ -517,6 +517,9 @@ set(agcDriverSources ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/DeferredDestruction.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/MemoryAccounting.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/PlaceholderImages.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/CommandStream.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/CommandThunks.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/SealedBatch.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/Recorder.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/ParallelCompare.cpp ${CMAKE_CURRENT_SOURCE_DIR}/Graphics/src/ShaderInputState.cpp @@ -1213,3 +1216,20 @@ if(BUILD_TESTING) endif() target_sources(agc_driver_scattered_runs_tests PRIVATE tests/AllocationFailure.cpp) +add_library(agc_stream_guard_accepted OBJECT tests/StreamGuards.cpp) +target_include_directories(agc_stream_guard_accepted PRIVATE ${LIBS_INCLUDE_DIR} ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR}) +foreach(agcStreamGuard IN ITEMS owning_payload owning_array pointer_argument) + string(TOUPPER "${agcStreamGuard}" agcStreamGuardDefine) + add_library(agc_stream_guard_${agcStreamGuard} OBJECT EXCLUDE_FROM_ALL tests/StreamGuards.cpp) + target_include_directories(agc_stream_guard_${agcStreamGuard} PRIVATE ${LIBS_INCLUDE_DIR} ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR}) + target_compile_definitions(agc_stream_guard_${agcStreamGuard} PRIVATE APS5_GUARD_${agcStreamGuardDefine}) + add_test(NAME agc_stream_guard_${agcStreamGuard} COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target agc_stream_guard_${agcStreamGuard} --config $) +endforeach() +set_tests_properties(agc_stream_guard_owning_payload PROPERTIES PASS_REGULAR_EXPRESSION "payload is never destroyed, so it must be trivially destructible") +set_tests_properties(agc_stream_guard_owning_array PROPERTIES PASS_REGULAR_EXPRESSION "arrays are copied as bytes, so their elements must be trivially copyable") +set_tests_properties(agc_stream_guard_pointer_argument PROPERTIES PASS_REGULAR_EXPRESSION "pointer-to-const argument would be read") +set_tests_properties(agc_stream_guard_owning_payload agc_stream_guard_owning_array agc_stream_guard_pointer_argument PROPERTIES RESOURCE_LOCK agc_stream_guard_build TIMEOUT 300) +if(Python3_Interpreter_FOUND) + add_test(NAME agc_command_resolver_sites COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_command_resolver_sites.py) + set_tests_properties(agc_command_resolver_sites PROPERTIES TIMEOUT 20) +endif() diff --git a/core/libs/prx/libSceAgcDriver/Execution/include/PerformanceTrace.hpp b/core/libs/prx/libSceAgcDriver/Execution/include/PerformanceTrace.hpp index 07e61310ab38..cd2a48d9e314 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/include/PerformanceTrace.hpp +++ b/core/libs/prx/libSceAgcDriver/Execution/include/PerformanceTrace.hpp @@ -529,6 +529,9 @@ class TraceFormat { using Clock = std::chrono::steady_clock; static constexpr std::array WorkerBusyScopes{"Driver.Packet", "Driver.Suspend", "Driver.EndSubmission", "Driver.Rewind", "Driver.Completion", "Driver.FinisherDrain"}; static constexpr std::string_view WorkerWaitScope = "Driver.WorkerWait"; + static constexpr char EncoderPostScope[] = "Encoder.post"; + static constexpr char EncoderCommandScope[] = "Encoder.command"; + static constexpr char EncoderWaitScope[] = "Encoder.wait"; static constexpr std::string_view WorkerPrefix = "queue worker "; static constexpr std::size_t TopPhases = 8; @@ -695,6 +698,10 @@ class TraceFormat { std::map phaseCounts; std::map waitedPhases; std::map ownedCounts; + std::uint64_t encoderPosts = 0; + std::uint64_t encoderCommands = 0; + std::uint64_t encoderWaits = 0; + Clock::duration encoderWait{}; std::map graphicsCounts; bool dropped = summary.ownedDrawUnbound != 0; if (summary.ownedDrawUnbound != 0) ownedCounts["OwnedDraw.unbound"] = summary.ownedDrawUnbound; @@ -718,7 +725,12 @@ class TraceFormat { for (const auto& total : thread.totals) { const std::string_view scope = total.scope; if (total.stage == nullptr && std::find(WorkerBusyScopes.begin(), WorkerBusyScopes.end(), scope) != WorkerBusyScopes.end()) busy += total.length; - if (total.stage == nullptr && GraphicsTrackScope(scope)) graphicsCounts[std::string(scope)] += total.count; + if (total.stage == nullptr && scope == EncoderPostScope) encoderPosts += total.count; + else if (total.stage == nullptr && scope == EncoderCommandScope) encoderCommands += total.count; + else if (total.stage == nullptr && scope == EncoderWaitScope) { + encoderWaits += total.count; + encoderWait += total.length; + } else if (total.stage == nullptr && GraphicsTrackScope(scope)) graphicsCounts[std::string(scope)] += total.count; else if (scope.starts_with("OwnedDraw.") && total.stage == nullptr) ownedCounts[std::string(scope)] += total.count; else if (scope != WorkerWaitScope) { const auto name = Name(total.scope, total.stage); @@ -777,6 +789,7 @@ class TraceFormat { output += ':' + std::to_string(value); } output += '}'; + output += ",\"encoder\":{\"posts\":" + std::to_string(encoderPosts) + ",\"commands\":" + std::to_string(encoderCommands) + ",\"waits\":" + std::to_string(encoderWaits) + ",\"wait_ms_per_frame\":" + number(milliseconds(encoderWait) * perPresent) + '}'; output += ",\"graphics_track\":{"; bool firstGraphics = true; for (const auto& [name, value] : graphicsCounts) { diff --git a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp index e6bb2e238714..e546fdffbc0c 100644 --- a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp +++ b/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp @@ -885,11 +885,12 @@ struct VulkanDevice::State { template TFunction DeviceFunction(Graphics::FunctionName name) const { ++Graphics::DeviceProcLookups(); - auto function = reinterpret_cast(deviceProc(device, name.Value())); + auto function = deviceProc(device, name.Value()); if (function == nullptr) { throw std::runtime_error(std::string("Vulkan device function missing: ") + name.Value()); } - return function; + if (Graphics::IsCommandName(name.Value())) function = Graphics::CommandThunk(name.Value(), function, device); + return reinterpret_cast(function); } void CreateWorkgroupMemoryLayout() { @@ -1235,6 +1236,7 @@ struct VulkanDevice::State { } Graphics::ResetCheckpointSnapshots(); if (compileOnly && device != VK_NULL_HANDLE) { + Graphics::ForgetCommandDevice(device); reinterpret_cast(deviceProc(device, "vkDestroyDevice"))(device, nullptr); device = VK_NULL_HANDLE; } @@ -1348,6 +1350,7 @@ struct VulkanDevice::State { if (settlePool != VK_NULL_HANDLE) destroyPool(device, settlePool, nullptr); Graphics::DestroyRecordingPools(context); Graphics::DestroyDeferredObjects(device); + Graphics::ForgetCommandDevice(device); destroyDevice(device, nullptr); Graphics::MemoryAccounting::ForgetDevice(device); } @@ -2877,7 +2880,7 @@ VulkanDevice::VulkanDevice(const PresentationWindow* window, bool compileOnly) : if (!GuestMemory::GpuMutex().HeldByThisThread()) gpuLock.lock(); state->placeholderImages = std::make_unique(graphicsContext()); } - state->recorder = std::make_unique(graphicsContext(), state->timelineSemaphores); + state->recorder = std::make_unique(graphicsContext(), state->timelineSemaphores, state->functionsReady, family); state->recorder->Activate(); state->context = buildContext(); state->contextReady = true; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/CommandList.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/CommandList.hpp new file mode 100644 index 000000000000..bddbc707fc8d --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/CommandList.hpp @@ -0,0 +1,119 @@ +#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_COMMANDLIST_HPP +#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_COMMANDLIST_HPP + +#include +#include +#include +#include +#include + +#define APS5_COMMANDS(X) \ + X(CmdBeginQuery) \ + X(CmdBeginRenderPass) \ + X(CmdBeginRenderingKHR) \ + X(CmdBindDescriptorSets) \ + X(CmdBindIndexBuffer) \ + X(CmdBindPipeline) \ + X(CmdBindShadersEXT) \ + X(CmdBindVertexBuffers) \ + X(CmdBlitImage) \ + X(CmdClearAttachments) \ + X(CmdClearColorImage) \ + X(CmdClearDepthStencilImage) \ + X(CmdCopyBuffer) \ + X(CmdCopyBufferToImage) \ + X(CmdCopyImage) \ + X(CmdCopyImageToBuffer) \ + X(CmdCopyQueryPoolResults) \ + X(CmdDispatch) \ + X(CmdDispatchBase) \ + X(CmdDispatchIndirect) \ + X(CmdDraw) \ + X(CmdDrawIndexed) \ + X(CmdDrawIndexedIndirect) \ + X(CmdDrawIndexedIndirectCountKHR) \ + X(CmdDrawIndirect) \ + X(CmdDrawIndirectCountKHR) \ + X(CmdDrawMeshTasksEXT) \ + X(CmdDrawMeshTasksIndirectEXT) \ + X(CmdEndQuery) \ + X(CmdEndRenderPass) \ + X(CmdEndRenderingKHR) \ + X(CmdExecuteCommands) \ + X(CmdFillBuffer) \ + X(CmdPipelineBarrier) \ + X(CmdPushConstants) \ + X(CmdPushDescriptorSetKHR) \ + X(CmdResetQueryPool) \ + X(CmdResolveImage) \ + X(CmdSetCheckpointNV) \ + X(CmdSetColorWriteMaskEXT) \ + X(CmdSetCullMode) \ + X(CmdSetCullModeEXT) \ + X(CmdSetDepthBias) \ + X(CmdSetDepthBias2EXT) \ + X(CmdSetDepthBiasEnableEXT) \ + X(CmdSetDepthBounds) \ + X(CmdSetDepthBoundsTestEnable) \ + X(CmdSetDepthBoundsTestEnableEXT) \ + X(CmdSetDepthCompareOp) \ + X(CmdSetDepthCompareOpEXT) \ + X(CmdSetDepthTestEnable) \ + X(CmdSetDepthTestEnableEXT) \ + X(CmdSetDepthWriteEnable) \ + X(CmdSetDepthWriteEnableEXT) \ + X(CmdSetFrontFace) \ + X(CmdSetFrontFaceEXT) \ + X(CmdSetScissor) \ + X(CmdSetScissorWithCount) \ + X(CmdSetScissorWithCountEXT) \ + X(CmdSetStencilCompareMask) \ + X(CmdSetStencilOp) \ + X(CmdSetStencilOpEXT) \ + X(CmdSetStencilReference) \ + X(CmdSetStencilTestEnable) \ + X(CmdSetStencilTestEnableEXT) \ + X(CmdSetStencilWriteMask) \ + X(CmdSetViewport) \ + X(CmdSetViewportWithCount) \ + X(CmdSetViewportWithCountEXT) \ + X(CmdUpdateBuffer) \ + X(CmdWriteBufferMarkerAMD) \ + X(CmdWriteTimestamp) + +namespace AgcDriver::Graphics { + +enum class CommandId : std::uint16_t { +#define APS5_COMMAND_ID(name) name, + APS5_COMMANDS(APS5_COMMAND_ID) +#undef APS5_COMMAND_ID + Count +}; + +inline constexpr std::size_t CommandCount = static_cast(CommandId::Count); + +struct DeviceFunctions; + +struct CommandFunctions { +#define APS5_COMMAND_MEMBER(name) PFN_vk##name name = nullptr; + APS5_COMMANDS(APS5_COMMAND_MEMBER) +#undef APS5_COMMAND_MEMBER + const DeviceFunctions* listed = nullptr; +}; + +std::span CommandNames(); +bool IsCommandName(std::string_view name) noexcept; +CommandId CommandFor(std::string_view name); +void ResolveCommandFunctions(CommandFunctions& functions, VkDevice device, PFN_vkGetDeviceProcAddr resolve); +const CommandFunctions& StreamedCommands(); +PFN_vkVoidFunction CommandThunk(std::string_view name, PFN_vkVoidFunction real, VkDevice device = VK_NULL_HANDLE); +void ForgetCommandDevice(VkDevice device); +std::size_t CommandDeviceEntries(CommandId id) noexcept; +std::size_t CommandDeviceStorage(CommandId id) noexcept; +bool IsCommandThunk(std::string_view name, PFN_vkVoidFunction function) noexcept; +std::size_t CommandThunkSlots(CommandId id) noexcept; +bool CommandStreams(CommandId id) noexcept; + +} + +#endif diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/CommandStream.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/CommandStream.hpp new file mode 100644 index 000000000000..9c6cf41cd4ae --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/CommandStream.hpp @@ -0,0 +1,166 @@ +#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_COMMANDSTREAM_HPP +#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_COMMANDSTREAM_HPP + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace AgcDriver::Graphics { + +struct CommandFunctions; +class WorkBudget; +class CommandStream; + +class StreamMaterializer { +public: + virtual VkCommandBuffer Begin(CommandStream& stream) = 0; + +protected: + ~StreamMaterializer() = default; +}; + +struct Demotion { + const char* command = nullptr; + VkStructureType chained = VK_STRUCTURE_TYPE_MAX_ENUM; +}; + +bool OnReplayThread() noexcept; + +class ReplayThreadScope { +public: + ReplayThreadScope() noexcept; + ~ReplayThreadScope(); + ReplayThreadScope(const ReplayThreadScope&) = delete; + ReplayThreadScope& operator=(const ReplayThreadScope&) = delete; + +private: + bool previous; +}; + +class CommandStream { +public: + using Run = void (*)(const std::byte* payload, VkCommandBuffer commands, const CommandFunctions& functions); + static constexpr std::size_t RecordAlign = 16; + static constexpr std::size_t ChunkBytes = 64 * 1024; + static constexpr std::size_t Aligned(std::size_t bytes) { return (bytes + RecordAlign - 1) / RecordAlign * RecordAlign; } + + explicit CommandStream(const CommandFunctions& functions, WorkBudget* budget = nullptr, StreamMaterializer* materializer = nullptr); + ~CommandStream(); + CommandStream(const CommandStream&) = delete; + CommandStream& operator=(const CommandStream&) = delete; + + VkCommandBuffer Handle() const noexcept { return reinterpret_cast(reinterpret_cast(this) | HandleTag); } + static bool IsHandle(VkCommandBuffer commands) noexcept { return (reinterpret_cast(commands) & HandleTag) != 0; } + static CommandStream& From(VkCommandBuffer commands) noexcept { return *reinterpret_cast(reinterpret_cast(commands) & ~HandleTag); } + + template + static constexpr void CheckPlain() { + static_assert(((!std::is_pointer_v || !std::is_const_v>) && ...), "AGC graphics: a streamed command copies its arguments by value, so a pointer-to-const argument would be read after the caller's storage is gone; stream it with its pointed-to data"); + } + + template + void Emplace(Run run, const Payload& payload, std::span... arrays) { + static_assert((std::is_trivially_copyable_v && ...), "AGC graphics: a streamed command's arrays are copied as bytes, so their elements must be trivially copyable; keep owners in batch storage"); + static_assert(std::is_trivially_destructible_v, "AGC graphics: a streamed command's payload is never destroyed, so it must be trivially destructible; keep owners in batch storage"); + static_assert(std::is_nothrow_copy_constructible_v, "AGC graphics: a streamed command's payload must be built without throwing"); + const std::size_t bytes = Aligned(sizeof(Payload)) + (Aligned(sizeof(T) * arrays.size()) + ... + 0); + EmplaceBytes(run, bytes, [&](std::byte* at) noexcept { + new (at) Payload(payload); + at += Aligned(sizeof(Payload)); + ((at = copyInto(at, arrays)), ...); + }); + } + + template + void EmplaceBytes(Run run, std::size_t payloadBytes, Fill&& fill) { + static_assert(std::is_nothrow_invocable_v, "AGC graphics: a streamed command's bytes must be written without throwing"); + payloadBytes = Aligned(payloadBytes); + if (auto* at = reserve(run, payloadBytes); at != nullptr) [[likely]] { + fill(at); + ops.fetch_add(1, std::memory_order_relaxed); + return; + } + auto scratch = pastCap(payloadBytes); + fill(scratch.get()); + runPastCap(run, scratch.get()); + } + + const CommandFunctions& Functions() const noexcept { return functions; } + VkCommandBuffer Materialized() const noexcept { return materialized; } + const Demotion& DemotedBy() const noexcept { return demotion; } + VkCommandBuffer Demote(const char* command, VkStructureType chained = VK_STRUCTURE_TYPE_MAX_ENUM); + void Poison(std::exception_ptr reason) noexcept; + bool Poisoned() const noexcept { return poisoned.load(std::memory_order_acquire); } + std::exception_ptr Reason() const; + void Seal() noexcept { sealed.store(true, std::memory_order_release); } + bool Sealed() const noexcept { return sealed.load(std::memory_order_acquire); } + std::uint64_t Ops() const noexcept { return ops.load(std::memory_order_relaxed); } + std::size_t Bytes() const noexcept { return bytes.load(std::memory_order_relaxed); } + std::size_t Charged() const noexcept { return charged; } + std::size_t Cap() const noexcept { return cap; } + void ReleaseMemory() noexcept; + + template + void ForEach(Visit&& visit) const { + for (const auto& chunk : chunks) { + std::size_t offset = 0; + while (offset < chunk->used) { + Record record; + std::memcpy(&record, chunk->bytes.get() + offset, sizeof(Record)); + visit(record.run, chunk->bytes.get() + offset + RecordHeader); + offset += RecordHeader + record.bytes; + } + } + } + +private: + static constexpr std::uintptr_t HandleTag = 1; + struct Record { + Run run; + std::size_t bytes; + }; + static constexpr std::size_t RecordHeader = (sizeof(Record) + RecordAlign - 1) / RecordAlign * RecordAlign; + struct Chunk { + explicit Chunk(std::size_t capacity); + std::unique_ptr bytes; + std::size_t capacity; + std::size_t used = 0; + }; + std::byte* reserve(Run run, std::size_t payloadBytes); + std::unique_ptr pastCap(std::size_t payloadBytes); + void runPastCap(Run run, const std::byte* payload); + template + static std::byte* copyInto(std::byte* at, std::span array) noexcept { + if (!array.empty()) std::memcpy(at, array.data(), sizeof(T) * array.size()); + return at + Aligned(sizeof(T) * array.size()); + } + const CommandFunctions& functions; + WorkBudget* budget; + StreamMaterializer* materializer; + VkCommandBuffer materialized = VK_NULL_HANDLE; + Demotion demotion; + std::vector> chunks; + std::size_t charged = 0; + std::size_t cap; + std::atomic ops{0}; + std::atomic bytes{0}; + std::atomic sealed{false}; + std::atomic poisoned{false}; + mutable std::mutex reasonMutex; + std::exception_ptr reason; +}; + +void Replay(const CommandStream& stream, VkCommandBuffer target, const CommandFunctions& real); + +} + +#endif diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp index b5dc76f34500..7068d2ed42af 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Context.hpp @@ -7,6 +7,7 @@ #include #include #include "prx/libc/include/PrimedSharedMutex.hpp" +#include "prx/libSceAgcDriver/Graphics/include/CommandList.hpp" #include #include #include @@ -17,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -183,6 +185,8 @@ struct DeviceFunctions { PFN_vkCmdCopyBufferToImage cmdCopyBufferToImage = nullptr; PFN_vkCmdCopyImageToBuffer cmdCopyImageToBuffer = nullptr; PFN_vkCmdClearColorImage cmdClearColorImage = nullptr; + PFN_vkCmdBeginQuery cmdBeginQuery = nullptr; + PFN_vkCmdEndQuery cmdEndQuery = nullptr; PFN_vkUpdateDescriptorSets updateDescriptorSets = nullptr; PFN_vkAllocateDescriptorSets allocateDescriptorSets = nullptr; PFN_vkGetFenceStatus getFenceStatus = nullptr; @@ -367,17 +371,49 @@ struct Context { VertexBufferFormats* vertexFormats = nullptr; template - TFunction Function(FunctionName name) const { - return lookup(name.Value()); + TFunction Function(FunctionName name, std::source_location where = std::source_location::current()) const { + return lookup(name.Value(), where); } // The table's entry point, or a per-call lookup while the table is absent or lacks it. + const DeviceFunctions* Table() const { return functions; } + template TFunction Resolved(TFunction DeviceFunctions::*member, FunctionName name) const { - if (functions != nullptr && functions->*member != nullptr) return functions->*member; + if (const auto* table = Table(); table != nullptr && table->*member != nullptr) return table->*member; return lookup(name.Value()); } + const CommandFunctions* BatchFor(const CommandFunctions* batch) const noexcept { + return batch != nullptr && batch->listed == Table() ? batch : nullptr; + } + + template + TFunction ForBatch(const CommandFunctions* batch, TFunction CommandFunctions::*command, TFunction DeviceFunctions::*member, FunctionName name) const { + if (batch != nullptr && batch->*command != nullptr) return batch->*command; + return Resolved(member, name); + } + + template + TFunction ForBatch(const CommandFunctions* batch, TFunction CommandFunctions::*command, TrackedFunction DeviceFunctions::*member, const char* name) const { + if (batch != nullptr && batch->*command != nullptr) return batch->*command; + return tracked(member, name); + } + + void OverlayCommands(CommandFunctions& target, const CommandFunctions& real) const { + const auto* table = Table(); + if (table == nullptr) return; + forEachOverlay([&](auto command, auto member, const char* name) { overlay(target.*command, real.*command, entry(*table, member), name); }); + } + + bool OverlayMatches(const DeviceFunctions& snapshot) const { + const auto* table = Table(); + if (table == nullptr) return true; + bool same = true; + forEachOverlay([&](auto, auto member, const char*) { same = same && entry(*table, member) == entry(snapshot, member); }); + return same; + } + class ComputeBinder { public: void operator()(VkCommandBuffer commands, VkPipeline pipeline) const { @@ -505,17 +541,64 @@ struct Context { friend void FillDeviceFunctions(const Context& context, DeviceFunctions& functions); template - TFunction lookup(const char* name) const { + TFunction lookup(const char* name, [[maybe_unused]] std::source_location where = std::source_location::current()) const { Require(deviceProc != nullptr, "missing Vulkan device function resolver"); ++DeviceProcLookups(); - const auto function = reinterpret_cast(deviceProc(device, name)); + const auto function = deviceProc(device, name); if (function == nullptr) throw std::runtime_error(std::string("AGC graphics: missing Vulkan function: ") + name); - return function; + if (IsCommandName(name)) return reinterpret_cast(CommandThunk(name, function, device)); + return reinterpret_cast(function); + } + + template + static void forEachOverlay(TVisit&& visit) { + visit(&CommandFunctions::CmdBindDescriptorSets, &DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets"); + visit(&CommandFunctions::CmdBindIndexBuffer, &DeviceFunctions::cmdBindIndexBuffer, "vkCmdBindIndexBuffer"); + visit(&CommandFunctions::CmdBindPipeline, &DeviceFunctions::cmdBindPipeline, "vkCmdBindPipeline"); + visit(&CommandFunctions::CmdBindVertexBuffers, &DeviceFunctions::cmdBindVertexBuffers, "vkCmdBindVertexBuffers"); + visit(&CommandFunctions::CmdDraw, &DeviceFunctions::cmdDraw, "vkCmdDraw"); + visit(&CommandFunctions::CmdDrawIndexed, &DeviceFunctions::cmdDrawIndexed, "vkCmdDrawIndexed"); + visit(&CommandFunctions::CmdDrawIndexedIndirect, &DeviceFunctions::cmdDrawIndexedIndirect, "vkCmdDrawIndexedIndirect"); + visit(&CommandFunctions::CmdDrawIndirect, &DeviceFunctions::cmdDrawIndirect, "vkCmdDrawIndirect"); + visit(&CommandFunctions::CmdSetColorWriteMaskEXT, &DeviceFunctions::cmdSetColorWriteMask, "vkCmdSetColorWriteMaskEXT"); + visit(&CommandFunctions::CmdSetCullModeEXT, &DeviceFunctions::cmdSetCullMode, "vkCmdSetCullModeEXT"); + visit(&CommandFunctions::CmdSetDepthBias, &DeviceFunctions::cmdSetDepthBias, "vkCmdSetDepthBias"); + visit(&CommandFunctions::CmdSetDepthBiasEnableEXT, &DeviceFunctions::cmdSetDepthBiasEnable, "vkCmdSetDepthBiasEnableEXT"); + visit(&CommandFunctions::CmdSetDepthBounds, &DeviceFunctions::cmdSetDepthBounds, "vkCmdSetDepthBounds"); + visit(&CommandFunctions::CmdSetDepthBoundsTestEnableEXT, &DeviceFunctions::cmdSetDepthBoundsTestEnable, "vkCmdSetDepthBoundsTestEnableEXT"); + visit(&CommandFunctions::CmdSetDepthCompareOpEXT, &DeviceFunctions::cmdSetDepthCompareOp, "vkCmdSetDepthCompareOpEXT"); + visit(&CommandFunctions::CmdSetDepthTestEnableEXT, &DeviceFunctions::cmdSetDepthTestEnable, "vkCmdSetDepthTestEnableEXT"); + visit(&CommandFunctions::CmdSetDepthWriteEnableEXT, &DeviceFunctions::cmdSetDepthWriteEnable, "vkCmdSetDepthWriteEnableEXT"); + visit(&CommandFunctions::CmdSetFrontFaceEXT, &DeviceFunctions::cmdSetFrontFace, "vkCmdSetFrontFaceEXT"); + visit(&CommandFunctions::CmdSetScissor, &DeviceFunctions::cmdSetScissor, "vkCmdSetScissor"); + visit(&CommandFunctions::CmdSetStencilCompareMask, &DeviceFunctions::cmdSetStencilCompareMask, "vkCmdSetStencilCompareMask"); + visit(&CommandFunctions::CmdSetStencilOpEXT, &DeviceFunctions::cmdSetStencilOp, "vkCmdSetStencilOpEXT"); + visit(&CommandFunctions::CmdSetStencilReference, &DeviceFunctions::cmdSetStencilReference, "vkCmdSetStencilReference"); + visit(&CommandFunctions::CmdSetStencilTestEnableEXT, &DeviceFunctions::cmdSetStencilTestEnable, "vkCmdSetStencilTestEnableEXT"); + visit(&CommandFunctions::CmdSetStencilWriteMask, &DeviceFunctions::cmdSetStencilWriteMask, "vkCmdSetStencilWriteMask"); + visit(&CommandFunctions::CmdSetViewport, &DeviceFunctions::cmdSetViewport, "vkCmdSetViewport"); + } + + template + static TFunction entry(const DeviceFunctions& table, TFunction DeviceFunctions::*member) { + return table.*member; + } + + template + static TFunction entry(const DeviceFunctions& table, TrackedFunction DeviceFunctions::*member) { + return (table.*member).function; + } + + template + void overlay(TFunction& target, TFunction real, TFunction listed, const char* name) const { + if (listed == nullptr) return; + if (real != nullptr && (listed == real || CommandThunk(name, reinterpret_cast(real), device) == reinterpret_cast(listed))) return; + target = listed; } template TFunction tracked(TrackedFunction DeviceFunctions::*member, const char* name) const { - if (functions != nullptr && (functions->*member).function != nullptr) return (functions->*member).function; + if (const auto* table = Table(); table != nullptr && (table->*member).function != nullptr) return (table->*member).function; return lookup(name); } }; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp index 8f4c98bd5acd..e4f8f1585209 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/Recorder.hpp @@ -2,6 +2,8 @@ #define CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_RECORDER_HPP #include "prx/libSceAgcDriver/Graphics/include/BarrierBatch.hpp" +#include "prx/libSceAgcDriver/Graphics/include/CommandList.hpp" +#include "prx/libSceAgcDriver/Graphics/include/SealedBatch.hpp" #include "prx/libSceAgcDriver/Graphics/include/Context.hpp" #include "prx/libSceAgcDriver/Graphics/include/PassHazards.hpp" #include "prx/libSceAgcDriver/Execution/include/Mutex.hpp" @@ -13,6 +15,7 @@ #include #include #include +#include #include #include #include @@ -21,12 +24,14 @@ #include #include #include +#include #include #include #include #include #include #include +#include namespace AgcDriver::Graphics { @@ -66,9 +71,10 @@ class CommandState { CommandState(const CommandState&) = delete; CommandState& operator=(const CommandState&) = delete; - void Begin(VkCommandBuffer commands, bool suppress = true); + void Begin(VkCommandBuffer commands, bool suppress = true, const CommandFunctions* functions = nullptr); void Invalidate() noexcept; VkCommandBuffer Commands() const { return commands; } + const CommandFunctions* FunctionsFor(VkCommandBuffer recording, const Context& context) const noexcept { return recording == commands ? context.BatchFor(functions) : nullptr; } bool Known(Slot slot) const { return (valid & Mask(slot)) != 0; } VkPipeline BoundPipeline() const { return pipelineKnown ? pipeline : VK_NULL_HANDLE; } void BindPipeline(const Context& context, VkPipeline pipeline, std::uint32_t dynamicSlots); @@ -111,6 +117,7 @@ class CommandState { void applyFaces(Slot first, VkStencilFaceFlags faces, std::array CommandState::*field, const TValue& value, TEmit emit); VkCommandBuffer commands = VK_NULL_HANDLE; + const CommandFunctions* functions = nullptr; std::uint32_t trackable = 0; std::uint32_t valid = 0; std::uint32_t overwritten = 0; @@ -151,10 +158,10 @@ class CommandState { // up to serial S" WITHOUT the mutex (WaitSerial), because the monotonic value cannot be reset or // recycled the way the pooled batch fences are, and afterwards run the completions under the mutex // (FinishUpTo). Without timeline semaphores callers use the locked Sync as before. -class Recorder { +class Recorder : private StreamMaterializer { public: // `timelineSemaphores`: the device enabled VK_KHR_timeline_semaphore (WaitSerial is usable). - explicit Recorder(const Context& context, bool timelineSemaphores = false); + explicit Recorder(const Context& context, bool timelineSemaphores = false, bool deferredBatches = false, std::uint32_t queueFamily = 0, WorkBudget::Limits limits = {}); ~Recorder(); Recorder(const Recorder&) = delete; Recorder& operator=(const Recorder&) = delete; @@ -166,7 +173,7 @@ class Recorder { // so a dispatch, fill or copy whose leading barrier asks for a subset of them may skip it // (the [barriers] line counts the merges). The call clears the mask (whatever the caller // records is assumed uncovered until it marks); a new batch starts uncovered. - VkCommandBuffer Commands(VkAccessFlags* coveredAccess = nullptr); + VkCommandBuffer Commands(VkAccessFlags* coveredAccess = nullptr, std::source_location where = std::source_location::current()); // After a trailing barrier with ALL_COMMANDS as its destination stage: `access` is its // destination access mask. void MarkCovered(VkAccessFlags access); @@ -177,9 +184,9 @@ class Recorder { static constexpr std::uint64_t RunAccessWritten = 1, RunAccessImage = 2, RunAccessBuffer = 4; using RunAccess = std::array; static std::uint32_t PeekUnorderedDispatch(); - VkCommandBuffer OverlapCommands(std::uint32_t queueKey, std::span owners, std::span accesses, VkAccessFlags* coveredAccess, bool& overlapped); + VkCommandBuffer OverlapCommands(std::uint32_t queueKey, std::span owners, std::span accesses, VkAccessFlags* coveredAccess, bool& overlapped, std::source_location where = std::source_location::current()); void DeferDispatchBarrier(std::uint32_t queueKey, std::span owners, std::span accesses); - VkCommandBuffer RunCommands(std::uint32_t queueKey, const void* owner, std::span accesses, bool& inRun, VkAccessFlags* coveredAccess); + VkCommandBuffer RunCommands(std::uint32_t queueKey, const void* owner, std::span accesses, bool& inRun, VkAccessFlags* coveredAccess, std::source_location where = std::source_location::current()); void OpenBatch() { ensureOpen(); } bool RunOpen() const { return open != nullptr && open->deferredDispatchQueue != 0; } void AfterRun(std::function work); @@ -213,8 +220,8 @@ class Recorder { void FlushKeyStores(); void FlushKeyStoresOverlapping(std::uint64_t address, std::size_t bytes) { if (HasQueuedKeyStores() && QueuedKeyStoreOverlaps(address, bytes)) FlushKeyStores(); } bool Recording() const { return open != nullptr; } - bool Idle() const { return open == nullptr && inFlight.empty(); } - std::uint64_t OpenSerial() const { return submissions + 1; } + bool Idle() const { return open == nullptr && sealedBatches.empty() && inFlight.empty(); } + std::uint64_t OpenSerial() const { return sealedThrough + 1; } std::uint64_t CompletedThrough() const { return inFlight.empty() ? submissions : inFlight.front()->serial - 1; } // Whether recorded work still has completion actions (write-backs the CPU must see) to run. bool HasCompletions() const; @@ -245,6 +252,7 @@ class Recorder { std::shared_ptr UploadScratchBuffer(UploadScratch kind, std::size_t bytes); static constexpr VkPipelineStageFlags UploadScratchReuseStages = VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT; std::size_t OpenKeptBytes() const { return open != nullptr ? open->keptBytes : 0; } + std::size_t OpenKeptCount() const { return open != nullptr ? open->kept.size() : 0; } void FlushDeferredReleases(); static constexpr std::size_t KeptBytesBudget = std::size_t{512} << 20u; void BoundKeptBytes(); @@ -379,6 +387,9 @@ class Recorder { std::optional DescribePendingWrite(std::uint64_t address, std::size_t bytes) const; // Ends and submits the open batch without waiting. void Submit(); + std::uint64_t Seal(); + std::uint64_t QueueSealed(); + std::size_t SealedBatches() const noexcept { return sealedBatches.size(); } void HoldNextSubmit(VkSemaphore semaphore, std::uint64_t value); bool SubmitHeld() const; // Submits the open batch and returns the serial of the newest submitted batch (0 when nothing was @@ -648,6 +659,34 @@ class Recorder { // there must not have a publish recorded for it (UnitShadow), see SyncThrough. static bool InCompletion(); void Activate(); + class UnwindPoison { + public: + explicit UnwindPoison(Recorder& recorder) : recorder(recorder), exceptions(std::uncaught_exceptions()) {} + ~UnwindPoison() { + if (std::uncaught_exceptions() > exceptions) recorder.poisonOpen(); + } + UnwindPoison(const UnwindPoison&) = delete; + UnwindPoison& operator=(const UnwindPoison&) = delete; + + private: + Recorder& recorder; + int exceptions; + }; + UnwindPoison UnwindGuard() { return UnwindPoison(*this); } + struct StreamStatistics { + std::uint64_t deferred = 0; + std::uint64_t direct = 0; + std::uint64_t refused = 0; + std::uint64_t demoted = 0; + std::uint64_t poisoned = 0; + std::uint64_t replayed = 0; + std::uint64_t replayFailed = 0; + }; + StreamStatistics StreamCounts() const; + std::vector> Demotions() const; + std::string StreamReport() const; + std::uint64_t StreamOps() const { return open != nullptr && open->stream != nullptr ? open->stream->Ops() : 0; } + bool Deferred() const { return open != nullptr && open->stream != nullptr && open->stream->Materialized() == VK_NULL_HANDLE; } // APS5_PROFILE_DRAW: syncs by source (0 device idle, 1 CPU access to pending writes, 2 CPU read // after a recorded store, 3 address-based dispatch, 4 other). Contract: the call announces the // source for the Sync/SyncThrough this thread makes NEXT, which consumes it (a sync without a @@ -801,13 +840,19 @@ class Recorder { }; static_assert(std::is_nothrow_move_constructible_v && std::is_nothrow_move_assignable_v); struct Batch { + std::unique_ptr stream; + std::shared_ptr sealed; + VkCommandBuffer real = VK_NULL_HANDLE; std::uint64_t sampleBatch = 0; std::vector foldedSamples; VkCommandBuffer commands = VK_NULL_HANDLE; + const CommandFunctions* functions = nullptr; CommandState graphicsState; + VkCommandPool pool = VK_NULL_HANDLE; VkFence fence = VK_NULL_HANDLE; std::vector> kept; std::size_t keptBytes = 0; + bool unwound = false; std::unordered_set keptOwners; std::array, static_cast(UploadScratch::Count)> uploadScratch; std::vector> completions; @@ -835,6 +880,10 @@ class Recorder { // Submission number (1-based): identifies a batch after its allocation may have been reused. std::uint64_t serial = 0; std::uint64_t predictedSerial = 0; + std::uint64_t sealedSerial = 0; + VkSemaphore hold = VK_NULL_HANDLE; + std::uint64_t holdValue = 0; + std::int64_t labelSince = std::numeric_limits::min(); AgcDriver::FaultToken firstToken = 0; AgcDriver::FaultToken lastToken = 0; std::uint64_t traceId = 0; @@ -980,12 +1029,12 @@ class Recorder { void beginSegment(Batch& batch); void endSegment(Batch& batch); void copySegments(VkCommandBuffer commands, std::uint32_t count); + void reserveSampleRestore(const Batch& batch); void retireSegments(std::uint32_t count); void recordQueuedDumps(VkCommandBuffer commands, std::span writes); void dispatchDumps(VkCommandBuffer commands, std::uint32_t firstDump, std::uint32_t dumps, std::uint32_t firstSegment, std::uint32_t lastSegment); void foldSegments(); void foldQueuedDumps(VkCommandBuffer commands, std::span writes, std::size_t first, std::size_t end, std::uint32_t& dumpIndex, std::uint32_t& consumed); - void reserveSampleRestore(const Batch& batch); std::vector pendingSamples; std::uint64_t sampleBatches = 0; bool countingSamples = false; @@ -999,7 +1048,6 @@ class Recorder { VkDescriptorSetLayout boundChangedCopySetLayout = VK_NULL_HANDLE; VkPipelineLayout boundChangedCopyLayout = VK_NULL_HANDLE; VkPipeline boundChangedCopyPipeline = VK_NULL_HANDLE; - PFN_vkCmdPushDescriptorSetKHR cmdPushChangedCopySet = nullptr; int sampleCounterState = 0; std::unique_ptr sampleCounter; VkPipelineLayout sampleLayout = VK_NULL_HANDLE; @@ -1038,8 +1086,8 @@ class Recorder { PFN_vkCmdPushConstants cmdPushConstants = nullptr; PFN_vkCmdDispatch cmdDispatch = nullptr; template - TFunction function(TFunction resolved, FunctionName name) const { - return resolved != nullptr ? resolved : context.Function(name); + TFunction function(TFunction resolved, FunctionName name, std::source_location where = std::source_location::current()) const { + return resolved != nullptr ? resolved : context.Function(name, where); } VkResult fenceStatus(VkFence fence) const { return function(getFenceStatus, "vkGetFenceStatus")(context.device, fence); } bool gpuDone(const Batch& batch) const; @@ -1058,7 +1106,7 @@ class Recorder { // form, toward the host only); returns whether the batch's host-read barrier was included. bool closeStoreRun(bool atSubmit = false); // Ends the render pass a draw left open (vkCmdEndRenderPass, the pass's trailing barrier). - void endOpenRenderPass(PassBreak by, bool barrier = true); + void endOpenRenderPass(PassBreak by, bool barrier = true, std::source_location where = std::source_location::current()); // Records the queued key stores as one run (`forWriter`: before a command writing, reading or // labelling over one, not at Submit). void recordKeyStores(bool forWriter); @@ -1071,6 +1119,11 @@ class Recorder { void finish(std::unique_ptr batch, bool wait, int source, bool releaseNow = false, bool publishActions = true); void DrainValidationFailure(); void discard(std::unique_ptr batch) noexcept; + std::unique_ptr sealOpen(); + std::uint64_t queue(std::unique_ptr batch); + void unqueued(std::unique_ptr batch, std::exception_ptr reason) noexcept; + void markLabel(Batch& batch); + void refreshLabelMark() noexcept; void removeLabels(Batch& batch); void release(Batch& batch) noexcept; static bool overlaps(const Batch& batch, std::uint64_t address, std::uint64_t end); @@ -1147,6 +1200,34 @@ class Recorder { static std::size_t retentionHash(const void* object) { return static_cast((reinterpret_cast(object) >> 4u) * 0x9e3779b97f4a7c15ull >> 32u); } + VkCommandBuffer Begin(CommandStream& stream) override; + VkCommandBuffer allocateBegun(); + std::unique_ptr makeExecutor(); + bool defers() const; + void poisonOpen() noexcept; + std::exception_ptr failureOf(const Batch& batch) const; + void overlayListed(); + void noteDemotion(const Demotion& demotion); + VkCommandBuffer live() { return open->commands; } + CommandFunctions realCommands; + DeviceFunctions listedFunctions; + CommandFunctions directCommands; + CommandFunctions streamedCommands; + bool realResolved = false; + FailureLatch latch; + WorkBudget budget; + std::unique_ptr executor; + std::uint32_t queueFamily = 0; + bool deferring = false; + std::atomic deferredBatches{0}; + std::atomic directBatches{0}; + std::atomic demotedBatches{0}; + std::atomic poisonedBatches{0}; + const std::exception_ptr unwoundDrawReason = std::make_exception_ptr(std::runtime_error("AGC graphics: a draw threw while recording, so the batch holds part of it")); + std::atomic replayedBatches{0}; + std::atomic failedReplays{0}; + mutable std::mutex demotionMutex; + std::map demotions; std::uint64_t passGeneration = 0; std::vector> holdKept; std::uint64_t holdKeptSerial = 0; @@ -1157,6 +1238,8 @@ class Recorder { std::vector finishing; mutable std::shared_ptr published; std::uint64_t submissions = 0; + std::uint64_t sealedThrough = 0; + std::deque> sealedBatches; std::size_t inFlightKeptBytes = 0; std::uint64_t writeNoteCount = 0; std::shared_ptr drawUpload; diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/RuntimeSwitches.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/RuntimeSwitches.hpp index f64773699229..1eb02e7fb5da 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/include/RuntimeSwitches.hpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/RuntimeSwitches.hpp @@ -30,6 +30,11 @@ enum class RuntimeSwitch : std::size_t { NoStagePoolReuse, IndexInPlaceBehindWriter, WideLibraryKeys, + NoRecordEncoder, + NoAdaptiveEncoder, + QuiescedSegments, + DirectBatches, + NoStreamedPushDescriptors, NoWideTableCopyHle, NoSampledLookupMemo, NoDccMipFastClear, @@ -46,6 +51,7 @@ namespace RuntimeSwitches { const char* Name(RuntimeSwitch id); bool Set(RuntimeSwitch id); void Assign(RuntimeSwitch id, bool set); +std::uint64_t Generation(); std::optional Find(std::string_view name); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/include/SealedBatch.hpp b/core/libs/prx/libSceAgcDriver/Graphics/include/SealedBatch.hpp new file mode 100644 index 000000000000..d9eab6685713 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Graphics/include/SealedBatch.hpp @@ -0,0 +1,215 @@ +#ifndef CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_SEALEDBATCH_HPP +#define CORE_LIBS_PRX_LIBSCEAGCDRIVER_GRAPHICS_INCLUDE_SEALEDBATCH_HPP + +#include "prx/libSceAgcDriver/Graphics/include/CommandStream.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace AgcDriver::Graphics { + +struct BatchCancelled : std::runtime_error { + BatchCancelled() : std::runtime_error("AGC graphics: the batch was cancelled after an earlier batch failed or the device shut down") {} +}; + +struct RecordingShutDown : std::runtime_error { + RecordingShutDown() : std::runtime_error("AGC graphics: the recorder shut down while a wait was pending") {} +}; + +class FailureLatch { +public: + static constexpr std::uint64_t NoSerial = std::numeric_limits::max(); + bool Fail(std::uint64_t serial, std::exception_ptr error) noexcept; + bool LoseDevice(std::exception_ptr error) noexcept; + void Shutdown() noexcept; + bool Failed() const noexcept { return failedSerial.load(std::memory_order_acquire) != NoSerial; } + bool DeviceLost() const noexcept { return deviceLost.load(std::memory_order_acquire); } + bool ShuttingDown() const noexcept { return shuttingDown.load(std::memory_order_acquire); } + std::uint64_t FailedSerial() const noexcept { return failedSerial.load(std::memory_order_acquire); } + std::exception_ptr Error() const; + void ThrowFor(std::uint64_t serial) const; + +private: + std::atomic failedSerial{NoSerial}; + std::atomic deviceLost{false}; + std::atomic shuttingDown{false}; + mutable std::mutex mutex; + std::exception_ptr error; +}; + +template +void WaitObservingFailure(const FailureLatch& latch, std::uint64_t serial, std::chrono::nanoseconds slice, WaitSlice&& waitSlice) { + while (!waitSlice(slice)) latch.ThrowFor(serial); +} + +class WorkBudget { +public: + struct Limits { + std::size_t encodingBatches = 4; + std::size_t outstandingBatches = 16; + std::size_t outstandingBytes = 64u << 20; + }; + enum class Mode : std::uint8_t { Deferred, Direct }; + explicit WorkBudget(Limits limits) : limits(limits) {} + Mode Choose() const noexcept; + void Open(const FailureLatch& latch, std::uint64_t serial, std::chrono::nanoseconds slice = std::chrono::milliseconds(1)); + bool TryOpen() noexcept; + void Sealed() noexcept; + void ReplayReleased() noexcept; + void Charge(std::size_t bytes) noexcept; + void Retired(std::size_t bytes) noexcept; + void Uncharge(std::size_t bytes) noexcept; + std::size_t StreamCap() const noexcept { return limits.outstandingBytes / std::max(limits.outstandingBatches, 1); } + bool OverBytes() const noexcept { return bytes.load(std::memory_order_relaxed) >= limits.outstandingBytes; } + std::size_t Encoding() const noexcept { return encoding.load(std::memory_order_relaxed); } + std::size_t Outstanding() const noexcept { return outstanding.load(std::memory_order_relaxed); } + std::size_t OutstandingBytes() const noexcept { return bytes.load(std::memory_order_relaxed); } + std::uint64_t RoomWaits() const noexcept { return roomWaits.load(std::memory_order_relaxed); } + std::uint64_t Refusals() const noexcept { return refusals.load(std::memory_order_relaxed); } + +private: + bool room() const noexcept { return outstanding.load(std::memory_order_relaxed) < limits.outstandingBatches && bytes.load(std::memory_order_relaxed) < limits.outstandingBytes; } + Limits limits; + std::atomic encoding{0}; + std::atomic outstanding{0}; + std::atomic bytes{0}; + std::atomic roomWaits{0}; + std::atomic refusals{0}; + std::mutex mutex; + std::condition_variable retired; +}; + +class SealedBatch { +public: + enum class Outcome : std::uint8_t { Pending, Encoded, ReplayFailed, Cancelled, Submitted, SubmitFailed, DeviceLost }; + SealedBatch(std::uint64_t serial, CommandStream& stream, const CommandFunctions& real, FailureLatch& latch, WorkBudget* budget = nullptr); + ~SealedBatch(); + SealedBatch(const SealedBatch&) = delete; + SealedBatch& operator=(const SealedBatch&) = delete; + + std::uint64_t Serial() const noexcept { return serial; } + const CommandStream& Stream() const noexcept { return stream; } + const CommandFunctions& Real() const noexcept { return real; } + + bool Superseded() const noexcept; + bool Claim() noexcept; + void Encoded(VkCommandBuffer commands, std::uint32_t worker) noexcept; + void Failed(std::exception_ptr reason, VkCommandBuffer commands, std::uint32_t worker) noexcept; + void Cancel() noexcept; + + void AwaitReplayReleased() noexcept; + VkCommandBuffer Await(); + void Returned(VkResult result) noexcept; + void NotSubmitted() noexcept; + void GpuDone() noexcept; + void DeviceIdleAfterLoss() noexcept; + + bool ReplayReleased() const noexcept { return replay.load(std::memory_order_acquire) == Released; } + bool SubmitReturned() const noexcept { return submitReturned.load(std::memory_order_acquire); } + bool GpuReleased() const noexcept { return gpuReleased.load(std::memory_order_acquire); } + bool Retirable() const noexcept { return ReplayReleased() && SubmitReturned() && GpuReleased(); } + Outcome Result() const noexcept { return outcome.load(std::memory_order_acquire); } + std::exception_ptr Error() const; + VkCommandBuffer Commands() const noexcept { return commands; } + std::uint32_t Worker() const noexcept { return worker; } + +private: + enum ReplayState : std::uint32_t { Unclaimed, Claimed, Released }; + void releaseReplay(Outcome result, std::exception_ptr reason, VkCommandBuffer buffer, std::uint32_t by) noexcept; + void maybeRetire() noexcept; + std::uint64_t serial; + CommandStream& stream; + const CommandFunctions& real; + FailureLatch& latch; + WorkBudget* budget; + std::size_t charged = 0; + std::atomic replay{Unclaimed}; + std::atomic cancelRequested{false}; + std::atomic outcome{Outcome::Pending}; + std::atomic submitReturned{false}; + std::atomic gpuReleased{false}; + std::atomic retiredCharge{false}; + VkCommandBuffer commands = VK_NULL_HANDLE; + std::uint32_t worker = 0; + mutable std::mutex errorMutex; + std::exception_ptr error; +}; + +class CommandBufferPool { +public: + virtual VkCommandBuffer Begin() = 0; + virtual void End(VkCommandBuffer commands) = 0; + virtual void Recycle(VkCommandBuffer commands) noexcept = 0; + virtual ~CommandBufferPool() = default; +}; + +struct ReplayEntryPoints { + VkDevice device = VK_NULL_HANDLE; + PFN_vkCreateCommandPool createPool = nullptr; + PFN_vkDestroyCommandPool destroyPool = nullptr; + PFN_vkAllocateCommandBuffers allocate = nullptr; + PFN_vkFreeCommandBuffers free = nullptr; + PFN_vkBeginCommandBuffer begin = nullptr; + PFN_vkEndCommandBuffer end = nullptr; +}; + +std::unique_ptr BorrowReplayPool(const ReplayEntryPoints& entry, VkCommandPool pool); +std::unique_ptr CreateReplayPool(const ReplayEntryPoints& entry, std::uint32_t queueFamily); + +class ReplayExecutor { +public: + virtual void Execute(std::shared_ptr batch) noexcept = 0; + virtual void Retire(VkCommandBuffer commands, std::uint32_t worker) noexcept = 0; + virtual void Shutdown() noexcept = 0; + virtual ~ReplayExecutor() = default; +}; + +class InlineExecutor final : public ReplayExecutor { +public: + explicit InlineExecutor(std::unique_ptr pool) : pool(std::move(pool)) {} + void Execute(std::shared_ptr batch) noexcept override; + void Retire(VkCommandBuffer commands, std::uint32_t worker) noexcept override; + void Shutdown() noexcept override {} + +private: + std::unique_ptr pool; +}; + +class SingleExecutor final : public ReplayExecutor { +public: + using PoolFactory = std::function()>; + explicit SingleExecutor(PoolFactory makePool); + ~SingleExecutor() override; + void Execute(std::shared_ptr batch) noexcept override; + void Retire(VkCommandBuffer commands, std::uint32_t worker) noexcept override; + void Shutdown() noexcept override; + std::uint64_t Replayed() const noexcept { return replayed.load(std::memory_order_relaxed); } + +private: + void run(PoolFactory makePool) noexcept; + std::mutex mutex; + std::condition_variable wake; + std::deque> queue; + std::vector recycled; + bool stopping = false; + std::atomic replayed{0}; + std::thread thread; +}; + +void ReplayBatch(SealedBatch& batch, CommandBufferPool& pool, std::uint32_t worker) noexcept; + +} + +#endif diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/CommandStream.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/CommandStream.cpp new file mode 100644 index 000000000000..0644fa39e079 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/CommandStream.cpp @@ -0,0 +1,136 @@ +#include "prx/libSceAgcDriver/Graphics/include/CommandStream.hpp" +#include "prx/libSceAgcDriver/Graphics/include/CommandList.hpp" +#include "prx/libSceAgcDriver/Graphics/include/SealedBatch.hpp" +#include "prx/libc/include/HostThreadSlot.hpp" +#include +#include +#include +#include +#include +#include + +namespace AgcDriver::Graphics { + +namespace { + +struct ReplayThreadTag; +using ReplayThreadSlot = HostThreadSlot; + +[[noreturn]] void refuseReplayThreadAppend() { + std::fputs("AGC graphics: a command was appended to a stream from a replay thread; replay reads only its stream and the real functions\n", stderr); + std::fflush(stderr); + std::abort(); +} + +} + +bool OnReplayThread() noexcept { + return ReplayThreadSlot::Get(); +} + +ReplayThreadScope::ReplayThreadScope() noexcept : previous(ReplayThreadSlot::Get()) { + ReplayThreadSlot::Set(true); +} + +ReplayThreadScope::~ReplayThreadScope() { + ReplayThreadSlot::Set(previous); +} + +CommandStream::Chunk::Chunk(std::size_t capacity) : bytes(new std::byte[capacity]), capacity(capacity) {} + +CommandStream::CommandStream(const CommandFunctions& functions, WorkBudget* budget, StreamMaterializer* materializer) : functions(functions), budget(budget), materializer(materializer), cap(budget != nullptr ? budget->StreamCap() : SIZE_MAX) {} + +CommandStream::~CommandStream() = default; + +std::byte* CommandStream::reserve(Run run, std::size_t payloadBytes) { + if (OnReplayThread()) refuseReplayThreadAppend(); + try { + if (Sealed()) throw std::logic_error("AGC graphics: a command was appended to a sealed stream"); + if (materialized != VK_NULL_HANDLE) throw std::logic_error("AGC graphics: a command was appended to a stream after it was demoted to a command buffer"); + if (Poisoned()) std::rethrow_exception(Reason()); + const std::size_t need = RecordHeader + payloadBytes; + if (chunks.empty() || chunks.back()->capacity - chunks.back()->used < need) { + const std::size_t capacity = std::max(ChunkBytes, need); + if (capacity > cap - std::min(charged, cap)) return nullptr; + chunks.push_back(std::make_unique(capacity)); + charged += capacity; + if (budget != nullptr) budget->Charge(capacity); + } + auto& chunk = *chunks.back(); + auto* at = chunk.bytes.get() + chunk.used; + const Record record{run, payloadBytes}; + std::memcpy(at, &record, sizeof(Record)); + chunk.used += need; + bytes.fetch_add(need, std::memory_order_relaxed); + return at + RecordHeader; + } catch (...) { + Poison(std::current_exception()); + throw; + } +} + +std::unique_ptr CommandStream::pastCap(std::size_t payloadBytes) { + Demote("stream byte cap"); + try { + return std::unique_ptr(new std::byte[std::max(payloadBytes, RecordAlign)]); + } catch (...) { + Poison(std::current_exception()); + throw; + } +} + +void CommandStream::runPastCap(Run run, const std::byte* payload) { + run(payload, materialized, functions); +} + +void CommandStream::Poison(std::exception_ptr why) noexcept { + { + std::lock_guard lock(reasonMutex); + if (reason == nullptr) reason = why; + } + poisoned.store(true, std::memory_order_release); +} + +std::exception_ptr CommandStream::Reason() const { + std::lock_guard lock(reasonMutex); + return reason; +} + +VkCommandBuffer CommandStream::Demote(const char* command, VkStructureType chained) { + if (materialized != VK_NULL_HANDLE) return materialized; + if (OnReplayThread()) refuseReplayThreadAppend(); + try { + if (Sealed()) throw std::logic_error("AGC graphics: a sealed stream was demoted to a command buffer"); + if (Poisoned()) std::rethrow_exception(Reason()); + if (materializer == nullptr) throw std::logic_error(std::string("AGC graphics: ") + command + " needs a command buffer, and this stream has no way to demote to one"); + const auto target = materializer->Begin(*this); + { + const ReplayThreadScope scope; + ForEach([&](Run run, const std::byte* payload) { run(payload, target, functions); }); + } + materialized = target; + demotion = Demotion{command, chained}; + chunks.clear(); + if (budget != nullptr) budget->Uncharge(charged); + charged = 0; + return target; + } catch (...) { + Poison(std::current_exception()); + throw; + } +} + +void CommandStream::ReleaseMemory() noexcept { + chunks.clear(); +} + +void Replay(const CommandStream& stream, VkCommandBuffer target, const CommandFunctions& real) { + if (!stream.Sealed()) throw std::logic_error("AGC graphics: a stream was replayed before it was sealed"); + if (stream.Poisoned()) std::rethrow_exception(stream.Reason()); + if (stream.Materialized() != VK_NULL_HANDLE) throw std::logic_error("AGC graphics: a stream demoted to a command buffer was replayed"); + if (CommandStream::IsHandle(target)) throw std::logic_error("AGC graphics: a stream was replayed into a stream handle instead of a command buffer"); + const ReplayThreadScope scope; + stream.ForEach([&](CommandStream::Run run, const std::byte* payload) { run(payload, target, real); }); +} + +} diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/CommandThunks.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/CommandThunks.cpp new file mode 100644 index 000000000000..89e6c5631bad --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/CommandThunks.cpp @@ -0,0 +1,850 @@ +#include "prx/libSceAgcDriver/Graphics/include/CommandList.hpp" +#include "prx/libSceAgcDriver/Graphics/include/CommandStream.hpp" +#include "prx/libSceAgcDriver/Graphics/include/RuntimeSwitches.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace AgcDriver::Graphics { + +namespace { + +constexpr std::size_t ThunkSlots = 8; + +constexpr std::array Names{ +#define APS5_COMMAND_NAME(name) "vk" #name, + APS5_COMMANDS(APS5_COMMAND_NAME) +#undef APS5_COMMAND_NAME +}; + +constexpr std::size_t indexOf(CommandId id) { + return static_cast(id); +} + +std::array, ThunkSlots>, CommandCount> realSlots{}; +std::mutex slotMutex; + +struct DeviceEntry { + std::atomic version{0}; + std::atomic key{nullptr}; + std::atomic real{nullptr}; + DeviceEntry* next = nullptr; +}; + +void rewrite(DeviceEntry& entry, const void* key, PFN_vkVoidFunction real) noexcept { + const auto version = entry.version.load(std::memory_order_relaxed); + entry.version.store(version + 1, std::memory_order_relaxed); + entry.real.store(real, std::memory_order_release); + entry.key.store(key, std::memory_order_release); + entry.version.store(version + 2, std::memory_order_release); +} + +std::array, CommandCount> deviceEntries{}; +std::array deviceEntryStorage{}; +std::atomic keyedDevices{0}; + +const void* dispatchKey(const void* handle) noexcept { + const void* key = nullptr; + std::memcpy(&key, handle, sizeof(key)); + return key; +} + +[[noreturn]] void noDeviceEntry(const char* command) { + throw std::logic_error(std::string("AGC graphics: ") + command + " was called on a command buffer whose device registered no entry point for it"); +} + +PFN_vkVoidFunction deviceReal(std::size_t id, const void* key, const char* command) { + for (auto* entry = deviceEntries[id].load(std::memory_order_acquire); entry != nullptr; entry = entry->next) { + for (;;) { + const auto before = entry->version.load(std::memory_order_acquire); + const auto held = entry->key.load(std::memory_order_acquire); + const auto real = entry->real.load(std::memory_order_acquire); + if ((before & 1) != 0 || entry->version.load(std::memory_order_relaxed) != before) continue; + if (held == key) return real; + break; + } + } + noDeviceEntry(command); +} + +template +struct Command; + +#define APS5_COMMAND_TRAIT(name) \ + template<> \ + struct Command { \ + using Pfn = PFN_vk##name; \ + static constexpr auto member = &CommandFunctions::name; \ + static constexpr const char* text = "vk" #name; \ + }; +APS5_COMMANDS(APS5_COMMAND_TRAIT) +#undef APS5_COMMAND_TRAIT + +template +const T& unpack(const std::byte* payload) { + return *std::launder(reinterpret_cast(payload)); +} + +template +const T* arrayAt(const std::byte*& at, std::uint32_t count) { + const auto* values = count != 0 ? reinterpret_cast(at) : nullptr; + at += CommandStream::Aligned(sizeof(T) * count); + return values; +} + +template +const std::byte* afterHeader(const std::byte* payload) { + return payload + CommandStream::Aligned(sizeof(Header)); +} + +constexpr VkStructureType Unchained = VK_STRUCTURE_TYPE_MAX_ENUM; + +VkStructureType chainOf(const void* next) { + return next != nullptr ? static_cast(next)->sType : Unchained; +} + +template +VkStructureType chained(const T* values, std::uint32_t count) { + for (std::uint32_t index = 0; index < count; ++index) { + if (values[index].pNext != nullptr) return chainOf(values[index].pNext); + } + return Unchained; +} + +template +inline constexpr bool PlainArguments = ((!std::is_pointer_v || !std::is_const_v>) && ...); + +template +void runPlain(const std::byte* payload, VkCommandBuffer target, const CommandFunctions& functions) { + std::apply([&](const A&... arguments) { (functions.*Command::member)(target, arguments...); }, unpack>(payload)); +} + +template +void direct(CommandStream& stream, VkStructureType chain, A... arguments) { + const auto target = stream.Demote(Command::text, chain); + (stream.Functions().*Command::member)(target, arguments...); +} + +template +struct PlainCommand : std::false_type {}; + +template +struct PlainCommand : std::bool_constant> {}; + +struct Copies { + static constexpr bool Streams = true; +}; + +template +struct Streamer { + static constexpr bool Streams = PlainCommand::Pfn>::value; + template + static void Append(CommandStream& stream, A... arguments) { + if constexpr (PlainArguments) stream.Emplace(&runPlain, std::tuple(arguments...)); + else direct(stream, Unchained, arguments...); + } +}; + +struct RangeHeader { + std::uint32_t first; + std::uint32_t count; +}; + +template +struct RangeStreamer : Copies { + static void Append(CommandStream& stream, std::uint32_t first, std::uint32_t count, const T* values) { + stream.Emplace([](const std::byte* payload, VkCommandBuffer target, const CommandFunctions& functions) { + const auto header = unpack(payload); + const auto* at = afterHeader(payload); + (functions.*Command::member)(target, header.first, header.count, arrayAt(at, header.count)); + }, RangeHeader{first, count}, std::span(values, count)); + } +}; + +template<> +struct Streamer : RangeStreamer {}; +template<> +struct Streamer : RangeStreamer {}; +template<> +struct Streamer : RangeStreamer {}; + +template +struct CountStreamer : Copies { + static void Append(CommandStream& stream, std::uint32_t count, const T* values) { + stream.Emplace([](const std::byte* payload, VkCommandBuffer target, const CommandFunctions& functions) { + const auto header = unpack(payload); + const auto* at = afterHeader(payload); + (functions.*Command::member)(target, header.count, arrayAt(at, header.count)); + }, RangeHeader{0, count}, std::span(values, count)); + } +}; + +template<> +struct Streamer : CountStreamer {}; +template<> +struct Streamer : CountStreamer {}; +template<> +struct Streamer : CountStreamer {}; +template<> +struct Streamer : CountStreamer {}; + +struct BindSetsHeader { + VkPipelineBindPoint bindPoint; + VkPipelineLayout layout; + std::uint32_t firstSet; + std::uint32_t sets; + std::uint32_t offsets; +}; + +template<> +struct Streamer : Copies { + static void Append(CommandStream& stream, VkPipelineBindPoint bindPoint, VkPipelineLayout layout, std::uint32_t firstSet, std::uint32_t sets, const VkDescriptorSet* descriptorSets, std::uint32_t offsets, const std::uint32_t* dynamicOffsets) { + stream.Emplace([](const std::byte* payload, VkCommandBuffer target, const CommandFunctions& functions) { + const auto header = unpack(payload); + const auto* at = afterHeader(payload); + const auto* descriptorSets = arrayAt(at, header.sets); + const auto* dynamicOffsets = arrayAt(at, header.offsets); + functions.CmdBindDescriptorSets(target, header.bindPoint, header.layout, header.firstSet, header.sets, descriptorSets, header.offsets, dynamicOffsets); + }, BindSetsHeader{bindPoint, layout, firstSet, sets, offsets}, std::span(descriptorSets, sets), std::span(dynamicOffsets, offsets)); + } +}; + +struct PushHeader { + VkPipelineLayout layout; + VkShaderStageFlags stages; + std::uint32_t offset; + std::uint32_t size; +}; + +template<> +struct Streamer : Copies { + static void Append(CommandStream& stream, VkPipelineLayout layout, VkShaderStageFlags stages, std::uint32_t offset, std::uint32_t size, const void* values) { + stream.Emplace([](const std::byte* payload, VkCommandBuffer target, const CommandFunctions& functions) { + const auto header = unpack(payload); + functions.CmdPushConstants(target, header.layout, header.stages, header.offset, header.size, afterHeader(payload)); + }, PushHeader{layout, stages, offset, size}, std::span(static_cast(values), size)); + } +}; + +template<> +struct Streamer : Copies { + static void Append(CommandStream& stream, std::uint32_t first, std::uint32_t count, const VkBuffer* buffers, const VkDeviceSize* offsets) { + stream.Emplace([](const std::byte* payload, VkCommandBuffer target, const CommandFunctions& functions) { + const auto header = unpack(payload); + const auto* at = afterHeader(payload); + const auto* buffers = arrayAt(at, header.count); + const auto* offsets = arrayAt(at, header.count); + functions.CmdBindVertexBuffers(target, header.first, header.count, buffers, offsets); + }, RangeHeader{first, count}, std::span(buffers, count), std::span(offsets, count)); + } +}; + +struct BarrierHeader { + VkPipelineStageFlags source; + VkPipelineStageFlags destination; + VkDependencyFlags dependencies; + std::uint32_t memory; + std::uint32_t buffers; + std::uint32_t images; +}; + +template<> +struct Streamer : Copies { + static void Append(CommandStream& stream, VkPipelineStageFlags source, VkPipelineStageFlags destination, VkDependencyFlags dependencies, std::uint32_t memory, const VkMemoryBarrier* memoryBarriers, std::uint32_t buffers, const VkBufferMemoryBarrier* bufferBarriers, std::uint32_t images, const VkImageMemoryBarrier* imageBarriers) { + auto chain = chained(memoryBarriers, memory); + if (chain == Unchained) chain = chained(bufferBarriers, buffers); + if (chain == Unchained) chain = chained(imageBarriers, images); + if (chain != Unchained) { + direct(stream, chain, source, destination, dependencies, memory, memoryBarriers, buffers, bufferBarriers, images, imageBarriers); + return; + } + stream.Emplace([](const std::byte* payload, VkCommandBuffer target, const CommandFunctions& functions) { + const auto header = unpack(payload); + const auto* at = afterHeader(payload); + const auto* memoryBarriers = arrayAt(at, header.memory); + const auto* bufferBarriers = arrayAt(at, header.buffers); + const auto* imageBarriers = arrayAt(at, header.images); + functions.CmdPipelineBarrier(target, header.source, header.destination, header.dependencies, header.memory, memoryBarriers, header.buffers, bufferBarriers, header.images, imageBarriers); + }, BarrierHeader{source, destination, dependencies, memory, buffers, images}, std::span(memoryBarriers, memory), std::span(bufferBarriers, buffers), std::span(imageBarriers, images)); + } +}; + +struct CopyBufferHeader { + VkBuffer source; + VkBuffer destination; + std::uint32_t count; +}; + +template<> +struct Streamer : Copies { + static void Append(CommandStream& stream, VkBuffer source, VkBuffer destination, std::uint32_t count, const VkBufferCopy* regions) { + stream.Emplace([](const std::byte* payload, VkCommandBuffer target, const CommandFunctions& functions) { + const auto header = unpack(payload); + const auto* at = afterHeader(payload); + functions.CmdCopyBuffer(target, header.source, header.destination, header.count, arrayAt(at, header.count)); + }, CopyBufferHeader{source, destination, count}, std::span(regions, count)); + } +}; + +struct UpdateBufferHeader { + VkBuffer buffer; + VkDeviceSize offset; + VkDeviceSize size; +}; + +template<> +struct Streamer : Copies { + static void Append(CommandStream& stream, VkBuffer buffer, VkDeviceSize offset, VkDeviceSize size, const void* data) { + stream.Emplace([](const std::byte* payload, VkCommandBuffer target, const CommandFunctions& functions) { + const auto header = unpack(payload); + functions.CmdUpdateBuffer(target, header.buffer, header.offset, header.size, afterHeader(payload)); + }, UpdateBufferHeader{buffer, offset, size}, std::span(static_cast(data), static_cast(size))); + } +}; + +struct BufferImageHeader { + VkBuffer buffer; + VkImage image; + VkImageLayout layout; + std::uint32_t count; +}; + +template<> +struct Streamer : Copies { + static void Append(CommandStream& stream, VkBuffer source, VkImage destination, VkImageLayout layout, std::uint32_t count, const VkBufferImageCopy* regions) { + stream.Emplace([](const std::byte* payload, VkCommandBuffer target, const CommandFunctions& functions) { + const auto header = unpack(payload); + const auto* at = afterHeader(payload); + functions.CmdCopyBufferToImage(target, header.buffer, header.image, header.layout, header.count, arrayAt(at, header.count)); + }, BufferImageHeader{source, destination, layout, count}, std::span(regions, count)); + } +}; + +template<> +struct Streamer : Copies { + static void Append(CommandStream& stream, VkImage source, VkImageLayout layout, VkBuffer destination, std::uint32_t count, const VkBufferImageCopy* regions) { + stream.Emplace([](const std::byte* payload, VkCommandBuffer target, const CommandFunctions& functions) { + const auto header = unpack(payload); + const auto* at = afterHeader(payload); + functions.CmdCopyImageToBuffer(target, header.image, header.layout, header.buffer, header.count, arrayAt(at, header.count)); + }, BufferImageHeader{destination, source, layout, count}, std::span(regions, count)); + } +}; + +struct ImageToImageHeader { + VkImage source; + VkImageLayout sourceLayout; + VkImage destination; + VkImageLayout destinationLayout; + std::uint32_t count; + VkFilter filter; +}; + +template<> +struct Streamer : Copies { + static void Append(CommandStream& stream, VkImage source, VkImageLayout sourceLayout, VkImage destination, VkImageLayout destinationLayout, std::uint32_t count, const VkImageCopy* regions) { + stream.Emplace([](const std::byte* payload, VkCommandBuffer target, const CommandFunctions& functions) { + const auto header = unpack(payload); + const auto* at = afterHeader(payload); + functions.CmdCopyImage(target, header.source, header.sourceLayout, header.destination, header.destinationLayout, header.count, arrayAt(at, header.count)); + }, ImageToImageHeader{source, sourceLayout, destination, destinationLayout, count, VK_FILTER_NEAREST}, std::span(regions, count)); + } +}; + +template<> +struct Streamer : Copies { + static void Append(CommandStream& stream, VkImage source, VkImageLayout sourceLayout, VkImage destination, VkImageLayout destinationLayout, std::uint32_t count, const VkImageBlit* regions, VkFilter filter) { + stream.Emplace([](const std::byte* payload, VkCommandBuffer target, const CommandFunctions& functions) { + const auto header = unpack(payload); + const auto* at = afterHeader(payload); + functions.CmdBlitImage(target, header.source, header.sourceLayout, header.destination, header.destinationLayout, header.count, arrayAt(at, header.count), header.filter); + }, ImageToImageHeader{source, sourceLayout, destination, destinationLayout, count, filter}, std::span(regions, count)); + } +}; + +template<> +struct Streamer : Copies { + static void Append(CommandStream& stream, VkImage source, VkImageLayout sourceLayout, VkImage destination, VkImageLayout destinationLayout, std::uint32_t count, const VkImageResolve* regions) { + stream.Emplace([](const std::byte* payload, VkCommandBuffer target, const CommandFunctions& functions) { + const auto header = unpack(payload); + const auto* at = afterHeader(payload); + functions.CmdResolveImage(target, header.source, header.sourceLayout, header.destination, header.destinationLayout, header.count, arrayAt(at, header.count)); + }, ImageToImageHeader{source, sourceLayout, destination, destinationLayout, count, VK_FILTER_NEAREST}, std::span(regions, count)); + } +}; + +struct ClearColorHeader { + VkImage image; + VkImageLayout layout; + VkClearColorValue color; + std::uint32_t count; +}; + +template<> +struct Streamer : Copies { + static void Append(CommandStream& stream, VkImage image, VkImageLayout layout, const VkClearColorValue* color, std::uint32_t count, const VkImageSubresourceRange* ranges) { + stream.Emplace([](const std::byte* payload, VkCommandBuffer target, const CommandFunctions& functions) { + const auto& header = unpack(payload); + const auto* at = afterHeader(payload); + functions.CmdClearColorImage(target, header.image, header.layout, &header.color, header.count, arrayAt(at, header.count)); + }, ClearColorHeader{image, layout, *color, count}, std::span(ranges, count)); + } +}; + +struct ClearDepthHeader { + VkImage image; + VkImageLayout layout; + VkClearDepthStencilValue value; + std::uint32_t count; +}; + +template<> +struct Streamer : Copies { + static void Append(CommandStream& stream, VkImage image, VkImageLayout layout, const VkClearDepthStencilValue* value, std::uint32_t count, const VkImageSubresourceRange* ranges) { + stream.Emplace([](const std::byte* payload, VkCommandBuffer target, const CommandFunctions& functions) { + const auto& header = unpack(payload); + const auto* at = afterHeader(payload); + functions.CmdClearDepthStencilImage(target, header.image, header.layout, &header.value, header.count, arrayAt(at, header.count)); + }, ClearDepthHeader{image, layout, *value, count}, std::span(ranges, count)); + } +}; + +struct ClearAttachmentsHeader { + std::uint32_t attachments; + std::uint32_t rects; +}; + +template<> +struct Streamer : Copies { + static void Append(CommandStream& stream, std::uint32_t attachments, const VkClearAttachment* clears, std::uint32_t rects, const VkClearRect* areas) { + stream.Emplace([](const std::byte* payload, VkCommandBuffer target, const CommandFunctions& functions) { + const auto header = unpack(payload); + const auto* at = afterHeader(payload); + const auto* clears = arrayAt(at, header.attachments); + const auto* areas = arrayAt(at, header.rects); + functions.CmdClearAttachments(target, header.attachments, clears, header.rects, areas); + }, ClearAttachmentsHeader{attachments, rects}, std::span(clears, attachments), std::span(areas, rects)); + } +}; + +struct BeginPassHeader { + VkRenderPassBeginInfo info; + VkSubpassContents contents; +}; + +template<> +struct Streamer : Copies { + static void Append(CommandStream& stream, const VkRenderPassBeginInfo* info, VkSubpassContents contents) { + if (info->pNext != nullptr) { + direct(stream, chainOf(info->pNext), info, contents); + return; + } + stream.Emplace([](const std::byte* payload, VkCommandBuffer target, const CommandFunctions& functions) { + auto header = unpack(payload); + const auto* at = afterHeader(payload); + header.info.pClearValues = arrayAt(at, header.info.clearValueCount); + functions.CmdBeginRenderPass(target, &header.info, header.contents); + }, BeginPassHeader{*info, contents}, std::span(info->pClearValues, info->clearValueCount)); + } +}; + +struct RenderingHeader { + VkRenderingInfoKHR info; + VkRenderingAttachmentInfoKHR depth; + VkRenderingAttachmentInfoKHR stencil; +}; + +template<> +struct Streamer : Copies { + static void Append(CommandStream& stream, const VkRenderingInfoKHR* info) { + auto chain = chainOf(info->pNext); + if (chain == Unchained && info->pDepthAttachment != nullptr) chain = chainOf(info->pDepthAttachment->pNext); + if (chain == Unchained && info->pStencilAttachment != nullptr) chain = chainOf(info->pStencilAttachment->pNext); + if (chain == Unchained) chain = chained(info->pColorAttachments, info->colorAttachmentCount); + if (chain != Unchained) { + direct(stream, chain, info); + return; + } + stream.Emplace([](const std::byte* payload, VkCommandBuffer target, const CommandFunctions& functions) { + auto header = unpack(payload); + const auto* at = afterHeader(payload); + header.info.pColorAttachments = arrayAt(at, header.info.colorAttachmentCount); + if (header.info.pDepthAttachment != nullptr) header.info.pDepthAttachment = &header.depth; + if (header.info.pStencilAttachment != nullptr) header.info.pStencilAttachment = &header.stencil; + functions.CmdBeginRenderingKHR(target, &header.info); + }, RenderingHeader{*info, info->pDepthAttachment != nullptr ? *info->pDepthAttachment : VkRenderingAttachmentInfoKHR{}, info->pStencilAttachment != nullptr ? *info->pStencilAttachment : VkRenderingAttachmentInfoKHR{}}, std::span(info->pColorAttachments, info->colorAttachmentCount)); + } +}; + +template<> +struct Streamer : CountStreamer {}; + +template<> +struct Streamer : Copies { + static void Append(CommandStream& stream, const void* marker) { + stream.Emplace([](const std::byte* payload, VkCommandBuffer target, const CommandFunctions& functions) { + functions.CmdSetCheckpointNV(target, reinterpret_cast(unpack(payload))); + }, reinterpret_cast(marker)); + } +}; + +template<> +struct Streamer : Copies { + static void Append(CommandStream& stream, const VkDepthBiasInfoEXT* info) { + if (info->pNext != nullptr) { + direct(stream, chainOf(info->pNext), info); + return; + } + stream.Emplace([](const std::byte* payload, VkCommandBuffer target, const CommandFunctions& functions) { + functions.CmdSetDepthBias2EXT(target, &unpack(payload)); + }, *info); + } +}; + +struct BindShadersHeader { + std::uint32_t count; + std::uint32_t shaders; +}; + +template<> +struct Streamer : Copies { + static void Append(CommandStream& stream, std::uint32_t count, const VkShaderStageFlagBits* stages, const VkShaderEXT* shaders) { + const std::uint32_t bound = shaders != nullptr ? count : 0; + stream.Emplace([](const std::byte* payload, VkCommandBuffer target, const CommandFunctions& functions) { + const auto header = unpack(payload); + const auto* at = afterHeader(payload); + const auto* stages = arrayAt(at, header.count); + const auto* shaders = arrayAt(at, header.shaders); + functions.CmdBindShadersEXT(target, header.count, stages, shaders); + }, BindShadersHeader{count, bound}, std::span(stages, count), std::span(shaders, bound)); + } +}; + +enum class DescriptorArray : std::uint8_t { Images, Buffers, Views, Unknown }; + +DescriptorArray arrayFor(VkDescriptorType type) noexcept { + switch (type) { + case VK_DESCRIPTOR_TYPE_SAMPLER: + case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: + case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: + case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: + case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT: + return DescriptorArray::Images; + case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER: + case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER: + case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: + case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: + return DescriptorArray::Buffers; + case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: + case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: + return DescriptorArray::Views; + default: + return DescriptorArray::Unknown; + } +} + +std::size_t descriptorBytes(const VkWriteDescriptorSet& write) noexcept { + switch (arrayFor(write.descriptorType)) { + case DescriptorArray::Images: + return CommandStream::Aligned(sizeof(VkDescriptorImageInfo) * write.descriptorCount); + case DescriptorArray::Buffers: + return CommandStream::Aligned(sizeof(VkDescriptorBufferInfo) * write.descriptorCount); + case DescriptorArray::Views: + return CommandStream::Aligned(sizeof(VkBufferView) * write.descriptorCount); + case DescriptorArray::Unknown: + break; + } + return 0; +} + +template +const T* copyDescriptors(std::byte*& at, const T* values, std::uint32_t count) noexcept { + if (count == 0) return nullptr; + std::memcpy(at, values, sizeof(T) * count); + const auto* copied = reinterpret_cast(at); + at += CommandStream::Aligned(sizeof(T) * count); + return copied; +} + +struct PushSetHeader { + VkPipelineBindPoint bindPoint; + VkPipelineLayout layout; + std::uint32_t set; + std::uint32_t writes; +}; + +template<> +struct Streamer : Copies { + static void Append(CommandStream& stream, VkPipelineBindPoint bindPoint, VkPipelineLayout layout, std::uint32_t set, std::uint32_t count, const VkWriteDescriptorSet* writes) { + auto chain = chained(writes, count); + bool copyable = chain == Unchained && !RuntimeSwitches::Set(RuntimeSwitch::NoStreamedPushDescriptors); + std::size_t bytes = CommandStream::Aligned(sizeof(PushSetHeader)) + CommandStream::Aligned(sizeof(VkWriteDescriptorSet) * count); + for (std::uint32_t index = 0; copyable && index < count; ++index) { + copyable = arrayFor(writes[index].descriptorType) != DescriptorArray::Unknown; + bytes += descriptorBytes(writes[index]); + } + if (!copyable) { + direct(stream, chain, bindPoint, layout, set, count, writes); + return; + } + stream.EmplaceBytes([](const std::byte* payload, VkCommandBuffer target, const CommandFunctions& functions) { + const auto header = unpack(payload); + const auto* copies = header.writes != 0 ? reinterpret_cast(afterHeader(payload)) : nullptr; + functions.CmdPushDescriptorSetKHR(target, header.bindPoint, header.layout, header.set, header.writes, copies); + }, bytes, [&](std::byte* at) noexcept { + new (at) PushSetHeader{bindPoint, layout, set, count}; + auto* copies = reinterpret_cast(at + CommandStream::Aligned(sizeof(PushSetHeader))); + if (count != 0) std::memcpy(static_cast(copies), writes, sizeof(VkWriteDescriptorSet) * count); + auto* data = reinterpret_cast(copies) + CommandStream::Aligned(sizeof(VkWriteDescriptorSet) * count); + for (std::uint32_t index = 0; index < count; ++index) { + auto& copy = copies[index]; + const auto& write = writes[index]; + copy.pImageInfo = nullptr; + copy.pBufferInfo = nullptr; + copy.pTexelBufferView = nullptr; + switch (arrayFor(write.descriptorType)) { + case DescriptorArray::Images: + copy.pImageInfo = copyDescriptors(data, write.pImageInfo, write.descriptorCount); + break; + case DescriptorArray::Buffers: + copy.pBufferInfo = copyDescriptors(data, write.pBufferInfo, write.descriptorCount); + break; + case DescriptorArray::Views: + copy.pTexelBufferView = copyDescriptors(data, write.pTexelBufferView, write.descriptorCount); + break; + case DescriptorArray::Unknown: + break; + } + } + }); + } +}; + +void refuseStreamSecondaries(std::uint32_t count, const VkCommandBuffer* buffers) { + if (std::any_of(buffers, buffers + count, &CommandStream::IsHandle)) throw std::logic_error("AGC graphics: vkCmdExecuteCommands was given a stream handle as a secondary command buffer; a secondary must be a command buffer that has finished recording"); +} + +template +void toStream(VkCommandBuffer commands, A... arguments) { + if constexpr (Id == CommandId::CmdExecuteCommands) refuseStreamSecondaries(arguments...); + auto& stream = CommandStream::From(commands); + if (const auto target = stream.Materialized(); target != VK_NULL_HANDLE) { + (stream.Functions().*Command::member)(target, arguments...); + return; + } + Streamer::Append(stream, arguments...); +} + +template +VKAPI_ATTR void VKAPI_CALL thunk(VkCommandBuffer commands, A... arguments) { + if (!CommandStream::IsHandle(commands)) [[likely]] { + reinterpret_cast::Pfn>(realSlots[indexOf(Id)][K].load(std::memory_order_relaxed))(commands, arguments...); + return; + } + toStream(commands, arguments...); +} + +template +VKAPI_ATTR void VKAPI_CALL keyed(VkCommandBuffer commands, A... arguments) { + if (!CommandStream::IsHandle(commands)) [[likely]] { + reinterpret_cast::Pfn>(deviceReal(indexOf(Id), dispatchKey(commands), Command::text))(commands, arguments...); + return; + } + toStream(commands, arguments...); +} + +[[noreturn]] void notAStream(const char* command) { + throw std::logic_error(std::string(command) + " of a streamed batch was given a command buffer that is not a stream"); +} + +template +VKAPI_ATTR void VKAPI_CALL streamed(VkCommandBuffer commands, A... arguments) { + if (!CommandStream::IsHandle(commands)) [[unlikely]] notAStream(Command::text); + toStream(commands, arguments...); +} + +template +void setStreamed(CommandFunctions& functions, void(VKAPI_PTR*)(VkCommandBuffer, A...)) { + functions.*Command::member = &streamed; +} + +template +PFN_vkVoidFunction thunkOf(void(VKAPI_PTR*)(VkCommandBuffer, A...)) { + return reinterpret_cast(&thunk); +} + +template +std::array thunksFor(std::index_sequence) { + return {thunkOf(typename Command::Pfn{})...}; +} + +const std::array, CommandCount>& thunks() { + static const std::array, CommandCount> table{ +#define APS5_COMMAND_THUNKS(name) thunksFor(std::make_index_sequence{}), + APS5_COMMANDS(APS5_COMMAND_THUNKS) +#undef APS5_COMMAND_THUNKS + }; + return table; +} + +template +PFN_vkVoidFunction keyedOf(void(VKAPI_PTR*)(VkCommandBuffer, A...)) { + return reinterpret_cast(&keyed); +} + +const std::array& keyedThunks() { + static const std::array table{ +#define APS5_COMMAND_KEYED(name) keyedOf(typename Command::Pfn{}), + APS5_COMMANDS(APS5_COMMAND_KEYED) +#undef APS5_COMMAND_KEYED + }; + return table; +} + +PFN_vkVoidFunction deviceThunk(std::size_t id, std::string_view name, PFN_vkVoidFunction real, VkDevice device) { + if (device == VK_NULL_HANDLE) throw std::runtime_error("AGC graphics: " + std::string(name) + " has more than " + std::to_string(ThunkSlots) + " distinct driver entry points and no device to key another by"); + const auto key = dispatchKey(device); + DeviceEntry* free = nullptr; + for (auto* entry = deviceEntries[id].load(std::memory_order_relaxed); entry != nullptr; entry = entry->next) { + const auto held = entry->key.load(std::memory_order_relaxed); + if (held == nullptr && free == nullptr) free = entry; + if (held != key) continue; + if (entry->real.load(std::memory_order_relaxed) == real) return keyedThunks()[id]; + throw std::runtime_error("AGC graphics: one device gave two different entry points for " + std::string(name)); + } + const bool fresh = free == nullptr; + if (fresh) { + free = new DeviceEntry; + free->next = deviceEntries[id].load(std::memory_order_relaxed); + ++deviceEntryStorage[id]; + } + rewrite(*free, key, real); + if (fresh) deviceEntries[id].store(free, std::memory_order_release); + keyedDevices.fetch_add(1, std::memory_order_relaxed); + return keyedThunks()[id]; +} + +const std::vector>& sortedNames() { + static const auto sorted = [] { + std::vector> names; + for (std::size_t index = 0; index < CommandCount; ++index) names.emplace_back(Names[index], static_cast(index)); + std::sort(names.begin(), names.end()); + return names; + }(); + return sorted; +} + +const std::pair* find(std::string_view name) noexcept { + const auto& names = sortedNames(); + const auto found = std::lower_bound(names.begin(), names.end(), name, [](const auto& entry, std::string_view key) { return entry.first < key; }); + return found != names.end() && found->first == name ? &*found : nullptr; +} + +} + +std::span CommandNames() { + return Names; +} + +bool IsCommandName(std::string_view name) noexcept { + return name.starts_with("vkCmd"); +} + +CommandId CommandFor(std::string_view name) { + if (const auto* found = find(name)) return found->second; + throw std::logic_error("AGC graphics: " + std::string(name) + " is a Vulkan command without a command-stream thunk; add it to APS5_COMMANDS"); +} + +const CommandFunctions& StreamedCommands() { + static const CommandFunctions functions = [] { + CommandFunctions table{}; +#define APS5_COMMAND_STREAMED(name) setStreamed(table, typename Command::Pfn{}); + APS5_COMMANDS(APS5_COMMAND_STREAMED) +#undef APS5_COMMAND_STREAMED + return table; + }(); + return functions; +} + +void ResolveCommandFunctions(CommandFunctions& functions, VkDevice device, PFN_vkGetDeviceProcAddr resolve) { +#define APS5_COMMAND_RESOLVE(name) functions.name = reinterpret_cast(resolve(device, "vk" #name)); + APS5_COMMANDS(APS5_COMMAND_RESOLVE) +#undef APS5_COMMAND_RESOLVE +} + +PFN_vkVoidFunction CommandThunk(std::string_view name, PFN_vkVoidFunction real, VkDevice device) { + if (real == nullptr) return nullptr; + const auto id = indexOf(CommandFor(name)); + auto& slots = realSlots[id]; + for (std::size_t slot = 0; slot < ThunkSlots; ++slot) { + if (slots[slot].load(std::memory_order_acquire) == real) return thunks()[id][slot]; + } + std::lock_guard lock(slotMutex); + for (std::size_t slot = 0; slot < ThunkSlots; ++slot) { + const auto held = slots[slot].load(std::memory_order_acquire); + if (held == real) return thunks()[id][slot]; + if (held != nullptr) continue; + slots[slot].store(real, std::memory_order_release); + return thunks()[id][slot]; + } + return deviceThunk(id, name, real, device); +} + +void ForgetCommandDevice(VkDevice device) { + if (device == VK_NULL_HANDLE || keyedDevices.load(std::memory_order_relaxed) == 0) return; + const auto key = dispatchKey(device); + std::lock_guard lock(slotMutex); + for (std::size_t id = 0; id < CommandCount; ++id) { + for (auto* entry = deviceEntries[id].load(std::memory_order_relaxed); entry != nullptr; entry = entry->next) { + if (entry->key.load(std::memory_order_relaxed) != key) continue; + rewrite(*entry, nullptr, nullptr); + keyedDevices.fetch_sub(1, std::memory_order_relaxed); + } + } +} + +std::size_t CommandDeviceEntries(CommandId id) noexcept { + std::lock_guard lock(slotMutex); + std::size_t live = 0; + for (auto* entry = deviceEntries[indexOf(id)].load(std::memory_order_acquire); entry != nullptr; entry = entry->next) live += entry->key.load(std::memory_order_relaxed) != nullptr ? 1 : 0; + return live; +} + +std::size_t CommandDeviceStorage(CommandId id) noexcept { + std::lock_guard lock(slotMutex); + return deviceEntryStorage[indexOf(id)]; +} + +bool CommandStreams(CommandId id) noexcept { + static constexpr std::array streams{ +#define APS5_COMMAND_STREAMS(name) Streamer::Streams, + APS5_COMMANDS(APS5_COMMAND_STREAMS) +#undef APS5_COMMAND_STREAMS + }; + return streams[indexOf(id)]; +} + +bool IsCommandThunk(std::string_view name, PFN_vkVoidFunction function) noexcept { + const auto* found = find(name); + if (found == nullptr || function == nullptr) return false; + const auto& row = thunks()[indexOf(found->second)]; + return std::find(row.begin(), row.end(), function) != row.end() || keyedThunks()[indexOf(found->second)] == function; +} + +std::size_t CommandThunkSlots(CommandId id) noexcept { + std::size_t used = 0; + for (const auto& slot : realSlots[indexOf(id)]) used += slot.load(std::memory_order_acquire) != nullptr ? 1 : 0; + return used; +} + +} diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp index 1595d899b3bc..7c7fb7cc8698 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp @@ -2623,7 +2623,7 @@ void CompactIndirectListRestart(const Context& context, const Pm4::DrawParameter // The draw commands of one draw: the vertex and index buffer binds, then the direct draw, the // GPU-side indirect draw from `argumentBuffer` or the CPU-read records with the driver's rules. -bool recordDrawCommandsImpl(const Context& context, VkCommandBuffer commands, const State& state, const Pm4::DrawParameters& draw, const DrawInputs& inputs, const IndirectRecord* indirect, VkBuffer argumentBuffer, VkDeviceSize argumentOffset, const DrawTraceContext* trace, std::uint32_t& subdraw, std::optional pieceFirstIndex = std::nullopt) { +bool recordDrawCommandsImpl(const Context& context, VkCommandBuffer commands, const CommandFunctions* functions, const State& state, const Pm4::DrawParameters& draw, const DrawInputs& inputs, const IndirectRecord* indirect, VkBuffer argumentBuffer, VkDeviceSize argumentOffset, const DrawTraceContext* trace, std::uint32_t& subdraw, std::optional pieceFirstIndex = std::nullopt) { bool emitted = false; if (context.recorder != nullptr) context.recorder->NoteSampledDraw(commands); const auto recorded = [&](std::uint32_t index) { @@ -2648,24 +2648,24 @@ bool recordDrawCommandsImpl(const Context& context, VkCommandBuffer commands, co emitted = true; return true; } - if (!inputs.vertexHandles.empty()) context.Resolved(&DeviceFunctions::cmdBindVertexBuffers, "vkCmdBindVertexBuffers")(commands, 0, static_cast(inputs.vertexHandles.size()), inputs.vertexHandles.data(), inputs.vertexOffsets.data()); + if (!inputs.vertexHandles.empty()) context.ForBatch(functions, &CommandFunctions::CmdBindVertexBuffers, &DeviceFunctions::cmdBindVertexBuffers, "vkCmdBindVertexBuffers")(commands, 0, static_cast(inputs.vertexHandles.size()), inputs.vertexHandles.data(), inputs.vertexOffsets.data()); if (inputs.expandedIndexCount != 0u) { - context.Resolved(&DeviceFunctions::cmdBindIndexBuffer, "vkCmdBindIndexBuffer")(commands, inputs.indexHandle, inputs.indexOffset, VK_INDEX_TYPE_UINT32); + context.ForBatch(functions, &CommandFunctions::CmdBindIndexBuffer, &DeviceFunctions::cmdBindIndexBuffer, "vkCmdBindIndexBuffer")(commands, inputs.indexHandle, inputs.indexOffset, VK_INDEX_TYPE_UINT32); CountVkDraw(VkDrawKind::Indexed); - context.Resolved(&DeviceFunctions::cmdDrawIndexed, "vkCmdDrawIndexed")(commands, inputs.expandedIndexCount, draw.instanceCount, 0, static_cast(draw.firstVertex), draw.firstInstance); + context.ForBatch(functions, &CommandFunctions::CmdDrawIndexed, &DeviceFunctions::cmdDrawIndexed, "vkCmdDrawIndexed")(commands, inputs.expandedIndexCount, draw.instanceCount, 0, static_cast(draw.firstVertex), draw.firstInstance); emitted = true; return true; } - if (draw.indexed) context.Resolved(&DeviceFunctions::cmdBindIndexBuffer, "vkCmdBindIndexBuffer")(commands, inputs.indexHandle, inputs.indexOffset, draw.indexSize == 2 ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32); + if (draw.indexed) context.ForBatch(functions, &CommandFunctions::CmdBindIndexBuffer, &DeviceFunctions::cmdBindIndexBuffer, "vkCmdBindIndexBuffer")(commands, inputs.indexHandle, inputs.indexOffset, draw.indexSize == 2 ? VK_INDEX_TYPE_UINT16 : VK_INDEX_TYPE_UINT32); if (args == nullptr) { if (draw.indexed) { CountVkDraw(VkDrawKind::Indexed); - context.Resolved(&DeviceFunctions::cmdDrawIndexed, "vkCmdDrawIndexed")(commands, pieceFirstIndex ? draw.indexCount : inputs.indexCount.value_or(draw.indexCount), draw.instanceCount, pieceFirstIndex.value_or(0u), static_cast(draw.firstVertex), draw.firstInstance); + context.ForBatch(functions, &CommandFunctions::CmdDrawIndexed, &DeviceFunctions::cmdDrawIndexed, "vkCmdDrawIndexed")(commands, pieceFirstIndex ? draw.indexCount : inputs.indexCount.value_or(draw.indexCount), draw.instanceCount, pieceFirstIndex.value_or(0u), static_cast(draw.firstVertex), draw.firstInstance); recorded(subdraw++); emitted = true; } else { CountVkDraw(VkDrawKind::Direct); - context.Resolved(&DeviceFunctions::cmdDraw, "vkCmdDraw")(commands, draw.indexCount, draw.instanceCount, draw.firstVertex, draw.firstInstance); + context.ForBatch(functions, &CommandFunctions::CmdDraw, &DeviceFunctions::cmdDraw, "vkCmdDraw")(commands, draw.indexCount, draw.instanceCount, draw.firstVertex, draw.firstInstance); recorded(subdraw++); emitted = true; } @@ -2677,14 +2677,14 @@ bool recordDrawCommandsImpl(const Context& context, VkCommandBuffer commands, co else context.Function("vkCmdDrawIndirectCountKHR")(commands, argumentBuffer, argumentOffset, indirect->countImport->buffer, HostImportOffset(*indirect->countImport, args->countAddress), args->count, args->stride); } else if (args->count <= 1 || context.multiDrawIndirect) { CountVkDraw(VkDrawKind::Indirect); - if (draw.indexed) context.Resolved(&DeviceFunctions::cmdDrawIndexedIndirect, "vkCmdDrawIndexedIndirect")(commands, argumentBuffer, argumentOffset, args->count, args->stride); - else context.Resolved(&DeviceFunctions::cmdDrawIndirect, "vkCmdDrawIndirect")(commands, argumentBuffer, argumentOffset, args->count, args->stride); + if (draw.indexed) context.ForBatch(functions, &CommandFunctions::CmdDrawIndexedIndirect, &DeviceFunctions::cmdDrawIndexedIndirect, "vkCmdDrawIndexedIndirect")(commands, argumentBuffer, argumentOffset, args->count, args->stride); + else context.ForBatch(functions, &CommandFunctions::CmdDrawIndirect, &DeviceFunctions::cmdDrawIndirect, "vkCmdDrawIndirect")(commands, argumentBuffer, argumentOffset, args->count, args->stride); } else { for (std::uint32_t record = 0; record < args->count; ++record) { const auto offset = argumentOffset + static_cast(record) * args->stride; CountVkDraw(VkDrawKind::Indirect); - if (draw.indexed) context.Resolved(&DeviceFunctions::cmdDrawIndexedIndirect, "vkCmdDrawIndexedIndirect")(commands, argumentBuffer, offset, 1, args->stride); - else context.Resolved(&DeviceFunctions::cmdDrawIndirect, "vkCmdDrawIndirect")(commands, argumentBuffer, offset, 1, args->stride); + if (draw.indexed) context.ForBatch(functions, &CommandFunctions::CmdDrawIndexedIndirect, &DeviceFunctions::cmdDrawIndexedIndirect, "vkCmdDrawIndexedIndirect")(commands, argumentBuffer, offset, 1, args->stride); + else context.ForBatch(functions, &CommandFunctions::CmdDrawIndirect, &DeviceFunctions::cmdDrawIndirect, "vkCmdDrawIndirect")(commands, argumentBuffer, offset, 1, args->stride); } } } else { @@ -2701,12 +2701,12 @@ bool recordDrawCommandsImpl(const Context& context, VkCommandBuffer commands, co const auto vertexOffset = args->vertexRule == Rule::InPlace ? record.vertexOffset : args->vertexConstant; emitted = true; CountVkDraw(VkDrawKind::Indexed); - context.Resolved(&DeviceFunctions::cmdDrawIndexed, "vkCmdDrawIndexed")(commands, std::min(record.count, boundCount - record.firstVertexOrIndex), record.instances, record.firstVertexOrIndex, static_cast(vertexOffset), firstInstance); + context.ForBatch(functions, &CommandFunctions::CmdDrawIndexed, &DeviceFunctions::cmdDrawIndexed, "vkCmdDrawIndexed")(commands, std::min(record.count, boundCount - record.firstVertexOrIndex), record.instances, record.firstVertexOrIndex, static_cast(vertexOffset), firstInstance); } else { const auto firstVertex = args->vertexRule == Rule::InPlace ? record.firstVertexOrIndex : args->vertexConstant; emitted = true; CountVkDraw(VkDrawKind::Direct); - context.Resolved(&DeviceFunctions::cmdDraw, "vkCmdDraw")(commands, record.count, record.instances, firstVertex, firstInstance); + context.ForBatch(functions, &CommandFunctions::CmdDraw, &DeviceFunctions::cmdDraw, "vkCmdDraw")(commands, record.count, record.instances, firstVertex, firstInstance); } } } @@ -2721,8 +2721,8 @@ void NoteGuestWorkIn(const Context& context, VkCommandBuffer commands) { NoteGuestWorkOnCommandBuffer(commands); } -void recordDrawCommands(const Context& context, VkCommandBuffer commands, const State& state, const Pm4::DrawParameters& draw, const DrawInputs& inputs, const IndirectRecord* indirect, VkBuffer argumentBuffer, VkDeviceSize argumentOffset, const DrawTraceContext* trace, std::uint32_t& subdraw, std::optional pieceFirstIndex = std::nullopt) { - if (recordDrawCommandsImpl(context, commands, state, draw, inputs, indirect, argumentBuffer, argumentOffset, trace, subdraw, pieceFirstIndex)) NoteGuestWorkIn(context, commands); +void recordDrawCommands(const Context& context, VkCommandBuffer commands, const CommandFunctions* functions, const State& state, const Pm4::DrawParameters& draw, const DrawInputs& inputs, const IndirectRecord* indirect, VkBuffer argumentBuffer, VkDeviceSize argumentOffset, const DrawTraceContext* trace, std::uint32_t& subdraw, std::optional pieceFirstIndex = std::nullopt) { + if (recordDrawCommandsImpl(context, commands, functions, state, draw, inputs, indirect, argumentBuffer, argumentOffset, trace, subdraw, pieceFirstIndex)) NoteGuestWorkIn(context, commands); } // The GPU-side records of an indirect draw, recorded outside the render pass: the stores that @@ -2861,7 +2861,9 @@ std::shared_ptr> reserveSpaceKeep(Recorder& recorder } void keepRecordedDraw(Recorder& recorder, const std::shared_ptr& resources, const std::shared_ptr& pipeline, const std::shared_ptr& framebuffer, DrawInputs& inputs, std::span> residents, std::span> slices, VkRect2D scissor, std::unique_ptr scratch, std::function checkRecords, bool listed, bool completion, const DrawOutcome& outcome, std::shared_ptr use, std::shared_ptr* spaceKeep) { - std::shared_ptr scratchOwner(std::move(scratch)); + std::shared_ptr scratchOwner; + const auto unwindGuard = recorder.UnwindGuard(); + scratchOwner = std::move(scratch); recorder.ReserveRetention(4 + inputs.vertexBuffers.size() + residents.size() + (scratchOwner != nullptr ? 1u : 0u)); resources->KeepStorageImageBytes(recorder); for (const auto& target : residents) { @@ -3038,7 +3040,7 @@ void recordStencilReplay(const Context& context, CommandState& recording, const recording.SetStencilReference(context, VK_STENCIL_FACE_FRONT_AND_BACK, pass.reference); std::memcpy(block.data() + referenceOffset, &pass.word, sizeof(pass.word)); pipeline.PushConstants(commands, stages, block); - recordDrawCommands(context, commands, selected, piece, inputs, nullptr, VK_NULL_HANDLE, 0, nullptr, unusedSubdraw, firstIndex); + recordDrawCommands(context, commands, recording.FunctionsFor(commands, context), selected, piece, inputs, nullptr, VK_NULL_HANDLE, 0, nullptr, unusedSubdraw, firstIndex); } }; if (passes.size() == 1u) { @@ -3155,14 +3157,9 @@ void captureInputs(const Context& context, Recorder& recorder, VkCommandBuffer c CaptureTrace::Log("input-capture draw=%llu batch=%llu target=%llx ranges=%zu bytes=%zu", draw, batch, static_cast(target), samples.size(), total); if (samples.empty()) return; auto readback = std::make_shared(context, total, VK_BUFFER_USAGE_TRANSFER_DST_BIT); - RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT); - const auto copy = context.Function("vkCmdCopyBuffer"); - for (const auto& sample : samples) { - const VkBufferCopy region{sample.sourceOffset, sample.offset, sample.expected.size()}; - copy(commands, sample.source, readback->Handle(), 1, ®ion); - } - RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_HOST_READ_BIT | VK_ACCESS_SHADER_READ_BIT); - recorder.OnComplete([draw, batch, target, readback, samples = std::move(samples)] { + const auto kept = std::make_shared>(std::move(samples)); + recorder.OnComplete([draw, batch, target, readback, kept] { + const auto& samples = *kept; const auto actual = readback->Bytes(); std::size_t differences = 0; for (const auto& sample : samples) { @@ -3180,6 +3177,13 @@ void captureInputs(const Context& context, Recorder& recorder, VkCommandBuffer c } CaptureTrace::Log("input-result draw=%llu batch=%llu ranges=%zu mismatched=%zu", draw, batch, samples.size(), differences); }); + RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_HOST_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_HOST_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT); + const auto copy = context.Function("vkCmdCopyBuffer"); + for (const auto& sample : *kept) { + const VkBufferCopy region{sample.sourceOffset, sample.offset, sample.expected.size()}; + copy(commands, sample.source, readback->Handle(), 1, ®ion); + } + RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT, VK_ACCESS_HOST_READ_BIT | VK_ACCESS_SHADER_READ_BIT); } bool WriteOnlyPasses() { @@ -3335,6 +3339,8 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam VkDeviceSize argumentOffset = 0; bool rewritten = false; if (!meshIndirect && !inputs.restartTable.empty()) meshArguments = directMeshArguments(context, draw, inputs.restartTable); + std::vector> reorderKept; + const auto unwindGuard = recorder->UnwindGuard(); static const bool timeEachDraw = std::getenv("APS5_PROFILE_GPU_DRAWS") != nullptr; auto eachDrawTiming = Recorder::NoTiming; std::array movedPush; @@ -3383,9 +3389,8 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam // Earlier recorded work (dispatches, the previous draw) wrote the images in the general // layout, which a lean draw renders in: no transitions. if (!record.reordered.empty()) { - std::vector> kept; - RecordSampleOrder(context, rec, record.reorderPass, record.reordered, true, kept); - for (auto& object : kept) recorder->Keep(std::move(object)); + RecordSampleOrder(context, rec, record.reorderPass, record.reordered, true, reorderKept); + for (auto& object : reorderKept) recorder->Keep(std::move(object)); } for (const auto& write : record.staged) RecordStagedClear(context, cb, *write.temporary); APS5_LOG_OUT_DEBUG("Beginning pipeline renderExtent=%ux%u", state.renderExtent.width, state.renderExtent.height); @@ -3398,8 +3403,8 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam if (drawBindings != nullptr) { const auto set = drawBindings->allocation.set; const auto fragmentSet = drawBindings->fragmentAllocation.set; - if (set != VK_NULL_HANDLE) context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout(), 0, 1, &set, 0, nullptr); - if (fragmentSet != VK_NULL_HANDLE) context.Resolved(&DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout(), ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet, 1, &fragmentSet, 0, nullptr); + if (set != VK_NULL_HANDLE) context.ForBatch(rec.FunctionsFor(cb, context), &CommandFunctions::CmdBindDescriptorSets, &DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout(), 0, 1, &set, 0, nullptr); + if (fragmentSet != VK_NULL_HANDLE) context.ForBatch(rec.FunctionsFor(cb, context), &CommandFunctions::CmdBindDescriptorSets, &DeviceFunctions::cmdBindDescriptorSets, "vkCmdBindDescriptorSets")(cb, VK_PIPELINE_BIND_POINT_GRAPHICS, record.pipeline->Layout(), ShaderRecompiler::RuntimeAbi::FragmentDescriptorSet, 1, &fragmentSet, 0, nullptr); } else { resources.BindDrawUse(cb, record.pipeline->Layout(), drawUse.get()); } @@ -3424,18 +3429,18 @@ void recordDraw(const Context& context, const State& state, const Pm4::DrawParam } } noteDrawFaultToken(context, *recorder, cb, shaders, draw, static_cast(state.stages.mesh.has_value() ? AgcDriver::FaultStage::mesh : AgcDriver::FaultStage::graphics), record.indirect != nullptr ? record.indirect->args : nullptr); - if (record.stencilReplay.empty()) recordDrawCommands(context, cb, state, draw, inputs, record.indirect, argumentBuffer, argumentOffset, trace, subdraw); + if (record.stencilReplay.empty()) recordDrawCommands(context, cb, rec.FunctionsFor(cb, context), state, draw, inputs, record.indirect, argumentBuffer, argumentOffset, trace, subdraw); else { recordStencilReplay(context, rec, state, record.masked, draw, inputs, record.stencilReplay, shaders, resources, pushBytes, pushStages); for (const auto& [reference, pipeline] : record.stencilReplay) recorder->Keep(pipeline); } if (record.pipeline->SplitsFaces()) { record.pipeline->ContinueBackFaces(rec, state, record.masked); - recordDrawCommands(context, cb, state, draw, inputs, record.indirect, argumentBuffer, argumentOffset, trace, subdraw); + recordDrawCommands(context, cb, rec.FunctionsFor(cb, context), state, draw, inputs, record.indirect, argumentBuffer, argumentOffset, trace, subdraw); } if (record.pipeline->SplitsSecondChannel()) { record.pipeline->ContinueSecondChannel(rec, state, record.masked); - recordDrawCommands(context, cb, state, draw, inputs, record.indirect, argumentBuffer, argumentOffset, trace, subdraw); + recordDrawCommands(context, cb, rec.FunctionsFor(cb, context), state, draw, inputs, record.indirect, argumentBuffer, argumentOffset, trace, subdraw); } }; if (parallelThis) { @@ -4946,6 +4951,8 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D std::optional batchRecording; if (!recorded) batchRecording.emplace().Begin(commands, false); auto& recording = recorded ? recorder->GraphicsState() : *batchRecording; + std::optional unwindGuard; + if (recorded) unwindGuard.emplace(*recorder); if (recorded) recorder->PrepareSampleSlot(); APS5_LOG_CHARS_OUT_DEBUG("CommandBatch created"); // The draw's [gputime] class range: from its first barrier to the download barrier. @@ -5045,18 +5052,18 @@ void recordPreparedDraw(const Context& context, const State& state, const Pm4::D APS5_LOG_CHARS_OUT_DEBUG("Push constants recorded"); std::uint32_t subdraw = 0; if (recorded) noteDrawFaultToken(context, *recorder, commands, shaders, draw, static_cast(state.stages.mesh.has_value() ? AgcDriver::FaultStage::mesh : AgcDriver::FaultStage::graphics), args); - if (stencilReplay.empty()) recordDrawCommands(context, commands, state, draw, inputs, args != nullptr ? &indirect : nullptr, argumentBuffer, argumentOffset, prepared.trace, subdraw); + if (stencilReplay.empty()) recordDrawCommands(context, commands, recording.FunctionsFor(commands, context), state, draw, inputs, args != nullptr ? &indirect : nullptr, argumentBuffer, argumentOffset, prepared.trace, subdraw); else { recordStencilReplay(context, recording, state, masked.has_value() ? &*masked : nullptr, draw, inputs, stencilReplay, shaders, *resources); if (recorded) for (const auto& [reference, selectedPipeline] : stencilReplay) recorder->Keep(selectedPipeline); } if (pipeline->SplitsFaces()) { pipeline->ContinueBackFaces(recording, state, masked.has_value() ? &*masked : nullptr); - recordDrawCommands(context, commands, state, draw, inputs, args != nullptr ? &indirect : nullptr, argumentBuffer, argumentOffset, prepared.trace, subdraw); + recordDrawCommands(context, commands, recording.FunctionsFor(commands, context), state, draw, inputs, args != nullptr ? &indirect : nullptr, argumentBuffer, argumentOffset, prepared.trace, subdraw); } if (pipeline->SplitsSecondChannel()) { pipeline->ContinueSecondChannel(recording, state, masked.has_value() ? &*masked : nullptr); - recordDrawCommands(context, commands, state, draw, inputs, args != nullptr ? &indirect : nullptr, argumentBuffer, argumentOffset, prepared.trace, subdraw); + recordDrawCommands(context, commands, recording.FunctionsFor(commands, context), state, draw, inputs, args != nullptr ? &indirect : nullptr, argumentBuffer, argumentOffset, prepared.trace, subdraw); } if (meshArguments != nullptr && recorded) recorder->Keep(meshArguments); if (argumentSnapshot != nullptr && recorded) recorder->Keep(argumentSnapshot); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp index 6fe081ca5ab9..bcfd561129f0 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/GuestBufferMemory.cpp @@ -4661,7 +4661,7 @@ void finishLeaseBatches(std::uint64_t target, const void* site) { const auto& state = Leases(); auto* recorder = Recorder::Active(); if (recorder == nullptr || recorder != state.leaseRecorder || target <= recorder->CompletedThrough()) return; - if (target >= recorder->OpenSerial()) recorder->Submit(); + if (target > recorder->Submissions()) recorder->Submit(); Recorder::AnnounceSyncSite(site); recorder->FinishUpTo(target); } diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp index 604d4ab0712c..2e00b47012ba 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp @@ -1193,7 +1193,7 @@ static bool PrepareCheckpointMarker(const Context& context) { if (state.device == context.device && state.buffer != VK_NULL_HANDLE) return state.write != nullptr; if (state.device != VK_NULL_HANDLE && state.device != context.device) return false; if (context.device == VK_NULL_HANDLE || context.deviceProc == nullptr) return false; - auto write = reinterpret_cast(context.deviceProc(context.device, "vkCmdWriteBufferMarkerAMD")); + auto write = reinterpret_cast(CommandThunk("vkCmdWriteBufferMarkerAMD", context.deviceProc(context.device, "vkCmdWriteBufferMarkerAMD"), context.device)); if (write == nullptr) return false; auto destroyBuffer = reinterpret_cast(context.deviceProc(context.device, "vkDestroyBuffer")); auto freeMemory = reinterpret_cast(context.deviceProc(context.device, "vkFreeMemory")); @@ -1290,7 +1290,7 @@ void WriteNvCheckpointToken(const Context& context, VkCommandBuffer commands, st if (commands == VK_NULL_HANDLE || token == 0) return; try { if (context.device == VK_NULL_HANDLE || context.deviceProc == nullptr) return; - auto setCheckpoint = reinterpret_cast(context.deviceProc(context.device, "vkCmdSetCheckpointNV")); + auto setCheckpoint = reinterpret_cast(CommandThunk("vkCmdSetCheckpointNV", context.deviceProc(context.device, "vkCmdSetCheckpointNV"), context.device)); if (setCheckpoint == nullptr) return; EmitNvCheckpointToken(commands, static_cast(token), setCheckpoint); } catch (...) { @@ -1404,7 +1404,17 @@ struct Recorder::ProgressWatcher { } }; -Recorder::Recorder(const Context& context, bool timelineSemaphores) : context(context), id(nextRecorderId.fetch_add(1)) { +Recorder::Recorder(const Context& context, bool timelineSemaphores, bool deferredBatches, std::uint32_t queueFamily, WorkBudget::Limits limits) : context(context), id(nextRecorderId.fetch_add(1)), budget(limits), queueFamily(queueFamily) { + if (deferredBatches && context.deviceProc != nullptr) { + ResolveCommandFunctions(realCommands, context.device, context.deviceProc); + executor = makeExecutor(); + deferring = true; + } + if (context.deviceProc != nullptr) { + if (!deferring) ResolveCommandFunctions(realCommands, context.device, context.deviceProc); + realResolved = true; + overlayListed(); + } { std::lock_guard lock(liveRecordersMutex); liveRecorders.push_back(id); @@ -1449,13 +1459,19 @@ Recorder::Recorder(const Context& context, bool timelineSemaphores) : context(co } Recorder::~Recorder() { - try { - Sync(); - } catch (const std::exception& error) { - std::fprintf(stderr, "[gpu] recorder teardown: %s\n", error.what()); + for (;;) { + try { + Sync(); + break; + } catch (const std::exception& error) { + std::fprintf(stderr, "[gpu] recorder teardown: %s\n", error.what()); + if (inFlight.empty()) break; + } } if (open != nullptr) discard(std::move(open)); ForgetHtileMasks_nid_no_patch(id); + latch.Shutdown(); + if (executor != nullptr) executor->Shutdown(); progressWatcher.reset(); holdKept.clear(); if (activeRecorder == this) { @@ -1525,6 +1541,7 @@ Recorder::~Recorder() { // Sync() above waited for every batch, so no submission still signals the timeline. if (timeline != VK_NULL_HANDLE) context.Function("vkDestroySemaphore")(context.device, timeline, nullptr); timeline = VK_NULL_HANDLE; + executor.reset(); } std::optional Recorder::PendingLabelSince() { @@ -1618,8 +1635,9 @@ std::uint32_t CommandState::DynamicSlots(std::span states) return slots; } -void CommandState::Begin(VkCommandBuffer recording, bool suppress) { +void CommandState::Begin(VkCommandBuffer recording, bool suppress, const CommandFunctions* table) { commands = recording; + functions = table; trackable = suppress ? ~0u : 0u; Invalidate(); } @@ -1659,7 +1677,7 @@ void CommandState::applyFaces(Slot first, VkStencilFaceFlags faces, std::array viewports, std::span scissors) { Require(!viewports.empty() && viewports.size() == scissors.size(), "every viewport needs a scissor"); const auto count = static_cast(viewports.size()); - context.tracked(&DeviceFunctions::cmdSetViewport, "vkCmdSetViewport")(commands, 0, count, viewports.data()); - context.tracked(&DeviceFunctions::cmdSetScissor, "vkCmdSetScissor")(commands, 0, count, scissors.data()); + context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetViewport, &DeviceFunctions::cmdSetViewport, "vkCmdSetViewport")(commands, 0, count, viewports.data()); + context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetScissor, &DeviceFunctions::cmdSetScissor, "vkCmdSetScissor")(commands, 0, count, scissors.data()); viewport = viewports.front(); scissor = scissors.front(); wrote(Mask(Viewport) | Mask(Scissor)); @@ -1691,60 +1709,60 @@ void CommandState::ExecuteCommands(const Context& context, std::uint32_t count, void CommandState::SetDepthBias(const Context& context, float constant, float clamp, float slope) { const std::array bias{constant, clamp, slope}; - apply(DepthBias, &CommandState::depthBias, bias, [](const auto& left, const auto& right) { return sameBits(left, right); }, [&] { context.tracked(&DeviceFunctions::cmdSetDepthBias, "vkCmdSetDepthBias")(commands, constant, clamp, slope); }); + apply(DepthBias, &CommandState::depthBias, bias, [](const auto& left, const auto& right) { return sameBits(left, right); }, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetDepthBias, &DeviceFunctions::cmdSetDepthBias, "vkCmdSetDepthBias")(commands, constant, clamp, slope); }); } void CommandState::SetDepthBounds(const Context& context, float minimum, float maximum) { const std::array bounds{minimum, maximum}; - apply(DepthBounds, &CommandState::depthBounds, bounds, [](const auto& left, const auto& right) { return sameBits(left, right); }, [&] { context.tracked(&DeviceFunctions::cmdSetDepthBounds, "vkCmdSetDepthBounds")(commands, minimum, maximum); }); + apply(DepthBounds, &CommandState::depthBounds, bounds, [](const auto& left, const auto& right) { return sameBits(left, right); }, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetDepthBounds, &DeviceFunctions::cmdSetDepthBounds, "vkCmdSetDepthBounds")(commands, minimum, maximum); }); } void CommandState::SetCullMode(const Context& context, VkCullModeFlags mode) { - apply(CullMode, &CommandState::cullMode, mode, std::equal_to<>{}, [&] { context.tracked(&DeviceFunctions::cmdSetCullMode, "vkCmdSetCullModeEXT")(commands, mode); }); + apply(CullMode, &CommandState::cullMode, mode, std::equal_to<>{}, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetCullModeEXT, &DeviceFunctions::cmdSetCullMode, "vkCmdSetCullModeEXT")(commands, mode); }); } void CommandState::SetFrontFace(const Context& context, VkFrontFace face) { - apply(FrontFace, &CommandState::frontFace, face, std::equal_to<>{}, [&] { context.tracked(&DeviceFunctions::cmdSetFrontFace, "vkCmdSetFrontFaceEXT")(commands, face); }); + apply(FrontFace, &CommandState::frontFace, face, std::equal_to<>{}, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetFrontFaceEXT, &DeviceFunctions::cmdSetFrontFace, "vkCmdSetFrontFaceEXT")(commands, face); }); } void CommandState::SetDepthTestEnable(const Context& context, VkBool32 enable) { - apply(DepthTest, &CommandState::depthTest, enable, std::equal_to<>{}, [&] { context.tracked(&DeviceFunctions::cmdSetDepthTestEnable, "vkCmdSetDepthTestEnableEXT")(commands, enable); }); + apply(DepthTest, &CommandState::depthTest, enable, std::equal_to<>{}, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetDepthTestEnableEXT, &DeviceFunctions::cmdSetDepthTestEnable, "vkCmdSetDepthTestEnableEXT")(commands, enable); }); } void CommandState::SetDepthBiasEnable(const Context& context, VkBool32 enable) { - apply(DepthBiasEnable, &CommandState::depthBiasEnable, enable, std::equal_to<>{}, [&] { context.tracked(&DeviceFunctions::cmdSetDepthBiasEnable, "vkCmdSetDepthBiasEnableEXT")(commands, enable); }); + apply(DepthBiasEnable, &CommandState::depthBiasEnable, enable, std::equal_to<>{}, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetDepthBiasEnableEXT, &DeviceFunctions::cmdSetDepthBiasEnable, "vkCmdSetDepthBiasEnableEXT")(commands, enable); }); } void CommandState::SetDepthWriteEnable(const Context& context, VkBool32 enable) { - apply(DepthWrite, &CommandState::depthWrite, enable, std::equal_to<>{}, [&] { context.tracked(&DeviceFunctions::cmdSetDepthWriteEnable, "vkCmdSetDepthWriteEnableEXT")(commands, enable); }); + apply(DepthWrite, &CommandState::depthWrite, enable, std::equal_to<>{}, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetDepthWriteEnableEXT, &DeviceFunctions::cmdSetDepthWriteEnable, "vkCmdSetDepthWriteEnableEXT")(commands, enable); }); } void CommandState::SetDepthCompareOp(const Context& context, VkCompareOp compare) { - apply(DepthCompare, &CommandState::depthCompare, compare, std::equal_to<>{}, [&] { context.tracked(&DeviceFunctions::cmdSetDepthCompareOp, "vkCmdSetDepthCompareOpEXT")(commands, compare); }); + apply(DepthCompare, &CommandState::depthCompare, compare, std::equal_to<>{}, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetDepthCompareOpEXT, &DeviceFunctions::cmdSetDepthCompareOp, "vkCmdSetDepthCompareOpEXT")(commands, compare); }); } void CommandState::SetDepthBoundsTestEnable(const Context& context, VkBool32 enable) { - apply(DepthBoundsTest, &CommandState::depthBoundsTest, enable, std::equal_to<>{}, [&] { context.tracked(&DeviceFunctions::cmdSetDepthBoundsTestEnable, "vkCmdSetDepthBoundsTestEnableEXT")(commands, enable); }); + apply(DepthBoundsTest, &CommandState::depthBoundsTest, enable, std::equal_to<>{}, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetDepthBoundsTestEnableEXT, &DeviceFunctions::cmdSetDepthBoundsTestEnable, "vkCmdSetDepthBoundsTestEnableEXT")(commands, enable); }); } void CommandState::SetStencilTestEnable(const Context& context, VkBool32 enable) { - apply(StencilTest, &CommandState::stencilTest, enable, std::equal_to<>{}, [&] { context.tracked(&DeviceFunctions::cmdSetStencilTestEnable, "vkCmdSetStencilTestEnableEXT")(commands, enable); }); + apply(StencilTest, &CommandState::stencilTest, enable, std::equal_to<>{}, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetStencilTestEnableEXT, &DeviceFunctions::cmdSetStencilTestEnable, "vkCmdSetStencilTestEnableEXT")(commands, enable); }); } void CommandState::SetStencilOp(const Context& context, VkStencilFaceFlags faces, VkStencilOp failOp, VkStencilOp passOp, VkStencilOp depthFailOp, VkCompareOp compareOp) { - applyFaces(StencilOpFront, faces, &CommandState::stencilOps, StencilOps{failOp, passOp, depthFailOp, compareOp}, [&](VkStencilFaceFlags needed) { context.tracked(&DeviceFunctions::cmdSetStencilOp, "vkCmdSetStencilOpEXT")(commands, needed, failOp, passOp, depthFailOp, compareOp); }); + applyFaces(StencilOpFront, faces, &CommandState::stencilOps, StencilOps{failOp, passOp, depthFailOp, compareOp}, [&](VkStencilFaceFlags needed) { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetStencilOpEXT, &DeviceFunctions::cmdSetStencilOp, "vkCmdSetStencilOpEXT")(commands, needed, failOp, passOp, depthFailOp, compareOp); }); } void CommandState::SetStencilCompareMask(const Context& context, VkStencilFaceFlags faces, std::uint32_t mask) { - applyFaces(CompareMaskFront, faces, &CommandState::compareMasks, mask, [&](VkStencilFaceFlags needed) { context.tracked(&DeviceFunctions::cmdSetStencilCompareMask, "vkCmdSetStencilCompareMask")(commands, needed, mask); }); + applyFaces(CompareMaskFront, faces, &CommandState::compareMasks, mask, [&](VkStencilFaceFlags needed) { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetStencilCompareMask, &DeviceFunctions::cmdSetStencilCompareMask, "vkCmdSetStencilCompareMask")(commands, needed, mask); }); } void CommandState::SetStencilWriteMask(const Context& context, VkStencilFaceFlags faces, std::uint32_t mask) { - applyFaces(WriteMaskFront, faces, &CommandState::writeMasks, mask, [&](VkStencilFaceFlags needed) { context.tracked(&DeviceFunctions::cmdSetStencilWriteMask, "vkCmdSetStencilWriteMask")(commands, needed, mask); }); + applyFaces(WriteMaskFront, faces, &CommandState::writeMasks, mask, [&](VkStencilFaceFlags needed) { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetStencilWriteMask, &DeviceFunctions::cmdSetStencilWriteMask, "vkCmdSetStencilWriteMask")(commands, needed, mask); }); } void CommandState::SetStencilReference(const Context& context, VkStencilFaceFlags faces, std::uint32_t reference) { - applyFaces(ReferenceFront, faces, &CommandState::references, reference, [&](VkStencilFaceFlags needed) { context.tracked(&DeviceFunctions::cmdSetStencilReference, "vkCmdSetStencilReference")(commands, needed, reference); }); + applyFaces(ReferenceFront, faces, &CommandState::references, reference, [&](VkStencilFaceFlags needed) { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetStencilReference, &DeviceFunctions::cmdSetStencilReference, "vkCmdSetStencilReference")(commands, needed, reference); }); } void CommandState::SetColorWriteMasks(const Context& context, std::span masks) { @@ -1753,7 +1771,7 @@ void CommandState::SetColorWriteMasks(const Context& context, std::span(masks.size()); std::ranges::copy(masks, value.masks.begin()); const auto covered = [](const ColorWriteMasks& known, const ColorWriteMasks& wanted) { return wanted.count <= known.count && std::equal(wanted.masks.begin(), wanted.masks.begin() + wanted.count, known.masks.begin()); }; - apply(ColorWriteMask, &CommandState::colorWriteMasks, value, covered, [&] { context.tracked(&DeviceFunctions::cmdSetColorWriteMask, "vkCmdSetColorWriteMaskEXT")(commands, 0, value.count, masks.data()); }); + apply(ColorWriteMask, &CommandState::colorWriteMasks, value, covered, [&] { context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetColorWriteMaskEXT, &DeviceFunctions::cmdSetColorWriteMask, "vkCmdSetColorWriteMaskEXT")(commands, 0, value.count, masks.data()); }); } CommandState& Recorder::GraphicsState() { @@ -1991,7 +2009,7 @@ void Recorder::flushDeferredDispatch() { auto after = std::move(open->afterRun); open->afterRun.clear(); constexpr VkAccessFlags dispatchedAccess = VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_HOST_READ_BIT; - recordBarrier(open->commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT, dispatchedAccess); + recordBarrier(live(), VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT | VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT, dispatchedAccess); CountBarriers(CommandClass::DispatchTrailing); open->coveredAccess = dispatchedAccess; overlapFlushed.fetch_add(1, std::memory_order_relaxed); @@ -2023,12 +2041,12 @@ bool Recorder::joinsRun(std::uint32_t queueKey, std::span own return std::none_of(owners.begin(), owners.end(), taken) && !runConflict(accesses); } -VkCommandBuffer Recorder::RunCommands(std::uint32_t queueKey, const void* owner, std::span accesses, bool& inRun, VkAccessFlags* coveredAccess) { +VkCommandBuffer Recorder::RunCommands(std::uint32_t queueKey, const void* owner, std::span accesses, bool& inRun, VkAccessFlags* coveredAccess, std::source_location where) { GuestMemory::AssertGpuLockHeld("Recorder::RunCommands"); inRun = joinsRun(queueKey, std::span(&owner, 1), accesses); if (!inRun) return Commands(coveredAccess); if (coveredAccess != nullptr) *coveredAccess = 0; - return open->commands; + return live(); } void Recorder::AfterRun(std::function work) { @@ -2043,12 +2061,12 @@ bool Recorder::CloseRunOwing(const void* owner) { return true; } -VkCommandBuffer Recorder::OverlapCommands(std::uint32_t queueKey, std::span owners, std::span accesses, VkAccessFlags* coveredAccess, bool& overlapped) { +VkCommandBuffer Recorder::OverlapCommands(std::uint32_t queueKey, std::span owners, std::span accesses, VkAccessFlags* coveredAccess, bool& overlapped, std::source_location where) { GuestMemory::AssertGpuLockHeld("Recorder::OverlapCommands"); overlapped = joinsRun(queueKey, owners, accesses); if (!overlapped) return Commands(coveredAccess); if (coveredAccess != nullptr) *coveredAccess = 0; - return open->commands; + return live(); } void Recorder::DeferDispatchBarrier(std::uint32_t queueKey, std::span owners, std::span accesses) { @@ -2097,17 +2115,17 @@ std::uint64_t Recorder::ReapsWithWork() { return holdCounters.reapsWithWork; } -VkCommandBuffer Recorder::Commands(VkAccessFlags* coveredAccess) { +VkCommandBuffer Recorder::Commands(VkAccessFlags* coveredAccess, std::source_location where) { ensureOpen(); flushDeferredDispatch(); // Work recorded after a draw's render pass or an inline store run must see their writes: the // pass's end and the run's trailing barrier go in first (a per-batch run waits for Submit, or // for a caller whose ranges overlap a queued store: FlushStores). - if (open->renderPass.open) endOpenRenderPass(PassBreak::Command); + if (open->renderPass.open) endOpenRenderPass(PassBreak::Command, true, where); if (open->run.open && !LabelRunsPerBatch()) closeStoreRun(); if (coveredAccess != nullptr) *coveredAccess = open->coveredAccess; open->coveredAccess = 0; - return open->commands; + return live(); } void Recorder::MarkCovered(VkAccessFlags access) { @@ -2168,18 +2186,25 @@ bool Recorder::RenderPassOpen() const { return open != nullptr && open->renderPass.open; } -void Recorder::endOpenRenderPass(PassBreak by, bool barrier) { +void Recorder::endOpenRenderPass(PassBreak by, bool barrier, std::source_location where) { ++passGeneration; auto& pass = open->renderPass; if (open->segmentActive) endSegment(*open); - EndRenderPass(context, open->commands); + EndRenderPass(context, live()); // The pass's attachment and shader writes are visible to everything recorded after it (the // host sees them at the batch's fence). if (barrier) { - recordBarrier(open->commands, PassEndBarrier.srcStage, PassEndBarrier.dstStage, PassEndBarrier.srcAccess, PassEndBarrier.dstAccess); + recordBarrier(live(), PassEndBarrier.srcStage, PassEndBarrier.dstStage, PassEndBarrier.srcAccess, PassEndBarrier.dstAccess); CountBarriers(CommandClass::Draw); } - if (pass.afterPass) pass.afterPass(open->graphicsState); + std::exception_ptr failure; + if (pass.afterPass) { + try { + pass.afterPass(open->graphicsState); + } catch (...) { + failure = std::current_exception(); + } + } EndGpuTiming(pass.timing); open->coveredAccess = barrier ? VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT : 0; open->hostReadOwed = true; @@ -2187,7 +2212,6 @@ void Recorder::endOpenRenderPass(PassBreak by, bool barrier) { pass = {}; pass.closedBy = by; PerformanceTrace::Amount(PassBreakScopeNames[static_cast(by)], 1); - std::exception_ptr failure; for (auto& work : after) { try { work(*this); @@ -2265,18 +2289,138 @@ void Recorder::recordKeyStores(bool forWriter) { if (forWriter) keyStoreRunsForWriter.fetch_add(1, std::memory_order_relaxed); } +bool Recorder::defers() const { + static const bool recordInline = [] { + const char* value = std::getenv("APS5_RECORD_INLINE"); + return value != nullptr && std::strcmp(value, "0") != 0; + }(); + return deferring && !recordInline && !RuntimeSwitches::Set(RuntimeSwitch::DirectBatches); +} + +VkCommandBuffer Recorder::allocateBegun() { + VkCommandBufferAllocateInfo allocation{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; + allocation.commandPool = context.pool; + allocation.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + allocation.commandBufferCount = 1; + VkCommandBuffer commands = VK_NULL_HANDLE; + Check(context.Function("vkAllocateCommandBuffers")(context.device, &allocation, &commands), "vkAllocateCommandBuffers recorder"); + VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + const auto result = function(beginCommandBuffer, "vkBeginCommandBuffer")(commands, &begin); + if (result != VK_SUCCESS) { + context.Function("vkFreeCommandBuffers")(context.device, context.pool, 1, &commands); + Check(result, "vkBeginCommandBuffer recorder"); + } + return commands; +} + +VkCommandBuffer Recorder::Begin(CommandStream& stream) { + if (open == nullptr || open->stream.get() != &stream) throw std::logic_error("AGC graphics: a stream that is not the open batch's asked for a command buffer"); + open->real = allocateBegun(); + demotedBatches.fetch_add(1, std::memory_order_relaxed); + return open->real; +} + +void Recorder::poisonOpen() noexcept { + if (open == nullptr || open->unwound) return; + open->unwound = true; + if (open->stream != nullptr && open->stream->Materialized() == VK_NULL_HANDLE) open->stream->Poison(unwoundDrawReason); +} + +std::exception_ptr Recorder::failureOf(const Batch& batch) const { + if (batch.stream != nullptr && batch.stream->Poisoned()) return batch.stream->Reason(); + return batch.unwound ? unwoundDrawReason : nullptr; +} + +std::unique_ptr Recorder::makeExecutor() { + ReplayEntryPoints entry; + entry.device = context.device; + entry.createPool = context.Function("vkCreateCommandPool"); + entry.destroyPool = context.Function("vkDestroyCommandPool"); + entry.allocate = context.Function("vkAllocateCommandBuffers"); + entry.free = context.Function("vkFreeCommandBuffers"); + entry.begin = context.Function("vkBeginCommandBuffer"); + entry.end = context.Function("vkEndCommandBuffer"); + static const bool thread = [] { + const char* value = std::getenv("APS5_ENCODE_THREAD"); + return value != nullptr && std::strcmp(value, "0") != 0; + }(); + if (!thread) return std::make_unique(BorrowReplayPool(entry, context.pool)); + const auto family = queueFamily; + return std::make_unique([entry, family] { return CreateReplayPool(entry, family); }); +} + +Recorder::StreamStatistics Recorder::StreamCounts() const { + StreamStatistics counts; + counts.deferred = deferredBatches.load(std::memory_order_relaxed); + counts.direct = directBatches.load(std::memory_order_relaxed); + counts.refused = budget.Refusals(); + counts.demoted = demotedBatches.load(std::memory_order_relaxed); + counts.poisoned = poisonedBatches.load(std::memory_order_relaxed); + counts.replayed = replayedBatches.load(std::memory_order_relaxed); + counts.replayFailed = failedReplays.load(std::memory_order_relaxed); + return counts; +} + +void Recorder::noteDemotion(const Demotion& demotion) { + if (demotion.command == nullptr) return; + std::string key = demotion.command; + if (demotion.chained != VK_STRUCTURE_TYPE_MAX_ENUM) key += "/" + std::to_string(static_cast(demotion.chained)); + std::lock_guard lock(demotionMutex); + ++demotions[key]; +} + +std::string Recorder::StreamReport() const { + const auto counts = StreamCounts(); + std::string demoted; + for (const auto& [key, count] : Demotions()) demoted += " " + key + " " + std::to_string(count); + char line[512]; + std::snprintf(line, sizeof(line), "[recorder] batches: %llu deferred, %llu direct (%llu refused by admission), %llu demoted (by command/sType:%s), %llu poisoned; %llu replayed, %llu replays failed\n", static_cast(counts.deferred), static_cast(counts.direct), static_cast(counts.refused), static_cast(counts.demoted), demoted.empty() ? " none" : demoted.c_str(), static_cast(counts.poisoned), static_cast(counts.replayed), static_cast(counts.replayFailed)); + return line; +} + +std::vector> Recorder::Demotions() const { + std::lock_guard lock(demotionMutex); + return {demotions.begin(), demotions.end()}; +} + +void Recorder::overlayListed() { + directCommands = realCommands; + streamedCommands = StreamedCommands(); + const auto* table = context.Table(); + if (table == nullptr) return; + listedFunctions = *table; + context.OverlayCommands(directCommands, realCommands); + context.OverlayCommands(streamedCommands, realCommands); + directCommands.listed = table; + streamedCommands.listed = table; +} + void Recorder::ensureOpen() { GuestMemory::AssertGpuLockHeld("Recorder::Commands"); if (open == nullptr) { + if (realResolved && !context.OverlayMatches(listedFunctions)) overlayListed(); ++passGeneration; auto batch = std::make_unique(); batch->sampleBatch = ++sampleBatches; try { - VkCommandBufferAllocateInfo allocation{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; - allocation.commandPool = context.pool; - allocation.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; - allocation.commandBufferCount = 1; - Check(context.Function("vkAllocateCommandBuffers")(context.device, &allocation, &batch->commands), "vkAllocateCommandBuffers recorder"); + batch->pool = context.pool; + if (defers() && budget.TryOpen()) { + try { + batch->stream = std::make_unique(realCommands, &budget, static_cast(this)); + } catch (...) { + budget.Retired(0); + throw; + } + batch->commands = batch->stream->Handle(); + batch->functions = &streamedCommands; + deferredBatches.fetch_add(1, std::memory_order_relaxed); + } else { + batch->real = allocateBegun(); + batch->commands = batch->real; + batch->functions = realResolved ? &directCommands : nullptr; + directBatches.fetch_add(1, std::memory_order_relaxed); + } if (!fenceless) { if (!spare.empty()) { batch->fence = spare.back(); @@ -2286,11 +2430,8 @@ void Recorder::ensureOpen() { Check(context.Function("vkCreateFence")(context.device, &info, nullptr, &batch->fence), "vkCreateFence recorder"); } } - VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; - begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; - Check(function(beginCommandBuffer, "vkBeginCommandBuffer")(batch->commands, &begin), "vkBeginCommandBuffer recorder"); static const bool suppress = std::getenv("APS5_NO_STATE_SUPPRESSION") == nullptr; - batch->graphicsState.Begin(batch->commands, suppress); + batch->graphicsState.Begin(batch->commands, suppress, batch->functions); } catch (...) { release(*batch); throw; @@ -2305,17 +2446,17 @@ void Recorder::ensureOpen() { for (auto& slot : retention) slot = {}; ++retentionEpoch; } - open->predictedSerial = submissions + 1; + open->predictedSerial = sealedThrough + 1; try { if (open->queue == 0) { - WriteCheckpointSerial(context, open->commands, open->predictedSerial, open->queue); + WriteCheckpointSerial(context, live(), open->predictedSerial, open->queue); if (BatchBeginTokensEnabled()) { const AgcDriver::FaultToken beginToken = AgcDriver::ClaimBatchBeginToken(AgcDriver::FaultTokenRing::Instance(), open->predictedSerial); NoteFaultToken(beginToken); - WriteCheckpointMarker(context, open->commands, beginToken, open->queue); - WriteNvCheckpointToken(context, open->commands, beginToken, open->queue); + WriteCheckpointMarker(context, live(), beginToken, open->queue); + WriteNvCheckpointToken(context, live(), beginToken, open->queue); } - } else WriteCheckpointSentinel(context, open->commands); + } else WriteCheckpointSentinel(context, live()); } catch (...) { } if (PerformanceTrace::Recording()) { @@ -2369,7 +2510,7 @@ void Recorder::RecordStore(VkBuffer buffer, VkDeviceSize offset, std::spancommands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); + recordBarrier(live(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); CountBarriers(CommandClass::LabelRun); run.open = true; storeRuns.fetch_add(1, std::memory_order_relaxed); @@ -2394,7 +2535,7 @@ void Recorder::RecordStore(VkBuffer buffer, VkDeviceSize offset, std::spancommands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); + recordBarrier(live(), VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); CountBarriers(CommandClass::LabelRun); storeWawBarriers.fetch_add(1, std::memory_order_relaxed); } @@ -2416,7 +2557,7 @@ void Recorder::recordBarrier(VkCommandBuffer commands, VkPipelineStageFlags sour void Recorder::flushPendingStore() { auto& run = open->run; if (run.bytes.empty()) return; - function(cmdUpdateBuffer, "vkCmdUpdateBuffer")(open->commands, run.buffer, run.offset, run.bytes.size(), run.bytes.data()); + function(cmdUpdateBuffer, "vkCmdUpdateBuffer")(live(), run.buffer, run.offset, run.bytes.size(), run.bytes.data()); run.recorded.emplace_back(run.buffer, run.offset, run.offset + run.bytes.size()); run.storedBytes += run.bytes.size(); run.bytes.clear(); @@ -2435,7 +2576,7 @@ bool Recorder::closeStoreRun(bool atSubmit) { if (!open->keyStores.empty()) recordKeyStores(true); const bool passEndLast = open->renderPass.open && !open->renderPass.afterPass && open->renderPass.afterEnd.empty(); if (open->renderPass.open) endOpenRenderPass(PassBreak::Label); - const auto commands = open->commands; + const auto commands = live(); run.timing = beginTiming(ClassKey(CommandClass::LabelRun)); if (BarrierValidate()) { std::vector> ranges; @@ -2524,7 +2665,7 @@ bool Recorder::closeStoreRun(bool atSubmit) { } flushPendingStore(); // The run's stores are visible to the host and to everything recorded after them. - recordBarrier(open->commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT); + recordBarrier(live(), VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT | VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT); CountBarriers(CommandClass::LabelRun); EndGpuTiming(run.timing, run.storedBytes); run.timing = NoTiming; @@ -2815,7 +2956,7 @@ std::uint32_t Recorder::BeginInPassGpuTiming(std::uint64_t key) { std::uint32_t Recorder::beginTiming(std::uint64_t key) { const bool full = GpuTimingEnabled(); if (!full && !(key == BatchTimingKey && BatchStampsEnabled())) return NoTiming; - const auto commands = open->commands; + const auto commands = live(); const std::uint32_t queryCount = full ? MaxTimedRanges * 2 : 2; if (open->queries == VK_NULL_HANDLE) { if (!sparePools.empty()) { @@ -2848,7 +2989,7 @@ std::uint32_t Recorder::beginTiming(std::uint64_t key) { void Recorder::EndGpuTiming(std::uint32_t index, std::uint64_t bytes) { if (index == NoTiming || open == nullptr || open->queries == VK_NULL_HANDLE) return; if (index < open->timedBytes.size()) open->timedBytes[index] += bytes; - context.Function("vkCmdWriteTimestamp")(open->commands, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, open->queries, index * 2 + 1); + context.Function("vkCmdWriteTimestamp")(live(), VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, open->queries, index * 2 + 1); } bool Recorder::RecordDispatchArguments(VkCommandBuffer commands, VkDeviceAddress source, VkDeviceAddress arguments, const std::array* threadGroup) { @@ -2985,7 +3126,7 @@ std::uint64_t Recorder::SamplesTotal() { void Recorder::NoteSampledDraw(VkCommandBuffer commands) { if (open == nullptr) return; if (segmentMode()) { - if (countingSamples && commands == open->commands && !open->segmentActive) beginSegment(*open); + if (countingSamples && open->commands == commands && !open->segmentActive) beginSegment(*open); return; } if (open->sampleActive) open->samplesDrawn = true; @@ -3212,7 +3353,8 @@ void Recorder::takeSegmentPool(Batch& batch) { void Recorder::beginSegment(Batch& batch) { Require(batch.segments != VK_NULL_HANDLE && batch.segmentNext < SegmentSlots, "an occlusion segment begins without a reset query slot"); batch.segmentSlot = batch.segmentNext++; - function(cmdBeginQuery, "vkCmdBeginQuery")(batch.commands, batch.segments, batch.segmentSlot, context.occlusionQueryPrecise ? VK_QUERY_CONTROL_PRECISE_BIT : 0u); + const auto flags = context.occlusionQueryPrecise ? VK_QUERY_CONTROL_PRECISE_BIT : 0u; + function(cmdBeginQuery, "vkCmdBeginQuery")(batch.commands, batch.segments, batch.segmentSlot, flags); batch.segmentActive = true; } @@ -3301,7 +3443,7 @@ void Recorder::foldQueuedDumps(VkCommandBuffer commands, std::spancommands; + const auto commands = live(); const auto count = static_cast(std::min(pendingSamples.size(), SegmentFoldCapacity)); recordBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); copySegments(commands, count); @@ -3332,7 +3474,9 @@ void Recorder::foldSamples(Batch& batch, VkDeviceAddress target, std::uint32_t b std::size_t done = 0; do { const auto count = static_cast(std::min(SampleFoldCapacity, pendingSamples.size() - done)); - if (done != 0) recordBarrier(commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); + if (done != 0) { + recordBarrier(commands, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_TRANSFER_WRITE_BIT); + } for (std::uint32_t i = 0; i < count; ++i) { const auto& segment = pendingSamples[done + i]; copy(commands, segment.handle, segment.slot, 1, sampleCounter->Handle(), 16 + 8 * i, 8, VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT); @@ -3515,7 +3659,6 @@ bool Recorder::RecordBoundChangedCopy(VkCommandBuffer commands, BoundWords resul boundChangedCopyState = -1; VkShaderModule module = VK_NULL_HANDLE; try { - cmdPushChangedCopySet = context.Function("vkCmdPushDescriptorSetKHR"); std::array bindings{}; for (std::uint32_t binding = 0; binding < bindings.size(); ++binding) bindings[binding] = {binding, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, nullptr}; VkDescriptorSetLayoutCreateInfo setInfo{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; @@ -3576,7 +3719,7 @@ bool Recorder::RecordBoundChangedCopy(VkCommandBuffer commands, BoundWords resul writes[binding].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; writes[binding].pBufferInfo = &infos[binding]; } - cmdPushChangedCopySet(commands, VK_PIPELINE_BIND_POINT_COMPUTE, boundChangedCopyLayout, 0, static_cast(writes.size()), writes.data()); + context.Function("vkCmdPushDescriptorSetKHR")(commands, VK_PIPELINE_BIND_POINT_COMPUTE, boundChangedCopyLayout, 0, static_cast(writes.size()), writes.data()); const Parameters parameters{bases[0], bases[1], bases[2], count, alwaysCopy ? 1u : 0u, counter != VK_NULL_HANDLE ? 1u : 0u}; function(cmdPushConstants, "vkCmdPushConstants")(commands, boundChangedCopyLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(parameters), ¶meters); function(cmdDispatch, "vkCmdDispatch")(commands, (count + GroupSize - 1) / GroupSize, 1, 1); @@ -3873,15 +4016,22 @@ std::shared_ptr Recorder::mirrorDrawInput(std::map DrawInputBudget && pool.recency.front() != entry->first) eraseDrawSnapshot(drawSnapshots.find(pool.recency.front())); const auto commands = Commands(); + Keep(host); + Keep(mirror); const auto timing = BeginGpuTiming(CommandClass::InputMirror); CopyBuffer(context, commands, host->Handle(), 0, mirror->Handle(), 0, copied); RecordMemoryBarrier(context, commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT | VK_ACCESS_INDEX_READ_BIT); CountBarriers(CommandClass::InputMirror); EndGpuTiming(timing, copied); - Keep(host); - Keep(mirror); - pool.bytes += bytes; - drawInputMirrorBytes += bytes; + ChangeUndoneOnDiscard( + [&] { + pool.bytes += bytes; + drawInputMirrorBytes += bytes; + }, + [this, key = entry->first, published = mirror.get()] { + const auto current = drawSnapshots.find(key); + if (current != drawSnapshots.end() && current->second.mirror.get() == published) dropDrawInputMirror(current); + }); return mirror; } @@ -4235,7 +4385,7 @@ void Recorder::OnWriteComplete(std::uint64_t address, std::size_t bytes, std::fu } bool Recorder::noteWrite(std::uint64_t address, std::size_t bytes, bool ownLabel, int value, std::int64_t word) { - CaptureTrace::Log("buffer-write batch=%llu address=%llx bytes=%zu label=%d", static_cast(submissions + 1), static_cast(address), bytes, ownLabel); + CaptureTrace::Log("buffer-write batch=%llu address=%llx bytes=%zu label=%d", static_cast(sealedThrough + 1), static_cast(address), bytes, ownLabel); if (bytes == 0) return false; GuestMemory::ForgetKnownZero(address, bytes); ensureOpen(); @@ -4568,7 +4718,7 @@ bool Recorder::ReadTracking() { } void Recorder::NotePendingRead(std::uint64_t address, std::size_t bytes, ReadKind kind) { - CaptureTrace::Log("buffer-read batch=%llu address=%llx bytes=%zu kind=%d", static_cast(submissions + 1), static_cast(address), bytes, static_cast(kind)); + CaptureTrace::Log("buffer-read batch=%llu address=%llx bytes=%zu kind=%d", static_cast(sealedThrough + 1), static_cast(address), bytes, static_cast(kind)); if (bytes == 0 || !ReadTrackingEnabled()) return; ensureOpen(); open->reads.push_back({address, address + bytes, kind}); @@ -4579,7 +4729,7 @@ void Recorder::NotePendingReads(std::span(submissions + 1), static_cast(begin), static_cast(end - begin), static_cast(kind)); + CaptureTrace::Log("buffer-read batch=%llu address=%llx bytes=%llu kind=%d", static_cast(sealedThrough + 1), static_cast(begin), static_cast(end - begin), static_cast(kind)); if (end > begin) open->reads.push_back({begin, end, kind}); } readsNoted.Add(ranges.size()); @@ -4670,7 +4820,7 @@ std::optional Recorder::DescribePendingRead(std::uint if (bytes == 0) return std::nullopt; const auto end = address + bytes; if (open != nullptr) { - if (const auto kind = readOverlap(*open, address, end)) return PendingReadInfo{submissions + 1, open->queue, *kind, true, false}; + if (const auto kind = readOverlap(*open, address, end)) return PendingReadInfo{sealedThrough + 1, open->queue, *kind, true, false}; } for (auto it = inFlight.rbegin(); it != inFlight.rend(); ++it) { if (const auto kind = readOverlap(**it, address, end)) return PendingReadInfo{(*it)->serial, (*it)->queue, *kind, false, signaled(**it)}; @@ -4701,7 +4851,7 @@ std::optional Recorder::DescribePendingWrite(std::ui const bool syncAll = !SyncThroughEnabled(); const auto allBatches = inFlight.size() + (open != nullptr ? 1 : 0); if (open != nullptr) { - if (const auto* range = firstOverlap(*open)) return PendingWriteInfo{submissions + 1, true, false, range->first, range->second, inFlight.size() + 1}; + if (const auto* range = firstOverlap(*open)) return PendingWriteInfo{sealedThrough + 1, true, false, range->first, range->second, inFlight.size() + 1}; } std::size_t finished = inFlight.size(); for (auto it = inFlight.rbegin(); it != inFlight.rend(); ++it, --finished) { @@ -4717,6 +4867,9 @@ std::optional Recorder::DescribePendingWrite(std::ui bool Recorder::HasCompletions() const { if (open != nullptr && (!open->completions.empty() || !open->validations.empty())) return true; + for (const auto& batch : sealedBatches) { + if (!batch->completions.empty() || !batch->validations.empty()) return true; + } for (const auto& batch : inFlight) { if (!batch->completions.empty() || !batch->validations.empty()) return true; } @@ -4760,9 +4913,7 @@ void Recorder::NoteLabel(std::uint64_t address, std::span bytes wideLabelBytes = std::max(wideLabelBytes, bytes.size()); recordedWideLabels.store(wideLabels.size(), std::memory_order_relaxed); } - if (activeRecorder == this && pendingLabelSince.load(std::memory_order_relaxed) == NoPendingLabel) { - pendingLabelSince.store(std::chrono::steady_clock::now().time_since_epoch().count(), std::memory_order_release); - } + markLabel(*open); noteWriteOn(*open, address, bytes.size(), true); } @@ -4863,8 +5014,8 @@ bool Recorder::unsignaled(std::uint64_t serial) const { } void Recorder::AfterCompletions(std::uint64_t address, std::span bytes, std::uint64_t stamp, std::uint32_t queue, bool storedOnGpu) { - Require(open != nullptr || !inFlight.empty(), "no batch to append a completion label to"); - Batch& batch = open != nullptr ? *open : *inFlight.back(); + Require(open != nullptr || !sealedBatches.empty() || !inFlight.empty(), "no batch to append a completion label to"); + Batch& batch = open != nullptr ? *open : !sealedBatches.empty() ? *sealedBatches.back() : *inFlight.back(); std::vector copy(bytes.begin(), bytes.end()); // The store bypasses the flush hook: it runs inside finish() under the mutex, and the hook would // find this very range noted (or a later label to it) and sync re-entrantly. Stamped like every @@ -4902,23 +5053,35 @@ void Recorder::AfterCompletions(std::uint64_t address, std::span action) { if (Idle()) return false; - Batch& batch = open != nullptr ? *open : *inFlight.back(); + Batch& batch = open != nullptr ? *open : !sealedBatches.empty() ? *sealedBatches.back() : *inFlight.back(); batch.completions.push_back(std::move(action)); ++batch.completionLabelCount; completionLabels.fetch_add(1, std::memory_order_acq_rel); - if (&batch == open.get() && activeRecorder == this && pendingLabelSince.load(std::memory_order_relaxed) == NoPendingLabel) { - pendingLabelSince.store(std::chrono::steady_clock::now().time_since_epoch().count(), std::memory_order_release); - } + if (!batch.submitted) markLabel(batch); return true; } +void Recorder::markLabel(Batch& batch) { + if (batch.labelSince == NoPendingLabel) batch.labelSince = std::chrono::steady_clock::now().time_since_epoch().count(); + if (activeRecorder == this && pendingLabelSince.load(std::memory_order_relaxed) == NoPendingLabel) pendingLabelSince.store(batch.labelSince, std::memory_order_release); +} + +void Recorder::refreshLabelMark() noexcept { + if (activeRecorder != this) return; + auto since = NoPendingLabel; + const auto older = [&](std::int64_t mark) { + if (mark != NoPendingLabel && (since == NoPendingLabel || mark < since)) since = mark; + }; + for (const auto& batch : sealedBatches) older(batch->labelSince); + if (open != nullptr) older(open->labelSince); + pendingLabelSince.store(since, std::memory_order_release); +} + void Recorder::NoteWrittenBack(std::uint64_t address, std::size_t bytes) { Recorder* recorder = activeRecorder; if (recorder == nullptr || bytes == 0) return; @@ -4999,9 +5162,61 @@ void Recorder::Submit() { // count behind, and the callers that act on it would otherwise take the mutex for nothing at // every packet or submission end until a real batch is next submitted. if (activeRecorder == this) workSinceSubmit.store(0, std::memory_order_relaxed); + if (sealedBatches.empty()) { + if (auto batch = sealOpen()) queue(std::move(batch)); + return; + } + std::exception_ptr failure; + try { + Seal(); + } catch (...) { + failure = std::current_exception(); + } + while (!sealedBatches.empty()) { + try { + QueueSealed(); + } catch (...) { + if (failure == nullptr) failure = std::current_exception(); + } + } + if (failure != nullptr) std::rethrow_exception(failure); +} + +std::uint64_t Recorder::Seal() { + auto batch = sealOpen(); + if (batch == nullptr) return 0; + const auto serial = batch->sealedSerial; + try { + sealedBatches.push_back(std::move(batch)); + } catch (...) { + unqueued(std::move(batch), std::current_exception()); + throw; + } + return serial; +} + +std::unique_ptr Recorder::sealOpen() { dropStaleHoldKept(); - if (open == nullptr) return; - GuestMemory::AssertGpuLockHeld("Recorder::Submit"); + if (open == nullptr) return nullptr; + GuestMemory::AssertGpuLockHeld("Recorder::Seal"); + struct DiscardUnsealed { + Recorder& recorder; + std::unique_ptr& batch; + ~DiscardUnsealed() { + if (batch != nullptr) recorder.discard(std::move(batch)); + } + }; + if (const auto reason = failureOf(*open)) { + auto failed = std::move(open); + const DiscardUnsealed discardFailed{*this, failed}; + poisonedBatches.fetch_add(1, std::memory_order_relaxed); + std::rethrow_exception(reason); + } + if (latch.Failed() || latch.DeviceLost()) { + auto failed = std::move(open); + const DiscardUnsealed discardFailed{*this, failed}; + latch.ThrowFor(sealedThrough + 1); + } flushDeferredDispatch(); if (!open->keyStores.empty()) recordKeyStores(false); if (open->renderPass.open) endOpenRenderPass(PassBreak::NewBatch); @@ -5019,7 +5234,7 @@ void Recorder::Submit() { if (open->hostReadOwed && !hostReadCovered) { // A fence makes nothing visible to the host: a lean draw's writes (no download barrier of // its own) get the batch's one here. - recordBarrier(open->commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT); + recordBarrier(live(), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_HOST_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_HOST_READ_BIT); CountBarriers(CommandClass::Draw); } EndGpuTiming(open->batchTiming); @@ -5030,37 +5245,106 @@ void Recorder::Submit() { for (const auto& [begin, end] : notedReads(*open)) open->readGeneration = std::max(open->readGeneration, GuestMemory::CollectWrites(begin, end - begin)); } auto batch = std::move(open); + const DiscardUnsealed discardUnsealed{*this, batch}; + if (const auto reason = failureOf(*batch)) { + poisonedBatches.fetch_add(1, std::memory_order_relaxed); + std::rethrow_exception(reason); + } + const std::uint64_t serial = ++sealedThrough; + try { + batch->sealedSerial = serial; + if (batch->stream != nullptr && batch->stream->Materialized() == VK_NULL_HANDLE) { + batch->sealed = std::make_shared(serial, *batch->stream, realCommands, latch, &budget); + executor->Execute(batch->sealed); + } else { + if (batch->stream != nullptr) noteDemotion(batch->stream->DemotedBy()); + Check(function(endCommandBuffer, "vkEndCommandBuffer")(batch->real), "vkEndCommandBuffer recorder"); + } + } catch (...) { + if (latch.FailedSerial() > serial) sealedThrough = serial - 1; + throw; + } + batch->hold = std::exchange(submitHold, VK_NULL_HANDLE); + batch->holdValue = submitHoldValue; + return std::move(batch); +} + +void Recorder::unqueued(std::unique_ptr batch, std::exception_ptr reason) noexcept { + const auto serial = batch->sealedSerial; + if (!latch.DeviceLost() && latch.FailedSerial() > serial) { + if (sealedThrough == serial && open == nullptr) { + sealedThrough = serial - 1; + if (submitHold == VK_NULL_HANDLE) { + submitHold = batch->hold; + submitHoldValue = batch->holdValue; + } + } else { + latch.Fail(serial, reason); + } + } + discard(std::move(batch)); +} + +std::uint64_t Recorder::QueueSealed() { + PerformanceTimer frameTiming("Recorder.QueueSealed"); + if (sealedBatches.empty()) return 0; + GuestMemory::AssertGpuLockHeld("Recorder::QueueSealed"); + auto batch = std::move(sealedBatches.front()); + sealedBatches.pop_front(); + return queue(std::move(batch)); +} + +std::uint64_t Recorder::queue(std::unique_ptr batch) { + const std::uint64_t serial = batch->sealedSerial; + VkCommandBuffer submitted = batch->real; + std::string tokensStr; + try { + if (latch.DeviceLost() || latch.FailedSerial() < serial) latch.ThrowFor(serial); + if (serial != submissions + 1) throw std::logic_error("AGC graphics: sealed batch " + std::to_string(serial) + " was queued after batch " + std::to_string(submissions)); + if (batch->sealed != nullptr) { + try { + submitted = batch->sealed->Await(); + } catch (...) { + failedReplays.fetch_add(1, std::memory_order_relaxed); + throw; + } + replayedBatches.fetch_add(1, std::memory_order_relaxed); + batch->stream->ReleaseMemory(); + } + if (injectedSubmitFailures.load(std::memory_order_relaxed) != 0 && injectedSubmitFailures.fetch_sub(1, std::memory_order_relaxed) != 0) throw std::runtime_error("vkQueueSubmit recorder: injected failure"); + if (CheckpointMarkersEnabled() && batch->queue == 0 && batch->predictedSerial != 0) { + Require(batch->predictedSerial == serial, "Recorder::Submit submit serial mismatch"); + try { + if (const auto snapshot = GuestBufferMemory::TrySnapshotAddressSpace(); snapshot.has_value()) AgcDriver::SubmissionSnapshots::DeviceSnapshots().NoteSubmit(serial, snapshot->first, snapshot->second, AgcDriver::SubmitBracket{serial, CompletedThrough(), batch->firstToken, batch->lastToken}); + } catch (...) { + } + } + tokensStr = "["; + for (std::size_t i = 0; i < batch->drawTraceTokens.size(); ++i) { + if (i > 0) tokensStr += ","; + tokensStr += std::to_string(batch->drawTraceTokens[i]); + } + tokensStr += "]"; + CaptureTrace::Log("submit batch=%llu tokens=%s", static_cast(serial), tokensStr.c_str()); + DestroyDeferredAtIdle(context); + } catch (...) { + unqueued(std::move(batch), std::current_exception()); + throw; + } struct DiscardUnsubmitted { Recorder& recorder; std::unique_ptr& batch; ~DiscardUnsubmitted() { if (batch != nullptr && !batch->submitted) recorder.discard(std::move(batch)); } - } discardUnsubmitted{*this, batch}; - Check(function(endCommandBuffer, "vkEndCommandBuffer")(batch->commands), "vkEndCommandBuffer recorder"); - if (injectedSubmitFailures.load(std::memory_order_relaxed) != 0 && injectedSubmitFailures.fetch_sub(1, std::memory_order_relaxed) != 0) throw std::runtime_error("vkQueueSubmit recorder: injected failure"); + }; + const DiscardUnsubmitted discardUnsubmitted{*this, batch}; VkSubmitInfo submission{VK_STRUCTURE_TYPE_SUBMIT_INFO}; submission.commandBufferCount = 1; - submission.pCommandBuffers = &batch->commands; - // The timeline reaches this batch's serial when it completes (see WaitSerial). - const std::uint64_t serial = submissions + 1; - if (CheckpointMarkersEnabled() && batch->queue == 0 && batch->predictedSerial != 0) { - Require(batch->predictedSerial == serial, "Recorder::Submit submit serial mismatch"); - try { - if (const auto snapshot = GuestBufferMemory::TrySnapshotAddressSpace(); snapshot.has_value()) AgcDriver::SubmissionSnapshots::DeviceSnapshots().NoteSubmit(serial, snapshot->first, snapshot->second, AgcDriver::SubmitBracket{serial, CompletedThrough(), batch->firstToken, batch->lastToken}); - } catch (...) { - } - } - std::string tokensStr = "["; - for (std::size_t i = 0; i < batch->drawTraceTokens.size(); ++i) { - if (i > 0) tokensStr += ","; - tokensStr += std::to_string(batch->drawTraceTokens[i]); - } - tokensStr += "]"; - CaptureTrace::Log("submit batch=%llu tokens=%s", static_cast(serial), tokensStr.c_str()); + submission.pCommandBuffers = &submitted; VkTimelineSemaphoreSubmitInfoKHR timelineInfo{VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO_KHR}; - const VkSemaphore hold = std::exchange(submitHold, VK_NULL_HANDLE); - const std::uint64_t holdValue = submitHoldValue; + const VkSemaphore hold = batch->hold; + const std::uint64_t holdValue = batch->holdValue; VkPipelineStageFlags holdStage = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; if (hold != VK_NULL_HANDLE) { submission.waitSemaphoreCount = 1; @@ -5076,15 +5360,27 @@ void Recorder::Submit() { submission.pSignalSemaphores = &timeline; } if (hold != VK_NULL_HANDLE || timeline != VK_NULL_HANDLE) submission.pNext = &timelineInfo; - DestroyDeferredAtIdle(context); const auto submitStart = std::chrono::steady_clock::now(); batch->submitStarted.store(true, std::memory_order_release); const auto result = function(queueSubmit, "vkQueueSubmit")(context.queue, 1, &submission, batch->fence); + const bool queuedNothing = result != VK_SUCCESS && result != VK_ERROR_DEVICE_LOST; + if (batch->sealed != nullptr && !queuedNothing) batch->sealed->Returned(result); + std::exception_ptr refused; + if (result != VK_SUCCESS) { + try { + Check(result, "vkQueueSubmit recorder"); + } catch (...) { + refused = std::current_exception(); + } + if (batch->sealed == nullptr && result == VK_ERROR_DEVICE_LOST) latch.LoseDevice(refused); + } if (result == VK_ERROR_DEVICE_LOST) { const auto idle = context.Function("vkDeviceWaitIdle")(context.device); if (idle != VK_SUCCESS && idle != VK_ERROR_DEVICE_LOST) std::terminate(); + if (batch->sealed != nullptr) batch->sealed->DeviceIdleAfterLoss(); } - Check(result, "vkQueueSubmit recorder"); + if (queuedNothing) unqueued(std::move(batch), refused); + if (refused != nullptr) std::rethrow_exception(refused); if (batch->guestWork) LibcRunReportMilestone_nid_no_patch(2); batch->submitted = true; batch->serial = ++submissions; @@ -5113,7 +5409,8 @@ void Recorder::Submit() { } inFlight.push_back(std::move(batch)); inFlightKeptBytes += inFlight.back()->keptBytes; - if (activeRecorder == this) pendingLabelSince.store(NoPendingLabel, std::memory_order_release); + refreshLabelMark(); + return serial; } std::uint64_t Recorder::SubmitAndEpoch() { @@ -5122,7 +5419,7 @@ std::uint64_t Recorder::SubmitAndEpoch() { } std::uint64_t Recorder::OpenBatchSerial() { - return open != nullptr ? submissions + 1 : 0; + return open != nullptr ? sealedThrough + 1 : 0; } namespace { @@ -5148,16 +5445,33 @@ struct RestoreSyncSite { // The timeline wait itself, on handles copied out of the recorder: the caller holds no mutex, and // the recorder may be torn down meanwhile (its destructor waits for the registered waiters to // leave after completing every batch, so the handles stay valid until this returns). -VkResult WaitTimeline(VkDevice device, VkSemaphore timeline, PFN_vkWaitSemaphoresKHR waitSemaphores, std::uint64_t serial) { +constexpr std::uint64_t TimelineSliceNanos = 100'000'000ull; +constexpr unsigned TimelineSlicesPerReport = 50; + +VkResult WaitTimelineSlice(VkDevice device, VkSemaphore timeline, PFN_vkWaitSemaphoresKHR waitSemaphores, std::uint64_t serial, std::uint64_t nanos) { VkSemaphoreWaitInfoKHR wait{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO_KHR}; wait.semaphoreCount = 1; wait.pSemaphores = &timeline; wait.pValues = &serial; - auto result = waitSemaphores(device, &wait, 5'000'000'000ull); - for (int waited = 5; result == VK_TIMEOUT; waited += 5) { + return waitSemaphores(device, &wait, nanos); +} + +std::exception_ptr LatchStops(const FailureLatch& latch, std::uint64_t serial) noexcept { + try { + latch.ThrowFor(serial); + } catch (...) { + return std::current_exception(); + } + return nullptr; +} + +VkResult WaitTimeline(VkDevice device, VkSemaphore timeline, PFN_vkWaitSemaphoresKHR waitSemaphores, std::uint64_t serial, const FailureLatch& latch, std::exception_ptr& stopped) { + auto result = WaitTimelineSlice(device, timeline, waitSemaphores, serial, TimelineSliceNanos); + for (unsigned slices = 1; result == VK_TIMEOUT; ++slices) { + if (stopped = LatchStops(latch, serial); stopped != nullptr) return VK_TIMEOUT; // As for the fence wait in finish(): a hung batch is reported every 5 s. - std::fprintf(stderr, "[gpu] recorded batch %llu still running on the GPU after %d s (timeline wait)\n", static_cast(serial), waited); - result = waitSemaphores(device, &wait, 5'000'000'000ull); + if (slices % TimelineSlicesPerReport == 0) std::fprintf(stderr, "[gpu] recorded batch %llu still running on the GPU after %u s (timeline wait)\n", static_cast(serial), slices / 10); + result = WaitTimelineSlice(device, timeline, waitSemaphores, serial, TimelineSliceNanos); } return result; } @@ -5170,11 +5484,13 @@ void Recorder::WaitSerial(std::uint64_t serial) { static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; const auto start = profile ? std::chrono::steady_clock::now() : std::chrono::steady_clock::time_point{}; const UnlockedWaiter waiter{id}; - const auto result = WaitTimeline(context.device, timeline, context.Function("vkWaitSemaphoresKHR"), serial); + std::exception_ptr stopped; + const auto result = WaitTimeline(context.device, timeline, context.Function("vkWaitSemaphoresKHR"), serial, latch, stopped); if (profile) { unlockedWaits.fetch_add(1, std::memory_order_relaxed); unlockedWaitedUs.fetch_add(static_cast(std::chrono::duration_cast(std::chrono::steady_clock::now() - start).count()), std::memory_order_relaxed); } + if (stopped != nullptr) std::rethrow_exception(stopped); Check(result, "vkWaitSemaphoresKHR recorder"); } @@ -5182,12 +5498,15 @@ bool Recorder::WaitSerialFor(std::uint64_t serial, std::uint64_t timeoutNanos) { PerformanceTimer frameTiming("Recorder.WaitSerialFor"); if (timeline == VK_NULL_HANDLE || serial == 0) return false; const UnlockedWaiter waiter{id}; - VkSemaphoreWaitInfoKHR wait{VK_STRUCTURE_TYPE_SEMAPHORE_WAIT_INFO_KHR}; - wait.semaphoreCount = 1; - wait.pSemaphores = &timeline; - wait.pValues = &serial; - const auto result = context.Function("vkWaitSemaphoresKHR")(context.device, &wait, timeoutNanos); - if (result == VK_TIMEOUT) return false; + const auto waitSemaphores = context.Function("vkWaitSemaphoresKHR"); + auto left = timeoutNanos; + auto result = WaitTimelineSlice(context.device, timeline, waitSemaphores, serial, std::min(left, TimelineSliceNanos)); + while (result == VK_TIMEOUT) { + if (const auto stopped = LatchStops(latch, serial); stopped != nullptr) std::rethrow_exception(stopped); + left -= std::min(left, TimelineSliceNanos); + if (left == 0) return false; + result = WaitTimelineSlice(context.device, timeline, waitSemaphores, serial, std::min(left, TimelineSliceNanos)); + } Check(result, "vkWaitSemaphoresKHR submission progress"); return true; } @@ -5222,12 +5541,16 @@ void Recorder::Sync() { PerformanceTimer frameTiming("Recorder.Sync"); const auto source = std::exchange(announcedSource, 4); const void* site = std::exchange(announcedSite, nullptr); - Submit(); + std::exception_ptr failure; + try { + Submit(); + } catch (...) { + failure = std::current_exception(); + } // Counted only when something is waited for: an idle recorder's Sync is free and would only // swamp the site table with the callers that check nothing first. const auto previousSite = inFlight.empty() ? activeSyncSite : BeginSyncSite(source, site != nullptr ? site : __builtin_return_address(0)); RestoreSyncSite restore{previousSite}; - std::exception_ptr failure; bool draining = validationFailure != nullptr; while (!inFlight.empty()) { auto batch = std::move(inFlight.front()); @@ -5235,7 +5558,10 @@ void Recorder::Sync() { try { finish(std::move(batch), true, source, false, !draining); } catch (...) { - if (validationFailure == nullptr) throw; + if (validationFailure == nullptr) { + if (!failure) failure = std::current_exception(); + break; + } if (!failure) failure = std::current_exception(); draining = true; } @@ -5418,6 +5744,7 @@ bool Recorder::syncThroughUnlocked(std::uint64_t address, std::uint64_t end, int // teardown running under the GpuMutex (the driver's drain and failure paths reset the device // under it; a worker dropping its last device reference outside its lock would not). const auto myId = id; + const auto& waitLatch = latch; const auto device = context.device; const auto semaphore = timeline; const auto waitSemaphores = context.Function("vkWaitSemaphoresKHR"); @@ -5453,11 +5780,12 @@ bool Recorder::syncThroughUnlocked(std::uint64_t address, std::uint64_t end, int auto waited = start; auto& mutex = GuestMemory::GpuMutex(); VkResult result = VK_SUCCESS; + std::exception_ptr stopped; { // Registered before the release: a teardown can only start once the mutex is free. const UnlockedWaiter waiter{myId}; mutex.unlock(); - result = WaitTimeline(device, semaphore, waitSemaphores, targetSerial); + result = WaitTimeline(device, semaphore, waitSemaphores, targetSerial, waitLatch, stopped); // Read before the relock: the GPU wait, not the wait for the mutex behind it. if (profile || trace) waited = std::chrono::steady_clock::now(); } @@ -5500,9 +5828,11 @@ bool Recorder::syncThroughUnlocked(std::uint64_t address, std::uint64_t end, int if (!RecorderAlive(myId)) { // Torn down meanwhile: its destructor's Sync() ran every completion, nothing is pending. ++holdCounters.hookUnlockedTornDown; + if (stopped != nullptr) std::rethrow_exception(stopped); Check(result, "vkWaitSemaphoresKHR recorder"); return true; } + if (stopped != nullptr) std::rethrow_exception(stopped); Check(result, "vkWaitSemaphoresKHR recorder"); if (validationFailure != nullptr) DrainValidationFailure(); // The completions up to the target, under the mutex again; the fences are signaled, so the @@ -5646,14 +5976,19 @@ void Recorder::finish(std::unique_ptr batch, bool wait, int source, bool AgcDriver::ProfilePrint_nid_no_patch("[recorder] %llu syncs waited %.1f s for the GPU in total (sources, count/wait: idle %llu/%.1fs, pending write %llu/%.1fs, recorded store %llu/%.1fs, address-based %llu/%.1fs, other %llu/%.1fs); hook %llu calls, %llu locked; %llu targeted syncs left %llu batches in flight; snapshot %llu rebuilds %.0f ms, %llu notes covered; %llu unlocked timeline waits %.1f s; %llu submissions, %zu label entries, %llu completion labels pending; fence waits by thread (count/wait):%s; top sync sites (source@caller syncs/batches/wait):%s; under holds (cumulative): %llu completions ran %.0f ms (kept objects released %.0f ms), pending-write syncs from completions: %llu skipped, %llu waited %.0f ms; %llu reaps (%llu with work) retired %llu batches in %.0f ms; hook waits unlocked %llu / %.0f ms GPU (pending write %llu / %.0f ms, recorded store %llu / %.0f ms) + %.0f ms relock (%llu found the recorder torn down), locked %llu; deferred releases: on the release thread %llu batches (%llu objects) in %.0f ms, inline %llu batches (%llu objects) in %.0f ms (%llu batches over the queue bound of %zu), queue max %llu batches, %llu pending\n",static_cast(waits), waitedMs / 1000, static_cast(syncCounts[0]), syncWaitedMs[0] / 1000, static_cast(syncCounts[1]), syncWaitedMs[1] / 1000, static_cast(syncCounts[2]), syncWaitedMs[2] / 1000, static_cast(syncCounts[3]), syncWaitedMs[3] / 1000, static_cast(syncCounts[4]), syncWaitedMs[4] / 1000, static_cast(hookCalls.load()), static_cast(hookLocks.load()), static_cast(targetedSyncs.load()), static_cast(batchesLeftInFlight.load()), static_cast(snapshotRebuilds), snapshotRebuildMs, static_cast(snapshotCovered), static_cast(unlockedWaits.load()), unlockedWaitedUs.load() / 1e6, static_cast(recorder.submissions), recorder.PendingLabels(), static_cast(completionLabels.load()), ThreadSyncReport().c_str(), SyncSiteReport().c_str(), static_cast(h.completions), h.completionMs, h.keptReleaseMs, static_cast(h.completionSyncsSkipped), static_cast(h.completionSyncsWaited), h.completionSyncWaitMs, static_cast(h.reaps), static_cast(h.reapsWithWork), static_cast(h.reapBatches), h.reapMs, static_cast(h.hookUnlockedWaits), h.hookUnlockedWaitMs, static_cast(h.hookUnlockedWaitsBySource[1]), h.hookUnlockedWaitMsBySource[1], static_cast(h.hookUnlockedWaitsBySource[2]), h.hookUnlockedWaitMsBySource[2], h.hookRelockMs, static_cast(h.hookUnlockedTornDown), static_cast(h.hookLockedWaits), static_cast(threadReleases.load()), static_cast(threadObjects.load()), threadReleaseUs.load() / 1000.0, static_cast(inlineReleases.load()), static_cast(inlineObjects.load()), inlineReleaseUs.load() / 1000.0, static_cast(inlineOverBound.load()), ReleaseQueueBound(), static_cast(releaseQueueMax.load()), static_cast(deferredPending.load())); AgcDriver::ProfilePrint_nid_no_patch("[recorder] completion label stores: %llu run, %llu skipped (no CPU write-back overlapped them); %llu counted pending at a write-back; %llu write-backs over a tracked label; %llu write-back completions pending\n", static_cast(completionStoresRun.load()), static_cast(completionStoresSkipped.load()), static_cast(completionLabelsCountedLate.load()), static_cast(writeBacksOverLabels.load()), static_cast(writeBackCompletions.load())); AgcDriver::ProfilePrint_nid_no_patch("[recorder] submits %llu, vkQueueSubmit mean %.1f us, max %.1f us; command buffers freed at batch release %llu, fences kept for reuse %llu\n", static_cast(submitCount), submitCount != 0 ? submitUs / static_cast(submitCount) : 0.0, submitMaxUs, static_cast(commandBuffersFreed.load()), static_cast(fencesKept.load())); + if (recorder.deferring) AgcDriver::ProfilePrint_nid_no_patch("%s", recorder.StreamReport().c_str()); const auto reads = Recorder::ReadCounts(); AgcDriver::ProfilePrint_nid_no_patch("[recorder] in-place reads: %llu noted, %llu queries, hits by reader: dispatch element %llu, gpu copy %llu, address-based %llu, indirect %llu, storage upload %llu, copy source %llu, draw input %llu, address-based read-only %llu; %llu hits on signaled batches ignored\n", static_cast(reads.noted), static_cast(reads.queries), static_cast(reads.hits[0]), static_cast(reads.hits[1]), static_cast(reads.hits[2]), static_cast(reads.hits[3]), static_cast(reads.hits[4]), static_cast(reads.hits[5]), static_cast(reads.hits[6]), static_cast(reads.hits[7]), static_cast(reads.staleIgnored)); } } } report{profile, source, waitStart, *this, signaledAtStart}; + std::exception_ptr stopped; const auto waitTimeline = [&] { VkResult reached = VK_SUCCESS; - if (batch->serial > reachedSerial && batch->serial > readTimeline()) reached = WaitTimeline(context.device, timeline, context.Function("vkWaitSemaphoresKHR"), batch->serial); + if (batch->serial > reachedSerial && batch->serial > readTimeline()) { + reached = WaitTimeline(context.device, timeline, context.Function("vkWaitSemaphoresKHR"), batch->serial, latch, stopped); + if (stopped != nullptr) return VK_ERROR_DEVICE_LOST; + } if (reached == VK_SUCCESS) reachedSerial = std::max(reachedSerial, batch->serial); return reached; }; @@ -5668,10 +6003,15 @@ void Recorder::finish(std::unique_ptr batch, bool wait, int source, bool const auto idle = context.Function("vkDeviceWaitIdle")(context.device); Check(idle, "vkDeviceWaitIdle after recorder fence failure"); } + if (batch->sealed != nullptr) batch->sealed->GpuDone(); if (result != VK_SUCCESS) { + removeLabels(*batch); release(*batch); + if (stopped != nullptr) std::rethrow_exception(stopped); Check(result, fenceless ? "vkWaitSemaphoresKHR recorder" : "vkWaitForFences recorder"); } + } else if (batch->sealed != nullptr) { + batch->sealed->GpuDone(); } if (!publishActions || validationFailure != nullptr) { batch->validations.clear(); @@ -5778,8 +6118,11 @@ void Recorder::finish(std::unique_ptr batch, bool wait, int source, bool } void Recorder::discard(std::unique_ptr batch) noexcept { + if (batch->sealed != nullptr && !batch->sealed->SubmitReturned()) batch->sealed->NotSubmitted(); std::erase_if(pendingSamples, [&](const SampleSegment& sample) { return sample.batch == batch->sampleBatch; }); std::erase_if(batch->foldedSamples, [&](const SampleSegment& sample) { return sample.batch == batch->sampleBatch; }); + if (open != nullptr) std::erase_if(open->foldedSamples, [&](const SampleSegment& sample) { return sample.batch == batch->sampleBatch; }); + for (const auto& sealedBatch : sealedBatches) std::erase_if(sealedBatch->foldedSamples, [&](const SampleSegment& sample) { return sample.batch == batch->sampleBatch; }); if (pendingSamples.size() + batch->foldedSamples.size() <= pendingSamples.capacity()) { pendingSamples.insert(pendingSamples.begin(), std::make_move_iterator(batch->foldedSamples.begin()), std::make_move_iterator(batch->foldedSamples.end())); } else { @@ -5800,7 +6143,7 @@ void Recorder::discard(std::unique_ptr batch) noexcept { if (batch->completionStoreCount != 0) SubtractCount(completionStores, batch->completionStoreCount); if (batch->writeBackCompletionCount != 0) SubtractCount(writeBackCompletions, batch->writeBackCompletionCount); if (batch->validationCount != 0) SubtractCount(validationCompletions, batch->validationCount); - if (activeRecorder == this) pendingLabelSince.store(NoPendingLabel, std::memory_order_release); + refreshLabelMark(); release(*batch); try { publishPendingWrites(); @@ -5843,10 +6186,21 @@ void Recorder::release(Batch& batch) noexcept { batch.segments = VK_NULL_HANDLE; batch.segmentPool.reset(); static const bool profile = std::getenv("APS5_PROFILE_DRAW") != nullptr; - if (batch.commands != VK_NULL_HANDLE) { - context.Function("vkFreeCommandBuffers")(context.device, context.pool, 1, &batch.commands); + if (batch.real != VK_NULL_HANDLE) { + context.Function("vkFreeCommandBuffers")(context.device, batch.pool != VK_NULL_HANDLE ? batch.pool : context.pool, 1, &batch.real); if (profile) commandBuffersFreed.fetch_add(1, std::memory_order_relaxed); } + batch.real = VK_NULL_HANDLE; + if (batch.sealed != nullptr) { + if (batch.sealed->Commands() != VK_NULL_HANDLE) { + executor->Retire(batch.sealed->Commands(), batch.sealed->Worker()); + if (profile) commandBuffersFreed.fetch_add(1, std::memory_order_relaxed); + } + batch.sealed.reset(); + } else if (batch.stream != nullptr) { + budget.Retired(batch.stream->Charged()); + } + batch.stream.reset(); batch.commands = VK_NULL_HANDLE; if (batch.fence != VK_NULL_HANDLE && spare.size() < 64 && function(resetFences, "vkResetFences")(context.device, 1, &batch.fence) == VK_SUCCESS) { try { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp index 6c0c9ee117e6..4aac726400eb 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/Resources.cpp @@ -318,6 +318,8 @@ void FillDeviceFunctions(const Context& context, DeviceFunctions& functions) { functions.cmdCopyBufferToImage = context.Function("vkCmdCopyBufferToImage"); functions.cmdCopyImageToBuffer = context.Function("vkCmdCopyImageToBuffer"); functions.cmdClearColorImage = context.Function("vkCmdClearColorImage"); + functions.cmdBeginQuery = context.Function("vkCmdBeginQuery"); + functions.cmdEndQuery = context.Function("vkCmdEndQuery"); functions.updateDescriptorSets = context.Function("vkUpdateDescriptorSets"); functions.allocateDescriptorSets = context.Function("vkAllocateDescriptorSets"); functions.getFenceStatus = context.Function("vkGetFenceStatus"); diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/RuntimeSwitches.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/RuntimeSwitches.cpp index 274cec6fb75c..5e83adc38055 100644 --- a/core/libs/prx/libSceAgcDriver/Graphics/src/RuntimeSwitches.cpp +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/RuntimeSwitches.cpp @@ -37,6 +37,11 @@ constexpr std::array SwitchNames{ "APS5_NO_STAGE_POOL_REUSE", "APS5_INDEX_IN_PLACE_BEHIND_WRITER", "APS5_WIDE_LIBRARY_KEYS", + "APS5_NO_RECORD_ENCODER", + "APS5_NO_ADAPTIVE_ENCODER", + "APS5_QUIESCED_SEGMENTS", + "APS5_DIRECT_BATCHES", + "APS5_NO_STREAMED_PUSH_DESCRIPTORS", "APS5_NO_WIDE_TABLE_COPY_HLE", "APS5_NO_SAMPLED_LOOKUP_MEMO", "APS5_NO_DCC_MIP_FAST_CLEAR", @@ -70,6 +75,11 @@ struct SwitchValues { std::getenv("APS5_NO_STAGE_POOL_REUSE") != nullptr, std::getenv("APS5_INDEX_IN_PLACE_BEHIND_WRITER") != nullptr, std::getenv("APS5_WIDE_LIBRARY_KEYS") != nullptr, + std::getenv("APS5_NO_RECORD_ENCODER") != nullptr, + std::getenv("APS5_NO_ADAPTIVE_ENCODER") != nullptr, + std::getenv("APS5_QUIESCED_SEGMENTS") != nullptr, + std::getenv("APS5_DIRECT_BATCHES") != nullptr, + std::getenv("APS5_NO_STREAMED_PUSH_DESCRIPTORS") != nullptr, std::getenv("APS5_NO_WIDE_TABLE_COPY_HLE") != nullptr, std::getenv("APS5_NO_SAMPLED_LOOKUP_MEMO") != nullptr, std::getenv("APS5_NO_DCC_MIP_FAST_CLEAR") != nullptr, @@ -154,6 +164,12 @@ bool InArm(const AbSchedule::Arm& arm, RuntimeSwitch id) { namespace RuntimeSwitches { +namespace { + +std::atomic generation{0}; + +} + const char* Name(RuntimeSwitch id) { return SwitchNames.at(static_cast(id)); } @@ -163,7 +179,11 @@ bool Set(RuntimeSwitch id) { } void Assign(RuntimeSwitch id, bool set) { - Values().set.at(static_cast(id)).store(set, std::memory_order_relaxed); + if (Values().set.at(static_cast(id)).exchange(set, std::memory_order_relaxed) != set) generation.fetch_add(1, std::memory_order_release); +} + +std::uint64_t Generation() { + return generation.load(std::memory_order_acquire); } std::optional Find(std::string_view name) { diff --git a/core/libs/prx/libSceAgcDriver/Graphics/src/SealedBatch.cpp b/core/libs/prx/libSceAgcDriver/Graphics/src/SealedBatch.cpp new file mode 100644 index 000000000000..056911d47e0e --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/Graphics/src/SealedBatch.cpp @@ -0,0 +1,390 @@ +#include "prx/libSceAgcDriver/Graphics/include/SealedBatch.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Context.hpp" +#include +#include +#include +#include + +namespace AgcDriver::Graphics { + +namespace { + +[[noreturn]] void refuse(const char* message) { + std::fprintf(stderr, "AGC graphics: %s\n", message); + std::fflush(stderr); + std::abort(); +} + +std::exception_ptr submitError(VkResult result) { + return std::make_exception_ptr(std::runtime_error("AGC graphics: vkQueueSubmit failed with VkResult " + std::to_string(static_cast(result)))); +} + +} + +bool FailureLatch::Fail(std::uint64_t serial, std::exception_ptr reason) noexcept { + std::lock_guard lock(mutex); + const auto current = failedSerial.load(std::memory_order_relaxed); + if (serial >= current) return false; + if (current == NoSerial || error == nullptr) error = reason; + failedSerial.store(serial, std::memory_order_release); + return true; +} + +bool FailureLatch::LoseDevice(std::exception_ptr reason) noexcept { + std::lock_guard lock(mutex); + if (error == nullptr) error = reason; + return !deviceLost.exchange(true, std::memory_order_acq_rel); +} + +void FailureLatch::Shutdown() noexcept { + shuttingDown.store(true, std::memory_order_release); +} + +std::exception_ptr FailureLatch::Error() const { + std::lock_guard lock(mutex); + return error; +} + +void FailureLatch::ThrowFor(std::uint64_t serial) const { + if (DeviceLost() || FailedSerial() <= serial) { + if (const auto reason = Error(); reason != nullptr) std::rethrow_exception(reason); + throw BatchCancelled(); + } + if (ShuttingDown()) throw RecordingShutDown(); +} + +WorkBudget::Mode WorkBudget::Choose() const noexcept { + return encoding.load(std::memory_order_relaxed) >= limits.encodingBatches ? Mode::Direct : Mode::Deferred; +} + +void WorkBudget::Open(const FailureLatch& latch, std::uint64_t serial, std::chrono::nanoseconds slice) { + std::unique_lock lock(mutex); + if (!room()) { + roomWaits.fetch_add(1, std::memory_order_relaxed); + while (!retired.wait_for(lock, slice, [&] { return room(); })) latch.ThrowFor(serial); + } + outstanding.fetch_add(1, std::memory_order_relaxed); +} + +bool WorkBudget::TryOpen() noexcept { + std::lock_guard lock(mutex); + if (encoding.load(std::memory_order_relaxed) >= limits.encodingBatches || !room()) { + refusals.fetch_add(1, std::memory_order_relaxed); + return false; + } + outstanding.fetch_add(1, std::memory_order_relaxed); + return true; +} + +void WorkBudget::Sealed() noexcept { + encoding.fetch_add(1, std::memory_order_relaxed); +} + +void WorkBudget::ReplayReleased() noexcept { + encoding.fetch_sub(1, std::memory_order_relaxed); +} + +void WorkBudget::Charge(std::size_t charge) noexcept { + bytes.fetch_add(charge, std::memory_order_relaxed); +} + +void WorkBudget::Retired(std::size_t charge) noexcept { + { + std::lock_guard lock(mutex); + bytes.fetch_sub(charge, std::memory_order_relaxed); + outstanding.fetch_sub(1, std::memory_order_relaxed); + } + retired.notify_all(); +} + +void WorkBudget::Uncharge(std::size_t charge) noexcept { + { + std::lock_guard lock(mutex); + bytes.fetch_sub(charge, std::memory_order_relaxed); + } + retired.notify_all(); +} + +SealedBatch::SealedBatch(std::uint64_t serial, CommandStream& stream, const CommandFunctions& real, FailureLatch& latch, WorkBudget* budget) : serial(serial), stream(stream), real(real), latch(latch), budget(budget) { + stream.Seal(); + charged = stream.Charged(); + if (budget != nullptr) budget->Sealed(); +} + +SealedBatch::~SealedBatch() { + if (!ReplayReleased()) refuse("a sealed batch was destroyed while a replay could still read its stream"); + if (!SubmitReturned()) refuse("a sealed batch was destroyed before its submission returned or was skipped"); + if (!GpuReleased()) refuse("a sealed batch was destroyed before the GPU released it"); +} + +bool SealedBatch::Superseded() const noexcept { + return latch.DeviceLost() || latch.ShuttingDown() || latch.FailedSerial() < serial; +} + +bool SealedBatch::Claim() noexcept { + auto expected = static_cast(Unclaimed); + return replay.compare_exchange_strong(expected, Claimed, std::memory_order_acq_rel); +} + +void SealedBatch::Encoded(VkCommandBuffer buffer, std::uint32_t by) noexcept { + if (replay.load(std::memory_order_relaxed) != Claimed) refuse("a batch was reported encoded by a worker that had not claimed it"); + if (cancelRequested.load(std::memory_order_acquire)) releaseReplay(Outcome::Cancelled, std::make_exception_ptr(BatchCancelled()), buffer, by); + else releaseReplay(Outcome::Encoded, nullptr, buffer, by); +} + +void SealedBatch::Failed(std::exception_ptr reason, VkCommandBuffer buffer, std::uint32_t by) noexcept { + if (replay.load(std::memory_order_relaxed) != Claimed) refuse("a batch was reported failed by a worker that had not claimed it"); + latch.Fail(serial, reason); + releaseReplay(Outcome::ReplayFailed, reason, buffer, by); +} + +void SealedBatch::Cancel() noexcept { + cancelRequested.store(true, std::memory_order_release); + if (Claim()) releaseReplay(Outcome::Cancelled, std::make_exception_ptr(BatchCancelled()), VK_NULL_HANDLE, 0); +} + +void SealedBatch::releaseReplay(Outcome result, std::exception_ptr reason, VkCommandBuffer buffer, std::uint32_t by) noexcept { + commands = buffer; + worker = by; + { + std::lock_guard lock(errorMutex); + error = reason; + } + if (budget != nullptr) budget->ReplayReleased(); + outcome.store(result, std::memory_order_release); + replay.store(Released, std::memory_order_release); + replay.notify_all(); + maybeRetire(); +} + +void SealedBatch::AwaitReplayReleased() noexcept { + for (auto state = replay.load(std::memory_order_acquire); state != Released; state = replay.load(std::memory_order_acquire)) replay.wait(state, std::memory_order_acquire); +} + +VkCommandBuffer SealedBatch::Await() { + AwaitReplayReleased(); + if (outcome.load(std::memory_order_acquire) == Outcome::Encoded) return commands; + if (const auto reason = Error(); reason != nullptr) std::rethrow_exception(reason); + throw BatchCancelled(); +} + +void SealedBatch::Returned(VkResult result) noexcept { + if (!ReplayReleased()) refuse("a batch's submission returned before its replay released it"); + if (result == VK_SUCCESS) { + outcome.store(Outcome::Submitted, std::memory_order_release); + } else if (result == VK_ERROR_DEVICE_LOST) { + const auto reason = submitError(result); + { + std::lock_guard lock(errorMutex); + error = reason; + } + latch.LoseDevice(reason); + outcome.store(Outcome::DeviceLost, std::memory_order_release); + } else { + const auto reason = submitError(result); + { + std::lock_guard lock(errorMutex); + error = reason; + } + latch.Fail(serial, reason); + outcome.store(Outcome::SubmitFailed, std::memory_order_release); + gpuReleased.store(true, std::memory_order_release); + } + submitReturned.store(true, std::memory_order_release); + maybeRetire(); +} + +void SealedBatch::NotSubmitted() noexcept { + AwaitReplayReleased(); + if (outcome.load(std::memory_order_acquire) == Outcome::Encoded) outcome.store(Outcome::Cancelled, std::memory_order_release); + gpuReleased.store(true, std::memory_order_release); + submitReturned.store(true, std::memory_order_release); + maybeRetire(); +} + +void SealedBatch::GpuDone() noexcept { + if (outcome.load(std::memory_order_acquire) == Outcome::DeviceLost) return; + gpuReleased.store(true, std::memory_order_release); + maybeRetire(); +} + +void SealedBatch::DeviceIdleAfterLoss() noexcept { + if (!latch.DeviceLost()) refuse("a batch was released as idle after device loss while the device was not lost"); + gpuReleased.store(true, std::memory_order_release); + maybeRetire(); +} + +void SealedBatch::maybeRetire() noexcept { + if (!Retirable() || retiredCharge.exchange(true, std::memory_order_acq_rel)) return; + if (budget != nullptr) budget->Retired(charged); +} + +std::exception_ptr SealedBatch::Error() const { + std::lock_guard lock(errorMutex); + return error; +} + +void ReplayBatch(SealedBatch& batch, CommandBufferPool& pool, std::uint32_t worker) noexcept { + if (batch.Superseded()) { + batch.Cancel(); + return; + } + if (!batch.Claim()) return; + VkCommandBuffer commands = VK_NULL_HANDLE; + try { + commands = pool.Begin(); + Replay(batch.Stream(), commands, batch.Real()); + pool.End(commands); + batch.Encoded(commands, worker); + } catch (...) { + if (commands != VK_NULL_HANDLE) pool.Recycle(commands); + batch.Failed(std::current_exception(), VK_NULL_HANDLE, worker); + } +} + +void InlineExecutor::Execute(std::shared_ptr batch) noexcept { + ReplayBatch(*batch, *pool, 0); +} + +void InlineExecutor::Retire(VkCommandBuffer commands, std::uint32_t) noexcept { + if (commands != VK_NULL_HANDLE) pool->Recycle(commands); +} + +SingleExecutor::SingleExecutor(PoolFactory makePool) : thread([this, makePool = std::move(makePool)]() mutable { run(std::move(makePool)); }) {} + +SingleExecutor::~SingleExecutor() { + Shutdown(); +} + +void SingleExecutor::Execute(std::shared_ptr batch) noexcept { + { + std::lock_guard lock(mutex); + if (!stopping) { + queue.push_back(std::move(batch)); + batch = nullptr; + } + } + if (batch != nullptr) { + batch->Cancel(); + return; + } + wake.notify_one(); +} + +void SingleExecutor::Retire(VkCommandBuffer commands, std::uint32_t) noexcept { + if (commands == VK_NULL_HANDLE) return; + { + std::lock_guard lock(mutex); + recycled.push_back(commands); + } + wake.notify_one(); +} + +void SingleExecutor::Shutdown() noexcept { + { + std::lock_guard lock(mutex); + stopping = true; + } + wake.notify_one(); + if (thread.joinable() && thread.get_id() != std::this_thread::get_id()) thread.join(); +} + +void SingleExecutor::run(PoolFactory makePool) noexcept { + std::unique_ptr pool; + std::exception_ptr poolError; + try { + pool = makePool(); + if (pool == nullptr) throw std::runtime_error("AGC graphics: the replay worker's command pool factory returned no pool"); + } catch (...) { + poolError = std::current_exception(); + } + std::deque> work; + std::vector returned; + for (;;) { + bool stop = false; + { + std::unique_lock lock(mutex); + wake.wait(lock, [&] { return stopping || !queue.empty() || !recycled.empty(); }); + work.swap(queue); + returned.swap(recycled); + stop = stopping; + } + for (const auto commands : returned) { + if (pool != nullptr) pool->Recycle(commands); + } + returned.clear(); + for (auto& batch : work) { + if (stop) { + batch->Cancel(); + } else if (pool == nullptr) { + if (batch->Claim()) batch->Failed(poolError, VK_NULL_HANDLE, 0); + } else { + ReplayBatch(*batch, *pool, 0); + replayed.fetch_add(1, std::memory_order_relaxed); + } + batch.reset(); + } + work.clear(); + if (stop) break; + } + pool.reset(); +} + +namespace { + +class ReplayBufferPool final : public CommandBufferPool { +public: + ReplayBufferPool(const ReplayEntryPoints& entry, VkCommandPool pool, bool owned) : entry(entry), pool(pool), owned(owned) {} + void Create(std::uint32_t queueFamily) { + VkCommandPoolCreateInfo info{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; + info.queueFamilyIndex = queueFamily; + Check(entry.createPool(entry.device, &info, nullptr, &pool), "vkCreateCommandPool replay"); + } + ~ReplayBufferPool() override { + if (owned && pool != VK_NULL_HANDLE) entry.destroyPool(entry.device, pool, nullptr); + } + ReplayBufferPool(const ReplayBufferPool&) = delete; + ReplayBufferPool& operator=(const ReplayBufferPool&) = delete; + VkCommandBuffer Begin() override { + VkCommandBufferAllocateInfo allocation{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; + allocation.commandPool = pool; + allocation.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; + allocation.commandBufferCount = 1; + VkCommandBuffer commands = VK_NULL_HANDLE; + Check(entry.allocate(entry.device, &allocation, &commands), "vkAllocateCommandBuffers replay"); + VkCommandBufferBeginInfo begin{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT; + const auto result = entry.begin(commands, &begin); + if (result != VK_SUCCESS) { + Recycle(commands); + Check(result, "vkBeginCommandBuffer replay"); + } + return commands; + } + void End(VkCommandBuffer commands) override { + Check(entry.end(commands), "vkEndCommandBuffer replay"); + } + void Recycle(VkCommandBuffer commands) noexcept override { + if (commands != VK_NULL_HANDLE) entry.free(entry.device, pool, 1, &commands); + } + +private: + ReplayEntryPoints entry; + VkCommandPool pool; + bool owned; +}; + +} + +std::unique_ptr BorrowReplayPool(const ReplayEntryPoints& entry, VkCommandPool pool) { + return std::make_unique(entry, pool, false); +} + +std::unique_ptr CreateReplayPool(const ReplayEntryPoints& entry, std::uint32_t queueFamily) { + auto owner = std::make_unique(entry, VK_NULL_HANDLE, true); + owner->Create(queueFamily); + return owner; +} + + +} diff --git a/core/libs/prx/libSceAgcDriver/tests/CommandThunks.cpp b/core/libs/prx/libSceAgcDriver/tests/CommandThunks.cpp new file mode 100644 index 000000000000..b76f9ee10f3a --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/CommandThunks.cpp @@ -0,0 +1,1557 @@ +#include "prx/libSceAgcDriver/Graphics/include/CommandList.hpp" +#include "FakeHandles.hpp" +#include "prx/libSceAgcDriver/Graphics/include/CommandStream.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Context.hpp" +#include "prx/libSceAgcDriver/Graphics/include/RuntimeSwitches.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +template +void fillBytes(std::vector& values, int byte) { + if (!values.empty()) std::memset(static_cast(values.data()), byte, values.size() * sizeof(T)); +} + +} + +namespace AgcDriver::Graphics { + +std::uint64_t& DeviceProcLookups() { + thread_local std::uint64_t count = 0; + return count; +} + +} + +namespace { + +using AgcDriver::Graphics::CommandFunctions; +using AgcDriver::Graphics::CommandId; +using AgcDriver::Graphics::CommandStream; +using AgcDriver::Graphics::StreamMaterializer; + +void Require(bool condition, const std::string& message) { + if (!condition) { + std::fprintf(stderr, "command thunks: %s\n", message.c_str()); + throw std::runtime_error(message); + } +} + +template +bool Throws(Body&& body) { + try { + body(); + } catch (const Exception&) { + return true; + } + return false; +} + +std::vector log; + + +std::uintptr_t id(VkCommandBuffer commands) { + return reinterpret_cast(commands) >> 4; +} + +template +void note(const char* name, VkCommandBuffer commands, const T&... values) { + std::ostringstream text; + text << name << '@' << id(commands); + ((text << ' ' << values), ...); + log.push_back(text.str()); +} + +VKAPI_ATTR void VKAPI_CALL draw(VkCommandBuffer commands, std::uint32_t vertices, std::uint32_t instances, std::uint32_t firstVertex, std::uint32_t firstInstance) { + note("draw", commands, vertices, instances, firstVertex, firstInstance); +} + +VKAPI_ATTR void VKAPI_CALL dispatch(VkCommandBuffer commands, std::uint32_t x, std::uint32_t y, std::uint32_t z) { + note("dispatch", commands, x, y, z); +} + +VKAPI_ATTR void VKAPI_CALL bindPipeline(VkCommandBuffer commands, VkPipelineBindPoint point, VkPipeline pipeline) { + note("bindPipeline", commands, point, reinterpret_cast(pipeline)); +} + +VKAPI_ATTR void VKAPI_CALL setViewport(VkCommandBuffer commands, std::uint32_t first, std::uint32_t count, const VkViewport* viewports) { + std::ostringstream text; + for (std::uint32_t index = 0; index < count; ++index) text << viewports[index].x << ',' << viewports[index].width << ';'; + note("setViewport", commands, first, count, text.str()); +} + +VKAPI_ATTR void VKAPI_CALL setScissorWithCount(VkCommandBuffer commands, std::uint32_t count, const VkRect2D* scissors) { + std::ostringstream text; + for (std::uint32_t index = 0; index < count; ++index) text << scissors[index].offset.x << ',' << scissors[index].extent.width << ';'; + note("setScissorWithCount", commands, count, text.str()); +} + +VKAPI_ATTR void VKAPI_CALL pushConstants(VkCommandBuffer commands, VkPipelineLayout layout, VkShaderStageFlags stages, std::uint32_t offset, std::uint32_t size, const void* values) { + std::string bytes(static_cast(values), size); + note("pushConstants", commands, reinterpret_cast(layout), stages, offset, size, bytes); +} + +VKAPI_ATTR void VKAPI_CALL bindDescriptorSets(VkCommandBuffer commands, VkPipelineBindPoint point, VkPipelineLayout layout, std::uint32_t first, std::uint32_t count, const VkDescriptorSet* sets, std::uint32_t offsets, const std::uint32_t* dynamicOffsets) { + std::ostringstream text; + for (std::uint32_t index = 0; index < count; ++index) text << reinterpret_cast(sets[index]) << ';'; + for (std::uint32_t index = 0; index < offsets; ++index) text << dynamicOffsets[index] << ':'; + note("bindDescriptorSets", commands, point, reinterpret_cast(layout), first, count, offsets, text.str()); +} + +VKAPI_ATTR void VKAPI_CALL pipelineBarrier(VkCommandBuffer commands, VkPipelineStageFlags source, VkPipelineStageFlags destination, VkDependencyFlags dependencies, std::uint32_t memory, const VkMemoryBarrier* memoryBarriers, std::uint32_t buffers, const VkBufferMemoryBarrier* bufferBarriers, std::uint32_t images, const VkImageMemoryBarrier* imageBarriers) { + std::ostringstream text; + for (std::uint32_t index = 0; index < memory; ++index) text << memoryBarriers[index].srcAccessMask << '>' << memoryBarriers[index].dstAccessMask << ';'; + for (std::uint32_t index = 0; index < buffers; ++index) text << reinterpret_cast(bufferBarriers[index].buffer) << '+' << bufferBarriers[index].size << ';'; + for (std::uint32_t index = 0; index < images; ++index) text << reinterpret_cast(imageBarriers[index].image) << '/' << imageBarriers[index].newLayout << ';'; + note("pipelineBarrier", commands, source, destination, dependencies, memory, buffers, images, text.str()); +} + +VKAPI_ATTR void VKAPI_CALL updateBuffer(VkCommandBuffer commands, VkBuffer buffer, VkDeviceSize offset, VkDeviceSize size, const void* data) { + note("updateBuffer", commands, reinterpret_cast(buffer), offset, size, std::string(static_cast(data), static_cast(size))); +} + +VKAPI_ATTR void VKAPI_CALL clearAttachments(VkCommandBuffer commands, std::uint32_t attachments, const VkClearAttachment* clears, std::uint32_t rects, const VkClearRect* areas) { + std::ostringstream text; + for (std::uint32_t index = 0; index < attachments; ++index) text << clears[index].colorAttachment << '=' << clears[index].clearValue.color.uint32[0] << ';'; + for (std::uint32_t index = 0; index < rects; ++index) text << areas[index].rect.extent.width << 'x' << areas[index].rect.extent.height << ';'; + note("clearAttachments", commands, attachments, rects, text.str()); +} + +VKAPI_ATTR void VKAPI_CALL beginRenderPass(VkCommandBuffer commands, const VkRenderPassBeginInfo* info, VkSubpassContents contents) { + std::ostringstream text; + for (std::uint32_t index = 0; index < info->clearValueCount; ++index) text << info->pClearValues[index].color.float32[0] << ';'; + note("beginRenderPass", commands, reinterpret_cast(info->renderPass), info->renderArea.extent.width, info->clearValueCount, contents, text.str(), info->pNext != nullptr); +} + +VKAPI_ATTR void VKAPI_CALL beginRendering(VkCommandBuffer commands, const VkRenderingInfoKHR* info) { + std::ostringstream text; + for (std::uint32_t index = 0; index < info->colorAttachmentCount; ++index) text << reinterpret_cast(info->pColorAttachments[index].imageView) << ';'; + note("beginRendering", commands, info->renderArea.extent.width, info->colorAttachmentCount, text.str(), info->pDepthAttachment != nullptr ? reinterpret_cast(info->pDepthAttachment->imageView) : 0, info->pStencilAttachment != nullptr ? reinterpret_cast(info->pStencilAttachment->imageView) : 0); +} + +VKAPI_ATTR void VKAPI_CALL blitImage(VkCommandBuffer commands, VkImage source, VkImageLayout sourceLayout, VkImage destination, VkImageLayout destinationLayout, std::uint32_t count, const VkImageBlit* regions, VkFilter filter) { + std::ostringstream text; + for (std::uint32_t index = 0; index < count; ++index) text << regions[index].srcOffsets[1].x << '>' << regions[index].dstOffsets[1].x << ';'; + note("blitImage", commands, reinterpret_cast(source), sourceLayout, reinterpret_cast(destination), destinationLayout, count, filter, text.str()); +} + +VKAPI_ATTR void VKAPI_CALL pushDescriptorSet(VkCommandBuffer commands, VkPipelineBindPoint point, VkPipelineLayout layout, std::uint32_t set, std::uint32_t count, const VkWriteDescriptorSet* writes) { + note("pushDescriptorSet", commands, point, reinterpret_cast(layout), set, count, count != 0 ? writes[0].dstBinding : 0); +} + +CommandFunctions capturing() { + CommandFunctions functions{}; + functions.CmdDraw = &draw; + functions.CmdDispatch = &dispatch; + functions.CmdBindPipeline = &bindPipeline; + functions.CmdSetViewport = &setViewport; + functions.CmdSetScissorWithCount = &setScissorWithCount; + functions.CmdPushConstants = &pushConstants; + functions.CmdBindDescriptorSets = &bindDescriptorSets; + functions.CmdPipelineBarrier = &pipelineBarrier; + functions.CmdUpdateBuffer = &updateBuffer; + functions.CmdClearAttachments = &clearAttachments; + functions.CmdBeginRenderPass = &beginRenderPass; + functions.CmdBeginRenderingKHR = &beginRendering; + functions.CmdBlitImage = &blitImage; + functions.CmdPushDescriptorSetKHR = &pushDescriptorSet; + return functions; +} + +const CommandFunctions& Real() { + static const CommandFunctions functions = capturing(); + return functions; +} + +template +Pfn thunked(const char* name, Pfn real) { + return reinterpret_cast(AgcDriver::Graphics::CommandThunk(name, reinterpret_cast(real))); +} + +struct Thunks { + PFN_vkCmdDraw draw = thunked("vkCmdDraw", Real().CmdDraw); + PFN_vkCmdDispatch dispatch = thunked("vkCmdDispatch", Real().CmdDispatch); + PFN_vkCmdBindPipeline bindPipeline = thunked("vkCmdBindPipeline", Real().CmdBindPipeline); + PFN_vkCmdSetViewport setViewport = thunked("vkCmdSetViewport", Real().CmdSetViewport); + PFN_vkCmdSetScissorWithCount setScissorWithCount = thunked("vkCmdSetScissorWithCount", Real().CmdSetScissorWithCount); + PFN_vkCmdPushConstants pushConstants = thunked("vkCmdPushConstants", Real().CmdPushConstants); + PFN_vkCmdBindDescriptorSets bindDescriptorSets = thunked("vkCmdBindDescriptorSets", Real().CmdBindDescriptorSets); + PFN_vkCmdPipelineBarrier pipelineBarrier = thunked("vkCmdPipelineBarrier", Real().CmdPipelineBarrier); + PFN_vkCmdUpdateBuffer updateBuffer = thunked("vkCmdUpdateBuffer", Real().CmdUpdateBuffer); + PFN_vkCmdClearAttachments clearAttachments = thunked("vkCmdClearAttachments", Real().CmdClearAttachments); + PFN_vkCmdBeginRenderPass beginRenderPass = thunked("vkCmdBeginRenderPass", Real().CmdBeginRenderPass); + PFN_vkCmdBeginRenderingKHR beginRendering = thunked("vkCmdBeginRenderingKHR", Real().CmdBeginRenderingKHR); + PFN_vkCmdBlitImage blitImage = thunked("vkCmdBlitImage", Real().CmdBlitImage); + PFN_vkCmdPushDescriptorSetKHR pushDescriptorSet = thunked("vkCmdPushDescriptorSetKHR", Real().CmdPushDescriptorSetKHR); +}; + +const Thunks& thunks() { + static const Thunks table; + return table; +} + +template +VkBuffer handle(T value) { + return reinterpret_cast(static_cast(value)); +} + +template +Handle fake(std::uint64_t value) { + return reinterpret_cast(static_cast(value * 16 + 0x1000)); +} + +using Op = std::function; + +std::vector operations(bool chainedBarriers) { + const auto& t = thunks(); + std::vector ops; + ops.emplace_back([&t](VkCommandBuffer commands, std::mt19937& random) { t.draw(commands, random() % 100, 1 + random() % 4, random() % 7, random() % 3); }); + ops.emplace_back([&t](VkCommandBuffer commands, std::mt19937& random) { t.dispatch(commands, random() % 64, random() % 8, 1); }); + ops.emplace_back([&t](VkCommandBuffer commands, std::mt19937& random) { t.bindPipeline(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, fake(random() % 9)); }); + ops.emplace_back([&t](VkCommandBuffer commands, std::mt19937& random) { + std::vector viewports(1 + random() % 3); + for (auto& viewport : viewports) viewport = VkViewport{static_cast(random() % 50), 0, static_cast(random() % 500), 10, 0, 1}; + t.setViewport(commands, random() % 2, static_cast(viewports.size()), viewports.data()); + fillBytes(viewports, 0x5a); + }); + ops.emplace_back([&t](VkCommandBuffer commands, std::mt19937& random) { + std::vector scissors(random() % 3); + for (auto& scissor : scissors) scissor = VkRect2D{{static_cast(random() % 40), 0}, {static_cast(random() % 400), 9}}; + t.setScissorWithCount(commands, static_cast(scissors.size()), scissors.data()); + fillBytes(scissors, 0x5a); + }); + ops.emplace_back([&t](VkCommandBuffer commands, std::mt19937& random) { + std::string bytes(4 * (1 + random() % 8), 'a'); + for (auto& byte : bytes) byte = static_cast('a' + random() % 26); + t.pushConstants(commands, fake(3), VK_SHADER_STAGE_ALL, 4 * (random() % 4), static_cast(bytes.size()), bytes.data()); + std::fill(bytes.begin(), bytes.end(), '#'); + }); + ops.emplace_back([&t](VkCommandBuffer commands, std::mt19937& random) { + std::vector sets(1 + random() % 3); + for (auto& set : sets) set = fake(random() % 99); + std::vector offsets(random() % 3); + for (auto& offset : offsets) offset = random() % 4096; + t.bindDescriptorSets(commands, VK_PIPELINE_BIND_POINT_COMPUTE, fake(5), random() % 2, static_cast(sets.size()), sets.data(), static_cast(offsets.size()), offsets.data()); + fillBytes(sets, 0); + fillBytes(offsets, 0); + }); + ops.emplace_back([&t, chainedBarriers](VkCommandBuffer commands, std::mt19937& random) { + std::vector memory(random() % 2, VkMemoryBarrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, static_cast(random() % 64), static_cast(random() % 64)}); + std::vector buffers(random() % 3); + for (auto& barrier : buffers) barrier = VkBufferMemoryBarrier{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, nullptr, 0, 0, 0, 0, fake(random() % 30), 0, random() % 1000}; + std::vector images(random() % 3); + for (auto& barrier : images) { + barrier = VkImageMemoryBarrier{}; + barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; + barrier.image = fake(random() % 30); + barrier.newLayout = static_cast(random() % 8); + } + VkMemoryBarrier2 chain{}; + chain.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2; + if (chainedBarriers && !images.empty() && random() % 4 == 0) images.front().pNext = &chain; + t.pipelineBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, static_cast(memory.size()), memory.data(), static_cast(buffers.size()), buffers.data(), static_cast(images.size()), images.data()); + fillBytes(memory, 0); + fillBytes(buffers, 0); + fillBytes(images, 0); + }); + ops.emplace_back([&t](VkCommandBuffer commands, std::mt19937& random) { + std::string bytes(4 * (1 + random() % 6), 'q'); + for (auto& byte : bytes) byte = static_cast('A' + random() % 26); + t.updateBuffer(commands, fake(random() % 30), 4 * (random() % 8), bytes.size(), bytes.data()); + std::fill(bytes.begin(), bytes.end(), '#'); + }); + ops.emplace_back([&t](VkCommandBuffer commands, std::mt19937& random) { + std::vector clears(1 + random() % 2); + for (auto& clear : clears) { + clear = VkClearAttachment{VK_IMAGE_ASPECT_COLOR_BIT, static_cast(random() % 4), {}}; + clear.clearValue.color.uint32[0] = random() % 1000; + } + std::vector rects(1 + random() % 2, VkClearRect{{{0, 0}, {static_cast(random() % 640), static_cast(random() % 480)}}, 0, 1}); + t.clearAttachments(commands, static_cast(clears.size()), clears.data(), static_cast(rects.size()), rects.data()); + fillBytes(clears, 0); + fillBytes(rects, 0); + }); + ops.emplace_back([&t](VkCommandBuffer commands, std::mt19937& random) { + std::vector values(random() % 3); + for (auto& value : values) value.color.float32[0] = static_cast(random() % 100); + VkRenderPassBeginInfo info{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, nullptr, fake(random() % 9), fake(1), {{0, 0}, {static_cast(random() % 800), 600}}, static_cast(values.size()), values.data()}; + t.beginRenderPass(commands, &info, VK_SUBPASS_CONTENTS_INLINE); + fillBytes(values, 0); + info = {}; + }); + ops.emplace_back([&t](VkCommandBuffer commands, std::mt19937& random) { + std::vector colors(random() % 3); + for (auto& color : colors) { + color = VkRenderingAttachmentInfoKHR{}; + color.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR; + color.imageView = fake(random() % 50); + } + VkRenderingAttachmentInfoKHR depth{}; + depth.sType = VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR; + depth.imageView = fake(70 + random() % 5); + VkRenderingInfoKHR info{}; + info.sType = VK_STRUCTURE_TYPE_RENDERING_INFO_KHR; + info.renderArea.extent = {static_cast(random() % 900), 10}; + info.colorAttachmentCount = static_cast(colors.size()); + info.pColorAttachments = colors.data(); + if (random() % 2 == 0) info.pDepthAttachment = &depth; + t.beginRendering(commands, &info); + fillBytes(colors, 0); + depth = {}; + info = {}; + }); + ops.emplace_back([&t](VkCommandBuffer commands, std::mt19937& random) { + std::vector regions(1 + random() % 2); + for (auto& region : regions) { + region = VkImageBlit{}; + region.srcOffsets[1].x = static_cast(random() % 256); + region.dstOffsets[1].x = static_cast(random() % 128); + } + t.blitImage(commands, fake(1), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, fake(2), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, static_cast(regions.size()), regions.data(), random() % 2 == 0 ? VK_FILTER_LINEAR : VK_FILTER_NEAREST); + fillBytes(regions, 0); + }); + return ops; +} + +std::vector runProgram(std::uint32_t seed, std::size_t length, VkCommandBuffer commands, bool chainedBarriers, std::function after = {}) { + log.clear(); + std::mt19937 random(seed); + const auto ops = operations(chainedBarriers); + for (std::size_t step = 0; step < length; ++step) ops[random() % ops.size()](commands, random); + if (after) after(); + return log; +} + +std::vector retarget(std::vector lines, VkCommandBuffer from, VkCommandBuffer to) { + const auto source = "@" + std::to_string(id(from)) + " "; + const auto target = "@" + std::to_string(id(to)) + " "; + for (auto& line : lines) { + if (const auto at = line.find(source); at != std::string::npos) line.replace(at, source.size(), target); + } + return lines; +} + +std::string firstDifference(const std::vector& expected, const std::vector& actual) { + for (std::size_t index = 0; index < std::min(expected.size(), actual.size()); ++index) { + if (expected[index] != actual[index]) return "at " + std::to_string(index) + ": expected '" + expected[index] + "', got '" + actual[index] + "'"; + } + return "lengths " + std::to_string(expected.size()) + " and " + std::to_string(actual.size()); +} + +void StreamReplayRecordsWhatDirectRecords() { + const auto direct = FakeCommandBuffer(3); + const auto target = FakeCommandBuffer(4); + for (std::uint32_t seed = 1; seed <= 40; ++seed) { + const auto expected = retarget(runProgram(seed, 200, direct, false), direct, target); + CommandStream stream(Real()); + const auto streamed = runProgram(seed, 200, stream.Handle(), false); + Require(streamed.empty(), "a streamed command reached the driver while recording: " + (streamed.empty() ? std::string() : streamed.front())); + stream.Seal(); + log.clear(); + AgcDriver::Graphics::Replay(stream, target, Real()); + Require(log == expected, "seed " + std::to_string(seed) + ": the replay differs from direct recording " + firstDifference(expected, log)); + Require(stream.Ops() == expected.size(), "the stream counted " + std::to_string(stream.Ops()) + " ops for " + std::to_string(expected.size()) + " commands"); + } +} + +class FakeMaterializer final : public StreamMaterializer { +public: + explicit FakeMaterializer(VkCommandBuffer buffer) : buffer(buffer) {} + VkCommandBuffer Begin(CommandStream&) override { + ++begun; + note("begin", buffer); + return buffer; + } + VkCommandBuffer buffer; + int begun = 0; +}; + +void DemotionReplaysThePrefixInOrder() { + const auto direct = FakeCommandBuffer(5); + const auto target = FakeCommandBuffer(6); + std::size_t demotedSeeds = 0; + for (std::uint32_t seed = 1; seed <= 40; ++seed) { + auto expected = retarget(runProgram(seed, 120, direct, true), direct, target); + FakeMaterializer materializer(target); + CommandStream stream(Real(), nullptr, &materializer); + const auto lines = runProgram(seed, 120, stream.Handle(), true); + if (stream.Materialized() == VK_NULL_HANDLE) { + Require(lines.empty(), "a stream that never demoted reached the driver"); + continue; + } + ++demotedSeeds; + Require(materializer.begun == 1, "the stream began " + std::to_string(materializer.begun) + " command buffers"); + Require(!lines.empty() && lines.front() == "begin@" + std::to_string(id(target)), "the demotion did not begin its command buffer first"); + const std::vector replayed(lines.begin() + 1, lines.end()); + Require(replayed == expected, "seed " + std::to_string(seed) + ": the demoted recording differs from direct recording " + firstDifference(expected, replayed)); + Require(std::string_view(stream.DemotedBy().command) == "vkCmdPipelineBarrier" && stream.DemotedBy().chained == VK_STRUCTURE_TYPE_MEMORY_BARRIER_2, "the demotion was not attributed to the chained barrier"); + Require(stream.Bytes() == 0 || stream.Materialized() != VK_NULL_HANDLE, "the stream kept records after its demotion"); + Require(Throws([&] { + stream.Seal(); + AgcDriver::Graphics::Replay(stream, target, Real()); + }), "a demoted stream was replayed"); + } + Require(demotedSeeds >= 10, "only " + std::to_string(demotedSeeds) + " of 40 programs demoted"); +} + +void PushDescriptorsDemoteOnlyWhatTheyCannotCopy() { + const auto target = FakeCommandBuffer(8); + VkDescriptorImageInfo image{fake(3), fake(4), VK_IMAGE_LAYOUT_GENERAL}; + { + FakeMaterializer materializer(target); + CommandStream stream(Real(), nullptr, &materializer); + log.clear(); + VkWriteDescriptorSet write{}; + write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + write.dstBinding = 7; + write.descriptorCount = 1; + write.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + write.pImageInfo = ℑ + thunks().pushDescriptorSet(stream.Handle(), VK_PIPELINE_BIND_POINT_COMPUTE, fake(2), 0, 1, &write); + Require(log.empty() && stream.Materialized() == VK_NULL_HANDLE && stream.Ops() == 1, "a copyable push descriptor write did not stream"); + } + VkWriteDescriptorSetInlineUniformBlock inlineBlock{}; + inlineBlock.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_INLINE_UNIFORM_BLOCK; + VkWriteDescriptorSetAccelerationStructureKHR structures{}; + structures.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_ACCELERATION_STRUCTURE_KHR; + struct Case { + const char* what; + VkDescriptorType type; + const void* next; + bool switchedOff; + VkStructureType chained; + }; + const std::array cases{{ + {"an inline uniform block", VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK, &inlineBlock, false, VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_INLINE_UNIFORM_BLOCK}, + {"an acceleration structure", VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, &structures, false, VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_ACCELERATION_STRUCTURE_KHR}, + {"a descriptor type with no array to copy", VK_DESCRIPTOR_TYPE_MUTABLE_EXT, nullptr, false, VK_STRUCTURE_TYPE_MAX_ENUM}, + {"APS5_NO_STREAMED_PUSH_DESCRIPTORS", VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, nullptr, true, VK_STRUCTURE_TYPE_MAX_ENUM}, + }}; + for (const auto& item : cases) { + AgcDriver::Graphics::RuntimeSwitches::Assign(AgcDriver::Graphics::RuntimeSwitch::NoStreamedPushDescriptors, item.switchedOff); + FakeMaterializer materializer(target); + CommandStream stream(Real(), nullptr, &materializer); + log.clear(); + thunks().draw(stream.Handle(), 3, 1, 0, 0); + VkWriteDescriptorSet write{}; + write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + write.pNext = item.next; + write.dstBinding = 7; + write.descriptorCount = 1; + write.descriptorType = item.type; + write.pImageInfo = ℑ + Require(log.empty(), "a streamed draw reached the driver"); + thunks().pushDescriptorSet(stream.Handle(), VK_PIPELINE_BIND_POINT_COMPUTE, fake(2), 0, 1, &write); + thunks().draw(stream.Handle(), 4, 1, 0, 0); + AgcDriver::Graphics::RuntimeSwitches::Assign(AgcDriver::Graphics::RuntimeSwitch::NoStreamedPushDescriptors, false); + const std::vector expected{"begin@8", "draw@8 3 1 0 0", "pushDescriptorSet@8 1 4128 0 1 7", "draw@8 4 1 0 0"}; + Require(log == expected, std::string(item.what) + ": the push descriptor demotion recorded " + firstDifference(expected, log)); + Require(std::string_view(stream.DemotedBy().command) == "vkCmdPushDescriptorSetKHR" && stream.DemotedBy().chained == item.chained, std::string(item.what) + ": the push descriptor demotion was not attributed to its command and chain"); + } +} + +void DemotionWithoutAMaterializerPoisons() { + CommandStream stream(Real()); + thunks().draw(stream.Handle(), 1, 1, 0, 0); + VkWriteDescriptorSetInlineUniformBlock inlineBlock{}; + inlineBlock.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_INLINE_UNIFORM_BLOCK; + VkWriteDescriptorSet write{}; + write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + write.pNext = &inlineBlock; + write.descriptorType = VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK; + Require(Throws([&] { thunks().pushDescriptorSet(stream.Handle(), VK_PIPELINE_BIND_POINT_COMPUTE, fake(2), 0, 1, &write); }), "a stream with no materializer demoted"); + Require(stream.Poisoned(), "a failed demotion left the stream unpoisoned"); +} + +void DirectCallsReachTheirOwnEntryPoint() { + log.clear(); + thunks().draw(FakeCommandBuffer(9), 1, 2, 3, 4); + Require(log == std::vector{"draw@9 1 2 3 4"}, "a direct call did not reach the real entry point: " + (log.empty() ? std::string("nothing") : log.front())); +} + +template +VKAPI_ATTR void VKAPI_CALL stencilSlot(VkCommandBuffer commands, VkStencilFaceFlags, std::uint32_t reference) { + note("stencil", commands, K, reference); +} + +template +std::array stencils(std::integer_sequence) { + return {&stencilSlot...}; +} + +struct alignas(16) FakeDispatchable { + const void* key; +}; + +std::atomic reusedRight{0}; +std::atomic reusedWrong{0}; + +VKAPI_ATTR void VKAPI_CALL reusedFirst(VkCommandBuffer, VkStencilFaceFlags, std::uint32_t) { + reusedRight.fetch_add(1, std::memory_order_relaxed); +} + +VKAPI_ATTR void VKAPI_CALL reusedSecond(VkCommandBuffer, VkStencilFaceFlags, std::uint32_t) { + reusedWrong.fetch_add(1, std::memory_order_relaxed); +} + +VkDevice deviceOf(FakeDispatchable& dispatchable) { + return reinterpret_cast(&dispatchable); +} + +VkCommandBuffer commandsOf(FakeDispatchable& dispatchable) { + return reinterpret_cast(&dispatchable); +} + +void EntryPointsBeyondTheSlotsAreKeyedByDevice() { + using AgcDriver::Graphics::CommandThunk; + constexpr const char* Name = "vkCmdSetStencilReference"; + const auto reals = stencils(std::make_integer_sequence{}); + const auto entry = [&](std::size_t index) { return reinterpret_cast(reals[index]); }; + Require(AgcDriver::Graphics::CommandThunkSlots(CommandId::CmdSetStencilReference) == 0, "another test used the stencil reference slots"); + std::vector given; + for (std::size_t index = 0; index < 8; ++index) { + const auto thunk = CommandThunk(Name, entry(index)); + Require(AgcDriver::Graphics::IsCommandThunk(Name, thunk), "a slot's entry point was not a thunk"); + for (const auto earlier : given) Require(earlier != thunk, "two entry points shared a thunk slot"); + given.push_back(thunk); + log.clear(); + reinterpret_cast(thunk)(FakeCommandBuffer(2), VK_STENCIL_FACE_FRONT_BIT, 9); + Require(log == std::vector{"stencil@2 " + std::to_string(index) + " 9"}, "slot " + std::to_string(index) + " reached the wrong entry point"); + } + Require(CommandThunk(Name, entry(0)) == given[0], "the same entry point took a second slot"); + Require(AgcDriver::Graphics::CommandThunkSlots(CommandId::CmdSetStencilReference) == 8, "the slots in use were miscounted"); + Require(Throws([&] { CommandThunk(Name, entry(8)); }), "a ninth entry point with no device to key it by was given a thunk"); + static const int keys[3] = {}; + FakeDispatchable first{&keys[0]}; + FakeDispatchable second{&keys[1]}; + FakeDispatchable firstCommands{&keys[0]}; + FakeDispatchable secondCommands{&keys[1]}; + FakeDispatchable strangerCommands{&keys[2]}; + const auto keyed = CommandThunk(Name, entry(8), deviceOf(first)); + Require(AgcDriver::Graphics::IsCommandThunk(Name, keyed) && std::find(given.begin(), given.end(), keyed) == given.end(), "a ninth entry point on a device was not given the keyed thunk"); + Require(CommandThunk(Name, entry(9), deviceOf(second)) == keyed, "a second device's entry point was given another thunk"); + Require(CommandThunk(Name, entry(8), deviceOf(first)) == keyed && AgcDriver::Graphics::CommandDeviceEntries(CommandId::CmdSetStencilReference) == 2, "a device's repeated entry point was registered twice"); + Require(CommandThunk(Name, entry(0), deviceOf(first)) == given[0], "an entry point that holds a slot was keyed instead"); + const auto call = reinterpret_cast(keyed); + log.clear(); + call(commandsOf(firstCommands), VK_STENCIL_FACE_FRONT_BIT, 1); + call(commandsOf(secondCommands), VK_STENCIL_FACE_BACK_BIT, 2); + const std::vector routed{"stencil@" + std::to_string(id(commandsOf(firstCommands))) + " 8 1", "stencil@" + std::to_string(id(commandsOf(secondCommands))) + " 9 2"}; + Require(log == routed, "the keyed thunk did not route each command buffer to its device's entry point: " + firstDifference(routed, log)); + Require(Throws([&] { call(commandsOf(strangerCommands), VK_STENCIL_FACE_FRONT_BIT, 3); }), "a command buffer of an unregistered device reached an entry point"); + Require(Throws([&] { CommandThunk(Name, entry(10), deviceOf(first)); }), "one device gave two entry points for one command and both were kept"); + { + CommandFunctions functions{}; + functions.CmdSetStencilReference = reals[10]; + CommandStream stream(functions); + log.clear(); + call(stream.Handle(), VK_STENCIL_FACE_FRONT_BIT, 4); + Require(log.empty() && stream.Ops() == 1, "the keyed thunk did not stream a stream handle"); + stream.Seal(); + AgcDriver::Graphics::Replay(stream, FakeCommandBuffer(3), functions); + Require(log == std::vector{"stencil@3 10 4"}, "the keyed thunk's streamed call replayed wrongly"); + } + AgcDriver::Graphics::ForgetCommandDevice(deviceOf(first)); + Require(AgcDriver::Graphics::CommandDeviceEntries(CommandId::CmdSetStencilReference) == 1, "a forgotten device kept its entry"); + Require(Throws([&] { call(commandsOf(firstCommands), VK_STENCIL_FACE_FRONT_BIT, 5); }), "a forgotten device's command buffer still reached its entry point"); + Require(CommandThunk(Name, entry(10), deviceOf(first)) == keyed, "a device created where a forgotten one was could not register its entry point"); + log.clear(); + call(commandsOf(firstCommands), VK_STENCIL_FACE_FRONT_BIT, 6); + call(commandsOf(secondCommands), VK_STENCIL_FACE_FRONT_BIT, 7); + Require(log.size() == 2 && log[0].ends_with(" 10 6") && log[1].ends_with(" 9 7"), "the keyed thunk routed wrongly after a device was replaced"); + AgcDriver::Graphics::ForgetCommandDevice(deviceOf(first)); + AgcDriver::Graphics::ForgetCommandDevice(deviceOf(second)); + Require(AgcDriver::Graphics::CommandDeviceEntries(CommandId::CmdSetStencilReference) == 0, "forgetting every device left entries"); + const auto peak = AgcDriver::Graphics::CommandDeviceStorage(CommandId::CmdSetStencilReference); + Require(peak == 2, "two live devices kept " + std::to_string(peak) + " entries of storage"); + constexpr std::size_t Cycles = 200; + static const int cycleKeys[Cycles] = {}; + std::vector devices; + std::vector buffers; + for (std::size_t index = 0; index < Cycles; ++index) { + devices.push_back(FakeDispatchable{&cycleKeys[index]}); + buffers.push_back(FakeDispatchable{&cycleKeys[index]}); + } + for (std::size_t cycle = 0; cycle + 1 < Cycles; cycle += 2) { + Require(CommandThunk(Name, entry(8), deviceOf(devices[cycle])) == keyed && CommandThunk(Name, entry(9), deviceOf(devices[cycle + 1])) == keyed, "a device created after others were destroyed was not given the keyed thunk"); + log.clear(); + call(commandsOf(buffers[cycle]), VK_STENCIL_FACE_FRONT_BIT, 1); + call(commandsOf(buffers[cycle + 1]), VK_STENCIL_FACE_FRONT_BIT, 2); + Require(log.size() == 2 && log[0].ends_with(" 8 1") && log[1].ends_with(" 9 2"), "cycle " + std::to_string(cycle) + " routed a command buffer to the wrong device's entry point"); + if (cycle > 0) Require(Throws([&] { call(commandsOf(buffers[cycle - 1]), VK_STENCIL_FACE_FRONT_BIT, 3); }), "a destroyed device's command buffer reached an entry point in cycle " + std::to_string(cycle)); + Require(AgcDriver::Graphics::CommandDeviceEntries(CommandId::CmdSetStencilReference) == 2, "cycle " + std::to_string(cycle) + " miscounted the live devices"); + AgcDriver::Graphics::ForgetCommandDevice(deviceOf(devices[cycle])); + AgcDriver::Graphics::ForgetCommandDevice(deviceOf(devices[cycle + 1])); + Require(AgcDriver::Graphics::CommandDeviceStorage(CommandId::CmdSetStencilReference) == peak, "creating and destroying devices grew the entries to " + std::to_string(AgcDriver::Graphics::CommandDeviceStorage(CommandId::CmdSetStencilReference)) + " after cycle " + std::to_string(cycle)); + } + Require(AgcDriver::Graphics::CommandDeviceEntries(CommandId::CmdSetStencilReference) == 0, "forgetting every cycled device left entries"); + static const int raceKeys[2] = {}; + FakeDispatchable racedFirst{&raceKeys[0]}; + FakeDispatchable racedSecond{&raceKeys[1]}; + FakeDispatchable racedCommands{&raceKeys[0]}; + const auto firstReal = reinterpret_cast(&reusedFirst); + const auto secondReal = reinterpret_cast(&reusedSecond); + Require(CommandThunk(Name, firstReal, deviceOf(racedFirst)) == keyed, "the raced device was not given the keyed thunk"); + std::atomic stop{false}; + std::atomic reuses{0}; + std::thread writer([&] { + while (!stop.load(std::memory_order_relaxed)) { + AgcDriver::Graphics::ForgetCommandDevice(deviceOf(racedFirst)); + CommandThunk(Name, secondReal, deviceOf(racedSecond)); + AgcDriver::Graphics::ForgetCommandDevice(deviceOf(racedSecond)); + CommandThunk(Name, firstReal, deviceOf(racedFirst)); + reuses.fetch_add(1, std::memory_order_relaxed); + } + }); + std::uint64_t missing = 0; + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2); + while (std::chrono::steady_clock::now() < deadline && reusedWrong.load(std::memory_order_relaxed) == 0) { + for (int index = 0; index < 4096; ++index) { + try { + call(commandsOf(racedCommands), VK_STENCIL_FACE_FRONT_BIT, 1); + } catch (const std::logic_error&) { + ++missing; + } + } + } + stop.store(true); + writer.join(); + Require(reusedWrong.load() == 0, "a lookup racing a forget and reuse of its node called another device's entry point " + std::to_string(reusedWrong.load()) + " times (" + std::to_string(reusedRight.load()) + " right, " + std::to_string(reuses.load()) + " reuses)"); + Require(reusedRight.load() > 0 && reuses.load() > 0, "the forget and reuse race never ran both sides"); + Require(AgcDriver::Graphics::CommandDeviceStorage(CommandId::CmdSetStencilReference) == peak, "the forget and reuse race grew the entries"); + AgcDriver::Graphics::ForgetCommandDevice(deviceOf(racedFirst)); + std::cout << "keyed race: " << reusedRight.load() << " right, " << missing << " missing, " << reuses.load() << " reuses\n"; +} + +void EveryListedCommandStreams() { + for (std::size_t index = 0; index < AgcDriver::Graphics::CommandCount; ++index) { + Require(AgcDriver::Graphics::CommandStreams(static_cast(index)), std::string(AgcDriver::Graphics::CommandNames()[index]) + " is listed but has no streamer, so every batch that records it demotes"); + } +} + +void EveryListedCommandHasAThunk() { + std::size_t names = 0; + for (const auto name : AgcDriver::Graphics::CommandNames()) { + ++names; + Require(AgcDriver::Graphics::IsCommandName(name), std::string(name) + " is listed but is not a command name"); + Require(AgcDriver::Graphics::CommandNames()[static_cast(AgcDriver::Graphics::CommandFor(name))] == name, std::string(name) + " maps to another command"); + } + Require(names == AgcDriver::Graphics::CommandCount, "the name list and the command ids differ in length"); + Require(Throws([] { static_cast(AgcDriver::Graphics::CommandFor("vkCmdNotACommand")); }), "an unknown command resolved"); + Require(AgcDriver::Graphics::CommandThunk("vkCmdDraw", nullptr) == nullptr, "a missing entry point was given a thunk"); + Require(!AgcDriver::Graphics::IsCommandName("vkCreateBuffer"), "a non-command was taken for a command"); +} + +std::string captured; +std::vector> capturedCommands; + +template +void put(const T& value) { + static_assert(std::is_trivially_copyable_v); + captured.append(reinterpret_cast(&value), sizeof(T)); +} + +template +void putArray(const T* values, std::uint32_t count) { + put(count); + put(values != nullptr); + for (std::uint32_t index = 0; index < count; ++index) put(values[index]); +} + +void putNext(const void* next) { + put(next == nullptr); +} + +void putTag(const char* name) { + capturedCommands.emplace_back(captured.size(), name); + captured += '|'; + captured += name; + captured += '|'; +} + +void putMemory(const VkMemoryBarrier& barrier) { + put(barrier.sType); + putNext(barrier.pNext); + put(barrier.srcAccessMask); + put(barrier.dstAccessMask); +} + +void putBuffer(const VkBufferMemoryBarrier& barrier) { + put(barrier.sType); + putNext(barrier.pNext); + put(barrier.srcAccessMask); + put(barrier.dstAccessMask); + put(barrier.srcQueueFamilyIndex); + put(barrier.dstQueueFamilyIndex); + put(barrier.buffer); + put(barrier.offset); + put(barrier.size); +} + +void putImage(const VkImageMemoryBarrier& barrier) { + put(barrier.sType); + putNext(barrier.pNext); + put(barrier.srcAccessMask); + put(barrier.dstAccessMask); + put(barrier.oldLayout); + put(barrier.newLayout); + put(barrier.srcQueueFamilyIndex); + put(barrier.dstQueueFamilyIndex); + put(barrier.image); + put(barrier.subresourceRange); +} + +void putAttachment(const VkRenderingAttachmentInfoKHR* attachment) { + put(attachment != nullptr); + if (attachment == nullptr) return; + put(attachment->sType); + putNext(attachment->pNext); + put(attachment->imageView); + put(attachment->imageLayout); + put(attachment->resolveMode); + put(attachment->resolveImageView); + put(attachment->resolveImageLayout); + put(attachment->loadOp); + put(attachment->storeOp); + put(attachment->clearValue); +} + +template +struct Exact; + +#define APS5_EXACT_RANGE(name, T) \ + template<> \ + struct Exact { \ + static VKAPI_ATTR void VKAPI_CALL Run(VkCommandBuffer commands, std::uint32_t first, std::uint32_t count, const T* values) { \ + putTag(#name); \ + put(commands); \ + put(first); \ + putArray(values, count); \ + } \ + }; +APS5_EXACT_RANGE(CmdSetViewport, VkViewport) +APS5_EXACT_RANGE(CmdSetScissor, VkRect2D) +APS5_EXACT_RANGE(CmdSetColorWriteMaskEXT, VkColorComponentFlags) +#undef APS5_EXACT_RANGE + +#define APS5_EXACT_COUNT(name, T) \ + template<> \ + struct Exact { \ + static VKAPI_ATTR void VKAPI_CALL Run(VkCommandBuffer commands, std::uint32_t count, const T* values) { \ + putTag(#name); \ + put(commands); \ + putArray(values, count); \ + } \ + }; +APS5_EXACT_COUNT(CmdSetViewportWithCount, VkViewport) +APS5_EXACT_COUNT(CmdSetViewportWithCountEXT, VkViewport) +APS5_EXACT_COUNT(CmdSetScissorWithCount, VkRect2D) +APS5_EXACT_COUNT(CmdSetScissorWithCountEXT, VkRect2D) +APS5_EXACT_COUNT(CmdExecuteCommands, VkCommandBuffer) +#undef APS5_EXACT_COUNT + +template<> +struct Exact { + static VKAPI_ATTR void VKAPI_CALL Run(VkCommandBuffer commands, VkPipelineBindPoint point, VkPipelineLayout layout, std::uint32_t first, std::uint32_t count, const VkDescriptorSet* sets, std::uint32_t offsets, const std::uint32_t* dynamicOffsets) { + putTag("CmdBindDescriptorSets"); + put(commands); + put(point); + put(layout); + put(first); + putArray(sets, count); + putArray(dynamicOffsets, offsets); + } +}; + +template<> +struct Exact { + static VKAPI_ATTR void VKAPI_CALL Run(VkCommandBuffer commands, VkPipelineLayout layout, VkShaderStageFlags stages, std::uint32_t offset, std::uint32_t size, const void* values) { + putTag("CmdPushConstants"); + put(commands); + put(layout); + put(stages); + put(offset); + putArray(static_cast(values), size); + } +}; + +template<> +struct Exact { + static VKAPI_ATTR void VKAPI_CALL Run(VkCommandBuffer commands, std::uint32_t first, std::uint32_t count, const VkBuffer* buffers, const VkDeviceSize* offsets) { + putTag("CmdBindVertexBuffers"); + put(commands); + put(first); + putArray(buffers, count); + putArray(offsets, count); + } +}; + +template<> +struct Exact { + static VKAPI_ATTR void VKAPI_CALL Run(VkCommandBuffer commands, VkPipelineStageFlags source, VkPipelineStageFlags destination, VkDependencyFlags dependencies, std::uint32_t memory, const VkMemoryBarrier* memoryBarriers, std::uint32_t buffers, const VkBufferMemoryBarrier* bufferBarriers, std::uint32_t images, const VkImageMemoryBarrier* imageBarriers) { + putTag("CmdPipelineBarrier"); + put(commands); + put(source); + put(destination); + put(dependencies); + put(memory); + for (std::uint32_t index = 0; index < memory; ++index) putMemory(memoryBarriers[index]); + put(buffers); + for (std::uint32_t index = 0; index < buffers; ++index) putBuffer(bufferBarriers[index]); + put(images); + for (std::uint32_t index = 0; index < images; ++index) putImage(imageBarriers[index]); + } +}; + +template<> +struct Exact { + static VKAPI_ATTR void VKAPI_CALL Run(VkCommandBuffer commands, VkBuffer source, VkBuffer destination, std::uint32_t count, const VkBufferCopy* regions) { + putTag("CmdCopyBuffer"); + put(commands); + put(source); + put(destination); + putArray(regions, count); + } +}; + +template<> +struct Exact { + static VKAPI_ATTR void VKAPI_CALL Run(VkCommandBuffer commands, VkBuffer buffer, VkDeviceSize offset, VkDeviceSize size, const void* data) { + putTag("CmdUpdateBuffer"); + put(commands); + put(buffer); + put(offset); + put(size); + putArray(static_cast(data), static_cast(size)); + } +}; + +template<> +struct Exact { + static VKAPI_ATTR void VKAPI_CALL Run(VkCommandBuffer commands, VkBuffer source, VkImage destination, VkImageLayout layout, std::uint32_t count, const VkBufferImageCopy* regions) { + putTag("CmdCopyBufferToImage"); + put(commands); + put(source); + put(destination); + put(layout); + putArray(regions, count); + } +}; + +template<> +struct Exact { + static VKAPI_ATTR void VKAPI_CALL Run(VkCommandBuffer commands, VkImage source, VkImageLayout layout, VkBuffer destination, std::uint32_t count, const VkBufferImageCopy* regions) { + putTag("CmdCopyImageToBuffer"); + put(commands); + put(source); + put(layout); + put(destination); + putArray(regions, count); + } +}; + +template<> +struct Exact { + static VKAPI_ATTR void VKAPI_CALL Run(VkCommandBuffer commands, VkImage source, VkImageLayout sourceLayout, VkImage destination, VkImageLayout destinationLayout, std::uint32_t count, const VkImageCopy* regions) { + putTag("CmdCopyImage"); + put(commands); + put(source); + put(sourceLayout); + put(destination); + put(destinationLayout); + putArray(regions, count); + } +}; + +template<> +struct Exact { + static VKAPI_ATTR void VKAPI_CALL Run(VkCommandBuffer commands, VkImage source, VkImageLayout sourceLayout, VkImage destination, VkImageLayout destinationLayout, std::uint32_t count, const VkImageResolve* regions) { + putTag("CmdResolveImage"); + put(commands); + put(source); + put(sourceLayout); + put(destination); + put(destinationLayout); + putArray(regions, count); + } +}; + +template<> +struct Exact { + static VKAPI_ATTR void VKAPI_CALL Run(VkCommandBuffer commands, VkImage source, VkImageLayout sourceLayout, VkImage destination, VkImageLayout destinationLayout, std::uint32_t count, const VkImageBlit* regions, VkFilter filter) { + putTag("CmdBlitImage"); + put(commands); + put(source); + put(sourceLayout); + put(destination); + put(destinationLayout); + putArray(regions, count); + put(filter); + } +}; + +template<> +struct Exact { + static VKAPI_ATTR void VKAPI_CALL Run(VkCommandBuffer commands, VkImage image, VkImageLayout layout, const VkClearColorValue* color, std::uint32_t count, const VkImageSubresourceRange* ranges) { + putTag("CmdClearColorImage"); + put(commands); + put(image); + put(layout); + put(*color); + putArray(ranges, count); + } +}; + +template<> +struct Exact { + static VKAPI_ATTR void VKAPI_CALL Run(VkCommandBuffer commands, VkImage image, VkImageLayout layout, const VkClearDepthStencilValue* value, std::uint32_t count, const VkImageSubresourceRange* ranges) { + putTag("CmdClearDepthStencilImage"); + put(commands); + put(image); + put(layout); + put(*value); + putArray(ranges, count); + } +}; + +template<> +struct Exact { + static VKAPI_ATTR void VKAPI_CALL Run(VkCommandBuffer commands, std::uint32_t attachments, const VkClearAttachment* clears, std::uint32_t rects, const VkClearRect* areas) { + putTag("CmdClearAttachments"); + put(commands); + putArray(clears, attachments); + putArray(areas, rects); + } +}; + +template<> +struct Exact { + static VKAPI_ATTR void VKAPI_CALL Run(VkCommandBuffer commands, const VkRenderPassBeginInfo* info, VkSubpassContents contents) { + putTag("CmdBeginRenderPass"); + put(commands); + put(info->sType); + putNext(info->pNext); + put(info->renderPass); + put(info->framebuffer); + put(info->renderArea); + putArray(info->pClearValues, info->clearValueCount); + put(contents); + } +}; + +template<> +struct Exact { + static VKAPI_ATTR void VKAPI_CALL Run(VkCommandBuffer commands, const VkRenderingInfoKHR* info) { + putTag("CmdBeginRenderingKHR"); + put(commands); + put(info->sType); + putNext(info->pNext); + put(info->flags); + put(info->renderArea); + put(info->layerCount); + put(info->viewMask); + put(info->colorAttachmentCount); + put(info->pColorAttachments != nullptr); + for (std::uint32_t index = 0; index < info->colorAttachmentCount; ++index) putAttachment(&info->pColorAttachments[index]); + putAttachment(info->pDepthAttachment); + putAttachment(info->pStencilAttachment); + } +}; + +template<> +struct Exact { + static VKAPI_ATTR void VKAPI_CALL Run(VkCommandBuffer commands, const void* marker) { + putTag("CmdSetCheckpointNV"); + put(commands); + put(marker); + } +}; + +template<> +struct Exact { + static VKAPI_ATTR void VKAPI_CALL Run(VkCommandBuffer commands, const VkDepthBiasInfoEXT* info) { + putTag("CmdSetDepthBias2EXT"); + put(commands); + put(info->sType); + putNext(info->pNext); + put(info->depthBiasConstantFactor); + put(info->depthBiasClamp); + put(info->depthBiasSlopeFactor); + } +}; + +template<> +struct Exact { + static VKAPI_ATTR void VKAPI_CALL Run(VkCommandBuffer commands, std::uint32_t count, const VkShaderStageFlagBits* stages, const VkShaderEXT* shaders) { + putTag("CmdBindShadersEXT"); + put(commands); + putArray(stages, count); + put(shaders != nullptr); + if (shaders != nullptr) putArray(shaders, count); + } +}; + +enum class WriteArray { Images, Buffers, Views }; + +WriteArray writeArray(VkDescriptorType type) { + switch (type) { + case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER: + case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER: + case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: + case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: + return WriteArray::Buffers; + case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: + case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: + return WriteArray::Views; + default: + return WriteArray::Images; + } +} + +template<> +struct Exact { + static VKAPI_ATTR void VKAPI_CALL Run(VkCommandBuffer commands, VkPipelineBindPoint point, VkPipelineLayout layout, std::uint32_t set, std::uint32_t count, const VkWriteDescriptorSet* writes) { + putTag("CmdPushDescriptorSetKHR"); + put(commands); + put(point); + put(layout); + put(set); + put(count); + for (std::uint32_t index = 0; index < count; ++index) { + const auto& write = writes[index]; + put(write.sType); + putNext(write.pNext); + put(write.dstSet); + put(write.dstBinding); + put(write.dstArrayElement); + put(write.descriptorType); + switch (writeArray(write.descriptorType)) { + case WriteArray::Images: + putArray(write.pImageInfo, write.descriptorCount); + break; + case WriteArray::Buffers: + putArray(write.pBufferInfo, write.descriptorCount); + break; + case WriteArray::Views: + putArray(write.pTexelBufferView, write.descriptorCount); + break; + } + } + } +}; + +CommandFunctions exactFunctions() { + CommandFunctions functions{}; +#define APS5_EXACT(name) functions.name = &Exact::Run; + APS5_EXACT(CmdSetViewport) + APS5_EXACT(CmdSetScissor) + APS5_EXACT(CmdSetColorWriteMaskEXT) + APS5_EXACT(CmdSetViewportWithCount) + APS5_EXACT(CmdSetViewportWithCountEXT) + APS5_EXACT(CmdSetScissorWithCount) + APS5_EXACT(CmdSetScissorWithCountEXT) + APS5_EXACT(CmdBindDescriptorSets) + APS5_EXACT(CmdPushConstants) + APS5_EXACT(CmdBindVertexBuffers) + APS5_EXACT(CmdPipelineBarrier) + APS5_EXACT(CmdCopyBuffer) + APS5_EXACT(CmdUpdateBuffer) + APS5_EXACT(CmdCopyBufferToImage) + APS5_EXACT(CmdCopyImageToBuffer) + APS5_EXACT(CmdCopyImage) + APS5_EXACT(CmdResolveImage) + APS5_EXACT(CmdBlitImage) + APS5_EXACT(CmdClearColorImage) + APS5_EXACT(CmdClearDepthStencilImage) + APS5_EXACT(CmdClearAttachments) + APS5_EXACT(CmdBeginRenderPass) + APS5_EXACT(CmdBeginRenderingKHR) + APS5_EXACT(CmdExecuteCommands) + APS5_EXACT(CmdSetCheckpointNV) + APS5_EXACT(CmdSetDepthBias2EXT) + APS5_EXACT(CmdBindShadersEXT) + APS5_EXACT(CmdPushDescriptorSetKHR) +#undef APS5_EXACT + return functions; +} + +template +decltype(&Exact::Run) exactThunk() { + return reinterpret_cast::Run)>(AgcDriver::Graphics::CommandThunk(AgcDriver::Graphics::CommandNames()[static_cast(Id)], reinterpret_cast(&Exact::Run))); +} + +struct Sources { + std::array viewports; + std::array rects; + std::array masks; + std::array sets; + std::array dynamicOffsets; + std::array constants; + std::array vertexBuffers; + std::array vertexOffsets; + std::array memoryBarriers; + std::array bufferBarriers; + std::array imageBarriers; + std::array bufferCopies; + std::array update; + std::array bufferImageCopies; + std::array imageCopies; + std::array imageResolves; + std::array blits; + VkClearColorValue color; + VkClearDepthStencilValue depthValue; + std::array ranges; + std::array clears; + std::array clearRects; + std::array clearValues; + VkRenderPassBeginInfo pass; + std::array colors; + VkRenderingAttachmentInfoKHR depth; + VkRenderingAttachmentInfoKHR stencil; + VkRenderingInfoKHR rendering; + VkRenderingInfoKHR renderingWithoutStencil; + std::array secondaries; + VkDepthBiasInfoEXT depthBias; + std::array stages; + std::array shaders; + std::array imageInfos; + std::array bufferInfos; + std::array texelViews; + std::array writes; +}; + +template +void fill(T& value, std::uint32_t& next) { + auto* bytes = reinterpret_cast(&value); + for (std::size_t index = 0; index < sizeof(T); ++index) bytes[index] = static_cast(next++ * 37 + 11); +} + +template +void structured(T& value, VkStructureType type, std::uint32_t& next) { + fill(value, next); + value.sType = type; + value.pNext = nullptr; +} + +void prepare(Sources& sources) { + std::memset(&sources, 0, sizeof(sources)); + std::uint32_t next = 1; + for (auto& value : sources.viewports) fill(value, next); + for (auto& value : sources.rects) fill(value, next); + for (auto& value : sources.masks) fill(value, next); + for (auto& value : sources.sets) fill(value, next); + for (auto& value : sources.dynamicOffsets) fill(value, next); + fill(sources.constants, next); + for (auto& value : sources.vertexBuffers) fill(value, next); + for (auto& value : sources.vertexOffsets) fill(value, next); + for (auto& value : sources.memoryBarriers) structured(value, VK_STRUCTURE_TYPE_MEMORY_BARRIER, next); + for (auto& value : sources.bufferBarriers) structured(value, VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER, next); + for (auto& value : sources.imageBarriers) structured(value, VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, next); + for (auto& value : sources.bufferCopies) fill(value, next); + fill(sources.update, next); + for (auto& value : sources.bufferImageCopies) fill(value, next); + for (auto& value : sources.imageCopies) fill(value, next); + for (auto& value : sources.imageResolves) fill(value, next); + for (auto& value : sources.blits) fill(value, next); + fill(sources.color, next); + fill(sources.depthValue, next); + for (auto& value : sources.ranges) fill(value, next); + for (auto& value : sources.clears) fill(value, next); + for (auto& value : sources.clearRects) fill(value, next); + for (auto& value : sources.clearValues) fill(value, next); + structured(sources.pass, VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, next); + sources.pass.clearValueCount = static_cast(sources.clearValues.size()); + sources.pass.pClearValues = sources.clearValues.data(); + for (auto& value : sources.colors) structured(value, VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR, next); + structured(sources.depth, VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR, next); + structured(sources.stencil, VK_STRUCTURE_TYPE_RENDERING_ATTACHMENT_INFO_KHR, next); + structured(sources.rendering, VK_STRUCTURE_TYPE_RENDERING_INFO_KHR, next); + sources.rendering.colorAttachmentCount = static_cast(sources.colors.size()); + sources.rendering.pColorAttachments = sources.colors.data(); + sources.rendering.pDepthAttachment = &sources.depth; + sources.rendering.pStencilAttachment = &sources.stencil; + sources.renderingWithoutStencil = sources.rendering; + sources.renderingWithoutStencil.pStencilAttachment = nullptr; + for (auto& value : sources.secondaries) fill(value, next); + structured(sources.depthBias, VK_STRUCTURE_TYPE_DEPTH_BIAS_INFO_EXT, next); + sources.stages = {VK_SHADER_STAGE_VERTEX_BIT, VK_SHADER_STAGE_GEOMETRY_BIT, VK_SHADER_STAGE_FRAGMENT_BIT}; + for (auto& value : sources.shaders) fill(value, next); + for (auto& value : sources.imageInfos) fill(value, next); + for (auto& value : sources.bufferInfos) fill(value, next); + for (auto& value : sources.texelViews) fill(value, next); + for (auto& value : sources.writes) structured(value, VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, next); + const auto ignored = [](auto& pointer) { pointer = reinterpret_cast>(static_cast(0x40)); }; + for (auto& write : sources.writes) { + ignored(write.pImageInfo); + ignored(write.pBufferInfo); + ignored(write.pTexelBufferView); + } + sources.writes[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + sources.writes[0].descriptorCount = 3; + sources.writes[0].pImageInfo = sources.imageInfos.data(); + sources.writes[1].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + sources.writes[1].descriptorCount = 2; + sources.writes[1].pBufferInfo = sources.bufferInfos.data(); + sources.writes[2].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER; + sources.writes[2].descriptorCount = 2; + sources.writes[2].pTexelBufferView = sources.texelViews.data(); + sources.writes[3].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; + sources.writes[3].descriptorCount = 1; + sources.writes[3].pImageInfo = sources.imageInfos.data() + 3; + sources.writes[4].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC; + sources.writes[4].descriptorCount = 1; + sources.writes[4].pBufferInfo = sources.bufferInfos.data() + 2; +} + +void recordEverySpecializedCommand(VkCommandBuffer commands, const Sources& sources) { + exactThunk()(commands, 1, 3, sources.viewports.data()); + exactThunk()(commands, 2, 3, sources.rects.data()); + exactThunk()(commands, 1, 3, sources.masks.data()); + exactThunk()(commands, 2, sources.viewports.data()); + exactThunk()(commands, 3, sources.viewports.data()); + exactThunk()(commands, 3, sources.rects.data()); + exactThunk()(commands, 1, sources.rects.data()); + exactThunk()(commands, VK_PIPELINE_BIND_POINT_COMPUTE, fake(41), 2, 3, sources.sets.data(), 4, sources.dynamicOffsets.data()); + exactThunk()(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, fake(42), 0, 1, sources.sets.data(), 0, nullptr); + exactThunk()(commands, fake(43), VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 12, 20, sources.constants.data()); + exactThunk()(commands, 4, 3, sources.vertexBuffers.data(), sources.vertexOffsets.data()); + exactThunk()(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, VK_DEPENDENCY_BY_REGION_BIT, 2, sources.memoryBarriers.data(), 2, sources.bufferBarriers.data(), 2, sources.imageBarriers.data()); + exactThunk()(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, 0, 0, nullptr, 1, sources.bufferBarriers.data() + 1, 0, nullptr); + exactThunk()(commands, handle(51), handle(52), 2, sources.bufferCopies.data()); + exactThunk()(commands, handle(53), 24, 12, sources.update.data()); + exactThunk()(commands, handle(54), fake(55), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 2, sources.bufferImageCopies.data()); + exactThunk()(commands, fake(56), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, handle(57), 2, sources.bufferImageCopies.data()); + exactThunk()(commands, fake(58), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, fake(59), VK_IMAGE_LAYOUT_GENERAL, 2, sources.imageCopies.data()); + exactThunk()(commands, fake(158), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, fake(159), VK_IMAGE_LAYOUT_GENERAL, 2, sources.imageResolves.data()); + exactThunk()(commands, fake(60), VK_IMAGE_LAYOUT_GENERAL, fake(61), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 2, sources.blits.data(), VK_FILTER_LINEAR); + exactThunk()(commands, fake(62), VK_IMAGE_LAYOUT_GENERAL, &sources.color, 2, sources.ranges.data()); + exactThunk()(commands, fake(63), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &sources.depthValue, 2, sources.ranges.data()); + exactThunk()(commands, 2, sources.clears.data(), 2, sources.clearRects.data()); + exactThunk()(commands, &sources.pass, VK_SUBPASS_CONTENTS_INLINE); + exactThunk()(commands, &sources.rendering); + exactThunk()(commands, &sources.renderingWithoutStencil); + exactThunk()(commands, 3, sources.secondaries.data()); + exactThunk()(commands, &sources.secondaries[1]); + exactThunk()(commands, &sources.depthBias); + exactThunk()(commands, 3, sources.stages.data(), sources.shaders.data()); + exactThunk()(commands, 2, sources.stages.data(), nullptr); + exactThunk()(commands, VK_PIPELINE_BIND_POINT_GRAPHICS, fake(64), 1, 5, sources.writes.data()); +} + +std::string firstByteDifference(const std::string& expected, const std::string& actual, const std::vector>& commands) { + const auto length = std::min(expected.size(), actual.size()); + std::size_t index = 0; + while (index < length && expected[index] == actual[index]) ++index; + std::string command = "?"; + for (const auto& [offset, name] : commands) { + if (offset <= index) command = name; + } + return "first difference at byte " + std::to_string(index) + " of " + std::to_string(expected.size()) + " (" + std::to_string(actual.size()) + " replayed), in " + command; +} + +void SpecializedStreamersKeepEveryArgument() { + const auto exact = exactFunctions(); + const auto direct = FakeCommandBuffer(70); + Sources sources; + prepare(sources); + captured.clear(); + capturedCommands.clear(); + recordEverySpecializedCommand(direct, sources); + const auto expected = captured; + const auto commandsAt = capturedCommands; + Require(expected.size() > 2000, "the direct recording captured only " + std::to_string(expected.size()) + " bytes"); + const auto commands = commandsAt.size(); + Require(commands == 32, "the direct recording captured " + std::to_string(commands) + " commands"); + CommandStream stream(exact); + captured.clear(); + recordEverySpecializedCommand(stream.Handle(), sources); + Require(captured.empty(), "a specialized command reached the driver while recording"); + Require(stream.Materialized() == VK_NULL_HANDLE && !stream.Poisoned(), "a specialized command demoted the stream"); + std::memset(static_cast(&sources), 0xA5, sizeof(sources)); + stream.Seal(); + AgcDriver::Graphics::Replay(stream, direct, exact); + Require(captured == expected, "the replay after the sources were overwritten differs: " + firstByteDifference(expected, captured, commandsAt)); + Require(stream.Ops() == commands, "the stream counted " + std::to_string(stream.Ops()) + " ops for " + std::to_string(commands) + " commands"); +} + +void StreamHandlesAreNeverExecutedAsSecondaries() { + const auto exact = exactFunctions(); + const auto execute = exactThunk(); + CommandStream secondaryStream(exact); + const std::array secondaries{FakeCommandBuffer(72), secondaryStream.Handle()}; + for (const bool demoted : {false, true}) { + const std::string what = demoted ? "a demoted stream" : "a stream"; + FakeMaterializer materializer(FakeCommandBuffer(71)); + CommandStream stream(exact, nullptr, &materializer); + if (demoted) stream.Demote("vkCmdExecuteCommands test"); + captured.clear(); + Require(Throws([&] { execute(stream.Handle(), static_cast(secondaries.size()), secondaries.data()); }), what + " executed a stream handle as a secondary command buffer"); + Require(captured.empty() && stream.Ops() == 0, what + " recorded the refused vkCmdExecuteCommands"); + execute(stream.Handle(), 1, secondaries.data()); + Require(demoted ? !captured.empty() : stream.Ops() == 1, what + " did not record the execution of a real secondary command buffer"); + } +} + +VKAPI_ATTR void VKAPI_CALL emptyDraw(VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t, std::uint32_t) {} + +struct CommandCosts { + double raw = 0; + double thunk = 0; + double typedDirect = 0; + double thunkStreamed = 0; + double typedStreamed = 0; +}; + +template +double nanosPerCall(int calls, Body&& body) { + const auto start = std::chrono::steady_clock::now(); + for (int call = 0; call < calls; ++call) body(static_cast(call)); + return std::chrono::duration(std::chrono::steady_clock::now() - start).count() / calls; +} + +double median(std::vector values) { + std::sort(values.begin(), values.end()); + return values[values.size() / 2]; +} + +CommandCosts MeasureCommandCosts(int directCalls, int streamedCalls, int rounds) { + CommandFunctions direct{}; + direct.CmdDraw = &emptyDraw; + AgcDriver::Graphics::DeviceFunctions deviceTable{}; + deviceTable.cmdDraw = thunked("vkCmdDraw", &emptyDraw); + AgcDriver::Graphics::Context device{}; + device.functions = &deviceTable; + direct.listed = &deviceTable; + auto streamed = AgcDriver::Graphics::StreamedCommands(); + streamed.listed = &deviceTable; + const CommandFunctions* volatile rawDevice = &direct; + const AgcDriver::Graphics::Context* volatile context = &device; + const CommandFunctions* volatile directBatch = &direct; + const CommandFunctions* volatile streamedBatch = &streamed; + const auto target = FakeCommandBuffer(1); + std::vector raw, thunk, typed, thunkStreamed, typedStreamed; + const std::array, 3> direct3{ + [&] { raw.push_back(nanosPerCall(directCalls, [&](std::uint32_t call) { rawDevice->CmdDraw(target, call, 1, 0, 0); })); }, + [&] { thunk.push_back(nanosPerCall(directCalls, [&](std::uint32_t call) { context->Resolved(&AgcDriver::Graphics::DeviceFunctions::cmdDraw, "vkCmdDraw")(target, call, 1, 0, 0); })); }, + [&] { typed.push_back(nanosPerCall(directCalls, [&](std::uint32_t call) { context->ForBatch(directBatch, &CommandFunctions::CmdDraw, &AgcDriver::Graphics::DeviceFunctions::cmdDraw, "vkCmdDraw")(target, call, 1, 0, 0); })); }, + }; + for (int round = 0; round < rounds; ++round) { + for (std::size_t step = 0; step < direct3.size(); ++step) direct3[(step + static_cast(round)) % direct3.size()](); + { + CommandStream stream(direct); + const auto handle = stream.Handle(); + thunkStreamed.push_back(nanosPerCall(streamedCalls, [&](std::uint32_t call) { context->Resolved(&AgcDriver::Graphics::DeviceFunctions::cmdDraw, "vkCmdDraw")(handle, call, 1, 0, 0); })); + } + { + CommandStream stream(direct); + const auto handle = stream.Handle(); + typedStreamed.push_back(nanosPerCall(streamedCalls, [&](std::uint32_t call) { context->ForBatch(streamedBatch, &CommandFunctions::CmdDraw, &AgcDriver::Graphics::DeviceFunctions::cmdDraw, "vkCmdDraw")(handle, call, 1, 0, 0); })); + } + } + std::vector typedOver, thunkOver; + for (std::size_t round = 0; round < raw.size(); ++round) { + typedOver.push_back(typed[round] - raw[round]); + thunkOver.push_back(thunk[round] - raw[round]); + } + CommandCosts costs; + costs.raw = median(raw); + costs.thunk = costs.raw + median(thunkOver); + costs.typedDirect = costs.raw + median(typedOver); + costs.thunkStreamed = median(thunkStreamed); + costs.typedStreamed = median(typedStreamed); + return costs; +} + +VKAPI_ATTR void VKAPI_CALL emptyPush(VkCommandBuffer, VkPipelineBindPoint, VkPipelineLayout, std::uint32_t, std::uint32_t, const VkWriteDescriptorSet*) {} + +void PushDescriptorCost(int calls, int rounds) { + CommandFunctions direct{}; + direct.CmdPushDescriptorSetKHR = &emptyPush; + const auto streamedPush = AgcDriver::Graphics::StreamedCommands().CmdPushDescriptorSetKHR; + std::array images{}; + VkDescriptorBufferInfo buffer{fake(1), 0, 256}; + std::array writes{}; + for (auto& write : writes) write.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; + writes[0].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; + writes[0].descriptorCount = 2; + writes[0].pImageInfo = images.data(); + writes[1].dstBinding = 1; + writes[1].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; + writes[1].descriptorCount = 1; + writes[1].pBufferInfo = &buffer; + std::vector raw, append, replay; + for (int round = 0; round < rounds; ++round) { + raw.push_back(nanosPerCall(calls, [&](std::uint32_t call) { direct.CmdPushDescriptorSetKHR(FakeCommandBuffer(1), VK_PIPELINE_BIND_POINT_GRAPHICS, fake(call & 7), 0, 2, writes.data()); })); + CommandStream stream(direct); + const auto handle = stream.Handle(); + append.push_back(nanosPerCall(calls, [&](std::uint32_t call) { streamedPush(handle, VK_PIPELINE_BIND_POINT_GRAPHICS, fake(call & 7), 0, 2, writes.data()); })); + stream.Seal(); + const auto start = std::chrono::steady_clock::now(); + AgcDriver::Graphics::Replay(stream, FakeCommandBuffer(1), direct); + replay.push_back(std::chrono::duration(std::chrono::steady_clock::now() - start).count() / calls); + } + std::printf("push descriptors (2 writes, 3 descriptors; medians of %d rounds): direct %.2f ns, streamed append %.2f ns, replay %.2f ns per call\n", rounds, median(raw), median(append), median(replay)); +} + +VKAPI_ATTR void VKAPI_CALL emptyStencil(VkCommandBuffer, VkStencilFaceFlags, std::uint32_t) {} + +void KeyedLookupCost(int calls, int rounds) { + using AgcDriver::Graphics::CommandThunk; + constexpr const char* Name = "vkCmdSetStencilReference"; + const auto reals = stencils(std::make_integer_sequence{}); + for (const auto real : reals) CommandThunk(Name, reinterpret_cast(real)); + static const int keys[4] = {}; + std::array devices{FakeDispatchable{&keys[0]}, FakeDispatchable{&keys[1]}, FakeDispatchable{&keys[2]}, FakeDispatchable{&keys[3]}}; + std::array buffers = devices; + PFN_vkCmdSetStencilReference keyed = nullptr; + for (auto& device : devices) keyed = reinterpret_cast(CommandThunk(Name, reinterpret_cast(&emptyStencil), deviceOf(device))); + volatile PFN_vkCmdSetStencilReference raw = &emptyStencil; + std::vector direct, newest, oldest; + for (int round = 0; round < rounds; ++round) { + direct.push_back(nanosPerCall(calls, [&](std::uint32_t call) { raw(commandsOf(buffers[3]), VK_STENCIL_FACE_FRONT_BIT, call); })); + newest.push_back(nanosPerCall(calls, [&](std::uint32_t call) { keyed(commandsOf(buffers[3]), VK_STENCIL_FACE_FRONT_BIT, call); })); + oldest.push_back(nanosPerCall(calls, [&](std::uint32_t call) { keyed(commandsOf(buffers[0]), VK_STENCIL_FACE_FRONT_BIT, call); })); + } + for (auto& device : devices) AgcDriver::Graphics::ForgetCommandDevice(deviceOf(device)); + std::printf("keyed lookup past the slots, 4 devices (medians of %d rounds): raw %.2f ns, first node %.2f ns, fourth node %.2f ns per call\n", rounds, median(direct), median(newest), median(oldest)); +} + +bool InstrumentedBuild() { +#if defined(__SANITIZE_ADDRESS__) || defined(__SANITIZE_THREAD__) + return true; +#elif defined(__has_feature) +#if __has_feature(address_sanitizer) || __has_feature(thread_sanitizer) + return true; +#else + return false; +#endif +#else + return false; +#endif +} + +int DirectModeCost() { + constexpr int DirectCalls = 5'000'000; + constexpr int StreamedCalls = 1'000'000; + constexpr int Rounds = 21; + PushDescriptorCost(StreamedCalls / 4, Rounds); + KeyedLookupCost(StreamedCalls, Rounds); + const auto costs = MeasureCommandCosts(DirectCalls, StreamedCalls, Rounds); + const double thunkOver = costs.thunk - costs.raw; + const double typedOver = costs.typedDirect - costs.raw; + std::printf("command cost (medians of %d interleaved rounds, each through its table): direct batch: raw %.2f ns, thunk %.2f ns (+%.2f), typed %.2f ns (+%.2f); streamed batch: thunk %.2f ns, typed %.2f ns\n", Rounds, costs.raw, costs.thunk, thunkOver, costs.typedDirect, typedOver, costs.thunkStreamed, costs.typedStreamed); + if (thunkOver < 0.2) { + std::printf("the thunk adds %.2f ns here, too little to tell a typed call from it; not gated\n", thunkOver); + return 0; + } + const bool resolvable = thunkOver >= 0.5; + const double limit = resolvable ? thunkOver * 0.75 : thunkOver + 0.1; + if (typedOver <= limit) return 0; + if (InstrumentedBuild()) { + std::printf("typed direct adds %.2f ns over the limit of %.2f ns from the thunk's %.2f ns; not gated in a sanitizer build\n", typedOver, limit, thunkOver); + return 0; + } + if (resolvable) std::fprintf(stderr, "command thunks: a direct batch's typed command adds %.2f ns over a raw table call, more than three quarters of the thunk's %.2f ns\n", typedOver, thunkOver); + else std::fprintf(stderr, "command thunks: a direct batch's typed command adds %.2f ns over a raw table call, more than the thunk's %.2f ns\n", typedOver, thunkOver); + return 1; +} + +} + +int batchDraws = 0; +int hookDraws = 0; +int batchViewports = 0; +int hookViewports = 0; + +VKAPI_ATTR void VKAPI_CALL batchDraw(VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t, std::uint32_t) { + ++batchDraws; +} + +VKAPI_ATTR void VKAPI_CALL hookDraw(VkCommandBuffer, std::uint32_t, std::uint32_t, std::uint32_t, std::uint32_t) { + ++hookDraws; +} + +VKAPI_ATTR void VKAPI_CALL batchViewport(VkCommandBuffer, std::uint32_t, std::uint32_t, const VkViewport*) { + ++batchViewports; +} + +VKAPI_ATTR void VKAPI_CALL hookViewport(VkCommandBuffer, std::uint32_t, std::uint32_t, const VkViewport*) { + ++hookViewports; +} + +void BatchTablesDeferToTheContextsOwnEntryPoints() { + using AgcDriver::Graphics::DeviceFunctions; + const auto target = FakeCommandBuffer(3); + const VkViewport viewport{}; + DeviceFunctions table{}; + table.cmdDraw = thunked("vkCmdDraw", &batchDraw); + table.cmdSetViewport = thunked("vkCmdSetViewport", &batchViewport); + CommandFunctions batch{}; + batch.CmdDraw = &batchDraw; + batch.CmdSetViewport = &batchViewport; + batch.listed = &table; + AgcDriver::Graphics::Context context{}; + context.functions = &table; + const auto record = [&](const AgcDriver::Graphics::Context& through, const CommandFunctions* commands) { + through.ForBatch(through.BatchFor(commands), &CommandFunctions::CmdDraw, &DeviceFunctions::cmdDraw, "vkCmdDraw")(target, 3, 1, 0, 0); + through.ForBatch(through.BatchFor(commands), &CommandFunctions::CmdSetViewport, &DeviceFunctions::cmdSetViewport, "vkCmdSetViewport")(target, 0, 1, &viewport); + }; + const auto counts = [&] { return std::array{batchDraws, hookDraws, batchViewports, hookViewports}; }; + Require(context.ForBatch(context.BatchFor(&batch), &CommandFunctions::CmdDraw, &DeviceFunctions::cmdDraw, "vkCmdDraw") == &batchDraw, "a batch built against the context's table did not use its own entry point"); + record(context, &batch); + Require((counts() == std::array{1, 0, 1, 0}), "a batch built against the context's table did not reach its entry points"); + DeviceFunctions traced = table; + traced.cmdDraw = &hookDraw; + traced.cmdSetViewport = &hookViewport; + AgcDriver::Graphics::Context tracing = context; + tracing.functions = &traced; + record(tracing, &batch); + Require((counts() == std::array{1, 1, 1, 1}), "a context with its own table recorded into a batch built against another table bypassed its own entry points"); + CommandFunctions unlisted = batch; + unlisted.listed = nullptr; + record(tracing, &unlisted); + Require((counts() == std::array{1, 2, 1, 2}), "a batch built without a table bypassed the context's table"); + AgcDriver::Graphics::Context bare{}; + record(bare, &unlisted); + Require((counts() == std::array{2, 2, 2, 2}), "a context without a table did not use the batch's entry points"); +} + +int main(int argc, char** argv) { + try { + if (argc == 2 && std::string_view(argv[1]) == "--bench") return DirectModeCost(); + EveryListedCommandHasAThunk(); + EveryListedCommandStreams(); + DirectCallsReachTheirOwnEntryPoint(); + StreamReplayRecordsWhatDirectRecords(); + DemotionReplaysThePrefixInOrder(); + SpecializedStreamersKeepEveryArgument(); + StreamHandlesAreNeverExecutedAsSecondaries(); + PushDescriptorsDemoteOnlyWhatTheyCannotCopy(); + DemotionWithoutAMaterializerPoisons(); + EntryPointsBeyondTheSlotsAreKeyedByDevice(); + BatchTablesDeferToTheContextsOwnEntryPoints(); + std::cout << "command thunks passed\n"; + return 0; + } catch (const std::exception& error) { + std::fprintf(stderr, "command thunks: %s\n", error.what()); + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/DeviceFault.cpp b/core/libs/prx/libSceAgcDriver/tests/DeviceFault.cpp index 8ef1d6f9bba1..32bc5a7736e5 100644 --- a/core/libs/prx/libSceAgcDriver/tests/DeviceFault.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/DeviceFault.cpp @@ -1,5 +1,6 @@ #include "prx/libSceAgcDriver/Execution/include/DeviceFault.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" +#include "FakeHandles.hpp" #include #include #include @@ -450,7 +451,7 @@ void TokenEmission() { emitCmd = VK_NULL_HANDLE; emitMarker = nullptr; emitCalls = 0; - static VkCommandBuffer fakeCmd = reinterpret_cast(static_cast(0xC0FFEE1)); + static VkCommandBuffer fakeCmd = FakeCommandBuffer(0xC0FFEE1); AgcDriver::Graphics::EmitNvCheckpointToken(fakeCmd, token, MockEmitCheckpoint); Require(emitCalls == 1, "the checkpoint backend was not called once"); Require(emitCmd == fakeCmd, "the checkpoint backend got the wrong command buffer"); @@ -597,7 +598,7 @@ void IndirectRoundTrip() { emitCmd = VK_NULL_HANDLE; emitMarker = nullptr; emitCalls = 0; - static VkCommandBuffer fakeCmd = reinterpret_cast(static_cast(0xC0FFEE2)); + static VkCommandBuffer fakeCmd = FakeCommandBuffer(0xC0FFEE2); AgcDriver::Graphics::EmitNvCheckpointToken(fakeCmd, token, MockEmitCheckpoint); Require(emitCalls == 1, "the indirect checkpoint backend was not called once"); Require(emitCmd == fakeCmd, "the indirect checkpoint backend got the wrong command buffer"); diff --git a/core/libs/prx/libSceAgcDriver/tests/FakeHandles.hpp b/core/libs/prx/libSceAgcDriver/tests/FakeHandles.hpp new file mode 100644 index 000000000000..e5d7a2903763 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/FakeHandles.hpp @@ -0,0 +1,10 @@ +#pragma once + +#include + +#include + +inline VkCommandBuffer FakeCommandBuffer(std::uintptr_t index) noexcept { + constexpr std::uintptr_t dispatchableAlignment = 16; + return reinterpret_cast(index * dispatchableAlignment); +} diff --git a/core/libs/prx/libSceAgcDriver/tests/FrameReplayState.cpp b/core/libs/prx/libSceAgcDriver/tests/FrameReplayState.cpp index 77d389b62646..2abd16e7d9af 100644 --- a/core/libs/prx/libSceAgcDriver/tests/FrameReplayState.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/FrameReplayState.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" +#include "FakeHandles.hpp" #define main frameReplayToolMain #include "../tools/FrameReplay.cpp" #undef main @@ -829,7 +830,7 @@ std::uintptr_t mockHandles = 1; std::map mockFences; VKAPI_ATTR VkResult VKAPI_CALL mockAllocateCommandBuffers(VkDevice, const VkCommandBufferAllocateInfo*, VkCommandBuffer* commands) { - *commands = reinterpret_cast(mockHandles++); + *commands = FakeCommandBuffer(mockHandles++); return VK_SUCCESS; } diff --git a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp index 102ef4b051d2..5d4ee89b8be7 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Graphics.cpp @@ -1,6 +1,7 @@ #include "prx/libc/include/Api.hpp" #include "RdnaDecoder/RdnaInstructionDecoder.hpp" #include "BdaTests.hpp" +#include "FakeHandles.hpp" #include "GraphicsTests.hpp" #include "CommandStateLog.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" @@ -6430,7 +6431,8 @@ bool releaseOptimizedLink = false; template THandle makeHandle() { const auto value = mock.next++; - if constexpr (std::is_pointer_v) return reinterpret_cast(static_cast(value)); + if constexpr (std::is_same_v) return FakeCommandBuffer(value); + else if constexpr (std::is_pointer_v) return reinterpret_cast(static_cast(value)); else return static_cast(value); } @@ -7978,7 +7980,7 @@ void resourceTests() { mock = MockVulkan{}; const auto context = mockContext(); const auto state = AgcDriver::Graphics::DecodeState(makeState()); - const auto commands = reinterpret_cast(std::uintptr_t{1}); + const auto commands = FakeCommandBuffer(1); { ShaderRecompiler::RecompileResult vertex; ShaderRecompiler::RecompileResult fragment; @@ -9303,7 +9305,7 @@ void misalignedShaderDataTests() { mock = MockVulkan{}; auto context = mockContext(); context.limits.minStorageBufferOffsetAlignment = 16; - const auto commands = reinterpret_cast(std::uintptr_t{1}); + const auto commands = FakeCommandBuffer(1); alignas(64) std::array guest{1, 2, 3, 4, 5, 6, 7, 8}; { ShaderRecompiler::RecompileResult compute; @@ -9338,7 +9340,7 @@ void imageTableTemplateRefreshTests() { context.imageTableCapacity = 2; context.limits.maxDescriptorSetSampledImages = 2; context.limits.maxPerStageDescriptorSampledImages = 2; - const auto commands = reinterpret_cast(std::uintptr_t{1}); + const auto commands = FakeCommandBuffer(1); { ShaderRecompiler::RecompileResult compute; auto map = makeBinding(Role::ImageTableMap, static_cast(ShaderRecompiler::RuntimeAbi::Binding::ImageTableMap), 1, std::vector(Abi::HeaderWords)); diff --git a/core/libs/prx/libSceAgcDriver/tests/HostImportRetireHold.cpp b/core/libs/prx/libSceAgcDriver/tests/HostImportRetireHold.cpp index 05a483a40521..c299229a2b94 100644 --- a/core/libs/prx/libSceAgcDriver/tests/HostImportRetireHold.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/HostImportRetireHold.cpp @@ -1,4 +1,5 @@ #include "HostImportFailure.hpp" +#include "FakeHandles.hpp" #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" @@ -54,7 +55,7 @@ bool Live(VkBuffer buffer) { } VKAPI_ATTR VkResult VKAPI_CALL mockAllocateCommandBuffers(VkDevice, const VkCommandBufferAllocateInfo*, VkCommandBuffer* commands) { - *commands = reinterpret_cast(mock.next++); + *commands = FakeCommandBuffer(mock.next++); return VK_SUCCESS; } diff --git a/core/libs/prx/libSceAgcDriver/tests/HostImportSparseDmaBuf.cpp b/core/libs/prx/libSceAgcDriver/tests/HostImportSparseDmaBuf.cpp index ce5b285dd0dc..a0e9af0801d1 100644 --- a/core/libs/prx/libSceAgcDriver/tests/HostImportSparseDmaBuf.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/HostImportSparseDmaBuf.cpp @@ -1,4 +1,5 @@ #include "prx/libSceAgcDriver/Graphics/include/GuestBufferMemory.hpp" +#include "FakeHandles.hpp" #include "AllocationFailure.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Graphics/include/UnitShadow.hpp" @@ -93,7 +94,7 @@ VKAPI_ATTR void VKAPI_CALL mockDestroyFence(VkDevice, VkFence fence, const VkAll } VKAPI_ATTR VkResult VKAPI_CALL mockAllocateCommandBuffers(VkDevice, const VkCommandBufferAllocateInfo*, VkCommandBuffer* commands) { - *commands = reinterpret_cast(mock.next++); + *commands = FakeCommandBuffer(mock.next++); return VK_SUCCESS; } diff --git a/core/libs/prx/libSceAgcDriver/tests/PerformanceTrace.cpp b/core/libs/prx/libSceAgcDriver/tests/PerformanceTrace.cpp index b6e338bc1f78..625e274c4819 100644 --- a/core/libs/prx/libSceAgcDriver/tests/PerformanceTrace.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/PerformanceTrace.cpp @@ -377,15 +377,24 @@ void SummaryFields() { "\"worker_busy_pct\":{\"queue worker 0x0\":35.000}," "\"phase_totals_ms\":{\"Driver.Completion\":2.000,\"Driver.Packet\":12.000,\"Driver.Packet.draw\":10.000,\"Driver.Present\":6.000,\"Driver.Present.inflight_wait\":4.000}," "\"top_phases_ms_per_frame\":{\"Driver.Packet\":6.000,\"Driver.Packet.draw\":5.000,\"Driver.Present\":3.000,\"Driver.Present.inflight_wait\":2.000,\"Driver.Completion\":1.000}," - "\"owned_draw_counts\":{},\"graphics_track\":{},\"trace_dropped\":false,\"trace\":\"aps5-trace-abc-7.json.gz\"}\n"; + "\"owned_draw_counts\":{},\"encoder\":{\"posts\":0,\"commands\":0,\"waits\":0,\"wait_ms_per_frame\":0.000},\"graphics_track\":{}," + "\"trace_dropped\":false,\"trace\":\"aps5-trace-abc-7.json.gz\"}\n"; Check(line == expected, "summary line changed"); auto unboundSummary = summary; unboundSummary.ownedDrawUnbound = 3; const auto unboundLine = TraceFormat::Summary(unboundSummary, threads, presents); - Check(unboundLine.find("\"owned_draw_counts\":{\"OwnedDraw.unbound\":3},\"graphics_track\":{},\"trace_dropped\":true") != std::string::npos, "unbound draw counts were not marked as incomplete"); + Check(unboundLine.find("\"owned_draw_counts\":{\"OwnedDraw.unbound\":3},\"encoder\":{\"posts\":0,\"commands\":0,\"waits\":0,\"wait_ms_per_frame\":0.000},\"graphics_track\":{},\"trace_dropped\":true") != std::string::npos, "unbound draw counts were not marked as incomplete"); auto drained = threads; drained[0].totals.push_back({"Driver.FinisherDrain", nullptr, milliseconds(4), 2}); Check(TraceFormat::Summary(summary, drained, presents).find("\"worker_busy_pct\":{\"queue worker 0x0\":45.000}") != std::string::npos, "the queue worker's waits for the draw finisher were not counted as busy"); + auto encoded = threads; + encoded[0].totals.push_back({"Encoder.post", nullptr, {}, 3}); + encoded[1].totals.push_back({"Encoder.post", nullptr, {}, 2}); + encoded[0].totals.push_back({"Encoder.command", nullptr, {}, 40}); + encoded[1].totals.push_back({"Encoder.wait", nullptr, milliseconds(6), 4}); + const auto encodedLine = TraceFormat::Summary(summary, encoded, presents); + Check(encodedLine.find("\"encoder\":{\"posts\":5,\"commands\":40,\"waits\":4,\"wait_ms_per_frame\":3.000}") != std::string::npos, "encoder posts, commands and waits were not summed across threads"); + Check(encodedLine.find("Encoder.") == std::string::npos, "encoder scopes were listed as phases"); auto counted = threads; counted[0].totals.push_back({"OwnedDraw.arm_attempt", nullptr, {}, 5}); counted[1].totals.push_back({"OwnedDraw.arm_attempt", nullptr, {}, 3}); @@ -527,7 +536,7 @@ void IntervalSummaryFields() { "\"worker_busy_pct\":{\"queue worker 0x0\":30.000}," "\"phase_totals_ms\":{\"Driver.Packet\":12.000}," "\"top_phases_ms_per_frame\":{\"Driver.Packet\":6.000}," - "\"owned_draw_counts\":{},\"graphics_track\":{},\"trace_dropped\":false,\"trace\":\"\"}\n"; + "\"owned_draw_counts\":{},\"encoder\":{\"posts\":0,\"commands\":0,\"waits\":0,\"wait_ms_per_frame\":0.000},\"graphics_track\":{},\"trace_dropped\":false,\"trace\":\"\"}\n"; Check(line == expected, "interval summary line changed"); } diff --git a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp index e5fb32ed8c09..0052adcd9ca3 100644 --- a/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/Recorder.cpp @@ -563,6 +563,19 @@ class Device { minLod.pNext = address.pNext; address.pNext = &minLod; } + VkPhysicalDeviceTimelineSemaphoreFeaturesKHR timelineFeatures{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TIMELINE_SEMAPHORE_FEATURES_KHR}; + if (hasExtension(VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME)) { + VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &timelineFeatures}; + function("vkGetPhysicalDeviceFeatures2")(context.physical, &features); + timelineSemaphores = timelineFeatures.timelineSemaphore == VK_TRUE; + } + timelineFeatures = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_TIMELINE_SEMAPHORE_FEATURES_KHR}; + timelineFeatures.timelineSemaphore = VK_TRUE; + if (timelineSemaphores) { + extensionsEnabled.push_back(VK_KHR_TIMELINE_SEMAPHORE_EXTENSION_NAME); + timelineFeatures.pNext = address.pNext; + address.pNext = &timelineFeatures; + } VkPhysicalDeviceExtendedDynamicState3FeaturesEXT dynamicState3{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_3_FEATURES_EXT}; if (std::getenv("APS5_NO_DYNAMIC_COLOR_WRITE_MASK") == nullptr && hasExtension(VK_EXT_EXTENDED_DYNAMIC_STATE_3_EXTENSION_NAME)) { VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &dynamicState3}; @@ -680,8 +693,14 @@ class Device { ~Device() { release(); } bool NullDescriptors() const { return nullDescriptors; } bool PushDescriptors() const { return pushDescriptors; } + bool TimelineSemaphores() const { return timelineSemaphores; } void UsePushDescriptors() { context.pushDescriptors = pushDescriptors; } const Context& GetContext() const { return context; } + DeviceFunctions* UseFunctionTable() { + FillDeviceFunctions(context, functions); + context.functions = &functions; + return &functions; + } bool Graphics() const { return graphics; } bool Timestamps() const { std::uint32_t count = 0; @@ -741,8 +760,10 @@ class Device { bool graphics = false; std::mutex settleMutex; bool nullDescriptors = false; + DeviceFunctions functions{}; bool memoryBudget = false; bool pushDescriptors = false; + bool timelineSemaphores = false; }; using Kind = Recorder::ReadKind; @@ -2024,6 +2045,866 @@ void completionWaitTests(const Device& device, Recorder& recorder) { Require(memory[1] == 9u && Recorder::PendingCompletionLabels() == 0, "completion wait: a reader of a label stored behind a completion did not wait for that store"); } +void recordBarrierThrough(const Context& context, VkCommandBuffer commands) { + const VkMemoryBarrier barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT}; + context.Function("vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &barrier, 0, nullptr, 0, nullptr); +} + +PFN_vkGetDeviceProcAddr passedDeviceProc = nullptr; +PFN_vkEndCommandBuffer passedEndCommandBuffer = nullptr; +PFN_vkQueueSubmit passedQueueSubmit = nullptr; +std::atomic failingEnds{0}; +std::atomic countedSubmits{0}; +std::atomic refusedSubmits{false}; +std::atomic lostSubmits{0}; +std::atomic failingBarriers{0}; +std::atomic failingFences{0}; +std::atomic lostIdles{0}; +std::atomic stalledTimeline{false}; +std::atomic countedSerialWaits{0}; +thread_local bool countingSerialWaits = false; +PFN_vkWaitForFences passedWaitForFences = nullptr; +VkDevice commandsDevice = VK_NULL_HANDLE; +std::atomic liveCommandBuffers{0}; + +VKAPI_ATTR VkResult VKAPI_CALL failingEndCommandBuffer(VkCommandBuffer commands) { + if (failingEnds.load() != 0) { + failingEnds.fetch_sub(1); + return VK_ERROR_OUT_OF_DEVICE_MEMORY; + } + return passedEndCommandBuffer(commands); +} + +struct SubmitCapture { + std::uint64_t signal = 0; + VkSemaphore wait = VK_NULL_HANDLE; + std::uint64_t waitValue = 0; +}; +std::mutex submitCaptureMutex; +std::vector submitCaptures; + +void captureSubmit(const VkSubmitInfo& submit) { + SubmitCapture capture; + for (const auto* next = static_cast(submit.pNext); next != nullptr; next = next->pNext) { + if (next->sType != VK_STRUCTURE_TYPE_TIMELINE_SEMAPHORE_SUBMIT_INFO) continue; + const auto& timeline = *reinterpret_cast(next); + if (timeline.signalSemaphoreValueCount != 0) capture.signal = timeline.pSignalSemaphoreValues[0]; + if (timeline.waitSemaphoreValueCount != 0) capture.waitValue = timeline.pWaitSemaphoreValues[0]; + } + if (submit.waitSemaphoreCount != 0) capture.wait = submit.pWaitSemaphores[0]; + std::lock_guard lock(submitCaptureMutex); + submitCaptures.push_back(capture); +} + +std::vector takeSubmitCaptures() { + std::lock_guard lock(submitCaptureMutex); + return std::exchange(submitCaptures, {}); +} + +VKAPI_ATTR VkResult VKAPI_CALL countingQueueSubmit(VkQueue queue, std::uint32_t count, const VkSubmitInfo* submits, VkFence fence) { + countedSubmits.fetch_add(1); + for (std::uint32_t index = 0; index < count; ++index) captureSubmit(submits[index]); + if (refusedSubmits.load()) return VK_ERROR_OUT_OF_HOST_MEMORY; + if (lostSubmits.load() != 0) { + lostSubmits.fetch_sub(1); + return VK_ERROR_DEVICE_LOST; + } + return passedQueueSubmit(queue, count, submits, fence); +} + +VKAPI_ATTR VkResult VKAPI_CALL failingWaitForFences(VkDevice device, std::uint32_t count, const VkFence* fences, VkBool32 all, std::uint64_t timeout) { + if (failingFences.load() != 0) { + failingFences.fetch_sub(1); + return VK_ERROR_OUT_OF_DEVICE_MEMORY; + } + return passedWaitForFences(device, count, fences, all, timeout); +} + +VKAPI_ATTR VkResult VKAPI_CALL losingDeviceWaitIdle(VkDevice device) { + if (lostIdles.load() != 0) { + lostIdles.fetch_sub(1); + return VK_ERROR_DEVICE_LOST; + } + return reinterpret_cast(passedDeviceProc(device, "vkDeviceWaitIdle"))(device); +} + +VKAPI_ATTR VkResult VKAPI_CALL stallingCounterValue(VkDevice device, VkSemaphore semaphore, std::uint64_t* value) { + if (stalledTimeline.load()) { + *value = 0; + return VK_SUCCESS; + } + return reinterpret_cast(passedDeviceProc(device, "vkGetSemaphoreCounterValueKHR"))(device, semaphore, value); +} + +VKAPI_ATTR VkResult VKAPI_CALL stallingWaitSemaphores(VkDevice device, const VkSemaphoreWaitInfo* info, std::uint64_t timeout) { + if (countingSerialWaits) countedSerialWaits.fetch_add(1); + if (stalledTimeline.load()) return VK_TIMEOUT; + return reinterpret_cast(passedDeviceProc(device, "vkWaitSemaphoresKHR"))(device, info, timeout); +} + +VKAPI_ATTR VkResult VKAPI_CALL countingAllocateCommandBuffers(VkDevice device, const VkCommandBufferAllocateInfo* info, VkCommandBuffer* buffers) { + const auto result = reinterpret_cast(passedDeviceProc(device, "vkAllocateCommandBuffers"))(device, info, buffers); + if (result == VK_SUCCESS) liveCommandBuffers.fetch_add(info->commandBufferCount); + return result; +} + +VKAPI_ATTR void VKAPI_CALL countingFreeCommandBuffers(VkDevice device, VkCommandPool pool, std::uint32_t count, const VkCommandBuffer* buffers) { + for (std::uint32_t index = 0; index < count; ++index) { + if (buffers[index] != VK_NULL_HANDLE) liveCommandBuffers.fetch_sub(1); + } + reinterpret_cast(passedDeviceProc(device, "vkFreeCommandBuffers"))(device, pool, count, buffers); +} + +VKAPI_ATTR void VKAPI_CALL failingPipelineBarrier(VkCommandBuffer commands, VkPipelineStageFlags source, VkPipelineStageFlags destination, VkDependencyFlags flags, std::uint32_t memoryCount, const VkMemoryBarrier* memory, std::uint32_t bufferCount, const VkBufferMemoryBarrier* buffers, std::uint32_t imageCount, const VkImageMemoryBarrier* images) { + if (failingBarriers.load() != 0) { + failingBarriers.fetch_sub(1); + throw std::runtime_error("vkCmdPipelineBarrier: injected failure"); + } + std::vector unchained(memory, memory + memoryCount); + for (auto& barrier : unchained) barrier.pNext = nullptr; + reinterpret_cast(passedDeviceProc(commandsDevice, "vkCmdPipelineBarrier"))(commands, source, destination, flags, memoryCount, unchained.data(), bufferCount, buffers, imageCount, images); +} + +void demoteThrough(const Context& context, VkCommandBuffer commands) { + const VkMemoryBarrier chain{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, 0, 0}; + const VkMemoryBarrier barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER, &chain, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_TRANSFER_READ_BIT}; + context.Function("vkCmdPipelineBarrier")(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 1, &barrier, 0, nullptr, 0, nullptr); +} + +VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL replayFailingDeviceProc(VkDevice device, const char* name) { + if (std::strcmp(name, "vkAllocateCommandBuffers") == 0) return reinterpret_cast(countingAllocateCommandBuffers); + if (std::strcmp(name, "vkFreeCommandBuffers") == 0) return reinterpret_cast(countingFreeCommandBuffers); + if (std::strcmp(name, "vkCmdPipelineBarrier") == 0) { + commandsDevice = device; + return reinterpret_cast(failingPipelineBarrier); + } + if (std::strcmp(name, "vkEndCommandBuffer") == 0) return reinterpret_cast(failingEndCommandBuffer); + if (std::strcmp(name, "vkQueueSubmit") == 0) return reinterpret_cast(countingQueueSubmit); + if (std::strcmp(name, "vkDeviceWaitIdle") == 0) return reinterpret_cast(losingDeviceWaitIdle); + if (std::strcmp(name, "vkGetSemaphoreCounterValueKHR") == 0) return reinterpret_cast(stallingCounterValue); + if (std::strcmp(name, "vkWaitSemaphoresKHR") == 0) return reinterpret_cast(stallingWaitSemaphores); + if (std::strcmp(name, "vkWaitForFences") == 0) { + passedWaitForFences = reinterpret_cast(passedDeviceProc(device, name)); + return reinterpret_cast(failingWaitForFences); + } + return passedDeviceProc(device, name); +} + +bool failedWith(const std::function& body, std::string_view reason) { + try { + body(); + } catch (const std::exception& error) { + return std::string_view(error.what()).find(reason) != std::string_view::npos; + } + return false; +} + +std::future failedSerialWait(Recorder& recorder, std::uint64_t serial) { + const auto entered = countedSerialWaits.load(); + auto waited = std::async(std::launch::async, [&recorder, serial] { + countingSerialWaits = true; + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30); + try { + while (!recorder.WaitSerialFor(serial, 100'000'000ull)) { + if (std::chrono::steady_clock::now() > deadline) return false; + } + } catch (const std::exception&) { + return true; + } + return false; + }); + while (countedSerialWaits.load() == entered && waited.wait_for(std::chrono::seconds(0)) != std::future_status::ready) std::this_thread::yield(); + return waited; +} + +void finishAfterDeviceLossTests(const Device& device) { + if (!device.TimelineSemaphores()) { + std::cout << "skipped, no timeline semaphores: finishing a batch in flight after device loss not tested\n"; + return; + } + const auto& context = device.GetContext(); + passedDeviceProc = context.deviceProc; + passedEndCommandBuffer = reinterpret_cast(context.deviceProc(context.device, "vkEndCommandBuffer")); + passedQueueSubmit = reinterpret_cast(context.deviceProc(context.device, "vkQueueSubmit")); + Context failing = context; + failing.deviceProc = replayFailingDeviceProc; + const char* recordInline = std::getenv("APS5_RECORD_INLINE"); + const bool deferring = recordInline == nullptr || std::strcmp(recordInline, "0") == 0; + if (!deferring) std::cout << "APS5_RECORD_INLINE: finishing a deferred batch after device loss not tested\n"; + for (const bool deferred : {false, true}) { + if (deferred && !deferring) continue; + const auto buffersBefore = liveCommandBuffers.load(); + bool lost = false; + bool finishedLost = false; + bool finished = false; + std::string next; + { + Recorder recorder(failing, true, deferred, context.queueFamily, WorkBudget::Limits{4, 1, 64u << 20}); + struct Unstall { + ~Unstall() { stalledTimeline.store(false); } + } unstall; + recordBarrierThrough(failing, recorder.Commands()); + stalledTimeline.store(true); + recorder.Submit(); + recordBarrierThrough(failing, recorder.Commands()); + lostSubmits.store(1); + lostIdles.store(1); + lost = failedWith([&] { recorder.Submit(); }, "Vulkan result -4"); + lostSubmits.store(0); + lostIdles.store(0); + Check(context.Function("vkDeviceWaitIdle")(context.device), "vkDeviceWaitIdle before finishing the stalled batch"); + finishedLost = failedWith([&] { recorder.Sync(); }, "Vulkan result -4"); + stalledTimeline.store(false); + finished = recorder.InFlightBatches() == 0; + if (deferred) { + try { + const auto before = recorder.StreamCounts(); + recorder.Commands(); + const auto after = recorder.StreamCounts(); + next = after.deferred > before.deferred ? "deferred" : after.direct > before.direct ? "direct" : "none"; + } catch (const std::exception& error) { + next = error.what(); + } + } + } + stalledTimeline.store(false); + const std::string mode = deferred ? "deferred" : "direct"; + Require(lost, "the injected device loss on a " + mode + " submit did not surface"); + Require(finishedLost, "finishing a " + mode + " batch whose timeline wait the device loss stopped did not surface the loss"); + Require(finished, "a " + mode + " batch was still in flight after its finish saw the device loss"); + Require(liveCommandBuffers.load() == buffersBefore, "finishing a " + mode + " batch after device loss leaked " + std::to_string(liveCommandBuffers.load() - buffersBefore) + " command buffers"); + Require(!deferred || next == "deferred", "with room for one deferred batch, the batch after one finished on device loss was " + next + ", so the finished batch was never released by the GPU"); + } + std::cout << "a batch finished on device loss is released and frees its command buffer\n"; +} + +void sealedBatchTests(const Device& device) { + if (!device.TimelineSemaphores()) { + std::cout << "skipped, no timeline semaphores: sealed batch serials, holds and label marks not tested\n"; + return; + } + const auto& context = device.GetContext(); + passedDeviceProc = context.deviceProc; + passedEndCommandBuffer = reinterpret_cast(context.deviceProc(context.device, "vkEndCommandBuffer")); + passedQueueSubmit = reinterpret_cast(context.deviceProc(context.device, "vkQueueSubmit")); + Context failing = context; + failing.deviceProc = replayFailingDeviceProc; + VkSemaphoreTypeCreateInfoKHR type{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO_KHR}; + type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE_KHR; + type.initialValue = 8; + VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type}; + VkSemaphore holds = VK_NULL_HANDLE; + Require(context.Function("vkCreateSemaphore")(context.device, &info, nullptr, &holds) == VK_SUCCESS, "no timeline semaphore to hold submissions"); + { + Recorder recorder(failing, true, true, context.queueFamily); + recorder.Activate(); + const auto before = recorder.Submissions(); + recordBarrierThrough(failing, recorder.Commands()); + recorder.HoldNextSubmit(holds, 3); + Require(recorder.AfterRecordedWork([] {}), "the first batch took no action behind its work"); + const auto firstMark = Recorder::PendingLabelSince(); + Require(firstMark.has_value(), "an action behind the first batch started no label mark"); + const auto first = recorder.Seal(); + Require(first == before + 1 && recorder.OpenSerial() == first + 1 && recorder.SealedBatches() == 1 && recorder.Submissions() == before && !recorder.Idle(), "sealing the first batch did not give it the next serial, or queued it"); + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + const auto secondStart = std::chrono::steady_clock::now(); + recordBarrierThrough(failing, recorder.Commands()); + recorder.HoldNextSubmit(holds, 5); + Require(recorder.AfterRecordedWork([] {}), "the second batch took no action behind its work"); + const auto secondEnd = std::chrono::steady_clock::now(); + Require(Recorder::PendingLabelSince() == firstMark, "a label in the second batch moved the mark of the older sealed batch"); + const auto second = recorder.Seal(); + Require(second == first + 1 && recorder.SealedBatches() == 2 && recorder.Submissions() == before, "the second sealed batch did not take the serial after the first"); + takeSubmitCaptures(); + Require(recorder.QueueSealed() == first && recorder.Submissions() == first && recorder.SealedBatches() == 1, "the first sealed batch was not queued first"); + const auto secondMark = Recorder::PendingLabelSince(); + Require(secondMark.has_value() && *secondMark >= secondStart && *secondMark <= secondEnd, "after the first batch was queued, the label mark was not the second batch's own"); + Require(recorder.QueueSealed() == second && recorder.Submissions() == second && recorder.SealedBatches() == 0, "the second sealed batch was not queued with its own serial"); + Require(!Recorder::PendingLabelSince().has_value(), "a label mark was left after every sealed batch was queued"); + const auto captures = takeSubmitCaptures(); + Require(captures.size() == 2, "two sealed batches made " + std::to_string(captures.size()) + " submissions"); + Require(captures[0].signal == first && captures[0].wait == holds && captures[0].waitValue == 3, "the first sealed batch did not submit with its own serial and hold"); + Require(captures[1].signal == second && captures[1].wait == holds && captures[1].waitValue == 5, "the second sealed batch did not submit with its own serial and hold"); + recorder.Sync(); + Require(recorder.Idle(), "the recorder was not idle after both sealed batches completed"); + } + { + alignas(64) static std::uint32_t memory[16]; + const std::array value{std::byte{1}, std::byte{0}, std::byte{0}, std::byte{0}}; + Recorder recorder(failing, true, true, context.queueFamily); + recorder.Activate(); + recordBarrierThrough(failing, recorder.Commands()); + recorder.OnComplete([] {}); + const auto sealed = recorder.Seal(); + Require(recorder.SealedBatches() == 1 && recorder.HasCompletions(), "the completions of a sealed batch were not pending"); + recorder.AfterCompletions(reinterpret_cast(memory), value, 9, 0, false); + Require(recorder.QueueSealed() == sealed && recorder.SealedBatches() == 0, "the sealed batch with a completion label was not queued"); + recorder.Sync(); + Require(recorder.Idle() && !recorder.HasCompletions() && memory[0] == 1, "the completion label appended behind a sealed batch did not land"); + } + { + Recorder recorder(failing, true, true, context.queueFamily); + const auto before = recorder.Submissions(); + recordBarrierThrough(failing, recorder.Commands()); + const auto first = recorder.Seal(); + recordBarrierThrough(failing, recorder.Commands()); + const auto second = recorder.Seal(); + Require(second == first + 1, "two sealed batches did not take consecutive serials"); + std::atomic waiting{false}; + bool waiterSaw = false; + bool waiterTimedOut = false; + std::thread waiter([&] { + waiting.store(true); + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(20); + waiterSaw = failedWith( + [&] { + while (!recorder.WaitSerialFor(first, 50'000'000)) { + if (std::chrono::steady_clock::now() > deadline) { + waiterTimedOut = true; + return; + } + } + }, + "injected failure"); + }); + while (!waiting.load()) std::this_thread::yield(); + const auto submitted = countedSubmits.load(); + Recorder::FailNextSubmitsForTest(1u); + const bool failed = failedWith([&] { recorder.QueueSealed(); }, "injected failure"); + Recorder::FailNextSubmitsForTest(0u); + waiter.join(); + Require(failed, "the sealed batch's failure before it was queued did not surface"); + Require(!waiterTimedOut && waiterSaw, "a waiter on a sealed batch that failed before it was queued did not see that failure"); + Require(failedWith([&] { recorder.WaitSerial(first); }, "injected failure"), "a later waiter on the failed sealed batch did not see its failure"); + Require(failedWith([&] { recorder.QueueSealed(); }, "injected failure"), "the batch sealed after the failed one was not refused with that failure"); + Require(countedSubmits.load() == submitted && recorder.SealedBatches() == 0 && recorder.Submissions() == before, "a sealed batch reached the queue after an earlier one failed before it was queued"); + } + { + Recorder recorder(failing, true, true, context.queueFamily); + recordBarrierThrough(failing, recorder.Commands()); + recorder.HoldNextSubmit(holds, 7); + const auto first = recorder.Seal(); + Recorder::FailNextSubmitsForTest(1u); + const bool failed = failedWith([&] { recorder.QueueSealed(); }, "injected failure"); + Recorder::FailNextSubmitsForTest(0u); + Require(failed, "the newest sealed batch's failure before it was queued did not surface"); + recordBarrierThrough(failing, recorder.Commands()); + Require(recorder.Seal() == first, "the serial of the newest sealed batch that failed before it was queued was not returned"); + takeSubmitCaptures(); + Require(recorder.QueueSealed() == first, "the batch that reused a returned serial was not queued"); + const auto captures = takeSubmitCaptures(); + Require(captures.size() == 1 && captures[0].signal == first && captures[0].wait == holds && captures[0].waitValue == 7, "the hold of a sealed batch that failed before it was queued did not pass to the next batch"); + recorder.Sync(); + } + { + Recorder recorder(failing, true, true, context.queueFamily); + const auto before = recorder.Submissions(); + recordBarrierThrough(failing, recorder.Commands()); + recorder.HoldNextSubmit(holds, 7); + const auto first = recorder.Seal(); + recordBarrierThrough(failing, recorder.Commands()); + recorder.HoldNextSubmit(holds, 9); + const auto submitted = countedSubmits.load(); + Recorder::FailNextSubmitsForTest(1u); + const bool failed = failedWith([&] { recorder.QueueSealed(); }, "injected failure"); + Recorder::FailNextSubmitsForTest(0u); + Require(failed, "the newest sealed batch's failure before it was queued did not surface while another batch was open"); + Require(failedWith([&] { recorder.WaitSerialFor(first, 50'000'000); }, "injected failure"), "a waiter on a sealed batch that failed before it was queued, with a batch open, did not see its failure"); + Require(failedWith([&] { recorder.Seal(); }, "injected failure"), "the batch open when an earlier sealed batch failed before it was queued was not refused with that failure"); + Require(countedSubmits.load() == submitted && recorder.SealedBatches() == 0 && recorder.Submissions() == before, "a batch reached the queue after an earlier one failed before it was queued while it was open"); + } + context.Function("vkDestroySemaphore")(context.device, holds, nullptr); + const char* recordInline = std::getenv("APS5_RECORD_INLINE"); + if ((recordInline != nullptr && std::strcmp(recordInline, "0") != 0) || RuntimeSwitches::Set(RuntimeSwitch::DirectBatches)) { + std::cout << "deferred batches off: the recorder's work budget limits not tested\n"; + return; + } + { + Recorder recorder(context, false, true, context.queueFamily, WorkBudget::Limits{0, 16, 64u << 20}); + recordBarrierThrough(context, recorder.Commands()); + recorder.Submit(); + recorder.Sync(); + const auto counts = recorder.StreamCounts(); + Require(counts.deferred == 0 && counts.direct == 1 && counts.refused == 1, "a recorder limited to no encoding batches deferred its batch: " + recorder.StreamReport()); + } + { + Recorder recorder(context, false, true, context.queueFamily, WorkBudget::Limits{1, 16, 64u << 20}); + recordBarrierThrough(context, recorder.Commands()); + recorder.Submit(); + recorder.Sync(); + const auto counts = recorder.StreamCounts(); + Require(counts.deferred == 1 && counts.direct == 0 && counts.refused == 0, "a recorder allowed one encoding batch did not defer its batch: " + recorder.StreamReport()); + } +} + +void deferredBatchTests(const Device& device) { + const char* recordInline = std::getenv("APS5_RECORD_INLINE"); + if (recordInline != nullptr && std::strcmp(recordInline, "0") != 0) { + std::cout << "APS5_RECORD_INLINE: deferred batch tests not run\n"; + return; + } + const auto& context = device.GetContext(); + { + Recorder recorder(context, false, true, context.queueFamily); + const auto commands = recorder.Commands(); + Require(recorder.Deferred() && CommandStream::IsHandle(commands), "a deferred recorder opened its batch on a command buffer"); + recordBarrierThrough(context, commands); + recordBarrierThrough(context, commands); + Require(recorder.StreamOps() >= 2, "barriers recorded into a deferred batch did not reach its stream"); + Require(recorder.GraphicsState().FunctionsFor(commands, context) != nullptr && recorder.GraphicsState().FunctionsFor(commands, context)->CmdSetViewport == StreamedCommands().CmdSetViewport, "a deferred batch's draw state did not take the streamed command table"); + Require(recorder.GraphicsState().FunctionsFor(VK_NULL_HANDLE, context) == nullptr, "the batch's command table was given for another command buffer"); + const auto streamedOps = recorder.StreamOps(); + recorder.GraphicsState().SetViewport(context, VkViewport{0.0f, 0.0f, 16.0f, 16.0f, 0.0f, 1.0f}); + Require(recorder.StreamOps() == streamedOps + 1, "a viewport set through a deferred batch's draw state did not reach its stream"); + recorder.Submit(); + recorder.Sync(); + const auto counts = recorder.StreamCounts(); + Require(counts.deferred == 1 && counts.replayed == 1 && counts.direct == 0 && counts.demoted == 0 && counts.poisoned == 0, "a deferred batch was not replayed once: " + recorder.StreamReport()); + } + { + RuntimeSwitches::Assign(RuntimeSwitch::DirectBatches, true); + Recorder recorder(context, false, true, context.queueFamily); + const auto commands = recorder.Commands(); + RuntimeSwitches::Assign(RuntimeSwitch::DirectBatches, false); + Require(!recorder.Deferred() && !CommandStream::IsHandle(commands), "APS5_DIRECT_BATCHES opened a deferred batch"); + recordBarrierThrough(context, commands); + const auto* direct = recorder.GraphicsState().FunctionsFor(commands, context); + Require(direct != nullptr && direct->CmdSetViewport != StreamedCommands().CmdSetViewport, "a direct batch's draw state did not take the driver's command table"); + Require(direct->CmdSetViewport != nullptr && !IsCommandThunk("vkCmdSetViewport", reinterpret_cast(direct->CmdSetViewport)), "a direct batch's draw state records through the thunk"); + recorder.GraphicsState().SetViewport(context, VkViewport{0.0f, 0.0f, 16.0f, 16.0f, 0.0f, 1.0f}); + recorder.Submit(); + recorder.Sync(); + Require(recorder.StreamCounts().direct == 1 && recorder.StreamCounts().replayed == 0, "a direct batch was replayed"); + static_cast(recorder.Commands()); + Require(recorder.Deferred(), "the batch after APS5_DIRECT_BATCHES was cleared opened direct"); + recorder.Submit(); + recorder.Sync(); + } + { + Recorder recorder(context, false, true, context.queueFamily); + const auto commands = recorder.Commands(); + recordBarrierThrough(context, commands); + bool caught = false; + try { + const auto guard = recorder.UnwindGuard(); + recordBarrierThrough(context, commands); + recordBarrierThrough(context, commands); + throw std::runtime_error("draw failed mid-batch"); + } catch (const std::runtime_error&) { + caught = true; + } + Require(caught, "the unwinding draw did not throw"); + bool refused = false; + try { + recorder.Submit(); + } catch (const std::runtime_error& error) { + refused = std::string(error.what()).find("a draw threw while recording") != std::string::npos; + } + Require(refused, "a deferred batch that a draw unwound through was submitted"); + Require(recorder.StreamCounts().poisoned == 1 && recorder.StreamCounts().replayed == 0, "the poisoned batch was replayed: " + recorder.StreamReport()); + recordBarrierThrough(context, recorder.Commands()); + recorder.Submit(); + recorder.Sync(); + Require(recorder.StreamCounts().replayed == 1, "the batch after a poisoned one was not replayed"); + } + const auto unwindsThrough = [&](Recorder& recorder, VkCommandBuffer commands, const Context& through) { + bool caught = false; + try { + const auto guard = recorder.UnwindGuard(); + recordBarrierThrough(through, commands); + recordBarrierThrough(through, commands); + throw std::runtime_error("draw failed mid-batch"); + } catch (const std::runtime_error&) { + caught = true; + } + Require(caught, "the unwinding draw did not throw"); + try { + recorder.Submit(); + } catch (const std::runtime_error& error) { + return std::string(error.what()).find("a draw threw while recording") != std::string::npos; + } + return false; + }; + std::string unwindFailures; + const auto unwindAttempt = [&](const std::function& run) { + try { + run(); + } catch (const std::exception& error) { + unwindFailures += std::string(error.what()) + "; "; + } + }; + unwindAttempt([&] { + RuntimeSwitches::Assign(RuntimeSwitch::DirectBatches, true); + Recorder recorder(context, false, true, context.queueFamily); + const auto commands = recorder.Commands(); + RuntimeSwitches::Assign(RuntimeSwitch::DirectBatches, false); + Require(!recorder.Deferred() && !CommandStream::IsHandle(commands), "APS5_DIRECT_BATCHES opened a deferred batch"); + recordBarrierThrough(context, commands); + Require(unwindsThrough(recorder, commands, context), "a direct batch that a draw unwound through was submitted"); + Require(recorder.StreamCounts().poisoned == 1 && recorder.StreamCounts().direct == 1, "the poisoned direct batch was not counted: " + recorder.StreamReport()); + recordBarrierThrough(context, recorder.Commands()); + recorder.Submit(); + recorder.Sync(); + Require(recorder.StreamCounts().direct == 1 && recorder.StreamCounts().poisoned == 1 && recorder.StreamCounts().replayed == 1, "the batch after a poisoned direct one was not replayed: " + recorder.StreamReport()); + }); + passedDeviceProc = context.deviceProc; + passedEndCommandBuffer = reinterpret_cast(context.deviceProc(context.device, "vkEndCommandBuffer")); + passedQueueSubmit = reinterpret_cast(context.deviceProc(context.device, "vkQueueSubmit")); + { + Context failing = context; + failing.deviceProc = replayFailingDeviceProc; + Recorder recorder(failing, false, true, context.queueFamily); + const auto commands = recorder.Commands(); + recordBarrierThrough(failing, commands); + Require(recorder.Deferred(), "the batch opened direct"); + const auto streamed = recorder.StreamOps(); + demoteThrough(failing, commands); + Require(!recorder.Deferred(), "a pNext-chained command did not demote the batch"); + recordBarrierThrough(failing, commands); + Require(recorder.StreamOps() == streamed, "a command after the demotion was streamed instead of recorded into the command buffer"); + recorder.Submit(); + recorder.Sync(); + const auto demotions = recorder.Demotions(); + Require(recorder.StreamCounts().demoted == 1 && recorder.StreamCounts().replayed == 0, "the demoted batch was replayed: " + recorder.StreamReport()); + Require(demotions.size() == 1 && demotions[0].first == "vkCmdPipelineBarrier/" + std::to_string(VK_STRUCTURE_TYPE_MEMORY_BARRIER) && demotions[0].second == 1, "the demotion was not counted by command: " + recorder.StreamReport()); + } + unwindAttempt([&] { + Context failing = context; + failing.deviceProc = replayFailingDeviceProc; + Recorder recorder(failing, false, true, context.queueFamily); + const auto commands = recorder.Commands(); + recordBarrierThrough(failing, commands); + demoteThrough(failing, commands); + Require(!recorder.Deferred(), "a pNext-chained command did not demote the batch"); + Require(unwindsThrough(recorder, commands, failing), "a demoted batch that a draw unwound through was submitted"); + Require(recorder.StreamCounts().poisoned == 1 && recorder.StreamCounts().demoted == 1 && recorder.StreamCounts().replayed == 0, "the poisoned demoted batch was not counted: " + recorder.StreamReport()); + recordBarrierThrough(failing, recorder.Commands()); + recorder.Submit(); + recorder.Sync(); + Require(recorder.StreamCounts().replayed == 1 && recorder.StreamCounts().poisoned == 1, "the batch after a poisoned demoted one was not replayed: " + recorder.StreamReport()); + }); + Require(unwindFailures.empty(), "a batch a draw unwound through was not refused: " + unwindFailures); + { + Context failing = context; + passedDeviceProc = context.deviceProc; + passedEndCommandBuffer = reinterpret_cast(context.deviceProc(context.device, "vkEndCommandBuffer")); + passedQueueSubmit = reinterpret_cast(context.deviceProc(context.device, "vkQueueSubmit")); + failing.deviceProc = replayFailingDeviceProc; + Recorder recorder(failing, false, true, context.queueFamily); + bool ran = false; + const auto counted = countedSubmits.load(); + recordBarrierThrough(failing, recorder.Commands()); + recorder.Submit(); + recorder.Sync(); + const auto submitted = countedSubmits.load(); + Require(submitted == counted + 1, "the recorder's submit did not reach the counting submit wrapper"); + recordBarrierThrough(failing, recorder.Commands()); + static_cast(recorder.AfterRecordedWork([&] { ran = true; })); + refusedSubmits.store(true); + failingEnds.store(1); + bool failed = false; + try { + recorder.Submit(); + } catch (const std::exception&) { + failed = true; + } + Require(failed && failingEnds.load() == 0, "a batch whose replay failed was not refused at submit"); + Require(countedSubmits.load() == submitted, "a batch whose replay failed reached vkQueueSubmit"); + Require(recorder.StreamCounts().replayFailed == 1, "the failed replay was not counted: " + recorder.StreamReport()); + recorder.Sync(); + Require(!ran, "a completion of a batch whose replay failed ran"); + recordBarrierThrough(failing, recorder.Commands()); + bool cancelled = false; + try { + recorder.Submit(); + } catch (const std::exception&) { + cancelled = true; + } + refusedSubmits.store(false); + Require(cancelled && countedSubmits.load() == submitted, "a batch after a failed replay was submitted"); + } + { + Context failing = context; + failing.deviceProc = replayFailingDeviceProc; + std::uint64_t submitted = 0; + { + Recorder recorder(failing, false, true, context.queueFamily); + recordBarrierThrough(failing, recorder.Commands()); + recorder.Submit(); + submitted = countedSubmits.load(); + recordBarrierThrough(failing, recorder.Commands()); + failingEnds.store(1); + } + Require(failingEnds.load() == 0, "the batch left open at teardown was not replayed"); + Require(countedSubmits.load() == submitted, "a batch whose replay failed at teardown reached vkQueueSubmit"); + } + { + Context failing = context; + failing.deviceProc = replayFailingDeviceProc; + Recorder recorder(failing, false, true, context.queueFamily); + recordBarrierThrough(failing, recorder.Commands()); + lostSubmits.store(1); + bool lost = false; + try { + recorder.Submit(); + } catch (const std::exception&) { + lost = true; + } + Require(lost && lostSubmits.load() == 0, "the injected device loss did not surface at submit"); + const auto commands = recorder.Commands(); + demoteThrough(failing, commands); + Require(!recorder.Deferred(), "a pNext-chained command did not demote the batch"); + const auto submitted = countedSubmits.load(); + bool refused = false; + try { + recorder.Submit(); + } catch (const std::exception&) { + refused = true; + } + Require(refused && countedSubmits.load() == submitted, "a direct batch reached vkQueueSubmit after the device was lost"); + } + { + Context failing = context; + failing.deviceProc = replayFailingDeviceProc; + RuntimeSwitches::Assign(RuntimeSwitch::DirectBatches, true); + Recorder recorder(failing, false, true, context.queueFamily); + recordBarrierThrough(failing, recorder.Commands()); + RuntimeSwitches::Assign(RuntimeSwitch::DirectBatches, false); + Require(!recorder.Deferred(), "APS5_DIRECT_BATCHES opened a deferred batch"); + lostSubmits.store(1); + bool lost = false; + try { + recorder.Submit(); + } catch (const std::exception&) { + lost = true; + } + Require(lost && lostSubmits.load() == 0, "the injected device loss of a direct batch did not surface at submit"); + recordBarrierThrough(failing, recorder.Commands()); + const auto submitted = countedSubmits.load(); + bool refused = false; + try { + recorder.Submit(); + } catch (const std::exception&) { + refused = true; + } + Require(refused && countedSubmits.load() == submitted, "a batch reached vkQueueSubmit after a direct batch lost the device"); + } + { + Context failing = context; + failing.deviceProc = replayFailingDeviceProc; + RuntimeSwitches::Assign(RuntimeSwitch::DirectBatches, true); + Recorder recorder(failing, true, true, context.queueFamily); + recordBarrierThrough(failing, recorder.Commands()); + RuntimeSwitches::Assign(RuntimeSwitch::DirectBatches, false); + Require(!recorder.Deferred(), "APS5_DIRECT_BATCHES opened a deferred batch"); + const auto serial = recorder.OpenBatchSerial(); + auto waited = failedSerialWait(recorder, serial); + refusedSubmits.store(true); + bool failed = false; + try { + recorder.Submit(); + } catch (const std::exception&) { + failed = true; + } + refusedSubmits.store(false); + Require(failed, "the refused submission of a direct batch did not surface at submit"); + Require(waited.wait_for(std::chrono::milliseconds(100)) != std::future_status::ready, "a wait on the serial of a refused submission ended before a batch completed that serial"); + recordBarrierThrough(failing, recorder.Commands()); + Require(recorder.OpenBatchSerial() == serial, "the batch after a refused submission did not take back its serial"); + const auto submitted = countedSubmits.load(); + recorder.Submit(); + Require(countedSubmits.load() == submitted + 1, "the batch after a refused submission did not reach vkQueueSubmit"); + recorder.Sync(); + if (waited.wait_for(std::chrono::seconds(10)) != std::future_status::ready) { + std::fprintf(stderr, "a wait on the serial of a refused submission did not end after the next batch completed it\n"); + std::fflush(stderr); + std::_Exit(1); + } + Require(!waited.get(), "a wait on the serial of a refused submission failed after the next batch completed it"); + } + { + Context failing = context; + failing.deviceProc = replayFailingDeviceProc; + RuntimeSwitches::Assign(RuntimeSwitch::DirectBatches, true); + Recorder recorder(failing, true, true, context.queueFamily); + recordBarrierThrough(failing, recorder.Commands()); + const auto first = recorder.Seal(); + recordBarrierThrough(failing, recorder.Commands()); + const auto second = recorder.Seal(); + RuntimeSwitches::Assign(RuntimeSwitch::DirectBatches, false); + Require(recorder.SealedBatches() == 2 && second == first + 1, "two direct batches were not sealed in order"); + auto waited = failedSerialWait(recorder, first); + refusedSubmits.store(true); + bool failed = false; + try { + recorder.QueueSealed(); + } catch (const std::exception&) { + failed = true; + } + refusedSubmits.store(false); + Require(failed, "the refused submission of a sealed batch with a newer one behind it did not surface"); + if (waited.wait_for(std::chrono::seconds(10)) != std::future_status::ready) { + std::fprintf(stderr, "a wait on a refused batch with a newer sealed batch behind it did not end\n"); + std::fflush(stderr); + std::_Exit(1); + } + Require(waited.get(), "a wait on a refused batch with a newer sealed batch behind it returned as if the batch completed"); + const auto submitted = countedSubmits.load(); + bool refused = false; + try { + recorder.QueueSealed(); + } catch (const std::exception&) { + refused = true; + } + Require(refused && countedSubmits.load() == submitted, "a sealed batch reached vkQueueSubmit after the batch before it was refused"); + } + { + Context failing = context; + failing.deviceProc = replayFailingDeviceProc; + Recorder recorder(failing, false, true, context.queueFamily); + recordBarrierThrough(failing, recorder.Commands()); + const std::uint32_t labelValue = 7; + recorder.NoteLabel(0x60040, std::as_bytes(std::span(&labelValue, 1)), 300, 0); + recorder.Submit(); + recordBarrierThrough(failing, recorder.Commands()); + recorder.Submit(); + recordBarrierThrough(failing, recorder.Commands()); + Require(recorder.InFlightBatches() == 2, "two submitted batches were not in flight"); + Require(recorder.PendingLabels() == 1, "the first batch's label did not enter the table"); + refusedSubmits.store(true); + failingFences.store(1); + std::string reason; + try { + recorder.Sync(); + } catch (const std::exception& error) { + reason = error.what(); + } + refusedSubmits.store(false); + Require(failingFences.load() == 0, "Sync did not wait on the first batch's fence"); + Require(recorder.InFlightBatches() == 1, "Sync left " + std::to_string(recorder.InFlightBatches()) + " batches in flight after a fence wait failed, not the one it did not reach"); + Require(recorder.PendingLabels() == 0, "a batch retired by a failed fence wait left its label in the table"); + Require(reason.find("vkQueueSubmit") != std::string::npos, "Sync did not report the submission failure first: " + reason); + recorder.Sync(); + Require(recorder.InFlightBatches() == 0, "a sync after a failed fence wait left " + std::to_string(recorder.InFlightBatches()) + " batches in flight"); + } + { + Context failing = context; + failing.deviceProc = replayFailingDeviceProc; + const auto live = liveCommandBuffers.load(); + bool completed = false; + { + Recorder recorder(failing, false, true, context.queueFamily); + recordBarrierThrough(failing, recorder.Commands()); + recorder.Submit(); + recordBarrierThrough(failing, recorder.Commands()); + recorder.OnComplete([&completed] { completed = true; }); + recorder.Submit(); + Require(recorder.InFlightBatches() == 2, "two submitted batches were not in flight"); + failingFences.store(1); + } + Require(failingFences.load() == 0, "teardown did not wait on the first batch's fence"); + Require(completed, "a recorder whose teardown wait failed dropped the batch it did not reach without finishing it"); + Require(liveCommandBuffers.load() == live, "a recorder whose teardown wait failed leaked " + std::to_string(liveCommandBuffers.load() - live) + " command buffers"); + } + { + Context failing = context; + failing.deviceProc = replayFailingDeviceProc; + const auto live = liveCommandBuffers.load(); + { + Recorder recorder(failing, false, true, context.queueFamily); + const auto commands = recorder.Commands(); + recordBarrierThrough(failing, commands); + Require(recorder.Deferred(), "the batch opened direct"); + failingBarriers.store(1); + bool demotionFailed = false; + try { + demoteThrough(failing, commands); + } catch (const std::runtime_error&) { + demotionFailed = true; + } + Require(demotionFailed && failingBarriers.load() == 0, "a replay failure while demoting the stream did not surface"); + const auto submitted = countedSubmits.load(); + bool refused = false; + try { + recorder.Submit(); + } catch (const std::exception&) { + refused = true; + } + Require(refused && countedSubmits.load() == submitted, "a batch whose demotion failed was submitted"); + recordBarrierThrough(failing, recorder.Commands()); + recorder.Submit(); + recorder.Sync(); + Require(countedSubmits.load() == submitted + 1, "the batch after a failed demotion was not submitted"); + } + Require(liveCommandBuffers.load() == live, "a command buffer allocated for a failed demotion was not freed: " + std::to_string(liveCommandBuffers.load() - live) + " still allocated"); + } + if (!device.TimelineSemaphores()) { + std::cout << "skipped, no timeline semaphores: held teardown and serial waits under a failed replay not tested\n"; + } else { + Context failing = context; + failing.deviceProc = replayFailingDeviceProc; + VkSemaphoreTypeCreateInfoKHR type{VK_STRUCTURE_TYPE_SEMAPHORE_TYPE_CREATE_INFO_KHR}; + type.semaphoreType = VK_SEMAPHORE_TYPE_TIMELINE_KHR; + VkSemaphoreCreateInfo info{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, &type}; + VkSemaphore gate = VK_NULL_HANDLE; + Require(context.Function("vkCreateSemaphore")(context.device, &info, nullptr, &gate) == VK_SUCCESS, "no timeline semaphore to hold the GPU"); + std::uint64_t submitted = 0; + std::thread release; + { + Recorder recorder(failing, true, true, context.queueFamily); + Require(recorder.HasTimeline(), "the recorder made no timeline semaphore on a device that has them"); + struct OpenGate { + const Context& context; + VkSemaphore gate; + const std::thread& release; + ~OpenGate() { + if (release.joinable()) return; + VkSemaphoreSignalInfoKHR signal{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO_KHR}; + signal.semaphore = gate; + signal.value = 1; + context.Function("vkSignalSemaphoreKHR")(context.device, &signal); + } + } openGate{context, gate, release}; + recordBarrierThrough(failing, recorder.Commands()); + recorder.HoldNextSubmit(gate, 1); + recorder.Submit(); + submitted = countedSubmits.load(); + Require(recorder.UnsignaledBatches() == 1, "the held batch was not left running on the GPU"); + recordBarrierThrough(failing, recorder.Commands()); + failingEnds.store(1); + release = std::thread([&] { + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + VkSemaphoreSignalInfoKHR signal{VK_STRUCTURE_TYPE_SEMAPHORE_SIGNAL_INFO_KHR}; + signal.semaphore = gate; + signal.value = 1; + Require(context.Function("vkSignalSemaphoreKHR")(context.device, &signal) == VK_SUCCESS, "the gate was not signaled"); + }); + } + release.join(); + Require(failingEnds.load() == 0 && countedSubmits.load() == submitted, "the batch whose replay failed at teardown was submitted, or was never replayed"); + context.Function("vkDestroySemaphore")(context.device, gate, nullptr); + Recorder recorder(failing, true, true, context.queueFamily); + recordBarrierThrough(failing, recorder.Commands()); + const auto serial = recorder.OpenBatchSerial(); + auto waited = failedSerialWait(recorder, serial); + failingEnds.store(1); + bool failed = false; + try { + recorder.Submit(); + } catch (const std::exception&) { + failed = true; + } + Require(failed && failingEnds.load() == 0, "the replay of the waited batch did not fail at submit"); + if (waited.wait_for(std::chrono::seconds(10)) != std::future_status::ready) { + std::fprintf(stderr, "a wait on the serial of a batch whose replay failed did not end\n"); + std::fflush(stderr); + std::_Exit(1); + } + Require(waited.get(), "a wait on the serial of a batch whose replay failed returned as if the batch completed"); + } + std::cout << "deferred batch tests passed\n"; +} + int gpuTimingCompletionTests(const Device& device, bool incomplete) { const auto& context = device.GetContext(); if (!device.Timestamps()) { @@ -7196,7 +8077,88 @@ void drawInputMirrorTests(const Device& device) { std::memset(reinterpret_cast(first), 0x5a, 16); CollectWrites(first, 16); Require(reuse(first) == nullptr && use(0, 0), "a mirrored snapshot outlived a CPU store or kept its mirror's bytes"); + const auto current = CollectWrites(first, held); + const auto currentHost = snapshot(first); + cache.KeepDrawSnapshot(first, held, current, registry, currentHost, Use::Vertex); + Recorder::FailNextSubmitsForTest(1); + const auto lostMirror = reuse(first); + Require(lostMirror != nullptr && lostMirror != currentHost && use(2 * held, held), "a mirror was not made for the batch that will be discarded"); + bool refused = false; + try { + cache.Submit(); + } catch (const std::runtime_error&) { + refused = true; + } + Recorder::FailNextSubmitsForTest(0); + Require(refused, "the batch holding a mirror's upload was not refused"); + Require(use(held, 0), "a discarded batch left its draw input mirror cached"); + const auto remade = reuse(first); + Require(remade != nullptr && remade != lostMirror && !remade->Mapped() && use(2 * held, held), "a mirror was not made again after its batch was discarded"); + Require(drawInputHolds(context, cache, remade, first, held), "a draw input mirror made after a discarded batch does not hold the bytes of its snapshot"); cache.Sync(); + const auto failedRegistration = [&](Recorder& batch, const Context& through, bool deferred, bool demoted, const char* mode) -> std::weak_ptr { + const auto commands = batch.Commands(); + if (demoted) demoteThrough(through, commands); + Require(batch.Deferred() == deferred, std::string("the ") + mode + " batch did not open in its mode"); + const auto reusing = [&] { return batch.ReusableDrawSnapshot(first, held, Use::Vertex, nullptr, 0, nullptr, 0, nullptr, true); }; + const auto counted = [&](std::size_t kept, std::size_t mirrored) { return batch.DrawInputBytes() == std::pair{kept, mirrored}; }; + auto host = snapshot(first); + batch.KeepDrawSnapshot(first, held, CollectWrites(first, held), registry, host, Use::Vertex); + const std::weak_ptr hostWatch = host; + host.reset(); + const auto keptBefore = batch.OpenKeptCount(); + Recorder::FailNextDiscardRegistrationsForTest(1); + bool refused = false; + try { + reusing(); + } catch (const std::bad_alloc&) { + refused = true; + } + Recorder::FailNextDiscardRegistrationsForTest(0); + Require(refused, std::string("registering the discard of a mirror did not fail in a ") + mode + " batch"); + Require(counted(held, 0), std::string("a mirror whose discard registration failed was counted in a ") + mode + " batch"); + Require(batch.OpenKeptCount() == keptBefore + 2, std::string("a ") + mode + " batch did not keep both operands of the mirror copy it recorded"); + std::memset(reinterpret_cast(first), 0x5a, 16); + CollectWrites(first, 16); + Require(reusing() == nullptr && counted(0, 0), std::string("a snapshot whose guest memory changed outlived its eviction in a ") + mode + " batch"); + Require(!hostWatch.expired(), std::string("the host snapshot a ") + mode + " batch copies from was released with the cache entry"); + batch.Submit(); + batch.Sync(); + const auto next = snapshot(first); + batch.KeepDrawSnapshot(first, held, CollectWrites(first, held), registry, next, Use::Vertex); + const auto retried = reusing(); + Require(retried != nullptr && retried != next && !retried->Mapped() && counted(2 * held, held), std::string("a mirror was not made again after its discard registration failed in a ") + mode + " batch"); + Require(drawInputHolds(through, batch, retried, first, held), std::string("the mirror made after a failed discard registration does not hold the bytes of its snapshot in a ") + mode + " batch"); + batch.Sync(); + return hostWatch; + }; + std::string mirrorFailures; + const auto inMode = [&](const char* mode, const Context& through, bool deferred, bool demoted) { + std::weak_ptr hostWatch; + try { + { + Recorder batch(through, false, deferred || demoted, context.queueFamily); + hostWatch = failedRegistration(batch, through, deferred, demoted, mode); + } + Require(hostWatch.expired(), std::string("the host snapshot of a ") + mode + " batch outlived its recorder"); + } catch (const std::exception& error) { + Recorder::FailNextDiscardRegistrationsForTest(0); + mirrorFailures += std::string(error.what()) + "; "; + } + }; + const char* recordInline = std::getenv("APS5_RECORD_INLINE"); + const bool inlineRecording = recordInline != nullptr && std::strcmp(recordInline, "0") != 0; + if (!inlineRecording) inMode("deferred", context, true, false); + inMode("direct", context, false, false); + if (!inlineRecording) { + passedDeviceProc = context.deviceProc; + passedEndCommandBuffer = reinterpret_cast(context.deviceProc(context.device, "vkEndCommandBuffer")); + passedQueueSubmit = reinterpret_cast(context.deviceProc(context.device, "vkQueueSubmit")); + auto failing = context; + failing.deviceProc = replayFailingDeviceProc; + inMode("demoted", failing, false, true); + } + Require(mirrorFailures.empty(), "a failed discard registration left a mirror copy without its operands: " + mirrorFailures); auto tight = context; tight.memoryProperties2 = tightMemoryBudget; Recorder narrow(tight); @@ -14292,7 +15254,7 @@ class CoverPass { CoverPass(const CoverPass&) = delete; CoverPass& operator=(const CoverPass&) = delete; - bool Draw(Recorder& recorder) const { + bool Draw(Recorder& recorder, std::function afterPass = {}) const { const auto start = recorder.StartDrawPass(PassKey, false, false, PassAccess{}); const bool continued = start.continued; const auto commands = start.commands; @@ -14303,7 +15265,7 @@ class CoverPass { recorder.GraphicsState().BindPipeline(context, pipeline, 0); recorder.NoteSampledDraw(commands); context.Function("vkCmdDraw")(commands, 3, 1, 0, 0); - recorder.LeaveRenderPassOpen(PassKey, Recorder::NoTiming, false, PassAccess{}); + recorder.LeaveRenderPassOpen(PassKey, Recorder::NoTiming, false, PassAccess{}, std::move(afterPass)); return continued; } @@ -14323,9 +15285,9 @@ class CoverPass { } static constexpr std::uint64_t Samples = 64; + static constexpr std::uint64_t PassKey = 0xc0de; private: - static constexpr std::uint64_t PassKey = 0xc0de; void begin(VkCommandBuffer commands, bool secondaryContents = false) const { if (context.graphicsPipelineLibrary) { if (!transitioned) { @@ -14437,6 +15399,50 @@ void inPassSampleDumpTests(Recorder& recorder, const Context& context, const Cov if (context.occlusionQueryPrecise) Require(folded == base + passes * CoverPass::Samples, "segments folded at Submit without a dump counted the wrong samples"); } +void discardedSampleTests(Recorder& recorder, const Context& context, const CoverPass& cover, std::uint64_t* words, std::uint64_t address, VkDeviceAddress target) { + const auto passes = [&](std::size_t count) { + for (std::size_t i = 0; i < count; ++i) { + Require(!cover.Draw(recorder), "a draw after other work continued a pass"); + recorder.Commands(); + } + }; + const auto failSubmit = [&] { + Recorder::FailNextSubmitsForTest(1u); + bool discarded = false; + try { + recorder.Submit(); + } catch (const std::exception& error) { + discarded = std::string(error.what()).find("injected failure") != std::string::npos; + } + Recorder::FailNextSubmitsForTest(0u); + Require(discarded, "the batch with closed occlusion segments was not discarded"); + }; + recorder.Sync(); + const auto base = recorder.SamplesTotal(); + passes(2); + failSubmit(); + Require(recorder.SamplesTotal() == base, "the segments of a discarded batch were read"); + passes(3); + recorder.Submit(); + passes(70); + failSubmit(); + std::fill(words, words + 64, 0); + Require(recorder.DumpSamples(target, address), "a dump after a discarded fold was not made on the GPU"); + recorder.Sync(); + const auto dumped = words[0] & ~SampleReady; + Require((words[0] & SampleReady) != 0 && dumped > base, "a discarded batch that folded the segments of a submitted one lost their samples"); + const auto kept = dumped - base; + Require(recorder.SamplesTotal() == dumped, "the host total and the dump disagree after a discarded fold"); + if (context.occlusionQueryPrecise) Require(kept == 3 * CoverPass::Samples, "a discarded batch's segments were counted beside the submitted ones it folded"); + std::fill(words, words + 64, 0); + passes(1); + Require(recorder.DumpSamples(target, address), "a dump after a discarded batch was not made on the GPU"); + recorder.Sync(); + const auto total = recorder.SamplesTotal(); + Require((words[0] & SampleReady) != 0 && (words[0] & ~SampleReady) == total && total > base + kept, "a dump after a discarded batch counted the wrong draws"); + if (context.occlusionQueryPrecise) Require(total == base + 4 * CoverPass::Samples, "a dump after a discarded batch counted the wrong samples"); +} + bool pendingKeyStoreTests(const Device& device, Recorder& recorder) { const auto& context = device.GetContext(); if (context.hostImportAlignment == 0) { @@ -14703,8 +15709,10 @@ void sampleDumpTests(const Device& device, Recorder& recorder) { } CoverPass cover(context); inPassSampleDumpTests(recorder, context, cover, words, address, target); + discardedSampleTests(recorder, context, cover, words, address, target); } + std::uint32_t uncountedGraphicsBinds = 0; PFN_vkCmdBindPipeline uncountedRealBind = nullptr; @@ -14715,7 +15723,7 @@ VKAPI_ATTR void VKAPI_CALL countingBind(VkCommandBuffer commands, VkPipelineBind void firstSampleCopyTrackingTest(const Device& device) { auto context = device.GetContext(); - uncountedRealBind = reinterpret_cast(context.deviceProc(context.device, "vkCmdBindPipeline")); + uncountedRealBind = reinterpret_cast(AgcDriver::Graphics::CommandThunk("vkCmdBindPipeline", context.deviceProc(context.device, "vkCmdBindPipeline"), context.device)); DeviceFunctions hooks; hooks.cmdBindPipeline = countingBind; context.functions = &hooks; @@ -14882,9 +15890,52 @@ void discardedSampleTests(const Device& device) { failedSubmit("a batch that folded earlier samples at capacity"); Require(Recorder::SampleDumpCounts().capacityFolds == capacityFolds + 1, "a discarded batch at the fold capacity did not fold"); restoredTotal("a discarded batch that folded earlier samples at capacity", beforeCapacity, shortOfCapacity); + if (recorder.QueuesSampleDumps()) { + recorder.Sync(); + const auto beforeSealed = recorder.SamplesTotal(); + const auto foldsBeforeSealed = Recorder::SampleDumpCounts().capacityFolds; + std::size_t sealed = 0; + while (Recorder::SampleDumpCounts().capacityFolds == foldsBeforeSealed && sealed < 4096) { + cover.Draw(recorder); + recorder.EndPassSamples(); + recorder.Seal(); + ++sealed; + } + Require(Recorder::SampleDumpCounts().capacityFolds == foldsBeforeSealed + 1 && recorder.SealedBatches() == sealed, "sealed batches never folded their occlusion segments at capacity"); + Recorder::FailNextSubmitsForTest(1); + while (recorder.SealedBatches() != 0) { + try { + recorder.QueueSealed(); + } catch (const std::exception&) { + } + } + Recorder::FailNextSubmitsForTest(0); + std::uint64_t afterSealed = 0; + completesWithin(std::chrono::seconds(20), "the sample total after refused sealed batches", [&] { afterSealed = recorder.SamplesTotal(); }); + Require(afterSealed == beforeSealed, "the segments of refused sealed batches were counted after the last of them was discarded (" + std::to_string(afterSealed - beforeSealed) + " samples)"); + } std::cout << "Recorder discarded sample tests passed\n"; } +void failedPassEndTests(const Device& device) { + auto context = device.GetContext(); + Recorder recorder(context); + CoverPass cover(context); + cover.Draw(recorder, [](CommandState&) { throw std::runtime_error("injected after-pass failure"); }); + bool failed = false; + try { + recorder.Submit(); + } catch (const std::runtime_error& error) { + failed = std::string(error.what()) == "injected after-pass failure"; + } + Require(failed, "a render pass whose after-pass work threw did not fail the submit"); + Require(!recorder.RenderPassOpen(), "a render pass whose after-pass work threw was left open after it was ended"); + cover.Draw(recorder); + recorder.Submit(); + recorder.Sync(); + std::cout << "Recorder failed pass end tests passed\n"; +} + void discardActionTests(const Device& device) { auto context = device.GetContext(); Recorder recorder(context); @@ -15148,6 +16199,30 @@ void graphicsStateTests(const Device& device) { std::cout << "graphics state through the recorder passed (" << (suppressing ? "suppressing" : "unsuppressed") << ")\n"; } +bool streamedSegmentTests(const Device& device) { + const auto& context = device.GetContext(); + Recorder recorder(context, false, true, context.queueFamily); + recorder.CountSamples(); + const auto base = recorder.SamplesTotal(); + const auto before = Recorder::SampleDumpCounts().segments; + constexpr std::uint32_t segments = 300; + for (std::uint32_t i = 0; i < segments; ++i) { + recorder.PrepareSampleSlot(); + const auto commands = recorder.Commands(); + if (!recorder.Deferred()) return false; + const auto ops = recorder.StreamOps(); + recordBarrierThrough(context, commands); + recorder.NoteSampledDraw(commands); + recorder.EndPassSamples(); + Require(recorder.StreamOps() == ops + 3, "an occlusion segment's queries were not streamed in order with the batch's commands"); + } + recorder.Submit(); + recorder.Sync(); + Require(Recorder::SampleDumpCounts().segments - before == segments, "the streamed occlusion segments were not all closed"); + Require(recorder.SamplesTotal() == base, "occlusion segments without draws counted samples"); + return true; +} + void passContentsTests(const Device& device) { auto context = device.GetContext(); Recorder recorder(context); @@ -18883,12 +19958,10 @@ bool clearHandOverTests(const Device& device, Recorder& recorder, bool watched) constexpr std::size_t bytes = surfaceA + 65536; static_assert(surfaceB <= surfaceA && keyCount <= bytes - surfaceA, "B lies over the first units of A, and B's DCC keys follow A inside the block"); const auto decided = PrepareImportWatch(base); -#ifndef _WIN32 if (watched && decided == ImportWatch::Unwatch) { std::cout << "host imports are compared on this device: " << what << " not tested\n"; return false; } -#endif void* block = nullptr; if (watched) { block = AllocateWatched(bytes, 65536); @@ -20353,7 +21426,8 @@ int main(int argc, char** argv) { } device.UsePushDescriptors(); } - Recorder recorder(device.GetContext()); + const bool deferred = argc == 1 && device.UseFunctionTable() != nullptr; + Recorder recorder(device.GetContext(), false, deferred, device.GetContext().queueFamily); recorder.Activate(); if (argc == 2 && std::string_view(argv[1]) == "--command-reuse-only") { if (device.GetContext().hostImportAlignment == 0) return 77; @@ -20725,6 +21799,18 @@ int main(int argc, char** argv) { std::cout << "Occlusion counter dump tests passed\n"; return 0; } + if (argc == 2 && std::string_view(argv[1]) == "--streamed-segments-only") { + if (!device.GetContext().bufferDeviceAddress) { + std::cout << "skipped, the device lacks buffer device addresses\n"; + return 77; + } + if (!streamedSegmentTests(device)) { + std::cout << "skipped, batches are recorded direct\n"; + return 77; + } + std::cout << "Streamed occlusion segment tests passed\n"; + return 0; + } if (argc == 2 && std::string_view(argv[1]) == "--graphics-state-only") { graphicsStateTests(device); return 0; @@ -21002,6 +22088,7 @@ int main(int argc, char** argv) { shadowedKeyStoreTests(device, recorder); sampleDumpTests(device, recorder); discardActionTests(device); + failedPassEndTests(device); discardedSampleTests(device); copiedDirectOrderingTests(device, recorder); copiedWriteBackTests(device, recorder); @@ -21010,7 +22097,18 @@ int main(int argc, char** argv) { drawSnapshotPatchTests(device); drawSnapshotEpochTests(device); gpu.lock(); + deferredBatchTests(device); + sealedBatchTests(device); + finishAfterDeviceLossTests(device); recorder.Activate(); + const auto replayedBefore = recorder.StreamCounts().replayed; + const bool drew = vertexTargetRangeTests(device, recorder, false); + const char* recordInline = std::getenv("APS5_RECORD_INLINE"); + const bool direct = recordInline != nullptr && std::strcmp(recordInline, "0") != 0; + const auto counts = recorder.StreamCounts(); + Require(direct ? counts.deferred == 0 : counts.deferred != 0, "the recorder suite's recorder did not follow APS5_RECORD_INLINE: " + recorder.StreamReport()); + Require(direct || !drew || counts.replayed > replayedBefore, "the vertex-range workload drew but replayed no deferred batch"); + std::cout << recorder.StreamReport(); std::cout << "Recorder read tracking and label tests passed\n"; return 0; } diff --git a/core/libs/prx/libSceAgcDriver/tests/RecorderKeptBytes.cpp b/core/libs/prx/libSceAgcDriver/tests/RecorderKeptBytes.cpp index e7f4d33e1397..8c32d0413f9e 100644 --- a/core/libs/prx/libSceAgcDriver/tests/RecorderKeptBytes.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/RecorderKeptBytes.cpp @@ -1,6 +1,7 @@ #include #include #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" +#include "FakeHandles.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include #include @@ -50,7 +51,7 @@ std::vector commandOrder; std::vector> barrierMasks; VKAPI_ATTR VkResult VKAPI_CALL mockAllocateCommandBuffers(VkDevice, const VkCommandBufferAllocateInfo*, VkCommandBuffer* commands) { - *commands = reinterpret_cast(mock.next++); + *commands = FakeCommandBuffer(mock.next++); ++mock.allocatedCommands; return VK_SUCCESS; } diff --git a/core/libs/prx/libSceAgcDriver/tests/SealedBatch.cpp b/core/libs/prx/libSceAgcDriver/tests/SealedBatch.cpp new file mode 100644 index 000000000000..4dbbc9818279 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/SealedBatch.cpp @@ -0,0 +1,790 @@ +#include "AllocationFailure.hpp" +#include "prx/libSceAgcDriver/Graphics/include/CommandList.hpp" +#include "prx/libSceAgcDriver/Graphics/include/SealedBatch.hpp" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using AgcDriver::Graphics::BatchCancelled; +using AgcDriver::Graphics::CommandBufferPool; +using AgcDriver::Graphics::CommandStream; +using AgcDriver::Graphics::CreateReplayPool; +using AgcDriver::Graphics::ReplayEntryPoints; +using AgcDriver::Graphics::CommandFunctions; +using AgcDriver::Graphics::FailureLatch; +using AgcDriver::Graphics::InlineExecutor; +using AgcDriver::Graphics::RecordingShutDown; +using AgcDriver::Graphics::SealedBatch; +using AgcDriver::Graphics::SingleExecutor; +using AgcDriver::Graphics::WorkBudget; +using Outcome = SealedBatch::Outcome; + +void Require(bool condition, const std::string& message) { + if (condition) return; + std::fprintf(stderr, "sealed batch: %s\n", message.c_str()); + std::fflush(stderr); + throw std::runtime_error(message); +} + +template +bool Throws(Call&& call) { + try { + call(); + } catch (const Error&) { + return true; + } + return false; +} + +const CommandFunctions& Real() { + static const CommandFunctions functions{}; + return functions; +} + +struct Seen { + std::mutex mutex; + std::vector values; + std::vector targets; + std::atomic replayThreadCalls{0}; +}; + +Seen& seen() { + static Seen value; + return value; +} + +struct Value { + std::uint32_t value; + std::uint32_t count; +}; + +void runValue(const std::byte* payload, VkCommandBuffer commands, const CommandFunctions&) { + Value header; + std::memcpy(&header, payload, sizeof(header)); + const auto* array = payload + CommandStream::Aligned(sizeof(Value)); + std::lock_guard lock(seen().mutex); + seen().values.push_back(header.value); + for (std::uint32_t i = 0; i < header.count; ++i) { + std::uint32_t element; + std::memcpy(&element, array + i * sizeof(std::uint32_t), sizeof(element)); + seen().values.push_back(element); + } + seen().targets.push_back(commands); + if (AgcDriver::Graphics::OnReplayThread()) seen().replayThreadCalls.fetch_add(1); +} + +void append(CommandStream& stream, std::uint32_t value, std::span array = {}) { + stream.Emplace(&runValue, Value{value, static_cast(array.size())}, array); +} + +std::vector takeSeen() { + std::lock_guard lock(seen().mutex); + auto values = std::move(seen().values); + seen().values.clear(); + seen().targets.clear(); + return values; +} + +VkCommandBuffer fakeBuffer(std::uintptr_t id) { + return reinterpret_cast(id << 4); +} + +class FakePool final : public CommandBufferPool { +public: + struct Shared { + std::mutex mutex; + std::vector users; + std::vector recycled; + std::atomic begun{0}; + std::atomic hold{false}; + std::atomic holding{false}; + std::atomic failEnd{false}; + }; + explicit FakePool(std::shared_ptr shared) : shared(std::move(shared)) {} + VkCommandBuffer Begin() override { + note(); + if (shared->hold.load()) { + shared->holding.store(true); + while (shared->hold.load()) std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + return fakeBuffer(static_cast(++shared->begun)); + } + void End(VkCommandBuffer) override { + note(); + if (shared->failEnd.load()) throw std::runtime_error("vkEndCommandBuffer failed"); + } + void Recycle(VkCommandBuffer commands) noexcept override { + note(); + std::lock_guard lock(shared->mutex); + shared->recycled.push_back(commands); + } + +private: + void note() { + std::lock_guard lock(shared->mutex); + shared->users.push_back(std::this_thread::get_id()); + } + std::shared_ptr shared; +}; + +void retireUnsubmitted(SealedBatch& batch) { + batch.NotSubmitted(); + Require(batch.Retirable(), "a batch skipped by its submitter is not retirable"); +} + +void StreamsReplayInOrderAcrossChunks() { + CommandStream stream(Real()); + Require(CommandStream::IsHandle(stream.Handle()) && &CommandStream::From(stream.Handle()) == &stream, "the stream handle does not round-trip to its stream"); + Require(!CommandStream::IsHandle(fakeBuffer(7)), "a real command buffer reads as a stream handle"); + std::vector large(40000); + for (std::size_t i = 0; i < large.size(); ++i) large[i] = static_cast(i); + const std::array small{7, 8, 9}; + append(stream, 1, small); + append(stream, 2, large); + append(stream, 3); + for (std::uint32_t i = 0; i < 5000; ++i) append(stream, 100 + i); + Require(stream.Ops() == 5003, "the stream counted " + std::to_string(stream.Ops()) + " ops"); + Require(stream.Charged() > CommandStream::ChunkBytes, "a record larger than a chunk did not get its own chunk"); + Require(Throws([&] { AgcDriver::Graphics::Replay(stream, fakeBuffer(1), Real()); }), "an unsealed stream was replayed"); + stream.Seal(); + Require(Throws([&] { AgcDriver::Graphics::Replay(stream, stream.Handle(), Real()); }), "a stream was replayed into a stream handle"); + takeSeen(); + AgcDriver::Graphics::Replay(stream, fakeBuffer(1), Real()); + const auto values = takeSeen(); + Require(values.size() == 4 + 1 + large.size() + 1 + 5000, "replay produced " + std::to_string(values.size()) + " values"); + Require(values[0] == 1 && values[1] == 7 && values[3] == 9 && values[4] == 2 && values[5] == 0 && values[4 + large.size()] == 39999 && values[5 + large.size()] == 3 && values.back() == 5099, "replay did not keep the records and their arrays in order"); + Require(seen().replayThreadCalls.exchange(0) == 5003, "replay did not mark its thread as a replay thread"); + Require(!AgcDriver::Graphics::OnReplayThread(), "the replay thread mark outlived the replay"); +} + +void SealedAndFailedAppendsPoison() { + CommandStream stream(Real()); + append(stream, 1); + stream.Seal(); + Require(Throws([&] { append(stream, 2); }), "an append after Seal did not throw"); + Require(stream.Poisoned(), "an append after Seal did not poison the stream even though the caller caught the error"); + Require(Throws([&] { AgcDriver::Graphics::Replay(stream, fakeBuffer(1), Real()); }), "a poisoned stream replayed"); + CommandStream poisoned(Real()); + append(poisoned, 1); + poisoned.Poison(std::make_exception_ptr(std::invalid_argument("unknown pNext"))); + poisoned.Poison(std::make_exception_ptr(std::runtime_error("second reason"))); + Require(Throws([&] { append(poisoned, 2); }), "an append to a poisoned stream did not rethrow the first reason"); +} + +void InlineReplayFailureReachesTheLatch() { + FailureLatch latch; + auto shared = std::make_shared(); + InlineExecutor executor(std::make_unique(shared)); + CommandStream good(Real()); + append(good, 11); + auto first = std::make_shared(1, good, Real(), latch); + executor.Execute(first); + Require(first->Result() == Outcome::Encoded && first->Await() != VK_NULL_HANDLE, "the inline executor did not encode a good batch"); + first->Returned(VK_SUCCESS); + Require(!first->Retirable(), "a submitted batch was retirable before its fence"); + first->GpuDone(); + Require(first->Retirable(), "a submitted batch whose fence signalled is not retirable"); + executor.Retire(first->Commands(), first->Worker()); + CommandStream bad(Real()); + append(bad, 12); + bad.Poison(std::make_exception_ptr(std::invalid_argument("unknown pNext"))); + auto second = std::make_shared(2, bad, Real(), latch); + executor.Execute(second); + Require(second->Result() == Outcome::ReplayFailed, "a poisoned batch was not reported failed"); + Require(Throws([&] { second->Await(); }), "Await did not rethrow the replay error"); + Require(latch.FailedSerial() == 2, "the replay failure did not reach the latch"); + retireUnsubmitted(*second); + CommandStream later(Real()); + append(later, 13); + auto third = std::make_shared(3, later, Real(), latch); + executor.Execute(third); + Require(third->Result() == Outcome::Cancelled && Throws([&] { third->Await(); }), "a batch after a failed one was not cancelled"); + retireUnsubmitted(*third); + shared->failEnd.store(true); + FailureLatch fresh; + CommandStream ending(Real()); + append(ending, 14); + auto fourth = std::make_shared(1, ending, Real(), fresh); + executor.Execute(fourth); + Require(fourth->Result() == Outcome::ReplayFailed && fourth->Commands() == VK_NULL_HANDLE && shared->recycled.size() == 3, "a buffer whose end failed was not recycled before the failure was published"); + retireUnsubmitted(*fourth); +} + +void CancelDoesNotImpersonateTheWorker() { + FailureLatch latch; + auto shared = std::make_shared(); + shared->hold.store(true); + SingleExecutor executor([shared] { return std::make_unique(shared); }); + CommandStream stream(Real()); + append(stream, 21); + auto batch = std::make_shared(1, stream, Real(), latch); + executor.Execute(batch); + while (!shared->holding.load()) std::this_thread::sleep_for(std::chrono::milliseconds(1)); + batch->Cancel(); + Require(!batch->ReplayReleased(), "a cancel released the replay while the worker still held the batch"); + Require(batch->Result() == Outcome::Pending, "a cancel published an outcome while the worker still held the batch"); + shared->hold.store(false); + Require(Throws([&] { batch->Await(); }), "a batch cancelled while replaying did not end cancelled"); + Require(batch->ReplayReleased() && batch->Commands() != VK_NULL_HANDLE, "a batch cancelled during replay lost the buffer the worker began"); + retireUnsubmitted(*batch); + executor.Retire(batch->Commands(), batch->Worker()); + CommandStream unclaimed(Real()); + append(unclaimed, 22); + auto early = std::make_shared(2, unclaimed, Real(), latch); + early->Cancel(); + Require(early->ReplayReleased() && early->Result() == Outcome::Cancelled, "a batch cancelled before any worker claimed it was not released at once"); + Require(!early->Claim(), "a worker claimed a batch that was already cancelled"); + retireUnsubmitted(*early); +} + +void RefusedBatchWaitsForItsReplay() { + FailureLatch latch; + auto shared = std::make_shared(); + shared->hold.store(true); + SingleExecutor executor([shared] { return std::make_unique(shared); }); + CommandStream stream(Real()); + append(stream, 31); + auto batch = std::make_shared(1, stream, Real(), latch); + executor.Execute(batch); + while (!shared->holding.load()) std::this_thread::sleep_for(std::chrono::milliseconds(1)); + std::atomic entered{false}; + std::atomic skipped{false}; + std::thread submitter([&] { + entered.store(true); + batch->NotSubmitted(); + skipped.store(true); + }); + while (!entered.load()) std::this_thread::sleep_for(std::chrono::milliseconds(1)); + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + const bool returnedEarly = skipped.load(); + shared->hold.store(false); + submitter.join(); + Require(!returnedEarly, "a batch was skipped by its submitter before its replay released it"); + Require(batch->ReplayReleased() && batch->Retirable() && batch->Result() == Outcome::Cancelled, "a refused batch was not cancelled and retirable once its replay released it"); + executor.Retire(batch->Commands(), batch->Worker()); +} + +void FailureReachesSerialWaiters() { + FailureLatch latch; + std::atomic earlierDone{false}; + auto later = std::async(std::launch::async, [&] { + try { + AgcDriver::Graphics::WaitObservingFailure(latch, 5, std::chrono::milliseconds(1), [](std::chrono::nanoseconds slice) { + std::this_thread::sleep_for(slice); + return false; + }); + } catch (const std::invalid_argument&) { + return true; + } + return false; + }); + auto earlier = std::async(std::launch::async, [&] { + AgcDriver::Graphics::WaitObservingFailure(latch, 2, std::chrono::milliseconds(1), [&](std::chrono::nanoseconds slice) { + std::this_thread::sleep_for(slice); + return earlierDone.load(); + }); + return true; + }); + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + latch.Fail(3, std::make_exception_ptr(std::invalid_argument("replay of batch 3 failed"))); + Require(Throws([&] { latch.ThrowFor(3); }), "a waiter on the failed serial itself did not see its failure"); + Require(later.wait_for(std::chrono::seconds(5)) == std::future_status::ready && later.get(), "a waiter on a serial after the failed batch did not see a failure that arrived after it started waiting"); + Require(earlier.wait_for(std::chrono::milliseconds(50)) == std::future_status::timeout, "a waiter on a serial before the failed batch gave up on work that can still complete"); + earlierDone.store(true); + Require(earlier.wait_for(std::chrono::seconds(5)) == std::future_status::ready && earlier.get(), "a waiter on an earlier serial did not finish when its work completed"); + Require(!latch.Fail(4, nullptr) && latch.FailedSerial() == 3 && latch.Fail(1, std::make_exception_ptr(std::runtime_error("earlier"))) && latch.FailedSerial() == 1, "the latch did not keep the lowest failed serial"); + FailureLatch closing; + auto parked = std::async(std::launch::async, [&] { + return Throws([&] { + AgcDriver::Graphics::WaitObservingFailure(closing, 1, std::chrono::milliseconds(1), [](std::chrono::nanoseconds slice) { + std::this_thread::sleep_for(slice); + return false; + }); + }); + }); + closing.Shutdown(); + Require(parked.wait_for(std::chrono::seconds(5)) == std::future_status::ready && parked.get(), "shutdown did not release a serial waiter"); +} + +void DeviceLossHoldsResourcesUntilTheDeviceIsIdle() { + FailureLatch latch; + auto shared = std::make_shared(); + InlineExecutor executor(std::make_unique(shared)); + CommandStream lostStream(Real()); + append(lostStream, 31); + auto lost = std::make_shared(1, lostStream, Real(), latch); + executor.Execute(lost); + static_cast(lost->Await()); + lost->Returned(VK_ERROR_DEVICE_LOST); + Require(lost->Result() == Outcome::DeviceLost && lost->SubmitReturned() && !lost->GpuReleased() && !lost->Retirable(), "a batch whose submit lost the device was retirable before the device was idled"); + lost->GpuDone(); + Require(!lost->Retirable(), "a fence observation released a batch after device loss"); + Require(latch.DeviceLost() && Throws([&] { latch.ThrowFor(0); }), "device loss did not fail every serial, including earlier ones"); + lost->DeviceIdleAfterLoss(); + Require(lost->Retirable(), "the lost-device cleanup did not release the batch"); + FailureLatch other; + CommandStream failedStream(Real()); + append(failedStream, 32); + auto failed = std::make_shared(4, failedStream, Real(), other); + executor.Execute(failed); + static_cast(failed->Await()); + failed->Returned(VK_ERROR_OUT_OF_DEVICE_MEMORY); + Require(failed->Result() == Outcome::SubmitFailed && failed->Retirable() && other.FailedSerial() == 4 && !other.DeviceLost(), "an ordinary failed submit was not retirable at once or did not latch its serial"); + CommandStream earlyStream(Real()); + append(earlyStream, 33); + auto early = std::make_shared(5, earlyStream, Real(), other); + executor.Execute(early); + Require(early->Result() == Outcome::Cancelled, "a batch after a failed submit was replayed"); + retireUnsubmitted(*early); +} + +void FenceBeforeReturnStaysHeld() { + FailureLatch latch; + auto shared = std::make_shared(); + InlineExecutor executor(std::make_unique(shared)); + CommandStream stream(Real()); + append(stream, 41); + auto batch = std::make_shared(1, stream, Real(), latch); + executor.Execute(batch); + static_cast(batch->Await()); + batch->GpuDone(); + Require(!batch->Retirable(), "a batch whose fence signalled before vkQueueSubmit returned was retirable"); + batch->Returned(VK_SUCCESS); + Require(batch->Retirable(), "a batch did not retire once its submit returned after the fence"); +} + +void BudgetBoundsWorkThroughRetirement() { + WorkBudget budget(WorkBudget::Limits{2, 3, 1u << 30}); + FailureLatch latch; + auto shared = std::make_shared(); + shared->hold.store(true); + SingleExecutor executor([shared] { return std::make_unique(shared); }); + std::vector> streams; + std::vector> batches; + for (std::uint64_t serial = 1; serial <= 3; ++serial) { + Require(budget.Choose() == (serial <= 2 ? WorkBudget::Mode::Deferred : WorkBudget::Mode::Direct), "batch " + std::to_string(serial) + " chose the wrong mode with " + std::to_string(budget.Encoding()) + " batches encoding"); + budget.Open(latch, serial); + streams.push_back(std::make_unique(Real(), &budget)); + append(*streams.back(), static_cast(serial)); + if (serial <= 2) { + batches.push_back(std::make_shared(serial, *streams.back(), Real(), latch, &budget)); + executor.Execute(batches.back()); + } + } + Require(budget.Outstanding() == 3 && budget.OutstandingBytes() == 3 * CommandStream::ChunkBytes, "the budget did not count every open batch and its stream bytes"); + auto blocked = std::async(std::launch::async, [&] { + budget.Open(latch, 4); + return true; + }); + Require(blocked.wait_for(std::chrono::milliseconds(50)) == std::future_status::timeout, "a fourth batch opened past the outstanding bound"); + shared->hold.store(false); + static_cast(batches[0]->Await()); + static_cast(batches[1]->Await()); + Require(budget.Encoding() == 0 && budget.Choose() == WorkBudget::Mode::Deferred, "encoding admission did not reopen once the replays were released"); + streams[0]->ReleaseMemory(); + Require(blocked.wait_for(std::chrono::milliseconds(50)) == std::future_status::timeout && budget.OutstandingBytes() == 3 * CommandStream::ChunkBytes, "a batch's charge was released when its replay finished instead of when it retired"); + batches[0]->Returned(VK_SUCCESS); + batches[0]->GpuDone(); + Require(blocked.wait_for(std::chrono::seconds(5)) == std::future_status::ready && blocked.get(), "a retirement did not admit the blocked batch"); + Require(budget.RoomWaits() == 1, "the room wait was not counted"); + batches[0]->GpuDone(); + batches[0]->Returned(VK_SUCCESS); + Require(budget.Outstanding() == 3 && budget.OutstandingBytes() == 2 * CommandStream::ChunkBytes, "a batch released its budget charge twice"); + auto failing = std::async(std::launch::async, [&] { return Throws([&] { budget.Open(latch, 5); }); }); + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + latch.Fail(2, std::make_exception_ptr(std::invalid_argument("batch 2 failed"))); + Require(failing.wait_for(std::chrono::seconds(5)) == std::future_status::ready && failing.get(), "a batch waiting for room did not see a later failure"); + retireUnsubmitted(*batches[1]); + executor.Retire(batches[0]->Commands(), 0); + executor.Retire(batches[1]->Commands(), 0); + budget.Retired(streams[2]->Charged()); + budget.Retired(0); +} + +class CountingMaterializer final : public AgcDriver::Graphics::StreamMaterializer { +public: + VkCommandBuffer Begin(CommandStream&) override { + ++begun; + return fakeBuffer(90); + } + int begun = 0; +}; + +void StreamByteCapDemotesTheBatch() { + WorkBudget budget(WorkBudget::Limits{4, 4, 16 * CommandStream::ChunkBytes}); + FailureLatch latch; + budget.Open(latch, 1); + const auto cap = budget.StreamCap(); + Require(cap == 4 * CommandStream::ChunkBytes, "the stream cap is not the outstanding bytes shared by the outstanding batches: " + std::to_string(cap)); + const std::vector array(1000, 5); + { + CountingMaterializer materializer; + CommandStream stream(Real(), &budget, &materializer); + takeSeen(); + std::uint32_t appended = 0; + while (stream.Materialized() == VK_NULL_HANDLE && appended < 1000) { + append(stream, appended++, array); + Require(stream.Charged() <= cap, "a stream was charged " + std::to_string(stream.Charged()) + " bytes past its cap of " + std::to_string(cap)); + } + Require(stream.Materialized() != VK_NULL_HANDLE, "a stream at its byte cap did not demote"); + Require(std::string_view(stream.DemotedBy().command) == "stream byte cap" && stream.DemotedBy().chained == VK_STRUCTURE_TYPE_MAX_ENUM, "the cap demotion was not attributed to the cap"); + Require(materializer.begun == 1, "the cap demotion began " + std::to_string(materializer.begun) + " command buffers"); + Require(stream.Charged() == 0 && budget.OutstandingBytes() == 0, "a demoted stream's freed chunks stayed charged: " + std::to_string(budget.OutstandingBytes()) + " bytes"); + const auto values = takeSeen(); + Require(values.size() == appended * (array.size() + 1) && values.front() == 0 && values[(appended - 1) * (array.size() + 1)] == appended - 1, "the cap demotion did not record every command in order, including the one past the cap"); + budget.Retired(stream.Charged()); + } + for (const std::size_t before : {std::size_t{0}, std::size_t{1}}) { + budget.Open(latch, 2); + CountingMaterializer materializer; + CommandStream stream(Real(), &budget, &materializer); + takeSeen(); + for (std::size_t index = 0; index < before; ++index) append(stream, 7, array); + std::vector large(cap / sizeof(std::uint32_t)); + for (std::size_t index = 0; index < large.size(); ++index) large[index] = static_cast(index); + append(stream, 9, large); + Require(stream.Charged() == 0 && budget.OutstandingBytes() == 0, "one command larger than the remaining cap left " + std::to_string(budget.OutstandingBytes()) + " bytes charged for a cap of " + std::to_string(cap)); + Require(stream.Materialized() != VK_NULL_HANDLE && std::string_view(stream.DemotedBy().command) == "stream byte cap", "one command larger than the remaining cap did not demote"); + const auto values = takeSeen(); + Require(values.size() == before * (array.size() + 1) + 1 + large.size() && values[before * (array.size() + 1)] == 9 && values.back() == large.back(), "the command past the cap was not recorded after the prefix"); + budget.Retired(stream.Charged()); + } + budget.Open(latch, 3); + CommandStream undemotable(Real(), &budget); + bool refused = false; + for (std::uint32_t value = 0; value < 1000 && !refused; ++value) refused = Throws([&] { append(undemotable, value, array); }); + Require(refused && undemotable.Poisoned() && undemotable.Charged() <= cap, "a stream with no way to demote grew past its cap instead of ending"); + budget.Retired(undemotable.Charged()); + takeSeen(); + seen().replayThreadCalls.store(0); +} + +VKAPI_ATTR void VKAPI_CALL seeMarker(VkCommandBuffer, const void* marker) { + std::lock_guard lock(seen().mutex); + seen().values.push_back(static_cast(reinterpret_cast(marker))); +} + +void TwoThreadsAppendToTwoStreams() { + constexpr std::uint32_t Records = 20000; + WorkBudget budget(WorkBudget::Limits{4, 4, 1u << 30}); + FailureLatch latch; + budget.Open(latch, 1); + budget.Open(latch, 2); + CommandFunctions functions{}; + functions.CmdSetCheckpointNV = &seeMarker; + std::array, 2> streams{std::make_unique(functions, &budget), std::make_unique(functions, &budget)}; + const auto setCheckpoint = AgcDriver::Graphics::StreamedCommands().CmdSetCheckpointNV; + std::atomic ready{0}; + const auto record = [&](std::size_t which) { + auto& stream = *streams[which]; + const auto tag = static_cast(which + 1) << 24; + ready.fetch_add(1); + while (ready.load() != 2) std::this_thread::yield(); + for (std::uint32_t index = 0; index < Records; ++index) { + const std::array array{tag | index, tag | (index * 7)}; + if (index % 3 == 0) setCheckpoint(stream.Handle(), reinterpret_cast(static_cast(tag | index))); + else append(stream, tag | index, std::span(array.data(), index % 3)); + } + }; + std::thread other(record, 1); + record(0); + other.join(); + Require(budget.OutstandingBytes() == streams[0]->Charged() + streams[1]->Charged(), "two streams charging at once left the budget at " + std::to_string(budget.OutstandingBytes()) + " bytes"); + takeSeen(); + for (std::size_t which = 0; which < streams.size(); ++which) { + auto& stream = *streams[which]; + Require(stream.Ops() == Records && stream.Materialized() == VK_NULL_HANDLE && !stream.Poisoned(), "stream " + std::to_string(which) + " counted " + std::to_string(stream.Ops()) + " ops"); + stream.Seal(); + AgcDriver::Graphics::Replay(stream, fakeBuffer(80 + which), functions); + const auto values = takeSeen(); + const auto tag = static_cast(which + 1) << 24; + std::vector expected; + for (std::uint32_t index = 0; index < Records; ++index) { + expected.push_back(tag | index); + if (index % 3 == 2) { + expected.push_back(tag | index); + expected.push_back(tag | (index * 7)); + } else if (index % 3 == 1) { + expected.push_back(tag | index); + } + } + Require(values == expected, "stream " + std::to_string(which) + " replayed " + std::to_string(values.size()) + " values that differ from what its thread appended"); + } + seen().replayThreadCalls.store(0); + budget.Retired(streams[0]->Charged()); + budget.Retired(streams[1]->Charged()); +} + +void TwoThreadsChargeOneBudgetAtOnce() { + constexpr std::uint64_t Streams = 20000; + constexpr std::uint64_t MostStreams = 16 * Streams; + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(60); + std::atomic late{false}; + WorkBudget budget(WorkBudget::Limits{4, 4, std::size_t{1} << 62}); + std::array, 2> done{}; + std::array charged{}; + std::array otherAtStart{}; + std::atomic ready{0}; + const auto charge = [&](std::size_t which) { + const auto other = 1 - which; + ready.fetch_add(1); + while (ready.load() != 2) std::this_thread::yield(); + otherAtStart[which] = done[other].load(); + while (done[which].load() < MostStreams && (done[which].load() < Streams || done[other].load() < Streams)) { + if (late.load() || std::chrono::steady_clock::now() > deadline) { + late.store(true); + return; + } + CommandStream stream(Real(), &budget); + append(stream, static_cast(which)); + charged[which] += stream.Charged(); + done[which].fetch_add(1); + } + }; + std::thread second(charge, 1); + charge(0); + second.join(); + takeSeen(); + Require(!late.load(), "two threads did not charge " + std::to_string(Streams) + " streams each within 60 seconds: " + std::to_string(done[0].load()) + " and " + std::to_string(done[1].load())); + Require(otherAtStart[0] < Streams && otherAtStart[1] < Streams, "one thread finished charging before the other started"); + Require(budget.OutstandingBytes() == charged[0] + charged[1], "two threads charging one budget at once lost " + std::to_string(charged[0] + charged[1] - budget.OutstandingBytes()) + " bytes"); +} + +void RetirementOutlivesTheStream() { + WorkBudget budget(WorkBudget::Limits{2, 2, 1u << 30}); + FailureLatch latch; + budget.Open(latch, 1); + auto stream = std::make_unique(Real(), &budget); + append(*stream, 51); + const auto charged = stream->Charged(); + SealedBatch batch(1, *stream, Real(), latch, &budget); + Require(batch.Claim(), "an unclaimed batch could not be claimed"); + batch.Encoded(fakeBuffer(51), 0); + stream.reset(); + Require(budget.OutstandingBytes() == charged, "the budget lost the batch's charge before it retired"); + retireUnsubmitted(batch); + Require(budget.OutstandingBytes() == 0 && budget.Outstanding() == 0, "retirement after the stream was freed did not return the batch's charge"); +} + +std::atomic createdPools{0}; +std::atomic destroyedPools{0}; + +VKAPI_ATTR VkResult VKAPI_CALL countedCreatePool(VkDevice, const VkCommandPoolCreateInfo*, const VkAllocationCallbacks*, VkCommandPool* pool) { + *pool = reinterpret_cast(static_cast(++createdPools) << 4); + return VK_SUCCESS; +} + +VKAPI_ATTR void VKAPI_CALL countedDestroyPool(VkDevice, VkCommandPool, const VkAllocationCallbacks*) { + ++destroyedPools; +} + +void ReplayPoolCreationDoesNotLeak() { + ReplayEntryPoints entry; + entry.createPool = countedCreatePool; + entry.destroyPool = countedDestroyPool; + CreateReplayPool(entry, 0).reset(); + Require(createdPools.load() == 1 && destroyedPools.load() == 1, "an owned replay pool was not destroyed with its owner"); + AgcDriver::Tests::SetAllocationFailureCountdown(0); + const bool threw = Throws([&] { static_cast(CreateReplayPool(entry, 0)); }); + AgcDriver::Tests::SetAllocationFailureCountdown(-1); + Require(threw, "the injected allocation failure did not surface"); + Require(createdPools.load() == destroyedPools.load(), "a replay pool created before its owner failed to allocate was leaked: " + std::to_string(createdPools.load()) + " created, " + std::to_string(destroyedPools.load()) + " destroyed"); +} + +void SingleExecutorOwnsItsPoolAndThread() { + FailureLatch latch; + auto shared = std::make_shared(); + std::thread::id worker; + std::vector> streams; + std::vector> batches; + { + SingleExecutor executor([shared, &worker] { + worker = std::this_thread::get_id(); + return std::make_unique(shared); + }); + takeSeen(); + seen().replayThreadCalls.store(0); + for (std::uint64_t serial = 1; serial <= 8; ++serial) { + streams.push_back(std::make_unique(Real())); + append(*streams.back(), static_cast(serial)); + batches.push_back(std::make_shared(serial, *streams.back(), Real(), latch)); + executor.Execute(batches.back()); + } + for (auto& batch : batches) static_cast(batch->Await()); + const auto values = takeSeen(); + Require(values == std::vector{1, 2, 3, 4, 5, 6, 7, 8}, "the single executor did not replay batches in order"); + Require(seen().replayThreadCalls.exchange(0) == 8, "the single executor's replays were not marked as replay threads"); + for (auto& batch : batches) { + batch->Returned(VK_SUCCESS); + batch->GpuDone(); + executor.Retire(batch->Commands(), batch->Worker()); + } + executor.Shutdown(); + std::lock_guard lock(shared->mutex); + Require(shared->recycled.size() == 8, "retired buffers were not recycled before shutdown returned"); + for (const auto& id : shared->users) Require(id == worker, "a pool was used off its worker thread"); + CommandStream afterStream(Real()); + append(afterStream, 9); + auto after = std::make_shared(9, afterStream, Real(), latch); + executor.Execute(after); + Require(after->Result() == Outcome::Cancelled, "a batch handed to a stopped executor was not cancelled"); + retireUnsubmitted(*after); + } + FailureLatch broken; + CommandStream stream(Real()); + append(stream, 10); + auto batch = std::make_shared(1, stream, Real(), broken); + { + SingleExecutor executor([]() -> std::unique_ptr { throw std::runtime_error("vkCreateCommandPool failed"); }); + executor.Execute(batch); + Require(Throws([&] { batch->Await(); }) && batch->Result() == Outcome::ReplayFailed && broken.FailedSerial() == 1, "a worker without a pool did not fail its batches"); + } + retireUnsubmitted(*batch); +} + +void ShutdownCancelsQueuedBatches() { + FailureLatch latch; + auto shared = std::make_shared(); + shared->hold.store(true); + std::vector> streams; + std::vector> batches; + { + SingleExecutor executor([shared] { return std::make_unique(shared); }); + for (std::uint64_t serial = 1; serial <= 3; ++serial) { + streams.push_back(std::make_unique(Real())); + append(*streams.back(), static_cast(serial)); + batches.push_back(std::make_shared(serial, *streams.back(), Real(), latch)); + executor.Execute(batches.back()); + while (!shared->holding.load()) std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + std::thread release([shared] { + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + shared->hold.store(false); + }); + executor.Shutdown(); + release.join(); + } + Require(batches[0]->ReplayReleased() && batches[1]->Result() == Outcome::Cancelled && batches[2]->Result() == Outcome::Cancelled, "shutdown left queued batches unreleased"); + for (auto& batch : batches) retireUnsubmitted(*batch); +} + +int destroyUnretired() { + FailureLatch latch; + CommandStream stream(Real()); + append(stream, 1); + auto batch = std::make_unique(1, stream, Real(), latch); + batch->Cancel(); + batch.reset(); + return 0; +} + +int appendOnReplayThread() { + CommandStream stream(Real()); + const AgcDriver::Graphics::ReplayThreadScope scope; + append(stream, 1); + return 0; +} + +void DiesWith(const std::string& self, const std::string& mode, const std::string& expected) { + const auto output = std::filesystem::temp_directory_path() / ("aps5-sealed-batch" + mode + "-" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()) + ".txt"); + std::string command = "\"" + self + "\" " + mode + " 2> \"" + output.string() + "\""; +#ifdef _WIN32 + command = "\"" + command + "\""; +#endif + const int status = std::system(command.c_str()); + std::stringstream text; + text << std::ifstream(output).rdbuf(); + std::error_code error; + std::filesystem::remove(output, error); + Require(status != 0, "the " + mode + " child did not end abnormally"); + Require(text.str().find(expected) != std::string::npos, "the " + mode + " child did not print \"" + expected + "\": " + text.str()); +} + +} + +void AdmissionOpensDirectInsteadOfWaiting() { + WorkBudget budget(WorkBudget::Limits{2, 3, 1u << 30}); + FailureLatch latch; + auto shared = std::make_shared(); + shared->hold.store(true); + SingleExecutor executor([shared] { return std::make_unique(shared); }); + std::vector> streams; + std::vector> batches; + for (std::uint64_t serial = 1; serial <= 2; ++serial) { + Require(budget.TryOpen(), "batch " + std::to_string(serial) + " was refused under the encoding bound"); + streams.push_back(std::make_unique(Real(), &budget)); + append(*streams.back(), static_cast(serial)); + batches.push_back(std::make_shared(serial, *streams.back(), Real(), latch, &budget)); + executor.Execute(batches.back()); + } + const auto start = std::chrono::steady_clock::now(); + Require(!budget.TryOpen(), "a batch was admitted while two sealed batches waited for the replay worker"); + Require(std::chrono::steady_clock::now() - start < std::chrono::milliseconds(50), "a refused admission waited"); + Require(budget.Refusals() == 1 && budget.Outstanding() == 2 && budget.RoomWaits() == 0, "a refused admission was not counted, or took a slot"); + shared->hold.store(false); + static_cast(batches[0]->Await()); + static_cast(batches[1]->Await()); + Require(budget.TryOpen(), "admission did not reopen once the replays were released"); + Require(!budget.TryOpen(), "a batch was admitted past the outstanding bound"); + Require(budget.Refusals() == 2, "the outstanding refusal was not counted"); + for (auto& batch : batches) { + batch->Returned(VK_SUCCESS); + batch->GpuDone(); + executor.Retire(batch->Commands(), 0); + } + Require(budget.Outstanding() == 1 && budget.TryOpen(), "retired batches did not give their slots back"); + budget.Retired(0); + budget.Retired(0); +} + +int main(int argc, char** argv) { +#ifdef _WIN32 + _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); +#endif + if (argc == 2 && std::string_view(argv[1]) == "--destroy-unretired") return destroyUnretired(); + if (argc == 2 && std::string_view(argv[1]) == "--append-on-replay") return appendOnReplayThread(); + try { + StreamsReplayInOrderAcrossChunks(); + SealedAndFailedAppendsPoison(); + InlineReplayFailureReachesTheLatch(); + CancelDoesNotImpersonateTheWorker(); + RefusedBatchWaitsForItsReplay(); + FailureReachesSerialWaiters(); + DeviceLossHoldsResourcesUntilTheDeviceIsIdle(); + FenceBeforeReturnStaysHeld(); + BudgetBoundsWorkThroughRetirement(); + RetirementOutlivesTheStream(); + StreamByteCapDemotesTheBatch(); + TwoThreadsAppendToTwoStreams(); + TwoThreadsChargeOneBudgetAtOnce(); + ReplayPoolCreationDoesNotLeak(); + AdmissionOpensDirectInsteadOfWaiting(); + SingleExecutorOwnsItsPoolAndThread(); + ShutdownCancelsQueuedBatches(); + DiesWith(argv[0], "--destroy-unretired", "destroyed before its submission returned"); + DiesWith(argv[0], "--append-on-replay", "appended to a stream from a replay thread"); + } catch (const std::exception& error) { + std::fprintf(stderr, "sealed batch: %s\n", error.what()); + return 1; + } + std::puts("sealed batch: ok"); + return 0; +} diff --git a/core/libs/prx/libSceAgcDriver/tests/StreamGuards.cpp b/core/libs/prx/libSceAgcDriver/tests/StreamGuards.cpp new file mode 100644 index 000000000000..7aea358968c6 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/StreamGuards.cpp @@ -0,0 +1,22 @@ +#include "prx/libSceAgcDriver/Graphics/include/CommandStream.hpp" +#include +#include +#include +#include + +using AgcDriver::Graphics::CommandStream; + +void StreamGuardedPayloads(CommandStream& stream) { +#if defined(APS5_GUARD_OWNING_PAYLOAD) + stream.Emplace(nullptr, std::shared_ptr()); +#elif defined(APS5_GUARD_OWNING_ARRAY) + const std::string names[1]; + stream.Emplace(nullptr, std::uint32_t{1}, std::span(names)); +#elif defined(APS5_GUARD_POINTER_ARGUMENT) + CommandStream::CheckPlain(); +#else + const std::uint32_t words[2]{}; + stream.Emplace(nullptr, std::uint64_t{0}, std::span(words)); + CommandStream::CheckPlain(); +#endif +} diff --git a/core/libs/prx/libSceAgcDriver/tests/TextureDetiler.cpp b/core/libs/prx/libSceAgcDriver/tests/TextureDetiler.cpp index 68297257b09e..04b02f049e1d 100644 --- a/core/libs/prx/libSceAgcDriver/tests/TextureDetiler.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/TextureDetiler.cpp @@ -1,4 +1,5 @@ #include "GraphicsTests.hpp" +#include "FakeHandles.hpp" #include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" #include "prx/libSceAgcDriver/Graphics/include/ColorTargetLayout.hpp" #include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" @@ -69,7 +70,7 @@ void reject(TAction action, std::string_view reason) { void RunTextureDetilerTests(const Context& context, const TextureDetilerTestAccess& access) { TextureDetiler detiler(context); - const auto commands = reinterpret_cast(static_cast(1)); + const auto commands = FakeCommandBuffer(1); const auto source = access.makeBuffer(4096); const auto destination = access.makeBuffer(4096); @@ -213,7 +214,7 @@ void RunTextureDetilerTests(const Context& context, const TextureDetilerTestAcce DeviceFunctions table{}; table.updateDescriptorSets = context.Function("vkUpdateDescriptorSets"); table.allocateDescriptorSets = context.Function("vkAllocateDescriptorSets"); - table.cmdBindPipeline = reinterpret_cast(context.deviceProc(context.device, "vkCmdBindPipeline")); + table.cmdBindPipeline = reinterpret_cast(AgcDriver::Graphics::CommandThunk("vkCmdBindPipeline", context.deviceProc(context.device, "vkCmdBindPipeline"), context.device)); table.cmdBindDescriptorSets = context.Function("vkCmdBindDescriptorSets"); table.cmdPushConstants = context.Function("vkCmdPushConstants"); table.cmdDispatch = context.Function("vkCmdDispatch"); diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_command_thunks_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_command_thunks_tests.cmake new file mode 100644 index 000000000000..1772b0073361 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_command_thunks_tests.cmake @@ -0,0 +1,13 @@ +if(BUILD_TESTING) + add_test_executable(agc_command_thunks_tests tests/CommandThunks.cpp Graphics/src/CommandStream.cpp Graphics/src/SealedBatch.cpp Graphics/src/CommandThunks.cpp Graphics/src/RuntimeSwitches.cpp) + target_include_directories(agc_command_thunks_tests PRIVATE ${LIBS_INCLUDE_DIR} ${CMAKE_SOURCE_DIR}/3rdparty/Vulkan-Headers/include) + target_link_libraries(agc_command_thunks_tests PRIVATE libc) + configure_windows_unwind(agc_command_thunks_tests) + add_test(NAME agc_command_thunks COMMAND agc_command_thunks_tests) + add_test(NAME agc_command_thunks_direct_cost COMMAND agc_command_thunks_tests --bench) + set_tests_properties(agc_command_thunks agc_command_thunks_direct_cost PROPERTIES TIMEOUT 60) + if(WIN32) + set_tests_properties(agc_command_thunks agc_command_thunks_direct_cost PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_depth_plane_sampling_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_depth_plane_sampling_tests.cmake index 15c7782d4762..77e646ff85ee 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_depth_plane_sampling_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_depth_plane_sampling_tests.cmake @@ -5,8 +5,11 @@ if(BUILD_TESTING) set_tests_properties(agc_driver_depth_plane_sampling_unimported PROPERTIES ENVIRONMENT "APS5_NO_HOST_IMPORT=1" SKIP_RETURN_CODE 77 TIMEOUT 120) add_test(NAME agc_driver_depth_plane_sampling_per_use COMMAND agc_driver_depth_plane_sampling_tests) set_tests_properties(agc_driver_depth_plane_sampling_per_use PROPERTIES ENVIRONMENT "ANYPS5_NO_SHADER_CACHE=1;APS5_NO_DEPTH_PLANE_REUSE=1" SKIP_RETURN_CODE 77 TIMEOUT 120) + add_test(NAME agc_driver_depth_plane_sampling_streamed_secondaries COMMAND agc_driver_depth_plane_sampling_tests --streamed-secondaries) + set_tests_properties(agc_driver_depth_plane_sampling_streamed_secondaries PROPERTIES ENVIRONMENT "APS5_PARALLEL_ATLAS=1" SKIP_RETURN_CODE 77 TIMEOUT 30 + FAIL_REGULAR_EXPRESSION "SYNC-HAZARD-|VUID-|was not found but was requested by env var VK_INSTANCE_LAYERS") if(WIN32) - set_tests_properties(agc_driver_depth_plane_sampling_evicting agc_driver_depth_plane_sampling_unimported agc_driver_depth_plane_sampling_per_use PROPERTIES ENVIRONMENT_MODIFICATION + set_tests_properties(agc_driver_depth_plane_sampling_evicting agc_driver_depth_plane_sampling_unimported agc_driver_depth_plane_sampling_per_use agc_driver_depth_plane_sampling_streamed_secondaries PROPERTIES ENVIRONMENT_MODIFICATION "PATH=path_list_prepend:$") endif() endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_recorder_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_recorder_tests.cmake index 3fd270c88a8b..188ecc7a1ee7 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_recorder_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_driver_recorder_tests.cmake @@ -566,8 +566,10 @@ if(BUILD_TESTING) endif() add_test(NAME agc_driver_recorder COMMAND agc_driver_recorder_tests) set_tests_properties(agc_driver_recorder PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) + add_test(NAME agc_driver_recorder_record_inline COMMAND agc_driver_recorder_tests) + set_tests_properties(agc_driver_recorder_record_inline PROPERTIES ENVIRONMENT "APS5_RECORD_INLINE=1" SKIP_RETURN_CODE 77 TIMEOUT 30) if(ANYPS5_ENABLE_ASAN) - set_tests_properties(agc_driver_recorder PROPERTIES TIMEOUT 120) + set_tests_properties(agc_driver_recorder agc_driver_recorder_record_inline PROPERTIES TIMEOUT 120) endif() if(WIN32) add_test(NAME agc_storage_cpu_snapshot COMMAND agc_driver_recorder_tests --storage-cpu-snapshot-only) @@ -638,6 +640,8 @@ if(BUILD_TESTING) set_tests_properties(agc_shadowed_key_stores PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) add_test(NAME agc_sample_dumps COMMAND agc_driver_recorder_tests --sample-dumps-only) set_tests_properties(agc_sample_dumps PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) + add_test(NAME agc_streamed_segments COMMAND agc_driver_recorder_tests --streamed-segments-only) + set_tests_properties(agc_streamed_segments PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) add_test(NAME agc_snapshot_read_into_staging COMMAND agc_driver_recorder_tests --snapshot-read-into-staging-only) set_tests_properties(agc_snapshot_read_into_staging PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 30) add_test(NAME agc_uncounted_passes COMMAND agc_driver_recorder_tests --uncounted-passes-only) diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_pipeline_cache_allocation_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_pipeline_cache_allocation_tests.cmake index 40b9cc72fd3f..ec68b26dd371 100644 --- a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_pipeline_cache_allocation_tests.cmake +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_pipeline_cache_allocation_tests.cmake @@ -1,5 +1,5 @@ add_test_executable(agc_pipeline_cache_allocation_tests EXCLUDE_FROM_ALL tests/PipelineCacheFailures.cpp - Graphics/src/PipelineCache.cpp tests/AllocationFailure.cpp) + Graphics/src/PipelineCache.cpp Graphics/src/CommandStream.cpp Graphics/src/SealedBatch.cpp Graphics/src/CommandThunks.cpp Graphics/src/RuntimeSwitches.cpp tests/AllocationFailure.cpp) target_include_directories(agc_pipeline_cache_allocation_tests PRIVATE ${LIBS_INCLUDE_DIR} ${CMAKE_SOURCE_DIR}/core/shader/recompiler ${ANYPS5_VULKAN_HEADERS_INCLUDE_DIR}) target_link_libraries(agc_pipeline_cache_allocation_tests PRIVATE shader_recompiler_agc_driver libc) set_target_properties(agc_pipeline_cache_allocation_tests PROPERTIES CXX_EXTENSIONS OFF) diff --git a/core/libs/prx/libSceAgcDriver/tests/cmake/agc_sealed_batch_tests.cmake b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_sealed_batch_tests.cmake new file mode 100644 index 000000000000..62f68bd30393 --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/cmake/agc_sealed_batch_tests.cmake @@ -0,0 +1,12 @@ +if(BUILD_TESTING) + add_test_executable(agc_sealed_batch_tests tests/SealedBatch.cpp Graphics/src/CommandStream.cpp Graphics/src/SealedBatch.cpp Graphics/src/CommandThunks.cpp Graphics/src/RuntimeSwitches.cpp tests/AllocationFailure.cpp) + target_include_directories(agc_sealed_batch_tests PRIVATE ${LIBS_INCLUDE_DIR} ${CMAKE_SOURCE_DIR}/3rdparty/Vulkan-Headers/include) + target_link_libraries(agc_sealed_batch_tests PRIVATE libc) + configure_windows_unwind(agc_sealed_batch_tests) + add_test(NAME agc_sealed_batch COMMAND agc_sealed_batch_tests) + set_tests_properties(agc_sealed_batch PROPERTIES TIMEOUT 30) + if(WIN32) + set_tests_properties(agc_sealed_batch PROPERTIES ENVIRONMENT_MODIFICATION + "PATH=path_list_prepend:$") + endif() +endif() diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/ColorWriteMaskDynamic.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/ColorWriteMaskDynamic.cpp index 41c41b320f21..1546cff1aa04 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/ColorWriteMaskDynamic.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/ColorWriteMaskDynamic.cpp @@ -199,7 +199,7 @@ struct MaskTrace { AgcDriver::Graphics::DeviceFunctions* functions; explicit MaskTrace(const AgcDriver::Graphics::Context& context) { functions = const_cast(context.functions); - NativeSetMasks = context.dynamicColorWriteMask ? reinterpret_cast(context.deviceProc(context.device, "vkCmdSetColorWriteMaskEXT")) : nullptr; + NativeSetMasks = context.dynamicColorWriteMask ? reinterpret_cast(AgcDriver::Graphics::CommandThunk("vkCmdSetColorWriteMaskEXT", context.deviceProc(context.device, "vkCmdSetColorWriteMaskEXT"), context.device)) : nullptr; Require(functions != nullptr && NativeSetMasks != nullptr, "vkCmdSetColorWriteMaskEXT is unavailable"); functions->cmdSetColorWriteMask = CountMasks; } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DepthBiasPerFace.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DepthBiasPerFace.cpp index e47518278888..cf5d291f97a7 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DepthBiasPerFace.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DepthBiasPerFace.cpp @@ -87,8 +87,8 @@ VKAPI_ATTR void VKAPI_CALL SetScissor(VkCommandBuffer commands, std::uint32_t fi AgcDriver::Graphics::Context TracedContext(const AgcDriver::VulkanDevice& device) { auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(device); - Trace.viewport = reinterpret_cast(context.deviceProc(context.device, "vkCmdSetViewport")); - Trace.scissor = reinterpret_cast(context.deviceProc(context.device, "vkCmdSetScissor")); + Trace.viewport = reinterpret_cast(AgcDriver::Graphics::CommandThunk("vkCmdSetViewport", context.deviceProc(context.device, "vkCmdSetViewport"), context.device)); + Trace.scissor = reinterpret_cast(AgcDriver::Graphics::CommandThunk("vkCmdSetScissor", context.deviceProc(context.device, "vkCmdSetScissor"), context.device)); Trace.functions = context.functions != nullptr ? *context.functions : AgcDriver::Graphics::DeviceFunctions{}; Trace.functions.cmdSetViewport = SetViewport; Trace.functions.cmdSetScissor = SetScissor; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/DepthPlaneSampling.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/DepthPlaneSampling.cpp index 2cda2a7fa440..477c1b6ac340 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/DepthPlaneSampling.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/DepthPlaneSampling.cpp @@ -113,6 +113,9 @@ constexpr std::size_t ParallelStencilOffset = 0x860000; constexpr std::size_t ParallelStencilPlaneOffset = 0x880000; constexpr std::size_t ParallelD16Offset = 0x8a0000; constexpr std::size_t AliasOffset = 0x900000; +constexpr std::size_t StreamedSecondaryOffset = 0x980000; +constexpr std::size_t StreamedSecondaryStride = 0x20000; +constexpr std::uint32_t StreamedSecondaryDraws = 4; constexpr float DrawnDepth = 0.25f; constexpr float DrawnD16Depth = 0.2f; constexpr std::uint32_t DrawnD16Bits = 13107; @@ -838,6 +841,42 @@ void ParallelAtlasCase(AgcDriver::VulkanDevice& device, GuestBlock& block, std:: Require(pooled == (parallel ? 8u : 0u), std::to_string(pooled) + " of the case's 8 depth-only draws were recorded on the recording pool, expected " + (parallel ? "all" : "none")); } +float StreamedSecondaryDepth(std::uint32_t draw) { + return 0.125f * static_cast(draw + 1); +} + +int StreamedSecondariesCase(AgcDriver::VulkanDevice& device, GuestBlock& block, std::span output) { + const char* parallelAtlasSwitch = std::getenv("APS5_PARALLEL_ATLAS"); + if (parallelAtlasSwitch == nullptr || parallelAtlasSwitch[0] == '\0' || parallelAtlasSwitch[0] == '0' || std::getenv("APS5_PROFILE_GPU_DRAWS") != nullptr || std::getenv("APS5_GPU_CHECKPOINTS") != nullptr || !AgcDriver::VulkanDeviceTestAccess::ContextOf(device).graphicsPipelineLibrary) { + std::puts("skipped, pooled depth-only recording needs APS5_PARALLEL_ATLAS and a graphics pipeline library"); + return VulkanTestSkipped; + } + auto* recorder = AgcDriver::Graphics::Recorder::Active(); + Require(recorder != nullptr, "the device has no active recorder"); + device.WaitIdle(); + const auto recorded = AgcDriver::Graphics::RecordingPool::RecordedBuffers(); + const auto before = recorder->StreamCounts(); + for (std::uint32_t draw = 0; draw < StreamedSecondaryDraws; ++draw) { + DrawDepth(device, reinterpret_cast(block.At(StreamedSecondaryOffset + draw * StreamedSecondaryStride)), {128, 128}, VK_FORMAT_D32_SFLOAT, StreamedSecondaryDepth(draw), 0, 0, std::nullopt, true, false); + Require(recorder->Deferred(), "pooled draw " + std::to_string(draw) + " executed its secondary command buffer outside a streamed batch"); + } + device.WaitIdle(); + const auto after = recorder->StreamCounts(); + const auto pooled = AgcDriver::Graphics::RecordingPool::RecordedBuffers() - recorded; + const auto streamed = after.deferred - before.deferred; + const auto replayed = after.replayed - before.replayed; + std::cout << "streamed secondaries: " << pooled << " pooled draws in " << streamed << " streamed batches, " << replayed << " replayed, " << after.direct - before.direct << " direct, " << after.demoted - before.demoted << " demoted\n"; + Require(pooled == StreamedSecondaryDraws, std::to_string(pooled) + " of " + std::to_string(StreamedSecondaryDraws) + " depth-only draws were recorded on the recording pool"); + Require(streamed != 0 && replayed == streamed && after.direct == before.direct && after.demoted == before.demoted && after.replayFailed == before.replayFailed, "the batches that executed the pooled secondary command buffers were not all streamed and replayed"); + const Shape shape{Format32Float, 128, 128, Type2D, 0, Swizzle64KbZX}; + for (std::uint32_t draw = 0; draw < StreamedSecondaryDraws; ++draw) { + Load(device, block.At(StreamedSecondaryOffset + draw * StreamedSecondaryStride), shape, 0, output); + Expect(output, Bits(StreamedSecondaryDepth(draw)), "streamed secondary draw " + std::to_string(draw)); + } + std::puts("streamed secondaries test passed"); + return 0; +} + int main(int argc, char** argv) { try { const std::vector arguments(argv + 1, argv + argc); @@ -847,6 +886,7 @@ int main(int argc, char** argv) { const auto device = OpenVulkanTestDevice(); if (!device) return VulkanTestSkipped; const std::span output(reinterpret_cast(block.At(OutputOffset)), Threads); + if (argc > 1 && std::string(argv[1]) == "--streamed-secondaries") return StreamedSecondariesCase(*device, block, output); const auto present = [&] { if (!evicting) return; AgcDriver::Graphics::Recorder::CountPresent(); diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/PipelineOptimizedReadback.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/PipelineOptimizedReadback.cpp index d684b6946216..49f74ba4caec 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/PipelineOptimizedReadback.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/PipelineOptimizedReadback.cpp @@ -270,7 +270,7 @@ int main(int argc, char** argv) { std::printf("pipeline readback: %s, %.*s, LTO %s%s\n", device->DeviceName().c_str(), static_cast(mode.size()), mode.data(), optimize ? "enabled" : "disabled", force ? " (explicit test override)" : " (production policy)"); trace.resolve = context.deviceProc; trace.create = context.Function("vkCreateGraphicsPipelines"); - trace.bind = reinterpret_cast(context.deviceProc(context.device, "vkCmdBindPipeline")); + trace.bind = reinterpret_cast(AgcDriver::Graphics::CommandThunk("vkCmdBindPipeline", context.deviceProc(context.device, "vkCmdBindPipeline"), context.device)); trace.draw = context.Function("vkCmdDraw"); trace.functions = context.functions != nullptr ? *context.functions : DeviceFunctions{}; trace.functions.cmdBindPipeline = BindPipeline; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/StencilNullFeedback.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/StencilNullFeedback.cpp index b706fc42dd67..36a93f679401 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/StencilNullFeedback.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/StencilNullFeedback.cpp @@ -56,7 +56,7 @@ struct BindTrace { const auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(device); functions = const_cast(context.functions); Require(functions != nullptr, "native pipeline bind table is unavailable"); - NativeBind = reinterpret_cast(context.deviceProc(context.device, "vkCmdBindPipeline")); + NativeBind = reinterpret_cast(AgcDriver::Graphics::CommandThunk("vkCmdBindPipeline", context.deviceProc(context.device, "vkCmdBindPipeline"), context.device)); functions->cmdBindPipeline = CountBind; } ~BindTrace() { functions->cmdBindPipeline = NativeBind; } diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/StencilReplay.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/StencilReplay.cpp index 4de08e7da185..11ae89c3dce3 100644 --- a/core/libs/prx/libSceAgcDriver/tests/execution/StencilReplay.cpp +++ b/core/libs/prx/libSceAgcDriver/tests/execution/StencilReplay.cpp @@ -56,9 +56,9 @@ struct BindTrace { const auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(device); functions = const_cast(context.functions); Require(functions != nullptr, "native pipeline bind table is unavailable"); - NativeBind = reinterpret_cast(context.deviceProc(context.device, "vkCmdBindPipeline")); - NativeDraw = reinterpret_cast(context.deviceProc(context.device, "vkCmdDraw")); - NativeDrawIndexed = reinterpret_cast(context.deviceProc(context.device, "vkCmdDrawIndexed")); + NativeBind = reinterpret_cast(AgcDriver::Graphics::CommandThunk("vkCmdBindPipeline", context.deviceProc(context.device, "vkCmdBindPipeline"), context.device)); + NativeDraw = reinterpret_cast(AgcDriver::Graphics::CommandThunk("vkCmdDraw", context.deviceProc(context.device, "vkCmdDraw"), context.device)); + NativeDrawIndexed = reinterpret_cast(AgcDriver::Graphics::CommandThunk("vkCmdDrawIndexed", context.deviceProc(context.device, "vkCmdDrawIndexed"), context.device)); functions->cmdBindPipeline = CountBind; functions->cmdDraw = CountDraw; functions->cmdDrawIndexed = CountDrawIndexed; diff --git a/core/libs/prx/libSceAgcDriver/tests/execution/StreamedMeshArguments.cpp b/core/libs/prx/libSceAgcDriver/tests/execution/StreamedMeshArguments.cpp new file mode 100644 index 000000000000..7ce1a784af5f --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/execution/StreamedMeshArguments.cpp @@ -0,0 +1,57 @@ +#include "prx/libSceAgcDriver/Execution/include/GuestMemory.hpp" +#include "prx/libSceAgcDriver/Execution/include/VulkanDevice.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Recorder.hpp" +#include "prx/libSceAgcDriver/Graphics/include/Resources.hpp" +#include "VulkanTestDevice.hpp" +#include +#include +#include +#include + +namespace AgcDriver { + +struct VulkanDeviceTestAccess { + static Graphics::Context ContextOf(const VulkanDevice& device) { return device.graphicsContext(); } +}; + +} + +int main() { + try { + const auto device = OpenVulkanTestDevice(); + if (!device) return VulkanTestSkipped; + using namespace AgcDriver::Graphics; + const auto context = AgcDriver::VulkanDeviceTestAccess::ContextOf(*device); + auto* recorder = Recorder::Active(); + Require(recorder != nullptr, "the device has no active recorder"); + Require(context.functions != nullptr && context.functions->cmdPipelineBarrier != nullptr, "the device table is unavailable"); + std::lock_guard gpu(AgcDriver::GuestMemory::GpuMutex()); + constexpr auto usage = VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + Buffer record(context, 4096, usage); + Buffer arguments(context, 4096, usage); + const auto commands = recorder->Commands(); + if (!recorder->Deferred()) { + std::printf("skipped, the open batch is direct\n"); + return VulkanTestSkipped; + } + const auto before = recorder->StreamOps(); + const std::array rules{}; + bool recorded = false; + const VkMemoryBarrier barrier{VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT}; + context.functions->cmdPipelineBarrier(commands, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, 0, 1, &barrier, 0, nullptr, 0, nullptr); + recorded = recorder->RecordMeshArguments(commands, record.DeviceAddress(), arguments.DeviceAddress(), rules); + const auto after = recorder->StreamOps(); + if (!recorded) { + std::printf("skipped, the mesh argument kernel is unavailable\n"); + return VulkanTestSkipped; + } + const auto queued = after - before; + Require(queued == 6, "the mesh argument kernel bypassed the batch's stream: " + std::to_string(queued) + " commands streamed, expected the leading barrier plus the kernel's barrier, bind, push constants, dispatch and barrier"); + recorder->Sync(); + std::cout << "streamed mesh arguments test passed\n"; + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/core/libs/prx/libSceAgcDriver/tests/test_command_resolver_sites.py b/core/libs/prx/libSceAgcDriver/tests/test_command_resolver_sites.py new file mode 100644 index 000000000000..0ae4cb595e6c --- /dev/null +++ b/core/libs/prx/libSceAgcDriver/tests/test_command_resolver_sites.py @@ -0,0 +1,175 @@ +import re +import sys +import unittest +from pathlib import Path + +DRIVER = Path(__file__).resolve().parents[1] +COMMAND_LIST = DRIVER / "Graphics/include/CommandList.hpp" + +LITERAL = re.compile(r'"vk(Cmd\w+)"') +NAMED_RESOLVE = re.compile(r'(?:deviceProc|vkGetDeviceProcAddr|GetDeviceProcAddr)\s*\([^;]*?"vkCmd\w+"') +GENERIC_RESOLVE = re.compile(r'\b(?:deviceProc|resolve)\s*\(\s*\w+\s*,\s*(?![\s"])[^;)]*\)') +THUNKED = re.compile(r'CommandThunk\s*\(') + +RESOLVERS = { + "Graphics/include/Context.hpp": "Context::lookup, which returns a thunk for every listed command", + "Execution/src/VulkanDevice.cpp": "VulkanDevice's DeviceFunction, which returns a thunk for every listed command", + "Graphics/src/CommandThunks.cpp": "ResolveCommandFunctions, the real entry points that only replay and demotion call", +} + +TYPED_SCOPES = { + "Graphics/src/Draw.cpp": re.compile(r'^\w[^;{]*\brecordDrawCommandsImpl\('), + "Graphics/src/Recorder.cpp": re.compile(r'^\w[^;{]*\bCommandState::(?:Set\w+|BindPipeline)\('), +} +TYPED_EXEMPT = { + "CmdDrawIndirectCountKHR": "no DeviceFunctions entry to fall back on", + "CmdDrawIndexedIndirectCountKHR": "no DeviceFunctions entry to fall back on", + "CmdDrawMeshTasksEXT": "no DeviceFunctions entry to fall back on", + "CmdDrawMeshTasksIndirectEXT": "no DeviceFunctions entry to fall back on", +} +UNTYPED_COMMAND = re.compile(r'\b(?:Resolved|tracked)\s*\(\s*&DeviceFunctions::(cmd\w+)|\bFunction') +FOR_BATCH = re.compile(r'\bForBatch\s*\(\s*([^,]+?)\s*,') + + +def bodies(text, header): + lines = text.splitlines() + for start, line in enumerate(lines): + if not header.search(line) or line.rstrip().endswith(";"): + continue + depth = 0 + opened = False + for number in range(start, len(lines)): + depth += lines[number].count("{") - lines[number].count("}") + opened = opened or "{" in lines[number] + if opened and depth <= 0: + yield start + 1, lines[start:number + 1] + break + + +def untyped_sites(text, header): + found = [] + for first, body in bodies(text, header): + for offset, line in enumerate(body): + for member, command in UNTYPED_COMMAND.findall(line): + name = command or "C" + member[1:] + if name not in TYPED_EXEMPT: + found.append(first + offset) + for table in FOR_BATCH.findall(line): + if table not in ("functions", "context.BatchFor(functions)"): + found.append(first + offset) + return found + + +def listed_commands(text): + return set(re.findall(r'X\((Cmd\w+)\)', text)) + + +def unlisted(text, listed): + return sorted({name for name in LITERAL.findall(text) if name not in listed}) + + +def unthunked_named(text): + return [number for number, line in enumerate(text.splitlines(), 1) if NAMED_RESOLVE.search(line) and not THUNKED.search(line)] + + +def generic_sites(text): + return [number for number, line in enumerate(text.splitlines(), 1) if GENERIC_RESOLVE.search(line)] + + +def sources(root): + return sorted(list((root / "Graphics").rglob("*.[ch]pp")) + list((root / "Execution").rglob("*.[ch]pp"))) + + +def problems(root, listed, resolvers, typed=None): + typed = typed or {} + messages = [] + for path in sources(root): + name = path.relative_to(root).as_posix() + text = path.read_text(encoding="utf-8", errors="replace") + missing = unlisted(text, listed) + if missing: + messages.append(f"{name}: {', '.join(missing)} not in APS5_COMMANDS: a stream handle passed to it would reach the driver; add it to Graphics/include/CommandList.hpp") + raw = unthunked_named(text) + if raw: + messages.append(f"{name}: a vkCmd entry point resolved without CommandThunk (lines {', '.join(map(str, raw))}): resolve it through Context::Function or wrap it in CommandThunk") + generic = generic_sites(text) + if generic and name not in resolvers: + messages.append(f"{name}: resolves device functions by a variable name (lines {', '.join(map(str, generic))}): use Context::Function, or wrap vkCmd names in CommandThunk and add the file to RESOLVERS") + for name, header in sorted(typed.items()): + path = root / name + if not path.exists(): + messages.append(f"{name}: listed in TYPED_SCOPES but missing") + continue + text = path.read_text(encoding="utf-8", errors="replace") + if not any(True for _ in bodies(text, header)): + messages.append(f"{name}: no function matches its TYPED_SCOPES header") + untyped = untyped_sites(text, header) + if untyped: + messages.append(f"{name}: a per-draw command resolved without the batch's command table (lines {', '.join(map(str, untyped))}): record it through Context::ForBatch(functions, ...) or Context::ForBatch(context.BatchFor(functions), ...)") + for name in sorted(resolvers): + path = root / name + if not path.exists(): + messages.append(f"{name}: listed in RESOLVERS but missing") + elif not THUNKED.search(path.read_text(encoding="utf-8", errors="replace")): + messages.append(f"{name}: a resolver that never calls CommandThunk") + return messages + + +class RulesTest(unittest.TestCase): + def test_a_literal_outside_the_list_is_reported(self): + self.assertEqual(unlisted('f("vkCmdDraw"); f("vkCmdTraceRaysKHR");', {"CmdDraw"}), ["CmdTraceRaysKHR"]) + + def test_a_named_resolve_needs_a_thunk(self): + text = "\n".join([ + 'auto a = reinterpret_cast(context.deviceProc(context.device, "vkCmdDraw"));', + 'auto b = reinterpret_cast(CommandThunk("vkCmdDraw", context.deviceProc(context.device, "vkCmdDraw")));', + 'auto c = reinterpret_cast(context.deviceProc(context.device, "vkDestroyBuffer"));', + ]) + self.assertEqual(unthunked_named(text), [1]) + + def test_a_generic_resolve_is_found(self): + self.assertEqual(generic_sites("const auto function = deviceProc(device, name);\nint x = 0;"), [1]) + self.assertEqual(generic_sites('auto f = deviceProc(device, "vkDestroyFence");'), []) + + def test_a_tree_with_a_raw_resolver_fails(self): + import tempfile + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "Graphics").mkdir() + (root / "Graphics/Raw.cpp").write_text('auto f = deviceProc(device, name);\nauto g = context.deviceProc(context.device, "vkCmdDraw");\nh("vkCmdTraceRaysKHR");\n') + messages = problems(root, {"CmdDraw"}, {}) + self.assertEqual(len(messages), 3, messages) + + def test_a_per_draw_command_outside_the_batch_table_is_reported(self): + header = re.compile(r'^\w[^;{]*\bCommandState::Set\w+\(') + text = "\n".join([ + "void CommandState::SetA(const Context& context) {", + ' context.ForBatch(functions, &CommandFunctions::CmdSetViewport, &DeviceFunctions::cmdSetViewport, "vkCmdSetViewport")(commands, 0, 1, &v);', + ' context.ForBatch(context.BatchFor(functions), &CommandFunctions::CmdSetScissor, &DeviceFunctions::cmdSetScissor, "vkCmdSetScissor")(commands, 0, 1, &s);', + "}", + "void CommandState::SetB(const Context& context) {", + ' context.Resolved(&DeviceFunctions::cmdSetScissor, "vkCmdSetScissor")(commands, 0, 1, &s);', + ' context.Function("vkCmdSetDepthBias")(commands, 0, 0, 0);', + ' context.ForBatch(nullptr, &CommandFunctions::CmdSetViewport, &DeviceFunctions::cmdSetViewport, "vkCmdSetViewport")(commands, 0, 1, &v);', + ' context.Function("vkCmdDrawMeshTasksEXT")(commands, 1, 1, 1);', + ' context.ForBatch(context.BatchFor(nullptr), &CommandFunctions::CmdSetViewport, &DeviceFunctions::cmdSetViewport, "vkCmdSetViewport")(commands, 0, 1, &v);', + "}", + "void Other(const Context& context) {", + ' context.Resolved(&DeviceFunctions::cmdSetScissor, "vkCmdSetScissor")(commands, 0, 1, &s);', + "}", + ]) + self.assertEqual(untyped_sites(text, header), [6, 7, 8, 10]) + + def test_the_list_parses(self): + self.assertIn("CmdDraw", listed_commands(COMMAND_LIST.read_text(encoding="utf-8"))) + + +class DriverTreeTest(unittest.TestCase): + def test_every_command_resolves_through_a_thunk(self): + listed = listed_commands(COMMAND_LIST.read_text(encoding="utf-8")) + messages = problems(DRIVER, listed, RESOLVERS, TYPED_SCOPES) + self.assertEqual(messages, [], "\n".join(messages)) + + +if __name__ == "__main__": + unittest.main(argv=sys.argv[:1]) diff --git a/docs/dev/ARCHITECTURE.md b/docs/dev/ARCHITECTURE.md index 106e726ce158..143a05318e48 100644 --- a/docs/dev/ARCHITECTURE.md +++ b/docs/dev/ARCHITECTURE.md @@ -146,6 +146,7 @@ flowchart LR - `Driver::RegisterShader` splits shader preparation in two. `PlanRegistered` runs on the registering guest thread: it validates the registers and entry point, decodes the code and builds the recompile request, so invalid registrations still fail there. The RDNA to IR translation and resource plan (`PrepareShader`) run on a background pool of `hardware_concurrency() / 2` threads (at least 2, 64 MiB stacks), which `Driver::stop` joins when it closes the pool. - A thread that needs the GPU mutex, the committer's next item or the end of the committer's queue spins before it blocks (`HandoffSpin.hpp`): `GpuMutexType::lock` retries `try_lock` for the window, the committer polls its item count, and `DrawPipeline::Drain` polls it for twice the window, so a hand-off that completes within the window costs no kernel wake-up. The window is 150 us when the process may run on more than 8 logical processors (its affinity mask, via `CpuTopology`) and 0 otherwise, where the spinning threads would compete with the holder; `APS5_HANDOFF_SPIN_US=` sets it (0 turns it off, at most 10000). Ordering and the lock's semantics are unchanged. - Queue 0's packet worker decodes, captures and prepares a draw and hands its recording (`Graphics::Draw` under the GPU lock) to a committer thread in [`DrawPipeline.cpp`](../../core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawPipeline.cpp), so the next packet is decoded while the previous draw is recorded. Each queued item carries the guest ranges it will write (`DrawWriteRanges`: written buffers and storage images, color targets with their DCC and CMASK, depth and stencil). A later packet that reads or writes one of those ranges, or that the pipeline can't order, drains it first; labels, submission ends, buffer fills and DMA packets are queued as items instead. With `APS5_PIPELINE_DISPATCH=1` (off by default), a `DISPATCH_DIRECT` whose dispatch-cache entry hits with a recipe is queued as an item too, carrying the dispatch's written buffers and storage images (`DispatchWriteRanges`); the capture and the cache lookup stay on the worker and the recipe is recorded on the committer. A dispatch still drains when its lookup misses, when what it reads overlaps a write still pending, when the hit is verified against data or when its writes cannot be ranged (bindless access, GDS, fault buffer). An indirect draw resolved on the CPU (its records read by the worker) drains only when its records or its count overlap a queued write; the records it draws inline drain first, and its last drawn record is queued like a direct draw (`APS5_NO_PIPELINED_INDIRECT=1` drains at every indirect draw). An exception thrown by a commit is rethrown on the worker at its next enqueue or drain, as an inline draw error would be. On by default; `APS5_PIPELINED_DRAWS=0` records every draw inline, and `APS5_EXACT_DRAW_WRITES=0` widens the color and depth ranges to estimates. +- The recorder records a batch into a command stream instead of a command buffer when the device table is resolved ([`Recorder.cpp`](../../core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp), [`CommandStream.cpp`](../../core/libs/prx/libSceAgcDriver/Graphics/src/CommandStream.cpp)). The batch hands out a tagged handle; every `vkCmd*` resolution (the device table, `Context::Function`, `deviceProc`) returns the thunk for that name from the one list in [`CommandList.hpp`](../../core/libs/prx/libSceAgcDriver/Graphics/include/CommandList.hpp), and a thunk given a tagged handle copies the call and its arrays into the stream ([`CommandThunks.cpp`](../../core/libs/prx/libSceAgcDriver/Graphics/src/CommandThunks.cpp)). Every listed command has a streamer that copies its arrays, including push descriptor writes by descriptor type. A call carrying a `pNext` chain (which is also how inline uniform blocks and acceleration structures arrive) demotes the batch, and so does a command that would take its stream past its byte cap (the budget's outstanding bytes divided by its outstanding batches), so a stream is never charged more than its cap: the stream replays its prefix in order into a real command buffer, and that command and later calls go there directly. A command with more distinct driver entry points than its thunk slots gets a thunk that finds the entry point by the command buffer's loader dispatch key, which equals its device's. `Submit` seals the stream and replays it into a command buffer before submitting ([`SealedBatch.cpp`](../../core/libs/prx/libSceAgcDriver/Graphics/src/SealedBatch.cpp)); a replay failure is latched and every later `Submit` throws it without submitting. A draw that throws while recording poisons the open stream, and `Submit` throws instead of submitting part of a draw. Admission (`WorkBudget::TryOpen`) records a batch directly when too many streams are encoding or outstanding. `APS5_RECORD_INLINE=1` or `APS5_DIRECT_BATCHES=1` records every batch directly; `APS5_ENCODE_THREAD=1` replays on one worker thread instead of the submitting thread. - A dispatch's resource build runs stage A (binding plan, buffers, descriptor set) without the GPU lock and stage B (image lookups) under it. Between them `VulkanDevice::presync` waits, still without the lock, for recorded work that writes a surface stage B would read on the CPU and for recorded work that writes the DCC keys of an image the dispatch binds (`ShaderResources::PresyncSurfaces`), so the locked `WaitForKeyWriters` finds nothing pending to synchronize with. A key range is waited for only when recorded work writes it, the key-store memo does not give its value (`DccKeyWritersPending`, without the mutex) and the pending stores do not give it either (`DccKeyWriterNeedsSync`, under the mutex, the same test `WaitForKeyWriters` makes before it synchronizes). Stage A's own key scan runs before that wait, and stage B compares it with the keys it reads under the lock as before. `APS5_NO_DCC_PRESYNC=1` leaves the key ranges out; `APS5_NO_PRESYNC=1` disables the whole pre-sync. - `APS5_DRAW_PIPELINE` (any value turns it on, even `0`; off by default, meant with `APS5_PIPELINED_DRAWS=32 APS5_PIPELINE_DISPATCH=1`) takes more of a draw off the worker. A `DrawFinisher` thread runs the second half of a direct pipelined draw (stage materialization, the draw cache insert and the hand-off to the committer) while the worker reads the next packets; the worker drains it before the next draw's cache lookup, before packets other than register writes and draws, and before guest reads, and finishes in place a draw whose stages may write memory (`ProgramWritesMemory`) or write through the BDA page table. The committer skips the storage-image layer scans whose inputs match its last commit (`CommitTrims`), and a resource or storage image proved current keeps its proof for the rest of the collect epoch until `GuestMemory::BreakProofs` (a CPU write, a write-back, a recorded write) moves `ProofSerial`. A draw that continues the open render pass with equal color and depth targets takes the previous draw's resident images and attachment views while the collect epoch, `ProofSerial`, `StorageTexture::PendingSerial`, each image's version and storage cache entry and the depth surface serials are unchanged; `APS5_NO_PASS_ATTACHMENT_MEMO=1` looks them up anew and `APS5_VERIFY_PASS_ATTACHMENTS=1` compares a hit with the full lookup. Color metadata passes go through the pipeline with their write ranges (`PipelinedColorMetadataPassWrites`) instead of draining it. A data-only hit whose shape entry belongs to an older draw replaces that entry in place at the second sight of the same read user words. On Linux the main image's pages get a page table entry, and capture pages are pooled across threads. `APS5_VERIFY_DRAW_PIPELINE=1` runs a full check next to 1 in 64 reused proofs and prints `[epoch-proofs]` counts. - The shader registry maps a code address to every header registered for that code, in registration order. Static, graphics and rectangle ABI resolution pick the header at the bound address (or one equal to it, `SameHeader`, which also takes a hull header fused by `sceAgcFuseShaderHalves` (type 3) as the registered back half (type 7) it copies, the fused registers aside; graphics ABI resolution then uses the fused header's shader registers); draws and dispatches pick the program by the stage's binary type (`RegisteredProgram`), and a front entry matching both type 2 and type 4 throws. Within a type the last registration wins; re-registering an identical earlier header makes its snapshot current again without preparing it again, and changed code drops the older headers. diff --git a/docs/dev/ENVIRONMENT.md b/docs/dev/ENVIRONMENT.md index 4c307d836ba2..d94556adce03 100644 --- a/docs/dev/ENVIRONMENT.md +++ b/docs/dev/ENVIRONMENT.md @@ -61,6 +61,8 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_GATHER_CONST` | integer | `core/shader/recompiler/SpirvBackend/src/SpirvImageEmitter.cpp` | | integer every non-depth gather returns in all four texels instead of the sampled value | | `APS5_IMAGE_TABLE_KEY_SCAN` | integer | `core/shader/recompiler/Optimization/src/ResourceMaterializer.cpp` | 256 | number of image-table entries the key scan examines | | `APS5_IMAGE_TABLE_STRICT` | string | `core/shader/recompiler/Optimization/src/ResourceMaterializer.cpp` | | sets image-table materialization to its strict form; 0 leaves it off | +| `APS5_NO_ADAPTIVE_ENCODER` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/RuntimeSwitches.cpp` | | hands every draw's commands to the command encoder thread; unset, the encoder records a draw inline for a span of draws whenever the hand-off cost the drawing thread at least as much as the recording it moved. APS5_AB can toggle it | +| `APS5_QUIESCED_SEGMENTS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/RuntimeSwitches.cpp` | | begins and ends occlusion counting segments directly in the command buffer after waiting for the command encoder to finish what it holds; unset, a segment begun or ended while the encoder records the batch goes to the encoder in order with the draws. APS5_AB can toggle it | | `APS5_NO_ATOMIC_BARRIER` | presence | `core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvFormatConvert.cpp` | | drops the device-scope acquire/release memory barrier emitted after atomics | | `APS5_NO_ATOMIC_ZERO_SKIP` | presence | `core/shader/recompiler/SpirvBackend/src/SpirvMemory/SpirvMemoryInstructions.cpp` | | restores plain buffer atomics instead of skipping identity-operand atomics | | `APS5_NO_BUFFER_SUBSTITUTES` | presence | `core/shader/recompiler/Recompiler.cpp` | | specializes a null buffer V# with its own words instead of the fields its slot had the first time a dispatch of the same program bound it | @@ -227,11 +229,14 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_DUMP_STORAGE_GATE` | path | `core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp` | | with `APS5_DUMP_STORAGE`, waits for this path to exist and reads matching live images directly without guest writeback; at most eight addresses, 8 MiB linear storage per image; writes `storage_direct_
_.raw` with the existing pitch, height and VkFormat header and first-mip pixels | | `APS5_SCREENSHOT_TRIGGER` | string | `core/libs/prx/libSceAgcDriver/Execution/src/Screenshot.cpp` | | regular file consumed to request a PNG of the next presented frame, including with APS5_NO_PAD_INPUT; recreate it for another request; a trigger another process holds open is retried at the next frame; use a separate path per process; no filesystem polling when unset | | `APS5_TEST_DIRECT_READBACK` | presence | `core/libs/prx/libSceAgcDriver/tests/execution/LayeredVolumeDraw.cpp` | | runs the clean-volume gated live-image readback regression in the layered volume execution test | +| `APS5_DIRECT_BATCHES` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/RuntimeSwitches.cpp` | | opens every recorder batch as a command buffer recorded on the drawing thread instead of a command stream replayed at submit; APS5_AB can toggle it, unlike `APS5_RECORD_INLINE`. Without it, a stream whose replay fails is never submitted and every later submit on that recorder throws the same error | +| `APS5_NO_STREAMED_PUSH_DESCRIPTORS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/RuntimeSwitches.cpp` | | demotes a command stream to a command buffer at every `vkCmdPushDescriptorSetKHR` instead of copying its descriptor writes into the stream; APS5_AB can toggle it | | `APS5_DUMP_SUBMITS` | string | `core/libs/prx/libSceAgcDriver/Execution/src/SubmissionCapture.cpp` | | directory in which every submission is captured for replay | | `APS5_DUMP_TARGETS` | integer | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | 0 | dumps the first n renders of each non-resident color target as target_
_.raw in the working directory; a non-zero value also runs every draw synchronously, and in practice it needs APS5_NO_RESIDENT_TARGETS=1 | | `APS5_DUMP_TEXTURE` | string | `core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp` | | hex addresses or WxH extents whose sampled textures are dumped on each of their first 8 uploads as texture_
_.raw | | `APS5_BC1_RDNA2_DECODE` | string | `core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp` | 0 | `1` expands sampled BC1 UNORM textures to RGBA8 on upload using the [measured RDNA2 interpolation](https://github.com/boykopovar/AnyPS5/pull/23070). An expanded 4×4 block uses 64 image bytes instead of 8 compressed bytes. | | `APS5_EAGER_WRITEBACK` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp` | | writes back pending storage layers eagerly | +| `APS5_ENCODE_THREAD` | string | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | any value other than `0` replays each sealed recorder batch on one replay thread with its own command pool; unset, the submitting thread replays the batch itself just before it submits it | | `APS5_EXACT_DRAW_WRITES` | string | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/WrittenBuffers.cpp` | | sizes a color or depth target's draw write ranges from its own bytes and slices (the default when unset); `0` uses the slack and unknown-byte approximation instead | | `APS5_FILL_CHAIN` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp` | | seeds and doubles the fill pattern in place in the import | | `APS5_FILL_CLEAR_EXACT_ONLY` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Memory/BufferFill.cpp` | | turns a fill into a clear only when it covers the target exactly and nothing else | @@ -464,6 +469,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_NO_RECORDED_CLEAR` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp` | | waits for a storage image's fast clear in a batch of its own instead of recording it | | `APS5_NO_RECORDER_SYNC_DRAWS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | gives the draws the recorder waits for their own batch instead of recording them with the wait | | `APS5_NO_RECORD_COPIED_DRAWS` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | waits for copied-write draws at once instead of listing their write-back for later | +| `APS5_NO_RECORD_ENCODER` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/RuntimeSwitches.cpp` | | records each draw's commands on the drawing thread instead of handing them to the command encoder, leaving the encoder thread idle; APS5_AB can toggle it, unlike `APS5_RECORD_INLINE`, which also stops the thread from being created | | `APS5_NO_RECT_INDIRECT` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/IndirectDraw.cpp` | | sends an indirect rectangle-list draw down the CPU path instead of the GPU-side path | | `APS5_NO_REFRESH_GPU_ORDERED` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Texture.cpp` | | waits on the CPU for the pending writers a storage refresh flushes and compares the guest bytes, instead of re-uploading the layers from the import behind the write-backs | | `APS5_NO_RESIDENT_LINEAR` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | drops the residency of linear color targets, so a target whose address has a host import, or whose import a draw would make, is copied in and out again | @@ -570,6 +576,7 @@ The code reads environment names through `getenv`, `IsEnvironmentSet`, `kibSetti | `APS5_PROFILE_TARGET_MEMO` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Draw.cpp` | | prints one `[target-memo]` line per 10 s summed over every thread: target memo lookups, hits and accepts, depth hits, refusals by reason (invalid, thread changed, descriptor, resident gone or evicted, depth overlap, metadata, each proof field that moved, post-depth invalidation, admission, recipe draws), memo builds and `APS5_VERIFY_TARGET_MEMO` checks; the counts are only kept while this switch or `APS5_PROFILE_DRAW` is set, so the memo hit path costs nothing without them | | `APS5_PROVEN_OVERWRITE` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/RuntimeSwitches.cpp` | | before a compute dispatch looks up a storage image the recompiler proved it stores over every texel of its level (never reading it), and the grid, the user data and the other bindings complete that proof, drops other images' pending results inside the level's covered bytes instead of writing them back; also counts a pending image as over a range only where one of its pending units lies; APS5_AB can toggle it | | `APS5_READONLY_DEPTH_BOUNDS_COMPARE` | string | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Draw/DrawDecode.cpp` | 0 | `1` enables a read-only GREATER_OR_EQUAL comparison at viewport depth 1 for eligible single-sample D32S8 draws with native depth bounds; read once per process; unset or `0` keeps the normal path | +| `APS5_RECORD_INLINE` | string | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | any value other than `0` opens every recorder batch as a command buffer recorded on the drawing thread; unset, a batch records into a command stream that is replayed into a command buffer when it is submitted | | `APS5_REAP_EACH_PACKET` | presence | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Synchronization/DeferredLabels.cpp` | | reaps deferred labels after every packet | | `APS5_REGISTRATION_PREPARE_COMMIT_GB` | number | `core/libs/prx/libSceAgcDriver/Execution/src/Driver/Shaders/ShaderRegistry.cpp` | half of physical RAM | stops preparing newly registered shaders ahead of use when process-private memory reaches this GiB budget; `0` disables registration-time preparation | | `APS5_RELEASE_ON_UNLOCK` | presence | `core/libs/prx/libSceAgcDriver/Graphics/src/Recorder.cpp` | | destroys deferred batches on the unlocking thread instead of a release thread | diff --git a/docs/dev/debt/libSceAgcDriver.md b/docs/dev/debt/libSceAgcDriver.md index ace9efa050ec..539eb4f7e4f0 100644 --- a/docs/dev/debt/libSceAgcDriver.md +++ b/docs/dev/debt/libSceAgcDriver.md @@ -492,6 +492,7 @@ Eligible single-sample draws retain native finite bounds inside [0, 1] and use a - [Resource epoch lifetime invalidation](../../../core/libs/prx/libSceAgcDriver/Graphics/src/ShaderResources.cpp) remains outside the attachment memo: import retirement advances the import registry epoch without breaking the resource epoch proof, and sampled-cache release can leave that proof valid before revalidation reaches released-image and depth-copy refresh checks. Close by routing retirement, replacement, release and source-depth content changes through one resource-proof invalidation contract before publishing each transition; cover ordinary retirement, budget release, delayed producers and writes to already-pending units with negative controls against the epoch early return. Audit all transition sites and compare invalidation fan-out rather than adding unconditional resource walks to each draw. - [Stale depth planes over reused guest memory](../../../core/libs/prx/libSceAgcDriver/Graphics/src/DepthSurface.cpp) (libSceAgcDriver): a depth surface outlives the guest memory it mirrors, so a flush over a later allocation stores pending results into it; a pending fast clear used to skip the guest-write check and write zero there. A flush now drops a unit whose recorded allocation (`backingSerial`) changed, and a storing sync drops the units the guest wrote and forgets the clear. Not covered: reuse inside one unchanged registration with no write since the last sync, and the stencil plane, which compares bytes with its last mark. Closes when: surfaces are retired on allocation changes (an unmap hook that keeps the `surfacesMutex`/`GuestAllocations` lock order) instead of at flush time. PPSA27616 reached this through a cubemap of 128x128 depth faces whose memory its heap had taken back. - [Label access width](../../../core/libs/prx/libSceAgcDriver/Execution/include/Pm4.hpp) (libSceAgcDriver) - a PM4 wait reads its label with one acquire `atomic_ref` load at the wait's width: 4 bytes, or 8 bytes at an 8-byte-aligned address (`WAIT_REG_MEM_64` masks the address to 8 bytes; a zero high mask makes it a 4-byte wait). The driver stores a label at the width of the packet that writes it, and `AgcDriverStoreGuestLabel_nid_postfix` stores 8 bytes. A 4-byte wait on half of a label stored as 8 bytes, or an 8-byte wait on a label stored as two 4-byte halves, is an overlapping atomic access of another size, which C++ does not order: x86-64 and arm64 see each aligned access whole, but the wait's acquire does not formally pair with that release, and ThreadSanitizer does not report it. Closes when: each label is written and polled at one width, or a wait that overlaps a wider or narrower store reads it at the store's width. +- [Demoted and latched command streams](../../../core/libs/prx/libSceAgcDriver/Graphics/src/CommandThunks.cpp) (libSceAgcDriver) - the thunks copy plain arguments and the arrays of the commands the recorder uses; a `pNext` chain, `vkCmdExecuteCommands`, `vkCmdPushDescriptorSetKHR`, `vkCmdSetDepthBias2EXT` and `vkCmdSetCheckpointNV` demote the batch to a command buffer, counted by command and `sType` in the profile line. A replay failure latches: the batch is not submitted and every later `Submit` on that recorder throws the stored error, so one failed replay ends the device's graphics work. Replay runs on the submitting thread unless `APS5_ENCODE_THREAD` is set, so recording into a stream saves no time until submission moves off the guest thread. ### Opt-in draw paths diff --git a/tools/tests/test_trace_digest.py b/tools/tests/test_trace_digest.py index 371376478226..7560a24ab297 100644 --- a/tools/tests/test_trace_digest.py +++ b/tools/tests/test_trace_digest.py @@ -572,6 +572,37 @@ def test_owned_draw_interval_counts_are_preserved(self): with self.assertRaises(ValueError): trace_digest.validate_interval(first) + def test_encoder_interval_counts_are_preserved(self): + first = interval_line(0.0, 30.0, 20.0, 5.0) + second = interval_line(30.0, 60.0, 20.0, 5.0) + first["encoder"] = {"posts": 3100, "commands": 84000, "waits": 23, "wait_ms_per_frame": 0.25} + for line in (first, second): + trace_digest.validate_interval(line) + result = trace_digest.digest_intervals([first, second]) + self.assertEqual(result["intervals"][0]["encoder"], first["encoder"]) + text = trace_digest.markdown_intervals(result) + self.assertIn("| 1 | 3100 | 84000 | 23 | 0.25 |", text) + self.assertIn("| 2 | - | - | - | - |", text) + self.assertNotIn("encoder posts", trace_digest.markdown_intervals(trace_digest.digest_intervals([second]))) + first["encoder"] = {"waits": -1} + with self.assertRaises(ValueError): + trace_digest.validate_interval(first) + + def test_encoder_waits_without_posts_are_shown(self): + waited = interval_line(0.0, 30.0, 20.0, 5.0) + idle = interval_line(30.0, 60.0, 20.0, 5.0) + older = interval_line(60.0, 90.0, 20.0, 5.0) + waited["encoder"] = {"posts": 0, "commands": 0, "waits": 7, "wait_ms_per_frame": 0.5} + idle["encoder"] = {"posts": 0, "commands": 0, "waits": 0, "wait_ms_per_frame": 0.0} + for line in (waited, idle, older): + trace_digest.validate_interval(line) + text = trace_digest.markdown_intervals(trace_digest.digest_intervals([waited, idle, older])) + self.assertIn("encoder posts", text) + self.assertIn("| 1 | 0 | 0 | 7 | 0.50 |", text) + self.assertIn("| 2 | 0 | 0 | 0 | 0.00 |", text) + self.assertIn("| 3 | - | - | - | - |", text) + self.assertNotIn("encoder posts", trace_digest.markdown_intervals(trace_digest.digest_intervals([idle, older]))) + def test_graphics_track_interval_counts_are_preserved(self): first = interval_line(0.0, 30.0, 20.0, 5.0) second = interval_line(30.0, 60.0, 20.0, 5.0) diff --git a/tools/trace_digest.py b/tools/trace_digest.py index d80dd8e6cbd2..d409a15b45ad 100644 --- a/tools/trace_digest.py +++ b/tools/trace_digest.py @@ -567,6 +567,14 @@ def validate_interval(record): counts = record.get("owned_draw_counts", {}) if not isinstance(counts, dict) or any(not isinstance(name, str) or type(value) is not int or value < 0 for name, value in counts.items()): raise ValueError("owned_draw_counts must map names to non-negative integers") + encoder = record.get("encoder", {}) + if not isinstance(encoder, dict): + raise ValueError("encoder must be an object") + for name in ("posts", "commands", "waits"): + if name in encoder and (type(encoder[name]) is not int or encoder[name] < 0): + raise ValueError(f"encoder.{name} must be a non-negative integer") + if "wait_ms_per_frame" in encoder: + interval_number(encoder["wait_ms_per_frame"], "encoder.wait_ms_per_frame") graphics = record.get("graphics_track", {}) if not isinstance(graphics, dict) or any(not isinstance(name, str) or type(value) is not int or value < 0 for name, value in graphics.items()): raise ValueError("graphics_track must map names to non-negative integers") @@ -603,7 +611,7 @@ def digest_intervals(lines): "frame_ms": line["frame_ms"], "gpu_busy_ms_per_present": line["gpu_busy_ms_per_present"], "busiest_worker": {"thread": busiest[0], "pct": busiest[1]} if busiest else None, "top_phase": {"name": largest[0], "ms_per_frame": largest[1]} if largest else None, - "trace_dropped": line.get("trace_dropped", False), "owned_draw_counts": line.get("owned_draw_counts"), + "trace_dropped": line.get("trace_dropped", False), "owned_draw_counts": line.get("owned_draw_counts"), "encoder": line.get("encoder"), "graphics_track": line.get("graphics_track")}) first = lines[0] if lines else {} keys = INTERVAL_IDENTITY_KEYS @@ -633,6 +641,14 @@ def markdown_intervals(result): lines += ["", "| # | " + " | ".join(table_cell(name) for name in count_names) + " |", "|---|" + "---|" * len(count_names)] for index, row in enumerate(rows, 1): lines.append(f"| {index} | " + " | ".join(str(row["owned_draw_counts"].get(name, 0)) if row["owned_draw_counts"] is not None else "-" for name in count_names) + " |") + if any(row["encoder"] and any(row["encoder"].get(name) for name in ("posts", "commands", "waits", "wait_ms_per_frame")) for row in rows): + lines += ["", "| # | encoder posts | commands | waits | wait ms/frame |", "|---|---|---|---|---|"] + for index, row in enumerate(rows, 1): + encoder = row["encoder"] + if encoder is None: + lines.append(f"| {index} | - | - | - | - |") + continue + lines.append(f"| {index} | {encoder.get('posts', 0)} | {encoder.get('commands', 0)} | {encoder.get('waits', 0)} | {encoder.get('wait_ms_per_frame', 0.0):.2f} |") track = [row["graphics_track"] or {} for row in rows] if any(track): lines += ["", "| # | passes | continued | closed | top close reason | barriers | merged | copies | copy MiB |",