diff --git a/crates/reims-vgpu/src/graphics.rs b/crates/reims-vgpu/src/graphics.rs index cfafe6dc0..aae211eb5 100644 --- a/crates/reims-vgpu/src/graphics.rs +++ b/crates/reims-vgpu/src/graphics.rs @@ -800,6 +800,11 @@ impl GraphicsDevice

{ }, )); } + // A platform whose imports of the host's memory cost each submission stages the + // caches' copies through the host's CPU (`ApiPlatform::STAGED_SURFACE_COPIES`). + if P::STAGED_SURFACE_COPIES { + decoder.set_staged_surface_copies(); + } if unified_memory { let cache_budget = cache_budget(own_memory); decoder.set_cache_budget(cache_budget); diff --git a/crates/reims-vgpu/src/graphics/decode/mod.rs b/crates/reims-vgpu/src/graphics/decode/mod.rs index 6192c985b..01df163ac 100644 --- a/crates/reims-vgpu/src/graphics/decode/mod.rs +++ b/crates/reims-vgpu/src/graphics/decode/mod.rs @@ -1431,9 +1431,20 @@ impl GraphicsDecoder

{ } /// Whether a cached block on `device` is named by its runs, with no view: the device copies - /// the guest's RAM by them (`surface_pages`, "By runs"). + /// the guest's RAM by them (`surface_pages`, "By runs"), or the caches' copies are staged + /// ([`Self::set_staged_surface_copies`]). fn copies_by_runs(&self, device: &P::Device) -> bool { - device.copies_guest_ram() + device.copies_guest_ram() || self.surface_caches.staged() + } + + /// Stages the IOSurface device caches' copies from now on (`surface_cache`, "Staged + /// copies"): no surface's view takes an import of its pages, and every cache copies them + /// through the host's CPU, timed by the platform's clock. Set once, at the device's make, + /// before any surface is named. + pub(crate) fn set_staged_surface_copies(&self) { + self.shared.surface_views.lock().set_staged(); + let platform = Arc::clone(&self.platform); + (self.surface_caches).set_staged(Arc::new(move || platform.clock().now_mono())); } /// Whether `SURFACE_PAGES` makes views ([`RGFX_FEATURE_SURFACE_PAGES`]). @@ -2367,8 +2378,10 @@ impl GraphicsDecoder

