diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index a1ace1dbe..73359a6cf 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -629,8 +629,12 @@ consumer's. one after the refusal in the host-cached type. - `Device::import_dma_buf(fd, len, release)` (unix) imports a dma-buf (`VK_EXT_external_memory_dma_buf`) only on a device whose Shared memory type is host-coherent, - only into the first memory type the fd's query offers, and only where that type is host-visible - and host-coherent and the buffer's requirements list it. A device whose Shared type is not + and only into a host-visible, host-coherent type the buffer's requirements list, chosen once + from the fd's query (`vkGetMemoryFdPropertiesKHR`). The query's first type is the driver's word + for where such an import lives. Where it is a host-visible, host-coherent type the requirements + list, the import takes it. Where it is device-local, the import takes the first type the query + offers that the requirements list and that is device-local, host-visible and host-coherent, in + that first type's own heap. Anything else is refused. A device whose Shared type is not host-coherent (Shared memory's coherence) refuses every dma-buf with `Limit::ImportCoherence`, whatever its query offers; anything else is `Limit::ImportType`; nothing is imported after either. It takes the fd (the consumer's @@ -687,8 +691,12 @@ imports, a GPU write reaches them, where Metal drops it. The two rules differ because a failed dma-buf import is not harmless: on NVIDIA's Linux driver (620.70.06, an RTX 3090) one failed dma-buf import into a later type the query offered broke every -later allocation of that type, the Shared type among them, so the dma-buf rule attempts nothing it -is not sure of. +later allocation of that type, the Shared type among them, so the dma-buf rule makes one choice and +one import, never trying a type after another, and takes a later type only of the first type's own +device memory. On the RTX 2080 and the RTX 3090 (620.70.06) a udmabuf's query offers type 0, which +has no property flag, and type 4, host-visible, host-coherent and host-cached, both of the host +heap: the first is neither a coherent type nor device memory, so the import is refused there (jobs +m3-max-78547 and m3-max-78667). They differ in coherence too. A type's `VK_MEMORY_PROPERTY_HOST_COHERENT_BIT` speaks only for the mappings Vulkan makes (`vkMapMemory`); Vulkan promises nothing for writes outside them, and the @@ -1227,33 +1235,31 @@ exported block, an exported surface in either form, and a Direct3D 11 import. remove are 3.54 GB of the 40.49 GB a guest's run of the same compute benchmark copies over its imports (job m3-max-68603), under 5% of each workload's time (above), so it stays a known gap. The runtime asks the `LINEAR` tiling alone. -- On the Iris Xe (ANV, Mesa 26.2.6) the dma-buf query offers a device-local-only type first, so - its dma-bufs are refused with `Limit::ImportType`, and a consumer imports those pages by pointer. - Its sparse buffers import no dma-buf either, so `Device::import_dma_bufs` refuses there, as it - does on the RTX 3090 (NVIDIA 620.70.06). +- On the Iris Xe of RPL-P (ANV, Mesa 26.2.6, the i915 kernel driver) a udmabuf's query offers + types 0 to 6, the first device-local only, and the buffer lists 0 to 2, all of one heap: the + dma-buf rule takes type 1, device-local, host-visible and host-coherent (job m3-max-78652). + There the GPU read 65,536 bytes the guest's side wrote through its own mapping after the import, + none stale, and the guest's side read a GPU fill of them, none stale, with no flush or + invalidate call (the same job). That run and the Shared type's flag are all that stand for the + import's coherence on that device: no Vulkan query says whether a driver's GPU mapping of + another driver's dma-buf sees the CPU's caches (Imported blocks), and a stale read would show + only as a wrong value. On an Xe2 device under the xe kernel driver the same table as the lab's + Iris Xe on types 0 to 2 was read from a reporter's log, so the rule takes type 1 there too; it + was not run on that chip. Under xe, Mesa's Intel driver binds an imported object with its + cached-coherent caching entry (`anv_device_get_pat_entry`, as read in Mesa's source). The Iris + Xe's sparse buffers import no dma-buf, so `Device::import_dma_bufs` refuses there, as it does on + the RTX 3090 (NVIDIA 620.70.06). - Under AMD's open Linux driver (AMDVLK 2025.Q2.1, LLPC) on a Radeon 780M (1002:15bf, and the - same on a 1002:1900), no no-copy import takes a guest's pages, so the consumer copies them. The - pages are shared mappings of memfds, and their dma-buf is a udmabuf of the memfd's pages. - `Device::import_dma_buf` refuses with `Limit::ImportType`: the fd's query offers every memory - type (0xffff), and the first, the only one the dma-buf rule takes (Imported blocks), is not - host-visible and host-coherent. `Device::import_host_memory` of the same pages fails in the - driver, an `Error::Vulkan` of `vkAllocateMemory` with `VK_ERROR_INVALID_EXTERNAL_HANDLE`: - both AMD Linux drivers on that card import a pointer to private anonymous pages only, and refuse - shared or file-backed pages such as the guest's. + same on a 1002:1900), `Device::import_host_memory` of a guest's pages fails in the driver, an + `Error::Vulkan` of `vkAllocateMemory` with `VK_ERROR_INVALID_EXTERNAL_HANDLE`: both AMD Linux + drivers on that card import a pointer to private anonymous pages only, and refuse shared or + file-backed pages such as the guest's, which are shared mappings of memfds. `Device::dma_buf_granule` is `None` there, so pages that span more than one dma-buf holds have - no dma-buf route. Under RADV (Mesa 26.2.6) on the same card the same pages import as dma-bufs - (`import_dma_buf`, and `import_dma_bufs` where they span more than one holds). In one guest run - of a GPU compute benchmark from a cold boot on the 1002:15bf, the consumer copied the pages of - 1,693 imports of no-copy buffers and heaps: 1,491 that both calls refused, 165 that span more - than one dma-buf holds, and 37 read-only ones, which it copies on every device (no import is - read-only, Imported blocks). The writable copies took part in 17,083 commits, compared 1.82 TB, - and wrote 0.98 GB to the copies and 60.46 GB back to the pages. The copies' syncs took 230.2 s - of the consumer's CPU on the committing and completion threads. In a run of the same benchmark - under RADV on the same card, 1,622 imports were dma-bufs (168 of them over several), 32 were - read-only copies, and the copies' syncs took 5.7 ms. On a Radeon 780M (1002:1900) under AMD's Windows driver - (26.11.2, LLPC), in a guest session (not that benchmark run), all 998 of the consumer's - host-pointer imports took the pages in place, none refused, and its 97 copies were the - read-only ones. + no dma-buf route, and the consumer copies them. Under RADV (Mesa 26.2.6) on the same card the + same pages import as dma-bufs (`import_dma_buf`, and `import_dma_bufs` where they span more + than one holds). On a Radeon 780M (1002:1900) under AMD's Windows driver (26.11.2, LLPC), in a + guest session, all 998 of the consumer's host-pointer imports took the pages in place, none + refused, and its 97 copies were the read-only ones. - An exported surface takes the copy form, its planes copied at each acquire and release, in four cases the build found. A copy form's planes are textures over a buffer in the exported block, which is Private, so the CPU's `replace_region` and `get_bytes` on them are refused @@ -1368,7 +1374,8 @@ exported block, an exported surface in either form, and a Direct3D 11 import. `Metrics::over_copies_imported`): its bytes are copied into an image of its own before the submissions that use it, and back after a command writes it. This is by handle type, not by host: the guest pages of the Mac and Windows hosts, which import by address, and on Linux any - pages not imported as a dma-buf (on the Iris Xe and the RTX 3090, all of them). An image bound + pages not imported as a dma-buf (on the RTX 3090, all of them; on the Iris Xe, those one dma-buf + cannot hold, Imported blocks). An image bound in imported memory is made for the import's handle, so "initialLayout must be `VK_IMAGE_LAYOUT_UNDEFINED`" (`VUID-VkImageCreateInfo-pNext-01443`), and a move out of the undefined layout keeps no bytes. Over a dma-buf, an acquire from the other side keeps them @@ -1404,16 +1411,17 @@ exported block, an exported surface in either form, and a Direct3D 11 import. cannot be bound in the buffer's import: "If image requires a dedicated allocation (as reported by vkGetImageMemoryRequirements2 in VkMemoryDedicatedRequirements::requiresDedicatedAllocation for image), memory must have been created with VkMemoryDedicatedAllocateInfo::image equal to - image" (`VUID-vkBindImageMemory-image-01445`). On the Iris Xe (ANV) and the RTX 3090 (NVIDIA) - the runtime imports no guest dma-buf: the dma-buf rule imports only into the first type the - fd's query offers, and only where that type is host-visible and host-coherent (on NVIDIA's - driver one failed import into a later type broke every later allocation of that type, Imported - blocks), and the first type those devices offer is not. Their pages take the host-memory import - above. On the Iris Xe the consumer's own no-copy pages stay the counted copy at each submission - for a second reason too: one dma-buf holds only what udmabuf's stock limit of 1,024 runs - allows (about 4 MiB of a guest buffer), and the runtime binds several dma-bufs behind one buffer - only where the device has a granule, which the Iris Xe has not (Imported blocks). Each of these - is a known gap, reopened only by a measured copied share above 5% of a frame on that card. + image" (`VUID-vkBindImageMemory-image-01445`). On the RTX 3090 (NVIDIA) the runtime imports no + guest dma-buf: the first type the fd's query offers there is neither a coherent type nor device + memory (Imported blocks), so its pages take the host-memory import above. On the Iris Xe (ANV) + a dma-buf is imported into type 1, and a texture over a buffer in that import is in place, its + move home one acquire and no copy, at a pitch of 256 bytes and as a render target at 32 (job + m3-max-78694). There the consumer's no-copy pages stay the counted copy where one dma-buf cannot + hold them: one dma-buf holds only what udmabuf's stock limit of 1,024 runs allows (about 4 MiB + of a guest buffer), and the runtime binds several dma-bufs behind one buffer only where the + device has a granule, which the Iris Xe has not (Imported blocks), so such pages take the + host-memory import above. Each of these is a known gap, reopened only by a measured copied share + above 5% of a frame on that card. - A texture over a buffer in an import over several dma-bufs (`Device::import_dma_bufs`) is the counted copy too: the block's buffer is sparse, bound to one import per dma-buf. - A texture over a buffer in an exported block is the counted copy of a texture over a buffer on diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index fd4c8014c..f937a168a 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -2254,9 +2254,11 @@ pub enum Limit { handle: ImportHandle, }, /// An import whose handle's memory type query offers no type the import takes, so nothing is - /// imported: for a dma-buf, the first type the fd's query offers is not host-visible and - /// host-coherent, or the buffer's memory requirements do not list it; for several, that holds - /// of one fd, or one fd's type is not the first fd's, which `listed` then names alone; for + /// imported: for a dma-buf, the first type the fd's query offers is neither host-visible and + /// host-coherent with the buffer's memory requirements listing it, nor device-local with a + /// device-local, host-visible and host-coherent type of its heap offered and listed (the + /// dma-buf rule, `Device::import_dma_buf`); for several, that holds of one fd, or one fd's + /// type is not the first fd's, which `listed` then names alone; for /// host memory, the pointer's query offers no type that is both and that the requirements /// list; for a Direct3D 11 texture, the handle's properties /// (`vkGetMemoryWin32HandlePropertiesKHR`) and the plane image's requirements share no type. diff --git a/crates/metal2vulkan-runtime/src/import.rs b/crates/metal2vulkan-runtime/src/import.rs index 3496616d5..025129e7c 100644 --- a/crates/metal2vulkan-runtime/src/import.rs +++ b/crates/metal2vulkan-runtime/src/import.rs @@ -6,10 +6,15 @@ //! handle's query, and each a block the consumer places buffers in as it places them in a block //! it took. //! -//! The two rules differ. A dma-buf is imported only into the first type its fd's query offers, -//! and only where that type is host-visible and host-coherent: on NVIDIA's Linux driver -//! (620.70.06) one failed dma-buf import into a later type broke every later allocation of that -//! type, the Shared type among them, so the rule attempts nothing it is not sure of. And it is +//! The two rules differ. A dma-buf's rule reads the first type its fd's query offers as the +//! driver's word for where such an import lives: a mappable, coherent view of the memory, which it +//! takes where the buffer lists it and it is host-visible and host-coherent; or the device's own +//! memory, where it is device-local, and then the rule takes the first type offered that the +//! buffer lists and that is device-local, host-visible and host-coherent, in that first type's own +//! heap. Anything else is refused. It makes one choice from the query and one import, and never +//! tries a type after another: on NVIDIA's Linux driver (620.70.06) one failed dma-buf import into +//! a later type broke every later allocation of that type, the Shared type among them, so the rule +//! attempts nothing it is not sure of. And it is //! imported only on a device whose Shared type is host-coherent (one that holds no //! `crate::coherence::Coherence`), and refused elsewhere ([`Limit::ImportCoherence`]). The //! consumer writes the pages through its own cached mapping, which no Vulkan flush reaches; a @@ -81,6 +86,47 @@ pub(crate) struct Imports { pub(crate) sparse: Option, /// The host-visible and host-coherent memory types, one bit each. pub(crate) coherent: u32, + /// What the dma-buf rule reads of the device's memory types ([`dma_buf_type`]). + #[cfg(unix)] + pub(crate) dma_buf_types: DmaBufTypes, +} + +/// What the dma-buf rule reads of the device's memory types ([`dma_buf_type`]). +#[cfg(unix)] +#[derive(Clone, Copy, Debug)] +pub(crate) struct DmaBufTypes { + /// The host-visible and host-coherent types, one bit each. + pub(crate) coherent: u32, + /// The device-local types, one bit each. + pub(crate) device_local: u32, + /// For each type, the types of its heap, one bit each; 0 past the device's types. + pub(crate) heaps: [u32; vk::MAX_MEMORY_TYPES], +} + +#[cfg(unix)] +impl DmaBufTypes { + /// Of the device's memory `types`. + pub(crate) fn of(types: &[vk::MemoryType]) -> DmaBufTypes { + let with = |flags: vk::MemoryPropertyFlags| { + (0u32..) + .zip(types) + .filter(|(_, kind)| kind.property_flags.contains(flags)) + .fold(0, |bits, (index, _)| bits | 1 << index) + }; + let heaps = std::array::from_fn(|index| { + types.get(index).map_or(0, |kind| { + (0u32..) + .zip(types) + .filter(|(_, other)| other.heap_index == kind.heap_index) + .fold(0, |bits, (other, _)| bits | 1 << other) + }) + }); + DmaBufTypes { + coherent: with(COHERENT), + device_local: with(vk::MemoryPropertyFlags::DEVICE_LOCAL), + heaps, + } + } } impl Imports { @@ -136,6 +182,8 @@ impl Imports { .zip(memory.memory_types_as_slice()) .filter(|(_, kind)| kind.property_flags.contains(COHERENT)) .fold(0, |bits, (index, _)| bits | 1 << index); + #[cfg(unix)] + let dma_buf_types = DmaBufTypes::of(memory.memory_types_as_slice()); Imports { host, #[cfg(unix)] @@ -143,6 +191,8 @@ impl Imports { #[cfg(unix)] sparse: None, coherent, + #[cfg(unix)] + dma_buf_types, } } @@ -422,30 +472,46 @@ const COHERENT: vk::MemoryPropertyFlags = vk::MemoryPropertyFlags::from_raw( | vk::MemoryPropertyFlags::HOST_COHERENT.as_raw(), ); -/// The dma-buf rule, for an import of `handle`: on a device whose Shared type is host-coherent -/// (`shared_coherent`: the device holds no `crate::coherence::Coherence`), the first type the -/// fd's query `offered`, where the buffer's requirements `listed` it and it is one of the -/// `coherent` types. Err: [`Limit::ImportCoherence`] on a device whose Shared type is not, whatever -/// is offered; [`Limit::ImportType`] where the first type offered is not taken, whatever else is. +/// The dma-buf rule, for an import of `handle`, on a device whose Shared type is host-coherent +/// (`shared_coherent`: the device holds no `crate::coherence::Coherence`), over the types the +/// fd's query `offered` and the buffer's requirements `listed`. The first type offered is either +/// a mappable, coherent view of the memory or the device's own memory: where it is listed, +/// host-visible and host-coherent, the rule takes it; where it is device-local, the rule takes the +/// first type offered that is listed, device-local, host-visible and host-coherent, in that first +/// type's own heap. Anything else is refused. One choice from the query, then one import: no type +/// is tried after another, as on NVIDIA's Linux driver (620.70.06) one failed dma-buf import into +/// a later type broke every later allocation of that type. Err: [`Limit::ImportCoherence`] on a +/// device whose Shared type is not host-coherent, whatever is offered; [`Limit::ImportType`] where +/// the rule takes no type. #[cfg(unix)] pub(crate) fn dma_buf_type( handle: ImportHandle, shared_coherent: bool, offered: u32, listed: u32, - coherent: u32, + types: &DmaBufTypes, ) -> Result { if !shared_coherent { return Err(Limit::ImportCoherence { handle }); } + let refused = Limit::ImportType { + handle, + offered, + listed, + }; let first = offered.trailing_zeros(); - (first < u32::BITS && (listed & coherent) & (1 << first) != 0) - .then_some(first) - .ok_or(Limit::ImportType { - handle, - offered, - listed, - }) + let Some(&heap) = types.heaps.get(first as usize) else { + return Err(refused); + }; + let lead = 1 << first; + if listed & types.coherent & lead != 0 { + return Ok(first); + } + if types.device_local & lead == 0 { + return Err(refused); + } + let taken = offered & listed & types.coherent & types.device_local & heap; + (taken != 0).then(|| taken.trailing_zeros()).ok_or(refused) } /// The host-memory rule: the first type the pointer's query `offered` that the buffer's @@ -462,11 +528,13 @@ impl Device { /// the host reaches the bytes through the consumer's own mappings of the pages, so the /// block's `contents` is `None`, and its zero mark is 0. /// - /// It imports only on a device whose Shared memory type is host-coherent, only into the first - /// memory type the fd's query (`vkGetMemoryFdPropertiesKHR`) offers, and only where that type - /// is host-visible and host-coherent and the buffer's memory requirements list it, and returns - /// the block with the index of that type. Every refusal comes before any allocation is - /// attempted, with nothing imported. + /// It imports only on a device whose Shared memory type is host-coherent, into the type the + /// dma-buf rule takes from the fd's query (`vkGetMemoryFdPropertiesKHR`) and the buffer's + /// memory requirements: the first type offered, where the requirements list it and it is + /// host-visible and host-coherent; else, where that first type is device-local, the first + /// type offered that the requirements list and that is device-local, host-visible and + /// host-coherent, in the first type's heap. It returns the block with the index of that type. + /// Every refusal comes before any allocation is attempted, with nothing imported. /// /// The call takes `fd`, the consumer's own fd of the dma-buf (a dup of it, where the consumer /// keeps one). After `Ok` the driver owns it. After a refusal (`Limit`, [`Error::Quiesced`]) @@ -532,7 +600,7 @@ impl Device { shared_coherent, offered, listed, - core.imports.coherent, + &core.imports.dma_buf_types, ) .map_err(Error::Limit)?; check_size(handle, len, &needs)?; @@ -698,7 +766,7 @@ impl Device { shared_coherent, offered, listed, - core.imports.coherent, + &core.imports.dma_buf_types, ) { Ok(taken) => index = Some(taken), Err(refusal) => { diff --git a/crates/metal2vulkan-runtime/src/tests/import.rs b/crates/metal2vulkan-runtime/src/tests/import.rs index 5b93a429e..3da6bd3d4 100644 --- a/crates/metal2vulkan-runtime/src/tests/import.rs +++ b/crates/metal2vulkan-runtime/src/tests/import.rs @@ -16,34 +16,119 @@ use crate::import::host_type; #[cfg(unix)] use crate::{ImportHandle, Limit}; -/// The dma-buf rule takes the first type the fd's query offers, only where it is host-visible, -/// host-coherent and listed by the buffer's requirements; never a later one. +/// The dma-buf rule's view of a memory table of `(flags, heap)` types. +#[cfg(unix)] +fn table(types: &[(ash::vk::MemoryPropertyFlags, u32)]) -> crate::import::DmaBufTypes { + let types: Vec = (types.iter()) + .map(|&(flags, heap)| { + ash::vk::MemoryType::default() + .property_flags(flags) + .heap_index(heap) + }) + .collect(); + crate::import::DmaBufTypes::of(&types) +} + +/// The dma-buf rule over the three shapes of the lab's tables, each type as its device lists it +/// with its heap, and a udmabuf's query and buffer list as the device answered them: +/// +/// - RADV's (the Radeon 780M of Hawk Point, Mesa 26.2.6, job m3-max-78548): the query offers 5, +/// 11 and 16, and the first, 5, is host-visible and host-coherent and listed: the rule takes +/// it, as the rule before it did. +/// - ANV's on the Iris Xe of RPL-P (Mesa 26.2.6, i915, job m3-max-78652; 0 device-local, 1 that, +/// host-visible and host-coherent, 2 that and host-cached, and 3 to 6 again, all of one heap): +/// the query offers 0 to 6 and the buffer lists 0 to 2, and the first, 0, is device memory: the +/// rule takes 1, the first offered and listed type of its heap that is device-local, +/// host-visible and host-coherent, where the rule before it refused. Where that type is of +/// another heap, it is refused. +/// - NVIDIA's on the RTX 2080 (620.70.06, job m3-max-78547): the query offers 0, which has no +/// property flag, and 4, host-visible, host-coherent and host-cached, both in heap 1: the first +/// is neither a coherent view nor device memory, so the import is refused, as before. #[cfg(unix)] #[test] -fn a_dma_buf_takes_only_the_first_type_offered() { +fn a_dma_buf_takes_the_first_offered_type_or_a_coherent_type_of_its_device_memory() { use crate::import::dma_buf_type; - // Coherent types 1, 2, 3, 4 and 5; the buffer lists 0 to 5. - let coherent = 0b11_1110; - let listed = 0b11_1111; - let cases = [ - // The first offered (0) is not coherent: refused, though 4 is offered and coherent. - (0x11, None), - (0x7f, None), - // The first offered (5) is coherent and listed. - (0x420, Some(5)), - (0x20, Some(5)), - // The first offered (1) is coherent but not listed by a buffer that lists 0 and 2. - (0x06, None), - (0, None), - ]; - for (offered, expected) in cases { - let listed = if offered == 0x06 { 0b101 } else { listed }; + use ash::vk::MemoryPropertyFlags as F; + let (dl, hv, hc, cached) = ( + F::DEVICE_LOCAL, + F::HOST_VISIBLE, + F::HOST_COHERENT, + F::HOST_CACHED, + ); + let handle = ImportHandle::DmaBuf; + let refused = |offered, listed| { + Err(Limit::ImportType { + handle, + offered, + listed, + }) + }; + let radv = table(&[ + (dl, 1), + (dl, 1), + (hv | hc, 0), + (dl | hv | hc, 1), + (dl | hv | hc, 1), + (hv | hc | cached, 0), + (hv | hc | cached, 0), + (dl, 1), + (dl, 1), + (dl, 1), + (dl, 1), + (F::empty(), 0), + (F::empty(), 0), + (dl, 1), + (hv | hc, 0), + (dl | hv | hc, 1), + (hv | hc | cached, 0), + ]); + assert_eq!(dma_buf_type(handle, true, 0x10820, 0x1eaad, &radv), Ok(5)); + // The first offered, coherent but not listed, and not device memory: refused. + assert_eq!( + dma_buf_type(handle, true, 0x10820, 0x1eaad & !0x20, &radv), + refused(0x10820, 0x1eaad & !0x20) + ); + let iris = table(&[ + (dl, 0), + (dl | hv | hc, 0), + (dl | hv | hc | cached, 0), + (dl, 0), + (dl, 0), + (dl | hv | hc, 0), + (dl | hv | hc | cached, 0), + ]); + assert_eq!(dma_buf_type(handle, true, 0x7f, 0b111, &iris), Ok(1)); + assert_eq!(dma_buf_type(handle, true, 0b101, 0b111, &iris), Ok(2)); + // Nothing coherent offered, or nothing coherent listed: refused. + for (offered, listed) in [(0b001, 0b111), (0b111, 0b001)] { assert_eq!( - dma_buf_type(ImportHandle::DmaBuf, true, offered, listed, coherent).ok(), - expected, - "offered {offered:#x}" + dma_buf_type(handle, true, offered, listed, &iris), + refused(offered, listed), + "offered {offered:#x}, listed {listed:#x}" ); } + // A coherent device-local type of another heap than the first offered type's: refused. + let apart = table(&[(dl, 0), (dl | hv | hc, 1)]); + assert_eq!( + dma_buf_type(handle, true, 0b11, 0b11, &apart), + refused(0b11, 0b11) + ); + let rtx_2080 = table(&[ + (F::empty(), 1), + (dl, 0), + (dl, 0), + (hv | hc, 1), + (hv | hc | cached, 1), + (dl | hv | hc, 2), + ]); + assert_eq!( + dma_buf_type(handle, true, 0x11, 0x3b, &rtx_2080), + refused(0x11, 0x3b) + ); + assert_eq!( + dma_buf_type(handle, true, 0, 0b111, &iris), + refused(0, 0b111) + ); } /// The dma-buf rule over Meteor Lake's types under Mesa's Intel driver and the i915 kernel driver @@ -61,7 +146,7 @@ fn a_dma_buf_takes_only_the_first_type_offered() { fn a_dma_buf_is_refused_where_the_shared_type_is_not_host_coherent() { use crate::coherence::Coherence; use crate::floor::choose; - use crate::import::dma_buf_type; + use crate::import::{dma_buf_type, DmaBufTypes}; use crate::tests::floor::memory; use ash::vk::MemoryPropertyFlags as F; let local = F::DEVICE_LOCAL; @@ -86,16 +171,17 @@ fn a_dma_buf_is_refused_where_the_shared_type_is_not_host_coherent() { ); let coherent = coherent_bits(&meteor_lake); assert_eq!(coherent, 0b01); + let rule = &DmaBufTypes::of(meteor_lake.memory_types_as_slice()); let (offered, listed) = (0b11, 0b11); // The rule without the state, as it stood: type 0. assert_eq!( - dma_buf_type(ImportHandle::DmaBuf, true, offered, listed, coherent), + dma_buf_type(ImportHandle::DmaBuf, true, offered, listed, rule), Ok(0) ); // Keyed by the state: refused, for one dma-buf and for several. for handle in [ImportHandle::DmaBuf, ImportHandle::DmaBufs] { assert_eq!( - dma_buf_type(handle, !held, offered, listed, coherent), + dma_buf_type(handle, !held, offered, listed, rule), Err(Limit::ImportCoherence { handle }), "{handle:?}" ); @@ -103,7 +189,7 @@ fn a_dma_buf_is_refused_where_the_shared_type_is_not_host_coherent() { // Whatever the fd offers. for offered in [0b01, 0b10] { assert_eq!( - dma_buf_type(ImportHandle::DmaBuf, !held, offered, listed, coherent), + dma_buf_type(ImportHandle::DmaBuf, !held, offered, listed, rule), Err(Limit::ImportCoherence { handle: ImportHandle::DmaBuf }), @@ -132,10 +218,11 @@ fn a_dma_buf_is_refused_where_the_shared_type_is_not_host_coherent() { ); let coherent = coherent_bits(&reported); assert_eq!(coherent, 0b01001); + let rule = &DmaBufTypes::of(reported.memory_types_as_slice()); for handle in [ImportHandle::DmaBuf, ImportHandle::DmaBufs] { for offered in [0b00001, 0b00010, 0b01000, 0b11011] { assert_eq!( - dma_buf_type(handle, !held, offered, 0b11011, coherent), + dma_buf_type(handle, !held, offered, 0b11011, rule), Err(Limit::ImportCoherence { handle }), "{handle:?}, offered {offered:#x}" ); @@ -150,13 +237,13 @@ fn a_dma_buf_is_refused_where_the_shared_type_is_not_host_coherent() { assert_eq!(types.shared, 2); let held = Coherence::of(&iris, types, 64).is_some(); assert!(!held, "no coherence state for a coherent Shared type"); - let coherent = coherent_bits(&iris); + let rule = &DmaBufTypes::of(iris.memory_types_as_slice()); assert_eq!( - dma_buf_type(ImportHandle::DmaBuf, !held, 0b110, 0b111, coherent), + dma_buf_type(ImportHandle::DmaBuf, !held, 0b110, 0b111, rule), Ok(1) ); assert_eq!( - dma_buf_type(ImportHandle::DmaBuf, !held, 0b001, 0b111, coherent), + dma_buf_type(ImportHandle::DmaBuf, !held, 0b001, 0b111, rule), Err(Limit::ImportType { handle: ImportHandle::DmaBuf, offered: 0b001, @@ -1038,7 +1125,8 @@ pub(crate) mod on_device { let listed = crate::memory::import_requirements(device.core(), LEN, dma_buf_ext) .memory_type_bits; let coherent = device.core().imports.coherent; - let unkeyed = dma_buf_type(ImportHandle::DmaBuf, true, offered, listed, coherent); + let rule = &device.core().imports.dma_buf_types; + let unkeyed = dma_buf_type(ImportHandle::DmaBuf, true, offered, listed, rule); let (release, released) = releasing(); match device.import_dma_buf(fd, LEN, release) { Err(Error::Limit(Limit::ImportCoherence { @@ -1119,15 +1207,103 @@ pub(crate) mod on_device { }); } - /// A dma-buf is imported where the first type its fd's query offers is host-visible and - /// host-coherent, and a GPU fill reaches its pages; elsewhere it is refused at the query with - /// nothing imported, and an ordinary Shared allocation and a host-memory import still - /// succeed after it. A device that does not import a dma-buf refuses it typed, and so does a - /// device whose Shared type is not host-coherent (under `m2v_shared_view`). + /// The dma-buf type the rule takes on each device, nothing imported, printed with what it + /// rests on: the query of a udmabuf's fd, the buffer's list, each type's flags and heap, the + /// type the rule takes, and the type the rule before it took (the first type offered, where + /// that is listed, host-visible and host-coherent). The type taken is the first offered where + /// that one is listed and coherent; else the first offered is device-local, and the type + /// taken is offered, listed, device-local and coherent, in the first offered type's heap, with + /// no such type of that heap before it. #[cfg(target_os = "linux")] #[test] - fn every_device_imports_a_dma_buf_only_into_its_first_offered_type() { + fn every_device_takes_its_dma_buf_type_by_the_rule() { use crate::import::dma_buf_type; + use std::os::fd::AsRawFd; + use vk::MemoryPropertyFlags as F; + each_device("dma_buf_rule", |name, _, device| { + const LEN: u64 = 64 << 10; + let Some((fd, _memfd)) = dma_buf(LEN) else { + println!("dma-buf rule: {name}: no /dev/udmabuf here"); + return; + }; + let core = device.core(); + let Some(fds) = core.imports.dma_buf.as_ref() else { + println!("dma-buf rule: {name}: imports no dma-buf"); + return; + }; + let handle = vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT; + let mut properties = vk::MemoryFdPropertiesKHR::default(); + // SAFETY: the extensions are enabled; `fd` is open, and the query takes no ownership. + unsafe { fds.get_memory_fd_properties(handle, fd.as_raw_fd(), &mut properties) } + .unwrap_or_else(|error| panic!("{name}: the fd's query: {error}")); + let offered = properties.memory_type_bits; + let listed = crate::memory::import_requirements(core, LEN, handle).memory_type_bits; + let raw = device.raw(); + // SAFETY: the physical device is the instance's. + let types = unsafe { + (raw.instance).get_physical_device_memory_properties(raw.physical_device) + }; + let flags = |index: u32| { + let flags = types.memory_types[index as usize].property_flags; + let named = [ + (F::DEVICE_LOCAL, "DL"), + (F::HOST_VISIBLE, "HV"), + (F::HOST_COHERENT, "HC"), + (F::HOST_CACHED, "HCACHED"), + ]; + let names: Vec<&str> = (named.iter()) + .filter(|(flag, _)| flags.contains(*flag)) + .map(|(_, name)| *name) + .collect(); + names.join("|") + }; + let heap = |index: u32| types.memory_types[index as usize].heap_index; + let table: Vec = (0..types.memory_type_count) + .map(|index| format!("{index}:{}@{}", flags(index), heap(index))) + .collect(); + let rule = &core.imports.dma_buf_types; + let coherent = rule.coherent; + let shared_coherent = core.coherence.is_none(); + let taken = dma_buf_type(ImportHandle::DmaBuf, shared_coherent, offered, listed, rule); + let first = offered.trailing_zeros(); + let before = (shared_coherent && first < u32::BITS) + .then_some(first) + .filter(|&first| (listed & coherent) & (1 << first) != 0); + println!( + "dma-buf rule: {name}: offered {offered:#x}, listed {listed:#x}, types [{}]; \ + before (the first type offered): {before:?}; the rule: {:?}", + table.join(" "), + taken.ok() + ); + if let Some(taken) = taken.ok().filter(|&taken| Some(taken) != before) { + assert!( + before.is_none() && rule.device_local & (1 << first) != 0, + "{name}: type {taken} past a first offered type that is no device memory" + ); + let usable = offered & listed & coherent & rule.device_local; + assert!(usable & (1 << taken) != 0, "{name}: type {taken}"); + assert_eq!(heap(taken), heap(first), "{name}: type {taken}'s heap"); + let earlier_usable = (0..taken) + .filter(|&index| heap(index) == heap(first)) + .any(|index| usable & (1 << index) != 0); + assert!(!earlier_usable, "{name}: a usable type before {taken}"); + } + }); + } + + /// A dma-buf is imported where the dma-buf rule takes a type, and each side + /// reads the other's write with no flush or invalidate call: the guest's side writes the + /// pages through a shared mapping of the memfd after the import and the GPU copies them out, + /// then a GPU fill is read through the same mapping, each byte compared. Elsewhere it is + /// refused at the query with nothing imported, and an ordinary Shared allocation and a + /// host-memory import still succeed after it. A device that does not import a dma-buf refuses + /// it typed, and so does a device whose Shared type is not host-coherent (under + /// `m2v_shared_view`). + #[cfg(target_os = "linux")] + #[test] + fn every_device_imports_a_dma_buf_by_the_rule_and_each_side_reads_the_other_s_write() { + use crate::import::dma_buf_type; + use std::os::fd::AsRawFd; each_device("import_dma_buf", |name, _, device| { const LEN: u64 = 64 << 10; let Some((fd, memfd)) = dma_buf(LEN) else { @@ -1154,31 +1330,80 @@ pub(crate) mod on_device { (MemoryClass::Shared, None, LEN, 0), "{name}" ); + // SAFETY: a new shared mapping of the memfd's pages, the guest's side of them, + // unmapped below. + let base = unsafe { + libc::mmap( + std::ptr::null_mut(), + LEN as usize, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_SHARED, + memfd.as_raw_fd(), + 0, + ) + }; + assert_ne!(base, libc::MAP_FAILED, "{name}: a shared mapping"); + // SAFETY: the mapping spans `LEN` bytes, which nothing else on the host + // touches while it lasts. + let pages = + unsafe { std::slice::from_raw_parts_mut(base.cast::(), LEN as usize) }; let buffer = (device.new_buffer(block.id, 0, LEN, None)).expect("a buffer"); let queue = device.new_command_queue(4).expect("a queue"); - let command_buffer = queue.command_buffer().expect("a command buffer"); - let mut encoder = command_buffer.blit_command_encoder().expect("an encoder"); - encoder - .fill_buffer(&buffer, 0..LEN, 0x3c) - .unwrap_or_else(|error| panic!("{name}: {error}")); - encoder.end_encoding(); - command_buffer.commit().expect("a commit"); - finished(name, &command_buffer); - assert_eq!(command_buffer.error(), None, "{name}"); - let mut pages = vec![0u8; LEN as usize]; - let read = std::os::unix::fs::FileExt::read_exact_at( - &std::fs::File::from(memfd), - &mut pages, - 0, + let blit = |record: &dyn Fn(&mut crate::BlitCommandEncoder)| { + let command_buffer = queue.command_buffer().expect("a command buffer"); + let mut encoder = + command_buffer.blit_command_encoder().expect("an encoder"); + record(&mut encoder); + encoder.end_encoding(); + command_buffer.commit().expect("a commit"); + finished(name, &command_buffer); + assert_eq!(command_buffer.error(), None, "{name}"); + }; + // The guest's side writes after the import, with no flush call; the GPU + // copies the pages out. + let written: Vec = (0..LEN).map(|i| (i % 251) as u8 ^ 0x5a).collect(); + pages.copy_from_slice(&written); + let cpu = (device.take_block(MemoryClass::Shared, LEN)) + .unwrap_or_else(|error| panic!("{name}: a Shared block: {error}")); + let out = (device.new_buffer(cpu.id, 0, LEN, None)).expect("a buffer"); + blit(&|encoder| { + encoder + .copy_from_buffer_to_buffer(&buffer, 0, &out, 0, LEN) + .unwrap_or_else(|error| panic!("{name}: {error}")) + }); + let contents = out.contents().expect("a Shared buffer's contents"); + // SAFETY: the buffer spans `LEN` bytes, and the copy into it finished. + let seen = + unsafe { std::slice::from_raw_parts(contents.as_ptr(), LEN as usize) }; + let stale = (seen.iter().zip(&written)).filter(|(a, b)| a != b).count(); + assert_eq!( + stale, 0, + "{name}: bytes of the guest's write the GPU read stale" ); - read.expect("the memfd's bytes"); - assert!(pages.iter().all(|&byte| byte == 0x3c), "{name}: the pages"); - drop((command_buffer, queue, buffer, block)); + let gpu_read = (seen[0], seen[LEN as usize - 1]); + // The GPU writes; the guest's side reads through its mapping, with no + // invalidate call. + blit(&|encoder| { + encoder + .fill_buffer(&buffer, 0..LEN, 0x3c) + .unwrap_or_else(|error| panic!("{name}: {error}")) + }); + let stale = pages.iter().filter(|&&byte| byte != 0x3c).count(); + assert_eq!( + stale, 0, + "{name}: bytes of the GPU's fill the guest read stale" + ); + let guest_read = (pages[0], pages[LEN as usize - 1]); + // SAFETY: the test's mapping, which nothing uses past here. + assert_eq!(unsafe { libc::munmap(base, LEN as usize) }, 0, "{name}"); + drop((out, cpu, queue, buffer, block)); wait_until(&device, "the release", || released.load(Ordering::SeqCst)); assert_eq!(counters.gauges().imports, 0, "{name}"); println!( - "import: {name}: a dma-buf imported into its first offered type, \ - {memory_type}" + "import: {name}: a dma-buf imported into type {memory_type}; the GPU read \ + the guest's write ({:#04x} .. {:#04x}, {LEN} bytes, 0 stale), the guest \ + read the GPU's fill ({:#04x} .. {:#04x}, 0 stale)", + gpu_read.0, gpu_read.1, guest_read.0, guest_read.1 ); } Err(Error::Limit(Limit::ImportCoherence { @@ -1194,9 +1419,9 @@ pub(crate) mod on_device { offered, listed, })) => { - let coherent = device.core().imports.coherent; let handle = ImportHandle::DmaBuf; - let rule = dma_buf_type(handle, true, offered, listed, coherent); + let types = &device.core().imports.dma_buf_types; + let rule = dma_buf_type(handle, true, offered, listed, types); assert!(rule.is_err(), "{name}"); assert!(device.core().coherence.is_none(), "{name}"); assert_eq!(counters.gauges(), before, "{name}: nothing imported"); diff --git a/crates/metal2vulkan-runtime/src/tests/import_time.rs b/crates/metal2vulkan-runtime/src/tests/import_time.rs index 5287a294f..dcb8315c8 100644 --- a/crates/metal2vulkan-runtime/src/tests/import_time.rs +++ b/crates/metal2vulkan-runtime/src/tests/import_time.rs @@ -559,7 +559,7 @@ mod on_device { shared_coherent, offered, listed, - core.imports.coherent, + &core.imports.dma_buf_types, ); index = Some(taken.expect("the call's type")); }