One page, one import: a buffer over a live import's pages lies inside it, else a copy

VK_EXT_external_memory_host leaves a host allocation imported twice into one device
undefined (issue 6: "Some platforms do not allow locking the same physical pages for device
access multiple times, so attempting to do it may result in undefined behavior"). The runtime
imported the same pages twice in several ways: a heap's own import was never noted in
HostAliases, so a no-copy buffer over exactly a heap's bytes, or over part of them, imported
them again (the consumer's guest heaps over 2 MiB page-block views, and the block's view as a
buffer); a buffer over part of a live buffer's bytes imported its own (counted,
object_churn.imports_inside_live: 34 in one 3090 walk); and a heap over a live buffer's bytes
imported its own.

Now:
- a heap's own import is noted (HostAliases::hold), joining no key;
- a buffer or heap over exactly a live import's bytes lies in that import (a heap keeps its
  heap identity);
- a buffer whose window a live import holds all of is bound inside that import's memory at
  its offset, with a VkBuffer of its own and no import (Device::bind_in_import,
  Placement::in_import, which holds the import; the import is exposed, so never released
  while idle); counted object_churn.buffers_bound_in_import;
- a buffer or heap whose window a live import holds some of and not all, and a heap a live
  import holds more than, is a copy (CopiedBecause::OverImport, copied_over_live_imports,
  announced copied-host-pages);
- rebinds take the same rule;
- imports_inside_live now counts only imports made where a live one held some of the pages
  all the same (two buffers made at once).

Tests: host_aliases unit test a_page_a_live_import_holds_is_never_imported_again; device
tests one_import (heap first, buffer first). Not yet run: this commit is for the build.
This commit is contained in:
Anees Iqbal committed 2026-11-11 19:01:50 -08:00
1 parent 269d7066c4
commit cfd7bc829e
10 files changed
+812 -78

No files matched your search

