diff --git a/CMakePresets.json b/CMakePresets.json index 37f7c0746..ca4753a04 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -34,7 +34,7 @@ "xmem_shim_test_controls", "startup_stub_xcrdapi", "startup_stub_xcrdapi_break_window_control", "xmem_run_break_readers_check", "xmem_run_break_readers_control", "xmem_cross_call_merge_check", "xmem_placeholder_split_check", "xmem_map_split_first_check", "startup_dstorage_break_window_check", - "xmem_page_runs_device_check", "linear_buffer_backing_check", "existing_heap_shared_buffer_check", "mesh86_typed_vsharp_check", "mesh86_typed_vsharp_wide_format_mut", "mesh86_typed_vsharp_any_map_mut", "mesh86_typed_vsharp_any_swizzle_mut", "mesh86_typed_vsharp_any_tid_mut", + "xmem_page_runs_device_check", "linear_buffer_backing_check", "existing_heap_shared_buffer_check", "startup_request_publisher_check", "mesh86_typed_vsharp_check", "mesh86_typed_vsharp_wide_format_mut", "mesh86_typed_vsharp_any_map_mut", "mesh86_typed_vsharp_any_swizzle_mut", "mesh86_typed_vsharp_any_tid_mut", "bcpack_formats_check", "startup_stub_consumer", "startup_inline_retire", "startup_resource_retire_title", "startup_table_lock", "native_compute_ir_dump", "native_pixel_ir_dump", "native_store_replay", "native_raw_buffer_view_check" ] @@ -50,7 +50,7 @@ "displayName": "Windows pull request smoke tests", "filter": { "include": { - "name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_mesh57_real_shape|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_(dispatch|constants|count)_inline_warp|startup_inline_retire_(on|control)_warp|startup_resource_retire_title_inline_warp_debug0|startup_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|existing_heap_shared_buffer(_offset_control)?_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run|mesh86_typed_vsharp_[a-z_]+)$" + "name": "^(bcpack_all_formats(_golden_control)?|startup_bcpack_storage|desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_mesh57_real_shape|startup_mesh57_runtime(_[a-z]+)?_warp|native_fixed_mesh57_published_pair(_refusal)?_warp|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_(dispatch|constants|count)_inline_warp|startup_inline_retire_(on|control)_warp|startup_resource_retire_title_inline_warp_debug0|startup_table_lock_(control_)?warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_indirect_mesh_cache_heap(_wide)?_warp|runtime_mesh86_cache_cli_check|startup_shader_cache_key|startup_present_readback|startup_present_planes(_control)?|startup_present_composite_(warp|overlay_removed_control_warp)|startup_mesh_title_snapshot_warp|startup_list_copy_(warp|title_snapshot_warp|validation(_[a-z_]+_control)?)|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp|existing_heap_shared_buffer(_offset_control)?_warp|startup_stage_package|startup_compute_packed_d16_x_uav_reference|native_.*_(ir|dxil|controls)|native_direct_mesh|startup_triage_run|mesh86_typed_vsharp_[a-z_]+|startup_request_publisher(_inline_control)?)$" } } }, diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 976e2f80e..4069613b5 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1865,6 +1865,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_D3D12_RELEASE_RETIRED=1` | opt-in, effective with `X2W_D3D12_RENDER=1` only (the list handlers that record holds exist only there): frees the desktop object of a released committed 2D texture of one narrow class once no recorded list, submission or release-time fence refers to it ([details](#d3d12-resource-budget)). Unset, nothing changes | | `X2W_D3D12_INLINE_DESCRIPTORS=1` | opt-in: leaves byte +0x18 of the guest device at 0, so the title writes constant buffer views and copies CBV/SRV/UAV descriptors itself instead of calling device slots 17 and 24 (sampler copies still arrive through slot 24); with `X2W_D3D12_RELEASE_RETIRED=1`, a retired resource is then freed once its release fences pass ([details](#d3d12-inline-descriptors)). Unset, nothing changes | | `X2W_D3D12_NO_VISIBLE_HEAP_MIRROR=1` | negative control only: title view and sampler heaps created shader-visible get no CPU-only mirror. By default every view, sampler and copy the stand-in writes into a shader-visible range goes to the mirror first and is copied from there, and copies and `ClearUnorderedAccessView*` read a visible descriptor from the mirror, because desktop D3D12 reads those only from CPU-only heaps (debug layer message 654; a driver fault on a GTX 1060, #3558). The switch restores the direct read | +| `X2W_SYNC_MESH_REQUESTS=1` | negative control only: mesh pipeline creations write their requests themselves, under the path's lock, before they answer: slot 57 (`req_.ps57`, `.root`, `.m57`, and `.s57` with `X2W_MESH57_CAPTURE_STATE=1`) and slot 86 (`.ps86`, `.root`, `.stream86`, `.m86`). By default a creation queues its request and returns; one background thread writes the parts in order (`src/startup_stubs/request_publisher.h`). A key is queued once per process, at most 64 MiB of parts wait at a time (a request past that is dropped; slot 57 keeps its stages and queues it again on a later call, slot 86 asks again in a later run), and what is still queued is written at module unload for at most 2 s. The periodic `x2w-render mesh request publisher:` line counts queued, repeated, written, failed and dropped requests. On a GTX 1060 a title creating thousands of mesh pipelines waited on these writes one creation at a time: about 7 slot 86 creations a second, and a 45 s gap in presents while title threads queued on the slot 57 request lock. `ctest --preset dev --no-tests=error -R '^startup_request_publisher'` (the inline control must fail) | | `X2W_D3D12_RELEASE_RETIRED_VIEWS=1` | legacy diagnostic. Logs that clearing live slots is disabled and enables the existing retirement breakdown when base retirement and budgets are on ([details](#d3d12-resource-budget)) | | `X2W_D3D12_AGILITY=` | opt-in: the stand-ins select the Agility SDK `D3D12Core.dll` in `` before the first D3D12 device of the process (Windows Developer Mode only; `` on the executable's drive). Unset, the in-box runtime stays and nothing is read ([details](#d3d12-agility-sdk-runtime)) | | `X2W_D3D12_RETIRE_REASONS=1` | diagnostic only, effective with `X2W_D3D12_RELEASE_RETIRED=1` and `X2W_D3D12_BUDGET=1`: adds one `x2w-retire held:` line to the heartbeat that counts final-released resources whose desktop object is still alive, by reason ([details](#d3d12-resource-budget)). Unset, nothing is recorded | diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 2b012ca84..59f3235eb 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -590,6 +590,93 @@ bool publish_shader_request(u64 key, const wchar_t* ext, const void* data, std:: return exists; } +// Mesh pipeline requests (slot 57 and slot 86) are written on one background thread (request_publisher.h), so a title +// that creates thousands of mesh pipelines does not wait on a probe, a temporary file and a rename per request part, +// one creation at a time. At most mesh_request_publish_limit bytes of copied parts wait; a request past that is +// dropped and counted, and the title asks for it again in a later run. X2W_SYNC_MESH_REQUESTS=1 (negative control) +// writes them on the creating thread, as before. +constexpr std::size_t mesh_request_publish_limit = std::size_t{64} << 20; + +bool sync_mesh_requests() +{ + static const bool on = x2w_local::env_on("X2W_SYNC_MESH_REQUESTS"); + return on; +} + +bool write_mesh_request_part(void*, u64 key, const wchar_t* extension, const void* data, std::size_t bytes) +{ + return publish_shader_request(key, extension, data, bytes); +} + +// The cache directory, read once when the publisher is made, so the unload writer reads no environment variable. +wchar_t mesh_request_dir[MAX_PATH]; + +// Made on first use and never destroyed: the drain below runs at module unload, after function-local statics are gone. +x2w_startup::RequestPublisher* volatile mesh_request_instance; + +x2w_startup::RequestPublisher& mesh_request_publisher() +{ + static auto* publisher = [] { + const DWORD n = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", mesh_request_dir, MAX_PATH); + if (!n || n >= MAX_PATH) mesh_request_dir[0] = 0; + auto* made = new x2w_startup::RequestPublisher(write_mesh_request_part, nullptr, mesh_request_publish_limit); + mesh_request_instance = made; + return made; + }(); + return *publisher; +} + +// The unload writer: a temporary file of its own and a rename, without the cache index (whose lock a terminated +// thread may hold) or anything else that locks. A part already on disk is left as it is. +bool write_mesh_request_part_at_exit(void*, u64 key, const wchar_t* extension, const void* data, std::size_t bytes) +{ + if (!mesh_request_dir[0]) return false; + wchar_t path[MAX_PATH], temporary[MAX_PATH]; + if (swprintf(path, MAX_PATH, L"%s\\req_%016llx%s", mesh_request_dir, key, extension) < 0 || + swprintf(temporary, MAX_PATH, L"%s.%lu.exit.tmp", path, GetCurrentProcessId()) < 0) + return false; + if (GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES) return true; + HANDLE file = CreateFileW(temporary, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (file == INVALID_HANDLE_VALUE) return false; + DWORD written = 0; + const bool complete = WriteFile(file, data, static_cast(bytes), &written, nullptr) && written == bytes; + CloseHandle(file); + if (complete && MoveFileExW(temporary, path, 0)) return true; + DeleteFileW(temporary); + return GetFileAttributesW(path) != INVALID_FILE_ATTRIBUTES; +} + +// At module unload, write what is still queued, for at most two seconds, so a short run (a fixture) leaves its +// requests on disk. Nothing is made here when no request was queued. +struct MeshRequestDrain { + ~MeshRequestDrain() + { + if (auto* publisher = mesh_request_instance) publisher->drain(2000, write_mesh_request_part_at_exit); + } +} mesh_request_drain; + +// Publishes the parts of one request in order: queued, or written now under X2W_SYNC_MESH_REQUESTS=1. False when the +// request was dropped (queued) or a part could not be written (sync). +bool publish_mesh_request(u64 key, const x2w_startup::RequestPublisher::Part* parts, std::size_t count) +{ + if (!sync_mesh_requests()) return mesh_request_publisher().enqueue(key, parts, count); + for (std::size_t i = 0; i < count; ++i) + if (!publish_shader_request(key, parts[i].extension, parts[i].data, parts[i].bytes)) return false; + return true; +} + +void mesh_request_publisher_line(char (&line)[256]) +{ + line[0] = 0; + auto* publisher = mesh_request_instance; + if (!publisher) return; + const auto s = publisher->stats(); + if (!s.queued && !s.dropped) return; + std::snprintf(line, sizeof(line), + "x2w-render mesh request publisher: queued %lld repeated %lld written %lld failed %lld dropped %lld pending %zu (%zu KiB, high water %zu KiB)", + s.queued, s.repeated, s.written, s.failed, s.dropped, s.pending, s.pending_bytes >> 10, s.high_water_bytes >> 10); +} + bool native_shaders_only() { static const bool enabled = [] { @@ -1067,13 +1154,19 @@ void request_slot57_mesh(Wrapper* pipeline, const std::vector* bo std::memcpy(packed.data() + sizeof(key), lengths, sizeof(lengths)); for (const auto* bytes : {&desc, &info->state_a, &info->state_b}) packed.insert(packed.end(), bytes->begin(), bytes->end()); - if (!publish_shader_request(variant, L".s57", packed.data(), packed.size())) + const x2w_startup::RequestPublisher::Part state{L".s57", packed.data(), packed.size()}; + if (!publish_mesh_request(variant, &state, 1)) log("x2w-draw fixed mesh state %016llx could not be published", variant); } const unsigned char none = 0; - if (written.count(key) || (publish_shader_request(key, L".ps57", pixel.empty() ? &none : pixel.data(), pixel.size()) && - publish_shader_request(key, L".root", root_blob.data(), root_blob.size()) && - publish_shader_request(key, L".m57", mesh.data(), mesh.size()))) { + // The parts are copied into the publisher's queue (or written now with X2W_SYNC_MESH_REQUESTS=1); a dropped + // request keeps its stages, so a later call queues it again. + const x2w_startup::RequestPublisher::Part parts[]{ + {L".ps57", pixel.empty() ? &none : pixel.data(), pixel.size()}, + {L".root", root_blob.data(), root_blob.size()}, + {L".m57", mesh.data(), mesh.size()}, + }; + if (written.count(key) || publish_mesh_request(key, parts, std::size(parts))) { const bool first = written.insert(key).second; static LONG logged; if (first && first_calls(logged, 12)) diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index c85af6416..2ef8b4268 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -54,6 +54,7 @@ #include #include "startup_stubs/derived_blend.h" #include "startup_stubs/placement_publish.h" +#include "startup_stubs/request_publisher.h" #include "startup_stubs/resource_address_index.h" #include "startup_stubs/placed_build.h" #include "startup_stubs/placed_buffer_range.h" @@ -9009,6 +9010,9 @@ HRESULT __stdcall queue_present(Wrapper* self, UINT planes, const void* plane_pa char mesh57_line[1536]; mesh57_outcome_line(mesh57_line); log("%s", mesh57_line); + char mesh_request_line[256]; + mesh_request_publisher_line(mesh_request_line); + if (mesh_request_line[0]) log("%s", mesh_request_line); } if (render_mode() && frame % 300 == 0) { // Slot-61 calls since the start, by outcome, then by signature kind (zero kinds left out). diff --git a/src/startup_stubs/mesh86_cache.inl b/src/startup_stubs/mesh86_cache.inl index 1696db4c3..6a8866a39 100644 --- a/src/startup_stubs/mesh86_cache.inl +++ b/src/startup_stubs/mesh86_cache.inl @@ -265,15 +265,27 @@ ID3D12PipelineState* try_cached_mesh86(const D3D12_PIPELINE_STATE_STREAM_DESC& d auto key = fnv_bytes(revision, sizeof(revision) - 1); for (const auto* part : {&request.ms, &request.ps, &root_blob, &request.stream}) key = fnv_part(*part, key); static SRWLOCK lock = SRWLOCK_INIT; - x2w_startup::ExclusiveNoteLock guard(lock); const unsigned char none = 0; - if (!publish_shader_request(key, L".ps86", request.ps.empty() ? &none : request.ps.data(), request.ps.size()) || - !publish_shader_request(key, L".root", root_blob.data(), root_blob.size()) || - !publish_shader_request(key, L".stream86", request.stream.data(), request.stream.size()) || - !publish_shader_request(key, L".m86", request.ms.data(), request.ms.size())) { - std::snprintf(why, why_size, "slot86 mesh request %016llx publication failed", key); - return nullptr; + const x2w_startup::RequestPublisher::Part parts[]{ + {L".ps86", request.ps.empty() ? &none : request.ps.data(), request.ps.size()}, + {L".root", root_blob.data(), root_blob.size()}, + {L".stream86", request.stream.data(), request.stream.size()}, + {L".m86", request.ms.data(), request.ms.size()}, + }; + if (sync_mesh_requests()) { + // X2W_SYNC_MESH_REQUESTS=1: every creation writes its request under the lock, as before the publisher. + x2w_startup::ExclusiveNoteLock guard(lock); + for (const auto& part : parts) + if (!publish_shader_request(key, part.extension, part.data, part.bytes)) { + std::snprintf(why, why_size, "slot86 mesh request %016llx publication failed", key); + return nullptr; + } + } else { + // The request is written on the publisher's thread; until the translator answers it the creation below finds + // no marker and reports it pending, the same answer a creation gave while its own write was in progress. + publish_mesh_request(key, parts, std::size(parts)); } + x2w_startup::ExclusiveNoteLock guard(lock); published_key = key; const auto* params = root_info(request.root); // Only the resource heap can be indexed, and only through a published heap-buffer window (bind_mesh86_heap). The diff --git a/src/startup_stubs/request_publisher.h b/src/startup_stubs/request_publisher.h new file mode 100644 index 000000000..969099e6a --- /dev/null +++ b/src/startup_stubs/request_publisher.h @@ -0,0 +1,265 @@ +// Experimental (docs/startup-runtime.md): writes shader-cache request parts on one background thread. +// +// A mesh pipeline creation publishes its request (several parts, each a probe, a temporary file and a rename) before +// it can answer. A title that creates thousands of mesh pipelines then waits on that file work, one creation at a +// time. The publisher takes a copy of a request's parts and returns; its thread writes them. +// +// - The parts of one request are written in the order given, and requests in the order queued. +// - A key is queued once per process. A repeated enqueue of it returns true without copying anything. A request that +// could not be queued (out of memory) or written forgets its key, so a later enqueue of it is accepted again. +// - The queued bytes are bounded. A request that would pass the bound is dropped and counted. +// - stop() ends the thread and joins it (the destructor calls it). +// - drain() is for module unload: it writes what is still queued on the calling thread, with its own writer (one that +// takes no lock a terminated thread may hold), and only once the writer thread has ended. While the thread still +// runs (an executable's static destructors) it waits for the thread instead. A request stays at the front of the +// queue while it is written, so a drain after the thread was terminated mid-write writes it again from the start. +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace x2w_startup { + +class RequestPublisher { +public: + // Writes one part; returns false when the part could not be written. + using Write = bool (*)(void* context, std::uint64_t key, const wchar_t* extension, const void* data, std::size_t bytes); + + struct Part { + const wchar_t* extension; + const void* data; + std::size_t bytes; + }; + + struct Stats { + long long queued = 0; // requests accepted + long long repeated = 0; // enqueues of a key already accepted + long long written = 0; // requests whose parts were all written + long long failed = 0; // requests with a part that could not be written + long long dropped = 0; // requests over the byte bound + std::size_t pending = 0, pending_bytes = 0, high_water_bytes = 0; + }; + + RequestPublisher(Write write, void* context, std::size_t byte_limit, bool start_thread = true) noexcept + : write_(write), context_(context), byte_limit_(byte_limit), start_thread_(start_thread) + { + } + RequestPublisher(const RequestPublisher&) = delete; + RequestPublisher& operator=(const RequestPublisher&) = delete; + ~RequestPublisher() { stop(); } + + // Copies the parts and queues them as one request. False when the request was dropped (or out of memory). + bool enqueue(std::uint64_t key, const Part* parts, std::size_t count) + { + std::size_t bytes = 0; + for (std::size_t i = 0; i < count; ++i) bytes += parts[i].bytes; + AcquireSRWLockExclusive(&lock_); + if (seen_.count(key)) { + ++stats_.repeated; + ReleaseSRWLockExclusive(&lock_); + return true; + } + if (stopping_ || bytes > byte_limit_ || stats_.pending_bytes > byte_limit_ - bytes) { + ++stats_.dropped; + ReleaseSRWLockExclusive(&lock_); + return false; + } + try { + Request request{key, bytes, {}}; + request.parts.reserve(count); + for (std::size_t i = 0; i < count; ++i) { + const auto* begin = static_cast(parts[i].data); + request.parts.push_back({parts[i].extension, std::vector(begin, begin + parts[i].bytes)}); + } + seen_.insert(key); + queue_.push_back(std::move(request)); + } catch (...) { + // The key may already be recorded when queuing the copy fails: forget it, so a retry is accepted. + seen_.erase(key); + ++stats_.dropped; + ReleaseSRWLockExclusive(&lock_); + return false; + } + ++stats_.queued; + ++stats_.pending; + stats_.pending_bytes += bytes; + if (stats_.pending_bytes > stats_.high_water_bytes) stats_.high_water_bytes = stats_.pending_bytes; + const bool start = start_thread_ && !thread_started_; + thread_started_ = thread_started_ || start; + // No thread could be started: the queuing thread writes, as before the publisher. + while (inline_writes_ && !queue_.empty()) write_front(write_); + ReleaseSRWLockExclusive(&lock_); + if (start) start_thread(); + WakeConditionVariable(&work_); + return true; + } + + // Waits until every queued request is written or timeout_ms passes; true when the queue is empty. + bool flush(DWORD timeout_ms) + { + const ULONGLONG deadline = GetTickCount64() + timeout_ms; + AcquireSRWLockExclusive(&lock_); + while (!queue_.empty()) { + const ULONGLONG now = GetTickCount64(); + if (now >= deadline || !thread_running()) break; + SleepConditionVariableSRW(&idle_, &lock_, static_cast(deadline - now), 0); + } + const bool empty = queue_.empty(); + ReleaseSRWLockExclusive(&lock_); + return empty; + } + + // Ends the writer thread after the request it is writing, and joins it. What is still queued stays queued. + void stop() + { + AcquireSRWLockExclusive(&lock_); + stopping_ = true; + const HANDLE thread = thread_; + ReleaseSRWLockExclusive(&lock_); + WakeAllConditionVariable(&work_); + if (thread && thread_alive(thread)) WaitForSingleObject(thread, INFINITE); + } + + // Module unload. Once the writer thread has ended (or never started), writes what is still queued on the calling + // thread with `write` (nullptr: the publisher's writer) until the queue is empty or timeout_ms passes. While the + // thread still runs, waits for it instead. Never waits for the lock. Returns the requests written here. + std::size_t drain(DWORD timeout_ms, Write write = nullptr) + { + if (!TryAcquireSRWLockExclusive(&lock_)) return 0; + const HANDLE thread = thread_; + const bool running = thread && thread_alive(thread); + ReleaseSRWLockExclusive(&lock_); + if (running) { + flush(timeout_ms); + return 0; + } + if (!TryAcquireSRWLockExclusive(&lock_)) return 0; + const ULONGLONG deadline = GetTickCount64() + timeout_ms; + std::size_t done = 0; + while (!queue_.empty() && GetTickCount64() < deadline) { + write_front(write ? write : write_); + ++done; + } + ReleaseSRWLockExclusive(&lock_); + return done; + } + + Stats stats() const + { + AcquireSRWLockShared(&lock_); + const Stats copy = stats_; + ReleaseSRWLockShared(&lock_); + return copy; + } + +private: + struct OwnedPart { + std::wstring extension; + std::vector data; + }; + struct Request { + std::uint64_t key; + std::size_t bytes; + std::vector parts; + }; + + static bool thread_alive(HANDLE thread) { return WaitForSingleObject(thread, 0) == WAIT_TIMEOUT; } + + // With lock_ held: the writer thread exists and has not ended. + bool thread_running() const { return thread_ && thread_alive(thread_); } + + // Writes the front request with `write` and pops it. Called with lock_ held exclusive; releases it while writing + // when unlock (only the writer thread pops while it runs, so the front stays valid). + void write_front(Write write, bool unlock = false) + { + Request& request = queue_.front(); + if (unlock) ReleaseSRWLockExclusive(&lock_); + bool complete = true; + for (const auto& part : request.parts) + if (!write(context_, request.key, part.extension.c_str(), part.data.data(), part.data.size())) { + complete = false; + break; + } + if (unlock) AcquireSRWLockExclusive(&lock_); + ++(complete ? stats_.written : stats_.failed); + if (!complete) seen_.erase(request.key); + --stats_.pending; + stats_.pending_bytes -= request.bytes; + queue_.pop_front(); + } + + static DWORD WINAPI thread_main(void* self) + { + auto* publisher = static_cast(self); + const HMODULE module = publisher->module_; + publisher->run(); + if (module) FreeLibraryAndExitThread(module, 0); + return 0; + } + + void run() + { + AcquireSRWLockExclusive(&lock_); + for (;;) { + while (queue_.empty() && !stopping_) { + WakeAllConditionVariable(&idle_); + SleepConditionVariableSRW(&work_, &lock_, INFINITE, 0); + } + if (stopping_) break; + write_front(write_, true); + if (queue_.empty()) WakeAllConditionVariable(&idle_); + } + WakeAllConditionVariable(&idle_); + ReleaseSRWLockExclusive(&lock_); + } + + void start_thread() + { + // The thread holds a reference on this module so a FreeLibrary cannot unmap the code it runs; it releases it + // when stop() ends it. + HMODULE module = nullptr; + GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, reinterpret_cast(&thread_main), &module); + module_ = module; + // Created suspended so stop() always finds the handle of a thread that has started. + if (HANDLE thread = CreateThread(nullptr, 0, thread_main, this, CREATE_SUSPENDED, nullptr)) { + AcquireSRWLockExclusive(&lock_); + thread_ = thread; + ReleaseSRWLockExclusive(&lock_); + ResumeThread(thread); + return; + } + module_ = nullptr; + if (module) FreeLibrary(module); + // No thread: write on the queuing threads instead, as before the publisher. + AcquireSRWLockExclusive(&lock_); + thread_started_ = false; + start_thread_ = false; + inline_writes_ = true; + while (!queue_.empty()) write_front(write_); + ReleaseSRWLockExclusive(&lock_); + } + + Write write_; + void* context_; + std::size_t byte_limit_; + bool start_thread_; + bool thread_started_ = false; + bool inline_writes_ = false; + bool stopping_ = false; + HANDLE thread_ = nullptr; + HMODULE module_ = nullptr; + mutable SRWLOCK lock_ = SRWLOCK_INIT; + CONDITION_VARIABLE work_ = CONDITION_VARIABLE_INIT, idle_ = CONDITION_VARIABLE_INIT; + std::deque queue_; + std::unordered_set seen_; + Stats stats_; +}; + +} // namespace x2w_startup diff --git a/tests/cmake/startup_request_publisher.cmake b/tests/cmake/startup_request_publisher.cmake new file mode 100644 index 000000000..29dd4d7d9 --- /dev/null +++ b/tests/cmake/startup_request_publisher.cmake @@ -0,0 +1,9 @@ +# Background writes of shader-cache request parts (src/startup_stubs/request_publisher.h), without a device. A slot 86 +# mesh creation queues its request and returns. The inline control waits for each write, as creation did before, and +# must fail. +add_executable(startup_request_publisher_check tests/startup_request_publisher_check.cpp) +target_include_directories(startup_request_publisher_check PRIVATE src) +target_compile_features(startup_request_publisher_check PRIVATE cxx_std_17) +add_test(NAME startup_request_publisher COMMAND startup_request_publisher_check) +add_test(NAME startup_request_publisher_inline_control COMMAND startup_request_publisher_check --mutate inline) +set_tests_properties(startup_request_publisher_inline_control PROPERTIES WILL_FAIL TRUE) diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 973629d5a..d8ed10eb1 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -3653,6 +3653,22 @@ int main(int argc, char** argv) try if (!dispatch(pair.Get(), root.Get(), "mesh with PS") || !dispatch(depth.Get(), root.Get(), "mesh with no PS") || !dispatch(pair.Get(), root.Get(), "repeat mesh with PS")) return 1; + // Requests are written by the background publisher (request_publisher.h), .m57 last as the ready marker. + // Wait, bounded, for both complete requests and no part still in its temporary name before the exact checks. + const auto complete_requests = [&cache] { + unsigned markers = 0; + for (const auto& file : std::filesystem::directory_iterator(cache)) { + if (file.path().extension() == ".tmp") return ~0u; + if (file.path().extension() == ".m57") ++markers; + } + return markers; + }; + const ULONGLONG wait_start = GetTickCount64(); + while (complete_requests() != 2 && GetTickCount64() - wait_start < 10000) Sleep(10); + if (complete_requests() != 2) { + std::puts("FAIL: the two slot 57 requests were not complete within 10 s"); + return 1; + } unsigned requests = 0, with_ps = 0, files = 0; const auto matches = [](const std::filesystem::path& path, const void* bytes, std::size_t size) { std::ifstream stream(path, std::ios::binary); diff --git a/tests/startup_request_publisher_check.cpp b/tests/startup_request_publisher_check.cpp new file mode 100644 index 000000000..0ff8e5815 --- /dev/null +++ b/tests/startup_request_publisher_check.cpp @@ -0,0 +1,237 @@ +// Checks src/startup_stubs/request_publisher.h without a device: a queued request returns while its writer is held, +// parts and requests are written in order, a repeated key is written once, the byte bound drops and counts, a failed +// part stops its request, an enqueue that runs out of memory at any allocation can be retried, and drain() writes the queue on the calling thread (module unload). --mutate inline is the +// negative control: each enqueue waits for its write, as a slot 86 mesh creation did before the publisher, so the +// held-writer case must fail. +#include "startup_stubs/request_publisher.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Allocation failure injection for this thread only (the writer thread is unaffected): with allocations_left >= 0, +// that many allocations succeed and the next one throws std::bad_alloc. Debug builds (_ITERATOR_DEBUG_LEVEL != 0) +// also allocate an iterator proxy inside noexcept container constructors, where a throw ends in std::terminate and +// the CRT's modal report: those allocations are neither failed nor counted. +thread_local long allocations_left = -1; + +void* operator new(std::size_t size) +{ +#if _ITERATOR_DEBUG_LEVEL != 0 + if (size == sizeof(std::_Container_proxy)) { + if (void* p = std::malloc(size)) return p; + throw std::bad_alloc(); + } +#endif + if (allocations_left == 0) { + allocations_left = -1; + throw std::bad_alloc(); + } + if (allocations_left > 0) --allocations_left; + if (void* p = std::malloc(size ? size : 1)) return p; + throw std::bad_alloc(); +} +void operator delete(void* p) noexcept { std::free(p); } +void operator delete(void* p, std::size_t) noexcept { std::free(p); } + +namespace { + +using x2w_startup::RequestPublisher; + +bool inline_mutation = false; +int failures = 0; + +void expect(bool ok, const char* what) +{ + if (!ok) { + std::printf("FAIL %s\n", what); + ++failures; + } +} + +struct Writer { + SRWLOCK lock = SRWLOCK_INIT; + std::vector writes; // "::" + HANDLE gate = nullptr; // when set, every write waits for it + std::wstring fail_extension; + + static bool write(void* context, std::uint64_t key, const wchar_t* extension, const void* data, std::size_t bytes) + { + auto& self = *static_cast(context); + if (self.gate) WaitForSingleObject(self.gate, 5000); + if (bytes && !data) return false; + if (extension == self.fail_extension) return false; + char line[64]; + std::snprintf(line, sizeof(line), "%llx:%ls:%zu", static_cast(key), extension, bytes); + AcquireSRWLockExclusive(&self.lock); + self.writes.push_back(line); + ReleaseSRWLockExclusive(&self.lock); + return true; + } + // The unload writer: recorded with an "exit " prefix. + static bool exit_write(void* context, std::uint64_t key, const wchar_t* extension, const void* data, std::size_t bytes) + { + auto& self = *static_cast(context); + char line[64]; + std::snprintf(line, sizeof(line), "exit %llx:%ls:%zu", static_cast(key), extension, bytes); + AcquireSRWLockExclusive(&self.lock); + self.writes.push_back(line); + ReleaseSRWLockExclusive(&self.lock); + return data || !bytes; + } + std::vector snapshot() + { + AcquireSRWLockShared(&lock); + auto copy = writes; + ReleaseSRWLockShared(&lock); + return copy; + } +}; + +const unsigned char bytes[64]{}; + +// Queues a one-part request. +bool one_part(RequestPublisher& publisher, std::uint64_t key, std::size_t size) +{ + const RequestPublisher::Part part{L".a", bytes, size}; + return publisher.enqueue(key, &part, 1); +} + +bool queue(RequestPublisher& publisher, std::uint64_t key, std::size_t size = 4) +{ + const RequestPublisher::Part parts[]{{L".a", bytes, size}, {L".b", bytes, size}, {L".m", bytes, size}}; + const bool queued = publisher.enqueue(key, parts, std::size(parts)); + if (inline_mutation) publisher.flush(500); // the creation waits for its own write + return queued; +} + +void held_writer() +{ + Writer writer; + writer.gate = CreateEventW(nullptr, TRUE, FALSE, nullptr); + RequestPublisher publisher(Writer::write, &writer, 1 << 20); + const ULONGLONG start = GetTickCount64(); + for (std::uint64_t key = 1; key <= 3; ++key) queue(publisher, key); + const ULONGLONG queued_ms = GetTickCount64() - start; + expect(queued_ms < 250, "three requests queue while the writer is held"); + expect(writer.snapshot().empty(), "nothing is written before the writer is released"); + SetEvent(writer.gate); + expect(publisher.flush(5000), "flush returns once every request is written"); + const std::vector want{"1:.a:4", "1:.b:4", "1:.m:4", "2:.a:4", "2:.b:4", "2:.m:4", + "3:.a:4", "3:.b:4", "3:.m:4"}; + expect(writer.snapshot() == want, "parts and requests are written in the order queued"); + const auto s = publisher.stats(); + expect(s.queued == 3 && s.written == 3 && s.pending == 0 && s.pending_bytes == 0 && s.high_water_bytes == 36, + "stats count three written requests and a 36-byte high water"); + + expect(queue(publisher, 2), "a repeated key is accepted"); + publisher.flush(5000); + expect(writer.snapshot().size() == want.size() && publisher.stats().repeated == 1, + "a repeated key is not written again"); + std::printf("held writer: %llu ms to queue three requests\n", static_cast(queued_ms)); + CloseHandle(writer.gate); +} + +void byte_bound_and_drain() +{ + Writer writer; + RequestPublisher publisher(Writer::write, &writer, 100, /*start_thread=*/false); + expect(one_part(publisher, 7, 60), "a 60-byte request fits"); + expect(!one_part(publisher, 8, 60), "a second one is dropped"); + expect(!one_part(publisher, 9, 101), "one over the bound is dropped"); + expect(publisher.stats().dropped == 2 && publisher.stats().pending == 1, "two drops, one pending"); + expect(writer.snapshot().empty(), "nothing is written without the thread"); + expect(publisher.drain(1000, Writer::exit_write) == 1, "drain writes the pending request"); + expect(writer.snapshot() == std::vector{"exit 7:.a:60"}, "drain wrote it with the unload writer"); + expect(one_part(publisher, 8, 60), + "a dropped key is accepted once there is room"); + expect(publisher.drain(1000) == 1 && publisher.stats().pending_bytes == 0, "the queue is empty after drain"); +} + +void failed_part() +{ + Writer writer; + writer.fail_extension = L".b"; + RequestPublisher publisher(Writer::write, &writer, 1 << 20); + queue(publisher, 5); + publisher.flush(5000); + expect(writer.snapshot() == std::vector{"5:.a:4"}, "a failed part stops its request"); + expect(publisher.stats().failed == 1 && publisher.stats().written == 0, "the request counts as failed"); + writer.fail_extension.clear(); + queue(publisher, 5); + publisher.flush(5000); + const auto s = publisher.stats(); + expect(s.queued == 2 && s.repeated == 0 && s.written == 1, "a failed request is accepted and written again"); +} + +// Fails each allocation of an enqueue in turn, from the first one until the enqueue no longer fails. Every failed +// enqueue must report a drop and leave its key unrecorded, so the same key is queued (not counted as repeated) on retry. +void allocation_failure_retry() +{ + Writer writer; + RequestPublisher publisher(Writer::write, &writer, 1 << 20); + int failed = 0; + for (long n = 0; n < 256; ++n) { + const std::uint64_t key = 0x100 + static_cast(n); + const auto before = publisher.stats(); + allocations_left = n; + const bool queued = queue(publisher, key); + allocations_left = -1; + if (queued) break; + ++failed; + expect(publisher.stats().dropped == before.dropped + 1, "an enqueue out of memory counts a drop"); + expect(queue(publisher, key), "a retry after an allocation failure is accepted"); + const auto after = publisher.stats(); + expect(after.queued == before.queued + 1 && after.repeated == before.repeated, + "a retry after an allocation failure queues the request"); + } + expect(failed >= 3, "allocation failures were injected inside enqueue"); + publisher.flush(5000); + expect(publisher.stats().written == publisher.stats().queued, "every retried request is written"); +} + +void drain_while_running_and_stop() +{ + Writer writer; + writer.gate = CreateEventW(nullptr, TRUE, FALSE, nullptr); + { + RequestPublisher publisher(Writer::write, &writer, 1 << 20); + queue(publisher, 9); + // The thread still runs (an executable's static destructors): drain waits for it and writes nothing itself. + SetEvent(writer.gate); + expect(publisher.drain(5000, Writer::exit_write) == 0, "drain writes nothing while the thread runs"); + expect(writer.snapshot().size() == 3 && writer.snapshot()[0] == "9:.a:4", "the thread wrote the request"); + publisher.stop(); + expect(!one_part(publisher, 10, 4), + "a stopped publisher accepts nothing"); + } // the destructor joins the stopped thread + CloseHandle(writer.gate); +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc == 3 && !std::strcmp(argv[1], "--mutate") && !std::strcmp(argv[2], "inline")) inline_mutation = true; + else if (argc != 1) { + std::printf("usage: %s [--mutate inline]\n", argv[0]); + return 2; + } + held_writer(); + byte_bound_and_drain(); + failed_part(); + allocation_failure_retry(); + drain_while_running_and_stop(); + if (failures) { + std::printf("request publisher: %d failed\n", failures); + return 1; + } + std::printf("request publisher: all cases passed\n"); + return 0; +}