core, common/vulkan: lazy-fault non-batch PSOs
Symmetry pass for the Vulkan backend matching the D3D12 fix.
# What changed
Three threads now share the lazy-fault PSO matrix without
serialising on a single compile mutex:
* common/vulkan/shader_cache: ShaderCache is now thread-safe.
Two internal mutexes:
- m_shader_cache_mutex covers the SPIR-V index
(unordered_map), the blob file, and the index file. NOT
held across ShaderCompiler::CompileShader, so two threads
compiling different shaders run truly in parallel. Two
threads compiling the SAME shader both run glslang; the
double-check under the lock picks whichever publishes
first and the loser's SPIR-V is discarded.
- m_pipeline_cache_mutex serialises the VkPipelineCache.
Per Vulkan 1.0 spec, the pipelineCache parameter to
vkCreateGraphicsPipelines is in the host-synchronised
parameter list - the application must guarantee no
concurrent use of the same VkPipelineCache. Exposed via
PipelineCacheMutex() for callers that need to honour the
contract.
* core/gpu_hw_vulkan: non-batch pipelines (VRAM fill / copy /
write / update depth / readback, display, downsample) and
their shared fullscreen-quad / UV-quad vertex shaders are now
lazy-fault helpers, same shape as the D3D12 backend's
GetVRAMFillPipeline / GetDisplayPipeline / etc. Each helper
runs glslang lock-free, takes PipelineCacheMutex briefly
around vkCreateGraphicsPipelines, and writes the slot.
Twelve sites that bound the raw member pipelines via
vkCmdBindPipeline now go through the helpers.
* core/gpu_hw_vulkan: the batch helpers (GetBatchFragmentShader,
GetBatchPipeline) no longer hold m_batch_shader_mutex across
the slow operations. Each runs glslang + vkCreateShaderModule
lock-free, takes PipelineCacheMutex around the
vkCreateGraphicsPipelines call, then takes m_batch_shader_mutex
BRIEFLY to publish under a double-check - the mutex is now a
publish-step lock only, scoped to a slot.store + race-loser
vkDestroy*. Window measured in microseconds instead of the
previous hundreds of milliseconds.
# Why this matters (Vulkan-specific reasoning)
In the pre-fix design, m_batch_shader_mutex covered the entire
compile-and-publish sequence, including the glslang -> SPIR-V
step. After a UpdateSettings change (e.g. texture filter,
resolution scale) the precompile worker would hold the mutex
across each ~150-300 ms glslang compile of the heavier shaders,
and every concurrent main-thread DrawBatchVertices stalled
behind it for the full duration. The runloop never made forward
progress until the worker finished the entire 2160-entry batch
matrix - same user-visible multi-second hang the D3D12 backend
had.
Unlike D3D12, Vulkan 1.0 cannot drop the lock entirely:
vkCreateGraphicsPipelines requires external sync on the
pipelineCache parameter (D3D12's CreateGraphicsPipelineState
is thread-safe by Microsoft's documentation, no equivalent
guarantee in Vulkan 1.0). The
VK_PIPELINE_CACHE_CREATE_EXTERNALLY_SYNCHRONIZED_BIT flag from
Vulkan 1.3 would let us elide this, but SwanStation targets
VK_API_VERSION_1_0, so the lock around vkCreateGraphicsPipelines
is mandatory.
The win is still substantial because the EXPENSIVE step -
glslang -> SPIR-V translation, which has the D3DCompile-style
optimiser cost characteristic - now runs lock-free across
threads. vkCreateGraphicsPipelines itself is mostly the driver
enqueueing SPIR-V -> GPU-ISA work onto its own background
threads; the caller-thread time inside that call is short. So
PipelineCacheMutex is held for tens of milliseconds per
compile, not hundreds.
# Lazy main-thread pre-fill (mandatory)
Same pattern as D3D12: in Lazy mode, after the non-batch
upfront block (which is now empty - all non-batch PSOs are
lazy too), the main thread pre-fills every non-batch helper
before spawning the worker. Without this, the worker could
hold PipelineCacheMutex through the batch matrix walk and the
runloop's first FillVRAM / UpdateDisplay would starve on
non-FIFO Windows std::mutex.
# Behaviour summary (same shape as D3D12 commit)
* Disabled: CompilePipelines builds only the two batch vertex
shaders. All other PSOs faulted in on first draw.
~150 KB shader-cache + ~150 KB pipeline-cache
footprint after a session.
* Lazy: CompilePipelines builds the two batch vertex
shaders + all non-batch PSOs via the main-thread
pre-fill, then spawns the worker to walk the
batch matrix in the background. Gameplay starts
instantly; worker fills slots opportunistically.
~5 MB cache footprint when worker finishes.
* Enabled: CompilePipelines builds the two batch vertex
shaders + every batch shader-module + every PSO
upfront via the same helpers (so the progress bar
ticks per pipeline). Original ~35 s upfront pause.
~5 MB cache footprint immediately.
# Files touched
* src/common/vulkan/shader_cache.h: declare
m_shader_cache_mutex, m_pipeline_cache_mutex, add
PipelineCacheMutex() accessor.
* src/common/vulkan/shader_cache.cpp: scope-narrow
m_shader_cache_mutex around index + file I/O in
GetShaderSPV; add the double-check + publish pattern to
CompileAndAddShaderSPV.
* src/core/gpu_hw_vulkan.h: declare 13 lazy helpers, two
member shader-module slots for the shared
fullscreen-quad / UV-quad vertex shaders.
* src/core/gpu_hw_vulkan.cpp: implement the helpers, gate the
upfront non-batch block on precompile_sync, add the
main-thread pre-fill for Lazy, swap 12 draw-path bindings
onto the helpers, update DestroyPipelines to tear down the
member shaders.
The 25 retro_* libretro exports are preserved. .so size is
unchanged versus master.
This commit is contained in:
parent
75e826954f
commit
65d02fd1cc
4 changed files with 896 additions and 410 deletions
|
|
@ -425,19 +425,35 @@ std::optional<ShaderCompiler::SPIRVCodeVector> ShaderCache::GetShaderSPV(ShaderC
|
|||
std::string_view shader_code)
|
||||
{
|
||||
const auto key = GetCacheKey(type, shader_code);
|
||||
auto iter = m_index.find(key);
|
||||
if (iter == m_index.end())
|
||||
return CompileAndAddShaderSPV(key, shader_code);
|
||||
|
||||
SPIRVCodeVector spv(iter->second.blob_size);
|
||||
if (rfseek(m_blob_file, iter->second.file_offset, SEEK_SET) != 0 ||
|
||||
rfread(spv.data(), sizeof(SPIRVCodeType), iter->second.blob_size, m_blob_file) != iter->second.blob_size)
|
||||
// Fast path: look up in the index under the lock and read the
|
||||
// existing SPIR-V if present. The lock window covers the
|
||||
// unordered_map lookup AND the rfseek+rfread on the blob file
|
||||
// since file position is shared mutable state.
|
||||
{
|
||||
Log_ErrorPrintf("Read blob from file failed, recompiling");
|
||||
return ShaderCompiler::CompileShader(type, shader_code, m_debug);
|
||||
std::lock_guard<std::mutex> lock(m_shader_cache_mutex);
|
||||
auto iter = m_index.find(key);
|
||||
if (iter != m_index.end())
|
||||
{
|
||||
SPIRVCodeVector spv(iter->second.blob_size);
|
||||
if (rfseek(m_blob_file, iter->second.file_offset, SEEK_SET) != 0 ||
|
||||
rfread(spv.data(), sizeof(SPIRVCodeType), iter->second.blob_size, m_blob_file) != iter->second.blob_size)
|
||||
{
|
||||
Log_ErrorPrintf("Read blob from file failed, recompiling");
|
||||
// Fall through to compile path below (outside the lock).
|
||||
}
|
||||
else
|
||||
{
|
||||
return spv;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return spv;
|
||||
// Slow path: compile WITHOUT the cache mutex held, so other threads
|
||||
// can use the cache (or fault their own different shaders) in
|
||||
// parallel. Concurrent compiles of the same shader are tolerated -
|
||||
// see the publish step in CompileAndAddShaderSPV.
|
||||
return CompileAndAddShaderSPV(key, shader_code);
|
||||
}
|
||||
|
||||
VkShaderModule ShaderCache::GetShaderModule(ShaderCompiler::Type type, std::string_view shader_code)
|
||||
|
|
@ -473,10 +489,38 @@ VkShaderModule ShaderCache::GetFragmentShader(std::string_view shader_code)
|
|||
std::optional<ShaderCompiler::SPIRVCodeVector> ShaderCache::CompileAndAddShaderSPV(const CacheIndexKey& key,
|
||||
std::string_view shader_code)
|
||||
{
|
||||
// SLOW: glslang -> SPIR-V runs WITHOUT the cache mutex held. Two
|
||||
// threads racing to compile the same shader both end up here;
|
||||
// glslang is deterministic on identical source so they produce
|
||||
// identical SPIR-V. The double-check below picks whichever
|
||||
// completed first.
|
||||
std::optional<SPIRVCodeVector> spv = ShaderCompiler::CompileShader(key.shader_type, shader_code, m_debug);
|
||||
if (!spv.has_value())
|
||||
return {};
|
||||
|
||||
// FAST: take the lock to publish. Double-check under the lock in
|
||||
// case another thread won the race - if so, read their SPIR-V
|
||||
// from disk and return it instead of writing ours (saves a file
|
||||
// write and keeps the index uniquely-keyed).
|
||||
std::lock_guard<std::mutex> lock(m_shader_cache_mutex);
|
||||
|
||||
auto iter = m_index.find(key);
|
||||
if (iter != m_index.end())
|
||||
{
|
||||
SPIRVCodeVector existing(iter->second.blob_size);
|
||||
if (rfseek(m_blob_file, iter->second.file_offset, SEEK_SET) != 0 ||
|
||||
rfread(existing.data(), sizeof(SPIRVCodeType), iter->second.blob_size, m_blob_file) != iter->second.blob_size)
|
||||
{
|
||||
// Read failure on the existing entry - fall through to our
|
||||
// freshly-compiled SPIR-V rather than fail the call.
|
||||
Log_WarningPrintf("Double-checked shader cache read failed; using freshly-compiled SPIR-V");
|
||||
}
|
||||
else
|
||||
{
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
|
||||
if (!m_blob_file || rfseek(m_blob_file, 0, SEEK_END) != 0)
|
||||
return spv;
|
||||
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@
|
|||
#include "vulkan_loader.h"
|
||||
#include <cstdio>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
|
@ -88,6 +89,45 @@ private:
|
|||
RFILE* m_blob_file = nullptr;
|
||||
std::string m_pipeline_cache_filename;
|
||||
|
||||
// Protects m_index (the unordered_map), m_blob_file (rfseek/rfread
|
||||
// share file position state), and m_index_file. NOT held across
|
||||
// the slow ShaderCompiler::CompileShader (glslang -> SPIR-V) call
|
||||
// - that runs lock-free so two threads compiling different shaders
|
||||
// truly run in parallel. Two threads racing to compile the same
|
||||
// shader is harmless: glslang is deterministic on identical source,
|
||||
// so both produce identical SPIR-V; the double-check in
|
||||
// CompileAndAddShaderSPV picks whichever publishes first.
|
||||
std::mutex m_shader_cache_mutex;
|
||||
|
||||
// Serialises external access to m_pipeline_cache. Per the Vulkan
|
||||
// spec, the pipelineCache parameter to vkCreateGraphicsPipelines /
|
||||
// vkCreateComputePipelines / vkMergePipelineCaches is in the host-
|
||||
// synchronisation parameter list - the application must guarantee
|
||||
// no concurrent use of the same VkPipelineCache. (The
|
||||
// VK_PIPELINE_CACHE_CREATE_EXTERNALLY_SYNCHRONIZED_BIT flag from
|
||||
// Vulkan 1.3 / VK_EXT_pipeline_creation_cache_control would
|
||||
// confirm the contract to the driver; without it the driver is
|
||||
// permitted to assume serial access.)
|
||||
//
|
||||
// Lazy-fault PSO compile helpers in GPU_HW_Vulkan acquire this via
|
||||
// PipelineCacheMutex() around their gpbuilder.Create(...) call.
|
||||
// The actual SPIR-V -> GPU-ISA compile inside the driver is
|
||||
// typically offloaded to the driver's own background threads, so
|
||||
// the lock window per call is short relative to the glslang
|
||||
// compile - and crucially, the glslang compile (which is the
|
||||
// slow part on shaders that hit D3DCompile-style optimiser
|
||||
// pathological cases) is now outside this lock entirely.
|
||||
std::mutex m_pipeline_cache_mutex;
|
||||
|
||||
public:
|
||||
// Exposed so lazy-fault PSO compile helpers can synchronise their
|
||||
// vkCreateGraphicsPipelines call against any other thread also
|
||||
// creating pipelines with the same VkPipelineCache. Returned
|
||||
// by-reference; lifetime tied to the ShaderCache singleton.
|
||||
std::mutex& PipelineCacheMutex() { return m_pipeline_cache_mutex; }
|
||||
|
||||
private:
|
||||
|
||||
CacheIndex m_index;
|
||||
|
||||
VkPipelineCache m_pipeline_cache = VK_NULL_HANDLE;
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -167,6 +167,34 @@ private:
|
|||
VkPipeline GetBatchPipeline(uint8_t depth_test, uint8_t render_mode, uint8_t texture_mode, uint8_t transparency_mode, bool dithering,
|
||||
bool interlacing);
|
||||
|
||||
// Lazy non-batch PSO compile path. Mirrors the D3D12 backend's
|
||||
// GetVRAMFillPipeline / GetVRAMCopyPipeline / GetDisplayPipeline
|
||||
// / etc. helpers: each non-batch pipeline (VRAM fill / copy /
|
||||
// write / update depth / readback, display, downsample) is
|
||||
// built on first use rather than unconditionally at GPU init.
|
||||
//
|
||||
// Unlike the batch helpers these helpers run main-thread-only.
|
||||
// The Lazy worker pre-fills them via the main-thread pre-fill
|
||||
// pass in CompilePipelines BEFORE spawning the batch worker, so
|
||||
// by the time gameplay begins all 18-ish non-batch slots are
|
||||
// filled and no contention can occur.
|
||||
//
|
||||
// The shared fullscreen-quad / UV-quad vertex shader modules are
|
||||
// cached as members so each helper can reach them without
|
||||
// re-running glslang + vkCreateShaderModule on every call.
|
||||
VkShaderModule GetFullscreenQuadVertexShader();
|
||||
VkShaderModule GetUVQuadVertexShader();
|
||||
VkPipeline GetVRAMFillPipeline(uint8_t wrapped, uint8_t interlaced);
|
||||
VkPipeline GetVRAMCopyPipeline(uint8_t depth_test);
|
||||
VkPipeline GetVRAMWritePipeline(uint8_t depth_test);
|
||||
VkPipeline GetVRAMUpdateDepthPipeline();
|
||||
VkPipeline GetVRAMReadbackPipeline();
|
||||
VkPipeline GetDisplayPipeline(uint8_t depth_24, uint8_t interlace_mode);
|
||||
VkPipeline GetDownsampleFirstPassPipeline();
|
||||
VkPipeline GetDownsampleMidPassPipeline();
|
||||
VkPipeline GetDownsampleBlurPassPipeline();
|
||||
VkPipeline GetDownsampleCompositePassPipeline();
|
||||
|
||||
// Background-thread worker for 'Lazy' mode: walks the full PSO
|
||||
// matrix and calls GetBatchPipeline on each cell. Main thread
|
||||
// can race ahead and fault in any slot it actually needs at draw
|
||||
|
|
@ -235,19 +263,22 @@ private:
|
|||
//
|
||||
// std::atomic<VkPipeline> rather than a plain VkPipeline so the
|
||||
// draw path can sample a slot without taking any lock. The slow
|
||||
// path (slot still null after the atomic load) takes the compile
|
||||
// mutex, re-checks the slot, compiles if still null, publishes
|
||||
// back to the slot. The fast path - which is what DrawBatchVertices
|
||||
// path (slot still null after the atomic load) compiles glslang
|
||||
// + vkCreateGraphicsPipelines lock-free, then takes
|
||||
// m_batch_shader_mutex briefly to publish into the slot under a
|
||||
// double-check. The fast path - which is what DrawBatchVertices
|
||||
// hits once a slot has been filled either by the precompile worker
|
||||
// or by an earlier main-thread fault-in - is a single
|
||||
// memory_order_acquire load with no kernel calls and no
|
||||
// serialisation against the worker. Without this, the user-visible
|
||||
// experience after a texture-filter change was a multi-second
|
||||
// hang: the precompile worker holds m_batch_shader_mutex for the
|
||||
// duration of each ~50-200 ms vkCreateGraphicsPipelines call, so
|
||||
// serialisation against the worker.
|
||||
//
|
||||
// Without this, the user-visible experience after a texture-filter
|
||||
// change was a multi-second hang: the precompile worker held
|
||||
// m_batch_shader_mutex for the duration of each glslang ->
|
||||
// SPIR-V compile (~hundreds of ms on the heavier shaders), so
|
||||
// every concurrent main-thread DrawBatchVertices stalled behind
|
||||
// it for one PSO compile, and the runloop never made forward
|
||||
// progress until the worker finished the entire 2160-entry
|
||||
// it for at least one full compile, and the runloop never made
|
||||
// forward progress until the worker finished the entire 2160-entry
|
||||
// matrix.
|
||||
DimensionalArray<std::atomic<VkPipeline>, 2, 2, 5, 9, 4, 3> m_batch_pipelines{};
|
||||
|
||||
|
|
@ -256,21 +287,25 @@ private:
|
|||
// locals in CompilePipelines and were leaked on success; now they
|
||||
// live for the lifetime of this GPU backend so the lazy PSO
|
||||
// builder can reach them at draw time, and DestroyPipelines tears
|
||||
// them down properly via SafeDestroyShaderModule.
|
||||
// them down properly.
|
||||
//
|
||||
// Dup slots for texture_mode 3 / 7 stay VK_NULL_HANDLE; the
|
||||
// helper-entry remap (see GetBatchFragmentShader) routes all
|
||||
// accesses through the canonical slots 2 / 6.
|
||||
//
|
||||
// m_batch_shader_mutex serialises the SLOW path of the lazy
|
||||
// helpers:
|
||||
// - g_vulkan_shader_cache mutations (its unordered_map indices
|
||||
// aren't thread-safe on insert)
|
||||
// - the VkPipelineCache passed to vkCreateGraphicsPipelines
|
||||
// (Vulkan spec: must be externally synchronised when shared
|
||||
// across threads)
|
||||
// - the writes that publish a newly-compiled VkPipeline /
|
||||
// VkShaderModule back into the matrix slot
|
||||
// m_batch_shader_mutex serialises only the PUBLISH step of the
|
||||
// lazy batch helpers - writing a freshly-compiled VkPipeline /
|
||||
// VkShaderModule back into the matrix slot, under a double-check
|
||||
// for "did another thread win the race". The slow operations
|
||||
// themselves (glslang -> SPIR-V, vkCreateShaderModule,
|
||||
// vkCreateGraphicsPipelines) all run WITHOUT this mutex held:
|
||||
// - g_vulkan_shader_cache has its own internal mutex (covers
|
||||
// SPIR-V index + cache file I/O; does NOT span the glslang
|
||||
// compile).
|
||||
// - g_vulkan_shader_cache->PipelineCacheMutex() (Vulkan 1.0
|
||||
// spec: the pipelineCache parameter to
|
||||
// vkCreateGraphicsPipelines is host-synchronised) is taken
|
||||
// just around the gpbuilder.Create() call.
|
||||
// The FAST path - draw-time lookup of an already-filled slot -
|
||||
// does NOT take this mutex; it uses an atomic load on the slot
|
||||
// itself. See the comment on m_batch_pipelines above for why
|
||||
|
|
@ -283,6 +318,14 @@ private:
|
|||
DimensionalArray<std::atomic<VkShaderModule>, 2> m_batch_vertex_shaders{}; // [textured]
|
||||
DimensionalArray<std::atomic<VkShaderModule>, 2, 2, 9, 4> m_batch_fragment_shaders{}; // [render][texture][dither][interlace]
|
||||
|
||||
// Shared vertex shaders used by all non-batch pipelines. Cached
|
||||
// here so the lazy non-batch helpers don't run glslang +
|
||||
// vkCreateShaderModule on every call - first GetXxxQuadVertexShader
|
||||
// call populates them, subsequent calls return the cached handle.
|
||||
// DestroyPipelines tears them down via SafeDestroyShaderModule.
|
||||
VkShaderModule m_fullscreen_quad_vertex_shader = VK_NULL_HANDLE;
|
||||
VkShaderModule m_uv_quad_vertex_shader = VK_NULL_HANDLE;
|
||||
|
||||
// [wrapped][interlaced]
|
||||
DimensionalArray<VkPipeline, 2, 2> m_vram_fill_pipelines{};
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue