diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 0317f4c80..2e741d3a3 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -3007,6 +3007,23 @@ impl Device { self.zeroed_buffer_of(call, length, (modes, class), of, (placement.into(), None)) } + /// A `Shared` buffer of the runtime's own of `length` bytes, all zero, at `placement`, for an + /// indirect command buffer's records or the slots past them: in fresh pages of its own at any + /// length, whatever a held import costs, where the device takes them, so that a recovery's + /// carry keeps its pages and its bytes (`FreshPages::Always`); else where + /// [`zeroed_buffer`](Device::zeroed_buffer) lays such a buffer. Refused as that is. + pub(super) fn records_buffer( + &self, + call: &'static str, + length: u64, + modes: Modes, + placement: impl Into, + ) -> Result { + let of = NewBufferOf::Runtime(FreshPages::Always); + let placed = (placement.into(), None); + self.zeroed_buffer_of(call, length, (modes, MemoryClass::Shared), of, placed) + } + /// [`zeroed_buffer`](Device::zeroed_buffer) for `of`, its byte `aligned` (where given) on a /// multiple of 256 bytes of its memory ([`Device::placed_new_buffer`]). fn zeroed_buffer_of( @@ -3227,20 +3244,27 @@ impl Device { // host-visible one of the runtime's own lies in fresh pages where the device takes them // and its check found a held import adds nothing to its submissions (`fresh_pages.rs`). // The in-place check's buffer of pooled memory lies in neither. + // An indirect command buffer's records lie in them at any length, whatever a held import + // costs (`FreshPages::Always`). + let takes = match fresh { + FreshPages::Always => fresh_pages::class_takes_fresh_pages(class), + FreshPages::WherePaid | FreshPages::Wherever => { + fresh_pages::takes_fresh_pages(size, class) + } + }; let wants_fresh = !of_heap && !plain && lead == 0 - && fresh_pages::takes_fresh_pages(size, class) + && takes && (shared.host_import.as_ref()).is_ok_and(|importer| importer.pointers().is_some()) - && (fresh == FreshPages::Wherever || self.fresh_pages_pay_now()); - let making = (!of_heap && !plain && lead == 0 && fresh == FreshPages::WherePaid).then_some( - BufferMaking { - size, - class, - fresh_pages: wants_fresh, - holds, - }, - ); + && (fresh != FreshPages::WherePaid || self.fresh_pages_pay_now()); + let parks = matches!(fresh, FreshPages::WherePaid | FreshPages::Always); + let making = (!of_heap && !plain && lead == 0 && parks).then_some(BufferMaking { + size, + class, + fresh_pages: wants_fresh, + holds, + }); let mut taken = making.and_then(|making| self.recycled_buffer(&making)); let fresh = match (&taken, wants_fresh) { (None, true) => self.fresh_page_buffer(size, class)?, @@ -3934,6 +3958,10 @@ enum FreshPages { /// which lies where a rebind's copy under an image in place lies whatever that cost /// (`buffer_descriptor.rs`'s `copied_pages`), and whose import lives only for its round. Wherever, + /// Wherever the device takes them, at any length: an indirect command buffer's records and + /// slots past them, which a recovery's carry keeps only in the runtime's own pages + /// (`indirect_command_buffer/carry.rs`, `fresh_pages.rs`). + Always, } /// What a new buffer's bytes hold as [`Device::placed_new_buffer`] makes it. diff --git a/crates/metal2vulkan-runtime/src/fresh_pages.rs b/crates/metal2vulkan-runtime/src/fresh_pages.rs index e3546f52e..e14a69585 100644 --- a/crates/metal2vulkan-runtime/src/fresh_pages.rs +++ b/crates/metal2vulkan-runtime/src/fresh_pages.rs @@ -36,6 +36,13 @@ //! pages already touched (about 4.5 us per MiB), which is cheaper than an import of fresh ones //! (16 us per MiB). An import also costs 17 to 43 us whatever its size, against a pooled //! placement's none. +//! - **An indirect command buffer's records** (and its slots past them) lie in fresh pages of +//! their own at any length, whatever a held import costs, where the device imports host +//! pointers and the class's best type takes them: a device's recovery keeps them only in the +//! runtime's own pages, as Metal keeps a buffer's records across its GPU's restart +//! (`indirect_command_buffer/carry.rs`). Each such buffer is one more held import, which ANV on +//! i915 lists in every execbuffer at about 0.35 us (`submit_check.rs`) and RADV pays by its +//! pages. //! - **Recycled.** A parked buffer of the same making (`recycle.rs`) is still taken first, and its //! bytes set to zero on the host (0.29 ms for 64 MiB), since its pages hold its last owner's. //! Only a buffer made here reads zero unwritten. @@ -69,11 +76,18 @@ pub(super) const FRESH_PAGES_PAST: u64 = BLOCK_BYTES / 2; /// where the device takes them (the module docs): `class` is the buffer's after a `Managed` /// buffer on a device without unified memory took `Private` memory and a host copy. pub(super) fn takes_fresh_pages(size: u64, class: MemoryClass) -> bool { + size > FRESH_PAGES_PAST && class_takes_fresh_pages(class) +} + +/// Whether a buffer in memory of `class` may lie in fresh pages at all, whatever its length: the +/// host maps memory of the class, on a system that maps such pages. An indirect command buffer's +/// records take them at any length (`buffer.rs`'s `FreshPages::Always`). +pub(super) fn class_takes_fresh_pages(class: MemoryClass) -> bool { let host_visible = matches!( class, MemoryClass::Shared | MemoryClass::WriteCombined | MemoryClass::Managed ); - host_visible && size > FRESH_PAGES_PAST && cfg!(unix) + host_visible && cfg!(unix) } /// Anonymous private pages the runtime mapped for a buffer of its own, or for a block of the diff --git a/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs b/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs index fd09b21a5..4562ca3ff 100644 --- a/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs +++ b/crates/metal2vulkan-runtime/src/indirect_command_buffer.rs @@ -14,7 +14,11 @@ //! translated kernel that reads the ID from an argument buffer reaches the buffer last made with //! the ID. The buffer is host-visible whatever storage mode the program asks for; the object //! answers the mode asked for, and the CPU encodes and reads back a `Private` buffer's commands -//! as a `Shared` one's, as plain Metal does. +//! as a `Shared` one's, as plain Metal does. The records, and the slots past them, lie in fresh +//! pages of the runtime's own where the device imports host pointers (`fresh_pages.rs`), so +//! that a device's recovery keeps them, as Metal keeps a buffer's records across its GPU's +//! restart; elsewhere in pooled memory, which the recovery's carry cannot keep +//! (`indirect_command_buffer/carry.rs`). //! - **CPU encoding.** [`IndirectCommandBuffer::indirect_compute_command_at`] gives a compute //! command's setters, which write its record as Metal's do (an M3 Max on macOS 26.7 and an M4 on //! 27.0.1): a buffer's address plus its offset's low 32 bits as one address; threadgroup lengths @@ -77,7 +81,6 @@ use super::error::{internal, invalid, Error, IndirectRule, MemoryKind, Problem, use super::families::GpuFamily; use super::indirect_execute::Unforeseen; use super::kept_commands::{Kept, KeptChunk, KeptChunks, StepChunk, StepCopy, UnlockedWrites}; -use super::memory::MemoryClass; use super::pipeline::{ ComputePipelineState, ComputeProgram, GraphicsState, RenderPipelineState, RenderProgram, RenderStateKind, WeakComputePipelineState, WeakRenderPipelineState, @@ -618,23 +621,16 @@ impl Device { &self.shared().identifiers, metal_allocated_size(descriptor, size), )?; - let storage = self.zeroed_buffer( - CALL, - length, - backing, - MemoryClass::Shared, - false, - Place::Records(held.id), - )?; + // In the runtime's own pages where the device imports them, so that a recovery keeps + // the records (`indirect_command_buffer/carry.rs`). + let storage = self.records_buffer(CALL, length, backing, Place::Records(held.id))?; // The slots past the record's, of their own buffer, as long as Metal's storage grows. let overflow = match (layout, overflow_bytes) { (Some(layout), Some(bytes)) => { - let storage = self.zeroed_buffer( + let storage = self.records_buffer( CALL, bytes.max(SLOT_BYTES), backing, - MemoryClass::Shared, - false, AddressPlacement::Outside, )?; Some(Overflow { diff --git a/crates/metal2vulkan-runtime/src/indirect_command_buffer/carry.rs b/crates/metal2vulkan-runtime/src/indirect_command_buffer/carry.rs index fa1ddd6c9..c51f37864 100644 --- a/crates/metal2vulkan-runtime/src/indirect_command_buffer/carry.rs +++ b/crates/metal2vulkan-runtime/src/indirect_command_buffer/carry.rs @@ -4,14 +4,17 @@ //! //! - **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 under `pipelines` wait for the carry; a setter's write without it -//! (`Batch`: one that adds nothing to what the records may hold) does not, and one meanwhile -//! races the carry. A host read outside a command buffer's work holds the storage's parts it -//! reads. +//! (`Buffer::carry_runtime`): in the runtime's own pages, where every such buffer lies on a +//! device that imports host pointers (`fresh_pages.rs`), the same pages there, the records as +//! the CPU and the GPU left them, as Metal keeps them across its GPU's restart; in pooled +//! host-visible memory, on a device that imports none or where the import failed, 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 under `pipelines` wait for the carry; +//! a setter's write without it (`Batch`: one that adds nothing to what the records may hold) +//! does not: in the runtime's own pages it writes the pages the carry keeps, and in pooled +//! memory one meanwhile races the carry. 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 diff --git a/crates/metal2vulkan-runtime/src/submit_check.rs b/crates/metal2vulkan-runtime/src/submit_check.rs index 70c3c7074..db501982a 100644 --- a/crates/metal2vulkan-runtime/src/submit_check.rs +++ b/crates/metal2vulkan-runtime/src/submit_check.rs @@ -39,7 +39,9 @@ //! with 256 of 1 MiB, 8.3 with none), below the floor for one import and past it for //! [`TAX_IMPORTS`]. Where it does, the runtime keeps its own long buffers out of //! fresh pages (`fresh_pages.rs`): each would add that cost, and more for its length, to every -//! submission for its whole life, where its fresh pages save one clear of its bytes. And it +//! submission for its whole life, where its fresh pages save one clear of its bytes. An +//! indirect command buffer's records lie in them whatever this answers, as a device's recovery +//! keeps them only there (`indirect_command_buffer/carry.rs`): one import a live buffer. And it //! releases a no-copy buffer's idle pointer import and imports it again at its next blit //! (`host_residency.rs`): under `HostMemory::new`'s contract the pages at the pointer stay the //! same while the buffer lives, so the new import reads what the kept one would on any driver, diff --git a/crates/metal2vulkan-runtime/src/tests/icb_carry_race.rs b/crates/metal2vulkan-runtime/src/tests/icb_carry_race.rs index 7a568b6e6..27e9af8eb 100644 --- a/crates/metal2vulkan-runtime/src/tests/icb_carry_race.rs +++ b/crates/metal2vulkan-runtime/src/tests/icb_carry_race.rs @@ -1,9 +1,15 @@ -//! An indirect command buffer's setter racing its device's recovery, whose carry takes the -//! buffer to the generation it makes (`indirect_command_buffer/carry.rs`): a set held by a hook -//! (`hold_next_set`) once its batch is made, while the recovery runs to the end, writes the -//! records the recovered buffer holds once let go, as a set made after the carry does, where -//! the carry moved them to new memory (a buffer of pooled memory: its records reset there) as -//! where it kept them. +//! An indirect command buffer across its device's recovery, whose carry takes the buffer to the +//! generation it makes (`indirect_command_buffer/carry.rs`): +//! +//! - the commands the CPU encoded before it read back and run after it, as Metal keeps a +//! buffer's records across its GPU's restart, where the records lie in the runtime's own pages, +//! as they do on a device that imports host pointers; +//! - a set held by a hook (`hold_next_set`) once its batch is made, while the recovery runs to the +//! end, writes the records the recovered buffer holds once let go, as a set made after the +//! carry does, where the carry moved them to new memory (a buffer of pooled memory: its records +//! reset there) as where it kept them. +//! +//! The tests print whether the carry kept the records' pages (`Kept`) or moved them (`Lost`). //! //! 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`). @@ -11,9 +17,13 @@ use super::device_recovery::{device, Scratch}; use super::device_recovery_carry::BYTES; -use super::device_recovery_live_table::{dispatched, dispatches, execute, indirect_state, WORDS}; +use super::device_recovery_live_table::{ + dispatched, dispatches, encode_command, execute, indirect_state, WORDS, +}; use crate::indirect_command_buffer::hold_next_set; -use crate::{Device, Error, IndirectCommandBuffer, ResourceOptions, Size}; +use crate::{ + Device, Error, IndirectCommandBuffer, IndirectCommandBufferDescriptor, ResourceOptions, Size, +}; use metal2vulkan::metal::IndirectCommandType; use std::sync::mpsc; @@ -89,3 +99,81 @@ fn a_locked_set_held_across_a_recovery_lands_on_the_recovered_records() { dispatched() ); } + +/// The render commands of [`a_recovery_keeps_the_commands_the_cpu_encoded`]'s buffer of draws. +const DRAWS: u64 = 64; + +/// The commands the CPU encoded before a recovery, read back and run after it as they were, as +/// Metal keeps a buffer's records across its GPU's restart: a compute command encoded whole +/// (state, buffers, dispatch) runs, and each of a buffer of draws' commands reads back its two +/// vertex and two fragment buffers, nil at offsets of their own, which the setters wrote without +/// the lock. The records lie in the runtime's own pages where the device imports host pointers, +/// which the carry keeps (`Kept`); in pooled memory it moved them to new memory and reset every +/// command (`Lost`), where Metal's are kept. +#[test] +fn a_recovery_keeps_the_commands_the_cpu_encoded() { + let scratch = Scratch::new(); + let device = device(&scratch.0); + let compute = indirect_state(&device); + let icb = dispatches(&device); + let private = || { + device + .new_buffer(BYTES, ResourceOptions::private()) + .unwrap() + }; + let (input, output, scale) = (private(), private(), private()); + encode_command(&icb, &compute, [&input, &output, &scale]); + let mut descriptor = IndirectCommandBufferDescriptor::new(); + descriptor.command_types = IndirectCommandType::DRAW; + descriptor.max_vertex_buffer_bind_count = 2; + descriptor.max_fragment_buffer_bind_count = 2; + let draws = device + .new_indirect_command_buffer(&descriptor, DRAWS, ResourceOptions::shared()) + .unwrap(); + // Command `i`'s vertex buffers 0 and 1 and fragment buffers 0 and 1: nil, at offsets of its + // own (a nil buffer's address is its offset). + let at = |i: u64| { + let first = (i + 1) * 64; + [first, first + 16, first + 32, first + 48] + }; + for i in 0..DRAWS { + let command = draws.indirect_render_command_at(i).unwrap(); + let [v0, v1, f0, f1] = at(i); + command.set_vertex_buffer(None, v0, 0).unwrap(); + command.set_vertex_buffer(None, v1, 1).unwrap(); + command.set_fragment_buffer(None, f0, 0).unwrap(); + command.set_fragment_buffer(None, f1, 1).unwrap(); + } + let records = [icb.records_address(), draws.records_address()]; + device.recover_for_test().unwrap(); + let kept = [icb.records_address(), draws.records_address()] == records; + let carry = if kept { "Kept" } else { "Lost" }; + eprintln!("ICB-CARRY-RACE encoded before the recovery: {carry}"); + let read = |i: u64| { + let command = draws.indirect_render_command_at(i).unwrap(); + let address = |binding: Result, Error>| { + binding.unwrap().map(|binding| binding.address.0) + }; + [ + address(command.vertex_buffer(0)), + address(command.vertex_buffer(1)), + address(command.fragment_buffer(0)), + address(command.fragment_buffer(1)), + ] + }; + for i in 0..DRAWS { + assert_eq!(read(i), at(i).map(Some), "render command {i} ({carry})"); + } + let command = icb.indirect_compute_command_at(0).unwrap(); + assert_eq!( + command.command_type().unwrap(), + IndirectCommandType::CONCURRENT_DISPATCH_THREADS, + "the dispatch encoded before the recovery ({carry})" + ); + let queue = device.new_command_queue().unwrap(); + assert_eq!( + execute(&device, &queue, &icb, [&input, &output, &scale]), + dispatched(), + "the command encoded before the recovery ran ({carry})" + ); +} diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index d6896c1d4..b86c64461 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 520; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2246; +pub const RUNTIME_VERSION: u32 = 2247; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/docs/API.md b/docs/API.md index 1c7f792df..1b7fba22f 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3829,7 +3829,9 @@ bound. 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, and of an indirect - command buffer's records outside the runtime's own pages (every command reset); the other objects + command buffer's records on a device that imports no host pointer, or where their import failed + (every command reset; the notice counts such buffers), where Metal's are kept, as they are in + the runtime's own pages everywhere else; 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