Skip to content

Memory kinds and placed resources

Two steps: memory, then resources

In many engines, "create a buffer" also finds memory for it. RI splits this in two:

  1. Allocate a memory block of a given kind and size: RI::allocateMemory.
  2. Place resources in it at offsets you choose: RI::createBuffer(device, memory, offset, desc).

A buffer owns no memory; it is a view of part of a block. This lets you write your own allocator (one large block, sub-allocated however you like), and place two resources at the same offset when they are never used at the same time (aliasing; for textures, see Textures). A separate memory allocator helper built on these two calls sub-allocates memory blocks for buffers and textures automatically.

To place a buffer you need its size and alignment, which depend on the GPU and the usage: RI::bufferRequirements gives both. Every buffer fits every available memory kind, though on Vulkan a few usages (such as indirect scratch) may need allocateMemory's forResource parameter to pick a compatible native type. Textures, by contrast, usually fit eGPU only (see RI::textureRequirements).

// How much memory, at what alignment, a buffer with this description needs.
const RI::BufferDesc dataDesc{
    .size = kBytes,
    .usage = RI::BufferUsage::eRead | RI::BufferUsage::eReadWrite | RI::BufferUsage::eCopySrc |
             RI::BufferUsage::eCopyDst,
};
const RI::MemoryRequirements dataReq = RI::bufferRequirements(device, dataDesc);
// Two such buffers side by side: the second starts at an aligned offset.
const uint64 outputOffset = alignUp(dataReq.size, dataReq.alignment);
RI::Memory gpuMemory = RI::allocateMemory(device, RI::MemoryKind::eGPU, outputOffset + dataReq.size);
RI::Memory uploadMemory = RI::allocateMemory(device, RI::MemoryKind::eUpload, paramsOffset + 256);
RI::Memory readbackMemory = RI::allocateMemory(device, RI::MemoryKind::eReadback, kBytes);
RI::Buffer input = RI::createBuffer(device, gpuMemory, 0, dataDesc);
RI::Buffer output = RI::createBuffer(device, gpuMemory, outputOffset, dataDesc);
RI::Buffer staging = RI::createBuffer(device, uploadMemory, 0, {.size = kBytes, .usage = RI::BufferUsage::eCopySrc});
RI::Buffer params =
    RI::createBuffer(device, uploadMemory, paramsOffset, {.size = 256, .usage = RI::BufferUsage::eConstant});
RI::Buffer result = RI::createBuffer(device, readbackMemory, 0, {.size = kBytes, .usage = RI::BufferUsage::eCopyDst});

The four memory kinds

Native APIs list many memory types; RI has four kinds, named after what they are for:

Kind Who writes, who reads Mapped Typical use
eGPU the GPU no everything the GPU works on: fastest for the GPU
eUpload the CPU writes, the GPU reads yes staging data to copy into eGPU memory; small per-frame constants
eReadback the GPU writes, the CPU reads yes results copied back from eGPU memory
eGPUUpload the CPU writes into GPU memory yes data the GPU reads often and the CPU updates, without a copy (needs ReBAR)

eGPUUpload exists only where all of the GPU's memory is visible to the CPU (resizable BAR, "ReBAR"). Check device.limits.gpuUploadMemory before using it; allocating it elsewhere reports an unsupported error.

What each kind is natively

Kind Vulkan memory type D3D12 heap type
eGPU DEVICE_LOCAL, preferably not HOST_VISIBLE DEFAULT
eUpload HOST_VISIBLE \| HOST_COHERENT, preferably neither DEVICE_LOCAL nor HOST_CACHED UPLOAD
eReadback HOST_VISIBLE \| HOST_COHERENT, preferably HOST_CACHED and not DEVICE_LOCAL READBACK
eGPUUpload DEVICE_LOCAL \| HOST_VISIBLE \| HOST_COHERENT, on the largest device-local heap GPU_UPLOAD

On Vulkan, RI picks one memory type per kind when the device is created, among the types that accept buffers. It never uses AMD's device-coherent or uncached types, protected memory, or lazily allocated memory. On D3D12, memory is an ID3D12Heap; buffers are placed in it with CreatePlacedResource2. Knowing which native memory pool each kind uses matters when you manage memory budgets yourself, because RI does not track budgets.

Mapping: always on, never flushed

Memory of every kind except eGPU is mapped once, when it is allocated, and stays mapped until it is freed. memory.mapped is the CPU address of the block, and buffer.mapped is the address of a buffer placed in it (memory.mapped + offset). There is no map or unmap call, and no flush or invalidate: RI chooses coherent memory.

// Upload memory stays mapped: write through buffer.mapped, no map call.
auto *values = static_cast<float *>(staging.mapped);
for (uint32 i = 0; i < kCount; ++i) {
    values[i] = static_cast<float>(i);
}
const float offset = 0.25f;
std::memcpy(params.mapped, &offset, sizeof(offset));

