From adf532c5eb70d2b0e1b58e0b60944b7154f6c379 Mon Sep 17 00:00:00 2001 From: JohnConnorNPC <128232619+JohnConnorNPC@users.noreply.github.com> Date: Sun, 29 Nov 2026 05:02:54 +1000 Subject: [PATCH] startup: list the shader cache once and skip absent mesh57 profiles With X2W_NATIVE_SHADERS set, every slot-57 pipeline creation opened .mesh57-state in the cache root. The file almost never exists, and under Wine each missing-name open in a ~274k-entry cache directory costs ~145 ms, so slot-57 creation fell to ~18 per second. Add src/startup_stubs/cache_index.h: a one-time FindFirstFileExW listing of the cache's top-level files, kept as sorted FNV-1a-64 hashes of the ASCII-lowercased names. A lookup answers present, absent or unknown; unknown (failed or missing listing, another directory) falls back to the disk. add() and a contradiction counter cover the runtime's own writes. The first lookup logs "x2w-draw cache index: names in ms". Only the mesh57 profile lookup uses the index here. Behaviour change: a mesh57 profile written while the process runs is read by the next process. Measured under Wine on a 273,716-file cache: one listing ~1.2 s, one missing-name open ~145 ms. Tests: startup_cache_index (deviceless) and its per-call control, which must fail on the disk-probe count; native_fixed_mesh57* now add 2000 other cache files and 64 profile-less pipelines and require 2 opens for 66 lookups. --- CMakeLists.txt | 11 ++ docs/experiments/native-fixed-mesh57.md | 2 +- docs/startup-runtime.md | 2 +- src/startup_stubs/cache_index.h | 201 ++++++++++++++++++++ src/startup_stubs/d3d12_draw.inl | 26 +++ src/startup_stubs/d3d12_xs_device.cpp | 1 + src/startup_stubs/native_mesh57.inl | 15 ++ tests/startup_cache_index_check.cpp | 232 ++++++++++++++++++++++++ tests/startup_indirect_draw_indexed.cpp | 19 ++ 9 files changed, 507 insertions(+), 2 deletions(-) create mode 100644 src/startup_stubs/cache_index.h create mode 100644 tests/startup_cache_index_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 252816910f..8961e7970b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -659,6 +659,17 @@ add_test(NAME startup_descriptor_heap_type COMMAND startup_descriptor_heap_type_ add_test(NAME startup_descriptor_heap_type_off_by_one_control COMMAND startup_descriptor_heap_type_check --mutate off-by-one) add_test(NAME startup_descriptor_heap_type_signed_control COMMAND startup_descriptor_heap_type_check --mutate signed) set_tests_properties(startup_descriptor_heap_type_off_by_one_control startup_descriptor_heap_type_signed_control PROPERTIES WILL_FAIL TRUE) +# The one-time shader-cache listing that gates the native slot-57 profile open (src/startup_stubs/cache_index.h), +# without a device. The per-call control probes the disk for every name, as before the index, and must fail on the +# probe count alone. +add_executable(startup_cache_index_check tests/startup_cache_index_check.cpp) +target_include_directories(startup_cache_index_check PRIVATE src) +target_compile_features(startup_cache_index_check PRIVATE cxx_std_17) +add_test(NAME startup_cache_index COMMAND startup_cache_index_check) +add_test(NAME startup_cache_index_per_call_control COMMAND startup_cache_index_check --mutate per-call) +set_tests_properties(startup_cache_index_per_call_control PROPERTIES + PASS_REGULAR_EXPRESSION "FAIL: \\(a\\) 515 disk probes for 515 lookups.*startup_cache_index_check: 1 failed" + FAIL_REGULAR_EXPRESSION "FAIL: \\([b-h]\\)") # The same header without a GPU (src/startup_stubs/null_texture_view.h): fake adapters that lack # or have each use, R8G8B8A8 with one use, only B8G8R8A8, and failed queries. WARP has both uses, so # only this check reaches the rewrite on CI. The mutated run is the negative control. diff --git a/docs/experiments/native-fixed-mesh57.md b/docs/experiments/native-fixed-mesh57.md index aa73960277..008b6b5243 100644 --- a/docs/experiments/native-fixed-mesh57.md +++ b/docs/experiments/native-fixed-mesh57.md @@ -25,7 +25,7 @@ The `native_fixed_mesh57_waterfall_{warp,hardware}` fixture draws a triangle cov Set `X2W_SHADER_CACHE` to the request cache and `X2W_MESH57_CAPTURE_STATE=1` to retain the fixed creation state when a matching root consumes a mesh pipeline. A `req_.s57` file contains the little-endian 64-bit stage/root request key, three little-endian 32-bit lengths, and the corresponding byte spans for the normalized descriptor, register block A and register block B. For the base layout the stand-in clears the captured root and span pointer fields at DWORD-pair indices 0, 1, 3, 5 and 13. It preserves the lengths and other fields. The variant key extends the existing stage/root key with those three length-prefixed spans. Distinct fixed states can coexist for one stage pair. The fixture overwrites both blocks after creation and checks their archived bytes for accepted and refused variants. -Native preparation reads a separately reviewed `.mesh57-state` profile from the cache. Its versioned Windows x64 header is defined by `Mesh57Profile` in `src/startup_stubs/mesh57_profile.h`. The header supplies the MS entry layout and desktop fixed-function state. The file ends with the normalized descriptor, register blocks, serialized root and both guest programs. The stand-in compares every byte before building a PSO. The fixture authors this profile from its own known inputs. A captured register block alone does not establish the desktop rasterizer state or MS entry layout. +Native preparation reads a separately reviewed `.mesh57-state` profile from the cache. The stand-in lists the cache's top-level file names once per process, at the first profile lookup (`src/startup_stubs/cache_index.h`), and opens a profile only when that listing has its name. A profile written while the process runs is read by the next process. Its versioned Windows x64 header is defined by `Mesh57Profile` in `src/startup_stubs/mesh57_profile.h`. The header supplies the MS entry layout and desktop fixed-function state. The file ends with the normalized descriptor, register blocks, serialized root and both guest programs. The stand-in compares every byte before building a PSO. The fixture authors this profile from its own known inputs. A captured register block alone does not establish the desktop rasterizer state or MS entry layout. For the recognized 0x300-byte fixed layout, the variant key ignores relocation of the two shader record blocks and retains their relative offsets. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index ecf3ba26d3..766bf2c5cd 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1652,7 +1652,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_D3D12_PERMISSIVE=1` | wraps the device: recording command lists, console present, view tracking; on a runtime without shader model 6.6 (in-box Windows 10), root signatures with the heap-indexing flags (`0xC00`) are serialized again without them, and the copy kept for shader translation gets that call's bits back when `CreateRootSignature` receives the returned blob's own buffer (a copy of the bytes keeps the desktop flags; `d3d12_xs_shim_heap_indexing`). The retry runs only on runtimes that refuse the flags (before shader model 6.6); where the runtime accepts them, `d3d12_xs_shim_heap_indexing` reports a capability skip (77) | | `X2W_D3D12_RENDER=1` | draws through translated pipelines from `X2W_SHADER_CACHE` and forwards [single-record indirect Dispatch](experiments.md#gpu-written-indirect-dispatch-arguments), [DrawIndexed](experiments.md#gpu-written-indirect-indexed-draw-arguments), [Draw](experiments.md#gpu-written-indirect-draw-arguments), and [DispatchMesh](experiments.md#gpu-written-indirect-mesh-dispatch-arguments) for supported desktop pipelines and tracked placed buffers | | `X2W_DRAW_MISSING_SHADER=1` | records a [diagnostic fallback draw](experiments/missing-shader-fallback.md) for direct, non-indexed triangle lists while the requested translation manifest is absent. Requires single-sample attachments and a guest viewport and scissor. The shader pair leaves the attachments untouched. The render totals report `missing shader fallback draws`. | -| `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}`, when needed RTV variants `req_.rtv`, and for device slot 67 compute pipelines `req_.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. | +| `X2W_SHADER_CACHE=` | translation cache: the runtime writes source requests `req_.{a,b,root}`, when needed RTV variants `req_.rtv`, and for device slot 67 compute pipelines `req_.{desc,sa,sb,data,root,c67}` (see [Compute pipeline requests](#compute-pipeline-requests)). A console pipeline that an `ExecuteIndirect` draw (list slot 61) refuses writes the same request as a direct draw, once per pipeline, and draws nothing (`startup_indirect_requests_warp`). Only direct draws poll for its manifest, so such a pipeline stays in the `missing` count until a direct draw uses it; the `x2w-render totals` line counts `pipelines first looked up by ExecuteIndirect N`. This is a per-process lookup count. Check for the ready marker `req_.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending ` while the process is running, or start the run with `run.ps1 -Translate` (see [Translating shaders during a run](#translating-shaders-during-a-run)). Active draws poll for an absent manifest at most once per second per pipeline and use the published translation on a subsequent draw. The translator compiles `.vs.cso` and `.ps.cso` with `fxc.exe`: `X2W_FXC`, else the Windows SDK 10.0.26100.0 copy, else the newest `Windows Kits\10\bin\\x64`, else `PATH`. When none exists it writes `.fail` naming `X2W_FXC` without publishing a new manifest. `X2W_FXC=` (empty) publishes the manifest alone. Rerun `--pending` with compilation enabled to fill in missing bytecode for an existing manifest. At its first native slot-57 profile lookup the runtime lists the directory's top-level file names once and logs `x2w-draw cache index: names in ms` (`src/startup_stubs/cache_index.h`). A `.mesh57-state` profile is opened only when that listing has its name, so a profile written while the process runs is read by the next process. Manifests and every other cache file are still looked up on disk. | | `X2W_NATIVE_SHADERS=` (`run.ps1 -NativeShaders `) | experimental, in render mode: translates device slot 67 compute requests in the stand-in with the C++ compiler; `` holds `dxcompiler.dll` and `dxil.dll`. See [Translating compute programs in the stand-in](#translating-compute-programs-in-the-stand-in) | | `X2W_D3D12_LINEAR_BUFFERS=1` or `=copy` | opt-in backing for linear buffers placed at a title address (device slot 133, initial state `COMMON`): shared where the adapter, extent and memory allow it (private allocations larger than 256 MiB are skipped only with `X2W_D3D12_CAP_EXISTING_HEAP=1`), otherwise copied from title memory at each submission, otherwise the default backing is kept and the refusal recorded; `copy` never shares. Unset or `0`, slot 133 keeps its default backing. See [Linear buffer backing (device slot 133, opt-in)](#linear-buffer-backing-device-slot-133-opt-in) | | `X2W_D3D12_CAP_EXISTING_HEAP=1` | opt-in 256 MiB (`unplaced_existing_heap_allowed`) allocation-size cap on `OpenExistingHeapFromAddress` in device slot 133 (`startup_slot133_heap_cap_*`). Unset (default), private allocations larger than 256 MiB keep the formerly aliased path: a capped copied placement is refused by `CopyBufferRegion` (list slot 15) as `title_backed_source`, losing a late guest write made after recording and before submit. Set, allocations larger than 256 MiB skip `OpenExistingHeapFromAddress` so multi-GiB startup blocks are not pinned in `WorkingSetSize` and `NonLocal` GPU memory | diff --git a/src/startup_stubs/cache_index.h b/src/startup_stubs/cache_index.h new file mode 100644 index 0000000000..a8bd672460 --- /dev/null +++ b/src/startup_stubs/cache_index.h @@ -0,0 +1,201 @@ +// Experimental (docs/startup-runtime.md, X2W_SHADER_CACHE): one listing of the shader cache's top-level files, so +// that looking up a name that is not there costs no file-system call. +// +// Under Wine, opening a missing name in a cache directory with ~274k entries costs ~155 ms, because the +// case-insensitive lookup reads the whole directory. CacheNameIndex keeps the FNV-1a-64 hash of each +// ASCII-lowercased name in a sorted vector, never the names (8 bytes per name). Windows and Wine match the cache's +// ASCII names case-insensitively, and so does the index. A hash collision can only report a missing name as +// present: the caller then opens it and takes its missing-file path. A listed name is never reported absent. +// +// CacheDirectoryIndex lists one directory once, at its first lookup (std::call_once; FindFirstFileExW on +// "\*", files only, so names in subdirectories are not indexed). A lookup answers present, absent or +// unknown. unknown means "look on disk": the listing failed (any error but ERROR_FILE_NOT_FOUND, including a +// missing directory), or the lookup names a directory other than the listed one. A file that another process +// creates after the listing reads absent until the next process starts. add() records the caller's own writes, and +// count_contradiction() counts a write that found a file the index had reported absent. +#pragma once + +#include +#include +#include +#include + +namespace x2w_startup { + +inline wchar_t cache_name_fold(wchar_t c) noexcept +{ + return c >= L'A' && c <= L'Z' ? static_cast(c - L'A' + L'a') : c; +} + +// FNV-1a-64 over the folded name's UTF-16 code units, low byte first. +inline std::uint64_t cache_name_hash(const wchar_t* name) noexcept +{ + std::uint64_t hash = 1469598103934665603ull; + for (; *name; ++name) { + const auto unit = static_cast(cache_name_fold(*name)) & 0xffffu; + hash = (hash ^ (unit & 0xffu)) * 1099511628211ull; + hash = (hash ^ (unit >> 8)) * 1099511628211ull; + } + return hash; +} + +// add() every name, then seal() once; contains() and size() answer for the sealed set. +class CacheNameIndex { +public: + void add(const wchar_t* name) { hashes_.push_back(cache_name_hash(name)); } + void seal() + { + std::sort(hashes_.begin(), hashes_.end()); + hashes_.erase(std::unique(hashes_.begin(), hashes_.end()), hashes_.end()); + } + bool contains(const wchar_t* name) const noexcept + { + return std::binary_search(hashes_.begin(), hashes_.end(), cache_name_hash(name)); + } + std::size_t size() const noexcept { return hashes_.size(); } + void clear() noexcept { hashes_.clear(); hashes_.shrink_to_fit(); } + +private: + std::vector hashes_; +}; + +} // namespace x2w_startup + +#ifdef _WIN32 +#include +#include +#include +#include + +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +namespace x2w_startup { + +enum class CacheLookup : unsigned char { absent, present, unknown }; + +class CacheDirectoryIndex { +public: + CacheDirectoryIndex() = default; + CacheDirectoryIndex(const CacheDirectoryIndex&) = delete; + CacheDirectoryIndex& operator=(const CacheDirectoryIndex&) = delete; + + // Whether \ exists. The first call lists directory; *listed_now is set for that one call, so + // its caller can log the listing. + CacheLookup lookup(const wchar_t* directory, const wchar_t* name, bool* listed_now = nullptr) noexcept + { + if (listed_now) *listed_now = false; + try { + std::call_once(once_, [&] { + list(directory); + if (listed_now) *listed_now = true; + }); + } catch (...) { + return CacheLookup::unknown; + } + if (!ready_.load(std::memory_order_acquire) || !same_directory(directory)) return CacheLookup::unknown; + if (listed_.contains(name)) return CacheLookup::present; + SharedLock guard(lock_); + return written_.count(cache_name_hash(name)) ? CacheLookup::present : CacheLookup::absent; + } + + // A file the caller created in the listed directory, after or during the listing. + void add(const wchar_t* name) noexcept + { + try { + ExclusiveLock guard(lock_); + written_.insert(cache_name_hash(name)); + } catch (...) { + // The name keeps its listed answer. + } + } + + // A write found a file that the index had reported absent: another writer created it after the listing. + void count_contradiction() noexcept { InterlockedIncrement(&contradictions_); } + LONG contradictions() const noexcept { return contradictions_; } + + // The listing, once lookup() has made it: usable, number of distinct names, time taken, and the error that + // made it unusable (0 when usable). + bool ready() const noexcept { return ready_.load(std::memory_order_acquire); } + std::size_t names() const noexcept { return ready() ? listed_.size() : 0; } + unsigned long long listing_ms() const noexcept { return listing_ms_.load(std::memory_order_acquire); } + DWORD listing_error() const noexcept { return listing_error_.load(std::memory_order_acquire); } + +private: + struct SharedLock { + explicit SharedLock(SRWLOCK& lock) : lock(lock) { AcquireSRWLockShared(&lock); } + ~SharedLock() { ReleaseSRWLockShared(&lock); } + SRWLOCK& lock; + }; + struct ExclusiveLock { + explicit ExclusiveLock(SRWLOCK& lock) : lock(lock) { AcquireSRWLockExclusive(&lock); } + ~ExclusiveLock() { ReleaseSRWLockExclusive(&lock); } + SRWLOCK& lock; + }; + + bool same_directory(const wchar_t* directory) const noexcept + { + std::size_t i = 0; + for (; directory[i]; ++i) + if (i == directory_.size() || cache_name_fold(directory[i]) != directory_[i]) return false; + return i == directory_.size(); + } + + void list(const wchar_t* directory) noexcept + { + LARGE_INTEGER start{}, end{}, frequency{}; + QueryPerformanceCounter(&start); + DWORD error = ERROR_SUCCESS; + try { + directory_ = directory; + for (auto& c : directory_) c = cache_name_fold(c); + const std::wstring mask = std::wstring(directory) + L"\\*"; + WIN32_FIND_DATAW found; + const HANDLE find = FindFirstFileExW(mask.c_str(), FindExInfoBasic, &found, FindExSearchNameMatch, nullptr, + FIND_FIRST_EX_LARGE_FETCH); + if (find == INVALID_HANDLE_VALUE) { + error = GetLastError(); + if (error == ERROR_FILE_NOT_FOUND) error = ERROR_SUCCESS; // no entry at all: an empty listing + } else { + try { + do { + if (!(found.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) listed_.add(found.cFileName); + } while (FindNextFileW(find, &found)); + error = GetLastError(); + if (error == ERROR_NO_MORE_FILES) error = ERROR_SUCCESS; + } catch (...) { + error = ERROR_NOT_ENOUGH_MEMORY; + } + FindClose(find); + } + if (error == ERROR_SUCCESS) listed_.seal(); + } catch (...) { + error = ERROR_NOT_ENOUGH_MEMORY; + } + if (error != ERROR_SUCCESS) listed_.clear(); + QueryPerformanceCounter(&end); + QueryPerformanceFrequency(&frequency); + listing_ms_.store(static_cast((end.QuadPart - start.QuadPart) * 1000 / frequency.QuadPart), + std::memory_order_release); + listing_error_.store(error, std::memory_order_release); + ready_.store(error == ERROR_SUCCESS, std::memory_order_release); + } + + std::once_flag once_; + std::atomic ready_{false}; + std::atomic listing_ms_{0}; + std::atomic listing_error_{0}; + std::wstring directory_; // folded + CacheNameIndex listed_; + mutable SRWLOCK lock_ = SRWLOCK_INIT; // leaf lock for written_; never held across I/O + std::unordered_set written_; + volatile LONG contradictions_ = 0; +}; + +} // namespace x2w_startup +#endif diff --git a/src/startup_stubs/d3d12_draw.inl b/src/startup_stubs/d3d12_draw.inl index 1933d5f78e..5a0beeba9d 100644 --- a/src/startup_stubs/d3d12_draw.inl +++ b/src/startup_stubs/d3d12_draw.inl @@ -258,6 +258,32 @@ bool cache_path(wchar_t* out, const wchar_t* prefix, u64 key, const wchar_t* ext return true; } +// X2W_SHADER_CACHE's top-level names, listed at the first cache_lookup (src/startup_stubs/cache_index.h). +x2w_startup::CacheDirectoryIndex& cache_index() +{ + static x2w_startup::CacheDirectoryIndex index; + return index; +} + +// Whether the file cache_path would name exists, by the listing: absent needs no file-system call, and unknown +// (no usable listing) means look on disk. +x2w_startup::CacheLookup cache_lookup(const wchar_t* prefix, u64 key, const wchar_t* extension) +{ + wchar_t dir[MAX_PATH], name[MAX_PATH]; + const DWORD n = GetEnvironmentVariableW(L"X2W_SHADER_CACHE", dir, MAX_PATH); + if (!n || n >= MAX_PATH) return x2w_startup::CacheLookup::unknown; + swprintf(name, MAX_PATH, L"%s%016llx%s", prefix, key, extension); + auto& index = cache_index(); + bool listed_now = false; + const auto result = index.lookup(dir, name, &listed_now); + if (listed_now && index.ready()) + log("x2w-draw cache index: %zu names in %llu ms", index.names(), index.listing_ms()); + else if (listed_now) + log("x2w-draw cache index: listing failed with error %lu after %llu ms; lookups use the disk", + static_cast(index.listing_error()), index.listing_ms()); + return result; +} + bool read_text(const wchar_t* path, std::string& out) { HANDLE file = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); diff --git a/src/startup_stubs/d3d12_xs_device.cpp b/src/startup_stubs/d3d12_xs_device.cpp index 56dbe26c48..50bcad4451 100644 --- a/src/startup_stubs/d3d12_xs_device.cpp +++ b/src/startup_stubs/d3d12_xs_device.cpp @@ -23,6 +23,7 @@ #include "startup_stubs/overlay_window.h" #include "startup_stubs/draw_bmp.h" #include "startup_stubs/mesh57_profile.h" +#include "startup_stubs/cache_index.h" #include "startup_stubs/draw_dump_tracking.h" #include "startup_stubs/present_readback_state.h" #include "startup_stubs/pixel_history.h" diff --git a/src/startup_stubs/native_mesh57.inl b/src/startup_stubs/native_mesh57.inl index b8455b82d3..c370718147 100644 --- a/src/startup_stubs/native_mesh57.inl +++ b/src/startup_stubs/native_mesh57.inl @@ -212,6 +212,15 @@ const char* bind_mesh57_buffers(Wrapper* self, Pass& pass, ID3D12GraphicsCommand if (!reads.empty()) list->SetGraphicsRootDescriptorTable(1, gpu); return nullptr; } +// Slot-57 profile lookups that reached the cache, and the ones that opened the file (fixtures read both). +LONG mesh57_profile_lookups, mesh57_profile_opens; + +extern "C" __declspec(dllexport) void x2w_d3d12_mesh57_profile_stats(LONG* lookups, LONG* opens) +{ + if (lookups) *lookups = mesh57_profile_lookups; + if (opens) *opens = mesh57_profile_opens; +} + #ifdef X2W_NATIVE_SHADERS void prepare_native_mesh57(Wrapper* pipeline) { @@ -244,6 +253,12 @@ void prepare_native_mesh57(Wrapper* pipeline) const auto variant = fnv_part(info->state_b, fnv_part(info->state_a, fnv_part(normalized, key))); if (!cache_path(path, L"", variant, L".mesh57-state")) return; + InterlockedIncrement(&mesh57_profile_lookups); + // Profiles are placed before the process starts and most creations have none: skip the open when the + // cache listing has no such name. A profile written while the process runs is read by the next one. + if (cache_lookup(L"", variant, L".mesh57-state") == x2w_startup::CacheLookup::absent) + return; + InterlockedIncrement(&mesh57_profile_opens); std::ifstream file(std::filesystem::path(path), std::ios::binary); if (!file) return; diff --git a/tests/startup_cache_index_check.cpp b/tests/startup_cache_index_check.cpp new file mode 100644 index 0000000000..c64a804d1e --- /dev/null +++ b/tests/startup_cache_index_check.cpp @@ -0,0 +1,232 @@ +// Checks src/startup_stubs/cache_index.h without a device. prepare_native_mesh57 asks the index before it opens +// .mesh57-state, and opens the file only for present or unknown. The cache directory holds 2000 other +// cache files, names that look like profiles, a subdirectory and a directory with a profile's name. +// (a) 514 lookups of missing profiles probe the disk 0 times; (b) present profiles, any ASCII case, are read; +// (c) one listing of the top-level files only; (d) other directories and subdirectories: unknown; +// (e) add() and the contradiction counter; (f) an empty directory lists empty, a missing one +// is unknown; (g) concurrent first lookups list once and agree; (h) the name hash and the sorted set. +// --mutate per-call probes the disk for every name, as the stand-in did before the index; it must fail (a) only. +// --measure lists once and opens one missing name there, timing both; it changes nothing. +#include "startup_stubs/cache_index.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace fs = std::filesystem; +using x2w_startup::CacheLookup; +using Clock = std::chrono::steady_clock; + +bool per_call = false; +int failures = 0; + +void fail(const char* part, const std::string& what) +{ + std::printf("FAIL: (%s) %s\n", part, what.c_str()); + ++failures; +} + +unsigned long long key(unsigned long long seed) +{ + return (seed + 1) * 0x9e3779b97f4a7c15ull; +} + +// The name cache_lookup(L"", variant, L".mesh57-state") asks for. +std::wstring profile(unsigned long long variant) +{ + wchar_t name[64]; + std::swprintf(name, 64, L"%016llx.mesh57-state", variant); + return name; +} + +void write(const fs::path& path, const std::string& bytes) +{ + std::ofstream(path, std::ios::binary) << bytes; +} + +// What prepare_native_mesh57 does: skip the open when the index says absent, else open the file. +bool load(x2w_startup::CacheDirectoryIndex& index, const fs::path& directory, const std::wstring& name, + std::string& bytes, unsigned& probes) +{ + if (!per_call && index.lookup(directory.c_str(), name.c_str()) == CacheLookup::absent) return false; + ++probes; + std::ifstream file(directory / name, std::ios::binary); + if (!file) return false; + bytes.assign(std::istreambuf_iterator(file), {}); + return true; +} + +const char* text(CacheLookup lookup) +{ + return lookup == CacheLookup::absent ? "absent" : lookup == CacheLookup::present ? "present" : "unknown"; +} + +void expect(const char* part, x2w_startup::CacheDirectoryIndex& index, const fs::path& directory, + const std::wstring& name, CacheLookup expected) +{ + const auto got = index.lookup(directory.c_str(), name.c_str()); + if (got != expected) { + char narrow[96]; + std::snprintf(narrow, sizeof(narrow), "%ls", name.c_str()); + fail(part, std::string(narrow) + " is " + text(got) + ", expected " + text(expected)); + } +} + +int measure(const fs::path& directory) +{ + x2w_startup::CacheDirectoryIndex index; + const auto missing = profile(0xfedcba9876543210ull); + auto start = Clock::now(); + const auto first = index.lookup(directory.c_str(), missing.c_str()); + const double listing = std::chrono::duration(Clock::now() - start).count(); + start = Clock::now(); + const auto second = index.lookup(directory.c_str(), missing.c_str()); + const double lookup = std::chrono::duration(Clock::now() - start).count(); + start = Clock::now(); + const bool opened = static_cast(std::ifstream(directory / missing, std::ios::binary)); + const double open = std::chrono::duration(Clock::now() - start).count(); + std::printf("measure: listing %zu names (error %lu, own timer %llu ms): first lookup %s in %.1f ms, second %s in " + "%.3f ms; one missing-name open %s in %.1f ms\n", index.names(), + static_cast(index.listing_error()), index.listing_ms(), text(first), listing, + text(second), lookup, opened ? "opened" : "failed", open); + return 0; +} + +} // namespace + +int main(int argc, char** argv) +{ + if (argc == 3 && std::strcmp(argv[1], "--measure") == 0) return measure(argv[2]); + if (argc == 3 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "per-call") == 0) { + per_call = true; + } else if (argc != 1) { + return 2; + } + // Windows recycles process IDs; never reuse an old directory. + const auto prefix = "cache-index-" + std::to_string(GetCurrentProcessId()) + "-"; + fs::path cache; + for (unsigned attempt = 0;; ++attempt) { + cache = fs::current_path() / (prefix + std::to_string(attempt)); + if (fs::create_directory(cache)) break; + } + // 2000 other cache files, as cache_path names them. + const wchar_t* const others[]{L"req_%016llx.c67", L"%016llx.txt", L"%016llx.cs.cso", L"req_%016llx.ia"}; + for (unsigned i = 0; i < 2000; ++i) { + wchar_t name[64]; + std::swprintf(name, 64, others[i % 4], key(i)); + write(cache / name, "x"); + } + // Names that look like profiles but are none a lookup below asks for: a short variant, a non-hex name and a + // profile name with another extension. A directory with a profile's name, and a profile in a subdirectory. + const auto as_directory = key(7000), other_extension = key(7001), nested = key(7002); + write(cache / L"0123456789abcde.mesh57-state", "short"); + write(cache / L"zz.mesh57-state", "not hex"); + write(cache / (profile(other_extension) + L".tmp"), "tmp"); + fs::create_directory(cache / profile(as_directory)); + fs::create_directory(cache / L"sub"); + write(cache / L"sub" / profile(nested), "nested"); + // Two reviewed profiles: one as cache_path spells it, one with upper-case hex and extension on disk. + const auto lower = key(8000), upper = key(8001); + write(cache / profile(lower), "profile lower"); + wchar_t upper_name[64]; + std::swprintf(upper_name, 64, L"%016llX.MESH57-STATE", upper); + write(cache / upper_name, "profile upper"); + const std::size_t files = 2000 + 3 + 2; + + x2w_startup::CacheDirectoryIndex index; + std::string bytes; + unsigned probes = 0; + for (unsigned i = 0; i < 512; ++i) + if (load(index, cache, profile(key(9000 + i)), bytes, probes)) fail("a", "loaded a missing profile"); + for (const auto variant : {as_directory, other_extension, nested}) + if (load(index, cache, profile(variant), bytes, probes)) fail("a", "loaded a decoy"); + if (probes) fail("a", std::to_string(probes) + " disk probes for 515 lookups of missing profiles, expected 0"); + std::printf("(a) 515 lookups of missing profiles: %u disk probes\n", probes); + + probes = 0; + if (!load(index, cache, profile(lower), bytes, probes) || bytes != "profile lower") + fail("b", "lower-case profile not read"); + if (!load(index, cache, profile(upper), bytes, probes) || bytes != "profile upper") + fail("b", "upper-case profile not read through its lower-case name"); + expect("b", index, cache, L"ZZ.MESH57-STATE", CacheLookup::present); + expect("b", index, cache, L"0123456789ABCDE.mesh57-state", CacheLookup::present); + std::printf("(b) 2 present profiles: %u disk probes, both read\n", probes); + + if (!index.ready() || index.names() != files || index.listing_error()) + fail("c", "listing ready " + std::to_string(index.ready()) + ", " + std::to_string(index.names()) + + " names (expected " + std::to_string(files) + "), error " + std::to_string(index.listing_error())); + expect("c", index, cache, L"sub", CacheLookup::absent); + std::printf("(c) one listing: %zu names in %llu ms\n", index.names(), index.listing_ms()); + + expect("d", index, cache / L"sub", profile(nested), CacheLookup::unknown); + expect("d", index, cache / L"missing", profile(lower), CacheLookup::unknown); + expect("d", index, fs::path(cache.wstring() + L"X"), profile(lower), CacheLookup::unknown); + auto upper_directory = cache.wstring(); + for (auto& c : upper_directory) c = static_cast(std::towupper(c)); + expect("d", index, fs::path(upper_directory), profile(lower), CacheLookup::present); + + const auto late = key(8002); + write(cache / profile(late), "profile late"); + expect("e", index, cache, profile(late), CacheLookup::absent); + index.add(profile(late).c_str()); + expect("e", index, cache, profile(late), CacheLookup::present); + expect("e", index, cache, profile(key(8003)), CacheLookup::absent); + index.count_contradiction(); + index.count_contradiction(); + if (index.contradictions() != 2) fail("e", std::to_string(index.contradictions()) + " contradictions, expected 2"); + + const auto empty = cache / L"empty"; + fs::create_directory(empty); + x2w_startup::CacheDirectoryIndex empty_index; + expect("f", empty_index, empty, profile(lower), CacheLookup::absent); + if (!empty_index.ready() || empty_index.names()) fail("f", "the empty directory's listing is not ready and empty"); + x2w_startup::CacheDirectoryIndex missing_index; + expect("f", missing_index, cache / L"missing", profile(lower), CacheLookup::unknown); + if (missing_index.ready() || !missing_index.listing_error()) + fail("f", "a missing directory gave a usable listing"); + std::printf("(f) missing directory: listing error %lu, lookups unknown\n", + static_cast(missing_index.listing_error())); + + x2w_startup::CacheDirectoryIndex shared; + std::atomic wrong{0}, listed{0}; + std::vector threads; + for (unsigned t = 0; t < 8; ++t) + threads.emplace_back([&, t] { + for (unsigned i = 0; i < 256; ++i) { + const bool present = (i + t) % 16 == 0; + bool listed_now = false; + const auto got = shared.lookup(cache.c_str(), profile(present ? lower : key(20000 + 256 * t + i)).c_str(), + &listed_now); + listed += listed_now; + if (got != (present ? CacheLookup::present : CacheLookup::absent)) ++wrong; + } + }); + for (auto& thread : threads) thread.join(); + if (wrong || listed != 1) fail("g", std::to_string(wrong.load()) + " wrong answers, " + std::to_string(listed.load()) + + " calls reported the listing"); + + if (x2w_startup::cache_name_hash(L"Req_ABCDEF.C67") != x2w_startup::cache_name_hash(L"req_abcdef.c67") || + x2w_startup::cache_name_hash(L"req_abcdef.c67") == x2w_startup::cache_name_hash(L"req_abcdeg.c67") || + x2w_startup::cache_name_hash(L"ab") == x2w_startup::cache_name_hash(L"ba")) + fail("h", "name hash folds the wrong characters or ignores order"); + x2w_startup::CacheNameIndex names; + for (const auto* name : {L"b.txt", L"A.TXT", L"a.txt", L"c.txt"}) names.add(name); + names.seal(); + if (names.size() != 3 || !names.contains(L"a.txt") || !names.contains(L"B.TXT") || names.contains(L"d.txt")) + fail("h", "sorted name set gives the wrong answers (" + std::to_string(names.size()) + " names)"); + + std::printf("startup_cache_index_check: %d failed\n", failures); + if (!failures) fs::remove_all(cache); + return failures ? 1 : 0; +} diff --git a/tests/startup_indirect_draw_indexed.cpp b/tests/startup_indirect_draw_indexed.cpp index 2cc49b9dc1..e4fa387b6e 100644 --- a/tests/startup_indirect_draw_indexed.cpp +++ b/tests/startup_indirect_draw_indexed.cpp @@ -33,6 +33,7 @@ extern "C" __declspec(dllimport) HRESULT WINAPI D3D12XboxCreateDevice(IUnknown*, const void*, REFIID, void**); extern "C" __declspec(dllimport) BOOL x2w_d3d12_distinct_rect_scratch(void*, void*); extern "C" __declspec(dllimport) std::size_t x2w_d3d12_census_report(char* out, std::size_t capacity); +extern "C" __declspec(dllimport) void x2w_d3d12_mesh57_profile_stats(LONG* lookups, LONG* opens); #if defined(OFFSCREEN_AGILITY_620) extern "C" { @@ -2069,6 +2070,13 @@ static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, if (std::filesystem::create_directory(cache)) break; } check(SetEnvironmentVariableW(L"X2W_SHADER_CACHE", cache.c_str()) ? S_OK : E_FAIL, "native mesh cache"); + // 2000 other cache files: the profile lookups below must not open a name the cache does not hold. + for (UINT64 i = 0; i < 2000; ++i) { + static const char* const others[]{"req_%016llx.c67", "%016llx.txt", "%016llx.cs.cso", "req_%016llx.ia"}; + char other[64]; + std::snprintf(other, sizeof(other), others[i % 4], (i + 1) * 0x9e3779b97f4a7c15ull); + std::ofstream(cache / other, std::ios::binary) << "x"; + } ComPtr blob; D3D12_ROOT_SIGNATURE_DESC empty{}; D3D12_ROOT_PARAMETER params[5]{}; @@ -2262,6 +2270,17 @@ static int native_fixed_mesh_fixture(ID3D12Device* device, ID3D12Device* guest, const auto pso = create(); fields[15] = 1; // Same stages and root, unreviewed fixed pipeline state. const auto mismatched = create(); + // 64 more fixed states without a profile. Only the two profiles above may be opened. + for (UINT64 extra = 2; extra < 66; ++extra) { + fields[15] = extra; + create(); + } + fields[15] = 1; + LONG lookups = -1, opens = -1; + x2w_d3d12_mesh57_profile_stats(&lookups, &opens); + std::printf("native fixed mesh profile lookups %ld, opens %ld (2 profiles, 2000 other cache files)\n", lookups, opens); + if (lookups != 66 || opens != 2) + return 1; state_a.fill(0); state_b.fill(0); check(SetEnvironmentVariableA("X2W_MESH57_CAPTURE_STATE", "1") ? S_OK : E_FAIL, "enable fixed-state archive");