diff --git a/crates/reims-vgpu/src/graphics/decode/mod.rs b/crates/reims-vgpu/src/graphics/decode/mod.rs index 956b1e716..766953125 100644 --- a/crates/reims-vgpu/src/graphics/decode/mod.rs +++ b/crates/reims-vgpu/src/graphics/decode/mod.rs @@ -2488,12 +2488,14 @@ impl GraphicsDecoder

{ log::info!( target: "reims_vgpu::graphics", "IOSurface device caches' shapes in place over their pages: {} made ({} MiB), \ - {} refused (rt-shape-in-place-refused-*), the makes {} us in all and {} us \ - at the longest; {} writes the pages took with no copy, {} kept dirty as \ - their buffer held bytes the pages lacked; {} moved to an image of their \ - kind's usage for a texture theirs did not take, {} such textures over the \ - buffer instead", - sh.in_place, sh.in_place_bytes >> 20, sh.in_place_refused, + {} refused (rt-shape-in-place-refused-*), {} moved there after their make \ + ({} MiB), {} moves refused (rt-shape-moved-in-place-refused-*), the makes \ + {} us in all and {} us at the longest; {} writes the pages took with no \ + copy, {} kept dirty as their buffer held bytes the pages lacked; {} moved \ + to an image of their kind's usage for a texture theirs did not take, {} \ + such textures over the buffer instead", + sh.in_place, sh.in_place_bytes >> 20, sh.in_place_refused, sh.moved_in_place, + sh.moved_in_place_bytes >> 20, sh.moved_in_place_refused, sh.in_place_make_ns / 1_000, sh.in_place_make_most_ns / 1_000, sh.in_place_writes, sh.in_place_dirty, sh.moved_widened, sh.widened_unshaped ); diff --git a/crates/reims-vgpu/src/graphics/decode/surface_cache.rs b/crates/reims-vgpu/src/graphics/decode/surface_cache.rs index 47d40e9dd..6ef9e6bd4 100644 --- a/crates/reims-vgpu/src/graphics/decode/surface_cache.rs +++ b/crates/reims-vgpu/src/graphics/decode/surface_cache.rs @@ -869,6 +869,29 @@ impl Default for InPlace

{ } } +impl InPlace

{ + /// What an image in place over the pages is made over: the import kept, else what makes one; + /// `None` where the block is not named by its runs. + fn source(&self) -> Option>>> { + match (&self.import, &self.unmade) { + (Some(import), _) => Some(Ok(import.clone_ref())), + (None, Some(unmade)) => Some(Err(Arc::clone(unmade))), + (None, None) => None, + } + } +} + +/// A shape a begin moves in place over its surface's pages ([`shapes`]' "In place", +/// [`SurfaceCaches::movable`]): its identity, key and image, the usage its image in place takes, +/// and what that image is made over ([`InPlace::source`]). +struct Moving { + id: u64, + key: ShapeKey, + from: P::Texture, + usage: u64, + source: Result>>, +} + impl SurfaceCache

{ /// Whether a guest texture that lies over the buffer itself lives ([`Unshaped`]). fn unshaped_live(&self) -> bool { @@ -4193,6 +4216,12 @@ impl SurfaceCaches

{ let Some(length) = self.unattached(block) else { return Ok(None); }; + // Staged and named by their runs, the pages are what a shape's image in place over them + // is made over ([`shapes`]' "In place"), as at a make by runs. + let unmade = match (&named, self.staged.is_some()) { + (Named::Runs(_, unmade), true) => Some(Arc::clone(unmade)), + _ => None, + }; let ends = match named { // Staged, the pages are copied whichever way they are named. _ if self.staged.is_some() => match named.copied(length) { @@ -4215,6 +4244,9 @@ impl SurfaceCaches

{ cache.pages = Some(ends); cache.carried = None; cache.changed = Changed::All; + if unmade.is_some() { + cache.in_place.unmade = unmade; + } } let pages = Pages { runs: host_pages, @@ -5733,6 +5765,112 @@ impl SurfaceCaches

{ reims_vgpu_vulkan::answer::count_kind_by(shapes::IN_PLACE_MAKE_NS_MOST, rise); } + /// The import `import` an image in place over the block at `block`'s pages lies over, kept + /// by its cache where it keeps none ([`InPlace::import`]); else let go of with the lock: the + /// image holds its own, so one made meanwhile goes with it. + fn keep_import(&mut self, block: u64, import: P::Buffer) { + match self.by_block.get_mut(&block) { + Some(cache) if cache.in_place.import.is_none() => cache.in_place.import = Some(import), + _ => self.let_go.push(import), + } + } + + /// The first shape of the block at `block`'s cache that may move in place over its pages + /// now ([`shapes`]' "In place"): one refused in place at its make for a why that may pass + /// ([`shapes::ShapeTable::movable`]), the cache idle ([`Self::promotion_idle`]), so no work + /// in flight reads the shape's views, and a new shape of its key would be made in place at + /// the CPU's `generation` ([`SurfaceCache::not_in_place`]): the pages then hold every byte + /// the cache holds, with no write of the GPU's or a guest's lock since its last copy. + fn movable(&mut self, block: u64, generation: u64) -> Option> { + if !(self.by_block.get(&block))?.shapes.any_movable() { + return None; + } + if self.promotion_idle(block).is_err() { + return None; + } + let dirty_since = !self.dirty_since(block).is_empty(); + let cache = self.by_block.get(&block)?; + let fits = + |key: &ShapeKey| (cache.not_in_place(key, Some(generation), dirty_since)).is_none(); + let (id, key, from, usage) = cache.shapes.movable(fits)?; + Some(Moving { + id, + key, + from: from.clone_ref(), + usage, + source: cache.in_place.source()?, + }) + } + + /// Moves the shape `moving` names of the block at `block`'s cache to `image`, in place over + /// its pages ([`shapes`]' "In place"), where it may still move at the CPU's `generation` + /// ([`Self::movable`]): `image` added as an in-place shape of its key, the shape's views made + /// `image`'s ([`Texture::retarget_views`]) with no copy, as the pages hold every byte the + /// cache holds, and the shape taken out as at a promotion, its references the new shape's + /// and its image held, its bytes still the caches', until no texture made over it before + /// lives ([`shapes::ShapeTable::promote`]); counted. `Err` with `image`, for the caller to + /// let go of with no lock held, where the cache changed meanwhile or the platform refused the + /// retarget. + fn move_in_place( + &mut self, + block: u64, + moving: &Moving

, + image: P::Texture, + generation: u64, + ) -> Result<(), P::Texture> { + if self.promotion_idle(block).is_err() { + return Err(image); + } + let dirty_since = !self.dirty_since(block).is_empty(); + let now = self.tick_shapes(); + let Some(cache) = self.by_block.get_mut(&block) else { + return Err(image); + }; + let same = |key: &ShapeKey| *key == moving.key; + let still = (cache.shapes.movable(same)).is_some_and(|(id, ..)| id == moving.id); + if !still || (cache.not_in_place(&moving.key, Some(generation), dirty_since)).is_some() { + return Err(image); + } + let onto = image.clone_ref(); + let (reference, _) = cache + .shapes + .insert_in_place(moving.key, image, moving.usage, now); + let new = reference.id(); + drop(reference); + if moving.from.retarget_views(&onto).is_none() { + return Err(cache.shapes.take_id(new).map_or(onto, |shape| shape.image)); + } + cache.shapes.promote(moving.id, new, true); + let bytes = moving.key.bytes(); + let counts = &mut self.counts.shapes; + counts.moved_in_place += 1; + counts.moved_in_place_bytes += bytes; + reims_vgpu_vulkan::answer::count_kind(shapes::MOVED_IN_PLACE); + reims_vgpu_vulkan::answer::count_kind_by(shapes::MOVED_IN_PLACE_BYTES, bytes); + Ok(()) + } + + /// The platform made no image in place for the shape `id` of the block at `block`'s cache + /// that a begin would move there, for `why` ([`Caches::make_in_place`]): the shape keeps its + /// own image for good, its why that one ([`shapes::ShapeTable::refused`]); counted by why + /// ([`shapes::MOVED_IN_PLACE_REFUSED`]), the first of each why logged. + fn refuse_move(&mut self, block: u64, id: u64, why: &'static str) { + if let Some(cache) = self.by_block.get_mut(&block) { + cache.shapes.refused(id, why); + } + self.counts.shapes.moved_in_place_refused += 1; + let (code, first) = why_code(shapes::MOVED_IN_PLACE_REFUSED, why); + reims_vgpu_vulkan::answer::count_kind(code); + if first { + log::info!( + target: "reims_vgpu::graphics", kind:% = code; + "the IOSurface block at {block:#x}: a shape made before it could lie in place over \ + its pages was not moved there ({why}); it keeps the platform's own image ({code}; \ + the rest are counted)" + ); + } + } + /// Moves the in-place shape `id` of the block at `block`'s cache to `image`, of its kind's /// usage, the platform's own (the module doc of [`shapes`], "In place"), the cache idle /// ([`Self::promotion_idle`]): `image` added as a shape of the same key, the in-place image @@ -8303,19 +8441,25 @@ pub(crate) struct Caches { } /// The counts' code of a shape not made in place over its pages for `why` -/// ([`shapes::IN_PLACE_REFUSED`]), made once a why and kept for the process (the counts keep -/// codes as `&'static str`), and whether the why is met for the first time: its line is logged -/// the first time alone, the rest counted (docs/conventions.md). The whys are bounded: the -/// caches' own and the platform's. +/// ([`shapes::IN_PLACE_REFUSED`]), and whether the why is met for the first time +/// ([`why_code`]). fn in_place_refused_code(why: &str) -> (&'static str, bool) { - static CODES: Mutex> = Mutex::new(Vec::new()); + why_code(shapes::IN_PLACE_REFUSED, why) +} + +/// The counts' code `-`, made once a code and kept for the process (the counts keep +/// codes as `&'static str`), and whether it is met for the first time: its line is logged the +/// first time alone, the rest counted (docs/conventions.md). The whys are bounded: the caches' +/// own and the platform's. +fn why_code(prefix: &'static str, why: &str) -> (&'static str, bool) { + static CODES: Mutex> = Mutex::new(Vec::new()); let mut codes = CODES.lock(); - if let Some(&(_, code)) = codes.iter().find(|(w, _)| w == why) { + if let Some(&(_, _, code)) = (codes.iter()).find(|(p, w, _)| *p == prefix && w == why) { return (code, false); } - let code = format!("{}-{why}", shapes::IN_PLACE_REFUSED); + let code = format!("{prefix}-{why}"); let code: &'static str = Box::leak(code.into_boxed_str()); - codes.push((why.to_owned(), code)); + codes.push((prefix, why.to_owned(), code)); (code, true) } @@ -9179,8 +9323,13 @@ impl Caches

{ (desc, ask): (&TextureDesc, InPlaceAsk), ) -> Option> { let held = self.shape_of(platform, device, block, key, (desc, ask))?; + let mut st = self.lock(); + // What an image in place it may move to later takes ([`shapes`]' "In place"). + if let Some(cache) = st.by_block.get_mut(&block) { + cache.shapes.asked(held.0.id(), ask.usage); + } if key.storage { - self.lock().ask_promotion(device, block, key); + st.ask_promotion(device, block, key); } Some(held) } @@ -9192,7 +9341,8 @@ impl Caches

{ self.lock().promoted_at_make(block, key) } - /// [`Self::shape`]'s shape, before the promotion it asks. + /// [`Self::shape`]'s shape, before the promotion it asks. One not made in place over its + /// pages keeps the why ([`shapes::ShapeTable::refused`]), which a later begin may see pass. fn shape_of( &self, platform: &P, @@ -9211,15 +9361,25 @@ impl Caches

{ if let Some(found) = self.plane_shape(platform, device, block, &key) { return Some(found); } - if let Some(found) = self.in_place_shape(device, block, key, desc, ask) { - return found; - } + let refused = match self.in_place_shape(device, block, key, desc, ask) { + Some(Ok(found)) => return found, + Some(Err(why)) => Some(why), + None => None, + }; + let note = |held: &Option>| { + if let (Some(why), Some((reference, _))) = (refused, held) + && let Some(cache) = self.lock().by_block.get_mut(&block) + { + cache.shapes.refused(reference.id(), why); + } + }; if self.shapes_placed.load(Ordering::Acquire) && self.fills_at_once(block) && !self.fills_zeros(block) && let Some(image) = maker(device, desc, true) && let Some(placed) = self.placed_shape(device, block, key, image) { + note(&placed); return placed; } let Some(image) = maker(device, desc, false) else { @@ -9228,16 +9388,17 @@ impl Caches

{ }; let (shape, gone) = self.lock().add_shape(block, key, image, (true, None)); let_go_of_shapes(block, gone); + note(&shape); shape } /// The shape `key` of the block at `block`'s cache made in place over its pages where it may /// ([`shapes`]' "In place"), its image of `desc` but of the usage the texture declares /// (`ask`): the pages' import made first where the cache holds none, with the lock let go - /// of, as the image is ([`InPlaceMaker`]), whose make is timed and counted. `Some` with the - /// shape where it was made, or the cache held it meanwhile, `Some(None)` where the block lost - /// its cache meanwhile; `None` where it is not made in place, counted by why, for the caller - /// to make it as before. + /// of, as the image is ([`Self::make_in_place`]). `Ok` with the shape where it was made, or + /// the cache held it meanwhile, `Ok(None)` where the block lost its cache meanwhile; `Err` + /// with the why where it is not made in place, counted by why, for the caller to make it as + /// before; `None` where no make in place is asked here. fn in_place_shape( &self, device: &P::Device, @@ -9245,22 +9406,75 @@ impl Caches

{ key: ShapeKey, desc: &TextureDesc, ask: InPlaceAsk, - ) -> Option>> { + ) -> Option>, &'static str>> { let maker = self.in_place_maker.get()?; - let (source, now) = { + let source = { let mut st = self.lock(); if let Some(why) = st.not_in_place(block, &key, ask.generation) { st.refuse_in_place(block, why); - return None; + return Some(Err(why)); } - let in_place = &st.by_block.get(&block)?.in_place; - let source = match (&in_place.import, &in_place.unmade) { - (Some(import), _) => Ok(import.clone_ref()), - (None, Some(unmade)) => Err(Arc::clone(unmade)), - (None, None) => return None, - }; - (source, st.shape_now.clone()) + st.by_block.get(&block)?.in_place.source()? }; + let narrowed = TextureDesc { + usage: ask.usage, + ..*desc + }; + let (image, import) = + match self.make_in_place(maker, device, block, source, &narrowed, &key) { + Ok(made) => made, + Err(why) => { + self.lock().refuse_in_place(block, why); + return Some(Err(why)); + } + }; + let mut st = self.lock(); + // Looked at again: the cache may have changed with the lock let go of. + match st.find_shape(block, &key) { + None => { + st.let_go.push(import); + drop(st); + let_go_of_shapes(block, vec![image]); + return Some(Ok(None)); + } + Some(Some(found)) => { + st.let_go.push(import); + drop(st); + let_go_of_shapes(block, vec![image]); + return Some(Ok(Some(found))); + } + Some(None) => {} + } + if let Some(why) = st.not_in_place(block, &key, ask.generation) { + st.refuse_in_place(block, why); + st.let_go.push(import); + drop(st); + let_go_of_shapes(block, vec![image]); + return Some(Err(why)); + } + st.keep_import(block, import); + let (shape, gone) = st.add_shape(block, key, image, (false, Some(ask.usage))); + drop(st); + let_go_of_shapes(block, gone); + Some(Ok(shape)) + } + + /// An image of `desc` in place over the block at `block`'s pages at `key`'s place and pitch, + /// made with no lock held by `maker` ([`InPlaceMaker`]) over `source`, the cache's import of + /// the pages or what makes one ([`InPlace::source`]): the image and the import it lies over, + /// for the caller to keep ([`SurfaceCaches::keep_import`]) or let go of. The make is timed + /// and counted, refused or not ([`SurfaceCaches::count_in_place_make`]). `Err` with the why + /// where there is no import (`no-import`, logged) or the platform refused the image (its why), + /// the import then let go of. + fn make_in_place( + &self, + maker: &InPlaceMaker

, + device: &P::Device, + block: u64, + source: Result>>, + desc: &TextureDesc, + key: &ShapeKey, + ) -> Result<(P::Texture, P::Buffer), &'static str> { let import = match source { Ok(import) => import, Err(unmade) => match unmade.make_import(device) { @@ -9271,8 +9485,7 @@ impl Caches

{ "the IOSurface block at {block:#x}: no import of its pages for a shape in \ place ({why:?})" ); - self.lock().refuse_in_place(block, "no-import"); - return None; + return Err("no-import"); } Err(raise) => { log::warn!( @@ -9280,65 +9493,73 @@ impl Caches

{ "the IOSurface block at {block:#x}: the platform raised at the import of \ its pages for a shape in place ({raise:?})" ); - self.lock().refuse_in_place(block, "no-import"); - return None; + return Err("no-import"); } }, }; - let narrowed = TextureDesc { - usage: ask.usage, - ..*desc - }; + let now = self.lock().shape_now.clone(); let start = now.as_ref().map(|now| now()); - let made = maker(device, &import, &narrowed, key.offset, key.bytes_per_row); + let made = maker(device, &import, desc, key.offset, key.bytes_per_row); let ns = match (now, start) { (Some(now), Some(start)) => now().saturating_duration_since(start).as_nanos(), _ => 0, }; let mut st = self.lock(); st.count_in_place_make(u64::try_from(ns).unwrap_or(u64::MAX)); - let image = match made { - Ok(image) => image, + match made { + Ok(image) => Ok((image, import)), Err(refused) => { - st.refuse_in_place(block, refused.0); st.let_go.push(import); - return None; + Err(refused.0) } + } + } + + /// Moves in place over their pages the shapes of the block `u` names that its cache made + /// before they could lie there, where they now may ([`shapes`]' "In place"), as a begin's + /// promotions are made, before it counts its uses: each move's image made with the lock let + /// go of ([`Self::make_in_place`]), and the move made once it is taken again where nothing + /// changed meanwhile ([`SurfaceCaches::move_in_place`]). One the platform refuses leaves the + /// shape on its own image for good, counted by why ([`SurfaceCaches::refuse_move`]). None + /// while the process records (`reims_vgpu_vulkan::recorder`), whose stream holds no retarget; + /// at most [`shapes::MOVES_A_BEGIN`] a block a begin. + fn move_in_place(&self, state: &mut Locked<'_, P>, device: &P::Device, u: &RgfxOpSurfaceUse) { + let Some(maker) = self.in_place_maker.get() else { + return; }; - // Looked at again: the cache may have changed with the lock let go of. - match st.find_shape(block, &key) { - None => { - st.let_go.push(import); - drop(st); - let_go_of_shapes(block, vec![image]); - return Some(None); - } - Some(Some(found)) => { - st.let_go.push(import); - drop(st); - let_go_of_shapes(block, vec![image]); - return Some(Some(found)); - } - Some(None) => {} + if reims_vgpu_vulkan::recorder::on() { + return; } - if let Some(why) = st.not_in_place(block, &key, ask.generation) { - st.refuse_in_place(block, why); - st.let_go.push(import); - drop(st); - let_go_of_shapes(block, vec![image]); - return None; - } - // The image holds its own import: a second one made meanwhile goes with it. - if let Some(cache) = st.by_block.get_mut(&block) { - match &cache.in_place.import { - Some(_) => st.let_go.push(import), - None => cache.in_place.import = Some(import), + let block = u.block_offset; + for _ in 0..shapes::MOVES_A_BEGIN { + let Some(moving) = state.movable(block, u.cpu_gen) else { + return; + }; + let desc = TextureDesc { + usage: moving.usage, + ..super::surface_shapes::shape_image_desc(moving.from.pixel_format(), &moving.key) + }; + let source = match &moving.source { + Ok(import) => Ok(import.clone_ref()), + Err(unmade) => Err(Arc::clone(unmade)), + }; + let made = state + .unlocked(|| self.make_in_place(maker, device, block, source, &desc, &moving.key)); + let image = match made { + Ok((image, import)) => { + state.keep_import(block, import); + image + } + Err(why) => { + state.refuse_move(block, moving.id, why); + continue; + } + }; + if let Err(image) = state.move_in_place(block, &moving, image, u.cpu_gen) { + state.unlocked(|| let_go_of_shapes(block, vec![image])); + return; } } - let (shape, gone) = st.add_shape(block, key, image, (false, Some(ask.usage))); - drop(st); - let_go_of_shapes(block, gone); - Some(shape) } /// The usage of the image of the shape `reference` names of the block at `block`'s cache, @@ -10117,6 +10338,11 @@ impl Caches

{ state.unlocked(|| let_go_of_shapes(u.block_offset, gone)); } } + // The shapes its uses' caches made before they could lie in place over their pages move + // there where they now may, the caches idle ([`shapes`]' "In place"). + for u in uses { + self.move_in_place(&mut state, device, u); + } let picked: Vec = by_block(&state, uses).into_iter().copied().collect(); let decoded_of = |block: u64| { (reach.decoded.iter()) 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 7ea39e73f..4e2c36bc5 100644 --- a/crates/reims-vgpu/src/graphics/decode/surface_cache/shapes.rs +++ b/crates/reims-vgpu/src/graphics/decode/surface_cache/shapes.rs @@ -216,7 +216,21 @@ //! CPU generation is settled, either never moved by a read-write lock (0) or seen unlocked by a //! use's `RGFX_SURFACE_USE_REFILL` at that generation (`SurfaceCaches`'s `settle`). Anywhere else, //! and where the platform refuses (its why), the shape takes the platform's own image as before, -//! counted by why ([`IN_PLACE_REFUSED`]). The make's time is counted ([`IN_PLACE_MAKE_NS`]): on rt, +//! counted by why ([`IN_PLACE_REFUSED`]), and keeps the why. One refused for a why of the +//! caches' that may pass ([`MOVABLE`]) moves in place once it has, as a deferred surface's shapes +//! made before the CPU's first lock named its pages do: at the first begin of a command buffer +//! that uses its cache, as a promotion is made, where the cache is idle ("Promotion"), the +//! generation settled and the cache holding nothing the pages lack, so the pages hold every byte +//! its image holds, an image in place is made over them of its textures' usages together, its +//! views made that image's with no copy, and its own image +//! held as a promoted plain image is, counted ([`MOVED_IN_PLACE`]). A guest's write to the pages +//! after the shape's last copy moves the generation, which stays unsettled until a use carrying +//! `RGFX_SURFACE_USE_REFILL` shows its unlock, whose fill takes the newer bytes first; a GPU's +//! write marks it dirty until a copy out takes it. A move the platform refuses leaves the shape on +//! its own image for good, counted by why ([`MOVED_IN_PLACE_REFUSED`]); a begin makes at most +//! [`MOVES_A_BEGIN`] a block. A straight download of a shape not in place is counted by the why +//! its make was refused for ([`DOWNLOADS_REFUSED`]). The make's time is counted, a move's among +//! them ([`IN_PLACE_MAKE_NS`]): on rt, //! over host memory on a device of one memory, it moves the image home in a submission of its own //! before it returns, so the bytes the guest's CPU wrote before the make and after its return are //! kept, as Metal touches no byte at a texture's make; a write by another of the guest's threads @@ -472,6 +486,27 @@ pub(crate) const IN_PLACE_DIRTY: &str = "rt-shape-in-place-dirty"; pub(crate) const MOVED_WIDENED: &str = "rt-shape-moved-widened"; pub(crate) const WIDENED_UNSHAPED: &str = "rt-shape-widened-unshaped"; +/// The counts' code of the shapes made before they could lie in place over their pages that +/// moved there later, and their bytes (the module doc, "In place"); and the prefix of the codes +/// of the moves the platform refused, a code a why (`rt-shape-moved-in-place-refused-`). +pub(crate) const MOVED_IN_PLACE: &str = "rt-shape-moved-in-place"; +pub(crate) const MOVED_IN_PLACE_BYTES: &str = "rt-shape-moved-in-place-bytes"; +pub(crate) const MOVED_IN_PLACE_REFUSED: &str = "rt-shape-moved-in-place-refused"; + +/// The prefix of the counts' codes of the straight downloads of shapes not in place, by the why +/// their make was not (`rt-shape-downloads-refused-`; the module doc, "In place"). +pub(crate) const DOWNLOADS_REFUSED: &str = "rt-shape-downloads-refused"; + +/// The whys of the caches' own for a shape not made in place over its pages that may pass while +/// the shape lives, for which a begin moves it there once they have (the module doc, "In +/// place"): the cache's layout (pages it carries until its pages are named), a texture over its +/// buffer, its pages not named yet, its CPU generation not settled, and a write the pages lack. +pub(crate) const MOVABLE: [&str; 5] = ["layout", "over-buffer", "no-pages", "unsettled", "behind"]; + +/// The moves in place a begin makes at most for a block (the module doc, "In place"): a bound on +/// its work, as each move's image is made with the caches' lock let go of. +pub(crate) const MOVES_A_BEGIN: usize = 8; + /// The degradation code of an encoder that may have written two shapes of one plane: Metal /// would write the plane's one texture memory through both in the order the GPU ran them, which /// the per-shape form cannot know; the shape the walk noted last is taken as the plane's write @@ -855,6 +890,11 @@ pub(crate) struct ShapeCounts { pub(crate) in_place_dirty: u64, pub(crate) moved_widened: u64, pub(crate) widened_unshaped: u64, + /// Shapes made before they could lie in place over their pages that moved there at a begin, + /// and their bytes; and the moves the platform refused (the module doc, "In place"). + pub(crate) moved_in_place: u64, + pub(crate) moved_in_place_bytes: u64, + pub(crate) moved_in_place_refused: u64, } /// What an entry's shapes hold now, for the host's summary (`crate::graphics::summary::kept`), @@ -930,6 +970,12 @@ pub(crate) struct Shape { /// Its image lies in place over the surface's pages, of this usage (the module doc, "In /// place"); `None` for an image of the platform's own. pub(crate) in_place: Option, + /// The usages of the textures made over it together, Metal's Unknown (0) taking every one: + /// what an image in place it moves to takes ([`ShapeTable::asked`]); `None` before the first. + asked: Option, + /// Why it was not made in place over the surface's pages, where it was asked + /// ([`ShapeTable::refused`]): one of [`MOVABLE`] lets a later begin move it there. + refused: Option<&'static str>, } /// A plain shape's image promoted into a storage shape, held while a texture made over the plain @@ -970,6 +1016,17 @@ impl Shape { Arc::as_ptr(&self.tag).addr() as u64 } + /// Whether it may move in place over the surface's pages ([`ShapeTable::any_movable`]). + fn movable(&self) -> bool { + self.in_place.is_none() + && !self.plane + && !self.drawn + && !self.dirty + && !self.video + && self.asked.is_some() + && self.refused.is_some_and(|why| MOVABLE.contains(&why)) + } + /// It holds no write the buffer lacks: a copy into the buffer, a fill from it, or a loss of /// its image took what it held. Unreferenced, it then waits for the age rule, which its /// table's [`Idle`] is told. @@ -1183,13 +1240,15 @@ impl ShapeTable { cleared: false, used: now, in_place: None, + asked: None, + refused: None, }); (reference, again) } /// Adds the shape of `key` as [`Self::insert`] does, its image `image` in place over the /// surface's pages, of `usage` (the module doc, "In place"): it holds the pages, so it owes no - /// fill. + /// fill, and its image is the pages' memory, so it counts no bytes of the caches' budget. pub(crate) fn insert_in_place( &mut self, key: ShapeKey, @@ -1200,10 +1259,50 @@ impl ShapeTable { let made = self.insert(key, image, false, now); if let Some(shape) = self.shapes.last_mut() { shape.in_place = Some(usage); + shape.bytes = 0; } made } + /// A texture declaring `usage` was made over the shape `id`: the shape's textures' usages + /// together ([`Shape::asked`]), Metal's Unknown (0) taking every one. + pub(crate) fn asked(&mut self, id: u64, usage: u64) { + if let Some(shape) = self.shapes.iter_mut().find(|s| s.id() == id) { + shape.asked = Some(match shape.asked { + None => usage, + Some(asked) if asked == 0 || usage == 0 => 0, + Some(asked) => asked | usage, + }); + } + } + + /// The shape `id` is not in place over the surface's pages for `why` ([`Shape::refused`]). + pub(crate) fn refused(&mut self, id: u64, why: &'static str) { + if let Some(shape) = self.shapes.iter_mut().find(|s| s.id() == id) { + shape.refused = Some(why); + } + } + + /// Whether a shape may move in place over the surface's pages (the module doc, "In place"): + /// one of the platform's own image, no plane shape, refused in place at its make for a why + /// that may pass ([`MOVABLE`]), with a texture made over it, holding no write the buffer + /// lacks. A cache that holds none is passed by at once. + pub(crate) fn any_movable(&self) -> bool { + self.shapes.iter().any(Shape::movable) + } + + /// The first shape that may move in place over the surface's pages ([`Self::any_movable`]) + /// whose key `fits`: its identity, key and image, and the usage an image in place takes for + /// it, its textures' together ([`Shape::asked`]), as a shape made in place takes the usage + /// its texture declares. + pub(crate) fn movable( + &self, + fits: impl Fn(&ShapeKey) -> bool, + ) -> Option<(u64, ShapeKey, &T, u64)> { + let shape = (self.shapes.iter()).find(|s| s.movable() && fits(&s.key))?; + Some((shape.id(), shape.key, &shape.image, shape.asked?)) + } + /// The usage of the image of the shape `id`, where it lies in place over the surface's pages /// (the module doc, "In place"); `None` for any other shape, and where the table holds none /// of `id`. @@ -1438,6 +1537,9 @@ impl ShapeTable { counts.downloaded_bytes += shape.bytes; reims_vgpu_vulkan::answer::count_kind(DOWNLOADS); reims_vgpu_vulkan::answer::count_kind_by(DOWNLOAD_BYTES, shape.bytes); + if let Some(why) = shape.refused { + reims_vgpu_vulkan::answer::count_kind(super::why_code(DOWNLOADS_REFUSED, why).0); + } } } diff --git a/crates/reims-vgpu/src/graphics/decode/surface_shapes.rs b/crates/reims-vgpu/src/graphics/decode/surface_shapes.rs index 1947daa9d..ac58ed0f8 100644 --- a/crates/reims-vgpu/src/graphics/decode/surface_shapes.rs +++ b/crates/reims-vgpu/src/graphics/decode/surface_shapes.rs @@ -77,6 +77,22 @@ const TEXTURE_USAGE_PIXEL_FORMAT_VIEW: u64 = 0x10; /// (`shapes`, "The shape"). const PLAIN_USAGE: u64 = 0x1 | 0x4; +/// The image of the shape `key` in `pixel_format`: the guest's format and size, Private, at no +/// index of the guest's; a storage shape's of Metal's Unknown usage, which takes every use and a +/// view in any format of the texel's size, a plain shape's `ShaderRead | RenderTarget` alone +/// (`shapes`, "The shape"). +pub(super) fn shape_image_desc(pixel_format: u64, key: &ShapeKey) -> TextureDesc { + TextureDesc { + texture_type: TEXTURE_TYPE_2D, + pixel_format, + width: key.width, + height: key.height, + usage: if key.storage { 0 } else { PLAIN_USAGE }, + resource_options: Some(STORAGE_PRIVATE), + ..TextureDesc::default() + } +} + /// Whether a texture over a plain shape took the storage shape for its format was logged /// ([`FORMAT_STORAGE`]): its line is logged the first time alone, the rest counted /// (docs/conventions.md). @@ -260,19 +276,7 @@ impl GraphicsDecoder

{ }; let d = &m.desc; let pixel_format = u64::from(d.pixel_format); - // The image: the guest's format and size, Private, at no index of the guest's; a storage - // shape's of Metal's Unknown usage, which takes every use and a view in any format of the - // texel's size, a plain shape's `ShaderRead | RenderTarget` alone (`shapes`, "The - // shape"). - let image = TextureDesc { - texture_type: TEXTURE_TYPE_2D, - pixel_format, - width: key.width, - height: key.height, - usage: if key.storage { 0 } else { PLAIN_USAGE }, - resource_options: Some(STORAGE_PRIVATE), - ..TextureDesc::default() - }; + let image = shape_image_desc(pixel_format, &key); // A texture that writes a video cache's plane whole views the plane (`shapes`, "Plane // shapes"); any other that takes storage, its storage shape. A new shape is made in place // over the pages where it may, of the usage the texture declares (`shapes`, "In place"). @@ -5649,4 +5653,180 @@ mod tests { assert_eq!((shapes.moved_widened, shapes.widened_unshaped), (1, 0)); assert_eq!(made.lock().len(), 1, "no second make in place"); } + + /// [`shaped_staged`]'s rig over a deferred block of two pages (`surface_cache`'s module doc, + /// "Deferred blocks"), a surface the CPU has not locked: its pages, whose bytes are set (from + /// page 1), are not named until [`attach_pages`]. + fn shaped_staged_deferred() -> Rig { + use reims_vgpu_graphics::wire::{RGFX_SURFACE_PAGES_CACHED, RGFX_SURFACE_PAGES_DEFERRED}; + let mut r = rig(8); + r.dec.set_staged_surface_copies(); + let page = r.page; + r.dec.set_deferred_budget(8 * page); + take_shapes(&r); + r.dec.hold_resource_ids(0, 1); + ram_bytes(&r, 1, 2 * page, Some(0x11)); + let flags = RGFX_SURFACE_PAGES_CACHED | RGFX_SURFACE_PAGES_DEFERRED; + assert_eq!( + r.pages_flagged(BLOCK, 0, &[], 2 * page, flags), + RGFX_STATUS_OK + ); + queues(&mut r); + assert_eq!(r.buffer(10, BLOCK, 2 * page), Ok(())); + compute_pipeline(&mut r, 31); + r.p.script() + .always(TEXTURE_SLOT_WRITES, Step::value(Some(true))); + r + } + + /// The deferred block's pages named at the CPU's first lock, by their runs, pages 1 and 2. + fn attach_pages(r: &mut Rig) { + use reims_vgpu_graphics::wire::{RGFX_SURFACE_PAGES_ATTACH, RGFX_SURFACE_PAGES_CACHED}; + let page = r.page; + let flags = RGFX_SURFACE_PAGES_CACHED | RGFX_SURFACE_PAGES_ATTACH; + assert_eq!( + r.pages_flagged(BLOCK, 7, &[(1, 2)], 2 * page, flags), + RGFX_STATUS_OK + ); + } + + /// [`shaped_staged_deferred`]'s texture 25 made before the pages are named, written by a + /// shader; then the pages named and the write downloaded into them: the image of its shape, + /// the platform's own. + fn written_before_its_pages(r: &mut Rig) -> u64 { + let own = writable_at(r, 25, 0); + shader_writes(r, 0x100, 25); + complete_staged(r); + attach_pages(r); + let done = download(r, BLOCK); + complete_staged(r); + assert!(done.load(Ordering::SeqCst), "answered"); + own + } + + /// A deferred surface's shape made before the CPU's first lock named its pages takes the + /// platform's own image, refused in place as `no-pages`. Once the pages are named and its + /// write is downloaded into them, the next begin of a command buffer that uses the surface + /// moves it in place with no copy: an image in place over the pages of its texture's usage, + /// the texture's view made a view of it, counted. A write through it is then in the pages, + /// and the download that follows copies nothing (`shapes`, "In place") + #[test] + fn a_deferred_surfaces_shape_moves_in_place_once_its_pages_hold_its_bytes() { + let mut r = shaped_staged_deferred(); + let made = in_place(&r, |_| None); + let cache = cache_id(&r); + let code = "rt-shape-in-place-refused-no-pages"; + let was = counted(code); + let own = written_before_its_pages(&mut r); + assert!(made.lock().is_empty(), "no make asked before the pages"); + assert_eq!(counted(code) - was, 1); + assert_eq!(r.dec.caches().counts().shapes.moved_in_place, 0); + + let mark = r.p.call_log().mark(); + use_surfaces(&mut r, 1, 0x101, &[(BLOCK, 0, false)]); + complete_staged(&r); + let calls = r.p.call_log().since(mark); + assert_eq!(*made.lock(), [(0x2, 0, 128)], "of the texture's usage"); + let moved = retargets(&calls); + assert_eq!(moved.len(), 1, "{moved:?}"); + assert_eq!(moved[0].0, handle(&r, 25).0, "texture 25's view"); + assert_ne!(moved[0].1, own, "onto an image of its own"); + assert!(texture_copies(&calls).is_empty(), "no copy"); + assert!(fills(&calls).is_empty(), "no fill"); + let shapes = r.dec.caches().counts().shapes; + assert_eq!( + (shapes.moved_in_place, shapes.moved_in_place_bytes), + (1, 32 * 8 * 4) + ); + + let downloaded = shapes.downloaded; + shader_writes(&mut r, 0x102, 25); + complete_staged(&r); + let mark = r.p.call_log().mark(); + let done = download(&r, BLOCK); + complete_staged(&r); + let calls = r.p.call_log().since(mark); + assert!(done.load(Ordering::SeqCst), "answered"); + assert!(written_back(&calls).is_empty(), "no write-back"); + assert!( + copies_out(&calls, cache).is_empty(), + "nothing out of the buffer" + ); + let shapes = r.dec.caches().counts().shapes; + assert_eq!((shapes.in_place_writes, shapes.downloaded), (1, downloaded)); + assert_eq!(made.lock().len(), 1, "moved once"); + } + + /// A guest's write to the pages after the download that lets a shape move in place, under a + /// read-write lock that moves the surface's CPU generation, holds the move: the begin whose + /// use carries `RGFX_SURFACE_USE_REFILL` at the new generation fills the shape's own image + /// from the pages, with the newer bytes, and moves nothing; the next begin moves it, its + /// image in place over the pages that hold those bytes, with no copy (`shapes`, "In place") + #[test] + fn a_guest_write_after_the_download_holds_the_move_until_its_unlock_shows() { + use super::super::surface_cache::CPU_GEN_OFFSET; + use reims_vgpu_graphics::ops::RGFX_SURFACE_USE_REFILL; + let mut r = shaped_staged_deferred(); + let made = in_place(&r, |_| None); + let page = r.page; + let own = written_before_its_pages(&mut r); + ram_bytes(&r, 1, 2 * page, Some(0x22)); + assert!( + r.dec + .region + .write(BLOCK + CPU_GEN_OFFSET, &1u64.to_le_bytes()) + ); + + let mark = r.p.call_log().mark(); + use_flagged(&mut r, 1, 0x101, &[(BLOCK, 1, RGFX_SURFACE_USE_REFILL)]); + complete_staged(&r); + let calls = r.p.call_log().since(mark); + assert!(made.lock().is_empty(), "no move at the unlock's begin"); + assert!(retargets(&calls).is_empty()); + let filled: Vec = fills(&calls).into_iter().map(|(_, _, to)| to).collect(); + assert!(filled.contains(&own), "the newer bytes filled: {filled:?}"); + assert_eq!(r.dec.caches().counts().shapes.moved_in_place, 0); + + let mark = r.p.call_log().mark(); + use_surfaces(&mut r, 1, 0x102, &[(BLOCK, 1, false)]); + complete_staged(&r); + let calls = r.p.call_log().since(mark); + assert_eq!(*made.lock(), [(0x2, 0, 128)]); + assert_eq!(retargets(&calls).len(), 1); + assert!(texture_copies(&calls).is_empty(), "no copy"); + assert!(fills(&calls).is_empty(), "no fill"); + assert_eq!(r.dec.caches().counts().shapes.moved_in_place, 1); + } + + /// A move in place the platform refuses leaves the shape on its own image for good, counted + /// by the platform's why and not asked again at later begins; its later straight downloads + /// are counted by that why (`shapes`, "In place") + #[test] + fn a_refused_move_in_place_leaves_the_shape_on_its_own_image() { + let mut r = shaped_staged_deferred(); + let made = in_place(&r, |_| Some("linear-features")); + let code = "rt-shape-moved-in-place-refused-linear-features"; + let downloads = "rt-shape-downloads-refused-linear-features"; + let (was, downloads_was) = (counted(code), counted(downloads)); + written_before_its_pages(&mut r); + use_surfaces(&mut r, 1, 0x101, &[(BLOCK, 0, false)]); + complete_staged(&r); + assert_eq!(made.lock().len(), 1, "asked once"); + assert_eq!(counted(code) - was, 1); + let shapes = r.dec.caches().counts().shapes; + assert_eq!( + (shapes.moved_in_place, shapes.moved_in_place_refused), + (0, 1) + ); + + shader_writes(&mut r, 0x102, 25); + complete_staged(&r); + let done = download(&r, BLOCK); + complete_staged(&r); + assert!(done.load(Ordering::SeqCst), "answered"); + use_surfaces(&mut r, 1, 0x103, &[(BLOCK, 0, false)]); + complete_staged(&r); + assert_eq!(made.lock().len(), 1, "not asked again"); + assert_eq!(counted(downloads) - downloads_was, 1); + } }