diff --git a/src/asahi/lib/agx_device.c b/src/asahi/lib/agx_device.c index 6a259577ade7..a72f0d0d51a3 100644 --- a/src/asahi/lib/agx_device.c +++ b/src/asahi/lib/agx_device.c @@ -977,6 +977,7 @@ agx_cleanup_partial_device(struct agx_device *dev, unsigned initialized) util_sparse_array_finish(&dev->bo_map); simple_mtx_destroy(&dev->bo_cache.lock); simple_mtx_destroy(&dev->bo_map_lock); + simple_mtx_destroy(&dev->bo_mmap_lock); agxdecode_destroy_context(dev->agxdecode); } if (initialized & AGX_INIT_VIRTIO) { @@ -1346,6 +1347,7 @@ agx_open_device(void *memctx, struct agx_device *dev) util_sparse_array_init(&dev->bo_map, sizeof(struct agx_bo), 512); simple_mtx_init(&dev->bo_map_lock, mtx_plain); + simple_mtx_init(&dev->bo_mmap_lock, mtx_plain); simple_mtx_init(&dev->bo_cache.lock, mtx_plain); list_inithead(&dev->bo_cache.lru); diff --git a/src/asahi/lib/agx_device.h b/src/asahi/lib/agx_device.h index cc9297a30fe0..9b0dba49537e 100644 --- a/src/asahi/lib/agx_device.h +++ b/src/asahi/lib/agx_device.h @@ -242,6 +242,8 @@ struct agx_device { simple_mtx_t bo_map_lock; struct util_sparse_array bo_map; + /* Held while agx_bo_map_placed() maps a BO or moves its mapping. */ + simple_mtx_t bo_mmap_lock; /* Exclusive upper bound for every loop over bo_map. */ uint32_t max_handle; @@ -387,24 +389,54 @@ agx_bo_map_placed(struct agx_bo *bo, void *fixed_addr, size_t length) if (bo->flags & AGX_BO_HOST_PTR) return fixed_addr && fixed_addr != bo->_map ? NULL : bo->_map; - /* The BO cache deliberately preserves CPU mappings. A Vulkan allocation - * may therefore inherit a mapping from an earlier allocation even though - * the new VkDeviceMemory object has never been mapped. A placed map must - * move that stale process mapping to the application's reserved address; - * returning it would violate VK_EXT_map_memory_placed. - * - * Keep ordinary mapping reuse unchanged. Only the explicit placed-map - * contract is allowed to relocate an existing BO mapping. */ - if (fixed_addr && bo->_map && bo->_map != fixed_addr) { - bo->dev->ops.bo_munmap(bo->dev, bo); - bo->_map = NULL; - bo->_map_size = 0; + void *map = p_atomic_read(&bo->_map); + if (map && (!fixed_addr || map == fixed_addr)) + return map; + + /* Threads that share a BO can map it for the first time at once (two + * contexts mapping one resource), and each would install its own mapping + * over the other's and leak it. So the mapping is made, or moved, under + * the device's lock and checked again there. On a backend with + * bo_mmap_independent it is made into a copy of the BO and published + * after its size, so a thread that finds it without the lock above finds + * it whole, never a failed mapping. A backend without it is only allowed + * to map the BO itself, so it maps the BO in place under the lock. */ + simple_mtx_lock(&bo->dev->bo_mmap_lock); + map = bo->_map; + if (!map || (fixed_addr && map != fixed_addr)) { + /* The BO cache deliberately preserves CPU mappings. A Vulkan + * allocation may therefore inherit a mapping from an earlier allocation + * even though the new VkDeviceMemory object has never been mapped. A + * placed map must move that stale process mapping to the application's + * reserved address; returning it would violate + * VK_EXT_map_memory_placed. + * + * Keep ordinary mapping reuse unchanged. Only the explicit placed-map + * contract is allowed to relocate an existing BO mapping. */ + if (map) { + bo->dev->ops.bo_munmap(bo->dev, bo); + p_atomic_set(&bo->_map, NULL); + bo->_map_size = 0; + } + + if (bo->dev->ops.bo_mmap_independent) { + struct agx_bo copy = *bo; + copy._map = NULL; + copy._map_size = 0; + bo->dev->ops.bo_mmap(bo->dev, ©, fixed_addr, + fixed_addr ? length : 0); + map = copy._map; + bo->_map_size = copy._map_size; + p_atomic_set(&bo->_map, map); + } else { + bo->dev->ops.bo_mmap(bo->dev, bo, fixed_addr, + fixed_addr ? length : 0); + map = bo->_map; + } } + simple_mtx_unlock(&bo->dev->bo_mmap_lock); - if (!bo->_map) - bo->dev->ops.bo_mmap(bo->dev, bo, fixed_addr, fixed_addr ? length : 0); - - return bo->_map; + return map; } static inline void * diff --git a/src/asahi/vulkan/hk_device_memory.c b/src/asahi/vulkan/hk_device_memory.c index 05d00e95c7b5..fb68e33d1119 100644 --- a/src/asahi/vulkan/hk_device_memory.c +++ b/src/asahi/vulkan/hk_device_memory.c @@ -469,6 +469,21 @@ hk_AllocateMemory(VkDevice device, const VkMemoryAllocateInfo *pAllocateInfo, result = vk_error(dev, VK_ERROR_INVALID_EXTERNAL_HANDLE); goto fail_alloc; } + + /* Every byte of allocationSize must be backed by the imported object. + * An image bound to the memory is checked against the BO + * (hk_image_plane_bind()), but a buffer may use the whole of + * allocationSize, which would then run past the BO. */ + if (mem->bo->size < pAllocateInfo->allocationSize) { + result = vk_errorf(dev, VK_ERROR_INVALID_EXTERNAL_HANDLE, + "allocationSize %" PRIu64 " exceeds the imported " + "object (%" PRIu64 " bytes)", + (uint64_t)pAllocateInfo->allocationSize, + (uint64_t)mem->bo->size); + agx_bo_unreference(&dev->dev, mem->bo); + mem->bo = NULL; + goto fail_alloc; + } assert(!(flags & ~mem->bo->flags)); mem->alias_import = true; } else if (host_info && host_info->handleType) { @@ -663,6 +678,46 @@ hk_AllocateMemory(VkDevice device, const VkMemoryAllocateInfo *pAllocateInfo, return result; } +/* The CPU mapping that host image copies of this memory go through. + * + * It is this object's own mapping of the whole BO (agx_bo_map_owned()), made + * at the first copy and kept until vkFreeMemory. The application's + * vkMapMemory2 and vkUnmapMemory2 of the memory, which may run on other + * threads while copies do, map, move and unmap only the BO's shared mapping + * or their own, so they never touch the one a copy is using. + * + * Host image copies need no external synchronization on the memory, so two + * threads can make the mapping at once: the first one installed is kept and + * the other is unmapped. Host memory stays where the application put it, and + * a backend that cannot map a BO twice has only the shared mapping; copies + * use the BO's shared mapping there. NULL if the BO cannot be mapped. + */ +void * +hk_device_memory_copy_map(struct hk_device_memory *mem) +{ + void *map = p_atomic_read(&mem->copy_map); + if (map) + return map; + + if (!mem->bo->dev->ops.bo_mmap_independent || + (mem->bo->flags & AGX_BO_HOST_PTR)) { + map = agx_bo_map(mem->bo); + } else { + size_t size; + map = agx_bo_map_owned(mem->bo, NULL, 0, &size); + if (map == NULL) + return NULL; + + void *installed = p_atomic_cmpxchg(&mem->copy_map, NULL, map); + if (installed != NULL) { + agx_bo_unmap_owned(mem->bo, map, size); + return installed; + } + } + + return map; +} + VKAPI_ATTR void VKAPI_CALL hk_FreeMemory(VkDevice device, VkDeviceMemory _mem, const VkAllocationCallbacks *pAllocator) @@ -687,6 +742,8 @@ hk_FreeMemory(VkDevice device, VkDeviceMemory _mem, * the BO; an owned one belongs to this object alone. */ if (mem->map_owned) agx_bo_unmap_owned(mem->bo, mem->map, mem->map_size); + if (mem->copy_map) + agx_bo_unmap_owned(mem->bo, mem->copy_map, mem->bo->size); /* The BO may outlive this object in the BO cache. */ hk_set_memory_priority(dev, mem, 0.5f); diff --git a/src/asahi/vulkan/hk_device_memory.h b/src/asahi/vulkan/hk_device_memory.h index f304853531de..809e3e65d512 100644 --- a/src/asahi/vulkan/hk_device_memory.h +++ b/src/asahi/vulkan/hk_device_memory.h @@ -39,6 +39,11 @@ struct hk_device_memory { size_t map_size; bool map_owned; + /* The mapping host image copies go through (hk_device_memory_copy_map()), + * NULL until the first copy. It covers the whole BO and lives until + * vkFreeMemory. */ + void *copy_map; + /* Residency preference the kernel accepted (memory priority 1.0). */ bool keep_resident; @@ -63,6 +68,8 @@ hk_device_memory_addr(const struct hk_device_memory *mem) return mem->replay_va ? mem->replay_va->addr : mem->bo->va->addr; } +void *hk_device_memory_copy_map(struct hk_device_memory *mem); + extern const VkExternalMemoryProperties hk_opaque_fd_mem_props; extern const VkExternalMemoryProperties hk_dma_buf_mem_props; extern const VkExternalMemoryProperties hk_host_ptr_mem_props; diff --git a/src/asahi/vulkan/hk_image.c b/src/asahi/vulkan/hk_image.c index 1599a0c63c5d..f35f2783d823 100644 --- a/src/asahi/vulkan/hk_image.c +++ b/src/asahi/vulkan/hk_image.c @@ -2263,7 +2263,8 @@ hk_image_plane_bind(struct hk_device *dev, struct hk_image_plane *plane, &bo_offset_B)) return false; - plane->map = agx_bo_map(mem->bo) + bo_offset_B; + plane->mem = mem; + plane->bo_offset_B = bo_offset_B; plane->rem = mem_size_B - bo_offset_B; } @@ -2337,7 +2338,19 @@ hk_plane_index(VkFormat format, VkImageAspectFlags aspect_mask) } } -static void +/* The CPU address of a bound plane for host image copies, NULL if the BO + * cannot be mapped. The copies go through the memory's own copy mapping + * rather than the BO mapping vkMapMemory2 gives the application, which + * vkUnmapMemory2 removes and a placed vkMapMemory2 moves, on any thread. + */ +static char * +hk_image_plane_map(const struct hk_image_plane *plane) +{ + char *map = hk_device_memory_copy_map(plane->mem); + return map ? map + plane->bo_offset_B : NULL; +} + +static VkResult hk_copy_memory_to_image(struct hk_device *device, struct hk_image *dst_image, const VkMemoryToImageCopyEXT *info, bool copy_memcpy) { @@ -2376,8 +2389,12 @@ hk_copy_memory_to_image(struct hk_device *device, struct hk_image *dst_image, bool tiled = ail_is_level_twiddled_uncompressed( layout, info->imageSubresource.mipLevel); + char *dst = hk_image_plane_map(&dst_image->planes[plane]); + if (!dst) + return vk_error(device, VK_ERROR_MEMORY_MAP_FAILED); + const char *src = (const char *)info->pHostPointer; - char *dst = (char *)dst_image->planes[plane].map + image_offset; + dst += image_offset; for (unsigned layer = 0; layer < layers; layer++, src += src_layer_stride, dst += dst_layer_stride) { if (copy_memcpy) { @@ -2394,6 +2411,8 @@ hk_copy_memory_to_image(struct hk_device *device, struct hk_image *dst_image, offset.y, extent.width, extent.height); } } + + return VK_SUCCESS; } VKAPI_ATTR VkResult VKAPI_CALL @@ -2404,14 +2423,17 @@ hk_CopyMemoryToImageEXT(VkDevice _device, VK_FROM_HANDLE(hk_image, dst_image, info->dstImage); for (unsigned i = 0; i < info->regionCount; i++) { - hk_copy_memory_to_image(device, dst_image, &info->pRegions[i], - info->flags & VK_HOST_IMAGE_COPY_MEMCPY_EXT); + VkResult result = + hk_copy_memory_to_image(device, dst_image, &info->pRegions[i], + info->flags & VK_HOST_IMAGE_COPY_MEMCPY_EXT); + if (result != VK_SUCCESS) + return result; } return VK_SUCCESS; } -static void +static VkResult hk_copy_image_to_memory(struct hk_device *device, struct hk_image *src_image, const VkImageToMemoryCopyEXT *info, bool copy_memcpy) { @@ -2456,7 +2478,11 @@ hk_copy_image_to_memory(struct hk_device *device, struct hk_image *src_image, bool tiled = ail_is_level_twiddled_uncompressed( layout, info->imageSubresource.mipLevel); - const char *src = (const char *)src_image->planes[plane].map + image_offset; + const char *src = hk_image_plane_map(&src_image->planes[plane]); + if (!src) + return vk_error(device, VK_ERROR_MEMORY_MAP_FAILED); + + src += image_offset; char *dst = (char *)info->pHostPointer; for (unsigned layer = 0; layer < layers; layer++, src += src_layer_stride, dst += dst_layer_stride) { @@ -2476,6 +2502,8 @@ hk_copy_image_to_memory(struct hk_device *device, struct hk_image *src_image, dst_pitch, offset.x, offset.y, extent.width, extent.height); } } + + return VK_SUCCESS; } VKAPI_ATTR VkResult VKAPI_CALL @@ -2486,14 +2514,17 @@ hk_CopyImageToMemoryEXT(VkDevice _device, VK_FROM_HANDLE(hk_image, image, info->srcImage); for (unsigned i = 0; i < info->regionCount; i++) { - hk_copy_image_to_memory(device, image, &info->pRegions[i], - info->flags & VK_HOST_IMAGE_COPY_MEMCPY_EXT); + VkResult result = + hk_copy_image_to_memory(device, image, &info->pRegions[i], + info->flags & VK_HOST_IMAGE_COPY_MEMCPY_EXT); + if (result != VK_SUCCESS) + return result; } return VK_SUCCESS; } -static void +static VkResult hk_copy_image_to_image_cpu(struct hk_device *device, struct hk_image *src_image, struct hk_image *dst_image, const VkImageCopy2 *info, bool copy_memcpy) @@ -2542,9 +2573,13 @@ hk_copy_image_to_image_cpu(struct hk_device *device, struct hk_image *src_image, bool dst_tiled = ail_is_level_twiddled_uncompressed( dst_layout, info->dstSubresource.mipLevel); - const char *src = - (const char *)src_image->planes[src_plane].map + src_image_offset; - char *dst = (char *)dst_image->planes[dst_plane].map + dst_image_offset; + const char *src = hk_image_plane_map(&src_image->planes[src_plane]); + char *dst = hk_image_plane_map(&dst_image->planes[dst_plane]); + if (!src || !dst) + return vk_error(device, VK_ERROR_MEMORY_MAP_FAILED); + + src += src_image_offset; + dst += dst_image_offset; for (unsigned layer = 0; layer < layers_to_copy; layer++, src += src_layer_stride, dst += dst_layer_stride) { @@ -2635,6 +2670,8 @@ hk_copy_image_to_image_cpu(struct hk_device *device, struct hk_image *src_image, free(temp_tile); } } + + return VK_SUCCESS; } VKAPI_ATTR VkResult VKAPI_CALL @@ -2648,20 +2685,25 @@ hk_CopyImageToImageEXT(VkDevice _device, pCopyImageToImageInfo->flags & VK_HOST_IMAGE_COPY_MEMCPY_EXT; for (uint32_t i = 0; i < pCopyImageToImageInfo->regionCount; ++i) { + VkResult result; if (hk_split_depth_stencil(src_image->vk.format)) { VkImageCopy2 info = pCopyImageToImageInfo->pRegions[i]; u_foreach_bit(b, info.dstSubresource.aspectMask) { info.srcSubresource.aspectMask = BITFIELD_BIT(b); info.dstSubresource.aspectMask = BITFIELD_BIT(b); - hk_copy_image_to_image_cpu(device, src_image, dst_image, &info, - copy_memcpy); + result = hk_copy_image_to_image_cpu(device, src_image, dst_image, + &info, copy_memcpy); + if (result != VK_SUCCESS) + return result; } continue; } - hk_copy_image_to_image_cpu(device, src_image, dst_image, - pCopyImageToImageInfo->pRegions + i, - copy_memcpy); + result = hk_copy_image_to_image_cpu(device, src_image, dst_image, + pCopyImageToImageInfo->pRegions + i, + copy_memcpy); + if (result != VK_SUCCESS) + return result; } return VK_SUCCESS; diff --git a/src/asahi/vulkan/hk_image.h b/src/asahi/vulkan/hk_image.h index dcd985a2a61e..2e1534cc1e5d 100644 --- a/src/asahi/vulkan/hk_image.h +++ b/src/asahi/vulkan/hk_image.h @@ -61,8 +61,12 @@ struct hk_image_plane { /* Bytes of that VA counted in hk_device::sparse_scratch_B. */ uint64_t sparse_scratch_B; - /* For host image copy */ - void *map; + /* For host image copy: the memory bound to this plane and the plane's + * offset in its BO. The copies go through the memory's copy mapping + * (hk_image_plane_map()). + */ + struct hk_device_memory *mem; + uint64_t bo_offset_B; uint32_t rem; /* If the image has sparse residency, its residency is tracked in this diff --git a/src/asahi/vulkan/meson.build b/src/asahi/vulkan/meson.build index 151fceeab499..ccc476da9044 100644 --- a/src/asahi/vulkan/meson.build +++ b/src/asahi/vulkan/meson.build @@ -696,11 +696,19 @@ if with_tests dependencies : [hk_deps], link_with : [libhk], link_args : [ld_args_gc_sections, hk_wrap_test_link_args, '-Wl,--wrap=agx_bo_bind', '-Wl,--wrap=agx_bo_cache_evict_all', - '-Wl,--wrap=agx_bo_export', + '-Wl,--wrap=agx_bo_export', '-Wl,--wrap=agx_bo_import', '-Wl,--wrap=hk_get_cgroup_memory_available', '-Wl,--wrap=__vk_errorf', '-Wl,--wrap=os_get_available_system_memory', '-Wl,--wrap=os_get_total_physical_memory']), suite : ['asahi']) + test('hk_host_image_copy', executable('hk_host_image_copy_test', + files('tests/test-hk-host-image-copy.c'), + include_directories : [inc_gallium, inc_gallium_aux, inc_include, inc_src, + inc_asahi, inc_virtio_gpu, inc_virtio_vdrm, include_directories('.')], + dependencies : [hk_deps, dep_thread], link_with : [libhk], + link_args : [ld_args_gc_sections, hk_wrap_test_link_args, + '-Wl,--wrap=__vk_errorf']), + suite : ['asahi']) test('hk_tes_query', executable('hk_tes_query_test', files('tests/test-hk-tes-query.c'), include_directories : [inc_gallium, inc_gallium_aux, inc_include, inc_src, inc_asahi, inc_virtio_gpu, inc_virtio_vdrm, include_directories('.')], diff --git a/src/asahi/vulkan/tests/test-hk-host-image-copy.c b/src/asahi/vulkan/tests/test-hk-host-image-copy.c new file mode 100644 index 000000000000..288b93fa0b0f --- /dev/null +++ b/src/asahi/vulkan/tests/test-hk-host-image-copy.c @@ -0,0 +1,470 @@ +/* Copyright 2026 Aurora Silicon + * SPDX-License-Identifier: MIT + * + * Host image copies through memory the application maps, unmaps and maps at + * a placed address, and from two threads at once. The BO is a memfd, so what + * a copy wrote can be read back from the file whichever mapping it went + * through. + */ +#undef NDEBUG +#include "hk_device.h" +#include "hk_device_memory.h" +#include "hk_entrypoints.h" +#include "hk_image.h" + +#include +#include +#include +#include +#include +#include +#include + +#define W 64 +#define H 64 +#define SIZE (4 * AIL_PAGESIZE) + +static int backing = -1; +static unsigned mmaps, munmaps; +/* The agx_bo each mapping was made into, for the last two mappings. */ +static struct agx_bo *mapped_bo[2]; + +/* While set, each mapping waits here until two threads are mapping. */ +static pthread_barrier_t *mmap_rendezvous; +/* While set, each mapping takes 100 ms. */ +static bool slow_mmap; + +static void +mock_mmap(struct agx_device *dev, struct agx_bo *bo, void *fixed_addr, + size_t length) +{ + assert(!bo->_map); + if (mmap_rendezvous) + pthread_barrier_wait(mmap_rendezvous); + if (slow_mmap) + usleep(100 * 1000); + + bo->_map_size = length ?: bo->size; + void *map = mmap(fixed_addr, bo->_map_size, PROT_READ | PROT_WRITE, + MAP_SHARED | (fixed_addr ? MAP_FIXED : 0), backing, 0); + assert(map != MAP_FAILED); + bo->_map = map; + mapped_bo[p_atomic_inc_return(&mmaps) & 1] = bo; +} + +static void +mock_munmap(struct agx_device *dev, struct agx_bo *bo) +{ + assert(!munmap(bo->_map, agx_bo_map_size(bo))); + p_atomic_inc(&munmaps); +} + +__typeof__(__vk_errorf) __wrap___vk_errorf; +VkResult +__wrap___vk_errorf(const void *object, VkResult result, const char *file, + int line, const char *format, ...) +{ + return result; +} + +static void +init_image(struct hk_image *image) +{ + *image = (struct hk_image){0}; + image->vk.base.type = VK_OBJECT_TYPE_IMAGE; + image->vk.image_type = VK_IMAGE_TYPE_2D; + image->vk.format = VK_FORMAT_R8G8B8A8_UNORM; + image->vk.extent = (VkExtent3D){W, H, 1}; + image->vk.mip_levels = 1; + image->vk.array_layers = 1; + image->plane_count = 1; + image->planes[0].layout = (struct ail_layout){ + .width_px = W, + .height_px = H, + .depth_px = 1, + .sample_count_sa = 1, + .levels = 1, + .tiling = AIL_TILING_LINEAR, + .format = PIPE_FORMAT_R8G8B8A8_UNORM, + }; + ail_make_miptree(&image->planes[0].layout); + assert(image->planes[0].layout.size_B <= SIZE / 2); +} + +static void +fill(uint32_t *texels, uint32_t seed) +{ + for (unsigned i = 0; i < W * H; ++i) + texels[i] = seed * 0x9e3779b9u + i; +} + +/* The image's texels as the BO holds them, read from the file. */ +static void +backing_texels(const struct hk_image *image, uint64_t offset_B, + uint32_t *texels) +{ + const struct ail_layout *layout = &image->planes[0].layout; + const uint32_t stride_B = ail_get_linear_stride_B(layout, 0); + for (unsigned y = 0; y < H; ++y) { + assert(pread(backing, texels + y * W, W * 4, offset_B + y * stride_B) == + W * 4); + } +} + +static void +to_image(VkDevice device, struct hk_image *image, const uint32_t *texels) +{ + const VkMemoryToImageCopyEXT region = { + .sType = VK_STRUCTURE_TYPE_MEMORY_TO_IMAGE_COPY_EXT, + .pHostPointer = texels, + .imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, + .imageExtent = {W, H, 1}, + }; + const VkCopyMemoryToImageInfoEXT info = { + .sType = VK_STRUCTURE_TYPE_COPY_MEMORY_TO_IMAGE_INFO_EXT, + .dstImage = hk_image_to_handle(image), + .dstImageLayout = VK_IMAGE_LAYOUT_GENERAL, + .regionCount = 1, + .pRegions = ®ion, + }; + assert(hk_CopyMemoryToImageEXT(device, &info) == VK_SUCCESS); +} + +static void +from_image(VkDevice device, struct hk_image *image, uint32_t *texels) +{ + const VkImageToMemoryCopyEXT region = { + .sType = VK_STRUCTURE_TYPE_IMAGE_TO_MEMORY_COPY_EXT, + .pHostPointer = texels, + .imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, + .imageExtent = {W, H, 1}, + }; + const VkCopyImageToMemoryInfoEXT info = { + .sType = VK_STRUCTURE_TYPE_COPY_IMAGE_TO_MEMORY_INFO_EXT, + .srcImage = hk_image_to_handle(image), + .srcImageLayout = VK_IMAGE_LAYOUT_GENERAL, + .regionCount = 1, + .pRegions = ®ion, + }; + assert(hk_CopyImageToMemoryEXT(device, &info) == VK_SUCCESS); +} + +static void +image_to_image(VkDevice device, struct hk_image *src, struct hk_image *dst) +{ + const VkImageCopy2 region = { + .sType = VK_STRUCTURE_TYPE_IMAGE_COPY_2, + .srcSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, + .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, + .extent = {W, H, 1}, + }; + const VkCopyImageToImageInfoEXT info = { + .sType = VK_STRUCTURE_TYPE_COPY_IMAGE_TO_IMAGE_INFO_EXT, + .srcImage = hk_image_to_handle(src), + .srcImageLayout = VK_IMAGE_LAYOUT_GENERAL, + .dstImage = hk_image_to_handle(dst), + .dstImageLayout = VK_IMAGE_LAYOUT_GENERAL, + .regionCount = 1, + .pRegions = ®ion, + }; + assert(hk_CopyImageToImageEXT(device, &info) == VK_SUCCESS); +} + +static void * +map(VkDevice device, VkDeviceMemory memory, void *placed) +{ + const VkMemoryMapPlacedInfoEXT placed_info = { + .sType = VK_STRUCTURE_TYPE_MEMORY_MAP_PLACED_INFO_EXT, + .pPlacedAddress = placed, + }; + const VkMemoryMapInfoKHR info = { + .sType = VK_STRUCTURE_TYPE_MEMORY_MAP_INFO_KHR, + .pNext = placed ? &placed_info : NULL, + .flags = placed ? VK_MEMORY_MAP_PLACED_BIT_EXT : 0, + .memory = memory, + .size = VK_WHOLE_SIZE, + }; + void *data = NULL; + assert(hk_MapMemory2KHR(device, &info, &data) == VK_SUCCESS); + assert(data && (!placed || data == placed)); + return data; +} + +static void +unmap(VkDevice device, VkDeviceMemory memory, bool reserve) +{ + const VkMemoryUnmapInfoKHR info = { + .sType = VK_STRUCTURE_TYPE_MEMORY_UNMAP_INFO_KHR, + .flags = reserve ? VK_MEMORY_UNMAP_RESERVE_BIT_EXT : 0, + .memory = memory, + }; + assert(hk_UnmapMemory2KHR(device, &info) == VK_SUCCESS); +} + +/* Whether [addr, addr + size) is one inaccessible mapping, per + * /proc/self/maps: what an application's reservation must stay. */ +static bool +reserved(const void *addr, size_t size) +{ + FILE *maps = fopen("/proc/self/maps", "r"); + assert(maps); + char line[512]; + bool found = false; + while (fgets(line, sizeof(line), maps)) { + uintptr_t lo, hi; + char perms[5]; + if (sscanf(line, "%lx-%lx %4s", &lo, &hi, perms) != 3) + continue; + if (lo <= (uintptr_t)addr && (uintptr_t)addr + size <= hi) { + found = !strcmp(perms, "---p"); + break; + } + } + fclose(maps); + return found; +} + +/* Whether [addr, addr + size) is mapped readable and writable, per + * /proc/self/maps. */ +static bool +mapped_rw(const void *addr, size_t size) +{ + FILE *maps = fopen("/proc/self/maps", "r"); + assert(maps); + char line[512]; + bool found = false; + while (fgets(line, sizeof(line), maps)) { + uintptr_t lo, hi; + char perms[5]; + if (sscanf(line, "%lx-%lx %4s", &lo, &hi, perms) != 3) + continue; + if (lo <= (uintptr_t)addr && (uintptr_t)addr + size <= hi) { + found = !strncmp(perms, "rw", 2); + break; + } + } + fclose(maps); + return found; +} + +struct copy_job { + VkDevice device; + struct hk_image *image; + uint32_t texels[W * H]; +}; + +static void * +copy_thread(void *data) +{ + struct copy_job *job = data; + to_image(job->device, job->image, job->texels); + return NULL; +} + +struct map_job { + pthread_barrier_t *start; + struct agx_bo *bo; + void *map; +}; + +static void * +map_thread(void *data) +{ + struct map_job *job = data; + pthread_barrier_wait(job->start); + job->map = agx_bo_map(job->bo); + return NULL; +} + +int +main(void) +{ + backing = memfd_create("hk-host-image-copy", MFD_CLOEXEC); + assert(backing >= 0 && !ftruncate(backing, SIZE)); + + struct hk_device *dev = calloc(1, sizeof(*dev)); + assert(dev); + vk_object_base_init(&dev->vk, &dev->vk.base, VK_OBJECT_TYPE_DEVICE); + dev->dev.ops.bo_mmap = mock_mmap; + dev->dev.ops.bo_munmap = mock_munmap; + dev->dev.ops.bo_mmap_independent = true; + simple_mtx_init(&dev->dev.bo_mmap_lock, mtx_plain); + VkDevice device = hk_device_to_handle(dev); + + struct agx_va va = {.addr = 0x100000000, .size_B = SIZE}; + struct agx_bo bo = {.dev = &dev->dev, .size = SIZE, .va = &va}; + struct hk_device_memory mem = {0}; + mem.vk.base.type = VK_OBJECT_TYPE_DEVICE_MEMORY; + mem.vk.size = SIZE; + mem.bo = &bo; + VkDeviceMemory memory = hk_device_memory_to_handle(&mem); + + /* Two images in the memory, bound while it is mapped. */ + struct hk_image a, b; + init_image(&a); + init_image(&b); + void *data = map(device, memory, NULL); + memset(data, 0, SIZE); + const VkBindImageMemoryInfo binds[2] = { + {.sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO, + .image = hk_image_to_handle(&a), + .memory = memory}, + {.sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO, + .image = hk_image_to_handle(&b), + .memory = memory, + .memoryOffset = SIZE / 2}, + }; + assert(hk_BindImageMemory2(device, 2, binds) == VK_SUCCESS); + /* Binding maps nothing. */ + assert(!mem.copy_map); + + static uint32_t in[W * H], out[W * H]; + + /* Unmapped: the first copy maps the memory for the copies, leaves the + * application's mapping unmapped, and lands in the memory. */ + unmap(device, memory, false); + assert(!bo._map); + const unsigned before_copies = mmaps; + fill(in, 1); + to_image(device, &a, in); + assert(mem.copy_map && !bo._map && mmaps == before_copies + 1); + void *copy_map = mem.copy_map; + backing_texels(&a, 0, out); + assert(!memcmp(in, out, sizeof(in))); + memset(out, 0, sizeof(out)); + from_image(device, &a, out); + assert(!memcmp(in, out, sizeof(in))); + image_to_image(device, &a, &b); + backing_texels(&b, SIZE / 2, out); + assert(!memcmp(in, out, sizeof(in))); + /* One mapping serves every copy that follows. */ + from_image(device, &b, out); + assert(mmaps == before_copies + 1 && mem.copy_map == copy_map); + + /* Mapped at a placed address: the copies keep their mapping, and what + * they write shows through the application's. */ + void *placed = + mmap(NULL, SIZE, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + assert(placed != MAP_FAILED); + data = map(device, memory, placed); + assert(bo._map == placed); + const unsigned placed_mmaps = mmaps; + fill(in, 2); + to_image(device, &a, in); + assert(bo._map == placed && mem.map == placed && mmaps == placed_mmaps); + assert(mem.copy_map == copy_map && mapped_rw(copy_map, SIZE)); + const uint32_t stride_B = ail_get_linear_stride_B(&a.planes[0].layout, 0); + for (unsigned y = 0; y < H; ++y) + assert(!memcmp((char *)placed + y * stride_B, in + y * W, W * 4)); + image_to_image(device, &a, &b); + backing_texels(&b, SIZE / 2, out); + assert(!memcmp(in, out, sizeof(in))); + + /* Unmapped with the range kept reserved: the copies leave the reservation + * inaccessible and the application's mapping unmapped. */ + unmap(device, memory, true); + assert(!bo._map && reserved(placed, SIZE)); + fill(in, 3); + to_image(device, &a, in); + assert(!bo._map && reserved(placed, SIZE) && mem.copy_map == copy_map); + backing_texels(&a, 0, out); + assert(!memcmp(in, out, sizeof(in))); + + /* Placed again, then unmapped: neither moves nor removes the copies' + * mapping, which a copy on another thread could be using meanwhile. */ + data = map(device, memory, placed); + assert(bo._map == placed && mapped_rw(copy_map, SIZE)); + unmap(device, memory, false); + assert(!bo._map && mapped_rw(copy_map, SIZE)); + fill(in, 4); + to_image(device, &a, in); + backing_texels(&a, 0, out); + assert(!memcmp(in, out, sizeof(in))); + + assert(munmap(copy_map, SIZE) == 0); + + /* Two threads copy into the two images of memory no copy has mapped yet, + * and both map it at once: one mapping is kept, the other unmapped, and + * both copies land in the memory. */ + struct hk_device_memory mem2 = {0}; + mem2.vk.base.type = VK_OBJECT_TYPE_DEVICE_MEMORY; + mem2.vk.size = SIZE; + mem2.bo = &bo; + a.planes[0].mem = &mem2; + b.planes[0].mem = &mem2; + pthread_barrier_t rendezvous; + assert(!pthread_barrier_init(&rendezvous, NULL, 2)); + mmap_rendezvous = &rendezvous; + static struct copy_job jobs[2]; + pthread_t threads[2]; + const unsigned race_mmaps = mmaps, race_munmaps = munmaps; + for (unsigned i = 0; i < 2; ++i) { + jobs[i] = (struct copy_job){.device = device, .image = i ? &b : &a}; + fill(jobs[i].texels, 5 + i); + assert(!pthread_create(&threads[i], NULL, copy_thread, &jobs[i])); + } + for (unsigned i = 0; i < 2; ++i) + assert(!pthread_join(threads[i], NULL)); + mmap_rendezvous = NULL; + pthread_barrier_destroy(&rendezvous); + assert(mmaps == race_mmaps + 2 && munmaps == race_munmaps + 1); + assert(mem2.copy_map && mapped_rw(mem2.copy_map, SIZE)); + backing_texels(&a, 0, out); + assert(!memcmp(jobs[0].texels, out, sizeof(out))); + backing_texels(&b, SIZE / 2, out); + assert(!memcmp(jobs[1].texels, out, sizeof(out))); + assert(munmap(mem2.copy_map, SIZE) == 0); + + /* Two threads map a BO's shared mapping for the first time at once, the + * first while the second starts: it is mapped once, and both get that + * mapping. */ + struct agx_bo bo2 = {.dev = &dev->dev, .size = SIZE, .va = &va}; + pthread_barrier_t start; + assert(!pthread_barrier_init(&start, NULL, 2)); + static struct map_job map_jobs[2]; + slow_mmap = true; + const unsigned shared_mmaps = mmaps; + for (unsigned i = 0; i < 2; ++i) { + map_jobs[i] = (struct map_job){.start = &start, .bo = &bo2}; + assert(!pthread_create(&threads[i], NULL, map_thread, &map_jobs[i])); + } + for (unsigned i = 0; i < 2; ++i) + assert(!pthread_join(threads[i], NULL)); + slow_mmap = false; + assert(mmaps == shared_mmaps + 1); + assert(map_jobs[0].map && map_jobs[0].map == map_jobs[1].map && + map_jobs[0].map == bo2._map); + assert(munmap(bo2._map, SIZE) == 0); + + /* The same on a backend that can only map a BO itself: it is mapped + * once, in place, and both threads get that mapping. */ + dev->dev.ops.bo_mmap_independent = false; + struct agx_bo bo3 = {.dev = &dev->dev, .size = SIZE, .va = &va}; + mapped_bo[0] = mapped_bo[1] = NULL; + slow_mmap = true; + const unsigned inplace_mmaps = mmaps; + for (unsigned i = 0; i < 2; ++i) { + map_jobs[i] = (struct map_job){.start = &start, .bo = &bo3}; + assert(!pthread_create(&threads[i], NULL, map_thread, &map_jobs[i])); + } + for (unsigned i = 0; i < 2; ++i) + assert(!pthread_join(threads[i], NULL)); + slow_mmap = false; + assert(mmaps == inplace_mmaps + 1); + assert(mapped_bo[mmaps & 1] == &bo3); + assert(map_jobs[0].map && map_jobs[0].map == map_jobs[1].map && + map_jobs[0].map == bo3._map); + assert(munmap(bo3._map, SIZE) == 0); + dev->dev.ops.bo_mmap_independent = true; + pthread_barrier_destroy(&start); + + close(backing); + simple_mtx_destroy(&dev->dev.bo_mmap_lock); + vk_object_base_finish(&dev->vk.base); + free(dev); + puts("PASS: host image copies keep their own mapping through unmapped, " + "placed and reserved mappings and two copying threads; a BO's " + "shared mapping is made once when two threads map it first, in " + "place on a backend that cannot map a copy"); + 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 4b6bb00fd101..2ce43d8100e8 100644 --- a/src/asahi/vulkan/tests/test-hk-memory-oom.c +++ b/src/asahi/vulkan/tests/test-hk-memory-oom.c @@ -37,6 +37,7 @@ __typeof__(agx_bo_bind) __wrap_agx_bo_bind; __typeof__(agx_bo_cache_evict_all) __wrap_agx_bo_cache_evict_all; __typeof__(agx_bo_cache_evict_all) __real_agx_bo_cache_evict_all; __typeof__(agx_bo_export) __wrap_agx_bo_export; +__typeof__(agx_bo_import) __wrap_agx_bo_import; __typeof__(hk_get_cgroup_memory_available) __wrap_hk_get_cgroup_memory_available; __typeof__(__vk_errorf) __wrap___vk_errorf; __typeof__(os_get_available_system_memory) __wrap_os_get_available_system_memory; @@ -128,6 +129,19 @@ __wrap_agx_bo_export(struct agx_device *dev, struct agx_bo *bo) return -1; } +/* An imported object of import_size bytes. */ +static uint64_t import_size; + +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); + if (bo) + p_atomic_set(&bo->refcnt, 1); + return bo; +} + bool __wrap_hk_get_cgroup_memory_available(const char *cgroup, const char *mountinfo, uint64_t *available) @@ -522,6 +536,44 @@ main(void) assert(bo_calls == before); agx_bo_cache_evict_all(&dev->dev); + /* An fd import whose object is smaller than allocationSize is refused, + * releases the object and leaves the fd with the caller. One at least as + * large is taken and consumes the fd. */ + VkImportMemoryFdInfoKHR import_info = { + .sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR, + .handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT, + .fd = open("/dev/null", O_RDONLY | O_CLOEXEC), + }; + assert(import_info.fd >= 0); + const VkMemoryAllocateInfo import_alloc = { + .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, + .pNext = &import_info, + .allocationSize = MIB, + }; + import_size = 16384; + before = bo_calls; + assert(hk_AllocateMemory(hk_device_to_handle(dev), &import_alloc, &allocator, + &memory) == VK_ERROR_INVALID_EXTERNAL_HANDLE); + assert(bo_calls == before + 1 && !pinned && !host_live); + assert(!*hk_device_physical(dev)->mem_heaps[0].used); + assert(fcntl(import_info.fd, F_GETFD) != -1); + import_size = MIB - 16384; + assert(hk_AllocateMemory(hk_device_to_handle(dev), &import_alloc, &allocator, + &memory) == VK_ERROR_INVALID_EXTERNAL_HANDLE); + assert(!pinned && fcntl(import_info.fd, F_GETFD) != -1); + for (unsigned i = 0; i < 2; ++i) { + import_size = i ? 4 * MIB : MIB; + const int fd = import_info.fd; + assert(hk_AllocateMemory(hk_device_to_handle(dev), &import_alloc, + &allocator, &memory) == VK_SUCCESS); + assert(hk_device_memory_from_handle(memory)->bo->size == import_size); + assert(fcntl(fd, F_GETFD) == -1 && errno == EBADF); + hk_FreeMemory(hk_device_to_handle(dev), memory, &allocator); + import_info.fd = open("/dev/null", O_RDONLY | O_CLOEXEC); + assert(import_info.fd >= 0); + } + close(import_info.fd); + assert(!pinned && !host_live && !kernel_oom_attempts); wsi_headless_finish_wsi(&pdev->wsi_device, vk_default_allocator()); vk_object_base_finish(&dev->vk.base); @@ -532,6 +584,6 @@ main(void) simple_mtx_destroy(&dev->dev.bo_map_lock); free(dev); free(pdev); - puts("PASS: 2050 swapchain allocation attempts and sync-file probe, no kernel OOM entry or retained backing"); + puts("PASS: 2050 swapchain allocation attempts, sync-file probe and fd imports, no kernel OOM entry or retained backing"); return 0; }