diff --git a/crates/reims-vgpu-c/include/reims_vgpu.h b/crates/reims-vgpu-c/include/reims_vgpu.h index 1204fb227..ef0613e65 100644 --- a/crates/reims-vgpu-c/include/reims_vgpu.h +++ b/crates/reims-vgpu-c/include/reims_vgpu.h @@ -199,9 +199,10 @@ typedef void (*RvgDestroyFn)(void *ctx); // (`reims-vgpu.icb-create-`), a thread that lets go of a closed process's objects and answers // its close (`reims-vgpu.graphics-closes-`), a thread that moves a staged copy of a surface's // device cache into its pages and answers what waited for it -// (`reims-vgpu.graphics-into-pages-`), or the platform's thread that runs a command buffer's -// scheduled or completed handler; or the host's own, inside -// rvg_graphics_device_mmio_write_taking. +// (`reims-vgpu.graphics-into-pages-`), a video session's picture landing thread, which posts +// a decode's completion as the decode is done (`reims-vgpu.graphics-video-land`), or the +// platform's thread that runs a command buffer's scheduled or completed handler; or the host's +// own, inside rvg_graphics_device_mmio_write_taking. // Never inside another call of the host's into the library. The library may hold locks of its // own around it (docs/api.md section 5 names them), but none that a function it may call waits // for, directly or through a thread of the library's, so it may call them at once. It may wait diff --git a/crates/reims-vgpu-c/src/graphics.rs b/crates/reims-vgpu-c/src/graphics.rs index 975e67659..435bc1280 100644 --- a/crates/reims-vgpu-c/src/graphics.rs +++ b/crates/reims-vgpu-c/src/graphics.rs @@ -128,9 +128,10 @@ const _: () = { /// (`reims-vgpu.icb-create-`), a thread that lets go of a closed process's objects and answers /// its close (`reims-vgpu.graphics-closes-`), a thread that moves a staged copy of a surface's /// device cache into its pages and answers what waited for it -/// (`reims-vgpu.graphics-into-pages-`), or the platform's thread that runs a command buffer's -/// scheduled or completed handler; or the host's own, inside -/// rvg_graphics_device_mmio_write_taking. +/// (`reims-vgpu.graphics-into-pages-`), a video session's picture landing thread, which posts +/// a decode's completion as the decode is done (`reims-vgpu.graphics-video-land`), or the +/// platform's thread that runs a command buffer's scheduled or completed handler; or the host's +/// own, inside rvg_graphics_device_mmio_write_taking. /// Never inside another call of the host's into the library. The library may hold locks of its /// own around it (docs/api.md section 5 names them), but none that a function it may call waits /// for, directly or through a thread of the library's, so it may call them at once. It may wait diff --git a/crates/reims-vgpu-video/src/vaapi/va/frame.rs b/crates/reims-vgpu-video/src/vaapi/va/frame.rs index 34d725719..ab1eeb05c 100644 --- a/crates/reims-vgpu-video/src/vaapi/va/frame.rs +++ b/crates/reims-vgpu-video/src/vaapi/va/frame.rs @@ -367,6 +367,18 @@ impl Frame { &self, target: &GuestTarget<'_>, writes: &GuestWrites, + ) -> Result { + self.write_to_guest_telling(target, writes, &mut || {}) + } + + /// [`Self::write_to_guest`], calling `decoded` once the frame's decode is done and the runs + /// that write it are issued behind it, before they are waited for: from then on the write is + /// the GPU's work alone. Not called where the decode failed, or the runs were not issued. + pub fn write_to_guest_telling( + &self, + target: &GuestTarget<'_>, + writes: &GuestWrites, + decoded: &mut dyn FnMut(), ) -> Result { let rect = self.rect; let (coded_width, coded_height) = self.surface.size(); @@ -375,7 +387,7 @@ impl Frame { target.height().min(coded_height.saturating_sub(rect.y)), ); wait::by(&self.deadline, || { - super::zero_copy::write(self, target, &writes.0, size) + super::zero_copy::write(self, target, &writes.0, size, decoded) }) } } diff --git a/crates/reims-vgpu-video/src/vaapi/va/zero_copy.rs b/crates/reims-vgpu-video/src/vaapi/va/zero_copy.rs index e9c813de7..5f9343547 100644 --- a/crates/reims-vgpu-video/src/vaapi/va/zero_copy.rs +++ b/crates/reims-vgpu-video/src/vaapi/va/zero_copy.rs @@ -184,12 +184,14 @@ fn declined(why: impl Into) -> DeviceWrite { /// the frame did not decode, or the GPU did not finish the frame by its /// deadline. The runs are issued before the decode is waited for, so a frame /// that did not decode leaves the buffer holding what they copied from its -/// decode surface. +/// decode surface. `decoded` is called once the decode is done, the runs +/// issued and not yet waited for (`Frame::write_to_guest_telling`). pub(crate) fn write( frame: &Frame, target: &GuestTarget<'_>, imports: &GuestImports, (width, height): (u32, u32), + decoded_now: &mut dyn FnMut(), ) -> Result { let format = frame.surface.format(); let display = frame.surface.display(); @@ -268,6 +270,9 @@ pub(crate) fn write( let mut decoded = Ok(()); let ran = import.run(frame.surface.id(), x, y, w, deadline, || { decoded = frame.surface.sync_by(deadline); + if decoded.is_ok() { + decoded_now(); + } }); if let Err(Error::Stalled(_)) = &ran { let works = import.works(); diff --git a/crates/reims-vgpu/src/graphics.rs b/crates/reims-vgpu/src/graphics.rs index 75a79f016..7bed7d359 100644 --- a/crates/reims-vgpu/src/graphics.rs +++ b/crates/reims-vgpu/src/graphics.rs @@ -136,8 +136,8 @@ use crate::graphics::completion::cb_failed; use crate::graphics::decode::shares::ListenSink; use crate::graphics::decode::worker::{Job, Settle, Unsettled, Worker}; use crate::graphics::decode::{ - Begun, CompletionSink, DecodeError, Decoders, DrainAnswer, GraphicsDecoder, Joined, LibraryJob, - LibraryStart, MadeLibrary, PipelineJob, PipelineReply, ReflectionSink, ScheduledSink, + AheadSinks, Begun, CompletionSink, DecodeError, Decoders, DrainAnswer, FinishedSink, + GraphicsDecoder, Joined, LibraryJob, LibraryStart, MadeLibrary, PipelineJob, PipelineReply, ReflectionSink, ScheduledSink, SignalSink, Sinks, SubmittedSink, SurfacePresent, Then, compile_refusing, complete, make_library, refused_reply, refusing, }; @@ -2469,12 +2469,26 @@ impl GraphicsControl

