Foundations
GPU synchronization: barriers, stages, layouts
A GPU runs the commands of a command buffer in order, but not one after the other: they overlap, and their results sit in caches for a while. When one command reads what another wrote, the program has to say so, with a barrier. This page explains what a barrier does, how to write one well, and how images add layouts on top. The last part shows RASM's barriers.
In short
- Two uses of the same memory, where at least one writes, form a hazard: read after write, write after read, or write after write.
- A barrier is an execution dependency (later work waits for earlier work) plus, for writes, a memory dependency (the write is flushed from caches and made visible to the reader).
- Both halves are scoped by pipeline stages and access types: "wait for these stages, and make these writes visible to those reads".
- Narrow scopes keep the GPU busy. Too wide is slow but correct; too narrow is a bug that may only show on another GPU.
- Images also have a layout, the way their memory is arranged for one kind of use. A barrier changes it, and the old contents can be discarded at the same time.
- Across submissions and queues, semaphores order GPU work and fences tell the CPU. A render graph can write all of this from declared reads and writes.
1Why the GPU needs to be told
Commands in one command buffer start in the order they were recorded. But a GPU is a pipeline with many cores: the next command starts as soon as there is room, long before the last one is done. Without a barrier, a command that reads a buffer can run at the same time as the command that writes it.
Older APIs found these cases themselves. Vulkan and Direct3D 12 do not: the program says where they are.
A missing barrier is not an error the driver reports. It is a race, and it may only show up on another GPU, another driver, or under more load.
2Hazards
Take two commands, A then B, that use the same memory. What matters is which of them writes.
RAW: read after write
Culling writes a draw list, the draw reads it.
Barrier: wait for A, and make A's writes visible to B
WAR: write after read
A pass samples a texture, the next frame draws into it.
Barrier: only wait for A. A read leaves nothing in a cache to flush.
WAW: write after write
Two passes draw into the same target.
Barrier: wait for A, and order the writes, so the last one wins
RAR: read after read
Two passes sample the same texture.
Barrier: nothing. Reads never conflict (but an image may still need a layout change).
3Two halves: execution and memory
"Wait for A" is only half of the job. The other half is caches. A GPU has a small cache next to each group of cores, a larger shared one, and then memory. A write first lands in a cache near the core that made it. Another core may hold an old copy of the same bytes in its own cache.
Execution dependency
"Work after the barrier, in these stages, does not start before work before the barrier, in those stages, has finished." Enough for write after read.
Memory dependency
"Writes of these kinds, before the barrier, are made available, and then visible to accesses of those kinds after it." Needed for read after write and write after write.
4Pipeline stages: what to wait for
A command passes through stages. A draw goes through the graphics pipeline; a dispatch through the compute stage; a copy through the transfer stage. A barrier names stages on both sides:
That last sentence is where the speed comes from. Name the latest source stage that really writes, and the earliest destination stage that really reads. Everything else can overlap:
5Access types: what to flush and make visible
Stages say when. Access types say which memory traffic the memory dependency covers. Each access type belongs to certain stages:
| Stage | Reads | Writes |
|---|---|---|
| draw indirect | indirect command read | — |
| index input, vertex input | index read, vertex attribute read | — |
| vertex, fragment, compute shader | uniform read, shader sampled read, shader storage read | shader storage write |
| early and late depth tests | depth attachment read | depth attachment write |
| color output | color attachment read (blending, load) | color attachment write |
| copy | transfer read | transfer write |
| host | host read | host write |
One barrier, read from left to right. This one is the example of section 6:
- Source access: only the writes before the barrier. A read leaves nothing to flush, so naming it does nothing.
- Destination access: every read and write after the barrier that must see the earlier writes (or come after them).
- Write after read: source access is empty. The stages alone are enough.
6Writing a barrier: Vulkan synchronization2
Vulkan 1.3 made synchronization2 core. It packs stage and access together for each side of each barrier, which is easier to read than the original call. One call, vkCmdPipelineBarrier2, takes a list of barriers of three kinds:
Memory barrier
Covers all memory. Use it for buffers. Drivers rarely do better with a per-buffer barrier, and a global one also covers memory read through GPU pointers.
Buffer barrier
Covers one range of one buffer. Use it to pass a buffer between queue families (section 9).
Image barrier
Covers some mips and layers of one image. Use it for images: it is the only kind that can change a layout.
A memory barrier for the example on this page's first picture, where a compute shader writes the draw commands of a later indirect draw:
// A compute pass wrote draw commands; the next draw reads them as indirect arguments.
VkMemoryBarrier2 barrier = {.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER_2,
.srcStageMask = VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT,
.srcAccessMask = VK_ACCESS_2_SHADER_STORAGE_WRITE_BIT,
.dstStageMask = VK_PIPELINE_STAGE_2_DRAW_INDIRECT_BIT,
.dstAccessMask = VK_ACCESS_2_INDIRECT_COMMAND_READ_BIT};
VkDependencyInfo dependency = {.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO, .memoryBarrierCount = 1, .pMemoryBarriers = &barrier};
vkCmdPipelineBarrier2(commandBuffer, &dependency);
Put several barriers into one call when they sit at the same point: the driver can then do one wait instead of several. And never put a barrier between two draws "just in case": every barrier drains part of the pipeline.
7Image layouts
GPUs store images in different arrangements for different uses: tiled and compressed for drawing into, a different tiling for sampling, plain lines for the display. Vulkan calls the arrangement a layout, and it is part of the image's state. An image barrier changes it, between the source and the destination scopes.
| Layout (Vulkan) | For |
|---|---|
| UNDEFINED | "I do not care about the contents". Only valid as the old layout: changing from it may throw the contents away. |
| COLOR_ATTACHMENT_OPTIMAL | drawing into the image |
| DEPTH_STENCIL_ATTACHMENT_OPTIMAL | depth testing and writing |
| SHADER_READ_ONLY_OPTIMAL | sampling in shaders |
| TRANSFER_SRC / TRANSFER_DST_OPTIMAL | copies and blits |
| GENERAL | anything, including storage writes; possibly slower |
| PRESENT_SRC | handing a swapchain image to the display |
Place the barriers of such a target yourself. Here two passes sample it after the draw.
Two details catch people out:
A discard still waits
An image barrier is a full barrier. Even a "discard" must still wait for the last use of the image (a write after read), so its source stages are not empty.
One layout per mip and layer
The layout belongs to each mip level and array layer. A barrier can change only some of them, and the program must then track each one.
8Worked example: the barriers of a small frame
A frame with four steps: a compute pass builds a draw list, a pass draws the scene into an offscreen target using that list, a post pass samples the target and draws into the swapchain image, and the image is presented. Click through the barriers (or use the arrow keys).
1. Draw list: compute writes, the draw reads
A global memory barrier is enough: no layout is involved. The destination is the earliest stage that reads the list.
2. Offscreen target: discard, then draw
The pass clears the target, so the old contents can go: the old layout is UNDEFINED. The source stage still makes the draw wait for last frame's samples.
3. Post pass: the target becomes a texture
This is the code snippet's twin, for an image. In the same call goes the barrier for the swapchain image: UNDEFINED to color attachment, waiting at color output, where the acquire semaphore waits too (see the swapchain).
4. Present
Four barriers for four uses. In a bigger frame, the same reasoning repeats per resource: who wrote it last, who reads it next, which layout.
9Beyond one command buffer
A barrier works inside one queue. Other borders need other tools:
Commands on one queue, even in different submissions
Use a pipeline barrier. Its first scope covers everything submitted earlier to the same queue, and its second scope everything later.
Submission order is enough; no semaphore needed.
Two queues (graphics and async compute, or transfer)
Use a semaphore. The signaling submit finishes and makes its writes available; the waiting submit waits at the stages it names.
GPU → CPU
Use a fence (or timeline value), plus a barrier to the host stage. The barrier makes the GPU's writes available to the host; the fence says they are done.
Memory that is not host-coherent: also invalidate the CPU's range before reading.
CPU → GPU
Use the submit itself. Host writes made before a submit are visible to it.
Memory that is not host-coherent: flush the range first.
Passing a resource between queue families
When to use a second queue, and what it costs: Async compute and multiple queues.
10Other APIs
| API | Who places barriers | How |
|---|---|---|
| Vulkan | the program | pipeline barriers with stages, accesses and layouts; events for split barriers |
| Direct3D 12 | the program | resource barriers between resource states (a state is roughly layout + access); "enhanced barriers" add Vulkan-like stages and accesses; split barriers with begin and end |
| Metal | the driver, by default | tracks hazards per resource; resources can opt out ("untracked") and use fences or events instead |
| WebGPU | the implementation, always | tracks every use inside and between passes; the program never writes a barrier |
11Automating it, and pitfalls
Writing every barrier by hand does not scale. Two common helpers:
Track the state of each resource
Each image remembers its current layout and last use. A call like "make this texture readable" records the right barrier, or none. Simple, but each call only knows the past.
A render graph
Passes declare what they read and write before anything is recorded. The graph knows the whole frame, so it can place, merge and move barriers. See render graphs.
The usual mistakes:
- Read access in the source mask
- Does nothing. The intended write is not flushed if it was left out.
- Forgetting write after read
- A pass overwrites a texture while the previous pass still samples it.
- ALL_COMMANDS on both sides, everywhere
- Correct but slow: the GPU drains at every barrier.
- Wrong old layout
- Undefined contents, or a validation error. UNDEFINED as old layout when the contents are needed loses them.
- A barrier inside a render pass
- Not allowed in Vulkan's dynamic rendering, except for special self-dependencies. End the pass first.
- Testing on one GPU
- Some GPUs flush caches anyway, and hide the missing barrier. Use the validation layer's synchronization validation.
12In RASM
RASM uses synchronization2, a graphics queue and, with async compute on, a compute queue. The RHI offers two barrier calls, deliberately coarse: a global memoryBarrier between sets of PipelineStage, and an image transition between two TextureUsage values. RenderContext remembers each texture's usage, and the RenderGraph derives barriers from what passes declare.
vkCmdPipelineBarrier2 in RASM comes from src/rhi/vulkan/vulkanCommandBuffer.cpp. Three more calls there record barriers of their own: aliasingBarrier (a global barrier before the first pass of a transient target, memory aliasing), copyToTextures (staged texture uploads: every texture of the batch to the copy layout in one call, then back to SAMPLED) and copyFromTexture (a readback: the one mip and layer to the copy layout and back, then the buffer to the host). Textures filled from the CPU in a format with host image copy skip the GPU entirely: fillTexture changes their layout on the host (vkTransitionImageLayout) and leaves them SAMPLED.The three stage sets
PipelineStage | Vulkan stages | Accesses as before (writes only) | Accesses as after |
|---|---|---|---|
COMPUTE | compute shader | shader storage write | shader storage read and write, uniform read |
GRAPHICS | draw indirect, index input, vertex shader, fragment shader | shader storage write | indirect command, index, shader storage and uniform read; shader storage write |
HOST | host | host write | host read and write |
PipelineStage is a set of flags, so one barrier can name several with |. Before the late culling the graph records GRAPHICS | COMPUTE → COMPUTE: the early draws read the lists that it rewrites, and the Hi-Z build wrote what it reads. endFrame ends with COMPUTE → HOST, so the CPU reads the cull stats after the fence.
Texture usages and their scopes
TextureUsage | Vulkan layout | As old usage, waits for | As new usage, blocks |
|---|---|---|---|
UNKNOWN | undefined | color output, depth tests, fragment and compute shaders; flushes color, depth and storage writes | — (not a target) |
COLOR_ATTACHMENT | color attachment | color output writes | color output reads and writes |
DEPTH_STENCIL_ATTACHMENT | depth attachment | depth test writes | depth test reads and writes |
STORAGE | general | compute shader storage writes | compute shader storage reads and writes |
SAMPLED | shader read only | fragment and compute shaders (no access: reads) | fragment and compute shader reads |
PRESENT_SRC | present | — (not a source) | nothing |
Any other usage has no scope: the transition logs an error, records nothing and returns false. The source scope comes only from the old usage and the destination only from the new one, so each table row is written once. UNKNOWN as the old usage is the "discard" of section 7: it waits for every stage that could have used the image, because the last use is not known. Its color output stage also chains the barrier to the swapchain's acquire semaphore.
Remembering texture states
SAMPLED → SAMPLED records nothing (read after read). Any other same-usage transition is still recorded, because attachments are written: COLOR_ATTACHMENT → COLOR_ATTACHMENT orders earlier draws before a pass that loads the image. submitBatches calls discardRecording when a submit fails or the frame is dropped, so the next frame starts from the layouts the GPU really has. With async compute a frame is several submits, so each submit forgets only its own command buffers' changes: the batches that went out keep theirs.The barriers of one frame
Renderer::render with the default EngineConfig: occlusionCulling on; async compute, anti-aliasing, bloom and the UI off. Every pass is a graph pass in the one frame command buffer, so no barrier sits inside a rendering scope. With async compute on, the barriers between the two queues become waits (next section). The graph records the barrier before each pass from what the pass declares; the COMPUTE → COMPUTE barriers between dispatches inside a pass come from the pass itself (recordSceneCulling, recordHiz). With EngineConfig::ui, a UI pass after the tone map loads the image. A readback asked for this frame is copied in endFrame, before the move to PRESENT_SRC. See occlusion culling.Across queues
With EngineConfig::asyncCompute, the Animate, Skin, culling and Hi-Z passes run on a compute queue from a family without graphics. Work on the other queue is outside a barrier's scopes, so a barrier between the queues becomes a wait: the waiting submit waits for the other queue's timeline fence (FenceValue in SubmitInfo::waits).
| Between | RASM uses |
|---|---|
| passes on one queue | a barrier, as without async compute |
| a compute batch and a graphics batch | a timeline fence wait at all commands (VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT), since a batch often starts with a layout transition that must come after it |
| uploads and the compute queue | the upload submit waits for the last compute submit, and a compute submit waits for the last upload (UploadManager::lastSubmit) |
| barriers in a compute-queue command buffer | fitToComputeQueue: graphics source stages become all commands, which chains to the submit's wait; graphics destination stages and graphics-only accesses are dropped |
| resource ownership | with a compute queue, every buffer and image is created VK_SHARING_MODE_CONCURRENT for both families; a texture a load fills on the transfer queue moves to the graphics family by a release and an acquire (transfer queues) |
The render graph's part
Before each pass, RenderGraph::execute records at most one memoryBarrier, moves the textures the pass reads to SAMPLED and, for a compute pass, the storage target it writes to STORAGE (bloom). Before the first pass of a transient target it records the aliasingBarrier. bufferBarrier keeps, per buffer and per queue, the stages of the last write and of the reads since. Its rules are the hazards of section 2: a read after a write waits for the write (once per reading stage), and a write waits for every use since the last write. A use on the other queue gets a wait instead (RenderGraph::waitForOtherQueue). The state carries over to the next frame. See render graphs.
Where RASM follows the textbook, and where it differs
| Part | This page | RASM |
|---|---|---|
| Stages | name the latest source and earliest destination | Three coarse sets. GRAPHICS always means four stages, so a barrier into GRAPHICS waits from draw indirect on: correct, sometimes wider than needed. |
| Access rule | source: writes; destination: reads and writes | The same, in memoryBarrier. |
| Buffer barriers | global memory barriers are fine | Global ones. Shaders reach buffers through device addresses, which a per-buffer barrier could not name anyway. The one buffer barrier is a readback's: copy → host, on the buffer the image was copied into. |
| Image barriers | per mip and layer | Always the whole mip chain and every layer. No per-mip tracking. Only a readback's copy moves the one mip and layer it copies, and puts it back. |
| Batching | several barriers per call | One barrier per vkCmdPipelineBarrier2 call, except two: copyToTextures moves all the textures of an upload batch in one call, and copyFromTexture ends with the image and the buffer barrier in one call. |
| State tracking | per resource, or a render graph | Both: TextureStates for textures, RenderGraph::bufferAccess for buffers used by graph passes, the scene passes included, per queue. RenderGraph::textureAccess tracks textures across queues only. Only the barriers between dispatches inside one pass are placed by the pass itself. |
| Discard | UNDEFINED as old layout | The discard flag, or UNKNOWN as the state. beginPass discards the attachments a pass clears, and keeps the ones it loads. |
| Split barriers, events | possible | None. |
| Queues | semaphores, ownership transfers | A graphics queue, and a compute queue when EngineConfig::asyncCompute is on and the GPU has one. Timeline fence waits between them, and concurrent sharing instead of ownership transfers (P11). The frames' uploads go on the graphics queue and need no semaphore there: copyBuffers brackets them with all-commands barriers. The loads' copies go on a transfer queue (EngineConfig::transferQueue); a frame waits only for load values the CPU saw reached, and a texture filled there is released by the transfer queue and acquired by the graphics queue (transfer queues). |
| Host reads | barrier to host, fence, invalidate | All three: COMPUTE → HOST at the end of the frame, or of its last compute batch with async compute, the slot's fences, and readBuffer invalidates the range. A readback has its own copy → host barrier, and takeReadback waits for the fence of the frame that copied it (readbacks). |
| Host-side layout change | — | Loaded textures use host image copy where it costs the GPU nothing for their format (on lavapipe, not on the RTX 3060): fillTexture transitions and fills them on the CPU, with no GPU barrier. The others go through the staging ring, with the barriers of copyToTextures. |
Where it lives in code
| What | Where |
|---|---|
PipelineStage, TextureUsage | include/rasm/render/resource.h |
| Stage and access masks, image scopes, upload barriers, compute-queue barriers | toVkStageMask, getSrcScope, getDstScope, copyBuffers, copyToTextures, copyFromTexture, aliasingBarrier, fitToComputeQueue in src/rhi/vulkan/vulkanCommandBuffer.cpp |
| Fence waits of a submit | VulkanQueue::submit in src/rhi/vulkan/vulkanQueue.cpp; RenderContext::submit in src/rhi/renderContext.cpp |
| Texture state tracking | TextureStates in src/rhi/textureStates.cpp |
| Checks: no barrier inside a pass | RenderContext::memoryBarrier, transitionImageLayout in src/rhi/renderContext.cpp |
| Graph barriers and queue waits | RenderGraph::bufferBarrier, RenderGraph::waitForOtherQueue, RenderGraph::textureWaits in src/renderer/renderGraph.cpp; Renderer::waitForQueue in src/renderer/renderer.cpp |
| Barriers inside the culling and Hi-Z passes | recordSceneCulling, recordHiz in src/renderer/gpuScene.cpp |
| Pass and frame transitions | Renderer::beginPass, endPass, endFrame in src/renderer/renderer.cpp |
- Use synchronization2 (
vkCmdPipelineBarrier2) and dynamic rendering; no render pass objects. - No barrier, dispatch or layout change between
beginRenderingandendRendering;RenderContextchecks it. - A texture's layout changes only through
transitionImageLayout, soTexture::statestays true. A frame that is not submitted callsdiscardRecording. - A new
TextureUsagethat textures move into needs a source and a destination scope ingetSrcScopeandgetDstScope. - A graph pass declares every buffer and texture it uses, or the graph cannot place its barriers or its waits across queues.
- Waits between queues stay at all commands, because the first commands of a batch are often layout transitions.
- Test with
enableValidationandenableSyncValidationon (orverify.py --sync); a change that adds validation messages is not done.
With async compute every resource is shared by both queue families instead of moving ownership (P11); only a texture a load fills on the transfer queue moves ownership, once (transfer queues). The render graph places barriers and aliases transient render targets, but does not cull passes (D9). Aliasing needs its own global barrier: see Transient memory and aliasing.
Further reading
- The Khronos Group, Vulkan Specification: the chapter "Synchronization and Cache Control".
- The Khronos Group, Synchronization Examples, on the Vulkan-Docs wiki: barriers for common cases.
- Hans-Kristian Arntzen, Yet another blog explaining Vulkan synchronization (2019).
- Matthäus Chajdas, Vulkan barriers explained, GPUOpen (2017).
- Microsoft, Direct3D 12 documentation: "Using resource barriers to synchronize resource states", and "Enhanced barriers".