Compare commits

...
Author SHA1 Message Date
千川白浪 e68e3ce939 Merge pull request #4 from reiasu2/fix/export-unattached-cb-deadlock
🐛 Fix snapshot save deadlock when >64 unattached surface caches are dirty
2026-12-04 13:51:42 +08:00
棠渚听潮 0427583422 🐛 Commit each unattached surface cache writeback before acquiring the next command buffer 2026-12-02 23:58:44 +08:00
@@ -529,7 +529,7 @@ use reims_vgpu_vulkan::core::platform::os::clock::MonoTime;
#[cfg(unix)] #[cfg(unix)]
use reims_vgpu_vulkan::core::platform::resource::SurfaceHandle; use reims_vgpu_vulkan::core::platform::resource::SurfaceHandle;
use reims_vgpu_vulkan::core::platform::resource::{Buffer as _, MemoryFor}; use reims_vgpu_vulkan::core::platform::resource::{Buffer as _, MemoryFor};
use reims_vgpu_vulkan::core::platform::types::NsRange; use reims_vgpu_vulkan::core::platform::types::{CommandBufferStatus, NsRange};
use reims_vgpu_vulkan::core::platform::values::{PagesPlane, TextureDesc}; use reims_vgpu_vulkan::core::platform::values::{PagesPlane, TextureDesc};
use reims_vgpu_vulkan::core::platform::{Handle, Platform}; use reims_vgpu_vulkan::core::platform::{Handle, Platform};
use reims_vgpu_vulkan::core::raise::{OnFault, Raise, RaiseResult, refusals}; use reims_vgpu_vulkan::core::raise::{OnFault, Raise, RaiseResult, refusals};
@@ -8366,6 +8366,25 @@ impl<P: Platform> Caches<P> {
pub(crate) fn export_unattached( pub(crate) fn export_unattached(
&self, &self,
device: &P::Device, device: &P::Device,
) -> Result<Vec<(u64, Vec<u8>)>, &'static str> {
self.export_unattached_with(
device,
|queue| queue.command_buffer(ON),
|cb| cb.commit(ON),
|| device.wait_idle(),
|cb| cb.wait_until_completed(ON),
|buffer| device.read_standalone_buffer(buffer),
)
}
fn export_unattached_with(
&self,
device: &P::Device,
mut command_buffer: impl FnMut(&P::CommandQueue) -> RaiseResult<Option<P::CommandBuffer>>,
mut commit: impl FnMut(&P::CommandBuffer) -> RaiseResult<()>,
mut wait_idle: impl FnMut(),
mut wait_completed: impl FnMut(&P::CommandBuffer) -> RaiseResult<()>,
mut read_buffer: impl FnMut(&P::Buffer) -> Result<Option<Vec<u8>>, &'static str>,
) -> Result<Vec<(u64, Vec<u8>)>, &'static str> { ) -> Result<Vec<(u64, Vec<u8>)>, &'static str> {
let need_mem: Vec<P::Buffer> = { let need_mem: Vec<P::Buffer> = {
let state = self.lock(); let state = self.lock();
@@ -8373,17 +8392,14 @@ impl<P: Platform> Caches<P> {
.by_block .by_block
.values() .values()
.filter(|c| { .filter(|c| {
c.pages.is_none() c.pages.is_none() && !c.device.memory_made() && c.shapes.iter().any(|s| s.dirty)
&& !c.device.memory_made()
&& c.shapes.iter().any(|s| s.dirty)
}) })
.map(|c| c.device.clone_ref()) .map(|c| c.device.clone_ref())
.collect() .collect()
}; };
self.make_memory(need_mem, MemoryFor::WriteBack); self.make_memory(need_mem, MemoryFor::WriteBack);
let mut flushed_any = false; let (dirty_blocks, queue) = {
{
let mut state = self.lock(); let mut state = self.lock();
let dirty_blocks: Vec<u64> = state let dirty_blocks: Vec<u64> = state
.by_block .by_block
@@ -8391,45 +8407,85 @@ impl<P: Platform> Caches<P> {
.filter(|(_, c)| c.pages.is_none() && c.shapes.iter().any(|s| s.dirty)) .filter(|(_, c)| c.pages.is_none() && c.shapes.iter().any(|s| s.dirty))
.map(|(&b, _)| b) .map(|(&b, _)| b)
.collect(); .collect();
if !dirty_blocks.is_empty() { let queue = if dirty_blocks.is_empty() {
None
} else {
if !state if !state
.make_transfer(device) .make_transfer(device)
.map_err(|_| "snapshot_save: surface cache transfer init failed")? .map_err(|_| "snapshot_save: surface cache transfer init failed")?
{ {
return Err("snapshot_save: surface cache transfer queue unavailable"); return Err("snapshot_save: surface cache transfer queue unavailable");
} }
for block in dirty_blocks { state
let cb_opt = {
let transfer = state
.transfer .transfer
.as_mut() .as_ref()
.ok_or("snapshot_save: surface cache transfer missing")?; .map(|transfer| transfer.queue.clone_ref())
transfer };
.queue (dirty_blocks, queue)
.command_buffer(ON) };
if let Some(queue) = queue {
let mut submitted = Vec::new();
let flushed = (|| {
for block in dirty_blocks {
let cb = command_buffer(&queue)
.map_err(|_| "snapshot_save: surface cache command buffer failed")? .map_err(|_| "snapshot_save: surface cache command buffer failed")?
}; .ok_or("snapshot_save: surface cache command buffer unavailable")?;
let Some(cb) = cb_opt else { let mut state = self.lock();
return Err("snapshot_save: surface cache command buffer unavailable"); let Some(cache) = state.by_block.get_mut(&block).filter(|cache| {
}; cache.pages.is_none() && cache.shapes.iter().any(|s| s.dirty)
let Some(cache) = state.by_block.get_mut(&block) else { }) else {
continue; continue;
}; };
if !cache.copy_through(MemoryFor::WriteBack) { if !cache.copy_through(MemoryFor::WriteBack) {
return Err("snapshot_save: deferred surface cache allocation failed"); return Err("snapshot_save: deferred surface cache allocation failed");
} }
let back = shapes::write_back::<P>(&cb, &cache.device, &cache.shapes, |s| { let back =
s.dirty shapes::write_back::<P>(&cb, &cache.device, &cache.shapes, |s| s.dirty)
})
.map_err(|_| "snapshot_save: surface cache shape write_back failed")?; .map_err(|_| "snapshot_save: surface cache shape write_back failed")?;
cache.wrote_shapes(&back); if back.is_empty() {
state.owed_commits.push(cb); return Err("snapshot_save: surface cache blit encoder unavailable");
flushed_any = true; }
// Retirement frees the queue slot even while we keep the handle for status.
let commit_failed = "snapshot_save: surface cache command buffer commit failed";
state.unlocked(|| commit(&cb)).map_err(|_| commit_failed)?;
let status = cb.status();
if status.raw() < CommandBufferStatus::COMMITTED.raw()
|| status == CommandBufferStatus::ERROR
{
return Err(commit_failed);
}
drop(state);
submitted.push((block, back, cb));
}
Ok(())
})();
let mut wait_failed = false;
if !submitted.is_empty() {
wait_idle();
for (_, _, cb) in &submitted {
if wait_completed(cb).is_err() {
wait_failed = true;
} }
} }
} }
if flushed_any { flushed?;
device.wait_idle(); if wait_failed
|| submitted
.iter()
.any(|(_, _, cb)| cb.status() != CommandBufferStatus::COMPLETED)
{
return Err(
"snapshot_save: surface cache command buffer did not complete successfully",
);
}
let mut state = self.lock();
let state = &mut *state;
for (block, back, _) in &submitted {
if let Some(cache) = state.by_block.get_mut(block) {
cache.wrote_shapes(back);
cache.shapes.written_back(back, &mut state.counts.shapes);
}
}
} }
let mut to_read: Vec<(u64, P::Buffer)> = { let mut to_read: Vec<(u64, P::Buffer)> = {
@@ -8445,7 +8501,7 @@ impl<P: Platform> Caches<P> {
let mut out = Vec::with_capacity(to_read.len()); let mut out = Vec::with_capacity(to_read.len());
for (block, buf) in to_read { for (block, buf) in to_read {
match device.read_standalone_buffer(&buf)? { match read_buffer(&buf)? {
Some(bytes) => out.push((block, bytes)), Some(bytes) => out.push((block, bytes)),
None => return Err("snapshot_save: unattached surface cache buffer unreadable"), None => return Err("snapshot_save: unattached surface cache buffer unreadable"),
} }
@@ -16385,6 +16441,325 @@ pub(super) mod tests {
r.pages_flagged(block, 0, &[], length, flags) r.pages_flagged(block, 0, &[], length, flags)
} }
const SNAPSHOT_CACHE_LENGTH: u64 = 0x1000;
fn snapshot_rig(blocks: u64) -> Rig {
let r = rig(8);
r.dec.set_deferred_budget(blocks * SNAPSHOT_CACHE_LENGTH);
r.dec.caches().shaped = true;
r
}
fn dirty_unattached_cache(r: &mut Rig, block: u64) -> reims_vgpu_vulkan::core::platform::ObjId {
assert_eq!(defer(r, block, SNAPSHOT_CACHE_LENGTH), RGFX_STATUS_OK);
let key = ShapeKey {
plane: 0,
offset: 128,
bytes_per_row: 128,
width: 16,
height: 2,
texel_bytes: 4,
storage: false,
};
let desc = r.p.texture_descriptor(&TextureDesc {
pixel_format: 80,
width: key.width,
height: key.height,
..TextureDesc::default()
});
let image = r.device.new_texture(ON, &desc).unwrap().unwrap();
let id = image.id();
let mut state = r.dec.caches();
let cache = state.by_block.get_mut(&block).unwrap();
assert!(cache.pages.is_none());
assert!(!cache.device.memory_made());
let (reference, _) = cache.shapes.insert(key, image, false, 0);
assert!(cache.shapes.mark_dirty(reference.id()));
id
}
#[test]
fn snapshot_exports_more_dirty_unattached_caches_than_the_transfer_queue_holds() {
use reims_vgpu_vulkan::core::platform::types::MtlSize;
const BLOCKS: u64 = 80;
const CAPACITY: usize = 64;
let mut r = snapshot_rig(BLOCKS + 1);
let mut textures = HashMap::default();
let mut expected = Vec::new();
for i in 0..BLOCKS {
let block = BLOCK + i * 0x2000;
let texture = dirty_unattached_cache(&mut r, block);
let texels = [[i as u8; 64], [255 - i as u8; 64]];
let mut bytes = vec![0; SNAPSHOT_CACHE_LENGTH.to_usize()];
for (row, texels) in bytes[128..].chunks_mut(128).zip(&texels) {
row[..64].copy_from_slice(texels);
}
textures.insert(texture, texels);
expected.push((block, bytes));
}
assert_eq!(
defer(&mut r, BLOCK + BLOCKS * 0x2000, SNAPSHOT_CACHE_LENGTH),
RGFX_STATUS_OK
);
let mark = r.p.call_log().mark();
let world = r.p.world();
let mut acquired = 0;
let retired = Cell::new(0);
let caches = &r.dec.surface_caches;
let exported = caches.export_unattached_with(
&r.device,
|queue| {
assert!(
caches.try_lock().is_some(),
"queue acquisition holds the cache lock"
);
let in_flight = world.committed().len();
assert_eq!(
world.live("MTLCommandBuffer").len(),
in_flight + retired.get(),
"a previous buffer is uncommitted"
);
if in_flight == CAPACITY {
retired.set(retired.get() + world.complete_all(CompleteOn::Caller));
}
assert!(world.committed().len() < CAPACITY);
acquired += 1;
queue.command_buffer(ON)
},
|cb| cb.commit(ON),
|| {
assert_eq!(caches.try_lock().unwrap().counts.shapes.written_back, 0);
retired.set(retired.get() + world.complete_all(CompleteOn::Caller));
},
|cb| cb.wait_until_completed(ON),
|buffer| {
assert!(world.live("MTLCommandBuffer").is_empty());
// The fake logs blits without executing them. Reproduce each logged GPU copy.
let calls = r.p.call_log().since(mark);
let mut copies = calls.iter().filter(|call| {
call.sel.starts_with("copyFromTexture:")
&& call.args[5].as_obj() == Some(buffer.id())
});
let copy = copies.next().expect("a copy into this cache");
assert!(copies.next().is_none());
assert_eq!(copy.args[4], Arg::val(&MtlSize::new(16, 2, 1)));
let source = &textures[&copy.args[0].as_obj().unwrap()];
let offset = copy.args[6].as_u64().unwrap().to_usize();
let pitch = copy.args[7].as_u64().unwrap().to_usize();
let mut bytes = vec![0; buffer.length().to_usize()];
for (row, texels) in source.iter().enumerate() {
let at = offset + row * pitch;
bytes[at..at + 64].copy_from_slice(texels);
}
Ok(Some(bytes))
},
);
assert_eq!(acquired, BLOCKS);
assert_eq!(retired.get(), BLOCKS.to_usize());
assert_eq!(exported.unwrap(), expected);
let state = r.dec.caches();
assert_eq!(state.counts.shapes.written_back, BLOCKS);
assert!(
state
.by_block
.values()
.all(|cache| cache.shapes.iter().all(|s| !s.dirty))
);
}
#[test]
fn snapshot_drops_uncommitted_unattached_writebacks_on_error() {
use reims_vgpu_vulkan::core::testkit::Step;
use reims_vgpu_vulkan::core::testkit::impls::resource::MAKE_MEMORY;
for (selector, steps, error) in [
(
"commandBuffer",
vec![Step::Nil],
"snapshot_save: surface cache command buffer unavailable",
),
(
MAKE_MEMORY,
vec![Step::value(false); 2],
"snapshot_save: deferred surface cache allocation failed",
),
(
"blitCommandEncoder",
vec![Step::Nil],
"snapshot_save: surface cache blit encoder unavailable",
),
(
"endEncoding",
vec![Step::unrecognized("endEncoding")],
"snapshot_save: surface cache shape write_back failed",
),
(
"commit",
vec![Step::unrecognized("commit")],
"snapshot_save: surface cache command buffer commit failed",
),
] {
let mut r = snapshot_rig(1);
dirty_unattached_cache(&mut r, BLOCK);
for step in steps {
r.p.script().push(selector, step);
}
let caches = &r.dec.surface_caches;
assert_eq!(caches.export_unattached(&r.device), Err(error));
assert!(r.p.world().live("MTLCommandBuffer").is_empty());
assert!(
r.dec.caches().by_block[&BLOCK]
.shapes
.iter()
.all(|s| s.dirty)
);
}
}
#[test]
fn snapshot_stops_before_readback_if_a_later_writeback_fails() {
let mut r = snapshot_rig(2);
dirty_unattached_cache(&mut r, BLOCK);
dirty_unattached_cache(&mut r, BLOCK + 0x2000);
r.p.faults()
.at("MTLCommandQueue", "commandBuffer", 1, Fault::Nil);
let caches = &r.dec.surface_caches;
let world = r.p.world();
let mut retired = 0;
let exported = caches.export_unattached_with(
&r.device,
|queue| queue.command_buffer(ON),
|cb| cb.commit(ON),
|| retired += world.complete_all(CompleteOn::Caller),
|cb| cb.wait_until_completed(ON),
|_| panic!("a failed writeback must stop the snapshot before readback"),
);
assert_eq!(
exported,
Err("snapshot_save: surface cache command buffer unavailable")
);
assert_eq!(retired, 1);
assert!(world.live("MTLCommandBuffer").is_empty());
let state = r.dec.caches();
assert_eq!(state.counts.shapes.written_back, 0);
assert_eq!(
state
.by_block
.values()
.filter(|c| c.shapes.iter().any(|s| s.dirty))
.count(),
2
);
}
#[test]
fn snapshot_preserves_dirty_shapes_if_writeback_commit_is_silently_refused() {
let mut r = snapshot_rig(1);
dirty_unattached_cache(&mut r, BLOCK);
let exported = r.dec.surface_caches.export_unattached_with(
&r.device,
|queue| queue.command_buffer(ON),
|_| Ok(()),
|| panic!("a refused commit leaves no submitted work to wait for"),
|_| panic!("a refused commit leaves no submitted work to wait for"),
|_| panic!("a refused commit must stop the snapshot before readback"),
);
assert_eq!(
exported,
Err("snapshot_save: surface cache command buffer commit failed")
);
assert!(r.p.world().live("MTLCommandBuffer").is_empty());
let state = r.dec.caches();
assert_eq!(state.counts.shapes.written_back, 0);
assert!(state.by_block[&BLOCK].shapes.iter().all(|s| s.dirty));
}
#[test]
fn snapshot_preserves_dirty_shapes_if_a_submitted_writeback_fails() {
let mut r = snapshot_rig(2);
dirty_unattached_cache(&mut r, BLOCK);
dirty_unattached_cache(&mut r, BLOCK + 0x2000);
let world = r.p.world();
let exported = r.dec.surface_caches.export_unattached_with(
&r.device,
|queue| queue.command_buffer(ON),
|cb| cb.commit(ON),
|| {
let [first, second] = world.committed().try_into().unwrap();
assert!(world.complete(
first,
CommandBufferStatus::COMPLETED,
None,
CompleteOn::Caller
));
assert!(world.complete(
second,
CommandBufferStatus::ERROR,
None,
CompleteOn::Caller
));
},
|cb| cb.wait_until_completed(ON),
|_| panic!("a failed writeback must stop the snapshot before readback"),
);
assert_eq!(
exported,
Err("snapshot_save: surface cache command buffer did not complete successfully")
);
assert!(world.live("MTLCommandBuffer").is_empty());
let state = r.dec.caches();
assert_eq!(state.counts.shapes.written_back, 0);
assert!(
state
.by_block
.values()
.all(|cache| cache.shapes.iter().all(|s| s.dirty))
);
}
#[test]
fn snapshot_waits_for_each_submitted_writeback_status_after_wait_idle() {
let mut r = snapshot_rig(1);
dirty_unattached_cache(&mut r, BLOCK);
let world = r.p.world();
let mut waited_completed = 0;
let exported = r.dec.surface_caches.export_unattached_with(
&r.device,
|queue| queue.command_buffer(ON),
|cb| cb.commit(ON),
|| {
// Simulate wait_idle returning before the completion worker has
// published the command buffer's final COMPLETED status.
assert_eq!(world.committed().len(), 1);
},
|cb| {
waited_completed += 1;
assert_eq!(cb.status(), CommandBufferStatus::SCHEDULED);
assert_eq!(world.complete_all(CompleteOn::Caller), 1);
cb.wait_until_completed(ON)
},
|buffer| {
assert!(world.live("MTLCommandBuffer").is_empty());
Ok(Some(vec![0xAB; buffer.length().to_usize()]))
},
);
assert_eq!(waited_completed, 1);
assert_eq!(
exported,
Ok(vec![(BLOCK, vec![0xAB; SNAPSHOT_CACHE_LENGTH.to_usize()])])
);
let state = r.dec.caches();
assert_eq!(state.counts.shapes.written_back, 1);
assert!(state.by_block[&BLOCK].shapes.iter().all(|s| !s.dirty));
}
/// A `SURFACE_PAGES` naming the pages of the deferred block at `block`, `runs` as /// A `SURFACE_PAGES` naming the pages of the deferred block at `block`, `runs` as
/// [`Rig::pages`]'s, from context `context`; its answer. /// [`Rig::pages`]'s, from context `context`; its answer.
fn attach(r: &mut Rig, block: u64, context: u32, runs: &[(u64, u64)], length: u64) -> u32 { fn attach(r: &mut Rig, block: u64, context: u32, runs: &[(u64, u64)], length: u64) -> u32 {