diff --git a/crates/reims-vgpu/src/graphics.rs b/crates/reims-vgpu/src/graphics.rs index 336ba9d04..25d9c5465 100644 --- a/crates/reims-vgpu/src/graphics.rs +++ b/crates/reims-vgpu/src/graphics.rs @@ -1184,21 +1184,19 @@ impl GraphicsDevice

{ // surfaces the guest lends: each session decodes on the arm. // Its encoders, where the arm encodes the source frames the guest lends. if video.guest_decodes() { + let runtime = crate::video::runtime::PlatformRuntime::of(&platform); let backend = vt::VtBackend::new( Arc::clone(&video), decoder.lent_views(), gpu_device.clone_ref(), + Arc::clone(&runtime), ); let mut decoders = (video.guest_decoder_list()).unwrap_or_else(|| vt_decoders(&caps)); decoders.extend(video.guest_av1().map(|_| av1::vt_decoder())); let (decoders, encoders) = vt_lists(config.guest_arch, decoders, video.guest_encoders()); - vt = paravirt::Host::with_backend( - decoders, - Arc::new(backend), - crate::video::runtime::PlatformRuntime::of(&platform), - ); + vt = paravirt::Host::with_backend(decoders, Arc::new(backend), runtime); if !encoders.is_empty() { let backend = vt::VtEncoderBackend::new( Arc::clone(&video), diff --git a/crates/reims-vgpu/src/graphics/video_host.rs b/crates/reims-vgpu/src/graphics/video_host.rs index 88e8682d0..781d5c37c 100644 --- a/crates/reims-vgpu/src/graphics/video_host.rs +++ b/crates/reims-vgpu/src/graphics/video_host.rs @@ -114,7 +114,6 @@ use std::time::Duration; use reims_vgpu_graphics::wire::{RGFX_VIDEO_CODEC_H264, RGFX_VIDEO_CODEC_HEVC}; use reims_vgpu_video::codec::PictureStart; use reims_vgpu_video::core::device_memory::MemoryIdentity; -#[cfg(unix)] use reims_vgpu_video::core::device_wait::{KeptMark, Lingering, poll_until}; use reims_vgpu_video::core::runtime::{MonoTime, Runtime}; use reims_vgpu_vulkan::core::host::HostPtr; @@ -147,10 +146,10 @@ pub(crate) const TEARDOWN_WAIT: Duration = Duration::from_secs(10); /// How long a picture's landing that failed in device caches when the hardware's work ran past /// its deadline waits for that work to be let go, before it acquires the caches -/// ([`Landing::failed_in_caches`]): 10 s on the session's clock, twice the hardware's own deadline -/// (`reims_vgpu_video::core::device_wait::DEVICE_WAIT`), so that the work has 15 s from its first -/// wait to finish. Ours. Past it, the process dies. -#[cfg(unix)] +/// (`Landing::failed_in_caches`), and a VideoToolbox picture's that failed so in the surface the +/// guest lent, before its decoder answers (`super::vt`): 10 s on the session's clock, twice the +/// hardware's own deadline (`reims_vgpu_video::core::device_wait::DEVICE_WAIT`), so that the work +/// has 15 s from its first wait to finish. Ours. Past it, the process dies. pub(crate) const STALL_HOLD: Duration = Duration::from_secs(10); /// The code of a host video session whose staging ended (`Stage::copy_with_caches`): a second @@ -2049,7 +2048,7 @@ impl Landing<'_, P> { error: BackendError, ) -> BackendError { if let Failed::Stalled(since) = failed { - hold_while_kept(self.clock, since, STALL_HOLD, &error); + hold_while_kept(self.clock, since, STALL_HOLD, IN_CACHES, &error); } for plane in planes { if let Err(why) = plane.external_write_done() { @@ -2063,19 +2062,34 @@ impl Landing<'_, P> { } } -/// Waits on `clock` until no work the thread of `since` kept after the mark is held, its device -/// not done with it ([`Lingering::holds_since`]), asking after it as a backend asks after its -/// device ([`poll_until`]): at once where none was kept. Past `within`, the process dies with a -/// fault of the decode (`error`'s): the device's memory the work may still write is never read -/// before it is acquired, and no read of it waits unbounded. +/// The landing [`Landing::failed_in_caches`] holds, as its death names it. #[cfg(unix)] -fn hold_while_kept(clock: &dyn Runtime, since: KeptMark, within: Duration, error: &BackendError) { - let held = || Lingering::made().is_some_and(|kept| kept.holds_since(since)); +const IN_CACHES: &str = "a picture's landing in its device caches"; + +/// Whether work the thread of `since` kept after the mark is held, its device not done with it +/// ([`Lingering::holds_since`]). +pub(super) fn kept_since(since: KeptMark) -> bool { + Lingering::made().is_some_and(|kept| kept.holds_since(since)) +} + +/// Waits on `clock` until no work the thread of `since` kept after the mark is held +/// ([`kept_since`]), asking after it as a backend asks after its device ([`poll_until`]): at once +/// where none was kept. Past `within`, the process dies with a fault of the decode, `landing`'s +/// that failed with `error`: nothing the work may still write is read, or given back to the +/// guest, before the device is done with it, and no wait for it is unbounded. +pub(super) fn hold_while_kept( + clock: &dyn Runtime, + since: KeptMark, + within: Duration, + landing: &str, + error: &dyn std::fmt::Display, +) { + let held = || kept_since(since); let let_go = poll_until(clock, clock.deadline_in(within), || (!held()).then_some(())); if let_go.is_none() { decode_fault(format_args!( - "a picture's landing in its device caches, {error}: the hardware's work, which may \ - still write them, was not done {within:?} past its deadline" + "{landing}, {error}: the hardware's work, which may still write there, was not done \ + {within:?} past its deadline" )) .fatal() } diff --git a/crates/reims-vgpu/src/graphics/video_host/tests.rs b/crates/reims-vgpu/src/graphics/video_host/tests.rs index d64cb4c13..3ed792a67 100644 --- a/crates/reims-vgpu/src/graphics/video_host/tests.rs +++ b/crates/reims-vgpu/src/graphics/video_host/tests.rs @@ -815,8 +815,9 @@ fn a_stalled_landing_whose_kept_work_is_not_let_go_ends_the_process() { scope.spawn(|| lingering.keep("a test's work kept elsewhere", kept)); }); let within = Duration::from_millis(300); + let hold = || hold_while_kept(&*runtime, since, within, IN_CACHES, &error); assert_eq!( - catch_death(|| hold_while_kept(&*runtime, since, within, &error)), + catch_death(hold), Ok(()), "nothing this thread kept since the mark" ); @@ -826,10 +827,7 @@ fn a_stalled_landing_whose_kept_work_is_not_let_go_ends_the_process() { Box::new(Stuck(Arc::clone(&stuck))), ); let started = runtime.now(); - assert_eq!( - catch_death(|| hold_while_kept(&*runtime, since, within, &error)), - Err(decode_fault("").site()) - ); + assert_eq!(catch_death(hold), Err(decode_fault("").site())); assert!( runtime.elapsed_since(started) >= within, "held to its bound" diff --git a/crates/reims-vgpu/src/graphics/vt.rs b/crates/reims-vgpu/src/graphics/vt.rs index 0ad75468e..9af192a0b 100644 --- a/crates/reims-vgpu/src/graphics/vt.rs +++ b/crates/reims-vgpu/src/graphics/vt.rs @@ -7,10 +7,13 @@ //! surface's guest RAM pages //! ([`LentViews::view`]), laid out as the kext read the surface ([`layout_of`]). The arm's decoder //! answers once the picture is there; the session then emits the frame, and lets go of the -//! surface with a `rels`. A decoder whose 4:4:4 pictures the device's GPU writes -//! ([`GuestDecoder::lands_4_4_4_by_gpu`]) is handed, for a 4:4:4 surface, a Shared buffer of the -//! device's over the surface's pages ([`LentViews::buffer_over`]), which the GPU writes them in -//! place through. +//! surface with a `rels`. A decode that fails while the hardware's work, which may still write the +//! surface, ran past its deadline is answered once the device is done with that work, up to +//! [`STALL_HOLD`], and the process dies past it ([`answered_once_written`]): the surface goes back +//! to the guest only once nothing of the host's can write it. A decoder whose 4:4:4 pictures the +//! device's GPU writes ([`GuestDecoder::lands_4_4_4_by_gpu`]) is handed, for a 4:4:4 surface, a +//! Shared buffer of the device's over the surface's pages ([`LentViews::buffer_over`]), which the +//! GPU writes them in place through. //! //! Its paravirtual encoders are the arm's too ([`VtEncoderBackend`]): each session's encoder is //! one of the arm's [`GuestEncoder`]s, which reads each source frame from the IOSurface the guest @@ -33,6 +36,7 @@ use std::collections::VecDeque; use std::sync::Arc; +use std::time::Duration; use reims_vgpu_graphics::wire::{ RGFX_VIDEO_CODEC_H264, RGFX_VIDEO_CODEC_HEVC, RGFX_VIDEO_CODEC_VP9, RGFX_VIDEO_DECODE, @@ -40,7 +44,9 @@ use reims_vgpu_graphics::wire::{ }; use reims_vgpu_video::codec::encode::{Coded, FailedSample}; use reims_vgpu_video::core::backend::{BackendError as VideoError, Chroma, PixelFormat}; +use reims_vgpu_video::core::device_wait::KeptMark; use reims_vgpu_video::core::fourcc::FourCc; +use reims_vgpu_video::core::runtime::Runtime; use reims_vgpu_video::core::surfaces::{PlaneLayout, SurfaceLayout}; use reims_vgpu_video::paravirt::status::{self, OsStatus}; use reims_vgpu_video::paravirt::{ @@ -54,6 +60,15 @@ use super::GuestSurface; use super::decode::{ GraphicsVideo, GuestDecoder, GuestEncoder, GuestOutput, GuestSource, LentView, LentViews, }; +use super::video_host::{STALL_HOLD, hold_while_kept, kept_since}; + +/// Counted at each VideoToolbox picture whose decode failed while the hardware's work into the +/// guest's surface ran past its deadline, its answer held until the device is done with the work +/// ([`answered_once_written`]). +pub(super) const VT_DECODE_STALL_HELD: &str = "vt-decode-stall-held"; + +/// The landing [`answered_once_written`] holds, as its death names it. +const IN_SURFACE: &str = "a VideoToolbox picture's landing in the surface the guest lent"; /// The views a decoder or encoder keeps, of the surfaces it used last: past the measured pools /// of 11 to 14 surfaces (the module doc), with room for a pool of a stream that keeps more @@ -66,20 +81,24 @@ pub(super) struct VtBackend { video: Arc>, views: LentViews

, device: P::Device, + clock: Arc, } impl VtBackend

