Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2648,6 +2648,8 @@ if(TARGET Vulkan::Headers)
target_compile_definitions(d3d12_existing_heap_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
target_compile_options(d3d12_existing_heap_test PRIVATE /W4 /permissive- /utf-8)
add_test(NAME d3d12_existing_heap COMMAND d3d12_existing_heap_test)
add_test(NAME d3d12_host_prefix COMMAND d3d12_existing_heap_test --host-prefix-only)
set_tests_properties(d3d12_host_prefix PROPERTIES SKIP_RETURN_CODE 77)
set_tests_properties(d3d12_existing_heap PROPERTIES SKIP_RETURN_CODE 77)
# The same with write watching off: the guarded cases only, the concurrent writers among them.
add_test(NAME d3d12_existing_heap_no_write_watch COMMAND d3d12_existing_heap_test)
Expand Down
23 changes: 11 additions & 12 deletions runtime/shims/d3d12_vulkan_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5750,14 +5750,13 @@ class Resource final
const VkDeviceSize alignment = device_.info.host_pointer_alignment;
if (!device_.get_host_pointer_properties || !alignment) return E_NOTIMPL;
const auto start = reinterpret_cast<std::uintptr_t>(address);
if (!address || !desc_.Width || desc_.Width > UINT64_MAX - 2 * alignment) return E_INVALIDARG;
if (start & 3) return E_NOTIMPL; // byte-unaligned copies keep the ordinary-buffer fallback
if (!address || !desc_.Width || alignment > UINT64_MAX / 2 ||
(alignment & (alignment - 1)) || desc_.Width > UINT64_MAX - 2 * alignment) return E_INVALIDARG;
const bool need_bda = device_.info.buffer_device_address || device_.arena.buffer != VK_NULL_HANDLE;
// Apply the same backing size rule to imports. The committed-range check and Vulkan bind requirements
// below cover the padding as well. The import never initializes or writes the caller's padding.
// Keep the device-address word padding, and include the host page prefix in the backing buffer.
const VkDeviceSize backing_size = need_bda ? align_up(desc_.Width, sizeof(std::uint32_t)) : desc_.Width;
// The import starts at the page that holds `address`, and the buffer is bound at the offset inside it: the
// title places small buffers inside a page too (a 16-byte UAV at a 64-byte-aligned address on an RTX 5090,
// found in review), which an import of `address` itself would refuse.
// Bind at zero; replay and device addresses carry the logical buffer's prefix instead.
const std::uintptr_t base = start & ~static_cast<std::uintptr_t>(alignment - 1);
void* const base_address = reinterpret_cast<void*>(base);
const VkDeviceSize offset = start - base;
Expand Down Expand Up @@ -5801,7 +5800,7 @@ class Resource final
VkExternalMemoryBufferCreateInfo external{VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO};
external.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT;
VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, &external};
info.size = backing_size;
info.size = offset + backing_size;
info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT |
VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT |
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT |
Expand Down Expand Up @@ -5835,9 +5834,8 @@ class Resource final
&host) != VK_SUCCESS)
return decline(E_NOTIMPL);
const std::uint32_t types = host.memoryTypeBits & requirements.memoryTypeBits;
// An offset off the buffer's own alignment cannot be bound: the fallback answers.
if (!types || (offset % requirements.alignment) || requirements.size > bytes - offset)
return decline(E_NOTIMPL);
// The binding is at zero; requirements cover the prefix as part of the buffer.
if (!types || requirements.size > bytes) return decline(E_NOTIMPL);
VkImportMemoryHostPointerInfoEXT import{VK_STRUCTURE_TYPE_IMPORT_MEMORY_HOST_POINTER_INFO_EXT};
import.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_HOST_ALLOCATION_BIT_EXT;
import.pHostPointer = base_address;
Expand Down Expand Up @@ -5869,12 +5867,12 @@ class Resource final
if (memory_) break;
}
if (!memory_) return decline(E_OUTOFMEMORY);
if (vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, offset) != VK_SUCCESS)
return decline(E_OUTOFMEMORY);
if (vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, 0) != VK_SUCCESS) return decline(E_OUTOFMEMORY);
if (need_bda && vk.vkGetBufferDeviceAddress) {
VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO};
bda.buffer = buffer_;
buffer_va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &bda);
if (buffer_va_) buffer_va_ += offset;
gpu_va_ = buffer_va_;
}
// An import the driver put below the arena cannot be named by a V#: the V# keeps 48 bits of (device address
Expand Down Expand Up @@ -5913,6 +5911,7 @@ class Resource final
leonida::ResourceBinding binding{};
binding.buffer = buffer_;
binding.indirect_arguments = (info.usage & VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT) != 0;
binding.buffer_offset = offset;
binding.size = desc_.Width;
binding.host = static_cast<const std::uint8_t*>(address);
binding.host_readable = true;
Expand Down
14 changes: 8 additions & 6 deletions runtime/src/vulkan_replay.h
Original file line number Diff line number Diff line change
Expand Up @@ -2192,7 +2192,9 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) {
return ReplayResult::invalid_copy;
if (buffer.size > UINT64_MAX - buffer.buffer_offset) return ReplayResult::invalid_copy;
const VkDeviceSize backing_offset = buffer.buffer_offset + offset;
if (backing_offset % alignment && !copy.tile_footprint) return unsupported_at(__LINE__);
// A host-import prefix may be word aligned without being texel aligned (e.g. +4 for RGBA16).
// The replay stages those copies through aligned scratch; VkBufferCopy still needs word alignment.
if (backing_offset % alignment && backing_offset % 4 && !copy.tile_footprint) return unsupported_at(__LINE__);
VkBufferImageCopy region{};
region.bufferOffset = backing_offset;
region.bufferRowLength = placed.row_pitch / format.bytes * format.block;
Expand All @@ -2212,13 +2214,13 @@ inline ReplayResult prepare_texture_copy(const CopyTexture& copy, Prepared& p) {
return ReplayResult::success;
}

// CopyTiles accepts arbitrary byte offsets into its linear buffer, while VkBufferImageCopy requires texel/block
// CopyTiles byte offsets and word-aligned imported host prefixes may violate VkBufferImageCopy texel/block
// alignment (VUID-vkCmdCopyBufferToImage-dstImage-07975). Stage only the occupied texels/blocks through aligned
// transfer scratch; leave partial-tile padding alone.
inline bool stage_unaligned_tile(const ReplayFunctions& vk, Prepared& p, const ResourceBinding& image,
const BlockFormat& fmt, bool upload) {
auto& region = p.buffer_image_copies.front();
if (!fmt.bytes || !fmt.block || image.rgb96 ||
if (!vk.copy_buffer || !fmt.bytes || !fmt.block || image.rgb96 ||
(image.depth24_as_float && region.imageSubresource.aspectMask == VK_IMAGE_ASPECT_DEPTH_BIT))
return false;
const VkDeviceSize blocks_w = (VkDeviceSize(region.imageExtent.width) + fmt.block - 1) / fmt.block;
Expand Down Expand Up @@ -3067,8 +3069,8 @@ inline void plan_statistics_segments(PreparedList& out) {
}

// Overlapping pipeline-statistics queries (D3D-252): the same physical-segment layout the occlusion planner
// builds, in the statistics pool. Each Begin and End of a statistics query — and every non-timestamp resolve
// while one runs, because its helper dispatch would be counted — closes the one open physical query and opens
// builds, in the statistics pool. Each Begin and End of a statistics query — and every non-timestamp resolve
// while one runs, because its helper dispatch would be counted — closes the one open physical query and opens
// a new one, so each logical query keeps a contiguous slot range and its result is the sum of that range
// (statistics_sum.comp). A Begin or End of another query kind leaves the segments alone.
inline ReplayResult plan_overlapping_statistics_segments(PreparedList& out) {
Expand Down Expand Up @@ -3562,7 +3564,7 @@ ReplayResult prepare(const CommandList& list, Resolve&& resolve, const ReplayFun
static_cast<unsigned long long>(n));
}
const ResourceBinding& image = upload ? p.binding : p.source;
if (result == ReplayResult::success && texture_copy->tile_footprint && !p.buffer_image_copies.empty()) {
if (result == ReplayResult::success && !p.buffer_image_copies.empty()) {
const auto& region = p.buffer_image_copies.front();
const BlockFormat fmt = copy_block_format(image, region.imageSubresource.aspectMask);
const std::uint32_t alignment =
Expand Down
130 changes: 128 additions & 2 deletions runtime/test/d3d12_existing_heap_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -223,14 +223,16 @@ int check_import(ID3D12Device* device, bool supported) {
// pagefile-backed section with EPERM (measured on an RX 9060 XT under Wine, found in review), while NVIDIA and
// AMD's Windows driver import it. The fallback is checked to exist; the readback below needs the import. Since the shadow fallback
// keeps the title's VA, a refused import still reads back through the shadow.
int check_title_placed(ID3D12Device* device, const char* kind, void* pages, UINT64 size, bool may_refuse = false) {
int check_title_placed(ID3D12Device* device, const char* kind, void* pages, UINT64 size, bool may_refuse = false, bool buffers_only = false) {
const char* who = "vulkan slot-133 buffer";
D3D12_RESOURCE_DESC desc{};
desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
desc.Width = size;
desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1;
desc.SampleDesc.Count = 1;
desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
const std::vector<std::uint8_t> initial(static_cast<std::uint8_t*>(pages),
static_cast<std::uint8_t*>(pages) + size);
Ref<ID3D12Resource> buffer;
EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&buffer.p)), S_OK);
if (may_refuse && buffer->GetGPUVirtualAddress() != reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(pages)) {
Expand All @@ -239,6 +241,7 @@ int check_title_placed(ID3D12Device* device, const char* kind, void* pages, UINT
return 0;
}
EXPECT(buffer->GetGPUVirtualAddress() == reinterpret_cast<D3D12_GPU_VIRTUAL_ADDRESS>(pages));
EXPECT(std::memcmp(pages, initial.data(), initial.size()) == 0);
auto* bytes = static_cast<std::uint8_t*>(pages);
for (UINT64 i = 0; i < size; ++i) bytes[i] = static_cast<std::uint8_t>(i * 131u + 7u);

Expand Down Expand Up @@ -272,6 +275,102 @@ int check_title_placed(ID3D12Device* device, const char* kind, void* pages, UINT
readback->Unmap(0, nullptr);
EXPECT(same);

// Reverse the copy: a real import writes the caller's pages, including for sub-page allocations.
D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD};
Ref<ID3D12Resource> upload;
EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &desc,
D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
IID_PPV_ARGS(&upload.p))));
std::vector<std::uint8_t> reversed(static_cast<size_t>(size));
for (size_t i = 0; i < reversed.size(); ++i) reversed[i] = static_cast<std::uint8_t>(i * 17u + 0x39u);
EXPECT(SUCCEEDED(upload->Map(0, nullptr, &mapped)));
std::memcpy(mapped, reversed.data(), reversed.size());
upload->Unmap(0, nullptr);
EXPECT(SUCCEEDED(allocator->Reset()));
EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr)));
D3D12_RESOURCE_BARRIER barrier{};
barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
barrier.Transition = {buffer.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST};
list->ResourceBarrier(1, &barrier);
list->CopyBufferRegion(buffer.p, 0, upload.p, 0, size);
EXPECT(SUCCEEDED(list->Close()));
queue->ExecuteCommandLists(1, lists);
EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
EXPECT(SUCCEEDED(queue->Signal(fence.p, 2)));
done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
EXPECT(done != nullptr && SUCCEEDED(fence->SetEventOnCompletion(2, done)));
const DWORD waited = WaitForSingleObject(done, 10000);
CloseHandle(done);
EXPECT(waited == WAIT_OBJECT_0);
// A refused import (`may_refuse`) is a shadow at the same VA: filled from the pages before every submission but
// never written back, so only a real import shows the copy in the caller's pages.
if (!(may_refuse && rt::d3d12::title_shadow_buffer(buffer.p))) {
EXPECT(std::memcmp(pages, reversed.data(), reversed.size()) == 0);
}