{ let reflection: ReflectionSink = Arc::new(move |reply: PipelineReply| { reflection_poster.post(&reply.bytes()); }); + // A completion posted at its decode shows no present: one waiting for the buffer is shown + // at its end, once its decode's copy is done. + let ahead = queue.map(|queue| { + let ahead_poster = poster.clone(); + let post: CompletionSink = Arc::new(move |record: RgfxCbComplete, then: Then| { + ahead_poster.post_unwaiting(record.as_bytes(), Some(then)); + }); + let (presents, finished_poster) = (Arc::clone(&self.presents), poster.clone()); + let finished: FinishedSink = Arc::new(move |seqno| { + presents.finished(queue, seqno, &finished_poster); + }); + AheadSinks { post, finished } + }); Sinks { completion: Some(completion), signal: Some(signal), scheduled: Some(scheduled), submitted: Some(submitted), reflection: Some(reflection), + ahead, } } @@ -2482,9 +2496,10 @@ impl GraphicsControl

{ /// thread ([`Self::begin_command_buffer`]): made at the queue's first buffer, and shared by /// each buffer after it whose poster posts as theirs does ([`CompletionPoster::posts_as`]). /// What sinks post depends on their poster and the presents alone, so shared ones post what - /// new ones would. Made at each begin, they cost the begin five closures and six posters - /// (measured: 0.30 us of a buffer's 14.9 us from its take to its begin on an Iris Xe's queue - /// thread, in Geekbench 7's Super Resolution), and its lane their release after the walk. + /// new ones would. Made at each begin, they would cost the begin seven closures and eight + /// posters (measured with five and six: 0.30 us of a buffer's 14.9 us from its take to its + /// begin on an Iris Xe's queue thread, in Geekbench 7's Super Resolution), and its lane their + /// release after the walk. fn queue_sinks(&self, poster: &CompletionPoster) -> Sinks { let Some(queue) = poster.queue_obj_id() else { return self.sinks(poster); diff --git a/crates/reims-vgpu/src/graphics/decode/cmdbuf.rs b/crates/reims-vgpu/src/graphics/decode/cmdbuf.rs index 858bcd3c9..0ecab1aa7 100644 --- a/crates/reims-vgpu/src/graphics/decode/cmdbuf.rs +++ b/crates/reims-vgpu/src/graphics/decode/cmdbuf.rs @@ -161,6 +161,7 @@ use zerocopy::{FromBytes, IntoBytes}; use super::super::completion::{cb_complete, cb_failed, cb_unlanded}; use super::commit_order::Until; +use super::completions::{CompletionTurn, Completions, Post}; use super::helpers::{Hand, Slots}; use super::lane::{Lane, Turn}; use super::sequencer::Ticket; @@ -168,11 +169,12 @@ use super::shares::FanOut; use super::split::{Estimate, PACE_WAIT_MOST, Parts, Progress, QueueRate, SplitHold}; use super::surface_cache::shapes::ShapeRef; use super::surface_cache::{Reach, Uses}; -use super::surface_order::{Marks, Signalled}; +use super::surface_order::{AheadEntry, Marks, Signalled}; use super::tables::{FOUND_A_HOLD, QueueCounts}; use super::{ - DecodeError, Decoders, Drain, GraphicsDecoder, ObjHandle, ScheduledSink, SignalSink, - SubmittedSink, blit, compute, context_of, op_fault, read, refused, refusing, render, video, + DecodeError, Decoders, Drain, FinishedSink, GraphicsDecoder, ObjHandle, ScheduledSink, + SignalSink, SubmittedSink, Then, blit, compute, context_of, op_fault, read, refused, refusing, + render, video, }; /// The op stream runs under a live raise handler (the ring loop's), so an encode's @@ -893,6 +895,78 @@ pub(crate) struct Begun { /// It holds a video encoder, so it is walked in its turn: its session's work starts as it is /// walked, and so in its queue's order. ordered: bool, + /// Its queue's turns of their completion posts ([`super::completions`]). + completions: Arc, + /// The blocks of its decode's output, where it is a decode alone that may post its completion + /// at its decode ([`ahead_at_decode`]). + ahead: Option>, +} + +/// A command buffer's turn of its completion post, taken by the first of its completion handler +/// and its post at its decode ([`video::Landed`]), which posts its record. +type TurnCell = Arc>>; + +/// What a command buffer's completion handler ends besides its record: its turn of its completion +/// post ([`TurnCell`]), and, where it may post its completion at its decode, its decode's place +/// among those completed ahead of their ends ([`super::surface_order::CompletedAhead`]) and what +/// its end tells once that post is on its ring ([`BothDone`], [`super::AheadSinks::finished`]). +struct Ending { + turn: TurnCell, + entry: Option>, + after: Option<(Arc, FinishedSink)>, +} + +impl Ending

{ + /// The ending of a command buffer whose turn is `turn`, and that holds no decode completed + /// ahead. + fn of(turn: CompletionTurn) -> Self { + Ending { + turn: Arc::new(Mutex::new(Some(turn))), + entry: None, + after: None, + } + } +} + +/// What runs once both a command buffer's completion posted at its decode is on its ring and its +/// platform end has come, run by the later of the two ([`GraphicsDecoder::post_at_decode`]): the +/// end's notice to what waits for the buffer, and the release of its context's drain, each after +/// the record, as for a buffer whose handler posts it. +#[derive(Default)] +struct BothDone(Mutex>>); + +impl BothDone { + /// One of the two came, with what it runs (`None` for the post): runs it and the other's, + /// where the other came first. + fn came(&self, then: Option) { + let first = { + let mut state = self.0.lock(); + match state.take() { + Some(first) => first, + None => { + *state = Some(then); + return; + } + } + }; + for then in [first, then].into_iter().flatten() { + then(); + } + } +} + +/// Whether the op stream `take` read may post its completion at its decode, ahead of its platform +/// end ([`video::Landed`]; the module docs of [`video`], "Completed at the decode"): a decode alone, +/// no other video op, no render, compute or blit work, and no event's wait or signal, so nothing +/// but the decode's picture is the guest's at its end. +fn ahead_at_decode(take: &Take) -> Option<(u64, u64)> { + let alone = take.video + && !take.work + && !take.waits + && !take.signals + && take.video_ops == 1 + && take.decodes.len() == 1; + alone.then(|| take.decodes[0]) } impl Begun

{ @@ -1107,6 +1181,8 @@ struct Take { uses: Vec, /// The stream holds a `WAIT_EVENT`, of an event the host holds or not. waits: bool, + /// The stream holds a `SIGNAL_EVENT`. + signals: bool, /// The stream holds a `SUBMITTED`. asks: bool, /// The buffers of other queues its first `SURFACE_ORDER` names, where it holds one. @@ -1124,6 +1200,8 @@ struct Take { predicates: bool, /// The luma and chroma textures of each of its decodes, in stream order. decodes: Vec<(u64, u64)>, + /// How many video ops (decodes and encodes) it holds. + video_ops: usize, /// The `Managed` buffers its first `UPLOADS_WRITTEN` names, with the bytes the buffer wrote /// in each, which its begin brings to their GPU copies ([`GraphicsDecoder::uploads_written`]); /// empty where it holds none. @@ -1160,6 +1238,7 @@ fn take(mut ops: &[u8]) -> Take { } } RGFX_OP_WAIT_EVENT => out.waits = true, + RGFX_OP_SIGNAL_EVENT => out.signals = true, RGFX_OP_SUBMITTED => out.asks = true, RGFX_OP_SURFACE_ORDER if out.order.is_none() => { let body = &ops[RGFX_OP_BODY_OFFSET as usize..len]; @@ -1200,6 +1279,7 @@ fn take(mut ops: &[u8]) -> Take { RGFX_OP_GROUP_VIDEO => { let body = &ops[RGFX_OP_BODY_OFFSET as usize..len]; out.decodes.extend(video::decode_textures(tag, body)); + out.video_ops += 1; } _ => {} }, @@ -1885,25 +1965,38 @@ impl GraphicsDecoder

{ let (fill_waits, follows, uses) = (self.surface_caches).before_answering(device, &cb, &take.uses, &reach, answer)?; // The buffers of other queues it runs after, on the GPU, kept for the work the host starts - // off it (`surface_order`). - let order_waits = match &take.order { - Some(waits) => { - let now = self.shared.platform.clock().now_mono(); + // off it (`surface_order`): those its op names, and the decodes completed ahead of their + // ends whose outputs it uses, which the guest's slots no longer name. + let kept = &self.shared.completed_ahead; + let order_waits = if take.order.is_some() || (kept.any() && !take.uses.is_empty()) { + let now = self.shared.platform.clock().now_mono(); + let blocks = take.uses.iter().map(|u| u.block_offset); + let ahead = kept.waits_for(m.queue_obj_id, blocks, now); + if take.order.is_some() || !ahead.is_empty() { (self.shared.surface_order.lock()).before( device, m.queue_obj_id, &cb, - waits, + (take.order.as_deref(), &ahead), + kept, now, )? + } else { + Vec::new() } - None => Vec::new(), + } else { + Vec::new() }; let waits_for_order = !order_waits.is_empty(); *self.order_waits.borrow_mut() = order_waits; // Those GPU waits hold back none of its records, nor its queue ([`Line`]), and nor do the // fills of caches made at its begin: only an event's wait, or a deferred copy's, does. let (behind, held) = hold(counts, follows || take.waits); + // A decode alone over device caches may post its completion at its decode. + let ahead = (ahead_at_decode(&take)) + .filter(|_| uses.is_some() && self.sinks.ahead.is_some()) + .map(|(luma, chroma)| self.decode_blocks(luma, chroma)) + .filter(|blocks| !blocks.is_empty()); let begun = Begun { queue_obj_id: m.queue_obj_id, queue: (take.video && uses.is_some()).then(|| queue.clone_ref()), @@ -1925,6 +2018,8 @@ impl GraphicsDecoder

{ behind, drain, ordered: take.video, + completions: Arc::clone(&counts.completions), + ahead, }; // A thread of its process that waits for it to be scheduled may ask for its record from // now, where it would have got it here had it asked for its `CB_SUBMITTED`. @@ -1974,6 +2069,8 @@ impl GraphicsDecoder

{ behind, drain, ordered, + completions, + ahead, .. } = begun; let Some(ops) = read::(message).and_then(|m| ops_of(message, &m)) else { @@ -2056,10 +2153,41 @@ impl GraphicsDecoder

{ // completion makes the buffer's. let (parts, split_hold) = split.map_or((None, None), |s| (s.parts, s.hold)); // After the buffers of its queue taken before it ([`super::lane`]): its signal of its - // queue's surface timeline is decided in its ring's order ([`Self::order_signal`]). + // queue's surface timeline is decided in its ring's order ([`Self::order_signal`]), and + // its turn of its completion post taken in its commit order. self.wait_turn(); - let signalled = self.order_signal(device, queue_obj_id, &marks, seqno, order, &cb)?; + let turn = completions.turn(); + // A decode alone over device caches posts its completion at its decode where it waits + // for nothing and is walked whole: it signals its queue's surface timeline, which the + // buffers of other queues that use its output then wait for, as they would for a buffer + // they named ([`super::surface_order`], "A decode completed ahead of its end"). + let ahead = ahead.filter(|_| { + held.is_none() + && !behind + && parts.is_none() + && events.signals.0.is_none() + && events.waits.is_empty() + && events.landings.len() == 1 + }); + let names = order || ahead.is_some(); + let signalled = self.order_signal(device, queue_obj_id, &marks, seqno, names, &cb)?; let signal_committed = signalled.as_ref().map(Signalled::committed); + let ahead = ahead.filter(|_| signalled.is_some()); + let landed = ahead.as_ref().and_then(|_| events.landings.first().cloned()); + let entry = ahead.map(|blocks| { + (self.shared.completed_ahead).enter(&self.shared.platform, blocks, queue_obj_id, seqno) + }); + let after = (self.sinks.ahead.as_ref()) + .filter(|_| landed.is_some()) + .map(|sinks| (Arc::new(BothDone::default()), Arc::clone(&sinks.finished))); + let ending = Ending { + turn: Arc::new(Mutex::new(Some(turn))), + entry, + after, + }; + let at_decode = (ending.after.as_ref()).map(|(both, _)| { + self.post_at_decode(cb_obj_id, seqno, (&ending.turn, both), &line, scheduled.clone()) + }); // Register the submission and completion paths and commit: no scheduled or completed // handler, so the platform posts the buffer's records from the threads that submit it // and see it complete, waking no handler thread; and none to submit where its records @@ -2080,6 +2208,7 @@ impl GraphicsDecoder

{ drain, false, (submitted, held.clone(), scheduled), + ending, ); let handler = signalling(handler, signalled); let handler = completed_with(handler, order_hold.clone()); @@ -2151,11 +2280,57 @@ impl GraphicsDecoder

{ line.post_through(&scheduled); } } + // Its completion goes at its decode from now, where it goes there: at once where the + // decode is done already. + if let (Some(landed), Some(at_decode)) = (landed, at_decode) { + landed.arm(at_decode); + } // cbwalked: queue, seqno: its walk and its last commit are done (`cenc`) reims_vgpu_vulkan::core::trace::event("cbwalked", &[queue_obj_id, seqno]); Ok(Ok(())) } + /// The post of command buffer `cb_obj_id`'s completion, at `seqno`, at its decode + /// ([`video::Landed::arm`]), where it takes its `turn` before its completion handler: the + /// records of its queue's buffers committed up to it that are not yet posted go first, in + /// `line`'s order, its own `scheduled` among them, then its `CB_COMPLETE` in its turn, with no + /// GPU times (0 for each), and failed where its picture failed already, through the sink of + /// such posts ([`super::AheadSinks::post`]), telling `both` once it is on the ring. Its + /// completion handler then posts no record ([`Self::completed_handler`]). + fn post_at_decode( + &self, + cb_obj_id: u64, + seqno: u64, + (turn, both): (&TurnCell, &Arc), + line: &Arc, + scheduled: Option>, + ) -> video::EarlyPost { + let turn = Arc::clone(turn); + let both = Arc::clone(both); + let line = Arc::clone(line); + let sink = self.sinks.ahead.as_ref().map(|a| Arc::clone(&a.post)); + let kept = Arc::clone(&self.shared.completed_ahead); + Box::new(move |landed: Arc| { + let Some(turn) = turn.lock().take() else { + return; + }; + let failed = landed.post().unwrap_or(false); + if let Some(scheduled) = &scheduled { + line.post_through(scheduled); + } + let record = match failed { + true => cb_unlanded(cb_obj_id, seqno, 0, 0), + false => cb_complete(cb_obj_id, seqno, 0, 0, None), + }; + kept.posted(); + let post: Post = Box::new(move || match &sink { + Some(sink) => sink(record, Box::new(move || both.came(None))), + None => both.came(None), + }); + turn.finish(Some(post)); + }) + } + /// The `CB_SUBMITTED` of command buffer `cb_obj_id`, at `seqno`, where it `asks` for one and /// there is a sink: posted already where the answer on a doorbell's thread posted it. fn submitted(&self, cb_obj_id: u64, seqno: u64, asks: bool) -> Option> { @@ -2258,8 +2433,10 @@ impl GraphicsDecoder

{ let held = Arc::clone(held); cb.add_submission_handler(ON, Box::new(move || held.release()))?; } - // In its queue's order ([`super::lane`]): its signal, and its commit. + // In its queue's order ([`super::lane`]): its signal, its turn of its completion post, + // and its commit. self.wait_turn(); + let turn = counts.completions.turn(); let signalled = self.order_signal(device, queue_obj_id, &counts.order, seqno, names, &cb)?; let signal_committed = signalled.as_ref().map(Signalled::committed); @@ -2270,6 +2447,7 @@ impl GraphicsDecoder

{ drain, true, (None, held.clone(), None), + Ending::of(turn), ); let handler = signalling(handler, signalled); cb.add_completion_seen_handler(ON, leaving(handler, in_flight.commits()))?; @@ -2391,7 +2569,11 @@ impl GraphicsDecoder

{ /// events to that no notification posted ([`Signals::finish`]), then its completion, which /// for a `stand_in` ([`Self::stand_in_for_failed`]) is its failure whatever the stand-in's /// outcome, and for a buffer one of whose decodes' pictures did not land is its failure too - /// ([`cb_unlanded`]), and lets `drain` (its context's) go. + /// ([`cb_unlanded`]), in its turn of its queue's completion posts ([`super::completions`]), + /// and lets `drain` (its context's) go. Where its post at its decode took its turn first + /// ([`Self::post_at_decode`]), it posts no record; and its decode leaves those completed ahead + /// of their ends as it ends (`ending`). + #[allow(clippy::too_many_arguments)] fn completed_handler( &self, cb_obj_id: u64, @@ -2400,6 +2582,7 @@ impl GraphicsDecoder

{ drain: Option>, stand_in: bool, (submitted, held, scheduled): Unposted, + ending: Ending

, ) -> CompletedHandler { let sink = self.sinks.completion.clone(); let context = self.context; @@ -2439,12 +2622,34 @@ impl GraphicsDecoder

{ // buffer that failed may have signalled them before its fault, and a guest waiting // for one would wait for good: each is posted whatever the outcome. signals.finish(); + let Ending { turn, entry, after } = ending; + // Posted at its decode: the record is the guest's, or is on its way there in its turn, + // and its buffer's work is done now. What waits for its end is told once both are. + let Some(turn) = turn.lock().take() else { + drop(entry); + let both = after.as_ref().map(|(both, _)| Arc::clone(both)); + let end: Then = Box::new(move || { + if let Some((_, finished)) = &after { + finished(seqno); + } + drop(drain); + }); + match both { + Some(both) => both.came(Some(end)), + None => end(), + } + return; + }; // The GPU times on the device's clock, the one the guest's kext maps the device's // times by; none is 0 for each. let (start, end) = info.gpu_times_ns.map(runtime::gpu_times).unwrap_or((0, 0)); + // Each decode's outcome is fixed as posted here ([`video::Landed::post`]). + let unlanded = (landings.iter()).fold(false, |any, landed| { + landed.post().unwrap_or_else(|| landed.failed()) | any + }); let record = if stand_in { cb_failed(cb_obj_id, seqno) - } else if info.error.is_none() && landings.iter().any(|landed| landed.failed()) { + } else if info.error.is_none() && unlanded { cb_unlanded(cb_obj_id, seqno, start, end) } else { cb_complete(cb_obj_id, seqno, start, end, info.error.as_ref()) @@ -2461,10 +2666,12 @@ impl GraphicsDecoder

{ } // The buffer's work and its completion are done: a drain of its context may end, // once the record is on the guest's ring. - match &sink { + let post: Post = Box::new(move || match &sink { Some(sink) => sink(record, Box::new(move || drop(drain))), None => drop(drain), - } + }); + turn.finish(Some(post)); + drop(entry); }) } @@ -4717,6 +4924,11 @@ mod tests { unlanded: std::sync::atomic::AtomicBool, /// Each decode answers no picture, as for one the stream's random access skips. skipped: std::sync::atomic::AtomicBool, + /// Each decode's [`Landed`], which a test tells of the decode done ([`Landed::decoded`]). + landings: Mutex>>, + /// Each decode tells of itself done before it answers, as a session whose decode ended + /// before its command buffer's commit does. + decoded_at_once: std::sync::atomic::AtomicBool, } /// A fake host's video of H.264 and HEVC decode, recording into its [`VideoSeen`]; each of @@ -4802,6 +5014,10 @@ mod tests { if self.seen.unlanded.load(Ordering::Relaxed) { landed.fail(); } + if self.seen.decoded_at_once.load(Ordering::Relaxed) { + landed.decoded(); + } + self.seen.landings.lock().push(Arc::clone(&landed)); Ok(Decoded { value: self.decodes.fetch_add(1, Ordering::Relaxed) as u64 + 1, skipped: self.seen.skipped.load(Ordering::Relaxed), @@ -5520,6 +5736,312 @@ mod tests { .0 } + /// The `CB_COMPLETE` records a sink took: each one's buffer, status and GPU times. + type Records = Arc>>; + + /// Each record's buffer, status and GPU times. + fn posted(records: &Records) -> Vec<(u64, u32, u64, u64)> { + (records.lock().iter()) + .map(|r| (r.cb_obj_id, r.status, r.gpu_start_ns, r.gpu_end_ns)) + .collect() + } + + /// [`cached_video_whole`]'s rig with queue 9 too, its `CB_COMPLETE` records taken, and the + /// seqnos of the ends told of buffers whose completions went at their decodes + /// ([`super::super::AheadSinks::finished`]). + fn video_posting() -> ( + super::super::surface_pages::tests::Rig, + Arc, + Records, + Arc>>, + ) { + let (mut r, seen) = cached_video_whole(); + let records = Records::default(); + let sink = Arc::clone(&records); + (r.dec).set_completion_sink(Arc::new(move |record| sink.lock().push(record))); + let ends = Arc::new(Mutex::new(Vec::new())); + let sink = Arc::clone(&ends); + (r.dec).set_finished_sink(Arc::new(move |seqno| sink.lock().push(seqno))); + let queue = RgfxQueueCreate { + header: RgfxMsgHeader { + r#type: RGFX_CMD_QUEUE_CREATE, + size: size_of::() as u32, + seqno: 0, + }, + obj_id: 9, + ..RgfxQueueCreate::default() + }; + assert_eq!(r.dec.decode(&r.device, queue.as_bytes()).unwrap(), Ok(())); + (r, seen, records, ends) + } + + /// `message`, a `COMMAND_BUFFER`, on queue `queue`. + fn on_queue(mut message: Vec, queue: u64) -> Vec { + let at = std::mem::offset_of!(RgfxCommandBuffer, queue_obj_id); + message[at..at + 8].copy_from_slice(&queue.to_le_bytes()); + message + } + + /// The `COMMAND_BUFFER` `cb_obj_id` at `seqno` on queue 9 of [`video_posting`]'s rig that + /// reads its block and holds nothing else. + fn reads_cached_video(cb_obj_id: u64, seqno: u64) -> Vec { + use super::super::surface_pages::tests::BLOCK; + use reims_vgpu_graphics::ops::{RGFX_OP_SURFACE_USE, RgfxOpSurfaceUse}; + + let surface_use = RgfxOpSurfaceUse { + block_offset: BLOCK, + cpu_gen: 0, + flags: 0, + reserved_14: 0, + }; + let ops = op(RGFX_OP_SURFACE_USE, surface_use.as_bytes()); + on_queue(command_buffer_message(cb_obj_id, seqno, &ops), 9) + } + + /// Each `encodeSignalEvent:value:` and `encodeWaitForEvent:value:` since `mark`: whether it + /// signals, its event's id and its value. + fn event_calls(r: &super::super::surface_pages::tests::Rig, mark: u64) -> Vec<(bool, u64, u64)> { + (r.p.call_log().since(mark).iter()) + .filter_map(|c| { + let signals = if c.sel == "encodeSignalEvent:value:" { + true + } else if c.sel == "encodeWaitForEvent:value:" { + false + } else { + return None; + }; + let event = c.args.first().and_then(Arg::as_obj).map_or(0, |o| o.0); + Some((signals, event, c.args.get(1).and_then(Arg::as_u64).unwrap_or(0))) + }) + .collect() + } + + /// A command buffer of a decode alone into device caches posts its `CB_COMPLETE` as its + /// session tells of the decode done, with no GPU times, ahead of its platform end, and posts + /// no second record at that end. Everything else moves at the end: its context's drain, its + /// place among its queue's buffers in flight, its decode's place among those kept by their + /// blocks, and the notice of its end, which the host's presents waiting for it take + /// ([`super::super::AheadSinks::finished`]). + #[test] + fn a_decode_alone_into_caches_completes_at_its_decode_and_ends_at_its_end() { + use super::super::surface_pages::tests::BLOCK; + + let (r, seen, records, ends) = video_posting(); + let in_flight = |r: &super::super::surface_pages::tests::Rig| { + let counts = r.dec.queue_counts(1).unwrap(); + counts.in_flight.load(Ordering::Acquire) + }; + // Walked for context 0, whose drain then holds it. + let mut walker = r.dec.sender(Some(0), r.dec.sinks.clone()); + assert_eq!( + walker + .decode(&r.device, &writes_cached_video(100, 1, true)) + .unwrap(), + Ok(()) + ); + walker.end_message(); + let drained = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let set = Arc::clone(&drained); + drop(r.dec.drain_context( + 0, + false, + Box::new(move || set.store(true, Ordering::SeqCst)), + )); + assert!(posted(&records).is_empty(), "the decode is not done"); + let landed = Arc::clone(&seen.landings.lock()[0]); + landed.decoded(); + assert_eq!(posted(&records), [(100, RGFX_CB_OK, 0, 0)]); + assert!(ends.lock().is_empty()); + assert!(!drained.load(Ordering::SeqCst)); + assert_eq!(in_flight(&r), 1); + assert!(r.dec.shared.completed_ahead.holds(BLOCK)); + assert_eq!(r.dec.shared.completed_ahead.posts(), 1); + + r.p.world().complete_all(CompleteOn::Caller); + assert_eq!(posted(&records).len(), 1, "no second record"); + assert_eq!(*ends.lock(), [1]); + assert!(drained.load(Ordering::SeqCst)); + assert_eq!(in_flight(&r), 0); + assert!(!r.dec.shared.completed_ahead.holds(BLOCK)); + } + + /// A completion posted at a decode keeps its queue's order: behind a buffer of the queue + /// committed before it whose record its platform end posts, and posted at the buffer's commit + /// where its decode was done before it. (The buffer before it holds no op: one that used the + /// decode's block would hold the decode's start, on the CPU, until its end.) + #[test] + fn a_completion_at_a_decode_goes_in_its_queues_order() { + let (mut r, seen, records, ends) = video_posting(); + assert_eq!( + r.dec + .decode(&r.device, &command_buffer_message(100, 1, &[])) + .unwrap(), + Ok(()) + ); + let first = r.p.world().committed(); + seen.decoded_at_once.store(true, Ordering::Relaxed); + assert_eq!( + r.dec + .decode(&r.device, &writes_cached_video(101, 2, true)) + .unwrap(), + Ok(()) + ); + assert!(posted(&records).is_empty(), "behind buffer 100"); + assert_eq!(seen.landings.lock().len(), 1); + for id in first { + r.p.world().complete(id, CommandBufferStatus::COMPLETED, None, CompleteOn::Caller); + } + assert_eq!( + (posted(&records).iter()) + .map(|&(cb, status, ..)| (cb, status)) + .collect::>(), + [(100, RGFX_CB_OK), (101, RGFX_CB_OK)] + ); + assert_eq!(posted(&records)[1], (101, RGFX_CB_OK, 0, 0)); + assert!(ends.lock().is_empty(), "buffer 101's end is to come"); + r.p.world().complete_all(CompleteOn::Caller); + assert_eq!(posted(&records).len(), 2); + assert_eq!(*ends.lock(), [2]); + } + + /// A buffer of another queue that uses a decode's output, begun after the decode's + /// completion went at its decode, which the guest's slots then name no more, waits on the GPU + /// for the decode's buffer's end as for a buffer it named: for the value of the decode's + /// queue's timeline the decode's buffer signals. Counted as a buffer held; one begun after + /// that end waits for nothing. + #[test] + fn a_reader_of_a_decode_completed_ahead_waits_on_the_gpu_for_its_end() { + let (mut r, seen, records, _) = video_posting(); + let mark = r.p.call_log().mark(); + assert_eq!( + r.dec + .decode(&r.device, &writes_cached_video(100, 1, true)) + .unwrap(), + Ok(()) + ); + let signals: Vec<_> = (event_calls(&r, mark).into_iter()) + .filter(|&(signals, ..)| signals) + .collect(); + Arc::clone(&seen.landings.lock()[0]).decoded(); + assert_eq!(posted(&records).len(), 1); + let mark = r.p.call_log().mark(); + assert_eq!( + r.dec.decode(&r.device, &reads_cached_video(200, 1)).unwrap(), + Ok(()) + ); + let waits = |r: &super::super::surface_pages::tests::Rig, mark| { + (event_calls(r, mark).into_iter()) + .filter(|&(signals, ..)| !signals) + .collect::>() + }; + let waited = waits(&r, mark); + assert_eq!(waited.len(), 1, "{waited:?}"); + let (_, event, value) = waited[0]; + assert!( + signals.contains(&(true, event, value)), + "the decode's buffer signals {event} to {value} at its end: {signals:?}" + ); + assert_eq!(r.dec.shared.surface_order.lock().counts().held, 1); + + r.p.world().complete_all(CompleteOn::Caller); + let mark = r.p.call_log().mark(); + assert_eq!( + r.dec.decode(&r.device, &reads_cached_video(201, 2)).unwrap(), + Ok(()) + ); + assert!(waits(&r, mark).is_empty(), "its end has come"); + } + + /// A video decode of another queue into a decode's output, begun after the decode's + /// completion went at its decode, waits on the CPU for the decode's buffer's end before its + /// session's work starts, as it would for a buffer it named. + #[test] + fn a_decode_after_a_decode_completed_ahead_waits_on_the_cpu_for_its_end() { + let (mut r, seen, records, _) = video_posting(); + assert_eq!( + r.dec + .decode(&r.device, &writes_cached_video(100, 1, true)) + .unwrap(), + Ok(()) + ); + Arc::clone(&seen.landings.lock()[0]).decoded(); + assert_eq!(posted(&records).len(), 1); + let message = on_queue(writes_cached_video(200, 1, true), 9); + let mut walker = r.dec.sender(None, super::super::Sinks::default()); + std::thread::scope(|scope| { + let walk = scope.spawn(|| walker.decode(&r.p.device(), &message).unwrap()); + std::thread::sleep(std::time::Duration::from_millis(100)); + assert_eq!(seen.decodes.lock().len(), 1, "it waits for buffer 100's end"); + r.p.world().complete_all(CompleteOn::Caller); + assert_eq!(walk.join().unwrap(), Ok(())); + }); + assert_eq!(seen.decodes.lock().len(), 2); + } + + /// A lock's download of a decode's output asked after the decode's completion went at its + /// decode copies the cache out once the decode's buffer has ended: its copy waits on the GPU + /// for the value the decode's buffer signals at its end, with no wait of its own added. + #[test] + fn a_download_after_a_decode_completed_ahead_copies_after_its_end() { + use super::super::surface_pages::tests::BLOCK; + + let (mut r, seen, records, _) = video_posting(); + let mark = r.p.call_log().mark(); + assert_eq!( + r.dec + .decode(&r.device, &writes_cached_video(100, 1, true)) + .unwrap(), + Ok(()) + ); + let signals: Vec<_> = (event_calls(&r, mark).into_iter()) + .filter(|&(signals, ..)| signals) + .collect(); + Arc::clone(&seen.landings.lock()[0]).decoded(); + assert_eq!(posted(&records).len(), 1); + let mark = r.p.call_log().mark(); + let done = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let set = Arc::clone(&done); + r.dec.surface_download( + &r.device, + BLOCK, + Box::new(move || set.store(true, Ordering::SeqCst)), + super::super::no_raise(), + ); + let waits = event_calls(&r, mark); + assert!( + (waits.iter()).any(|&(s, event, value)| !s && signals.contains(&(true, event, value))), + "the copy waits for the decode's buffer's end: {waits:?} {signals:?}" + ); + assert!(!done.load(Ordering::SeqCst)); + r.p.world().complete_all(CompleteOn::Caller); + assert!(done.load(Ordering::SeqCst)); + } + + /// A present of a decode's output asked after the decode's completion went at its decode, + /// whose writers the guest's slots no longer name, waits for the decode's buffer as for a + /// writer named: until its end. Counted. (The rig's guest names no writers at all.) + #[test] + fn a_present_after_a_decode_completed_ahead_waits_for_its_end() { + let (mut r, seen, records, _) = video_posting(); + assert_eq!( + r.dec + .decode(&r.device, &writes_cached_video(100, 1, true)) + .unwrap(), + Ok(()) + ); + let writers = |r: &super::super::surface_pages::tests::Rig| { + (r.dec.surface_present(0x99).unwrap().writers.iter()) + .map(|w| (w.queue_obj_id, w.seqno)) + .collect::>() + }; + Arc::clone(&seen.landings.lock()[0]).decoded(); + assert_eq!(posted(&records).len(), 1); + assert_eq!(writers(&r), [(1, 1)]); + assert_eq!(r.dec.shared.completed_ahead.presents_held(), 1); + r.p.world().complete_all(CompleteOn::Caller); + assert!(writers(&r).is_empty()); + } + /// A decoder's new output, a command buffer of a decode alone whose textures are the whole of /// the surface's two planes, takes no fill of its cache: the cache made as zeros, the decode /// waits for those, its picture lands over them, and nothing is copied in from the pages. The @@ -6068,6 +6590,7 @@ mod tests { None, false, (submitted, None, scheduled), + Ending::of(Arc::new(Completions::default()).turn()), ); let submission = submission.unwrap(); if ran { diff --git a/crates/reims-vgpu/src/graphics/decode/completions.rs b/crates/reims-vgpu/src/graphics/decode/completions.rs new file mode 100644 index 000000000..adec2827f --- /dev/null +++ b/crates/reims-vgpu/src/graphics/decode/completions.rs @@ -0,0 +1,163 @@ +//! A queue's order of `CB_COMPLETE` records, which the guest takes as its command buffers' +//! completion order on the queue, as Metal completes a queue's buffers in their commit order. +//! +//! A command buffer takes a turn in its queue's [`Completions`] in its commit order (in its turn +//! in its queue's lane, [`super::lane`]), and finishes it with the post of its record +//! ([`CompletionTurn::finish`]): a post runs once every turn before it has finished, in turn +//! order, one at a time, on the thread that finished the turn at the front or the turn that let it +//! run. The platform completes a queue's buffers in their commit order, so a buffer's turn is at +//! the front by its completion handler, and its post runs there; the order holds a post back only +//! where a buffer posts its completion ahead of its platform end, at its decode +//! ([`super::video::Landed`], "Completed at the decode" in its module docs), behind a buffer +//! committed before it whose own is still to come. A turn let go of unfinished (its buffer never +//! committed, or its handler dropped) finishes with no post. + +use std::collections::BTreeMap; +use std::sync::Arc; + +use reims_vgpu_vulkan::core::sync::Mutex; + +/// A record's post, run in its turn. +pub(crate) type Post = Box; + +/// A queue's turns of completion posts (the module docs). +#[derive(Default)] +pub(crate) struct Completions(Mutex); + +/// [`Completions`]' state. +#[derive(Default)] +struct Turns { + /// The next turn to give. + given: u64, + /// The turn whose post runs next. + front: u64, + /// The turns finished past the front, with their posts. + ahead: BTreeMap>, + /// A thread runs the posts at the front. + running: bool, +} + +/// A command buffer's turn in its queue's [`Completions`], finished once: by +/// [`Self::finish`], or with no post as it is dropped. +pub(crate) struct CompletionTurn { + line: Arc, + at: u64, + finished: bool, +} + +impl Completions { + /// The next turn, after every turn given before it. + pub(crate) fn turn(self: &Arc) -> CompletionTurn { + let mut turns = self.0.lock(); + let at = turns.given; + turns.given += 1; + CompletionTurn { + line: Arc::clone(self), + at, + finished: false, + } + } + + /// Turn `at` finished with `post`: runs it, and each finished turn after it, where it is at + /// the front and no thread runs them; else leaves it to the thread that does. + fn finish(&self, at: u64, post: Option) { + let mut turns = self.0.lock(); + if turns.running || at != turns.front { + turns.ahead.insert(at, post); + return; + } + turns.running = true; + turns.front += 1; + drop(turns); + let mut next = post; + loop { + if let Some(post) = next.take() { + post(); + } + let mut turns = self.0.lock(); + let front = turns.front; + match turns.ahead.remove(&front) { + Some(post) => { + turns.front += 1; + next = post; + } + None => { + turns.running = false; + return; + } + } + } + } + + /// How many turns finished past the front wait for it (for the tests). + #[cfg(test)] + pub(crate) fn waiting(&self) -> usize { + self.0.lock().ahead.len() + } +} + +impl CompletionTurn { + /// Finishes the turn with `post`, which runs once every turn before it has finished. + pub(crate) fn finish(mut self, post: Option) { + self.finished = true; + self.line.finish(self.at, post); + } +} + +impl Drop for CompletionTurn { + fn drop(&mut self) { + if !self.finished { + self.line.finish(self.at, None); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn noting(log: &Arc>>, n: u32) -> Option { + let log = Arc::clone(log); + Some(Box::new(move || log.lock().push(n))) + } + + #[test] + fn posts_run_in_turn_order_whatever_order_their_turns_finish_in() { + let line = Arc::new(Completions::default()); + let log = Arc::new(Mutex::new(Vec::new())); + let (a, b, c) = (line.turn(), line.turn(), line.turn()); + c.finish(noting(&log, 3)); + b.finish(noting(&log, 2)); + assert!(log.lock().is_empty(), "both wait for the first"); + assert_eq!(line.waiting(), 2); + a.finish(noting(&log, 1)); + assert_eq!(*log.lock(), [1, 2, 3]); + assert_eq!(line.waiting(), 0); + line.turn().finish(noting(&log, 4)); + assert_eq!(*log.lock(), [1, 2, 3, 4], "a turn at the front posts at once"); + } + + #[test] + fn a_turn_dropped_unfinished_lets_the_turns_after_it_post() { + let line = Arc::new(Completions::default()); + let log = Arc::new(Mutex::new(Vec::new())); + let (a, b) = (line.turn(), line.turn()); + b.finish(noting(&log, 2)); + drop(a); + assert_eq!(*log.lock(), [2]); + } + + #[test] + fn a_post_that_finishes_a_later_turn_runs_it_after_itself() { + let line = Arc::new(Completions::default()); + let log = Arc::new(Mutex::new(Vec::new())); + let (a, b) = (line.turn(), line.turn()); + let inner = noting(&log, 2); + let l = Arc::clone(&log); + a.finish(Some(Box::new(move || { + b.finish(inner); + l.lock().push(1); + }))); + assert_eq!(*log.lock(), [1, 2]); + } +} diff --git a/crates/reims-vgpu/src/graphics/decode/mod.rs b/crates/reims-vgpu/src/graphics/decode/mod.rs index 3588ea812..52c6422b2 100644 --- a/crates/reims-vgpu/src/graphics/decode/mod.rs +++ b/crates/reims-vgpu/src/graphics/decode/mod.rs @@ -71,6 +71,11 @@ //! - `surface_order` ([`surface_order::SurfaceOrder`]), the queues' surface timelines: a leaf, //! taken under no other lock and holding none, by a command buffer that holds `SURFACE_ORDER` //! (or is waited for) while its waits and its signal are encoded, and at a queue's make and end. +//! - `completed_ahead` ([`surface_order::CompletedAhead`]), the decodes completed ahead of their +//! ends, by block: a leaf, taken alone where a decode's command buffer enters it and leaves it, +//! and by a command buffer that uses a block, before its waits are encoded, where it holds any. +//! - each queue's completion turns ([`completions::Completions`]): a leaf, never held across a +//! post. //! //! Where two are held at once, they are taken in this order: the Shared pool's ([`PoolLedger`], //! held while a heap over a block of it is made and stored, and while a `POOL_GIVE` asks whether @@ -180,6 +185,7 @@ mod churn; mod close_cost; mod cmdbuf; mod commit_order; +mod completions; #[cfg(test)] mod composite_cost; mod compute; @@ -350,8 +356,25 @@ pub(crate) struct Sinks { pub(crate) scheduled: Option, pub(crate) submitted: Option, pub(crate) reflection: Option, + /// Where a command buffer's completion may be posted at its decode ([`AheadSinks`]). + pub(crate) ahead: Option, } +/// The sinks of a command buffer's `CB_COMPLETE` posted at its decode, ahead of its platform end +/// ([`video::Landed`]; the module docs of [`video`], "Completed at the decode"): `post` writes +/// the record to the queue's completion ring as [`CompletionSink`] does, telling nothing that +/// waits for the buffer's end, and `finished` tells that, at its end, with its seqno, once the +/// record is on the ring: the host's presents waiting for the buffer are shown then +/// (`present::PresentQueue::finished`), after the decode's copy into its output's device caches. +#[derive(Clone)] +pub(crate) struct AheadSinks { + pub(crate) post: CompletionSink, + pub(crate) finished: FinishedSink, +} + +/// [`AheadSinks::finished`]. +pub(crate) type FinishedSink = Arc; + /// An answer the host gives once a context's command buffers have finished (a `CONTEXT_CLOSE`'s, /// a `BLOCK_RELEASE`'s). pub(crate) type DrainAnswer = Box; @@ -892,6 +915,9 @@ pub(crate) struct Shared { /// The queues' surface timelines, which order command buffers of different queues over the /// IOSurfaces they share ([`surface_order`]). surface_order: Mutex>, + /// The decodes completed ahead of their platform ends, by their outputs' blocks, which a + /// buffer of another queue that uses one waits for ([`surface_order::CompletedAhead`]). + completed_ahead: Arc, /// The device's resets, which end every wait for another queue's buffers /// ([`commit_order`]). commit_cancel: commit_order::Cancel, @@ -1269,6 +1295,7 @@ impl GraphicsDecoder

{ sequencer: Arc::default(), split_gate: Arc::default(), surface_order: Mutex::new(surface_order::SurfaceOrder::new()), + completed_ahead: Arc::default(), commit_cancel: commit_order::Cancel::default(), release_queue: OnceLock::new(), shares: Arc::default(), @@ -2766,12 +2793,28 @@ impl GraphicsDecoder

{ /// once its work finishes (the ring loop's, writing the queue's completion /// ring). /// What follows each record is run as soon as `sink` returns. + /// A completion posted at its decode goes to `sink` too, with no end told + /// ([`Self::set_finished_sink`]). #[cfg(test)] pub(crate) fn set_completion_sink(&mut self, sink: Arc) { - self.sinks.completion = Some(Arc::new(move |record, then: Then| { + let sink: CompletionSink = Arc::new(move |record, then: Then| { sink(record); then(); - })); + }); + self.sinks.completion = Some(Arc::clone(&sink)); + self.sinks.ahead = Some(AheadSinks { + post: sink, + finished: Arc::new(|_| ()), + }); + } + + /// Sets the sink told of the end of each command buffer whose completion was posted at its + /// decode ([`AheadSinks::finished`]), after [`Self::set_completion_sink`]. + #[cfg(test)] + pub(crate) fn set_finished_sink(&mut self, sink: FinishedSink) { + if let Some(ahead) = &mut self.sinks.ahead { + ahead.finished = sink; + } } /// Sets the sink the decoder hands each shared event a command buffer signalled to, once the @@ -3328,7 +3371,7 @@ impl GraphicsDecoder

{ _ => None, }) .flatten()?; - let writers = writers_at + let mut writers: Vec = writers_at .and_then(|at| self.region.surface_writers(at)) .map(|record| { record @@ -3338,6 +3381,16 @@ impl GraphicsDecoder

{ .collect() }) .unwrap_or_default(); + // A decode into the surface whose completion went at its decode, which the guest's + // writers no longer name, is waited for to its end (`surface_order`, "A decode completed + // ahead of its end is still waited for"). + let kept = &self.shared.completed_ahead; + if kept.any() + && let Some((block, _)) = span + { + let now = self.shared.platform.clock().now_mono(); + writers.extend(kept.present_writers(block, &writers, now)); + } Some(SurfacePresent { texture, span, diff --git a/crates/reims-vgpu/src/graphics/decode/surface_order.rs b/crates/reims-vgpu/src/graphics/decode/surface_order.rs index da92d6e96..1921a2850 100644 --- a/crates/reims-vgpu/src/graphics/decode/surface_order.rs +++ b/crates/reims-vgpu/src/graphics/decode/surface_order.rs @@ -41,6 +41,19 @@ //! a queue of its own as the host walks the buffer, so the buffer's GPU waits do not hold it: //! the host waits for the same buffers on the CPU first ([`OrderWait`]), so a decode's output //! lands after the reads of other queues committed before it, as any other write does. +//! - **A decode completed ahead of its end is still waited for.** A command buffer of a decode +//! alone may post its `CB_COMPLETE` as its session's decode is done, before the picture's copy +//! into the output's device caches has run ([`super::video::Landed`], "Completed at the +//! decode" in its module docs). The guest's kext empties the output's slots of the buffer as it +//! takes that record, so a buffer posted after it names nothing of the output. The host keeps +//! each such decode by its output's blocks until its platform end ([`CompletedAhead`]), and a +//! buffer of another queue that uses one of those blocks waits for it as for a named buffer: +//! on the GPU at its begin, and on the CPU before work started off it; and a present of a +//! surface in one waits for it as for a writer the guest named ([`CompletedAhead::present_writers`]), +//! which the host's presents count done at the buffer's end, not at its record +//! ([`super::AheadSinks`]). The decode's buffer signals its queue's timeline whether it holds +//! the op or not. A lock's download needs no such wait: it waits for the caches' users' ends, +//! the decode's buffer among them ([`super::surface_cache`]). //! //! The order's state is the decoder's `surface_order` lock, a leaf: held while a buffer's waits //! and signal are encoded, never across a platform call that may wait. A command buffer made only @@ -53,16 +66,18 @@ use std::collections::HashMap; use std::sync::Arc; -use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; +use std::time::Duration; use reims_vgpu_graphics::ops::RgfxSurfaceOrderWait; -use reims_vgpu_graphics::wire::RGFX_CONTEXT_OBJ_ID_SHIFT; +use reims_vgpu_graphics::wire::{RGFX_CONTEXT_OBJ_ID_SHIFT, RgfxSurfaceWriter}; use reims_vgpu_vulkan::core::platform::command::{CommandBuffer, CommandQueue, CompletedInfo}; use reims_vgpu_vulkan::core::platform::device::GpuDevice; use reims_vgpu_vulkan::core::platform::event::{EventRef, SharedEvent}; -use reims_vgpu_vulkan::core::platform::os::clock::MonoTime; +use reims_vgpu_vulkan::core::platform::os::clock::{Clock as _, MonoTime}; use reims_vgpu_vulkan::core::platform::{Handle, Platform}; use reims_vgpu_vulkan::core::raise::{OnFault, RaiseResult, refusals}; +use reims_vgpu_vulkan::core::sync::Mutex; use super::commit_order; @@ -245,6 +260,184 @@ pub(crate) struct OrderCounts { pub(crate) stale: u64, /// Signals for buffers that did not run: a command buffer of their own, or a CPU set. pub(crate) released: u64, + /// Waits for a decode completed ahead of its end that a buffer's named waits did not cover + /// ([`CompletedAhead`]): the buffers it held. + pub(crate) held: u64, +} + +/// The decodes whose command buffers posted their `CB_COMPLETE` ahead of their platform end, by +/// the blocks of their outputs, until that end (the module doc, "A decode completed ahead of its +/// end is still waited for"). +#[derive(Default)] +pub(crate) struct CompletedAhead { + /// Each block's decode. + blocks: Mutex>, + /// How many blocks it holds, read with no lock, so a buffer that uses a surface finds none + /// with an atomic load where no decode is out ahead ([`Self::waits_for`]). + live: AtomicUsize, + /// The longest a buffer of another queue that waited for one of them was begun before its + /// end, in nanoseconds (diagnostics only). + longest: AtomicU64, + /// How many decodes' command buffers posted their completion at their decodes (diagnostics + /// only). + posted: AtomicU64, + /// How many of the host's presents waited for one that the guest's writers named not + /// (diagnostics only). + presents: AtomicU64, +} + +/// A decode in [`CompletedAhead`]. +struct Ahead { + /// Its command buffer's queue and seqno. + queue: u64, + seqno: u64, + /// When the first buffer of another queue that waits for it was begun. + since: Option, +} + +/// A decode's place in [`CompletedAhead`], from before its command buffer's commit until its +/// completion handler has run, which drops it. +pub(crate) struct AheadEntry { + table: Arc, + platform: Arc

, + blocks: Vec, + queue: u64, + seqno: u64, +} + +impl CompletedAhead { + /// Keeps the decode of queue `queue`'s buffer at `seqno`, whose output lies in `blocks`, until + /// the entry answered is dropped, which reads the time on `platform`'s clock. A later decode + /// into a block takes its place there. + pub(crate) fn enter( + self: &Arc, + platform: &Arc

, + blocks: Vec, + queue: u64, + seqno: u64, + ) -> AheadEntry

{ + let mut map = self.blocks.lock(); + for &block in &blocks { + let ahead = Ahead { + queue, + seqno, + since: None, + }; + if map.insert(block, ahead).is_none() { + self.live.fetch_add(1, Ordering::AcqRel); + } + } + AheadEntry { + table: Arc::clone(self), + platform: Arc::clone(platform), + blocks, + queue, + seqno, + } + } + + /// Whether it keeps any decode, read with no lock. + pub(crate) fn any(&self) -> bool { + self.live.load(Ordering::Acquire) > 0 + } + + /// A decode's command buffer posted its completion at its decode. + pub(crate) fn posted(&self) { + self.posted.fetch_add(1, Ordering::Relaxed); + } + + /// How many decodes' command buffers posted their completion at their decodes. + pub(crate) fn posts(&self) -> u64 { + self.posted.load(Ordering::Relaxed) + } + + /// The writers a present of a surface in `block` waits for besides `named`, those the guest's + /// writers record names: the decode kept there, where one is and `named` holds nothing of its + /// queue at its seqno or past it, at `now`. Counted. + pub(crate) fn present_writers( + &self, + block: u64, + named: &[RgfxSurfaceWriter], + now: MonoTime, + ) -> Option { + let wait = self.waits_for(0, std::iter::once(block), now).pop()?; + let covered = (named.iter()) + .any(|w| w.queue_obj_id == wait.queue_obj_id && w.seqno >= wait.seqno); + if covered { + return None; + } + self.presents.fetch_add(1, Ordering::Relaxed); + Some(RgfxSurfaceWriter { + queue_obj_id: wait.queue_obj_id, + seqno: wait.seqno, + }) + } + + /// How many presents waited for a decode the guest's writers named not. + pub(crate) fn presents_held(&self) -> u64 { + self.presents.load(Ordering::Relaxed) + } + + /// The decodes of other queues than `queue` whose outputs lie in `blocks`, as the waits a + /// buffer of `queue` that uses those blocks makes for them, begun at `now`. No lock is taken, + /// and nothing allocated, where no decode is kept. + pub(crate) fn waits_for( + &self, + queue: u64, + blocks: impl Iterator, + now: MonoTime, + ) -> Vec { + if self.live.load(Ordering::Acquire) == 0 { + return Vec::new(); + } + let mut map = self.blocks.lock(); + let mut waits = Vec::new(); + for block in blocks { + if let Some(ahead) = map.get_mut(&block) + && ahead.queue != queue + { + ahead.since.get_or_insert(now); + waits.push(RgfxSurfaceOrderWait { + queue_obj_id: ahead.queue, + seqno: ahead.seqno, + }); + } + } + waits + } + + /// Whether it keeps a decode (for the tests). + #[cfg(test)] + pub(crate) fn holds(&self, block: u64) -> bool { + self.blocks.lock().contains_key(&block) + } + + /// The longest a buffer of another queue that waited for a decode kept here was begun before + /// the decode's end. + pub(crate) fn longest(&self) -> Duration { + Duration::from_nanos(self.longest.load(Ordering::Acquire)) + } +} + +impl Drop for AheadEntry

{ + fn drop(&mut self) { + let now = self.platform.clock().now_mono(); + let table = &self.table; + let mut map = table.blocks.lock(); + for block in &self.blocks { + let ours = map + .get(block) + .is_some_and(|a| a.queue == self.queue && a.seqno == self.seqno); + if ours && let Some(ahead) = map.remove(block) { + table.live.fetch_sub(1, Ordering::AcqRel); + if let Some(since) = ahead.since { + let held = now.saturating_duration_since(since).as_nanos(); + let held = u64::try_from(held).unwrap_or(u64::MAX); + table.longest.fetch_max(held, Ordering::AcqRel); + } + } + } + } } /// One queue the host holds, from its create to its end. @@ -432,18 +625,24 @@ impl SurfaceOrder

{ }) } - /// Makes `cb`, a command buffer of queue `queue` that holds the op, wait on the GPU for each - /// buffer of `waits` not yet finished (the module doc); the waits it made, one a queue. Logs - /// the counts where it comes [`LOGGED_AFTER`] or more after their last log, at `now`. + /// Makes `cb`, a command buffer of queue `queue`, wait on the GPU for each buffer not yet + /// finished of `waits`, those its op names where it holds one, and of `ahead`, the decodes + /// completed ahead of their ends whose outputs it uses ([`CompletedAhead::waits_for`]; the + /// module doc); the waits it made, one a queue. Logs the counts where it comes + /// [`LOGGED_AFTER`] or more after their last log, at `now`, with the longest wait `kept` + /// saw. pub(crate) fn before( &mut self, device: &P::Device, queue: u64, cb: &P::CommandBuffer, - waits: &[RgfxSurfaceOrderWait], + (waits, ahead): (Option<&[RgfxSurfaceOrderWait]>, &[RgfxSurfaceOrderWait]), + kept: &CompletedAhead, now: MonoTime, ) -> RaiseResult>> { - self.counts.buffers += 1; + if waits.is_some() { + self.counts.buffers += 1; + } let last = *self.logged_at.get_or_insert(now); if now.saturating_duration_since(last) >= LOGGED_AFTER { self.logged_at = Some(now); @@ -452,59 +651,58 @@ impl SurfaceOrder

{ target: "reims_vgpu::graphics", "surface order: {} command buffers named {} buffers of other queues: {} GPU \ waits ({} for buffers not yet taken), {} naming no buffer; {} signals for \ - buffers that did not run", - c.buffers, c.named, c.waits, c.ahead, c.stale, c.released + buffers that did not run; {} decodes completed ahead of their ends, {} buffers \ + and {} presents held behind them (the longest begun {} us before one's end)", + c.buffers, + c.named, + c.waits, + c.ahead, + c.stale, + c.released, + kept.posts(), + c.held, + kept.presents_held(), + kept.longest().as_micros() ); } // One wait a queue, for the highest value of it. let mut targets: Vec<(u64, u64)> = Vec::new(); - for w in waits { + for w in waits.unwrap_or_default() { let (q, s) = (w.queue_obj_id, w.seqno); if q == queue || q == 0 || s == 0 { continue; } self.counts.named += 1; - let Some(named) = self.queues.get_mut(&q) else { - self.counts.stale += 1; + let Some(target) = self.target(device, q, s) else { continue; }; - let marks = Arc::clone(&named.marks); - let done = marks.done.load(Ordering::Acquire); - if done >= s || named.event(device).is_none() { - continue; - } - let signalled = marks.signalled.load(Ordering::Acquire); - let target = if named.ended { - s.min(signalled) - } else if s <= signalled { - s - } else { - if let Some(published) = named.published.as_ref().and_then(|p| p()) - && s > published - { - self.counts.stale += 1; - continue; - } - // Not yet signalled. Raised before `taken` is read ([`Marks::quiet`]). - marks.waited.fetch_max(s, Ordering::SeqCst); - if marks.taken.load(Ordering::SeqCst) >= s { - // Taken without a signal: it held no op, so it used no surface the bundle - // named. What the queue signalled before it is what it can be ordered after. - signalled - } else { - // Not yet taken: it signals once taken, if its ring holds it. - self.counts.ahead += 1; - s - } - }; - if target <= done { - continue; - } match targets.iter_mut().find(|(tq, _)| *tq == q) { Some((_, v)) => *v = (*v).max(target), None => targets.push((q, target)), } } + // A decode completed ahead of its end, past what the named waits wait for of its queue, + // holds the buffer. + for w in ahead { + let (q, s) = (w.queue_obj_id, w.seqno); + if q == queue || q == 0 || s == 0 { + continue; + } + let Some(target) = self.target(device, q, s) else { + continue; + }; + match targets.iter_mut().find(|(tq, _)| *tq == q) { + Some((_, v)) if *v >= target => {} + Some((_, v)) => { + self.counts.held += 1; + *v = target; + } + None => { + self.counts.held += 1; + targets.push((q, target)); + } + } + } let mut made = Vec::with_capacity(targets.len()); for &(q, value) in &targets { let Some(named) = self.queues.get(&q) else { @@ -523,6 +721,47 @@ impl SurfaceOrder

{ Ok(made) } + /// The value of queue `q`'s timeline a wait for its buffer at `s` waits for, where it waits: + /// `None` where the host does not hold the queue (counted stale), the buffer has finished, + /// the platform makes no shared event, or `s` lies past what the queue's ring has published + /// (counted stale). + fn target(&mut self, device: &P::Device, q: u64, s: u64) -> Option { + let Some(named) = self.queues.get_mut(&q) else { + self.counts.stale += 1; + return None; + }; + let marks = Arc::clone(&named.marks); + let done = marks.done.load(Ordering::Acquire); + if done >= s || named.event(device).is_none() { + return None; + } + let signalled = marks.signalled.load(Ordering::Acquire); + let target = if named.ended { + s.min(signalled) + } else if s <= signalled { + s + } else { + if let Some(published) = named.published.as_ref().and_then(|p| p()) + && s > published + { + self.counts.stale += 1; + return None; + } + // Not yet signalled. Raised before `taken` is read ([`Marks::quiet`]). + marks.waited.fetch_max(s, Ordering::SeqCst); + if marks.taken.load(Ordering::SeqCst) >= s { + // Taken without a signal: it held no op, so it used no surface the bundle + // named. What the queue signalled before it is what it can be ordered after. + signalled + } else { + // Not yet taken: it signals once taken, if its ring holds it. + self.counts.ahead += 1; + s + } + }; + (target > done).then_some(target) + } + /// Notes queue `queue`'s buffer at `seqno` taken, and has `cb`, its command buffer or its /// stand-in, signal the queue's timeline to `seqno` as it ends where it `names` the op or a /// buffer of another queue waits past what the queue has signalled; then what its completed diff --git a/crates/reims-vgpu/src/graphics/decode/tables.rs b/crates/reims-vgpu/src/graphics/decode/tables.rs index 20fa030c6..4b99f7281 100644 --- a/crates/reims-vgpu/src/graphics/decode/tables.rs +++ b/crates/reims-vgpu/src/graphics/decode/tables.rs @@ -73,6 +73,9 @@ pub(crate) struct QueueCounts { /// Its committed command buffers' records the host may post ahead of the platform's /// submission, in commit order ([`super::cmdbuf::Line`]). pub(crate) line: Arc, + /// Its command buffers' turns of their `CB_COMPLETE` posts, in commit order + /// ([`super::completions`]). + pub(crate) completions: Arc, /// Where its command buffers' walks and commits run, each in its turn; `None` for a queue /// whose buffers are carried out whole where they are taken (the decoder's own tests). pub(crate) lane: Option>, @@ -94,6 +97,7 @@ impl QueueCounts { rate: Arc::default(), order, line: Arc::default(), + completions: Arc::default(), lane: Some(lane), answered: Mutex::default(), } diff --git a/crates/reims-vgpu/src/graphics/decode/video.rs b/crates/reims-vgpu/src/graphics/decode/video.rs index 01699db31..1197426d6 100644 --- a/crates/reims-vgpu/src/graphics/decode/video.rs +++ b/crates/reims-vgpu/src/graphics/decode/video.rs @@ -18,11 +18,24 @@ //! answers as a decode error: an HEVC picture's schedule, waiting for the buffer, fails //! (`kVTVideoDecoderMalfunctionErr`, docs/graphics-kext/design.md, "A decode the driver cannot //! complete is a decode error"). +//! +//! **Completed at the decode.** A session whose picture lands in its output's device caches by +//! GPU work of its own after the decode is done (the VA-API arm's video processing, +//! `super::super::vaapi`) tells of the decode done as it issues that work ([`Landed::decoded`]). +//! A command buffer of that decode alone, which waits for no event and signals none, then posts +//! its `CB_COMPLETE` there, in its queue's order of records, ahead of its platform end +//! ([`Landed::arm`], `super::cmdbuf`): the guest's decoder hands the picture on while the copy +//! runs. Everything else stays at the platform end, after the copy: the session's signal, the +//! buffer's surface timeline and its caches' copies into the pages, which every reader of the +//! output waits for (a GPU reader on another queue, a lock's download, a present), the queue's +//! later work, the drain of its context and its place among the queue's buffers in flight. Such +//! a `CB_COMPLETE` carries no GPU times (0 for each), and is posted on the thread that tells of +//! the decode done (the VA-API arm's picture landing thread, `reims-vgpu.graphics-video-land`), +//! or on the buffer's lane where the decode was done before its commit. use std::mem::ManuallyDrop; use std::ptr::NonNull; use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; use reims_vgpu_graphics::ops::video::{ RGFX_OP_VIDEO_DECODE_H264, RGFX_OP_VIDEO_DECODE_H265, RGFX_OP_VIDEO_ENCODE_H264, @@ -53,6 +66,7 @@ use reims_vgpu_vulkan::core::platform::resource::SurfaceMemory; use reims_vgpu_vulkan::core::platform::types::PixelFormatInfo; use reims_vgpu_vulkan::core::platform::values::PagesPlane; use reims_vgpu_vulkan::core::raise::RaiseResult; +use reims_vgpu_vulkan::core::sync::Mutex; use zerocopy::FromBytes; use super::worker::Worker; @@ -347,19 +361,98 @@ pub struct Decoded { /// Whether a decode's picture landed: set by its session before it signals the decode's value, /// and read by the command buffer waiting for it as it completes, which completes failed, Metal's -/// internal error, where the picture did not land (the module docs). -#[derive(Debug, Default)] -pub struct Landed(AtomicBool); +/// internal error, where the picture did not land (the module docs). Where its session tells of +/// the decode done before the picture lands ([`Self::decoded`]), a command buffer of the decode +/// alone posts its completion then ([`Self::arm`]; the module docs, "Completed at the decode"), +/// and its record says what was known then: a picture that fails to land after it was posted +/// leaves the buffer completed ([`Self::fail`]'s answer). +#[derive(Default)] +pub struct Landed(Mutex); + +/// [`Landed`]'s state. +#[derive(Default)] +struct Outcome { + /// The picture did not land. + failed: bool, + /// Its session told of its decode done. + decoded: bool, + /// Its command buffer's post of its completion, armed at its commit until the decode is + /// done. + early: Option, + /// Its command buffer's completion was posted, answering the picture failed or not. + posted: Option, +} + +/// A command buffer's post of its completion at its decode ([`Landed::arm`]), handed the decode's +/// [`Landed`]. +pub(super) type EarlyPost = Box) + Send>; impl Landed { - /// The picture did not land. - pub fn fail(&self) { - self.0.store(true, Ordering::SeqCst); + /// The picture did not land. Answers whether its command buffer's completion was posted + /// already, answering that it landed: the guest has the picture as the landing left it, and + /// the session is to tell the guest of the failure otherwise. + pub fn fail(&self) -> bool { + let (posted, early) = { + let mut outcome = self.0.lock(); + outcome.failed = true; + (outcome.posted == Some(false), outcome.early.take()) + }; + drop(early); + posted } /// Whether the picture did not land. pub fn failed(&self) -> bool { - self.0.load(Ordering::SeqCst) + self.0.lock().failed + } + + /// The session's decode of the picture is done, and its landing from here is work the + /// output's readers wait for (the module docs, "Completed at the decode"): the command + /// buffer's completion is posted now where its commit armed it, else at its arming. + pub fn decoded(self: &Arc) { + let early = { + let mut outcome = self.0.lock(); + outcome.decoded = true; + outcome.early.take() + }; + if let Some(early) = early { + early(Arc::clone(self)); + } + } + + /// Arms `early`, the command buffer's post of its completion, at its commit: run at once + /// where the decode is done already, else as it is ([`Self::decoded`]); dropped where the + /// completion was posted already, or the picture failed. + pub(super) fn arm(self: &Arc, early: EarlyPost) { + let now = { + let mut outcome = self.0.lock(); + if outcome.posted.is_some() || outcome.failed { + Some(None) + } else if outcome.decoded { + Some(Some(early)) + } else { + outcome.early = Some(early); + None + } + }; + if let Some(Some(early)) = now { + early(Arc::clone(self)); + } + } + + /// Fixes what the command buffer's completion answers, once: whether the picture failed, to + /// the first that asks, which posts it; `None` once it is posted. The post armed goes. + pub(super) fn post(&self) -> Option { + let (failed, early) = { + let mut outcome = self.0.lock(); + if outcome.posted.is_some() { + return None; + } + outcome.posted = Some(outcome.failed); + (outcome.failed, outcome.early.take()) + }; + drop(early); + Some(failed) } } @@ -1100,7 +1193,7 @@ impl GraphicsDecoder

{ /// The blocks of the surfaces the textures `luma_id` and `chroma_id` of a decode lie over, /// each once, in that order. - fn decode_blocks(&self, luma_id: u64, chroma_id: u64) -> Vec { + pub(super) fn decode_blocks(&self, luma_id: u64, chroma_id: u64) -> Vec { let block = |id| { let place = self.entry(id)?.place?; self.span_of(place.buffer_obj_id).map(|(block, _)| block) diff --git a/crates/reims-vgpu/src/graphics/vaapi.rs b/crates/reims-vgpu/src/graphics/vaapi.rs index 8fcd43acc..d5829d2f2 100644 --- a/crates/reims-vgpu/src/graphics/vaapi.rs +++ b/crates/reims-vgpu/src/graphics/vaapi.rs @@ -1422,19 +1422,21 @@ type SessionCopier

= Result>>>, String>; impl VaPicture

{ /// Writes the picture by the driver's video processing into `memory`, laid out as `layout` - /// (the VA crate's `Frame::write_to_guest`): `None` once it is there, or why it was not + /// (the VA crate's `Frame::write_to_guest_telling`), calling `decoded` once the decode is + /// done and the runs are issued behind it: `None` once it is there, or why it was not /// written, nothing written. `Err` where the decode or a run failed or ran past its deadline: /// no copy may race the GPU's write, so the picture fails. fn write_in_place( &self, layout: &SurfaceLayout, memory: &dyn DeviceMemory, + decoded: &mut dyn FnMut(), ) -> Result, BackendError> { let target = match GuestTarget::new(layout, memory) { Ok(target) => target, Err(why) => return Ok(Some(why)), }; - match self.frame.write_to_guest(&target, &self.imports)? { + match (self.frame).write_to_guest_telling(&target, &self.imports, decoded)? { DeviceWrite::Written => Ok(None), DeviceWrite::Declined(why) => Ok(Some(why)), } @@ -1480,11 +1482,14 @@ impl HostPicture

for VaPicture

{ let declined = match &self.targets { // In its device cache, through the cache's memory as a dma-buf, where the video // decodes into caches: the driver's check refused the picture's codec and format, or - // its planes do not lie as a decode's target must. + // its planes do not lie as a decode's target must. Once its decode is done, what is + // left is the runs' GPU work into the caches, which the output's readers wait for. #[cfg(unix)] Some(targets) if to.luma.cached || to.chroma.cached => { match targets.in_cache(to.luma, to.chroma, bit_depth) { - Ok((layout, bytes)) => match self.write_in_place(&layout, &bytes)? { + Ok((layout, bytes)) => match self.write_in_place(&layout, &bytes, &mut || { + to.decode_done() + })? { None => { to.luma.external_write_done()?; return Ok(()); @@ -1495,7 +1500,7 @@ impl HostPicture

for VaPicture

{ } } _ => match in_place(to.luma, to.chroma, bit_depth) { - Ok((layout, pages)) => match self.write_in_place(&layout, &*pages.memory)? { + Ok((layout, pages)) => match self.write_in_place(&layout, &*pages.memory, &mut || {})? { None => return Ok(()), Some(why) => why, }, diff --git a/crates/reims-vgpu/src/graphics/video_host.rs b/crates/reims-vgpu/src/graphics/video_host.rs index be48aef5f..9723e28a4 100644 --- a/crates/reims-vgpu/src/graphics/video_host.rs +++ b/crates/reims-vgpu/src/graphics/video_host.rs @@ -286,6 +286,9 @@ pub(crate) struct Landing<'a, P: Platform> { cpu_from: Option, /// How long [`Landing::copy_rows`]'s copy took. cpu_took: Option, + /// Whether the picture landed, for the command buffer that waits for it, which its decode's + /// end may complete ([`Landing::decode_done`]). + landed: &'a Arc, } /// Where the planes in a device cache are staged in the staging buffer: each one's first byte. @@ -296,6 +299,17 @@ struct Staged { } impl Landing<'_, P> { + /// Says that the picture's decode is done, and what is left of its landing is GPU work into + /// the output's device caches, which every reader of the output waits for: where both planes + /// lie in caches, the command buffer that waits for the picture may post its completion now + /// ([`Landed::decoded`]; `super::decode`'s video module docs, "Completed at the decode"). Said + /// by the VA-API arm's video processing into the caches (`super::vaapi`). + pub(crate) fn decode_done(&self) { + if self.luma.cached && self.chroma.cached { + self.landed.decoded(); + } + } + /// Says that the hardware decoded the picture straight into the output's planes, so that /// nothing was copied (`super::vaapi`). pub(crate) fn decoded_there(&mut self) { @@ -1058,7 +1072,7 @@ fn land_pictures( _bitstream, landed, } = job; - match picture.map(|picture| land(picture, &output, &mut stage, clock)) { + match picture.map(|picture| land(picture, &output, &mut stage, clock, &landed)) { None => counts.lock().skipped += 1, Some(Ok((way, hardware_failed, cpu))) => { let mut counts = counts.lock(); @@ -1116,11 +1130,13 @@ fn land_pictures( /// how, what the hardware answered where it failed the decode and the picture landed all the /// same ([`Landing::hardware_failed`]), and how long the CPU's copy took where the CPU copied it /// (from its start to the end of [`Landing::copy_rows`], or to the picture's landing's return). +/// `landed` is told where the decode is done before the landing ends ([`Landing::decode_done`]). fn land( picture: Box>, output: &DecodeOutput

, stage: &mut Stage

, clock: &dyn Runtime, + landed: &Arc, ) -> Result<(Way, Option, Option), BackendError> { let mut landing = Landing { luma: &output.luma, @@ -1133,6 +1149,7 @@ fn land( hardware_failed: None, cpu_from: None, cpu_took: None, + landed, }; picture.land(&mut landing)?; let cpu = match (landing.cpu_took, landing.cpu_from) { diff --git a/docs/api.md b/docs/api.md index 5a10af5fc..663bbddef 100644 --- a/docs/api.md +++ b/docs/api.md @@ -389,7 +389,7 @@ returns. The library logs through the `log` crate; a Rust host installs its own | callback | thread | serialized with | order | |---|---|---|---| -| `raise_interrupt` | the thread that posts the event it raises for: the device's control thread, `reims-vgpu.graphics-control`; one of ring 0's threads, `reims-vgpu.graphics-ring0-`, which carry out a guest process's control messages, its presents and a block's pages and downloads, each on its lane; a display's refresh thread, `reims-vgpu.graphics-refresh` (display 0's) and, on a device of several displays, `reims-vgpu.graphics-refresh-`; a command queue's service thread, `reims-vgpu.graphics-queue-`, or one of its lane's threads, which walk and commit its command buffers, `reims-vgpu.graphics-lane-`; a pipeline compile's thread, `reims-vgpu.graphics-compile-`; a thread that makes IOSurfaces' and pages blocks' views, `reims-vgpu.graphics-surfaces-`; a thread that makes indirect command buffers, `reims-vgpu.icb-create-`; a thread that lets go of a closed process's objects and answers its close, `reims-vgpu.graphics-closes-`; a thread that moves a staged copy of a surface's device cache into its pages and answers what waited for it, `reims-vgpu.graphics-into-pages-`; or the platform's thread that runs a command buffer's scheduled or completed handler; or the host's own, inside `rvg_graphics_device_mmio_write_taking` or `rvg_graphics_device_doorbell_write`. Never inside another call of the host's | nothing: they may call at once | each after the completion ring's message it raises for is published | +| `raise_interrupt` | the thread that posts the event it raises for: the device's control thread, `reims-vgpu.graphics-control`; one of ring 0's threads, `reims-vgpu.graphics-ring0-`, which carry out a guest process's control messages, its presents and a block's pages and downloads, each on its lane; a display's refresh thread, `reims-vgpu.graphics-refresh` (display 0's) and, on a device of several displays, `reims-vgpu.graphics-refresh-`; a command queue's service thread, `reims-vgpu.graphics-queue-`, or one of its lane's threads, which walk and commit its command buffers, `reims-vgpu.graphics-lane-`; a pipeline compile's thread, `reims-vgpu.graphics-compile-`; a thread that makes IOSurfaces' and pages blocks' views, `reims-vgpu.graphics-surfaces-`; a thread that makes indirect command buffers, `reims-vgpu.icb-create-`; a thread that lets go of a closed process's objects and answers its close, `reims-vgpu.graphics-closes-`; a thread that moves a staged copy of a surface's device cache into its pages and answers what waited for it, `reims-vgpu.graphics-into-pages-`; a video session's picture landing thread, which posts a decode's completion as the decode is done, `reims-vgpu.graphics-video-land`; or the platform's thread that runs a command buffer's scheduled or completed handler; or the host's own, inside `rvg_graphics_device_mmio_write_taking` or `rvg_graphics_device_doorbell_write`. Never inside another call of the host's | nothing: they may call at once | each after the completion ring's message it raises for is published | | `route_doorbell`, `route_doorbell_page` (the route of a queue whose process has a doorbell page, at that page's doorbell in BAR 4) | one of ring 0's threads, `reims-vgpu.graphics-ring0-`, or the control thread, `reims-vgpu.graphics-control`, as a command queue is made, destroyed or its process closed, with no lock of the library's held, where it may wait for a lock the host holds while it calls the device (QEMU's BQL), since no function the host calls under it waits for a thread inside the callback but the release of the process's last device, at most 5 s; dropping a route, also the host's own inside `rvg_graphics_device_mmio_write_taking` (a STATUS write of 0, or a `DOORBELL_PAGE_BIND` write that binds a page to another context) or `rvg_graphics_device_reset`, where it must not wait for a lock the host holds around that call | nothing: they may call at once | a queue's route before its create is answered, and its drop once its queue has ended and before its destroy, its process's close or the reset is answered; a dropped route takes no write once the call returns | | `cursor_glyph`, `cursor_show`, `cursor_move` (display 0's), and `cursor_glyph_at`, `cursor_show_at`, `cursor_move_at` (each display's from 1, named) | the display thread: one serial worker for the whole process (after 5 s idle it exits, and the next callback starts a new one) | every display callback of the process: one at a time | the order the device's control thread took the guest's cursor and display power commands, of every display, and its resets | | `pool_add` | the device's pool thread, `reims-vgpu.graphics-pool`, with no lock of the library's held; never inside a call of the host's; it must not wait for a lock the host holds while it calls the device (QEMU queues the add for its main loop) | one at a time | the order the device places the pieces, each before its `pool_remove`; the host answers each with `rvg_graphics_device_pool_added` once the guest's address space has it | @@ -417,6 +417,8 @@ may run under these: read; - the decoder's lock, with the download's answer slot, at a `SURFACE_DOWNLOAD` answered at once; - a command buffer's `CB_SUBMITTED` latch, wherever that is posted; +- on a picture landing thread, the run of the video processing that copies a decoded picture into + its output's device caches, at the decode's completion posted as the decode is done; - the presents' queue, at a present answered at once with no window. No function of the device takes any of them, and `_mmio_write_taking` only tries the claim and the diff --git a/docs/graphics-kext/design.md b/docs/graphics-kext/design.md index 2bc920707..ac245da21 100644 --- a/docs/graphics-kext/design.md +++ b/docs/graphics-kext/design.md @@ -5848,7 +5848,12 @@ committed in. The bundle names the order instead, as it posts each buffer: writers' end, as a bundle without readers did. - A slot names a buffer only while it runs: once the host has finished it, and its post has named it, its process empties the slot where no later buffer of - the queue raised it, as a buffer that named it would wait for nothing. Four + the queue raised it, as a buffer that named it would wait for nothing. A + buffer of a video decode alone into device caches, which the host completes + as the decode is done, ahead of its copy into the caches (docs/video/devices.md), + leaves its slot then, and the host itself has every later buffer of another + queue that uses the surface, every download and every present wait for its + end, as they would for a slot that named it. Four slots of each record are shared by every process's queues. A queue that finds none free takes one of its process's that names a buffer of another of its queues which its own buffer runs after, its post having named that buffer: diff --git a/docs/video/devices.md b/docs/video/devices.md index 657b045d1..46c24fed0 100644 --- a/docs/video/devices.md +++ b/docs/video/devices.md @@ -143,6 +143,15 @@ command buffer of the session's process (`graphics/decode/video.rs`): - **The command buffer's later work, and its completion, wait** for the session's event to reach the value the decode signals once its picture has landed. So a CPU lock of the output waits for the picture, as for any GPU write. +- **A command buffer of a decode alone into device caches completes at the decode**, where the + VA-API arm copies the picture into the caches by its video processing on the GPU: its + `CB_COMPLETE` goes as the decode is done and that copy is issued, in its queue's order, with + GPU times of 0, so the guest's decoder hands the picture on while the copy runs. The rest stays + at the buffer's end, after the copy: its later work, its surface timeline and the caches' copy + into the pages. Every reader of the output that the guest's writer slots, emptied at the + `CB_COMPLETE`, no longer point at the decode waits for that end all the same: a command buffer + of another queue that uses the output, on the GPU, or on the CPU for a decode; a CPU lock's + download; and a present (reims-vgpu's `graphics/decode/video.rs`, "Completed at the decode"). - **A picture that fails to land** still signals its value, and the command buffer completes failed, with Metal's internal error. The guest's video driver answers that as a decode error: an HEVC picture's schedule waits for its verdict and fails (`kVTVideoDecoderMalfunctionErr`,