Barriers¶
Why the GPU needs them¶
The GPU does not run a command list one command at a time. It overlaps commands whenever it can, and it keeps writes in caches that other parts of the GPU may not see. When one command writes memory and a later command reads or writes the same memory, you must tell the GPU to wait for the write to finish and make it visible, or the later command may see stale data. That synchronization command is a barrier.
In RI, barriers are explicit: you write them. RI does not track which buffers or textures a command uses: with bindless access, a dispatch or draw call does not reveal which resources its shader reads or writes, so RI cannot know for certain, and it does not guess.
Coarse barriers: stage to stage¶
An RI barrier names two sets of stages, not resources:
RI::cmdBarrier(cmd, RI::Stage::eCopy, RI::Stage::eCompute); // the copy's writes, then the shader's reads
cmdBarrier(cmd, before, after) means: every write made by the before stages, in
commands recorded earlier, is finished and visible to every access by the after stages,
in commands recorded later.
| Stage | Covers |
|---|---|
Stage::eCopy |
copy commands (cmdCopyBuffer, cmdCopyTexture, cmdCopyBufferToTexture, cmdCopyTextureToBuffer), small writes (cmdWriteSmallData), and clears (cmdClearTexture, cmdClearBuffer) |
Stage::eCompute |
compute shaders (cmdDispatch) |
Stage::eIndirect |
reading indirect arguments (cmdExecuteIndirect) |
Stage::eVertex |
every shader stage before rasterization (vertex, hull, domain, geometry, task, and mesh shaders), including the buffers they pull vertices from |
Stage::ePixel |
pixel shaders |
Stage::eRenderTarget |
color attachment reads and writes in a rendering section, and color resolves |
Stage::eDepthStencil |
depth and stencil tests and writes in a rendering section, and depth/stencil resolves |
Stage::eAccelerationStructure |
acceleration structure builds and updates (requires DeviceLimits::rayTracing) |
Stage::eAll |
every stage |
Stages combine with |.
A barrier is needed between a write and a later access (read or write) of the same memory:
- copy, then a shader reads the copied data:
cmdBarrier(cmd, Stage::eCopy, Stage::eCompute); - a shader writes, then a copy reads:
cmdBarrier(cmd, Stage::eCompute, Stage::eCopy); - a shader writes, then another dispatch reads:
cmdBarrier(cmd, Stage::eCompute, Stage::eCompute); - a rendering section writes a texture, then shaders sample it:
cmdBarrier(cmd, Stage::eRenderTarget | Stage::eDepthStencil, Stage::ePixel | Stage::eCompute); - a compute shader writes a buffer, then a draw pulls vertices from it:
cmdBarrier(cmd, Stage::eCompute, Stage::eVertex).
The before side covers everything recorded earlier, including earlier submissions: a
command list that reads what a previous submission wrote starts with a barrier too.
Two reads never need a barrier. Two dispatches that write different buffers and read nothing of each other need none either.
Why coarse is enough¶
Naming resources in a barrier ("only this buffer") is the fine-grained form. RI has no resource-naming barrier: on desktop GPUs, a barrier that changes no image layout costs about the same whether it names one resource or none. Buffers have no layouts, so for them a global barrier is all there is. Textures have layouts, but RI keeps every texture in one resting layout between operations, so barriers between your work never change one (Image layouts are RI's business). Finer control is available through native code.
Attachments¶
Rendering sections are RI's own operations. Around them RI switches textures between layouts,
and its switch back to rest at cmdEndRendering already makes the section's attachment writes
visible on backends that switch. Write the barrier after a section anyway: on Vulkan with
unified layouts (or eGeneral mode) there is no switch, and the barrier is what orders the
next reads. On D3D12, global barriers cannot name attachment accesses, so Stage::eRenderTarget
and Stage::eDepthStencil add nothing there, and a barrier whose before or after holds only
attachment stages records nothing.
The CPU side: nothing to do¶
On D3D12, once a submission's fence value is reached, the CPU sees its writes in mapped
memory. Vulkan needs one more barrier, from all GPU writes to the host stage, before the
CPU can read them. RI's cmdEnd adds this barrier on Vulkan, so on
both backends: once the submission's TimelinePoint is reached, mapped memory holds the GPU's
results. You never write a barrier to the CPU.
The same in native code¶
RI::cmdBegin(cmd);
RI::cmdCopyBuffer(cmd, staging, 0, input, 0, kBytes);
RI::cmdBarrier(cmd, RI::Stage::eCopy, RI::Stage::eCompute); // the copy's writes, then the shader's reads
RI::cmdSetHeap(cmd, heap);
RI::cmdSetPipeline(cmd, pipeline);
RI::Helpers::cmdSetRootData(cmd, Root{.inputSlot = 0, .outputSlot = 1, .paramsSlot = 2, .scale = 3.0f, .count = kCount});
RI::cmdDispatch(cmd, (kCount + 63) / 64, 1, 1); // 64 threads per group, see [numthreads]
RI::cmdBarrier(cmd, RI::Stage::eCompute, RI::Stage::eCopy); // the shader's writes, then the copy's reads
RI::cmdCopyBuffer(cmd, output, 0, result, 0, kBytes);
RI::cmdEnd(cmd);
A global memory barrier (VkMemoryBarrier2) through vkCmdPipelineBarrier2:
// A global memory barrier: every write of `srcStages` becomes visible to
// every access of `dstStages`. Buffers have no layouts, so this is all they need.
const auto barrier = [&](VkPipelineStageFlags2 srcStages, VkPipelineStageFlags2 dstStages,
VkAccessFlags2 dstAccess) {
const VkMemoryBarrier2 memoryBarrier{.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2,
.srcStageMask = srcStages,
.srcAccessMask = VK_ACCESS_2_MEMORY_WRITE_BIT,
.dstStageMask = dstStages,
.dstAccessMask = dstAccess};
const VkDependencyInfo dependency{.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO,
.memoryBarrierCount = 1,
.pMemoryBarriers = &memoryBarrier};
vkCmdPipelineBarrier2(cmd, &dependency);
};
const VkCommandBufferBeginInfo beginInfo{.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
check(vkBeginCommandBuffer(cmd, &beginInfo), "vkBeginCommandBuffer");
const VkBufferCopy copyIn{.srcOffset = 0, .dstOffset = 0, .size = kBytes};
vkCmdCopyBuffer(cmd, staging, input, 1, ©In);
barrier(VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT, VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT,
VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT);
// The same order as RI's rule: the heap first, then the pipeline.
vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipelineLayout, 0, 1, &heap, 0, nullptr);
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_COMPUTE, pipeline);
const Root root{.inputSlot = 0, .outputSlot = 1, .paramsSlot = 2, .scale = 3.0f, .count = kCount};
vkCmdPushConstants(cmd, pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(root), &root);
vkCmdDispatch(cmd, (kCount + 63) / 64, 1, 1);
barrier(VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT,
VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT);
const VkBufferCopy copyOut{.srcOffset = 0, .dstOffset = 0, .size = kBytes};
vkCmdCopyBuffer(cmd, output, result, 1, ©Out);
// Make the copy's writes visible to the CPU (the host stage) before ending.
barrier(VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_2_HOST_BIT, VK_ACCESS_2_HOST_READ_BIT);
check(vkEndCommandBuffer(cmd), "vkEndCommandBuffer");
| RI stage | Vulkan stage |
|---|---|
eCopy |
VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT |
eCompute |
VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT |
eIndirect |
VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT (plus VK_PIPELINE_STAGE_2_COMMAND_PREPROCESS_BIT_EXT when DeviceLimits::indirectRootData is true) |
eVertex |
VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT |
ePixel |
VK_PIPELINE_STAGE_2_FRAGMENT_SHADER_BIT |
eRenderTarget |
VK_PIPELINE_STAGE_2_COLOR_ATTACHMENT_OUTPUT_BIT |
eDepthStencil |
VK_PIPELINE_STAGE_2_EARLY_FRAGMENT_TESTS_BIT \| VK_PIPELINE_STAGE_2_LATE_FRAGMENT_TESTS_BIT |
eAccelerationStructure |
VK_PIPELINE_STAGE_2_ACCELERATION_STRUCTURE_BUILD_BIT_KHR |
eAll |
VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT |
RI uses VK_ACCESS_2_MEMORY_WRITE_BIT as the source access and
VK_ACCESS_2_MEMORY_READ_BIT | VK_ACCESS_2_MEMORY_WRITE_BIT as the destination access.
A global enhanced barrier (D3D12_GLOBAL_BARRIER) through ID3D12GraphicsCommandList7::Barrier:
// A global barrier: no resource named. Buffers have no layouts, so this is all they need.
const auto barrier = [&](D3D12_BARRIER_SYNC syncBefore, D3D12_BARRIER_ACCESS accessBefore,
D3D12_BARRIER_SYNC syncAfter, D3D12_BARRIER_ACCESS accessAfter) {
D3D12_GLOBAL_BARRIER global{.SyncBefore = syncBefore,
.SyncAfter = syncAfter,
.AccessBefore = accessBefore,
.AccessAfter = accessAfter};
const D3D12_BARRIER_GROUP group{.Type = D3D12_BARRIER_TYPE_GLOBAL, .NumBarriers = 1, .pGlobalBarriers = &global};
cmd->Barrier(1, &group);
};
check(cmd->Reset(allocator.Get(), nullptr), "ID3D12GraphicsCommandList::Reset"); // opens it for recording
cmd->CopyBufferRegion(input.Get(), 0, staging.Get(), 0, kBytes); // destination first
barrier(D3D12_BARRIER_SYNC_COPY, D3D12_BARRIER_ACCESS_COPY_DEST, D3D12_BARRIER_SYNC_COMPUTE_SHADING,
D3D12_BARRIER_ACCESS_SHADER_RESOURCE | D3D12_BARRIER_ACCESS_UNORDERED_ACCESS);
ID3D12DescriptorHeap *heaps[] = {viewHeap.Get(), samplerHeap.Get()};
cmd->SetDescriptorHeaps(2, heaps); // before the root signature that indexes them
cmd->SetComputeRootSignature(rootSignature.Get());
cmd->SetPipelineState(pipeline.Get());
const Root root{.inputSlot = 0, .outputSlot = 1, .paramsSlot = 2, .scale = 3.0f, .count = kCount};
cmd->SetComputeRoot32BitConstants(0, sizeof(root) / 4, &root, 0);
cmd->Dispatch((kCount + 63) / 64, 1, 1);
barrier(D3D12_BARRIER_SYNC_COMPUTE_SHADING, D3D12_BARRIER_ACCESS_UNORDERED_ACCESS, D3D12_BARRIER_SYNC_COPY,
D3D12_BARRIER_ACCESS_COPY_SOURCE);
cmd->CopyBufferRegion(result.Get(), 0, output.Get(), 0, kBytes);
// No barrier to the CPU: once the fence value is reached, mapped reads see the writes.
check(cmd->Close(), "ID3D12GraphicsCommandList::Close");
| RI stage | D3D12 sync | Accesses |
|---|---|---|
eCopy |
SYNC_COPY \| SYNC_CLEAR_UNORDERED_ACCESS_VIEW |
COPY_SOURCE \| COPY_DEST \| UNORDERED_ACCESS |
eCompute |
SYNC_COMPUTE_SHADING |
UNORDERED_ACCESS \| SHADER_RESOURCE \| CONSTANT_BUFFER (plus RAYTRACING_ACCELERATION_STRUCTURE_READ when DeviceLimits::rayTracing is supported) |
eIndirect |
SYNC_EXECUTE_INDIRECT |
INDIRECT_ARGUMENT |
eVertex |
SYNC_VERTEX_SHADING |
UNORDERED_ACCESS \| SHADER_RESOURCE \| CONSTANT_BUFFER (plus RAYTRACING_ACCELERATION_STRUCTURE_READ when DeviceLimits::rayTracing is supported) |
ePixel |
SYNC_PIXEL_SHADING |
UNORDERED_ACCESS \| SHADER_RESOURCE \| CONSTANT_BUFFER (plus RAYTRACING_ACCELERATION_STRUCTURE_READ when DeviceLimits::rayTracing is supported) |
eRenderTarget, eDepthStencil |
none: covered by RI's switch at cmdEndRendering |
none |
eAccelerationStructure |
SYNC_BUILD_RAYTRACING_ACCELERATION_STRUCTURE |
RAYTRACING_ACCELERATION_STRUCTURE_READ \| RAYTRACING_ACCELERATION_STRUCTURE_WRITE |
eAll |
SYNC_ALL |
every access above |
What to watch for: enhanced barriers need the Agility SDK and a recent driver; the older
ResourceBarrier with resource states is the legacy model.