From 045ae9caa83e2bdec0709f7499bd7d5d44452c42 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Sat, 14 Nov 2026 05:12:55 -0800 Subject: [PATCH] RUNTIME 2290: pieces of a shared dma-buf file bind in one import of the file On RADV every guest no-copy buffer and heap is a dma-buf import of its own (the shared mapping's pointer is refused), and RADV lists every import in every submission: the 780M's vkQueueSubmit cost ~0.45 us per live import (the consumer's Super Resolution: ~1,010 imports, p50 531 us a submit). The lever agreed with the consumer: a source answers pieces of files it shares, and the runtime imports each file once. - DmaBufChunk is { file: Arc, offset, length } (was { fd, length }). A chunk at offset 0 whose Arc the runtime alone holds (Arc::try_unwrap) is a dma-buf of its own, imported exactly as before; any other is a piece of a shared file (dma_buf.rs Piece). - DmaBufRequest gains `alignment` (the host page, a plain dma-buf buffer's memory alignment, asked once, or the granule where the request may split) and `shared_files` (false for an image's dedicated import, a guest RAM's chunk and its probe, and a list of runs: those take a dma-buf of its own at offset 0, as before). A misaligned piece, or one past its file, is misuse (Invalid, Problem::DmaBuf). - Each device generation keeps DmaBufFiles: the address of the file's Arc (never the inode) -> Weak, one import of the whole dma-buf, dedicated to nothing, made with no lock held and entered under a leaf lock (a racer's import freed). Each buffer's DmaBufPages holds one Arc per piece; the last holder takes it out of the map under the lock (Arc::into_inner) and frees it through its own device handle. - A plain buffer binds at its piece's offset (Placement::dma_buf takes the offset), a sparse one each piece at its memory offset. - Residency keeps pieces: a dup of an own descriptor (counted against the fd budget, as before), an Arc clone of a shared file (no descriptor). - import_dma_buf borrows the descriptor (it always handed the driver a dup). - WorkCounts: dma_buf_pieces_joined, dma_buf_shared_imports_live (new); dma_buf_imports counts imports made (own chunks and first pieces). Tests: tests/dma_buf_pieces.rs (Piece classification, the map's holds, no device); tests/dma_buf_shared_files.rs (device: four buffers over one file -> one import, three joined, bytes and fills in their pieces, freed with the last; the negative control of own files; two pieces of one file in a sparse buffer at their offsets; release and import again; a misaligned piece refused). Example shared_files: the 780M submit-cost A/B (own files, 8 a file, 1000 a file). Docs: dma_buf.rs module, with_dma_buf (a shared-file import is never dedicated: where a device needs that, the buffer is a copy, the source not asked again), HostRam::with_dma_buf, HOWTO, runtime README; api_signatures.tsv; REFUSALS regenerated (unchanged). Public API change (runtime): DmaBufChunk { file: Arc, offset, length } (+Clone), was { fd, length }; today's behaviour is `file: Arc::new(fd), offset: 0` with no clone kept. DmaBufRequest gains `alignment` and `shared_files`. No Degradation kind. Verified (dmagroup, msi): m3-max-29050 at 51e7f6b569: tests 72/72 on lavapipe (--cfg m2v_cpu_icd; Mesa 26.2.4 takes the no-pointer dma-buf route with /dev/udmabuf), clippy -p runtime -p validation --all-features --all-targets -D warnings plain 0 and m2v_cpu_icd 0, example builds (release). Seen: 4 buffers over one file -> imports 1, joined 3, shared live +1; own files -> imports 4, joined 0; sparse reverse-order pieces -> one import, bytes in order; misaligned (2048 vs 4096) -> Invalid DmaBuf, nothing imported. The 780M submit-cost A/B runs after landing. --- crates/metal2vulkan-runtime/Cargo.toml | 6 + crates/metal2vulkan-runtime/README.md | 3 +- .../examples/shared_files.rs | 278 +++++++ crates/metal2vulkan-runtime/src/device/mod.rs | 6 + crates/metal2vulkan-runtime/src/dma_buf.rs | 713 ++++++++++++++---- .../metal2vulkan-runtime/src/host_memory.rs | 26 +- crates/metal2vulkan-runtime/src/host_ram.rs | 5 +- .../src/host_residency.rs | 40 +- crates/metal2vulkan-runtime/src/memory.rs | 27 +- .../metal2vulkan-runtime/src/tests/copied.rs | 3 +- .../src/tests/copied_device.rs | 7 +- .../src/tests/dma_buf_first_imports.rs | 2 +- .../src/tests/dma_buf_import_cycles.rs | 3 +- .../src/tests/dma_buf_leak_probe.rs | 3 +- .../src/tests/dma_buf_pieces.rs | 92 +++ .../src/tests/dma_buf_shared_files.rs | 473 ++++++++++++ .../src/tests/dropped_uncommitted.rs | 3 +- .../src/tests/export_after_dma_buf.rs | 6 +- .../src/tests/host_memory.rs | 2 + .../src/tests/host_ram_dma_buf.rs | 12 +- .../src/tests/host_ram_listed_bench.rs | 9 +- .../src/tests/host_residency.rs | 8 +- .../src/tests/import_free_hold_bench.rs | 2 +- crates/metal2vulkan-runtime/src/tests/mod.rs | 4 + .../metal2vulkan-runtime/src/work_counts.rs | 62 +- .../src/runtime_lane/dma_buf_imports.rs | 9 +- crates/metal2vulkan/src/cache/mod.rs | 2 +- crates/metal2vulkan/tests/api_signatures.tsv | 9 +- docs/HOWTO.md | 19 +- 29 files changed, 1615 insertions(+), 219 deletions(-) create mode 100644 crates/metal2vulkan-runtime/examples/shared_files.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/dma_buf_pieces.rs create mode 100644 crates/metal2vulkan-runtime/src/tests/dma_buf_shared_files.rs diff --git a/crates/metal2vulkan-runtime/Cargo.toml b/crates/metal2vulkan-runtime/Cargo.toml index 00fb047fa..9bb8fd8d9 100644 --- a/crates/metal2vulkan-runtime/Cargo.toml +++ b/crates/metal2vulkan-runtime/Cargo.toml @@ -59,6 +59,12 @@ path = "examples/host_ab/main.rs" name = "submit_path" path = "examples/submit_path.rs" +# Not a consumer's example: a kernel submission's cost beside no-copy buffers over dma-bufs, each +# a dma-buf of its own against pieces of shared files (Linux, udmabuf). +[[example]] +name = "shared_files" +path = "examples/shared_files.rs" + # Not a consumer's example: the CPU cost of an indirect command buffer's command setters, a # render and a compute command encoded field by field (examples/icb_setters.rs). [[example]] diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index fcede01eb..dab07188e 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -664,7 +664,8 @@ Calls Metal does not have, for a consumer that emulates a Metal device: may hold (`command_writes`), which decides whether an execution runs on the GPU alone, takes what every such state of the command buffer may write, whichever encoder set it. - `HostMemory::with_dma_buf` and its `DmaBufSource`: dma-bufs of a no-copy object's pages, for a - device that refuses their pointer. + device that refuses their pointer, each chunk a dma-buf of its own or a piece of a file the + source shares among several objects (`DmaBufChunk`), which the device imports once. - `HostMemory::with_dirty_pages` and its `DirtyPages` (with `DirtyStamp`): the consumer's log of the writes to a no-copy object's pages, by which every copy of them into memory of the device's own (a shadow of a texture over them, a copied buffer or heap over them) copies in only the diff --git a/crates/metal2vulkan-runtime/examples/shared_files.rs b/crates/metal2vulkan-runtime/examples/shared_files.rs new file mode 100644 index 000000000..b1dfc772b --- /dev/null +++ b/crates/metal2vulkan-runtime/examples/shared_files.rs @@ -0,0 +1,278 @@ +//! Not a consumer's example: what one kernel submission costs beside no-copy buffers over +//! dma-bufs of their pages, each a dma-buf of its own against pieces of files shared among them +//! (`DmaBufChunk`, one import per file), on a device that refuses the pages' pointer: RADV refuses +//! the pointer of a `memfd`'s shared mapping, as of QEMU's guest RAM, and lists every import in +//! every kernel submission. Linux only, with access to `/dev/udmabuf`. +//! +//! ```sh +//! cargo run --release -p metal2vulkan-runtime --example shared_files [-- BUFFERS [PER_FILE ...]] +//! ``` +//! +//! For each count of buffers a file (by default 1, 8 and `BUFFERS`, which is 1000 by default): +//! `BUFFERS` no-copy buffers of 64 KiB over one sealed `memfd` mapped shared, each +//! answered by a source with a piece of the `udmabuf` of its file's run of the `memfd` (1: a +//! `udmabuf` of its own pages, a dma-buf of its own), each buffer's Metal address handed out (so +//! its import stays imported, as a guest's buffers' do); then 300 command buffers of one 4-KiB +//! fill, one at a time, each waited for, after 30 untimed. One `SHARED-FILES` line +//! each: the imports made, the pieces joined to a live import, the dma-buf memories and shared +//! imports live (`WorkCounts::dma_buf_imports`, `dma_buf_pieces_joined`, `dma_buf_memories_live`, +//! `dma_buf_shared_imports_live`), a command buffer's time from its kernelStartTime to its +//! kernelEndTime (50th and 90th percentiles), and the mean time of a `vkQueueSubmit` call in the +//! driver (`WorkCounts::batch_submit_nanos` over `queue_submissions`). A device that imports the +//! pointer (NVIDIA, lavapipe) makes no dma-buf import, which the line shows. + +#[cfg(target_os = "linux")] +mod linux { + use metal2vulkan_runtime::{ + Buffer, CommandBufferStatus, CommandQueue, Device, DmaBufChunk, DmaBufRequest, + DmaBufSource, HostMemory, ResourceOptions, + }; + use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; + use std::ptr::NonNull; + use std::sync::Arc; + use std::time::Duration; + + /// The bytes of each buffer: one 64-KiB chunk, RADV 26.2.4's sparse granule. + const BUFFER_BYTES: usize = 64 << 10; + /// Command buffers committed untimed first. + const WARM: usize = 30; + /// Command buffers timed. + const COMMITS: usize = 300; + /// The longest a command buffer may take. + const WAIT: Duration = Duration::from_secs(60); + + /// `struct udmabuf_create` of Linux's `include/uapi/linux/udmabuf.h`. + #[repr(C)] + struct Create { + memfd: u32, + flags: u32, + offset: u64, + size: u64, + } + + /// `UDMABUF_FLAGS_CLOEXEC`. + const UDMABUF_FLAGS_CLOEXEC: u32 = 0x01; + + /// `UDMABUF_CREATE`, `_IOW('u', 0x42, struct udmabuf_create)` in the generic ioctl encoding. + const UDMABUF_CREATE: u64 = + (1 << 30) | ((size_of::() as u64) << 16) | ((b'u' as u64) << 8) | 0x42; + + /// A dma-buf of `memfd`'s `size` bytes from `offset`. + fn udmabuf(memfd: &OwnedFd, offset: u64, size: u64) -> std::io::Result { + let device = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open("/dev/udmabuf")?; + let create = Create { + memfd: memfd.as_raw_fd() as u32, + flags: UDMABUF_FLAGS_CLOEXEC, + offset, + size, + }; + // SAFETY: the ioctl reads `create`, a valid `udmabuf_create`. + let fd = unsafe { libc::ioctl(device.as_raw_fd(), UDMABUF_CREATE as _, &create) }; + if fd < 0 { + return Err(std::io::Error::last_os_error()); + } + // SAFETY: a new descriptor the ioctl returned, owned at once. + Ok(unsafe { OwnedFd::from_raw_fd(fd) }) + } + + /// Guest RAM: a `memfd` of `len` bytes sealed against growing and shrinking, mapped shared + /// whole; unmapped when dropped. + struct Ram { + fd: OwnedFd, + at: NonNull, + len: usize, + } + + impl Ram { + fn new(len: usize) -> Ram { + // SAFETY: a new anonymous file, owned at once, then sized and sealed. + let fd = unsafe { + let fd = libc::memfd_create( + c"m2v-shared-files".as_ptr(), + libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING, + ); + assert!(fd >= 0, "memfd_create: {}", std::io::Error::last_os_error()); + OwnedFd::from_raw_fd(fd) + }; + // SAFETY: the descriptor is this object's. + unsafe { + assert_eq!(libc::ftruncate(fd.as_raw_fd(), len as libc::off_t), 0); + let seals = libc::F_SEAL_GROW | libc::F_SEAL_SHRINK | libc::F_SEAL_SEAL; + assert_eq!(libc::fcntl(fd.as_raw_fd(), libc::F_ADD_SEALS, seals), 0); + } + // SAFETY: a new shared mapping of the whole file. + let at = unsafe { + libc::mmap( + std::ptr::null_mut(), + len, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_SHARED, + fd.as_raw_fd(), + 0, + ) + }; + assert_ne!(at, libc::MAP_FAILED, "mmap of the memfd"); + Ram { + fd, + at: NonNull::new(at.cast()).unwrap(), + len, + } + } + + /// The mapping's address `offset` bytes in. + fn pointer(&self, offset: usize) -> NonNull { + assert!(offset < self.len); + // SAFETY: inside the mapping. + unsafe { NonNull::new_unchecked(self.at.as_ptr().add(offset)) } + } + + /// A source answering each request with a piece of the file of `per_file` buffers' + /// pages its pages lie in (made now, held by the source), or, for 1, a `udmabuf` of its + /// own pages made as it is asked. + fn source(&self, per_file: usize) -> DmaBufSource { + let base = self.at.as_ptr() as u64; + let file_bytes = (per_file * BUFFER_BYTES) as u64; + let memfd = Arc::new(self.fd.try_clone().unwrap()); + let files: Vec> = match per_file { + 1 => Vec::new(), + _ => (0..(self.len as u64).div_ceil(file_bytes)) + .map(|index| { + let at = index * file_bytes; + let size = file_bytes.min(self.len as u64 - at); + Arc::new(udmabuf(&memfd, at, size).expect("a udmabuf of a file's run")) + }) + .collect(), + }; + Arc::new(move |request: DmaBufRequest| { + let at = (request.start.as_ptr() as u64) + .checked_sub(base) + .ok_or_else(|| std::io::Error::other("pages before the mapping"))?; + if files.is_empty() { + return Ok(vec![DmaBufChunk { + file: Arc::new(udmabuf(&memfd, at, request.length)?), + offset: 0, + length: request.length, + }]); + } + let (index, offset) = (at / file_bytes, at % file_bytes); + let file = (files.get(index as usize)) + .filter(|_| offset + request.length <= file_bytes) + .ok_or_else(|| std::io::Error::other("pages across two files"))?; + Ok(vec![DmaBufChunk { + file: Arc::clone(file), + offset, + length: request.length, + }]) + }) + } + } + + impl Drop for Ram { + fn drop(&mut self) { + // SAFETY: the mapping is this object's, and its buffers went first. + unsafe { libc::munmap(self.at.as_ptr().cast(), self.len) }; + } + } + + /// Commit a fill of `target`'s 4 KiB and wait for it: the microseconds from its + /// kernelStartTime to its kernelEndTime. + fn submitted(queue: &CommandQueue, target: &Buffer, value: u8) -> f64 { + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.fill_buffer(target, 0..4096, value).unwrap(); + blit.end_encoding().unwrap(); + command_buffer.commit().unwrap(); + command_buffer.wait_until_completed_for(WAIT).unwrap(); + assert_eq!(command_buffer.status(), CommandBufferStatus::Completed); + (command_buffer.kernel_end_time() - command_buffer.kernel_start_time()) * 1e6 + } + + /// The phase of `buffers` buffers, `per_file` a file: held, measured and printed. + pub fn phase( + device: &Device, + queue: &CommandQueue, + target: &Buffer, + buffers: usize, + per_file: usize, + ) { + let ram = Ram::new(buffers * BUFFER_BYTES); + let source = ram.source(per_file); + let before = device.work_counts(); + let held: Vec = (0..buffers) + .map(|index| { + let at = ram.pointer(index * BUFFER_BYTES); + // SAFETY: the mapping outlives the buffers (dropped first), and the source makes + // dma-bufs of exactly the pages asked for. + unsafe { + device.new_buffer_with_bytes_no_copy( + HostMemory::with_dma_buf(at, Arc::clone(&source)), + BUFFER_BYTES as u64, + ResourceOptions::shared(), + None, + ) + } + .unwrap() + }) + .collect(); + drop(source); + // Handed out, as a guest's buffers' addresses are: each import stays imported for good. + for buffer in &held { + buffer.gpu_address(); + } + for value in 0..WARM { + submitted(queue, target, value as u8); + } + let counts = device.work_counts(); + let mut times: Vec = (0..COMMITS) + .map(|value| submitted(queue, target, value as u8)) + .collect(); + let after = device.work_counts(); + times.sort_by(f64::total_cmp); + let at = |p: usize| times[(times.len() * p / 100).min(times.len() - 1)]; + let submits = after.queue_submissions - counts.queue_submissions; + let in_driver = (after.batch_submit_nanos - counts.batch_submit_nanos) as f64 + / submits.max(1) as f64 + / 1e3; + println!( + "SHARED-FILES {}: {buffers} buffers, {per_file} a file: {} imports made, {} pieces \ + joined, {} dma-buf memories live ({} shared imports); submit p50 {:.1} us (p90 \ + {:.1}); vkQueueSubmit {in_driver:.1} us each in the driver over {submits} calls", + device.name(), + counts.dma_buf_imports - before.dma_buf_imports, + counts.dma_buf_pieces_joined - before.dma_buf_pieces_joined, + counts.dma_buf_memories_live, + counts.dma_buf_shared_imports_live, + at(50), + at(90), + ); + drop(held); + } +} + +#[cfg(target_os = "linux")] +fn main() { + use metal2vulkan_runtime::{Device, ResourceOptions}; + let mut args = std::env::args() + .skip(1) + .map(|arg| arg.parse::().unwrap()); + let buffers = args.next().unwrap_or(1000); + let mut per_file: Vec = args.collect(); + if per_file.is_empty() { + per_file = vec![1, 8, buffers]; + } + let device = Device::system_default().unwrap(); + println!("device: {}", device.name()); + let queue = device.new_command_queue().unwrap(); + let target = device.new_buffer(4096, ResourceOptions::shared()).unwrap(); + for each in per_file { + linux::phase(&device, &queue, &target, buffers, each); + } +} + +#[cfg(not(target_os = "linux"))] +fn main() { + println!("shared_files: Linux only (udmabuf)"); +} diff --git a/crates/metal2vulkan-runtime/src/device/mod.rs b/crates/metal2vulkan-runtime/src/device/mod.rs index 78e9f17c8..7f892c0ac 100644 --- a/crates/metal2vulkan-runtime/src/device/mod.rs +++ b/crates/metal2vulkan-runtime/src/device/mod.rs @@ -674,6 +674,10 @@ pub(super) struct DeviceShared { /// them (`host_residency.rs`). #[cfg(unix)] pub(super) residency: super::host_residency::Sweeper, + /// Its one import of each dma-buf a caller's source shares among the chunks of several + /// buffers and heaps, by the file's identity (`dma_buf.rs`'s `DmaBufFiles`). + #[cfg(unix)] + pub(super) dma_buf_files: super::dma_buf::DmaBufFiles, /// What lets go of its kept empty memory blocks and parked objects once their time passed, /// whether or not the program makes anything more, and its thread (`idle_sweep.rs`). pub(super) idle_sweep: crate::idle_sweep::IdleSweep, @@ -3154,6 +3158,8 @@ impl Device { carry: Default::default(), #[cfg(unix)] residency: Default::default(), + #[cfg(unix)] + dma_buf_files: Default::default(), idle_sweep, timing, view_reinterpretation, diff --git a/crates/metal2vulkan-runtime/src/dma_buf.rs b/crates/metal2vulkan-runtime/src/dma_buf.rs index bcb4132b9..c7e5af1d4 100644 --- a/crates/metal2vulkan-runtime/src/dma_buf.rs +++ b/crates/metal2vulkan-runtime/src/dma_buf.rs @@ -7,22 +7,45 @@ //! never calls a source. The caller's contract is [`DmaBufSource`]'s, [`DmaBufRequest`]'s and //! `HostMemory::with_dma_buf`'s; this is how the runtime keeps it. //! -//! - **The imports.** Each chunk is its own memory, of the best type of the buffer's memory class -//! (`memory.rs`'s `candidates`: host-visible and coherent, never a device-coherent type of -//! `VK_AMD_device_coherent_memory`, which the runtime does not enable) among those -//! `vkGetMemoryFdPropertiesKHR` and the buffer take. A source that was called is kept with the -//! imports ([`DmaBufPages`]) and dropped with them. +//! - **The imports.** A chunk that is a dma-buf of its own (at offset 0, the runtime its `Arc`'s +//! only holder once the source returns: [`Piece`]) is its own memory, of the best type of the +//! buffer's memory class (`memory.rs`'s `candidates`: host-visible and coherent, never a +//! device-coherent type of `VK_AMD_device_coherent_memory`, which the runtime does not enable) +//! among those `vkGetMemoryFdPropertiesKHR` and the buffer take. A source that was called is +//! kept with the imports ([`DmaBufPages`]) and dropped with them. +//! - **Shared files.** Any other chunk is a piece of a file the source shares among several +//! buffers and heaps (a no-copy buffer's, heap's or rebind's request takes them, +//! [`DmaBufRequest::shared_files`]; an image's, a guest RAM's and a list of runs' take a dma-buf +//! of its own alone). Each device generation imports each such file once ([`DmaBufFiles`], +//! keyed by the address of the file's `Arc`, which the import holds a clone of, never by the +//! descriptor's file), as one `VkDeviceMemory` of the whole dma-buf, of the type the first +//! buffer's class ranks best, dedicated to nothing; a later piece of the file joins that import +//! where its buffer takes the import's type (counted: `WorkCounts::dma_buf_pieces_joined`), and +//! its buffer is a copy of the pages, as for a chunk no type takes, where it does not. The import +//! is made with no lock held, and entered in the device's map under its leaf lock; one made +//! meanwhile by another thread for the same file is freed and that thread's joined. Each +//! buffer's or heap's pages hold the import ([`DmaBufFile`]); the last holder takes it out of +//! the map and frees it (`WorkCounts::dma_buf_shared_imports_live`), after its own `VkBuffer` +//! went, so the import lives while any buffer bound in it does, and so while any command buffer +//! that holds one runs. The driver imports a duplicate of the file's descriptor. A shared file's +//! import is never dedicated, as several buffers bind in it: where the driver refuses it so +//! (NVIDIA's 615.71.09 refuses small dma-bufs dedicated to nothing), the buffer is refused as +//! for a refused chunk (a copy of the pages), and the source is not asked again. A recovery's +//! new generation asks the source again and imports its answer in a map of its own. //! - **The buffer** is a `VkBuffer` made for dma-bufs over the pages from their first byte, so its //! bytes lie at their offset in their first page whatever the chunks, and a rebind between one //! chunk and several keeps their place in it. **One chunk** gives a plain buffer bound at the -//! import's start, the import dedicated to nothing; where the driver refuses that in every type -//! and the buffer is the only resource bound in the import for its life (a no-copy buffer's -//! own import, never a heap's; a copy's list of a guest RAM's runs; the page a use of a RAM asks -//! the driver with), dedicated to the buffer (`memory.rs`'s `DmaBufFor::Buffer`), counted -//! (`WorkCounts::dma_buf_buffer_imports_dedicated`). A guest RAM's chunk or an object's run -//! inside one never is: its objects' buffers are bound in it too (`host_ram.rs`). -//! **Several chunks** give a sparse one (`SPARSE_BINDING`), each chunk bound at -//! its offset from the request's start by one `vkQueueBindSparse` on the device's first queue +//! chunk's offset in its import (the start of a dma-buf of its own, the piece's offset in a +//! shared file's), a multiple of the buffer's memory alignment (the request's `alignment` holds +//! it); a dma-buf of its own is imported dedicated to nothing, and where the driver refuses that +//! in every type and the buffer is the only resource bound in the import for its life (a +//! no-copy buffer's own import, never a heap's; a copy's list of a guest RAM's runs; the page a +//! use of a RAM asks the driver with), dedicated to the buffer (`memory.rs`'s +//! `DmaBufFor::Buffer`), counted (`WorkCounts::dma_buf_buffer_imports_dedicated`). A guest RAM's +//! chunk or an object's run inside one never is: its objects' buffers are bound in it too +//! (`host_ram.rs`). **Several chunks** give a sparse one (`SPARSE_BINDING`), each chunk bound at +//! its offset from the request's start, from its offset in its import, by one +//! `vkQueueBindSparse` on the device's first queue //! (`device/submit.rs`): the call does not wait for it, which would wait behind that queue's //! work in flight; every later submission on every queue waits for it until it completed, and //! the buffer's release does where none did. The granule is the alignment of such a buffer @@ -97,8 +120,8 @@ //! copy of the pages, as where no source is given (`copied.rs`, //! `WorkCounts::copied_host_buffers_device_refused`); a rebind, memory imported only as dma-bufs //! and pages whose window the device's import alignment does not cover are refused -//! (`Unsupported`, `HostMemory`). Counted: `WorkCounts::dma_buf_imports` (each chunk) and -//! `WorkCounts::dma_buf_sparse_buffers`. +//! (`Unsupported`, `HostMemory`). Counted: `WorkCounts::dma_buf_imports` (each chunk of its own, +//! and each shared file's first import) and `WorkCounts::dma_buf_sparse_buffers`. use super::buffer::{usage, Pages}; use super::buffer_descriptor::HostBuffer; @@ -120,7 +143,7 @@ use metal2vulkan::vk::{Format, FormatFeatureFlags2, ImageCreateFlags, SampleCoun use std::ops::Range; use std::os::fd::{AsFd, BorrowedFd, OwnedFd}; use std::ptr::NonNull; -use std::sync::{Arc, Mutex, PoisonError}; +use std::sync::{Arc, Mutex, PoisonError, Weak}; use std::time::Duration; /// A runtime extension (Metal has none): makes dma-bufs of the host pages a no-copy import @@ -136,18 +159,28 @@ use std::time::Duration; /// calls is dropped with the call; one it called is kept with the imports it made, until they go. /// /// It returns dma-bufs of the pages asked for ([`DmaBufRequest`]) in chunks ([`DmaBufChunk`]), in -/// order: each chunk's length a positive multiple of the host page, at most its dma-buf's size, -/// and every boundary between two chunks, as an offset from the request's `start`, a multiple of -/// its `granule`. The descriptors are the runtime's from then on: Vulkan's once imported, closed -/// otherwise. An `Err` keeps the pointer's refusal (`Unsupported`, `HostMemory`), or makes a -/// texture a shadow of the bytes instead (announced `shadowed-texture`); chunks that break these -/// rules or the request's, or a descriptor that is no dma-buf, are refused as misuse (`Invalid`, +/// order: each chunk's length a positive multiple of the host page, its offset in its file a +/// multiple of the request's `alignment`, the chunk within its file's size, and every boundary +/// between two chunks, as an offset from the request's `start`, a multiple of its `granule`. A +/// chunk is a dma-buf of its own (a file the source keeps no clone of, the chunk at offset 0), +/// or, where the request's `shared_files` allows, a piece of a file the source shares among the +/// buffers and heaps it answers (several pieces of one file, in one answer or in many, each the +/// same `Arc`): the runtime imports each such file once on the device, whatever buffers lie in +/// it, and binds each buffer at its piece's offset there, so a device that lists every import in +/// every submission (RADV) lists one per file, not one per buffer. A file's import lives while +/// any buffer or heap bound in it does. The descriptors are the runtime's from then on: Vulkan's +/// once imported, closed otherwise; a shared file's stays open while the runtime holds its `Arc`. +/// An `Err` keeps the pointer's refusal (`Unsupported`, `HostMemory`), or makes a texture a +/// shadow of the bytes instead (announced `shadowed-texture`); chunks that break these rules or +/// the request's, or a descriptor that is no dma-buf, are refused as misuse (`Invalid`, /// `Problem::DmaBuf`). pub type DmaBufSource = Arc std::io::Result> + Send + Sync + 'static>; /// What a [`DmaBufSource`] is asked for: `length` bytes of host pages from `start`, both multiples -/// of the host page, to be returned as chunks split only at multiples of `granule` from `start`. +/// of the host page, to be returned as chunks split only at multiples of `granule` from `start`, +/// each at an offset in its file that is a multiple of `alignment`, pieces of shared files only +/// where `shared_files` says so. /// /// A buffer's or heap's request is the caller's range rounded out to the host page, whatever the /// device's import alignment for host pointers (a dma-buf has none). A texture's starts at the page @@ -172,6 +205,19 @@ pub struct DmaBufRequest { /// (a multiple of the host page); `length` where it does not, so that exactly one chunk is /// taken. pub granule: u64, + /// The multiple of which every chunk's offset in its file is: the host page, or the memory + /// alignment of the buffer bound there where that is larger (Vulkan binds memory only at a + /// multiple of it, `VUID-vkBindBufferMemory-memoryOffset-01036`), or the `granule` where the + /// request may be answered in several chunks (each binds a sparse buffer's memory at its + /// offset, `VUID-VkSparseMemoryBind-memory-01096`). A power of two. A chunk at another offset + /// is refused (`Invalid`, `Problem::DmaBuf`). + pub alignment: u64, + /// Whether the chunks may be pieces of files the source shares, or lie at an offset in their + /// file: a no-copy buffer's, heap's or rebind's pages. Where `false` each chunk must be a + /// dma-buf of its own at offset 0, the runtime the only holder of its `Arc` once the source + /// returns (a texture's image's dedicated import, a guest RAM's chunk or a use's probe of + /// one, `HostRam::with_dma_buf`); another answer is refused as the source's failure is there. + pub shared_files: bool, } // SAFETY: a request is an address and two lengths, plain data: nothing is reached through the @@ -189,27 +235,42 @@ unsafe impl Sync for DmaBufRequest {} /// multiples of the host page, its `granule` its `length`); the requests are by start and share /// no page, each inside one chunk of the RAM (they may lie in several chunks, and in several of /// its ranges), and at most as many as the RAM was given. It returns -/// one [`DmaBufChunk`]: a dma-buf whose bytes are the requests' pages one after another, in -/// order, its `length` their total. The descriptor is the runtime's from then on: Vulkan's once -/// imported, closed otherwise. An `Err`, or a chunk of another length or no dma-buf, leaves the -/// copy to what it takes without the source. +/// one [`DmaBufChunk`]: a dma-buf of its own (each request's `shared_files` is `false`) whose +/// bytes are the requests' pages one after another, in order, its `length` their total. The +/// descriptor is the runtime's from then on: Vulkan's once imported, closed otherwise. An `Err`, +/// or a chunk of another length, a piece of a shared file or at an offset, or no dma-buf, leaves +/// the copy to what it takes without the source. pub type DmaBufRunsSource = Arc std::io::Result + Send + Sync + 'static>; -/// One chunk of a [`DmaBufSource`]'s answer: a dma-buf whose bytes `0..length` are the requested -/// pages from where the chunks before it end. -#[derive(Debug)] +/// One chunk of a [`DmaBufSource`]'s answer (a runtime extension: Metal has none): the bytes +/// `offset..offset + length` of the dma-buf `file`, which are the requested pages from where the +/// chunks before it end. +/// +/// A dma-buf of its own is `file: Arc::new(fd), offset: 0`, imported alone, as its own memory. A +/// piece of a file the source shares is the same `Arc` (a clone of it) in each chunk over that +/// file: the runtime knows a file by its `Arc`'s identity alone (never by the descriptor's number +/// or the file's inode), imports a duplicate of its descriptor once on each device, as one +/// `VkDeviceMemory` of the whole dma-buf, dedicated to nothing, and binds every buffer over its +/// pieces at their offsets in that import ([`DmaBufSource`]). +#[derive(Clone, Debug)] pub struct DmaBufChunk { - /// The dma-buf. - pub fd: OwnedFd, - /// The bytes of the chunk, a multiple of the host page. + /// The dma-buf the chunk lies in. + pub file: Arc, + /// Where the chunk starts in the dma-buf: a multiple of the request's `alignment`, and 0 for + /// a dma-buf of its own. + pub offset: u64, + /// The bytes of the chunk, a multiple of the host page, within the dma-buf from `offset`. pub length: u64, } /// The imports of the chunks a no-copy buffer's host pages lie in, and the source that made them: /// held by the pages' placement (`memory.rs`), so by the buffers and images over them, and freed, /// the source dropped, once the last of those goes. Every `VkBuffer` bound to them is destroyed -/// first (`buffer.rs`'s `HostImport`). +/// first (`buffer.rs`'s `HostImport`). A chunk of a file the source shares lies in the device's +/// one import of that file ([`DmaBufFile`]), which the pages hold beside the other buffers' and +/// heaps' pages bound in it: they let go of their hold as they go, and the last to let go frees +/// it ([`DmaBufFiles::let_go`]). /// /// The last holder may go on a runtime thread (a command buffer's completion lets go of the /// buffer): the imports are freed inside a section of the exit guard, as every Vulkan call there @@ -217,7 +278,14 @@ pub struct DmaBufChunk { /// (`exit_guard::program`), its panic caught. While the process exits both are left to its end. pub(super) struct DmaBufPages { device: Device, + /// The imports of the pages' chunks that are dma-bufs of their own, freed as the pages go. memories: Vec, + /// The device's imports of the shared files the pages' other chunks lie in, one hold per + /// such chunk: let go of as the pages go, freed with the last hold. + files: Vec>, + /// The imports the pages made, of their own chunks and of shared files no buffer had + /// imported yet: what `WorkCounts::dma_buf_imports` counts of them. + made: usize, /// The imports are an image's dedicated one (`Device::dma_buf_image`), not a buffer's chunks: /// what the live gauges count them as (`WorkCounts::dma_buf_image_memories_live`). of_image: bool, @@ -249,6 +317,9 @@ impl Drop for DmaBufPages { if let Some(source) = self.source.take() { std::mem::forget(source); } + for file in self.files.drain(..) { + std::mem::forget(file); + } let after_free = self.after_free.get_mut(); for after in after_free.unwrap_or_else(PoisonError::into_inner).drain(..) { std::mem::forget(after); @@ -257,9 +328,14 @@ impl Drop for DmaBufPages { }; let shared = self.device.shared(); let raw_device = shared.vk(); + // The shared files' imports whose last hold these pages were, out of the device's map. + let last = shared.dma_buf_files.let_go(self.files.drain(..)); + let freed: Vec = (self.memories.iter().copied()) + .chain(last.iter().map(|file| file.memory)) + .collect(); if let Some(log) = crate::memory_log::MemoryLog::new(shared.instance.sink()) { use ash::vk::Handle; - let memories: Vec = (self.memories.iter()) + let memories: Vec = (freed.iter()) .map(|memory| format!("0x{:x}", memory.as_raw())) .collect(); log.line(format!( @@ -270,12 +346,14 @@ impl Drop for DmaBufPages { memories.join(", ") )); } - for &memory in &self.memories { + for &memory in &freed { // SAFETY: nothing is bound to the imports any more and no command reads them (the - // struct's docs). + // struct's docs): a shared file's, once its last holder let go of it, has no buffer + // bound in it either. unsafe { release::object(raw_device, memory) }; } - (shared.counts).dma_buf_memories_freed(self.of_image, self.memories.len()); + (shared.counts).dma_buf_memories_freed(self.of_image, freed.len()); + shared.counts.dma_buf_shared_imports_freed(last.len()); if self.kept_for_fds { shared.counts.host_import_kept_for_fds(false); } @@ -300,6 +378,8 @@ impl DmaBufPages { DmaBufPages { device: device.clone(), memories: Vec::new(), + files: Vec::new(), + made: 0, of_image, source: Some(ProgramObject::new(source)), start: request.start.as_ptr() as u64, @@ -319,6 +399,8 @@ impl DmaBufPages { DmaBufPages { device: device.clone(), memories: Vec::new(), + files: Vec::new(), + made: 0, of_image: false, source: None, start: start.as_ptr() as u64, @@ -336,6 +418,8 @@ impl DmaBufPages { DmaBufPages { device: device.clone(), memories: Vec::new(), + files: Vec::new(), + made: 0, of_image: true, source: None, start: 0, @@ -364,6 +448,7 @@ impl DmaBufPages { /// live. fn hold(&mut self, memory: vk::DeviceMemory) { self.memories.push(memory); + self.made += 1; (self.device.shared().counts).dma_buf_memory_imported(self.of_image); } @@ -404,10 +489,178 @@ impl std::fmt::Debug for DmaBufPages { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("DmaBufPages") .field("memories", &self.memories) + .field("files", &self.files.len()) .finish_non_exhaustive() } } +/// A chunk of a source's answer as the runtime takes it ([`DmaBufChunk`]). +#[derive(Debug)] +pub(super) enum Piece { + /// A dma-buf of its own, at offset 0, the runtime its `Arc`'s only holder: `length` bytes of + /// it imported alone, as today's chunk always was, the import its own memory. + Own { fd: OwnedFd, length: u64 }, + /// A piece of a file the source shares, or at an offset in its file: bound at `offset` of the + /// device's one import of the file ([`DmaBufFiles`]). + Shared { + file: Arc, + offset: u64, + length: u64, + }, +} + +impl Piece { + /// `chunk` as a dma-buf of its own where it is one (at offset 0, and the source kept no + /// clone of its `Arc`: taking the descriptor out is atomic, so a source's clone made at once + /// on another thread leaves it shared), else as a piece of a shared file. + pub(super) fn of(chunk: DmaBufChunk) -> Piece { + let DmaBufChunk { + file, + offset, + length, + } = chunk; + if offset != 0 { + return Piece::Shared { + file, + offset, + length, + }; + } + match Arc::try_unwrap(file) { + Ok(fd) => Piece::Own { fd, length }, + Err(file) => Piece::Shared { + file, + offset, + length, + }, + } + } + + /// The bytes of the piece. + fn length(&self) -> u64 { + match self { + Piece::Own { length, .. } | Piece::Shared { length, .. } => *length, + } + } + + /// Where the piece lies in its import: 0 in its own, its offset in its file's. + fn offset(&self) -> u64 { + match self { + Piece::Own { .. } => 0, + Piece::Shared { offset, .. } => *offset, + } + } + + /// Whether it is a dma-buf of its own, which holds a descriptor of the runtime's. + pub(super) fn own(&self) -> bool { + matches!(self, Piece::Own { .. }) + } + + /// The same piece again, for an import made again of it (`host_residency.rs`): a duplicate of + /// its own descriptor, or a clone of its file's `Arc`, which opens no descriptor. + pub(super) fn again(&self) -> std::io::Result { + Ok(match self { + Piece::Own { fd, length } => Piece::Own { + fd: fd.try_clone()?, + length: *length, + }, + Piece::Shared { + file, + offset, + length, + } => Piece::Shared { + file: Arc::clone(file), + offset: *offset, + length: *length, + }, + }) + } +} + +/// A device's one import of a dma-buf a caller's source shares among the chunks of several +/// buffers and heaps ([`DmaBufChunk`]): the whole dma-buf, dedicated to nothing, of one memory +/// type. Held by the pages of each buffer and heap bound in it ([`DmaBufPages`]), and freed by +/// the last of them to let go ([`DmaBufFiles::let_go`]): every hold is made and let go of under +/// the device's map's lock, so it has no handle of the device and no `Drop` of its own. +#[derive(Debug)] +pub(super) struct DmaBufFile { + /// The file, held so that no other file's `Arc` takes its address while it is imported. + file: Arc, + memory: vk::DeviceMemory, + type_index: u32, +} + +#[cfg(test)] +impl DmaBufFile { + /// A stand-in import of `file`, of no memory: for the map's own tests + /// (`tests/dma_buf_pieces.rs`). + pub(super) fn stand_in(file: Arc) -> DmaBufFile { + DmaBufFile { + file, + memory: vk::DeviceMemory::null(), + type_index: 0, + } + } +} + +/// A device generation's one import of each dma-buf a caller's source shares +/// ([`DmaBufFile`]), by the address of the file's `Arc`: the file's identity, never the +/// descriptor's number or the file's inode (a dma-buf's inode is no documented identity). An +/// entry lives while its import does: the last holder lets go of it and removes the entry under +/// the map's lock, so the map holds at most one entry per live import, as many as the buffers and +/// heaps bound in them at most. A recovery's next generation has a map of its own. The lock is a +/// leaf: nothing else is taken while it is held, and no driver call is made under it. +#[derive(Default)] +pub(crate) struct DmaBufFiles(Mutex>>); + +/// A file's key in the map: its `Arc`'s address. +fn file_key(file: &Arc) -> usize { + Arc::as_ptr(file) as usize +} + +impl DmaBufFiles { + /// The live import of `file`, a new hold of it; `None` where the device holds none. + pub(super) fn live(&self, file: &Arc) -> Option> { + lock(&self.0).get(&file_key(file)).and_then(Weak::upgrade) + } + + /// `made`, a new import of its file made with no lock held, entered as the file's import; or, + /// where another thread entered one of the same file meanwhile, a hold of that one, with + /// `made` back for the caller to free. + pub(super) fn enter( + &self, + made: DmaBufFile, + ) -> Result, (Arc, DmaBufFile)> { + let key = file_key(&made.file); + let mut map = lock(&self.0); + if let Some(live) = map.get(&key).and_then(Weak::upgrade) { + return Err((live, made)); + } + let entered = Arc::new(made); + map.insert(key, Arc::downgrade(&entered)); + Ok(entered) + } + + /// Let go of `holds`: the imports they were the last holds of, out of the map, for the + /// caller to free. A hold is taken only under the lock ([`live`](Self::live), + /// [`enter`](Self::enter)), so the last is known here exactly. + pub(super) fn let_go(&self, holds: impl Iterator>) -> Vec { + let mut map = lock(&self.0); + let mut last = Vec::new(); + for hold in holds { + let key = file_key(&hold.file); + let at = Arc::as_ptr(&hold); + if let Some(file) = Arc::into_inner(hold) { + if map.get(&key).is_some_and(|entry| entry.as_ptr() == at) { + map.remove(&key); + } + last.push(file); + } + } + last + } +} + /// Whether chunks of `lengths` bytes, in order, answer `request` as the [`DmaBufSource`] contract /// allows on a host of `page`-byte pages: at least one, each a positive multiple of the page; /// every boundary between two a multiple of the granule from the request's start; together the @@ -447,15 +700,32 @@ fn lasting_refusal(error: &Error) -> bool { } /// Whether `chunks` answer `request` as the [`DmaBufSource`] contract allows on a host of -/// `page`-byte pages ([`chunks_cover`]), each a dma-buf of at least its length. +/// `page`-byte pages ([`chunks_cover`]), each within its dma-buf from its offset, a multiple of +/// the request's alignment. fn answers(chunks: &[DmaBufChunk], request: &DmaBufRequest, page: u64) -> bool { let lengths: Vec = chunks.iter().map(|chunk| chunk.length).collect(); + let alignment = request.alignment.max(1); let held = |chunk: &DmaBufChunk| { - dma_buf_length(chunk.fd.as_fd()).is_some_and(|bytes| chunk.length <= bytes) + let end = chunk.offset.checked_add(chunk.length); + chunk.offset.is_multiple_of(alignment) + && (end.zip(dma_buf_length(chunk.file.as_fd()))) + .is_some_and(|(end, bytes)| end <= bytes) }; chunks_cover(&lengths, request, page) && chunks.iter().all(held) } +/// `chunks` as the runtime takes them ([`Piece::of`]), where they answer `request` as the +/// [`DmaBufSource`] contract allows on a host of `page`-byte pages ([`answers`]), each a dma-buf +/// of its own where the request takes no piece of a shared file; `None` otherwise, every +/// descriptor closed or let go of. +fn taken(chunks: Vec, request: &DmaBufRequest, page: u64) -> Option> { + if !answers(&chunks, request, page) { + return None; + } + let pieces: Vec = chunks.into_iter().map(Piece::of).collect(); + (request.shared_files || pieces.iter().all(Piece::own)).then_some(pieces) +} + /// The bytes of the dma-buf `fd`; `None` where it is no dma-buf (its file is not on the kernel's /// dma-buf file system). #[cfg(target_os = "linux")] @@ -535,39 +805,37 @@ impl Device { start, length: window.size, granule, + alignment: self.chunk_alignment(importer, granule, window.size), + shared_files: true, }; let chunks = source(request).map_err(|_| not_importable())?; - if !answers(&chunks, &request, importer.page) { - return Err(invalid(call, Problem::DmaBuf)); - } - // Duplicates of the descriptors, kept where the device may release the import: the - // import takes the originals. - let kept: Option> = keep - .then(|| { - (chunks.iter()) - .map(|chunk| Some((chunk.fd.try_clone().ok()?, chunk.length))) - .collect() - }) + let pieces = (taken(chunks, &request, importer.page)) + .ok_or_else(|| invalid(call, Problem::DmaBuf))?; + // The pieces again, kept where the device may release the import: a duplicate of each + // descriptor of its own (the import takes the originals), a clone of each shared file's + // `Arc`. + let kept: Option> = keep + .then(|| pieces.iter().map(|piece| piece.again().ok()).collect()) .flatten(); let kept_source = kept.as_ref().map(|_| Arc::clone(&source)); let mut pages = DmaBufPages::new(self, source, request, false); // SAFETY: the caller's. - let (buffer, memory, type_index) = unsafe { - self.chunks_buffer(importer, chunks, &mut pages, length, window, (class, sole)) + let (buffer, bound) = unsafe { + self.chunks_buffer(importer, pieces, &mut pages, length, window, (class, sole)) }?; let counts = &self.shared().counts; - counts.dma_buf_imported(pages.memories.len()); + counts.dma_buf_imported(pages.made); if pages.bound.is_some() { counts.dma_buf_sparse_buffer_made(); } - let again = kept.zip(kept_source).and_then(|(chunks, source)| { - Again::dma_bufs(self, chunks, source, request, (length, *window, class)) + let again = kept.zip(kept_source).and_then(|(pieces, source)| { + Again::dma_bufs(self, pieces, 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); + let placement = Placement::dma_buf(Arc::new(pages), bound, window.size, start); Ok((buffer, placement, again)) } @@ -612,9 +880,15 @@ impl Device { start, length, granule: length, + alignment: importer.page, + shared_files: false, }; - let chunks = match source(request) { - Ok(chunks) if chunks.len() == 1 && answers(&chunks, &request, importer.page) => chunks, + let answered = source(request).map(|chunks| match chunks.len() { + 1 => taken(chunks, &request, importer.page), + _ => None, + }); + let pieces = match answered { + Ok(Some(pieces)) => pieces, answered => { shared.counts.host_ram_dma_buf_import_failed(); return Err(match answered { @@ -624,7 +898,7 @@ impl Device { } }; // SAFETY: the caller's. - let imported = unsafe { self.ram_span_import(importer, chunks, request, source, sole) }; + let imported = unsafe { self.ram_span_import(importer, pieces, request, source, sole) }; if let Err(error) = &imported { shared.counts.host_ram_dma_buf_import_failed(); if lasting_refusal(error) { @@ -634,9 +908,9 @@ impl Device { imported } - /// The driver's import of `chunks`, the one dma-buf `source` answered `request` with - /// ([`Device::ram_span_as_dma_buf`], whose `sole` this is): the `VkBuffer` over it and its - /// placement. + /// The driver's import of `pieces`, the one dma-buf of its own `source` answered `request` + /// with ([`Device::ram_span_as_dma_buf`], whose `sole` this is): the `VkBuffer` over it and + /// its placement. /// /// # Safety /// @@ -644,7 +918,7 @@ impl Device { unsafe fn ram_span_import( &self, importer: &Importer, - chunks: Vec, + pieces: Vec, request: DmaBufRequest, source: &DmaBufSource, sole: bool, @@ -657,19 +931,18 @@ impl Device { }; let mut pages = DmaBufPages::new(self, Arc::clone(source), request, false); // SAFETY: the caller's. - let (buffer, memory, type_index) = unsafe { + let (buffer, bound) = unsafe { self.chunks_buffer( importer, - chunks, + pieces, &mut pages, length, &window, (MemoryClass::Shared, sole), ) }?; - self.shared().counts.dma_buf_imported(pages.memories.len()); - let placement = - Placement::dma_buf(Arc::new(pages), memory, type_index, length, request.start); + self.shared().counts.dma_buf_imported(pages.made); + let placement = Placement::dma_buf(Arc::new(pages), bound, length, request.start); Ok((buffer.raw, placement)) } @@ -751,6 +1024,8 @@ impl Device { start, length, granule: length, + alignment: importer.page, + shared_files: false, }) }) .collect(); @@ -762,10 +1037,11 @@ impl Device { start, length, granule: length, + alignment: importer.page, + shared_files: false, }; - if !answers(std::slice::from_ref(&chunk), &whole, importer.page) { - return Err(invalid("use_host_ram", Problem::DmaBuf)); - } + let pieces = taken(vec![chunk], &whole, importer.page) + .ok_or_else(|| invalid("use_host_ram", Problem::DmaBuf))?; let window = ImportWindow { start: start.as_ptr() as u64, size: length, @@ -773,10 +1049,10 @@ impl Device { }; let mut pages = DmaBufPages::of_runs(self, start); // SAFETY: the caller's. - let (buffer, memory, type_index) = unsafe { + let (buffer, bound) = unsafe { self.chunks_buffer( importer, - vec![chunk], + pieces, &mut pages, length, &window, @@ -788,20 +1064,21 @@ impl Device { shared.host_ram.refuse_dma_bufs(); } })?; - shared.counts.dma_buf_imported(pages.memories.len()); - let placement = Placement::dma_buf(Arc::new(pages), memory, type_index, length, start); + shared.counts.dma_buf_imported(pages.made); + let placement = Placement::dma_buf(Arc::new(pages), bound, length, start); Ok((buffer.raw, placement)) } - /// 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. + /// The pages of a released import made again from the pieces `kept` of it, 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 (a shared file's import live + /// still, or made again), 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)], + kept: &[Piece], source: &DmaBufSource, request: DmaBufRequest, again: &Again, @@ -815,16 +1092,11 @@ impl Device { .host_import .as_ref() .map_err(|_| internal("a dma-buf import made again on a device that imports none"))?; - let chunks = chunks - .iter() - .map(|(fd, length)| { - let fd = fd - .try_clone() - .map_err(|_| Error::OutOfMemory(MemoryKind::Host))?; - Ok(DmaBufChunk { - fd, - length: *length, - }) + let pieces = (kept.iter()) + .map(|piece| { + piece + .again() + .map_err(|_| Error::OutOfMemory(MemoryKind::Host)) }) .collect::, Error>>()?; let mut pages = DmaBufPages::new(self, Arc::clone(source), request, false); @@ -832,11 +1104,11 @@ impl Device { // 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). Kept only by a // no-copy buffer's own import (`Device::import_from_source`'s `keep`), its buffer the - // only resource bound in it, as the new one is. - let (buffer, memory, type_index) = unsafe { + // only resource bound in its own pieces' imports, as the new one is. + let (buffer, bound) = unsafe { self.chunks_buffer( importer, - chunks, + pieces, &mut pages, again.length, window, @@ -848,7 +1120,7 @@ impl Device { other => refused(other), })?; let start = request.start; - let placement = Placement::dma_buf(Arc::new(pages), memory, type_index, window.size, start); + let placement = Placement::dma_buf(Arc::new(pages), bound, window.size, start); let made = self.pages_of( buffer.raw, placement, @@ -860,33 +1132,36 @@ impl Device { } /// The `VkBuffer` of a no-copy buffer of `length` bytes over `window`'s pages from their - /// first byte, its bytes `window.offset` bytes into it whatever the chunks, made for - /// dma-bufs, each of `chunks` imported (noted in `pages`) as memory of `class` and bound at - /// its offset from the window's start: one chunk by `vkBindBufferMemory` to a plain buffer, - /// several by a sparse binding of a `SPARSE_BINDING` one (`Device::bind_sparse_buffer`, noted - /// in `pages`). The buffer, its one import (`VK_NULL_HANDLE` for several) and the first - /// import's type. Each import is dedicated to nothing; where `sole` (the caller binds no - /// other resource in the import, ever) and the buffer is a plain one, an import the driver - /// refuses so is made dedicated to the buffer (`memory.rs`'s `DmaBufFor::Buffer`). Refused, - /// the buffer released, where the bytes padded to 16 run past the chunks, the buffer's memory - /// does not fit them or its alignment misses their boundaries, a chunk's types take none of - /// the class's the buffer takes, the driver refuses a chunk, or the binding fails. + /// first byte, its bytes `window.offset` bytes into it whatever the pieces, made for + /// dma-bufs, each of `pieces` imported or joined (held in `pages`) as memory of `class` and + /// bound at its offset from the window's start, from its offset in its import: one piece by + /// `vkBindBufferMemory` to a plain buffer, several by a sparse binding of a `SPARSE_BINDING` + /// one (`Device::bind_sparse_buffer`, noted in `pages`). The buffer and where it is bound + /// ([`BoundIn`]). A dma-buf of its own is imported dedicated to nothing; where `sole` (the + /// caller binds no other resource in its import, ever) and the buffer is a plain one, an + /// import the driver refuses so is made dedicated to the buffer (`memory.rs`'s + /// `DmaBufFor::Buffer`). A piece of a shared file lies in the device's one import of the file + /// ([`Device::file_import`]), never dedicated: where the driver refuses that, the buffer is + /// refused as for a refused chunk. Refused, the buffer released, where the bytes padded to 16 + /// run past the pieces, the buffer's memory does not fit them or its alignment misses their + /// boundaries or offsets, a piece's types take none of the class's the buffer takes, the + /// driver refuses a piece, or the binding fails. /// /// # Safety /// - /// As [`Device::import_from_source`]'s; `chunks` meet [`chunks_cover`]. + /// As [`Device::import_from_source`]'s; `pieces` meet [`chunks_cover`]. unsafe fn chunks_buffer( &self, importer: &Importer, - chunks: Vec, + pieces: Vec, pages: &mut DmaBufPages, length: u64, window: &ImportWindow, (class, sole): (MemoryClass, bool), - ) -> Result<(HostBuffer, vk::DeviceMemory, u32), Error> { + ) -> Result<(HostBuffer, BoundIn), Error> { let shared = self.shared(); let raw_device = shared.vk(); - let lengths: Vec = chunks.iter().map(|chunk| chunk.length).collect(); + let lengths: Vec = pieces.iter().map(Piece::length).collect(); let size: u64 = lengths.iter().sum(); // A range the binding layer pads to 16 bytes from the bytes stays inside the buffer, as // a pointer's import holds it (`based_size`). @@ -914,59 +1189,69 @@ impl Device { let requirements = unsafe { raw_device.get_buffer_memory_requirements(raw) }; let bound = (|| { let alignment = requirements.alignment.max(1); + // Each piece binds at its offset in its import, which the alignment must divide + // (the request's alignment holds it: Vulkan keeps a buffer's alignment the same for + // every buffer of its usage and flags). + let aligned = (pieces.iter()).all(|piece| piece.offset().is_multiple_of(alignment)); let fits = match sparse { - // Each chunk binds whole at its offset, which the alignment must divide, as it - // must divide each chunk's length. + // Each piece binds whole at its offset in the buffer, which the alignment must + // divide, as it must divide each piece's length. true => lengths .iter() .all(|length| length.is_multiple_of(alignment)), false => requirements.size <= size, }; - if !fits { + if !aligned || !fits { return Err(not_importable()); } - // A plain buffer bound at the import's start, its requirements' size within it. + // A plain buffer bound at its piece's offset, its requirements' size within it. let dedicated_to = (sole && !sparse).then_some(raw); let memories = self.import_chunks( importer, - chunks, + pieces, pages, &requirements, (class, dedicated_to), )?; if !sparse { + let one = memories[0]; // SAFETY: the buffer is unbound, made for dma-bufs; the memory is of a type it - // takes and holds its requirements from 0. - unsafe { crate::creation::bind_buffer(raw_device, raw, memories[0].0, 0) } + // takes and holds its requirements from the piece's offset, a multiple of their + // alignment. + unsafe { crate::creation::bind_buffer(raw_device, raw, one.memory, one.offset) } .map_err(vulkan)?; - return Ok(memories[0]); + return Ok(one); } let mut offset = 0; let binds: Vec = (memories.iter().zip(&lengths)) - .map(|(&(memory, _), &length)| { + .map(|(at, &length)| { let bind = vk::SparseMemoryBind::default() .resource_offset(offset) .size(length) - .memory(memory) - .memory_offset(0); + .memory(at.memory) + .memory_offset(at.offset); offset += length; bind }) .collect(); pages.bound = Some(self.bind_sparse_buffer(raw, &binds)?); - Ok((vk::DeviceMemory::null(), memories[0].1)) + Ok(BoundIn { + memory: vk::DeviceMemory::null(), + offset: 0, + type_index: memories[0].type_index, + }) })(); match bound { // The bytes lie `window.offset` bytes into the buffer, which is bound from the // window's first byte; it holds the pages, and its padding past them is no one's. - Ok((memory, type_index)) => { + Ok(bound) => { let buffer = HostBuffer { raw, base: window.offset, size: window.size, requirements, }; - Ok((buffer, memory, type_index)) + Ok((buffer, bound)) } Err(error) => { // SAFETY: no command uses the buffer; a failed binding left nothing pending. @@ -976,25 +1261,39 @@ impl Device { } } - /// Each of `chunks` imported as memory of `class` of a type both it and a buffer of - /// `requirements` take, in order, noted in `pages` (which frees them), with its type: where - /// `dedicated_to` names the buffer (one chunk, its import the buffer's alone), dedicated to it - /// where the driver refuses the import dedicated to nothing, counted - /// (`WorkCounts::dma_buf_buffer_imports_dedicated`). Refused (`Unsupported`, `HostMemory`) - /// where a chunk's types take none of the class's the buffer takes, or the driver refuses it; - /// the descriptors not yet imported are closed then. + /// Each of `pieces`, in order, as memory of `class` of a type both it and a buffer of + /// `requirements` take, held in `pages` (which frees or lets go of them), with its type and + /// its offset there: a dma-buf of its own imported, where `dedicated_to` names the buffer + /// (one piece, its import the buffer's alone), dedicated to it where the driver refuses the + /// import dedicated to nothing, counted (`WorkCounts::dma_buf_buffer_imports_dedicated`); a + /// piece of a shared file in the device's import of the file ([`Device::file_import`]). + /// Refused (`Unsupported`, `HostMemory`) where a piece's types take none of the class's the + /// buffer takes, or the driver refuses it; the descriptors not yet imported are closed then. fn import_chunks( &self, importer: &Importer, - chunks: Vec, + pieces: Vec, pages: &mut DmaBufPages, requirements: &vk::MemoryRequirements, (class, dedicated_to): (MemoryClass, Option), - ) -> Result, Error> { + ) -> Result, Error> { let shared = self.shared(); let raw_device = shared.vk(); - let mut imported = Vec::with_capacity(chunks.len()); - for DmaBufChunk { fd, length } in chunks { + let mut imported = Vec::with_capacity(pieces.len()); + for piece in pieces { + let (fd, length) = match piece { + Piece::Own { fd, length } => (fd, length), + Piece::Shared { file, offset, .. } => { + let (memory, type_index) = + self.file_import(importer, &file, pages, requirements, class)?; + imported.push(BoundIn { + memory, + offset, + type_index, + }); + continue; + } + }; // SAFETY: the importer is this device's, and the descriptor a dma-buf. let types = unsafe { importer.dma_buf_types(raw_device, fd.as_fd()) } .map_err(import_refused)?; @@ -1003,7 +1302,7 @@ impl Device { let made = memory::import_dma_buf( &shared.memory, raw_device, - fd, + fd.as_fd(), length, (allowed, class), purpose, @@ -1016,11 +1315,104 @@ impl Device { shared.counts.dma_buf_buffer_import_dedicated(); } pages.hold(memory); - imported.push((memory, type_index)); + imported.push(BoundIn { + memory, + offset: 0, + type_index, + }); } Ok(imported) } + /// The device's import of the shared dma-buf `file`, held in `pages` (which lets go of it), + /// and its memory type, which a buffer of `requirements` takes: the live one, joined + /// (`WorkCounts::dma_buf_pieces_joined`), or else a new import of the whole dma-buf, + /// dedicated to nothing, as memory of `class` of a type both it and the buffer take, made with + /// no lock held and entered in the device's map ([`DmaBufFiles`]), counted live + /// (`WorkCounts::dma_buf_shared_imports_live`); where another thread entered one of the same + /// file meanwhile, that one is joined and this one freed. The driver takes a duplicate of the + /// file's descriptor, the `Arc`'s staying open while the import holds it. Refused (`Unsupported`, + /// `HostMemory`) where the live import's type is none the buffer takes, the file's types take + /// none of the class's the buffer takes, or the driver refuses it (dedicated to nothing: a + /// shared file's import is never dedicated, as several buffers bind in it). + fn file_import( + &self, + importer: &Importer, + file: &Arc, + pages: &mut DmaBufPages, + requirements: &vk::MemoryRequirements, + class: MemoryClass, + ) -> Result<(vk::DeviceMemory, u32), Error> { + let shared = self.shared(); + let raw_device = shared.vk(); + let join = |pages: &mut DmaBufPages, live: Arc| { + let at = (live.memory, live.type_index); + pages.files.push(live); + if requirements.memory_type_bits & (1 << at.1) == 0 { + return Err(not_importable()); + } + shared.counts.dma_buf_piece_joined(); + Ok(at) + }; + if let Some(live) = shared.dma_buf_files.live(file) { + return join(pages, live); + } + let size = dma_buf_length(file.as_fd()).ok_or_else(not_importable)?; + // SAFETY: the importer is this device's, and the descriptor a dma-buf. + let types = + unsafe { importer.dma_buf_types(raw_device, file.as_fd()) }.map_err(import_refused)?; + let allowed = types & requirements.memory_type_bits; + let made = memory::import_dma_buf( + &shared.memory, + raw_device, + file.as_fd(), + size, + (allowed, class), + DmaBufFor::Shared, + ); + let (memory, type_index, _) = made.map_err(|failure| match failure { + ImportFailure::NoMemoryType => not_importable(), + ImportFailure::Vulkan(error) => import_refused(error), + })?; + let made = DmaBufFile { + file: Arc::clone(file), + memory, + type_index, + }; + match shared.dma_buf_files.enter(made) { + Ok(entered) => { + pages.files.push(entered); + pages.made += 1; + shared.counts.dma_buf_memory_imported(false); + shared.counts.dma_buf_shared_import_made(); + Ok((memory, type_index)) + } + Err((live, made)) => { + // SAFETY: nothing is bound to the import, made just now, and no command uses it. + unsafe { release::object(raw_device, made.memory) }; + join(pages, live) + } + } + } + + /// The multiple of which every chunk's offset in its file lies for a buffer's request of + /// `length` bytes split at `granule` ([`DmaBufRequest::alignment`]): the host page, or the + /// memory alignment of a plain buffer made for dma-bufs where that is larger (asked once, + /// [`Importer::dma_buf_alignment`]), or the granule where the request may be split (each + /// chunk then binds a sparse buffer, whose alignment the granule is a multiple of). Each a + /// power of two, so the largest is a multiple of the others. + fn chunk_alignment(&self, importer: &Importer, granule: u64, length: u64) -> u64 { + let plain = *importer.dma_buf_alignment.get_or_init(|| { + self.dma_buf_buffer_requirements(importer.page, vk::BufferCreateFlags::empty()) + .map(|requirements| requirements.alignment) + }); + let alignment = importer.page.max(plain.unwrap_or(1)); + match granule < length { + true => alignment.max(granule), + false => alignment, + } + } + /// The granule a dma-buf source's chunks split at, where the device assembles a buffer of /// several: it has `sparseBinding`, its queue family binds sparse memory, it imports /// dma-bufs for a sparse buffer without a dedicated allocation, and such a buffer takes every @@ -1126,6 +1518,16 @@ impl Device { } } +/// Where a buffer over dma-buf pages is bound ([`Device::chunks_buffer`]): its one import and +/// its offset there (`VK_NULL_HANDLE` and 0 for a sparse buffer over several), and the memory +/// type of its first import. +#[derive(Clone, Copy, Debug)] +pub(super) struct BoundIn { + pub(super) memory: vk::DeviceMemory, + pub(super) offset: u64, + pub(super) type_index: u32, +} + /// `DRM_FORMAT_MOD_LINEAR` of Linux's `drm_fourcc.h`: one plane of rows one after another, each /// the plane's pitch from the last. pub(super) const DRM_FORMAT_MOD_LINEAR: u64 = 0; @@ -1423,6 +1825,8 @@ impl Device { start, length, granule: length, + alignment: page, + shared_files: false, }, bound_at, })) @@ -1720,7 +2124,7 @@ impl Device { let imported = memory::import_dma_buf( &shared.memory, raw_device, - fd, + fd.as_fd(), requirements.size, allowed, DmaBufFor::Image(raw), @@ -1807,16 +2211,19 @@ impl Device { ) } }; - // A request whose granule is its length takes one chunk (`chunks_cover`). - let answered = answers(&chunks, &request, importer.page); - let (true, Ok([chunk])) = (answered, <[DmaBufChunk; 1]>::try_from(chunks)) else { + // A request whose granule is its length takes one chunk (`chunks_cover`), a dma-buf of + // its own (the request takes no shared file: the import is the image's dedicated one). + let answered = taken(chunks, &request, importer.page).map(<[Piece; 1]>::try_from); + let Some(Ok([Piece::Own { fd, .. }])) = answered else { return refuse( DmaBufRefusal::Source, - "the caller's source answered other than one dma-buf of the pages asked".to_owned(), + "the caller's source answered other than one dma-buf of its own of the pages \ + asked" + .to_owned(), ); }; // SAFETY: the importer is this device's, and the descriptor a dma-buf. - let types = match unsafe { importer.dma_buf_types(raw_device, chunk.fd.as_fd()) } { + let types = match unsafe { importer.dma_buf_types(raw_device, fd.as_fd()) } { Ok(types) => types, Err(error) => { let why = format!("the driver refuses the dma-buf ({error:?})"); @@ -1832,8 +2239,14 @@ impl Device { None => (requirements.size, DmaBufFor::Image(raw)), Some(_) => (request.length, DmaBufFor::Shared), }; - let imported = - memory::import_dma_buf(&shared.memory, raw_device, chunk.fd, size, allowed, purpose); + let imported = memory::import_dma_buf( + &shared.memory, + raw_device, + fd.as_fd(), + size, + allowed, + purpose, + ); let memory = match imported { Ok((memory, _, _)) => memory, Err(ImportFailure::NoMemoryType) => { @@ -2492,7 +2905,8 @@ impl ExportedPages { } /// A source of dma-bufs of the pages: each request over them from their first byte, of at - /// most their length, answered with one chunk of their dma-buf. + /// most their length, answered with one chunk of their dma-buf, a duplicate of its descriptor + /// of its own. pub(super) fn source(&self) -> DmaBufSource { let start = self.start.as_ptr() as u64; let length = self.length; @@ -2507,7 +2921,8 @@ impl ExportedPages { )); } Ok(vec![DmaBufChunk { - fd: fd.try_clone()?, + file: Arc::new(fd.try_clone()?), + offset: 0, length: request.length, }]) }) diff --git a/crates/metal2vulkan-runtime/src/host_memory.rs b/crates/metal2vulkan-runtime/src/host_memory.rs index 6f680cbd5..936d61d5f 100644 --- a/crates/metal2vulkan-runtime/src/host_memory.rs +++ b/crates/metal2vulkan-runtime/src/host_memory.rs @@ -332,12 +332,28 @@ impl HostMemory { /// (a `granule` of the request's `length`), and pages that one dma-buf cannot hold (more runs /// than one `udmabuf` takes) are refused. /// + /// The chunks may be pieces of files the source shares among the buffers and heaps it answers + /// (`DmaBufChunk`: the same `Arc`, an offset in the file that is a multiple of the request's + /// `alignment`): the device imports each such file once, whole, and binds each buffer at its + /// piece's offset there, so RADV, which lists every import in every kernel submission, lists + /// one per file (`WorkCounts::dma_buf_pieces_joined`, `dma_buf_shared_imports_live`). The + /// file's import lives while any buffer or heap bound in it does (and the command buffers that + /// hold them), and goes with the last; a buffer's deallocator and keep-alive wait for its own + /// binding's end, not for the file's import, which no command reaches the buffer's bytes + /// through once it went. A shared file's import is never dedicated to a buffer: where the + /// driver takes the file only dedicated (NVIDIA's 615.71.09 refuses small dma-bufs otherwise), + /// the buffer is a copy of the pages as for a refused chunk, and the source is not asked + /// again; answer such a device's requests with dma-bufs of their own. A request whose + /// `shared_files` is `false` (a texture's image) takes one dma-buf of its own at offset 0. + /// /// A no-copy buffer's own import of the chunks (not a heap's or a rebind's) may be released /// while idle, or past the 64 the device keeps resident, 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. A buffer whose + /// each dma-buf of its own, within a quarter of the process's `RLIMIT_NOFILE` soft limit, and + /// the `Arc` of each shared file, which opens none (the file's import goes once every buffer + /// bound in it went or was released). The next blit imports them again (or joins the file's + /// live import), 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 @@ -1187,6 +1203,11 @@ pub(super) struct Importer { /// the first time a pointer is refused and a source called; `None` where the device makes no /// such buffer. pub(super) sparse_granule: std::sync::OnceLock>, + /// The memory alignment of a plain buffer made for dma-bufs, which Vulkan keeps the same for + /// every buffer of the same usage and flags: what a chunk's offset in its file is a multiple + /// of (`dma_buf.rs`'s `DmaBufRequest::alignment`). Asked once, as the granule is; `None` + /// where the driver makes no such buffer. + pub(super) dma_buf_alignment: std::sync::OnceLock>, } /// A device's import of host memory by its pointer (`VK_EXT_external_memory_host`). A clone is the @@ -1250,6 +1271,7 @@ impl Importer { dma_buf, dma_buf_images, sparse_granule: std::sync::OnceLock::new(), + dma_buf_alignment: std::sync::OnceLock::new(), }) } diff --git a/crates/metal2vulkan-runtime/src/host_ram.rs b/crates/metal2vulkan-runtime/src/host_ram.rs index 736581731..cccf92aac 100644 --- a/crates/metal2vulkan-runtime/src/host_ram.rs +++ b/crates/metal2vulkan-runtime/src/host_ram.rs @@ -300,8 +300,9 @@ impl HostRam { /// [`HostRam::with_largest_dma_buf`] allows where the device's held imports add to the cost of /// every submission, or the rest of its range; an object's run inside one; a copy's range /// inside one, but in lists of the source of [`HostRam::with_dma_buf_of_runs`] where it - /// takes those; a texture's pages inside one), its `granule` its `length`: the source answers - /// one dma-buf of exactly those pages. The source is called on the thread importing the chunk + /// takes those; a texture's pages inside one), its `granule` its `length`, its + /// `shared_files` `false`: the source answers one dma-buf of its own of exactly those pages + /// (a `DmaBufChunk` at offset 0 whose `Arc` it keeps no clone of). The source is called on the thread importing the chunk /// (the device's, or one making an object over it), with no lock of the runtime's held, and /// is kept with each import it made until that import is freed. A source that fails, or /// answers otherwise, leaves the chunk to its pointer. No Metal counterpart. diff --git a/crates/metal2vulkan-runtime/src/host_residency.rs b/crates/metal2vulkan-runtime/src/host_residency.rs index 4090b452a..d956e8fc4 100644 --- a/crates/metal2vulkan-runtime/src/host_residency.rs +++ b/crates/metal2vulkan-runtime/src/host_residency.rs @@ -18,9 +18,13 @@ //! - **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; +//! pointer), where the device kept a descriptor of each dma-buf of its own within the +//! descriptors the process's devices keep at most ([`kept_fds_limit`]), and the `Arc` of each +//! shared file its other pieces lie in, which opens no descriptor; an import past them is +//! made as any other and stays imported. A piece of a shared file lies in the device's one +//! import of the file, which the buffers and heaps bound in it hold: a release lets go of the +//! buffer's hold, and the import is freed only with the last, so it leaves the submissions' +//! list only once every buffer in it went or was released; //! - 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 @@ -122,13 +126,12 @@ use super::buffer::{FixedPages, HostImport, Imported, Pages, Shape}; use super::device::lock; -use super::dma_buf::{DmaBufRequest, DmaBufSource}; +use super::dma_buf::{DmaBufRequest, DmaBufSource, Piece}; use super::error::{internal, Error}; use super::exit_guard; use super::host_memory::ImportWindow; use super::memory::MemoryClass; use super::Device; -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}; @@ -204,11 +207,12 @@ pub(super) struct Again { /// 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. + /// The pieces its source made, in order: a duplicate of the descriptor of each dma-buf of its + /// own the device imported, and a clone of each shared file's `Arc` with its piece's place + /// (`dma_buf.rs`'s `Piece::again`). 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)>, + chunks: Vec, source: DmaBufSource, request: DmaBufRequest, }, @@ -225,18 +229,19 @@ pub(super) struct ImportedAt(pub(super) NonNull); 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. + /// `chunks` kept, their descriptors of their own 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. A shared + /// file's `Arc` opens no descriptor and counts none. pub(super) fn dma_bufs( device: &Device, - chunks: Vec<(OwnedFd, u64)>, + chunks: Vec, source: DmaBufSource, request: DmaBufRequest, (length, window, class): (u64, ImportWindow, MemoryClass), ) -> Option { let shared = device.shared(); - let count = chunks.len() as u64; + let count = own_descriptors(&chunks); let cap = shared.residency.shared.fds_cap.load(Ordering::Relaxed); if !shared.counts.host_import_fds_keep(count, cap) { return None; @@ -283,12 +288,17 @@ impl Drop for Again { let AgainFrom::DmaBufs { chunks, .. } = &self.from else { return; }; - let count = chunks.len() as u64; + let count = own_descriptors(chunks); self.device.shared().counts.host_import_fds_closed(count); KEPT_FDS.fetch_sub(count, Ordering::AcqRel); } } +/// The descriptors of their own `pieces` hold: one per dma-buf of its own. +fn own_descriptors(pieces: &[Piece]) -> u64 { + pieces.iter().filter(|piece| piece.own()).count() as u64 +} + /// A releasable import's residency (the module docs). pub(super) struct Residency { device: Device, diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs index a33781514..f298a4e34 100644 --- a/crates/metal2vulkan-runtime/src/memory.rs +++ b/crates/metal2vulkan-runtime/src/memory.rs @@ -2114,26 +2114,25 @@ impl Placement { } /// The placement of a no-copy buffer's `size` bytes of host pages in the imports of the - /// caller's dma-bufs of them, `pages`: at offset 0 of `memory`, of type `type_index`, where - /// they are one import, or no memory (`VK_NULL_HANDLE`) where they are several bound to a - /// sparse buffer; their host address is `mapped`, the pages' pointer (the runtime never maps - /// a dma-buf). No block of the runtime's, so freeing it returns nothing; it keeps the imports - /// until it goes. + /// caller's dma-bufs of them, `pages`, bound as `bound` says: at its offset of its memory (0 + /// of a dma-buf of its own, the piece's offset of a shared file's import), where they are one + /// import, or no memory (`VK_NULL_HANDLE`) where they are several bound to a sparse buffer; + /// their host address is `mapped`, the pages' pointer (the runtime never maps a dma-buf). No + /// block of the runtime's, so freeing it returns nothing; it keeps the imports until it goes. #[cfg(unix)] pub(super) fn dma_buf( pages: Arc, - memory: vk::DeviceMemory, - type_index: u32, + bound: crate::dma_buf::BoundIn, size: u64, mapped: NonNull, ) -> Placement { Placement { - type_index, + type_index: bound.type_index, holds: Holds::Buffers, block: None, size, - memory, - offset: 0, + memory: bound.memory, + offset: bound.offset, mapped: Some(Mapped(mapped)), address: None, own_pages: false, @@ -4835,17 +4834,17 @@ pub(super) enum DmaBufFor { /// (620.70.06, measured), and a second close of a number the kernel gave another thread's /// descriptor meanwhile closes that one. At its own number, the clone's closes reach nothing /// else, and once a failed import returns it is closed where the driver left it open. `fd` -/// itself is closed here as it always was, once, on the way out. +/// itself stays the caller's, open: a dma-buf of its own the caller closes once the import +/// returns, and a shared file's descriptor stays with its `Arc` (`dma_buf.rs`'s `DmaBufFile`). #[cfg(unix)] pub(super) fn import_dma_buf( memory: &Mutex, device: &ash::Device, - fd: std::os::fd::OwnedFd, + fd: std::os::fd::BorrowedFd<'_>, size: u64, (allowed, class): (u32, MemoryClass), purpose: DmaBufFor, ) -> Result<(vk::DeviceMemory, u32, bool), ImportFailure> { - use std::os::fd::AsFd; let kind = (std::mem::discriminant(&purpose), class); // The forms of the import, each tried in every type: a buffer's memory dedicated to nothing // first, then to the buffer. @@ -4899,7 +4898,7 @@ pub(super) fn import_dma_buf( }; // The descriptor the driver takes, which it owns once the import succeeds and may // close even when it fails (the doc above): never `fd`. - let handed = match Handed::of(fd.as_fd()) { + let handed = match Handed::of(fd) { Ok(handed) => handed, Err(_) => { failure = ImportFailure::Vulkan(vk::Result::ERROR_TOO_MANY_OBJECTS); diff --git a/crates/metal2vulkan-runtime/src/tests/copied.rs b/crates/metal2vulkan-runtime/src/tests/copied.rs index f72c4bdeb..99c72c0f9 100644 --- a/crates/metal2vulkan-runtime/src/tests/copied.rs +++ b/crates/metal2vulkan-runtime/src/tests/copied.rs @@ -1130,7 +1130,8 @@ impl DmaBufMapping { return Err(std::io::Error::other("not the mapping's pages")); } Ok(vec![crate::DmaBufChunk { - fd: dma_buf.try_clone()?, + file: Arc::new(dma_buf.try_clone()?), + offset: 0, length, }]) }) diff --git a/crates/metal2vulkan-runtime/src/tests/copied_device.rs b/crates/metal2vulkan-runtime/src/tests/copied_device.rs index c89ff7ffb..3bc9fc83a 100644 --- a/crates/metal2vulkan-runtime/src/tests/copied_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/copied_device.rs @@ -2288,7 +2288,12 @@ impl ReadOnlyHost { .checked_sub(base) .ok_or_else(|| std::io::Error::other("pages before the view"))?; Ok(vec![crate::DmaBufChunk { - fd: super::host_residency::udmabuf(&fd, offset as u64, request.length)?, + file: Arc::new(super::host_residency::udmabuf( + &fd, + offset as u64, + request.length, + )?), + offset: 0, length: request.length, }]) }); diff --git a/crates/metal2vulkan-runtime/src/tests/dma_buf_first_imports.rs b/crates/metal2vulkan-runtime/src/tests/dma_buf_first_imports.rs index 0d27fdb3d..eabe73c56 100644 --- a/crates/metal2vulkan-runtime/src/tests/dma_buf_first_imports.rs +++ b/crates/metal2vulkan-runtime/src/tests/dma_buf_first_imports.rs @@ -76,7 +76,7 @@ fn imports_at_once(memory: &Mutex, most: &AtomicUsize) -> usize { let imported = import_dma_buf( memory, &device, - fd, + std::os::fd::AsFd::as_fd(&fd), 4096, (1, MemoryClass::Shared), DmaBufFor::Shared, diff --git a/crates/metal2vulkan-runtime/src/tests/dma_buf_import_cycles.rs b/crates/metal2vulkan-runtime/src/tests/dma_buf_import_cycles.rs index 18ce3fae6..f61d849b7 100644 --- a/crates/metal2vulkan-runtime/src/tests/dma_buf_import_cycles.rs +++ b/crates/metal2vulkan-runtime/src/tests/dma_buf_import_cycles.rs @@ -155,7 +155,8 @@ impl Pages { let chunks = (0..count) .map(|index| { Ok(DmaBufChunk { - fd: udmabuf(&fd, at + index * each, each)?, + file: Arc::new(udmabuf(&fd, at + index * each, each)?), + offset: 0, length: each, }) }) diff --git a/crates/metal2vulkan-runtime/src/tests/dma_buf_leak_probe.rs b/crates/metal2vulkan-runtime/src/tests/dma_buf_leak_probe.rs index f64ce6831..5c90e8e4c 100644 --- a/crates/metal2vulkan-runtime/src/tests/dma_buf_leak_probe.rs +++ b/crates/metal2vulkan-runtime/src/tests/dma_buf_leak_probe.rs @@ -561,7 +561,8 @@ impl Probe { } } Ok(vec![DmaBufChunk { - fd: chunk, + file: Arc::new(chunk), + offset: 0, length: request.length, }]) }); diff --git a/crates/metal2vulkan-runtime/src/tests/dma_buf_pieces.rs b/crates/metal2vulkan-runtime/src/tests/dma_buf_pieces.rs new file mode 100644 index 000000000..d618412fc --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/dma_buf_pieces.rs @@ -0,0 +1,92 @@ +//! How the runtime takes a dma-buf source's chunks (`dma_buf.rs`'s `Piece`) and keeps one import +//! of each shared file (`DmaBufFiles`), with no device: a chunk is a dma-buf of its own only at +//! offset 0 with the runtime its `Arc`'s only holder; a file is known by its `Arc` alone, never by +//! its descriptor's file; the map hands out holds of a live import, takes a second import of the +//! same file made meanwhile back to its maker, and gives an import back to free only with its last +//! hold, removing its entry then. + +use crate::dma_buf::{DmaBufFile, DmaBufFiles, Piece}; +use crate::DmaBufChunk; +use std::os::fd::{AsRawFd, OwnedFd}; +use std::sync::Arc; + +/// A descriptor of `/dev/null`, standing in for a dma-buf: nothing here reads it. +fn descriptor() -> OwnedFd { + OwnedFd::from(std::fs::File::open("/dev/null").unwrap()) +} + +/// A chunk at offset 0 whose `Arc` the runtime alone holds is a dma-buf of its own; one whose +/// `Arc` the source still holds, or at an offset, is a piece of a shared file, the same `Arc`. +/// Again, one of its own is a new descriptor, a shared one the same file. +#[test] +fn a_chunk_is_its_own_dma_buf_only_alone_at_offset_0() { + let length = 1 << 16; + let own = Piece::of(DmaBufChunk { + file: Arc::new(descriptor()), + offset: 0, + length, + }); + assert!(own.own(), "{own:?}"); + let shared = Arc::new(descriptor()); + let piece = Piece::of(DmaBufChunk { + file: Arc::clone(&shared), + offset: 0, + length, + }); + let Piece::Shared { + file, offset: 0, .. + } = &piece + else { + panic!("a chunk of a file the source holds: {piece:?}"); + }; + assert!(Arc::ptr_eq(file, &shared)); + let at = Piece::of(DmaBufChunk { + file: Arc::new(descriptor()), + offset: 1 << 16, + length, + }); + assert!( + matches!(at, Piece::Shared { offset, .. } if offset == 1 << 16), + "a chunk at an offset: {at:?}" + ); + let (Piece::Own { fd, .. }, Ok(Piece::Own { fd: again, .. })) = (&own, own.again()) else { + panic!("a dma-buf of its own again"); + }; + assert_ne!(fd.as_raw_fd(), again.as_raw_fd(), "a new descriptor"); + let Ok(Piece::Shared { file: again, .. }) = piece.again() else { + panic!("a shared piece again"); + }; + assert!(Arc::ptr_eq(&again, &shared), "the same file, no descriptor"); +} + +/// The map's holds of one file's import: the entered import is the live one; a second import of +/// the same file made meanwhile goes back to its maker with a hold of the live one; a duplicate +/// descriptor in another `Arc` is another file; letting go of every hold but the last frees +/// nothing, and the last gives the import back, its entry gone, so the file is imported anew. +#[test] +fn a_shared_file_is_one_import_until_its_last_hold_goes() { + let files = DmaBufFiles::default(); + let file = Arc::new(descriptor()); + let first = files + .enter(DmaBufFile::stand_in(Arc::clone(&file))) + .unwrap(); + let joined = files.live(&file).expect("the entered import is live"); + assert!(Arc::ptr_eq(&first, &joined)); + let raced = files.enter(DmaBufFile::stand_in(Arc::clone(&file))); + let Err((live, _made)) = raced else { + panic!("a second import of a live file was entered"); + }; + assert!(Arc::ptr_eq(&live, &first)); + let other = Arc::new(file.try_clone().unwrap()); + assert!( + files.live(&other).is_none(), + "a duplicate descriptor in another Arc is another file" + ); + assert!(files.let_go([first, joined].into_iter()).is_empty()); + assert!(files.live(&file).is_some(), "one hold left"); + let last = files.let_go(std::iter::once(live)); + assert_eq!(last.len(), 1, "the last hold gives the import back"); + assert!(files.live(&file).is_none(), "its entry gone"); + let again = files.enter(DmaBufFile::stand_in(Arc::clone(&file))); + assert!(again.is_ok(), "the file imported anew"); +} diff --git a/crates/metal2vulkan-runtime/src/tests/dma_buf_shared_files.rs b/crates/metal2vulkan-runtime/src/tests/dma_buf_shared_files.rs new file mode 100644 index 000000000..655fc148f --- /dev/null +++ b/crates/metal2vulkan-runtime/src/tests/dma_buf_shared_files.rs @@ -0,0 +1,473 @@ +//! No-copy buffers over pieces of shared dma-bufs (`dma_buf.rs`'s `DmaBufFiles`), on the device +//! the cfg selects made without `VK_EXT_external_memory_host` (`tests/no_pointer_import.rs`), so +//! that every device that lists the dma-buf route takes it. The memory is guest RAM as QEMU makes +//! it: a sealed `memfd` mapped shared, whose view maps the file from its first byte; the shared +//! file is one `udmabuf` of the file's pages, whose pieces a source hands each buffer (the same +//! `Arc`, the source holding its own clone), as a consumer groups its guest's buffers. +//! +//! - **One import.** Four buffers over pieces of one file: one import of the file +//! (`WorkCounts::dma_buf_imports`), the three others joined to it (`dma_buf_pieces_joined`), +//! one shared import live (`dma_buf_shared_imports_live`, within `dma_buf_memories_live`). Each +//! buffer's GPU reads are its own piece's bytes, its GPU fill lands in its piece's pages and no +//! other's, and the CPU's later writes to the file reach its next read. The import lives while +//! any of the buffers does, and goes with the last. +//! - **Its negative control.** The same buffers whose source answers a dma-buf of its own for +//! each: one import each, none joined, no shared import. +//! - **Several pieces.** A buffer longer than the device's sparse granule, answered with two +//! pieces of one file laid in it in the other order: each bound at its offset in the one +//! import (its second piece joined), the buffer's bytes in order. Where the device binds no +//! buffer in several pieces (the request's granule is its length) the line says so and one +//! piece is answered. +//! - **Released and imported again.** Two buffers over pieces of one file, read by blits, their +//! imports released while idle (`Device::release_idle_host_imports`): the file's import goes +//! with the second release; the next blit of each makes the import again and joins it, its +//! bytes the file's. +//! - **Misuse.** A piece whose offset in its file misses the request's alignment is refused +//! (`Invalid`, `Problem::DmaBuf`), nothing imported. +//! +//! Each prints one line (`DMA-BUF-SHARED`) with the counts it checks. A device test: compiled only +//! under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`), on Linux. Where `/dev/udmabuf` cannot be +//! opened, or the device lists no dma-buf route, it says so and passes without running. + +use super::host_residency::{ + counting, counts_once, gpu_fill, host_page, read, release, udmabuf, udmabuf_list, + udmabuf_openable, Ram, Scratch, +}; +use super::no_pointer_import::{device, lists_dma_buf_route}; +use crate::{ + Buffer, Device, DmaBufChunk, DmaBufRequest, DmaBufSource, Error, HostMemory, Invalid, Problem, + ResourceOptions, WorkCounts, +}; +use std::os::fd::OwnedFd; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; + +const TEST: &str = "DMA-BUF-SHARED"; + +/// The buffers over pieces of one file. +const BUFFERS: usize = 4; + +/// The device of these tests, with its shader cache's scratch directory; `None`, said, where +/// `/dev/udmabuf` cannot be opened or the device lists no dma-buf route. +fn on_device(test: &str) -> Option<(Scratch, Device)> { + if !udmabuf_openable(test) { + return None; + } + let scratch = Scratch::new(); + let device = device(&scratch.0, None); + if !lists_dma_buf_route(&device) { + eprintln!("{test}: {} lists no dma-buf route: not run", device.name()); + return None; + } + Some((scratch, device)) +} + +/// A source that answers each request with one piece of `file`, a dma-buf of `ram`'s file from +/// its first byte, at the request's offset in the view (which maps the file from its first byte) +/// plus `skew`, keeping the largest alignment asked in `alignment`. +fn shared_source( + ram: &Ram, + file: &Arc, + skew: u64, + alignment: &Arc, +) -> DmaBufSource { + let base = ram.pointer(0).as_ptr() as u64; + let file = Arc::clone(file); + let alignment = Arc::clone(alignment); + Arc::new(move |request: DmaBufRequest| { + alignment.fetch_max(request.alignment, Ordering::AcqRel); + let at = (request.start.as_ptr() as u64) + .checked_sub(base) + .ok_or_else(|| std::io::Error::other("pages before the view"))?; + Ok(vec![DmaBufChunk { + file: Arc::clone(&file), + offset: at + skew, + length: request.length, + }]) + }) +} + +/// A no-copy buffer of `length` bytes over `ram`'s view from `offset`, of `source`'s dma-bufs. +fn no_copy( + device: &Device, + ram: &Ram, + (offset, length): (usize, usize), + source: DmaBufSource, +) -> Result { + // SAFETY: each test's view outlives its buffers, and the source makes dma-bufs of its pages. + unsafe { + device.new_buffer_with_bytes_no_copy( + HostMemory::with_dma_buf(ram.pointer(offset), source), + length as u64, + ResourceOptions::default(), + None, + ) + } +} + +/// The dma-buf counts of `after` since `before`: imports made, pieces joined, the change of the +/// shared imports live and of the dma-buf memories live. +fn moved(before: &WorkCounts, after: &WorkCounts) -> (u64, u64, i64, i64) { + let live = |counts: &WorkCounts| { + ( + counts.dma_buf_shared_imports_live as i64, + counts.dma_buf_memories_live as i64, + ) + }; + let (shared_before, memories_before) = live(before); + let (shared_after, memories_after) = live(after); + ( + after.dma_buf_imports - before.dma_buf_imports, + after.dma_buf_pieces_joined - before.dma_buf_pieces_joined, + shared_after - shared_before, + memories_after - memories_before, + ) +} + +/// Four buffers over pieces of one shared file, 16 pages apart: one import, three joined; each +/// buffer's reads, fills and the CPU's later writes in its own piece's pages; the import kept +/// while one buffer lives, and freed with the last. +#[test] +fn pieces_of_one_shared_file_lie_in_one_import() { + const NAME: &str = "pieces_of_one_shared_file_lie_in_one_import"; + let Some((_scratch, device)) = on_device(NAME) else { + return; + }; + let page = host_page(); + let (stride, length) = (16 * page, 2 * page); + let len = BUFFERS * stride; + let ram = Ram::new(len, 0, len); + let mut expected = counting(len, 3); + ram.write_file(0, &expected); + let file = Arc::new(udmabuf(ram.file(), 0, len as u64).unwrap()); + let alignment = Arc::new(AtomicU64::new(0)); + let source = shared_source(&ram, &file, 0, &alignment); + let before = device.work_counts(); + let buffers: Vec = (0..BUFFERS) + .map(|index| { + no_copy(&device, &ram, (index * stride, length), Arc::clone(&source)).unwrap_or_else( + |error| { + panic!( + "{NAME}: buffer {index}: {error:?} (alignment asked {})", + alignment.load(Ordering::Acquire) + ) + }, + ) + }) + .collect(); + let made = device.work_counts(); + let (imports, joined, shared, memories) = moved(&before, &made); + eprintln!( + "{TEST}: {NAME} on {}: {BUFFERS} buffers over one file: imports {imports}, joined \ + {joined}, shared imports live +{shared}, dma-buf memories live +{memories}, alignment \ + asked {}", + device.name(), + alignment.load(Ordering::Acquire) + ); + assert_eq!( + (imports, joined, shared, memories), + (1, BUFFERS as u64 - 1, 1, 1), + "{NAME}: one import of the file, every other piece joined" + ); + let queue = device.new_command_queue().unwrap(); + for (index, buffer) in buffers.iter().enumerate() { + let at = index * stride; + assert_eq!( + read(&queue, buffer, length), + expected[at..at + length], + "{NAME}: buffer {index} reads its own piece" + ); + let value = 0xa0 + index as u8; + gpu_fill(&queue, buffer, page as u64..page as u64 + 256, value); + expected[at + page..at + page + 256].fill(value); + } + assert_eq!( + ram.read_file(0, len), + expected, + "{NAME}: each fill in its own piece's pages, the rest as it was" + ); + for (index, buffer) in buffers.iter().enumerate() { + let bytes = vec![0x5a ^ index as u8; 64]; + ram.write_file(index * stride + 64, &bytes); + assert_eq!( + read(&queue, buffer, 128)[64..], + bytes[..], + "{NAME}: buffer {index} reads the CPU's later writes" + ); + } + drop(buffers); + let freed = |counts: &WorkCounts| { + counts.dma_buf_shared_imports_live == before.dma_buf_shared_imports_live + && counts.dma_buf_memories_live == before.dma_buf_memories_live + }; + counts_once(NAME, &device, "the import freed with the buffers", freed); + // Two buffers no command used, whose releases free at once: the file imported anew, the + // import kept while the second lies in it, freed with it. + let first = no_copy(&device, &ram, (0, length), Arc::clone(&source)).unwrap(); + let second = no_copy(&device, &ram, (stride, length), Arc::clone(&source)).unwrap(); + drop(source); + drop(file); + let fresh = device.work_counts(); + drop(first); + let kept = device.work_counts(); + assert_eq!( + (moved(&made, &fresh).0, moved(&made, &fresh).1), + (1, 1), + "{NAME}: the file imported anew, the second joined" + ); + assert_eq!( + (moved(&before, &kept).2, moved(&before, &kept).3), + (1, 1), + "{NAME}: the file's import kept while one buffer lies in it" + ); + assert_eq!( + read(&queue, &second, length)[..page], + ram.read_file(stride, page)[..], + "{NAME}: the buffer left reads its piece" + ); + drop(second); + counts_once(NAME, &device, "the import freed with the last", freed); +} + +/// The negative control: the same four buffers, each answered with a dma-buf of its own: an +/// import each, none joined, no shared import live. +#[test] +fn chunks_of_their_own_are_an_import_each() { + const NAME: &str = "chunks_of_their_own_are_an_import_each"; + let Some((_scratch, device)) = on_device(NAME) else { + return; + }; + let page = host_page(); + let (stride, length) = (16 * page, 2 * page); + let len = BUFFERS * stride; + let ram = Ram::new(len, 0, len); + let expected = counting(len, 5); + ram.write_file(0, &expected); + let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let before = device.work_counts(); + let buffers: Vec = (0..BUFFERS) + .map(|index| no_copy(&device, &ram, (index * stride, length), ram.source(&calls)).unwrap()) + .collect(); + let made = device.work_counts(); + let (imports, joined, shared, memories) = moved(&before, &made); + eprintln!( + "{TEST}: {NAME} on {}: {BUFFERS} buffers of their own dma-bufs: imports {imports}, joined \ + {joined}, shared imports live +{shared}, dma-buf memories live +{memories}", + device.name() + ); + assert_eq!( + (imports, joined, shared, memories), + (BUFFERS as u64, 0, 0, BUFFERS as i64), + "{NAME}: an import each" + ); + let queue = device.new_command_queue().unwrap(); + for (index, buffer) in buffers.iter().enumerate() { + let at = index * stride; + assert_eq!(read(&queue, buffer, length), expected[at..at + length]); + } + drop(buffers); + counts_once(NAME, &device, "the imports freed", |counts| { + counts.dma_buf_memories_live == before.dma_buf_memories_live + }); +} + +/// A buffer longer than the device's sparse granule over two pieces of one file, laid in the file +/// in the other order: each bound at its offset in the file's one import, the second joined, the +/// buffer's bytes in order and a fill across the pieces' boundary in the file's pages there. +/// Where the request's granule is its length the device binds one piece, which the line says. +#[test] +fn a_buffer_over_two_pieces_of_one_file_binds_each_at_its_offset() { + const NAME: &str = "a_buffer_over_two_pieces_of_one_file_binds_each_at_its_offset"; + let Some((_scratch, device)) = on_device(NAME) else { + return; + }; + let page = host_page(); + let length = 256 << 10; + let len = 2 * length; + let ram = Ram::new(len, 0, len); + let mut expected = counting(len, 11); + ram.write_file(0, &expected); + let asked = Arc::new(std::sync::Mutex::new(None)); + // The file: the request's pages past the granule, then those before it. + let made_file = { + let asked = Arc::clone(&asked); + let ram_file = ram.file().try_clone().unwrap(); + move |request: DmaBufRequest| -> std::io::Result> { + *asked.lock().unwrap() = Some((request.granule, request.length, request.alignment)); + let (granule, length) = (request.granule, request.length); + if granule >= length { + let file = udmabuf(&ram_file, 0, length)?; + return Ok(vec![DmaBufChunk { + file: Arc::new(file), + offset: 0, + length, + }]); + } + let rounded = length.next_multiple_of(granule); + let file = Arc::new(udmabuf_list( + &ram_file, + &[(granule, rounded - granule), (0, granule)], + )?); + Ok(vec![ + DmaBufChunk { + file: Arc::clone(&file), + offset: rounded - granule, + length: granule, + }, + DmaBufChunk { + file, + offset: 0, + length: rounded - granule, + }, + ]) + } + }; + let before = device.work_counts(); + let buffer = no_copy(&device, &ram, (0, length), Arc::new(made_file)).unwrap(); + let made = device.work_counts(); + let answered = *asked.lock().unwrap(); + let (granule, _, alignment) = answered.expect("the source was asked"); + let (imports, joined, shared, _) = moved(&before, &made); + let sparse = made.dma_buf_sparse_buffers - before.dma_buf_sparse_buffers; + let split = granule < length as u64; + eprintln!( + "{TEST}: {NAME} on {}: granule {granule}, alignment {alignment}: {}: imports {imports}, \ + joined {joined}, shared imports live +{shared}, sparse buffers {sparse}", + device.name(), + match split { + true => "two pieces of one file", + false => "the device binds one piece: one dma-buf of its own", + } + ); + match split { + true => assert_eq!((imports, joined, shared, sparse), (1, 1, 1, 1), "{NAME}"), + false => assert_eq!((imports, joined, shared, sparse), (1, 0, 0, 0), "{NAME}"), + } + let queue = device.new_command_queue().unwrap(); + assert_eq!( + read(&queue, &buffer, length), + expected[..length], + "{NAME}: the buffer's bytes in order" + ); + let boundary = match split { + true => granule as usize, + false => length / 2, + }; + let across = (boundary - 128) as u64..(boundary + 128) as u64; + gpu_fill(&queue, &buffer, across, 0xc3); + expected[boundary - 128..boundary + 128].fill(0xc3); + assert_eq!( + ram.read_file(0, len)[..length], + expected[..length], + "{NAME}: a fill across the pieces' boundary in the file's pages there ({page}-byte pages)" + ); +} + +/// Two buffers over pieces of one file, read by blits, then released while idle: the file's +/// import goes with the second release; each buffer's next blit makes the import again or joins +/// it, reading its piece. +#[test] +fn released_pieces_import_their_file_again() { + const NAME: &str = "released_pieces_import_their_file_again"; + let Some((_scratch, device)) = on_device(NAME) else { + return; + }; + let page = host_page(); + let (stride, length) = (16 * page, 2 * page); + let len = 2 * stride; + let ram = Ram::new(len, 0, len); + let expected = counting(len, 13); + ram.write_file(0, &expected); + let file = Arc::new(udmabuf(ram.file(), 0, len as u64).unwrap()); + let alignment = Arc::new(AtomicU64::new(0)); + let source = shared_source(&ram, &file, 0, &alignment); + let before = device.work_counts(); + let buffers: Vec = (0..2) + .map(|index| no_copy(&device, &ram, (index * stride, length), Arc::clone(&source)).unwrap()) + .collect(); + let queue = device.new_command_queue().unwrap(); + for (index, buffer) in buffers.iter().enumerate() { + let at = index * stride; + assert_eq!(read(&queue, buffer, length), expected[at..at + length]); + } + release(NAME, &device, 2); + let released = device.work_counts(); + let (imports, joined, shared, memories) = moved(&before, &released); + assert_eq!( + (imports, joined, shared, memories), + (1, 1, 0, 0), + "{NAME}: the file's import goes with both buffers released" + ); + let changed = vec![0x77; 64]; + ram.write_file(stride, &changed); + let mut now = expected.clone(); + now[stride..stride + 64].copy_from_slice(&changed); + for (index, buffer) in buffers.iter().enumerate() { + let at = index * stride; + assert_eq!( + read(&queue, buffer, length), + now[at..at + length], + "{NAME}: buffer {index} imported again reads its piece" + ); + } + let again = device.work_counts(); + let (imports, joined, shared, _) = moved(&released, &again); + eprintln!( + "{TEST}: {NAME} on {}: released 2 (shared imports live back to +0), imported again: \ + imports {imports}, joined {joined}, shared imports live +{shared}, reimported {}", + device.name(), + again.host_imports_reimported - released.host_imports_reimported + ); + assert_eq!( + (imports, joined, shared), + (0, 1, 1), + "{NAME}: one import of the file again (imports again are not counted as new imports), \ + the other joined" + ); + assert_eq!( + again.host_imports_reimported - released.host_imports_reimported, + 2 + ); +} + +/// A piece whose offset in its file misses the request's alignment (half a page in) is misuse: +/// refused (`Invalid`, `Problem::DmaBuf`), nothing imported. +#[test] +fn a_piece_off_the_request_s_alignment_is_refused() { + const NAME: &str = "a_piece_off_the_request_s_alignment_is_refused"; + let Some((_scratch, device)) = on_device(NAME) else { + return; + }; + let page = host_page(); + let len = 4 * page; + let ram = Ram::new(len, 0, len); + let file = Arc::new(udmabuf(ram.file(), 0, len as u64).unwrap()); + let alignment = Arc::new(AtomicU64::new(0)); + let source = shared_source(&ram, &file, page as u64 / 2, &alignment); + let before = device.work_counts(); + let made = no_copy(&device, &ram, (0, 2 * page), source); + let after = device.work_counts(); + eprintln!( + "{TEST}: {NAME} on {}: a piece {} bytes in, alignment {}: {:?}", + device.name(), + page / 2, + alignment.load(Ordering::Acquire), + made.as_ref().err() + ); + assert!( + matches!( + made, + Err(Error::Invalid(Invalid { + problem: Problem::DmaBuf, + .. + })) + ), + "{NAME}: {:?}", + made.err() + ); + assert_eq!( + moved(&before, &after), + (0, 0, 0, 0), + "{NAME}: nothing imported" + ); +} diff --git a/crates/metal2vulkan-runtime/src/tests/dropped_uncommitted.rs b/crates/metal2vulkan-runtime/src/tests/dropped_uncommitted.rs index 7a6e2056c..c624e6368 100644 --- a/crates/metal2vulkan-runtime/src/tests/dropped_uncommitted.rs +++ b/crates/metal2vulkan-runtime/src/tests/dropped_uncommitted.rs @@ -128,7 +128,8 @@ impl GuestRam { .checked_sub(base) .ok_or_else(|| std::io::Error::other("pages before the mapping"))?; Ok(vec![DmaBufChunk { - fd: udmabuf(&fd, (file_at + at) as u64, request.length)?, + file: Arc::new(udmabuf(&fd, (file_at + at) as u64, request.length)?), + offset: 0, length: request.length, }]) }); diff --git a/crates/metal2vulkan-runtime/src/tests/export_after_dma_buf.rs b/crates/metal2vulkan-runtime/src/tests/export_after_dma_buf.rs index 8efad8c03..5beeb9efa 100644 --- a/crates/metal2vulkan-runtime/src/tests/export_after_dma_buf.rs +++ b/crates/metal2vulkan-runtime/src/tests/export_after_dma_buf.rs @@ -183,7 +183,8 @@ fn probe(device: &Device, page: u64) -> (u64, u64) { return Err(std::io::Error::other("pages other than the view's")); } Ok(vec![DmaBufChunk { - fd: source_buf.try_clone()?, + file: Arc::new(source_buf.try_clone()?), + offset: 0, length, }]) }); @@ -628,11 +629,10 @@ fn the_type_each_class_s_dma_buf_import_takes_against_the_class_s_order() { for class in classes { let before = dma_buf_class_order(types, allowed, class, unified); let after = dma_buf_candidates(types, allowed, class, unified); - let handed = fd.try_clone().unwrap(); let imported = import_dma_buf( &device.shared().memory, device.shared().vk(), - handed, + std::os::fd::AsFd::as_fd(&fd), bytes, (allowed, class), DmaBufFor::Shared, diff --git a/crates/metal2vulkan-runtime/src/tests/host_memory.rs b/crates/metal2vulkan-runtime/src/tests/host_memory.rs index 72ae9ec37..8199a519e 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_memory.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_memory.rs @@ -707,6 +707,8 @@ fn a_source_s_chunks_cover_the_request_at_its_granule() { start, length, granule, + alignment: page, + shared_files: true, }; let one = request(8 * page, 8 * page); assert!(chunks_cover(&[8 * page], &one, page)); diff --git a/crates/metal2vulkan-runtime/src/tests/host_ram_dma_buf.rs b/crates/metal2vulkan-runtime/src/tests/host_ram_dma_buf.rs index 9cfab7e1f..f51d1faa2 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_ram_dma_buf.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_ram_dma_buf.rs @@ -194,7 +194,8 @@ fn listed_ram( } let fd = udmabuf(&memfd, first - start, request.length)?; Ok(vec![DmaBufChunk { - fd, + file: Arc::new(fd), + offset: 0, length: request.length, }]) }) @@ -220,7 +221,11 @@ fn listed_ram( .collect(); let fd = udmabuf_list(&memfd, &runs)?; let length = runs.iter().map(|&(_, length)| length).sum(); - Ok(DmaBufChunk { fd, length }) + Ok(DmaBufChunk { + file: Arc::new(fd), + offset: 0, + length, + }) }) }; let at = NonNull::new(start as *mut u8).unwrap(); @@ -303,7 +308,8 @@ fn sourced_buffer( asked.lock().unwrap().viewed.push((first, request.length)); let fd = udmabuf(&file, first - view, request.length)?; Ok(vec![DmaBufChunk { - fd, + file: Arc::new(fd), + offset: 0, length: request.length, }]) }); diff --git a/crates/metal2vulkan-runtime/src/tests/host_ram_listed_bench.rs b/crates/metal2vulkan-runtime/src/tests/host_ram_listed_bench.rs index ed85ded45..ea76a5bb8 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_ram_listed_bench.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_ram_listed_bench.rs @@ -157,7 +157,8 @@ pub(super) fn ram_timed( let first = request.start.as_ptr() as u64; let fd = udmabuf(&memfd, first - start, request.length)?; Ok(vec![DmaBufChunk { - fd, + file: Arc::new(fd), + offset: 0, length: request.length, }]) }); @@ -171,7 +172,11 @@ pub(super) fn ram_timed( let took = u64::try_from(began.elapsed().as_nanos()).unwrap_or(u64::MAX); listing_nanos.fetch_add(took, Ordering::Relaxed); let length = runs.iter().map(|&(_, length)| length).sum(); - Ok(DmaBufChunk { fd: fd?, length }) + Ok(DmaBufChunk { + file: Arc::new(fd?), + offset: 0, + length, + }) }); let keep: KeepAlive = Box::new(Mapping { start, diff --git a/crates/metal2vulkan-runtime/src/tests/host_residency.rs b/crates/metal2vulkan-runtime/src/tests/host_residency.rs index 253118c54..a6d7bc3b3 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_residency.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_residency.rs @@ -310,6 +310,11 @@ impl Ram { } } + /// The file. + pub(super) fn file(&self) -> &OwnedFd { + &self.fd + } + /// The view's address `offset` bytes in. pub(super) fn pointer(&self, offset: usize) -> NonNull { assert!(offset < self.len); @@ -385,7 +390,8 @@ impl Ram { .ok_or_else(|| std::io::Error::other("pages before the view"))?; let offset = (file_at.load(Ordering::Acquire) + at) as u64; Ok(vec![DmaBufChunk { - fd: udmabuf(&fd, offset, request.length)?, + file: Arc::new(udmabuf(&fd, offset, request.length)?), + offset: 0, length: request.length, }]) }) diff --git a/crates/metal2vulkan-runtime/src/tests/import_free_hold_bench.rs b/crates/metal2vulkan-runtime/src/tests/import_free_hold_bench.rs index b9a03382f..5f3163fb8 100644 --- a/crates/metal2vulkan-runtime/src/tests/import_free_hold_bench.rs +++ b/crates/metal2vulkan-runtime/src/tests/import_free_hold_bench.rs @@ -311,7 +311,7 @@ fn make( let imported = crate::memory::import_dma_buf( &shared.memory, raw, - fd, + std::os::fd::AsFd::as_fd(&fd), kind.bytes, allowed, purpose, diff --git a/crates/metal2vulkan-runtime/src/tests/mod.rs b/crates/metal2vulkan-runtime/src/tests/mod.rs index bca0b5209..82ffd4946 100644 --- a/crates/metal2vulkan-runtime/src/tests/mod.rs +++ b/crates/metal2vulkan-runtime/src/tests/mod.rs @@ -198,8 +198,12 @@ mod dma_buf_first_imports; mod dma_buf_import_cycles; #[cfg(all(any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))] mod dma_buf_leak_probe; +#[cfg(unix)] +mod dma_buf_pieces; #[cfg(all(any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))] mod dma_buf_plane_offset; +#[cfg(all(any(m2v_gpu, m2v_cpu_icd), target_os = "linux"))] +mod dma_buf_shared_files; #[cfg(any(m2v_gpu, m2v_cpu_icd))] mod draw_again; #[cfg(any(m2v_gpu, m2v_cpu_icd))] diff --git a/crates/metal2vulkan-runtime/src/work_counts.rs b/crates/metal2vulkan-runtime/src/work_counts.rs index db87f184c..6fdbf8710 100644 --- a/crates/metal2vulkan-runtime/src/work_counts.rs +++ b/crates/metal2vulkan-runtime/src/work_counts.rs @@ -438,6 +438,8 @@ pub(crate) struct Counters { dma_buf_buffer_imports_dedicated: AtomicU64, dma_buf_memories_live: AtomicU64, dma_buf_image_memories_live: AtomicU64, + dma_buf_pieces_joined: AtomicU64, + dma_buf_shared_imports_live: AtomicU64, host_imports_released: AtomicU64, host_imports_released_over_most: AtomicU64, host_imports_reimported: AtomicU64, @@ -4117,11 +4119,30 @@ impl Counters { } } - /// `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) { + /// `imports` imports of dma-bufs a caller's source made of host pages (its chunks of their + /// own, and shared files no buffer had imported yet) were made, and a buffer bound in them, + /// where the device refused the pages' pointer (`dma_buf.rs`). + pub(crate) fn dma_buf_imported(&self, imports: usize) { self.dma_buf_imports - .fetch_add(chunks as u64, Ordering::Relaxed); + .fetch_add(imports as u64, Ordering::Relaxed); + } + + /// A piece of a shared file was bound in the device's import of the file, live already + /// (`dma_buf.rs`'s `file_import`). + pub(crate) fn dma_buf_piece_joined(&self) { + self.dma_buf_pieces_joined.fetch_add(1, Ordering::Relaxed); + } + + /// A shared file was imported and is held (`dma_buf.rs`'s `file_import`), besides + /// [`dma_buf_memory_imported`](Self::dma_buf_memory_imported). + pub(crate) fn dma_buf_shared_import_made(&self) { + (self.dma_buf_shared_imports_live).fetch_add(1, Ordering::Relaxed); + } + + /// `count` shared files' imports were freed, besides + /// [`dma_buf_memories_freed`](Self::dma_buf_memories_freed). + pub(crate) fn dma_buf_shared_imports_freed(&self, count: usize) { + (self.dma_buf_shared_imports_live).fetch_sub(count as u64, Ordering::Relaxed); } /// A dma-buf the driver refused to import dedicated to nothing, in every type tried, was @@ -8939,9 +8960,11 @@ pub struct WorkCounts { /// 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. + /// Imports of dma-bufs of host pages a caller's source made (`HostMemory::with_dma_buf`), + /// where the device refused the pages' pointer: no-copy buffers', heaps' and rebinds' alike, + /// one per chunk that is a dma-buf of its own, and one per shared file at its first piece + /// (`DmaBufChunk`), whose later pieces join it (`dma_buf_pieces_joined`). None where every + /// pointer was imported. pub dma_buf_imports: u64, /// Imports of a dma-buf of host pages that back one `VkBuffer` alone for their life (a /// no-copy buffer's own import of one chunk, a heap's never; a copy's list of a guest RAM's @@ -8951,11 +8974,20 @@ pub struct WorkCounts { /// 615.71.09 refuses a dma-buf of one 4 KiB page so (`ERROR_OUT_OF_DEVICE_MEMORY`) and takes /// it dedicated; one of 64 KiB it takes either way. Counted in `dma_buf_imports` too. pub dma_buf_buffer_imports_dedicated: u64, - /// Those chunks' imports live now: each a `VkDeviceMemory` the device holds until the last - /// buffer, texture or command buffer over its pages lets go. RADV lists each, as every - /// imported memory, in every kernel submission of the device (Mesa 26.2.4's global BO list), - /// and amdgpu's work per submission grows with them (`runtime_lane::submit_per_import`). + /// Those imports live now: each a `VkDeviceMemory` the device holds until the last buffer, + /// texture or command buffer over its pages (a shared file's: over any of its pieces) lets + /// go. RADV lists each, as every imported memory, in every kernel submission of the device + /// (Mesa 26.2.4's global BO list), and amdgpu's work per submission grows with them + /// (`runtime_lane::submit_per_import`). pub dma_buf_memories_live: u64, + /// Pieces of a file a caller's source shares (`DmaBufChunk`) bound in the device's import of + /// that file, live already as the buffer, heap or rebind was made over them: each a buffer's + /// chunk that took no import of its own. + pub dma_buf_pieces_joined: u64, + /// The device's imports of files a caller's source shares live now, one per file whatever + /// the pieces bound in it, freed with the last buffer or heap bound in it. Counted in + /// `dma_buf_memories_live` too. + pub dma_buf_shared_imports_live: u64, /// The dma-buf imports of images over such memory live now (`dma_buf_images`: each image's /// own, a dedicated one, or one bound at its texels' offset, `dma_buf_images_at_offset`), and /// the dedicated ones of images over the runtime's memory exported as a dma-buf @@ -8964,8 +8996,9 @@ pub struct WorkCounts { pub dma_buf_image_memories_live: u64, /// No-copy buffers' imports of dma-bufs released while idle, their `VkBuffer` destroyed and /// their memory freed, the dma-bufs kept: a runtime-internal residency, which nothing of - /// Metal's observes (`HostMemory::with_dma_buf` documents it). Their chunks leave - /// `dma_buf_memories_live`. + /// Metal's observes (`HostMemory::with_dma_buf` documents it). Their chunks of their own leave + /// `dma_buf_memories_live`; a shared file's import leaves it once every buffer bound in it + /// went or was released. pub host_imports_released: u64, /// Of `host_imports_released`, those released while more releasable imports held their memory /// than the device keeps at most, 64 where a held import adds to every submission's cost (its @@ -11651,6 +11684,9 @@ impl Device { dma_buf_image_memories_live: counters .dma_buf_image_memories_live .load(Ordering::Relaxed), + dma_buf_pieces_joined: counters.dma_buf_pieces_joined.load(Ordering::Relaxed), + dma_buf_shared_imports_live: (counters.dma_buf_shared_imports_live) + .load(Ordering::Relaxed), host_imports_released: counters.host_imports_released.load(Ordering::Relaxed), host_imports_released_over_most: (counters.host_imports_released_over_most) .load(Ordering::Relaxed), 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 979fd5b36..dac240e92 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/dma_buf_imports.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/dma_buf_imports.rs @@ -314,7 +314,8 @@ impl Memfd { plan.into_iter() .map(|(items, length)| { Ok(DmaBufChunk { - fd: udmabuf(fd.as_fd(), &items)?, + file: Arc::new(udmabuf(fd.as_fd(), &items)?), + offset: 0, length, }) }) @@ -1252,7 +1253,8 @@ fn shared_memory_without_a_working_source_is_a_copy_and_misuse_refused() { let fd = Arc::new(ram.fd.try_clone().unwrap()); let short: DmaBufSource = Arc::new(move |_| { Ok(vec![DmaBufChunk { - fd: udmabuf(fd.as_fd(), &[(page as u64, page as u64)])?, + file: Arc::new(udmabuf(fd.as_fd(), &[(page as u64, page as u64)])?), + offset: 0, length: page as u64, }]) }); @@ -1263,7 +1265,8 @@ fn shared_memory_without_a_working_source_is_a_copy_and_misuse_refused() { let fd = Arc::new(ram.fd.try_clone().unwrap()); let file: DmaBufSource = Arc::new(move |request| { Ok(vec![DmaBufChunk { - fd: fd.try_clone()?, + file: Arc::new(fd.try_clone()?), + offset: 0, length: request.length, }]) }); diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index fdc9b81db..cb594dda9 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 522; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2289; +pub const RUNTIME_VERSION: u32 = 2290; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 3f367c230..09a26052f 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2214,10 +2214,13 @@ field metal2vulkan-runtime::DeviceProperties.supports_32bit_float_filtering pub field metal2vulkan-runtime::DeviceProperties.vendor_id pub vendor_id: u32 field metal2vulkan-runtime::DeviceRefused.attempts pub attempts: Vec<(usize, VkResultCode)> field metal2vulkan-runtime::DeviceRefused.device pub device: String -field metal2vulkan-runtime::DmaBufChunk.fd pub fd: OwnedFd +field metal2vulkan-runtime::DmaBufChunk.file pub file: Arc field metal2vulkan-runtime::DmaBufChunk.length pub length: u64 +field metal2vulkan-runtime::DmaBufChunk.offset pub offset: u64 +field metal2vulkan-runtime::DmaBufRequest.alignment pub alignment: u64 field metal2vulkan-runtime::DmaBufRequest.granule pub granule: u64 field metal2vulkan-runtime::DmaBufRequest.length pub length: u64 +field metal2vulkan-runtime::DmaBufRequest.shared_files pub shared_files: bool field metal2vulkan-runtime::DmaBufRequest.start pub start: NonNull field metal2vulkan-runtime::EncodedComputeCommand.barrier pub barrier: bool field metal2vulkan-runtime::EncodedComputeCommand.command_type pub command_type: IndirectCommandType @@ -2870,6 +2873,8 @@ field metal2vulkan-runtime::WorkCounts.dma_buf_images pub dma_buf_images: u64 field metal2vulkan-runtime::WorkCounts.dma_buf_images_at_offset pub dma_buf_images_at_offset: u64 field metal2vulkan-runtime::WorkCounts.dma_buf_imports pub dma_buf_imports: u64 field metal2vulkan-runtime::WorkCounts.dma_buf_memories_live pub dma_buf_memories_live: u64 +field metal2vulkan-runtime::WorkCounts.dma_buf_pieces_joined pub dma_buf_pieces_joined: u64 +field metal2vulkan-runtime::WorkCounts.dma_buf_shared_imports_live pub dma_buf_shared_imports_live: u64 field metal2vulkan-runtime::WorkCounts.dma_buf_sparse_buffers pub dma_buf_sparse_buffers: u64 field metal2vulkan-runtime::WorkCounts.dma_buf_textures_in_place pub dma_buf_textures_in_place: u64 field metal2vulkan-runtime::WorkCounts.draw_heap_parts_made pub draw_heap_parts_made: u64 @@ -10359,7 +10364,7 @@ struct metal2vulkan-runtime::DeviceOptions #[derive(Clone, Default)] #[non_exhau struct metal2vulkan-runtime::DeviceProperties #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct DeviceProperties struct metal2vulkan-runtime::DeviceRefused #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct DeviceRefused struct metal2vulkan-runtime::DirtyStamp #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct DirtyStamp(pub u64) -struct metal2vulkan-runtime::DmaBufChunk #[derive(Debug)] pub struct DmaBufChunk +struct metal2vulkan-runtime::DmaBufChunk #[derive(Clone, Debug)] pub struct DmaBufChunk struct metal2vulkan-runtime::DmaBufRequest #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct DmaBufRequest struct metal2vulkan-runtime::DynamicLibrary #[derive(Clone, Debug)] pub struct DynamicLibrary(Arc) struct metal2vulkan-runtime::EncodedComputeCommand #[derive(Clone, Debug)] #[non_exhaustive] pub struct EncodedComputeCommand diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 5a4a0f671..e0e076815 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -253,7 +253,24 @@ dma-bufs of exactly the pages asked for, in order, split only at multiples of it the granule is less than the length (64 KiB on RADV of Mesa 26.2.4, 4 KiB on 26.0.8), several chunks are bound to one sparse buffer and must total the length rounded up to the granule: pad the last with a scratch page of your own, repeated. A texture's request takes one chunk, of the same -file pieces the buffer's chunks hold there. A device that imports a dma-buf for a plain buffer but +file pieces the buffer's chunks hold there. + +A chunk is `DmaBufChunk { file, offset, length }`. `file: Arc::new(fd), offset: 0`, with no clone +of the `Arc` kept, is a dma-buf of its own: one import (one `VkDeviceMemory`) for that chunk. To +put several buffers and heaps in one import, make one dma-buf of all their pages and answer each +request with a piece of it: the same `Arc` (keep a clone to hand out the next piece), the pages' +`offset` in that dma-buf, a multiple of the request's `alignment` (the host page, or more where the +device binds the buffer only at a larger multiple, or the granule where the request may split). +The runtime imports each such file once on the device, whole, and binds each buffer at its offset +in it; the import goes with the last buffer or heap bound in it. RADV lists every import in every +kernel submission (about 0.45 us each on the Radeon 780M, the consumer's measurement), so a +guest's thousand buffers in a hundred files are a hundred listed imports there, not a thousand. The runtime knows a file by its `Arc` +alone: two `Arc`s of one dma-buf are two files, imported twice. A request whose `shared_files` is +`false` (a texture's image, which takes a dedicated import) takes a dma-buf of its own at offset 0. +An import of a shared file is never dedicated to one buffer: on a device that takes small dma-bufs +only dedicated (NVIDIA's 615.71.09), the buffer is a copy of the pages, so answer its requests +with dma-bufs of their own. `WorkCounts::dma_buf_imports`, `dma_buf_pieces_joined` and +`dma_buf_shared_imports_live` count what the device made of them. A device that imports a dma-buf for a plain buffer but reports none for a sparse one asks with a granule of the whole length: one chunk, which one udmabuf must hold, else the object is refused. ANV of Mesa 26.2.6 on i915 is such a device: it takes a view of up to `list_limit` runs through its dma-buf, and refuses the pointer of a mapping