Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion docs/experiments/native-fixed-mesh57.md
Original file line number Diff line number Diff line change
Expand Up @@ -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_<variant>.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 `<variant>.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 `<variant>.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.
Expand Down
2 changes: 1 addition & 1 deletion docs/startup-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<dir>` | translation cache: the runtime writes source requests `req_<key>.{a,b,root}`, when needed RTV variants `req_<key>.rtv`, and for device slot 67 compute pipelines `req_<key>.{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_<key>.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending <dir>` 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\<version>\x64`, else `PATH`. When none exists it writes `<key>.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=<dir>` | translation cache: the runtime writes source requests `req_<key>.{a,b,root}`, when needed RTV variants `req_<key>.rtv`, and for device slot 67 compute pipelines `req_<key>.{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_<key>.a` to confirm a complete request is available. Run `tools/startup/gfx2hlsl.py --pending <dir>` 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\<version>\x64`, else `PATH`. When none exists it writes `<key>.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: <n> names in <ms> ms` (`src/startup_stubs/cache_index.h`). A `<variant>.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=<dir>` (`run.ps1 -NativeShaders <dir>`) | experimental, in render mode: translates device slot 67 compute requests in the stand-in with the C++ compiler; `<dir>` 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 |
Expand Down
201 changes: 201 additions & 0 deletions src/startup_stubs/cache_index.h
Original file line number Diff line number Diff line change
@@ -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
// "<directory>\*", 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 <algorithm>
#include <cstddef>
#include <cstdint>
#include <vector>

namespace x2w_startup {

inline wchar_t cache_name_fold(wchar_t c) noexcept
{
return c >= L'A' && c <= L'Z' ? static_cast<wchar_t>(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<std::uint32_t>(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<std::uint64_t> hashes_;
};

} // namespace x2w_startup

#ifdef _WIN32
#include <atomic>
#include <mutex>
#include <string>
#include <unordered_set>

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>

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 <directory>\<name> 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<unsigned long long>((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<bool> ready_{false};
std::atomic<unsigned long long> listing_ms_{0};
std::atomic<DWORD> 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<std::uint64_t> written_;
volatile LONG contradictions_ = 0;
};

} // namespace x2w_startup
#endif
Loading
Loading