From aaedba617bb041eb4163f64b3b343bdc8adff681 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Wed, 2 Dec 2026 04:32:05 -0800 Subject: [PATCH] :bug: Answer a download failed where the platform refuses its copy What the guest observes changes. Before, each copy the host makes for itself between a surface's device cache, its shapes, its wide home and its pages took the platform's answer to each command with go_on(), so a refused one changed nothing of the caches' state. A shape whose write-back was refused was marked written back, a refused fill marked its shape filled and the cache at the new generation, and a SURFACE_DOWNLOAD whose copy into the pages was refused was answered RGFX_STATUS_OK over the pages' older bytes, and never copied again. Now each such copy folds its commands' answers, by the ruling that keeps today's behaviour for the guest's own commands alone, and a refused one, or an encoder the platform made not, leaves what it was to move as not copied: - A shape whose write-back was refused stays dirty, and one whose fill was refused owes it still. A refused fill of the buffer leaves the cache at its older generation. - A download whose copy into the pages was refused, or that waits for a copy that landed short (a refused later round of one that circulates its pieces), is answered failed (RGFX_STATUS_REFUSED) through the driver's existing path, where it was answered OK on stale bytes before. The cache stays written, so the next download copies it again. A refused copy's pieces put none of their bytes into the pages. - A fill or a copy into a wide home refused at a command buffer's begin, and a write's copy into its plane's other shapes or a copy between a cache and its home refused at its encoder's end, fails that command buffer with MTLCommandBufferErrorOutOfMemory, as a cache's refused memory already does. - An early copy refused is not made, its command buffer not committed, and the refill it carried no longer marks the buffer as holding the pages; that also holds where the platform refuses a copy by runs, which left it so before. The host tries none of these again by itself: the next use, download or release that needs the copy makes it. Each refusal is counted under surface-copy-refused, the process's first logged at warn. The guest's own blits and draws still go on past a refused command. No rt-refused or rt-unbuilt code shows in the degradation counts of the 30 latest kept boot logs, so no boot has reached these paths so far. Five new fake-platform tests, red before (m3-max-78078, all five failed), pass with the fix: the reims-vgpu fake set (m3-max-78128, 1170 passed, 115 skipped) and its surface, shape and command buffer rt tests on the 5080 (m3-max-78131, 31 passed). --- .../reims-vgpu/src/graphics/decode/cmdbuf.rs | 9 +- .../src/graphics/decode/surface_cache.rs | 796 ++++++++++++++---- .../graphics/decode/surface_cache/shapes.rs | 241 ++++-- .../src/graphics/decode/surface_shapes.rs | 83 +- docs/conventions.md | 14 +- 5 files changed, 875 insertions(+), 268 deletions(-) diff --git a/crates/reims-vgpu/src/graphics/decode/cmdbuf.rs b/crates/reims-vgpu/src/graphics/decode/cmdbuf.rs index 1c47ad4d8..b5d743871 100644 --- a/crates/reims-vgpu/src/graphics/decode/cmdbuf.rs +++ b/crates/reims-vgpu/src/graphics/decode/cmdbuf.rs @@ -3910,7 +3910,9 @@ impl GraphicsDecoder

