diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index ace48dd80..428f65af0 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -210,7 +210,8 @@ the runtime made. observes it. A no-copy buffer, heap or buffer rebind whose import the caller's gate refuses (`HostMemory::with_import_gate`), or whose admitted import fails, is made over a copy of its bytes in memory of the device's own, announced (`copied-host-pages`, - [HOWTO](../../docs/HOWTO.md#copied-host-buffers)). + [HOWTO](../../docs/HOWTO.md#copied-host-buffers)), wherever the process maps the pages + readable (a dma-buf's mapping among them); over pages not mapped readable it is refused. `CommandBuffer::used_resources` lists what a command buffer uses until it completes, so a program knows when it may take memory away. - **Hazards** are tracked as Metal tracks them. A heap's resources are untracked by default, so diff --git a/crates/metal2vulkan-runtime/src/copied.rs b/crates/metal2vulkan-runtime/src/copied.rs index f24ae0148..635c56b0b 100644 --- a/crates/metal2vulkan-runtime/src/copied.rs +++ b/crates/metal2vulkan-runtime/src/copied.rs @@ -7,8 +7,11 @@ //! - **The copy.** A `VkBuffer` of the buffer's length in host-visible, coherent memory of the //! runtime's own ([`MemoryClass::Shared`](crate::memory::MemoryClass)), which the GPU uses; the //! buffer's `contents` stays the caller's pointer, as Metal's is. Made over pages the process -//! reads: the first copy reads them through the kernel ([`read_pages`]), and pages it cannot -//! read (memory Metal makes no buffer over) keep the import's own refusal. +//! reads ([`read_caller`]): the first copy reads them through the kernel ([`read_pages`]), and +//! where the kernel fails the read, with plain loads where the process maps every page with +//! read permission ([`mapped_readable`]): on Linux the kernel reads no page it cannot pin, such +//! as a mapping of a dma-buf (`VM_PFNMAP`). Pages not mapped, or mapped without read permission +//! (memory Metal makes no buffer over), keep the import's own refusal. //! - **Coherence.** The runtime keeps, for each copy, the bytes the pages and the copy last agreed //! on (its snapshot). At each commit, before any of the command buffer's work is submitted, //! every byte the CPU changed in the pages since then is written into the copy @@ -35,6 +38,7 @@ //! (`shadowed-texture`): no image is bound to the copy. use crate::device::lock; +use crate::host_memory::mapped_readable; use crate::work_counts::Counters; use std::ptr::NonNull; use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering}; @@ -94,20 +98,43 @@ impl Drop for Copied { impl CopiedBuffers { /// Register the copy at `copy` of the `length` bytes at `pages`, its bytes read from the pages - /// now, through the kernel ([`read_pages`]). Refused, registering nothing, where the process - /// cannot read every page, or the host has no memory for the bytes the copy and the pages last - /// agreed on. + /// now ([`read_caller`]: through the kernel, or where it fails, with plain loads of pages + /// mapped readable). Refused, registering nothing, where the process cannot read every page, + /// or the host has no memory for the bytes the copy and the pages last agreed on. /// /// # Safety /// /// `copy` is `length` bytes of mapped memory nothing else uses yet, which stays mapped until /// the answer is dropped; `pages` the caller's bytes, which stay mapped as long - /// (`HostMemory::new`). + /// (`HostMemory::new`), and which the CPU reads without a fault wherever the process maps + /// them with read permission. pub(crate) unsafe fn add( self: &Arc, pages: NonNull, copy: NonNull, length: usize, + ) -> Result { + let read = |pages: NonNull, into: &mut [u8]| { + // SAFETY: the caller's bytes, read with plain loads only where the process maps them + // readable (the caller's contract). + unsafe { read_caller(pages, into, read_pages, mapped_readable) } + }; + // SAFETY: the caller's. + unsafe { self.add_reading(pages, copy, length, read) } + } + + /// [`CopiedBuffers::add`], the first bytes of the pages read by `read`, which answers whether + /// it read every one. + /// + /// # Safety + /// + /// As [`CopiedBuffers::add`]'s. + pub(crate) unsafe fn add_reading( + self: &Arc, + pages: NonNull, + copy: NonNull, + length: usize, + read: impl FnOnce(NonNull, &mut [u8]) -> bool, ) -> Result { let mut snapshot = Vec::new(); if snapshot.try_reserve_exact(length).is_err() { @@ -115,7 +142,7 @@ impl CopiedBuffers { } snapshot.resize(length, 0u8); let mut snapshot = snapshot.into_boxed_slice(); - if !read_pages(pages, &mut snapshot) { + if !read(pages, &mut snapshot) { return Err(NotCopied::Unreadable); } // SAFETY: the copy is `length` bytes nothing else uses yet (the caller's). @@ -211,12 +238,44 @@ pub(crate) unsafe fn sync( written } +/// Read the caller's `into.len()` bytes at `pages` into `into`: through the kernel (`kernel`, +/// [`read_pages`]), and where it fails, with plain loads where every page of them is mapped with +/// read permission (`readable`, asked for the bytes' addresses, [`mapped_readable`]). Whether +/// they were read: `false` where the kernel failed and a page is not mapped readable. +/// +/// The kernel's read is a test that faults on nothing, but on Linux it pins each page, and no +/// page of a `VM_PFNMAP` or `VM_IO` mapping can be pinned: a mapping of a dma-buf (udmabuf's on +/// Linux 7.2, measured) is mapped readable and fails it all the same. The plain loads are the +/// access a copy's comparisons make at each commit ([`sync`]). +/// +/// # Safety +/// +/// `pages` is `into.len()` bytes the CPU reads without a fault wherever `readable` answers `true` +/// for them. +pub(crate) unsafe fn read_caller( + pages: NonNull, + into: &mut [u8], + kernel: impl FnOnce(NonNull, &mut [u8]) -> bool, + readable: impl FnOnce(u64, u64) -> bool, +) -> bool { + if kernel(pages, into) { + return true; + } + let start = pages.as_ptr() as u64; + if !readable(start, start + into.len() as u64) { + return false; + } + // SAFETY: the bytes are mapped readable (the caller's); `into` is the runtime's own, apart. + unsafe { std::ptr::copy_nonoverlapping(pages.as_ptr(), into.as_mut_ptr(), into.len()) }; + true +} + /// Read the caller's `into.len()` bytes at `pages` into `into` through the kernel, which answers a /// page the process cannot read (unmapped, or mapped without read permission) with a failure, not a /// fault: `false` then. On Linux `process_vm_readv` of the process's own pages; on macOS /// `mach_vm_read_overwrite` of its own task's; elsewhere nothing is read and the answer is `false`. #[cfg(target_os = "linux")] -fn read_pages(pages: NonNull, into: &mut [u8]) -> bool { +pub(crate) fn read_pages(pages: NonNull, into: &mut [u8]) -> bool { let mut done = 0; while done < into.len() { let local = libc::iovec { @@ -240,7 +299,7 @@ fn read_pages(pages: NonNull, into: &mut [u8]) -> bool { /// [`read_pages`] on macOS. #[cfg(target_os = "macos")] -fn read_pages(pages: NonNull, into: &mut [u8]) -> bool { +pub(crate) fn read_pages(pages: NonNull, into: &mut [u8]) -> bool { unsafe extern "C" { /// ``: the port of this process's task. static mach_task_self_: libc::mach_port_t; @@ -269,6 +328,6 @@ fn read_pages(pages: NonNull, into: &mut [u8]) -> bool { /// [`read_pages`] where the system is not asked: nothing is copied. #[cfg(not(any(target_os = "linux", target_os = "macos")))] -fn read_pages(_pages: NonNull, _into: &mut [u8]) -> bool { +pub(crate) fn read_pages(_pages: NonNull, _into: &mut [u8]) -> bool { false } diff --git a/crates/metal2vulkan-runtime/src/host_memory.rs b/crates/metal2vulkan-runtime/src/host_memory.rs index 148c6fd3d..6e087b85a 100644 --- a/crates/metal2vulkan-runtime/src/host_memory.rs +++ b/crates/metal2vulkan-runtime/src/host_memory.rs @@ -618,18 +618,23 @@ pub(super) fn import_refused(error: vk::Result) -> Error { /// Refuse the window's pages, typed, unless the process maps every one of them writable: Linux /// drivers pin imported pages for writing. Asked by each call that imports the pages itself, not /// by a buffer that lies in a live import of them. The kernel answers for the mappings over the -/// window ([`queried_writable`]) at each call, so a page remapped or reprotected since an earlier +/// window ([`queried_permitted`]) at each call, so a page remapped or reprotected since an earlier /// import is judged as it is now: one query per mapping, so its cost grows with the mappings over /// the window (a view of scattered pages maps each run apart). The queries go through the file /// the process keeps open ([`kept_maps`]). A kernel without the query (before Linux 6.11) has the -/// lines of `/proc/self/maps` read up to the window instead ([`writable`]), from a file opened for +/// lines of `/proc/self/maps` read up to the window instead ([`permitted`]), from a file opened for /// the reading, which cost about 4.5 ms per import in a process of 34,000 mappings. Each mapping /// asked is counted in `counts` (`WorkCounts::host_mappings_queried`). When the file cannot be /// opened, every import is refused as not implemented here. #[cfg(target_os = "linux")] pub(super) fn refuse_unwritable(window: &ImportWindow, counts: &Counters) -> Result<(), Error> { let mut asked = 0; - let answer = mappings_writable(window.start, window.start + window.size, &mut asked); + let answer = mappings_permitted( + window.start, + window.start + window.size, + Access::Write, + &mut asked, + ); counts.host_mappings_queried(asked); match answer { Some(true) => Ok(()), @@ -640,25 +645,69 @@ pub(super) fn refuse_unwritable(window: &ImportWindow, counts: &Counters) -> Res } } -/// Whether the process maps `[start, end)` without a gap, each page with write permission, as the -/// kernel answers now: for the mappings over it ([`queried_writable`]), or from the lines of -/// `/proc/self/maps` where the kernel predates the query ([`writable`]); `None` when that file +/// Whether the process maps every page of `[start, end)` with read permission, as the kernel +/// answers now ([`mappings_permitted`]): where it does, the CPU reads the bytes with plain loads, +/// as a copied host buffer's comparisons read them at each commit (`copied.rs`). `false` where +/// the mappings cannot be read (`/proc/self/maps` does not open). +#[cfg(target_os = "linux")] +pub(super) fn mapped_readable(start: u64, end: u64) -> bool { + mappings_permitted(start, end, Access::Read, &mut 0) == Some(true) +} + +/// [`mapped_readable`] where the runtime does not ask the system for its mappings: `false`. +#[cfg(not(target_os = "linux"))] +pub(super) fn mapped_readable(_start: u64, _end: u64) -> bool { + false +} + +/// A permission the process's mappings are asked for. +#[cfg(target_os = "linux")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Access { + /// `VM_READ`, the `r` of a mapping's line in the maps: a copy reads the pages (`copied.rs`). + Read, + /// `VM_WRITE`, the `w`: Linux drivers pin imported pages for writing ([`refuse_unwritable`]). + Write, +} + +#[cfg(target_os = "linux")] +impl Access { + /// The mapping's flag of the permission in `PROCMAP_QUERY`'s answer (`vma_flags`). + fn queried(self) -> u64 { + match self { + Access::Read => PROCMAP_QUERY_VMA_READABLE, + Access::Write => PROCMAP_QUERY_VMA_WRITABLE, + } + } + + /// The permission's place and letter in a maps line's permissions (`rw-p`). + fn letter(self) -> (usize, u8) { + match self { + Access::Read => (0, b'r'), + Access::Write => (1, b'w'), + } + } +} + +/// Whether the process maps `[start, end)` without a gap, each page with `access`, as the kernel +/// answers now: for the mappings over it ([`queried_permitted`]), or from the lines of +/// `/proc/self/maps` where the kernel predates the query ([`permitted`]); `None` when that file /// cannot be opened. Each mapping asked is added to `asked`. #[cfg(target_os = "linux")] -fn mappings_writable(start: u64, end: u64, asked: &mut u64) -> Option { +fn mappings_permitted(start: u64, end: u64, access: Access, asked: &mut u64) -> Option { use std::io::BufRead; let maps = kept_maps()?; - if let Some(writable) = queried_writable(&maps, start, end, asked) { - return Some(writable); + if let Some(permitted) = queried_permitted(&maps, start, end, access, asked) { + return Some(permitted); } // The lines are read from a file of their own: reading moves its position, which the kept // one's queries share among threads. let maps = std::fs::File::open("/proc/self/maps").ok()?; let lines = std::io::BufReader::new(maps).lines().map_while(Result::ok); - Some(writable(lines, start, end, asked)) + Some(permitted(lines, start, end, access, asked)) } -/// This process's `/proc/self/maps`, opened once for [`queried_writable`] and kept with the id of +/// This process's `/proc/self/maps`, opened once for [`queried_permitted`] and kept with the id of /// the process that opened it, or opened again (`None` where it cannot be): each `PROCMAP_QUERY` /// answers from the process's mappings as they are at the call, so a file kept open reads the same /// answers as one opened for the call, without the opening, which cost each import about as much @@ -709,20 +758,26 @@ const _: () = assert!(std::mem::size_of::() == 104); const PROCMAP_QUERY: u64 = (3 << 30) | ((std::mem::size_of::() as u64) << 16) | ((b'f' as u64) << 8) | 17; +/// `PROCMAP_QUERY_VMA_READABLE`: the mapping's `VM_READ`, the `r` of its line in the maps. +#[cfg(target_os = "linux")] +const PROCMAP_QUERY_VMA_READABLE: u64 = 0x01; + /// `PROCMAP_QUERY_VMA_WRITABLE`: the mapping's `VM_WRITE`, the `w` of its line in the maps. #[cfg(target_os = "linux")] const PROCMAP_QUERY_VMA_WRITABLE: u64 = 0x02; -/// Whether the process maps `[start, end)` without a gap, each mapping with write permission, as -/// the kernel answers `PROCMAP_QUERY` on `maps` (this process's `/proc/self/maps`): one query per +/// Whether the process maps `[start, end)` without a gap, each mapping with `access`, as the +/// kernel answers `PROCMAP_QUERY` on `maps` (this process's `/proc/self/maps`): one query per /// mapping the window touches, each for the mapping covering the first address not yet covered, /// and each added to `asked`. `None` where the kernel does not answer the query (before Linux -/// 6.11, `ENOTTY`) or fails it otherwise; a missing mapping (`ENOENT`) is an answer, not writable. +/// 6.11, `ENOTTY`) or fails it otherwise; a missing mapping (`ENOENT`) is an answer, not +/// permitted. #[cfg(target_os = "linux")] -pub(super) fn queried_writable( +pub(super) fn queried_permitted( maps: &std::fs::File, start: u64, end: u64, + access: Access, asked: &mut u64, ) -> Option { use std::os::fd::AsRawFd; @@ -751,7 +806,7 @@ pub(super) fn queried_writable( if query.vma_start > covered || query.vma_end <= covered { return None; } - if query.vma_flags & PROCMAP_QUERY_VMA_WRITABLE == 0 { + if query.vma_flags & access.queried() == 0 { return Some(false); } covered = query.vma_end; @@ -767,14 +822,15 @@ pub(super) fn refuse_unwritable(_window: &ImportWindow, _counts: &Counters) -> R } /// Whether the mappings of `maps` (lines of `/proc//maps`, in address order) cover -/// `[start, end)` without a gap, each with write permission, adding to `asked` each mapping it -/// judged (one ending past the address it reached). Reading stops at the first line past `end`; a -/// line that does not parse is skipped. +/// `[start, end)` without a gap, each with `access`, adding to `asked` each mapping it judged (one +/// ending past the address it reached). Reading stops at the first line past `end`; a line that +/// does not parse is skipped. #[cfg(target_os = "linux")] -pub(super) fn writable( +pub(super) fn permitted( maps: impl IntoIterator, start: u64, end: u64, + access: Access, asked: &mut u64, ) -> bool { let mut covered = start; @@ -782,14 +838,14 @@ pub(super) fn writable( if covered >= end { break; } - let Some((from, to, write)) = mapping(&line) else { + let Some((from, to, allowed)) = mapping(&line, access) else { continue; }; if to <= covered { continue; } *asked += 1; - if from > covered || !write { + if from > covered || !allowed { return false; } covered = to; @@ -797,16 +853,17 @@ pub(super) fn writable( covered >= end } -/// One line of `/proc//maps`: the mapping's start, its end, and whether it is writable. +/// One line of `/proc//maps`: the mapping's start, its end, and whether it has `access`. #[cfg(target_os = "linux")] -fn mapping(line: &str) -> Option<(u64, u64, bool)> { +fn mapping(line: &str, access: Access) -> Option<(u64, u64, bool)> { let mut fields = line.split_ascii_whitespace(); let (from, to) = fields.next()?.split_once('-')?; let permissions = fields.next()?; + let (place, letter) = access.letter(); Some(( u64::from_str_radix(from, 16).ok()?, u64::from_str_radix(to, 16).ok()?, - permissions.as_bytes().get(1) == Some(&b'w'), + permissions.as_bytes().get(place) == Some(&letter), )) } diff --git a/crates/metal2vulkan-runtime/src/tests/copied.rs b/crates/metal2vulkan-runtime/src/tests/copied.rs index 7134af70e..8e0700bf2 100644 --- a/crates/metal2vulkan-runtime/src/tests/copied.rs +++ b/crates/metal2vulkan-runtime/src/tests/copied.rs @@ -1,9 +1,14 @@ //! The comparisons that keep a copied host buffer coherent with the caller's pages (`copied.rs`), //! on plain memory: a commit's copy in writes the bytes the CPU changed alone, and a completion's -//! merge back writes the bytes the GPU changed alone, keeping a byte the CPU changed since. +//! merge back writes the bytes the GPU changed alone, keeping a byte the CPU changed since. And +//! the copy's first read of the pages: where the kernel's read fails, pages mapped readable are +//! copied all the same and others refused; on Linux, a mapping of a dma-buf (`VM_PFNMAP`), which +//! the kernel's read refuses, is copied (where `/dev/udmabuf` opens). -use crate::copied::sync; +use crate::copied::{read_caller, sync, CopiedBuffers, NotCopied}; +use std::cell::Cell; use std::ptr::NonNull; +use std::sync::Arc; /// `bytes` as a pointer the comparison reads or writes. fn at(bytes: &mut [u8]) -> NonNull { @@ -57,3 +62,203 @@ fn copied_merge_back_keeps_a_byte_the_cpu_changed_since() { assert_eq!(snapshot, pages, "they agree"); assert_eq!(copy, pages); } + +/// Where the kernel's read of the pages fails (a mapping it cannot pin), pages the process maps +/// readable are read with plain loads and copied; where a page is not mapped readable, the copy +/// is refused and nothing written; where the kernel reads them, no mapping is asked about. +#[test] +fn copied_pages_the_kernel_cannot_read_are_copied_where_mapped_readable() { + let mut pages: Vec = (0..4099_u32).map(|i| (i * 7 + 3) as u8).collect(); + let length = pages.len(); + let start = pages.as_ptr() as u64; + let buffers = Arc::new(CopiedBuffers::default()); + let asked = Cell::new(None); + let mut copy = vec![0_u8; length]; + let read_readable = |from: NonNull, into: &mut [u8]| { + let readable = |start, end| { + asked.set(Some((start, end))); + true + }; + // SAFETY: plain memory, readable. + unsafe { read_caller(from, into, |_, _| false, readable) } + }; + // SAFETY: the copy and the pages are the test's, of `length` bytes, live past the answer. + let copied = + unsafe { buffers.add_reading(at(&mut pages), at(&mut copy), length, read_readable) }; + assert!(copied.is_ok(), "copied"); + assert_eq!(copy, pages, "the copy holds the pages' bytes"); + assert_eq!(asked.get(), Some((start, start + length as u64)), "asked"); + let mut refused_copy = vec![0_u8; length]; + let read_unreadable = |from: NonNull, into: &mut [u8]| { + // SAFETY: nothing is read. + unsafe { read_caller(from, into, |_, _| false, |_, _| false) } + }; + // SAFETY: as above; nothing reads the pages. + let refused = unsafe { + buffers.add_reading( + at(&mut pages), + at(&mut refused_copy), + length, + read_unreadable, + ) + }; + assert_eq!(refused.err(), Some(NotCopied::Unreadable)); + assert!(refused_copy.iter().all(|&byte| byte == 0), "nothing copied"); + let mut into = vec![0_u8; length]; + asked.set(None); + let kernel = |from: NonNull, into: &mut [u8]| { + // SAFETY: the pages are `into.len()` bytes of plain memory. + unsafe { std::ptr::copy_nonoverlapping(from.as_ptr(), into.as_mut_ptr(), into.len()) }; + true + }; + // SAFETY: as above. + let read = unsafe { + read_caller(at(&mut pages), &mut into, kernel, |start, end| { + asked.set(Some((start, end))); + false + }) + }; + assert!(read); + assert_eq!( + (into, asked.get()), + (pages, None), + "the kernel's read alone" + ); +} + +/// A copy of pages of a dma-buf mapping (udmabuf's, `VM_PFNMAP`), which the kernel's read cannot +/// pin and fails: the copy is made, and holds their bytes. The test says which read took them +/// (`--no-capture`). Not run where `/dev/udmabuf` does not open, which the test says. +#[cfg(target_os = "linux")] +#[test] +fn copied_pages_of_a_dma_buf_mapping_are_copied() { + use crate::copied::read_pages; + // SAFETY: `sysconf` reads a system constant. + let page = usize::try_from(unsafe { libc::sysconf(libc::_SC_PAGESIZE) }).unwrap(); + let length = 16 * page; + let pattern: Vec = (0..length).map(|i| (i % 251) as u8 ^ 0x5A).collect(); + let Some(mapping) = DmaBufMapping::new(&pattern) else { + return; + }; + // The path the test is for: the kernel cannot read the mapping's pages. + let mut probe = vec![0_u8; page]; + match read_pages(mapping.pages, &mut probe) { + true => println!("the kernel reads this udmabuf mapping: copied through the kernel"), + false => println!("the kernel cannot read this udmabuf mapping: copied with plain loads"), + } + let buffers = Arc::new(CopiedBuffers::default()); + let mut copy = vec![0_u8; length]; + // SAFETY: the copy is the test's; the mapping is `length` bytes, readable, live past the + // answer. + let copied = unsafe { buffers.add(mapping.pages, at(&mut copy), length) }; + assert!(copied.is_ok(), "copied"); + assert!(copy == pattern, "the copy holds the dma-buf's bytes"); +} + +/// A shared mapping of a dma-buf (`/dev/udmabuf`) of a `memfd`'s pages, as a consumer maps guest +/// RAM: `VM_PFNMAP`, which the kernel cannot pin. Unmapped when dropped. +#[cfg(target_os = "linux")] +pub(super) struct DmaBufMapping { + /// The mapping's first byte. + pub(super) pages: NonNull, + length: usize, + _dma_buf: std::os::fd::OwnedFd, + _memfd: std::os::fd::OwnedFd, +} + +#[cfg(target_os = "linux")] +impl DmaBufMapping { + /// A mapping of a dma-buf of a new `memfd` holding `bytes` (whole pages), or `None` where + /// `/dev/udmabuf` does not open, which it says. + pub(super) fn new(bytes: &[u8]) -> Option { + use std::io::Write; + use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; + /// `struct udmabuf_create` of Linux's `include/uapi/linux/udmabuf.h`. + #[repr(C)] + struct Create { + memfd: u32, + flags: u32, + offset: u64, + size: u64, + } + /// `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; + /// `UDMABUF_FLAGS_CLOEXEC`. + const UDMABUF_FLAGS_CLOEXEC: u32 = 0x01; + let device = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open("/dev/udmabuf"); + let device = match device { + Ok(device) => device, + Err(error) => { + println!("/dev/udmabuf cannot be opened ({error}): not run"); + return None; + } + }; + let length = bytes.len(); + // A memfd sealed against shrinking, as udmabuf requires, holding the bytes. + // SAFETY: a NUL-terminated name. + let memfd = unsafe { + libc::memfd_create( + c"m2v-copied-udmabuf".as_ptr(), + libc::MFD_CLOEXEC | libc::MFD_ALLOW_SEALING, + ) + }; + assert!(memfd >= 0, "memfd: {}", std::io::Error::last_os_error()); + // SAFETY: a new descriptor, owned at once. + let memfd = unsafe { OwnedFd::from_raw_fd(memfd) }; + std::fs::File::from(memfd.try_clone().unwrap()) + .write_all(bytes) + .unwrap(); + // SAFETY: seals the memfd made above. + let sealed = + unsafe { libc::fcntl(memfd.as_raw_fd(), libc::F_ADD_SEALS, libc::F_SEAL_SHRINK) }; + assert_eq!(sealed, 0, "seal: {}", std::io::Error::last_os_error()); + let create = Create { + memfd: memfd.as_raw_fd() as u32, + flags: UDMABUF_FLAGS_CLOEXEC, + offset: 0, + size: length as u64, + }; + // SAFETY: the ioctl reads `create`, a valid `udmabuf_create`. + let dma_buf = unsafe { libc::ioctl(device.as_raw_fd(), UDMABUF_CREATE as _, &create) }; + assert!(dma_buf >= 0, "udmabuf: {}", std::io::Error::last_os_error()); + // SAFETY: a new descriptor the ioctl returned, owned at once. + let dma_buf = unsafe { OwnedFd::from_raw_fd(dma_buf) }; + // SAFETY: a new shared mapping of the dma-buf, unmapped by the answer's drop. + let mapped = unsafe { + libc::mmap( + std::ptr::null_mut(), + length, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_SHARED, + dma_buf.as_raw_fd(), + 0, + ) + }; + assert_ne!( + mapped, + libc::MAP_FAILED, + "{}", + std::io::Error::last_os_error() + ); + Some(DmaBufMapping { + pages: NonNull::new(mapped.cast()).unwrap(), + length, + _dma_buf: dma_buf, + _memfd: memfd, + }) + } +} + +#[cfg(target_os = "linux")] +impl Drop for DmaBufMapping { + fn drop(&mut self) { + // SAFETY: the mapping made by `new`, which nothing uses now. + let unmapped = unsafe { libc::munmap(self.pages.as_ptr().cast(), self.length) }; + assert_eq!(unmapped, 0); + } +} diff --git a/crates/metal2vulkan-runtime/src/tests/copied_device.rs b/crates/metal2vulkan-runtime/src/tests/copied_device.rs index 2df649fd7..55c9fae8f 100644 --- a/crates/metal2vulkan-runtime/src/tests/copied_device.rs +++ b/crates/metal2vulkan-runtime/src/tests/copied_device.rs @@ -15,6 +15,8 @@ //! those bytes alone merged back. //! - **Unreadable pages** (mapped without access, memory Metal makes no buffer over) are never //! copied: the buffer is refused, as their import is. +//! - **A dma-buf's mapping** (Linux, where `/dev/udmabuf` opens), whose pages the kernel's read +//! cannot pin, is copied where the gate refuses its import, with the same coherence. //! - **Rebinds.** A rebind's new pages are a copy where the gate refuses their import or the //! admitted import fails, with the same coherence; the old pages stay as they were, and a later //! rebind imports again. @@ -41,10 +43,21 @@ const LENGTH: usize = 64 * 1024; /// Host memory of whole pages, in a pattern of its own, freed when dropped (after the device). struct Host { pointer: NonNull, - layout: Layout, + backing: Backing, seed: u8, } +/// What a [`Host`]'s pages are. +enum Backing { + /// An allocation of this layout. + Allocated(Layout), + /// A mapping of a dma-buf of a `memfd`'s pages, as a consumer maps guest RAM. + #[cfg(target_os = "linux")] + DmaBuf { + _mapping: super::copied::DmaBufMapping, + }, +} + impl Host { fn new(seed: u8) -> Host { let layout = Layout::from_size_align(LENGTH, 1 << 16).unwrap(); @@ -52,18 +65,28 @@ impl Host { let pointer = NonNull::new(unsafe { std::alloc::alloc(layout) }).unwrap(); let host = Host { pointer, - layout, + backing: Backing::Allocated(layout), seed, }; host.write(0, &host.pattern()); host } + /// Host memory over a dma-buf's mapping (`VM_PFNMAP`), or `None` where `/dev/udmabuf` does + /// not open, which it says. + #[cfg(target_os = "linux")] + fn over_dma_buf(seed: u8) -> Option { + let mapping = super::copied::DmaBufMapping::new(&pattern(seed))?; + Some(Host { + pointer: mapping.pages, + backing: Backing::DmaBuf { _mapping: mapping }, + seed, + }) + } + /// The pattern it was made with. fn pattern(&self) -> Vec { - (0..LENGTH) - .map(|i| ((i % 251) as u8).wrapping_add(self.seed.wrapping_mul(37))) - .collect() + pattern(self.seed) } /// Its bytes, read while no command buffer runs. @@ -109,11 +132,25 @@ impl Host { impl Drop for Host { fn drop(&mut self) { - // SAFETY: allocated with this layout. - unsafe { std::alloc::dealloc(self.pointer.as_ptr(), self.layout) }; + match self.backing { + // SAFETY: allocated with this layout. + Backing::Allocated(layout) => unsafe { + std::alloc::dealloc(self.pointer.as_ptr(), layout) + }, + // Unmapped by the mapping's own drop. + #[cfg(target_os = "linux")] + Backing::DmaBuf { .. } => {} + } } } +/// The bytes of a [`Host`] of `seed`. +fn pattern(seed: u8) -> Vec { + (0..LENGTH) + .map(|i| ((i % 251) as u8).wrapping_add(seed.wrapping_mul(37))) + .collect() +} + /// The degrade notices a device announced. type Heard = Arc>>; @@ -295,6 +332,28 @@ fn copied_buffer_is_made_where_the_caller_s_gate_refuses_the_import() { drop((buffer, imported)); } +/// Pages of a dma-buf's mapping (`VM_PFNMAP`, as a consumer maps guest RAM), which the kernel's +/// read cannot pin, whose import the gate refuses, are copied all the same (read with plain loads, +/// mapped readable), with the copy's coherence. Linux only, where `/dev/udmabuf` opens. +#[cfg(target_os = "linux")] +#[test] +fn copied_buffer_is_made_over_a_dma_buf_mapping_the_gate_refuses() { + let Some(host) = Host::over_dma_buf(9) else { + return; + }; + let Some((device, heard)) = device() else { + return; + }; + let asked: Arc>> = Arc::default(); + let before = device.work_counts(); + let buffer = host.buffer(&device, Some(gate(&asked, false))); + let after = device.work_counts(); + assert_eq!(moved(&before, &after), [1, 1, 1, 0, 0]); + assert_eq!(announced(&heard), 1, "announced once"); + lies_in_a_copy(&device, &buffer, &host); + drop(buffer); +} + #[test] fn copied_buffer_is_made_where_an_admitted_import_fails_announced() { let (host, other) = (Host::new(3), Host::new(4)); diff --git a/crates/metal2vulkan-runtime/src/tests/host_memory.rs b/crates/metal2vulkan-runtime/src/tests/host_memory.rs index 4ebb63af5..8874ba345 100644 --- a/crates/metal2vulkan-runtime/src/tests/host_memory.rs +++ b/crates/metal2vulkan-runtime/src/tests/host_memory.rs @@ -1,6 +1,8 @@ //! Buffers over host memory (`host_memory.rs`): the pages an import covers, where the buffer //! binds in them, the memory types an import may use, and the host's page. +#[cfg(target_os = "linux")] +use crate::host_memory::Access; use crate::host_memory::{ based_size, binds_in, buffer_base, host_page, import_refused, import_window, refused, ImportWindow, WindowRefusal, @@ -217,7 +219,7 @@ fn the_host_page_is_unknown_elsewhere() { assert_eq!(host_page(), None); } -/// Lines of `/proc//maps` (address order) for the writability check. +/// Lines of `/proc//maps` (address order) for the permission checks. #[cfg(target_os = "linux")] fn maps(lines: &[&str]) -> Vec { lines.iter().map(|line| line.to_string()).collect() @@ -226,7 +228,7 @@ fn maps(lines: &[&str]) -> Vec { #[cfg(target_os = "linux")] #[test] fn only_pages_mapped_writable_without_a_gap_are_importable() { - use crate::host_memory::writable; + use crate::host_memory::permitted; let lines = maps(&[ "1000-3000 rw-p 00000000 00:00 0", "3000-5000 rw-s 00000000 00:01 7 /dev/shm/guest (deleted)", @@ -238,7 +240,10 @@ fn only_pages_mapped_writable_without_a_gap_are_importable() { // The answer, and how many mappings it judged. let judged = |lines: Vec, start: u64, end: u64| { let mut asked = 0; - (writable(lines, start, end, &mut asked), asked) + ( + permitted(lines, start, end, Access::Write, &mut asked), + asked, + ) }; // Inside one mapping, and across two adjacent writable ones (private and shared). assert_eq!(judged(lines.clone(), 0x1000, 0x3000), (true, 1)); @@ -255,6 +260,37 @@ fn only_pages_mapped_writable_without_a_gap_are_importable() { assert_eq!(judged(Vec::new(), 0x1000, 0x2000), (false, 0)); } +/// The read check takes a mapping's `r` as the write check takes its `w`: a read-only page is +/// readable, a page mapped without access or a gap is not. +#[cfg(target_os = "linux")] +#[test] +fn only_pages_mapped_readable_without_a_gap_are_readable() { + use crate::host_memory::permitted; + let lines = maps(&[ + "1000-3000 rw-s 00000000 00:06 1066 /dmabuf:", + "3000-5000 r--p 00000000 00:00 0", + "5000-6000 ---p 00000000 00:00 0", + "6000-7000 -w-p 00000000 00:00 0", + "8000-9000 r-xp 00000000 00:00 0", + ]); + let judged = |start: u64, end: u64| { + let mut asked = 0; + ( + permitted(lines.clone(), start, end, Access::Read, &mut asked), + asked, + ) + }; + // Shared and read-only mappings, adjacent. + assert_eq!(judged(0x1000, 0x5000), (true, 2)); + // A page mapped without access, alone or at the end of a range; a write-only one. + assert_eq!(judged(0x5000, 0x6000), (false, 1)); + assert_eq!(judged(0x4000, 0x6000), (false, 2)); + assert_eq!(judged(0x6000, 0x7000), (false, 1)); + // A gap, and an executable mapping past it. + assert_eq!(judged(0x7000, 0x9000), (false, 1)); + assert_eq!(judged(0x8000, 0x9000), (true, 1)); +} + /// The mapping queries go through one file the process keeps open (`host_memory::kept_maps`), /// opened once, whose answers follow the mappings as they are at each query (the test below). #[cfg(target_os = "linux")] @@ -309,9 +345,10 @@ fn this_process_s_read_only_and_unmapped_pages_are_refused() { assert!(refused(refuse_unwritable(&window, &counts))); } -/// The kernel's answer for a window (`PROCMAP_QUERY`) is the maps lines' answer, over one -/// mapping, two of different permissions, a read-only page alone, and a page no longer mapped; -/// and a kernel of Linux 6.11 or later answers it, so no import reads the maps' text. Both +/// The kernel's answer for a window (`PROCMAP_QUERY`) is the maps lines' answer, for write +/// permission and for read permission, over one mapping, two of different permissions, a +/// read-only page alone, a page mapped without access, and a page no longer mapped; and a kernel +/// of Linux 6.11 or later answers it, so no import or copy reads the maps' text. Both /// answers read the address space of a child forked for each state ([`window_answers`]), which /// no other thread changes: in this process, another test's mapping may take the unmapped page /// between the two readings. @@ -351,15 +388,15 @@ fn the_kernel_s_answer_for_a_window_is_the_maps_lines_answer() { let windows = [(0, 1), (0, 2), (1, 2), (1, 3), (0, 3), (2, 3)]; let spans = windows.map(|(from, to)| (base + from * page, base + to * page)); let check = |state: &str| { - for ((from, to), (read, queried)) in windows.into_iter().zip(window_answers(&spans)) { - if queries { - assert_eq!( - queried, - Some(read), - "{state}: pages {from}..{to} on {release}" - ); - } else if let Some(queried) = queried { - assert_eq!(queried, read, "{state}: pages {from}..{to} on {release}"); + for access in [Access::Write, Access::Read] { + let answers = window_answers(&spans, access); + for ((from, to), (lines, queried)) in windows.into_iter().zip(answers) { + let what = format!("{state}, {access:?}: pages {from}..{to} on {release}"); + if queries { + assert_eq!(queried, Some(lines), "{what}"); + } else if let Some(queried) = queried { + assert_eq!(queried, lines, "{what}"); + } } } }; @@ -369,6 +406,10 @@ fn the_kernel_s_answer_for_a_window_is_the_maps_lines_answer() { let protected = unsafe { libc::mprotect(page_at(1), page as usize, libc::PROT_READ) }; assert_eq!(protected, 0); check("the middle page read-only"); + // SAFETY: as above; its middle page loses every access. + let protected = unsafe { libc::mprotect(page_at(1), page as usize, libc::PROT_NONE) }; + assert_eq!(protected, 0); + check("the middle page without access"); // SAFETY: as above; its last page goes. assert_eq!(unsafe { libc::munmap(page_at(2), page as usize) }, 0); check("the last page unmapped"); @@ -376,17 +417,20 @@ fn the_kernel_s_answer_for_a_window_is_the_maps_lines_answer() { assert_eq!(unsafe { libc::munmap(at, 2 * page as usize) }, 0); } -/// The answers for windows `[start, end)` in a child forked now: the maps lines' answer -/// ([`writable`](crate::host_memory::writable)) and the kernel's -/// ([`queried_writable`](crate::host_memory::queried_writable)), from one snapshot. The child's -/// address space is this process's at the fork, and its one thread maps nothing. It asks the -/// kernel and copies its maps text to a pipe without allocating (a fork of a multithreaded -/// process leaves only async-signal-safe calls safe; another thread may have held `malloc`'s lock) -/// and ends with `_exit`, which runs no exit handler; this process reads the lines' answers from -/// the copy. +/// The answers for windows `[start, end)` in a child forked now, for write permission and for +/// read permission: the maps lines' answer ([`permitted`](crate::host_memory::permitted)) and the +/// kernel's ([`queried_permitted`](crate::host_memory::queried_permitted)), from one snapshot. +/// The child's address space is this process's at the fork, and its one thread maps nothing. It +/// asks the kernel and copies its maps text to a pipe without allocating (a fork of a +/// multithreaded process leaves only async-signal-safe calls safe; another thread may have held +/// `malloc`'s lock) and ends with `_exit`, which runs no exit handler; this process reads the +/// lines' answers from the copy. #[cfg(target_os = "linux")] -fn window_answers(windows: &[(u64, u64); N]) -> [(bool, Option); N] { - use crate::host_memory::writable; +fn window_answers( + windows: &[(u64, u64); N], + access: Access, +) -> [(bool, Option); N] { + use crate::host_memory::permitted; use std::io::Read; use std::os::fd::FromRawFd; let mut pipe = [0; 2]; @@ -400,7 +444,7 @@ fn window_answers(windows: &[(u64, u64); N]) -> [(bool, Option(windows: &[(u64, u64); N]) -> [(bool, Option(sink: i32, windows: &[(u64, u64); N]) -> i32 { - use crate::host_memory::queried_writable; +fn send_window_answers( + sink: i32, + windows: &[(u64, u64); N], + access: Access, +) -> i32 { + use crate::host_memory::queried_permitted; use std::os::fd::FromRawFd; let send = |mut bytes: &[u8]| { while !bytes.is_empty() { @@ -464,12 +513,13 @@ fn send_window_answers(sink: i32, windows: &[(u64, u64); N]) -> } // SAFETY: `fd` is the file just opened, which the `File` owns from here. let maps = unsafe { std::fs::File::from_raw_fd(fd) }; - let answers = windows.map( - |(start, end)| match queried_writable(&maps, start, end, &mut 0) { - None => 0, - Some(writable) => 1 | (u8::from(writable) << 1), - }, - ); + let answers = + windows.map( + |(start, end)| match queried_permitted(&maps, start, end, access, &mut 0) { + None => 0, + Some(permitted) => 1 | (u8::from(permitted) << 1), + }, + ); if !send(&answers) { return 3; } diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index f096842cc..ffb4a8f02 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -80e091a01f7206d78ce68c7d42a45e6c4d6b9d5330f575d921dbc821ce5acb72 +ae11e49b0ae007b1a9659a6c39a2e4247fd794c8472282a24ec6530cab3fb76f diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 3ea61220e..685c2e7f9 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 479; /// 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 = 1698; +pub const RUNTIME_VERSION: u32 = 1699; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/docs/API.md b/docs/API.md index 06b88deef..23eeaaf57 100644 --- a/docs/API.md +++ b/docs/API.md @@ -2507,8 +2507,11 @@ bound. the device's own, which no import maps (a heap's textures shadows of its bytes): the caller's gate (`HostMemory::with_import_gate`) refused the pages' import, or the import the device and the gate admitted failed (out of memory, or another Vulkan error, such as a driver out - of the mappings the host kernel allows). Pages the process cannot read are never copied: the - buffer is refused, as their import is. A copy whose own allocation fails refuses the call + of the mappings the host kernel allows). The copy reads the pages through the kernel, and + where the kernel cannot (on Linux it pins each page, which a dma-buf's mapping does not allow), + with plain loads where the process maps every page readable. Pages not mapped, or mapped + without read permission, are never copied: the buffer is refused, as their import is. A copy + whose own allocation fails refuses the call (`OutOfMemory`). A heap's rebind and memory whose GPU writes Metal's private option bit 24 drops are never copied. Counted: `WorkCounts::copied_host_buffers_made`, of them `copied_host_buffers_refused` and `copied_host_buffers_degraded` (and `copied_heaps_made`, diff --git a/docs/FAST-PATHS.md b/docs/FAST-PATHS.md index 95aa7b45c..0c35f2c5b 100644 --- a/docs/FAST-PATHS.md +++ b/docs/FAST-PATHS.md @@ -319,8 +319,10 @@ driver's. Each is open work. - **A copied host buffer costs O(its size) at every commit and every batch's completion** (`copied.rs`, `copied-host-pages`): each compares every byte of every live copy with the bytes the copy and the pages last agreed on, whichever buffers the work names, where a page log or the - work's uses could bound it. A copy is made only where the caller's gate refuses an import or an - admitted import fails, never by default. + work's uses could bound it: a live 64 MiB copy added 45 to 68 ms to each empty command buffer's + commit and wait (0.2 ms without) on an RTX 5080 laptop (Intel Core Ultra 9 275HX). A copy is + made only where the caller's gate refuses an import or an admitted import fails, never by + default. - **A copied host buffer's merge keeps the CPU's byte where the CPU and the GPU both wrote it** between a commit and the completion: bytes are merged one at a time, so a GPU write never rewrites a byte beside it, but a byte both wrote keeps the CPU's, where on Metal the later write diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 638f9f9be..6d413bebe 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -336,8 +336,11 @@ Each commit writes into the copy every byte the CPU changed in the pages since t pages last agreed, and each batch's completion writes back every byte the GPU changed, before its handlers run or a waiter returns, keeping a byte the CPU changed since (`copied_copy_in_bytes`, `copied_merge_back_bytes`). Each compares every byte of every live copy, so keep copies few. A -texture over a copied buffer is a shadow of its bytes. Pages the process cannot read are never -copied: the buffer is refused, as their import is. +texture over a copied buffer is a shadow of its bytes. The copy reads the pages through the kernel +first, and where the kernel cannot read them, with plain loads where the process maps every page +with read permission: on Linux the kernel's read pins each page, which a mapping of a dma-buf +(`VM_PFNMAP`) does not allow. Pages not mapped, or mapped +without read permission, are never copied: the buffer is refused, as their import is. A no-copy heap's own buffer is copied the same way (`copied_heaps_made`): its buffers lie in the copy, and its textures are shadows of its bytes. `Buffer::rebind_bytes_no_copy` gives the buffer a