if (buffers_only) {
// RGBA16 requires an 8-byte Vulkan buffer-image offset, while an imported host prefix may be +4.
// Exercise both directions and verify every untouched host byte, including row padding.
D3D12_RESOURCE_DESC td{};
td.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
td.Width = 1;
td.Height = 2;
td.DepthOrArraySize = td.MipLevels = 1;
td.Format = DXGI_FORMAT_R16G16B16A16_UNORM;
td.SampleDesc.Count = 1;
D3D12_HEAP_PROPERTIES gpu_heap{D3D12_HEAP_TYPE_DEFAULT};
Ref<ID3D12Resource> image;
EXPECT(SUCCEEDED(device->CreateCommittedResource(&gpu_heap, D3D12_HEAP_FLAG_NONE, &td,
D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&image.p))));
D3D12_TEXTURE_COPY_LOCATION linear{};
linear.pResource = buffer.p;
linear.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT;
linear.PlacedFootprint.Footprint = {td.Format, 1, 2, 1, 256};
D3D12_TEXTURE_COPY_LOCATION tex{};
tex.pResource = image.p;
tex.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX;
EXPECT(SUCCEEDED(allocator->Reset()));
EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr)));
barrier.Transition = {buffer.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE};
list->ResourceBarrier(1, &barrier);
list->CopyTextureRegion(&tex, 0, 0, 0, &linear, nullptr);
EXPECT(SUCCEEDED(list->Close()));
queue->ExecuteCommandLists(1, lists);
EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
EXPECT(SUCCEEDED(queue->Signal(fence.p, 3)));
done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
EXPECT(done && SUCCEEDED(fence->SetEventOnCompletion(3, done)));
const DWORD uploaded = WaitForSingleObject(done, 10000);
CloseHandle(done);
EXPECT(uploaded == WAIT_OBJECT_0);
std::memset(pages, 0x6d, static_cast<size_t>(size));
EXPECT(SUCCEEDED(allocator->Reset()));
EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr)));
D3D12_RESOURCE_BARRIER transitions[2] = {barrier, barrier};
transitions[0].Transition = {image.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE};
transitions[1].Transition = {buffer.p, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES,
D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COPY_DEST};
list->ResourceBarrier(2, transitions);
list->CopyTextureRegion(&linear, 0, 0, 0, &tex, nullptr);
EXPECT(SUCCEEDED(list->Close()));
queue->ExecuteCommandLists(1, lists);
EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success);
EXPECT(SUCCEEDED(queue->Signal(fence.p, 4)));
done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
EXPECT(done && SUCCEEDED(fence->SetEventOnCompletion(4, done)));
const DWORD downloaded = WaitForSingleObject(done, 10000);
CloseHandle(done);
EXPECT(downloaded == WAIT_OBJECT_0);
for (size_t i = 0; i < static_cast<size_t>(size); ++i) {
const bool texel = i < 8 || (i >= 256 && i < 264);
EXPECT(bytes[i] == (texel ? reversed[i] : 0x6d));
}
return 0;
}

