Files
mandy/runtime/shims/d3d12_title_buffer_windows.h

682 lines
36 KiB
C++

#pragma once
#include <algorithm>
#include <array>
#include <atomic>
#include <utility>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <iterator>
#include <map>
#include <memory>
#include <vector>
#include <vulkan/vulkan.h>
#include "../src/arena_staging.h"
#include "../src/memory_breakdown.h"
namespace rt::d3d12 {
// Storage for shader-addressed mirrors when the main arena has no usable offset.
// Sub-ranges freed via free() are coalesced for reuse; one empty standard block (4 MiB unstaged or 64 MiB staged) is
// kept as a spare and any other empty block releases its Vulkan buffer and memory. When staged mode is enabled (for
// BAR-restricted GPUs with a staged DEVICE_LOCAL arena), blocks are 64 MiB pure DEVICE_LOCAL VRAM slabs paired with a
// HOST_VISIBLE staging mirror and an exact byte-range dirty tracker; both VRAM and host staging bytes count against
// `reserved_` and `cap`.
class TitleBufferWindows {
static constexpr VkDeviceSize kBlockSize = 4ull << 20;
static constexpr VkDeviceSize kStagedBlockSize = 64ull << 20;
struct StagedSlot {
leonida::ArenaStaging staging;
std::vector<VkBufferCopy> last_upload;
};
struct Block {
VkBuffer buffer{};
VkDeviceMemory memory{};
VkBuffer staging_buffer{};
VkDeviceMemory staging_memory{};
std::unique_ptr<StagedSlot> staged;
VkDeviceAddress address{};
VkDeviceSize capacity{}, used{}, reserved_bytes{};
std::uint8_t* mapped{};
std::size_t live{};
std::map<VkDeviceSize, VkDeviceSize> free_ranges; // offset -> size, coalesced
};
std::vector<Block> blocks_;
VkDeviceSize reserved_{};
bool staged_ = false;
// A new block's allocation failed at this time: none is tried again for kRetryAfter. After the story load the
// driver refused every 4 MiB block (VK_ERROR_OUT_OF_HOST_MEMORY), and each V# that wanted a copy tried again,
// through DeviceState::allocate's sleeping retries under the device's memory lock: one submission spent 28-35 s
// there (speed-8, speed-9). A view refused meanwhile goes without a copy, as one past the cap does.
static constexpr auto kRetryAfter = std::chrono::seconds(2);
std::chrono::steady_clock::time_point failed_at_{};
bool failed_ = false;
bool address_logged_ = false;
unsigned failure_lines_ = 0;
// The first failures of each block allocation, with the Vulkan call and its result (the count is in
// GeometryViews' line, `allocation failures`).
void note_block_failure(const char* call, VkResult result, VkDeviceSize bytes) {
if (failure_lines_ >= 4) return;
++failure_lines_;
std::fprintf(stderr, "[rt] d3d12: title buffer block of %llu KiB: %s failed (VkResult %d)\n",
static_cast<unsigned long long>(bytes >> 10), call, int(result));
}
bool local_refused_ = false; // device-local blocks refused once: host memory from then on
// SystemMemory: where a device_local allocation goes instead (set_system_memory; GeometryViews from
// LEONIDA_GEOMETRY_HOST).
int system_memory_ = 0;
bool system_memory_logged_ = false;
std::uint64_t quick_refusals_ = 0;
// The blocks' (device address, capacity), readable without the owner's lock: published in order, a slot never
// reused before release(). A destroyed block's slot keeps its other fields and only its address goes to 0 (the
// readers skip it), so a reader never sees a slot half rewritten. Blocks are destroyed only once their last
// range was freed, which GeometryViews does after the GPU work that used them completed.
static constexpr std::size_t kPublished = 4096;
struct Published {
std::atomic<VkDeviceAddress> address{0};
VkDeviceSize capacity{};
std::uint8_t* mapped{};
VkBuffer buffer{};
VkBuffer staging_buffer{};
StagedSlot* staged{};
bool host_cached{false};
};
std::array<Published, kPublished> published_{};
std::atomic<std::size_t> published_count_{0};
std::atomic<std::uint64_t> layout_generation_{0}; // bumped by every block made or destroyed
template<class Device>
void destroy_block(Device& d, std::vector<Block>::iterator it) {
// Unpublished first, so no lock-free reader picks it up again; then the owner is told, so tables built from
// for_each_block (the console heap pass's backed table) cut it before the next submission.
for (std::size_t i = 0, n = published_count_.load(std::memory_order_relaxed); i < n; ++i)
if (published_[i].buffer == it->buffer && published_[i].address.load(std::memory_order_relaxed)) {
published_[i].address.store(0, std::memory_order_release);
break;
}
layout_generation_.fetch_add(1, std::memory_order_release);
if constexpr (requires { d.title_block_gone(VkDeviceAddress{}, VkDeviceSize{}); })
d.title_block_gone(it->address, it->capacity);
if (it->staged) {
d.context->vk.vkUnmapMemory(d.info.device, it->staging_memory);
d.context->vk.vkDestroyBuffer(d.info.device, it->staging_buffer, nullptr);
d.context->vk.vkFreeMemory(d.info.device, it->staging_memory, nullptr);
} else {
d.context->vk.vkUnmapMemory(d.info.device, it->memory);
}
d.context->vk.vkDestroyBuffer(d.info.device, it->buffer, nullptr);
d.context->vk.vkFreeMemory(d.info.device, it->memory, nullptr);
reserved_ -= it->reserved_bytes;
blocks_.erase(it);
}
// The memory types a system-memory block may take: host-visible ones outside device-local memory (the GPU reads
// them over the bus), the write-back (cached) ones only when `cached`, else the write-combined ones only. None of
// them: every type `bits` allows (an integrated GPU, whose memory is all device-local).
template<class Device>
static std::uint32_t system_memory_types(const Device& d, std::uint32_t bits, bool cached) {
if constexpr (requires { d.memory.memoryTypes[0].propertyFlags; d.memory.memoryTypeCount; }) {
std::uint32_t host = 0, wanted = 0;
for (std::uint32_t i = 0; i < d.memory.memoryTypeCount && i < 32; ++i) {
if (!(bits & (1u << i))) continue;
const VkMemoryPropertyFlags f = d.memory.memoryTypes[i].propertyFlags;
if ((f & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) || !(f & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) ||
!(f & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT))
continue;
host |= 1u << i;
if (bool(f & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) == cached) wanted |= 1u << i;
}
return wanted ? wanted : host ? host : bits;
} else {
(void)d;
(void)cached;
return bits;
}
}
public:
// Whether a block at device address `address` of `capacity` bytes can be named by shaders: its offset from
// heap_base (`base`, the arena's address), as a V#'s 48-bit base holds it. With `signed_offsets` (every loaded
// module sign-extends the base) any block within 2^47 of heap_base on either side; otherwise only one above it, at
// a positive offset below 2^47 (the range both decoder generations read alike).
static bool shader_reachable(VkDeviceAddress address, VkDeviceSize capacity, VkDeviceAddress base,
bool signed_offsets) {
constexpr std::uint64_t k47 = 1ull << 47;
if (!address || !capacity || capacity > k47) return false;
const std::uint64_t offset = address - base; // mod 2^64: a block below heap_base is a negative offset
if (offset < k47) return capacity <= k47 - offset;
// Below heap_base: [offset, offset + capacity) must stay within [-2^47, 2^47).
return signed_offsets && offset >= ~(k47 - 1);
}
// Where blocks asked for as device_local go: kDeviceLocal (Resizable BAR while the driver gives it, the default),
// kSystemCached (host memory outside VRAM, write-back where the device offers it: what VIctory gives its copies
// of title memory) or kSystemUncached (host memory outside VRAM, write-combined). The GPU reads the system-memory
// kinds over the bus. Set before the first allocation.
static constexpr int kDeviceLocal = 0, kSystemCached = 1, kSystemUncached = 2;
void set_system_memory(int kind) { system_memory_ = kind; }
int system_memory() const { return system_memory_; }
void set_staged(bool enabled) { staged_ = enabled; }
bool staged() const { return staged_; }
VkDeviceSize reserved() const { return reserved_; }
// f(device address, capacity) for each live block; from any thread.
template <class F>
void for_each_block(F&& f) const {
const std::size_t n = published_count_.load(std::memory_order_acquire);
for (std::size_t i = 0; i < n; ++i)
if (const VkDeviceAddress address = published_[i].address.load(std::memory_order_acquire))
f(address, published_[i].capacity);
}
// Changes whenever a block is made or destroyed; from any thread.
std::uint64_t layout_generation() const { return layout_generation_.load(std::memory_order_acquire); }
// The block whose mapping holds [p, p + bytes): its buffer and the offset of p in it. From any thread.
bool find_mapped(const std::uint8_t* p, std::size_t bytes, VkBuffer& buffer, VkDeviceSize& offset) const {
const std::size_t n = published_count_.load(std::memory_order_acquire);
for (std::size_t i = 0; i < n; ++i) {
const Published& b = published_[i];
if (!b.address.load(std::memory_order_acquire)) continue;
if (p >= b.mapped && p - b.mapped < std::ptrdiff_t(b.capacity) &&
bytes <= std::size_t(b.capacity) - std::size_t(p - b.mapped)) {
buffer = b.buffer;
offset = VkDeviceSize(p - b.mapped);
return true;
}
}
return false;
}
std::size_t block_count() const { return blocks_.size(); }
std::size_t empty_blocks() const {
std::size_t count = 0;
for (const auto& b : blocks_)
if (b.live == 0) ++count;
return count;
}
template<class Device>
bool allocate(Device& d, VkDeviceSize bytes, VkDeviceSize& offset, std::uint8_t*& mapped,
bool device_local = false, VkDeviceSize cap = UINT64_MAX, bool* at_cap = nullptr,
VkBuffer* out_buffer = nullptr, VkDeviceSize* out_buffer_offset = nullptr,
VkDeviceAddress* out_address = nullptr) {
if (!bytes) return false;
const VkDeviceSize alignment = device_local ? 16 : 65536;
auto take = [&](Block& b) {
for (auto it = b.free_ranges.begin(); it != b.free_ranges.end(); ++it) {
const VkDeviceSize range_start = it->first;
const VkDeviceSize range_end = range_start + it->second;
const VkDeviceSize start = (range_start + alignment - 1) & ~(alignment - 1);
if (start < range_start || start > range_end || bytes > range_end - start) continue;
b.free_ranges.erase(it);
if (start > range_start) b.free_ranges.emplace(range_start, start - range_start);
const VkDeviceSize end = start + bytes;
if (end < range_end) b.free_ranges.emplace(end, range_end - end);
if (end > b.used) b.used = end;
++b.live;
mapped = b.mapped + start;
offset = b.address - d.arena.address + start;
if (out_buffer) *out_buffer = b.buffer;
if (out_buffer_offset) *out_buffer_offset = start;
if (out_address) *out_address = b.address + start;
return true;
}
return false;
};
if (!blocks_.empty() && take(blocks_.back())) return true;
// A large view may start a new slab while smaller views still fit earlier tails or freed holes.
// Use those even after the budget can no longer accommodate another slab.
if ((device_local || staged_) && blocks_.size() > 1)
for (std::size_t i = blocks_.size() - 1; i != 0; --i)
if (take(blocks_[i - 1])) return true;
auto& vk = d.context->vk;
if (!vk.vkGetBufferDeviceAddress) return false;
if (failed_ && std::chrono::steady_clock::now() - failed_at_ < kRetryAfter) {
++quick_refusals_;
return false;
}
const auto failed = [&] {
failed_ = true;
failed_at_ = std::chrono::steady_clock::now();
return false;
};
auto drop_unfitting_spare = [&] {
for (auto it = blocks_.begin(); it != blocks_.end(); ++it) {
if (it->live == 0 && bytes > it->capacity) {
destroy_block(d, it);
return true;
}
}
return false;
};
const bool make_staged = staged_ && !device_local;
const VkDeviceSize min_budget = make_staged ? (bytes <= UINT64_MAX / 2 ? bytes * 2 : UINT64_MAX) : bytes;
VkDeviceSize remaining_cap = reserved_ < cap ? cap - reserved_ : 0;
if (min_budget > remaining_cap) {
if (drop_unfitting_spare()) remaining_cap = reserved_ < cap ? cap - reserved_ : 0;
if (min_budget > remaining_cap) {
if (at_cap) *at_cap = true;
return false;
}
}
const VkDeviceSize slab_size = make_staged ? kStagedBlockSize : kBlockSize;
const VkDeviceSize max_single = make_staged ? remaining_cap / 2 : remaining_cap;
Block b{};
b.capacity = std::max(bytes, std::min(slab_size, max_single));
VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
info.size = b.capacity;
info.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT |
VK_BUFFER_USAGE_TRANSFER_SRC_BIT;
if (make_staged) {
info.usage |= VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT |
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT |
VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT;
if constexpr (requires { d.info.conditional_rendering; }) {
if (d.info.conditional_rendering) info.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT;
}
}
d.share(info);
if (const VkResult made = vk.vkCreateBuffer(d.info.device, &info, nullptr, &b.buffer); made != VK_SUCCESS) {
note_block_failure("vkCreateBuffer", made, b.capacity);
return failed();
}
VkMemoryRequirements req{};
vk.vkGetBufferMemoryRequirements(d.info.device, b.buffer, &req);
if (req.size > remaining_cap) {
if (drop_unfitting_spare()) remaining_cap = reserved_ < cap ? cap - reserved_ : 0;
if (req.size > remaining_cap) {
if (at_cap) *at_cap = true;
vk.vkDestroyBuffer(d.info.device, b.buffer, nullptr);
return false;
}
}
void* host{};
VkResult bound = VK_ERROR_OUT_OF_DEVICE_MEMORY, mapped_result = VK_ERROR_MEMORY_MAP_FAILED;
bool block_staged = false;
bool block_host_cached = false;
VkDeviceSize staging_reserved = 0;
if (make_staged && !local_refused_) {
VkMemoryPropertyFlags vram_chosen = 0;
VkDeviceMemory vram_mem = VK_NULL_HANDLE;
{
leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::windows);
vram_mem = d.allocate(req, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, 0, &vram_chosen, true);
}
VkBuffer staging_buf = VK_NULL_HANDLE;
VkDeviceMemory staging_mem = VK_NULL_HANDLE;
VkMemoryRequirements sreq{};
if (vram_mem && (vram_chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) {
VkBufferCreateInfo sinfo{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};
sinfo.size = b.capacity;
sinfo.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT;
d.share(sinfo);
if (vk.vkCreateBuffer(d.info.device, &sinfo, nullptr, &staging_buf) == VK_SUCCESS) {
vk.vkGetBufferMemoryRequirements(d.info.device, staging_buf, &sreq);
if (req.size <= remaining_cap && sreq.size <= remaining_cap - req.size) {
sreq.memoryTypeBits = system_memory_types(d, sreq.memoryTypeBits, /*cached=*/true);
leonida::memory_breakdown::Owner owner(leonida::memory_breakdown::Consumer::staging);
staging_mem = d.allocate(
sreq, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
VK_MEMORY_PROPERTY_HOST_CACHED_BIT, nullptr, false);
}
}
}
if (vram_mem && staging_buf && staging_mem &&
vk.vkBindBufferMemory(d.info.device, staging_buf, staging_mem, 0) == VK_SUCCESS &&
vk.vkMapMemory(d.info.device, staging_mem, 0, VK_WHOLE_SIZE, 0, &host) == VK_SUCCESS &&
vk.vkBindBufferMemory(d.info.device, b.buffer, vram_mem, 0) == VK_SUCCESS) {
b.memory = vram_mem;
b.staging_buffer = staging_buf;
b.staging_memory = staging_mem;
bound = VK_SUCCESS;
mapped_result = VK_SUCCESS;
block_staged = true;
block_host_cached = true;
staging_reserved = sreq.size;
} else {
if (host && staging_mem) {
vk.vkUnmapMemory(d.info.device, staging_mem);
host = nullptr;
}
if (staging_buf) vk.vkDestroyBuffer(d.info.device, staging_buf, nullptr);
if (staging_mem) vk.vkFreeMemory(d.info.device, staging_mem, nullptr);
if (vram_mem) vk.vkFreeMemory(d.info.device, vram_mem, nullptr);
local_refused_ = true;
std::fprintf(stderr, "[rt] d3d12: title buffer windows: staged DEVICE_LOCAL slab of %llu KiB refused; "
"falling back to host memory for later blocks\n",
static_cast<unsigned long long>(req.size >> 10));
}
}
if (!block_staged) {
// Device-local (Resizable BAR) when asked and while the driver gives it; host memory otherwise. After the
// story load the driver refused every 4 MiB device-local, host-visible block with a device address
// (VK_ERROR_OUT_OF_HOST_MEMORY, speed-8/-9) while host memory still served: once that happens, later blocks
// go straight to host memory instead of through DeviceState::allocate's sleeping retries first.
// A device_local request under set_system_memory takes system memory instead, out of the types that are not
// device-local (memory_type_order would otherwise give the first host-visible type, which can be the BAR).
VkMemoryPropertyFlags chosen = 0;
const bool system = device_local && system_memory_ != kDeviceLocal;
const bool want_local = device_local && !local_refused_ && !system;
VkMemoryRequirements types = req;
if (system) types.memoryTypeBits = system_memory_types(d, req.memoryTypeBits, system_memory_ == kSystemCached);
b.memory = d.allocate(types, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT,
want_local ? VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT
: system && system_memory_ == kSystemCached ? VK_MEMORY_PROPERTY_HOST_CACHED_BIT
: 0,
&chosen, true);
if (b.memory && system && !system_memory_logged_) {
system_memory_logged_ = true;
std::fprintf(stderr, "[rt] d3d12: title buffer copies in system memory (LEONIDA_GEOMETRY_HOST): memory "
"flags 0x%x (%s, %s)\n",
unsigned(chosen),
(chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) ? "device-local: no other type" : "not VRAM",
(chosen & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) ? "write-back" : "write-combined");
}
if (b.memory && want_local && !(chosen & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) {
local_refused_ = true;
std::fprintf(stderr, "[rt] d3d12: title buffer windows: device-local memory refused a %llu KiB block; "
"this and later blocks are in host memory\n",
static_cast<unsigned long long>(req.size >> 10));
}
if (b.memory) block_host_cached = (chosen & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) != 0;
if (!b.memory) note_block_failure("vkAllocateMemory (DeviceState::allocate)", bound, req.size);
else if ((bound = vk.vkBindBufferMemory(d.info.device, b.buffer, b.memory, 0)) != VK_SUCCESS)
note_block_failure("vkBindBufferMemory", bound, req.size);
else if ((mapped_result = vk.vkMapMemory(d.info.device, b.memory, 0, VK_WHOLE_SIZE, 0, &host)) != VK_SUCCESS)
note_block_failure("vkMapMemory", mapped_result, req.size);
}
if (b.memory && bound == VK_SUCCESS && mapped_result == VK_SUCCESS) {
VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO};
address.buffer = b.buffer;
b.address = vk.vkGetBufferDeviceAddress(d.info.device, &address);
const auto biased = b.address - d.arena.address;
bool signed_offsets = false;
if constexpr (requires { d.vsharp_offsets_signed(); }) signed_offsets = d.vsharp_offsets_signed();
if (shader_reachable(b.address, b.capacity, d.arena.address, signed_offsets)) {
b.mapped = static_cast<std::uint8_t*>(host);
b.reserved_bytes = req.size + staging_reserved;
b.free_ranges.emplace(0, b.capacity);
if (block_staged) {
b.staged = std::make_unique<StagedSlot>();
b.staged->staging.init(b.capacity);
}
if (const std::size_t n = published_count_.load(std::memory_order_relaxed); n < kPublished) {
published_[n].capacity = b.capacity;
published_[n].mapped = b.mapped;
published_[n].buffer = b.buffer;
published_[n].staging_buffer = b.staging_buffer;
published_[n].staged = b.staged.get();
published_[n].host_cached = block_host_cached;
published_[n].address.store(b.address, std::memory_order_relaxed);
published_count_.store(n + 1, std::memory_order_release);
}
layout_generation_.fetch_add(1, std::memory_order_release);
blocks_.push_back(std::move(b));
reserved_ += blocks_.back().reserved_bytes;
if (blocks_.size() == 1 || !(blocks_.size() & (blocks_.size() - 1)))
std::fprintf(stderr, "[rt] d3d12: title buffer shadows outside the arena%s: %zu blocks, "
"new block %llu KiB at shader VA 0x%llx\n",
block_staged ? " (DEVICE_LOCAL VRAM)" : "", blocks_.size(),
static_cast<unsigned long long>(blocks_.back().capacity >> 10),
static_cast<unsigned long long>(biased));
return take(blocks_.back());
}
if (!address_logged_) {
address_logged_ = true;
std::fprintf(stderr, "[rt] d3d12: title buffer block refused: its device address 0x%llx is not within "
"reach of a V# base from heap_base 0x%llx (%s offsets; later ones are counted, "
"not logged)\n",
static_cast<unsigned long long>(b.address),
static_cast<unsigned long long>(d.arena.address), signed_offsets ? "signed" : "unsigned");
}
if (block_staged) {
vk.vkUnmapMemory(d.info.device, b.staging_memory);
vk.vkDestroyBuffer(d.info.device, b.staging_buffer, nullptr);
vk.vkFreeMemory(d.info.device, b.staging_memory, nullptr);
} else {
vk.vkUnmapMemory(d.info.device, b.memory);
}
}
vk.vkDestroyBuffer(d.info.device, b.buffer, nullptr);
if (b.memory) vk.vkFreeMemory(d.info.device, b.memory, nullptr);
return failed();
}
// Returns [offset, offset + bytes) to its block for reuse; keeps staged blocks and one empty 4 MiB block pooled
// as spares and destroys any other empty block. Caller must guarantee no in-flight GPU work references this range.
template<class Device>
bool free(Device& d, VkDeviceSize offset, VkDeviceSize bytes) {
if (!bytes) return false;
const VkDeviceAddress bda = d.arena.address + offset;
for (auto it = blocks_.begin(); it != blocks_.end(); ++it) {
Block& b = *it;
if (bda < b.address || bda - b.address >= b.capacity) continue;
const VkDeviceSize start = bda - b.address;
if (bytes > b.capacity - start) return false;
VkDeviceSize merged_begin = start;
VkDeviceSize merged_end = start + bytes;
auto next = b.free_ranges.lower_bound(start);
if (next != b.free_ranges.begin()) {
auto prev = std::prev(next);
if (prev->first + prev->second >= merged_begin) {
merged_begin = prev->first;
merged_end = std::max(merged_end, prev->first + prev->second);
next = b.free_ranges.erase(prev);
}
}
while (next != b.free_ranges.end() && next->first <= merged_end) {
merged_end = std::max(merged_end, next->first + next->second);
next = b.free_ranges.erase(next);
}
b.free_ranges.emplace(merged_begin, merged_end - merged_begin);
if (b.live > 0) --b.live;
if (b.live == 0) {
const VkDeviceSize std_cap = b.staged ? kStagedBlockSize : kBlockSize;
if (b.capacity == std_cap && empty_blocks() == 1) {
b.free_ranges.clear();
b.free_ranges.emplace(0, b.capacity);
b.used = 0;
} else {
destroy_block(d, it);
}
}
return true;
}
return false;
}
// Allocations refused at once because a new block failed less than kRetryAfter ago.
std::uint64_t quick_refusals() const { return quick_refusals_; }
// Lock-free dirty marking for CPU writes into a staged block's mapped staging mirror.
bool mark_dirty_ptr(const void* ptr, std::size_t bytes) const {
if (!staged_ || !ptr || !bytes) return false;
const auto* p = static_cast<const std::uint8_t*>(ptr);
const std::size_t n = published_count_.load(std::memory_order_acquire);
for (std::size_t i = 0; i < n; ++i) {
const Published& b = published_[i];
if (!b.staged || !b.address.load(std::memory_order_acquire)) continue;
if (p >= b.mapped && p - b.mapped < std::ptrdiff_t(b.capacity)) {
const VkDeviceSize off = static_cast<VkDeviceSize>(p - b.mapped);
const VkDeviceSize clamped = std::min<VkDeviceSize>(bytes, b.capacity - off);
b.staged->staging.mark(off, clamped);
return true;
}
}
return false;
}
// Locates [ptr, ptr + bytes) in a staged block's mapped staging mirror, returning its published slot index and
// buffer-relative VkBufferCopy range. Lock-free.
bool find_staged_range(const std::uint8_t* ptr, std::size_t bytes, std::size_t& slot_index,
VkBufferCopy& region) const {
if (!staged_ || !ptr || !bytes) return false;
const std::size_t n = published_count_.load(std::memory_order_acquire);
for (std::size_t i = 0; i < n; ++i) {
const Published& b = published_[i];
if (!b.staged || !b.address.load(std::memory_order_acquire)) continue;
if (ptr >= b.mapped && ptr - b.mapped < std::ptrdiff_t(b.capacity)) {
const VkDeviceSize off = static_cast<VkDeviceSize>(ptr - b.mapped);
const VkDeviceSize clamped = std::min<VkDeviceSize>(bytes, b.capacity - off);
slot_index = i;
region = {off, off, clamped};
return true;
}
}
return false;
}
// Records staged staging->VRAM buffer copies for all published staged blocks into `cmd`. Serialized by the
// caller's arena upload mutex. Returns true if at least one copy was recorded.
template<class Vk>
bool record_uploads(VkCommandBuffer cmd, const Vk& vk) {
if (!staged_) return false;
bool any = false;
const std::size_t n = published_count_.load(std::memory_order_acquire);
for (std::size_t i = 0; i < n; ++i) {
const Published& b = published_[i];
if (!b.staged || !b.address.load(std::memory_order_acquire)) continue;
if (!b.staged->staging.drain(b.staged->last_upload)) continue;
vk.vkCmdCopyBuffer(cmd, b.staging_buffer, b.buffer,
static_cast<std::uint32_t>(b.staged->last_upload.size()),
b.staged->last_upload.data());
any = true;
}
return any;
}
void commit_uploads(bool submitted) {
if (!staged_) return;
const std::size_t n = published_count_.load(std::memory_order_acquire);
for (std::size_t i = 0; i < n; ++i) {
const Published& b = published_[i];
if (!b.staged) continue;
if (!b.staged->last_upload.empty()) {
if (!submitted) b.staged->staging.requeue(b.staged->last_upload);
b.staged->last_upload.clear();
}
}
}
// Collects GPU-written ranges from each staged block's VRAM buffer into `batches` (subtracting host-dirty ranges)
// so callers can submit arena + external window readbacks in a single `copy_buffers_sync` call.
template<class Batch>
void collect_host_readbacks(std::map<std::size_t, std::vector<VkBufferCopy>>& per_slot,
std::vector<Batch>& batches, std::vector<std::size_t>& slots) {
if (!staged_ || per_slot.empty()) return;
const std::size_t n = published_count_.load(std::memory_order_acquire);
for (auto& [slot, copies] : per_slot) {
if (slot >= n || copies.empty()) continue;
const Published& b = published_[slot];
if (!b.staged || !b.address.load(std::memory_order_acquire)) continue;
b.staged->staging.subtract_dirty(copies);
if (copies.empty()) continue;
batches.push_back(Batch{b.buffer, b.staging_buffer, copies});
slots.push_back(slot);
}
}
void note_host_readbacks(const std::vector<std::size_t>& slots,
const std::map<std::size_t, std::vector<VkBufferCopy>>& per_slot) {
if (!staged_ || slots.empty()) return;
const std::size_t n = published_count_.load(std::memory_order_acquire);
for (const std::size_t slot : slots) {
if (slot >= n) continue;
const auto it = per_slot.find(slot);
if (it == per_slot.end() || it->second.empty()) continue;
const Published& b = published_[slot];
if (b.staged) b.staged->staging.note_readback(it->second);
}
}
// If [ptr, ptr+len) lies in an uncached (e.g. ReBAR WC BAR1) non-staged block, returns true with its VkBuffer
// and byte offset so callers can DMA-read it into a HOST_CACHED scratch buffer instead of doing slow WC reads.
bool find_uncached_buffer(const std::uint8_t* ptr, std::size_t len, VkBuffer& out_buffer,
VkDeviceSize& out_offset) const {
if (staged_ || !ptr || !len) return false;
const auto p = reinterpret_cast<std::uintptr_t>(ptr);
const std::size_t n = published_count_.load(std::memory_order_acquire);
for (std::size_t i = 0; i < n; ++i) {
const Published& b = published_[i];
if (b.host_cached || b.staged || !b.mapped || !b.buffer || !b.address.load(std::memory_order_acquire))
continue;
const auto lo = reinterpret_cast<std::uintptr_t>(b.mapped);
const auto hi = lo + static_cast<std::uintptr_t>(b.capacity);
if (p >= lo && p < hi && len <= hi - p) {
out_buffer = b.buffer;
out_offset = static_cast<VkDeviceSize>(p - lo);
return true;
}
}
return false;
}
// Synchronously reads back GPU-written ranges from each staged block's VRAM buffer into its staging mirror
// in a single batched submission.
template<class Context>
bool sync_to_host(Context& ctx, VkQueue queue, std::uint32_t queue_family,
std::map<std::size_t, std::vector<VkBufferCopy>>& per_slot) {
if (!staged_ || per_slot.empty()) return true;
std::vector<typename Context::BufferCopyBatch> batches;
std::vector<std::size_t> slots;
collect_host_readbacks(per_slot, batches, slots);
if (batches.empty()) return true;
if (!ctx.copy_buffers_sync(batches, queue, queue_family)) return false;
note_host_readbacks(slots, per_slot);
return true;
}
leonida::ArenaStaging::Stats staging_stats() const {
leonida::ArenaStaging::Stats total{};
if (!staged_) return total;
const std::size_t n = published_count_.load(std::memory_order_acquire);
for (std::size_t i = 0; i < n; ++i) {
const Published& b = published_[i];
if (!b.staged) continue;
const auto st = b.staged->staging.stats();
total.flushes += st.flushes;
total.regions += st.regions;
total.bytes += st.bytes;
total.readbacks += st.readbacks;
total.readback_regions += st.readback_regions;
total.readback_bytes += st.readback_bytes;
}
return total;
}
bool lookup(VkDeviceAddress address, std::uint64_t& host, std::uint64_t& remaining) const {
for (const auto& b : blocks_) {
const auto delta = address - b.address;
if (delta < b.used) {
host = reinterpret_cast<std::uintptr_t>(b.mapped) + delta;
remaining = b.used - delta;
return true;
}
}
return false;
}
// Device idle. No tracker writes into the blocks after this point.
template<class Device>
void release(Device& d) {
for (auto& b : blocks_) {
if (b.staged) {
d.context->vk.vkUnmapMemory(d.info.device, b.staging_memory);
d.context->vk.vkDestroyBuffer(d.info.device, b.staging_buffer, nullptr);
d.context->vk.vkFreeMemory(d.info.device, b.staging_memory, nullptr);
} else {
d.context->vk.vkUnmapMemory(d.info.device, b.memory);
}
d.context->vk.vkDestroyBuffer(d.info.device, b.buffer, nullptr);
d.context->vk.vkFreeMemory(d.info.device, b.memory, nullptr);
}
blocks_.clear();
for (std::size_t i = 0, n = published_count_.load(std::memory_order_relaxed); i < n; ++i) {
published_[i].staged = nullptr;
published_[i].staging_buffer = VK_NULL_HANDLE;
published_[i].address.store(0, std::memory_order_relaxed);
}
published_count_.store(0, std::memory_order_release);
layout_generation_.fetch_add(1, std::memory_order_release);
reserved_ = 0;
}
};
} // namespace rt::d3d12