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<OwnedFd>, 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<DmaBufFile>, 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<OwnedFd>, 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.
This commit is contained in:
1 parent
f073427f9b
commit
045ae9caa8
29 files changed
+1615
-219
No files matched your search
@@ -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]]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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::<Create>() 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<OwnedFd> {
|
||||
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<u8>,
|
||||
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<u8> {
|
||||
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<Arc<OwnedFd>> = 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<Buffer> = (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<f64> = (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::<usize>().unwrap());
|
||||
let buffers = args.next().unwrap_or(1000);
|
||||
let mut per_file: Vec<usize> = 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)");
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<Option<u64>>,
|
||||
/// 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<Option<u64>>,
|
||||
}
|
||||
|
||||
/// 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(),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<Piece>,
|
||||
source: DmaBufSource,
|
||||
request: DmaBufRequest,
|
||||
},
|
||||
@@ -225,18 +229,19 @@ pub(super) struct ImportedAt(pub(super) NonNull<u8>);
|
||||
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<Piece>,
|
||||
source: DmaBufSource,
|
||||
request: DmaBufRequest,
|
||||
(length, window, class): (u64, ImportWindow, MemoryClass),
|
||||
) -> Option<Again> {
|
||||
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,
|
||||
|
||||
@@ -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<DmaBufPages>,
|
||||
memory: vk::DeviceMemory,
|
||||
type_index: u32,
|
||||
bound: crate::dma_buf::BoundIn,
|
||||
size: u64,
|
||||
mapped: NonNull<u8>,
|
||||
) -> 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<Memory>,
|
||||
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);
|
||||
|
||||
@@ -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,
|
||||
}])
|
||||
})
|
||||
|
||||
@@ -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,
|
||||
}])
|
||||
});
|
||||
|
||||
@@ -76,7 +76,7 @@ fn imports_at_once(memory: &Mutex<Memory>, most: &AtomicUsize) -> usize {
|
||||
let imported = import_dma_buf(
|
||||
memory,
|
||||
&device,
|
||||
fd,
|
||||
std::os::fd::AsFd::as_fd(&fd),
|
||||
4096,
|
||||
(1, MemoryClass::Shared),
|
||||
DmaBufFor::Shared,
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
})
|
||||
|
||||
@@ -561,7 +561,8 @@ impl Probe {
|
||||
}
|
||||
}
|
||||
Ok(vec![DmaBufChunk {
|
||||
fd: chunk,
|
||||
file: Arc::new(chunk),
|
||||
offset: 0,
|
||||
length: request.length,
|
||||
}])
|
||||
});
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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<OwnedFd>,
|
||||
skew: u64,
|
||||
alignment: &Arc<AtomicU64>,
|
||||
) -> 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<Buffer, Error> {
|
||||
// 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<Buffer> = (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<Buffer> = (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<Vec<DmaBufChunk>> {
|
||||
*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<Buffer> = (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"
|
||||
);
|
||||
}
|
||||
@@ -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,
|
||||
}])
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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,
|
||||
}])
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<u8> {
|
||||
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,
|
||||
}])
|
||||
})
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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))]
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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,
|
||||
}])
|
||||
});
|
||||
|
||||
Vendored
+1
-1
@@ -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
|
||||
|
||||
@@ -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<OwnedFd>
|
||||
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<u8>
|
||||
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<Shared>)
|
||||
struct metal2vulkan-runtime::EncodedComputeCommand #[derive(Clone, Debug)] #[non_exhaustive] pub struct EncodedComputeCommand
|
||||
|
||||
|
Can't render this file because it is too large.
|
+18
-1
@@ -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
|
||||
|
||||
Reference in new issue
Block a user