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
13 changes: 7 additions & 6 deletions docs/d3d12_vulkan.md
Original file line number Diff line number Diff line change
Expand Up @@ -962,7 +962,8 @@ The compute path, end to end:
- With `VK_EXT_conditional_rendering`, the arena is created with the conditional-rendering usage, and
`SetPredication` on a default-heap buffer reads at the buffer's offset in the arena plus the call's offset.
- `CreateHeap` reserves the requested size in the arena at 64 KiB, and a buffer placed in it gets the heap's
place plus the placed offset as its console VA. A placed texture keeps its own `VkDeviceMemory` and a null VA,
place plus the placed offset as its console VA. A placed texture has memory of its own (a range of a
shared block or its own `VkDeviceMemory`, section 3.3) and a null VA,
1D, 2D and 3D alike (arrays and mips included), and a dimension outside the enum is `E_INVALIDARG`, as on the
host (RTX 2080 Ti and WARP, `d3d12_placed_dimensions_test`);
tiled (`64KB_UNDEFINED_SWIZZLE` and Xbox `0x101`) 2D/3D placed textures are backed the same way with
Expand Down Expand Up @@ -1479,8 +1480,8 @@ The layer therefore owns the console VAs. It returns them from `ID3D12Resource::
|---|---|
| Address space | Two ranges. A **BDA arena** holds buffers, descriptor heaps and shader code; its device address is `heap_base`. A separate **image key range** supplies unique console VAs for images; those keys are never added to `heap_base`. The arena's `VkBuffer` is created with all buffer usages the game can bind (uniform, storage, vertex, index, indirect, transfer) plus `SHADER_DEVICE_ADDRESS`, and its memory with `VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT`. |
| Buffers | A buffer resource is a range in the arena's single `VkBuffer`: offset = its console VA, size = the resource size. Buffer commands bind the arena buffer with that offset, so its device address is exactly `arena_bda + offset`; no per-resource `VkBuffer` object is needed. |
| Images | Each image gets a unique console VA key and lives in its own `VkDeviceMemory` (or a suballocated device-local image heap) with optimal tiling. Shader image access goes through the T#/hash table, so nothing dereferences the key. Keeping images out of the arena avoids forcing optimal-tiled images into the arena's memory type and keeps the arena sized by buffers, not textures. |
| Heaps and placed resources | `CreateHeap` reserves the requested size in the arena, so a buffer placed at a 64 KiB-aligned offset is that offset into the arena and its console VA is the heap's place plus the offset. A placed texture (1D, 2D or 3D) gets its own `VkDeviceMemory`; one the title placed at its own address through the console's `CreatePlacedResourceX` (Xbox device slot 133) reports that title address from `GetGPUVirtualAddress`, as the console does — a title turns it into the CPU pointer it clears the texture through — while its pixels do not alias the title's pages yet. Any other texture answers a null VA, as on D3D12. Tiled (`64KB_UNDEFINED_SWIZZLE` and Xbox `0x101`) 2D/3D placed textures (D3D-191) and multisampled 2D placed textures (D3D-222) share that backing, answer `GetResourceAllocationInfo` and `GetResourceTiling`, and check heap/offset alignments. Reserved buffers can use heap tile mappings (section 4.2). |
| Images | Each image gets a unique console VA key and has device-local memory with optimal tiling: a range of a 64 MiB block that other textures share (`runtime/src/image_memory.h`, `VK-IMAGE-MEMORY-POOL`), or its own `VkDeviceMemory` when it is a render target, a depth buffer, a CPU-visible texture or larger than an eighth of a block, or when device-local memory has no room for another block. A range goes back to its block when the last submission that could use the image has completed. One reused from an earlier texture is zeroed before the next submission that runs shaders, as a committed resource reads as zero. Blocks hold only optimal-tiled images, so `bufferImageGranularity` does not apply. Shader image access goes through the T#/hash table, so nothing dereferences the key. Keeping images out of the arena avoids forcing optimal-tiled images into the arena's memory type and keeps the arena sized by buffers, not textures. |
| Heaps and placed resources | `CreateHeap` reserves the requested size in the arena, so a buffer placed at a 64 KiB-aligned offset is that offset into the arena and its console VA is the heap's place plus the offset. A placed texture (1D, 2D or 3D) gets its own memory (a range of a shared block or its own `VkDeviceMemory`, above); one the title placed at its own address through the console's `CreatePlacedResourceX` (Xbox device slot 133) reports that title address from `GetGPUVirtualAddress`, as the console does — a title turns it into the CPU pointer it clears the texture through — while its pixels do not alias the title's pages yet. Any other texture answers a null VA, as on D3D12. Tiled (`64KB_UNDEFINED_SWIZZLE` and Xbox `0x101`) 2D/3D placed textures (D3D-191) and multisampled 2D placed textures (D3D-222) share that backing, answer `GetResourceAllocationInfo` and `GetResourceTiling`, and check heap/offset alignments. Reserved buffers can use heap tile mappings (section 4.2). |
| Descriptor heaps | Shader-visible CBV/SRV/UAV and sampler heaps are allocated in the low 4 GB of the arena. RTV/DSV heaps are host-side only. |
| Shader code | Each FSSM blob is uploaded to the arena; its console VA is the code base. |
| Upload/readback | `D3D12_HEAP_TYPE_UPLOAD`/`READBACK` resources are separate host-visible buffers outside the arena. Their console VAs are only used by copy APIs; if the game binds one as a vertex/index buffer or reads it in a shader, the layer biases the view/descriptor by `-heap_base` so the shader's addition lands on the host BDA (**ASSUMPTION**; **measured to fail for a V#**, see below). |
Expand Down Expand Up @@ -2146,7 +2147,7 @@ The trace will enumerate them.
| `ID3D12PipelineState` | `VkPipeline` + a `PipelineInfo` | Shader hash → SPIR-V + index entry; PSO state → Vulkan state; dynamic state where possible. The BVH builder's compute PSOs arrive at device slot 62 with a plain `D3D12_COMPUTE_PIPELINE_STATE_DESC`. |
| `ID3D12DescriptorHeap` | `DescriptorHeap` (shadow + optional arena range) | CBV/SRV/UAV and sampler heaps can be shader-visible; RTV/DSV are host-only. Start handles use the measured RAX return at heap slots 9/10. Increments are layer-chosen (32/32) pending the console value. |
| `ID3D12Resource` | `Resource` (a range in the arena buffer; a separate `VkImage` for textures) | Committed, placed and reserved. Reserved buffers use sparse memory where supported (section 4.2). Xbox textures may arrive through device slot 76. `GetGPUVirtualAddress` returns a console VA (a buffer offset or an image key). |
| `ID3D12Heap` | `Heap` (a reserved VA range) | Buffer ranges are backed by the arena; images get their own `VkDeviceMemory`. Residency calls are no-ops. True buffer/image aliasing inside a heap is **Open**. |
| `ID3D12Heap` | `Heap` (a reserved VA range) | Buffer ranges are backed by the arena; images get ranges of shared blocks or their own `VkDeviceMemory` (section 3.3). Residency calls are no-ops. True buffer/image aliasing inside a heap is **Open**. |
| `ID3D12Fence` / `ID3D12Fence1` | `Fence` over a timeline `VkSemaphore` | `GetCompletedValue` = counter value; `SetEventOnCompletion` = wait thread + Win32 event; CPU `Signal` = host signal. |
| Resource barriers (legacy) | `vkCmdPipelineBarrier` | Per-subresource state tracking; `BEGIN_ONLY`/`END_ONLY` become conservative full barriers at the begin point. |
| Enhanced barriers (`ID3D12GraphicsCommandList7::Barrier`) | `vkCmdPipelineBarrier2` | Direct mapping of sync/access/layout; prefer it when the game uses it. |
Expand Down Expand Up @@ -2346,8 +2347,8 @@ The trace will enumerate them.
layout enum. The FidelityFX upscaler creates 10 default-heap resources through this slot, so it is not optional
for middleware. The console tiled data layout is GFX10 `SW_64KB_D` (Mesa addrlib `GFX10_SW_64K_D_RBPLUS_PATINFO`),
and the detile and tile path is implemented in `resource_detile.h` and verified by `resource_detile_test` (D3D-316).
- `CreateCommittedResource`: allocate an aligned range in the arena for a buffer, or a separate `VkDeviceMemory`
for an image; record the initial state. Map `D3D12_HEAP_TYPE_DEFAULT` to device-local memory, `UPLOAD`/`READBACK`
- `CreateCommittedResource`: allocate an aligned range in the arena for a buffer, or a range of a shared block
or a separate `VkDeviceMemory` for an image (section 3.3); record the initial state. Map `D3D12_HEAP_TYPE_DEFAULT` to device-local memory, `UPLOAD`/`READBACK`
to separate host-visible buffers. This remains the path for buffers and for any PC-style committed resource.
- `ID3D12Resource::GetDesc` returns the description with its defaults filled in, as the PC runtime does: `MipLevels`
0 becomes the full chain, and `Alignment` 0 becomes the placement alignment, 64 KiB, or 4 MiB for a multisampled
Expand Down
13 changes: 13 additions & 0 deletions runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -584,6 +584,11 @@ if(BUILD_TESTING)
# VulkanContext::buffer_at's VA index (runtime/src/buffer_va_index.h): pure stdlib, no Vulkan instance.
add_executable(buffer_va_index_test test/buffer_va_index_test.cpp)
add_test(NAME buffer_va_index COMMAND buffer_va_index_test)
# Textures sharing blocks of device memory (runtime/src/image_memory.h): pure stdlib, counted fake allocations.
add_executable(image_memory_test test/image_memory_test.cpp)
find_package(Threads REQUIRED)
target_link_libraries(image_memory_test PRIVATE Threads::Threads)
add_test(NAME image_memory COMMAND image_memory_test)

add_executable(xbox_present_readback_size_test test/xbox_present_readback_size_test.cpp)
add_test(NAME xbox_present_readback_size COMMAND xbox_present_readback_size_test)
Expand Down Expand Up @@ -1856,6 +1861,14 @@ if(TARGET Vulkan::Headers)
set_tests_properties(d3d12_queue_wait PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60)
add_test(NAME d3d12_queue_wait_timeout COMMAND d3d12_queue_wait_test --timeout-control)
set_tests_properties(d3d12_queue_wait_timeout PROPERTIES SKIP_RETURN_CODE 77 WILL_FAIL TRUE TIMEOUT 10)
# Textures share blocks of device memory, and a reused range neither leaks old texels nor touches its neighbours.
add_executable(d3d12_texture_memory_test test/d3d12_texture_memory_test.cpp)
target_link_libraries(d3d12_texture_memory_test PRIVATE gta6rt_d3d12_com d3d12 dxgi)
target_compile_definitions(d3d12_texture_memory_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
target_compile_options(d3d12_texture_memory_test PRIVATE /W4 /permissive- /utf-8)
add_test(NAME d3d12_texture_memory COMMAND d3d12_texture_memory_test)
set_tests_properties(d3d12_texture_memory PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120
FAIL_REGULAR_EXPRESSION "Validation Error;VUID-")
# ExecuteCommandLists refuses a list whose type isn't the queue's (debug-layer message 836).
add_executable(d3d12_queue_list_type_test test/d3d12_queue_list_type_test.cpp)
target_link_libraries(d3d12_queue_list_type_test PRIVATE gta6rt_d3d12_com)
Expand Down
9 changes: 9 additions & 0 deletions runtime/shims/d3d12_com.h
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,15 @@ bool device_sparse_buffer_tiles(ID3D12Device* device);
// The size in bytes of the device's GPU address arena, or 0 without one. For tests.
std::uint64_t device_arena_size(ID3D12Device* device);

// The blocks of device memory that textures share (src/image_memory.h): how many, their bytes, and the textures in
// them. For tests.
struct ImageMemoryStats {
std::uint64_t blocks = 0;
std::uint64_t block_bytes = 0;
std::uint64_t textures = 0;
};
ImageMemoryStats image_memory_stats(ID3D12Device* device);

// The bindless set 0 a device with VulkanDeviceInfo::bindless keeps (vulkan_bindless.h), and its layout: what a
// pipeline whose shader declares set-0 bindings is created with and binds. Null without such a set. The set is
// brought up to date at every ExecuteCommandLists.
Expand Down
58 changes: 58 additions & 0 deletions runtime/shims/d3d12_vulkan_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -568,6 +568,8 @@ struct DeviceState {
create.pQueueFamilyIndices = families.data();
}
std::unique_ptr<leonida::VulkanContext> context;
// The blocks textures share (allocate_image). Freed after the context, whose deferred queue holds ranges of them.
std::unique_ptr<leonida::ImageMemory> image_memory;
VkPhysicalDeviceMemoryProperties memory{};
// D3D-96: upload-heap buffers prefer DEVICE_LOCAL | HOST_VISIBLE memory, so the GPU reads them from VRAM. Only
// with Resizable BAR (leonida::resizable_bar); LEONIDA_UPLOAD_SYSMEM=1 keeps them in system memory to compare.
Expand Down Expand Up @@ -1412,6 +1414,23 @@ struct DeviceState {
}
return VK_NULL_HANDLE;
}

// A range of a device-local block for a texture, or null: the texture is too large to share one, or device-local
// memory has no room for another block, and the caller makes its own allocation as it would without the blocks.
std::unique_ptr<leonida::ImageMemory::Range> allocate_image(const VkMemoryRequirements& requirements,
VkMemoryPropertyFlags& chosen) {
for (const std::uint32_t i : leonida::memory_type_order(memory, requirements.memoryTypeBits,
VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0,
requirements.size)) {
const VkDeviceSize block = leonida::image_block_bytes(memory.memoryHeaps[memory.memoryTypes[i].heapIndex].size);
if (requirements.size > block / 8) continue;
if (auto range = image_memory->allocate(i, requirements.size, requirements.alignment, block)) {
chosen = memory.memoryTypes[i].propertyFlags;
return range;
}
}
return nullptr;
}
};

// The Vulkan format for a texture this layer can create, with the D24 fallback; VK_FORMAT_UNDEFINED, after a log
Expand Down Expand Up @@ -1832,6 +1851,8 @@ class Resource final
device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image, image_);
if (buffer_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::buffer, buffer_);
if (memory_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::device_memory, memory_);
if (image_range_)
device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image_memory, image_range_.release());
}

leonida::ResourceId id() const { return resource_id(this); }
Expand Down Expand Up @@ -2260,6 +2281,10 @@ class Resource final
// (NVIDIA Pascal / 582.78: memoryTypeBits == 0), or fail to allocate one. Staging copies do not need
// that usage, so recreate the image without it and continue on that path, as for a refused format above.
VkMemoryRequirements requirements{};
// Render targets and depth buffers keep their own allocations: there are few of them, and a driver may give one
// a better place.
constexpr D3D12_RESOURCE_FLAGS attachment =
D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
for (;;) {
vk.vkGetImageMemoryRequirements(device_.info.device, image_, &requirements);
// NVIDIA's Pascal driver (582.78 on a GTX 1050 Ti) reports HOST_IMAGE_TRANSFER for the format and creates
Expand All @@ -2268,6 +2293,14 @@ class Resource final
// branch on any GPU with force_host_transfer_retry.
bool retry = host_transfer_ &&
(requirements.memoryTypeBits == 0 || device_.info.force_host_transfer_retry);
if (!(desc_.Flags & attachment) && !host_transfer_)
image_range_ = device_.allocate_image(requirements, memory_flags_);
if (image_range_) {
if (vk.vkBindImageMemory(device_.info.device, image_, image_range_->memory(), image_range_->offset()) ==
VK_SUCCESS)
break;
return E_OUTOFMEMORY;
}
if (!retry) {
memory_ = device_.allocate(requirements, 0, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &memory_flags_);
if (memory_ && vk.vkBindImageMemory(device_.info.device, image_, memory_, 0) == VK_SUCCESS) break;
Expand Down Expand Up @@ -2332,6 +2365,8 @@ class Resource final
// Never used yet: the first command that touches a part zero-fills it and moves it to the layout of the
// state that command expects (vulkan_replay.h, initialize), so no submission is needed here.
device_.context->add_resource(id(), binding, VK_IMAGE_LAYOUT_UNDEFINED);
// A shader may read it before any command names it: D3D12 gives zeros, and a reused range holds an older texture.
if (image_range_ && image_range_->reused() && !binding.not_zeroed) device_.context->note_shader_image(id());
return S_OK;
}

Expand Down Expand Up @@ -2659,6 +2694,7 @@ class Resource final
VkImage image_ = VK_NULL_HANDLE;
VkBuffer buffer_ = VK_NULL_HANDLE;
VkDeviceMemory memory_ = VK_NULL_HANDLE;
std::unique_ptr<leonida::ImageMemory::Range> image_range_; // a texture's, instead of memory_
VkMemoryPropertyFlags memory_flags_ = 0;
VkAccelerationStructureKHR accel_ = VK_NULL_HANDLE;
void* mapped_ = nullptr;
Expand Down Expand Up @@ -5195,6 +5231,17 @@ class Device final
info.conditional_rendering, info.ray_tracing,
info.xdxr_acceleration_structures &&
info.buffer_device_address);
state_.image_memory = std::make_unique<leonida::ImageMemory>(
[device = info.device, make = state_.context->vk.vkAllocateMemory](std::uint32_t type, std::uint64_t bytes) {
VkMemoryAllocateInfo block{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};
block.allocationSize = bytes;
block.memoryTypeIndex = type;
VkDeviceMemory out = VK_NULL_HANDLE;
return make(device, &block, nullptr, &out) == VK_SUCCESS ? out : VkDeviceMemory(VK_NULL_HANDLE);
},
[device = info.device, free = state_.context->vk.vkFreeMemory](VkDeviceMemory block) {
free(device, block, nullptr);
});
state_.context->mesh_queries = info.mesh_shader_queries;
state_.context->set_depth_range_unrestricted(info.depth_range_unrestricted);
if (info.physical && state_.format_properties) {
Expand Down Expand Up @@ -5569,6 +5616,7 @@ class Device final
if (state_.pipeline_cache_handle)
state_.context->vk.vkDestroyPipelineCache(state_.info.device, state_.pipeline_cache_handle, nullptr);
state_.context.reset();
state_.image_memory.reset(); // the context's deferred queue gave its ranges back
if (owned_.device) owned_.destroy_device(owned_.device, nullptr);
if (owned_.instance) owned_.destroy_instance(owned_.instance, nullptr);
}
Expand Down Expand Up @@ -9117,6 +9165,16 @@ std::uint64_t device_arena_size(ID3D12Device* device) {
return d ? d->state().arena.size : 0;
}

ImageMemoryStats image_memory_stats(ID3D12Device* device) {
if (!device) return {};
ID3D12Device* real = rt::d3d12_xs::device_proxy_real_device(device);
if (!real) real = device;
const Device* d = Device::from<Device>(real);
if (!d || !d->state().image_memory) return {};
const auto stats = d->state().image_memory->stats();
return {stats.blocks, stats.block_bytes, stats.ranges};
}

namespace {
const leonida::BindlessSet* bindless_of(ID3D12Device* device) {
if (!device) return nullptr;
Expand Down
Loading
Loading