Skip to content
Open
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
26 changes: 23 additions & 3 deletions docs/d3d12_vulkan.md
Original file line number Diff line number Diff line change
Expand Up @@ -769,6 +769,26 @@ The compute path, end to end:
`LEONIDA_ARENA_LOG=1` also logs one line per VA handed out, per refused allocation, and per upload or readback
buffer VA outside the arena.
- Default-heap buffers are 64 KiB-aligned ranges in it, zeroed through its mapping; their console VA is the offset.
- A released default-heap buffer's range goes back through the device's deletion queue, as the buffer's Vulkan
objects do (`DeferredDeletionQueue::Kind::arena_range`, D3D-475): once every submission made before the release,
on any queue, has completed, and the one after it, since a submission that has already resolved the buffer may
still be on its way to `vkQueueSubmit`. It used to go back at once, so the next buffer placed there was
zero-filled through the mapping under a read still in flight. An allocation that finds no room while such ranges
are on their way takes back those the GPU is done with (`VulkanContext::reclaim_retired`: with the resource and
tracker locks held no submission is half-recorded, so a range released after the last recorded submission is
free once that one has completed), then waits for the device to go idle and tries once more; only then is it
`E_OUTOFMEMORY`. Allocations that fit cost what they did. Measured (`d3d12_arena_retire_test`, RTX 3060, driver
617.14, `LEONIDA_VK_VALIDATION=1` with sync validation, 0 messages): queue A copies a 1 MiB buffer to a readback
buffer behind a `Wait` for a fence queue C signals after about 300 ms of 64 MiB copies, C's `Signal` submitted
first so A's batch is submitted (a GPU wait, not a batch held on the CPU); the buffer is released and a 1 MiB
buffer made while the gate is closed. Before: the new buffer got the released range (VA 0x10000) and the read
found all 262144 words zero. Now: it gets 0x110000, the read matches, and once the read and the submission after
it have completed the next buffer gets 0x10000 back. With a 16 MiB arena, a 12 MiB buffer made and released four
times with nothing submitted gets the same range each time, and one made while a released 12 MiB buffer waits for
a gated read waits for the device (280 ms) and gets that range, where before it took it at once (1.4 ms) and the
read found 3145728 of 3145728 words zero. Not covered: heaps (`CreateHeap`, whose placed buffers are ranges of
the heap's range), shader-visible descriptor heaps and shader code still go back to the arena when the object is
destroyed, as D3D12 lets the layer require of the application for those objects.
- Shader-visible descriptor heaps also live in it: the CPU handle is its host mapping and the GPU handle is the VA,
so descriptor bytes the application writes itself are what shaders load.
- Upload and readback buffers keep their own memory, and their VA is their device address minus the heap base.
Expand Down Expand Up @@ -927,9 +947,9 @@ The compute path, end to end:
- Only the first viewport and scissor are used, and primitive restart is not modelled yet.

**Resources and heaps:**
- A buffer of 0 bytes, or one whose size wraps when aligned, is `E_INVALIDARG`. One the arena cannot hold is
`E_OUTOFMEMORY`, and so is a shader-visible descriptor heap the arena cannot hold (in host memory its GPU
handle would be 0).
- A buffer of 0 bytes, or one whose size wraps when aligned, is `E_INVALIDARG`. One the arena cannot hold, even
after the ranges of released buffers have come back (GPU address arena above, D3D-475), is `E_OUTOFMEMORY`, and
so is a shader-visible descriptor heap the arena cannot hold (in host memory its GPU handle would be 0).
- If the arena cannot be created, its buffer is released, so other buffers keep their own memory and get no VA.
- 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.
Expand Down
9 changes: 9 additions & 0 deletions runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1472,6 +1472,15 @@ if(TARGET Vulkan::Headers)
add_test(NAME d3d12_queue_handover COMMAND d3d12_queue_handover_test)
set_tests_properties(d3d12_queue_handover PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 400
FAIL_REGULAR_EXPRESSION "Validation Error;VUID-")
# A default-heap buffer released under a GPU-gated read keeps its arena range until the read is done, and a full
# arena waits for such ranges instead of failing (docs/d3d12_vulkan.md section 4.4, D3D-475).
add_executable(d3d12_arena_retire_test test/d3d12_arena_retire_test.cpp)
target_link_libraries(d3d12_arena_retire_test PRIVATE gta6rt_d3d12_com)
target_compile_definitions(d3d12_arena_retire_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX)
target_compile_options(d3d12_arena_retire_test PRIVATE /W4 /permissive- /utf-8)
add_test(NAME d3d12_arena_retire COMMAND d3d12_arena_retire_test)
set_tests_properties(d3d12_arena_retire PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 120
FAIL_REGULAR_EXPRESSION "Validation Error;VUID-")
# The same on a caller-owned device: two VkQueues handed to the layer (the D3D12 queues share them), and one
# (every D3D12 queue shares it, where a Wait ahead of its Signal would never progress on the GPU).
add_test(NAME d3d12_queue_handover_two_queues COMMAND d3d12_queue_handover_test --two-queues)
Expand Down
55 changes: 49 additions & 6 deletions runtime/shims/d3d12_vulkan_device.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -661,6 +661,8 @@ struct DeviceState {
VkDeviceSize in_use = 0, peak_in_use = 0, peak_end = 0;
VkDeviceSize use_in_use[4] = {}, use_peak[4] = {};
std::uint64_t allocations = 0, failures = 0;
// Bytes of released buffers that wait for the submissions made before their release (arena_retire).
VkDeviceSize retiring = 0;
} arena;

std::uint32_t sparse_buffer_memory_types = 0;
Expand Down Expand Up @@ -691,9 +693,27 @@ struct DeviceState {

// A zero-size range is refused: it would share its offset with the next range, and its release would collide
// with that range's free entry. The fit test cannot wrap: free blocks lie inside the arena (below 4 GiB).
// A released buffer's range comes back only once the GPU is done with it (arena_retire); out of room while some
// are on their way, this takes back what is done, then waits for the device to finish and tries once more.
bool arena_allocate(VkDeviceSize bytes, VkDeviceSize alignment, VkDeviceSize& out, ArenaUse use) {
if (!bytes || bytes > arena.size) return false;
std::lock_guard lock(arena.mutex);
for (int pass = 0;; ++pass) {
{
std::lock_guard lock(arena.mutex);
if (arena_take_locked(bytes, alignment, out, use)) return true;
if (pass == 2 || !arena.retiring || !context) {
++arena.failures;
if (arena.log)
std::fprintf(stderr, "[rt] d3d12: arena %s: no room for 0x%llx bytes\n", kArenaUseNames[use],
(unsigned long long)bytes);
return false;
}
}
context->reclaim_retired(pass == 1);
}
}

bool arena_take_locked(VkDeviceSize bytes, VkDeviceSize alignment, VkDeviceSize& out, ArenaUse use) {
for (auto it = arena.free.begin(); it != arena.free.end(); ++it) {
const VkDeviceSize start = (it->first + alignment - 1) / alignment * alignment;
const VkDeviceSize end = it->first + it->second;
Expand All @@ -714,10 +734,6 @@ struct DeviceState {
(unsigned long long)start, (unsigned long long)bytes);
return true;
}
++arena.failures;
if (arena.log)
std::fprintf(stderr, "[rt] d3d12: arena %s: no room for 0x%llx bytes\n", kArenaUseNames[use],
(unsigned long long)bytes);
return false;
}

Expand Down Expand Up @@ -746,6 +762,10 @@ struct DeviceState {
void arena_release(VkDeviceSize offset, VkDeviceSize bytes, ArenaUse use) {
if (!bytes) return;
std::lock_guard lock(arena.mutex);
arena_release_locked(offset, bytes, use);
}

void arena_release_locked(VkDeviceSize offset, VkDeviceSize bytes, ArenaUse use) {
arena.in_use -= bytes;
arena.use_in_use[use] -= bytes;
auto it = arena.free.emplace(offset, bytes).first;
Expand All @@ -761,6 +781,27 @@ struct DeviceState {
}
}

// A default-heap buffer is destroyed: work submitted before may still read or write its range, and the next
// buffer placed there is zero-filled through the host mapping at once. So the range goes back through the
// device's deletion queue (VulkanContext::defer_destroy, D3D-475) with the buffer's other objects, once every
// submission made before has completed. Offset and size fit the item's 64 bits: the arena is below 4 GiB.
void arena_retire(VkDeviceSize offset, VkDeviceSize bytes) {
if (!bytes) return;
{
std::lock_guard lock(arena.mutex);
arena.retiring += bytes;
}
context->defer_destroy(leonida::DeferredDeletionQueue::Kind::arena_range, (offset << 32) | bytes);
}

// The deletion queue's DeferredDeletionQueue::ArenaReleaseFn: `user` is the DeviceState.
static void arena_retired(void* user, std::uint64_t offset, std::uint64_t bytes) {
auto& device = *static_cast<DeviceState*>(user);
std::lock_guard lock(device.arena.mutex);
device.arena.retiring -= bytes;
device.arena_release_locked(offset, bytes, arena_buffer);
}

// The translator's output, loaded on first use.
std::mutex library_mutex;
bool library_tried = false;
Expand Down Expand Up @@ -1703,7 +1744,7 @@ class Resource final
}
if (image_address_) device_.forget_image(image_address_);
device_.context->remove_resource(id());
if (in_arena_) device_.arena_release(arena_offset_, desc_.Width, DeviceState::arena_buffer);
if (in_arena_) device_.arena_retire(arena_offset_, desc_.Width); // back once the GPU is done with it
if (image_ && !sparse_image_)
device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::image, image_);
if (buffer_) device_.context->defer_destroy(leonida::DeferredDeletionQueue::Kind::buffer, buffer_);
Expand Down Expand Up @@ -4915,6 +4956,7 @@ class Device final
arena.log = getenv_s(&length, log, "LEONIDA_ARENA_LOG") == 0 && length > 1 && log[0] != '0';
state_.context->set_heap_base(arena.address);
state_.context->set_zero_page(arena.buffer, 0, kArenaReserved);
state_.context->set_arena_release(&DeviceState::arena_retired, &state_);
return true;
}

