Skip to content
systemcoding.dev
GPU

Record and Submit Your First Vulkan Command Buffer

Create a command pool, record a vkCmdFillBuffer into a command buffer, submit it with a fence, and read the result back from host-visible memory in C++.

7 min read
Summarize in AI
Flat illustration of a terminal session, with the Vulkan, C++ and GNU Bash logos.

Vulkan does not run commands when you call a function. Calls like vkCmdDraw and vkCmdCopyBuffer write into a command buffer, a list stored in memory, and nothing happens on the GPU until you submit that list to a queue. Understanding this one idea makes the rest of the API easier to predict. This post records and submits the smallest command buffer that proves it works, and it does so without a window: it fills a buffer with a known number on the GPU, waits for the fence, and reads the result back on the CPU. There is no triangle and no swapchain, which keeps attention on the command path. It builds on the logical device from the previous post.

The plan

The program does five things in order:

  1. Create a command pool for the graphics queue family.

  2. Allocate a command buffer from the pool.

  3. Create a buffer in host-visible memory, so the CPU can read it afterward.

  4. Record vkCmdFillBuffer into the command buffer.

  5. Submit with a fence, wait for the fence and read the memory.

vkCmdFillBuffer writes a 32-bit value repeatedly across a range of a buffer. It is a transfer-style command that needs no pipeline, no shader and no render target, so it is the cleanest first command.

Command pools

Command buffers are not allocated one by one from the system. They come from a pool, which manages their memory and is tied to one queue family, because command buffers recorded for a family can only be submitted to queues of that family.

pool.cppcpp
#include <vulkan/vulkan.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <stdexcept>

VkCommandPool create_command_pool(VkDevice device, uint32_t family) {
    VkCommandPoolCreateInfo ci{};
    ci.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
    ci.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
    ci.queueFamilyIndex = family;

    VkCommandPool pool = VK_NULL_HANDLE;
    if (vkCreateCommandPool(device, &ci, nullptr, &pool) != VK_SUCCESS)
        throw std::runtime_error("vkCreateCommandPool failed");
    return pool;
}

The RESET_COMMAND_BUFFER_BIT flag allows each buffer from this pool to be reset and recorded again individually. Without it, buffers can be reset only by resetting the whole pool. For a renderer that re-records one buffer per frame, the flag is convenient, and for one that resets everything at once, resetting the pool is faster.

Pools are not thread safe. Two threads recording commands must use two pools. That rule is the reason pools exist, since it allows recording in parallel without locks.

Allocating a command buffer

allocate.cppcpp
VkCommandBuffer allocate_command_buffer(VkDevice device, VkCommandPool pool) {
    VkCommandBufferAllocateInfo ai{};
    ai.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
    ai.commandPool = pool;
    ai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
    ai.commandBufferCount = 1;

    VkCommandBuffer cb = VK_NULL_HANDLE;
    if (vkAllocateCommandBuffers(device, &ai, &cb) != VK_SUCCESS)
        throw std::runtime_error("vkAllocateCommandBuffers failed");
    return cb;
}

A primary command buffer can be submitted to a queue. A secondary one can only be called from a primary, which is how recording is split across threads in advanced renderers. A first program uses primaries only. You free command buffers with vkFreeCommandBuffers, or by destroying the pool, which frees all of them.

A buffer the CPU can read

To see the result, the buffer must live in memory the CPU can map. Create it and allocate host-visible, host-coherent memory. The memory-type search is the helper from the guide, repeated here so the post is complete:

host_buffer.cppcpp
uint32_t find_memory_type(VkPhysicalDevice phys, uint32_t type_bits, VkMemoryPropertyFlags want) {
    VkPhysicalDeviceMemoryProperties mem;
    vkGetPhysicalDeviceMemoryProperties(phys, &mem);
    for (uint32_t i = 0; i < mem.memoryTypeCount; ++i) {
        if ((type_bits & (1u << i)) && (mem.memoryTypes[i].propertyFlags & want) == want)
            return i;
    }
    throw std::runtime_error("no suitable memory type");
}

struct HostBuffer {
    VkBuffer buffer = VK_NULL_HANDLE;
    VkDeviceMemory memory = VK_NULL_HANDLE;
    VkDeviceSize size = 0;
};

