Path: blob/21.2-virgl/src/amd/vulkan/radv_android.c
7099 views
/*1* Copyright © 2017, Google Inc.2*3* Permission is hereby granted, free of charge, to any person obtaining a4* copy of this software and associated documentation files (the "Software"),5* to deal in the Software without restriction, including without limitation6* the rights to use, copy, modify, merge, publish, distribute, sublicense,7* and/or sell copies of the Software, and to permit persons to whom the8* Software is furnished to do so, subject to the following conditions:9*10* The above copyright notice and this permission notice (including the next11* paragraph) shall be included in all copies or substantial portions of the12* Software.13*14* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR15* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,16* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL17* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER18* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING19* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS20* IN THE SOFTWARE.21*/2223#ifdef ANDROID24#include <libsync.h>25#include <hardware/gralloc.h>26#include <hardware/hardware.h>27#include <hardware/hwvulkan.h>28#include <vulkan/vk_android_native_buffer.h>29#include <vulkan/vk_icd.h>3031#if ANDROID_API_LEVEL >= 2632#include <hardware/gralloc1.h>33#endif34#endif3536#include "util/os_file.h"3738#include "radv_private.h"39#include "vk_util.h"4041#ifdef ANDROID4243static int radv_hal_open(const struct hw_module_t *mod, const char *id, struct hw_device_t **dev);44static int radv_hal_close(struct hw_device_t *dev);4546static void UNUSED47static_asserts(void)48{49STATIC_ASSERT(HWVULKAN_DISPATCH_MAGIC == ICD_LOADER_MAGIC);50}5152PUBLIC struct hwvulkan_module_t HAL_MODULE_INFO_SYM = {53.common =54{55.tag = HARDWARE_MODULE_TAG,56.module_api_version = HWVULKAN_MODULE_API_VERSION_0_1,57.hal_api_version = HARDWARE_MAKE_API_VERSION(1, 0),58.id = HWVULKAN_HARDWARE_MODULE_ID,59.name = "AMD Vulkan HAL",60.author = "Google",61.methods =62&(hw_module_methods_t){63.open = radv_hal_open,64},65},66};6768/* If any bits in test_mask are set, then unset them and return true. */69static inline bool70unmask32(uint32_t *inout_mask, uint32_t test_mask)71{72uint32_t orig_mask = *inout_mask;73*inout_mask &= ~test_mask;74return *inout_mask != orig_mask;75}7677static int78radv_hal_open(const struct hw_module_t *mod, const char *id, struct hw_device_t **dev)79{80assert(mod == &HAL_MODULE_INFO_SYM.common);81assert(strcmp(id, HWVULKAN_DEVICE_0) == 0);8283hwvulkan_device_t *hal_dev = malloc(sizeof(*hal_dev));84if (!hal_dev)85return -1;8687*hal_dev = (hwvulkan_device_t){88.common =89{90.tag = HARDWARE_DEVICE_TAG,91.version = HWVULKAN_DEVICE_API_VERSION_0_1,92.module = &HAL_MODULE_INFO_SYM.common,93.close = radv_hal_close,94},95.EnumerateInstanceExtensionProperties = radv_EnumerateInstanceExtensionProperties,96.CreateInstance = radv_CreateInstance,97.GetInstanceProcAddr = radv_GetInstanceProcAddr,98};99100*dev = &hal_dev->common;101return 0;102}103104static int105radv_hal_close(struct hw_device_t *dev)106{107/* hwvulkan.h claims that hw_device_t::close() is never called. */108return -1;109}110111VkResult112radv_image_from_gralloc(VkDevice device_h, const VkImageCreateInfo *base_info,113const VkNativeBufferANDROID *gralloc_info,114const VkAllocationCallbacks *alloc, VkImage *out_image_h)115116{117RADV_FROM_HANDLE(radv_device, device, device_h);118VkImage image_h = VK_NULL_HANDLE;119struct radv_image *image = NULL;120VkResult result;121122if (gralloc_info->handle->numFds != 1) {123return vk_errorf(device->instance, VK_ERROR_INVALID_EXTERNAL_HANDLE,124"VkNativeBufferANDROID::handle::numFds is %d, "125"expected 1",126gralloc_info->handle->numFds);127}128129/* Do not close the gralloc handle's dma_buf. The lifetime of the dma_buf130* must exceed that of the gralloc handle, and we do not own the gralloc131* handle.132*/133int dma_buf = gralloc_info->handle->data[0];134135VkDeviceMemory memory_h;136137const VkImportMemoryFdInfoKHR import_info = {138.sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR,139.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT,140.fd = os_dupfd_cloexec(dma_buf),141};142143/* Find the first VRAM memory type, or GART for PRIME images. */144int memory_type_index = -1;145for (int i = 0; i < device->physical_device->memory_properties.memoryTypeCount; ++i) {146bool is_local = !!(device->physical_device->memory_properties.memoryTypes[i].propertyFlags &147VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);148if (is_local) {149memory_type_index = i;150break;151}152}153154/* fallback */155if (memory_type_index == -1)156memory_type_index = 0;157158result = radv_AllocateMemory(device_h,159&(VkMemoryAllocateInfo){160.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,161.pNext = &import_info,162/* Max buffer size, unused for imports */163.allocationSize = 0x7FFFFFFF,164.memoryTypeIndex = memory_type_index,165},166alloc, &memory_h);167if (result != VK_SUCCESS)168return result;169170struct radeon_bo_metadata md;171device->ws->buffer_get_metadata(device->ws, radv_device_memory_from_handle(memory_h)->bo, &md);172173VkImageCreateInfo updated_base_info = *base_info;174175VkExternalMemoryImageCreateInfo external_memory_info = {176.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,177.pNext = updated_base_info.pNext,178.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT,179};180181updated_base_info.pNext = &external_memory_info;182183result = radv_image_create(device_h,184&(struct radv_image_create_info){185.vk_info = &updated_base_info,186.no_metadata_planes = true,187.bo_metadata = &md,188},189alloc, &image_h);190191if (result != VK_SUCCESS)192goto fail_create_image;193194image = radv_image_from_handle(image_h);195196radv_image_override_offset_stride(device, image, 0, gralloc_info->stride);197198radv_BindImageMemory(device_h, image_h, memory_h, 0);199200image->owned_memory = memory_h;201/* Don't clobber the out-parameter until success is certain. */202*out_image_h = image_h;203204return VK_SUCCESS;205206fail_create_image:207radv_FreeMemory(device_h, memory_h, alloc);208return result;209}210211VkResult212radv_GetSwapchainGrallocUsageANDROID(VkDevice device_h, VkFormat format,213VkImageUsageFlags imageUsage, int *grallocUsage)214{215RADV_FROM_HANDLE(radv_device, device, device_h);216struct radv_physical_device *phys_dev = device->physical_device;217VkPhysicalDevice phys_dev_h = radv_physical_device_to_handle(phys_dev);218VkResult result;219220*grallocUsage = 0;221222/* WARNING: Android Nougat's libvulkan.so hardcodes the VkImageUsageFlags223* returned to applications via VkSurfaceCapabilitiesKHR::supportedUsageFlags.224* The relevant code in libvulkan/swapchain.cpp contains this fun comment:225*226* TODO(jessehall): I think these are right, but haven't thought hard227* about it. Do we need to query the driver for support of any of228* these?229*230* Any disagreement between this function and the hardcoded231* VkSurfaceCapabilitiesKHR:supportedUsageFlags causes tests232* dEQP-VK.wsi.android.swapchain.*.image_usage to fail.233*/234235const VkPhysicalDeviceImageFormatInfo2 image_format_info = {236.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,237.format = format,238.type = VK_IMAGE_TYPE_2D,239.tiling = VK_IMAGE_TILING_OPTIMAL,240.usage = imageUsage,241};242243VkImageFormatProperties2 image_format_props = {244.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2,245};246247/* Check that requested format and usage are supported. */248result = radv_GetPhysicalDeviceImageFormatProperties2(phys_dev_h, &image_format_info,249&image_format_props);250if (result != VK_SUCCESS) {251return vk_errorf(device->instance, result,252"radv_GetPhysicalDeviceImageFormatProperties2 failed "253"inside %s",254__func__);255}256257if (unmask32(&imageUsage, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT))258*grallocUsage |= GRALLOC_USAGE_HW_RENDER;259260if (unmask32(&imageUsage, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT |261VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT))262*grallocUsage |= GRALLOC_USAGE_HW_TEXTURE;263264/* All VkImageUsageFlags not explicitly checked here are unsupported for265* gralloc swapchains.266*/267if (imageUsage != 0) {268return vk_errorf(device->instance, VK_ERROR_FORMAT_NOT_SUPPORTED,269"unsupported VkImageUsageFlags(0x%x) for gralloc "270"swapchain",271imageUsage);272}273274/*275* FINISHME: Advertise all display-supported formats. Mostly276* DRM_FORMAT_ARGB2101010 and DRM_FORMAT_ABGR2101010, but need to check277* what we need for 30-bit colors.278*/279if (format == VK_FORMAT_B8G8R8A8_UNORM || format == VK_FORMAT_B5G6R5_UNORM_PACK16) {280*grallocUsage |=281GRALLOC_USAGE_HW_FB | GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_EXTERNAL_DISP;282}283284if (*grallocUsage == 0)285return VK_ERROR_FORMAT_NOT_SUPPORTED;286287return VK_SUCCESS;288}289290VkResult291radv_GetSwapchainGrallocUsage2ANDROID(VkDevice device_h, VkFormat format,292VkImageUsageFlags imageUsage,293VkSwapchainImageUsageFlagsANDROID swapchainImageUsage,294uint64_t *grallocConsumerUsage,295uint64_t *grallocProducerUsage)296{297/* Before level 26 (Android 8.0/Oreo) the loader uses298* vkGetSwapchainGrallocUsageANDROID. */299#if ANDROID_API_LEVEL >= 26300RADV_FROM_HANDLE(radv_device, device, device_h);301struct radv_physical_device *phys_dev = device->physical_device;302VkPhysicalDevice phys_dev_h = radv_physical_device_to_handle(phys_dev);303VkResult result;304305*grallocConsumerUsage = 0;306*grallocProducerUsage = 0;307308if (swapchainImageUsage & VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID)309return vk_errorf(device->instance, VK_ERROR_FORMAT_NOT_SUPPORTED,310"The Vulkan loader tried to query shared presentable image support");311312const VkPhysicalDeviceImageFormatInfo2 image_format_info = {313.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,314.format = format,315.type = VK_IMAGE_TYPE_2D,316.tiling = VK_IMAGE_TILING_OPTIMAL,317.usage = imageUsage,318};319320VkImageFormatProperties2 image_format_props = {321.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2,322};323324/* Check that requested format and usage are supported. */325result = radv_GetPhysicalDeviceImageFormatProperties2(phys_dev_h, &image_format_info,326&image_format_props);327if (result != VK_SUCCESS) {328return vk_errorf(device->instance, result,329"radv_GetPhysicalDeviceImageFormatProperties2 failed "330"inside %s",331__func__);332}333334if (unmask32(&imageUsage,335VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT)) {336*grallocProducerUsage |= GRALLOC1_PRODUCER_USAGE_GPU_RENDER_TARGET;337*grallocConsumerUsage |= GRALLOC1_CONSUMER_USAGE_CLIENT_TARGET;338}339340if (unmask32(&imageUsage, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT |341VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT)) {342*grallocConsumerUsage |= GRALLOC1_CONSUMER_USAGE_GPU_TEXTURE;343}344345if (imageUsage != 0) {346return vk_errorf(device->instance, VK_ERROR_FORMAT_NOT_SUPPORTED,347"unsupported VkImageUsageFlags(0x%x) for gralloc "348"swapchain",349imageUsage);350}351352/*353* FINISHME: Advertise all display-supported formats. Mostly354* DRM_FORMAT_ARGB2101010 and DRM_FORMAT_ABGR2101010, but need to check355* what we need for 30-bit colors.356*/357if (format == VK_FORMAT_B8G8R8A8_UNORM || format == VK_FORMAT_B5G6R5_UNORM_PACK16) {358*grallocProducerUsage |= GRALLOC1_PRODUCER_USAGE_GPU_RENDER_TARGET;359*grallocConsumerUsage |= GRALLOC1_CONSUMER_USAGE_HWCOMPOSER;360}361362if (!*grallocProducerUsage && !*grallocConsumerUsage)363return VK_ERROR_FORMAT_NOT_SUPPORTED;364365return VK_SUCCESS;366#else367*grallocConsumerUsage = 0;368*grallocProducerUsage = 0;369return VK_ERROR_FORMAT_NOT_SUPPORTED;370#endif371}372373VkResult374radv_AcquireImageANDROID(VkDevice device_h, VkImage image_h, int nativeFenceFd, VkSemaphore semaphore,375VkFence fence)376{377RADV_FROM_HANDLE(radv_device, device, device_h);378VkResult result = VK_SUCCESS;379380/* From https://source.android.com/devices/graphics/implement-vulkan :381*382* "The driver takes ownership of the fence file descriptor and closes383* the fence file descriptor when no longer needed. The driver must do384* so even if neither a semaphore or fence object is provided, or even385* if vkAcquireImageANDROID fails and returns an error."386*387* The Vulkan spec for VkImportFence/SemaphoreFdKHR(), however, requires388* the file descriptor to be left alone on failure.389*/390int semaphore_fd = -1, fence_fd = -1;391if (nativeFenceFd >= 0) {392if (semaphore != VK_NULL_HANDLE && fence != VK_NULL_HANDLE) {393/* We have both so we have to import the sync file twice. One of394* them needs to be a dup.395*/396semaphore_fd = nativeFenceFd;397fence_fd = dup(nativeFenceFd);398if (fence_fd < 0) {399VkResult err = (errno == EMFILE) ? VK_ERROR_TOO_MANY_OBJECTS :400VK_ERROR_OUT_OF_HOST_MEMORY;401close(nativeFenceFd);402return vk_error(device->instance, err);403}404} else if (semaphore != VK_NULL_HANDLE) {405semaphore_fd = nativeFenceFd;406} else if (fence != VK_NULL_HANDLE) {407fence_fd = nativeFenceFd;408} else {409/* Nothing to import into so we have to close the file */410close(nativeFenceFd);411}412}413414if (semaphore != VK_NULL_HANDLE) {415const VkImportSemaphoreFdInfoKHR info = {416.sType = VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_FD_INFO_KHR,417.semaphore = semaphore,418.flags = VK_SEMAPHORE_IMPORT_TEMPORARY_BIT,419.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT,420.fd = semaphore_fd,421};422result = radv_ImportSemaphoreFdKHR(device_h, &info);423if (result == VK_SUCCESS)424semaphore_fd = -1; /* RADV took ownership */425}426427if (result == VK_SUCCESS && fence != VK_NULL_HANDLE) {428const VkImportFenceFdInfoKHR info = {429.sType = VK_STRUCTURE_TYPE_IMPORT_FENCE_FD_INFO_KHR,430.fence = fence,431.flags = VK_FENCE_IMPORT_TEMPORARY_BIT,432.handleType = VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT,433.fd = fence_fd,434};435result = radv_ImportFenceFdKHR(device_h, &info);436if (result == VK_SUCCESS)437fence_fd = -1; /* RADV took ownership */438}439440if (semaphore_fd >= 0)441close(semaphore_fd);442if (fence_fd >= 0)443close(fence_fd);444445return result;446}447448VkResult449radv_QueueSignalReleaseImageANDROID(VkQueue _queue, uint32_t waitSemaphoreCount,450const VkSemaphore *pWaitSemaphores, VkImage image,451int *pNativeFenceFd)452{453RADV_FROM_HANDLE(radv_queue, queue, _queue);454VkResult result = VK_SUCCESS;455456if (waitSemaphoreCount == 0) {457if (pNativeFenceFd)458*pNativeFenceFd = -1;459return VK_SUCCESS;460}461462int fd = -1;463464for (uint32_t i = 0; i < waitSemaphoreCount; ++i) {465int tmp_fd;466result =467radv_GetSemaphoreFdKHR(radv_device_to_handle(queue->device),468&(VkSemaphoreGetFdInfoKHR){469.sType = VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR,470.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT,471.semaphore = pWaitSemaphores[i],472},473&tmp_fd);474if (result != VK_SUCCESS) {475if (fd >= 0)476close(fd);477return result;478}479480if (fd < 0)481fd = tmp_fd;482else if (tmp_fd >= 0) {483sync_accumulate("radv", &fd, tmp_fd);484close(tmp_fd);485}486}487488if (pNativeFenceFd) {489*pNativeFenceFd = fd;490} else if (fd >= 0) {491close(fd);492/* We still need to do the exports, to reset the semaphores, but493* otherwise we don't wait on them. */494}495return VK_SUCCESS;496}497#endif498499#if RADV_SUPPORT_ANDROID_HARDWARE_BUFFER500501enum {502/* Usage bit equal to GRALLOC_USAGE_HW_CAMERA_MASK */503AHARDWAREBUFFER_USAGE_CAMERA_MASK = 0x00060000U,504};505506static inline VkFormat507vk_format_from_android(unsigned android_format, unsigned android_usage)508{509switch (android_format) {510case AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM:511case AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM:512return VK_FORMAT_R8G8B8A8_UNORM;513case AHARDWAREBUFFER_FORMAT_R8G8B8_UNORM:514return VK_FORMAT_R8G8B8_UNORM;515case AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM:516return VK_FORMAT_R5G6B5_UNORM_PACK16;517case AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT:518return VK_FORMAT_R16G16B16A16_SFLOAT;519case AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM:520return VK_FORMAT_A2B10G10R10_UNORM_PACK32;521case AHARDWAREBUFFER_FORMAT_Y8Cb8Cr8_420:522return VK_FORMAT_G8_B8R8_2PLANE_420_UNORM;523case AHARDWAREBUFFER_FORMAT_IMPLEMENTATION_DEFINED:524if (android_usage & AHARDWAREBUFFER_USAGE_CAMERA_MASK)525return VK_FORMAT_G8_B8R8_2PLANE_420_UNORM;526else527return VK_FORMAT_R8G8B8_UNORM;528case AHARDWAREBUFFER_FORMAT_BLOB:529default:530return VK_FORMAT_UNDEFINED;531}532}533534static inline unsigned535android_format_from_vk(unsigned vk_format)536{537switch (vk_format) {538case VK_FORMAT_R8G8B8A8_UNORM:539return AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM;540case VK_FORMAT_R8G8B8_UNORM:541return AHARDWAREBUFFER_FORMAT_R8G8B8_UNORM;542case VK_FORMAT_R5G6B5_UNORM_PACK16:543return AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM;544case VK_FORMAT_R16G16B16A16_SFLOAT:545return AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT;546case VK_FORMAT_A2B10G10R10_UNORM_PACK32:547return AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM;548case VK_FORMAT_G8_B8R8_2PLANE_420_UNORM:549return AHARDWAREBUFFER_FORMAT_Y8Cb8Cr8_420;550default:551return AHARDWAREBUFFER_FORMAT_BLOB;552}553}554555uint64_t556radv_ahb_usage_from_vk_usage(const VkImageCreateFlags vk_create, const VkImageUsageFlags vk_usage)557{558uint64_t ahb_usage = 0;559if (vk_usage & VK_IMAGE_USAGE_SAMPLED_BIT)560ahb_usage |= AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;561562if (vk_usage & VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT)563ahb_usage |= AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;564565if (vk_usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT)566ahb_usage |= AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT;567568if (vk_create & VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT)569ahb_usage |= AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP;570571if (vk_create & VK_IMAGE_CREATE_PROTECTED_BIT)572ahb_usage |= AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT;573574/* No usage bits set - set at least one GPU usage. */575if (ahb_usage == 0)576ahb_usage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;577return ahb_usage;578}579580static VkResult581get_ahb_buffer_format_properties(VkDevice device_h, const struct AHardwareBuffer *buffer,582VkAndroidHardwareBufferFormatPropertiesANDROID *pProperties)583{584RADV_FROM_HANDLE(radv_device, device, device_h);585586/* Get a description of buffer contents . */587AHardwareBuffer_Desc desc;588AHardwareBuffer_describe(buffer, &desc);589590/* Verify description. */591const uint64_t gpu_usage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |592AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT |593AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER;594595/* "Buffer must be a valid Android hardware buffer object with at least596* one of the AHARDWAREBUFFER_USAGE_GPU_* usage flags."597*/598if (!(desc.usage & (gpu_usage)))599return VK_ERROR_INVALID_EXTERNAL_HANDLE;600601/* Fill properties fields based on description. */602VkAndroidHardwareBufferFormatPropertiesANDROID *p = pProperties;603604p->format = vk_format_from_android(desc.format, desc.usage);605p->externalFormat = (uint64_t)(uintptr_t)p->format;606607VkFormatProperties format_properties;608radv_GetPhysicalDeviceFormatProperties(radv_physical_device_to_handle(device->physical_device),609p->format, &format_properties);610611if (desc.usage & AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER)612p->formatFeatures = format_properties.linearTilingFeatures;613else614p->formatFeatures = format_properties.optimalTilingFeatures;615616/* "Images can be created with an external format even if the Android hardware617* buffer has a format which has an equivalent Vulkan format to enable618* consistent handling of images from sources that might use either category619* of format. However, all images created with an external format are subject620* to the valid usage requirements associated with external formats, even if621* the Android hardware buffer’s format has a Vulkan equivalent."622*623* "The formatFeatures member *must* include624* VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT and at least one of625* VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT or626* VK_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT"627*/628assert(p->formatFeatures & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT);629630p->formatFeatures |= VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT;631632/* "Implementations may not always be able to determine the color model,633* numerical range, or chroma offsets of the image contents, so the values634* in VkAndroidHardwareBufferFormatPropertiesANDROID are only suggestions.635* Applications should treat these values as sensible defaults to use in636* the absence of more reliable information obtained through some other637* means."638*/639p->samplerYcbcrConversionComponents.r = VK_COMPONENT_SWIZZLE_IDENTITY;640p->samplerYcbcrConversionComponents.g = VK_COMPONENT_SWIZZLE_IDENTITY;641p->samplerYcbcrConversionComponents.b = VK_COMPONENT_SWIZZLE_IDENTITY;642p->samplerYcbcrConversionComponents.a = VK_COMPONENT_SWIZZLE_IDENTITY;643644p->suggestedYcbcrModel = VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_601;645p->suggestedYcbcrRange = VK_SAMPLER_YCBCR_RANGE_ITU_FULL;646647p->suggestedXChromaOffset = VK_CHROMA_LOCATION_MIDPOINT;648p->suggestedYChromaOffset = VK_CHROMA_LOCATION_MIDPOINT;649650return VK_SUCCESS;651}652653VkResult654radv_GetAndroidHardwareBufferPropertiesANDROID(VkDevice device_h,655const struct AHardwareBuffer *buffer,656VkAndroidHardwareBufferPropertiesANDROID *pProperties)657{658RADV_FROM_HANDLE(radv_device, dev, device_h);659struct radv_physical_device *pdevice = dev->physical_device;660661VkAndroidHardwareBufferFormatPropertiesANDROID *format_prop =662vk_find_struct(pProperties->pNext, ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID);663664/* Fill format properties of an Android hardware buffer. */665if (format_prop)666get_ahb_buffer_format_properties(device_h, buffer, format_prop);667668/* NOTE - We support buffers with only one handle but do not error on669* multiple handle case. Reason is that we want to support YUV formats670* where we have many logical planes but they all point to the same671* buffer, like is the case with VK_FORMAT_G8_B8R8_2PLANE_420_UNORM.672*/673const native_handle_t *handle = AHardwareBuffer_getNativeHandle(buffer);674int dma_buf = (handle && handle->numFds) ? handle->data[0] : -1;675if (dma_buf < 0)676return VK_ERROR_INVALID_EXTERNAL_HANDLE;677678/* All memory types. */679uint32_t memory_types = (1u << pdevice->memory_properties.memoryTypeCount) - 1;680681pProperties->allocationSize = lseek(dma_buf, 0, SEEK_END);682pProperties->memoryTypeBits = memory_types;683684return VK_SUCCESS;685}686687VkResult688radv_GetMemoryAndroidHardwareBufferANDROID(VkDevice device_h,689const VkMemoryGetAndroidHardwareBufferInfoANDROID *pInfo,690struct AHardwareBuffer **pBuffer)691{692RADV_FROM_HANDLE(radv_device_memory, mem, pInfo->memory);693694/* This should always be set due to the export handle types being set on695* allocation. */696assert(mem->android_hardware_buffer);697698/* Some quotes from Vulkan spec:699*700* "If the device memory was created by importing an Android hardware701* buffer, vkGetMemoryAndroidHardwareBufferANDROID must return that same702* Android hardware buffer object."703*704* "VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID must705* have been included in VkExportMemoryAllocateInfo::handleTypes when706* memory was created."707*/708*pBuffer = mem->android_hardware_buffer;709/* Increase refcount. */710AHardwareBuffer_acquire(mem->android_hardware_buffer);711return VK_SUCCESS;712}713714#endif715716VkFormat717radv_select_android_external_format(const void *next, VkFormat default_format)718{719#if RADV_SUPPORT_ANDROID_HARDWARE_BUFFER720const VkExternalFormatANDROID *android_format =721vk_find_struct_const(next, EXTERNAL_FORMAT_ANDROID);722723if (android_format && android_format->externalFormat) {724return (VkFormat)android_format->externalFormat;725}726#endif727728return default_format;729}730731VkResult732radv_import_ahb_memory(struct radv_device *device, struct radv_device_memory *mem,733unsigned priority, const VkImportAndroidHardwareBufferInfoANDROID *info)734{735#if RADV_SUPPORT_ANDROID_HARDWARE_BUFFER736/* Import from AHardwareBuffer to radv_device_memory. */737const native_handle_t *handle = AHardwareBuffer_getNativeHandle(info->buffer);738739/* NOTE - We support buffers with only one handle but do not error on740* multiple handle case. Reason is that we want to support YUV formats741* where we have many logical planes but they all point to the same742* buffer, like is the case with VK_FORMAT_G8_B8R8_2PLANE_420_UNORM.743*/744int dma_buf = (handle && handle->numFds) ? handle->data[0] : -1;745if (dma_buf < 0)746return VK_ERROR_INVALID_EXTERNAL_HANDLE;747748uint64_t alloc_size = 0;749VkResult result =750device->ws->buffer_from_fd(device->ws, dma_buf, priority, &mem->bo, &alloc_size);751if (result != VK_SUCCESS)752return result;753754if (mem->image) {755struct radeon_bo_metadata metadata;756device->ws->buffer_get_metadata(device->ws, mem->bo, &metadata);757758struct radv_image_create_info create_info = {.no_metadata_planes = true,759.bo_metadata = &metadata};760761VkResult result = radv_image_create_layout(device, create_info, NULL, mem->image);762if (result != VK_SUCCESS) {763device->ws->buffer_destroy(device->ws, mem->bo);764mem->bo = NULL;765return result;766}767768if (alloc_size < mem->image->size) {769device->ws->buffer_destroy(device->ws, mem->bo);770mem->bo = NULL;771return VK_ERROR_INVALID_EXTERNAL_HANDLE;772}773} else if (mem->buffer) {774if (alloc_size < mem->buffer->size) {775device->ws->buffer_destroy(device->ws, mem->bo);776mem->bo = NULL;777return VK_ERROR_INVALID_EXTERNAL_HANDLE;778}779}780781/* "If the vkAllocateMemory command succeeds, the implementation must782* acquire a reference to the imported hardware buffer, which it must783* release when the device memory object is freed. If the command fails,784* the implementation must not retain a reference."785*/786AHardwareBuffer_acquire(info->buffer);787mem->android_hardware_buffer = info->buffer;788789return VK_SUCCESS;790#else /* RADV_SUPPORT_ANDROID_HARDWARE_BUFFER */791return VK_ERROR_EXTENSION_NOT_PRESENT;792#endif793}794795VkResult796radv_create_ahb_memory(struct radv_device *device, struct radv_device_memory *mem,797unsigned priority, const VkMemoryAllocateInfo *pAllocateInfo)798{799#if RADV_SUPPORT_ANDROID_HARDWARE_BUFFER800const VkMemoryDedicatedAllocateInfo *dedicated_info =801vk_find_struct_const(pAllocateInfo->pNext, MEMORY_DEDICATED_ALLOCATE_INFO);802803uint32_t w = 0;804uint32_t h = 1;805uint32_t layers = 1;806uint32_t format = 0;807uint64_t usage = 0;808809/* If caller passed dedicated information. */810if (dedicated_info && dedicated_info->image) {811RADV_FROM_HANDLE(radv_image, image, dedicated_info->image);812w = image->info.width;813h = image->info.height;814layers = image->info.array_size;815format = android_format_from_vk(image->vk_format);816usage = radv_ahb_usage_from_vk_usage(image->flags, image->usage);817} else if (dedicated_info && dedicated_info->buffer) {818RADV_FROM_HANDLE(radv_buffer, buffer, dedicated_info->buffer);819w = buffer->size;820format = AHARDWAREBUFFER_FORMAT_BLOB;821usage = AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN | AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN;822} else {823w = pAllocateInfo->allocationSize;824format = AHARDWAREBUFFER_FORMAT_BLOB;825usage = AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN | AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN;826}827828struct AHardwareBuffer *android_hardware_buffer = NULL;829struct AHardwareBuffer_Desc desc = {830.width = w,831.height = h,832.layers = layers,833.format = format,834.usage = usage,835};836837if (AHardwareBuffer_allocate(&desc, &android_hardware_buffer) != 0)838return VK_ERROR_OUT_OF_HOST_MEMORY;839840mem->android_hardware_buffer = android_hardware_buffer;841842const struct VkImportAndroidHardwareBufferInfoANDROID import_info = {843.buffer = mem->android_hardware_buffer,844};845846VkResult result = radv_import_ahb_memory(device, mem, priority, &import_info);847848/* Release a reference to avoid leak for AHB allocation. */849AHardwareBuffer_release(mem->android_hardware_buffer);850851return result;852#else /* RADV_SUPPORT_ANDROID_HARDWARE_BUFFER */853return VK_ERROR_EXTENSION_NOT_PRESENT;854#endif855}856857bool858radv_android_gralloc_supports_format(VkFormat format, VkImageUsageFlagBits usage)859{860#if RADV_SUPPORT_ANDROID_HARDWARE_BUFFER861/* Ideally we check Gralloc for what it supports and then merge that with the radv862format support, but there is no easy gralloc query besides just creating an image.863That seems a bit on the expensive side, so just hardcode for now. */864/* TODO: Add multi-plane formats after confirming everything works between radeonsi865and radv. */866switch (format) {867case VK_FORMAT_R8G8B8A8_UNORM:868case VK_FORMAT_R5G6B5_UNORM_PACK16:869return true;870case VK_FORMAT_R8_UNORM:871case VK_FORMAT_R8G8_UNORM:872return !(usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT);873default:874return false;875}876#else877(void)format;878(void)usage;879return false;880#endif881}882883884