D3D12_RESOURCE_DESC texture = desc;
texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
texture.Width = texture.Height = 64;
Expand Down Expand Up @@ -480,6 +579,25 @@ int check_title_placed_shadow(ID3D12Device* device, const char* kind, void* page
return 0;
}

// Independent of OpenExistingHeapFromAddress: only actual imported-buffer copies and surrounding-byte checks.
int check_host_prefix_buffers(ID3D12Device* device) {
constexpr SIZE_T size = 4 * 0x10000;
auto* pages = static_cast<unsigned char*>(VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
if (!pages) return 1;
int failures = 0;
for (unsigned prefix : {0u, 4u, 8u, 16u, 32u, 64u}) {
std::memset(pages, 0xa5, size);
failures += check_title_placed(device, "host prefix buffer", pages + prefix, 0x1000 - prefix,
false, true);
for (unsigned i = 0; i < prefix; ++i) failures += pages[i] != 0xa5;
for (SIZE_T i = 0x1000; i < size; ++i) failures += pages[i] != 0xa5;
}
VirtualFree(pages, 0, MEM_RELEASE);
std::printf("host prefix buffers: 0/4/8/16/32/64-byte offsets, bidirectional buffer/texture copies and surrounding bytes: %s\n",
failures ? "FAIL" : "PASS");
return failures;
}

int check_title_placed_all(ID3D12Device* device) {
constexpr SIZE_T size = 4 * 0x10000;
int failures = 0;
Expand All @@ -490,6 +608,7 @@ int check_title_placed_all(ID3D12Device* device) {
// Inside a page, as the title places small UAV buffers (64-byte aligned, found in review on an RTX 5090): the
// import starts at the page and the buffer is bound at the offset.
failures += check_title_placed(device, "64 bytes into a page", static_cast<char*>(pages) + 64, 0x1000 - 64);
failures += check_host_prefix_buffers(device);
VirtualFree(pages, 0, MEM_RELEASE);
HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, DWORD(size), nullptr);
void* view = section ? MapViewOfFile(section, FILE_MAP_ALL_ACCESS, 0, 0, size) : nullptr;
Expand Down Expand Up @@ -1869,7 +1988,9 @@ void print_cases(const std::vector<Case>& cases, const char* who) {
}
} // namespace

int main() {
int main(int argc, char** argv) {
const bool prefix_only = argc == 2 && std::strcmp(argv[1], "--host-prefix-only") == 0;
if (argc != 1 && !prefix_only) return 2;
_putenv_s("LEONIDA_TITLE_TEXTURE_PERIOD_MS", "0");
_putenv_s("LEONIDA_TITLE_TEXTURE_CHECK_KB", "0");
vktest::Device vk;
Expand All @@ -1892,6 +2013,11 @@ int main() {
info.bindless_partially_bound = vk.partially_bound;
info.robust_image_access = vk.robust_image_access; // a Texture3D UAV is bound only with it
if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1;
if (prefix_only) {
if (!vk.host_pointer_alignment) return 77;
const int result = check_host_prefix_buffers(ours.p);
return result || vk.validation_errors() ? 1 : 0;
}
failures += check(ours.p, "vulkan");
const std::vector<Case> vulkan_cases = open_cases(ours.p);
print_cases(vulkan_cases, "vulkan");
Expand Down
Loading