{ /// The backend of `video`'s guest decoders, landing in views `views` makes, and in buffers - /// of `device`'s over them where a decoder's GPU writes them. + /// of `device`'s over them where a decoder's GPU writes them, a stalled decode's answer held + /// on `clock` ([`answered_once_written`]). pub(super) fn new( video: Arc>, views: LentViews

, device: P::Device, + clock: Arc, ) -> Self { Self { video, views, device, + clock, } } } @@ -122,6 +141,7 @@ impl Backend for VtBackend

{ decoder, views: self.views.clone(), device: self.device.clone_ref(), + clock: Arc::clone(&self.clock), kept: VecDeque::new(), said: Vec::new(), tiles, @@ -135,6 +155,8 @@ struct VtDecoder { decoder: Box>, views: LentViews

, device: P::Device, + /// The clock a stalled decode's answer is held on ([`answered_once_written`]). + clock: Arc, kept: Kept>>, /// The reasons a decode failed, or a view has no buffer, each logged once. said: Vec, @@ -284,6 +306,7 @@ impl VtDecoder

{ memory: &**view.memory(), buffer, }; + let since = KeptMark::here(); let decoded = match region { None => self.decoder.decode(parameter_sets, access_unit, &output), Some(r) => self.decoder.decode_region( @@ -293,6 +316,7 @@ impl VtDecoder

{ [r.source_x, r.source_y, r.width, r.height], ), }; + let decoded = answered_once_written(&*self.clock, since, STALL_HOLD, decoded); match decoded { Ok(true) => Ok(Decoded::Landed), Ok(false) | Err(VideoError::SkippedLeadingPicture(_)) => Ok(Decoded::Skipped), @@ -471,6 +495,36 @@ impl BackendEncoder for VtEncoder

{ } } +/// The arm's answer `decoded` to a decode that began at `since`: at once, but where it failed +/// while work the hardware began, which may still write the guest's surface, ran past its +/// deadline and is kept until the device is done with it ([`kept_since`]; NVDEC's copies into the +/// surface's registered pages, VA-API's video processing into its import). That answer waits on +/// `clock` until the device is done, counted ([`VT_DECODE_STALL_HELD`]) and logged once a boot, +/// up to `within`; past it, the process dies ([`hold_while_kept`]). The session gives the surface +/// back to the guest only with the answer, so no write of the hardware's lands in it once it is +/// the guest's again, and a device reset's wait for the session's message in hand outlasts them. +fn answered_once_written( + clock: &dyn Runtime, + since: KeptMark, + within: Duration, + decoded: Result, +) -> Result { + if let Err(error) = &decoded + && kept_since(since) + { + reims_vgpu_vulkan::answer::count_kind(VT_DECODE_STALL_HELD); + log::warn!( + kind:% = VT_DECODE_STALL_HELD; + "hardware video: a VideoToolbox decode failed ({error}) while the hardware's work, \ + which may still write the guest's surface, ran past its deadline: its answer, and \ + the surface's return to the guest, wait until the device is done, up to {within:?}, \ + and the process dies past it (counted as {VT_DECODE_STALL_HELD})" + ); + hold_while_kept(clock, since, within, IN_SURFACE, error); + } + decoded +} + /// The layout of the surface `record` describes, as the kext read it of the IOSurface: its /// format, size and two planes, each from its offset at its own pitch. `Err` says why a surface /// is not one a picture lands in: not of two planes. @@ -571,8 +625,221 @@ fn region_layout(layout: &SurfaceLayout, region: TileRegion) -> Result); + + impl Unfinished for Stuck { + fn finished(&mut self) -> bool { + self.0.load(Ordering::SeqCst) + } + } + + /// The arm's answer to a decode whose write into the guest's surface ran past its deadline, + /// as NVDEC's copy into the surface's registered pages, or VA-API's video processing into its + /// import, fails: the work kept on this thread until `done` is set. + fn stalled(done: &Arc) -> Result { + let kept = Box::new(Stuck(Arc::clone(done))); + Lingering::process(&StdRuntime::shared()).keep("a test's stalled write", kept); + Err(VideoError::Malfunction(STALLED.to_owned())) + } + + /// How long into a test's hold its device finishes the stalled write ([`done_while`]). + const DONE_AFTER: Duration = Duration::from_millis(300); + + /// `f`'s value, with `done` set [`DONE_AFTER`] into it on a thread of its own, as a device + /// that finishes the stalled write then. + fn done_while(done: &AtomicBool, f: impl FnOnce() -> R) -> R { + std::thread::scope(|scope| { + scope.spawn(|| { + std::thread::sleep(DONE_AFTER); + done.store(true, Ordering::SeqCst); + }); + f() + }) + } + + /// A decode that failed while the hardware's write into the guest's surface ran past its + /// deadline, the device done with the write inside the hold, is answered only once the + /// device is done: its error as the arm gave it, the process living, the held stall counted. + /// The session gives the surface back with the answer (`rels`), so not before either. + #[test] + fn a_stalled_decode_is_answered_once_the_device_is_done_with_its_write() { + let runtime = StdRuntime::shared(); + let held = counted(VT_DECODE_STALL_HELD); + let done = Arc::new(AtomicBool::new(false)); + let since = KeptMark::here(); + let decoded = stalled(&done); + let started = runtime.now(); + let within = Duration::from_secs(10); + let answer = done_while(&done, || { + catch_death(|| answered_once_written(&*runtime, since, within, decoded)) + }); + let waited = runtime.elapsed_since(started); + assert!( + done.load(Ordering::SeqCst), + "answered once the device was done" + ); + assert!(waited >= DONE_AFTER, "{waited:?}"); + assert_eq!(answer, Ok(Err(VideoError::Malfunction(STALLED.to_owned())))); + assert_eq!(counted(VT_DECODE_STALL_HELD), held + 1); + } + + /// One whose write the device is not done with within the hold ends the process, at a fault + /// of the decode: the surface never goes back to the guest while the hardware may write it. + #[test] + fn a_stalled_decode_whose_write_outlives_the_hold_ends_the_process() { + let runtime = StdRuntime::shared(); + let stuck = Arc::new(AtomicBool::new(false)); + let since = KeptMark::here(); + let decoded = stalled(&stuck); + let within = Duration::from_millis(300); + let started = runtime.now(); + let died = catch_death(|| answered_once_written(&*runtime, since, within, decoded)); + assert_eq!(died, Err(super::super::decode::op_fault("").site())); + assert!( + runtime.elapsed_since(started) >= within, + "held to its bound" + ); + stuck.store(true, Ordering::SeqCst); + } + + /// A decode that fails with no work of the hardware's kept since it began, or lands, is + /// answered at once, whatever was kept before it or by another thread, and counts nothing. + #[test] + fn a_decode_with_no_work_kept_since_it_began_is_answered_at_once() { + let runtime = StdRuntime::shared(); + let held = counted(VT_DECODE_STALL_HELD); + let before = Arc::new(AtomicBool::new(false)); + let _ = stalled(&before); + let since = KeptMark::here(); + let elsewhere = Arc::new(AtomicBool::new(false)); + std::thread::scope(|scope| { + scope.spawn(|| stalled(&elsewhere)); + }); + let within = Duration::from_secs(10); + let started = runtime.now(); + let bad: Result = Err(VideoError::BadData( + "a slice that does not parse".to_owned(), + )); + let answer = answered_once_written(&*runtime, since, within, bad.clone()); + assert_eq!(answer, bad); + assert_eq!( + answered_once_written(&*runtime, since, within, Ok(true)), + Ok(true) + ); + assert!(runtime.elapsed_since(started) < Duration::from_secs(1)); + assert_eq!(counted(VT_DECODE_STALL_HELD), held); + for done in [&before, &elsewhere] { + done.store(true, Ordering::SeqCst); + } + } + + /// An arm whose every decode's write into the guest's surface runs past its deadline + /// ([`stalled`]), its work kept until `done` is set; it counts its decodes. + struct StallingArm { + done: Arc, + decodes: Arc, + } + + impl GuestDecoder for StallingArm { + fn decode( + &mut self, + _parameter_sets: &[u8], + _au: &[u8], + _output: &GuestOutput<'_, FakePlatform>, + ) -> Result { + self.decodes.fetch_add(1, Ordering::SeqCst); + stalled(&self.done) + } + } + + /// A session's decoder (`VtDecoder`) whose arm's write into the surface the guest lent stalls + /// answers the session only once the device is done with the write: `land` holds the arm's + /// error ([`answered_once_written`]) until then, the process living, the held stall counted, + /// and the session's `rels` of the surface comes only with the answer. The surface is mapped + /// through the decoder's views of guest RAM as a `VT_MESSAGE`'s lend is. + #[test] + fn a_session_s_stalled_decode_is_answered_once_the_device_is_done_with_its_write() { + use reims_vgpu_graphics::region::Region; + use reims_vgpu_vulkan::core::memory::descriptor::{ + GuestPhysicalRange, MemoryMapDescriptor, + }; + use reims_vgpu_vulkan::core::memory::map::MemoryMap; + use reims_vgpu_vulkan::core::testkit::GuestRam; + + use super::super::VtSurface; + use super::super::decode::GraphicsDecoder; + + /// The guest RAM's first byte. + const RAM: u64 = 0x10_0000; + let p = Arc::new(FakePlatform::new()); + let page = (p.vm().page_size()) + .max(reims_vgpu_vulkan::core::memory::PAGE_SIZE) + .max(4096); + let region = Arc::new(Region::new(0x10_0000).unwrap()); + let mut dec = GraphicsDecoder::::new(Arc::clone(&p), region); + let ram = GuestRam::with_range(RAM, 8 * page).unwrap(); + p.fake_vm().adopt(&ram); + let mut desc = MemoryMapDescriptor::new(); + for r in ram.ranges() { + desc.add_range(GuestPhysicalRange { + physical_address: r.physical_address, + physical_length: r.physical().physical_length, + host_address: r.host(), + }); + } + dec.set_guest_memory(MemoryMap::new(Arc::clone(&p), &desc).unwrap(), Arc::new(())); + let done = Arc::new(AtomicBool::new(false)); + let decodes = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let mut decoder = VtDecoder { + decoder: Box::new(StallingArm { + done: Arc::clone(&done), + decodes: Arc::clone(&decodes), + }), + views: dec.lent_views(), + device: p.device(), + clock: StdRuntime::shared(), + kept: VecDeque::new(), + said: Vec::new(), + tiles: None, + }; + let record = nv12(); + let surface = GuestSurface::new(VtSurface { + surface: record, + runs: vec![(RAM, record.length.next_multiple_of(page))], + table: false, + }); + let held = counted(VT_DECODE_STALL_HELD); + let runtime = StdRuntime::shared(); + let started = runtime.now(); + let answer = done_while(&done, || { + catch_death(|| decoder.decode(&[], &[0, 0, 0, 1, 0x26, 0x01], &surface)) + }); + let waited = runtime.elapsed_since(started); + assert_eq!(decodes.load(Ordering::SeqCst), 1, "the arm decoded it"); + assert!( + done.load(Ordering::SeqCst), + "answered once the device was done" + ); + assert!(waited >= DONE_AFTER, "{waited:?}"); + assert_eq!(answer, Ok(Err(status::VIDEO_DECODER_MALFUNCTION))); + assert_eq!(counted(VT_DECODE_STALL_HELD), held + 1); + // The session lets go of it with its `rels`, which this test stands in for. + surface.letting_go(); + } /// The runs of the `n`th of a pool's 1080p `420v` surfaces, each in a run of its own. fn pool_runs(n: u64) -> Vec<(u64, u64)> {