diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 6a6d03274e..c3f1a8a145 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -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 @@ -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). | @@ -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. | @@ -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 diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index de10c26e81..1544671726 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -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) @@ -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) diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index cf83f1f28a..cdf406cdbd 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -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. diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 8ff20b5a4c..1f73b53bb0 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -568,6 +568,8 @@ struct DeviceState { create.pQueueFamilyIndices = families.data(); } std::unique_ptr context; + // The blocks textures share (allocate_image). Freed after the context, whose deferred queue holds ranges of them. + std::unique_ptr 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. @@ -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 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 @@ -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); } @@ -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 @@ -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; @@ -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; } @@ -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 image_range_; // a texture's, instead of memory_ VkMemoryPropertyFlags memory_flags_ = 0; VkAccelerationStructureKHR accel_ = VK_NULL_HANDLE; void* mapped_ = nullptr; @@ -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( + [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) { @@ -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); } @@ -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(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; diff --git a/runtime/src/image_memory.h b/runtime/src/image_memory.h new file mode 100644 index 0000000000..3a473192ba --- /dev/null +++ b/runtime/src/image_memory.h @@ -0,0 +1,231 @@ +#pragma once + +// Memory for textures, handed out as ranges of larger blocks instead of one driver allocation each. Making and freeing +// an allocation is a kernel call that costs tens to hundreds of microseconds, where a range costs a map lookup; a title +// that streams textures makes and frees them all the time. Vulkan also guarantees only 4096 live allocations +// (maxMemoryAllocationCount). +// +// No Vulkan or Windows dependency: the caller allocates and frees the blocks (ImageMemoryPool's two callbacks), so the +// policy is checked on the CPU (test/image_memory_test.cpp). All the images of a block are optimal-tiled, so +// bufferImageGranularity, which separates linear from optimal resources, does not apply. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +// The free space of one block: the smallest free piece that holds the request is used (best fit), and a released range +// is merged with the free pieces beside it. +class BlockRanges { +public: + explicit BlockRanges(std::uint64_t size) : size_(size) { insert(0, size); } + + // False when no free piece holds `size` bytes at `alignment`. `reused`: the range starts in bytes some earlier range + // of this block held, so it may hold that range's data. + bool allocate(std::uint64_t size, std::uint64_t alignment, std::uint64_t& offset, bool& reused) { + if (!size || !alignment || size > size_) return false; + for (auto it = by_size_.lower_bound({size, 0}); it != by_size_.end(); ++it) { + const auto [piece_size, piece] = *it; + const std::uint64_t start = (piece + alignment - 1) / alignment * alignment; + const std::uint64_t lead = start - piece; + if (lead > piece_size || size > piece_size - lead) continue; + erase(piece, piece_size); + insert(piece, lead); + insert(start + size, piece_size - lead - size); + offset = start; + reused = start < touched_; + touched_ = std::max(touched_, start + size); + in_use_ += size; + return true; + } + return false; + } + + // Gives back a range allocate() returned. + void release(std::uint64_t offset, std::uint64_t size) { + in_use_ -= size; + if (const auto next = by_offset_.lower_bound(offset); next != by_offset_.end() && offset + size == next->first) { + const std::uint64_t next_size = next->second; + erase(next->first, next_size); + size += next_size; + } + if (auto previous = by_offset_.lower_bound(offset); previous != by_offset_.begin()) { + previous = std::prev(previous); + const auto [start, previous_size] = *previous; + if (start + previous_size == offset) { + erase(start, previous_size); + offset = start; + size += previous_size; + } + } + insert(offset, size); + } + + bool empty() const { return in_use_ == 0; } + std::uint64_t size() const { return size_; } + std::uint64_t in_use() const { return in_use_; } + // The largest free piece, so a full block is passed over without a search. + std::uint64_t largest() const { return by_size_.empty() ? 0 : by_size_.rbegin()->first; } + +private: + void insert(std::uint64_t offset, std::uint64_t size) { + if (!size) return; + by_offset_[offset] = size; + by_size_.insert({size, offset}); + } + void erase(std::uint64_t offset, std::uint64_t size) { + by_offset_.erase(offset); + by_size_.erase({size, offset}); + } + + std::uint64_t size_; + std::uint64_t in_use_ = 0; + std::uint64_t touched_ = 0; // bytes below this were handed out before + std::map by_offset_; // offset -> size + std::set> by_size_; // (size, offset) +}; + +// Blocks of device memory, by memory type, split into ranges. Thread-safe. Every Range must be gone before the pool is. +template +class ImageMemoryPool { +public: + // A null Memory{}: the driver has no room in the type. + using AllocateFn = std::function; + using FreeFn = std::function; + + // One image's range. Destroying it gives the bytes back to the block, so it is destroyed when no submission that + // used the image is still running (DeferredDeletionQueue). + class Range { + public: + Range(const Range&) = delete; + Range& operator=(const Range&) = delete; + ~Range() { pool_.release(*this); } + + Memory memory() const { return memory_; } + std::uint64_t offset() const { return offset_; } + // The bytes may hold what an earlier range left; the memory of a new block was never given to one. + bool reused() const { return reused_; } + + private: + friend class ImageMemoryPool; + Range(ImageMemoryPool& pool, void* block, Memory memory, std::uint64_t offset, std::uint64_t size, bool reused) + : pool_(pool), block_(block), memory_(memory), offset_(offset), size_(size), reused_(reused) {} + + ImageMemoryPool& pool_; + void* block_; + Memory memory_; + std::uint64_t offset_; + std::uint64_t size_; + bool reused_; + }; + + struct Stats { + std::uint64_t blocks = 0; // live driver allocations + std::uint64_t block_bytes = 0; // their size + std::uint64_t ranges = 0; // live ranges in them + }; + + ImageMemoryPool(AllocateFn allocate, FreeFn free) : allocate_(std::move(allocate)), free_(std::move(free)) {} + ImageMemoryPool(const ImageMemoryPool&) = delete; + ImageMemoryPool& operator=(const ImageMemoryPool&) = delete; + ~ImageMemoryPool() { + for (auto& [type, pool] : types_) + for (const auto& block : pool.blocks) free_(block->memory); + } + + // A range of a block of `type`, in a new block of `block_bytes` when no block has room. Null when the driver has no + // room for that block; the caller then makes its own allocation. + std::unique_ptr allocate(std::uint32_t type, std::uint64_t size, std::uint64_t alignment, + std::uint64_t block_bytes) { + std::lock_guard lock(mutex_); + Type& pool = types_[type]; + std::uint64_t offset = 0; + bool reused = false; + for (const auto& block : pool.blocks) { + if (block->ranges.largest() < size || !block->ranges.allocate(size, alignment, offset, reused)) continue; + ++ranges_; + return std::unique_ptr(new Range(*this, block.get(), block->memory, offset, size, reused)); + } + // A failed driver allocation is slow, and a full heap stays full until something is given back: do not ask for + // another block at every texture until a range is released, or that many textures later. + if (size > block_bytes || (pool.skip && pool.skip--)) return nullptr; + const Memory memory = allocate_(type, block_bytes); + if (!memory) { + pool.skip = kRetryAfter; + return nullptr; + } + auto block = std::make_unique(type, memory, block_bytes); + if (!block->ranges.allocate(size, alignment, offset, reused)) { + free_(memory); + return nullptr; + } + ++ranges_; + pool.blocks.push_back(std::move(block)); + return std::unique_ptr(new Range(*this, pool.blocks.back().get(), memory, offset, size, reused)); + } + + Stats stats() const { + std::lock_guard lock(mutex_); + Stats result; + result.ranges = ranges_; + for (const auto& [type, pool] : types_) + for (const auto& block : pool.blocks) { + ++result.blocks; + result.block_bytes += block->ranges.size(); + } + return result; + } + +private: + static constexpr std::uint32_t kRetryAfter = 64; + + struct Block { + Block(std::uint32_t t, Memory m, std::uint64_t bytes) : type(t), memory(m), ranges(bytes) {} + std::uint32_t type; + Memory memory; + BlockRanges ranges; + }; + struct Type { + std::vector> blocks; + std::uint32_t skip = 0; + }; + + void release(const Range& range) { + Memory dead{}; + bool free_block = false; + { + std::lock_guard lock(mutex_); + Block& block = *static_cast(range.block_); + Type& pool = types_[block.type]; + block.ranges.release(range.offset_, range.size_); + pool.skip = 0; + --ranges_; + // One empty block is kept, so a title that frees and makes the same textures does not ask the driver each + // time. + if (block.ranges.empty() && std::count_if(pool.blocks.begin(), pool.blocks.end(), + [](const auto& b) { return b->ranges.empty(); }) > 1) { + dead = block.memory; + free_block = true; + std::erase_if(pool.blocks, [&](const auto& b) { return b.get() == █ }); + } + } + if (free_block) free_(dead); + } + + mutable std::mutex mutex_; + AllocateFn allocate_; + FreeFn free_; + std::map types_; + std::uint64_t ranges_ = 0; +}; + +} // namespace leonida diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index ab6786a518..6779137ec9 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -11,6 +11,7 @@ #endif #include "binary_occlusion_spirv.h" #include "buffer_va_index.h" +#include "image_memory.h" #include "occlusion_sum_spirv.h" #include "queue_holds.h" #include "retire_tickets.h" @@ -426,6 +427,7 @@ class OcclusionResolve { }; struct SparseResource; +using ImageMemory = ImageMemoryPool; // Zero-allocation O(1) Ring Buffer deferred deletion queue tied to the device timeline semaphore. class DeferredDeletionQueue { @@ -437,6 +439,7 @@ class DeferredDeletionQueue { sparse_resource, buffer, device_memory, + image_memory, // an ImageMemory::Range*, deleted: its bytes go back to their block acceleration_structure, framebuffer, }; @@ -522,6 +525,9 @@ class DeferredDeletionQueue { case Kind::device_memory: vk.vkFreeMemory(device, reinterpret_cast(item.handle), nullptr); break; + case Kind::image_memory: + delete reinterpret_cast(item.handle); + break; case Kind::acceleration_structure: if (vk.vkDestroyAccelerationStructureKHR) vk.vkDestroyAccelerationStructureKHR( diff --git a/runtime/src/vulkan_memory.h b/runtime/src/vulkan_memory.h index 08c764d33c..a818ce2054 100644 --- a/runtime/src/vulkan_memory.h +++ b/runtime/src/vulkan_memory.h @@ -56,6 +56,12 @@ inline std::vector memory_type_order(const VkPhysicalDeviceMemory return order; } +// The size of the blocks that textures share (image_memory.h): 64 MiB, or a sixteenth of a small heap, such as the BAR +// window of a GPU without Resizable BAR. A texture larger than an eighth of a block has its own allocation. +inline VkDeviceSize image_block_bytes(VkDeviceSize heap) { + return std::min(VkDeviceSize(64) << 20, heap / 16) & ~VkDeviceSize(0xffff); +} + // D3D-299: true when an allocation that preferred DEVICE_LOCAL without needing host access (a texture, a default-heap // buffer outside the arena) got a type without it, so the GPU now reads it from system memory. A host-visible // allocation (the arena, an upload heap) in system memory is the memory type policy without Resizable BAR, not this. diff --git a/runtime/test/d3d12_texture_memory_test.cpp b/runtime/test/d3d12_texture_memory_test.cpp new file mode 100644 index 0000000000..2d82fe0f16 --- /dev/null +++ b/runtime/test/d3d12_texture_memory_test.cpp @@ -0,0 +1,247 @@ +// Textures share blocks of device memory (src/image_memory.h) on the Vulkan-backed device: many small textures take a +// few driver allocations, each keeps its own texels, a released texture's range is used again without touching its +// neighbours, and a texture made in a used range reads as zero before anything writes it, as a committed resource does. +// Render targets and large textures keep their own memory. No game data. LEONIDA_VK_VALIDATION=1 adds +// VK_LAYER_KHRONOS_validation. +#include "host_wine.h" +#include "../shims/d3d12_com.h" + +#include +#include +#include +#include +#include + +namespace { +int failures = 0; +void check(bool ok, const char* what) { + if (ok) return; + std::printf("FAIL: %s\n", what); + ++failures; +} + +template +struct Ref { + T* p = nullptr; + Ref() = default; + Ref(const Ref&) = delete; + Ref& operator=(const Ref&) = delete; + Ref(Ref&& other) noexcept : p(other.p) { other.p = nullptr; } + ~Ref() { reset(); } + T* operator->() const { return p; } + void reset() { + if (p) p->Release(); + p = nullptr; + } +}; + +constexpr UINT kSide = 64; +constexpr UINT kPitch = kSide * 4; // a multiple of D3D12_TEXTURE_DATA_PITCH_ALIGNMENT +constexpr UINT kBytes = kPitch * kSide; + +D3D12_RESOURCE_DESC texture_desc(UINT side, UINT16 mips, D3D12_RESOURCE_FLAGS flags) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = desc.Height = side; + desc.DepthOrArraySize = 1; + desc.MipLevels = mips; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.SampleDesc.Count = 1; + desc.Flags = flags; + return desc; +} + +D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + return desc; +} + +struct Gpu { + Ref device; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + HANDLE event = nullptr; + UINT64 value = 0; + + ~Gpu() { + if (event) CloseHandle(event); + } + + bool init() { + if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&device.p))) || !device.p) return false; + D3D12_COMMAND_QUEUE_DESC desc{}; + event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + return event && SUCCEEDED(device->CreateCommandQueue(&desc, IID_PPV_ARGS(&queue.p))) && + SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p))) && + SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p))) && + SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p))); + } + + // Runs what was recorded and waits for it, so that what was released before it is gone. + bool run() { + if (FAILED(list->Close())) return false; + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + if (FAILED(queue->Signal(fence.p, ++value)) || FAILED(fence->SetEventOnCompletion(value, event))) return false; + if (WaitForSingleObject(event, 30000) != WAIT_OBJECT_0) return false; + return SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, nullptr)); + } + + HRESULT create(D3D12_HEAP_TYPE heap, const D3D12_RESOURCE_DESC& desc, D3D12_RESOURCE_STATES state, + Ref& out, D3D12_HEAP_FLAGS flags = D3D12_HEAP_FLAG_NONE) { + D3D12_HEAP_PROPERTIES properties{}; + properties.Type = heap; + return device->CreateCommittedResource(&properties, flags, &desc, state, nullptr, IID_PPV_ARGS(&out.p)); + } +}; + +D3D12_TEXTURE_COPY_LOCATION place(ID3D12Resource* resource, UINT64 offset) { + D3D12_TEXTURE_COPY_LOCATION location{}; + location.pResource = resource; + location.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + location.PlacedFootprint.Offset = offset; + location.PlacedFootprint.Footprint = {DXGI_FORMAT_R8G8B8A8_UNORM, kSide, kSide, 1, kPitch}; + return location; +} + +D3D12_TEXTURE_COPY_LOCATION whole(ID3D12Resource* resource) { + D3D12_TEXTURE_COPY_LOCATION location{}; + location.pResource = resource; + location.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + return location; +} + +void transition(ID3D12GraphicsCommandList* list, ID3D12Resource* resource, D3D12_RESOURCE_STATES from, + D3D12_RESOURCE_STATES to) { + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + barrier.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, from, to}; + list->ResourceBarrier(1, &barrier); +} + +// Reads every texture back and compares each with `expected(index)` (one byte, repeated). +template +int mismatches(Gpu& gpu, const std::vector>& textures, Expected&& expected) { + int bad = 0; + constexpr std::size_t kBatch = 64; + Ref readback; + if (FAILED(gpu.create(D3D12_HEAP_TYPE_READBACK, buffer_desc(UINT64(kBytes) * kBatch), + D3D12_RESOURCE_STATE_COPY_DEST, readback))) + return int(textures.size()); + for (std::size_t first = 0; first < textures.size(); first += kBatch) { + const std::size_t count = std::min(kBatch, textures.size() - first); + for (std::size_t i = 0; i < count; ++i) { + ID3D12Resource* texture = textures[first + i].p; + if (!texture) continue; + transition(gpu.list.p, texture, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_SOURCE); + const auto from = whole(texture); + const auto to = place(readback.p, UINT64(kBytes) * i); + gpu.list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + transition(gpu.list.p, texture, D3D12_RESOURCE_STATE_COPY_SOURCE, D3D12_RESOURCE_STATE_COMMON); + } + if (!gpu.run()) return int(textures.size()); + const std::uint8_t* data = nullptr; + D3D12_RANGE range{0, kBytes * count}; + if (FAILED(readback->Map(0, &range, reinterpret_cast(const_cast(&data))))) return int(textures.size()); + for (std::size_t i = 0; i < count; ++i) { + if (!textures[first + i].p) continue; + const std::uint8_t value = expected(first + i); + for (UINT b = 0; b < kBytes; ++b) + if (data[UINT64(kBytes) * i + b] != value) { + ++bad; + break; + } + } + readback->Unmap(0, nullptr); + } + return bad; +} +} // namespace + +int main() { + Gpu gpu; + if (!gpu.init()) { + std::printf("SKIP: no Vulkan device\n"); + return 77; // ctest skips + } + constexpr std::size_t kTextures = 256; + const auto desc = texture_desc(kSide, 1, D3D12_RESOURCE_FLAG_NONE); + const auto before = rt::d3d12::image_memory_stats(gpu.device.p); + check(before.textures == 0, "no texture is in a block at first"); + + std::vector> textures(kTextures); + for (auto& texture : textures) + check(SUCCEEDED(gpu.create(D3D12_HEAP_TYPE_DEFAULT, desc, D3D12_RESOURCE_STATE_COMMON, texture)), + "create a texture"); + const auto all = rt::d3d12::image_memory_stats(gpu.device.p); + std::printf("%zu textures: %llu in %llu blocks of %llu bytes\n", kTextures, (unsigned long long)all.textures, + (unsigned long long)all.blocks, (unsigned long long)all.block_bytes); + check(all.blocks != 0, "small textures share blocks"); + check(all.textures == kTextures, "every small texture is in a block"); + check(all.blocks <= 2, "256 small textures take at most two driver allocations"); + const auto value_of = [](std::size_t i) { return std::uint8_t(1 + i % 250); }; + + // A value of its own in each, through an upload buffer, then read back: neighbours must not overwrite each other. + Ref upload; + check(SUCCEEDED(gpu.create(D3D12_HEAP_TYPE_UPLOAD, buffer_desc(UINT64(kBytes) * kTextures), + D3D12_RESOURCE_STATE_GENERIC_READ, upload)), + "create the upload buffer"); + std::uint8_t* mapped = nullptr; + if (!upload.p || FAILED(upload->Map(0, nullptr, reinterpret_cast(&mapped)))) return 1; + for (std::size_t i = 0; i < kTextures; ++i) std::memset(mapped + UINT64(kBytes) * i, value_of(i), kBytes); + for (std::size_t i = 0; i < kTextures; ++i) { + transition(gpu.list.p, textures[i].p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST); + const auto to = whole(textures[i].p); + const auto from = place(upload.p, UINT64(kBytes) * i); + gpu.list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + transition(gpu.list.p, textures[i].p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON); + } + check(gpu.run(), "upload"); + check(mismatches(gpu, textures, value_of) == 0, "each texture keeps its own texels"); + + // Release every other one; its range goes back when the next submission has completed. + for (std::size_t i = 1; i < kTextures; i += 2) textures[i].reset(); + check(gpu.run() && gpu.run(), "submit after the release"); + const auto half = rt::d3d12::image_memory_stats(gpu.device.p); + check(half.textures == kTextures / 2, "a released texture leaves its block"); + + // New textures in those ranges: no new block, zero before anything writes them, and the others are untouched. + std::vector> made(kTextures / 2); + for (auto& texture : made) + check(SUCCEEDED(gpu.create(D3D12_HEAP_TYPE_DEFAULT, desc, D3D12_RESOURCE_STATE_COMMON, texture)), + "create a texture in a used range"); + const auto again = rt::d3d12::image_memory_stats(gpu.device.p); + check(again.textures == kTextures && again.blocks == half.blocks, "the released ranges are used again"); + check(mismatches(gpu, made, [](std::size_t) { return std::uint8_t(0); }) == 0, + "a texture in a used range reads as zero"); + check(mismatches(gpu, textures, value_of) == 0, "its neighbours keep their texels"); + + // Render targets and large textures have their own allocations. + Ref target, large; + const auto counted = rt::d3d12::image_memory_stats(gpu.device.p).textures; + check(SUCCEEDED(gpu.create(D3D12_HEAP_TYPE_DEFAULT, + texture_desc(kSide, 1, D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET), + D3D12_RESOURCE_STATE_COMMON, target)), + "create a render target"); + check(SUCCEEDED(gpu.create(D3D12_HEAP_TYPE_DEFAULT, texture_desc(4096, 1, D3D12_RESOURCE_FLAG_NONE), + D3D12_RESOURCE_STATE_COMMON, large)), + "create a large texture"); + check(rt::d3d12::image_memory_stats(gpu.device.p).textures == counted, + "a render target and a large texture are not in a block"); + + textures.clear(); + made.clear(); + check(gpu.run() && gpu.run(), "submit after releasing every texture"); + const auto none = rt::d3d12::image_memory_stats(gpu.device.p); + check(none.textures == 0 && none.blocks <= 1, "with every texture gone, at most one spare block is left"); + if (!failures) std::printf("texture memory: textures share blocks, keep their texels, and start zeroed\n"); + return failures ? 1 : 0; +} diff --git a/runtime/test/image_memory_test.cpp b/runtime/test/image_memory_test.cpp new file mode 100644 index 0000000000..49439b6149 --- /dev/null +++ b/runtime/test/image_memory_test.cpp @@ -0,0 +1,188 @@ +// ImageMemoryPool and BlockRanges (runtime/src/image_memory.h): textures sharing blocks of device memory. CPU only, with +// counted fake allocations: fixed cases for the block policy, then random requests checked against a list of the live +// ranges (no overlap, aligned, inside the block, and all of it usable again when everything is released). + +#include "../src/image_memory.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using leonida::BlockRanges; +using Pool = leonida::ImageMemoryPool; +constexpr std::uint64_t kMiB = std::uint64_t(1) << 20; + +int failures = 0; +void check(bool ok, const char* what) { + if (ok) return; + std::printf("FAIL: %s\n", what); + ++failures; +} + +// A driver: hands out handles 1, 2, 3..., refuses when told, and notes what it freed. The pool frees a block outside +// its own lock, so the driver takes one, as vkAllocateMemory and vkFreeMemory may run on several threads. +struct Driver { + std::mutex mutex; + std::uintptr_t next = 1; + std::set live; + int allocations = 0; + int frees = 0; + bool full = false; + + Pool pool() { + return Pool([this](std::uint32_t, std::uint64_t) -> std::uintptr_t { + std::lock_guard lock(mutex); + ++allocations; + if (full) return 0; + live.insert(next); + return next++; + }, [this](std::uintptr_t memory) { + std::lock_guard lock(mutex); + ++frees; + check(live.erase(memory) == 1, "a block freed that was not live"); + }); + } +}; + +void block_ranges() { + BlockRanges ranges(1000); + std::uint64_t a = 0, b = 0, c = 0, d = 0; + bool reused = true; + check(ranges.allocate(100, 1, a, reused) && a == 0 && !reused, "the first range starts at 0 and is fresh"); + check(ranges.allocate(1, 256, b, reused) && b == 256, "a range starts at its alignment"); + check(ranges.allocate(700, 1, c, reused) && c == 257, "the best fitting free piece is used"); + check(!ranges.allocate(500, 1, d, reused), "a range larger than any free piece is refused"); + check(!ranges.allocate(0, 1, d, reused) && !ranges.allocate(1001, 1, d, reused), + "a zero or an oversized range is refused"); + ranges.release(a, 100); + ranges.release(c, 700); + ranges.release(b, 1); + check(ranges.empty() && ranges.largest() == 1000, "released ranges merge back into one piece"); + check(ranges.allocate(1000, 1, d, reused) && d == 0 && reused, "a range over earlier bytes is marked as reused"); +} + +void shared_blocks() { + Driver driver; + { + Pool pool = driver.pool(); + std::vector> ranges; + for (int i = 0; i < 64; ++i) ranges.push_back(pool.allocate(2, kMiB, 65536, 64 * kMiB)); + check(driver.allocations == 1 && pool.stats().blocks == 1 && pool.stats().ranges == 64 && + pool.stats().block_bytes == 64 * kMiB, + "64 one-MiB textures fill one block"); + auto extra = pool.allocate(2, kMiB, 65536, 64 * kMiB); + check(driver.allocations == 2, "the 65th makes a second block"); + check(extra && !extra->reused(), "a range of a new block is fresh"); + const auto other = pool.allocate(3, kMiB, 65536, 64 * kMiB); + check(driver.allocations == 3 && other->memory() != extra->memory(), "memory types do not share blocks"); + extra.reset(); + check(driver.frees == 0 && pool.stats().blocks == 3, "an emptied block is kept for the next textures"); + ranges.clear(); + check(driver.frees == 1 && pool.stats().blocks == 2, "only one empty block is kept per memory type"); + const auto again = pool.allocate(2, kMiB, 65536, 64 * kMiB); + check(driver.allocations == 3 && again && again->reused(), "the kept block is used again, and marked as reused"); + } + check(driver.live.empty(), "the pool frees its blocks"); +} + +void a_full_heap() { + Driver driver; + Pool pool = driver.pool(); + driver.full = true; + check(!pool.allocate(0, kMiB, 1024, 64 * kMiB), "a driver without room gives no range"); + const int asked = driver.allocations; + for (int i = 0; i < 64; ++i) check(!pool.allocate(0, kMiB, 1024, 64 * kMiB), "and goes on giving none"); + check(driver.allocations == asked, "a full heap is not asked again at every texture"); + check(!pool.allocate(0, kMiB, 1024, 64 * kMiB) && driver.allocations == asked + 1, "but is asked again later"); + check(!pool.allocate(0, 2 * kMiB, 1024, kMiB) && driver.allocations == asked + 1, + "a texture larger than a block is the caller's own allocation"); + + Driver other; + Pool second = other.pool(); + auto held = second.allocate(0, kMiB, 1024, 2 * kMiB); + other.full = true; + auto filling = second.allocate(0, kMiB, 1024, 2 * kMiB); + check(filling && other.allocations == 1, "a full heap still serves the block's own free space"); + check(!second.allocate(0, kMiB, 1024, 2 * kMiB) && other.allocations == 2, "and refuses once it is used up"); + filling.reset(); + check(second.allocate(0, kMiB, 1024, 2 * kMiB) != nullptr, "a released range is usable again at once"); + held.reset(); +} + +void random_requests() { + std::mt19937 random(1274); + for (int round = 0; round < 20; ++round) { + Driver driver; + Pool pool = driver.pool(); + struct Live { + std::unique_ptr range; + std::uint64_t size; + std::uint64_t alignment; + }; + std::vector live; + for (int step = 0; step < 4000; ++step) { + if (live.empty() || random() % 100 < 55) { + const std::uint64_t alignment = std::uint64_t(1) << (8 + random() % 9); + const std::uint64_t size = 1 + random() % (2 * kMiB); + auto range = pool.allocate(1, size, alignment, 16 * kMiB); + check(range != nullptr, "a driver with room serves a small range"); + if (!range) return; + check(range->offset() % alignment == 0 && range->offset() + size <= 16 * kMiB, "aligned, inside the block"); + for (const auto& l : live) + check(l.range->memory() != range->memory() || l.range->offset() >= range->offset() + size || + range->offset() >= l.range->offset() + l.size, + "live ranges do not overlap"); + live.push_back({std::move(range), size, alignment}); + } else { + const std::size_t i = random() % live.size(); + live[i] = std::move(live.back()); + live.pop_back(); + } + } + check(pool.stats().ranges == live.size(), "the range count follows"); + live.clear(); + check(pool.stats().ranges == 0 && pool.stats().blocks == 1, "everything released leaves one spare block"); + const auto whole = pool.allocate(1, 16 * kMiB, 1, 16 * kMiB); + check(whole && whole->offset() == 0, "the whole block is free again"); + } +} + +void threads() { + Driver driver; + { + Pool pool = driver.pool(); + std::vector workers; + for (unsigned t = 0; t < 4; ++t) + workers.emplace_back([&pool, t] { + std::mt19937 random(t); + std::vector> mine; + for (int i = 0; i < 2000; ++i) { + if (mine.size() < 16) mine.push_back(pool.allocate(0, 1 + random() % kMiB, 4096, 16 * kMiB)); + else mine.erase(mine.begin() + random() % mine.size()); + } + }); + for (auto& worker : workers) worker.join(); + check(pool.stats().ranges == 0, "concurrent use leaves no range behind"); + } + check(driver.live.empty(), "nor a block"); +} + +} // namespace + +int main() { + block_ranges(); + shared_blocks(); + a_full_heap(); + random_requests(); + threads(); + if (!failures) std::printf("image memory: textures share blocks, and released ranges are used again\n"); + return failures ? 1 : 0; +}