diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 69d9b6f97..d7ad03af1 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -839,8 +839,8 @@ meanwhile wait for it. uses of guest RAM (`HostRamUse`), the no-copy buffers, the `Private` buffers, the buffers in the runtime's own pages, the `Private` heaps with the buffers placed in them, the textures of `new_texture`, the textures over the buffers it carried and the views of either, and the - compute and tile pipeline states to the new `VkDevice`: the same objects, at the same addresses - and resource IDs. A pipeline state's base variant is made again there from what its creation + compute, tile, drawing and mesh pipeline states to the new `VkDevice`: the same objects, at the + same addresses and resource IDs. A pipeline state's base variant is made again there from what its creation compiled, with no translation, and the `VkPipeline` its creation predicted is queued with no wait; a bind of one whose making there failed is refused (`RuntimeGap::RemadeAfterRecoveryFailed`). Its objects on the lost `VkDevice` stay with it, and @@ -873,8 +873,8 @@ meanwhile wait for it. costs its submissions or that textures over such pages take less, or had not answered; and a `Managed` buffer without unified memory), detached no-copy buffers, `Shared`, no-copy and sparse heaps with the buffers placed in them, heaps' textures, textures over the caller's - `VkImage`, sparse and shareable textures, textures over buffers left and their views, render - pipeline states, buffers over the caller's `VkBuffer`, and exportable memory or events. Make it again. + `VkImage`, sparse and shareable textures, textures over buffers left and their views, buffers + over the caller's `VkBuffer`, and exportable memory or events. Make it again. Metal's objects go on. The recovery's notice counts the buffers, heaps, textures and events it carried and left, by kind. - The lost `VkDevice` is destroyed once the objects left on it went and, where `Device::raw` diff --git a/crates/metal2vulkan-runtime/src/argument_encoder.rs b/crates/metal2vulkan-runtime/src/argument_encoder.rs index 3ec233291..8c918aa66 100644 --- a/crates/metal2vulkan-runtime/src/argument_encoder.rs +++ b/crates/metal2vulkan-runtime/src/argument_encoder.rs @@ -683,7 +683,7 @@ impl ArgumentEncoder { match state { None => Ok(0), Some(state) => { - self.check_device(call, state.device())?; + self.check_device(call, state.bound_device()?)?; Ok(state.gpu_resource_id().0) } } diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 71bd110cb..2c0cb1f4e 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -2312,8 +2312,8 @@ degradations! { the device's checks found a held host-page import costs its submissions nothing and \ textures over such pages take what they take over its own memory), `Private` heaps \ with the buffers placed in them, textures of `new_texture`, textures over the \ - buffers carried and views of them, and compute and tile pipeline states made before \ - it go on, the contents of a `Private` \ + buffers carried and views of them, and pipeline states made before it go on, the \ + contents of a `Private` \ buffer or heap lost (it reads zero) and of a texture of `new_texture` of any \ storage mode (it reads as a new one) but a texture buffer over its texels' buffer \ carried; the other objects made before it are refused (`MadeBeforeRecovery`), \ diff --git a/crates/metal2vulkan-runtime/src/device/carry.rs b/crates/metal2vulkan-runtime/src/device/carry.rs index d01c3d4f6..73ef99f9c 100644 --- a/crates/metal2vulkan-runtime/src/device/carry.rs +++ b/crates/metal2vulkan-runtime/src/device/carry.rs @@ -2,7 +2,7 @@ //! uses of guest RAM, its no-copy buffers, the buffers of the runtime's memory whose bytes no //! pointer of the program's reaches or whose pages the runtime owns, its `Private` heaps with //! the buffers placed in them, its textures made by a call the recovery makes again -//! (`texture/carry.rs`), and its compute and tile pipeline states (`pipeline/carry.rs`), each the +//! (`texture/carry.rs`), and its pipeline states (`pipeline/carry.rs`), each the //! same object on the new `VkDevice`, as Metal keeps its objects across its GPU's recovery. A fence, a depth/stencil state, a library, a function, an address //! pool, a dynamic library and a binary archive hold no Vulkan object (`fence.rs`, //! `depth_stencil.rs`, `library.rs`, `address_pool.rs`, `dynamic_library.rs`, `binary_archive`): @@ -51,13 +51,16 @@ //! lost whatever its storage mode, as its image in the lost `VkDevice`'s memory was their only //! copy, one over a carried buffer (a texture buffer of `Device::new_texture` over its texels' //! buffer too) reading the buffer's bytes; its identity, resource ID, label and purgeable state -//! kept (`Texture::carry`). A compute or tile pipeline state, after the textures: its base -//! variant's objects made there from the pipeline its creation compiled, so nothing is +//! kept (`Texture::carry`). A pipeline state, after the textures, the compute and tile states +//! first, then the drawing ones: its base variant's objects (and a drawing state's +//! large-buffer form's) made there from the pipeline its creation compiled, so nothing is //! translated again, the `VkPipeline` its creation predicted queued on the making pool with no -//! wait; the lost generation's memo of compiled pipelines taken first where both generations -//! compile alike (`PipelineMemo::carry_from`); its identity, ID, `uniqueIdentifier` and label -//! kept (`ComputePipelineState::carry`). One whose making there failed stays the lost -//! generation's, refused where bound (`RuntimeGap::RemadeAfterRecoveryFailed`). +//! wait (a drawing state's neutrals and depth stand-in copies made as at its creation); the +//! lost generation's memo of compiled pipelines taken first where both generations compile +//! alike (`PipelineMemo::carry_from`), where alone a state is made again; its identity, ID, +//! `uniqueIdentifier` and label kept (`ComputePipelineState::carry`, `GraphicsState::carry`). +//! One whose making there failed stays the lost generation's, refused where bound +//! (`RuntimeGap::RemadeAfterRecoveryFailed`). //! - **The bytes kept are the pages'.** A buffer or texture carried with its contents reads the //! pages it lies in, imported again. Vulkan makes the content of external memory imported to a //! lost device undefined (vkspec 5.2.3, "Lost Device"): read here as the hung work's writes, @@ -123,8 +126,10 @@ use crate::buffer::Buffer; use crate::event::EventShared; use crate::heap::{Heap, WeakHeap}; use crate::host_ram::RamUseCell; -use crate::pipeline::carry::StateCarried; -use crate::pipeline::{ComputePipelineState, WeakComputePipelineState}; +use crate::pipeline::carry::{compiles_alike, StateCarried}; +use crate::pipeline::{ + ComputePipelineState, GraphicsState, WeakComputePipelineState, WeakRenderPipelineState, +}; use crate::queue::Slots; use crate::resource::ObjectId; use crate::texture::carry::{Remade, TextureLeft, WeakTexture}; @@ -180,14 +185,19 @@ struct State { /// The program's compute states, tile states' kernels among them (`pipeline/carry.rs`), held /// weakly. compute_states: Vec, + /// The program's drawing states, mesh ones and twins among them (`pipeline/render/carry.rs`), + /// held weakly. + render_states: Vec, /// The size at which the next keeping drops the gone events' entries. prune_at: usize, /// The size at which the next keeping drops the gone textures' entries. textures_prune_at: usize, /// The size at which the next keeping drops the gone handles' entries. links_prune_at: usize, - /// The size at which the next keeping drops the gone states' entries. + /// The size at which the next keeping drops the gone compute states' entries. states_prune_at: usize, + /// The size at which the next keeping drops the gone drawing states' entries. + render_states_prune_at: usize, /// The recovery took the generation's objects ([`Carry::take`]): what is kept from now on, /// its maker carries. taken: bool, @@ -236,6 +246,7 @@ pub(crate) struct Taken { textures: Vec, links: Vec>, compute_states: Vec, + render_states: Vec, } impl Carry { @@ -314,6 +325,21 @@ impl Carry { state_list.taken } + /// Keep `state`, a drawing state made or carried here (`pipeline/render/carry.rs`): as + /// [`compute_state`](Self::compute_state). + pub(crate) fn render_state(&self, state: &GraphicsState) -> bool { + let mut state_list = lock(&self.state); + if state_list.render_states.len() >= state_list.render_states_prune_at { + state_list + .render_states + .retain(WeakRenderPipelineState::lives); + state_list.render_states_prune_at = + (2 * state_list.render_states.len()).max(PRUNE_FLOOR); + } + state_list.render_states.push(state.downgrade()); + state_list.taken + } + /// Keep `link`, this generation's handle of the device an object holding no Vulkan object /// answers ([`LineDevice`]): as [`event`](Self::event), its gone entries dropped as the /// registry grows. @@ -348,6 +374,9 @@ impl Carry { compute_states: (state.compute_states.iter()) .filter_map(WeakComputePipelineState::upgrade) .collect(), + render_states: (state.render_states.iter()) + .filter_map(WeakRenderPipelineState::graphics) + .collect(), } } @@ -729,14 +758,14 @@ impl Device { textures, links, compute_states, + render_states, } = shared.carry.take(shared); for link in &links { link.carry(next); } // The lost generation's compiled functions and pipelines, the next's too where both // compile alike: a creation there, or a state's remaking, translates nothing again. - let profile = |device: &Device| device.compile_device().profile_fingerprint(); - if profile(self) == profile(next) { + if compiles_alike(self, next) { next.shared() .shader_cache .memo @@ -766,6 +795,11 @@ impl Device { for state in &compute_states { carried.state(state.carry(next)); } + // Then the drawing states, mesh ones and twins among them, alike + // (`pipeline/render/carry.rs`). + for state in &render_states { + carried.state(state.carry(next)); + } carried } diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index e699d1524..b1151c754 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -2128,44 +2128,45 @@ pub enum RuntimeGap { /// bytes it may reach through a root table), and a resolve target set on a texture a draw of /// the pass read. ColorAttachmentGroups, - /// An object made before its device's recovery from the loss of its `VkDevice` that the recovery - /// did not carry to the new one (the runtime made a new `VkDevice` behind the device, announced as - /// `Degradation::DeviceRecovered`; `Device::recover_for_test` runs the same recovery). The recovery - /// carries the events, the fences, the depth/stencil states, the libraries and their functions, the - /// dynamic libraries, the binary archives and the address pools (their handle of the device alone: - /// they hold no Vulkan object), the uses of guest RAM, the no-copy buffers (made again over the - /// same pages), the `Private` buffers (their contents lost: they read zero), the buffers in the - /// runtime's own pages (their contents and `contents` pointer kept): a long host-visible buffer's - /// fresh pages, and the blocks of pages the `Shared` and `Managed` buffers lie in where the - /// device's checks found a held host-page import costs its submissions nothing and textures over - /// such pages take what they take over its own memory; and the `Private` heaps with the buffers - /// placed in them (their contents lost: they read zero), in which buffers and textures are made - /// again after it; and the textures of `Device::new_texture` (their contents lost), those over the - /// buffers it carried (reading the buffers' bytes) and the views of either; and the compute and - /// tile pipeline states (their base variants made again there from what their creations compiled; a - /// bind of one whose making there failed is refused, `RemadeAfterRecoveryFailed`). Every other - /// object's Vulkan objects are the lost `VkDevice`'s, which serves nothing more: a pooled `Shared` - /// or `Managed` buffer in memory the device allocated, whose `contents` pointer is its lost - /// memory's mapping, a detached no-copy buffer, a `Shared`, no-copy or sparse heap and the buffers - /// placed in it, a heap's texture or one over a heap's buffer, a texture over the caller's - /// `VkImage`, a sparse or shareable texture, a texture over a buffer left, a view of any of them, a - /// render pipeline state, a sampler state, an indirect command buffer, a buffer over the caller's - /// `VkBuffer` or in exportable memory, and an event made exportable. A call that meets such an - /// object with the new generation (an encoder's bind, a pipeline's making from its functions, a - /// buffer or texture placed in its heap) or that needs its own lost `VkDevice` (its placements, its - /// imports again, its event signals) is refused, where Metal's object goes on; the recovery's - /// notice counts the buffers, heaps, textures and events it left. The same object made again on the - /// device serves; a command buffer made before the recovery fails as its victim - /// (`GpuRecoveryVictim`). + /// An object made before its device's recovery from the loss of its `VkDevice` that the + /// recovery did not carry to the new one (the runtime made a new `VkDevice` behind the device, + /// announced as `Degradation::DeviceRecovered`; `Device::recover_for_test` runs the same + /// recovery). The recovery carries the events, the fences, the depth/stencil states, the + /// libraries and their functions, the dynamic libraries, the binary archives and the address + /// pools (their handle of the device alone: they hold no Vulkan object), the uses of guest RAM, + /// the no-copy buffers (made again over the same pages), the `Private` buffers (their contents + /// lost: they read zero), the buffers in the runtime's own pages (their contents and `contents` + /// pointer kept): a long host-visible buffer's fresh pages, and the blocks of pages the + /// `Shared` and `Managed` buffers lie in where the device's checks found a held host-page + /// import costs its submissions nothing and textures over such pages take what they take over + /// its own memory; and the `Private` heaps with the buffers placed in them (their contents + /// lost: they read zero), in which buffers and textures are made again after it; and the + /// textures of `Device::new_texture` (their contents lost), those over the buffers it carried + /// (reading the buffers' bytes) and the views of either; and the pipeline states (their base + /// variants made again there from what their creations compiled; a bind of one whose making + /// there failed is refused, `RemadeAfterRecoveryFailed`). Every other object's Vulkan objects + /// are the lost `VkDevice`'s, which serves nothing more: a pooled `Shared` or `Managed` buffer + /// in memory the device allocated, whose `contents` pointer is its lost memory's mapping, a + /// detached no-copy buffer, a `Shared`, no-copy or sparse heap and the buffers placed in it, a + /// heap's texture or one over a heap's buffer, a texture over the caller's `VkImage`, a sparse + /// or shareable texture, a texture over a buffer left, a view of any of them, a sampler state, + /// an indirect command buffer, a buffer over the caller's `VkBuffer` or in exportable memory, + /// and an event made exportable. A call that meets such an object with the new generation (an + /// encoder's bind, a pipeline's making from its functions, a buffer or texture placed in its + /// heap) or that needs its own lost `VkDevice` (its placements, its imports again, its event + /// signals) is refused, where Metal's object goes on; the recovery's notice counts the buffers, + /// heaps, textures and events it left. The same object made again on the device serves; a + /// command buffer made before the recovery fails as its victim (`GpuRecoveryVictim`). MadeBeforeRecovery, /// `Device::recover_for_test` on a device the consumer made (`Device::from_raw`): the runtime /// cannot make a new `VkDevice` of the consumer's, so it recovers none, and the device is /// left as it was. A real loss of such a device answers as a lost device does. AdoptedDeviceRecovery, /// A bind of a pipeline state made before its device's recovery whose making on the new - /// `VkDevice` failed there (its shader modules, layouts or sampler set refused): the state - /// stays its lost generation's, and the recovery's notice counts it. Metal's state goes on; - /// the same state made again on the device serves. + /// `VkDevice` failed there (its shader modules, layouts or sampler set refused, or the new + /// `VkDevice` compiles otherwise than the lost one did): the state stays its lost generation's, + /// and the recovery's notice counts it. Metal's state goes on; the same state made again on + /// the device serves. RemadeAfterRecoveryFailed, } diff --git a/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs b/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs index bd82cda9b..6312ebe5f 100644 --- a/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs +++ b/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs @@ -4601,8 +4601,9 @@ impl IndirectRenderCommand { pub fn set_render_pipeline_state(&self, state: &RenderPipelineState) -> Result<(), Error> { const CALL: &str = "set_render_pipeline_state"; self.icb.check_command_types(CALL)?; - if !state.device().same(self.icb.device()) { - return Err(state.device().foreign(CALL, self.icb.device())); + let device = state.bound_device()?; + if !device.same(self.icb.device()) { + return Err(device.foreign(CALL, self.icb.device())); } if self.descriptor().inherit_pipeline_state { return Err(problem( diff --git a/crates/metal2vulkan-runtime/src/pipeline/carry.rs b/crates/metal2vulkan-runtime/src/pipeline/carry.rs index f09e81c90..248a1a1ee 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/carry.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/carry.rs @@ -4,12 +4,14 @@ //! - **What is made again.** A state's program (`Program`) holds its generation's objects: its //! variants' shader modules, layouts and `VkPipeline`s, its plans, its pool makings. The //! recovery makes the state's base variant again on the new generation from the pipeline its -//! creation compiled, which the state holds, so nothing is translated again; its other -//! variants, plans and `VkPipeline`s are made there as its dispatches and draws need them, the -//! device's memo of compiled pipelines carried before (`PipelineMemo::carry_from`) sparing -//! their translations. The `VkPipeline` its creation predicted is queued on the device's -//! making pool with no wait: a dispatch or draw that binds the state before it is made holds -//! its command buffer for it, as at creation. +//! creation compiled, which the state holds, so nothing is translated again (a drawing state's +//! large-buffer form's too); its other variants, plans and `VkPipeline`s are made there as its +//! dispatches and draws need them, the device's memo of compiled pipelines carried before +//! (`PipelineMemo::carry_from`) sparing their translations. The `VkPipeline` its creation +//! predicted is queued on the device's making pool with no wait: a dispatch or draw that binds +//! the state before it is made holds its command buffer for it, as at creation. A compiled +//! pipeline is its compile profile's: where the new generation compiles otherwise +//! ([`compiles_alike`]), no state is made again there. //! - **What stays.** The state object: its handles, ID, `uniqueIdentifier`, label and sampler //! numbers. Its program on the next generation is linked after the lost one's //! ([`ProgramLink`]); its handles reach it from then on, and the work of a command buffer of @@ -17,6 +19,9 @@ //! the lost generation, and so the lost `VkDevice`, until it goes (`device/carry.rs`). //! - **A failed making** leaves the state's program the lost generation's: the recovery's notice //! counts it, and a bind of the state is refused (`RuntimeGap::RemadeAfterRecoveryFailed`). +//! +//! A compute state (and so a tile state's kernel) is carried here; a drawing state, mesh ones +//! among them, by `render/carry.rs`, its program's fields being its module's. use super::memo::Remembered; use super::{ @@ -48,6 +53,19 @@ pub(crate) fn generation_of(device: &Device) -> usize { std::ptr::from_ref(device.shared()).addr() } +/// Whether `to`, a generation a recovery made, compiles as `from`, the lost one, does: one compile +/// profile, so what one compiled the other takes (the memo's pipelines, a state's own). +pub(crate) fn compiles_alike(from: &Device, to: &Device) -> bool { + let profile = |device: &Device| device.compile_device().profile_fingerprint(); + profile(from) == profile(to) +} + +/// What a state's making again on a generation that compiles otherwise answers +/// ([`compiles_alike`]): refused, as its compiled pipeline is not that generation's. +pub(crate) fn compiled_otherwise() -> Error { + Error::NotImplemented(RuntimeGap::RemadeAfterRecoveryFailed) +} + impl OfGeneration for Program { fn generation(&self) -> usize { generation_of(&self.device) @@ -142,8 +160,12 @@ impl ComputePipelineState { impl Program { /// This program made again on `to`, the generation a recovery made (the module docs): its /// base variant's objects made there from its compiled pipeline, its predicted `VkPipeline` - /// queued on the making pool with no wait. Refused as the objects' making refuses. + /// queued on the making pool with no wait. Refused as the objects' making refuses, and where + /// `to` compiles otherwise. fn made_again(&self, to: &Device) -> Result { + if !compiles_alike(&self.device, to) { + return Err(compiled_otherwise()); + } // The variant a state carried before made of the same pipeline there, where it lives: one // variant of a pipeline on a generation, as its creations share it. let pipeline = &self.base.pipeline; diff --git a/crates/metal2vulkan-runtime/src/pipeline/predicted.rs b/crates/metal2vulkan-runtime/src/pipeline/predicted.rs index 7217c436e..27848e9ad 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/predicted.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/predicted.rs @@ -133,7 +133,9 @@ impl GraphicsState { /// constants can take (`render/residual.rs`); where the key differs from that form, hand the /// key itself to the device's pool right after, at the rank nothing waits for, for the draws /// that bind what the prediction names. A key whose pass is refused is left to its draw. - pub(crate) fn make_at_creation(&self) { + /// Not `waited`, a recovery's making again of the state (`render/carry.rs`), nothing waits + /// for the making handed to the pool (`RenderVariant::make_at_creation`). + pub(crate) fn make_at_creation(&self, waited: bool) { let Some((variant, key)) = self.predicted() else { return; }; @@ -148,7 +150,7 @@ impl GraphicsState { Err(_) => (general, Vec::new()), }, }; - RenderVariant::make_at_creation(vec![(variant, made, pass)], ahead, self); + RenderVariant::make_at_creation(vec![(variant, made, pass)], ahead, self, waited); } /// The key of the predicted first draw (the module docs), where the state alone describes diff --git a/crates/metal2vulkan-runtime/src/pipeline/render.rs b/crates/metal2vulkan-runtime/src/pipeline/render.rs index 97dcafb76..e2e118c73 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/render.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/render.rs @@ -87,6 +87,7 @@ use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex, OnceLock, Weak}; use std::time::Instant; +mod carry; mod residual; /// The general form of a key, which `tests::general_form` reads from IDs and meanings alone. @@ -145,6 +146,11 @@ impl WeakRenderPipelineState { pub(crate) fn lives(&self) -> bool { self.0.strong_count() > 0 } + + /// The drawing state, while the program holds it ([`upgrade`](Self::upgrade)'s). + pub(crate) fn graphics(&self) -> Option { + self.0.upgrade().map(GraphicsState) + } } /// The same drawing state ([`WeakRenderPipelineState::names`]'s identity). @@ -173,6 +179,9 @@ impl RenderProgram { identifier: None, _samplers: Vec::new(), program: Arc::clone(&self.0), + next: OnceLock::new(), + carried: AtomicBool::new(false), + remake_failed: AtomicBool::new(false), })))) } } @@ -188,13 +197,34 @@ pub(crate) struct StateShared { /// The sampler IDs the state numbered as it was made (`resource_ids/numbered.rs`), held /// while it lives. _samplers: Vec>, + /// Its program on the generation it was made on. program: Arc, + /// Its program on each generation its device's recoveries carried it to, in turn + /// (`pipeline/carry.rs`), which its reaches take from then on ([`StateShared::program`]). + next: OnceLock>>, + /// `next` is set: one load before a reach walks it. + carried: AtomicBool, + /// Its making on the generation a recovery made failed: a bind of it is refused + /// (`RuntimeGap::RemadeAfterRecoveryFailed`). + remake_failed: AtomicBool, } impl std::ops::Deref for StateShared { type Target = Program; fn deref(&self) -> &Program { - &self.program + self.program() + } +} + +impl StateShared { + /// The program this reach of the state takes (`pipeline/carry.rs`): the one it was made + /// with, until a recovery carried it. + #[inline] + fn program(&self) -> &Arc { + match self.carried.load(Ordering::Acquire) { + false => &self.program, + true => super::carry::reached(&self.program, &self.next), + } } } @@ -205,7 +235,7 @@ impl Drop for StateShared { let Some(id) = self.id.as_ref().filter(|id| id.id().0 != 0) else { return; }; - let program = &self.program; + let program = self.program(); program .device .shared() @@ -826,6 +856,15 @@ impl RenderPipelineState { } } + /// The device a bind of the state checks it against: its program's; refused where its + /// making on the generation a recovery made failed (`pipeline/carry.rs`). + pub(crate) fn bound_device(&self) -> Result<&Device, Error> { + match &self.0 { + Kind::Graphics(state) => state.bound_device(), + Kind::Tile(state) => state.kernel().bound_device(), + } + } + /// `supportIndirectCommandBuffers`: a drawing state's descriptor's; false for a tile /// pipeline's, whose descriptor has no such field. pub fn support_indirect_command_buffers(&self) -> bool { @@ -1266,7 +1305,7 @@ impl RenderPipelineState { /// What a drawing state runs, held without its ID; `None` for a tile pipeline's. pub(crate) fn program(&self) -> Option { match &self.0 { - Kind::Graphics(state) => Some(RenderProgram(Arc::clone(&state.0.program))), + Kind::Graphics(state) => Some(RenderProgram(Arc::clone(state.0.program()))), Kind::Tile(_) => None, } } @@ -1772,7 +1811,7 @@ impl GraphicsState { // Its first draw's predicted `VkPipeline`, made where Metal compiles (`predicted.rs`): // a state drawn in color groups draws as its twins, which predict their own. if grouped.is_none() { - state.make_at_creation(); + state.make_at_creation(true); } // The pipelines its tested draws' depth stand-in copies by, made where Metal compiles. state.make_stand_in_copies(); @@ -1804,7 +1843,7 @@ impl GraphicsState { None, )?; made.make_neutrals(); - made.make_at_creation(); + made.make_at_creation(true); made.make_stand_in_copies(); twins.push(made); } @@ -1814,6 +1853,7 @@ impl GraphicsState { .set(twins) .map_err(|_| internal("a state's color groups made twice"))?; } + state.kept(device); Ok(state) } @@ -1929,6 +1969,7 @@ impl GraphicsState { None, )?; state.make_neutrals(); + state.kept(device); // The creation's record, as the program asked for it (`warm/record.rs`). device.record_pipeline(|| crate::warm::Pipeline::Mesh(requested.clone())); Ok(state) @@ -2053,6 +2094,9 @@ impl GraphicsState { identifier, _samplers: samplers, program: Arc::new(program), + next: OnceLock::new(), + carried: AtomicBool::new(false), + remake_failed: AtomicBool::new(false), } }))) } @@ -2231,7 +2275,7 @@ impl GraphicsState { /// Whether `other` is this state (a clone of it, or the state a command runs once the /// program released it, `RenderProgram::state`), not another state alike. pub(crate) fn is(&self, other: &GraphicsState) -> bool { - Arc::ptr_eq(&self.0.program, &other.0.program) + Arc::ptr_eq(self.0.program(), other.0.program()) } /// Note that it made a visible function table (`function_table.rs`). @@ -2254,13 +2298,13 @@ impl GraphicsState { /// Its program, named without holding it: what a draw's encoder keeps the state's last /// settle under (`live_bind.rs`), which [`runs`](Self::runs) tells apart. pub(crate) fn program_name(&self) -> ProgramName { - ProgramName(Arc::downgrade(&self.0.program)) + ProgramName(Arc::downgrade(self.0.program())) } /// Whether it runs the program `name` names, as [`is`](Self::is) tells states apart, without /// touching either's counts. pub(crate) fn runs(&self, name: &ProgramName) -> bool { - std::ptr::eq(Arc::as_ptr(&self.0.program), name.0.as_ptr()) + std::ptr::eq(Arc::as_ptr(self.0.program()), name.0.as_ptr()) } /// How many of `stage`'s function's last `binary_functions` were added without the stage's @@ -3254,11 +3298,14 @@ impl RenderVariant { /// driver and settles its entries. The makings of `ahead`'s keys (a predicted key whose general /// form is among `keys`, `render/residual.rs`) are handed to the pool right after, under either /// policy, at the rank nothing waits for, and not waited for. Their specialized notices wait - /// for their first draws ([`first_use`](Self::first_use)). Each key is its variant's. + /// for their first draws ([`first_use`](Self::first_use)). Each key is its variant's. Not + /// `waited` (a recovery's making again of the state, `render/carry.rs`), those handed to the + /// pool under `PipelineWaitPolicy::Bounded` are not waited for at all. pub(crate) fn make_at_creation( keys: Vec<(Arc, GraphicsKey, RenderPassObject)>, ahead: Vec<(Arc, GraphicsKey, RenderPassObject)>, state: &GraphicsState, + waited: bool, ) { let device = &state.0.device; let joined = device.compile_device().policy().pipeline_waits == PipelineWaitPolicy::Exact; @@ -3342,7 +3389,11 @@ impl RenderVariant { drop(variant.pooled(state, (key, Arc::new(pass), ticket), (line, claimed), true)); } // Those handed to the pool, waited for a bound at most: a making still running then goes - // on for the draws that take it. + // on for the draws that take it. None where not `waited`: each goes on for its draws. + let handed = match waited { + true => handed, + false => Vec::new(), + }; let deadline = Instant::now() + device.compile_device().policy().pipeline_creation_wait; for making in &handed { if making.wait_until(deadline).is_none() { diff --git a/crates/metal2vulkan-runtime/src/pipeline/render/carry.rs b/crates/metal2vulkan-runtime/src/pipeline/render/carry.rs new file mode 100644 index 000000000..f9bc293e1 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/pipeline/render/carry.rs @@ -0,0 +1,167 @@ +//! What a device's recovery carries of a drawing state, a mesh one or a twin among them +//! (`pipeline/carry.rs`, whose chain of programs a drawing state keeps as a compute state does): +//! the same state object on the new `VkDevice`, its program made again there. +//! +//! - **What is made again.** Its base variant's objects, and its large-buffer form's where it has +//! one, from the pipelines its creation compiled, or the live variants of them the new +//! generation holds already ([`RenderVariant::made_again`]); then, as at its creation, its +//! neutrals and its depth stand-in's copies, and the `VkPipeline` of its predicted first draw +//! handed to the making pool, waited for by nothing (`GraphicsState::make_at_creation`). Its +//! other variants, plans, settles, routings and `VkPipeline`s are made there as its draws need +//! them. +//! - **What it keeps.** Its descriptors and their keys, its label and its added binary functions' +//! counts; and its twins (its color groups', its single-sample and its factor-scaling states), +//! each a state the recovery carries on its own. Its visible function tables are its lost +//! generation's, as is every object it made there. + +use super::super::carry::{ + compiled_otherwise, compiles_alike, generation_of, last, link, OfGeneration, StateCarried, +}; +use super::{ + lock, pipeline_names, AtBindViews, CompiledVariant, GraphicsState, KeptShapes, Lru, PieceHolds, + Program, ReadSlots, Remembered, RenderVariant, StateDescriptor, StateLog, TextureAccessMemo, + LAST_PIPELINES, SETTLED, VARIANTS, +}; +use crate::degradation::NoticesFor; +use crate::error::{Error, RuntimeGap}; +use crate::Device; +use std::collections::VecDeque; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; + +impl OfGeneration for Program { + fn generation(&self) -> usize { + generation_of(&self.device) + } +} + +impl GraphicsState { + /// Kept by its generation for a recovery to carry, with its color groups' twins: carried by + /// this maker where that generation's recovery took its objects before. A warm pass's state + /// is no program's. + pub(super) fn kept(&self, device: &Device) { + if crate::warm::warming() { + return; + } + let twins = self.0.color_groups.get().into_iter().flatten(); + for state in std::iter::once(self).chain(twins) { + if device.shared().carry.render_state(state) { + device.carry_late(|serving| state.carry(serving).unwrap_or(Ok(()))); + } + } + } + + /// Carry the state, made on a generation of its device that a recovery leaves, to `to`, the + /// generation that recovery made (the module docs). + pub(crate) fn carry(&self, to: &Device) -> StateCarried { + let shared = &self.0; + let (last, slot) = last(&shared.program, &shared.next); + if last.generation() == generation_of(to) { + return None; + } + let program = match last.made_again(to) { + Ok(program) => program, + Err(error) => { + shared.remake_failed.store(true, Ordering::Release); + return Some(Err(error)); + } + }; + if !link(slot, program) { + return None; + } + shared.carried.store(true, Ordering::Release); + { + // What its creation made, made on `to`: this thread reaches the program there, inside + // whatever command buffer's work it does. + let _reach = NoticesFor::of_generation(generation_of(to)); + self.make_neutrals(); + // A state drawn in color groups draws as its twins, which predict their own. + if self.0.color_groups.get().is_none() { + self.make_at_creation(false); + } + self.make_stand_in_copies(); + } + // Kept there for a later recovery to carry on. + if to.shared().carry.render_state(self) { + to.carry_late(|serving| self.carry(serving).unwrap_or(Ok(()))); + } + Some(Ok(())) + } + + /// The device a bind of the state checks it against: its program's (`Device::foreign` + /// answers a lost generation's `MadeBeforeRecovery`); refused where its making on the + /// generation a recovery made failed. + pub(crate) fn bound_device(&self) -> Result<&Device, Error> { + match self.0.remake_failed.load(Ordering::Acquire) { + false => Ok(self.device()), + true => Err(Error::NotImplemented(RuntimeGap::RemadeAfterRecoveryFailed)), + } + } +} + +impl Program { + /// This program made again on `to`, the generation a recovery made (the module docs). + /// Refused as its variants' objects' making refuses, and where `to` compiles otherwise. + fn made_again(&self, to: &Device) -> Result { + if !compiles_alike(&self.device, to) { + return Err(compiled_otherwise()); + } + let base = self.base.made_again(to, &self.descriptor)?; + let large = (self.large.as_ref()) + .map(|large| large.made_again(to, &self.descriptor)) + .transpose()?; + let indirect = self.descriptor.support_indirect_command_buffers(); + let read = ReadSlots::of(base.shared_pipeline(), indirect); + let at_bind_views = AtBindViews::new(to, &base.shared_pipeline().interface, read); + let log = StateLog::new( + self.label.as_deref(), + &self.descriptor.function_names(), + || self.descriptor.logged(), + ); + Ok(Program { + device: to.clone(), + descriptor: self.descriptor.clone(), + drawn: self.drawn.clone(), + base, + stand_in: self.stand_in, + others: Mutex::new(Lru::counted(VARIANTS)), + large, + scaling: Mutex::new(lock(&self.scaling).clone()), + added_unsupported: self.added_unsupported, + single_sample: Mutex::new(lock(&self.single_sample).clone()), + color_groups: self.color_groups.clone(), + log, + label: self.label.clone(), + texture_accesses: TextureAccessMemo::new(), + descriptor_key: self.descriptor_key.clone(), + compiled_key: self.compiled_key.clone(), + settled: Mutex::new(VecDeque::with_capacity(SETTLED)), + made_tables: AtomicBool::new(false), + last_pipelines: Mutex::new(VecDeque::with_capacity(LAST_PIPELINES)), + routed: Mutex::new(None), + pieces: PieceHolds::new(), + at_bind_views, + band_refusals: Mutex::new([None; 2]), + kept_shapes: KeptShapes::default(), + }) + } +} + +impl RenderVariant { + /// This variant made again on `to`, a generation a recovery made, of a state of + /// `descriptor`: the live variant of its pipeline there where one of its key lives (the + /// variant a state carried before made of it: one variant of a pipeline on a generation, as + /// creations share it), else one made of its pipeline, its objects made there. + fn made_again( + &self, + to: &Device, + descriptor: &StateDescriptor, + ) -> Result, Error> { + let memo = &to.shared().shader_cache.memo; + let found = (memo.render(&self.pipeline.key)) + .unwrap_or_else(|| Remembered::Compiled(Arc::clone(&self.pipeline))); + RenderVariant::of(to, self.key.clone(), CompiledVariant::found(found), || { + pipeline_names(descriptor.stages()) + }) + } +} diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 7eccd0470..24240195b 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -3038,7 +3038,7 @@ impl RenderLowering { /// the pass's color groups taken. fn set_state(&mut self, state: &RenderPipelineState) -> Result<(), Error> { const CALL: &str = "set_render_pipeline_state"; - self.core.check_device(CALL, state.device())?; + self.core.check_device(CALL, state.bound_device()?)?; let drawn = drawn_as(self.layout.samples, state)?; let state = self.grouped_as(drawn.clone())?; // Routed once here: the check and each draw read it (`routing`). diff --git a/crates/metal2vulkan-runtime/src/render/call_checks.rs b/crates/metal2vulkan-runtime/src/render/call_checks.rs index 4c8c249ce..da5708792 100644 --- a/crates/metal2vulkan-runtime/src/render/call_checks.rs +++ b/crates/metal2vulkan-runtime/src/render/call_checks.rs @@ -439,7 +439,7 @@ impl CallChecks { state: &RenderPipelineState, ) -> Result { const CALL: &str = "set_render_pipeline_state"; - check_device(device, CALL, state.device())?; + check_device(device, CALL, state.bound_device()?)?; let RenderStateKind::Graphics(graphics) = state.kind() else { return FROM_NOW; }; diff --git a/docs/API.md b/docs/API.md index 1b8ceedd8..38616be36 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3652,8 +3652,8 @@ bound. pages the `Shared` and `Managed` buffers lie in where the device's checks found a held host-page import costs its submissions nothing and textures over such pages take what they take over its own memory), `Private` heaps with the buffers placed in them, textures of `new_texture`, - textures over the buffers carried and views of them, and compute and tile pipeline states made - before it go on, the contents of a `Private` buffer or heap lost (it reads zero) and of a + textures over the buffers carried and views of them, and pipeline states made before it go on, + the contents of a `Private` buffer or heap lost (it reads zero) and of a texture of `new_texture` of any storage mode (it reads as a new one) but a texture buffer over its texels' buffer carried; the other objects made before it are refused (`MadeBeforeRecovery`), where Metal's go on; the calls during it wait for it, and a device call the loss met while it @@ -3672,7 +3672,12 @@ bound. image there. Their images on the lost `VkDevice` stay with them, and keep it, until they go. A heap's texture, one over the caller's `VkImage`, a sparse or shareable texture and one over a buffer left are refused, with their views. A `Shared` heap, whose bytes are pooled host-visible - memory the device allocated, is refused with its buffers, as a pooled buffer is. + memory the device allocated, is refused with its buffers, as a pooled buffer is. A compute, tile, + drawing or mesh pipeline state is the same state on the new `VkDevice` (its identity, ID, + `uniqueIdentifier` and label): its base variant made again there from what its creation + compiled, with no translation, and the `VkPipeline` its creation predicted queued with no wait; + a bind of one whose making there failed is refused (`RemadeAfterRecoveryFailed`). Its objects + on the lost `VkDevice` stay with it, and keep it, until it goes. - `metal2vulkan-degrade-private-properties-unknown` (precision). `PrivatePropertiesUnknown`: Apple's private device properties the device has no answer for: no document describes them and nothing the device reports maps to them. Cost: the device gives no answer for them (`PrivateAnswer::value` is diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index a07f82d4b..5186b7e57 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -267,7 +267,7 @@ Columns: | `ColorAttachmentGroups` | What a render pass the device draws in color groups does not build | every device (runtime piece not built) | `ours` | 1: `crates/metal2vulkan-runtime/src/render/color_groups.rs (gap)` | `app`: in a render pass of more color attachments than the device draws at once (five or more on a device of four), or one at an index past them: a pipeline state of other colors, a tile state, an execution of render commands, a draw reading another group's attachment | | `MadeBeforeRecovery` | An object made before its device's recovery from the loss of its `VkDevice` that the recovery did not carry to the new one (the runtime made a new... | every device (runtime piece not built) | `ours` | 3: `crates/metal2vulkan-runtime/src/device/line.rs (foreign)`, `crates/metal2vulkan-runtime/src/device/line.rs (lost_refusal)` (+1) | `app`: any object a program made before its device recovered from a lost VkDevice that the recovery does not carry (a pooled Shared or Managed buffer in memory the device allocated, a texture, a pipeline state), used after the recovery | | `AdoptedDeviceRecovery` | `Device::recover_for_test` on a device the consumer made (`Device::from_raw`) | every device (runtime piece not built) | `ours` | 1: `crates/metal2vulkan-runtime/src/device/line.rs (recover_for_test)` | `none`: the recovery test hook on a device the consumer made itself | -| `RemadeAfterRecoveryFailed` | A bind of a pipeline state made before its device's recovery whose making on the new `VkDevice` failed there (its shader modules, layouts or... | every device (runtime piece not built) | `ours` | 1: `crates/metal2vulkan-runtime/src/pipeline/carry.rs (bound_device)` | `app`: a pipeline state made before its device recovered from a lost VkDevice whose making again on the new one failed, bound after the recovery | +| `RemadeAfterRecoveryFailed` | A bind of a pipeline state made before its device's recovery whose making on the new `VkDevice` failed there (its shader modules, layouts or... | every device (runtime piece not built) | `ours` | 3: `crates/metal2vulkan-runtime/src/pipeline/carry.rs (bound_device)`, `crates/metal2vulkan-runtime/src/pipeline/carry.rs (compiled_otherwise)` (+1) | `app`: a pipeline state made before its device recovered from a lost VkDevice whose making again on the new one failed, bound after the recovery | ## 3. Apple-only calls (`Error::AppleOnly`) @@ -786,7 +786,7 @@ Each refusal's sites, with the function that builds it. - `gap::ColorAttachmentGroups`: `crates/metal2vulkan-runtime/src/render/color_groups.rs (gap)` - `gap::MadeBeforeRecovery`: `crates/metal2vulkan-runtime/src/device/line.rs (foreign)`; `crates/metal2vulkan-runtime/src/device/line.rs (lost_refusal)`; `crates/metal2vulkan-runtime/src/event.rs (carry)` - `gap::AdoptedDeviceRecovery`: `crates/metal2vulkan-runtime/src/device/line.rs (recover_for_test)` -- `gap::RemadeAfterRecoveryFailed`: `crates/metal2vulkan-runtime/src/pipeline/carry.rs (bound_device)` +- `gap::RemadeAfterRecoveryFailed`: `crates/metal2vulkan-runtime/src/pipeline/carry.rs (bound_device)`; `crates/metal2vulkan-runtime/src/pipeline/carry.rs (compiled_otherwise)`; `crates/metal2vulkan-runtime/src/pipeline/render/carry.rs (bound_device)` - `apple::ProtectedContent`: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs (commit_now)`; `crates/metal2vulkan-runtime/src/command_buffer/protection.rs (refuse_protected_state_encoder)`; `crates/metal2vulkan-runtime/src/command_buffer/protection.rs (set)` - `apple::ViewportTransformDisabled`: `crates/metal2vulkan-runtime/src/apple_only.rs (check)` - `apple::VertexAmplificationMode`: `crates/metal2vulkan-runtime/src/apple_only.rs (check)`; `crates/metal2vulkan-runtime/src/apple_only.rs (set_vertex_amplification_mode)`