Copy a no-copy buffer, heap or rebind whose import the caller's gate refuses or that fails, announced

A new HostMemory::with_import_gate(ImportGate) asks the caller once,
holding no lock of the runtime's, just before a no-copy buffer, a
no-copy heap or a buffer rebind imports its pages, passing an
ImportRequest with the pages the import would map. If the gate answers
false, or an import the device and the gate admitted then fails
(OutOfMemory, another Vulkan error), the object is made over a copy of
the pages instead of failing. The default stays import-first. The copy
is host-visible memory owned by the runtime; `contents` stays the
caller's pointer. Each commit copies in the bytes the CPU changed since
the last sync, and each batch's completion merges back the bytes the GPU
changed (CPU wins where both wrote), byte by byte, before events,
waiters and handlers see it. Every copy is announced
(`copied-host-pages`) and counted. Pages the process cannot read are
never copied (the first copy reads through the kernel:
process_vm_readv / mach_vm_read_overwrite). A copied heap's buffers lie
in the copy and its textures are shadows. A rebind's copy is laid out as
its import would be. A rebind over an in-place image is refused
(NotImplemented(RebindTextures)) and a heap's rebind still imports
without asking. A caller's DirtyPages log stays attached to the copy as
to an import. The in-place check's pointer class skips copied buffers.

Ports dev-perf's fff961b7e5, 630d1b0174, 33d7aa5e98 and 9b4d4190f5 onto
a smaller coherence design: every live copy is compared in full at each
commit and completion, instead of dev-perf's log-driven,
encoder-collected copies (dev-perf's copied.rs, 79301a2515 and its
fixes, sat on a page log development has replaced). Also brings
789fa3d294's unreadable-page rule, 5190983470's lane site, and
1c7d49f788's copied-buffer skip. A driver that refuses the pointer
still fails the call (dev-perf copied there too; not taken). Known gaps
in FAST-PATHS: the compare costs O(size) per commit and completion, a
byte both sides wrote keeps the CPU's value, and a shared event's value
can be seen before the merge (c5db2d1b8a not ported). RUNTIME_VERSION
1690. Runtime-sources pin recomputed.

