Path: blob/21.2-virgl/src/intel/vulkan/anv_android.c
4547 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#include <hardware/gralloc.h>2425#if ANDROID_API_LEVEL >= 2626#include <hardware/gralloc1.h>27#endif2829#include <hardware/hardware.h>30#include <hardware/hwvulkan.h>31#include <vulkan/vk_android_native_buffer.h>32#include <vulkan/vk_icd.h>33#include <sync/sync.h>3435#include "anv_private.h"36#include "vk_util.h"3738static int anv_hal_open(const struct hw_module_t* mod, const char* id, struct hw_device_t** dev);39static int anv_hal_close(struct hw_device_t *dev);4041static void UNUSED42static_asserts(void)43{44STATIC_ASSERT(HWVULKAN_DISPATCH_MAGIC == ICD_LOADER_MAGIC);45}4647PUBLIC struct hwvulkan_module_t HAL_MODULE_INFO_SYM = {48.common = {49.tag = HARDWARE_MODULE_TAG,50.module_api_version = HWVULKAN_MODULE_API_VERSION_0_1,51.hal_api_version = HARDWARE_MAKE_API_VERSION(1, 0),52.id = HWVULKAN_HARDWARE_MODULE_ID,53.name = "Intel Vulkan HAL",54.author = "Intel",55.methods = &(hw_module_methods_t) {56.open = anv_hal_open,57},58},59};6061/* If any bits in test_mask are set, then unset them and return true. */62static inline bool63unmask32(uint32_t *inout_mask, uint32_t test_mask)64{65uint32_t orig_mask = *inout_mask;66*inout_mask &= ~test_mask;67return *inout_mask != orig_mask;68}6970static int71anv_hal_open(const struct hw_module_t* mod, const char* id,72struct hw_device_t** dev)73{74assert(mod == &HAL_MODULE_INFO_SYM.common);75assert(strcmp(id, HWVULKAN_DEVICE_0) == 0);7677hwvulkan_device_t *hal_dev = malloc(sizeof(*hal_dev));78if (!hal_dev)79return -1;8081*hal_dev = (hwvulkan_device_t) {82.common = {83.tag = HARDWARE_DEVICE_TAG,84.version = HWVULKAN_DEVICE_API_VERSION_0_1,85.module = &HAL_MODULE_INFO_SYM.common,86.close = anv_hal_close,87},88.EnumerateInstanceExtensionProperties = anv_EnumerateInstanceExtensionProperties,89.CreateInstance = anv_CreateInstance,90.GetInstanceProcAddr = anv_GetInstanceProcAddr,91};9293*dev = &hal_dev->common;94return 0;95}9697static int98anv_hal_close(struct hw_device_t *dev)99{100/* hwvulkan.h claims that hw_device_t::close() is never called. */101return -1;102}103104#if ANDROID_API_LEVEL >= 26105#include <vndk/hardware_buffer.h>106/* See i915_private_android_types.h in minigbm. */107#define HAL_PIXEL_FORMAT_NV12_Y_TILED_INTEL 0x100108109enum {110/* Usage bit equal to GRALLOC_USAGE_HW_CAMERA_MASK */111AHARDWAREBUFFER_USAGE_CAMERA_MASK = 0x00060000U,112};113114inline VkFormat115vk_format_from_android(unsigned android_format, unsigned android_usage)116{117switch (android_format) {118case AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM:119return VK_FORMAT_R8G8B8A8_UNORM;120case AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM:121case AHARDWAREBUFFER_FORMAT_R8G8B8_UNORM:122return VK_FORMAT_R8G8B8_UNORM;123case AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM:124return VK_FORMAT_R5G6B5_UNORM_PACK16;125case AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT:126return VK_FORMAT_R16G16B16A16_SFLOAT;127case AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM:128return VK_FORMAT_A2B10G10R10_UNORM_PACK32;129case AHARDWAREBUFFER_FORMAT_Y8Cb8Cr8_420:130case HAL_PIXEL_FORMAT_NV12_Y_TILED_INTEL:131return VK_FORMAT_G8_B8R8_2PLANE_420_UNORM;132case AHARDWAREBUFFER_FORMAT_IMPLEMENTATION_DEFINED:133if (android_usage & AHARDWAREBUFFER_USAGE_CAMERA_MASK)134return VK_FORMAT_G8_B8R8_2PLANE_420_UNORM;135else136return VK_FORMAT_R8G8B8_UNORM;137case AHARDWAREBUFFER_FORMAT_BLOB:138default:139return VK_FORMAT_UNDEFINED;140}141}142143static inline unsigned144android_format_from_vk(unsigned vk_format)145{146switch (vk_format) {147case VK_FORMAT_R8G8B8A8_UNORM:148return AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM;149case VK_FORMAT_R8G8B8_UNORM:150return AHARDWAREBUFFER_FORMAT_R8G8B8_UNORM;151case VK_FORMAT_R5G6B5_UNORM_PACK16:152return AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM;153case VK_FORMAT_R16G16B16A16_SFLOAT:154return AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT;155case VK_FORMAT_A2B10G10R10_UNORM_PACK32:156return AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM;157case VK_FORMAT_G8_B8R8_2PLANE_420_UNORM:158#ifdef HAVE_CROS_GRALLOC159return AHARDWAREBUFFER_FORMAT_Y8Cb8Cr8_420;160#else161return HAL_PIXEL_FORMAT_NV12_Y_TILED_INTEL;162#endif163default:164return AHARDWAREBUFFER_FORMAT_BLOB;165}166}167168static VkResult169get_ahw_buffer_format_properties(170VkDevice device_h,171const struct AHardwareBuffer *buffer,172VkAndroidHardwareBufferFormatPropertiesANDROID *pProperties)173{174ANV_FROM_HANDLE(anv_device, device, device_h);175176/* Get a description of buffer contents . */177AHardwareBuffer_Desc desc;178AHardwareBuffer_describe(buffer, &desc);179180/* Verify description. */181uint64_t gpu_usage =182AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |183AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT |184AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER;185186/* "Buffer must be a valid Android hardware buffer object with at least187* one of the AHARDWAREBUFFER_USAGE_GPU_* usage flags."188*/189if (!(desc.usage & (gpu_usage)))190return VK_ERROR_INVALID_EXTERNAL_HANDLE;191192/* Fill properties fields based on description. */193VkAndroidHardwareBufferFormatPropertiesANDROID *p = pProperties;194195p->format = vk_format_from_android(desc.format, desc.usage);196197const struct anv_format *anv_format = anv_get_format(p->format);198p->externalFormat = (uint64_t) (uintptr_t) anv_format;199200/* Default to OPTIMAL tiling but set to linear in case201* of AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER usage.202*/203VkImageTiling tiling = VK_IMAGE_TILING_OPTIMAL;204205if (desc.usage & AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER)206tiling = VK_IMAGE_TILING_LINEAR;207208p->formatFeatures =209anv_get_image_format_features(&device->info, p->format, anv_format,210tiling, NULL);211212/* "Images can be created with an external format even if the Android hardware213* buffer has a format which has an equivalent Vulkan format to enable214* consistent handling of images from sources that might use either category215* of format. However, all images created with an external format are subject216* to the valid usage requirements associated with external formats, even if217* the Android hardware buffer’s format has a Vulkan equivalent."218*219* "The formatFeatures member *must* include220* VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT and at least one of221* VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT or222* VK_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT"223*/224p->formatFeatures |=225VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT;226227/* "Implementations may not always be able to determine the color model,228* numerical range, or chroma offsets of the image contents, so the values229* in VkAndroidHardwareBufferFormatPropertiesANDROID are only suggestions.230* Applications should treat these values as sensible defaults to use in231* the absence of more reliable information obtained through some other232* means."233*/234p->samplerYcbcrConversionComponents.r = VK_COMPONENT_SWIZZLE_IDENTITY;235p->samplerYcbcrConversionComponents.g = VK_COMPONENT_SWIZZLE_IDENTITY;236p->samplerYcbcrConversionComponents.b = VK_COMPONENT_SWIZZLE_IDENTITY;237p->samplerYcbcrConversionComponents.a = VK_COMPONENT_SWIZZLE_IDENTITY;238239p->suggestedYcbcrModel = VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_601;240p->suggestedYcbcrRange = VK_SAMPLER_YCBCR_RANGE_ITU_FULL;241242p->suggestedXChromaOffset = VK_CHROMA_LOCATION_MIDPOINT;243p->suggestedYChromaOffset = VK_CHROMA_LOCATION_MIDPOINT;244245return VK_SUCCESS;246}247248VkResult249anv_GetAndroidHardwareBufferPropertiesANDROID(250VkDevice device_h,251const struct AHardwareBuffer *buffer,252VkAndroidHardwareBufferPropertiesANDROID *pProperties)253{254ANV_FROM_HANDLE(anv_device, dev, device_h);255256VkAndroidHardwareBufferFormatPropertiesANDROID *format_prop =257vk_find_struct(pProperties->pNext,258ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID);259260/* Fill format properties of an Android hardware buffer. */261if (format_prop)262get_ahw_buffer_format_properties(device_h, buffer, format_prop);263264/* NOTE - We support buffers with only one handle but do not error on265* multiple handle case. Reason is that we want to support YUV formats266* where we have many logical planes but they all point to the same267* buffer, like is the case with VK_FORMAT_G8_B8R8_2PLANE_420_UNORM.268*/269const native_handle_t *handle =270AHardwareBuffer_getNativeHandle(buffer);271int dma_buf = (handle && handle->numFds) ? handle->data[0] : -1;272if (dma_buf < 0)273return VK_ERROR_INVALID_EXTERNAL_HANDLE;274275/* All memory types. */276uint32_t memory_types = (1ull << dev->physical->memory.type_count) - 1;277278pProperties->allocationSize = lseek(dma_buf, 0, SEEK_END);279pProperties->memoryTypeBits = memory_types;280281return VK_SUCCESS;282}283284VkResult285anv_GetMemoryAndroidHardwareBufferANDROID(286VkDevice device_h,287const VkMemoryGetAndroidHardwareBufferInfoANDROID *pInfo,288struct AHardwareBuffer **pBuffer)289{290ANV_FROM_HANDLE(anv_device_memory, mem, pInfo->memory);291292/* Some quotes from Vulkan spec:293*294* "If the device memory was created by importing an Android hardware295* buffer, vkGetMemoryAndroidHardwareBufferANDROID must return that same296* Android hardware buffer object."297*298* "VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID must299* have been included in VkExportMemoryAllocateInfo::handleTypes when300* memory was created."301*/302if (mem->ahw) {303*pBuffer = mem->ahw;304/* Increase refcount. */305AHardwareBuffer_acquire(mem->ahw);306return VK_SUCCESS;307}308309return VK_ERROR_OUT_OF_HOST_MEMORY;310}311312#endif313314/* Construct ahw usage mask from image usage bits, see315* 'AHardwareBuffer Usage Equivalence' in Vulkan spec.316*/317uint64_t318anv_ahw_usage_from_vk_usage(const VkImageCreateFlags vk_create,319const VkImageUsageFlags vk_usage)320{321uint64_t ahw_usage = 0;322#if ANDROID_API_LEVEL >= 26323if (vk_usage & VK_IMAGE_USAGE_SAMPLED_BIT)324ahw_usage |= AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;325326if (vk_usage & VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT)327ahw_usage |= AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;328329if (vk_usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT)330ahw_usage |= AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT;331332if (vk_create & VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT)333ahw_usage |= AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP;334335if (vk_create & VK_IMAGE_CREATE_PROTECTED_BIT)336ahw_usage |= AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT;337338/* No usage bits set - set at least one GPU usage. */339if (ahw_usage == 0)340ahw_usage = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE;341#endif342return ahw_usage;343}344345/*346* Called from anv_AllocateMemory when import AHardwareBuffer.347*/348VkResult349anv_import_ahw_memory(VkDevice device_h,350struct anv_device_memory *mem,351const VkImportAndroidHardwareBufferInfoANDROID *info)352{353#if ANDROID_API_LEVEL >= 26354ANV_FROM_HANDLE(anv_device, device, device_h);355356/* Import from AHardwareBuffer to anv_device_memory. */357const native_handle_t *handle =358AHardwareBuffer_getNativeHandle(info->buffer);359360/* NOTE - We support buffers with only one handle but do not error on361* multiple handle case. Reason is that we want to support YUV formats362* where we have many logical planes but they all point to the same363* buffer, like is the case with VK_FORMAT_G8_B8R8_2PLANE_420_UNORM.364*/365int dma_buf = (handle && handle->numFds) ? handle->data[0] : -1;366if (dma_buf < 0)367return VK_ERROR_INVALID_EXTERNAL_HANDLE;368369VkResult result = anv_device_import_bo(device, dma_buf, 0,3700 /* client_address */,371&mem->bo);372assert(result == VK_SUCCESS);373374/* "If the vkAllocateMemory command succeeds, the implementation must375* acquire a reference to the imported hardware buffer, which it must376* release when the device memory object is freed. If the command fails,377* the implementation must not retain a reference."378*/379AHardwareBuffer_acquire(info->buffer);380mem->ahw = info->buffer;381382return VK_SUCCESS;383#else384return VK_ERROR_EXTENSION_NOT_PRESENT;385#endif386}387388VkResult389anv_create_ahw_memory(VkDevice device_h,390struct anv_device_memory *mem,391const VkMemoryAllocateInfo *pAllocateInfo)392{393#if ANDROID_API_LEVEL >= 26394ANV_FROM_HANDLE(anv_device, dev, device_h);395396const VkMemoryDedicatedAllocateInfo *dedicated_info =397vk_find_struct_const(pAllocateInfo->pNext,398MEMORY_DEDICATED_ALLOCATE_INFO);399400uint32_t w = 0;401uint32_t h = 1;402uint32_t layers = 1;403uint32_t format = 0;404uint64_t usage = 0;405406/* If caller passed dedicated information. */407if (dedicated_info && dedicated_info->image) {408ANV_FROM_HANDLE(anv_image, image, dedicated_info->image);409w = image->extent.width;410h = image->extent.height;411layers = image->array_size;412format = android_format_from_vk(image->vk_format);413usage = anv_ahw_usage_from_vk_usage(image->create_flags, image->usage);414} else if (dedicated_info && dedicated_info->buffer) {415ANV_FROM_HANDLE(anv_buffer, buffer, dedicated_info->buffer);416w = buffer->size;417format = AHARDWAREBUFFER_FORMAT_BLOB;418usage = AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN |419AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN;420} else {421w = pAllocateInfo->allocationSize;422format = AHARDWAREBUFFER_FORMAT_BLOB;423usage = AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN |424AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN;425}426427struct AHardwareBuffer *ahw = NULL;428struct AHardwareBuffer_Desc desc = {429.width = w,430.height = h,431.layers = layers,432.format = format,433.usage = usage,434};435436if (AHardwareBuffer_allocate(&desc, &ahw) != 0)437return VK_ERROR_OUT_OF_HOST_MEMORY;438439const VkImportAndroidHardwareBufferInfoANDROID import_info = {440.buffer = ahw,441};442VkResult result = anv_import_ahw_memory(device_h, mem, &import_info);443444/* Release a reference to avoid leak for AHB allocation. */445AHardwareBuffer_release(ahw);446447return result;448#else449return VK_ERROR_EXTENSION_NOT_PRESENT;450#endif451452}453454VkResult455anv_image_from_external(456VkDevice device_h,457const VkImageCreateInfo *base_info,458const VkExternalMemoryImageCreateInfo *create_info,459const VkAllocationCallbacks *alloc,460VkImage *out_image_h)461{462#if ANDROID_API_LEVEL >= 26463ANV_FROM_HANDLE(anv_device, device, device_h);464465const VkExternalFormatANDROID *ext_info =466vk_find_struct_const(base_info->pNext, EXTERNAL_FORMAT_ANDROID);467468if (ext_info && ext_info->externalFormat != 0) {469assert(base_info->format == VK_FORMAT_UNDEFINED);470assert(base_info->imageType == VK_IMAGE_TYPE_2D);471assert(base_info->usage == VK_IMAGE_USAGE_SAMPLED_BIT);472assert(base_info->tiling == VK_IMAGE_TILING_OPTIMAL);473}474475struct anv_image_create_info anv_info = {476.vk_info = base_info,477.isl_extra_usage_flags = ISL_SURF_USAGE_DISABLE_AUX_BIT,478.external_format = true,479};480481VkImage image_h;482VkResult result = anv_image_create(device_h, &anv_info, alloc, &image_h);483if (result != VK_SUCCESS)484return result;485486*out_image_h = image_h;487488return VK_SUCCESS;489#else490return VK_ERROR_EXTENSION_NOT_PRESENT;491#endif492}493494495VkResult496anv_image_from_gralloc(VkDevice device_h,497const VkImageCreateInfo *base_info,498const VkNativeBufferANDROID *gralloc_info,499const VkAllocationCallbacks *alloc,500VkImage *out_image_h)501502{503ANV_FROM_HANDLE(anv_device, device, device_h);504VkImage image_h = VK_NULL_HANDLE;505struct anv_image *image = NULL;506struct anv_bo *bo = NULL;507VkResult result;508509struct anv_image_create_info anv_info = {510.vk_info = base_info,511.isl_extra_usage_flags = ISL_SURF_USAGE_DISABLE_AUX_BIT,512};513514if (gralloc_info->handle->numFds != 1) {515return vk_errorf(device, device, VK_ERROR_INVALID_EXTERNAL_HANDLE,516"VkNativeBufferANDROID::handle::numFds is %d, "517"expected 1", gralloc_info->handle->numFds);518}519520/* Do not close the gralloc handle's dma_buf. The lifetime of the dma_buf521* must exceed that of the gralloc handle, and we do not own the gralloc522* handle.523*/524int dma_buf = gralloc_info->handle->data[0];525526/* We need to set the WRITE flag on window system buffers so that GEM will527* know we're writing to them and synchronize uses on other rings (for528* example, if the display server uses the blitter ring).529*530* If this function fails and if the imported bo was resident in the cache,531* we should avoid updating the bo's flags. Therefore, we defer updating532* the flags until success is certain.533*534*/535result = anv_device_import_bo(device, dma_buf,536ANV_BO_ALLOC_IMPLICIT_SYNC |537ANV_BO_ALLOC_IMPLICIT_WRITE,5380 /* client_address */,539&bo);540if (result != VK_SUCCESS) {541return vk_errorf(device, device, result,542"failed to import dma-buf from VkNativeBufferANDROID");543}544545int i915_tiling = anv_gem_get_tiling(device, bo->gem_handle);546switch (i915_tiling) {547case I915_TILING_NONE:548anv_info.isl_tiling_flags = ISL_TILING_LINEAR_BIT;549break;550case I915_TILING_X:551anv_info.isl_tiling_flags = ISL_TILING_X_BIT;552break;553case I915_TILING_Y:554anv_info.isl_tiling_flags = ISL_TILING_Y0_BIT;555break;556case -1:557result = vk_errorf(device, device, VK_ERROR_INVALID_EXTERNAL_HANDLE,558"DRM_IOCTL_I915_GEM_GET_TILING failed for "559"VkNativeBufferANDROID");560goto fail_tiling;561default:562result = vk_errorf(device, device, VK_ERROR_INVALID_EXTERNAL_HANDLE,563"DRM_IOCTL_I915_GEM_GET_TILING returned unknown "564"tiling %d for VkNativeBufferANDROID", i915_tiling);565goto fail_tiling;566}567568enum isl_format format = anv_get_isl_format(&device->info,569base_info->format,570VK_IMAGE_ASPECT_COLOR_BIT,571base_info->tiling);572assert(format != ISL_FORMAT_UNSUPPORTED);573574result = anv_image_create(device_h, &anv_info, alloc, &image_h);575image = anv_image_from_handle(image_h);576if (result != VK_SUCCESS)577goto fail_create;578579VkImageMemoryRequirementsInfo2 mem_reqs_info = {580.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,581.image = image_h,582};583584VkMemoryRequirements2 mem_reqs = {585.sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,586};587588anv_GetImageMemoryRequirements2(device_h, &mem_reqs_info, &mem_reqs);589590VkDeviceSize aligned_image_size =591align_u64(mem_reqs.memoryRequirements.size,592mem_reqs.memoryRequirements.alignment);593594if (bo->size < aligned_image_size) {595result = vk_errorf(device, device, VK_ERROR_INVALID_EXTERNAL_HANDLE,596"dma-buf from VkNativeBufferANDROID is too small for "597"VkImage: %"PRIu64"B < %"PRIu64"B",598bo->size, aligned_image_size);599goto fail_size;600}601602assert(!image->disjoint);603assert(image->n_planes == 1);604assert(image->planes[0].primary_surface.memory_range.binding ==605ANV_IMAGE_MEMORY_BINDING_MAIN);606assert(image->bindings[ANV_IMAGE_MEMORY_BINDING_MAIN].address.bo == NULL);607assert(image->bindings[ANV_IMAGE_MEMORY_BINDING_MAIN].address.offset == 0);608image->bindings[ANV_IMAGE_MEMORY_BINDING_MAIN].address.bo = bo;609image->from_gralloc = true;610611/* Don't clobber the out-parameter until success is certain. */612*out_image_h = image_h;613614return VK_SUCCESS;615616fail_size:617anv_DestroyImage(device_h, image_h, alloc);618fail_create:619fail_tiling:620anv_device_release_bo(device, bo);621622return result;623}624625VkResult626anv_image_bind_from_gralloc(struct anv_device *device,627struct anv_image *image,628const VkNativeBufferANDROID *gralloc_info)629{630/* Do not close the gralloc handle's dma_buf. The lifetime of the dma_buf631* must exceed that of the gralloc handle, and we do not own the gralloc632* handle.633*/634int dma_buf = gralloc_info->handle->data[0];635636/* We need to set the WRITE flag on window system buffers so that GEM will637* know we're writing to them and synchronize uses on other rings (for638* example, if the display server uses the blitter ring).639*640* If this function fails and if the imported bo was resident in the cache,641* we should avoid updating the bo's flags. Therefore, we defer updating642* the flags until success is certain.643*644*/645struct anv_bo *bo = NULL;646VkResult result = anv_device_import_bo(device, dma_buf,647ANV_BO_ALLOC_IMPLICIT_SYNC |648ANV_BO_ALLOC_IMPLICIT_WRITE,6490 /* client_address */,650&bo);651if (result != VK_SUCCESS) {652return vk_errorf(device, &device->vk.base, result,653"failed to import dma-buf from VkNativeBufferANDROID");654}655656uint64_t img_size = image->bindings[ANV_IMAGE_MEMORY_BINDING_MAIN].memory_range.size;657if (img_size < bo->size) {658result = vk_errorf(device, &device->vk.base, VK_ERROR_INVALID_EXTERNAL_HANDLE,659"dma-buf from VkNativeBufferANDROID is too small for "660"VkImage: %"PRIu64"B < %"PRIu64"B",661bo->size, img_size);662anv_device_release_bo(device, bo);663return result;664}665666assert(!image->disjoint);667assert(image->n_planes == 1);668assert(image->planes[0].primary_surface.memory_range.binding ==669ANV_IMAGE_MEMORY_BINDING_MAIN);670assert(image->bindings[ANV_IMAGE_MEMORY_BINDING_MAIN].address.bo == NULL);671assert(image->bindings[ANV_IMAGE_MEMORY_BINDING_MAIN].address.offset == 0);672image->bindings[ANV_IMAGE_MEMORY_BINDING_MAIN].address.bo = bo;673image->from_gralloc = true;674675return VK_SUCCESS;676}677678static VkResult679format_supported_with_usage(VkDevice device_h, VkFormat format,680VkImageUsageFlags imageUsage)681{682ANV_FROM_HANDLE(anv_device, device, device_h);683VkPhysicalDevice phys_dev_h = anv_physical_device_to_handle(device->physical);684VkResult result;685686const VkPhysicalDeviceImageFormatInfo2 image_format_info = {687.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,688.format = format,689.type = VK_IMAGE_TYPE_2D,690.tiling = VK_IMAGE_TILING_OPTIMAL,691.usage = imageUsage,692};693694VkImageFormatProperties2 image_format_props = {695.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2,696};697698/* Check that requested format and usage are supported. */699result = anv_GetPhysicalDeviceImageFormatProperties2(phys_dev_h,700&image_format_info, &image_format_props);701if (result != VK_SUCCESS) {702return vk_errorf(device, device, result,703"anv_GetPhysicalDeviceImageFormatProperties2 failed "704"inside %s", __func__);705}706return VK_SUCCESS;707}708709710static VkResult711setup_gralloc0_usage(struct anv_device *device, VkFormat format,712VkImageUsageFlags imageUsage, int *grallocUsage)713{714/* WARNING: Android's libvulkan.so hardcodes the VkImageUsageFlags715* returned to applications via VkSurfaceCapabilitiesKHR::supportedUsageFlags.716* The relevant code in libvulkan/swapchain.cpp contains this fun comment:717*718* TODO(jessehall): I think these are right, but haven't thought hard719* about it. Do we need to query the driver for support of any of720* these?721*722* Any disagreement between this function and the hardcoded723* VkSurfaceCapabilitiesKHR:supportedUsageFlags causes tests724* dEQP-VK.wsi.android.swapchain.*.image_usage to fail.725*/726727if (unmask32(&imageUsage, VK_IMAGE_USAGE_TRANSFER_DST_BIT |728VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT))729*grallocUsage |= GRALLOC_USAGE_HW_RENDER;730731if (unmask32(&imageUsage, VK_IMAGE_USAGE_TRANSFER_SRC_BIT |732VK_IMAGE_USAGE_SAMPLED_BIT |733VK_IMAGE_USAGE_STORAGE_BIT |734VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT))735*grallocUsage |= GRALLOC_USAGE_HW_TEXTURE;736737/* All VkImageUsageFlags not explicitly checked here are unsupported for738* gralloc swapchains.739*/740if (imageUsage != 0) {741return vk_errorf(device, device, VK_ERROR_FORMAT_NOT_SUPPORTED,742"unsupported VkImageUsageFlags(0x%x) for gralloc "743"swapchain", imageUsage);744}745746/* The below formats support GRALLOC_USAGE_HW_FB (that is, display747* scanout). This short list of formats is univserally supported on Intel748* but is incomplete. The full set of supported formats is dependent on749* kernel and hardware.750*751* FINISHME: Advertise all display-supported formats.752*/753switch (format) {754case VK_FORMAT_B8G8R8A8_UNORM:755case VK_FORMAT_R5G6B5_UNORM_PACK16:756case VK_FORMAT_R8G8B8A8_UNORM:757case VK_FORMAT_R8G8B8A8_SRGB:758*grallocUsage |= GRALLOC_USAGE_HW_FB |759GRALLOC_USAGE_HW_COMPOSER |760GRALLOC_USAGE_EXTERNAL_DISP;761break;762default:763mesa_logw("%s: unsupported format=%d", __func__, format);764}765766if (*grallocUsage == 0)767return VK_ERROR_FORMAT_NOT_SUPPORTED;768769return VK_SUCCESS;770}771772#if ANDROID_API_LEVEL >= 26773VkResult anv_GetSwapchainGrallocUsage2ANDROID(774VkDevice device_h,775VkFormat format,776VkImageUsageFlags imageUsage,777VkSwapchainImageUsageFlagsANDROID swapchainImageUsage,778uint64_t* grallocConsumerUsage,779uint64_t* grallocProducerUsage)780{781ANV_FROM_HANDLE(anv_device, device, device_h);782VkResult result;783784*grallocConsumerUsage = 0;785*grallocProducerUsage = 0;786mesa_logd("%s: format=%d, usage=0x%x", __func__, format, imageUsage);787788result = format_supported_with_usage(device_h, format, imageUsage);789if (result != VK_SUCCESS)790return result;791792int32_t grallocUsage = 0;793result = setup_gralloc0_usage(device, format, imageUsage, &grallocUsage);794if (result != VK_SUCCESS)795return result;796797/* Setup gralloc1 usage flags from gralloc0 flags. */798799if (grallocUsage & GRALLOC_USAGE_HW_RENDER) {800*grallocProducerUsage |= GRALLOC1_PRODUCER_USAGE_GPU_RENDER_TARGET;801*grallocConsumerUsage |= GRALLOC1_CONSUMER_USAGE_CLIENT_TARGET;802}803804if (grallocUsage & GRALLOC_USAGE_HW_TEXTURE) {805*grallocConsumerUsage |= GRALLOC1_CONSUMER_USAGE_GPU_TEXTURE;806}807808if (grallocUsage & (GRALLOC_USAGE_HW_FB |809GRALLOC_USAGE_HW_COMPOSER |810GRALLOC_USAGE_EXTERNAL_DISP)) {811*grallocProducerUsage |= GRALLOC1_PRODUCER_USAGE_GPU_RENDER_TARGET;812*grallocConsumerUsage |= GRALLOC1_CONSUMER_USAGE_HWCOMPOSER;813}814815return VK_SUCCESS;816}817#endif818819VkResult anv_GetSwapchainGrallocUsageANDROID(820VkDevice device_h,821VkFormat format,822VkImageUsageFlags imageUsage,823int* grallocUsage)824{825ANV_FROM_HANDLE(anv_device, device, device_h);826VkResult result;827828*grallocUsage = 0;829mesa_logd("%s: format=%d, usage=0x%x", __func__, format, imageUsage);830831result = format_supported_with_usage(device_h, format, imageUsage);832if (result != VK_SUCCESS)833return result;834835return setup_gralloc0_usage(device, format, imageUsage, grallocUsage);836}837838VkResult839anv_AcquireImageANDROID(840VkDevice device_h,841VkImage image_h,842int nativeFenceFd,843VkSemaphore semaphore_h,844VkFence fence_h)845{846ANV_FROM_HANDLE(anv_device, device, device_h);847VkResult result = VK_SUCCESS;848849/* From https://source.android.com/devices/graphics/implement-vulkan :850*851* "The driver takes ownership of the fence file descriptor and closes852* the fence file descriptor when no longer needed. The driver must do853* so even if neither a semaphore or fence object is provided, or even854* if vkAcquireImageANDROID fails and returns an error."855*856* The Vulkan spec for VkImportFence/SemaphoreFdKHR(), however, requires857* the file descriptor to be left alone on failure.858*/859int semaphore_fd = -1, fence_fd = -1;860if (nativeFenceFd >= 0) {861if (semaphore_h != VK_NULL_HANDLE && fence_h != VK_NULL_HANDLE) {862/* We have both so we have to import the sync file twice. One of863* them needs to be a dup.864*/865semaphore_fd = nativeFenceFd;866fence_fd = dup(nativeFenceFd);867if (fence_fd < 0) {868VkResult err = (errno == EMFILE) ? VK_ERROR_TOO_MANY_OBJECTS :869VK_ERROR_OUT_OF_HOST_MEMORY;870close(nativeFenceFd);871return vk_error(err);872}873} else if (semaphore_h != VK_NULL_HANDLE) {874semaphore_fd = nativeFenceFd;875} else if (fence_h != VK_NULL_HANDLE) {876fence_fd = nativeFenceFd;877} else {878/* Nothing to import into so we have to close the file */879close(nativeFenceFd);880}881}882883if (semaphore_h != VK_NULL_HANDLE) {884const VkImportSemaphoreFdInfoKHR info = {885.sType = VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_FD_INFO_KHR,886.semaphore = semaphore_h,887.flags = VK_SEMAPHORE_IMPORT_TEMPORARY_BIT,888.handleType = VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT,889.fd = semaphore_fd,890};891result = anv_ImportSemaphoreFdKHR(device_h, &info);892if (result == VK_SUCCESS)893semaphore_fd = -1; /* ANV took ownership */894}895896if (result == VK_SUCCESS && fence_h != VK_NULL_HANDLE) {897const VkImportFenceFdInfoKHR info = {898.sType = VK_STRUCTURE_TYPE_IMPORT_FENCE_FD_INFO_KHR,899.fence = fence_h,900.flags = VK_FENCE_IMPORT_TEMPORARY_BIT,901.handleType = VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT,902.fd = fence_fd,903};904result = anv_ImportFenceFdKHR(device_h, &info);905if (result == VK_SUCCESS)906fence_fd = -1; /* ANV took ownership */907}908909if (semaphore_fd >= 0)910close(semaphore_fd);911if (fence_fd >= 0)912close(fence_fd);913914return result;915}916917VkResult918anv_QueueSignalReleaseImageANDROID(919VkQueue queue,920uint32_t waitSemaphoreCount,921const VkSemaphore* pWaitSemaphores,922VkImage image,923int* pNativeFenceFd)924{925VkResult result;926927if (waitSemaphoreCount == 0)928goto done;929930result = anv_QueueSubmit(queue, 1,931&(VkSubmitInfo) {932.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO,933.waitSemaphoreCount = 1,934.pWaitSemaphores = pWaitSemaphores,935},936(VkFence) VK_NULL_HANDLE);937if (result != VK_SUCCESS)938return result;939940done:941if (pNativeFenceFd) {942/* We can rely implicit on sync because above we submitted all943* semaphores to the queue.944*/945*pNativeFenceFd = -1;946}947948return VK_SUCCESS;949}950951952