From 03b3702b68f493c4f3995517932264a78b6aa5a1 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Thu, 19 Nov 2026 14:17:55 -0300 Subject: [PATCH 1/4] asahi: create a BO at a GPU address the caller chose agx_bo_create_at() creates a BO whose only GPU mapping is a VA the caller allocated, for example one in the capture/replay region at a captured address. The BO is never cached, so the address is free again as soon as the BO is. bo_alloc takes the VA over and frees it on failure, which also plugs the VA the virtio backend leaked when vdrm_bo_create() failed. Signed-off-by: Jonathan Goyvaerts --- src/asahi/lib/agx_bo.c | 47 +++++++++++++++------ src/asahi/lib/agx_bo.h | 3 ++ src/asahi/lib/agx_device.c | 5 ++- src/asahi/lib/agx_device.h | 4 +- src/asahi/lib/agx_device_virtio.c | 6 ++- src/asahi/lib/tests/test-agx-bo-cache.c | 3 +- src/asahi/vulkan/tests/test-hk-memory-oom.c | 5 ++- 7 files changed, 52 insertions(+), 21 deletions(-) diff --git a/src/asahi/lib/agx_bo.c b/src/asahi/lib/agx_bo.c index c92b280929ff..094468c9fd59 100644 --- a/src/asahi/lib/agx_bo.c +++ b/src/asahi/lib/agx_bo.c @@ -738,6 +738,37 @@ agx_bo_ensure_ro_shadow(struct agx_device *dev, struct agx_bo *bo) return ret; } +/* Hands out a freshly allocated or reused BO. */ +static struct agx_bo * +agx_bo_publish(struct agx_device *dev, struct agx_bo *bo, const char *label) +{ + bo->label = label; + p_atomic_set(&bo->refcnt, 1); + + if (dev->debug & + (AGX_DBG_TRACE | AGX_DBG_ASYNCTRACE)) { + agx_bo_map(bo); + agxdecode_track_alloc(dev->agxdecode, bo); + } + + agx_bo_dump_all_periodic(dev); + return bo; +} + +/* A BO whose only GPU address is `va`, which it takes over, also when it + * fails. Never cached: the address is free again once the BO is. */ +struct agx_bo * +agx_bo_create_at(struct agx_device *dev, size_t size, enum agx_bo_flags flags, + struct agx_va *va, const char *label) +{ + assert(size > 0 && va != NULL); + flags |= AGX_BO_NO_CACHE; + + struct agx_bo *bo = dev->ops.bo_alloc(dev, ALIGN_POT(size, AIL_PAGESIZE), + AIL_PAGESIZE, flags, va); + return bo ? agx_bo_publish(dev, bo, label) : NULL; +} + struct agx_bo * agx_bo_create_checked(struct agx_device *dev, size_t size, unsigned align, enum agx_bo_flags flags, const char *label, @@ -786,14 +817,14 @@ agx_bo_create_checked(struct agx_device *dev, size_t size, unsigned align, * flush the cache to make space for the new allocation. */ if (!bo) - bo = dev->ops.bo_alloc(dev, size, align, flags); + bo = dev->ops.bo_alloc(dev, size, align, flags, NULL); if (!bo) { bo = agx_bo_cache_fetch(dev, size, align, flags, false); reused = bo != NULL; } if (!bo) { agx_bo_cache_evict_all(dev); - bo = dev->ops.bo_alloc(dev, size, align, flags); + bo = dev->ops.bo_alloc(dev, size, align, flags, NULL); } if (!bo) { @@ -839,17 +870,7 @@ agx_bo_create_checked(struct agx_device *dev, size_t size, unsigned align, memset(map, 0, bo->size); } - bo->label = label; - p_atomic_set(&bo->refcnt, 1); - - if (dev->debug & - (AGX_DBG_TRACE | AGX_DBG_ASYNCTRACE)) { - agx_bo_map(bo); - agxdecode_track_alloc(dev->agxdecode, bo); - } - - agx_bo_dump_all_periodic(dev); - return bo; + return agx_bo_publish(dev, bo, label); } struct agx_bo * diff --git a/src/asahi/lib/agx_bo.h b/src/asahi/lib/agx_bo.h index e8f4e8104b8e..16e1a4d61fc4 100644 --- a/src/asahi/lib/agx_bo.h +++ b/src/asahi/lib/agx_bo.h @@ -184,6 +184,9 @@ struct agx_bo *agx_bo_create_checked(struct agx_device *dev, size_t size, struct agx_bo *agx_bo_create(struct agx_device *dev, size_t size, unsigned align, enum agx_bo_flags flags, const char *label); +struct agx_bo *agx_bo_create_at(struct agx_device *dev, size_t size, + enum agx_bo_flags flags, struct agx_va *va, + const char *label); int agx_bo_ensure_ro_shadow(struct agx_device *dev, struct agx_bo *bo); diff --git a/src/asahi/lib/agx_device.c b/src/asahi/lib/agx_device.c index 40d39b46c3c8..1b8dd31337ea 100644 --- a/src/asahi/lib/agx_device.c +++ b/src/asahi/lib/agx_device.c @@ -409,7 +409,7 @@ agx_bind_timestamps(struct agx_device *dev, struct agx_bo *bo, uint32_t *handle) static struct agx_bo * agx_bo_alloc(struct agx_device *dev, size_t size, size_t align, - enum agx_bo_flags flags) + enum agx_bo_flags flags, struct agx_va *va) { struct agx_bo *bo; unsigned handle = 0; @@ -430,6 +430,7 @@ agx_bo_alloc(struct agx_device *dev, size_t size, size_t align, int ret = drmIoctl(dev->fd, DRM_IOCTL_ASAHI_GEM_CREATE, &gem_create); if (ret) { fprintf(stderr, "DRM_IOCTL_ASAHI_GEM_CREATE failed: %m\n"); + agx_va_free(dev, va, false); return NULL; } @@ -451,7 +452,7 @@ agx_bo_alloc(struct agx_device *dev, size_t size, size_t align, bo->prime_fd = -1; enum agx_va_flags va_flags = flags & AGX_BO_LOW_VA ? AGX_VA_USC : 0; - bo->va = agx_va_alloc(dev, size, bo->align, va_flags, 0); + bo->va = va ?: agx_va_alloc(dev, size, bo->align, va_flags, 0); if (!bo->va) { fprintf(stderr, "Failed to allocate BO VMA\n"); agx_bo_free(dev, bo); diff --git a/src/asahi/lib/agx_device.h b/src/asahi/lib/agx_device.h index 58c1e402959b..b32c97c1bf6a 100644 --- a/src/asahi/lib/agx_device.h +++ b/src/asahi/lib/agx_device.h @@ -112,8 +112,10 @@ struct agx_submit_virt { }; typedef struct { + /* A BO at `va` (agx_bo_create_at()), which it takes over and frees on + * failure too, or at a VA of its own when `va` is NULL. */ struct agx_bo *(*bo_alloc)(struct agx_device *dev, size_t size, size_t align, - enum agx_bo_flags flags); + enum agx_bo_flags flags, struct agx_va *va); int (*bo_bind)(struct agx_device *dev, struct drm_asahi_gem_bind_op *ops, uint32_t count); void (*bo_mmap)(struct agx_device *dev, struct agx_bo *bo, void *fixed_addr, diff --git a/src/asahi/lib/agx_device_virtio.c b/src/asahi/lib/agx_device_virtio.c index 6bf89810937d..59b186842f7f 100644 --- a/src/asahi/lib/agx_device_virtio.c +++ b/src/asahi/lib/agx_device_virtio.c @@ -52,7 +52,7 @@ agx_virtio_simple_ioctl(struct agx_device *dev, unsigned cmd, void *_req) static struct agx_bo * agx_virtio_bo_alloc(struct agx_device *dev, size_t size, size_t align, - enum agx_bo_flags flags) + enum agx_bo_flags flags, struct agx_va *va) { struct agx_bo *bo; unsigned handle = 0; @@ -79,7 +79,8 @@ agx_virtio_bo_alloc(struct agx_device *dev, size_t size, size_t align, uint32_t blob_id = p_atomic_inc_return(&dev->next_blob_id); enum agx_va_flags va_flags = flags & AGX_BO_LOW_VA ? AGX_VA_USC : 0; - struct agx_va *va = agx_va_alloc(dev, size, align, va_flags, 0); + if (!va) + va = agx_va_alloc(dev, size, align, va_flags, 0); if (!va) { fprintf(stderr, "Failed to allocate BO VMA\n"); return NULL; @@ -92,6 +93,7 @@ agx_virtio_bo_alloc(struct agx_device *dev, size_t size, size_t align, handle = vdrm_bo_create(dev->vdrm, size, blob_flags, blob_id, 0, &req.hdr); if (!handle) { fprintf(stderr, "vdrm_bo_created failed\n"); + agx_va_free(dev, va, false); return NULL; } diff --git a/src/asahi/lib/tests/test-agx-bo-cache.c b/src/asahi/lib/tests/test-agx-bo-cache.c index 568253e60398..717a3fbb11a1 100644 --- a/src/asahi/lib/tests/test-agx-bo-cache.c +++ b/src/asahi/lib/tests/test-agx-bo-cache.c @@ -43,8 +43,9 @@ static struct mock_state mock; static struct agx_bo * mock_bo_alloc(struct agx_device *dev, size_t size, size_t align, - enum agx_bo_flags flags) + enum agx_bo_flags flags, struct agx_va *va) { + assert(va == NULL); mock.alloc_calls++; const uint32_t handle = ++mock.next_handle; diff --git a/src/asahi/vulkan/tests/test-hk-memory-oom.c b/src/asahi/vulkan/tests/test-hk-memory-oom.c index 70b562d8b773..6327b18961c9 100644 --- a/src/asahi/vulkan/tests/test-hk-memory-oom.c +++ b/src/asahi/vulkan/tests/test-hk-memory-oom.c @@ -76,9 +76,10 @@ __wrap_os_get_total_physical_memory(uint64_t *size) * reference counting, VA release and WSI object cleanup use production code. */ static struct agx_bo * mock_bo_alloc(struct agx_device *dev, size_t size, size_t align, - enum agx_bo_flags flags) + enum agx_bo_flags flags, struct agx_va *va) { ++bo_calls; + assert(va == NULL); if (limited && size > limit - host - pinned - cached) { ++kernel_oom_attempts; return NULL; @@ -159,7 +160,7 @@ struct agx_bo * __wrap_agx_bo_import(struct agx_device *dev, int fd) { struct agx_bo *bo = mock_bo_alloc(dev, import_size, AIL_PAGESIZE, - AGX_BO_SHARED | AGX_BO_SHAREABLE); + AGX_BO_SHARED | AGX_BO_SHAREABLE, NULL); if (bo) p_atomic_set(&bo->refcnt, 1); return bo; From 6810c6e3178ddff00d158118b6b6ec0aae7ef51e Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Thu, 19 Nov 2026 14:17:55 -0300 Subject: [PATCH 2/4] borealis: map capture/replay memory once and bind capture/replay buffers into it A capture/replay buffer had a VA of its own, and capture/replay memory a second mapping in the capture/replay region when descriptor buffer capture/replay was on. Either way the GPU wrote and read one page through two VAs. G17P and M5 caches are tagged by VA, so a read through one after a barrier could return lines written before it through the other. Follow RADV: memory allocated with VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT gets its only address in the capture/replay region, the captured one on replay. A buffer takes its memory's address plus the bind offset, which replays because a capture/replay buffer must be bound to capture/replay memory (VUID-VkBindBufferMemoryInfo-bufferDeviceAddressCaptureReplay-09200, VUID-VkBindBufferMemoryInfo-buffer-09201). Images already did that. A replay address that is taken still fails with VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS, now from vkAllocateMemory, and the memory's opaque capture address is simply its address. Such memory is never cached, so the low-memory check no longer counts on the BO cache for it. Sparse buffers keep a VA of their own, and so do capture/replay buffers of a device that enabled VK_EXT_buffer_device_address's bufferDeviceAddressCaptureReplayEXT: that extension does not ask for capture/replay memory, so only the buffer's own VA can replay. (A device cannot enable both buffer device address extensions.) Those buffers bind the sparse fill page until memory is bound, and the page was only created for the KHR feature: creating one failed with VK_ERROR_UNKNOWN. Create it for the EXT feature instead. A KHR capture/replay buffer has no address until memory is bound. vkGetBufferDeviceAddress may not ask for it before that: an unbound capture/replay buffer is allowed only with VK_EXT_buffer_device_address (VUID-vkGetBufferDeviceAddress-bufferDeviceAddress-03324), whose buffers keep their own VA. vkGetBufferOpaqueCaptureAddress may ask; it reports the address the buffer was created with, which it must return, or 0, no specific address. The new brl-*-capture-replay shim tests check both paths. Signed-off-by: Jonathan Goyvaerts --- src/asahi/meson.build | 19 ++ src/asahi/vulkan/hk_buffer.c | 32 ++- src/asahi/vulkan/hk_buffer.h | 3 + src/asahi/vulkan/hk_device.c | 10 +- src/asahi/vulkan/hk_device.h | 14 +- src/asahi/vulkan/hk_device_memory.c | 114 ++++----- src/asahi/vulkan/hk_device_memory.h | 12 +- src/asahi/vulkan/meson.build | 9 + .../vulkan/tests/hk_vulkan_capture_replay.c | 235 ++++++++++++++++++ src/asahi/vulkan/tests/test-hk-memory-oom.c | 51 +++- 10 files changed, 396 insertions(+), 103 deletions(-) create mode 100644 src/asahi/vulkan/tests/hk_vulkan_capture_replay.c diff --git a/src/asahi/meson.build b/src/asahi/meson.build index 1cb70cd47c71..c9a8e3997d4f 100644 --- a/src/asahi/meson.build +++ b/src/asahi/meson.build @@ -462,6 +462,25 @@ if with_tools.contains('drm-shim') and with_asahi_vk and with_tests timeout : 120, ) + # Buffer device address capture/replay through capture/replay memory alone. + foreach chip : ['g13g', 'g17p'] + test( + 'brl-' + chip + '-capture-replay', + prog_python, + args : [ + files('../gallium/drivers/asahi/tests/run-shim.py'), + libasahi_noop_drm_shim, + hk_vulkan_capture_replay, + ], + env : [ + 'ASAHI_SHIM_CHIP=' + chip, + 'VK_DRIVER_FILES=' + _dev_icd.full_path(), + ], + depends : [_dev_icd, libvulkan_asahi], + suite : ['asahi'], + ) + endforeach + # Explicit DRM plane layouts: placement, requirements, subresource layouts # and validation, without executing on the GPU. foreach chip : ['g13g', 'g17p'] diff --git a/src/asahi/vulkan/hk_buffer.c b/src/asahi/vulkan/hk_buffer.c index 4e04ffde67f7..2cc83e5b1058 100644 --- a/src/asahi/vulkan/hk_buffer.c +++ b/src/asahi/vulkan/hk_buffer.c @@ -328,10 +328,23 @@ hk_CreateBuffer(VkDevice device, const VkBufferCreateInfo *pCreateInfo, if (!buffer) return vk_error(dev, VK_ERROR_OUT_OF_HOST_MEMORY); + if (buffer->vk.create_flags & + VK_BUFFER_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT) + buffer->opaque_capture_address = hk_get_bda_replay_addr(pCreateInfo); + + /* A sparse buffer has an address of its own, and so has a capture/replay + * buffer of VK_EXT_buffer_device_address, whose memory need not replay + * and whose address may be asked before the bind + * (VUID-vkGetBufferDeviceAddress-bufferDeviceAddress-03324). + * Any other buffer takes its memory's address plus the offset, which + * replays with capture/replay memory + * (VUID-VkBindBufferMemoryInfo-bufferDeviceAddressCaptureReplay-09200, + * VUID-VkBindBufferMemoryInfo-buffer-09201). */ if (buffer->vk.size > 0 && - (buffer->vk.create_flags & - (VK_BUFFER_CREATE_SPARSE_BINDING_BIT | - VK_BUFFER_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT))) { + ((buffer->vk.create_flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT) || + ((buffer->vk.create_flags & + VK_BUFFER_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT) && + dev->vk.enabled_features.bufferDeviceAddressCaptureReplayEXT))) { const uint32_t alignment = hk_get_buffer_alignment( hk_device_physical(dev), buffer->vk.usage, buffer->vk.create_flags); @@ -640,8 +653,8 @@ hk_BindBufferMemory2(VkDevice device, uint32_t bindInfoCount, assert(buffer->vk.device_address == 0); buffer->vk.device_address = hk_device_memory_addr(mem) + pBindInfos[i].memoryOffset; - if (!mem->replay_va && - !(mem->bo->flags & (AGX_BO_SHARED | AGX_BO_SHAREABLE | AGX_BO_HOST_PTR))) { + if (!(mem->bo->flags & + (AGX_BO_SHARED | AGX_BO_SHAREABLE | AGX_BO_HOST_PTR))) { buffer->storage_backing_handle = mem->bo->handle; buffer->storage_backing_offset = pBindInfos[i].memoryOffset; } @@ -693,6 +706,15 @@ hk_GetBufferOpaqueCaptureAddress(UNUSED VkDevice device, { VK_FROM_HANDLE(hk_buffer, buffer, pInfo->buffer); + /* The address asked for is the answer (vkGetBufferOpaqueCaptureAddress), + * also before the bind, which this query does not need. A KHR + * capture/replay buffer has no address of its own until then: 0 is no + * specific address. */ + if (buffer->opaque_capture_address) + return buffer->opaque_capture_address; + if (!buffer->vk.device_address) + return 0; + return hk_buffer_address_rw(buffer, 0); } diff --git a/src/asahi/vulkan/hk_buffer.h b/src/asahi/vulkan/hk_buffer.h index 66f213300da7..2639fd39fbdd 100644 --- a/src/asahi/vulkan/hk_buffer.h +++ b/src/asahi/vulkan/hk_buffer.h @@ -25,6 +25,9 @@ struct hk_buffer { /** Reserved VA for sparse buffers, NULL otherwise. */ struct agx_va *va; + /** Capture/replay address the application asked for, 0 for none. */ + uint64_t opaque_capture_address; + /** Bytes of that VA counted in hk_device::sparse_scratch_B. */ uint64_t sparse_scratch_B; diff --git a/src/asahi/vulkan/hk_device.c b/src/asahi/vulkan/hk_device.c index 83c6e07fb11b..654685ee38e3 100644 --- a/src/asahi/vulkan/hk_device.c +++ b/src/asahi/vulkan/hk_device.c @@ -931,8 +931,7 @@ hk_init_g17p_grid_helper(struct hk_device *dev, * On M5 every resource through which these features map memory at a second * address is seen as it is created, so the scope follows the live ones * instead (host_alias.dynamic, hk_cdm_alias_scope()): buffers and image - * planes with an address of their own and memory mapped again for - * descriptor buffer capture/replay (va_alias_resources), fd and dma-buf + * planes with an address of their own (va_alias_resources), fd and dma-buf * imports, and host imports that may alias (hk_host_import_aliases()). An * acceleration structure's address is its buffer's, also on replay, so its * capture/replay is covered by the buffer's. An import of private anonymous @@ -1191,10 +1190,11 @@ hk_CreateDevice(VkPhysicalDevice physicalDevice, } } - /* Capture-replay buffers reserve their VA and bind the fill page until - * memory is bound, like sparse buffers, so they need it too. */ + /* VK_EXT_buffer_device_address capture/replay buffers reserve their VA + * and bind the fill page until memory is bound, like sparse buffers, so + * they need it too (hk_CreateBuffer()). */ if (dev->vk.enabled_features.sparseBinding || - dev->vk.enabled_features.bufferDeviceAddressCaptureReplay) { + dev->vk.enabled_features.bufferDeviceAddressCaptureReplayEXT) { dev->sparse_fill = agx_bo_create(&dev->dev, AIL_PAGESIZE, 0, 0, "Sparse fill page"); if (!dev->sparse_fill || !agx_bo_map(dev->sparse_fill)) { diff --git a/src/asahi/vulkan/hk_device.h b/src/asahi/vulkan/hk_device.h index ab122422efb3..80a54c404ff3 100644 --- a/src/asahi/vulkan/hk_device.h +++ b/src/asahi/vulkan/hk_device.h @@ -136,10 +136,9 @@ struct hk_device { /* Scratch-filled sparse VA (M5: bounded by sparseAddressSpaceSize). */ uint64_t sparse_scratch_B; /* Live buffers and image planes with a GPU virtual address of their own - * (sparse binding, capture/replay buffers), and memory mapped again for - * descriptor buffer capture/replay, atomic (hk_device_va_alias_get()). - * Their memory is also mapped at another address, see - * hk_cdm_alias_scope(). */ + * (sparse binding, bufferDeviceAddressCaptureReplayEXT buffers), atomic + * (hk_device_va_alias_get()). Their memory is also mapped at another + * address, see hk_cdm_alias_scope(). */ uint32_t va_alias_resources; /* Whether anything this device enabled can map memory at a second GPU * virtual address at any time, decided at creation @@ -474,9 +473,10 @@ enum hk_perftest { * keep memory scope unconditionally while dynamic mode is active. * * On G17P, memory scope is selected at barrier recording time whenever - * va_alias_resources != 0 (live sparse, capture/replay, fd, or writable host - * imports). The flush is emitted into an open compute stream holding work; - * earlier closed streams already flushed at stream end. + * va_alias_resources != 0 (live sparse, bufferDeviceAddressCaptureReplayEXT + * buffers, fd, or writable host imports). The flush is emitted into an open + * compute stream holding work; earlier closed streams already flushed at + * stream end. * * Not covered on G17P: resources or imports created after command buffer * recording and reached via device address or UpdateAfterBind descriptors; diff --git a/src/asahi/vulkan/hk_device_memory.c b/src/asahi/vulkan/hk_device_memory.c index 2033fa3f5322..a019c6b9a9a4 100644 --- a/src/asahi/vulkan/hk_device_memory.c +++ b/src/asahi/vulkan/hk_device_memory.c @@ -387,19 +387,6 @@ hk_host_import_untrack(struct hk_device *dev, struct hk_device_memory *mem) (void *)mem, stopped, p_atomic_read(&dev->alias_live)); } -/* Memory mapped again in the capture/replay region (replay_va) counts from - * its mapping to its release (hk_device_va_alias_get()). */ -static void -hk_memory_release_replay_va(struct hk_device *dev, - struct hk_device_memory *mem) -{ - if (!mem->replay_va) - return; - agx_va_free(&dev->dev, mem->replay_va, true); - mem->replay_va = NULL; - hk_device_va_alias_put(dev); -} - VKAPI_ATTR VkResult VKAPI_CALL hk_AllocateMemory(VkDevice device, const VkMemoryAllocateInfo *pAllocateInfo, const VkAllocationCallbacks *pAllocator, VkDeviceMemory *pMem) @@ -572,16 +559,56 @@ hk_AllocateMemory(VkDevice device, const VkMemoryAllocateInfo *pAllocateInfo, if (type->propertyFlags & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) flags |= AGX_BO_WRITEBACK; + /* Capture/replay memory is never cached (agx_bo_create_at()). */ + const bool capture_replay = + mem->vk.alloc_flags & + VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT; + /* A BO from the cache allocates nothing new. Fetch from the cache once * and run hk_system_memory_fits() only on a real miss (including after * discarding purged entries), avoiding both a duplicate cache-lock walk - * and per-allocation /proc/meminfo reads. */ + * and per-allocation /proc/meminfo reads. Capture/replay memory always + * allocates. */ bool mem_rejected = false; /* D3D12 promises 64 KiB alignment for heap addresses, and this costs * only virtual address space. */ - mem->bo = agx_bo_create_checked(&dev->dev, aligned_size, 64 * 1024, flags, - "App memory", hk_allow_bo_alloc, - &mem_rejected); + if (capture_replay) { + /* Not from the cache, but as in agx_bo_create_checked(), idle cached + * BOs must not be why it fails: evict them and ask once more. */ + if (!hk_system_memory_fits(aligned_size)) { + agx_bo_cache_evict_all(&dev->dev); + mem_rejected = !hk_system_memory_fits(aligned_size); + } + } else { + mem->bo = agx_bo_create_checked(&dev->dev, aligned_size, 64 * 1024, + flags, "App memory", hk_allow_bo_alloc, + &mem_rejected); + } + + if (capture_replay && !mem_rejected) { + /* Capture/replay memory has one address, in the capture/replay + * region and the captured one on replay. Buffers and images bound + * to it take it plus their offset, so they replay with it. */ + const uint64_t fixed_addr = + capture_info ? capture_info->opaqueCaptureAddress : 0; + enum agx_va_flags va_flags = fixed_addr ? AGX_VA_FIXED : 0; + if (dev->dev.replay_heap_initialized) + va_flags |= AGX_VA_CAPTURE_REPLAY; + struct agx_va *va = agx_va_alloc(&dev->dev, aligned_size, 64 * 1024, + va_flags, fixed_addr); + if (!va) { + /* A replay address that is already taken is the application's + * error to handle, not an out-of-memory condition. */ + result = fixed_addr + ? vk_errorf(dev, VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS, + "Capture/replay address %#llx is in use", + (unsigned long long)fixed_addr) + : vk_error(dev, VK_ERROR_OUT_OF_DEVICE_MEMORY); + goto fail_alloc; + } + mem->bo = agx_bo_create_at(&dev->dev, aligned_size, flags, va, + "App memory"); + } if (!mem->bo) { if (mem_rejected) { result = vk_errorf(dev, VK_ERROR_OUT_OF_DEVICE_MEMORY, @@ -594,60 +621,12 @@ hk_AllocateMemory(VkDevice device, const VkMemoryAllocateInfo *pAllocateInfo, } } - /* VK_EXT_descriptor_buffer capture/replay: image descriptors embed the - * address of the image's memory, so memory allocated for capture/replay - * also maps at an address in the capture/replay region, the captured one - * on replay when that is one. Buffers and images bound to it take that - * address (hk_device_memory_addr()); buffers with a capture/replay address - * of their own keep it. */ - if ((mem->vk.alloc_flags & - VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT) && - dev->vk.enabled_features.descriptorBufferCaptureReplay && - dev->dev.replay_heap_initialized) { - const uint64_t fixed_addr = - capture_info ? capture_info->opaqueCaptureAddress : 0; - mem->replay_va = agx_va_alloc( - &dev->dev, mem->bo->size, 64 * 1024, - AGX_VA_CAPTURE_REPLAY | (fixed_addr ? AGX_VA_FIXED : 0), fixed_addr); - if (mem->replay_va && - (agx_bo_bind(&dev->dev, mem->bo, mem->replay_va->addr, - mem->bo->size, 0, - DRM_ASAHI_BIND_READ | DRM_ASAHI_BIND_WRITE) || - agx_bo_bind(&dev->dev, mem->bo, - agx_rw_addr_to_ro(&dev->dev, mem->replay_va->addr), - mem->bo->size, 0, DRM_ASAHI_BIND_READ))) { - agx_va_free(&dev->dev, mem->replay_va, true); - mem->replay_va = NULL; - agx_bo_unreference(&dev->dev, mem->bo); - mem->bo = NULL; - result = vk_error(dev, VK_ERROR_OUT_OF_DEVICE_MEMORY); - goto fail_alloc; - } - /* An address this region cannot take was not captured with the - * feature (on a device without it, it is the BO's own address): keep - * buffer device address replay as it was, through the buffers' own - * capture/replay addresses. */ - /* The memory is reached through two read-write addresses now. */ - if (mem->replay_va) - hk_device_va_alias_get(dev, HK_ALIAS_CAUSE_CAPTURE_REPLAY); - } - - if (mem->vk.alloc_flags & - VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT) { - mem->opaque_capture_address = - mem->replay_va ? mem->replay_va->addr - : capture_info && capture_info->opaqueCaptureAddress - ? capture_info->opaqueCaptureAddress - : mem->bo->va->addr; - } - /* Shadow map in case this is used for a sparse resident buffer. The mapping * persists with the BO across userspace cache reuse, so cached allocations * skip the redundant VM_BIND ioctl. */ int ret = agx_bo_ensure_ro_shadow(&dev->dev, mem->bo); if (ret) { /* The bind fails once the VM carries a sticky error. */ - hk_memory_release_replay_va(dev, mem); agx_bo_unreference(&dev->dev, mem->bo); mem->bo = NULL; vk_device_memory_destroy(&dev->vk, pAllocator, &mem->vk); @@ -658,7 +637,6 @@ hk_AllocateMemory(VkDevice device, const VkMemoryAllocateInfo *pAllocateInfo, result = hk_host_import_track(dev, mem, host_info->pHostPointer, mem->bo->size, host_maps_before_pin); if (result != VK_SUCCESS) { - hk_memory_release_replay_va(dev, mem); agx_bo_unreference(&dev->dev, mem->bo); mem->bo = NULL; vk_device_memory_destroy(&dev->vk, pAllocator, &mem->vk); @@ -786,8 +764,6 @@ hk_FreeMemory(VkDevice device, VkDeviceMemory _mem, /* The BO may outlive this object in the BO cache. */ hk_set_memory_priority(dev, mem, 0.5f); - hk_memory_release_replay_va(dev, mem); - if (mem->alias_import) p_atomic_dec(&dev->va_alias_resources); @@ -1005,5 +981,5 @@ hk_GetDeviceMemoryOpaqueCaptureAddress( { VK_FROM_HANDLE(hk_device_memory, memory, pInfo->memory); - return memory->opaque_capture_address; + return hk_device_memory_addr(memory); } diff --git a/src/asahi/vulkan/hk_device_memory.h b/src/asahi/vulkan/hk_device_memory.h index 809e3e65d512..616622d34c30 100644 --- a/src/asahi/vulkan/hk_device_memory.h +++ b/src/asahi/vulkan/hk_device_memory.h @@ -22,16 +22,6 @@ struct hk_device_memory { struct agx_bo *bo; - /* Opaque application-visible token used for BDA capture/replay. This is - * deliberately separate from the BO's current mapping: replay buffers own - * the fixed VA that determines their device address. */ - uint64_t opaque_capture_address; - - /* VK_EXT_descriptor_buffer capture/replay (hk_AllocateMemory()): a second - * mapping of the BO at an address that replays, which buffers and images - * bound to this memory take as its address. NULL otherwise. */ - struct agx_va *replay_va; - void *map; /* map is this object's own mapping of map_size bytes rather than the @@ -65,7 +55,7 @@ VK_DEFINE_NONDISP_HANDLE_CASTS(hk_device_memory, vk.base, VkDeviceMemory, static inline uint64_t hk_device_memory_addr(const struct hk_device_memory *mem) { - return mem->replay_va ? mem->replay_va->addr : mem->bo->va->addr; + return mem->bo->va->addr; } void *hk_device_memory_copy_map(struct hk_device_memory *mem); diff --git a/src/asahi/vulkan/meson.build b/src/asahi/vulkan/meson.build index e7e16b487f45..c34849135315 100644 --- a/src/asahi/vulkan/meson.build +++ b/src/asahi/vulkan/meson.build @@ -1295,6 +1295,15 @@ if with_tests gnu_symbol_visibility : 'hidden', ) + hk_vulkan_capture_replay = executable( + 'brl-vulkan-capture-replay', + files('tests/hk_vulkan_capture_replay.c'), + include_directories : [inc_include], + dependencies : [cc.find_library('vulkan')], + c_args : [c_msvc_compat_args], + gnu_symbol_visibility : 'hidden', + ) + hk_vulkan_sparse_bind_first_submit = executable( 'hk-vulkan-sparse-bind-first-submit', files('tests/hk_vulkan_sparse_bind_first_submit.c'), diff --git a/src/asahi/vulkan/tests/hk_vulkan_capture_replay.c b/src/asahi/vulkan/tests/hk_vulkan_capture_replay.c new file mode 100644 index 000000000000..68cadfa43147 --- /dev/null +++ b/src/asahi/vulkan/tests/hk_vulkan_capture_replay.c @@ -0,0 +1,235 @@ +/* Copyright 2026 Aurora Silicon + * SPDX-License-Identifier: MIT + * + * Buffer device address capture/replay without a second mapping: a + * capture/replay buffer takes its memory's address plus the bind offset, + * memory allocated again on another device at its captured address gets it + * back and so does the buffer, and an address still in use is refused with + * VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS. With VK_EXT_buffer_device_address, + * whose memory need not be capture/replay memory, the buffer's own address + * replays. Nothing executes on the GPU, so the test also runs under the + * no-op DRM shim. + */ +#include +#include +#include +#include +#include + +#define CHECK(call) \ + do { \ + VkResult r_ = (call); \ + if (r_ != VK_SUCCESS) { \ + fprintf(stderr, "FAIL: %s: %d\n", #call, r_); \ + exit(1); \ + } \ + } while (0) + +#define EXPECT(cond) \ + do { \ + if (!(cond)) { \ + fprintf(stderr, "FAIL: %s\n", #cond); \ + exit(1); \ + } \ + } while (0) + +static const VkDeviceSize offset = 64 * 1024, size = 256 * 1024; + +static VkDevice +make_device(VkPhysicalDevice pdev, bool ext) +{ + const float priority = 1.0f; + const VkDeviceQueueCreateInfo queue_info = { + .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, + .queueCount = 1, + .pQueuePriorities = &priority, + }; + const VkPhysicalDeviceVulkan12Features f12 = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES, + .bufferDeviceAddress = VK_TRUE, + .bufferDeviceAddressCaptureReplay = VK_TRUE, + }; + const VkPhysicalDeviceBufferDeviceAddressFeaturesEXT fext = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BUFFER_DEVICE_ADDRESS_FEATURES_EXT, + .bufferDeviceAddress = VK_TRUE, + .bufferDeviceAddressCaptureReplay = VK_TRUE, + }; + const char *ext_name = VK_EXT_BUFFER_DEVICE_ADDRESS_EXTENSION_NAME; + const VkDeviceCreateInfo device_info = { + .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, + .pNext = ext ? (const void *)&fext : &f12, + .queueCreateInfoCount = 1, + .pQueueCreateInfos = &queue_info, + .enabledExtensionCount = ext, + .ppEnabledExtensionNames = &ext_name, + }; + VkDevice dev; + CHECK(vkCreateDevice(pdev, &device_info, NULL, &dev)); + return dev; +} + +static VkResult +alloc(VkDevice dev, uint64_t replay_addr, VkDeviceMemory *mem) +{ + const VkMemoryOpaqueCaptureAddressAllocateInfo capture = { + .sType = VK_STRUCTURE_TYPE_MEMORY_OPAQUE_CAPTURE_ADDRESS_ALLOCATE_INFO, + .opaqueCaptureAddress = replay_addr, + }; + const VkMemoryAllocateFlagsInfo flags = { + .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, + .pNext = &capture, + .flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT | + VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT, + }; + const VkMemoryAllocateInfo info = { + .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .pNext = &flags, + .allocationSize = size, + }; + return vkAllocateMemory(dev, &info, NULL, mem); +} + +/* A capture/replay buffer bound at `offset` in `mem`; returns its address. */ +static uint64_t +bind_buffer(VkDevice dev, VkDeviceMemory mem, uint64_t replay_addr, + VkBuffer *buf) +{ + const VkBufferOpaqueCaptureAddressCreateInfo capture = { + .sType = VK_STRUCTURE_TYPE_BUFFER_OPAQUE_CAPTURE_ADDRESS_CREATE_INFO, + .opaqueCaptureAddress = replay_addr, + }; + const VkBufferCreateInfo info = { + .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, + .pNext = &capture, + .flags = VK_BUFFER_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT, + .size = 4096, + .usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | + VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, + }; + CHECK(vkCreateBuffer(dev, &info, NULL, buf)); + const VkBufferDeviceAddressInfo addr_info = { + .sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, + .buffer = *buf, + }; + /* Before the bind, the address asked for (none on capture). */ + EXPECT(vkGetBufferOpaqueCaptureAddress(dev, &addr_info) == replay_addr); + VkMemoryRequirements req; + vkGetBufferMemoryRequirements(dev, *buf, &req); + EXPECT((req.memoryTypeBits & 1) && offset % req.alignment == 0); + CHECK(vkBindBufferMemory(dev, *buf, mem, offset)); + + const uint64_t addr = vkGetBufferDeviceAddress(dev, &addr_info); + EXPECT(vkGetBufferOpaqueCaptureAddress(dev, &addr_info) == addr); + return addr; +} + +static uint64_t +memory_addr(VkDevice dev, VkDeviceMemory mem) +{ + const VkDeviceMemoryOpaqueCaptureAddressInfo info = { + .sType = VK_STRUCTURE_TYPE_DEVICE_MEMORY_OPAQUE_CAPTURE_ADDRESS_INFO, + .memory = mem, + }; + return vkGetDeviceMemoryOpaqueCaptureAddress(dev, &info); +} + +int +main(void) +{ + const VkApplicationInfo app = { + .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, + .apiVersion = VK_API_VERSION_1_3, + }; + const VkInstanceCreateInfo instance_info = { + .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, + .pApplicationInfo = &app, + }; + VkInstance instance; + CHECK(vkCreateInstance(&instance_info, NULL, &instance)); + uint32_t count = 1; + VkPhysicalDevice pdev; + VkResult r = vkEnumeratePhysicalDevices(instance, &count, &pdev); + if ((r != VK_SUCCESS && r != VK_INCOMPLETE) || count == 0) { + fprintf(stderr, "no physical device\n"); + return 2; + } + + /* Capture. */ + VkDevice dev = make_device(pdev, false); + VkDeviceMemory mem, taken; + VkBuffer buf; + CHECK(alloc(dev, 0, &mem)); + const uint64_t mem_addr = memory_addr(dev, mem); + const uint64_t buf_addr = bind_buffer(dev, mem, 0, &buf); + EXPECT(mem_addr != 0 && buf_addr == mem_addr + offset); + EXPECT(alloc(dev, mem_addr, &taken) == + VK_ERROR_INVALID_OPAQUE_CAPTURE_ADDRESS); + vkDestroyBuffer(dev, buf, NULL); + vkFreeMemory(dev, mem, NULL); + vkDestroyDevice(dev, NULL); + + /* Replay, on a new device. */ + dev = make_device(pdev, false); + CHECK(alloc(dev, mem_addr, &mem)); + EXPECT(memory_addr(dev, mem) == mem_addr); + EXPECT(bind_buffer(dev, mem, buf_addr, &buf) == buf_addr); + vkDestroyBuffer(dev, buf, NULL); + vkFreeMemory(dev, mem, NULL); + + /* Freed, the address is free again. */ + CHECK(alloc(dev, mem_addr, &mem)); + vkFreeMemory(dev, mem, NULL); + vkDestroyDevice(dev, NULL); + + /* VK_EXT_buffer_device_address: ordinary memory, the buffer replays its + * own address. The replay device allocates other memory first, so that + * ordinary addresses differ from the capture's. */ + const VkMemoryAllocateInfo plain = { + .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .allocationSize = size, + }; + uint64_t ext_addr = 0; + for (unsigned replay = 0; replay < 2; replay++) { + dev = make_device(pdev, true); + PFN_vkGetBufferDeviceAddressEXT get_addr = + (PFN_vkGetBufferDeviceAddressEXT)vkGetDeviceProcAddr( + dev, "vkGetBufferDeviceAddressEXT"); + EXPECT(get_addr != NULL); + VkDeviceMemory other = VK_NULL_HANDLE; + if (replay) + CHECK(vkAllocateMemory(dev, &plain, NULL, &other)); + CHECK(vkAllocateMemory(dev, &plain, NULL, &mem)); + const VkBufferDeviceAddressCreateInfoEXT replay_info = { + .sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_CREATE_INFO_EXT, + .deviceAddress = ext_addr, + }; + const VkBufferCreateInfo info = { + .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, + .pNext = &replay_info, + .flags = VK_BUFFER_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT, + .size = 4096, + .usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | + VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, + }; + CHECK(vkCreateBuffer(dev, &info, NULL, &buf)); + const VkBufferDeviceAddressInfo addr_info = { + .sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO, + .buffer = buf, + }; + /* The EXT feature lets the address be asked before the bind + * (VUID-vkGetBufferDeviceAddress-bufferDeviceAddress-03324). */ + const uint64_t addr = get_addr(dev, &addr_info); + CHECK(vkBindBufferMemory(dev, buf, mem, offset)); + EXPECT(get_addr(dev, &addr_info) == addr); + EXPECT(addr != 0 && (!replay || addr == ext_addr)); + ext_addr = addr; + vkDestroyBuffer(dev, buf, NULL); + vkFreeMemory(dev, mem, NULL); + vkFreeMemory(dev, other, NULL); + vkDestroyDevice(dev, NULL); + } + + vkDestroyInstance(instance, NULL); + printf("PASS\n"); + return 0; +} diff --git a/src/asahi/vulkan/tests/test-hk-memory-oom.c b/src/asahi/vulkan/tests/test-hk-memory-oom.c index 6327b18961c9..c7b0772bb8fb 100644 --- a/src/asahi/vulkan/tests/test-hk-memory-oom.c +++ b/src/asahi/vulkan/tests/test-hk-memory-oom.c @@ -79,13 +79,14 @@ mock_bo_alloc(struct agx_device *dev, size_t size, size_t align, enum agx_bo_flags flags, struct agx_va *va) { ++bo_calls; - assert(va == NULL); - if (limited && size > limit - host - pinned - cached) { - ++kernel_oom_attempts; + /* bo_alloc takes over a caller's VA and frees it when it fails. */ + if ((limited && size > limit - host - pinned - cached) || bo_fails) { + if (limited && size > limit - host - pinned - cached) + ++kernel_oom_attempts; + if (va) + agx_va_free(dev, va, false); return NULL; } - if (bo_fails) - return NULL; struct agx_bo *bo = calloc(1, sizeof(*bo)); assert(bo); unsigned handle; @@ -100,7 +101,7 @@ mock_bo_alloc(struct agx_device *dev, size_t size, size_t align, bo->size = size; bo->align = align; bo->flags = flags; - bo->va = agx_va_alloc(dev, size, align, 0, 0); + bo->va = va ?: agx_va_alloc(dev, size, align, 0, 0); assert(bo->va); pinned += size; if (pinned > peak) @@ -351,6 +352,23 @@ alloc(struct hk_device *dev, uint64_t size, VkDeviceMemory *memory) return alloc_type(dev, size, 0, memory); } +static VkResult +alloc_capture_replay(struct hk_device *dev, uint64_t size, + VkDeviceMemory *memory) +{ + const VkMemoryAllocateFlagsInfo flags = { + .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO, + .flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT | + VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT, + }; + const VkMemoryAllocateInfo info = { + .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .pNext = &flags, + .allocationSize = size, + }; + return hk_AllocateMemory(hk_device_to_handle(dev), &info, &allocator, memory); +} + static void swapchain_attempt(struct hk_device *dev, uint64_t image_size) { @@ -625,6 +643,27 @@ main(void) hk_FreeMemory(hk_device_to_handle(dev), memory, &allocator); agx_bo_cache_evict_all(&dev->dev); + /* Capture/replay memory never comes from the cache and never goes back + * to it, but a refusal still evicts the cache and asks once more. */ + fake_available = 64 * 1024 * MIB; + assert(alloc(dev, 128 * MIB, &memory) == VK_SUCCESS); + hk_FreeMemory(hk_device_to_handle(dev), memory, &allocator); + assert(dev->dev.bo_cache.size == 128 * MIB); + fake_available = 512 * MIB + 1024 * MIB - 1; + free_returns_available = true; + meminfo_reads = 0; + before = bo_calls; + assert(alloc_capture_replay(dev, 512 * MIB, &memory) == VK_SUCCESS); + assert(meminfo_reads == 2 && bo_calls == before + 1); + assert(!dev->dev.bo_cache.size && pinned == 512 * MIB); + free_returns_available = false; + hk_FreeMemory(hk_device_to_handle(dev), memory, &allocator); + assert(!dev->dev.bo_cache.size && !pinned); + /* Without anything to evict, it is refused. */ + fake_available = 1024 * MIB; + assert(alloc_capture_replay(dev, 512 * MIB, &memory) == + VK_ERROR_OUT_OF_DEVICE_MEMORY); + /* Warm BO-cache reuse across 4 KiB..64 MiB must issue zero VM_BINDs, * isolate memory types by BO flags, retry after a bind failure, and reset * cleanly on cache eviction. */ From e6751e447ee1278fa23fc4ab49065eb0941cabe3 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Thu, 19 Nov 2026 14:18:03 -0300 Subject: [PATCH 3/4] borealis: stop counting KHR capture/replay among the features that alias memory Capture/replay of buffer device addresses through Vulkan 1.2 or VK_KHR_buffer_device_address, and descriptor buffer and acceleration structure capture/replay, no longer map memory at a second address. A device that enables them but none of sparse binding, bufferDeviceAddressCaptureReplayEXT, or fd or writable host imports keeps the ordinary strong flush at its dependencies on M5. Signed-off-by: Jonathan Goyvaerts --- src/asahi/vulkan/hk_device.c | 43 +++++++++++++++--------------------- src/asahi/vulkan/hk_device.h | 9 ++++---- 2 files changed, 23 insertions(+), 29 deletions(-) diff --git a/src/asahi/vulkan/hk_device.c b/src/asahi/vulkan/hk_device.c index 654685ee38e3..bfb7d6ef4c34 100644 --- a/src/asahi/vulkan/hk_device.c +++ b/src/asahi/vulkan/hk_device.c @@ -909,11 +909,13 @@ hk_init_g17p_grid_helper(struct hk_device *dev, /* Whether memory can be mapped at a second GPU virtual address at any time * in the life of `dev`, from what it enabled (hk_cdm_alias_scope()): * - * - sparse buffers and images, and capture/replay buffers, have an address - * of their own, and the memory bound to them keeps its own as well; - * - an fd import of memory from elsewhere gets an address of its own, and - * another import may map the same pages (two dma-bufs over one memfd, or - * a dma-buf and a host import of its pages); + * - sparse buffers and images, and capture/replay buffers of + * VK_EXT_buffer_device_address, have an address of their own, and the + * memory bound to them keeps its own as well; + * - an fd import gets an address of its own. Importing one GEM object again, + * our own export included, gives the same BO and address (agx_bo_import()), + * but two dma-bufs can share pages under different GEM objects (two + * udmabufs over one memfd), and a host import may map a dma-buf's pages; * - a host import gets an address of its own, and the same pages may be * imported again, or be mapped by the application at a second virtual * address that another import, or memory of another kind, reaches. With @@ -921,12 +923,14 @@ hk_init_g17p_grid_helper(struct hk_device *dev, * GPU, so the GPU writes no imported page and a read through the import * cannot miss a write through another address. * - * Nothing else maps memory the GPU writes at two addresses: the read-only - * shadow of every allocation is read only through sparse and capture/replay - * buffers, and the driver's other second mappings (descriptor tables, - * acceleration structure tables, shader code) hold memory written by the - * CPU alone. The structures of these features may only be used when they - * are enabled, so a device that enabled none of them never has such memory. + * Nothing else maps memory the GPU writes at two addresses: capture/replay + * memory has its address in the capture/replay region alone, and other + * buffers and images bound to it take that address; the read-only shadow of + * every allocation is read only through sparse buffers; and the driver's + * other second mappings (descriptor tables, acceleration structure tables, + * shader code) hold memory written by the CPU alone. The structures of these + * features may only be used when they are enabled, so a device that enabled + * none of them never has such memory. * * On M5 every resource through which these features map memory at a second * address is seen as it is created, so the scope follows the live ones @@ -953,13 +957,7 @@ hk_device_may_alias_memory(const struct hk_device *dev, f->sparseResidencyImage2D || f->sparseResidencyImage3D || f->sparseResidency2Samples || f->sparseResidency4Samples || f->sparseResidency8Samples || f->sparseResidency16Samples || - f->sparseResidencyAliased) - return true; - - if (f->bufferDeviceAddressCaptureReplay || - f->bufferDeviceAddressCaptureReplayEXT || - f->descriptorBufferCaptureReplay || - f->accelerationStructureCaptureReplay) + f->sparseResidencyAliased || f->bufferDeviceAddressCaptureReplayEXT) return true; if (ext->KHR_external_memory_fd || ext->EXT_external_memory_dma_buf) @@ -993,13 +991,8 @@ hk_device_trace_alias_reasons(const struct hk_device *dev, f->sparseResidency8Samples || f->sparseResidency16Samples, "sparseResidencyNSamples"); HK_ALIAS_REASON(f->sparseResidencyAliased, "sparseResidencyAliased"); - HK_ALIAS_REASON(f->bufferDeviceAddressCaptureReplay || - f->bufferDeviceAddressCaptureReplayEXT, - "bufferDeviceAddressCaptureReplay"); - HK_ALIAS_REASON(f->descriptorBufferCaptureReplay, - "descriptorBufferCaptureReplay"); - HK_ALIAS_REASON(f->accelerationStructureCaptureReplay, - "accelerationStructureCaptureReplay"); + HK_ALIAS_REASON(f->bufferDeviceAddressCaptureReplayEXT, + "bufferDeviceAddressCaptureReplayEXT"); HK_ALIAS_REASON(ext->KHR_external_memory_fd, "KHR_external_memory_fd"); HK_ALIAS_REASON(ext->EXT_external_memory_dma_buf, "EXT_external_memory_dma_buf"); HK_ALIAS_REASON(ext->EXT_external_memory_host && diff --git a/src/asahi/vulkan/hk_device.h b/src/asahi/vulkan/hk_device.h index 80a54c404ff3..8a808c2595a8 100644 --- a/src/asahi/vulkan/hk_device.h +++ b/src/asahi/vulkan/hk_device.h @@ -463,10 +463,11 @@ enum hk_perftest { * mapped at more than one GPU VA an application compute/transfer barrier needs * the memory-scoped strong flush (hk_cdm_visibility_flush()). * - * On M5, devices that enable aliasing-capable features (sparse, BDA, - * capture/replay, fd/dma-buf, writable host imports) track active aliasing - * resources in alias_live under host_alias.dynamic (or force memory scope via - * may_alias_memory / ASAHI_M5_HOST_ALIAS_STATIC=1). Barriers recorded while + * On M5, devices that enable aliasing-capable features (sparse, + * VK_EXT_buffer_device_address capture/replay, fd/dma-buf, writable host + * imports) track active aliasing resources in alias_live under + * host_alias.dynamic (or force memory scope via may_alias_memory / + * ASAHI_M5_HOST_ALIAS_STATIC=1). Barriers recorded while * alias_live == 0 record patch sites (struct hk_alias_site) that are upgraded * in place when alias_live leaves 0 or at submission; unpatched paths * (graphics dependencies, event-using command buffers) and stream-end flushes From 2785fdd1910ab167feae34e8333e8de2c32d2650 Mon Sep 17 00:00:00 2001 From: Jonathan Goyvaerts Date: Fri, 20 Nov 2026 16:26:57 -0300 Subject: [PATCH 4/4] borealis: patch barrier records on G17P as on M5 when memory first aliases G17P and M5 GPU caches are tagged by virtual address, so a read through a second address of the same memory after a dependency needs the memory-scope flush. M5 records a dependency without that scope while no resource with a second address lives, and writes the scope over the dependency's barrier record when one appears (patch sites, host_alias.dynamic). G17P instead read a live count when the barrier was recorded. A command buffer recorded before the first such resource, and run after it, kept the cheaper flush: a read through the second address after a barrier was stale when the buffer reached that address through an address it loads or a descriptor written after it was bound. Select the patch-site mode by the hardware property, hk_va_tagged_caches(), instead of the chip, so G17P takes it too, and drop G17P's record-time count (va_alias_resources, alias_import). The barrier word, its memory-scope bit and the in-place stream (the kernel runs the recorded stream at its own address) are the same on both. G17P thereby gets M5's alias classification: a host import counts only while its pages may be mapped elsewhere, and fd and dma-buf imports count for their lifetime. On top of that, G17P needs: - G17P command memory is CPU-cached (hk_g17p_cached_cmd_memory()), so a patched word is written back. - Transfers ordered before a draw and task launches record patch sites instead of keeping memory scope for good, on both chips. G17P's count let them keep the cheap flush. A site on a tessellation stage's tail is not dropped by the next batched draw (hk_cs::alias_pin). - The G17P CDM reads about 256 bytes of stream past the launch it runs, also across event waits, so a site patched while a command buffer runs can be missed. M5 gave a command buffer that uses events memory scope throughout. Narrow that, on both chips, to a command buffer that waits for an event the host may set: the only way a running command buffer reaches memory aliased after it started. Such a wait's barriers may hold only host operations in their first scope (VUID-vkCmdWaitEvents2-pEvents-03839): it has no barriers, or barriers whose srcStageMask is HOST or NONE. Only a device source stage with no HOST beside it rules the host out. Setting an event, as DXVK does for its event queries, now records a patch site like any other dependency instead of costing every barrier of the command buffer memory scope. The byte-stencil dispatch check (hk_byte_stencil_validate_dispatch()) read the dropped count to prove that disjoint addresses are disjoint memory. It now asks for no live aliasing resource (alias_live) on a device that tracks them, and otherwise for no enabled feature through which memory can get a second address (may_alias_memory). That is exact on G17P and M5 and also covers the fd and dma-buf imports the old count missed on other chips. The memory-scoped end of every M5 compute stream stays M5-only. The end of a G17P command already makes its writes visible at every address: bt xsub, with the second address created while the writer runs, reads exact without it. The helper that moves sites with an inline merge is inline again, so the unit tests run the real one. They check that sites and the pin move with a merge, and that a pinned tessellation tail stays. The new brl-g17p-event-alias shim test records a host-event wait (no barriers, a NONE source stage, HOST), ends the command buffer and then creates the first aliasing resource: the command buffer must have taken memory scope at its end. An event set in the command buffer must still wait for the patch. Only G17P was run on hardware. On M5 this changes the graphics-path sites and the event rule; it was built and unit tested without hardware. Signed-off-by: Jonathan Goyvaerts --- src/asahi/meson.build | 18 ++ src/asahi/vulkan/hk_buffer.c | 4 +- src/asahi/vulkan/hk_cmd_buffer.c | 49 ++-- src/asahi/vulkan/hk_cmd_buffer.h | 55 +++- src/asahi/vulkan/hk_cmd_dispatch.c | 7 +- src/asahi/vulkan/hk_cmd_draw.c | 15 +- src/asahi/vulkan/hk_device.c | 15 +- src/asahi/vulkan/hk_device.h | 101 +++---- src/asahi/vulkan/hk_device_memory.c | 14 +- src/asahi/vulkan/hk_device_memory.h | 6 +- src/asahi/vulkan/hk_event.c | 50 +++- src/asahi/vulkan/hk_image.c | 4 +- src/asahi/vulkan/hk_nir_tile_byte_stencil.c | 9 +- src/asahi/vulkan/hk_tess_batch.c | 3 +- src/asahi/vulkan/meson.build | 9 + .../vulkan/tests/hk_vulkan_event_alias.c | 249 ++++++++++++++++++ .../tests/test-hk-execution-allowance.c | 56 +++- src/asahi/vulkan/tests/test-hk-tess-batch.c | 22 +- 18 files changed, 519 insertions(+), 167 deletions(-) create mode 100644 src/asahi/vulkan/tests/hk_vulkan_event_alias.c diff --git a/src/asahi/meson.build b/src/asahi/meson.build index c9a8e3997d4f..7e6f11173cbb 100644 --- a/src/asahi/meson.build +++ b/src/asahi/meson.build @@ -481,6 +481,24 @@ if with_tools.contains('drm-shim') and with_asahi_vk and with_tests ) endforeach + # A wait for a host-set event, also one without barriers, gives its + # command buffer memory scope at its end, before memory first aliases. + test( + 'brl-g17p-event-alias', + prog_python, + args : [ + files('../gallium/drivers/asahi/tests/run-shim.py'), + libasahi_noop_drm_shim, + hk_vulkan_event_alias, + ], + env : [ + 'ASAHI_SHIM_CHIP=g17p', + 'VK_DRIVER_FILES=' + _dev_icd.full_path(), + ], + depends : [_dev_icd, libvulkan_asahi], + suite : ['asahi'], + ) + # Explicit DRM plane layouts: placement, requirements, subresource layouts # and validation, without executing on the GPU. foreach chip : ['g13g', 'g17p'] diff --git a/src/asahi/vulkan/hk_buffer.c b/src/asahi/vulkan/hk_buffer.c index 2cc83e5b1058..f1fc9d0b234f 100644 --- a/src/asahi/vulkan/hk_buffer.c +++ b/src/asahi/vulkan/hk_buffer.c @@ -478,7 +478,7 @@ hk_CreateBuffer(VkDevice device, const VkBufferCreateInfo *pCreateInfo, * the memory's, or other resources' (hk_cdm_alias_scope()). It counts * before memory can be bound to it. */ if (buffer->va) - hk_device_va_alias_get(dev, (buffer->vk.create_flags & + hk_device_alias_get(dev, 1, (buffer->vk.create_flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT) ? HK_ALIAS_CAUSE_SPARSE : HK_ALIAS_CAUSE_CAPTURE_REPLAY); @@ -520,7 +520,7 @@ hk_DestroyBuffer(VkDevice device, VkBuffer _buffer, if (buffer->va) { agx_va_free(&dev->dev, buffer->va, true); - hk_device_va_alias_put(dev); + hk_device_alias_put(dev, 1); } hk_release_sparse_scratch(dev, buffer->sparse_scratch_B); diff --git a/src/asahi/vulkan/hk_cmd_buffer.c b/src/asahi/vulkan/hk_cmd_buffer.c index 43e1b757d97e..38075db142f6 100644 --- a/src/asahi/vulkan/hk_cmd_buffer.c +++ b/src/asahi/vulkan/hk_cmd_buffer.c @@ -184,19 +184,24 @@ hk_descriptor_state_fini(struct hk_cmd_buffer *cmd, } } -/* Writes the stream words of the patch sites. M5 command memory is mapped - * uncached (hk_g17p_cached_cmd_memory() is G17P-only), so the words need no - * cache maintenance, only to be stored whole (the GPU may read the stream - * meanwhile when the alias count leaves 0) and made visible before the - * submission or host signal that lets the GPU run them. */ +/* Writes the stream words of the patch sites. Each is stored whole (the GPU + * may read the stream meanwhile when the alias count leaves 0) and made + * visible before the submission or host signal that lets the GPU run them: + * written back from the CPU cache where command memory is cached + * (hk_g17p_cached_cmd_memory()), else only fenced. */ void hk_cmd_buffer_patch_alias_sites(struct hk_cmd_buffer *cmd) { if (p_atomic_read(&cmd->alias_patched) || !cmd->alias_sites.size) return; - util_dynarray_foreach(&cmd->alias_sites, struct hk_alias_site, site) + const bool cached = + hk_g17p_cached_cmd_memory(&hk_cmd_buffer_device(cmd)->dev); + util_dynarray_foreach(&cmd->alias_sites, struct hk_alias_site, site) { __atomic_store_n(site->word, site->value, __ATOMIC_RELAXED); + if (cached) + util_flush_range_no_fence(site->word, sizeof(*site->word)); + } __sync_synchronize(); if (util_has_cache_ops()) @@ -204,25 +209,8 @@ hk_cmd_buffer_patch_alias_sites(struct hk_cmd_buffer *cmd) p_atomic_set(&cmd->alias_patched, 1); } -void -hk_cmd_buffer_move_alias_sites(struct hk_cmd_buffer *cmd, const void *from, - const void *from_end, uint8_t *to, size_t skip) -{ - util_dynarray_foreach(&cmd->alias_sites, struct hk_alias_site, site) { - const uint8_t *word = (const uint8_t *)site->word; - if (word < (const uint8_t *)from || word >= (const uint8_t *)from_end) - continue; - - /* A site in the folded leading record moves to the trailing record - * that absorbed it. */ - const size_t offset = word - (const uint8_t *)from; - site->word = (uint32_t *)(offset < skip ? to - AGX3_CDM_BARRIER_SIZE - : to + offset - skip); - } -} - /* At vkEndCommandBuffer, once nothing moves the streams any more: a command - * buffer that uses events gets memory scope throughout + * buffer that waits for a host-set event gets memory scope throughout * (hk_cmd_alias_scope()), one recorded while a resource may alias by now is * written at once, and any other waits in host_alias.cmd_buffers for * hk_device_patch_alias_sites(), besides the check at submission. */ @@ -232,7 +220,7 @@ hk_cmd_buffer_end_alias_sites(struct hk_cmd_buffer *cmd) if (!cmd->alias_sites.size) return; - if (cmd->state.uses_events) { + if (cmd->state.alias_host_wait) { hk_cmd_buffer_patch_alias_sites(cmd); return; } @@ -1132,8 +1120,8 @@ hk_EndCommandBuffer(VkCommandBuffer commandBuffer) * with ENOTSUPP ("G18 compute admission rejected ... stream_bytes=52"). */ if (cs->type == HK_CS_CDM && !cs->g18_dispatch_sealed) { - /* With host_alias.dynamic, every stream holding work ends with the - * memory-scoped strong flush, also where its last record is an + /* M5 with host_alias.dynamic: every stream holding work ends with + * the memory-scoped strong flush, also where its last record is an * application barrier recorded without memory scope. Each command * then writes back what it wrote by its end, as the memory scope of * each barrier did under the per-device rule, so a later command @@ -1143,8 +1131,11 @@ hk_EndCommandBuffer(VkCommandBuffer commandBuffer) * another device's, process's or API's mapping of the same pages, * which Vulkan orders after this work only at a submission * boundary. Submit packing keeps the scope only at a packet's end - * while no resource may alias. */ - if (dev->host_alias.dynamic && + * while no resource may alias. The end of a G17P command already + * publishes its writes to every address (bt xsub with the second + * address created while the writer runs reads exact), so G17P + * streams end with their own records. */ + if (dev->host_alias.dynamic && agx_chip_g17_m5(dev->dev.chip) && hk_cdm_visibility_flush_needed(dev, cs, true)) { if (cs->current != cs->weak_barrier_end && cs->current != cs->strong_flush_end) diff --git a/src/asahi/vulkan/hk_cmd_buffer.h b/src/asahi/vulkan/hk_cmd_buffer.h index c75001cb525c..1093bc7d898c 100644 --- a/src/asahi/vulkan/hk_cmd_buffer.h +++ b/src/asahi/vulkan/hk_cmd_buffer.h @@ -1384,10 +1384,14 @@ struct hk_cs { /* The vertex stages read the hoisted preamble after this stream. */ bool pre_gfx_writes_preamble; - /* M5: patch sites recorded in this stream (hk_cmd_buffer::alias_sites), + /* Patch sites recorded in this stream (hk_cmd_buffer::alias_sites), * which a merge moves with its bytes. */ uint32_t alias_sites; + /* current just after a barrier record that is a patch site: a later + * launch must not drop it (hk_tess_batch_stage()). */ + void *alias_pin; + /* AGX3 CDM: the value of current just after a standalone barrier that is * the stream's *first* record. Apple's emitter only opens a stream with a * barrier (the strong flush that makes a preceding render visible), so a @@ -1824,12 +1828,10 @@ hk_root_only_flush_supported(enum agx_chip chip, const struct hk_cs *cs) void *hk_cmd_buffer_emit_cs_jump(struct hk_cmd_buffer *cmd, void *current, uint64_t target, bool vdm); -/* Moves the patch sites of cmd in [from, from_end), copied to `to` without - * their first `skip` bytes, which were folded into the record just before - * `to` (hk_cs_merge_cdm_until()). */ -void hk_cmd_buffer_move_alias_sites(struct hk_cmd_buffer *cmd, - const void *from, const void *from_end, - uint8_t *to, size_t skip); +static inline void hk_cmd_buffer_move_alias_sites(struct hk_cmd_buffer *cmd, + const void *from, + const void *from_end, + uint8_t *to, size_t skip); /* * Helper to merge two compute control streams, concatenating the second control @@ -1902,6 +1904,11 @@ hk_cs_merge_cdm_until(struct hk_cs *a, const struct hk_cs *b, void *b_current) if (b->alias_sites && a->cmd == b->cmd) hk_cmd_buffer_move_alias_sites(a->cmd, b->start, b_current, dst, b_skip); + a->alias_pin = + b->alias_pin && a->cmd == b->cmd + ? dst + ((uint8_t *)b->alias_pin - (uint8_t *)b->start) - b_skip + : a->current == dst ? a->alias_pin + : NULL; /* These markers point just past an emitted barrier. Preserve them in * the destination root so another adjacent merge still has an exact @@ -1935,6 +1942,7 @@ hk_cs_merge_cdm_until(struct hk_cs *a, const struct hk_cs *b, void *b_current) a->strong_flush_end = b->strong_flush_end; a->weak_barrier_end = b->weak_barrier_end; a->memory_flush_end = b->memory_flush_end; + a->alias_pin = b->alias_pin; a->app_dispatch_end = NULL; } @@ -2199,6 +2207,10 @@ struct hk_cmd_buffer { * pipeline barrier that carries its barriers. */ bool brl_legacy_event_wait; + /* A wait for an event the host may set: its barriers name HOST or no + * device stage as their source (hk_CmdWaitEvents2()). */ + bool alias_host_wait; + /* Scoped around direct/indirect AS builds, including their meta blits. */ bool as_build_recording; @@ -2346,7 +2358,7 @@ struct hk_cmd_buffer { * reference. */ struct hk_ioto_arena ioto; - /* M5 with hk_device::host_alias.dynamic: the application dependencies + /* With hk_device::host_alias.dynamic: the application dependencies * recorded without memory scope (struct hk_alias_site), written once an * import may alias (hk_cdm_alias_scope()). alias_patched (atomic) once * they are; alias_registered (atomic) while alias_link is in @@ -2371,9 +2383,34 @@ struct hk_alias_site { uint32_t value; }; +/* Moves the patch sites of cmd in [from, from_end), copied to `to` without + * their first `skip` bytes, which were folded into the record just before + * `to` (hk_cs_merge_cdm_until()). */ +static inline void +hk_cmd_buffer_move_alias_sites(struct hk_cmd_buffer *cmd, const void *from, + const void *from_end, uint8_t *to, size_t skip) +{ + util_dynarray_foreach(&cmd->alias_sites, struct hk_alias_site, site) { + const uint8_t *word = (const uint8_t *)site->word; + if (word < (const uint8_t *)from || word >= (const uint8_t *)from_end) + continue; + + /* A site in the folded leading record moves to the trailing record + * that absorbed it. */ + const size_t offset = word - (const uint8_t *)from; + site->word = (uint32_t *)(offset < skip ? to - AGX3_CDM_BARRIER_SIZE + : to + offset - skip); + } +} + /* Whether an application dependency recorded now needs memory scope: as * hk_cdm_alias_scope(), and also, with host_alias.dynamic, in a command - * buffer that uses events. */ + * buffer that waits for an event the host may set. Such a wait is the one way + * an execution that already started can reach memory aliased after it + * started (VUID-vkCmdWaitEvents2-pEvents-03839), and by then the CDM may + * have read the records past the wait (about 256 bytes of stream on G17P), + * so writing its sites comes too late. Setting an event, as DXVK does for + * its event queries, lets nothing in. */ bool hk_cmd_alias_scope(struct hk_cmd_buffer *cmd); /* After an application dependency was recorded into cs without memory scope diff --git a/src/asahi/vulkan/hk_cmd_dispatch.c b/src/asahi/vulkan/hk_cmd_dispatch.c index 2f4e91659e83..723388214541 100644 --- a/src/asahi/vulkan/hk_cmd_dispatch.c +++ b/src/asahi/vulkan/hk_cmd_dispatch.c @@ -708,7 +708,7 @@ hk_cmd_alias_scope(struct hk_cmd_buffer *cmd) { const struct hk_device *dev = hk_cmd_buffer_device(cmd); return hk_cdm_alias_scope(dev) || - (dev->host_alias.dynamic && cmd->state.uses_events); + (dev->host_alias.dynamic && cmd->state.alias_host_wait); } void @@ -742,9 +742,10 @@ hk_cdm_note_alias_site(struct hk_cmd_buffer *cmd, struct hk_cs *cs) .value = dev->host_alias.flush_word, }; cs->alias_sites++; - /* A following application dispatch must not drop the record - * (hk_dispatch_m5_native_impl()). */ + /* A following launch must not drop the record (application + * dispatch barrier elision, hk_tess_batch_stage()). */ cs->app_dispatch_end = NULL; + cs->alias_pin = cs->current; return; } } diff --git a/src/asahi/vulkan/hk_cmd_draw.c b/src/asahi/vulkan/hk_cmd_draw.c index 9121aeefe0ef..47e218632000 100644 --- a/src/asahi/vulkan/hk_cmd_draw.c +++ b/src/asahi/vulkan/hk_cmd_draw.c @@ -3724,15 +3724,17 @@ hk_xfer_order(struct hk_cmd_buffer *cmd, struct hk_cs *cs) } /* Each launch ends in a weak ordering record; strengthen the last one - * into a cache flush, as a barrier does (hk_CmdPipelineBarrier2()). No - * patch site is recorded here (hk_cdm_alias_scope_unpatched()). */ - const bool alias_scope = hk_cdm_alias_scope_unpatched(dev); + * into a cache flush, as a barrier does (hk_CmdPipelineBarrier2()), + * including its patch site. */ + const bool alias_scope = hk_cmd_alias_scope(cmd); for (unsigned i = 0; i < n; ++i) { struct hk_cs *w = flush[i]; if (hk_cdm_visibility_flush_needed(dev, w, alias_scope)) { hk_ensure_cs_has_space(cmd, w, AGX3_CDM_BARRIER_SIZE); hk_cdm_visibility_flush(dev, w, alias_scope); } + if (!alias_scope) + hk_cdm_note_alias_site(cmd, w); } perf_debug(cmd, "Ordering an unsynchronized transfer before graphics"); @@ -14973,14 +14975,15 @@ hk_dispatch_task_kernel(struct hk_cmd_buffer *cmd, struct hk_shader *task, /* The launch ends in a weak ordering record, which doesn't make the * entries visible to the mesh draws that read them; strengthen it into a - * cache flush, as a barrier does, without a patch site - * (hk_cdm_alias_scope_unpatched()). */ + * cache flush, as a barrier does, including its patch site. */ struct hk_device *dev = hk_cmd_buffer_device(cmd); - const bool alias_scope = hk_cdm_alias_scope_unpatched(dev); + const bool alias_scope = hk_cmd_alias_scope(cmd); if (hk_cdm_visibility_flush_needed(dev, ccs, alias_scope)) { hk_ensure_cs_has_space(cmd, ccs, AGX3_CDM_BARRIER_SIZE); hk_cdm_visibility_flush(dev, ccs, alias_scope); } + if (!alias_scope) + hk_cdm_note_alias_site(cmd, ccs); } /* G17P software task stage. The task shader runs as a compute kernel in the diff --git a/src/asahi/vulkan/hk_device.c b/src/asahi/vulkan/hk_device.c index bfb7d6ef4c34..dc90a5a7417f 100644 --- a/src/asahi/vulkan/hk_device.c +++ b/src/asahi/vulkan/hk_device.c @@ -932,11 +932,11 @@ hk_init_g17p_grid_helper(struct hk_device *dev, * features may only be used when they are enabled, so a device that enabled * none of them never has such memory. * - * On M5 every resource through which these features map memory at a second - * address is seen as it is created, so the scope follows the live ones - * instead (host_alias.dynamic, hk_cdm_alias_scope()): buffers and image - * planes with an address of their own (va_alias_resources), fd and dma-buf - * imports, and host imports that may alias (hk_host_import_aliases()). An + * With VA-tagged caches every resource through which these features map + * memory at a second address is seen as it is created, so the scope follows + * the live ones instead (host_alias.dynamic, hk_cdm_alias_scope()): buffers + * and image planes with an address of their own, fd and dma-buf imports, + * and host imports that may alias (hk_host_import_aliases()). An * acceleration structure's address is its buffer's, also on replay, so its * capture/replay is covered by the buffer's. An import of private anonymous * memory of this process (malloc, aligned_alloc, an anonymous private mmap) @@ -1063,9 +1063,10 @@ hk_CreateDevice(VkPhysicalDevice physicalDevice, simple_mtx_init(&dev->host_alias.cmd_lock, mtx_plain); list_inithead(&dev->host_alias.cmd_buffers); u_rwlock_init(&dev->host_alias.patch_lock); - dev->host_alias.trace = agx_chip_g17_m5(pdev->dev.chip) && + /* dev->dev is opened below: the chip comes from pdev. */ + dev->host_alias.trace = hk_va_tagged_caches(pdev->dev.chip) && debug_get_bool_option("ASAHI_M5_HOST_ALIAS_TRACE", false); - if (dev->may_alias_memory && agx_chip_g17_m5(pdev->dev.chip) && + if (dev->may_alias_memory && hk_va_tagged_caches(pdev->dev.chip) && !debug_get_option_m5_host_alias_static()) { /* The word hk_cdm_flush() records for a memory-scoped strong flush. */ const struct agx3_cdm_barrier_info info = { diff --git a/src/asahi/vulkan/hk_device.h b/src/asahi/vulkan/hk_device.h index 8a808c2595a8..08260fafaf17 100644 --- a/src/asahi/vulkan/hk_device.h +++ b/src/asahi/vulkan/hk_device.h @@ -135,25 +135,21 @@ struct hk_device { struct agx_device dev; /* Scratch-filled sparse VA (M5: bounded by sparseAddressSpaceSize). */ uint64_t sparse_scratch_B; - /* Live buffers and image planes with a GPU virtual address of their own - * (sparse binding, bufferDeviceAddressCaptureReplayEXT buffers), atomic - * (hk_device_va_alias_get()). Their memory is also mapped at another - * address, see hk_cdm_alias_scope(). */ - uint32_t va_alias_resources; /* Whether anything this device enabled can map memory at a second GPU * virtual address at any time, decided at creation - * (hk_device_may_alias_memory()). M5 uses it in place of - * va_alias_resources, see hk_cdm_alias_scope(). */ + * (hk_device_may_alias_memory()). Left false with host_alias.dynamic, + * see hk_cdm_alias_scope(). */ bool may_alias_memory; - /* M5 with host_alias.dynamic: live resources through which memory has or - * may have a second GPU address (hk_device_alias_get()), atomic: - * va_alias_resources, fd and dma-buf imports, and host imports that may - * alias. hk_cdm_alias_scope() asks for memory scope while it is not 0. */ + /* With host_alias.dynamic: live resources through which memory has or + * may have a second GPU address (hk_device_alias_get()), atomic: buffers + * and image planes with an address of their own, fd and dma-buf imports, + * and host imports that may alias. hk_cdm_alias_scope() asks for memory + * scope while it is not 0. */ uint32_t alias_live; struct { - /* M5: the device enabled a feature through which memory can get a - * second address, so the scope follows alias_live instead of - * may_alias_memory, which was left false + /* VA-tagged caches (hk_va_tagged_caches()): the device enabled a + * feature through which memory can get a second address, so the scope + * follows alias_live instead of may_alias_memory, which was left false * (hk_device_may_alias_memory()). */ bool dynamic; /* ASAHI_M5_HOST_ALIAS_TRACE=1. */ @@ -459,39 +455,43 @@ enum hk_perftest { #define HK_PERF(dev, flag) unlikely((dev)->perftest &HK_PERF_##flag) -/* G17P and M5 GPU caches are tagged by virtual address, so when memory may be - * mapped at more than one GPU VA an application compute/transfer barrier needs - * the memory-scoped strong flush (hk_cdm_visibility_flush()). +/* Whether the GPU caches are tagged by virtual address (G17P and M5): a + * strong CDM flush then makes a write visible only to reads through the same + * mapping, and a read through a second address of the same memory needs the + * memory-scope flush (hk_cdm_alias_scope()). */ +static inline bool +hk_va_tagged_caches(enum agx_chip chip) +{ + return chip == AGX_CHIP_G17P || agx_chip_g17_m5(chip); +} + +/* With VA-tagged caches, when memory may be mapped at more than one GPU VA an + * application compute/transfer barrier needs the memory-scoped strong flush + * (hk_cdm_visibility_flush()). * - * On M5, devices that enable aliasing-capable features (sparse, + * Devices that enable aliasing-capable features (sparse, * VK_EXT_buffer_device_address capture/replay, fd/dma-buf, writable host - * imports) track active aliasing resources in alias_live under + * imports) track live aliasing resources in alias_live under * host_alias.dynamic (or force memory scope via may_alias_memory / - * ASAHI_M5_HOST_ALIAS_STATIC=1). Barriers recorded while - * alias_live == 0 record patch sites (struct hk_alias_site) that are upgraded - * in place when alias_live leaves 0 or at submission; unpatched paths - * (graphics dependencies, event-using command buffers) and stream-end flushes - * keep memory scope unconditionally while dynamic mode is active. + * ASAHI_M5_HOST_ALIAS_STATIC=1, also on G17P). Barriers recorded while + * alias_live == 0 record patch sites (struct hk_alias_site): the 4-byte + * barrier record, upgraded in place when alias_live leaves 0 or at + * submission. A command buffer that waits for an event the host may set keeps + * memory scope throughout while dynamic mode is active. * - * On G17P, memory scope is selected at barrier recording time whenever - * va_alias_resources != 0 (live sparse, bufferDeviceAddressCaptureReplayEXT - * buffers, fd, or writable host imports). The flush is emitted into an open - * compute stream holding work; earlier closed streams already flushed at - * stream end. + * M5 compute streams end with the memory-scoped flush while dynamic mode is + * active. G17P streams end without it: the end of a G17P command already + * publishes its writes to every address. * - * Not covered on G17P: resources or imports created after command buffer - * recording and reached via device address or UpdateAfterBind descriptors; - * graphics-only sources writing through a sparse image read via a plain alias - * receive only the ordinary post-graphics strong flush (untested). + * Not covered: graphics-only sources writing through a sparse image read via + * a plain alias receive only the ordinary post-graphics strong flush + * (untested). */ static inline bool hk_cdm_alias_scope(const struct hk_device *dev) { - if (agx_chip_g17_m5(dev->dev.chip)) - return dev->may_alias_memory || p_atomic_read(&dev->alias_live); - - return dev->dev.chip == AGX_CHIP_G17P && - p_atomic_read(&dev->va_alias_resources) != 0; + return hk_va_tagged_caches(dev->dev.chip) && + (dev->may_alias_memory || p_atomic_read(&dev->alias_live)); } /* Whether the CDM strong flush has a memory-scoped form, which memory @@ -528,15 +528,6 @@ hk_cdm_caches_pending(const struct hk_device *dev) return dev->dev.chip == AGX_CHIP_G17A; } -/* As hk_cdm_alias_scope(), for an application dependency recorded without a - * patch site (struct hk_alias_site): with host_alias.dynamic always, since - * nothing would give the record memory scope once a resource may alias. */ -static inline bool -hk_cdm_alias_scope_unpatched(const struct hk_device *dev) -{ - return hk_cdm_alias_scope(dev) || dev->host_alias.dynamic; -} - /* Writes the patch sites of every executable command buffer that has * unwritten ones (host_alias.cmd_buffers), when the first resource that may * alias appears. Returns how many command buffers it wrote. */ @@ -596,22 +587,6 @@ hk_device_alias_put(struct hk_device *dev, uint32_t n) p_atomic_add(&dev->alias_live, -(int32_t)n); } -/* A buffer, image plane or memory object that maps memory at a GPU address - * of its own (va_alias_resources), from its creation to its destruction. */ -static inline void -hk_device_va_alias_get(struct hk_device *dev, enum hk_alias_cause cause) -{ - p_atomic_inc(&dev->va_alias_resources); - hk_device_alias_get(dev, 1, cause); -} - -static inline void -hk_device_va_alias_put(struct hk_device *dev) -{ - p_atomic_dec(&dev->va_alias_resources); - hk_device_alias_put(dev, 1); -} - /* At submission, while an import may alias: writes the patch sites of the * submitted command buffers, before submit packing copies their streams. */ void hk_submit_patch_alias_sites(struct hk_device *dev, diff --git a/src/asahi/vulkan/hk_device_memory.c b/src/asahi/vulkan/hk_device_memory.c index a019c6b9a9a4..10accc6a8d49 100644 --- a/src/asahi/vulkan/hk_device_memory.c +++ b/src/asahi/vulkan/hk_device_memory.c @@ -301,7 +301,7 @@ hk_host_maps_classify_self(const void *pointer, uint64_t size) return cls; } -/* M5 with host_alias.dynamic: enter a host import into the device's set, so +/* With host_alias.dynamic: enter a host import into the device's set, so * hk_cdm_alias_scope() asks for memory scope while it may alias * (hk_host_import_aliases()). A GPU-writable import of pages that are all * private anonymous memory of this process (/proc/self/maps), and that no @@ -327,7 +327,7 @@ hk_host_import_track(struct hk_device *dev, struct hk_device_memory *mem, if (!dev->host_alias.dynamic) { /* Under the per-device rule nothing is tracked; say the import * happened, so a trace shows whether an application imports at all. */ - if (agx_chip_g17_m5(dev->dev.chip) && debug_get_option_m5_host_alias_trace()) + if (hk_va_tagged_caches(dev->dev.chip) && debug_get_option_m5_host_alias_trace()) fprintf(stderr, "M5_HOST_ALIAS import %p+%#" PRIx64 " (per-device rule)\n", pointer, size); return VK_SUCCESS; @@ -509,7 +509,6 @@ hk_AllocateMemory(VkDevice device, const VkMemoryAllocateInfo *pAllocateInfo, goto fail_alloc; } assert(!(flags & ~mem->bo->flags)); - mem->alias_import = true; } else if (host_info && host_info->handleType) { /* The pointer and the size are multiples of * minImportedHostPointerAlignment (VUID-VkImportMemoryHostPointerInfoEXT- @@ -521,7 +520,7 @@ hk_AllocateMemory(VkDevice device, const VkMemoryAllocateInfo *pAllocateInfo, * hk_host_memory_read_only. With hk_host_memory_import_read_only only * such a range is taken, and a range the kernel can pin for writing is * refused, also with hk_host_memory_read_only: the GPU then writes - * through no host import (hk_cdm_alias_scope()). Otherwise, on M5, + * through no host import (hk_cdm_alias_scope()). Otherwise * hk_host_import_track() decides below whether this import may alias. */ assert(host_info->handleType == @@ -547,7 +546,6 @@ hk_AllocateMemory(VkDevice device, const VkMemoryAllocateInfo *pAllocateInfo, host_info->pHostPointer, strerror(err)); goto fail_alloc; } - mem->alias_import = access != AGX_HOST_PTR_READ_ONLY; } else { enum agx_bo_flags flags = 0; if (handle_types) @@ -658,9 +656,6 @@ hk_AllocateMemory(VkDevice device, const VkMemoryAllocateInfo *pAllocateInfo, if (mem->bo->flags & (AGX_BO_SHAREABLE | AGX_BO_SHARED)) hk_add_ext_bo(dev, mem->bo); - if (mem->alias_import) - p_atomic_inc(&dev->va_alias_resources); - if (priority_info) hk_set_memory_priority(dev, mem, priority_info->priority); @@ -764,9 +759,6 @@ hk_FreeMemory(VkDevice device, VkDeviceMemory _mem, /* The BO may outlive this object in the BO cache. */ hk_set_memory_priority(dev, mem, 0.5f); - if (mem->alias_import) - p_atomic_dec(&dev->va_alias_resources); - /* No work that may still run reaches this memory any more. */ hk_host_import_untrack(dev, mem); if (mem->alias_fd) diff --git a/src/asahi/vulkan/hk_device_memory.h b/src/asahi/vulkan/hk_device_memory.h index 616622d34c30..004d9b1c1cca 100644 --- a/src/asahi/vulkan/hk_device_memory.h +++ b/src/asahi/vulkan/hk_device_memory.h @@ -37,11 +37,7 @@ struct hk_device_memory { /* Residency preference the kernel accepted (memory priority 1.0). */ bool keep_resident; - /* An import the GPU may write that another import can map at a second - * address too: counted in hk_device::va_alias_resources while it lives. */ - bool alias_import; - - /* A host import in hk_device::host_alias.imports (M5, host_alias.dynamic). */ + /* A host import in hk_device::host_alias.imports (host_alias.dynamic). */ bool host_alias_tracked; /* An fd or dma-buf import, counted in hk_device::alias_live for its * lifetime (hk_device_alias_get()). */ diff --git a/src/asahi/vulkan/hk_event.c b/src/asahi/vulkan/hk_event.c index d2b52ee2eb06..e1c2d4c69633 100644 --- a/src/asahi/vulkan/hk_event.c +++ b/src/asahi/vulkan/hk_event.c @@ -149,15 +149,17 @@ hk_CmdSetEvent2(VkCommandBuffer commandBuffer, VkEvent _event, /* The wait orders later work behind this stream's source work, but on * G17P and M5 a read through another address of the same memory also * needs the source writes flushed with memory scope - * (hk_cdm_alias_scope()). A command buffer that uses events records no - * patch site for a later host import: it has the scope whenever an - * import could add such an address (hk_cmd_alias_scope()). */ + * (hk_cdm_alias_scope()). Where only a resource created later could + * map it there, the stream's last record is a patch site instead. */ struct hk_device *dev = hk_cmd_buffer_device(cmd); struct hk_cs *cs = cmd->current_cs.cs; - if (cs && (src_kinds & (HK_SYNC_COMPUTE | HK_SYNC_XFER)) && - hk_cmd_alias_scope(cmd) && hk_cdm_visibility_flush_needed(dev, cs, true)) { - hk_ensure_cs_has_space(cmd, cs, AGX3_CDM_BARRIER_SIZE); - hk_cdm_visibility_flush(dev, cs, true); + if (cs && (src_kinds & (HK_SYNC_COMPUTE | HK_SYNC_XFER))) { + if (!hk_cmd_alias_scope(cmd)) { + hk_cdm_note_alias_site(cmd, cs); + } else if (hk_cdm_visibility_flush_needed(dev, cs, true)) { + hk_ensure_cs_has_space(cmd, cs, AGX3_CDM_BARRIER_SIZE); + hk_cdm_visibility_flush(dev, cs, true); + } } /* A host access in this dependency is made available before the status @@ -181,6 +183,35 @@ hk_CmdResetEvent2(VkCommandBuffer commandBuffer, VkEvent _event, hk_event_write(cmd, event, hk_sync_kinds_src(stageMask), VK_EVENT_RESET); } +/* Whether a wait may be on an event set by vkSetEvent. Its barriers must then + * hold only host operations in their first synchronization scope + * (VUID-vkCmdWaitEvents2-pEvents-03839, + * VUID-vkCmdWaitEvents-srcStageMask-01158): no barriers at all, or barriers + * whose srcStageMask is HOST or NONE. Only a source stage on the device, with + * no HOST beside it, rules the host out. */ +static bool +hk_dependency_waits_for_host(const VkDependencyInfo *info) +{ + const VkPipelineStageFlags2 host = VK_PIPELINE_STAGE_2_HOST_BIT; + VkPipelineStageFlags2 src = 0; + for (uint32_t i = 0; i < info->memoryBarrierCount; ++i) { + if (info->pMemoryBarriers[i].srcStageMask & host) + return true; + src |= info->pMemoryBarriers[i].srcStageMask; + } + for (uint32_t i = 0; i < info->bufferMemoryBarrierCount; ++i) { + if (info->pBufferMemoryBarriers[i].srcStageMask & host) + return true; + src |= info->pBufferMemoryBarriers[i].srcStageMask; + } + for (uint32_t i = 0; i < info->imageMemoryBarrierCount; ++i) { + if (info->pImageMemoryBarriers[i].srcStageMask & host) + return true; + src |= info->pImageMemoryBarriers[i].srcStageMask; + } + return src == VK_PIPELINE_STAGE_2_NONE; +} + /* A wait polls the event word on the GPU, so a later host vkSetEvent is * honoured. A poll whose set never comes hangs the queue, which only G17P * recovers from; elsewhere the wait is the plain barrier below. */ @@ -201,6 +232,11 @@ hk_CmdWaitEvents2(VkCommandBuffer commandBuffer, uint32_t eventCount, cmd->state.uses_events = true; perf_debug(cmd, "Wait events"); + /* An event the host sets (hk_cmd_alias_scope()). */ + for (uint32_t i = 0; i < eventCount; ++i) + cmd->state.alias_host_wait |= + hk_dependency_waits_for_host(&pDependencyInfos[i]); + for (uint32_t i = 0; i < eventCount; ++i) { VK_FROM_HANDLE(hk_event, event, pEvents[i]); assert(pDependencyInfos[i].sType == VK_STRUCTURE_TYPE_DEPENDENCY_INFO); diff --git a/src/asahi/vulkan/hk_image.c b/src/asahi/vulkan/hk_image.c index 1c56f907304f..4f84ff3f6618 100644 --- a/src/asahi/vulkan/hk_image.c +++ b/src/asahi/vulkan/hk_image.c @@ -1752,7 +1752,7 @@ hk_image_plane_alloc_vma(struct hk_device *dev, struct hk_image_plane *plane, /* Bound memory is reached through this plane's own address as well * (hk_cdm_alias_scope()); hk_image_plane_finish() drops the count, * also when a later step of the image's creation fails. */ - hk_device_va_alias_get(dev, HK_ALIAS_CAUSE_SPARSE); + hk_device_alias_get(dev, 1, HK_ALIAS_CAUSE_SPARSE); } if (sparse_resident) { @@ -1805,7 +1805,7 @@ hk_image_plane_finish(struct hk_device *dev, struct hk_image_plane *plane, if (plane->va) { agx_va_free(&dev->dev, plane->va, true); plane->va = NULL; - hk_device_va_alias_put(dev); + hk_device_alias_put(dev, 1); } hk_release_sparse_scratch(dev, plane->sparse_scratch_B); plane->sparse_scratch_B = 0; diff --git a/src/asahi/vulkan/hk_nir_tile_byte_stencil.c b/src/asahi/vulkan/hk_nir_tile_byte_stencil.c index 8a78db91f3c9..237a07eec594 100644 --- a/src/asahi/vulkan/hk_nir_tile_byte_stencil.c +++ b/src/asahi/vulkan/hk_nir_tile_byte_stencil.c @@ -2766,11 +2766,12 @@ hk_byte_stencil_validate_dispatch(const struct hk_device *dev, return false; /* Guarantee 1:1 physical-to-VA mapping across all writable buffers so VA - * disjointness implies physical non-aliasing. */ + * disjointness implies physical non-aliasing: no live resource gives + * memory a second address. With host_alias.dynamic, alias_live counts + * them and may_alias_memory is false; without it, may_alias_memory says + * whether the device enabled anything that can. */ const bool alias_free = - p_atomic_read(&dev->va_alias_resources) == 0 && - p_atomic_read(&dev->alias_live) == 0 && - !hk_cdm_alias_scope(dev); + !dev->may_alias_memory && p_atomic_read(&dev->alias_live) == 0; return hk_byte_stencil_validate_dispatch_core( alias_free, desc, plan, base_x, base_y, base_z, groups_x, groups_y, diff --git a/src/asahi/vulkan/hk_tess_batch.c b/src/asahi/vulkan/hk_tess_batch.c index 94e7f1f6bd91..e6458371e3bd 100644 --- a/src/asahi/vulkan/hk_tess_batch.c +++ b/src/asahi/vulkan/hk_tess_batch.c @@ -51,7 +51,8 @@ hk_tess_batch_stage(struct hk_cmd_buffer *cmd, enum hk_tess_stage stage) /* Before the tail goes: a chunk link must still follow a barrier. */ hk_ensure_cs_has_space(cmd, cs, 0x2000); - if (cs->stats.cmds && cs->current == cs->weak_barrier_end) { + if (cs->stats.cmds && cs->current == cs->weak_barrier_end && + cs->current != cs->alias_pin) { batch->dropped[stage] = cs->current; cs->current = (uint8_t *)cs->current - AGX3_CDM_BARRIER_SIZE; cs->weak_barrier_end = NULL; diff --git a/src/asahi/vulkan/meson.build b/src/asahi/vulkan/meson.build index c34849135315..dfaaa1eff77b 100644 --- a/src/asahi/vulkan/meson.build +++ b/src/asahi/vulkan/meson.build @@ -1304,6 +1304,15 @@ if with_tests gnu_symbol_visibility : 'hidden', ) + hk_vulkan_event_alias = executable( + 'brl-vulkan-event-alias', + files('tests/hk_vulkan_event_alias.c'), + include_directories : [inc_include], + dependencies : [cc.find_library('vulkan')], + c_args : [c_msvc_compat_args], + gnu_symbol_visibility : 'hidden', + ) + hk_vulkan_sparse_bind_first_submit = executable( 'hk-vulkan-sparse-bind-first-submit', files('tests/hk_vulkan_sparse_bind_first_submit.c'), diff --git a/src/asahi/vulkan/tests/hk_vulkan_event_alias.c b/src/asahi/vulkan/tests/hk_vulkan_event_alias.c new file mode 100644 index 000000000000..467c22664969 --- /dev/null +++ b/src/asahi/vulkan/tests/hk_vulkan_event_alias.c @@ -0,0 +1,249 @@ +/* Copyright 2026 Aurora Silicon + * SPDX-License-Identifier: MIT + * + * A command buffer that waits for an event the host sets must take memory + * scope throughout at vkEndCommandBuffer on G17P and M5: memory that first + * aliases while it waits is too late to patch, the CDM may have read the + * records past the wait. A vkSetEvent wait may have no barriers at all, or + * barriers with no source stage (VUID-vkCmdWaitEvents2-pEvents-03839). Each + * case records transfer work, the wait and a barrier, ends the command + * buffer, then creates a sparse buffer so that memory first aliases after + * recording. The driver's alias trace says how many command buffers were + * still waiting for that to be patched: none for a host wait, the one + * recorded for an event the device sets. Nothing + * executes on the GPU, so the test runs under the no-op DRM shim. + */ +#include +#include +#include +#include +#include +#include + +#define CHECK(call) \ + do { \ + VkResult r_ = (call); \ + if (r_ != VK_SUCCESS) { \ + fprintf(stderr, "FAIL: %s: %d\n", #call, r_); \ + exit(1); \ + } \ + } while (0) + +static VkDevice dev; +static VkQueue queue; +static VkCommandPool pool; +static VkBuffer dst; +static VkEvent event; + +enum wait_kind { WAIT_EMPTY, WAIT_NONE_STAGE, WAIT_HOST_STAGE, WAIT_DEVICE_SET }; + +static const VkMemoryBarrier2 xfer_barrier = { + .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2, + .srcStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT, + .srcAccessMask = VK_ACCESS_2_TRANSFER_WRITE_BIT, + .dstStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT, + .dstAccessMask = VK_ACCESS_2_TRANSFER_READ_BIT | VK_ACCESS_2_TRANSFER_WRITE_BIT, +}; +static const VkMemoryBarrier2 host_barrier = { + .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2, + .srcStageMask = VK_PIPELINE_STAGE_2_HOST_BIT, + .srcAccessMask = VK_ACCESS_2_HOST_WRITE_BIT, + .dstStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT, + .dstAccessMask = VK_ACCESS_2_TRANSFER_READ_BIT | VK_ACCESS_2_TRANSFER_WRITE_BIT, +}; + +/* An empty first scope also holds only host operations. */ +static const VkMemoryBarrier2 none_barrier = { + .sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2, + .srcStageMask = VK_PIPELINE_STAGE_2_NONE, + .dstStageMask = VK_PIPELINE_STAGE_2_TRANSFER_BIT, + .dstAccessMask = VK_ACCESS_2_TRANSFER_READ_BIT | VK_ACCESS_2_TRANSFER_WRITE_BIT, +}; + +static VkDependencyInfo +dep(const VkMemoryBarrier2 *b) +{ + return (VkDependencyInfo){ + .sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO, + .memoryBarrierCount = b ? 1 : 0, + .pMemoryBarriers = b, + }; +} + +/* Records and ends the case, then returns the patched= count the trace + * reports when the first aliasing resource appears. */ +static unsigned +run_case(enum wait_kind kind) +{ + VkCommandBuffer cb; + const VkCommandBufferAllocateInfo cai = { + .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, + .commandPool = pool, + .level = VK_COMMAND_BUFFER_LEVEL_PRIMARY, + .commandBufferCount = 1, + }; + CHECK(vkAllocateCommandBuffers(dev, &cai, &cb)); + const VkCommandBufferBeginInfo bi = { + .sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, + }; + CHECK(vkBeginCommandBuffer(cb, &bi)); + + vkCmdFillBuffer(cb, dst, 0, 4096, 1); + const VkDependencyInfo xfer = dep(&xfer_barrier); + VkDependencyInfo wait = dep(NULL); + if (kind == WAIT_NONE_STAGE) + wait = dep(&none_barrier); + if (kind == WAIT_HOST_STAGE) + wait = dep(&host_barrier); + if (kind == WAIT_DEVICE_SET) { + vkCmdSetEvent2(cb, event, &xfer); + wait = xfer; + } + vkCmdWaitEvents2(cb, 1, &event, &wait); + vkCmdPipelineBarrier2(cb, &xfer); + vkCmdFillBuffer(cb, dst, 4096, 4096, 2); + vkCmdPipelineBarrier2(cb, &xfer); + vkCmdFillBuffer(cb, dst, 8192, 4096, 3); + CHECK(vkEndCommandBuffer(cb)); + + /* The first aliasing resource, after recording; the trace goes to stderr. */ + fflush(stderr); + FILE *log = tmpfile(); + const int saved = dup(2); + if (!log || saved < 0 || dup2(fileno(log), 2) < 0) { + fprintf(stderr, "FAIL: redirect stderr\n"); + exit(1); + } + const VkBufferCreateInfo sbi = { + .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, + .flags = VK_BUFFER_CREATE_SPARSE_BINDING_BIT, + .size = 1 << 20, + .usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, + }; + VkBuffer sparse; + const VkResult r = vkCreateBuffer(dev, &sbi, NULL, &sparse); + fflush(stderr); + dup2(saved, 2); + close(saved); + CHECK(r); + + unsigned patched = ~0u; + char line[256]; + rewind(log); + while (fgets(line, sizeof(line), log)) { + if (sscanf(line, "M5_HOST_ALIAS began cause=sparse patched=%u", + &patched) == 1) + break; + } + fclose(log); + + if (kind != WAIT_DEVICE_SET) + CHECK(vkSetEvent(dev, event)); + vkDestroyBuffer(dev, sparse, NULL); + vkFreeCommandBuffers(dev, pool, 1, &cb); + CHECK(vkResetEvent(dev, event)); + return patched; +} + +int +main(void) +{ + setenv("ASAHI_M5_HOST_ALIAS_TRACE", "1", 1); + + const VkApplicationInfo app = { + .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, + .apiVersion = VK_API_VERSION_1_3, + }; + const VkInstanceCreateInfo ici = { + .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, + .pApplicationInfo = &app, + }; + VkInstance inst; + CHECK(vkCreateInstance(&ici, NULL, &inst)); + uint32_t n = 1; + VkPhysicalDevice pdev; + const VkResult er = vkEnumeratePhysicalDevices(inst, &n, &pdev); + if ((er != VK_SUCCESS && er != VK_INCOMPLETE) || n == 0) { + fprintf(stderr, "FAIL: no physical device\n"); + return 1; + } + + VkPhysicalDeviceFeatures supported; + vkGetPhysicalDeviceFeatures(pdev, &supported); + if (!supported.sparseBinding) { + printf("SKIP: no sparseBinding\n"); + return 77; + } + + const float priority = 1.0f; + const VkDeviceQueueCreateInfo qi = { + .sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO, + .queueCount = 1, + .pQueuePriorities = &priority, + }; + const VkPhysicalDeviceVulkan13Features f13 = { + .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_3_FEATURES, + .synchronization2 = VK_TRUE, + }; + const VkPhysicalDeviceFeatures f = {.sparseBinding = VK_TRUE}; + const VkDeviceCreateInfo dci = { + .sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, + .pNext = &f13, + .queueCreateInfoCount = 1, + .pQueueCreateInfos = &qi, + .pEnabledFeatures = &f, + }; + CHECK(vkCreateDevice(pdev, &dci, NULL, &dev)); + vkGetDeviceQueue(dev, 0, 0, &queue); + + const VkCommandPoolCreateInfo pci = { + .sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO, + }; + CHECK(vkCreateCommandPool(dev, &pci, NULL, &pool)); + const VkEventCreateInfo eci = {.sType = VK_STRUCTURE_TYPE_EVENT_CREATE_INFO}; + CHECK(vkCreateEvent(dev, &eci, NULL, &event)); + + const VkBufferCreateInfo bci = { + .sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, + .size = 16384, + .usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT, + }; + CHECK(vkCreateBuffer(dev, &bci, NULL, &dst)); + VkMemoryRequirements req; + vkGetBufferMemoryRequirements(dev, dst, &req); + const VkMemoryAllocateInfo mai = { + .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .allocationSize = req.size, + .memoryTypeIndex = __builtin_ctz(req.memoryTypeBits), + }; + VkDeviceMemory mem; + CHECK(vkAllocateMemory(dev, &mai, NULL, &mem)); + CHECK(vkBindBufferMemory(dev, dst, mem, 0)); + + static const struct { + enum wait_kind kind; + const char *name; + unsigned patched; + } cases[] = { + {WAIT_EMPTY, "host event, no barriers", 0}, + {WAIT_NONE_STAGE, "host event, NONE srcStageMask", 0}, + {WAIT_HOST_STAGE, "host event, HOST in srcStageMask", 0}, + {WAIT_DEVICE_SET, "event set by vkCmdSetEvent2", 1}, + }; + int fails = 0; + for (unsigned i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) { + const unsigned patched = run_case(cases[i].kind); + const bool ok = patched == cases[i].patched; + printf("%s: %s: patched=%d, want %u\n", ok ? "ok" : "FAIL", + cases[i].name, (int)patched, cases[i].patched); + fails += !ok; + } + + vkDestroyBuffer(dev, dst, NULL); + vkFreeMemory(dev, mem, NULL); + vkDestroyEvent(dev, event, NULL); + vkDestroyCommandPool(dev, pool, NULL); + vkDestroyDevice(dev, NULL); + vkDestroyInstance(inst, NULL); + return fails ? 1 : 0; +} diff --git a/src/asahi/vulkan/tests/test-hk-execution-allowance.c b/src/asahi/vulkan/tests/test-hk-execution-allowance.c index 19601cff83d0..173a233cbad0 100644 --- a/src/asahi/vulkan/tests/test-hk-execution-allowance.c +++ b/src/asahi/vulkan/tests/test-hk-execution-allowance.c @@ -20,15 +20,6 @@ hk_cmd_buffer_emit_cs_jump(struct hk_cmd_buffer *cmd, void *current, return (uint8_t *)current + AGX_CDM_STREAM_LINK_LENGTH; } -/* The streams here record no alias sites (hk_cs::alias_sites stays zero), so - * the merge never moves any. */ -void -hk_cmd_buffer_move_alias_sites(struct hk_cmd_buffer *cmd, const void *from, - const void *from_end, uint8_t *to, size_t skip) -{ - assert(!"no alias sites are recorded"); -} - /* Merged streams here record no attachments; with more than one merge call * the compiler keeps hk_cs_merge_cdm() out of line, with its attachment loop. */ bool @@ -112,6 +103,52 @@ init_opener(struct hk_cs *cs, uint8_t *bytes, size_t size, bool memory, } } +/* Patch sites and the pin move with the words an inline merge copies; a site + * on b's folded opening barrier moves to a's trailing record, and a pin on + * a's tail stays where b adds nothing after it. */ +static void +check_merge_alias_sites(void) +{ + static struct hk_cmd_buffer cmd; + uint8_t a_bytes[HK_CS_SPACE_PADDING + 256], b_bytes[64]; + struct hk_cs a, b; + uint8_t *a_tail = a_bytes + LAUNCH_BYTES; + + init_tail(&a, a_bytes, sizeof(a_bytes), false); + init_opener(&b, b_bytes, sizeof(b_bytes), false, true); + agx3_cmdstream_store_le32(b_bytes + AGX3_CDM_BARRIER_SIZE + LAUNCH_BYTES, + plain_flush); + b.current = b_bytes + 2 * AGX3_CDM_BARRIER_SIZE + LAUNCH_BYTES; + b.strong_flush_end = b.alias_pin = b.current; + a.cmd = b.cmd = &cmd; + b.alias_sites = 2; + cmd.alias_sites = UTIL_DYNARRAY_INIT; + const struct hk_alias_site opener = {(uint32_t *)b_bytes, memory_flush}; + const struct hk_alias_site flush = { + (uint32_t *)(b_bytes + AGX3_CDM_BARRIER_SIZE + LAUNCH_BYTES), + memory_flush}; + util_dynarray_append(&cmd.alias_sites, opener); + util_dynarray_append(&cmd.alias_sites, flush); + hk_cs_merge_cdm(&a, &b); + + const struct hk_alias_site *sites = cmd.alias_sites.data; + assert((uint8_t *)sites[0].word == a_tail); + assert((uint8_t *)sites[1].word == + a_tail + AGX3_CDM_BARRIER_SIZE + LAUNCH_BYTES); + assert(word_at(sites[1].word) == plain_flush); + assert((uint8_t *)a.alias_pin == + (uint8_t *)sites[1].word + AGX3_CDM_BARRIER_SIZE); + assert(a.alias_sites == 2); + util_dynarray_fini(&cmd.alias_sites); + + init_tail(&a, a_bytes, sizeof(a_bytes), false); + init_opener(&b, b_bytes, sizeof(b_bytes), false, false); + a.cmd = b.cmd = &cmd; + a.alias_pin = a.current; + hk_cs_merge_cdm(&a, &b); + assert(a.alias_pin == a.current); +} + static void check_merge_memory_scope(void) { @@ -238,5 +275,6 @@ int main(void) for (unsigned link = 0; link < 2; ++link) check_merge(a, b, link); check_merge_memory_scope(); + check_merge_alias_sites(); return 0; } diff --git a/src/asahi/vulkan/tests/test-hk-tess-batch.c b/src/asahi/vulkan/tests/test-hk-tess-batch.c index a7119824718f..3a004eb695c9 100644 --- a/src/asahi/vulkan/tests/test-hk-tess-batch.c +++ b/src/asahi/vulkan/tests/test-hk-tess-batch.c @@ -73,15 +73,6 @@ hk_cmd_buffer_emit_cs_jump(struct hk_cmd_buffer *cmd, void *current, return (uint8_t *)current + AGX_CDM_STREAM_LINK_LENGTH; } -/* The streams here record no alias sites (hk_cs::alias_sites stays zero), so - * the merge never moves any. */ -void -hk_cmd_buffer_move_alias_sites(struct hk_cmd_buffer *cmd, const void *from, - const void *from_end, uint8_t *to, size_t skip) -{ - assert(!"no alias sites are recorded"); -} - /* As the driver's: move to a new chunk through a link when the space does * not fit. */ void @@ -392,6 +383,19 @@ main(void) stage_major(r, n, 0, 3, 0) && count(r, n, WEAK) == 0 && link_ok && pre->stream_linked); + /* A patch site at a stage's tail (hk_cdm_note_alias_site()) stays: the + * next draw's launch goes after it. */ + cmd = new_cmd(); + pre = open_pre_gfx(cmd); + record_draw(cmd, 0, 0); + struct hk_cs *pinned = cmd->tess_batch.stages[HK_TESS_STAGE_VS]; + pinned->alias_pin = pinned->current; + record_draw(cmd, 1, 0); + hk_tess_batch_flush(cmd); + n = decode(pre, r, MAX_RECORDS, &link_ok); + T("patch site: kept", n > 2 && r[0] == (LAUNCH | HK_TESS_STAGE_VS) && + r[1] == WEAK && count(r, n, WEAK) == 1); + /* Other pre-graphics work splits the batch: it follows the tessellation * of the draws before it and precedes that of the draws after it. */ cmd = new_cmd();