HostBuffer create_host_buffer(VkPhysicalDevice phys, VkDevice device, VkDeviceSize size) {
    VkBufferCreateInfo bi{};
    bi.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
    bi.size = size;
    bi.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
    bi.sharingMode = VK_SHARING_MODE_EXCLUSIVE;

    HostBuffer b;
    b.size = size;
    vkCreateBuffer(device, &bi, nullptr, &b.buffer);

    VkMemoryRequirements req;
    vkGetBufferMemoryRequirements(device, b.buffer, &req);

    VkMemoryAllocateInfo ai{};
    ai.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
    ai.allocationSize = req.size;
    ai.memoryTypeIndex = find_memory_type(phys, req.memoryTypeBits,
        VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
    vkAllocateMemory(device, &ai, nullptr, &b.memory);
    vkBindBufferMemory(device, b.buffer, b.memory, 0);
    return b;
}

Usage flags matter. vkCmdFillBuffer requires the destination buffer to have been created with VK_BUFFER_USAGE_TRANSFER_DST_BIT, and the validation layer reports a missing flag. Host-coherent memory means CPU writes and device writes become visible to each other without explicit flush or invalidate calls, so reading after the GPU finishes needs no extra step.

Record the commands

Recording happens between vkBeginCommandBuffer and vkEndCommandBuffer. Every vkCmd* function in between appends to the list:

record_fill.cppcpp
void record_fill(VkCommandBuffer cb, VkBuffer buffer, VkDeviceSize size, uint32_t value) {
    VkCommandBufferBeginInfo begin{};
    begin.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
    begin.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;

    vkBeginCommandBuffer(cb, &begin);
    vkCmdFillBuffer(cb, buffer, 0, size, value);
    vkEndCommandBuffer(cb);
}

ONE_TIME_SUBMIT_BIT tells the driver this recording will be submitted once and then reset or discarded, which allows it to use cheaper internal storage. A buffer meant for repeated submission omits the flag. After vkEndCommandBuffer, the buffer is in the executable state and ready to submit. Nothing has run on the GPU, and the recording could have happened on another thread a minute earlier.

Submit and wait

Submission hands the buffer to a queue. The call returns at once, long before the GPU is done, so you need a way to find out when it finishes. A fence is the CPU-side signal: you pass it to the submit call and later wait on it.

submit.cppcpp
void submit_and_wait(VkDevice device, VkQueue queue, VkCommandBuffer cb) {
    VkFenceCreateInfo fi{};
    fi.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
    VkFence fence = VK_NULL_HANDLE;
    vkCreateFence(device, &fi, nullptr, &fence);

    VkSubmitInfo submit{};
    submit.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
    submit.commandBufferCount = 1;
    submit.pCommandBuffers = &cb;

    if (vkQueueSubmit(queue, 1, &submit, fence) != VK_SUCCESS)
        throw std::runtime_error("vkQueueSubmit failed");

    vkWaitForFences(device, 1, &fence, VK_TRUE, UINT64_MAX);
    vkDestroyFence(device, fence, nullptr);
}

vkWaitForFences blocks the CPU until the fence signals. The arguments say wait for one fence, wait for all of them if there were several, and wait without a timeout, since UINT64_MAX nanoseconds is effectively forever. The older VkSubmitInfo is used here because it is the shortest. Vulkan 1.3 adds vkQueueSubmit2, which the guide uses, and either works.

Read the result

Once the fence has signaled, the fill is complete and the memory holds the result. Map it, read it, unmap it:

readback.cppcpp
void print_buffer(VkDevice device, const HostBuffer& b, int count) {
    void* mapped = nullptr;
    vkMapMemory(device, b.memory, 0, b.size, 0, &mapped);
    const uint32_t* words = static_cast<const uint32_t*>(mapped);
    for (int i = 0; i < count; ++i)
        std::printf("word[%d] = 0x%08X\n", i, words[i]);
    vkUnmapMemory(device, b.memory);
}

The whole program

Assuming the device, queue and family index from earlier posts, the main sequence is:

main.cppcpp
const VkDeviceSize kSize = 256;     // bytes, a multiple of 4

VkCommandPool pool = create_command_pool(ctx.device, *gpu.families.graphics);
VkCommandBuffer cb = allocate_command_buffer(ctx.device, pool);
HostBuffer buf = create_host_buffer(gpu.device, ctx.device, kSize);

record_fill(cb, buf.buffer, kSize, 0xDEADBEEF);
submit_and_wait(ctx.device, ctx.graphics_queue, cb);
print_buffer(ctx.device, buf, 4);

vkDestroyBuffer(ctx.device, buf.buffer, nullptr);
vkFreeMemory(ctx.device, buf.memory, nullptr);
vkDestroyCommandPool(ctx.device, pool, nullptr);

The program prints the first four 32-bit words of the buffer, all set by the GPU:

Text
word[0] = 0xDEADBEEF
word[1] = 0xDEADBEEF
word[2] = 0xDEADBEEF
word[3] = 0xDEADBEEF

If the output instead shows zeros or garbage, the fence was not waited on, so the CPU read memory the GPU had not yet written, or the submit returned an error that went unchecked. That is the failure the fence exists to prevent.

The fill size and offset of vkCmdFillBuffer must be multiples of 4, the size can be VK_WHOLE_SIZE to fill to the end, and the value is a 32-bit pattern. A size that is not a multiple of 4 is a validation error.

What to take from it

Three ideas from this tiny program carry through everything else. Recording is separate from submission, and recording touches only the command buffer. Submission is asynchronous, so completion must be observed through a fence or semaphore. Objects are destroyed after the GPU is done with them, and here the fence wait guarantees it, which is the same reason a renderer's shutdown begins with vkDeviceWaitIdle.

Reusing the buffer costs one more call: because the pool allows resets, call vkResetCommandBuffer(cb, 0) and record again, but only after the fence from the previous submission has signaled, since resetting a buffer the GPU is reading is undefined.

Errors you may see

A submit failing with VK_ERROR_DEVICE_LOST means the GPU stopped, often because of an invalid command. Beginning a buffer that is already recording is a validation error that names the call. Using a buffer without TRANSFER_DST in vkCmdFillBuffer triggers a message citing the usage flag. And forgetting to end the command buffer before submitting reports the buffer as not executable. In each case, the validation layer's message is more precise than the result code, which is why it must be on.

The commands and structures are defined in the Vulkan specification, Command Buffers chapter and the Fill buffer command description.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.