diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 43886af30f..edbaf138f9 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -4335,6 +4335,27 @@ when it cannot sample the submission lock for that long. A progress warning leav device state intact. The driver checkpoint and fault-info queries run after Vulkan reports device loss. This mode is off by default. +Each fault address is also looked up in this process (RT-FAULT-ADDRESS-OWNER). On Windows, `VirtualQuery` of the +same number gives the region's base, allocation base, state, protection and type. A GPU address isn't a CPU one, +but a host import, a range of the title's memory and a raw CPU pointer that reached a shader all share the +number. With `LEONIDA_ADDRESS_BINDINGS=1` as well, the device enables `VK_EXT_device_address_binding_report`, and +a debug messenger records the GPU virtual address range of every buffer, image and allocation the driver binds +and unbinds (`runtime/src/address_binding.h`). The fault report then lists, for each address: +- the live objects that contain the address ("containing"), and those that only share its reported page, whose + size is the fault's `addressPrecision` ("on the page"); +- the live objects that end nearest below it and start nearest above it; +- up to 16 recently unbound objects that held it, with their type, range, handle and the times they were bound + and unbound. + +"Nothing live or recently unbound there" means that no object of this device had that GPU address. On an +RTX 5070 Ti the world-start loss of 1.0.2.1 reported write addresses far above every bound range, at about 50,000 +binds. The record keeps the last 16,384 unbinds and costs one map entry per live binding. + +There is one record per process. A second Vulkan instance in the same process (a second device) is refused a +messenger, and its device doesn't enable the extension, so the two devices' GPU addresses aren't mixed. If +`LEONIDA_ADDRESS_BINDINGS=1` is set but no messenger records the device, the fault report says that the bindings +were not recorded, so this can't be mistaken for "nothing live or recently unbound there". + Each dispatch line carries a `seq`: a number every recorded dispatch gets, across queues and submissions, in the order the submissions were recorded. The list keeps the last 64, so its numbers can have gaps where a submission recorded more than that. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 10ee582b12..38fb6435ad 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1896,6 +1896,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) + add_executable(address_binding_test test/address_binding_test.cpp) + target_link_libraries(address_binding_test PRIVATE Vulkan::Headers) + add_test(NAME address_binding COMMAND address_binding_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_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 1fb36401e3..cc8b84f084 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -14396,7 +14396,10 @@ class Device final state_.context.reset(); state_.image_memory.reset(); // the context's deferred queue gave its ranges back if (owned_.device) owned_.destroy_device(owned_.device, nullptr); - if (owned_.instance) owned_.destroy_instance(owned_.instance, nullptr); + if (owned_.instance) { + leonida::address_binding::uninstall_messenger(owned_.instance); + owned_.destroy_instance(owned_.instance, nullptr); + } } bool ok() const { return state_.context && state_.context->loaded(); } @@ -20697,8 +20700,11 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin return E_FAIL; } owned.destroy_instance = reinterpret_cast(get(owned.instance, "vkDestroyInstance")); + // LEONIDA_ADDRESS_BINDINGS: the device's bindings reach this messenger from vkCreateDevice on (address_binding.h). + if (has_debug_utils) leonida::address_binding::install_messenger(owned.instance, get); const auto fail = [&](const char* why) { std::fprintf(stderr, "[rt] d3d12: %s\n", why); + leonida::address_binding::uninstall_messenger(owned.instance); owned.destroy_instance(owned.instance, nullptr); return E_FAIL; }; @@ -21439,6 +21445,8 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin if (aftermath && !info.device_diagnostics_config) std::fprintf(stderr, "[rt] aftermath: VK_NV_device_diagnostics_config unavailable; the dump has no shader " "debug info, resource tracking or checkpoints\n"); + leonida::address_binding::enable_device(owned.instance, info.physical, vkGetPhysicalDeviceFeatures2, extensions, + device_extensions, device_info); device_info.enabledExtensionCount = std::uint32_t(device_extensions.size()); device_info.ppEnabledExtensionNames = device_extensions.empty() ? nullptr : device_extensions.data(); if (vkCreateDevice(info.physical, &device_info, nullptr, &owned.device) != VK_SUCCESS) diff --git a/runtime/src/address_binding.h b/runtime/src/address_binding.h new file mode 100644 index 0000000000..b8c54e18b1 --- /dev/null +++ b/runtime/src/address_binding.h @@ -0,0 +1,303 @@ +#pragma once +// LEONIDA_ADDRESS_BINDINGS=1, with LEONIDA_DEVICE_FAULT=1: names what the driver had bound at a device-fault address +// (RT-FAULT-ADDRESS-OWNER). VK_EXT_device_address_binding_report has the driver report the GPU virtual address range +// of every buffer, image and allocation as it is bound and unbound, to the instance's debug messengers. This keeps +// the live ranges and the most recent unbound ones, so the device-fault report (vulkan_device_fault.h) can say which +// object contains a faulting address, which objects end right below it and start right above it, and which objects +// held it before. An address that none of them covers is a GPU address no object of this device was ever given. +// +// The record and the report are pure (record_binding, report); the Vulkan side is install_messenger before +// vkCreateDevice's bindings start and enable_device on the device's create chain. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida::address_binding { + +struct Entry { + std::uint64_t base = 0, size = 0; + VkObjectType type = VK_OBJECT_TYPE_UNKNOWN; + std::uint64_t handle = 0; + bool internal = false; // VK_DEVICE_ADDRESS_BINDING_INTERNAL_OBJECT_BIT_EXT + double bound_at = 0, unbound_at = 0; // seconds since the record started; unbound_at 0 while live +}; + +class Record { +public: + static constexpr std::size_t kept_unbound = 16384; + + // One report: bound, or unbound (matched to its live entry by base, handle and size). + void record(Entry e, bool bind, double now) { + std::lock_guard lock(mutex_); + if (bind) { + e.bound_at = now; + live_.emplace(e.base, e); + ++binds_; + return; + } + ++unbinds_; + auto [first, last] = live_.equal_range(e.base); + for (auto it = first; it != last; ++it) { + if (it->second.handle != e.handle || it->second.size != e.size) continue; + e = it->second; + live_.erase(it); + break; + } + e.unbound_at = now; + unbound_.push_back(e); + if (unbound_.size() > kept_unbound) unbound_.pop_front(); + } + + // What was bound at and around the `precision`-sized page of `address`, one line per finding. + std::string report(std::uint64_t address, std::uint64_t precision) const { + std::lock_guard lock(mutex_); + std::string out; + char line[160]; + std::snprintf(line, sizeof line, "0x%" PRIx64 " (precision 0x%" PRIx64 "): %" PRIu64 " binds, %" PRIu64 + " unbinds, %zu live\n", + address, precision, binds_, unbinds_, live_.size()); + out += line; + const std::uint64_t lo = precision > 1 ? address & ~(precision - 1) : address; + const std::uint64_t hi = lo + (precision > 1 ? precision : 1); + const auto overlaps = [&](const Entry& e) { return e.base < hi && e.base + e.size > lo; }; + int containing = 0; + const Entry* below = nullptr; + const Entry* above = nullptr; + // "containing" only for an object the address itself is in; one that shares only the reported page with it is + // "on the page", since the driver gives the fault address no closer than `precision`. + const auto inside = [&](const Entry& e) { return address >= e.base && address - e.base < e.size; }; + for (const auto& [base, e] : live_) { + if (overlaps(e)) { + if (containing++ < 16) out += describe(inside(e) ? "live, containing" : "live, on the page", e, address); + continue; + } + if (base + e.size <= lo && (!below || base + e.size > below->base + below->size)) below = &e; + if (base >= hi && (!above || base < above->base)) above = &e; + } + if (below) out += describe("live, nearest below", *below, address); + if (above) out += describe("live, nearest above", *above, address); + int held = 0; + for (auto it = unbound_.rbegin(); it != unbound_.rend() && held < 16; ++it) + if (overlaps(*it)) { + out += describe(inside(*it) ? "unbound, held it" : "unbound, held the page", *it, address); + ++held; + } + if (!containing && !held) out += " nothing live or recently unbound there\n"; + return out; + } + +private: + static const char* type_name(VkObjectType t) { + switch (t) { + case VK_OBJECT_TYPE_BUFFER: return "buffer"; + case VK_OBJECT_TYPE_IMAGE: return "image"; + case VK_OBJECT_TYPE_DEVICE_MEMORY: return "memory"; + case VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_KHR: return "acceleration structure"; + case VK_OBJECT_TYPE_COMMAND_BUFFER: return "command buffer"; + case VK_OBJECT_TYPE_PIPELINE: return "pipeline"; + case VK_OBJECT_TYPE_QUERY_POOL: return "query pool"; + case VK_OBJECT_TYPE_DESCRIPTOR_POOL: return "descriptor pool"; + default: return "object"; + } + } + + static std::string describe(const char* what, const Entry& e, std::uint64_t address) { + const std::uint64_t end = e.base + e.size; + const char* relation; + std::uint64_t distance; + if (address >= e.base && address < end) { + relation = "into"; + distance = address - e.base; + } else if (address >= end) { + relation = "past the end of"; + distance = address - end; + } else { + relation = "before"; + distance = e.base - address; + } + char line[320]; + std::snprintf(line, sizeof line, + " %s: %s%s 0x%" PRIx64 "..0x%" PRIx64 " (%" PRIu64 " KiB) handle 0x%" PRIx64 + " bound at %.1f s%s; the address is 0x%" PRIx64 " %s it\n", + what, type_name(e.type), e.internal ? " (driver-internal)" : "", e.base, end, e.size >> 10, + e.handle, e.bound_at, e.unbound_at ? (", unbound at " + std::to_string(e.unbound_at) + " s").c_str() : "", + distance, relation); + return line; + } + + mutable std::mutex mutex_; + std::multimap live_; // by base address + std::deque unbound_; // the most recent last + std::uint64_t binds_ = 0, unbinds_ = 0; +}; + +struct State { + std::mutex install; // the messenger fields below; the record has a lock of its own + Record record; + std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now(); + VkPhysicalDeviceAddressBindingReportFeaturesEXT feature{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ADDRESS_BINDING_REPORT_FEATURES_EXT}; + VkDebugUtilsMessengerEXT messenger = VK_NULL_HANDLE; + VkInstance messenger_instance = VK_NULL_HANDLE; + PFN_vkDestroyDebugUtilsMessengerEXT destroy_messenger = nullptr; + // A device enabled the report and this process's messenger records it. Read at a device fault on whatever thread + // notices it, so atomic. + std::atomic on{false}; +}; + +inline State& state() { + static State s; + return s; +} + +inline bool requested() { + const char* v = std::getenv("LEONIDA_ADDRESS_BINDINGS"); + return v && v[0] == '1' && !v[1]; +} + +inline VKAPI_ATTR VkBool32 VKAPI_CALL on_message(VkDebugUtilsMessageSeverityFlagBitsEXT, + VkDebugUtilsMessageTypeFlagsEXT types, + const VkDebugUtilsMessengerCallbackDataEXT* data, void*) { + if (!(types & VK_DEBUG_UTILS_MESSAGE_TYPE_DEVICE_ADDRESS_BINDING_BIT_EXT) || !data) return VK_FALSE; + const VkDeviceAddressBindingCallbackDataEXT* binding = nullptr; + for (auto* p = static_cast(data->pNext); p; p = p->pNext) + if (p->sType == VK_STRUCTURE_TYPE_DEVICE_ADDRESS_BINDING_CALLBACK_DATA_EXT) + binding = reinterpret_cast(p); + if (!binding) return VK_FALSE; + State& s = state(); + Entry e; + e.base = binding->baseAddress; + e.size = binding->size; + e.internal = (binding->flags & VK_DEVICE_ADDRESS_BINDING_INTERNAL_OBJECT_BIT_EXT) != 0; + if (data->objectCount && data->pObjects) { + e.type = data->pObjects[0].objectType; + e.handle = data->pObjects[0].objectHandle; + } + const double now = std::chrono::duration(std::chrono::steady_clock::now() - s.start).count(); + s.record.record(e, binding->bindingType == VK_DEVICE_ADDRESS_BINDING_TYPE_BIND_EXT, now); + return VK_FALSE; +} + +// Before vkCreateDevice: adds the extension and its feature to `device`'s chain when the device has them and +// `instance` has this process's messenger. Without the messenger nothing would record the reports, so the device is +// left as it is and a fault report says the bindings were not recorded. +inline bool enable_device(VkInstance instance, VkPhysicalDevice physical, PFN_vkGetPhysicalDeviceFeatures2 query, + std::span advertised, std::vector& extensions, + VkDeviceCreateInfo& device) { + if (!requested() || !query) return false; + { + State& s = state(); + std::lock_guard lock(s.install); + if (!s.messenger || s.messenger_instance != instance) { + std::fprintf(stderr, "[rt] address-binding: no messenger on this device's instance; bindings are not " + "recorded\n"); + return false; + } + } + const bool has = std::any_of(advertised.begin(), advertised.end(), [](const auto& e) { + return std::strcmp(e.extensionName, VK_EXT_DEVICE_ADDRESS_BINDING_REPORT_EXTENSION_NAME) == 0; + }); + State& s = state(); + if (!has) { + std::fprintf(stderr, "[rt] address-binding: the device has no VK_EXT_device_address_binding_report\n"); + return false; + } + s.feature.pNext = nullptr; + VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &s.feature}; + query(physical, &features); + if (!s.feature.reportAddressBinding) { + std::fprintf(stderr, "[rt] address-binding: reportAddressBinding is not supported\n"); + return false; + } + extensions.push_back(VK_EXT_DEVICE_ADDRESS_BINDING_REPORT_EXTENSION_NAME); + s.feature.pNext = const_cast(device.pNext); + device.pNext = &s.feature; + s.on = true; + return true; +} + +// After vkCreateInstance with VK_EXT_debug_utils and before vkCreateDevice: bindings reach the instance's messengers +// as they happen. +inline void install_messenger(VkInstance instance, PFN_vkGetInstanceProcAddr get) { + if (!requested() || !instance || !get) return; + const auto create = + reinterpret_cast(get(instance, "vkCreateDebugUtilsMessengerEXT")); + if (!create) { + std::fprintf(stderr, "[rt] address-binding: no vkCreateDebugUtilsMessengerEXT\n"); + return; + } + VkDebugUtilsMessengerCreateInfoEXT info{VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT}; + info.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT | + VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; + info.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_DEVICE_ADDRESS_BINDING_BIT_EXT; + info.pfnUserCallback = &on_message; + State& s = state(); + std::lock_guard lock(s.install); + // One record per process: a second instance (a second device in one process) would mix its GPU addresses with + // the first's, and overwriting the handle would leave the first messenger alive past its instance. So the + // second one is refused, and its device is not enabled. + if (s.messenger) { + std::fprintf(stderr, "[rt] address-binding: a messenger is already installed for another instance; this " + "instance's bindings are not recorded\n"); + return; + } + VkDebugUtilsMessengerEXT messenger = VK_NULL_HANDLE; + const VkResult r = create(instance, &info, nullptr, &messenger); + if (r == VK_SUCCESS) { + s.messenger = messenger; + s.messenger_instance = instance; + s.destroy_messenger = reinterpret_cast( + get(instance, "vkDestroyDebugUtilsMessengerEXT")); + } + std::fprintf(stderr, "[rt] address-binding: messenger %s\n", r == VK_SUCCESS ? "installed" : "failed"); +} + +// Before vkDestroyInstance: a messenger may not outlive its instance. What it recorded stays. +inline void uninstall_messenger(VkInstance instance) { + State& s = state(); + std::lock_guard lock(s.install); + if (!s.messenger || s.messenger_instance != instance) return; + if (s.destroy_messenger) s.destroy_messenger(instance, s.messenger, nullptr); + s.messenger = VK_NULL_HANDLE; + s.messenger_instance = VK_NULL_HANDLE; + s.destroy_messenger = nullptr; + s.on = false; +} + +// At a device fault: what the driver had bound at and around `address`, on stderr. +inline void describe(std::uint64_t address, std::uint64_t precision) { + State& s = state(); + if (!s.on) { + // Asked for but not recording: say so, rather than leave a report that reads as "no object there". + if (requested()) + std::fprintf(stderr, "[rt] address-binding: 0x%" PRIx64 ": bindings were not recorded for this device (no " + "messenger or no VK_EXT_device_address_binding_report; see the address-binding " + "lines at startup)\n", address); + return; + } + const std::string text = s.record.report(address, precision); + std::size_t at = 0; + while (at < text.size()) { + const std::size_t end = text.find('\n', at); + std::fprintf(stderr, "[rt] address-binding: %.*s\n", int((end == std::string::npos ? text.size() : end) - at), + text.c_str() + at); + if (end == std::string::npos) break; + at = end + 1; + } +} + +} // namespace leonida::address_binding diff --git a/runtime/src/vulkan_device_fault.h b/runtime/src/vulkan_device_fault.h index b3af188d13..50094e9626 100644 --- a/runtime/src/vulkan_device_fault.h +++ b/runtime/src/vulkan_device_fault.h @@ -1,6 +1,14 @@ #pragma once #include +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include // VirtualQuery: what the process has at a fault address +#endif + +#include "address_binding.h" // LEONIDA_ADDRESS_BINDINGS: the bound object at a fault address #include "vulkan_device_markers.h" @@ -998,6 +1006,19 @@ class DeviceFaultDiagnostics { std::fprintf(stderr, "[rt] device-fault: address[%zu] type=%d address=0x%" PRIx64 " precision=%" PRIu64 "\n", i, int(address.addressType), address.reportedAddress, address.addressPrecision); +#ifdef _WIN32 + // The page in this process at the same number. A GPU address is not a CPU one, but a host import, a title + // range or a raw CPU pointer that reached the GPU shares it, so the region says which of those it can be. + MEMORY_BASIC_INFORMATION page{}; + if (VirtualQuery(reinterpret_cast(static_cast(address.reportedAddress)), &page, + sizeof page)) + std::fprintf(stderr, "[rt] device-fault: address[%zu] in this process: base %p allocation %p size 0x%zx " + "state 0x%lx protect 0x%lx type 0x%lx\n", + i, page.BaseAddress, page.AllocationBase, page.RegionSize, + static_cast(page.State), static_cast(page.Protect), + static_cast(page.Type)); +#endif + leonida::address_binding::describe(address.reportedAddress, address.addressPrecision); } for (std::size_t i = 0; i < counts.vendorInfoCount; ++i) { const auto& vendor = vendors[i]; diff --git a/runtime/test/address_binding_test.cpp b/runtime/test/address_binding_test.cpp new file mode 100644 index 0000000000..ebb87cde32 --- /dev/null +++ b/runtime/test/address_binding_test.cpp @@ -0,0 +1,265 @@ +// src/address_binding.h: the record of VK_EXT_device_address_binding_report reports and what it says about a +// device-fault address. Synthetic reports only: no Vulkan device, no GPU. +#include "../src/address_binding.h" + +#include +#include +#include +#include +#include +#include +#include + +#ifndef _WIN32 +static int _putenv_s(const char* name, const char* value) { return setenv(name, value, 1); } +#endif + +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ + return 1; \ + } \ +} while (0) + +using namespace leonida::address_binding; + +static bool has(const std::string& text, const char* part) { return text.find(part) != std::string::npos; } + +static Entry entry(std::uint64_t base, std::uint64_t size, VkObjectType type, std::uint64_t handle) { + Entry e; + e.base = base; + e.size = size; + e.type = type; + e.handle = handle; + return e; +} + +static int test_record() { + Record r; + r.record(entry(0x10000, 0x1cf000, VK_OBJECT_TYPE_IMAGE, 0xa), true, 1.0); // ends at 0x1df000 + r.record(entry(0x200000, 0x10000, VK_OBJECT_TYPE_BUFFER, 0xb), true, 2.0); + r.record(entry(0x400000, 0x1000, VK_OBJECT_TYPE_BUFFER, 0xc), true, 3.0); + r.record(entry(0x400000, 0x1000, VK_OBJECT_TYPE_BUFFER, 0xc), false, 4.0); // unbound again + + // Inside the image: it contains the page. + std::string text = r.report(0x1ce000, 0x1000); + CHECK(has(text, "3 binds, 1 unbinds, 2 live")); + CHECK(has(text, "live, containing: image 0x10000..0x1df000")); + CHECK(has(text, "0x1be000 into it")); + + // The page just past the image and below the buffer: no owner, the neighbours either side. + text = r.report(0x1e0123, 0x1000); + CHECK(!has(text, "containing")); + CHECK(has(text, "nearest below: image")); + CHECK(has(text, "0x1123 past the end of it")); // from the address, not its page + CHECK(has(text, "nearest above: buffer 0x200000")); + CHECK(has(text, "nothing live or recently unbound there")); + + // Where the unbound buffer was: it held the page, and nothing live does. + text = r.report(0x400800, 0x1000); + CHECK(has(text, "unbound, held it: buffer 0x400000..0x401000")); + CHECK(has(text, "unbound at 4.0")); + CHECK(!has(text, "nothing live")); + + // Far above everything: only the nearest below, which is the highest live object. + text = r.report(0x29b52a80000, 0x1000); + CHECK(has(text, "nearest below: buffer 0x200000")); + CHECK(!has(text, "nearest above")); + return 0; +} + +// The edges of an object and of the reported page (review of RT-FAULT-ADDRESS-OWNER). +static int test_boundaries() { + Record r; + r.record(entry(0x10000, 0x1cf000, VK_OBJECT_TYPE_IMAGE, 0xa), true, 1.0); // ends at 0x1df000 + // The last byte of the image is in it. + std::string text = r.report(0x1defff, 0x1000); + CHECK(has(text, "live, containing: image")); + CHECK(has(text, "0x1cefff into it")); + // The byte right after its end is not, whatever the precision of a page that starts there. + text = r.report(0x1df000, 0x1000); + CHECK(!has(text, "live, containing") && !has(text, "on the page")); + CHECK(has(text, "nearest below: image") && has(text, "0x0 past the end of it")); + text = r.report(0x1df000, 1); + CHECK(!has(text, "live, containing") && has(text, "nearest below: image")); + // A coarse page that reaches back into the image: the image is on the page, but does not contain the address. + text = r.report(0x1df010, 0x2000); + CHECK(has(text, "live, on the page: image") && !has(text, "live, containing")); + CHECK(has(text, "0x10 past the end of it")); + CHECK(!has(text, "nothing live")); + // The same address at byte precision: no object there, only the neighbour. + text = r.report(0x1df010, 1); + CHECK(!has(text, "on the page") && has(text, "nearest below: image")); + CHECK(has(text, "nothing live or recently unbound there")); + // The first byte of the image, and the one before it. + CHECK(has(r.report(0x10000, 1), "live, containing: image")); + text = r.report(0xffff, 1); + CHECK(has(text, "nearest above: image") && has(text, "0x1 before it")); + // An unbound object that only shares the page is "held the page", not "held it". + r.record(entry(0x300000, 0x800, VK_OBJECT_TYPE_BUFFER, 0xd), true, 2.0); + r.record(entry(0x300000, 0x800, VK_OBJECT_TYPE_BUFFER, 0xd), false, 3.0); + CHECK(has(r.report(0x300900, 0x1000), "unbound, held the page: buffer 0x300000..0x300800")); + CHECK(has(r.report(0x300100, 0x1000), "unbound, held it: buffer 0x300000..0x300800")); + return 0; +} + +// An unbind removes only the live entry with the same base, handle and size; the unbound list is capped. +static int test_unbind_matching_and_cap() { + Record r; + r.record(entry(0x100000, 0x1000, VK_OBJECT_TYPE_BUFFER, 0x1), true, 1.0); + r.record(entry(0x100000, 0x1000, VK_OBJECT_TYPE_BUFFER, 0x2), true, 1.0); // aliased: same base, other handle + r.record(entry(0x100000, 0x2000, VK_OBJECT_TYPE_BUFFER, 0x2), false, 2.0); // size differs: no live entry goes + CHECK(has(r.report(0x100000, 0x1000), "2 live")); + r.record(entry(0x100000, 0x1000, VK_OBJECT_TYPE_BUFFER, 0x3), false, 2.0); // handle differs: none goes + CHECK(has(r.report(0x100000, 0x1000), "2 live")); + r.record(entry(0x100000, 0x1000, VK_OBJECT_TYPE_BUFFER, 0x2), false, 3.0); // matches the second only + std::string text = r.report(0x100000, 0x1000); + CHECK(has(text, "1 live")); + CHECK(has(text, "live, containing: buffer 0x100000..0x101000 (4 KiB) handle 0x1")); + CHECK(!has(text, "live, containing: buffer 0x100000..0x101000 (4 KiB) handle 0x2")); + + // Past kept_unbound, the oldest unbound objects are forgotten and the newest kept. + Record capped; + const std::uint64_t n = Record::kept_unbound + 8; + for (std::uint64_t i = 0; i < n; ++i) { + const auto e = entry(0x1000000 + i * 0x1000, 0x1000, VK_OBJECT_TYPE_BUFFER, 0x100 + i); + capped.record(e, true, 1.0); + capped.record(e, false, 2.0); + } + CHECK(has(capped.report(0x1000000, 0x1000), "nothing live or recently unbound there")); // the first, dropped + CHECK(has(capped.report(0x1000000 + 7 * 0x1000, 0x1000), "nothing live or recently unbound")); // the 8th + CHECK(has(capped.report(0x1000000 + 8 * 0x1000, 0x1000), "unbound, held it")); // the oldest one kept + CHECK(has(capped.report(0x1000000 + (n - 1) * 0x1000, 0x1000), "unbound, held it")); + return 0; +} + +// The messenger's thread records while a device-fault report reads. +static int test_threads() { + Record r; + constexpr int threads = 4, per = 2000; + std::vector pool; + for (int t = 0; t < threads; ++t) + pool.emplace_back([&r, t] { + for (int i = 0; i < per; ++i) { + const auto e = entry(0x10000000ull * (t + 1) + std::uint64_t(i) * 0x1000, 0x1000, + VK_OBJECT_TYPE_BUFFER, std::uint64_t(t) << 32 | std::uint64_t(i)); + r.record(e, true, 1.0); + if (i % 2) r.record(e, false, 2.0); + } + }); + pool.emplace_back([&r] { + for (int i = 0; i < 200; ++i) (void)r.report(0x10000000ull + std::uint64_t(i) * 0x1000, 0x1000); + }); + for (auto& thread : pool) thread.join(); + char expect[96]; + std::snprintf(expect, sizeof expect, "%d binds, %d unbinds, %d live", threads * per, threads * per / 2, + threads * per / 2); + CHECK(has(r.report(0, 0x1000), expect)); + return 0; +} + +static int test_messages() { + // Through the messenger callback, as the driver delivers them. + VkDeviceAddressBindingCallbackDataEXT binding{VK_STRUCTURE_TYPE_DEVICE_ADDRESS_BINDING_CALLBACK_DATA_EXT}; + binding.baseAddress = 0x800000; + binding.size = 0x2000; + binding.bindingType = VK_DEVICE_ADDRESS_BINDING_TYPE_BIND_EXT; + binding.flags = VK_DEVICE_ADDRESS_BINDING_INTERNAL_OBJECT_BIT_EXT; + VkDebugUtilsObjectNameInfoEXT object{VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT}; + object.objectType = VK_OBJECT_TYPE_DEVICE_MEMORY; + object.objectHandle = 0x77; + VkDebugUtilsMessengerCallbackDataEXT data{VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CALLBACK_DATA_EXT, &binding}; + data.objectCount = 1; + data.pObjects = &object; + // A message of another type is not a binding. + on_message(VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT, VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT, &data, nullptr); + CHECK(has(state().record.report(0x800000, 0x1000), "0 binds")); + on_message(VK_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT, VK_DEBUG_UTILS_MESSAGE_TYPE_DEVICE_ADDRESS_BINDING_BIT_EXT, + &data, nullptr); + const std::string text = state().record.report(0x801000, 0x1000); + CHECK(has(text, "1 binds")); + CHECK(has(text, "live, containing: memory (driver-internal) 0x800000..0x802000")); + CHECK(has(text, "handle 0x77")); + return 0; +} + +static VKAPI_ATTR void VKAPI_CALL features(VkPhysicalDevice, VkPhysicalDeviceFeatures2* f) { + for (auto* p = static_cast(f->pNext); p; p = p->pNext) + if (p->sType == VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ADDRESS_BINDING_REPORT_FEATURES_EXT) + reinterpret_cast(p)->reportAddressBinding = VK_TRUE; +} + +// A fake debug-utils instance: messengers are numbered as they are made and counted as they are destroyed. +static int created_messengers = 0, destroyed_messengers = 0; + +static VKAPI_ATTR VkResult VKAPI_CALL fake_create(VkInstance, const VkDebugUtilsMessengerCreateInfoEXT*, + const VkAllocationCallbacks*, VkDebugUtilsMessengerEXT* out) { + *out = reinterpret_cast(static_cast(++created_messengers)); + return VK_SUCCESS; +} + +static VKAPI_ATTR void VKAPI_CALL fake_destroy(VkInstance, VkDebugUtilsMessengerEXT, const VkAllocationCallbacks*) { + ++destroyed_messengers; +} + +static VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL fake_get(VkInstance, const char* name) { + if (std::strcmp(name, "vkCreateDebugUtilsMessengerEXT") == 0) return reinterpret_cast(&fake_create); + if (std::strcmp(name, "vkDestroyDebugUtilsMessengerEXT") == 0) + return reinterpret_cast(&fake_destroy); + return nullptr; +} + +static VkInstance fake_instance(std::uintptr_t n) { return reinterpret_cast(n); } + +static int test_enable() { + VkExtensionProperties ext{}; + std::snprintf(ext.extensionName, sizeof ext.extensionName, "%s", VK_EXT_DEVICE_ADDRESS_BINDING_REPORT_EXTENSION_NAME); + std::vector extensions; + VkDeviceCreateInfo device{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; + // Not asked for: nothing changes. + _putenv_s("LEONIDA_ADDRESS_BINDINGS", ""); + CHECK(!enable_device(VK_NULL_HANDLE, VK_NULL_HANDLE, &features, {&ext, 1}, extensions, device)); + CHECK(extensions.empty() && !device.pNext); + _putenv_s("LEONIDA_ADDRESS_BINDINGS", "1"); + const VkInstance first = fake_instance(0x1000), second = fake_instance(0x2000); + // Asked for, but no messenger records the reports: the device is left as it is, and a fault says so. + CHECK(!enable_device(first, VK_NULL_HANDLE, &features, {&ext, 1}, extensions, device)); + CHECK(extensions.empty() && !device.pNext && !state().on); + install_messenger(first, &fake_get); + CHECK(created_messengers == 1 && state().messenger_instance == first); + // A second instance in the same process: refused, so the first messenger is neither overwritten nor leaked. + install_messenger(second, &fake_get); + CHECK(created_messengers == 1 && state().messenger_instance == first); + CHECK(!enable_device(second, VK_NULL_HANDLE, &features, {&ext, 1}, extensions, device)); + CHECK(extensions.empty() && !device.pNext && !state().on); + uninstall_messenger(second); // not its messenger: nothing happens + CHECK(destroyed_messengers == 0 && state().messenger); + // Asked for, the instance has the messenger and the device has the extension: it goes on the chain. + CHECK(enable_device(first, VK_NULL_HANDLE, &features, {&ext, 1}, extensions, device)); + CHECK(extensions.size() == 1 && device.pNext == &state().feature && state().feature.reportAddressBinding); + CHECK(state().on); + // Asked for, and the device does not list it: refused. + std::vector none; + VkDeviceCreateInfo other{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; + CHECK(!enable_device(first, VK_NULL_HANDLE, &features, {}, none, other)); + CHECK(none.empty() && !other.pNext); + // Teardown of the first instance destroys its messenger; the second instance can then have one. + uninstall_messenger(first); + CHECK(destroyed_messengers == 1 && !state().messenger && !state().on); + install_messenger(second, &fake_get); + CHECK(created_messengers == 2 && state().messenger_instance == second); + uninstall_messenger(second); + CHECK(destroyed_messengers == 2); + return 0; +} + +int main() { + if (const int r = test_record()) return r; + if (const int r = test_boundaries()) return r; + if (const int r = test_unbind_matching_and_cap()) return r; + if (const int r = test_threads()) return r; + if (const int r = test_messages()) return r; + if (const int r = test_enable()) return r; + std::printf("address_binding: containing, neighbouring and unbound objects at a fault address\n"); + return 0; +}