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
7 changes: 6 additions & 1 deletion docs/d3d12_vulkan.md
Original file line number Diff line number Diff line change
Expand Up @@ -2362,7 +2362,12 @@ Pipeline creation:
and pipeline-cache UUID. When the file is absent or incompatible, the runtime starts with an empty cache.
The offline checker matches the runtime's layout and subgroup request for compute shaders with no descriptor
bindings and the standard 144-byte push-constant range.
The runtime writes its own `pipeline_cache.session.bin` on device teardown. A compatible session file
The runtime writes its own `pipeline_cache.session.bin` on device teardown, and, since a title never releases its
device, when `gta6rt` ends with the device alive: at the run's exit, at a console close and from an
unhandled-exception filter (a fault in the title or its DLLs, the int3 after a device loss). The title's own
`SetUnhandledExceptionFilter` is served by the runtime, which keeps its filter first and passes the exception on.
That exit write (`save_pipeline_caches_at_exit`, `shims/d3d12_compile_exit.h`) waits 1 s for a build still running
on a title thread, then writes the pipelines finished so far, with 3 s for the write itself. A compatible session file
initializes the live cache directly if there is no offline seed. With both files present the session cache
merges into the offline seed. `LEONIDA_DIRECT_SESSION_CACHE=0` also uses a merge when only the session exists.
The files must match the Vulkan vendor, device and pipeline-cache UUID. Vulkan supplies an opaque snapshot.
Expand Down
7 changes: 7 additions & 0 deletions runtime/shims/d3d12_compile_exit.h
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,11 @@ namespace rt::d3d12 {
// False when one was still running at the deadline. Defined with the Vulkan device (d3d12_vulkan_device.cpp).
bool stop_pipeline_compiles(unsigned wait_ms);

// Writes each live device's session pipeline cache (pipeline_cache.session.bin), as ~Device does, for a process that
// ends with its devices alive: after stop_pipeline_compiles, so the compiler's own builds are done. A build still
// running on another thread is given `wait_ms`, then the cache is written without it (the pipelines finished so far);
// the write itself is given 3 s before the process goes on ending. Runs once per process; true when a cache write
// finished.
bool save_pipeline_caches_at_exit(unsigned wait_ms);

} // namespace rt::d3d12
75 changes: 73 additions & 2 deletions runtime/shims/d3d12_vulkan_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1422,7 +1422,7 @@ bool startup_cache_checkpoints_enabled() {

// Writes the session cache at a startup checkpoint or during device teardown. The size cap applies to either write.
void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache,
bool checkpoint = false) {
bool checkpoint = false, const char* op = nullptr) {
if (!cache || !vk.vkGetPipelineCacheData) return;
auto limit = pipeline_cache_save_limit();
// The output is an opaque Vulkan blob. A prefix is not an incremental cache.
Expand Down Expand Up @@ -1453,7 +1453,7 @@ void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDev
written <= size && staging.publish(path, written);
if (trace_pipeline_compile())
std::fprintf(stderr, "[rt] pipeline-cache op=%s bytes=%zu query_us=%lld fill_us=%lld publish_us=%lld ok=%d result=%d\n",
checkpoint ? "checkpoint" : "teardown", written, queried-start, filled-queried,
op ? op : checkpoint ? "checkpoint" : "teardown", written, queried-start, filled-queried,
compile_us()-filled, int(ok), int(result));
if (ok) std::fprintf(stderr, "[rt] d3d12: wrote %zu bytes to pipeline_cache.session.bin\n", written);
else std::fprintf(stderr, "[rt] d3d12: pipeline cache snapshot incomplete (%d); previous session retained\n", int(result));
Expand Down Expand Up @@ -10663,6 +10663,14 @@ class QueryHeap final
bool registered_ = false; // added to the context, so removed from it on destruction
};

// The live devices whose session pipeline cache an ending process writes (save_pipeline_caches_at_exit). A title
// never releases its device, so ~Device, the only other writer, does not run in a real boot: without this, a run that
// ends (normally, at a console close or in a crash) keeps none of what it compiled. Timed, so a crash handler that
// finds it held gives up instead of hanging the process.
std::timed_mutex exit_cache_mutex;
std::vector<DeviceState*> exit_cache_devices;
std::atomic<bool> exit_cache_saved{false};

