diff --git a/crates/reims-vgpu/src/graphics.rs b/crates/reims-vgpu/src/graphics.rs index 25d9c5465..c4e5018b4 100644 --- a/crates/reims-vgpu/src/graphics.rs +++ b/crates/reims-vgpu/src/graphics.rs @@ -3421,6 +3421,11 @@ impl GraphicsControl

{ refusing(|| decoder.stand_in_for_failed(&self.device, message)), Ok(true) ); + // Posted at once, the failure still comes after the video work its walk handed + // off, which writes or reads the guest's surfaces. + if !matches!(outcome, Ok(Ok(()))) && !stood_in { + decoder.wait_for_hand_offs(); + } (outcome, stood_in, answers) }; let (outcome, stood_in, answers) = outcome; @@ -3816,8 +3821,11 @@ impl GraphicsControl

{ refusing(|| decoder.stand_in_for_failed(&control.device, &message)), Ok(true) ); - // A failure posted below comes after the commits of the buffers before it. + // A failure posted below comes after the video work its walk handed off, which + // writes or reads the guest's surfaces, and after the commits of the buffers + // before it. if !matches!(outcome, Ok(Ok(()))) && !stood_in { + decoder.wait_for_hand_offs(); decoder.wait_turn(); } let turn = decoder.take_turn(); diff --git a/crates/reims-vgpu/src/graphics/decode/cmdbuf.rs b/crates/reims-vgpu/src/graphics/decode/cmdbuf.rs index f03876dc4..418df247a 100644 --- a/crates/reims-vgpu/src/graphics/decode/cmdbuf.rs +++ b/crates/reims-vgpu/src/graphics/decode/cmdbuf.rs @@ -2725,13 +2725,16 @@ impl GraphicsDecoder

