diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index e843d8debc..81a8a44215 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2719,7 +2719,11 @@ Pipeline creation: a device loss or a kill never reaches teardown, so neither file used to keep that boot's compute pipelines. Compute pipelines are therefore journaled one file each (`src/pipeline_cache_journal.h`): `pipeline_cache.d/cs-.bin` beside the session file, named by a hash of the SPIR-V words, the stage flags and - subgroup request, the push-constant range and the bindless layout. A build creates a `VkPipelineCache` from its + subgroup request, the push-constant range and the bindless layout. Each file is a 24-byte stamp (`LPJ1`, then a + hash of the gta6rt executable that wrote it and a hash of the device-create config it was written under: + extensions, feature bits, the NVIDIA diagnostics config and its flags, `src/vulkan_device_config.h`) followed by + the cache blob; files an older runtime wrote have no stamp + and are read as before. A build creates a `VkPipelineCache` from its file (if the header names this device and pipeline-cache UUID) and creates the pipeline against it; when the driver reports a compile (creation feedback without `APPLICATION_PIPELINE_CACHE_HIT`, or no file), that cache is written back to the file at once, through a staging file renamed over it. Without a file, and with @@ -2754,7 +2758,19 @@ Pipeline creation: LEONIDA_SHADERS, LEONIDA_PIPELINE_CACHE_DIR, and LEONIDA_DEVICE_FAULT/LEONIDA_AFTERMATH, whose diagnostics config makes other pipelines) and builds every compute entry of the library through the dispatch path (`build_compute_pipeline`), largest first, on below-normal-priority threads. Entries with a usable journal file are - skipped (only their header is read), so it can be stopped and started again. Running as gta6rt.exe it also fills + skipped (only their stamp and header are read), so it can be stopped and started again. Only files this gta6rt + binary wrote under this device-create config count as done: on NVIDIA 621.40 a rebuilt runtime was measured getting few hits from another build's + files (#1608), so a file from another build, or one without a stamp, is built against again. A hit takes + milliseconds and the file is then stamped as this build's; a miss is compiled and the file rewritten. The run's last + lines say how many files came from another build and how many of them the driver still took, and the runtime's + journal lines count them too (`from another build: N, M of them found`). Files this build wrote under another + device-create config are handled the same way and counted apart (`from another device config`). NVIDIA's + diagnostics config (`LEONIDA_DEVICE_FAULT=1`, `LEONIDA_AFTERMATH=1`) also names its pipelines apart; on NVIDIA + 621.01 a journal precompiled without it gave a boot with it 0 of 10 pipelines from the journal (10 compiled), and + 10 of 10 when both matched. So a pipeline with no file that has one under the other setting is reported, by the + precompiler and once at boot (`only under the other diagnostics config setting: N`): run the precompiler with the + boot's `LEONIDA_DEVICE_FAULT` / `LEONIDA_AFTERMATH`. `LEONIDA_PIPELINE_JOURNAL_BUILD=` stands in for the + executable's hash (tests). Running as gta6rt.exe it also fills NVIDIA's disk cache, which that driver keys by the executable's name. Measured on an RTX 4070 Ti (driver 630.20), 4 threads: modules of 3.6-5.8 MB took 46-145 s each, 12 in 312 s, about 3.5 GB of host memory each while in the driver (14.5 GB peak for four). Graphics pipelines are not covered: they are built at a title's draw from its PSO diff --git a/docs/running.md b/docs/running.md index 3b71966d95..88618f17e3 100644 --- a/docs/running.md +++ b/docs/running.md @@ -51,7 +51,11 @@ reasons behind each step: [linux_proton.md](linux_proton.md#amd-on-linux-what-go `LEONIDA_SHADERS`, `LEONIDA_PIPELINE_CACHE_DIR` and `LEONIDA_DEVICE_FAULT`, before the first run. It built 3,693 compute pipelines. Not `make_game.py --stages pipelines`: its cache never matches the runtime's driver keys. The pre-compile builds the programs `LEONIDA_SKIP_COMPUTE` names too (`--skip-listed` leaves them out) and ends - with one line that counts what it built, what was journaled already and what it left out. + with one line that counts what it built, what was journaled already and what it left out. After a rebuild of + gta6rt, run it again: files another build wrote are not counted as journaled already, and it says how many of them + the driver still took. Run it with the same `LEONIDA_DEVICE_FAULT` and `LEONIDA_AFTERMATH` as the boot: NVIDIA's + diagnostics config (`LEONIDA_DEVICE_FAULT=1`) compiles other pipelines, and a journal made without it gives such a + boot no hits. - **Driver and OS:** `amdgpu.lockup_timeout=30000,60000,10000,10000` on the kernel command line (the default is 2000 ms; reboot needed). - **Environment:** diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 3c0112060b..5eada4c935 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -2001,6 +2001,10 @@ if(TARGET Vulkan::Headers) add_executable(vulkan_device_fault_test test/vulkan_device_fault_test.cpp) target_link_libraries(vulkan_device_fault_test PRIVATE Vulkan::Headers) add_test(NAME vulkan_device_fault COMMAND vulkan_device_fault_test) + # The device-create config the pipeline journal stamps its files with (src/vulkan_device_config.h), on the CPU. + add_executable(vulkan_device_config_test test/vulkan_device_config_test.cpp) + target_link_libraries(vulkan_device_config_test PRIVATE Vulkan::Headers) + add_test(NAME vulkan_device_config COMMAND vulkan_device_config_test) # The AMD breadcrumbs (LEONIDA_DEVICE_MARKERS): seq numbering, marker writes and the likely-hang verdict, on the CPU. add_executable(vulkan_device_markers_test test/vulkan_device_markers_test.cpp) target_link_libraries(vulkan_device_markers_test PRIVATE Vulkan::Headers) diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index 2c948ff3d3..93f1a22d6c 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -112,6 +112,9 @@ struct VulkanDeviceInfo { bool device_checkpoints = false; bool device_diagnostics_config = false; bool device_markers = false; // VK_AMD_buffer_marker enabled for LEONIDA_DEVICE_MARKERS=1 + // leonida::device_create_config of the VkDeviceCreateInfo (src/vulkan_device_config.h): the pipeline journal's + // stamp. 0 for a caller-owned device. + std::uint64_t device_create_config = 0; bool separate_depth_stencil_layouts = true; bool depth_range_unrestricted = false; // VK_EXT_depth_range_unrestricted enabled on this device. std::uint32_t max_push_constants_size = 0; diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 748d6144a5..aff67419d6 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -46,6 +46,7 @@ #include "../src/vulkan_mesh_limits.h" #include "../src/resource_tiling.h" #include "../src/cached_pso.h" +#include "../src/vulkan_device_config.h" #include "../src/compile_gate_calibration.h" #include "../src/pipeline_cache_file.h" #include "../src/pipeline_profile.h" @@ -2881,6 +2882,15 @@ struct DeviceState { // has no file for may still be in it (build_compute asks it first, when it can ask without a compile). bool pipeline_cache_seeded = false; std::atomic journal_hits{0}, journal_writes{0}, journal_shared_hits{0}; + // Builds whose journal file another gta6rt build wrote (or an older runtime, without a stamp), and how many of them + // the driver still found there. + std::atomic journal_other_build{0}, journal_other_build_hits{0}; + // Builds whose journal file this build wrote under another device-create config (src/vulkan_device_config.h), and + // how many of them the driver still found there. + std::atomic journal_other_config{0}, journal_other_config_hits{0}; + // Builds with no journal file that have one under the other NVIDIA diagnostics config setting: the driver does not + // take those across the setting (621.01), so they were compiled. + std::atomic journal_other_diagnostics{0}; std::atomic journal_bytes{0}; // on disk: counted at the cache's creation, then added to std::uint64_t journal_budget = leonida::pipeline_journal::default_budget; // Ask the shared cache first, with FAIL_ON_PIPELINE_COMPILE_REQUIRED, while the driver honours it. @@ -11577,6 +11587,33 @@ std::unique_lock compute_driver_turn(DeviceState& device) return turn; } +// LOCAL FIX (pipeline journal build stamp, pipeline_cache_journal.h): the binary that writes journal files, for their +// stamp: a hash of this executable, read once. LEONIDA_PIPELINE_JOURNAL_BUILD (16 hex digits) names another, for tests. +std::uint64_t journal_build() { + static const std::uint64_t build = [] { + char text[32] = {}; + size_t length = 0; + if (getenv_s(&length, text, "LEONIDA_PIPELINE_JOURNAL_BUILD") == 0 && length > 1) { + char* end = nullptr; + const unsigned long long value = std::strtoull(text, &end, 16); + if (end && !*end && value) return std::uint64_t(value); + std::fprintf(stderr, "[rt] d3d12: pipeline journal: LEONIDA_PIPELINE_JOURNAL_BUILD=%s is not a nonzero hex " + "number; the executable's own build is used\n", text); + } + std::wstring path(32768, L'\0'); + const DWORD n = GetModuleFileNameW(nullptr, path.data(), DWORD(path.size())); + if (!n || n >= path.size()) return std::uint64_t{0}; + path.resize(n); + return leonida::pipeline_journal::file_build(std::filesystem::path(path)); + }(); + return build; +} + +// What this process writes journal files as: its build and its device's create config. +leonida::pipeline_journal::Writer journal_writer(const DeviceState& device) { + return {journal_build(), device.info.device_create_config}; +} + // LOCAL FIX (pipeline journal, pipeline_cache_journal.h): one compute pipeline's own VkPipelineCache for the length // of its build. load() reads the journal file, before any driver call. In the build's one compile-gate turn, // create() makes the cache from the file's contents (seeded) or empty, and finish() takes the cache's data when the @@ -11609,8 +11646,13 @@ class JournalCache { bool has_file_data() const { return !file_.data.empty(); } bool found() const { return enabled_ && built_ && !write_; } // the pipeline came out of the journal file bool written() const { return written_; } // publish() wrote the file + bool other_build() const { return other_build_; } // the file came from another gta6rt build + bool other_config() const { return other_config_; } // written under another device-create config + bool restamped() const { return restamped_; } // publish() stamped it as this build's after a hit - void load(std::filesystem::path path) { + // `restamp`: after a hit from a local file another build wrote, write it again with this build's stamp + // (precompile: the file is then journaled already for this build). + void load(std::filesystem::path path, bool restamp = false) { const auto& vk = device_.context->vk; if (!vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache || !vk.vkGetPipelineCacheData) return; enabled_ = true; @@ -11618,6 +11660,10 @@ class JournalCache { namespace journal = leonida::pipeline_journal; const auto role = compile_helper::build_host.load() ? journal::ReadRole::materialize_local : journal::ReadRole::runtime; file_ = journal::read_with_seed(path_, pipeline_journal_roots().seed, device_.pso_identity, role); + const auto writer = journal_writer(device_); + other_build_ = file_.other_build(writer.build); + other_config_ = !other_build_ && file_.other_config(writer.config); + restamp_ = restamp && file_.other_writer(writer) && !file_.from_seed; } // In the build's driver turn. @@ -11634,6 +11680,7 @@ class JournalCache { info.pInitialData = nullptr; if (vk.vkCreatePipelineCache(device_.info.device, &info, nullptr, &cache) != VK_SUCCESS) cache = VK_NULL_HANDLE; } + if (restamp_ && seeded) keep_.swap(file_.data); // written again with this build's stamp after a hit std::vector().swap(file_.data); // the driver has its own copy } @@ -11666,8 +11713,29 @@ class JournalCache { void publish() { namespace journal = leonida::pipeline_journal; if (!enabled_ || !built_) return; + if (other_build_) { + device_.journal_other_build.fetch_add(1); + if (!write_) device_.journal_other_build_hits.fetch_add(1); + } + if (other_config_) { + device_.journal_other_config.fetch_add(1); + if (!write_) device_.journal_other_config_hits.fetch_add(1); + } if (!write_) { report(device_.journal_hits.fetch_add(1) + 1, "found in their journal file"); + if (!keep_.empty()) { + // A hit from another build's (or device config's) file: this writer's stamp on the same blob. + const auto file = journal::stamped(journal_writer(device_), keep_.data(), keep_.size()); + std::vector().swap(keep_); + if (!journal::write_entry(path_, file.data(), file.size())) { + auto total = device_.journal_bytes.load(); + while (!device_.journal_bytes.compare_exchange_weak( + total, journal::replace_bytes(total, file_.bytes, file.size()))) { + } + restamped_ = true; + } + return; + } journal::touch_local_hit(path_, file_, std::filesystem::file_time_type::clock::now()); return; } @@ -11676,9 +11744,12 @@ class JournalCache { name_, int(result_), data_size_); return; } + // The file: this build's and device config's stamp, then the blob. + const auto file = journal::stamped(journal_writer(device_), blob_.data(), blob_.size()); + std::vector().swap(blob_); // A rewrite replaces the file's old size. Two builds of one name at once may both count: the next boot's // tidy counts again. - if (journal::replace_bytes(device_.journal_bytes.load(), file_.bytes, blob_.size()) > device_.journal_budget) { + if (journal::replace_bytes(device_.journal_bytes.load(), file_.bytes, file.size()) > device_.journal_budget) { static std::atomic said{false}; if (!said.exchange(true)) std::fprintf(stderr, "[rt] d3d12: pipeline journal: %llu bytes on disk, the %llu-byte budget " @@ -11687,7 +11758,7 @@ class JournalCache { static_cast(device_.journal_budget)); return; } - if (const std::error_code error = journal::write_entry(path_, blob_.data(), blob_.size())) { + if (const std::error_code error = journal::write_entry(path_, file.data(), file.size())) { static std::atomic said{false}; if (!said.exchange(true)) std::fprintf(stderr, "[rt] d3d12: pipeline journal: could not write %ls: %s\n", path_.c_str(), @@ -11695,7 +11766,7 @@ class JournalCache { return; } auto total = device_.journal_bytes.load(); - while (!device_.journal_bytes.compare_exchange_weak(total, journal::replace_bytes(total, file_.bytes, blob_.size()))) { + while (!device_.journal_bytes.compare_exchange_weak(total, journal::replace_bytes(total, file_.bytes, file.size()))) { } written_ = true; report(device_.journal_writes.fetch_add(1) + 1, "compiled and written to their journal file"); @@ -11706,8 +11777,13 @@ class JournalCache { void report(unsigned count, const char* what) const { if (count != 1 && count % 100) return; std::fprintf(stderr, "[rt] d3d12: pipeline journal: %u compute pipeline(s) %s (so far: %u from journal files, " - "%u written, %u from the shared cache)\n", count, what, - device_.journal_hits.load(), device_.journal_writes.load(), device_.journal_shared_hits.load()); + "%u written, %u from the shared cache; from another build: %u, %u of them found; from " + "another device config: %u, %u of them found; only under the other diagnostics config " + "setting: %u)\n", + count, what, device_.journal_hits.load(), device_.journal_writes.load(), + device_.journal_shared_hits.load(), device_.journal_other_build.load(), + device_.journal_other_build_hits.load(), device_.journal_other_config.load(), + device_.journal_other_config_hits.load(), device_.journal_other_diagnostics.load()); } DeviceState& device_; @@ -11718,8 +11794,13 @@ class JournalCache { bool built_ = false; bool write_ = false; bool written_ = false; + bool other_build_ = false; + bool other_config_ = false; + bool restamp_ = false; + bool restamped_ = false; std::filesystem::path path_; leonida::pipeline_journal::EntryFile file_; + std::vector keep_; // restamp: the file's blob, for a hit std::vector blob_; std::size_t data_size_ = 0; VkResult result_ = VK_SUCCESS; @@ -11738,13 +11819,18 @@ struct ComputeBuild { bool journal_hit = false; // found in its journal file bool journaled = false; // compiled and written to its journal file bool from_shared = false; // found in the shared cache + bool other_build = false; // its journal file came from another gta6rt build (or had no stamp) + bool other_config = false; // its journal file came from this build under another device-create config + bool other_diagnostics = false; // no journal file, but one under the other NVIDIA diagnostics config setting + bool restamped = false; // ComputeBuildOptions::restamp_hits and that file was a hit: stamped as this build's }; struct ComputeBuildOptions { const char* trigger = "dispatch"; // what asked: dispatch, warmup, dispatch-worker, precompile... const std::string* cache_key = nullptr; // the title's PSO description key, for the compile trace bool serialize_big = true; // LEONIDA_SERIAL_BIG_COMPILES=1: modules over 128 KiB one at a time - bool skip_journaled = false; // precompile: leave a pipeline whose journal file exists alone + bool skip_journaled = false; // precompile: leave a pipeline whose journal file this build wrote alone + bool restamp_hits = false; // precompile: a hit from another build's file stamps it as this build's bool use_helper = true; // LEONIDA_COMPILE_HELPER: a missing journal file comes from the helper bool helper_wait = true; // wait for the helper's file (false: ask, and answer deferred) std::uint64_t helper_priority = 0; // the request's urgency: 0 a dispatch, else the warm-up's module size @@ -11816,21 +11902,40 @@ ComputeBuild build_compute_pipeline(DeviceState& device, const leonida::ShaderEn key.value(std::uint32_t(entry->binding_count != 0)); // NVIDIA's diagnostics config (LEONIDA_DEVICE_FAULT=1, Aftermath) compiles with shader debug info: other // pipelines, kept apart so switching it on and off does not rewrite every file. Absent when off, so the - // names of ordinary boots stay as they were. - if (device.info.device_diagnostics_config) { - key.text("nv-diagnostics-config"); - key.value(std::uint32_t(leonida::aftermath::extra_config_flags())); + // names of ordinary boots stay as they were. `other` names the file under the other setting: on NVIDIA + // 621.01 a file from one setting gave the other no hits, so finding only that one is reported. + leonida::pipeline_journal::Hasher other = key; + auto& diagnostics_key = device.info.device_diagnostics_config ? key : other; + diagnostics_key.text("nv-diagnostics-config"); + diagnostics_key.value(std::uint32_t(leonida::aftermath::extra_config_flags())); + if (entry->binding_count) { + hash_bindless_layout(key, device.bindless->features()); + hash_bindless_layout(other, device.bindless->features()); } - if (entry->binding_count) hash_bindless_layout(key, device.bindless->features()); const auto path = leonida::pipeline_journal::entry_path(journal_dir, "cs", key.digest()); out.journal_path = path; if (options.key_only) return out; - // Precompile: a usable file is there already, so the pipeline is not built (only its header is read). - if (options.skip_journaled && leonida::pipeline_journal::entry_usable(path, device.pso_identity)) { + // Precompile: a usable file this build wrote is there already, so the pipeline is not built (only its stamp and + // header are read). One from another build is built against: the driver may no longer take it. + if (options.skip_journaled && + leonida::pipeline_journal::entry_current(path, device.pso_identity, journal_writer(device))) { out.skipped = true; return out; } - journal.load(path); + journal.load(path, options.restamp_hits); + if (!journal.has_file_data() && + leonida::pipeline_journal::entry_usable( + leonida::pipeline_journal::entry_path(journal_dir, "cs", other.digest()), device.pso_identity)) { + out.other_diagnostics = true; + device.journal_other_diagnostics.fetch_add(1); + static std::atomic said{false}; + if (!said.exchange(true)) + std::fprintf(stderr, "[rt] d3d12: pipeline journal: %s has a journal file only for a device %s NVIDIA's " + "diagnostics config (LEONIDA_DEVICE_FAULT=1, LEONIDA_AFTERMATH=1), which the driver " + "does not take across that setting; run gta6rt --precompile-pipelines with this " + "boot's setting\n", + entry->name.c_str(), device.info.device_diagnostics_config ? "without" : "with"); + } // LOCAL FIX (compile helper, d3d12_compile_helper.h): no file, so this would be a compile in this process, // where the driver's lock it holds stops the title's submissions. The helper process compiles it into the file // instead, and the create below is a hit. Asked without waiting, the build answers deferred and is asked @@ -11848,7 +11953,7 @@ ComputeBuild build_compute_pipeline(DeviceState& device, const leonida::ShaderEn } else { const ULONGLONG asked = GetTickCount64(); if (helper.build(path, entry->name, device.pso_identity, &why)) { - journal.load(path); + journal.load(path, options.restamp_hits); std::fprintf(stderr, "[rt] d3d12: compile helper built %s in %.1f s (%zu B SPIR-V, %s)\n", entry->name.c_str(), double(GetTickCount64() - asked) / 1000.0, bytes, trigger); } else { @@ -11954,6 +12059,9 @@ ComputeBuild build_compute_pipeline(DeviceState& device, const leonida::ShaderEn out.from_shared = from_shared; out.journal_hit = journal.found(); out.journaled = journal.written(); + out.other_build = journal.other_build(); + out.other_config = journal.other_config(); + out.restamped = journal.restamped(); out.ms = GetTickCount64() - started; if (created == VK_SUCCESS && built && out.ms >= 2000) std::fprintf(stderr, "[rt] d3d12: compute pipeline %s took %.1f s to build (%zu B SPIR-V)\n", @@ -23266,6 +23374,8 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin "debug info, resource tracking or checkpoints\n"); device_info.enabledExtensionCount = std::uint32_t(device_extensions.size()); device_info.ppEnabledExtensionNames = device_extensions.empty() ? nullptr : device_extensions.data(); + // The pipeline journal stamps its files with this (src/vulkan_device_config.h): the driver's key holds it. + info.device_create_config = leonida::device_create_config(device_info); if (vkCreateDevice(info.physical, &device_info, nullptr, &owned.device) != VK_SUCCESS) return fail("vkCreateDevice failed"); info.device = owned.device; @@ -23494,6 +23604,9 @@ int precompile_compute_pipelines(const PrecompileOptions& options) { std::atomic next{0}; std::mutex progress_mutex; std::size_t done = 0, compiled = 0, skipped = 0, hits = 0, failed = 0, journaled = 0, elsewhere = 0; + std::size_t other_build = 0, other_build_hits = 0; // built against a file another gta6rt build wrote + std::size_t other_config = 0, other_config_hits = 0; // built against one written under another device config + std::size_t other_diagnostics = 0; // no file, but one under the other diagnostics config setting std::uint64_t done_bytes = 0; std::mutex big_mutex; std::condition_variable big_free; @@ -23514,6 +23627,7 @@ int precompile_compute_pipelines(const PrecompileOptions& options) { build_options.trigger = "precompile"; build_options.serialize_big = false; // nothing else is building; big_threads bounds them instead build_options.skip_journaled = !options.rebuild; + build_options.restamp_hits = true; build_options.use_helper = options.via_helper; build_options.mark_building = !options.via_helper; // an entry another process is compiling is left to it ComputeBuild build; @@ -23537,6 +23651,15 @@ int precompile_compute_pipelines(const PrecompileOptions& options) { else if (build.result != VK_SUCCESS || (!build.pipeline && !build.skipped)) ++failed; else if (build.journal_hit || build.from_shared) ++hits, what = "found in a cache"; else ++compiled, what = build.journaled ? "compiled and journaled" : "compiled (not journaled)"; + if (build.other_build && build.result == VK_SUCCESS && build.pipeline) { + ++other_build; + if (build.journal_hit) ++other_build_hits, what = "found in another build's journal file"; + } + if (build.other_config && build.result == VK_SUCCESS && build.pipeline) { + ++other_config; + if (build.journal_hit) ++other_config_hits, what = "found in another device config's journal file"; + } + if (build.other_diagnostics && build.result == VK_SUCCESS && build.pipeline) ++other_diagnostics; const double elapsed = std::chrono::duration(Clock::now() - began).count(); const double eta = done_bytes ? elapsed / double(done_bytes) * double(total_bytes - done_bytes) : 0.0; // Skips are not logged one by one (a resumed run skips thousands); every 100th is, with the counts. @@ -23557,6 +23680,19 @@ int precompile_compute_pipelines(const PrecompileOptions& options) { compiled + hits, compiled, hits, journaled, elsewhere, failed, listed_left_out, listed, options.skip_listed ? " (--skip-listed)" : "", not_buildable, filtered, std::chrono::duration(Clock::now() - began).count()); + if (other_build) + std::fprintf(stderr, "[precompile] %zu journal file(s) from another gta6rt build or without a build stamp: %zu " + "still found by the driver (now stamped as this build's), %zu compiled again\n", + other_build, other_build_hits, other_build - other_build_hits); + if (other_config) + std::fprintf(stderr, "[precompile] %zu journal file(s) from this build under another device config (device " + "features, extensions, LEONIDA_DEVICE_FAULT or LEONIDA_AFTERMATH): %zu still found by the " + "driver (now stamped with this config), %zu compiled again\n", + other_config, other_config_hits, other_config - other_config_hits); + if (other_diagnostics) + std::fprintf(stderr, "[precompile] %zu entries had a journal file only for a device %s NVIDIA's diagnostics " + "config: built for this setting\n", + other_diagnostics, host.state().info.device_diagnostics_config ? "without" : "with"); return failed ? 2 : 0; } diff --git a/runtime/src/pipeline_cache_journal.h b/runtime/src/pipeline_cache_journal.h index 6a72d07f03..51589d8198 100644 --- a/runtime/src/pipeline_cache_journal.h +++ b/runtime/src/pipeline_cache_journal.h @@ -17,6 +17,14 @@ // The hash only picks the file. Whether the pipeline in it may be used is the driver's decision: it checks the blob // header (vendor, device, pipeline-cache UUID; checked here first too, so a driver update starts over) and its own key. // +// Each file starts with a stamp naming what wrote it (stamp_bytes: magic, size, a hash of the executable, and a hash of +// the device-create config, vulkan_device_config.h), then the blob. The driver's own key can hold more than the header +// shows: on NVIDIA 621.40 files were found to give hits only to the gta6rt build that wrote them, and on 621.01 files +// written without NVIDIA's diagnostics config gave a device with it no hits. So gta6rt --precompile-pipelines counts a +// file as done only when this binary wrote it for this device config (entry_current); any other file is built against +// again, which takes milliseconds when the driver still takes it. Files without a stamp (older runtimes) are read like +// files from another build. +// // Upkeep (tidy, at the first pipeline of a device): staging files a killed writer left behind are removed once they are // ten minutes old, and past LEONIDA_PIPELINE_JOURNAL_BYTES the least recently used files go until three quarters of // it is left. A file's modification time is its last use: written, or touched when a build found its pipeline there. @@ -29,6 +37,7 @@ #include #include #include +#include #include #include #include @@ -49,6 +58,46 @@ inline constexpr std::uint32_t key_version = 1; // A file larger than this is not read (a corrupt or foreign file; one pipeline's cache is a few MiB at most). inline constexpr std::size_t entry_read_limit = std::size_t{256} << 20; +// The stamp before the blob: "LPJ1", its own size, the writing binary's build, then the device-create config it was +// written under (little-endian, like the host). +inline constexpr std::uint32_t stamp_magic = 0x314a504c; // "LPJ1" +inline constexpr std::size_t stamp_bytes = 24; + +// What wrote a file: the binary and the device-create config. +struct Writer { + std::uint64_t build = 0; // 0: the writer did not know its own build + std::uint64_t config = 0; // 0: not recorded +}; + +struct Stamp { + bool present = false; + std::uint64_t build = 0; + std::uint64_t config = 0; +}; + +inline Stamp read_stamp(const void* data, std::size_t size) { + Stamp stamp; + if (!data || size < stamp_bytes) return stamp; + const auto* p = static_cast(data); + if (pipeline_cache_store::read_u32(p) != stamp_magic || pipeline_cache_store::read_u32(p + 4) != stamp_bytes) + return stamp; + const auto u64 = [p](std::size_t at) { + return std::uint64_t(pipeline_cache_store::read_u32(p + at)) | + (std::uint64_t(pipeline_cache_store::read_u32(p + at + 4)) << 32); + }; + stamp.present = true; + stamp.build = u64(8); + stamp.config = u64(16); + return stamp; +} + +inline void put_stamp(void* out, const Writer& writer) { + auto* p = static_cast(out); + const std::uint64_t fields[3] = {std::uint64_t(stamp_magic) | (std::uint64_t(stamp_bytes) << 32), writer.build, + writer.config}; + for (std::size_t i = 0; i < stamp_bytes; ++i) p[i] = static_cast(fields[i / 8] >> (8 * (i % 8))); +} + // 64-bit FNV-1a. Not cryptographic: it names a file, and a collision costs one compile, not a wrong pipeline. class Hasher { public: @@ -81,6 +130,27 @@ class Hasher { std::uint64_t hash_ = 0xcbf29ce484222325ull; }; +// A binary's build, for the stamp: a hash of the file's contents (0 when it cannot be read). Any rebuild of the +// executable is another build, whatever its name or folder; a copy of it is the same one. +inline std::uint64_t file_build(const std::filesystem::path& path) { + std::ifstream file(path, std::ios::binary); + if (!file) return 0; + Hasher hash; + hash.text("binary"); + std::vector chunk(std::size_t{1} << 20); + std::uint64_t total = 0; + while (file) { + file.read(chunk.data(), static_cast(chunk.size())); + const auto got = static_cast(file.gcount()); + if (!got) break; + hash.bytes(chunk.data(), got); + total += got; + } + if (file.bad() || !total) return 0; + hash.value(total); + return hash.digest() ? hash.digest() : 1; // 0 means unknown +} + // /-.bin inline std::filesystem::path entry_path(const std::filesystem::path& dir, const char* kind, std::uint64_t key) { char name[64]; @@ -125,10 +195,23 @@ inline Roots resolve_roots(const std::filesystem::path& local, const std::filesy // The selected compatible bytes plus metadata for the *writable* leaf as the build found it. struct EntryFile { - std::vector data; // compatible local bytes, else compatible seed bytes; empty when neither is usable + std::vector data; // compatible local bytes, else compatible seed bytes, stamp removed; empty when neither bool from_seed = false; // an external hit must not refresh either the immutable seed or a stale local file std::uint64_t bytes = 0; // its size on disk, whatever its contents (0: none): what a rewrite replaces std::filesystem::file_time_type used{}; // its modification time: its last use + Stamp stamp; // of the file `data` came from + + // `data` came from a file another binary than `build` wrote (or one without a stamp). + bool other_build(std::uint64_t build) const { + return !data.empty() && !(stamp.present && stamp.build && stamp.build == build); + } + // `data` came from a stamped file written under another device-create config (an unstamped file says nothing of + // its config, and counts as from another build). + bool other_config(std::uint64_t config) const { + return !data.empty() && stamp.present && stamp.config != config; + } + // Either: not this writer's file, so a precompile builds against it again. + bool other_writer(const Writer& writer) const { return other_build(writer.build) || other_config(writer.config); } }; inline EntryFile read_entry_file(const std::filesystem::path& path, const cached_pso::Identity& identity, @@ -143,30 +226,67 @@ inline EntryFile read_entry_file(const std::filesystem::path& path, const cached std::ifstream file(path, std::ios::binary); if (!file) return entry; entry.data.resize(static_cast(size)); - if (!file.read(entry.data.data(), static_cast(entry.data.size())) || - !pipeline_cache_store::header_matches(entry.data.data(), entry.data.size(), identity)) + if (!file.read(entry.data.data(), static_cast(entry.data.size()))) { + entry.data.clear(); + return entry; + } + entry.stamp = read_stamp(entry.data.data(), entry.data.size()); + if (entry.stamp.present) entry.data.erase(entry.data.begin(), entry.data.begin() + stamp_bytes); + if (!pipeline_cache_store::header_matches(entry.data.data(), entry.data.size(), identity)) { entry.data.clear(); + entry.stamp = {}; + } return entry; } -// The file's bytes, or empty when it is missing, unreadable, over `limit`, or its header does not name `identity`. +// The file's blob (its stamp removed), or empty when it is missing, unreadable, over `limit`, or its header does not +// name `identity`. inline std::vector read_entry(const std::filesystem::path& path, const cached_pso::Identity& identity, std::size_t limit = entry_read_limit) { return read_entry_file(path, identity, limit).data; } -// Whether the file is there with a header naming this device and driver: only the header is read (gta6rt -// --precompile-pipelines asks this of thousands of files of a few MiB). -inline bool entry_usable(const std::filesystem::path& path, const cached_pso::Identity& identity, - std::size_t limit = entry_read_limit) { +// What a file's first bytes say: whether its blob header names this device and driver, and its stamp. +struct EntryCheck { + bool usable = false; + Stamp stamp; +}; + +// Only the stamp and the blob header are read (gta6rt --precompile-pipelines asks this of thousands of files of a few +// MiB). +inline EntryCheck check_entry(const std::filesystem::path& path, const cached_pso::Identity& identity, + std::size_t limit = entry_read_limit) { + EntryCheck check; // A helper-ready file must also fit the consumer's bounded read. Check metadata, not the full payload. std::error_code ec; const auto size = std::filesystem::file_size(path, ec); - if (ec || size < pipeline_cache_store::header_bytes || size > limit) return false; + if (ec || size < pipeline_cache_store::header_bytes || size > limit) return check; std::ifstream file(path, std::ios::binary); - char header[pipeline_cache_store::header_bytes]; - return file && file.read(header, sizeof(header)) && - pipeline_cache_store::header_matches(header, sizeof(header), identity); + char head[stamp_bytes + pipeline_cache_store::header_bytes]; + const std::size_t want = (std::min)(sizeof(head), static_cast(size)); + if (!file || !file.read(head, static_cast(want))) return check; + const Stamp stamp = read_stamp(head, want); + const std::size_t at = stamp.present ? stamp_bytes : 0; + if (!pipeline_cache_store::header_matches(head + at, want - at, identity)) return check; + check.usable = true; + check.stamp = stamp; + return check; +} + +// Whether the file is there with a header naming this device and driver, whichever binary wrote it. +inline bool entry_usable(const std::filesystem::path& path, const cached_pso::Identity& identity, + std::size_t limit = entry_read_limit) { + return check_entry(path, identity, limit).usable; +} + +// Whether the file is usable and this binary (`writer.build`, nonzero) wrote it under this device-create config: what +// gta6rt --precompile-pipelines leaves alone. Any other file may still give the driver a hit, or may not; only building +// against it tells. +inline bool entry_current(const std::filesystem::path& path, const cached_pso::Identity& identity, const Writer& writer, + std::size_t limit = entry_read_limit) { + const EntryCheck check = check_entry(path, identity, limit); + return check.usable && check.stamp.present && writer.build && check.stamp.build == writer.build && + check.stamp.config == writer.config; } enum class ReadRole { runtime, materialize_local }; @@ -178,7 +298,9 @@ inline EntryFile read_with_seed(const std::filesystem::path& local_entry, const auto local = read_entry_file(local_entry, identity, limit); // Build hosts promise a file in the writable journal. External data must not satisfy such a request. if (role == ReadRole::runtime && local.data.empty() && !seed.empty()) { - local.data = read_entry_file(seed / local_entry.filename(), identity, limit).data; + auto external = read_entry_file(seed / local_entry.filename(), identity, limit); + local.data = std::move(external.data); + local.stamp = external.stamp; local.from_seed = !local.data.empty(); } return local; @@ -353,4 +475,12 @@ inline std::error_code write_entry(const std::filesystem::path& path, const void return write_pipeline_cache_file(path, static_cast(data), size); } +// A journal file's bytes: the stamp for `writer`, then the pipeline cache blob. +inline std::vector stamped(const Writer& writer, const void* blob, std::size_t size) { + std::vector out(stamp_bytes + size); + put_stamp(out.data(), writer); + if (size) std::memcpy(out.data() + stamp_bytes, blob, size); + return out; +} + } // namespace leonida::pipeline_journal diff --git a/runtime/src/vulkan_device_config.h b/runtime/src/vulkan_device_config.h new file mode 100644 index 0000000000..32867f714f --- /dev/null +++ b/runtime/src/vulkan_device_config.h @@ -0,0 +1,112 @@ +// What a VkDeviceCreateInfo asks of the driver that its pipeline compiles can depend on, as one 64-bit value: the +// pipeline journal's stamp (pipeline_cache_journal.h) records it next to the writing binary's build. +// +// On NVIDIA (621.01, RTX 4070 SUPER) a journal file written by a device without the diagnostics config +// (VK_NV_device_diagnostics_config, LEONIDA_DEVICE_FAULT=1 or LEONIDA_AFTERMATH=1) gave a device with it no hits, and +// the other way round: the driver's own key holds device-create state that the blob header does not show. Hashed: +// - the enabled extensions, in any order; +// - pEnabledFeatures; +// - each structure on the pNext chain by its type, and the contents of those listed in add_struct (the core feature +// structures, robustness2, device fault and the diagnostics config with its flags); others count by presence. +// Queue create infos are left out: they do not change a compile. +// +// Header only; tested by vulkan_device_config_test. +#pragma once + +#include + +#include +#include +#include +#include +#include +#include + +namespace leonida { + +namespace device_config_detail { + +struct Fnv { + std::uint64_t hash = 0xcbf29ce484222325ull; + void bytes(const void* data, std::size_t size) { + const auto* p = static_cast(data); + for (std::size_t i = 0; i < size; ++i) { + hash ^= p[i]; + hash *= 0x100000001b3ull; + } + } + void value(std::uint32_t v) { bytes(&v, sizeof(v)); } +}; + +// The members after sType and pNext, up to and including `last` (so trailing padding is never read). +template +void add_members(Fnv& h, const T& s, std::size_t last_end) { + const std::size_t first = offsetof(T, pNext) + sizeof(void*); + h.bytes(reinterpret_cast(&s) + first, last_end - first); +} + +#define LEONIDA_DEVICE_CONFIG_MEMBERS(T, last) \ + add_members(h, *reinterpret_cast(s), offsetof(T, last) + sizeof(T::last)) + +inline void add_struct(Fnv& h, const VkBaseInStructure* s) { + h.value(std::uint32_t(s->sType)); + switch (s->sType) { + case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2: + LEONIDA_DEVICE_CONFIG_MEMBERS(VkPhysicalDeviceFeatures2, features); + break; + case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_1_FEATURES: + LEONIDA_DEVICE_CONFIG_MEMBERS(VkPhysicalDeviceVulkan11Features, shaderDrawParameters); + break; + case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES: + LEONIDA_DEVICE_CONFIG_MEMBERS(VkPhysicalDeviceVulkan12Features, subgroupBroadcastDynamicId); + break; + case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES: + LEONIDA_DEVICE_CONFIG_MEMBERS(VkPhysicalDeviceVulkan13Features, maintenance4); + break; + case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ROBUSTNESS_2_FEATURES_EXT: + LEONIDA_DEVICE_CONFIG_MEMBERS(VkPhysicalDeviceRobustness2FeaturesEXT, nullDescriptor); + break; + case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FAULT_FEATURES_EXT: + LEONIDA_DEVICE_CONFIG_MEMBERS(VkPhysicalDeviceFaultFeaturesEXT, deviceFaultVendorBinary); + break; + case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DIAGNOSTICS_CONFIG_FEATURES_NV: + LEONIDA_DEVICE_CONFIG_MEMBERS(VkPhysicalDeviceDiagnosticsConfigFeaturesNV, diagnosticsConfig); + break; + case VK_STRUCTURE_TYPE_DEVICE_DIAGNOSTICS_CONFIG_CREATE_INFO_NV: + LEONIDA_DEVICE_CONFIG_MEMBERS(VkDeviceDiagnosticsConfigCreateInfoNV, flags); + break; + default: + break; + } +} + +#undef LEONIDA_DEVICE_CONFIG_MEMBERS + +} // namespace device_config_detail + +// Never 0, so a stamp's 0 can mean "not recorded". +inline std::uint64_t device_create_config(const VkDeviceCreateInfo& info) { + using namespace device_config_detail; + Fnv h; + h.bytes("device-create-config", 20); + std::vector extensions; + for (std::uint32_t i = 0; i < info.enabledExtensionCount; ++i) + if (info.ppEnabledExtensionNames && info.ppEnabledExtensionNames[i]) + extensions.emplace_back(info.ppEnabledExtensionNames[i]); + std::sort(extensions.begin(), extensions.end()); + extensions.erase(std::unique(extensions.begin(), extensions.end()), extensions.end()); + h.value(std::uint32_t(extensions.size())); + for (const std::string_view name : extensions) { + h.bytes(name.data(), name.size()); + h.value(0); + } + h.value(info.pEnabledFeatures ? 1u : 0u); + if (info.pEnabledFeatures) h.bytes(info.pEnabledFeatures, sizeof(VkPhysicalDeviceFeatures)); + // A chain is short; the bound only stops a cycle. + std::size_t links = 0; + for (auto* s = static_cast(info.pNext); s && links < 256; s = s->pNext, ++links) + add_struct(h, s); + return h.hash ? h.hash : 1; +} + +} // namespace leonida diff --git a/runtime/test/check_precompile_skip_list.cmake b/runtime/test/check_precompile_skip_list.cmake index 5945db7615..febded776a 100644 --- a/runtime/test/check_precompile_skip_list.cmake +++ b/runtime/test/check_precompile_skip_list.cmake @@ -5,7 +5,16 @@ # A library of two synthetic compute entries, one of them named by LEONIDA_SKIP_COMPUTE, is precompiled three times: # 1. into an empty journal with the list set and no flag: both entries are built; # 2. into another empty journal with --skip-listed: only the unlisted one is, and the listed one is reported; -# 3. into the first journal again: both are journaled already, nothing is built. +# 3. into the first journal again: both are journaled already, nothing is built; +# 4. into the first journal as another build (LEONIDA_PIPELINE_JOURNAL_BUILD): both files are from another build, +# so both are built against them again and reported, and then stamped as that build's; +# 5. as that build again: both are journaled already; +# 6. with LEONIDA_DEVICE_FAULT=2 (fault info and checkpoints, no diagnostics config): when the device has either, the +# device-create config differs, so both files are from another device config and built against again; +# 7. LEONIDA_DEVICE_FAULT=2 again: both are journaled already; +# 8. with LEONIDA_DEVICE_FAULT=1: when the device has NVIDIA's diagnostics config, the pipelines are named apart and +# have no files yet, and both are reported as journaled only without that config; +# 9. LEONIDA_DEVICE_FAULT=1 again: both are journaled already. # The verdicts are read from the output and the journal folders, since under Wine an exit status alone can look fine. cmake_minimum_required(VERSION 3.24) @@ -30,7 +39,8 @@ file(WRITE "${TEST_DIR}/shaders/index.json" # Only what this test sets: a journal setting or helper from the caller's environment would change the counts. foreach(var LEONIDA_PIPELINE_JOURNAL LEONIDA_PIPELINE_CACHE_BYTES LEONIDA_PIPELINE_JOURNAL_BYTES - LEONIDA_PIPELINE_JOURNAL_SEED_DIR LEONIDA_COMPILE_HELPER LEONIDA_LAZY_COMPUTE) + LEONIDA_PIPELINE_JOURNAL_SEED_DIR LEONIDA_PIPELINE_JOURNAL_BUILD LEONIDA_COMPILE_HELPER LEONIDA_LAZY_COMPUTE + LEONIDA_DEVICE_FAULT LEONIDA_AFTERMATH LEONIDA_DEVICE_MARKERS) unset(ENV{${var}}) endforeach() file(TO_NATIVE_PATH "${TEST_DIR}/shaders" shaders) @@ -95,6 +105,14 @@ else() if(NOT count EQUAL 2) string(APPEND failures "list set, no flag: ${count} journal files, not 2\n") endif() + # Each file starts with the stamp naming the binary that wrote it (pipeline_cache_journal.h). + file(GLOB files "${TEST_DIR}/cache_all/pipeline_cache.d/cs-*.bin") + foreach(f IN LISTS files) + file(READ "${f}" magic LIMIT 4 HEX) + if(NOT magic STREQUAL "4c504a31") # "LPJ1" + string(APPEND failures "list set, no flag: ${f} does not start with the build stamp\n") + endif() + endforeach() endif() # 2. --skip-listed: the listed entry is left out and named, the other one is built. @@ -115,6 +133,62 @@ if(journaled) precompile("again" cache_all) expect_exit("again" 0) expect("again" "\n\\[precompile\\] done: 0 built \\(0 compiled, 0 from a cache\\), 2 journaled already, 0 being built by another process, 0 failed; left out: 0 of 1 listed in LEONIDA_SKIP_COMPUTE, 0 not buildable, 0 filtered out; in [0-9]+ s\n") + expect_not("again" "from another gta6rt build") + + # 4. Another build: the files are not counted as done. Each is built against its file again (a cache hit when the + # driver still takes it, else a compile that rewrites it) and the closing lines say so. + set(ENV{LEONIDA_PIPELINE_JOURNAL_BUILD} "1234abcd5678ef90") + precompile("another build" cache_all) + expect_exit("another build" 0) + expect("another build" "\n\\[precompile\\] done: 2 built \\([0-9]+ compiled, [0-9]+ from a cache\\), 0 journaled already, 0 being built by another process, 0 failed; ") + expect("another build" "\n\\[precompile\\] 2 journal file\\(s\\) from another gta6rt build or without a build stamp: [0-9]+ still found by the driver \\(now stamped as this build's\\), [0-9]+ compiled again\n") + + # 5. That build again: its own files now. + precompile("another build again" cache_all) + expect_exit("another build again" 0) + expect("another build again" "\n\\[precompile\\] done: 0 built \\(0 compiled, 0 from a cache\\), 2 journaled already, ") + expect_not("another build again" "from another gta6rt build") + + # 6. Another device-create config, same names: LEONIDA_DEVICE_FAULT=2 adds the fault and checkpoint extensions. + set(ENV{LEONIDA_DEVICE_FAULT} "2") + precompile("device fault 2" cache_all) + expect_exit("device fault 2" 0) + expect_not("device fault 2" "from another gta6rt build") + if(out MATCHES "device-fault: enabled \\(fault info on|checkpoints on") + expect("device fault 2" "\n\\[precompile\\] done: 2 built \\([0-9]+ compiled, [0-9]+ from a cache\\), 0 journaled already, ") + expect("device fault 2" "\n\\[precompile\\] 2 journal file\\(s\\) from this build under another device config \\([^)]*\\): [0-9]+ still found by the driver \\(now stamped with this config\\), [0-9]+ compiled again\n") + else() + message("note: no device fault extension here, so LEONIDA_DEVICE_FAULT=2 leaves the device config as it was") + expect("device fault 2" "\n\\[precompile\\] done: 0 built \\(0 compiled, 0 from a cache\\), 2 journaled already, ") + endif() + # 7. The same config again: its own files now. + precompile("device fault 2 again" cache_all) + expect_exit("device fault 2 again" 0) + expect("device fault 2 again" "\n\\[precompile\\] done: 0 built \\(0 compiled, 0 from a cache\\), 2 journaled already, ") + expect_not("device fault 2 again" "under another device config") + + # 8. NVIDIA's diagnostics config: other names, so no files yet, and the ones without the config are reported. + set(ENV{LEONIDA_DEVICE_FAULT} "1") + precompile("device fault 1" cache_all) + expect_exit("device fault 1" 0) + if(out MATCHES "NVIDIA diagnostics config on") + expect("device fault 1" "\n\\[precompile\\] done: 2 built \\([0-9]+ compiled, [0-9]+ from a cache\\), 0 journaled already, ") + expect("device fault 1" "\n\\[precompile\\] 2 entries had a journal file only for a device without NVIDIA's diagnostics config: built for this setting\n") + expect_not("device fault 1" "under another device config") + journal_files(cache_all count) + if(NOT count EQUAL 4) + string(APPEND failures "device fault 1: ${count} journal files, not 4 (2 without, 2 with the diagnostics config)\n") + endif() + # 9. The same setting again: its own files now. + precompile("device fault 1 again" cache_all) + expect_exit("device fault 1 again" 0) + expect("device fault 1 again" "\n\\[precompile\\] done: 0 built \\(0 compiled, 0 from a cache\\), 2 journaled already, ") + expect_not("device fault 1 again" "only for a device") + else() + message("note: no NVIDIA diagnostics config here, so the LEONIDA_DEVICE_FAULT=1 checks are left out") + endif() + unset(ENV{LEONIDA_DEVICE_FAULT}) + unset(ENV{LEONIDA_PIPELINE_JOURNAL_BUILD}) endif() if(failures) diff --git a/runtime/test/pipeline_cache_journal_test.cpp b/runtime/test/pipeline_cache_journal_test.cpp index c3793c96cf..7897ec9b5b 100644 --- a/runtime/test/pipeline_cache_journal_test.cpp +++ b/runtime/test/pipeline_cache_journal_test.cpp @@ -227,6 +227,116 @@ static int test_entry_file(const fs::path& dir) { return 0; } +// The writer stamp before the blob: read and stripped, files without one read as before, and only a file this build +// wrote under this device-create config is current (what gta6rt --precompile-pipelines leaves alone). +static int test_stamp(const fs::path& dir) { + const auto id = identity(); + constexpr std::uint64_t ours = 0x0123456789abcdefull, theirs = 0xfedcba9876543210ull; + constexpr std::uint64_t plain = 0x1111222233334444ull, diagnostics = 0x5555666677778888ull; + const journal::Writer we{ours, plain}, other_build{theirs, plain}, other_config{ours, diagnostics}; + + // Round trip; the stamp is its own size and does not look like a blob header. + std::uint8_t raw[journal::stamp_bytes]; + static_assert(journal::stamp_bytes == 24); + journal::put_stamp(raw, we); + auto stamp = journal::read_stamp(raw, sizeof(raw)); + CHECK(stamp.present && stamp.build == ours && stamp.config == plain); + CHECK(std::memcmp(raw, "LPJ1", 4) == 0); + CHECK(!journal::read_stamp(raw, sizeof(raw) - 1).present); + CHECK(!store::header_matches(raw, sizeof(raw), id)); + const auto bare = blob(id, 64); + CHECK(!journal::read_stamp(bare.data(), bare.size()).present); // a blob alone: no stamp + // The 16-byte stamp of an earlier draft (size field 16) is not this stamp. + std::uint8_t old[journal::stamp_bytes]; + journal::put_stamp(old, we); + old[4] = 16; + CHECK(!journal::read_stamp(old, sizeof(old)).present); + + // A stamped file: read_entry gives the blob alone, with the stamp beside it. + const auto path = journal::entry_path(dir / "stamp", "cs", 5); + const auto file = journal::stamped(we, bare.data(), bare.size()); + CHECK(file.size() == journal::stamp_bytes + bare.size()); + CHECK(!journal::write_entry(path, file.data(), file.size())); + auto entry = journal::read_entry_file(path, id); + CHECK(entry.data == bare && entry.bytes == file.size() && entry.stamp.present && entry.stamp.build == ours && + entry.stamp.config == plain); + CHECK(journal::read_entry(path, id) == bare); + CHECK(!entry.other_build(ours) && entry.other_build(theirs) && entry.other_build(0)); + CHECK(!entry.other_config(plain) && entry.other_config(diagnostics)); + CHECK(!entry.other_writer(we) && entry.other_writer(other_build) && entry.other_writer(other_config)); + CHECK(journal::entry_usable(path, id)); + CHECK(journal::entry_current(path, id, we)); + CHECK(!journal::entry_current(path, id, other_build)); // another build wrote it: built against again + CHECK(!journal::entry_current(path, id, other_config)); // another device config (diagnostics on): the same + CHECK(!journal::entry_current(path, id, {0, plain})); // a build that does not know itself never skips + auto other = id; + other.cache_uuid[0] ^= 1; + CHECK(!journal::entry_usable(path, other) && !journal::entry_current(path, other, we)); + entry = journal::read_entry_file(path, other); + CHECK(entry.data.empty() && !entry.stamp.present && !entry.other_build(theirs) && !entry.other_config(diagnostics)); + // The read limit counts the stamp: it is what is on disk. + CHECK(journal::read_entry(path, id, file.size() - 1).empty() && !journal::entry_usable(path, id, file.size() - 1)); + CHECK(journal::entry_current(path, id, we, file.size())); + + // A stamp for build 0 (a writer that could not read itself) is never current. + const auto zero = journal::stamped({0, plain}, bare.data(), bare.size()); + CHECK(!journal::write_entry(path, zero.data(), zero.size())); + CHECK(journal::entry_usable(path, id) && !journal::entry_current(path, id, {0, plain})); + CHECK(journal::read_entry_file(path, id).other_build(0)); + + // Written under another device config by this build: other_config, not other_build. + const auto diag = journal::stamped(other_config, bare.data(), bare.size()); + CHECK(!journal::write_entry(path, diag.data(), diag.size())); + entry = journal::read_entry_file(path, id); + CHECK(!entry.other_build(ours) && entry.other_config(plain) && entry.other_writer(we)); + CHECK(journal::entry_current(path, id, other_config) && !journal::entry_current(path, id, we)); + + // A file an older runtime wrote (no stamp): still usable, read as from another build (its config unknown, so not + // also counted as another config), never current. + CHECK(!journal::write_entry(path, bare.data(), bare.size())); + entry = journal::read_entry_file(path, id); + CHECK(entry.data == bare && !entry.stamp.present && entry.other_build(ours) && !entry.other_config(plain)); + CHECK(entry.other_writer(we)); + CHECK(journal::entry_usable(path, id) && !journal::entry_current(path, id, we)); + + // A stamp then less than a header, or a stamp then a foreign blob: not usable. + CHECK(!journal::write_entry(path, file.data(), journal::stamp_bytes + 8)); + CHECK(journal::read_entry(path, id).empty() && !journal::entry_usable(path, id)); + const auto foreign = blob(other, 64); + const auto foreign_file = journal::stamped(we, foreign.data(), foreign.size()); + CHECK(!journal::write_entry(path, foreign_file.data(), foreign_file.size())); + CHECK(journal::read_entry(path, id).empty() && !journal::entry_usable(path, id)); + CHECK(journal::read_entry(path, other) == foreign && journal::entry_current(path, other, we)); + + // A seed file's stamp comes with its data. + const auto local = dir / "stamp-local" / "pipeline_cache.d", seed = dir / "stamp-seed"; + const auto seed_file = journal::stamped({theirs, diagnostics}, bare.data(), bare.size()); + CHECK(!journal::write_entry(journal::entry_path(seed, "cs", 6), seed_file.data(), seed_file.size())); + const auto roots = journal::resolve_roots(local, seed); + entry = journal::read_with_seed(journal::entry_path(local, "cs", 6), roots.seed, id, journal::ReadRole::runtime); + CHECK(entry.from_seed && entry.data == bare && entry.stamp.present && entry.stamp.build == theirs && + entry.stamp.config == diagnostics); + CHECK(entry.other_build(ours) && !entry.other_build(theirs) && entry.other_config(plain)); + + // A binary's build: its contents, not its name or folder. + const auto a = dir / "bin" / "gta6rt.exe", copy = dir / "bin2" / "renamed.exe", rebuilt = dir / "bin" / "b.exe"; + std::vector exe(3u << 20); // more than one read chunk + for (std::size_t i = 0; i < exe.size(); ++i) exe[i] = static_cast(i * 2654435761u >> 13); + CHECK(!journal::write_entry(a, exe.data(), exe.size())); + CHECK(!journal::write_entry(copy, exe.data(), exe.size())); + exe[exe.size() / 2] ^= 1; // a one-byte change + CHECK(!journal::write_entry(rebuilt, exe.data(), exe.size())); + const auto build_a = journal::file_build(a); + CHECK(build_a != 0 && build_a == journal::file_build(a) && build_a == journal::file_build(copy)); + CHECK(journal::file_build(rebuilt) != 0 && journal::file_build(rebuilt) != build_a); + CHECK(!journal::write_entry(rebuilt, exe.data(), exe.size() - 1)); // the same bytes, one fewer + CHECK(journal::file_build(rebuilt) != build_a); + CHECK(journal::file_build(dir / "bin" / "missing.exe") == 0); + CHECK(!journal::write_entry(rebuilt, exe.data(), 0)); + CHECK(journal::file_build(rebuilt) == 0); // empty: unknown + return 0; +} + static int test_overlay(const fs::path& dir) { using std::chrono::hours; const auto local = dir / "overlay" / "pipeline_cache.d", seed = dir / "seed"; @@ -329,6 +439,7 @@ int main() { if (!failed) failed = test_names(); if (!failed) failed = test_tidy(dir); if (!failed) failed = test_entry_file(dir); + if (!failed) failed = test_stamp(dir); if (!failed) failed = test_overlay(dir); fs::remove_all(dir, ec); if (failed) return failed; diff --git a/runtime/test/vulkan_device_config_test.cpp b/runtime/test/vulkan_device_config_test.cpp new file mode 100644 index 0000000000..af56825609 --- /dev/null +++ b/runtime/test/vulkan_device_config_test.cpp @@ -0,0 +1,111 @@ +// leonida::device_create_config (src/vulkan_device_config.h): what of a VkDeviceCreateInfo the pipeline journal's stamp +// records, on the CPU. +#include "../src/vulkan_device_config.h" +#include "../src/vulkan_device_fault.h" + +#include +#include +#include + +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + std::fprintf(stderr, "%s:%d: CHECK(%s) failed\n", __FILE__, __LINE__, #cond); \ + return 1; \ + } \ + } while (0) + +namespace { + +VkBool32 diagnostics_supported = VK_TRUE; + +void VKAPI_PTR query_features(VkPhysicalDevice, VkPhysicalDeviceFeatures2* features) { + for (auto* next = static_cast(features->pNext); next; next = next->pNext) { + if (next->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FAULT_FEATURES_EXT) + reinterpret_cast(next)->deviceFault = VK_TRUE; + else if (next->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DIAGNOSTICS_CONFIG_FEATURES_NV) + reinterpret_cast(next)->diagnosticsConfig = + diagnostics_supported; + } +} + +// The runtime's shape: core features, a 1.2/1.3 chain and a few extensions; `fault`: LEONIDA_DEVICE_FAULT's request +// through DeviceFaultFeatures (the device-fault test's fake device), 0 none, 1 with the diagnostics config, 2 without. +struct Device { + VkPhysicalDeviceFeatures core{}; + VkPhysicalDeviceVulkan13Features v13{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES}; + VkPhysicalDeviceVulkan12Features v12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, &v13}; + std::vector extensions{VK_KHR_SWAPCHAIN_EXTENSION_NAME, VK_EXT_ROBUSTNESS_2_EXTENSION_NAME}; + leonida::DeviceFaultFeatures fault_features; + VkDeviceCreateInfo info{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &v12}; + + explicit Device(int fault = 0, VkDeviceDiagnosticsConfigFlagsNV extra = 0) { + core.robustBufferAccess = VK_TRUE; + core.shaderInt64 = VK_TRUE; + v12.bufferDeviceAddress = VK_TRUE; + v13.synchronization2 = VK_TRUE; + if (fault) { + static const VkExtensionProperties advertised[] = {{VK_EXT_DEVICE_FAULT_EXTENSION_NAME, 2}, + {VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME, 2}, + {VK_NV_DEVICE_DIAGNOSTICS_CONFIG_EXTENSION_NAME, 2}}; + fault_features.enable(VK_NULL_HANDLE, query_features, advertised, extensions, info, + {true, fault == 1, extra}); + } + info.pEnabledFeatures = &core; + } + std::uint64_t config() { + info.enabledExtensionCount = std::uint32_t(extensions.size()); + info.ppEnabledExtensionNames = extensions.data(); + return leonida::device_create_config(info); + } +}; + +} // namespace + +int main() { + Device base; + const std::uint64_t plain = base.config(); + CHECK(plain != 0); + CHECK(Device().config() == plain); // the same create info, another process: the same value + + // Extension order does not matter; the set does. + Device reordered; + std::swap(reordered.extensions[0], reordered.extensions[1]); + CHECK(reordered.config() == plain); + Device more; + more.extensions.push_back(VK_EXT_CUSTOM_BORDER_COLOR_EXTENSION_NAME); + CHECK(more.config() != plain); + + // Feature bits, core and chained. + Device no_int64; + no_int64.core.shaderInt64 = VK_FALSE; + CHECK(no_int64.config() != plain); + Device v13_last; + v13_last.v13.maintenance4 = VK_TRUE; // the last member: counted + CHECK(v13_last.config() != plain); + Device v12_last; + v12_last.v12.subgroupBroadcastDynamicId = VK_TRUE; + CHECK(v12_last.config() != plain); + + // LEONIDA_DEVICE_FAULT=1 (diagnostics config) and =2 (fault info and checkpoints only) differ from a plain device + // and from each other; Aftermath's extra flags count. + const std::uint64_t with_config = Device(1).config(); + const std::uint64_t without_config = Device(2).config(); + CHECK(with_config != plain && without_config != plain && with_config != without_config); + CHECK(Device(1).config() == with_config); + const std::uint64_t shader_errors = + Device(1, VK_DEVICE_DIAGNOSTICS_CONFIG_ENABLE_SHADER_ERROR_REPORTING_BIT_NV).config(); + CHECK(shader_errors != with_config && shader_errors != plain); + + // A device without the config feature gets no config struct: =1 is then the same as =2. + diagnostics_supported = VK_FALSE; + CHECK(Device(1).config() == without_config); + diagnostics_supported = VK_TRUE; + + // Nothing enabled at all still hashes to a nonzero value. + VkDeviceCreateInfo empty{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; + CHECK(leonida::device_create_config(empty) != 0 && leonida::device_create_config(empty) != plain); + + std::printf("vulkan_device_config: ok\n"); + return 0; +}