From 12b74c2654485398dce7eb5cd73ebeedbda52451 Mon Sep 17 00:00:00 2001 From: jimblackler Date: Sun, 29 Nov 2026 12:13:47 +0000 Subject: [PATCH 1/4] device_memory_report: Stop duplicating Vulkan object names The DebugMarker layer now records object names with process IDs and lifetime tracking, and trace consumers read them directly alongside allocation events. Publishing names here as well adds trace overhead and leaves two naming paths to maintain. Drop the debug naming intercepts, naming extension advertisement, and session-start name replay so DebugMarker acts as the sole producer. Keep the memory report extension advertisement and its device-creation fallback guard intact so drivers without that extension do not fail. Bug: b/564416621 --- .../VkLayer_DeviceMemoryReport.json.in | 10 - .../device_memory_report.cpp | 104 --------- .../device_memory_report.h | 63 +---- ...ice_memory_report_handwritten_dispatch.cpp | 40 +--- ...vice_memory_report_handwritten_functions.h | 158 +------------ layersvt/test/test_devicememoryreport.cpp | 216 +----------------- .../test/test_devicememoryreport_dispatch.cpp | 131 ++--------- layersvt/test/test_devicememoryreport_peer.h | 7 - 8 files changed, 46 insertions(+), 683 deletions(-) diff --git a/layersvt/device_memory_report/VkLayer_DeviceMemoryReport.json.in b/layersvt/device_memory_report/VkLayer_DeviceMemoryReport.json.in index d95e30b04a..9cbbf16db0 100644 --- a/layersvt/device_memory_report/VkLayer_DeviceMemoryReport.json.in +++ b/layersvt/device_memory_report/VkLayer_DeviceMemoryReport.json.in @@ -7,20 +7,10 @@ "api_version": "@JSON_VERSION@", "implementation_version": "1", "description": "Vulkan Device Memory Report Layer", - "instance_extensions": [ - { - "name": "VK_EXT_debug_utils", - "spec_version": "2" - } - ], "device_extensions": [ { "name": "VK_EXT_device_memory_report", "spec_version": "2" - }, - { - "name": "VK_EXT_debug_marker", - "spec_version": "4" } ] } diff --git a/layersvt/device_memory_report/device_memory_report.cpp b/layersvt/device_memory_report/device_memory_report.cpp index 4ba5ed3df5..bfe8f0bcee 100644 --- a/layersvt/device_memory_report/device_memory_report.cpp +++ b/layersvt/device_memory_report/device_memory_report.cpp @@ -279,23 +279,6 @@ void EmitAllocationTraceEvent(const AllocationTraceEvent& event) { "memory_type", event.memory_type); } -/** - * @brief Writes one object name to the trace, for consumers to join onto memory events by handle. - * - * Emits a "VulkanObjectName" instant event under the "VulkanDeviceMemoryReport" category with - * three debug annotations: - * - "object_type" (int32_t): the VkObjectType value of the named object. - * - "object_handle" (uint64_t): the raw Vulkan handle of the object. - * - "object_name" (string): the debug name assigned to the object, or an empty string when a - * previously assigned name has been cleared. - */ -void EmitDebugObjectName(VkObjectType object_type, uint64_t object_handle, std::string_view name) { - TRACE_EVENT_INSTANT("VulkanDeviceMemoryReport", "VulkanObjectName", - "object_type", static_cast(object_type), - "object_handle", object_handle, - "object_name", name); -} - } // namespace void DeviceMemoryReport::RemoveResourceBinding(const ObjectKey& resource_key, Resource& resource, bool update_unbound_counter) { @@ -486,7 +469,6 @@ void DeviceMemoryReport::Reset() { resources_.clear(); memory_allocations_.clear(); usage_memory_bytes_.clear(); - debug_object_names_.clear(); } void DeviceMemoryReport::ReattributeDriverAllocations(uint64_t object_handle, VkObjectType object_type) { @@ -550,73 +532,6 @@ void DeviceMemoryReport::OnDestroyObject(uint64_t object_handle, VkObjectType ob RemoveResourceBinding(res_it->first, res_it->second); resources_.erase(res_it); } - if (debug_object_names_.erase(std::make_pair(object_type, object_handle)) > 0) { - EmitDebugObjectName(object_type, object_handle, ""); - } -} - -void DeviceMemoryReport::SetDebugObjectName(VkObjectType object_type, uint64_t object_handle, const char* name) { - // Other types would be trace volume that nothing reads; VK_LAYER_GOOGLE_DebugMarker names them - // all for consumers that need it. - switch (object_type) { - case VK_OBJECT_TYPE_BUFFER: - case VK_OBJECT_TYPE_IMAGE: - case VK_OBJECT_TYPE_DEVICE_MEMORY: - break; - default: - return; - } - - // A null or empty name clears the name, and the clear still has to be published. A view, not a - // string: the overwhelmingly common call is an application re-applying a name that has not - // changed, some do it every frame, and that path must not allocate. - const std::string_view new_name = name ? std::string_view(name) : std::string_view(); - const auto key = std::make_pair(object_type, object_handle); - - std::lock_guard lock(counter_mutex_); - - auto existing = debug_object_names_.find(key); - if (existing == debug_object_names_.end()) { - // Nothing stored and nothing to store: no state change to publish. - if (new_name.empty()) return; - debug_object_names_.emplace(key, new_name); - } else if (existing->second == new_name) { - // Applications re-apply the same name routinely, so only a change is worth publishing. - return; - } else if (new_name.empty()) { - debug_object_names_.erase(existing); - } else { - // Assigning in place reuses the capacity already allocated for the previous name. - existing->second.assign(new_name); - } - EmitDebugObjectName(object_type, object_handle, new_name); -} - -void DeviceMemoryReport::SetDebugObjectName(VkDebugReportObjectTypeEXT object_type, uint64_t object_handle, const char* name) { - // VK_EXT_debug_marker names objects with the legacy VkDebugReportObjectTypeEXT enum. Only the - // types this layer attributes memory to are mapped. - VkObjectType mapped_type = VK_OBJECT_TYPE_UNKNOWN; - switch (object_type) { - case VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT: - mapped_type = VK_OBJECT_TYPE_BUFFER; - break; - case VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT: - mapped_type = VK_OBJECT_TYPE_IMAGE; - break; - case VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT: - mapped_type = VK_OBJECT_TYPE_DEVICE_MEMORY; - break; - default: - return; - } - SetDebugObjectName(mapped_type, object_handle, name); -} - -void DeviceMemoryReport::EmitAllDebugObjectNames() { - for (const auto& [key, name] : debug_object_names_) { - const auto& [object_type, object_handle] = key; - EmitDebugObjectName(object_type, object_handle, name); - } } void DeviceMemoryReport::DumpCurrentCountersAndAllocations() { @@ -663,11 +578,6 @@ void DeviceMemoryReport::DumpCurrentCountersAndAllocations() { }); } } - - // Names are replayed after the allocations for the same reason they are replayed at all: a - // session that attaches mid-run never saw the naming calls, and a name with no allocation to - // attach to is meaningless. - EmitAllDebugObjectNames(); } void DeviceMemoryReport::OnMemoryReportEvent(const VkDeviceMemoryReportCallbackDataEXT* pCallbackData) { @@ -711,10 +621,6 @@ void DeviceMemoryReport::OnMemoryReportEvent(const VkDeviceMemoryReportCallbackD .object_handle = stale_object_handle, .memory_type = stale_memory_type, }); - if (!is_driver && - debug_object_names_.erase(std::make_pair(VK_OBJECT_TYPE_DEVICE_MEMORY, key.id)) > 0) { - EmitDebugObjectName(VK_OBJECT_TYPE_DEVICE_MEMORY, key.id, ""); - } } auto& allocation = memory_allocations_[key]; allocation.total_size = pCallbackData->size; @@ -760,13 +666,6 @@ void DeviceMemoryReport::OnMemoryReportEvent(const VkDeviceMemoryReportCallbackD ClampSubAllocationsToAllocation(key); UpdateAllocationUnboundCounter(key); } - - const bool is_free = pCallbackData->type == VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT || - pCallbackData->type == VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_UNIMPORT_EXT; - if (is_free && !is_driver && - debug_object_names_.erase(std::make_pair(VK_OBJECT_TYPE_DEVICE_MEMORY, key.id)) > 0) { - EmitDebugObjectName(VK_OBJECT_TYPE_DEVICE_MEMORY, key.id, ""); - } } void DeviceMemoryReport::SetHasMemoryReportCallback(VkDevice device, bool has_callback) { @@ -839,7 +738,4 @@ void DeviceMemoryReport::OnFreeMemory(VkDevice device, VkDeviceMemory memory) { .memory_type = "unbound_memory", }); } - if (debug_object_names_.erase(std::make_pair(VK_OBJECT_TYPE_DEVICE_MEMORY, handle)) > 0) { - EmitDebugObjectName(VK_OBJECT_TYPE_DEVICE_MEMORY, handle, ""); - } } diff --git a/layersvt/device_memory_report/device_memory_report.h b/layersvt/device_memory_report/device_memory_report.h index 442f343abd..26dd7058e7 100644 --- a/layersvt/device_memory_report/device_memory_report.h +++ b/layersvt/device_memory_report/device_memory_report.h @@ -52,17 +52,14 @@ const char* GetImageCluster(VkImageUsageFlags usage, VkMemoryPropertyFlags memFl * VK_EXT_device_memory_report callbacks (when supported by the underlying driver) or falling back * to direct allocation intercepts (vkAllocateMemory/vkFreeMemory). * Object bindings (vkBindBufferMemory, vkBindImageMemory, vkBindBufferMemory2, vkBindImageMemory2) - * are tracked to attribute memory allocations to usage categories. The layer also advertises and - * intercepts VK_EXT_debug_utils and VK_EXT_debug_marker (stripping VK_EXT_debug_marker at device - * creation when unsupported downstream) so debug object names for buffers, images, and device - * memory are published standalone without requiring VK_LAYER_GOOGLE_DebugMarker. + * are tracked to attribute memory allocations to usage categories. Debug object names are not + * handled by this layer; VK_LAYER_GOOGLE_DebugMarker publishes them. * * Track Categories: * Memory usage counters are reported to Perfetto under: * - Driver vs Application allocations (e.g., vulkan.mem.driver.* vs vulkan.mem.app.*) * - Usages (vulkan.mem.*.usage.) - * - Instant events under the "VulkanDeviceMemoryReport" category ("VulkanMemoryAllocation" and - * "VulkanObjectName") + * - Instant events under the "VulkanDeviceMemoryReport" category ("VulkanMemoryAllocation") * * This class is a singleton and provides thread-safe access to its state. */ @@ -212,44 +209,16 @@ class DeviceMemoryReport { void DumpCurrentCountersAndAllocations(); /** - * @brief Handles destruction of a Vulkan object, cleaning up tracked usage state and any - * recorded debug name. + * @brief Handles destruction of a Vulkan object, cleaning up tracked usage state. * - * Handles are only unique within an object type, so @p object_type is required to clear the - * destroyed object's name without dropping the name of an unrelated live object that shares - * the handle value. + * Handles are only unique within an object type, so @p object_type is required to find the + * destroyed object without disturbing an unrelated live object that shares the handle value. * * @param object_handle The 64-bit handle of the destroyed Vulkan object. * @param object_type The type of the destroyed object, as a VkObjectType. */ void OnDestroyObject(uint64_t object_handle, VkObjectType object_type); - /** - * @brief Records the debug name an application gave to a Vulkan object and publishes it. - * - * Names arrive through VK_EXT_debug_utils or VK_EXT_debug_marker, typically well after the - * object was created, so they are published as their own event stream rather than attached to - * the memory events. Only the object types this layer attributes memory to are kept. - * - * @param object_type The type of the object, as a VkObjectType. - * @param object_handle The 64-bit handle of the object. - * @param name The name given by the application. A null or empty name clears the stored name. - */ - void SetDebugObjectName(VkObjectType object_type, uint64_t object_handle, const char* name); - - /** - * @brief Records the debug name an application gave to a Vulkan object via the legacy - * VK_EXT_debug_marker extension and publishes it. - * - * Maps the legacy VkDebugReportObjectTypeEXT enum to VkObjectType for the object types this - * layer attributes memory to, and ignores all other types. - * - * @param object_type The type of the object, as a VkDebugReportObjectTypeEXT. - * @param object_handle The 64-bit handle of the object. - * @param name The name given by the application. A null or empty name clears the stored name. - */ - void SetDebugObjectName(VkDebugReportObjectTypeEXT object_type, uint64_t object_handle, const char* name); - private: friend class DeviceMemoryReportTestPeer; @@ -269,7 +238,7 @@ class DeviceMemoryReport { * * Non-dispatchable Vulkan handles (VkBuffer, VkImage, VkDeviceMemory) are only unique within * their own object type, so the type is part of the key to prevent colliding handles of - * different types from overwriting each other's metadata, bindings or names. + * different types from overwriting each other's metadata or bindings. */ using ObjectKey = std::pair; @@ -377,11 +346,6 @@ class DeviceMemoryReport { */ void ReattributeDriverAllocations(uint64_t object_handle, VkObjectType object_type); - /** - * @brief Republishes every known object name. Called while counter_mutex_ is held. - */ - void EmitAllDebugObjectNames(); - /** * @brief Increments trace counter for a memory track. */ @@ -432,17 +396,4 @@ class DeviceMemoryReport { * @brief Maps a usage track name to its current total memory usage in bytes. */ std::unordered_map usage_memory_bytes_; - - /** - * @brief Maps a pair of (object_type, object_handle) to the name the application gave the object. - * - * Handles are only unique within an object type, hence the pair key. Like resources_ and - * memory_allocations_, keys are not scoped by VkDevice, and entries persist across - * OnDestroyDevice until the object itself is destroyed or Reset() is called. Objects not - * destroyed through vkDestroyImage, vkDestroyBuffer, or vkFreeMemory (such as presentable - * VkImages owned by a VkSwapchainKHR) retain their entries until Reset() or until a recycled - * handle is renamed. Guarded by counter_mutex_. std::map is used instead of unordered_map for - * pair key support and deterministic replay order. - */ - std::map debug_object_names_; }; diff --git a/layersvt/device_memory_report/device_memory_report_handwritten_dispatch.cpp b/layersvt/device_memory_report/device_memory_report_handwritten_dispatch.cpp index 03882f822e..03a1ee38be 100644 --- a/layersvt/device_memory_report/device_memory_report_handwritten_dispatch.cpp +++ b/layersvt/device_memory_report/device_memory_report_handwritten_dispatch.cpp @@ -32,9 +32,6 @@ static PFN_vkVoidFunction devmemreport_known_instance_functions(const char* pNam if (strcmp(pName, "vkEnumeratePhysicalDevices") == 0) return reinterpret_cast(vkEnumeratePhysicalDevices); if (strcmp(pName, "vkEnumeratePhysicalDeviceGroups") == 0) return reinterpret_cast(vkEnumeratePhysicalDeviceGroups); if (strcmp(pName, "vkEnumerateDeviceExtensionProperties") == 0) return reinterpret_cast(vkEnumerateDeviceExtensionProperties); - if (strcmp(pName, "vkCreateDebugUtilsMessengerEXT") == 0) return reinterpret_cast(vkCreateDebugUtilsMessengerEXT); - if (strcmp(pName, "vkDestroyDebugUtilsMessengerEXT") == 0) return reinterpret_cast(vkDestroyDebugUtilsMessengerEXT); - if (strcmp(pName, "vkSubmitDebugUtilsMessageEXT") == 0) return reinterpret_cast(vkSubmitDebugUtilsMessageEXT); return nullptr; } @@ -60,29 +57,6 @@ static PFN_vkVoidFunction devmemreport_known_core_device_functions(const char* p return nullptr; } -// Device functions for extensions provided directly by this layer (VK_EXT_debug_utils and -// VK_EXT_debug_marker). These are returned unconditionally so the layer functions standalone -// even when neither the underlying driver nor VK_LAYER_GOOGLE_DebugMarker implements them. -static PFN_vkVoidFunction devmemreport_known_layer_device_extension_functions(const char* pName) { - // VK_EXT_debug_utils - if (strcmp(pName, "vkSetDebugUtilsObjectNameEXT") == 0) return reinterpret_cast(vkSetDebugUtilsObjectNameEXT); - if (strcmp(pName, "vkSetDebugUtilsObjectTagEXT") == 0) return reinterpret_cast(vkSetDebugUtilsObjectTagEXT); - if (strcmp(pName, "vkCmdBeginDebugUtilsLabelEXT") == 0) return reinterpret_cast(vkCmdBeginDebugUtilsLabelEXT); - if (strcmp(pName, "vkCmdEndDebugUtilsLabelEXT") == 0) return reinterpret_cast(vkCmdEndDebugUtilsLabelEXT); - if (strcmp(pName, "vkCmdInsertDebugUtilsLabelEXT") == 0) return reinterpret_cast(vkCmdInsertDebugUtilsLabelEXT); - if (strcmp(pName, "vkQueueBeginDebugUtilsLabelEXT") == 0) return reinterpret_cast(vkQueueBeginDebugUtilsLabelEXT); - if (strcmp(pName, "vkQueueEndDebugUtilsLabelEXT") == 0) return reinterpret_cast(vkQueueEndDebugUtilsLabelEXT); - if (strcmp(pName, "vkQueueInsertDebugUtilsLabelEXT") == 0) return reinterpret_cast(vkQueueInsertDebugUtilsLabelEXT); - - // VK_EXT_debug_marker - if (strcmp(pName, "vkDebugMarkerSetObjectNameEXT") == 0) return reinterpret_cast(vkDebugMarkerSetObjectNameEXT); - if (strcmp(pName, "vkDebugMarkerSetObjectTagEXT") == 0) return reinterpret_cast(vkDebugMarkerSetObjectTagEXT); - if (strcmp(pName, "vkCmdDebugMarkerBeginEXT") == 0) return reinterpret_cast(vkCmdDebugMarkerBeginEXT); - if (strcmp(pName, "vkCmdDebugMarkerEndEXT") == 0) return reinterpret_cast(vkCmdDebugMarkerEndEXT); - if (strcmp(pName, "vkCmdDebugMarkerInsertEXT") == 0) return reinterpret_cast(vkCmdDebugMarkerInsertEXT); - return nullptr; -} - static PFN_vkVoidFunction devmemreport_known_device_extension_functions(const char* pName) { if (strcmp(pName, "vkBindBufferMemory2KHR") == 0) return reinterpret_cast(vkBindBufferMemory2KHR); if (strcmp(pName, "vkBindImageMemory2KHR") == 0) return reinterpret_cast(vkBindImageMemory2KHR); @@ -120,22 +94,18 @@ EXPORT_FUNCTION VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetInstanceProcAddr(V return func; } - // Core device functions and layer-provided debug extension functions can be returned directly from GIPA. + // Core device functions can be returned directly from GIPA. func = devmemreport_known_core_device_functions(pName); if (func) { return func; } - func = devmemreport_known_layer_device_extension_functions(pName); - if (func) { - return func; - } auto table = instance_dispatch_table(instance); if (table == NULL || table->GetInstanceProcAddr == NULL) { return nullptr; } - // For driver-dependent extension device commands, verify the underlying chain supports them before returning an interceptor. + // For extension device commands, verify the underlying chain supports them before returning an interceptor. PFN_vkVoidFunction down_func = table->GetInstanceProcAddr(instance, pName); if (down_func == nullptr) { return nullptr; @@ -154,12 +124,6 @@ EXPORT_FUNCTION VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL vkGetDeviceProcAddr(VkD return nullptr; } - // Extensions provided by this layer itself are always available regardless of underlying driver support. - PFN_vkVoidFunction layer_ext_func = devmemreport_known_layer_device_extension_functions(pName); - if (layer_ext_func) { - return layer_ext_func; - } - if (device_dispatch_table(device)->GetDeviceProcAddr == NULL) { return nullptr; } diff --git a/layersvt/device_memory_report/device_memory_report_handwritten_functions.h b/layersvt/device_memory_report/device_memory_report_handwritten_functions.h index f8d1b65969..f87c74c846 100644 --- a/layersvt/device_memory_report/device_memory_report_handwritten_functions.h +++ b/layersvt/device_memory_report/device_memory_report_handwritten_functions.h @@ -32,22 +32,20 @@ // - vkCreateInstance: Initializes Perfetto tracing and the instance dispatch table. // - vkEnumeratePhysicalDevices / vkEnumeratePhysicalDeviceGroups: Tracks the mapping // between physical devices and instances to support dispatch table lookups. -// - vkCreateDevice / vkDestroyDevice: Initializes/destroys device dispatch tables, strips -// layer-advertised device extensions (VK_EXT_device_memory_report, VK_EXT_debug_marker) when -// unsupported by the underlying driver, and injects VK_EXT_device_memory_report callback -// registration into device creation. +// - vkCreateDevice / vkDestroyDevice: Initializes/destroys device dispatch tables, strips the +// layer-advertised VK_EXT_device_memory_report extension when unsupported by the underlying +// driver, and injects VK_EXT_device_memory_report callback registration into device creation. // -// Memory tracking, resource tracking & debug naming intercepts: +// Memory tracking & resource tracking intercepts: // - vkAllocateMemory / vkFreeMemory: Tracks direct allocations/frees as fallbacks. // - vkBindBufferMemory* / vkBindImageMemory*: Associates buffer/image handles with memory allocations. // - vkCreateBuffer / vkDestroyBuffer: Tracks buffer creation, usage flags, and requested sizes. // - vkCreateImage / vkDestroyImage: Tracks image creation and usage flags. // - vkGetBufferMemoryRequirements* / vkGetImageMemoryRequirements*: Tracks resource memory requirements. -// - vkSetDebugUtilsObjectNameEXT / vkDebugMarkerSetObjectNameEXT (and companion passthroughs): -// Records debug object names for buffers, images, and device memory so the layer can operate -// standalone without VK_LAYER_GOOGLE_DebugMarker. // - vkEnumerate*ExtensionProperties / vkEnumerate*LayerProperties: Advertises the layer and -// support for VK_EXT_device_memory_report, VK_EXT_debug_utils, and VK_EXT_debug_marker. +// support for VK_EXT_device_memory_report. +// +// Debug object names are not handled here: VK_LAYER_GOOGLE_DebugMarker publishes them. #define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0])) @@ -159,9 +157,8 @@ VKAPI_ATTR VkResult VKAPI_CALL vkCreateDevice(VkPhysicalDevice physicalDevice, c // Call the function and create the dispatch table chain_info->u.pLayerInfo = chain_info->u.pLayerInfo->pNext; - // Check if the underlying driver supports VK_EXT_device_memory_report or VK_EXT_debug_marker. + // Check if the underlying driver supports VK_EXT_device_memory_report. bool supports_memory_report = false; - bool supports_debug_marker = false; if (instance_dispatch_table(physicalDevice)->EnumerateDeviceExtensionProperties) { uint32_t extension_count = 0; VkResult enumerate_result = instance_dispatch_table(physicalDevice)->EnumerateDeviceExtensionProperties( @@ -177,10 +174,6 @@ VKAPI_ATTR VkResult VKAPI_CALL vkCreateDevice(VkPhysicalDevice physicalDevice, c for (const auto& extension : extensions) { if (strcmp(extension.extensionName, VK_EXT_DEVICE_MEMORY_REPORT_EXTENSION_NAME) == 0) { supports_memory_report = true; - } else if (strcmp(extension.extensionName, VK_EXT_DEBUG_MARKER_EXTENSION_NAME) == 0) { - supports_debug_marker = true; - } - if (supports_memory_report && supports_debug_marker) { break; } } @@ -188,15 +181,12 @@ VKAPI_ATTR VkResult VKAPI_CALL vkCreateDevice(VkPhysicalDevice physicalDevice, c } } - // Strip layer-advertised device extensions if the underlying driver does not natively support - // them, and inject VK_EXT_device_memory_report callback registration when supported. + // Strip the layer-advertised VK_EXT_device_memory_report if the underlying driver does not + // natively support it, and inject its callback registration when supported. VkDeviceCreateInfo modified_create_info = *pCreateInfo; std::vector enabled_extensions; for (uint32_t i = 0; i < pCreateInfo->enabledExtensionCount; ++i) { const char* name = pCreateInfo->ppEnabledExtensionNames[i]; - if (!supports_debug_marker && strcmp(name, VK_EXT_DEBUG_MARKER_EXTENSION_NAME) == 0) { - continue; - } if (!supports_memory_report && strcmp(name, VK_EXT_DEVICE_MEMORY_REPORT_EXTENSION_NAME) == 0) { continue; } @@ -312,11 +302,8 @@ EXPORT_FUNCTION VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateInstanceExtensionPrope assert(pPropertyCount != nullptr); - static const VkExtensionProperties instanceExtensions[] = { - {VK_EXT_DEBUG_UTILS_EXTENSION_NAME, VK_EXT_DEBUG_UTILS_SPEC_VERSION}, - }; - - return util_GetExtensionProperties(ARRAY_SIZE(instanceExtensions), instanceExtensions, pPropertyCount, pProperties); + // The layer provides no instance extensions. + return util_GetExtensionProperties(0, nullptr, pPropertyCount, pProperties); } EXPORT_FUNCTION VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateInstanceLayerProperties(uint32_t* pPropertyCount, @@ -352,7 +339,6 @@ EXPORT_FUNCTION VKAPI_ATTR VkResult VKAPI_CALL vkEnumerateDeviceExtensionPropert static const VkExtensionProperties layer_device_extensions[] = { {VK_EXT_DEVICE_MEMORY_REPORT_EXTENSION_NAME, VK_EXT_DEVICE_MEMORY_REPORT_SPEC_VERSION}, - {VK_EXT_DEBUG_MARKER_EXTENSION_NAME, VK_EXT_DEBUG_MARKER_SPEC_VERSION}, }; if (pLayerName != nullptr && strcmp(pLayerName, LAYER_NAME) == 0) { @@ -634,124 +620,4 @@ VKAPI_ATTR void VKAPI_CALL vkGetBufferMemoryRequirements2KHR(VkDevice device, co } } -// Object naming from VK_EXT_debug_utils. -VKAPI_ATTR VkResult VKAPI_CALL vkSetDebugUtilsObjectNameEXT(VkDevice device, const VkDebugUtilsObjectNameInfoEXT* pNameInfo) { - assert(pNameInfo != nullptr); - auto* table = device_dispatch_table(device); - // Naming is informational, so a driver that does not implement it is not an error. - VkResult result = (table->SetDebugUtilsObjectNameEXT != nullptr) - ? table->SetDebugUtilsObjectNameEXT(device, pNameInfo) - : VK_SUCCESS; - if (result == VK_SUCCESS) { - DeviceMemoryReport::Get().SetDebugObjectName(pNameInfo->objectType, pNameInfo->objectHandle, - pNameInfo->pObjectName); - } - return result; -} - -// Object naming from VK_EXT_debug_marker, the predecessor of VK_EXT_debug_utils. -VKAPI_ATTR VkResult VKAPI_CALL vkDebugMarkerSetObjectNameEXT(VkDevice device, const VkDebugMarkerObjectNameInfoEXT* pNameInfo) { - assert(pNameInfo != nullptr); - auto* table = device_dispatch_table(device); - VkResult result = (table->DebugMarkerSetObjectNameEXT != nullptr) - ? table->DebugMarkerSetObjectNameEXT(device, pNameInfo) - : VK_SUCCESS; - if (result == VK_SUCCESS) { - DeviceMemoryReport::Get().SetDebugObjectName(pNameInfo->objectType, pNameInfo->object, - pNameInfo->pObjectName); - } - return result; -} - -// Companion passthroughs for VK_EXT_debug_utils and VK_EXT_debug_marker so the layer can -// advertise and support both extensions standalone without VK_LAYER_GOOGLE_DebugMarker. -VKAPI_ATTR VkResult VKAPI_CALL vkSetDebugUtilsObjectTagEXT(VkDevice device, const VkDebugUtilsObjectTagInfoEXT* pTagInfo) { - auto* table = device_dispatch_table(device); - return (table->SetDebugUtilsObjectTagEXT != nullptr) ? table->SetDebugUtilsObjectTagEXT(device, pTagInfo) : VK_SUCCESS; -} - -VKAPI_ATTR void VKAPI_CALL vkCmdBeginDebugUtilsLabelEXT(VkCommandBuffer commandBuffer, const VkDebugUtilsLabelEXT* pLabelInfo) { - if (device_dispatch_table(commandBuffer)->CmdBeginDebugUtilsLabelEXT) { - device_dispatch_table(commandBuffer)->CmdBeginDebugUtilsLabelEXT(commandBuffer, pLabelInfo); - } -} - -VKAPI_ATTR void VKAPI_CALL vkCmdEndDebugUtilsLabelEXT(VkCommandBuffer commandBuffer) { - if (device_dispatch_table(commandBuffer)->CmdEndDebugUtilsLabelEXT) { - device_dispatch_table(commandBuffer)->CmdEndDebugUtilsLabelEXT(commandBuffer); - } -} - -VKAPI_ATTR void VKAPI_CALL vkCmdInsertDebugUtilsLabelEXT(VkCommandBuffer commandBuffer, const VkDebugUtilsLabelEXT* pLabelInfo) { - if (device_dispatch_table(commandBuffer)->CmdInsertDebugUtilsLabelEXT) { - device_dispatch_table(commandBuffer)->CmdInsertDebugUtilsLabelEXT(commandBuffer, pLabelInfo); - } -} - -VKAPI_ATTR void VKAPI_CALL vkQueueBeginDebugUtilsLabelEXT(VkQueue queue, const VkDebugUtilsLabelEXT* pLabelInfo) { - if (device_dispatch_table(queue)->QueueBeginDebugUtilsLabelEXT) { - device_dispatch_table(queue)->QueueBeginDebugUtilsLabelEXT(queue, pLabelInfo); - } -} - -VKAPI_ATTR void VKAPI_CALL vkQueueEndDebugUtilsLabelEXT(VkQueue queue) { - if (device_dispatch_table(queue)->QueueEndDebugUtilsLabelEXT) { - device_dispatch_table(queue)->QueueEndDebugUtilsLabelEXT(queue); - } -} - -VKAPI_ATTR void VKAPI_CALL vkQueueInsertDebugUtilsLabelEXT(VkQueue queue, const VkDebugUtilsLabelEXT* pLabelInfo) { - if (device_dispatch_table(queue)->QueueInsertDebugUtilsLabelEXT) { - device_dispatch_table(queue)->QueueInsertDebugUtilsLabelEXT(queue, pLabelInfo); - } -} - -VKAPI_ATTR VkResult VKAPI_CALL vkCreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, - const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pMessenger) { - assert(pMessenger != nullptr); - if (instance_dispatch_table(instance)->CreateDebugUtilsMessengerEXT != nullptr) { - return instance_dispatch_table(instance)->CreateDebugUtilsMessengerEXT(instance, pCreateInfo, pAllocator, pMessenger); - } - *pMessenger = VK_NULL_HANDLE; - return VK_SUCCESS; -} - -VKAPI_ATTR void VKAPI_CALL vkDestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT messenger, - const VkAllocationCallbacks* pAllocator) { - if (instance_dispatch_table(instance)->DestroyDebugUtilsMessengerEXT) { - instance_dispatch_table(instance)->DestroyDebugUtilsMessengerEXT(instance, messenger, pAllocator); - } -} - -VKAPI_ATTR void VKAPI_CALL vkSubmitDebugUtilsMessageEXT(VkInstance instance, VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity, - VkDebugUtilsMessageTypeFlagsEXT messageTypes, - const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData) { - if (instance_dispatch_table(instance)->SubmitDebugUtilsMessageEXT) { - instance_dispatch_table(instance)->SubmitDebugUtilsMessageEXT(instance, messageSeverity, messageTypes, pCallbackData); - } -} - -VKAPI_ATTR VkResult VKAPI_CALL vkDebugMarkerSetObjectTagEXT(VkDevice device, const VkDebugMarkerObjectTagInfoEXT* pTagInfo) { - auto* table = device_dispatch_table(device); - return (table->DebugMarkerSetObjectTagEXT != nullptr) ? table->DebugMarkerSetObjectTagEXT(device, pTagInfo) : VK_SUCCESS; -} - -VKAPI_ATTR void VKAPI_CALL vkCmdDebugMarkerBeginEXT(VkCommandBuffer commandBuffer, const VkDebugMarkerMarkerInfoEXT* pMarkerInfo) { - if (device_dispatch_table(commandBuffer)->CmdDebugMarkerBeginEXT) { - device_dispatch_table(commandBuffer)->CmdDebugMarkerBeginEXT(commandBuffer, pMarkerInfo); - } -} - -VKAPI_ATTR void VKAPI_CALL vkCmdDebugMarkerEndEXT(VkCommandBuffer commandBuffer) { - if (device_dispatch_table(commandBuffer)->CmdDebugMarkerEndEXT) { - device_dispatch_table(commandBuffer)->CmdDebugMarkerEndEXT(commandBuffer); - } -} - -VKAPI_ATTR void VKAPI_CALL vkCmdDebugMarkerInsertEXT(VkCommandBuffer commandBuffer, const VkDebugMarkerMarkerInfoEXT* pMarkerInfo) { - if (device_dispatch_table(commandBuffer)->CmdDebugMarkerInsertEXT) { - device_dispatch_table(commandBuffer)->CmdDebugMarkerInsertEXT(commandBuffer, pMarkerInfo); - } -} - } // extern "C" diff --git a/layersvt/test/test_devicememoryreport.cpp b/layersvt/test/test_devicememoryreport.cpp index 8429391422..87f90ef956 100644 --- a/layersvt/test/test_devicememoryreport.cpp +++ b/layersvt/test/test_devicememoryreport.cpp @@ -84,19 +84,11 @@ TEST_F(DeviceMemoryReportTests, ExtensionProperties) { VkInstance instance = inst_builder.GetInstance(); EXPECT_NE(instance, VK_NULL_HANDLE); - // Test instance extension properties advertised by the layer + // The layer provides no instance extensions. Debug object names come from + // VK_LAYER_GOOGLE_DebugMarker, so VK_EXT_debug_utils is not advertised here. uint32_t inst_ext_count = 0; EXPECT_EQ(vkEnumerateInstanceExtensionProperties(kLayerName, &inst_ext_count, nullptr), VK_SUCCESS); - EXPECT_EQ(inst_ext_count, 1u); - std::vector inst_exts(inst_ext_count); - EXPECT_EQ(vkEnumerateInstanceExtensionProperties(kLayerName, &inst_ext_count, inst_exts.data()), VK_SUCCESS); - bool found_debug_utils = false; - for (const auto& ext : inst_exts) { - if (strcmp(ext.extensionName, VK_EXT_DEBUG_UTILS_EXTENSION_NAME) == 0) { - found_debug_utils = true; - } - } - EXPECT_TRUE(found_debug_utils); + EXPECT_EQ(inst_ext_count, 0u); VkPhysicalDevice phys_dev = VK_NULL_HANDLE; inst_builder.GetPhysicalDevice(&phys_dev); @@ -104,7 +96,7 @@ TEST_F(DeviceMemoryReportTests, ExtensionProperties) { // Test device extension properties advertised by the layer uint32_t dev_ext_count = 0; EXPECT_EQ(vkEnumerateDeviceExtensionProperties(phys_dev, kLayerName, &dev_ext_count, nullptr), VK_SUCCESS); - EXPECT_GE(dev_ext_count, 2u); + EXPECT_EQ(dev_ext_count, 1u); std::vector dev_exts(dev_ext_count); EXPECT_EQ(vkEnumerateDeviceExtensionProperties(phys_dev, kLayerName, &dev_ext_count, dev_exts.data()), VK_SUCCESS); bool found_mem_report = false; @@ -117,7 +109,7 @@ TEST_F(DeviceMemoryReportTests, ExtensionProperties) { } } EXPECT_TRUE(found_mem_report); - EXPECT_TRUE(found_debug_marker); + EXPECT_FALSE(found_debug_marker); } inst_builder.Reset(); @@ -927,201 +919,3 @@ TEST_F(DeviceMemoryReportTests, MemoryReportSnapshotDump) { EXPECT_FALSE(DeviceMemoryReportTestPeer::FindResource(VK_OBJECT_TYPE_BUFFER, buffer_handle).has_value()); EXPECT_FALSE(DeviceMemoryReportTestPeer::FindResource(VK_OBJECT_TYPE_IMAGE, image_handle).has_value()); } - - -TEST_F(DeviceMemoryReportTests, DebugObjectNames) { - TEST_DESCRIPTION("Test that object names are recorded for the object types the layer attributes memory to"); - - InitializeDeviceMemoryReportPerfetto(); - - const uint64_t buffer_handle = 0xE001; - const uint64_t image_handle = 0xE002; - const uint64_t memory_handle = 0xE003; - - DeviceMemoryReport::Get().SetDebugObjectName(VK_OBJECT_TYPE_BUFFER, buffer_handle, "vertex_buffer"); - DeviceMemoryReport::Get().SetDebugObjectName(VK_OBJECT_TYPE_IMAGE, image_handle, "albedo_texture"); - DeviceMemoryReport::Get().SetDebugObjectName(VK_OBJECT_TYPE_DEVICE_MEMORY, memory_handle, "scene_heap"); - - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_BUFFER, buffer_handle), "vertex_buffer"); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_IMAGE, image_handle), "albedo_texture"); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_DEVICE_MEMORY, memory_handle), "scene_heap"); - - // Handles are only unique within an object type, so the same handle can carry a different name - // for a different type. - DeviceMemoryReport::Get().SetDebugObjectName(VK_OBJECT_TYPE_IMAGE, buffer_handle, "shadow_map"); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_BUFFER, buffer_handle), "vertex_buffer"); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_IMAGE, buffer_handle), "shadow_map"); - - // Renaming replaces the stored name. - DeviceMemoryReport::Get().SetDebugObjectName(VK_OBJECT_TYPE_BUFFER, buffer_handle, "index_buffer"); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_BUFFER, buffer_handle), "index_buffer"); - - // Re-applying the same name preserves state and suppresses a duplicate trace emission (the - // TRACE_EVENT_INSTANT output is consumed by Perfetto and cannot be counted directly here). - DeviceMemoryReport::Get().SetDebugObjectName(VK_OBJECT_TYPE_BUFFER, buffer_handle, "index_buffer"); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_BUFFER, buffer_handle), "index_buffer"); - - // A null name clears the name rather than recording a placeholder, and clearing an already - // unnamed object is a no-op. - DeviceMemoryReport::Get().SetDebugObjectName(VK_OBJECT_TYPE_BUFFER, buffer_handle, nullptr); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_BUFFER, buffer_handle), ""); - DeviceMemoryReport::Get().SetDebugObjectName(VK_OBJECT_TYPE_BUFFER, buffer_handle, ""); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_BUFFER, buffer_handle), ""); - - // Object types the memory view cannot attribute memory to are not tracked at all. - DeviceMemoryReport::Get().SetDebugObjectName(VK_OBJECT_TYPE_PIPELINE, 0xE004, "lighting_pipeline"); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_PIPELINE, 0xE004), ""); - - // Unnamed objects report no name. - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_BUFFER, 0xE005), ""); -} - -TEST_F(DeviceMemoryReportTests, DebugObjectNamesSurviveSnapshotDump) { - TEST_DESCRIPTION("Test that a snapshot dump replays object names for sessions that attach late"); - - InitializeDeviceMemoryReportPerfetto(); - - const uint64_t buffer_handle = 0xE101; - DeviceMemoryReport::Get().SetDebugObjectName(VK_OBJECT_TYPE_BUFFER, buffer_handle, "persistent_buffer"); - - DeviceMemoryReport::Get().DumpCurrentCountersAndAllocations(); - - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_BUFFER, buffer_handle), "persistent_buffer"); -} - -TEST_F(DeviceMemoryReportTests, DebugObjectNamesDestroyedOnObjectDestroy) { - TEST_DESCRIPTION("Test that debug names are cleared when objects are destroyed or freed"); - - InitializeDeviceMemoryReportPerfetto(); - - const uint64_t buffer_handle = 0xE201; - const uint64_t image_handle = 0xE202; - const uint64_t memory_handle = 0xE203; - - DeviceMemoryReport::Get().SetDebugObjectName(VK_OBJECT_TYPE_BUFFER, buffer_handle, "temp_buffer"); - DeviceMemoryReport::Get().SetDebugObjectName(VK_OBJECT_TYPE_IMAGE, image_handle, "temp_image"); - DeviceMemoryReport::Get().SetDebugObjectName(VK_OBJECT_TYPE_DEVICE_MEMORY, memory_handle, "temp_memory"); - - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_BUFFER, buffer_handle), "temp_buffer"); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_IMAGE, image_handle), "temp_image"); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_DEVICE_MEMORY, memory_handle), "temp_memory"); - - DeviceMemoryReport::Get().OnDestroyObject(buffer_handle, VK_OBJECT_TYPE_BUFFER); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_BUFFER, buffer_handle), ""); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_IMAGE, image_handle), "temp_image"); - - DeviceMemoryReport::Get().OnDestroyObject(image_handle, VK_OBJECT_TYPE_IMAGE); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_IMAGE, image_handle), ""); - - VkDevice dummy_device = reinterpret_cast(0xD001); - VkDeviceMemory dummy_memory = reinterpret_cast(memory_handle); - DeviceMemoryReport::Get().OnAllocateMemory(dummy_device, dummy_memory, 1024, 0, 0); - DeviceMemoryReport::Get().OnFreeMemory(dummy_device, dummy_memory); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_DEVICE_MEMORY, memory_handle), ""); - - // On callback-capable devices, OnFreeMemory must keep the debug name intact until the - // VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT callback emits DESTROY. - VkDevice callback_device = reinterpret_cast(0xD002); - DeviceMemoryReport::Get().SetHasMemoryReportCallback(callback_device, true); - const uint64_t callback_mem_handle = 0xE204; - DeviceMemoryReport::Get().SetDebugObjectName(VK_OBJECT_TYPE_DEVICE_MEMORY, callback_mem_handle, "callback_memory"); - DeviceMemoryReport::Get().OnFreeMemory(callback_device, reinterpret_cast(callback_mem_handle)); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_DEVICE_MEMORY, callback_mem_handle), "callback_memory"); - - VkDeviceMemoryReportCallbackDataEXT free_cb = {}; - free_cb.sType = VK_STRUCTURE_TYPE_DEVICE_MEMORY_REPORT_CALLBACK_DATA_EXT; - free_cb.flags = 0; - free_cb.type = VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT; - free_cb.memoryObjectId = 0x9001; - free_cb.size = 1024; - free_cb.objectType = VK_OBJECT_TYPE_DEVICE_MEMORY; - free_cb.objectHandle = callback_mem_handle; - DeviceMemoryReport::MemoryReportCallback(&free_cb, nullptr); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_DEVICE_MEMORY, callback_mem_handle), ""); - - // Retiring a stale active VkDeviceMemory allocation via a duplicate ALLOCATE_EXT (without an - // intervening FREE_EXT) also clears its debug name so the replacement does not inherit it. - const uint64_t recycled_mem_handle = 0xE205; - VkDeviceMemoryReportCallbackDataEXT alloc_cb = {}; - alloc_cb.sType = VK_STRUCTURE_TYPE_DEVICE_MEMORY_REPORT_CALLBACK_DATA_EXT; - alloc_cb.type = VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_ALLOCATE_EXT; - alloc_cb.memoryObjectId = 0x9002; - alloc_cb.size = 2048; - alloc_cb.objectType = VK_OBJECT_TYPE_DEVICE_MEMORY; - alloc_cb.objectHandle = recycled_mem_handle; - DeviceMemoryReport::MemoryReportCallback(&alloc_cb, nullptr); - DeviceMemoryReport::Get().SetDebugObjectName(VK_OBJECT_TYPE_DEVICE_MEMORY, recycled_mem_handle, "old_heap_name"); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_DEVICE_MEMORY, recycled_mem_handle), "old_heap_name"); - - alloc_cb.memoryObjectId = 0x9003; - alloc_cb.size = 4096; - DeviceMemoryReport::MemoryReportCallback(&alloc_cb, nullptr); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_DEVICE_MEMORY, recycled_mem_handle), ""); - - alloc_cb.type = VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT; - DeviceMemoryReport::MemoryReportCallback(&alloc_cb, nullptr); -} - -TEST_F(DeviceMemoryReportTests, DebugObjectNameClearOnlyAffectsItsOwnType) { - TEST_DESCRIPTION("Test that clearing the name of a destroyed object spares a same-numbered object of another type"); - - InitializeDeviceMemoryReportPerfetto(); - - // Handles are only unique within an object type, so a buffer, an image, a device memory - // allocation, and a driver memoryObjectId can legitimately carry the same numeric value. - const uint64_t shared_handle = 0xE301; - - DeviceMemoryReport::Get().SetDebugObjectName(VK_OBJECT_TYPE_BUFFER, shared_handle, "collided_buffer"); - DeviceMemoryReport::Get().SetDebugObjectName(VK_OBJECT_TYPE_IMAGE, shared_handle, "collided_image"); - DeviceMemoryReport::Get().SetDebugObjectName(VK_OBJECT_TYPE_DEVICE_MEMORY, shared_handle, "collided_memory"); - - DeviceMemoryReport::Get().OnDestroyObject(shared_handle, VK_OBJECT_TYPE_BUFFER); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_BUFFER, shared_handle), ""); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_IMAGE, shared_handle), "collided_image"); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_DEVICE_MEMORY, shared_handle), "collided_memory"); - - // Freeing a driver-internal allocation whose memoryObjectId matches shared_handle must not - // erase the live VkDeviceMemory's debug name. - VkDeviceMemoryReportCallbackDataEXT driver_cb = {}; - driver_cb.sType = VK_STRUCTURE_TYPE_DEVICE_MEMORY_REPORT_CALLBACK_DATA_EXT; - driver_cb.flags = 0; - driver_cb.type = VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_ALLOCATE_EXT; - driver_cb.memoryObjectId = shared_handle; - driver_cb.size = 4096; - driver_cb.objectType = VK_OBJECT_TYPE_COMMAND_BUFFER; - driver_cb.objectHandle = 0x9999; - DeviceMemoryReport::MemoryReportCallback(&driver_cb, nullptr); - driver_cb.type = VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT; - DeviceMemoryReport::MemoryReportCallback(&driver_cb, nullptr); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_DEVICE_MEMORY, shared_handle), "collided_memory"); - - DeviceMemoryReport::Get().OnDestroyObject(shared_handle, VK_OBJECT_TYPE_IMAGE); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_IMAGE, shared_handle), ""); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_DEVICE_MEMORY, shared_handle), "collided_memory"); -} - -TEST_F(DeviceMemoryReportTests, DebugObjectNamesLegacyDebugReportTypes) { - TEST_DESCRIPTION("Test that VK_EXT_debug_marker object types map to their VkObjectType counterparts"); - - InitializeDeviceMemoryReportPerfetto(); - - const uint64_t buffer_handle = 0xE401; - const uint64_t image_handle = 0xE402; - const uint64_t memory_handle = 0xE403; - - DeviceMemoryReport::Get().SetDebugObjectName(VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, buffer_handle, "marker_buffer"); - DeviceMemoryReport::Get().SetDebugObjectName(VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, image_handle, "marker_image"); - DeviceMemoryReport::Get().SetDebugObjectName(VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, memory_handle, "marker_memory"); - - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_BUFFER, buffer_handle), "marker_buffer"); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_IMAGE, image_handle), "marker_image"); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_DEVICE_MEMORY, memory_handle), "marker_memory"); - - // Clearing through the legacy overload clears the underlying VkObjectType entry. - DeviceMemoryReport::Get().SetDebugObjectName(VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, buffer_handle, nullptr); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_BUFFER, buffer_handle), ""); - - // Untracked legacy object types are ignored. - DeviceMemoryReport::Get().SetDebugObjectName(VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, 0xE404, "marker_pipeline"); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_PIPELINE, 0xE404), ""); -} diff --git a/layersvt/test/test_devicememoryreport_dispatch.cpp b/layersvt/test/test_devicememoryreport_dispatch.cpp index 7f0c0eeca3..6b9f4ccd99 100644 --- a/layersvt/test/test_devicememoryreport_dispatch.cpp +++ b/layersvt/test/test_devicememoryreport_dispatch.cpp @@ -49,12 +49,6 @@ std::unordered_set g_bound_images; bool g_buffer_bound_at_last_requirements_query = false; bool g_image_bound_at_last_requirements_query = false; -// Controls whether the stub driver implements VK_EXT_debug_utils / VK_EXT_debug_marker naming. -bool g_stub_supports_debug_utils = false; -bool g_stub_supports_debug_marker = false; -int g_set_debug_utils_name_calls = 0; -int g_debug_marker_set_name_calls = 0; - template HandleType MakeHandle(uintptr_t value) { return reinterpret_cast(value); @@ -138,16 +132,6 @@ VKAPI_ATTR void VKAPI_CALL StubGetImageMemoryRequirements(VkDevice, VkImage imag pMemoryRequirements->memoryTypeBits = 1; } -VKAPI_ATTR VkResult VKAPI_CALL StubSetDebugUtilsObjectNameEXT(VkDevice, const VkDebugUtilsObjectNameInfoEXT*) { - ++g_set_debug_utils_name_calls; - return VK_SUCCESS; -} - -VKAPI_ATTR VkResult VKAPI_CALL StubDebugMarkerSetObjectNameEXT(VkDevice, const VkDebugMarkerObjectNameInfoEXT*) { - ++g_debug_marker_set_name_calls; - return VK_SUCCESS; -} - VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL StubGetDeviceProcAddr(VkDevice, const char* pName) { if (pName == nullptr) return nullptr; const std::string name(pName); @@ -168,12 +152,6 @@ VKAPI_ATTR PFN_vkVoidFunction VKAPI_CALL StubGetDeviceProcAddr(VkDevice, const c } if (name == "vkGetBufferMemoryRequirements") return reinterpret_cast(StubGetBufferMemoryRequirements); if (name == "vkGetImageMemoryRequirements") return reinterpret_cast(StubGetImageMemoryRequirements); - if (g_stub_supports_debug_utils && name == "vkSetDebugUtilsObjectNameEXT") { - return reinterpret_cast(StubSetDebugUtilsObjectNameEXT); - } - if (g_stub_supports_debug_marker && name == "vkDebugMarkerSetObjectNameEXT") { - return reinterpret_cast(StubDebugMarkerSetObjectNameEXT); - } // Everything else is not implemented by the stub driver. return nullptr; @@ -212,10 +190,6 @@ class DeviceMemoryReportDispatchTests : public ::testing::Test { g_bound_images.clear(); g_buffer_bound_at_last_requirements_query = false; g_image_bound_at_last_requirements_query = false; - g_stub_supports_debug_utils = false; - g_stub_supports_debug_marker = false; - g_set_debug_utils_name_calls = 0; - g_debug_marker_set_name_calls = 0; } void TearDown() override { @@ -466,68 +440,14 @@ TEST_F(DeviceMemoryReportDispatchTests, BindImageMemory2SkipsDisjointImagePlaneB EXPECT_EQ(DeviceMemoryReport::Get().GetRecordedResourceSize(VK_OBJECT_TYPE_IMAGE, AsObjectHandle(image)), 0u); } -TEST_F(DeviceMemoryReportDispatchTests, SetDebugUtilsObjectNameStandaloneAndChained) { - // 1. Standalone: driver/lower layers do not implement vkSetDebugUtilsObjectNameEXT. - g_stub_supports_debug_utils = false; - FakeDevice standalone_device; - VkBuffer buffer = MakeHandle(0xB9001); - - auto pfn_set_name = reinterpret_cast( - vkGetDeviceProcAddr(standalone_device.handle(), "vkSetDebugUtilsObjectNameEXT")); - ASSERT_NE(pfn_set_name, nullptr); - - VkDebugUtilsObjectNameInfoEXT name_info = {}; - name_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_OBJECT_NAME_INFO_EXT; - name_info.objectType = VK_OBJECT_TYPE_BUFFER; - name_info.objectHandle = AsObjectHandle(buffer); - name_info.pObjectName = "standalone_buffer"; - - EXPECT_EQ(pfn_set_name(standalone_device.handle(), &name_info), VK_SUCCESS); - EXPECT_EQ(g_set_debug_utils_name_calls, 0); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_BUFFER, AsObjectHandle(buffer)), - "standalone_buffer"); - - // 2. Chained: driver/lower layer implements vkSetDebugUtilsObjectNameEXT. - g_stub_supports_debug_utils = true; - FakeDevice chained_device; - name_info.pObjectName = "chained_buffer"; - - EXPECT_EQ(pfn_set_name(chained_device.handle(), &name_info), VK_SUCCESS); - EXPECT_EQ(g_set_debug_utils_name_calls, 1); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_BUFFER, AsObjectHandle(buffer)), - "chained_buffer"); -} - -TEST_F(DeviceMemoryReportDispatchTests, DebugMarkerSetObjectNameStandaloneAndChained) { - // 1. Standalone: driver/lower layers do not implement vkDebugMarkerSetObjectNameEXT. - g_stub_supports_debug_marker = false; - FakeDevice standalone_device; - VkImage image = MakeHandle(0xB9002); - - auto pfn_marker_set_name = reinterpret_cast( - vkGetDeviceProcAddr(standalone_device.handle(), "vkDebugMarkerSetObjectNameEXT")); - ASSERT_NE(pfn_marker_set_name, nullptr); - - VkDebugMarkerObjectNameInfoEXT marker_info = {}; - marker_info.sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT; - marker_info.objectType = VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT; - marker_info.object = AsObjectHandle(image); - marker_info.pObjectName = "standalone_image"; - - EXPECT_EQ(pfn_marker_set_name(standalone_device.handle(), &marker_info), VK_SUCCESS); - EXPECT_EQ(g_debug_marker_set_name_calls, 0); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_IMAGE, AsObjectHandle(image)), - "standalone_image"); - - // 2. Chained: driver/lower layer implements vkDebugMarkerSetObjectNameEXT. - g_stub_supports_debug_marker = true; - FakeDevice chained_device; - marker_info.pObjectName = "chained_image"; - - EXPECT_EQ(pfn_marker_set_name(chained_device.handle(), &marker_info), VK_SUCCESS); - EXPECT_EQ(g_debug_marker_set_name_calls, 1); - EXPECT_EQ(DeviceMemoryReportTestPeer::GetDebugObjectName(VK_OBJECT_TYPE_IMAGE, AsObjectHandle(image)), - "chained_image"); +TEST_F(DeviceMemoryReportDispatchTests, DoesNotProvideDebugNamingEntryPoints) { + // Debug object names are published by VK_LAYER_GOOGLE_DebugMarker. This layer must not hand out + // naming entry points of its own when nothing below it implements them. + FakeDevice device; + for (const char* name : {"vkSetDebugUtilsObjectNameEXT", "vkSetDebugUtilsObjectTagEXT", "vkCmdBeginDebugUtilsLabelEXT", + "vkDebugMarkerSetObjectNameEXT", "vkCmdDebugMarkerBeginEXT"}) { + EXPECT_EQ(vkGetDeviceProcAddr(device.handle(), name), nullptr) << name; + } } VKAPI_ATTR VkResult VKAPI_CALL StubEnumerateDeviceExtensionPropertiesWithOverlap( @@ -611,39 +531,28 @@ TEST_F(DeviceMemoryReportDispatchTests, EnumerateDeviceExtensionPropertiesDedupl VkPhysicalDevice physical_device = instance.physical_device(); // Downstream exposes VK_KHR_swapchain + VK_EXT_device_memory_report (2 extensions). - // The layer merges VK_EXT_device_memory_report (duplicate) + VK_EXT_debug_marker (new), - // so both the count query and the fill query must report 3 extensions. + // The layer's VK_EXT_device_memory_report is a duplicate, so both the count query and the fill + // query must report 2 extensions. uint32_t count = 0; EXPECT_EQ(vkEnumerateDeviceExtensionProperties(physical_device, nullptr, &count, nullptr), VK_SUCCESS); - EXPECT_EQ(count, 3u); + EXPECT_EQ(count, 2u); - // Passing non-null pProperties with count == 0 or count < 3 must return VK_INCOMPLETE. - std::vector properties(3); + // Passing non-null pProperties with count == 0 or count < 2 must return VK_INCOMPLETE. + std::vector properties(2); uint32_t zero_count = 0; EXPECT_EQ(vkEnumerateDeviceExtensionProperties(physical_device, nullptr, &zero_count, properties.data()), VK_INCOMPLETE); EXPECT_EQ(zero_count, 0u); - uint32_t partial_count = 2; + uint32_t partial_count = 1; EXPECT_EQ(vkEnumerateDeviceExtensionProperties(physical_device, nullptr, &partial_count, properties.data()), VK_INCOMPLETE); - EXPECT_EQ(partial_count, 2u); + EXPECT_EQ(partial_count, 1u); - uint32_t full_count = 3; + uint32_t full_count = 2; EXPECT_EQ(vkEnumerateDeviceExtensionProperties(physical_device, nullptr, &full_count, properties.data()), VK_SUCCESS); - EXPECT_EQ(full_count, 3u); -} - -TEST_F(DeviceMemoryReportDispatchTests, CreateDebugUtilsMessengerStubInitializesHandle) { - FakeInstance instance; - auto pfn_create_messenger = reinterpret_cast( - vkGetInstanceProcAddr(instance.handle(), "vkCreateDebugUtilsMessengerEXT")); - ASSERT_NE(pfn_create_messenger, nullptr); - - VkDebugUtilsMessengerCreateInfoEXT create_info = {}; - create_info.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT; - VkDebugUtilsMessengerEXT messenger = MakeHandle(0xDEADBEEF); - - EXPECT_EQ(pfn_create_messenger(instance.handle(), &create_info, nullptr, &messenger), VK_SUCCESS); - EXPECT_EQ(messenger, static_cast(VK_NULL_HANDLE)); + EXPECT_EQ(full_count, 2u); + for (const auto& property : properties) { + EXPECT_STRNE(property.extensionName, VK_EXT_DEBUG_MARKER_EXTENSION_NAME); + } } // Runs the layer's vkCreateDevice against the stub driver, with an optional application pNext chain. diff --git a/layersvt/test/test_devicememoryreport_peer.h b/layersvt/test/test_devicememoryreport_peer.h index f9164cb782..585d484762 100644 --- a/layersvt/test/test_devicememoryreport_peer.h +++ b/layersvt/test/test_devicememoryreport_peer.h @@ -47,13 +47,6 @@ class DeviceMemoryReportTestPeer { return it->second; } - static std::string GetDebugObjectName(VkObjectType object_type, uint64_t object_handle) { - auto& report = DeviceMemoryReport::Get(); - std::lock_guard lock(report.counter_mutex_); - auto it = report.debug_object_names_.find(std::make_pair(object_type, object_handle)); - return it != report.debug_object_names_.end() ? it->second : std::string(); - } - private: static std::optional FindAllocationByKey(const DeviceMemoryReport::AllocationKey& key) { auto& report = DeviceMemoryReport::Get(); From 8d841c13e4c0dd14d292049e01ff253aa79372ce Mon Sep 17 00:00:00 2001 From: jimblackler Date: Sun, 29 Nov 2026 12:23:23 +0000 Subject: [PATCH 2/4] device_memory_report: Switch traces to vulkan.memory_tracker Track events write annotation keys and string values in full on every packet, inflating trace size. Perfetto imports vulkan.memory_tracker packets directly into its standard allocation table with interned strings. Register that data source, emit one native packet per allocation or binding event, and intern keys and clusters per sequence. Replay live allocations at one shared timestamp on session start while holding back racing live events. Usage counter removal follows in the next change. Bug: b/564416621 --- .../device_memory_report.cpp | 242 ++++------ .../device_memory_report.h | 44 +- .../device_memory_report_perfetto.cpp | 221 ++++++++- .../device_memory_report_perfetto.h | 93 ++++ layersvt/test/test_devicememoryreport.cpp | 444 +++++++++++++++++- .../test/test_devicememoryreport_dispatch.cpp | 2 + 6 files changed, 872 insertions(+), 174 deletions(-) diff --git a/layersvt/device_memory_report/device_memory_report.cpp b/layersvt/device_memory_report/device_memory_report.cpp index bfe8f0bcee..57d7d9ba70 100644 --- a/layersvt/device_memory_report/device_memory_report.cpp +++ b/layersvt/device_memory_report/device_memory_report.cpp @@ -18,6 +18,7 @@ #include "perfetto/perfetto.h" #include #include +#include #include #include #include @@ -29,6 +30,37 @@ VkDeviceSize ClampToAllocation(VkDeviceSize offset, VkDeviceSize size, VkDeviceS return offset < total_size ? std::min(size, total_size - offset) : 0; } +using Event = perfetto::protos::pbzero::VulkanMemoryEvent; + +// An event for a VkDeviceMemory allocation (application) or a driver-internal allocation. +VulkanMemoryEventData AllocationEvent(Event::Operation operation, bool is_driver, uint64_t memory_object_id, VkDeviceSize size, + VkObjectType object_type, uint64_t object_handle, const char* cluster) { + return { + .source = is_driver ? Event::SOURCE_DRIVER : Event::SOURCE_DEVICE_MEMORY, + .operation = operation, + .device_memory = memory_object_id, + .object_handle = object_handle, + .memory_size = size, + .object_type = object_type, + .cluster = cluster, + }; +} + +// An event for a buffer or image bound into a VkDeviceMemory allocation. +VulkanMemoryEventData BindingEvent(Event::Operation operation, VkObjectType object_type, uint64_t resource_handle, + uint64_t memory_handle, VkDeviceSize size, VkDeviceSize offset, const char* cluster) { + return { + .source = object_type == VK_OBJECT_TYPE_IMAGE ? Event::SOURCE_IMAGE : Event::SOURCE_BUFFER, + .operation = operation, + .device_memory = memory_handle, + .object_handle = resource_handle, + .memory_size = size, + .offset = offset, + .object_type = object_type, + .cluster = cluster, + }; +} + } // namespace DeviceMemoryReport& DeviceMemoryReport::Get() { @@ -254,33 +286,6 @@ void DeviceMemoryReport::UpdateAllocationUnboundCounter(const AllocationKey& key allocation.applied_unbound_bytes = new_unbound; } -namespace { - -struct AllocationTraceEvent { - const char* operation; - const char* source; - uint64_t memory_object_id; - VkDeviceSize size; - VkDeviceSize offset; - VkObjectType object_type; - uint64_t object_handle; - const char* memory_type; -}; - -void EmitAllocationTraceEvent(const AllocationTraceEvent& event) { - TRACE_EVENT_INSTANT("VulkanDeviceMemoryReport", "VulkanMemoryAllocation", - "operation", event.operation, - "source", event.source, - "memory_object_id", event.memory_object_id, - "size", static_cast(event.size), - "offset", static_cast(event.offset), - "object_type", static_cast(event.object_type), - "object_handle", event.object_handle, - "memory_type", event.memory_type); -} - -} // namespace - void DeviceMemoryReport::RemoveResourceBinding(const ObjectKey& resource_key, Resource& resource, bool update_unbound_counter) { if (resource.bound_memory == 0) return; @@ -292,7 +297,6 @@ void DeviceMemoryReport::RemoveResourceBinding(const ObjectKey& resource_key, Re auto& allocation = allocation_it->second; const auto& [object_type, object_handle] = resource_key; - bool is_image = (object_type == VK_OBJECT_TYPE_IMAGE); const char* cluster_name = resource.GetCluster(allocation.mem_flags); auto& suballocations = allocation.sub_allocations; @@ -300,24 +304,16 @@ void DeviceMemoryReport::RemoveResourceBinding(const ObjectKey& resource_key, Re // since a single memory block can have multiple resources bound to it. for (auto it = suballocations.begin(); it != suballocations.end(); ++it) { if (it->object_type == object_type && it->resource_handle == object_handle) { - VkDeviceSize suballocation_size = it->size; - VkDeviceSize suballocation_offset = it->offset; + const VkDeviceSize suballocation_size = it->size; + const VkDeviceSize suballocation_offset = it->offset; SubtractCounterBytes(it->usage_track, suballocation_size); suballocations.erase(it); if (update_unbound_counter) { UpdateAllocationUnboundCounter(AllocationKey::App(memory_handle)); } - EmitAllocationTraceEvent({ - .operation = "DESTROY", - .source = is_image ? "IMAGE" : "BUFFER", - .memory_object_id = memory_handle, - .size = suballocation_size, - .offset = suballocation_offset, - .object_type = object_type, - .object_handle = object_handle, - .memory_type = cluster_name, - }); + EmitVulkanMemoryEvent(BindingEvent(Event::OP_DESTROY_BOUND, object_type, object_handle, memory_handle, + suballocation_size, suballocation_offset, cluster_name)); break; } } @@ -351,25 +347,17 @@ void DeviceMemoryReport::BindResourceMemoryLocked(const ObjectKey& resource_key, // Suballocations represent individual resources (like buffers or images) that are bound // to specific offset regions within a single large memory allocation. // We add a record here to track this specific resource's footprint within the larger memory block. - allocation.sub_allocations.push_back({ object_type, resource_handle, memory_offset, res_size, new_usage_track }); + allocation.sub_allocations.push_back( + {object_type, resource_handle, memory_offset, res_size, new_usage_track}); resource.bound_memory = memory_handle; // Each distinct virtual resource handle adds its clamped size to its specific category track upon binding. AddCounterBytes(new_usage_track, res_size); UpdateAllocationUnboundCounter(key); - bool is_image = (object_type == VK_OBJECT_TYPE_IMAGE); const char* cluster_name = resource.GetCluster(allocation.mem_flags); - EmitAllocationTraceEvent({ - .operation = "BIND", - .source = is_image ? "IMAGE" : "BUFFER", - .memory_object_id = memory_handle, - .size = res_size, - .offset = memory_offset, - .object_type = object_type, - .object_handle = resource_handle, - .memory_type = cluster_name, - }); + EmitVulkanMemoryEvent(BindingEvent(Event::OP_BIND, object_type, resource_handle, memory_handle, res_size, memory_offset, + cluster_name)); } void DeviceMemoryReport::ClampSubAllocationsToAllocation(const AllocationKey& key) { @@ -419,22 +407,13 @@ void DeviceMemoryReport::RemoveAllocationTracking(const AllocationKey& key) { for (const auto& suballocation : allocation.sub_allocations) { SubtractCounterBytes(suballocation.usage_track, suballocation.size); auto resource_iterator = resources_.find({suballocation.object_type, suballocation.resource_handle}); - bool is_image = (suballocation.object_type == VK_OBJECT_TYPE_IMAGE); const char* cluster_name = "unbound_memory"; if (resource_iterator != resources_.end()) { cluster_name = resource_iterator->second.GetCluster(allocation.mem_flags); resource_iterator->second.bound_memory = 0; } - EmitAllocationTraceEvent({ - .operation = "DESTROY", - .source = is_image ? "IMAGE" : "BUFFER", - .memory_object_id = key.id, - .size = suballocation.size, - .offset = suballocation.offset, - .object_type = suballocation.object_type, - .object_handle = suballocation.resource_handle, - .memory_type = cluster_name, - }); + EmitVulkanMemoryEvent(BindingEvent(Event::OP_DESTROY_BOUND, suballocation.object_type, suballocation.resource_handle, + key.id, suballocation.size, suballocation.offset, cluster_name)); } if (allocation.applied_unbound_bytes > 0) { SubtractCounterBytes(allocation.unbound_usage_track, allocation.applied_unbound_bytes); @@ -485,26 +464,10 @@ void DeviceMemoryReport::ReattributeDriverAllocations(uint64_t object_handle, Vk } // Re-attribution is published as DESTROY (old cluster) + CREATE (new cluster) so that // consumers summing CREATE/DESTROY sizes per memory_type stay balanced. - EmitAllocationTraceEvent({ - .operation = "DESTROY", - .source = "DRIVER", - .memory_object_id = key.id, - .size = allocation.total_size, - .offset = 0, - .object_type = allocation.object_type, - .object_handle = allocation.object_handle, - .memory_type = old_cluster_name, - }); - EmitAllocationTraceEvent({ - .operation = "CREATE", - .source = "DRIVER", - .memory_object_id = key.id, - .size = allocation.total_size, - .offset = 0, - .object_type = allocation.object_type, - .object_handle = allocation.object_handle, - .memory_type = allocation.cluster_name, - }); + EmitVulkanMemoryEvent(AllocationEvent(Event::OP_DESTROY, /*is_driver=*/true, key.id, allocation.total_size, + allocation.object_type, allocation.object_handle, old_cluster_name)); + EmitVulkanMemoryEvent(AllocationEvent(Event::OP_CREATE, /*is_driver=*/true, key.id, allocation.total_size, + allocation.object_type, allocation.object_handle, allocation.cluster_name)); } } @@ -534,50 +497,48 @@ void DeviceMemoryReport::OnDestroyObject(uint64_t object_handle, VkObjectType ob } } -void DeviceMemoryReport::DumpCurrentCountersAndAllocations() { +void DeviceMemoryReport::DumpCurrentCounters() { std::lock_guard lock(counter_mutex_); for (const auto& pair : usage_memory_bytes_) { if (pair.second > 0) { TRACE_COUNTER("VulkanDeviceMemoryReport", GetCounterTrack(pair.first), pair.second); } } +} +void DeviceMemoryReport::ReplayLiveAllocations(uint32_t instance_index) { + std::lock_guard lock(counter_mutex_); + // Every replayed event carries the same timestamp, so consumers see the state at session start + // as a single point in time. + const uint64_t timestamp = GetVulkanMemoryTraceTimeNs(); for (const auto& pair : memory_allocations_) { uint64_t memory_handle = pair.first.id; const auto& allocation = pair.second; if (allocation.total_size == 0) continue; - const char* memory_type = allocation.is_driver ? allocation.cluster_name : "unbound_memory"; - EmitAllocationTraceEvent({ - .operation = "CREATE", - .source = allocation.is_driver ? "DRIVER" : "DEVICE_MEMORY", - .memory_object_id = memory_handle, - .size = allocation.total_size, - .offset = 0, - .object_type = allocation.object_type, - .object_handle = allocation.object_handle, - .memory_type = memory_type, - }); + const char* cluster_name = allocation.is_driver ? allocation.cluster_name : "unbound_memory"; + VulkanMemoryEventData create = + AllocationEvent(Event::OP_CREATE, allocation.is_driver, memory_handle, allocation.total_size, + allocation.object_type, allocation.object_handle, cluster_name); + create.timestamp = timestamp; + EmitVulkanMemoryEvent(create, instance_index); for (const auto& suballocation : allocation.sub_allocations) { auto resource_iterator = resources_.find({suballocation.object_type, suballocation.resource_handle}); - bool is_image = (suballocation.object_type == VK_OBJECT_TYPE_IMAGE); - const char* cluster_name = (resource_iterator != resources_.end()) - ? resource_iterator->second.GetCluster(allocation.mem_flags) - : "unbound_memory"; - - EmitAllocationTraceEvent({ - .operation = "BIND", - .source = is_image ? "IMAGE" : "BUFFER", - .memory_object_id = memory_handle, - .size = suballocation.size, - .offset = suballocation.offset, - .object_type = suballocation.object_type, - .object_handle = suballocation.resource_handle, - .memory_type = cluster_name, - }); + const char* binding_cluster_name = (resource_iterator != resources_.end()) + ? resource_iterator->second.GetCluster(allocation.mem_flags) + : "unbound_memory"; + + VulkanMemoryEventData bind = BindingEvent(Event::OP_BIND, suballocation.object_type, suballocation.resource_handle, + memory_handle, suballocation.size, suballocation.offset, + binding_cluster_name); + bind.timestamp = timestamp; + EmitVulkanMemoryEvent(bind, instance_index); } } + // Live events are held back from the instance until now, and are emitted with counter_mutex_ + // held, so none of them is written before the replay or duplicated by it. + MarkVulkanMemoryReplayDone(instance_index); } void DeviceMemoryReport::OnMemoryReportEvent(const VkDeviceMemoryReportCallbackDataEXT* pCallbackData) { @@ -590,9 +551,8 @@ void DeviceMemoryReport::OnMemoryReportEvent(const VkDeviceMemoryReportCallbackD const bool is_driver = pCallbackData->objectType != VK_OBJECT_TYPE_DEVICE_MEMORY; const AllocationKey key = is_driver ? AllocationKey::Driver(pCallbackData->memoryObjectId) : AllocationKey::App(pCallbackData->objectHandle); - const char* source = is_driver ? "DRIVER" : "DEVICE_MEMORY"; - const char* operation_name = nullptr; + std::optional operation; const char* memory_type = "unbound_memory"; VkDeviceSize event_size = pCallbackData->size; VkObjectType event_object_type = pCallbackData->objectType; @@ -611,16 +571,8 @@ void DeviceMemoryReport::OnMemoryReportEvent(const VkDeviceMemoryReportCallbackD const VkObjectType stale_object_type = stale.object_type; const uint64_t stale_object_handle = stale.object_handle; RemoveAllocationTracking(key); - EmitAllocationTraceEvent({ - .operation = "DESTROY", - .source = source, - .memory_object_id = key.id, - .size = stale_size, - .offset = 0, - .object_type = stale_object_type, - .object_handle = stale_object_handle, - .memory_type = stale_memory_type, - }); + EmitVulkanMemoryEvent(AllocationEvent(Event::OP_DESTROY, is_driver, key.id, stale_size, stale_object_type, + stale_object_handle, stale_memory_type)); } auto& allocation = memory_allocations_[key]; allocation.total_size = pCallbackData->size; @@ -631,7 +583,7 @@ void DeviceMemoryReport::OnMemoryReportEvent(const VkDeviceMemoryReportCallbackD // Also resolves cluster_name for the CREATE event. App allocations are updated below. UpdateAllocationUnboundCounter(key); } - operation_name = "CREATE"; + operation = Event::OP_CREATE; memory_type = is_driver ? allocation.cluster_name : "unbound_memory"; } else if (pCallbackData->type == VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT || pCallbackData->type == VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_UNIMPORT_EXT) { @@ -642,27 +594,19 @@ void DeviceMemoryReport::OnMemoryReportEvent(const VkDeviceMemoryReportCallbackD event_object_type = allocation_iterator->second.object_type; event_object_handle = allocation_iterator->second.object_handle; RemoveAllocationTracking(key); - operation_name = "DESTROY"; + operation = Event::OP_DESTROY; } } - if (operation_name != nullptr) { - EmitAllocationTraceEvent({ - .operation = operation_name, - .source = source, - .memory_object_id = key.id, - .size = event_size, - .offset = 0, - .object_type = event_object_type, - .object_handle = event_object_handle, - .memory_type = memory_type, - }); + if (operation.has_value()) { + EmitVulkanMemoryEvent(AllocationEvent(*operation, is_driver, key.id, event_size, event_object_type, + event_object_handle, memory_type)); } if (!is_driver && (pCallbackData->type == VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_ALLOCATE_EXT || pCallbackData->type == VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_IMPORT_EXT)) { // Bindings recorded against a placeholder before its size was known are clamped after CREATE, - // so the corrective DESTROY/BIND events follow it in the trace. + // so the corrective DESTROY_BOUND/BIND events follow it in the trace. ClampSubAllocationsToAllocation(key); UpdateAllocationUnboundCounter(key); } @@ -699,16 +643,8 @@ void DeviceMemoryReport::OnAllocateMemory(VkDevice device, VkDeviceMemory memory allocation.object_type = VK_OBJECT_TYPE_DEVICE_MEMORY; allocation.object_handle = handle; - EmitAllocationTraceEvent({ - .operation = "CREATE", - .source = "DEVICE_MEMORY", - .memory_object_id = handle, - .size = size, - .offset = 0, - .object_type = VK_OBJECT_TYPE_DEVICE_MEMORY, - .object_handle = handle, - .memory_type = "unbound_memory", - }); + EmitVulkanMemoryEvent(AllocationEvent(Event::OP_CREATE, /*is_driver=*/false, handle, size, + VK_OBJECT_TYPE_DEVICE_MEMORY, handle, "unbound_memory")); // Clamp bindings recorded against a placeholder after CREATE (see OnMemoryReportEvent). ClampSubAllocationsToAllocation(key); @@ -724,18 +660,10 @@ void DeviceMemoryReport::OnFreeMemory(VkDevice device, VkDeviceMemory memory) { const AllocationKey key = AllocationKey::App(handle); auto allocation_iterator = memory_allocations_.find(key); if (allocation_iterator != memory_allocations_.end()) { - VkDeviceSize freed_size = allocation_iterator->second.total_size; + const VkDeviceSize freed_size = allocation_iterator->second.total_size; RemoveAllocationTracking(key); - EmitAllocationTraceEvent({ - .operation = "DESTROY", - .source = "DEVICE_MEMORY", - .memory_object_id = handle, - .size = freed_size, - .offset = 0, - .object_type = VK_OBJECT_TYPE_DEVICE_MEMORY, - .object_handle = handle, - .memory_type = "unbound_memory", - }); + EmitVulkanMemoryEvent(AllocationEvent(Event::OP_DESTROY, /*is_driver=*/false, handle, freed_size, + VK_OBJECT_TYPE_DEVICE_MEMORY, handle, "unbound_memory")); } } diff --git a/layersvt/device_memory_report/device_memory_report.h b/layersvt/device_memory_report/device_memory_report.h index 26dd7058e7..3b94016375 100644 --- a/layersvt/device_memory_report/device_memory_report.h +++ b/layersvt/device_memory_report/device_memory_report.h @@ -42,7 +42,7 @@ const char* GetImageCluster(VkImageUsageFlags usage, VkMemoryPropertyFlags memFl /** * The DeviceMemoryReport class is responsible for tracking Vulkan device memory - * allocations and object associations, sending live memory usage counters to Perfetto traces. + * allocations and object associations, and reporting them to Perfetto traces. * * It tracks allocations per object handle, categorizing memory by usage * types (e.g., textures, surfaces, buffers). @@ -55,11 +55,24 @@ const char* GetImageCluster(VkImageUsageFlags usage, VkMemoryPropertyFlags memFl * are tracked to attribute memory allocations to usage categories. Debug object names are not * handled by this layer; VK_LAYER_GOOGLE_DebugMarker publishes them. * - * Track Categories: - * Memory usage counters are reported to Perfetto under: - * - Driver vs Application allocations (e.g., vulkan.mem.driver.* vs vulkan.mem.app.*) - * - Usages (vulkan.mem.*.usage.) - * - Instant events under the "VulkanDeviceMemoryReport" category ("VulkanMemoryAllocation") + * What is emitted: + * Usage counters (vulkan.mem.app.usage. and vulkan.mem.driver.usage.) under the + * "VulkanDeviceMemoryReport" track event category, and one VulkanMemoryEvent TracePacket per + * memory event on the "vulkan.memory_tracker" data source (see VulkanMemoryEventData in + * device_memory_report_perfetto.h for the encoding): + * - SOURCE_DEVICE_MEMORY: an application VkDeviceMemory. OP_CREATE on allocate or import, + * OP_DESTROY on free or unimport. Cluster "unbound_memory". + * - SOURCE_BUFFER / SOURCE_IMAGE: a buffer or image bound into a VkDeviceMemory (device_memory). + * OP_BIND when bound, OP_DESTROY_BOUND when the binding goes away (the resource is unbound, + * re-bound, destroyed, its memory is freed, or the binding is clamped and re-bound). Cluster is + * the resource's usage cluster (GetBufferCluster / GetImageCluster). + * - SOURCE_DRIVER: a driver-internal allocation reported by VK_EXT_device_memory_report + * (device_memory is its memoryObjectId). OP_CREATE / OP_DESTROY. Cluster is the usage cluster of + * the VkBuffer / VkImage it belongs to, or "driver". When a buffer or image is created after its + * driver allocations were reported, they are re-attributed with OP_DESTROY (old cluster) then + * OP_CREATE (new cluster). + * When a session starts, OP_CREATE is replayed for every live allocation, each followed by OP_BIND + * for its live bindings, all with the same timestamp. * * This class is a singleton and provides thread-safe access to its state. */ @@ -202,11 +215,24 @@ class DeviceMemoryReport { void OnCreateBuffer(uint64_t buffer_handle, VkBufferUsageFlags usage, VkDeviceSize size); /** - * @brief Dumps the current state of counters and allocations to Perfetto. - * Invoked when a new Perfetto tracing session starts. Acquires counter_mutex_, + * @brief Writes the current values of the usage counters to Perfetto. + * Invoked when a new track event session starts. Acquires counter_mutex_, * so it must not be called while that lock is held. */ - void DumpCurrentCountersAndAllocations(); + void DumpCurrentCounters(); + + /** + * @brief Session-start replay for a vulkan.memory_tracker data source instance. + * + * Emits, to that instance only, OP_CREATE for every live allocation with a known size, each + * followed by OP_BIND for each of its live bindings, all with one timestamp taken at the start of + * the replay. Live events are held back from the instance until the replay is done. Invoked from + * the data source's OnStart. Acquires counter_mutex_, so it must not be called while that lock + * is held. + * + * @param instance_index The data source instance index (StartArgs::internal_instance_index). + */ + void ReplayLiveAllocations(uint32_t instance_index); /** * @brief Handles destruction of a Vulkan object, cleaning up tracked usage state. diff --git a/layersvt/device_memory_report/device_memory_report_perfetto.cpp b/layersvt/device_memory_report/device_memory_report_perfetto.cpp index b5fc41d262..57a09a615b 100644 --- a/layersvt/device_memory_report/device_memory_report_perfetto.cpp +++ b/layersvt/device_memory_report/device_memory_report_perfetto.cpp @@ -15,16 +15,183 @@ #include "device_memory_report_perfetto.h" #include "device_memory_report.h" +#include +#include +#include #include #include #include #include #include +#include PERFETTO_TRACK_EVENT_STATIC_STORAGE(); namespace { +using perfetto::protos::pbzero::TracePacket; +using perfetto::protos::pbzero::VulkanMemoryEvent; + +// Same clock as Perfetto's track events use by default. +#if defined(__APPLE__) || defined(_WIN32) +constexpr perfetto::protos::pbzero::BuiltinClock kTraceClock = perfetto::protos::pbzero::BUILTIN_CLOCK_MONOTONIC; +#else +constexpr perfetto::protos::pbzero::BuiltinClock kTraceClock = perfetto::protos::pbzero::BUILTIN_CLOCK_BOOTTIME; +#endif + +// Bit i is set once the session-start replay for data source instance i has been emitted. Live +// events are only written to instances whose bit is set, so that an event racing with the start +// of a session is neither written before the replay nor duplicated by it. Set and tested with the +// DeviceMemoryReport lock held. +std::atomic g_replayed_instances{0}; + +std::atomic g_event_hook_installed{false}; + +VulkanMemoryEventHook& EventHook() { + static VulkanMemoryEventHook hook; + return hook; +} + +// Per-sequence interning state. Perfetto destroys and recreates it whenever the incremental state +// is cleared (e.g. every TraceConfig.incremental_state_config.clear_period_ms). +struct VulkanMemoryTrackerIncrementalState { + bool was_cleared = true; + uint64_t next_iid = 1; + // Keys and string values share one iid space, as in InternedData.vulkan_memory_keys. + std::map> iids; +}; + +// Per-sequence state that survives incremental state clears: the instance's config and the +// emitting process and thread. +struct VulkanMemoryTrackerTlsState { + template + explicit VulkanMemoryTrackerTlsState(TraceContext&& ctx) { + auto data_source = ctx.GetDataSourceLocked(); + if (data_source) { + track_device_memory_usage = data_source->track_device_memory_usage(); + track_driver_memory_usage = data_source->track_driver_memory_usage(); + } + } + + bool track_device_memory_usage = false; + bool track_driver_memory_usage = false; + uint32_t pid = static_cast(perfetto::base::GetProcessId()); + int64_t tid = static_cast(perfetto::base::GetThreadId()); +}; + +struct VulkanMemoryTrackerTraits : public perfetto::DefaultDataSourceTraits { + using IncrementalStateType = VulkanMemoryTrackerIncrementalState; + using TlsStateType = VulkanMemoryTrackerTlsState; +}; + +class VulkanMemoryTrackerDataSource + : public perfetto::DataSource { + public: + // OnStart() takes the DeviceMemoryReport lock, which is held while emitting events; emitting can + // take the data source lock (to create the per-thread state), so the callbacks must not run + // under the data source lock. + static constexpr bool kRequiresCallbacksUnderLock = false; + + void OnSetup(const SetupArgs& args) override { + perfetto::protos::pbzero::VulkanMemoryConfig_Decoder config(args.config->vulkan_memory_config_raw()); + track_device_memory_usage_ = config.track_device_memory_usage(); + track_driver_memory_usage_ = config.track_driver_memory_usage(); + ClearVulkanMemoryReplayDoneForTesting(args.internal_instance_index); + } + + void OnStart(const StartArgs& args) override { + DeviceMemoryReport::Get().ReplayLiveAllocations(args.internal_instance_index); + } + + void OnStop(const StopArgs& args) override { ClearVulkanMemoryReplayDoneForTesting(args.internal_instance_index); } + + bool track_device_memory_usage() const { return track_device_memory_usage_; } + bool track_driver_memory_usage() const { return track_driver_memory_usage_; } + + private: + bool track_device_memory_usage_ = false; + bool track_driver_memory_usage_ = false; +}; + +void WriteVulkanMemoryEvent(VulkanMemoryTrackerDataSource::TraceContext& ctx, const VulkanMemoryEventData& event, + uint64_t timestamp) { + const bool is_driver = event.source == VulkanMemoryEvent::SOURCE_DRIVER; + const VulkanMemoryTrackerTlsState& tls = *ctx.GetCustomTlsState(); + if (is_driver ? !tls.track_driver_memory_usage : !tls.track_device_memory_usage) return; + + VulkanMemoryTrackerIncrementalState& state = *ctx.GetIncrementalState(); + + // Intern every string the event refers to before starting the packet, so that the definitions + // of strings new to this sequence go into the same packet's interned_data. + struct NewString { + uint64_t iid; + std::string_view str; + }; + std::array new_strings; + size_t new_string_count = 0; + auto intern = [&](std::string_view str) { + auto it = state.iids.find(str); + if (it != state.iids.end()) return it->second; + const uint64_t iid = state.next_iid++; + state.iids.emplace(std::string(str), iid); + new_strings[new_string_count++] = {iid, str}; + return iid; + }; + const bool is_binding = + event.operation == VulkanMemoryEvent::OP_BIND || event.operation == VulkanMemoryEvent::OP_DESTROY_BOUND; + const bool has_offset = is_binding && event.offset != 0; + const uint64_t cluster_key = intern("cluster"); + const uint64_t cluster_value = intern(event.cluster != nullptr ? event.cluster : "unbound_memory"); + const uint64_t tid_key = intern("tid"); + const uint64_t offset_key = has_offset ? intern("offset") : 0; + const uint64_t object_type_key = is_driver ? intern("object_type") : 0; + + auto packet = ctx.NewTracePacket(); + packet->set_timestamp(timestamp); + packet->set_timestamp_clock_id(static_cast(kTraceClock)); + if (state.was_cleared) { + packet->set_sequence_flags(TracePacket::SEQ_INCREMENTAL_STATE_CLEARED); + state.was_cleared = false; + } else { + packet->set_sequence_flags(TracePacket::SEQ_NEEDS_INCREMENTAL_STATE); + } + if (new_string_count > 0) { + auto* interned_data = packet->set_interned_data(); + for (size_t i = 0; i < new_string_count; ++i) { + auto* interned_string = interned_data->add_vulkan_memory_keys(); + interned_string->set_iid(new_strings[i].iid); + interned_string->set_str(reinterpret_cast(new_strings[i].str.data()), new_strings[i].str.size()); + } + } + + auto* memory_event = packet->set_vulkan_memory_event(); + memory_event->set_source(event.source); + memory_event->set_operation(event.operation); + // Trace Processor reads the event's own timestamp, not the packet's. + memory_event->set_timestamp(static_cast(timestamp)); + memory_event->set_pid(tls.pid); + memory_event->set_device_memory(event.device_memory); + memory_event->set_object_handle(event.object_handle); + memory_event->set_memory_size(event.memory_size); + + auto* cluster = memory_event->add_annotations(); + cluster->set_key_iid(cluster_key); + cluster->set_string_iid(cluster_value); + if (has_offset) { + auto* offset = memory_event->add_annotations(); + offset->set_key_iid(offset_key); + offset->set_int_value(static_cast(event.offset)); + } + if (is_driver) { + auto* object_type = memory_event->add_annotations(); + object_type->set_key_iid(object_type_key); + object_type->set_int_value(static_cast(event.object_type)); + } + auto* tid = memory_event->add_annotations(); + tid->set_key_iid(tid_key); + tid->set_int_value(tls.tid); +} + class DeviceMemoryReportSessionObserver : public perfetto::TrackEventSessionObserver { public: DeviceMemoryReportSessionObserver() { @@ -38,7 +205,7 @@ class DeviceMemoryReportSessionObserver : public perfetto::TrackEventSessionObse } void OnStart(const perfetto::DataSourceBase::StartArgs&) override { - DeviceMemoryReport::Get().DumpCurrentCountersAndAllocations(); + DeviceMemoryReport::Get().DumpCurrentCounters(); } }; @@ -47,6 +214,9 @@ class DeviceMemoryReportSessionObserver : public perfetto::TrackEventSessionObse void InitializeDeviceMemoryReportPerfetto() { static std::once_flag init_flag; std::call_once(init_flag, []() { + // Construct the singleton before registering the data source, so that it is destroyed after + // the data source can no longer call into it. + (void)DeviceMemoryReport::Get(); static DeviceMemoryReportSessionObserver session_observer; perfetto::TracingInitArgs args; args.backends = perfetto::kSystemBackend; @@ -54,12 +224,59 @@ void InitializeDeviceMemoryReportPerfetto() { perfetto::TrackEvent::Register(); perfetto::TrackEvent::AddSessionObserver(&session_observer); + perfetto::DataSourceDescriptor descriptor; + descriptor.set_name(kVulkanMemoryTrackerDataSourceName); + VulkanMemoryTrackerDataSource::Register(descriptor); + if (TRACE_EVENT_CATEGORY_ENABLED("VulkanDeviceMemoryReport")) { - DeviceMemoryReport::Get().DumpCurrentCountersAndAllocations(); + DeviceMemoryReport::Get().DumpCurrentCounters(); + } + }); +} + +uint64_t GetVulkanMemoryTraceTimeNs() { + if constexpr (kTraceClock == perfetto::protos::pbzero::BUILTIN_CLOCK_BOOTTIME) { + return static_cast(perfetto::base::GetBootTimeNs().count()); + } else { + return static_cast(perfetto::base::GetWallTimeNs().count()); + } +} + +void EmitVulkanMemoryEvent(const VulkanMemoryEventData& event, uint32_t instance_index) { + uint64_t timestamp = event.timestamp; + if (g_event_hook_installed.load(std::memory_order_relaxed)) { + if (timestamp == 0) timestamp = GetVulkanMemoryTraceTimeNs(); + VulkanMemoryEventData stamped = event; + stamped.timestamp = timestamp; + EventHook()(stamped); + } + VulkanMemoryTrackerDataSource::Trace([&](VulkanMemoryTrackerDataSource::TraceContext ctx) { + const uint32_t instance = ctx.instance_index(); + if (instance_index == kAllVulkanMemoryTrackerInstances) { + if ((g_replayed_instances.load(std::memory_order_relaxed) & (1u << instance)) == 0) return; + } else if (instance != instance_index) { + return; } + // Concurrent sessions get the same timestamp for the same event. + if (timestamp == 0) timestamp = GetVulkanMemoryTraceTimeNs(); + WriteVulkanMemoryEvent(ctx, event, timestamp); }); } +void MarkVulkanMemoryReplayDone(uint32_t instance_index) { + g_replayed_instances.fetch_or(1u << instance_index, std::memory_order_relaxed); +} + +void ClearVulkanMemoryReplayDoneForTesting(uint32_t instance_index) { + g_replayed_instances.fetch_and(~(1u << instance_index), std::memory_order_relaxed); +} + +void SetVulkanMemoryEventHookForTesting(VulkanMemoryEventHook hook) { + g_event_hook_installed.store(false, std::memory_order_relaxed); + EventHook() = std::move(hook); + g_event_hook_installed.store(static_cast(EventHook()), std::memory_order_relaxed); +} + perfetto::CounterTrack GetCounterTrack(std::string_view name) { static std::mutex tracks_mutex; // Declare track_names first so LIFO static destruction destroys tracks before the strings it views. diff --git a/layersvt/device_memory_report/device_memory_report_perfetto.h b/layersvt/device_memory_report/device_memory_report_perfetto.h index b3a7645668..e7be6b40b4 100644 --- a/layersvt/device_memory_report/device_memory_report_perfetto.h +++ b/layersvt/device_memory_report/device_memory_report_perfetto.h @@ -17,6 +17,9 @@ #define LAYERSVT_DEVICE_MEMORY_REPORT_PERFETTO_H #include "perfetto/perfetto.h" +#include +#include +#include #include // Define categories used for Perfetto tracing in DeviceMemoryReport layer. @@ -24,7 +27,97 @@ PERFETTO_DEFINE_CATEGORIES( perfetto::Category("VulkanDeviceMemoryReport").SetDescription("Vulkan Device Memory Report Counters") ); +/** + * @brief Name of the Perfetto data source the layer emits VulkanMemoryEvent packets on. + * + * The name and its config (DataSourceConfig.vulkan_memory_config, a VulkanMemoryConfig) are + * pre-existing in Perfetto: track_device_memory_usage enables the SOURCE_DEVICE_MEMORY, + * SOURCE_BUFFER and SOURCE_IMAGE events, and track_driver_memory_usage the SOURCE_DRIVER events. + */ +inline constexpr const char* kVulkanMemoryTrackerDataSourceName = "vulkan.memory_tracker"; + +/** + * @brief One VulkanMemoryEvent as the layer emits it, before it is serialized. + * + * Serialized as a TracePacket carrying a VulkanMemoryEvent with: + * - source, operation, device_memory, object_handle and memory_size as given here; + * - timestamp (also the packet timestamp) and pid; + * - interned annotations: "cluster" (string) always, "tid" (int) always, "offset" (int) on + * OP_BIND / OP_DESTROY_BOUND when non-zero, and "object_type" (int) on SOURCE_DRIVER only. + */ +struct VulkanMemoryEventData { + using Event = perfetto::protos::pbzero::VulkanMemoryEvent; + + Event::Source source = Event::SOURCE_UNSPECIFIED; + Event::Operation operation = Event::OP_UNSPECIFIED; + /** Trace time in ns (see GetVulkanMemoryTraceTimeNs). 0 means "stamp with the current time". */ + uint64_t timestamp = 0; + /** The VkDeviceMemory handle for application events and bindings, the memoryObjectId for driver events. */ + uint64_t device_memory = 0; + uint64_t object_handle = 0; + uint64_t memory_size = 0; + /** Binding offset; only emitted on OP_BIND / OP_DESTROY_BOUND, and only when non-zero. */ + VkDeviceSize offset = 0; + /** VkObjectType of the driver allocation; only emitted on SOURCE_DRIVER. */ + VkObjectType object_type = VK_OBJECT_TYPE_UNKNOWN; + /** Cluster name. Must point to a string that outlives the call (in practice, a literal). */ + const char* cluster = "unbound_memory"; +}; + +/** @brief Target for EmitVulkanMemoryEvent meaning "every active instance that finished its replay". */ +inline constexpr uint32_t kAllVulkanMemoryTrackerInstances = UINT32_MAX; + +/** + * @brief Initializes Perfetto and registers the vulkan.memory_tracker data source. Idempotent. + */ void InitializeDeviceMemoryReportPerfetto(); + +/** + * @brief Returns the current time in the clock the events are timestamped with (boot time on + * Linux and Android). + */ +uint64_t GetVulkanMemoryTraceTimeNs(); + +/** + * @brief Emits one VulkanMemoryEvent. + * + * Costs one relaxed atomic load when no vulkan.memory_tracker session is active (and no test hook + * is installed). Must be called with the DeviceMemoryReport lock held, which orders live events + * against the session-start replay. + * + * @param event The event to emit. + * @param instance_index kAllVulkanMemoryTrackerInstances for a live event, which goes to every + * active instance whose session-start replay has been emitted; otherwise the single instance a + * replayed event is for. + */ +void EmitVulkanMemoryEvent(const VulkanMemoryEventData& event, + uint32_t instance_index = kAllVulkanMemoryTrackerInstances); + +/** + * @brief Marks the session-start replay of a data source instance as emitted, so that live events + * go to it from now on. Must be called with the DeviceMemoryReport lock held, right after the + * replay. + */ +void MarkVulkanMemoryReplayDone(uint32_t instance_index); + +/** + * @brief Test hook invoked synchronously with every event passed to EmitVulkanMemoryEvent, whether + * or not a session is active, with its timestamp filled in. + */ +using VulkanMemoryEventHook = std::function; + +/** + * @brief Installs (or, with an empty hook, removes) the test hook. Not thread-safe against + * concurrent event emission; call it while no events are being emitted. + */ +void SetVulkanMemoryEventHookForTesting(VulkanMemoryEventHook hook); + +/** + * @brief Forgets that the replay of an instance was emitted, so that live events are held back + * from it as they are between its start and its replay (for testing). + */ +void ClearVulkanMemoryReplayDoneForTesting(uint32_t instance_index); + perfetto::CounterTrack GetCounterTrack(std::string_view name); #endif // LAYERSVT_DEVICE_MEMORY_REPORT_PERFETTO_H diff --git a/layersvt/test/test_devicememoryreport.cpp b/layersvt/test/test_devicememoryreport.cpp index 87f90ef956..22d2cc940a 100644 --- a/layersvt/test/test_devicememoryreport.cpp +++ b/layersvt/test/test_devicememoryreport.cpp @@ -21,10 +21,49 @@ #include #include +#include +#include +#include #include +#include +#include +#include static const char* kLayerName = "VK_LAYER_GOOGLE_DeviceMemoryReport"; +using Event = perfetto::protos::pbzero::VulkanMemoryEvent; + +// The fields of an emitted event that tests check. object_type is only compared for SOURCE_DRIVER +// events, as it is only emitted for them. +struct ExpectedEvent { + Event::Source source; + Event::Operation operation; + uint64_t device_memory; + uint64_t object_handle; + uint64_t memory_size; + std::string cluster; + VkDeviceSize offset = 0; + VkObjectType object_type = VK_OBJECT_TYPE_UNKNOWN; +}; + +static void ExpectEvents(const std::vector& actual, const std::vector& expected) { + ASSERT_EQ(actual.size(), expected.size()); + for (size_t i = 0; i < expected.size(); ++i) { + SCOPED_TRACE("event " + std::to_string(i)); + EXPECT_EQ(actual[i].source, expected[i].source); + EXPECT_EQ(actual[i].operation, expected[i].operation); + EXPECT_EQ(actual[i].device_memory, expected[i].device_memory); + EXPECT_EQ(actual[i].object_handle, expected[i].object_handle); + EXPECT_EQ(actual[i].memory_size, expected[i].memory_size); + EXPECT_STREQ(actual[i].cluster, expected[i].cluster.c_str()); + EXPECT_EQ(actual[i].offset, expected[i].offset); + if (expected[i].source == Event::SOURCE_DRIVER) { + EXPECT_EQ(actual[i].object_type, expected[i].object_type); + } + EXPECT_NE(actual[i].timestamp, 0u); + } +} + class DeviceMemoryReportTests : public VkTestFramework { public: ~DeviceMemoryReportTests(){}; @@ -36,12 +75,24 @@ class DeviceMemoryReportTests : public VkTestFramework { void SetUp() override { VkTestFramework::SetUp(); DeviceMemoryReport::Get().Reset(); + events_.clear(); + SetVulkanMemoryEventHookForTesting([this](const VulkanMemoryEventData& event) { events_.push_back(event); }); } void TearDown() override { + SetVulkanMemoryEventHookForTesting({}); DeviceMemoryReport::Get().Reset(); VkTestFramework::TearDown(); } + + // Returns the events emitted since the last call (or since the test started). + std::vector TakeEvents() { + std::vector events = std::move(events_); + events_.clear(); + return events; + } + + std::vector events_; }; TEST_F(DeviceMemoryReportTests, InitLayer) { @@ -157,7 +208,15 @@ TEST_F(DeviceMemoryReportTests, EmitEventsAndSubCounters) { DeviceMemoryReport::Get().OnAllocateMemory(dummy_device, dummy_memory, 4096); DeviceMemoryReport::Get().OnFreeMemory(dummy_device, dummy_memory); - EXPECT_TRUE(true); + // A FREE reports the size the allocation was created with, not the size in the callback. + ExpectEvents(TakeEvents(), { + {Event::SOURCE_DEVICE_MEMORY, Event::OP_CREATE, 0x5000, 0x5000, 1024 * 1024, "unbound_memory"}, + {Event::SOURCE_DEVICE_MEMORY, Event::OP_DESTROY, 0x5000, 0x5000, 1024 * 1024, "unbound_memory"}, + {Event::SOURCE_DRIVER, Event::OP_CREATE, 0x1000, 0x5000, 2048, "driver", 0, VK_OBJECT_TYPE_BUFFER}, + {Event::SOURCE_DRIVER, Event::OP_DESTROY, 0x1000, 0x5000, 2048, "driver", 0, VK_OBJECT_TYPE_BUFFER}, + {Event::SOURCE_DEVICE_MEMORY, Event::OP_CREATE, 0x5678, 0x5678, 4096, "unbound_memory"}, + {Event::SOURCE_DEVICE_MEMORY, Event::OP_DESTROY, 0x5678, 0x5678, 4096, "unbound_memory"}, + }); } TEST_F(DeviceMemoryReportTests, BufferImageBindingAndCallbackSuppression) { @@ -202,7 +261,18 @@ TEST_F(DeviceMemoryReportTests, BufferImageBindingAndCallbackSuppression) { DeviceMemoryReport::Get().OnAllocateMemory(test_device, test_memory, 8192); DeviceMemoryReport::Get().OnFreeMemory(test_device, test_memory); - EXPECT_TRUE(true); + // Bindings recorded before the allocation was reported are emitted at bind time, and the + // allocation's free removes them. The suppressed fallback allocation emits nothing. + ExpectEvents(TakeEvents(), { + {Event::SOURCE_BUFFER, Event::OP_BIND, memory_handle, buffer_handle, 1024, "geometry_mesh"}, + {Event::SOURCE_IMAGE, Event::OP_BIND, memory_handle, image_handle, 2048, "color_render_target", 1024}, + {Event::SOURCE_DEVICE_MEMORY, Event::OP_CREATE, memory_handle, memory_handle, 4096, "unbound_memory"}, + {Event::SOURCE_BUFFER, Event::OP_DESTROY_BOUND, memory_handle, buffer_handle, 1024, "geometry_mesh"}, + {Event::SOURCE_IMAGE, Event::OP_DESTROY_BOUND, memory_handle, image_handle, 2048, "color_render_target", 1024}, + {Event::SOURCE_DEVICE_MEMORY, Event::OP_DESTROY, memory_handle, memory_handle, 4096, "unbound_memory"}, + {Event::SOURCE_DEVICE_MEMORY, Event::OP_CREATE, 0xEF01, 0xEF01, 8192, "unbound_memory"}, + {Event::SOURCE_DEVICE_MEMORY, Event::OP_DESTROY, 0xEF01, 0xEF01, 8192, "unbound_memory"}, + }); } TEST_F(DeviceMemoryReportTests, UsageTypeBreakdown) { @@ -289,7 +359,29 @@ TEST_F(DeviceMemoryReportTests, UsageTypeBreakdown) { DeviceMemoryReport::Get().OnDestroyObject(storage_buf, VK_OBJECT_TYPE_BUFFER); DeviceMemoryReport::Get().OnDestroyObject(indirect_buf, VK_OBJECT_TYPE_BUFFER); - EXPECT_TRUE(true); + // Every binding is published under its usage cluster, both when bound and when the free removes + // it. Destroying the already-unbound resources emits nothing more. + const std::vector> expected_clusters = { + {color_img, "color_render_target"}, {depth_img, "depth_stencil_target"}, {sampled_img, "static_texture"}, + {storage_img, "storage_compute_image"}, {transient_img, "transient_memoryless"}, {vtx_buf, "geometry_mesh"}, + {idx_buf, "geometry_mesh"}, {ubo_buf, "uniform_constants"}, {staging_buf, "staging_transfer"}, + {storage_buf, "compute_storage"}, {indirect_buf, "indirect_gpu_driven"}, + }; + const std::vector events = TakeEvents(); + ASSERT_EQ(events.size(), 2 + 2 * expected_clusters.size()); + EXPECT_EQ(events.front().operation, Event::OP_CREATE); + EXPECT_EQ(events.back().operation, Event::OP_DESTROY); + for (size_t i = 0; i < expected_clusters.size(); ++i) { + const VulkanMemoryEventData& bind = events[1 + i]; + const VulkanMemoryEventData& unbind = events[1 + expected_clusters.size() + i]; + EXPECT_EQ(bind.operation, Event::OP_BIND); + EXPECT_EQ(unbind.operation, Event::OP_DESTROY_BOUND); + EXPECT_EQ(bind.object_handle, expected_clusters[i].first); + EXPECT_EQ(unbind.object_handle, expected_clusters[i].first); + EXPECT_STREQ(bind.cluster, expected_clusters[i].second.c_str()); + EXPECT_STREQ(unbind.cluster, expected_clusters[i].second.c_str()); + EXPECT_EQ(bind.source, i < 5 ? Event::SOURCE_IMAGE : Event::SOURCE_BUFFER); + } } TEST_F(DeviceMemoryReportTests, MemoryAliasingAndOverlap) { @@ -354,7 +446,18 @@ TEST_F(DeviceMemoryReportTests, MemoryAliasingAndOverlap) { DeviceMemoryReport::Get().OnDestroyObject(image_b, VK_OBJECT_TYPE_IMAGE); DeviceMemoryReport::Get().OnDestroyObject(buffer_c, VK_OBJECT_TYPE_BUFFER); - EXPECT_TRUE(true); + // Overlapping bindings are each published with their full (clamped) size and offset; consumers + // compute the slab's bound footprint as the union of the live bindings' ranges. + ExpectEvents(TakeEvents(), { + {Event::SOURCE_DEVICE_MEMORY, Event::OP_CREATE, mem_handle, mem_handle, 10000, "unbound_memory"}, + {Event::SOURCE_IMAGE, Event::OP_BIND, mem_handle, image_a, 4000, "color_render_target"}, + {Event::SOURCE_IMAGE, Event::OP_BIND, mem_handle, image_b, 4000, "static_texture", 2000}, + {Event::SOURCE_BUFFER, Event::OP_BIND, mem_handle, buffer_c, 1500, "geometry_mesh", 8000}, + {Event::SOURCE_IMAGE, Event::OP_DESTROY_BOUND, mem_handle, image_a, 4000, "color_render_target"}, + {Event::SOURCE_IMAGE, Event::OP_DESTROY_BOUND, mem_handle, image_b, 4000, "static_texture", 2000}, + {Event::SOURCE_BUFFER, Event::OP_DESTROY_BOUND, mem_handle, buffer_c, 1500, "geometry_mesh", 8000}, + {Event::SOURCE_DEVICE_MEMORY, Event::OP_DESTROY, mem_handle, mem_handle, 10000, "unbound_memory"}, + }); } TEST_F(DeviceMemoryReportTests, BindingsAreClampedToTheirAllocation) { @@ -410,6 +513,21 @@ TEST_F(DeviceMemoryReportTests, BindingsAreClampedToTheirAllocation) { ASSERT_TRUE(second_alloc.has_value()); ASSERT_EQ(second_alloc->sub_allocations.size(), 1u); EXPECT_EQ(second_alloc->sub_allocations[0].size, 2000u); + + // Bindings against a known allocation are clamped when bound, and one entirely outside it is not + // published. Bindings recorded before the allocation was known are published unclamped, then + // corrected after its CREATE: the overhanging ones are removed and the parts that lie within the + // allocation are bound again. + ExpectEvents(TakeEvents(), { + {Event::SOURCE_DEVICE_MEMORY, Event::OP_CREATE, 0xE001, 0xE001, 16000, "unbound_memory"}, + {Event::SOURCE_BUFFER, Event::OP_BIND, 0xE001, 0xE101, 4000, "geometry_mesh", 12000}, + {Event::SOURCE_BUFFER, Event::OP_BIND, 0xE002, 0xE103, 4000, "geometry_mesh", 8000}, + {Event::SOURCE_BUFFER, Event::OP_BIND, 0xE002, 0xE104, 1000, "geometry_mesh", 12000}, + {Event::SOURCE_DEVICE_MEMORY, Event::OP_CREATE, 0xE002, 0xE002, 10000, "unbound_memory"}, + {Event::SOURCE_BUFFER, Event::OP_DESTROY_BOUND, 0xE002, 0xE103, 4000, "geometry_mesh", 8000}, + {Event::SOURCE_BUFFER, Event::OP_DESTROY_BOUND, 0xE002, 0xE104, 1000, "geometry_mesh", 12000}, + {Event::SOURCE_BUFFER, Event::OP_BIND, 0xE002, 0xE103, 2000, "geometry_mesh", 8000}, + }); } TEST_F(DeviceMemoryReportTests, ClusterClassificationFunctions) { @@ -617,6 +735,15 @@ TEST_F(DeviceMemoryReportTests, DriverVsAppUnboundMemoryAttribution) { DeviceMemoryReport::Get().OnDestroyObject(shared_handle, VK_OBJECT_TYPE_IMAGE); + // Driver events carry the object type of the driver allocation; the application allocation is + // "unbound_memory" even though its handle matches the image. + ExpectEvents(TakeEvents(), { + {Event::SOURCE_DRIVER, Event::OP_CREATE, 0x8001, shared_handle, 4096, "color_render_target", 0, VK_OBJECT_TYPE_IMAGE}, + {Event::SOURCE_DRIVER, Event::OP_DESTROY, 0x8001, shared_handle, 4096, "color_render_target", 0, VK_OBJECT_TYPE_IMAGE}, + {Event::SOURCE_DEVICE_MEMORY, Event::OP_CREATE, shared_handle, shared_handle, 8192, "unbound_memory"}, + {Event::SOURCE_DEVICE_MEMORY, Event::OP_DESTROY, shared_handle, shared_handle, 8192, "unbound_memory"}, + }); + // Case 3: Driver allocation arrives before OnCreateBuffer (tests re-attribution) uint64_t buffer_handle = 0xF002; VkDeviceMemoryReportCallbackDataEXT buffer_callback_data = {}; @@ -640,6 +767,12 @@ TEST_F(DeviceMemoryReportTests, DriverVsAppUnboundMemoryAttribution) { auto reattributed_buf_alloc = DeviceMemoryReportTestPeer::FindDriverAllocation(0x8003); ASSERT_TRUE(reattributed_buf_alloc.has_value()); EXPECT_STREQ(reattributed_buf_alloc->cluster_name, "geometry_mesh"); + // Re-attribution is published as a DESTROY under the old cluster and a CREATE under the new one. + ExpectEvents(TakeEvents(), { + {Event::SOURCE_DRIVER, Event::OP_CREATE, 0x8003, buffer_handle, 4096, "driver", 0, VK_OBJECT_TYPE_BUFFER}, + {Event::SOURCE_DRIVER, Event::OP_DESTROY, 0x8003, buffer_handle, 4096, "driver", 0, VK_OBJECT_TYPE_BUFFER}, + {Event::SOURCE_DRIVER, Event::OP_CREATE, 0x8003, buffer_handle, 4096, "geometry_mesh", 0, VK_OBJECT_TYPE_BUFFER}, + }); // Clean up buffer_callback_data.type = VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT; @@ -686,8 +819,14 @@ TEST_F(DeviceMemoryReportTests, DriverVsAppUnboundMemoryAttribution) { DeviceMemoryReport::MemoryReportCallback(&dup_cb, nullptr); EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.driver"), 4096u); + TakeEvents(); dup_cb.size = 2048; DeviceMemoryReport::MemoryReportCallback(&dup_cb, nullptr); + // A second ALLOCATE for a live memoryObjectId retires the first allocation before creating the new one. + ExpectEvents(TakeEvents(), { + {Event::SOURCE_DRIVER, Event::OP_DESTROY, 0x8005, 0xF004, 4096, "driver", 0, VK_OBJECT_TYPE_COMMAND_POOL}, + {Event::SOURCE_DRIVER, Event::OP_CREATE, 0x8005, 0xF004, 2048, "driver", 0, VK_OBJECT_TYPE_COMMAND_POOL}, + }); EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.driver"), 2048u); dup_cb.type = VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT; @@ -864,7 +1003,7 @@ TEST_F(DeviceMemoryReportTests, BufferAndImageWithCollidingHandlesAreTrackedInde } TEST_F(DeviceMemoryReportTests, MemoryReportSnapshotDump) { - TEST_DESCRIPTION("Test DumpCurrentCountersAndAllocations state dump and instant event emissions when a trace session begins"); + TEST_DESCRIPTION("Test the counter dump and the replay of live allocations and bindings when a trace session begins"); InitializeDeviceMemoryReportPerfetto(); @@ -897,8 +1036,39 @@ TEST_F(DeviceMemoryReportTests, MemoryReportSnapshotDump) { EXPECT_EQ(allocation->sub_allocations.size(), 2u); EXPECT_EQ(allocation->applied_unbound_bytes, 8192u); + // A driver allocation is replayed under its resolved cluster, and a placeholder allocation whose + // size is not known yet is not replayed. + VkDeviceMemoryReportCallbackDataEXT driver_data = callback_data; + driver_data.memoryObjectId = 0x7001; + driver_data.size = 512; + driver_data.objectType = VK_OBJECT_TYPE_IMAGE; + driver_data.objectHandle = image_handle; + DeviceMemoryReport::MemoryReportCallback(&driver_data, nullptr); + DeviceMemoryReport::Get().SetAllocationMemoryProperties(0xE003, 0); + TakeEvents(); + // Test dumping the current snapshot of counters, allocations, and suballocations - DeviceMemoryReport::Get().DumpCurrentCountersAndAllocations(); + DeviceMemoryReport::Get().DumpCurrentCounters(); + DeviceMemoryReport::Get().ReplayLiveAllocations(0); + ClearVulkanMemoryReplayDoneForTesting(0); + + std::vector replay = TakeEvents(); + ASSERT_EQ(replay.size(), 4u); + // Allocations are replayed in no particular order, but each one's bindings follow its CREATE. + const size_t app_create = replay[0].source == Event::SOURCE_DEVICE_MEMORY ? 0 : 1; + const size_t driver_create = app_create == 0 ? 3 : 0; + ExpectEvents({replay.begin() + app_create, replay.begin() + app_create + 3}, { + {Event::SOURCE_DEVICE_MEMORY, Event::OP_CREATE, memory_handle, memory_handle, 16384, "unbound_memory"}, + {Event::SOURCE_BUFFER, Event::OP_BIND, memory_handle, buffer_handle, 4096, "compute_storage"}, + {Event::SOURCE_IMAGE, Event::OP_BIND, memory_handle, image_handle, 4096, "color_render_target", 4096}, + }); + ExpectEvents({replay[driver_create]}, { + {Event::SOURCE_DRIVER, Event::OP_CREATE, 0x7001, image_handle, 512, "color_render_target", 0, VK_OBJECT_TYPE_IMAGE}, + }); + // The whole replay carries a single timestamp. + for (const VulkanMemoryEventData& event : replay) { + EXPECT_EQ(event.timestamp, replay[0].timestamp); + } // Verify that dumping state is non-destructive and preserves allocation invariants auto post_dump_allocation = DeviceMemoryReportTestPeer::FindAllocation(memory_handle); @@ -919,3 +1089,265 @@ TEST_F(DeviceMemoryReportTests, MemoryReportSnapshotDump) { EXPECT_FALSE(DeviceMemoryReportTestPeer::FindResource(VK_OBJECT_TYPE_BUFFER, buffer_handle).has_value()); EXPECT_FALSE(DeviceMemoryReportTestPeer::FindResource(VK_OBJECT_TYPE_IMAGE, image_handle).has_value()); } + +namespace { + +// One VulkanMemoryEvent packet decoded from a trace, with its annotations resolved through the +// sequence's interned strings. +struct DecodedEvent { + uint32_t sequence_flags = 0; + uint64_t packet_timestamp = 0; + uint32_t clock_id = 0; + std::vector> new_interned_strings; + int32_t source = 0; + int32_t operation = 0; + int64_t timestamp = 0; + uint32_t pid = 0; + uint64_t device_memory = 0; + uint64_t object_handle = 0; + uint64_t memory_size = 0; + std::map int_annotations; + std::map string_annotations; +}; + +// Runs a vulkan.memory_tracker session on the in-process tracing backend. +class VulkanMemoryTrackerSession { + public: + VulkanMemoryTrackerSession(bool track_device_memory_usage, bool track_driver_memory_usage) { + InitializeDeviceMemoryReportPerfetto(); + perfetto::TracingInitArgs args; + args.backends = perfetto::kInProcessBackend; + perfetto::Tracing::Initialize(args); + + perfetto::TraceConfig config; + config.add_buffers()->set_size_kb(1024); + auto* data_source = config.add_data_sources()->mutable_config(); + data_source->set_name(kVulkanMemoryTrackerDataSourceName); + perfetto::protos::gen::VulkanMemoryConfig memory_config; + memory_config.set_track_device_memory_usage(track_device_memory_usage); + memory_config.set_track_driver_memory_usage(track_driver_memory_usage); + data_source->set_vulkan_memory_config_raw(memory_config.SerializeAsString()); + + session_ = perfetto::Tracing::NewTrace(perfetto::kInProcessBackend); + session_->Setup(config); + session_->StartBlocking(); + } + + // Stops the session and returns its events, in trace order. + std::vector Stop() { + session_->FlushBlocking(); + session_->StopBlocking(); + std::vector trace_data = session_->ReadTraceBlocking(); + + std::vector events; + std::map interned; + perfetto::protos::pbzero::Trace_Decoder trace(reinterpret_cast(trace_data.data()), trace_data.size()); + for (auto it = trace.packet(); it; ++it) { + perfetto::protos::pbzero::TracePacket_Decoder packet(*it); + if (!packet.has_vulkan_memory_event()) continue; + DecodedEvent decoded; + decoded.sequence_flags = packet.sequence_flags(); + decoded.packet_timestamp = packet.timestamp(); + decoded.clock_id = packet.timestamp_clock_id(); + if (decoded.sequence_flags & + static_cast(perfetto::protos::pbzero::TracePacket::SEQ_INCREMENTAL_STATE_CLEARED)) { + interned.clear(); + } + if (packet.has_interned_data()) { + perfetto::protos::pbzero::InternedData_Decoder interned_data(packet.interned_data()); + for (auto key = interned_data.vulkan_memory_keys(); key; ++key) { + perfetto::protos::pbzero::InternedString_Decoder interned_string(*key); + std::string str(reinterpret_cast(interned_string.str().data), interned_string.str().size); + decoded.new_interned_strings.emplace_back(interned_string.iid(), str); + interned[interned_string.iid()] = str; + } + } + Event::Decoder event(packet.vulkan_memory_event()); + decoded.source = event.source(); + decoded.operation = event.operation(); + decoded.timestamp = event.timestamp(); + decoded.pid = event.pid(); + decoded.device_memory = event.device_memory(); + decoded.object_handle = event.object_handle(); + decoded.memory_size = event.memory_size(); + for (auto annotation_it = event.annotations(); annotation_it; ++annotation_it) { + perfetto::protos::pbzero::VulkanMemoryEventAnnotation_Decoder annotation(*annotation_it); + const std::string key = interned.count(annotation.key_iid()) ? interned[annotation.key_iid()] : ""; + if (annotation.has_string_iid()) { + decoded.string_annotations[key] = + interned.count(annotation.string_iid()) ? interned[annotation.string_iid()] : ""; + } else { + decoded.int_annotations[key] = annotation.int_value(); + } + } + events.push_back(std::move(decoded)); + } + return events; + } + + private: + std::unique_ptr session_; +}; + +void AllocateAppMemory(uint64_t memory_handle, VkDeviceSize size) { + VkDeviceMemoryReportCallbackDataEXT cb = {}; + cb.sType = VK_STRUCTURE_TYPE_DEVICE_MEMORY_REPORT_CALLBACK_DATA_EXT; + cb.type = VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_ALLOCATE_EXT; + cb.memoryObjectId = memory_handle + 1; + cb.size = size; + cb.objectType = VK_OBJECT_TYPE_DEVICE_MEMORY; + cb.objectHandle = memory_handle; + DeviceMemoryReport::MemoryReportCallback(&cb, nullptr); +} + +void AllocateDriverMemory(uint64_t memory_object_id, VkDeviceSize size) { + VkDeviceMemoryReportCallbackDataEXT cb = {}; + cb.sType = VK_STRUCTURE_TYPE_DEVICE_MEMORY_REPORT_CALLBACK_DATA_EXT; + cb.type = VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_ALLOCATE_EXT; + cb.memoryObjectId = memory_object_id; + cb.size = size; + cb.objectType = VK_OBJECT_TYPE_PIPELINE_CACHE; + cb.objectHandle = 0xCAFE; + DeviceMemoryReport::MemoryReportCallback(&cb, nullptr); +} + +} // namespace + +TEST_F(DeviceMemoryReportTests, VulkanMemoryTrackerDataSourceEncoding) { + TEST_DESCRIPTION("Test the VulkanMemoryEvent packets written to a vulkan.memory_tracker session"); + + // Live before the session starts, so replayed at its start. + AllocateAppMemory(0xB001, 65536); + DeviceMemoryReport::Get().OnCreateBuffer(0xB101, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, 4096); + DeviceMemoryReport::Get().OnBindBufferMemory(0xB101, 0xB001, 8192); + + VulkanMemoryTrackerSession session(/*track_device_memory_usage=*/true, /*track_driver_memory_usage=*/true); + AllocateDriverMemory(0xB201, 1024); + DeviceMemoryReport::Get().OnDestroyObject(0xB101, VK_OBJECT_TYPE_BUFFER); + const std::vector events = session.Stop(); + + ASSERT_EQ(events.size(), 4u); +#if defined(__APPLE__) || defined(_WIN32) + constexpr perfetto::protos::pbzero::BuiltinClock kExpectedTraceClock = perfetto::protos::pbzero::BUILTIN_CLOCK_MONOTONIC; +#else + constexpr perfetto::protos::pbzero::BuiltinClock kExpectedTraceClock = perfetto::protos::pbzero::BUILTIN_CLOCK_BOOTTIME; +#endif + const uint32_t pid = static_cast(perfetto::base::GetProcessId()); + for (const DecodedEvent& event : events) { + EXPECT_EQ(event.pid, pid); + EXPECT_EQ(static_cast(event.timestamp), event.packet_timestamp); + EXPECT_NE(event.timestamp, 0); + EXPECT_EQ(event.clock_id, static_cast(kExpectedTraceClock)); + EXPECT_EQ(event.string_annotations.size(), 1u); + EXPECT_EQ(event.int_annotations.count("tid"), 1u); + } + + // The replay (on the tracing thread) shares one timestamp. + EXPECT_EQ(events[0].source, Event::SOURCE_DEVICE_MEMORY); + EXPECT_EQ(events[0].operation, Event::OP_CREATE); + EXPECT_EQ(events[0].device_memory, 0xB001u); + EXPECT_EQ(events[0].object_handle, 0xB001u); + EXPECT_EQ(events[0].memory_size, 65536u); + EXPECT_EQ(events[0].string_annotations.at("cluster"), "unbound_memory"); + EXPECT_EQ(events[0].int_annotations.size(), 1u); + EXPECT_EQ(events[1].source, Event::SOURCE_BUFFER); + EXPECT_EQ(events[1].operation, Event::OP_BIND); + EXPECT_EQ(events[1].device_memory, 0xB001u); + EXPECT_EQ(events[1].object_handle, 0xB101u); + EXPECT_EQ(events[1].memory_size, 4096u); + EXPECT_EQ(events[1].string_annotations.at("cluster"), "geometry_mesh"); + EXPECT_EQ(events[1].int_annotations.at("offset"), 8192); + EXPECT_EQ(events[1].timestamp, events[0].timestamp); + + // Live events, from this thread. + const int64_t tid = static_cast(perfetto::base::GetThreadId()); + EXPECT_EQ(events[2].source, Event::SOURCE_DRIVER); + EXPECT_EQ(events[2].operation, Event::OP_CREATE); + EXPECT_EQ(events[2].device_memory, 0xB201u); + EXPECT_EQ(events[2].object_handle, 0xCAFEu); + EXPECT_EQ(events[2].memory_size, 1024u); + EXPECT_EQ(events[2].string_annotations.at("cluster"), "driver"); + EXPECT_EQ(events[2].int_annotations.at("object_type"), VK_OBJECT_TYPE_PIPELINE_CACHE); + EXPECT_EQ(events[2].int_annotations.at("tid"), tid); + EXPECT_GE(events[2].timestamp, events[1].timestamp); + EXPECT_EQ(events[3].source, Event::SOURCE_BUFFER); + EXPECT_EQ(events[3].operation, Event::OP_DESTROY_BOUND); + EXPECT_EQ(events[3].object_handle, 0xB101u); + EXPECT_EQ(events[3].int_annotations.at("offset"), 8192); + EXPECT_EQ(events[3].int_annotations.at("tid"), tid); + EXPECT_EQ(events[3].int_annotations.count("object_type"), 0u); + + constexpr uint32_t kCleared = perfetto::protos::pbzero::TracePacket::SEQ_INCREMENTAL_STATE_CLEARED; + constexpr uint32_t kNeeds = perfetto::protos::pbzero::TracePacket::SEQ_NEEDS_INCREMENTAL_STATE; + // The first packet of each sequence (replay thread, this thread) resets the incremental state, + // and every string is defined once per sequence, before or in the first packet that uses it, + // with iids starting at 1. + EXPECT_EQ(events[0].sequence_flags, kCleared); + EXPECT_EQ(events[1].sequence_flags, kNeeds); + EXPECT_EQ(events[2].sequence_flags, kCleared); + EXPECT_EQ(events[3].sequence_flags, kNeeds); + const std::vector> first_strings = {{1, "cluster"}, {2, "unbound_memory"}, {3, "tid"}}; + EXPECT_EQ(events[0].new_interned_strings, first_strings); + const std::vector> bind_strings = {{4, "geometry_mesh"}, {5, "offset"}}; + EXPECT_EQ(events[1].new_interned_strings, bind_strings); + const std::vector> driver_strings = { + {1, "cluster"}, {2, "driver"}, {3, "tid"}, {4, "object_type"}}; + EXPECT_EQ(events[2].new_interned_strings, driver_strings); + const std::vector> unbind_strings = {{5, "geometry_mesh"}, {6, "offset"}}; + EXPECT_EQ(events[3].new_interned_strings, unbind_strings); +} + +TEST_F(DeviceMemoryReportTests, VulkanMemoryTrackerDataSourceConfig) { + TEST_DESCRIPTION("Test that VulkanMemoryConfig selects the application and driver events"); + + { + VulkanMemoryTrackerSession session(/*track_device_memory_usage=*/true, /*track_driver_memory_usage=*/false); + AllocateAppMemory(0xB301, 4096); + AllocateDriverMemory(0xB302, 1024); + const std::vector events = session.Stop(); + ASSERT_EQ(events.size(), 1u); + EXPECT_EQ(events[0].source, Event::SOURCE_DEVICE_MEMORY); + } + DeviceMemoryReport::Get().Reset(); + { + VulkanMemoryTrackerSession session(/*track_device_memory_usage=*/false, /*track_driver_memory_usage=*/true); + AllocateAppMemory(0xB401, 4096); + AllocateDriverMemory(0xB402, 1024); + const std::vector events = session.Stop(); + ASSERT_EQ(events.size(), 1u); + EXPECT_EQ(events[0].source, Event::SOURCE_DRIVER); + } +} + +TEST_F(DeviceMemoryReportTests, VulkanMemoryTrackerLiveEventsWaitForReplay) { + TEST_DESCRIPTION("Test that live events are held back from a session until its start replay was emitted"); + + VulkanMemoryTrackerSession session(/*track_device_memory_usage=*/true, /*track_driver_memory_usage=*/true); + AllocateAppMemory(0xB501, 4096); + + // Simulate an event that races with the start of the session: the instance has started, but its + // replay has not been emitted yet. The session's instance index is not known here, so treat every + // instance as started but not replayed. + constexpr uint32_t kMaxInstances = 8; + for (uint32_t i = 0; i < kMaxInstances; ++i) ClearVulkanMemoryReplayDoneForTesting(i); + AllocateAppMemory(0xB502, 8192); + // The replay then includes that allocation, and live events flow again after it. + for (uint32_t i = 0; i < kMaxInstances; ++i) DeviceMemoryReport::Get().ReplayLiveAllocations(i); + AllocateAppMemory(0xB503, 16384); + + const std::vector events = session.Stop(); + std::vector> creates; + for (const DecodedEvent& event : events) { + ASSERT_EQ(event.operation, Event::OP_CREATE); + creates.emplace_back(event.device_memory, event.memory_size); + } + // 0xB501 live, then the replay of 0xB501 and 0xB502 (in either order), then 0xB503 live. 0xB502 is + // only written once. + ASSERT_EQ(creates.size(), 4u); + EXPECT_EQ(creates[0], std::make_pair(uint64_t{0xB501}, uint64_t{4096})); + std::vector> replayed = {creates[1], creates[2]}; + std::sort(replayed.begin(), replayed.end()); + const std::vector> expected_replay = {{0xB501, 4096}, {0xB502, 8192}}; + EXPECT_EQ(replayed, expected_replay); + EXPECT_EQ(creates[3], std::make_pair(uint64_t{0xB503}, uint64_t{16384})); +} diff --git a/layersvt/test/test_devicememoryreport_dispatch.cpp b/layersvt/test/test_devicememoryreport_dispatch.cpp index 6b9f4ccd99..1f000f21b7 100644 --- a/layersvt/test/test_devicememoryreport_dispatch.cpp +++ b/layersvt/test/test_devicememoryreport_dispatch.cpp @@ -21,6 +21,7 @@ // Vulkan implementation. #include "device_memory_report.h" +#include "device_memory_report_perfetto.h" #include "test_devicememoryreport_peer.h" #include "vk_layer_table.h" @@ -31,6 +32,7 @@ #include #include #include +#include namespace { From 3a3b397ca3e67e0dd7a9006b7c3ea3b3e2e4847c Mon Sep 17 00:00:00 2001 From: jimblackler Date: Sun, 29 Nov 2026 12:26:29 +0000 Subject: [PATCH 3/4] device_memory_report: Stop emitting derived usage counters Trace consumers can compute per-cluster application, unbound, and driver totals directly from the allocation stream. Maintaining running counter tracks in the layer duplicates that work and adds trace volume. Delete the usage counter tracks, interval-union bookkeeping, counter replay at session start, and the remaining track-event category so the layer writes only allocation events. Keep suballocation tracking, binding clamping, and driver cluster resolution needed for those events. Bug: b/564416621 --- .../device_memory_report.cpp | 193 +++--------------- .../device_memory_report.h | 66 ++---- .../device_memory_report_perfetto.cpp | 53 +---- .../device_memory_report_perfetto.h | 8 - layersvt/test/test_devicememoryreport.cpp | 176 +++------------- .../test/test_devicememoryreport_dispatch.cpp | 17 +- layersvt/test/test_devicememoryreport_peer.h | 4 +- 7 files changed, 99 insertions(+), 418 deletions(-) diff --git a/layersvt/device_memory_report/device_memory_report.cpp b/layersvt/device_memory_report/device_memory_report.cpp index 57d7d9ba70..f8e42ac713 100644 --- a/layersvt/device_memory_report/device_memory_report.cpp +++ b/layersvt/device_memory_report/device_memory_report.cpp @@ -88,30 +88,18 @@ VkInstance DeviceMemoryReport::GetVkInstance(VkPhysicalDevice phys_dev) { } void DeviceMemoryReport::SetDeviceMemoryProperties(VkDevice device, const VkPhysicalDeviceMemoryProperties& props) { - std::lock_guard lock(counter_mutex_); + std::lock_guard lock(state_mutex_); device_memory_properties_map_[device] = props; } void DeviceMemoryReport::SetAllocationMemoryProperties(uint64_t memory_handle, VkMemoryPropertyFlags property_flags) { - std::lock_guard lock(counter_mutex_); + std::lock_guard lock(state_mutex_); const AllocationKey key = AllocationKey::App(memory_handle); - auto& allocation = memory_allocations_[key]; - allocation.mem_flags = property_flags; - // An allocation with total_size > 0 represents an active physical memory allocation that - // has already been recorded and contributed to Perfetto counter tracks. - // Changing its memory property flags (e.g., HOST_VISIBLE or LAZILY_ALLOCATED) can alter - // how its unbound memory headroom is classified into usage categories (such as staging - // vs general buffer or transient memoryless). We must update the unbound counter to move - // the reported bytes from the old usage track to the newly classified track. - // If total_size == 0, the allocation has not yet been instantiated (or is being configured - // prior to allocation), so no counter bytes have been emitted to Perfetto yet. - if (allocation.total_size > 0) { - UpdateAllocationUnboundCounter(key); - } + memory_allocations_[key].mem_flags = property_flags; } void DeviceMemoryReport::OnDestroyDevice(VkDevice device) { - std::lock_guard lock(counter_mutex_); + std::lock_guard lock(state_mutex_); has_callback_map_.erase(device); device_memory_properties_map_.erase(device); } @@ -196,97 +184,20 @@ const char* GetImageCluster(VkImageUsageFlags usage, VkMemoryPropertyFlags memFl return "general_image"; } -// Construct a Perfetto track name for visualizing memory usage by category in the UI. -static std::string GetUsageTrackName(bool is_driver, std::string_view usage) { - std::string track = is_driver ? "vulkan.mem.driver.usage." : "vulkan.mem.app.usage."; - track += usage; - return track; -} - -void DeviceMemoryReport::AddCounterBytes(const std::string& track, uint64_t size) { - uint64_t& bytes = usage_memory_bytes_[track]; - bytes += size; - TRACE_COUNTER("VulkanDeviceMemoryReport", GetCounterTrack(track), bytes); -} - -void DeviceMemoryReport::SubtractCounterBytes(const std::string& track, uint64_t size) { - uint64_t& bytes = usage_memory_bytes_[track]; - bytes = (bytes >= size) ? (bytes - size) : 0; - TRACE_COUNTER("VulkanDeviceMemoryReport", GetCounterTrack(track), bytes); -} - -void DeviceMemoryReport::UpdateAllocationUnboundCounter(const AllocationKey& key) { - auto allocation_it = memory_allocations_.find(key); - if (allocation_it == memory_allocations_.end()) return; - auto& allocation = allocation_it->second; - - uint64_t bound_size = 0; - std::vector> intervals; - intervals.reserve(allocation.sub_allocations.size()); - for (const auto& suballocation : allocation.sub_allocations) { - // Sub-allocations are clamped to the allocation when bound and by ClampSubAllocationsToAllocation - // once a placeholder's size is known, so a stored binding never extends past total_size. - assert(allocation.total_size == 0 || suballocation.offset + suballocation.size <= allocation.total_size); - // Clamp anyway in release builds: a binding past the end would otherwise make the unsigned - // unbound size below wrap around. - const VkDeviceSize bound = ClampToAllocation(suballocation.offset, suballocation.size, allocation.total_size); - if (bound > 0) { - intervals.emplace_back(suballocation.offset, suballocation.offset + bound); - } - } - if (!intervals.empty()) { - std::sort(intervals.begin(), intervals.end()); - - // Overlapping and adjacent intervals are merged: - // bound_size is calculated as the mathematical union (distinct physical footprint) of all intervals. - VkDeviceSize current_start = intervals[0].first; - VkDeviceSize current_end = intervals[0].second; - for (size_t i = 1; i < intervals.size(); ++i) { - if (intervals[i].first <= current_end) { - // Overlapping or adjacent interval: extend current merged range - current_end = std::max(current_end, intervals[i].second); - } else { - // Disjoint interval: add previous merged interval size and begin next range - bound_size += (current_end - current_start); - current_start = intervals[i].first; - current_end = intervals[i].second; - } - } - bound_size += (current_end - current_start); - } - - // Intervals are clamped to the allocation, so bound_size never exceeds total_size. - uint64_t new_unbound = allocation.total_size - bound_size; - - const char* cluster_name = allocation.is_driver ? "driver" : "unbound_memory"; - if (allocation.is_driver && - (allocation.object_type == VK_OBJECT_TYPE_IMAGE || - allocation.object_type == VK_OBJECT_TYPE_BUFFER)) { +void DeviceMemoryReport::ResolveDriverCluster(MemoryAllocation& allocation) { + assert(allocation.is_driver); + const char* cluster_name = "driver"; + if (allocation.object_type == VK_OBJECT_TYPE_IMAGE || allocation.object_type == VK_OBJECT_TYPE_BUFFER) { auto res_it = resources_.find({allocation.object_type, allocation.object_handle}); - // If the memory object has an associated resource of the matching type, use it as the track name. + // If the memory object has an associated resource of the matching type, use its cluster. if (res_it != resources_.end()) { cluster_name = res_it->second.GetCluster(allocation.mem_flags); } } allocation.cluster_name = cluster_name; - std::string new_unbound_track = GetUsageTrackName(allocation.is_driver, cluster_name); - - // If the unbound memory usage track name or the number of unbound bytes has changed, - // update the global counters by subtracting the old bytes from the old track - // and adding the new bytes to the new track. - if (allocation.unbound_usage_track != new_unbound_track || allocation.applied_unbound_bytes != new_unbound) { - if (allocation.applied_unbound_bytes > 0) { - SubtractCounterBytes(allocation.unbound_usage_track, allocation.applied_unbound_bytes); - } - if (new_unbound > 0) { - AddCounterBytes(new_unbound_track, new_unbound); - } - } - allocation.unbound_usage_track = new_unbound_track; - allocation.applied_unbound_bytes = new_unbound; } -void DeviceMemoryReport::RemoveResourceBinding(const ObjectKey& resource_key, Resource& resource, bool update_unbound_counter) { +void DeviceMemoryReport::RemoveResourceBinding(const ObjectKey& resource_key, Resource& resource) { if (resource.bound_memory == 0) return; const uint64_t memory_handle = resource.bound_memory; @@ -306,11 +217,7 @@ void DeviceMemoryReport::RemoveResourceBinding(const ObjectKey& resource_key, Re if (it->object_type == object_type && it->resource_handle == object_handle) { const VkDeviceSize suballocation_size = it->size; const VkDeviceSize suballocation_offset = it->offset; - SubtractCounterBytes(it->usage_track, suballocation_size); suballocations.erase(it); - if (update_unbound_counter) { - UpdateAllocationUnboundCounter(AllocationKey::App(memory_handle)); - } EmitVulkanMemoryEvent(BindingEvent(Event::OP_DESTROY_BOUND, object_type, object_handle, memory_handle, suballocation_size, suballocation_offset, cluster_name)); @@ -320,7 +227,7 @@ void DeviceMemoryReport::RemoveResourceBinding(const ObjectKey& resource_key, Re } void DeviceMemoryReport::BindResourceMemory(VkObjectType object_type, uint64_t resource_handle, uint64_t memory_handle, VkDeviceSize memory_offset) { - std::lock_guard lock(counter_mutex_); + std::lock_guard lock(state_mutex_); const ObjectKey resource_key = {object_type, resource_handle}; auto res_it = resources_.find(resource_key); if (res_it == resources_.end() || res_it->second.size == 0) return; @@ -337,24 +244,17 @@ void DeviceMemoryReport::BindResourceMemoryLocked(const ObjectKey& resource_key, VkDeviceSize res_size = resource.size; // Clamp the bound resource size to the backing VkDeviceMemory allocation when its size is known, // so drivers returning a worst-case requirement (e.g. for imported AHardwareBuffers) or out-of-range - // bindings do not inflate usage counters or snapshot BIND records beyond the physical allocation (b/578430447). + // bindings do not inflate BIND records beyond the physical allocation (b/578430447). if (allocation.total_size > 0) { res_size = ClampToAllocation(memory_offset, res_size, allocation.total_size); if (res_size == 0) return; } - std::string new_usage_track = GetUsageTrackName(allocation.is_driver, resource.GetCluster(allocation.mem_flags)); - // Suballocations represent individual resources (like buffers or images) that are bound // to specific offset regions within a single large memory allocation. // We add a record here to track this specific resource's footprint within the larger memory block. - allocation.sub_allocations.push_back( - {object_type, resource_handle, memory_offset, res_size, new_usage_track}); + allocation.sub_allocations.push_back({object_type, resource_handle, memory_offset, res_size}); resource.bound_memory = memory_handle; - // Each distinct virtual resource handle adds its clamped size to its specific category track upon binding. - AddCounterBytes(new_usage_track, res_size); - UpdateAllocationUnboundCounter(key); - const char* cluster_name = resource.GetCluster(allocation.mem_flags); EmitVulkanMemoryEvent(BindingEvent(Event::OP_BIND, object_type, resource_handle, memory_handle, res_size, memory_offset, cluster_name)); @@ -381,10 +281,10 @@ void DeviceMemoryReport::ClampSubAllocationsToAllocation(const AllocationKey& ke overhangs.push_back({resource_key, &res_it->second, suballocation.offset}); } } - // Unbind every overhanging resource before re-binding any, so the unbound counter is only - // recomputed once all remaining bindings lie within the allocation. + // Unbind every overhanging resource before re-binding any, so all the DESTROY_BOUND events + // precede the corrective BIND events. for (const auto& overhang : overhangs) { - RemoveResourceBinding(overhang.resource_key, *overhang.resource, /*update_unbound_counter=*/false); + RemoveResourceBinding(overhang.resource_key, *overhang.resource); } for (const auto& overhang : overhangs) { BindResourceMemoryLocked(overhang.resource_key, *overhang.resource, key.id, overhang.offset); @@ -405,7 +305,6 @@ void DeviceMemoryReport::RemoveAllocationTracking(const AllocationKey& key) { auto& allocation = allocation_it->second; for (const auto& suballocation : allocation.sub_allocations) { - SubtractCounterBytes(suballocation.usage_track, suballocation.size); auto resource_iterator = resources_.find({suballocation.object_type, suballocation.resource_handle}); const char* cluster_name = "unbound_memory"; if (resource_iterator != resources_.end()) { @@ -415,39 +314,29 @@ void DeviceMemoryReport::RemoveAllocationTracking(const AllocationKey& key) { EmitVulkanMemoryEvent(BindingEvent(Event::OP_DESTROY_BOUND, suballocation.object_type, suballocation.resource_handle, key.id, suballocation.size, suballocation.offset, cluster_name)); } - if (allocation.applied_unbound_bytes > 0) { - SubtractCounterBytes(allocation.unbound_usage_track, allocation.applied_unbound_bytes); - } memory_allocations_.erase(allocation_it); } void DeviceMemoryReport::OnRecordResourceSize(VkObjectType object_type, uint64_t resource_handle, VkDeviceSize size) { - std::lock_guard lock(counter_mutex_); + std::lock_guard lock(state_mutex_); auto& res = resources_[{object_type, resource_handle}]; res.is_image = (object_type == VK_OBJECT_TYPE_IMAGE); res.size = size; } VkDeviceSize DeviceMemoryReport::GetRecordedResourceSize(VkObjectType object_type, uint64_t resource_handle) { - std::lock_guard lock(counter_mutex_); + std::lock_guard lock(state_mutex_); auto it = resources_.find({object_type, resource_handle}); return it != resources_.end() ? it->second.size : 0; } -uint64_t DeviceMemoryReport::GetUsageCounterBytes(const std::string& track) { - std::lock_guard lock(counter_mutex_); - auto it = usage_memory_bytes_.find(track); - return it != usage_memory_bytes_.end() ? it->second : 0; -} - void DeviceMemoryReport::Reset() { - std::scoped_lock lock(map_mutex_, counter_mutex_); + std::scoped_lock lock(map_mutex_, state_mutex_); vk_instance_map_.clear(); has_callback_map_.clear(); device_memory_properties_map_.clear(); resources_.clear(); memory_allocations_.clear(); - usage_memory_bytes_.clear(); } void DeviceMemoryReport::ReattributeDriverAllocations(uint64_t object_handle, VkObjectType object_type) { @@ -458,7 +347,7 @@ void DeviceMemoryReport::ReattributeDriverAllocations(uint64_t object_handle, Vk continue; } const char* old_cluster_name = allocation.cluster_name; - UpdateAllocationUnboundCounter(key); + ResolveDriverCluster(allocation); if (allocation.total_size == 0 || std::string_view(old_cluster_name) == allocation.cluster_name) { continue; } @@ -472,7 +361,7 @@ void DeviceMemoryReport::ReattributeDriverAllocations(uint64_t object_handle, Vk } void DeviceMemoryReport::OnCreateImage(uint64_t image_handle, VkImageUsageFlags usage) { - std::lock_guard lock(counter_mutex_); + std::lock_guard lock(state_mutex_); auto& res = resources_[{VK_OBJECT_TYPE_IMAGE, image_handle}]; res.is_image = true; res.image_usage = usage; @@ -480,7 +369,7 @@ void DeviceMemoryReport::OnCreateImage(uint64_t image_handle, VkImageUsageFlags } void DeviceMemoryReport::OnCreateBuffer(uint64_t buffer_handle, VkBufferUsageFlags usage, VkDeviceSize size) { - std::lock_guard lock(counter_mutex_); + std::lock_guard lock(state_mutex_); auto& res = resources_[{VK_OBJECT_TYPE_BUFFER, buffer_handle}]; res.is_image = false; res.buffer_usage = usage; @@ -489,7 +378,7 @@ void DeviceMemoryReport::OnCreateBuffer(uint64_t buffer_handle, VkBufferUsageFla } void DeviceMemoryReport::OnDestroyObject(uint64_t object_handle, VkObjectType object_type) { - std::lock_guard lock(counter_mutex_); + std::lock_guard lock(state_mutex_); auto res_it = resources_.find({object_type, object_handle}); if (res_it != resources_.end()) { RemoveResourceBinding(res_it->first, res_it->second); @@ -497,17 +386,8 @@ void DeviceMemoryReport::OnDestroyObject(uint64_t object_handle, VkObjectType ob } } -void DeviceMemoryReport::DumpCurrentCounters() { - std::lock_guard lock(counter_mutex_); - for (const auto& pair : usage_memory_bytes_) { - if (pair.second > 0) { - TRACE_COUNTER("VulkanDeviceMemoryReport", GetCounterTrack(pair.first), pair.second); - } - } -} - void DeviceMemoryReport::ReplayLiveAllocations(uint32_t instance_index) { - std::lock_guard lock(counter_mutex_); + std::lock_guard lock(state_mutex_); // Every replayed event carries the same timestamp, so consumers see the state at session start // as a single point in time. const uint64_t timestamp = GetVulkanMemoryTraceTimeNs(); @@ -536,13 +416,13 @@ void DeviceMemoryReport::ReplayLiveAllocations(uint32_t instance_index) { EmitVulkanMemoryEvent(bind, instance_index); } } - // Live events are held back from the instance until now, and are emitted with counter_mutex_ + // Live events are held back from the instance until now, and are emitted with state_mutex_ // held, so none of them is written before the replay or duplicated by it. MarkVulkanMemoryReplayDone(instance_index); } void DeviceMemoryReport::OnMemoryReportEvent(const VkDeviceMemoryReportCallbackDataEXT* pCallbackData) { - std::lock_guard lock(counter_mutex_); + std::lock_guard lock(state_mutex_); // Per the VK_EXT_device_memory_report specification, VkDeviceMemoryReportFlagsEXT is reserved and always 0. // Explicit application allocations (vkAllocateMemory / memory imports) report VK_OBJECT_TYPE_DEVICE_MEMORY // with objectHandle set to the VkDeviceMemory handle, which we use as the key for compatibility with Bind*Memory. @@ -562,7 +442,7 @@ void DeviceMemoryReport::OnMemoryReportEvent(const VkDeviceMemoryReportCallbackD // An entry with total_size == 0 is a placeholder created ahead of the allocation (e.g. by // SetAllocationMemoryProperties or BindResourceMemory) and must be kept so its mem_flags and // bindings carry over. An entry with total_size > 0 is a live allocation for which no - // FREE/UNIMPORT arrived; retire it (counters and trace) so its bytes do not leak. + // FREE/UNIMPORT arrived; retire it (state and trace) so its bytes do not leak. auto existing_it = memory_allocations_.find(key); if (existing_it != memory_allocations_.end() && existing_it->second.total_size > 0) { const MemoryAllocation& stale = existing_it->second; @@ -580,8 +460,8 @@ void DeviceMemoryReport::OnMemoryReportEvent(const VkDeviceMemoryReportCallbackD allocation.object_type = pCallbackData->objectType; allocation.object_handle = pCallbackData->objectHandle; if (is_driver) { - // Also resolves cluster_name for the CREATE event. App allocations are updated below. - UpdateAllocationUnboundCounter(key); + // Resolves cluster_name for the CREATE event. + ResolveDriverCluster(allocation); } operation = Event::OP_CREATE; memory_type = is_driver ? allocation.cluster_name : "unbound_memory"; @@ -608,17 +488,16 @@ void DeviceMemoryReport::OnMemoryReportEvent(const VkDeviceMemoryReportCallbackD // Bindings recorded against a placeholder before its size was known are clamped after CREATE, // so the corrective DESTROY_BOUND/BIND events follow it in the trace. ClampSubAllocationsToAllocation(key); - UpdateAllocationUnboundCounter(key); } } void DeviceMemoryReport::SetHasMemoryReportCallback(VkDevice device, bool has_callback) { - std::lock_guard lock(counter_mutex_); + std::lock_guard lock(state_mutex_); has_callback_map_[device] = has_callback; } void DeviceMemoryReport::OnAllocateMemory(VkDevice device, VkDeviceMemory memory, VkDeviceSize size, uint32_t memory_type_index, VkMemoryPropertyFlags property_flags) { - std::lock_guard lock(counter_mutex_); + std::lock_guard lock(state_mutex_); uint64_t handle = reinterpret_cast(memory); const AllocationKey key = AllocationKey::App(handle); auto& allocation = memory_allocations_[key]; @@ -630,14 +509,9 @@ void DeviceMemoryReport::OnAllocateMemory(VkDevice device, VkDeviceMemory memory mem_flags = prop_it->second.memoryTypes[memory_type_index].propertyFlags; } } - bool mem_flags_changed = (allocation.mem_flags != mem_flags); allocation.mem_flags = mem_flags; - if (has_callback_map_[device]) { - if (mem_flags_changed && allocation.total_size > 0) { - UpdateAllocationUnboundCounter(key); - } - } else { + if (!has_callback_map_[device]) { allocation.total_size = size; allocation.is_driver = false; allocation.object_type = VK_OBJECT_TYPE_DEVICE_MEMORY; @@ -648,12 +522,11 @@ void DeviceMemoryReport::OnAllocateMemory(VkDevice device, VkDeviceMemory memory // Clamp bindings recorded against a placeholder after CREATE (see OnMemoryReportEvent). ClampSubAllocationsToAllocation(key); - UpdateAllocationUnboundCounter(key); } } void DeviceMemoryReport::OnFreeMemory(VkDevice device, VkDeviceMemory memory) { - std::lock_guard lock(counter_mutex_); + std::lock_guard lock(state_mutex_); if (has_callback_map_[device]) return; uint64_t handle = reinterpret_cast(memory); diff --git a/layersvt/device_memory_report/device_memory_report.h b/layersvt/device_memory_report/device_memory_report.h index 3b94016375..2fd21b6c87 100644 --- a/layersvt/device_memory_report/device_memory_report.h +++ b/layersvt/device_memory_report/device_memory_report.h @@ -56,10 +56,8 @@ const char* GetImageCluster(VkImageUsageFlags usage, VkMemoryPropertyFlags memFl * handled by this layer; VK_LAYER_GOOGLE_DebugMarker publishes them. * * What is emitted: - * Usage counters (vulkan.mem.app.usage. and vulkan.mem.driver.usage.) under the - * "VulkanDeviceMemoryReport" track event category, and one VulkanMemoryEvent TracePacket per - * memory event on the "vulkan.memory_tracker" data source (see VulkanMemoryEventData in - * device_memory_report_perfetto.h for the encoding): + * One VulkanMemoryEvent TracePacket per memory event on the "vulkan.memory_tracker" data source + * (see VulkanMemoryEventData in device_memory_report_perfetto.h for the encoding): * - SOURCE_DEVICE_MEMORY: an application VkDeviceMemory. OP_CREATE on allocate or import, * OP_DESTROY on free or unimport. Cluster "unbound_memory". * - SOURCE_BUFFER / SOURCE_IMAGE: a buffer or image bound into a VkDeviceMemory (device_memory). @@ -74,6 +72,12 @@ const char* GetImageCluster(VkImageUsageFlags usage, VkMemoryPropertyFlags memFl * When a session starts, OP_CREATE is replayed for every live allocation, each followed by OP_BIND * for its live bindings, all with the same timestamp. * + * The layer emits no counters and no object names. Consumers derive per-cluster usage from the + * events: application usage per cluster is the sum of the live bindings' sizes, unbound application + * memory is each live VkDeviceMemory's size minus the size of the union of its live bindings' + * ranges, and driver usage per cluster is the sum of the live driver allocations' sizes. Object + * names come from VK_LAYER_GOOGLE_DebugMarker. + * * This class is a singleton and provides thread-safe access to its state. */ class DeviceMemoryReport { @@ -192,13 +196,6 @@ class DeviceMemoryReport { */ void Reset(); - /** - * @brief Retrieves the current total memory bytes recorded on a usage track (for testing). - * @param track The full usage track name (e.g. "vulkan.mem.app.usage.unbound_memory"). - * @return Number of bytes currently recorded on the track, or 0 if the track has no counter. - */ - uint64_t GetUsageCounterBytes(const std::string& track); - /** * @brief Tracks creation of a Vulkan image and its usage flags. * @param image_handle The 64-bit handle of the Vulkan image. @@ -214,20 +211,13 @@ class DeviceMemoryReport { */ void OnCreateBuffer(uint64_t buffer_handle, VkBufferUsageFlags usage, VkDeviceSize size); - /** - * @brief Writes the current values of the usage counters to Perfetto. - * Invoked when a new track event session starts. Acquires counter_mutex_, - * so it must not be called while that lock is held. - */ - void DumpCurrentCounters(); - /** * @brief Session-start replay for a vulkan.memory_tracker data source instance. * * Emits, to that instance only, OP_CREATE for every live allocation with a known size, each * followed by OP_BIND for each of its live bindings, all with one timestamp taken at the start of * the replay. Live events are held back from the instance until the replay is done. Invoked from - * the data source's OnStart. Acquires counter_mutex_, so it must not be called while that lock + * the data source's OnStart. Acquires state_mutex_, so it must not be called while that lock * is held. * * @param instance_index The data source instance index (StartArgs::internal_instance_index). @@ -256,7 +246,6 @@ class DeviceMemoryReport { uint64_t resource_handle; /**< Handle of the bound Vulkan resource (buffer or image). */ VkDeviceSize offset; /**< Offset in bytes within the physical memory allocation where the resource is bound. */ VkDeviceSize size; /**< Size in bytes of the sub-allocated resource. */ - std::string usage_track; /**< Name of the memory usage trace counter category for this sub-allocation. */ }; /** @@ -273,12 +262,10 @@ class DeviceMemoryReport { */ struct MemoryAllocation { VkDeviceSize total_size = 0; - VkDeviceSize applied_unbound_bytes = 0; bool is_driver = false; VkObjectType object_type = VK_OBJECT_TYPE_UNKNOWN; VkMemoryPropertyFlags mem_flags = 0; std::vector sub_allocations; - std::string unbound_usage_track; uint64_t object_handle = 0; const char* cluster_name = "unbound_memory"; }; @@ -331,7 +318,7 @@ class DeviceMemoryReport { void BindResourceMemory(VkObjectType object_type, uint64_t resource_handle, uint64_t memory_handle, VkDeviceSize memory_offset); /** - * @brief Records a binding of an already-unbound resource; caller must hold counter_mutex_. + * @brief Records a binding of an already-unbound resource; caller must hold state_mutex_. * The bound size is clamped to the allocation when its size is known, and a binding that lies * entirely outside the allocation is dropped. */ @@ -339,21 +326,20 @@ class DeviceMemoryReport { /** * @brief Re-binds sub-allocations recorded against a placeholder (before total_size was known) - * that extend past the allocation, so their sizes, counters, and trace events are clamped to it. + * that extend past the allocation, so their sizes and trace events are clamped to it. */ void ClampSubAllocationsToAllocation(const AllocationKey& key); /** - * @brief Updates unbound memory category counter for a physical memory slab. - * Unbound memory is allocated device memory not currently bound to any active resource (e.g. buffer or image). + * @brief Sets the cluster of a driver allocation: the usage cluster of the VkBuffer / VkImage it + * belongs to when that resource is known, otherwise "driver". */ - void UpdateAllocationUnboundCounter(const AllocationKey& key); + void ResolveDriverCluster(MemoryAllocation& allocation); /** * @brief Removes a sub-allocation of a resource from a physical memory slab if bound. - * @param update_unbound_counter Whether to recompute the slab's unbound counter afterwards. */ - void RemoveResourceBinding(const ObjectKey& resource_key, Resource& resource, bool update_unbound_counter = true); + void RemoveResourceBinding(const ObjectKey& resource_key, Resource& resource); /** * @brief Removes all sub-allocations and tracking for a memory slab being freed. @@ -368,20 +354,10 @@ class DeviceMemoryReport { * known, each matching allocation is moved to its resource cluster. When the cluster changes, * a DESTROY event for the old cluster followed by a CREATE event for the new cluster is * emitted so trace consumers can keep per-cluster accounting consistent. - * Called while counter_mutex_ is held. + * Called while state_mutex_ is held. */ void ReattributeDriverAllocations(uint64_t object_handle, VkObjectType object_type); - /** - * @brief Increments trace counter for a memory track. - */ - void AddCounterBytes(const std::string& track, uint64_t size); - - /** - * @brief Decrements trace counter for a memory track with underflow protection. - */ - void SubtractCounterBytes(const std::string& track, uint64_t size); - /** * @brief Mutex protecting access to the physical device to instance mapping table. */ @@ -393,9 +369,10 @@ class DeviceMemoryReport { std::unordered_map vk_instance_map_; /** - * @brief Mutex protecting access to memory tracking tables and counter states. + * @brief Mutex protecting access to the memory tracking tables. Held while emitting events, so + * that events are emitted in the order of the state changes they describe. */ - std::mutex counter_mutex_; + std::mutex state_mutex_; /** * @brief Maps a Vulkan device handle to a boolean indicating if driver memory report callback is active. @@ -417,9 +394,4 @@ class DeviceMemoryReport { * to its allocation details and sub-allocations. */ std::unordered_map memory_allocations_; - - /** - * @brief Maps a usage track name to its current total memory usage in bytes. - */ - std::unordered_map usage_memory_bytes_; }; diff --git a/layersvt/device_memory_report/device_memory_report_perfetto.cpp b/layersvt/device_memory_report/device_memory_report_perfetto.cpp index 57a09a615b..f279b21c90 100644 --- a/layersvt/device_memory_report/device_memory_report_perfetto.cpp +++ b/layersvt/device_memory_report/device_memory_report_perfetto.cpp @@ -21,12 +21,8 @@ #include #include #include -#include -#include #include -PERFETTO_TRACK_EVENT_STATIC_STORAGE(); - namespace { using perfetto::protos::pbzero::TracePacket; @@ -192,23 +188,6 @@ void WriteVulkanMemoryEvent(VulkanMemoryTrackerDataSource::TraceContext& ctx, co tid->set_int_value(tls.tid); } -class DeviceMemoryReportSessionObserver : public perfetto::TrackEventSessionObserver { -public: - DeviceMemoryReportSessionObserver() { - // Touch the singleton during observer construction so DeviceMemoryReport - // completes construction first and is destroyed after this observer unregisters. - (void)DeviceMemoryReport::Get(); - } - - ~DeviceMemoryReportSessionObserver() override { - perfetto::TrackEvent::RemoveSessionObserver(this); - } - - void OnStart(const perfetto::DataSourceBase::StartArgs&) override { - DeviceMemoryReport::Get().DumpCurrentCounters(); - } -}; - } // namespace void InitializeDeviceMemoryReportPerfetto() { @@ -217,20 +196,15 @@ void InitializeDeviceMemoryReportPerfetto() { // Construct the singleton before registering the data source, so that it is destroyed after // the data source can no longer call into it. (void)DeviceMemoryReport::Get(); - static DeviceMemoryReportSessionObserver session_observer; perfetto::TracingInitArgs args; args.backends = perfetto::kSystemBackend; perfetto::Tracing::Initialize(args); - perfetto::TrackEvent::Register(); - perfetto::TrackEvent::AddSessionObserver(&session_observer); + // A session that is already running when the data source is registered still calls + // OnSetup / OnStart, which replays the live allocations. perfetto::DataSourceDescriptor descriptor; descriptor.set_name(kVulkanMemoryTrackerDataSourceName); VulkanMemoryTrackerDataSource::Register(descriptor); - - if (TRACE_EVENT_CATEGORY_ENABLED("VulkanDeviceMemoryReport")) { - DeviceMemoryReport::Get().DumpCurrentCounters(); - } }); } @@ -276,26 +250,3 @@ void SetVulkanMemoryEventHookForTesting(VulkanMemoryEventHook hook) { EventHook() = std::move(hook); g_event_hook_installed.store(static_cast(EventHook()), std::memory_order_relaxed); } - -perfetto::CounterTrack GetCounterTrack(std::string_view name) { - static std::mutex tracks_mutex; - // Declare track_names first so LIFO static destruction destroys tracks before the strings it views. - static std::unordered_set track_names; - static std::unordered_map tracks; - std::lock_guard lock(tracks_mutex); - - auto it = tracks.find(name); - if (it != tracks.end()) { - return it->second; - } - - // CounterTrack captures ProcessTrack::Current().uuid at construction time; ensure tracing is - // initialized before constructing the first track so it isn't parented to the null/global track. - InitializeDeviceMemoryReportPerfetto(); - - auto name_it = track_names.emplace(name).first; - perfetto::CounterTrack track = perfetto::CounterTrack(perfetto::DynamicString(*name_it)) - .set_unit(perfetto::CounterTrack::Unit::UNIT_SIZE_BYTES); - tracks.emplace(*name_it, track); - return track; -} diff --git a/layersvt/device_memory_report/device_memory_report_perfetto.h b/layersvt/device_memory_report/device_memory_report_perfetto.h index e7be6b40b4..b88bc6e0b7 100644 --- a/layersvt/device_memory_report/device_memory_report_perfetto.h +++ b/layersvt/device_memory_report/device_memory_report_perfetto.h @@ -20,12 +20,6 @@ #include #include #include -#include - -// Define categories used for Perfetto tracing in DeviceMemoryReport layer. -PERFETTO_DEFINE_CATEGORIES( - perfetto::Category("VulkanDeviceMemoryReport").SetDescription("Vulkan Device Memory Report Counters") -); /** * @brief Name of the Perfetto data source the layer emits VulkanMemoryEvent packets on. @@ -118,6 +112,4 @@ void SetVulkanMemoryEventHookForTesting(VulkanMemoryEventHook hook); */ void ClearVulkanMemoryReplayDoneForTesting(uint32_t instance_index); -perfetto::CounterTrack GetCounterTrack(std::string_view name); - #endif // LAYERSVT_DEVICE_MEMORY_REPORT_PERFETTO_H diff --git a/layersvt/test/test_devicememoryreport.cpp b/layersvt/test/test_devicememoryreport.cpp index 22d2cc940a..e3e6e54ca9 100644 --- a/layersvt/test/test_devicememoryreport.cpp +++ b/layersvt/test/test_devicememoryreport.cpp @@ -166,7 +166,7 @@ TEST_F(DeviceMemoryReportTests, ExtensionProperties) { inst_builder.Reset(); } -TEST_F(DeviceMemoryReportTests, EmitEventsAndSubCounters) { +TEST_F(DeviceMemoryReportTests, EmitAllocationEvents) { TEST_DESCRIPTION("Test calling OnMemoryReportEvent with object types and allocating/freeing memory"); InitializeDeviceMemoryReportPerfetto(); @@ -181,12 +181,10 @@ TEST_F(DeviceMemoryReportTests, EmitEventsAndSubCounters) { cb_data.objectHandle = 0x5000; DeviceMemoryReport::MemoryReportCallback(&cb_data, nullptr); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.unbound_memory"), 1024u * 1024u); cb_data.type = VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT; cb_data.size = 512 * 1024; DeviceMemoryReport::MemoryReportCallback(&cb_data, nullptr); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.unbound_memory"), 0u); // VkDeviceMemoryReportFlagsEXT is reserved and always 0; any objectType other than // VK_OBJECT_TYPE_DEVICE_MEMORY identifies driver-internal memory. @@ -195,12 +193,10 @@ TEST_F(DeviceMemoryReportTests, EmitEventsAndSubCounters) { cb_data.objectType = VK_OBJECT_TYPE_BUFFER; cb_data.size = 2048; DeviceMemoryReport::MemoryReportCallback(&cb_data, nullptr); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.driver"), 2048u); // Free the driver allocation cb_data.type = VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT; DeviceMemoryReport::MemoryReportCallback(&cb_data, nullptr); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.driver"), 0u); // Test direct allocate/free fallbacks VkDevice dummy_device = reinterpret_cast(0x1234); @@ -394,6 +390,8 @@ TEST_F(DeviceMemoryReportTests, MemoryAliasingAndOverlap) { uint64_t image_b = 0xD102; uint64_t buffer_c = 0xD103; + // The usage figures below are what consumers derive from the emitted events; the layer itself + // only publishes each binding's range. // Step 1: Allocate a 10,000-byte continuous physical memory slab (VkDeviceMemory). // Initial state: total = 10,000 B, bound = 0 B, unbound_memory = 10,000 B. VkDeviceMemoryReportCallbackDataEXT cb_data = {}; @@ -438,7 +436,7 @@ TEST_F(DeviceMemoryReportTests, MemoryAliasingAndOverlap) { DeviceMemoryReport::Get().OnDestroyObject(image_a, VK_OBJECT_TYPE_IMAGE); // Step 6: Free physical memory slab. - // - All remaining sub-allocations on this slab are cleaned up and unbound counter is reset. + // - All remaining sub-allocations on this slab are removed before the slab itself. cb_data.type = VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT; DeviceMemoryReport::MemoryReportCallback(&cb_data, nullptr); @@ -464,8 +462,6 @@ TEST_F(DeviceMemoryReportTests, BindingsAreClampedToTheirAllocation) { TEST_DESCRIPTION("Only the part of a binding that lies within its VkDeviceMemory allocation counts as bound"); InitializeDeviceMemoryReportPerfetto(); - const std::string unbound_track = "vulkan.mem.app.usage.unbound_memory"; - const std::string mesh_track = "vulkan.mem.app.usage.geometry_mesh"; VkDeviceMemoryReportCallbackDataEXT cb_data = {}; cb_data.sType = VK_STRUCTURE_TYPE_DEVICE_MEMORY_REPORT_CALLBACK_DATA_EXT; @@ -475,13 +471,10 @@ TEST_F(DeviceMemoryReportTests, BindingsAreClampedToTheirAllocation) { cb_data.objectHandle = 0xE001; cb_data.size = 16000; DeviceMemoryReport::MemoryReportCallback(&cb_data, nullptr); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes(unbound_track), 16000u); // [12000, 20000) overhangs the 16,000-byte allocation, so only [12000, 16000) is bound. DeviceMemoryReport::Get().OnCreateBuffer(0xE101, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, 8000); DeviceMemoryReport::Get().OnBindBufferMemory(0xE101, 0xE001, 12000); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes(unbound_track), 12000u); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes(mesh_track), 4000u); auto first_alloc = DeviceMemoryReportTestPeer::FindAllocation(0xE001); ASSERT_TRUE(first_alloc.has_value()); ASSERT_EQ(first_alloc->sub_allocations.size(), 1u); @@ -490,8 +483,6 @@ TEST_F(DeviceMemoryReportTests, BindingsAreClampedToTheirAllocation) { // [20000, 21000) lies entirely outside the allocation, so nothing more is bound. DeviceMemoryReport::Get().OnCreateBuffer(0xE102, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, 1000); DeviceMemoryReport::Get().OnBindBufferMemory(0xE102, 0xE001, 20000); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes(unbound_track), 12000u); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes(mesh_track), 4000u); first_alloc = DeviceMemoryReportTestPeer::FindAllocation(0xE001); ASSERT_TRUE(first_alloc.has_value()); EXPECT_EQ(first_alloc->sub_allocations.size(), 1u); @@ -506,9 +497,7 @@ TEST_F(DeviceMemoryReportTests, BindingsAreClampedToTheirAllocation) { cb_data.size = 10000; DeviceMemoryReport::MemoryReportCallback(&cb_data, nullptr); // 12,000 B from the first allocation plus 10,000 - 2,000 B from the second. - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes(unbound_track), 20000u); // 4,000 B from the first allocation plus 2,000 B from the clamped [8000, 10000) binding; [12000, 13000) is dropped. - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes(mesh_track), 6000u); auto second_alloc = DeviceMemoryReportTestPeer::FindAllocation(0xE002); ASSERT_TRUE(second_alloc.has_value()); ASSERT_EQ(second_alloc->sub_allocations.size(), 1u); @@ -598,90 +587,6 @@ TEST_F(DeviceMemoryReportTests, ClusterClassificationFunctions) { EXPECT_STREQ(GetImageCluster(0, 0), "general_image"); } -TEST_F(DeviceMemoryReportTests, StaticCounterTrackLookup) { - TEST_DESCRIPTION("Test static counter track lookup and dynamic fallback track creation"); - - perfetto::CounterTrack track_staging = GetCounterTrack("vulkan.mem.app.usage.staging_transfer"); - EXPECT_EQ(track_staging.Serialize().counter().unit(), perfetto::protos::gen::CounterDescriptor::UNIT_SIZE_BYTES); - EXPECT_NE(track_staging.uuid, 0u); - - perfetto::CounterTrack track_storage = GetCounterTrack("vulkan.mem.app.usage.compute_storage"); - EXPECT_EQ(track_storage.Serialize().counter().unit(), perfetto::protos::gen::CounterDescriptor::UNIT_SIZE_BYTES); - EXPECT_NE(track_storage.uuid, 0u); - - perfetto::CounterTrack track_unbound = GetCounterTrack("vulkan.mem.driver.usage.driver"); - EXPECT_EQ(track_unbound.Serialize().counter().unit(), perfetto::protos::gen::CounterDescriptor::UNIT_SIZE_BYTES); - EXPECT_NE(track_unbound.uuid, 0u); - - perfetto::CounterTrack dynamic_track = GetCounterTrack("vulkan.mem.app.custom_track"); - EXPECT_EQ(dynamic_track.Serialize().counter().unit(), perfetto::protos::gen::CounterDescriptor::UNIT_SIZE_BYTES); - EXPECT_NE(dynamic_track.uuid, 0u); - - // Re-query the dynamic track to ensure persistent registry returns consistent track - perfetto::CounterTrack dynamic_track_again = GetCounterTrack("vulkan.mem.app.custom_track"); - EXPECT_EQ(dynamic_track.uuid, dynamic_track_again.uuid); - EXPECT_EQ(dynamic_track_again.Serialize().counter().unit(), perfetto::protos::gen::CounterDescriptor::UNIT_SIZE_BYTES); -} - -TEST_F(DeviceMemoryReportTests, CounterTracksAreScopedToProcessTrack) { - TEST_DESCRIPTION( - "Test that counter tracks are parented to the process track, so Perfetto scopes them under the traced " - "application instead of emitting them as global tracks"); - - InitializeDeviceMemoryReportPerfetto(); - - // Perfetto only assigns a process uuid once tracing has been initialized. Tracks created before that (for - // example during static initialization) are permanently parented to the null/global track. - const uint64_t process_uuid = perfetto::ProcessTrack::Current().uuid; - ASSERT_NE(process_uuid, 0u) << "Perfetto tracing was not initialized"; - - const char* kTrackNames[] = { - "vulkan.mem.app.usage.color_render_target", - "vulkan.mem.app.usage.unbound_memory", - "vulkan.mem.driver.usage.static_texture", - "vulkan.mem.driver.usage.driver", - "vulkan.mem.app.usage.brand_new_category", - }; - - for (const char* name : kTrackNames) { - perfetto::CounterTrack track = GetCounterTrack(name); - - EXPECT_NE(track.uuid, 0u) << "track " << name; - EXPECT_EQ(track.parent_uuid, process_uuid) << "track " << name << " is not scoped to the process track"; - - // The uuid must match what Perfetto derives for a process-scoped track of the same name. - EXPECT_EQ(track.uuid, perfetto::CounterTrack(perfetto::DynamicString(name)).uuid) << "track " << name; - - const perfetto::protos::gen::TrackDescriptor descriptor = track.Serialize(); - EXPECT_EQ(descriptor.uuid(), track.uuid) << "track " << name; - EXPECT_EQ(descriptor.parent_uuid(), process_uuid) << "track " << name; - EXPECT_EQ(descriptor.counter().unit(), perfetto::protos::gen::CounterDescriptor::UNIT_SIZE_BYTES) - << "track " << name; - } -} - -TEST_F(DeviceMemoryReportTests, GetCounterTrackInitializesTracing) { - TEST_DESCRIPTION("Test that GetCounterTrack initializes Perfetto itself, so tracks always have process context"); - - // Force fork+execve so the child starts with an uninitialized process_uuid rather than - // inheriting static state already initialized by earlier tests in this binary. - GTEST_FLAG_SET(death_test_style, "threadsafe"); - - EXPECT_EXIT( - { - if (perfetto::ProcessTrack::Current().uuid != 0u) { - exit(1); - } - perfetto::CounterTrack track = GetCounterTrack("vulkan.mem.app.usage.general_image"); - const uint64_t process_uuid = perfetto::ProcessTrack::Current().uuid; - if (process_uuid == 0u || track.parent_uuid != process_uuid) { - exit(2); - } - exit(0); - }, - ::testing::ExitedWithCode(0), ""); -} - TEST_F(DeviceMemoryReportTests, DriverVsAppUnboundMemoryAttribution) { TEST_DESCRIPTION("Test that application unbound memory is not misclassified when object handle matches an existing resource handle"); @@ -705,13 +610,10 @@ TEST_F(DeviceMemoryReportTests, DriverVsAppUnboundMemoryAttribution) { DeviceMemoryReport::MemoryReportCallback(&driver_callback_data, nullptr); // Driver allocation with image handle should be attributed to the color_render_target track - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.color_render_target"), 4096u); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.driver"), 0u); // Clean up driver allocation driver_callback_data.type = VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT; DeviceMemoryReport::MemoryReportCallback(&driver_callback_data, nullptr); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.color_render_target"), 0u); // Case 2: Application allocation where VkDeviceMemory handle happens to have the same integer value as shared_handle VkDeviceMemoryReportCallbackDataEXT application_callback_data = {}; @@ -725,13 +627,10 @@ TEST_F(DeviceMemoryReportTests, DriverVsAppUnboundMemoryAttribution) { DeviceMemoryReport::MemoryReportCallback(&application_callback_data, nullptr); // Application allocation should be classified as unbound_memory, NOT color_render_target - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.unbound_memory"), 8192u); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.color_render_target"), 0u); // Clean up application allocation and resource application_callback_data.type = VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT; DeviceMemoryReport::MemoryReportCallback(&application_callback_data, nullptr); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.unbound_memory"), 0u); DeviceMemoryReport::Get().OnDestroyObject(shared_handle, VK_OBJECT_TYPE_IMAGE); @@ -757,13 +656,9 @@ TEST_F(DeviceMemoryReportTests, DriverVsAppUnboundMemoryAttribution) { DeviceMemoryReport::MemoryReportCallback(&buffer_callback_data, nullptr); // Prior to OnCreateBuffer, the driver allocation is counted under driver - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.driver"), 4096u); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.geometry_mesh"), 0u); // When the buffer is created, the allocation is re-attributed to the geometry_mesh cluster DeviceMemoryReport::Get().OnCreateBuffer(buffer_handle, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, 4096); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.driver"), 0u); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.geometry_mesh"), 4096u); auto reattributed_buf_alloc = DeviceMemoryReportTestPeer::FindDriverAllocation(0x8003); ASSERT_TRUE(reattributed_buf_alloc.has_value()); EXPECT_STREQ(reattributed_buf_alloc->cluster_name, "geometry_mesh"); @@ -777,7 +672,6 @@ TEST_F(DeviceMemoryReportTests, DriverVsAppUnboundMemoryAttribution) { // Clean up buffer_callback_data.type = VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT; DeviceMemoryReport::MemoryReportCallback(&buffer_callback_data, nullptr); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.geometry_mesh"), 0u); DeviceMemoryReport::Get().OnDestroyObject(buffer_handle, VK_OBJECT_TYPE_BUFFER); // Case 4: Driver allocation arrives before OnCreateImage (tests re-attribution) @@ -792,19 +686,14 @@ TEST_F(DeviceMemoryReportTests, DriverVsAppUnboundMemoryAttribution) { image_callback_data.objectHandle = image_handle; DeviceMemoryReport::MemoryReportCallback(&image_callback_data, nullptr); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.driver"), 16384u); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.static_texture"), 0u); DeviceMemoryReport::Get().OnCreateImage(image_handle, VK_IMAGE_USAGE_SAMPLED_BIT); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.driver"), 0u); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.static_texture"), 16384u); auto reattributed_img_alloc = DeviceMemoryReportTestPeer::FindDriverAllocation(0x8004); ASSERT_TRUE(reattributed_img_alloc.has_value()); EXPECT_STREQ(reattributed_img_alloc->cluster_name, "static_texture"); image_callback_data.type = VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT; DeviceMemoryReport::MemoryReportCallback(&image_callback_data, nullptr); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.static_texture"), 0u); DeviceMemoryReport::Get().OnDestroyObject(image_handle, VK_OBJECT_TYPE_IMAGE); // Case 5: Duplicate ALLOCATE/IMPORT on an existing active key replaces tracking cleanly without leaking bytes @@ -817,7 +706,6 @@ TEST_F(DeviceMemoryReportTests, DriverVsAppUnboundMemoryAttribution) { dup_cb.objectType = VK_OBJECT_TYPE_COMMAND_POOL; dup_cb.objectHandle = 0xF004; DeviceMemoryReport::MemoryReportCallback(&dup_cb, nullptr); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.driver"), 4096u); TakeEvents(); dup_cb.size = 2048; @@ -827,11 +715,9 @@ TEST_F(DeviceMemoryReportTests, DriverVsAppUnboundMemoryAttribution) { {Event::SOURCE_DRIVER, Event::OP_DESTROY, 0x8005, 0xF004, 4096, "driver", 0, VK_OBJECT_TYPE_COMMAND_POOL}, {Event::SOURCE_DRIVER, Event::OP_CREATE, 0x8005, 0xF004, 2048, "driver", 0, VK_OBJECT_TYPE_COMMAND_POOL}, }); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.driver"), 2048u); dup_cb.type = VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT; DeviceMemoryReport::MemoryReportCallback(&dup_cb, nullptr); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.driver"), 0u); // Case 6: Driver-internal allocation with VK_OBJECT_TYPE_UNKNOWN and objectHandle = 0 VkDeviceMemoryReportCallbackDataEXT unknown_cb = {}; @@ -843,7 +729,6 @@ TEST_F(DeviceMemoryReportTests, DriverVsAppUnboundMemoryAttribution) { unknown_cb.objectType = VK_OBJECT_TYPE_UNKNOWN; unknown_cb.objectHandle = 0; DeviceMemoryReport::MemoryReportCallback(&unknown_cb, nullptr); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.driver"), 1024u); auto unknown_alloc = DeviceMemoryReportTestPeer::FindDriverAllocation(0x8006); ASSERT_TRUE(unknown_alloc.has_value()); EXPECT_TRUE(unknown_alloc->is_driver); @@ -852,12 +737,12 @@ TEST_F(DeviceMemoryReportTests, DriverVsAppUnboundMemoryAttribution) { unknown_cb.type = VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT; DeviceMemoryReport::MemoryReportCallback(&unknown_cb, nullptr); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.driver"), 0u); // Case 7: Driver VK_OBJECT_TYPE_IMAGE allocation whose objectHandle collides with an existing VkBuffer // before OnCreateImage must not inherit the buffer's usage cluster. uint64_t cross_type_handle = 0xF005; DeviceMemoryReport::Get().OnCreateBuffer(cross_type_handle, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, 4096); + TakeEvents(); VkDeviceMemoryReportCallbackDataEXT cross_type_cb = {}; cross_type_cb.sType = VK_STRUCTURE_TYPE_DEVICE_MEMORY_REPORT_CALLBACK_DATA_EXT; cross_type_cb.flags = 0; @@ -867,12 +752,13 @@ TEST_F(DeviceMemoryReportTests, DriverVsAppUnboundMemoryAttribution) { cross_type_cb.objectType = VK_OBJECT_TYPE_IMAGE; cross_type_cb.objectHandle = cross_type_handle; DeviceMemoryReport::MemoryReportCallback(&cross_type_cb, nullptr); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.driver"), 2048u); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.geometry_mesh"), 0u); cross_type_cb.type = VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT; DeviceMemoryReport::MemoryReportCallback(&cross_type_cb, nullptr); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.driver"), 0u); + std::vector cross_type_events = TakeEvents(); + ASSERT_EQ(cross_type_events.size(), 2u); + EXPECT_STREQ(cross_type_events[0].cluster, "driver"); + EXPECT_STREQ(cross_type_events[1].cluster, "driver"); DeviceMemoryReport::Get().OnDestroyObject(cross_type_handle, VK_OBJECT_TYPE_BUFFER); } @@ -896,8 +782,6 @@ TEST_F(DeviceMemoryReportTests, DriverMemoryObjectIdCollidingWithAppHandle) { DeviceMemoryReport::Get().OnCreateBuffer(buffer_handle, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, 4096); DeviceMemoryReport::Get().OnBindBufferMemory(buffer_handle, colliding_value, 0); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.geometry_mesh"), 4096u); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.unbound_memory"), 4096u); // Driver allocation whose memoryObjectId equals the live VkDeviceMemory handle. VkDeviceMemoryReportCallbackDataEXT driver_cb = {}; @@ -909,9 +793,6 @@ TEST_F(DeviceMemoryReportTests, DriverMemoryObjectIdCollidingWithAppHandle) { driver_cb.objectHandle = 0xF103; DeviceMemoryReport::MemoryReportCallback(&driver_cb, nullptr); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.driver"), 1024u); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.geometry_mesh"), 4096u); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.unbound_memory"), 4096u); auto app_alloc = DeviceMemoryReportTestPeer::FindAllocation(colliding_value); ASSERT_TRUE(app_alloc.has_value()); EXPECT_FALSE(app_alloc->is_driver); @@ -926,17 +807,22 @@ TEST_F(DeviceMemoryReportTests, DriverMemoryObjectIdCollidingWithAppHandle) { // Freeing the driver allocation leaves the application allocation intact. driver_cb.type = VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT; DeviceMemoryReport::MemoryReportCallback(&driver_cb, nullptr); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.driver.usage.driver"), 0u); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.geometry_mesh"), 4096u); EXPECT_TRUE(DeviceMemoryReportTestPeer::FindAllocation(colliding_value).has_value()); EXPECT_FALSE(DeviceMemoryReportTestPeer::FindDriverAllocation(colliding_value).has_value()); - // Freeing the application allocation releases its bindings and unbound bytes. + // Freeing the application allocation releases its bindings. app_cb.type = VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT; DeviceMemoryReport::MemoryReportCallback(&app_cb, nullptr); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.geometry_mesh"), 0u); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.unbound_memory"), 0u); DeviceMemoryReport::Get().OnDestroyObject(buffer_handle, VK_OBJECT_TYPE_BUFFER); + + ExpectEvents(TakeEvents(), { + {Event::SOURCE_DEVICE_MEMORY, Event::OP_CREATE, colliding_value, colliding_value, 8192, "unbound_memory"}, + {Event::SOURCE_BUFFER, Event::OP_BIND, colliding_value, buffer_handle, 4096, "geometry_mesh"}, + {Event::SOURCE_DRIVER, Event::OP_CREATE, colliding_value, 0xF103, 1024, "driver", 0, VK_OBJECT_TYPE_COMMAND_POOL}, + {Event::SOURCE_DRIVER, Event::OP_DESTROY, colliding_value, 0xF103, 1024, "driver", 0, VK_OBJECT_TYPE_COMMAND_POOL}, + {Event::SOURCE_BUFFER, Event::OP_DESTROY_BOUND, colliding_value, buffer_handle, 4096, "geometry_mesh"}, + {Event::SOURCE_DEVICE_MEMORY, Event::OP_DESTROY, colliding_value, colliding_value, 8192, "unbound_memory"}, + }); } TEST_F(DeviceMemoryReportTests, BufferAndImageWithCollidingHandlesAreTrackedIndependently) { @@ -974,9 +860,6 @@ TEST_F(DeviceMemoryReportTests, BufferAndImageWithCollidingHandlesAreTrackedInde // Binding both into the same block keeps two distinct suballocations. DeviceMemoryReport::Get().OnBindBufferMemory(shared_handle, memory_handle, 0); DeviceMemoryReport::Get().OnBindImageMemory(shared_handle, memory_handle, 4096); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.geometry_mesh"), 4096u); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.static_texture"), 8192u); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.unbound_memory"), 4096u); auto allocation = DeviceMemoryReportTestPeer::FindAllocation(memory_handle); ASSERT_TRUE(allocation.has_value()); ASSERT_EQ(allocation->sub_allocations.size(), 2u); @@ -985,9 +868,6 @@ TEST_F(DeviceMemoryReportTests, BufferAndImageWithCollidingHandlesAreTrackedInde // Destroying the buffer unbinds only the buffer. DeviceMemoryReport::Get().OnDestroyObject(shared_handle, VK_OBJECT_TYPE_BUFFER); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.geometry_mesh"), 0u); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.static_texture"), 8192u); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.unbound_memory"), 8192u); EXPECT_FALSE(DeviceMemoryReportTestPeer::FindResource(VK_OBJECT_TYPE_BUFFER, shared_handle).has_value()); EXPECT_TRUE(DeviceMemoryReportTestPeer::FindResource(VK_OBJECT_TYPE_IMAGE, shared_handle).has_value()); allocation = DeviceMemoryReportTestPeer::FindAllocation(memory_handle); @@ -997,13 +877,20 @@ TEST_F(DeviceMemoryReportTests, BufferAndImageWithCollidingHandlesAreTrackedInde app_cb.type = VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT; DeviceMemoryReport::MemoryReportCallback(&app_cb, nullptr); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.static_texture"), 0u); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.unbound_memory"), 0u); DeviceMemoryReport::Get().OnDestroyObject(shared_handle, VK_OBJECT_TYPE_IMAGE); + + ExpectEvents(TakeEvents(), { + {Event::SOURCE_DEVICE_MEMORY, Event::OP_CREATE, memory_handle, memory_handle, 16384, "unbound_memory"}, + {Event::SOURCE_BUFFER, Event::OP_BIND, memory_handle, shared_handle, 4096, "geometry_mesh"}, + {Event::SOURCE_IMAGE, Event::OP_BIND, memory_handle, shared_handle, 8192, "static_texture", 4096}, + {Event::SOURCE_BUFFER, Event::OP_DESTROY_BOUND, memory_handle, shared_handle, 4096, "geometry_mesh"}, + {Event::SOURCE_IMAGE, Event::OP_DESTROY_BOUND, memory_handle, shared_handle, 8192, "static_texture", 4096}, + {Event::SOURCE_DEVICE_MEMORY, Event::OP_DESTROY, memory_handle, memory_handle, 16384, "unbound_memory"}, + }); } TEST_F(DeviceMemoryReportTests, MemoryReportSnapshotDump) { - TEST_DESCRIPTION("Test the counter dump and the replay of live allocations and bindings when a trace session begins"); + TEST_DESCRIPTION("Test the replay of live allocations and bindings when a trace session begins"); InitializeDeviceMemoryReportPerfetto(); @@ -1034,7 +921,6 @@ TEST_F(DeviceMemoryReportTests, MemoryReportSnapshotDump) { ASSERT_TRUE(allocation.has_value()); EXPECT_EQ(allocation->total_size, 16384u); EXPECT_EQ(allocation->sub_allocations.size(), 2u); - EXPECT_EQ(allocation->applied_unbound_bytes, 8192u); // A driver allocation is replayed under its resolved cluster, and a placeholder allocation whose // size is not known yet is not replayed. @@ -1047,8 +933,7 @@ TEST_F(DeviceMemoryReportTests, MemoryReportSnapshotDump) { DeviceMemoryReport::Get().SetAllocationMemoryProperties(0xE003, 0); TakeEvents(); - // Test dumping the current snapshot of counters, allocations, and suballocations - DeviceMemoryReport::Get().DumpCurrentCounters(); + // Replay the live allocations and bindings, as at the start of a session. DeviceMemoryReport::Get().ReplayLiveAllocations(0); ClearVulkanMemoryReplayDoneForTesting(0); @@ -1075,7 +960,6 @@ TEST_F(DeviceMemoryReportTests, MemoryReportSnapshotDump) { ASSERT_TRUE(post_dump_allocation.has_value()); EXPECT_EQ(post_dump_allocation->total_size, 16384u); EXPECT_EQ(post_dump_allocation->sub_allocations.size(), 2u); - EXPECT_EQ(post_dump_allocation->applied_unbound_bytes, 8192u); // Verify cleanup callback_data.type = VK_DEVICE_MEMORY_REPORT_EVENT_TYPE_FREE_EXT; diff --git a/layersvt/test/test_devicememoryreport_dispatch.cpp b/layersvt/test/test_devicememoryreport_dispatch.cpp index 1f000f21b7..e33845a82f 100644 --- a/layersvt/test/test_devicememoryreport_dispatch.cpp +++ b/layersvt/test/test_devicememoryreport_dispatch.cpp @@ -276,6 +276,11 @@ TEST_F(DeviceMemoryReportDispatchTests, CreateImageSkipsMemoryRequirementsForAnd // Once the AHardwareBuffer memory is bound, the post-bind size is queried and clamped to the // imported VkDeviceMemory allocation size. + std::vector events; + SetVulkanMemoryEventHookForTesting([&events](const VulkanMemoryEventData& event) { + if (event.operation == perfetto::protos::pbzero::VulkanMemoryEvent::OP_BIND) events.push_back(event); + }); + VkMemoryAllocateInfo alloc_info = {}; alloc_info.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc_info.allocationSize = 10592256; @@ -290,8 +295,10 @@ TEST_F(DeviceMemoryReportDispatchTests, CreateImageSkipsMemoryRequirementsForAnd EXPECT_EQ(vkBindImageMemory2(device.handle(), 1, &bind_info), VK_SUCCESS); EXPECT_EQ(g_image_requirements_queries, 1); EXPECT_TRUE(g_image_bound_at_last_requirements_query); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.color_render_target"), 10592256u); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.unbound_memory"), 0u); + ASSERT_EQ(events.size(), 1u); + EXPECT_EQ(events[0].object_handle, AsObjectHandle(image)); + EXPECT_EQ(events[0].memory_size, 10592256u); + EXPECT_STREQ(events[0].cluster, "color_render_target"); // Also verify the Vulkan 1.0 vkBindImageMemory path queries requirements only after binding. VkImage image_v1 = VK_NULL_HANDLE; @@ -304,8 +311,10 @@ TEST_F(DeviceMemoryReportDispatchTests, CreateImageSkipsMemoryRequirementsForAnd EXPECT_EQ(vkBindImageMemory(device.handle(), image_v1, memory_v1, 0), VK_SUCCESS); EXPECT_EQ(g_image_requirements_queries, 2); EXPECT_TRUE(g_image_bound_at_last_requirements_query); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.color_render_target"), 2u * 10592256u); - EXPECT_EQ(DeviceMemoryReport::Get().GetUsageCounterBytes("vulkan.mem.app.usage.unbound_memory"), 0u); + ASSERT_EQ(events.size(), 2u); + EXPECT_EQ(events[1].object_handle, AsObjectHandle(image_v1)); + EXPECT_EQ(events[1].memory_size, 10592256u); + SetVulkanMemoryEventHookForTesting({}); vkDestroyImage(device.handle(), image_v1, nullptr); vkFreeMemory(device.handle(), memory_v1, nullptr); diff --git a/layersvt/test/test_devicememoryreport_peer.h b/layersvt/test/test_devicememoryreport_peer.h index 585d484762..a20d31dba2 100644 --- a/layersvt/test/test_devicememoryreport_peer.h +++ b/layersvt/test/test_devicememoryreport_peer.h @@ -39,7 +39,7 @@ class DeviceMemoryReportTestPeer { static std::optional FindResource(VkObjectType object_type, uint64_t resource_handle) { auto& report = DeviceMemoryReport::Get(); - std::lock_guard lock(report.counter_mutex_); + std::lock_guard lock(report.state_mutex_); auto it = report.resources_.find({object_type, resource_handle}); if (it == report.resources_.end()) { return std::nullopt; @@ -50,7 +50,7 @@ class DeviceMemoryReportTestPeer { private: static std::optional FindAllocationByKey(const DeviceMemoryReport::AllocationKey& key) { auto& report = DeviceMemoryReport::Get(); - std::lock_guard lock(report.counter_mutex_); + std::lock_guard lock(report.state_mutex_); auto it = report.memory_allocations_.find(key); if (it == report.memory_allocations_.end()) { return std::nullopt; From a73a731ddcd6f90390d869cd76b18694e6844b10 Mon Sep 17 00:00:00 2001 From: jimblackler Date: Sun, 29 Nov 2026 13:32:50 +0000 Subject: [PATCH 4/4] device_memory_report: Replay placeholder bindings at session start Bindings recorded against a placeholder allocation (before its VkDeviceMemory size is known) emit OP_BIND live, and derived usage series rely on those bindings being present at session start. ReplayLiveAllocations skipped the entire entry when total_size == 0, dropping those live bindings. Keep skipping OP_CREATE for size-0 placeholders while still replaying their OP_BIND suballocations. Bug: b/564416621 --- .../device_memory_report.cpp | 18 ++++++++++-------- layersvt/test/test_devicememoryreport.cpp | 16 ++++++++++++++++ 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/layersvt/device_memory_report/device_memory_report.cpp b/layersvt/device_memory_report/device_memory_report.cpp index f8e42ac713..5b10e50022 100644 --- a/layersvt/device_memory_report/device_memory_report.cpp +++ b/layersvt/device_memory_report/device_memory_report.cpp @@ -394,14 +394,16 @@ void DeviceMemoryReport::ReplayLiveAllocations(uint32_t instance_index) { for (const auto& pair : memory_allocations_) { uint64_t memory_handle = pair.first.id; const auto& allocation = pair.second; - if (allocation.total_size == 0) continue; - - const char* cluster_name = allocation.is_driver ? allocation.cluster_name : "unbound_memory"; - VulkanMemoryEventData create = - AllocationEvent(Event::OP_CREATE, allocation.is_driver, memory_handle, allocation.total_size, - allocation.object_type, allocation.object_handle, cluster_name); - create.timestamp = timestamp; - EmitVulkanMemoryEvent(create, instance_index); + // A placeholder (size not known yet) has no CREATE, but bindings recorded against it were + // published when bound, so they are replayed too. + if (allocation.total_size > 0) { + const char* cluster_name = allocation.is_driver ? allocation.cluster_name : "unbound_memory"; + VulkanMemoryEventData create = + AllocationEvent(Event::OP_CREATE, allocation.is_driver, memory_handle, allocation.total_size, + allocation.object_type, allocation.object_handle, cluster_name); + create.timestamp = timestamp; + EmitVulkanMemoryEvent(create, instance_index); + } for (const auto& suballocation : allocation.sub_allocations) { auto resource_iterator = resources_.find({suballocation.object_type, suballocation.resource_handle}); diff --git a/layersvt/test/test_devicememoryreport.cpp b/layersvt/test/test_devicememoryreport.cpp index e3e6e54ca9..31dde0f184 100644 --- a/layersvt/test/test_devicememoryreport.cpp +++ b/layersvt/test/test_devicememoryreport.cpp @@ -1235,3 +1235,19 @@ TEST_F(DeviceMemoryReportTests, VulkanMemoryTrackerLiveEventsWaitForReplay) { EXPECT_EQ(replayed, expected_replay); EXPECT_EQ(creates[3], std::make_pair(uint64_t{0xB503}, uint64_t{16384})); } + +TEST_F(DeviceMemoryReportTests, PlaceholderBindingsAreReplayed) { + TEST_DESCRIPTION("Test that bindings on a size-0 placeholder allocation are replayed at session start"); + + const uint64_t memory_handle = 0xD001; + const uint64_t buffer_handle = 0xD101; + DeviceMemoryReport::Get().OnCreateBuffer(buffer_handle, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, 8192); + DeviceMemoryReport::Get().OnBindBufferMemory(buffer_handle, memory_handle, 0); + TakeEvents(); + + DeviceMemoryReport::Get().ReplayLiveAllocations(0); + ClearVulkanMemoryReplayDoneForTesting(0); + ExpectEvents(TakeEvents(), { + {Event::SOURCE_BUFFER, Event::OP_BIND, memory_handle, buffer_handle, 8192, "geometry_mesh"}, + }); +}