Expand All @@ -4926,6 +4968,7 @@ class Device final
}
state_.context->drain_deleted_resources(UINT64_MAX);
state_.context->set_bindless_release(nullptr, nullptr);
state_.context->set_arena_release(nullptr, nullptr);
state_.context->set_bindless_current(nullptr); // the retired generations go with state_.bindless below
}
state_.staging_queue.reset(); // it uses the context
Expand Down
42 changes: 41 additions & 1 deletion runtime/src/vulkan_backend.h
Original file line number Diff line number Diff line change
Expand Up @@ -405,16 +405,20 @@ class DeferredDeletionQueue {
buffer,
device_memory,
acceleration_structure,
arena_range, // a default-heap buffer's range of the GPU address arena (D3D-475)
framebuffer,
};

struct Item {
std::uint64_t ticket = 0;
std::uint64_t handle = 0; // for bindless_slot: (uint64_t(dimension) << 32) | index
// for bindless_slot: (uint64_t(dimension) << 32) | index; for arena_range: (offset << 32) | bytes, both below
// 4 GiB as the arena is
std::uint64_t handle = 0;
Kind kind = Kind::image_view;
};

using BindlessReleaseFn = void (*)(void* user, std::uint32_t dimension, std::uint32_t index);
using ArenaReleaseFn = void (*)(void* user, std::uint64_t offset, std::uint64_t bytes);