{ /// faulted at an op: one naming an object its process does not hold among them; what names /// an object whose create the host refused is dropped instead, [`refused`]), as a buffer Metal /// could not run still finishes: a command buffer on its queue holding the buffer's event ops - /// alone, each wait and signal of an event its process holds, in stream order. Its completion - /// posts the shared event values signalled and then the buffer's failure ([`cb_failed`]), so - /// the failure comes in its queue's order, once the buffers committed before it finish, and - /// nothing waiting for one of its values, on the GPU or in the guest, waits for good. - /// `Ok(false)` where there is none, and the caller posts the failure at once: a message too - /// short to name its queue, and a queue the process does not hold or that makes no command - /// buffer. + /// alone, each wait and signal of an event its process holds, in stream order, and, at its + /// place among them, a wait for each video op's work its walk handed a session before it + /// failed ([`video::HandOff`]), which writes or reads the guest's surfaces whatever becomes of + /// the buffer. Its completion posts the shared event values signalled and then the buffer's + /// failure ([`cb_failed`]), so the failure comes in its queue's order, once the buffers + /// committed before it finish and the work handed off is done, and nothing waiting for one of + /// its values, on the GPU or in the guest, waits for good. `Ok(false)` where there is none, + /// and the caller posts the failure at once, once the work handed off is done + /// ([`GraphicsDecoder::wait_for_hand_offs`]): a message too short to name its queue, and a + /// queue the process does not hold or that makes no command buffer. pub(crate) fn stand_in_for_failed( &self, device: &P::Device, @@ -2769,8 +2772,12 @@ impl GraphicsDecoder

{ let in_flight = InFlight::new(&counts.in_flight, &counts.out); let mut events = EventOps::default(); let carried = event_ops(ops); - // A signal before a wait the stand-in carries is reached before the stand-in's end - // ([`Signals`]). + // The work its walk handed sessions, in stream order: each waited for after the event ops + // before it. + let handed = self.handed_off.borrow(); + let mut handed_waits = handed.iter().peekable(); + // A signal before a wait the stand-in carries, a hand-off's among them, is reached before + // the stand-in's end ([`Signals`]). let last_wait = carried.iter().rposition(|(signal, op)| { !signal && matches!( @@ -2778,7 +2785,11 @@ impl GraphicsDecoder

{ Some(ObjHandle::Event(_) | ObjHandle::SharedEvent(_)) ) }); + let last_handed = handed.last().map(|h| h.events_before); for (at, (signal, op)) in carried.into_iter().enumerate() { + while let Some(h) = handed_waits.next_if(|h| h.events_before <= at) { + cb.encode_wait(Some(h.event()), h.value)?; + } let (event, shared) = match self.named(op.event_obj_id) { Some(ObjHandle::Event(e)) => (EventRef::Event(e), None), Some(ObjHandle::SharedEvent(e)) => (EventRef::Shared(e), Some(e)), @@ -2794,7 +2805,8 @@ impl GraphicsDecoder

{ if signal { cb.encode_signal(Some(event), op.value)?; if let Some(shared) = shared { - let mid = last_wait.is_some_and(|wait| wait > at); + let mid = last_wait.is_some_and(|wait| wait > at) + || last_handed.is_some_and(|before| before > at); self.note_signal(&mut events, shared, op, mid)?; } } else { @@ -2802,6 +2814,10 @@ impl GraphicsDecoder

{ events.waits.push((op.event_obj_id, op.value)); } } + for h in handed_waits { + cb.encode_wait(Some(h.event()), h.value)?; + } + drop(handed); // It holds its queue as the buffer would have. let (_, held) = hold(counts, !events.waits.is_empty()); if let Some(held) = &held { @@ -2833,6 +2849,8 @@ impl GraphicsDecoder

{ if let Some(signal) = &signal_committed { signal.note(); } + // Its waits hold the work handed off: none is left for the failure's post to wait for. + self.handed_off.borrow_mut().clear(); Ok(true) } @@ -3378,6 +3396,7 @@ impl GraphicsDecoder

{ self.slot_shapes.borrow_mut().clear(); self.slot_pipeline.set(0); self.firsts.set((0, 0)); + self.events_walked.set(0); } /// [`Self::walk_ops`]' walk of `ops`, the whole of a command buffer's op stream or a range @@ -4103,13 +4122,17 @@ impl GraphicsDecoder

{ }; match op_group(tag) { RGFX_OP_GROUP_FRAMING => { + let event = matches!(tag, RGFX_OP_SIGNAL_EVENT | RGFX_OP_WAIT_EVENT); // An event's wait or signal: the part it goes into is observed. - if matches!(tag, RGFX_OP_SIGNAL_EVENT | RGFX_OP_WAIT_EVENT) - && let Some(s) = split.as_mut() - { + if event && let Some(s) = split.as_mut() { s.events = true; s.paced = false; } + // Counted as a stand-in reads the buffer's event ops ([`event_ops`]), for + // where a video op's hand-off lies among them ([`video::HandOff`]). + if event && RgfxOpEvent::read_from_prefix(body).is_ok() { + self.events_walked.set(self.events_walked.get() + 1); + } self.framing_op((tag, body, &ops[len..]), cb, encoder, events)?; if tag == RGFX_OP_ENCODER_END { self.reconcile_laid(cb)?; @@ -4173,7 +4196,7 @@ impl GraphicsDecoder

{ return Err(no_encoder(tag, "video")); }; let landings = (&mut events.landings, &mut events.decodes); - match video::decode_op(tag, body, self, session.session(), cb, landings) { + match video::decode_op(tag, body, self, session, cb, landings) { Ok(true) => {} Ok(false) => return Err(unknown_op(tag)), Err(raise) => contain(raise)?, @@ -5989,6 +6012,138 @@ mod tests { ); } + /// A command buffer whose walk faults after its session took a decode is stood in for by a + /// buffer that waits for the session's value at the decode's place among the buffer's event + /// ops (`video::HandOff`): after the signal before it, which is reached before the stand-in's + /// end and so goes to the guest as the event reaches it, and before the signal after it. The + /// session's work, the output's landing, runs whatever becomes of the buffer, so the buffer's + /// failure comes once the stand-in completes, behind that wait: here, once the session's event + /// reached the value and the fake's GPU then completed the stand-in. + #[test] + fn a_stand_in_waits_for_the_decode_its_walk_handed_off() { + let (p, mut dec) = setup(); + let device = p.device(); + let seen = decode_setup(&p, &mut dec); + let event = RgfxSharedEventCreate { + header: RgfxMsgHeader { + r#type: RGFX_CMD_SHARED_EVENT_CREATE, + size: size_of::() as u32, + seqno: 0, + }, + obj_id: 70, + initial_value: 0, + }; + assert_eq!(dec.decode(&device, event.as_bytes()).unwrap(), Ok(())); + let posted = Arc::new(Mutex::new(Vec::<(u32, u64, u64)>::new())); + let signals = Arc::clone(&posted); + dec.set_signal_sink(Arc::new(move |m| { + signals.lock().push((m.header.r#type, m.obj_id, m.value)); + })); + let completions = Arc::clone(&posted); + dec.set_completion_sink(Arc::new(move |m| { + completions + .lock() + .push((m.header.r#type, m.cb_obj_id, u64::from(m.status))); + })); + // A signal of 70 to 2, the decode, a signal of 70 to 3, and a wait for event 99, which + // the process does not hold: the walk faults there, after the session took the decode. + let mut ops = event_op(RGFX_OP_SIGNAL_EVENT, 70, 2); + ops.extend(decode_ops()); + ops.extend(event_op(RGFX_OP_SIGNAL_EVENT, 70, 3)); + ops.extend(event_op(RGFX_OP_WAIT_EVENT, 99, 1)); + let message = command_buffer_message(150, 70, &ops); + assert!(dec.decode(&device, &message).is_err()); + assert_eq!(seen.decodes.lock().len(), 1, "the session took the decode"); + let mark = p.call_log().mark(); + assert!(dec.stand_in_for_failed(&device, &message).unwrap()); + let session = seen.events.lock()[0].clone_ref(); + let Some(ObjHandle::SharedEvent(guests)) = dec.object(70) else { + panic!("no shared event 70"); + }; + let guests = guests.clone_ref(); + let event_calls: Vec<(&str, Vec)> = (p.call_log().since(mark).into_iter()) + .filter(|c| { + matches!( + c.sel, + "encodeSignalEvent:value:" | "encodeWaitForEvent:value:" + ) + }) + .map(|c| (c.sel, c.args)) + .collect(); + let at = |event: &::SharedEvent, value: u64| { + vec![ + Arg::Obj(Some(EventRef::::Shared(event).id())), + Arg::U64(value), + ] + }; + assert_eq!( + event_calls, + [ + ("encodeSignalEvent:value:", at(&guests, 2)), + ("encodeWaitForEvent:value:", at(&session, 1)), + ("encodeSignalEvent:value:", at(&guests, 3)), + ], + "the stand-in's waits and signals, in the buffer's order" + ); + let asked = (p.call_log().sels_since(mark).into_iter()) + .filter(|sel| *sel == "notifyListener:atValue:block:") + .count(); + assert_eq!( + asked, 1, + "the signal to 2, before the decode's wait, as the event reaches it" + ); + assert!( + posted.lock().is_empty(), + "nothing posted while the decode's work runs" + ); + // The landing done: the session's event reaches the decode's value, and the stand-in + // completes behind it, with the buffer's failure. + session.set_signaled_value(1).unwrap(); + p.world().complete_all(CompleteOn::Caller); + let posted = posted.lock(); + assert!( + posted.contains(&(RGFX_EVT_EVENT_SIGNALLED, 70, 3)), + "{posted:?}" + ); + assert_eq!( + posted.last(), + Some(&(RGFX_EVT_CB_COMPLETE, 150, u64::from(RGFX_CB_INTERNAL))), + "{posted:?}" + ); + } + + /// Where no stand-in is made for a command buffer whose walk faulted after its session took + /// a decode (here its queue makes no command buffer), the failure, posted at once, waits on + /// the CPU for the session's value first ([`GraphicsDecoder::wait_for_hand_offs`]): it goes + /// once the landing is done. What was waited for once is not waited for again. + #[test] + fn a_failure_with_no_stand_in_waits_for_the_decode_its_walk_handed_off() { + let (p, mut dec) = setup(); + let device = p.device(); + let seen = decode_setup(&p, &mut dec); + let mut ops = decode_ops(); + ops.extend(event_op(RGFX_OP_WAIT_EVENT, 99, 1)); + let message = command_buffer_message(151, 71, &ops); + assert!(dec.decode(&device, &message).is_err()); + assert_eq!(seen.decodes.lock().len(), 1, "the session took the decode"); + p.script().push("commandBuffer", Step::Nil); + assert!(!dec.stand_in_for_failed(&device, &message).unwrap()); + let session = seen.events.lock()[0].clone_ref(); + let seen_at_post = std::thread::scope(|scope| { + scope.spawn(|| { + std::thread::sleep(Duration::from_millis(300)); + session.set_signaled_value(1).unwrap(); + }); + dec.wait_for_hand_offs(); + session.signaled_value() + }); + assert_eq!( + seen_at_post, 1, + "the session's value, reached before the post" + ); + assert!(dec.handed_off.borrow().is_empty(), "waited for once"); + } + /// A plane of a buffer over host memory in a block of the region reaches the host's video as /// the block's memory: the block's bytes, the buffer's place in them, and an identity that /// ends at the block's `BLOCK_RELEASE`, one for the block whichever decode names it. diff --git a/crates/reims-vgpu/src/graphics/decode/mod.rs b/crates/reims-vgpu/src/graphics/decode/mod.rs index 1ec8a3126..ad2563554 100644 --- a/crates/reims-vgpu/src/graphics/decode/mod.rs +++ b/crates/reims-vgpu/src/graphics/decode/mod.rs @@ -1565,6 +1565,15 @@ pub struct GraphicsDecoder { /// The shapes of its command buffer's pre-pass that no compile thread took, which the walk /// makes at its first dispatch ([`prepass`], "The walk makes the rest"). untaken: RefCell>>, + /// The work of its command buffer's video ops that their sessions took, in stream order, from + /// the moment each session answered its value ([`video::HandOff`]): what a stand-in for the + /// buffer, where its walk faulted after them, waits for at their places + /// ([`Self::stand_in_for_failed`]), and the failure's post where none is made + /// ([`Self::wait_for_hand_offs`]). + handed_off: RefCell>>, + /// How many of its command buffer's event ops (`WAIT_EVENT`, `SIGNAL_EVENT`) its walk has + /// passed: where each hand-off lies among them ([`video::HandOff::events_before`]). + events_walked: Cell, } /// The slice of a wait for a lock within the time `within` answers left ([`taken_within`]). @@ -1807,6 +1816,8 @@ impl GraphicsDecoder

{ work_names: RefCell::new(None), firsts: Cell::new((0, 0)), untaken: RefCell::new(None), + handed_off: RefCell::new(Vec::new()), + events_walked: Cell::new(0), } } @@ -1855,6 +1866,8 @@ impl GraphicsDecoder

{ self.order_waits.get_mut().clear(); self.work_names.get_mut().take(); self.untaken.get_mut().take(); + self.handed_off.get_mut().clear(); + self.events_walked.set(0); } /// The walk about to run makes `untaken`, its pre-pass's shapes no compile thread took, at diff --git a/crates/reims-vgpu/src/graphics/decode/video.rs b/crates/reims-vgpu/src/graphics/decode/video.rs index cedcf7354..e4c4d5b43 100644 --- a/crates/reims-vgpu/src/graphics/decode/video.rs +++ b/crates/reims-vgpu/src/graphics/decode/video.rs @@ -40,6 +40,18 @@ //! (`super::super::video_host::CARRIED_CODE`, counted as a degradation). Where the session ends //! before another decode, its last picture's among them, no command buffer is left to fail, and //! the guest is never told (`super::super::video_host::UNTOLD_CODE`, counted and logged). +//! +//! **A walk that faults after a hand-off.** Once the session has answered a decode's or an +//! encode's value, its work runs whatever becomes of the command buffer: the landing writes the +//! output's pages, an encode reads its source in place. A later op of the buffer that faults (the +//! cache's note of the decode, the wait's encode, any op after them) leaves the buffer +//! uncommitted, and its stand-in carries the guest's event ops alone; so each such work is noted +//! as the session answers ([`HandOff`]), and the stand-in waits for its value at its place among +//! those ops ([`GraphicsDecoder::stand_in_for_failed`]), or, where no stand-in is made, the +//! failure's post waits for it on the CPU, up to [`HAND_OFF_WAIT`] +//! ([`GraphicsDecoder::wait_for_hand_offs`]). The guest is told of the failure once the host's +//! work on its surfaces is done, as it would be of the buffer's completion, and a reset's settle, +//! which waits for the stand-in, waits for the work too. use std::mem::ManuallyDrop; use std::ptr::NonNull; @@ -68,7 +80,6 @@ use reims_vgpu_vulkan::core::platform::Handle as _; use reims_vgpu_vulkan::core::platform::Platform; use reims_vgpu_vulkan::core::platform::command::CommandBuffer as _; use reims_vgpu_vulkan::core::platform::event::EventRef; -#[cfg(windows)] use reims_vgpu_vulkan::core::platform::event::SharedEvent as _; use reims_vgpu_vulkan::core::platform::resource::Buffer as _; #[cfg(unix)] @@ -83,6 +94,34 @@ use super::surface_order::{DecodeLanding, Landing}; use super::worker::Worker; use super::{Entry, GraphicsDecoder, ObjHandle, bad_reference, op_fault}; +/// The longest a failure's post waits on the CPU for the work its command buffer's sessions took +/// ([`GraphicsDecoder::wait_for_hand_offs`]): 15 s, the hardware's deadline +/// (`reims_vgpu_video::core::device_wait::DEVICE_WAIT`) and the hold of a stalled landing after +/// it (`super::super::video_host::STALL_HOLD`), past which the process has died. +pub(super) const HAND_OFF_WAIT: std::time::Duration = + reims_vgpu_video::core::device_wait::DEVICE_WAIT + .saturating_add(super::super::video_host::STALL_HOLD); + +/// Work of a video op that its session took ([`decode_op`], [`encode_op`]; the module docs, "A +/// walk that faults after a hand-off"): from the session's answer on, the session writes the +/// output or reads the source until its event reaches the value. +pub(super) struct HandOff { + /// The session, held as the walk's encoder holds it, let go of on the video worker. + session: SessionHold

, + /// The value the session's event reaches once the work is done. + pub(super) value: u64, + /// How many of the command buffer's event ops come before its op in stream order, as a + /// stand-in reads them (`super::cmdbuf`'s `event_ops`). + pub(super) events_before: usize, +} + +impl HandOff

{ + /// The session's event, which reaches [`Self::value`] once the work is done. + pub(super) fn event(&self) -> EventRef<'_, P> { + self.session.session().event() + } +} + /// How long a video op waits on the CPU for the host's own work on its surface's device cache /// before the log names the wait (diagnostics only): it waits on after /// ([`GraphicsDecoder::wait_for_cache`]). The work is a copy of the surface's pages, a few @@ -932,14 +971,15 @@ pub(super) fn decode_op( tag: u16, payload: &[u8], objs: &GraphicsDecoder

, - session: &Arc>, + hold: &SessionHold

, cb: &P::CommandBuffer, (landings, decodes): (&mut Vec>, &mut Vec>), ) -> RaiseResult { if let Some(codec) = encode_codec(tag) { - encode_op(tag, codec, payload, objs, session, cb)?; + encode_op(tag, codec, payload, objs, hold, cb)?; return Ok(true); } + let session = hold.session(); let Some(read) = DecodeOp::read(tag, payload) else { return Ok(false); }; @@ -963,6 +1003,8 @@ pub(super) fn decode_op( return Err(fault); } }; + // The session writes the output from here, whatever becomes of the buffer. + objs.hand_off(hold, done.value); // The guest's decodes in flight, this one among them, as many as the spare surfaces of the // caches over Direct3D 11 textures an ask keeps (`surface_cache`'s `exported`). #[cfg(windows)] @@ -1058,9 +1100,10 @@ fn encode_op( codec: u32, payload: &[u8], objs: &GraphicsDecoder

, - session: &Arc>, + hold: &SessionHold

, cb: &P::CommandBuffer, ) -> RaiseResult<()> { + let session = hold.session(); let fault = |what: std::fmt::Arguments<'_>| op_fault(format_args!("video op {tag:#06x}: {what}")); let (m, rest) = RgfxVideoOpEncode::read_from_prefix(payload) @@ -1129,11 +1172,56 @@ fn encode_op( // source among them. objs.wait_for_order_on_cpu(); let value = session.encode(&encode)?; + // The session reads the source from here, whatever becomes of the buffer. + objs.hand_off(hold, value); cb.encode_wait(Some(session.event()), value)?; Ok(()) } impl GraphicsDecoder

{ + /// Notes the work of the video op the walk is at that `session` took, whose event reaches + /// `value` once it is done ([`HandOff`]), at its place among the buffer's event ops. + fn hand_off(&self, session: &SessionHold

, value: u64) { + self.handed_off.borrow_mut().push(HandOff { + session: session.another(), + value, + events_before: self.events_walked.get(), + }); + } + + /// Waits on the CPU, up to [`HAND_OFF_WAIT`] in all, for the work the sessions took of the + /// message's command buffer, whose walk failed and for which no stand-in waits + /// ([`Self::stand_in_for_failed`]): the caller posts the buffer's failure once it returns + /// (the module docs, "A walk that faults after a hand-off"). Work not done by then, or whose + /// event is a plain one, which the CPU cannot read, is logged, and the failure goes all the + /// same; past the bound the stalled landing's hold has ended the process. + pub(crate) fn wait_for_hand_offs(&self) { + use reims_vgpu_vulkan::core::platform::os::clock::Clock as _; + let handed = std::mem::take(&mut *self.handed_off.borrow_mut()); + if handed.is_empty() { + return; + } + let clock = self.platform.clock(); + let until = clock.now_mono().saturating_add(HAND_OFF_WAIT); + for h in &handed { + let left = until.saturating_duration_since(clock.now_mono()); + let millis = u64::try_from(left.as_millis()).unwrap_or(u64::MAX); + let done = match h.event() { + EventRef::Shared(event) => event.wait_until_signaled_value(h.value, millis), + EventRef::Event(_) => false, + }; + if !done { + log::warn!( + target: "reims_vgpu::graphics", + "a command buffer whose walk failed after its video work was taken: the \ + failure goes before the session's event was seen at {} (the work may still \ + touch its surfaces)", + h.value + ); + } + } + } + /// The host's hardware video, which `VIDEO_SESSION_CREATE` makes its sessions on. pub(crate) fn set_video(&mut self, video: Arc>) { // Set once, at the device's make.