diff --git a/crates/metal2vulkan-runtime/src/buffer.rs b/crates/metal2vulkan-runtime/src/buffer.rs index 991cf6246..dbeff91cc 100644 --- a/crates/metal2vulkan-runtime/src/buffer.rs +++ b/crates/metal2vulkan-runtime/src/buffer.rs @@ -1416,8 +1416,9 @@ pub(crate) enum KeptBecause { Heap, /// A rebind's import (`rebind.rs`). Rebind, - /// An import by pointer on a device whose pointer imports its submission checks did not - /// find to follow their address (`submit_check.rs`), or off Unix. + /// An import by pointer on a device whose submission checks did not find a held pointer + /// import to cost every submission (`submit_check.rs`), or made before they answered, or off + /// Unix. Pointer, /// No stand-in buffer for a read of a released one. NoStandIn, diff --git a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs index 6826abb23..4c8e34117 100644 --- a/crates/metal2vulkan-runtime/src/buffer_descriptor.rs +++ b/crates/metal2vulkan-runtime/src/buffer_descriptor.rs @@ -569,17 +569,14 @@ 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 - /// 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 - /// follow their address (as the device's submission checks find, `submit_check.rs`: ANV on - /// i915, RADV, 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). Such a - /// remap under a live buffer breaks [`HostMemory::new`]'s contract, and under a live import of - /// the pointer `VK_EXT_external_memory_host`'s too, which this call does not mend: the pages + /// imports, and stay ordered with each other as before. A remap under a live buffer breaks + /// [`HostMemory::new`]'s contract, and under a live import of the pointer + /// `VK_EXT_external_memory_host`'s too, which leaves undefined whether the import holds a + /// reference to its pages: what such a buffer's later commands read and write is then + /// unspecified (`docs/FAST-PATHS.md`, known gaps), and this call does not mend it. The pages /// are replaced or unmapped once every buffer over them signalled that its import went (its - /// keep-alive dropped, or its deallocator ran; docs/HOWTO.md, "Unmapping host memory"). Not - /// a Metal call: Metal needs none. A `length` of 0 tells nothing. + /// keep-alive dropped, or its deallocator ran; docs/HOWTO.md, "Unmapping host memory"). 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 /// new pages: a buffer made over those bytes while it runs may lie in either pages. The bytes @@ -923,7 +920,7 @@ impl Device { // (`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`), as it may its own import of the - // pointer where the driver's pointer imports follow their address; a heap's import + // pointer where a held pointer import costs every submission; a heap's import // stays, as does an import of a read-only view. // Whether the device was asked the pointer, or imports none, whose refusal a // failed source leaves standing (the window takes it, and the memory is no @@ -1681,11 +1678,11 @@ 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 (`Device::pointer_imports_follow_their_address`): 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. + /// `again` made it (`host_residency.rs`), on a device whose held pointer imports cost every + /// submission (`Device::pointer_imports_tax_submissions`): a new `VkBuffer` made and bound as + /// the first was, over an import of the pages mapped at the pointer, the kept import's under + /// `HostMemory::new`'s contract. 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, diff --git a/crates/metal2vulkan-runtime/src/host_memory.rs b/crates/metal2vulkan-runtime/src/host_memory.rs index 5e5a2ff62..c9cc72236 100644 --- a/crates/metal2vulkan-runtime/src/host_memory.rs +++ b/crates/metal2vulkan-runtime/src/host_memory.rs @@ -60,13 +60,11 @@ //! refuses the pointer; a rebind to such memory is refused, as is a guest RAM with no source //! (`Device::use_host_ram`), naming the extension ([`Importer::pointer_import`]). //! - **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, but on a driver whose pointer imports follow their address (as the -//! device's submission checks find, `submit_check.rs`: ANV on i915, RADV, lavapipe), the import -//! of the pointer reads the pages mapped there at each submission (a remap under a live buffer, -//! which [`HostMemory::new`] forbids, reaches it there; `docs/FAST-PATHS.md`, known gaps). 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 +//! them then: the GPU uses the pages mapped at the pointer when the buffer was made, which +//! [`HostMemory::new`]'s contract keeps there while the buffer lives. What a buffer reads after +//! a remap under it, which that contract forbids, is unspecified (`docs/FAST-PATHS.md`, known +//! gaps). 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 //! `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 diff --git a/crates/metal2vulkan-runtime/src/host_residency.rs b/crates/metal2vulkan-runtime/src/host_residency.rs index 499d99109..50ba12de4 100644 --- a/crates/metal2vulkan-runtime/src/host_residency.rs +++ b/crates/metal2vulkan-runtime/src/host_residency.rs @@ -21,14 +21,14 @@ //! 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 device whose check found its pointer imports follow their -//! address (`submit_check.rs`, `Device::pointer_imports_follow_their_address`; ANV on i915, -//! RADV and lavapipe answered so): there the kept import reads, at each submission, the pages -//! mapped at its pointer then, as an import again at the same pointer does, so releasing it -//! changes nothing a command reads. Elsewhere, and in a buffer made before the check -//! answered, 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; +//! - of its pages' pointer, on a device whose check found a held pointer import adds to every +//! submission's cost (`submit_check.rs`, the import tax: RADV and ANV on i915 pay one, NVIDIA's +//! driver and MoltenVK none measured): the caller's pages stay mapped at the pointer, with the +//! same backing, while the buffer lives (`HostMemory::new`), so an import again at the same +//! pointer reads the pages the kept import read, on every driver, and releasing it changes +//! nothing a command reads. Elsewhere, and in a buffer made before the check answered, a +//! pointer import stays imported: a release would spare no submission any cost, and the +//! import again would cost the next blit; //! - of a run of a guest RAM alone (`host_ram.rs`), which a buffer over one run inside a chunk //! not imported yet was bound in while the device's thread imports the chunk: made again in //! the chunk's import where that is made by then (and lays the bytes as the run's did), else @@ -70,12 +70,14 @@ //! 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. A guest RAM run's in its chunk's import, or the run's alone. 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. +//! imported. A pointer import at its pointer, over the pages the kept import read, which +//! `HostMemory::new`'s contract keeps mapped there while the buffer lives. A guest RAM run's in +//! its chunk's import, or the run's alone. 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 @@ -172,8 +174,8 @@ pub(super) enum AgainFrom { source: DmaBufSource, request: DmaBufRequest, }, - /// The pointer its pages were imported at, on a driver whose pointer imports follow their - /// address. + /// The pointer its pages were imported at, on a device whose held pointer imports cost every + /// submission. Pointer(ImportedAt), /// The run of a guest RAM it was an import of alone, made while the run's chunk was not /// imported (`host_ram.rs`): bound again in the chunk's import where it is made by then, @@ -222,17 +224,17 @@ impl Again { }) } - /// The pages imported at `pointer`, made again there: `None` where the device's pointer - /// imports may keep the pages they were made over (its check found they do, could not run, - /// or has not answered: `Device::pointer_imports_follow_their_address`), so that the import - /// stays imported. + /// The pages imported at `pointer`, made again there: `None` where a held pointer import + /// costs the device's submissions nothing, so that a release would buy nothing (its check + /// found so, could not run, or has not answered: `Device::pointer_imports_tax_submissions`), + /// and the import stays imported. pub(super) fn pointer( device: &Device, pointer: NonNull, (length, window, class): (u64, ImportWindow, MemoryClass), ) -> Option { - let follows = device.pointer_imports_follow_their_address_now(); - follows.then(|| Again { + let taxed = device.pointer_imports_tax_submissions(); + taxed.then(|| Again { device: device.clone(), from: AgainFrom::Pointer(ImportedAt(pointer)), length, diff --git a/crates/metal2vulkan-runtime/src/submit_check.rs b/crates/metal2vulkan-runtime/src/submit_check.rs index 6d67e585d..01504bc21 100644 --- a/crates/metal2vulkan-runtime/src/submit_check.rs +++ b/crates/metal2vulkan-runtime/src/submit_check.rs @@ -1,9 +1,8 @@ //! The device's checks of its submissions, on a thread of its own, once per driver, release, //! kernel and runtime: whether `VkSubmitInfo`s that signal nothing merge into one submission of -//! the driver's ([`Check::Merge`]), whether a host-pointer import the device holds adds to the cost -//! of every submission ([`Check::ImportTax`]), and whether a pointer import reads the pages mapped -//! at its pointer at each submission ([`Check::Follows`]). Each answers a question the runtime -//! once read from the driver's identity, its `driverID`, vendor and `deviceID`, so that a GPU no +//! the driver's ([`Check::Merge`]), and whether a host-pointer import the device holds adds to the +//! cost of every submission ([`Check::ImportTax`]). Each answers a question the runtime once read +//! from the driver's identity, its `driverID`, vendor and `deviceID`, so that a GPU no //! row named took every slow route: the check measures the device itself, and nothing of a //! decision reads its identity. //! @@ -38,27 +37,18 @@ //! with 256 of 1 MiB, 8.3 with none), below the floor for one import and past it for //! [`TAX_IMPORTS`]. Where it does, the runtime keeps its own long buffers out of //! fresh pages (`fresh_pages.rs`): each would add that cost, and more for its length, to every -//! submission for its whole life, where its fresh pages save one clear of its bytes. RADV lists -//! every memory it imported in each kernel submission, and amdgpu gets every page of a pointer -//! import again in each (`amdgpu_cs_parser_bos`): the probe measured 10.3 us more a submission +//! submission for its whole life, where its fresh pages save one clear of its bytes. And it +//! releases a no-copy buffer's idle pointer import and imports it again at its next blit +//! (`host_residency.rs`): under `HostMemory::new`'s contract the pages at the pointer stay the +//! same while the buffer lives, so the new import reads what the kept one would on any driver, +//! and every submission meanwhile is spared the import's cost. Where a held import costs +//! nothing (NVIDIA's on the RTX 5080 Laptop GPU, below), a release would save nothing and cost +//! the import again, so every pointer import stays imported. RADV lists every memory it +//! imported in each kernel submission, and amdgpu gets every page of a pointer import again in +//! each (`amdgpu_cs_parser_bos`): the probe measured 10.3 us more a submission //! for one import of 16 MiB on the Radeon 780M (24.1 for 64 MiB), 6.8 on the RX 7900 XTX //! (35.7), 45.8 on the RX 550 (191.3), against 0.2 on the Iris Xe for one import (its cost is //! per import, above) and none on the M3 Max. -//! - **Follows** (Linux alone). Two pages the check maps, the first written with a pattern, are -//! imported by their pointer and bound to a buffer; a copy of the first page into the second is -//! submitted, then new anonymous pages are mapped over the first (`mmap` with `MAP_FIXED`) and -//! written with another pattern, and the same copy submitted again; and a second pair, its first -//! page replaced before any submission, copied once. Where every copy read the pages mapped at -//! the first page's address as it was submitted, the driver's pointer imports follow their -//! address (`Holds`), and an idle no-copy buffer's import may be released and made again at its -//! pointer at its next use (`host_residency.rs`), which reads the pages the kept import would. -//! Where a copy read the pages the import was made over, the driver keeps them (`Fails`), as -//! NVIDIA's pins them, and as Metal wires a no-copy buffer's pages when it is made: such an -//! import stays live. Not run on another system: on macOS every Vulkan driver imports a pointer -//! through Metal, which wires the pages as it makes the buffer, so the import keeps them, and a -//! remap of pages the kernel wired is not made. Anonymous pages replace anonymous pages, mapped -//! throughout, so no submission meets a range without pages; only the first page of each pair -//! is replaced, and the GPU writes only the second. //! - **Load beside it.** Other work on the device or the host's CPU adds to a submission's time //! and never takes from it, so each timed check reads floors, a form's least time in each half of //! its rounds or phases, and answers only where the two halves agree. Each half holds several @@ -110,7 +100,7 @@ //! - **Its cost**: [`ROUNDS`] rounds of each merge form and [`TAX_PHASES`] phases of //! [`TAX_SUBMITS`] submissions, each waited for, every command buffer empty; the //! [`TAX_IMPORTS`] imports of [`TAX_BYTES`] in all made and freed once a try, over pages -//! written once; and on Linux three copies of 256 bytes; each timed check again, at most +//! written once, none bound to a buffer or read by a command; each timed check again, at most //! [`TRIES`] times in all, where its halves disagree, and the import tax's [`TAX_REPEATS`] //! tries more where it answers `Holds` past its margin, and the merge's [`MERGE_REPEATS`] where //! its answer is clear of the load beside it. The probe's rounds took 3 to 12 ms on those @@ -127,8 +117,8 @@ //! check holds from its making, the merge's floors only reported, and its other checks answer //! for its life. //! - **Out of the device's way.** Before each step that allocates, frees, maps or unmaps pages, -//! or submits (each round, each import and its release, each submission of a phase, each copy -//! and remap), the thread steps aside for the device's allocations and frees on other threads +//! or submits (each round, each import and its release, each submission of a phase), the +//! thread steps aside for the device's allocations and frees on other threads //! (`step_aside.rs`): it goes on once none is in progress and none ended for //! `step_aside::QUIET`, at once while a call waits for its verdicts (`ANSWER_WAIT`, //! `Device::settle_submit_checks`). Beside a program's burst of makings its verdicts so come @@ -136,7 +126,7 @@ //! - **Its thread** holds nothing of the device, as the queue-switch check's does //! (`queue_switch_check.rs`): only the parts of it the checks work with ([`Parts`]), never a //! handle, so the device's last handle never goes on it. It reads the stop between its steps -//! (each round, each phase, each copy): the device's teardown stops it there and waits for the +//! (each round, each phase): the device's teardown stops it there and waits for the //! step in progress, the release of its objects and of its parts, and the checks end //! unrecorded, what had not answered `Unchecked`. So does the device's loss, at the call that //! answers it (`VK_ERROR_DEVICE_LOST`, from a submission or a wait): nothing is submitted again, @@ -147,8 +137,8 @@ //! with the relay's mark after each of its uses of the queue where the device relays its queues' //! failures (`device/relay.rs`, `By::Checks`); the commands it records go through the driver's //! own entry points, counted among none of the device's (`WorkCounts::commands_recorded`, -//! `recorder::unrouted`); its allocations, buffers, bindings and releases are counted as the -//! checks' (`WorkCounts::device_checks`), not among the process's (`object_churn`). Its +//! `recorder::unrouted`); its allocations and releases are counted as the checks' +//! (`WorkCounts::device_checks`), not among the process's (`object_churn`). Its //! submission calls hold the device's loader word (`loader_word.rs`). use crate::allocations::Allocations; @@ -165,7 +155,6 @@ use crate::loader_word::{DeviceWord, Held}; use crate::recorder::{self, Command}; use crate::release; use crate::shader_cache::store::{hex, Lookup, Store}; -use crate::sharing::Sharing; use crate::work_counts::Counters; use ash::vk; use sha2::{Digest, Sha256}; @@ -253,10 +242,6 @@ const WAIT_SLICE: Duration = Duration::from_millis(100); /// with a source of dma-bufs, `host_ram.rs`): their run takes milliseconds. pub(crate) const ANSWER_WAIT: Duration = Duration::from_secs(10); -/// The bytes the follows check copies. -#[cfg(target_os = "linux")] -const COPIED: u64 = 256; - /// A check, in the order they run and the record holds their verdicts. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) enum Check { @@ -264,13 +249,14 @@ pub(crate) enum Check { Merge, /// A held host-pointer import adds to every submission's cost. ImportTax, - /// A pointer import reads the pages mapped at its pointer at each submission. - Follows, } impl Check { + /// How many checks there are. + pub(crate) const COUNT: usize = 2; + /// Every check, in order. - pub(crate) const ALL: [Check; 3] = [Check::Merge, Check::ImportTax, Check::Follows]; + pub(crate) const ALL: [Check; Check::COUNT] = [Check::Merge, Check::ImportTax]; fn index(self) -> usize { self as usize @@ -323,7 +309,7 @@ pub(crate) struct Measured { /// A device's verdicts of its submission checks, and their state (the module docs). pub(crate) struct SubmitChecks { - verdicts: [AtomicU8; 3], + verdicts: [AtomicU8; Check::COUNT], measured: [AtomicI64; 4], started: AtomicBool, settled: Mutex, @@ -621,8 +607,8 @@ fn floor(times: &[i64]) -> i64 { /// The version of what the checks measure, of what earns a record and of how it is named and /// framed: a change to any bumps it, and a record of another version is never read (one of 3 may /// hold an import tax `Holds` short of [`TAX_MARGIN`], one of 5 a merge verdict of one loaded -/// try). -pub(crate) const CHECK_VERSION: u32 = 6; +/// try, one of 6 three verdicts). +pub(crate) const CHECK_VERSION: u32 = 7; /// A record's first bytes. const MAGIC: [u8; 8] = *b"M2VSUBC\0"; @@ -631,7 +617,7 @@ const MAGIC: [u8; 8] = *b"M2VSUBC\0"; const NAME_TAG: &[u8] = b"metal2vulkan submission checks record\0"; /// A record's length: magic, version, runtime, identity, verdicts, measured, checksum. -const RECORD_BYTES: usize = 8 + 4 + 4 + 32 + 3 + 4 * 8 + 32; +const RECORD_BYTES: usize = 8 + 4 + 4 + 32 + Check::COUNT + 4 * 8 + 32; /// The kernel's release (`uname -r`), which the import tax's cost is the work of on RADV: empty /// where the system answers none. @@ -672,7 +658,7 @@ pub(crate) fn record_name(identity: &DriverIdentity) -> String { /// version u32 CHECK_VERSION /// runtime u32 RUNTIME_VERSION /// identity 32 bytes the identity's and the kernel's digest for these checks -/// verdicts 3 bytes one per check, in Check::ALL's order: Holds 1, Fails 2, Unchecked 3 +/// verdicts 2 bytes one per check, in Check::ALL's order: Holds 1, Fails 2, Unchecked 3 /// measured 4 x i64 merged, apart, held, bare, in nanoseconds /// checksum 32 bytes SHA-256 of every byte before it /// ``` @@ -680,7 +666,7 @@ pub(crate) fn record_name(identity: &DriverIdentity) -> String { /// Integers are little-endian. pub(crate) fn encode( identity: &DriverIdentity, - verdicts: [Verdict; 3], + verdicts: [Verdict; Check::COUNT], measured: Measured, ) -> Vec { let mut bytes = Vec::with_capacity(RECORD_BYTES); @@ -705,7 +691,10 @@ pub(crate) fn encode( /// The verdicts and measurements `bytes` record for `identity`: `None` for anything but a whole /// record of this version and runtime, for this identity and kernel, whose checksum holds and /// whose every verdict is an answer. -pub(crate) fn decode(identity: &DriverIdentity, bytes: &[u8]) -> Option<([Verdict; 3], Measured)> { +pub(crate) fn decode( + identity: &DriverIdentity, + bytes: &[u8], +) -> Option<([Verdict; Check::COUNT], Measured)> { if bytes.len() != RECORD_BYTES { return None; } @@ -718,7 +707,7 @@ pub(crate) fn decode(identity: &DriverIdentity, bytes: &[u8]) -> Option<([Verdic let (version, rest) = rest.split_at(4); let (runtime, rest) = rest.split_at(4); let (identity_digest, rest) = rest.split_at(32); - let (verdicts, rest) = rest.split_at(3); + let (verdicts, rest) = rest.split_at(Check::COUNT); let word = |bytes: &[u8]| u32::from_le_bytes(bytes.try_into().unwrap_or([0xff; 4])); if magic != MAGIC || word(version) != CHECK_VERSION @@ -727,7 +716,7 @@ pub(crate) fn decode(identity: &DriverIdentity, bytes: &[u8]) -> Option<([Verdic { return None; } - let verdicts = [0, 1, 2].map(|i| Verdict::of_byte(verdicts[i])); + let verdicts: [Verdict; Check::COUNT] = std::array::from_fn(|i| Verdict::of_byte(verdicts[i])); if verdicts.contains(&Verdict::Pending) { return None; } @@ -834,27 +823,20 @@ impl Device { /// Whether a host-pointer import the device holds adds to the cost of every submission, as /// its check found (`submit_check.rs`): where it does, a guest RAM with a source of dma-bufs - /// imports its chunks as dma-bufs first (`host_ram.rs`). `false` until it answers. + /// imports its chunks as dma-bufs first (`host_ram.rs`), and a no-copy buffer's idle pointer + /// import is released and imported again at its next blit (`host_residency.rs`). `false` until + /// it answers. pub(crate) fn pointer_imports_tax_submissions(&self) -> bool { self.shared().submit_checks.holds(Check::ImportTax) } - /// No Metal counterpart: whether the device's imports of host memory by its pointer read the - /// pages mapped at the pointer at each submission, as its check found: `true` where they do, - /// and an idle no-copy buffer's import is released and made again at its next use; `false` - /// where they keep the pages they were made over (as Metal's no-copy buffer does), where the - /// check could not run or did not run (macOS), and until it answers - /// ([`settle_submit_checks`](Device::settle_submit_checks) waits for it). A runtime extension: - /// where it is `true`, pages mapped over a live no-copy buffer's addresses are what its later - /// command buffers read and write. - pub fn pointer_imports_follow_their_address(&self) -> bool { - self.current().pointer_imports_follow_their_address_now() - } - - /// [`Device::pointer_imports_follow_their_address`] on the generation that serves - /// (`device/line.rs`). - pub(crate) fn pointer_imports_follow_their_address_now(&self) -> bool { - self.shared().submit_checks.holds(Check::Follows) + /// Whether the device releases a no-copy buffer's idle import of its pointer and imports it + /// again at its next blit (`host_residency.rs`): its check found a held import adds to every + /// submission's cost (`submit_check.rs`); `false` until it answers, and for a buffer made + /// before then. A runtime extension for the lanes that hold a device to the path it chooses. + #[doc(hidden)] + pub fn releases_idle_pointer_imports(&self) -> bool { + self.current().pointer_imports_tax_submissions() } /// Wait until the device's submission checks answered, or `timeout` passed: whether they did. @@ -913,7 +895,6 @@ impl Device { format!( "merge {:?}{assumed} ({:.1} us in one call of {MERGED} against {:.1} us apart), import tax \ {:?} ({:.1} us a submission with {} imports of {} MiB in all held against {:.1} us), \ - follows {:?}, \ {took}{split}{merge_unearned}{unearned}{short}{tax_tries} (floors)", checks.verdict(Check::Merge), us(m.merged), @@ -923,7 +904,6 @@ impl Device { TAX_IMPORTS, TAX_BYTES >> 20, us(m.bare), - checks.verdict(Check::Follows), ) } } @@ -946,8 +926,6 @@ struct Parts { store: Arc, /// The device's import of host pointers, where it imports them. pointers: Option, - /// The queue families its buffers are shared among. - families: Vec, /// Its memory types' properties, by index. type_flags: Vec, identity: DriverIdentity, @@ -956,16 +934,12 @@ struct Parts { } /// The commands the checks record their own command buffers with, as the device's driver gave -/// them (`recorder::unrouted`): counted among none of the device's (`WorkCounts::commands_recorded`, -/// `copy_sites`), as their submissions are among none of its submissions. +/// them (`recorder::unrouted`): counted among none of the device's +/// (`WorkCounts::commands_recorded`), as their submissions are among none of its submissions. #[derive(Clone, Copy)] struct Recording { begin: vk::PFN_vkBeginCommandBuffer, end: vk::PFN_vkEndCommandBuffer, - #[cfg(target_os = "linux")] - copy: vk::PFN_vkCmdCopyBuffer, - #[cfg(target_os = "linux")] - barrier: vk::PFN_vkCmdPipelineBarrier, } impl Recording { @@ -986,14 +960,6 @@ impl Recording { Command::EndCommandBuffer, commands.end_command_buffer, ), - #[cfg(target_os = "linux")] - copy: recorder::unrouted(slot, Command::CmdCopyBuffer, commands.cmd_copy_buffer), - #[cfg(target_os = "linux")] - barrier: recorder::unrouted( - slot, - Command::CmdPipelineBarrier, - commands.cmd_pipeline_barrier, - ), } } } @@ -1022,7 +988,6 @@ impl Parts { pointers: (shared.host_import.as_ref().ok()) .and_then(Importer::pointers) .cloned(), - families: shared.queue_families.clone(), type_flags, identity: device.driver_identity(), recording: Recording::of(shared), @@ -1136,7 +1101,6 @@ fn measure(parts: &Parts, objects: &Objects) -> Option<(Measured, bool)> { tax(parts, objects) })?; checks.set(Check::ImportTax, taxed); - checks.set(Check::Follows, follows(parts, objects)?); let measured = Measured { merged, apart, @@ -1291,7 +1255,7 @@ fn tax(parts: &Parts, objects: &Objects) -> Option> { if tax_holds(phase) && imports.is_empty() { for pages in &pieces { parts.step(); - match Import::make(parts, pages, false) { + match Import::make(parts, pages) { Some(Some(import)) => imports.push(import), made => return release_all(parts, imports.drain(..)).and(made.map(|_| None)), } @@ -1334,113 +1298,6 @@ fn release_all<'p>(parts: &Parts, imports: impl IntoIterator>) Some(()) } -/// The follows check's verdict (the module docs); `None` where the check stops. -#[cfg(target_os = "linux")] -fn follows(parts: &Parts, objects: &Objects) -> Option { - let Some(page) = crate::host_memory::host_page() else { - return Some(Verdict::Unchecked); - }; - // The kept import, its first page replaced between two submissions. - let Some(kept) = follows_pair(parts, objects, page, false)? else { - return Some(Verdict::Unchecked); - }; - if !parts.goes_on() { - return None; - } - // An import whose first page is replaced before its first submission. - let Some(fresh) = follows_pair(parts, objects, page, true)? else { - return Some(Verdict::Unchecked); - }; - Some(match (kept, fresh) { - (Read::New, Read::New) => Verdict::Holds, - (Read::Old, Read::Old) => Verdict::Fails, - _ => Verdict::Unchecked, - }) -} - -/// Not run off Linux (the module docs). -#[cfg(not(target_os = "linux"))] -fn follows(_parts: &Parts, _objects: &Objects) -> Option { - Some(Verdict::Unchecked) -} - -/// What a copy of the replaced page read. -#[cfg(target_os = "linux")] -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Read { - /// The pages the import was made over. - Old, - /// The pages mapped over them. - New, - /// Neither. - Other, -} - -/// Patterns the follows check writes: the pages an import was made over, and those mapped over -/// them. -#[cfg(target_os = "linux")] -const OLD: u8 = 0xa1; -#[cfg(target_os = "linux")] -const NEW: u8 = 0xb2; - -/// One pair of pages imported and copied (the module docs): what the copy after the remap read -/// (`before_first` replaces the first page before any submission). `Some(None)` where the device -/// takes no such import or a copy failed; `None` where the check stops. -#[cfg(target_os = "linux")] -fn follows_pair( - parts: &Parts, - objects: &Objects, - page: u64, - before_first: bool, -) -> Option> { - parts.step(); - let Some(pages) = Pages::map(2 * page) else { - return Some(None); - }; - pages.fill(OLD); - parts.step(); - let Some(import) = Import::make(parts, &pages, true)? else { - return Some(None); - }; - let read = |pages: &Pages| { - // SAFETY: the second page is the check's, mapped, and no copy into it is pending. - let bytes = unsafe { - std::slice::from_raw_parts(pages.start.as_ptr().add(page as usize), COPIED as usize) - }; - match bytes { - _ if bytes.iter().all(|&b| b == OLD) => Read::Old, - _ if bytes.iter().all(|&b| b == NEW) => Read::New, - _ => Read::Other, - } - }; - let answer = (|| { - if !before_first { - pages.clear_second(page); - parts.step(); - if !objects.copy(parts, &import, page)? { - return Some(None); - } - if read(&pages) != Read::Old { - return Some(None); - } - } - parts.step(); - if !pages.replace_first(page) { - return Some(None); - } - pages.clear_second(page); - parts.step(); - if !objects.copy(parts, &import, page)? { - return Some(None); - } - Some(Some(read(&pages))) - })(); - // The import's free, then the pages' unmapping as they go. - parts.step(); - import.release(parts)?; - answer -} - /// Anonymous private pages the check maps, read-write, unmapped as this goes where every import /// of them was freed (an import left unreleased, as the process exits, keeps them mapped to the /// end). @@ -1488,39 +1345,6 @@ impl Pages { // SAFETY: the pages are the check's, mapped read-write, and nothing reads them meanwhile. unsafe { std::ptr::write_bytes(self.start.as_ptr(), byte, self.length as usize) }; } - - /// Zero the second page's bytes the copy writes. - #[cfg(target_os = "linux")] - fn clear_second(&self, page: u64) { - // SAFETY: as `fill`; no copy into the page is pending. - unsafe { - std::ptr::write_bytes(self.start.as_ptr().add(page as usize), 0, COPIED as usize) - }; - } - - /// Map new anonymous pages over the first page (`MAP_FIXED`), written with [`NEW`]: whether - /// the system did. - #[cfg(target_os = "linux")] - fn replace_first(&self, page: u64) -> bool { - // SAFETY: the first page is the check's own mapping, replaced in one call, so the range - // is mapped throughout; no copy of it is pending. - let pointer = unsafe { - libc::mmap( - self.start.as_ptr().cast(), - page as usize, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_ANON | libc::MAP_PRIVATE | libc::MAP_FIXED, - -1, - 0, - ) - }; - if pointer != self.start.as_ptr().cast() { - return false; - } - // SAFETY: the new page is mapped read-write, the check's. - unsafe { std::ptr::write_bytes(self.start.as_ptr(), NEW, page as usize) }; - true - } } impl Drop for Pages { @@ -1536,19 +1360,18 @@ impl Drop for Pages { } } -/// An import of a [`Pages`]' bytes by their pointer, in its own `VkDeviceMemory`, and, for the -/// follows check, a buffer bound to it. +/// An import of a [`Pages`]' bytes by their pointer, in its own `VkDeviceMemory`, bound to +/// nothing. struct Import<'p> { memory: vk::DeviceMemory, - buffer: vk::Buffer, pages: &'p Pages, } impl<'p> Import<'p> { - /// The import of `pages`, with a buffer bound where `bound`, in a host-coherent type the - /// pointer takes. `Some(None)` where the device imports no host pointer, the pages take no - /// such type, or a call was refused; `None` where the process is exiting. - fn make(parts: &Parts, pages: &'p Pages, bound: bool) -> Option>> { + /// The import of `pages`, in a host-coherent type the pointer takes. `Some(None)` where the + /// device imports no host pointer, the pages take no such type, or a call was refused; `None` + /// where the process is exiting. + fn make(parts: &Parts, pages: &'p Pages) -> Option>> { let Some(pointers) = &parts.pointers else { return Some(None); }; @@ -1565,41 +1388,12 @@ impl<'p> Import<'p> { { return Some(None); } - let mut buffer = vk::Buffer::null(); - let mut allowed = types; - if bound { - let mut external = vk::ExternalMemoryBufferCreateInfo::default() - .handle_types(vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT); - let info = Sharing::new(&parts.families).buffer( - vk::BufferCreateInfo::default() - .size(pages.length) - .usage(vk::BufferUsageFlags::TRANSFER_SRC | vk::BufferUsageFlags::TRANSFER_DST) - .push_next(&mut external), - ); - // SAFETY: the device is live and `info` and its chain valid, inside a section. - buffer = match unsafe { crate::creation::buffer(raw, &info) } { - Ok(buffer) => buffer, - Err(_) => return Some(None), - }; - exit_guard::called(Call::CreateBuffer); - // SAFETY: `buffer` is a live buffer of this device. - let requirements = unsafe { raw.get_buffer_memory_requirements(buffer) }; - exit_guard::called(Call::GetBufferMemoryRequirements); - allowed &= requirements.memory_type_bits; - } let coherent = vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT; let type_index = (parts.type_flags.iter().zip(0u32..)) - .find(|&(flags, index)| allowed & (1 << index) != 0 && flags.contains(coherent)) + .find(|&(flags, index)| types & (1 << index) != 0 && flags.contains(coherent)) .map(|(_, index)| index); - let discard = |buffer: vk::Buffer| { - if buffer != vk::Buffer::null() { - // SAFETY: the buffer is unused. - unsafe { release::object(raw, buffer) }; - } - }; let Some(type_index) = type_index else { - discard(buffer); return Some(None); }; let mut import = vk::ImportMemoryHostPointerInfoEXT::default() @@ -1616,29 +1410,12 @@ impl<'p> Import<'p> { Ok(memory) => memory, Err(_) => { exit_guard::called(Call::AllocateMemory); - discard(buffer); return Some(None); } }; exit_guard::called(Call::AllocateMemory); - if bound { - // SAFETY: the memory is the pages', of a type the buffer takes and its whole length; - // the buffer is unbound. - if unsafe { crate::creation::bind_buffer(raw, buffer, memory, 0) }.is_err() { - exit_guard::called(Call::BindBufferMemory); - discard(buffer); - // SAFETY: the memory is unused. - unsafe { release::object(raw, memory) }; - return Some(None); - } - exit_guard::called(Call::BindBufferMemory); - } pages.imports.set(pages.imports.get() + 1); - Some(Some(Import { - memory, - buffer, - pages, - })) + Some(Some(Import { memory, pages })) } /// Free it, inside a section: `None` where the process is exiting, the import then left to @@ -1647,24 +1424,19 @@ impl<'p> Import<'p> { let _held = parts.step_held(); let _busy = exit_guard::enter()?; let raw = parts.vk(); - // SAFETY: no submission that names them is pending (each was waited for). - unsafe { - if self.buffer != vk::Buffer::null() { - release::object(raw, self.buffer); - } - release::object(raw, self.memory); - } + // SAFETY: no submission names it (none binds it). + unsafe { release::object(raw, self.memory) }; self.pages.imports.set(self.pages.imports.get() - 1); Some(()) } } -/// The checks' command pool, of the first `VkQueue`'s family, and its command buffers -/// ([`MERGED`] empty ones and, on Linux, one for the follows check's copy), made as the checks -/// start, as the device is made, before the program holds it: their `vkAllocateCommandBuffers` -/// is the one call of the checks' that the loader serves, which reads the device's loader word -/// (`loader_word.rs`), so none of theirs reads it beside the program's work, whose messages -/// MoltenVK writes it with. The checks' thread records them ([`Objects::make`]). +/// The checks' command pool, of the first `VkQueue`'s family, and its [`MERGED`] empty command +/// buffers, made as the checks start, as the device is made, before the program holds it: their +/// `vkAllocateCommandBuffers` is the one call of the checks' that the loader serves, which reads +/// the device's loader word (`loader_word.rs`), so none of theirs reads it beside the program's +/// work, whose messages MoltenVK writes it with. The checks' thread records them, once +/// ([`Objects::make`]). struct Made { pool: vk::CommandPool, buffers: Vec, @@ -1676,16 +1448,14 @@ impl Made { fn make(device: &Device) -> Option { let shared = device.shared(); let raw = shared.vk(); - let info = vk::CommandPoolCreateInfo::default() - .flags(vk::CommandPoolCreateFlags::RESET_COMMAND_BUFFER) - .queue_family_index(shared.queues[0].family); + let info = vk::CommandPoolCreateInfo::default().queue_family_index(shared.queues[0].family); // SAFETY: the device is live. let pool = unsafe { raw.create_command_pool(&info, None) }.ok()?; exit_guard::called(Call::CreateCommandPool); let allocate = vk::CommandBufferAllocateInfo::default() .command_pool(pool) .level(vk::CommandBufferLevel::PRIMARY) - .command_buffer_count(MERGED as u32 + u32::from(cfg!(target_os = "linux"))); + .command_buffer_count(MERGED as u32); // The loader serves it; the device's loader word is put back first. match device.allocate_command_buffers(&allocate) { Ok(buffers) => Some(Made { pool, buffers }), @@ -1703,8 +1473,6 @@ impl Made { struct Objects { pool: vk::CommandPool, empty: Vec, - #[cfg(target_os = "linux")] - copy: vk::CommandBuffer, fence: vk::Fence, } @@ -1717,8 +1485,6 @@ impl Objects { let mut objects = Objects { pool: made.pool, empty: made.buffers, - #[cfg(target_os = "linux")] - copy: vk::CommandBuffer::null(), fence: vk::Fence::null(), }; if objects.fill(parts).is_none() { @@ -1732,10 +1498,6 @@ impl Objects { /// Record the command buffers and make the fence, inside the caller's section. fn fill(&mut self, parts: &Parts) -> Option<()> { let raw = parts.vk(); - #[cfg(target_os = "linux")] - { - self.copy = self.empty.pop()?; - } let begin = vk::CommandBufferBeginInfo::default(); let recording = parts.recording; for &buffer in &self.empty { @@ -1854,52 +1616,6 @@ impl Objects { self.submit(parts, &self.empty[..1], true) } - /// Record and submit a copy of [`COPIED`] bytes from the start of `import`'s buffer to - /// `page` bytes in, then a barrier to the host's reads, and wait for it: whether it ran. - /// `None` where the process is exiting or the device was lost. - #[cfg(target_os = "linux")] - fn copy(&self, parts: &Parts, import: &Import, page: u64) -> Option { - { - let _busy = exit_guard::enter()?; - let region = vk::BufferCopy::default().dst_offset(page).size(COPIED); - let barrier = vk::MemoryBarrier::default() - .src_access_mask(vk::AccessFlags::TRANSFER_WRITE) - .dst_access_mask(vk::AccessFlags::HOST_READ); - let begin = vk::CommandBufferBeginInfo::default() - .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); - let recording = parts.recording; - // SAFETY: the copy command buffer is the check's, in no pending submission (each is - // waited for), its pool made to reset its buffers; the buffer is live, and its two - // ranges do not overlap; each array lives for its call. - unsafe { - if (recording.begin)(self.copy, &begin) != vk::Result::SUCCESS { - return Some(false); - } - exit_guard::called(Call::BeginCommandBuffer); - (recording.copy)(self.copy, import.buffer, import.buffer, 1, ®ion); - exit_guard::called(Call::CmdCopyBuffer); - (recording.barrier)( - self.copy, - vk::PipelineStageFlags::TRANSFER, - vk::PipelineStageFlags::HOST, - vk::DependencyFlags::empty(), - 1, - &barrier, - 0, - std::ptr::null(), - 0, - std::ptr::null(), - ); - exit_guard::called(Call::CmdPipelineBarrier); - if (recording.end)(self.copy) != vk::Result::SUCCESS { - return Some(false); - } - exit_guard::called(Call::EndCommandBuffer); - } - } - Some(self.submit(parts, &[self.copy], true)?.is_some()) - } - /// Wait for the fence, a slice at a time, each a section, then reset it: whether it was /// signalled. `None` where the process is exiting or the device was lost. fn wait(&self, parts: &Parts) -> Option { diff --git a/crates/metal2vulkan-runtime/src/tests/host_residency.rs b/crates/metal2vulkan-runtime/src/tests/host_residency.rs index 169742789..24e8dbcab 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_residency.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_residency.rs @@ -221,8 +221,8 @@ pub(super) fn device_with(cache: &Path, messages: Option) -> Device ..DeviceOptions::default() }; let device = Device::system_default_with(&options).unwrap(); - // A no-copy buffer's pointer import is releasable only where the device's check found its - // pointer imports follow their address as the buffer was made (`submit_check.rs`). + // A no-copy buffer's pointer import is releasable only where the device's check found a held + // pointer import costs every submission as the buffer was made (`submit_check.rs`). assert!( device.settle_submit_checks(crate::tests::SETTLE), "the submission checks never answered" @@ -519,8 +519,8 @@ pub(super) 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 unless the -/// driver's pointer imports follow their address (`tests/pointer_residency.rs`). +/// Where the device imports the pointer, the hook releases nothing and the counts stay 0 unless a +/// held pointer import costs the device's every submission (`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"; @@ -535,7 +535,7 @@ 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 { - if !super::pointer_residency::follows(device) { + if !device.releases_idle_pointer_imports() { assert_eq!(device.release_idle_host_imports(), 0, "{TEST}"); assert_eq!(residency(&device.work_counts()), (0, 0, 0, 0), "{TEST}"); } diff --git a/crates/metal2vulkan-runtime/src/tests/in_place_check.rs b/crates/metal2vulkan-runtime/src/tests/in_place_check.rs index 5842bd10d..9e724309c 100644 --- a/crates/metal2vulkan-runtime/src/tests/in_place_check.rs +++ b/crates/metal2vulkan-runtime/src/tests/in_place_check.rs @@ -41,18 +41,18 @@ const PINNED: u64 = 16 << 10; /// The submission checks' answers each device the placement test compares recalls /// ([`answering`]), in `Check::ALL`'s order: a held import adds nothing to a submission, so the -/// device's long buffers take fresh pages where it makes them; the merge and the follows check -/// answer as a driver without either property does. -const ANSWERS: [Verdict; 3] = [Verdict::Fails, Verdict::Fails, Verdict::Fails]; +/// device's long buffers take fresh pages where it makes them; the merge answers as a driver that +/// does not merge does. +const ANSWERS: [Verdict; Check::COUNT] = [Verdict::Fails, Verdict::Fails]; /// [`ANSWERS`] but that a held import adds to every submission's cost, as on RADV: the device's /// long buffers take no fresh pages (`fresh_pages.rs`). -const TAXED: [Verdict; 3] = [Verdict::Fails, Verdict::Holds, Verdict::Fails]; +const TAXED: [Verdict; Check::COUNT] = [Verdict::Fails, Verdict::Holds]; /// A record of submission-check answers for the driver of the device the cfg selects, and its /// path under a shader cache's directory. struct AnswersRecord { - answers: [Verdict; 3], + answers: [Verdict; Check::COUNT], bytes: Vec, under: PathBuf, } @@ -60,7 +60,7 @@ struct AnswersRecord { impl AnswersRecord { /// The record of `answers`, its identity and path read from a device made over a cache of its /// own and dropped before any device that recalls the record is made. - fn new(answers: [Verdict; 3]) -> AnswersRecord { + fn new(answers: [Verdict; Check::COUNT]) -> AnswersRecord { let scratch = Scratch::new("in-place-check-identity"); let probe = device(&scratch.0); let identity = probe.driver_identity(); diff --git a/crates/metal2vulkan-runtime/src/tests/pointer_residency.rs b/crates/metal2vulkan-runtime/src/tests/pointer_residency.rs index 1dd509032..1baa03e9c 100644 --- a/crates/metal2vulkan-runtime/src/tests/pointer_residency.rs +++ b/crates/metal2vulkan-runtime/src/tests/pointer_residency.rs @@ -5,11 +5,14 @@ //! mapped shared, imported by its pointer (`HostMemory::new`), as ANV, NVIDIA and lavapipe import //! it; on a device that refuses that pointer (RADV, which imports the `memfd`'s dma-bufs, //! `tests/host_residency.rs`, and makes a no-copy buffer over it with no source a copy of its -//! pages), private anonymous pages, which RADV imports by their pointer. Where -//! the device's check found its pointer imports follow their address (`submit_check.rs`, -//! `Device::pointer_imports_follow_their_address`: ANV on i915, RADV and lavapipe answer so), the -//! device releases such an import while idle and imports it again at the same pointer at its next -//! blit. +//! pages), private anonymous pages, which RADV imports by their pointer. Where the device's check +//! found a held pointer import adds to every submission's cost (`submit_check.rs`, the import tax: +//! `Device::releases_idle_pointer_imports`), the device releases such an import while idle and +//! imports it again at the same pointer at its next blit; elsewhere it keeps it +//! ([`an_idle_pointer_import_is_released_where_held_imports_cost_submissions`]). The other tests +//! hold the device to the release whatever its check found (`SubmitChecks::force`): the pages stay +//! mapped at the pointer while the buffer lives (`HostMemory::new`), so an import again reads what +//! the kept one read on every driver, and the path is the same on each. //! The tests release imports at once through the crate's hook (`Device::release_idle_host_imports`) //! and check: //! - the counts that show the release and the import again ran (`WorkCounts::host_imports_released`, @@ -21,9 +24,8 @@ //! no import of them lived; //! - that a buffer whose Metal address was handed out stays imported. //! -//! A device whose check found otherwise keeps every pointer import: the hook -//! releases none, and each test says so and passes. Where the device refuses the pointers of both -//! kinds of pages each test says so and passes without running. +//! Where the device refuses the pointers of both kinds of pages 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. No test maps pages over a live @@ -34,18 +36,20 @@ use super::host_residency::{ counting, device, gpu_fill, gpu_read, host_page, read, release, residency, Ram, Scratch, }; +use crate::submit_check::{Check, Verdict}; use crate::{Buffer, Device, Error, HostBacking, HostMemory, ResourceOptions}; use metal2vulkan::error::Feature; use std::ptr::NonNull; -/// Whether `device`'s check found its pointer imports follow their address, so that the device -/// releases them while idle: once its checks answered. -pub(super) fn follows(device: &Device) -> bool { +/// Hold `device` to releasing the idle pointer imports of the no-copy buffers made from now on, +/// whatever its check found (the module docs): once its checks answered, their import tax holds. +pub(super) fn release_pointer_imports(device: &Device) { assert!( device.settle_submit_checks(crate::tests::SETTLE), "the submission checks never answered" ); - device.pointer_imports_follow_their_address() + (device.shared().submit_checks).force(Check::ImportTax, Verdict::Holds); + assert!(device.releases_idle_pointer_imports()); } /// Run `test` on the device the cfg selects. @@ -180,8 +184,7 @@ impl Drop for Pages { /// A no-copy buffer over `bytes.len()` bytes of new pages holding `bytes`, imported by its /// pointer: guest RAM's view, or, where the device refuses its pointer (the call refused, or the /// buffer a copy of the pages, `HostBacking::Copied`), private anonymous pages (the module docs). -/// `None`, printed, where the device refuses both, which a device with the fact never does. The -/// buffer drops before the pages. +/// `None`, printed, where the device refuses both. The buffer drops before the pages. fn no_copy(test: &str, device: &Device, bytes: &[u8]) -> Option<(Pages, Buffer)> { let mut refused = Vec::new(); for pages in [Pages::shared(bytes.len()), Pages::private(bytes.len())] { @@ -212,10 +215,6 @@ fn no_copy(test: &str, device: &Device, bytes: &[u8]) -> Option<(Pages, Buffer)> Err(error) => panic!("{test}: new_buffer_with_bytes_no_copy: {error:?}"), } } - assert!( - !follows(device), - "{test}: the pointers refused: {refused:?}" - ); eprintln!( "{test}: on {}: the device refuses the pointers: {refused:?}", device.name() @@ -223,8 +222,8 @@ fn no_copy(test: &str, device: &Device, bytes: &[u8]) -> Option<(Pages, Buffer)> None } -/// A no-copy buffer over 4 pages, imported by its pointer, on a device whose driver's pointer -/// imports follow their address: +/// A no-copy buffer over 4 pages, imported by its pointer, on a device held to releasing it (the +/// module docs): /// - 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; /// - the CPU's writes made while it is released, through `contents` and through guest RAM's file @@ -232,12 +231,11 @@ fn no_copy(test: &str, device: &Device, bytes: &[u8]) -> Option<(Pages, Buffer)> /// - 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| { + release_pointer_imports(device); let page = host_page(); let len = 4 * page; let queue = device.new_command_queue().unwrap(); @@ -246,12 +244,6 @@ fn an_idle_pointer_import_is_released_and_imported_again_at_its_next_blit() { 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; @@ -308,18 +300,80 @@ fn an_idle_pointer_import_is_released_and_imported_again_at_its_next_blit() { }); } -/// A no-copy buffer over 2 pages, imported by its pointer on a device whose driver's pointer -/// imports follow their address, read by a blit and its import released; then, with no import of -/// them live, other pages mapped over its addresses and the device told. The next blit imports it -/// again at its pointer and reads the new pages. +/// A no-copy buffer over 2 pages, imported by its pointer and read by a blit, on the device as its +/// check found it: the hook releases its import where a held pointer import adds to every +/// submission's cost (`Device::releases_idle_pointer_imports`, the import tax), and the next blit +/// imports it again; elsewhere the import stays, counted as kept for its pointer +/// (`WorkCounts::host_imports_kept_pointer`), and the hook releases nothing. Printed with the +/// check's report (`POINTER-RESIDENCY-GATE`): the evidence of the path the device took. A device +/// that releases pointer imports took the check's own, so it refuses no pointer of both kinds. +#[test] +fn an_idle_pointer_import_is_released_where_held_imports_cost_submissions() { + const TEST: &str = "pointer residency gate"; + on_device(|device| { + assert!( + device.settle_submit_checks(crate::tests::SETTLE), + "{TEST}: the submission checks never answered" + ); + let releases = device.releases_idle_pointer_imports(); + let len = 2 * host_page(); + let queue = device.new_command_queue().unwrap(); + let bytes = counting(len, 23); + let before = device.work_counts(); + let Some((_pages, buffer)) = no_copy(TEST, device, &bytes) else { + assert!( + !releases, + "{TEST}: a device that releases pointer imports refused both pointers" + ); + return; + }; + assert!(read(&queue, &buffer, len) == bytes, "{TEST}"); + let made = device.work_counts(); + let kept = made.host_imports_kept_pointer - before.host_imports_kept_pointer; + let resident = made.host_imports_resident - before.host_imports_resident; + assert_eq!( + (kept, resident), + (u64::from(!releases), u64::from(releases)), + "{TEST}: kept for its pointer, or releasable" + ); + match releases { + true => release(TEST, device, 1), + false => assert_eq!(device.release_idle_host_imports(), 0, "{TEST}: released"), + } + assert!( + read(&queue, &buffer, len) == bytes, + "{TEST}: after the hook" + ); + let after = device.work_counts(); + let moved = ( + after.host_imports_released - before.host_imports_released, + after.host_imports_reimported - before.host_imports_reimported, + ); + assert_eq!( + moved, + (u64::from(releases), u64::from(releases)), + "{TEST}: released and imported again" + ); + drop(buffer); + eprintln!( + "POINTER-RESIDENCY-GATE {TEST}: on {}: idle pointer imports released {releases}; {}", + device.name(), + device.submit_check_report() + ); + }); +} + +/// A no-copy buffer over 2 pages, imported by its pointer on a device held to releasing it (the +/// module docs), read by a blit and its import released; then, with no import of them live, other +/// pages mapped over its addresses and the device told: a remap under a live buffer, which +/// `HostMemory::new`'s contract forbids, but under no live import. The next blit imports it again +/// at its pointer and reads the new pages, the runtime's own answer where such a remap leaves the +/// buffer's bytes unspecified (`docs/FAST-PATHS.md`, known gaps). #[test] fn a_released_pointer_import_is_made_again_over_the_pages_mapped_at_its_pointer() { const TEST: &str = "pointer residency remap"; on_device(|device| { - if !follows(device) { - eprintln!("{TEST}: on {}: pointer imports kept", device.name()); - return; - } + release_pointer_imports(device); let page = host_page(); let len = 2 * page; let queue = device.new_command_queue().unwrap(); @@ -458,10 +512,10 @@ fn a_file_s_pages_mapped_under_a_kept_pointer_import() { let lost = device.is_lost(); let recoveries = device.work_counts().device_recoveries; eprintln!( - "FILE-REMAP {TEST}: on {} (the fact {}): another buffer's fill {}; the copy {read_of}; \ - the device lost: {lost}; its recoveries: {recoveries}", + "FILE-REMAP {TEST}: on {} (idle pointer imports released: {}): another buffer's fill \ + {}; the copy {read_of}; the device lost: {lost}; its recoveries: {recoveries}", device.name(), - follows(device), + device.releases_idle_pointer_imports(), filled.as_deref().unwrap_or("completed"), ); match device.properties().description.driver_id { diff --git a/crates/metal2vulkan-runtime/src/tests/submit_check.rs b/crates/metal2vulkan-runtime/src/tests/submit_check.rs index aee085f6d..a253057b6 100644 --- a/crates/metal2vulkan-runtime/src/tests/submit_check.rs +++ b/crates/metal2vulkan-runtime/src/tests/submit_check.rs @@ -424,7 +424,7 @@ fn identity(device_id: u32) -> DriverIdentity { #[test] fn a_record_holds_its_identity_s_verdicts() { let (one, other) = (identity(0x15bf), identity(0x1114)); - let verdicts = [Verdict::Holds, Verdict::Holds, Verdict::Fails]; + let verdicts = [Verdict::Holds, Verdict::Fails]; let measured = Measured { merged: 13_200, apart: 37_300, @@ -439,10 +439,6 @@ fn a_record_holds_its_identity_s_verdicts() { let mut changed = bytes.clone(); changed[60] ^= 1; assert_eq!(decode(&one, &changed), None); - let pending = encode( - &one, - [Verdict::Holds, Verdict::Pending, Verdict::Fails], - measured, - ); + let pending = encode(&one, [Verdict::Holds, Verdict::Pending], measured); assert_eq!(decode(&one, &pending), None); } diff --git a/crates/metal2vulkan-runtime/src/tests/submit_check_device.rs b/crates/metal2vulkan-runtime/src/tests/submit_check_device.rs index d5c5de762..dd4f875a2 100644 --- a/crates/metal2vulkan-runtime/src/tests/submit_check_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/submit_check_device.rs @@ -3,20 +3,22 @@ //! follow their verdicts alone. //! //! - **They answer.** A device made over a fresh shader cache runs its checks once -//! (`WorkCounts::submit_checks_run`), each verdict an answer (never pending once settled; the -//! follows check answered on Linux where the device imports host pointers), their calls counted -//! apart (`WorkCounts::submit_check_calls`), their allocations too (`device_checks`), and their -//! commands among none of the device's -//! (`commands_recorded`: a device that ran them recorded the copies one that recalled them did, -//! the follows check's three among neither); a later device over the same cache recalls them +//! (`WorkCounts::submit_checks_run`), each verdict an answer (never pending once settled), their +//! calls counted apart (`WorkCounts::submit_check_calls`), their allocations too +//! (`device_checks`), and their commands among none of the device's (`commands_recorded`: a +//! device that ran them recorded the copies one that recalled them did); a later device over the +//! same cache recalls them //! (`submit_checks_recalled`), runs none, and holds the verdicts of the last device that ran //! them: the first's, or, where load split its tries or its import tax answered `Holds` short //! of a record and nothing was recorded, those of the next device that ran them. +//! - **No remap under an import.** The checks map no page over a live import of it: they make and +//! bind no buffer, and every import of theirs is freed by the time they answer +//! ([`a_device_s_checks_map_no_pages_over_a_live_import`]). //! - **The paths follow them.** Grouped batches where the merge holds //! (`WorkCounts::grouped_submissions`), a long `Shared` buffer in fresh pages where a held -//! import adds nothing to a submission (`fresh_page_buffers_made`), a no-copy buffer's pointer -//! import released while idle where pointer imports follow their address -//! (`host_imports_released`, `tests/pointer_residency.rs` for the release itself). Each +//! import adds nothing to a submission (`fresh_page_buffers_made`), and a no-copy buffer's +//! pointer import released while idle where one does (`host_imports_released`: on Linux, +//! `tests/pointer_residency.rs`). Each //! verdict is printed, with what the checks measured: the evidence of which path the device //! took. //! @@ -74,7 +76,7 @@ fn files_named(directory: &Path, name: &str) -> Vec { } /// Each check's verdict on `device`. -fn verdicts(device: &Device) -> [Verdict; 3] { +fn verdicts(device: &Device) -> [Verdict; Check::COUNT] { Check::ALL.map(|check| device.shared().submit_checks.verdict(check)) } @@ -90,13 +92,6 @@ fn the_checks_answer_once_and_a_second_device_recalls_them() { println!("{}: {}", first.name(), first.submit_check_report()); assert!(!answered.contains(&Verdict::Pending), "{answered:?}"); let imports = first.shared().host_import.is_ok(); - if imports && cfg!(target_os = "linux") { - assert_ne!( - answered[2], - Verdict::Unchecked, - "the follows check did not run" - ); - } let counts = first.work_counts(); let mut copies = counts.commands_recorded.cmd_copy_buffer; assert_eq!(counts.submit_checks_run, 1); @@ -109,8 +104,7 @@ fn the_checks_answer_once_and_a_second_device_recalls_them() { counts.device_checks.vk_memory_allocations > 0, "the checks' allocations were not counted apart" ); - // Each import tax try makes its imports once and releases them once (`tax_holds`); the - // follows check imports one page pair a pass, two passes, on Linux. + // Each import tax try makes its imports once and releases them once (`tax_holds`). let tries = (first.shared().submit_checks.tax_tries).load(std::sync::atomic::Ordering::Relaxed); let checks = &counts.device_checks; println!( @@ -118,9 +112,8 @@ fn the_checks_answer_once_and_a_second_device_recalls_them() { checks.vk_memory_allocations, checks.vk_memory_freed, ); if imports { - let follows = if cfg!(target_os = "linux") { 2 } else { 0 }; assert!( - checks.vk_memory_allocations <= tries * TAX_IMPORTS + follows, + checks.vk_memory_allocations <= tries * TAX_IMPORTS, "{} allocations over {tries} tries of {TAX_IMPORTS} imports", checks.vk_memory_allocations, ); @@ -176,6 +169,55 @@ fn the_checks_answer_once_and_a_second_device_recalls_them() { } } +/// A device's making maps no page over a live import of it, on its own thread or the checks': +/// the submission checks' imports are the import tax's (`submit_check.rs`), over pages the checks +/// map where the kernel places them, never map over, and unmap only once every import of them was +/// freed; they make and bind no buffer, so none of their commands reads imported pages. A device +/// made over a fresh shader cache runs them (`WorkCounts::submit_checks_run`), counted apart +/// (`WorkCounts::device_checks`, the queue-switch check's work among it, which makes no buffer or +/// memory): no `vkCreateBuffer` or `vkBindBufferMemory`, at most [`TAX_IMPORTS`] memories a try, +/// and, where the import tax answered, every one freed by then. Printed (`NO-REMAP`). +#[test] +fn a_device_s_checks_map_no_pages_over_a_live_import() { + let scratch = Scratch::new("submit-checks-no-remap"); + let device = device(&scratch.0); + assert!( + device.settle_submit_checks(SETTLE), + "the checks never answered" + ); + let counts = device.work_counts(); + assert_eq!(counts.submit_checks_run, 1, "the checks did not run"); + let checks = &counts.device_checks; + let tries = (device.shared().submit_checks.tax_tries).load(Ordering::Relaxed); + let taxed = device.shared().submit_checks.verdict(Check::ImportTax); + println!( + "NO-REMAP {}: the checks' memories {} allocated, {} freed over {tries} import tax tries \ + (import tax {taxed:?}); buffers {} made, {} bound: {}", + device.name(), + checks.vk_memory_allocations, + checks.vk_memory_freed, + checks.vk_buffers_made, + checks.vk_buffer_bindings, + device.submit_check_report(), + ); + assert_eq!( + (checks.vk_buffers_made, checks.vk_buffer_bindings), + (0, 0), + "the checks made or bound a buffer" + ); + assert!( + checks.vk_memory_allocations <= tries * TAX_IMPORTS, + "{} memories over {tries} tries of {TAX_IMPORTS} imports", + checks.vk_memory_allocations, + ); + if taxed != Verdict::Unchecked { + assert_eq!( + checks.vk_memory_freed, checks.vk_memory_allocations, + "an import of the checks outlived their answer" + ); + } +} + /// A loss of the device the checks meet stops them at the call that answers it, here a wait for /// their fence answering `VK_ERROR_DEVICE_LOST` (injected, `SubmitChecks::lost_at_wait`): nothing /// is submitted after it, so no fence or command buffer of theirs goes to the lost device again, diff --git a/crates/metal2vulkan-runtime/src/tests/unmap_order.rs b/crates/metal2vulkan-runtime/src/tests/unmap_order.rs index 813672ee7..b3509ed74 100644 --- a/crates/metal2vulkan-runtime/src/tests/unmap_order.rs +++ b/crates/metal2vulkan-runtime/src/tests/unmap_order.rs @@ -8,7 +8,8 @@ //! - the queue's thread that sees a command buffer holding the buffer complete, for one released //! while that command buffer waits for an event; //! - that thread again, for one whose import the device released while idle and its next blit -//! imported again (`host_residency.rs`), on a device whose pointer imports follow their address. +//! imported again (`host_residency.rs`), the device held to releasing idle pointer imports +//! whatever its check found (`tests/pointer_residency.rs`). //! //! Each signal reads the device's live host imports (`WorkCounts::host_imports_live`, a census of //! its imported blocks under the memory's lock, under which each import's `vkFreeMemory` runs) and @@ -21,7 +22,7 @@ //! `m2v_cpu_icd`), on Linux, on the kind of device the cfg selects. use super::host_residency::{device, host_page, release, Scratch}; -use super::pointer_residency::follows; +use super::pointer_residency::release_pointer_imports; use crate::{ Buffer, BufferContents, BufferDescriptor, CommandQueue, Device, EventRef, HostMemory, ResourceOptions, SharedEvent, @@ -204,7 +205,7 @@ fn a_no_copy_buffer_s_signal_comes_after_every_free_of_its_pages() { device.settle_in_place_checks(crate::tests::SETTLE), "{TEST}: the in-place checks never settled" ); - let reimports = follows(&device); + release_pointer_imports(&device); let len = PAGES * host_page(); let queue = device.new_command_queue().unwrap(); let into = device @@ -226,9 +227,6 @@ fn a_no_copy_buffer_s_signal_comes_after_every_free_of_its_pages() { let mut ran = Vec::new(); for round in 0..ROUNDS { for case in cases { - if case == Case::Reimported && !reimports { - continue; - } for signal in [Signal::KeepAlive, Signal::Deallocator] { let what = format!("{TEST}: round {round}, {case:?}, {signal:?}"); let buffer = no_copy(&device, len, signal, &seen); @@ -276,21 +274,14 @@ fn a_no_copy_buffer_s_signal_comes_after_every_free_of_its_pages() { ); let reimported = counts.host_imports_reimported - base.host_imports_reimported; let released = counts.host_imports_released - base.host_imports_released; - if reimports { - let expected = (ROUNDS * 2) as u64; - assert_eq!(released, expected, "{TEST}: imports released while idle"); - assert_eq!(reimported, expected, "{TEST}: imports made again"); - } + let expected = (ROUNDS * 2) as u64; + assert_eq!(released, expected, "{TEST}: imports released while idle"); + assert_eq!(reimported, expected, "{TEST}: imports made again"); eprintln!( "UNMAP-ORDER {TEST}: on {}: {} buffers unmapped at their signals ({} rounds; released and \ - imported again while idle: {}), {submitted} command buffers of the other thread", + imported again while idle: {released}), {submitted} command buffers of the other thread", device.name(), ran.len(), ROUNDS, - if reimports { - format!("{released}") - } else { - "none, the device keeps its pointer imports".to_owned() - }, ); } diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index 35c84dc2e..9f3b97a00 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -5952,7 +5952,7 @@ pub struct WorkCounts { pub queue_switch_checks_recalled: u64, /// Runs in this process of the device's submission checks (`submit_check.rs`: whether /// `VkSubmitInfo`s that signal nothing merge, whether a held host-pointer import adds to every - /// submission's cost, whether a pointer import follows its address), whatever they answered. + /// submission's cost), whatever they answered. pub submit_checks_run: u64, /// Devices whose submission checks' verdicts were read from the record of an earlier run of /// the same driver, device, kernel and runtime: no check ran for them. @@ -7240,9 +7240,9 @@ pub struct WorkCounts { /// 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 submission checks did not find its pointer imports to read the pages - /// mapped at the pointer at each submission - /// (`Device::pointer_imports_follow_their_address`), or off Unix. + /// idle as the device's submission checks did not find a held pointer import to cost every + /// submission (`Device::releases_idle_pointer_imports`), or had not answered as the buffer + /// was made, 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. 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 0b9cc51fb..4192cb550 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/submit_per_import.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/submit_per_import.rs @@ -31,9 +31,9 @@ //! 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 device's check found its pointer imports follow their address (the runtime's -//! `submit_check.rs`), again once the device's residency thread -//! released the idle ones while paced frames kept the read ones in use. Printed as +//! where the device's check found a held pointer import adds to every submission's cost (the +//! runtime's `submit_check.rs`, `Device::releases_idle_pointer_imports`), 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 @@ -436,10 +436,10 @@ fn submit_per_import_guest_shape() { .collect(); let used = &buffers[..GUEST_USED]; guest_measure(&device, &queue, &target, used, "at once"); - if !device.pointer_imports_follow_their_address() { + if !device.releases_idle_pointer_imports() { eprintln!( - "SUBMIT-GUEST-SHAPE {}: pointer imports kept (the device's check did not find them \ - follow their address)", + "SUBMIT-GUEST-SHAPE {}: pointer imports kept (the device's check did not find a held \ + one to cost its submissions)", device.name() ); return; diff --git a/crates/metal2vulkan/src/device/driver_facts.rs b/crates/metal2vulkan/src/device/driver_facts.rs index 47630bdfa..69e062fcd 100644 --- a/crates/metal2vulkan/src/device/driver_facts.rs +++ b/crates/metal2vulkan/src/device/driver_facts.rs @@ -11,14 +11,13 @@ //! A GPU that reports more than one `deviceID` is one device class under each: every table here //! names it by the ID it was measured under, and a description is read by its //! [`DeviceDescription::canonical_device_id`]. MoltenVK's `deviceID` on Apple's GPUs is the macOS -//! release and the GPU family, so a row of one names every GPU of the family under that macOS. -//! A driver or GPU no row names takes no fact: the reader takes the route each fact's docs name -//! for a driver without it. A question a device answers about itself in a few milliseconds is no -//! row: the runtime's device checks measure it on each device, once per driver and release -//! (whether its submissions that signal nothing merge, whether a held host-pointer import adds to -//! each submission's cost, whether a pointer import follows its address: the runtime's -//! `submit_check.rs`; textures in place over host pages, `in_place_check.rs`; the GPU's idling -//! between `VkQueue`s, `queue_switch_check.rs`). +//! release and the GPU family, so a row of one names every GPU of the family under that macOS. A +//! driver or GPU no row names takes no fact: the reader takes the route each fact's docs name for a +//! driver without it. A question a device answers about itself in a few milliseconds is no row: the +//! runtime's device checks measure it on each device, once per driver and release (whether its +//! submissions that signal nothing merge, whether a held host-pointer import adds to each +//! submission's cost: the runtime's `submit_check.rs`; textures in place over host pages, +//! `in_place_check.rs`; the GPU's idling between `VkQueue`s, `queue_switch_check.rs`). use crate::device::description::APPLE_VENDOR_ID; use crate::device::profile::DriverWorkaround; diff --git a/crates/metal2vulkan/src/device/tests/driver_facts.rs b/crates/metal2vulkan/src/device/tests/driver_facts.rs index 82356a224..a1aa0bde1 100644 --- a/crates/metal2vulkan/src/device/tests/driver_facts.rs +++ b/crates/metal2vulkan/src/device/tests/driver_facts.rs @@ -711,8 +711,8 @@ fn nvidia_s_every_1024th_signalling_submit_stall_holds_on_the_gpu_measured() { /// submissions), at another release too. Under /// the RX 7900 XTX's (0x744c) it takes the one answer measured there too, BC1 to BC3's block /// decode, and none of the 780M's others; under the RX 550's (0x699f) the one answer measured -/// there, a cleared depth at the standard positions. Whether its submissions merge and whether -/// its pointer imports follow their address are no facts of the table: the runtime's device +/// there, a cleared depth at the standard positions. Whether its submissions merge and whether a +/// held pointer import costs its submissions are no facts of the table: the runtime's device /// checks answer them on each device (`submit_check.rs` in the runtime), so a GPU no row names /// takes those paths too. #[test] diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 88a74fe7f..da75c3f31 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -8257,7 +8257,6 @@ method metal2vulkan-runtime::Device::new_tile_render_pipeline_state pub fn new_t method metal2vulkan-runtime::Device::new_tile_render_pipeline_state_with_reflection pub fn new_tile_render_pipeline_state_with_reflection(&self, descriptor: &TileRenderPipelineDescriptor, options: &PipelineOptions) -> Result<(RenderPipelineState, Option), Error> method metal2vulkan-runtime::Device::pixel_format_capabilities pub fn pixel_format_capabilities(&self, format: PixelFormat) -> FormatCapabilities method metal2vulkan-runtime::Device::pixel_format_info pub fn pixel_format_info(&self, raw: u64) -> PixelFormatInfo -method metal2vulkan-runtime::Device::pointer_imports_follow_their_address pub fn pointer_imports_follow_their_address(&self) -> bool method metal2vulkan-runtime::Device::private_properties pub fn private_properties(&self) -> PrivateProperties method metal2vulkan-runtime::Device::properties pub fn properties(&self) -> &DeviceProperties method metal2vulkan-runtime::Device::queue_switch_check_report pub fn queue_switch_check_report(&self) -> String @@ -8265,6 +8264,7 @@ method metal2vulkan-runtime::Device::raw pub unsafe fn raw(&self) -> DeviceHandl method metal2vulkan-runtime::Device::recover_for_test pub fn recover_for_test(&self) -> Result<(), Error> method metal2vulkan-runtime::Device::registry_id pub fn registry_id(&self) -> u64 method metal2vulkan-runtime::Device::registry_ids_with pub fn registry_ids_with(options: &DeviceOptions) -> Result, Error> +method metal2vulkan-runtime::Device::releases_idle_pointer_imports pub fn releases_idle_pointer_imports(&self) -> bool method metal2vulkan-runtime::Device::reserve_address_pool pub fn reserve_address_pool(&self, placement: AddressPlacement, length: u64) -> Result method metal2vulkan-runtime::Device::reserve_resource_ids pub fn reserve_resource_ids(&self, kind: ResourceIdKind, ids: &[ResourceId]) -> Result<(), Error> method metal2vulkan-runtime::Device::sampler_id_pool_size pub fn sampler_id_pool_size(&self) -> u64 diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 00cc9d9c5..c780ca45e 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -688,18 +688,19 @@ driver's. Each is open work. the runtime it waits, for good behind a loop without bound. A fault or hang on another queue ends the loop as Metal's does. -- **A no-copy buffer imported by its pointer follows a remap of its pages** on a driver whose - pointer imports follow their address (`Device::pointer_imports_follow_their_address`, the device's - own check: ANV on i915, RADV, lavapipe): pages mapped over the buffer's addresses after it was - made (`mmap` with `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. On RADV (Mesa 26.2.4, the Radeon 780M and the RX 7900 XTX) - a file's pages mapped so over a live pointer import of anonymous pages lose the device: its next - submission is rejected whatever it uses ("The CS has been rejected"): amdgpu's userptr takes only - pages with no file behind them, and each submission lists every memory the device imported. No - exact form exists once the pages are gone, and `Device::host_range_remapped` does not release such - an import. 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. +- **What a no-copy buffer reads after a remap of its pages under it is unspecified**, where Metal's + buffer keeps the pages it was made over. `HostMemory::new`'s contract forbids replacing the pages + under a live buffer (`mmap` with `MAP_FIXED`), and no notice tells of it. Under a live import of + the pointer, `VK_EXT_external_memory_host` leaves undefined whether the import holds a reference + to its pages, so what later command buffers read and write is the driver's, and differs between + drivers. Under a released one (`host_residency.rs`), the next blit imports the new pages. On RADV + (Mesa 26.2.4, the Radeon 780M and the RX 7900 XTX) a file's pages mapped so over a live pointer + import of anonymous pages lose the device: its next submission is rejected whatever it uses ("The + CS has been rejected"): amdgpu's userptr takes only pages with no file behind them, and each + submission lists every memory the device imported. No exact form exists once the pages are gone, + and `Device::host_range_remapped` does not release such an import. 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. - **On a device with one graphics queue, a compositor's command buffers wait behind another queue's long one**: RADV, ANV and lavapipe expose a single graphics `VkQueue`, so every command queue, `Device::new_command_queue_unshared`'s included, submits to it, in order. A command buffer committed behind another queue's 200 ms one starts @@ -727,9 +728,9 @@ driver's. Each is open work. page**: amdgpu gets every page of each live pointer import again in each command submission (the RX 7900 XTX under Linux 7.0.0: the scheduler thread's CPU per command buffer of a guest-shaped frame 18 us with none, 328 us with 275 imports of 512 KiB, 1144 us with 275 of - 2 MiB). An idle one is released where the device's check finds its pointer imports follow their - address (`Device::pointer_imports_follow_their_address`), but one whose Metal address was handed - out, or one made before the check answered, stays live. 275 kept dma-buf imports of 512 KiB each + 2 MiB). An idle one is released where the device's check finds a held pointer import costs every + submission (`submit_check.rs`, the import tax), but one whose Metal address was handed out, or one + made before the check answered, stays live. 275 kept dma-buf imports of 512 KiB each cost 54-56 us per command buffer there (no other size measured). - **A detach or rebind between a command buffer's submissions.** A command buffer's later submission, behind an event wait, reaches a no-copy buffer detached or rebound after its first diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 610628649..4cf5f142a 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -289,13 +289,16 @@ released: 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, as the device - checks once per driver, release and kernel by remapping pages of its own under a live import - (`Device::pointer_imports_follow_their_address`, Linux only; ANV, RADV and lavapipe answer yes, - NVIDIA no). There a live import reads, at each submission, the pages mapped at its pointer then, - so the new import at the same pointer reads what the kept one would. Buffers made before the check - answered keep their imports. A blit whose released buffer the device cannot import again is - refused, typed as the first import would be. Elsewhere a pointer import stays imported. +- An import of the pointer, on a device whose held pointer imports add to every submission's cost, + as the device checks once per driver, release and kernel (its import tax check, which holds 32 + imports of its own pages through timed submissions; RADV and ANV on i915 pay it). The new import + at the same pointer reads the pages the kept one did: `HostMemory::new`'s contract keeps the + caller's pages mapped there, with the same backing, while the buffer lives. Buffers made before + the check answered keep their imports. A blit whose released buffer the device cannot import + again is refused, typed as the first import would be. Where a held import costs nothing (NVIDIA's + driver on an RTX 5080 Laptop GPU, 615.71.09: 2.1 to 2.2 us a submission with and without; + MoltenVK 1.4.2 on an M3 Max), a pointer import stays imported: releasing it would save nothing + and cost the next blit an import. 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 @@ -305,8 +308,9 @@ rebind's imports. `WorkCounts::host_imports_released`, `host_imports_reimported` `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 +whatever reads them, by cause (a heap's, a rebind's, a pointer import on a device whose held +imports cost no submission or made before its check answered, 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 @@ -457,14 +461,14 @@ An import is freed by the thread that drops the last reference to it; by a queue last command buffer holding it completed (one that used the buffer, a blit's hold on an import the device releases while idle, or a texture's image over the pages); by a handler thread where a keep-alive alone waits for the free; and, while the buffer lives, by the device's residency thread -(`metal2vulkan-residency`), which every half second frees the idle pointer imports past their -window on a driver whose pointer imports follow their address (above), the next blit importing -them again on the thread that encodes it. On RADV and ANV every submission of the device, from any -thread, lists every live import. So pages unmapped before their objects go meet those threads at -any moment, also where the objects are dropped right after on another thread: on ANV a submission -that lists an import of pages gone fails and the device is lost, and on a Radeon 780M (Linux 7.3.3) -an unmap of pages under a live pointer import oopsed the kernel in amdgpu's notifier -(`amdgpu_hmm_invalidate_gfx`), the GPU's work hanging until the machine was rebooted. +(`metal2vulkan-residency`), which every half second frees the idle imports past their window that +the device releases (above), the next blit importing them again on the thread that encodes it. On +RADV and ANV every submission of the device, from any thread, lists every live import. So pages +unmapped before their objects go meet those threads at any moment, also where the objects are +dropped right after on another thread: on ANV a submission that lists an import of pages gone fails +and the device is lost, and on a Radeon 780M (Linux 7.3.3) an unmap of pages under a live pointer +import oopsed the kernel in amdgpu's notifier (`amdgpu_hmm_invalidate_gfx`), the GPU's work hanging +until the machine was rebooted. ### Copied host buffers