1 /*------------------------------------------------------------------------
2 * Vulkan Conformance Tests
3 * ------------------------
5 * Copyright (c) 2017 The Khronos Group Inc.
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
21 * \brief Synchronization tests for resources shared with DX11 keyed mutex
22 *//*--------------------------------------------------------------------*/
24 #include "vktSynchronizationWin32KeyedMutexTests.hpp"
26 #include "vkDeviceUtil.hpp"
27 #include "vkPlatform.hpp"
28 #include "vkCmdUtil.hpp"
29 #include "vktTestCaseUtil.hpp"
30 #include "deSharedPtr.hpp"
32 #include "vktSynchronizationUtil.hpp"
33 #include "vktSynchronizationOperation.hpp"
34 #include "vktSynchronizationOperationTestData.hpp"
35 #include "vktExternalMemoryUtil.hpp"
36 #include "vktTestGroupUtil.hpp"
37 #include "vktCustomInstancesDevices.hpp"
39 #include "tcuResultCollector.hpp"
40 #include "tcuTestLog.hpp"
41 #include "tcuCommandLine.hpp"
43 #if (DE_OS == DE_OS_WIN32)
44 # define WIN32_LEAN_AND_MEAN
48 # include <versionhelpers.h>
50 # include <d3dcompiler.h>
52 typedef HRESULT (WINAPI * LPD3DX11COMPILEFROMMEMORY)(LPCSTR,
55 CONST D3D10_SHADER_MACRO*,
61 void*, /* ID3DX11ThreadPump */
68 using namespace vkt::ExternalMemoryUtil;
73 namespace synchronization
80 static const ResourceDescription s_resourcesWin32KeyedMutex[] =
82 { RESOURCE_TYPE_BUFFER, tcu::IVec4( 0x4000, 0, 0, 0), vk::VK_IMAGE_TYPE_LAST, vk::VK_FORMAT_UNDEFINED, (vk::VkImageAspectFlags)0, vk::VK_SAMPLE_COUNT_1_BIT }, // 16 KiB (min max UBO range)
83 { RESOURCE_TYPE_BUFFER, tcu::IVec4(0x40000, 0, 0, 0), vk::VK_IMAGE_TYPE_LAST, vk::VK_FORMAT_UNDEFINED, (vk::VkImageAspectFlags)0, vk::VK_SAMPLE_COUNT_1_BIT }, // 256 KiB
85 { RESOURCE_TYPE_IMAGE, tcu::IVec4(128, 128, 0, 0), vk::VK_IMAGE_TYPE_2D, vk::VK_FORMAT_R8_UNORM, vk::VK_IMAGE_ASPECT_COLOR_BIT, vk::VK_SAMPLE_COUNT_1_BIT },
86 { RESOURCE_TYPE_IMAGE, tcu::IVec4(128, 128, 0, 0), vk::VK_IMAGE_TYPE_2D, vk::VK_FORMAT_R16_UINT, vk::VK_IMAGE_ASPECT_COLOR_BIT, vk::VK_SAMPLE_COUNT_1_BIT },
87 { RESOURCE_TYPE_IMAGE, tcu::IVec4(128, 128, 0, 0), vk::VK_IMAGE_TYPE_2D, vk::VK_FORMAT_R8G8B8A8_UNORM, vk::VK_IMAGE_ASPECT_COLOR_BIT, vk::VK_SAMPLE_COUNT_1_BIT },
88 { RESOURCE_TYPE_IMAGE, tcu::IVec4(128, 128, 0, 0), vk::VK_IMAGE_TYPE_2D, vk::VK_FORMAT_R16G16B16A16_UINT, vk::VK_IMAGE_ASPECT_COLOR_BIT, vk::VK_SAMPLE_COUNT_1_BIT },
89 { RESOURCE_TYPE_IMAGE, tcu::IVec4(128, 128, 0, 0), vk::VK_IMAGE_TYPE_2D, vk::VK_FORMAT_R32G32B32A32_SFLOAT, vk::VK_IMAGE_ASPECT_COLOR_BIT, vk::VK_SAMPLE_COUNT_1_BIT },
94 TestConfig (const ResourceDescription& resource_,
95 OperationName writeOp_,
96 OperationName readOp_,
97 vk::VkExternalMemoryHandleTypeFlagBits memoryHandleTypeBuffer_,
98 vk::VkExternalMemoryHandleTypeFlagBits memoryHandleTypeImage_)
99 : resource (resource_)
102 , memoryHandleTypeBuffer (memoryHandleTypeBuffer_)
103 , memoryHandleTypeImage (memoryHandleTypeImage_)
107 const ResourceDescription resource;
108 const OperationName writeOp;
109 const OperationName readOp;
110 const vk::VkExternalMemoryHandleTypeFlagBits memoryHandleTypeBuffer;
111 const vk::VkExternalMemoryHandleTypeFlagBits memoryHandleTypeImage;
114 bool checkQueueFlags (vk::VkQueueFlags availableFlags, const vk::VkQueueFlags neededFlags)
116 if ((availableFlags & (vk::VK_QUEUE_GRAPHICS_BIT | vk::VK_QUEUE_COMPUTE_BIT)) != 0)
117 availableFlags |= vk::VK_QUEUE_TRANSFER_BIT;
119 return (availableFlags & neededFlags) != 0;
122 class SimpleAllocation : public vk::Allocation
125 SimpleAllocation (const vk::DeviceInterface& vkd,
127 const vk::VkDeviceMemory memory);
128 ~SimpleAllocation (void);
131 const vk::DeviceInterface& m_vkd;
132 const vk::VkDevice m_device;
135 SimpleAllocation::SimpleAllocation (const vk::DeviceInterface& vkd,
137 const vk::VkDeviceMemory memory)
138 : Allocation (memory, 0, DE_NULL)
144 SimpleAllocation::~SimpleAllocation (void)
146 m_vkd.freeMemory(m_device, getMemory(), DE_NULL);
149 CustomInstance createTestInstance (Context& context)
151 std::vector<std::string> extensions;
152 extensions.push_back("VK_KHR_get_physical_device_properties2");
153 extensions.push_back("VK_KHR_external_memory_capabilities");
155 return createCustomInstanceWithExtensions(context, extensions);
158 vk::Move<vk::VkDevice> createTestDevice (Context& context,
159 vk::VkInstance instance,
160 const vk::InstanceInterface& vki,
161 vk::VkPhysicalDevice physicalDevice)
163 const bool validationEnabled = context.getTestContext().getCommandLine().isValidationEnabled();
164 const deUint32 apiVersion = context.getUsedApiVersion();
165 const vk::PlatformInterface& vkp = context.getPlatformInterface();
166 const float priority = 0.0f;
167 const std::vector<vk::VkQueueFamilyProperties> queueFamilyProperties = vk::getPhysicalDeviceQueueFamilyProperties(vki, physicalDevice);
168 std::vector<deUint32> queueFamilyIndices (queueFamilyProperties.size(), 0xFFFFFFFFu);
169 std::vector<const char*> extensions;
171 if (!isCoreDeviceExtension(apiVersion, "VK_KHR_external_memory"))
172 extensions.push_back("VK_KHR_external_memory");
173 if (!isCoreDeviceExtension(apiVersion, "VK_KHR_dedicated_allocation"))
174 extensions.push_back("VK_KHR_dedicated_allocation");
175 if (!isCoreDeviceExtension(apiVersion, "VK_KHR_get_memory_requirements2"))
176 extensions.push_back("VK_KHR_get_memory_requirements2");
178 extensions.push_back("VK_KHR_external_memory_win32");
179 extensions.push_back("VK_KHR_win32_keyed_mutex");
181 const auto& features = context.getDeviceFeatures();
185 std::vector<vk::VkDeviceQueueCreateInfo> queues;
187 for (size_t ndx = 0; ndx < queueFamilyProperties.size(); ndx++)
189 const vk::VkDeviceQueueCreateInfo createInfo =
191 vk::VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO,
200 queues.push_back(createInfo);
203 const vk::VkDeviceCreateInfo createInfo =
205 vk::VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO,
209 (deUint32)queues.size(),
215 (deUint32)extensions.size(),
216 extensions.empty() ? DE_NULL : &extensions[0],
220 return createCustomDevice(validationEnabled, vkp, instance, vki, physicalDevice, &createInfo);
222 catch (const vk::Error& error)
224 if (error.getError() == vk::VK_ERROR_EXTENSION_NOT_PRESENT)
225 TCU_THROW(NotSupportedError, "Required extensions not supported");
231 deUint32 chooseMemoryType (deUint32 bits)
233 DE_ASSERT(bits != 0);
235 for (deUint32 memoryTypeIndex = 0; (1u << memoryTypeIndex) <= bits; memoryTypeIndex++)
237 if ((bits & (1u << memoryTypeIndex)) != 0)
238 return memoryTypeIndex;
241 DE_FATAL("No supported memory types");
245 bool isOpaqueHandleType (const vk::VkExternalMemoryHandleTypeFlagBits handleType)
249 case vk::VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_FD_BIT:
250 case vk::VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT:
251 case vk::VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT:
253 case vk::VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_BIT:
254 case vk::VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_KMT_BIT:
255 case vk::VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_HEAP_BIT:
256 case vk::VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D12_RESOURCE_BIT:
257 case vk::VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT:
258 case vk::VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_MAPPED_FOREIGN_MEMORY_BIT_EXT:
259 case vk::VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID:
262 TCU_THROW(InternalError, "Unknown handle type or multiple bits set");
266 vk::Move<vk::VkDeviceMemory> importMemory (const vk::DeviceInterface& vkd,
268 const vk::VkMemoryRequirements& requirements,
269 vk::VkExternalMemoryHandleTypeFlagBits externalType,
270 NativeHandle& handle,
271 bool requiresDedicated,
275 const vk::VkMemoryDedicatedAllocateInfo dedicatedInfo =
277 vk::VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
282 const vk::VkImportMemoryWin32HandleInfoKHR importInfo =
284 vk::VK_STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_KHR,
285 (requiresDedicated) ? &dedicatedInfo : DE_NULL,
287 handle.getWin32Handle(),
288 (vk::pt::Win32LPCWSTR)NULL
291 deUint32 handleCompatibleMemoryTypeBits = ~0u;
292 if(!isOpaqueHandleType(externalType))
294 vk::VkMemoryWin32HandlePropertiesKHR memoryWin32HandleProperties =
296 vk::VK_STRUCTURE_TYPE_MEMORY_WIN32_HANDLE_PROPERTIES_KHR,
300 VK_CHECK(vkd.getMemoryWin32HandlePropertiesKHR(device, externalType, handle.getWin32Handle(), &memoryWin32HandleProperties));
301 handleCompatibleMemoryTypeBits &= memoryWin32HandleProperties.memoryTypeBits;
304 const vk::VkMemoryAllocateInfo info =
306 vk::VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
309 chooseMemoryType(requirements.memoryTypeBits & handleCompatibleMemoryTypeBits)
312 vk::Move<vk::VkDeviceMemory> memory (vk::allocateMemory(vkd, device, &info));
319 de::MovePtr<vk::Allocation> importAndBindMemory (const vk::DeviceInterface& vkd,
322 NativeHandle& nativeHandle,
323 vk::VkExternalMemoryHandleTypeFlagBits externalType)
325 const vk::VkBufferMemoryRequirementsInfo2 requirementsInfo =
327 vk::VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2,
331 vk::VkMemoryDedicatedRequirements dedicatedRequirements =
333 vk::VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
338 vk::VkMemoryRequirements2 requirements =
340 vk::VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
341 &dedicatedRequirements,
344 vkd.getBufferMemoryRequirements2(device, &requirementsInfo, &requirements);
346 vk::Move<vk::VkDeviceMemory> memory = importMemory(vkd, device, requirements.memoryRequirements, externalType, nativeHandle, !!dedicatedRequirements.requiresDedicatedAllocation, buffer, DE_NULL);
347 VK_CHECK(vkd.bindBufferMemory(device, buffer, *memory, 0u));
349 return de::MovePtr<vk::Allocation>(new SimpleAllocation(vkd, device, memory.disown()));
352 de::MovePtr<vk::Allocation> importAndBindMemory (const vk::DeviceInterface& vkd,
355 NativeHandle& nativeHandle,
356 vk::VkExternalMemoryHandleTypeFlagBits externalType)
358 const vk::VkImageMemoryRequirementsInfo2 requirementsInfo =
360 vk::VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2,
364 vk::VkMemoryDedicatedRequirements dedicatedRequirements =
366 vk::VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS,
371 vk::VkMemoryRequirements2 requirements =
373 vk::VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
374 &dedicatedRequirements,
377 vkd.getImageMemoryRequirements2(device, &requirementsInfo, &requirements);
379 vk::Move<vk::VkDeviceMemory> memory = importMemory(vkd, device, requirements.memoryRequirements, externalType, nativeHandle, !!dedicatedRequirements.requiresDedicatedAllocation, DE_NULL, image);
380 VK_CHECK(vkd.bindImageMemory(device, image, *memory, 0u));
382 return de::MovePtr<vk::Allocation>(new SimpleAllocation(vkd, device, memory.disown()));
385 de::MovePtr<Resource> importResource (const vk::DeviceInterface& vkd,
387 const ResourceDescription& resourceDesc,
388 const std::vector<deUint32>& queueFamilyIndices,
389 const OperationSupport& readOp,
390 const OperationSupport& writeOp,
391 NativeHandle& nativeHandle,
392 vk::VkExternalMemoryHandleTypeFlagBits externalType)
394 if (resourceDesc.type == RESOURCE_TYPE_IMAGE)
396 const vk::VkExtent3D extent =
398 (deUint32)resourceDesc.size.x(),
399 de::max(1u, (deUint32)resourceDesc.size.y()),
400 de::max(1u, (deUint32)resourceDesc.size.z())
402 const vk::VkImageSubresourceRange subresourceRange =
404 resourceDesc.imageAspect,
410 const vk::VkImageSubresourceLayers subresourceLayers =
412 resourceDesc.imageAspect,
417 const vk::VkExternalMemoryImageCreateInfo externalInfo =
419 vk::VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
421 (vk::VkExternalMemoryHandleTypeFlags)externalType
423 const vk::VkImageTiling tiling = VK_IMAGE_TILING_OPTIMAL;
424 const vk::VkImageCreateInfo createInfo =
426 vk::VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
430 resourceDesc.imageType,
431 resourceDesc.imageFormat,
435 resourceDesc.imageSamples,
437 readOp.getInResourceUsageFlags() | writeOp.getOutResourceUsageFlags(),
438 vk::VK_SHARING_MODE_EXCLUSIVE,
440 (deUint32)queueFamilyIndices.size(),
441 &queueFamilyIndices[0],
442 vk::VK_IMAGE_LAYOUT_UNDEFINED
445 vk::Move<vk::VkImage> image = vk::createImage(vkd, device, &createInfo);
446 de::MovePtr<vk::Allocation> allocation = importAndBindMemory(vkd, device, *image, nativeHandle, externalType);
448 return de::MovePtr<Resource>(new Resource(image, allocation, extent, resourceDesc.imageType, resourceDesc.imageFormat, subresourceRange, subresourceLayers, tiling));
452 const vk::VkDeviceSize offset = 0u;
453 const vk::VkDeviceSize size = static_cast<vk::VkDeviceSize>(resourceDesc.size.x());
454 const vk::VkBufferUsageFlags usage = readOp.getInResourceUsageFlags() | writeOp.getOutResourceUsageFlags();
455 const vk::VkExternalMemoryBufferCreateInfo externalInfo =
457 vk::VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO,
459 (vk::VkExternalMemoryHandleTypeFlags)externalType
461 const vk::VkBufferCreateInfo createInfo =
463 vk::VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
469 vk::VK_SHARING_MODE_EXCLUSIVE,
470 (deUint32)queueFamilyIndices.size(),
471 &queueFamilyIndices[0]
473 vk::Move<vk::VkBuffer> buffer = vk::createBuffer(vkd, device, &createInfo);
474 de::MovePtr<vk::Allocation> allocation = importAndBindMemory(vkd, device, *buffer, nativeHandle, externalType);
476 return de::MovePtr<Resource>(new Resource(resourceDesc.type, buffer, allocation, offset, size));
480 void recordWriteBarrier (const vk::DeviceInterface& vkd,
481 vk::VkCommandBuffer commandBuffer,
482 const Resource& resource,
483 const SyncInfo& writeSync,
484 deUint32 writeQueueFamilyIndex,
485 const SyncInfo& readSync)
487 const vk::VkPipelineStageFlags srcStageMask = static_cast<VkPipelineStageFlags>(writeSync.stageMask);
488 const vk::VkAccessFlags srcAccessMask = static_cast<VkAccessFlags>(writeSync.accessMask);
490 const vk::VkPipelineStageFlags dstStageMask = static_cast<VkPipelineStageFlags>(readSync.stageMask);
491 const vk::VkAccessFlags dstAccessMask = static_cast<VkAccessFlags>(readSync.accessMask);
493 const vk::VkDependencyFlags dependencyFlags = 0;
495 if (resource.getType() == RESOURCE_TYPE_IMAGE)
497 const vk::VkImageMemoryBarrier barrier =
499 vk::VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
505 writeSync.imageLayout,
506 readSync.imageLayout,
508 writeQueueFamilyIndex,
509 VK_QUEUE_FAMILY_EXTERNAL,
511 resource.getImage().handle,
512 resource.getImage().subresourceRange
515 vkd.cmdPipelineBarrier(commandBuffer, srcStageMask, dstStageMask, dependencyFlags, 0u, (const vk::VkMemoryBarrier*)DE_NULL, 0u, (const vk::VkBufferMemoryBarrier*)DE_NULL, 1u, (const vk::VkImageMemoryBarrier*)&barrier);
519 const vk::VkBufferMemoryBarrier barrier =
521 vk::VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,
527 writeQueueFamilyIndex,
528 VK_QUEUE_FAMILY_EXTERNAL,
530 resource.getBuffer().handle,
535 vkd.cmdPipelineBarrier(commandBuffer, srcStageMask, dstStageMask, dependencyFlags, 0u, (const vk::VkMemoryBarrier*)DE_NULL, 1u, (const vk::VkBufferMemoryBarrier*)&barrier, 0u, (const vk::VkImageMemoryBarrier*)DE_NULL);
539 void recordReadBarrier (const vk::DeviceInterface& vkd,
540 vk::VkCommandBuffer commandBuffer,
541 const Resource& resource,
542 const SyncInfo& writeSync,
543 const SyncInfo& readSync,
544 deUint32 readQueueFamilyIndex)
546 const vk::VkPipelineStageFlags srcStageMask = static_cast<VkPipelineStageFlags>(readSync.stageMask);
547 const vk::VkAccessFlags srcAccessMask = static_cast<VkAccessFlags>(readSync.accessMask);
549 const vk::VkPipelineStageFlags dstStageMask = static_cast<VkPipelineStageFlags>(readSync.stageMask);
550 const vk::VkAccessFlags dstAccessMask = static_cast<VkAccessFlags>(readSync.accessMask);
552 const vk::VkDependencyFlags dependencyFlags = 0;
554 if (resource.getType() == RESOURCE_TYPE_IMAGE)
556 const vk::VkImageMemoryBarrier barrier =
558 vk::VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
564 writeSync.imageLayout,
565 readSync.imageLayout,
567 VK_QUEUE_FAMILY_EXTERNAL,
568 readQueueFamilyIndex,
570 resource.getImage().handle,
571 resource.getImage().subresourceRange
574 vkd.cmdPipelineBarrier(commandBuffer, srcStageMask, dstStageMask, dependencyFlags, 0u, (const vk::VkMemoryBarrier*)DE_NULL, 0u, (const vk::VkBufferMemoryBarrier*)DE_NULL, 1u, (const vk::VkImageMemoryBarrier*)&barrier);
578 const vk::VkBufferMemoryBarrier barrier =
580 vk::VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER,
586 VK_QUEUE_FAMILY_EXTERNAL,
587 readQueueFamilyIndex,
589 resource.getBuffer().handle,
594 vkd.cmdPipelineBarrier(commandBuffer, srcStageMask, dstStageMask, dependencyFlags, 0u, (const vk::VkMemoryBarrier*)DE_NULL, 1u, (const vk::VkBufferMemoryBarrier*)&barrier, 0u, (const vk::VkImageMemoryBarrier*)DE_NULL);
598 std::vector<deUint32> getFamilyIndices (const std::vector<vk::VkQueueFamilyProperties>& properties)
600 std::vector<deUint32> indices (properties.size(), 0);
602 for (deUint32 ndx = 0; ndx < properties.size(); ndx++)
620 KEYED_MUTEX_INIT = 0,
621 KEYED_MUTEX_VK_WRITE = 1,
622 KEYED_MUTEX_DX_COPY = 2,
623 KEYED_MUTEX_VK_VERIFY = 3,
624 KEYED_MUTEX_DONE = 4,
627 #if (DE_OS == DE_OS_WIN32)
628 DX11Operation (const ResourceDescription& resourceDesc,
629 vk::VkExternalMemoryHandleTypeFlagBits memoryHandleType,
630 ID3D11Device* pDevice,
631 ID3D11DeviceContext* pContext,
632 LPD3DX11COMPILEFROMMEMORY fnD3DX11CompileFromMemory,
633 pD3DCompile fnD3DCompile)
634 : m_resourceDesc (resourceDesc)
636 , m_pDevice (pDevice)
637 , m_pContext (pContext)
638 , m_fnD3DX11CompileFromMemory (fnD3DX11CompileFromMemory)
639 , m_fnD3DCompile (fnD3DCompile)
641 , m_pRenderTargetView (0)
642 , m_pVertexShader (0)
644 , m_pVertexBuffer (0)
646 , m_pSamplerLinear (0)
651 if (memoryHandleType == vk::VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT ||
652 memoryHandleType == vk::VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_BIT)
654 m_isMemNtHandle = true;
656 m_isMemNtHandle = false;
658 m_securityAttributes.lpSecurityDescriptor = 0;
660 for (UINT i = 0; i < BUFFER_COUNT; i++)
662 m_pTexture[i] = NULL;
664 m_keyedMutex[i] = NULL;
667 if (m_resourceDesc.type == RESOURCE_TYPE_BUFFER)
669 // SHARED_NTHANDLE is not supported with CreateBuffer().
670 TCU_CHECK_INTERNAL(!m_isMemNtHandle);
672 D3D11_BUFFER_DESC descBuf = { };
673 descBuf.ByteWidth = (UINT)m_resourceDesc.size.x();
674 descBuf.Usage = D3D11_USAGE_DEFAULT;
675 descBuf.BindFlags = 0;
676 descBuf.CPUAccessFlags = 0;
677 descBuf.MiscFlags = D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX;
678 descBuf.StructureByteStride = 0;
680 for (UINT i = 0; i < BUFFER_COUNT; ++i)
682 hr = m_pDevice->CreateBuffer(&descBuf, NULL, &m_pBuffer[i]);
684 TCU_FAIL("Failed to create a buffer");
686 m_sharedMemHandle[i] = 0;
688 IDXGIResource* tempResource = NULL;
689 hr = m_pBuffer[i]->QueryInterface(__uuidof(IDXGIResource), (void**)&tempResource);
691 TCU_FAIL("Query interface of IDXGIResource failed");
692 hr = tempResource->GetSharedHandle(&m_sharedMemHandle[i]);
693 tempResource->Release();
695 TCU_FAIL("Failed to get DX shared handle");
697 hr = m_pBuffer[i]->QueryInterface(__uuidof(IDXGIKeyedMutex), (void**)&m_keyedMutex[i]);
699 TCU_FAIL("Query interface of IDXGIKeyedMutex failed");
701 // Take ownership of the lock.
702 m_keyedMutex[i]->AcquireSync(KEYED_MUTEX_INIT, INFINITE);
705 // Release the buffer write lock for Vulkan to write into.
706 m_keyedMutex[BUFFER_VK_WRITE]->ReleaseSync(KEYED_MUTEX_VK_WRITE);
708 m_sharedMemSize = descBuf.ByteWidth;
709 m_sharedMemOffset = 0;
713 DE_ASSERT(m_resourceDesc.type == RESOURCE_TYPE_IMAGE);
715 for (UINT i = 0; i < BUFFER_COUNT; ++i)
717 D3D11_TEXTURE2D_DESC descColor = { };
718 descColor.Width = m_resourceDesc.size.x();
719 descColor.Height = m_resourceDesc.size.y();
720 descColor.MipLevels = 1;
721 descColor.ArraySize = 1;
722 descColor.Format = getDxgiFormat(m_resourceDesc.imageFormat);
723 descColor.SampleDesc.Count = 1;
724 descColor.SampleDesc.Quality = 0;
725 descColor.Usage = D3D11_USAGE_DEFAULT;
726 descColor.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE;
727 descColor.CPUAccessFlags = 0;
730 descColor.MiscFlags = D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX | D3D11_RESOURCE_MISC_SHARED_NTHANDLE;
732 descColor.MiscFlags = D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX;
734 hr = m_pDevice->CreateTexture2D(&descColor, NULL, &m_pTexture[i]);
736 TCU_FAIL("Unable to create DX11 texture");
738 m_sharedMemHandle[i] = 0;
742 IDXGIResource1* tempResource1 = NULL;
743 hr = m_pTexture[i]->QueryInterface(__uuidof(IDXGIResource1), (void**)&tempResource1);
745 TCU_FAIL("Unable to query IDXGIResource1 interface");
747 hr = tempResource1->CreateSharedHandle(getSecurityAttributes(), DXGI_SHARED_RESOURCE_READ | DXGI_SHARED_RESOURCE_WRITE, /*lpName*/NULL, &m_sharedMemHandle[i]);
748 tempResource1->Release();
750 TCU_FAIL("Enable to get DX shared handle");
754 IDXGIResource* tempResource = NULL;
755 hr = m_pTexture[i]->QueryInterface(__uuidof(IDXGIResource), (void**)&tempResource);
757 TCU_FAIL("Query interface of IDXGIResource failed");
758 hr = tempResource->GetSharedHandle(&m_sharedMemHandle[i]);
759 tempResource->Release();
761 TCU_FAIL("Failed to get DX shared handle");
764 hr = m_pTexture[i]->QueryInterface(__uuidof(IDXGIKeyedMutex), (void**)&m_keyedMutex[i]);
766 TCU_FAIL("Unable to query DX11 keyed mutex interface");
768 // Take ownership of the lock.
769 m_keyedMutex[i]->AcquireSync(KEYED_MUTEX_INIT, INFINITE);
773 m_sharedMemOffset = 0;
775 hr = m_pDevice->CreateRenderTargetView(m_pTexture[BUFFER_VK_READ], NULL, &m_pRenderTargetView);
777 TCU_FAIL("Unable to create DX11 render target view");
779 m_pContext->OMSetRenderTargets(1, &m_pRenderTargetView, NULL);
781 // Setup the viewport
783 vp.Width = (FLOAT)m_resourceDesc.size.x();
784 vp.Height = (FLOAT)m_resourceDesc.size.y();
789 m_pContext->RSSetViewports(1, &vp);
791 // Compile the vertex shader
793 "Texture2D txDiffuse : register(t0);\n"
794 "SamplerState samLinear : register(s0);\n"
797 " float4 Pos : POSITION;\n"
798 " float2 Tex : TEXCOORD0;\n"
802 " float4 Pos : SV_POSITION;\n"
803 " float2 Tex : TEXCOORD0;\n"
805 "PS_INPUT VS(VS_INPUT input)\n"
807 " PS_INPUT output = (PS_INPUT)0;\n"
808 " output.Pos = input.Pos;\n"
809 " output.Tex = input.Tex;\n"
813 "float4 PS(PS_INPUT input) : SV_Target\n"
815 " return txDiffuse.Sample(samLinear, input.Tex);\n"
818 // Define the input layout
819 D3D11_INPUT_ELEMENT_DESC layout[] =
821 { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
822 { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
825 createShaders(shader, "VS", "vs_4_0", ARRAYSIZE(layout), layout, &m_pVertexShader, "PS", "ps_4_0", &m_pPixelShader);
833 SimpleVertex vertices[] =
835 { { -1.f, -1.f, 0.0f }, { 0.0f, 1.0f } },
836 { { -1.f, 1.f, 0.0f }, { 0.0f, 0.0f } },
837 { { 1.f, -1.f, 0.0f }, { 1.0f, 1.0f } },
838 { { 1.f, 1.f, 0.0f }, { 1.0f, 0.0f } },
841 D3D11_BUFFER_DESC bd = { };
842 bd.Usage = D3D11_USAGE_DEFAULT;
843 bd.ByteWidth = sizeof (vertices);
844 bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
845 bd.CPUAccessFlags = 0;
846 D3D11_SUBRESOURCE_DATA InitData = { };
847 InitData.pSysMem = vertices;
848 hr = m_pDevice->CreateBuffer(&bd, &InitData, &m_pVertexBuffer);
850 TCU_FAIL("Failed to create DX11 vertex buffer");
853 UINT stride = sizeof (SimpleVertex);
855 m_pContext->IASetVertexBuffers(0, 1, &m_pVertexBuffer, &stride, &offset);
857 // Set primitive topology
858 m_pContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
862 D3D11_SHADER_RESOURCE_VIEW_DESC SRVDesc = { };
863 SRVDesc.Format = getDxgiFormat(m_resourceDesc.imageFormat);
864 SRVDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
865 SRVDesc.Texture2D.MipLevels = 1;
867 hr = m_pDevice->CreateShaderResourceView(m_pTexture[BUFFER_VK_WRITE], &SRVDesc, &m_pTextureRV);
869 TCU_FAIL("Failed to create DX11 resource view");
871 // Create the sample state
872 D3D11_SAMPLER_DESC sampDesc = { };
873 sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
874 sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
875 sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
876 sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
877 sampDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
879 sampDesc.MaxLOD = D3D11_FLOAT32_MAX;
880 hr = m_pDevice->CreateSamplerState(&sampDesc, &m_pSamplerLinear);
882 TCU_FAIL("Failed to create DX11 sampler state");
884 // Release the lock for VK to write into the texture.
885 m_keyedMutex[BUFFER_VK_WRITE]->ReleaseSync(KEYED_MUTEX_VK_WRITE);
893 #endif // #if (DE_OS == DE_OS_WIN32)
895 NativeHandle getNativeHandle (Buffer buffer)
897 #if (DE_OS == DE_OS_WIN32)
898 return NativeHandle((m_isMemNtHandle) ? NativeHandle::WIN32HANDLETYPE_NT : NativeHandle::WIN32HANDLETYPE_KMT, vk::pt::Win32Handle(m_sharedMemHandle[buffer]));
901 return NativeHandle();
907 #if (DE_OS == DE_OS_WIN32)
908 m_keyedMutex[BUFFER_VK_WRITE]->AcquireSync(KEYED_MUTEX_DX_COPY, INFINITE);
910 if (m_resourceDesc.type == RESOURCE_TYPE_BUFFER) {
911 m_pContext->CopySubresourceRegion(m_pBuffer[BUFFER_VK_READ], 0, 0, 0, 0, m_pBuffer[BUFFER_VK_WRITE], 0, NULL);
913 m_pContext->OMSetRenderTargets(1, &m_pRenderTargetView, NULL);
915 const FLOAT gray[] = { 0.f, 0.f, 1.f, 1.f };
916 m_pContext->ClearRenderTargetView(m_pRenderTargetView, gray);
918 m_pContext->VSSetShader(m_pVertexShader, NULL, 0);
919 m_pContext->PSSetShader(m_pPixelShader, NULL, 0);
920 m_pContext->PSSetShaderResources(0, 1, &m_pTextureRV);
921 m_pContext->PSSetSamplers(0, 1, &m_pSamplerLinear);
922 m_pContext->Draw(4, 0);
925 m_keyedMutex[BUFFER_VK_WRITE]->ReleaseSync(KEYED_MUTEX_DONE);
926 m_keyedMutex[BUFFER_VK_READ]->ReleaseSync(KEYED_MUTEX_VK_VERIFY);
927 #endif // #if (DE_OS == DE_OS_WIN32)
930 #if (DE_OS == DE_OS_WIN32)
931 void d3dx11CompileShader (const char* shaderCode, const char * entryPoint, const char* shaderModel, ID3D10Blob** ppBlobOut)
935 ID3D10Blob* pErrorBlob;
936 hr = m_fnD3DX11CompileFromMemory (shaderCode,
950 pErrorBlob->Release();
953 TCU_FAIL("D3DX11CompileFromMemory failed to compile shader");
956 void d3dCompileShader (const char* shaderCode, const char * entryPoint, const char* shaderModel, ID3DBlob** ppBlobOut)
960 ID3DBlob* pErrorBlob;
961 hr = m_fnD3DCompile (shaderCode,
973 pErrorBlob->Release();
976 TCU_FAIL("D3DCompile failed to compile shader");
979 void createShaders (const char* shaderSrc,
980 const char* vsEntryPoint,
981 const char* vsShaderModel,
983 D3D11_INPUT_ELEMENT_DESC* pLayoutDesc,
984 ID3D11VertexShader** pVertexShader,
985 const char* psEntryPoint,
986 const char* psShaderModel,
987 ID3D11PixelShader** pPixelShader)
991 if (m_fnD3DX11CompileFromMemory) {
994 d3dx11CompileShader(shaderSrc, vsEntryPoint, vsShaderModel, &pVSBlob);
996 hr = m_pDevice->CreateVertexShader(pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), NULL, pVertexShader);
998 TCU_FAIL("Failed to create DX11 vertex shader");
1000 ID3D11InputLayout *pVertexLayout;
1001 hr = m_pDevice->CreateInputLayout(pLayoutDesc, numLayoutDesc, pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &pVertexLayout);
1003 TCU_FAIL("Failed to create vertex input layout");
1005 m_pContext->IASetInputLayout(pVertexLayout);
1006 pVertexLayout->Release();
1010 ID3D10Blob* pPSBlob;
1011 d3dx11CompileShader(shaderSrc, psEntryPoint, psShaderModel, &pPSBlob);
1013 hr = m_pDevice->CreatePixelShader(pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), NULL, pPixelShader);
1015 TCU_FAIL("Failed to create DX11 pixel shader");
1019 d3dCompileShader(shaderSrc, vsEntryPoint, vsShaderModel, &pVSBlob);
1021 hr = m_pDevice->CreateVertexShader(pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), NULL, pVertexShader);
1023 TCU_FAIL("Failed to create DX11 vertex shader");
1025 ID3D11InputLayout *pVertexLayout;
1026 hr = m_pDevice->CreateInputLayout(pLayoutDesc, numLayoutDesc, pVSBlob->GetBufferPointer(), pVSBlob->GetBufferSize(), &pVertexLayout);
1028 TCU_FAIL("Failed to create vertex input layout");
1030 m_pContext->IASetInputLayout(pVertexLayout);
1031 pVertexLayout->Release();
1036 d3dCompileShader(shaderSrc, psEntryPoint, psShaderModel, &pPSBlob);
1038 hr = m_pDevice->CreatePixelShader(pPSBlob->GetBufferPointer(), pPSBlob->GetBufferSize(), NULL, pPixelShader);
1040 TCU_FAIL("Failed to create DX11 pixel shader");
1043 #endif // #if (DE_OS == DE_OS_WIN32)
1046 #if (DE_OS == DE_OS_WIN32)
1049 if (m_securityAttributes.lpSecurityDescriptor)
1051 freeSecurityDescriptor(m_securityAttributes.lpSecurityDescriptor);
1052 m_securityAttributes.lpSecurityDescriptor = NULL;
1056 m_pContext->ClearState();
1058 if (m_pRenderTargetView)
1060 m_pRenderTargetView->Release();
1061 m_pRenderTargetView = NULL;
1064 if (m_pSamplerLinear)
1066 m_pSamplerLinear->Release();
1067 m_pSamplerLinear = NULL;
1072 m_pTextureRV->Release();
1073 m_pTextureRV = NULL;
1076 if (m_pVertexBuffer)
1078 m_pVertexBuffer->Release();
1079 m_pVertexBuffer = NULL;
1082 if (m_pVertexShader)
1084 m_pVertexShader->Release();
1085 m_pVertexShader = NULL;
1090 m_pPixelShader->Release();
1091 m_pPixelShader = NULL;
1094 for (int i = 0; i < BUFFER_COUNT; i++)
1096 if (m_keyedMutex[i])
1098 m_keyedMutex[i]->AcquireSync(KEYED_MUTEX_DONE, INFINITE);
1099 m_keyedMutex[i]->Release();
1100 m_keyedMutex[i] = NULL;
1103 if (m_isMemNtHandle && m_sharedMemHandle[i]) {
1104 CloseHandle(m_sharedMemHandle[i]);
1105 m_sharedMemHandle[i] = 0;
1109 m_pBuffer[i]->Release();
1110 m_pBuffer[i] = NULL;
1113 if (m_pTexture[i]) {
1114 m_pTexture[i]->Release();
1115 m_pTexture[i] = NULL;
1120 static void* getSecurityDescriptor ()
1122 PSECURITY_DESCRIPTOR pSD = (PSECURITY_DESCRIPTOR)deCalloc(SECURITY_DESCRIPTOR_MIN_LENGTH + 2 * sizeof (void**));
1126 PSID* ppEveryoneSID = (PSID*)((PBYTE)pSD + SECURITY_DESCRIPTOR_MIN_LENGTH);
1127 PACL* ppACL = (PACL*)((PBYTE)ppEveryoneSID + sizeof(PSID*));
1129 bool res = InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION);
1132 SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY;
1133 AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, ppEveryoneSID);
1135 EXPLICIT_ACCESS ea = { };
1136 ea.grfAccessPermissions = STANDARD_RIGHTS_ALL | SPECIFIC_RIGHTS_ALL;
1137 ea.grfAccessMode = SET_ACCESS;
1138 ea.grfInheritance = INHERIT_ONLY;
1139 ea.Trustee.TrusteeForm = TRUSTEE_IS_SID;
1140 ea.Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP;
1141 ea.Trustee.ptstrName = (LPTSTR)*ppEveryoneSID;
1143 SetEntriesInAcl(1, &ea, NULL, ppACL);
1145 res = SetSecurityDescriptorDacl(pSD, TRUE, *ppACL, FALSE);
1152 static void freeSecurityDescriptor (void* pSD)
1156 PSID* ppEveryoneSID = (PSID*)((PBYTE)pSD + SECURITY_DESCRIPTOR_MIN_LENGTH);
1157 PACL* ppACL = (PACL*)((PBYTE)ppEveryoneSID + sizeof(PSID*));
1160 FreeSid(*ppEveryoneSID);
1169 static DXGI_FORMAT getDxgiFormat (vk::VkFormat format)
1173 case vk::VK_FORMAT_R8_UNORM:
1174 return DXGI_FORMAT_R8_UNORM;
1175 case vk::VK_FORMAT_R16_UINT:
1176 return DXGI_FORMAT_R16_UINT;
1177 case vk::VK_FORMAT_R8G8B8A8_UNORM:
1178 return DXGI_FORMAT_R8G8B8A8_UNORM;
1179 case vk::VK_FORMAT_R16G16B16A16_UINT:
1180 return DXGI_FORMAT_R16G16B16A16_UINT;
1181 case vk::VK_FORMAT_R32G32B32A32_SFLOAT:
1182 return DXGI_FORMAT_R32G32B32A32_FLOAT;
1183 case vk::VK_FORMAT_D16_UNORM:
1184 return DXGI_FORMAT_D16_UNORM;
1185 case vk::VK_FORMAT_D32_SFLOAT:
1186 return DXGI_FORMAT_D32_FLOAT;
1188 TCU_CHECK_INTERNAL(!"Unsupported DXGI format");
1189 return DXGI_FORMAT_UNKNOWN;
1193 ResourceDescription m_resourceDesc;
1195 deUint64 m_sharedMemSize;
1196 deUint64 m_sharedMemOffset;
1197 HANDLE m_sharedMemHandle[BUFFER_COUNT];
1198 bool m_isMemNtHandle;
1200 ID3D11Device* m_pDevice;
1201 ID3D11DeviceContext* m_pContext;
1202 LPD3DX11COMPILEFROMMEMORY m_fnD3DX11CompileFromMemory;
1203 pD3DCompile m_fnD3DCompile;
1205 ID3D11RenderTargetView* m_pRenderTargetView;
1206 ID3D11VertexShader* m_pVertexShader;
1207 ID3D11PixelShader* m_pPixelShader;
1208 ID3D11Buffer* m_pVertexBuffer;
1209 ID3D11ShaderResourceView* m_pTextureRV;
1210 ID3D11SamplerState* m_pSamplerLinear;
1212 ID3D11Texture2D* m_pTexture[BUFFER_COUNT];
1213 ID3D11Buffer* m_pBuffer[BUFFER_COUNT];
1214 IDXGIKeyedMutex* m_keyedMutex[BUFFER_COUNT];
1216 SECURITY_ATTRIBUTES m_securityAttributes;
1218 SECURITY_ATTRIBUTES* getSecurityAttributes ()
1220 m_securityAttributes.nLength = sizeof (SECURITY_ATTRIBUTES);
1221 m_securityAttributes.bInheritHandle = TRUE;
1222 if (!m_securityAttributes.lpSecurityDescriptor)
1223 m_securityAttributes.lpSecurityDescriptor = getSecurityDescriptor();
1225 return &m_securityAttributes;
1227 #endif // #if (DE_OS == DE_OS_WIN32)
1230 class DX11OperationSupport
1233 DX11OperationSupport (const vk::InstanceInterface& vki,
1234 vk::VkPhysicalDevice physicalDevice)
1235 #if (DE_OS == DE_OS_WIN32)
1238 , m_hD3DCompilerLib (0)
1240 , m_fnD3D11CreateDevice (0)
1241 , m_fnD3DX11CompileFromMemory (0)
1242 , m_fnD3DCompile (0)
1245 #if (DE_OS == DE_OS_WIN32)
1248 vk::VkPhysicalDeviceIDProperties propertiesId = { vk::VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES };
1249 vk::VkPhysicalDeviceProperties2 properties = { vk::VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2 };
1251 properties.pNext = &propertiesId;
1253 vki.getPhysicalDeviceProperties2(physicalDevice, &properties);
1254 if (!propertiesId.deviceLUIDValid)
1255 TCU_FAIL("Physical device deviceLUIDValid is not valid");
1258 m_hD3D11Lib = LoadLibrary("d3d11.dll");
1260 TCU_FAIL("Failed to load d3d11.dll");
1263 m_fnD3D11CreateDevice = (LPD3D11CREATEDEVICE) GetProcAddress(m_hD3D11Lib, "D3D11CreateDevice");
1264 if (!m_fnD3D11CreateDevice)
1265 TCU_FAIL("Unable to find D3D11CreateDevice() function");
1267 m_hD3DX11Lib = LoadLibrary("d3dx11_42.dll");
1269 m_fnD3DX11CompileFromMemory = (LPD3DX11COMPILEFROMMEMORY) GetProcAddress(m_hD3DX11Lib, "D3DX11CompileFromMemory");
1272 m_hD3DCompilerLib = LoadLibrary("d3dcompiler_43.dll");
1273 if (!m_hD3DCompilerLib)
1274 m_hD3DCompilerLib = LoadLibrary("d3dcompiler_47.dll");
1275 if (!m_hD3DCompilerLib)
1276 TCU_FAIL("Unable to load DX11 d3dcompiler_43.dll or d3dcompiler_47.dll");
1278 m_fnD3DCompile = (pD3DCompile)GetProcAddress(m_hD3DCompilerLib, "D3DCompile");
1279 if (!m_fnD3DCompile)
1280 TCU_FAIL("Unable to load find D3DCompile");
1283 m_hDxgiLib = LoadLibrary("dxgi.dll");
1285 TCU_FAIL("Unable to load DX11 dxgi.dll");
1287 typedef HRESULT (WINAPI *LPCREATEDXGIFACTORY1)(REFIID riid, void** ppFactory);
1288 LPCREATEDXGIFACTORY1 CreateDXGIFactory1 = (LPCREATEDXGIFACTORY1)GetProcAddress(m_hDxgiLib, "CreateDXGIFactory1");
1289 if (!CreateDXGIFactory1)
1290 TCU_FAIL("Unable to load find CreateDXGIFactory1");
1292 IDXGIFactory1* pFactory = NULL;
1293 hr = CreateDXGIFactory1(__uuidof(IDXGIFactory), (void**)&pFactory);
1295 TCU_FAIL("Unable to create IDXGIFactory interface");
1297 IDXGIAdapter *pAdapter = NULL;
1298 for (UINT i = 0; pFactory->EnumAdapters(i, &pAdapter) != DXGI_ERROR_NOT_FOUND; ++i)
1300 DXGI_ADAPTER_DESC desc;
1301 pAdapter->GetDesc(&desc);
1303 if (deMemCmp(&desc.AdapterLuid, propertiesId.deviceLUID, VK_LUID_SIZE_KHR) == 0)
1306 pFactory->Release();
1308 D3D_FEATURE_LEVEL fLevel[] = {D3D_FEATURE_LEVEL_11_0};
1309 UINT devflags = D3D11_CREATE_DEVICE_PREVENT_INTERNAL_THREADING_OPTIMIZATIONS | // no separate D3D11 worker thread
1311 D3D11_CREATE_DEVICE_DEBUG | // useful for diagnosing DX failures
1313 D3D11_CREATE_DEVICE_SINGLETHREADED;
1315 hr = m_fnD3D11CreateDevice (pAdapter,
1316 pAdapter ? D3D_DRIVER_TYPE_UNKNOWN : D3D_DRIVER_TYPE_HARDWARE,
1320 DE_LENGTH_OF_ARRAY(fLevel),
1327 pAdapter->Release();
1331 TCU_FAIL("Failed to created DX11 device");
1333 TCU_FAIL("Failed to created DX11 context");
1336 DE_UNREF(physicalDevice);
1337 TCU_THROW(NotSupportedError, "OS not supported");
1341 ~DX11OperationSupport ()
1343 #if (DE_OS == DE_OS_WIN32)
1348 #if (DE_OS == DE_OS_WIN32)
1352 m_pContext->Release();
1357 m_pDevice->Release();
1363 FreeLibrary(m_hDxgiLib);
1367 if (m_hD3DCompilerLib)
1369 FreeLibrary(m_hD3DCompilerLib);
1370 m_hD3DCompilerLib = 0;
1375 FreeLibrary(m_hD3DX11Lib);
1381 FreeLibrary(m_hD3D11Lib);
1388 virtual de::MovePtr<DX11Operation> build (const ResourceDescription& resourceDesc, vk::VkExternalMemoryHandleTypeFlagBits memoryHandleType) const
1390 #if (DE_OS == DE_OS_WIN32)
1391 return de::MovePtr<DX11Operation>(new DX11Operation(resourceDesc, memoryHandleType, m_pDevice, m_pContext, m_fnD3DX11CompileFromMemory, m_fnD3DCompile));
1393 DE_UNREF(resourceDesc);
1394 DE_UNREF(memoryHandleType);
1395 TCU_THROW(NotSupportedError, "OS not supported");
1401 #if (DE_OS == DE_OS_WIN32)
1402 typedef HRESULT (WINAPI *LPD3D11CREATEDEVICE)(IDXGIAdapter*,
1406 const D3D_FEATURE_LEVEL*,
1411 ID3D11DeviceContext**);
1413 HMODULE m_hD3D11Lib;
1414 HMODULE m_hD3DX11Lib;
1415 HMODULE m_hD3DCompilerLib;
1417 LPD3D11CREATEDEVICE m_fnD3D11CreateDevice;
1418 LPD3DX11COMPILEFROMMEMORY m_fnD3DX11CompileFromMemory;
1419 pD3DCompile m_fnD3DCompile;
1420 ID3D11Device* m_pDevice;
1421 ID3D11DeviceContext* m_pContext;
1425 // Class to wrap a singleton instance and device
1426 class InstanceAndDevice
1428 InstanceAndDevice (Context& context)
1429 : m_instance (createTestInstance(context))
1430 , m_vki (m_instance.getDriver())
1431 , m_physicalDevice (vk::chooseDevice(m_vki, m_instance, context.getTestContext().getCommandLine()))
1432 , m_logicalDevice (createTestDevice(context, m_instance, m_vki, m_physicalDevice))
1433 , m_supportDX11 (new DX11OperationSupport(m_vki, m_physicalDevice))
1439 static vk::VkInstance getInstance(Context& context)
1441 if (!m_instanceAndDevice)
1442 m_instanceAndDevice = SharedPtr<InstanceAndDevice>(new InstanceAndDevice(context));
1444 return m_instanceAndDevice->m_instance;
1446 static const vk::InstanceDriver& getDriver()
1448 DE_ASSERT(m_instanceAndDevice);
1449 return m_instanceAndDevice->m_instance.getDriver();
1451 static vk::VkPhysicalDevice getPhysicalDevice()
1453 DE_ASSERT(m_instanceAndDevice);
1454 return m_instanceAndDevice->m_physicalDevice;
1456 static const Unique<vk::VkDevice>& getDevice()
1458 DE_ASSERT(m_instanceAndDevice);
1459 return m_instanceAndDevice->m_logicalDevice;
1461 static const de::UniquePtr<DX11OperationSupport>& getSupportDX11()
1463 DE_ASSERT(m_instanceAndDevice);
1464 return m_instanceAndDevice->m_supportDX11;
1466 static void collectMessages()
1468 DE_ASSERT(m_instanceAndDevice);
1469 m_instanceAndDevice->m_instance.collectMessages();
1472 static void destroy()
1474 m_instanceAndDevice.clear();
1478 CustomInstance m_instance;
1479 const vk::InstanceDriver& m_vki;
1480 const vk::VkPhysicalDevice m_physicalDevice;
1481 const Unique<vk::VkDevice> m_logicalDevice;
1482 const de::UniquePtr<DX11OperationSupport> m_supportDX11;
1484 static SharedPtr<InstanceAndDevice> m_instanceAndDevice;
1486 SharedPtr<InstanceAndDevice> InstanceAndDevice::m_instanceAndDevice;
1489 class Win32KeyedMutexTestInstance : public TestInstance
1492 Win32KeyedMutexTestInstance (Context& context,
1495 virtual tcu::TestStatus iterate (void);
1498 const TestConfig m_config;
1499 const de::UniquePtr<OperationSupport> m_supportWriteOp;
1500 const de::UniquePtr<OperationSupport> m_supportReadOp;
1502 const vk::VkInstance m_instance;
1504 const vk::InstanceDriver& m_vki;
1505 const vk::VkPhysicalDevice m_physicalDevice;
1506 const std::vector<vk::VkQueueFamilyProperties> m_queueFamilies;
1507 const std::vector<deUint32> m_queueFamilyIndices;
1508 const vk::Unique<vk::VkDevice>& m_device;
1509 const vk::DeviceDriver m_vkd;
1511 const vk::VkExternalMemoryHandleTypeFlagBits m_memoryHandleType;
1513 // \todo Should this be moved to the group same way as in the other tests?
1514 PipelineCacheData m_pipelineCacheData;
1515 tcu::ResultCollector m_resultCollector;
1518 bool m_useDedicatedAllocation;
1521 Win32KeyedMutexTestInstance::Win32KeyedMutexTestInstance (Context& context,
1523 : TestInstance (context)
1525 , m_supportWriteOp (makeOperationSupport(config.writeOp, config.resource))
1526 , m_supportReadOp (makeOperationSupport(config.readOp, config.resource))
1528 , m_instance (InstanceAndDevice::getInstance(context))
1530 , m_vki (InstanceAndDevice::getDriver())
1531 , m_physicalDevice (InstanceAndDevice::getPhysicalDevice())
1532 , m_queueFamilies (vk::getPhysicalDeviceQueueFamilyProperties(m_vki, m_physicalDevice))
1533 , m_queueFamilyIndices (getFamilyIndices(m_queueFamilies))
1534 , m_device (InstanceAndDevice::getDevice())
1535 , m_vkd (context.getPlatformInterface(), m_instance, *m_device)
1537 , m_memoryHandleType ((m_config.resource.type == RESOURCE_TYPE_IMAGE) ? m_config.memoryHandleTypeImage : m_config.memoryHandleTypeBuffer)
1539 , m_resultCollector (context.getTestContext().getLog())
1542 , m_useDedicatedAllocation (false)
1544 #if (DE_OS == DE_OS_WIN32)
1545 TestLog& log = m_context.getTestContext().getLog();
1547 // Check resource support
1548 if (m_config.resource.type == RESOURCE_TYPE_IMAGE)
1550 if (m_memoryHandleType == vk::VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_BIT && !IsWindows8OrGreater())
1551 TCU_THROW(NotSupportedError, "Memory handle type not supported by this OS");
1553 const vk::VkPhysicalDeviceExternalImageFormatInfo externalInfo =
1555 vk::VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
1559 const vk::VkPhysicalDeviceImageFormatInfo2 imageFormatInfo =
1561 vk::VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2,
1563 m_config.resource.imageFormat,
1564 m_config.resource.imageType,
1565 vk::VK_IMAGE_TILING_OPTIMAL,
1566 m_supportReadOp->getInResourceUsageFlags() | m_supportWriteOp->getOutResourceUsageFlags(),
1569 vk::VkExternalImageFormatProperties externalProperties =
1571 vk::VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES,
1575 vk::VkImageFormatProperties2 formatProperties =
1577 vk::VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2,
1578 &externalProperties,
1587 const vk::VkResult res = m_vki.getPhysicalDeviceImageFormatProperties2(m_physicalDevice, &imageFormatInfo, &formatProperties);
1588 if (res == vk::VK_ERROR_FORMAT_NOT_SUPPORTED)
1589 TCU_THROW(NotSupportedError, "Handle type is not compatible");
1592 // \todo How to log this nicely?
1593 log << TestLog::Message << "External image format properties: " << imageFormatInfo << "\n"<< externalProperties << TestLog::EndMessage;
1595 if ((externalProperties.externalMemoryProperties.externalMemoryFeatures & vk::VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT) == 0)
1596 TCU_THROW(NotSupportedError, "Importing image resource not supported");
1598 if (externalProperties.externalMemoryProperties.externalMemoryFeatures & vk::VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT)
1599 m_useDedicatedAllocation = true;
1603 if (m_memoryHandleType == vk::VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_BIT && !IsWindows8OrGreater())
1604 TCU_THROW(NotSupportedError, "Memory handle type not supported by this OS");
1606 const vk::VkPhysicalDeviceExternalBufferInfo info =
1608 vk::VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_BUFFER_INFO,
1612 m_supportReadOp->getInResourceUsageFlags() | m_supportWriteOp->getOutResourceUsageFlags(),
1615 vk::VkExternalBufferProperties properties =
1617 vk::VK_STRUCTURE_TYPE_EXTERNAL_BUFFER_PROPERTIES,
1621 m_vki.getPhysicalDeviceExternalBufferProperties(m_physicalDevice, &info, &properties);
1623 log << TestLog::Message << "External buffer properties: " << info << "\n" << properties << TestLog::EndMessage;
1625 if ((properties.externalMemoryProperties.externalMemoryFeatures & vk::VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT) == 0)
1626 TCU_THROW(NotSupportedError, "Importing memory type not supported");
1628 if (properties.externalMemoryProperties.externalMemoryFeatures & vk::VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT)
1629 m_useDedicatedAllocation = true;
1632 DE_UNREF(m_useDedicatedAllocation);
1633 TCU_THROW(NotSupportedError, "OS not supported");
1637 tcu::TestStatus Win32KeyedMutexTestInstance::iterate (void)
1639 TestLog& log (m_context.getTestContext().getLog());
1643 const deUint32 queueFamily = (deUint32)m_queueNdx;
1645 const tcu::ScopedLogSection queuePairSection (log, "Queue-" + de::toString(queueFamily), "Queue-" + de::toString(queueFamily));
1647 const vk::VkQueue queue (getDeviceQueue(m_vkd, *m_device, queueFamily, 0u));
1648 const vk::Unique<vk::VkCommandPool> commandPool (createCommandPool(m_vkd, *m_device, 0u, queueFamily));
1649 const vk::Unique<vk::VkCommandBuffer> commandBufferWrite (allocateCommandBuffer(m_vkd, *m_device, *commandPool, vk::VK_COMMAND_BUFFER_LEVEL_PRIMARY));
1650 const vk::Unique<vk::VkCommandBuffer> commandBufferRead (allocateCommandBuffer(m_vkd, *m_device, *commandPool, vk::VK_COMMAND_BUFFER_LEVEL_PRIMARY));
1651 vk::SimpleAllocator allocator (m_vkd, *m_device, vk::getPhysicalDeviceMemoryProperties(m_vki, m_physicalDevice));
1652 OperationContext operationContext (m_context, SynchronizationType::LEGACY, m_vki, m_vkd, m_physicalDevice, *m_device, allocator, m_context.getBinaryCollection(), m_pipelineCacheData);
1654 if (!checkQueueFlags(m_queueFamilies[m_queueNdx].queueFlags, vk::VK_QUEUE_GRAPHICS_BIT))
1655 TCU_THROW(NotSupportedError, "Operation not supported by the source queue");
1657 const de::UniquePtr<DX11Operation> dx11Op (InstanceAndDevice::getSupportDX11()->build(m_config.resource, m_memoryHandleType));
1659 NativeHandle nativeHandleWrite = dx11Op->getNativeHandle(DX11Operation::BUFFER_VK_WRITE);
1660 const de::UniquePtr<Resource> resourceWrite (importResource(m_vkd, *m_device, m_config.resource, m_queueFamilyIndices, *m_supportReadOp, *m_supportWriteOp, nativeHandleWrite, m_memoryHandleType));
1662 NativeHandle nativeHandleRead = dx11Op->getNativeHandle(DX11Operation::BUFFER_VK_READ);
1663 const de::UniquePtr<Resource> resourceRead (importResource(m_vkd, *m_device, m_config.resource, m_queueFamilyIndices, *m_supportReadOp, *m_supportWriteOp, nativeHandleRead, m_memoryHandleType));
1665 const de::UniquePtr<Operation> writeOp (m_supportWriteOp->build(operationContext, *resourceWrite));
1666 const de::UniquePtr<Operation> readOp (m_supportReadOp->build(operationContext, *resourceRead));
1668 const SyncInfo writeSync = writeOp->getOutSyncInfo();
1669 const SyncInfo readSync = readOp->getInSyncInfo();
1671 beginCommandBuffer(m_vkd, *commandBufferWrite);
1672 writeOp->recordCommands(*commandBufferWrite);
1673 recordWriteBarrier(m_vkd, *commandBufferWrite, *resourceWrite, writeSync, queueFamily, readSync);
1674 endCommandBuffer(m_vkd, *commandBufferWrite);
1676 beginCommandBuffer(m_vkd, *commandBufferRead);
1677 recordReadBarrier(m_vkd, *commandBufferRead, *resourceRead, writeSync, readSync, queueFamily);
1678 readOp->recordCommands(*commandBufferRead);
1679 endCommandBuffer(m_vkd, *commandBufferRead);
1682 vk::VkDeviceMemory memory = resourceWrite->getMemory();
1683 deUint64 keyInit = DX11Operation::KEYED_MUTEX_VK_WRITE;
1684 deUint32 timeout = 0xFFFFFFFF; // INFINITE
1685 deUint64 keyExternal = DX11Operation::KEYED_MUTEX_DX_COPY;
1686 vk::VkWin32KeyedMutexAcquireReleaseInfoKHR keyedMutexInfo =
1688 vk::VK_STRUCTURE_TYPE_WIN32_KEYED_MUTEX_ACQUIRE_RELEASE_INFO_KHR,
1701 const vk::VkCommandBuffer commandBuffer = *commandBufferWrite;
1702 const vk::VkSubmitInfo submitInfo =
1704 vk::VK_STRUCTURE_TYPE_SUBMIT_INFO,
1717 VK_CHECK(m_vkd.queueSubmit(queue, 1u, &submitInfo, DE_NULL));
1720 dx11Op->copyMemory();
1723 vk::VkDeviceMemory memory = resourceRead->getMemory();
1724 deUint64 keyInternal = DX11Operation::KEYED_MUTEX_VK_VERIFY;
1725 deUint32 timeout = 0xFFFFFFFF; // INFINITE
1726 deUint64 keyExternal = DX11Operation::KEYED_MUTEX_DONE;
1727 vk::VkWin32KeyedMutexAcquireReleaseInfoKHR keyedMutexInfo =
1729 vk::VK_STRUCTURE_TYPE_WIN32_KEYED_MUTEX_ACQUIRE_RELEASE_INFO_KHR,
1742 const vk::VkCommandBuffer commandBuffer = *commandBufferRead;
1743 const vk::VkSubmitInfo submitInfo =
1745 vk::VK_STRUCTURE_TYPE_SUBMIT_INFO,
1758 VK_CHECK(m_vkd.queueSubmit(queue, 1u, &submitInfo, DE_NULL));
1761 VK_CHECK(m_vkd.queueWaitIdle(queue));
1764 const Data expected = writeOp->getData();
1765 const Data actual = readOp->getData();
1767 DE_ASSERT(expected.size == actual.size);
1769 if (0 != deMemCmp(expected.data, actual.data, expected.size))
1771 const size_t maxBytesLogged = 256;
1772 std::ostringstream expectedData;
1773 std::ostringstream actualData;
1776 // Find first byte difference
1777 for (; actual.data[byteNdx] == expected.data[byteNdx]; byteNdx++)
1782 log << TestLog::Message << "First different byte at offset: " << byteNdx << TestLog::EndMessage;
1784 // Log 8 previous bytes before the first incorrect byte
1787 expectedData << "... ";
1788 actualData << "... ";
1795 for (size_t i = 0; i < maxBytesLogged && byteNdx < expected.size; i++, byteNdx++)
1797 expectedData << (i > 0 ? ", " : "") << (deUint32)expected.data[byteNdx];
1798 actualData << (i > 0 ? ", " : "") << (deUint32)actual.data[byteNdx];
1801 if (expected.size > byteNdx)
1803 expectedData << "...";
1804 actualData << "...";
1807 log << TestLog::Message << "Expected data: (" << expectedData.str() << ")" << TestLog::EndMessage;
1808 log << TestLog::Message << "Actual data: (" << actualData.str() << ")" << TestLog::EndMessage;
1810 m_resultCollector.fail("Memory contents don't match");
1814 catch (const tcu::NotSupportedError& error)
1816 log << TestLog::Message << "Not supported: " << error.getMessage() << TestLog::EndMessage;
1818 catch (const tcu::TestError& error)
1820 m_resultCollector.fail(std::string("Exception: ") + error.getMessage());
1823 // Collect possible validation errors.
1824 InstanceAndDevice::collectMessages();
1826 // Move to next queue
1830 if (m_queueNdx >= m_queueFamilies.size())
1832 return tcu::TestStatus(m_resultCollector.getResult(), m_resultCollector.getMessage());
1836 return tcu::TestStatus::incomplete();
1843 void init (vk::SourceCollections& dst, TestConfig config) const
1845 const de::UniquePtr<OperationSupport> readOp (makeOperationSupport(config.readOp, config.resource));
1846 const de::UniquePtr<OperationSupport> writeOp (makeOperationSupport(config.writeOp, config.resource));
1848 readOp->initPrograms(dst);
1849 writeOp->initPrograms(dst);
1855 static void createTests (tcu::TestCaseGroup* group)
1857 tcu::TestContext& testCtx = group->getTestContext();
1860 vk::VkExternalMemoryHandleTypeFlagBits memoryHandleTypeBuffer;
1861 vk::VkExternalMemoryHandleTypeFlagBits memoryHandleTypeImage;
1862 const char* nameSuffix;
1866 (vk::VkExternalMemoryHandleTypeFlagBits)0u, // DX11 doesn't support buffers with an NT handle
1867 vk::VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_BIT,
1871 vk::VK_EXTERNAL_MEMORY_HANDLE_TYPE_OPAQUE_WIN32_KMT_BIT,
1872 vk::VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_KMT_BIT,
1877 for (size_t writeOpNdx = 0; writeOpNdx < DE_LENGTH_OF_ARRAY(s_writeOps); ++writeOpNdx)
1878 for (size_t readOpNdx = 0; readOpNdx < DE_LENGTH_OF_ARRAY(s_readOps); ++readOpNdx)
1880 const OperationName writeOp = s_writeOps[writeOpNdx];
1881 const OperationName readOp = s_readOps[readOpNdx];
1882 const std::string opGroupName = getOperationName(writeOp) + "_" + getOperationName(readOp);
1885 de::MovePtr<tcu::TestCaseGroup> opGroup (new tcu::TestCaseGroup(testCtx, opGroupName.c_str(), ""));
1887 for (size_t resourceNdx = 0; resourceNdx < DE_LENGTH_OF_ARRAY(s_resourcesWin32KeyedMutex); ++resourceNdx)
1889 const ResourceDescription& resource = s_resourcesWin32KeyedMutex[resourceNdx];
1891 for (size_t caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(cases); caseNdx++)
1893 if (resource.type == RESOURCE_TYPE_BUFFER && !cases[caseNdx].memoryHandleTypeBuffer)
1896 if (resource.type == RESOURCE_TYPE_IMAGE && !cases[caseNdx].memoryHandleTypeImage)
1899 std::string name = getResourceName(resource) + cases[caseNdx].nameSuffix;
1901 if (isResourceSupported(writeOp, resource) && isResourceSupported(readOp, resource))
1903 const TestConfig config (resource, writeOp, readOp, cases[caseNdx].memoryHandleTypeBuffer, cases[caseNdx].memoryHandleTypeImage);
1905 opGroup->addChild(new InstanceFactory1<Win32KeyedMutexTestInstance, TestConfig, Progs>(testCtx, tcu::NODETYPE_SELF_VALIDATE, name, "", Progs(), config));
1912 group->addChild(opGroup.release());
1916 static void cleanupGroup (tcu::TestCaseGroup* group)
1919 // Destroy singleton object
1920 InstanceAndDevice::destroy();
1923 tcu::TestCaseGroup* createWin32KeyedMutexTest (tcu::TestContext& testCtx)
1925 return createTestGroup(testCtx, "win32_keyed_mutex", "", createTests, cleanupGroup);
1928 } // synchronization