+5 -6
View File
@@ -3258,19 +3258,18 @@ impl Device {
}
/// A no-copy buffer of `length` bytes lying in `import`, the import of the same bytes a live
/// no-copy buffer lies in (`host_aliases.rs`), at `address`, released to `release` once
/// nothing holds it. Dropping the result releases every part but the import, which the last
/// buffer over it releases.
/// no-copy buffer or heap lies in (`host_aliases.rs`), at `address`, released to `release`
/// once nothing holds it: a heap's own buffer where `of_heap`, of a heap's identity. Dropping
/// the result releases every part but the import, which the last buffer over it releases.
pub(super) fn buffer_in_import(
&self,
import: Arc<HostImport>,
length: u64,
modes: Modes,
(length, modes, of_heap): (u64, Modes, bool),
(address, reserved): (GpuAddress, Held),
release: Option<Release>,
naming: Naming,
) -> Buffer {
let identity = naming.identity(modes.hazard, false);
let identity = naming.identity(modes.hazard, of_heap);
let own = OwnBytes {
lie: self.host_lie(identity.key, import, release, false),
reserved,
@@ -10,18 +10,19 @@ use super::address::{
AddressPlacement, AddressRange, GpuAddress, Held, Place, PlacementConflict, RangeToken,
};
use super::address_pool::AddressPool;
#[cfg(unix)]
use super::buffer::Pages;
use super::buffer::{
usage, Buffer, BufferParts, HostCell, HostPages, Lying, Modes, Naming, Owner, ReadApart,
usage, Buffer, BufferParts, HostCell, HostImport, HostPages, Lying, Modes, Naming, Owner,
ReadApart,
};
#[cfg(unix)]
use super::buffer::{ImportPages, Pages};
use super::copied::NotCopied;
use super::device::lock;
use super::dirty_pages::{DirtySource, PagesLog};
use super::error::MemoryKind;
use super::error::{internal, invalid, nil, vulkan, Error, Problem, RuntimeGap};
use super::heap::{Heap, HeapProblem};
use super::host_aliases::Kind;
use super::host_aliases::{Kind, Within};
use super::host_bytes::HostBytes;
use super::host_memory::{
based_size, binds_in, buffer_base, import_refused, import_window, not_importable,
@@ -31,7 +32,7 @@ use super::host_memory::{
use super::host_ram::{RamOnDevice, Routed};
#[cfg(unix)]
use super::host_residency::Again;
use super::memory::{ImportFailure, MemoryClass, Placement};
use super::memory::{BoundMemory, ImportFailure, Mapped, MemoryClass, Placement};
use super::read_only_view::ReadOnlyView;
use super::rebind::RebindProblem;
use super::texture::stand_in::TextureImages;
@@ -815,26 +816,25 @@ impl Device {
// in its import, and a buffer of either class in its copy where it is a copied host
// buffer and no import of the class lives (`host_aliases.rs`, `copied.rs`): one
// `VkBuffer`, one snapshot and one key, its dma-buf source dropped uncalled and the gate
// unasked, as no page is mapped for it. A heap's own buffer imports or copies its own, as
// does one whose GPU writes are dropped (its import is a read-only view of the pages, or
// its copy drops them).
// unasked, as no page is mapped for it. A heap's own buffer lies so in a live import of
// the same bytes, joining no key (`host_aliases.rs`, "One page, one import"), and copies
// its own; one whose GPU writes are dropped imports or copies its own (its import is a
// read-only view of the pages, or its copy drops them).
let made_over = (pointer.as_ptr() as u64, length);
// A two-copy buffer's host copy lies in no copy of the pages (`managed_copy.rs`).
let shares = (!of_heap && !drops_writes)
let shares = (!drops_writes)
.then(|| shared.aliases.import(made_over, class))
.flatten()
.filter(|import| !(matches!(naming, Naming::HostCopy) && import.copied()));
if shares.is_none() && !of_heap && shared.aliases.inside_live(made_over, class) {
shared.counts.churn.import_inside_live();
}
.filter(|import| !(matches!(naming, Naming::HostCopy) && import.copied()))
.filter(|import| !(of_heap && import.copied()));
if let Some(import) = shares {
let address = self.place_window(placement, &window, length)?;
let kind = match import.copied() {
true => Kind::Copy,
false => Kind::Import(class),
};
let buffer =
self.buffer_in_import(Arc::clone(&import), length, modes, address, release, naming);
let made = (length, modes, of_heap);
let buffer = self.buffer_in_import(Arc::clone(&import), made, address, release, naming);
let key = buffer.identity().key;
// The GPU's writes through it are reported to the import's logs, as through the
// buffer it was made for, over the same bytes (`dirty_pages.rs`), and merged back
@@ -851,7 +851,11 @@ impl Device {
shared.counts.copied_host_buffer_shared();
self.degrade_copied_shared(call, pointer, length, import.copy_drops_writes());
}
shared.aliases.join(key, made_over, kind, &import);
if of_heap {
shared.aliases.hold(key, made_over, kind, &import);
} else {
shared.aliases.join(key, made_over, kind, &import);
}
shared.aliases.place(key, made_over);
return Ok(buffer);
}
@@ -893,11 +897,29 @@ impl Device {
kept_runs.as_ref(),
window.offset,
);
let (buffer, memory, again) = match in_chunk {
// One page, one import (`host_aliases.rs`): a buffer (not a heap's own) whose pages a
// live import of another buffer's or heap's holds all of is bound inside that import's
// memory, with no import of its own, no pin and no gate; pages a live import holds some
// of, and not all, and a heap's pages one holds more of, are a copy below, never imported
// again. A buffer whose GPU writes are dropped imports a read-only view of its own.
let within = match (&in_chunk, drops_writes) {
(None, false) => (shared.aliases).within((window.start, window.size), importer.unit()),
_ => Within::Free,
};
let inside = match &within {
// SAFETY: the window's pages are the caller's at the addresses the import's pages
// were imported from, which hold all of them (`HostAliases::within`).
Within::Inside(import) if !of_heap => unsafe {
self.bind_in_import(import, &window, length)
},
_ => None,
};
let over_import = inside.is_none() && !matches!(within, Within::Free);
let (buffer, memory, again) = match (in_chunk, inside) {
// A buffer (not a heap) bound in an import of its own run alone, its chunk not
// imported yet, is released while idle and bound in the chunk's import at its next
// use where that is made by then (`host_residency.rs`).
Some((buffer, memory)) => {
(Some((buffer, memory)), _) => {
#[cfg(unix)]
let again = (routed.as_ref().filter(|_| !of_heap))
.and_then(|routed| routed.run_again(&memory))
@@ -906,7 +928,9 @@ impl Device {
let again = None;
(buffer, memory, again)
}
None => {
// Bound inside a live import, which is never released while it lies there.
(None, Some((buffer, memory))) => (buffer, memory, None),
(None, None) => {
if let Some(refusal) = no_route {
return Err(refusal);
}
@@ -934,6 +958,14 @@ impl Device {
buffer
});
}
// Pages a live import holds some of: a copy, the gate unasked and no page pinned.
if over_import {
// SAFETY: the caller's contract.
let copied = unsafe {
self.copied_buffer(copy, release, dirty, CopiedFor::OverImport, naming)
};
return copied.map(|buffer| noted(kept(buffer, log, kept_runs, made_of)));
}
let refused_by_host = copyable
&& host.by_pointer
&& gate.as_ref().is_some_and(|gate| {
@@ -1022,7 +1054,16 @@ impl Device {
}
};
let (buffer, memory, again) = match imported {
Ok(imported) => imported,
Ok(imported) => {
// A page imported twice all the same: another buffer over them, made at
// once, was noted after this one looked.
let unit = importer.unit();
let found = (shared.aliases).within((window.start, window.size), unit);
if !matches!(found, Within::Free) {
shared.counts.churn.import_inside_live();
}
imported
}
// An import the device and the gate admitted that then failed, or pages the
// runtime refused for the driver that no dma-buf of them served: a copy,
// announced with the failure.
@@ -1093,14 +1134,16 @@ impl Device {
keep_in(pages, &buffer, log, kept_runs, made_of);
}
// A buffer over the bytes another no-copy buffer covers joins it (`host_aliases.rs`), and
// a later one lies in its import; one whose GPU writes are dropped joins none.
if let (false, false, Some(current)) = (of_heap, drops_writes, current) {
(shared.aliases).join(
buffer.identity().key,
made_over,
Kind::Import(class),
current.import(),
);
// a later one lies in its import, or inside it over part of them; a heap's own import is
// noted so, joining no key; one whose GPU writes are dropped joins none.
if let (false, Some(current)) = (drops_writes, current) {
let (key, kind) = (buffer.identity().key, Kind::Import(class));
match of_heap {
true => (shared.aliases).hold(key, made_over, kind, current.import()),
false => {
(shared.aliases).join(key, made_over, kind, current.import());
}
}
}
// Its uses order against every other key's over bytes they meet, a heap's own buffer's
// too (`host_aliases.rs`).
@@ -1271,6 +1314,24 @@ impl Device {
let in_chunk = (routed.as_ref().filter(|_| !moved && !drops_writes)).and_then(
|routed| unsafe { self.bind_in_chunk(importer, routed, &window, length) },
);
// One page, one import (`host_aliases.rs`), as at a buffer's making: new pages a
// live import holds all of are bound inside it (a buffer's, not a heap's own),
// and pages one holds some of, or a heap's it holds all of, are a copy, the gate
// unasked.
let within = match (&in_chunk, moved || drops_writes) {
(None, false) => (shared.aliases).within((window.start, window.size), unit),
_ => Within::Free,
};
let inside = match &within {
// SAFETY: the window's pages are the caller's at the addresses the import's
// pages were imported from, which hold all of them.
Within::Inside(import) if heap.is_none() => unsafe {
self.bind_in_import(import, &window, length)
},
_ => None,
};
let over_import = inside.is_none() && !matches!(within, Within::Free);
let in_chunk = in_chunk.or(inside);
let chunk_bound = in_chunk.is_some();
let kept_runs = routed.as_ref().map(Routed::kept);
// Whether an import alive now holds every page of them: counted once the import
@@ -1285,7 +1346,12 @@ impl Device {
// process cannot write); or where the import it admitted fails, of the pointer or
// of the caller's dma-bufs. Bytes moved in their page are a copy, the gate unasked.
let gate = gate.filter(|_| {
copyable && !read_only_copy && host.by_pointer && !moved && !chunk_bound
copyable
&& !read_only_copy
&& host.by_pointer
&& !moved
&& !chunk_bound
&& !over_import
});
let refused_by_host = match gate {
Some(gate) => {
@@ -1310,7 +1376,8 @@ impl Device {
// Only pages imported here are pinned, and so have their writability asked; pages
// the process cannot write are a copy whose GPU writes are dropped
// ([`unwritable_pages`]).
let imports = !chunk_bound && !refused_by_host && !moved && !read_only_copy;
let imports =
!chunk_bound && !refused_by_host && !moved && !read_only_copy && !over_import;
let unwritable = imports && unwritable_pages(&host, writable, &shared.counts)?;
let imports = imports && !unwritable;
// The heap's images bound to its bytes, and the images in place over the bytes,
@@ -1455,6 +1522,7 @@ impl Device {
(false, Some(_)) => CopiedBecause::Failed,
(false, None) if read_only_copy => CopiedBecause::ReadOnly,
(false, None) if unwritable => CopiedBecause::Unwritable,
(false, None) if over_import => CopiedBecause::OverImport,
(false, None) => CopiedBecause::Refused,
};
let (host, placement, copied) = copy(failed.as_ref())?;
@@ -1710,6 +1778,86 @@ impl Device {
}
}
/// The `VkBuffer` of a no-copy buffer of `length` bytes over `window`, whose pages all lie
/// inside those of `import`, a live import of the caller's pages (`host_aliases.rs`, "One
/// page, one import"), bound inside that import's memory where they lie, and its placement,
/// which holds the import: no import of its own, no pin and no gate. The import is kept
/// imported for good from now on (another buffer lies in its memory, `host_residency.rs`).
/// `None` where the buffer cannot be bound there exactly (its alignment, its memory types,
/// the imports of a buffer's own dma-bufs, whose memory is that buffer's alone, or the device
/// lost): the pages are then a copy, never a second import.
///
/// # Safety
///
/// The window's pages are host memory of this process at the host addresses `import`'s pages
/// were imported from, which hold all of them.
pub(super) unsafe fn bind_in_import(
&self,
import: &Arc<HostImport>,
window: &ImportWindow,
length: u64,
) -> Option<(HostBuffer, Placement)> {
let shared = self.shared();
let raw_device = shared.vk();
let pages = import.pages(ReadApart::SecondBuffer);
#[cfg(unix)]
if matches!(pages, ImportPages::StandIn(_)) {
return None;
}
let within = &pages.memory.placement;
// One dma-buf a buffer's own import made is dedicated to its `VkBuffer`
// (`VUID-vkBindBufferMemory-memory-01508`); a guest RAM chunk's import of one is not.
let dedicated = within.over_dma_buf() && !within.over_ram_chunk();
let mapped = within.mapped.map(|mapped| mapped.as_ptr() as u64);
let (false, false, Some(mapped)) =
(dedicated, within.memory == vk::DeviceMemory::null(), mapped)
else {
return None;
};
let handle = match lock(&shared.memory).bound_memory(within) {
BoundMemory::External(handle) => handle,
_ => return None,
};
// Where the window starts in the import's placement.
let into = window.start.checked_sub(mapped)?;
if into.checked_add(window.size)? > within.size() {
return None;
}
let buffer = self.host_buffer(window, length, handle).ok()?;
let requirements = buffer.requirements;
let bound_at = binds_in(window, buffer.base, buffer.size, &requirements)
.ok()
.map(|at| within.offset + into + at)
.filter(|at| at.is_multiple_of(requirements.alignment.max(1)))
.filter(|_| requirements.memory_type_bits & (1 << within.type_index()) != 0);
let start = NonNull::new(window.start as *mut u8);
let (Some(bound_at), Some(start)) = (bound_at, start) else {
// SAFETY: the buffer is unused.
unsafe { release::object(raw_device, buffer.raw) };
return None;
};
// SAFETY: the buffer is unbound and made for the import's handle type, and the import's
// memory holds its size and requirements from `bound_at` (`binds_in` against the window,
// which lies in the import's placement).
let bound = unsafe {
crate::creation::bind_buffer(raw_device, buffer.raw, within.memory, bound_at)
};
if bound.is_err() {
// SAFETY: the buffer is unused.
unsafe { release::object(raw_device, buffer.raw) };
return None;
}
let placement = Placement::in_import(
Arc::clone(import),
(within, handle),
within.offset + into,
window.size,
Mapped::of_caller(start),
);
shared.counts.churn.buffer_bound_in_import();
Some((buffer, placement))
}
/// The `VkBuffer` of a no-copy buffer of `length` bytes at `pointer`, made for host
/// allocations and bound in the import of the window's pages at their pointer
/// (`VK_EXT_external_memory_host`), or of a read-only view of them where `drops_writes`
@@ -1996,6 +2144,11 @@ impl Device {
"the process maps some of them read-only, which Linux drivers pin no pointer \
of, and whose dma-bufs would take the GPU's writes, which Metal drops"
}
CopiedBecause::OverImport => {
"a live import of another no-copy buffer's or heap's pages holds some of \
their pages and not all (or more than a heap's own bytes), and \
VK_EXT_external_memory_host leaves pages imported twice undefined"
}
};
let dropped = match (drops, cause) {
(true, CopiedBecause::ReadOnly | CopiedBecause::Unwritable) => {
@@ -2089,6 +2242,7 @@ impl Device {
CopiedFor::Failed(failed) => (CopiedBecause::Failed, Some(failed)),
CopiedFor::ReadOnly => (CopiedBecause::ReadOnly, None),
CopiedFor::Unwritable => (CopiedBecause::Unwritable, None),
CopiedFor::OverImport => (CopiedBecause::OverImport, None),
};
let shared = self.shared();
let raw_device = shared.vk();
@@ -2503,6 +2657,10 @@ enum CopiedFor {
/// The process cannot write every page ([`unwritable_pages`]): the copy drops the GPU's
/// writes, as Metal drops them.
Unwritable,
/// A live import of another buffer's or heap's pages holds some of them and not all, or more
/// than a heap's own bytes (`host_aliases.rs`, "One page, one import"): no page is imported
/// twice.
OverImport,
}
/// An import of a no-copy object's pages that the device and the gate admitted and that failed
@@ -165,8 +165,10 @@ pub(crate) struct ChurnCounters {
/// By [`Recycled`]: the objects a making took from a recycler, parked there, and let go of
/// past its bounds (`recycle.rs`).
recycled: [[AtomicU64; 3]; 2],
/// No-copy buffers that imported their pages where a live import holds them all.
/// No-copy buffers and heaps that imported their pages where a live import holds some.
imports_inside_live: AtomicU64,
/// No-copy buffers bound inside a live import's memory, with no import of their own.
buffers_bound_in_import: AtomicU64,
/// By [`KeepBy`], then cut or whole: the keeps, then their texels.
keeps: [[AtomicU64; 4]; 3],
}
@@ -177,11 +179,16 @@ impl ChurnCounters {
self.owned[owned as usize].fetch_add(1, Ordering::Relaxed);
}
/// A no-copy buffer imported its pages where a live import holds them all.
/// A no-copy buffer or heap imported its pages where a live import holds some of them.
pub(crate) fn import_inside_live(&self) {
self.imports_inside_live.fetch_add(1, Ordering::Relaxed);
}
/// A no-copy buffer was bound inside a live import's memory, with no import of its own.
pub(crate) fn buffer_bound_in_import(&self) {
self.buffers_bound_in_import.fetch_add(1, Ordering::Relaxed);
}
/// A making took a parked object of `what`.
pub(crate) fn taken(&self, what: Recycled) {
self.recycled[what as usize][0].fetch_add(1, Ordering::Relaxed);
@@ -243,6 +250,7 @@ impl ChurnCounters {
buffers_parked: recycled(Recycled::Buffer, 1),
buffers_evicted: recycled(Recycled::Buffer, 2),
imports_inside_live: self.imports_inside_live.load(Ordering::Relaxed),
buffers_bound_in_import: self.buffers_bound_in_import.load(Ordering::Relaxed),
release_sites: RELEASE_SITES.read(),
release_sites_dropped: RELEASE_SITES.dropped(),
},
@@ -324,9 +332,17 @@ pub struct ObjectChurn {
pub buffers_parked: u64,
/// Parked buffers destroyed past the recycler's bounds.
pub buffers_evicted: u64,
/// No-copy buffers that imported their pages where a live import of another no-copy buffer
/// held all of them (`host_aliases.rs`): imports a buffer could have lain in, at an offset.
/// No-copy buffers and heaps that imported their pages where a live import of another held
/// some of them all the same (`host_aliases.rs`, "One page, one import"): two made at once
/// over them, each looking before the other's import was noted. A page imported twice, which
/// `VK_EXT_external_memory_host` leaves undefined; every other buffer over pages a live
/// import holds lies inside it (`buffers_bound_in_import`) or is a copy
/// (`WorkCounts::copied_over_live_imports`).
pub imports_inside_live: u64,
/// No-copy buffers bound inside the memory of a live import that holds all their pages, at
/// their offset, with no import of their own (`host_aliases.rs`, "One page, one import"):
/// over part of another no-copy buffer's or heap's bytes.
pub buffers_bound_in_import: u64,
/// The places that released the images, buffers, buffer views and memory counted above, each
/// with its calls (`regions` unused): the first 32 the process met.
pub release_sites: [CopySite; COPY_SITES],
+105 -36
View File
@@ -9,7 +9,7 @@
//! the program orders them).
//!
//! - **One memory, one key.** A no-copy buffer made over exactly the bytes a live one covers
//! (the same first byte and length; not a heap's) joins it: the device notes the first such
//! (the same first byte and length; not a heap's own) joins it: the device notes the first such
//! buffer's key as the memory's ([`Alias`]), and each command's uses of a buffer that joined
//! carry a use of the memory's key too, of the same bytes and access ([`HostAliases::augment`],
//! `EncoderCore`). The tracker orders those as one resource's, inside an encoder, between
@@ -41,6 +41,22 @@
//! (`Device::rebind_host_pages`; a heap's own buffer, and bytes with a texture's aliasing image
//! over them, import their own), and in a live copy of them where its textures were planned at
//! the offset the copy lays the bytes at (its first byte) and no image in place rides on it.
//! - **One page, one import.** `VK_EXT_external_memory_host` leaves undefined a host allocation
//! imported twice into one device ("Some platforms do not allow locking the same physical pages
//! for device access multiple times, so attempting to do it may result in undefined behavior"),
//! so a page a live import holds is never imported again while it lives
//! ([`HostAliases::within`], looked up by the bytes the live buffers and heaps were made over,
//! rounded out to the import's unit). A heap's own import is noted as a buffer's is, joining no
//! key ([`HostAliases::hold`]): a buffer over exactly a heap's bytes lies in its import, and a
//! heap over exactly a live import's bytes lies in that import. A buffer whose pages a live
//! import holds all of is bound inside that import's memory at their offset, with a `VkBuffer`
//! of its own and no import (`Device::bind_in_import`, `WorkCounts::object_churn
//! .buffers_bound_in_import`), which keeps the import imported for good while it lives (no
//! residency release, `host_residency.rs`). A buffer or heap whose pages a live import holds
//! some of, and not all, and a heap whose pages a live import holds more of than its own bytes,
//! are a copy of the pages instead (`copied.rs`, `WorkCounts::copied_over_live_imports`).
//! `WorkCounts::object_churn.imports_inside_live` counts the imports made where one held some of
//! the pages all the same (two buffers made at once over them).
//! - **Ownership stays the buffer's.** The added uses are hazard tracking's alone: what a command
//! holds and lists (`EncoderCore::touch`, rebind holds, `used_resources`) is named by the
//! command's own uses, each buffer by its own key.
@@ -125,6 +141,17 @@ pub(super) enum Kind {
Copy,
}
/// What the live imports hold of the pages a new import would take ([`HostAliases::within`]).
pub(super) enum Within<I> {
/// No live import holds any of them: the new import is their only one.
Free,
/// A live import holds all of them: a buffer over them is bound inside its memory.
Inside(Arc<I>),
/// A live import holds some of them, none all: a buffer over them is a copy of them, so
/// that no page is imported twice.
Meets,
}
/// The device's no-copy buffers by the host memory they were made over (the module docs), and
/// the imports of it they lie in (`I`: a `HostImport`, but in unit tests).
pub(super) struct HostAliases<I = HostImport> {
@@ -340,8 +367,9 @@ struct Over {
/// A memory live buffers were made over.
struct Memory<I> {
/// The first such buffer's key: the memory's.
key: ResourceKey,
/// The first such buffer's key: the memory's. `None` while a heap's own buffer alone was
/// made over it ([`HostAliases::hold`]), which a later buffer lies in without joining.
key: Option<ResourceKey>,
/// How many live buffers were made over it.
buffers: usize,
/// Its imports a buffer made, by kind: a later buffer lies in one while it lives
@@ -366,28 +394,42 @@ impl<I> HostAliases<I> {
live(Kind::Import(class)).or_else(|| live(Kind::Copy))
}
/// Whether a live import of `class` was made over memory that holds all of `memory` and more
/// (`WorkCounts::object_churn.imports_inside_live`): a buffer over part of a live no-copy
/// buffer's bytes, which imports its own.
pub(super) fn inside_live(&self, memory: (u64, u64), class: MemoryClass) -> bool {
/// What the live imports noted hold of the pages `window` (the first byte's host address and
/// the length of whole import units, `unit` bytes each, a new import's window): an import of
/// any class, not a copy, whose bytes rounded out to `unit` hold them all, which a buffer over
/// them lies inside ([`Within::Inside`]); else whether one holds some of them
/// ([`Within::Meets`]), which a new import would pin a second time; else none
/// ([`Within::Free`]). One live import of a page at a time: `VK_EXT_external_memory_host`
/// leaves a host allocation imported twice into a device undefined ("Some platforms do not
/// allow locking the same physical pages for device access multiple times"), and the
/// runtime's imports by pointer and of dma-bufs are kept to one per page alike.
pub(super) fn within(&self, window: (u64, u64), unit: u64) -> Within<I> {
let inner = lock(&self.inner);
let end = memory.0.saturating_add(memory.1);
let found = inner
.memories
.overlapping(memory.0, end)
.filter(|&(start, length)| {
(start, length) != memory
&& start <= memory.0
&& end <= start.saturating_add(length)
})
.any(|at| {
inner.memories.get(at).is_some_and(|noted| {
(noted.imports.iter()).any(|(made, import)| {
*made == Kind::Import(class) && import.strong_count() > 0
})
})
});
found
let unit = unit.max(1);
let (start, end) = (window.0, window.0.saturating_add(window.1));
let mut meets = false;
for at in inner.memories.overlapping(start, end) {
let Some(import) = inner.memories.get(at).and_then(|noted| {
(noted.imports.iter())
.filter(|(made, _)| matches!(made, Kind::Import(_)))
.find_map(|(_, import)| import.upgrade())
}) else {
continue;
};
let from = at.0 - at.0 % unit;
let to =
at.0.saturating_add(at.1)
.div_ceil(unit)
.saturating_mul(unit);
if from <= start && end <= to {
return Within::Inside(import);
}
meets = true;
}
match meets {
true => Within::Meets,
false => Within::Free,
}
}
/// Note the buffer of `key`, made over `memory` (its first byte's host address and its
@@ -402,17 +444,48 @@ impl<I> HostAliases<I> {
import: &Arc<I>,
) -> Option<Alias> {
let mut inner = lock(&self.inner);
// A joining buffer's note always has a key: its own, where the memory had none.
let owner = self.note(&mut inner, key, memory, (kind, import), true)?;
if owner == key {
return None;
}
let alias = Alias { key: owner };
Arc::make_mut(&mut inner.aliases).insert(key, alias);
self.any.store(true, Ordering::Relaxed);
self.changed();
Some(alias)
}
/// Note a heap's own buffer of `key`, made over `memory` and lying in `import`, of `kind`, as
/// [`join`](Self::join) notes a buffer, but joining no key: a later buffer over the memory
/// lies in `import` ([`import`](Self::import)), and one over part of it inside it
/// ([`within`](Self::within)), each keeping its own key (a heap's bytes join none, "Not
/// joined" in the module docs); the first such buffer's key becomes the memory's.
pub(super) fn hold(&self, key: ResourceKey, memory: (u64, u64), kind: Kind, import: &Arc<I>) {
let mut inner = lock(&self.inner);
self.note(&mut inner, key, memory, (kind, import), false);
}
/// Note the buffer of `key` over `memory`, lying in `import` of its kind, its key the
/// memory's where it `joins` and the memory has none: the memory's key.
fn note(
&self,
inner: &mut Inner<I>,
key: ResourceKey,
memory: (u64, u64),
(kind, import): (Kind, &Arc<I>),
joins: bool,
) -> Option<ResourceKey> {
let Inner {
made_over,
memories,
aliases,
serial,
placements: _,
} = &mut *inner;
..
} = inner;
let noted = memories.get_or_insert_with(memory, || {
*serial += 1;
Memory {
key,
key: None,
buffers: 0,
imports: Vec::new(),
serial: *serial,
@@ -425,6 +498,9 @@ impl<I> HostAliases<I> {
if !noted.imports.iter().any(|(made, _)| *made == kind) {
noted.imports.push((kind, Arc::downgrade(import)));
}
if joins && noted.key.is_none() {
noted.key = Some(key);
}
let owner = noted.key;
let over = Over {
memory,
@@ -432,14 +508,7 @@ impl<I> HostAliases<I> {
};
made_over.insert(key, over);
self.noted.store(memories.len(), Ordering::Relaxed);
if owner == key {
return None;
}
let alias = Alias { key: owner };
Arc::make_mut(aliases).insert(key, alias);
self.any.store(true, Ordering::Relaxed);
self.changed();
Some(alias)
owner
}
/// The memory the buffer of `key` joined, if it joined one.
+65
View File
@@ -1822,6 +1822,26 @@ pub(super) struct Placement {
/// The device's import of a chunk of a guest RAM the placement lies in (`host_ram.rs`), which
/// no block of the placement's holds: kept until the placement goes.
ram_chunk: Option<Arc<RamChunk>>,
/// The live import of the caller's pages the placement lies inside (`host_aliases.rs`, "One
/// page, one import"), whose memory it is, which no block of the placement's holds: kept
/// until the placement goes.
in_import: Option<InImport>,
}
/// A placement's hold on the live import of host pages it lies inside ([`Placement::in_import`]),
/// and the external handle type that import's memory was imported as.
#[derive(Clone)]
pub(super) struct InImport {
_import: Arc<crate::buffer::HostImport>,
handle: vk::ExternalMemoryHandleTypeFlags,
}
impl std::fmt::Debug for InImport {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("InImport")
.field("handle", &self.handle)
.finish_non_exhaustive()
}
}
impl Placement {
@@ -1852,6 +1872,7 @@ impl Placement {
#[cfg(unix)]
dma_buf: None,
ram_chunk: None,
in_import: None,
}
}
@@ -1886,6 +1907,44 @@ impl Placement {
#[cfg(unix)]
dma_buf,
ram_chunk: Some(chunk),
in_import: None,
}
}
/// The placement of a no-copy buffer's `size` bytes of host pages that lie inside the pages of
/// `import`, a live import of them (`host_aliases.rs`, "One page, one import"), from `offset`
/// of the memory of `within`, that import's placement, which was imported as `handle`; the
/// caller reaches them at `mapped`. No block of the runtime's, so freeing it returns nothing;
/// it keeps the import until it goes, and lends its dma-bufs and guest RAM chunk where it
/// lies in those.
pub(super) fn in_import(
import: Arc<crate::buffer::HostImport>,
(within, handle): (&Placement, vk::ExternalMemoryHandleTypeFlags),
offset: u64,
size: u64,
mapped: Mapped,
) -> Placement {
Placement {
type_index: within.type_index,
holds: Holds::Buffers,
block: None,
size,
memory: within.memory,
offset,
mapped: Some(mapped),
address: None,
own_pages: false,
pooled_pages: false,
read_only_view: false,
overflowed: false,
fresh: false,
#[cfg(unix)]
dma_buf: within.dma_buf.clone(),
ram_chunk: within.ram_chunk.clone(),
in_import: Some(InImport {
_import: import,
handle,
}),
}
}
@@ -1919,6 +1978,7 @@ impl Placement {
fresh: false,
dma_buf: Some(pages),
ram_chunk: None,
in_import: None,
}
}
@@ -2048,6 +2108,7 @@ impl Placement {
#[cfg(unix)]
dma_buf: self.dma_buf.clone(),
ram_chunk: self.ram_chunk.clone(),
in_import: self.in_import.clone(),
}
}
}
@@ -3408,6 +3469,7 @@ impl Memory {
#[cfg(unix)]
dma_buf: None,
ram_chunk: None,
in_import: None,
}
}
@@ -3763,6 +3825,9 @@ impl Memory {
if let Some(chunk) = &placement.ram_chunk {
return BoundMemory::External(chunk.handle_type());
}
if let Some(inside) = &placement.in_import {
return BoundMemory::External(inside.handle);
}
let Some(index) = placement.block else {
return BoundMemory::NoImage(NoImage::Caller);
};
@@ -1,6 +1,6 @@
//! No-copy buffers over the same host memory (`host_aliases.rs`).
use super::super::host_aliases::{Alias, HostAliases, Kind, Memories, Quiet};
use super::super::host_aliases::{Alias, HostAliases, Kind, Memories, Quiet, Within};
use super::super::memory::MemoryClass;
use super::super::resource::ResourceKey;
use super::super::tracker::{Access, Use, UseRange};
@@ -161,7 +161,10 @@ fn a_buffer_over_the_bytes_a_copy_covers_lies_in_the_copy() {
assert!(aliases
.import((0x40000, 0x2000), MemoryClass::Shared)
.is_none());
assert!(!aliases.inside_live((0x40000, 0x2000), MemoryClass::Shared));
assert!(matches!(
aliases.within((0x40000, 0x2000), PAGE),
Within::Free
));
// A buffer that lies in it joins the memory's key.
assert_eq!(
aliases.join(second, memory, Kind::Copy, &copy),
@@ -188,6 +191,113 @@ fn a_buffer_over_the_bytes_a_copy_covers_lies_in_the_copy() {
/// The host page of the tests that name none of their own: an import's unit.
const PAGE: u64 = 0x1000;
/// The live import, if any, a new import of `window` would lie inside, else whether one meets it.
fn within(aliases: &Aliases, window: (u64, u64)) -> Option<Option<u32>> {
match aliases.within(window, PAGE) {
Within::Free => None,
Within::Inside(import) => Some(Some(*import)),
Within::Meets => Some(None),
}
}
/// One live import of a page (`VK_EXT_external_memory_host` leaves pages imported twice
/// undefined): a heap's own import is held, joining no key, and a later buffer over its exact
/// bytes lies in it and is the memory's key; pages a live import (a heap's or a buffer's) holds
/// all of lie inside it, at any offset, whatever its class; pages one holds some of meet it,
/// rounded out to the import's unit; a copy is no import, and imports that went hold nothing.
#[test]
fn a_page_a_live_import_holds_is_never_imported_again() {
let aliases = Aliases::default();
let heap_bytes = (0x100000, 0x200000);
let (heap, exact, inside, apart) = (
ResourceKey::new(),
ResourceKey::new(),
ResourceKey::new(),
ResourceKey::new(),
);
assert_eq!(within(&aliases, (0x100000, 0x1000)), None);
let heap_import = Arc::new(7);
aliases.hold(
heap,
heap_bytes,
Kind::Import(MemoryClass::Shared),
&heap_import,
);
// The heap's import is found for its exact bytes and inside them, its key joined by none.
assert!(Arc::ptr_eq(
&aliases.import(heap_bytes, MemoryClass::Shared).unwrap(),
&heap_import
));
assert_eq!(aliases.of(heap), None);
for window in [
heap_bytes,
(0x100000, 0x1000),
(0x2ff000, 0x1000),
(0x180000, 0x8000),
] {
assert_eq!(within(&aliases, window), Some(Some(7)), "{window:x?}");
}
// Across either edge, or around it whole: it meets, and no new import is made.
for window in [(0xff000, 0x2000), (0x2ff000, 0x2000), (0xf0000, 0x300000)] {
assert_eq!(within(&aliases, window), Some(None), "{window:x?}");
}
// Beside it: free.
assert_eq!(within(&aliases, (0x300000, 0x1000)), None);
assert_eq!(within(&aliases, (0xff000, 0x1000)), None);
// A buffer over its exact bytes lies in its import and becomes the memory's key; a second
// joins that key, not the heap's.
assert_eq!(
aliases.join(
exact,
heap_bytes,
Kind::Import(MemoryClass::Shared),
&heap_import
),
None
);
let second = ResourceKey::new();
assert_eq!(
aliases.join(
second,
heap_bytes,
Kind::Import(MemoryClass::Shared),
&heap_import
),
Some(Alias { key: exact })
);
// A buffer bound inside it, over bytes that miss the page's start, is an import of its own
// bytes too: a later buffer inside those lies inside either, never beside both.
let bound = Arc::new(8);
aliases.join(
inside,
(0x180010, 0x3000),
Kind::Import(MemoryClass::Managed),
&bound,
);
assert!(matches!(
within(&aliases, (0x181000, 0x1000)),
Some(Some(7 | 8))
));
// Across the bound buffer's edge but inside the heap's: inside the heap's.
assert_eq!(within(&aliases, (0x182000, 0x4000)), Some(Some(7)));
// A copy over other bytes is no import: free.
aliases.join(apart, (0x400000, 0x4000), Kind::Copy, &Arc::new(9));
assert_eq!(within(&aliases, (0x400000, 0x4000)), None);
// Every buffer over the heap's bytes gone, the bound one's still over its own: the heap's
// pages are free but those, which its import holds.
for key in [heap, exact, second] {
aliases.forget(key);
}
assert_eq!(within(&aliases, (0x100000, 0x1000)), None);
assert_eq!(within(&aliases, (0x180000, 0x1000)), Some(Some(8)));
// Its import gone, though it is still noted: free.
drop(bound);
assert_eq!(within(&aliases, (0x180000, 0x1000)), None);
aliases.forget(inside);
aliases.forget(apart);
drop(heap_import);
}
/// A reported remap counts the ranges placed buffers lie over that have a page among its bytes
/// rounded out to the import's unit, with or without memories noted: none for bytes beside
/// them, one for a byte of a page one lies on, and none at all with nothing placed.
@@ -372,6 +372,8 @@ mod noted_apart;
mod notice_command_buffers;
mod numbered_samplers;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod one_import;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod opencl_data;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod opencl_images;
@@ -0,0 +1,300 @@
//! One live import of a page (`host_aliases.rs`, "One page, one import"):
//! `VK_EXT_external_memory_host` leaves undefined a host allocation imported twice into one
//! device, so the device never imports again a page a live import of a no-copy buffer or heap
//! holds. A buffer over exactly a heap's bytes lies in the heap's import, and a heap over exactly
//! a live buffer's bytes in the buffer's; a buffer whose pages a live import holds all of is bound
//! inside that import's memory at their offset (`WorkCounts::object_churn
//! .buffers_bound_in_import`); and a buffer or heap whose pages one holds some of (across its
//! edge, or around it) is a copy of them (`WorkCounts::copied_over_live_imports`). Each test
//! counts the device's imports by pointer (`host_pointer_imports_made`), reads what the GPU wrote
//! through each buffer in the host's bytes, and what the host wrote in what the GPU copied out.
//!
//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`,
//! `m2v_cpu_icd`), on the kind of device the cfg selects. A device that imports no host pointer
//! says so and passes.
use super::blit_holds::{device, Scratch};
use crate::{
Buffer, CommandBufferStatus, CommandQueue, Device, Error, Heap, HeapDescriptor, HeapType,
HostMemory, ResourceOptions,
};
use std::alloc::Layout;
use std::ptr::NonNull;
/// The bytes of each test's host memory, and of a heap over its first half.
const BYTES: usize = 4 << 20;
const HEAP: u64 = 2 << 20;
/// `BYTES` bytes of zeroed host memory, aligned to 2 MiB, freed when dropped.
struct Pages(NonNull<u8>);
impl Pages {
fn layout() -> Layout {
Layout::from_size_align(BYTES, 2 << 20).unwrap()
}
fn new() -> Pages {
// SAFETY: the layout's size is not zero.
let pointer = unsafe { std::alloc::alloc_zeroed(Pages::layout()) };
Pages(NonNull::new(pointer).unwrap())
}
/// The memory `at` bytes in.
///
/// # Safety
///
/// It outlives every buffer and heap made over it.
unsafe fn at(&self, at: usize) -> HostMemory {
assert!(at < BYTES);
// SAFETY: inside the allocation; the caller's contract.
unsafe { HostMemory::new(NonNull::new_unchecked(self.0.as_ptr().add(at))) }
}
/// The bytes `at..at + length`.
fn bytes(&self, at: usize, length: usize) -> &[u8] {
assert!(at + length <= BYTES);
// SAFETY: inside the allocation, which no command writes while the test reads it.
unsafe { std::slice::from_raw_parts(self.0.as_ptr().add(at), length) }
}
/// Set the bytes from `at` on to `value`.
fn set(&self, at: usize, length: usize, value: u8) {
assert!(at + length <= BYTES);
// SAFETY: inside the allocation, which no command uses now.
unsafe { std::ptr::write_bytes(self.0.as_ptr().add(at), value, length) };
}
}
impl Drop for Pages {
fn drop(&mut self) {
// SAFETY: allocated with this layout in `Pages::new`.
unsafe { std::alloc::dealloc(self.0.as_ptr(), Pages::layout()) };
}
}
/// The device's first imports by pointer (not those of an import released while idle made
/// again, `host_residency.rs`), its buffers bound inside a live import, its copies made over a
/// live import, and the imports made where a live one held some of the pages all the same.
fn imports(device: &Device) -> [u64; 4] {
let counts = device.work_counts();
[
counts.host_pointer_imports_made - counts.host_imports_reimported,
counts.object_churn.buffers_bound_in_import,
counts.copied_over_live_imports,
counts.object_churn.imports_inside_live,
]
}
/// `counts` moved on by `by`.
fn plus(counts: [u64; 4], by: [u64; 4]) -> [u64; 4] {
std::array::from_fn(|at| counts[at] + by[at])
}
/// A no-copy buffer of `length` bytes `at` bytes into `pages`, of `Shared` storage.
fn buffer(device: &Device, pages: &Pages, at: usize, length: u64) -> Buffer {
// SAFETY: the pages outlive the buffer (dropped after the device), and only the test's
// commands use them while it lives.
unsafe {
device.new_buffer_with_bytes_no_copy(pages.at(at), length, ResourceOptions::shared(), None)
}
.unwrap()
}
/// A no-copy automatic heap of `size` bytes `at` bytes into `pages`; `None` where the device
/// imports no host pointer.
fn heap(device: &Device, pages: &Pages, at: usize, size: u64) -> Option<Heap> {
let descriptor = HeapDescriptor::new(HeapType::Automatic, size, ResourceOptions::shared());
// SAFETY: as `buffer`'s.
match unsafe { device.new_heap_with_bytes_no_copy(pages.at(at), &descriptor, None, None) } {
Ok(heap) => Some(heap),
Err(Error::Unsupported(gap)) => {
eprintln!("ONE-IMPORT: the device imports no host memory: {gap:?}");
None
}
Err(error) => panic!("new_heap_with_bytes_no_copy: {error:?}"),
}
}
/// Commit what `encode` records into one blit encoder, and wait for it.
fn blits(queue: &CommandQueue, encode: impl FnOnce(&mut crate::BlitCommandEncoder)) {
let command_buffer = queue.command_buffer().unwrap();
let mut blit = command_buffer.blit_command_encoder().unwrap();
encode(&mut blit);
blit.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed().unwrap();
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
}
/// The first `length` bytes of `buffer` as the GPU reads them: copied into a `Shared` buffer of
/// the runtime's own.
fn read(device: &Device, queue: &CommandQueue, buffer: &Buffer, length: u64) -> Vec<u8> {
let out = device
.new_buffer(length, ResourceOptions::shared())
.unwrap();
blits(queue, |blit| {
blit.copy_from_buffer_to_buffer(buffer, 0, &out, 0, length)
.unwrap()
});
let contents = out.contents().unwrap();
// SAFETY: the buffer's `length` bytes, which no command writes any more.
unsafe { std::slice::from_raw_parts(contents.as_ptr(), length as usize) }.to_vec()
}
/// A heap over host pages, then buffers over them: one over exactly the heap's bytes lies in its
/// import; two over part of them (one from a byte past a page's start) are bound inside it; one
/// across its end is a copy. No page is imported a second time, and the GPU's writes through
/// each reach the host's bytes, the host's writes the GPU's reads.
#[test]
fn buffers_over_a_heaps_pages_lie_inside_its_import() {
let pages = Pages::new();
let scratch = Scratch::new("one-import-heap-first");
let device = device(&scratch.0);
let queue = device.new_command_queue().unwrap();
let start = imports(&device);
let Some(heap) = heap(&device, &pages, 0, HEAP) else {
return;
};
let after_heap = imports(&device);
if after_heap[0] == start[0] {
eprintln!("ONE-IMPORT: the heap's pages are a copy here, imported by no pointer");
return;
}
assert_eq!(
after_heap,
plus(start, [1, 0, 0, 0]),
"the heap's own import"
);
let exact = buffer(&device, &pages, 0, HEAP);
assert_eq!(
imports(&device),
after_heap,
"a buffer over the heap's exact bytes"
);
let inside = buffer(&device, &pages, 64 << 10, 256 << 10);
let unaligned = buffer(&device, &pages, (64 << 10) + 0x10, 0x2000);
assert_eq!(
imports(&device),
plus(after_heap, [0, 2, 0, 0]),
"two buffers over part of the heap's bytes"
);
let across = buffer(&device, &pages, HEAP as usize - 4096, 8192);
let last = plus(after_heap, [0, 2, 1, 0]);
assert_eq!(imports(&device), last, "a buffer across the heap's end");
// The GPU's writes through each reach the host's bytes.
blits(&queue, |blit| {
blit.fill_buffer(&exact, 0..4096, 0x11).unwrap();
blit.fill_buffer(&inside, 4096..8192, 0x22).unwrap();
blit.fill_buffer(&across, 4096..8192, 0x33).unwrap();
});
assert!(pages.bytes(0, 4096).iter().all(|&byte| byte == 0x11));
let inside_at = (64 << 10) + 4096;
assert!(pages
.bytes(inside_at, 4096)
.iter()
.all(|&byte| byte == 0x22));
assert!(pages
.bytes(HEAP as usize, 4096)
.iter()
.all(|&byte| byte == 0x33));
// A placed buffer of the heap's, through the heap's own import.
let placed = heap.new_buffer(4096, ResourceOptions::shared()).unwrap();
blits(&queue, |blit| {
blit.fill_buffer(&placed, 0..4096, 0x44).unwrap()
});
assert!(pages.bytes(0, 4096).iter().all(|&byte| byte == 0x44));
// The host's writes reach the GPU's reads through each.
pages.set((64 << 10) + 0x10, 0x2000, 0x55);
assert!(read(&device, &queue, &unaligned, 0x2000)
.iter()
.all(|&byte| byte == 0x55));
pages.set(HEAP as usize - 4096, 8192, 0x66);
assert!(read(&device, &queue, &across, 8192)
.iter()
.all(|&byte| byte == 0x66));
pages.set(64 << 10, 256 << 10, 0x77);
assert!(read(&device, &queue, &inside, 256 << 10)
.iter()
.all(|&byte| byte == 0x77));
assert_eq!(imports(&device)[0], last[0], "no import since");
drop((placed, exact, inside, unaligned, across, heap));
}
/// Buffers over host pages, then heaps: a heap over exactly a live buffer's bytes lies in its
/// import, its placed buffers' writes reaching the host's bytes through it; a heap around a
/// live buffer's pages, which that import holds some of, is a copy; a buffer over part of a live
/// buffer's bytes is bound inside its import. No page is imported a second time.
#[test]
fn heaps_and_buffers_over_a_buffers_pages_lie_inside_its_import() {
let pages = Pages::new();
let scratch = Scratch::new("one-import-buffer-first");
let device = device(&scratch.0);
let queue = device.new_command_queue().unwrap();
let start = imports(&device);
let first = buffer(&device, &pages, 0, HEAP);
let after_first = imports(&device);
if after_first[0] == start[0] {
eprintln!("ONE-IMPORT: the buffer's pages are a copy here, imported by no pointer");
return;
}
assert_eq!(
after_first,
plus(start, [1, 0, 0, 0]),
"the buffer's own import"
);
let Some(heap) = heap(&device, &pages, 0, HEAP) else {
return;
};
assert_eq!(
imports(&device),
after_first,
"a heap over the buffer's exact bytes"
);
let placed = heap.new_buffer(8192, ResourceOptions::shared()).unwrap();
blits(&queue, |blit| {
blit.fill_buffer(&placed, 0..8192, 0x5c).unwrap()
});
assert!(pages.bytes(0, 8192).iter().all(|&byte| byte == 0x5c));
pages.set(0, 4096, 0x5d);
assert!(read(&device, &queue, &placed, 4096)
.iter()
.all(|&byte| byte == 0x5d));
// A buffer over part of the first one's bytes: bound inside its import.
let part = buffer(&device, &pages, 1 << 20, 64 << 10);
let bound = plus(after_first, [0, 1, 0, 0]);
assert_eq!(
imports(&device),
bound,
"a buffer over part of a buffer's bytes"
);
blits(&queue, |blit| {
blit.fill_buffer(&part, 0..4096, 0x6e).unwrap()
});
assert!(pages.bytes(1 << 20, 4096).iter().all(|&byte| byte == 0x6e));
// A small buffer in the second half, then a heap around it: the heap is a copy.
let small = buffer(&device, &pages, (3 << 20) + 4096, 4096);
let after_small = plus(bound, [1, 0, 0, 0]);
assert_eq!(
imports(&device),
after_small,
"a buffer over pages no import holds"
);
let copied_heaps = device.work_counts().copied_heaps_made;
let around = heap(&device, &pages, 2 << 20, HEAP).unwrap();
assert_eq!(
imports(&device),
plus(after_small, [0, 0, 1, 0]),
"a heap around a live buffer's pages"
);
assert_eq!(device.work_counts().copied_heaps_made, copied_heaps + 1);
let in_copy = around.new_buffer(4096, ResourceOptions::shared()).unwrap();
blits(&queue, |blit| {
blit.fill_buffer(&in_copy, 0..4096, 0x7f).unwrap()
});
assert!(pages.bytes(2 << 20, 4096).iter().all(|&byte| byte == 0x7f));
drop((in_copy, around, small, part, placed, heap, first));
}
@@ -375,6 +375,7 @@ pub(crate) struct Counters {
copied_rebind_pages_moved: AtomicU64,
copied_read_only_memory: AtomicU64,
copied_unwritable_pages: AtomicU64,
copied_over_live_imports: AtomicU64,
copied_rebind_pages_made: AtomicU64,
copied_rebind_images_made: AtomicU64,
copied_heaps_made: AtomicU64,
@@ -3380,6 +3381,7 @@ impl Counters {
CopiedBecause::Moved => &self.copied_rebind_pages_moved,
CopiedBecause::ReadOnly => &self.copied_read_only_memory,
CopiedBecause::Unwritable => &self.copied_unwritable_pages,
CopiedBecause::OverImport => &self.copied_over_live_imports,
}
.fetch_add(1, Ordering::Relaxed);
}
@@ -7230,6 +7232,13 @@ pub struct WorkCounts {
/// tried and their dma-buf source never called; the caller's gate is asked first where the
/// pointer would be imported, and a copy it refused is counted as refused.
pub copied_unwritable_pages: u64,
/// Of `copied_host_buffers_made`: no-copy buffers and heaps whose pages a live import of
/// another held some of, and not all (a buffer's bytes across the edge of another's or a
/// heap's), or a heap whose pages one held more of than the heap's own bytes, made over a
/// copy so that no page is imported twice (`host_aliases.rs`, "One page, one import"):
/// `VK_EXT_external_memory_host` leaves a host allocation imported twice into a device
/// undefined. Their import is never tried, their gate never asked.
pub copied_over_live_imports: u64,
/// Of the copies made, those a rebind gave a buffer as its new pages
/// (`Buffer::rebind_bytes_no_copy`), in `copied_host_buffers_made` and its kin too.
pub copied_rebind_pages_made: u64,
@@ -9268,6 +9277,7 @@ impl Device {
copied_rebind_pages_moved: counters.copied_rebind_pages_moved.load(Ordering::Relaxed),
copied_read_only_memory: counters.copied_read_only_memory.load(Ordering::Relaxed),
copied_unwritable_pages: counters.copied_unwritable_pages.load(Ordering::Relaxed),
copied_over_live_imports: counters.copied_over_live_imports.load(Ordering::Relaxed),
copied_rebind_pages_made: counters.copied_rebind_pages_made.load(Ordering::Relaxed),
copied_rebind_images_made: counters.copied_rebind_images_made.load(Ordering::Relaxed),
copied_heaps_made: counters.copied_heaps_made.load(Ordering::Relaxed),
@@ -9723,4 +9733,7 @@ pub(crate) enum CopiedBecause {
/// The process maps some of the pages read-only, whose GPU writes Metal drops and no import
/// on Linux keeps out of them: the copy drops them.
Unwritable,
/// A live import of another buffer or heap holds some of the pages and not all, or more than
/// a heap's own bytes: a second import would pin them twice (`host_aliases.rs`).
OverImport,
}
@@ -2284,6 +2284,7 @@ field metal2vulkan-runtime::MisplacedNotice.place pub place: NoticePlace
field metal2vulkan-runtime::Nil.call pub call: &'static str
field metal2vulkan-runtime::Nil.problem pub problem: Problem
field metal2vulkan-runtime::NotInPlace.why pub why: String
field metal2vulkan-runtime::ObjectChurn.buffers_bound_in_import pub buffers_bound_in_import: u64
field metal2vulkan-runtime::ObjectChurn.buffers_evicted pub buffers_evicted: u64
field metal2vulkan-runtime::ObjectChurn.buffers_parked pub buffers_parked: u64
field metal2vulkan-runtime::ObjectChurn.buffers_recycled pub buffers_recycled: u64
@@ -2680,6 +2681,7 @@ field metal2vulkan-runtime::WorkCounts.copied_host_buffers_shared pub copied_hos
field metal2vulkan-runtime::WorkCounts.copied_merge_back_bytes pub copied_merge_back_bytes: u64
field metal2vulkan-runtime::WorkCounts.copied_merges_compared pub copied_merges_compared: u64
field metal2vulkan-runtime::WorkCounts.copied_merges_skipped pub copied_merges_skipped: u64
field metal2vulkan-runtime::WorkCounts.copied_over_live_imports pub copied_over_live_imports: u64
field metal2vulkan-runtime::WorkCounts.copied_read_only_memory pub copied_read_only_memory: u64
field metal2vulkan-runtime::WorkCounts.copied_rebind_images_made pub copied_rebind_images_made: u64
field metal2vulkan-runtime::WorkCounts.copied_rebind_pages_made pub copied_rebind_pages_made: u64
Can't render this file because it is too large.