{ /// side written is copied into the other in `cb` before the next encoder /// ([`super::surface_cache::Caches::reconcile`]), so it reads the write through either, as /// the Macs' next encoders read it (docs/graphics-kext/dgpu-oracle.md, Q37). An encoder that - /// wrote both sides of a block keeps the home's writes in the texels both hold. + /// wrote both sides of a block keeps the home's writes in the texels both hold. A copy the + /// platform refused a command of fails the command buffer, as a refused memory does + /// (`surface_cache`'s module doc, "Refused copies"). fn reconcile_laid(&self, cb: &P::CommandBuffer) -> RaiseResult<()> { let uses = std::mem::take(&mut *self.laid_uses.borrow_mut()); let mut written: Vec<(u64, bool)> = Vec::new(); @@ -3937,7 +3939,10 @@ impl GraphicsDecoder

{ self.laid_written .borrow_mut() .extend(written.iter().map(|&(block, _)| block)); - self.surface_caches.reconcile(cb, &written) + if self.surface_caches.reconcile(cb, &written)? { + self.out_of_memory.set(true); + } + Ok(()) } /// In the per-shape form, the encoder just ended in `cb` may have written the shapes its uses diff --git a/crates/reims-vgpu/src/graphics/decode/surface_cache.rs b/crates/reims-vgpu/src/graphics/decode/surface_cache.rs index 69c17d85d..2b93be47c 100644 --- a/crates/reims-vgpu/src/graphics/decode/surface_cache.rs +++ b/crates/reims-vgpu/src/graphics/decode/surface_cache.rs @@ -436,6 +436,29 @@ //! a download's or a release's, which reads nothing of the buffer //! ([`SurfaceCache::moves_none_out`]): the cache's fills then go on going straight. //! +//! - **Refused copies.** Each copy the host makes for itself between a cache's buffer, its +//! shapes, its wide home and its pages (a fill, a refill, a write-back, a copy out, an early +//! copy, a write's copy into the other shapes of its plane, a copy between the cache and its +//! home) takes the platform's answer to each of its commands ([`Encoded`]): one it refused, or +//! an encoder it made not, leaves what the copy was to move as not copied, counted at each +//! refusal ([`COPY_REFUSED`], the process's first logged). A shape whose fill was refused owes +//! it still, and one whose write-back was refused stays dirty; a fill of the buffer refused +//! leaves the cache at its older generation; a buffer whose refill was refused lacks the pages +//! still, and takes no write-back and makes no copy out over them. A copy out refused, a +//! command of it or a later round of one that circulates its pieces ([`Rounds`]), moves no +//! more of a piece's bytes into the pages, and leaves the cache written +//! ([`SurfaceCache::take_refused_out`]): the `SURFACE_DOWNLOAD` it answers, and each that waits +//! for it, is answered failed (`RGFX_STATUS_REFUSED`), where before it was answered done over +//! the pages' older bytes; a release's is logged. An early copy refused is not made, its +//! command buffer not committed. A fill, or a copy into a wide home, refused at a command +//! buffer's begin, and a write's copy into another shape or a copy between a cache and its +//! home refused at its encoder's end, fails the command buffer as a refused memory does +//! ("Deferred memory"). A cache's zeros refused leave it unmade, as where the platform makes +//! no encoder for them, and the host's video's zeros owed. The host tries none again of its +//! own: the next use, download or release that needs the copy makes it. The guest's own +//! commands are no such copies: one the platform refused is dropped, and its command buffer +//! goes on, as a Metal app's goes on past a command its device drops. +//! //! - **Straight fills.** In the per-shape form a fill of a cache whose buffer holds no memory //! copies the pages straight into its shapes' images, with nothing copied into the buffer //! ([`SurfaceCache::fills_straight`]): its pages are a view or copied through pieces, it keeps @@ -531,7 +554,7 @@ use reims_vgpu_vulkan::core::platform::resource::SurfaceHandle; use reims_vgpu_vulkan::core::platform::resource::{Buffer as _, MemoryFor}; use reims_vgpu_vulkan::core::platform::types::NsRange; use reims_vgpu_vulkan::core::platform::values::{PagesPlane, TextureDesc}; -use reims_vgpu_vulkan::core::platform::{Handle, Platform}; +use reims_vgpu_vulkan::core::platform::{Encoded, Handle, Platform}; use reims_vgpu_vulkan::core::raise::{OnFault, Raise, RaiseResult, refusals}; use reims_vgpu_vulkan::core::sync::{Condvar, Mutex, MutexGuard}; @@ -989,6 +1012,23 @@ impl SurfaceCache

{ (cpu, Some(written)) } + /// Whether the cache holds a write its pages lack ([`Self::written`]), its last copy into them + /// having landed short among them ([`Self::take_refused_out`]). + fn holds_write(&self) -> bool { + self.written || (self.out.as_ref()).is_some_and(|out| out.landing.refused()) + } + + /// The cache's last copy into its pages, where it landed short of what it was to move (a + /// later round of a copy that circulates its pieces the platform refused, [`Rounds`]), is + /// taken back: the cache holds its write still, and the next download or release copies it + /// again (the module doc, "Refused copies"). The copy has ended, so nothing waits for it. + fn take_refused_out(&mut self) { + if (self.out.as_ref()).is_some_and(|out| out.landing.refused()) { + self.out = None; + self.written = true; + } + } + /// Whether a copy of the cache out to its pages moves none of its bytes, with no shape /// holding a write to copy into the buffer first: a staged copy out whose record holds none of /// the texels that may differ from the pages ([`Self::out_bytes`]). @@ -1106,8 +1146,12 @@ struct EarlyCopy { /// answers waiting for it, given as the platform sees its command buffer done, and the threads /// waiting for it ([`Caches::wait_copied_out`], [`Caches::wait_copies_into`]). struct Landing { - /// The answers waiting; `None` once it landed. - waiting: Mutex>>, + /// The answers waiting, each given whether the copy moved all it was to; `None` once it + /// landed. + waiting: Mutex>>, + /// The platform refused a command of the copy, which lands without all it was to move (the + /// module doc, "Refused copies"): set as it lands. + refused: AtomicBool, landed: Condvar, /// What its command buffer's completion gave of the copy, for a slow answer's line, and a /// release's pace ([`ReleasePace`]). @@ -1242,11 +1286,62 @@ impl CopyTrace { /// copy out of a cache runs as it is carried out. pub(crate) type Answer = Box; +/// What an answer waiting for a copy into a cache's pages runs as it lands, given whether it +/// moved all it was to ([`Landing::then`]). +type Landed = Box; + +/// What a copy into a cache's pages answers where the platform raised at it or refused a command +/// of it ([`CopyAnswers`]). +pub(crate) type Failed = Box; + +/// A `SURFACE_DOWNLOAD`'s or a `BLOCK_RELEASE`'s answers ([`SurfaceCaches::download`], +/// [`SurfaceCaches::released`]): `done` once the pages hold the cache, or `failed` where the +/// platform raised at the copy, or refused a command of it, so the pages lack what the cache +/// holds (the module doc, "Refused copies"). The first given goes; the other is dropped ungiven. +#[derive(Clone)] +pub(crate) struct CopyAnswers(Arc>>); + +impl CopyAnswers { + pub(crate) fn new(done: Answer, failed: Failed) -> Self { + CopyAnswers(Arc::new(Mutex::new(Some((done, failed))))) + } + + /// Answers that answer nothing: a copy no message of the guest's asked. + fn none() -> Self { + CopyAnswers::new(Box::new(|| {}), Box::new(|_| {})) + } + + /// The pages hold the cache. + fn done(&self) { + let answers = self.0.lock().take(); + if let Some((done, _)) = answers { + done(); + } + } + + /// The platform raised at the copy: `raise`. + pub(crate) fn failed(&self, raise: Raise) { + let answers = self.0.lock().take(); + if let Some((_, failed)) = answers { + failed(raise); + } + } + + /// The copy landed, `whole` where it moved all it was to: done, else failed as refused. + fn landed(&self, whole: bool) { + match whole { + true => self.done(), + false => self.failed(copy_refused_raise()), + } + } +} + impl Landing { /// A copy in flight. fn new() -> Arc { Arc::new(Landing { waiting: Mutex::new(Some(Vec::new())), + refused: AtomicBool::new(false), landed: Condvar::new(), times: Mutex::new(CopyTimes::default()), }) @@ -1264,19 +1359,30 @@ impl Landing { self.waiting.lock().is_none() } + /// The copy lands short of what it was to move, the platform having refused a command of it + /// ([`Self::land`] next). + fn refuse(&self) { + self.refused.store(true, Ordering::Release); + } + + /// Whether the copy landed short of what it was to move ([`Self::refuse`]). + fn refused(&self) -> bool { + self.refused.load(Ordering::Acquire) + } + /// [`Self::landed`], its lock tried: `None` where it is held. fn try_landed(&self) -> Option { Some(self.waiting.try_lock()?.is_none()) } - /// Gives `done` once the copy landed: here where it has. - fn then(&self, done: Answer) { + /// Gives `done` once the copy landed, with whether it moved all it was to: here where it has. + fn then(&self, done: Landed) { let mut waiting = self.waiting.lock(); match waiting.as_mut() { Some(answers) => answers.push(done), None => { drop(waiting); - done(); + done(!self.refused()); } } } @@ -1285,8 +1391,9 @@ impl Landing { fn land(&self) { let answers = self.waiting.lock().take(); self.landed.notify_all(); + let whole = !self.refused(); for done in answers.into_iter().flatten() { - done(); + done(whole); } } @@ -1310,11 +1417,48 @@ impl Landing { } } -/// Gives `done` once every copy of `landings` has landed: at once where none is in flight. -fn after_landings(mut landings: Vec>, done: Answer) { +/// Answers `answers` once every copy of `landings` has landed: done at once where none is in +/// flight; failed, as refused, once one lands short of what it was to move (the module doc, +/// "Refused copies"). +fn after_landings(mut landings: Vec>, answers: CopyAnswers) { match landings.pop() { - Some(landing) => landing.then(Box::new(move || after_landings(landings, done))), - None => done(), + Some(landing) => landing.then(Box::new(move |whole| match whole { + true => after_landings(landings, answers), + false => answers.landed(false), + })), + None => answers.done(), + } +} + +/// The degradation code of a copy of the host's own between a cache and its shapes, home or +/// pages that the platform refused a command or the encoder of, counted at each refusal (the +/// module doc, "Refused copies"; docs/conventions.md). +pub(crate) const COPY_REFUSED: &str = "surface-copy-refused"; + +/// The platform refused `what`, a copy of the host's own, a command of it or its encoder: +/// counted under [`COPY_REFUSED`], and the process's first logged (the module doc, "Refused +/// copies"). +fn copy_refused(what: std::fmt::Arguments<'_>) { + reims_vgpu_vulkan::answer::count_kind(COPY_REFUSED); + // Once per boot; later ones at debug, counted (`core::logging`). + log::warn!( + target: "reims_vgpu::graphics", kind:% = COPY_REFUSED; + "{what}: the platform refused it, and what it was to move is left as not copied, for the \ + guest's next use, download or release to copy again ({COPY_REFUSED})" + ); +} + +/// The raise a download or a release answers whose copy into the pages the platform refused a +/// command of ([`CopyAnswers::landed`]). +fn copy_refused_raise() -> Raise { + Raise::foreign("rgfx.platform.refused").with_detail(format!("refused: {COPY_REFUSED}")) +} + +/// Folds `encoded`, the platform's answer to a command of a copy of the host's own, into +/// `whole`, the copy's: refused once any is (the module doc, "Refused copies"). +pub(crate) fn fold(whole: &mut Encoded, encoded: Encoded) { + if !encoded.recorded() { + *whole = Encoded::REFUSED; } } @@ -1708,7 +1852,8 @@ impl ReleasePace

{ landed: None, }); let pace = Arc::downgrade(self); - copy.then(Box::new(move || { + // Timed from its landing whether it moved all it was to or landed short. + copy.then(Box::new(move |_| { let Some(pace) = pace.upgrade() else { return; }; @@ -2513,8 +2658,9 @@ pub(crate) struct SurfaceCaches { /// ([`INTO_PAGES_THREADS`]), a block's in the order their command buffers completed. lands_out: Arc, /// A fill since it was last taken found the platform refused a cache's buffer its memory - /// ([`Self::fill`], [`Self::fill_shapes`]): a begin's fails its command buffer - /// ([`Begin::out_of_memory`]). + /// ([`Self::fill`], [`Self::fill_shapes`]), or a command of the fill or of a copy into a + /// wide home ([`Self::home_in`], the module doc, "Refused copies"): a begin's fails its + /// command buffer ([`Begin::out_of_memory`]). memory_refused: bool, /// The command buffers finished that used a cache and wait on the GPU for a buffer of another /// queue that had not finished then, each as the cache's users name it: by its queue and the @@ -2577,7 +2723,8 @@ pub(crate) const INTO_PAGES_THREADS: &str = "reims-vgpu.graphics-into-pages"; /// Fills `length` bytes of `cache` with zeros on `transfer`'s queue, its command buffer owed to /// `owed_commits` ([`SurfaceCaches::zero`]): the transfer event's value at which it is done, -/// `None` where the platform made no command buffer or encoder for it. +/// `None` where the platform made no command buffer or encoder for it, or refused a command of it +/// (the module doc, "Refused copies"). fn zero_on( transfer: &mut Transfer

, owed_commits: &mut Vec, @@ -2591,16 +2738,21 @@ fn zero_on( return Ok(None); }; let range = NsRange::new(0, length); - blit.encode( + let filled = blit.encode( ON, BlitCmd::FillBuffer { buffer: cache, range, value: 0, }, - )? - .go_on(); - blit.encode(ON, BlitCmd::EndEncoding)?.go_on(); + )?; + let ended = blit.encode(ON, BlitCmd::EndEncoding)?; + // Refused, the fill is not made, its command buffer not committed (the module doc, "Refused + // copies"). + if !filled.recorded() || !ended.recorded() { + copy_refused(format_args!("a device cache's fill with zeros")); + return Ok(None); + } transfer.signalled += 1; let value = transfer.signalled; cb.encode_signal(Some(EventRef::Event(&transfer.event)), value)?; @@ -3032,8 +3184,10 @@ impl SurfaceCaches

{ block: u64, generation: u64, ) -> RaiseResult { + // A copy the platform refuses leaves the pages without the cache's write, which the fill + // after it then drops: the pages are the surface's from its naming on. if self.written_since_host(block) { - self.write_back(device, block, Box::new(|| {}), None)?; + self.write_back(device, block, CopyAnswers::none(), None)?; } self.fill_named_again(device, block, generation)?; Ok(true) @@ -3064,7 +3218,7 @@ impl SurfaceCaches

{ return self.named_again(device, block, generation); } if self.by_block.contains_key(&block) { - self.released(device, block, 0, None, None, Box::new(|| {}), None)?; + self.released(device, block, 0, None, None, CopyAnswers::none(), None)?; } // Past the caches' budget the block lies in place in its pages, as where the platform // makes no cache: the make was not tried, or its cache is let go of by the caller. @@ -3345,7 +3499,7 @@ impl SurfaceCaches

{ made: &mut Option>>, ) -> RaiseResult { if self.by_block.contains_key(&block) { - self.released(device, block, 0, None, None, Box::new(|| {}), None)?; + self.released(device, block, 0, None, None, CopyAnswers::none(), None)?; } let room = self.deferred_room(block); let mut video = None; @@ -3484,7 +3638,8 @@ impl SurfaceCaches

{ /// is no work of the caches', and its writes, were there any, would take these zeros over /// them; the bundle names no such buffer. /// Nothing for any other cache, and where the caches have no transfer queue or the platform - /// made no command buffer or encoder for the fill. + /// made no command buffer or encoder for the fill, or refused it: the zeros are then owed at + /// the video's next use. pub(super) fn zero_for_video(&mut self, block: u64) -> RaiseResult<()> { let (Some(transfer), Some(cache)) = (self.transfer.as_mut(), self.by_block.get_mut(&block)) else { @@ -4184,7 +4339,7 @@ impl SurfaceCaches

{ let Some(cache) = self.by_block.get_mut(&block) else { return Ok(()); }; - let written = cache.written; + let written = cache.holds_write(); let Some(home) = cache.wide.as_mut().filter(|h| h.stale) else { return Ok(()); }; @@ -4192,8 +4347,20 @@ impl SurfaceCaches

{ if home.pages && !written { return Ok(()); } - if encode_home::

(cb, cache, Way::Out, self.fence.as_ref())? { - self.counts.wide_copies += 1; + match encode_home::

(cb, cache, Way::Out, self.fence.as_ref())? { + Some(copied) if copied.recorded() => self.counts.wide_copies += 1, + // Refused, the home lacks the texels still, and the command buffer fails (the module + // doc, "Refused copies"). + Some(_) => { + if let Some(home) = cache.wide.as_mut() { + home.stale = true; + } + self.memory_refused = true; + copy_refused(format_args!( + "the IOSurface block at {block:#x}: a copy of its cache into its wide home" + )); + } + None => {} } Ok(()) } @@ -4202,25 +4369,37 @@ impl SurfaceCaches

{ /// through the textures over its wide home (`from_home`) or over its cache: the side it /// wrote is copied into the other in `cb`, its texel rows alone, so the encoders after it /// read the write through either, as Metal's do (the module doc, "Wider than the plane"). - /// Nothing where the block has no wide home. + /// Nothing where the block has no wide home. Whether the platform refused the copy, which + /// fails the command buffer (the module doc, "Refused copies"): a home it was to copy into + /// lacks the cache's texels still. pub(crate) fn reconcile( &mut self, cb: &P::CommandBuffer, block: u64, from_home: bool, - ) -> RaiseResult<()> { + ) -> RaiseResult { let Some(cache) = self.by_block.get_mut(&block) else { - return Ok(()); + return Ok(false); }; let Some(home) = cache.wide.as_mut() else { - return Ok(()); + return Ok(false); }; home.stale = false; let way = if from_home { Way::In } else { Way::Out }; - if encode_home::

(cb, cache, way, self.fence.as_ref())? { - self.counts.wide_copies += 1; + match encode_home::

(cb, cache, way, self.fence.as_ref())? { + Some(copied) if copied.recorded() => self.counts.wide_copies += 1, + Some(_) => { + if let Some(home) = cache.wide.as_mut().filter(|_| !from_home) { + home.stale = true; + } + copy_refused(format_args!( + "the IOSurface block at {block:#x}: a copy between its cache and its wide home" + )); + return Ok(true); + } + None => {} } - Ok(()) + Ok(false) } /// The fence an encoder that may have written a laid-out cache or its wide home updates as it @@ -4430,14 +4609,15 @@ impl SurfaceCaches

{ let into: Vec = (others.iter()).filter(|o| o.1).map(|o| o.0).collect(); // The source's overlap goes into the buffer on the way: within its extent. Where the // platform refuses the buffer's memory, no copy is made, and `refused` fails the - // command buffer (the module doc, "Deferred memory"). + // command buffer (the module doc, "Deferred memory"); so it does where the platform + // refuses a command of the copy ("Refused copies"). if !into.is_empty() && !cache.copy_through(MemoryFor::Reconcile) { *refused = true; } else { if !into.is_empty() { cache.changed.add(key.span()); } - shapes::copy_overlaps::

( + let copied = shapes::copy_overlaps::

( cb, &cache.device, &cache.shapes, @@ -4445,6 +4625,13 @@ impl SurfaceCaches

{ self.fence.as_ref(), &mut self.counts.shapes, )?; + if !copied.recorded() { + *refused = true; + copy_refused(format_args!( + "the IOSurface block at {block:#x}: a write's copy into the other shapes \ + of its plane" + )); + } } for (id, _) in others.iter().filter(|o| !o.1) { let Some(shape) = cache.shapes.take_id(*id) else { @@ -4931,7 +5118,9 @@ impl SurfaceCaches

{ if self.pending(block, true) > 0 || self.deferring(block) { return false; } - self.by_block.get(&block).is_some_and(|cache| cache.written) + self.by_block + .get(&block) + .is_some_and(SurfaceCache::holds_write) } /// Runs `op` on the caches once every command buffer begun and not finished that may write @@ -5353,26 +5542,53 @@ impl SurfaceCaches

{ cb.encode_wait(Some(EventRef::Event(writer)), end)?; } // A buffer that lacks the pages takes them first ("Straight fills"), through the - // view, which needs no piece. + // view, which needs no piece. A copy not made, its command buffer not committed, + // leaves it lacking them still. + let (lacks, changed) = (cache.lacks, cache.changed.clone()); let staging = (None, &self.spares, &mut Vec::new()); - refill::

(device, &cb, cache, block, &mut self.counts, staging)?; + let mut whole = refill::

(device, &cb, cache, block, &mut self.counts, staging)?; let view = match &cache.pages { Some(CachePages::View(pages)) => Some(pages), _ => None, }; // The dirty shapes first, the writer's (rule 3); made clean once the copy is // committed, so one not committed leaves them dirty. - let back = shapes::write_back::

(&cb, &cache.device, &cache.shapes, |s| s.dirty)?; - let Some(blit) = cb.blit_encoder(ON)? else { - continue; + let mut back = Vec::new(); + if whole.recorded() { + (back, whole) = + shapes::write_back::

(&cb, &cache.device, &cache.shapes, |s| s.dirty)?; + } + let blit = match whole.recorded() { + true => cb.blit_encoder(ON)?, + false => None, }; // A copy by runs the platform refuses encodes nothing: the download that follows - // copies, through the view it makes then (`copy`). - if !encode_out::

(&blit, cache, view)? { - blit.encode(ON, BlitCmd::EndEncoding)?.go_on(); + // copies, through the view it makes then (`copy`). One the platform refused a + // command or the encoder of is not made either (the module doc, "Refused copies"). + let out = match &blit { + Some(blit) => { + let out = encode_out::

(blit, cache, view)?; + fold(&mut whole, blit.encode(ON, BlitCmd::EndEncoding)?); + out + } + None => None, + }; + if blit.is_none() { + whole = Encoded::REFUSED; + } + if let Some(out) = out { + fold(&mut whole, out); + } + if out.is_none() || !whole.recorded() { + (cache.lacks, cache.changed) = (lacks, changed); + if !whole.recorded() { + copy_refused(format_args!( + "the IOSurface block at {block:#x}: an early copy of its cache into its \ + pages" + )); + } continue; } - blit.encode(ON, BlitCmd::EndEncoding)?.go_on(); let landing = Landing::new(); // The answers waiting go as the platform sees the copy done, on its thread, with no // wake of a handler thread between; the buffers live until its completed handler, @@ -5427,7 +5643,9 @@ impl SurfaceCaches

{ /// `generation` or the newer one it holds, on the transfer queue, after every command buffer /// that used it before, reading the host's devices' writes over the pages so far; where a /// deferred copy is being made ([`Self::carry_out`]), the fill's command buffer signals its - /// event. The transfer event's value at which it is done; `None` where it made none. + /// event. The transfer event's value at which it is done; `None` where it made none. A fill + /// the platform refused a command of fails the command buffer whose begin asked it (the + /// module doc, "Refused copies"). fn fill( &mut self, device: &P::Device, @@ -5484,18 +5702,20 @@ impl SurfaceCaches

{ if !reserve.is_empty() { self.left_over.insert(block, reserve); } - let staged = staged?; + let (staged, copied) = staged?; if let Some(staged) = staged { cb.add_completed_handler(ON, Box::new(move |_: CompletedInfo| staged.done()))?; } // Every shape takes the CPU's bytes the buffer took, its own writes not copied out // overwritten as the buffer's are (the module doc of `shapes`); a straight fill gave - // them the pages' bytes already. + // them the pages' bytes already. A buffer whose fill was refused gives them none. + let mut whole = copied; if straight { self.counts.straight += 1; - } else { + } else if copied.recorded() { let (buffer, table) = (&cache.device, &mut cache.shapes); - shapes::fill::

(&cb, buffer, table, |_| true, &mut self.counts.shapes)?; + let filled = shapes::fill::

(&cb, buffer, table, |_| true, &mut self.counts.shapes); + fold(&mut whole, filled?); } #[cfg(windows)] exported::planes_filled(&cache.surface); @@ -5520,16 +5740,30 @@ impl SurfaceCaches

{ } let length = cache.moved(Way::In); if let Some(cache) = self.by_block.get_mut(&block) { - cache.generation = Some(cache.generation.map_or(generation, |g| g.max(generation))); - cache.host_read = host; cache.filled_at = value; cache.users.clear(); - // A stand-in home lacks the pages' texels the fill brought; a home over the pages - // holds them. - if let Some(home) = cache.wide.as_mut().filter(|home| !home.pages) { - home.stale = true; + // A fill refused leaves the cache at its older generation, for the next use to fill + // again; a shape whose own copy was refused owes it still (the module doc, "Refused + // copies"). + if copied.recorded() { + cache.generation = Some(cache.generation.map_or(generation, |g| g.max(generation))); + cache.host_read = host; + // A stand-in home lacks the pages' texels the fill brought; a home over the + // pages holds them. + if let Some(home) = cache.wide.as_mut().filter(|home| !home.pages) { + home.stale = true; + } } } + if !whole.recorded() { + self.memory_refused = true; + copy_refused(format_args!( + "the IOSurface block at {block:#x}: a fill of its cache from its pages" + )); + } + if !copied.recorded() { + return Ok(Some(value)); + } self.owes_none(block); self.counts.fills += 1; self.counts.filled_bytes += length; @@ -5547,7 +5781,9 @@ impl SurfaceCaches

{ /// `CacheSurface::clear_of`), clears their images instead, with the buffer's memory left /// unmade (the module doc of `shapes`, "Zeros"; [`shapes::fill_clears`]); a fill that owes /// another shape copies through the buffer, its memory made. The transfer event's value at - /// which it is done; `None` where it made none, as where nothing was left to fill. + /// which it is done; `None` where it made none, as where nothing was left to fill. A shape + /// whose fill the platform refused owes it still, and the command buffer whose begin asked + /// it fails (the module doc, "Refused copies"). fn fill_shapes(&mut self, device: &P::Device, block: u64) -> RaiseResult> { let asker = self.asker.take(); self.touch_shapes(block); @@ -5596,34 +5832,45 @@ impl SurfaceCaches

{ let mut reserve = self.reserved.remove(&block).unwrap_or_default(); reserve.extend(self.left_over.remove(&block).unwrap_or_default()); let owed: &dyn Fn(&shapes::Shape) -> bool = &|s| s.owed; - let mut filled = || -> RaiseResult> { + let mut filled = || -> RaiseResult<(Vec, Encoded)> { if clearing { let (surface, counts) = (&cache.surface, &mut self.counts.shapes); let pass_of = |s: &shapes::Shape| Ok(surface.clear_of(&s.key)); - shapes::fill_clears::

(pass_of, &cb, &mut cache.shapes, owed, counts)?; - return Ok(Vec::new()); + let cleared = + shapes::fill_clears::

(pass_of, &cb, &mut cache.shapes, owed, counts)?; + return Ok((Vec::new(), cleared)); } let staging = (timed, &self.spares, &mut reserve); if straight { let way = (Way::In, block, Some(owed)); - let staged = copy::

(device, &cb, cache, way, &mut self.counts, staging, None)?; + let (staged, copied) = + copy::

(device, &cb, cache, way, &mut self.counts, staging, None)?; if let Some(staged) = staged { cb.add_completed_handler(ON, Box::new(move |_: CompletedInfo| staged.done()))?; } - return Ok(Vec::new()); + return Ok((Vec::new(), copied)); + } + // A buffer that lacks the pages takes them first, the dirty shapes' writes over them, + // and the shapes owed take the buffer once it holds both: none from a buffer whose + // refill or write-back was refused (the module doc, "Refused copies"). + let refilled = refill::

(device, &cb, cache, block, &mut self.counts, staging)?; + if !refilled.recorded() { + return Ok((Vec::new(), refilled)); } - // A buffer that lacks the pages takes them first, the dirty shapes' writes over them. - refill::

(device, &cb, cache, block, &mut self.counts, staging)?; let (buffer, table) = (&cache.device, &mut cache.shapes); - let back = shapes::write_back::

(&cb, buffer, table, |s| s.dirty && !s.owed)?; - shapes::fill::

(&cb, buffer, table, owed, &mut self.counts.shapes)?; - Ok(back) + let (back, mut whole) = + shapes::write_back::

(&cb, buffer, table, |s| s.dirty && !s.owed)?; + if whole.recorded() { + let filled = shapes::fill::

(&cb, buffer, table, owed, &mut self.counts.shapes); + fold(&mut whole, filled?); + } + Ok((back, whole)) }; let filled = filled(); if !reserve.is_empty() { self.left_over.insert(block, reserve); } - let back = filled?; + let (back, whole) = filled?; #[cfg(windows)] if planes { exported::planes_filled(&cache.surface); @@ -5652,6 +5899,12 @@ impl SurfaceCaches

{ cache.wrote_shapes(&back); cache.shapes.written_back(&back, &mut self.counts.shapes); } + if !whole.recorded() { + self.memory_refused = true; + copy_refused(format_args!( + "the IOSurface block at {block:#x}: a fill of its shapes" + )); + } self.counts.shapes.fills_made += 1; Ok(Some(value)) } @@ -5765,7 +6018,7 @@ impl SurfaceCaches

{ let Some(cache) = self.by_block.get_mut(&block) else { return true; }; - if cache.written + if cache.holds_write() || (cache.out.as_ref()).is_some_and(|out| out.landing.try_landed() != Some(true)) { return false; @@ -5789,13 +6042,15 @@ impl SurfaceCaches

{ /// command buffer that used it, where one that may write it was committed since its last copy, /// no device of the host wrote the pages since its last fill, and the CPU's generation `cpu` /// of the surface, as the copy is made, is not past the cache's ([`Self::behind_the_cpu`]); - /// `done` once the pages hold it, at once where nothing is to copy. + /// `answers` done once the pages hold it, at once where nothing is to copy, or failed where + /// the platform refused a command of the copy, its own or one in flight it waits for (the + /// module doc, "Refused copies"). pub(crate) fn download( &mut self, device: &P::Device, block: u64, cpu: Option, - done: Box, + answers: CopyAnswers, trace: Option<&CopyTrace>, ) -> RaiseResult<()> { self.after_recovery(device); @@ -5823,7 +6078,7 @@ impl SurfaceCaches

{ if let Some(trace) = trace { trace.behind(&landings); } - after_landings(landings, done); + after_landings(landings, answers); return Ok(()); } // The CPU reads back a write that was the only one since the cache's last copy: the next @@ -5840,14 +6095,15 @@ impl SurfaceCaches

{ pages are not named; nothing is copied" ); } - self.write_back(device, block, done, trace) + self.write_back(device, block, answers, trace) } /// The block at `block` went (its `BLOCK_RELEASE`, of `RGFX_BLOCK_RELEASE_*` `flags`): its /// cache goes once the pages hold what a buffer wrote of it, unless a device of the host wrote /// them since its last fill, or the CPU's generation `cpu` of the surface, as the copy is - /// made, is past the cache's ([`Self::behind_the_cpu`]); `done` then, at once where nothing is - /// to copy. A release whose surface had no client left (`RGFX_BLOCK_RELEASE_NO_CLIENT`) copies + /// made, is past the cache's ([`Self::behind_the_cpu`]); `answers` done then, at once where + /// nothing is to copy, or failed where the platform refused a command of the copy (the + /// module doc, "Refused copies"). A release whose surface had no client left (`RGFX_BLOCK_RELEASE_NO_CLIENT`) copies /// too: a surface with no client can still be looked up again, from a mach port or an XPC /// object that holds it (how one process hands a surface it drew to another), and the process /// that looks it up then reads the pages. One whose surface nothing but the kext held @@ -5864,7 +6120,7 @@ impl SurfaceCaches

{ flags: u32, cpu: Option, clients: Option, - done: Box, + answers: CopyAnswers, trace: Option<&CopyTrace>, ) -> RaiseResult>> { self.after_recovery(device); @@ -5893,7 +6149,7 @@ impl SurfaceCaches

{ if let Some(trace) = trace { trace.behind(&landings); } - after_landings(landings, done); + after_landings(landings, answers); } else { if flags & RGFX_BLOCK_RELEASE_NO_CLIENT != 0 { self.counts.unread += 1; @@ -5901,7 +6157,7 @@ impl SurfaceCaches

{ if flagged { self.counts.retaken += 1; } - self.write_back(device, block, done, trace)?; + self.write_back(device, block, answers, trace)?; self.release_copy = self.out_copy(block); } let gone = self.by_block.remove(&block); @@ -6109,7 +6365,7 @@ impl SurfaceCaches

{ }; !unheld && cache.pages.is_some() - && (cache.written || self.pending(block, true) > 0 || self.deferring(block)) + && (cache.holds_write() || self.pending(block, true) > 0 || self.deferring(block)) } /// Notes a copy into the pages of host addresses `runs` asked and not yet landed, letting go of @@ -6135,12 +6391,14 @@ impl SurfaceCaches

{ /// Whether the block's cache holds a command buffer's write the pages do not: one was /// committed since its last copy, and no device of the host wrote the pages since its last - /// fill. Where one did, its write is the newer, and the cache's is dropped. + /// fill. Where one did, its write is the newer, and the cache's is dropped. A last copy + /// that landed short is taken back first ([`SurfaceCache::take_refused_out`]). fn written_since_host(&mut self, block: u64) -> bool { let host = self.watched.writes(block); let Some(cache) = self.by_block.get_mut(&block) else { return false; }; + cache.take_refused_out(); if cache.written && host > cache.host_read { cache.written = false; self.counts.host_writes += 1; @@ -6175,8 +6433,11 @@ impl SurfaceCaches

{ } /// Copies the cache of the block at `block` into the surface's pages on the transfer queue, - /// after every command buffer that used it; `done` once the copy has finished. Where no copy - /// can be made `done` is given at once. The copy signals the transfer event, which a use that + /// after every command buffer that used it; `answers` done once the copy has finished. Where + /// no copy can be made, done is given at once. Where the platform refuses a command of the + /// copy, its encoder, or a later round of a copy that circulates its pieces, failed once the + /// copy's command buffers have finished: the copy lands short, the cache stays written, and + /// its shapes whose write-back was refused stay dirty (the module doc, "Refused copies"). The copy signals the transfer event, which a use that /// writes the cache waits for on the GPU while it is in flight, and lands for the downloads and /// releases that copy nothing behind it ([`SurfaceCache::out`]), and for the `SURFACE_PAGES` /// of a block over the same pages ([`Self::copies_into`]). @@ -6184,19 +6445,19 @@ impl SurfaceCaches

{ &mut self, device: &P::Device, block: u64, - done: Box, + answers: CopyAnswers, trace: Option<&CopyTrace>, ) -> RaiseResult<()> { // A deferred block whose pages are not named has nowhere to copy to. if self.unattached(block).is_some() || !self.make_transfer(device)? { - done(); + answers.done(); return Ok(()); } let signal = (self.signal_with.as_ref()).map(|(event, number)| (event.clone_ref(), *number)); let (Some(transfer), Some(cache)) = (self.transfer.as_mut(), self.by_block.get_mut(&block)) else { - done(); + answers.done(); return Ok(()); }; // The buffer's memory first, as for every copy through it ("Deferred memory"); none for @@ -6205,7 +6466,7 @@ impl SurfaceCaches

{ let Some(cb) = (transfer.queue.command_buffer(ON)?).filter(|_| { cache.pages.is_some() && (moves_none || cache.copy_through(MemoryFor::WriteBack)) }) else { - done(); + answers.done(); return Ok(()); }; wait_before::

(&cb, signal.as_ref())?; @@ -6217,19 +6478,28 @@ impl SurfaceCaches

{ // the pages' own bytes beside the shapes' writes; not for a copy that moves none. let staging = (timed, &self.spares, &mut reserve); let refilled = if moves_none { - Ok(()) + Ok(Encoded::RECORDED) } else { refill::

(device, &cb, cache, block, &mut self.counts, staging) }; - if let Err(raise) = refilled { - if !reserve.is_empty() { - self.left_over.insert(block, reserve); + let refilled = match refilled { + Ok(refilled) => refilled, + Err(raise) => { + if !reserve.is_empty() { + self.left_over.insert(block, reserve); + } + return Err(raise); } - return Err(raise); - } - // The dirty shapes go into the buffer first, which takes them on to the pages (rule 3). - let back = shapes::write_back::

(&cb, &cache.device, &cache.shapes, |s| s.dirty); - let back = match back { + }; + // The dirty shapes go into the buffer first, which takes them on to the pages (rule 3): + // none into a buffer whose refill was refused, which would land over them as it is made + // again, and no copy out of a buffer that lacks the pages or a shape's write (the module + // doc, "Refused copies"). + let back = match refilled.recorded() { + true => shapes::write_back::

(&cb, &cache.device, &cache.shapes, |s| s.dirty), + false => Ok((Vec::new(), Encoded::REFUSED)), + }; + let (back, mut whole) = match back { Ok(back) => back, Err(raise) => { if !reserve.is_empty() { @@ -6239,19 +6509,24 @@ impl SurfaceCaches

{ } }; cache.wrote_shapes(&back); - let staged = copy::

( - device, - &cb, - cache, - (Way::Out, block, None), - &mut self.counts, - (timed, &self.spares, &mut reserve), - (transfer.rounds.as_ref()).map(|rounds| (&transfer.queue, rounds)), - ); + let staged = match whole.recorded() { + true => copy::

( + device, + &cb, + cache, + (Way::Out, block, None), + &mut self.counts, + (timed, &self.spares, &mut reserve), + (transfer.rounds.as_ref()).map(|rounds| (&transfer.queue, rounds)), + ), + false => Ok((None, Encoded::REFUSED)), + }; if !reserve.is_empty() { self.left_over.insert(block, reserve); } - let mut staged = staged?; + let (mut staged, copied) = staged?; + fold(&mut whole, copied); + let whole = whole.recorded(); // A copy that circulates its pieces commits its second round after `cb`, and each later // one as the host has moved the round before it in its piece out ([`Rounds`]); the last // signals the deferred copy's number, and the copy's own event stands for a value of @@ -6291,10 +6566,13 @@ impl SurfaceCaches

{ // piece is committed then; the last round's lands the copy, its GPU times and the // CPU's time those of the last round ([`Circulation`]). (Some(staged), Some(second)) => { - let end: CopyEnd = Box::new(move |gpu_times, took| { + let end: CopyEnd = Box::new(move |gpu_times, took, all| { drop(held); + if !all { + lands.refuse(); + } lands.land_timed(gpu_times, took); - done(); + answers.landed(all); }); let circulation = Arc::new(Circulation { block, @@ -6325,8 +6603,11 @@ impl SurfaceCaches

{ .map_or(std::time::Duration::ZERO, |(now, at)| { now().saturating_duration_since(at) }); + if !whole { + lands.refuse(); + } lands.land_timed(gpu_times, took); - done(); + answers.landed(whole); }; lands_out.submit_waitless(block, Box::new(lands_now)); }), @@ -6339,8 +6620,11 @@ impl SurfaceCaches

{ ON, Box::new(move |info: CompletedInfo| { CopyGpu::add(&gpu.out, info.gpu_times_ns); + if !whole { + lands.refuse(); + } lands.land_timed(info.gpu_times_ns, std::time::Duration::ZERO); - done(); + answers.landed(whole); }), )?; cb.add_completed_handler(ON, Box::new(move |_: CompletedInfo| drop(held)))?; @@ -6356,15 +6640,19 @@ impl SurfaceCaches

{ } let length = cache.moved(Way::Out); if let Some(cache) = self.by_block.get_mut(&block) { - cache.written = false; cache.users.clear(); cache.shapes.written_back(&back, &mut self.counts.shapes); - // A home over the pages takes the cache's texels with them. - if let Some(home) = cache.wide.as_mut().filter(|home| home.pages) { - home.stale = false; + // A copy refused leaves the cache written, for the next download or release to copy + // again (the module doc, "Refused copies"). + if whole { + cache.written = false; + // A home over the pages takes the cache's texels with them. + if let Some(home) = cache.wide.as_mut().filter(|home| home.pages) { + home.stale = false; + } + cache.read_back.writes = 0; } // This copy is the cache's last: an early copy before it is waited for on the GPU. - cache.read_back.writes = 0; cache.read_back.copy = None; cache.out = Some(OutCopy { value, @@ -6374,6 +6662,12 @@ impl SurfaceCaches

{ } let runs = (self.watched.0.lock().get(&block)).map_or_else(Vec::new, |p| p.runs.clone()); self.note_into(runs, &landing); + if !whole { + copy_refused(format_args!( + "the IOSurface block at {block:#x}: a copy of its cache into its pages" + )); + return Ok(()); + } self.counts.downloads += 1; self.counts.downloaded_bytes += length; Ok(()) @@ -7703,17 +7997,20 @@ impl Caches

{ /// An encoder just ended in command buffer `cb` that may have written the surfaces of /// `written`, each by its block and whether through a texture over its wide home: each side - /// written is copied into the other in `cb` ([`SurfaceCaches::reconcile`]). + /// written is copied into the other in `cb` ([`SurfaceCaches::reconcile`]). Whether the + /// platform refused a copy, which fails the command buffer (the module doc, "Refused + /// copies"). pub(crate) fn reconcile( &self, cb: &P::CommandBuffer, written: &[(u64, bool)], - ) -> RaiseResult<()> { + ) -> RaiseResult { let mut state = self.lock(); + let mut refused = false; for &(block, from_home) in written { - state.reconcile(cb, block, from_home)?; + refused |= state.reconcile(cb, block, from_home)?; } - Ok(()) + Ok(refused) } /// Whether the encoder being walked, which may have written the shapes `written`, each by its @@ -7729,7 +8026,8 @@ impl Caches

{ /// takes the write in `cb` ([`SurfaceCaches::reconcile_shapes`]). What goes is let go of with /// no lock held, a refusal logged. A cache's buffer the copy goes through has its memory made /// with the lock let go of first ([`Self::make_memory`]); whether the platform refused one - /// its memory, which fails the command buffer (the module doc, "Deferred memory"). + /// its memory, which fails the command buffer (the module doc, "Deferred memory"), or + /// refused a command of a copy ("Refused copies"). pub(crate) fn reconcile_shapes( &self, cb: &P::CommandBuffer, @@ -8336,7 +8634,7 @@ impl Caches

{ /// command buffer begun and not finished that may write it, waiting for none /// ([`Self::after_writers`]), `ran` as it is carried out then, and what it waited for then in /// `trace`: `done` once the pages hold the cache, or `failed` where the platform raised at - /// the copy. + /// the copy or refused a command of it (the module doc, "Refused copies"). #[allow(clippy::too_many_arguments)] // the download's, and its trace pub(crate) fn download( &self, @@ -8353,7 +8651,7 @@ impl Caches

{ let buffer = self .lock() .deferred_buffer(block, MemoryFor::Download, |c| { - c.written && !c.moves_none_out() + c.holds_write() && !c.moves_none_out() }); self.make_memory(buffer.into_iter().collect(), MemoryFor::Download); let mut state = self.lock(); @@ -8423,7 +8721,8 @@ impl Caches

{ /// The block at `block` went, its `BLOCK_RELEASE` ([`SurfaceCaches::released`]), after every /// command buffer begun and not finished that may write its cache, waiting for none /// ([`Self::after_writers`]), `ran` as it is carried out then: `done` once the pages hold the - /// cache, or `failed` where the platform raised at the copy, and the cache handed to + /// cache, or `failed` where the platform raised at the copy or refused a command of it (the + /// module doc, "Refused copies"), and the cache handed to /// `let_go`, which lets go of it on a thread of its own, with no lock of the caches' held. /// A release that may copy its cache waits for its turn first ([`ReleasePace`]), timed by /// `now`, the platform's monotonic clock. Nothing names the block until it is answered: the @@ -8488,8 +8787,10 @@ impl Caches

{ let device = on; let cpu = cpu_generation(®ion, block); let clients = surface_clients(®ion, block); + let answers = CopyAnswers::new(done, failed); + let asked = answers.clone(); let released = refusing(|| { - state.released(&device, block, flags, cpu, clients, done, Some(&trace)) + state.released(&device, block, flags, cpu, clients, asked, Some(&trace)) }); let copy = state.release_copy.take(); if let Some(turn) = turn { @@ -8498,7 +8799,7 @@ impl Caches

{ match released { Ok(Some(cache)) => let_go(cache), Ok(None) => {} - Err(raise) => failed(raise), + Err(raise) => answers.failed(raise), } }); if !may_copy { @@ -8612,7 +8913,8 @@ impl Caches

{ /// ([`SurfaceCaches::released`]), after every command buffer begun and not finished that may /// write it and the copies of it asked, waiting for them here: the buffers made over the /// block after it lie over its pages. The cache is returned, for the caller to let go of - /// with the lock let go. + /// with the lock let go. `done` once the pages hold it; a copy the platform refused a + /// command of gives none, counted (the module doc, "Refused copies"). pub(crate) fn released( &self, device: &P::Device, @@ -8628,7 +8930,8 @@ impl Caches

{ if reserve_ahead(&mut state, device, &wants) { self.wait_copies(&mut state, block); } - state.released(device, block, 0, None, None, done, None) + let answers = CopyAnswers::new(done, Box::new(|_| {})); + state.released(device, block, 0, None, None, answers, None) } /// A cache for the block at `block`, whose surface's pages `view` maps: `Ok(false)` where @@ -9034,8 +9337,10 @@ fn download_op( Box::new(move |state| { ran(); let cpu = cpu_generation(®ion, block); - if let Err(raise) = refusing(|| state.download(&device, block, cpu, done, Some(&trace))) { - failed(raise); + let answers = CopyAnswers::new(done, failed); + let asked = answers.clone(); + if let Err(raise) = refusing(|| state.download(&device, block, cpu, asked, Some(&trace))) { + answers.failed(raise); } }) } @@ -9467,42 +9772,43 @@ fn encode_out( blit: &P::BlitEncoder, cache: &SurfaceCache

, view: Option<&P::Buffer>, -) -> RaiseResult { +) -> RaiseResult> { let whole = 0..cache.length; let spans = (cache.texels.as_deref()).unwrap_or(std::slice::from_ref(&whole)); match (view, &cache.pages) { (Some(pages), _) => { let parts = cache.moves(spans.iter().map(|span| (span.clone(), span.start))); - between::

(blit, (&cache.device, pages), &parts, Way::Out)?; - Ok(true) + between::

(blit, (&cache.device, pages), &parts, Way::Out).map(Some) } (None, Some(CachePages::Runs { runs, .. })) => { let runs = match &cache.repitched { Some(laid) => laid.runs(runs), None => runs_at(runs, spans), }; - blit.copy_to_guest_ram(ON, &cache.device, &runs) + let by_runs = blit.copy_to_guest_ram(ON, &cache.device, &runs)?; + Ok(by_runs.then_some(Encoded::RECORDED)) } - (None, _) => Ok(false), + (None, _) => Ok(None), } } /// Encodes on `blit` a copy of each of `parts` between `cache` and `other`, a buffer that keeps /// the surface's layout (its view, or a copy's staging): each its byte of `other`, its byte of /// the cache and its bytes ([`SurfaceCache::moves`]), into the cache for [`Way::In`], out of it -/// for [`Way::Out`]. +/// for [`Way::Out`]. Refused where the platform refused one (the module doc, "Refused copies"). fn between( blit: &P::BlitEncoder, (cache, other): (&P::Buffer, &P::Buffer), parts: &[(u64, u64, u64)], way: Way, -) -> RaiseResult<()> { +) -> RaiseResult { + let mut whole = Encoded::RECORDED; for &(at, in_cache, size) in parts { let (source, source_offset, destination, destination_offset) = match way { Way::In => (other, at, cache, in_cache), Way::Out => (cache, in_cache, other, at), }; - blit.encode( + let encoded = blit.encode( ON, BlitCmd::CopyBufferToBuffer { source_buffer: Some(source), @@ -9511,37 +9817,47 @@ fn between( destination_offset, size, }, - )? - .go_on(); + )?; + fold(&mut whole, encoded); } - Ok(()) + Ok(whole) } /// Encodes in `cb`, in a blit encoder of its own, a copy of `cache`'s texel rows between the /// cache and its wide home ([`WideHome`]): into the cache for [`Way::In`], out of it into the home /// for [`Way::Out`]. Each row moves between its place in the cache, at the GPU's pitch, and its /// place in the surface's layout, which the home keeps ([`Repitched::cut`]), after the encoder -/// waits for `fence`, the writers' ([`SurfaceCaches::writes_fence`]). False, with nothing -/// encoded, where the cache has no home or the platform made no encoder. +/// waits for `fence`, the writers' ([`SurfaceCaches::writes_fence`]). `None`, with nothing +/// encoded, where the cache has no home; refused where the platform made no encoder or refused +/// a command (the module doc, "Refused copies"), with no copy after a wait it refused. fn encode_home( cb: &P::CommandBuffer, cache: &SurfaceCache

, way: Way, fence: Option<&P::Fence>, -) -> RaiseResult { +) -> RaiseResult> { let Some(home) = &cache.wide else { - return Ok(false); + return Ok(None); }; let Some(blit) = cb.blit_encoder(ON)? else { - return Ok(false); + return Ok(Some(Encoded::REFUSED)); }; + let mut whole = Encoded::RECORDED; if let Some(fence) = fence { - blit.encode(ON, BlitCmd::WaitForFence { fence })?.go_on(); + fold( + &mut whole, + blit.encode(ON, BlitCmd::WaitForFence { fence })?, + ); } - let parts = cache.moves([(0..cache.length, 0)]); - between::

(&blit, (&cache.device, &home.buffer), &parts, way)?; - blit.encode(ON, BlitCmd::EndEncoding)?.go_on(); - Ok(true) + if whole.recorded() { + let parts = cache.moves([(0..cache.length, 0)]); + fold( + &mut whole, + between::

(&blit, (&cache.device, &home.buffer), &parts, way)?, + ); + } + fold(&mut whole, blit.encode(ON, BlitCmd::EndEncoding)?); + Ok(Some(whole)) } /// The longest piece of a staged copy (the module doc, "Staged copies"): metal2vulkan-runtime's @@ -9806,9 +10122,10 @@ fn end_rounds(begun: Option>) -> RaiseResult<()> { Ok(()) } -/// Lands a copy out ([`Circulation`]), given its last command buffer's GPU times and the CPU's -/// time of its last move into the pages. -type CopyEnd = Box, std::time::Duration) + Send>; +/// Lands a copy out ([`Circulation`]), given its last command buffer's GPU times, the CPU's time +/// of its last move into the pages, and whether it made every round (the module doc, "Refused +/// copies"). +type CopyEnd = Box, std::time::Duration, bool) + Send>; /// A copy out that circulates its pieces ([`Rounds`]), as its rounds' completed handlers share /// it. @@ -9844,8 +10161,9 @@ impl Circulation

{ /// ([`Staging::drain`]), then the round after it in its piece, where there is one, is /// committed. After the last round the host sets the copy's own event to /// [`ROUNDS_DRAINED`], gives the pieces back and lands the copy. Where the platform makes a - /// round not, logged, the copy ends with the round before it, and the deferred copy's - /// number that round would have signalled is set on the CPU. + /// round not, or refuses a command of it, counted and logged ([`COPY_REFUSED`]), the copy + /// ends with the round before it, short (the module doc, "Refused copies"), and the + /// deferred copy's number that round would have signalled is set on the CPU. fn round_done(self: &Arc, round: usize, gpu_times: Option<(u64, u64)>) { let at = self.now.as_ref().map(|now| now()); let mut staged = self.staged.lock(); @@ -9861,12 +10179,11 @@ impl Circulation

{ if next < rounds.count { let made = refusing(|| self.commit_round(&staging.pieces, rounds, next)); if !matches!(made, Ok(true)) { - log::warn!( - target: "reims_vgpu::graphics", - "the IOSurface block at {:#x}: the platform made round {next} of its staged \ - copy out not ({made:?}); the copy ends with the rounds before it", + copy_refused(format_args!( + "the IOSurface block at {:#x}: round {next} of its staged copy out \ + ({made:?}), the copy ending with the rounds before it", self.block - ); + )); cut = true; } } @@ -9886,6 +10203,8 @@ impl Circulation

{ return; }; drop(staged); + let all = (staging.rounds.as_ref()) + .is_none_or(|rounds| rounds.count == rounds.later.len() + ROUND_PIECES); if let Some(rounds) = &staging.rounds { let mut sets = vec![(&rounds.own, ROUNDS_DRAINED)]; if rounds.count < rounds.later.len() + ROUND_PIECES @@ -9909,14 +10228,15 @@ impl Circulation

{ now().saturating_duration_since(at) }); if let Some(end) = self.end.lock().take() { - end(gpu_times, took); + end(gpu_times, took, all); } } /// Commits round `round` on the rounds' queue: a copy of its parts out of the cache into its /// piece of `pieces`, after the copy's first rounds, its completion handled as each round's /// ([`round_ended`]); the last round signals the deferred copy's number. False where the - /// platform made its command buffer or its encoder not. + /// platform made its command buffer or its encoder not, or refused a command of it, which + /// is then not committed. fn commit_round( self: &Arc, pieces: &[Piece

], @@ -9936,8 +10256,11 @@ impl Circulation

{ let Some(blit) = cb.blit_encoder(ON)? else { return Ok(false); }; - between::

(&blit, (&rounds.cache, &**piece), parts, Way::Out)?; - blit.encode(ON, BlitCmd::EndEncoding)?.go_on(); + let copied = between::

(&blit, (&rounds.cache, &**piece), parts, Way::Out)?; + let ended = blit.encode(ON, BlitCmd::EndEncoding)?; + if !copied.recorded() || !ended.recorded() { + return Ok(false); + } if round + 1 == rounds.count { signal_after::

(&cb, rounds.signal.as_ref())?; } @@ -10406,6 +10729,11 @@ impl StagedCodes { /// caller commits after `cb`, and the copy keeps each later round's parts for the host to /// commit on the rounds' queue. Where the platform makes no event, command buffer or encoder /// for the second round, it takes a piece for each piece's length as any other copy does. +/// +/// With the staging, whether every command was recorded: refused where the platform made no +/// encoder or refused a command, or no view or piece was made, so nothing was copied (the module +/// doc, "Refused copies"). A refused copy leaves the record and [`SurfaceCache::lacks`] as they +/// were, moves no piece's bytes into the pages, and makes no later round. fn copy( device: &P::Device, cb: &P::CommandBuffer, @@ -10414,19 +10742,26 @@ fn copy( counts: &mut CacheCounts, (timed, spares, reserve): (Option<&Now>, &Arc>, &mut Vec>), rounds_on: Option<(&P::CommandQueue, &P::CommandQueue)>, -) -> RaiseResult>> { +) -> RaiseResult<(Option>, Encoded)> { if way == Way::In && cache.pages.is_some() { cache.changed = Changed::All; } let Some(blit) = cb.blit_encoder(ON)? else { - return Ok(None); + return Ok((None, Encoded::REFUSED)); }; + let mut whole = Encoded::RECORDED; let by_runs = match (&cache.pages, way) { (Some(CachePages::Runs { runs, .. }), Way::In) => match &cache.repitched { Some(laid) => blit.copy_from_guest_ram_at(ON, &laid.runs(runs), &cache.device)?, None => blit.copy_from_guest_ram(ON, runs, &cache.device, 0)?, }, - (Some(CachePages::Runs { .. }), Way::Out) => encode_out::

(&blit, cache, None)?, + (Some(CachePages::Runs { .. }), Way::Out) => match encode_out::

(&blit, cache, None)? { + Some(out) => { + fold(&mut whole, out); + true + } + None => false, + }, (Some(CachePages::View(_) | CachePages::Copied(_)) | None, _) => false, }; let mut moved = by_runs; @@ -10458,15 +10793,19 @@ fn copy( Some(pick) => { let sources = [(pages, 0..cache.length, 0)]; let table = &mut cache.shapes; - shapes::fill_from::

(&blit, &sources, table, pick, &mut counts.shapes)?; + let counts = &mut counts.shapes; + let filled = shapes::fill_from::

(&blit, &sources, table, pick, counts); + fold(&mut whole, filled?); } None => { let parts = cache.moves([(0..cache.length, 0)]); - between::

(&blit, (&cache.device, pages), &parts, Way::In)?; + let copied = between::

(&blit, (&cache.device, pages), &parts, Way::In); + fold(&mut whole, copied?); } }, Way::Out => { - encode_out::

(&blit, cache, Some(pages))?; + let out = encode_out::

(&blit, cache, Some(pages))?; + fold(&mut whole, out.unwrap_or(Encoded::REFUSED)); } } moved = true; @@ -10539,7 +10878,9 @@ fn copy( .map(|p| (&*pieces[p.piece], p.bytes.clone(), p.at)) .collect(); let table = &mut cache.shapes; - shapes::fill_from::

(&blit, &sources, table, pick, &mut counts.shapes)?; + let filled = + shapes::fill_from::

(&blit, &sources, table, pick, &mut counts.shapes); + fold(&mut whole, filled?); } // The GPU's copy moves each place's bytes the cache holds between its piece and the // cache, the CPU's the surface's between it and the pages; a copy out's CPU copy @@ -10554,11 +10895,14 @@ fn copy( later[round - ROUND_PIECES].extend(parts); } (Some((_, _, _, second)), 1) => { - between::

(second, (&cache.device, &*pieces[1]), &parts, way)?; + let copied = + between::

(second, (&cache.device, &*pieces[1]), &parts, way); + fold(&mut whole, copied?); } _ => { let piece = &*pieces[place.piece]; - between::

(&blit, (&cache.device, piece), &parts, way)?; + let copied = between::

(&blit, (&cache.device, piece), &parts, way); + fold(&mut whole, copied?); } } } @@ -10569,7 +10913,7 @@ fn copy( } let rounds = match rounds.take() { Some((own, queue, second, encoder)) => { - encoder.encode(ON, BlitCmd::EndEncoding)?.go_on(); + fold(&mut whole, encoder.encode(ON, BlitCmd::EndEncoding)?); second.encode_signal(Some(EventRef::Shared(&own)), ROUNDS_BEGUN)?; Some(Rounds { second: Some(second), @@ -10632,14 +10976,16 @@ fn copy( ); } let parts = cache.moves([(place.bytes.clone(), place.at)]); - between::

( + let copied = between::

( &blit, (&cache.device, &*pieces[place.piece]), &parts, Way::In, - )?; + ); + fold(&mut whole, copied?); from += bytes; } + moved = true; cache.staged = true; if let (Some(now), Some(at)) = (timed, at) { FILLS.copied(from); @@ -10654,14 +11000,27 @@ fn copy( } end_rounds::

(rounds)?; } - blit.encode(ON, BlitCmd::EndEncoding)?.go_on(); - if moved && cache.pages.is_some() { + fold(&mut whole, blit.encode(ON, BlitCmd::EndEncoding)?); + // Nothing copied, no view or piece made, is no copy made. + if !moved { + whole = Encoded::REFUSED; + } + if !whole.recorded() { + // A refused copy's pieces hold bytes no GPU copy wrote: none go into the pages, and no + // later round is made, the second's command buffer let go of uncommitted. + if let Some(staging) = staged.as_mut() { + staging.into = None; + staging.rounds = None; + } + return Ok((staged, whole)); + } + if cache.pages.is_some() { cache.changed = Changed::none(); if way == Way::In { cache.lacks = straight.is_some(); } } - Ok(staged) + Ok((staged, whole)) } /// Where `cache`'s buffer lacks the pages' bytes its shapes took ([`SurfaceCache::lacks`]), @@ -10669,7 +11028,8 @@ fn copy( /// "Straight fills"): of the block at `block`, as [`copy`] fills it, through `staging`, its /// pieces kept until `cb` completes; counted in `counts`. The buffer then holds the pages as they /// are now, not as the straight fill read them. Its memory is made already. Nothing where it -/// lacks none; where nothing was copied, it lacks them still. +/// lacks none; where nothing was copied, it lacks them still, refused (the module doc, "Refused +/// copies"). fn refill( device: &P::Device, cb: &P::CommandBuffer, @@ -10677,11 +11037,11 @@ fn refill( block: u64, counts: &mut CacheCounts, staging: (Option<&Now>, &Arc>, &mut Vec>), -) -> RaiseResult<()> { +) -> RaiseResult { if !cache.lacks { - return Ok(()); + return Ok(Encoded::RECORDED); } - let staged = copy::

( + let (staged, whole) = copy::

( device, cb, cache, @@ -10697,7 +11057,7 @@ fn refill( counts.buffer_refills += 1; counts.buffer_refilled_bytes += cache.moved(Way::In); } - Ok(()) + Ok(whole) } /// Where a fill goes straight from the pages into the shapes ([`copy`]), the shapes it fills. @@ -16079,6 +16439,34 @@ pub(super) mod tests { assert_eq!((counts.downloads, counts.runs_refused), (1, 1)); } + /// A copy of a cache into its pages that the platform refuses, here through the view its + /// refused copy by runs made, leaves the cache as not copied: the download is answered + /// refused, never done over the pages' older bytes, counted under its own code, and the next + /// download copies the cache again and is answered done + #[test] + fn a_download_whose_copy_into_its_pages_the_platform_refuses_is_refused() { + use reims_vgpu_vulkan::core::testkit::Step; + use reims_vgpu_vulkan::core::testkit::impls::blit::BUFFER_TO_GUEST_RAM; + let mut r = cached_by_runs(); + let cache = cache_id(&r); + use_surfaces(&mut r, 1, 0x100, &[(BLOCK, 0, true)]); + r.p.script().push(BUFFER_TO_GUEST_RAM, Step::value(false)); + r.p.script().push(COPY, Step::Nil); + let before = counted("surface-copy-refused"); + let (done, refused) = download_answered(&r, BLOCK); + r.p.world().complete_all(CompleteOn::Caller); + assert!(refused.load(Ordering::SeqCst), "refused"); + assert!(!done.load(Ordering::SeqCst), "never done"); + assert_eq!(counted("surface-copy-refused"), before + 1); + let mark = r.p.call_log().mark(); + let (done, refused) = download_answered(&r, BLOCK); + let out = copies(&r.p.call_log().since(mark)); + assert_eq!(out.len(), 1, "copied again"); + assert_eq!(out[0].0, cache); + r.p.world().complete_all(CompleteOn::Caller); + assert!(done.load(Ordering::SeqCst) && !refused.load(Ordering::SeqCst)); + } + /// A block named by its runs that the platform makes no cache for takes its view then, and /// its buffers lie over the view #[test] @@ -16565,6 +16953,23 @@ pub(super) mod tests { done } + /// A download of the block at `block`'s cache, as [`download`]: whether it was answered + /// done, and whether refused (its `failed` given). + pub(crate) fn download_answered(r: &Rig, block: u64) -> (Arc, Arc) { + let (done, refused) = ( + Arc::new(AtomicBool::new(false)), + Arc::new(AtomicBool::new(false)), + ); + let (set, refuse) = (Arc::clone(&done), Arc::clone(&refused)); + r.dec.surface_download( + &r.device, + block, + Box::new(move || set.store(true, Ordering::SeqCst)), + Box::new(move |_| refuse.store(true, Ordering::SeqCst)), + ); + (done, refused) + } + /// Completes every command buffer in flight, then waits until the staged copies out of the /// caches they completed have landed in their pages ([`INTO_PAGES_THREADS`]); again while /// those landings commit more, the later rounds of a copy that circulates its pieces @@ -18907,6 +19312,31 @@ pub(super) mod tests { } } + /// A later round of a circulating download that the platform refuses ends the copy before + /// its last bytes reach the pages: the download is answered refused, never done, counted + /// under its own code, and the next download copies the cache again and is answered done + #[test] + fn a_circulating_download_whose_later_round_the_platform_refuses_is_refused() { + use reims_vgpu_vulkan::core::testkit::script::Step; + let r = circulating(); + // Rounds 0 and 1 go with the download: round 2's copy is the third. + r.p.script().after(COPY, 2, Step::Nil); + let before = counted("surface-copy-refused"); + let (done, refused) = download_answered(&r, BLOCK); + complete_staged(&r); + assert!(refused.load(Ordering::SeqCst), "refused"); + assert!(!done.load(Ordering::SeqCst), "never done"); + assert_eq!(counted("surface-copy-refused"), before + 1); + let mark = r.p.call_log().mark(); + let (done, refused) = download_answered(&r, BLOCK); + assert!( + !copies_at(&r.p.call_log().since(mark)).is_empty(), + "copied again" + ); + complete_staged(&r); + assert!(done.load(Ordering::SeqCst) && !refused.load(Ordering::SeqCst)); + } + /// Writes `bytes` over the Shared buffer of id `id` from its byte `at`, as a GPU copy into it /// would. fn write_buffer(r: &Rig, id: u64, at: u64, bytes: &[u8]) { diff --git a/crates/reims-vgpu/src/graphics/decode/surface_cache/shapes.rs b/crates/reims-vgpu/src/graphics/decode/surface_cache/shapes.rs index 3f27c9e38..262376465 100644 --- a/crates/reims-vgpu/src/graphics/decode/surface_cache/shapes.rs +++ b/crates/reims-vgpu/src/graphics/decode/surface_cache/shapes.rs @@ -211,7 +211,6 @@ use std::collections::VecDeque; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; -use reims_vgpu_vulkan::core::platform::Platform; use reims_vgpu_vulkan::core::platform::blit::{BlitCmd, BlitEncoder as _}; use reims_vgpu_vulkan::core::platform::command::CommandBuffer as _; use reims_vgpu_vulkan::core::platform::descriptor::RenderPassDescriptor as _; @@ -219,7 +218,10 @@ use reims_vgpu_vulkan::core::platform::render::{RenderCmd, RenderEncoder as _}; use reims_vgpu_vulkan::core::platform::resource::Texture as _; use reims_vgpu_vulkan::core::platform::types::{ClearColor, MtlOrigin, MtlSize, PixelFormatInfo}; use reims_vgpu_vulkan::core::platform::values::ColorAttachmentSet; +use reims_vgpu_vulkan::core::platform::{Encoded, Platform}; use reims_vgpu_vulkan::core::raise::{OnFault, RaiseResult}; + +use super::fold; use reims_vgpu_vulkan::gpu::no_texture::no_view; /// How many unreferenced shapes an entry keeps, the most recently used (the planner's ruling of @@ -1062,24 +1064,28 @@ impl ShapeTable { /// Encodes in `cb`, in a blit encoder of its own, a copy of `buffer`, a cache's, into each shape of /// `table` that `pick` picks, each the buffer's bytes at its place ([`ShapeKey::span`]), which /// then owes no fill and holds no write the buffer lacks; counted in `counts`. Nothing where it -/// picks none, or the platform made no encoder. +/// picks none. Refused where the platform made no encoder or refused a command +/// (`super`'s module doc, "Refused copies"): a shape whose copy it refused, or every shape where +/// it refused the encoder or its end, owes its fill still. pub(crate) fn fill( cb: &P::CommandBuffer, buffer: &P::Buffer, table: &mut ShapeTable, pick: impl Fn(&Shape) -> bool, counts: &mut ShapeCounts, -) -> RaiseResult<()> { +) -> RaiseResult { const ON: OnFault = OnFault::Return; if !table.iter().any(&pick) { - return Ok(()); + return Ok(Encoded::RECORDED); } let Some(blit) = cb.blit_encoder(ON)? else { - return Ok(()); + return Ok(Encoded::REFUSED); }; - for shape in table.iter_mut().filter(|s| pick(s)) { + let mut whole = Encoded::RECORDED; + let mut copied = Vec::new(); + for shape in table.iter().filter(|s| pick(s)) { let key = shape.key; - blit.encode( + let encoded = blit.encode( ON, BlitCmd::CopyBufferToTexture { source_buffer: buffer, @@ -1092,12 +1098,20 @@ pub(crate) fn fill( destination_level: 0, destination_origin: MtlOrigin::default(), }, - )? - .go_on(); - filled(shape, counts); + )?; + fold(&mut whole, encoded); + if encoded.recorded() { + copied.push(shape.id()); + } } - blit.encode(ON, BlitCmd::EndEncoding)?.go_on(); - Ok(()) + let ended = blit.encode(ON, BlitCmd::EndEncoding)?; + fold(&mut whole, ended); + if ended.recorded() { + for shape in table.iter_mut().filter(|s| copied.contains(&s.id())) { + filled(shape, counts); + } + } + Ok(whole) } /// Metal's `MTLTextureUsageRenderTarget`, `MTLLoadActionClear` and `MTLStoreActionStore`: what @@ -1131,29 +1145,36 @@ pub(crate) fn clears_fit( /// memory yet, reads (the module doc, "Zeros"), with no copy and no source. Each shape then owes /// no fill and holds no write the buffer lacks, as [`fill`] leaves it, counted in `counts` as a /// fill and as a clear. The caller made sure each takes a clear ([`clears_fit`]): one that does -/// not, or that `pass_of` gives no pass, or whose pass the platform made no encoder for, is left -/// owing its fill. +/// not, or that `pass_of` gives no pass, is left owing its fill; so is one whose pass the platform +/// made no encoder for or refused the end of, the fill then refused (`super`'s module doc, +/// "Refused copies"). pub(crate) fn fill_clears( pass_of: impl Fn(&Shape) -> RaiseResult>, cb: &P::CommandBuffer, table: &mut ShapeTable, pick: impl Fn(&Shape) -> bool, counts: &mut ShapeCounts, -) -> RaiseResult<()> { +) -> RaiseResult { const ON: OnFault = OnFault::Return; + let mut whole = Encoded::RECORDED; for shape in (table.iter_mut()).filter(|s| pick(s) && takes_clear::

(s)) { let Some(pass) = pass_of(shape)? else { continue; }; let Some(encoder) = cb.render_encoder(ON, &pass)? else { + whole = Encoded::REFUSED; continue; }; - encoder.encode(ON, RenderCmd::EndEncoding)?.go_on(); + let ended = encoder.encode(ON, RenderCmd::EndEncoding)?; + fold(&mut whole, ended); + if !ended.recorded() { + continue; + } counts.zero_cleared += 1; counts.zero_cleared_bytes += shape.bytes; filled(shape, counts); } - Ok(()) + Ok(whole) } /// A render pass of `platform`'s whose one colour attachment is `image`, loaded by a clear to @@ -1205,18 +1226,22 @@ pub(crate) type Source<'a, B> = (&'a B, std::ops::Range, u64); /// each its own texels, which the caller made sure the split lies between /// (`SurfaceCache::fills_straight`). The shape then owes no fill and holds no write the buffer /// lacks, as [`fill`] leaves it, counted in `counts` as a fill and as one made straight, with the -/// copies encoded. A row no source holds ends its shape's copies there. +/// copies encoded. A row no source holds ends its shape's copies there. Refused where the +/// platform refused a copy (`super`'s module doc, "Refused copies"): that copy's shape owes its +/// fill still. pub(crate) fn fill_from( blit: &P::BlitEncoder, sources: &[Source<'_, P::Buffer>], table: &mut ShapeTable, pick: &dyn Fn(&Shape) -> bool, counts: &mut ShapeCounts, -) -> RaiseResult<()> { +) -> RaiseResult { const ON: OnFault = OnFault::Return; let source_of = |byte: u64| sources.iter().find(|(_, held, _)| held.contains(&byte)); + let mut whole = Encoded::RECORDED; for shape in table.iter_mut().filter(|s| pick(s)) { let key = shape.key; + let mut took = Encoded::RECORDED; let row = key.width.saturating_mul(key.texel_bytes); let mut y = 0; 'rows: while y < key.height { @@ -1230,7 +1255,7 @@ pub(crate) fn fill_from( let rows = ((held.end - end).checked_div(key.bytes_per_row)) .map_or(1, |more| more.saturating_add(1)) .min(key.height - y); - blit.encode( + let encoded = blit.encode( ON, BlitCmd::CopyBufferToTexture { source_buffer: buffer, @@ -1243,8 +1268,8 @@ pub(crate) fn fill_from( destination_level: 0, destination_origin: MtlOrigin { x: 0, y, z: 0 }, }, - )? - .go_on(); + )?; + fold(&mut took, encoded); counts.straight_copies += 1; y += rows; continue; @@ -1256,7 +1281,7 @@ pub(crate) fn fill_from( break 'rows; }; let part = held.end.min(end) - from; - blit.encode( + let encoded = blit.encode( ON, BlitCmd::CopyBufferToTexture { source_buffer: buffer, @@ -1273,43 +1298,50 @@ pub(crate) fn fill_from( z: 0, }, }, - )? - .go_on(); + )?; + fold(&mut took, encoded); counts.straight_copies += 1; counts.straight_split_rows += u64::from(from == start); from += part; } y += 1; } + fold(&mut whole, took); + if !took.recorded() { + continue; + } counts.straight_fills += 1; counts.straight_bytes += shape.bytes; filled(shape, counts); } - Ok(()) + Ok(whole) } /// Encodes in `cb`, in a blit encoder of its own, a copy of each shape of `table` that `pick` /// picks into `buffer`, a cache's, its whole extent at its place ([`ShapeKey::span`]): the ids of -/// the shapes copied, for [`ShapeTable::written_back`] once `cb` is committed. Shapes agree where -/// they overlap (rule 1), so their order is free. None where it picks none, or the platform made -/// no encoder. +/// the shapes copied, for [`ShapeTable::written_back`] once `cb` is committed, and whether every +/// copy was recorded. Shapes agree where they overlap (rule 1), so their order is free. None +/// where it picks none. Refused where the platform made no encoder or refused a command +/// (`super`'s module doc, "Refused copies"): a shape whose copy it refused, or every shape where +/// it refused the encoder or its end, is not among the ids, and stays dirty. pub(crate) fn write_back( cb: &P::CommandBuffer, buffer: &P::Buffer, table: &ShapeTable, pick: impl Fn(&Shape) -> bool, -) -> RaiseResult> { +) -> RaiseResult<(Vec, Encoded)> { const ON: OnFault = OnFault::Return; if !table.iter().any(&pick) { - return Ok(Vec::new()); + return Ok((Vec::new(), Encoded::RECORDED)); } let Some(blit) = cb.blit_encoder(ON)? else { - return Ok(Vec::new()); + return Ok((Vec::new(), Encoded::REFUSED)); }; let mut ids = Vec::new(); + let mut whole = Encoded::RECORDED; for shape in table.iter().filter(|s| pick(s)) { let key = shape.key; - blit.encode( + let encoded = blit.encode( ON, BlitCmd::CopyTextureToBuffer { source_texture: &shape.image, @@ -1322,12 +1354,18 @@ pub(crate) fn write_back( destination_bytes_per_row: key.bytes_per_row, destination_bytes_per_image: key.bytes_per_row.saturating_mul(key.height), }, - )? - .go_on(); - ids.push(shape.id()); + )?; + fold(&mut whole, encoded); + if encoded.recorded() { + ids.push(shape.id()); + } } - blit.encode(ON, BlitCmd::EndEncoding)?.go_on(); - Ok(ids) + let ended = blit.encode(ON, BlitCmd::EndEncoding)?; + fold(&mut whole, ended); + if !ended.recorded() { + ids.clear(); + } + Ok((ids, whole)) } /// Encodes in `cb` rule 1's copy of the shape `source` of `table`, which the encoder just ended @@ -1339,8 +1377,10 @@ pub(crate) fn write_back( /// and the buffer only takes a write early that the source, dirty, copies into it again. A /// texel of another shape that the source's rows cover only in part (one wider than the /// source's, at the end of its rows) keeps its bytes, counted in `counts` -/// ([`ShapeCounts::straddled`]). Nothing where `into` names no shape, the table holds no -/// `source`, or the platform made no encoder. +/// ([`ShapeCounts::straddled`]). Nothing where `into` names no shape or the table holds no +/// `source`. Refused where the platform made no encoder or refused a command (`super`'s module +/// doc, "Refused copies"); the other shapes take nothing where it refused the wait or the copy +/// into the buffer. pub(crate) fn copy_overlaps( cb: &P::CommandBuffer, buffer: &P::Buffer, @@ -1348,10 +1388,10 @@ pub(crate) fn copy_overlaps( (source, into): (u64, &[u64]), fence: Option<&P::Fence>, counts: &mut ShapeCounts, -) -> RaiseResult<()> { +) -> RaiseResult { const ON: OnFault = OnFault::Return; let Some(from) = table.iter().find(|s| s.id() == source) else { - return Ok(()); + return Ok(Encoded::RECORDED); }; let targets: Vec<&Shape> = (table.iter()) .filter(|s| s.id() != source && into.contains(&s.id())) @@ -1359,33 +1399,43 @@ pub(crate) fn copy_overlaps( let Some((bytes, rows)) = (targets.iter().map(|t| from.key.overlap(&t.key))) .reduce(|(b, r), (bytes, rows)| (b.max(bytes), r.max(rows))) else { - return Ok(()); + return Ok(Encoded::RECORDED); }; let key = from.key; let Some(blit) = cb.blit_encoder(ON)? else { - return Ok(()); + return Ok(Encoded::REFUSED); }; + let mut whole = Encoded::RECORDED; if let Some(fence) = fence { - blit.encode(ON, BlitCmd::WaitForFence { fence })?.go_on(); + fold( + &mut whole, + blit.encode(ON, BlitCmd::WaitForFence { fence })?, + ); + } + if whole.recorded() { + let encoded = blit.encode( + ON, + BlitCmd::CopyTextureToBuffer { + source_texture: &from.image, + source_slice: 0, + source_level: 0, + source_origin: MtlOrigin::default(), + source_size: MtlSize::new(bytes.div_ceil(key.texel_bytes), rows, 1), + destination_buffer: buffer, + destination_offset: key.offset, + destination_bytes_per_row: key.bytes_per_row, + destination_bytes_per_image: key.bytes_per_row.saturating_mul(rows), + }, + )?; + fold(&mut whole, encoded); + } + fold(&mut whole, blit.encode(ON, BlitCmd::EndEncoding)?); + // The others take nothing of a buffer the source's overlap did not reach. + if !whole.recorded() { + return Ok(whole); } - blit.encode( - ON, - BlitCmd::CopyTextureToBuffer { - source_texture: &from.image, - source_slice: 0, - source_level: 0, - source_origin: MtlOrigin::default(), - source_size: MtlSize::new(bytes.div_ceil(key.texel_bytes), rows, 1), - destination_buffer: buffer, - destination_offset: key.offset, - destination_bytes_per_row: key.bytes_per_row, - destination_bytes_per_image: key.bytes_per_row.saturating_mul(rows), - }, - )? - .go_on(); - blit.encode(ON, BlitCmd::EndEncoding)?.go_on(); let Some(blit) = cb.blit_encoder(ON)? else { - return Ok(()); + return Ok(Encoded::REFUSED); }; for target in targets { let (bytes, rows) = key.overlap(&target.key); @@ -1397,7 +1447,7 @@ pub(crate) fn copy_overlaps( if width == 0 || rows == 0 { continue; } - blit.encode( + let encoded = blit.encode( ON, BlitCmd::CopyBufferToTexture { source_buffer: buffer, @@ -1410,8 +1460,8 @@ pub(crate) fn copy_overlaps( destination_level: 0, destination_origin: MtlOrigin::default(), }, - )? - .go_on(); + )?; + fold(&mut whole, encoded); counts.overlap_copies += 1; counts.overlap_bytes += width * rows * texel; if target.key.storage != key.storage { @@ -1421,8 +1471,8 @@ pub(crate) fn copy_overlaps( reims_vgpu_vulkan::answer::count_kind_by(ORDER_COPY_BYTES, width * rows * texel); } } - blit.encode(ON, BlitCmd::EndEncoding)?.go_on(); - Ok(()) + fold(&mut whole, blit.encode(ON, BlitCmd::EndEncoding)?); + Ok(whole) } #[cfg(test)] @@ -1931,7 +1981,11 @@ mod tests { let mark = platform.call_log().mark(); let mut counts = ShapeCounts::default(); let pass_of = |s: &Shape<_>| zeros_pass(&platform, &s.image).map(Some); - fill_clears::(pass_of, &cb, &mut table, |s| s.owed, &mut counts).unwrap(); + assert!( + fill_clears::(pass_of, &cb, &mut table, |s| s.owed, &mut counts) + .unwrap() + .recorded() + ); let calls = platform.call_log().since(mark); let sels: Vec<&str> = calls.iter().map(|c| c.sel).collect(); assert_eq!( @@ -2082,7 +2136,11 @@ mod tests { let mut counts = ShapeCounts::default(); let cb = queue.command_buffer(ON).unwrap().unwrap(); let pass_of = |s: &Shape<_>| zeros_pass(&*platform, &s.image).map(Some); - fill_clears::(pass_of, &cb, &mut table, |s| s.owed, &mut counts).unwrap(); + assert!( + fill_clears::(pass_of, &cb, &mut table, |s| s.owed, &mut counts) + .unwrap() + .recorded() + ); cb.commit(ON).unwrap(); cb.wait_until_completed(ON).unwrap(); assert_eq!(counts.zero_cleared, 4, "each cleared"); @@ -2172,7 +2230,11 @@ mod tests { }; let mut counts = ShapeCounts::default(); let cb = queue.command_buffer(ON).unwrap().unwrap(); - fill::(&cb, &buffer, &mut table, |s| s.owed, &mut counts).unwrap(); + assert!( + fill::(&cb, &buffer, &mut table, |s| s.owed, &mut counts) + .unwrap() + .recorded() + ); cb.commit(ON).unwrap(); cb.wait_until_completed(ON).unwrap(); assert_eq!(counts.fills, 3); @@ -2233,7 +2295,8 @@ mod tests { assert!(table.mark_dirty(id)); } let cb = queue.command_buffer(ON).unwrap().unwrap(); - let written = write_back::(&cb, &back, &table, |s| s.dirty).unwrap(); + let (written, recorded) = write_back::(&cb, &back, &table, |s| s.dirty).unwrap(); + assert!(recorded.recorded()); cb.commit(ON).unwrap(); cb.wait_until_completed(ON).unwrap(); assert_eq!(written, inner); @@ -2258,7 +2321,11 @@ mod tests { ); // Nothing owes a fill now: nothing is encoded, nothing counted. let cb = queue.command_buffer(ON).unwrap().unwrap(); - fill::(&cb, &buffer, &mut table, |s| s.owed, &mut counts).unwrap(); + assert!( + fill::(&cb, &buffer, &mut table, |s| s.owed, &mut counts) + .unwrap() + .recorded() + ); cb.commit(ON).unwrap(); cb.wait_until_completed(ON).unwrap(); assert_eq!(counts.fills, 3); @@ -2397,11 +2464,19 @@ mod tests { let mut counts = ShapeCounts::default(); store(&p); let cb = queue.command_buffer(ON).unwrap().unwrap(); - fill::(&cb, &buffer, &mut table, |s| s.id() == whole, &mut counts).unwrap(); + assert!( + fill::(&cb, &buffer, &mut table, |s| s.id() == whole, &mut counts) + .unwrap() + .recorded() + ); commit(cb); store(&vec![0; LENGTH.to_usize()]); let cb = queue.command_buffer(ON).unwrap().unwrap(); - fill::(&cb, &buffer, &mut table, |s| s.id() != whole, &mut counts).unwrap(); + assert!( + fill::(&cb, &buffer, &mut table, |s| s.id() != whole, &mut counts) + .unwrap() + .recorded() + ); commit(cb); assert_eq!( rows_of(&table, wide), @@ -2409,15 +2484,15 @@ mod tests { ); let cb = queue.command_buffer(ON).unwrap().unwrap(); - copy_overlaps::( + let copied = copy_overlaps::( &cb, &buffer, &table, (whole, &[wide, narrow]), None, &mut counts, - ) - .unwrap(); + ); + assert!(copied.unwrap().recorded()); commit(cb); assert_eq!(rows_of(&table, wide), corner(&p, 32, 8)); assert_eq!(rows_of(&table, narrow), corner(&p, 18, 2)); @@ -2446,10 +2521,18 @@ mod tests { // The narrow one takes `q`, then gives the whole its two rows. store(&q); let cb = queue.command_buffer(ON).unwrap().unwrap(); - fill::(&cb, &buffer, &mut table, |s| s.id() == narrow, &mut counts).unwrap(); + assert!( + fill::(&cb, &buffer, &mut table, |s| s.id() == narrow, &mut counts) + .unwrap() + .recorded() + ); commit(cb); let cb = queue.command_buffer(ON).unwrap().unwrap(); - copy_overlaps::(&cb, &buffer, &table, (narrow, &[whole]), None, &mut counts).unwrap(); + assert!( + copy_overlaps::(&cb, &buffer, &table, (narrow, &[whole]), None, &mut counts) + .unwrap() + .recorded() + ); commit(cb); let mut want = corner(&p, ROW, 16); for (y, row) in want.iter_mut().enumerate().take(2) { diff --git a/crates/reims-vgpu/src/graphics/decode/surface_shapes.rs b/crates/reims-vgpu/src/graphics/decode/surface_shapes.rs index 72c2d1cee..eeb40ca45 100644 --- a/crates/reims-vgpu/src/graphics/decode/surface_shapes.rs +++ b/crates/reims-vgpu/src/graphics/decode/surface_shapes.rs @@ -448,8 +448,9 @@ mod tests { use super::super::surface_cache::tests::{ NO_REACH, blit_with, blits_with, buffer_bytes, cache_id, cached, complete_round, - complete_staged, copies, counted, download, encoder_with, pages_id, queues, ram_bytes, - reading, release, surface_texture, surface_texture_as, surface_textures, use_surfaces, + complete_staged, copies, counted, download, download_answered, encoder_with, pages_id, + queues, ram_bytes, reading, release, surface_texture, surface_texture_as, surface_textures, + use_surfaces, }; use super::super::surface_pages::tests::{BLOCK, Rig, one_plane, rig}; use super::*; @@ -1462,6 +1463,84 @@ mod tests { assert_eq!(r.dec.caches().counts().shapes.written_back, 1); } + /// A dirty shape whose write back into its cache's buffer the platform refuses stays dirty, + /// and the download that asked it copies nothing into the pages, the buffer lacking the + /// write: it is answered refused, counted under its own code, and the next download writes + /// the shape back, copies the buffer into the pages and is answered done + #[test] + fn a_shape_whose_write_back_the_platform_refuses_stays_dirty() { + let mut r = shaped(); + buffer_made(&r); + let cache = cache_id(&r); + let image = texture_image(&mut r, 21, 80, (32, 8)); + write(&mut r, 0x100, 21, (32, 8)); + r.p.world().complete_all(CompleteOn::Caller); + r.p.script().push(TO_BUFFER, Step::Nil); + let before = counted("surface-copy-refused"); + let mark = r.p.call_log().mark(); + let (done, refused) = download_answered(&r, BLOCK); + let calls = r.p.call_log().since(mark); + assert!(copies(&calls).is_empty(), "nothing into the pages"); + r.p.world().complete_all(CompleteOn::Caller); + assert!(refused.load(Ordering::SeqCst), "refused"); + assert!(!done.load(Ordering::SeqCst), "never done"); + assert_eq!(counted("surface-copy-refused"), before + 1); + assert_eq!(r.dec.caches().counts().shapes.written_back, 0); + let mark = r.p.call_log().mark(); + let (done, refused) = download_answered(&r, BLOCK); + let calls = r.p.call_log().since(mark); + assert_eq!(written_back(&calls), [(image, cache, 0)]); + assert_eq!(copies(&calls).len(), 1); + r.p.world().complete_all(CompleteOn::Caller); + assert!(done.load(Ordering::SeqCst) && !refused.load(Ordering::SeqCst)); + } + + /// A shape whose fill the platform refuses owes it still: the next use that names the block + /// fills it, and the refusal is counted under its own code + #[test] + fn a_shape_whose_fill_the_platform_refuses_owes_it_still() { + let mut r = shaped(); + let pages = pages_id(&r); + texture(&mut r, 21, 80, (32, 8)); + r.p.script().push(FILL, Step::Nil); + let before = counted("surface-copy-refused"); + use_surfaces(&mut r, 1, 0x100, &[(BLOCK, 2, false)]); + assert_eq!(counted("surface-copy-refused"), before + 1); + r.p.world().complete_all(CompleteOn::Caller); + let mark = r.p.call_log().mark(); + use_surfaces(&mut r, 1, 0x101, &[(BLOCK, 2, false)]); + let filled = fills(&r.p.call_log().since(mark)); + assert_eq!(filled.len(), 1, "filled again"); + assert_eq!(filled[0].0, pages); + assert_eq!(r.dec.caches().counts().shapes.fills, 1); + } + + /// A write through one shape whose copy into its plane's other shape the platform refuses + /// fails its command buffer, as one whose buffer the platform refused its memory does, and + /// the other shape takes nothing of the buffer's older bytes; the refusal is counted under its + /// own code + #[test] + fn a_writes_copy_into_its_planes_other_shape_the_platform_refuses_fails_its_buffer() { + use reims_vgpu_vulkan::core::testkit::impls::command::FAIL_OUT_OF_MEMORY; + let (mut r, _) = placing_deferred(); + let a = texture_image(&mut r, 21, 80, (32, 8)); + let b = texture_image(&mut r, 22, 80, (16, 4)); + use_surfaces(&mut r, 1, 0x100, &[(BLOCK, 0, false)]); + r.p.world().complete_all(CompleteOn::Caller); + r.p.script().push(TO_BUFFER, Step::Nil); + let before = counted("surface-copy-refused"); + let mark = r.p.call_log().mark(); + write(&mut r, 0x101, 21, (32, 8)); + r.p.world().complete_all(CompleteOn::Caller); + let calls = r.p.call_log().since(mark); + assert!(calls.iter().any(|c| c.sel == TO_BUFFER), "asked"); + let (_, into) = overlaps(&calls, &[a, b]); + assert!(into.is_empty(), "B takes nothing"); + let failed = calls.iter().filter(|c| c.sel == FAIL_OUT_OF_MEMORY).count(); + assert_eq!(failed, 1); + assert_eq!(counted("surface-copy-refused"), before + 1); + } + /// A buffer-to-buffer copy (`copyFromBuffer:sourceOffset:toBuffer:destinationOffset:size:`). const BUFFER_COPY: &str = "copyFromBuffer:sourceOffset:toBuffer:destinationOffset:size:"; diff --git a/docs/conventions.md b/docs/conventions.md index 1134e7879..3aa48b33f 100644 --- a/docs/conventions.md +++ b/docs/conventions.md @@ -242,8 +242,18 @@ repeats the ones code cites. read and drawable format, whose draws took the colour's pass: "The colour as a table"; `display-frame-refused`, a frame of the window the platform refused a pass or a command of, not presented, the window - keeping its last complete frame: "A refused encode"), and the guest's slow - answers' + keeping its last complete frame: "A refused encode"), the surfaces' device + caches' (`surface-copy-refused`, a copy of the host's own between a cache, + its shapes, its wide home and its pages that the platform refused a + command or the encoder of, counted at each refusal and made again only at + the guest's next use, download or release: what it was to move is left as + not copied, so a `SURFACE_DOWNLOAD` whose copy into the pages was refused + is answered failed (`RGFX_STATUS_REFUSED`), where it was answered done + over the pages' older bytes before, and a fill, or a copy into a shape + or a wide home, refused for a command buffer fails it with Metal's + `MTLCommandBufferErrorOutOfMemory`, as a cache's refused memory does: + `graphics/decode/surface_cache.rs`, "Refused copies"), and the guest's + slow answers' (`slow-answer-over-make`, a ring-0 answer that went on its ring a frame, 16.7 ms, or more after the device read its command, during which a make of rt's pool ran, and `slow-answer-over-make-max-ns` the longest;