✨ Guest RAM now reaches the Vulkan device as one host-pointer import per RAMBlock, and every reference into it is a checked slice
Component: `crates/reims-vgpu`, Vulkan backend and the runtime rails that feed it. Pathway: x86 macOS / Linux Vulkan, and the MoltenVK arm by construction — neither booted for this commit. ## What runs now - `caps::host_pointer` — the capability rungs for `VK_EXT_external_memory_host`, in the same shape the dma-buf rungs had and for the same reason: a bug report has to say which check refused. The granularity travels with the rung rather than beside it, because a rung with no granularity is not actionable and a granularity from a device that declined the handle type is a number nothing may act on. `minImportedHostPointerAlignment` is queried, never assumed: MoltenVK reports Apple's page size and a Linux driver may report more. - `runtime::guest_ram_map` — the process's imports, built once from ABI v17's spans on the first guest-memory reference of a boot, and the only place a GPA becomes a bindable reference. The backend measures the granularity and the runtime holds the `HostOps`; neither side has both, so the granularity is latched by the backend and the spans fetched here. - `engine::host_ram` — the import site. One `VkDeviceMemory` and one `VkBuffer` per RAMBlock, held for the device's life, in a map with no eviction policy and no capacity. That is the prize: the dma-buf rail needed an LRU bounded by pinned bytes because `UDMABUF_CREATE_LIST` walked every page and pinned it, and here the expensive step happens once and the cheap step is a range check. - Memory-type selection goes through `caps::memory_topology::select_memory_type` rather than ranking a second time, so the two cannot diverge on the first host where the ranking mattered. ## What was deleted, and why in this commit `runtime::guest_dmabuf`, `engine::dmabuf` and `caps::external_memory` are gone, along with `GuestDmaBuf`, `GuestPageWindow`, the engine's import cache, the `DeferredHandle::DmaBufImport` graveyard arm, `external_memory_fd`, and the `export_available()` pre-gate in `mapping_write`. The plan sequenced this as its own phase, but rewiring the consumers left the dma-buf types with no producer: keeping them would have been the two-spellings-of-one-rail divergence the plan warns about, in the same tree. The C shim's `dmabuf_for_pages`, its ABI codes and `reims-vgpu-dmabuf.c` are still present and now unused; they go next, with the `AGENTS.md` rewrite. `REIMS_VGPU_DMABUF` becomes `REIMS_VGPU_GUEST_IMPORT`, still narrow-only. Two decline variants became unrepresentable rather than untested: `BufferImportDecline::WindowTooSmall` and its sampled twin. The range now comes from a `GuestRef` whose bound is checked where it is built, so there is no longer a way for a bind to name bytes past what was resolved. ## What this commit does not do A page list that is not one GPA-contiguous stretch is refused by name (`guest_ram_map_scattered`) and gathered on the CPU. That is a property of the *bind* and not of the import — the pages are all inside one RAMBlock and each is nameable — but a `VkBuffer` range is one offset and one length, and no consumer takes several yet. The refusal is counted so how often it costs anything is measurable on a driven boot, which is what should decide whether widening the bind sites is worth doing. Tests: 1641 lib + all integration green, ignored counts unchanged (the wire-layout fixtures are absent on this checkout as usual). New: 8 rung tests in `caps::host_pointer`, 10 in `runtime::guest_ram_map` (per-span resolution on a machine with a PCI hole, the host asked exactly once, each refusal keeping its own name, a reset rebuilding against fresh identities, and the expected refusal landing on the off channel rather than the fail one), 3 in `engine::host_ram`, 1 more on the `vk_caps` line. Clippy `-D warnings` clean on all three arms (native Vulkan, `--target x86_64-unknown-linux-gnu`, `--target aarch64-apple-darwin --features backend-metal`). `scripts/feature-matrix`: all three arms pass, warnings=0. Not verified: no live boot on either pathway — the import has never run against a real driver, so `host_pointer_import=supported` and the bind path are untested against hardware. The `backend-metal` test arm was not run (Linux host). The Metal-direct arm still has no import at all; that is the next phase. Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
71a317b4cd
commit
159fde84a7
19 files changed
+1885
-2208
No files matched your search
@@ -1,453 +0,0 @@
|
||||
//! Whether this device can import a Linux dma-buf as `VkDeviceMemory`, and the
|
||||
//! extensions that answer implies.
|
||||
//!
|
||||
//! # Why this is not `VK_EXT_external_memory_host` wearing a different name
|
||||
//!
|
||||
//! That extension is banned crate-wide and stays banned. It imports an arbitrary
|
||||
//! **host virtual address range** belonging to this process, which over guest RAM
|
||||
//! is the whole guest: the pointer is unbounded by anything the guest asked for,
|
||||
//! it aliases whatever the QEMU RAMBlock mapping happens to cover, and it cannot
|
||||
//! be revoked once handed to the driver.
|
||||
//!
|
||||
//! A dma-buf is a different object with different properties, and the difference
|
||||
//! is what makes it admissible where the host-pointer import is not:
|
||||
//!
|
||||
//! * **Bounded by construction.** The fd names an explicit list of page-sized
|
||||
//! ranges chosen when it was created. There is no pointer to stray from and no
|
||||
//! surrounding mapping to reach; a page not named at create time is not
|
||||
//! reachable through the fd at all.
|
||||
//! * **Revocable.** Closing the fd and freeing the `VkDeviceMemory` ends the
|
||||
//! GPU's access. A host-pointer import has no such handle.
|
||||
//! * **Kernel-mediated.** The importing driver takes a reference on pages the
|
||||
//! kernel is tracking, rather than being handed a raw address it must trust.
|
||||
//!
|
||||
//! That is the same mechanism upstream QEMU's virtio-gpu blob path uses for
|
||||
//! exactly this purpose, and it is what lets guest pages be a GPU source *and*
|
||||
//! destination without the copy crossings that dominate this device's cost.
|
||||
//!
|
||||
//! # Query and enable together
|
||||
//!
|
||||
//! Same rule as [`super::device_features`], for the same reason: the extensions
|
||||
//! are named here and nowhere else, so no site can bind an import the device was
|
||||
//! never asked to support. [`DmaBufImport::required_extensions`] is the only
|
||||
//! producer of those strings.
|
||||
//!
|
||||
//! # Optional, and switchable off
|
||||
//!
|
||||
//! Neither extension is a requirement. A host that advertises neither reaches
|
||||
//! [`DmaBufImport::NoDmaBufExtension`], asks for nothing at `vkCreateDevice`, and
|
||||
//! runs every guest-memory rail through the copying path it used before this
|
||||
//! capability existed. That is the whole support story for Apple hosts, for a
|
||||
//! Linux ICD without the extension, and for a device that declines the handle
|
||||
//! type — three different hosts, three different rungs, one behavior.
|
||||
//!
|
||||
//! [`crate::env::DMABUF`] adds a fourth: an operator can take a host that *is*
|
||||
//! capable down to [`DmaBufImport::DisabledByEnv`]. This is the only way to
|
||||
//! exercise the copying rails on a machine where the import works, so a
|
||||
//! regression in them is findable without hunting for hardware that lacks the
|
||||
//! extension. It cannot run the other way — see [`crate::env`] for why no
|
||||
//! variable may widen a measured capability.
|
||||
|
||||
use ash::vk;
|
||||
|
||||
/// Buffer usage every imported guest-memory buffer is created with, and
|
||||
/// therefore the usage [`query`] asks the device about.
|
||||
///
|
||||
/// Importability is a property of the handle type **and the usage**, so asking
|
||||
/// about a narrower set than the import site binds is a query that can answer
|
||||
/// yes to a bind the driver then refuses. The set is the union of both
|
||||
/// directions the rail runs in:
|
||||
///
|
||||
/// * `TRANSFER_SRC` — guest pages as the source of an upload into a device-local
|
||||
/// image or buffer.
|
||||
/// * `TRANSFER_DST` — guest pages as the destination of a render/compute result,
|
||||
/// which is the writeback the deferred-flush rail otherwise stages through the
|
||||
/// CPU.
|
||||
/// * `VERTEX_BUFFER` / `INDEX_BUFFER` / `STORAGE_BUFFER` / `UNIFORM_BUFFER` —
|
||||
/// guest pages bound directly to a draw, with no copy at all.
|
||||
pub const GUEST_IMPORT_USAGE: vk::BufferUsageFlags = vk::BufferUsageFlags::from_raw(
|
||||
vk::BufferUsageFlags::TRANSFER_SRC.as_raw()
|
||||
| vk::BufferUsageFlags::TRANSFER_DST.as_raw()
|
||||
| vk::BufferUsageFlags::VERTEX_BUFFER.as_raw()
|
||||
| vk::BufferUsageFlags::INDEX_BUFFER.as_raw()
|
||||
| vk::BufferUsageFlags::STORAGE_BUFFER.as_raw()
|
||||
| vk::BufferUsageFlags::UNIFORM_BUFFER.as_raw(),
|
||||
);
|
||||
|
||||
/// Whether guest pages can reach this device as a dma-buf import, and when they
|
||||
/// cannot, which check said so.
|
||||
///
|
||||
/// Rungs rather than a bool because every negative rung is a different host and
|
||||
/// a different answer for a bug report: an Apple host has no dma-buf at all, a
|
||||
/// Linux host with an old ICD may have the fd extension without it, and a device
|
||||
/// can advertise both and still decline the handle type for this usage.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum DmaBufImport {
|
||||
/// Both extensions advertised and the device reports DMA_BUF importable for
|
||||
/// [`GUEST_IMPORT_USAGE`]. The only rung on which the import path may run.
|
||||
Supported,
|
||||
/// No [`query`] has been run. The default, so a [`super::HostGpuCaps`] built
|
||||
/// without one never claims a capability nothing checked for.
|
||||
#[default]
|
||||
Unqueried,
|
||||
/// `VK_KHR_external_memory_fd` absent. Without it there is no
|
||||
/// `vkGetMemoryFdProperties` to ask which memory types accept the fd, and
|
||||
/// nothing to chain onto `vkAllocateMemory` to import through.
|
||||
NoExternalMemoryFd,
|
||||
/// `VK_EXT_external_memory_dma_buf` absent. Expected on every non-Linux ICD,
|
||||
/// MoltenVK included — the handle type names a Linux kernel object.
|
||||
NoDmaBufExtension,
|
||||
/// Both extensions advertised, and the device still declines DMA_BUF as an
|
||||
/// importable handle type for [`GUEST_IMPORT_USAGE`].
|
||||
NotImportable,
|
||||
/// [`crate::env::DMABUF`] was set off. The only rung that is a statement
|
||||
/// about policy rather than about the host: this device may well be capable,
|
||||
/// and the operator asked for the copying rails anyway. Distinct from every
|
||||
/// rung above precisely so a log does not read as a hardware limitation when
|
||||
/// it is a switch someone left set.
|
||||
DisabledByEnv,
|
||||
}
|
||||
|
||||
impl DmaBufImport {
|
||||
/// The one place the import path asks whether it may run.
|
||||
pub fn is_available(self) -> bool {
|
||||
matches!(self, Self::Supported)
|
||||
}
|
||||
|
||||
/// Stable slug for the `reason=` field of a decline, and for the capability
|
||||
/// line. Named per rung so a log says which check refused.
|
||||
pub fn slug(self) -> &'static str {
|
||||
match self {
|
||||
Self::Supported => "supported",
|
||||
Self::Unqueried => "unqueried",
|
||||
Self::NoExternalMemoryFd => "no_external_memory_fd",
|
||||
Self::NoDmaBufExtension => "no_dma_buf_extension",
|
||||
Self::NotImportable => "not_importable",
|
||||
Self::DisabledByEnv => "disabled_by_env",
|
||||
}
|
||||
}
|
||||
|
||||
/// Stable byte encoding for [`LATCHED`].
|
||||
///
|
||||
/// Both directions are written out rather than cast, so a rung added later
|
||||
/// is a non-exhaustive-match error here instead of a value that decodes as a
|
||||
/// neighbouring rung — which would be a log naming the wrong check and, on
|
||||
/// the `Supported` code, a rail opened by an arithmetic accident.
|
||||
fn code(self) -> u8 {
|
||||
match self {
|
||||
Self::Unqueried => 0,
|
||||
Self::Supported => 1,
|
||||
Self::NoExternalMemoryFd => 2,
|
||||
Self::NoDmaBufExtension => 3,
|
||||
Self::NotImportable => 4,
|
||||
Self::DisabledByEnv => 5,
|
||||
}
|
||||
}
|
||||
|
||||
/// Inverse of [`Self::code`]. An unknown byte is [`Self::Unqueried`] — the
|
||||
/// rung that claims nothing — so a decode that somehow goes wrong closes the
|
||||
/// rail's *export* side rather than opening it.
|
||||
fn from_code(code: u8) -> Self {
|
||||
match code {
|
||||
1 => Self::Supported,
|
||||
2 => Self::NoExternalMemoryFd,
|
||||
3 => Self::NoDmaBufExtension,
|
||||
4 => Self::NotImportable,
|
||||
5 => Self::DisabledByEnv,
|
||||
_ => Self::Unqueried,
|
||||
}
|
||||
}
|
||||
|
||||
/// Device extension names this rung requires. Only [`Self::Supported`]
|
||||
/// requires any: asking for an extension on a rung that cannot use it would
|
||||
/// fail device creation on the hosts that do not have it, which is every
|
||||
/// host the negative rungs describe.
|
||||
pub fn required_extensions(self) -> Vec<*const std::os::raw::c_char> {
|
||||
if self.is_available() {
|
||||
vec![
|
||||
vk::KHR_EXTERNAL_MEMORY_FD_NAME.as_ptr(),
|
||||
vk::EXT_EXTERNAL_MEMORY_DMA_BUF_NAME.as_ptr(),
|
||||
]
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The rung this process resolved, readable without the engine lock and
|
||||
/// without a device context in hand.
|
||||
///
|
||||
/// # Why the answer is published rather than only held on `HostGpuCaps`
|
||||
///
|
||||
/// The rail has two halves in two crates' worth of distance from each other:
|
||||
/// the runtime asks the host to *export* a dma-buf over guest pages, and the
|
||||
/// engine *imports* it. Only the engine held the answer, so the export ran
|
||||
/// unconditionally and the import declined afterwards — which on any host
|
||||
/// without the extension meant a `UDMABUF_CREATE_LIST` per window, a cached fd,
|
||||
/// and up to [`crate::runtime::guest_dmabuf::MAX_PINNED_BYTES`] of the guest's
|
||||
/// RAM made unswappable, all of it to feed an import that could never happen.
|
||||
/// Pinning guest memory for a capability the device does not have is the cost
|
||||
/// this publishes to avoid.
|
||||
///
|
||||
/// Zero — [`DmaBufImport::Unqueried`] — until a device is created, which is the
|
||||
/// honest answer and the one the export side treats as "not settled, let the
|
||||
/// import site decide".
|
||||
static LATCHED: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
|
||||
|
||||
/// Publish the rung a freshly created device resolved to.
|
||||
///
|
||||
/// Called once per `vkCreateDevice`, including each recreate, so a rebuilt
|
||||
/// device republishes rather than leaving the previous one's answer standing.
|
||||
pub fn latch(rung: DmaBufImport) {
|
||||
LATCHED.store(rung.code(), std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// The published rung. [`DmaBufImport::Unqueried`] before any device exists.
|
||||
///
|
||||
/// `Relaxed` on both sides: this gates whether an optimization is attempted, and
|
||||
/// a reader that sees the previous value takes the copying path for one window.
|
||||
/// Nothing here orders access to any other memory.
|
||||
pub fn latched() -> DmaBufImport {
|
||||
DmaBufImport::from_code(LATCHED.load(std::sync::atomic::Ordering::Relaxed))
|
||||
}
|
||||
|
||||
/// What [`crate::env::DMABUF`] says about running this rail at all.
|
||||
///
|
||||
/// `None` to go on and ask the device. `Some` short-circuits [`query`], which
|
||||
/// is deliberate on two counts: the device is not asked about a handle type
|
||||
/// nothing will import, and neither extension is then named at `vkCreateDevice`,
|
||||
/// so the switch produces exactly the device a host without them would get
|
||||
/// rather than a capable device with one gate closed.
|
||||
///
|
||||
/// [`crate::env::Switch::On`] is not a way to turn the rail on — no variable may
|
||||
/// widen a measured capability — but it is not ignored either: an operator who
|
||||
/// set it has stated an expectation, and if the device then refuses, the `vk_caps`
|
||||
/// line names the rung that refused. Only the unrecognized case is reported here,
|
||||
/// because that is the one an operator would otherwise read as "the switch did
|
||||
/// nothing" with no way to tell a typo from a device that declined.
|
||||
fn env_override() -> Option<DmaBufImport> {
|
||||
match crate::env::read(crate::env::DMABUF) {
|
||||
(crate::env::Switch::Off, _) => Some(DmaBufImport::DisabledByEnv),
|
||||
(crate::env::Switch::Unrecognized, value) => {
|
||||
crate::observe::fail(format!(
|
||||
"vk_dmabuf_env_unrecognized var={} value={:?} (expected on|off; the rail is left \
|
||||
to the device)",
|
||||
crate::env::DMABUF,
|
||||
value.unwrap_or_default()
|
||||
));
|
||||
None
|
||||
}
|
||||
(crate::env::Switch::On | crate::env::Switch::Unset, _) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve dma-buf importability against one physical device.
|
||||
///
|
||||
/// `has_extension` is passed in rather than enumerated here because the caller
|
||||
/// already enumerates device extensions for the other capability queries.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `pd` must be a physical device belonging to `instance`.
|
||||
pub unsafe fn query(
|
||||
instance: &ash::Instance,
|
||||
pd: vk::PhysicalDevice,
|
||||
has_extension: &dyn Fn(&std::ffi::CStr) -> bool,
|
||||
) -> DmaBufImport {
|
||||
if let Some(disabled) = env_override() {
|
||||
return disabled;
|
||||
}
|
||||
if !has_extension(vk::KHR_EXTERNAL_MEMORY_FD_NAME) {
|
||||
return DmaBufImport::NoExternalMemoryFd;
|
||||
}
|
||||
if !has_extension(vk::EXT_EXTERNAL_MEMORY_DMA_BUF_NAME) {
|
||||
return DmaBufImport::NoDmaBufExtension;
|
||||
}
|
||||
// `vkGetPhysicalDeviceExternalBufferProperties` is Vulkan 1.1 core and the
|
||||
// baseline is 1.2, so this is always answerable once the handle type itself
|
||||
// is spelled by an advertised extension.
|
||||
let info = vk::PhysicalDeviceExternalBufferInfo::default()
|
||||
.usage(GUEST_IMPORT_USAGE)
|
||||
.handle_type(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT);
|
||||
let mut props = vk::ExternalBufferProperties::default();
|
||||
unsafe { instance.get_physical_device_external_buffer_properties(pd, &info, &mut props) };
|
||||
if props
|
||||
.external_memory_properties
|
||||
.external_memory_features
|
||||
.contains(vk::ExternalMemoryFeatureFlags::IMPORTABLE)
|
||||
{
|
||||
DmaBufImport::Supported
|
||||
} else {
|
||||
DmaBufImport::NotImportable
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Every rung, so a rung added without a test here fails to compile rather
|
||||
/// than quietly skipping the invariants below.
|
||||
const RUNGS: [DmaBufImport; 6] = [
|
||||
DmaBufImport::Supported,
|
||||
DmaBufImport::Unqueried,
|
||||
DmaBufImport::NoExternalMemoryFd,
|
||||
DmaBufImport::NoDmaBufExtension,
|
||||
DmaBufImport::NotImportable,
|
||||
DmaBufImport::DisabledByEnv,
|
||||
];
|
||||
|
||||
/// Only the supported rung asks for extension strings. Requesting
|
||||
/// `VK_EXT_external_memory_dma_buf` on a host that does not advertise it
|
||||
/// fails `vkCreateDevice` outright — so a negative rung that still named its
|
||||
/// extensions would turn "no zero-copy here" into "no Vulkan here", on
|
||||
/// exactly the hosts the rung exists to describe.
|
||||
#[test]
|
||||
fn only_the_supported_rung_names_extensions() {
|
||||
assert_eq!(DmaBufImport::Supported.required_extensions().len(), 2);
|
||||
for rung in RUNGS.into_iter().filter(|r| !r.is_available()) {
|
||||
assert!(
|
||||
rung.required_extensions().is_empty(),
|
||||
"{rung:?} must not request an extension it cannot use"
|
||||
);
|
||||
assert!(!rung.is_available(), "{rung:?} must not gate the rail open");
|
||||
}
|
||||
}
|
||||
|
||||
/// The default rung is "nobody asked", not "no". Both refuse the rail, but
|
||||
/// only one of them is honest about a `HostGpuCaps` that was never queried —
|
||||
/// and the slug is what a reader greps to tell them apart.
|
||||
#[test]
|
||||
fn the_default_rung_says_it_was_never_queried() {
|
||||
assert_eq!(DmaBufImport::default(), DmaBufImport::Unqueried);
|
||||
assert_eq!(DmaBufImport::default().slug(), "unqueried");
|
||||
}
|
||||
|
||||
/// One slug per rung: two rungs sharing one would mean watching the slug
|
||||
/// fire in the log and still not knowing which check refused.
|
||||
#[test]
|
||||
fn every_rung_has_its_own_slug() {
|
||||
let mut slugs: Vec<_> = RUNGS.iter().map(|r| r.slug()).collect();
|
||||
slugs.sort_unstable();
|
||||
let count = slugs.len();
|
||||
slugs.dedup();
|
||||
assert_eq!(slugs.len(), count, "two rungs share a slug");
|
||||
assert!(slugs
|
||||
.iter()
|
||||
.all(|s| s.bytes().all(|b| b.is_ascii_lowercase() || b == b'_')));
|
||||
}
|
||||
|
||||
/// The usage set queried is the usage set bound. Asking about a narrower set
|
||||
/// than the import site creates its buffer with is a query that can answer
|
||||
/// yes to a bind the driver then refuses — the failure would land at
|
||||
/// `vkCreateBuffer` on a guest frame rather than at capability time.
|
||||
#[test]
|
||||
fn the_queried_usage_covers_both_directions_of_the_rail() {
|
||||
// Guest pages as a GPU *source* — the upload the CPU otherwise gathers.
|
||||
assert!(GUEST_IMPORT_USAGE.contains(vk::BufferUsageFlags::TRANSFER_SRC));
|
||||
// Guest pages as a GPU *destination* — the writeback the deferred-flush
|
||||
// rail otherwise stages through the CPU, and the larger half of the cost.
|
||||
assert!(GUEST_IMPORT_USAGE.contains(vk::BufferUsageFlags::TRANSFER_DST));
|
||||
// Bound straight to a draw, with no copy in either direction.
|
||||
for direct in [
|
||||
vk::BufferUsageFlags::VERTEX_BUFFER,
|
||||
vk::BufferUsageFlags::INDEX_BUFFER,
|
||||
vk::BufferUsageFlags::STORAGE_BUFFER,
|
||||
vk::BufferUsageFlags::UNIFORM_BUFFER,
|
||||
] {
|
||||
assert!(GUEST_IMPORT_USAGE.contains(direct));
|
||||
}
|
||||
}
|
||||
|
||||
/// Set [`crate::env::DMABUF`] to `value`, read the override, and restore.
|
||||
/// One test at a time: the variable is process-global.
|
||||
fn with_env(value: Option<&str>) -> Option<DmaBufImport> {
|
||||
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// SAFETY: the lock serializes every mutation of this variable in this
|
||||
// process, and the only reader is `env_override`, called below.
|
||||
unsafe {
|
||||
match value {
|
||||
Some(v) => std::env::set_var(crate::env::DMABUF, v),
|
||||
None => std::env::remove_var(crate::env::DMABUF),
|
||||
}
|
||||
}
|
||||
let out = env_override();
|
||||
unsafe { std::env::remove_var(crate::env::DMABUF) };
|
||||
out
|
||||
}
|
||||
|
||||
/// The switch turns the rail off, and lands on a rung that says a person did
|
||||
/// it. Reading `no_dma_buf_extension` for a host that has the extension would
|
||||
/// send the next bug report hunting for a driver problem.
|
||||
#[test]
|
||||
fn the_env_switch_takes_a_capable_host_down() {
|
||||
assert_eq!(with_env(Some("0")), Some(DmaBufImport::DisabledByEnv));
|
||||
assert_eq!(with_env(Some("off")), Some(DmaBufImport::DisabledByEnv));
|
||||
assert!(!DmaBufImport::DisabledByEnv.is_available());
|
||||
assert!(DmaBufImport::DisabledByEnv.required_extensions().is_empty());
|
||||
assert_eq!(DmaBufImport::DisabledByEnv.slug(), "disabled_by_env");
|
||||
}
|
||||
|
||||
/// The switch has no on direction. Setting it affirmatively hands the answer
|
||||
/// straight back to the device — which is the whole rule from [`crate::env`]:
|
||||
/// a variable may narrow what this device does and may never widen it, because
|
||||
/// binding an extension the host does not advertise fails `vkCreateDevice` and
|
||||
/// importing a handle type it declines is undefined behavior in the driver.
|
||||
#[test]
|
||||
fn the_env_switch_cannot_turn_the_rail_on() {
|
||||
for on in ["1", "on", "true", "yes"] {
|
||||
assert_eq!(with_env(Some(on)), None, "{on} must not preempt the query");
|
||||
}
|
||||
assert_eq!(with_env(None), None);
|
||||
}
|
||||
|
||||
/// A misspelled value leaves the device to decide, rather than guessing at
|
||||
/// an intent. `env::read` keeps the raw value so the line above names it.
|
||||
#[test]
|
||||
fn an_unrecognized_value_does_not_change_the_answer() {
|
||||
assert_eq!(with_env(Some("maybe")), None);
|
||||
}
|
||||
|
||||
/// Every rung survives the byte encoding the published answer travels
|
||||
/// through, and no two share a code. A collision would let the export side
|
||||
/// read `Supported` for a host that refused — pinning guest pages for an
|
||||
/// import that then declines, which is the exact cost the latch exists to
|
||||
/// avoid.
|
||||
#[test]
|
||||
fn every_rung_round_trips_through_its_code() {
|
||||
let mut codes: Vec<u8> = RUNGS.iter().map(|r| r.code()).collect();
|
||||
for rung in RUNGS {
|
||||
assert_eq!(DmaBufImport::from_code(rung.code()), rung, "{rung:?}");
|
||||
}
|
||||
let count = codes.len();
|
||||
codes.sort_unstable();
|
||||
codes.dedup();
|
||||
assert_eq!(codes.len(), count, "two rungs share a code");
|
||||
}
|
||||
|
||||
/// An unrecognized byte decodes to the rung that claims nothing, so a decode
|
||||
/// that goes wrong closes the export side rather than opening it. Zero is
|
||||
/// pinned separately because it is the atomic's initializer, written as a
|
||||
/// literal where `code()` cannot be called.
|
||||
#[test]
|
||||
fn an_unknown_code_is_the_rung_that_claims_nothing() {
|
||||
assert_eq!(DmaBufImport::Unqueried.code(), 0);
|
||||
for code in [6u8, 7, 100, u8::MAX] {
|
||||
assert_eq!(DmaBufImport::from_code(code), DmaBufImport::Unqueried);
|
||||
}
|
||||
}
|
||||
|
||||
/// The published answer starts at "nobody asked" and follows the last
|
||||
/// device created — a recreate republishes rather than leaving a stale rung
|
||||
/// standing.
|
||||
#[test]
|
||||
fn the_published_rung_follows_the_last_device() {
|
||||
assert_eq!(DmaBufImport::from_code(0), DmaBufImport::Unqueried);
|
||||
for rung in RUNGS {
|
||||
latch(rung);
|
||||
assert_eq!(latched(), rung, "{rung:?}");
|
||||
}
|
||||
latch(DmaBufImport::Unqueried);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,457 @@
|
||||
//! Whether this device can import a host pointer over guest RAM as
|
||||
//! `VkDeviceMemory`, and the extension that answer implies.
|
||||
//!
|
||||
//! # Why a host pointer, and why it is bounded
|
||||
//!
|
||||
//! `VK_EXT_external_memory_host` is the one primitive that spans every host
|
||||
//! this device targets: Linux, Windows, and macOS through MoltenVK, which
|
||||
//! implements it over `newBufferWithBytesNoCopy` — the same call the
|
||||
//! Metal-direct arm makes. dma-buf is a Linux kernel object and always will be,
|
||||
//! and `VK_KHR_external_memory_win32` is not the Windows equivalent: it moves
|
||||
//! NT handles for GPU-allocated or D3D resources, not arbitrary host pointers.
|
||||
//!
|
||||
//! What the extension does not carry is a bound. That is
|
||||
//! [`crate::runtime::guest_ram`]'s job, and it is a type rather than a rule: an
|
||||
//! import is sized to a RAMBlock exactly, and every reference inside it is a
|
||||
//! `GuestSlice` that no call site can construct without the bounds check. Read
|
||||
//! that module's doc before adding an import site; nothing here re-states it,
|
||||
//! and nothing scans for violations of it.
|
||||
//!
|
||||
//! # Query and enable together
|
||||
//!
|
||||
//! Same rule as [`super::device_features`], for the same reason: the extension
|
||||
//! is named here and nowhere else, so no site can bind an import the device was
|
||||
//! never asked to support. [`HostPointerImport::required_extensions`] is the
|
||||
//! only producer of that string.
|
||||
//!
|
||||
//! # Optional, and switchable off
|
||||
//!
|
||||
//! The extension is never a requirement. A host that does not advertise it
|
||||
//! reaches [`HostPointerImport::NoHostPointerExtension`], asks for nothing at
|
||||
//! `vkCreateDevice`, and runs every guest-memory rail through the copying path.
|
||||
//! Those rails are not a legacy arm — they are the only arm on such a host, and
|
||||
//! they are the arm a discrete GPU takes regardless, because there the copy into
|
||||
//! VRAM is the point.
|
||||
//!
|
||||
//! [`crate::env::GUEST_IMPORT`] adds one more rung: an operator can take a host
|
||||
//! that *is* capable down to [`HostPointerImport::DisabledByEnv`]. That is the
|
||||
//! only way to exercise the copying rails on a machine where the import works,
|
||||
//! so a regression in them is findable without hunting for hardware that lacks
|
||||
//! the extension. It cannot run the other way — see [`crate::env`] for why no
|
||||
//! variable may widen a measured capability.
|
||||
|
||||
use ash::vk;
|
||||
|
||||
/// Buffer usage every imported guest-memory buffer is created with, and
|
||||
/// therefore the usage [`query`] asks the device about.
|
||||
///
|
||||
/// Importability is a property of the handle type **and the usage**, so asking
|
||||
/// about a narrower set than the import site binds is a query that can answer
|
||||
/// yes to a bind the driver then refuses. The set is the union of every
|
||||
/// direction the rail runs in:
|
||||
///
|
||||
/// * `TRANSFER_SRC` — guest pages as the source of an upload into a
|
||||
/// device-local image or buffer.
|
||||
/// * `TRANSFER_DST` — guest pages as the destination of a render or compute
|
||||
/// result, which is the writeback the deferred-flush rail otherwise stages
|
||||
/// through the CPU.
|
||||
/// * `VERTEX_BUFFER` / `INDEX_BUFFER` / `STORAGE_BUFFER` / `UNIFORM_BUFFER` —
|
||||
/// guest pages bound directly to a draw, with no copy at all.
|
||||
///
|
||||
/// **Buffers only, deliberately.** An image has implementation-defined tiling,
|
||||
/// and an optimally-tiled image backed by linear guest bytes is not a thing
|
||||
/// this device may assume works on an unknown driver. A buffer's memory layout
|
||||
/// is the bytes themselves on every implementation, which is why it is the
|
||||
/// universal primitive here and why guest pages reach an image through a
|
||||
/// `vkCmdCopyBufferToImage` from an imported buffer rather than by being one.
|
||||
pub const GUEST_IMPORT_USAGE: vk::BufferUsageFlags = vk::BufferUsageFlags::from_raw(
|
||||
vk::BufferUsageFlags::TRANSFER_SRC.as_raw()
|
||||
| vk::BufferUsageFlags::TRANSFER_DST.as_raw()
|
||||
| vk::BufferUsageFlags::VERTEX_BUFFER.as_raw()
|
||||
| vk::BufferUsageFlags::INDEX_BUFFER.as_raw()
|
||||
| vk::BufferUsageFlags::STORAGE_BUFFER.as_raw()
|
||||
| vk::BufferUsageFlags::UNIFORM_BUFFER.as_raw(),
|
||||
);
|
||||
|
||||
/// Whether guest RAM can reach this device as a host-pointer import, and when
|
||||
/// it cannot, which check said so.
|
||||
///
|
||||
/// Rungs rather than a bool because every negative rung is a different host and
|
||||
/// a different answer for a bug report: a Linux ICD without the extension, a
|
||||
/// device that advertises it and still declines the handle type for this usage,
|
||||
/// and a RAMBlock whose base cannot meet the device's own import granularity
|
||||
/// are three separate findings, and only the last is about this guest's memory
|
||||
/// rather than about the driver.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum HostPointerImport {
|
||||
/// The extension is advertised and the device reports the host-allocation
|
||||
/// handle type importable for [`GUEST_IMPORT_USAGE`]. The only rung on
|
||||
/// which the import path may run.
|
||||
Supported,
|
||||
/// No [`query`] has been run. The default, so a [`super::HostGpuCaps`] built
|
||||
/// without one never claims a capability nothing checked for.
|
||||
#[default]
|
||||
Unqueried,
|
||||
/// `VK_EXT_external_memory_host` absent. Without it there is no
|
||||
/// `vkGetMemoryHostPointerPropertiesEXT` to ask which memory types accept
|
||||
/// the pointer, and nothing to chain onto `vkAllocateMemory` to import
|
||||
/// through.
|
||||
NoHostPointerExtension,
|
||||
/// The extension is advertised, and the device still declines
|
||||
/// `HOST_ALLOCATION_EXT` as an importable handle type for
|
||||
/// [`GUEST_IMPORT_USAGE`].
|
||||
NotImportable,
|
||||
/// The device reported a `minImportedHostPointerAlignment` that no RAMBlock
|
||||
/// can satisfy — zero, or not a power of two. Both make the granularity
|
||||
/// arithmetic in [`crate::runtime::guest_ram`] meaningless, and a driver
|
||||
/// reporting either is broken rather than restrictive.
|
||||
///
|
||||
/// A RAMBlock whose *base* merely needs rounding is not this rung: the
|
||||
/// import trims forward to the granule and refuses per region, which is a
|
||||
/// property of one block rather than of the device.
|
||||
AlignmentUnsatisfiable,
|
||||
/// [`crate::env::GUEST_IMPORT`] was set off. The only rung that is a
|
||||
/// statement about policy rather than about the host: this device may well
|
||||
/// be capable, and the operator asked for the copying rails anyway.
|
||||
/// Distinct from every rung above precisely so a log does not read as a
|
||||
/// hardware limitation when it is a switch someone left set.
|
||||
DisabledByEnv,
|
||||
}
|
||||
|
||||
impl HostPointerImport {
|
||||
/// The one place the import path asks whether it may run.
|
||||
pub fn is_available(self) -> bool {
|
||||
matches!(self, Self::Supported)
|
||||
}
|
||||
|
||||
/// Stable slug for the `reason=` field of a decline, and for the capability
|
||||
/// line. Named per rung so a log says which check refused.
|
||||
pub fn slug(self) -> &'static str {
|
||||
match self {
|
||||
Self::Supported => "supported",
|
||||
Self::Unqueried => "unqueried",
|
||||
Self::NoHostPointerExtension => "no_host_pointer_extension",
|
||||
Self::NotImportable => "not_importable",
|
||||
Self::AlignmentUnsatisfiable => "alignment_unsatisfiable",
|
||||
Self::DisabledByEnv => "disabled_by_env",
|
||||
}
|
||||
}
|
||||
|
||||
/// Device extension names this rung requires. Only [`Self::Supported`]
|
||||
/// requires any: asking for an extension on a rung that cannot use it would
|
||||
/// fail device creation on the hosts that do not have it, which is every
|
||||
/// host the negative rungs describe.
|
||||
pub fn required_extensions(self) -> Vec<*const std::os::raw::c_char> {
|
||||
if self.is_available() {
|
||||
vec![vk::EXT_EXTERNAL_MEMORY_HOST_NAME.as_ptr()]
|
||||
} else {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the device answered, together with the granularity an import must meet.
|
||||
///
|
||||
/// The pair travels together because they are one answer: a rung of
|
||||
/// [`HostPointerImport::Supported`] with no granularity is not actionable, and
|
||||
/// a granularity from a device that declined the handle type is a number
|
||||
/// nothing may act on. Splitting them is how a site ends up importing at an
|
||||
/// alignment the device never agreed to.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct HostPointerCaps {
|
||||
/// Which check answered.
|
||||
pub rung: HostPointerImport,
|
||||
/// `minImportedHostPointerAlignment` as the device reported it. Both the
|
||||
/// imported pointer and the imported length must be multiples of it.
|
||||
///
|
||||
/// Zero on every rung but [`HostPointerImport::Supported`], and never
|
||||
/// assumed to be 4096: MoltenVK reports Apple's page size, and a Linux
|
||||
/// driver may report more than either.
|
||||
pub min_alignment: u64,
|
||||
}
|
||||
|
||||
impl HostPointerCaps {
|
||||
/// A negative answer with no granularity, for the rungs that have none.
|
||||
fn refused(rung: HostPointerImport) -> Self {
|
||||
Self {
|
||||
rung,
|
||||
min_alignment: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the import path may run.
|
||||
pub fn is_available(self) -> bool {
|
||||
self.rung.is_available()
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`crate::env::GUEST_IMPORT`] says about running this rail at all.
|
||||
///
|
||||
/// `None` to go on and ask the device. `Some` short-circuits [`query`], which is
|
||||
/// deliberate on two counts: the device is not asked about a handle type nothing
|
||||
/// will import, and the extension is then not named at `vkCreateDevice`, so the
|
||||
/// switch produces exactly the device a host without it would get rather than a
|
||||
/// capable device with one gate closed.
|
||||
///
|
||||
/// [`crate::env::Switch::On`] is not a way to turn the rail on — no variable may
|
||||
/// widen a measured capability — but it is not ignored either: an operator who
|
||||
/// set it has stated an expectation, and if the device then refuses, the
|
||||
/// `vk_caps` line names the rung that refused. Only the unrecognized case is
|
||||
/// reported here, because that is the one an operator would otherwise read as
|
||||
/// "the switch did nothing" with no way to tell a typo from a device that
|
||||
/// declined.
|
||||
fn env_override() -> Option<HostPointerImport> {
|
||||
match crate::env::read(crate::env::GUEST_IMPORT) {
|
||||
(crate::env::Switch::Off, _) => Some(HostPointerImport::DisabledByEnv),
|
||||
(crate::env::Switch::Unrecognized, value) => {
|
||||
crate::observe::fail(format!(
|
||||
"vk_guest_import_env_unrecognized var={} value={:?} (expected on|off; the rail is \
|
||||
left to the device)",
|
||||
crate::env::GUEST_IMPORT,
|
||||
value.unwrap_or_default()
|
||||
));
|
||||
None
|
||||
}
|
||||
(crate::env::Switch::On | crate::env::Switch::Unset, _) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve host-pointer importability against one physical device.
|
||||
///
|
||||
/// `has_extension` is passed in rather than enumerated here because the caller
|
||||
/// already enumerates device extensions for the other capability queries.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `pd` must be a physical device belonging to `instance`.
|
||||
pub unsafe fn query(
|
||||
instance: &ash::Instance,
|
||||
pd: vk::PhysicalDevice,
|
||||
has_extension: &dyn Fn(&std::ffi::CStr) -> bool,
|
||||
) -> HostPointerCaps {
|
||||
if let Some(disabled) = env_override() {
|
||||
return HostPointerCaps::refused(disabled);
|
||||
}
|
||||
if !has_extension(vk::EXT_EXTERNAL_MEMORY_HOST_NAME) {
|
||||
return HostPointerCaps::refused(HostPointerImport::NoHostPointerExtension);
|
||||
}
|
||||
// `vkGetPhysicalDeviceExternalBufferProperties` is Vulkan 1.1 core and the
|
||||
// baseline is 1.2, so this is always answerable once the handle type itself
|
||||
// is spelled by an advertised extension.
|
||||
let info = vk::PhysicalDeviceExternalBufferInfo::default()
|
||||
.usage(GUEST_IMPORT_USAGE)
|
||||
.handle_type(vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT);
|
||||
let mut props = vk::ExternalBufferProperties::default();
|
||||
unsafe { instance.get_physical_device_external_buffer_properties(pd, &info, &mut props) };
|
||||
if !props
|
||||
.external_memory_properties
|
||||
.external_memory_features
|
||||
.contains(vk::ExternalMemoryFeatureFlags::IMPORTABLE)
|
||||
{
|
||||
return HostPointerCaps::refused(HostPointerImport::NotImportable);
|
||||
}
|
||||
|
||||
// The granularity is the device's, not ours, and it is not 4096 everywhere:
|
||||
// MoltenVK reports Apple's page size and a Linux driver may report more.
|
||||
// Asking is the whole reason this query exists rather than a constant.
|
||||
let mut host_props = vk::PhysicalDeviceExternalMemoryHostPropertiesEXT::default();
|
||||
let mut props2 = vk::PhysicalDeviceProperties2::default().push_next(&mut host_props);
|
||||
unsafe { instance.get_physical_device_properties2(pd, &mut props2) };
|
||||
let min_alignment = host_props.min_imported_host_pointer_alignment;
|
||||
if min_alignment == 0 || !min_alignment.is_power_of_two() {
|
||||
return HostPointerCaps::refused(HostPointerImport::AlignmentUnsatisfiable);
|
||||
}
|
||||
|
||||
HostPointerCaps {
|
||||
rung: HostPointerImport::Supported,
|
||||
min_alignment,
|
||||
}
|
||||
}
|
||||
|
||||
/// Which memory type an import of `host_ptr` must use, or `None` when the
|
||||
/// device accepts none that also meet `req`.
|
||||
///
|
||||
/// `vkGetMemoryHostPointerPropertiesEXT` answers with a `memoryTypeBits` mask
|
||||
/// that is a property of the *pointer*, not of the device, so it cannot be
|
||||
/// resolved once at capability time. It is fed through
|
||||
/// [`super::memory_topology::select_memory_type`] rather than being ranked here:
|
||||
/// a second selection site is a second policy, and the two would diverge on the
|
||||
/// first host where the ranking mattered.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `device` must be the logical device the import will be made on, `ext` its
|
||||
/// loaded `VK_EXT_external_memory_host` entry points, and `host_ptr` a live
|
||||
/// mapping in this process aligned to the device's
|
||||
/// [`HostPointerCaps::min_alignment`].
|
||||
pub unsafe fn import_memory_type(
|
||||
ext: &ash::ext::external_memory_host::Device,
|
||||
memory_props: &vk::PhysicalDeviceMemoryProperties,
|
||||
host_ptr: *const std::ffi::c_void,
|
||||
req: &super::memory_topology::MemoryRequest,
|
||||
) -> Option<u32> {
|
||||
let mut ptr_props = vk::MemoryHostPointerPropertiesEXT::default();
|
||||
// `ash` 0.38 wraps this extension as raw function pointers only, so the
|
||||
// call goes through `fp()` rather than a checked method.
|
||||
//
|
||||
// SAFETY: the caller's contract supplies a live, correctly aligned mapping
|
||||
// and the extension's own device-loaded entry points; `ptr_props` is a
|
||||
// correctly initialized out-struct with its `sType` set by `default()`.
|
||||
let rc = unsafe {
|
||||
(ext.fp().get_memory_host_pointer_properties_ext)(
|
||||
ext.device(),
|
||||
vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT,
|
||||
host_ptr,
|
||||
&mut ptr_props,
|
||||
)
|
||||
};
|
||||
if rc != vk::Result::SUCCESS {
|
||||
return None;
|
||||
}
|
||||
super::memory_topology::select_memory_type(memory_props, ptr_props.memory_type_bits, req)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Every rung, so a rung added without a test here fails to compile rather
|
||||
/// than quietly skipping the invariants below.
|
||||
const RUNGS: [HostPointerImport; 6] = [
|
||||
HostPointerImport::Supported,
|
||||
HostPointerImport::Unqueried,
|
||||
HostPointerImport::NoHostPointerExtension,
|
||||
HostPointerImport::NotImportable,
|
||||
HostPointerImport::AlignmentUnsatisfiable,
|
||||
HostPointerImport::DisabledByEnv,
|
||||
];
|
||||
|
||||
/// Only the supported rung asks for an extension string. Requesting
|
||||
/// `VK_EXT_external_memory_host` on a host that does not advertise it fails
|
||||
/// `vkCreateDevice` outright — so a negative rung that still named its
|
||||
/// extension would turn "no zero-copy here" into "no Vulkan here", on
|
||||
/// exactly the hosts the rung exists to describe.
|
||||
#[test]
|
||||
fn only_the_supported_rung_names_an_extension() {
|
||||
assert_eq!(HostPointerImport::Supported.required_extensions().len(), 1);
|
||||
for rung in RUNGS.into_iter().filter(|r| !r.is_available()) {
|
||||
assert!(
|
||||
rung.required_extensions().is_empty(),
|
||||
"{rung:?} must not request an extension it cannot use"
|
||||
);
|
||||
assert!(!rung.is_available(), "{rung:?} must not gate the rail open");
|
||||
}
|
||||
}
|
||||
|
||||
/// The default rung is "nobody asked", not "no". Both refuse the rail, but
|
||||
/// only one of them is honest about a `HostGpuCaps` that was never queried —
|
||||
/// and the slug is what a reader greps to tell them apart.
|
||||
#[test]
|
||||
fn the_default_rung_says_it_was_never_queried() {
|
||||
assert_eq!(HostPointerImport::default(), HostPointerImport::Unqueried);
|
||||
assert_eq!(HostPointerImport::default().slug(), "unqueried");
|
||||
assert_eq!(HostPointerCaps::default().min_alignment, 0);
|
||||
assert!(!HostPointerCaps::default().is_available());
|
||||
}
|
||||
|
||||
/// One slug per rung: two rungs sharing one would mean watching the slug
|
||||
/// fire in the log and still not knowing which check refused.
|
||||
#[test]
|
||||
fn every_rung_has_its_own_slug() {
|
||||
let mut slugs: Vec<_> = RUNGS.iter().map(|r| r.slug()).collect();
|
||||
let count = slugs.len();
|
||||
slugs.sort_unstable();
|
||||
slugs.dedup();
|
||||
assert_eq!(slugs.len(), count, "two rungs share a slug");
|
||||
assert!(slugs
|
||||
.iter()
|
||||
.all(|s| s.bytes().all(|b| b.is_ascii_lowercase() || b == b'_')));
|
||||
}
|
||||
|
||||
/// A negative rung carries no granularity. A non-zero alignment beside a
|
||||
/// refusal is a number an import site could act on, and every one of those
|
||||
/// rungs describes a device that would reject the import.
|
||||
#[test]
|
||||
fn a_refused_rung_carries_no_granularity() {
|
||||
for rung in RUNGS.into_iter().filter(|r| !r.is_available()) {
|
||||
let caps = HostPointerCaps::refused(rung);
|
||||
assert_eq!(caps.min_alignment, 0, "{rung:?}");
|
||||
assert!(!caps.is_available(), "{rung:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The usage set queried is the usage set bound. Asking about a narrower set
|
||||
/// than the import site creates its buffer with is a query that can answer
|
||||
/// yes to a bind the driver then refuses — the failure would land at
|
||||
/// `vkCreateBuffer` on a guest frame rather than at capability time.
|
||||
#[test]
|
||||
fn the_queried_usage_covers_both_directions_of_the_rail() {
|
||||
// Guest pages as a GPU *source* — the upload the CPU otherwise gathers.
|
||||
assert!(GUEST_IMPORT_USAGE.contains(vk::BufferUsageFlags::TRANSFER_SRC));
|
||||
// Guest pages as a GPU *destination* — the writeback the deferred-flush
|
||||
// rail otherwise stages through the CPU, and the larger half of the cost.
|
||||
assert!(GUEST_IMPORT_USAGE.contains(vk::BufferUsageFlags::TRANSFER_DST));
|
||||
// Bound straight to a draw, with no copy in either direction.
|
||||
for direct in [
|
||||
vk::BufferUsageFlags::VERTEX_BUFFER,
|
||||
vk::BufferUsageFlags::INDEX_BUFFER,
|
||||
vk::BufferUsageFlags::STORAGE_BUFFER,
|
||||
vk::BufferUsageFlags::UNIFORM_BUFFER,
|
||||
] {
|
||||
assert!(GUEST_IMPORT_USAGE.contains(direct));
|
||||
}
|
||||
}
|
||||
|
||||
/// Set [`crate::env::GUEST_IMPORT`] to `value`, read the override, and
|
||||
/// restore. One test at a time: the variable is process-global.
|
||||
fn with_env(value: Option<&str>) -> Option<HostPointerImport> {
|
||||
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
let _guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
|
||||
// SAFETY: the lock serializes every mutation of this variable in this
|
||||
// process, and the only reader is `env_override`, called below.
|
||||
unsafe {
|
||||
match value {
|
||||
Some(v) => std::env::set_var(crate::env::GUEST_IMPORT, v),
|
||||
None => std::env::remove_var(crate::env::GUEST_IMPORT),
|
||||
}
|
||||
}
|
||||
let out = env_override();
|
||||
unsafe { std::env::remove_var(crate::env::GUEST_IMPORT) };
|
||||
out
|
||||
}
|
||||
|
||||
/// The switch turns the rail off, and lands on a rung that says a person did
|
||||
/// it. Reading `no_host_pointer_extension` for a host that has the extension
|
||||
/// would send the next bug report hunting for a driver problem.
|
||||
#[test]
|
||||
fn the_env_switch_takes_a_capable_host_down() {
|
||||
assert_eq!(with_env(Some("0")), Some(HostPointerImport::DisabledByEnv));
|
||||
assert_eq!(with_env(Some("off")), Some(HostPointerImport::DisabledByEnv));
|
||||
assert!(!HostPointerImport::DisabledByEnv.is_available());
|
||||
assert!(HostPointerImport::DisabledByEnv
|
||||
.required_extensions()
|
||||
.is_empty());
|
||||
assert_eq!(HostPointerImport::DisabledByEnv.slug(), "disabled_by_env");
|
||||
}
|
||||
|
||||
/// The switch has no on direction. Setting it affirmatively hands the answer
|
||||
/// straight back to the device — which is the whole rule from [`crate::env`]:
|
||||
/// a variable may narrow what this device does and may never widen it,
|
||||
/// because binding an extension the host does not advertise fails
|
||||
/// `vkCreateDevice` and importing a handle type it declines is undefined
|
||||
/// behavior in the driver.
|
||||
#[test]
|
||||
fn the_env_switch_cannot_turn_the_rail_on() {
|
||||
for on in ["1", "on", "true", "yes"] {
|
||||
assert_eq!(with_env(Some(on)), None, "{on} must not preempt the query");
|
||||
}
|
||||
assert_eq!(with_env(None), None);
|
||||
}
|
||||
|
||||
/// A misspelled value leaves the device to decide, rather than guessing at
|
||||
/// an intent. `env::read` keeps the raw value so the line above names it.
|
||||
#[test]
|
||||
fn an_unrecognized_value_does_not_change_the_answer() {
|
||||
assert_eq!(with_env(Some("maybe")), None);
|
||||
}
|
||||
}
|
||||
@@ -17,11 +17,12 @@
|
||||
//! allocation names a [`MemoryClass`] and this module turns it into flags.
|
||||
//! * [`device_features`] — which optional device features are queried and
|
||||
//! enabled, in one place, so no site can ask about one it did not request.
|
||||
//! * [`external_memory::DmaBufImport`] — whether guest pages can reach the GPU
|
||||
//! as a dma-buf import. This is the *import* direction, and it satisfies the
|
||||
//! rule the deleted export bit did not: the zero-copy upload and writeback
|
||||
//! rails branch on it, and on a host where it reads anything but `Supported`
|
||||
//! they take the staged path and say which rung refused.
|
||||
//! * [`host_pointer::HostPointerImport`] — whether guest RAM can reach the GPU
|
||||
//! as a host-pointer import over a whole RAMBlock, and at what granularity.
|
||||
//! The rail that replaces the dma-buf one on every host, because it is the
|
||||
//! only primitive Linux, Windows and macOS all have. Same rule again: the
|
||||
//! import site branches on it, and a negative rung names the check that
|
||||
//! refused rather than reading as a slow host.
|
||||
//! * [`DriverQuirk`] — the only place driver identity may change behavior.
|
||||
//!
|
||||
//! **Vulkan 1.2 is the baseline on every supported host.** See [`api_floor`]
|
||||
@@ -43,10 +44,10 @@
|
||||
pub mod api_floor;
|
||||
pub mod device_features;
|
||||
pub mod device_select;
|
||||
pub mod external_memory;
|
||||
pub mod host_pointer;
|
||||
pub mod memory_topology;
|
||||
|
||||
pub(crate) use external_memory::DmaBufImport;
|
||||
pub(crate) use host_pointer::{HostPointerCaps, HostPointerImport};
|
||||
pub(crate) use memory_topology::{MappedMemoryKind, MemoryClass, MemoryProfile};
|
||||
|
||||
use ash::vk;
|
||||
@@ -84,10 +85,11 @@ impl DriverQuirk {
|
||||
pub struct HostGpuCaps {
|
||||
pub memory: MemoryProfile,
|
||||
pub quirks: DriverQuirk,
|
||||
/// Whether guest pages may be imported as `VkDeviceMemory` through a
|
||||
/// dma-buf fd. Read by the zero-copy rails to decide between a direct bind
|
||||
/// and a staged copy, and by nothing else.
|
||||
pub dma_buf_import: DmaBufImport,
|
||||
/// Whether guest RAM may be imported as `VkDeviceMemory` through a host
|
||||
/// pointer over a whole RAMBlock, and at what granularity. Read by
|
||||
/// `runtime::guest_ram_map` through the granularity latch, by the import
|
||||
/// site, and by nothing else.
|
||||
pub host_pointer: HostPointerCaps,
|
||||
/// `VK_KHR_portability_subset` was advertised. Kept for the selection log
|
||||
/// line and for constructing [`DriverQuirk`] — never gate behavior on it
|
||||
/// directly.
|
||||
@@ -109,14 +111,15 @@ impl HostGpuCaps {
|
||||
/// something the device reported.
|
||||
pub fn selection_line(&self, device_name: &str) -> String {
|
||||
format!(
|
||||
"vk_caps api={} baseline={} memory={} memory_signal={} device_local_mb={} host_visible_device_local_mb={} dma_buf_import={} portability_subset={} type={:?} name={device_name:?}",
|
||||
"vk_caps api={} baseline={} memory={} memory_signal={} device_local_mb={} host_visible_device_local_mb={} host_pointer_import={} host_pointer_align={} portability_subset={} type={:?} name={device_name:?}",
|
||||
api_floor::version_str(self.device_api_version),
|
||||
api_floor::version_str(api_floor::MIN_SUPPORTED_API),
|
||||
self.memory.topology.slug(),
|
||||
self.memory.signal.slug(),
|
||||
self.memory.device_local_bytes >> 20,
|
||||
self.memory.host_visible_device_local_bytes >> 20,
|
||||
self.dma_buf_import.slug(),
|
||||
self.host_pointer.rung.slug(),
|
||||
self.host_pointer.min_alignment,
|
||||
self.portability_subset,
|
||||
self.device_type,
|
||||
)
|
||||
@@ -132,7 +135,10 @@ mod tests {
|
||||
HostGpuCaps {
|
||||
memory: memory_topology::classify_memory(props),
|
||||
quirks: DriverQuirk::default(),
|
||||
dma_buf_import: DmaBufImport::Supported,
|
||||
host_pointer: HostPointerCaps {
|
||||
rung: HostPointerImport::Supported,
|
||||
min_alignment: 4096,
|
||||
},
|
||||
portability_subset: false,
|
||||
device_api_version: api,
|
||||
device_type: vk::PhysicalDeviceType::DISCRETE_GPU,
|
||||
@@ -152,21 +158,42 @@ mod tests {
|
||||
// The baseline is stated on every line so no reader mistakes the
|
||||
// device's reported version for a requirement.
|
||||
assert!(line.contains("baseline=1.2"), "{line}");
|
||||
// Which rung the zero-copy rails are on. "This host is slow" and "this
|
||||
// host cannot import guest pages" are the same report, and this is the
|
||||
// field that separates them without a second boot.
|
||||
assert!(line.contains("dma_buf_import=supported"), "{line}");
|
||||
}
|
||||
|
||||
/// A host that cannot import guest pages says so on the same line, naming
|
||||
/// the check that refused rather than just the absence.
|
||||
/// The host-pointer rung and its granularity are on the same line, and the
|
||||
/// granularity is there because it is measured rather than assumed: a
|
||||
/// MoltenVK device reports Apple's page size and a Linux driver may report
|
||||
/// more, and "the import refused" and "the import ran at a granularity
|
||||
/// nobody expected" are two different bug reports.
|
||||
#[test]
|
||||
fn the_selection_line_carries_the_host_pointer_rung_and_its_granularity() {
|
||||
let line = caps(vk::API_VERSION_1_2, &fixtures::apple_m3_max()).selection_line("Apple");
|
||||
assert!(line.contains("host_pointer_import=supported"), "{line}");
|
||||
assert!(line.contains("host_pointer_align=4096"), "{line}");
|
||||
|
||||
let mut refused = caps(vk::API_VERSION_1_2, &fixtures::apple_m3_max());
|
||||
refused.host_pointer = HostPointerCaps::default();
|
||||
let line = refused.selection_line("Apple");
|
||||
assert!(line.contains("host_pointer_import=unqueried"), "{line}");
|
||||
// A refused rung carries no granularity, so the line cannot suggest one
|
||||
// an import site could act on.
|
||||
assert!(line.contains("host_pointer_align=0"), "{line}");
|
||||
}
|
||||
|
||||
/// A host that cannot import guest RAM says so on the same line, naming the
|
||||
/// check that refused rather than just the absence. "This host is slow" and
|
||||
/// "this host cannot import guest RAM" are the same bug report, and this is
|
||||
/// the field that separates them without a second boot.
|
||||
#[test]
|
||||
fn the_selection_line_names_the_rung_that_refused_the_import() {
|
||||
let mut c = caps(vk::API_VERSION_1_2, &fixtures::apple_m3_max());
|
||||
c.dma_buf_import = DmaBufImport::NoDmaBufExtension;
|
||||
c.host_pointer = HostPointerCaps {
|
||||
rung: HostPointerImport::NoHostPointerExtension,
|
||||
min_alignment: 0,
|
||||
};
|
||||
let line = c.selection_line("Apple M3 Max");
|
||||
assert!(
|
||||
line.contains("dma_buf_import=no_dma_buf_extension"),
|
||||
line.contains("host_pointer_import=no_host_pointer_extension"),
|
||||
"{line}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -269,14 +269,14 @@ pub(crate) struct DeviceContext {
|
||||
/// physical device, and the previous code re-queried it through the loader
|
||||
/// on every single allocation.
|
||||
pub memory_properties: vk::PhysicalDeviceMemoryProperties,
|
||||
/// `VK_KHR_external_memory_fd` entry points, loaded only where
|
||||
/// [`HostGpuCaps::dma_buf_import`] resolved to `Supported` — which is also
|
||||
/// the only rung on which the extension was enabled, so loading it on any
|
||||
/// other would resolve entry points the device was never asked for.
|
||||
/// `VK_EXT_external_memory_host` entry points, loaded only where
|
||||
/// [`HostGpuCaps::host_pointer`] resolved to `Supported` — which is also the
|
||||
/// only rung on which the extension was enabled, so loading it on any other
|
||||
/// would resolve entry points the device was never asked for.
|
||||
///
|
||||
/// `None` is the answer on every host without dma-buf, and
|
||||
/// [`super::dmabuf::import_buffer`] declines by name when it sees one.
|
||||
pub external_memory_fd: Option<ash::khr::external_memory_fd::Device>,
|
||||
/// `None` is the answer on every host without the extension, and the import
|
||||
/// site declines by name when it sees one.
|
||||
pub external_memory_host: Option<ash::ext::external_memory_host::Device>,
|
||||
/// Queue family used for all engine submits (graphics draws + compute).
|
||||
pub gq: u32,
|
||||
/// True when `gq` supports both GRAPHICS and COMPUTE (required for engine compute).
|
||||
@@ -526,20 +526,28 @@ impl DeviceContext {
|
||||
// shader buffer access (index fetch, attachment access, and
|
||||
// encoder-level suspects remain open).
|
||||
let enabled = features.enabled_features();
|
||||
// Whether guest pages can reach this device as a dma-buf import. Asked
|
||||
// alongside the other capability queries, and — like them — the only
|
||||
// producer of the extension strings its answer requires.
|
||||
let dma_buf_import = crate::backend::vulkan::caps::external_memory::query(
|
||||
&instance,
|
||||
pd,
|
||||
&has_device_extension,
|
||||
);
|
||||
// Published for the guest-page export side, which decides whether to ask
|
||||
// the host for a dma-buf at all and has no device context to read. Set
|
||||
// here rather than at the end of this function so a later failure leaves
|
||||
// the export side knowing the answer too — it is a property of the
|
||||
// physical device, and nothing below can change it.
|
||||
crate::backend::vulkan::caps::external_memory::latch(dma_buf_import);
|
||||
// Whether guest RAM can reach this device as a host-pointer import over
|
||||
// whole RAMBlocks, and at what granularity. Same shape as the query
|
||||
// above and for the same reason: the answer is the only producer of the
|
||||
// extension string it requires.
|
||||
let host_pointer =
|
||||
crate::backend::vulkan::caps::host_pointer::query(&instance, pd, &has_device_extension);
|
||||
// Published for `runtime::guest_ram_map`, which builds the imports and
|
||||
// has no device context to read the granularity from. A negative rung
|
||||
// withdraws it rather than publishing zero, so the absence of a number
|
||||
// is itself the gate and no site can act on a granularity from a device
|
||||
// that declined the handle type.
|
||||
match host_pointer.rung {
|
||||
crate::backend::vulkan::caps::HostPointerImport::Supported => {
|
||||
crate::runtime::guest_ram::latch_granularity(host_pointer.min_alignment);
|
||||
}
|
||||
_ => crate::runtime::guest_ram::forget_granularity(),
|
||||
}
|
||||
// Every import this process holds names a `VkDeviceMemory` that dies
|
||||
// with the device below. Dropping them here, before the new one exists,
|
||||
// is what makes a recreate rebuild against fresh identities instead of
|
||||
// resolving a stale slice against a handle that is gone.
|
||||
crate::runtime::guest_ram_map::reset();
|
||||
let portability_subset = has_device_extension(vk::KHR_PORTABILITY_SUBSET_NAME);
|
||||
let vertex_attribute_divisor = has_device_extension(vk::KHR_VERTEX_ATTRIBUTE_DIVISOR_NAME);
|
||||
#[cfg(feature = "host-window")]
|
||||
@@ -608,7 +616,9 @@ impl DeviceContext {
|
||||
enabled_device_extensions.extend(features.required_extensions());
|
||||
// Only the `Supported` rung names any, so a host without dma-buf does
|
||||
// not fail device creation asking for an extension it does not have.
|
||||
enabled_device_extensions.extend(dma_buf_import.required_extensions());
|
||||
// Only the `Supported` rung names `VK_EXT_external_memory_host`, so a
|
||||
// host without it gets a device rather than a failed `vkCreateDevice`.
|
||||
enabled_device_extensions.extend(host_pointer.rung.required_extensions());
|
||||
// These three are built in `caps` too. They are bound to locals here
|
||||
// only because `push_next` borrows them for the lifetime of `dci`.
|
||||
let mut en16 = features.enabled_16bit_storage();
|
||||
@@ -665,17 +675,19 @@ impl DeviceContext {
|
||||
let caps = HostGpuCaps {
|
||||
memory: classify_memory(&memory_properties),
|
||||
quirks: DriverQuirk::for_portability_subset(portability_subset),
|
||||
dma_buf_import,
|
||||
host_pointer,
|
||||
portability_subset,
|
||||
device_api_version: props.api_version,
|
||||
device_type: props.device_type,
|
||||
};
|
||||
// Loaded from the same answer that enabled the extension, so the two
|
||||
// cannot disagree about whether these entry points are legal to call.
|
||||
let external_memory_fd = caps
|
||||
.dma_buf_import
|
||||
// Loaded from the same answer that enabled the extension, so the two
|
||||
// cannot disagree about whether these entry points are legal to call.
|
||||
let external_memory_host = caps
|
||||
.host_pointer
|
||||
.is_available()
|
||||
.then(|| ash::khr::external_memory_fd::Device::new(&instance, &device));
|
||||
.then(|| ash::ext::external_memory_host::Device::new(&instance, &device));
|
||||
let device_name = CStr::from_ptr(props.device_name.as_ptr())
|
||||
.to_string_lossy()
|
||||
.into_owned();
|
||||
@@ -743,7 +755,7 @@ impl DeviceContext {
|
||||
device,
|
||||
caps,
|
||||
memory_properties,
|
||||
external_memory_fd,
|
||||
external_memory_host,
|
||||
gq,
|
||||
compute_capable,
|
||||
storage_image_write_without_format: storage_image_write_without_format_bgra,
|
||||
|
||||
@@ -1,776 +0,0 @@
|
||||
//! Import a dma-buf fd as `VkDeviceMemory` and bind a `VkBuffer` to it.
|
||||
//!
|
||||
//! This is the one place a foreign allocation becomes something the engine can
|
||||
//! bind. Everything about *which* pages the fd covers is decided before it gets
|
||||
//! here — see [`crate::qemu::host_ops`] for how a guest page run becomes an fd,
|
||||
//! and [`super::super::caps::external_memory`] for why a dma-buf is admissible
|
||||
//! where a host-pointer import is not.
|
||||
//!
|
||||
//! # The fd ownership rule
|
||||
//!
|
||||
//! `vkAllocateMemory` with a chained `VkImportMemoryFdInfoKHR` **takes ownership
|
||||
//! of the fd on success** and leaves it with the caller on failure. Get that
|
||||
//! backwards in either direction and the bug is invisible until it is fatal: a
|
||||
//! double close eventually closes an unrelated fd this process has since opened,
|
||||
//! and a missed close leaks one per imported buffer until the process hits its
|
||||
//! limit mid-frame.
|
||||
//!
|
||||
//! [`import_buffer`] takes an [`OwnedFd`] by value so the type system carries the
|
||||
//! rule. On the success path the fd is released with [`IntoRawFd::into_raw_fd`]
|
||||
//! and deliberately not closed; on every failure path it is simply dropped,
|
||||
//! which closes it. There is no path that does both and none that does neither.
|
||||
|
||||
use std::os::fd::{AsRawFd, IntoRawFd, OwnedFd};
|
||||
use std::sync::Arc;
|
||||
|
||||
use ash::vk;
|
||||
|
||||
use super::types::GuestDmaBuf;
|
||||
use crate::observe::Decline;
|
||||
|
||||
/// A guest page run living on the GPU as a bindable buffer, with no copy
|
||||
/// between it and the guest's own view of those pages.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct ImportedDmaBuf {
|
||||
pub buffer: vk::Buffer,
|
||||
pub memory: vk::DeviceMemory,
|
||||
/// Bytes the fd covers. The buffer spans all of it.
|
||||
pub size: vk::DeviceSize,
|
||||
}
|
||||
|
||||
impl ImportedDmaBuf {
|
||||
/// Release both halves. Freeing the memory is what ends the GPU's access to
|
||||
/// the guest pages, so this is the revocation the capability doc promises —
|
||||
/// it must run even on a teardown path that is otherwise giving up.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// No submission may still reference `buffer`, and `device` must be the one
|
||||
/// the import was made against.
|
||||
pub(crate) unsafe fn destroy(self, device: &ash::Device) {
|
||||
unsafe {
|
||||
device.destroy_buffer(self.buffer, None);
|
||||
device.free_memory(self.memory, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A check that stopped a dma-buf from becoming a bindable buffer.
|
||||
///
|
||||
/// Every variant is a distinct check with its own slug: an import that fails
|
||||
/// costs the frame a copy at best and the guest's work at worst, and "the import
|
||||
/// declined" without saying which step is half a diagnostic.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum DmaBufDecline {
|
||||
/// The device is not on the `Supported` rung. Carries the rung so the log
|
||||
/// says whether this host lacks the extension or declines the handle type.
|
||||
Unsupported {
|
||||
rung: crate::backend::vulkan::caps::DmaBufImport,
|
||||
},
|
||||
/// `vkGetMemoryFdPropertiesKHR` failed. The fd is not one this device can
|
||||
/// answer about — a non-dma-buf fd reaches here, as does a dma-buf whose
|
||||
/// exporter this driver cannot talk to.
|
||||
FdProperties { result: vk::Result },
|
||||
/// The device accepts the fd but reports no memory type for it. Distinct
|
||||
/// from [`Self::NoCommonMemoryType`]: here the *fd* matched nothing, before
|
||||
/// the buffer's own requirements narrowed anything.
|
||||
NoImportableMemoryType,
|
||||
/// `vkCreateBuffer` failed for a buffer declared external.
|
||||
CreateBuffer { result: vk::Result },
|
||||
/// The memory types that accept the fd and the memory types the buffer
|
||||
/// accepts are disjoint, so no single index satisfies both.
|
||||
NoCommonMemoryType { fd_bits: u32, buffer_bits: u32 },
|
||||
/// The buffer needs more bytes than the fd covers. A guest page run shorter
|
||||
/// than the resource that named it lands here rather than binding a buffer
|
||||
/// that reads past the end of the import.
|
||||
TooSmall { required: u64, available: u64 },
|
||||
/// `vkAllocateMemory` failed. The fd is still owned by this process and has
|
||||
/// been closed.
|
||||
AllocateMemory { result: vk::Result },
|
||||
/// `vkBindBufferMemory` failed after a successful import.
|
||||
BindBuffer { result: vk::Result },
|
||||
/// The runtime's fd could not be duplicated, so there was nothing to hand
|
||||
/// `vkAllocateMemory` that this process could also keep. Distinct from every
|
||||
/// check above because it fails before the device is asked anything at all —
|
||||
/// a process at its descriptor limit reaches here, and no Vulkan result
|
||||
/// describes that.
|
||||
CloneFd { errno: i32 },
|
||||
/// The pinned-bytes bound is full of imports the command buffer now being
|
||||
/// recorded already names, so nothing can be displaced to make room. Not a
|
||||
/// device refusal and not a page-list problem: one draw asked for more guest
|
||||
/// memory at once than the rail is allowed to pin, and the caller gathers on
|
||||
/// the CPU instead.
|
||||
BoundInUse { held: u64, incoming: u64 },
|
||||
}
|
||||
|
||||
impl Decline for DmaBufDecline {
|
||||
fn slug(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Unsupported { .. } => "vk_dmabuf_unsupported",
|
||||
Self::FdProperties { .. } => "vk_dmabuf_fd_properties",
|
||||
Self::NoImportableMemoryType => "vk_dmabuf_no_importable_memory_type",
|
||||
Self::CreateBuffer { .. } => "vk_dmabuf_create_buffer",
|
||||
Self::NoCommonMemoryType { .. } => "vk_dmabuf_no_common_memory_type",
|
||||
Self::TooSmall { .. } => "vk_dmabuf_too_small",
|
||||
Self::AllocateMemory { .. } => "vk_dmabuf_allocate_memory",
|
||||
Self::BindBuffer { .. } => "vk_dmabuf_bind_buffer",
|
||||
Self::CloneFd { .. } => "vk_dmabuf_clone_fd",
|
||||
Self::BoundInUse { .. } => "vk_dmabuf_bound_in_use",
|
||||
}
|
||||
}
|
||||
|
||||
fn fields(&self) -> Vec<(&'static str, String)> {
|
||||
match self {
|
||||
Self::Unsupported { rung } => vec![("rung", rung.slug().to_string())],
|
||||
Self::FdProperties { result }
|
||||
| Self::CreateBuffer { result }
|
||||
| Self::AllocateMemory { result }
|
||||
| Self::BindBuffer { result } => {
|
||||
vec![(
|
||||
"vk_result",
|
||||
format!("{result:?}").replace(char::is_whitespace, "_"),
|
||||
)]
|
||||
}
|
||||
Self::NoImportableMemoryType => Vec::new(),
|
||||
Self::CloneFd { errno } => vec![("errno", errno.to_string())],
|
||||
Self::NoCommonMemoryType {
|
||||
fd_bits,
|
||||
buffer_bits,
|
||||
} => vec![
|
||||
("fd_bits", format!("{fd_bits:#x}")),
|
||||
("buffer_bits", format!("{buffer_bits:#x}")),
|
||||
],
|
||||
Self::TooSmall {
|
||||
required,
|
||||
available,
|
||||
} => vec![
|
||||
("required", required.to_string()),
|
||||
("available", available.to_string()),
|
||||
],
|
||||
Self::BoundInUse { held, incoming } => vec![
|
||||
("held", held.to_string()),
|
||||
("incoming", incoming.to_string()),
|
||||
],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
crate::observe::decline::decline_display!(DmaBufDecline);
|
||||
|
||||
/// Turn a dma-buf fd covering `size` bytes of guest pages into a bound
|
||||
/// `VkBuffer`.
|
||||
///
|
||||
/// The buffer is created with [`GUEST_IMPORT_USAGE`], which is the same usage
|
||||
/// the capability query asked the device about — so a device on the `Supported`
|
||||
/// rung has already answered yes to this exact combination.
|
||||
///
|
||||
/// The allocation is dedicated. One import is one buffer by construction, which
|
||||
/// is precisely the dedicated model, and some drivers require it for dma-buf
|
||||
/// imports rather than merely preferring it.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `fd` must be a dma-buf whose mapping covers at least `size` bytes, and it
|
||||
/// must remain valid for the lifetime of the returned import — which it does,
|
||||
/// because the import takes ownership of it.
|
||||
///
|
||||
/// [`GUEST_IMPORT_USAGE`]: crate::backend::vulkan::caps::external_memory::GUEST_IMPORT_USAGE
|
||||
pub(crate) unsafe fn import_buffer(
|
||||
ctx: &super::context::DeviceContext,
|
||||
fd: OwnedFd,
|
||||
size: u64,
|
||||
) -> Result<ImportedDmaBuf, DmaBufDecline> {
|
||||
use crate::backend::vulkan::caps::external_memory::GUEST_IMPORT_USAGE;
|
||||
|
||||
let Some(loader) = ctx.external_memory_fd.as_ref() else {
|
||||
return Err(DmaBufDecline::Unsupported {
|
||||
rung: ctx.caps.dma_buf_import,
|
||||
});
|
||||
};
|
||||
const HANDLE_TYPE: vk::ExternalMemoryHandleTypeFlags =
|
||||
vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT;
|
||||
|
||||
// Which memory types will accept *this* fd. Asked before anything is
|
||||
// created, because the answer is a property of the exporter and can differ
|
||||
// between two fds on one device — guest RAM and a GPU-exported buffer are
|
||||
// both dma-bufs and need not land in the same heap.
|
||||
let mut fd_props = vk::MemoryFdPropertiesKHR::default();
|
||||
unsafe { loader.get_memory_fd_properties(HANDLE_TYPE, fd.as_raw_fd(), &mut fd_props) }
|
||||
.map_err(|result| DmaBufDecline::FdProperties { result })?;
|
||||
if fd_props.memory_type_bits == 0 {
|
||||
return Err(DmaBufDecline::NoImportableMemoryType);
|
||||
}
|
||||
|
||||
let mut external = vk::ExternalMemoryBufferCreateInfo::default().handle_types(HANDLE_TYPE);
|
||||
let create = vk::BufferCreateInfo::default()
|
||||
.size(size)
|
||||
.usage(GUEST_IMPORT_USAGE)
|
||||
.sharing_mode(vk::SharingMode::EXCLUSIVE)
|
||||
.push_next(&mut external);
|
||||
let buffer = unsafe { ctx.device.create_buffer(&create, None) }
|
||||
.map_err(|result| DmaBufDecline::CreateBuffer { result })?;
|
||||
|
||||
// From here every failure must destroy the buffer before returning, so the
|
||||
// work is done in a closure and the cleanup happens once at the end.
|
||||
let bound = (|| {
|
||||
let reqs = unsafe { ctx.device.get_buffer_memory_requirements(buffer) };
|
||||
if reqs.size > size {
|
||||
return Err(DmaBufDecline::TooSmall {
|
||||
required: reqs.size,
|
||||
available: size,
|
||||
});
|
||||
}
|
||||
let common = reqs.memory_type_bits & fd_props.memory_type_bits;
|
||||
if common == 0 {
|
||||
return Err(DmaBufDecline::NoCommonMemoryType {
|
||||
fd_bits: fd_props.memory_type_bits,
|
||||
buffer_bits: reqs.memory_type_bits,
|
||||
});
|
||||
}
|
||||
// The lowest common index. There is no preference to express: the
|
||||
// exporter already decided where these pages live, so the memory-class
|
||||
// machinery that ranks heaps for owned allocations has nothing to rank
|
||||
// here — every bit in `common` names the same underlying pages.
|
||||
let memory_type_index = common.trailing_zeros();
|
||||
|
||||
let mut import = vk::ImportMemoryFdInfoKHR::default()
|
||||
.handle_type(HANDLE_TYPE)
|
||||
.fd(fd.as_raw_fd());
|
||||
let mut dedicated = vk::MemoryDedicatedAllocateInfo::default().buffer(buffer);
|
||||
let allocate = vk::MemoryAllocateInfo::default()
|
||||
.allocation_size(size)
|
||||
.memory_type_index(memory_type_index)
|
||||
.push_next(&mut import)
|
||||
.push_next(&mut dedicated);
|
||||
let memory = unsafe { ctx.device.allocate_memory(&allocate, None) }
|
||||
.map_err(|result| DmaBufDecline::AllocateMemory { result })?;
|
||||
|
||||
match unsafe { ctx.device.bind_buffer_memory(buffer, memory, 0) } {
|
||||
Ok(()) => Ok(ImportedDmaBuf {
|
||||
buffer,
|
||||
memory,
|
||||
size,
|
||||
}),
|
||||
Err(result) => {
|
||||
// The import succeeded, so the fd is the driver's now and
|
||||
// freeing the memory is what releases it.
|
||||
unsafe { ctx.device.free_memory(memory, None) };
|
||||
Err(DmaBufDecline::BindBuffer { result })
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
match bound {
|
||||
Ok(import) => {
|
||||
// Ownership moved to the driver at `vkAllocateMemory`. Releasing the
|
||||
// `OwnedFd` without closing it is what keeps this from being a
|
||||
// double close the moment the driver closes its copy.
|
||||
let _ = fd.into_raw_fd();
|
||||
Ok(import)
|
||||
}
|
||||
Err(decline) => {
|
||||
unsafe { ctx.device.destroy_buffer(buffer, None) };
|
||||
// `fd` drops here and closes. Correct on every arm above: either
|
||||
// `vkAllocateMemory` was never reached, or it failed — and a failed
|
||||
// import leaves the fd with the caller.
|
||||
Err(decline)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A check that stopped a resident's frame from being copied straight into the
|
||||
/// guest's own pages, so the flush took the CPU route instead.
|
||||
///
|
||||
/// Every one of these is a *routing* answer rather than a loss — the copying
|
||||
/// rail still lands the frame — but each is a whole flush's worth of memcpy that
|
||||
/// the device paid and did not have to, so they are named individually and
|
||||
/// counted.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum GuestWriteDecline {
|
||||
/// The device cannot import a dma-buf at all. Carries the rung so the log
|
||||
/// says which check refused; expected on every non-Linux host.
|
||||
Unsupported {
|
||||
rung: crate::backend::vulkan::caps::DmaBufImport,
|
||||
},
|
||||
/// The resident's physical channel order is not the guest's scanout order,
|
||||
/// so landing it would need an R/B exchange — which a buffer→image copy
|
||||
/// cannot perform. The copying rail's `into_bgra8` is where that lives.
|
||||
NotScanoutOrder,
|
||||
/// The resident's geometry is not the geometry the window promised the
|
||||
/// guest. Copying anyway would land one extent's pixels under another's row
|
||||
/// pitch.
|
||||
GeometryMoved {
|
||||
resident_width: u32,
|
||||
resident_height: u32,
|
||||
want_width: u32,
|
||||
want_height: u32,
|
||||
},
|
||||
/// The frame's last byte falls past the end of the imported window. A short
|
||||
/// page list reaches here rather than writing past the pages the fd names.
|
||||
WindowTooSmall { need: u64, have: u64 },
|
||||
/// The import itself declined; the inner reason names the step.
|
||||
Import { inner: DmaBufDecline },
|
||||
}
|
||||
|
||||
impl Decline for GuestWriteDecline {
|
||||
fn slug(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Unsupported { .. } => "gpu_writeback_unsupported",
|
||||
Self::NotScanoutOrder => "gpu_writeback_not_scanout_order",
|
||||
Self::GeometryMoved { .. } => "gpu_writeback_geometry_moved",
|
||||
Self::WindowTooSmall { .. } => "gpu_writeback_window_too_small",
|
||||
// The inner decline's own slug, so a driver that refuses the fd and
|
||||
// a page run that is too short stay as distinguishable here as they
|
||||
// are at the import site.
|
||||
Self::Import { inner } => inner.slug(),
|
||||
}
|
||||
}
|
||||
|
||||
fn fields(&self) -> Vec<(&'static str, String)> {
|
||||
match self {
|
||||
Self::Unsupported { rung } => vec![("rung", rung.slug().to_string())],
|
||||
Self::NotScanoutOrder => Vec::new(),
|
||||
Self::GeometryMoved {
|
||||
resident_width,
|
||||
resident_height,
|
||||
want_width,
|
||||
want_height,
|
||||
} => vec![
|
||||
("resident", format!("{resident_width}x{resident_height}")),
|
||||
("want", format!("{want_width}x{want_height}")),
|
||||
],
|
||||
Self::WindowTooSmall { need, have } => {
|
||||
vec![("need", need.to_string()), ("have", have.to_string())]
|
||||
}
|
||||
Self::Import { inner } => inner.fields(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
crate::observe::decline::decline_display!(GuestWriteDecline);
|
||||
|
||||
/// Imports of guest page windows, kept across frames.
|
||||
///
|
||||
/// # Why this is a second cache and not the runtime's
|
||||
///
|
||||
/// [`crate::runtime::guest_dmabuf`] caches the *fd* — the result of the page
|
||||
/// walk and the pin. This caches the `VkDeviceMemory` and `VkBuffer` made from
|
||||
/// one, which is a different object with a different owner: the fd belongs to
|
||||
/// this process and the device memory belongs to the driver, and only the
|
||||
/// importer can release the second. Two caches, each bounding what it actually
|
||||
/// holds, is the arrangement that keeps an eviction in either from being a
|
||||
/// use-after-free in the other.
|
||||
///
|
||||
/// # What bounds it
|
||||
///
|
||||
/// The same guest bytes the runtime cache pins, because an import references
|
||||
/// exactly the pages its fd names and no others. Making the two bounds equal is
|
||||
/// what keeps a window that the runtime is still caching from being re-imported
|
||||
/// every frame — a smaller bound here would pay `vkAllocateMemory` per flush to
|
||||
/// hold pages that are pinned regardless.
|
||||
///
|
||||
/// # When an entry may be freed
|
||||
///
|
||||
/// `vkFreeMemory` on memory an in-flight command buffer references is undefined
|
||||
/// behaviour, so this cache never frees an eviction itself: [`Self::get_or_import`]
|
||||
/// hands the displaced imports back and
|
||||
/// [`super::pools::ResourcePools::import_guest_window`] routes each through the
|
||||
/// ring's graveyard, which destroys it once every slot open at that instant has
|
||||
/// retired. That is what lets a *draw* import a window — it records a copy and
|
||||
/// submits without waiting, so the "no consumer outlives its own fence" rule the
|
||||
/// writeback rail relied on is no longer true of every caller.
|
||||
///
|
||||
/// The graveyard cannot see the command buffer currently being **recorded**,
|
||||
/// though, because its slot is not pending until submit. So an eviction is also
|
||||
/// refused for any entry the open recording has already been handed, tracked by
|
||||
/// [`Self::epoch`]; a draw whose own imports do not fit under the bound is
|
||||
/// declined ([`DmaBufDecline::BoundInUse`]) and gathers on the CPU instead.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct ImportCache {
|
||||
entries: Vec<ImportEntry>,
|
||||
bytes: u64,
|
||||
clock: u64,
|
||||
/// Bumped by [`Self::begin_recording`] at the start of each command buffer.
|
||||
/// An entry stamped with the current value has been handed to the CB being
|
||||
/// recorded right now, which no fence and no graveyard mask can yet name.
|
||||
epoch: u64,
|
||||
}
|
||||
|
||||
struct ImportEntry {
|
||||
/// [`GuestDmaBuf::id`], which is monotonic and never reused. The fd *number*
|
||||
/// cannot be the key: it is recycled the instant one closes, so a freed
|
||||
/// window and a fresh one can wear the same number and the second would bind
|
||||
/// the first's memory.
|
||||
window: u64,
|
||||
/// Holding the runtime's window keeps its id from being retired while this
|
||||
/// entry names it, so the key cannot go stale under the entry it identifies.
|
||||
_window_fd: Arc<GuestDmaBuf>,
|
||||
import: ImportedDmaBuf,
|
||||
used: u64,
|
||||
/// [`ImportCache::epoch`] when this entry was last handed out. Equal to the
|
||||
/// live epoch means the command buffer still recording may already name it.
|
||||
epoch: u64,
|
||||
}
|
||||
|
||||
/// Most guest memory this device will hold imported at once. Equal to the
|
||||
/// runtime cache's pin bound by construction; see [`ImportCache`].
|
||||
const MAX_IMPORTED_BYTES: u64 = crate::runtime::guest_dmabuf::MAX_PINNED_BYTES;
|
||||
|
||||
/// Index of the entry to drop next: the one least recently handed out, skipping
|
||||
/// every entry the command buffer now recording has already been given.
|
||||
///
|
||||
/// Separate from the eviction loop so the choice can be tested without a Vulkan
|
||||
/// device — the loop's other half is handing the import to the graveyard, and
|
||||
/// getting *which* entry it displaces wrong is either a re-import every frame or
|
||||
/// a copy reading freed memory.
|
||||
fn lru_victim(entries: &[ImportEntry], live_epoch: u64) -> Option<usize> {
|
||||
entries
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, e)| e.epoch != live_epoch)
|
||||
.min_by_key(|(_, e)| e.used)
|
||||
.map(|(i, _)| i)
|
||||
}
|
||||
|
||||
impl ImportCache {
|
||||
/// Start of a command buffer's recording. Every entry handed out from here
|
||||
/// until the next call is pinned against eviction, because nothing else can
|
||||
/// name a CB that has not been submitted.
|
||||
pub(crate) fn begin_recording(&mut self) {
|
||||
self.epoch += 1;
|
||||
}
|
||||
|
||||
/// The bound `window`'s pages reach the device through, imported if this is
|
||||
/// the first time this window has been asked for.
|
||||
///
|
||||
/// `size` is the whole extent the fd covers, so one window is one buffer
|
||||
/// whatever part of it a given copy names — a caller wanting a sub-range
|
||||
/// says so with the copy's own offset rather than by importing twice.
|
||||
///
|
||||
/// Imports displaced to make room are **appended to `displaced` rather than
|
||||
/// freed**: the caller owns disposing of them safely, which for a submitting
|
||||
/// caller means the ring's graveyard. See [`ImportCache`].
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `device` must be the one `ctx` owns.
|
||||
pub(crate) unsafe fn get_or_import(
|
||||
&mut self,
|
||||
ctx: &super::context::DeviceContext,
|
||||
window: &Arc<GuestDmaBuf>,
|
||||
size: u64,
|
||||
displaced: &mut Vec<ImportedDmaBuf>,
|
||||
) -> Result<ImportedDmaBuf, DmaBufDecline> {
|
||||
self.clock += 1;
|
||||
let clock = self.clock;
|
||||
let epoch = self.epoch;
|
||||
if let Some(entry) = self.entries.iter_mut().find(|e| e.window == window.id) {
|
||||
entry.used = clock;
|
||||
entry.epoch = epoch;
|
||||
return Ok(entry.import);
|
||||
}
|
||||
// Before the import rather than after it, so the bound is restored
|
||||
// before it is added to rather than after.
|
||||
self.evict_to_bound(size, displaced);
|
||||
if self.bytes.saturating_add(size) > MAX_IMPORTED_BYTES {
|
||||
// Everything left is pinned by the CB now recording, so there is no
|
||||
// eviction that would not free memory a recorded copy reads. The
|
||||
// caller still has its CPU gather; taking it is slower than this
|
||||
// rail and correct, which is the whole reason the fallback is kept.
|
||||
return Err(DmaBufDecline::BoundInUse {
|
||||
held: self.bytes,
|
||||
incoming: size,
|
||||
});
|
||||
}
|
||||
// The driver takes the fd it is given, and the runtime keeps the
|
||||
// original for every other importer and for the revocation that closing
|
||||
// it performs. So the import gets a duplicate; `import_buffer` then owns
|
||||
// exactly one fd and its ownership rule stays a local property.
|
||||
let fd = window.fd.try_clone().map_err(|e| DmaBufDecline::CloneFd {
|
||||
errno: e.raw_os_error().unwrap_or(0),
|
||||
})?;
|
||||
let import = unsafe { import_buffer(ctx, fd, size) }?;
|
||||
self.entries.push(ImportEntry {
|
||||
window: window.id,
|
||||
_window_fd: Arc::clone(window),
|
||||
import,
|
||||
used: clock,
|
||||
epoch,
|
||||
});
|
||||
self.bytes += size;
|
||||
Ok(import)
|
||||
}
|
||||
|
||||
/// Displace least-recently-used imports into `displaced` until `incoming`
|
||||
/// more bytes would fit under [`MAX_IMPORTED_BYTES`], or until everything
|
||||
/// left is pinned by the open recording.
|
||||
fn evict_to_bound(&mut self, incoming: u64, displaced: &mut Vec<ImportedDmaBuf>) {
|
||||
while self.bytes.saturating_add(incoming) > MAX_IMPORTED_BYTES {
|
||||
let Some(victim) = lru_victim(&self.entries, self.epoch) else {
|
||||
return;
|
||||
};
|
||||
let entry = self.entries.swap_remove(victim);
|
||||
self.bytes = self.bytes.saturating_sub(entry.import.size);
|
||||
displaced.push(entry.import);
|
||||
}
|
||||
}
|
||||
|
||||
/// Release every import. The revocation this rail's capability doc promises,
|
||||
/// so it must run on a teardown that is otherwise giving up.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// No submission may still reference any import, and `device` must be the
|
||||
/// one they were made against.
|
||||
pub(crate) unsafe fn destroy_all(&mut self, device: &ash::Device) {
|
||||
for entry in self.entries.drain(..) {
|
||||
unsafe { entry.import.destroy(device) };
|
||||
}
|
||||
self.bytes = 0;
|
||||
}
|
||||
|
||||
/// Guest memory currently reachable by the device through imports. Census
|
||||
/// only.
|
||||
pub(crate) fn imported_bytes(&self) -> u64 {
|
||||
self.bytes
|
||||
}
|
||||
|
||||
/// Windows currently imported. Census only.
|
||||
pub(crate) fn len(&self) -> usize {
|
||||
self.entries.len()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn every_decline() -> Vec<DmaBufDecline> {
|
||||
vec![
|
||||
DmaBufDecline::Unsupported {
|
||||
rung: crate::backend::vulkan::caps::DmaBufImport::NoDmaBufExtension,
|
||||
},
|
||||
DmaBufDecline::FdProperties {
|
||||
result: vk::Result::ERROR_INVALID_EXTERNAL_HANDLE,
|
||||
},
|
||||
DmaBufDecline::NoImportableMemoryType,
|
||||
DmaBufDecline::CreateBuffer {
|
||||
result: vk::Result::ERROR_OUT_OF_HOST_MEMORY,
|
||||
},
|
||||
DmaBufDecline::NoCommonMemoryType {
|
||||
fd_bits: 0x9,
|
||||
buffer_bits: 0x6,
|
||||
},
|
||||
DmaBufDecline::TooSmall {
|
||||
required: 8192,
|
||||
available: 4096,
|
||||
},
|
||||
DmaBufDecline::AllocateMemory {
|
||||
result: vk::Result::ERROR_OUT_OF_DEVICE_MEMORY,
|
||||
},
|
||||
DmaBufDecline::BindBuffer {
|
||||
result: vk::Result::ERROR_INVALID_EXTERNAL_HANDLE,
|
||||
},
|
||||
DmaBufDecline::CloneFd { errno: 24 },
|
||||
]
|
||||
}
|
||||
|
||||
/// One slug per check. Two of these sharing one would mean watching the
|
||||
/// import fail in the log and being unable to tell a driver that refused the
|
||||
/// fd from a page run that was simply too short.
|
||||
#[test]
|
||||
fn every_decline_has_its_own_log_safe_slug() {
|
||||
let mut slugs: Vec<_> = every_decline().iter().map(|d| d.slug()).collect();
|
||||
let count = slugs.len();
|
||||
slugs.sort_unstable();
|
||||
slugs.dedup();
|
||||
assert_eq!(slugs.len(), count, "two dma-buf declines share a slug");
|
||||
for slug in slugs {
|
||||
assert!(
|
||||
slug.starts_with("vk_dmabuf_"),
|
||||
"{slug} is not greppable as a dma-buf decline"
|
||||
);
|
||||
assert!(slug
|
||||
.bytes()
|
||||
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_'));
|
||||
}
|
||||
}
|
||||
|
||||
/// A decline that names only its class leaves out the value that caused it.
|
||||
/// The two that carry a size and the two that carry a bitmask are the ones
|
||||
/// where the number *is* the diagnosis.
|
||||
#[test]
|
||||
fn declines_carry_the_values_behind_them() {
|
||||
for decline in every_decline() {
|
||||
let rendered = decline.to_string();
|
||||
assert!(rendered.contains(decline.slug()), "{rendered}");
|
||||
assert!(
|
||||
!rendered.contains(' ') || rendered.split(' ').count() > 1,
|
||||
"{rendered}"
|
||||
);
|
||||
}
|
||||
let short = DmaBufDecline::TooSmall {
|
||||
required: 8192,
|
||||
available: 4096,
|
||||
};
|
||||
assert!(short.to_string().contains("required=8192"));
|
||||
assert!(short.to_string().contains("available=4096"));
|
||||
let disjoint = DmaBufDecline::NoCommonMemoryType {
|
||||
fd_bits: 0x9,
|
||||
buffer_bits: 0x6,
|
||||
};
|
||||
assert!(disjoint.to_string().contains("fd_bits=0x9"));
|
||||
assert!(disjoint.to_string().contains("buffer_bits=0x6"));
|
||||
}
|
||||
|
||||
/// The unsupported decline reports *which* rung refused, not just that one
|
||||
/// did — an Apple host and a Linux host with an old ICD are different bug
|
||||
/// reports and must not render identically.
|
||||
#[test]
|
||||
fn the_unsupported_decline_names_the_rung() {
|
||||
use crate::backend::vulkan::caps::DmaBufImport;
|
||||
let apple = DmaBufDecline::Unsupported {
|
||||
rung: DmaBufImport::NoDmaBufExtension,
|
||||
};
|
||||
let declined = DmaBufDecline::Unsupported {
|
||||
rung: DmaBufImport::NotImportable,
|
||||
};
|
||||
assert!(apple.to_string().contains("rung=no_dma_buf_extension"));
|
||||
assert!(declined.to_string().contains("rung=not_importable"));
|
||||
assert_ne!(apple.to_string(), declined.to_string());
|
||||
}
|
||||
|
||||
fn entry(window: u64, size: u64, used: u64) -> ImportEntry {
|
||||
entry_at_epoch(window, size, used, 0)
|
||||
}
|
||||
|
||||
fn entry_at_epoch(window: u64, size: u64, used: u64, epoch: u64) -> ImportEntry {
|
||||
let (read, _write) = std::io::pipe().expect("a pipe for a placeholder fd");
|
||||
ImportEntry {
|
||||
window,
|
||||
_window_fd: Arc::new(GuestDmaBuf {
|
||||
id: window,
|
||||
fd: std::os::fd::OwnedFd::from(read),
|
||||
}),
|
||||
// Never destroyed: no test here reaches `vkFreeMemory`, and the
|
||||
// cache's own bookkeeping is what is under test.
|
||||
import: ImportedDmaBuf {
|
||||
buffer: vk::Buffer::null(),
|
||||
memory: vk::DeviceMemory::null(),
|
||||
size,
|
||||
},
|
||||
used,
|
||||
epoch,
|
||||
}
|
||||
}
|
||||
|
||||
/// The least recently handed-out import is the one that goes.
|
||||
///
|
||||
/// Getting this backwards does not fail anything: the cache still answers
|
||||
/// correctly, and the only symptom is `vkAllocateMemory` on the hot window
|
||||
/// every frame while a cold one is kept — a performance defect that looks
|
||||
/// exactly like the rail working.
|
||||
#[test]
|
||||
fn eviction_takes_the_least_recently_used_import() {
|
||||
let entries = vec![entry(1, 4096, 30), entry(2, 4096, 7), entry(3, 4096, 19)];
|
||||
assert_eq!(lru_victim(&entries, 1), Some(1));
|
||||
assert_eq!(lru_victim(&[], 1), None);
|
||||
}
|
||||
|
||||
/// An import the command buffer now recording was already handed is not a
|
||||
/// candidate however cold it looks, because nothing else can see that CB.
|
||||
///
|
||||
/// A submitted CB is named by its ring slot, so the graveyard holds its
|
||||
/// imports until the slot retires. One still being *recorded* has no slot
|
||||
/// bit set and no fence, so an eviction would `vkFreeMemory` guest pages a
|
||||
/// recorded `vkCmdCopyBufferToImage` is about to read — the frame comes back
|
||||
/// as whatever the driver put there, or the submit faults.
|
||||
#[test]
|
||||
fn an_import_the_open_recording_holds_is_never_the_victim() {
|
||||
let entries = vec![
|
||||
entry_at_epoch(1, 4096, 1, 7),
|
||||
entry_at_epoch(2, 4096, 2, 6),
|
||||
entry_at_epoch(3, 4096, 3, 7),
|
||||
];
|
||||
assert_eq!(
|
||||
lru_victim(&entries, 7),
|
||||
Some(1),
|
||||
"the coldest entry is pinned by the live epoch; the next one goes"
|
||||
);
|
||||
assert_eq!(
|
||||
lru_victim(&entries, 8),
|
||||
Some(0),
|
||||
"a later recording pins none of them, so the plain LRU answer returns"
|
||||
);
|
||||
}
|
||||
|
||||
/// Displacement hands the imports back rather than freeing them, and stops
|
||||
/// as soon as everything left belongs to the open recording.
|
||||
///
|
||||
/// Both halves are load-bearing. Freeing here would be a `vkFreeMemory`
|
||||
/// under a possibly in-flight command buffer, which is why the caller routes
|
||||
/// them through the ring's graveyard instead. And a loop that could not stop
|
||||
/// would either spin or evict the recording's own pages.
|
||||
#[test]
|
||||
fn displacement_yields_the_imports_and_stops_at_the_pinned_ones() {
|
||||
let mut cache = ImportCache {
|
||||
entries: vec![
|
||||
entry_at_epoch(1, MAX_IMPORTED_BYTES / 2, 1, 4),
|
||||
entry_at_epoch(2, MAX_IMPORTED_BYTES / 2, 2, 3),
|
||||
],
|
||||
bytes: MAX_IMPORTED_BYTES,
|
||||
clock: 2,
|
||||
epoch: 4,
|
||||
};
|
||||
|
||||
let mut displaced = Vec::new();
|
||||
cache.evict_to_bound(MAX_IMPORTED_BYTES / 2, &mut displaced);
|
||||
assert_eq!(
|
||||
displaced.len(),
|
||||
1,
|
||||
"the unpinned entry is the one displaced"
|
||||
);
|
||||
assert_eq!(cache.entries.len(), 1);
|
||||
assert_eq!(cache.entries[0].window, 1);
|
||||
assert_eq!(cache.bytes, MAX_IMPORTED_BYTES / 2);
|
||||
|
||||
// Nothing unpinned is left, so a second ask cannot be satisfied and must
|
||||
// leave the survivor alone rather than loop or free it.
|
||||
let mut again = Vec::new();
|
||||
cache.evict_to_bound(MAX_IMPORTED_BYTES, &mut again);
|
||||
assert!(again.is_empty());
|
||||
assert_eq!(cache.entries.len(), 1);
|
||||
}
|
||||
|
||||
/// The two caches bound the same physical guest pages, so they carry the
|
||||
/// same number.
|
||||
///
|
||||
/// A smaller bound here would evict imports of windows the runtime is still
|
||||
/// pinning, which pays `vkAllocateMemory` per flush to reach pages that stay
|
||||
/// unswappable either way — the cost without the saving.
|
||||
#[test]
|
||||
fn the_import_bound_matches_the_pin_bound() {
|
||||
assert_eq!(
|
||||
MAX_IMPORTED_BYTES,
|
||||
crate::runtime::guest_dmabuf::MAX_PINNED_BYTES
|
||||
);
|
||||
}
|
||||
|
||||
/// The key is the window's monotonic id, never the fd number.
|
||||
///
|
||||
/// An fd number is recycled the instant one closes, so a cache keyed on it
|
||||
/// would hand a fresh window the previous occupant's `VkDeviceMemory` — a
|
||||
/// flush landing one surface's pixels in another's pages, which no counter
|
||||
/// in this device would report.
|
||||
#[test]
|
||||
fn the_cache_key_is_the_window_id_and_not_the_fd() {
|
||||
let first = entry(1, 4096, 1);
|
||||
let second = entry(2, 4096, 2);
|
||||
assert_ne!(first.window, second.window);
|
||||
// Two live pipes can share neither number, but a closed one's is free
|
||||
// for the next open — which is exactly why the id, and not this, is the
|
||||
// key.
|
||||
assert_eq!(first.window, first._window_fd.id);
|
||||
assert_eq!(second.window, second._window_fd.id);
|
||||
}
|
||||
}
|
||||
@@ -154,14 +154,24 @@ unsafe fn import_guest_buffer_window(
|
||||
pools: &mut ResourcePools,
|
||||
src: &super::types::GuestRunSource,
|
||||
) -> Option<BoundBuffer> {
|
||||
if !ctx.caps.dma_buf_import.is_available() {
|
||||
if !ctx.caps.host_pointer.is_available() {
|
||||
return None;
|
||||
}
|
||||
let window = src.pages.as_ref()?;
|
||||
let offset = u64::from(window.head_offset);
|
||||
let guest_ref = src.pages.as_ref()?;
|
||||
let bound = match unsafe { pools.bind_guest_ram(ctx, guest_ref) } {
|
||||
Ok(bound) => bound,
|
||||
Err(inner) => {
|
||||
crate::observe::Emit::decline("vk_buffer_import", &inner).fail_once(0);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
// The imported buffer spans the whole RAMBlock, so the span's first byte is
|
||||
// the bound range's start plus whatever widening it to the device's import
|
||||
// granularity added at the front.
|
||||
let offset = bound.offset + bound.head;
|
||||
// Unlike the sampled rail's copy offset, this one is a *bind*: the device
|
||||
// publishes the alignment it will accept and there is no arm that can
|
||||
// renegotiate it. A guest span that lands elsewhere in its page is gathered.
|
||||
// renegotiate it. A guest span that lands elsewhere is gathered.
|
||||
if !offset.is_multiple_of(ctx.guest_bind_offset_align) {
|
||||
crate::observe::Emit::decline(
|
||||
"vk_buffer_import",
|
||||
@@ -173,28 +183,10 @@ unsafe fn import_guest_buffer_window(
|
||||
.fail_once(offset % ctx.guest_bind_offset_align);
|
||||
return None;
|
||||
}
|
||||
let mapped = (window.gpas.len() as u64).saturating_mul(u64::from(window.page_size));
|
||||
if offset.saturating_add(src.total_len) > mapped {
|
||||
crate::observe::Emit::decline(
|
||||
"vk_buffer_import",
|
||||
&BufferImportDecline::WindowTooSmall {
|
||||
need: offset + src.total_len,
|
||||
have: mapped,
|
||||
},
|
||||
)
|
||||
.fail_once(0);
|
||||
return None;
|
||||
}
|
||||
match unsafe { pools.import_guest_window(ctx, &window.dmabuf, mapped) } {
|
||||
Ok(import) => Some(BoundBuffer {
|
||||
buffer: import.buffer,
|
||||
offset,
|
||||
}),
|
||||
Err(inner) => {
|
||||
crate::observe::Emit::decline("vk_buffer_import", &inner).fail_once(0);
|
||||
None
|
||||
}
|
||||
}
|
||||
Some(BoundBuffer {
|
||||
buffer: bound.buffer,
|
||||
offset,
|
||||
})
|
||||
}
|
||||
|
||||
/// A check that sent a guest buffer span back to the CPU gather.
|
||||
@@ -203,15 +195,12 @@ enum BufferImportDecline {
|
||||
/// The span does not start at an offset this device will bind a vertex or
|
||||
/// storage buffer at. See [`super::context::DeviceContext::guest_bind_offset_align`].
|
||||
BindOffsetAlignment { offset: u64, align: u64 },
|
||||
/// The page list does not reach the end of the span it was resolved for.
|
||||
WindowTooSmall { need: u64, have: u64 },
|
||||
}
|
||||
|
||||
impl crate::observe::Decline for BufferImportDecline {
|
||||
fn slug(&self) -> &'static str {
|
||||
match self {
|
||||
Self::BindOffsetAlignment { .. } => "buffer_import_bind_offset_alignment",
|
||||
Self::WindowTooSmall { .. } => "buffer_import_window_too_small",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,9 +209,6 @@ impl crate::observe::Decline for BufferImportDecline {
|
||||
Self::BindOffsetAlignment { offset, align } => {
|
||||
vec![("offset", offset.to_string()), ("align", align.to_string())]
|
||||
}
|
||||
Self::WindowTooSmall { need, have } => {
|
||||
vec![("need", need.to_string()), ("have", have.to_string())]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -360,11 +346,20 @@ unsafe fn import_sampled_guest_window(
|
||||
pools: &mut ResourcePools,
|
||||
src: &super::types::GuestRunSource,
|
||||
) -> Option<GuestTexels> {
|
||||
if !ctx.caps.dma_buf_import.is_available() {
|
||||
if !ctx.caps.host_pointer.is_available() {
|
||||
return None;
|
||||
}
|
||||
let window = src.pages.as_ref()?;
|
||||
let offset = u64::from(window.head_offset);
|
||||
let guest_ref = src.pages.as_ref()?;
|
||||
let bound = match unsafe { pools.bind_guest_ram(ctx, guest_ref) } {
|
||||
Ok(bound) => bound,
|
||||
Err(inner) => {
|
||||
crate::observe::Emit::decline("vk_sampled_import", &inner).fail_once(0);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
// As on the buffer rail: the buffer spans the RAMBlock, so the first texel
|
||||
// sits at the bound range's start plus the granularity widening.
|
||||
let offset = bound.offset + bound.head;
|
||||
if !offset.is_multiple_of(GUEST_IMPORT_COPY_OFFSET_ALIGN) {
|
||||
crate::observe::Emit::decline(
|
||||
"vk_sampled_import",
|
||||
@@ -373,31 +368,10 @@ unsafe fn import_sampled_guest_window(
|
||||
.fail_once(offset % GUEST_IMPORT_COPY_OFFSET_ALIGN);
|
||||
return None;
|
||||
}
|
||||
let mapped = (window.gpas.len() as u64).saturating_mul(u64::from(window.page_size));
|
||||
// The window is whole pages and the span starts inside the first one, so a
|
||||
// span reaching past the last page is a page list that never covered it.
|
||||
// Refusing beats binding a buffer the copy reads off the end of.
|
||||
if offset.saturating_add(src.total_len) > mapped {
|
||||
crate::observe::Emit::decline(
|
||||
"vk_sampled_import",
|
||||
&SampledImportDecline::WindowTooSmall {
|
||||
need: offset + src.total_len,
|
||||
have: mapped,
|
||||
},
|
||||
)
|
||||
.fail_once(0);
|
||||
return None;
|
||||
}
|
||||
match unsafe { pools.import_guest_window(ctx, &window.dmabuf, mapped) } {
|
||||
Ok(import) => Some(GuestTexels::Imported {
|
||||
buffer: import.buffer,
|
||||
offset,
|
||||
}),
|
||||
Err(inner) => {
|
||||
crate::observe::Emit::decline("vk_sampled_import", &inner).fail_once(0);
|
||||
None
|
||||
}
|
||||
}
|
||||
Some(GuestTexels::Imported {
|
||||
buffer: bound.buffer,
|
||||
offset,
|
||||
})
|
||||
}
|
||||
|
||||
/// A check that sent a guest-sourced sampled bind back to the CPU gather before
|
||||
@@ -411,25 +385,18 @@ enum SampledImportDecline {
|
||||
/// The first texel does not sit at an offset `vkCmdCopyBufferToImage` can
|
||||
/// name. See [`GUEST_IMPORT_COPY_OFFSET_ALIGN`].
|
||||
CopyOffsetAlignment { offset: u64 },
|
||||
/// The page list does not reach the end of the texel span it was resolved
|
||||
/// for.
|
||||
WindowTooSmall { need: u64, have: u64 },
|
||||
}
|
||||
|
||||
impl crate::observe::Decline for SampledImportDecline {
|
||||
fn slug(&self) -> &'static str {
|
||||
match self {
|
||||
Self::CopyOffsetAlignment { .. } => "sampled_import_copy_offset_alignment",
|
||||
Self::WindowTooSmall { .. } => "sampled_import_window_too_small",
|
||||
}
|
||||
}
|
||||
|
||||
fn fields(&self) -> Vec<(&'static str, String)> {
|
||||
match self {
|
||||
Self::CopyOffsetAlignment { offset } => vec![("offset", offset.to_string())],
|
||||
Self::WindowTooSmall { need, have } => {
|
||||
vec![("need", need.to_string()), ("have", have.to_string())]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1172,7 +1139,6 @@ pub(crate) unsafe fn execute_draw_inner(
|
||||
// deliberately does not bump: it records into the open batch's CB, which
|
||||
// still names every import the draws before it were handed and has not
|
||||
// been submitted, so nothing may free one out from under it.
|
||||
pools.dmabuf_imports_mut().begin_recording();
|
||||
pools.begin_entry(ctx, counters)?
|
||||
};
|
||||
phase.enter(super::draw_phase::Phase::Pipeline);
|
||||
@@ -3215,20 +3181,20 @@ mod tests {
|
||||
/// rail runs at all on a given host: it is a device limit against a guest
|
||||
/// allocator's choices, and neither side is under this device's control. A
|
||||
/// boot where the rail moves nothing has to be able to say whether that is
|
||||
/// because the host cannot export, or because every span this guest hands
|
||||
/// because the host cannot import, or because every span this guest hands
|
||||
/// over lands mid-alignment.
|
||||
///
|
||||
/// The short-window refusals that used to sit beside this one are gone,
|
||||
/// unrepresentable rather than untested: the range comes from a
|
||||
/// `GuestRef`, whose bound is checked where it is built and cannot be
|
||||
/// skipped, so there is no longer a way for a bind to name bytes past the
|
||||
/// end of what was resolved.
|
||||
#[test]
|
||||
fn every_buffer_import_decline_names_its_own_check() {
|
||||
let declines = [
|
||||
BufferImportDecline::BindOffsetAlignment {
|
||||
offset: 40,
|
||||
align: 64,
|
||||
},
|
||||
BufferImportDecline::WindowTooSmall {
|
||||
need: 8192,
|
||||
have: 4096,
|
||||
},
|
||||
];
|
||||
let declines = [BufferImportDecline::BindOffsetAlignment {
|
||||
offset: 40,
|
||||
align: 64,
|
||||
}];
|
||||
let slugs: Vec<_> = declines.iter().map(|d| d.slug()).collect();
|
||||
let unique: std::collections::HashSet<_> = slugs.iter().collect();
|
||||
assert_eq!(slugs.len(), unique.len(), "slugs collide: {slugs:?}");
|
||||
@@ -3237,11 +3203,15 @@ mod tests {
|
||||
assert!(decline.slug().starts_with("buffer_import_"));
|
||||
}
|
||||
// The two rails refuse for different reasons and must not share a slug
|
||||
// with each other either — a sampled window and a buffer span can fail
|
||||
// the same way and still need different fixes.
|
||||
// with each other either — a sampled bind and a buffer bind can fail the
|
||||
// same way and still need different fixes.
|
||||
assert_ne!(
|
||||
BufferImportDecline::WindowTooSmall { need: 1, have: 0 }.slug(),
|
||||
SampledImportDecline::WindowTooSmall { need: 1, have: 0 }.slug()
|
||||
BufferImportDecline::BindOffsetAlignment {
|
||||
offset: 1,
|
||||
align: 2
|
||||
}
|
||||
.slug(),
|
||||
SampledImportDecline::CopyOffsetAlignment { offset: 1 }.slug()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3250,18 +3220,12 @@ mod tests {
|
||||
///
|
||||
/// They route to the same place — the CPU gather — so nothing downstream
|
||||
/// tells them apart, and a shared slug would leave "this host never imports
|
||||
/// a sampled window" with no way to say whether the exporter is missing, the
|
||||
/// page list is short, or every window this guest hands over lands on an odd
|
||||
/// offset. Those are three different fixes.
|
||||
/// a sampled window" with no way to say whether the device cannot import at
|
||||
/// all or every window this guest hands over lands on an odd offset. Those
|
||||
/// are different fixes.
|
||||
#[test]
|
||||
fn every_sampled_import_decline_names_its_own_check() {
|
||||
let declines = [
|
||||
SampledImportDecline::CopyOffsetAlignment { offset: 12 },
|
||||
SampledImportDecline::WindowTooSmall {
|
||||
need: 8192,
|
||||
have: 4096,
|
||||
},
|
||||
];
|
||||
let declines = [SampledImportDecline::CopyOffsetAlignment { offset: 12 }];
|
||||
let slugs: Vec<_> = declines.iter().map(|d| d.slug()).collect();
|
||||
let unique: std::collections::HashSet<_> = slugs.iter().collect();
|
||||
assert_eq!(slugs.len(), unique.len(), "slugs collide: {slugs:?}");
|
||||
|
||||
@@ -0,0 +1,471 @@
|
||||
//! Import a RAMBlock's host mapping as `VkDeviceMemory` and bind a `VkBuffer`
|
||||
//! over all of it.
|
||||
//!
|
||||
//! This is the one place guest memory becomes something the engine can bind.
|
||||
//! Which *bytes* a draw reaches is decided before it gets here and is carried by
|
||||
//! a [`GuestRef`], whose bound cannot be skipped — see
|
||||
//! [`crate::runtime::guest_ram`] for why that is a type and not a review rule,
|
||||
//! and [`super::super::caps::host_pointer`] for the capability that gates the
|
||||
//! whole rail.
|
||||
//!
|
||||
//! # One import per RAMBlock, and no cache
|
||||
//!
|
||||
//! The dma-buf rail this replaces needed a cache with an LRU and a pinned-byte
|
||||
//! bound, because creating an fd walked every page and took a kernel reference
|
||||
//! on each. Here the expensive step happens once per RAMBlock for the device's
|
||||
//! life and the cheap step — naming a range inside it — is a bounds check.
|
||||
//!
|
||||
//! So [`HostRamImports`] is a map with no eviction policy and no capacity. It
|
||||
//! holds at most one entry per span the shim reported, which on an ordinary
|
||||
//! machine is one or two. That is the whole prize of the model, and a future
|
||||
//! change that adds an eviction rule here has almost certainly misunderstood it:
|
||||
//! evicting an import does not free guest RAM, it only forces the next draw to
|
||||
//! pay `get_user_pages` again for a mapping that never moved.
|
||||
//!
|
||||
//! **Do not import the same RAMBlock twice.** `VK_EXT_external_memory_host`
|
||||
//! does not guarantee that importing one host allocation twice into one device
|
||||
//! works, which is why the map is keyed on
|
||||
//! [`crate::runtime::guest_ram::ImportId`] and the key is never reused.
|
||||
//!
|
||||
//! # What the import does not promise
|
||||
//!
|
||||
//! Freeing the memory ends the GPU's access, but nothing in the extension's
|
||||
//! specification says the pages were pinned while it lived. amdgpu and the
|
||||
//! NVIDIA driver call `get_user_pages` at import time in practice; that is an
|
||||
//! observation about two drivers rather than a contract. The honest statement is
|
||||
//! in [`crate::runtime::guest_ram`]'s module doc and is not repeated as a
|
||||
//! guarantee here.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use ash::vk;
|
||||
|
||||
use crate::observe::Decline;
|
||||
use crate::runtime::guest_ram::{GuestRamError, GuestRamImport, GuestRef};
|
||||
|
||||
/// One RAMBlock living on the GPU as a bindable buffer, with no copy between it
|
||||
/// and the guest's own view of those bytes.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct ImportedHostRam {
|
||||
pub buffer: vk::Buffer,
|
||||
pub memory: vk::DeviceMemory,
|
||||
/// Bytes the import covers. The buffer spans all of it, so every
|
||||
/// [`crate::runtime::guest_ram::BoundRange`] inside the import is a valid
|
||||
/// offset into this one buffer.
|
||||
pub size: vk::DeviceSize,
|
||||
}
|
||||
|
||||
impl ImportedHostRam {
|
||||
/// Release both halves. Freeing the memory is what ends the GPU's access to
|
||||
/// guest RAM, so it must run even on a teardown path that is otherwise
|
||||
/// giving up.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// No submission may still reference `buffer`, and `device` must be the one
|
||||
/// the import was made against.
|
||||
pub(crate) unsafe fn destroy(self, device: &ash::Device) {
|
||||
unsafe {
|
||||
device.destroy_buffer(self.buffer, None);
|
||||
device.free_memory(self.memory, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A check that stopped guest RAM from becoming a bindable buffer.
|
||||
///
|
||||
/// Every variant is a distinct check with its own slug. An import that fails at
|
||||
/// `vkAllocateMemory` and one the device declined a memory type for are two
|
||||
/// different findings — the first is usually the driver refusing the pointer's
|
||||
/// backing, the second is a memory-type intersection that came out empty — and a
|
||||
/// shared reason would leave a reader unable to tell them apart.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum HostRamDecline {
|
||||
/// This device cannot import a host pointer at all. Carries the rung so the
|
||||
/// log says which check refused; expected on every host without the
|
||||
/// extension and on any host where an operator turned the rail off.
|
||||
Unsupported {
|
||||
rung: crate::backend::vulkan::caps::HostPointerImport,
|
||||
},
|
||||
/// `vkGetMemoryHostPointerPropertiesEXT` declined the pointer, or no memory
|
||||
/// type it named also satisfies what this device wants for guest memory.
|
||||
NoImportableMemoryType { host_base: usize },
|
||||
/// `vkCreateBuffer` over the whole span failed.
|
||||
CreateBuffer { result: vk::Result },
|
||||
/// The buffer the driver made needs more bytes than the span has. The import
|
||||
/// is sized to the RAMBlock exactly and may not be rounded up: the bytes past
|
||||
/// the end are this process's own memory.
|
||||
TooSmall { required: u64, available: u64 },
|
||||
/// `vkAllocateMemory` with the chained import failed. On most drivers this
|
||||
/// is the pointer being refused — not fd-backed, not aligned, or not a
|
||||
/// mapping the driver can take a reference on.
|
||||
AllocateMemory { result: vk::Result },
|
||||
/// `vkBindBufferMemory` failed after a successful import.
|
||||
BindBuffer { result: vk::Result },
|
||||
/// The reference did not survive its own bound. Carries the check that
|
||||
/// refused, from [`crate::runtime::guest_ram`].
|
||||
Bound { inner: GuestRamError },
|
||||
}
|
||||
|
||||
impl Decline for HostRamDecline {
|
||||
fn slug(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Unsupported { .. } => "host_ram_import_unsupported",
|
||||
Self::NoImportableMemoryType { .. } => "host_ram_import_no_importable_memory_type",
|
||||
Self::CreateBuffer { .. } => "host_ram_import_create_buffer",
|
||||
Self::TooSmall { .. } => "host_ram_import_too_small",
|
||||
Self::AllocateMemory { .. } => "host_ram_import_allocate_memory",
|
||||
Self::BindBuffer { .. } => "host_ram_import_bind_buffer",
|
||||
// The inner check is the diagnosis. Forwarding rather than adding a
|
||||
// slug keeps one name per check across the two modules.
|
||||
Self::Bound { inner } => inner.slug(),
|
||||
}
|
||||
}
|
||||
|
||||
fn fields(&self) -> Vec<(&'static str, String)> {
|
||||
match self {
|
||||
Self::Unsupported { rung } => vec![("rung", rung.slug().to_string())],
|
||||
Self::NoImportableMemoryType { host_base } => {
|
||||
vec![("host_base", format!("{host_base:#x}"))]
|
||||
}
|
||||
Self::CreateBuffer { result }
|
||||
| Self::AllocateMemory { result }
|
||||
| Self::BindBuffer { result } => vec![("result", format!("{result:?}"))],
|
||||
Self::TooSmall {
|
||||
required,
|
||||
available,
|
||||
} => vec![
|
||||
("required", required.to_string()),
|
||||
("available", available.to_string()),
|
||||
],
|
||||
Self::Bound { inner } => inner.fields(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
crate::observe::decline_display!(HostRamDecline);
|
||||
|
||||
/// A guest-memory range the engine can bind right now.
|
||||
///
|
||||
/// The buffer spans the whole RAMBlock, so `offset` and `len` are the only
|
||||
/// things that differ between two references into the same block. Both came out
|
||||
/// of [`GuestRamImport::resolve`], which is the only producer of either.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct BoundGuestRam {
|
||||
pub buffer: vk::Buffer,
|
||||
pub offset: vk::DeviceSize,
|
||||
pub len: vk::DeviceSize,
|
||||
/// Bytes from `offset` to the first byte the caller asked for, added by
|
||||
/// widening the range to the device's import granularity. A caller that
|
||||
/// binds `offset` and reads from byte zero of it reads this many bytes early.
|
||||
pub head: vk::DeviceSize,
|
||||
}
|
||||
|
||||
/// Every RAMBlock this device has imported, keyed by import identity.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct HostRamImports {
|
||||
live: HashMap<u64, ImportedHostRam>,
|
||||
}
|
||||
|
||||
impl HostRamImports {
|
||||
/// Resolve `guest_ref` to a bindable range, importing its RAMBlock if this
|
||||
/// is the first reference into it.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `ctx` must be the live device context, and the import's host base must
|
||||
/// still be a mapping in this process — which it is for the VM's lifetime,
|
||||
/// because it is QEMU's own RAMBlock mapping.
|
||||
pub(crate) unsafe fn bind(
|
||||
&mut self,
|
||||
ctx: &super::context::DeviceContext,
|
||||
guest_ref: &GuestRef,
|
||||
) -> Result<BoundGuestRam, HostRamDecline> {
|
||||
// The bound first, so a reference that cannot name its own bytes never
|
||||
// reaches an import call.
|
||||
let range = guest_ref
|
||||
.bound()
|
||||
.map_err(|inner| HostRamDecline::Bound { inner })?;
|
||||
let import = guest_ref.import();
|
||||
let key = import.id().get();
|
||||
let live = match self.live.get(&key) {
|
||||
Some(live) => *live,
|
||||
None => {
|
||||
let made = unsafe { import_ramblock(ctx, import) }?;
|
||||
self.live.insert(key, made);
|
||||
made
|
||||
}
|
||||
};
|
||||
Ok(BoundGuestRam {
|
||||
buffer: live.buffer,
|
||||
offset: range.offset,
|
||||
len: range.len,
|
||||
head: guest_ref.head(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Release every import. Called on device teardown, before the device goes.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// No submission may still reference any imported buffer.
|
||||
pub(crate) unsafe fn destroy_all(&mut self, device: &ash::Device) {
|
||||
for (_, live) in self.live.drain() {
|
||||
unsafe { live.destroy(device) };
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes of guest RAM this device currently has imported, for the census.
|
||||
pub(crate) fn imported_bytes(&self) -> u64 {
|
||||
self.live.values().map(|l| l.size).sum()
|
||||
}
|
||||
|
||||
/// How many RAMBlocks are imported. One or two on an ordinary machine, and
|
||||
/// the number that must not grow with the workload — a rising count here is
|
||||
/// the per-resource import the model exists to avoid.
|
||||
pub(crate) fn len(&self) -> usize {
|
||||
self.live.len()
|
||||
}
|
||||
}
|
||||
|
||||
/// Import one RAMBlock's whole host mapping.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// As [`HostRamImports::bind`].
|
||||
unsafe fn import_ramblock(
|
||||
ctx: &super::context::DeviceContext,
|
||||
import: &GuestRamImport,
|
||||
) -> Result<ImportedHostRam, HostRamDecline> {
|
||||
use crate::backend::vulkan::caps::host_pointer::GUEST_IMPORT_USAGE;
|
||||
|
||||
let Some(loader) = ctx.external_memory_host.as_ref() else {
|
||||
return Err(HostRamDecline::Unsupported {
|
||||
rung: ctx.caps.host_pointer.rung,
|
||||
});
|
||||
};
|
||||
const HANDLE_TYPE: vk::ExternalMemoryHandleTypeFlags =
|
||||
vk::ExternalMemoryHandleTypeFlags::HOST_ALLOCATION_EXT;
|
||||
|
||||
let host_base = import.host_base();
|
||||
let size = import.len();
|
||||
|
||||
// Which memory types will accept *this* pointer. Asked before anything is
|
||||
// created, because the answer is a property of the mapping rather than of
|
||||
// the device — and it goes through the one memory-type selector this
|
||||
// backend has, so the ranking is not restated here.
|
||||
//
|
||||
// `Upload` is the class: guest RAM is host memory the GPU reaches, which is
|
||||
// exactly what that preference describes. On a discrete host the selector
|
||||
// will land on a host-visible type, and the copy into VRAM is a separate
|
||||
// decision made by the caller, not by this import.
|
||||
let req = ctx
|
||||
.caps
|
||||
.memory_request(crate::backend::vulkan::caps::MemoryClass::Upload);
|
||||
let memory_type_index = unsafe {
|
||||
crate::backend::vulkan::caps::host_pointer::import_memory_type(
|
||||
loader,
|
||||
&ctx.memory_properties,
|
||||
host_base as *const std::ffi::c_void,
|
||||
&req,
|
||||
)
|
||||
}
|
||||
.ok_or(HostRamDecline::NoImportableMemoryType { host_base })?;
|
||||
|
||||
let mut external = vk::ExternalMemoryBufferCreateInfo::default().handle_types(HANDLE_TYPE);
|
||||
let create = vk::BufferCreateInfo::default()
|
||||
.size(size)
|
||||
.usage(GUEST_IMPORT_USAGE)
|
||||
.sharing_mode(vk::SharingMode::EXCLUSIVE)
|
||||
.push_next(&mut external);
|
||||
let buffer = unsafe { ctx.device.create_buffer(&create, None) }
|
||||
.map_err(|result| HostRamDecline::CreateBuffer { result })?;
|
||||
|
||||
// From here every failure must destroy the buffer before returning, so the
|
||||
// work is done in a closure and the cleanup happens once at the end.
|
||||
let bound = (|| {
|
||||
let reqs = unsafe { ctx.device.get_buffer_memory_requirements(buffer) };
|
||||
if reqs.size > size {
|
||||
// Not rounded up. The bytes past the end of a RAMBlock are this
|
||||
// process's own memory, and handing the GPU write access to them is
|
||||
// the one stray the bound exists to prevent.
|
||||
return Err(HostRamDecline::TooSmall {
|
||||
required: reqs.size,
|
||||
available: size,
|
||||
});
|
||||
}
|
||||
if reqs.memory_type_bits & (1u32 << memory_type_index) == 0 {
|
||||
return Err(HostRamDecline::NoImportableMemoryType { host_base });
|
||||
}
|
||||
|
||||
let mut host_import = vk::ImportMemoryHostPointerInfoEXT::default()
|
||||
.handle_type(HANDLE_TYPE)
|
||||
.host_pointer(host_base as *mut std::ffi::c_void);
|
||||
let allocate = vk::MemoryAllocateInfo::default()
|
||||
.allocation_size(size)
|
||||
.memory_type_index(memory_type_index)
|
||||
.push_next(&mut host_import);
|
||||
let memory = unsafe { ctx.device.allocate_memory(&allocate, None) }
|
||||
.map_err(|result| HostRamDecline::AllocateMemory { result })?;
|
||||
|
||||
match unsafe { ctx.device.bind_buffer_memory(buffer, memory, 0) } {
|
||||
Ok(()) => Ok(ImportedHostRam {
|
||||
buffer,
|
||||
memory,
|
||||
size,
|
||||
}),
|
||||
Err(result) => {
|
||||
// Freeing the memory is what ends the GPU's access to the
|
||||
// pointer, so it happens even on this failure path.
|
||||
unsafe { ctx.device.free_memory(memory, None) };
|
||||
Err(HostRamDecline::BindBuffer { result })
|
||||
}
|
||||
}
|
||||
})();
|
||||
|
||||
if bound.is_err() {
|
||||
unsafe { ctx.device.destroy_buffer(buffer, None) };
|
||||
}
|
||||
bound
|
||||
}
|
||||
|
||||
/// A check that stopped a resident's frame from being copied straight into the
|
||||
/// guest's own pages, so the flush took the CPU route instead.
|
||||
///
|
||||
/// Every one of these is a *routing* answer rather than a loss — the copying
|
||||
/// rail still lands the frame — but each is a whole flush's worth of memcpy that
|
||||
/// the device paid and did not have to, so they are named individually and
|
||||
/// counted.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum GuestWriteDecline {
|
||||
/// The device cannot import guest RAM at all. Carries the rung so the log
|
||||
/// says which check refused; expected on every host without the extension.
|
||||
Unsupported {
|
||||
rung: crate::backend::vulkan::caps::HostPointerImport,
|
||||
},
|
||||
/// The resident's physical channel order is not the guest's scanout order,
|
||||
/// so landing it would need an R/B exchange — which a buffer→image copy
|
||||
/// cannot perform. The copying rail's `into_bgra8` is where that lives.
|
||||
NotScanoutOrder,
|
||||
/// The resident's geometry is not the geometry the window promised the
|
||||
/// guest. Copying anyway would land one extent's pixels under another's row
|
||||
/// pitch.
|
||||
GeometryMoved {
|
||||
resident_width: u32,
|
||||
resident_height: u32,
|
||||
want_width: u32,
|
||||
want_height: u32,
|
||||
},
|
||||
/// The frame's last byte falls past the end of the range the runtime asked
|
||||
/// for.
|
||||
///
|
||||
/// Not the same check as the import bound, and that is why it is kept: the
|
||||
/// runtime sizes the request from the mapping's page plan and the engine
|
||||
/// computes the extent from the resident's own geometry and row pitch. Two
|
||||
/// independently-derived numbers, and a disagreement between them is a
|
||||
/// frame that would land under the wrong pitch.
|
||||
WindowTooSmall { need: u64, have: u64 },
|
||||
/// The import itself declined; the inner reason names the step.
|
||||
Import { inner: HostRamDecline },
|
||||
}
|
||||
|
||||
impl Decline for GuestWriteDecline {
|
||||
fn slug(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Unsupported { .. } => "gpu_writeback_unsupported",
|
||||
Self::NotScanoutOrder => "gpu_writeback_not_scanout_order",
|
||||
Self::GeometryMoved { .. } => "gpu_writeback_geometry_moved",
|
||||
Self::WindowTooSmall { .. } => "gpu_writeback_window_too_small",
|
||||
// The inner decline's own slug, so a driver that refuses the pointer
|
||||
// and a range that is too short stay as distinguishable here as they
|
||||
// are at the import site.
|
||||
Self::Import { inner } => inner.slug(),
|
||||
}
|
||||
}
|
||||
|
||||
fn fields(&self) -> Vec<(&'static str, String)> {
|
||||
match self {
|
||||
Self::Unsupported { rung } => vec![("rung", rung.slug().to_string())],
|
||||
Self::NotScanoutOrder => Vec::new(),
|
||||
Self::GeometryMoved {
|
||||
resident_width,
|
||||
resident_height,
|
||||
want_width,
|
||||
want_height,
|
||||
} => vec![
|
||||
("resident", format!("{resident_width}x{resident_height}")),
|
||||
("want", format!("{want_width}x{want_height}")),
|
||||
],
|
||||
Self::WindowTooSmall { need, have } => {
|
||||
vec![("need", need.to_string()), ("have", have.to_string())]
|
||||
}
|
||||
Self::Import { inner } => inner.fields(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
crate::observe::decline::decline_display!(GuestWriteDecline);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::backend::vulkan::caps::HostPointerImport;
|
||||
|
||||
/// One slug per check. Two sharing one would mean watching a slug fire and
|
||||
/// still not knowing whether the driver refused the pointer or the memory
|
||||
/// type intersection came out empty.
|
||||
#[test]
|
||||
fn every_decline_has_its_own_slug() {
|
||||
let all = [
|
||||
HostRamDecline::Unsupported {
|
||||
rung: HostPointerImport::Unqueried,
|
||||
},
|
||||
HostRamDecline::NoImportableMemoryType { host_base: 0 },
|
||||
HostRamDecline::CreateBuffer {
|
||||
result: vk::Result::ERROR_UNKNOWN,
|
||||
},
|
||||
HostRamDecline::TooSmall {
|
||||
required: 0,
|
||||
available: 0,
|
||||
},
|
||||
HostRamDecline::AllocateMemory {
|
||||
result: vk::Result::ERROR_UNKNOWN,
|
||||
},
|
||||
HostRamDecline::BindBuffer {
|
||||
result: vk::Result::ERROR_UNKNOWN,
|
||||
},
|
||||
];
|
||||
let mut slugs: Vec<_> = all.iter().map(|d| d.slug()).collect();
|
||||
let count = slugs.len();
|
||||
slugs.sort_unstable();
|
||||
slugs.dedup();
|
||||
assert_eq!(slugs.len(), count, "two checks share a slug");
|
||||
for slug in slugs {
|
||||
assert!(slug.starts_with("host_ram_import_"), "{slug}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A bound refusal keeps the inner check's name rather than being renamed
|
||||
/// at the boundary. The two modules are one rail and a reader greps one
|
||||
/// vocabulary.
|
||||
#[test]
|
||||
fn a_bound_refusal_forwards_the_check_that_refused() {
|
||||
let inner = GuestRamError::SliceEndPastImport {
|
||||
end: 0x1001,
|
||||
import_len: 0x1000,
|
||||
};
|
||||
let outer = HostRamDecline::Bound { inner };
|
||||
assert_eq!(outer.slug(), inner.slug());
|
||||
assert_eq!(outer.fields(), inner.fields());
|
||||
}
|
||||
|
||||
/// A fresh map holds nothing and reports nothing imported. The count is the
|
||||
/// reading that says whether the model held: it must stay at the number of
|
||||
/// RAMBlocks for a whole boot rather than tracking the workload.
|
||||
#[test]
|
||||
fn an_empty_map_reports_no_imports() {
|
||||
let imports = HostRamImports::default();
|
||||
assert_eq!(imports.len(), 0);
|
||||
assert_eq!(imports.imported_bytes(), 0);
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,6 @@ mod counters;
|
||||
mod desc_arena;
|
||||
mod device_lost;
|
||||
mod digest;
|
||||
mod dmabuf;
|
||||
mod draw_execution;
|
||||
mod draw_phase;
|
||||
mod draw_preparation;
|
||||
@@ -23,6 +22,7 @@ pub(crate) mod draw_validation;
|
||||
mod exec;
|
||||
mod exec_compute;
|
||||
mod facade_decline;
|
||||
mod host_ram;
|
||||
mod host_slab;
|
||||
pub mod init_decline;
|
||||
mod pools;
|
||||
@@ -47,7 +47,7 @@ pub use types::{
|
||||
BlendFactor, BlendOp, BlendStateResource, BufferContent, ColorWriteMask, ComputeBufferResource,
|
||||
ComputeOutput, ComputeRequest, ComputeResidentSampleBind, ComputeSampledImageResource,
|
||||
ComputeStorageImageResource, ComputeStorageResidency, CullMode, DepthClipMode, DepthState,
|
||||
DrawError, DrawOutput, DrawRequest, FillMode, GuestDmaBuf, GuestPageWindow, GuestRun,
|
||||
DrawError, DrawOutput, DrawRequest, FillMode, GuestRun,
|
||||
GuestRunSource, IndexType, IndexedDrawResource, PrimitiveTopology, SampledContentIdentity,
|
||||
SampledImageResource, SampledSource, SamplerAddressMode, SamplerBorderColor,
|
||||
SamplerCompareFunction, SamplerFilter, SamplerMipFilter, SamplerResource, ScissorResource,
|
||||
@@ -1692,17 +1692,9 @@ pub fn read_target_leased(identity: &TargetIdentity) -> Result<Option<LeasedFram
|
||||
/// and its row pitch; the engine takes it as given and checks only what it can
|
||||
/// see — that the resident matches the extent and that the window is long enough.
|
||||
pub struct GuestPageTarget {
|
||||
/// The dma-buf over the pages. Held by `Arc` because the import cache keeps
|
||||
/// it alive for as long as it names the window, and cloned rather than
|
||||
/// consumed because the runtime's own cache keeps the original.
|
||||
pub window: std::sync::Arc<GuestDmaBuf>,
|
||||
/// Bytes the fd covers, which is whole pages and therefore at or past
|
||||
/// `offset` plus the frame's extent.
|
||||
pub mapped_bytes: u64,
|
||||
/// Byte offset of the frame's first texel inside the dma-buf. Nonzero
|
||||
/// whenever the surface does not start on a page boundary, which is what a
|
||||
/// buffer→image copy expresses natively and a bound buffer cannot.
|
||||
pub offset: u64,
|
||||
/// The bounded reference to the guest bytes the frame lands in, covering
|
||||
/// the extent this copy names and nothing more.
|
||||
pub guest: crate::runtime::guest_ram::GuestRef,
|
||||
/// Guest row pitch in **texels** (`bufferRowLength`). Rows past the first
|
||||
/// start this far apart, which is how a padded guest pitch is honoured
|
||||
/// without the inter-row bytes ever being written.
|
||||
@@ -1721,7 +1713,7 @@ impl GuestPageTarget {
|
||||
fn extent_end(&self) -> u64 {
|
||||
let pitch = u64::from(self.row_length_texels.max(self.width)) * 4;
|
||||
let rows_before = u64::from(self.height.saturating_sub(1));
|
||||
self.offset + rows_before * pitch + u64::from(self.width) * 4
|
||||
rows_before * pitch + u64::from(self.width) * 4
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1757,7 +1749,7 @@ pub fn copy_target_to_guest_pages(
|
||||
identity: &TargetIdentity,
|
||||
dst: &GuestPageTarget,
|
||||
) -> Result<(), DrawError> {
|
||||
use dmabuf::GuestWriteDecline;
|
||||
use host_ram::GuestWriteDecline;
|
||||
let mut guard = lock_engine();
|
||||
let EngineState {
|
||||
ref mut owner,
|
||||
@@ -1766,9 +1758,9 @@ pub fn copy_target_to_guest_pages(
|
||||
..
|
||||
} = &mut *guard;
|
||||
let ctx = owner.ensure(counters)?;
|
||||
if !ctx.caps.dma_buf_import.is_available() {
|
||||
if !ctx.caps.host_pointer.is_available() {
|
||||
return Err(DrawError::GuestPageWrite(GuestWriteDecline::Unsupported {
|
||||
rung: ctx.caps.dma_buf_import,
|
||||
rung: ctx.caps.host_pointer.rung,
|
||||
}));
|
||||
}
|
||||
unsafe { pools.ensure_init(ctx, counters)? };
|
||||
@@ -1789,23 +1781,19 @@ pub fn copy_target_to_guest_pages(
|
||||
));
|
||||
}
|
||||
let need = dst.extent_end();
|
||||
if need > dst.mapped_bytes {
|
||||
if need > dst.guest.requested() {
|
||||
return Err(DrawError::GuestPageWrite(
|
||||
GuestWriteDecline::WindowTooSmall {
|
||||
need,
|
||||
have: dst.mapped_bytes,
|
||||
have: dst.guest.requested(),
|
||||
},
|
||||
));
|
||||
}
|
||||
unsafe {
|
||||
// The whole window, not `need`: one window is one buffer whatever part
|
||||
// of it this copy names, so the next flush of the same surface reuses
|
||||
// the import instead of making a second one over the same pages.
|
||||
pools.dmabuf_imports_mut().begin_recording();
|
||||
let import = pools
|
||||
.import_guest_window(ctx, &dst.window, dst.mapped_bytes)
|
||||
let bound = pools
|
||||
.bind_guest_ram(ctx, &dst.guest)
|
||||
.map_err(|inner| DrawError::GuestPageWrite(GuestWriteDecline::Import { inner }))?;
|
||||
copy_image_level0_to_buffer(ctx, pools, counters, &snap, import.buffer, dst)?;
|
||||
copy_image_level0_to_buffer(ctx, pools, counters, &snap, bound.buffer, dst, bound)?;
|
||||
pools.registry_set_layout(identity, ash::vk::ImageLayout::TRANSFER_SRC_OPTIMAL);
|
||||
counters.note_target_read(u64::from(dst.width) * u64::from(dst.height) * 4);
|
||||
}
|
||||
@@ -1825,6 +1813,7 @@ unsafe fn copy_image_level0_to_buffer(
|
||||
snap: &ResidentReadSnapshot,
|
||||
buffer: ash::vk::Buffer,
|
||||
dst: &GuestPageTarget,
|
||||
bound: host_ram::BoundGuestRam,
|
||||
) -> Result<(), DrawError> {
|
||||
let submit_started = std::time::Instant::now();
|
||||
// Appended to a recording batch where there is one, for the reason
|
||||
@@ -1897,7 +1886,7 @@ unsafe fn copy_image_level0_to_buffer(
|
||||
.cmd_write_timestamp(cb, ash::vk::PipelineStageFlags::TRANSFER, probe.pool, 1);
|
||||
}
|
||||
let region = [ash::vk::BufferImageCopy::default()
|
||||
.buffer_offset(dst.offset)
|
||||
.buffer_offset(bound.offset + bound.head)
|
||||
// In texels, and only meaningful when the guest's pitch is wider than
|
||||
// the frame. Zero means tight rows, which is what the guest's own row
|
||||
// pitch reduces to whenever it equals `width * 4`.
|
||||
@@ -1929,9 +1918,10 @@ unsafe fn copy_image_level0_to_buffer(
|
||||
// released to `HOST` with `HOST_READ`, which is what makes it visible to a
|
||||
// CPU access after the fence signals.
|
||||
//
|
||||
// Cache maintenance beyond that is the exporter's. `udmabuf` hands the
|
||||
// importer references to ordinary system pages, and a PCIe write to system
|
||||
// memory is snooped, so there is no invalidate for this side to issue.
|
||||
// Cache maintenance beyond that is the driver's. A host-pointer import
|
||||
// names ordinary system pages this process already has mapped, and a PCIe
|
||||
// write to system memory is snooped, so there is no invalidate for this
|
||||
// side to issue.
|
||||
let host_visible = [ash::vk::MemoryBarrier::default()
|
||||
.src_access_mask(ash::vk::AccessFlags::TRANSFER_WRITE)
|
||||
.dst_access_mask(ash::vk::AccessFlags::HOST_READ)];
|
||||
@@ -2007,24 +1997,22 @@ unsafe fn copy_image_level0_to_buffer(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Guest memory the device can currently reach through imported dma-bufs, and
|
||||
/// how many windows that is.
|
||||
/// Guest memory the device can currently reach through host-pointer imports,
|
||||
/// and how many RAMBlocks that is.
|
||||
///
|
||||
/// # Nothing calls this, so the number it computes is in no log
|
||||
///
|
||||
/// Kept rather than deleted, because it is the only thing in the tree that can
|
||||
/// answer "how much guest RAM can the device reach right now" on the *importer*
|
||||
/// side. `runtime::guest_dmabuf` emits its own totals on every miss
|
||||
/// (`guest_dmabuf_pinned_kb_sum`, `guest_dmabuf_windows_sum`), so the exporter
|
||||
/// side of the isolation rail is measurable and this side is not — and the two
|
||||
/// are not the same population, because an export the runtime has cached can
|
||||
/// still be declined by the backend before it becomes an import. Wiring this
|
||||
/// into the census is a new emission, which is a behaviour change owed a driven
|
||||
/// boot; recorded here so the asymmetry is not mistaken for coverage.
|
||||
/// Kept because it is the only thing in the tree that can answer "how much
|
||||
/// guest RAM can the device reach right now", and because the *count* is the
|
||||
/// reading that says whether the one-import-per-RAMBlock model held: it should
|
||||
/// be one or two for a whole boot, and a count that tracks the workload is the
|
||||
/// per-resource import the model exists to avoid. Wiring it into the census is
|
||||
/// a new emission, which is a behaviour change owed a driven boot; recorded
|
||||
/// here so the gap is not mistaken for coverage.
|
||||
pub fn guest_import_census() -> (u64, usize) {
|
||||
let mut guard = lock_engine();
|
||||
let cache = guard.pools.dmabuf_imports_mut();
|
||||
(cache.imported_bytes(), cache.len())
|
||||
let guard = lock_engine();
|
||||
let (count, bytes) = guard.pools.host_ram_import_census();
|
||||
(bytes, count)
|
||||
}
|
||||
|
||||
/// The `srcAccessMask` a resident color target's readback must drain.
|
||||
@@ -2438,15 +2426,24 @@ mod engine_lock_census_tests {
|
||||
mod guest_page_target_tests {
|
||||
use super::*;
|
||||
|
||||
fn target(width: u32, height: u32, row_length_texels: u32, offset: u64) -> GuestPageTarget {
|
||||
let (read, _write) = std::io::pipe().expect("a pipe for a placeholder fd");
|
||||
/// A target over a synthetic import large enough that the bound under test
|
||||
/// is the extent arithmetic and not the import's own length.
|
||||
fn target(width: u32, height: u32, row_length_texels: u32) -> GuestPageTarget {
|
||||
use crate::runtime::guest_ram::{GuestRamImport, GuestRamRegion, GuestRef};
|
||||
let import = std::sync::Arc::new(
|
||||
GuestRamImport::new(
|
||||
GuestRamRegion {
|
||||
gpa_base: 0,
|
||||
host_va: 0x7f00_0000_0000,
|
||||
len: 1 << 30,
|
||||
},
|
||||
4096,
|
||||
)
|
||||
.expect("a plausible RAMBlock"),
|
||||
);
|
||||
let slice = import.slice(0, 1 << 20).expect("inside");
|
||||
GuestPageTarget {
|
||||
window: std::sync::Arc::new(GuestDmaBuf {
|
||||
id: 1,
|
||||
fd: std::os::fd::OwnedFd::from(read),
|
||||
}),
|
||||
mapped_bytes: u64::MAX,
|
||||
offset,
|
||||
guest: GuestRef::new(import, slice).expect("its own import"),
|
||||
row_length_texels,
|
||||
width,
|
||||
height,
|
||||
@@ -2466,32 +2463,22 @@ mod guest_page_target_tests {
|
||||
fn the_write_bound_ends_at_the_last_texel_and_not_a_row_pitch_past_it() {
|
||||
// 8 rows of 4 texels at a 16-texel pitch: 7 full pitches plus one packed
|
||||
// row, not 8 full pitches.
|
||||
let padded = target(4, 8, 16, 0);
|
||||
let padded = target(4, 8, 16);
|
||||
assert_eq!(padded.extent_end(), 7 * 16 * 4 + 4 * 4);
|
||||
// A tight frame is the same expression with the pitch equal to the
|
||||
// width, which reduces to the whole frame.
|
||||
let tight = target(4, 8, 4, 0);
|
||||
let tight = target(4, 8, 4);
|
||||
assert_eq!(tight.extent_end(), 4 * 8 * 4);
|
||||
}
|
||||
|
||||
/// A frame that does not start on a page boundary is bounded from where it
|
||||
/// actually starts. Dropping the offset here would under-report the reach by
|
||||
/// exactly the amount the copy writes past the end of the export.
|
||||
#[test]
|
||||
fn the_write_bound_includes_the_offset_into_the_window() {
|
||||
let at_zero = target(64, 64, 64, 0);
|
||||
let shifted = target(64, 64, 64, 512);
|
||||
assert_eq!(shifted.extent_end(), at_zero.extent_end() + 512);
|
||||
}
|
||||
|
||||
/// A zero row length means tight rows, which is what `bufferRowLength`
|
||||
/// itself means — so the bound must read it as the frame's own width rather
|
||||
/// than as a zero pitch that collapses every row onto the first.
|
||||
#[test]
|
||||
fn a_zero_row_length_is_a_tight_pitch_and_not_a_zero_one() {
|
||||
assert_eq!(
|
||||
target(32, 4, 0, 0).extent_end(),
|
||||
target(32, 4, 32, 0).extent_end()
|
||||
target(32, 4, 0).extent_end(),
|
||||
target(32, 4, 32).extent_end()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ use super::device_lost::{DeviceLostDecline, DeviceLostOp};
|
||||
use super::host_slab::{HostSlabToken, HOST_SLAB_IDLE_KEEP_EMPTY};
|
||||
use super::types::{DrawError, ResidentReclaim, StorageImageFormat, TargetIdentity};
|
||||
use super::vk_call::{VkCall, VkOp};
|
||||
use super::{color_subresource_range, dmabuf, host_slab, reason, slab, types};
|
||||
use super::{color_subresource_range, host_ram, host_slab, reason, slab, types};
|
||||
use crate::backend::vulkan::caps::{MappedMemoryKind, MemoryClass};
|
||||
use crate::backend::vulkan::translate;
|
||||
use crate::model::ComputeStorageResidencyKey;
|
||||
@@ -378,7 +378,10 @@ pub(crate) struct ResourcePools {
|
||||
/// here rather than beside its one consumer so it is destroyed by the same
|
||||
/// teardown that destroys every other device object, and so the bound is
|
||||
/// enforced against the pool that owns it. See [`dmabuf::ImportCache`].
|
||||
dmabuf_imports: dmabuf::ImportCache,
|
||||
/// Every RAMBlock this device has imported as a host pointer. Not a cache:
|
||||
/// one entry per span the shim reported, held for the device's life, with
|
||||
/// no eviction — see `host_ram` for why adding one would be a mistake.
|
||||
host_ram_imports: host_ram::HostRamImports,
|
||||
/// Whether any command buffer recorded or submitted since the last quiesce
|
||||
/// **reads** guest RAM when it executes.
|
||||
///
|
||||
@@ -498,12 +501,6 @@ pub(crate) enum DeferredHandle {
|
||||
RenderPass(vk::RenderPass),
|
||||
ShaderModule(vk::ShaderModule),
|
||||
Sampler(vk::Sampler),
|
||||
/// A guest page-window import displaced from [`dmabuf::ImportCache`]
|
||||
/// by its pinned-bytes bound. Freeing the `VkDeviceMemory` is what revokes
|
||||
/// the GPU's reach into those guest pages, and an in-flight command buffer
|
||||
/// may still be copying out of it, so the revocation waits for the ring
|
||||
/// exactly like every image destroy does.
|
||||
DmaBufImport(dmabuf::ImportedDmaBuf),
|
||||
}
|
||||
|
||||
impl ResourcePools {
|
||||
@@ -551,7 +548,6 @@ impl ResourcePools {
|
||||
DeferredHandle::RenderPass(rp) => device.destroy_render_pass(rp, None),
|
||||
DeferredHandle::ShaderModule(s) => device.destroy_shader_module(s, None),
|
||||
DeferredHandle::Sampler(s) => device.destroy_sampler(s, None),
|
||||
DeferredHandle::DmaBufImport(import) => unsafe { import.destroy(device) },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,38 +44,35 @@ impl ResourcePools {
|
||||
(self.registry.len(), self.targets.len(), sampled, storage)
|
||||
}
|
||||
|
||||
/// The guest page-window import cache. `&mut` because every use of it can
|
||||
/// import or evict; there is no read-only question to ask of it.
|
||||
pub(crate) fn dmabuf_imports_mut(&mut self) -> &mut dmabuf::ImportCache {
|
||||
&mut self.dmabuf_imports
|
||||
}
|
||||
|
||||
/// The bindable buffer over `window`'s guest pages, importing it if this is
|
||||
/// the first ask, and retiring whatever the pinned-bytes bound displaced.
|
||||
/// The bindable range `guest_ref` names, importing its RAMBlock if this is
|
||||
/// the first reference into it.
|
||||
///
|
||||
/// This is the only way to reach [`dmabuf::ImportCache::get_or_import`]
|
||||
/// that is safe for a caller which submits without waiting: a displaced
|
||||
/// import goes to the graveyard, so its `vkFreeMemory` lands after every
|
||||
/// command buffer that could still be copying out of it has retired.
|
||||
/// Unlike [`Self::import_guest_window`] there is nothing to displace: an
|
||||
/// import is per RAMBlock and lives as long as the device, so no caller can
|
||||
/// find the buffer it just bound freed underneath a submission in flight.
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// `ctx` must own the device every live import was made against.
|
||||
pub(crate) unsafe fn import_guest_window(
|
||||
pub(crate) unsafe fn bind_guest_ram(
|
||||
&mut self,
|
||||
ctx: &DeviceContext,
|
||||
window: &std::sync::Arc<types::GuestDmaBuf>,
|
||||
size: u64,
|
||||
) -> Result<dmabuf::ImportedDmaBuf, dmabuf::DmaBufDecline> {
|
||||
let mut displaced = Vec::new();
|
||||
let result = unsafe {
|
||||
self.dmabuf_imports
|
||||
.get_or_import(ctx, window, size, &mut displaced)
|
||||
};
|
||||
for import in displaced {
|
||||
unsafe { self.dispose(&ctx.device, DeferredHandle::DmaBufImport(import)) };
|
||||
}
|
||||
result
|
||||
guest_ref: &crate::runtime::guest_ram::GuestRef,
|
||||
) -> Result<host_ram::BoundGuestRam, host_ram::HostRamDecline> {
|
||||
unsafe { self.host_ram_imports.bind(ctx, guest_ref) }
|
||||
}
|
||||
|
||||
/// How many RAMBlocks are imported, and how many bytes they cover.
|
||||
///
|
||||
/// The count is the reading that says whether the model held: one or two
|
||||
/// for a whole boot. A count that tracks the workload is a per-resource
|
||||
/// import, which the extension does not guarantee works and which pays the
|
||||
/// driver's page pinning for an answer that never changes.
|
||||
pub(crate) fn host_ram_import_census(&self) -> (usize, u64) {
|
||||
(
|
||||
self.host_ram_imports.len(),
|
||||
self.host_ram_imports.imported_bytes(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn new() -> Self {
|
||||
@@ -128,7 +125,7 @@ impl ResourcePools {
|
||||
open_batch: None,
|
||||
slab: slab::SlabPool::new(),
|
||||
host_slab: host_slab::HostSlabPool::new(),
|
||||
dmabuf_imports: dmabuf::ImportCache::default(),
|
||||
host_ram_imports: host_ram::HostRamImports::default(),
|
||||
guest_reads_in_flight: false,
|
||||
initialized: false,
|
||||
}
|
||||
|
||||
@@ -147,7 +147,9 @@ impl ResourcePools {
|
||||
// the guest pages they name — the revocation the dma-buf carve-out rests
|
||||
// on, and the one release that must happen even when the teardown is
|
||||
// otherwise giving up.
|
||||
self.dmabuf_imports.destroy_all(device);
|
||||
// Freeing these is what ends the GPU's access to guest RAM, so it runs
|
||||
// on every teardown path including the ones that are giving up.
|
||||
self.host_ram_imports.destroy_all(device);
|
||||
// Free every slab block now that all slab-backed images are destroyed.
|
||||
self.slab.destroy_all(device);
|
||||
// Same for the HOST_VISIBLE upload blocks: every staging buffer bound
|
||||
|
||||
@@ -38,7 +38,7 @@ pub enum DrawError {
|
||||
/// A resident's frame could not be copied straight into the guest's pages,
|
||||
/// so the flush owes the CPU route instead.
|
||||
/// See [`super::dmabuf::GuestWriteDecline`].
|
||||
GuestPageWrite(super::dmabuf::GuestWriteDecline),
|
||||
GuestPageWrite(super::host_ram::GuestWriteDecline),
|
||||
/// A specific Vulkan call that returned an error, typed by *(rail,
|
||||
/// operation)*. Former `Vulkan(String)` sites move here so the log names
|
||||
/// which call refused.
|
||||
@@ -1491,58 +1491,19 @@ pub struct GuestRunSource {
|
||||
/// Guest row stride in texels for the buffer→image copy
|
||||
/// (`bufferRowLength`); 0 = tight rows.
|
||||
pub row_length_texels: u32,
|
||||
/// The guest pages [`Self::runs`] were coalesced from, when the producer
|
||||
/// resolved them and the host could export them.
|
||||
/// The same bytes [`Self::runs`] cover, as a bounded reference into this
|
||||
/// process's import of the RAMBlock behind them.
|
||||
///
|
||||
/// Separate from [`GuestRun`] because a run is a *host-pointer* span the CPU
|
||||
/// gather walks, while this is an offset the GPU binds. Keeping both lets one
|
||||
/// source feed either without reconstructing the other's view.
|
||||
///
|
||||
/// `None` is the honest answer for a synthetic source — a test fixture over
|
||||
/// a host `Vec` has no guest pages — and for a host that cannot export. The
|
||||
/// gather path needs only [`GuestRun::host_ptr`] and is unaffected either
|
||||
/// way; this is what lets the GPU read the same bytes with no CPU gather at
|
||||
/// all.
|
||||
pub pages: Option<std::sync::Arc<GuestPageWindow>>,
|
||||
}
|
||||
|
||||
/// One dma-buf over a guest page window, and the id an importer keys it by.
|
||||
#[derive(Debug)]
|
||||
pub struct GuestDmaBuf {
|
||||
/// Process-unique and monotonic. An importer cannot key a cache on the fd
|
||||
/// number instead: numbers are recycled the instant one closes, so a freed
|
||||
/// window and a fresh one can wear the same number and the second would
|
||||
/// bind the first's memory.
|
||||
pub id: u64,
|
||||
/// Owned. Dropping this closes the last reference this process holds, which
|
||||
/// is what ends the GPU's access once every import of it is also gone.
|
||||
pub fd: std::os::fd::OwnedFd,
|
||||
}
|
||||
|
||||
/// The guest pages behind a [`GuestRunSource`], with the dma-buf over them.
|
||||
///
|
||||
/// Separate from [`GuestRun`] because a run is a *host-pointer* span that may
|
||||
/// start part-way into a page, while a dma-buf names whole pages. Keeping both
|
||||
/// lets the same source feed the CPU gather and the GPU-direct bind without
|
||||
/// either having to reconstruct the other's view.
|
||||
#[derive(Debug)]
|
||||
pub struct GuestPageWindow {
|
||||
/// Page-aligned guest physical addresses, in order, covering the span.
|
||||
pub gpas: Vec<u64>,
|
||||
pub page_size: u32,
|
||||
/// Byte offset of the span's first byte within `gpas[0]`. A dma-buf starts
|
||||
/// at a page boundary, so a consumer binding the import must add this to
|
||||
/// reach the first byte the guest actually named.
|
||||
pub head_offset: u32,
|
||||
/// The dma-buf over `gpas`. Not optional: a window with no dma-buf offers
|
||||
/// nothing a `GuestRun` does not already, so "this host cannot export these
|
||||
/// pages" is expressed once, by [`GuestRunSource::pages`] being `None`, and
|
||||
/// a consumer holding a window never has to re-ask.
|
||||
pub dmabuf: std::sync::Arc<GuestDmaBuf>,
|
||||
}
|
||||
|
||||
impl GuestPageWindow {
|
||||
/// Bytes the dma-buf covers — whole pages, so at least
|
||||
/// `head_offset + total_len` of the span it was built for.
|
||||
pub fn mapped_bytes(&self) -> u64 {
|
||||
self.gpas.len() as u64 * u64::from(self.page_size)
|
||||
}
|
||||
/// a host `Vec` has no guest pages — for a host that cannot import, and for
|
||||
/// a page list that is not one contiguous bind range. The gather path needs
|
||||
/// only [`GuestRun::host_ptr`] and is unaffected either way; this is what
|
||||
/// lets the GPU read the same bytes with no CPU gather at all.
|
||||
pub pages: Option<crate::runtime::guest_ram::GuestRef>,
|
||||
}
|
||||
|
||||
/// Producer-assigned identity + generation for CPU-sourced sampled content.
|
||||
|
||||
@@ -26,10 +26,16 @@
|
||||
//! Reading it is how a caller notices an operator asked for something the host
|
||||
//! cannot give and says so, rather than ignoring the request in silence.
|
||||
|
||||
/// Guest pages reach the GPU as a dma-buf import. Setting this off makes the
|
||||
/// device take the copying rails on a host that could have imported —
|
||||
/// see [`crate::backend::vulkan::caps::external_memory`].
|
||||
pub const DMABUF: &str = "REIMS_VGPU_DMABUF";
|
||||
/// Guest RAM reaches the GPU as a host-pointer import over whole RAMBlocks.
|
||||
/// Setting this off makes the device take the copying rails on a host that
|
||||
/// could have imported — see
|
||||
/// [`crate::backend::vulkan::caps::host_pointer`].
|
||||
///
|
||||
/// This is the switch that matters for verification. Where the import works
|
||||
/// every guest window takes it and the copying rails run zero times, so a green
|
||||
/// boot says nothing about them — and they are the only rails on a host without
|
||||
/// the extension, and the rails a discrete GPU takes regardless.
|
||||
pub const GUEST_IMPORT: &str = "REIMS_VGPU_GUEST_IMPORT";
|
||||
|
||||
/// Verbose per-draw logging on top of the always-on fail sink.
|
||||
pub const DRAW_LOG: &str = "REIMS_VGPU_DRAW_LOG";
|
||||
@@ -188,7 +194,7 @@ mod tests {
|
||||
/// by grepping their own environment.
|
||||
#[test]
|
||||
fn every_name_carries_the_crate_prefix() {
|
||||
for name in [DMABUF, DRAW_LOG] {
|
||||
for name in [DRAW_LOG, GUEST_IMPORT] {
|
||||
assert!(name.starts_with("REIMS_VGPU_"), "{name}");
|
||||
assert!(
|
||||
name.bytes()
|
||||
|
||||
@@ -2316,29 +2316,24 @@ pub(super) fn task_gva_guest_run_window<M: HostMemory + HostOps>(
|
||||
Some((gpas, runs))
|
||||
}
|
||||
|
||||
/// The page window behind a set of runs, when this host can export a dma-buf
|
||||
/// over it.
|
||||
/// The bounded guest-memory reference behind a set of runs, when this host can
|
||||
/// import guest RAM and the pages are one bindable stretch.
|
||||
///
|
||||
/// `None` is the routing answer for every host that cannot — no
|
||||
/// `/dev/udmabuf`, guest RAM without a backing fd, a run list too scattered to
|
||||
/// name — and the caller gathers on the CPU exactly as it did before. The
|
||||
/// refusal is logged once per reason by the cache, so a fall back to the copy
|
||||
/// is never silent.
|
||||
/// `None` is the routing answer for every host that cannot import — no
|
||||
/// `VK_EXT_external_memory_host`, an operator who turned the rail off, a shim
|
||||
/// that cannot say where guest RAM lives, or a page list that is not one bind
|
||||
/// range — and the caller gathers on the CPU exactly as it did before. Every
|
||||
/// refusal is named on the always-on sink by
|
||||
/// [`crate::runtime::guest_ram_map`], so a fall back to the copy is never
|
||||
/// silent.
|
||||
fn guest_page_window<M: HostOps>(
|
||||
host: &mut M,
|
||||
gpas: Vec<u64>,
|
||||
page: u64,
|
||||
head_offset: u64,
|
||||
) -> Option<std::sync::Arc<crate::backend::vulkan::engine::GuestPageWindow>> {
|
||||
let dmabuf = crate::runtime::guest_dmabuf::dmabuf_for(host, &gpas, page as u32)?;
|
||||
Some(std::sync::Arc::new(
|
||||
crate::backend::vulkan::engine::GuestPageWindow {
|
||||
gpas,
|
||||
page_size: page as u32,
|
||||
head_offset: head_offset as u32,
|
||||
dmabuf,
|
||||
},
|
||||
))
|
||||
span: u64,
|
||||
) -> Option<crate::runtime::guest_ram::GuestRef> {
|
||||
crate::runtime::guest_ram_map::reference_for_pages(host, &gpas, page, head_offset, span).ok()
|
||||
}
|
||||
|
||||
/// Coalesce GPA-contiguous stretches of `window` into packed host-VA runs
|
||||
@@ -2488,9 +2483,9 @@ fn try_buffer_zero_copy_resolved<M: HostMemory + HostOps>(
|
||||
// though the bind itself resolves.
|
||||
let (gpas, runs) = task_gva_guest_run_window(state, host, task_id, gva + offset, span)?;
|
||||
let page = state.page_size();
|
||||
let pages = guest_page_window(host, gpas, page, (gva + offset) % page);
|
||||
let pages = guest_page_window(host, gpas, page, (gva + offset) % page, span);
|
||||
crate::runtime::drain::note_store_route(if pages.is_some() {
|
||||
"zc_buffer_dmabuf"
|
||||
"zc_buffer_imported"
|
||||
} else {
|
||||
"zc_buffer_gathered"
|
||||
});
|
||||
@@ -2627,7 +2622,7 @@ fn try_linear_sample_zero_copy<M: HostMemory + HostOps>(
|
||||
runs: std::sync::Arc::new(runs),
|
||||
total_len: span,
|
||||
row_length_texels,
|
||||
pages: guest_page_window(host, gpas, page as u64, gva % page as u64),
|
||||
pages: guest_page_window(host, gpas, page as u64, gva % page as u64, span),
|
||||
},
|
||||
native,
|
||||
vouched.map(LinearSampleIdentity::from),
|
||||
@@ -2703,7 +2698,7 @@ pub(super) fn try_type11_sample_zero_copy<M: HostMemory + HostOps>(
|
||||
runs: std::sync::Arc::new(runs),
|
||||
total_len: span,
|
||||
row_length_texels,
|
||||
pages: guest_page_window(host, gpas, page as u64, base_off % page as u64),
|
||||
pages: guest_page_window(host, gpas, page as u64, base_off % page as u64, span),
|
||||
},
|
||||
native,
|
||||
vouched.map(LinearSampleIdentity::from),
|
||||
@@ -2784,7 +2779,7 @@ fn try_type5_sample_zero_copy<M: HostMemory + HostOps>(
|
||||
runs: std::sync::Arc::new(runs),
|
||||
total_len: span,
|
||||
row_length_texels,
|
||||
pages: guest_page_window(host, gpas, page as u64, base_off % page as u64),
|
||||
pages: guest_page_window(host, gpas, page as u64, base_off % page as u64, span),
|
||||
},
|
||||
native,
|
||||
vouched.map(LinearSampleIdentity::from),
|
||||
|
||||
@@ -1,629 +0,0 @@
|
||||
//! The dma-buf over a guest page window, made once and kept.
|
||||
//!
|
||||
//! # Why this is cached rather than made per draw
|
||||
//!
|
||||
//! `UDMABUF_CREATE_LIST` is not a lookup. It walks the run list, takes a
|
||||
//! reference on every page, and builds a scatter-gather table — and the pages it
|
||||
//! references become unswappable and unmigratable for as long as the fd lives.
|
||||
//! A guest surface is bound several times per draw and its pages do not move
|
||||
//! between binds, so making one per bind would pay that walk thousands of times
|
||||
//! a second to get the same answer.
|
||||
//!
|
||||
//! # What bounds it
|
||||
//!
|
||||
//! Pinning is the cost, so pinned bytes are the bound — not entry count, which
|
||||
//! says nothing about how much of the guest's RAM this device has made
|
||||
//! unswappable. [`MAX_PINNED_BYTES`] caps it and the least-recently-used window
|
||||
//! is dropped to stay under.
|
||||
//!
|
||||
//! Dropping an entry here does **not** by itself end the GPU's access: an
|
||||
//! importer holds its own reference through the `VkDeviceMemory` it made, and
|
||||
//! that reference is what its own bounded cache releases. The two caches are
|
||||
//! deliberately independent — each bounds the resource it actually holds, and
|
||||
//! neither can be made to hold the other's — so an entry evicted here is only
|
||||
//! ever a repeated ioctl, never a use-after-free.
|
||||
//!
|
||||
//! # Staleness
|
||||
//!
|
||||
//! The key *is* the page list, so a guest that rewires its page table produces a
|
||||
//! different key and gets a different dma-buf. There is no stale-content case to
|
||||
//! detect: an entry describes exactly the pages it was made from, and a window
|
||||
//! naming other pages cannot reach it.
|
||||
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
use parking_lot::Mutex;
|
||||
|
||||
use crate::backend::vulkan::engine::GuestDmaBuf;
|
||||
use crate::contract::fnv;
|
||||
use crate::runtime::host::{DmaBufExportError, HostOps};
|
||||
|
||||
/// Most guest memory this device will hold pinned through dma-bufs at once.
|
||||
///
|
||||
/// The basis is the largest single surface the device accepts. Every host pixel
|
||||
/// buffer here is tightly packed BGRA8, so [`crate::model::MAX_SCANOUT_DIM`]
|
||||
/// squared at 4 bytes per texel — 256 MiB — is the largest window that can ever
|
||||
/// be asked for. Two of those means a full-size frame's windows plus a second
|
||||
/// set arriving, which is what keeps a resize or a display change from evicting
|
||||
/// the frame it is in the middle of drawing; and it bounds the share of the
|
||||
/// guest's RAM this device can make unswappable at 512 MiB regardless of how
|
||||
/// much the guest has.
|
||||
pub const MAX_PINNED_BYTES: u64 =
|
||||
2 * (crate::model::MAX_SCANOUT_DIM as u64) * (crate::model::MAX_SCANOUT_DIM as u64) * 4;
|
||||
|
||||
/// Source of the ids in [`GuestDmaBuf::id`]. Monotonic and never reused, which
|
||||
/// is the property an importer's cache key needs and an fd number lacks.
|
||||
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
struct Entry {
|
||||
gpas: Vec<u64>,
|
||||
bytes: u64,
|
||||
dmabuf: Arc<GuestDmaBuf>,
|
||||
/// Bumped on every hit; the smallest is evicted first.
|
||||
used: u64,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Cache {
|
||||
/// Windows grouped by [`digest`] of their page list.
|
||||
///
|
||||
/// A bucket holds more than one entry only on a digest collision, so the
|
||||
/// full page-list comparison that decides a hit runs once per lookup
|
||||
/// instead of once per table entry. The digest is not stored on the
|
||||
/// [`Entry`] as well: the map key already is it, and a second copy is a
|
||||
/// field that can drift from the bucket it sits in.
|
||||
buckets: std::collections::HashMap<u64, Vec<Entry>>,
|
||||
/// Windows across all buckets. Kept alongside rather than summed on demand
|
||||
/// because eviction tests it every pass and the census reads it per miss.
|
||||
entry_count: usize,
|
||||
pinned_bytes: u64,
|
||||
clock: u64,
|
||||
/// Set once the host has refused for a reason that cannot change while the
|
||||
/// process runs, so a host with no `/dev/udmabuf` stops asking per bind.
|
||||
/// A per-window refusal — a scattered run list, a page that is not RAM —
|
||||
/// must NOT land here: it says nothing about the next window.
|
||||
host_refusal: Option<DmaBufExportError>,
|
||||
}
|
||||
|
||||
static CACHE: Mutex<Option<Cache>> = Mutex::new(None);
|
||||
|
||||
/// Whether the importing device can take a dma-buf at all, asked before this
|
||||
/// host is asked to make one.
|
||||
///
|
||||
/// The export is not free and not reversible in the way a refused import is: it
|
||||
/// walks the run list, takes a kernel reference on every page, and leaves those
|
||||
/// pages unswappable and unmigratable for as long as the cache holds the fd.
|
||||
/// Doing that and *then* learning the device cannot import it costs the guest up
|
||||
/// to [`MAX_PINNED_BYTES`] of its own RAM for nothing — on Apple hosts, on a
|
||||
/// Linux ICD without the extension, and whenever [`crate::env::DMABUF`] is off.
|
||||
/// So the import side's answer is consulted first.
|
||||
///
|
||||
/// [`DmaBufImport::Unqueried`] is not a refusal. No device exists yet, so the
|
||||
/// answer is not settled; the export goes ahead and the import site decides, as
|
||||
/// it did before this gate. Nothing is latched on that rung either — the very
|
||||
/// next window may get a real answer.
|
||||
fn backend_import_refusal() -> Option<crate::backend::vulkan::caps::DmaBufImport> {
|
||||
use crate::backend::vulkan::caps::DmaBufImport;
|
||||
let rung = crate::backend::vulkan::caps::external_memory::latched();
|
||||
if rung.is_available() || rung == DmaBufImport::Unqueried {
|
||||
return None;
|
||||
}
|
||||
Some(rung)
|
||||
}
|
||||
|
||||
/// Whether assembling a page list for [`dmabuf_for`] can lead anywhere.
|
||||
///
|
||||
/// The same answer [`dmabuf_for`] gates itself on, published so a rail can skip
|
||||
/// the work of *reaching* it. A caller that walks the guest's page table to
|
||||
/// build the list pays an `O(pages)` cost before it can be told no, and on a
|
||||
/// host that will never import — the MoltenVK pathway, an ICD without the
|
||||
/// extension, [`crate::env::DMABUF`] off — that cost repeats for the life of the
|
||||
/// process.
|
||||
///
|
||||
/// This is a shortcut and never the decision: every caller still routes on what
|
||||
/// [`dmabuf_for`] returns, so a rail that skips this check is slower and not
|
||||
/// wrong. Callers must keep any side effect that runs before them, because a
|
||||
/// decline is a routing answer and the copying rail behind it expects the same
|
||||
/// state it always did.
|
||||
pub fn export_available() -> bool {
|
||||
backend_import_refusal().is_none()
|
||||
}
|
||||
|
||||
/// Whether a refusal is a property of the host rather than of this window.
|
||||
///
|
||||
/// The distinction decides whether asking again can ever produce a different
|
||||
/// answer. A missing `/dev/udmabuf` and a guest RAM with no backing fd are
|
||||
/// settled for the life of the process; a run list past the bound, a page that
|
||||
/// is not RAM, and a failed create are all properties of the window in hand and
|
||||
/// say nothing about the next one.
|
||||
fn is_permanent(error: DmaBufExportError) -> bool {
|
||||
matches!(
|
||||
error,
|
||||
DmaBufExportError::CallbackMissing
|
||||
| DmaBufExportError::Unsupported
|
||||
| DmaBufExportError::NotMemfd
|
||||
)
|
||||
}
|
||||
|
||||
/// A 64-bit digest of the page list, used as the cache key.
|
||||
///
|
||||
/// FNV-1a over the GPAs and the page size. A collision would bind one window's
|
||||
/// dma-buf for another's pages, so the full list is compared on hit rather than
|
||||
/// trusting the digest — the digest only narrows the search.
|
||||
fn digest(gpas: &[u64], page_size: u32) -> u64 {
|
||||
let mut hash = fnv::FNV_OFFSET_BASIS;
|
||||
hash = fnv::fold_u64(hash, u64::from(page_size));
|
||||
hash = fnv::fold_u64(hash, gpas.len() as u64);
|
||||
for gpa in gpas {
|
||||
hash = fnv::fold_u64(hash, *gpa);
|
||||
}
|
||||
hash
|
||||
}
|
||||
|
||||
/// Find the window for `gpas`, marking it used, and report what the search
|
||||
/// compared.
|
||||
///
|
||||
/// # Why the step count is still taken
|
||||
///
|
||||
/// It is the proof that the bucket is doing its job. The comparison this counts
|
||||
/// is the full page list — the digest only narrows the search and cannot decide
|
||||
/// a hit — so a lookup that compares one list has resolved the table in one
|
||||
/// step, and one that compares many has found a digest collision. Charged on
|
||||
/// hit *and* miss, so `guest_dmabuf_scan_steps / guest_dmabuf_lookups` read
|
||||
/// against `guest_dmabuf_windows_sum / guest_dmabuf_misses` says whether the
|
||||
/// search still scales with the table.
|
||||
///
|
||||
/// A count rather than a timer: this rail is read on a shared development host
|
||||
/// where every `_us` field is an upper bound, and counts survive contention.
|
||||
fn lookup(
|
||||
cache: &mut Cache,
|
||||
key: u64,
|
||||
gpas: &[u64],
|
||||
clock: u64,
|
||||
) -> (Option<Arc<GuestDmaBuf>>, u64) {
|
||||
let mut steps: u64 = 0;
|
||||
let Some(bucket) = cache.buckets.get_mut(&key) else {
|
||||
return (None, steps);
|
||||
};
|
||||
let found = bucket.iter_mut().find(|e| {
|
||||
steps += 1;
|
||||
e.gpas == gpas
|
||||
});
|
||||
match found {
|
||||
Some(entry) => {
|
||||
entry.used = clock;
|
||||
(Some(Arc::clone(&entry.dmabuf)), steps)
|
||||
}
|
||||
None => (None, steps),
|
||||
}
|
||||
}
|
||||
|
||||
/// The dma-buf over `gpas`, made if this is the first time these pages have been
|
||||
/// asked for and reused otherwise.
|
||||
///
|
||||
/// `None` when this host cannot export them. That is a routing answer and not a
|
||||
/// failure — the caller gathers on the CPU instead — but it is emitted through
|
||||
/// the fail-visible path the first time each distinct reason appears, because a
|
||||
/// silent fall back to the copy is exactly the "works, but slowly, and nobody
|
||||
/// knows why" case the zero-copy rail exists to remove.
|
||||
pub fn dmabuf_for<M: HostOps>(
|
||||
host: &mut M,
|
||||
gpas: &[u64],
|
||||
page_size: u32,
|
||||
) -> Option<Arc<GuestDmaBuf>> {
|
||||
if gpas.is_empty() || page_size == 0 {
|
||||
return None;
|
||||
}
|
||||
if let Some(rung) = backend_import_refusal() {
|
||||
// Once: the rung is a property of the physical device and does not move
|
||||
// while the process runs. The line is on the fail channel because a
|
||||
// reader asking why this boot copies every guest window needs to find
|
||||
// the answer without a second boot — and `disabled_by_env` here is how
|
||||
// they discover a switch someone left set.
|
||||
static NOTED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
if !NOTED.swap(true, Ordering::Relaxed) {
|
||||
crate::observe::fail(format!(
|
||||
"guest_dmabuf_export off reason=backend_cannot_import rung={} \
|
||||
(guest windows take the copying rails; no guest pages are pinned)",
|
||||
rung.slug()
|
||||
));
|
||||
}
|
||||
return None;
|
||||
}
|
||||
let key = digest(gpas, page_size);
|
||||
let mut guard = CACHE.lock();
|
||||
let cache = guard.get_or_insert_with(Cache::default);
|
||||
if let Some(refusal) = cache.host_refusal {
|
||||
// Settled for the life of the process. Asking again would ioctl on
|
||||
// every bind to be told the same thing.
|
||||
let _ = refusal;
|
||||
return None;
|
||||
}
|
||||
cache.clock += 1;
|
||||
let clock = cache.clock;
|
||||
let (found, steps) = lookup(cache, key, gpas, clock);
|
||||
crate::runtime::drain::note_store_route("guest_dmabuf_lookups");
|
||||
crate::runtime::drain::note_store_route_n("guest_dmabuf_scan_steps", steps);
|
||||
if let Some(dmabuf) = found {
|
||||
crate::runtime::drain::note_store_route("guest_dmabuf_hits");
|
||||
return Some(dmabuf);
|
||||
}
|
||||
|
||||
let fd = match host.dmabuf_for_pages(gpas, page_size as usize) {
|
||||
Ok(fd) => fd,
|
||||
Err(error) => {
|
||||
if is_permanent(error) {
|
||||
cache.host_refusal = Some(error);
|
||||
}
|
||||
drop(guard);
|
||||
// Fail-visible, and latched per reason: a host that cannot export at
|
||||
// all says so once rather than once per bind, and a window that is
|
||||
// too scattered says so with the numbers that made it so.
|
||||
crate::observe::Emit::decline("guest_dmabuf_export", &error)
|
||||
.field("pages", gpas.len())
|
||||
.field("page_size", page_size)
|
||||
.fail_once(0);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
let bytes = gpas.len() as u64 * u64::from(page_size);
|
||||
let dmabuf = Arc::new(GuestDmaBuf {
|
||||
id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
|
||||
fd,
|
||||
});
|
||||
cache.buckets.entry(key).or_default().push(Entry {
|
||||
gpas: gpas.to_vec(),
|
||||
bytes,
|
||||
dmabuf: Arc::clone(&dmabuf),
|
||||
used: clock,
|
||||
});
|
||||
cache.entry_count += 1;
|
||||
cache.pinned_bytes += bytes;
|
||||
evict_to_bound(cache);
|
||||
// The table's own size, sampled once per miss. Both fields are needed
|
||||
// because the entry count and the pin come apart by orders of magnitude:
|
||||
// 512 MiB of 8 KiB vertex windows is 65 536 entries and 512 MiB of one
|
||||
// framebuffer is one.
|
||||
//
|
||||
// A driven x86/Vulkan boot reads this table at ~956 windows holding ~490 MiB
|
||||
// — right against [`MAX_PINNED_BYTES`], so it evicts continuously, and far
|
||||
// longer than a table a linear search can afford. That reading is what put
|
||||
// the lookup in a bucket; it stays sampled because the bound it establishes
|
||||
// is the one [`evict_to_bound`]'s cost is priced against.
|
||||
//
|
||||
// These two are **sums, not gauges** — the census map adds. Divide each by
|
||||
// `guest_dmabuf_misses` for the mean over the window; a reader quoting the
|
||||
// raw field as "the cache holds N windows" is off by the miss count.
|
||||
crate::runtime::drain::note_store_route("guest_dmabuf_misses");
|
||||
crate::runtime::drain::note_store_route_n("guest_dmabuf_windows_sum", cache.entry_count as u64);
|
||||
crate::runtime::drain::note_store_route_n(
|
||||
"guest_dmabuf_pinned_kb_sum",
|
||||
cache.pinned_bytes >> 10,
|
||||
);
|
||||
Some(dmabuf)
|
||||
}
|
||||
|
||||
/// Drop least-recently-used windows until the pinned total is back under
|
||||
/// [`MAX_PINNED_BYTES`].
|
||||
///
|
||||
/// The entry just inserted is the most recently used, so it is never the one
|
||||
/// evicted — a single window larger than the whole bound would otherwise be
|
||||
/// created and dropped on every bind, which is worse than not caching at all.
|
||||
///
|
||||
/// Still a walk of every window, and deliberately so: it runs only on a miss
|
||||
/// that pushed the pin over the bound, which the lookup no longer does, and an
|
||||
/// LRU order maintained on the side would have to be updated on every one of
|
||||
/// the millions of hits to save work on the thousands of evictions.
|
||||
fn evict_to_bound(cache: &mut Cache) {
|
||||
while cache.pinned_bytes > MAX_PINNED_BYTES && cache.entry_count > 1 {
|
||||
// Ties in `used` break in whatever order the map iterates. They cannot
|
||||
// arise between two live windows — the clock advances once per lookup
|
||||
// and only the window that lookup touched takes the new value — and
|
||||
// between equally-stale windows either choice is the same choice.
|
||||
let Some((key, idx)) = cache
|
||||
.buckets
|
||||
.iter()
|
||||
.flat_map(|(k, bucket)| bucket.iter().enumerate().map(move |(i, e)| (*k, i, e.used)))
|
||||
.min_by_key(|&(_, _, used)| used)
|
||||
.map(|(k, i, _)| (k, i))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let Some(bucket) = cache.buckets.get_mut(&key) else {
|
||||
return;
|
||||
};
|
||||
cache.pinned_bytes -= bucket[idx].bytes;
|
||||
bucket.swap_remove(idx);
|
||||
if bucket.is_empty() {
|
||||
cache.buckets.remove(&key);
|
||||
}
|
||||
cache.entry_count -= 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Two accessors used to sit here, `pinned_bytes` and `cached_windows`, each
|
||||
// documented "census only" and each with no caller. The census this module
|
||||
// actually takes is in `store_dmabuf` above, which reads `cache.pinned_bytes`
|
||||
// and `cache.entry_count` straight off the guard it is already holding and
|
||||
// emits them as `guest_dmabuf_pinned_kb_sum` and `guest_dmabuf_windows_sum`.
|
||||
// So the accessors were a second way to ask a question nothing asked, and
|
||||
// removing them loses no reading — both numbers are still on the counter set.
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Two different page lists must not share a dma-buf, and the same list
|
||||
/// must not build a second one.
|
||||
///
|
||||
/// The digest alone cannot carry this: it narrows the search, and the full
|
||||
/// list decides. A cache that trusted the digest would hand one window's
|
||||
/// pages to another on a collision, which is silent corruption rather than
|
||||
/// a slow frame.
|
||||
#[test]
|
||||
fn the_key_is_the_page_list_and_not_just_its_digest() {
|
||||
let a = [0x1000u64, 0x2000, 0x3000];
|
||||
let b = [0x1000u64, 0x2000, 0x4000];
|
||||
assert_ne!(digest(&a, 4096), digest(&b, 4096));
|
||||
// Same pages under a different page size are a different window: the
|
||||
// dma-buf's ranges are sized from it.
|
||||
assert_ne!(digest(&a, 4096), digest(&a, 16384));
|
||||
assert_eq!(digest(&a, 4096), digest(&a, 4096));
|
||||
}
|
||||
|
||||
/// A device that cannot import closes the export side, and one that has not
|
||||
/// been created yet does not.
|
||||
///
|
||||
/// The asymmetry is the point. A settled negative rung means no window will
|
||||
/// ever be imported, so exporting one only pins guest pages; `Unqueried`
|
||||
/// means no device exists yet and says nothing about what it will report, so
|
||||
/// treating it as a refusal would turn the first frames of every boot into
|
||||
/// copies on a host that is fully capable.
|
||||
#[test]
|
||||
fn a_settled_negative_rung_closes_the_export_and_unqueried_does_not() {
|
||||
use crate::backend::vulkan::caps::external_memory::latch;
|
||||
use crate::backend::vulkan::caps::DmaBufImport;
|
||||
|
||||
latch(DmaBufImport::Unqueried);
|
||||
assert_eq!(backend_import_refusal(), None, "no device yet is not a no");
|
||||
latch(DmaBufImport::Supported);
|
||||
assert_eq!(backend_import_refusal(), None);
|
||||
for closed in [
|
||||
DmaBufImport::NoExternalMemoryFd,
|
||||
DmaBufImport::NoDmaBufExtension,
|
||||
DmaBufImport::NotImportable,
|
||||
DmaBufImport::DisabledByEnv,
|
||||
] {
|
||||
latch(closed);
|
||||
assert_eq!(
|
||||
backend_import_refusal(),
|
||||
Some(closed),
|
||||
"{closed:?} must close the export and name itself"
|
||||
);
|
||||
}
|
||||
latch(DmaBufImport::Unqueried);
|
||||
}
|
||||
|
||||
/// The shortcut a rail takes before building a page list agrees with the
|
||||
/// gate that decides. Two answers here would mean a rail declining work
|
||||
/// `dmabuf_for` would have accepted, which is a silent loss of the rail on
|
||||
/// exactly the hosts that can run it.
|
||||
#[test]
|
||||
fn the_published_shortcut_agrees_with_the_gate() {
|
||||
use crate::backend::vulkan::caps::external_memory::latch;
|
||||
use crate::backend::vulkan::caps::DmaBufImport;
|
||||
|
||||
for rung in [
|
||||
DmaBufImport::Unqueried,
|
||||
DmaBufImport::Supported,
|
||||
DmaBufImport::NoExternalMemoryFd,
|
||||
DmaBufImport::NoDmaBufExtension,
|
||||
DmaBufImport::NotImportable,
|
||||
DmaBufImport::DisabledByEnv,
|
||||
] {
|
||||
latch(rung);
|
||||
assert_eq!(
|
||||
export_available(),
|
||||
backend_import_refusal().is_none(),
|
||||
"{rung:?}"
|
||||
);
|
||||
}
|
||||
latch(DmaBufImport::Unqueried);
|
||||
}
|
||||
|
||||
/// With the import side closed, the host is never asked to make a dma-buf.
|
||||
///
|
||||
/// The witness is the cache's own permanent-refusal latch: [`NullHost`]
|
||||
/// answers `CallbackMissing`, which [`is_permanent`] settles for the life of
|
||||
/// the process. So a gate that let the call through would leave that latch
|
||||
/// set, and its staying clear is proof the ioctl — and the page pin behind
|
||||
/// it — never happened.
|
||||
#[test]
|
||||
fn a_closed_import_side_never_asks_the_host_to_pin_anything() {
|
||||
use crate::backend::vulkan::caps::external_memory::latch;
|
||||
use crate::backend::vulkan::caps::DmaBufImport;
|
||||
|
||||
// Start from a cache that has not already given up on this host, so the
|
||||
// early return under test is the one being witnessed.
|
||||
*CACHE.lock() = Some(Cache::default());
|
||||
latch(DmaBufImport::NoDmaBufExtension);
|
||||
let mut host = crate::qemu::host_ops::NullHost;
|
||||
assert!(dmabuf_for(&mut host, &[0x1000, 0x2000], 4096).is_none());
|
||||
{
|
||||
let guard = CACHE.lock();
|
||||
let cache = guard.as_ref().expect("cache was seeded above");
|
||||
assert!(
|
||||
cache.host_refusal.is_none(),
|
||||
"the host was asked to export despite a closed import side"
|
||||
);
|
||||
assert_eq!(cache.entry_count, 0);
|
||||
assert_eq!(cache.pinned_bytes, 0);
|
||||
}
|
||||
latch(DmaBufImport::Unqueried);
|
||||
*CACHE.lock() = None;
|
||||
}
|
||||
|
||||
/// A host that cannot export at all is asked once. The alternative is an
|
||||
/// ioctl per bind — several thousand a second under compositing — to be
|
||||
/// told the same thing every time.
|
||||
#[test]
|
||||
fn a_permanent_refusal_is_settled_and_a_local_one_is_not() {
|
||||
for permanent in [
|
||||
DmaBufExportError::CallbackMissing,
|
||||
DmaBufExportError::Unsupported,
|
||||
DmaBufExportError::NotMemfd,
|
||||
] {
|
||||
assert!(is_permanent(permanent), "{permanent:?}");
|
||||
}
|
||||
// These describe the window in hand. Latching any of them would turn
|
||||
// one scattered surface into a process-wide loss of the rail.
|
||||
for local in [
|
||||
DmaBufExportError::TooFragmented,
|
||||
DmaBufExportError::NotRam,
|
||||
DmaBufExportError::Create,
|
||||
DmaBufExportError::Alignment,
|
||||
DmaBufExportError::PageSize,
|
||||
DmaBufExportError::Args,
|
||||
DmaBufExportError::UnknownCode(-99),
|
||||
] {
|
||||
assert!(!is_permanent(local), "{local:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The bound is on pinned bytes, and eviction never drops the entry that
|
||||
/// was just made.
|
||||
///
|
||||
/// A window larger than the whole bound would otherwise be created, counted,
|
||||
/// and immediately evicted on every single bind — paying the page walk every
|
||||
/// time to cache nothing, which is strictly worse than not caching.
|
||||
#[test]
|
||||
fn eviction_bounds_pinned_bytes_and_keeps_the_newest() {
|
||||
let mut cache = Cache::default();
|
||||
let big = MAX_PINNED_BYTES / 2 + 1;
|
||||
push(&mut cache, 1, big, 1);
|
||||
push(&mut cache, 2, big, 2);
|
||||
push(&mut cache, 3, big, 3);
|
||||
evict_to_bound(&mut cache);
|
||||
assert!(cache.pinned_bytes <= MAX_PINNED_BYTES, "bound not restored");
|
||||
let ids = ids(&cache);
|
||||
assert!(ids.contains(&3), "the newest window was evicted: {ids:?}");
|
||||
assert!(!ids.contains(&1), "the oldest window survived: {ids:?}");
|
||||
assert_eq!(cache.entry_count, ids.len(), "entry_count drifted");
|
||||
}
|
||||
|
||||
/// A hit resolves the table in one page-list comparison however many windows
|
||||
/// it holds.
|
||||
///
|
||||
/// This is the bound the bucket exists for. The lookup used to compare every
|
||||
/// entry's digest in turn, and a driven x86/Vulkan boot read 3.6 M lookups
|
||||
/// against 1.61 G comparisons — 444 per lookup, over a table averaging 956
|
||||
/// windows, which is the half-table walk a linear scan of a hit costs. The
|
||||
/// assertion is on the *step count* rather than a duration for the reason
|
||||
/// [`lookup`] gives.
|
||||
///
|
||||
/// A thousand windows rather than a handful: the failure mode being excluded
|
||||
/// is one that only shows up as the table grows, so a table small enough for
|
||||
/// a scan to look fine cannot witness it.
|
||||
#[test]
|
||||
fn a_hit_does_not_scale_with_the_number_of_cached_windows() {
|
||||
let mut cache = Cache::default();
|
||||
for id in 1..=1000u64 {
|
||||
push(&mut cache, id, 4096, id);
|
||||
}
|
||||
assert_eq!(cache.entry_count, 1000);
|
||||
// The window inserted last and the one inserted first cost the same,
|
||||
// which a scan cannot manage for both at once.
|
||||
for probe in [1u64, 500, 1000] {
|
||||
let gpas = [probe];
|
||||
let (found, steps) = lookup(&mut cache, digest(&gpas, 4096), &gpas, 10_000);
|
||||
assert!(found.is_some(), "window {probe} was not found");
|
||||
assert_eq!(steps, 1, "window {probe} took {steps} comparisons");
|
||||
}
|
||||
// A window that was never cached compares nothing at all: its digest
|
||||
// names no bucket.
|
||||
let absent = [0xdead_beefu64];
|
||||
let (found, steps) = lookup(&mut cache, digest(&absent, 4096), &absent, 10_001);
|
||||
assert!(found.is_none());
|
||||
assert_eq!(steps, 0, "a miss walked {steps} entries");
|
||||
}
|
||||
|
||||
/// Two windows whose page lists collide under [`digest`] share a bucket, and
|
||||
/// each still gets its own dma-buf.
|
||||
///
|
||||
/// The digest narrows and the full list decides, so the bucket has to hold
|
||||
/// both and the comparison inside it has to separate them. Constructed by
|
||||
/// filing both under one key rather than by finding a real FNV-1a collision:
|
||||
/// what is under test is the bucket's behaviour when it holds two, not the
|
||||
/// hash's spread.
|
||||
#[test]
|
||||
fn a_digest_collision_keeps_the_windows_apart() {
|
||||
let mut cache = Cache::default();
|
||||
let shared = 0x5eed_u64;
|
||||
for id in [11u64, 22] {
|
||||
cache.buckets.entry(shared).or_default().push(Entry {
|
||||
gpas: vec![id],
|
||||
bytes: 4096,
|
||||
dmabuf: Arc::new(GuestDmaBuf { id, fd: pipe_fd() }),
|
||||
used: id,
|
||||
});
|
||||
cache.entry_count += 1;
|
||||
cache.pinned_bytes += 4096;
|
||||
}
|
||||
for (probe, want) in [(11u64, 11u64), (22, 22)] {
|
||||
let (found, steps) = lookup(&mut cache, shared, &[probe], 99);
|
||||
assert_eq!(found.expect("collided window").id, want);
|
||||
assert!((1..=2).contains(&steps), "unexpected step count {steps}");
|
||||
}
|
||||
// A third list under the same digest matches neither.
|
||||
let (found, _) = lookup(&mut cache, shared, &[33], 100);
|
||||
assert!(found.is_none(), "a non-member matched inside the bucket");
|
||||
}
|
||||
|
||||
/// Push a window with a one-page list of `id` under its real digest.
|
||||
fn push(cache: &mut Cache, id: u64, bytes: u64, used: u64) {
|
||||
let gpas = vec![id];
|
||||
cache
|
||||
.buckets
|
||||
.entry(digest(&gpas, 4096))
|
||||
.or_default()
|
||||
.push(Entry {
|
||||
gpas,
|
||||
bytes,
|
||||
dmabuf: Arc::new(GuestDmaBuf {
|
||||
id,
|
||||
// A pipe read end is a cheap real fd; the cache never looks
|
||||
// at what the fd *is*, only that it owns one.
|
||||
fd: pipe_fd(),
|
||||
}),
|
||||
used,
|
||||
});
|
||||
cache.entry_count += 1;
|
||||
cache.pinned_bytes += bytes;
|
||||
}
|
||||
|
||||
fn ids(cache: &Cache) -> Vec<u64> {
|
||||
cache
|
||||
.buckets
|
||||
.values()
|
||||
.flatten()
|
||||
.map(|e| e.dmabuf.id)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A single window larger than the whole bound is kept rather than
|
||||
/// thrashed, and the accounting stays honest about being over.
|
||||
#[test]
|
||||
fn one_oversized_window_is_kept_rather_than_rebuilt_every_bind() {
|
||||
let mut cache = Cache::default();
|
||||
push(&mut cache, 1, MAX_PINNED_BYTES * 2, 1);
|
||||
evict_to_bound(&mut cache);
|
||||
assert_eq!(cache.entry_count, 1, "the only entry was evicted");
|
||||
}
|
||||
|
||||
fn pipe_fd() -> std::os::fd::OwnedFd {
|
||||
let (read, _write) = std::io::pipe().expect("a pipe for a placeholder fd");
|
||||
std::os::fd::OwnedFd::from(read)
|
||||
}
|
||||
}
|
||||
@@ -550,6 +550,114 @@ impl GuestSlice {
|
||||
}
|
||||
}
|
||||
|
||||
/// The import granularity the active backend published, or 0 before any
|
||||
/// backend has created a device that can import at all.
|
||||
///
|
||||
/// # Why this is a latch and not a parameter
|
||||
///
|
||||
/// The granularity is measured from the GPU — `minImportedHostPointerAlignment`
|
||||
/// on Vulkan, the host page size on the Metal-direct arm — and it is needed by
|
||||
/// [`crate::runtime::guest_ram_map`], which runs on the runtime side and holds
|
||||
/// no device context. The alternative is threading a number from the backend
|
||||
/// through every decode path that might name guest memory, which is how a site
|
||||
/// ends up with a default nobody measured.
|
||||
///
|
||||
/// Zero means *no backend has said it can import*, which is the honest answer
|
||||
/// on a host without the extension and the one the map treats as "run the
|
||||
/// copying rails". A backend that resolves a negative capability rung must not
|
||||
/// publish, so the absence of a number is itself the gate.
|
||||
static GRANULARITY: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||
|
||||
/// Publish the granularity a freshly created device resolved to.
|
||||
///
|
||||
/// Called once per device creation, including each recreate, so a rebuilt
|
||||
/// device republishes rather than leaving the previous one's answer standing. A
|
||||
/// backend whose capability rung refused must call [`forget_granularity`]
|
||||
/// instead — publishing a number from a device that declined the handle type is
|
||||
/// how the map would build imports nothing can bind.
|
||||
///
|
||||
/// Refuses a granularity that is not a power of two: every alignment
|
||||
/// computation here masks with `align - 1`, and a non-power-of-two would make
|
||||
/// those masks name arbitrary bytes rather than refusing.
|
||||
pub fn latch_granularity(align: u64) {
|
||||
if align == 0 || !align.is_power_of_two() {
|
||||
Emit::decline(EVENT, &GuestRamError::AlignmentNotPowerOfTwo { align }).fail();
|
||||
forget_granularity();
|
||||
return;
|
||||
}
|
||||
GRANULARITY.store(align, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Withdraw the published granularity: no device can import guest RAM.
|
||||
pub fn forget_granularity() {
|
||||
GRANULARITY.store(0, std::sync::atomic::Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// The published granularity, or `None` when no backend can import.
|
||||
///
|
||||
/// `Relaxed` on both sides: this gates whether an optimization is attempted, and
|
||||
/// a reader that sees the previous value takes the copying path for one window.
|
||||
/// Nothing here orders access to any other memory.
|
||||
pub fn granularity() -> Option<u64> {
|
||||
match GRANULARITY.load(std::sync::atomic::Ordering::Relaxed) {
|
||||
0 => None,
|
||||
align => Some(align),
|
||||
}
|
||||
}
|
||||
|
||||
/// A bounded guest-memory reference a backend can bind: the import that owns
|
||||
/// the bytes, and the slice inside it.
|
||||
///
|
||||
/// This is what replaces a page list plus an exported fd. Producing one costs a
|
||||
/// range check and an `Arc` clone — no ioctl, no allocation, no kernel
|
||||
/// reference per page — which is why nothing caches them.
|
||||
///
|
||||
/// The pair travels together because neither half is usable alone: a
|
||||
/// [`GuestSlice`] carries no absolute offset by construction, and the import is
|
||||
/// the only thing that can turn one into a [`BoundRange`].
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GuestRef {
|
||||
import: std::sync::Arc<GuestRamImport>,
|
||||
slice: GuestSlice,
|
||||
}
|
||||
|
||||
impl GuestRef {
|
||||
/// Pair a slice with the import that made it.
|
||||
///
|
||||
/// Refuses a mismatched pair up front rather than at bind time, so a
|
||||
/// mis-plumbed call site fails where it is written instead of one layer
|
||||
/// down inside the backend.
|
||||
pub fn new(
|
||||
import: std::sync::Arc<GuestRamImport>,
|
||||
slice: GuestSlice,
|
||||
) -> Result<Self, GuestRamError> {
|
||||
import.resolve(&slice)?;
|
||||
Ok(Self { import, slice })
|
||||
}
|
||||
|
||||
/// The import to bind against. The backend keys its device handle on
|
||||
/// [`GuestRamImport::id`] and imports [`GuestRamImport::host_base`] once.
|
||||
pub fn import(&self) -> &std::sync::Arc<GuestRamImport> {
|
||||
&self.import
|
||||
}
|
||||
|
||||
/// The checked byte range inside that import.
|
||||
pub fn bound(&self) -> Result<BoundRange, GuestRamError> {
|
||||
self.import.resolve(&self.slice)
|
||||
}
|
||||
|
||||
/// Bytes between the start of the bound range and the first byte the caller
|
||||
/// asked for.
|
||||
pub fn head(&self) -> u64 {
|
||||
self.slice.head()
|
||||
}
|
||||
|
||||
/// Bytes the caller asked for.
|
||||
pub fn requested(&self) -> u64 {
|
||||
self.slice.requested()
|
||||
}
|
||||
}
|
||||
|
||||
/// What a backend binds: a byte range inside one import, already checked.
|
||||
///
|
||||
/// Produced only by [`GuestRamImport::resolve`], so holding one is proof the
|
||||
|
||||
@@ -0,0 +1,547 @@
|
||||
//! The process's imports of guest RAM: built once from the shim's spans, and
|
||||
//! the only place a guest physical address becomes a bindable reference.
|
||||
//!
|
||||
//! # What this replaces
|
||||
//!
|
||||
//! The dma-buf rail had a cache here, and it had to: `UDMABUF_CREATE_LIST`
|
||||
//! walked every page, took a kernel reference on each, and cost enough that a
|
||||
//! digest-bucketed LRU bounded by pinned bytes was worth its own module.
|
||||
//!
|
||||
//! Under the host-pointer model there is nothing left to cache.
|
||||
//! [`crate::runtime::guest_ram::GuestRamImport::slice`] is a range check.
|
||||
//! What *is* worth holding is the small thing the cache was built around: the
|
||||
//! imports themselves, one per RAMBlock, made once at first use and held for
|
||||
//! the VM's lifetime. This module is that, and it is a `Vec` of at most a
|
||||
//! handful of entries rather than a cache with an eviction policy.
|
||||
//!
|
||||
//! # Why the imports are built here and not at device create
|
||||
//!
|
||||
//! The backend measures the granularity; the runtime holds the
|
||||
//! [`HostOps`](crate::runtime::HostOps) that can say where guest RAM lives.
|
||||
//! Neither side has both, and the device context deliberately does not take a
|
||||
//! host — see the module doc on [`crate::qemu::host_ops`] for why the runtime
|
||||
//! keeps it. So the granularity is published by the backend through
|
||||
//! [`crate::runtime::guest_ram::latch_granularity`] and the spans are fetched
|
||||
//! here, on the first guest-memory reference of a boot.
|
||||
//!
|
||||
//! Building lazily rather than eagerly also gets the ordering right for free:
|
||||
//! the device exists before any guest command is decoded, so the granularity is
|
||||
//! always published by the time the first reference is asked for.
|
||||
//!
|
||||
//! # What a refusal means
|
||||
//!
|
||||
//! Every refusal here puts the whole boot on the copying rails for the
|
||||
//! addresses it covers, so none of them is a slow path and none may be silent.
|
||||
//! The one *expected* refusal is [`MapRefusal::NoBackendImport`]: a host without
|
||||
//! the extension, or an operator who set
|
||||
//! [`crate::env::GUEST_IMPORT`](crate::env::GUEST_IMPORT) off. That one is a
|
||||
//! statement about the host rather than a loss, so it is reported once on the
|
||||
//! off channel rather than as a failure per reference.
|
||||
|
||||
use crate::runtime::guest_ram::{granularity, GuestRamError, GuestRamImport, GuestRef};
|
||||
use crate::runtime::host::{GuestRamRegionsError, HostOps};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Why a guest physical address did not become a bindable reference.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum MapRefusal {
|
||||
/// No backend published an import granularity: this host cannot import
|
||||
/// guest RAM, or an operator asked it not to. Expected, and the state every
|
||||
/// copying rail exists for.
|
||||
NoBackendImport,
|
||||
/// The shim could not say where guest RAM lives. Carries the check that
|
||||
/// refused.
|
||||
HostRefused(GuestRamRegionsError),
|
||||
/// The shim answered, but no span survived being bounded to the granularity
|
||||
/// — every region was empty, unmapped, malformed, or shorter than one
|
||||
/// granule. Distinct from [`Self::HostRefused`] because the host answered
|
||||
/// fine and it is our own bound that rejected every span.
|
||||
NoUsableRegion { spans: usize },
|
||||
/// The address is not inside any imported span. Guest RAM the GPU can reach
|
||||
/// exists, and this address is not in it — a device MMIO address, a hole,
|
||||
/// or a page the guest named that this machine does not back.
|
||||
GpaNotInAnyImport { gpa: u64 },
|
||||
/// The address is in a span, and the length asked for leaves it. Carries the
|
||||
/// bound's own reason so the check that refused keeps its name.
|
||||
OutsideImport(GuestRamError),
|
||||
/// A page list that is not one GPA-contiguous stretch.
|
||||
///
|
||||
/// Not a statement that the pages are un-importable — they are all inside
|
||||
/// one RAMBlock and each is nameable. It is a statement about the *bind*: a
|
||||
/// `VkBuffer` range and a Metal buffer offset are each one offset and one
|
||||
/// length, so a surface assembled from four stretches is four of them, and
|
||||
/// no consumer takes several yet. Named and counted because how often it
|
||||
/// fires is what says whether widening them is worth doing.
|
||||
Scattered { pages: usize, first: u64 },
|
||||
}
|
||||
|
||||
impl crate::observe::Decline for MapRefusal {
|
||||
fn slug(&self) -> &'static str {
|
||||
match self {
|
||||
Self::NoBackendImport => "guest_ram_map_no_backend_import",
|
||||
Self::HostRefused(_) => "guest_ram_map_host_refused",
|
||||
Self::NoUsableRegion { .. } => "guest_ram_map_no_usable_region",
|
||||
Self::GpaNotInAnyImport { .. } => "guest_ram_map_gpa_not_in_any_import",
|
||||
Self::Scattered { .. } => "guest_ram_map_scattered",
|
||||
// The inner reason is the diagnosis; this wrapper only says where
|
||||
// it happened, so it forwards rather than adding a slug of its own.
|
||||
Self::OutsideImport(inner) => inner.slug(),
|
||||
}
|
||||
}
|
||||
|
||||
fn fields(&self) -> Vec<(&'static str, String)> {
|
||||
match self {
|
||||
Self::NoBackendImport => Vec::new(),
|
||||
Self::HostRefused(inner) => {
|
||||
let mut f = vec![("host_reason", inner.slug().to_string())];
|
||||
f.extend(crate::observe::Decline::fields(inner));
|
||||
f
|
||||
}
|
||||
Self::NoUsableRegion { spans } => vec![("spans", spans.to_string())],
|
||||
Self::GpaNotInAnyImport { gpa } => vec![("gpa", format!("{gpa:#x}"))],
|
||||
Self::Scattered { pages, first } => vec![
|
||||
("pages", pages.to_string()),
|
||||
("first", format!("{first:#x}")),
|
||||
],
|
||||
Self::OutsideImport(inner) => inner.fields(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
crate::observe::decline_display!(MapRefusal);
|
||||
|
||||
/// The greppable event class for this module's refusals.
|
||||
const EVENT: &str = "guest_ram_map";
|
||||
|
||||
/// The imports this process holds, or the refusal that stopped it building any.
|
||||
///
|
||||
/// Resolved once and then read. A `Mutex` rather than a `OnceLock` because a
|
||||
/// device recreate must be able to drop the imports: the backend's handles die
|
||||
/// with the device, and an import whose identity outlived them would let a
|
||||
/// stale [`crate::runtime::guest_ram::GuestSlice`] resolve against a
|
||||
/// `VkDeviceMemory` that no longer exists.
|
||||
static MAP: std::sync::Mutex<Option<Resolved>> = std::sync::Mutex::new(None);
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Resolved {
|
||||
/// One per usable RAMBlock span, in the order the shim reported them.
|
||||
/// Ordinary machines have one or two.
|
||||
imports: Vec<Arc<GuestRamImport>>,
|
||||
/// Set when the resolution refused, so the next reference does not re-ask
|
||||
/// the shim for an answer that will not change. A refusal here is about the
|
||||
/// host and the granularity, both of which are fixed for the device's life.
|
||||
refusal: Option<MapRefusal>,
|
||||
}
|
||||
|
||||
/// Forget every import.
|
||||
///
|
||||
/// Called when the backend tears its device down. The next reference rebuilds,
|
||||
/// against fresh identities, so nothing made before the teardown resolves after
|
||||
/// it — see [`crate::runtime::guest_ram::ImportId`] for why that matters.
|
||||
pub fn reset() {
|
||||
*MAP.lock().unwrap_or_else(|p| p.into_inner()) = None;
|
||||
}
|
||||
|
||||
/// Every import this process holds, for a backend that needs to create or
|
||||
/// release its device-side handles.
|
||||
///
|
||||
/// Empty before the first reference of a boot and on a host that cannot import.
|
||||
pub fn imports() -> Vec<Arc<GuestRamImport>> {
|
||||
MAP.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.as_ref()
|
||||
.map(|r| r.imports.clone())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Turn a guest physical address and a length into a bindable reference.
|
||||
///
|
||||
/// The whole guest-memory rail goes through here. Building the imports on the
|
||||
/// first call is why `host` is taken: after that it is not touched.
|
||||
pub fn reference<H: HostOps + ?Sized>(
|
||||
host: &mut H,
|
||||
gpa: u64,
|
||||
len: u64,
|
||||
) -> Result<GuestRef, MapRefusal> {
|
||||
let mut guard = MAP.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let resolved = match guard.as_mut() {
|
||||
Some(resolved) => resolved,
|
||||
None => {
|
||||
*guard = Some(resolve(host));
|
||||
guard.as_mut().expect("just resolved")
|
||||
}
|
||||
};
|
||||
if let Some(refusal) = resolved.refusal {
|
||||
return Err(report_once(refusal));
|
||||
}
|
||||
let import = resolved
|
||||
.imports
|
||||
.iter()
|
||||
.find(|i| i.contains_gpa(gpa))
|
||||
.ok_or(MapRefusal::GpaNotInAnyImport { gpa })
|
||||
.map_err(report_once)?;
|
||||
// `slice_for_gpa` emits its own named refusal on the fail channel, so the
|
||||
// wrapper forwards the reason rather than adding a second line for it.
|
||||
let slice = import
|
||||
.slice_for_gpa(gpa, len)
|
||||
.map_err(MapRefusal::OutsideImport)?;
|
||||
GuestRef::new(Arc::clone(import), slice).map_err(MapRefusal::OutsideImport)
|
||||
}
|
||||
|
||||
/// [`reference`] for a decoded page list: `len` bytes starting `in_page` bytes
|
||||
/// into `gpas[0]`.
|
||||
///
|
||||
/// The one implementation of the contiguity rule, so the sampled, buffer and
|
||||
/// writeback rails cannot disagree about what a bindable page list is.
|
||||
pub fn reference_for_pages<H: HostOps + ?Sized>(
|
||||
host: &mut H,
|
||||
gpas: &[u64],
|
||||
page_size: u64,
|
||||
in_page: u64,
|
||||
len: u64,
|
||||
) -> Result<GuestRef, MapRefusal> {
|
||||
let Some(&first) = gpas.first() else {
|
||||
return Err(report_once(MapRefusal::Scattered {
|
||||
pages: 0,
|
||||
first: 0,
|
||||
}));
|
||||
};
|
||||
let contiguous = gpas
|
||||
.iter()
|
||||
.enumerate()
|
||||
.all(|(i, gpa)| *gpa == first + (i as u64) * page_size);
|
||||
if !contiguous {
|
||||
return Err(report_once(MapRefusal::Scattered {
|
||||
pages: gpas.len(),
|
||||
first,
|
||||
}));
|
||||
}
|
||||
reference(host, first + in_page, len)
|
||||
}
|
||||
|
||||
/// Ask the host where guest RAM lives and bound every span to the backend's
|
||||
/// granularity.
|
||||
fn resolve<H: HostOps + ?Sized>(host: &mut H) -> Resolved {
|
||||
let Some(align) = granularity() else {
|
||||
return Resolved {
|
||||
imports: Vec::new(),
|
||||
refusal: Some(MapRefusal::NoBackendImport),
|
||||
};
|
||||
};
|
||||
let spans = match host.guest_ram_regions() {
|
||||
Ok(spans) => spans,
|
||||
Err(why) => {
|
||||
return Resolved {
|
||||
imports: Vec::new(),
|
||||
refusal: Some(MapRefusal::HostRefused(why)),
|
||||
}
|
||||
}
|
||||
};
|
||||
let count = spans.len();
|
||||
// A span this device cannot bound is skipped rather than fatal: a machine
|
||||
// with one ordinary RAMBlock and one odd sliver should import the RAMBlock.
|
||||
// `GuestRamImport::new` names the check that rejected each skipped one on
|
||||
// the fail channel, so a partial import is never silent.
|
||||
let imports: Vec<Arc<GuestRamImport>> = spans
|
||||
.into_iter()
|
||||
.filter_map(|span| GuestRamImport::new(span, align).ok().map(Arc::new))
|
||||
.collect();
|
||||
let refusal = imports
|
||||
.is_empty()
|
||||
.then_some(MapRefusal::NoUsableRegion { spans: count });
|
||||
Resolved { imports, refusal }
|
||||
}
|
||||
|
||||
/// Emit `refusal` and hand it back.
|
||||
///
|
||||
/// Deduped by slug: these are per-reference and a decode path that names an
|
||||
/// unbacked address once will name it every frame.
|
||||
/// [`MapRefusal::NoBackendImport`] goes to the off channel — it is the host
|
||||
/// saying what it is, not a loss of guest work — and everything else to the
|
||||
/// fail channel.
|
||||
fn report_once(refusal: MapRefusal) -> MapRefusal {
|
||||
let line = crate::observe::Emit::decline(EVENT, &refusal);
|
||||
match refusal {
|
||||
MapRefusal::NoBackendImport => {
|
||||
if crate::observe::first_sight("guest_ram_map_no_backend_import", 0) {
|
||||
line.off();
|
||||
}
|
||||
}
|
||||
_ => line.fail_once(0),
|
||||
}
|
||||
refusal
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::runtime::guest_ram::{forget_granularity, latch_granularity, GuestRamRegion};
|
||||
|
||||
/// The whole module is process-global, and so is the granularity latch.
|
||||
/// Every test here takes this and restores both.
|
||||
static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
struct Spans(Vec<GuestRamRegion>);
|
||||
|
||||
impl HostOps for Spans {
|
||||
fn mono_ns(&self) -> u64 {
|
||||
0
|
||||
}
|
||||
fn enqueue(&mut self, _action: crate::runtime::host::HostAction) {}
|
||||
fn schedule_bh(&mut self) {}
|
||||
fn guest_ram_regions(&mut self) -> Result<Vec<GuestRamRegion>, GuestRamRegionsError> {
|
||||
Ok(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
struct Refusing;
|
||||
|
||||
impl HostOps for Refusing {
|
||||
fn mono_ns(&self) -> u64 {
|
||||
0
|
||||
}
|
||||
fn enqueue(&mut self, _action: crate::runtime::host::HostAction) {}
|
||||
fn schedule_bh(&mut self) {}
|
||||
fn guest_ram_regions(&mut self) -> Result<Vec<GuestRamRegion>, GuestRamRegionsError> {
|
||||
Err(GuestRamRegionsError::NoRam)
|
||||
}
|
||||
}
|
||||
|
||||
/// Two spans with a hole between them, which is the shape of an x86 machine
|
||||
/// with a PCI hole and the reason the lookup is a search rather than a
|
||||
/// single subtraction.
|
||||
fn two_spans() -> Spans {
|
||||
Spans(vec![
|
||||
GuestRamRegion {
|
||||
gpa_base: 0,
|
||||
host_va: 0x7f00_0000_0000,
|
||||
len: 0x8000_0000,
|
||||
},
|
||||
GuestRamRegion {
|
||||
gpa_base: 0x1_0000_0000,
|
||||
host_va: 0x7f80_0000_0000,
|
||||
len: 0x8000_0000,
|
||||
},
|
||||
])
|
||||
}
|
||||
|
||||
fn with_granularity<R>(align: Option<u64>, body: impl FnOnce() -> R) -> R {
|
||||
let _guard = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
reset();
|
||||
match align {
|
||||
Some(a) => latch_granularity(a),
|
||||
None => forget_granularity(),
|
||||
}
|
||||
let out = body();
|
||||
reset();
|
||||
forget_granularity();
|
||||
out
|
||||
}
|
||||
|
||||
/// An address in either span resolves, and the offset it resolves to is the
|
||||
/// one inside *that* span — not a distance from the first one. Getting this
|
||||
/// wrong on a machine with a PCI hole binds the GPU 4 GiB away from the
|
||||
/// bytes the guest named, inside a live import, where no bound would catch
|
||||
/// it.
|
||||
#[test]
|
||||
fn an_address_resolves_against_the_span_that_backs_it() {
|
||||
with_granularity(Some(0x1000), || {
|
||||
let mut host = two_spans();
|
||||
let low = reference(&mut host, 0x2000, 0x100).expect("in the first span");
|
||||
assert_eq!(low.bound().expect("checked").offset, 0x2000);
|
||||
|
||||
let high = reference(&mut host, 0x1_0000_2000, 0x100).expect("in the second span");
|
||||
assert_eq!(
|
||||
high.bound().expect("checked").offset,
|
||||
0x2000,
|
||||
"the offset is into the second import, not from the first span's base"
|
||||
);
|
||||
assert_ne!(low.import().id(), high.import().id());
|
||||
});
|
||||
}
|
||||
|
||||
/// The imports are built once. The shim's answer does not change, and
|
||||
/// re-asking would be an address-space walk per guest reference.
|
||||
#[test]
|
||||
fn the_host_is_asked_once_however_many_references_follow() {
|
||||
with_granularity(Some(0x1000), || {
|
||||
struct Counting(std::cell::Cell<usize>);
|
||||
impl HostOps for Counting {
|
||||
fn mono_ns(&self) -> u64 {
|
||||
0
|
||||
}
|
||||
fn enqueue(&mut self, _a: crate::runtime::host::HostAction) {}
|
||||
fn schedule_bh(&mut self) {}
|
||||
fn guest_ram_regions(
|
||||
&mut self,
|
||||
) -> Result<Vec<GuestRamRegion>, GuestRamRegionsError> {
|
||||
self.0.set(self.0.get() + 1);
|
||||
Ok(vec![GuestRamRegion {
|
||||
gpa_base: 0,
|
||||
host_va: 0x7f00_0000_0000,
|
||||
len: 0x8000,
|
||||
}])
|
||||
}
|
||||
}
|
||||
let mut host = Counting(std::cell::Cell::new(0));
|
||||
for _ in 0..5 {
|
||||
reference(&mut host, 0x1000, 8).expect("inside");
|
||||
}
|
||||
assert_eq!(host.0.get(), 1);
|
||||
assert_eq!(imports().len(), 1);
|
||||
});
|
||||
}
|
||||
|
||||
/// A host with no import capability refuses every reference by name, and
|
||||
/// never asks the shim at all. This is the ordinary state on a host without
|
||||
/// the extension, so it must not read as a failure of the guest's work.
|
||||
#[test]
|
||||
fn without_a_published_granularity_nothing_is_asked_and_nothing_resolves() {
|
||||
with_granularity(None, || {
|
||||
let mut host = two_spans();
|
||||
assert_eq!(
|
||||
reference(&mut host, 0x2000, 8).err(),
|
||||
Some(MapRefusal::NoBackendImport)
|
||||
);
|
||||
assert!(imports().is_empty());
|
||||
});
|
||||
}
|
||||
|
||||
/// The shim's own refusal is carried through with its name, rather than
|
||||
/// collapsing into "no imports". "This machine has no RAM span" and "this
|
||||
/// build's shim is too old" are different things to go fix.
|
||||
#[test]
|
||||
fn the_hosts_own_refusal_keeps_its_name() {
|
||||
with_granularity(Some(0x1000), || {
|
||||
assert_eq!(
|
||||
reference(&mut Refusing, 0x2000, 8).err(),
|
||||
Some(MapRefusal::HostRefused(GuestRamRegionsError::NoRam))
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// An address in the hole between two spans is refused by name. It is not a
|
||||
/// bound violation — no import claims it — and reporting it as one would
|
||||
/// send a reader looking for arithmetic that is not there.
|
||||
#[test]
|
||||
fn an_address_no_span_backs_is_refused_by_name() {
|
||||
with_granularity(Some(0x1000), || {
|
||||
let mut host = two_spans();
|
||||
let hole = 0x8000_0000;
|
||||
assert_eq!(
|
||||
reference(&mut host, hole, 8).err(),
|
||||
Some(MapRefusal::GpaNotInAnyImport { gpa: hole })
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// A length that leaves the span it started in is refused by the bound, with
|
||||
/// the bound's own reason. The next span's bytes are elsewhere in host
|
||||
/// memory, so running off the end of one import is exactly the stray this
|
||||
/// device is bounded against.
|
||||
#[test]
|
||||
fn a_length_that_runs_off_the_end_of_a_span_is_refused_by_the_bound() {
|
||||
with_granularity(Some(0x1000), || {
|
||||
let mut host = two_spans();
|
||||
let last_page = 0x8000_0000 - 0x1000;
|
||||
assert!(reference(&mut host, last_page, 0x1000).is_ok());
|
||||
assert!(matches!(
|
||||
reference(&mut host, last_page, 0x2000),
|
||||
Err(MapRefusal::OutsideImport(
|
||||
GuestRamError::SliceEndPastImport { .. }
|
||||
))
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
/// A span nothing can bound is skipped, and the ones that can be are still
|
||||
/// imported. Failing the whole map on one odd sliver would put a machine
|
||||
/// with an ordinary RAMBlock beside it on the copying rails for no reason.
|
||||
#[test]
|
||||
fn one_unusable_span_does_not_cost_the_usable_ones() {
|
||||
with_granularity(Some(0x1000), || {
|
||||
let mut host = Spans(vec![
|
||||
// Shorter than one granule: nothing to import.
|
||||
GuestRamRegion {
|
||||
gpa_base: 0,
|
||||
host_va: 0x7f00_0000_0000,
|
||||
len: 0x400,
|
||||
},
|
||||
GuestRamRegion {
|
||||
gpa_base: 0x1_0000_0000,
|
||||
host_va: 0x7f80_0000_0000,
|
||||
len: 0x8000,
|
||||
},
|
||||
]);
|
||||
assert!(reference(&mut host, 0x1_0000_0000, 8).is_ok());
|
||||
assert_eq!(imports().len(), 1);
|
||||
});
|
||||
}
|
||||
|
||||
/// Every span unusable is its own refusal, distinct from the host refusing:
|
||||
/// the host answered fine and our own bound rejected all of it.
|
||||
#[test]
|
||||
fn every_span_unusable_is_a_refusal_of_its_own() {
|
||||
with_granularity(Some(0x1000), || {
|
||||
let mut host = Spans(vec![GuestRamRegion {
|
||||
gpa_base: 0,
|
||||
host_va: 0x7f00_0000_0000,
|
||||
len: 0x400,
|
||||
}]);
|
||||
assert_eq!(
|
||||
reference(&mut host, 0, 8).err(),
|
||||
Some(MapRefusal::NoUsableRegion { spans: 1 })
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
/// A device recreate drops the imports, and the rebuilt ones carry new
|
||||
/// identities. A reference taken before the teardown must not resolve
|
||||
/// against the replacement, because the backend handle it named is gone.
|
||||
#[test]
|
||||
fn a_reset_rebuilds_against_fresh_identities() {
|
||||
with_granularity(Some(0x1000), || {
|
||||
let mut host = two_spans();
|
||||
let before = reference(&mut host, 0x2000, 8).expect("inside");
|
||||
reset();
|
||||
let after = reference(&mut host, 0x2000, 8).expect("inside");
|
||||
assert_ne!(before.import().id(), after.import().id());
|
||||
assert!(matches!(
|
||||
after.import().resolve(&before.import().slice(0, 8).unwrap()),
|
||||
Err(GuestRamError::SliceForeignImport { .. })
|
||||
));
|
||||
});
|
||||
}
|
||||
|
||||
/// The refusals reach the always-on log, and the expected one does not
|
||||
/// reach the fail channel.
|
||||
#[test]
|
||||
fn refusals_are_visible_and_the_expected_one_is_not_a_failure() {
|
||||
with_granularity(Some(0x1000), || {
|
||||
let capture = crate::observe::FailCapture::start();
|
||||
let mut host = two_spans();
|
||||
let _ = reference(&mut host, 0x8000_0000, 8);
|
||||
let line = capture.one(EVENT);
|
||||
assert!(
|
||||
line.contains("reason=guest_ram_map_gpa_not_in_any_import"),
|
||||
"{line}"
|
||||
);
|
||||
assert!(line.contains("gpa=0x80000000"), "{line}");
|
||||
assert!(!line.starts_with("OFF "), "a lost reference is a failure");
|
||||
});
|
||||
with_granularity(None, || {
|
||||
let capture = crate::observe::FailCapture::start();
|
||||
let mut host = two_spans();
|
||||
let _ = reference(&mut host, 0x2000, 8);
|
||||
// Not `capture.one(EVENT)`: an off-channel line's first token is
|
||||
// the literal `OFF`, which is the same thing the fail-log reading
|
||||
// notes in `AGENTS.md` warn about when ranking `reason=`.
|
||||
let lines = capture.lines();
|
||||
assert_eq!(
|
||||
lines,
|
||||
vec!["OFF guest_ram_map reason=guest_ram_map_no_backend_import"],
|
||||
"a host without the extension has not lost guest work"
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -664,10 +664,11 @@ pub enum GpuWritebackDecline {
|
||||
/// The page walk refused: these are no longer provably the mapping's pages.
|
||||
/// The copying rail refuses for the same reason and reports it.
|
||||
PagesNotOurs,
|
||||
/// This host cannot export the window as a dma-buf. Latched and reported by
|
||||
/// [`crate::runtime::guest_dmabuf`], which knows whether the reason is the
|
||||
/// host or this window.
|
||||
NoDmaBuf,
|
||||
/// This host cannot reach the window's bytes as a GPU import. Either no
|
||||
/// backend published an import granularity, or
|
||||
/// [`crate::runtime::guest_ram_map`] refused these pages — and it names
|
||||
/// which, so this variant does not restate a reason it does not know.
|
||||
NoGuestImport,
|
||||
/// The engine declined or the copy failed; the inner error names which.
|
||||
Engine {
|
||||
inner: crate::backend::vulkan::engine::DrawError,
|
||||
@@ -687,8 +688,8 @@ impl crate::observe::Decline for GpuWritebackDecline {
|
||||
Self::PageListShort { .. } => "gpuwb_page_list_short",
|
||||
Self::PageUnbacked { .. } => "gpuwb_page_unbacked",
|
||||
Self::PagesNotOurs => "gpuwb_pages_not_ours",
|
||||
Self::NoDmaBuf => "gpuwb_no_dmabuf",
|
||||
// The engine's own slug, so a driver that refuses the fd and a
|
||||
Self::NoGuestImport => "gpuwb_no_guest_import",
|
||||
// The engine's own slug, so a driver that refuses the pointer and a
|
||||
// resident in the wrong channel order stay as distinguishable here
|
||||
// as they are where they were decided.
|
||||
Self::Engine { inner } => crate::observe::Decline::slug(inner),
|
||||
@@ -697,7 +698,7 @@ impl crate::observe::Decline for GpuWritebackDecline {
|
||||
|
||||
fn fields(&self) -> Vec<(&'static str, String)> {
|
||||
match self {
|
||||
Self::NotWritable | Self::PagesNotOurs | Self::NoDmaBuf => Vec::new(),
|
||||
Self::NotWritable | Self::PagesNotOurs | Self::NoGuestImport => Vec::new(),
|
||||
Self::GeometryMoved {
|
||||
latched_width,
|
||||
latched_height,
|
||||
@@ -889,17 +890,17 @@ pub fn write_bgra8_from_resident_gpu<M: HostMemory + HostOps>(
|
||||
// whatever it left behind.
|
||||
crate::runtime::storage_flush::flush_intersecting(state, host, mapping_id, base_off, span_end);
|
||||
// Nothing below can land a frame on a host whose GPU cannot import guest
|
||||
// pages, so the walks below are skipped rather than run and discarded. Asked
|
||||
// RAM, so the walks below are skipped rather than run and discarded. Asked
|
||||
// *after* `flush_intersecting` and not before it: that call is a side effect
|
||||
// this rail owes whether or not it goes on to write anything, and the
|
||||
// copying arm that takes over from this decline expects the state it leaves.
|
||||
//
|
||||
// Not a second gate — `guest_dmabuf::dmabuf_for` still decides, and would
|
||||
// decline these same pages a few hundred microseconds later. This only
|
||||
// declines sooner, and on the pathways where the answer never changes that
|
||||
// is a page-table walk per flush for the life of the process.
|
||||
if !crate::runtime::guest_dmabuf::export_available() {
|
||||
return Err(GpuWritebackDecline::NoDmaBuf);
|
||||
// Not a second gate — `guest_ram_map::reference_for_pages` still decides,
|
||||
// and would decline these same pages a few hundred microseconds later. This
|
||||
// only declines sooner, and on the pathways where the answer never changes
|
||||
// that is a page-table walk per flush for the life of the process.
|
||||
if crate::runtime::guest_ram::granularity().is_none() {
|
||||
return Err(GpuWritebackDecline::NoGuestImport);
|
||||
}
|
||||
// Timed on its own because it is the largest `O(pages)` step left and its
|
||||
// fix is not the other one's. `vouch_for_write` re-walks every page of the
|
||||
@@ -935,14 +936,23 @@ pub fn write_bgra8_from_resident_gpu<M: HostMemory + HostOps>(
|
||||
};
|
||||
gpas.push(gpa);
|
||||
}
|
||||
let Some(window) = crate::runtime::guest_dmabuf::dmabuf_for(host, &gpas, page_size as u32)
|
||||
else {
|
||||
return Err(GpuWritebackDecline::NoDmaBuf);
|
||||
// The extent this copy names, and nothing past it. Padding after the final
|
||||
// row belongs to the surface's plane but is not texels this call was given,
|
||||
// and the copying rail does not write it either — a request that included
|
||||
// it would let the two rails land different guest memory for one frame.
|
||||
let pitch = u64::from(plan.row_length_texels.max(mw)) * 4;
|
||||
let extent = u64::from(mh.saturating_sub(1)) * pitch + u64::from(mw) * 4;
|
||||
let Ok(guest) = crate::runtime::guest_ram_map::reference_for_pages(
|
||||
host,
|
||||
&gpas,
|
||||
page_size,
|
||||
plan.in_page,
|
||||
extent,
|
||||
) else {
|
||||
return Err(GpuWritebackDecline::NoGuestImport);
|
||||
};
|
||||
let target = crate::backend::vulkan::engine::GuestPageTarget {
|
||||
window,
|
||||
mapped_bytes: gpas.len() as u64 * page_size,
|
||||
offset: plan.in_page,
|
||||
guest,
|
||||
row_length_texels: plan.row_length_texels,
|
||||
width: mw,
|
||||
height: mh,
|
||||
|
||||
@@ -38,17 +38,12 @@ pub mod fence_exec;
|
||||
pub mod gather_witness;
|
||||
/// Guest-physical control-plane writes via HostOps map_pages.
|
||||
pub mod gpa_map;
|
||||
/// The dma-buf over a guest page window — see the module doc for what bounds it.
|
||||
///
|
||||
/// Vulkan-only, and not merely because of where the code sits: a dma-buf is a
|
||||
/// Linux kernel object with no Metal importer, and every type this cache holds
|
||||
/// belongs to the Vulkan engine. A build without that backend has nothing to
|
||||
/// export to.
|
||||
#[cfg(feature = "backend-vulkan")]
|
||||
pub mod guest_dmabuf;
|
||||
/// The bound on every GPU reference to guest RAM — one import per RAMBlock,
|
||||
/// and the only type that can name a byte inside one.
|
||||
pub mod guest_ram;
|
||||
/// This process's imports of guest RAM, and the one place a guest physical
|
||||
/// address becomes a bindable reference.
|
||||
pub mod guest_ram_map;
|
||||
/// Task GVA → guest RAM reads.
|
||||
pub mod gva_mem;
|
||||
/// Task-GVA HostOps views (MapMemory2 / UnmapMemory lifecycle).
|
||||
|
||||
Reference in new issue
Block a user