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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 0 additions & 10 deletions layersvt/device_memory_report/VkLayer_DeviceMemoryReport.json.in
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
]
}
Expand Down
535 changes: 117 additions & 418 deletions layersvt/device_memory_report/device_memory_report.cpp

Large diffs are not rendered by default.

149 changes: 49 additions & 100 deletions layersvt/device_memory_report/device_memory_report.h
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand All @@ -52,17 +52,31 @@ 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.<category>)
* - Instant events under the "VulkanDeviceMemoryReport" category ("VulkanMemoryAllocation" and
* "VulkanObjectName")
* What is emitted:
* 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.
*
* 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.
*/
Expand Down Expand Up @@ -182,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.
Expand All @@ -205,51 +212,29 @@ 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_,
* so it must not be called while that lock is held.
* @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 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).
*/
void DumpCurrentCountersAndAllocations();
void ReplayLiveAllocations(uint32_t instance_index);

/**
* @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;

Expand All @@ -261,15 +246,14 @@ 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. */
};

/**
* @brief Identifies a Vulkan object as (object_type, handle).
*
* 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<VkObjectType, uint64_t>;

Expand All @@ -278,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<SubAllocation> sub_allocations;
std::string unbound_usage_track;
uint64_t object_handle = 0;
const char* cluster_name = "unbound_memory";
};
Expand Down Expand Up @@ -336,29 +318,28 @@ 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.
*/
void BindResourceMemoryLocked(const ObjectKey& resource_key, Resource& resource, uint64_t memory_handle, VkDeviceSize memory_offset);

/**
* @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.
Expand All @@ -373,25 +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 Republishes every known object name. Called while counter_mutex_ is held.
*/
void EmitAllDebugObjectNames();

/**
* @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.
*/
Expand All @@ -403,9 +369,10 @@ class DeviceMemoryReport {
std::unordered_map<VkPhysicalDevice, VkInstance> 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.
Expand All @@ -427,22 +394,4 @@ class DeviceMemoryReport {
* to its allocation details and sub-allocations.
*/
std::unordered_map<AllocationKey, MemoryAllocation, AllocationKeyHash> memory_allocations_;

/**
* @brief Maps a usage track name to its current total memory usage in bytes.
*/
std::unordered_map<std::string, uint64_t> 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<ObjectKey, std::string> debug_object_names_;
};
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,6 @@ static PFN_vkVoidFunction devmemreport_known_instance_functions(const char* pNam
if (strcmp(pName, "vkEnumeratePhysicalDevices") == 0) return reinterpret_cast<PFN_vkVoidFunction>(vkEnumeratePhysicalDevices);
if (strcmp(pName, "vkEnumeratePhysicalDeviceGroups") == 0) return reinterpret_cast<PFN_vkVoidFunction>(vkEnumeratePhysicalDeviceGroups);
if (strcmp(pName, "vkEnumerateDeviceExtensionProperties") == 0) return reinterpret_cast<PFN_vkVoidFunction>(vkEnumerateDeviceExtensionProperties);
if (strcmp(pName, "vkCreateDebugUtilsMessengerEXT") == 0) return reinterpret_cast<PFN_vkVoidFunction>(vkCreateDebugUtilsMessengerEXT);
if (strcmp(pName, "vkDestroyDebugUtilsMessengerEXT") == 0) return reinterpret_cast<PFN_vkVoidFunction>(vkDestroyDebugUtilsMessengerEXT);
if (strcmp(pName, "vkSubmitDebugUtilsMessageEXT") == 0) return reinterpret_cast<PFN_vkVoidFunction>(vkSubmitDebugUtilsMessageEXT);
return nullptr;
}

Expand All @@ -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<PFN_vkVoidFunction>(vkSetDebugUtilsObjectNameEXT);
if (strcmp(pName, "vkSetDebugUtilsObjectTagEXT") == 0) return reinterpret_cast<PFN_vkVoidFunction>(vkSetDebugUtilsObjectTagEXT);
if (strcmp(pName, "vkCmdBeginDebugUtilsLabelEXT") == 0) return reinterpret_cast<PFN_vkVoidFunction>(vkCmdBeginDebugUtilsLabelEXT);
if (strcmp(pName, "vkCmdEndDebugUtilsLabelEXT") == 0) return reinterpret_cast<PFN_vkVoidFunction>(vkCmdEndDebugUtilsLabelEXT);
if (strcmp(pName, "vkCmdInsertDebugUtilsLabelEXT") == 0) return reinterpret_cast<PFN_vkVoidFunction>(vkCmdInsertDebugUtilsLabelEXT);
if (strcmp(pName, "vkQueueBeginDebugUtilsLabelEXT") == 0) return reinterpret_cast<PFN_vkVoidFunction>(vkQueueBeginDebugUtilsLabelEXT);
if (strcmp(pName, "vkQueueEndDebugUtilsLabelEXT") == 0) return reinterpret_cast<PFN_vkVoidFunction>(vkQueueEndDebugUtilsLabelEXT);
if (strcmp(pName, "vkQueueInsertDebugUtilsLabelEXT") == 0) return reinterpret_cast<PFN_vkVoidFunction>(vkQueueInsertDebugUtilsLabelEXT);

// VK_EXT_debug_marker
if (strcmp(pName, "vkDebugMarkerSetObjectNameEXT") == 0) return reinterpret_cast<PFN_vkVoidFunction>(vkDebugMarkerSetObjectNameEXT);
if (strcmp(pName, "vkDebugMarkerSetObjectTagEXT") == 0) return reinterpret_cast<PFN_vkVoidFunction>(vkDebugMarkerSetObjectTagEXT);
if (strcmp(pName, "vkCmdDebugMarkerBeginEXT") == 0) return reinterpret_cast<PFN_vkVoidFunction>(vkCmdDebugMarkerBeginEXT);
if (strcmp(pName, "vkCmdDebugMarkerEndEXT") == 0) return reinterpret_cast<PFN_vkVoidFunction>(vkCmdDebugMarkerEndEXT);
if (strcmp(pName, "vkCmdDebugMarkerInsertEXT") == 0) return reinterpret_cast<PFN_vkVoidFunction>(vkCmdDebugMarkerInsertEXT);
return nullptr;
}

static PFN_vkVoidFunction devmemreport_known_device_extension_functions(const char* pName) {
if (strcmp(pName, "vkBindBufferMemory2KHR") == 0) return reinterpret_cast<PFN_vkVoidFunction>(vkBindBufferMemory2KHR);
if (strcmp(pName, "vkBindImageMemory2KHR") == 0) return reinterpret_cast<PFN_vkVoidFunction>(vkBindImageMemory2KHR);
Expand Down Expand Up @@ -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;
Expand All @@ -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;
}
Expand Down
Loading
Loading