Two rules:

  • Upload memory (eUpload and eGPUUpload) is write-only in practice. Reading it from the CPU works, but it is uncached and very slow.
  • Read GPU results only after the timeline point of the work that wrote them (Timeline points). RI makes the GPU's writes visible to the CPU at that point on both backends.

GPU addresses

Every buffer always has a 64-bit GPU address in buffer.gpuAddress. Shaders can read through it with buffer pointers, and GPU-built tables (acceleration-structure instances, work-graph inputs, your own virtual-memory tables) store it. On Vulkan this means every memory block is allocated with VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT and every buffer has VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; on D3D12 every buffer has an address anyway.

The same in native code

RI::Memory gpuMemory = RI::allocateMemory(device, RI::MemoryKind::eGPU, outputOffset + dataReq.size);
RI::Memory uploadMemory = RI::allocateMemory(device, RI::MemoryKind::eUpload, paramsOffset + 256);
RI::Memory readbackMemory = RI::allocateMemory(device, RI::MemoryKind::eReadback, kBytes);
// A memory type the resource accepts (`allowedTypes`, from its requirements)
// with every property in `required`.
uint32_t findMemoryType(VkPhysicalDevice gpu, uint32_t allowedTypes, VkMemoryPropertyFlags required) {
    VkPhysicalDeviceMemoryProperties memory{};
    vkGetPhysicalDeviceMemoryProperties(gpu, &memory);
    for (uint32_t i = 0; i < memory.memoryTypeCount; ++i) {
        if ((allowedTypes & (1u << i)) != 0 && (memory.memoryTypes[i].propertyFlags & required) == required) {
            return i;
        }
    }
    std::fprintf(stderr, "no suitable memory type\n");
    std::exit(1);
}
// One block of memory. The flags let buffers placed in it have a GPU address.
VkDeviceMemory allocate(VkDevice device, uint32_t type, VkDeviceSize size) {
    const VkMemoryAllocateFlagsInfo flags{
        .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO,
        .flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT,
    };
    const VkMemoryAllocateInfo info{
        .sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
        .pNext = &flags,
        .allocationSize = size,
        .memoryTypeIndex = type,
    };
    VkDeviceMemory memory = VK_NULL_HANDLE;
    check(vkAllocateMemory(device, &info, nullptr, &memory), "vkAllocateMemory");
    return memory;
}
// GPU memory: device-local. Upload and readback: CPU-visible and coherent
// (no flush/invalidate calls), mapped once for their whole lifetime.
const VkMemoryPropertyFlags hostCoherent = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
VkDeviceMemory gpuMemory = allocate(
    device, findMemoryType(gpu, req.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT), outputOffset + req.size);
VkDeviceMemory uploadMemory =
    allocate(device, findMemoryType(gpu, req.memoryTypeBits, hostCoherent), paramsOffset + 256);
VkDeviceMemory readbackMemory = allocate(
    device, findMemoryType(gpu, req.memoryTypeBits, hostCoherent | VK_MEMORY_PROPERTY_HOST_CACHED_BIT), kBytes);
void *uploadMapped = nullptr;
void *readbackMapped = nullptr;
check(vkMapMemory(device, uploadMemory, 0, VK_WHOLE_SIZE, 0, &uploadMapped), "vkMapMemory");
check(vkMapMemory(device, readbackMemory, 0, VK_WHOLE_SIZE, 0, &readbackMapped), "vkMapMemory");

What to watch for: memory types differ per GPU, so you search for one with the properties you need among those the resource accepts (memoryTypeBits). Without HOST_COHERENT, CPU writes need vkFlushMappedMemoryRanges and CPU reads need vkInvalidateMappedMemoryRanges.

// One block of memory: a heap of a given type. Buffers are placed in it later.
ComPtr<ID3D12Heap> allocate(ID3D12Device10 *device, D3D12_HEAP_TYPE type, UINT64 size) {
    const D3D12_HEAP_DESC desc{
        .SizeInBytes = (size + 65535) / 65536 * 65536, // whole 64 KiB blocks
        .Properties = {.Type = type},
        .Alignment = D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT,
        .Flags = D3D12_HEAP_FLAG_ALLOW_ONLY_BUFFERS,
    };
    ComPtr<ID3D12Heap> heap;
    check(device->CreateHeap(&desc, IID_PPV_ARGS(&heap)), "CreateHeap");
    return heap;
}
// DEFAULT: GPU memory. UPLOAD: CPU writes, GPU reads. READBACK: GPU writes, CPU reads.
ComPtr<ID3D12Heap> gpuMemory = allocate(device.Get(), D3D12_HEAP_TYPE_DEFAULT, outputOffset + info.SizeInBytes);
ComPtr<ID3D12Heap> uploadMemory = allocate(device.Get(), D3D12_HEAP_TYPE_UPLOAD, paramsOffset + 256);
ComPtr<ID3D12Heap> readbackMemory = allocate(device.Get(), D3D12_HEAP_TYPE_READBACK, kBytes);

What to watch for: D3D12 maps resources, not heaps. To keep a whole block mapped, RI places one buffer spanning the heap and maps it once; the buffers you place later share its memory.