{ Ok(Ok((view, import))) => { self.shared.surface_views.lock().viewed(block, view); // The view's buffers hold it; the import's buffer goes on the worker, where it - // may be the last hold of the import. - self.shared.surface_worker.drop_later(block, block, import); + // may be the last hold of the import (none where the caches' copies are staged). + if let Some(import) = import { + self.shared.surface_worker.drop_later(block, block, import); + } } Ok(Err(why)) => log::warn!( target: "reims_vgpu::graphics", kind:? = why; @@ -3135,8 +3148,10 @@ impl GraphicsDecoder

{ } /// What a present of IOSurface `iosurface_id` shows ([`SurfacePresent`]). The caller holds its - /// own reference to the texture: a destroy of it after this leaves it drawable. + /// own reference to the texture: a destroy of it after this leaves it drawable. Counted where + /// the device caches' copies are staged ([`surface_cache::Caches::count_present`]). pub(crate) fn surface_present(&self, iosurface_id: u32) -> Option> { + self.surface_caches.count_present(); let (obj_id, writers_at) = { let names = self.shared.surfaces.lock(); let obj_id = *names.by_surface.get(&iosurface_id)?.last()?; diff --git a/crates/reims-vgpu/src/graphics/decode/surface_cache.rs b/crates/reims-vgpu/src/graphics/decode/surface_cache.rs index 6e070cc76..cd29d0a2d 100644 --- a/crates/reims-vgpu/src/graphics/decode/surface_cache.rs +++ b/crates/reims-vgpu/src/graphics/decode/surface_cache.rs @@ -280,6 +280,19 @@ //! mapping of the pages, so the two never share a command buffer: each copy has a transfer //! command buffer of its own, and a refused copy by runs encodes nothing in it. //! +//! - **Staged copies.** On a platform whose imports of the host's memory may cost each of its +//! submissions while they live (`ApiPlatform::STAGED_SURFACE_COPIES`, set at the device's make, +//! [`Caches::set_staged`]), no cache's copies go through an import of its pages: every cache +//! copies as a copied one does (`CachePages::Copied`, "Deferred blocks", above), its block +//! named by its runs with no view ([`super::surface_pages`], "By runs"), and a deferred block's +//! pages taken so at their naming. A fill is the host's CPU reading the pages' bytes into a +//! Shared buffer of its own, which the GPU then copies into the cache; a download is the GPU's +//! copy of the cache into such a buffer, which the CPU empties into the pages once it is done. +//! Each is counted on the counts line by its kind's name (`cache-view`): how many and their +//! KiB, and the nanoseconds the host's CPU spent on them (`rt-fills-cache-view`, +//! `rt-fills-cache-view-kib`, `rt-fills-cache-view-cpu-ns`, and the same of `rt-downloads-`), +//! beside the surfaces the guest presented (`rt-presents`), which a frame's share falls out of. +//! //! [`GpuDevice::own_memory_budget`]: reims_vgpu_vulkan::core::platform::device::GpuDevice::own_memory_budget //! [`GpuDevice::copies_guest_ram`]: reims_vgpu_vulkan::core::platform::device::GpuDevice::copies_guest_ram //! [`GpuDevice::recoveries`]: reims_vgpu_vulkan::core::platform::device::GpuDevice::recoveries @@ -310,6 +323,7 @@ //! //! [`RGFX_SURFACE_PAGES_CACHED`]: reims_vgpu_graphics::wire::RGFX_SURFACE_PAGES_CACHED +use std::any::Any; use std::collections::hash_map::Entry; use std::collections::{BTreeSet, HashMap, HashSet, VecDeque}; use std::ops::Range; @@ -339,7 +353,7 @@ use reims_vgpu_vulkan::core::raise::{OnFault, Raise, RaiseResult, refusals}; use reims_vgpu_vulkan::core::sync::{Condvar, Mutex, MutexGuard}; use super::refusing; -use super::surface_pages::{SurfaceView, Unmade, buffer_over}; +use super::surface_pages::{PagesRefusal, SurfaceView, Unmade, buffer_over}; use crate::device_writes::{self, Watcher}; pub(crate) mod shapes; @@ -1088,10 +1102,24 @@ pub(crate) enum Named { Runs(Vec>, Arc>), } +impl Named

{ + /// The pages named, `length` bytes of them, copied (the module doc, "Staged copies"); `None` + /// where they hold fewer. + fn copied(self, length: u64) -> Option { + match self { + Named::View(view) => CopiedPages::of_view(&view, length), + Named::Runs(runs, unmade) => CopiedPages::of_runs(&runs, unmade, length), + } + } +} + /// The pages of a copied cache ([`CachePages::Copied`]): each run of them the guest's RAM /// mapping holds contiguously, as its host address and its bytes, in the surface's order. struct CopiedPages { runs: Vec<(HostPtr, u64)>, + /// What holds the mapping the runs lie in, where they lie in a view's, or in the guest's RAM + /// through what makes a view of them ([`Self::of_view`], [`Self::of_runs`]). + _hold: Option>, } impl CopiedPages { @@ -1110,7 +1138,34 @@ impl CopiedPages { _ => merged.push((at, bytes)), } } - (total >= length && length != 0).then_some(CopiedPages { runs: merged }) + (total >= length && length != 0).then_some(CopiedPages { + runs: merged, + _hold: None, + }) + } + + /// The pages `view` maps, `length` bytes of them, held by the view while the cache copies + /// them (the module doc, "Staged copies"); `None` where it holds fewer. + fn of_view(view: &Arc>, length: u64) -> Option { + let mut pages = CopiedPages::new(&[(view.base(), view.length())], length)?; + pages._hold = Some(Arc::clone(view) as Arc); + Some(pages) + } + + /// The pages of `runs`, the host addresses in the guest's RAM of a block named by its runs, + /// `length` bytes of them, held by `unmade`, which holds the guest RAM's mapping, while the + /// cache copies them (the module doc, "Staged copies"); `None` where they hold fewer. + fn of_runs( + runs: &[Range], + unmade: Arc>, + length: u64, + ) -> Option { + let runs: Vec<(HostPtr, u64)> = (runs.iter()) + .map(|r| (HostPtr::from_addr(r.start.to_usize()), r.end.saturating_sub(r.start))) + .collect(); + let mut pages = CopiedPages::new(&runs, length)?; + pages._hold = Some(unmade as Arc); + Some(pages) } /// Copies the surface's bytes `spans` of the pages into `buffer`, each to its own byte of @@ -1157,6 +1212,21 @@ impl CopiedPages { } } +/// The buffer over the view `unmade` makes on `device` now, which holds the view and the +/// runtime's import of its pages: the refusal where either is not made, which a view made where +/// the caches' copies are staged is, as it takes no import ([`Unmade::make`]). +fn imported( + unmade: &Unmade

, + device: &P::Device, +) -> RaiseResult> { + Ok(unmade.make(device)?.and_then(|(_view, import)| import.ok_or(PagesRefusal::NoBuffer))) +} + +/// `copied` as a cache's pages: staged (the module doc, "Staged copies"). +fn staged_pages(copied: CopiedPages) -> CachePages

{ + CachePages::Copied(Arc::new(copied)) +} + /// A deferred block's carried pages ([`SurfaceCache::carried`]): each run of its surface's /// resident pages as the surface's byte it starts at, its host address in the guest's RAM, which /// the kext holds wired until the block's pages are named or its release is answered, and its @@ -1618,6 +1688,9 @@ pub(crate) struct SurfaceCaches { shaped: bool, /// The shapes' clock, a tick a use: what orders their last uses ([`ShapeTable::sweep`]). shape_clock: u64, + /// Where every cache's copies are staged (the module doc, "Staged copies"; + /// [`Caches::set_staged`]), the platform's clock, which times the host's CPU's part of each. + staged: Option, } /// The command buffers begun and not finished that use one block's cache, by the number each was @@ -1815,6 +1888,7 @@ impl SurfaceCaches

{ release_copy: None, shaped: false, shape_clock: 0, + staged: None, } } @@ -2337,7 +2411,8 @@ impl SurfaceCaches

{ /// keeps its bytes, its generation and whether a buffer wrote it: `Some(true)`; `Some(false)` /// where they are fewer than the cache's bytes or the platform made no buffer over the view, /// the block keeping none; `None` where the block has no deferred cache whose pages are not - /// named. + /// named. Where the caches' copies are staged, the pages are taken copied, with no buffer + /// over the view (the module doc, "Staged copies"). pub(crate) fn attach( &mut self, device: &P::Device, @@ -2349,6 +2424,11 @@ impl SurfaceCaches

{ return Ok(None); }; let ends = match named { + // Staged, the pages are copied whichever way they are named. + _ if self.staged.is_some() => match named.copied(length) { + Some(copied) => CachePages::Copied(Arc::new(copied)), + None => return Ok(Some(false)), + }, Named::View(view) if view.length() >= length => { let over = || buffer_over(device, &view, 0, length, 0, None); match super::unkept::Kind::CacheView.making(over)? { @@ -3097,8 +3177,8 @@ impl SurfaceCaches

{ return Ok(Some((home.buffer.clone_ref(), home.pages))); } if let Some(CachePages::Runs { unmade, .. }) = &cache.pages { - match unmade.make(device)? { - Ok((_view, import)) => { + match imported(unmade, device)? { + Ok(import) => { log::info!( target: "reims_vgpu::graphics", "the IOSurface block at {block:#x}: a texture passes its plane's texels in \ @@ -3883,7 +3963,8 @@ impl SurfaceCaches

{ }; wait_before::

(&cb, signal.as_ref())?; wait_for_users::

(&cb, &self.ends, cache)?; - let staged = copy::

(device, &cb, cache, Way::In, block, &mut self.counts)?; + let timed = self.staged.as_ref(); + let staged = copy::

(device, &cb, cache, (Way::In, block), &mut self.counts, timed)?; if let Some(staged) = staged { cb.add_completed_handler(ON, Box::new(move |_: CompletedInfo| drop(staged)))?; } @@ -4313,7 +4394,8 @@ impl SurfaceCaches

{ let users = wait_for_users::

(&cb, &self.ends, cache)?; // 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 staged = copy::

(device, &cb, cache, Way::Out, block, &mut self.counts)?; + let timed = self.staged.as_ref(); + let staged = copy::

(device, &cb, cache, (Way::Out, block), &mut self.counts, timed)?; signal_after::

(&cb, signal.as_ref())?; // The buffers live until the copy is done, past the cache's own end at a release. let view = match &cache.pages { @@ -4615,6 +4697,8 @@ pub(crate) struct Caches { homes: AtomicBool, /// What makes a shape's image, in the per-shape form ([`Self::set_shapes`]). shape_maker: OnceLock>, + /// Every cache's copies are staged ([`Self::set_staged`]). + staged: AtomicBool, } /// What makes a shape's image ([`shapes`]): a texture of the descriptor on the device, of the @@ -4948,6 +5032,7 @@ impl Caches

{ on_fill_done, homes: AtomicBool::new(false), shape_maker: OnceLock::new(), + staged: AtomicBool::new(false), } } @@ -4964,6 +5049,26 @@ impl Caches

{ self.shape_maker.get().is_some() } + /// Stages every cache's copies from now on (the module doc, "Staged copies"), the host's + /// CPU's part of each timed by `now`: set once, at the device's make, before any cache. + pub(crate) fn set_staged(&self, now: Now) { + self.state.lock().staged = Some(now); + self.staged.store(true, Ordering::Release); + } + + /// Whether every cache's copies are staged ([`Self::set_staged`]). + pub(crate) fn staged(&self) -> bool { + self.staged.load(Ordering::Acquire) + } + + /// The guest presented a surface: counted where the caches' copies are staged + /// ([`PRESENTS`]), which the staged copies' share of a frame falls out of. + pub(crate) fn count_present(&self) { + if self.staged() { + reims_vgpu_vulkan::answer::count_kind(PRESENTS); + } + } + /// The shape `key` of the block at `block`'s cache, its image made of `desc` where the cache /// holds none yet, with the lock let go of, and added ([`SurfaceCaches::add_shape`]): a /// reference to it and its image. `None` where the caches take the default form, the block @@ -5815,7 +5920,8 @@ impl Caches

{ /// It follows every command buffer begun and not finished that may write the cache the block /// had, and the copies of it asked. The cache's buffer, and the buffer over `view` its copies /// take, are made with the caches' lock let go of ([`CacheMaker`]), and taken under it - /// ([`SurfaceCaches::make_with`]). + /// ([`SurfaceCaches::make_with`]). Where the caches' copies are staged, they take no buffer + /// over `view`: the cache copies its pages (the module doc, "Staged copies"). pub(crate) fn make( &self, device: &P::Device, @@ -5826,6 +5932,10 @@ impl Caches

{ layout: CacheLayout, ) -> RaiseResult { let length = view.length(); + if self.staged() { + let pages = || Ok(CopiedPages::of_view(view, length).map(staged_pages)); + return self.make_with(device, block, length, host_pages, generation, layout, pages); + } let pages = || { let over = || buffer_over(device, view, 0, length, 0, None); (super::unkept::Kind::CacheView.making(over)).map(|b| b.map(CachePages::View)) @@ -5926,7 +6036,9 @@ impl Caches

{ /// A cache for the block at `block`, named by its pages' runs with no view /// ([`super::surface_pages`]): `runs` in the surface's order, and `unmade`, which makes the - /// view where the platform refuses a copy by them; else as [`Self::make`]. + /// view where the platform refuses a copy by them, or which holds the guest RAM's mapping of + /// them where the caches' copies are staged, the cache copying the pages of `runs` (the module + /// doc, "Staged copies"); else as [`Self::make`]. #[allow(clippy::too_many_arguments)] // make's, and the runs pub(crate) fn make_by_runs( &self, @@ -5939,6 +6051,10 @@ impl Caches

{ layout: CacheLayout, ) -> RaiseResult { let length = unmade.length(); + if self.staged() { + let pages = || Ok(CopiedPages::of_runs(&runs, unmade, length).map(staged_pages)); + return self.make_with(device, block, length, host_pages, generation, layout, pages); + } let pages = || Ok(Some(CachePages::Runs { runs, unmade })); self.make_with(device, block, length, host_pages, generation, layout, pages) } @@ -6524,20 +6640,71 @@ fn encode_home( struct Staging { buffer: P::Buffer, into: Option<(Arc, Vec>)>, + /// Where the caches' copies are staged, the clock that times the copy into the pages + /// ([`DOWNLOADS`]). + timed: Option, } impl Staging

{ /// The copy into the buffer is done: a copy out of the cache moves its bytes into the pages. fn done(self) { if let Some((pages, spans)) = &self.into { + let at = self.timed.as_ref().map(|now| now()); // SAFETY: the buffer's Shared bytes, the cache's length, which hold every span and // which the copy into it, now done, was the last GPU work to use; the pages are // named, so wired. unsafe { pages.copy(self.buffer.contents().as_ptr::(), spans, true) }; + if let (Some(now), Some(at)) = (&self.timed, at) { + DOWNLOADS.took(now, at); + } } } } +/// The counts of one way of the staged copies (the module doc, "Staged copies"), by the kind of +/// their pages' buffers had they been imported (`cache-view`): how many, their KiB, and the +/// nanoseconds the host's CPU spent on them. +struct StagedCodes { + copies: &'static str, + kib: &'static str, + cpu_ns: &'static str, +} + +/// The staged fills: the host's CPU reads the pages into a Shared buffer the GPU copies into the +/// cache. +const FILLS: StagedCodes = StagedCodes { + copies: "rt-fills-cache-view", + kib: "rt-fills-cache-view-kib", + cpu_ns: "rt-fills-cache-view-cpu-ns", +}; + +/// The staged downloads: the GPU copies the cache into a Shared buffer the host's CPU then +/// writes into the pages. +const DOWNLOADS: StagedCodes = StagedCodes { + copies: "rt-downloads-cache-view", + kib: "rt-downloads-cache-view-kib", + cpu_ns: "rt-downloads-cache-view-cpu-ns", +}; + +/// The surfaces the guest presented while the caches' copies were staged, which the staged +/// copies' per-frame share falls out of ([`Caches::count_present`]). +const PRESENTS: &str = "rt-presents"; + +impl StagedCodes { + /// One copy of `bytes` bytes. + fn copied(&self, bytes: u64) { + reims_vgpu_vulkan::answer::count_kind(self.copies); + reims_vgpu_vulkan::answer::count_kind_by(self.kib, bytes.div_ceil(1024)); + } + + /// The host's CPU's part of one, from `at` to `now`. + fn took(&self, now: &Now, at: MonoTime) { + let took = now().saturating_duration_since(at).as_nanos(); + let took = u64::try_from(took).unwrap_or(u64::MAX); + reims_vgpu_vulkan::answer::count_kind_by(self.cpu_ns, took); + } +} + /// Encodes on `cb` a copy of `cache`'s bytes `way`, between the cache and its pages, of the block /// at `block`: by the pages' runs where the cache has them and the platform copies by them, else /// through the view, which a refused copy by runs makes now (the module doc; counted in @@ -6551,9 +6718,9 @@ fn copy( device: &P::Device, cb: &P::CommandBuffer, cache: &mut SurfaceCache

, - way: Way, - block: u64, + (way, block): (Way, u64), counts: &mut CacheCounts, + timed: Option<&Now>, ) -> RaiseResult>> { let Some(blit) = cb.blit_encoder(ON)? else { return Ok(None); @@ -6570,8 +6737,8 @@ fn copy( if !by_runs { if let Some(CachePages::Runs { unmade, .. }) = &cache.pages { counts.runs_refused += 1; - match unmade.make(device)? { - Ok((_view, import)) => { + match imported(unmade, device)? { + Ok(import) => { log::warn!( target: "reims_vgpu::graphics", "the IOSurface block at {block:#x}: the platform refused a copy by its \ @@ -6599,6 +6766,7 @@ fn copy( } } } + let at = timed.map(|now| now()); if let Some(CachePages::Copied(copied)) = &cache.pages && let Some(buffer) = device.new_buffer_of_length(ON, cache.length, STORAGE_SHARED)? { @@ -6623,7 +6791,25 @@ fn copy( let spans = cache.texels.clone().unwrap_or_else(|| vec![whole]); (Arc::clone(copied), spans) }); - staged = Some(Staging { buffer, into }); + if let (Some(now), Some(at)) = (timed, at) { + let codes = match &into { + Some((_, spans)) => { + DOWNLOADS.copied(spans.iter().map(|s| s.end - s.start).sum()); + &DOWNLOADS + } + None => { + FILLS.copied(cache.length); + &FILLS + } + }; + codes.took(now, at); + } + let timed = timed.cloned(); + staged = Some(Staging { + buffer, + into, + timed, + }); } if cache.pages.is_none() && way == Way::In @@ -6647,7 +6833,15 @@ fn copy( between::

(&blit, (&cache.device, &buffer), &parts, Way::In)?; from += bytes; } - staged = Some(Staging { buffer, into: None }); + if let (Some(now), Some(at)) = (timed, at) { + FILLS.copied(from); + FILLS.took(now, at); + } + staged = Some(Staging { + buffer, + into: None, + timed: None, + }); } } blit.encode(ON, BlitCmd::EndEncoding)?; @@ -12937,6 +13131,125 @@ pub(super) mod tests { } } + /// How many of the kind of code `code` the process counted ([`reims_vgpu_vulkan::answer`]). + fn counted(code: &str) -> u64 { + (reims_vgpu_vulkan::answer::counted_kinds().into_iter()) + .find(|(c, _)| *c == code) + .map_or(0, |(_, n)| n) + } + + /// Where the caches' copies are staged, a cached block is named by its runs with no view, + /// and its cache copies its pages through Shared buffers of each copy's own: its naming, its + /// first fill and a download make no buffer over the pages, so no import of them, and no + /// mapping of them. The fill's staging buffer holds the CPU's bytes before the GPU copies it + /// into the cache; the download's lands in the pages once the GPU's copy is done, before the + /// answer; each is counted, with its KiB (the module doc, "Staged copies") + #[test] + fn a_staged_caches_copies_make_no_import() { + let mut r = rig(8); + r.dec.set_staged_surface_copies(); + queues(&mut r); + let page = r.page; + let length = 2 * page; + let codes = [FILLS.copies, FILLS.kib, DOWNLOADS.copies, DOWNLOADS.kib]; + let before = codes.map(counted); + let written = ram_bytes(&r, 1, length, Some(0x11)); + let mark = r.p.call_log().mark(); + assert_eq!( + r.pages_cached(BLOCK, &[(1, 2)], length, true), + RGFX_STATUS_OK + ); + let cache = cache_id(&r); + assert!( + r.dec.views_of_surfaces().by_runs(BLOCK).is_some(), + "named by its runs, with no view" + ); + + // The first use fills the cache through a staging buffer the host's CPU filled. + let filling = r.p.call_log().mark(); + use_surfaces(&mut r, 1, 0x100, &[(BLOCK, 0, true)]); + let filled = copies(&r.p.call_log().since(filling)); + assert_eq!(filled.len(), 1); + assert_eq!(filled[0].1, cache, "into the cache"); + assert_eq!( + buffer_bytes(&r, filled[0].0, None), + written, + "the CPU's bytes, in the fill's staging buffer before the GPU copies it" + ); + r.p.world().complete_all(CompleteOn::Caller); + + // The download: the GPU copies the cache into a staging buffer, the pages take it once + // that copy is done, then the answer. + let out_mark = r.p.call_log().mark(); + let done = download(&r, BLOCK); + let out = copies(&r.p.call_log().since(out_mark)); + assert_eq!(out.len(), 1); + assert_eq!(out[0].0, cache, "out of the cache"); + assert_ne!(out[0].1, filled[0].0, "into a staging buffer of its own"); + buffer_bytes(&r, out[0].1, Some(0xc3)); + assert!(!done.load(Ordering::SeqCst), "not before the copy is done"); + r.p.world().complete_all(CompleteOn::Caller); + assert!(done.load(Ordering::SeqCst)); + assert!( + ram_bytes(&r, 1, length, None).iter().all(|&b| b == 0xc3), + "the pages hold what the GPU copied out of the cache" + ); + + let sels = r.p.call_log().sels_since(mark); + assert!( + !sels.contains(&"newBufferWithDescriptor:"), + "no buffer over the pages, so no import of them: {sels:?}" + ); + assert!(!sels.contains(&"mach_vm_remap"), "no mapping of the pages"); + let after = codes.map(counted); + let kib = length.div_ceil(1024); + assert_eq!( + [0, 1, 2, 3].map(|i| after[i] - before[i]), + [1, kib, 1, kib], + "one fill and one download, with their KiB" + ); + } + + /// Where the caches' copies are staged, a deferred block's pages are taken copied at the CPU + /// lock that names them, as their own way, not a refusal's (`attached_copied` stays 0): with + /// no view, no buffer over them and no mapping; a download moves the cache into them through + /// a staging buffer + #[test] + fn a_staged_deferred_blocks_pages_are_taken_copied_with_no_import() { + let mut r = deferring(8); + r.dec.set_staged_surface_copies(); + let page = r.page; + let length = 2 * page; + assert_eq!(defer(&mut r, BLOCK, length), RGFX_STATUS_OK); + let cache = cache_id(&r); + use_surfaces(&mut r, 1, 0x100, &[(BLOCK, 0, true)]); + r.p.world().complete_all(CompleteOn::Caller); + + let mark = r.p.call_log().mark(); + assert_eq!(attach(&mut r, BLOCK, 0, &[(1, 2)], length), RGFX_STATUS_OK); + assert_eq!(r.dec.caches().unattached(BLOCK), None); + let counts = r.dec.caches().counts(); + assert_eq!((counts.attached, counts.attached_copied), (1, 0)); + assert_eq!(cache_id(&r), cache, "the same cache"); + let done = download(&r, BLOCK); + let out = copies(&r.p.call_log().since(mark)); + assert_eq!(out.len(), 1); + assert_eq!(out[0].0, cache, "out of the cache"); + buffer_bytes(&r, out[0].1, Some(0xc3)); + r.p.world().complete_all(CompleteOn::Caller); + assert!(done.load(Ordering::SeqCst)); + assert!( + ram_bytes(&r, 1, length, None).iter().all(|&b| b == 0xc3), + "the pages hold what the GPU copied out of the cache" + ); + let sels = r.p.call_log().sels_since(mark); + assert!( + !sels.contains(&"newBufferWithDescriptor:"), + "no buffer over the pages, so no import of them: {sels:?}" + ); + assert!(!sels.contains(&"mach_vm_remap"), "no mapping of the pages"); + } + /// The platform's command queue. type Queue = ::CommandQueue; diff --git a/crates/reims-vgpu/src/graphics/decode/surface_pages.rs b/crates/reims-vgpu/src/graphics/decode/surface_pages.rs index cc0a8f413..af6cce459 100644 --- a/crates/reims-vgpu/src/graphics/decode/surface_pages.rs +++ b/crates/reims-vgpu/src/graphics/decode/surface_pages.rs @@ -240,6 +240,10 @@ //! no import. What would make its view is kept with it ([`Unmade`]): the cache makes the view //! where the platform refuses a copy, or where it makes no cache, and the block then lies over //! the view as any other. A block whose runs leave the RAM's mapping takes its view as before. +//! Where the device caches' copies are staged ([`SurfaceViews::set_staged`]), every cached block +//! is named by its runs too, and its cache copies their pages through the host's CPU +//! (`super::surface_cache`, "Staged copies"); a surface's view, where one is made, takes no +//! import of its pages. //! //! [`GpuDevice::copies_guest_ram`]: reims_vgpu_vulkan::core::platform::device::GpuDevice::copies_guest_ram //! @@ -977,6 +981,9 @@ pub(crate) struct Unmade { teardown: Option>, key: Vec<(u64, u64)>, length: u64, + /// Whether the view takes a buffer over the whole of it, which holds the runtime's import of + /// its pages: none where the device caches' copies are staged ([`SurfaceViews::set_staged`]). + import: bool, } impl Unmade

{ @@ -986,7 +993,8 @@ impl Unmade

{ } /// The view, mapped now, and a Shared buffer over the whole of it on `device`, which holds - /// the view and the runtime's import of its pages; the refusal where either is not made. + /// the view and the runtime's import of its pages, where the view takes one; the refusal + /// where either is not made. pub(crate) fn make(&self, device: &P::Device) -> RaiseResult, PagesRefusal>> { let view = match map_view( &self.memory, @@ -998,9 +1006,12 @@ impl Unmade

{ Ok(view) => view, Err(why) => return Ok(Err(why)), }; + if !self.import { + return Ok(Ok((view, None))); + } Ok( match buffer_over(device, &view, 0, view.length(), 0, None)? { - Some(import) => Ok((view, import)), + Some(import) => Ok((view, Some(import))), None => Err(PagesRefusal::NoBuffer), }, ) @@ -1066,18 +1077,23 @@ pub(crate) struct SurfaceViews { /// such block's view is made at its `SURFACE_PAGES`, and its address is its import's /// ([`Self::pages_address`]). known_imports: Option>, + /// The device caches' copies are staged ([`Self::set_staged`]): a surface's view takes no + /// import of its pages. + staged: bool, } /// What a `SURFACE_PAGES` found under the views' lock ([`SurfaceViews::surface_pages`]). enum Found { /// The block's view, the cache's, or the refusal. Done(Result>, PagesRefusal>), - /// A view to make of the runs `key` outside the lock, through `memory`. + /// A view to make of the runs `key` outside the lock, through `memory`, with a buffer over + /// it that holds the runtime's import of its pages where `import`. Make { memory: Arc>, lease: Lease, teardown: Option>, key: Vec<(u64, u64)>, + import: bool, }, } @@ -1116,6 +1132,7 @@ impl SurfaceViews

{ coverage: Arc::default(), view_addresses: Arc::new(Mutex::new(HostAddresses::imports())), known_imports: None, + staged: false, } } @@ -1137,6 +1154,16 @@ impl SurfaceViews

{ read_only && self.known_imports.is_none() } + /// Has the views of the surfaces' blocks take no import of their pages from now on, where + /// the device caches' copies are staged, through the host's CPU and a Shared buffer of each + /// copy's own ([`super::surface_cache`], "Staged copies"): a surface's buffers then lie over + /// its cache alone, and its cache copies by the pages' host bytes, so an import of them would + /// serve nothing and might cost each of the platform's submissions while it lived. A pages + /// block's view is made as before. Set once, at the device's make. + pub(crate) fn set_staged(&mut self) { + self.staged = true; + } + /// The GPU address of the view of the pages block at `block`, for its `SURFACE_PAGES` /// answer (`IMPORT_ADDRESSES`, "Addresses the host gives"): the one given it before, else /// where the platform knows the view's import as a block ([`ViewImports`]), the import's, @@ -1283,14 +1310,14 @@ impl SurfaceViews

{ lease, teardown, key, + import, } => { Self::make_room_for(views, platform, key.len()); if ask && !Self::room_for(platform, key.len()) { return Ok(Some(Err(PagesRefusal::NoRoom))); } - match make_view( - platform, device, pages, runs, &memory, lease, teardown, &key, - )? { + let on = (&*memory, lease, teardown); + match make_view(platform, device, pages, runs, on, &key, import)? { Ok((view, import)) => { let idle_mappings = platform.vm().idle_view_mappings(); let evicted = views.lock().keep(key, &view, import, idle_mappings); @@ -1517,6 +1544,7 @@ impl SurfaceViews

{ teardown: self.teardown.clone(), key, length: pages.length, + import: !self.staged, }; let block = ByRuns { runs: host, @@ -1566,8 +1594,10 @@ impl SurfaceViews

{ Ok(key) => key, Err(why) => return Found::Done(Err(why)), }; - // A read-only pages block's view, which has no import, serves no surface's block. - let hit = (self.cache.iter()).position(|c| c.runs == key && c.import.is_some()); + // A read-only pages block's view, which has no import, serves no surface's block, but + // where the caches' copies are staged, whose surfaces' views take none. + let staged = self.staged; + let hit = (self.cache.iter()).position(|c| c.runs == key && (c.import.is_some() || staged)); if let Some(cached) = hit.and_then(|at| self.cache.remove(at)) { let view = Arc::clone(&cached.view); self.cache.push_back(cached); @@ -1582,20 +1612,21 @@ impl SurfaceViews

{ lease: Arc::clone(lease), teardown: self.teardown.clone(), key, + import: !staged, } } - /// Caches `view`, just made of the runs `key` with `import` over it, at the back - /// ([`Self::cache_view`]), counted as made. + /// Caches `view`, just made of the runs `key` with `import` over it where it took one, at + /// the back ([`Self::cache_view`]), counted as made. fn keep( &mut self, key: Vec<(u64, u64)>, view: &Arc>, - import: P::Buffer, + import: Option, idle_mappings: Option, ) -> Vec> { self.counts.made += 1; - self.cache_view(key, Arc::clone(view), Some(import), false, idle_mappings) + self.cache_view(key, Arc::clone(view), import, false, idle_mappings) } /// Caches `view` of the runs `key`, with `import` over it where it has one, a block the @@ -2514,8 +2545,9 @@ impl SurfaceViews

{ } } -/// A view just made, and the buffer over the whole of it that holds its import. -pub(crate) type Made

= (Arc>,

::Buffer); +/// A view just made, and the buffer over the whole of it that holds its import, where it took +/// one. +pub(crate) type Made

= (Arc>, Option<

::Buffer>); /// The host addresses of the guest pages of `key` in `memory`'s mapping of the guest's RAM, in /// their order, as runs, each page that follows the last one's end in the same run; `None` where @@ -2562,19 +2594,18 @@ fn map_view( Ok(Arc::new(SurfaceView::new(mapping, lease, teardown))) } -/// The view of the runs `key` of the block `pages` names, through `memory`, which holds `lease`, -/// let go of on `teardown`, with a buffer over the whole of it on `device`, which holds the -/// runtime's import of its pages; logs what each cost. -#[allow(clippy::too_many_arguments)] // the block, its runs, and what the view is made through +/// The view of the runs `key` of the block `pages` names, through `on`'s memory, which holds its +/// lease, let go of on its teardown, with a buffer over the whole of it on `device`, which holds +/// the runtime's import of its pages, where `import` (none where the caches' copies are staged, +/// [`SurfaceViews::set_staged`]); logs what each cost. fn make_view( platform: &P, device: &P::Device, pages: &RgfxSurfacePages, runs: &[RgfxPageRun], - memory: &MemoryMap

, - lease: Lease, - teardown: Option>, + (memory, lease, teardown): (&MemoryMap

, Lease, Option>), key: &[(u64, u64)], + import: bool, ) -> RaiseResult, PagesRefusal>> { let clock = platform.clock(); let start = clock.now_mono(); @@ -2583,8 +2614,12 @@ fn make_view( Err(why) => return Ok(Err(why)), }; let mapped = clock.now_mono(); - let Some(import) = buffer_over(device, &view, 0, view.length(), 0, None)? else { - return Ok(Err(PagesRefusal::NoBuffer)); + let import = match import { + true => match buffer_over(device, &view, 0, view.length(), 0, None)? { + Some(import) => Some(import), + None => return Ok(Err(PagesRefusal::NoBuffer)), + }, + false => None, }; let imported = clock.now_mono(); log::debug!( diff --git a/crates/reims-vgpu/src/platform.rs b/crates/reims-vgpu/src/platform.rs index 8986b8a20..1afe70616 100644 --- a/crates/reims-vgpu/src/platform.rs +++ b/crates/reims-vgpu/src/platform.rs @@ -56,6 +56,12 @@ pub trait ApiPlatform: Platform { /// (`graphics::decode::unkept`). False by default: the platform keeps every pin. const PINS_IN_BLOCKS: bool = false; + /// Whether a graphics device on the platform stages its IOSurface device caches' copies + /// (`graphics::decode::surface_cache`, "Staged copies"): through the host's CPU and a Shared + /// buffer of each copy's own, with no import of a surface's pages, where an import of the + /// host's memory may cost each of the platform's submissions while it lives. False by default. + const STAGED_SURFACE_COPIES: bool = false; + /// The process's platform, made on first use. fn process() -> Arc; diff --git a/crates/reims-vgpu/src/platform/rt.rs b/crates/reims-vgpu/src/platform/rt.rs index 084c1a032..c13d7ee7a 100644 --- a/crates/reims-vgpu/src/platform/rt.rs +++ b/crates/reims-vgpu/src/platform/rt.rs @@ -17,6 +17,11 @@ impl ApiPlatform for RtPlatform { /// each other one (`rt-gpu-address-unpinned`), which the decoder counts again by kind. const PINS_IN_BLOCKS: bool = true; + /// Each of rt's imports of the host's memory is a Vulkan allocation of its own while it lives + /// (`reims_vgpu_vulkan::rt_platform::buffer`, "Imports"), which a driver may charge each + /// submission for: a surface's cache copies its pages through the host's CPU instead. + const STAGED_SURFACE_COPIES: bool = true; + fn process() -> Arc { crate::singleton::rt_platform() }