No-copy buffers keep what their pages were made of, and a making names who it makes

No change in behaviour; the plumbing a no-copy buffer's carry rests on.

- HostParts is clonable. A no-copy buffer's pages (not a heap's own) keep the
  parts of the caller's memory they were made of (HostPages::made_of), at
  making and at each rebind: what a recovery makes the buffer again of on the
  next generation.
- buffer_over_host_memory resolves its release and hands over to
  buffer_over_host_parts, which a carry calls with the parts kept.
- Naming says who a making makes: a new buffer, or a buffer a recovery carries,
  whose ObjectId, identity and attributes it keeps. It goes through
  BufferParts, buffer_in_import, copied_buffer and buffer_lying. Every other
  making names a new buffer.

Verification: none yet. Builds and tests come with the carry that uses it.
(cherry picked from commit 0417e783cc14a6bed17a54fac07df00075a48862)
This commit is contained in:
Anees Iqbal committed 2026-11-09 06:01:13 -08:00
1 parent 4ed1565b3a
commit e35a85e725
5 files changed
+159 -26

No files matched your search

+62 -8
View File
@@ -34,7 +34,7 @@ use super::fresh_pages;
use super::generated_commands::PREPROCESS_BUFFER;
use super::heap::{Heap, HeapType};
use super::host_aliases::Alias;
use super::host_memory::{HeldBack, KeepAlive, Release};
use super::host_memory::{HeldBack, HostParts, KeepAlive, Release};
use super::host_ram::RamOnDevice;
#[cfg(unix)]
use super::host_residency::{Again, Residency};
@@ -901,6 +901,9 @@ pub(super) struct HostPages {
/// The key they named to their copy, where they lie in one ([`HostPages::copied_as`]): its
/// naming goes as they go.
named: OnceLock<ResourceKey>,
/// The caller's memory they were made of, a buffer's (not a heap's own): what its device's
/// recovery makes the buffer again of on the next generation (`Buffer::carry`).
made_of: OnceLock<HostParts>,
}
impl HostPages {
@@ -918,6 +921,7 @@ impl HostPages {
dirty: OnceLock::new(),
ram_runs: OnceLock::new(),
named: OnceLock::new(),
made_of: OnceLock::new(),
}
}
@@ -966,6 +970,17 @@ impl HostPages {
}
}
/// Keep `parts`, the caller's memory they were made of ([`HostPages::made_of`]).
pub(super) fn keep_made_of(&self, parts: HostParts) {
let _kept = self.made_of.set(parts);
}
/// The caller's memory they were made of, a buffer's (not a heap's own), which its device's
/// recovery makes the buffer again of on the next generation (`Buffer::carry`).
pub(super) fn made_of(&self) -> Option<&HostParts> {
self.made_of.get()
}
/// Keep the guest RAM and the runs of it their caller resolved them to (`host_ram.rs`).
pub(super) fn keep_runs(&self, runs: (Arc<RamOnDevice>, Box<[Range<u64>]>)) {
let _kept = self.ram_runs.set(runs);
@@ -2173,6 +2188,32 @@ pub(super) struct BufferParts {
/// while idle (`host_residency.rs`).
#[cfg(unix)]
pub(super) again: Option<Again>,
/// A new buffer, or the same buffer on its device's next generation.
pub(super) naming: Naming,
}
/// Who a buffer being made is ([`Device::buffer_of`], `Device::buffer_over_host_parts`): a new
/// buffer, with an identity and an `ObjectId` of its own, or a buffer its device's recovery
/// carries (`Buffer::carry`), the same buffer on the next generation, its identity, `ObjectId`
/// and attributes the buffer's.
pub(super) enum Naming {
New,
Carried {
object_id: ObjectId,
identity: Identity,
attributes: ResourceAttributes,
},
}
impl Naming {
/// The buffer's identity: a new one of `hazard` (a heap's own where `of_heap`), or the
/// carried buffer's.
fn identity(&self, hazard: HazardTrackingMode, of_heap: bool) -> Identity {
match self {
Naming::New => Identity::new(hazard, of_heap),
Naming::Carried { identity, .. } => *identity,
}
}
}
impl std::fmt::Debug for Buffer {
@@ -2763,6 +2804,7 @@ impl Device {
mirror,
#[cfg(unix)]
again: None,
naming: Naming::New,
});
Ok((buffer, bytes))
}
@@ -2909,6 +2951,7 @@ impl Device {
mirror: None,
#[cfg(unix)]
again: None,
naming: Naming::New,
}))
}
@@ -2931,9 +2974,10 @@ impl Device {
mirror,
#[cfg(unix)]
again,
naming,
} = parts;
let pages = self.pages_of(raw, memory, offset, base, reach);
let identity = Identity::new(modes.hazard, of_heap);
let identity = naming.identity(modes.hazard, of_heap);
let lie = match owner {
// A no-copy buffer's pages are its until a rebind (`rebind.rs`).
Owner::Caller => {
@@ -2966,7 +3010,7 @@ impl Device {
mirror,
range_token: KeptToken::default(),
};
self.buffer_lying(own, length, modes, address)
self.buffer_lying(own, length, modes, address, naming)
}
/// The import of a no-copy buffer's `pages`: one the device releases while idle where
@@ -3006,8 +3050,9 @@ impl Device {
modes: Modes,
(address, reserved): (GpuAddress, Held),
release: Option<Release>,
naming: Naming,
) -> Buffer {
let identity = Identity::new(modes.hazard, false);
let identity = naming.identity(modes.hazard, false);
let own = OwnBytes {
lie: self.host_lie(identity.key, import, release, false),
reserved,
@@ -3016,7 +3061,7 @@ impl Device {
mirror: None,
range_token: KeptToken::default(),
};
self.buffer_lying(own, length, modes, address)
self.buffer_lying(own, length, modes, address, naming)
}
/// A no-copy buffer's lie, of `key`: pages of its own in `import`, released to `release`
@@ -3048,23 +3093,32 @@ impl Device {
Lie::Host(cell)
}
/// The buffer of `own`'s bytes, `length` long, of `modes`, at `address`.
/// The buffer of `own`'s bytes, `length` long, of `modes`, at `address`, named by `naming`.
fn buffer_lying(
&self,
own: OwnBytes,
length: u64,
modes: Modes,
address: GpuAddress,
naming: Naming,
) -> Buffer {
let options = ResourceOptions::new(modes.storage, modes.cache, own.identity.mode());
let (object_id, attributes) = match naming {
Naming::New => (ObjectId::new(), ResourceAttributes::new()),
Naming::Carried {
object_id,
attributes,
..
} => (object_id, attributes),
};
Buffer(Arc::new(BufferShared {
device: MadeOn::new(self.clone()),
generation: std::ptr::from_ref(self.shared()).addr(),
object_id: ObjectId::new(),
object_id,
length,
options,
address,
attributes: ResourceAttributes::new(),
attributes,
bytes: Bytes::Own(own),
held_by: HeldBy::default(),
handed_out: Arc::default(),
@@ -13,7 +13,7 @@ use super::address_pool::AddressPool;
#[cfg(unix)]
use super::buffer::Pages;
use super::buffer::{
usage, Buffer, BufferParts, HostCell, HostPages, Lying, Modes, Owner, ReadApart,
usage, Buffer, BufferParts, HostCell, HostPages, Lying, Modes, Naming, Owner, ReadApart,
};
use super::copied::NotCopied;
use super::degradation::Degradation;
@@ -27,7 +27,7 @@ use super::host_bytes::HostBytes;
use super::host_memory::{
based_size, binds_in, buffer_base, import_refused, import_window, not_importable,
refuse_unwritable, refused, unpinnable, Deallocator, HostMemory, HostParts, HostRelease,
ImportRequest, ImportWindow, Importer, KeepAlive, Source,
ImportRequest, ImportWindow, Importer, KeepAlive, Release, Source,
};
use super::host_ram::{RamOnDevice, Routed};
#[cfg(unix)]
@@ -680,6 +680,57 @@ impl Device {
placement: Place,
of_heap: bool,
drops_writes: bool,
) -> Result<Buffer, Error> {
let parts = memory.into_parts();
let release = release.of(parts.pointer, length);
let made = (call, length, options, placement);
// SAFETY: the caller's contract.
unsafe {
self.buffer_over_host_parts(made, parts, release, of_heap, drops_writes, Naming::New)
}
}
/// [`Device::buffer_over_host_memory`] of the caller's memory's `parts`, `made` (for its call,
/// of its length and options, at its placement) as the buffer `naming` names, given back to
/// `release`: a new buffer, or one its device's recovery carries to this generation
/// (`Buffer::carry`). A buffer's pages (not a heap's own) keep what they were made of, which
/// a recovery makes the buffer again of ([`HostPages::made_of`]).
///
/// # Safety
///
/// The memory of `parts` meets [`HostMemory::new`]'s contract for `length` bytes.
pub(super) unsafe fn buffer_over_host_parts(
&self,
made: (&'static str, u64, ResourceOptions, Place),
parts: HostParts,
release: Option<Release>,
of_heap: bool,
drops_writes: bool,
naming: Naming,
) -> Result<Buffer, Error> {
let made_of = (!of_heap).then(|| parts.clone());
// SAFETY: the caller's contract.
let buffer =
unsafe { self.host_parts_buffer(made, parts, release, of_heap, drops_writes, naming) }?;
if let (Some(made_of), Some(pages)) = (made_of, buffer.host_pages()) {
pages.keep_made_of(made_of);
}
Ok(buffer)
}
/// [`Device::buffer_over_host_parts`]'s buffer.
///
/// # Safety
///
/// As there.
unsafe fn host_parts_buffer(
&self,
(call, length, options, placement): (&'static str, u64, ResourceOptions, Place),
parts: HostParts,
release: Option<Release>,
of_heap: bool,
drops_writes: bool,
naming: Naming,
) -> Result<Buffer, Error> {
let modes = Modes::of(options)?;
let class = match modes.storage {
@@ -708,7 +759,7 @@ impl Device {
gate,
runs,
dma_buf_only,
} = memory.into_parts();
} = parts;
let source = (source, dma_buf_only);
let host = host_window(call, importer, pointer, length, source, drops_writes)?;
let window = host.window;
@@ -725,7 +776,6 @@ impl Device {
// does one whose GPU writes are dropped (its import is a read-only view of the pages, or
// its copy drops them).
let made_over = (pointer.as_ptr() as u64, length);
let release = release.of(pointer, length);
let shares = (!of_heap && !drops_writes)
.then(|| shared.aliases.import(made_over, class))
.flatten();
@@ -739,7 +789,7 @@ impl Device {
false => Kind::Import(class),
};
let buffer =
self.buffer_in_import(Arc::clone(&import), length, modes, address, release);
self.buffer_in_import(Arc::clone(&import), length, modes, address, release, naming);
let key = buffer.identity().key;
// The GPU's writes through it are reported to the import's logs, as through the
// buffer it was made for, over the same bytes (`dirty_pages.rs`), and merged back
@@ -823,8 +873,9 @@ impl Device {
// buffer over the bytes, nor does one lie in it.
if drops_writes && !crate::read_only_view::VIEWS_DROP_WRITES {
// SAFETY: the caller's contract.
let copied =
unsafe { self.copied_buffer(copy, release, dirty, CopiedFor::ReadOnly) };
let copied = unsafe {
self.copied_buffer(copy, release, dirty, CopiedFor::ReadOnly, naming)
};
return copied.map(|buffer| {
let buffer = kept(buffer, log, kept_runs);
shared.aliases.place(buffer.identity().key, made_over);
@@ -843,8 +894,9 @@ impl Device {
if refused_by_host {
shared.counts.host_import_refused_by_host();
// SAFETY: the caller's contract.
let copied =
unsafe { self.copied_buffer(copy, release, dirty, CopiedFor::Refused) };
let copied = unsafe {
self.copied_buffer(copy, release, dirty, CopiedFor::Refused, naming)
};
return copied.map(|buffer| noted(kept(buffer, log, kept_runs)));
}
// Only a buffer that imports its pages pins them, and so has their writability
@@ -854,8 +906,9 @@ impl Device {
// Metal drops them, their source never called ([`unwritable_pages`]).
if unwritable_pages(&host, writable, &shared.counts)? {
// SAFETY: the caller's contract.
let copied =
unsafe { self.copied_buffer(copy, release, dirty, CopiedFor::Unwritable) };
let copied = unsafe {
self.copied_buffer(copy, release, dirty, CopiedFor::Unwritable, naming)
};
return copied.map(|buffer| noted(kept(buffer, log, kept_runs)));
}
// SAFETY: the window lies in the pages of the caller's bytes, which stay mapped
@@ -911,7 +964,13 @@ impl Device {
Err((error, _)) if copyable && copies_after(&error) => {
// SAFETY: the caller's contract.
let copied = unsafe {
self.copied_buffer(copy, release, dirty, CopiedFor::Failed(error))
self.copied_buffer(
copy,
release,
dirty,
CopiedFor::Failed(error),
naming,
)
};
return copied.map(|buffer| noted(kept(buffer, log, kept_runs)));
}
@@ -922,7 +981,8 @@ impl Device {
Err((_, true)) if copyable => {
let why = CopiedFor::DeviceRefused;
// SAFETY: the caller's contract.
let copied = unsafe { self.copied_buffer(copy, release, dirty, why) };
let copied =
unsafe { self.copied_buffer(copy, release, dirty, why, naming) };
return copied.map(|buffer| noted(kept(buffer, log, kept_runs)));
}
Err((error, _)) => return Err(error),
@@ -954,6 +1014,7 @@ impl Device {
mirror: None,
#[cfg(unix)]
again,
naming,
});
// A buffer just made lies in its pages (`HostCell::current`), looked at once (their lock,
// `WorkCounts::no_copy_lies_read`) for everything below.
@@ -1026,6 +1087,9 @@ impl Device {
.host_import
.as_ref()
.map_err(|unsupported| Error::Unsupported(unsupported.clone()))?;
let parts = memory.into_parts();
// What a recovery makes a buffer's new pages again of (`HostPages::made_of`).
let made_of = heap.is_none().then(|| parts.clone());
let HostParts {
pointer,
source,
@@ -1034,7 +1098,7 @@ impl Device {
gate,
runs,
dma_buf_only,
} = memory.into_parts();
} = parts;
// A buffer whose GPU writes are dropped keeps them dropped over its new pages.
let drops_writes = cell.drops_writes();
let source = (source, dma_buf_only);
@@ -1383,6 +1447,9 @@ impl Device {
if let Some(release) = release.of(pointer, length) {
pages.release_to(release);
}
if let Some(made_of) = made_of {
pages.keep_made_of(made_of);
}
// What lay in the old pages goes with them: the images swapped out, and the texel views.
// A detached buffer lay in none: what took its stand-in goes with the new pages.
let keeper = match &old {
@@ -1904,9 +1971,10 @@ impl Device {
Place,
bool,
),
release: Option<super::host_memory::Release>,
release: Option<Release>,
dirty: Option<Arc<super::dirty_pages::DirtySource>>,
why: CopiedFor,
naming: Naming,
) -> Result<Buffer, Error> {
let read_only = matches!(why, CopiedFor::ReadOnly);
let (cause, failed) = match why {
@@ -2003,6 +2071,7 @@ impl Device {
mirror: None,
#[cfg(unix)]
again: None,
naming,
});
let drops = copied.drops_writes();
if let Some(pages) = buffer.host_pages() {
@@ -83,7 +83,7 @@
use super::address::Place;
use super::buffer::LINEAR_IMAGE_ALIGNMENT;
use super::buffer::{buffer_class, placed, usage, BufferParts, Modes, Owner};
use super::buffer::{buffer_class, placed, usage, BufferParts, Modes, Naming, Owner};
use super::device::lock;
use super::error::{invalid, nil, vulkan, Error, Problem};
use super::memory::{allocate_exported, Exported, DMA_BUF_HANDLE, EXPORT_HANDLE};
@@ -370,6 +370,7 @@ impl Device {
drops_writes: false,
mirror: None,
again: None,
naming: Naming::New,
});
// New memory holds no value until written: zero, as Metal's new buffer reads. Dropping
// `buffer` on failure releases it.
@@ -489,7 +489,9 @@ impl HostMemory {
}
}
/// A [`HostMemory`]'s parts ([`HostMemory::into_parts`]).
/// A [`HostMemory`]'s parts ([`HostMemory::into_parts`]): cloned, what a no-copy buffer's pages
/// were made of, which its device's recovery makes it again of (`HostPages::made_of`).
#[derive(Clone)]
pub(super) struct HostParts {
pub(super) pointer: NonNull<u8>,
pub(super) source: Option<Source>,
@@ -500,6 +502,12 @@ pub(super) struct HostParts {
pub(super) dma_buf_only: bool,
}
// SAFETY: as `HostMemory`'s: an address and the caller's guarantee for it, and parts that are
// `Send` and `Sync`.
unsafe impl Send for HostParts {}
// SAFETY: as above.
unsafe impl Sync for HostParts {}
/// A no-copy buffer's deallocator (Metal's block): called once, with the pointer and the length,
/// when the buffer is released. It may run on a runtime thread, as Metal's runs on any thread: a
/// command buffer's queue's handler thread, where that command buffer's release lets go of the
@@ -29,7 +29,7 @@
//! the memory against the runtime's work through semaphores or completion.
use super::address::AddressPlacement;
use super::buffer::{usage, Buffer, BufferParts, Modes, Owner};
use super::buffer::{usage, Buffer, BufferParts, Modes, Naming, Owner};
use super::device::lock;
use super::error::{invalid, nil, Error, Problem};
use super::memory::Placement;
@@ -323,6 +323,7 @@ impl Device {
mirror: None,
#[cfg(unix)]
again: None,
naming: Naming::New,
});
Ok(self.visible(buffer))
}