// The Vulkan objects create_vulkan_device_standalone made, destroyed with the device.
struct OwnedRuntime {
PFN_vkDestroyDevice destroy_device = nullptr;
Expand All @@ -10689,6 +10697,10 @@ class Device final
// worker still has a warm-up to run is one too high. The proxy's count waits for the pool.
rt::d3d12_xs::set_reference_settler([] { PipelineCompiler::instance().wait_idle(); });
state_.info = info;
{
std::lock_guard lock(exit_cache_mutex);
exit_cache_devices.push_back(&state_);
}
queue_users_.resize(info.command_queues.size(), 0);
compute_users_.resize(info.compute_queues.size(), 0);
copy_users_.resize(info.copy_queues.size(), 0);
Expand Down Expand Up @@ -11539,6 +11551,11 @@ class Device final
}

~Device() override {
{
// Before anything goes: an exit save in progress finishes with this device first.
std::lock_guard lock(exit_cache_mutex);
std::erase(exit_cache_devices, &state_);
}
leonida::value_sink::clear_arena(&state_); // first: it waits for a value write into the arena in progress
raw_images_.clear();
geometry_refresher_.reset(); // its refresh uses state_.geometry
Expand Down Expand Up @@ -16868,6 +16885,60 @@ bool stop_pipeline_compiles(unsigned wait_ms) {
return idle;
}

// How long an exit save waits for the write itself (save_session_pipeline_cache): a 77 MiB cache was measured at about
// 36 ms (fill and publish), so this only bounds a driver that blocks the read.
constexpr unsigned kExitCacheWriteMs = 3000;

bool save_pipeline_caches_at_exit(unsigned wait_ms) {
if (exit_cache_saved.exchange(true)) return false; // once: a crash during the normal exit's save does not redo it
std::unique_lock lock(exit_cache_mutex, std::defer_lock);
if (!lock.try_lock_for(std::chrono::milliseconds(wait_ms))) {
std::fprintf(stderr, "[rt] d3d12: device list busy for %u ms at exit; pipeline_cache.session.bin not written\n",
wait_ms);
return false;
}
bool wrote = false;
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(wait_ms);
for (DeviceState* d : exit_cache_devices) {
if (!d->context || !d->pipeline_cache_handle) continue;
// A build still running (a large one takes minutes; at a crash the faulting thread may be inside one) is
// given until the deadline, then the cache is written without it. Unlike at teardown, the previous file is
// not kept instead: the process is ending, so waiting longer is not possible and keeping the old file throws
// away everything this run compiled (measured: a 1,308 s boot that ended in a title fault with 2 builds
// running). The cache is not created EXTERNALLY_SYNCHRONIZED, so reading it during a build is valid; the
// snapshot holds the pipelines finished so far.
while (d->active_compiles.load() && std::chrono::steady_clock::now() < deadline)
std::this_thread::sleep_for(std::chrono::milliseconds(5));
if (const unsigned building = d->active_compiles.load())
std::fprintf(stderr, "[rt] d3d12: %u pipeline build(s) still running at exit; writing the pipelines "
"finished so far\n", building);
// On a thread of its own: a driver that holds the cache until a build ends would otherwise hold the ending
// process too. Past the deadline the process goes on ending; the file is published by a rename
// (CacheStagingFile), so a write cut off there leaves the previous file whole.
struct Write {
std::mutex mutex;
std::condition_variable done_cv;
bool done = false;
};
auto write = std::make_shared<Write>();
std::thread([write, d] {
save_session_pipeline_cache(d->context->vk, d->info.device, d->pipeline_cache_handle, false, "exit");
std::lock_guard done_lock(write->mutex);
write->done = true;
write->done_cv.notify_all();
}).detach();
std::unique_lock write_lock(write->mutex);
if (!write->done_cv.wait_for(write_lock, std::chrono::milliseconds(kExitCacheWriteMs),
[&] { return write->done; })) {
std::fprintf(stderr, "[rt] d3d12: pipeline cache still being written after %u ms at exit; the process "
"ends without waiting for it\n", kExitCacheWriteMs);
return wrote; // the device list stays as it is: the write still uses this device
}
wrote = true;
}
return wrote;
}

HRESULT create_vulkan_device(const VulkanDeviceInfo& info, REFIID riid, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
Expand Down
48 changes: 48 additions & 0 deletions runtime/src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
#include <exception>
#include <filesystem>
#include <map>
#include <mutex>
#include <string>
#include <system_error>
#include <vector>
Expand Down Expand Up @@ -231,15 +232,53 @@ int usage() {
// The run ends with the title's Vulkan device alive, so no ~Device stops the background pipeline compiler: stop it
// here, before ExitProcess ends its thread, maybe inside the driver's compiler (rt::d3d12::stop_pipeline_compiles).
constexpr unsigned kExitCompileWaitMs = 2000; // a console close gives the whole process 5 s
// For a build still running on a title thread, then the session cache write (rt::d3d12::save_pipeline_caches_at_exit).
constexpr unsigned kExitCacheWaitMs = 1000;

static BOOL WINAPI stop_compiles_on_console_exit(DWORD event) {
if (event == CTRL_C_EVENT || event == CTRL_BREAK_EVENT || event == CTRL_CLOSE_EVENT) {
rt::d3d12_xs::stop_list_values(500); // as at the run's end: no list-value thread cut off inside the layer
rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs);
rt::d3d12::save_pipeline_caches_at_exit(kExitCacheWaitMs);
}
return FALSE; // the next handler (the default one: ExitProcess) ends the process, as before
}

// A run that ends in an exception nothing handles (a fault in the title or one of its DLLs, the int3 after a device
// loss) would otherwise keep none of the pipelines it compiled, and the next boot builds them all again. The device is
// left alone apart from that write; the exception then goes on as before (the previous filter, or Windows' own
// handling), so the exit code is the exception's. Not for a stack overflow: no stack is left to write with.
static LPTOP_LEVEL_EXCEPTION_FILTER previous_fatal_filter = nullptr;
// The retail title installs a filter of its own (SetUnhandledExceptionFilter from api-ms-win-core-errorhandling),
// which replaced this one and ended the process without it (measured: a title fault at 354 s wrote nothing). Its
// call is served here instead: this filter stays installed and hands the exception to the title's, as Windows would.
static void* volatile title_fatal_filter = nullptr;

static LPTOP_LEVEL_EXCEPTION_FILTER WINAPI title_set_unhandled_exception_filter(LPTOP_LEVEL_EXCEPTION_FILTER filter) {
return reinterpret_cast<LPTOP_LEVEL_EXCEPTION_FILTER>(
InterlockedExchangePointer(&title_fatal_filter, reinterpret_cast<void*>(filter)));
}

static LONG WINAPI save_caches_on_fatal_exception(EXCEPTION_POINTERS* info) {
const DWORD code = info && info->ExceptionRecord ? info->ExceptionRecord->ExceptionCode : 0;
if (code != EXCEPTION_STACK_OVERFLOW) {
// Several title threads can fault at once (measured: eight within a second). The first writes; the others
// wait here for it, so none of them reaches the title's filter, which may end the process, mid-write.
static std::once_flag once;
std::call_once(once, [code] {
std::fprintf(stderr, "[rt] unhandled exception 0x%08lx: writing the session pipeline cache before the "
"process ends\n", static_cast<unsigned long>(code));
rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs);
rt::d3d12::save_pipeline_caches_at_exit(kExitCacheWaitMs);
std::fflush(stderr);
});
}
if (auto* title = reinterpret_cast<LPTOP_LEVEL_EXCEPTION_FILTER>(
InterlockedCompareExchangePointer(&title_fatal_filter, nullptr, nullptr)))
return title(info);
return previous_fatal_filter ? previous_fatal_filter(info) : EXCEPTION_CONTINUE_SEARCH;
}

static BOOL WINAPI show_package_window(HWND window, int command) {
const BOOL previous = ShowWindow(window, command);
const DWORD error = GetLastError();
Expand Down Expand Up @@ -347,6 +386,13 @@ int wmain(int argc, wchar_t** argv) {
rt::fs::configure(game_dir, overlay_dir);
#ifdef LEONIDA_VULKAN_DEVICE
if (run) {
// Before the image is loaded, so its import binds here (save_caches_on_fatal_exception).
const rt::shims::Entry filter_imports[] = {
{"api-ms-win-core-errorhandling-l1-1-0.dll", "SetUnhandledExceptionFilter",
reinterpret_cast<void*>(&title_set_unhandled_exception_filter)},
{"kernel32.dll", "SetUnhandledExceptionFilter", reinterpret_cast<void*>(&title_set_unhandled_exception_filter)},
};
rt::shims::Table{filter_imports, std::size(filter_imports)};
rt::package_splash::configure(game_dir);
if (rt::package_splash::configured()) {
const rt::shims::Entry window_imports[] = {
Expand Down Expand Up @@ -516,6 +562,7 @@ int wmain(int argc, wchar_t** argv) {
leonida::thread_sampler::start(main_module.base, main_module.size); // LEONIDA_SAMPLE_MS (diagnostic)
#ifdef LEONIDA_VULKAN_DEVICE
SetConsoleCtrlHandler(&stop_compiles_on_console_exit, TRUE);
previous_fatal_filter = SetUnhandledExceptionFilter(&save_caches_on_fatal_exception);
#endif
int code;
{
Expand All @@ -536,6 +583,7 @@ int wmain(int argc, wchar_t** argv) {
rt::d3d12_xs::stop_list_values(500);
#ifdef LEONIDA_VULKAN_DEVICE
rt::d3d12::stop_pipeline_compiles(kExitCompileWaitMs);
rt::d3d12::save_pipeline_caches_at_exit(kExitCacheWaitMs);
#endif
rt::cleanup_tls_clones();
ExitProcess(static_cast<UINT>(code));
Expand Down
31 changes: 21 additions & 10 deletions runtime/test/d3d12_compile_teardown_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@
// racing many PSOs released at once with builds queued and one usually running, repeated.
// restart a device made after the worker stopped gets a new one, and its builds run.
// exit stop_pipeline_compiles with a device alive: the queue goes, later builds are refused, a warm-up
// is skipped and a dispatch (LEONIDA_ASYNC_PIPELINES on) builds its pipeline in place and runs.
// is skipped and a dispatch (LEONIDA_ASYNC_PIPELINES on) builds its pipeline in place and runs;
// save_pipeline_caches_at_exit then writes the session cache with the device alive, once.
// After each case the compiler's thread is gone and the process's thread count is back where it was.
// No game data: the shader is test/glsl/cs_user_data.comp, the programs are made-up FSSM bytes.
#include "shader_fixture_path.h"
Expand Down Expand Up @@ -423,6 +424,14 @@ int main() {

auto& compiler = PipelineCompiler::instance();
EXPECT(!compiler.worker_running());
// llvmpipe keeps no pipelines in a VkPipelineCache (measured: vkGetPipelineCacheData returns the 32-byte header
// alone after the build), and the runtime writes no file of a bare header (save_session_pipeline_cache).
VkPhysicalDeviceDriverProperties driver{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES};
VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &driver};
reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>(
d.instance_proc(d.instance, "vkGetPhysicalDeviceProperties2"))(d.physical, &properties);
const bool caches = driver.driverID != VK_DRIVER_ID_MESA_LLVMPIPE;
const auto session_file = cache_dir / "pipeline_cache.session.bin";

// --- cache: one PSO built by the warm-up thread; the device writes the session cache at teardown -------------
{
Expand All @@ -433,14 +442,7 @@ int main() {
EXPECT(built(s.psos[0]));
s.release();
EXPECT(!compiler.worker_running());
// llvmpipe keeps no pipelines in a VkPipelineCache (measured: vkGetPipelineCacheData returns the 32-byte
// header alone after the build), and the runtime writes no file of a bare header (save_session_pipeline_cache).
VkPhysicalDeviceDriverProperties driver{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES};
VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &driver};
reinterpret_cast<PFN_vkGetPhysicalDeviceProperties2>(
d.instance_proc(d.instance, "vkGetPhysicalDeviceProperties2"))(d.physical, &properties);
const bool caches = driver.driverID != VK_DRIVER_ID_MESA_LLVMPIPE;
EXPECT(std::filesystem::exists(cache_dir / "pipeline_cache.session.bin") == caches);
EXPECT(std::filesystem::exists(session_file) == caches);
std::printf("cache: built in the background, session cache %s at teardown, worker joined\n",
caches ? "written" : "not written (the driver keeps no pipelines in its cache)");
}
Expand Down Expand Up @@ -660,10 +662,19 @@ int main() {
if (s.dispatch(pso, fresh)) return 1;
EXPECT(built(pso));
EXPECT(compiler.stats().submitted == before.submitted);
// The process ends with the device alive (a title never releases it): the exit save writes the session
// cache now, not at a teardown that will not come, and only once.
std::error_code ec;
std::filesystem::remove(session_file, ec);
EXPECT(!std::filesystem::exists(session_file));
EXPECT(rt::d3d12::save_pipeline_caches_at_exit(1000));
EXPECT(std::filesystem::exists(session_file) == caches);
EXPECT(!rt::d3d12::save_pipeline_caches_at_exit(1000));
s.release(); // the device's teardown after the exit stop: nothing left to cancel or join
EXPECT(!compiler.worker_running());
EXPECT(rt::d3d12::live_pipeline_states() == 0); // no PSO of any case leaked
std::printf("exit: queue dropped, later builds refused, a dispatch built its pipeline in place and ran\n");
std::printf("exit: queue dropped, later builds refused, a dispatch built its pipeline in place and ran, "
"session cache %s with the device alive, once\n", caches ? "written" : "not written (llvmpipe)");
}
std::printf("ok\n");
return 0;
Expand Down