diff --git a/crates/metal2vulkan-runtime/src/argument_table.rs b/crates/metal2vulkan-runtime/src/argument_table.rs index 26972c72c..59efc61cf 100644 --- a/crates/metal2vulkan-runtime/src/argument_table.rs +++ b/crates/metal2vulkan-runtime/src/argument_table.rs @@ -32,7 +32,7 @@ use super::address_map::SamplerMaps; use super::binding::bound_sampler; -use super::buffer::Buffer; +use super::buffer::{Buffer, ReadApart}; use super::device::lock; use super::device::Device; use super::encoder::EncoderCore; @@ -359,12 +359,15 @@ fn bound_buffer( if offset > buffer.length() { return None; } - let base = buffer.base(); + // The Metal address first, which keeps a no-copy buffer's import for good, then where the + // buffer lies, in one look. + let gpu_address = buffer.exposed_address(ReadApart::Binding).0; + let (base, device_address) = buffer.base_and_device_address(ReadApart::Binding); Some(BoundBuffer::Buffer { length: base + buffer.length(), offset: base + offset, - gpu_address: buffer.gpu_address().0 - base, - device_address: buffer.device_address().map(|address| address - base), + gpu_address: gpu_address - base, + device_address: device_address.map(|address| address - base), attribute_stride, }) } @@ -1079,6 +1082,9 @@ impl ArgumentTable { }), } }; + // Each slot read whole once: a kept slot against its value, then the slots not kept, + // each of which reads nothing. A read of a no-copy buffer is a look at where it lies + // (`WorkCounts::no_copy_lies_read`), one a slot here as in the refresh. for (&index, bound) in &kept.buffers { let whole = buffer(index); assert!( @@ -1086,13 +1092,14 @@ impl ArgumentTable { "{DIFFERS}: {stage:?} buffer {index} kept as {bound:?}, read whole as {whole:?}" ); } - for &index in self.buffers.keys().chain(self.bytes.keys()) { - if let Some(whole) = buffer(index) { - assert!( - kept.buffers.contains_key(&index), - "{DIFFERS}: {stage:?} buffer {index} not kept, read whole as {whole:?}" - ); - } + let not_kept = (self.buffers.keys().chain(self.bytes.keys())) + .filter(|&&index| !kept.buffers.contains_key(&index)); + for &index in not_kept { + let whole = buffer(index); + assert!( + whole.is_none(), + "{DIFFERS}: {stage:?} buffer {index} not kept, read whole as {whole:?}" + ); } for (&index, bound) in &kept.textures { let whole = self.textures.get(&index).map(bound_texture); diff --git a/crates/metal2vulkan-runtime/src/blit_texture.rs b/crates/metal2vulkan-runtime/src/blit_texture.rs index 7468ad5a1..2c167359f 100644 --- a/crates/metal2vulkan-runtime/src/blit_texture.rs +++ b/crates/metal2vulkan-runtime/src/blit_texture.rs @@ -1565,7 +1565,7 @@ impl BlitCommandEncoder { &image_unit, &layout, buffer.length(), - buffer.at(0).1, + buffer.start(), into_texture, ) .map_err(copy_problem)?; @@ -1592,11 +1592,9 @@ impl BlitCommandEncoder { destination: &Buffer, copy: &RowsCopy, ) -> Result<(), Error> { - let ((src, src_base), (dst, dst_base)) = (source.at(0), destination.at(0)); - let uses = [ - reads(source, copy.src_span.clone()), - writes(destination, copy.dst_span.clone()), - ]; + // Read as a blit's (`host_residency.rs`): the command buffer holds the imports. + let (src, src_base) = self.core().blit_at(source, 0)?; + let (dst, dst_base) = self.core().blit_at(destination, 0)?; // One buffer's bytes, or two no-copy buffers' made over the same bytes, which lie in one // import (`host_aliases.rs`): one `VkBuffer` from one byte 0. if (src, src_base) == (dst, dst_base) && copy.meets() { diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 6d57d3d92..04f6ceea1 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -35,7 +35,7 @@ use super::host_memory::{KeepAlive, Release}; use super::host_residency::{Again, Imported, Residency}; use super::memory::{Mapped, MemoryClass, Placement, BLOCK_BYTES}; use super::program_objects::ProgramObject; -use super::rebind::Unexact; +use super::rebind::{ImportHold, Unexact}; use super::resource::{Identity, ObjectId, ResourceKey}; use super::texture::first_move::Filled; use super::texture::shared_alias::SharedImages; @@ -48,8 +48,7 @@ use metal2vulkan::bind::ResidentRange; use std::any::Any; use std::ops::Range; use std::ptr::NonNull; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex, MutexGuard, OnceLock, Weak}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicU8, AtomicUsize, Ordering}; /// A Metal buffer (`MTLBuffer`). Cheap to clone (a retain); `Send + Sync`. Two handles are equal /// when they are the same buffer. @@ -149,9 +148,14 @@ pub(super) struct HostCell { /// and in it), which a detach makes present stand-ins (`detach.rs`), and the textures being /// made over them, which a detach refuses while one is. textures: Mutex, - /// The buffer's Metal address was handed out (`Buffer::gpu_address`): its import is kept - /// imported for good (`host_residency.rs`), and the call need not look again. - exposed: AtomicBool, + /// The reasons the buffer's Metal address was handed out for (`Buffer::gpu_address`, + /// `Buffer::exposed_address`), a bit each ([`ReadApart`]): once any is, its import is kept + /// imported for good (`host_residency.rs`), and a call for a reason noted need not look + /// again. + exposed: AtomicU8, + /// The device whose work counts each look at its pages adds to + /// (`WorkCounts::no_copy_lies_read`). + device: Device, } /// The textures over a buffer's host pages ([`HostCell`]): their images, which a detach makes @@ -298,7 +302,7 @@ impl Detached { return Err(internal("a detached buffer's stand-in placed in a heap")); }; let old = from.import.shape; - let pages = own.with(|pages| { + let pages = own.with(ReadApart::Binding, |pages| { let placement = &pages.memory.placement; Pages { raw: pages.raw, @@ -326,9 +330,11 @@ impl Detached { } } + pages.let_go_by_buffer(); impl HostCell { /// The pages the buffer lies in now; `None` while it is detached. pub(super) fn current(&self) -> Option> { + self.device.shared().counts.no_copy_lie_read(); match &*lock(&self.pages) { Lying::In(pages) => Some(Arc::clone(pages)), Lying::Detached(_) => None, @@ -337,6 +343,7 @@ impl HostCell { /// Where the buffer lies now. pub(super) fn lying(&self) -> Lying { + self.device.shared().counts.no_copy_lie_read(); lock(&self.pages).clone() } @@ -367,8 +374,20 @@ impl HostCell { } } - /// Lie `lying` from now on: where the buffer lay. + /// Lie `lying` from now on: where the buffer lay, which the caller lets go of. Counted in + /// [`host_cells_moved`]: a buffer binding that reads where it lies (its base, its device + /// address) may change. pub(super) fn replace(&self, lying: Lying) -> Lying { + let lay = { + let mut pages = lock(&self.pages); + let lay = std::mem::replace(&mut *pages, lying); + HOST_CELLS_MOVED.fetch_add(1, Ordering::AcqRel); + lay + }; + // The replays that hold the pages it lay in go first, so the caller lets go of them last, + // as it would without them (`HostPages::let_go_by_buffer`). + if let Lying::In(pages) = &lay { + pages.let_go_by_buffer(); lay } @@ -433,6 +452,7 @@ pub(super) struct ListedPages(Arc); impl ListedPages { fn new(pages: Arc) -> ListedPages { pages.listed.fetch_add(1, Ordering::AcqRel); + pages.import.note_listed(); ListedPages(pages) } } @@ -522,6 +542,12 @@ pub(super) struct HostPages { release: OnceLock, /// The live buffers' tables' holds on them ([`ListedPages`]). listed: AtomicUsize, + /// commands took, held from its commit until they are replayed, each counted until it is + /// gone ([`let_go_by_replay`](Self::let_go_by_replay)), so the count outlives them. + replay_holds: Arc, + /// Their buffer let go of them: its release, rebind or detach (pages lie in one buffer, + /// once) ([`let_go_by_buffer`](Self::let_go_by_buffer)). + let_go: AtomicBool, } impl HostPages { @@ -529,13 +555,45 @@ impl HostPages { fn new(import: Arc) -> HostPages { if import.lying.fetch_add(1, Ordering::AcqRel) > 0 { // Another buffer lies in it: imported for good (`host_residency.rs`). - import.expose(); + import.expose(ReadApart::SecondBuffer); } HostPages { parked: Mutex::new(Vec::new()), import, release: OnceLock::new(), listed: AtomicUsize::new(0), + replay_holds: Arc::new(AtomicUsize::new(0)), + let_go: AtomicBool::new(false), + /// A command buffer's replays hold them from now on (`recorder`): counted before its commit + /// reads whether their buffer let go of them ([`let_go_by_buffer`](Self::let_go_by_buffer)). + self.replay_holds.fetch_add(1, Ordering::SeqCst); + /// A command buffer's replays let go of `pages`: the pages, where that hold was their last. + /// Counted out only once the hold is gone, so their buffer's let-go that finds no hold + /// finds no replay letting go of one either ([`let_go_by_buffer`](Self::let_go_by_buffer)). + pub(super) fn let_go_by_replay(pages: Arc) -> Option { + let holds = Arc::clone(&pages.replay_holds); + let last = Arc::into_inner(pages); + holds.fetch_sub(1, Ordering::AcqRel); + last + /// Whether their buffer let go of them ([`let_go_by_buffer`](Self::let_go_by_buffer)): read + /// by a commit after its replays' holds on them are counted and its replays queued. + pub(super) fn buffer_let_go(&self) -> bool { + self.let_go.load(Ordering::SeqCst) + /// Their buffer lets go of them (its release, rebind or detach), the caller still holding + /// them: where command buffers' replays hold them, every replay waiting runs first, on this + /// thread, so the replays let go of them before the caller does, and their deallocator runs + /// at the call that lets go of them last, as it does with commands recorded as they are + /// encoded (`recorder`). Nothing where none holds them. + /// + /// Against a commit on another thread whose replays come to hold them, each marks its side + /// and then reads the other's, sequentially consistent, so at least one sees the other: + /// this finds the commit's hold, and its replays, queued before the commit read the mark, + /// and replays them here; or the commit finds the mark and replays them itself, letting go + /// of the pages where it lets go of them without a recorder (`Replays::commit`). + fn let_go_by_buffer(&self) { + self.let_go.store(true, Ordering::SeqCst); + if self.replay_holds.load(Ordering::SeqCst) == 0 { + recorder.settle_all(shared.vk()); } } @@ -547,7 +605,7 @@ impl HostPages { /// Their memory and where the bytes start in it (a heap's textures bind images there): a /// read that keeps the import imported for good (`host_residency.rs`). pub(super) fn memory(&self) -> (vk::DeviceMemory, u64) { - let pages = self.import.pages(); + let pages = self.import.pages(ReadApart::Texture); let placement = &pages.memory.placement; (placement.memory, placement.offset + pages.offset) } @@ -581,7 +639,7 @@ impl HostPages { /// the import imported for good (`host_residency.rs`). #[cfg(unix)] pub(super) fn dma_buf(&self) -> Option<(Arc, u64, u32)> { - let pages = self.import.pages(); + let pages = self.import.pages(ReadApart::Texture); let placement = &pages.memory.placement; let imports = Arc::clone(placement.dma_buf_pages()?); let start = (placement.mapped?.as_ptr() as u64).checked_add(pages.offset)?; @@ -631,6 +689,12 @@ impl HostPages { }); } + /// (`recorder`, [`HeldByReplay`]): never as a rule, as their buffer's let-go and each commit + /// whose replays hold them agree on which replays them first + /// ([`let_go_by_buffer`](Self::let_go_by_buffer)). Were it to, they would have gone at that + /// let-go or at the commit, where their deallocator or keep-alive ran; they go now, after + /// the replay, announced once per device (`Degradation::HostDeallocatorDelayed`). Nothing + /// where neither is left to run. /// Run `release`'s deallocator now, at Metal's moment, the caller's `keep_alive` keeping the /// pages mapped until the import is freed: the import keeps it, unless it keeps another's /// already, or `others` (another buffer lies in the import, whose own contract keeps the same @@ -684,6 +748,16 @@ pub(super) struct HostImport { objects: Objects, /// The [`HostPages`] lying in it. lying: AtomicUsize, + /// The reads other than a blit's that took it, a bit each ([`HostImport::note_read_apart`]): + /// counted in `WorkCounts::host_imports_read_apart` and the gauge of each reason while it + /// lives. + read_apart: AtomicU8, + /// Why the device never releases it while idle, for an import it keeps: counted in that + /// reason's `WorkCounts` gauge while it lives. `None` for a releasable one. + kept_because: Option, + /// A rebind's import that no live buffers' table listed yet ([`ListedPages`]): counted in + /// `WorkCounts::host_imports_rebound_unlisted` until one does or it goes. + unlisted: AtomicBool, /// The keep-alive of the pages that went while it lived with none other lying in it, dropped /// once it is freed: it keeps the bytes mapped for every buffer made over them, since all were /// made over the same bytes, so a later one's keep-alive is dropped as its pages go @@ -748,6 +822,67 @@ impl Shape { } } +/// Why a read other than a blit's took a host import ([`HostImport::note_read_apart`]), each +/// counted once per import in its `WorkCounts::host_imports_read_apart_*` gauge while the import +/// lives. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum ReadApart { + /// The buffer's Metal address handed out: `gpu_address`, or written for the caller. + Address, + /// The buffer's `VkBuffer` handed out (`Buffer::vk_buffer`). + VkBuffer, + /// A command's read other than a blit's copy: a binding, `use_resource`, or a copy of a + /// texture over the bytes. + Binding, + /// A texture over the bytes: an image bound to the memory, or a texel view over the + /// `VkBuffer`. + Texture, + /// A second buffer lying in the import, or sharing its buffer's range. + SecondBuffer, + /// No thread to release it while idle (`host_residency.rs`). + Unreleased, +} + +impl ReadApart { + /// How many reasons there are. + pub(crate) const COUNT: usize = 6; + const ALL: [ReadApart; ReadApart::COUNT] = [ + ReadApart::Address, + ReadApart::VkBuffer, + ReadApart::Binding, + ReadApart::Texture, + ReadApart::SecondBuffer, + ReadApart::Unreleased, + ]; + + /// Its bit in [`HostImport::read_apart`]. + fn bit(self) -> u8 { + 1 << self as u8 + } +} + +/// Why the device keeps a host import imported whatever reads it, never releasing it while idle +/// (`host_residency.rs`), each counted in its `WorkCounts::host_imports_kept_*` gauge while the +/// import lives. Imports of dma-bufs kept as their descriptors did not fit count apart +/// (`WorkCounts::host_imports_kept_for_fds`), as pointer imports here. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum KeptBecause { + /// A heap's own import. + Heap, + /// A rebind's import (`rebind.rs`). + Rebind, + /// An import by pointer on a device whose driver is not measured to follow the pointer + /// (`DriverFact::PointerImportsFollowTheirAddress`), or off Unix. + Pointer, + /// No stand-in buffer for a read of a released one. + NoStandIn, +} + +impl KeptBecause { + /// How many reasons there are. + pub(crate) const COUNT: usize = 4; +} + /// A host import's `VkBuffer` and memory. enum Objects { /// Imported until the import goes. @@ -784,13 +919,24 @@ impl std::ops::Deref for ImportPages<'_> { } impl HostImport { - /// The import of `pages`, no pages lying in it yet. - fn new(device: &Device, pages: Pages) -> HostImport { + /// The import of `pages`, no pages lying in it yet, which the device keeps imported for + /// `because` (`None`: an import of dma-bufs whose descriptors did not fit, counted as such). + fn new(device: &Device, pages: Pages, because: Option) -> HostImport { + if let Some(because) = because { + device.shared().counts.host_import_kept(because, true); + } + let unlisted = because == Some(KeptBecause::Rebind); + if unlisted { + device.shared().counts.host_import_rebound_unlisted(true); + } HostImport { device: device.clone(), shape: Shape::of(&pages), objects: Objects::Fixed(pages), lying: AtomicUsize::new(0), + read_apart: AtomicU8::new(0), + kept_because: because, + unlisted: AtomicBool::new(unlisted), kept: Mutex::new(None), after_free: Mutex::new(Vec::new()), shared: SharedImages::default(), @@ -811,9 +957,19 @@ impl HostImport { shape: Shape::of(&pages), objects: Objects::Releasable(Residency::new(device, pages, again, stand_in)), lying: AtomicUsize::new(0), + read_apart: AtomicU8::new(0), + kept_because: None, + unlisted: AtomicBool::new(false), kept: Mutex::new(None), after_free: Mutex::new(Vec::new()), - shared: SharedImages::default(), + } + } + + /// A live buffers' table listed pages lying in it ([`ListedPages`]): a rebind's import is + /// listed from now on (`WorkCounts::host_imports_rebound_unlisted`). A load once listed. + fn note_listed(&self) { + if self.unlisted.load(Ordering::Relaxed) && self.unlisted.swap(false, Ordering::Relaxed) { + (self.device.shared().counts).host_import_rebound_unlisted(false); } } @@ -826,13 +982,12 @@ impl HostImport { } } - /// Its `VkBuffer` and memory for a read other than a blit's, which keeps a releasable import - /// imported for good from then on (`host_residency.rs`). Released, it is imported again + /// Its `VkBuffer` and memory for a read other than a blit's, for `reason`, which keeps a + /// releasable import imported for good from then on (`host_residency.rs`). Released, it is imported again /// first; where the device cannot, the device is lost (its work no longer runs) and the read /// takes the device's stand-in. - pub(super) fn pages(&self) -> ImportPages<'_> { - match &self.objects { - Objects::Fixed(pages) => ImportPages::Fixed(pages), + pub(super) fn pages(&self, reason: ReadApart) -> ImportPages<'_> { + self.note_read_apart(reason); #[cfg(unix)] Objects::Releasable(residency) => match residency.exposed() { Some(held) => ImportPages::Held(held), @@ -847,17 +1002,13 @@ impl HostImport { } /// Its `VkBuffer` and memory for a blit's command (`Buffer::blit_at`), imported again where - /// released, with what the command buffer holds of them until it completed: nothing of an + /// released, with what the command buffer holds of them (`rebind::ImportHold`): nothing of an /// import that keeps them. Refused where the device cannot import them again. - pub(super) fn blit_pages( - &self, - ) -> Result<(ImportPages<'_>, Option>), Error> { - match &self.objects { - Objects::Fixed(pages) => Ok((ImportPages::Fixed(pages), None)), + pub(super) fn blit_pages(&self) -> Result<(ImportPages<'_>, Option), Error> { #[cfg(unix)] Objects::Releasable(residency) => { let held = residency.for_blit()?; - let hold: Arc = Arc::clone(&held) as _; + let hold = ImportHold::Held(Arc::clone(&held)); Ok((ImportPages::Held(held), Some(hold))) } } @@ -873,19 +1024,35 @@ impl HostImport { } } - /// Keep it imported for good from now on (`host_residency.rs`): whether it was ever - /// released, so a range of it noted before may be stale. - pub(super) fn expose(&self) -> bool { - match &self.objects { + /// Keep it imported for good from now on, for `reason` (`host_residency.rs`): whether it was + /// ever released, so a range of it noted before may be stale. + pub(super) fn expose(&self, reason: ReadApart) -> bool { + self.note_read_apart(reason); Objects::Fixed(_) => false, #[cfg(unix)] Objects::Releasable(residency) => residency.expose(), } } - /// The shared images of textures over its bytes (`texture/shared_alias.rs`). - pub(super) fn shared_images(&self) -> &SharedImages { - &self.shared + /// Note a read other than a blit's, for `reason` ([`HostImport::pages`], + /// [`HostImport::expose`]): the reads after which the device's residency keeps a releasable + /// import for good (`host_residency.rs`), noted for an import of any kind, counted once while + /// it lives (`WorkCounts::host_imports_read_apart`), and once for each reason. A load once + /// noted. + fn note_read_apart(&self, reason: ReadApart) { + let bit = reason.bit(); + if self.read_apart.load(Ordering::Relaxed) & bit != 0 { + return; + } + let before = self.read_apart.fetch_or(bit, Ordering::Relaxed); + if before & bit != 0 { + return; + } + let counts = &self.device.shared().counts; + if before == 0 { + counts.host_import_read_apart(true); + } + counts.host_import_read_apart_for(reason, true); } } @@ -943,6 +1110,21 @@ impl Drop for HostImport { // one, as every holder of one holds the import. self.shared.clear(); let shared = self.device.shared(); + let read_apart = self.read_apart.load(Ordering::Relaxed); + if read_apart != 0 { + shared.counts.host_import_read_apart(false); + } + for reason in ReadApart::ALL { + if read_apart & reason.bit() != 0 { + shared.counts.host_import_read_apart_for(reason, false); + } + } + if let Some(because) = self.kept_because { + shared.counts.host_import_kept(because, false); + } + if self.unlisted.load(Ordering::Relaxed) { + shared.counts.host_import_rebound_unlisted(false); + } drop(busy); // Once freed, the keep-alive goes, and the deallocators that waited for the free run. let kept = lock(&self.kept).take(); @@ -968,6 +1150,7 @@ impl Drop for HostImport { residency.let_go(); Some(Box::new(after) as Box) } + } }; match (freed, length) { // Freed now: what waited goes here. @@ -993,6 +1176,21 @@ impl Drop for HostImport { } } +/// Count and announce once that a deallocator of a no-copy buffer of `length` bytes waits for +/// the batches submitted before its release (`freed_memory.rs`): its import's memory, freed, +/// waits for them, and the deallocator with it. + device.shared().counts.host_deallocator_delayed(); + device.degrade_once(Degradation::HostDeallocatorDelayed, || { + ( + format!("a no-copy buffer of {length} bytes"), + "its pages' import, freed, waits for the batches submitted before its release: the \ + device's driver fails pending work whose pipelines read device addresses where \ + such memory is freed, and the caller gave no keep-alive" + .to_owned(), + ) + }); +} + /// What goes once a host import's memory is freed: the keep-alive of the pages that went while it /// lived, and the deallocators that waited for the free, each panic caught. It waits with the /// memory where that waits for the batches in flight (`freed_memory.rs`). @@ -1118,22 +1316,24 @@ pub(super) struct Bound { impl OwnBytes { /// `f` of the pages the buffer lies in now: a detached buffer's stand-in (`Detached`). A - /// read of a no-copy buffer's import other than a blit's, which keeps it imported for good - /// (`HostImport::pages`). - fn with(&self, f: impl FnOnce(&Pages) -> R) -> R { + /// read of a no-copy buffer's import other than a blit's, for `reason`, which keeps it + /// imported for good (`HostImport::pages`). + fn with(&self, reason: ReadApart, f: impl FnOnce(&Pages) -> R) -> R { match &self.lie { Lie::Fixed(fixed) => f(&fixed.pages), Lie::Host(cell) => match cell.lying() { - Lying::In(pages) => f(&pages.import.pages()), + Lying::In(pages) => f(&pages.import.pages(reason)), Lying::Detached(detached) => f(&detached.pages), }, } } /// [`with`](Self::with) while the buffer lies in pages: `None` while it is detached. + fn with_attached(&self, reason: ReadApart, f: impl FnOnce(&Pages) -> R) -> Option { match &self.lie { Lie::Fixed(fixed) => Some(f(&fixed.pages)), Lie::Host(cell) => match cell.lying() { + Lying::In(pages) => Some(f(&pages.import.pages(reason))), Lying::Detached(_) => None, }, } @@ -1791,10 +1991,17 @@ impl Device { let lie = match owner { // A no-copy buffer's pages are its until a rebind (`rebind.rs`). Owner::Caller => { + // Kept imported where nothing imports it again: a heap's, an import of dma-bufs + // whose descriptors did not fit (counted as such), or one by pointer. + let kept = match (of_heap, pages.memory.placement.over_dma_buf()) { + (true, _) => Some(KeptBecause::Heap), + (false, true) => None, + (false, false) => Some(KeptBecause::Pointer), + }; #[cfg(unix)] - let import = self.host_import(pages, again); + let import = self.host_import(pages, again, kept); #[cfg(not(unix))] - let import = Arc::new(HostImport::new(self, pages)); + let import = Arc::new(HostImport::new(self, pages, kept)); self.host_lie(identity.key, import, release) } Owner::Runtime | Owner::Vulkan => Lie::Fixed(Arc::new(FixedPages { @@ -1816,19 +2023,26 @@ impl Device { /// The import of a no-copy buffer's `pages`: one the device releases while idle where /// `again` imports them again and the device keeps a stand-in for it and a thread to release - /// it (`host_residency.rs`), else one it keeps. + /// it (`host_residency.rs`), else one it keeps, for `kept` where nothing imports it again. #[cfg(unix)] - fn host_import(&self, pages: Pages, again: Option) -> Arc { - let stand_in = again.as_ref().and_then(|_| self.detach_stand_in().ok()); - let (Some(again), Some(stand_in)) = - (again, stand_in.as_ref().and_then(Buffer::fixed_pages)) - else { - return Arc::new(HostImport::new(self, pages)); + fn host_import( + &self, + pages: Pages, + again: Option, + kept: Option, + ) -> Arc { + let Some(again) = again else { + return Arc::new(HostImport::new(self, pages, kept)); + }; + let stand_in = self.detach_stand_in().ok(); + let Some(stand_in) = stand_in.as_ref().and_then(Buffer::fixed_pages) else { + let kept = Some(KeptBecause::NoStandIn); + return Arc::new(HostImport::new(self, pages, kept)); }; let import = Arc::new(HostImport::releasable(self, pages, again, stand_in)); if !self.shared().residency.note(&import) { // No thread releases it: kept imported. - import.expose(); + import.expose(ReadApart::Unreleased); } import } @@ -1869,7 +2083,8 @@ impl Device { texels: Mutex::new(Vec::new()), aliases: Mutex::new(Vec::new()), textures: Mutex::new(TexturesOver::default()), - exposed: AtomicBool::new(false), + exposed: AtomicU8::new(0), + device: self.clone(), }); self.shared().rebinds.register(key, &cell); Lie::Host(cell) @@ -1935,10 +2150,18 @@ impl Device { base: u64, reach: u64, ) -> Arc { - let import = HostImport::new(self, self.pages_of(raw, memory, offset, base, reach)); + let pages = self.pages_of(raw, memory, offset, base, reach); + let import = HostImport::new(self, pages, Some(KeptBecause::Rebind)); Arc::new(HostPages::new(Arc::new(import))) } + /// Host pages a rebind gives a no-copy buffer lying in `import`, the import of the same bytes + /// a live no-copy buffer was made over (`rebind.rs`, `host_aliases.rs`), without their + /// release, as [`Device::host_pages`] gives them. + pub(super) fn pages_in_import(&self, import: Arc) -> Arc { + Arc::new(HostPages::new(import)) + } + /// The Vulkan device address of `raw`, where the device enables `bufferDeviceAddress`. /// /// # Safety @@ -2079,6 +2302,7 @@ impl Buffer { /// for a heap's buffer, whose bytes are its heap's. A buffer's pages are its for good. pub(super) fn own_pages_device_local(&self) -> Option { match &self.0.bytes { + Bytes::Own(own) => own.with(ReadApart::Binding, |pages| { let memory = lock(&self.0.device.shared().memory); Some(memory.is_device_local(&pages.memory.placement)) }), @@ -2204,13 +2428,26 @@ impl Buffer { /// buffer takes its offsets from here, since a buffer's byte 0 may lie past the `VkBuffer`'s: /// a no-copy buffer's ([`Buffer::base`]), and a heap buffer's, which is its heap's. pub(super) fn at(&self, offset: u64) -> (vk::Buffer, u64) { + self.at_for(offset, ReadApart::Binding) + } + + /// [`Buffer::at`] for `reason`, which a no-copy buffer's import counts its read apart for + /// (`HostImport::note_read_apart`). + pub(super) fn at_for(&self, offset: u64, reason: ReadApart) -> (vk::Buffer, u64) { match &self.0.bytes { + Bytes::Own(own) => own.with(reason, |pages| (pages.raw, pages.base + offset)), + Bytes::Heap(bytes) => bytes.bytes.at_for(bytes.offset + offset, reason), + } + } /// [`Buffer::at`] while the buffer's bytes lie in pages, read with them at once: `None` while /// they are detached (`detach.rs`), when its `VkBuffer` is the device's stand-in, which holds /// none of its bytes. pub(super) fn attached_at(&self, offset: u64) -> Option<(vk::Buffer, u64)> { match &self.0.bytes { + Bytes::Own(own) => { + own.with_attached(ReadApart::Binding, |pages| (pages.raw, pages.base + offset)) + } Bytes::Heap(bytes) => bytes.bytes.attached_at(bytes.offset + offset), } } @@ -2230,8 +2467,23 @@ impl Buffer { /// (`ArgumentTable::stage_table`) count from there, [`Buffer::base`] bytes before byte 0. /// A multiple of 256 bytes, so every alignment Vulkan asks of an offset holds of it. pub(super) fn space(&self) -> (vk::Buffer, u64) { - let (raw, start) = self.at(0); - (raw, start - self.base()) + // `at(0)` less `base()`, from one look at where the buffer lies. + let space = |pages: &Pages, base: u64| (pages.raw, pages.base - base); + match &self.0.bytes { + Bytes::Own(own) => match &own.lie { + Lie::Fixed(fixed) => space(&fixed.pages, Shape::of(&fixed.pages).base), + Lie::Host(cell) => match cell.lying() { + Lying::In(pages) => space( + &pages.import.pages(ReadApart::Binding), + pages.import.shape.base, + ), + Lying::Detached(detached) => { + space(&detached.pages, Shape::of(&detached.pages).base) + } + }, + }, + Bytes::Heap(bytes) => bytes.bytes.at_for(bytes.offset, ReadApart::Binding), + } } /// Where the buffer's byte 0 lies in its bind layer space ([`Buffer::space`]): 0, but for a @@ -2244,12 +2496,38 @@ impl Buffer { } } + /// [`base`](Self::base) and [`device_address`](Self::device_address) together, from one look + /// at where the buffer lies, a no-copy buffer's pages read for `reason` + /// (`HostImport::note_read_apart`): what a binding of it reads (`argument_table::bound_buffer`), + /// each as its own call reads it. + pub(super) fn base_and_device_address(&self, reason: ReadApart) -> (u64, Option) { + let address = |pages: &Pages| Some(pages.memory.device_address? + pages.base); + match &self.0.bytes { + Bytes::Own(own) => match &own.lie { + Lie::Fixed(fixed) => (Shape::of(&fixed.pages).base, address(&fixed.pages)), + Lie::Host(cell) => match cell.lying() { + Lying::In(pages) => { + let read = pages.import.pages(reason); + (pages.import.shape.base, address(&read)) + } + Lying::Detached(detached) => { + (Shape::of(&detached.pages).base, address(&detached.pages)) + } + }, + }, + Bytes::Heap(bytes) => ( + 0, + (bytes.bytes.device_address()).map(|address| address + bytes.offset), + ), + } + } + /// The memory the buffer's bytes lie in: the `VkDeviceMemory`, the offset of the buffer's /// first byte in it, and its memory type's index. A texture over the buffer aliases it there /// (`texture.rs`). pub(super) fn memory(&self) -> (vk::DeviceMemory, u64, u32) { match &self.0.bytes { - Bytes::Own(own) => own.with(|pages| { + Bytes::Own(own) => own.with(ReadApart::Texture, |pages| { let placement = &pages.memory.placement; ( placement.memory, @@ -2373,7 +2651,7 @@ impl Buffer { /// `bufferDeviceAddress`. pub(super) fn device_address(&self) -> Option { match &self.0.bytes { - Bytes::Own(own) => own.with(|pages| { + Bytes::Own(own) => own.with(ReadApart::Binding, |pages| { let address = pages.memory.device_address?; Some(address + pages.base) }), @@ -2452,7 +2730,11 @@ impl Buffer { owner: Owner::Caller, .. }, - ) => Some((self.gpu_address(), own.reserved, self.contents()?)), + ) => Some(( + self.exposed_address(ReadApart::SecondBuffer), + own.reserved, + self.contents()?, + )), Bytes::Own(_) | Bytes::Heap(_) => None, } } @@ -2535,32 +2817,40 @@ impl Buffer { } /// Keep a no-copy buffer's import imported for good from now on, its Metal address handed - /// out (`host_residency.rs`): imported again now where the device released it, and its - /// live-table range read again where one was noted before a release. - fn expose(&self) { + /// out for `reason` (`host_residency.rs`): imported again now where the device released it, + /// and its live-table range read again where one was noted before a release. + fn expose(&self, reason: ReadApart) { let Some(cell) = self.host_cell() else { return; }; - if cell.exposed.load(Ordering::Acquire) { + let bit = reason.bit(); + let before = cell.exposed.load(Ordering::Acquire); + if before & bit != 0 { return; } if let Some(pages) = cell.current() { - if pages.import.expose() { - self.device().shared().live_buffers.refresh(self); + match before { + 0 => { + if pages.import.expose(reason) { + self.device().shared().live_buffers.refresh(self); + } + } + // Kept imported already: the new reason is only counted. + _ => pages.import.note_read_apart(reason), } } - cell.exposed.store(true, Ordering::Release); + cell.exposed.fetch_or(bit, Ordering::Release); } /// [`Buffer::at`] for a blit's command, which reads the `VkBuffer` without exposing the /// buffer: a no-copy buffer's import the device released while idle is imported again first - /// (`host_residency.rs`). With what the command buffer holds until it completed: the - /// import's objects, where the device may release them. Refused where the device cannot - /// import them again. + /// (`host_residency.rs`). With what the command buffer holds of the import's objects, where + /// the device may release them (`rebind::ImportHold`). Refused where the device cannot import + /// them again. pub(super) fn blit_at( &self, offset: u64, - ) -> Result<((vk::Buffer, u64), Option>), Error> { + ) -> Result<((vk::Buffer, u64), Option), Error> { if let Bytes::Own(OwnBytes { lie: Lie::Host(cell), .. @@ -2581,27 +2871,18 @@ impl Buffer { self.pages_cell()?.current() } - /// Where the bytes of the host pages the buffer lies in ([`Buffer::pages_cell`]) start in - /// their memory, which an aliasing image's place in them is reckoned from. Refused (an - /// internal error) for a buffer over no host pages. - pub(super) fn pages_base(&self) -> Result { - let cell = self - .pages_cell() - .ok_or_else(|| internal("an aliasing image over host pages of a buffer over none"))?; - // A detached buffer's bytes are in no memory: no texture is made over them. - let pages = cell - .current() - .ok_or(Error::NotImplemented(RuntimeGap::DetachTextures))?; - Ok(pages.memory().1) - } - - /// Note `watch`, an aliasing image bound to the host pages the buffer lies in, where a - /// rebind gives those other pages (a no-copy buffer's, or for a heap's buffer its heap's): - /// the rebind makes the image again over them. A buffer over no host pages notes nothing. - pub(super) fn watch_alias(&self, watch: AliasWatch) { - if let Some(cell) = self.pages_cell() { - cell.watch_alias(watch); - } + /// The host imports `buffers` lie in now, each counted once however many lie in it + /// (`host_aliases.rs`): a committed command buffer's used buffers' + /// (`WorkCounts::host_imports_used`). Buffers over no host pages count none. + pub(super) fn distinct_host_imports(buffers: &[Buffer]) -> u64 { + let mut imports: Vec<*const HostImport> = buffers + .iter() + .filter_map(|buffer| buffer.host_pages()) + .map(|pages| Arc::as_ptr(&pages.import)) + .collect(); + imports.sort_unstable(); + imports.dedup(); + imports.len() as u64 } /// Note `noted`, a texture over the buffer's bytes (`TexturesOver`), where they are host @@ -2711,7 +2992,14 @@ impl Buffer { /// observes) is kept imported for good from this call on: a command may reach it unnamed by /// this address. pub fn gpu_address(&self) -> GpuAddress { - self.expose(); + self.exposed_address(ReadApart::Address) + } + + /// [`Buffer::gpu_address`] for the runtime's use that hands the address on for `reason` (a + /// binding's, a buffer sharing the range): the import kept as `gpu_address` keeps it, + /// counted for that reason. + pub(super) fn exposed_address(&self, reason: ReadApart) -> GpuAddress { + self.expose(reason); self.0.address } diff --git a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs index bf5b4ff85..1365342ad 100644 --- a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs +++ b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs @@ -10,7 +10,9 @@ use super::address::{ AddressPlacement, AddressRange, GpuAddress, Held, Place, PlacementConflict, RangeToken, }; use super::address_pool::AddressPool; -use super::buffer::{usage, Buffer, BufferParts, HostCell, Lying, Modes, Owner}; +#[cfg(unix)] +use super::buffer::Pages; +use super::buffer::{usage, Buffer, BufferParts, HostCell, Lying, Modes, Owner, ReadApart}; use super::device::lock; use super::error::MemoryKind; use super::error::{internal, invalid, nil, vulkan, Error, Problem, RuntimeGap}; @@ -20,6 +22,8 @@ use super::host_memory::{ refuse_unwritable, refused, Deallocator, HostMemory, HostRelease, ImportWindow, Importer, KeepAlive, Source, }; +#[cfg(unix)] +use super::host_residency::Again; use super::memory::{ImportFailure, MemoryClass, Placement}; use super::rebind::RebindProblem; use super::texture::stand_in::TextureImages; @@ -319,7 +323,11 @@ impl Device { /// made. Without the call, a no-copy buffer made over exactly the bytes a live one was made /// over, of its memory class, lies in that one's import (`host_aliases.rs`), and so over the /// pages that were there when that one was made. Buffers made before the call keep their own - /// pages and imports, and stay ordered with each other as before. Not a Metal call: Metal needs + /// imports, and stay ordered with each other as before. Their pages are those their imports + /// read: an import of dma-bufs keeps the pages it was made over, as Metal's buffer does, and so + /// does an import of the pointer on a driver that keeps them; on a driver whose pointer imports + /// lavapipe), an import of the pointer reads the pages mapped there at each submission, the new + /// ones from the remap on (`docs/FAST-PATHS.md`, known gaps). Not a Metal call: Metal needs /// none. A `length` of 0 tells nothing. /// /// The call may come at the unmap or after the new map, but before a buffer is made over the @@ -332,9 +340,13 @@ impl Device { /// covers none of them or many, never reading them all. pub fn host_range_remapped(&self, bytes: NonNull, length: u64) { let start = bytes.as_ptr() as u64; - self.shared() - .aliases - .remapped(start, start.saturating_add(length)); + let shared = self.shared(); + // The unit an import's pages round out to: an import by pointer over a page the call + // covers is taken anew at its next submission. + let unit = (shared.host_import.as_ref()) + .map_or(1, |importer| importer.page.max(importer.alignment)); + let imports = (shared.aliases).remapped(start, start.saturating_add(length), unit); + shared.counts.host_range_remapped(imports); } /// A buffer of `length` zero bytes at `placement`, for `call`: refused as @@ -436,7 +448,6 @@ impl Device { let problem = HeapProblem::HostMemoryAlignment { alignment }; return Err(invalid(call, Problem::Heap(problem))); } - refuse_unwritable(&window)?; // A buffer over the bytes a live no-copy buffer was made over, of its memory class, lies // in its import (`host_aliases.rs`), its dma-buf source dropped uncalled; a heap's own // buffer imports its own. @@ -455,14 +466,28 @@ impl Device { shared.aliases.place(buffer.identity().key, made_over); return Ok(buffer); } + // Only a buffer that imports its pages pins them, and so has their writability asked: one + // that lies in a live import pins none, that import's making asked for the same window, + // and the pages stay writable while imported (`HostMemory::new`). + refuse_unwritable(&window, &shared.counts)?; // SAFETY: the window lies in the pages of the caller's bytes, which stay mapped // (`HostMemory::new`), and the source's pieces hold them (`HostMemory::with_dma_buf`). No // lock of the runtime's is held. // A no-copy buffer's own import of dma-bufs keeps them, so the device may release it - // while idle and import them again (`host_residency.rs`); a heap's keeps none. + // while idle and import them again (`host_residency.rs`), as it may its own import of + // the pointer where the driver's pointer imports follow their address; a heap's import + // stays. let (buffer, memory, again) = match unsafe { self.import_by_pointer(importer, pointer, length, host, class) }? { - Ok((buffer, memory)) => (buffer, memory, None), + Ok((buffer, memory)) => { + #[cfg(unix)] + let again = (!of_heap) + .then(|| Again::pointer(self, pointer, (length, window, class))) + .flatten(); + #[cfg(not(unix))] + let again = None; + (buffer, memory, again) + } // SAFETY: as above. Err(source) => unsafe { let keep = !of_heap; @@ -570,7 +595,6 @@ impl Device { if (!texels.is_empty() || !aliases.is_empty()) && window.offset != cell.offset() { return Err(Error::NotImplemented(RuntimeGap::RebindTextures)); } - refuse_unwritable(&window)?; // Detached bytes are given pages with no texture being made over them, and none is // made until the textures that presented stand-ins present their own images again. let detached_textures = || Error::NotImplemented(RuntimeGap::DetachTextures); @@ -578,54 +602,73 @@ impl Device { true => Some(cell.settled().ok_or_else(detached_textures)?), false => None, }; - // SAFETY: the window lies in the pages of the caller's bytes, which stay mapped - // (`HostMemory::new`, `HostMemory::with_dma_buf`). - let (host, placement, remade) = - match unsafe { self.import_by_pointer(importer, pointer, length, host, class) }? { - Ok((host, placement)) => (host, placement, Remade::default()), - // The source is called with no lock of the runtime's held (`dma_buf.rs`): the - // textures over detached bytes are let go of meanwhile, and must be settled again - // after it. - Err(source) => { - let was_settled = settled.take().is_some(); - // SAFETY: as above, and the source's pieces hold the pages - // (`HostMemory::with_dma_buf`). - let (host, placement, _) = unsafe { - let window = &window; - self.import_from_source( - call, importer, pointer, length, window, source, class, false, - ) - }?; - // The aliasing images of the textures over the bytes, made over dma-bufs of their - // own pages, each of which the source makes: still with no lock held. - let again = self.dma_buf_images_again(&aliases, heap, &placement, pointer); - let remade = match again { - Ok(remade) => remade, - Err(error) => { - self.discard_import(host, placement); - return Err(error); - } - }; - if was_settled { - match cell.settled() { - Some(again) => settled = Some(again), - None => { - drop(remade); + // Bytes a live no-copy buffer was made over, of its memory class, are given the pages of + // its import, as a buffer made over them lies in it (`host_aliases.rs`), the dma-buf source + // dropped uncalled: they pin no page, that import's making asked about the same window, + // and the pages stay writable while imported (`HostMemory::new`). A heap's own buffer + let made_over = (pointer.as_ptr() as u64, length); + .then(|| shared.aliases.import(made_over, class)) + .flatten(); + let (pages, remade) = match shares { + Some(import) => (self.pages_in_import(import), Remade::default()), + None => { + // Only pages imported here are pinned, and so have their writability asked. + refuse_unwritable(&window, &shared.counts)?; + // Whether an import alive now holds every page of them: counted once the import + // is made (`WorkCounts::host_rebind_imports_covered`). + let unit = importer.page.max(importer.alignment); + let start = pointer.as_ptr() as u64; + let covered = (shared.aliases).covered(start, start.saturating_add(length), unit); + // SAFETY: the window lies in the pages of the caller's bytes, which stay mapped + // (`HostMemory::new`, `HostMemory::with_dma_buf`). + let (host, placement, remade) = match unsafe { + self.import_by_pointer(importer, pointer, length, host, class) + }? { + Ok((host, placement)) => (host, placement, Remade::default()), + // The source is called with no lock of the runtime's held (`dma_buf.rs`): + // the textures over detached bytes are let go of meanwhile, and must be + // settled again after it. + Err(source) => { + let was_settled = settled.take().is_some(); + // SAFETY: as above, and the source's pieces hold the pages + // (`HostMemory::with_dma_buf`). + let (host, placement, _) = unsafe { + let window = &window; + self.import_from_source( + call, importer, pointer, length, window, source, class, false, + ) + }?; + let remade = match again { + Ok(remade) => remade, + Err(error) => { self.discard_import(host, placement); - return Err(detached_textures()); + return Err(error); + } + }; + if was_settled { + match cell.settled() { + Some(again) => settled = Some(again), + None => { + drop(remade); + self.discard_import(host, placement); + return Err(detached_textures()); + } } } + (host, placement, remade) } - (host, placement, remade) - } - }; - let pages = self.host_pages( - host.raw, - placement, - window.offset, - host.base, - host.size - host.base, - ); + }; + let pages = self.host_pages( + host.raw, + placement, + window.offset, + host.base, + host.size - host.base, + ); + shared.counts.host_rebind_import_made(covered); + (pages, remade) + } + }; // The heap's images bound to its bytes, made again over the new pages. A refusal drops // them and the new pages unreleased: the deallocator goes unrun. let mut remade = remade; @@ -685,10 +728,10 @@ impl Device { keeper.park(views.park()); } drop(keeper); - // The device's heap sets view the textures' remade images (`heap_sets::renew`). + // The device's heap sets view the remade images and views of the textures over the + // bytes, and no other texture's elements change (`heap_sets::renew_over`). if rebound || !stood_in.is_empty() { - lock(&shared.resource_ids).renew_textures(); - super::heap_sets::renew(self); + super::heap_sets::renew_over(self, key); } if !stood_in.is_empty() { super::heap_sets::retire(self, Box::new(stood_in)); @@ -837,6 +880,41 @@ impl Device { } } + /// The pages of a released import of the window's pages at `pointer`, made again there as + /// `again` made it (`host_residency.rs`), on a driver whose pointer imports follow their + /// address (`DriverFact::PointerImportsFollowTheirAddress`): a new `VkBuffer` made and bound + /// as the first was, over an import of the pages mapped at the pointer now, which the kept + /// import would read too. Refused as the first import may be, typed as the import answers + /// (out of memory among them), or with the device lost. + #[cfg(unix)] + pub(super) fn import_pointer_again( + &self, + pointer: NonNull, + again: &Again, + ) -> Result { + if self.is_lost() { + return Err(Error::DeviceLost); + } + let shared = self.shared(); + let importer = shared + .host_import + .as_ref() + .map_err(|_| internal("a pointer import made again on a device that imports none"))?; + let window = &again.window; + // SAFETY: the caller's pages stay mapped at the pointer while the buffer lives + // (`HostMemory::new`), and the buffer outlives the placement: the import holds it, and a + // command buffer that reads it holds the buffer too. + let (buffer, placement) = + unsafe { self.import_pointer(importer, pointer, again.length, window, again.class) }?; + Ok(self.pages_of( + buffer.raw, + placement, + window.offset, + buffer.base, + buffer.size - buffer.base, + )) + } + /// No dma-buf is imported on this system: there is no source to call. /// /// # Safety @@ -901,7 +979,8 @@ impl Device { return Err(invalid(call, Problem::ForeignObject)); } let unshared = || { - let held = AddressRange::of(other.gpu_address().0, other.length()); + let address = other.exposed_address(ReadApart::SecondBuffer); + let held = AddressRange::of(address.0, other.length()); Error::PlacementConflict(PlacementConflict::Unshared { held }) }; let (address, held, first) = other.sharable_range().ok_or_else(unshared)?; @@ -991,7 +1070,10 @@ impl Device { let bound = unsafe { raw_device.bind_buffer_memory(raw, placement.memory, placement.offset + at) }; match bound { - Ok(()) => Ok(placement), + Ok(()) => { + shared.counts.host_pointer_import_made(size); + Ok(placement) + } Err(error) => { lock(&shared.memory).free(raw_device, &placement); Err(vulkan(error)) diff --git a/crates/metal2vulkan-runtime/src/buffer_texture.rs b/crates/metal2vulkan-runtime/src/buffer_texture.rs index eefdb1fdd..41a5f4e86 100644 --- a/crates/metal2vulkan-runtime/src/buffer_texture.rs +++ b/crates/metal2vulkan-runtime/src/buffer_texture.rs @@ -24,7 +24,7 @@ use super::address::ObjectsToken; use super::apple_only::AppleOnly; -use super::buffer::Buffer; +use super::buffer::{Buffer, ReadApart}; use super::chroma_pairs; use super::copy_plan::{surface_depth_unit, CopyProblem, CopyUnit, HostLayout, ImageRegion}; use super::degradation::Degradation; @@ -974,7 +974,7 @@ impl Texels { extent: [u32; 2], ) -> Result { let layout = &self.layout; - let (buffer, at) = self.buffer.at(layout.offset); + let (buffer, at) = self.buffer.at_for(layout.offset, ReadApart::Texture); let staging = self.staging(layout, at)?; let frame = Frame { rotation, @@ -1144,7 +1144,7 @@ impl Texels { offset: placed.offset - placed.offset % LINEAR_ALIGNMENT, ..placed }; - let (raw, at) = texels.buffer.at(texels.shader.offset); + let (raw, at) = (texels.buffer).at_for(texels.shader.offset, ReadApart::Texture); let device = texels.buffer.device(); let limits = device.compile_device().profile().limits(); if at.is_multiple_of(limits.min_texel_buffer_offset_alignment.max(1)) { @@ -1199,7 +1199,7 @@ impl Texels { fn viewed(&self) -> (vk::Buffer, u64) { match self.staged.as_deref().and_then(ShadowCopies::target) { Some(ShadowTarget::Buffer(staging)) => (staging.raw(), staging.into.dst_offset), - _ => self.buffer.at(self.shader.offset), + _ => (self.buffer).at_for(self.shader.offset, ReadApart::Texture), } } @@ -1231,7 +1231,7 @@ impl Texels { words: Option, ) -> Result { let layout = &self.layout; - let (buffer, at) = self.buffer.at(layout.offset); + let (buffer, at) = self.buffer.at_for(layout.offset, ReadApart::Texture); // Vulkan copies a depth or stencil aspect at multiples of 4 bytes only. let depth = vk::ImageAspectFlags::DEPTH | vk::ImageAspectFlags::STENCIL; let align = match aspects.intersects(depth) { diff --git a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs index 29ae715a9..6f7541bf2 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/mod.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/mod.rs @@ -79,7 +79,7 @@ use super::tracker::Footprint; use super::upload::{Upload, Uploads}; use super::used_resources::{EncoderKind, EncoderRecord, Reached, ReadRecord}; use super::values::CommandBufferStatus; -use super::{CommandQueue, Device}; +use super::{Buffer, CommandQueue, Device}; use crate::release; use ash::vk; use batches::Batches; @@ -1787,6 +1787,8 @@ impl CommandBuffer { // the lock: what it upgrades may be a resource's last hold. let used = reached.list(); device.shared().live_buffers.reach(&used); + let shared = device.shared(); + (shared.counts).commit_used_host_imports(Buffer::distinct_host_imports(&used.buffers)); // Listed again at its first submission where the list changed since (a rebind ends a // use). let listing = Listing::new(device, used); diff --git a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs index 2c695600e..4680e2900 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/reencode.rs @@ -25,6 +25,7 @@ //! as before. So does any encoder of a kind that logs nothing (a render encoder's). use super::{lock, CommandBuffer, CommandBufferShared, State}; +use crate::device::functions::Vk; use crate::encoder::{Replayed, Segment}; use crate::replay::Replay; use crate::residency::Residency; @@ -88,7 +89,8 @@ impl CommandBufferShared { continue; }; // What a refused splice held goes after the lock. - let spliced = lock(&self.state).splice_replay(at, replayed, residency); + let vk = device.shared().vk(); + let spliced = lock(&self.state).splice_replay(vk, at, replayed, residency); match spliced { Ok(()) => counts.encoder_reencoded(), Err(unspliced) => { @@ -134,9 +136,11 @@ impl State { /// recording retained stays retained; its `VkCommandBuffer`s go with the pool unsubmitted. /// Refused, changing nothing and giving `replayed` back, where its place is not one part /// without segments but pending dispatches' (which go, the encoding again having recorded them - /// at once), or the command buffer was submitted. + /// at once), or the command buffer was submitted. Its replays hold what its commands took + /// with `device`, the device's functions (`Replays::hold`). pub(super) fn splice_replay( &mut self, + device: &Vk, at: usize, replayed: Replayed, residency: Option, @@ -173,8 +177,9 @@ impl State { heaps, } = replayed; // Held weakly until the first submission, as the commit held what the first recording - // took. - taken.wait(); + // took, and by its replays until they are replayed: what they held last goes here, as + // it does without them (`Replays::hold`, with `device`, the device's functions). + Some(replays) => drop(replays.hold(device, |pages| taken.wait(pages))), let recorded = &mut self.recorded[part]; recorded.raws = raws; recorded.summary = summary; diff --git a/crates/metal2vulkan-runtime/src/compressed_blit.rs b/crates/metal2vulkan-runtime/src/compressed_blit.rs index 1353ec73b..a9d0e1312 100644 --- a/crates/metal2vulkan-runtime/src/compressed_blit.rs +++ b/crates/metal2vulkan-runtime/src/compressed_blit.rs @@ -290,7 +290,8 @@ impl BlitCommandEncoder { let back = RowsCopy::new(&tight, rows); let rewrite = self.rewrite(at, texel, rules)?; let (raw_scratch, scratch_base) = rewrite.scratch; - let (raw_buffer, base) = buffer.at(0); + // Read as a blit's (`host_residency.rs`): the command buffer holds the import. + let (raw_buffer, base) = self.core().blit_at(buffer, 0)?; let copy = |rows: &[BufferRange], (src, src_base), (dst, dst_base)| { let regions: Vec = rows .iter() diff --git a/crates/metal2vulkan-runtime/src/detach.rs b/crates/metal2vulkan-runtime/src/detach.rs index ed76b7a85..f7c5e77f6 100644 --- a/crates/metal2vulkan-runtime/src/detach.rs +++ b/crates/metal2vulkan-runtime/src/detach.rs @@ -187,12 +187,12 @@ impl Device { shared.aliases.leave(key); // It lies over no host bytes: its uses take its stand-in. shared.aliases.unplace(key); - // The device's heap sets view the stand-ins; the images and views they named before - // wait for the command buffers that may read them through the sets, and the old pages, - // which the images bound there read, wait with them. + // The device's heap sets view the stand-ins of the textures over the bytes, and no other + // texture's elements change (`heap_sets::renew_over`); the images and views they named + // before wait for the command buffers that may read them through the sets, and the old + // pages, which the images bound there read, wait with them. if !images.is_empty() || !texels.is_empty() { - lock(&shared.resource_ids).renew_textures(); - super::heap_sets::renew(self); + super::heap_sets::renew_over(self, key); } // What lay in the old pages goes with them, as a rebind's swapped images do: once the // command buffers that may read them through the heap sets completed, and once nothing diff --git a/crates/metal2vulkan-runtime/src/dma_buf.rs b/crates/metal2vulkan-runtime/src/dma_buf.rs index 7460132a4..03d62b86a 100644 --- a/crates/metal2vulkan-runtime/src/dma_buf.rs +++ b/crates/metal2vulkan-runtime/src/dma_buf.rs @@ -201,6 +201,10 @@ pub(super) struct DmaBufPages { /// The sparse binding of the buffer over several imports, which nothing waited for: the /// internal timeline and the value it signals (`Device::bind_sparse_buffer`). bound: Option<(vk::Semaphore, u64)>, + /// A no-copy buffer's own import that the device would release while idle but keeps + /// imported, as the descriptors to import it again did not fit (`host_residency.rs`): + /// counted in `WorkCounts::host_imports_kept_for_fds` while the pages live. + kept_for_fds: bool, } impl Drop for DmaBufPages { @@ -234,6 +238,9 @@ impl Drop for DmaBufPages { unsafe { release::object(raw_device, memory) }; } (shared.counts).dma_buf_memories_freed(self.of_image, self.memories.len()); + if self.kept_for_fds { + shared.counts.host_import_kept_for_fds(false); + } drop(busy); if let Some(source) = self.source.take() { exit_guard::program_release(move || drop(source)); @@ -258,6 +265,7 @@ impl DmaBufPages { start: request.start.as_ptr() as u64, length: request.length, bound: None, + kept_for_fds: false, } } @@ -389,7 +397,9 @@ impl Device { /// no lock of the runtime's held, and never again here. Where `keep`, a descriptor of each /// dma-buf is kept too, which imports them again once the device released the import while /// idle (`host_residency.rs`): `None` where the host gives no descriptor more, or the device - /// keeps as many as it may. Refused, everything made released, as the module says. + /// keeps as many as it may, the import then kept imported and counted + /// (`WorkCounts::host_imports_kept_for_fds`). Refused, everything made released, as the + /// module says. /// /// # Safety /// @@ -445,19 +455,30 @@ impl Device { if pages.bound.is_some() { counts.dma_buf_sparse_buffer_made(); } - let placement = Placement::dma_buf(Arc::new(pages), memory, type_index, window.size, start); let again = kept.zip(kept_source).and_then(|(chunks, source)| { - Again::new(self, chunks, source, request, (length, *window, class)) + Again::dma_bufs(self, chunks, source, request, (length, *window, class)) }); + if keep && again.is_none() { + pages.kept_for_fds = true; + counts.host_import_kept_for_fds(true); + } + let placement = Placement::dma_buf(Arc::new(pages), memory, type_index, window.size, start); Ok((buffer, placement, again)) } - /// The pages of a released import made again from the dma-bufs `again` kept - /// (`host_residency.rs`): a new `VkBuffer` made and bound as the first was, over imports of - /// the same dma-bufs, so over the pages they hold whatever the address maps now, at the same - /// offsets in the same memory type. Never calls the source. Refused (out of device memory, or - /// the device lost) where the device cannot import them again, or lays them otherwise. - pub(super) fn import_again(&self, again: &Again) -> Result { + /// The pages of a released import made again from the dma-bufs `chunks` it kept, which + /// `source` made for `request` (`host_residency.rs`), as `again` made it: a new `VkBuffer` + /// made and bound as the first was, over imports of the same dma-bufs, so over the pages they + /// hold whatever the address maps now, at the same offsets in the same memory type. Never + /// calls the source. Refused (out of device memory, or the device lost) where the device + /// cannot import them again, or lays them otherwise. + pub(super) fn import_dma_bufs_again( + &self, + chunks: &[(OwnedFd, u64)], + source: &DmaBufSource, + request: DmaBufRequest, + again: &Again, + ) -> Result { if self.is_lost() { return Err(Error::DeviceLost); } @@ -467,7 +488,8 @@ impl Device { .host_import .as_ref() .map_err(|_| internal("a dma-buf import made again on a device that imports none"))?; - let chunks = (again.chunks.iter()) + let chunks = chunks + .iter() .map(|(fd, length)| { let fd = fd .try_clone() @@ -478,7 +500,7 @@ impl Device { }) }) .collect::, Error>>()?; - let mut pages = DmaBufPages::new(self, Arc::clone(&again.source), again.request, false); + let mut pages = DmaBufPages::new(self, Arc::clone(source), request, false); let window = &again.window; // SAFETY: the dma-bufs are those the first import took, which hold the pages it was // made over for as long as they are open (the import holds them). @@ -496,7 +518,7 @@ impl Device { Error::DeviceLost => Error::DeviceLost, other => refused(other), })?; - let start = again.request.start; + let start = request.start; let placement = Placement::dma_buf(Arc::new(pages), memory, type_index, window.size, start); let made = self.pages_of( buffer.raw, diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 6e6ed43fe..b62db5037 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -486,7 +486,7 @@ impl EncoderCore { ) -> Result<(vk::Buffer, u64), Error> { let (at, hold) = buffer.blit_at(offset)?; if let Some(hold) = hold { - self.retain_shared(hold); + self.taken.hold_import(hold); } self.retain_shared(buffer.held()); Ok(at) diff --git a/crates/metal2vulkan-runtime/src/heap_sets.rs b/crates/metal2vulkan-runtime/src/heap_sets.rs index 4c1ad2c5e..f529b5611 100644 --- a/crates/metal2vulkan-runtime/src/heap_sets.rs +++ b/crates/metal2vulkan-runtime/src/heap_sets.rs @@ -20,7 +20,8 @@ //! each image array holds the texture at ID `i` as the array's class takes it //! (`bind::heap_element`: its view where it fits the class, else the neutral), written as the //! texture takes the slot ([`place`]), for each set that lives then, and by a set made later -//! for each texture that lives then. A texture the class fits that it cannot view (a format +//! elements of the textures whose images or texel views lie in those bytes ([`renew_over`]), +//! and of no other texture (`WorkCounts::heap_slots_rewritten`). A texture the class fits that it cannot view (a format //! the device cannot sample or store formatless, or that needs its function's decode) is the //! neutral, announced ([`Degradation::UnnamedTextureUnviewable`]); one whose usage the class //! lacks is the neutral, as Metal's contract leaves the read undefined. A shadowed texture's @@ -135,6 +136,9 @@ struct Placed { flags: u32, /// Whether a heap write stores the device's conversion of a NaN in it ([`NanResidue::of`]). residue: [bool; 2], + /// The key of the buffer whose bytes its images and texel views lie in + /// (`Texture::bytes_key`), whose rebind or detach writes its elements again ([`renew_over`]). + bytes: Option, texture: Weak, } @@ -360,7 +364,7 @@ impl DeviceHeaps { } /// Write texture slot `id` into the table and every heap set where its holder changed since - /// (every slot where `force`, a rebind's): its holder's elements, or the neutral's entry where + /// (whatever changed where `force`, a rebind's): its holder's elements, or the neutral's entry where /// it has none. The holder goes to `held`, to drop once the lock is free. fn sync( &mut self, @@ -392,6 +396,7 @@ impl DeviceHeaps { let facts = texture.facts(); let flags = handle_entry_flags(&facts); let residue = NanResidue::of(&facts); + let bytes = texture.bytes_key(); // The neutral's entry until every set holds the texture. if let Some(table) = &self.table { table.put(id, 0, 0); @@ -413,6 +418,7 @@ impl DeviceHeaps { serial, flags, residue, + bytes, texture: weak, }, ); @@ -1063,12 +1069,21 @@ pub(crate) fn heap_set( /// heap set (the module docs). A failure to write it leaves the ID's entry the neutral's, /// announced. pub(super) fn place(device: &Device, texture: &Texture) { - sync(device, texture.gpu_resource_id().0, false); + sync(device, Slots::Changed(texture.gpu_resource_id().0)); } -/// Write texture slot `id` where its holder changed (every slot's where `force`, `id` then -/// ignored). -fn sync(device: &Device, id: u64, force: bool) { +/// The texture slots a [`sync`] writes. +enum Slots { + /// One, where its holder changed since it was written. + Changed(u64), + /// Every live texture's. + All, + /// Those of the live textures whose images and texel views lie in the bytes of the buffer of + /// a key (`Texture::bytes_key`). + Over(ResourceKey), +} + +fn sync(device: &Device, slots: Slots) { let mut held = Vec::new(); let mut notes = Notes::default(); let failed = { @@ -1110,11 +1125,21 @@ pub(super) fn tickets_out(device: &Device) -> bool { !heaps.retirement.out.is_empty() || !heaps.replaced.out.is_empty() } -/// Write every live texture's elements again: a rebind remade their images or views -/// (`buffer_descriptor.rs`), whose caller commits no command that uses the bytes meanwhile, so -/// no pending command buffer reads the elements rewritten. +/// Write every live texture's elements again: a change of storage form swapped images in +/// (`texture/storage_form.rs`) while no command buffer that may read the elements is pending. pub(super) fn renew(device: &Device) { - sync(device, 0, true); + sync(device, Slots::All); +} + +/// Write again the elements of the live textures whose images and texel views lie in the bytes +/// of the buffer of `key` (`Texture::bytes_key`; a heap's own buffer for its textures and those +/// over its buffers), and no other's: a rebind or a detach of those bytes remade their images or +/// views, or made them present stand-ins or their own images again (`buffer_descriptor.rs`, +/// `detach.rs`); its caller commits no command that uses the bytes meanwhile, so no pending +/// command buffer reads the elements rewritten. Every other texture's images and views stay +/// what its elements were written with. +pub(super) fn renew_over(device: &Device, key: ResourceKey) { + sync(device, Slots::Over(key)); } /// A program's texture at `id`, of hold serial `serial`, went: its entry is the neutral's where @@ -1143,7 +1168,7 @@ pub(super) fn gone(device: &Device, id: u64, serial: u64, keeper: Option } /// Keep `kept`, what the sets' elements named until they were written again without it -/// (`renew`): the views and images of textures a detach or a reattach of their bytes replaced +/// (`renew_over`): the views and images of textures a detach or a reattach of their bytes replaced /// (`detach.rs`, `buffer_descriptor.rs`). It waits for the command buffers committed before it, /// which may read it (the module docs). pub(super) fn retire(device: &Device, kept: Keeper) { diff --git a/crates/metal2vulkan-runtime/src/host_aliases.rs b/crates/metal2vulkan-runtime/src/host_aliases.rs index c15d506df..a70768554 100644 --- a/crates/metal2vulkan-runtime/src/host_aliases.rs +++ b/crates/metal2vulkan-runtime/src/host_aliases.rs @@ -21,16 +21,10 @@ //! one resource to the driver, where the tracker's barriers are not all the ordering there is. //! MoltenVK records no barrier between blits and leaves their order to Metal's hazard //! tracking, which is by `MTLBuffer`: two imports were two, and a blit's write through one -//! raced a read through the other in one encoder and in one command buffer (EV -//! `IOS-alane2-mvk4`, an M4: mixed texels); one import is one `MTLBuffer`, which Metal orders. -//! Each buffer stays its own Metal object, with its own Metal addresses, object ID, key, pages -//! hold and release: a command buffer lists and holds, and marks reached unnamed -//! (`live_buffers.rs`), the buffers its commands use, not their memory, as Metal marks them -//! (EV `IOS-pairreach1-m4`); its deallocator runs once nothing holds its pages, as an import -//! of its own would let it, while the import lives on in the buffers that still lie in it, and -//! its keep-alive goes then too, since those buffers keep the same bytes mapped (`buffer.rs`'s -//! `HostPages`). Copies between two such buffers are copies within one `VkBuffer`, moved as -//! within one buffer (`blit.rs`, `blit_texture.rs`). +//! moved as within one buffer (`blit.rs`, `blit_texture.rs`). A buffer rebound onto the bytes a +//! live buffer was made over, of the class of its import, lies in that import too, joining no key +//! (`Device::rebind_host_pages`; a heap's own buffer, and bytes with a texture's aliasing image +//! over them, import their own). //! - **Ownership stays the buffer's.** The added uses are hazard tracking's alone: what a command //! holds and lists (`EncoderCore::touch`, rebind holds, `used_resources`) is named by the //! command's own uses, each buffer by its own key. @@ -55,8 +49,11 @@ //! use of a key's bytes carries a use of its range's key and of the key of each other range those //! bytes overlap, clipped to them ([`HostAliases::augment`]). So two keys over overlapping bytes //! are ordered where they overlap, whatever made them, at a cost of one lookup a use while no two -//! ranges meet, and of one use added per range met otherwise. A remap reported keeps a placement: -//! it orders more than the pages need, never less. A heap's own buffer is placed as a buffer is. +//! ranges meet, and of one use added per range met otherwise. Each range keeps the ranges that +//! meet it, so a use reads them there rather than looking them up by address, but where they +//! outnumber the classes of length that lookup visits ([`Placements::sharing`]). A remap +//! reported keeps a placement: it orders more than the pages need, never less. A heap's own +//! buffer is placed as a buffer is. //! - **Same address, same pages.** Sharing an import assumes the pages at the bytes' addresses //! are the ones the import holds: Metal's `newBufferWithBytesNoCopy:` wires the pages at the //! address when it makes each buffer, so a buffer made after the caller replaced the pages @@ -68,10 +65,11 @@ //! remap). Without the call, a buffer over the same bytes as a live one lies in its import, and //! so over the pages that were there when that one was made. //! - **Cheap, from anywhere.** The call sits on the caller's unmap path, at each release of a -//! buffer's pages and over whole reservations of several GiB: with no memory noted it returns -//! without the lock, and otherwise it finds the memories with a byte in the range by address -//! ([`Memories`]), never reading them all, and ends them without reading their buffers' notes -//! ([`Over`]). The lock is a leaf: nothing else is locked, and no buffer, pages hold or +//! buffer's pages and over whole reservations of several GiB: with no memory noted and no +//! bytes placed it returns without the lock, and otherwise it finds the memories with a byte in +//! the range by address ([`Memories`]), never reading them all, and ends them without reading +//! their buffers' notes ([`Over`]); the placed ranges it touches it counts by the same lookup +//! (`WorkCounts::host_imports_remapped`). The lock is a leaf: nothing else is locked, and no buffer, pages hold or //! deallocator is dropped, while it is held (the imports noted are weak), so the call may be //! made from any thread, a deallocator's among them. @@ -81,6 +79,7 @@ use super::key_hash::KeyMap; use super::memory::MemoryClass; use super::resource::ResourceKey; use super::tracker::{Use, UseRange}; +use std::cell::Cell; use std::collections::BTreeMap; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, Weak}; @@ -101,6 +100,9 @@ pub(super) struct HostAliases { crowded: AtomicBool, /// How many memories are noted: with none, a reported remap has none to end. noted: AtomicUsize, + /// How many ranges of bytes keys lie over ([`Placements`]): with none and no memory noted, a + /// reported remap meets nothing. + placed: AtomicUsize, /// How many times the buffers that joined a memory or the placements changed: while it /// stands, [`augment`](Self::augment) gives the same uses for the same uses /// (`noted_apart.rs`). Each change counts once it is made, under the lock. @@ -114,6 +116,7 @@ impl Default for HostAliases { any: AtomicBool::new(false), crowded: AtomicBool::new(false), noted: AtomicUsize::new(0), + placed: AtomicUsize::new(0), version: AtomicU64::new(0), inner: Mutex::new(Inner { made_over: KeyMap::default(), @@ -249,12 +252,20 @@ impl HostAliases { /// (`Device::host_range_remapped`): every live buffer made over memory with a byte among /// them leaves it, as a rebound buffer does ([`HostAliases::leave`]), keeping its pages, its /// import and the key it joined, so that a later buffer over any of those addresses neither - /// lies in an import made before nor joins their key. With no memory noted it returns at - /// once; else it ends the memories the lookup by address finds + /// lies in an import made before nor joins their key. With no memory noted and no bytes + /// placed it returns at once; else it ends the memories the lookup by address finds /// ([`Memories::overlapping`]). - pub(super) fn remapped(&self, start: u64, end: u64) { - if start >= end || self.noted.load(Ordering::Relaxed) == 0 { - return; + /// + /// Returns how many ranges of bytes buffers over host pages lie over now ([`Placements`]: + /// each an import, two only where buffers of two memory classes lie over the same bytes) + /// have a page among those `start..end` covers, rounded out to `unit` bytes, the import's + /// unit: the imports whose pages the replacement touches, which a driver's import by pointer + /// takes anew at its next submission (`WorkCounts::host_imports_remapped`). + pub(super) fn remapped(&self, start: u64, end: u64, unit: u64) -> usize { + if start >= end + || (self.noted.load(Ordering::Relaxed) == 0 && self.placed.load(Ordering::Relaxed) == 0) + { + return 0; } let mut inner = lock(&self.inner); let ended: Vec<(u64, u64)> = inner.memories.overlapping(start, end).collect(); @@ -262,6 +273,34 @@ impl HostAliases { inner.memories.remove(memory); } self.noted.store(inner.memories.len(), Ordering::Relaxed); + // An import's pages are its bytes rounded out to the unit: one has a page the remap + // covers exactly when its bytes meet the remap's range rounded out to the unit. + let unit = unit.max(1); + let from = start - start % unit; + let to = end.div_ceil(unit).saturating_mul(unit); + inner.placements.ranges.overlapping(from, to).count() + } + + /// Whether the bytes `start..end`, rounded out to `unit` bytes, the import's unit, lie within + /// the bytes some buffer over host pages lies over now ([`Placements`]: each an import's), + /// rounded out likewise: an import alive now holds each of their pages + /// (`WorkCounts::host_rebind_imports_covered`). + pub(super) fn covered(&self, start: u64, end: u64, unit: u64) -> bool { + if start >= end || self.placed.load(Ordering::Relaxed) == 0 { + return false; + } + let unit = unit.max(1); + let from = start - start % unit; + let to = end.div_ceil(unit).saturating_mul(unit); + let inner = lock(&self.inner); + let mut ranges = inner.placements.ranges.overlapping(from, to); + ranges.any(|(at, length)| { + let end = at + .saturating_add(length) + .div_ceil(unit) + .saturating_mul(unit); + at - at % unit <= from && to <= end + }) } /// The buffer of `key` is gone. @@ -278,6 +317,7 @@ impl HostAliases { inner.placements.unplace(key); self.crowded .store(inner.placements.crowded(), Ordering::Relaxed); + (self.placed).store(inner.placements.ranges.len(), Ordering::Relaxed); self.changed(); } @@ -291,6 +331,7 @@ impl HostAliases { inner.placements.place(key, at); self.crowded .store(inner.placements.crowded(), Ordering::Relaxed); + (self.placed).store(inner.placements.ranges.len(), Ordering::Relaxed); self.changed(); } @@ -300,6 +341,7 @@ impl HostAliases { inner.placements.unplace(key); self.crowded .store(inner.placements.crowded(), Ordering::Relaxed); + (self.placed).store(inner.placements.ranges.len(), Ordering::Relaxed); self.changed(); } @@ -315,6 +357,11 @@ impl HostAliases { pub(super) fn version(&self) -> u64 { self.version.load(Ordering::Relaxed) } + + /// How many uses looked the ranges their bytes meet up by address + /// (`WorkCounts::host_range_lookups`, [`Placements::sharing`]). + pub(super) fn range_lookups(&self) -> u64 { + lock(&self.inner).placements.looked_up.get() } /// `uses` and, for each use of a buffer that joined a memory, a use of the memory's key of @@ -341,6 +388,7 @@ impl HostAliases { return false; } let inner = lock(&self.inner); + let aliases = joined.then_some(&*inner.aliases); let placements = crowded.then_some(&inner.placements); augmented(aliases, placements, uses, all) } @@ -365,21 +413,27 @@ fn release(memories: &mut Memories>, over: Over) { /// and `placements`, into `all`, empty: the uses added follow `uses`, which go in at the first. /// Whether any was added. pub(super) fn augmented( - aliases: &KeyMap, + aliases: Option<&KeyMap>, placements: Option<&Placements>, uses: &[Use], all: &mut Vec>, ) -> bool { + let mut add = |added: Use| { if all.is_empty() { all.reserve(2 * uses.len()); + all.extend_from_slice(uses); } + all.push(added); + }; for used in uses { let UseRange::Bytes(bytes) = &used.range else { continue; }; - let joined = aliases.get(&used.key).map(|alias| alias.key); + let joined = aliases + .and_then(|aliases| aliases.get(&used.key)) + .map(|alias| alias.key); if let Some(key) = joined { - added.push(Use { + add(Use { key, ..used.clone() }); @@ -390,7 +444,7 @@ pub(super) fn augmented( placements.sharing(used.key, bytes, |key, range| { // The memory's key carries the same bytes already. if Some(key) != joined || range != *bytes { - added.push(Use { + add(Use { key, range: UseRange::Bytes(range), ..used.clone() @@ -412,6 +466,8 @@ pub(super) struct Placements { ranges: Memories, /// How many ranges are crowded ([`Placed::crowded`]). crowded: usize, + /// How many uses looked the ranges their bytes meet up by address ([`Placements::sharing`]). + looked_up: Cell, } /// A range of host bytes keys lie over. @@ -422,16 +478,41 @@ struct Placed { keys: usize, /// Whether its key lies over it still. first: bool, - /// How many other ranges meet it (share a byte with it). - met: usize, + /// The other ranges that meet it (share a byte with it), each with its key (a range's key + /// is its own while it lives), in the order the lookup by address finds them ([`seat`]). + meets: Vec<((u64, u64), ResourceKey)>, } impl Placed { /// Whether a use of a key over it takes another: a second key lies there, its key went, or /// another range meets it. fn crowded(&self) -> bool { - self.keys > 1 || !self.first || self.met > 0 + self.keys > 1 || !self.first || !self.meets.is_empty() } + + /// The range over `at`, whose key is `key`, meets it from now on. + fn meet(&mut self, at: (u64, u64), key: ResourceKey) { + let index = self + .meets + .partition_point(|&(other, _)| seat(other) < seat(at)); + self.meets.insert(index, (at, key)); + } + + /// The range over `at` meets it no longer. + fn part(&mut self, at: (u64, u64)) { + let index = self + .meets + .partition_point(|&(other, _)| seat(other) < seat(at)); + if self.meets.get(index).is_some_and(|&(other, _)| other == at) { + self.meets.remove(index); + } + } +} + +/// Where the lookup by address finds the range over `at` among others ([`Memories::candidates`]): +/// by class of length, then by first byte and length. +fn seat(at: (u64, u64)) -> (usize, u64, u64) { + (class(at.1), at.0, at.1) } impl Placements { @@ -454,18 +535,20 @@ impl Placements { } let end = at.0.saturating_add(at.1); let met: Vec<(u64, u64)> = self.ranges.overlapping(at.0, end).collect(); - for &other in &met { + let mut meets = Vec::with_capacity(met.len()); + for other in met { if let Some(range) = self.ranges.get_mut(other) { let was = range.crowded(); - range.met += 1; + range.meet(at, key); self.crowded += usize::from(!was && range.crowded()); + meets.push((other, range.key)); } } let range = Placed { key, keys: 1, first: true, - met: met.len(), + meets, }; self.crowded += usize::from(range.crowded()); self.ranges.get_or_insert_with(at, || range); @@ -490,13 +573,13 @@ impl Placements { return; } self.crowded -= usize::from(was); - self.ranges.remove(at); - let end = at.0.saturating_add(at.1); - let met: Vec<(u64, u64)> = self.ranges.overlapping(at.0, end).collect(); - for other in met { + let Some(gone) = self.ranges.remove(at) else { + return; + }; + for (other, _) in gone.meets { if let Some(range) = self.ranges.get_mut(other) { let was = range.crowded(); - range.met -= 1; + range.part(at); self.crowded -= usize::from(was && !range.crowded()); } } @@ -504,7 +587,12 @@ impl Placements { /// For a use of `bytes` of `key` (counted from its first byte), each other key those bytes /// share, and the bytes of it they are (counted from its range's first byte), to `each`: its - /// own range's key where another, and each other range's the bytes meet, clipped to it. + /// own range's key where another, and each other range's the bytes meet, clipped to it, in + /// the order the lookup by address finds them. The ranges the bytes may meet are those that + /// meet the key's own range, which it keeps: they are read from there while no more than the + /// classes of length the lookup by address visits (a range query each, where a kept range is + /// a comparison); a use of a range met by more, as one over many others' bytes is, looks up + /// those its bytes meet (`WorkCounts::host_range_lookups`). pub(super) fn sharing( &self, key: ResourceKey, @@ -523,23 +611,32 @@ impl Placements { if own.key != key { each(own.key, bytes.clone()); } - if own.met == 0 { + if own.meets.is_empty() { return; } // The host bytes the use covers, within the key's own. let start = at.0.saturating_add(bytes.start.min(at.1)); let end = at.0.saturating_add(bytes.end.min(at.1)); + let mut clipped = |other: (u64, u64), key: ResourceKey| { + let from = start.max(other.0); + let to = end.min(other.0.saturating_add(other.1)); + if from < to { + each(key, from - other.0..to - other.0); + } + }; + if own.meets.len() <= self.ranges.held_classes() { + for &(other, key) in &own.meets { + clipped(other, key); + } + return; + } + self.looked_up.set(self.looked_up.get() + 1); for other in self.ranges.overlapping(start, end) { if other == at { continue; } - let Some(range) = self.ranges.get(other) else { - continue; - }; - let from = start.max(other.0); - let to = end.min(other.0.saturating_add(other.1)); - if from < to { - each(range.key, from - other.0..to - other.0); + if let Some(range) = self.ranges.get(other) { + clipped(other, range.key); } } } @@ -547,13 +644,16 @@ impl Placements { /// Values by the host bytes they are over (their first byte's address and their length), found /// by address: the memories a remap ends. Each class of length (`class`) is ordered by first -/// byte, so the lookup of those with a byte in a range reads, in each class, the values whose -/// first byte lies from the class's longest length before the range to its end +/// byte, so the lookup of those with a byte in a range reads, in each class that holds a value, +/// the values whose first byte lies from the class's longest length before the range to its end /// ([`Memories::candidates`]): the ones it finds, and of the class only those over the one -/// address half its longest length before the range, which end before it. +/// address half its longest length before the range, which end before it. The classes that hold +/// none it does not visit. pub(super) struct Memories { /// The values by class of length, each by first byte's address and length. classes: Vec>, + /// The classes that hold a value, bit `class` each. + held: u128, /// How many values there are. len: usize, } @@ -561,6 +661,10 @@ pub(super) struct Memories { /// The classes of length: one for each power of two from 2 a `u64` length may reach, and one /// for the lengths of 0 and 1. const CLASSES: usize = u64::BITS as usize + 1; +const _: () = assert!( + CLASSES <= u128::BITS as usize, + "a class a bit of `Memories::held`" +); /// The class of `length`: the least `b` with `length <= 2^b` (so its lengths are past the class /// below's longest). @@ -580,6 +684,7 @@ impl Default for Memories { fn default() -> Self { Memories { classes: (0..CLASSES).map(|_| BTreeMap::new()).collect(), + held: 0, len: 0, } } @@ -607,32 +712,48 @@ impl Memories { memory: (u64, u64), make: impl FnOnce() -> T, ) -> &mut T { - let by = &mut self.classes[class(memory.1)]; + let class = class(memory.1); + let by = &mut self.classes[class]; if !by.contains_key(&memory) { self.len += 1; + self.held |= 1 << class; } by.entry(memory).or_insert_with(make) } /// Remove the value over `memory`. pub(super) fn remove(&mut self, memory: (u64, u64)) -> Option { - let removed = self.classes[class(memory.1)].remove(&memory); + let class = class(memory.1); + let by = &mut self.classes[class]; + let removed = by.remove(&memory); self.len -= usize::from(removed.is_some()); + if by.is_empty() { + self.held &= !(1 << class); + } removed } /// The memories the lookup of those with a byte in `start..end` reads (the type's docs): of - /// each class, those whose first byte lies from its longest length before `start` to `end`. + /// each class that holds a value, those whose first byte lies from its longest length before + /// `start` to `end`. pub(super) fn candidates(&self, start: u64, end: u64) -> impl Iterator + '_ { - self.classes - .iter() - .enumerate() - .filter(|(_, by)| !by.is_empty()) - .flat_map(move |(class, by)| { - let from = start.saturating_sub(longest(class) - 1); - by.range((from, 0)..(end.max(from), 0)) - .map(|(&memory, _)| memory) - }) + let mut held = self.held; + let classes = std::iter::from_fn(move || { + let class = (held != 0).then(|| held.trailing_zeros() as usize)?; + held &= held - 1; + Some(class) + }); + classes.flat_map(move |class| { + let from = start.saturating_sub(longest(class) - 1); + self.classes[class] + .range((from, 0)..(end.max(from), 0)) + .map(|(&memory, _)| memory) + }) + } + + /// How many classes hold a value: those the lookup visits. + pub(super) fn held_classes(&self) -> usize { + self.held.count_ones() as usize } /// The memories with a byte in `start..end`. diff --git a/crates/metal2vulkan-runtime/src/host_memory.rs b/crates/metal2vulkan-runtime/src/host_memory.rs index 624768502..6abdca81e 100644 --- a/crates/metal2vulkan-runtime/src/host_memory.rs +++ b/crates/metal2vulkan-runtime/src/host_memory.rs @@ -21,14 +21,17 @@ //! alignment above the host page whose rounding would take pages the range does not touch, an //! offset in the pages that misses the buffer's memory alignment, no memory type both allow, or //! a driver that refuses the pointer. -//! - **Pages the process cannot write** are refused typed on Linux, before the import +//! - **Pages the process cannot write** are refused typed on Linux, before the buffer's own import //! ([`refuse_unwritable`] asks the kernel for the process's own mappings over the window, with -//! `PROCMAP_QUERY` on `/proc/self/maps`, or reads that file's lines where the kernel predates -//! the query, Linux 6.11). Linux drivers pin -//! user pages for writing: NVIDIA failed a read-only page as out of device memory, RADV refused -//! it, and ANV imported it and lost the device at the GPU's first read. lavapipe read one, so -//! there the rule refuses a little more than the driver would. On macOS, MoltenVK hands the -//! range to Metal, which reads read-only pages, so there is no check. +//! `PROCMAP_QUERY` on `/proc/self/maps`, a file kept open for them (`kept_maps`), or reads +//! that file's lines where the kernel predates the query, Linux 6.11; +//! `WorkCounts::host_mappings_queried`). A buffer that lies in a live +//! import of the same bytes (`host_aliases.rs`) asks nothing: it pins no page, that import's +//! making asked for the same window, and [`HostMemory::new`]'s contract keeps imported pages +//! writable. Linux drivers pin user pages for writing: NVIDIA failed a read-only page as out of +//! device memory, RADV refused it, and ANV imported it and lost the device at the GPU's first +//! read. lavapipe read one, so there the rule refuses a little more than the driver would. On +//! macOS, MoltenVK hands the range to Metal, which reads read-only pages, so there is no check. //! - **What drivers answered**. Private anonymous memory was imported on every venue measured. RADV //! refused shared memory typed: anonymous shared memory, and any mapping of a file, a shared //! memory object or a `memfd` among them (QEMU's `memory-backend-memfd,share=on` guest RAM). It @@ -42,8 +45,8 @@ //! takes by its pointer is made exactly as before, with no call more. //! - **When**. The pages are imported when the buffer is made, on every platform, as Metal wires //! them then: the GPU uses the pages mapped at the pointer when the buffer was made, whatever is -//! mapped there later, and memory the device cannot import is refused by the call that makes the -//! buffer, as Metal answers nil there. The import costs work per page there: on macOS MoltenVK's +//! mapped there later, but on a driver whose pointer imports follow their address +//! there. The import costs work per page there: on macOS MoltenVK's //! `newBufferWithBytesNoCopy:` and its residency set's commit, about 11 to 20 ms per GiB (an M4, //! an M3 Max); Metal makes the buffer at once and pays at the first command using it (24 to 88 ms //! per GiB). The runtime once deferred the macOS import to the buffer's first GPU use, which @@ -85,6 +88,7 @@ use super::error::{vulkan, Error}; use super::exit_guard; use super::loader_word::LoaderWord; use super::program_objects::ProgramObject; +use super::work_counts::Counters; use ash::vk; use metal2vulkan::device::{EnableSet, VkExtension}; use metal2vulkan::error::{Feature, Unsupported}; @@ -179,12 +183,16 @@ impl HostMemory { /// while idle, because RADV lists every import in every submission. The release frees its /// `VkBuffer` and memory and keeps the chunks open: the runtime keeps a duplicate descriptor of /// each, within a quarter of the process's `RLIMIT_NOFILE` soft limit. The next blit imports - /// them again, on the thread that encodes it, which costs time then. Only a buffer that blits - /// alone have read is released. One whose `gpu_address` or `VkBuffer` was handed out, or with a - /// texture over its bytes, stays imported. Nothing of Metal's observes the release: the bytes, - /// the address and the pages stay, the CPU's writes made meanwhile are read, and the source is - /// not called again. A blit that finds the device unable to import the chunks again (out of - /// memory) is refused. + /// them again, on the thread that encodes it, which costs time then. A buffer whose + /// descriptors pass that quarter (read once, at the process's first such import) stays + /// imported, in every kernel submission's list (`WorkCounts::host_imports_kept_for_fds` counts + /// them). The runtime never changes the limit: a program that makes many no-copy buffers at + /// once raises its soft limit toward the hard one at startup (`setrlimit`), as QEMU does. Only + /// a buffer that blits alone have read is released. One whose `gpu_address` or `VkBuffer` was + /// handed out, or with a texture over its bytes, stays imported. Nothing of Metal's observes + /// the release: the bytes, the address and the pages stay, the CPU's writes made meanwhile are + /// read, and the source is not called again. A blit that finds the device unable to import the + /// chunks again (out of memory) is refused. /// /// # Safety /// @@ -389,15 +397,22 @@ pub(super) fn import_refused(error: vk::Result) -> Error { } /// Refuse the window's pages, typed, unless the process maps every one of them writable: Linux -/// drivers pin imported pages for writing. The kernel answers for the mappings over the window -/// ([`queried_writable`]) at each call, so a page remapped or reprotected since an earlier import -/// is judged as it is now; a kernel without the query (before Linux 6.11) has the lines of -/// `/proc/self/maps` read up to the window instead ([`writable`]), which cost about 4.5 ms per -/// import in a process of 34,000 mappings. When the file cannot be opened, every import is -/// refused as not implemented here. +/// drivers pin imported pages for writing. Asked by each call that imports the pages itself, not +/// by a buffer that lies in a live import of them. The kernel answers for the mappings over the +/// window ([`queried_writable`]) at each call, so a page remapped or reprotected since an earlier +/// import is judged as it is now: one query per mapping, so its cost grows with the mappings over +/// the window (a view of scattered pages maps each run apart). The queries go through the file +/// the process keeps open ([`kept_maps`]). A kernel without the query (before Linux 6.11) has the +/// lines of `/proc/self/maps` read up to the window instead ([`writable`]), from a file opened for +/// the reading, which cost about 4.5 ms per import in a process of 34,000 mappings. Each mapping +/// asked is counted in `counts` (`WorkCounts::host_mappings_queried`). When the file cannot be +/// opened, every import is refused as not implemented here. #[cfg(target_os = "linux")] -pub(super) fn refuse_unwritable(window: &ImportWindow) -> Result<(), Error> { - match host_writable(window.start, window.start + window.size) { +pub(super) fn refuse_unwritable(window: &ImportWindow, counts: &Counters) -> Result<(), Error> { + let mut asked = 0; + let answer = mappings_writable(window.start, window.start + window.size, &mut asked); + counts.host_mappings_queried(asked); + match answer { Some(true) => Ok(()), Some(false) => Err(not_importable()), None => Err(Error::Unsupported(Unsupported::not_implemented( @@ -411,83 +426,36 @@ pub(super) fn refuse_unwritable(window: &ImportWindow) -> Result<(), Error> { /// of `/proc/self/maps` where the kernel predates the query ([`writable`]); `None` when that file /// cannot be opened. #[cfg(target_os = "linux")] -pub(crate) fn host_writable(start: u64, end: u64) -> Option { +fn mappings_writable(start: u64, end: u64, asked: &mut u64) -> Option { use std::io::BufRead; + let maps = kept_maps()?; + if let Some(writable) = queried_writable(&maps, start, end, asked) { + return Some(writable); + } + // The lines are read from a file of their own: reading moves its position, which the kept + // one's queries share among threads. let maps = std::fs::File::open("/proc/self/maps").ok()?; - Some(match queried_writable(&maps, start, end) { - Some(writable) => writable, - None => { - let lines = std::io::BufReader::new(maps).lines().map_while(Result::ok); - writable(lines, start, end) - } - }) + let lines = std::io::BufReader::new(maps).lines().map_while(Result::ok); + Some(writable(lines, start, end, asked)) } -/// Whether the process maps `[start, end)` without a gap, each page with write permission, as the -/// kernel answers now: on Apple's systems the current protection of each region of the task's map -/// over it (`mach_vm_region`, `VM_REGION_BASIC_INFO_64`); `None` where the kernel fails the query -/// otherwise than for a missing region. -#[cfg(target_vendor = "apple")] -pub(crate) fn host_writable(start: u64, end: u64) -> Option { - /// `VM_REGION_BASIC_INFO_COUNT_64`: the `int`s of `vm_region_basic_info_data_64_t` (of - /// ``, under its `#pragma pack(4)`), whose first is the region's current - /// protection. - const BASIC_INFO_COUNT_64: usize = 9; - /// `VM_REGION_BASIC_INFO_64`. - const BASIC_INFO_64: i32 = 9; - /// `KERN_INVALID_ADDRESS`: no region at or above the address. - const INVALID_ADDRESS: i32 = 1; - /// `VM_PROT_WRITE`. - const PROT_WRITE: i32 = 0x02; - unsafe extern "C" { - /// The task's own port, `mach_task_self()`'s answer (``). - static mach_task_self_: u32; - fn mach_vm_region( - task: u32, - address: *mut u64, - size: *mut u64, - flavor: i32, - info: *mut i32, - count: *mut u32, - object_name: *mut u32, - ) -> i32; +/// This process's `/proc/self/maps`, opened once for [`queried_writable`] and kept with the id of +/// the process that opened it, or opened again (`None` where it cannot be): each `PROCMAP_QUERY` +/// answers from the process's mappings as they are at the call, so a file kept open reads the same +/// answers as one opened for the call, without the opening, which cost each import about as much +/// as its queries (an import over 57 mappings, the consumer's guest pages). A process forked +/// since holds the file of its parent's mappings, so one of another id opens its own. +#[cfg(target_os = "linux")] +pub(super) fn kept_maps() -> Option> { + static KEPT: Mutex)>> = Mutex::new(None); + let process = std::process::id(); + let mut kept = lock(&KEPT); + if let Some((_, maps)) = kept.as_ref().filter(|(opener, _)| *opener == process) { + return Some(std::sync::Arc::clone(maps)); } - let mut covered = start; - while covered < end { - let (mut address, mut size) = (covered, 0u64); - let mut info = [0i32; BASIC_INFO_COUNT_64]; - let mut count = BASIC_INFO_COUNT_64 as u32; - let mut object_name = 0u32; - // SAFETY: `mach_task_self_` is set as the task starts and only read after; every pointer - // is to a local of the type and size the call reads and writes; `count` holds `info`'s - // size in `int`s. - let result = unsafe { - mach_vm_region( - mach_task_self_, - &mut address, - &mut size, - BASIC_INFO_64, - info.as_mut_ptr(), - &mut count, - &mut object_name, - ) - }; - if result != 0 { - return (result == INVALID_ADDRESS).then_some(false); - } - // The call answers the region at the address, or the first above it: a gap. - if address > covered || info[0] & PROT_WRITE == 0 { - return Some(false); - } - covered = address.saturating_add(size); - } - Some(true) -} - -/// No answer on other systems. -#[cfg(not(any(target_os = "linux", target_vendor = "apple")))] -pub(crate) fn host_writable(_start: u64, _end: u64) -> Option { - None + let maps = std::sync::Arc::new(std::fs::File::open("/proc/self/maps").ok()?); + *kept = Some((process, std::sync::Arc::clone(&maps))); + Some(maps) } /// `struct procmap_query` of Linux's `include/uapi/linux/fs.h` (Linux 6.11): the argument of @@ -528,14 +496,20 @@ const PROCMAP_QUERY_VMA_WRITABLE: u64 = 0x02; /// Whether the process maps `[start, end)` without a gap, each mapping with write permission, as /// the kernel answers `PROCMAP_QUERY` on `maps` (this process's `/proc/self/maps`): one query per -/// mapping the window touches, each for the mapping covering the first address not yet covered. -/// `None` where the kernel does not answer the query (before Linux 6.11, `ENOTTY`) or fails it -/// otherwise; a missing mapping (`ENOENT`) is an answer, not writable. +/// mapping the window touches, each for the mapping covering the first address not yet covered, +/// and each added to `asked`. `None` where the kernel does not answer the query (before Linux +/// 6.11, `ENOTTY`) or fails it otherwise; a missing mapping (`ENOENT`) is an answer, not writable. #[cfg(target_os = "linux")] -pub(super) fn queried_writable(maps: &std::fs::File, start: u64, end: u64) -> Option { +pub(super) fn queried_writable( + maps: &std::fs::File, + start: u64, + end: u64, + asked: &mut u64, +) -> Option { use std::os::fd::AsRawFd; let mut covered = start; while covered < end { + *asked += 1; let mut query = ProcmapQuery { size: std::mem::size_of::() as u64, query_addr: covered, @@ -569,15 +543,21 @@ pub(super) fn queried_writable(maps: &std::fs::File, start: u64, end: u64) -> Op /// Refuse the window's pages unless the process can write them: no check off Linux (MoltenVK /// hands the range to Metal, which reads read-only pages). #[cfg(not(target_os = "linux"))] -pub(super) fn refuse_unwritable(_window: &ImportWindow) -> Result<(), Error> { +pub(super) fn refuse_unwritable(_window: &ImportWindow, _counts: &Counters) -> Result<(), Error> { Ok(()) } /// Whether the mappings of `maps` (lines of `/proc//maps`, in address order) cover -/// `[start, end)` without a gap, each with write permission. Reading stops at the first line past -/// `end`; a line that does not parse is skipped. +/// `[start, end)` without a gap, each with write permission, adding to `asked` each mapping it +/// judged (one ending past the address it reached). Reading stops at the first line past `end`; a +/// line that does not parse is skipped. #[cfg(target_os = "linux")] -pub(super) fn writable(maps: impl IntoIterator, start: u64, end: u64) -> bool { +pub(super) fn writable( + maps: impl IntoIterator, + start: u64, + end: u64, + asked: &mut u64, +) -> bool { let mut covered = start; for line in maps { if covered >= end { @@ -589,6 +569,7 @@ pub(super) fn writable(maps: impl IntoIterator, start: u64, end: if to <= covered { continue; } + *asked += 1; if from > covered || !write { return false; } diff --git a/crates/metal2vulkan-runtime/src/host_residency.rs b/crates/metal2vulkan-runtime/src/host_residency.rs index 6a6d9c6cb..bcbd009f6 100644 --- a/crates/metal2vulkan-runtime/src/host_residency.rs +++ b/crates/metal2vulkan-runtime/src/host_residency.rs @@ -1,4 +1,4 @@ -//! Idle imports of the caller's dma-bufs, released and imported again at their next use: a +//! Idle imports of a no-copy buffer's pages, released and imported again at their next use: a //! runtime-internal residency, which nothing of Metal's observes. //! //! RADV lists every `VkDeviceMemory` its device imported in every kernel submission's @@ -8,52 +8,64 @@ //! and each submission's list is the whole global list (`radv_amdgpu_get_bo_list`). Linux 7.0's //! amdgpu works per entry at every submission (`amdgpu_cs.c`: lookup and sort, lock, validate, //! page-table update, fence sync and fence add), about 0.75 us an entry on a Radeon 780M (the -//! consumer's measurement). So each import a device holds costs every submission, used or not: -//! a consumer whose guest keeps hundreds of transfer buffers paid most of its submission thread's -//! time for those idle. The runtime's own memory is pooled in few blocks, which RADV keeps out of -//! the list. +//! consumer's measurement). ANV on i915 lists every `VkDeviceMemory` of the device in every +//! execbuffer (`i915/anv_batch_chain.c`, `setup_execbuf_for_cmd_buffers`), a pointer import (an +//! i915 userptr) costing about 0.16 us of the kernel's time an execbuffer on an Iris Xe of RPL-P, +//! three times an ordinary buffer object. So each import a device holds costs every submission, +//! used or not: a consumer whose guest keeps hundreds of transfer buffers paid much of its +//! submission thread's time for those idle. The runtime's own memory is pooled in few blocks. //! -//! - **Which imports.** A no-copy buffer's own import of the dma-bufs its pages' source made -//! (`dma_buf.rs`, where the device refused the pages' pointer): not a heap's, nor a rebind's, -//! and only where the device kept a descriptor of each dma-buf ([`Again`]) within the -//! descriptors the process's devices keep at most ([`kept_fds_limit`]); an import past them is -//! made as any other and stays imported. Pages imported by their pointer stay -//! imported: importing them again would read the pages mapped at the address then, which a -//! remap may have replaced, and their exact form is the dma-buf's. +//! - **Which imports.** A no-copy buffer's own import (not a heap's, nor a rebind's) where the +//! device can make it again exactly ([`Again`]): +//! - of the dma-bufs its pages' source made (`dma_buf.rs`, where the device refused the pages' +//! pointer), where the device kept a descriptor of each dma-buf within the descriptors the +//! process's devices keep at most ([`kept_fds_limit`]); an import past them is made as any +//! other and stays imported; +//! - of its pages' pointer, on a driver whose pointer imports follow their address +//! again at the same pointer does, so releasing it changes nothing a command reads. Elsewhere +//! a pointer import stays imported: the driver may keep the pages it was made over, as +//! Metal's buffer does, and an import again would read those a remap put there since. //! - **Blits alone.** It stays releasable while every read of its `VkBuffer` and memory was a //! blit's (`Buffer::blit_at`: a copy or fill naming the buffer, a copy between it and a //! texture, `synchronize_resource`), which holds what it read until its command buffer -//! completed ([`Imported`]). Any other read keeps it imported for good from then on, before the +//! completed ([`Imported`]), weakly from the commit until the first submission +//! (`rebind::ImportHold`). Any other read keeps it imported for good from then on, before the //! read returns: its Metal address handed out (`gpu_address`, so a binding, an argument //! buffer, an argument table, an indirect command buffer or `use_resource`), its `VkBuffer` //! handed out (`vk_buffer`), a texture or texel view over its bytes, or a second buffer lying in //! the import (`host_aliases.rs`). So no pointer, descriptor or image other than a blit's //! command ever holds a released import's objects. //! - **Released while idle** by the device's residency thread ([`Sweeper`]), every [`TICK`]: an -//! import no command buffer holds (every one that read it completed) and that no blit took for -//! its window, [`IDLE`] at first and doubled at each import again, up to [`IDLE_MOST`], so an -//! import used now and then stays imported and an unused one goes. Its `VkBuffer` is destroyed -//! and its memory freed; the buffer, its Metal address, its host pages, the dma-bufs and the -//! caller's release stay. The crate's device tests release them at once, whatever their -//! windows (`tests/host_residency.rs`). +//! import no command buffer holds, even weakly (every one that read it completed) and that no +//! blit took for its window, [`IDLE`] at first and doubled at each import again, up to +//! [`IDLE_MOST`], so an import used now and then stays imported and an unused one goes. Its +//! `VkBuffer` is destroyed and its memory freed; the buffer, its Metal address, its host pages, +//! the dma-bufs and the caller's release stay. The crate's device tests release them at once, +//! whatever their windows (`tests/host_residency.rs`, `tests/pointer_residency.rs`). The doubling +//! bounds the churn whatever the program's pattern: an import is made again at most five times +//! before its window reaches [`IDLE_MOST`], and at most once per such window after. +//! - **The import going** (its last buffer released) lets go of its objects, and the caller's //! - **Imported again at the next blit,** on the encoding thread, before its command reads the -//! `VkBuffer`: from the dma-bufs kept, never from the source again, so the buffer lies over the -//! pages it was made over even where `host_range_remapped` told the device they were replaced -//! since, as a buffer made before that call keeps its pages. A dma-buf holds its pages for as -//! long as it is open, and adds nothing to a submission's list until it is imported. The new -//! `VkBuffer` lies at the same offsets in the same memory type; its device address may differ, -//! which no shader saw. Bytes the CPU wrote through `contents` meanwhile are in those pages, and -//! so read. Counted (`WorkCounts::host_imports_reimported`); refused where the device cannot -//! import them again (out of memory), which the blit's call returns. +//! `VkBuffer`. A dma-buf import from the dma-bufs kept, never from the source again, so the +//! buffer lies over the pages it was made over even where `host_range_remapped` told the device +//! they were replaced since, as a buffer made before that call keeps its pages; a dma-buf holds +//! its pages for as long as it is open, and adds nothing to a submission's list until it is +//! imported. A pointer import at its pointer, over the pages mapped there now, which the kept +//! import would read too. The new `VkBuffer` lies at the same offsets in the same memory type; +//! its device address may differ, which no shader saw. Bytes the CPU wrote through `contents` +//! meanwhile are in those pages, and so read. Counted (`WorkCounts::host_imports_reimported`); +//! refused where the device cannot import them again (a dma-buf's: out of memory; a pointer's: +//! as its first import may be, typed as the import answers), which the blit's call returns. //! - **Exact.** What the buffer holds is its host pages, which a release never touches; its //! commands order by its key, as before; Metal's reach of it unnamed needs its Metal address, //! which a releasable buffer never handed out (`live_buffers.rs` holds its range only where //! it may be stale, and lists it again at its exposure). A read that keeps it imported finds it //! released only where its address was never handed out: it imports it again first. //! - **Counted.** `WorkCounts::host_imports_released`, `host_imports_reimported`, -//! `host_imports_resident` (releasable imports holding their memory now) and -//! `host_import_fds_kept`; the device's dma-buf memories (`dma_buf_memories_live`) fall as -//! imports are released. +//! `host_imports_resident` (releasable imports holding their memory now), +//! `host_import_fds_kept`, and `host_imports_kept_for_fds` (imports kept as their descriptors +//! did not fit); the device's dma-buf memories (`dma_buf_memories_live`) and its +//! imports of host pages by their pointer (`host_imports_live`) fall as imports are released. use super::buffer::{FixedPages, HostImport, Pages, Shape}; use super::device::lock; @@ -63,7 +75,9 @@ use super::exit_guard; use super::host_memory::ImportWindow; use super::memory::MemoryClass; use super::Device; +use metal2vulkan::device::DriverFact; use std::os::fd::OwnedFd; +use std::ptr::NonNull; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex, OnceLock, PoisonError, Weak}; use std::thread::JoinHandle; @@ -118,26 +132,43 @@ fn now_ms() -> u64 { START.get_or_init(Instant::now).elapsed().as_millis() as u64 } -/// What imports a releasable import again: a descriptor of each dma-buf its source made, and -/// what the import was made of. The source stays for the textures over its bytes, which ask it -/// for dma-bufs of their own (`Device::dma_buf_image`), never for the import's again. +/// What imports a releasable import again (the module docs): what it was made of, and the +/// buffer's length, its window in the pages and its memory class. pub(super) struct Again { device: Device, - /// The dma-bufs, in order, with their lengths: duplicates of those the device imported. - pub(super) chunks: Vec<(OwnedFd, u64)>, - pub(super) source: DmaBufSource, - pub(super) request: DmaBufRequest, - /// The buffer's length, its window in the pages and its memory class. + pub(super) from: AgainFrom, pub(super) length: u64, pub(super) window: ImportWindow, pub(super) class: MemoryClass, } +/// What an import is made again of. +pub(super) enum AgainFrom { + /// A descriptor of each dma-buf its source made, in order, with their lengths: duplicates of + /// those the device imported. The source stays for the textures over its bytes, which ask it + /// for dma-bufs of their own (`Device::dma_buf_image`), never for the import's again. + DmaBufs { + chunks: Vec<(OwnedFd, u64)>, + source: DmaBufSource, + request: DmaBufRequest, + }, + /// The pointer its pages were imported at, on a driver whose pointer imports follow their + /// address. + Pointer(ImportedAt), +} + +/// The pointer a pointer import was made at. +pub(super) struct ImportedAt(pub(super) NonNull); + +// SAFETY: an address, which the residency hands to the driver to import again and never reads +// through; the caller's pages stay mapped there while the buffer lives (`HostMemory::new`). +unsafe impl Send for ImportedAt {} + impl Again { /// `chunks` kept, counted against the process's [`kept_fds_limit`] and the device's cap /// (only the crate's device tests cap it): `None`, the descriptors closed, where they do not /// fit, so that the import stays imported. - pub(super) fn new( + pub(super) fn dma_bufs( device: &Device, chunks: Vec<(OwnedFd, u64)>, source: DmaBufSource, @@ -156,9 +187,31 @@ impl Again { } Some(Again { device: device.clone(), - chunks, - source, - request, + from: AgainFrom::DmaBufs { + chunks, + source, + request, + }, + length, + window, + class, + }) + } + + /// The pages imported at `pointer`, made again there: `None` where the device's driver may + /// keep the pages a pointer import was made over + /// (`DriverFact::PointerImportsFollowTheirAddress` not measured of it), so that the import + /// stays imported. + pub(super) fn pointer( + device: &Device, + pointer: NonNull, + (length, window, class): (u64, ImportWindow, MemoryClass), + ) -> Option { + let follows = (device.properties().driver_facts) + .contains(&DriverFact::PointerImportsFollowTheirAddress); + follows.then(|| Again { + device: device.clone(), + from: AgainFrom::Pointer(ImportedAt(pointer)), length, window, class, @@ -168,7 +221,10 @@ impl Again { impl Drop for Again { fn drop(&mut self) { - let count = self.chunks.len() as u64; + let AgainFrom::DmaBufs { chunks, .. } = &self.from else { + return; + }; + let count = chunks.len() as u64; self.device.shared().counts.host_import_fds_closed(count); KEPT_FDS.fetch_sub(count, Ordering::AcqRel); } @@ -186,7 +242,6 @@ impl Drop for Imported { fn drop(&mut self) { // SAFETY: no pending command buffer uses them: each that read them holds them until it // completed, and no other read reached a releasable import (the module docs). - drop(unsafe { self.pages.release_import(&self.device, None) }); } } @@ -232,10 +287,7 @@ impl Residency { shape: Shape::of(&pages), device: device.clone(), state: Mutex::new(State { - held: Some(Arc::new(Imported { - device: device.clone(), - pages, - })), + held: Some(Arc::new(Imported::new(device, pages))), again: Some(again), window: IDLE.as_millis() as u64, released_once: false, @@ -313,9 +365,10 @@ impl Residency { return None; } let held = state.held.as_ref()?; - // A command buffer whose blit read it holds it until it completed; an exposing read - // holds it while it reads, under this lock. - if Arc::strong_count(held) > 1 { + // A command buffer whose blit read it holds it until it completed, weakly from its commit + // to its first submission (`rebind::ImportHold`); an exposing read holds it while it + // reads, under this lock. + if Arc::strong_count(held) > 1 || Arc::weak_count(held) > 0 { return None; } let idle = now.saturating_sub(self.used.load(Ordering::Relaxed)); @@ -329,21 +382,27 @@ impl Residency { state.held.take() } - /// Import it again from its dma-bufs (`Device::import_again`), under `state`'s lock, its - /// window doubled: its objects. Refused where released for good, where the device cannot, - /// and where it lays the bytes otherwise than the first import (an internal error: the same - /// dma-bufs, length and window). + /// Import it again from its dma-bufs (`Device::import_dma_bufs_again`) or at its pointer + /// (`Device::import_pointer_again`), under `state`'s lock, its window doubled: its objects. + /// Refused where released for good, where the device cannot, and where it lays the bytes + /// otherwise than the first import (an internal error: the same pages, length and window). fn import_again(&self, state: &mut State) -> Result, Error> { let again = state .again .as_ref() - .ok_or_else(|| internal("an import released without its dma-bufs"))?; - let pages = self.device.import_again(again)?; + .ok_or_else(|| internal("an import released without what imports it again"))?; + let pages = match &again.from { + AgainFrom::DmaBufs { + chunks, + source, + request, + } => self + .device + .import_dma_bufs_again(chunks, source, *request, again)?, + AgainFrom::Pointer(at) => self.device.import_pointer_again(at.0, again)?, + }; let laid = Shape::of(&pages); - let held = Arc::new(Imported { - device: self.device.clone(), - pages, - }); + let held = Arc::new(Imported::new(&self.device, pages)); if !laid.same(&self.shape) { // Freed at once: nothing read them. drop(held); @@ -359,14 +418,7 @@ impl Residency { } impl Residency { - /// Let go of its objects, the import going: freed now, or with the last command buffer that - /// read them. - pub(super) fn let_go(&self) { - let held = lock(&self.state).held.take(); - if held.is_some() { - self.device.shared().counts.host_import_resident(false); - } - drop(held); + self.device.shared().counts.host_import_resident(false); } } diff --git a/crates/metal2vulkan-runtime/src/interop.rs b/crates/metal2vulkan-runtime/src/interop.rs index f0fbdcf1a..b7edf0881 100644 --- a/crates/metal2vulkan-runtime/src/interop.rs +++ b/crates/metal2vulkan-runtime/src/interop.rs @@ -18,6 +18,7 @@ //! refuses what it can tell is no binary semaphore of the device: a null handle, and its own //! timeline semaphores (events' and queues'). Every other contract is the caller's. +use super::buffer::ReadApart; use super::device::relay::By; use super::event::EventRef; use super::texture::wrapped::Wrapped; @@ -151,7 +152,7 @@ impl Buffer { /// The `VkBuffer` stays the runtime's: the caller does not destroy it, and uses it only while /// the buffer lives, ordered against the runtime's work on it. pub unsafe fn vk_buffer(&self) -> (vk::Buffer, u64) { - self.at(0) + self.at_for(0, ReadApart::VkBuffer) } } diff --git a/crates/metal2vulkan-runtime/src/live_buffers.rs b/crates/metal2vulkan-runtime/src/live_buffers.rs index 4d45467b7..50f206296 100644 --- a/crates/metal2vulkan-runtime/src/live_buffers.rs +++ b/crates/metal2vulkan-runtime/src/live_buffers.rs @@ -102,6 +102,9 @@ struct Inner { listed: SortedChunks, /// Bumped by each change of what the table lists. generation: u64, + /// Bumped by each rebind or detach ([`LiveBuffers::rebound`]): a listing whose pages were + /// read before one is read again ([`LiveBuffers::register`]). + rebinds: u64, /// The table of the current generation, once made: dropped at the next change, so a gone /// buffer's pages go with the last command buffer that holds an older table. It holds the /// device only while a listed buffer lives, which holds it too. @@ -175,23 +178,38 @@ impl LiveBuffers { } } - /// List `buffer`, unless it is: a change of the list only where it was not. + /// List `buffer`, unless it is: a change of the list only where it was not. Its pages are + /// read with no lock held, so a rebind or detach of them meanwhile ([`rebound`](Self::rebound), + /// which follows the swap of its pages) has them read again: else the list would hold the + /// pages it let go of until the buffer goes, and their deallocator with them. fn register(&self, buffer: &Buffer) { let key = (buffer.metal_address().0, buffer.object_id()); - if lock(&self.inner).listed.contains(&key) { + loop { + let rebinds = { + let inner = lock(&self.inner); + if inner.listed.contains(&key) { + return; + } + inner.rebinds + }; + // Its range and pages, asked once, with no lock held. + let listed = Listed { + buffer: buffer.downgrade(), + length: buffer.length(), + resident: buffer.resident(), + }; + let mut inner = lock(&self.inner); + if inner.rebinds != rebinds { + // Dropped with no lock held, as `let_go` drops: it may hold the old pages last. + drop(inner); + drop(listed); + continue; + } + let stale = inner.listed.insert(key, listed).then(|| inner.change()); + drop(inner); + self.let_go(stale); return; } - // Its range and pages, asked once, with no lock held. - let listed = Listed { - buffer: buffer.downgrade(), - length: buffer.length(), - resident: buffer.resident(), - }; - let stale = { - let mut inner = lock(&self.inner); - inner.listed.insert(key, listed).then(|| inner.change()) - }; - self.let_go(stale); } /// `buffer`'s import was released while idle and imported again before its Metal address was @@ -235,6 +253,7 @@ impl LiveBuffers { }; let stale = { let mut inner = lock(&self.inner); + inner.rebinds = inner.rebinds.wrapping_add(1); let mut listed = Vec::new(); for buffer in &gone { let key = (buffer.metal_address().0, buffer.object_id()); diff --git a/crates/metal2vulkan-runtime/src/rebind.rs b/crates/metal2vulkan-runtime/src/rebind.rs index c4491b5f8..77be3520b 100644 --- a/crates/metal2vulkan-runtime/src/rebind.rs +++ b/crates/metal2vulkan-runtime/src/rebind.rs @@ -30,6 +30,11 @@ //! them after the rebind would be neither order. A command buffer committed with commands the //! runtime records only once earlier work completed (executions of an indirect command buffer //! the GPU writes) counts as uncommitted until it completed. +//! - **The new pages' import.** New memory that is the bytes a live no-copy buffer was made over, +//! of its memory class, lies in that buffer's import, as a buffer made over them does +//! (`host_aliases.rs`): the rebind imports nothing, pins no page and asks the kernel about no +//! mapping (`WorkCounts::host_mappings_queried`). A heap's, and a buffer's with a texture's +//! aliasing image over its bytes, import their new memory themselves. //! - **The deallocators.** The old range's runs once every command buffer first submitted //! before the rebind that used it completed (at the rebind where none holds it: a command //! buffer not yet submitted holds its pages weakly); the new range's at the next rebind's turn, @@ -495,6 +500,15 @@ impl Submitting<'_> { retained.push(Box::new(pages)); } } + // A blit's objects of a releasable import, held until it completes. Gone only with their + // import, as a rebind or a detach replaced its buffer's pages, which a pin above found + // moved: the recording that named them runs nothing. + for hold in taken.imports.drain(..) { + match hold.retained() { + Some(held) => retained.push(held), + None => found.moved = true, + } + } // `cell` and `now` drop here, under the lock: never the last hold of anything (above). found } @@ -595,6 +609,8 @@ pub(super) enum Pinned { #[derive(Default)] pub(super) struct Taken { pins: Vec<(ResourceKey, Pinned)>, + /// The objects of releasable imports its blits took ([`ImportHold`]). + imports: Vec, named: BTreeSet, resolved: Vec, /// A command named a detached buffer, and the encoder recorded nothing from it on @@ -602,7 +618,50 @@ pub(super) struct Taken { dead: bool, } +/// The objects of a releasable import a blit's command took (`Buffer::blit_at`, +/// `host_residency.rs`): held while its encoder records, weakly from the commit until the command +/// buffer's first submission, as its pages are, then until it completes. Held weakly, they keep +/// the device's residency from releasing them (the committed recording names their `VkBuffer`), +/// but not the import from going with its buffer's pages (a rebind, a detach), as Metal holds +/// nothing of a command buffer not yet submitted: their free, and the deallocator after it, run +/// in that call, and the recording that named them never runs (its pin of the pages moved). +pub(super) enum ImportHold { + #[cfg(unix)] + Held(Arc), + #[cfg(unix)] + Waiting(Weak), +} + +impl ImportHold { + /// Held weakly from now on. + fn wait(&mut self) { + match self { + #[cfg(unix)] + ImportHold::Held(held) => *self = ImportHold::Waiting(Arc::downgrade(held)), + #[cfg(unix)] + ImportHold::Waiting(_) => {} + } + } + + /// The objects, held until the command buffer completes: `None` where they went. + fn retained(self) -> Option> { + match self { + #[cfg(unix)] + ImportHold::Held(held) => Some(Box::new(held)), + #[cfg(unix)] + ImportHold::Waiting(held) => held + .upgrade() + .map(|held| Box::new(held) as Box), + } + } +} + impl Taken { + /// Note `hold`, the objects of a releasable import a blit took. + pub(super) fn hold_import(&mut self, hold: ImportHold) { + self.imports.push(hold); + } + /// Note `pinned`, what a command took of the buffer of `key`. pub(super) fn pin(&mut self, key: ResourceKey, pinned: Pinned) { self.pins.push((key, pinned)); @@ -667,6 +726,9 @@ impl Taken { *pinned = Pinned::Waiting(Arc::downgrade(pages)); } } + for hold in &mut self.imports { + hold.wait(); + } } /// Its named keys and resolved ranges let go, once judged (`Submitting::submit`). @@ -686,6 +748,7 @@ impl Taken { Pinned::Detached => None, }); retained.extend(live.map(|pages| Box::new(pages) as Box)); + retained.extend(self.imports.drain(..).filter_map(ImportHold::retained)); self.named.clear(); self.resolved.clear(); } diff --git a/crates/metal2vulkan-runtime/src/recorder/mod.rs b/crates/metal2vulkan-runtime/src/recorder/mod.rs new file mode 100644 index 000000000..2531cc586 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/recorder/mod.rs @@ -0,0 +1,6 @@ +//! ([`RecorderShared::settle_all`]), and a commit whose pages' buffer let go of them (released +//! or detached while an encoder took them, on any thread) replays its command buffer itself, +//! so the pages' deallocator runs in the call it runs in without a recorder. Each marks its +//! side, then reads the other's, so a let-go and a commit that race agree on which replays +//! (`HostPages::let_go_by_buffer`). Its release (completion, failure, drop) lets go of the +//! rest, after any replay in progress, replaying nothing more. diff --git a/crates/metal2vulkan-runtime/src/recorder/replays.rs b/crates/metal2vulkan-runtime/src/recorder/replays.rs new file mode 100644 index 000000000..9e87e47e1 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/recorder/replays.rs @@ -0,0 +1,88 @@ + /// Held through each [`settle_all`](Self::settle_all), so one finds the replays another + /// took off the queue replayed. + settling: Mutex<()>, + settling: Mutex::default(), + let replayed = replays.drain(functions.get(), true); + /// it is in, and for another thread's settle: what the release, rebind or detach of host + /// pages that replays hold does first, so the replays let go of them before it + /// (`HostPages::let_go_by_buffer`). Once the process exits, what ended is dropped + /// unreplayed instead ([`Replays::replay_ended`]). + pub(crate) fn settle_all(&self, device: &Vk) { + let _settling = lock(&self.settling); + replayed += replays.drain(device, true); + replayed += replays.drain(device, false); + /// ended waits for its replay: an encoder encoded again before its command buffer's first + /// submission (`reencode.rs`). As at the commit ([`commit`](Self::commit)), the pages it held + /// last are the answer, for the caller to let go of where it lets go of them without a + /// recorder. `fill` runs under its lock, which it must not take again. + pub(crate) fn hold( + self: &Arc, + device: &Vk, + fill: impl FnOnce(&mut Vec>), + ) -> Vec { + self.settle(device, &mut state) + /// which it must not take again. + /// Where the buffer of some of those pages let go of them (released, rebound or detached + /// while an encoder took them, on any thread), the commit would let go of them last without + /// a recorder: what ended replays now, on this thread, with `device`, the device's + /// functions. The pages it held last are the answer, for the caller to let go of where the + /// commit lets go of them without a recorder. Nothing as a rule. + let mut state = lock(&self.state); + Self::fill(&mut state, fill); + state.open = true; + self.settle(device, &mut state) + } + + /// What `state` holds once its command buffer committed (nothing before), under its lock: + /// queued for the recorder where something ended waits, then each page's buffer's let-go + /// read, after its hold was counted and the replays queued, so a let-go after the read finds + /// both (`HostPages::let_go_by_buffer`). Where one came before, everything ended replays now, + /// on this thread, with `device`; where nothing ended waits, what it holds goes now. The + /// pages it held last are the answer. + fn settle(self: &Arc, device: &Vk, state: &mut ReplayState) -> Vec { + if !state.open { + return last; + } + if !state.ended.is_empty() { + if !state.queued { + if state.held.iter().any(|pages| pages.buffer_let_go()) { + let replayed = self.replay_ended(device, state); + self.recorder + .by_submitter + .fetch_add(replayed, Ordering::Relaxed); + } + } + if state.ended.is_empty() { + self.let_go(state, Some(&mut last)); + /// Add what `fill` adds to what `state` holds, counted in each page's holds. + fn fill(state: &mut ReplayState, fill: impl FnOnce(&mut Vec>)) { + /// thread (`queued`, which it takes off), a submitting one, or one that settles, with + fn drain(&self, device: &Vk, queued: bool) -> u64 { + let replayed = self.replay_ended(device, &mut state); + // Nothing ended waits now: what it held for the replays goes. + if state.open { + self.let_go(&mut state, None); + } + replayed + } + + /// Replay every ended command buffer of `state` not yet replayed, in the order they ended, + /// inside a section, with `device`, the device's functions: how many. Once the process + /// exits, outside a section, they are dropped unreplayed instead, and their submission fails + /// ([`resolve`]), as a submission does then. + fn replay_ended(&self, device: &Vk, state: &mut ReplayState) -> u64 { + let Some(_busy) = exit_guard::enter() else { + state.ended.clear(); + return 0; + }; + self.replay(device, state, index); + /// Let go of what `state` holds, under its lock, running nothing of the program's. Where + /// `last` is given (a commit's, [`settle`](Self::settle)), the pages held last go to it, + /// for the caller to let go of. Elsewhere none is held last: the release, rebind or detach + /// of pages held here replays first, and a commit after it replays itself + /// (`HostPages::let_go_by_buffer`). Were one held last, it would go on the device's handler + /// threads (`Device::elsewhere`), as its deallocator may run the program's code, which may + /// not run on the recorder's thread nor under a submission's locks: announced there + /// (`HeldByReplay`). + let Some(pages) = HostPages::let_go_by_replay(pages) else { + let replayed = replays.drain(device, false); diff --git a/crates/metal2vulkan-runtime/src/residency.rs b/crates/metal2vulkan-runtime/src/residency.rs index 208ec2396..36834a715 100644 --- a/crates/metal2vulkan-runtime/src/residency.rs +++ b/crates/metal2vulkan-runtime/src/residency.rs @@ -63,7 +63,7 @@ //! a tile dispatch only where they hold the tile stage. A compute encoder names none, and its //! dispatches reach every resource it made resident. -use super::buffer::Buffer; +use super::buffer::{Buffer, ReadApart}; use super::heap::Heap; use super::indirect_command_buffer::IndirectCommandBuffer; use super::live_buffers::LiveTable; @@ -475,7 +475,7 @@ fn same(a: &Used, b: &Used) -> bool { fn stated(buffer: &Buffer, class: ResourceClass, token: u32) -> UsedResource { let base = buffer.base(); let mut used = UsedResource::new(class, token); - used.gpu_address = Some(buffer.gpu_address().0 - base); + used.gpu_address = Some(buffer.exposed_address(ReadApart::Binding).0 - base); used.length = base + buffer.length(); // A detached buffer's bytes are in no pages: an address reaching them misses and reads 0, as // Metal's unnamed reach of a detached buffer does (`detach.rs`), never the stand-in's. diff --git a/crates/metal2vulkan-runtime/src/resource_ids.rs b/crates/metal2vulkan-runtime/src/resource_ids.rs index 13acc72dc..f56adfcbb 100644 --- a/crates/metal2vulkan-runtime/src/resource_ids.rs +++ b/crates/metal2vulkan-runtime/src/resource_ids.rs @@ -414,9 +414,9 @@ impl ResourceIds { self.textures.plain.make(); } - /// Change every texture slot's generation, its holder kept: a rebind of host pages remade - /// images or emptied texel views a slot's elements were written with, so the device writes - /// them again (`heap_sets::renew`). + /// Change every texture slot's generation, its holder kept: a change of storage form swapped + /// in images a slot's elements were written with, so the device writes them again + /// (`heap_sets::renew`). pub(super) fn renew_textures(&mut self) { let generation = self.next(); for slot in self.textures.slots.values_mut() { diff --git a/crates/metal2vulkan-runtime/src/tests/host_aliases.rs b/crates/metal2vulkan-runtime/src/tests/host_aliases.rs index 84bd0c068..897811791 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_aliases.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_aliases.rs @@ -5,6 +5,7 @@ use super::super::memory::MemoryClass; use super::super::resource::ResourceKey; use super::super::tracker::{Access, Use, UseRange}; use ash::vk; +use std::collections::BTreeMap; use std::sync::Arc; /// The registry, its imports stood in for by numbers. @@ -143,6 +144,54 @@ fn a_buffer_over_the_bytes_another_covers_lies_in_its_import() { drop((again, own)); } +/// The host page of the tests that name none of their own: an import's unit. +const PAGE: u64 = 0x1000; + +/// A reported remap counts the ranges placed buffers lie over that have a page among its bytes +/// rounded out to the import's unit, with or without memories noted: none for bytes beside +/// them, one for a byte of a page one lies on, and none at all with nothing placed. +#[test] +fn a_reported_remap_counts_the_placed_ranges_it_touches() { + let aliases = Aliases::default(); + assert_eq!(aliases.remapped(0, u64::MAX, PAGE), 0, "nothing placed"); + let (first, second, third) = (ResourceKey::new(), ResourceKey::new(), ResourceKey::new()); + aliases.place(first, (0x40000, 0x8000)); + // A second key over the same bytes: one range, one import. + aliases.place(second, (0x40000, 0x8000)); + // Bytes in the middle of a page past the first range's. + aliases.place(third, (0x50010, 0x20)); + assert_eq!( + aliases.remapped(0x30000, 0x40000, PAGE), + 0, + "the pages before" + ); + assert_eq!( + aliases.remapped(0x48000, 0x50000, PAGE), + 0, + "the pages between" + ); + assert_eq!(aliases.remapped(0x44000, 0x44001, PAGE), 1, "a byte inside"); + // A byte of the third's page that is not one of its bytes: its page is replaced all the same. + assert_eq!( + aliases.remapped(0x50800, 0x50900, PAGE), + 1, + "a byte of its page" + ); + assert_eq!(aliases.remapped(0x50800, 0x50900, 1), 0, "not its bytes"); + assert_eq!(aliases.remapped(0x3f000, 0x51000, PAGE), 2, "both"); + // A remap keeps the placements: the same bytes count again. + assert_eq!(aliases.remapped(0x44000, 0x45000, PAGE), 1, "again"); + aliases.unplace(first); + assert_eq!( + aliases.remapped(0x44000, 0x45000, PAGE), + 1, + "one key left there" + ); + aliases.forget(second); + aliases.forget(third); + assert_eq!(aliases.remapped(0, u64::MAX, PAGE), 0, "all gone"); +} + /// After the caller reports a remap of any byte of a memory, a later buffer over it lies in no /// import made before and joins no earlier key; the buffers made before keep the key they /// joined, and forgetting them later leaves the new buffer's memory alone. A remap of other @@ -162,11 +211,11 @@ fn a_reported_remap_ends_the_sharing_of_imports_made_before() { Some(Alias { key: first }) ); // Bytes next to the memory, on either side: nothing changes. - aliases.remapped(0x30000, 0x40000); - aliases.remapped(0x48000, 0x50000); + aliases.remapped(0x30000, 0x40000, PAGE); + aliases.remapped(0x48000, 0x50000, PAGE); assert!(aliases.import(memory, MemoryClass::Shared).is_some()); // One page inside the memory: its import is shared no more. - aliases.remapped(0x44000, 0x45000); + aliases.remapped(0x44000, 0x45000, PAGE); assert!(aliases.import(memory, MemoryClass::Shared).is_none()); // A buffer made after imports anew and joins nothing; the second keeps the key it joined. let fresh = Arc::new(2); @@ -339,8 +388,8 @@ fn remaps_from_any_thread_keep_the_notes_whole() { let mut round = 0; while !done.load(std::sync::atomic::Ordering::SeqCst) { let (start, length) = memory(round); - aliases.remapped(start + PAGE / 2, start + length); - aliases.remapped(0, u64::MAX); + aliases.remapped(start + PAGE / 2, start + length, PAGE); + aliases.remapped(0, u64::MAX, PAGE); round += 1; } }); @@ -486,6 +535,185 @@ fn a_sample_through_a_second_key_waits_for_a_render_through_the_first() { ); } +/// A use of a range a few others meet reads them from what its range keeps, looking none up by +/// address (`WorkCounts::host_range_lookups`), as a draw's uses of the consumer's buffers over +/// one stretch of its pages do draw after draw; a use of a range met by more than the classes of +/// length the lookup visits looks them up, and takes the same uses. +#[test] +fn a_use_reads_the_ranges_its_range_keeps_while_few() { + let aliases = Aliases::default(); + let (whole, indices, rects) = (ResourceKey::new(), ResourceKey::new(), ResourceKey::new()); + // Three classes of length: a page, two pages and three (up to four). + aliases.place(whole, (0x10_0000, 0x3000)); + aliases.place(indices, (0x10_0000, 0x1000)); + aliases.place(rects, (0x10_1000, 0x2000)); + let uses = [sample(indices, 0x100..0x200), sample(rects, 0..0x2000)]; + let carried = vec![ + uses[0].clone(), + uses[1].clone(), + sample(whole, 0x100..0x200), + sample(whole, 0x1000..0x3000), + ]; + for _ in 0..100 { + assert_eq!(aliases.augment(&uses), Some(carried.clone())); + } + // The whole range, met by two ranges, reads them too, in the lookup's order. + let all = [write(whole, 0..0x3000)]; + let met = vec![ + all[0].clone(), + write(indices, 0..0x1000), + write(rects, 0..0x2000), + ]; + assert_eq!(aliases.augment(&all), Some(met)); + assert_eq!(aliases.range_lookups(), 0); + // Four quarter pages more inside it, a fourth class: met by six ranges, more than the four + // classes, it looks them up; each quarter page, met by two, reads them. + let quarters: Vec = (0..4).map(|_| ResourceKey::new()).collect(); + for (quarter, &key) in (0..4u64).zip(&quarters) { + aliases.place(key, (0x10_0000 + quarter * 0x800, 0x400)); + } + assert_eq!( + aliases.augment(&[write(whole, 0x1800..0x1c00)]), + Some(vec![ + write(whole, 0x1800..0x1c00), + write(quarters[3], 0..0x400), + write(rects, 0x800..0xc00), + ]) + ); + assert_eq!(aliases.range_lookups(), 1); + assert_eq!( + aliases.augment(&[sample(quarters[1], 0..0x400)]), + Some(vec![ + sample(quarters[1], 0..0x400), + sample(indices, 0x800..0xc00), + sample(whole, 0x800..0xc00), + ]) + ); + assert_eq!(aliases.range_lookups(), 1); +} + +/// The class of length `length` as the lookup by address orders ranges (`host_aliases::class`): +/// the least `b` with `length <= 2^b`. +fn class_of(length: u64) -> u32 { + u64::BITS - length.saturating_sub(1).leading_zeros() +} + +/// A model of the placements: each range of bytes by its first byte and length, with its key, +/// how many keys lie over it, and whether its key does. +type Model = BTreeMap<(u64, u64), (ResourceKey, usize, bool)>; + +/// `key`, which lay over `was`, lies over no bytes in `model` from now on. +fn model_unplace(model: &mut Model, key: ResourceKey, was: Option<(u64, u64)>) { + let Some(was) = was else { + return; + }; + let range = model.get_mut(&was).expect("a placed key's range"); + range.1 -= 1; + if range.0 == key { + range.2 = false; + } + if range.1 == 0 { + model.remove(&was); + } +} + +/// The uses a use of `bytes` of `key`, over `own`, takes beside its own in `model`: its range's +/// key where another, and the key of each other range its bytes meet, clipped, in the lookup's +/// order; none where its range is not crowded. +fn model_sharing( + model: &Model, + key: ResourceKey, + own: (u64, u64), + bytes: std::ops::Range, +) -> Vec> { + let (range_key, count, first) = model[&own]; + let end = own.0 + own.1; + let meets = |other: &(u64, u64)| *other != own && other.0 < end && own.0 < other.0 + other.1; + let mut taken = Vec::new(); + if count == 1 && first && !model.keys().any(meets) { + return taken; + } + if range_key != key { + taken.push(write(range_key, bytes.clone())); + } + let (from, to) = (own.0 + bytes.start.min(own.1), own.0 + bytes.end.min(own.1)); + let mut others: Vec<(&(u64, u64), &(ResourceKey, usize, bool))> = + model.iter().filter(|(other, _)| meets(other)).collect(); + others.sort_by_key(|(other, _)| (class_of(other.1), other.0, other.1)); + for (other, (other_key, _, _)) in others { + let (lo, hi) = (from.max(other.0), to.min(other.0 + other.1)); + if lo < hi { + taken.push(write(*other_key, lo - other.0..hi - other.0)); + } + } + taken +} + +/// Keys placed, rebound and removed at random over overlapping ranges of many lengths: each use +/// takes exactly the uses a reading of every range gives ([`model_sharing`]), whether its +/// range's company was read from what the range keeps or looked up by address, and both ran. +#[test] +fn a_use_takes_the_ranges_its_bytes_meet_kept_or_looked_up() { + const PAGE: u64 = 0x1000; + const BASE: u64 = 0x7000_0000_0000; + let mut state = 0x2545_f491_4f6c_dd1d_u64; + let mut next = move |below: u64| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % below + }; + let aliases = Aliases::default(); + let keys: Vec = (0..48).map(|_| ResourceKey::new()).collect(); + let mut at: Vec> = vec![None; keys.len()]; + let mut model = Model::new(); + let (mut kept, mut looked_up) = (0, 0); + for round in 0..4000 { + let index = next(keys.len() as u64) as usize; + let key = keys[index]; + match next(8) { + 0 => { + model_unplace(&mut model, key, at[index].take()); + aliases.unplace(key); + } + 1..=2 => { + let class = next(7); + let length = (1 + next(1 << class)) * PAGE; + let place = (BASE + next(192) * PAGE, length); + model_unplace(&mut model, key, at[index].take()); + model.entry(place).or_insert((key, 0, true)).1 += 1; + at[index] = Some(place); + aliases.place(key, place); + } + _ => {} + } + let Some(own) = at[index] else { + continue; + }; + let start = next(own.1 + PAGE); + let bytes = start..start + next(own.1 + PAGE); + let uses = [write(key, bytes.clone())]; + let taken = model_sharing(&model, key, own, bytes); + let met = model + .keys() + .filter(|other| **other != own && other.0 < own.0 + own.1 && own.0 < other.0 + other.1) + .count(); + let expected: Option>> = + (!taken.is_empty()).then(|| uses.iter().cloned().chain(taken).collect()); + let before = aliases.range_lookups(); + assert_eq!(aliases.augment(&uses), expected, "round {round}"); + match aliases.range_lookups() - before { + 0 if met > 0 => kept += 1, + 0 => {} + _ => looked_up += 1, + } + } + assert!( + kept > 100 && looked_up > 100, + "kept {kept}, looked up {looked_up}" + ); +} + /// The version counts each change of what `augment` reads: a buffer joining another's memory, /// a key placed, rebound or unplaced, a buffer forgotten. A buffer over a memory of its own, a /// rebound buffer leaving its memory, a reported remap, and `augment` itself change nothing it @@ -502,6 +730,7 @@ fn the_version_counts_each_change_augment_reads() { assert!(joined > version, "joined"); aliases.augment(&[write(second, 0..64)]); aliases.leave(second); + aliases.remapped(0x40000, 0x41000, PAGE); assert_eq!(aliases.version(), joined, "augment, leave and a remap"); let mut last = joined; let mut changed = |what: &str| { diff --git a/crates/metal2vulkan-runtime/src/tests/host_import_counts.rs b/crates/metal2vulkan-runtime/src/tests/host_import_counts.rs new file mode 100644 index 000000000..bd7020e79 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/host_import_counts.rs @@ -0,0 +1,372 @@ +//! The counts of no-copy buffers' host imports that a release while idle would weigh +//! (`WorkCounts::host_imports_used`, `WorkCounts::host_imports_read_apart`): the imports each +//! committed command buffer's commands use, each counted once per command buffer however many +//! buffers lie in it, and the live imports a read other than a blit's took, each also counted +//! once for each reason it was read apart for (`host_imports_read_apart_*`). Blits read none +//! apart: a copy with a texture, a two-plane texture's or a texture over a buffer's, included. +//! Each new import is either kept imported for its cause (`host_imports_kept_*`) or releasable. +//! Each import by pointer counts with its bytes (`host_pointer_imports_made`), and a reported +//! remap counts the live imports it touches (`host_remaps_over_imports`, `host_imports_remapped`). +//! A rebind's import counts as made, as covered where bytes a buffer lay over already held its +//! pages (`host_rebind_imports_made`, `host_rebind_imports_covered`), and as unlisted until a +//! command buffer that uses it commits (`host_imports_rebound_unlisted`). +//! +//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`), on the kind of device the cfg selects. A device that imports no host memory +//! says so and passes. + +use super::blit_holds::{device, over_host, until, Host, Scratch, BYTES}; +use crate::{ + BlitOption, Buffer, CommandBufferStatus, CommandQueue, Device, Error, Origin, ResourceOptions, + Size, Texture, TextureDescriptor, WorkCounts, +}; +use metal2vulkan::metal::{PixelFormat, TextureUsage}; +use std::ptr::NonNull; +use std::sync::atomic::AtomicUsize; +use std::sync::Arc; + +/// The two counts and the live imports. +fn counts(device: &Device) -> (u64, u64, u64) { + let counts = device.work_counts(); + ( + counts.host_imports_used, + counts.host_imports_read_apart, + counts.host_imports_live, + ) +} + +/// Commit what `encode` records into one blit encoder, and wait for it. +fn blits(queue: &CommandQueue, encode: impl FnOnce(&mut crate::BlitCommandEncoder)) { + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + encode(&mut blit); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed().unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); +} + +#[test] +fn a_command_buffer_counts_each_import_it_uses_once_and_blits_never_read_apart() { + let scratch = Scratch::new("import-counts"); + let (first, second, third) = (Host::new(), Host::new(), Host::new()); + let device = device(&scratch.0); + let queue = device.new_command_queue().unwrap(); + let runs = Arc::new(AtomicUsize::new(0)); + let (used, apart, before) = counts(&device); + let Some(a) = over_host(&device, &first, &runs) else { + return; + }; + let b = over_host(&device, &second, &runs).unwrap(); + let c = over_host(&device, &third, &runs).unwrap(); + // Made, three imports, none read apart. + let live = before + 3; + assert_eq!(counts(&device), (used, apart, live)); + + // Blits alone read none apart: three imports used once each. + blits(&queue, |blit| { + blit.fill_buffer(&a, 0..4096, 1).unwrap(); + blit.copy_from_buffer_to_buffer(&b, 0, &c, 0, 4096).unwrap(); + }); + assert_eq!(counts(&device), (used + 3, apart, live)); + + // A buffer over exactly `a`'s bytes lies in its import, which a second buffer reads apart; a + // command buffer using both counts the import once. + let d = over_host(&device, &first, &runs).unwrap(); + assert_eq!(counts(&device), (used + 3, apart + 1, live)); + blits(&queue, |blit| { + blit.fill_buffer(&a, 0..4096, 2).unwrap(); + blit.fill_buffer(&d, 4096..8192, 3).unwrap(); + }); + assert_eq!(counts(&device), (used + 4, apart + 1, live)); + + // Its Metal address handed out reads `b`'s import apart, once however often. + let _ = b.gpu_address(); + let _ = b.gpu_address(); + assert_eq!(counts(&device), (used + 4, apart + 2, live)); + + // The imports that go leave the gauge. + drop((a, b, c, d)); + until("the imports went", || { + let (_, now_apart, now_live) = counts(&device); + (now_apart, now_live) == (apart, before) + }); +} + +/// The reason gauges: the Metal address, the `VkBuffer`, a binding, a texture over the bytes, a +/// second buffer, no releasing thread. +fn reasons(counts: &WorkCounts) -> [u64; 6] { + [ + counts.host_imports_read_apart_address, + counts.host_imports_read_apart_vk_buffer, + counts.host_imports_read_apart_binding, + counts.host_imports_read_apart_texture, + counts.host_imports_read_apart_second_buffer, + counts.host_imports_read_apart_unreleased, + ] +} + +/// The imports kept imported for a cause, and the releasable ones holding their memory. +fn kept_or_resident(counts: &WorkCounts) -> u64 { + counts.host_imports_kept_of_heap + + counts.host_imports_kept_rebound + + counts.host_imports_kept_pointer + + counts.host_imports_kept_no_stand_in + + counts.host_imports_kept_for_fds + + counts.host_imports_resident +} + +/// `base` with `by` added at `reason`. +fn plus(base: [u64; 6], reason: usize, by: u64) -> [u64; 6] { + let mut out = base; + out[reason] += by; + out +} + +#[test] +fn each_read_apart_counts_for_its_reason_once_and_each_import_for_its_keeping() { + let scratch = Scratch::new("import-reasons"); + let hosts = [Host::new(), Host::new(), Host::new(), Host::new()]; + let device = device(&scratch.0); + let runs = Arc::new(AtomicUsize::new(0)); + let before = device.work_counts(); + let Some(a) = over_host(&device, &hosts[0], &runs) else { + return; + }; + let b = over_host(&device, &hosts[1], &runs).unwrap(); + let c = over_host(&device, &hosts[2], &runs).unwrap(); + let d = over_host(&device, &hosts[3], &runs).unwrap(); + // Each new import is kept for its cause, or releasable, holding its memory. + let made = device.work_counts(); + assert_eq!(kept_or_resident(&made), kept_or_resident(&before) + 4); + let base = reasons(&made); + let apart = made.host_imports_read_apart; + + // The Metal address handed out, once however often. + let _ = a.gpu_address(); + let _ = a.gpu_address(); + assert_eq!(reasons(&device.work_counts()), plus(base, 0, 1)); + // The `VkBuffer` handed out. + // SAFETY: only read, while the buffer lives. + let _ = unsafe { b.vk_buffer() }; + let now = plus(plus(base, 0, 1), 1, 1); + assert_eq!(reasons(&device.work_counts()), now); + // A texture over the bytes. + let texture = c + .new_texture(&over_bytes(ResourceOptions::default()), 0, ROW) + .unwrap(); + let now = plus(now, 3, 1); + assert_eq!(reasons(&device.work_counts()), now); + // A second buffer over `d`'s bytes lies in its import. + let e = over_host(&device, &hosts[3], &runs).unwrap(); + let now = plus(now, 4, 1); + assert_eq!(reasons(&device.work_counts()), now); + // Four imports read apart, each once whatever its reasons; `a`'s again for a second reason. + let _ = unsafe { a.vk_buffer() }; + let counts = device.work_counts(); + assert_eq!(reasons(&counts), plus(now, 1, 1)); + assert_eq!(counts.host_imports_read_apart, apart + 4); + + // The imports that go leave every gauge. + drop((texture, a, b, c, d, e)); + until("the imports went", || { + let counts = device.work_counts(); + reasons(&counts) == reasons(&before) + && counts.host_imports_read_apart == before.host_imports_read_apart + && kept_or_resident(&counts) <= kept_or_resident(&before) + }); +} + +/// The rows of a texture of [`BYTES`] of 4-byte texels, 1024 wide. +const ROW: u64 = 4096; + +/// A texture of [`BYTES`] of `RGBA8Unorm` texels, [`ROW`] bytes a row, of `options`, read by +/// shaders: over a buffer's bytes, or the consumer's paged texture where `Private`. +fn over_bytes(options: ResourceOptions) -> TextureDescriptor { + let height = BYTES as u64 / ROW; + let mut descriptor = + TextureDescriptor::texture_2d(PixelFormat::RGBA8Unorm, 1024, height, false); + descriptor.usage = TextureUsage::SHADER_READ; + descriptor.resource_options = options; + descriptor +} + +/// Copy the no-copy `buffer` into `texture` and back in one command buffer each, laid out as +/// `row` bytes a row: the imports used once each time, none read apart. +fn copies_read_none_apart(device: &Device, buffer: &Buffer, texture: &Texture, row: u64) { + let queue = device.new_command_queue().unwrap(); + let (width, height) = (texture.width(), texture.height()); + let (size, origin) = (Size::new(width, height, 1), Origin::new(0, 0, 0)); + let image = row * height; + let (used, apart, live) = counts(device); + blits(&queue, |blit| { + (blit.copy_from_buffer_to_texture( + buffer, + 0, + row, + image, + size, + texture, + 0, + 0, + origin, + BlitOption::None, + )) + .unwrap(); + }); + assert_eq!(counts(device), (used + 1, apart, live)); + blits(&queue, |blit| { + (blit.copy_from_texture_to_buffer( + texture, + 0, + 0, + origin, + size, + buffer, + 0, + row, + image, + BlitOption::None, + )) + .unwrap(); + }); + assert_eq!(counts(device), (used + 2, apart, live)); +} + +#[test] +fn copies_between_a_buffer_and_a_texture_never_read_apart() { + let scratch = Scratch::new("import-texture-copies"); + let host = Host::new(); + let device = device(&scratch.0); + let runs = Arc::new(AtomicUsize::new(0)); + let Some(buffer) = over_host(&device, &host, &runs) else { + return; + }; + // The consumer's paged textures, paged up out of the buffer and down into it. + let texture = device + .new_texture(&over_bytes(ResourceOptions::private())) + .unwrap(); + copies_read_none_apart(&device, &buffer, &texture, ROW); + // A texture over another buffer's bytes: its rows copied buffer to buffer. + let bytes = device + .new_buffer(BYTES as u64, ResourceOptions::default()) + .unwrap(); + let texture = bytes + .new_texture(&over_bytes(ResourceOptions::default()), 0, ROW) + .unwrap(); + copies_read_none_apart(&device, &buffer, &texture, ROW); + // A two-plane extended-range texture: plane 0's words moved by a dispatch. + let mut descriptor = over_bytes(ResourceOptions::private()); + descriptor.pixel_format = PixelFormat::RGB10A82PXR10; + descriptor.width = 512; + descriptor.height = 512; + match device.new_texture(&descriptor) { + Ok(texture) => copies_read_none_apart(&device, &buffer, &texture, 4 * 512), + Err(error @ (Error::Unsupported(_) | Error::NotImplemented(_))) => { + eprintln!("IMPORT-COUNTS: no two-plane texture: {error}"); + } + Err(error) => panic!("a two-plane texture: {error}"), + } +} + +/// The remap reports, those over live imports, the imports they touched, and the imports made by +/// pointer with their bytes. +fn remaps(device: &Device) -> [u64; 5] { + let counts = device.work_counts(); + [ + counts.host_remaps_reported, + counts.host_remaps_over_imports, + counts.host_imports_remapped, + counts.host_pointer_imports_made, + counts.host_pointer_import_bytes_made, + ] +} + +/// The first byte of `host`'s pages. +fn first_byte(host: &Host) -> NonNull { + NonNull::from(host.words()).cast() +} + +#[test] +fn a_remap_report_counts_the_live_imports_it_touches_and_imports_count_their_bytes() { + let scratch = Scratch::new("import-remaps"); + let (imported, fresh) = (Host::new(), Host::new()); + let device = device(&scratch.0); + let runs = Arc::new(AtomicUsize::new(0)); + let [reported, over, remapped, made, bytes] = remaps(&device); + let Some(buffer) = over_host(&device, &imported, &runs) else { + return; + }; + // One import by pointer of the buffer's whole pages. + let now = remaps(&device); + assert_eq!(now[3..], [made + 1, bytes + BYTES as u64]); + // A report over a page inside the buffer's bytes touches its import. + let inside = NonNull::new(first_byte(&imported).as_ptr().wrapping_add(8192)).unwrap(); + device.host_range_remapped(inside, 4096); + assert_eq!(remaps(&device)[..3], [reported + 1, over + 1, remapped + 1]); + // One over a range no buffer lies over touches none. + device.host_range_remapped(first_byte(&fresh), BYTES as u64); + assert_eq!(remaps(&device)[..3], [reported + 2, over + 1, remapped + 1]); + // A second buffer over the remapped bytes imports them anew (`host_aliases.rs`): two live + // imports over the same bytes, one placed range, which a report counts once. + let again = over_host(&device, &imported, &runs).unwrap(); + assert_eq!(remaps(&device)[3], made + 2); + device.host_range_remapped(inside, 4096); + assert_eq!(remaps(&device)[..3], [reported + 3, over + 2, remapped + 2]); + drop((buffer, again)); + // Gone, its pages touch nothing. + device.host_range_remapped(inside, 4096); + assert_eq!(remaps(&device)[..3], [reported + 4, over + 2, remapped + 2]); +} + +/// The imports rebinds made, those an import alive then covered, and the live rebinds' imports no +/// live buffers' table listed yet. +fn rebinds(device: &Device) -> [u64; 3] { + let counts = device.work_counts(); + [ + counts.host_rebind_imports_made, + counts.host_rebind_imports_covered, + counts.host_imports_rebound_unlisted, + ] +} + +/// `base` with `by` added at each place. +fn added(base: [u64; 3], by: [u64; 3]) -> [u64; 3] { + [base[0] + by[0], base[1] + by[1], base[2] + by[2]] +} + +#[test] +fn a_rebind_s_import_is_unlisted_until_a_command_buffer_uses_it_and_covered_over_bytes_lain_over() { + let scratch = Scratch::new("import-rebinds"); + let hosts = [Host::new(), Host::new(), Host::new()]; + let device = device(&scratch.0); + let queue = device.new_command_queue().unwrap(); + let runs = Arc::new(AtomicUsize::new(0)); + let Some(first) = over_host(&device, &hosts[0], &runs) else { + return; + }; + let second = over_host(&device, &hosts[1], &runs).unwrap(); + let before = rebinds(&device); + // A rebind onto bytes no buffer lies over: a new import, uncovered and unlisted. + // SAFETY: the pages outlive the device, and only the buffers' commands use them. + unsafe { first.rebind_bytes_no_copy(hosts[2].memory(), None, None) }.unwrap(); + assert_eq!(rebinds(&device), added(before, [1, 0, 1])); + // A second buffer rebound onto the same bytes imports them again (only bytes a live buffer + // was made over are shared, `host_aliases.rs`): the first one's import covers them. + // SAFETY: as above. + unsafe { second.rebind_bytes_no_copy(hosts[2].memory(), None, None) }.unwrap(); + assert_eq!(rebinds(&device), added(before, [2, 1, 2])); + // A command buffer using the first lists its import from its commit on. + blits(&queue, |blit| blit.fill_buffer(&first, 0..4096, 1).unwrap()); + assert_eq!(rebinds(&device), added(before, [2, 1, 1])); + // Rebound again onto the bytes it lies over: covered by its own import, the new one + // unlisted, the old one listed no more but counted as listed. + // SAFETY: as above. + unsafe { first.rebind_bytes_no_copy(hosts[2].memory(), None, None) }.unwrap(); + assert_eq!(rebinds(&device), added(before, [3, 2, 2])); + // The imports that go leave the gauge. + drop((first, second)); + until("the rebinds' imports went", || { + rebinds(&device)[2] == before[2] + }); +} diff --git a/crates/metal2vulkan-runtime/src/tests/host_memory.rs b/crates/metal2vulkan-runtime/src/tests/host_memory.rs index ed133ff23..4ebb63af5 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_memory.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_memory.rs @@ -235,28 +235,45 @@ fn only_pages_mapped_writable_without_a_gap_are_importable() { "not a mapping line", "8000-9000 rw-p 00000000 00:00 0", ]); + // The answer, and how many mappings it judged. + let judged = |lines: Vec, start: u64, end: u64| { + let mut asked = 0; + (writable(lines, start, end, &mut asked), asked) + }; // Inside one mapping, and across two adjacent writable ones (private and shared). - assert!(writable(lines.clone(), 0x1000, 0x3000)); - assert!(writable(lines.clone(), 0x2000, 0x5000)); + assert_eq!(judged(lines.clone(), 0x1000, 0x3000), (true, 1)); + assert_eq!(judged(lines.clone(), 0x2000, 0x5000), (true, 2)); // A read-only page, alone or at the end of a range. - assert!(!writable(lines.clone(), 0x5000, 0x6000)); - assert!(!writable(lines.clone(), 0x4000, 0x6000)); + assert_eq!(judged(lines.clone(), 0x5000, 0x6000), (false, 1)); + assert_eq!(judged(lines.clone(), 0x4000, 0x6000), (false, 2)); // A gap (0x6000-0x7000 is unmapped), and pages past the last mapping. - assert!(!writable(lines.clone(), 0x6000, 0x7000)); - assert!(!writable(lines.clone(), 0x7000, 0xa000)); + assert_eq!(judged(lines.clone(), 0x6000, 0x7000), (false, 1)); + assert_eq!(judged(lines.clone(), 0x7000, 0xa000), (false, 2)); // A line that does not parse is skipped. - assert!(writable(lines.clone(), 0x7000, 0x9000)); + assert_eq!(judged(lines.clone(), 0x7000, 0x9000), (true, 2)); // Nothing mapped at all. - assert!(!writable(Vec::new(), 0x1000, 0x2000)); + assert_eq!(judged(Vec::new(), 0x1000, 0x2000), (false, 0)); +} + +/// The mapping queries go through one file the process keeps open (`host_memory::kept_maps`), +/// opened once, whose answers follow the mappings as they are at each query (the test below). +#[cfg(target_os = "linux")] +#[test] +fn the_mapping_queries_keep_one_file_open() { + use crate::host_memory::kept_maps; + let first = kept_maps().expect("/proc/self/maps opens"); + let again = kept_maps().expect("/proc/self/maps opens"); + assert!(std::sync::Arc::ptr_eq(&first, &again)); } /// The check reads this process's own mappings: a fresh page is importable until it is made -/// read-only, and a page no longer mapped is not. +/// read-only, and a page no longer mapped is not, through the kept file's queries as they are now. #[cfg(target_os = "linux")] #[test] fn this_process_s_read_only_and_unmapped_pages_are_refused() { use crate::error::Error; use crate::host_memory::refuse_unwritable; + use crate::work_counts::Counters; let page = host_page().unwrap(); let len = page as usize; // SAFETY: a fresh private mapping, unmapped below. @@ -282,13 +299,14 @@ fn this_process_s_read_only_and_unmapped_pages_are_refused() { } _ => false, }; - assert_eq!(refuse_unwritable(&window), Ok(())); + let counts = Counters::default(); + assert_eq!(refuse_unwritable(&window, &counts), Ok(())); // SAFETY: the mapping is this test's. assert_eq!(unsafe { libc::mprotect(at, len, libc::PROT_READ) }, 0); - assert!(refused(refuse_unwritable(&window))); + assert!(refused(refuse_unwritable(&window, &counts))); // SAFETY: as above. assert_eq!(unsafe { libc::munmap(at, len) }, 0); - assert!(refused(refuse_unwritable(&window))); + assert!(refused(refuse_unwritable(&window, &counts))); } /// The kernel's answer for a window (`PROCMAP_QUERY`) is the maps lines' answer, over one @@ -409,7 +427,7 @@ fn window_answers(windows: &[(u64, u64); N]) -> [(bool, Option(sink: i32, windows: &[(u64, u64); N]) -> } // SAFETY: `fd` is the file just opened, which the `File` owns from here. let maps = unsafe { std::fs::File::from_raw_fd(fd) }; - let answers = windows.map(|(start, end)| match queried_writable(&maps, start, end) { - None => 0, - Some(writable) => 1 | (u8::from(writable) << 1), - }); + let answers = windows.map( + |(start, end)| match queried_writable(&maps, start, end, &mut 0) { + None => 0, + Some(writable) => 1 | (u8::from(writable) << 1), + }, + ); if !send(&answers) { return 3; } diff --git a/crates/metal2vulkan-runtime/src/tests/host_residency.rs b/crates/metal2vulkan-runtime/src/tests/host_residency.rs index a593349de..9a8173363 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_residency.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_residency.rs @@ -16,11 +16,12 @@ //! - the pages a release keeps across a remap of the buffer's addresses; //! - that a buffer whose Metal address was handed out stays imported; //! - that a buffer past the descriptors the device keeps (capped through -//! `Device::cap_kept_host_import_fds`) is made and stays imported. +//! `Device::cap_kept_host_import_fds`) is made and stays imported, counted while it lives +//! (`host_imports_kept_for_fds`). //! -//! A device that imports the pointer (NVIDIA, lavapipe) keeps the import and counts none of it; -//! each test says so and passes. Where `/dev/udmabuf` cannot be opened each test says so and -//! passes without running. +//! A device that imports the pointer (NVIDIA, lavapipe, ANV) runs none of it: each test says so +//! and passes, and `tests/pointer_residency.rs` checks the residency of pointer imports. Where +//! `/dev/udmabuf` cannot be opened each test says so and passes without running. //! //! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, //! `m2v_cpu_icd`), on Linux, on the kind of device the cfg selects. @@ -69,7 +70,7 @@ const UDMABUF_CREATE: u64 = (1 << 30) | ((size_of::() as u64) << 16) | ((b'u' as u64) << 8) | 0x42; /// The host's page size. -fn host_page() -> usize { +pub(super) fn host_page() -> usize { // SAFETY: `sysconf` reads a system constant. let page = unsafe { libc::sysconf(libc::_SC_PAGESIZE) }; usize::try_from(page).expect("a page size") @@ -109,10 +110,10 @@ fn udmabuf(memfd: &OwnedFd, offset: u64, size: u64) -> std::io::Result } /// A scratch directory for the device's shader cache, removed when dropped. -struct Scratch(PathBuf); +pub(super) struct Scratch(pub(super) PathBuf); impl Scratch { - fn new() -> Scratch { + pub(super) fn new() -> Scratch { static NEXT: AtomicUsize = AtomicUsize::new(0); let path = std::env::temp_dir().join(format!( "m2v-host-residency-{}-{}", @@ -132,7 +133,7 @@ impl Drop for Scratch { /// The device the cfg selects: a CPU device under `m2v_cpu_icd`, else a GPU, its shader cache /// in `cache`. -fn device(cache: &Path) -> Device { +pub(super) fn device(cache: &Path) -> Device { let options = DeviceOptions { kinds: match cfg!(m2v_cpu_icd) { true => vec![DeviceKind::Cpu], @@ -163,7 +164,7 @@ fn on_device(name: &str, test: impl FnOnce(&Device)) { /// Guest RAM: a `memfd` sealed against growing and shrinking, and a view of `len` of its bytes, a /// shared mapping from a file offset that [`Ram::remap`] changes. -struct Ram { +pub(super) struct Ram { fd: OwnedFd, at: NonNull, len: usize, @@ -173,7 +174,7 @@ struct Ram { impl Ram { /// A file of `file_len` bytes, its view of `len` bytes from `file_at`. - fn new(file_len: usize, file_at: usize, len: usize) -> Ram { + pub(super) fn new(file_len: usize, file_at: usize, len: usize) -> Ram { // SAFETY: a new anonymous file, owned at once, then sized and sealed. let fd = unsafe { let fd = libc::memfd_create( @@ -210,7 +211,7 @@ impl Ram { } /// The view's address `offset` bytes in. - fn pointer(&self, offset: usize) -> NonNull { + pub(super) fn pointer(&self, offset: usize) -> NonNull { assert!(offset < self.len); // SAFETY: inside the view. unsafe { NonNull::new_unchecked(self.at.as_ptr().add(offset)) } @@ -218,7 +219,7 @@ impl Ram { /// Map the file from `file_at` over the view, in place of the pages there (`mmap` with /// `MAP_FIXED`), as a guest remaps the RAM at those addresses. - fn remap(&self, file_at: usize) { + pub(super) fn remap(&self, file_at: usize) { // SAFETY: the view's own range, mapped again. let mapped = unsafe { libc::mmap( @@ -235,7 +236,7 @@ impl Ram { } /// Write `bytes` into the file at `offset`, not through the view. - fn write_file(&self, offset: usize, bytes: &[u8]) { + pub(super) fn write_file(&self, offset: usize, bytes: &[u8]) { // SAFETY: `bytes` is readable for its length. let written = unsafe { libc::pwrite( @@ -249,7 +250,7 @@ impl Ram { } /// The file's `len` bytes from `offset`, not through the view. - fn read_file(&self, offset: usize, len: usize) -> Vec { + pub(super) fn read_file(&self, offset: usize, len: usize) -> Vec { let mut bytes = vec![0; len]; // SAFETY: `bytes` is writable for its length. let read = unsafe { @@ -265,7 +266,7 @@ impl Ram { } /// The view's bytes. - fn view(&self) -> Vec { + pub(super) fn view(&self) -> Vec { // SAFETY: the view's bytes; each test orders the CPU's and the GPU's accesses. unsafe { std::slice::from_raw_parts(self.at.as_ptr(), self.len).to_vec() } } @@ -300,7 +301,7 @@ impl Drop for Ram { } /// Bytes `i % 251` from `start`. -fn counting(len: usize, start: usize) -> Vec { +pub(super) fn counting(len: usize, start: usize) -> Vec { (start..start + len).map(|i| (i % 251) as u8).collect() } @@ -328,7 +329,7 @@ fn no_copy( let chunks = device.work_counts().dma_buf_imports - before; if chunks == 0 { eprintln!( - "{test}: on {}: the pointer imported, which the device keeps", + "{test}: on {}: the pointer imported (`tests/pointer_residency.rs`)", device.name() ); } @@ -344,7 +345,11 @@ fn run(command_buffer: &crate::CommandBuffer) { /// `buffer`'s first `length` bytes, read back by a blit, and how long the blit's call took to /// encode (with an import again, where the device released the buffer's). -fn gpu_read(queue: &CommandQueue, buffer: &Buffer, length: usize) -> (Vec, Duration) { +pub(super) fn gpu_read( + queue: &CommandQueue, + buffer: &Buffer, + length: usize, +) -> (Vec, Duration) { let device = queue.device(); let copy = device .new_buffer(length as u64, ResourceOptions::shared()) @@ -364,12 +369,17 @@ fn gpu_read(queue: &CommandQueue, buffer: &Buffer, length: usize) -> (Vec, D } /// `buffer`'s first `length` bytes, read back by a blit. -fn read(queue: &CommandQueue, buffer: &Buffer, length: usize) -> Vec { +pub(super) fn read(queue: &CommandQueue, buffer: &Buffer, length: usize) -> Vec { gpu_read(queue, buffer, length).0 } /// Fill `range` of `buffer` with `value` by a blit. -fn gpu_fill(queue: &CommandQueue, buffer: &Buffer, range: std::ops::Range, value: u8) { +pub(super) fn gpu_fill( + queue: &CommandQueue, + buffer: &Buffer, + range: std::ops::Range, + value: u8, +) { let command_buffer = queue.command_buffer().unwrap(); let mut blit = command_buffer.blit_command_encoder().unwrap(); blit.fill_buffer(buffer, range, value).unwrap(); @@ -379,7 +389,7 @@ fn gpu_fill(queue: &CommandQueue, buffer: &Buffer, range: std::ops::Range, /// Release `count` idle imports through the hook, retried until the command buffers that read /// them let go (each at its completion, on the device's handler thread), within [`SETTLE`]. -fn release(test: &str, device: &Device, count: usize) { +pub(super) fn release(test: &str, device: &Device, count: usize) { let start = Instant::now(); let mut released = 0; while released < count { @@ -394,7 +404,7 @@ fn release(test: &str, device: &Device, count: usize) { } /// The device's counts once `settled` holds of them, within [`SETTLE`]. -fn counts_once( +pub(super) fn counts_once( test: &str, device: &Device, what: &str, @@ -412,7 +422,7 @@ fn counts_once( } /// The residency counts of `counts`: released, imported again, resident, descriptors kept. -fn residency(counts: &WorkCounts) -> (u64, u64, u64, u64) { +pub(super) fn residency(counts: &WorkCounts) -> (u64, u64, u64, u64) { ( counts.host_imports_released, counts.host_imports_reimported, @@ -431,7 +441,8 @@ fn residency(counts: &WorkCounts) -> (u64, u64, u64, u64) { /// - released again, its Metal address handed out imports it again at once and for good, /// closing the descriptors kept, and the hook releases it no more. /// -/// Where the device imports the pointer, the hook releases nothing and the counts stay 0. +/// Where the device imports the pointer, the hook releases nothing and the counts stay 0 unless the +/// driver's pointer imports follow their address (`tests/pointer_residency.rs`). #[test] fn an_idle_dma_buf_import_is_released_and_imported_again_at_its_next_blit() { const TEST: &str = "dma-buf residency"; @@ -446,8 +457,10 @@ fn an_idle_dma_buf_import_is_released_and_imported_again_at_its_next_blit() { let (buffer, chunks) = no_copy(TEST, device, &ram, (0, len), &calls); assert!(read(&queue, &buffer, len) == first, "{TEST}"); if chunks == 0 { - assert_eq!(device.release_idle_host_imports(), 0, "{TEST}"); - assert_eq!(residency(&device.work_counts()), (0, 0, 0, 0), "{TEST}"); + if !super::pointer_residency::follows(device) { + assert_eq!(device.release_idle_host_imports(), 0, "{TEST}"); + assert_eq!(residency(&device.work_counts()), (0, 0, 0, 0), "{TEST}"); + } return; } let imported = device.work_counts(); @@ -625,9 +638,10 @@ fn the_residency_thread_releases_an_idle_import_after_its_window() { /// With the device's kept descriptors capped at one (`Device::cap_kept_host_import_fds`), no-copy /// buffers over the file's pages 0 and 1, of one dma-buf each where the device imports dma-bufs: /// the first keeps its descriptor; the second, past the cap, is made and imported as any other and -/// keeps none, so it stays imported: the hook releases the first alone, blits read both buffers' -/// bytes, and the second is never imported again. Once the first is dropped its descriptor is -/// closed, and a third buffer keeps one again. +/// keeps none, so it stays imported, counted (`WorkCounts::host_imports_kept_for_fds`): the hook +/// releases the first alone, blits read both buffers' bytes, and the second is never imported +/// again. Once the first is dropped its descriptor is closed, and a third buffer keeps one again. +/// Once the second is dropped, the count falls back. #[test] fn a_buffer_past_the_kept_descriptors_stays_imported() { const TEST: &str = "dma-buf residency past the cap"; @@ -646,6 +660,11 @@ fn a_buffer_past_the_kept_descriptors_stays_imported() { return; } assert_eq!(chunks, 1, "{TEST}: one dma-buf a page"); + assert_eq!( + device.work_counts().host_imports_kept_for_fds, + 0, + "{TEST}: the first kept" + ); let (past, _) = no_copy(TEST, device, &ram, (page, page), &calls); let counts = device.work_counts(); assert_eq!( @@ -653,6 +672,10 @@ fn a_buffer_past_the_kept_descriptors_stays_imported() { (0, 0, 1, 1), "{TEST}: the second past the cap" ); + assert_eq!( + counts.host_imports_kept_for_fds, 1, + "{TEST}: the second kept imported for the cap" + ); assert!(read(&queue, &kept, page) == page_0, "{TEST}"); assert!(read(&queue, &past, page) == page_1, "{TEST}"); @@ -674,9 +697,16 @@ fn a_buffer_past_the_kept_descriptors_stays_imported() { let (third, _) = no_copy(TEST, device, &ram, (0, page), &calls); let counts = device.work_counts(); assert_eq!(residency(&counts), (1, 1, 1, 1), "{TEST}: the third kept"); + assert_eq!( + counts.host_imports_kept_for_fds, 1, + "{TEST}: the second still kept imported" + ); assert!(read(&queue, &third, page) == page_0, "{TEST}"); drop(third); drop(past); + counts_once(TEST, device, "the second's import freed", |counts| { + counts.host_imports_kept_for_fds == 0 + }); eprintln!( "{TEST}: on {}: the buffer past the cap stayed imported", device.name() diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index 872429118..dc8adf32e 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -73,6 +73,8 @@ mod heap_tiled_blocks; mod heap_usage; mod held_depth; mod host_aliases; +#[cfg(any(m2v_gpu, m2v_cpu_icd))] +mod host_import_counts; mod host_memory; #[cfg(all(any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))] mod host_residency; @@ -119,6 +121,8 @@ mod pipeline_wait_order; #[cfg(unix)] mod pitch_refusals; mod pixel_format_info; +#[cfg(all(any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))] +mod pointer_residency; mod private_properties; mod queue; mod range; diff --git a/crates/metal2vulkan-runtime/src/tests/pointer_residency.rs b/crates/metal2vulkan-runtime/src/tests/pointer_residency.rs new file mode 100644 index 000000000..74a9b0d05 --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/pointer_residency.rs @@ -0,0 +1,184 @@ +//! The residency of no-copy buffers' pointer imports (`host_residency.rs`), on the device the cfg +//! selects. +//! +//! The memory is guest RAM as QEMU's `memory-backend-memfd,share=on` makes it, a sealed `memfd` +//! mapped shared, imported by its pointer (`HostMemory::new`), as ANV, NVIDIA and lavapipe import +//! - that a kept import reads the pages a remap put at its address, which is the fact itself, on +//! a device with it; on any other the test prints the pages it read, a measurement of the +//! driver; +//! - the counts that show the release and the import again ran (`WorkCounts::host_imports_released`, +//! `host_imports_reimported`, `host_imports_resident`, `host_imports_live`), and none of a +//! dma-buf's descriptors kept; +//! - the bytes a blit reads and writes after a release, the CPU's writes made while released among +//! them; +//! - that a released import reads after a remap the pages the kept one would read; +//! - that a buffer whose Metal address was handed out stays imported. +//! +//! A device whose driver is not measured with the fact keeps every pointer import: the hook +//! +//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`, +//! `m2v_cpu_icd`), on Linux, on the kind of device the cfg selects. + +use super::host_residency::{ + counting, device, gpu_fill, gpu_read, host_page, read, release, residency, Ram, Scratch, +}; +use crate::{Buffer, Device, Error, HostMemory, ResourceOptions}; +use metal2vulkan::device::DriverFact; +use metal2vulkan::error::Feature; + +/// Whether `device`'s driver is measured to have its pointer imports follow their address, so +/// that the device releases them while idle. +pub(super) fn follows(device: &Device) -> bool { + (device.properties().driver_facts).contains(&DriverFact::PointerImportsFollowTheirAddress) +} + +/// Run `test` on the device the cfg selects. +fn on_device(test: impl FnOnce(&Device)) { + let scratch = Scratch::new(); + let device = device(&scratch.0); + test(&device); +} + + } +} + +#[test] +fn a_kept_pointer_import_reads_the_pages_a_remap_put_at_its_address() { + const TEST: &str = "pointer import remap"; + on_device(|device| { + let page = host_page(); + let len = 2 * page; + let queue = device.new_command_queue().unwrap(); + let old = counting(len, 13); + let new = counting(len, 131); + return; + }; + assert!(read(&queue, &buffer, len) == old, "{TEST}"); + + let bytes = read(&queue, &buffer, len); + _ if bytes == new => "the new pages", + _ if bytes == old => "the pages it was made over", + _ => "neither", + }; + eprintln!( + device.name(), + follows(device), + ); + if follows(device) { + assert_eq!(residency(&device.work_counts()).0, 0, "{TEST}: no release"); + } + drop(buffer); + }); +} + +/// A no-copy buffer over 4 pages, imported by its pointer, on a device whose driver's pointer +/// imports follow their address: +/// - read by a blit, its import released: the device's live host imports fall by one, no +/// descriptor is kept, and the hook releases it no further while released; +/// - released again, a GPU fill lands in the pages; +/// - released again, its Metal address handed out imports it again at once and for good, and the +/// hook releases it no more. +/// +/// Elsewhere the hook releases nothing and the counts stay 0. +#[test] +fn an_idle_pointer_import_is_released_and_imported_again_at_its_next_blit() { + const TEST: &str = "pointer residency"; + on_device(|device| { + let page = host_page(); + let len = 4 * page; + let queue = device.new_command_queue().unwrap(); + let first = counting(len, 7); + return; + }; + assert!(read(&queue, &buffer, len) == first, "{TEST}"); + if !follows(device) { + assert_eq!(device.release_idle_host_imports(), 0, "{TEST}"); + assert_eq!(residency(&device.work_counts()), (0, 0, 0, 0), "{TEST}"); + eprintln!("{TEST}: on {}: the pointer import kept", device.name()); + return; + } + let imported = device.work_counts(); + assert_eq!(residency(&imported), (0, 0, 1, 0), "{TEST}"); + let live = imported.host_imports_live; + + release(TEST, device, 1); + let released = device.work_counts(); + assert_eq!(residency(&released), (1, 0, 0, 0), "{TEST}: released"); + assert_eq!(released.host_imports_live, live - 1, "{TEST}"); + assert_eq!( + device.release_idle_host_imports(), + 0, + "{TEST}: released twice" + ); + + let second = counting(len, 59); + let contents = buffer.contents().unwrap(); + // SAFETY: the buffer's own bytes, which no command reads now. + unsafe { std::ptr::copy_nonoverlapping(second.as_ptr(), contents.as_ptr(), len / 2) }; + let (bytes, importing) = gpu_read(&queue, &buffer, len); + assert!(bytes == second, "{TEST}: the bytes written while released"); + let (bytes, imported) = gpu_read(&queue, &buffer, len); + assert!(bytes == second, "{TEST}"); + let again = device.work_counts(); + assert_eq!(residency(&again), (1, 1, 1, 0), "{TEST}: imported again"); + assert_eq!(again.host_imports_live, live, "{TEST}"); + + // A GPU write after a release lands in the pages. + release(TEST, device, 1); + gpu_fill(&queue, &buffer, page as u64..3 * page as u64, 0x6d); + let mut filled = second.clone(); + filled[page..3 * page].fill(0x6d); + let counts = device.work_counts(); + assert_eq!(residency(&counts), (2, 2, 1, 0), "{TEST}: filled"); + + // Its Metal address handed out keeps it imported for good, from the moment it is. + release(TEST, device, 1); + let address = buffer.gpu_address(); + assert_ne!(address.0, 0, "{TEST}"); + let counts = device.work_counts(); + assert_eq!(residency(&counts), (3, 3, 1, 0), "{TEST}: exposed"); + assert_eq!(counts.host_imports_live, live, "{TEST}"); + assert!(read(&queue, &buffer, len) == filled, "{TEST}"); + assert_eq!(device.release_idle_host_imports(), 0, "{TEST}: exposed"); + drop(buffer); + eprintln!( + "{TEST}: on {}: released 3 times, imported again 3 times; a copy's call took \ + {importing:?} importing it again, {imported:?} imported", + device.name() + ); + }); +} + +/// (`a_kept_pointer_import_reads_the_pages_a_remap_put_at_its_address`), so the release changed +/// nothing a command reads. +#[test] +fn a_released_pointer_import_reads_after_a_remap_what_the_kept_one_would() { + const TEST: &str = "pointer residency remap"; + on_device(|device| { + if !follows(device) { + eprintln!("{TEST}: on {}: pointer imports kept", device.name()); + return; + } + let page = host_page(); + let len = 2 * page; + let queue = device.new_command_queue().unwrap(); + let old = counting(len, 13); + let new = counting(len, 131); + return; + }; + assert!(read(&queue, &buffer, len) == old, "{TEST}"); + release(TEST, device, 1); + + assert!( + read(&queue, &buffer, len) == new, + "{TEST}: the released import" + ); + let counts = device.work_counts(); + assert_eq!(residency(&counts), (1, 1, 1, 0), "{TEST}: imported again"); + drop(buffer); + eprintln!( + "{TEST}: on {}: the released import read the new pages, as the kept one does", + device.name() + ); + }); +} diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index 634b9e2ee..9c2dff92a 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -5540,6 +5540,18 @@ impl Texture { } } + /// The key of the buffer whose bytes the texture's images and texel views lie in or are + /// copied from ([`memory`](Self::memory)): the buffer it is over, or its heap's own buffer + /// (a view's too). A rebind or a detach of those bytes remakes them, and no other texture's + /// (`heap_sets::renew_over`). `None` for a texture in memory of its own or of a sparse heap. + pub(super) fn bytes_key(&self) -> Option { + match self.memory() { + TextureMemory::Heap(heap) => heap.bytes().map(|bytes| bytes.identity().key), + TextureMemory::Buffer(buffer) => Some(buffer.identity().key), + TextureMemory::Own(_) => None, + } + } + /// Another reference to the texture, which a command buffer holds it by /// (`EncoderCore::retain_shared`). pub(super) fn held(&self) -> Arc { diff --git a/crates/metal2vulkan-runtime/src/two_planes.rs b/crates/metal2vulkan-runtime/src/two_planes.rs index c4440971b..7ae33e803 100644 --- a/crates/metal2vulkan-runtime/src/two_planes.rs +++ b/crates/metal2vulkan-runtime/src/two_planes.rs @@ -272,7 +272,8 @@ impl BlitCommandEncoder { max_groups: limits.max_compute_work_group_count[0], max_scratch: MAX_SCRATCH, }; - let (raw_buffer, base) = buffer.at(0); + // Read as a blit's (`host_residency.rs`): the command buffer holds the import. + let (raw_buffer, base) = self.core().blit_at(buffer, 0)?; let bands = bands(region.size, layout, base, &band_limits) .ok_or(Error::Unsupported(unmeasured(pf)))?; let align = band_limits.align; diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 331ace12b..3003f7d84 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -5,6 +5,7 @@ //! resident one by one on MoltenVK; and the completion waits that missed their wake, which a test //! holds to none. Not part of the API. +use super::buffer::{KeptBecause, ReadApart}; use super::command_buffer::GroupEnd; use super::degradation::Degradation; use super::device::lock; @@ -71,6 +72,7 @@ pub(crate) struct Counters { stand_in_bytes: AtomicU64, stale_detached_reaches: AtomicU64, detached_storage_reaches: AtomicU64, + heap_slots_rewritten: AtomicU64, heap_textures_tiled: AtomicU64, heap_texture_lossless_layouts: AtomicU64, heap_texture_block_compressed_layouts: AtomicU64, @@ -130,6 +132,7 @@ pub(crate) struct Counters { argument_samplers_taken: AtomicU64, bind_views_worked_out: AtomicU64, stage_tables_read: AtomicU64, + no_copy_lies_read: AtomicU64, commands_noted_as_before: AtomicU64, draws_settled: AtomicU64, depth16_sided_draws: AtomicU64, @@ -156,6 +159,7 @@ pub(crate) struct Counters { host_deallocators_delayed: AtomicU64, host_keep_alives_kept: AtomicU64, host_keep_alives_covered: AtomicU64, + host_mappings_queried: AtomicU64, dma_buf_imports: AtomicU64, dma_buf_memories_live: AtomicU64, dma_buf_image_memories_live: AtomicU64, @@ -164,6 +168,19 @@ pub(crate) struct Counters { host_imports_resident: AtomicU64, host_imports_lost: AtomicU64, host_import_fds_kept: AtomicU64, + host_imports_kept_for_fds: AtomicU64, + host_imports_used: AtomicU64, + host_imports_read_apart: AtomicU64, + host_imports_read_apart_by: [AtomicU64; ReadApart::COUNT], + host_imports_kept_by: [AtomicU64; KeptBecause::COUNT], + host_imports_rebound_unlisted: AtomicU64, + host_rebind_imports_made: AtomicU64, + host_rebind_imports_covered: AtomicU64, + host_remaps_reported: AtomicU64, + host_remaps_over_imports: AtomicU64, + host_imports_remapped: AtomicU64, + host_pointer_imports_made: AtomicU64, + host_pointer_import_bytes_made: AtomicU64, dma_buf_sparse_buffers: AtomicU64, dma_buf_images: AtomicU64, dma_buf_image_fallbacks: AtomicU64, @@ -861,6 +878,12 @@ impl Counters { self.stage_tables_read.fetch_add(1, Ordering::Relaxed); } + /// A look at where a no-copy buffer's bytes lie, which takes its pages' lock + /// (`buffer::HostCell`). + pub(crate) fn no_copy_lie_read(&self) { + self.no_copy_lies_read.fetch_add(1, Ordering::Relaxed); + } + /// A draw's uses were noted already: the last command its encoder noted had them /// (`noted_apart.rs`). pub(crate) fn command_noted_as_before(&self) { @@ -1030,6 +1053,17 @@ impl Counters { .fetch_add(1, Ordering::Relaxed); } + /// The kernel was asked about `mappings` of the process's mappings, for their write + /// permission, before an import of host pages (`host_memory.rs`'s `refuse_unwritable`, which + /// asks only on Linux). + #[cfg(target_os = "linux")] + pub(crate) fn host_mappings_queried(&self, mappings: u64) { + if mappings > 0 { + self.host_mappings_queried + .fetch_add(mappings, Ordering::Relaxed); + } + } + /// `chunks` chunks of host pages a caller's source made were imported as dma-buf memory, and /// a buffer bound in them, where the device refused the pages' pointer (`dma_buf.rs`). pub(crate) fn dma_buf_imported(&self, chunks: usize) { @@ -1074,6 +1108,77 @@ impl Counters { }; } + /// A committed command buffer's commands use `count` host imports (`Buffer::distinct_host_imports`). + pub(crate) fn commit_used_host_imports(&self, count: u64) { + self.host_imports_used.fetch_add(count, Ordering::Relaxed); + } + + /// A live host import was first read other than by a blit (`read_apart`), or such an import + /// went. + pub(crate) fn host_import_read_apart(&self, read_apart: bool) { + match read_apart { + true => self.host_imports_read_apart.fetch_add(1, Ordering::Relaxed), + false => self.host_imports_read_apart.fetch_sub(1, Ordering::Relaxed), + }; + } + + /// A live host import was first read apart for `reason` (`read_apart`), or such an import + /// went. + pub(crate) fn host_import_read_apart_for(&self, reason: ReadApart, read_apart: bool) { + let gauge = &self.host_imports_read_apart_by[reason as usize]; + match read_apart { + true => gauge.fetch_add(1, Ordering::Relaxed), + false => gauge.fetch_sub(1, Ordering::Relaxed), + }; + } + + /// A rebind's import that no live buffers' table listed yet was made (`unlisted`), or was + /// first listed, or went unlisted. + pub(crate) fn host_import_rebound_unlisted(&self, unlisted: bool) { + let gauge = &self.host_imports_rebound_unlisted; + match unlisted { + true => gauge.fetch_add(1, Ordering::Relaxed), + false => gauge.fetch_sub(1, Ordering::Relaxed), + }; + } + + /// A rebind imported its new pages, where bytes buffers over host pages lay over already held + /// them (`covered`) or not. + pub(crate) fn host_rebind_import_made(&self, covered: bool) { + self.host_rebind_imports_made + .fetch_add(1, Ordering::Relaxed); + if covered { + (self.host_rebind_imports_covered).fetch_add(1, Ordering::Relaxed); + } + } + + /// The caller reported a remap of host addresses (`Device::host_range_remapped`) whose pages + /// `imports` live imports have a page among. + pub(crate) fn host_range_remapped(&self, imports: usize) { + self.host_remaps_reported.fetch_add(1, Ordering::Relaxed); + if imports > 0 { + self.host_remaps_over_imports + .fetch_add(1, Ordering::Relaxed); + (self.host_imports_remapped).fetch_add(imports as u64, Ordering::Relaxed); + } + } + + /// The device imported `bytes` of host pages by their pointer (`Memory::import_host`). + pub(crate) fn host_pointer_import_made(&self, bytes: u64) { + (self.host_pointer_imports_made).fetch_add(1, Ordering::Relaxed); + (self.host_pointer_import_bytes_made).fetch_add(bytes, Ordering::Relaxed); + } + + /// A host import the device never releases while idle, for `because`, was made (`kept`), or + /// went. + pub(crate) fn host_import_kept(&self, because: KeptBecause, kept: bool) { + let gauge = &self.host_imports_kept_by[because as usize]; + match kept { + true => gauge.fetch_add(1, Ordering::Relaxed), + false => gauge.fetch_sub(1, Ordering::Relaxed), + }; + } + /// A read found a released import that the device could not import again: the device is /// lost. pub(crate) fn host_import_lost(&self) { @@ -1095,6 +1200,19 @@ impl Counters { .fetch_sub(count, Ordering::Relaxed); } + /// A no-copy buffer's own import of dma-bufs is kept imported from now on, as the + /// descriptors to import it again did not fit (`kept`), or such an import went. + pub(crate) fn host_import_kept_for_fds(&self, kept: bool) { + match kept { + true => self + .host_imports_kept_for_fds + .fetch_add(1, Ordering::Relaxed), + false => self + .host_imports_kept_for_fds + .fetch_sub(1, Ordering::Relaxed), + }; + } + /// A no-copy buffer's (or heap's, or rebind's) `VkBuffer` was assembled from several chunks' /// imports as a sparse buffer (`dma_buf.rs`). pub(crate) fn dma_buf_sparse_buffer_made(&self) { @@ -1469,6 +1587,14 @@ impl Counters { .fetch_add(1, Ordering::Relaxed); } + /// `count` texture slots of the device's heap were written again whatever changed + /// (`heap_sets::renew_over`, `heap_sets::renew`). + pub(crate) fn heap_slots_rewritten(&self, count: usize) { + if count > 0 { + (self.heap_slots_rewritten).fetch_add(count as u64, Ordering::Relaxed); + } + } + /// A texture in a heap over host pages was made tiled as Metal lays it out /// (`texture/heap_tiled.rs`). pub(crate) fn heap_texture_tiled(&self) { @@ -1722,6 +1848,15 @@ pub struct WorkCounts { /// Textures of storage usage over detached bytes that a later commit could reach unnamed, /// each counted once (`Degradation::DetachedStorageKeepsWrites`). pub detached_storage_reaches: u64, + /// Texture slots of the device's heap (its texture table and heap sets) written again by a + /// rebind or a detach of host pages, or by a change of storage form: for a rebind or a + /// detach, one for each live texture whose images or texel views lie in those bytes (in a + /// no-copy heap or over one of its buffers, for the heap's), and none for any other texture. + pub heap_slots_rewritten: u64, + /// Uses of a buffer over host pages that looked up by address the ranges of host bytes their + /// bytes meet (`host_aliases.rs`): a use of a range met by no more ranges than the classes of + /// length that lookup visits reads those its range keeps instead. + pub host_range_lookups: u64, /// Textures made in heaps over host pages laid out as Metal tiles them, each a shadow of its /// elements in the heap's bytes (`texture/heap_tiled.rs`). pub heap_textures_tiled: u64, @@ -1990,6 +2125,11 @@ pub struct WorkCounts { /// interface, with the same samplers' address-mode maps, while no no-copy buffer was rebound /// or detached (`live_bind::ReadFrom`). pub stage_tables_read: u64, + /// Looks at where a no-copy buffer's bytes lie, each of which takes its pages' lock + /// (`buffer::HostCell`): a draw's read of a table binding one takes one for the binding, its + /// base and device address read together (`argument_table::bound_buffer`), and a descriptor + /// written for it one for its `VkBuffer` and its space's start (`Buffer::space`). + pub no_copy_lies_read: u64, /// Draws whose uses their encoder did not note again: the last command it noted had the same /// uses, with the same uses of host aliases added, into the same part, with the same images /// held in their attachment layout, and none of them reached through the resident set alone @@ -2112,6 +2252,13 @@ pub struct WorkCounts { /// import of its pages stays mapped without them: another no-copy buffer made over the same /// bytes lies in it, or it keeps another's keep-alive already. pub host_keep_alives_covered: u64, + /// The process's mappings the kernel was asked about, for their write permission, before a + /// no-copy buffer's, heap's or rebind's own import of host pages, on Linux (one `PROCMAP_QUERY` + /// each, or one line of `/proc/self/maps` where the kernel predates the query): one per mapping + /// the import's pages lie in, a view of scattered pages one per run, at each such import. A + /// buffer made over the same bytes as a live one, which lies in its import, asks about none. + /// None off Linux. + pub host_mappings_queried: u64, /// Chunks of host pages imported as dma-buf memory from a caller's source /// (`HostMemory::with_dma_buf`), where the device refused the pages' pointer: no-copy /// buffers', heaps' and rebinds' alike, one per chunk. None where every pointer was imported. @@ -2140,6 +2287,86 @@ pub struct WorkCounts { /// The descriptors of dma-bufs the device keeps open now to import released imports again: at /// most a quarter of the process's descriptor limit. pub host_import_fds_kept: u64, + /// The live no-copy buffers' own imports of dma-bufs that the device would release while idle + /// but keeps imported, as the descriptors to import them again did not fit: past the quarter + /// of the process's `RLIMIT_NOFILE` soft limit the devices keep, or the host gave no duplicate. + /// Each stays in every kernel submission's list while it lives. A soft limit raised at startup + /// (`setrlimit`; the runtime reads it once, at the process's first such import) lets more go; + /// the runtime never changes the limit. + pub host_imports_kept_for_fds: u64, + /// The host imports each committed command buffer's commands use (a binding, a blit's operand, + /// `use_resource`, a texture over the bytes), each import counted once per command buffer + /// however many of its buffers lie in it, summed over command buffers: its change over a frame, + /// against `host_imports_live`, is how many of the imports every kernel submission lists the + /// frame's commands name. Counted at the commit, on the committing thread. + pub host_imports_used: u64, + /// The live host imports some read other than a blit's took (their Metal address or + /// `VkBuffer` handed out, a binding, a texture over the bytes, a second buffer lying in the + /// import): those a release while idle could never take, as the device keeps a releasable + /// import for good after such a read. Of imports of any kind. + pub host_imports_read_apart: u64, + /// Of those, the ones whose buffer's Metal address was handed out: `gpu_address` (a heap's + /// over the import's bytes too), or written for the caller into an argument buffer or an + /// indirect command buffer. Each of these six counts an import once for its reason, so an + /// import read apart for several reasons counts in each. + pub host_imports_read_apart_address: u64, + /// Of those, the ones whose buffer's `VkBuffer` was handed out (`Buffer::vk_buffer`). + pub host_imports_read_apart_vk_buffer: u64, + /// Of those, the ones a command read other than by a blit's copy: a binding (a buffer + /// argument, a vertex or index buffer, an argument table's entry, `use_resource`), and the + /// copies of a texture over the bytes that a command reads it through. + pub host_imports_read_apart_binding: u64, + /// Of those, the ones a texture over the bytes was made over: an image bound to the import's + /// memory, or a texel view or a shadow's copies over its `VkBuffer`. + pub host_imports_read_apart_texture: u64, + /// Of those, the ones a second no-copy buffer lies in (`host_aliases.rs`), or that a buffer + /// made over the same host memory shares its range with (`BufferDescriptor::range_of`). + pub host_imports_read_apart_second_buffer: u64, + /// Of those, the releasable ones kept imported because the host could start no thread to + /// release them. + pub host_imports_read_apart_unreleased: u64, + /// The caller's reports of host addresses whose pages it replaced + /// (`Device::host_range_remapped`), whatever lies over them. + pub host_remaps_reported: u64, + /// Of those, the reports with a page of a live host import among the addresses, rounded out + /// to the import's unit: a driver's import by pointer (ANV's userptr on i915) over a page + /// replaced takes its pages anew, all of them, at its next submission. + pub host_remaps_over_imports: u64, + /// The live host imports those reports touched, summed over the reports: each a range of + /// bytes no-copy buffers or a no-copy heap lie over (two imports only where buffers of two + /// memory classes lie over the same bytes). + pub host_imports_remapped: u64, + /// The host imports the device made by pointer (`VK_EXT_external_memory_host`): no-copy + /// buffers', heaps', rebinds' and releasable ones' made again. A driver takes an import's + /// pages at its first submission (ANV's userptr on i915). + pub host_pointer_imports_made: u64, + /// Their bytes: whole pages, rounded out to the import's unit. + pub host_pointer_import_bytes_made: u64, + /// The live host imports the device never releases while idle as a heap's own import (a + /// no-copy heap's). With the next three and `host_imports_kept_for_fds`, they are every live + /// no-copy import the device keeps imported whatever reads it. + pub host_imports_kept_of_heap: u64, + /// The live host imports a rebind gave a buffer (`rebind.rs`): never released while idle. + pub host_imports_kept_rebound: u64, + /// Of those, the ones no live buffers' table listed yet (`live_buffers.rs`): no command + /// buffer committed since the rebind used a buffer lying in them, so no command reaches them + /// unnamed, as Metal reaches a rebound buffer only once a command buffer used it again. + pub host_imports_rebound_unlisted: u64, + /// The imports rebinds made of their new pages (`Device::rebind_host_pages`): not those that + /// lie in the import of a live buffer made over the same bytes (`host_aliases.rs`). + pub host_rebind_imports_made: u64, + /// Of those, the ones whose pages, rounded out to the import's unit, lay within the bytes, + /// rounded out likewise, that a buffer over host pages lay over already (a no-copy buffer + /// made or rebound there, the rebound buffer itself included, or a no-copy heap's own + /// buffer): an import alive then held each of their pages. + pub host_rebind_imports_covered: u64, + /// The live no-copy buffers' imports of host pages by their pointer, never released while + /// idle as the device's driver is not measured to read the pages mapped at the pointer at + /// each submission (`DriverFact::PointerImportsFollowTheirAddress`), or off Unix. + pub host_imports_kept_pointer: u64, + /// The live no-copy buffers' imports the device would release while idle, but keeps, as it + /// could make no stand-in buffer for a read of a released one. + pub host_imports_kept_no_stand_in: u64, /// Of those buffers, heaps and rebinds, the ones whose `VkBuffer` is a sparse buffer /// assembled from several chunks. pub dma_buf_sparse_buffers: u64, @@ -2452,6 +2679,12 @@ impl Device { let counters = &self.shared().counts; let group_end = |end: GroupEnd| counters.group_ends[end as usize].load(Ordering::Relaxed); let pending = |bucket: usize| counters.batches_by_pending[bucket].load(Ordering::Relaxed); + let read_apart = |reason: ReadApart| { + counters.host_imports_read_apart_by[reason as usize].load(Ordering::Relaxed) + }; + let kept = |because: KeptBecause| { + counters.host_imports_kept_by[because as usize].load(Ordering::Relaxed) + }; let begun = |what: Begun| counters.command_buffers_begun_by[what as usize].load(Ordering::Relaxed); let (allocated, census, (parked, waiting), (made, freed)) = { @@ -2537,6 +2770,8 @@ impl Device { stand_in_bytes: counters.stand_in_bytes.load(Ordering::Relaxed), stale_detached_reaches: counters.stale_detached_reaches.load(Ordering::Relaxed), detached_storage_reaches: counters.detached_storage_reaches.load(Ordering::Relaxed), + heap_slots_rewritten: counters.heap_slots_rewritten.load(Ordering::Relaxed), + host_range_lookups: self.shared().aliases.range_lookups(), heap_textures_tiled: counters.heap_textures_tiled.load(Ordering::Relaxed), heap_texture_lossless_layouts: counters .heap_texture_lossless_layouts @@ -2620,6 +2855,7 @@ impl Device { argument_samplers_taken: counters.argument_samplers_taken.load(Ordering::Relaxed), bind_views_worked_out: counters.bind_views_worked_out.load(Ordering::Relaxed), stage_tables_read: counters.stage_tables_read.load(Ordering::Relaxed), + no_copy_lies_read: counters.no_copy_lies_read.load(Ordering::Relaxed), commands_noted_as_before: counters.commands_noted_as_before.load(Ordering::Relaxed), draws_settled: counters.draws_settled.load(Ordering::Relaxed), depth16_sided_draws: counters.depth16_sided_draws.load(Ordering::Relaxed), @@ -2655,6 +2891,7 @@ impl Device { host_deallocators_delayed: counters.host_deallocators_delayed.load(Ordering::Relaxed), host_keep_alives_kept: counters.host_keep_alives_kept.load(Ordering::Relaxed), host_keep_alives_covered: counters.host_keep_alives_covered.load(Ordering::Relaxed), + host_mappings_queried: counters.host_mappings_queried.load(Ordering::Relaxed), dma_buf_imports: counters.dma_buf_imports.load(Ordering::Relaxed), dma_buf_memories_live: counters.dma_buf_memories_live.load(Ordering::Relaxed), dma_buf_image_memories_live: counters @@ -2663,8 +2900,35 @@ impl Device { host_imports_released: counters.host_imports_released.load(Ordering::Relaxed), host_imports_reimported: counters.host_imports_reimported.load(Ordering::Relaxed), host_imports_resident: counters.host_imports_resident.load(Ordering::Relaxed), + host_imports_used: counters.host_imports_used.load(Ordering::Relaxed), + host_imports_read_apart: counters.host_imports_read_apart.load(Ordering::Relaxed), + host_imports_read_apart_address: read_apart(ReadApart::Address), + host_imports_read_apart_vk_buffer: read_apart(ReadApart::VkBuffer), + host_imports_read_apart_binding: read_apart(ReadApart::Binding), + host_imports_read_apart_texture: read_apart(ReadApart::Texture), + host_imports_read_apart_second_buffer: read_apart(ReadApart::SecondBuffer), + host_imports_read_apart_unreleased: read_apart(ReadApart::Unreleased), + host_imports_kept_of_heap: kept(KeptBecause::Heap), + host_imports_kept_rebound: kept(KeptBecause::Rebind), + host_imports_kept_pointer: kept(KeptBecause::Pointer), + host_imports_kept_no_stand_in: kept(KeptBecause::NoStandIn), + host_imports_rebound_unlisted: counters + .host_imports_rebound_unlisted + .load(Ordering::Relaxed), + host_rebind_imports_made: counters.host_rebind_imports_made.load(Ordering::Relaxed), + host_rebind_imports_covered: counters + .host_rebind_imports_covered + .load(Ordering::Relaxed), + host_remaps_reported: counters.host_remaps_reported.load(Ordering::Relaxed), + host_remaps_over_imports: counters.host_remaps_over_imports.load(Ordering::Relaxed), + host_imports_remapped: counters.host_imports_remapped.load(Ordering::Relaxed), + host_pointer_imports_made: counters.host_pointer_imports_made.load(Ordering::Relaxed), + host_pointer_import_bytes_made: counters + .host_pointer_import_bytes_made + .load(Ordering::Relaxed), host_imports_lost: counters.host_imports_lost.load(Ordering::Relaxed), host_import_fds_kept: counters.host_import_fds_kept.load(Ordering::Relaxed), + host_imports_kept_for_fds: counters.host_imports_kept_for_fds.load(Ordering::Relaxed), dma_buf_sparse_buffers: counters.dma_buf_sparse_buffers.load(Ordering::Relaxed), dma_buf_images: counters.dma_buf_images.load(Ordering::Relaxed), dma_buf_image_fallbacks: counters.dma_buf_image_fallbacks.load(Ordering::Relaxed), diff --git a/crates/metal2vulkan-validation/src/runtime_lane/detach.rs b/crates/metal2vulkan-validation/src/runtime_lane/detach.rs index cb3cb936a..85f9129aa 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/detach.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/detach.rs @@ -19,16 +19,21 @@ //! first submission, the rebind encodes a compute or blit encoder again over them, and the //! command buffer completes over the new pages, as Metal's (`EncodedUseRebound` before). The //! layer reports nothing: no Vulkan command takes the detached buffer's stand-in. +//! - **Racing a commit.** A detach on one thread while another commits a command buffer whose +//! command names the buffer runs the old pages' deallocator in one of the two calls, wherever +//! the device's recorder replays the commands, and announces nothing. //! - **No memory.** A detach places no memory of the bytes it detaches: once the device's //! stand-in is made, detaching a large heap, and a large buffer, allocates no device memory. //! - **Textures**: `detach_textures.rs`. -use super::degrade_notices::{assert_made_once, on_device as on_device_noticed}; +use super::degrade_notices::{ + assert_made_once, assert_once_allowing, on_device as on_device_noticed, +}; use super::host_memory::{gpu_read, on_device, recording, Mapping, Seen}; use super::no_copy_heaps::shared; use super::rebind_reach::{ - buffer_len, buffer_over, deallocated, heap_member, member_over, node, pages, rebind_heap_to, - rebind_to, walk, Outputs, Uses, Walked, A, B, POINTER_WALKER, + buffer_len, buffer_over, deallocated, heap_member, kept_member_over, member_over, node, pages, + rebind_heap_to, rebind_to, walk, Outputs, Uses, Walked, A, B, POINTER_WALKER, }; use super::shared_kinds; use super::{ @@ -617,3 +622,103 @@ fn a_detach_of_a_large_heap_allocates_no_device_memory() { ); }); } + +/// The rounds of [`a_detach_racing_a_commit_runs_the_deallocator_in_one_of_the_two_calls`], for +/// each form: two sweeps of the offsets. +const RACES: u32 = 640; + +/// How far apart the detach and the commit of a race start, at most, either first. +const RACE_SPAN: Duration = Duration::from_micros(40); + +/// How far one race's offset is from the last's. +const RACE_STEP: Duration = Duration::from_nanos(250); + +/// When a race's two calls start, after its other thread is spawned. +const RACE_LEAD: Duration = Duration::from_micros(500); + +/// Spin until `at`. +fn spin_until(at: Instant) { + while Instant::now() < at { + std::hint::spin_loop(); + } +} + +/// A detach on one thread racing the commit, on another, of a command buffer whose blit names the +/// buffer: the old pages' deallocator runs once, in one of the two calls (the detach where it lets +/// go of the pages last, the commit where its encoder held them last), wherever the device's +/// recorder replays the command buffer's commands, and nothing is announced: with a keep-alive +/// and without one. The command buffer, which an event holds back until both calls returned, +/// then fails `DetachedBacking`. The races start the two calls up to 40 us apart, either first, +/// swept in steps of 0.25 us, so that many land inside each other. +#[test] +fn a_detach_racing_a_commit_runs_the_deallocator_in_one_of_the_two_calls() { + for (form, kept) in [("no keep-alive", false), ("keep-alive", true)] { + on_device_noticed(|device, messages| { + let queue = device.new_command_queue().unwrap(); + let event = device.new_shared_event().unwrap(); + let made = || match kept { + true => kept_member_over(device, A).map(|(buffer, seen, _)| (buffer, seen)), + false => member_over(device, A), + }; + let detacher = std::thread::current().id(); + let (mut in_detach, mut in_commit, mut late, mut elsewhere) = (0, 0, 0, 0); + let before = device.work_counts(); + let span = RACE_SPAN.as_nanos() as i64; + for round in 0..RACES { + let Some((buffer, seen)) = made() else { + return; + }; + let value = u64::from(round) + 1; + let command_buffer = queue.command_buffer().unwrap(); + command_buffer + .encode_wait_for_event(EventRef::from(&event), value) + .unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.fill_buffer(&buffer, 0..16, 0x5a).unwrap(); + blit.end_encoding().unwrap(); + // The commit's start less the detach's, swept over the span. + let step = RACE_STEP.as_nanos() as i64; + let offset = (i64::from(round) * step) % (2 * span) - span; + let start = Instant::now() + RACE_LEAD; + let late_by = |ns: i64| Duration::from_nanos(ns.max(0) as u64); + let (commit_at, detach_at) = (start + late_by(offset), start + late_by(-offset)); + let committer = std::thread::scope(|scope| { + let committing = scope.spawn(|| { + spin_until(commit_at); + command_buffer.commit().unwrap(); + std::thread::current().id() + }); + spin_until(detach_at); + detach(&buffer); + committing.join().unwrap() + }); + let ran = *seen.thread.lock().unwrap(); + match (seen.runs.load(Ordering::SeqCst), ran) { + (1, Some(thread)) if thread == detacher => in_detach += 1, + (1, Some(thread)) if thread == committer => in_commit += 1, + (0, _) => late += 1, + _ => elsewhere += 1, + } + event.set_signaled_value(value); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + detached_backing(&command_buffer, form); + deallocated(&seen); + assert_eq!(seen.runs.load(Ordering::SeqCst), 1, "{form}: ran once"); + } + let inline = device.work_counts().command_buffers_replayed_inline + - before.command_buffers_replayed_inline; + eprintln!( + "DETACH race {} ({form}): {RACES} races, the deallocator ran in the detach {in_detach}, \ + in the commit {in_commit}, after both returned {late}, on another thread \ + {elsewhere}; {inline} command buffers replayed off the recorder's thread", + device.name() + ); + assert_eq!( + (late, elsewhere), + (0, 0), + "{form}: the deallocator ran outside the detach and the commit" + ); + assert_once_allowing(&messages.take_notices(), &[], &shared_kinds(device)); + }); + } +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/detach_textures.rs b/crates/metal2vulkan-validation/src/runtime_lane/detach_textures.rs index e73d5fecd..b84793ef4 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/detach_textures.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/detach_textures.rs @@ -24,6 +24,10 @@ //! where Metal reads zero; `DetachedStorageKeepsWrites` is announced once for it, with its ID, //! and `StaleDetachedReach` is not ([`DETACHED_REACHES`]). A device without //! `shaderStorageImageReadWithoutFormat` refuses that kernel, typed. +//! - **Only its own slots**: a detach, and a rebind, of one form's bytes write again the heap slots +//! of the textures over them alone (`WorkCounts::heap_slots_rewritten`), and every texture, +//! those over the other form's bytes and one of the device's own among them, reads its own +//! texels through its slot after each. //! - **Attached again**: a rebind gives every texture its pages back, those made while detached //! among them; a kernel's write of one made while detached lands in the new pages, through the //! copy back that dispatches where the device's does. @@ -510,6 +514,108 @@ fn a_rebind_gives_every_texture_its_pages_again() { }); } +/// Texels of the `n`th texture of [`a_rebind_or_a_detach_rewrites_its_own_textures_slots_alone`] +/// as of its `round`th fill, apart from every other texture's and round's. +fn marked(n: usize, round: usize) -> [f32; 16] { + std::array::from_fn(|i| (n * 100 + round * 20 + i) as f32) +} + +/// What [`QUERY_READ`] writes of a source holding `source`: each texel plus `(4, 0, 0, 0)`, its +/// width and not null. +fn read_of(source: &[f32; 16]) -> [f32; 16] { + std::array::from_fn(|i| source[i] + if i % 4 == 0 { 4.0 } else { 0.0 }) +} + +/// A detach and a rebind of one form's bytes write again the heap slots of the textures over +/// them alone (`WorkCounts::heap_slots_rewritten`): two for the two textures over them, after a +/// detach and after the rebind that gives them pages again, and two or none after a rebind of +/// attached bytes (none where nothing over them was remade: shadows of the bytes), none for the +/// two textures over the other form's bytes or for the device's own. After each, every texture +/// reads its own texels through its slot: a kernel reads each through its argument buffer, made +/// resident, those over the bytes filled again after the rebind. +#[test] +fn a_rebind_or_a_detach_rewrites_its_own_textures_slots_alone() { + on_device(|device| { + let query = QueryRead::new(device); + let (Some(buffer), Some(heap)) = ( + Bytes::new(device, Over::Buffer), + Bytes::new(device, Over::Heap), + ) else { + return; + }; + // Two textures over each form's bytes, and one of the device's own, by the form's index. + let mut textures: Vec<(Option, Texture)> = Vec::new(); + for (form, bytes) in [&buffer, &heap].into_iter().enumerate() { + let descriptor = query.descriptor(bytes.options()); + for index in 0..2 { + let Some(texture) = bytes.texture(&descriptor, index) else { + return; + }; + textures.push((Some(form), texture)); + } + } + textures.push((None, query.own(device, &[0.0; 16]))); + let mut held: Vec<[f32; 16]> = (0..textures.len()).map(|n| marked(n, 0)).collect(); + for ((_, texture), texels) in textures.iter().zip(&held) { + fill(texture, texels); + } + let read_all = |held: &[[f32; 16]], step: &str| { + for (n, ((form, texture), want)) in textures.iter().zip(held).enumerate() { + let target = query.own(device, &[0.0; 16]); + let run = query.run(device, texture, &target, &[texture, &target]); + completed(&run); + assert_eq!( + texels(&target), + read_of(want), + "{step}: texture {n} over {form:?}" + ); + } + }; + read_all(&held, "made"); + let rewritten = || device.work_counts().heap_slots_rewritten; + let mut round = 0; + let forms = [(&buffer, "a no-copy buffer"), (&heap, "a no-copy heap")]; + for (form, (bytes, over)) in forms.into_iter().enumerate() { + let refill = |held: &mut [[f32; 16]], round: usize| { + for (n, (of, texture)) in textures.iter().enumerate() { + if *of == Some(form) { + held[n] = marked(n, round); + fill(texture, &held[n]); + } + } + }; + let before = rewritten(); + bytes.rebind(); + let attached = rewritten() - before; + assert!( + attached == 0 || attached == 2, + "{over}: a rebind rewrote {attached} slots" + ); + round += 1; + refill(&mut held, round); + read_all(&held, &format!("{over}, rebound")); + + let before = rewritten(); + bytes.detach(); + assert_eq!(rewritten() - before, 2, "{over}: the detach"); + let before = rewritten(); + bytes.rebind(); + assert_eq!( + rewritten() - before, + 2, + "{over}: the rebind after the detach" + ); + round += 1; + refill(&mut held, round); + read_all(&held, &format!("{over}, detached and rebound")); + eprintln!( + "DETACH textures: {over}: a rebind rewrote {attached} heap slots, a detach and \ + its rebind 2 each, of 5 textures" + ); + } + }); +} + /// A texture made while its bytes are detached is their shadow, presenting a stand-in; once the /// bytes lie in pages again, a kernel's write of it lands in them, both forms. Where the device /// copies a shadow back by a dispatch (`DriverFact::ShadowCopyBackDispatchFaster`), that dispatch diff --git a/crates/metal2vulkan-validation/src/runtime_lane/dma_buf_imports.rs b/crates/metal2vulkan-validation/src/runtime_lane/dma_buf_imports.rs index a7ea699b4..d50dbe043 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/dma_buf_imports.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/dma_buf_imports.rs @@ -669,6 +669,80 @@ fn a_view_past_one_udmabuf_s_limits_is_assembled_from_chunks() { }); } +/// [`every_other_page`]'s 64 pages, each its own mapping, as a consumer's view of a surface's +/// scattered pages: a no-copy buffer over them all asks the kernel about each of the 64 mappings +/// for their write permission before its import (`WorkCounts::host_mappings_queried`), refused or +/// not. A second buffer over the same bytes, made while the first lives, lies in its import and +/// asks about none, its source uncalled, and the GPU reads the CPU's bytes through it. A buffer +/// over the first half of the bytes, not the same range, makes its own import and asks about its +/// 32 mappings. +#[test] +fn a_buffer_that_lies_in_a_live_import_asks_about_no_mapping() { + const TEST: &str = "dma-buf joined import"; + const RUNS: usize = 64; + if !udmabuf_openable(TEST) { + return; + } + on_device(|device| { + let page = host_page(); + let queue = device.new_command_queue().unwrap(); + let (ram, view, expected) = every_other_page(RUNS); + let length = RUNS * page; + let queried = || device.work_counts().host_mappings_queried; + let before = queried(); + let calls = Calls::default(); + let first = no_copy(device, &view, 0, length, ram.source(&view, &calls)); + let asked = queried() - before; + assert_eq!( + asked, RUNS as u64, + "{TEST}: the first buffer's mappings asked" + ); + let first = match (imports_dma_buf(device), first) { + (_, Ok(first)) => first, + (None, Err(error)) => { + eprintln!("{TEST}: on {}: {error:?}", device.name()); + return; + } + (Some(_), Err(error)) => panic!("{TEST}: {error:?}"), + }; + let before = queried(); + let joined = Calls::default(); + let second = no_copy(device, &view, 0, length, ram.source(&view, &joined)).unwrap(); + assert_eq!( + queried() - before, + 0, + "{TEST}: the second buffer's mappings asked" + ); + let joined = joined.lock().unwrap().clone(); + assert!(joined.is_empty(), "{TEST}: the second's source: {joined:?}"); + assert!( + gpu_read(&queue, &second, 0..length as u64) == expected, + "{TEST}: the GPU's read through the second buffer" + ); + let before = queried(); + let half = no_copy( + device, + &view, + 0, + length / 2, + ram.source(&view, &Calls::default()), + ); + assert_eq!( + queried() - before, + RUNS as u64 / 2, + "{TEST}: the half's mappings asked ({:?})", + half.as_ref().err() + ); + eprintln!( + "{TEST}: on {}: {RUNS} mappings asked for the first buffer, none for the second", + device.name() + ); + drop(half); + drop(second); + drop(first); + }); +} + /// The refusals: memfd memory with no source is refused typed where the device refuses its /// pointer (RADV), as before; a source that fails keeps that refusal, called once; chunks that do /// not cover the pages, and a chunk whose descriptor is no dma-buf (the memfd itself), are the diff --git a/crates/metal2vulkan-validation/src/runtime_lane/draw_work.rs b/crates/metal2vulkan-validation/src/runtime_lane/draw_work.rs index ffa36fb05..c162004c9 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/draw_work.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/draw_work.rs @@ -29,6 +29,8 @@ //! its own. //! - **Stage tables.** A draw reads into its encoder's bind state only the stage tables a call //! changed since a draw read them, through the same pipeline state's interface +//! (`WorkCounts::stage_tables_read`), and looks at where a no-copy buffer a table binds lies +//! once for its binding and once for its descriptor (`WorkCounts::no_copy_lies_read`). //! - **Pipelines.** A draw of a pipeline state one of whose last draws found its `VkPipeline` //! made, of the same variant and an equal key, finds that entry again without looking the key //! up (`WorkCounts::graphics_pipelines_looked_up`), states and keys switched between included. @@ -916,6 +918,62 @@ fn draws_into_a_pass_color_their_state_lacks_copy_no_color_set() { }); } +/// Draws whose encoder reads a table binding a no-copy buffer (the corners, over host pages, at +/// vertex buffer 0) again at each draw, for the bytes each sets at vertex buffer 1, look at where +/// the buffer lies at most twice each (`WorkCounts::no_copy_lies_read`): once for its binding, +/// its base and device address read together (`Buffer::base_and_device_address`), and once for a +/// descriptor written for it (`Buffer::space`), where each read took two looks. A build with +/// debug assertions looks once more a draw, as its check of the table brought in place reads the +/// slot whole again (`ArgumentTable::check_reading`). The target is the texture's. +#[test] +fn draws_reading_a_no_copy_buffer_s_binding_look_where_it_lies_once() { + use super::host_memory::{host_page, no_copy, Mapping}; + on_device(|device, _| { + let scene = Scene::new(device); + let red = solid(device, PixelFormat::RGBA8Unorm, RED); + let page = host_page(); + let pages = Mapping::anonymous(page); + pages.write(0, &[-1.0f32, -1.0, 1.0, 1.0].map(f32::to_le_bytes).concat()); + // SAFETY: the pages are this process's, mapped read and write, and outlive the buffer, + // which goes first. + let corners = unsafe { + no_copy( + device, + pages.pointer(), + page, + ResourceOptions::shared(), + None, + ) + } + .unwrap(); + let (command_buffer, mut encoder) = scene.encoder(device); + encoder.set_vertex_buffer(Some(&corners), 0, 0).unwrap(); + encoder.set_fragment_texture(Some(&red), 0).unwrap(); + let mut first = None; + for at in 0..SIDE { + encoder.set_vertex_bytes(&at.to_le_bytes(), 1).unwrap(); + draw(&mut encoder); + if at == 0 { + first = Some(device.work_counts()); + } + } + let (first, rest) = (first.unwrap(), device.work_counts()); + encoder.end_encoding().unwrap(); + let later = SIDE - 1; + eprintln!( + "DRAW-WORK {}: {} looks at where the buffer lies, {} tables read", + device.name(), + grew(&first, &rest, |c| c.no_copy_lies_read), + grew(&first, &rest, |c| c.stage_tables_read), + ); + assert_eq!(grew(&first, &rest, |c| c.stage_tables_read), later); + let looks = 2 + u64::from(cfg!(debug_assertions)); + assert!(grew(&first, &rest, |c| c.no_copy_lies_read) <= looks * later); + let pixels = scene.pixels(&command_buffer); + assert!(pixels.iter().all(|&p| p == RED), "{pixels:?}"); + }); +} + /// Whether `device` has unified memory, or host-coherent, host-cached memory none of whose types /// is device-local: its upload arenas then lie outside device-local memory. fn uploads_outside_device_memory(device: &Device) -> bool { diff --git a/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs b/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs index 0b034129f..0e650f571 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/frame_costs.rs @@ -1419,6 +1419,16 @@ fn measure(runs: &[Run]) { per_frame(|c| c.batches_with_two_or_three_pending), per_frame(|c| c.batches_with_four_or_more_pending), ); + eprintln!( + "FRAME-COST {name} {label}: a frame's host remap reports {:.1}, {:.1} of them over \ + live imports, touching {:.1} imports; {:.1} imports made by pointer, {:.1} KiB of \ + pages (each taken at its first kernel submission on i915)", + per_frame(|c| c.host_remaps_reported), + per_frame(|c| c.host_remaps_over_imports), + per_frame(|c| c.host_imports_remapped), + per_frame(|c| c.host_pointer_imports_made), + per_frame(|c| c.host_pointer_import_bytes_made) / 1024.0, + ); eprintln!( "FRAME-COST {name} {label}: the device's live VkDeviceMemory after the timed frames \ (what ANV on i915 lists in each kernel submission, beside its own buffer objects): \ diff --git a/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs b/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs index 10a239d4e..d1e062cc2 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/host_memory.rs @@ -2,7 +2,7 @@ //! purgeable state on the device the cfg selects, under the validation layer. Each test fails on //! any validation message, so a leaked import or buffer fails it too. //! -//! The host memory is the consumer's (`paravirt-decompile`): guest RAM is one shared memory +//! The host memory is the consumer's (reims-vgpu): guest RAM is one shared memory //! object, and the buffers wrap a second, 16-KiB-aligned mapping of some of its pages //! (`gpu_task/memory.rs`'s `no_copy_buffer`, with a deallocator that unmaps it; `display/efi.rs`'s //! framebuffer, with none), with resource options 0. The CPU writes through the guest RAM diff --git a/crates/metal2vulkan-validation/src/runtime_lane/rebind_reach.rs b/crates/metal2vulkan-validation/src/runtime_lane/rebind_reach.rs index 3b8fd5a3f..4c908ca97 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/rebind_reach.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/rebind_reach.rs @@ -319,7 +319,10 @@ impl Drop for DropFlag { /// A no-copy buffer over a node of `value`, its deallocator's runs in a `Seen` of its own, whose /// keep-alive holds the mapping and sets the flag returned as it drops; `None`, printed, where the /// device imports no host memory. -fn kept_member_over(device: &Device, value: u32) -> Option<(Buffer, Arc, Arc)> { +pub(super) fn kept_member_over( + device: &Device, + value: u32, +) -> Option<(Buffer, Arc, Arc)> { let seen = Arc::new(Seen::default()); let dropped = Arc::new(AtomicBool::new(false)); let mapping = pages(buffer_len(), 0, &node(value)); diff --git a/crates/metal2vulkan-validation/src/runtime_lane/rebinds.rs b/crates/metal2vulkan-validation/src/runtime_lane/rebinds.rs index 023573b94..ed1a6797b 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/rebinds.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/rebinds.rs @@ -282,6 +282,69 @@ fn rebinding_one_of_two_buffers_over_one_memory_moves_it_alone() { }); } +/// A rebind onto the bytes a live no-copy buffer was made over lies in that buffer's import, as a +/// buffer made over them does: it asks the kernel about none of their mappings +/// (`WorkCounts::host_mappings_queried`, which Linux's imports count) and imports nothing, and the +/// GPU reads and writes those bytes through either buffer. Rebound back onto bytes no live buffer +/// was made over, it imports them, asking about their mapping, and reads them. +#[test] +fn a_rebind_onto_a_live_buffer_s_bytes_lies_in_its_import() { + on_device(|device| { + let queue = device.new_command_queue().unwrap(); + let (live_seen, moved_seen, onto_seen, back_seen) = ( + Arc::new(Seen::default()), + Arc::new(Seen::default()), + Arc::new(Seen::default()), + Arc::new(Seen::default()), + ); + let queried = || device.work_counts().host_mappings_queried; + let shared = host(LEN, 5); + let shared_pointer = shared.pointer(); + let Some(live) = buffer_over(device, shared, &live_seen) else { + return; + }; + let Some(moved) = buffer_over(device, host(LEN, 6), &moved_seen) else { + return; + }; + let before = queried(); + // SAFETY: the shared mapping lives until the live buffer goes, after the moved one leaves + // it; no other thread encodes or commits meanwhile. + unsafe { + moved.rebind_bytes_no_copy( + HostMemory::new(shared_pointer), + Some(recording(&onto_seen, ())), + None, + ) + } + .unwrap(); + assert_eq!(queried() - before, 0, "mappings asked for the live import"); + assert_eq!(moved.contents(), Some(shared_pointer)); + assert_eq!(gpu_read(&queue, &moved, 0..64), counting(LEN, 5)[..64]); + gpu_fill(&queue, &moved, 0..16, 0x5d); + gpu_fill(&queue, &live, 16..32, 0x2e); + let both = [[0x5d; 16], [0x2e; 16]].concat(); + // SAFETY: the shared mapping lives; no command writes it now. + assert_eq!(unsafe { at(shared_pointer, 0..32) }, both); + assert_eq!(gpu_read(&queue, &live, 0..32), both); + assert_eq!(gpu_read(&queue, &moved, 0..32), both); + // Back onto fresh bytes: imported, their mapping asked about where Linux counts it. + let back = host(LEN, 7); + let before = queried(); + rebind(&moved, back, &back_seen).unwrap(); + let asked = queried() - before; + assert_eq!( + asked > 0, + cfg!(target_os = "linux"), + "{asked} mappings asked" + ); + assert_eq!(gpu_read(&queue, &moved, 0..64), counting(LEN, 7)[..64]); + ran(&onto_seen, shared_pointer, LEN, &both[..16], Thread::Any); + drop(moved); + drop(live); + eprintln!("REBIND onto a live import: no mapping asked; back: {asked} asked"); + }); +} + /// The consumer's task memory, rebound: a public kernel case runs over no-copy buffers, which are /// then rebound to new pages holding the case's inputs; the case run again reads them and writes /// its output into the new pages, matching Metal's output, at the same `gpu_address`es. diff --git a/crates/metal2vulkan-validation/src/runtime_lane/submit_per_import.rs b/crates/metal2vulkan-validation/src/runtime_lane/submit_per_import.rs index 94d0c47cf..028c7639f 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/submit_per_import.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/submit_per_import.rs @@ -28,15 +28,29 @@ //! submissions per commit, the objects each lists (dma-bufs and userptrs among them) and the //! microseconds each spent in the ioctl. Its slope over `n` is the kernel's cost per entry. //! -//! Ignored by default: a measurement, not a check. Run it by name with `--run-ignored all`; on a +//! A second measurement holds a guest's shape (`submit_per_import_guest_shape`): [`GUEST_IMPORTS`] +//! pointer imports, of which each frame's blits read [`GUEST_USED`], in frames of +//! [`GUEST_PER_FRAME`] command buffers. It measures frames at once, every import resident, then, +//! where the driver's pointer imports follow their address +//! (`DriverFact::PointerImportsFollowTheirAddress`), again once the device's residency thread +//! released the idle ones while paced frames kept the read ones in use. Printed as +//! `SUBMIT-GUEST-SHAPE` lines: the imports (`WorkCounts::host_imports_live`, +//! `host_imports_resident`, `host_imports_released`, `host_imports_reimported`), a frame's wall +//! time, the scheduler thread's CPU time a frame and, where the kernel-submission counter is +//! preloaded, the kernel submissions a frame, the objects and userptrs each lists and the +//! microseconds a frame spent in the ioctl. +//! +//! Ignored by default: measurements, not checks. Run them by name with `--run-ignored all`; on a //! host without `/dev/udmabuf` access the dma-buf rows say so and are skipped. +use super::commit_costs::percentiles; use super::commit_latency::named_cpu_us; use super::dma_buf_imports::{no_copy as dma_buf_no_copy, udmabuf_openable, Calls, Memfd}; use super::host_memory::{no_copy, Mapping}; use super::submit_costs::Execbuffers; use super::{validated_device_with, Messages, ScratchCache, WAIT}; use crate::gpu::TEST_DEVICE; +use metal2vulkan::device::DriverFact; use metal2vulkan_runtime::{ Buffer, CommandBuffer, CommandBufferStatus, CommandQueue, Device, ResourceOptions, }; @@ -54,6 +68,17 @@ const COMMITS: usize = 300; const RELEASED: Duration = Duration::from_secs(30); /// The linux name (15 bytes) of the device's scheduler thread. const SCHEDULER: &str = "metal2vulkan-sc"; +/// The guest's shape (a macOS guest's desktop on the Iris Xe of RPL-P, its counts of 2026-10-17): +/// its live host imports, those its frames' blits read, and its command buffers a frame. +const GUEST_IMPORTS: usize = 520; +const GUEST_USED: usize = 35; +const GUEST_PER_FRAME: usize = 43; +/// The guest-shape frames measured, after [`GUEST_WARM`] untimed, each committed in a row and +/// waited for at its end. +const GUEST_FRAMES: usize = 120; +const GUEST_WARM: usize = 10; +/// The frame period while the device's residency thread releases the idle imports. +const GUEST_PERIOD: Duration = Duration::from_micros(16_667); /// The kind of import a phase holds. #[derive(Clone, Copy, Debug)] @@ -226,3 +251,131 @@ fn submit_per_import() { } } } + +/// One guest-shape frame: [`GUEST_PER_FRAME`] command buffers committed in a row, the first of +/// which each copy 4 KiB out of one of `used` into `target`, the rest each fill `target`'s 4 KiB; +/// waited for at its end. +fn guest_frame(queue: &CommandQueue, target: &Buffer, used: &[Buffer]) { + let mut last = None; + for i in 0..GUEST_PER_FRAME { + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + match used.get(i) { + Some(import) => blit + .copy_from_buffer_to_buffer(import, 0, target, 0, 4096) + .unwrap(), + None => blit.fill_buffer(target, 0..4096, i as u8).unwrap(), + } + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + last = Some(command_buffer); + } + let last = last.expect("a frame of command buffers"); + last.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(last.status(), CommandBufferStatus::Completed); +} + +/// Guest-shape frames measured and printed as `phase`. +fn guest_measure( + device: &Device, + queue: &CommandQueue, + target: &Buffer, + used: &[Buffer], + phase: &str, +) { + for _ in 0..GUEST_WARM { + guest_frame(queue, target, used); + } + let counts = device.work_counts(); + let execbuffers = Execbuffers::read(); + let scheduler = named_cpu_us(SCHEDULER); + let times: Vec = (0..GUEST_FRAMES) + .map(|_| { + let start = Instant::now(); + guest_frame(queue, target, used); + start.elapsed().as_secs_f64() * 1e6 + }) + .collect(); + let scheduler = (named_cpu_us(SCHEDULER) - scheduler) / GUEST_FRAMES as f64; + let after = device.work_counts(); + let [p10, p50, p90] = percentiles(times); + let kernel = Execbuffers::read() + .zip(execbuffers) + .map(|(after, before)| { + let submissions = (after.execbuffers - before.execbuffers) as f64; + let each = |after: u64, before: u64| (after - before) as f64 / submissions; + format!( + "; {:.1} kernel submissions a frame, {:.0} objects each ({:.0} userptrs), {:.0} us \ + a frame in the ioctl ({:.1} us each)", + submissions / GUEST_FRAMES as f64, + each(after.objects, before.objects), + each(after.userptr, before.userptr), + (after.nanos - before.nanos) as f64 / 1e3 / GUEST_FRAMES as f64, + each(after.nanos, before.nanos) / 1e3, + ) + }) + .unwrap_or_default(); + eprintln!( + "SUBMIT-GUEST-SHAPE {}: {phase}: {} host imports live, {} to {} releasable resident, {} \ + released and {} imported again in all; frame p50 {p50:.0} us (p10 {p10:.0}, p90 \ + {p90:.0}); scheduler thread {scheduler:.1} us a frame{kernel}", + device.name(), + after.host_imports_live, + counts.host_imports_resident, + after.host_imports_resident, + after.host_imports_released, + after.host_imports_reimported, + ); +} + +/// The guest's shape, printed (the module docs). +#[test] +#[ignore = "a measurement, not a check: run by name with --run-ignored all"] +fn submit_per_import_guest_shape() { + let cache = ScratchCache::new().unwrap(); + let messages = Messages::default(); + let device = validated_device_with(TEST_DEVICE, &messages, cache.path(), |options| { + options.layers.clear(); + // A consumer's device keeps no execution record. + options.record_executions = false; + }) + .unwrap(); + let queue = device.new_command_queue().unwrap(); + let target = device.new_buffer(4096, ResourceOptions::shared()).unwrap(); + let pages = Mapping::anonymous(GUEST_IMPORTS * IMPORT_BYTES); + pages.fill(0x5a); + let buffers: Vec = (0..GUEST_IMPORTS) + .map(|i| { + // SAFETY: the pages are this process's, mapped read and write, and outlive the + // buffers (dropped first). + let at = unsafe { pages.pointer().add(i * IMPORT_BYTES) }; + // SAFETY: as above. + unsafe { no_copy(&device, at, IMPORT_BYTES, ResourceOptions::shared(), None) }.unwrap() + }) + .collect(); + let used = &buffers[..GUEST_USED]; + guest_measure(&device, &queue, &target, used, "at once"); + let follows = + (device.properties().driver_facts).contains(&DriverFact::PointerImportsFollowTheirAddress); + if !follows { + eprintln!( + "SUBMIT-GUEST-SHAPE {}: pointer imports kept (the driver is not measured to have them \ + follow their address)", + device.name() + ); + return; + } + let start = Instant::now(); + while device.work_counts().host_imports_resident > GUEST_USED as u64 { + assert!(start.elapsed() < RELEASED, "idle imports still resident"); + let frame = Instant::now(); + guest_frame(&queue, &target, used); + std::thread::sleep(GUEST_PERIOD.saturating_sub(frame.elapsed())); + } + let waited = format!( + "released after {:.1} s of paced frames", + start.elapsed().as_secs_f64() + ); + guest_measure(&device, &queue, &target, used, &waited); + drop(buffers); +} diff --git a/crates/metal2vulkan/src/device/driver_facts.rs b/crates/metal2vulkan/src/device/driver_facts.rs index 926b055a3..5c9cb5d28 100644 --- a/crates/metal2vulkan/src/device/driver_facts.rs +++ b/crates/metal2vulkan/src/device/driver_facts.rs @@ -1460,6 +1460,15 @@ pub enum DriverFact { /// or `shared-exponent-kept`, and its exact tile store (`TileStorePolicy::Exact`) adds no load /// pass for such an attachment. TileStoreIsMetals, + /// A buffer bound to memory the driver imported from a host pointer + /// (`VK_EXT_external_memory_host`) reads and writes, at each submission, the pages mapped at + /// that pointer then: pages the process maps over the address after the import (`mmap` with + /// `MAP_FIXED`) take the place of those it was made over, for the GPU as for the CPU. Vulkan + /// states nothing of a remap under a live import, and Metal's no-copy buffer keeps the pages + /// wired when it was made. ANV on i915 imports a pointer as a userptr object, whose pages the + /// kernel gets again at the next execbuffer once a remap invalidated them (Linux 7.2.9's + /// `i915_gem_object_userptr_submit_init`, or at its first execbuffer, before which nothing was + PointerImportsFollowTheirAddress, } impl DriverFact { @@ -1885,6 +1894,14 @@ const DYNAMIC_RESTART_WARNING: DriverDiagnostic = DriverDiagnostic { /// left a third answer; RADV, Mesa 26.0.8, on the RX 7900 XTX, clean at dd718a7905 but an /// unmeasured identity (`MEASURED_DEVICES`); and every GPU and release not measured, which store /// with `STORE`. +/// +/// `PointerImportsFollowTheirAddress`: ANV, Mesa 26.2.4 on the Iris Xe of RPL-P under Linux 7.2.9's +/// i915, measured with a probe outside the runtime (2026-10-17): a page of a `memfd` filled with +/// `0xaa`, mapped shared at an address and imported by its pointer as a buffer's memory, read +/// `0xaa` through a copy; another `memfd`'s page of `0xbb` mapped over the address with `MAP_FIXED`, +/// the next copy read `0xbb`; a page of `0xa2` imported and replaced by one of `0xb2` before any +/// submission, the first copy read `0xb2`. lavapipe (`MESA_LLVMPIPE`) from Mesa 26.0.8 through +/// 26.2.4 by construction, read in both releases' `lvp_AllocateMemory`, which binds an import's pub(crate) const MEASURED: &[Measured] = &[ Measured { fact: DriverFact::RobustIndexFetchReadsZero, @@ -2389,6 +2406,22 @@ pub(crate) const MEASURED: &[Measured] = &[ device: None, first: moltenvk(1, 4, 1), last: moltenvk(1, 4, 1), + }, + Measured { + fact: DriverFact::PointerImportsFollowTheirAddress, + driver: DriverId::INTEL_OPEN_SOURCE_MESA, + vendor: Some(INTEL_VENDOR_ID), + device: Some(INTEL_IRIS_XE_RPL_P), + first: mesa(26, 2, 4), + last: mesa(26, 2, 4), + }, + Measured { + fact: DriverFact::PointerImportsFollowTheirAddress, + driver: DriverId::MESA_LLVMPIPE, + vendor: None, + device: None, + first: mesa(26, 0, 8), + last: mesa(26, 2, 4), }, device: Some(INTEL_IRIS_XE_RPL_P), first: mesa(26, 2, 4), diff --git a/crates/metal2vulkan/src/device/tests/driver_facts.rs b/crates/metal2vulkan/src/device/tests/driver_facts.rs index d79692f48..c0afedb7a 100644 --- a/crates/metal2vulkan/src/device/tests/driver_facts.rs +++ b/crates/metal2vulkan/src/device/tests/driver_facts.rs @@ -533,6 +533,7 @@ const STALL: DriverFact = DriverFact::SemaphoreOperationsStallSubmits; const SAMPLED_HIZ: DriverFact = DriverFact::SampledDepthKeepsHiZ; const MSAA_DEPTH: DriverFact = DriverFact::MultisampledDepthFasterOutOfGeneral; const TILE_STORE: DriverFact = DriverFact::TileStoreIsMetals; +const FOLLOWS: DriverFact = DriverFact::PointerImportsFollowTheirAddress; /// Every committed profile's driver has exactly its measured facts (on a measured identity those /// its rows name, on any other its driver's defects alone). A profile of a measured identity: the @@ -556,6 +557,7 @@ const TILE_STORE: DriverFact = DriverFact::TileStoreIsMetals; /// shadow's copy back runs faster as a dispatch on the RPL-S and the RPL-P, and a merged shadow's /// copy in with its keep on the RPL-S alone, and a copy of rows /// linear-tiling attachment features uninitialized; NVIDIA's stalls a submission per thousand +/// semaphore operations on the RTX 5080 Laptop GPU; pointer imports follow their address on the /// profile is an unmeasured identity and takes its driver's defects alone: the GTX 1060 /// (580.178.04) and the RTX 5080 desktop GPU (another GPU at 615.71.09) NVIDIA's custom-position /// depth, the ARL (26.2.3) and the Tiger Lake Iris Xe (26.2.2) ANV's hidden aliased writes; the @@ -584,11 +586,11 @@ fn the_committed_profiles_drivers_have_their_facts() { ), ( "gate-lavapipe", - vec![DENORMALS, FRAGDEPTH, DEPTH16, FETCH, BC6H], + vec![DENORMALS, FRAGDEPTH, DEPTH16, FETCH, BC6H, FOLLOWS], ), ( "gate-lavapipe-x86_64", - vec![DENORMALS, FRAGDEPTH, DEPTH16, FETCH, BC6H], + vec![DENORMALS, FRAGDEPTH, DEPTH16, FETCH, BC6H, FOLLOWS], ), ("intel-arl-anv", vec![HIDE]), ("intel-irisxe-anv", vec![HIDE]), @@ -606,6 +608,7 @@ fn the_committed_profiles_drivers_have_their_facts() { COPY_BACK, SAMPLED_HIZ, MSAA_DEPTH, + FOLLOWS, ], ), ( diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 52853b31f..db654fd74 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -203,6 +203,12 @@ recorded here. Open differences from Metal that no note announces yet, and runtime costs still above the driver's. Each is open work. +- **A no-copy buffer imported by its pointer follows a remap of its pages** on a driver whose + pointer imports follow their address (`DriverFact::PointerImportsFollowTheirAddress`: ANV on + `MAP_FIXED`) are what its later command buffers read and write, where Metal's buffer keeps the + pages it was made over. `HostMemory::new`'s contract forbids such a remap under a live buffer, + and no notice tells of it. An import of dma-bufs (`HostMemory::with_dma_buf`) keeps its pages on + every driver, but is taken only where the device refuses the pointer. - **A runtime sampler's nearest sample of an 8-bit sRGB texture under native sampling.** On a device that samples the format, the sample keeps the device's sRGB decode (announced as `SrgbTexelDecode`), where the table's exact decode of the one texel it reads would cost little: diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 97e7ad3a4..cf49024e1 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -183,69 +183,44 @@ rebind that cannot make the image again is refused (`NotImplemented(RebindTextur `dma_buf_image_fallbacks` count what the route did. RADV lists every memory a device imported in every kernel submission, and amdgpu's work for a -submission grows with each entry, whether a command uses it or not. So the runtime releases a -no-copy buffer's import of dma-bufs that only blits have read (copies and fills of the buffer, -copies between it and a texture) and no pending command buffer holds, once it has stayed idle for -its window (2 seconds at first, doubled at each import again, up to 64 seconds), and imports it -again at the buffer's next blit, on the thread that encodes it, which pays that time. The new -import comes from the same dma-bufs, never from the source, so the buffer keeps the pages it was -made over even after `host_range_remapped`. Nothing of Metal's observes the release: the buffer's -bytes, its Metal address and its pages stay, and the CPU's writes made meanwhile are read. The -runtime holds a duplicate descriptor of each released chunk, within a quarter of the process's -`RLIMIT_NOFILE` soft limit (an import past it stays imported), and changes no limit: where many -no-copy buffers stand at once, raise the soft limit toward the hard one at startup (`setrlimit`), -as QEMU does. A buffer stays imported for good once its Metal address is handed out -(`gpu_address`, a binding, an argument buffer or table, an indirect command buffer, -`use_resource`), its `VkBuffer` is read, a texture is made over its bytes, or a second buffer lies -in its import; so do a heap's and a rebind's imports and memory imported by its pointer. A blit -whose released buffer the device cannot import again (out of memory) is refused. -`WorkCounts::host_imports_released`, `host_imports_reimported`, `host_imports_resident` and -`host_import_fds_kept` count it. +submission grows with each entry, whether a command uses it or not; ANV on i915 lists every memory +in every execbuffer too, a pointer import (an i915 userptr) costing about three times an ordinary +buffer object. So the runtime releases a no-copy buffer's own import that only blits have read +(copies and fills of the buffer, copies between it and a texture) and no pending command buffer +holds, once it has stayed idle for its window (2 seconds at first, doubled at each import again, up +to 64 seconds), and imports it again at the buffer's next blit, on the thread that encodes it, +which pays that time. Nothing of Metal's observes the release: the buffer's bytes, its Metal +address and its pages stay, and the CPU's writes made meanwhile are read. Two kinds of import are +released: -A texture over a buffer's bytes is an image over them where its rows lie one after another -(`bytes_per_row` is its texels' bytes, or it has one row; an array's slices likewise) and the -image holds no byte past its texels. A texture whose rows lie with bytes between them, as a guest -browser's padded surfaces' do, is one only where it only reads (no `RenderTarget`, `ShaderWrite`, -`ShaderAtomic` or block-write usage; `Unknown` usage counts as all of them), under the default -`padded_reads = PaddedReadsPolicy::Alias`; otherwise it is a shadow (`shadowed-texture`) on every -device but MoltenVK, whose image is a Metal texture over the buffer. An image at that pitch holds -the bytes between the rows in its subresource (`VkSubresourceLayout`: "size includes any extra -memory that is required based on rowPitch"), and Vulkan lets two kinds of operation write them, -where Metal leaves them as the program writes them. The image's layout transitions "may perform -read and write accesses on all memory bound to the image subresource range", and every image takes -one, its first move from the layout it is made in, before any use; the runtime's images take no -other. A render pass's load and store operations "read and write back any memory locations within -the image subresource bound for that attachment" (lavapipe writes back the bytes its 4-texel blocks -reach past a row, a signaling NaN's bits quieted). No query of the device's states otherwise. So a -texture that renders or that a shader writes is a shadow, and one that only reads keeps the bytes -between its rows across its first move (the host keeps the bytes the image is bound to through -it, so a CPU write between its rows meanwhile is undone, once per image; docs/API.md section 1, -docs/FAST-PATHS.md's known gaps); `padded_reads = PaddedReadsPolicy::Shadow`, which -`DevicePolicy::exact_answers()` selects, makes it a shadow too. To keep a surface that renders -aliased, lay its rows packed. +- An import of dma-bufs. The new import comes from the same dma-bufs, never from the source, so the + buffer keeps the pages it was made over even after `host_range_remapped`. The runtime holds a + duplicate descriptor of each released chunk, within a quarter of the process's `RLIMIT_NOFILE` + soft limit, read once at the process's first such import (an import past it stays imported, + counted by `WorkCounts::host_imports_kept_for_fds`), and changes no limit: where many no-copy + buffers stand at once, raise the soft limit toward the hard one at startup (`setrlimit`), as QEMU + does. + A blit whose released buffer the device cannot import again (out of memory) is refused. +- An import of the pointer, on a driver whose pointer imports follow their address + (`DriverFact::PointerImportsFollowTheirAddress`: ANV, Mesa 26.2.4 on the Iris Xe of Raptor -Over pages imported by their pointer, such a texture aliases them where the device lays an image's -rows at the texture's `bytes_per_row`: the driver's own linear image, or, where that lays its rows -otherwise, a `DRM_FORMAT_MOD_LINEAR` image at that pitch, which the driver may refuse (and which -the runtime makes of no depth or stencil format, as it makes no image over a dma-buf of one: Vulkan -has no query of where such a format's memory plane lies). Measured -(`runtime_lane::surface_texture_costs::pitch_classes`, nine formats, four usages, rows padded by -each power of two from 16 to 4096 bytes): +A buffer stays imported for good once its Metal address is handed out (`gpu_address`, a binding, an +argument buffer or table, an indirect command buffer, `use_resource`), its `VkBuffer` is read, a +texture is made over its bytes, or a second buffer lies in its import; so do a heap's and a +rebind's imports. `WorkCounts::host_imports_released`, `host_imports_reimported`, +`host_imports_resident` and `host_import_fds_kept` count it. For imports of either kind, +`host_imports_read_apart` counts the live ones that a read other than a blit's keeps for good (the +`host_imports_read_apart_*` gauges by reason: the Metal address, the `VkBuffer`, a binding, a +texture, a second buffer, no releasing thread), the `host_imports_kept_*` gauges the live ones kept +whatever reads them, by cause (a heap's, a rebind's, a pointer import on an unmeasured driver, no +stand-in, and `host_imports_kept_for_fds`), and `host_imports_used` the imports each committed +command buffer's commands use, summed over command buffers; against `host_imports_live` they show +how many of the listed imports a workload's commands name. Of a rebind's imports, +`host_imports_rebound_unlisted` counts the live ones no command buffer committed since the rebind +used (no command reaches them unnamed yet), `host_rebind_imports_made` those rebinds made, and +`host_rebind_imports_covered` those whose pages lay within bytes a buffer over host pages lay over +already. -- ANV (Mesa 26.2.4) packs its own rows tight and takes every pitch asked. -- NVIDIA (615.71.09) aligns its own rows to 128 bytes and takes any larger pitch for a texture it - samples or writes, in `BGRA8Unorm`, `RGBA8Unorm`, `RGB10A2Unorm`, `RGBA16Float`, `R8Unorm` and - `RG8Unorm`; not for a render target, and not in `R16Float`, `R32Float` or `RGBA32Float`, whose - `DRM_FORMAT_MOD_LINEAR` tiling it gives no sampling or transfers. -- RADV (Mesa 26.2.4) aligns its own rows to 256 bytes, refuses a pitch that is not a multiple of - 256, and asks a dedicated allocation of an image at any other, so it takes no pitch but its own. - -The own rows' alignments are as measured for `BGRA8Unorm`. Elsewhere the texture is a shadow -(`shadowed-texture`): a `BGRA8Unorm` surface with packed rows takes the driver's own linear image -on RADV where its texels' bytes are a multiple of 256, and on NVIDIA where they are a multiple of -128 (their own rows' alignments). -`WorkCounts::pitched_host_images` and `pitched_host_image_refusals` count the images at Metal's -pitch made and refused. ## 7. Check the integration