diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index 4f3736c50..df0ffdacd 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -846,19 +846,23 @@ meanwhile wait for it. recovery. - The recovery carries the events, the fences, the depth/stencil states, the libraries and their functions, the dynamic libraries, the binary archives, the address pools (`AddressPool`, whose slots take buffers after it as before), the - rasterization rate maps, the + rasterization rate maps, the argument encoders, the uses of guest RAM (`HostRamUse`), the no-copy buffers, the `Private` buffers (exportable ones among them), the buffers in the runtime's own pages, the `Private` heaps and the heaps over the caller's memory with the buffers and textures placed in them, the textures of `new_texture`, the textures over the buffers it carried and the views of either, the compute, - tile, drawing and mesh pipeline states, and the sampler states to the new `VkDevice`: the same + tile, drawing and mesh pipeline states, the sampler states, the indirect command buffers and the + visible function tables 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` go once none of that device's command buffers may record. A sampler state is placed there as at its making, so an argument buffer naming its resource ID reads it, and an equal request gets it; its `VkSampler`s are made - there as its binds need them. + there as its binds need them. An indirect command buffer keeps its records where they lie in the + runtime's own pages; elsewhere they are lost and every command reads as reset (the notice counts + these); the programs of the states its commands name are made there, a released state's too. A + visible function table keeps its entries. An event keeps the value the host saw and its listeners' notifications. A buffer in the runtime's own pages keeps its bytes and its `contents` pointer: a long host-visible buffer's fresh pages, and, on a device whose checks found that a held import of host pages costs its @@ -897,9 +901,10 @@ meanwhile wait for it. `VkImage`, sparse and shareable textures, textures over buffers left and their views, buffers over the caller's `VkBuffer`, `Shared` and `Managed` buffers in exportable memory, buffers in an opaque descriptor's dedicated allocation (Vulkan defines no buffer of another device identical to - its own) and exportable events. Make it again. + its own), exportable events and the visible function tables of pipeline states left. 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. + carried and left, by kind, and the indirect command buffers and visible function tables. - The lost `VkDevice` is destroyed once the objects left on it went and, where `Device::raw` answered its handles, a later `raw` call answered the new one's: `WorkCounts::vk_devices_live` reads 2 until then. A carried object but a texture holds nothing of it once none of its diff --git a/crates/metal2vulkan-runtime/src/argument_encoder.rs b/crates/metal2vulkan-runtime/src/argument_encoder.rs index 01751bb58..e7a033e12 100644 --- a/crates/metal2vulkan-runtime/src/argument_encoder.rs +++ b/crates/metal2vulkan-runtime/src/argument_encoder.rs @@ -74,6 +74,7 @@ //! compute state's is. use super::buffer::Buffer; +use super::device::carry::LineDevice; use super::device::device_error; use super::error::{internal, invalid, nil, Error, Problem}; use super::function_table::VisibleFunctionTable; @@ -166,7 +167,10 @@ fn layout_error(call: &'static str, error: ArgumentLayoutError) -> Error { /// Cheap to clone (the layout is shared); `Send + Sync`. #[derive(Clone, Debug)] pub struct ArgumentEncoder { - device: Device, + /// Its device: a handle a recovery carries (`device/carry.rs`), as the encoder holds no + /// Vulkan object, so an encoder made before a recovery writes the arguments of what is made + /// or carried after it. + device: LineDevice, layout: Arc, /// The argument buffer and the offset of the arguments in it. target: Option<(Buffer, u64)>, @@ -323,16 +327,19 @@ pub(super) fn buffer_word(buffer: Option<(u64, u64)>, offset: u64) -> Result) -> ArgumentEncoder { ArgumentEncoder { - device: device.clone(), + device: LineDevice::new(device), layout, target: None, label: None, } } - /// `device`. - pub fn device(&self) -> &Device { - &self.device + /// `device`: a generation handle of the device, owned, as Metal's `device` answers a retained + /// device: of the generation the encoder was made on, then of each one the device's + /// recoveries carried it to. The handle is the caller's: it keeps meaning that generation + /// while held. + pub fn device(&self) -> Device { + self.device.generation().clone() } /// `label`: `None` until one is set. @@ -400,8 +407,8 @@ impl ArgumentEncoder { self.target = None; return Ok(()); }; - if !buffer.generation().same(&self.device) { - return Err(buffer.generation().foreign(call, &self.device)); + if !buffer.generation().same(self.device.generation()) { + return Err(buffer.generation().foreign(call, self.device.generation())); } if buffer.storage_mode() == StorageMode::Private || buffer.mapped_contents().is_none() { return Err(invalid(call, Problem::StorageMode)); @@ -509,10 +516,10 @@ impl ArgumentEncoder { /// Refuse an object of another device. fn check_device(&self, call: &'static str, device: &Device) -> Result<(), Error> { - if device.same(&self.device) { + if device.same(self.device.generation()) { Ok(()) } else { - Err(device.foreign(call, &self.device)) + Err(device.foreign(call, self.device.generation())) } } @@ -848,6 +855,6 @@ impl ArgumentEncoder { let problem = ArgumentEncoderProblem::NoNestedArgumentBuffer { index }; nil(CALL, Problem::ArgumentEncoder(problem)) })?; - Ok(ArgumentEncoder::new(&self.device, nested)) + Ok(ArgumentEncoder::new(self.device.generation(), nested)) } } diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index b0c56dc07..1c9933339 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -3796,6 +3796,18 @@ enum NewBufferOf { Check(Holds), } +/// What a buffer's carry carries ([`Buffer::carry`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum CarryOf { + /// A buffer of the program's, kept among the next generation's program resources. + Program, + /// A heap's own buffer (`Buffer::carry_heap_bytes`). + Heap, + /// A buffer of the runtime's own whose `contents` pointer no program holds + /// (`Buffer::carry_runtime`). + Runtime, +} + /// Where [`Device::placed_new_buffer`] lays a long host-visible buffer of the runtime's own in /// fresh pages (`fresh_pages.rs`). #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -5209,7 +5221,7 @@ impl Buffer { /// memory or one in an opaque descriptor's dedicated allocation, and one whose making there /// fails. pub(crate) fn carry(&self, to: &Device) -> Result { - self.carry_as(to, false) + self.carry_as(to, CarryOf::Program) } /// [`Buffer::carry`] of a heap's own buffer (`heap.rs`), for its heap's carry @@ -5221,11 +5233,23 @@ impl Buffer { /// `Shared` one, of pooled host-visible memory (a heap's own buffer never lies in the /// runtime's own pages), and one over the caller's memory a no-copy buffer's carry leaves. pub(crate) fn carry_heap_bytes(&self, to: &Device) -> Result { - self.carry_as(to, true) + self.carry_as(to, CarryOf::Heap) } - /// [`Buffer::carry`], of a heap's own buffer where `of_heap`. - fn carry_as(&self, to: &Device, of_heap: bool) -> Result { + /// [`Buffer::carry`] of a buffer of the runtime's own whose `contents` pointer no program + /// holds, which its owner reads again after the carry (an indirect command buffer's records, + /// a visible function table's words), kept among none of `to`'s program resources or live + /// buffers: in the runtime's own pages, the same pages there, its contents and pointer as + /// they were; in pooled host-visible memory, new memory of its class there, its contents lost + /// with the `VkDevice` (it reads zero) and its pointer that memory's mapping, where a + /// program's buffer stays the lost generation's ([`Left::Pooled`]). + pub(crate) fn carry_runtime(&self, to: &Device) -> Result { + self.carry_as(to, CarryOf::Runtime) + } + + /// [`Buffer::carry`] of a buffer of `of`. + fn carry_as(&self, to: &Device, of: CarryOf) -> Result { + let of_heap = of == CarryOf::Heap; // The generation it was carried to last: a later recovery carries it on from there. let mut last = &self.0; while let Some(next) = last.next.get() { @@ -5301,11 +5325,14 @@ impl Buffer { } mirror = Some(HostCopy::Caller(Arc::new(carried))); (raw, placement, Contents::Kept) - } else if modes.storage == StorageMode::Private { + } else if modes.storage == StorageMode::Private + || (of == CarryOf::Runtime && !placement.over_own_pages() && !placement.in_page_block()) + { // New memory, as a new buffer's: its contents went with the lost `VkDevice`. In a // plain block (`Device::place_buffer`), where any of the device's buffers may lie, as // they do until its check of exportable blocks answered (`Holds::FdBuffers`); a - // heap's where its textures can lie too, as its making placed it. + // heap's where its textures can lie too, as its making placed it. A runtime buffer of + // pooled host-visible memory too: no program holds its `contents` pointer. let shared = to.shared(); let info = shared.sharing().buffer( vk::BufferCreateInfo::default() @@ -5439,7 +5466,7 @@ impl Buffer { from.carry.lost(from, Box::new(lost)); // The program's buffer is the next generation's from now on; a heap's own buffer is its // heap's, among no program resources. - if !of_heap { + if of == CarryOf::Program { let _kept = to.visible(self.clone()); } Ok(contents) diff --git a/crates/metal2vulkan-runtime/src/degradation.rs b/crates/metal2vulkan-runtime/src/degradation.rs index 67b91404b..7cf62bcb7 100644 --- a/crates/metal2vulkan-runtime/src/degradation.rs +++ b/crates/metal2vulkan-runtime/src/degradation.rs @@ -2310,18 +2310,22 @@ degradations! { /// payload then says it stopped and was parked (`Device::is_parked`). DeviceRecovered = "device-recovered", Performance, "the events, fences, depth/stencil states, libraries, functions, dynamic libraries, \ - binary archives, address pools, rasterization rate maps, uses of guest RAM, no-copy buffers, `Private` buffers, buffers in the runtime's own pages \ + binary archives, address pools, rasterization rate maps, argument encoders, uses of \ + guest RAM, no-copy buffers, `Private` buffers, buffers in the runtime's own pages \ (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), `Private` heaps \ and heaps over the caller's memory with the buffers and textures placed in them, \ - textures of `new_texture`, textures over the buffers carried and views of them, and \ - pipeline and sampler states made before it go on, the contents of a `Private` \ + textures of `new_texture`, textures over the buffers carried and views of them, \ + pipeline and sampler states, indirect command buffers and visible function tables \ + made before it go on, the contents of a `Private` \ buffer or heap lost (it reads zero) but an exportable buffer's, re-imported over \ its own memory, which keeps whatever that memory holds, and of a texture of \ `new_texture` or of a `Private` heap of any storage mode (it reads as a new one) but \ a texture buffer over its texels' buffer carried, a heap over the caller's memory \ - and what is placed in it reading the same pages; the other objects made before it \ + and what is placed in it reading the same pages, and of an indirect command \ + buffer's records outside the runtime's own pages (every command reset); the other \ + objects made before it \ are refused (`MadeBeforeRecovery`), where Metal's go on; the calls during it wait \ for it"; /// Apple's private device properties the device has no answer for diff --git a/crates/metal2vulkan-runtime/src/device/carry.rs b/crates/metal2vulkan-runtime/src/device/carry.rs index 6f08b2c0e..3bbdda79c 100644 --- a/crates/metal2vulkan-runtime/src/device/carry.rs +++ b/crates/metal2vulkan-runtime/src/device/carry.rs @@ -7,8 +7,12 @@ //! (`sampler.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, a binary archive and a rasterization rate map hold no Vulkan object //! (`fence.rs`, `depth_stencil.rs`, `library.rs`, `address_pool.rs`, `dynamic_library.rs`, -//! `binary_archive`, `rate_map.rs`): the recovery carries their handle of the device alone -//! ([`LineDevice`]), and the device's note that it released a map of layers. +//! `binary_archive`, `rate_map.rs`), and an argument encoder (`argument_encoder.rs`): the +//! recovery carries their handle of the device alone ([`LineDevice`]), and the device's note +//! that it released a map of layers. After the pipeline states, its indirect command buffers +//! (`indirect_command_buffer/carry.rs`) and its visible function tables +//! (`function_table/carry.rs`), each the same object there, their records and words buffers of +//! the runtime's own carried as such (`Buffer::carry_runtime`). //! //! - **Kept as made.** Each event (`EventShared::new`), heap (`Device::new_heap`) and texture of //! the program's (`Texture::made`) is kept here, held weakly, by the generation it was made on; @@ -102,8 +106,9 @@ //! memory's mapping, and a buffer in an opaque descriptor's dedicated allocation, whose import //! is dedicated to a buffer "identical to the buffer associated with the imported memory" //! (`VUID-VkMemoryDedicatedAllocateInfo-buffer-01879`), which Vulkan defines no buffer of another -//! device to be (`exported_memory.rs`); and an event whose semaphore was made exportable, -//! whose importers hold the lost semaphore. The recovery's notice counts the +//! device to be (`exported_memory.rs`); an event whose semaphore was made exportable, +//! whose importers hold the lost semaphore; and a visible function table whose pipeline state +//! stays the lost generation's (`function_table/carry.rs`). The recovery's notice counts the //! buffers, heaps, textures and events it carried and left by kind //! (`Degradation::DeviceRecovered`): a heap's buffers with their heap. //! - **Each generation's work reaches its own parts** (`NoticesFor::generation`). A command buffer of the @@ -146,8 +151,12 @@ use super::{lock, Device, DeviceShared}; use crate::buffer::Buffer; use crate::event::EventShared; +use crate::function_table::carry::WeakFunctionTable; +use crate::function_table::VisibleFunctionTable; use crate::heap::{Heap, WeakHeap}; use crate::host_ram::RamUseCell; +use crate::indirect_command_buffer::carry::WeakIndirectCommandBuffer; +use crate::indirect_command_buffer::IndirectCommandBuffer; use crate::pipeline::carry::{compiles_alike, StateCarried}; use crate::pipeline::{ ComputePipelineState, GraphicsState, WeakComputePipelineState, WeakRenderPipelineState, @@ -213,6 +222,12 @@ struct State { render_states: Vec, /// The program's sampler states (`sampler.rs`), held weakly. samplers: Vec>, + /// The program's indirect command buffers (`indirect_command_buffer/carry.rs`), held weakly: + /// few, so their gone entries are dropped at each keeping. + indirect_command_buffers: Vec, + /// The program's visible function tables (`function_table/carry.rs`), held weakly: as + /// `indirect_command_buffers`. + function_tables: 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. @@ -275,6 +290,8 @@ pub(crate) struct Taken { compute_states: Vec, render_states: Vec, samplers: Vec, + indirect_command_buffers: Vec, + function_tables: Vec, } impl Carry { @@ -380,6 +397,24 @@ impl Carry { state_list.taken } + /// Keep `icb`, an indirect command buffer made or carried here + /// (`indirect_command_buffer/carry.rs`): as [`ram_use`](Self::ram_use). + pub(crate) fn indirect_command_buffer(&self, icb: &IndirectCommandBuffer) -> bool { + let mut state = lock(&self.state); + (state.indirect_command_buffers).retain(WeakIndirectCommandBuffer::lives); + state.indirect_command_buffers.push(icb.downgrade()); + state.taken + } + + /// Keep `table`, a visible function table made or carried here (`function_table/carry.rs`): + /// as [`ram_use`](Self::ram_use). + pub(crate) fn function_table(&self, table: &VisibleFunctionTable) -> bool { + let mut state = lock(&self.state); + state.function_tables.retain(WeakFunctionTable::lives); + state.function_tables.push(table.downgrade()); + state.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. @@ -420,6 +455,12 @@ impl Carry { samplers: (state.samplers.iter()) .filter_map(SamplerState::upgrade) .collect(), + indirect_command_buffers: (state.indirect_command_buffers.iter()) + .filter_map(WeakIndirectCommandBuffer::upgrade) + .collect(), + function_tables: (state.function_tables.iter()) + .filter_map(WeakFunctionTable::upgrade) + .collect(), } } @@ -654,6 +695,11 @@ pub(crate) struct Carried { states: (u64, u64), /// The sampler states carried, and those left the lost generation's: it compiles otherwise. samplers: (u64, u64), + /// The indirect command buffers carried with their records, those whose records were lost, + /// and those left the lost generation's. + indirect_command_buffers: (u64, u64, u64), + /// The visible function tables carried, and those left the lost generation's. + function_tables: (u64, u64), } impl Carried { @@ -715,6 +761,18 @@ impl Carried { self.samplers.1 ) })) + .chain((self.indirect_command_buffers.2 > 0).then(|| { + format!( + "{} indirect command buffers whose making there failed", + self.indirect_command_buffers.2 + ) + })) + .chain((self.function_tables.1 > 0).then(|| { + format!( + "{} visible function tables of states left or whose making there failed", + self.function_tables.1 + ) + })) .collect::>() .join(", "); let ram = match ram_uses { @@ -757,10 +815,23 @@ impl Carried { 0 => String::new(), carried => format!(", and {carried} sampler states"), }; + let icbs = match self.indirect_command_buffers { + (0, 0, _) => String::new(), + (kept, lost, _) => format!( + ", and {} indirect command buffers, {lost} of them whose records were lost (every \ + command reset)", + kept + lost + ), + }; + let tables = match self.function_tables.0 { + 0 => String::new(), + carried => format!(", and {carried} visible function tables with their entries"), + }; format!( "it carried {} events, {ram}{} buffers with their contents and {lost} `Private` \ buffers ({lost_bytes} bytes) whose contents were lost (they read zero){heaps}\ - {host_heaps}{textures}{states}{samplers}; left refused (`MadeBeforeRecovery`): \ + {host_heaps}{textures}{states}{samplers}{icbs}{tables}; left refused \ + (`MadeBeforeRecovery`): \ {left}", self.events, self.kept ) @@ -813,6 +884,23 @@ impl Carried { } } + /// One indirect command buffer's carry. + fn indirect_command_buffer(&mut self, carried: Result) { + match carried { + Ok(Contents::Kept) => self.indirect_command_buffers.0 += 1, + Ok(Contents::Lost(_)) => self.indirect_command_buffers.1 += 1, + Err(_) => self.indirect_command_buffers.2 += 1, + } + } + + /// One visible function table's carry. + fn function_table(&mut self, carried: Result) { + match carried { + Ok(_) => self.function_tables.0 += 1, + Err(_) => self.function_tables.1 += 1, + } + } + /// One sampler state's carry. fn sampler(&mut self, carried: Option) { match carried { @@ -855,6 +943,8 @@ impl Device { compute_states, render_states, samplers, + indirect_command_buffers, + function_tables, } = shared.carry.take(shared); for link in &links { link.carry(next); @@ -905,6 +995,13 @@ impl Device { for state in &render_states { carried.state(state.carry(next)); } + // After the states: the programs their commands run, and the tables' states, are there. + for icb in &indirect_command_buffers { + carried.indirect_command_buffer(icb.carry(next)); + } + for table in &function_tables { + carried.function_table(table.carry(next)); + } carried } @@ -1071,7 +1168,7 @@ impl Drop for CallHold<'_> { /// The device of an object that holds no Vulkan object (a fence, a depth/stencil state, a library /// and its functions, an address pool, a dynamic library, a binary archive, a rasterization rate -/// map), which a recovery carries as its handle of the device +/// map, an argument encoder), which a recovery carries as its handle of the device /// alone: a root handle, which the object's own calls and checks go through /// ([`root`](Self::root): of whatever generation serves, matched by its line), and the generation /// handle its `device` answers ([`generation`](Self::generation)): the generation it was made on, diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index 8bc9a5831..92264dd47 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -2133,8 +2133,8 @@ pub enum RuntimeGap { /// 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, the address - /// pools and the rasterization rate maps (their handle of the device alone: they hold no Vulkan - /// object), the uses of guest RAM, + /// pools, the rasterization rate maps and the argument encoders (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 @@ -2151,20 +2151,24 @@ pub enum RuntimeGap { /// 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`); and the sampler states (their - /// `VkSampler`s made there as their binds need them). Every other object's Vulkan objects + /// `VkSampler`s made there as their binds need them); and the indirect command buffers (their + /// records kept where they lie in the runtime's own pages, else lost: every command reset; the + /// programs their commands run made there) and the visible function tables (their entries + /// kept). 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`, sparse or detached no-copy heap and the buffers and /// textures placed in it, a texture over the caller's `VkImage`, a sparse - /// or shareable texture, a texture over a buffer left, a view of any of them, an indirect - /// command buffer, a buffer over the caller's `VkBuffer`, a `Shared` or `Managed` buffer in + /// or shareable texture, a texture over a buffer left, a view of any of them, a visible + /// function table of a pipeline state left, a buffer over the caller's `VkBuffer`, a `Shared` + /// or `Managed` buffer in /// exportable memory or one in an opaque descriptor's dedicated allocation (Vulkan defines no /// buffer of another device identical to its own, `VUID-VkMemoryDedicatedAllocateInfo-buffer-01879`), /// 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 + /// heaps, textures, events, indirect command buffers and visible function tables 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 diff --git a/crates/metal2vulkan-runtime/src/function_table.rs b/crates/metal2vulkan-runtime/src/function_table.rs index fa8073a62..9583ce4f0 100644 --- a/crates/metal2vulkan-runtime/src/function_table.rs +++ b/crates/metal2vulkan-runtime/src/function_table.rs @@ -70,6 +70,8 @@ use metal2vulkan::metal::RenderStages; use metal2vulkan::pipeline::{LinkedFunction, LinkedFunctions, Stage}; use std::sync::{Arc, Mutex}; +pub(crate) mod carry; + /// A table's options: `Shared`, the default CPU cache mode, tracked (Metal's 512). fn table_options() -> ResourceOptions { ResourceOptions::new( @@ -153,12 +155,12 @@ pub struct FunctionHandle { /// The pipeline state that gives a handle or makes a table, and which of its functions' linked /// functions number the handles: a compute state's kernel's (a tile state's, its tile /// function's), or a drawing state's function of one stage; or a render state's stage it has no -/// function of, which numbers none, on its device. +/// function of, which numbers none, on the state's device. #[derive(Clone)] enum Maker { Compute(ComputePipelineState), Render(GraphicsState, Stage), - Unlinked(Device), + Unlinked(RenderPipelineState), } impl Maker { @@ -178,7 +180,7 @@ impl Maker { match self { Maker::Compute(state) => state.generation(), Maker::Render(state, _) => state.device(), - Maker::Unlinked(device) => device, + Maker::Unlinked(state) => state.generation(), } } @@ -191,7 +193,7 @@ impl Maker { let _held = state.hold(); state.device().clone() } - Maker::Unlinked(device) => device.clone(), + Maker::Unlinked(state) => state.device(), } } @@ -340,7 +342,7 @@ impl Maker { state: self, words, count: size, - writes: Mutex::new(()), + writes: Mutex::new(vec![0; (length / 4) as usize]), id: IdHold::take( &device.shared().resource_ids, IdSpace::FunctionTable, @@ -356,6 +358,10 @@ impl Maker { // The ID was free, so a table the registry still names under it is gone. lock(&device.shared().function_tables) .insert(table.gpu_resource_id().0, Arc::downgrade(&table.0)); + // Kept for a recovery to carry (`function_table/carry.rs`). + if device.shared().carry.function_table(&table) { + device.carry_late(|serving| table.carry(serving)); + } if let Maker::Render(state, _) = &table.0.state { state.made_a_table(); } @@ -549,7 +555,7 @@ impl RenderPipelineState { ]; stages .contains(&stage) - .then(|| Maker::Unlinked(self.device())) + .then(|| Maker::Unlinked(self.clone())) } } @@ -675,11 +681,13 @@ pub(super) struct TableShared { /// The state (and a drawing state's stage) that made the table: the only one whose handles /// it takes. state: Maker, - /// The table's words: bound, its size, its entries. + /// The table's words: bound, its size, its entries. A buffer of the runtime's own, carried + /// with the table (`function_table/carry.rs`). words: Buffer, count: u32, - /// Held while the CPU writes a word. - writes: Mutex<()>, + /// The words as the CPU wrote them, held while it writes one: what a recovery's carry to new + /// memory writes there (`function_table/carry.rs`). + writes: Mutex>, id: IdHold, } @@ -702,9 +710,12 @@ impl Eq for VisibleFunctionTable {} impl VisibleFunctionTable { /// Write the word `value` at byte `offset` of the table's buffer. fn write(&self, offset: u64, value: u32) { - let contents = self.0.words.mapped_contents(); - let _writing = lock(&self.0.writes); - if let Some(contents) = contents { + let mut written = lock(&self.0.writes); + if let Some(word) = written.get_mut((offset / 4) as usize) { + *word = value; + } + // Under `writes`, which a recovery's carry holds: the mapping of the parts it writes. + if let Some(contents) = self.0.words.mapped_contents() { // SAFETY: the table's buffer is `Shared` and mapped for its life, and holds // `FunctionTableWords::byte_len(count)` bytes; every caller writes a word of its // header or of an entry below `count`, at a multiple of 4 of the mapping, whose start diff --git a/crates/metal2vulkan-runtime/src/function_table/carry.rs b/crates/metal2vulkan-runtime/src/function_table/carry.rs new file mode 100644 index 000000000..28fd895ac --- /dev/null +++ b/crates/metal2vulkan-runtime/src/function_table/carry.rs @@ -0,0 +1,86 @@ +//! What a device's recovery carries of the program's visible function tables +//! (`device/carry.rs`): each the same object on the new `VkDevice`, after the pipeline state that +//! made it, as Metal keeps its objects across its GPU's recovery. +//! +//! - **The words.** The table's buffer of words is a buffer of the runtime's own whose `contents` +//! pointer no program holds, carried as such (`Buffer::carry_runtime`): in the runtime's own +//! pages, the same pages there, the words as they are; in pooled host-visible memory (a +//! write-combined buffer lies in device-local memory where the device maps such), new memory +//! there, written again from the host's copy of the words (`TableShared::writes`), so its +//! entries call the functions they called. The CPU's writes of words wait for the carry. +//! - **What stays.** The object, its `gpuResourceID` (the device's line's, `device/line.rs`'s +//! `Carried`), its entries and its label; it is listed among the new generation's tables, which +//! an argument buffer of the state's commands names (`BindState::function_tables`). +//! - **Left** the lost generation's, refused where it meets the next +//! (`RuntimeGap::MadeBeforeRecovery`): a table whose state stays there (its making failed, or +//! the generations compile otherwise, `pipeline/carry.rs`), and one whose words' carry fails. + +use super::{TableShared, VisibleFunctionTable}; +use crate::device::carry::{Contents, Left}; +use crate::device::lock; +use crate::Device; +use std::sync::{Arc, Weak}; + +/// A visible function table, held weakly by its generation's registry for a recovery to carry +/// (`Carry::function_table`). +pub(crate) struct WeakFunctionTable(Weak); + +impl WeakFunctionTable { + /// The table, while the program holds it. + pub(crate) fn upgrade(&self) -> Option { + self.0.upgrade().map(VisibleFunctionTable) + } + + /// Whether the table lives. + pub(crate) fn lives(&self) -> bool { + self.0.strong_count() > 0 + } +} + +impl VisibleFunctionTable { + /// The table, held weakly. + pub(crate) fn downgrade(&self) -> WeakFunctionTable { + WeakFunctionTable(Arc::downgrade(&self.0)) + } + + /// Carry the table, made on a generation of its device that a recovery leaves, to `to`, the + /// generation that recovery made, after the state that made it (the module docs): what + /// became of its words' memory, the words as they were either way. `Kept` where it was + /// carried there already. + pub(crate) fn carry(&self, to: &Device) -> Result { + let shared = &self.0; + if shared.words.generation().same(to) { + return Ok(Contents::Kept); + } + if !shared.state.generation().same(to) { + return Err(Left::Failed); + } + let written = lock(&shared.writes); + let contents = shared.words.carry_runtime(to)?; + if let Contents::Lost(_) = contents { + let Some(mapped) = shared.words.mapped_contents() else { + return Err(Left::Failed); + }; + for (at, word) in written.iter().enumerate() { + // SAFETY: the words' new memory is host-visible and mapped, `byte_len(count)` + // bytes, four for each word of the host copy, its start aligned past 4; no + // command reads them before the next generation serves, and the CPU's writes + // wait (`writes`, held). + unsafe { + mapped + .as_ptr() + .add(at * 4) + .cast::() + .write_volatile(word.to_le()); + } + } + } + drop(written); + lock(&to.shared().function_tables).insert(self.gpu_resource_id().0, Arc::downgrade(shared)); + // Kept there for a later recovery to carry on. + if to.shared().carry.function_table(self) { + to.carry_late(|serving| self.carry(serving)); + } + Ok(contents) + } +} diff --git a/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs b/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs index 97bfbdc50..bd6d58286 100644 --- a/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs +++ b/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs @@ -63,7 +63,7 @@ //! command sets as its vertex and fragment buffers; a buffer of either mesh kind holds both mesh //! draws, as Metal's does. -use super::address::{AddressPlacement, Place, RecordsId}; +use super::address::{AddressPlacement, AddressSpace, Place, RecordsId}; use super::buffer::{Buffer, Modes}; use super::degradation::{Degradation, NoticesFor}; use super::depth_stencil::DepthStencilState; @@ -105,9 +105,12 @@ use std::borrow::{Borrow, Cow}; use std::collections::{BTreeMap, BTreeSet}; use std::num::NonZeroU64; use std::ops::Range; +use std::ptr::NonNull; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, OnceLock, Weak}; +pub(crate) mod carry; + /// The threadgroup lengths a fresh descriptor binds, as Metal's answers. const DEFAULT_THREADGROUP_LENGTHS: u32 = 31; @@ -597,7 +600,7 @@ impl Device { .take_records_id(placed) .ok_or(Error::OutOfMemory(MemoryKind::Device))?; let id = RecordsHold { - device: self.clone(), + addresses: Arc::clone(&self.shared().addresses), held, }; let identifier = UniqueIdentifier::buffer( @@ -633,16 +636,15 @@ impl Device { } _ => None, }; - let mapped = storage - .mapped_contents() - .ok_or_else(|| internal("an indirect command buffer's records are not mapped"))? - .as_ptr() - .expose_provenance(); + if storage.mapped_contents().is_none() { + return Err(internal( + "an indirect command buffer's records are not mapped", + )); + } let options = ResourceOptions::new(modes.storage, modes.cache, storage.hazard_tracking_mode()); let icb = IndirectCommandBuffer(Arc::new(IcbShared { storage, - mapped, id, identifier, descriptor: *descriptor, @@ -665,6 +667,10 @@ impl Device { keeping: AtomicBool::new(false), })); icb.initialize()?; + // Kept for a recovery to carry (`indirect_command_buffer/carry.rs`). + if self.shared().carry.indirect_command_buffer(&icb) { + self.carry_late(|serving| icb.carry(serving)); + } self.take_device_sampler(); self.make_texture_pool(); Ok(icb) @@ -1053,11 +1059,9 @@ impl RenderLayout { pub struct IndirectCommandBuffer(Arc); struct IcbShared { - /// The header and the records. + /// The header and the records: host-visible on every generation it lies on, carried with + /// the buffer (`indirect_command_buffer/carry.rs`). storage: Buffer, - /// The address of `storage`'s contents, exposed ([`bytes`](IndirectCommandBuffer::bytes)): a - /// buffer of the runtime's own memory keeps its mapping for its life. - mapped: usize, /// Its ID, held while the buffer lives. id: RecordsHold, /// Its `uniqueIdentifier` (`unique_identifier.rs`), held while the buffer lives. @@ -1132,7 +1136,6 @@ const _: fn(&IcbShared) = |icb| { fn shared(_: &T) {} let IcbShared { storage, - mapped, id, identifier, descriptor, @@ -1155,7 +1158,6 @@ const _: fn(&IcbShared) = |icb| { keeping, } = icb; shared(storage); - shared(mapped); shared(id); shared(identifier); shared(descriptor); @@ -1516,15 +1518,17 @@ pub(super) struct OverflowRuns { pub(super) clears: Vec<(u64, u64)>, } -/// An indirect command buffer's records ID, given back as the buffer goes (`address.rs`). +/// An indirect command buffer's records ID, given back as the buffer goes (`address.rs`), to +/// the address space every generation of the device's line goes on with: a carried buffer's ID +/// is the same on each (`device/line.rs`'s `Carried`), and its hold keeps no generation. struct RecordsHold { - device: Device, + addresses: Arc>, held: RecordsId, } impl Drop for RecordsHold { fn drop(&mut self) { - lock(&self.device.shared().addresses).give_records_id(self.held); + lock(&self.addresses).give_records_id(self.held); } } @@ -1552,23 +1556,33 @@ impl std::hash::Hash for IndirectCommandBuffer { } impl IndirectCommandBuffer { - /// The records' bytes: the header, then each command's record, mapped for the buffer's life. + /// The records' bytes: the header, then each command's record, as the storage's mapping + /// holds them: on the generation of the command buffer whose work reads them, else on the one + /// the storage was carried to last (`Buffer::mapped_contents`). Host-visible on each, as made + /// and as carried (`indirect_command_buffer/carry.rs`), so never null. fn bytes(&self) -> *mut u8 { - std::ptr::with_exposed_provenance_mut(self.0.mapped) + (self.0.storage.mapped_contents()).map_or(std::ptr::null_mut(), NonNull::as_ptr) } /// Write the header and reset every command. fn initialize(&self) -> Result<(), Error> { let _writing = lock(&self.0.pipelines); + self.write_header() + } + + /// [`initialize`](Self::initialize), under the caller's hold of `pipelines`. + fn write_header(&self) -> Result<(), Error> { let length = storage_length(self.0.size) as usize; - // SAFETY: the storage is host-visible and mapped for its life, `length` bytes from its - // start; nothing else reaches it before the buffer is returned. + // SAFETY: the storage is host-visible and mapped, `length` bytes from its start; the + // caller holds `pipelines`, so no other CPU write reaches it meanwhile. let bytes = unsafe { std::slice::from_raw_parts_mut(self.bytes(), length) }; CommandBuffer::initialize(bytes, self.0.size, &self.0.records, self.0.inheritance) .map_err(|_| internal("an indirect command buffer's header was refused")) } - /// The bytes of command `index`'s record (below the size), as they are now. + /// The bytes of command `index`'s record (below the size), as they are now. A host read + /// outside a command buffer's work holds the storage's parts it reads, or `pipelines`, which a + /// recovery's carry of the buffer holds ([`read_record`](Self::read_record), `carry.rs`). fn record_now(&self, index: u32) -> [u8; COMMAND_BYTES] { (self.generation().shared().counts).indirect_record_bytes_copied(COMMAND_BYTES as u64); let mut bytes = [0; COMMAND_BYTES]; @@ -1598,7 +1612,10 @@ impl IndirectCommandBuffer { read: impl FnOnce(&RecordView<'_>) -> T, ) -> Result { self.generation().shared().counts.indirect_records_read(1); - let bytes = self.record_now(index); + let bytes = { + let _parts = self.0.storage.held_parts(); + self.record_now(index) + }; let view = RecordView::new(&bytes).map_err(|_| undecodable())?; Ok(read(&view)) } diff --git a/crates/metal2vulkan-runtime/src/indirect_command_buffer/carry.rs b/crates/metal2vulkan-runtime/src/indirect_command_buffer/carry.rs new file mode 100644 index 000000000..1b343f983 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/indirect_command_buffer/carry.rs @@ -0,0 +1,118 @@ +//! What a device's recovery carries of the program's indirect command buffers +//! (`device/carry.rs`): each the same object on the new `VkDevice`, as Metal keeps its objects +//! across its GPU's recovery. +//! +//! - **The records.** Its storage, and the buffer of the slots past its records ([`Overflow`]), +//! are buffers of the runtime's own whose `contents` pointer no program holds, carried as such +//! (`Buffer::carry_runtime`): in the runtime's own pages, the same pages there, the records as +//! they are; in pooled host-visible memory, new memory there, the records lost with the +//! `VkDevice`, whose memory Vulkan makes undefined (vkspec 5.2.3, "Lost Device"), written again +//! as a new buffer's: its header, every command reset, its slots past them zero. The CPU's +//! writes of the records wait for the carry (`pipelines`), and a host read outside a command +//! buffer's work holds the storage's parts it reads. +//! - **What stays.** The object, its records ID, address, `gpuResourceID`, `uniqueIdentifier` and +//! label, which are the device's line's rather than a generation's (`device/line.rs`'s +//! `Carried`); the threadgroup lengths past the last command's, which the host keeps; what its +//! records may hold (`written_commands.rs`) and the CPU's writes counted. +//! - **What is made again.** The program each state the CPU set on a command runs: a live state's +//! its program there, which the state's carry made before (`pipeline/carry.rs`); a released +//! state's made again there from its compiled pipeline, as is each program the buffer keeps of +//! the released states its GPU-written records may name (`released_programs.rs`). One whose +//! making there fails stays the lost generation's, refused where bound +//! (`RuntimeGap::MadeBeforeRecovery`). Its kept recordings of chunks (`kept_commands.rs`), the +//! lost generation's command buffers, are let go of; its executions there record them again. +//! Where the GPU may write its records, the new generation's keepers list it +//! (`Keepers::add`), so a state released there is kept for it too. +//! - **Left** the lost generation's, refused where it meets the next: a buffer whose storage's +//! carry fails (the making of its memory there). + +use super::{CommandState, IcbShared, IndirectCommandBuffer}; +use crate::device::carry::{Contents, Left}; +use crate::device::lock; +use crate::Device; +use std::sync::atomic::Ordering; +use std::sync::{Arc, Weak}; + +/// An indirect command buffer, held weakly by its generation's registry for a recovery to carry +/// (`Carry::indirect_command_buffer`). +pub(crate) struct WeakIndirectCommandBuffer(Weak); + +impl WeakIndirectCommandBuffer { + /// The buffer, while the program holds it. + pub(crate) fn upgrade(&self) -> Option { + self.0.upgrade().map(IndirectCommandBuffer) + } + + /// Whether the buffer lives. + pub(crate) fn lives(&self) -> bool { + self.0.strong_count() > 0 + } +} + +impl IndirectCommandBuffer { + /// The buffer, held weakly. + pub(crate) fn downgrade(&self) -> WeakIndirectCommandBuffer { + WeakIndirectCommandBuffer(Arc::downgrade(&self.0)) + } + + /// Carry the buffer, made on a generation of its device that a recovery leaves, to `to`, the + /// generation that recovery made, after its pipeline states (the module docs): what became of + /// its records. `Kept` where it was carried there already. + pub(crate) fn carry(&self, to: &Device) -> Result { + let shared = &self.0; + if shared.storage.generation().same(to) { + return Ok(Contents::Kept); + } + let mut commands = lock(&shared.pipelines); + // The slots past the records first: a buffer whose storage stays the lost generation's + // stays whole there, its device that of its storage (`generation`). + if let Some(overflow) = &shared.overflow { + overflow.storage.carry_runtime(to)?; + } + let contents = shared.storage.carry_runtime(to)?; + if let Contents::Lost(_) = contents { + // Every command reset, as a new buffer's: the states the CPU set on them go. + self.write_header().map_err(|_| Left::Failed)?; + commands.states.clear(); + } + for state in commands.states.values_mut() { + *state = state.carried(to); + } + commands.kept.clear(); + commands.step_kept.clear(); + drop(commands); + lock(&shared.kept).carry(to); + if shared.keeping.load(Ordering::Acquire) { + to.shared().keepers.add(&shared.kept); + } + // Kept there for a later recovery to carry on. + if to.shared().carry.indirect_command_buffer(self) { + to.carry_late(|serving| self.carry(serving)); + } + Ok(contents) + } +} + +impl CommandState { + /// The state on `to`, the generation a recovery made: a live state's program there, a + /// released state's made again there, or the lost one where its making there fails (the + /// module docs). + fn carried(&self, to: &Device) -> CommandState { + match self { + CommandState::Compute(named, program, stamp, can) => { + let program = match named.upgrade() { + Some(state) => state.program(), + None => program.made_again(to).unwrap_or_else(|_| program.clone()), + }; + CommandState::Compute(named.clone(), program, *stamp, *can) + } + CommandState::Render(named, program, stamp, can) => { + let program = match named.upgrade().and_then(|state| state.program()) { + Some(program) => program, + None => program.made_again(to).unwrap_or_else(|_| program.clone()), + }; + CommandState::Render(named.clone(), program, *stamp, *can) + } + } + } +} diff --git a/crates/metal2vulkan-runtime/src/pipeline/carry.rs b/crates/metal2vulkan-runtime/src/pipeline/carry.rs index 3af6a87bd..451b46ed4 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/carry.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/carry.rs @@ -29,8 +29,8 @@ use super::memo::Remembered; use super::{ - piece_holds, AtBindViews, ComputePipelineState, Kernel, Lru, Program, ReadSlots, Variant, - PLANNED, VARIANTS, + piece_holds, AtBindViews, ComputePipelineState, ComputeProgram, Kernel, Lru, Program, + ReadSlots, Variant, PLANNED, VARIANTS, }; use crate::degradation::NoticesFor; use crate::device::carry::{LetGo, LostParts, PartsCalls}; @@ -253,6 +253,17 @@ impl ComputePipelineState { } } +impl ComputeProgram { + /// This program made again on `to`, the generation a recovery made ([`Program::made_again`]): + /// a released state's, which an indirect command buffer the recovery carries runs + /// (`indirect_command_buffer/carry.rs`). + pub(crate) fn made_again(&self, to: &Device) -> Result { + self.0 + .made_again(to) + .map(|program| ComputeProgram(Arc::new(program))) + } +} + 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` diff --git a/crates/metal2vulkan-runtime/src/pipeline/render/carry.rs b/crates/metal2vulkan-runtime/src/pipeline/render/carry.rs index 91c4045af..f71419d5c 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/render/carry.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/render/carry.rs @@ -19,8 +19,8 @@ use super::super::carry::{ }; use super::{ lock, pipeline_names, AtBindViews, CompiledVariant, GraphicsState, KeptShapes, Lru, PieceHolds, - Program, ReadSlots, Remembered, RenderVariant, StateDescriptor, StateLog, TextureAccessMemo, - LAST_PIPELINES, SETTLED, VARIANTS, + Program, ReadSlots, Remembered, RenderProgram, RenderVariant, StateDescriptor, StateLog, + TextureAccessMemo, LAST_PIPELINES, SETTLED, VARIANTS, }; use crate::degradation::NoticesFor; use crate::error::{Error, RuntimeGap}; @@ -103,6 +103,17 @@ impl GraphicsState { } } +impl RenderProgram { + /// This program made again on `to`, the generation a recovery made ([`Program::made_again`]): + /// a released state's, which an indirect command buffer the recovery carries runs + /// (`indirect_command_buffer/carry.rs`). + pub(crate) fn made_again(&self, to: &Device) -> Result { + self.0 + .made_again(to) + .map(|program| RenderProgram(Arc::new(program))) + } +} + 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. diff --git a/crates/metal2vulkan-runtime/src/released_programs.rs b/crates/metal2vulkan-runtime/src/released_programs.rs index 7314be75d..bfd61d6b8 100644 --- a/crates/metal2vulkan-runtime/src/released_programs.rs +++ b/crates/metal2vulkan-runtime/src/released_programs.rs @@ -32,6 +32,7 @@ use super::device::lock; use super::pipeline::{ComputePipelineState, ComputeProgram, RenderPipelineState, RenderProgram}; use super::resource_ids::PIPELINE_HOLDERS; +use super::Device; use std::collections::{BTreeMap, VecDeque}; use std::sync::{Arc, Mutex, Weak}; @@ -58,6 +59,20 @@ impl KeptProgram { KeptProgram::Compute(_) => None, } } + + /// The program made again on `to`, the generation a recovery made, for a buffer it carries + /// (`indirect_command_buffer/carry.rs`); this one where its making there fails, refused where + /// bound (`RuntimeGap::MadeBeforeRecovery`). + fn made_again(&self, to: &Device) -> KeptProgram { + match self { + KeptProgram::Compute(program) => { + KeptProgram::Compute(program.made_again(to).unwrap_or_else(|_| program.clone())) + } + KeptProgram::Render(program) => { + KeptProgram::Render(program.made_again(to).unwrap_or_else(|_| program.clone())) + } + } + } } /// The programs a buffer keeps: by pipeline state ID, each with its state's hold serial @@ -101,6 +116,16 @@ impl KeptPrograms { self.0.keys().copied() } + /// Each program it keeps made again on `to`, the generation a recovery made, for the buffer + /// it carries ([`KeptProgram::made_again`]). + pub(super) fn carry(&mut self, to: &Device) { + for kept in self.0.values_mut() { + for (_, program) in kept.iter_mut() { + *program = program.made_again(to); + } + } + } + /// How many programs it keeps. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(super) fn count(&self) -> usize { diff --git a/crates/metal2vulkan-runtime/src/tests/device_recovery_every_kind.rs b/crates/metal2vulkan-runtime/src/tests/device_recovery_every_kind.rs new file mode 100644 index 000000000..e7330f4e7 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/device_recovery_every_kind.rs @@ -0,0 +1,388 @@ +//! Every kind of object a program makes and keeps, made before a device's recovery, serves after +//! it, as Metal's objects go on (`device/carry.rs`): each is used on the next generation (encoded +//! with, bound, reset, written) by command buffers that complete, and the lost generation goes +//! while they all live. The kinds: a command queue, a `Private` buffer, a heap and a buffer +//! placed in it, a texture, an event, a shared event, a fence, a sampler state, a depth/stencil +//! state, a library and a function, a compute and a drawing pipeline state, an address pool, a +//! rasterization rate map, a binary archive, a dynamic library, an indirect command buffer of +//! dispatches and one of draws, an argument encoder and a visible function table. +//! +//! A device test: compiled only under the validation crate's GPU safety cfgs, on the kind of device +//! the cfg selects (docs/VALIDATION.md). No GPU fault: the loss is marked (`Device::recover_for_test`). +//! The functions are the owned fixtures `examples/runtime_examples.ll`, `engine/tob_renders.ll`, +//! `engine/visible_table_caller.ll` and `engine/visible_table_functions.ll` (`llvm-as`). + +use super::device_recovery::{heard_device, outcome, recovery_notices, Heard, Scratch}; +use super::device_recovery_carry::{fill, live_vk_devices, read, BYTES}; +use super::device_recovery_live_table::{ + dispatched, encode_command, execute, indirect_state, WORDS, +}; +use super::device_recovery_pipelines::{draw, drawing_library, drawing_state, drawn}; +use super::device_recovery_states::dynamic_library; +use super::encoder_holds::library; +use crate::{ + AddressPlacement, BinaryArchiveDescriptor, CommandBufferStatus, CommandQueue, + ComputePipelineState, Device, EventRef, HeapDescriptor, HeapType, + IndirectCommandBufferDescriptor, LoadAction, PipelineOptions, RenderPassDescriptor, + ResourceOptions, Size, StoreAction, TextureDescriptor, VisibleFunctionTable, + VisibleFunctionTableDescriptor, +}; +use metal2vulkan::bind::{ + ArgumentDescriptor, RateMapDescriptor, RateMapLayerDescriptor, SamplerDescriptor, +}; +use metal2vulkan::metal::state::DepthStencilDescriptor; +use metal2vulkan::metal::{ + CompareFunction, DataType, IndirectCommandType, PixelFormat, TextureUsage, +}; +use metal2vulkan::pipeline::{ComputePipelineDescriptor, LinkedFunctions, StageSource}; + +/// The threads a table's dispatch runs, each calling entry `tid % 5` of its table. +const THREADS: u32 = 40; + +/// `visible_table_dispatch` linking `table_add`, `table_mul`, `table_sub` and `table_half`, and +/// a table of 5 entries of it calling `table_add` at 0 and `table_mul` at 1. +fn table_state(device: &Device) -> (ComputePipelineState, VisibleFunctionTable) { + let caller = library(device, "engine/visible_table_caller.ll"); + let functions = library(device, "engine/visible_table_functions.ll"); + let linked = ["table_add", "table_mul", "table_sub", "table_half"] + .iter() + .fold(LinkedFunctions::new(), |linked, name| { + linked.with_function( + functions + .new_function_with_name(name) + .unwrap() + .linked_function(), + ) + }); + let kernel = caller + .new_function_with_name("visible_table_dispatch") + .unwrap(); + let state = device + .new_compute_pipeline_state( + &ComputePipelineDescriptor::new(StageSource::Function( + kernel.function_descriptor().with_linked(linked), + )), + &PipelineOptions::default(), + ) + .unwrap(); + let table = state + .new_visible_function_table(&VisibleFunctionTableDescriptor::new(5)) + .unwrap(); + let handle = |name: &str| { + let function = functions.new_function_with_name(name).unwrap(); + state.function_handle(&function).unwrap().unwrap() + }; + let (add, mul) = (handle("table_add"), handle("table_mul")); + table.set_functions(&[Some(&add), Some(&mul)], 0).unwrap(); + (state, table) +} + +/// `state` over [`THREADS`] threads with `table` at buffer 1, as `queue`'s GPU work runs it, +/// completed: the words it wrote at buffer 0. +fn table_words( + device: &Device, + queue: &CommandQueue, + state: &ComputePipelineState, + table: &VisibleFunctionTable, +) -> Vec { + let out = device.new_buffer(BYTES, ResourceOptions::shared()).unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(state).unwrap(); + encoder.set_buffer(Some(&out), 0, 0).unwrap(); + encoder + .set_visible_function_tables(&[Some(table)], 1) + .unwrap(); + encoder + .dispatch_threads( + Size::new(THREADS.into(), 1, 1), + Size::new(THREADS.into(), 1, 1), + ) + .unwrap(); + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + assert_eq!( + outcome(&command_buffer), + (CommandBufferStatus::Completed, None) + ); + let contents = out.contents().unwrap(); + // SAFETY: a `Shared` buffer of `BYTES` bytes, which no work in flight writes. + let bytes = unsafe { std::slice::from_raw_parts(contents.as_ptr(), BYTES as usize) }; + (bytes.as_chunks::<4>().0.iter()) + .take(THREADS as usize) + .map(|word| u32::from_le_bytes(*word)) + .collect() +} + +/// What [`table_words`] reads back from a table calling `table_add` at 0 and `table_mul` at 1, +/// and `table_sub` at 3 where `sub`; its other entries null (`0xfffffffd`). +fn called(sub: bool) -> Vec { + (0..THREADS) + .map(|tid| match tid % 5 { + 0 => tid + 3, + 1 => tid * 3, + 3 if sub => tid.wrapping_sub(3), + _ => 0xffff_fffd, + }) + .collect() +} + +/// One of each kind of object a program makes and keeps, made before a recovery (the module +/// docs), serves after it: each is used by the next generation's command buffers, which +/// complete, and does what it did before. The indirect command buffer of dispatches runs its +/// command as encoded before where the recovery kept its records (they lie in the runtime's own +/// pages), else runs nothing, every command reset as its notice says; either way a blit's reset +/// of its commands and of the draws' buffer's, then a command encoded again, run. The visible +/// function table's entries call the functions they called, and one set after. The argument +/// encoder writes a buffer made before into an argument buffer made after. The recovery's notice +/// counts the indirect command buffers and the table; the lost `VkDevice` goes. +#[test] +fn every_kind_of_object_made_before_a_recovery_serves_after_it() { + let scratch = Scratch::new(); + let heard = Heard::default(); + let device = heard_device(&scratch.0, &heard); + let queue = device.new_command_queue().unwrap(); + let private = || { + device + .new_buffer(BYTES, ResourceOptions::private()) + .unwrap() + }; + let buffer = private(); + fill(&queue, &buffer, 7); + let heap = device + .new_heap(&HeapDescriptor::new( + HeapType::Automatic, + 1 << 20, + ResourceOptions::private(), + )) + .unwrap(); + let placed = heap.new_buffer(BYTES, ResourceOptions::private()).unwrap(); + let mut target = TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, 64, 64, false); + target.usage = TextureUsage::RENDER_TARGET; + target.resource_options = ResourceOptions::private(); + let texture = device.new_texture(&target).unwrap(); + let event = device.new_event().unwrap(); + let shared_event = device.new_shared_event().unwrap(); + let fence = device.new_fence(); + let sampler = device.new_sampler_state(&SamplerDescriptor::new()).unwrap(); + let mut depth = DepthStencilDescriptor::default(); + depth.depth_compare_function = CompareFunction::LessEqual; + let depth_stencil = device.new_depth_stencil_state(&depth).unwrap(); + let examples = library(&device, "examples/runtime_examples.ll"); + let function = examples.new_function_with_name("scale_and_offset").unwrap(); + let compute = indirect_state(&device); + let drawing = drawing_state(&device, &drawing_library(&device), None, "drawn"); + let pool = device + .reserve_address_pool(AddressPlacement::Any, 2 * BYTES) + .unwrap(); + let mut rates = RateMapDescriptor::new([64, 64]); + rates.layers = vec![RateMapLayerDescriptor::new(vec![1.0, 0.5], vec![1.0, 0.5])]; + let map = device.new_rasterization_rate_map(&rates).unwrap(); + let described = + ComputePipelineDescriptor::new(StageSource::Function(function.function_descriptor())); + let archive = device + .new_binary_archive(&BinaryArchiveDescriptor::new(None)) + .unwrap(); + archive.add_compute_pipeline_functions(&described).unwrap(); + let dynamic = dynamic_library(&device, &scratch.0); + let mut dispatches = IndirectCommandBufferDescriptor::new(); + dispatches.command_types = IndirectCommandType::CONCURRENT_DISPATCH_THREADS; + dispatches.max_kernel_buffer_bind_count = 3; + let icb = device + .new_indirect_command_buffer(&dispatches, 1, ResourceOptions::shared()) + .unwrap(); + let (input, output, scale) = (private(), private(), private()); + let buffers = [&input, &output, &scale]; + encode_command(&icb, &compute, buffers); + assert_eq!(execute(&device, &queue, &icb, buffers), dispatched()); + let mut draws = IndirectCommandBufferDescriptor::new(); + draws.command_types = IndirectCommandType::DRAW; + draws.max_vertex_buffer_bind_count = 1; + let draw_icb = device + .new_indirect_command_buffer(&draws, 2, ResourceOptions::shared()) + .unwrap(); + let mut arguments = device + .new_argument_encoder_with_arguments(&[ArgumentDescriptor::new(DataType::Pointer, 0)]) + .unwrap(); + let (table_state, table) = table_state(&device); + assert_eq!( + table_words(&device, &queue, &table_state, &table), + called(false) + ); + + let from = heard.lock().unwrap().len(); + device.recover_for_test().unwrap(); + let said = recovery_notices(&heard, from, "the device"); + assert_eq!(said.len(), 1, "{said:?}"); + assert!( + said[0].contains(", and 2 indirect command buffers, ") + && said[0].contains(", and 1 visible function tables with their entries"), + "{said:?}" + ); + + // The buffer (its contents lost: it reads zero), the heap's buffer and one made in the heap + // after, the address pool's slot, through the queue made before. + assert_eq!( + read(&device, &queue, &buffer).unwrap(), + vec![0; BYTES as usize] + ); + let in_heap = heap.new_buffer(BYTES, ResourceOptions::private()).unwrap(); + for (byte, buffer) in [(3, &placed), (4, &in_heap)] { + fill(&queue, buffer, byte); + assert_eq!( + read(&device, &queue, buffer).unwrap(), + vec![byte; BYTES as usize] + ); + } + let slot = device + .new_buffer_with_descriptor( + crate::BufferDescriptor::new( + BYTES, + ResourceOptions::private(), + crate::BufferContents::Zero, + ) + .with_pool_slot(&pool, 0), + ) + .unwrap(); + assert_eq!(slot.gpu_address(), pool.gpu_address()); + + // The compute state made before, and one made of the function made before, the sampler + // state bound, the fence updated and waited for, the events signalled. + let made_after = device + .new_compute_pipeline_state(&described, &PipelineOptions::default()) + .unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + for state in [&compute, &made_after] { + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(state).unwrap(); + encoder.set_buffer(Some(&input), 0, 0).unwrap(); + encoder.set_buffer(Some(&output), 0, 1).unwrap(); + encoder.set_buffer(Some(&scale), 0, 2).unwrap(); + encoder.set_sampler_state(Some(&sampler), 0).unwrap(); + encoder + .dispatch_threads(Size::new(WORDS, 1, 1), Size::new(32, 1, 1)) + .unwrap(); + encoder.update_fence(&fence).unwrap(); + encoder.end_encoding().unwrap(); + } + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.wait_for_fence(&fence).unwrap(); + blit.end_encoding().unwrap(); + (command_buffer.encode_signal_event(EventRef::from(&event), 1)).unwrap(); + (command_buffer.encode_signal_event(EventRef::from(&shared_event), 2)).unwrap(); + command_buffer.commit().unwrap(); + assert_eq!( + outcome(&command_buffer), + (CommandBufferStatus::Completed, None) + ); + assert!(shared_event.wait_until_signaled_value(2, super::device_recovery::WAIT)); + + // The drawing state; the depth/stencil state in a pass over the texture made before; a pass + // over the rate map, its target of the map's physical size. + assert_eq!(draw(&device, &queue, &drawing).unwrap(), drawn()); + let mut depth_target = TextureDescriptor::texture_2d(PixelFormat::Depth32Float, 64, 64, false); + depth_target.usage = TextureUsage::RENDER_TARGET; + depth_target.resource_options = ResourceOptions::private(); + let depth_target = device.new_texture(&depth_target).unwrap(); + let size = map.physical_size_for_layer(0); + let mut mapped = + TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, size.width, size.height, false); + mapped.usage = TextureUsage::RENDER_TARGET; + mapped.resource_options = ResourceOptions::private(); + let mapped = device.new_texture(&mapped).unwrap(); + for over_map in [false, true] { + let mut pass = RenderPassDescriptor::new(); + let attachment = &mut pass.color_attachments[0]; + attachment.texture = Some(match over_map { + false => texture.clone(), + true => mapped.clone(), + }); + attachment.load_action = LoadAction::Clear; + attachment.store_action = StoreAction::Store; + if over_map { + pass.rasterization_rate_map = Some(map.clone()); + } else { + pass.depth_attachment.texture = Some(depth_target.clone()); + pass.depth_attachment.load_action = LoadAction::Clear; + pass.depth_attachment.store_action = StoreAction::DontCare; + } + let command_buffer = queue.command_buffer().unwrap(); + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + if !over_map { + encoder.set_depth_stencil_state(&depth_stencil).unwrap(); + } + encoder.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + assert_eq!( + outcome(&command_buffer), + (CommandBufferStatus::Completed, None) + ); + } + + // The archive takes an add, a creation listing it makes its state; the dynamic library + // keeps its install name. + archive.add_compute_pipeline_functions(&described).unwrap(); + let options = PipelineOptions { + binary_archives: vec![archive.clone()], + ..PipelineOptions::default() + }; + device + .new_compute_pipeline_state(&described, &options) + .unwrap(); + assert!(dynamic.install_name().ends_with("libdyl.metallib")); + + // The indirect command buffers: the command as the recovery left it, then each buffer's + // commands reset by a blit, and the command encoded again, run. + let command = icb.indirect_compute_command_at(0).unwrap(); + let kept = command.command_type().unwrap() == IndirectCommandType::CONCURRENT_DISPATCH_THREADS; + let ran = execute(&device, &queue, &icb, buffers); + match kept { + true => assert_eq!(ran, dispatched(), "the command kept"), + false => assert!( + ran.iter().all(|word| word.to_bits() == u32::MAX), + "a reset command ran: {ran:?}" + ), + } + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.reset_commands_in_buffer(&icb, 0..1).unwrap(); + blit.reset_commands_in_buffer(&draw_icb, 0..2).unwrap(); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + assert_eq!( + outcome(&command_buffer), + (CommandBufferStatus::Completed, None) + ); + assert!(icb.device().generation_serves()); + encode_command(&icb, &compute, buffers); + assert_eq!(execute(&device, &queue, &icb, buffers), dispatched()); + + // The argument encoder writes the buffer made before into an argument buffer made after. + let argument_buffer = device.new_buffer(BYTES, ResourceOptions::shared()).unwrap(); + arguments + .set_argument_buffer(Some(&argument_buffer), 0) + .unwrap(); + arguments.set_buffer(Some(&buffer), 0, 0).unwrap(); + let contents = argument_buffer.contents().unwrap(); + // SAFETY: a `Shared` buffer of `BYTES` bytes, which no work reads or writes. + let word = unsafe { contents.as_ptr().cast::().read_unaligned() }; + assert_eq!(word, buffer.gpu_address().0); + assert!(arguments.device().generation_serves()); + + // The table calls what it called, and an entry set after. + assert_eq!( + table_words(&device, &queue, &table_state, &table), + called(false) + ); + let functions = library(&device, "engine/visible_table_functions.ll"); + let sub = functions.new_function_with_name("table_sub").unwrap(); + let sub = table_state.function_handle(&sub).unwrap().unwrap(); + table.set_function(Some(&sub), 3).unwrap(); + assert_eq!( + table_words(&device, &queue, &table_state, &table), + called(true) + ); + + // Nothing holds the lost `VkDevice`, while every object lives (to the end of the test). + assert_eq!(live_vk_devices(&device, 1), 1, "{said:?}"); +} diff --git a/crates/metal2vulkan-runtime/src/tests/device_recovery_live_table.rs b/crates/metal2vulkan-runtime/src/tests/device_recovery_live_table.rs index 3c8606fc6..f76939bd9 100644 --- a/crates/metal2vulkan-runtime/src/tests/device_recovery_live_table.rs +++ b/crates/metal2vulkan-runtime/src/tests/device_recovery_live_table.rs @@ -18,7 +18,7 @@ use metal2vulkan::metal::{IndirectCommandType, ResourceUsage}; use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource}; /// The floats an indirect command's dispatch writes, `i` each. -const WORDS: u64 = 64; +pub(super) const WORDS: u64 = 64; /// `scale_and_offset` of `device`'s example library, for indirect command buffers. pub(super) fn indirect_state(device: &Device) -> ComputePipelineState { diff --git a/crates/metal2vulkan-runtime/src/tests/device_recovery_pipelines.rs b/crates/metal2vulkan-runtime/src/tests/device_recovery_pipelines.rs index aa215b416..1269d5370 100644 --- a/crates/metal2vulkan-runtime/src/tests/device_recovery_pipelines.rs +++ b/crates/metal2vulkan-runtime/src/tests/device_recovery_pipelines.rs @@ -167,7 +167,7 @@ fn a_recovery_carries_a_compute_state() { /// A drawing state of `tob_rect` and `tob_solid` of `library` into `RGBA8Unorm`, blending by /// `factors` (source, destination) where given, labelled `label`. -fn drawing_state( +pub(super) fn drawing_state( device: &Device, library: &Library, factors: Option<(BlendFactor, BlendFactor)>, @@ -195,13 +195,13 @@ fn drawing_state( } /// The library of `tob_rect` and `tob_solid`, on `device`. -fn drawing_library(device: &Device) -> Library { +pub(super) fn drawing_library(device: &Device) -> Library { library(device, "engine/tob_renders.ll") } /// `state` drawing a rectangle over a [`SIDE`]-square target in [`COLOR`], as `queue`'s GPU work /// runs it, completed: the target's texels' words. Refused as the encoding refuses the state. -fn draw( +pub(super) fn draw( device: &Device, queue: &CommandQueue, state: &RenderPipelineState, @@ -241,7 +241,7 @@ fn draw( } /// What [`draw`] reads back. -fn drawn() -> Vec { +pub(super) fn drawn() -> Vec { vec![PACKED; (SIDE * SIDE) as usize] } diff --git a/crates/metal2vulkan-runtime/src/tests/device_recovery_states.rs b/crates/metal2vulkan-runtime/src/tests/device_recovery_states.rs index ea3559757..46345af2c 100644 --- a/crates/metal2vulkan-runtime/src/tests/device_recovery_states.rs +++ b/crates/metal2vulkan-runtime/src/tests/device_recovery_states.rs @@ -287,7 +287,7 @@ define float @_Z9dyl_scalef(float %x) { "; /// A dynamic library exporting one function, made on `device`, its install name a file in `dir`. -fn dynamic_library(device: &Device, dir: &Path) -> DynamicLibrary { +pub(super) fn dynamic_library(device: &Device, dir: &Path) -> DynamicLibrary { let module = llvm_assemble_text(DYLIB_MODULE).unwrap(); let name = dir.join("libdyl.metallib").to_string_lossy().into_owned(); let function = MtlbFunction { diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 9b58e9dd2..05115a3d9 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -142,6 +142,8 @@ mod device_memory_overflow; mod device_recovery; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod device_recovery_carry; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod device_recovery_every_kind; #[cfg(all(unix, any(m2v_gpu, m2v_cpu_icd)))] mod device_recovery_exportable; #[cfg(any(m2v_gpu, m2v_cpu_icd))] diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 01b9ce27a..bf688bbd3 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -8181,7 +8181,7 @@ method metal2vulkan-runtime::AppleOnlyCall::check pub fn check(self) -> Result<( method metal2vulkan-runtime::AppleOnlyCall::selector pub fn selector(self) -> &'static str method metal2vulkan-runtime::ArgumentEncoder::alignment pub fn alignment(&self) -> u64 method metal2vulkan-runtime::ArgumentEncoder::constant_data pub fn constant_data(&self, index: u32) -> Result, Error> -method metal2vulkan-runtime::ArgumentEncoder::device pub fn device(&self) -> &Device +method metal2vulkan-runtime::ArgumentEncoder::device pub fn device(&self) -> Device method metal2vulkan-runtime::ArgumentEncoder::encoded_length pub fn encoded_length(&self) -> u64 method metal2vulkan-runtime::ArgumentEncoder::label pub fn label(&self) -> Option<&str> method metal2vulkan-runtime::ArgumentEncoder::layout pub fn layout(&self) -> &ArgumentBufferLayout diff --git a/docs/API.md b/docs/API.md index cf4ad312d..d4d454dc8 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3721,18 +3721,20 @@ bound. which of the two, and was parked: never destroyed, its queues never waited for (`Device::is_parked`). `Device::recover_for_test` runs the same recovery with no GPU fault. Cost: the events, fences, depth/stencil states, libraries, - functions, dynamic libraries, binary archives, address pools, rasterization rate maps, uses of - guest RAM, no-copy + functions, dynamic libraries, binary archives, address pools, rasterization rate maps, argument + encoders, uses of guest RAM, no-copy buffers, `Private` buffers, buffers in the runtime's own pages (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), `Private` heaps and heaps over the caller's memory with the buffers and textures placed in them, textures of `new_texture`, textures over the buffers carried and views of them, - and pipeline and sampler states made before it go on, the contents of a `Private` buffer or heap + pipeline and sampler states, indirect command buffers and visible function tables made before it + go on, the contents of a `Private` buffer or heap lost (it reads zero) but an exportable buffer's, re-imported over its own memory, which keeps whatever that memory holds, and of a texture of `new_texture` or of a `Private` heap of any storage mode (it reads as a new one) but a texture buffer over its texels' buffer carried, a - heap over the caller's memory and what is placed in it reading the same pages; the other objects + heap over the caller's memory and what is placed in it reading the same pages, and of an indirect + command buffer's records outside the runtime's own pages (every command reset); 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 ran runs again after it. A no-copy buffer is made again over