Public API: ImportGate, ImportRequest { start, length }
(#[non_exhaustive]), HostMemory::with_import_gate,
Degradation::CopiedHostPages, Device::fail_next_host_imports (test
hook), and the WorkCounts fields host_imports_refused_by_host,
copied_host_buffers_{made,refused,degraded}, copied_copy_in_bytes,
copied_merge_back_bytes, copied_rebind_pages_made, copied_heaps_made.

Verified on the M3 Max (MoltenVK, m2v_gpu): 11 new device tests
(tests::copied_device: buffer, rebind and heap, gate refusal and failed
admitted import, unreadable pages, a heap texture round trip) and 167
tests in the touched device filters pass; the counters move as
expected ([1,1,1,0,0] for a refusal, [0,1,0,1,0] for a failed import)
and the announcement is heard; on a 64 KiB copy 4079 bytes copied in and
4080 merged back for a 4 KiB CPU write and a 4 KiB fill, checked
exactly. Sabotage: ignoring the gate and removing the merge fails the 3
buffer tests; ignoring the rebind gate fails both rebind tests (no heap
sabotage). 249 host tests pass. Workspace clippy plain and
--cfg m2v_gpu, and rustdoc, clean; clippy re-run clean on the landing
merge. Not run on Linux.
This commit is contained in:
Anees Iqbal committed 2026-10-28 23:36:31 +02:00
1 parent 8c09b7c2c0
commit 0a1851164d
28 files changed
+1736 -42

No files matched your search

+7 -1
View File
@@ -207,7 +207,10 @@ the runtime made.
([HOWTO](../../docs/HOWTO.md#6-host-memory-a-driver-refuses)). A no-copy buffer's import of such
dma-bufs that only blits have read may be released while idle and imported again at its next
blit, which then costs time: RADV lists every import in every submission. Nothing of Metal's
observes it.
observes it. A no-copy buffer, heap or buffer rebind whose import the caller's gate refuses
(`HostMemory::with_import_gate`), or whose admitted import fails, is made over a copy of its
bytes in memory of the device's own, announced (`copied-host-pages`,
[HOWTO](../../docs/HOWTO.md#copied-host-buffers)).
`CommandBuffer::used_resources` lists what a command buffer uses until it completes, so a
program knows when it may take memory away.
- **Hazards** are tracked as Metal tracks them. A heap's resources are untracked by default, so
@@ -287,6 +290,9 @@ Calls Metal does not have, for a consumer that emulates a Metal device:
the writes to a no-copy object's pages, by which every copy of them into memory of the device's
own (a shadow of a texture over them) copies in only the pages changed since its last copy, on
every device. The runtime's own writes into the pages are reported back, naming their writer.
- `HostMemory::with_import_gate` and its `ImportGate` (with `ImportRequest`): the consumer's
gate over a no-copy buffer's, heap's or rebind's import of its pages; a refusal makes a copy of
them.
- `HostBytes`: bytes at a pointer that may change while a call reads them (a guest's memory),
which `Texture::replace_region_with_host_bytes` and `BufferContents::CopyHost` copy once through
the pointer, where the slice forms would need the caller's own copy first.
+40 -2
View File
@@ -683,6 +683,11 @@ impl HostPages {
}
}
/// They lie in a copy of the caller's pages, registered as `copied` (`copied.rs`).
pub(super) fn set_copied(&self, copied: crate::copied::Copied) {
self.import.set_copied(copied);
}
/// Keep the caller's log of the writes to them (`dirty_pages.rs`), given with their memory.
pub(super) fn keep_dirty(&self, dirty: Arc<DirtySource>) {
let _kept = self.dirty.set(dirty);
@@ -765,6 +770,11 @@ impl HostPages {
self.import.shape.over_dma_buf
}
/// Whether they lie in a copy of the caller's pages (`copied.rs`), not an import of them.
pub(super) fn copied(&self) -> bool {
self.import.copied()
}
/// Where they lie as dma-bufs (`dma_buf.rs`): the imports, with the caller's source; the host
/// address where their bytes start (from which an image over them reckons its texels'); and
/// the imports' memory type. `None` for pages imported by their pointer. A read that keeps
@@ -921,6 +931,9 @@ pub(super) struct HostImport {
/// The releases of pages that went while it lived with no keep-alive: their deallocators
/// run once it is freed.
after_free: Mutex<Vec<Release>>,
/// Its place among its device's copied host buffers, where its memory is a copy of the
/// caller's pages, not their import (`copied.rs`): unregistered as it goes, before its memory.
copied: OnceLock<crate::copied::Copied>,
}
/// Where a host import's bytes lie in its `VkBuffer` and memory, which reading needs no
@@ -1097,6 +1110,7 @@ impl HostImport {
unlisted: AtomicBool::new(unlisted),
kept: Mutex::new(None),
after_free: Mutex::new(Vec::new()),
copied: OnceLock::new(),
}
}
@@ -1121,6 +1135,7 @@ impl HostImport {
unlisted: AtomicBool::new(false),
kept: Mutex::new(None),
after_free: Mutex::new(Vec::new()),
copied: OnceLock::new(),
}
}
@@ -1132,6 +1147,18 @@ impl HostImport {
}
}
/// Its memory is a copy of the caller's pages, registered as `copied` (`copied.rs`), not
/// their import.
pub(super) fn set_copied(&self, copied: crate::copied::Copied) {
// Set once, as the copied buffer is made.
let _ = self.copied.set(copied);
}
/// Whether its memory is a copy of the caller's pages (`copied.rs`), not their import.
pub(super) fn copied(&self) -> bool {
self.copied.get().is_some()
}
/// Whether its pages were imported through a read-only view of them, which drops the GPU's
/// writes (`read_only_view.rs`).
pub(super) fn drops_writes(&self) -> bool {
@@ -1267,6 +1294,8 @@ impl Device {
impl Drop for HostImport {
fn drop(&mut self) {
// A copy leaves its device's comparisons before its memory can go (`copied.rs`).
drop(self.copied.take());
// The Vulkan teardown is a section of the exit guard.
let Some(busy) = exit_guard::enter() else {
// The process is exiting: the pages stay imported to its end (`exit_guard`), so no
@@ -2568,7 +2597,7 @@ impl Device {
/// Place `raw` (for a buffer of `length` bytes) in memory of `class` and at `at` in the
/// address space; released again when either fails.
fn place_buffer(
pub(super) fn place_buffer(
&self,
raw: vk::Buffer,
length: u64,
@@ -2582,7 +2611,7 @@ impl Device {
/// [`place_buffer`](Device::place_buffer) for a heap's own buffer: where the heap's textures
/// can lie too (`Device::heap_requirements`).
fn place_heap_buffer(
pub(super) fn place_heap_buffer(
&self,
raw: vk::Buffer,
length: u64,
@@ -3360,6 +3389,15 @@ impl Buffer {
}
}
/// Whether the buffer's bytes lie in a copy of the caller's pages (a copied host buffer,
/// `copied.rs`), not an import of them; false for a buffer over no host pages, or detached.
pub(crate) fn copied(&self) -> bool {
match self.pages_cell().map(|cell| cell.lying()) {
Some(Lying::In(pages)) => pages.copied(),
_ => false,
}
}
/// Whether the host pages the buffer's bytes lie in (a no-copy buffer's, or for a heap's
/// buffer its heap's), or lay in while they are detached, were imported as dma-bufs
/// (`dma_buf.rs`); false for a buffer over no host pages.
@@ -13,6 +13,7 @@ use super::address_pool::AddressPool;
#[cfg(unix)]
use super::buffer::Pages;
use super::buffer::{usage, Buffer, BufferParts, HostCell, Lying, Modes, Owner, ReadApart};
use super::copied::NotCopied;
use super::degradation::Degradation;
use super::device::lock;
use super::error::MemoryKind;
@@ -21,8 +22,8 @@ use super::heap::{Heap, HeapProblem};
use super::host_bytes::HostBytes;
use super::host_memory::{
based_size, binds_in, buffer_base, import_refused, import_window, not_importable,
refuse_unwritable, refused, Deallocator, HostMemory, HostParts, HostRelease, ImportWindow,
Importer, KeepAlive, Source,
refuse_unwritable, refused, Deallocator, HostMemory, HostParts, HostRelease, ImportRequest,
ImportWindow, Importer, KeepAlive, Source,
};
#[cfg(unix)]
use super::host_residency::Again;
@@ -302,6 +303,13 @@ impl Device {
/// are: on macOS the pages are imported through a read-only view of them, by their pointer
/// alone; elsewhere the GPU's writes reach them, announced (`private-resource-option`).
///
/// Where the caller's gate refuses the import ([`HostMemory::with_import_gate`]), or the import
/// the device and the gate admitted fails (out of memory, another Vulkan error), the buffer is
/// made over a copy of the bytes in memory of the device's own instead, its `contents` still
/// the pointer, announced (`copied-host-pages`): each commit copies in the bytes the CPU
/// changed, and each batch's completion merges back the bytes the GPU changed (`copied.rs`).
/// Pages the process cannot read are never copied, and keep the import's refusal.
///
/// Refused: a length of 0 or past `max_buffer_length` (`Nil`, as plain Metal answers nil);
/// `Private` or `Memoryless` storage, as Metal stops them, and an undefined
/// option (`Invalid`); a device
@@ -477,6 +485,7 @@ impl Device {
source,
writable,
dirty,
gate,
} = memory.into_parts();
let host = host_window(call, importer, pointer, length, source, drops_writes)?;
let window = host.window;
@@ -511,6 +520,26 @@ impl Device {
// and the pages stay writable while imported (`HostMemory::new`).
let host = writability_settled(host, writable, &shared.counts)?;
let unwritable = host.unwritable;
// A no-copy buffer or heap whose pointer the device would import (not one whose GPU
// writes are dropped) may be a copy instead (`copied.rs`): where the caller's gate refuses
// the import, asked here with the pages it would map, holding no lock of the runtime's; or
// where the import it admitted fails.
let copyable = !drops_writes;
let refused_by_host = copyable
&& host.by_pointer
&& gate.as_ref().is_some_and(|gate| {
let request = ImportRequest {
start: NonNull::new(window.start as *mut u8).unwrap_or(pointer),
length: window.size,
};
!gate(request)
});
if refused_by_host {
shared.counts.host_import_refused_by_host();
let copy = (call, pointer, length, modes, placement, of_heap);
// SAFETY: the caller's contract.
return unsafe { self.copied_buffer(copy, release, dirty, None) };
}
// SAFETY: the window lies in the pages of the caller's bytes, which stay mapped
// (`HostMemory::new`), and the source's pieces hold them (`HostMemory::with_dma_buf`). No
// lock of the runtime's is held.
@@ -518,26 +547,35 @@ impl Device {
// while idle and import them again (`host_residency.rs`), as it may its own import of
// the pointer where the driver's pointer imports follow their address; a heap's import
// stays, as does an import of a read-only view.
let (buffer, memory, again) =
match unsafe { self.import_by_pointer(importer, pointer, length, host, class) }? {
Ok((buffer, memory)) => {
#[cfg(unix)]
let again = (!of_heap && !drops_writes)
.then(|| Again::pointer(self, pointer, (length, window, class)))
.flatten();
#[cfg(not(unix))]
let again = None;
(buffer, memory, again)
}
// SAFETY: as above.
Err(source) => unsafe {
let keep = !of_heap;
let window = &window;
self.import_from_source(
call, importer, pointer, length, window, source, class, keep,
)
}?,
};
let imported = unsafe { self.import_by_pointer(importer, pointer, length, host, class) };
let imported = match imported {
// An import the device and the gate admitted that then failed: a copy, announced.
Err(error) if copyable && copies_after(&error) => {
let copy = (call, pointer, length, modes, placement, of_heap);
// SAFETY: the caller's contract.
return unsafe { self.copied_buffer(copy, release, dirty, Some(error)) };
}
imported => imported,
};
let (buffer, memory, again) = match imported? {
Ok((buffer, memory)) => {
#[cfg(unix)]
let again = (!of_heap && !drops_writes)
.then(|| Again::pointer(self, pointer, (length, window, class)))
.flatten();
#[cfg(not(unix))]
let again = None;
(buffer, memory, again)
}
// SAFETY: as above.
Err(source) => unsafe {
let keep = !of_heap;
let window = &window;
self.import_from_source(
call, importer, pointer, length, window, source, class, keep,
)
}?,
};
if unwritable {
self.degrade_read_only_pages(call, pointer, length);
}
@@ -637,6 +675,7 @@ impl Device {
source,
writable,
dirty,
gate,
} = memory.into_parts();
// A buffer whose GPU writes are dropped keeps them dropped over its new pages.
let drops_writes = cell.drops_writes();
@@ -683,11 +722,62 @@ impl Device {
let unit = importer.page.max(importer.alignment);
let start = pointer.as_ptr() as u64;
let covered = (shared.aliases).covered(start, start.saturating_add(length), unit);
// SAFETY: the window lies in the pages of the caller's bytes, which stay mapped
// (`HostMemory::new`, `HostMemory::with_dma_buf`).
let (host, placement, remade) = match unsafe {
self.import_by_pointer(importer, pointer, length, host, class)
}? {
// A buffer's new pages whose pointer the device would import (not a heap's, nor
// a buffer's whose GPU writes are dropped) may be a copy of them instead
// (`copied.rs`): where the caller's gate refuses the import, asked here with the
// pages it would map, holding no lock of the runtime's; or where the import it
// admitted fails.
let copyable = heap.is_none() && !drops_writes;
let gate = gate.filter(|_| copyable && host.by_pointer);
let refused_by_host = match gate {
Some(gate) => {
// Asked with no lock of the runtime's held: the textures over detached
// bytes are let go of meanwhile, and settled again after it.
let was_settled = settled.take().is_some();
let request = ImportRequest {
start: NonNull::new(window.start as *mut u8).unwrap_or(pointer),
length: window.size,
};
let refused = !gate(request);
if was_settled {
settled = Some(cell.settled().ok_or_else(detached_textures)?);
}
refused
}
None => false,
};
if refused_by_host {
shared.counts.host_import_refused_by_host();
}
let copy = |failed: Option<Error>| {
// An image in place over the bytes would be made again over the copy, which
// is not done: refused, as over new pages no image takes.
if !in_place.is_empty() {
return Err(Error::NotImplemented(RuntimeGap::RebindTextures));
}
// SAFETY: the caller's contract.
unsafe { self.copied_pages(pointer, length, &window, failed) }
};
let imported = match refused_by_host {
true => Err(None),
// SAFETY: the window lies in the pages of the caller's bytes, which stay
// mapped (`HostMemory::new`, `HostMemory::with_dma_buf`).
false => match unsafe {
self.import_by_pointer(importer, pointer, length, host, class)
} {
Err(error) if copyable && copies_after(&error) => Err(Some(error)),
imported => Ok(imported),
},
};
let (imported, copied) = match imported {
Ok(imported) => (imported, None),
Err(failed) => {
let degraded = failed.is_some();
let (host, placement, copied) = copy(failed)?;
(Ok(Ok((host, placement))), Some((copied, degraded)))
}
};
let (host, placement, remade) = match imported? {
Ok((host, placement)) => (host, placement, Remade::default()),
// The source is called with no lock of the runtime's held (`dma_buf.rs`):
// the textures over detached bytes are let go of meanwhile, and must be
@@ -744,7 +834,15 @@ impl Device {
host.base,
host.size - host.base,
);
shared.counts.host_rebind_import_made(covered);
match copied {
Some((copied, degraded)) => {
pages.set_copied(copied);
shared.counts.copied_host_buffer_made(degraded);
shared.counts.copied_rebind_pages_made();
self.degrade_copied(call, pointer, length, degraded);
}
None => shared.counts.host_rebind_import_made(covered),
}
(pages, remade)
}
};
@@ -1045,6 +1143,245 @@ impl Device {
});
}
/// A copy of the `length` bytes at `pointer` for a rebind's new pages (`copied.rs`), laid
/// out as their import of `window` would be: a `VkBuffer` from the window's first page, the
/// bytes `window.offset` into it, in host-visible memory of the device's own, so the texel
/// views planned at the bytes' offset lie where they lay. Its memory's host address is the
/// window's, so the buffer's `contents` stays the pointer. Refused as
/// [`Device::copied_buffer`] refuses its copy.
///
/// # Safety
///
/// The caller's bytes meet [`HostMemory::new`]'s contract for `length` bytes.
unsafe fn copied_pages(
&self,
pointer: NonNull<u8>,
length: u64,
window: &ImportWindow,
failed: Option<Error>,
) -> Result<(HostBuffer, Placement, crate::copied::Copied), Error> {
let shared = self.shared();
let raw_device = shared.vk();
let bytes = usize::try_from(length).map_err(|_| Error::OutOfMemory(MemoryKind::Host))?;
// Padded to 16 bytes past the bytes, as a buffer of the runtime's own.
let size = (window.offset.checked_add(length))
.and_then(|end| end.checked_next_multiple_of(16))
.ok_or(Error::OutOfMemory(MemoryKind::Device))?;
let info = shared.sharing().buffer(
vk::BufferCreateInfo::default()
.size(size)
.usage(usage(false)),
);
// SAFETY: the device is live and `info` valid.
let raw = unsafe { crate::creation::buffer(raw_device, &info) }.map_err(vulkan)?;
shared.counts.buffer_made(info.usage);
// SAFETY: `raw` is a live buffer of this device.
let requirements = unsafe { raw_device.get_buffer_memory_requirements(raw) };
let allocated = crate::memory::allocate_addressed(
&shared.memory,
raw_device,
&super::buffer::placed(requirements),
MemoryClass::Shared,
&shared.counts,
);
let mut memory = match allocated {
Ok(memory) => memory,
Err(error) => {
// SAFETY: the buffer is unused.
unsafe { release::object(raw_device, raw) };
return Err(error);
}
};
let discard = |memory: &Placement| {
// SAFETY: the buffer is unused.
unsafe { release::object(raw_device, raw) };
lock(&shared.memory).free(raw_device, memory);
};
// SAFETY: the placement meets the buffer's requirements and is not bound elsewhere.
let bound =
unsafe { crate::creation::bind_buffer(raw_device, raw, memory.memory, memory.offset) };
if let Err(error) = bound {
discard(&memory);
return Err(vulkan(error));
}
let copy = memory
.mapped
.and_then(|mapped| NonNull::new(mapped.as_ptr().wrapping_add(window.offset as usize)));
let Some(copy) = copy else {
discard(&memory);
return Err(internal(
"a copied host buffer's memory is not host-visible",
));
};
// SAFETY: the copy is the placement's `length` bytes past the window's offset, mapped,
// which nothing uses yet and which stay mapped while the import holds them; the caller's
// bytes stay mapped as long (the caller's contract).
let copied = match unsafe { shared.copied.add(pointer, copy, bytes) } {
Ok(copied) => copied,
Err(why) => {
discard(&memory);
return Err(match why {
NotCopied::Unreadable => failed.unwrap_or_else(not_importable),
NotCopied::OutOfHostMemory => Error::OutOfMemory(MemoryKind::Host),
});
}
};
// The host address of the window's first byte, as an import's: `contents` is the
// pointer, `window.offset` past it.
let start = NonNull::new(pointer.as_ptr().wrapping_sub(window.offset as usize));
memory.mapped = Some(super::memory::Mapped::of_caller(start.unwrap_or(pointer)));
let host = HostBuffer {
raw,
base: window.offset,
size: window.offset + length,
requirements,
};
Ok((host, memory, copied))
}
/// Announce that `call` made the `length` bytes at `pointer` a copy of the caller's pages
/// (`Degradation::CopiedHostPages`): where `degraded`, because the import the device and the
/// gate admitted failed, else because the caller's gate refused it.
fn degrade_copied(
&self,
call: &'static str,
pointer: NonNull<u8>,
length: u64,
degraded: bool,
) {
self.degrade(Degradation::CopiedHostPages, || {
let why = match degraded {
false => {
"the caller's import gate (HostMemory::with_import_gate) refused their \
import"
}
true => "their import failed",
};
(
format!("{call} over {length:#x} bytes at {pointer:p}"),
format!("{why}, so the GPU uses a copy of them in memory of the device's own"),
)
});
}
/// A copied host buffer over the `length` bytes at `pointer` (`copied.rs`), of `modes`, at
/// `placement`, for `call`, a heap's own buffer where `of_heap` (laid where the heap's
/// textures could lie, its hazard identity a heap's), given back to `release`, its caller's
/// log `dirty` kept with it:
/// made where the caller's gate refused the pointer's import (`failed` is `None`), or where
/// the import the gate and the device admitted failed with `failed`. Announced
/// (`copied-host-pages`) and counted either way. Refused where its own memory cannot be had
/// (typed as the allocation answers), and where the process cannot read every page (memory
/// Metal makes no buffer over): with the import's failure where there was one, else as not
/// importable.
///
/// # Safety
///
/// The caller's bytes meet [`HostMemory::new`]'s contract for `length` bytes.
unsafe fn copied_buffer(
&self,
(call, pointer, length, modes, placement, of_heap): (
&'static str,
NonNull<u8>,
u64,
Modes,
Place,
bool,
),
release: Option<super::host_memory::Release>,
dirty: Option<Arc<super::dirty_pages::DirtySource>>,
failed: Option<Error>,
) -> Result<Buffer, Error> {
let shared = self.shared();
let raw_device = shared.vk();
let unreadable = |failed: Option<Error>| failed.unwrap_or_else(not_importable);
let bytes = usize::try_from(length).map_err(|_| Error::OutOfMemory(MemoryKind::Host))?;
// Padded to 16 bytes, so a device fill clears every byte too, as a buffer of its own.
let size = length
.checked_next_multiple_of(16)
.ok_or_else(|| nil(call, Problem::BufferLength { length }))?;
let info = shared.sharing().buffer(
vk::BufferCreateInfo::default()
.size(size)
.usage(usage(false)),
);
// SAFETY: the device is live and `info` valid.
let raw = unsafe { crate::creation::buffer(raw_device, &info) }.map_err(vulkan)?;
shared.counts.buffer_made(info.usage);
// A heap's own buffer lies where its textures could too, as an imported heap's.
let placed = match of_heap {
true => self.place_heap_buffer(raw, length, MemoryClass::Shared, placement),
false => self.place_buffer(raw, length, MemoryClass::Shared, placement),
};
let (mut memory, (address, reserved)) = match placed {
Ok(placed) => placed,
Err(error) => {
// SAFETY: the buffer is unused.
unsafe { release::object(raw_device, raw) };
return Err(error);
}
};
let discard = |memory: &Placement| {
// SAFETY: the buffer is unused.
unsafe { release::object(raw_device, raw) };
lock(&shared.memory).free(raw_device, memory);
};
let Some(copy) = memory
.mapped
.and_then(|mapped| NonNull::new(mapped.as_ptr()))
else {
discard(&memory);
return Err(internal(
"a copied host buffer's memory is not host-visible",
));
};
// SAFETY: the copy is the placement's `length` bytes, mapped, which nothing uses yet and
// which stay mapped while the import holds them; the caller's bytes stay mapped as long
// (the caller's contract).
let copied = match unsafe { shared.copied.add(pointer, copy, bytes) } {
Ok(copied) => copied,
Err(why) => {
discard(&memory);
return Err(match why {
NotCopied::Unreadable => unreadable(failed),
NotCopied::OutOfHostMemory => Error::OutOfMemory(MemoryKind::Host),
});
}
};
// Its `contents` is the caller's pointer, as a no-copy buffer's is.
memory.mapped = Some(super::memory::Mapped::of_caller(pointer));
let buffer = self.buffer_of(BufferParts {
raw,
memory,
offset: 0,
base: 0,
length,
reach: length,
modes,
address,
reserved,
owner: Owner::Caller,
release,
of_heap,
mirror: None,
#[cfg(unix)]
again: None,
});
if let Some(pages) = buffer.host_pages() {
pages.set_copied(copied);
// The caller's log of the pages' writes stays with them (`dirty_pages.rs`).
if let Some(dirty) = dirty {
pages.keep_dirty(dirty);
}
}
shared.counts.copied_host_buffer_made(failed.is_some());
if of_heap {
shared.counts.copied_heap_made();
}
self.degrade_copied(call, pointer, length, failed.is_some());
Ok(buffer)
}
/// Release `buffer` and its `placement`, an import made for a buffer or rebind that is not
/// made after all: the `VkBuffer` first, once its sparse binding completed.
pub(super) fn discard_import(&self, buffer: HostBuffer, placement: Placement) {
@@ -1178,6 +1515,16 @@ impl Device {
) -> Result<Placement, Error> {
let shared = self.shared();
let raw_device = shared.vk();
#[cfg(test)]
{
use std::sync::atomic::Ordering;
let failing = &shared.failing_host_imports;
if (failing.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_sub(1)))
.is_ok()
{
return Err(Error::OutOfMemory(MemoryKind::Device));
}
}
// SAFETY: the caller's contract keeps the pages mapped until the placement is freed.
let placement =
unsafe { lock(&shared.memory).import_host(raw_device, pages, size, allowed, class) }
@@ -1247,6 +1594,13 @@ fn writability_settled(
}
}
/// Whether `error`, an import's failure that is not the device's refusal of the pages, leaves the
/// no-copy buffer a copy of them (`copied.rs`): out of memory, or another Vulkan error. A lost
/// device does not, nor does misuse.
fn copies_after(error: &Error) -> bool {
matches!(error, Error::OutOfMemory(_) | Error::Vulkan(_))
}
/// The host pages a no-copy object of `length` bytes at `pointer` imports on the device of
/// `importer`, for `call`: the pages the range touches ([`import_window`]), imported by their
/// pointer where the device's import alignment covers them, else only as a dma-buf where the
@@ -404,6 +404,10 @@ fn finish(watch: &Watch, lists: &mut FenceLists, mut finished: Vec<(usize, Submi
else {
return true;
};
// The GPU's writes into copied host buffers go back to the caller's pages before anything
// sees the batches complete: their event signals, the scheduler, a waiter, their completed
// handlers (`copied.rs`).
device.shared().copied.merge_back(&device.shared().counts);
// The holds of the batches that end no command buffer go first, their work completed: a
// detach that sees one of their signals detaches what only they held (`detach.rs`).
for (_, batch) in &mut finished {
@@ -2824,6 +2824,9 @@ impl CommandBuffer {
let ticket = state.heaps.commit(device);
state.retained.push(Box::new(ticket));
}
// Every byte the CPU changed in a copied host buffer's pages is in its copy before any
// of this command buffer's work is submitted (`copied.rs`).
device.shared().copied.copy_in(&device.shared().counts);
state.status = CommandBufferStatus::Committed;
// Its set-0 cache is shut here, before anything records again: from the commit on it
// holds what its commands took only weakly (below), so no handle a kept set holds is
+274
View File
@@ -0,0 +1,274 @@
//! Copied host buffers: a no-copy buffer whose import of the caller's pages the caller's gate
//! refused ([`HostMemory::with_import_gate`](crate::HostMemory)), or whose import the gate and
//! the device admitted and that then failed (out of memory, another Vulkan error), is made all the
//! same over a copy of its bytes (`Device::buffer_over_host_memory`), announced
//! (`copied-host-pages`). No import maps the pages, so they take no kernel mapping.
//!
//! - **The copy.** A `VkBuffer` of the buffer's length in host-visible, coherent memory of the
//! runtime's own ([`MemoryClass::Shared`](crate::memory::MemoryClass)), which the GPU uses; the
//! buffer's `contents` stays the caller's pointer, as Metal's is. Made over pages the process
//! reads: the first copy reads them through the kernel ([`read_pages`]), and pages it cannot
//! read (memory Metal makes no buffer over) keep the import's own refusal.
//! - **Coherence.** The runtime keeps, for each copy, the bytes the pages and the copy last agreed
//! on (its snapshot). At each commit, before any of the command buffer's work is submitted,
//! every byte the CPU changed in the pages since then is written into the copy
//! ([`CopiedBuffers::copy_in`]). At each batch's completion, before its events are seen
//! signaled, the scheduler is told, its handlers run or a waiter returns, every byte the GPU
//! changed in the copy is written back into the pages, where the CPU did not change that byte
//! since ([`CopiedBuffers::merge_back`]): a byte both changed keeps the CPU's, which the next
//! commit copies in. Bytes are compared 8 at a time and merged one at a time where they differ,
//! so a merge writes no byte the GPU did not change. Each batch ends with a barrier that makes
//! its writes visible to the host (`tracker::Barrier::to_host`).
//! - **Cost.** Every live copy is compared whole at each commit and at each batch's completion,
//! whichever buffers the work names: O(bytes) per commit and per batch, a fallback's cost
//! (`docs/FAST-PATHS.md`, known gaps). Counted: `WorkCounts::copied_copy_in_bytes`,
//! `WorkCounts::copied_merge_back_bytes`.
//! - **Heaps and rebinds.** A no-copy heap's own buffer is copied as a buffer is, where the heap's
//! textures could lie, with a heap's hazard identity; its buffers lie in the copy at their
//! offsets, and its textures are shadows of its bytes (`AliasRoute::MemoryShadow` or Metal's
//! tiles). A buffer's rebind gives it a copy of its new pages laid out as their import would be
//! (`Device::copied_pages`), so texel views planned at the bytes' offset lie where they lay; a
//! rebind of a buffer with an image in place over it is refused instead
//! (`NotImplemented(RebindTextures)`).
//! - **What is not copied.** A heap's rebind and memory whose GPU writes Metal's private option
//! bit 24 drops import as before. A texture over a copied buffer is a shadow of its bytes
//! (`shadowed-texture`): no image is bound to the copy.
use crate::device::lock;
use crate::work_counts::Counters;
use std::ptr::NonNull;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
/// A device's live copied host buffers, compared at each commit and each batch's completion.
#[derive(Default)]
pub(crate) struct CopiedBuffers {
entries: Mutex<Vec<Entry>>,
/// How many are live: a commit or completion looks no further where none is.
live: AtomicUsize,
/// The next copy's id.
next: AtomicU64,
}
/// Why a copy was not made ([`CopiedBuffers::add`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum NotCopied {
/// A page is not mapped, or mapped without read permission: memory Metal makes no buffer over.
Unreadable,
/// The host has no memory for the copy's snapshot.
OutOfHostMemory,
}
/// A copy and the caller's pages it mirrors.
struct Entry {
id: u64,
/// The caller's bytes (the buffer's `contents`).
pages: NonNull<u8>,
/// The copy's bytes, mapped.
copy: NonNull<u8>,
/// The bytes the pages and the copy last agreed on.
snapshot: Box<[u8]>,
}
// SAFETY: the pointers name the caller's pages, which stay mapped while the buffer's import lives
// (`HostMemory::new`), and the copy's mapped memory, which the import holds; both are reached only
// under the registry's lock, which the import's drop takes before either goes ([`Copied`]).
unsafe impl Send for Entry {}
/// A live copy's place in its device's [`CopiedBuffers`]: dropped (unregistered) before the copy's
/// memory is freed, so no comparison reads it after (`HostImport`'s drop).
pub(crate) struct Copied {
buffers: Arc<CopiedBuffers>,
id: u64,
}
impl Drop for Copied {
fn drop(&mut self) {
let mut entries = lock(&self.buffers.entries);
if let Some(index) = entries.iter().position(|entry| entry.id == self.id) {
entries.swap_remove(index);
self.buffers.live.fetch_sub(1, Ordering::Relaxed);
}
}
}
impl CopiedBuffers {
/// Register the copy at `copy` of the `length` bytes at `pages`, its bytes read from the pages
/// now, through the kernel ([`read_pages`]). Refused, registering nothing, where the process
/// cannot read every page, or the host has no memory for the bytes the copy and the pages last
/// agreed on.
///
/// # Safety
///
/// `copy` is `length` bytes of mapped memory nothing else uses yet, which stays mapped until
/// the answer is dropped; `pages` the caller's bytes, which stay mapped as long
/// (`HostMemory::new`).
pub(crate) unsafe fn add(
self: &Arc<Self>,
pages: NonNull<u8>,
copy: NonNull<u8>,
length: usize,
) -> Result<Copied, NotCopied> {
let mut snapshot = Vec::new();
if snapshot.try_reserve_exact(length).is_err() {
return Err(NotCopied::OutOfHostMemory);
}
snapshot.resize(length, 0u8);
let mut snapshot = snapshot.into_boxed_slice();
if !read_pages(pages, &mut snapshot) {
return Err(NotCopied::Unreadable);
}
// SAFETY: the copy is `length` bytes nothing else uses yet (the caller's).
unsafe { std::ptr::copy_nonoverlapping(snapshot.as_ptr(), copy.as_ptr(), length) };
let id = self.next.fetch_add(1, Ordering::Relaxed);
lock(&self.entries).push(Entry {
id,
pages,
copy,
snapshot,
});
self.live.fetch_add(1, Ordering::Relaxed);
Ok(Copied {
buffers: Arc::clone(self),
id,
})
}
/// At a commit: write into each copy the bytes the CPU changed in its pages since they last
/// agreed, before any of the command buffer's work is submitted.
pub(crate) fn copy_in(&self, counts: &Counters) {
if self.live.load(Ordering::Relaxed) == 0 {
return;
}
let mut moved = 0u64;
for entry in lock(&self.entries).iter_mut() {
// SAFETY: the entry's pointers are live while it is registered (`Entry`).
moved += unsafe { sync(entry.pages, entry.copy, &mut entry.snapshot, false) };
}
counts.copied_copied_in(moved);
}
/// At a batch's completion: write back into each copy's pages the bytes the GPU changed in the
/// copy since they last agreed, where the CPU did not change them since, before anything sees
/// the batch complete.
pub(crate) fn merge_back(&self, counts: &Counters) {
if self.live.load(Ordering::Relaxed) == 0 {
return;
}
let mut moved = 0u64;
for entry in lock(&self.entries).iter_mut() {
// SAFETY: the entry's pointers are live while it is registered (`Entry`).
moved += unsafe { sync(entry.copy, entry.pages, &mut entry.snapshot, true) };
}
counts.copied_merged_back(moved);
}
}
/// Write into `to` each byte of `from` that differs from `snapshot`, and take it into `snapshot`;
/// where `keep_to`, a byte of `to` that differs from `snapshot` already (written since they last
/// agreed) is kept, though `snapshot` takes `from`'s, so the next copy the other way carries it.
/// The bytes written.
///
/// # Safety
///
/// `from` and `to` are `snapshot.len()` bytes of mapped memory each.
pub(crate) unsafe fn sync(
from: NonNull<u8>,
to: NonNull<u8>,
snapshot: &mut [u8],
keep_to: bool,
) -> u64 {
let (from, to) = (from.as_ptr(), to.as_ptr());
let mut written = 0u64;
let mut at = 0;
while at < snapshot.len() {
let span = (snapshot.len() - at).min(8);
let mut was = [0u8; 8];
was[..span].copy_from_slice(&snapshot[at..at + span]);
let mut now = [0u8; 8];
// SAFETY: `span` bytes at `at` lie in `from` (the caller's).
unsafe { std::ptr::copy_nonoverlapping(from.add(at), now.as_mut_ptr(), span) };
if now != was {
let mut there = [0u8; 8];
if keep_to {
// SAFETY: as above, in `to`.
unsafe { std::ptr::copy_nonoverlapping(to.add(at), there.as_mut_ptr(), span) };
}
for byte in 0..span {
if now[byte] == was[byte] {
continue;
}
if !keep_to || there[byte] == was[byte] {
// SAFETY: as above.
unsafe { to.add(at + byte).write_volatile(now[byte]) };
written += 1;
}
snapshot[at + byte] = now[byte];
}
}
at += span;
}
written
}
/// Read the caller's `into.len()` bytes at `pages` into `into` through the kernel, which answers a
/// page the process cannot read (unmapped, or mapped without read permission) with a failure, not a
/// fault: `false` then. On Linux `process_vm_readv` of the process's own pages; on macOS
/// `mach_vm_read_overwrite` of its own task's; elsewhere nothing is read and the answer is `false`.
#[cfg(target_os = "linux")]
fn read_pages(pages: NonNull<u8>, into: &mut [u8]) -> bool {
let mut done = 0;
while done < into.len() {
let local = libc::iovec {
iov_base: into[done..].as_mut_ptr().cast(),
iov_len: into.len() - done,
};
let remote = libc::iovec {
iov_base: pages.as_ptr().wrapping_add(done).cast(),
iov_len: into.len() - done,
};
// SAFETY: the local vector names `into`'s bytes, which the call writes; the remote one is
// read through the kernel, which answers an unreadable page with an error.
let read = unsafe { libc::process_vm_readv(libc::getpid(), &local, 1, &remote, 1, 0) };
if read <= 0 {
return false;
}
done += read as usize;
}
true
}
/// [`read_pages`] on macOS.
#[cfg(target_os = "macos")]
fn read_pages(pages: NonNull<u8>, into: &mut [u8]) -> bool {
unsafe extern "C" {
/// `<mach/mach_init.h>`: the port of this process's task.
static mach_task_self_: libc::mach_port_t;
fn mach_vm_read_overwrite(
target_task: libc::vm_map_t,
address: libc::mach_vm_address_t,
size: libc::mach_vm_size_t,
data: libc::mach_vm_address_t,
outsize: *mut libc::mach_vm_size_t,
) -> libc::kern_return_t;
}
let mut read = 0;
// SAFETY: the call writes `into`'s bytes alone, and answers an unreadable page of the source
// with an error.
let answer = unsafe {
mach_vm_read_overwrite(
mach_task_self_,
pages.as_ptr() as u64,
into.len() as u64,
into.as_mut_ptr() as u64,
&mut read,
)
};
answer == libc::KERN_SUCCESS && read == into.len() as u64
}
/// [`read_pages`] where the system is not asked: nothing is copied.
#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn read_pages(_pages: NonNull<u8>, _into: &mut [u8]) -> bool {
false
}
@@ -1840,6 +1840,22 @@ degradations! {
"the GPU's writes through it reach the pages, and the CPU then reads them there, \
where after Metal's GPU writes into pages the process maps read-only the CPU reads \
them as they were (an M3 Max under macOS 27.0.1, private and shared memory alike)";
/// A no-copy buffer, a no-copy heap or a buffer's rebind was made over a copy of the
/// caller's host pages in memory of the device's own, which no import maps (`copied.rs`;
/// a heap's textures shadows of its bytes): the caller's gate
/// (`HostMemory::with_import_gate`) refused the pages' import, or the import the device
/// and the gate admitted failed (out of memory, or another Vulkan error, such as a
/// driver out of the mappings the host kernel allows). A copy whose own allocation fails
/// refuses the call (`OutOfMemory`). Announced once per device, by the call that makes
/// it, or at each such call where `DeviceOptions::announce_each` asks. Counted:
/// `WorkCounts::copied_host_buffers_made`.
CopiedHostPages = "copied-host-pages", Precision,
"the GPU uses a copy of the bytes, into which each commit writes every byte the CPU \
changed in the pages since, and from which each batch's completion writes back \
every byte the GPU changed, where Metal's GPU reads and writes the pages \
themselves: a CPU write the GPU reads mid-command-buffer, or a GPU write the CPU \
reads before the batch completes (behind a shared event's value among them), is \
not seen, and each commit and completion compares every byte of every copy";
/// Batches of command buffers committed on one queue that the scheduler found ready
/// together, or held while two or more earlier submissions of their queue ran, went to the
/// driver in one `vkQueueSubmit`, only the last signalling its queue's timeline and their
@@ -434,6 +434,13 @@ pub(super) struct DeviceShared {
pub(super) rebinds: super::rebind::Rebinds,
/// The no-copy buffers by the host memory they were made over (`host_aliases.rs`).
pub(super) aliases: super::host_aliases::HostAliases,
/// Its copied host buffers, compared at each commit and each batch's completion
/// (`copied.rs`).
pub(crate) copied: Arc<super::copied::CopiedBuffers>,
/// How many of the next imports of host pages by their pointer fail as the driver's out of
/// device memory: for the tests of `copied.rs` (`Device::fail_next_host_imports`).
#[cfg(test)]
pub(crate) failing_host_imports: std::sync::atomic::AtomicU64,
/// The logs of its shadows over host pages a consumer logs the writes to
/// (`dirty_pages.rs`).
pub(super) dirty: super::dirty_pages::DirtyShadows,
@@ -944,6 +951,16 @@ pub(super) fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))]
impl Device {
/// Fail the next `count` imports of host pages by their pointer as the driver's out of device
/// memory: the tests' stand-in for an import the device and the gate admitted that then fails
/// (`copied.rs`).
pub(crate) fn fail_next_host_imports(&self, count: u64) {
(self.shared().failing_host_imports).store(count, Ordering::Relaxed);
}
}
impl Device {
/// `registryID`: an identifier of the physical device, from its `deviceUUID`.
pub fn registry_id(&self) -> u64 {
@@ -1854,6 +1871,9 @@ impl Device {
heap_keys: Default::default(),
rebinds: Default::default(),
aliases: Default::default(),
copied: Default::default(),
#[cfg(test)]
failing_host_imports: Default::default(),
dirty: Default::default(),
fresh: Default::default(),
owners: Default::default(),
+7
View File
@@ -558,6 +558,13 @@ impl Device {
/// private option bit 24 the GPU's writes to the memory are dropped as a no-copy buffer's are
/// ([`Device::new_buffer_with_bytes_no_copy`]).
///
/// Where the caller's gate refuses the import
/// ([`HostMemory::with_import_gate`](crate::HostMemory::with_import_gate)), or the import the
/// device and the gate admitted fails (out of memory, another Vulkan error), the heap's own
/// buffer is a copy of the pages in memory of the device's own instead, its buffers lying in
/// the copy and its textures shadows of its bytes, announced (`copied-host-pages`,
/// `copied.rs`).
///
/// Refused: a size of 0 (`Nil`, as [`Device::new_heap`] answers it); storage other than
/// `Shared`, a sparse heap, an undefined option (`Invalid`); memory whose first byte is not a multiple of the import's unit
/// (`Invalid`, [`HeapProblem::HostMemoryAlignment`]); and as
+56 -1
View File
@@ -129,8 +129,44 @@ pub struct HostMemory {
writable: bool,
/// The caller's log of the pages written ([`HostMemory::with_dirty_pages`]).
dirty: Option<Arc<dyn DirtyHook>>,
/// The caller's gate over the import of the pages ([`HostMemory::with_import_gate`]).
gate: Option<ImportGate>,
}
/// A consumer's gate over the import of a no-copy object's pages (a runtime extension,
/// [`HostMemory::with_import_gate`]): asked once, just before the runtime imports the pages for a
/// no-copy buffer or heap made over them, or for a buffer's rebind to them
/// (`Buffer::rebind_bytes_no_copy`), with the pages the import would map. `true` lets the import
/// go on; `false` refuses it, and the buffer is a copied host buffer instead (the heap's own
/// buffer too, the rebind's new pages a copy of them), whose bytes the GPU uses in memory of the
/// device's own, kept coherent with the pages at each commit and each completion, so the pages
/// take no kernel mapping (`copied.rs`, docs/HOWTO.md, "Copied host buffers"). Called on the
/// thread that makes the buffer, heap or rebind, holding no lock of the runtime's. Not asked for a
/// buffer or rebind that lies in a live import (one made over the same bytes), nor where the device
/// refused the import before it (no host-pointer import, an import alignment the range cannot
/// meet), nor for memory whose GPU writes Metal's private option bit 24 drops, nor for a heap's
/// rebind, which imports without asking. An import it lets go on that then fails (out of memory,
/// another Vulkan error) makes the copy all the same. Every copy is announced
/// (`copied-host-pages`). No Metal counterpart.
pub type ImportGate = Arc<dyn Fn(ImportRequest) -> bool + Send + Sync + 'static>;
/// The pages an [`ImportGate`] is asked about: those an import would map for the buffer, from the
/// host page its first byte lies in through the one its last lies in.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ImportRequest {
/// The first byte of the first page.
pub start: NonNull<u8>,
/// The bytes of the pages.
pub length: u64,
}
// SAFETY: a request is an address and a length, plain data: nothing is reached through the
// address.
unsafe impl Send for ImportRequest {}
// SAFETY: as above.
unsafe impl Sync for ImportRequest {}
/// What a [`HostMemory`] may carry besides its pointer: a [`DmaBufSource`] where the system has
/// file descriptors, nothing elsewhere.
#[cfg(unix)]
@@ -155,6 +191,7 @@ impl std::fmt::Debug for HostMemory {
.field("dma_buf", &self.source.is_some())
.field("writable", &self.writable)
.field("dirty_pages", &self.dirty.is_some())
.field("import_gate", &self.gate.is_some())
.finish()
}
}
@@ -194,6 +231,7 @@ impl HostMemory {
source: None,
writable: false,
dirty: None,
gate: None,
}
}
@@ -240,6 +278,7 @@ impl HostMemory {
source: Some(source),
writable: false,
dirty: None,
gate: None,
}
}
@@ -309,6 +348,19 @@ impl HostMemory {
}
}
/// This memory, with the caller's gate over the import of its pages (a runtime extension,
/// [`ImportGate`]): asked once, just before a no-copy buffer or heap made over it, or a
/// buffer's rebind to it, imports the pages; where it answers `false`, the buffer is a copied
/// host buffer (the heap's own buffer too, the rebind's new pages a copy), which no import maps,
/// announced (`copied-host-pages`) and counted (`WorkCounts::host_imports_refused_by_host`,
/// `WorkCounts::copied_host_buffers_refused`). No Metal counterpart.
pub fn with_import_gate(self, gate: ImportGate) -> HostMemory {
HostMemory {
gate: Some(gate),
..self
}
}
/// The pointer.
pub fn pointer(&self) -> NonNull<u8> {
self.pointer
@@ -316,7 +368,8 @@ impl HostMemory {
/// The pointer, the dma-buf source where the caller gave one, whether the caller vouched
/// for the pages' write permission ([`HostMemory::assume_writable`]), and its log of the pages
/// written ([`HostMemory::with_dirty_pages`]), kept with the pointer its offsets count from.
/// written ([`HostMemory::with_dirty_pages`]), kept with the pointer its offsets count from,
/// and its gate over their import ([`HostMemory::with_import_gate`]).
pub(super) fn into_parts(self) -> HostParts {
let dirty = (self.dirty).map(|hook| DirtySource::new(hook, self.pointer.as_ptr() as u64));
HostParts {
@@ -324,6 +377,7 @@ impl HostMemory {
source: self.source,
writable: self.writable,
dirty,
gate: self.gate,
}
}
}
@@ -334,6 +388,7 @@ pub(super) struct HostParts {
pub(super) source: Option<Source>,
pub(super) writable: bool,
pub(super) dirty: Option<Arc<DirtySource>>,
pub(super) gate: Option<ImportGate>,
}
/// A no-copy buffer's deallocator (Metal's block): called once, with the pointer and the length,
@@ -299,7 +299,7 @@ impl ClassPages {
/// A no-copy buffer of `length` bytes over anonymous pages mapped for it, imported by their
/// pointer, which its keep-alive unmaps ([`Anonymous`]). `None` where the device makes none, or
/// does not import the pointer (dma-bufs).
/// does not import the pointer (dma-bufs, or a copied host buffer, `copied.rs`).
#[cfg(unix)]
fn pointer_pages(device: &Device, length: u64) -> Option<ClassPages> {
let start = map_anonymous(length)?;
@@ -308,7 +308,7 @@ fn pointer_pages(device: &Device, length: u64) -> Option<ClassPages> {
// which stays until the keep-alive unmaps it, and which nothing else maps or frees.
let memory = unsafe { HostMemory::new(start) };
let buffer = no_copy_kept(device, memory, length, pages)?;
if buffer.over_dma_buf() {
if buffer.over_dma_buf() || buffer.copied() {
return None;
}
Some(ClassPages { buffer, start })
+2 -1
View File
@@ -58,6 +58,7 @@ mod command_buffer;
mod compressed_blit;
mod compute;
mod contexts;
mod copied;
mod copy_plan;
mod creation;
mod deferred;
@@ -290,7 +291,7 @@ pub use function_table::{
pub use gpu_time::host_time;
pub use heap::{Heap, HeapDescriptor, HeapProblem, HeapType, SizeAndAlign};
pub use host_bytes::HostBytes;
pub use host_memory::{Deallocator, HostMemory, KeepAlive};
pub use host_memory::{Deallocator, HostMemory, ImportGate, ImportRequest, KeepAlive};
pub use indirect_command_buffer::{
EncodedComputeCommand, EncodedRenderCommand, IndirectBufferBinding, IndirectCommand,
IndirectCommandBuffer, IndirectCommandBufferDescriptor, IndirectCommandBufferProblem,
@@ -682,6 +682,12 @@ impl Mapped {
pub(super) fn as_ptr(self) -> *mut u8 {
self.0.as_ptr()
}
/// The caller's bytes at `pointer`, as the host address of a copied host buffer's memory
/// (`copied.rs`): its `contents`, which the runtime's comparisons keep coherent with the copy.
pub(super) fn of_caller(pointer: NonNull<u8>) -> Mapped {
Mapped(pointer)
}
}
/// One `VkDeviceMemory` block.
@@ -903,6 +903,13 @@ impl Buffer {
/// memory from its next use, and one whose linear image aliases its bytes has its image made
/// again over the new memory before the call returns; nothing of the old contents is copied.
///
/// Where the caller's gate refuses the new pages' import
/// ([`HostMemory::with_import_gate`](crate::HostMemory::with_import_gate)), or the import the
/// device and the gate admitted fails (out of memory, another Vulkan error), the buffer is
/// given a copy of the new pages in memory of the device's own instead, its `contents` the new
/// pointer, announced (`copied-host-pages`, `copied.rs`); refused instead where an image in
/// place aliases the buffer's bytes (`NotImplemented(RebindTextures)`).
///
/// Refused: a buffer that is not a no-copy buffer of its own (`Invalid`,
/// [`RebindProblem::NotHostMemory`]); a command buffer not yet committed whose commands used
/// the buffer, or an open encoder that did (a render encoder with an attachment over it, from
@@ -0,0 +1,59 @@
//! The comparisons that keep a copied host buffer coherent with the caller's pages (`copied.rs`),
//! on plain memory: a commit's copy in writes the bytes the CPU changed alone, and a completion's
//! merge back writes the bytes the GPU changed alone, keeping a byte the CPU changed since.
use crate::copied::sync;
use std::ptr::NonNull;
/// `bytes` as a pointer the comparison reads or writes.
fn at(bytes: &mut [u8]) -> NonNull<u8> {
NonNull::new(bytes.as_mut_ptr()).unwrap()
}
#[test]
fn copied_copy_in_writes_the_bytes_the_cpu_changed_alone() {
let mut snapshot: Vec<u8> = (0..37).collect();
let mut pages = snapshot.clone();
// The GPU changed byte 1 of the copy, not yet merged back.
let mut copy = snapshot.clone();
copy[1] = 0xEE;
// The CPU changed byte 2, in the same word, and byte 36, in the last, short span.
pages[2] = 0xAA;
pages[36] = 0xBB;
// SAFETY: three buffers of the snapshot's length.
let written = unsafe { sync(at(&mut pages), at(&mut copy), &mut snapshot, false) };
assert_eq!(written, 2);
assert_eq!(copy[1], 0xEE, "the GPU's byte in the same word stays");
assert_eq!((copy[2], copy[36]), (0xAA, 0xBB), "the CPU's bytes are in");
assert_eq!((snapshot[2], snapshot[36]), (0xAA, 0xBB));
assert_eq!(snapshot[1], 1, "the GPU's byte is not agreed yet");
}
#[test]
fn copied_merge_back_keeps_a_byte_the_cpu_changed_since() {
let mut snapshot: Vec<u8> = (0..16).collect();
let mut pages = snapshot.clone();
let mut copy = snapshot.clone();
// The GPU wrote bytes 3, 4 and 9; the CPU wrote byte 4 too, and byte 5, since the commit.
copy[3] = 0x33;
copy[4] = 0x44;
copy[9] = 0x99;
pages[4] = 0xC4;
pages[5] = 0xC5;
// SAFETY: three buffers of the snapshot's length.
let written = unsafe { sync(at(&mut copy), at(&mut pages), &mut snapshot, true) };
assert_eq!(written, 2, "bytes 3 and 9");
assert_eq!(
(pages[3], pages[9]),
(0x33, 0x99),
"the GPU's bytes are back"
);
assert_eq!((pages[4], pages[5]), (0xC4, 0xC5), "the CPU's bytes stay");
// The next copy in carries the CPU's byte 4 (and 5) into the copy.
// SAFETY: as above.
let written = unsafe { sync(at(&mut pages), at(&mut copy), &mut snapshot, false) };
assert_eq!(written, 2);
assert_eq!((copy[4], copy[5]), (0xC4, 0xC5));
assert_eq!(snapshot, pages, "they agree");
assert_eq!(copy, pages);
}
@@ -0,0 +1,636 @@
//! Copied host buffers on a device (`copied.rs`): a no-copy buffer whose import the caller's gate
//! refuses, or whose import the gate and the device admitted and that then failed, is made over a
//! copy of its pages, whose reads and writes match the caller's bytes at the commit and at the
//! completion.
//!
//! - **The gate refuses.** The gate is asked once, with the buffer's pages, and the buffer is a
//! copy: no import of the pages is made, its `contents` is the pointer, and the copy is
//! announced (`copied-host-pages`) and counted as a refusal.
//! - **The admitted import fails.** The gate admits the import, which the driver then fails (the
//! tests' stand-in, `Device::fail_next_host_imports`, answers it as out of device memory): the
//! buffer is a copy all the same, announced and counted as degraded; the next buffer imports.
//! The same without a gate.
//! - **Coherence.** In each, the GPU reads the caller's bytes; a CPU write before a commit reaches
//! the GPU, those bytes alone copied in; a fill reaches the caller's pages at its completion,
//! those bytes alone merged back.
//! - **Unreadable pages** (mapped without access, memory Metal makes no buffer over) are never
//! copied: the buffer is refused, as their import is.
//! - **Rebinds.** A rebind's new pages are a copy where the gate refuses their import or the
//! admitted import fails, with the same coherence; the old pages stay as they were, and a later
//! rebind imports again.
//! - **Heaps.** A no-copy heap's own buffer is a copy in the same two cases; a buffer placed in
//! it reads the caller's bytes at its offset, and a fill through it reaches those pages alone.
//!
//! Device tests: compiled only under the GPU safety cfgs (`m2v_gpu`, `m2v_cpu_icd`), on the kind
//! of device the cfg selects. A device that imports no host memory says so and passes.
use crate::{
Buffer, CommandBufferStatus, Degradation, Device, DeviceKind, DeviceOptions, HostMemory,
ImportGate, ImportRequest, MessageSink, ResourceOptions, WorkCounts,
};
use std::alloc::Layout;
use std::ptr::NonNull;
use std::sync::{Arc, Mutex};
use std::time::Duration;
const WAIT: Duration = Duration::from_secs(60);
/// The bytes of each host memory.
const LENGTH: usize = 64 * 1024;
/// Host memory of whole pages, in a pattern of its own, freed when dropped (after the device).
struct Host {
pointer: NonNull<u8>,
layout: Layout,
seed: u8,
}
impl Host {
fn new(seed: u8) -> Host {
let layout = Layout::from_size_align(LENGTH, 1 << 16).unwrap();
// SAFETY: the layout's size is not zero.
let pointer = NonNull::new(unsafe { std::alloc::alloc(layout) }).unwrap();
let host = Host {
pointer,
layout,
seed,
};
host.write(0, &host.pattern());
host
}
/// The pattern it was made with.
fn pattern(&self) -> Vec<u8> {
(0..LENGTH)
.map(|i| ((i % 251) as u8).wrapping_add(self.seed.wrapping_mul(37)))
.collect()
}
/// Its bytes, read while no command buffer runs.
fn bytes(&self) -> Vec<u8> {
// SAFETY: the allocation's bytes, which no command buffer writes now.
unsafe { std::slice::from_raw_parts(self.pointer.as_ptr(), LENGTH) }.to_vec()
}
/// Write `bytes` at `at`, while no command buffer runs.
fn write(&self, at: usize, bytes: &[u8]) {
assert!(at + bytes.len() <= LENGTH);
// SAFETY: the allocation's bytes, which no command buffer uses now.
unsafe {
std::ptr::copy_nonoverlapping(
bytes.as_ptr(),
self.pointer.as_ptr().add(at),
bytes.len(),
)
};
}
/// A no-copy buffer over all of it, under a gate where given.
fn buffer(&self, device: &Device, gate: Option<ImportGate>) -> Buffer {
// SAFETY: the memory outlives every buffer over it and the device (dropped after both),
// and only the buffers' commands and the tests' reads between command buffers use it.
let memory = unsafe { HostMemory::new(self.pointer) };
let memory = match gate {
Some(gate) => memory.with_import_gate(gate),
None => memory,
};
// SAFETY: as above.
unsafe {
device.new_buffer_with_bytes_no_copy(
memory,
LENGTH as u64,
ResourceOptions::default(),
None,
)
}
.unwrap()
}
}
impl Drop for Host {
fn drop(&mut self) {
// SAFETY: allocated with this layout.
unsafe { std::alloc::dealloc(self.pointer.as_ptr(), self.layout) };
}
}
/// The degrade notices a device announced.
type Heard = Arc<Mutex<Vec<Degradation>>>;
/// A device of the cfg's kind, its notices into the answer's list; `None` where it imports no
/// host memory.
fn device() -> Option<(Device, Heard)> {
let heard: Heard = Arc::default();
let hearing = Arc::clone(&heard);
let options = DeviceOptions {
kinds: match cfg!(m2v_cpu_icd) {
true => vec![DeviceKind::Cpu],
false => vec![
DeviceKind::Discrete,
DeviceKind::Integrated,
DeviceKind::Virtual,
],
},
messages: Some(MessageSink::new(move |message| {
if let Some(notice) = &message.degradation {
hearing.lock().unwrap().push(notice.degradation);
}
})),
..DeviceOptions::default()
};
let device = Device::system_default_with(&options).unwrap();
if device.shared().host_import.is_err() {
eprintln!("COPIED: the device imports no host memory here; nothing to test");
return None;
}
Some((device, heard))
}
/// A gate answering `answer`, each request it is asked into `asked`.
fn gate(asked: &Arc<Mutex<Vec<ImportRequest>>>, answer: bool) -> ImportGate {
let asked = Arc::clone(asked);
Arc::new(move |request| {
asked.lock().unwrap().push(request);
answer
})
}
/// Commit one command buffer whose blit encoder `encode` fills, and wait for it.
fn blit(device: &Device, encode: impl FnOnce(&mut crate::BlitCommandEncoder)) {
let queue = device.new_command_queue().unwrap();
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.blit_command_encoder().unwrap();
encode(&mut encoder);
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer.wait_until_completed_for(WAIT).unwrap();
assert_eq!(command_buffer.status(), CommandBufferStatus::Completed);
}
/// The buffer's bytes as the GPU reads them: copied into one of the device's own, read there.
fn gpu_bytes(device: &Device, buffer: &Buffer) -> Vec<u8> {
let own = device
.new_buffer(LENGTH as u64, ResourceOptions::shared())
.unwrap();
blit(device, |encoder| {
encoder
.copy_from_buffer_to_buffer(buffer, 0, &own, 0, LENGTH as u64)
.unwrap();
});
let contents = own.contents().unwrap();
// SAFETY: the buffer's bytes, which no command writes now.
unsafe { std::slice::from_raw_parts(contents.as_ptr(), LENGTH) }.to_vec()
}
/// `buffer` lies in a copy of `host`'s pages: the GPU reads its bytes; a CPU write before a
/// commit reaches the GPU, those bytes alone copied in; a fill reaches its pages alone, those
/// bytes alone merged back.
fn lies_in_a_copy(device: &Device, buffer: &Buffer, host: &Host) {
assert!(buffer.copied(), "the buffer is a copy");
assert_eq!(
buffer.contents(),
Some(host.pointer),
"contents are the pointer"
);
assert_eq!(
gpu_bytes(device, buffer),
host.pattern(),
"the GPU reads the bytes"
);
// A CPU write before the commit reaches the GPU: only the bytes it changed are copied in.
let pattern = host.pattern();
let changed_in = pattern[..4096].iter().filter(|&&byte| byte != 0xC3).count() as u64;
let before = device.work_counts();
host.write(0, &[0xC3; 4096]);
let read = gpu_bytes(device, buffer);
let after_read = device.work_counts();
assert!(
read[..4096].iter().all(|&byte| byte == 0xC3),
"the GPU reads the CPU's write"
);
assert_eq!(read[4096..], pattern[4096..], "and the bytes after it");
assert_eq!(
after_read.copied_copy_in_bytes - before.copied_copy_in_bytes,
changed_in,
"the commit copies in the bytes the CPU changed alone"
);
// A fill reaches the pages at its completion: only the bytes it changed are merged back.
let changed_back = pattern[4096..8192]
.iter()
.filter(|&&byte| byte != 0x5A)
.count() as u64;
blit(device, |encoder| {
encoder.fill_buffer(buffer, 4096..8192, 0x5A).unwrap();
});
let filled = device.work_counts();
let bytes = host.bytes();
assert!(
bytes[4096..8192].iter().all(|&byte| byte == 0x5A),
"the fill reached the pages"
);
assert!(
bytes[..4096].iter().all(|&byte| byte == 0xC3),
"the bytes before it stay"
);
assert_eq!(bytes[8192..], pattern[8192..], "the bytes after it stay");
assert_eq!(
filled.copied_merge_back_bytes - after_read.copied_merge_back_bytes,
changed_back,
"the fill's bytes alone were merged back"
);
eprintln!(
"COPIED: copied in {} bytes, merged back {}",
after_read.copied_copy_in_bytes - before.copied_copy_in_bytes,
filled.copied_merge_back_bytes - after_read.copied_merge_back_bytes
);
}
/// The differences between two counts that a no-copy buffer's making moves: gate refusals,
/// copies made, of them refused and degraded, and pointer imports made.
fn moved(before: &WorkCounts, after: &WorkCounts) -> [u64; 5] {
[
after.host_imports_refused_by_host - before.host_imports_refused_by_host,
after.copied_host_buffers_made - before.copied_host_buffers_made,
after.copied_host_buffers_refused - before.copied_host_buffers_refused,
after.copied_host_buffers_degraded - before.copied_host_buffers_degraded,
after.host_pointer_imports_made - before.host_pointer_imports_made,
]
}
/// How many of `heard` are `copied-host-pages`.
fn announced(heard: &Heard) -> usize {
let notices = heard.lock().unwrap();
notices
.iter()
.filter(|&&kind| kind == Degradation::CopiedHostPages)
.count()
}
#[test]
fn copied_buffer_is_made_where_the_caller_s_gate_refuses_the_import() {
let (host, other) = (Host::new(1), Host::new(2));
let Some((device, heard)) = device() else {
return;
};
let asked: Arc<Mutex<Vec<ImportRequest>>> = Arc::default();
let before = device.work_counts();
let buffer = host.buffer(&device, Some(gate(&asked, false)));
let after = device.work_counts();
// Refused: a copy made, counted as a refusal, no import made.
assert_eq!(moved(&before, &after), [1, 1, 1, 0, 0]);
let requests = asked.lock().unwrap().clone();
assert_eq!(requests.len(), 1, "the gate was asked once");
assert_eq!(requests[0].start, host.pointer, "from the first page");
assert_eq!(requests[0].length, LENGTH as u64, "through the last");
assert_eq!(announced(&heard), 1, "announced once");
lies_in_a_copy(&device, &buffer, &host);
// A gate that admits it lets the import go on.
let before = device.work_counts();
let imported = other.buffer(&device, Some(gate(&asked, true)));
let after = device.work_counts();
assert_eq!(moved(&before, &after), [0, 0, 0, 0, 1]);
assert!(!imported.copied(), "imported");
assert_eq!(gpu_bytes(&device, &imported), other.pattern());
assert_eq!(asked.lock().unwrap().len(), 2, "asked once more");
drop((buffer, imported));
}
#[test]
fn copied_buffer_is_made_where_an_admitted_import_fails_announced() {
let (host, other) = (Host::new(3), Host::new(4));
let Some((device, heard)) = device() else {
return;
};
let asked: Arc<Mutex<Vec<ImportRequest>>> = Arc::default();
let before = device.work_counts();
device.fail_next_host_imports(1);
let buffer = host.buffer(&device, Some(gate(&asked, true)));
let after = device.work_counts();
// Admitted, its import failed: a copy made, degraded, no refusal.
assert_eq!(moved(&before, &after), [0, 1, 0, 1, 0]);
assert_eq!(asked.lock().unwrap().len(), 1, "the gate was asked once");
assert_eq!(announced(&heard), 1, "announced once");
lies_in_a_copy(&device, &buffer, &host);
// With no failure left, the next buffer imports its pages.
let before = device.work_counts();
let imported = other.buffer(&device, Some(gate(&asked, true)));
let after = device.work_counts();
assert_eq!(moved(&before, &after), [0, 0, 0, 0, 1]);
assert_eq!(gpu_bytes(&device, &imported), other.pattern());
assert_eq!(announced(&heard), 1, "nothing more announced");
drop((buffer, imported));
}
#[test]
fn copied_buffer_without_a_gate_whose_import_fails_is_made_announced() {
let host = Host::new(5);
let Some((device, heard)) = device() else {
return;
};
let before = device.work_counts();
device.fail_next_host_imports(1);
let buffer = host.buffer(&device, None);
let after = device.work_counts();
assert_eq!(moved(&before, &after), [0, 1, 0, 1, 0]);
assert_eq!(announced(&heard), 1, "announced once");
lies_in_a_copy(&device, &buffer, &host);
}
/// Pages mapped without access are memory Metal makes no buffer over: a refusing gate makes no
/// copy of them (reading them would fault), and the buffer is refused.
#[cfg(unix)]
#[test]
fn copied_buffer_is_never_made_over_pages_the_process_cannot_read() {
let Some((device, heard)) = device() else {
return;
};
// SAFETY: a new private anonymous mapping without access, at an address the kernel chooses.
let mapped = unsafe {
libc::mmap(
std::ptr::null_mut(),
LENGTH,
libc::PROT_NONE,
libc::MAP_PRIVATE | libc::MAP_ANON,
-1,
0,
)
};
assert_ne!(mapped, libc::MAP_FAILED);
let pointer = NonNull::new(mapped.cast::<u8>()).unwrap();
let asked: Arc<Mutex<Vec<ImportRequest>>> = Arc::default();
let before = device.work_counts();
// SAFETY: the buffer is refused before anything reads the pages (the test's claim); the
// mapping outlives the call.
let made = unsafe {
device.new_buffer_with_bytes_no_copy(
HostMemory::new(pointer).with_import_gate(gate(&asked, false)),
LENGTH as u64,
ResourceOptions::default(),
None,
)
};
let after = device.work_counts();
assert!(made.is_err(), "refused: {made:?}");
assert_eq!(
after.copied_host_buffers_made,
before.copied_host_buffers_made
);
assert_eq!(announced(&heard), 0, "nothing announced");
// SAFETY: the mapping made above, which nothing uses.
assert_eq!(unsafe { libc::munmap(mapped, LENGTH) }, 0);
}
/// Rebind `buffer` to all of `host`, under a gate where given.
fn rebind(buffer: &Buffer, host: &Host, gate: Option<ImportGate>) -> Result<(), crate::Error> {
// SAFETY: the memory outlives every buffer over it and the device (dropped after both), and
// no command that uses the buffer is encoded or pending.
let memory = unsafe { HostMemory::new(host.pointer) };
let memory = match gate {
Some(gate) => memory.with_import_gate(gate),
None => memory,
};
// SAFETY: as above.
unsafe { buffer.rebind_bytes_no_copy(memory, None, None) }
}
#[test]
fn copied_rebind_pages_are_made_where_the_caller_s_gate_refuses_the_import() {
let (first, second) = (Host::new(6), Host::new(7));
let Some((device, heard)) = device() else {
return;
};
let buffer = first.buffer(&device, None);
assert!(!buffer.copied(), "imported first");
let asked: Arc<Mutex<Vec<ImportRequest>>> = Arc::default();
let before = device.work_counts();
rebind(&buffer, &second, Some(gate(&asked, false))).unwrap();
let after = device.work_counts();
assert_eq!(moved(&before, &after), [1, 1, 1, 0, 0]);
assert_eq!(
after.copied_rebind_pages_made - before.copied_rebind_pages_made,
1
);
let requests = asked.lock().unwrap().clone();
assert_eq!(requests.len(), 1, "the gate was asked once");
assert_eq!(requests[0].start, second.pointer, "with the new pages");
assert_eq!(requests[0].length, LENGTH as u64);
assert_eq!(announced(&heard), 1, "announced once");
lies_in_a_copy(&device, &buffer, &second);
assert_eq!(
first.bytes(),
first.pattern(),
"the old pages stay as they were"
);
// Rebound again with no gate, it imports.
let before = device.work_counts();
rebind(&buffer, &first, None).unwrap();
let after = device.work_counts();
assert_eq!(moved(&before, &after), [0, 0, 0, 0, 1]);
assert!(!buffer.copied(), "imported again");
assert_eq!(gpu_bytes(&device, &buffer), first.pattern());
}
#[test]
fn copied_rebind_pages_are_made_where_an_admitted_import_fails_announced() {
let (first, second) = (Host::new(8), Host::new(9));
let Some((device, heard)) = device() else {
return;
};
let buffer = first.buffer(&device, None);
let asked: Arc<Mutex<Vec<ImportRequest>>> = Arc::default();
let before = device.work_counts();
device.fail_next_host_imports(1);
rebind(&buffer, &second, Some(gate(&asked, true))).unwrap();
let after = device.work_counts();
assert_eq!(moved(&before, &after), [0, 1, 0, 1, 0]);
assert_eq!(
after.copied_rebind_pages_made - before.copied_rebind_pages_made,
1
);
assert_eq!(asked.lock().unwrap().len(), 1, "the gate was asked once");
assert_eq!(announced(&heard), 1, "announced once");
lies_in_a_copy(&device, &buffer, &second);
assert_eq!(
first.bytes(),
first.pattern(),
"the old pages stay as they were"
);
}
/// A no-copy placement heap over all of `host`, under a gate where given.
fn heap(device: &Device, host: &Host, gate: Option<ImportGate>) -> crate::Heap {
// SAFETY: the memory outlives every heap over it and the device (dropped after both), and
// only the heap's resources' commands and the tests' reads between command buffers use it.
let memory = unsafe { HostMemory::new(host.pointer) };
let memory = match gate {
Some(gate) => memory.with_import_gate(gate),
None => memory,
};
let descriptor = crate::HeapDescriptor::new(
crate::HeapType::Placement,
LENGTH as u64,
ResourceOptions::default(),
);
// SAFETY: as above.
unsafe { device.new_heap_with_bytes_no_copy(memory, &descriptor, None, None) }.unwrap()
}
#[test]
fn copied_heap_is_made_where_the_caller_s_gate_refuses_the_import() {
let (host, other) = (Host::new(10), Host::new(11));
let Some((device, heard)) = device() else {
return;
};
let asked: Arc<Mutex<Vec<ImportRequest>>> = Arc::default();
let before = device.work_counts();
let copied = heap(&device, &host, Some(gate(&asked, false)));
let after = device.work_counts();
assert_eq!(moved(&before, &after), [1, 1, 1, 0, 0]);
assert_eq!(after.copied_heaps_made - before.copied_heaps_made, 1);
let requests = asked.lock().unwrap().clone();
assert_eq!(requests.len(), 1, "the gate was asked once");
assert_eq!(requests[0].start, host.pointer);
assert_eq!(requests[0].length, LENGTH as u64);
assert_eq!(announced(&heard), 1, "announced once");
// Its hazard tracking is an imported heap's.
let imported = heap(&device, &other, None);
assert_eq!(
copied.hazard_tracking_mode(),
imported.hazard_tracking_mode()
);
// A buffer placed at 16 KiB reads the caller's bytes there; a fill through it reaches those
// pages alone, merged back.
let at = 16 * 1024;
let buffer = copied
.new_buffer_at_offset(LENGTH as u64 - at, ResourceOptions::default(), at)
.unwrap();
let own = device
.new_buffer(LENGTH as u64 - at, ResourceOptions::shared())
.unwrap();
blit(&device, |encoder| {
encoder
.copy_from_buffer_to_buffer(&buffer, 0, &own, 0, LENGTH as u64 - at)
.unwrap();
});
let pattern = host.pattern();
let contents = own.contents().unwrap();
// SAFETY: the buffer's bytes, which no command writes now.
let read = unsafe { std::slice::from_raw_parts(contents.as_ptr(), LENGTH - at as usize) };
assert_eq!(
read,
&pattern[at as usize..],
"the GPU reads the heap's bytes"
);
let before = device.work_counts();
blit(&device, |encoder| {
encoder.fill_buffer(&buffer, 0..4096, 0x5A).unwrap();
});
let after = device.work_counts();
let bytes = host.bytes();
let (start, end) = (at as usize, at as usize + 4096);
assert!(bytes[start..end].iter().all(|&byte| byte == 0x5A));
assert_eq!(bytes[..start], pattern[..start], "the bytes before it stay");
assert_eq!(bytes[end..], pattern[end..], "the bytes after it stay");
let changed = pattern[start..end].iter().filter(|&&b| b != 0x5A).count() as u64;
assert_eq!(
after.copied_merge_back_bytes - before.copied_merge_back_bytes,
changed
);
drop((buffer, copied, imported));
}
#[test]
fn copied_heap_is_made_where_an_admitted_import_fails_announced() {
let host = Host::new(12);
let Some((device, heard)) = device() else {
return;
};
let before = device.work_counts();
device.fail_next_host_imports(1);
let copied = heap(&device, &host, None);
let after = device.work_counts();
assert_eq!(moved(&before, &after), [0, 1, 0, 1, 0]);
assert_eq!(after.copied_heaps_made - before.copied_heaps_made, 1);
assert_eq!(announced(&heard), 1, "announced once");
drop(copied);
}
#[test]
fn copied_heap_s_texture_keeps_its_texels_in_the_caller_s_pages() {
let host = Host::new(13);
let Some((device, _heard)) = device() else {
return;
};
let asked: Arc<Mutex<Vec<ImportRequest>>> = Arc::default();
let copied = heap(&device, &host, Some(gate(&asked, false)));
let mut descriptor = crate::TextureDescriptor::texture_2d(
metal2vulkan::metal::PixelFormat::RGBA8Unorm,
16,
16,
false,
);
descriptor.usage = metal2vulkan::metal::TextureUsage::SHADER_READ;
descriptor.resource_options = ResourceOptions::default();
let span = device
.heap_texture_size_and_align(&descriptor)
.unwrap()
.size as usize;
let texture = copied.new_texture_at_offset(&descriptor, 0).unwrap();
let bytes = 16 * 16 * 4;
let size = crate::Size::new(16, 16, 1);
let origin = crate::Origin { x: 0, y: 0, z: 0 };
let staging = device
.new_buffer_with_bytes(&[0xA5; 16 * 16 * 4], ResourceOptions::shared())
.unwrap();
let before = device.work_counts();
blit(&device, |encoder| {
encoder
.copy_from_buffer_to_texture(
&staging,
0,
16 * 4,
bytes,
size,
&texture,
0,
0,
origin,
crate::BlitOption::None,
)
.unwrap();
});
let after = device.work_counts();
// The texels reach the caller's pages in the texture's span alone, merged back.
let pattern = host.pattern();
assert_eq!(
host.bytes()[span..],
pattern[span..],
"past the texture's span"
);
assert!(after.copied_merge_back_bytes > before.copied_merge_back_bytes);
// A copy out of it reads them back.
let own = device.new_buffer(bytes, ResourceOptions::shared()).unwrap();
blit(&device, |encoder| {
encoder
.copy_from_texture_to_buffer(
&texture,
0,
0,
origin,
size,
&own,
0,
16 * 4,
bytes,
crate::BlitOption::None,
)
.unwrap();
});
let contents = own.contents().unwrap();
// SAFETY: the buffer's bytes, which no command writes now.
let read = unsafe { std::slice::from_raw_parts(contents.as_ptr(), bytes as usize) };
assert!(
read.iter().all(|&byte| byte == 0xA5),
"the texels read back"
);
drop((texture, copied));
}
@@ -43,6 +43,9 @@ mod completion_seen;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod compute;
mod contexts;
mod copied;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod copied_device;
#[cfg(any(m2v_gpu, m2v_cpu_icd))]
mod copy_bounds;
mod copy_plan;
@@ -2205,6 +2205,16 @@ impl Device {
texture was made"
.to_owned(),
)
} else if texels.buffer.copied() {
// A copied host buffer's bytes the GPU uses lie in memory of the device's
// own, no import of the pages (`copied.rs`): the shadow copies them, its
// copies the buffer's uses, which commits copy in and completions merge back.
ShadowCause::Refused(
Refusal::Placement,
"the buffer's bytes are a copy of the caller's pages in memory of the \
device's own, which no image over the pages lies in"
.to_owned(),
)
} else {
// The check's own textures measure the device whatever its policy.
let policy = match checking {
@@ -2389,6 +2389,28 @@ impl Device {
if p.image.route == AliasRoute::Tiled {
return Ok(p);
}
// A copied heap's bytes the GPU uses lie in a copy of the caller's pages (`copied.rs`),
// to which no image is bound: a shadow of them, as over pages no image takes, unless its
// route is one in memory of its own already.
if bytes.copied() {
if matches!(
p.image.route,
AliasRoute::Shadow
| AliasRoute::MemoryShadow
| AliasRoute::Unaliased
| AliasRoute::Planes
) {
return Ok(p);
}
let facts = self
.shared()
.textures
.facts(self.compile_device().profile());
let linear = plan_image(&p.layout, descriptor.image_usage(), false, &facts)
.map_err(|refusal| image_error(call, refusal))?;
let image = self.memory_shadow(linear, &p)?;
return Ok(HeapPlan { image, ..p });
}
if let HeapLayout::Tiled(tiled) = &p.metal_layout {
match self.tiled_heap_image(call, &p, tiled, descriptor)? {
Some(image) => return Ok(HeapPlan { image, ..p }),
@@ -290,6 +290,14 @@ pub(crate) struct Counters {
host_imports_remapped: AtomicU64,
host_pointer_imports_made: AtomicU64,
host_pointer_import_bytes_made: AtomicU64,
host_imports_refused_by_host: AtomicU64,
copied_host_buffers_made: AtomicU64,
copied_host_buffers_refused: AtomicU64,
copied_host_buffers_degraded: AtomicU64,
copied_rebind_pages_made: AtomicU64,
copied_heaps_made: AtomicU64,
copied_copy_in_bytes: AtomicU64,
copied_merge_back_bytes: AtomicU64,
dma_buf_sparse_buffers: AtomicU64,
dma_buf_images: AtomicU64,
dma_buf_image_fallbacks: AtomicU64,
@@ -1998,6 +2006,43 @@ impl Counters {
(self.host_pointer_import_bytes_made).fetch_add(bytes, Ordering::Relaxed);
}
/// The caller's import gate refused a no-copy buffer's import (`HostMemory::with_import_gate`).
pub(crate) fn host_import_refused_by_host(&self) {
(self.host_imports_refused_by_host).fetch_add(1, Ordering::Relaxed);
}
/// A copied host buffer was made (`copied.rs`): after an admitted import failed where
/// `degraded`, else for the gate's refusal.
pub(crate) fn copied_host_buffer_made(&self, degraded: bool) {
(self.copied_host_buffers_made).fetch_add(1, Ordering::Relaxed);
match degraded {
true => &self.copied_host_buffers_degraded,
false => &self.copied_host_buffers_refused,
}
.fetch_add(1, Ordering::Relaxed);
}
/// A no-copy heap's own buffer was made a copy of its pages (`copied.rs`).
pub(crate) fn copied_heap_made(&self) {
(self.copied_heaps_made).fetch_add(1, Ordering::Relaxed);
}
/// A rebind gave a buffer a copy of its new pages (`copied.rs`).
pub(crate) fn copied_rebind_pages_made(&self) {
(self.copied_rebind_pages_made).fetch_add(1, Ordering::Relaxed);
}
/// A commit copied `bytes` the CPU changed into copied host buffers (`copied.rs`).
pub(crate) fn copied_copied_in(&self, bytes: u64) {
(self.copied_copy_in_bytes).fetch_add(bytes, Ordering::Relaxed);
}
/// A batch's completion merged `bytes` the GPU changed back into the caller's pages
/// (`copied.rs`).
pub(crate) fn copied_merged_back(&self, bytes: u64) {
(self.copied_merge_back_bytes).fetch_add(bytes, Ordering::Relaxed);
}
/// A host import the device never releases while idle, for `because`, was made (`kept`), or
/// went.
pub(crate) fn host_import_kept(&self, because: KeptBecause, kept: bool) {
@@ -4256,6 +4301,31 @@ pub struct WorkCounts {
pub host_pointer_imports_made: u64,
/// Their bytes: whole pages, rounded out to the import's unit.
pub host_pointer_import_bytes_made: u64,
/// The no-copy buffers' imports the caller's gate refused (`HostMemory::with_import_gate`):
/// each made a copied host buffer instead (`copied_host_buffers_refused`).
pub host_imports_refused_by_host: u64,
/// The copied host buffers made (`copied-host-pages`): no-copy buffers whose bytes the GPU
/// uses in a copy of the caller's pages in memory of the device's own, which no import maps.
/// Each is one of the next two.
pub copied_host_buffers_made: u64,
/// Of those, the ones made because the caller's gate refused the import.
pub copied_host_buffers_refused: u64,
/// Of those, the ones made because an import the device and the gate admitted failed (out
/// of memory, another Vulkan error).
pub copied_host_buffers_degraded: 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,
/// Of the copies made, the no-copy heaps' own buffers (`Device::new_heap_with_bytes_no_copy`),
/// in `copied_host_buffers_made` and its kin too: the heap's buffers lie in the copy, and its
/// textures are shadows of its bytes.
pub copied_heaps_made: u64,
/// The bytes the CPU changed in copied host buffers' pages that commits copied into the
/// copies.
pub copied_copy_in_bytes: u64,
/// The bytes the GPU changed in copied host buffers' copies that batches' completions merged
/// back into the caller's pages.
pub copied_merge_back_bytes: u64,
/// The live host imports the device never releases while idle as a heap's own import (a
/// no-copy heap's). With the next three and `host_imports_kept_for_fds`, they are every live
/// no-copy import the device keeps imported whatever reads it.
@@ -5318,6 +5388,20 @@ impl Device {
host_pointer_import_bytes_made: counters
.host_pointer_import_bytes_made
.load(Ordering::Relaxed),
host_imports_refused_by_host: counters
.host_imports_refused_by_host
.load(Ordering::Relaxed),
copied_host_buffers_made: counters.copied_host_buffers_made.load(Ordering::Relaxed),
copied_host_buffers_refused: counters
.copied_host_buffers_refused
.load(Ordering::Relaxed),
copied_host_buffers_degraded: counters
.copied_host_buffers_degraded
.load(Ordering::Relaxed),
copied_rebind_pages_made: counters.copied_rebind_pages_made.load(Ordering::Relaxed),
copied_heaps_made: counters.copied_heaps_made.load(Ordering::Relaxed),
copied_copy_in_bytes: counters.copied_copy_in_bytes.load(Ordering::Relaxed),
copied_merge_back_bytes: counters.copied_merge_back_bytes.load(Ordering::Relaxed),
host_imports_lost: counters.host_imports_lost.load(Ordering::Relaxed),
host_import_fds_kept: counters.host_import_fds_kept.load(Ordering::Relaxed),
host_imports_kept_for_fds: counters.host_imports_kept_for_fds.load(Ordering::Relaxed),
@@ -1 +1 @@
cf96f6b5326a50e44684bbb23a25378bf4d88e870d3f37018a9d3c1f3090df18
7b97fe409765a767f4c23a117eeee0cbb4df62be4473820e013fb89051607958
@@ -446,7 +446,8 @@ pub(super) fn on_device_with(
/// Every kind is taken by a lane test's site: listed above, or a stage's precision note or
/// reconvergence; no kind is in two lists, and no list names a kind twice. `misplaced-notice`
/// ([`MISPLACED`]) is taken by the runtime's own tests instead, as no lane can meet it.
/// ([`MISPLACED`]) and `copied-host-pages` ([`COPIED_PAGES`]) are taken by the runtime's own tests
/// instead, as no lane can meet them.
///
/// This module compiles only under the device cfgs, so a kind that lands with no site leaves this
/// test red where the ordinary gate cannot read it. The runtime crate's
@@ -563,6 +564,7 @@ fn every_kind_has_a_site_a_lane_test_takes() {
&READ_ONLY_PAGES,
&MISPLACED,
&STILL_MAKING,
&COPIED_PAGES,
&DEPTH_DENORMALS,
&SIGNED_DEPTH_TESTS,
&FIRST_SPARSE,
@@ -778,6 +780,16 @@ const STILL_MAKING: [Degradation; 3] = [
Degradation::DrawDroppedUnmade,
];
/// The kind a no-copy buffer takes whose import of the caller's pages the caller's gate
/// (`HostMemory::with_import_gate`) refused, or whose import the gate and the device admitted and
/// that then failed, so the pages are copied. No lane meets it: no lane gives a gate, and no
/// venue's driver fails an admitted import on demand (NVIDIA's runs out of the host kernel's
/// mappings only past `vm.max_map_count`). The runtime's own tests
/// `copied_buffer_is_made_where_the_caller_s_gate_refuses_the_import` and
/// `copied_buffer_is_made_where_an_admitted_import_fails_announced` take its site, the import
/// failed by the runtime's test hook.
const COPIED_PAGES: [Degradation; 1] = [Degradation::CopiedHostPages];
/// The kind Metal's private option bit takes where the GPU's writes reach the memory here
/// ([`the_private_option_bit_is_announced_on_a_heap_of_the_runtime_s_memory`],
/// [`the_private_option_bit_drops_the_gpu_s_writes_to_no_copy_memory`]).
+1 -1
View File
@@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 477;
/// changes no behaviour, and then updates that hash alone with the commit saying why, or changes
/// behaviour and also bumps this version. The commit that bumps it says what changed; this comment
/// keeps no history.
pub const RUNTIME_VERSION: u32 = 1689;
pub const RUNTIME_VERSION: u32 = 1690;
/// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex,
/// of the manifest, the build script, and exactly the files the crate roots' module tree compiles
@@ -2072,6 +2072,8 @@ field metal2vulkan-runtime::HeapDescriptor.placement pub placement: AddressPlace
field metal2vulkan-runtime::HeapDescriptor.resource_options pub resource_options: ResourceOptions
field metal2vulkan-runtime::HeapDescriptor.size pub size: u64
field metal2vulkan-runtime::HeapDescriptor.sparse_page_size pub sparse_page_size: SparsePageSize
field metal2vulkan-runtime::ImportRequest.length pub length: u64
field metal2vulkan-runtime::ImportRequest.start pub start: NonNull<u8>
field metal2vulkan-runtime::IndirectBufferBinding.address pub address: GpuAddress
field metal2vulkan-runtime::IndirectBufferBinding.attribute_stride pub attribute_stride: Option<u64>
field metal2vulkan-runtime::IndirectCommandBufferDescriptor.allow_override_render_states pub allow_override_render_states: i64
@@ -2467,6 +2469,13 @@ field metal2vulkan-runtime::WorkCounts.completion_arms pub completion_arms: u64
field metal2vulkan-runtime::WorkCounts.completion_arms_after_a_wake pub completion_arms_after_a_wake: u64
field metal2vulkan-runtime::WorkCounts.completion_reads_ran_ahead pub completion_reads_ran_ahead: u64
field metal2vulkan-runtime::WorkCounts.compute_pipeline_create_nanos pub compute_pipeline_create_nanos: u64
field metal2vulkan-runtime::WorkCounts.copied_copy_in_bytes pub copied_copy_in_bytes: u64
field metal2vulkan-runtime::WorkCounts.copied_heaps_made pub copied_heaps_made: u64
field metal2vulkan-runtime::WorkCounts.copied_host_buffers_degraded pub copied_host_buffers_degraded: u64
field metal2vulkan-runtime::WorkCounts.copied_host_buffers_made pub copied_host_buffers_made: u64
field metal2vulkan-runtime::WorkCounts.copied_host_buffers_refused pub copied_host_buffers_refused: u64
field metal2vulkan-runtime::WorkCounts.copied_merge_back_bytes pub copied_merge_back_bytes: u64
field metal2vulkan-runtime::WorkCounts.copied_rebind_pages_made pub copied_rebind_pages_made: u64
field metal2vulkan-runtime::WorkCounts.copy_regions_split pub copy_regions_split: u64
field metal2vulkan-runtime::WorkCounts.copy_sites pub copy_sites: [CopySite; 32]
field metal2vulkan-runtime::WorkCounts.cpu_block_decodes pub cpu_block_decodes: u64
@@ -2593,6 +2602,7 @@ field metal2vulkan-runtime::WorkCounts.host_imports_read_apart_texture pub host_
field metal2vulkan-runtime::WorkCounts.host_imports_read_apart_unreleased pub host_imports_read_apart_unreleased: u64
field metal2vulkan-runtime::WorkCounts.host_imports_read_apart_vk_buffer pub host_imports_read_apart_vk_buffer: u64
field metal2vulkan-runtime::WorkCounts.host_imports_rebound_unlisted pub host_imports_rebound_unlisted: u64
field metal2vulkan-runtime::WorkCounts.host_imports_refused_by_host pub host_imports_refused_by_host: u64
field metal2vulkan-runtime::WorkCounts.host_imports_reimported pub host_imports_reimported: u64
field metal2vulkan-runtime::WorkCounts.host_imports_released pub host_imports_released: u64
field metal2vulkan-runtime::WorkCounts.host_imports_remapped pub host_imports_remapped: u64
@@ -4870,6 +4880,7 @@ macro-member metal2vulkan-runtime::Degradation::CombinedArchiveStages CombinedAr
macro-member metal2vulkan-runtime::Degradation::CompressedTexelDecode CompressedTexelDecode = "compressed-texel-decode", Precision,
macro-member metal2vulkan-runtime::Degradation::ComputedSampleDepth ComputedSampleDepth = "computed-sample-depth";
macro-member metal2vulkan-runtime::Degradation::CopiedDrawBytes CopiedDrawBytes = "copied-draw-bytes", Performance,
macro-member metal2vulkan-runtime::Degradation::CopiedHostPages CopiedHostPages = "copied-host-pages", Precision,
macro-member metal2vulkan-runtime::Degradation::CoverageReadsRoundedAlpha CoverageReadsRoundedAlpha = "coverage-reads-rounded-alpha";
macro-member metal2vulkan-runtime::Degradation::CpuBlockDecode CpuBlockDecode = "cpu-block-decode", Performance,
macro-member metal2vulkan-runtime::Degradation::CrossClassTextureNeutral CrossClassTextureNeutral = "cross-class-texture-neutral", Precision,
@@ -7772,6 +7783,7 @@ method metal2vulkan-runtime::HostMemory::new pub unsafe fn new(pointer: NonNull<
method metal2vulkan-runtime::HostMemory::pointer pub fn pointer(&self) -> NonNull<u8>
method metal2vulkan-runtime::HostMemory::with_dirty_pages pub fn with_dirty_pages<D>(self, source: Arc<D>) -> HostMemory where D: DirtyPages + ?Sized + 'static, D::Watch: 'static,
method metal2vulkan-runtime::HostMemory::with_dma_buf #[cfg(unix)] pub unsafe fn with_dma_buf(pointer: NonNull<u8>, source: DmaBufSource) -> HostMemory
method metal2vulkan-runtime::HostMemory::with_import_gate pub fn with_import_gate(self, gate: ImportGate) -> HostMemory
method metal2vulkan-runtime::IndirectBufferBinding::new pub fn new(address: GpuAddress, attribute_stride: Option<u64>) -> IndirectBufferBinding
method metal2vulkan-runtime::IndirectCommandBuffer::allocated_size pub fn allocated_size(&self) -> u64
method metal2vulkan-runtime::IndirectCommandBuffer::as_resource pub fn as_resource(&self) -> ResourceRef<'_>
@@ -9236,6 +9248,7 @@ struct metal2vulkan-runtime::Heap #[derive(Clone)] pub struct Heap(Arc<HeapShare
struct metal2vulkan-runtime::HeapDescriptor #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct HeapDescriptor
struct metal2vulkan-runtime::HostBytes #[derive(Clone, Copy, Debug)] pub struct HostBytes<'a>
struct metal2vulkan-runtime::HostMemory pub struct HostMemory
struct metal2vulkan-runtime::ImportRequest #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct ImportRequest
struct metal2vulkan-runtime::IndirectBufferBinding #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct IndirectBufferBinding
struct metal2vulkan-runtime::IndirectCommandBuffer #[derive(Clone)] pub struct IndirectCommandBuffer(Arc<IcbShared>)
struct metal2vulkan-runtime::IndirectCommandBufferDescriptor #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct IndirectCommandBufferDescriptor
@@ -9743,6 +9756,8 @@ trait-impl metal2vulkan-runtime::HostBytes impl fe impl Sync unsafe impl Sync fo
trait-impl metal2vulkan-runtime::HostMemory impl fe impl Send unsafe impl Send for HostMemory
trait-impl metal2vulkan-runtime::HostMemory impl fe impl Sync unsafe impl Sync for HostMemory
trait-impl metal2vulkan-runtime::HostMemory impl std::fmt::Debug impl std::fmt::Debug for HostMemory
trait-impl metal2vulkan-runtime::ImportRequest impl fe impl Send unsafe impl Send for ImportRequest
trait-impl metal2vulkan-runtime::ImportRequest impl fe impl Sync unsafe impl Sync for ImportRequest
trait-impl metal2vulkan-runtime::IndirectCommandBuffer impl Eq impl Eq for IndirectCommandBuffer
trait-impl metal2vulkan-runtime::IndirectCommandBuffer impl PartialEq impl PartialEq for IndirectCommandBuffer
trait-impl metal2vulkan-runtime::IndirectCommandBuffer impl std::fmt::Debug impl std::fmt::Debug for IndirectCommandBuffer
@@ -9892,6 +9907,7 @@ type metal2vulkan-runtime::Deallocator pub type Deallocator = Box<dyn FnOnce(Non
type metal2vulkan-runtime::DmaBufSource pub type DmaBufSource = Arc<dyn Fn(DmaBufRequest) -> std::io::Result<Vec<DmaBufChunk>> + Send + Sync + 'static>
type metal2vulkan-runtime::ExecutedCommandsHandler pub type ExecutedCommandsHandler = Arc<dyn Fn(&ExecutedCommands) + Send + Sync + 'static>
type metal2vulkan-runtime::Handler pub type Handler = Box<dyn FnOnce(&CommandBuffer) + Send + 'static>
type metal2vulkan-runtime::ImportGate pub type ImportGate = Arc<dyn Fn(ImportRequest) -> bool + Send + Sync + 'static>
type metal2vulkan-runtime::IndirectCommandCheck pub type IndirectCommandCheck = Box<dyn FnMut(u64, &IndirectCommand) + Send + 'static>
type metal2vulkan-runtime::KeepAlive pub type KeepAlive = Box<dyn Send + 'static>
type metal2vulkan-runtime::RangeToken pub type RangeToken = Box<dyn std::any::Any + Send + Sync>
Can't render this file because it is too large.
+16
View File
@@ -2491,6 +2491,22 @@ bound.
writes. Cost: the GPU's writes through it reach the pages, and the CPU then reads them there,
where after Metal's GPU writes into pages the process maps read-only the CPU reads them as they
were (an M3 Max under macOS 27.0.1, private and shared memory alike).
- `metal2vulkan-degrade-copied-host-pages` (precision). `CopiedHostPages`: A no-copy buffer, a
no-copy heap or a buffer's rebind was made over a copy of the caller's host pages in memory of
the device's own, which no import maps (a heap's textures shadows of its bytes):
the caller's gate (`HostMemory::with_import_gate`) refused the pages' import, or the import the
device and the gate admitted failed (out of memory, or another Vulkan error, such as a driver out
of the mappings the host kernel allows). Pages the process cannot read are never copied: the
buffer is refused, as their import is. A copy whose own allocation fails refuses the call
(`OutOfMemory`). A heap's rebind and memory whose GPU writes Metal's private option bit 24 drops
are never copied. Counted: `WorkCounts::copied_host_buffers_made`, of them
`copied_host_buffers_refused` and `copied_host_buffers_degraded` (and `copied_heaps_made`,
`copied_rebind_pages_made`). Cost: the GPU uses a copy of
the bytes, into which each commit writes every byte the CPU changed in the pages since, and from
which each batch's completion writes back every byte the GPU changed, where Metal's GPU reads and
writes the pages themselves: a CPU write the GPU reads mid-command-buffer, or a GPU write the CPU
reads before the batch completes (behind a shared event's value among them), is not seen, and
each commit and completion compares every byte of every copy.
- `metal2vulkan-degrade-grouped-completion` (precision). `GroupedCompletion`: Batches of command
buffers committed on one queue that the scheduler found ready together, or held while two or more
earlier submissions of their queue ran, went to the driver in one `vkQueueSubmit`, only the last
+14
View File
@@ -317,6 +317,20 @@ recorded here.
Open differences from Metal that no note announces yet, and runtime costs still above the
driver's. Each is open work.
- **A copied host buffer costs O(its size) at every commit and every batch's completion**
(`copied.rs`, `copied-host-pages`): each compares every byte of every live copy with the bytes
the copy and the pages last agreed on, whichever buffers the work names, where a page log or the
work's uses could bound it. A copy is made only where the caller's gate refuses an import or an
admitted import fails, never by default.
- **A copied host buffer's merge keeps the CPU's byte where the CPU and the GPU both wrote it**
between a commit and the completion: bytes are merged one at a time, so a GPU write never
rewrites a byte beside it, but a byte both wrote keeps the CPU's, where on Metal the later write
wins. A heap's rebind is never copied, nor a buffer's rebind with an image in place over the
buffer: a refused or failed import of either still refuses the call.
- **A shared event's value can reach the CPU before a copied host buffer's merge**: the host reads
the event's semaphore, which the batch signals before its completion merges the GPU's writes
back, so a CPU that waits for the value may read the pages before them, where Metal's writes are
in the pages when the value is seen.
- **A shadowed texture over an IOSurface plane's bytes is copied in whole for every command
buffer that samples it**, where it is a shadow: one that only samples or reads is an image in
place where its class's check passed (`in_place.rs`), so this holds for a plane that renders or
+31
View File
@@ -311,6 +311,37 @@ records it (`WorkCounts::copy_regions_split`): among them a two-plane YCbCr text
into its staging buffer where it converts whole (`WorkCounts::ycbcr_whole_conversions`), and a
staged texture's bytes and rows.
### Copied host buffers
A no-copy buffer whose import the runtime does not make is made over a copy of its bytes instead,
announced (`copied-host-pages`): no import maps the pages, so they take no kernel mapping. That
happens where:
- the caller's gate refuses the import: `HostMemory::with_import_gate(gate)` asks the `ImportGate`
once, on the thread making the buffer, heap or rebind and holding no lock of the runtime's, just
before the import, with the pages it would map (`ImportRequest`, the host pages from the first
byte's through the last's). `false` makes the copy (`WorkCounts::host_imports_refused_by_host`,
`copied_host_buffers_refused`). A consumer with a budget of mappings (Linux's
`vm.max_map_count`) refuses there, paying in copies instead of a failed call. It is not asked
for a buffer or rebind that lies in a live import of the same bytes, a heap's rebind, memory
whose GPU writes Metal's private option bit 24 drops, or where the device refused the pointer
before it;
- an import the device and the gate admitted fails (out of memory, another Vulkan error:
`copied_host_buffers_degraded`).
The copy is host-visible memory of the device's own; the buffer's `contents` is still the pointer.
Each commit writes into the copy every byte the CPU changed in the pages since the copy and the
pages last agreed, and each batch's completion writes back every byte the GPU changed, before its
handlers run or a waiter returns, keeping a byte the CPU changed since (`copied_copy_in_bytes`,
`copied_merge_back_bytes`). Each compares every byte of every live copy, so keep copies few. A
texture over a copied buffer is a shadow of its bytes. Pages the process cannot read are never
copied: the buffer is refused, as their import is.
A no-copy heap's own buffer is copied the same way (`copied_heaps_made`): its buffers lie in the
copy, and its textures are shadows of its bytes. `Buffer::rebind_bytes_no_copy` gives the buffer a
copy of its new pages the same way (`copied_rebind_pages_made`), except over a buffer with a
texture in place over it, which the rebind refuses (`NotImplemented(RebindTextures)`).
## 7. Check the integration
`spirv-val` checks structural validity, not agreement with Metal:
+4 -4
View File
@@ -235,7 +235,7 @@ Columns:
| `LayeredPass` | A layered render pass (`renderTargetArrayLength` 2 or more) that needs a step of one layer | every device (runtime piece not built) | `ours` | 1: `crates/metal2vulkan-runtime/src/color_resolve.rs (plan)` | `rare`: layered passes needing a per-layer color resolve |
| `OverlappingTextureCopies` | A blit copy between overlapping regions of one texture's texels (`copyFromTexture:...` with the source's region meeting the destination's, through... (not scheduled) | every device (runtime piece not built) | `ours` | 1: `crates/metal2vulkan-runtime/src/blit_texture.rs (texture_copies_of_bytes)` | `rare`: overlapping texture copies (Metal races) |
| `EmptyFillPattern` | A texture fill given no pattern bytes (`fillTexture:level:slice:region:bytes:length:` of length 0,... | every device (runtime piece not built) | `ours` | 1: `crates/metal2vulkan-runtime/src/blit_fill.rs (check_pattern)` | `none`: a fill of no pattern bytes through the Apple-private fillTexture:...:bytes:length: |
| `RebindTextures` | `Buffer::rebind_bytes_no_copy` of a no-copy buffer with a live texture over its bytes, given memory at another offset in its page than the old | every device (runtime piece not built) | `ours` | 9: `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (rebind_host_pages)`, `crates/metal2vulkan-runtime/src/texture/heap.rs (dma_buf_heap_images_again)` (+3) | `none`: a runtime extension's rebind with a live texture |
| `RebindTextures` | `Buffer::rebind_bytes_no_copy` of a no-copy buffer with a live texture over its bytes, given memory at another offset in its page than the old | every device (runtime piece not built) | `ours` | 10: `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (rebind_host_pages, 2 sites)`, `crates/metal2vulkan-runtime/src/texture/heap.rs (dma_buf_heap_images_again)` (+3) | `none`: a runtime extension's rebind with a live texture |
| `PvrtcBlockOrder` | A PVRTC texture's blocks in a Metal block order the runtime does not lay out | every device (runtime piece not built) | `ours` | 1: `crates/metal2vulkan-runtime/src/texture.rs (host_copy)` | `rare`: PVRTC regions off whole levels |
| `DecodedHeapTexture` | A heap's or a sparse heap's texture of an ASTC format on a device without that ASTC format (`astc.rs`), or a sparse heap's texture of an ETC2 or... | every device (runtime piece not built) | `ours` | 4: `crates/metal2vulkan-runtime/src/texture.rs (plan_sparse_texture)`, `crates/metal2vulkan-runtime/src/texture/heap.rs (heap_plan)` (+1) | `app`: an ASTC texture in a heap on a device without ASTC |
| `VertexFetchPast4GiB` | A draw (`drawPrimitives:` and its forms, or an indirect command buffer's command) that may read a vertex attribute the pipeline fetches in its... | every device (runtime piece not built) | `ours` | 1: `crates/metal2vulkan-runtime/src/render/vertex_reach.rs (check_vertex_reach)` | `rare`: vertex fetch past 4 GiB of a bind offset |
@@ -336,7 +336,7 @@ Columns:
| `ImageblockSize` | An imageblock size of more than 1024 cells over more than one row and column, or with a side past 65536, at a compute encoder's... | every device (a public call's own check of its arguments) | `unknown`: plain Metal is held to run the compute form, and the indirect form rests on Metal's API validation; neither measured on a named device | 3: `crates/metal2vulkan-runtime/src/compute.rs (imageblock_size, 2 sites)`, `crates/metal2vulkan-runtime/src/compute.rs (validated_imageblock_size)` | `-` |
| `EmptyThreadgroup` | A tile dispatch's threadgroup with no threads along an axis (a compute dispatch of one runs nothing, as plain Metal's) | every device (a public call's own check of its arguments) | `unknown`: Metal's answer for a tile dispatch of no threads along an axis is unmeasured | 1: `crates/metal2vulkan-runtime/src/render/tile_dispatch.rs (dispatch_tiles_resident)` | `-` |
| `SizeOutOfRange` | A size past what the call can state | every device (a public call's own check of its arguments) | `unknown`: Metal's answer for a tile dispatch's or mesh draw's axis past 32 bits is unmeasured | 2: `crates/metal2vulkan-runtime/src/render/mesh.rs`, `crates/metal2vulkan-runtime/src/render/tile_dispatch.rs (dispatch_tiles_resident)` | `-` |
| `BufferLength` | A buffer of no bytes, or more than the device can hold in one | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max: newBufferWithLength:0 answers nil | 8: `crates/metal2vulkan-runtime/src/buffer.rs (buffer_of_length)`, `crates/metal2vulkan-runtime/src/buffer.rs (placed_new_buffer)` (+6) | `-` |
| `BufferLength` | A buffer of no bytes, or more than the device can hold in one | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max: newBufferWithLength:0 answers nil | 9: `crates/metal2vulkan-runtime/src/buffer.rs (buffer_of_length)`, `crates/metal2vulkan-runtime/src/buffer.rs (placed_new_buffer)` (+7) | `-` |
| `UndefinedValue` | A raw value Metal does not define for this type | every device (a public call's own check of its arguments) | `metal-takes`: an Apple M3 Max: setPurgeableState:99, a value MTLPurgeableState does not define, answers 2, and neither plain Metal nor its API validation refuses it | 7: `crates/metal2vulkan-runtime/src/attributes.rs (from_raw)`, `crates/metal2vulkan-runtime/src/degradation.rs (refuse_private_bit)` (+5) | `-` |
| `StorageMode` | A storage mode this call does not take (`Memoryless` for a buffer, for one) | every device (a public call's own check of its arguments) | `metal-measured`: an Apple M3 Max: a buffer of the Memoryless mode asserts "Invalid storageMode", the API validation layer off | 14: `crates/metal2vulkan-runtime/src/argument_encoder.rs (target)`, `crates/metal2vulkan-runtime/src/buffer.rs (buffer_class)` (+12) | `-` |
| `HandlerAfterCommit` | A handler added after the command buffer was committed | every device (a public call's own check of its arguments) | `metal-documented`: Metal asserts "Completed handler provided after commit call" | 4: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs (add_completed_handler)`, `crates/metal2vulkan-runtime/src/command_buffer/mod.rs (add_scheduled_handler)` (+2) | `-` |
@@ -731,7 +731,7 @@ Each refusal's sites, with the function that builds it.
- `gap::LayeredPass`: `crates/metal2vulkan-runtime/src/color_resolve.rs (plan)`
- `gap::OverlappingTextureCopies`: `crates/metal2vulkan-runtime/src/blit_texture.rs (texture_copies_of_bytes)`
- `gap::EmptyFillPattern`: `crates/metal2vulkan-runtime/src/blit_fill.rs (check_pattern)`
- `gap::RebindTextures`: `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (rebind_host_pages)`; `crates/metal2vulkan-runtime/src/texture/heap.rs (dma_buf_heap_images_again)`; `crates/metal2vulkan-runtime/src/texture/heap.rs (rebound_heap_images, 3 sites)`; `crates/metal2vulkan-runtime/src/texture/in_place_image.rs (dma_buf_in_place_again)`; `crates/metal2vulkan-runtime/src/texture/in_place_image.rs (rebound_in_place_images, 3 sites)`
- `gap::RebindTextures`: `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (rebind_host_pages, 2 sites)`; `crates/metal2vulkan-runtime/src/texture/heap.rs (dma_buf_heap_images_again)`; `crates/metal2vulkan-runtime/src/texture/heap.rs (rebound_heap_images, 3 sites)`; `crates/metal2vulkan-runtime/src/texture/in_place_image.rs (dma_buf_in_place_again)`; `crates/metal2vulkan-runtime/src/texture/in_place_image.rs (rebound_in_place_images, 3 sites)`
- `gap::PvrtcBlockOrder`: `crates/metal2vulkan-runtime/src/texture.rs (host_copy)`
- `gap::DecodedHeapTexture`: `crates/metal2vulkan-runtime/src/texture.rs (plan_sparse_texture)`; `crates/metal2vulkan-runtime/src/texture/heap.rs (heap_plan)`; `crates/metal2vulkan-runtime/src/texture/heap.rs (heap_texture_size_and_align, 2 sites)`
- `gap::VertexFetchPast4GiB`: `crates/metal2vulkan-runtime/src/render/vertex_reach.rs (check_vertex_reach)`
@@ -802,7 +802,7 @@ Each refusal's sites, with the function that builds it.
- `invalid::ImageblockSize`: `crates/metal2vulkan-runtime/src/compute.rs (imageblock_size, 2 sites)`; `crates/metal2vulkan-runtime/src/compute.rs (validated_imageblock_size)`
- `invalid::EmptyThreadgroup`: `crates/metal2vulkan-runtime/src/render/tile_dispatch.rs (dispatch_tiles_resident)`
- `invalid::SizeOutOfRange`: `crates/metal2vulkan-runtime/src/render/mesh.rs`; `crates/metal2vulkan-runtime/src/render/tile_dispatch.rs (dispatch_tiles_resident)`
- `invalid::BufferLength`: `crates/metal2vulkan-runtime/src/buffer.rs (buffer_of_length)`; `crates/metal2vulkan-runtime/src/buffer.rs (placed_new_buffer)`; `crates/metal2vulkan-runtime/src/buffer.rs (unzeroed_buffer_with)`; `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (buffer_over_host_memory)`; `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (host_window)`; `crates/metal2vulkan-runtime/src/heap.rs (check_length)`; `crates/metal2vulkan-runtime/src/heap.rs (new_buffer)`; `crates/metal2vulkan-runtime/src/wrapped_buffer.rs (new_buffer_with_vk_buffer)`
- `invalid::BufferLength`: `crates/metal2vulkan-runtime/src/buffer.rs (buffer_of_length)`; `crates/metal2vulkan-runtime/src/buffer.rs (placed_new_buffer)`; `crates/metal2vulkan-runtime/src/buffer.rs (unzeroed_buffer_with)`; `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (buffer_over_host_memory)`; `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (copied_buffer)`; `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (host_window)`; `crates/metal2vulkan-runtime/src/heap.rs (check_length)`; `crates/metal2vulkan-runtime/src/heap.rs (new_buffer)`; `crates/metal2vulkan-runtime/src/wrapped_buffer.rs (new_buffer_with_vk_buffer)`
- `invalid::UndefinedValue`: `crates/metal2vulkan-runtime/src/attributes.rs (from_raw)`; `crates/metal2vulkan-runtime/src/degradation.rs (refuse_private_bit)`; `crates/metal2vulkan-runtime/src/heap.rs (from_raw)`; `crates/metal2vulkan-runtime/src/render_values.rs (undefined)`; `crates/metal2vulkan-runtime/src/sparse/mod.rs (undefined)`; `crates/metal2vulkan-runtime/src/values.rs (undefined)`; `crates/metal2vulkan-runtime/src/visibility.rs (from_raw)`
- `invalid::StorageMode`: `crates/metal2vulkan-runtime/src/argument_encoder.rs (target)`; `crates/metal2vulkan-runtime/src/buffer.rs (buffer_class)`; `crates/metal2vulkan-runtime/src/buffer_descriptor.rs (buffer_over_host_memory)`; `crates/metal2vulkan-runtime/src/heap.rs (heap_with_token)`; `crates/metal2vulkan-runtime/src/heap.rs (new_sparse_heap)`; `crates/metal2vulkan-runtime/src/heap.rs (no_copy_heap_with_token)`; `crates/metal2vulkan-runtime/src/indirect_command_buffer.rs (new_indirect_command_buffer)`; `crates/metal2vulkan-runtime/src/rate_map.rs (copy_parameter_data_to_buffer)`; `crates/metal2vulkan-runtime/src/texture.rs (check_viewable)`; `crates/metal2vulkan-runtime/src/texture.rs (host_copy)`; `crates/metal2vulkan-runtime/src/texture/heap.rs (heap_layout)`; `crates/metal2vulkan-runtime/src/texture/shared.rs (new_shared_texture)`; `crates/metal2vulkan-runtime/src/texture/wrapped.rs (new_texture_with_vk_image)`; `crates/metal2vulkan-runtime/src/wrapped_buffer.rs (new_buffer_with_vk_buffer)`
- `invalid::HandlerAfterCommit`: `crates/metal2vulkan-runtime/src/command_buffer/mod.rs (add_completed_handler)`; `crates/metal2vulkan-runtime/src/command_buffer/mod.rs (add_scheduled_handler)`; `crates/metal2vulkan-runtime/src/command_buffer/mod.rs (add_submission_handler)`; `crates/metal2vulkan-runtime/src/executed_commands.rs (add_executed_commands_handler)`