explicit DeferredDeletionQueue(std::size_t initial_capacity = 256) : pending_(next_pow2(initial_capacity)) {}

Expand All @@ -424,6 +428,13 @@ class DeferredDeletionQueue {
bindless_release_user_ = user;
}

// Who takes arena_range items back: the device that owns the arena.
void set_arena_release(ArenaReleaseFn fn, void* user) {
std::lock_guard lock(mutex_);
arena_release_fn_ = fn;
arena_release_user_ = user;
}

void push(std::uint64_t retire_ticket, Kind kind, std::uint64_t handle) {
if (!handle && kind != Kind::bindless_slot) return;
std::lock_guard lock(mutex_);
Expand All @@ -447,12 +458,16 @@ class DeferredDeletionQueue {
void drain(std::uint64_t current_ticket, VkDevice device, const VulkanDeviceFunctions& vk) {
BindlessReleaseFn release_fn = nullptr;
void* release_user = nullptr;
ArenaReleaseFn arena_fn = nullptr;
void* arena_user = nullptr;
std::vector<Item> to_destroy;
{
std::lock_guard lock(mutex_);
if (count_ == 0 || pending_[head_].ticket > current_ticket) return;
release_fn = bindless_release_fn_;
release_user = bindless_release_user_;
arena_fn = arena_release_fn_;
arena_user = arena_release_user_;
const std::size_t mask = pending_.size() - 1;
while (count_ > 0 && pending_[head_].ticket <= current_ticket) {
to_destroy.push_back(pending_[head_]);
Expand Down Expand Up @@ -494,6 +509,9 @@ class DeferredDeletionQueue {
vk.vkDestroyAccelerationStructureKHR(
device, reinterpret_cast<VkAccelerationStructureKHR>(item.handle), nullptr);
break;
case Kind::arena_range:
if (arena_fn) arena_fn(arena_user, item.handle >> 32, item.handle & 0xFFFFFFFFu);
break;
case Kind::framebuffer:
vk.vkDestroyFramebuffer(device, reinterpret_cast<VkFramebuffer>(item.handle), nullptr);
break;
Expand All @@ -515,6 +533,8 @@ class DeferredDeletionQueue {
std::size_t count_ = 0;
BindlessReleaseFn bindless_release_fn_ = nullptr;
void* bindless_release_user_ = nullptr;
ArenaReleaseFn arena_release_fn_ = nullptr;
void* arena_release_user_ = nullptr;
};

// Centralized single-thread fence dispatcher using Vulkan 1.2 vkWaitSemaphores(VK_SEMAPHORE_WAIT_ANY_BIT).
Expand Down Expand Up @@ -1398,6 +1418,9 @@ class VulkanContext {
deletion_queue_.set_bindless_release(fn, user);
}

void set_arena_release(DeferredDeletionQueue::ArenaReleaseFn fn, void* user) {
deletion_queue_.set_arena_release(fn, user);
}
// The ticket of the latest submission: everything submitted so far is at or below it, and a resource that any
// of that work may use can be freed once completed_retire_ticket() has reached it. Tickets run over all queues,
// each recorded with its queue's timeline value, so this waits for every queue's timeline to pass what was
Expand Down Expand Up @@ -1473,6 +1496,23 @@ class VulkanContext {
retire_tickets_.queue_idle(progress);
}

// For an allocator out of room (the GPU address arena, D3D-475): destroys and gives back what is retired now,
// having first waited for the device to finish everything submitted when `wait` is set. With resource_mutex_ and
// tracker_mutex_ held no submission is between resolving resources and recording its ticket, so once every
// recorded submission has completed, what was released after the last of them no longer waits for the next one.
void reclaim_retired(bool wait) {
std::unique_lock resource_lock(resource_mutex_);
std::lock_guard tracker_lock(tracker_mutex_);
if (wait && !is_device_lost()) {
std::lock_guard submit(submit_mutex_); // vkDeviceWaitIdle needs every VkQueue externally synchronized
if (vk.vkDeviceWaitIdle(device_) == VK_ERROR_DEVICE_LOST) mark_device_lost();
}
const std::uint64_t submitted = submitted_ticket_.load(std::memory_order_acquire);
const std::uint64_t done = completed_retire_ticket();
if (is_device_lost()) return;
deletion_queue_.drain(done == submitted ? done + 1 : done, device_, vk);
}

VulkanDeviceFunctions vk;

// Vulkan requires external synchronisation of a VkQueue; every D3D12 queue of the device may share one.
Expand Down
Loading