blob: fd9d99c13719f932c8a6cad9e0f92ceddc500145 [file] [view]
# Buffer Map Write With Read-Only Usages
## Overview
By default, WebGPU only allows `wgpu::BufferUsage::MapWrite` to be combined with
`wgpu::BufferUsage::CopySrc`. Updating a uniform, vertex, index, indirect or storage buffer
through mapping requires a separate staging buffer and an explicit copy.
The feature `wgpu::FeatureName::BufferMapWriteWithReadOnlyUsages` relaxes this restriction:
- It introduces a new `wgpu::BufferUsage::ReadOnlyStorage` buffer usage for buffers that are only
read (never written) as storage buffers by shaders.
- It allows `wgpu::BufferUsage::MapWrite` to be combined with GPU read-only usages:
`wgpu::BufferUsage::CopySrc`, `wgpu::BufferUsage::Vertex`, `wgpu::BufferUsage::Uniform`, and
`wgpu::BufferUsage::ReadOnlyStorage`. When texel buffers are also available, it allows
`wgpu::BufferUsage::MapWrite` to be combined with `wgpu::BufferUsage::ReadOnlyTexelBuffer` (see
[Interaction with texel buffers](#interaction-with-texel-buffers)).
`wgpu::BufferUsage::Index` and `wgpu::BufferUsage::Indirect` are not supported (see
[Notes and Limitations](#notes-and-limitations)).
With `wgpu::FeatureName::BufferMapWriteWithReadOnlyUsages`, the GPU can still only read from the
buffer and never write to it, so this feature can be supported:
- On both **cache-coherent** and **non-cache-coherent** Unified Memory Architecture (UMA)
integrated GPUs.
- On **discrete GPUs with Resizable BAR (ReBAR)**, where a host-visible device-local memory heap
allows the CPU to write directly into VRAM without a staging copy.
- On **OpenGL and OpenGL ES** on any GPU, where buffers can be mapped regardless of their usages
and the driver manages the backing memory.
- **Both with and without Dawn wire**, making it usable in both direct native applications and
client/server architectures (such as Chromium).
## Proposal
### API
- New feature name: `wgpu::FeatureName::BufferMapWriteWithReadOnlyUsages`.
- New buffer usage bit: `wgpu::BufferUsage::ReadOnlyStorage`.
Once `wgpu::FeatureName::BufferMapWriteWithReadOnlyUsages` is enabled on a device:
1. `wgpu::BufferUsage::ReadOnlyStorage` can be specified in `wgpu::BufferDescriptor::usage`, with
or without `wgpu::BufferUsage::MapWrite`. A buffer with `wgpu::BufferUsage::ReadOnlyStorage` can
be bound to bind group entries of type `wgpu::BufferBindingType::ReadOnlyStorage`, without
granting permission to bind it as a writable `wgpu::BufferBindingType::Storage` buffer.
- `wgpu::BufferUsage::Storage` continues to allow both `wgpu::BufferBindingType::Storage` and
`wgpu::BufferBindingType::ReadOnlyStorage` bindings. It does not add
`wgpu::BufferUsage::ReadOnlyStorage` to the buffer's usage: `wgpu::Buffer::GetUsage()` always
returns exactly the usages specified at creation.
- `wgpu::BufferUsage::ReadOnlyStorage` may be combined with `wgpu::BufferUsage::Storage`, in
which case it is redundant.
- Binding a buffer that has `wgpu::BufferUsage::ReadOnlyStorage` but not
`wgpu::BufferUsage::Storage` to a `wgpu::BufferBindingType::Storage` entry is a validation
error.
2. `wgpu::BufferUsage::MapWrite` can be combined with any subset of the following GPU read-only
buffer usages:
- `wgpu::BufferUsage::CopySrc`
- `wgpu::BufferUsage::Vertex`
- `wgpu::BufferUsage::Uniform`
- `wgpu::BufferUsage::ReadOnlyStorage`
- `wgpu::BufferUsage::ReadOnlyTexelBuffer`, only when texel buffers are also available on the
device (see [Interaction with texel buffers](#interaction-with-texel-buffers)).
### Interaction with texel buffers
Texel buffers are currently experimental in WebGPU and exposed through the `texel_buffers` WGSL
language feature. This proposal adds a `wgpu::BufferUsage::ReadOnlyTexelBuffer` buffer usage to
texel buffers, for buffers that are only read (never written) as texel buffers by shaders.
`wgpu::BufferUsage::ReadOnlyTexelBuffer` is part of texel buffers, not of
`wgpu::FeatureName::BufferMapWriteWithReadOnlyUsages`. It is available whenever texel buffers are
available on the device, whether or not `wgpu::FeatureName::BufferMapWriteWithReadOnlyUsages` is
enabled. It follows the same rules as `wgpu::BufferUsage::ReadOnlyStorage`, applied to texel
buffers:
- A `wgpu::TexelBufferView` can be created from a buffer with
`wgpu::BufferUsage::ReadOnlyTexelBuffer`, and bound to bind group entries whose
`wgpu::TexelBufferBindingLayout::access` is `wgpu::TexelBufferAccess::ReadOnly`.
- `wgpu::BufferUsage::TexelBuffer` continues to allow both `wgpu::TexelBufferAccess::ReadOnly` and
`wgpu::TexelBufferAccess::ReadWrite` bindings, and does not add
`wgpu::BufferUsage::ReadOnlyTexelBuffer` to `wgpu::Buffer::GetUsage()`.
- `wgpu::BufferUsage::ReadOnlyTexelBuffer` may be combined with `wgpu::BufferUsage::TexelBuffer`, in
which case it is redundant.
- Binding a texel buffer view whose buffer has `wgpu::BufferUsage::ReadOnlyTexelBuffer` but not
`wgpu::BufferUsage::TexelBuffer` to an entry with `wgpu::TexelBufferAccess::ReadWrite` is a
validation error.
Combining `wgpu::BufferUsage::MapWrite` with `wgpu::BufferUsage::ReadOnlyTexelBuffer` requires both
texel buffers and `wgpu::FeatureName::BufferMapWriteWithReadOnlyUsages` to be available on the
device.
### Example
#### Example Usage
```c++
wgpu::BufferDescriptor descriptor;
descriptor.size = size;
// MapWrite can be combined with GPU read-only usages such as ReadOnlyStorage.
descriptor.usage = wgpu::BufferUsage::MapWrite | wgpu::BufferUsage::ReadOnlyStorage;
wgpu::Buffer storageBuffer = device.CreateBuffer(&descriptor);
wgpu::Future future = storageBuffer.MapAsync(wgpu::MapMode::Write, 0, size,
wgpu::CallbackMode::WaitAnyOnly,
[storageBuffer, data, size](wgpu::MapAsyncStatus status, wgpu::StringView) {
if (status == wgpu::MapAsyncStatus::Success) {
memcpy(storageBuffer.GetMappedRange(), data, size);
storageBuffer.Unmap();
}
});
// The buffer must be unmapped before it is used in a submitted command buffer.
instance.WaitAny(future, UINT64_MAX);
// Bind the buffer as a read-only storage buffer in a bind group.
wgpu::BindGroupLayoutEntry bglEntry;
bglEntry.binding = 0;
bglEntry.visibility = wgpu::ShaderStage::Compute;
bglEntry.buffer.type = wgpu::BufferBindingType::ReadOnlyStorage;
wgpu::BindGroupLayoutDescriptor bglDesc;
bglDesc.entryCount = 1;
bglDesc.entries = &bglEntry;
wgpu::BindGroupLayout bgl = device.CreateBindGroupLayout(&bglDesc);
wgpu::BindGroupEntry bgEntry;
bgEntry.binding = 0;
bgEntry.buffer = storageBuffer;
bgEntry.offset = 0;
bgEntry.size = size;
wgpu::BindGroupDescriptor bgDesc;
bgDesc.layout = bgl;
bgDesc.entryCount = 1;
bgDesc.entries = &bgEntry;
wgpu::BindGroup bindGroup = device.CreateBindGroup(&bgDesc);
```
## Target API Support
The table below summarizes the requirements and backing memory to enable this feature on D3D11,
D3D12, Metal, Vulkan, and OpenGL/OpenGL ES:
| Backend | Requirement to enable | Backing memory for `MapWrite` + GPU read-only buffers |
| ------- | --------------------- | ----------------------------------------------------- |
| Direct3D 12 | `D3D12_FEATURE_DATA_ARCHITECTURE.UMA == TRUE`, **or** discrete GPU with Resizable BAR (`D3D12_FEATURE_DATA_D3D12_OPTIONS16.GPUUploadHeapSupported == TRUE`). | On UMA: custom heap (`D3D12_HEAP_TYPE_CUSTOM`) in `D3D12_MEMORY_POOL_L0` with `D3D12_CPU_PAGE_PROPERTY_WRITE_BACK` (cache-coherent UMA) or `D3D12_CPU_PAGE_PROPERTY_WRITE_COMBINE` (non-cache-coherent UMA). On dGPUs with Resizable BAR: GPU Upload Heap (`D3D12_HEAP_TYPE_GPU_UPLOAD`). |
| Metal | `[MTLDevice hasUnifiedMemory] == YES`. | `MTLResourceStorageModeShared` allocation with `MTLResourceCPUCacheModeWriteCombined`; no `didModifyRange:` synchronization needed. |
| Vulkan | A memory type exposing `VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT \| VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT \| VK_MEMORY_PROPERTY_HOST_COHERENT_BIT` backed by a sufficiently large heap (UMA, or dGPU with Resizable BAR exposing full VRAM rather than a small 256 MB BAR aperture). | A `DEVICE_LOCAL \| HOST_VISIBLE \| HOST_COHERENT` (write-combined) memory type; `VK_MEMORY_PROPERTY_HOST_CACHED_BIT` is not required. |
| Direct3D 11 | `D3D11_FEATURE_DATA_D3D11_OPTIONS2.UnifiedMemoryArchitecture == TRUE`, and `D3D11_FEATURE_DATA_D3D11_OPTIONS.MapNoOverwriteOnDynamicBufferSRV == TRUE` and `MapNoOverwriteOnDynamicConstantBuffer == TRUE`. | `D3D11_USAGE_DYNAMIC` buffer with `D3D11_CPU_ACCESS_WRITE`, mapped with `D3D11_MAP_WRITE_NO_OVERWRITE`. `Uniform` usage is backed by a separate dynamic constant buffer. |
| OpenGL / OpenGL ES | None. All GL buffer objects can be mapped with `glMapBufferRange()` regardless of how they are bound, so the existing `MapWrite` path (`GL_MAP_WRITE_BIT \| GL_MAP_UNSYNCHRONIZED_BIT`) works unchanged. | A regular buffer object created with `glBufferData()`; the driver decides where the memory lives. A `GL_DYNAMIC_DRAW` usage hint can be passed for `MapWrite` buffers. Zero-copy is not guaranteed: the driver may map a staging copy and upload it on `glUnmapBuffer()`. |
## Dawn wire compatibility
In Dawn wire, mapping a `MapWrite` buffer gives the client access to a client-side memory buffer
(via `MemoryTransferService::MemoryHandle`). When the client calls `Unmap()`, the written data is
flushed over the wire to the server-side buffer.
If a `MapWrite` buffer were also allowed to have GPU-writable usages (such as `CopyDst`, `Storage`,
`TexelBuffer` or `QueryResolve`), GPU commands executed on the server could modify the buffer's
contents without the client knowing. On a subsequent `MapAsync(wgpu::MapMode::Write)` call, the
client's memory would no longer match the server's buffer contents, breaking data consistency
between client and server.
With `BufferMapWriteWithReadOnlyUsages`, a `MapWrite` buffer can only be combined with GPU
read-only usages:
- The CPU (wire client) is the sole writer to the buffer.
- No GPU operation (shader writes, buffer copies, query resolves, `Queue::WriteBuffer` or
`CommandEncoder::ClearBuffer`) can modify the buffer on the server.
- Every modification originates from the client and is flushed to the server on `Unmap()`.
As a result, the wire client and wire server always have the exact same data, making this feature
safe to expose and use over Dawn wire.
### Zero-copy with triple mapping
This feature is also compatible with zero-copy "triple mapping" through the import transfer buffer
path. On that path, the shared memory that backs the wire transfer buffer (between the client and
server processes) is imported into the device as the buffer's backing memory (for example with
`wgpu::FeatureName::SharedBufferMemoryHostPointer` or `wgpu::FeatureName::HostMappedPointer`). The
same physical memory is then mapped three times: in the client process, in the server process, and
on the GPU. The client writes through `GetMappedRange()` directly into GPU-visible memory, and
`Unmap()` does not need to copy the data into a separate server-side buffer.
This works because the GPU never writes to the buffer:
- The transfer buffer always holds the current contents of the buffer, so nothing has to be copied
back to the client before a later `MapAsync(wgpu::MapMode::Write)`.
- The CPU and GPU never access the memory at the same time: the client only writes while the
buffer is mapped, and `MapAsync()` completes only after all previously submitted GPU work that
uses the buffer has finished.
## Comparison with Related Features
| Feature | Allowed usages with `MapRead` | Allowed usages with `MapWrite` | Hardware support | Dawn wire support |
| ------- | ----------------------------- | ------------------------------ | ---------------- | ----------------- |
| Core WebGPU | `CopyDst` | `CopySrc` | All GPUs | Yes |
| `BufferMapWriteWithReadOnlyUsages` | `CopyDst` | GPU read-only usages (`CopySrc`, `Vertex`, `Uniform`, `ReadOnlyStorage`, and `ReadOnlyTexelBuffer` when texel buffers are available) | UMA (coherent & non-coherent) and dGPUs with Resizable BAR | Yes |
| [`BufferMapWriteExtendedUsages`](./buffer_map_write_extended_usages.md) | `CopyDst` | All usages except `MapRead` | UMA (coherent & non-coherent) | No |
| [`BufferMapExtendedUsages`](./buffer_map_extended_usages.md) | All usages | All usages | Cache-coherent UMA | No |
`wgpu::FeatureName::BufferMapWriteExtendedUsages` and `wgpu::FeatureName::BufferMapExtendedUsages`
allow strictly more usage combinations with `wgpu::BufferUsage::MapWrite` than this feature, so:
- Enabling `wgpu::FeatureName::BufferMapWriteExtendedUsages` or
`wgpu::FeatureName::BufferMapExtendedUsages` on a device implicitly enables
`wgpu::FeatureName::BufferMapWriteWithReadOnlyUsages`, including the
`wgpu::BufferUsage::ReadOnlyStorage` usage and, when texel buffers are available, the
combination of `wgpu::BufferUsage::MapWrite` and `wgpu::BufferUsage::ReadOnlyTexelBuffer`.
`wgpu::Device::HasFeature()` returns `true` for the implicitly enabled feature.
- Any adapter that supports `wgpu::FeatureName::BufferMapWriteExtendedUsages` or
`wgpu::FeatureName::BufferMapExtendedUsages` also reports support for
`wgpu::FeatureName::BufferMapWriteWithReadOnlyUsages`, so it can be requested directly.
## Notes and Limitations
- `MapWrite` cannot be combined with `wgpu::BufferUsage::Index` or `wgpu::BufferUsage::Indirect`,
even though the GPU only reads these buffers from the application's point of view. WebGPU
implementations must validate the contents of index and indirect buffers before the GPU
consumes them. Depending on the implementation (for example in WebKit and Firefox), this
validation may rewrite the buffer contents in place, or rely on CPU-side shadow copies or cached
validation results that must be invalidated whenever the contents change. Both are incompatible
with this feature: in-place rewrites would make the GPU a writer of a `MapWrite` buffer and break
the client/server consistency guarantee described in
[Dawn wire compatibility](#dawn-wire-compatibility). These usages may be added in the future if
all implementations can validate index and indirect buffers without writing to them or depending
on CPU-side knowledge of their contents.
- `wgpu::BufferUsage::ReadOnlyStorage` does not depend on any hardware capability. It could be
proposed as a core WebGPU buffer usage. If it becomes part of core WebGPU,
`wgpu::FeatureName::BufferMapWriteWithReadOnlyUsages` would only need to allow combining
`wgpu::BufferUsage::MapWrite` with it, rather than introduce it. This is the same approach used
for `wgpu::BufferUsage::ReadOnlyTexelBuffer`, which is introduced by texel buffers (see
[Interaction with texel buffers](#interaction-with-texel-buffers)).
- This proposal keeps the semantics of `wgpu::BufferUsage::Storage` unchanged for backward
compatibility: it still allows both `wgpu::BufferBindingType::Storage` and
`wgpu::BufferBindingType::ReadOnlyStorage` bindings, and `wgpu::Buffer::GetUsage()` does not
implicitly report `wgpu::BufferUsage::ReadOnlyStorage`. As a result, two usages
(`wgpu::BufferUsage::Storage` and `wgpu::BufferUsage::ReadOnlyStorage`) allow
`wgpu::BufferBindingType::ReadOnlyStorage` bindings.
- If `wgpu::BufferUsage::ReadOnlyStorage` is proposed as a core usage, the WebGPU working group
may consider alternatives that are breaking changes to existing WebGPU content:
- Making `wgpu::BufferUsage::Storage` imply `wgpu::BufferUsage::ReadOnlyStorage`, so that
`GPUBuffer.usage` (`wgpu::Buffer::GetUsage()`) reports both bits for buffers created with
`wgpu::BufferUsage::Storage`. This changes an observable value, which can break applications
that compare `GPUBuffer.usage` against the usages they specified or reuse it to create other
buffers.
- Requiring `wgpu::BufferUsage::ReadOnlyStorage` for `wgpu::BufferBindingType::ReadOnlyStorage`
bindings, so that `wgpu::BufferUsage::Storage` only allows
`wgpu::BufferBindingType::Storage` bindings. This causes validation errors in existing
applications that bind `wgpu::BufferUsage::Storage` buffers as read-only storage buffers.
When used without Dawn wire:
- Reading from the mapped range on CPU (for example via `memcpy` out of `GetMappedRange()`) may be
extremely slow on integrated GPUs with non-cache-coherent UMA, or through PCIe on discrete GPUs
with ReBAR.
- Write the mapped range sequentially for the best write throughput on integrated GPUs with
non-cache-coherent UMA, or through PCIe on discrete GPUs with ReBAR.
When used with Dawn wire, `GetMappedRange()` returns client-side memory, so reading from the mapped
range on the client is not affected by the limitations above.