Eagerly initialize buffer tails

(cherry picked from commit bcc59481c9)
This commit is contained in:
Andy Leiserson committed 2026-09-01 12:34:12 -07:00
1 parent 0a7ad126dd
commit b9f2bb9071
5 files changed
+438 -23

No files matched your search

+1
View File
@@ -68,6 +68,7 @@ webgpu:api,validation,texture,destroy:submit_a_destroyed_texture_as_attachment:*
webgpu:shader,execution,expression,call,builtin,atan2:f16:* // dx12, fails with dxc, passes with fxc, https://github.com/gfx-rs/wgpu/issues/9179
webgpu:shader,execution,expression,call,builtin,textureDimensions:* // dx12, https://github.com/gfx-rs/wgpu/issues/9541
webgpu:shader,execution,expression,call,builtin,textureNumSamples:* // dx12, fails intermittently on WARP < 1.0.17
webgpu:shader,execution,robust_access_vertex:vertex_buffer_access:* // metal paravirt GPU only, https://github.com/gfx-rs/wgpu/issues/8023
webgpu:shader,validation,decl,let:* // texture/sampler let
webgpu:shader,validation,decl,override:* // 93%, unrestricted_pointer_parameters not implemented, https://github.com/gfx-rs/wgpu/issues/5158
+311
View File
@@ -6,6 +6,7 @@
use core::num::NonZeroU64;
use wgpu::util::DeviceExt as _;
use wgpu::*;
use wgpu_test::{
gpu_test, image::ReadbackBuffers, FailureCase, GpuTestConfiguration, GpuTestInitializer,
@@ -66,6 +67,10 @@ pub fn all_tests(vec: &mut Vec<GpuTestInitializer>) {
COPY_TEXTURE_TO_TEXTURE_3D_SOURCE_ORIGIN_Z_UNINIT,
COPY_BUFFER_TO_TEXTURE_3D_DEST_ORIGIN_Z_PARTIAL,
COPY_TEXTURE_TO_TEXTURE_3D_DEST_ORIGIN_Z_PARTIAL,
VERTEX_BUFFER_TAIL_INIT_PLAIN,
VERTEX_BUFFER_TAIL_INIT_MAP_WRITE,
VERTEX_BUFFER_TAIL_INIT_MAPPED_AT_CREATION,
VERTEX_BUFFER_TAIL_INIT_MAP_WRITE_MAPPED_AT_CREATION,
]);
}
@@ -1245,3 +1250,309 @@ async fn check_3d_copy_dest_init(ctx: &TestingContext, method: WriteMethod) {
.assert_buffer_contents(ctx, &expected)
.await;
}
// Tests that the padding (tail) at the end of a buffer allocation is
// zero-initialized.
//
// The test is effective mainly on Vulkan, where it can exploit the fact that
// `vkCmdBindVertexBuffers` does not specify the end of the binding, so a vertex
// shader can fetch a vertex whose bytes lie in the tail. Draw-time bounds
// checking does not limit the vertex count for indexed draws, so we use an
// indexed draw whose largest index points at the buffer tail.
const VB_TAIL_VERTEX_STRIDE: u64 = 4;
const VB_TAIL_VISIBLE_VERTS: u32 = 4;
const VB_TAIL_SHADER: &str = "
@group(0) @binding(0) var<storage, read_write> result: array<u32>;
@vertex
fn vs_main(@builtin(vertex_index) ix: u32, @location(0) value: u32) -> @builtin(position) vec4f {
result[ix] = value;
return vec4f(0.0, 0.0, 0.0, 1.0);
}
@fragment
fn fs_main() -> @location(0) vec4f {
return vec4f(0.0, 0.0, 0.0, 0.0);
}
";
// `MAP_WRITE` + `VERTEX` requires `MAPPABLE_PRIMARY_BUFFERS`.
#[apply(gpu_test!)]
static VERTEX_BUFFER_TAIL_INIT_PLAIN: GpuTestConfiguration = GpuTestConfiguration::new()
.parameters(
TestParameters::default()
.features(Features::VERTEX_WRITABLE_STORAGE)
.limits(Limits::downlevel_defaults()),
)
.run_async(|ctx| async move {
for app_writes in [false, true] {
check_vertex_buffer_tail_init(&ctx, false, false, app_writes).await;
}
});
#[apply(gpu_test!)]
static VERTEX_BUFFER_TAIL_INIT_MAP_WRITE: GpuTestConfiguration = GpuTestConfiguration::new()
.parameters(
TestParameters::default()
.features(Features::VERTEX_WRITABLE_STORAGE | Features::MAPPABLE_PRIMARY_BUFFERS)
.limits(Limits::downlevel_defaults()),
)
.run_async(|ctx| async move {
for app_writes in [false, true] {
check_vertex_buffer_tail_init(&ctx, true, false, app_writes).await;
}
});
#[apply(gpu_test!)]
static VERTEX_BUFFER_TAIL_INIT_MAPPED_AT_CREATION: GpuTestConfiguration =
GpuTestConfiguration::new()
.parameters(
TestParameters::default()
.features(Features::VERTEX_WRITABLE_STORAGE)
.limits(Limits::downlevel_defaults()),
)
.run_async(|ctx| async move {
for app_writes in [false, true] {
check_vertex_buffer_tail_init(&ctx, false, true, app_writes).await;
}
});
#[apply(gpu_test!)]
static VERTEX_BUFFER_TAIL_INIT_MAP_WRITE_MAPPED_AT_CREATION: GpuTestConfiguration =
GpuTestConfiguration::new()
.parameters(
TestParameters::default()
.features(Features::VERTEX_WRITABLE_STORAGE | Features::MAPPABLE_PRIMARY_BUFFERS)
.limits(Limits::downlevel_defaults()),
)
.run_async(|ctx| async move {
for app_writes in [false, true] {
check_vertex_buffer_tail_init(&ctx, true, true, app_writes).await;
}
});
async fn check_vertex_buffer_tail_init(
ctx: &TestingContext,
map_write: bool,
mapped_at_creation: bool,
app_writes: bool,
) {
let case_desc = format!(
"map_write={map_write}, mapped_at_creation={mapped_at_creation}, app_writes={app_writes}"
);
let vb_size = VB_TAIL_VISIBLE_VERTS as u64 * VB_TAIL_VERTEX_STRIDE;
let vertex_data: Vec<u32> = (0..VB_TAIL_VISIBLE_VERTS)
.map(|i| 0xA0A0_0000 + i)
.collect();
let vertex_data_bytes: &[u8] = bytemuck::cast_slice(&vertex_data);
// Add `COPY_DST` if the application needs it to write via the queue;
// it does not affect which tail-init path is taken.
let mut usage = BufferUsages::VERTEX;
if map_write {
usage |= BufferUsages::MAP_WRITE;
} else if app_writes && !mapped_at_creation {
usage |= BufferUsages::COPY_DST;
}
let vertex_buffer = ctx.device.create_buffer(&BufferDescriptor {
label: Some("vertex buffer under test"),
size: vb_size,
usage,
mapped_at_creation,
});
// Fill (or leave zero) the application-visible portion of the buffer.
if mapped_at_creation {
// The buffer is mapped at creation; write into it if desired, then unmap.
if app_writes {
let mut view = vertex_buffer.slice(..).get_mapped_range_mut().unwrap();
view.copy_from_slice(vertex_data_bytes);
}
vertex_buffer.unmap();
} else if app_writes {
if map_write {
vertex_buffer.slice(..).map_async(MapMode::Write, |_| ());
ctx.async_poll(PollType::wait_indefinitely()).await.unwrap();
{
let mut view = vertex_buffer.slice(..).get_mapped_range_mut().unwrap();
view.copy_from_slice(vertex_data_bytes);
}
vertex_buffer.unmap();
} else {
ctx.queue.write_buffer(&vertex_buffer, 0, vertex_data_bytes);
}
}
// Index buffer whose largest index (`VB_TAIL_VISIBLE_VERTS`) points one vertex
// past the visible area, into the tail.
let indices: Vec<u32> = (0..=VB_TAIL_VISIBLE_VERTS).collect();
let index_buffer = ctx.device.create_buffer_init(&util::BufferInitDescriptor {
label: Some("index buffer"),
contents: bytemuck::cast_slice(&indices),
usage: BufferUsages::INDEX,
});
// The vertex shader writes each fetched value into this buffer at `vertex_index`.
let result_len = indices.len();
let result_buffer = ctx.device.create_buffer(&BufferDescriptor {
label: Some("result buffer"),
size: (result_len * core::mem::size_of::<u32>()) as u64,
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
let readback = ctx.device.create_buffer(&BufferDescriptor {
label: Some("result readback"),
size: result_buffer.size(),
usage: BufferUsages::COPY_DST | BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let output_texture = ctx.device.create_texture(&TextureDescriptor {
label: Some("unused render attachment"),
size: Extent3d {
width: 1,
height: 1,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: TextureDimension::D2,
format: TextureFormat::Rgba8UnormSrgb,
usage: TextureUsages::RENDER_ATTACHMENT,
view_formats: &[],
});
let output_view = output_texture.create_view(&Default::default());
let shader = ctx.device.create_shader_module(ShaderModuleDescriptor {
label: Some("vertex buffer tail shader"),
source: ShaderSource::Wgsl(VB_TAIL_SHADER.into()),
});
let bgl = ctx
.device
.create_bind_group_layout(&BindGroupLayoutDescriptor {
label: None,
entries: &[BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::VERTEX,
ty: BindingType::Buffer {
ty: BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
});
let pipeline_layout = ctx
.device
.create_pipeline_layout(&PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
});
let pipeline = ctx
.device
.create_render_pipeline(&RenderPipelineDescriptor {
label: Some("vertex buffer tail pipeline"),
layout: Some(&pipeline_layout),
vertex: VertexState {
module: &shader,
entry_point: Some("vs_main"),
buffers: &[Some(VertexBufferLayout {
array_stride: VB_TAIL_VERTEX_STRIDE,
step_mode: VertexStepMode::Vertex,
attributes: &[VertexAttribute {
format: VertexFormat::Uint32,
offset: 0,
shader_location: 0,
}],
})],
compilation_options: Default::default(),
},
fragment: Some(FragmentState {
module: &shader,
entry_point: Some("fs_main"),
targets: &[Some(output_texture.format().into())],
compilation_options: Default::default(),
}),
primitive: PrimitiveState {
topology: PrimitiveTopology::PointList,
..Default::default()
},
depth_stencil: None,
multisample: MultisampleState::default(),
multiview_mask: None,
cache: None,
});
let bind_group = ctx.device.create_bind_group(&BindGroupDescriptor {
label: None,
layout: &bgl,
entries: &[BindGroupEntry {
binding: 0,
resource: result_buffer.as_entire_binding(),
}],
});
let mut encoder = ctx
.device
.create_command_encoder(&CommandEncoderDescriptor { label: None });
{
let mut pass = encoder.begin_render_pass(&RenderPassDescriptor {
label: Some("vertex buffer tail pass"),
color_attachments: &[Some(RenderPassColorAttachment {
view: &output_view,
depth_slice: None,
resolve_target: None,
ops: Operations {
load: LoadOp::Clear(Color::default()),
store: StoreOp::Store,
},
})],
..Default::default()
});
pass.set_pipeline(&pipeline);
pass.set_bind_group(0, &bind_group, &[]);
pass.set_vertex_buffer(0, vertex_buffer.slice(..));
pass.set_index_buffer(index_buffer.slice(..), IndexFormat::Uint32);
pass.draw_indexed(0..result_len as u32, 0, 0..1);
}
encoder.copy_buffer_to_buffer(&result_buffer, 0, &readback, 0, result_buffer.size());
ctx.queue.submit([encoder.finish()]);
let data = map_and_read(ctx, &readback).await;
let result: Vec<u32> = bytemuck::cast_slice(&data).to_vec();
// Visible vertices should match vertex data if the application wrote it, or
// be zero if not.
for i in 0..VB_TAIL_VISIBLE_VERTS as usize {
let got = result[i];
if app_writes {
assert_eq!(
got, vertex_data[i],
"did not read expected non-zero data in visible area \
(case: {case_desc}, vertex {i}): expected 0x{:08x}, got 0x{got:08x}",
vertex_data[i],
);
} else {
assert_eq!(
got, 0,
"did not read expected zero (uninitialized) data in visible area \
(case: {case_desc}, vertex {i}): got 0x{got:08x}",
);
}
}
// Tail vertex: never written by the application, must be zero-initialized.
let tail = result[VB_TAIL_VISIBLE_VERTS as usize];
assert_eq!(
tail, 0,
"did not read expected zero data in padding area (case: {case_desc}): got 0x{tail:08x}",
);
}
+32
View File
@@ -444,6 +444,38 @@ impl PendingWrites {
.push(TempResource::StagingBuffer(buffer));
}
pub fn clear_buffer(
&mut self,
device: &Arc<Device>,
buffer: &Arc<Buffer>,
range: core::ops::Range<wgt::BufferAddress>,
snatch_guard: &SnatchGuard,
) -> Result<(), QueueWriteError> {
let barriers = {
let mut trackers = device.trackers.lock();
trackers
.buffers
.set_single(buffer, wgt::BufferUses::COPY_DST)
.map(|pending| pending.into_hal(buffer, snatch_guard))
};
let dst_raw = buffer.try_raw(snatch_guard)?;
let encoder = self.activate();
unsafe {
encoder.transition_buffers(barriers.as_slice());
encoder.clear_buffer(dst_raw, range.clone());
}
self.insert_buffer(buffer);
// Ensure the overwritten bytes are marked as initialized so
// they don't need to be nulled prior to mapping or binding.
buffer.initialization_status.write().drain(range);
Ok(())
}
fn pre_submit(
&mut self,
command_allocator: &CommandAllocator,
+80 -14
View File
@@ -1077,25 +1077,28 @@ impl Device {
usage |= wgt::BufferUses::COPY_DST;
}
// The great thing about buffer sizes is there are so many to choose from!
// - The application may request an arbitrary byte-aligned size.
// - We add an extra byte if it's a vertex buffer so that we can simulate binding an
// empty range at the end of the buffer, which Vulkan does not natively allow.
// - The overall buffer size must be a non-zero multiple of 4.
// Because initialization operates at multiples of 4 bytes, and initialization
// tracking will never determine that it is necessary to initialize a region outside
// the application-visible range, we eagerly zero-initialize anything beyond that.
let actual_size = if desc.size == 0 {
wgt::COPY_BUFFER_ALIGNMENT
} else if desc.usage.contains(wgt::BufferUsages::VERTEX) {
// Bumping the size by 1 so that we can bind an empty range at the
// end of the buffer.
desc.size + 1
} else {
desc.size
};
let clear_remainder = actual_size % wgt::COPY_BUFFER_ALIGNMENT;
let aligned_size = if clear_remainder != 0 {
actual_size + wgt::COPY_BUFFER_ALIGNMENT - clear_remainder
} else {
actual_size
};
let actual_size = align_to(actual_size, wgt::COPY_BUFFER_ALIGNMENT);
let tail_start = desc.size & !(wgt::COPY_BUFFER_ALIGNMENT - 1);
debug_assert!(actual_size - 4 <= tail_start);
let hal_desc = hal::BufferDescriptor {
label: desc.label.to_hal(self.instance_flags),
size: aligned_size,
size: actual_size,
usage,
memory_flags: hal::MemoryFlags::empty(),
};
@@ -1126,7 +1129,7 @@ impl Device {
size: desc.size,
initialization_status: RwLock::new(
rank::BUFFER_INITIALIZATION_STATUS,
BufferInitTracker::new(aligned_size),
BufferInitTracker::new(tail_start),
),
map_state: Mutex::new(rank::BUFFER_MAP_STATE, resource::BufferMapState::Idle),
label: desc.label.to_string(),
@@ -1138,10 +1141,64 @@ impl Device {
let buffer = Arc::new(buffer);
let init_buffer_tail = |buffer, snatch_guard| {
let mapping = map_buffer(
buffer,
tail_start,
actual_size - tail_start,
HostMap::Write,
snatch_guard,
)?;
let raw = buffer
.raw(snatch_guard)
.expect("newly-created buffer cannot be destroyed");
unsafe {
// SAFETY: The buffer tail is valid and aligned.
mapping.ptr.cast::<u32>().as_ptr().write(0);
if !mapping.is_coherent {
#[allow(clippy::single_range_in_vec_init)]
self.raw()
.flush_mapped_ranges(raw, &[tail_start..actual_size]);
}
self.raw().unmap_buffer(raw);
}
Ok::<_, resource::CreateBufferError>(())
};
let buffer_use = if !desc.mapped_at_creation {
if tail_start == actual_size {
// No tail init necessary
} else if desc.usage.contains(wgt::BufferUsages::MAP_WRITE) {
// Tail init by mapping
let snatch_guard = self.snatchable_lock.read();
init_buffer_tail(&buffer, &snatch_guard)?;
} else if let Some(queue) = self.get_queue() {
// Schedule tail init in pending writes
let snatch_guard = self.snatchable_lock.read();
let mut pending_writes = queue.pending_writes.lock();
self.trackers
.lock()
.buffers
.insert_single(&buffer, wgt::BufferUses::COPY_DST);
pending_writes.clear_buffer(
self,
&buffer,
tail_start..actual_size,
&snatch_guard,
)?;
return Ok(buffer);
} else {
// Queue is gone, buffer will not be used.
}
wgt::BufferUses::empty()
} else if desc.usage.contains(wgt::BufferUsages::MAP_WRITE) {
// buffer is mappable, so we are just doing that at start
// Mapped-at-creation with MAP_WRITE. Tail init by mapping, then map the
// application-visible portion of the buffer. Don't do both in the same
// mapping, because the application shouldn't see the tail.
let snatch_guard = self.snatchable_lock.read();
if tail_start != actual_size {
init_buffer_tail(&buffer, &snatch_guard)?;
}
let map_size = buffer.size;
let mapping = if map_size == 0 {
hal::BufferMapping {
@@ -1149,9 +1206,9 @@ impl Device {
is_coherent: true,
}
} else {
let snatch_guard: SnatchGuard = self.snatchable_lock.read();
map_buffer(&buffer, 0, map_size, HostMap::Write, &snatch_guard)?
};
drop(snatch_guard);
*buffer.map_state.lock() = resource::BufferMapState::Active {
mapping,
range: 0..map_size,
@@ -1159,18 +1216,27 @@ impl Device {
};
wgt::BufferUses::MAP_WRITE
} else {
// Mapped-at-creation without MAP_WRITE. Create and zero-initialize a staging
// buffer for the entire buffer (including tail). It is okay to use a single
// mapping, `get_mapped_range` will still only expose the application-visible
// range. The application could corrupt the tail with an out-of-bounds write,
// which may cause problems for its shaders if they read out-of-bounds, but
// won't cause problems in wgpu.
let mut staging_buffer =
StagingBuffer::new(self, wgt::BufferSize::new(aligned_size).unwrap())?;
StagingBuffer::new(self, wgt::BufferSize::new(actual_size).unwrap())?;
// Zero initialize memory and then mark the buffer as initialized
// (it's guaranteed that this is the case by the time the buffer is usable)
staging_buffer.write_zeros();
buffer.initialization_status.write().drain(0..aligned_size);
buffer.initialization_status.write().drain(0..actual_size);
*buffer.map_state.lock() = resource::BufferMapState::Init { staging_buffer };
wgt::BufferUses::COPY_DST
};
// If we didn't add the buffer to the tracker already for initialization via
// PendingWrites, do so now.
self.trackers
.lock()
.buffers
+14 -9
View File
@@ -938,10 +938,12 @@ impl Buffer {
let staging_buffer = staging_buffer.flush();
if let Some(queue) = device.get_queue() {
let region = wgt::BufferSize::new(self.size).map(|size| hal::BufferCopy {
// Copy the entire staging buffer, including any
// zero-initialized padding.
let region = Some(hal::BufferCopy {
src_offset: 0,
dst_offset: 0,
size,
size: staging_buffer.size,
});
let transition_src = hal::BufferBarrier {
buffer: staging_buffer.raw(),
@@ -961,13 +963,13 @@ impl Buffer {
let encoder = pending_writes.activate();
unsafe {
encoder.transition_buffers(&[transition_src, transition_dst]);
if self.size > 0 {
encoder.copy_buffer_to_buffer(
staging_buffer.raw(),
raw_buf,
region.as_slice(),
);
}
// Buffers allocate at least `COPY_BUFFER_ALIGNMENT` bytes, so
// there's always something to copy here.
encoder.copy_buffer_to_buffer(
staging_buffer.raw(),
raw_buf,
region.as_slice(),
);
}
pending_writes.consume(staging_buffer);
pending_writes.insert_buffer(self);
@@ -1091,6 +1093,8 @@ pub enum CreateBufferError {
MissingFeatures(#[from] MissingFeatures),
#[error("Failed to create bind group for indirect buffer validation: {0}")]
IndirectValidationBindGroup(DeviceError),
#[error("Error initializing buffer: {0}")]
QueueWrite(#[from] queue::QueueWriteError),
}
crate::impl_resource_type!(Buffer);
@@ -1107,6 +1111,7 @@ impl WebGpuError for CreateBufferError {
Self::MissingDownlevelFlags(e) => e.webgpu_error_type(),
Self::IndirectValidationBindGroup(e) => e.webgpu_error_type(),
Self::MissingFeatures(e) => e.webgpu_error_type(),
Self::QueueWrite(e) => e.webgpu_error_type(),
Self::UnalignedSize
| Self::InvalidUsage(_)